---
title: "Control plane (TypeScript / Node)"
description: "The TypeScript control plane: modules, data model, APIs, jobs and reconciliation."
---

![Control plane](/blume-assets/content/docs/architecture/diagrams/04-control-plane.png)

The control plane (CP) is the only component that knows about *all* tenants. It
owns the tenant registry, runs provisioning, signs LiveKit tokens, and routes
LiveKit events. It was a Go design in the discussions; the decision is now
**TypeScript on Node**, which also matches the Pulumi Automation API
(TypeScript is a first-class language there) and the operator cockpit (the tenant console is a separate frontend, ADR-031 in [11](/architecture/decisions-open-questions)).

## Stack

| Concern | Choice | Notes |
|---|---|---|
| Runtime | **Node 26 LTS**, TypeScript strict, pnpm workspaces | One repo, two entrypoints: `api` and `worker` (two images from one Dockerfile: the worker alone will carry the Pulumi CLI); cockpit and tenant console are separate apps |
| HTTP | **Fastify 5** + `fastify-type-provider-zod` (zod 4) → OpenAPI | Schemas shared with the frontends; `fastify-raw-body` for the LiveKit webhook |
| Cockpit (operators) | **TanStack Start** (React) | Authorization inside every server function/route — never only `beforeLoad`. **Calls the CP API with the operator's access token; no DB or Infisical credentials** (ADR-017). Login: `openid-client` (code + PKCE), session in an encrypted cookie (iron-session) |
| DB access | **Drizzle ORM** on `pg` | Schema in TS; SQL migrations generated by `drizzle-kit generate`, committed in `packages/db/migrations/`, applied by Drizzle's migrator (ADR-016) |
| Queue | **pg-boss 12** (core Postgres) | No extra infra; policy `stately` + `singletonKey` = tenant id for per-tenant serialization; jobs are sent inside the caller's Drizzle transaction; see [Job queue](#job-queue-pg-boss) |
| IaC | Pulumi **Automation API** (`@pulumi/pulumi/automation`) | Drives the Pulumi CLI at runtime; state in the Postgres DIY backend (`pulumi_state` on core Postgres, ADR-022), secrets encrypted with a passphrase held in Infisical (ADR-021). **In this phase Pulumi owns the Coolify stack of a tenant only**; the rest of the saga still calls ports directly (see [Provisioner](#provisioner)) |
| Auth | `jose` + Zitadel JWKS | Verify issuer, audience, org id, role on every request |
| LiveKit | `livekit-server-sdk` | `AccessToken` + `VideoGrant`, `WebhookReceiver` |
| Secrets | Infisical SDK | Machine identity for the CP; short-lived reads |
| S3 | `@aws-sdk/client-s3` | Bucket, lifecycle, presign; RustFS admin API for keys |
| Observability | pino logs, OpenTelemetry traces, Prometheus metrics (OTel Prometheus exporter, no separate prom-client) | `tenant_id` label on every signal; trace ids injected into logs |
| Tooling | Biome (lint/format), Vitest, Testcontainers, tsup (bundles `api`/`worker`) | Internal packages are source packages; apps are bundled |

> Pulumi Automation API drives the CLI, so the worker image must ship the
> Pulumi CLI and the provider plugins it needs; pin versions. Pinned for this
> phase (ADR-020, Q-12): CLI **3.277.0**, `@pulumi/pulumi` 3.277.0, the
> `terraform-provider` bridge plugin **1.5.1**, `coolify-terraform/coolify`
> **0.1.33** — about 280 MB in the worker image, nothing downloaded at runtime.

## Process model

```
 api process      stateless, N replicas        verifies JWT, validates, enqueues jobs,
                                               serves admin/tenant/internal APIs
 worker process   M replicas, queue consumers   runs sagas, Pulumi, adapters, reconciler
 broker path      part of api, latency-critical  token signing + webhook router
                  (deployable as its own service so it scales and fails independently)
```

The **broker/router must not queue behind provisioning work**: it runs in the
`api` process (or a dedicated `broker` deployment) with no dependency on
workers, only on the DB and Infisical (cached).

The two processes hold **different Infisical identities** (hard rule: the API
holds no powerful credentials). The `api` runs as `cp-broker`: viewer on project
`fortspace-broker` only, so it can read the LiveKit key and the per-tenant
webhook signing secrets and nothing else. The `worker` runs as `cp-worker`
(Infisical org admin, admin on the fixed projects) and also owns the Zitadel
provisioner key, the RustFS root credentials and the shard admin DSNs. The api
has no Coolify, Zitadel-management or RustFS credential at all.

## API surfaces

| Surface | Audience | AuthN | Examples |
|---|---|---|---|
| `/admin/v1` | Fortspace operators | Zitadel login, platform org, role `operator` | `POST /tenants`, `POST /tenants/{id}/suspend`, `GET /shards`, `POST /tenants/{id}/relocate` |
| `/tenant/v1` | Tenant admins | Zitadel login, role `tenant_admin`; **tenant derived from token** | `PUT /sso`, `POST /domains`, `GET /usage`, `POST /modules/{name}` |
| `/internal/v1` | Tenant stacks, LiveKit | Tenant stacks: service-account JWT with project role `tenant_stack`; LiveKit: webhook signature | `POST /livekit/token`, `POST /livekit/webhook`, `POST /tenants/self/heartbeat` |

> **Prototype status.** Built: `/admin/v1` `POST /tenants`, `GET /tenants`,
> `GET /tenants/{id}`, `POST /tenants/{id}/retry` (from `PROVISIONING_FAILED`),
> `POST /tenants/{id}/offboard` (also retries a dead-lettered offboarding),
> `GET`/`POST /shards`, `GET /tenants/{id}/runs`, `GET /runs/{runId}`;
> `/internal/v1` `POST /livekit/token` and `POST /livekit/webhook`; plus
> `/healthz`, `/readyz` and (outside production) `/docs`; Prometheus metrics are
> served by the OTel exporter on its own port (`METRICS_PORT`, default 9464). Not yet:
> `/tenant/v1`, suspend/resume, relocate, usage, heartbeat.

Rules: no tenant id in a URL accepted from a tenant-level caller (the token
supplies it); every mutating endpoint is idempotent via `Idempotency-Key`
(stored in `idempotency_keys`; see below); all errors use RFC 9457 problem JSON.
Auth runs first: `requireOperator`/`requireTenantStack` are `onRequest` hooks, so
an unauthenticated caller gets 401 before any body validation. For an
idempotent route the order is auth → `Idempotency-Key` check → body validation
→ claim of the key.

**Idempotency.** The header is required (1–200 characters) and keyed by the
caller (`<kind>:<sub>` of the verified principal) plus the key. The request hash
covers method, URL and the canonicalized body. Same key + same request
replays the stored response verbatim (header `Idempotent-Replayed: true`);
same key + different request is a 422; same key while the first request is still
running is a 409. A key is claimed by inserting a row before the handler runs;
the response is stored when it is sent. A 5xx or 3xx response deletes the row,
so the client can retry. Rows older than 24 h are ignored and replaced. An
in-flight row whose owner crashed is **taken over by the next retry after a
60 s lease**; this is a deliberate trade-off with a known limit (a handler
slower than the lease can run twice), described in
[10](/architecture/security-operations#known-limitations-of-the-prototype).

Broker details: it signs for tenants in `PROVISIONING` or `ACTIVE` (the
provisioning probe needs a real token before activation) and refuses every
other state with a 403 problem (`tenant-not-active`). The room must parse as
exactly `<slug>__<uuid>` and the slug must be the caller's tenant
(`room-not-in-tenant` otherwise; a prefix match is not enough, `acme` must not
reach `acme2`). Grants are default-deny: only the permissions the request asks
for are set. Tokens last ≤ 1 h; `roomAdmin`/`roomRecord` tokens 10 min. The
response is `{ token, livekitUrl, expiresAt }`. The route is rate limited **per
tenant** (the verified tenant id, not the IP; default 50 requests per second;
429 problem). The LiveKit key/secret are read from Infisical
(`/platform/livekit` in project `fortspace-broker`) into an in-memory cache that
is refreshed in the background every 10 minutes and keeps the last good value
when a refresh fails, so a key rotation is picked up without a restart.

## Data model (core Postgres, schema `control_plane`)

```sql
CREATE TABLE tenants (
  id                       uuid PRIMARY KEY,
  slug                     text NOT NULL UNIQUE CHECK (slug ~ '^[a-z][a-z0-9-]{1,30}$'),
  name                     text NOT NULL,
  tier                     text NOT NULL DEFAULT 'standard',       -- standard | dedicated_data | enterprise
  status                   text NOT NULL,                          -- REQUESTED | PROVISIONING | PROVISIONING_FAILED | ACTIVE | SUSPENDED | OFFBOARDING | ERASED
  initial_admin_email      text NOT NULL,                          -- invited at the last provisioning step; never returned by the API
  zitadel_org_id           text,
  orchestrator_type        text NOT NULL DEFAULT 'coolify',        -- never store vendor-specific columns ('fake' in the prototype)
  orchestrator_resource_id text,                                   -- project uuid
  db_shard_id              uuid REFERENCES db_shards(id),
  db_name                  text,
  bucket                   text,
  region                   text NOT NULL DEFAULT 'eu',
  created_at               timestamptz NOT NULL DEFAULT now(),
  updated_at               timestamptz NOT NULL DEFAULT now(),     -- set by the single transition function
  erased_at                timestamptz
);                                                                    -- CHECKs on status and tier; index (created_at desc, id desc)

CREATE TABLE tenant_domains (
  tenant_id   uuid REFERENCES tenants(id) ON DELETE CASCADE,
  domain      text PRIMARY KEY,           -- verified email/login domain (unique across tenants)
  verified_at timestamptz
);

CREATE TABLE tenant_modules (
  tenant_id uuid REFERENCES tenants(id) ON DELETE CASCADE,
  module    text NOT NULL,                -- meet | chat | mail | files ...
  version   text NOT NULL,
  state     text NOT NULL,
  PRIMARY KEY (tenant_id, module)
);

CREATE TABLE db_shards (
  id uuid PRIMARY KEY, name text NOT NULL UNIQUE, host text NOT NULL, port int NOT NULL DEFAULT 5432,
  admin_secret_ref text NOT NULL,       -- Infisical ref to the shard admin DSN: infisical:/platform/shards/<name>#ADMIN_URL
  tenant_count int NOT NULL DEFAULT 0, max_tenants int NOT NULL DEFAULT 50,
  status text NOT NULL DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE', 'FULL', 'DRAINING')),
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE room_routes (               -- derived; used by the event router
  tenant_id uuid REFERENCES tenants(id) ON DELETE CASCADE PRIMARY KEY,
  slug text UNIQUE, webhook_url text NOT NULL, webhook_secret_ref text NOT NULL
);

CREATE TABLE provisioning_runs (          -- one row per job: action = provision | offboard (CHECK)
  id uuid PRIMARY KEY, tenant_id uuid NOT NULL REFERENCES tenants(id), action text NOT NULL,
  state text NOT NULL,                     -- queued | running | succeeded | failed (CHECK)
  step text,                               -- the step running now; null when idle or finished
  attempt int NOT NULL DEFAULT 0, error text,   -- error is redacted and capped at 2000 characters
  created_at timestamptz NOT NULL DEFAULT now(), started_at timestamptz, finished_at timestamptz
);

CREATE TABLE provisioning_steps (         -- step trace the cockpit reads; outputs are ids/refs only
  run_id uuid REFERENCES provisioning_runs(id) ON DELETE CASCADE, step text,
  state text,                              -- running | succeeded | failed | skipped
  attempt int, output jsonb NOT NULL DEFAULT '{}', error text,
  started_at timestamptz, finished_at timestamptz, PRIMARY KEY (run_id, step)
);

CREATE TABLE idempotency_keys (
  actor text NOT NULL, key text NOT NULL, method text NOT NULL, path text NOT NULL,
  request_hash text NOT NULL,
  status_code int, response_body jsonb,    -- null while the request is in flight (the lease row)
  created_at timestamptz NOT NULL DEFAULT now(),   -- also the lease start; reset when a retry takes over
  PRIMARY KEY (actor, key)
);

CREATE TABLE audit_log (                   -- append-only
  id bigserial PRIMARY KEY, at timestamptz NOT NULL DEFAULT now(), actor text NOT NULL, actor_org text,
  tenant_id uuid, action text NOT NULL, target text NOT NULL,
  detail jsonb NOT NULL DEFAULT '{}'       -- ids and timestamps only; keys that look like secret/password/token/key/email are rejected
);
```

Secrets are **never** columns: only Infisical paths/refs (`*_ref`, format
`infisical:<path>#<KEY>`) are stored. The same rule covers logs, job payloads,
step outputs and audit detail: step outputs and audit details are checked
against a sensitive-key pattern (whole words, so `apiKey` or `api_key` are
refused but `monkeyCount` and `*Ref` path keys are not) before they are written, and error text that
is persisted or served by `/runs` is redacted first.

Status changes go through **one** function (`transitionTenant`): it checks the
transition table of [05](/architecture/tenant-lifecycle), then updates `WHERE status =
<from>`; zero rows means someone else moved the tenant and the call fails with a
409. The API service and every worker path (including the dead-letter handler)
use it; nothing else writes `tenants.status`.

## Job queue (pg-boss)

Provisioning, rotation and reconciliation jobs run on **pg-boss**, a queue
stored in core Postgres (its own schema, `pgboss`). No broker is added to the
stack. The alternative considered was hand-rolling the pattern from
[youjustneedpostgres.com](https://youjustneedpostgres.com/) (`job_queue` table,
`FOR UPDATE SKIP LOCKED` dequeue, `LISTEN/NOTIFY`); pg-boss *is* that pattern
plus the parts we would otherwise have to write (ADR-015).

| Need | How |
|---|---|
| Atomic dequeue by many workers | `SKIP LOCKED` inside pg-boss; no double execution |
| One mutating job per tenant (also avoids Pulumi stack lock errors) | queue policy **`stately`** + `singletonKey = tenantId` on tenant-mutating queues: at most one *queued* and one *active* job per tenant, a second enqueue is refused (`send` returns `null`, surfaced as a 409). `singleton` would only limit *active* jobs and let several pile up queued |
| Crashed worker | Job expiration (`expireInSeconds` 1800) returns the job to the queue; steps are idempotent so a re-run is safe |
| Retries | Per queue: `retryLimit` 3, exponential backoff (30 s base, capped at 600 s); then the job fails into the dead-letter queue |
| Dead letters | `<queue>.dlq` per queue, drained by a worker handler: provisioning → run `failed`, tenant `PROVISIONING_FAILED`, audit row and a metric; offboarding → run `failed`, tenant stays `OFFBOARDING` (resources may still exist), audit row and a metric. A late or duplicate dead-letter job never flips a tenant that moved on (the handler locks the row and checks the status) |
| Scheduled work | pg-boss schedules: nightly reconciler per tenant, key/secret rotation reminders, expired-slug cleanup (**not built yet**) |
| Retention | Jobs are deleted 30 days after completion (`deleteAfterSeconds`). No `pg_partman` needed at our volume |

Queues: `tenant.provision` and `tenant.offboard` (each with its `.dlq`) exist in
the prototype. Planned: `tenant.suspend`, `tenant.upgrade`, `shard.add`,
`shard.relocate`, `reconcile.tenant`, `secrets.rotate`. Policies are per queue,
so provisioning and offboarding do not serialize against each other; the tenant
state machine (optimistic `UPDATE … WHERE status = <from>`) covers that.

Rules:

* **The queue drives execution; the registry is the source of truth.** Job
  state is not shown to users. `provisioning_runs` (step, state, attempt,
  error) is what the cockpit reads, so the queue can be purged or replaced
  without losing history.
* **Enqueue in the same transaction as the state change** (pg-boss accepts an
  existing DB connection), so a tenant row never exists without its job or the
  reverse.
* Payloads carry ids only (tenant id, run id), never secrets or content. A
  worker drops a **stale** job (tenant not in the expected state, or already
  erased) with a warning instead of failing it.
* `LISTEN/NOTIFY` is not used directly; pg-boss polls with short intervals.
  It is not durable, and polling cost is negligible here.
* The token broker and event router never go through the queue (see Process
  model).
* If sagas outgrow this (long human-approval waits, complex fan-out), move to
  Temporal. That is Q-11 and is not needed for the first saga.

## Provisioner

> **Prototype status.** The prototype runs the same steps through a plain
> **saga runner** (each step calls a port directly and records its result in
> `provisioning_steps`; a re-run skips steps already succeeded). Pulumi runs
> three of them (ADR-011, ADR-034): the tenant's identity stack, its secrets
> stacks and its Coolify stack. RustFS, the shard database, DNS and the invite
> still call their ports directly. Failed provisioning ends in
> `PROVISIONING_FAILED`.
> A first failure is
> retried by the queue and resumes at the failed step; when the retries are
> exhausted the dead-letter handler runs the **compensation pass** (each step's
> optional `compensate`, in reverse order, recorded as `compensate:<step>` rows
> in `provisioning_steps`) before the tenant leaves `PROVISIONING`. The operator
> can then retry (steps are re-created idempotently) or offboard.
>
> Steps, in order (`provisioning_steps.step`): `reserve`, `secrets`, `identity`,
> `storage`, `database`, `route`, `orchestrator`, `domains`, `probes`,
> `activate`. Offboarding: `stop-stack`, `database`, `storage`, `secrets`,
> `identity`, `routes`, `erase`. A step that already **succeeded for this
> tenant and action** (in this or an earlier run) is not re-run: its output is
> copied into the new run and the step is recorded as `skipped`. A queue retry
> reuses the run id and never rewrites a step already succeeded in that run, so
> every attempt resumes at the failed step. A failing step is recorded
> `failed`, the run `failed`, and the error rethrown so the queue retries; an
> operator retry (`POST /tenants/{id}/retry`) creates a **new run**. Secret-like
> keys in a step output are rejected; steps return ids only.

* Triggered by `POST /admin/v1/tenants`; in **one transaction** it writes the
  tenant row (`REQUESTED`), its modules, the queued run, the audit row and the
  `tenant.provision` job (`singletonKey = tenantId`). The worker moves the
  tenant to `PROVISIONING` (with an audit row) before the first step.
* Each Pulumi step loads (or creates) its stack through the Automation API and
  calls `up` with the complete set of what it declares:

  | Step | Pulumi project / stack | Declares |
  |---|---|---|
  | `secrets` | `tenant-secrets` / `<slug>.base` (and `<slug>.operator`) | Infisical project, folders, generated secrets, the stack's machine identity, its membership and client secret, the bootstrap copy |
  | `identity` | `tenant-identity` / `<slug>` | Zitadel org, project grants, login policy, meet app, service account, its grant and key |
  | `identity`, `storage`, `database`, `route` | `tenant-secrets` / `<slug>.<step>` | the secrets that step produces |
  | `orchestrator` | `tenant` / `<slug>` | the Coolify resources |

  Zitadel and Infisical use the official Terraform providers through the bridge
  (as the base stack does, ADR-033), configured with the worker's own
  credentials (`cp-provisioner`, `cp-worker`). The saga keeps the ordering, the
  retries and the compensation (`destroy`). One `secrets` stack per step because
  values such as the storage key and the database password only exist at their
  step.
* Limits: nothing calls `refresh` (drift detection) on these stacks yet (it
  works on the identity stack with the provisioner's rights). A run
  killed between creating an object and recording it in the state needs an
  operator to remove that object.
* On failure: job is retried with backoff (3×), then state
  `PROVISIONING_FAILED` and an operator alert (error log and the metric
  `fortspace_cp_provisioning_failures_total` for now); `provisioning_runs` and
  `provisioning_steps` keep the step trace.
* Detail and diagram: [05](/architecture/tenant-lifecycle).

### The orchestrator step in this phase (Pulumi + Coolify)

> **Status: designed and decided, not built yet.** The adapter, the port
> extension and the worker wiring land in the P3–P5 tasks of the control-plane
> plan; what follows is the design they implement. Until then the prototype
> keeps the file-backed fake orchestrator and the tenant row records
> `orchestrator_type = fake`.

One Pulumi stack per tenant drives the tenant's Coolify project:

| Concern | Value |
|---|---|
| Pulumi project / stack | project `tenant`, stack `<slug>` → `organization/tenant/<slug>` (ADR-022; the Postgres DIY backend only accepts the organization named `organization`, so `fortspace/tenant/<slug>` is impossible) |
| Coolify project | `fortspace-tenant-<slug>` (the `fortspace-` prefix is the guard: it can never match the pre-existing `fortspace` project) |
| Stack content | environment, compose service (the tenant modules), env vars (secrets as `pulumi.secret`), a per-tenant tag `tenant-<slug>`, a start action |
| State | `pulumi_state` database on core Postgres, its own role; only the worker holds the URL (hard rule 8) |
| Secrets | the stack's secrets are Pulumi secrets, encrypted in the checkpoint with a passphrase that lives in Infisical (ADR-021) |
| Inputs | the stack config is **not** in the backend: the adapter sets it from the registry on **every** run (`setAllConfig`), so the workspace is disposable |
| Operations | `up` (create-or-update), `preview`, `refresh` (drift), `destroy` + `removeStack` (offboarding) |

The `Orchestrator` port stays vendor-neutral (hard rule 1); the Pulumi and
Coolify types live in the adapter. It gains the operations the reconciler will
need: `preview(spec)` (planned changes, counts only), `refresh(resourceId)`
(drift summary) and secret inputs expressed as `SecretRef`s that the adapter
resolves through `SecretsPort` — **the spec never carries a value**. The
existing `createStack` becomes create-or-update (`up`) and `findStack` becomes
mandatory, so a stack whose id was never written to the registry can still be
found and deleted.

Errors map to `AppError`: a held stack lock is `conflict` (a second concurrent
`up` is refused by the backend), a provider or Coolify failure is `upstream`
or `unavailable`. No provider text that could contain a secret reaches a log,
a step output or an error message.

A lock left by a killed process is cleared with `stack.cancel()` — **only** by
the job that holds the tenant's pg-boss singleton, never by the API, and only
after the singleton confirms no live run for that tenant (Q-12).

### Why Pulumi *and* adapters

Coolify has no official Pulumi provider, but a maintained **Terraform** provider
exists: **`coolify-terraform/coolify`** (0.1.33). We consume it through
Pulumi's **Any Terraform Provider** (the `terraform-provider` bridge), so the
Coolify resources are managed by Pulumi without writing a provider (ADR-020).
The provider was verified against Coolify 4.7.6 in a spike: project,
environment, compose service, env vars, start, status read, drift detection,
reconciliation and destroy all worked.

The rule is the same either way: mutating Coolify's runtime state behind its
back would split authority, so Pulumi owns the *desired set of tenant resources
and their lifecycle* while every mutation goes through Coolify's own API (via
the generated provider today, via a REST adapter if we ever fall back), and
Coolify stays the runtime source of truth. Base infrastructure (VPS, DNS,
firewall, Coolify install) is regular Pulumi with real providers.

The **guards** around a root-team token are code and tests, not Coolify
permissions: the adapter only manages projects named `fortspace-tenant-<slug>`,
tags what it creates, and `destroy` acts only on stacks recorded in
`pulumi_state`. See [09](/architecture/infrastructure#coolify-layout) and
[10](/architecture/security-operations#exceptions-and-known-risks).

## Reconciler

> **Not in the prototype.** The registry-vs-reality comparison is future work;
> the prototype has no scheduled jobs.

A scheduled job per tenant (nightly + on demand):

1. `pulumi refresh` (dynamic providers `read()` call the adapters).
2. Health probes: go-meet `/healthz`, tuwunel, OIDC discovery.
3. Compare registry ↔ reality: orphan buckets/DBs/Coolify projects (alert, do
   not auto-delete), missing resources (auto-heal via `up`).
4. Emit drift metric + audit entry.

Auto-heal is limited to idempotent re-creation; destructive actions always need
an operator. The Pulumi adapter already offers the two operations the
reconciler needs (`preview`, `refresh`) — the scheduled loop itself is not
built yet.

## Ports and adapters

```ts
// packages/ports: interfaces and plain data types only, no vendor imports
interface Orchestrator { createStack(spec): Promise<{ resourceId }>; redeploy(resourceId);
  destroy(resourceId); health(resourceId): Promise<Health>; findStack(slug);
  preview(spec): Promise<{ changes: number }>; refresh(resourceId): Promise<{ drift: number }> }
// Coolify (Pulumi), Dokploy, K8s adapters implement it (prototype: file-backed fake)
interface IdentityPort   { applyTenant; destroyTenant; recover; inviteAdmin; oidcDiscoveryHealthy }
interface SecretsPort    { ensureFolder; getSecret; putSecret; putSecretIfAbsent; deleteFolder }
interface TenantSecretsPort { applyProject; applySecrets; destroyTenant; recover }
interface ObjectStorePort{ ensureBucket; ensureScopedUser; deleteScopedUser; emptyAndDeleteBucket }
interface DatabasePort   { ensureDatabase; resetRolePassword; migrate; dropDatabase }
interface DnsPort        { upsert; remove }
```

The `Orchestrator` port is the one that changes in this phase: `preview` and
`refresh` are added (the reconciler needs them), `findStack` becomes
mandatory, and `createStack` becomes create-or-update. Secret inputs travel as
`SecretRef`s inside the spec, never as values — the adapter resolves them
through `SecretsPort`. The port stays vendor-neutral: no Pulumi or Coolify
type crosses it (hard rule 1).

Every call is **create-or-get** (`ensure*`) or **delete-if-exists**, so a saga
step can be re-run. Calls to a vendor carry a timeout and map failures to
`upstream`/`unavailable` errors. Adapters exist for Zitadel, Infisical, RustFS
and the Postgres shard; the orchestrator and DNS are fakes, and every port also
has an in-memory fake that the contract tests run against.

Rule: no vendor type crosses a port (a test fails if a port imports anything
but relative files). The tenant row keeps
`orchestrator_type` (`fake` in the prototype, `coolify` once the Pulumi
adapter is wired) + `orchestrator_resource_id`, so
moving to Dokploy (or Kubernetes) means writing one adapter and migrating
tenants one at a time. All tenant-scoped names (Zitadel org, `meet-<slug>`,
Infisical project, bucket, S3 user and policy, database and role, stack) come
from one module (`naming.ts`); hand-built names elsewhere are a bug.

## Cockpit and tenant console

Two frontends, one API (ADR-031):

| App | Audience | Host | API surface | Status |
|---|---|---|---|---|
| **cockpit** (`apps/cockpit`, image `control-plane-cockpit`) | Fortspace operators | `cockpit.<domain>` | `/admin/v1` | prototype: login, tenants view, shards view |
| **console** (`apps/console`, image `control-plane-console`) | Tenant admins | `console.<domain>` | `/tenant/v1` | planned |

Both are TanStack Start apps talking to the CP API over HTTP (same repo, shared zod
types and a shared login/session package once the second one exists). Each is a
backend-for-frontend: its server performs the OIDC login, keeps the tokens
server-side, and forwards the user's access token to the API. Neither has
**database, Infisical or orchestrator credentials**, so the API stays the single
place where authorization, idempotency and audit are enforced (ADR-017).

Each app is its own OIDC client in Zitadel, and **each API surface accepts only
tokens issued to its own client** (audience check): a tenant-console token can
never reach `/admin/v1`, even if a role check had a bug. The cockpit lives in the
platform org; the console serves the tenant orgs.

Cockpit views: tenants, shards, provisioning runs, drift, audit. Console views
(planned): SSO connection wizard, domains, modules, usage, users, subscription,
data export. Server functions re-check the caller's role and tenant on every
call. In the prototype the cockpit has the login, a tenants view and a shards
view; roles are re-checked from a refreshed ID token every 10 minutes (see
[03](/architecture/identity-access#operator-login-cockpit)). Operators who need to see
what a tenant admin sees use an explicit, audited **support session**, not a
login into the console.

## Failure and availability

| Scenario | Behavior |
|---|---|
| Worker down | Provisioning delayed; calls unaffected |
| API down | Cockpit, tenant console and new joins fail → run ≥ 2 API replicas |
| Core Postgres down | CP down; running calls continue (tokens already issued, tenant stacks self-sufficient) |
| Infisical down | Broker keeps the last good LiveKit key in memory and the router the last good routes and webhook secrets (a read error serves the cached value, else a 502/503 problem so LiveKit retries); provisioning fails and is retried; new tenant stacks cannot start (existing keep running) |
| Identity provider unreachable | While discovery or the JWKS cannot be fetched the API answers 503 (not 401) to authenticated calls; an already cached key set keeps working and a failure is never cached, so the next request retries |
| Zitadel down | New logins fail; existing sessions and calls continue |
| Pulumi state backend down | The Coolify step fails (`unavailable`) and is retried; the tenant stays `PROVISIONING` and no Coolify mutation is attempted without state |
| Coolify down | The Coolify step fails (`upstream`) and is retried; the stack keeps its last known state in `pulumi_state` and the next `up` reconciles it |
