@domainkit/capsuledb 0.11.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +41 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { DomainKit, Principal, Reason, Storage } from "domainkit";
|
|
|
4
4
|
import { DateTime, Effect, Layer, Option, Schema as Schema$1 } from "effect";
|
|
5
5
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
|
6
6
|
//#region package.json
|
|
7
|
-
var version = "0.
|
|
7
|
+
var version = "0.12.1";
|
|
8
8
|
//#endregion
|
|
9
9
|
//#region src/internal/storage.ts
|
|
10
10
|
/**
|
|
@@ -106,6 +106,7 @@ const attachmentOf = (row) => attachmentCodec.read({
|
|
|
106
106
|
connectionId: row.connection_id,
|
|
107
107
|
domain: row.domain,
|
|
108
108
|
zone: row.zone,
|
|
109
|
+
label: row.label,
|
|
109
110
|
target: fromJson(row.target),
|
|
110
111
|
createdAt: iso(row.created_at)
|
|
111
112
|
});
|
|
@@ -335,16 +336,18 @@ const make$2 = (tables) => Effect.gen(function* () {
|
|
|
335
336
|
connectionId: input.connectionId,
|
|
336
337
|
domain: input.domain,
|
|
337
338
|
zone: input.zone,
|
|
339
|
+
label: input.label,
|
|
338
340
|
target: input.target,
|
|
339
341
|
createdAt: yield* DateTime.now
|
|
340
342
|
});
|
|
341
343
|
const encoded = yield* attachmentCodec.write(row);
|
|
342
344
|
return (yield* sql`
|
|
343
345
|
INSERT INTO ${attachments} (
|
|
344
|
-
id, owner_id, connection_id, domain, zone, target, created_at
|
|
346
|
+
id, owner_id, connection_id, domain, zone, label, target, created_at
|
|
345
347
|
) VALUES (
|
|
346
348
|
${encoded.id}, ${encoded.ownerId}, ${encoded.connectionId}, ${encoded.domain},
|
|
347
|
-
${encoded.zone}, ${
|
|
349
|
+
${encoded.zone}, ${encoded.label}, ${toJson(encoded.target)},
|
|
350
|
+
${at(encoded.createdAt)}
|
|
348
351
|
) ON CONFLICT (owner_id, domain) DO NOTHING RETURNING id
|
|
349
352
|
`)[0] === void 0 ? yield* invalid(`${input.domain} is already attached`, "domain") : row;
|
|
350
353
|
}))).pipe(guard("attachments.create")),
|
|
@@ -658,6 +661,11 @@ const make$1 = (prefix) => ({
|
|
|
658
661
|
connection_id: Schema.text(),
|
|
659
662
|
domain: Schema.text(),
|
|
660
663
|
zone: Schema.text(),
|
|
664
|
+
/**
|
|
665
|
+
* The provider's label for the zone at attach time, so a UI names the account offline. The
|
|
666
|
+
* default is what fills the rows an installation attached before the column existed.
|
|
667
|
+
*/
|
|
668
|
+
label: Schema.text({ default: "" }),
|
|
661
669
|
target: Schema.json(),
|
|
662
670
|
created_at: Schema.timestamp()
|
|
663
671
|
},
|
|
@@ -729,6 +737,27 @@ const make$1 = (prefix) => ({
|
|
|
729
737
|
indexes: [{ columns: ["owner_id", "next_check_at"] }, { columns: ["attachment_id"] }]
|
|
730
738
|
})
|
|
731
739
|
});
|
|
740
|
+
/**
|
|
741
|
+
* The attachments table as the first migration created it, before `label`.
|
|
742
|
+
*
|
|
743
|
+
* A migration is history: what it renders must not move, or an installation that already ran it
|
|
744
|
+
* sees a different checksum for work it has done. The declaration above is the current shape, and
|
|
745
|
+
* the migration that adds the column carries the difference.
|
|
746
|
+
*/
|
|
747
|
+
const attachmentsV1 = (prefix) => Schema.table(`${prefix}_attachments`, {
|
|
748
|
+
columns: {
|
|
749
|
+
id: Schema.text(),
|
|
750
|
+
owner_id: Schema.text(),
|
|
751
|
+
connection_id: Schema.text(),
|
|
752
|
+
domain: Schema.text(),
|
|
753
|
+
zone: Schema.text(),
|
|
754
|
+
target: Schema.json(),
|
|
755
|
+
created_at: Schema.timestamp()
|
|
756
|
+
},
|
|
757
|
+
primaryKey: ["id"],
|
|
758
|
+
uniques: [["owner_id", "domain"]],
|
|
759
|
+
indexes: [{ columns: ["owner_id", "connection_id"] }]
|
|
760
|
+
});
|
|
732
761
|
const list = (tables) => [
|
|
733
762
|
tables.authorizations,
|
|
734
763
|
tables.connections,
|
|
@@ -760,7 +789,15 @@ const make = (prefix = DEFAULT_PREFIX) => {
|
|
|
760
789
|
id: 1,
|
|
761
790
|
name: "create-storage",
|
|
762
791
|
risk: "additive",
|
|
763
|
-
steps: list(tables).map(Migration.createTable)
|
|
792
|
+
steps: list(tables).map((table) => Migration.createTable(table.name === tables.attachments.name ? attachmentsV1(prefix) : table))
|
|
793
|
+
}), Migration.make({
|
|
794
|
+
id: 2,
|
|
795
|
+
name: "attachment-label",
|
|
796
|
+
risk: "additive",
|
|
797
|
+
steps: [Migration.addColumn(tables.attachments.name, "label", {
|
|
798
|
+
type: "text",
|
|
799
|
+
default: ""
|
|
800
|
+
}), Migration.sql(Object.fromEntries(["postgres", "sqlite"].map((dialect) => [dialect, [`UPDATE ${tables.attachments.name} SET label = zone WHERE label = ''`]])))]
|
|
764
801
|
})],
|
|
765
802
|
layer: Layer.effect(Storage.Service)(make$2(tables))
|
|
766
803
|
});
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["Schema","make","make","makeTables","makeService","packageJson.version"],"sources":["../package.json","../src/internal/storage.ts","../src/internal/tables.ts","../src/capsule.ts","../src/PgStorage.ts","../src/index.ts"],"sourcesContent":["","/**\n * `Storage.Interface` on PostgreSQL.\n *\n * Every method reads `Principal` and filters by `owner_id`, so a row belonging to another tenant\n * is indistinguishable from a row that does not exist. Aggregate transitions run inside one\n * transaction over a `FOR UPDATE` row, single-flight guards use a session-level advisory lock on a\n * reserved connection, and revocation is two-phase: mark `pending`, call the provider outside any\n * transaction, then delete.\n *\n * Storage never sees plaintext. `Connect` seals a credential through `Custody` before it reaches\n * `upsert` or `rotate`, so this module only ever moves a ciphertext string.\n */\nimport { DomainKit, Principal, Reason, Storage } from \"domainkit\";\nimport { DateTime, Effect, Option, Schema } from \"effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlError from \"effect/unstable/sql/SqlError\";\n\nimport type { Tables } from \"./tables.ts\";\n\ntype Fail = DomainKit.Error;\n\n// ---------------------------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------------------------\n\nconst fail = (reason: Reason.Model) => Effect.fail(new DomainKit.Error({ reason }));\n\nconst notFound = (entity: Reason.NotFound[\"entity\"], id: string) =>\n fail(new Reason.NotFound({ entity, id }));\n\nconst invalid = (message: string, field?: string) =>\n fail(new Reason.InvalidInput({ message, ...(field === undefined ? {} : { field }) }));\n\nconst busy = (key: string) => fail(new Reason.Busy({ key }));\n\nconst storageFailed = (operation: string, message: string) =>\n new DomainKit.Error({\n reason: new Reason.StorageFailed({ operation, message }),\n });\n\nconst sqlMessage = (error: SqlError.SqlError): string =>\n error.reason.cause instanceof Error\n ? `${error.reason._tag}: ${error.reason.cause.message}`\n : `${error.reason._tag}: ${String(error.reason.cause)}`;\n\n/**\n * Collapse the SQL error channel into `DomainKit.Error`.\n *\n * A `DomainKit.Error` raised by the body is the deliberate outcome of an invariant and passes\n * through unchanged; anything else is a driver failure and becomes `StorageFailed`.\n */\nconst guard =\n (operation: string) =>\n <A, R>(effect: Effect.Effect<A, SqlError.SqlError | Fail, R>): Effect.Effect<A, Fail, R> =>\n Effect.catch(effect, (error) =>\n Effect.fail(DomainKit.isError(error) ? error : storageFailed(operation, sqlMessage(error))),\n );\n\n// ---------------------------------------------------------------------------------------------\n// Row codecs\n// ---------------------------------------------------------------------------------------------\n\n/**\n * A row is stored as its schema's encoded form spread over columns, so the core schema stays the\n * only description of a row's shape. Reading reassembles the encoded object and decodes it.\n */\nconst codec = <S extends Schema.ConstraintCodec<unknown, unknown>>(schema: S, subject: string) => {\n const decode = Schema.decodeUnknownEffect(schema);\n const encode = Schema.encodeUnknownEffect(schema);\n return {\n read: (input: unknown): Effect.Effect<S[\"Type\"], Fail, S[\"DecodingServices\"]> =>\n decode(input).pipe(\n Effect.mapError((error) =>\n storageFailed(`${subject}.decode`, `stored ${subject} is invalid: ${error.message}`),\n ),\n ),\n write: (value: S[\"Type\"]): Effect.Effect<S[\"Encoded\"], Fail, S[\"EncodingServices\"]> =>\n encode(value).pipe(\n Effect.mapError((error) =>\n storageFailed(`${subject}.encode`, `${subject} cannot be stored: ${error.message}`),\n ),\n ),\n };\n};\n\nconst authorizationCodec = codec(Storage.Authorization, \"authorization\");\nconst connectionCodec = codec(Storage.Connection, \"connection\");\nconst attachmentCodec = codec(Storage.Attachment, \"attachment\");\nconst continuationCodec = codec(Storage.Continuation, \"continuation\");\nconst attemptCodec = codec(Storage.Attempt, \"attempt\");\nconst readinessCodec = codec(Storage.Readiness, \"readiness\");\nconst credentialCodec = codec(Storage.Credential, \"credential\");\n\n// ---------------------------------------------------------------------------------------------\n// Column conversions\n// ---------------------------------------------------------------------------------------------\n\n/** A `TIMESTAMPTZ` column as the ISO string every DomainKit timestamp schema encodes to. */\nconst iso = (value: unknown): string =>\n value instanceof Date ? value.toISOString() : String(value);\n\nconst isoOrNull = (value: unknown): string | null => (value === null ? null : iso(value));\n\n/** An ISO string from a schema's encoded form as the `Date` the driver binds to `TIMESTAMPTZ`. */\nconst at = (value: string): Date => new Date(value);\n\nconst atOrNull = (value: string | null): Date | null => (value === null ? null : at(value));\n\nconst now = Effect.map(DateTime.now, DateTime.toDateUtc);\n\n/**\n * A `JSONB` column as a plain value.\n *\n * Drivers disagree about whether they parse JSON columns, so accept both and normalize here\n * rather than depending on a host's client configuration.\n */\nconst fromJson = (value: unknown): unknown =>\n typeof value === \"string\" ? (JSON.parse(value) as unknown) : value;\n\nconst fromJsonOrNull = (value: unknown): unknown => (value === null ? null : fromJson(value));\n\n/** Bind a value to a `JSONB` column as text; PostgreSQL coerces the untyped parameter. */\nconst toJson = (value: unknown): string => JSON.stringify(value ?? null);\n\nconst toJsonOrNull = (value: unknown): string | null =>\n value === null || value === undefined ? null : toJson(value);\n\n// ---------------------------------------------------------------------------------------------\n// Row shapes\n// ---------------------------------------------------------------------------------------------\n\ninterface AuthorizationRow {\n readonly id: string;\n readonly owner_id: string;\n readonly provider: string;\n readonly method: string;\n readonly capabilities: unknown;\n readonly context: unknown;\n readonly revocation: string;\n readonly created_by: string;\n readonly created_at: unknown;\n readonly credential_ciphertext: string;\n readonly credential_expires_at: unknown;\n readonly credential_rotated_at: unknown;\n}\n\ninterface ConnectionRow {\n readonly id: string;\n readonly owner_id: string;\n readonly authorization_id: string;\n readonly created_at: unknown;\n}\n\ninterface AttachmentRow {\n readonly id: string;\n readonly owner_id: string;\n readonly connection_id: string;\n readonly domain: string;\n readonly zone: string;\n readonly target: unknown;\n readonly created_at: unknown;\n}\n\ninterface ContinuationRow {\n readonly id: string;\n readonly owner_id: string;\n readonly actor_id: string;\n readonly provider: string;\n readonly payload: unknown;\n readonly return_to: string | null;\n readonly expires_at: unknown;\n}\n\ninterface AttemptRow {\n readonly id: string;\n readonly owner_id: string;\n readonly attachment_id: string;\n readonly kind: string;\n readonly status: string;\n readonly plan: unknown;\n readonly approval: unknown;\n readonly receipt: unknown;\n readonly rejection: unknown;\n readonly source_receipt_id: string | null;\n readonly lease_expires_at: unknown;\n readonly failure: string | null;\n readonly updated_at: unknown;\n}\n\ninterface ReadinessRow {\n readonly owner_id: string;\n readonly domain: string;\n readonly attachment_id: string | null;\n readonly overall: string;\n readonly requirements: unknown;\n readonly host: unknown;\n readonly pending_since: unknown;\n readonly checked_at: unknown;\n readonly next_check_at: unknown;\n}\n\nconst authorizationOf = (row: AuthorizationRow) =>\n authorizationCodec.read({\n id: row.id,\n ownerId: row.owner_id,\n provider: row.provider,\n method: row.method,\n capabilities: fromJson(row.capabilities),\n context: fromJson(row.context),\n revocation: row.revocation,\n createdBy: row.created_by,\n createdAt: iso(row.created_at),\n });\n\nconst credentialOf = (row: AuthorizationRow) =>\n credentialCodec.read({\n ciphertext: row.credential_ciphertext,\n expiresAt: isoOrNull(row.credential_expires_at),\n rotatedAt: iso(row.credential_rotated_at),\n });\n\nconst connectionOf = (row: ConnectionRow) =>\n connectionCodec.read({\n id: row.id,\n ownerId: row.owner_id,\n authorizationId: row.authorization_id,\n createdAt: iso(row.created_at),\n });\n\nconst attachmentOf = (row: AttachmentRow) =>\n attachmentCodec.read({\n id: row.id,\n ownerId: row.owner_id,\n connectionId: row.connection_id,\n domain: row.domain,\n zone: row.zone,\n target: fromJson(row.target),\n createdAt: iso(row.created_at),\n });\n\nconst continuationOf = (row: ContinuationRow) =>\n continuationCodec.read({\n id: row.id,\n ownerId: row.owner_id,\n actorId: row.actor_id,\n provider: row.provider,\n payload: fromJson(row.payload),\n returnTo: row.return_to,\n expiresAt: iso(row.expires_at),\n });\n\nconst attemptOf = (row: AttemptRow) =>\n attemptCodec.read({\n id: row.id,\n ownerId: row.owner_id,\n attachmentId: row.attachment_id,\n kind: row.kind,\n status: row.status,\n plan: fromJson(row.plan),\n approval: fromJsonOrNull(row.approval),\n receipt: fromJsonOrNull(row.receipt),\n rejection: fromJsonOrNull(row.rejection),\n sourceReceiptId: row.source_receipt_id,\n leaseExpiresAt: isoOrNull(row.lease_expires_at),\n failure: row.failure,\n updatedAt: iso(row.updated_at),\n });\n\nconst readinessOf = (row: ReadinessRow) =>\n readinessCodec.read({\n domain: row.domain,\n attachmentId: row.attachment_id,\n ownerId: row.owner_id,\n overall: row.overall,\n requirements: fromJson(row.requirements),\n host: fromJson(row.host),\n pendingSince: isoOrNull(row.pending_since),\n checkedAt: iso(row.checked_at),\n nextCheckAt: isoOrNull(row.next_check_at),\n });\n\nconst stale = (attempt: Storage.Attempt) =>\n fail(new Reason.Stale({ planId: attempt.id, digest: attempt.plan.digest }));\n\n/** `prefix_<uuid>`, the same identifier shape the memory implementation mints. */\nconst fresh = (prefix: string) => Effect.sync(() => `${prefix}_${crypto.randomUUID()}`);\n\n// ---------------------------------------------------------------------------------------------\n// Service\n// ---------------------------------------------------------------------------------------------\n\nexport const make = (\n tables: Tables,\n): Effect.Effect<Storage.Interface, never, SqlClient.SqlClient> =>\n Effect.gen(function* () {\n const client = yield* SqlClient.SqlClient;\n // A host may configure result-name transforms for its own tables; these queries read the exact\n // snake_case columns the capsule declared.\n const sql = client.withoutTransforms();\n\n const authorizations = sql(tables.authorizations.name);\n const connections = sql(tables.connections.name);\n const attachments = sql(tables.attachments.name);\n const continuations = sql(tables.continuations.name);\n const attempts = sql(tables.attempts.name);\n const readiness = sql(tables.readiness.name);\n\n /** The row this principal owns, locked for the rest of the transaction. */\n const lockedAuthorization = (owner: string, id: string) =>\n sql<AuthorizationRow>`\n SELECT * FROM ${authorizations} WHERE id = ${id} AND owner_id = ${owner} FOR UPDATE\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"authorization\", id) : Effect.succeed(rows[0]),\n ),\n );\n\n const lockedAttempt = (owner: string, id: string) =>\n sql<AttemptRow>`\n SELECT * FROM ${attempts} WHERE id = ${id} AND owner_id = ${owner} FOR UPDATE\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"plan\", id) : Effect.succeed(rows[0]),\n ),\n Effect.flatMap(attemptOf),\n );\n\n const requireConnection = (owner: string, id: string) =>\n sql<ConnectionRow>`\n SELECT * FROM ${connections} WHERE id = ${id} AND owner_id = ${owner}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"connection\", id) : Effect.succeed(rows[0]),\n ),\n );\n\n const requireAttachment = (owner: string, id: string) =>\n sql<AttachmentRow>`\n SELECT * FROM ${attachments} WHERE id = ${id} AND owner_id = ${owner}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"attachment\", id) : Effect.succeed(rows[0]),\n ),\n );\n\n const writeAuthorization = (\n authorization: Storage.Authorization,\n credential: Storage.Credential,\n ) =>\n Effect.all({\n row: authorizationCodec.write(authorization),\n secret: credentialCodec.write(credential),\n });\n\n /**\n * Phase one of revocation: mark the row `pending` so a crash between the provider call and the\n * delete is recoverable. Idempotent, and it never widens the row's state.\n *\n * Returns the ciphertext the caller is about to have revoked, which phase two checks.\n */\n const prepareRevocation = (owner: string, id: string) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const row = yield* lockedAuthorization(owner, id);\n yield* sql`\n UPDATE ${authorizations} SET revocation = 'pending', updated_at = ${yield* now}\n WHERE id = ${id} AND owner_id = ${owner}\n `;\n return row.credential_ciphertext;\n }),\n );\n\n /**\n * Phase two: delete the row, but only while it still holds the credential the provider was\n * asked to revoke.\n *\n * A credential refresh runs concurrently with revocation and rotates the row after the provider\n * call selected the old ciphertext. Deleting unconditionally would drop the row while the newly\n * issued credential is still live at the provider, with no local state left to revoke it from.\n * Leaving the row `pending` instead hands it to `recoverRevocations`, which revokes what the\n * row now holds. Every ciphertext is AES-GCM with a fresh IV, so equality here is exact.\n */\n const completeRevocation = (owner: string, id: string, ciphertext: string) =>\n sql`\n DELETE FROM ${authorizations}\n WHERE id = ${id} AND owner_id = ${owner} AND credential_ciphertext = ${ciphertext}\n `;\n\n const service: Storage.Interface = {\n authorizations: {\n upsert: ({ authorization, credential, expectedId }) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n if (authorization.ownerId !== ownerId) {\n return yield* invalid(\n \"Authorization owner does not match the principal\",\n \"ownerId\",\n );\n }\n const { row, secret } = yield* writeAuthorization(authorization, credential);\n const stamp = yield* now;\n return yield* sql.withTransaction(\n Effect.gen(function* () {\n if (expectedId !== undefined) {\n const current = yield* lockedAuthorization(ownerId, expectedId);\n if (current.revocation !== \"active\") {\n return yield* busy(`authorization:${expectedId}`);\n }\n if (authorization.id !== expectedId) {\n return yield* invalid(\"Authorization id must match expectedId\", \"id\");\n }\n // A replace overwrites every column the caller supplied, including `created_at`:\n // the row it returns has to be the row a later `get` reads back.\n yield* sql`\n UPDATE ${authorizations} SET\n provider = ${row.provider},\n method = ${row.method},\n capabilities = ${toJson(row.capabilities)},\n context = ${toJson(row.context)},\n revocation = ${row.revocation},\n created_by = ${row.createdBy},\n created_at = ${at(row.createdAt)},\n credential_ciphertext = ${secret.ciphertext},\n credential_expires_at = ${atOrNull(secret.expiresAt)},\n credential_rotated_at = ${at(secret.rotatedAt)},\n updated_at = ${stamp}\n WHERE id = ${expectedId} AND owner_id = ${ownerId}\n `;\n return authorization;\n }\n // An id already taken by any tenant is a caller defect, not a missing row, so the\n // insert claims it atomically instead of racing a prior existence check.\n const inserted = yield* sql<{ readonly id: string }>`\n INSERT INTO ${authorizations} (\n id, owner_id, provider, method, capabilities, context, revocation,\n created_by, created_at, credential_ciphertext, credential_expires_at,\n credential_rotated_at, updated_at\n ) VALUES (\n ${row.id}, ${row.ownerId}, ${row.provider}, ${row.method},\n ${toJson(row.capabilities)}, ${toJson(row.context)}, ${row.revocation},\n ${row.createdBy}, ${at(row.createdAt)}, ${secret.ciphertext},\n ${atOrNull(secret.expiresAt)}, ${at(secret.rotatedAt)}, ${stamp}\n ) ON CONFLICT (id) DO NOTHING RETURNING id\n `;\n return inserted[0] === undefined\n ? yield* invalid(`Authorization ${authorization.id} already exists`, \"id\")\n : authorization;\n }),\n );\n }),\n ).pipe(guard(\"authorizations.upsert\")),\n get: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AuthorizationRow>`\n SELECT * FROM ${authorizations} WHERE id = ${id} AND owner_id = ${ownerId}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"authorization\", id) : authorizationOf(rows[0]),\n ),\n ),\n ).pipe(guard(\"authorizations.get\")),\n credential: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AuthorizationRow>`\n SELECT * FROM ${authorizations} WHERE id = ${id} AND owner_id = ${ownerId}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"authorization\", id) : credentialOf(rows[0]),\n ),\n ),\n ).pipe(guard(\"authorizations.credential\")),\n rotate: (id, credential) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n const secret = yield* credentialCodec.write(credential);\n const updated = yield* sql<{ readonly id: string }>`\n UPDATE ${authorizations} SET\n credential_ciphertext = ${secret.ciphertext},\n credential_expires_at = ${atOrNull(secret.expiresAt)},\n credential_rotated_at = ${at(secret.rotatedAt)},\n updated_at = ${yield* now}\n WHERE id = ${id} AND owner_id = ${ownerId} RETURNING id\n `;\n if (updated[0] === undefined) return yield* notFound(\"authorization\", id);\n }),\n ).pipe(guard(\"authorizations.rotate\")),\n promoteCapabilities: (id, capabilities) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const current = yield* authorizationOf(yield* lockedAuthorization(ownerId, id));\n const merged = [...new Set([...current.capabilities, ...capabilities])];\n yield* sql`\n UPDATE ${authorizations}\n SET capabilities = ${toJson(merged)}, updated_at = ${yield* now}\n WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n }),\n ),\n ).pipe(guard(\"authorizations.promoteCapabilities\")),\n revoke: (id, revoke) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n const ciphertext = yield* prepareRevocation(ownerId, id).pipe(\n guard(\"authorizations.revoke\"),\n );\n yield* revoke;\n yield* completeRevocation(ownerId, id, ciphertext).pipe(\n guard(\"authorizations.completeRevocation\"),\n );\n }),\n ),\n recoverRevocations: (revoke) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n const rows = yield* sql<AuthorizationRow>`\n SELECT * FROM ${authorizations}\n WHERE owner_id = ${ownerId} AND revocation = 'pending'\n ORDER BY created_at\n `.pipe(guard(\"authorizations.pendingRevocations\"));\n yield* Effect.forEach(rows, (row) =>\n Effect.gen(function* () {\n yield* revoke(yield* authorizationOf(row));\n yield* completeRevocation(ownerId, row.id, row.credential_ciphertext).pipe(\n guard(\"authorizations.completeRevocation\"),\n );\n }),\n );\n return rows.length;\n }),\n ),\n },\n connections: {\n create: (authorizationId) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n yield* lockedAuthorization(ownerId, authorizationId);\n const row = new Storage.Connection({\n id: yield* fresh(\"conn\"),\n ownerId,\n authorizationId,\n createdAt: yield* DateTime.now,\n });\n const encoded = yield* connectionCodec.write(row);\n yield* sql`\n INSERT INTO ${connections} (id, owner_id, authorization_id, created_at)\n VALUES (${encoded.id}, ${encoded.ownerId}, ${encoded.authorizationId},\n ${at(encoded.createdAt)})\n `;\n return row;\n }),\n ),\n ).pipe(guard(\"connections.create\")),\n get: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.flatMap(requireConnection(ownerId, id), connectionOf),\n ).pipe(guard(\"connections.get\")),\n list: (filter) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.flatMap(\n filter?.provider === undefined\n ? sql<ConnectionRow>`\n SELECT * FROM ${connections} WHERE owner_id = ${ownerId} ORDER BY created_at\n `\n : sql<ConnectionRow>`\n SELECT c.* FROM ${connections} AS c\n JOIN ${authorizations} AS a ON a.id = c.authorization_id\n WHERE c.owner_id = ${ownerId} AND a.provider = ${filter.provider}\n ORDER BY c.created_at\n `,\n (rows) => Effect.forEach(rows, connectionOf),\n ),\n ).pipe(guard(\"connections.list\")),\n remove: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const rows = yield* sql<ConnectionRow>`\n SELECT * FROM ${connections}\n WHERE id = ${id} AND owner_id = ${ownerId} FOR UPDATE\n `;\n if (rows[0] === undefined) return yield* notFound(\"connection\", id);\n const held = yield* sql<{ readonly id: string }>`\n SELECT id FROM ${attachments}\n WHERE connection_id = ${id} AND owner_id = ${ownerId} LIMIT 1\n `;\n if (held[0] !== undefined) {\n return yield* invalid(`Connection ${id} still has attachments`, \"connectionId\");\n }\n yield* sql`DELETE FROM ${connections} WHERE id = ${id} AND owner_id = ${ownerId}`;\n }),\n ),\n ).pipe(guard(\"connections.remove\")),\n },\n attachments: {\n create: (input) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n yield* requireConnection(ownerId, input.connectionId);\n const row = new Storage.Attachment({\n id: yield* fresh(\"att\"),\n ownerId,\n connectionId: input.connectionId,\n domain: input.domain,\n zone: input.zone,\n target: input.target,\n createdAt: yield* DateTime.now,\n });\n const encoded = yield* attachmentCodec.write(row);\n // The unique (owner_id, domain) constraint decides the duplicate, so two concurrent\n // attaches cannot both win.\n const inserted = yield* sql<{ readonly id: string }>`\n INSERT INTO ${attachments} (\n id, owner_id, connection_id, domain, zone, target, created_at\n ) VALUES (\n ${encoded.id}, ${encoded.ownerId}, ${encoded.connectionId}, ${encoded.domain},\n ${encoded.zone}, ${toJson(encoded.target)}, ${at(encoded.createdAt)}\n ) ON CONFLICT (owner_id, domain) DO NOTHING RETURNING id\n `;\n return inserted[0] === undefined\n ? yield* invalid(`${input.domain} is already attached`, \"domain\")\n : row;\n }),\n ),\n ).pipe(guard(\"attachments.create\")),\n get: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.flatMap(requireAttachment(ownerId, id), attachmentOf),\n ).pipe(guard(\"attachments.get\")),\n byDomain: (domain) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AttachmentRow>`\n SELECT * FROM ${attachments} WHERE owner_id = ${ownerId} AND domain = ${domain}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined\n ? Effect.succeedNone\n : Effect.map(attachmentOf(rows[0]), Option.some),\n ),\n ),\n ).pipe(guard(\"attachments.byDomain\")),\n list: (connectionId) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n yield* requireConnection(ownerId, connectionId);\n const rows = yield* sql<AttachmentRow>`\n SELECT * FROM ${attachments}\n WHERE owner_id = ${ownerId} AND connection_id = ${connectionId}\n ORDER BY created_at\n `;\n return yield* Effect.forEach(rows, attachmentOf);\n }),\n ).pipe(guard(\"attachments.list\")),\n remove: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n yield* requireAttachment(ownerId, id);\n // Readiness is keyed by domain and outlives the attachment, so clear the link\n // rather than the row: what was observed about the domain is still true, and a\n // dangling attachment id would fail the next `readiness.put`.\n yield* sql`\n UPDATE ${readiness} SET attachment_id = NULL\n WHERE attachment_id = ${id} AND owner_id = ${ownerId}\n `;\n yield* sql`DELETE FROM ${attachments} WHERE id = ${id} AND owner_id = ${ownerId}`;\n }),\n ),\n ).pipe(guard(\"attachments.remove\")),\n },\n continuations: {\n put: (continuation) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n if (continuation.ownerId !== ownerId) {\n return yield* invalid(\"Continuation owner does not match the principal\", \"ownerId\");\n }\n const encoded = yield* continuationCodec.write(continuation);\n yield* sql`\n INSERT INTO ${continuations} (\n id, owner_id, actor_id, provider, payload, return_to, expires_at\n ) VALUES (\n ${encoded.id}, ${encoded.ownerId}, ${encoded.actorId}, ${encoded.provider},\n ${toJson(encoded.payload)}, ${encoded.returnTo}, ${at(encoded.expiresAt)}\n ) ON CONFLICT (id) DO UPDATE SET\n owner_id = EXCLUDED.owner_id,\n actor_id = EXCLUDED.actor_id,\n provider = EXCLUDED.provider,\n payload = EXCLUDED.payload,\n return_to = EXCLUDED.return_to,\n expires_at = EXCLUDED.expires_at\n `;\n }),\n ).pipe(guard(\"continuations.put\")),\n get: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n // A read, not a claim: the row survives so `consume` can still spend it.\n const rows = yield* sql<ContinuationRow>`\n SELECT * FROM ${continuations} WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n if (rows[0] === undefined) return yield* notFound(\"continuation\", id);\n const continuation = yield* continuationOf(rows[0]);\n const instant = yield* DateTime.now;\n return DateTime.toEpochMillis(continuation.expiresAt) <=\n DateTime.toEpochMillis(instant)\n ? yield* fail(new Reason.Expired({ entity: \"continuation\", id }))\n : continuation;\n }),\n ).pipe(guard(\"continuations.get\")),\n consume: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n // The delete is the claim: a second consume finds nothing, expired or not.\n const rows = yield* sql<ContinuationRow>`\n DELETE FROM ${continuations}\n WHERE id = ${id} AND owner_id = ${ownerId} RETURNING *\n `;\n if (rows[0] === undefined) return yield* notFound(\"continuation\", id);\n const continuation = yield* continuationOf(rows[0]);\n const instant = yield* DateTime.now;\n return DateTime.toEpochMillis(continuation.expiresAt) <=\n DateTime.toEpochMillis(instant)\n ? yield* fail(new Reason.Expired({ entity: \"continuation\", id }))\n : continuation;\n }),\n ).pipe(guard(\"continuations.consume\")),\n },\n attempts: {\n create: (attempt) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n if (attempt.ownerId !== ownerId) {\n return yield* invalid(\"Attempt owner does not match the principal\", \"ownerId\");\n }\n const encoded = yield* attemptCodec.write(attempt);\n const inserted = yield* sql<{ readonly id: string }>`\n INSERT INTO ${attempts} (\n id, owner_id, attachment_id, kind, status, plan, approval, approval_id,\n receipt, receipt_id, rejection, source_receipt_id, lease_expires_at, failure,\n plan_created_at, updated_at\n ) VALUES (\n ${encoded.id}, ${encoded.ownerId}, ${encoded.attachmentId}, ${encoded.kind},\n ${encoded.status}, ${toJson(encoded.plan)}, ${toJsonOrNull(encoded.approval)},\n ${attempt.approval?.id ?? null}, ${toJsonOrNull(encoded.receipt)},\n ${attempt.receipt?.id ?? null}, ${toJsonOrNull(encoded.rejection)},\n ${encoded.sourceReceiptId},\n ${atOrNull(encoded.leaseExpiresAt)}, ${encoded.failure},\n ${at(encoded.plan.createdAt)}, ${at(encoded.updatedAt)}\n ) ON CONFLICT (id) DO NOTHING RETURNING id\n `;\n return inserted[0] === undefined\n ? yield* invalid(`Plan ${attempt.id} already exists`, \"id\")\n : attempt;\n }),\n ).pipe(guard(\"attempts.create\")),\n get: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AttemptRow>`\n SELECT * FROM ${attempts} WHERE id = ${id} AND owner_id = ${ownerId}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"plan\", id) : attemptOf(rows[0]),\n ),\n ),\n ).pipe(guard(\"attempts.get\")),\n byApproval: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AttemptRow>`\n SELECT * FROM ${attempts} WHERE approval_id = ${id} AND owner_id = ${ownerId}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"approval\", id) : attemptOf(rows[0]),\n ),\n ),\n ).pipe(guard(\"attempts.byApproval\")),\n byReceipt: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AttemptRow>`\n SELECT * FROM ${attempts} WHERE receipt_id = ${id} AND owner_id = ${ownerId}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"receipt\", id) : attemptOf(rows[0]),\n ),\n ),\n ).pipe(guard(\"attempts.byReceipt\")),\n latest: (attachmentId, kind) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AttemptRow>`\n SELECT * FROM ${attempts}\n WHERE owner_id = ${ownerId} AND attachment_id = ${attachmentId} AND kind = ${kind}\n ORDER BY plan_created_at DESC, updated_at DESC LIMIT 1\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined\n ? Effect.succeedNone\n : Effect.map(attemptOf(rows[0]), Option.some),\n ),\n ),\n ).pipe(guard(\"attempts.latest\")),\n approve: (id, approval) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const current = yield* lockedAttempt(ownerId, id);\n // Replaying the same approval is how a retried request stays safe.\n if (current.approval?.id === approval.id) return current;\n if (current.status !== \"planned\") return yield* stale(current);\n const next = new Storage.Attempt({\n ...current,\n status: \"approved\",\n approval,\n updatedAt: yield* DateTime.now,\n });\n const encoded = yield* attemptCodec.write(next);\n yield* sql`\n UPDATE ${attempts} SET\n status = ${encoded.status},\n approval = ${toJsonOrNull(encoded.approval)},\n approval_id = ${approval.id},\n updated_at = ${at(encoded.updatedAt)}\n WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n return next;\n }),\n ),\n ).pipe(guard(\"attempts.approve\")),\n reject: (id, input) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const current = yield* lockedAttempt(ownerId, id);\n // Terminal: a second rejection is the same outcome, so it returns the first one.\n if (current.status === \"rejected\") return current;\n if (current.status === \"expired\") {\n return yield* fail(new Reason.Expired({ entity: \"plan\", id }));\n }\n // A digest mismatch means the reviewer declined a plan that is no longer current.\n if (current.status !== \"planned\" || current.plan.digest !== input.digest) {\n return yield* stale(current);\n }\n const instant = yield* DateTime.now;\n const next = new Storage.Attempt({\n ...current,\n status: \"rejected\",\n rejection: { actorId: input.actorId, reason: input.reason, at: instant },\n updatedAt: instant,\n });\n const encoded = yield* attemptCodec.write(next);\n yield* sql`\n UPDATE ${attempts} SET\n status = ${encoded.status},\n rejection = ${toJsonOrNull(encoded.rejection)},\n updated_at = ${at(encoded.updatedAt)}\n WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n return next;\n }),\n ),\n ).pipe(guard(\"attempts.reject\")),\n claim: (id, lease) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const current = yield* lockedAttempt(ownerId, id);\n const instant = yield* DateTime.now;\n if (current.status === \"applying\") {\n const held =\n current.leaseExpiresAt !== null &&\n DateTime.toEpochMillis(current.leaseExpiresAt) >\n DateTime.toEpochMillis(instant);\n if (held) return yield* busy(`apply:${id}`);\n } else if (current.status !== \"approved\" && current.status !== \"failed\") {\n return yield* stale(current);\n }\n const next = new Storage.Attempt({\n ...current,\n status: \"applying\",\n leaseExpiresAt: lease,\n failure: null,\n updatedAt: instant,\n });\n const encoded = yield* attemptCodec.write(next);\n yield* sql`\n UPDATE ${attempts} SET\n status = ${encoded.status},\n lease_expires_at = ${atOrNull(encoded.leaseExpiresAt)},\n failure = NULL,\n updated_at = ${at(encoded.updatedAt)}\n WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n return next;\n }),\n ),\n ).pipe(guard(\"attempts.claim\")),\n complete: (id, receipt) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const current = yield* lockedAttempt(ownerId, id);\n if (current.status !== \"applying\") return yield* stale(current);\n const next = new Storage.Attempt({\n ...current,\n status: receipt.status,\n receipt,\n leaseExpiresAt: null,\n updatedAt: yield* DateTime.now,\n });\n const encoded = yield* attemptCodec.write(next);\n yield* sql`\n UPDATE ${attempts} SET\n status = ${encoded.status},\n receipt = ${toJsonOrNull(encoded.receipt)},\n receipt_id = ${receipt.id},\n lease_expires_at = NULL,\n updated_at = ${at(encoded.updatedAt)}\n WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n return next;\n }),\n ),\n ).pipe(guard(\"attempts.complete\")),\n fail: (id, message) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const current = yield* lockedAttempt(ownerId, id);\n if (current.status !== \"applying\") return yield* stale(current);\n const next = new Storage.Attempt({\n ...current,\n status: \"failed\",\n failure: message,\n leaseExpiresAt: null,\n updatedAt: yield* DateTime.now,\n });\n const encoded = yield* attemptCodec.write(next);\n yield* sql`\n UPDATE ${attempts} SET\n status = ${encoded.status},\n failure = ${message},\n lease_expires_at = NULL,\n updated_at = ${at(encoded.updatedAt)}\n WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n return next;\n }),\n ),\n ).pipe(guard(\"attempts.fail\")),\n },\n readiness: {\n put: (row) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n if (row.ownerId !== ownerId) {\n return yield* invalid(\"Readiness owner does not match the principal\", \"ownerId\");\n }\n // A linked attachment has to exist for this owner; observe-only readiness has none.\n if (row.attachmentId !== null) yield* requireAttachment(ownerId, row.attachmentId);\n const encoded = yield* readinessCodec.write(row);\n yield* sql`\n INSERT INTO ${readiness} (\n owner_id, domain, attachment_id, overall, requirements, host, pending_since,\n checked_at, next_check_at\n ) VALUES (\n ${encoded.ownerId}, ${encoded.domain}, ${encoded.attachmentId},\n ${encoded.overall}, ${toJson(encoded.requirements)}, ${toJson(encoded.host)},\n ${atOrNull(encoded.pendingSince)}, ${at(encoded.checkedAt)},\n ${atOrNull(encoded.nextCheckAt)}\n ) ON CONFLICT (owner_id, domain) DO UPDATE SET\n attachment_id = EXCLUDED.attachment_id,\n overall = EXCLUDED.overall,\n requirements = EXCLUDED.requirements,\n host = EXCLUDED.host,\n pending_since = EXCLUDED.pending_since,\n checked_at = EXCLUDED.checked_at,\n next_check_at = EXCLUDED.next_check_at\n `;\n }),\n ).pipe(guard(\"readiness.put\")),\n get: (domain) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<ReadinessRow>`\n SELECT * FROM ${readiness}\n WHERE owner_id = ${ownerId} AND domain = ${domain}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined\n ? Effect.succeedNone\n : Effect.map(readinessOf(rows[0]), Option.some),\n ),\n ),\n ).pipe(guard(\"readiness.get\")),\n },\n withLock: (key, effect) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.scoped(\n Effect.gen(function* () {\n // A session lock, not a transaction lock: the guarded effect refreshes a credential\n // against the provider, and no transaction should stay open across an HTTP call.\n // `reserve` pins one pooled connection so the unlock runs on the session that took\n // the lock, and registering it after the connection makes it run first on release.\n const connection = yield* Effect.mapError(sql.reserve, (error) =>\n storageFailed(\"withLock\", sqlMessage(error)),\n );\n const scoped = `${ownerId}:${key}`;\n yield* Effect.acquireRelease(\n connection\n .execute(\n \"SELECT pg_try_advisory_lock(hashtextextended($1, 0)) AS acquired\",\n [scoped],\n undefined,\n )\n .pipe(\n Effect.mapError((error: SqlError.SqlError) =>\n storageFailed(\"withLock\", sqlMessage(error)),\n ),\n Effect.flatMap((rows: ReadonlyArray<{ readonly acquired: boolean }>) =>\n rows[0]?.acquired === true ? Effect.void : busy(key),\n ),\n ),\n () =>\n connection\n .execute(\n \"SELECT pg_advisory_unlock(hashtextextended($1, 0))\",\n [scoped],\n undefined,\n )\n .pipe(Effect.ignore),\n );\n return yield* effect;\n }),\n ),\n ),\n };\n\n return service;\n });\n","/**\n * The six tables DomainKit owns, declared once and rendered per dialect by CapsuleDB.\n *\n * Every table carries `owner_id` and every query filters by it: tenancy is a column, not a schema.\n * There are no foreign keys to host tables, and none between DomainKit's own tables either, so a\n * host can add its own in the emitted migration without fighting a constraint the package owns.\n */\nimport { Schema } from \"capsuledb\";\n\nexport interface Tables {\n readonly authorizations: Schema.Table;\n readonly connections: Schema.Table;\n readonly attachments: Schema.Table;\n readonly continuations: Schema.Table;\n readonly attempts: Schema.Table;\n readonly readiness: Schema.Table;\n}\n\n/** Default table prefix. Part of the physical layout, so it is immutable after the first deploy. */\nexport const DEFAULT_PREFIX = \"domainkit\";\n\n/**\n * Declare the six tables under `prefix`.\n *\n * `Schema.table` validates every identifier it will quote, so an invalid prefix throws\n * `CapsuleDefinitionError` here rather than reaching a renderer.\n */\nexport const make = (prefix: string): Tables => ({\n authorizations: Schema.table(`${prefix}_authorizations`, {\n columns: {\n id: Schema.text(),\n owner_id: Schema.text(),\n provider: Schema.text(),\n method: Schema.text(),\n capabilities: Schema.json(),\n context: Schema.json(),\n revocation: Schema.text(),\n created_by: Schema.text(),\n created_at: Schema.timestamp(),\n credential_ciphertext: Schema.text(),\n credential_expires_at: Schema.timestamp({ nullable: true }),\n credential_rotated_at: Schema.timestamp(),\n updated_at: Schema.timestamp(),\n },\n primaryKey: [\"id\"],\n indexes: [{ columns: [\"owner_id\", \"revocation\"] }, { columns: [\"owner_id\", \"provider\"] }],\n }),\n connections: Schema.table(`${prefix}_connections`, {\n columns: {\n id: Schema.text(),\n owner_id: Schema.text(),\n authorization_id: Schema.text(),\n created_at: Schema.timestamp(),\n },\n primaryKey: [\"id\"],\n indexes: [{ columns: [\"owner_id\"] }, { columns: [\"authorization_id\"] }],\n }),\n attachments: Schema.table(`${prefix}_attachments`, {\n columns: {\n id: Schema.text(),\n owner_id: Schema.text(),\n connection_id: Schema.text(),\n domain: Schema.text(),\n zone: Schema.text(),\n target: Schema.json(),\n created_at: Schema.timestamp(),\n },\n primaryKey: [\"id\"],\n // One attachment per domain per tenant; `attachments.create` reads the conflict as InvalidInput.\n uniques: [[\"owner_id\", \"domain\"]],\n indexes: [{ columns: [\"owner_id\", \"connection_id\"] }],\n }),\n continuations: Schema.table(`${prefix}_continuations`, {\n columns: {\n id: Schema.text(),\n owner_id: Schema.text(),\n actor_id: Schema.text(),\n provider: Schema.text(),\n payload: Schema.json(),\n return_to: Schema.text({ nullable: true }),\n expires_at: Schema.timestamp(),\n },\n primaryKey: [\"id\"],\n // Hosts sweep expired rows on this index; consume deletes the row it returns.\n indexes: [{ columns: [\"expires_at\"] }],\n }),\n attempts: Schema.table(`${prefix}_attempts`, {\n columns: {\n id: Schema.text(),\n owner_id: Schema.text(),\n attachment_id: Schema.text(),\n kind: Schema.text(),\n status: Schema.text(),\n plan: Schema.json(),\n approval: Schema.json({ nullable: true }),\n /** Denormalized from `approval` so `byApproval` is an index lookup. */\n approval_id: Schema.text({ nullable: true }),\n receipt: Schema.json({ nullable: true }),\n /** Denormalized from `receipt` so `byReceipt` is an index lookup. */\n receipt_id: Schema.text({ nullable: true }),\n /** Who declined the plan, why, and when; set when an attempt reaches `rejected`. */\n rejection: Schema.json({ nullable: true }),\n source_receipt_id: Schema.text({ nullable: true }),\n lease_expires_at: Schema.timestamp({ nullable: true }),\n failure: Schema.text({ nullable: true }),\n /** The plan's own `createdAt`; `latest` orders by it. */\n plan_created_at: Schema.timestamp(),\n updated_at: Schema.timestamp(),\n },\n primaryKey: [\"id\"],\n indexes: [\n { columns: [\"owner_id\", \"attachment_id\", \"kind\"] },\n { columns: [\"owner_id\", \"approval_id\"] },\n { columns: [\"owner_id\", \"receipt_id\"] },\n ],\n }),\n readiness: Schema.table(`${prefix}_readiness`, {\n columns: {\n owner_id: Schema.text(),\n domain: Schema.text(),\n /** Set while an attachment covers the domain; observe-only readiness leaves it null. */\n attachment_id: Schema.text({ nullable: true }),\n overall: Schema.text(),\n requirements: Schema.json(),\n host: Schema.json(),\n pending_since: Schema.timestamp({ nullable: true }),\n checked_at: Schema.timestamp(),\n next_check_at: Schema.timestamp({ nullable: true }),\n },\n // Keyed by domain, not by attachment, so a host observing public DNS alone gets the same row.\n primaryKey: [\"owner_id\", \"domain\"],\n // The sweep index drives the backoff ladder; the attachment index is for clearing the link.\n indexes: [{ columns: [\"owner_id\", \"next_check_at\"] }, { columns: [\"attachment_id\"] }],\n }),\n});\n\nexport const list = (tables: Tables): ReadonlyArray<Schema.Table> => [\n tables.authorizations,\n tables.connections,\n tables.attachments,\n tables.continuations,\n tables.attempts,\n tables.readiness,\n];\n","/**\n * DomainKit's CapsuleDB capsule: six tables and one `Storage.Service` implementation.\n *\n * The capsule is a plain value, so a host imports it, points `capsuledb emit` at it, or hands it\n * to `Registry.layer` without running an Effect first.\n */\nimport { Capsule, Migration } from \"capsuledb\";\nimport { Storage } from \"domainkit\";\nimport { Layer } from \"effect\";\nimport type * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nimport { make as makeService } from \"./internal/storage.ts\";\nimport { DEFAULT_PREFIX, list, make as makeTables } from \"./internal/tables.ts\";\n\nexport { DEFAULT_PREFIX };\n\n/**\n * Build the capsule for a table prefix.\n *\n * The prefix is part of the physical layout: it changes the rendered DDL and therefore the\n * migration checksums, so a deployed registry must keep the prefix it was created with.\n */\nexport const make = (\n prefix: string = DEFAULT_PREFIX,\n): Capsule.Capsule<Storage.Service, never, SqlClient.SqlClient> => {\n const tables = makeTables(prefix);\n return Capsule.make({\n id: \"domainkit.storage\",\n tables: list(tables),\n migrations: [\n Migration.make({\n id: 1,\n name: \"create-storage\",\n risk: \"additive\",\n steps: list(tables).map(Migration.createTable),\n }),\n ],\n layer: Layer.effect(Storage.Service)(makeService(tables)),\n });\n};\n\n/** The capsule under the default `domainkit` prefix. `capsuledb emit --export capsule` reads this. */\nexport const capsule: Capsule.Capsule<Storage.Service, never, SqlClient.SqlClient> = make();\n","/**\n * The layer a host installs: DomainKit's `Storage` on the host's own PostgreSQL client.\n *\n * `layer()` runs the capsule through CapsuleDB's registry, which creates the ledger, applies\n * pending migrations, and only then provides `Storage`. A host that owns its migration pipeline\n * applies `capsuledb emit` output instead and boots with `mode: \"assert\"`, which touches no schema\n * and fails unless the database already matches the capsule.\n *\n * The layer requires only `SqlClient`: credentials arrive sealed, so Storage never needs `Custody`.\n */\nimport { Pg, type Registry as RegistryTypes, Registry } from \"capsuledb\";\nimport type { Storage } from \"domainkit\";\nimport type * as Layer from \"effect/Layer\";\nimport type * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nimport { capsule, DEFAULT_PREFIX, make } from \"./capsule.ts\";\n\nexport interface Options {\n /** Table prefix. Default `domainkit`. Part of the physical layout; immutable after first deploy. */\n readonly prefix?: string;\n /** `prepare` (default) migrates at boot; `assert` expects the host applied `capsuledb emit` output. */\n readonly mode?: \"prepare\" | \"assert\";\n /**\n * Prefix for CapsuleDB's own ledger tables; default `capsuledb`. Set it only to match a prefix a\n * host already uses for other capsules, and pass the same value to `capsuledb emit --prefix`.\n */\n readonly registryPrefix?: string;\n}\n\nexport const layer = (\n options: Options = {},\n): Layer.Layer<Storage.Service, RegistryTypes.RegistryRuntimeError, SqlClient.SqlClient> =>\n Registry.layer({\n provider: Pg.profile,\n capsules: [\n options.prefix === undefined || options.prefix === DEFAULT_PREFIX\n ? capsule\n : make(options.prefix),\n ],\n ...(options.mode === undefined ? {} : { mode: options.mode }),\n ...(options.registryPrefix === undefined ? {} : { prefix: options.registryPrefix }),\n });\n","/**\n * DomainKit's `Storage` on PostgreSQL, as one declarative CapsuleDB capsule.\n *\n * Hosts install `PgStorage.layer()` under `DomainKit.layer` and supply their own `SqlClient`. The\n * `capsule` value is the same declaration `capsuledb emit` reads to write SQL for a host-owned\n * migration pipeline.\n */\nimport packageJson from \"../package.json\" with { type: \"json\" };\n\nexport const VERSION = packageJson.version;\n\nexport * as PgStorage from \"./PgStorage.ts\";\nexport { capsule } from \"./capsule.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;ACyBA,MAAM,QAAQ,WAAyB,OAAO,KAAK,IAAI,UAAU,MAAM,EAAE,OAAO,CAAC,CAAC;AAElF,MAAM,YAAY,QAAmC,OACnD,KAAK,IAAI,OAAO,SAAS;CAAE;CAAQ;AAAG,CAAC,CAAC;AAE1C,MAAM,WAAW,SAAiB,UAChC,KAAK,IAAI,OAAO,aAAa;CAAE;CAAS,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;AAAG,CAAC,CAAC;AAEtF,MAAM,QAAQ,QAAgB,KAAK,IAAI,OAAO,KAAK,EAAE,IAAI,CAAC,CAAC;AAE3D,MAAM,iBAAiB,WAAmB,YACxC,IAAI,UAAU,MAAM,EAClB,QAAQ,IAAI,OAAO,cAAc;CAAE;CAAW;AAAQ,CAAC,EACzD,CAAC;AAEH,MAAM,cAAc,UAClB,MAAM,OAAO,iBAAiB,QAC1B,GAAG,MAAM,OAAO,KAAK,IAAI,MAAM,OAAO,MAAM,YAC5C,GAAG,MAAM,OAAO,KAAK,IAAI,OAAO,MAAM,OAAO,KAAK;;;;;;;AAQxD,MAAM,SACH,eACM,WACL,OAAO,MAAM,SAAS,UACpB,OAAO,KAAK,UAAU,QAAQ,KAAK,IAAI,QAAQ,cAAc,WAAW,WAAW,KAAK,CAAC,CAAC,CAC5F;;;;;AAUJ,MAAM,SAA6D,QAAW,YAAoB;CAChG,MAAM,SAASA,SAAO,oBAAoB,MAAM;CAChD,MAAM,SAASA,S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CACP,OAAO;AACT;;;;;;;;;;;;;;;ACzHA,MAAa,QACX,SAAiB,mBACgD;CACjE,MAAM,SAASC,OAAW,MAAM;CAChC,OAAO,QAAQ,KAAK;EAClB,IAAI;EACJ,QAAQ,KAAK,MAAM;EACnB,YAAY,CACV,UAAU,KAAK;GACb,IAAI;GACJ,MAAM;GACN,MAAM;GACN,OAAO,KAAK,MAAM,CAAC,CAAC,IAAI,UAAU,WAAW;EAC/C,CAAC,CACH;EACA,OAAO,MAAM,OAAO,QAAQ,OAAO,CAAC,CAACC,OAAY,MAAM,CAAC;CAC1D,CAAC;AACH;;AAGA,MAAa,UAAwE,KAAK;;;;;;;;;;;;;;ACb1F,MAAa,SACX,UAAmB,CAAC,MAEpB,SAAS,MAAM;CACb,UAAU,GAAG;CACb,UAAU,CACR,QAAQ,WAAW,KAAA,KAAa,QAAQ,WAAA,cACpC,UACA,KAAK,QAAQ,MAAM,CACzB;CACA,GAAI,QAAQ,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,KAAK;CAC3D,GAAI,QAAQ,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,eAAe;AACnF,CAAC;;;;;;;;;;AChCH,MAAa,UAAUC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["Schema","make","make","makeTables","makeService","packageJson.version"],"sources":["../package.json","../src/internal/storage.ts","../src/internal/tables.ts","../src/capsule.ts","../src/PgStorage.ts","../src/index.ts"],"sourcesContent":["","/**\n * `Storage.Interface` on PostgreSQL.\n *\n * Every method reads `Principal` and filters by `owner_id`, so a row belonging to another tenant\n * is indistinguishable from a row that does not exist. Aggregate transitions run inside one\n * transaction over a `FOR UPDATE` row, single-flight guards use a session-level advisory lock on a\n * reserved connection, and revocation is two-phase: mark `pending`, call the provider outside any\n * transaction, then delete.\n *\n * Storage never sees plaintext. `Connect` seals a credential through `Custody` before it reaches\n * `upsert` or `rotate`, so this module only ever moves a ciphertext string.\n */\nimport { DomainKit, Principal, Reason, Storage } from \"domainkit\";\nimport { DateTime, Effect, Option, Schema } from \"effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlError from \"effect/unstable/sql/SqlError\";\n\nimport type { Tables } from \"./tables.ts\";\n\ntype Fail = DomainKit.Error;\n\n// ---------------------------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------------------------\n\nconst fail = (reason: Reason.Model) => Effect.fail(new DomainKit.Error({ reason }));\n\nconst notFound = (entity: Reason.NotFound[\"entity\"], id: string) =>\n fail(new Reason.NotFound({ entity, id }));\n\nconst invalid = (message: string, field?: string) =>\n fail(new Reason.InvalidInput({ message, ...(field === undefined ? {} : { field }) }));\n\nconst busy = (key: string) => fail(new Reason.Busy({ key }));\n\nconst storageFailed = (operation: string, message: string) =>\n new DomainKit.Error({\n reason: new Reason.StorageFailed({ operation, message }),\n });\n\nconst sqlMessage = (error: SqlError.SqlError): string =>\n error.reason.cause instanceof Error\n ? `${error.reason._tag}: ${error.reason.cause.message}`\n : `${error.reason._tag}: ${String(error.reason.cause)}`;\n\n/**\n * Collapse the SQL error channel into `DomainKit.Error`.\n *\n * A `DomainKit.Error` raised by the body is the deliberate outcome of an invariant and passes\n * through unchanged; anything else is a driver failure and becomes `StorageFailed`.\n */\nconst guard =\n (operation: string) =>\n <A, R>(effect: Effect.Effect<A, SqlError.SqlError | Fail, R>): Effect.Effect<A, Fail, R> =>\n Effect.catch(effect, (error) =>\n Effect.fail(DomainKit.isError(error) ? error : storageFailed(operation, sqlMessage(error))),\n );\n\n// ---------------------------------------------------------------------------------------------\n// Row codecs\n// ---------------------------------------------------------------------------------------------\n\n/**\n * A row is stored as its schema's encoded form spread over columns, so the core schema stays the\n * only description of a row's shape. Reading reassembles the encoded object and decodes it.\n */\nconst codec = <S extends Schema.ConstraintCodec<unknown, unknown>>(schema: S, subject: string) => {\n const decode = Schema.decodeUnknownEffect(schema);\n const encode = Schema.encodeUnknownEffect(schema);\n return {\n read: (input: unknown): Effect.Effect<S[\"Type\"], Fail, S[\"DecodingServices\"]> =>\n decode(input).pipe(\n Effect.mapError((error) =>\n storageFailed(`${subject}.decode`, `stored ${subject} is invalid: ${error.message}`),\n ),\n ),\n write: (value: S[\"Type\"]): Effect.Effect<S[\"Encoded\"], Fail, S[\"EncodingServices\"]> =>\n encode(value).pipe(\n Effect.mapError((error) =>\n storageFailed(`${subject}.encode`, `${subject} cannot be stored: ${error.message}`),\n ),\n ),\n };\n};\n\nconst authorizationCodec = codec(Storage.Authorization, \"authorization\");\nconst connectionCodec = codec(Storage.Connection, \"connection\");\nconst attachmentCodec = codec(Storage.Attachment, \"attachment\");\nconst continuationCodec = codec(Storage.Continuation, \"continuation\");\nconst attemptCodec = codec(Storage.Attempt, \"attempt\");\nconst readinessCodec = codec(Storage.Readiness, \"readiness\");\nconst credentialCodec = codec(Storage.Credential, \"credential\");\n\n// ---------------------------------------------------------------------------------------------\n// Column conversions\n// ---------------------------------------------------------------------------------------------\n\n/** A `TIMESTAMPTZ` column as the ISO string every DomainKit timestamp schema encodes to. */\nconst iso = (value: unknown): string =>\n value instanceof Date ? value.toISOString() : String(value);\n\nconst isoOrNull = (value: unknown): string | null => (value === null ? null : iso(value));\n\n/** An ISO string from a schema's encoded form as the `Date` the driver binds to `TIMESTAMPTZ`. */\nconst at = (value: string): Date => new Date(value);\n\nconst atOrNull = (value: string | null): Date | null => (value === null ? null : at(value));\n\nconst now = Effect.map(DateTime.now, DateTime.toDateUtc);\n\n/**\n * A `JSONB` column as a plain value.\n *\n * Drivers disagree about whether they parse JSON columns, so accept both and normalize here\n * rather than depending on a host's client configuration.\n */\nconst fromJson = (value: unknown): unknown =>\n typeof value === \"string\" ? (JSON.parse(value) as unknown) : value;\n\nconst fromJsonOrNull = (value: unknown): unknown => (value === null ? null : fromJson(value));\n\n/** Bind a value to a `JSONB` column as text; PostgreSQL coerces the untyped parameter. */\nconst toJson = (value: unknown): string => JSON.stringify(value ?? null);\n\nconst toJsonOrNull = (value: unknown): string | null =>\n value === null || value === undefined ? null : toJson(value);\n\n// ---------------------------------------------------------------------------------------------\n// Row shapes\n// ---------------------------------------------------------------------------------------------\n\ninterface AuthorizationRow {\n readonly id: string;\n readonly owner_id: string;\n readonly provider: string;\n readonly method: string;\n readonly capabilities: unknown;\n readonly context: unknown;\n readonly revocation: string;\n readonly created_by: string;\n readonly created_at: unknown;\n readonly credential_ciphertext: string;\n readonly credential_expires_at: unknown;\n readonly credential_rotated_at: unknown;\n}\n\ninterface ConnectionRow {\n readonly id: string;\n readonly owner_id: string;\n readonly authorization_id: string;\n readonly created_at: unknown;\n}\n\ninterface AttachmentRow {\n readonly id: string;\n readonly owner_id: string;\n readonly connection_id: string;\n readonly domain: string;\n readonly zone: string;\n readonly label: string;\n readonly target: unknown;\n readonly created_at: unknown;\n}\n\ninterface ContinuationRow {\n readonly id: string;\n readonly owner_id: string;\n readonly actor_id: string;\n readonly provider: string;\n readonly payload: unknown;\n readonly return_to: string | null;\n readonly expires_at: unknown;\n}\n\ninterface AttemptRow {\n readonly id: string;\n readonly owner_id: string;\n readonly attachment_id: string;\n readonly kind: string;\n readonly status: string;\n readonly plan: unknown;\n readonly approval: unknown;\n readonly receipt: unknown;\n readonly rejection: unknown;\n readonly source_receipt_id: string | null;\n readonly lease_expires_at: unknown;\n readonly failure: string | null;\n readonly updated_at: unknown;\n}\n\ninterface ReadinessRow {\n readonly owner_id: string;\n readonly domain: string;\n readonly attachment_id: string | null;\n readonly overall: string;\n readonly requirements: unknown;\n readonly host: unknown;\n readonly pending_since: unknown;\n readonly checked_at: unknown;\n readonly next_check_at: unknown;\n}\n\nconst authorizationOf = (row: AuthorizationRow) =>\n authorizationCodec.read({\n id: row.id,\n ownerId: row.owner_id,\n provider: row.provider,\n method: row.method,\n capabilities: fromJson(row.capabilities),\n context: fromJson(row.context),\n revocation: row.revocation,\n createdBy: row.created_by,\n createdAt: iso(row.created_at),\n });\n\nconst credentialOf = (row: AuthorizationRow) =>\n credentialCodec.read({\n ciphertext: row.credential_ciphertext,\n expiresAt: isoOrNull(row.credential_expires_at),\n rotatedAt: iso(row.credential_rotated_at),\n });\n\nconst connectionOf = (row: ConnectionRow) =>\n connectionCodec.read({\n id: row.id,\n ownerId: row.owner_id,\n authorizationId: row.authorization_id,\n createdAt: iso(row.created_at),\n });\n\nconst attachmentOf = (row: AttachmentRow) =>\n attachmentCodec.read({\n id: row.id,\n ownerId: row.owner_id,\n connectionId: row.connection_id,\n domain: row.domain,\n zone: row.zone,\n label: row.label,\n target: fromJson(row.target),\n createdAt: iso(row.created_at),\n });\n\nconst continuationOf = (row: ContinuationRow) =>\n continuationCodec.read({\n id: row.id,\n ownerId: row.owner_id,\n actorId: row.actor_id,\n provider: row.provider,\n payload: fromJson(row.payload),\n returnTo: row.return_to,\n expiresAt: iso(row.expires_at),\n });\n\nconst attemptOf = (row: AttemptRow) =>\n attemptCodec.read({\n id: row.id,\n ownerId: row.owner_id,\n attachmentId: row.attachment_id,\n kind: row.kind,\n status: row.status,\n plan: fromJson(row.plan),\n approval: fromJsonOrNull(row.approval),\n receipt: fromJsonOrNull(row.receipt),\n rejection: fromJsonOrNull(row.rejection),\n sourceReceiptId: row.source_receipt_id,\n leaseExpiresAt: isoOrNull(row.lease_expires_at),\n failure: row.failure,\n updatedAt: iso(row.updated_at),\n });\n\nconst readinessOf = (row: ReadinessRow) =>\n readinessCodec.read({\n domain: row.domain,\n attachmentId: row.attachment_id,\n ownerId: row.owner_id,\n overall: row.overall,\n requirements: fromJson(row.requirements),\n host: fromJson(row.host),\n pendingSince: isoOrNull(row.pending_since),\n checkedAt: iso(row.checked_at),\n nextCheckAt: isoOrNull(row.next_check_at),\n });\n\nconst stale = (attempt: Storage.Attempt) =>\n fail(new Reason.Stale({ planId: attempt.id, digest: attempt.plan.digest }));\n\n/** `prefix_<uuid>`, the same identifier shape the memory implementation mints. */\nconst fresh = (prefix: string) => Effect.sync(() => `${prefix}_${crypto.randomUUID()}`);\n\n// ---------------------------------------------------------------------------------------------\n// Service\n// ---------------------------------------------------------------------------------------------\n\nexport const make = (\n tables: Tables,\n): Effect.Effect<Storage.Interface, never, SqlClient.SqlClient> =>\n Effect.gen(function* () {\n const client = yield* SqlClient.SqlClient;\n // A host may configure result-name transforms for its own tables; these queries read the exact\n // snake_case columns the capsule declared.\n const sql = client.withoutTransforms();\n\n const authorizations = sql(tables.authorizations.name);\n const connections = sql(tables.connections.name);\n const attachments = sql(tables.attachments.name);\n const continuations = sql(tables.continuations.name);\n const attempts = sql(tables.attempts.name);\n const readiness = sql(tables.readiness.name);\n\n /** The row this principal owns, locked for the rest of the transaction. */\n const lockedAuthorization = (owner: string, id: string) =>\n sql<AuthorizationRow>`\n SELECT * FROM ${authorizations} WHERE id = ${id} AND owner_id = ${owner} FOR UPDATE\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"authorization\", id) : Effect.succeed(rows[0]),\n ),\n );\n\n const lockedAttempt = (owner: string, id: string) =>\n sql<AttemptRow>`\n SELECT * FROM ${attempts} WHERE id = ${id} AND owner_id = ${owner} FOR UPDATE\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"plan\", id) : Effect.succeed(rows[0]),\n ),\n Effect.flatMap(attemptOf),\n );\n\n const requireConnection = (owner: string, id: string) =>\n sql<ConnectionRow>`\n SELECT * FROM ${connections} WHERE id = ${id} AND owner_id = ${owner}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"connection\", id) : Effect.succeed(rows[0]),\n ),\n );\n\n const requireAttachment = (owner: string, id: string) =>\n sql<AttachmentRow>`\n SELECT * FROM ${attachments} WHERE id = ${id} AND owner_id = ${owner}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"attachment\", id) : Effect.succeed(rows[0]),\n ),\n );\n\n const writeAuthorization = (\n authorization: Storage.Authorization,\n credential: Storage.Credential,\n ) =>\n Effect.all({\n row: authorizationCodec.write(authorization),\n secret: credentialCodec.write(credential),\n });\n\n /**\n * Phase one of revocation: mark the row `pending` so a crash between the provider call and the\n * delete is recoverable. Idempotent, and it never widens the row's state.\n *\n * Returns the ciphertext the caller is about to have revoked, which phase two checks.\n */\n const prepareRevocation = (owner: string, id: string) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const row = yield* lockedAuthorization(owner, id);\n yield* sql`\n UPDATE ${authorizations} SET revocation = 'pending', updated_at = ${yield* now}\n WHERE id = ${id} AND owner_id = ${owner}\n `;\n return row.credential_ciphertext;\n }),\n );\n\n /**\n * Phase two: delete the row, but only while it still holds the credential the provider was\n * asked to revoke.\n *\n * A credential refresh runs concurrently with revocation and rotates the row after the provider\n * call selected the old ciphertext. Deleting unconditionally would drop the row while the newly\n * issued credential is still live at the provider, with no local state left to revoke it from.\n * Leaving the row `pending` instead hands it to `recoverRevocations`, which revokes what the\n * row now holds. Every ciphertext is AES-GCM with a fresh IV, so equality here is exact.\n */\n const completeRevocation = (owner: string, id: string, ciphertext: string) =>\n sql`\n DELETE FROM ${authorizations}\n WHERE id = ${id} AND owner_id = ${owner} AND credential_ciphertext = ${ciphertext}\n `;\n\n const service: Storage.Interface = {\n authorizations: {\n upsert: ({ authorization, credential, expectedId }) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n if (authorization.ownerId !== ownerId) {\n return yield* invalid(\n \"Authorization owner does not match the principal\",\n \"ownerId\",\n );\n }\n const { row, secret } = yield* writeAuthorization(authorization, credential);\n const stamp = yield* now;\n return yield* sql.withTransaction(\n Effect.gen(function* () {\n if (expectedId !== undefined) {\n const current = yield* lockedAuthorization(ownerId, expectedId);\n if (current.revocation !== \"active\") {\n return yield* busy(`authorization:${expectedId}`);\n }\n if (authorization.id !== expectedId) {\n return yield* invalid(\"Authorization id must match expectedId\", \"id\");\n }\n // A replace overwrites every column the caller supplied, including `created_at`:\n // the row it returns has to be the row a later `get` reads back.\n yield* sql`\n UPDATE ${authorizations} SET\n provider = ${row.provider},\n method = ${row.method},\n capabilities = ${toJson(row.capabilities)},\n context = ${toJson(row.context)},\n revocation = ${row.revocation},\n created_by = ${row.createdBy},\n created_at = ${at(row.createdAt)},\n credential_ciphertext = ${secret.ciphertext},\n credential_expires_at = ${atOrNull(secret.expiresAt)},\n credential_rotated_at = ${at(secret.rotatedAt)},\n updated_at = ${stamp}\n WHERE id = ${expectedId} AND owner_id = ${ownerId}\n `;\n return authorization;\n }\n // An id already taken by any tenant is a caller defect, not a missing row, so the\n // insert claims it atomically instead of racing a prior existence check.\n const inserted = yield* sql<{ readonly id: string }>`\n INSERT INTO ${authorizations} (\n id, owner_id, provider, method, capabilities, context, revocation,\n created_by, created_at, credential_ciphertext, credential_expires_at,\n credential_rotated_at, updated_at\n ) VALUES (\n ${row.id}, ${row.ownerId}, ${row.provider}, ${row.method},\n ${toJson(row.capabilities)}, ${toJson(row.context)}, ${row.revocation},\n ${row.createdBy}, ${at(row.createdAt)}, ${secret.ciphertext},\n ${atOrNull(secret.expiresAt)}, ${at(secret.rotatedAt)}, ${stamp}\n ) ON CONFLICT (id) DO NOTHING RETURNING id\n `;\n return inserted[0] === undefined\n ? yield* invalid(`Authorization ${authorization.id} already exists`, \"id\")\n : authorization;\n }),\n );\n }),\n ).pipe(guard(\"authorizations.upsert\")),\n get: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AuthorizationRow>`\n SELECT * FROM ${authorizations} WHERE id = ${id} AND owner_id = ${ownerId}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"authorization\", id) : authorizationOf(rows[0]),\n ),\n ),\n ).pipe(guard(\"authorizations.get\")),\n credential: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AuthorizationRow>`\n SELECT * FROM ${authorizations} WHERE id = ${id} AND owner_id = ${ownerId}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"authorization\", id) : credentialOf(rows[0]),\n ),\n ),\n ).pipe(guard(\"authorizations.credential\")),\n rotate: (id, credential) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n const secret = yield* credentialCodec.write(credential);\n const updated = yield* sql<{ readonly id: string }>`\n UPDATE ${authorizations} SET\n credential_ciphertext = ${secret.ciphertext},\n credential_expires_at = ${atOrNull(secret.expiresAt)},\n credential_rotated_at = ${at(secret.rotatedAt)},\n updated_at = ${yield* now}\n WHERE id = ${id} AND owner_id = ${ownerId} RETURNING id\n `;\n if (updated[0] === undefined) return yield* notFound(\"authorization\", id);\n }),\n ).pipe(guard(\"authorizations.rotate\")),\n promoteCapabilities: (id, capabilities) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const current = yield* authorizationOf(yield* lockedAuthorization(ownerId, id));\n const merged = [...new Set([...current.capabilities, ...capabilities])];\n yield* sql`\n UPDATE ${authorizations}\n SET capabilities = ${toJson(merged)}, updated_at = ${yield* now}\n WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n }),\n ),\n ).pipe(guard(\"authorizations.promoteCapabilities\")),\n revoke: (id, revoke) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n const ciphertext = yield* prepareRevocation(ownerId, id).pipe(\n guard(\"authorizations.revoke\"),\n );\n yield* revoke;\n yield* completeRevocation(ownerId, id, ciphertext).pipe(\n guard(\"authorizations.completeRevocation\"),\n );\n }),\n ),\n recoverRevocations: (revoke) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n const rows = yield* sql<AuthorizationRow>`\n SELECT * FROM ${authorizations}\n WHERE owner_id = ${ownerId} AND revocation = 'pending'\n ORDER BY created_at\n `.pipe(guard(\"authorizations.pendingRevocations\"));\n yield* Effect.forEach(rows, (row) =>\n Effect.gen(function* () {\n yield* revoke(yield* authorizationOf(row));\n yield* completeRevocation(ownerId, row.id, row.credential_ciphertext).pipe(\n guard(\"authorizations.completeRevocation\"),\n );\n }),\n );\n return rows.length;\n }),\n ),\n },\n connections: {\n create: (authorizationId) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n yield* lockedAuthorization(ownerId, authorizationId);\n const row = new Storage.Connection({\n id: yield* fresh(\"conn\"),\n ownerId,\n authorizationId,\n createdAt: yield* DateTime.now,\n });\n const encoded = yield* connectionCodec.write(row);\n yield* sql`\n INSERT INTO ${connections} (id, owner_id, authorization_id, created_at)\n VALUES (${encoded.id}, ${encoded.ownerId}, ${encoded.authorizationId},\n ${at(encoded.createdAt)})\n `;\n return row;\n }),\n ),\n ).pipe(guard(\"connections.create\")),\n get: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.flatMap(requireConnection(ownerId, id), connectionOf),\n ).pipe(guard(\"connections.get\")),\n list: (filter) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.flatMap(\n filter?.provider === undefined\n ? sql<ConnectionRow>`\n SELECT * FROM ${connections} WHERE owner_id = ${ownerId} ORDER BY created_at\n `\n : sql<ConnectionRow>`\n SELECT c.* FROM ${connections} AS c\n JOIN ${authorizations} AS a ON a.id = c.authorization_id\n WHERE c.owner_id = ${ownerId} AND a.provider = ${filter.provider}\n ORDER BY c.created_at\n `,\n (rows) => Effect.forEach(rows, connectionOf),\n ),\n ).pipe(guard(\"connections.list\")),\n remove: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const rows = yield* sql<ConnectionRow>`\n SELECT * FROM ${connections}\n WHERE id = ${id} AND owner_id = ${ownerId} FOR UPDATE\n `;\n if (rows[0] === undefined) return yield* notFound(\"connection\", id);\n const held = yield* sql<{ readonly id: string }>`\n SELECT id FROM ${attachments}\n WHERE connection_id = ${id} AND owner_id = ${ownerId} LIMIT 1\n `;\n if (held[0] !== undefined) {\n return yield* invalid(`Connection ${id} still has attachments`, \"connectionId\");\n }\n yield* sql`DELETE FROM ${connections} WHERE id = ${id} AND owner_id = ${ownerId}`;\n }),\n ),\n ).pipe(guard(\"connections.remove\")),\n },\n attachments: {\n create: (input) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n yield* requireConnection(ownerId, input.connectionId);\n const row = new Storage.Attachment({\n id: yield* fresh(\"att\"),\n ownerId,\n connectionId: input.connectionId,\n domain: input.domain,\n zone: input.zone,\n label: input.label,\n target: input.target,\n createdAt: yield* DateTime.now,\n });\n const encoded = yield* attachmentCodec.write(row);\n // The unique (owner_id, domain) constraint decides the duplicate, so two concurrent\n // attaches cannot both win.\n const inserted = yield* sql<{ readonly id: string }>`\n INSERT INTO ${attachments} (\n id, owner_id, connection_id, domain, zone, label, target, created_at\n ) VALUES (\n ${encoded.id}, ${encoded.ownerId}, ${encoded.connectionId}, ${encoded.domain},\n ${encoded.zone}, ${encoded.label}, ${toJson(encoded.target)},\n ${at(encoded.createdAt)}\n ) ON CONFLICT (owner_id, domain) DO NOTHING RETURNING id\n `;\n return inserted[0] === undefined\n ? yield* invalid(`${input.domain} is already attached`, \"domain\")\n : row;\n }),\n ),\n ).pipe(guard(\"attachments.create\")),\n get: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.flatMap(requireAttachment(ownerId, id), attachmentOf),\n ).pipe(guard(\"attachments.get\")),\n byDomain: (domain) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AttachmentRow>`\n SELECT * FROM ${attachments} WHERE owner_id = ${ownerId} AND domain = ${domain}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined\n ? Effect.succeedNone\n : Effect.map(attachmentOf(rows[0]), Option.some),\n ),\n ),\n ).pipe(guard(\"attachments.byDomain\")),\n list: (connectionId) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n yield* requireConnection(ownerId, connectionId);\n const rows = yield* sql<AttachmentRow>`\n SELECT * FROM ${attachments}\n WHERE owner_id = ${ownerId} AND connection_id = ${connectionId}\n ORDER BY created_at\n `;\n return yield* Effect.forEach(rows, attachmentOf);\n }),\n ).pipe(guard(\"attachments.list\")),\n remove: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n yield* requireAttachment(ownerId, id);\n // Readiness is keyed by domain and outlives the attachment, so clear the link\n // rather than the row: what was observed about the domain is still true, and a\n // dangling attachment id would fail the next `readiness.put`.\n yield* sql`\n UPDATE ${readiness} SET attachment_id = NULL\n WHERE attachment_id = ${id} AND owner_id = ${ownerId}\n `;\n yield* sql`DELETE FROM ${attachments} WHERE id = ${id} AND owner_id = ${ownerId}`;\n }),\n ),\n ).pipe(guard(\"attachments.remove\")),\n },\n continuations: {\n put: (continuation) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n if (continuation.ownerId !== ownerId) {\n return yield* invalid(\"Continuation owner does not match the principal\", \"ownerId\");\n }\n const encoded = yield* continuationCodec.write(continuation);\n yield* sql`\n INSERT INTO ${continuations} (\n id, owner_id, actor_id, provider, payload, return_to, expires_at\n ) VALUES (\n ${encoded.id}, ${encoded.ownerId}, ${encoded.actorId}, ${encoded.provider},\n ${toJson(encoded.payload)}, ${encoded.returnTo}, ${at(encoded.expiresAt)}\n ) ON CONFLICT (id) DO UPDATE SET\n owner_id = EXCLUDED.owner_id,\n actor_id = EXCLUDED.actor_id,\n provider = EXCLUDED.provider,\n payload = EXCLUDED.payload,\n return_to = EXCLUDED.return_to,\n expires_at = EXCLUDED.expires_at\n `;\n }),\n ).pipe(guard(\"continuations.put\")),\n get: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n // A read, not a claim: the row survives so `consume` can still spend it.\n const rows = yield* sql<ContinuationRow>`\n SELECT * FROM ${continuations} WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n if (rows[0] === undefined) return yield* notFound(\"continuation\", id);\n const continuation = yield* continuationOf(rows[0]);\n const instant = yield* DateTime.now;\n return DateTime.toEpochMillis(continuation.expiresAt) <=\n DateTime.toEpochMillis(instant)\n ? yield* fail(new Reason.Expired({ entity: \"continuation\", id }))\n : continuation;\n }),\n ).pipe(guard(\"continuations.get\")),\n consume: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n // The delete is the claim: a second consume finds nothing, expired or not.\n const rows = yield* sql<ContinuationRow>`\n DELETE FROM ${continuations}\n WHERE id = ${id} AND owner_id = ${ownerId} RETURNING *\n `;\n if (rows[0] === undefined) return yield* notFound(\"continuation\", id);\n const continuation = yield* continuationOf(rows[0]);\n const instant = yield* DateTime.now;\n return DateTime.toEpochMillis(continuation.expiresAt) <=\n DateTime.toEpochMillis(instant)\n ? yield* fail(new Reason.Expired({ entity: \"continuation\", id }))\n : continuation;\n }),\n ).pipe(guard(\"continuations.consume\")),\n },\n attempts: {\n create: (attempt) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n if (attempt.ownerId !== ownerId) {\n return yield* invalid(\"Attempt owner does not match the principal\", \"ownerId\");\n }\n const encoded = yield* attemptCodec.write(attempt);\n const inserted = yield* sql<{ readonly id: string }>`\n INSERT INTO ${attempts} (\n id, owner_id, attachment_id, kind, status, plan, approval, approval_id,\n receipt, receipt_id, rejection, source_receipt_id, lease_expires_at, failure,\n plan_created_at, updated_at\n ) VALUES (\n ${encoded.id}, ${encoded.ownerId}, ${encoded.attachmentId}, ${encoded.kind},\n ${encoded.status}, ${toJson(encoded.plan)}, ${toJsonOrNull(encoded.approval)},\n ${attempt.approval?.id ?? null}, ${toJsonOrNull(encoded.receipt)},\n ${attempt.receipt?.id ?? null}, ${toJsonOrNull(encoded.rejection)},\n ${encoded.sourceReceiptId},\n ${atOrNull(encoded.leaseExpiresAt)}, ${encoded.failure},\n ${at(encoded.plan.createdAt)}, ${at(encoded.updatedAt)}\n ) ON CONFLICT (id) DO NOTHING RETURNING id\n `;\n return inserted[0] === undefined\n ? yield* invalid(`Plan ${attempt.id} already exists`, \"id\")\n : attempt;\n }),\n ).pipe(guard(\"attempts.create\")),\n get: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AttemptRow>`\n SELECT * FROM ${attempts} WHERE id = ${id} AND owner_id = ${ownerId}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"plan\", id) : attemptOf(rows[0]),\n ),\n ),\n ).pipe(guard(\"attempts.get\")),\n byApproval: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AttemptRow>`\n SELECT * FROM ${attempts} WHERE approval_id = ${id} AND owner_id = ${ownerId}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"approval\", id) : attemptOf(rows[0]),\n ),\n ),\n ).pipe(guard(\"attempts.byApproval\")),\n byReceipt: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AttemptRow>`\n SELECT * FROM ${attempts} WHERE receipt_id = ${id} AND owner_id = ${ownerId}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"receipt\", id) : attemptOf(rows[0]),\n ),\n ),\n ).pipe(guard(\"attempts.byReceipt\")),\n latest: (attachmentId, kind) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<AttemptRow>`\n SELECT * FROM ${attempts}\n WHERE owner_id = ${ownerId} AND attachment_id = ${attachmentId} AND kind = ${kind}\n ORDER BY plan_created_at DESC, updated_at DESC LIMIT 1\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined\n ? Effect.succeedNone\n : Effect.map(attemptOf(rows[0]), Option.some),\n ),\n ),\n ).pipe(guard(\"attempts.latest\")),\n approve: (id, approval) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const current = yield* lockedAttempt(ownerId, id);\n // Replaying the same approval is how a retried request stays safe.\n if (current.approval?.id === approval.id) return current;\n if (current.status !== \"planned\") return yield* stale(current);\n const next = new Storage.Attempt({\n ...current,\n status: \"approved\",\n approval,\n updatedAt: yield* DateTime.now,\n });\n const encoded = yield* attemptCodec.write(next);\n yield* sql`\n UPDATE ${attempts} SET\n status = ${encoded.status},\n approval = ${toJsonOrNull(encoded.approval)},\n approval_id = ${approval.id},\n updated_at = ${at(encoded.updatedAt)}\n WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n return next;\n }),\n ),\n ).pipe(guard(\"attempts.approve\")),\n reject: (id, input) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const current = yield* lockedAttempt(ownerId, id);\n // Terminal: a second rejection is the same outcome, so it returns the first one.\n if (current.status === \"rejected\") return current;\n if (current.status === \"expired\") {\n return yield* fail(new Reason.Expired({ entity: \"plan\", id }));\n }\n // A digest mismatch means the reviewer declined a plan that is no longer current.\n if (current.status !== \"planned\" || current.plan.digest !== input.digest) {\n return yield* stale(current);\n }\n const instant = yield* DateTime.now;\n const next = new Storage.Attempt({\n ...current,\n status: \"rejected\",\n rejection: { actorId: input.actorId, reason: input.reason, at: instant },\n updatedAt: instant,\n });\n const encoded = yield* attemptCodec.write(next);\n yield* sql`\n UPDATE ${attempts} SET\n status = ${encoded.status},\n rejection = ${toJsonOrNull(encoded.rejection)},\n updated_at = ${at(encoded.updatedAt)}\n WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n return next;\n }),\n ),\n ).pipe(guard(\"attempts.reject\")),\n claim: (id, lease) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const current = yield* lockedAttempt(ownerId, id);\n const instant = yield* DateTime.now;\n if (current.status === \"applying\") {\n const held =\n current.leaseExpiresAt !== null &&\n DateTime.toEpochMillis(current.leaseExpiresAt) >\n DateTime.toEpochMillis(instant);\n if (held) return yield* busy(`apply:${id}`);\n } else if (current.status !== \"approved\" && current.status !== \"failed\") {\n return yield* stale(current);\n }\n const next = new Storage.Attempt({\n ...current,\n status: \"applying\",\n leaseExpiresAt: lease,\n failure: null,\n updatedAt: instant,\n });\n const encoded = yield* attemptCodec.write(next);\n yield* sql`\n UPDATE ${attempts} SET\n status = ${encoded.status},\n lease_expires_at = ${atOrNull(encoded.leaseExpiresAt)},\n failure = NULL,\n updated_at = ${at(encoded.updatedAt)}\n WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n return next;\n }),\n ),\n ).pipe(guard(\"attempts.claim\")),\n complete: (id, receipt) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const current = yield* lockedAttempt(ownerId, id);\n if (current.status !== \"applying\") return yield* stale(current);\n const next = new Storage.Attempt({\n ...current,\n status: receipt.status,\n receipt,\n leaseExpiresAt: null,\n updatedAt: yield* DateTime.now,\n });\n const encoded = yield* attemptCodec.write(next);\n yield* sql`\n UPDATE ${attempts} SET\n status = ${encoded.status},\n receipt = ${toJsonOrNull(encoded.receipt)},\n receipt_id = ${receipt.id},\n lease_expires_at = NULL,\n updated_at = ${at(encoded.updatedAt)}\n WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n return next;\n }),\n ),\n ).pipe(guard(\"attempts.complete\")),\n fail: (id, message) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const current = yield* lockedAttempt(ownerId, id);\n if (current.status !== \"applying\") return yield* stale(current);\n const next = new Storage.Attempt({\n ...current,\n status: \"failed\",\n failure: message,\n leaseExpiresAt: null,\n updatedAt: yield* DateTime.now,\n });\n const encoded = yield* attemptCodec.write(next);\n yield* sql`\n UPDATE ${attempts} SET\n status = ${encoded.status},\n failure = ${message},\n lease_expires_at = NULL,\n updated_at = ${at(encoded.updatedAt)}\n WHERE id = ${id} AND owner_id = ${ownerId}\n `;\n return next;\n }),\n ),\n ).pipe(guard(\"attempts.fail\")),\n },\n readiness: {\n put: (row) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n if (row.ownerId !== ownerId) {\n return yield* invalid(\"Readiness owner does not match the principal\", \"ownerId\");\n }\n // A linked attachment has to exist for this owner; observe-only readiness has none.\n if (row.attachmentId !== null) yield* requireAttachment(ownerId, row.attachmentId);\n const encoded = yield* readinessCodec.write(row);\n yield* sql`\n INSERT INTO ${readiness} (\n owner_id, domain, attachment_id, overall, requirements, host, pending_since,\n checked_at, next_check_at\n ) VALUES (\n ${encoded.ownerId}, ${encoded.domain}, ${encoded.attachmentId},\n ${encoded.overall}, ${toJson(encoded.requirements)}, ${toJson(encoded.host)},\n ${atOrNull(encoded.pendingSince)}, ${at(encoded.checkedAt)},\n ${atOrNull(encoded.nextCheckAt)}\n ) ON CONFLICT (owner_id, domain) DO UPDATE SET\n attachment_id = EXCLUDED.attachment_id,\n overall = EXCLUDED.overall,\n requirements = EXCLUDED.requirements,\n host = EXCLUDED.host,\n pending_since = EXCLUDED.pending_since,\n checked_at = EXCLUDED.checked_at,\n next_check_at = EXCLUDED.next_check_at\n `;\n }),\n ).pipe(guard(\"readiness.put\")),\n get: (domain) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<ReadinessRow>`\n SELECT * FROM ${readiness}\n WHERE owner_id = ${ownerId} AND domain = ${domain}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined\n ? Effect.succeedNone\n : Effect.map(readinessOf(rows[0]), Option.some),\n ),\n ),\n ).pipe(guard(\"readiness.get\")),\n },\n withLock: (key, effect) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.scoped(\n Effect.gen(function* () {\n // A session lock, not a transaction lock: the guarded effect refreshes a credential\n // against the provider, and no transaction should stay open across an HTTP call.\n // `reserve` pins one pooled connection so the unlock runs on the session that took\n // the lock, and registering it after the connection makes it run first on release.\n const connection = yield* Effect.mapError(sql.reserve, (error) =>\n storageFailed(\"withLock\", sqlMessage(error)),\n );\n const scoped = `${ownerId}:${key}`;\n yield* Effect.acquireRelease(\n connection\n .execute(\n \"SELECT pg_try_advisory_lock(hashtextextended($1, 0)) AS acquired\",\n [scoped],\n undefined,\n )\n .pipe(\n Effect.mapError((error: SqlError.SqlError) =>\n storageFailed(\"withLock\", sqlMessage(error)),\n ),\n Effect.flatMap((rows: ReadonlyArray<{ readonly acquired: boolean }>) =>\n rows[0]?.acquired === true ? Effect.void : busy(key),\n ),\n ),\n () =>\n connection\n .execute(\n \"SELECT pg_advisory_unlock(hashtextextended($1, 0))\",\n [scoped],\n undefined,\n )\n .pipe(Effect.ignore),\n );\n return yield* effect;\n }),\n ),\n ),\n };\n\n return service;\n });\n","/**\n * The six tables DomainKit owns, declared once and rendered per dialect by CapsuleDB.\n *\n * Every table carries `owner_id` and every query filters by it: tenancy is a column, not a schema.\n * There are no foreign keys to host tables, and none between DomainKit's own tables either, so a\n * host can add its own in the emitted migration without fighting a constraint the package owns.\n */\nimport { Schema } from \"capsuledb\";\n\nexport interface Tables {\n readonly authorizations: Schema.Table;\n readonly connections: Schema.Table;\n readonly attachments: Schema.Table;\n readonly continuations: Schema.Table;\n readonly attempts: Schema.Table;\n readonly readiness: Schema.Table;\n}\n\n/** Default table prefix. Part of the physical layout, so it is immutable after the first deploy. */\nexport const DEFAULT_PREFIX = \"domainkit\";\n\n/**\n * Declare the six tables under `prefix`.\n *\n * `Schema.table` validates every identifier it will quote, so an invalid prefix throws\n * `CapsuleDefinitionError` here rather than reaching a renderer.\n */\nexport const make = (prefix: string): Tables => ({\n authorizations: Schema.table(`${prefix}_authorizations`, {\n columns: {\n id: Schema.text(),\n owner_id: Schema.text(),\n provider: Schema.text(),\n method: Schema.text(),\n capabilities: Schema.json(),\n context: Schema.json(),\n revocation: Schema.text(),\n created_by: Schema.text(),\n created_at: Schema.timestamp(),\n credential_ciphertext: Schema.text(),\n credential_expires_at: Schema.timestamp({ nullable: true }),\n credential_rotated_at: Schema.timestamp(),\n updated_at: Schema.timestamp(),\n },\n primaryKey: [\"id\"],\n indexes: [{ columns: [\"owner_id\", \"revocation\"] }, { columns: [\"owner_id\", \"provider\"] }],\n }),\n connections: Schema.table(`${prefix}_connections`, {\n columns: {\n id: Schema.text(),\n owner_id: Schema.text(),\n authorization_id: Schema.text(),\n created_at: Schema.timestamp(),\n },\n primaryKey: [\"id\"],\n indexes: [{ columns: [\"owner_id\"] }, { columns: [\"authorization_id\"] }],\n }),\n attachments: Schema.table(`${prefix}_attachments`, {\n columns: {\n id: Schema.text(),\n owner_id: Schema.text(),\n connection_id: Schema.text(),\n domain: Schema.text(),\n zone: Schema.text(),\n /**\n * The provider's label for the zone at attach time, so a UI names the account offline. The\n * default is what fills the rows an installation attached before the column existed.\n */\n label: Schema.text({ default: \"\" }),\n target: Schema.json(),\n created_at: Schema.timestamp(),\n },\n primaryKey: [\"id\"],\n // One attachment per domain per tenant; `attachments.create` reads the conflict as InvalidInput.\n uniques: [[\"owner_id\", \"domain\"]],\n indexes: [{ columns: [\"owner_id\", \"connection_id\"] }],\n }),\n continuations: Schema.table(`${prefix}_continuations`, {\n columns: {\n id: Schema.text(),\n owner_id: Schema.text(),\n actor_id: Schema.text(),\n provider: Schema.text(),\n payload: Schema.json(),\n return_to: Schema.text({ nullable: true }),\n expires_at: Schema.timestamp(),\n },\n primaryKey: [\"id\"],\n // Hosts sweep expired rows on this index; consume deletes the row it returns.\n indexes: [{ columns: [\"expires_at\"] }],\n }),\n attempts: Schema.table(`${prefix}_attempts`, {\n columns: {\n id: Schema.text(),\n owner_id: Schema.text(),\n attachment_id: Schema.text(),\n kind: Schema.text(),\n status: Schema.text(),\n plan: Schema.json(),\n approval: Schema.json({ nullable: true }),\n /** Denormalized from `approval` so `byApproval` is an index lookup. */\n approval_id: Schema.text({ nullable: true }),\n receipt: Schema.json({ nullable: true }),\n /** Denormalized from `receipt` so `byReceipt` is an index lookup. */\n receipt_id: Schema.text({ nullable: true }),\n /** Who declined the plan, why, and when; set when an attempt reaches `rejected`. */\n rejection: Schema.json({ nullable: true }),\n source_receipt_id: Schema.text({ nullable: true }),\n lease_expires_at: Schema.timestamp({ nullable: true }),\n failure: Schema.text({ nullable: true }),\n /** The plan's own `createdAt`; `latest` orders by it. */\n plan_created_at: Schema.timestamp(),\n updated_at: Schema.timestamp(),\n },\n primaryKey: [\"id\"],\n indexes: [\n { columns: [\"owner_id\", \"attachment_id\", \"kind\"] },\n { columns: [\"owner_id\", \"approval_id\"] },\n { columns: [\"owner_id\", \"receipt_id\"] },\n ],\n }),\n readiness: Schema.table(`${prefix}_readiness`, {\n columns: {\n owner_id: Schema.text(),\n domain: Schema.text(),\n /** Set while an attachment covers the domain; observe-only readiness leaves it null. */\n attachment_id: Schema.text({ nullable: true }),\n overall: Schema.text(),\n requirements: Schema.json(),\n host: Schema.json(),\n pending_since: Schema.timestamp({ nullable: true }),\n checked_at: Schema.timestamp(),\n next_check_at: Schema.timestamp({ nullable: true }),\n },\n // Keyed by domain, not by attachment, so a host observing public DNS alone gets the same row.\n primaryKey: [\"owner_id\", \"domain\"],\n // The sweep index drives the backoff ladder; the attachment index is for clearing the link.\n indexes: [{ columns: [\"owner_id\", \"next_check_at\"] }, { columns: [\"attachment_id\"] }],\n }),\n});\n\n/**\n * The attachments table as the first migration created it, before `label`.\n *\n * A migration is history: what it renders must not move, or an installation that already ran it\n * sees a different checksum for work it has done. The declaration above is the current shape, and\n * the migration that adds the column carries the difference.\n */\nexport const attachmentsV1 = (prefix: string): Schema.Table =>\n Schema.table(`${prefix}_attachments`, {\n columns: {\n id: Schema.text(),\n owner_id: Schema.text(),\n connection_id: Schema.text(),\n domain: Schema.text(),\n zone: Schema.text(),\n target: Schema.json(),\n created_at: Schema.timestamp(),\n },\n primaryKey: [\"id\"],\n uniques: [[\"owner_id\", \"domain\"]],\n indexes: [{ columns: [\"owner_id\", \"connection_id\"] }],\n });\n\nexport const list = (tables: Tables): ReadonlyArray<Schema.Table> => [\n tables.authorizations,\n tables.connections,\n tables.attachments,\n tables.continuations,\n tables.attempts,\n tables.readiness,\n];\n","/**\n * DomainKit's CapsuleDB capsule: six tables and one `Storage.Service` implementation.\n *\n * The capsule is a plain value, so a host imports it, points `capsuledb emit` at it, or hands it\n * to `Registry.layer` without running an Effect first.\n */\nimport { Capsule, Migration } from \"capsuledb\";\nimport { Storage } from \"domainkit\";\nimport { Layer } from \"effect\";\nimport type * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nimport { make as makeService } from \"./internal/storage.ts\";\nimport { attachmentsV1, DEFAULT_PREFIX, list, make as makeTables } from \"./internal/tables.ts\";\n\nexport { DEFAULT_PREFIX };\n\n/**\n * Build the capsule for a table prefix.\n *\n * The prefix is part of the physical layout: it changes the rendered DDL and therefore the\n * migration checksums, so a deployed registry must keep the prefix it was created with.\n */\nexport const make = (\n prefix: string = DEFAULT_PREFIX,\n): Capsule.Capsule<Storage.Service, never, SqlClient.SqlClient> => {\n const tables = makeTables(prefix);\n return Capsule.make({\n id: \"domainkit.storage\",\n tables: list(tables),\n migrations: [\n Migration.make({\n id: 1,\n name: \"create-storage\",\n risk: \"additive\",\n steps: list(tables).map((table) =>\n Migration.createTable(\n table.name === tables.attachments.name ? attachmentsV1(prefix) : table,\n ),\n ),\n }),\n // An installation that attached domains before the column existed keeps those rows: the\n // default fills them, and the backfill names each one after the zone it is attached to,\n // which is what the provider's label is built from.\n Migration.make({\n id: 2,\n name: \"attachment-label\",\n risk: \"additive\",\n steps: [\n Migration.addColumn(tables.attachments.name, \"label\", { type: \"text\", default: \"\" }),\n Migration.sql(\n Object.fromEntries(\n ([\"postgres\", \"sqlite\"] as const).map((dialect) => [\n dialect,\n [`UPDATE ${tables.attachments.name} SET label = zone WHERE label = ''`],\n ]),\n ),\n ),\n ],\n }),\n ],\n layer: Layer.effect(Storage.Service)(makeService(tables)),\n });\n};\n\n/** The capsule under the default `domainkit` prefix. `capsuledb emit --export capsule` reads this. */\nexport const capsule: Capsule.Capsule<Storage.Service, never, SqlClient.SqlClient> = make();\n","/**\n * The layer a host installs: DomainKit's `Storage` on the host's own PostgreSQL client.\n *\n * `layer()` runs the capsule through CapsuleDB's registry, which creates the ledger, applies\n * pending migrations, and only then provides `Storage`. A host that owns its migration pipeline\n * applies `capsuledb emit` output instead and boots with `mode: \"assert\"`, which touches no schema\n * and fails unless the database already matches the capsule.\n *\n * The layer requires only `SqlClient`: credentials arrive sealed, so Storage never needs `Custody`.\n */\nimport { Pg, type Registry as RegistryTypes, Registry } from \"capsuledb\";\nimport type { Storage } from \"domainkit\";\nimport type * as Layer from \"effect/Layer\";\nimport type * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nimport { capsule, DEFAULT_PREFIX, make } from \"./capsule.ts\";\n\nexport interface Options {\n /** Table prefix. Default `domainkit`. Part of the physical layout; immutable after first deploy. */\n readonly prefix?: string;\n /** `prepare` (default) migrates at boot; `assert` expects the host applied `capsuledb emit` output. */\n readonly mode?: \"prepare\" | \"assert\";\n /**\n * Prefix for CapsuleDB's own ledger tables; default `capsuledb`. Set it only to match a prefix a\n * host already uses for other capsules, and pass the same value to `capsuledb emit --prefix`.\n */\n readonly registryPrefix?: string;\n}\n\nexport const layer = (\n options: Options = {},\n): Layer.Layer<Storage.Service, RegistryTypes.RegistryRuntimeError, SqlClient.SqlClient> =>\n Registry.layer({\n provider: Pg.profile,\n capsules: [\n options.prefix === undefined || options.prefix === DEFAULT_PREFIX\n ? capsule\n : make(options.prefix),\n ],\n ...(options.mode === undefined ? {} : { mode: options.mode }),\n ...(options.registryPrefix === undefined ? {} : { prefix: options.registryPrefix }),\n });\n","/**\n * DomainKit's `Storage` on PostgreSQL, as one declarative CapsuleDB capsule.\n *\n * Hosts install `PgStorage.layer()` under `DomainKit.layer` and supply their own `SqlClient`. The\n * `capsule` value is the same declaration `capsuledb emit` reads to write SQL for a host-owned\n * migration pipeline.\n */\nimport packageJson from \"../package.json\" with { type: \"json\" };\n\nexport const VERSION = packageJson.version;\n\nexport * as PgStorage from \"./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AAE,MAAM,QAAQ,KAAK;CAC3D,GAAI,QAAQ,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,eAAe;AACnF,CAAC;;;;;;;;;;AChCH,MAAa,UAAUC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@domainkit/capsuledb",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.1",
|
|
4
4
|
"description": "DomainKit Storage on PostgreSQL, as one declarative CapsuleDB capsule",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dns",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"typecheck": "tsc --noEmit"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"domainkit": "^0.
|
|
48
|
+
"domainkit": "^0.12.0"
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"@effect/sql-pg": "4.0.0-rc.112",
|