RolebookDocs

PostgreSQL resource lifecycle

Initializing owners, and deleting or moving resources atomically with their sharing state.

Sharing state belongs to an application row. Creating, deleting, or moving that row must change the sharing state in the same SERIALIZABLE transaction, or a private resource can outlive its grants or carry them somewhere they were never given.

Initializing a resource

A resource has exactly one owner, created when the resource is created:

import type { PostgresSharingAdapter, ParameterizedSqlExecutor } from "@rolebook/sharing-postgres";
import { withSerializableTransaction } from "@rolebook/sharing-postgres";

declare const executor: ParameterizedSqlExecutor;
declare const projectAdapter: PostgresSharingAdapter;
const workspaceId = "8c3a3b8e-2f0e-4c1b-9d55-1f0f1b5b8a10";
const projectId = "5d2a7c9e-6b1f-4f57-8e3a-0b9c1d2e3f40";
const user = { type: "user", id: "user_123" };

const result = await withSerializableTransaction(executor, async (transaction) => {
  await transaction.query(
    "INSERT INTO app.project (workspace_id, id, title, version) VALUES ($1, $2, $3, 1)",
    [workspaceId, projectId, "Q3 launch"],
  );
  return projectAdapter.initializeResourceInTransaction(transaction, {
    tenantId: workspaceId,
    resourceId: projectId,
    owner: user,
    actor: user,
    occurredAt: new Date(),
  });
});
// "applied" | "already_initialized" | "identity_ineligible" | "owner_mismatch" | "group_owner" | "not_found"
  • Initialization locks and verifies both the actor and the intended owner through the eligibility fence before creating or inspecting ownership; an ineligible one is identity_ineligible.
  • Retrying with the same owner is already_initialized; a different owner is owner_mismatch, and ownership is unchanged. A group owner is group_owner.
  • It records a resource.initialized audit event and mints the resource’s incarnation identifier.
  • initializeResourceInTransaction() accepts only a SerializablePostgresTransaction. initializeResource(input) opens its own transaction, for resources that already exist.
  • A resource without an owner row stays fail-closed: readAccess() returns nothing for it.
  • A key whose revision floor reached the largest bigint cannot start a new generation: initialization throws PostgresLifecycleConflictError and writes nothing.

Deleting and moving

resourceDeleted() and resourceMoved() return "unsupported": the adapter never mutates an application row through a standalone call. Use withLifecycleTransaction() and the matching ...InTransaction() method instead. Your callback performs the conditional application change on the supplied transaction, using the supplied pre-version in its WHERE clause:

import type { PostgresSharingAdapter } from "@rolebook/sharing-postgres";

declare const projectAdapter: PostgresSharingAdapter;
declare const project: { readonly version: string; readonly sharingRevision: string };
declare const idempotencyFingerprint: string;
const actor = { type: "user", id: "user_123" };
const [workspaceA, workspaceB, projectId] = ["ws_a", "ws_b", "project_1"];
const nextVersion = String(Number(project.version) + 1);

const moved = await projectAdapter.withLifecycleTransaction((transaction) =>
  projectAdapter.resourceMovedInTransaction(transaction, {
    fromTenantId: workspaceA,
    toTenantId: workspaceB,
    resourceId: projectId,
    expectedResourceVersion: project.version,
    expectedSharingRevision: project.sharingRevision,
    resultingResourceVersion: nextVersion,
    actor,
    requiredEligibleSubjects: [actor],
    idempotencyKey: "move-project_1-to-ws_b",
    idempotencyFingerprint,
    occurredAt: new Date(),
    moveResource: async (tx) => {
      const changed = await tx.query(
        `UPDATE app.project SET workspace_id = $3, version = $4
         WHERE workspace_id = $1 AND id = $2 AND version = $5`,
        [workspaceA, projectId, workspaceB, nextVersion, project.version],
      );
      return changed.rowCount === 1 ? "applied" : "conflict";
    },
  }),
);
// "applied" | "already_applied" | "not_found" | "conflict" | "identity_ineligible"

resourceDeletedInTransaction(transaction, { tenantId, resourceId, deleteResource, ... }) works the same way with a deleteResource callback.

What the adapter guarantees:

  • It adds and deduplicates the actor in requiredEligibleSubjects, locks every source-tenant identity before the callback, and returns identity_ineligible without calling it if any is stale.
  • Moves. Before the callback it locks and verifies the retained owner in the destination tenant and removes the source key’s live sharing rows (memberships, invitations, mutation idempotency), so the application’s UPDATE passes the restricting foreign keys. After the callback it re-attaches only the owner at the destination, with its original creation metadata. Members and invitees from the old tenant never gain access in the new one, and any grant the callback writes at the destination fails the move. A move must write its declared resultingResourceVersion. A move between two spellings of the same uuid tenant is a same-tenant move and keeps its grants.
  • Deletions. The adapter verifies that none of the resource’s sharing rows survive under any tenant. A deletion authorized against an earlier generation of a re-created, not yet initialized key returns conflict instead of deleting the replacement.
  • It increments the sharing revision and records the lifecycle idempotency record and audit event before commit. A lifecycle record is bound to the command’s fingerprint and to the sharing revision it was authorized against, so a retry replays as already_applied while a same-key command authorized against a re-created resource conflicts.
  • After the callback starts, a non-applied result or a failed postcondition throws PostgresLifecycleConflictError, and the transaction is marked rollback-only even if the error is caught. The same holds for errors the callback throws, including non-Error values.

Rules for lifecycle callbacks

Use only the transaction you are given. Write the conditional UPDATE or DELETE with the pre-version. Let a PostgresLifecycleConflictError escape so the transaction rolls back. Perform no external side effects: retries replay the whole unit of work. Never call a standalone lifecycle convenience after the application change committed: it cannot repair a split transaction.

Cross-tenant moves are unsupported by default and work only through this complete contract, including the restricting keys from the migrations: with them, an UPDATE of an initialized resource’s (tenant, id) outside the move path fails with 23001. Same-tenant hierarchy moves use the same contract and must update the resource version, so conditions and ancestry are evaluated again.