[data-reveal]{opacity:1!important;transform:none!important}
AntelopeJS DMS
DocumentationOperations

Operations

How operator actions, plan migrations, checkouts, webhooks and workspace creation stay safe under retries and crashes, and how to reconcile them.

This page is for the people who run a deployment of the SaaS module. Every money-moving workflow persists its intent before any Stripe or lifecycle effect, refuses timed takeovers, and stops in a reconciliation required state instead of replaying an effect it cannot prove. The design gives up automatic crash recovery to avoid double charges and conflicting external effects.

Start with the recorded outcome

A timed-out customer-credit request does not tell you whether Stripe applied the credit. The existing operation records what happened:

text
GET /api/saas/workspaces/<tenantId>/operations/<operationId>

This endpoint requires platform-owner authentication. A retry keeps the operation ID and the original values, because a new ID describes a new action.

What you establishNext step
The attempt definitively failed and its executor finishedRetry within the window below, with the same ID and values
The outcome is unknown, or an executor may still be activeStop automatic retries and reconcile the provider and local records
The action succeededDo not issue it again to refresh the screen

Reconciliation means investigating the recorded effects and proving that the previous executor has stopped. No button forces success. The sections below name the evidence to inspect for each workflow.

Operator actions

The platform-owner workspace page offers suspension, reactivation, immediate Stripe-backed upgrades and Stripe customer-balance credits. Every request carries a caller-supplied operation ID of 8 to 64 letters, digits or hyphens, and creates a private durable command intent before any Stripe or lifecycle effect. The command record keeps the actor, tenant, action, values, attempts, outcome and effective time. Retrying the same ID with the same values resumes an eligible failed operation. Reusing the ID with different values answers 409 saas.errors.operator.idempotency_mismatch.

Retry or reconcile

Operator attempts use no leases and no timed takeover. The outcome decides whether a retry is safe:

OutcomeNext step
Definitive failure whose execution has finishedRetry with the same operation and provider payload, for 23 hours from the intent's creation
Unknown outcome, a lost journal acknowledgement includedReconcile instead of retrying

A retry of an operation that is still running, that requires reconciliation, or whose 23-hour window has passed answers 409 saas.errors.operator.reconciliation_required. The 23-hour window keeps a one-hour margin inside Stripe's minimum 24-hour idempotency retention.

Suspension, reactivation and immediate plan changes persist a subscription transition before their effects. Its revision fences competing local transitions and deletion, and the operator journal must succeed before the intent is cleared. An ordinary subscription write rejects pending transitions and deletion markers. None of this provides distributed transactions, or fences an external request that has already left the process.

Inspect and resolve an operation

Inspect an operation through the platform-owner endpoint GET /api/saas/workspaces/:tenantId/operations/:operationId. Its requiresReconciliation field is true for a running or reconciliation_required operation, which may still have an old executor active.

Before you resolve such an operation, establish both of these:

  1. The previous executor is stopped or quiescent.
  2. What happened externally, from the persisted operation, the provider request details and the provider records.

A matching Stripe read alone does not prove quiescence. There is deliberately no force-success endpoint that clears the intent without those proofs.

Plan migrations

A bulk plan migration captures an immutable workspace list and the resolved target configuration before it starts. Each workspace gets a persisted outcome and a subscription transition before any provider effect. A crash after changing planId does not remove that workspace from the snapshot. A running job never uses timed takeover. At startup, a running job with no live executor is marked reconciliation_required, and keeps its per-workspace evidence and pending subscription intents instead of replaying effects.

POST /api/saas/plans-deletion/:fromPlanId/migrate-and-delete closes the source plan to sign-ups and starts the migration. It does not delete the plan. The migration's detail page reads its state from /api/saas/plan-migrations/:id (/header, /totals, /workspaces, /changes and /journal). Workspaces that arrive on the source plan after the capture are outside the job. Deleting the plan is a separate DELETE /api/saas/plans/:id, which refuses while a workspace is on the plan or a scheduled change targets it. A current reference count cannot exclude a suspended writer that already validated the plan.

Settling a migration requires stopping the prior executor or proving that it is quiescent, and establishing the provider, subscription, permission-cleanup and notification outcomes. A target planId or a matching Stripe response alone is not enough. The platform owner then settles it from the detail page:

  • POST /api/saas/plan-migrations/:id/workspaces/:tenantId/resolve records an uncertain workspace as moved (the DMS takes the target plan) or not moved (its intent is released so it can be retried).
  • POST /api/saas/plan-migrations/:id/retry moves again the workspaces known not to have moved, each under a new operation.
  • POST /api/saas/plan-migrations/:id/reconcile closes the migration and keeps its remaining workspaces on the source plan. It refuses while a workspace is uncertain.

There is no automatic force-success or effect-replay endpoint, and a job ID does not make arbitrary hooks idempotent.

Self-service changes and checkout

Self-service cancellation, deferred plan changes and administrative free grants also admit a subscription intent before any Stripe effect. An ambiguous schedule replacement keeps the previous mirror and the pending intent. It does not try to restore or erase the provider state blindly.

Checkout holds a checkout intent until the exact recorded session completes or expires. Completion admits one callback executor, and writes a terminal session receipt only after its awaited provider effects finish. An unknown callback outcome keeps the intent instead of allowing a timed replay. A session whose ID was never acknowledged locally requires manual reconciliation, executor quiescence included. A recorded session that expired unpaid releases the trial it reserved, on a best-effort basis. A failed release only withholds the trial. Checkout automation events stay best-effort, outside the terminal receipt, and promise neither exactly-once delivery nor external order.

Stripe webhooks

Stripe webhook dispatch admits an event once and fences completion with its admitted revision. An old pending record never permits a timed takeover. A handler failure becomes reconciliation_required, which blocks replay because the attempt may have partial effects. While the record is unresolved, a redelivery receives an error, not a successful acknowledgement or another execution.

Inspect stripe_webhook_events by Stripe event ID for its result, revision and error message. Recovery requires establishing the prior executor's quiescence and the handler's database and external outcomes. Do not delete the admission or resend blindly. There is no recovery endpoint, and unresolved records stay indefinitely. One exception is an unresolved invoice.created record: the invoice line injection task closes it as success once it has suspended or finalized the draft invoice. A cron deletes success and skipped records older than 90 days, daily at 04:00, so deduplication does not hold for a redelivery after that window.

The revision mutations need a database adapter that implements atomic revision updates, as the @antelopejs/mongodb adapter (1.8.10 or later) the test suite runs on does. Every record is written with a revision, and these mutations refuse a record without one. See Upgrading for rows written by earlier builds.

Tenant lifecycle consumers

A lifecycle-dependent module registers a required consumer through the public interface:

typescript
import {
  RegisterTenantLifecycleConsumer,
  type TenantLifecycleConsumerRegistration,
} from "@antelopejs/interface-dms-saas/tenant-lifecycle";

let lifecycleRegistration: TenantLifecycleConsumerRegistration | undefined;

export function construct(): void {
  lifecycleRegistration = RegisterTenantLifecycleConsumer({
    name: "cloud.workspaces",
    transitions: ["suspended", "reactivation_requested"],
    async consume(message) {
      const receipt = await applyWorkspaceLifecycle(message);
      return {
        receiptId: receipt.id,
        effectiveAt: receipt.effectiveAt,
      };
    },
  });
}

export function stop(): void {
  lifecycleRegistration?.unregister();
  lifecycleRegistration = undefined;
}

Registration lifecycle

Register required consumers during module construction, before module startup reconciliation. Registration may happen before the SaaS module is constructed, because the SaaS module replays buffered consumers when it attaches its module-owned registry. A consumer name is 3 to 64 characters long. It starts with a lower-case letter, followed by lower-case letters, digits, ., _ or -.

A registration is removed automatically when its owning module unloads. The explicit handle stays available for module stop compatibility.

Delivery guarantees and access

Every consumer declares the transitions it handles: created, suspended and reactivation_requested. For example, transitions: ["created"] handles creation only, and all three also handle suspension and reactivation. A consumer must return a durable receipt and deduplicate its effects by operationId.

Messages carry stable tenantId and operationId values. Deliveries and receipts are persisted, and a persisted success is skipped on later retries.

Concurrent reconcilers may invoke the same consumer more than once before its receipt is persisted. Consumers must deduplicate concurrent calls by operation identity. The outbox provides neither exactly-once execution nor ordering of external effects. Failed deliveries stay available to startup reconciliation and to a retry cron that runs every five minutes.

Access depends on the transition:

  • Suspension closes SaaS access before consumer delivery.
  • Reactivation keeps SaaS access closed until every required consumer returns a durable receipt.

The consumer therefore owns any product-specific sleep or wake work.

Successful workspace creation

Provisioning reserves free-workspace capacity per card, and trial eligibility per email and card identity, before it issues any provider effect. These reservations do not expire. An unknown provider or persistence outcome keeps the reservation and the account for reconciliation. The service never replays opaque provisioning hooks or stores their extras. Known provider handles and the attempt ID are persisted separately from billing profiles. Stripe customer metadata also holds the attempt ID, for investigating a lost creation response.

Platform owners inspect the first 100 unresolved records through GET /api/saas/workspaces/provisioning-attempts, and one record through GET /api/saas/workspaces/:tenantId/provisioning-attempt. A preparing record can stand for an executor that disappeared before it recorded its error. Before you repair a record or release an allocation, establish executor quiescence, provider cancellation or successful creation, and tenant closure. The SaaS module has no repair command. Never release uncertain reservations by age, or re-run non-idempotent hooks with guessed input.

For a creation, the operationId is workspace-created:<tenantId>, which stays the same across delivery retries.

Self-service provisioning writes a creation marker in the existing lifecycle outbox before it inserts the tenant. It allows payment confirmation only after ownership, billing records and every TENANT_BEING_PROVISIONED listener succeed. Trials and creations without an invoice need no payment, and a zero-total invoice already marked paid is not paid again. An invoice-backed creation is committed only after Stripe reports its first invoice paid. Consumer failures never roll back committed workspaces.

Inventory reconcilers must check the public provisioning gate before they create external resources. The check stops a concurrent inventory scan from provisioning a tenant whose membership, hooks or payment are still incomplete. It does not replace tenant existence, authorization or suspension checks.

typescript
import { IsTenantProvisioningCommitted } from
  "@antelopejs/interface-dms-saas/tenant-lifecycle";

async function reconcileTenant(tenantId: string): Promise<void> {
  if (!(await IsTenantProvisioningCommitted(tenantId))) return;
  await ensureWorkspaceResources(tenantId);
}

The gate returns true for legacy, default and bootstrap tenants that have no creation marker. It returns false for preparing, unpaid or cancelled creations, and it propagates storage failures, so callers must fail closed. Cancellation leaves a tombstone, so even a partial rollback cannot make an orphaned tenant eligible. Do not delete these markers while the tenant may stay in an inventory.

Reconciliation recovers a crash after a successful payment but before delivery, a partial consumer fan-out and lost receipts. It may deliver a message again when a consumer commits its effect before the receipt is saved, so consumers must make their resource creation and ownership linkage idempotent. Delivery skips tenants already deleted when the attempt starts. Consumers must also tolerate a deletion that races an in-flight attempt.

A definitive card decline permits rollback only after tenant lifecycle admission closes and every required deletion hook succeeds. An incomplete closure preserves the data, the account ownership and the recovery markers. Rollback never drops the tenant schema or the lifecycle and invitation tombstones. An ambiguous payment error preserves the tenant and the account, because a timeout can hide a successful charge. Reconciliation checks the payment status but never starts another charge. A crash before payment, an unpaid ambiguous result, or an interrupted pre-payment preparation requires payment and provisioning recovery. Reconciliation never emits created only because the tenant exists. The delivery operation ID does not make HTTP creation requests idempotent.

Register consumers before startup reconciliation. For a bootstrap or a backfill, use the existing tenant inventory and the gate, and do not treat created as a historical inventory API.