Metadata-Version: 2.4
Name: ffplatform
Version: 0.2.0
Summary: FF Platform SDK - Zero-dependency provisioning toolkit for FastFlowTech products
License-Expression: MIT
Requires-Python: >=3.10
Provides-Extra: build
Requires-Dist: build==1.2.2.post1; extra == 'build'
Requires-Dist: twine==6.1.0; extra == 'build'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.100.0; extra == 'fastapi'
Provides-Extra: test
Requires-Dist: fastapi==0.115.12; extra == 'test'
Requires-Dist: httpx==0.28.1; extra == 'test'
Description-Content-Type: text/markdown

# ffplatform - Python Platform SDK

Zero-dependency Platform SDK for FastFlowTech products. Provides standard provisioning, activation, cancellation, deletion, admin, and health endpoints.

## Install

```bash
pip install ffplatform --extra-index-url http://srv-119-gitea.lab:3000/api/packages/fastflowtech/pypi/simple --trusted-host srv-119-gitea.lab
```

For FastAPI support:

```bash
pip install ffplatform[fastapi] --extra-index-url http://srv-119-gitea.lab:3000/api/packages/fastflowtech/pypi/simple --trusted-host srv-119-gitea.lab
```

## Quick Start

### 1. Implement a TenantStore

Products implement one interface with three methods:

```python
from ffplatform.types import (
    ProvisionRequest, ProvisionResult,
    ActivateRequest, ActivateResult,
    DatabaseInfo,
)

class MyTenantStore:
    def provision(self, context: ProvisionRequest) -> ProvisionResult:
        # Product-specific: create tenant DB, seed data, etc.
        create_tenant(context.org_slug, context.stripe_customer_id)
        return ProvisionResult(success=True, status_code=201)

    def activate(self, context: ActivateRequest) -> ActivateResult:
        # Product-specific: mark tenant as active
        activate_tenant(context.org_slug)
        return ActivateResult(success=True)

    def list_databases(self) -> list[DatabaseInfo]:
        # Product-specific: list tenant databases for admin
        return [DatabaseInfo(org_slug="acme", status="active", ...)]
```

Async stores are also supported - just use `async def` methods.

### 2. Wire It Up

**stdlib (http.server):**

```python
from ffplatform.handlers import PlatformHandlers
from ffplatform.types import PlatformOptions
from ffplatform.adapters.stdlib import handle_platform_route

handlers = PlatformHandlers(
    store=MyTenantStore(),
    options=PlatformOptions(
        provision_api_key=os.environ.get("PROVISION_API_KEY", ""),
        product_name="my-product",
        version="1.0.0",
        environment=os.environ.get("ENVIRONMENT", "staging"),
    ),
)

# In your request handler:
result = handle_platform_route(path, method, headers, body, handlers)
if result is not None:
    status, data = result
    send_json_response(status, data)
    return
# ... handle other routes
```

**FastAPI:**

```python
from ffplatform.adapters.fastapi import register_platform_routes
from ffplatform.types import PlatformOptions

register_platform_routes(
    app=app,
    store=MyTenantStore(),
    options=PlatformOptions(
        provision_api_key=os.environ.get("PROVISION_API_KEY", ""),
        product_name="my-product",
        version="1.0.0",
    ),
    analytics_tracker=lambda event, props: track(event, props),
)
```

## Endpoints Provided

| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | `/v1/tenants/provision` | X-Api-Key | Create tenant |
| POST | `/v1/tenants/activate` | X-Api-Key | Activate tenant |
| POST | `/v1/tenants/deactivate` | X-Api-Key | Cancel tenant access through an optional store method |
| DELETE | `/v1/tenants/{orgSlug}` | X-Api-Key | Delete tenant data through an optional store method |
| GET | `/v1/admin/databases` | X-Api-Key | List tenant databases |
| GET | `/health` | None | Health check with SDK versions |

## Health Response Shape

```json
{
  "status": "ok",
  "timestamp": "2026-03-08T10:30:00Z",
  "product": "my-product",
  "version": "1.0.0",
  "environment": "staging",
  "sdks": [
    {"name": "platform", "version": "0.2.0"}
  ]
}
```

Register additional SDKs: `handlers.register_sdk("analytics", "0.2.0")`

## Analytics

Pass an optional `analytics_tracker` callable. The SDK calls it after successful provision/activate:

```python
# Tracked events: "platform.provision", "platform.activate"
analytics_tracker=lambda event, props: send_event(event, properties=props)
```

## Dockerfile

```dockerfile
RUN pip install --no-cache-dir -r requirements.txt \
    --extra-index-url http://srv-119-gitea.lab:3000/api/packages/fastflowtech/pypi/simple \
    --trusted-host srv-119-gitea.lab
```

## Dependencies

- **Core**: Zero dependencies (uses `urllib.request`, `threading`, `json` from stdlib)
- **FastAPI adapter**: Requires `fastapi >= 0.100.0` (optional extra)

## Cancellation and deletion (0.2.0)

Existing stores still require only the three original methods. Add either or both
optional capabilities when the service owns access or data for a workspace:

```python
from ffplatform import DeactivateRequest, DeactivateResult, DeleteTenantRequest, DeleteTenantResult

class MyTenantStore:
    # Keep provision, activate and list_databases as above.
    def deactivate(self, request: DeactivateRequest) -> DeactivateResult:
        suspend_access(request.org_slug)
        return DeactivateResult(success=True)

    def delete_tenant(self, request: DeleteTenantRequest) -> DeleteTenantResult:
        removed = remove_workspace_data(request.org_slug)
        return DeleteTenantResult(success=True, data={
            "orgSlug": request.org_slug,
            "status": "deleted" if removed else "already-deleted",
            "databaseRemoved": removed,
        })
```

Use `async def` for asynchronous stores. The async stdlib entry point is
`handle_platform_route_async`; FastAPI awaits lifecycle methods when needed.
The synchronous stdlib entry point requires synchronous methods. The optional
`DeactivatingTenantStore`, `DeletingTenantStore` and their `Async` variants are
separate protocols so adding them does not invalidate an existing `TenantStore`.

Send `POST /v1/tenants/deactivate` with `{"orgSlug":"acme"}`; the request object
also carries the original bytes in `raw_body`. Send `DELETE /v1/tenants/acme`
without a body. Both require the configured `X-Api-Key`. A missing or incorrect
key returns 401 before any store method runs; malformed JSON or an invalid slug
returns 400. Slugs must be nonblank, unpadded strings without path separators,
control characters, `?` or `#`. The reserved lifecycle paths provision, activate
and deactivate accept POST, not DELETE. Unmatched nested paths are not tenant
routes.

A missing `deactivate` method returns 200 with `status: cancelled-noop`: no
access was revoked by the SDK. A missing `delete_tenant` returns 501 with
`status: delete-not-implemented`: tenant data remains and the caller must treat
this as a refusal. The SDK never deletes a consumer's files or rows itself.
A service with no tenant state must implement deletion and explicitly say so.

Implemented methods control their response status and data. `status_code=None`
uses 200 on success or 500 on failure; a successful `data=None` uses the default
`cancelled` or `deleted` status with the slug. Empty objects, lists, strings,
false and zero are preserved. Exceptions return 500 without exposing exception
text. Successful implemented methods emit `platform.deactivate` or
`platform.delete_tenant` through the existing tracker; missing methods and
failures do not emit success events.

## Runtime visibility

`GET /health` reports `runtime: python` and a `platform` SDK version equal to the
installed package version. Reseller's SDK Readiness Matrix can identify a
configured Python product from these fields. Missing runtime information is
unknown, not proof that a service uses a different language. This package does
not add inventory collection or telemetry.

## Verification and publishing

The Python SDK workflows run the suite on Python 3.10 and 3.12 in CI containers.
The core remains dependency-free; FastAPI and build/test tools are extras.
Within the test container, from this directory:

```sh
python -m pip install '.[test,build]'
python -m unittest discover -s tests -v
python -m build
python -m twine check dist/*
```

SDK-only master pushes run package verification without pinning a Reseller
image. The separate publish workflow accepts `python-sdk-v<version>` tags on
master, verifies that the tag matches both version declarations, reruns tests,
publishes wheel and sdist to Gitea PyPI, and installs the published wheel into a
clean environment for another verification. Use a new version for a correction;
never overwrite a published version. No service deployment is part of publication.
