@domainkit/capsuledb 0.15.0 → 0.16.0

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/README.md CHANGED
@@ -3,7 +3,8 @@
3
3
  DomainKit's `Storage` on PostgreSQL, as one declarative [CapsuleDB](https://github.com/aryasaatvik/CapsuleDB)
4
4
  capsule. Install it under `DomainKit.layer` and the whole durable lifecycle — provider
5
5
  authorizations, connections, attachments, interactive-flow continuations, plan/approval/receipt
6
- attempts, and observed readiness — lives in your database, scoped to your tenants.
6
+ attempts, multi-domain batches, and observed readiness — lives in your database, scoped to your
7
+ tenants.
7
8
 
8
9
  The host owns the `SqlClient` and its lifetime. This package owns its own tables and never exposes
9
10
  rows, queries, or a raw client.
@@ -74,14 +75,20 @@ folder against the current capsule in CI.
74
75
 
75
76
  ## Tables
76
77
 
77
- | Table | Key | Holds |
78
- | -------------------------- | --------------------------------- | -------------------------------------------------------------------------------- |
79
- | `domainkit_authorizations` | `id` | provider grant, account label, capabilities, revocation state, sealed credential |
80
- | `domainkit_connections` | `id` | the principal-facing handle over one authorization |
81
- | `domainkit_attachments` | `id`, unique `(owner_id, domain)` | domain, zone, provider target |
82
- | `domainkit_continuations` | `id` | interactive-flow state with a TTL |
83
- | `domainkit_attempts` | `id` | plan, approval, receipt, status, lease, failure |
84
- | `domainkit_readiness` | `(owner_id, domain)` | latest observation, per-requirement evidence, backoff |
78
+ | Table | Key | Holds |
79
+ | -------------------------- | ------------------------------------------ | -------------------------------------------------------------------------------- |
80
+ | `domainkit_authorizations` | `id` | provider grant, account label, capabilities, revocation state, sealed credential |
81
+ | `domainkit_connections` | `id` | the principal-facing handle over one authorization |
82
+ | `domainkit_attachments` | `id`, unique `(owner_id, domain)` | domain, zone, provider target |
83
+ | `domainkit_continuations` | `id` | interactive-flow state with a TTL |
84
+ | `domainkit_attempts` | `id` | plan, approval, receipt, status, lease, failure |
85
+ | `domainkit_readiness` | `(owner_id, domain)` | latest observation, per-requirement evidence, backoff |
86
+ | `domainkit_batches` | `id`, unique `(owner_id, idempotency_key)` | batch status, approval digest, rejection |
87
+ | `domainkit_batch_items` | `(batch_id, attachment_id)` | one domain's place in a batch: position, attempt pointer, plan failure |
88
+
89
+ A batch item is a pointer: the plan, approval, receipt, lease, and failure it shows a customer all
90
+ live on the attempt it names, so nothing is stored twice and the batch's status is recomputed from
91
+ those attempts inside the transaction that moves it.
85
92
 
86
93
  Readiness is keyed by domain rather than by attachment, so a host observing public DNS alone gets
87
94
  the same row; `attachment_id` links the attachment when one exists and is cleared when it is
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.15.0";
7
+ var version = "0.16.0";
8
8
  //#endregion
9
9
  //#region src/internal/storage.ts
10
10
  /**
@@ -59,6 +59,8 @@ const attachmentCodec = codec(Storage.Attachment, "attachment");
59
59
  const continuationCodec = codec(Storage.Continuation, "continuation");
60
60
  const continuationHeaderCodec = codec(Storage.ContinuationHeader, "continuation header");
61
61
  const attemptCodec = codec(Storage.Attempt, "attempt");
62
+ const batchCodec = codec(Storage.Batch, "batch");
63
+ const batchItemCodec = codec(Storage.BatchItem, "batch item");
62
64
  const readinessCodec = codec(Storage.Readiness, "readiness");
63
65
  const credentialCodec = codec(Storage.Credential, "credential");
64
66
  /** A `TIMESTAMPTZ` column as the ISO string every DomainKit timestamp schema encodes to. */
@@ -142,6 +144,27 @@ const attemptOf = (row) => attemptCodec.read({
142
144
  failure: row.failure,
143
145
  updatedAt: iso(row.updated_at)
144
146
  });
147
+ const batchOf = (row) => batchCodec.read({
148
+ id: row.id,
149
+ ownerId: row.owner_id,
150
+ kind: row.kind,
151
+ status: row.status,
152
+ digest: row.digest,
153
+ approval: fromJsonOrNull(row.approval),
154
+ rejection: fromJsonOrNull(row.rejection),
155
+ idempotencyKey: row.idempotency_key,
156
+ createdBy: row.created_by,
157
+ createdAt: iso(row.created_at),
158
+ updatedAt: iso(row.updated_at),
159
+ completedAt: isoOrNull(row.completed_at)
160
+ });
161
+ const batchItemOf = (row) => batchItemCodec.read({
162
+ batchId: row.batch_id,
163
+ attachmentId: row.attachment_id,
164
+ position: row.position,
165
+ attemptId: row.attempt_id,
166
+ planFailure: row.plan_failure
167
+ });
145
168
  const readinessOf = (row) => readinessCodec.read({
146
169
  domain: row.domain,
147
170
  attachmentId: row.attachment_id,
@@ -157,6 +180,11 @@ const stale = (attempt) => fail(new Reason.Stale({
157
180
  planId: attempt.id,
158
181
  digest: attempt.plan.digest
159
182
  }));
183
+ const batchStale = (batch) => fail(new Reason.BatchStale({
184
+ batchId: batch.id,
185
+ status: batch.status,
186
+ digest: batch.digest
187
+ }));
160
188
  /** `prefix_<uuid>`, the same identifier shape the memory implementation mints. */
161
189
  const fresh = (prefix) => Effect.sync(() => `${prefix}_${crypto.randomUUID()}`);
162
190
  const make$2 = (tables) => Effect.gen(function* () {
@@ -167,6 +195,8 @@ const make$2 = (tables) => Effect.gen(function* () {
167
195
  const continuations = sql(tables.continuations.name);
168
196
  const attempts = sql(tables.attempts.name);
169
197
  const readiness = sql(tables.readiness.name);
198
+ const batches = sql(tables.batches.name);
199
+ const batchItems = sql(tables.batchItems.name);
170
200
  /** The row this principal owns, locked for the rest of the transaction. */
171
201
  const lockedAuthorization = (owner, id) => sql`
172
202
  SELECT * FROM ${authorizations} WHERE id = ${id} AND owner_id = ${owner} FOR UPDATE
@@ -212,6 +242,71 @@ const make$2 = (tables) => Effect.gen(function* () {
212
242
  DELETE FROM ${authorizations}
213
243
  WHERE id = ${id} AND owner_id = ${owner} AND credential_ciphertext = ${ciphertext}
214
244
  `;
245
+ const requireBatch = (owner, id) => sql`
246
+ SELECT * FROM ${batches} WHERE id = ${id} AND owner_id = ${owner}
247
+ `.pipe(Effect.flatMap((rows) => rows[0] === void 0 ? notFound("batch", id) : Effect.succeed(rows[0])), Effect.flatMap(batchOf));
248
+ /** The batch this principal owns, locked for the rest of the transaction. */
249
+ const lockedBatch = (owner, id) => sql`
250
+ SELECT * FROM ${batches} WHERE id = ${id} AND owner_id = ${owner} FOR UPDATE
251
+ `.pipe(Effect.flatMap((rows) => rows[0] === void 0 ? notFound("batch", id) : Effect.succeed(rows[0])), Effect.flatMap(batchOf));
252
+ const requireAttempt = (owner, id) => sql`
253
+ SELECT * FROM ${attempts} WHERE id = ${id} AND owner_id = ${owner}
254
+ `.pipe(Effect.flatMap((rows) => rows[0] === void 0 ? notFound("plan", id) : Effect.succeed(rows[0])));
255
+ /**
256
+ * A batch's items in `position` order, each with its attempt's status, which is what the
257
+ * aggregate's own status is recomputed from. The batch was already read under its owner, and
258
+ * the join carries the same filter so an item can only ever reach that owner's attempts.
259
+ */
260
+ const itemRows = (owner, batchId) => sql`
261
+ SELECT item.batch_id, item.attachment_id, item."position", item.attempt_id,
262
+ item.plan_failure, attempt.status AS attempt_status
263
+ FROM ${batchItems} AS item
264
+ LEFT JOIN ${attempts} AS attempt
265
+ ON attempt.id = item.attempt_id AND attempt.owner_id = ${owner}
266
+ WHERE item.batch_id = ${batchId}
267
+ ORDER BY item."position" ASC
268
+ `;
269
+ const aggregateOf = (owner, batch) => itemRows(owner, batch.id).pipe(Effect.flatMap((rows) => Effect.forEach(rows, batchItemOf)), Effect.map((items) => ({
270
+ batch,
271
+ items
272
+ })));
273
+ /**
274
+ * Write `batch` with its status recomputed from the items' attempts.
275
+ *
276
+ * Every transition ends here, inside the transaction that locked the row, so the stored status
277
+ * and the owner-scoped unfinished index never disagree with the attempts they summarize.
278
+ */
279
+ const settled = (owner, batch) => Effect.gen(function* () {
280
+ const rows = yield* itemRows(owner, batch.id);
281
+ const items = yield* Effect.forEach(rows, batchItemOf);
282
+ const status = Storage.batchStatusOf({
283
+ approved: batch.approval !== null,
284
+ rejected: batch.rejection !== null,
285
+ items: rows.map((row) => row.attempt_id === null ? null : row.attempt_status)
286
+ });
287
+ const instant = yield* DateTime.now;
288
+ const next = new Storage.Batch({
289
+ ...batch,
290
+ status,
291
+ completedAt: status === "complete" || status === "rejected" ? instant : null,
292
+ updatedAt: instant
293
+ });
294
+ const encoded = yield* batchCodec.write(next);
295
+ yield* sql`
296
+ UPDATE ${batches} SET
297
+ status = ${encoded.status},
298
+ digest = ${encoded.digest},
299
+ approval = ${toJsonOrNull(encoded.approval)},
300
+ rejection = ${toJsonOrNull(encoded.rejection)},
301
+ completed_at = ${atOrNull(encoded.completedAt)},
302
+ updated_at = ${at(encoded.updatedAt)}
303
+ WHERE id = ${batch.id} AND owner_id = ${owner}
304
+ `;
305
+ return {
306
+ batch: next,
307
+ items
308
+ };
309
+ });
215
310
  return {
216
311
  authorizations: {
217
312
  upsert: ({ authorization, credential, expectedId }) => Effect.flatMap(Principal.Service, ({ ownerId }) => Effect.gen(function* () {
@@ -593,6 +688,198 @@ const make$2 = (tables) => Effect.gen(function* () {
593
688
  return next;
594
689
  }))).pipe(guard("attempts.fail"))
595
690
  },
691
+ batches: {
692
+ create: (input) => Effect.flatMap(Principal.Service, ({ actorId, ownerId }) => sql.withTransaction(Effect.gen(function* () {
693
+ const replayed = (row) => Effect.flatMap(batchOf(row), (batch) => aggregateOf(ownerId, batch));
694
+ const existing = yield* sql`
695
+ SELECT * FROM ${batches}
696
+ WHERE owner_id = ${ownerId} AND idempotency_key = ${input.idempotencyKey}
697
+ `;
698
+ if (existing[0] !== void 0) return yield* replayed(existing[0]);
699
+ if (input.attachmentIds.length === 0) return yield* invalid("A batch needs at least one attachment", "attachmentIds");
700
+ if (new Set(input.attachmentIds).size !== input.attachmentIds.length) return yield* invalid("A batch holds one item per attachment", "attachmentIds");
701
+ for (const attachmentId of input.attachmentIds) yield* requireAttachment(ownerId, attachmentId);
702
+ const instant = yield* DateTime.now;
703
+ const batch = new Storage.Batch({
704
+ id: Storage.BatchId.make(yield* fresh("batch")),
705
+ ownerId,
706
+ kind: input.kind,
707
+ status: "planning",
708
+ digest: null,
709
+ approval: null,
710
+ rejection: null,
711
+ idempotencyKey: input.idempotencyKey,
712
+ createdBy: actorId,
713
+ createdAt: instant,
714
+ updatedAt: instant,
715
+ completedAt: null
716
+ });
717
+ const encoded = yield* batchCodec.write(batch);
718
+ if ((yield* sql`
719
+ INSERT INTO ${batches} (
720
+ id, owner_id, kind, status, digest, approval, rejection, idempotency_key,
721
+ created_by, created_at, updated_at, completed_at
722
+ ) VALUES (
723
+ ${encoded.id}, ${encoded.ownerId}, ${encoded.kind}, ${encoded.status},
724
+ ${encoded.digest}, ${toJsonOrNull(encoded.approval)},
725
+ ${toJsonOrNull(encoded.rejection)}, ${encoded.idempotencyKey},
726
+ ${encoded.createdBy}, ${at(encoded.createdAt)}, ${at(encoded.updatedAt)},
727
+ ${atOrNull(encoded.completedAt)}
728
+ ) ON CONFLICT (owner_id, idempotency_key) DO NOTHING RETURNING id
729
+ `)[0] === void 0) {
730
+ const winner = yield* sql`
731
+ SELECT * FROM ${batches}
732
+ WHERE owner_id = ${ownerId} AND idempotency_key = ${input.idempotencyKey}
733
+ `;
734
+ return winner[0] === void 0 ? yield* notFound("batch", input.idempotencyKey) : yield* replayed(winner[0]);
735
+ }
736
+ const items = input.attachmentIds.map((attachmentId, position) => new Storage.BatchItem({
737
+ batchId: batch.id,
738
+ attachmentId,
739
+ position,
740
+ attemptId: null,
741
+ planFailure: null
742
+ }));
743
+ for (const item of items) yield* sql`
744
+ INSERT INTO ${batchItems} (
745
+ batch_id, attachment_id, "position", attempt_id, plan_failure
746
+ ) VALUES (
747
+ ${item.batchId}, ${item.attachmentId}, ${item.position}, ${item.attemptId},
748
+ ${item.planFailure}
749
+ )
750
+ `;
751
+ return {
752
+ batch,
753
+ items
754
+ };
755
+ }))).pipe(guard("batches.create")),
756
+ get: (id) => Effect.flatMap(Principal.Service, ({ ownerId }) => Effect.flatMap(requireBatch(ownerId, id), (batch) => aggregateOf(ownerId, batch))).pipe(guard("batches.get")),
757
+ byIdempotencyKey: (key) => Effect.flatMap(Principal.Service, ({ ownerId }) => sql`
758
+ SELECT * FROM ${batches}
759
+ WHERE owner_id = ${ownerId} AND idempotency_key = ${key}
760
+ `.pipe(Effect.flatMap((rows) => rows[0] === void 0 ? Effect.succeedNone : Effect.flatMap(batchOf(rows[0]), (batch) => Effect.map(aggregateOf(ownerId, batch), Option.some))))).pipe(guard("batches.byIdempotencyKey")),
761
+ listUnfinished: () => Effect.flatMap(Principal.Service, ({ ownerId }) => Effect.gen(function* () {
762
+ const rows = yield* sql`
763
+ SELECT * FROM ${batches}
764
+ WHERE owner_id = ${ownerId} AND status NOT IN ('complete', 'rejected')
765
+ ORDER BY updated_at DESC
766
+ `;
767
+ if (rows.length === 0) return [];
768
+ const list = yield* Effect.forEach(rows, batchOf);
769
+ const itemsRows = yield* sql`
770
+ SELECT batch_id, attachment_id, "position", attempt_id, plan_failure
771
+ FROM ${batchItems}
772
+ WHERE ${sql.in("batch_id", list.map(({ id }) => id))}
773
+ ORDER BY "position" ASC
774
+ `;
775
+ const items = yield* Effect.forEach(itemsRows, batchItemOf);
776
+ return list.map((batch) => ({
777
+ batch,
778
+ items: items.filter((item) => item.batchId === batch.id)
779
+ }));
780
+ })).pipe(guard("batches.listUnfinished")),
781
+ recordItemPlan: (id, attachmentId, attemptId) => Effect.flatMap(Principal.Service, ({ ownerId }) => sql.withTransaction(Effect.gen(function* () {
782
+ const batch = yield* lockedBatch(ownerId, id);
783
+ if (batch.status !== "planning" && batch.status !== "planned") return yield* batchStale(batch);
784
+ const attempt = yield* requireAttempt(ownerId, attemptId);
785
+ if (attempt.attachment_id !== attachmentId || attempt.kind !== batch.kind) return yield* invalid(`Plan ${attemptId} does not belong to attachment ${attachmentId} in this batch`, "attemptId");
786
+ return (yield* sql`
787
+ UPDATE ${batchItems} SET attempt_id = ${attemptId}, plan_failure = NULL
788
+ WHERE batch_id = ${id} AND attachment_id = ${attachmentId}
789
+ RETURNING attachment_id
790
+ `)[0] === void 0 ? yield* notFound("attachment", attachmentId) : yield* settled(ownerId, batch);
791
+ }))).pipe(guard("batches.recordItemPlan")),
792
+ recordItemPlanFailure: (id, attachmentId, message) => Effect.flatMap(Principal.Service, ({ ownerId }) => sql.withTransaction(Effect.gen(function* () {
793
+ const batch = yield* lockedBatch(ownerId, id);
794
+ if (batch.status !== "planning" && batch.status !== "planned") return yield* batchStale(batch);
795
+ return (yield* sql`
796
+ UPDATE ${batchItems} SET attempt_id = NULL, plan_failure = ${message}
797
+ WHERE batch_id = ${id} AND attachment_id = ${attachmentId}
798
+ RETURNING attachment_id
799
+ `)[0] === void 0 ? yield* notFound("attachment", attachmentId) : yield* settled(ownerId, batch);
800
+ }))).pipe(guard("batches.recordItemPlanFailure")),
801
+ approve: (id, input) => Effect.flatMap(Principal.Service, ({ ownerId }) => sql.withTransaction(Effect.gen(function* () {
802
+ const batch = yield* lockedBatch(ownerId, id);
803
+ if (batch.approval !== null) return batch.digest === input.digest ? yield* aggregateOf(ownerId, batch) : yield* batchStale(batch);
804
+ if (batch.status !== "planned") return yield* batchStale(batch);
805
+ const items = yield* Effect.forEach(yield* itemRows(ownerId, id), batchItemOf);
806
+ const pairs = [];
807
+ for (const item of items) {
808
+ const supplied = input.approvals.find((entry) => entry.attachmentId === item.attachmentId);
809
+ if (supplied === void 0) return yield* invalid(`Batch ${id} has no approval for attachment ${item.attachmentId}`, "approvals");
810
+ if (item.attemptId === null || item.attemptId !== supplied.approval.planId) return yield* batchStale(batch);
811
+ pairs.push({
812
+ attemptId: item.attemptId,
813
+ approval: supplied.approval
814
+ });
815
+ }
816
+ const instant = yield* DateTime.now;
817
+ for (const pair of pairs) {
818
+ const current = yield* lockedAttempt(ownerId, pair.attemptId);
819
+ if (current.approval?.id === pair.approval.id) continue;
820
+ if (current.status !== "planned") return yield* stale(current);
821
+ const next = new Storage.Attempt({
822
+ ...current,
823
+ status: "approved",
824
+ approval: pair.approval,
825
+ updatedAt: instant
826
+ });
827
+ const encoded = yield* attemptCodec.write(next);
828
+ yield* sql`
829
+ UPDATE ${attempts} SET
830
+ status = ${encoded.status},
831
+ approval = ${toJsonOrNull(encoded.approval)},
832
+ approval_id = ${pair.approval.id},
833
+ updated_at = ${at(encoded.updatedAt)}
834
+ WHERE id = ${pair.attemptId} AND owner_id = ${ownerId}
835
+ `;
836
+ }
837
+ return yield* settled(ownerId, new Storage.Batch({
838
+ ...batch,
839
+ digest: input.digest,
840
+ approval: {
841
+ actorId: input.actorId,
842
+ at: instant
843
+ }
844
+ }));
845
+ }))).pipe(guard("batches.approve")),
846
+ reject: (id, input) => Effect.flatMap(Principal.Service, ({ ownerId }) => sql.withTransaction(Effect.gen(function* () {
847
+ const batch = yield* lockedBatch(ownerId, id);
848
+ if (batch.rejection !== null) return yield* aggregateOf(ownerId, batch);
849
+ if (batch.status !== "planning" && batch.status !== "planned") return yield* batchStale(batch);
850
+ const rows = yield* itemRows(ownerId, id);
851
+ const instant = yield* DateTime.now;
852
+ const rejection = {
853
+ actorId: input.actorId,
854
+ reason: input.reason,
855
+ at: instant
856
+ };
857
+ for (const row of rows) {
858
+ if (row.attempt_id === null || row.attempt_status !== "planned") continue;
859
+ const current = yield* lockedAttempt(ownerId, row.attempt_id);
860
+ if (current.status !== "planned") continue;
861
+ const next = new Storage.Attempt({
862
+ ...current,
863
+ status: "rejected",
864
+ rejection,
865
+ updatedAt: instant
866
+ });
867
+ const encoded = yield* attemptCodec.write(next);
868
+ yield* sql`
869
+ UPDATE ${attempts} SET
870
+ status = ${encoded.status},
871
+ rejection = ${toJsonOrNull(encoded.rejection)},
872
+ updated_at = ${at(encoded.updatedAt)}
873
+ WHERE id = ${row.attempt_id} AND owner_id = ${ownerId}
874
+ `;
875
+ }
876
+ return yield* settled(ownerId, new Storage.Batch({
877
+ ...batch,
878
+ rejection
879
+ }));
880
+ }))).pipe(guard("batches.reject")),
881
+ refresh: (id) => Effect.flatMap(Principal.Service, ({ ownerId }) => sql.withTransaction(Effect.flatMap(lockedBatch(ownerId, id), (batch) => settled(ownerId, batch)))).pipe(guard("batches.refresh"))
882
+ },
596
883
  readiness: {
597
884
  put: (row) => Effect.flatMap(Principal.Service, ({ ownerId }) => Effect.gen(function* () {
598
885
  if (row.ownerId !== ownerId) return yield* invalid("Readiness owner does not match the principal", "ownerId");
@@ -633,7 +920,7 @@ const make$2 = (tables) => Effect.gen(function* () {
633
920
  //#endregion
634
921
  //#region src/internal/tables.ts
635
922
  /**
636
- * The six tables DomainKit owns, declared once and rendered per dialect by CapsuleDB.
923
+ * The eight tables DomainKit owns, declared once and rendered per dialect by CapsuleDB.
637
924
  *
638
925
  * Every table carries `owner_id` and every query filters by it: tenancy is a column, not a schema.
639
926
  * There are no foreign keys to host tables, and none between DomainKit's own tables either, so a
@@ -642,7 +929,7 @@ const make$2 = (tables) => Effect.gen(function* () {
642
929
  /** Default table prefix. Part of the physical layout, so it is immutable after the first deploy. */
643
930
  const DEFAULT_PREFIX = "domainkit";
644
931
  /**
645
- * Declare the six tables under `prefix`.
932
+ * Declare the eight tables under `prefix`.
646
933
  *
647
934
  * `Schema.table` validates every identifier it will quote, so an invalid prefix throws
648
935
  * `CapsuleDefinitionError` here rather than reaching a renderer.
@@ -764,6 +1051,46 @@ const make$1 = (prefix) => ({
764
1051
  },
765
1052
  primaryKey: ["owner_id", "domain"],
766
1053
  indexes: [{ columns: ["owner_id", "next_check_at"] }, { columns: ["attachment_id"] }]
1054
+ }),
1055
+ batches: Schema.table(`${prefix}_batches`, {
1056
+ columns: {
1057
+ id: Schema.text(),
1058
+ owner_id: Schema.text(),
1059
+ kind: Schema.text(),
1060
+ status: Schema.text(),
1061
+ /** SHA-256 over the items' `attachmentId:planDigest` pairs; set when the batch is approved. */
1062
+ digest: Schema.text({ nullable: true }),
1063
+ /** Who bound the digest, and when; the per-attempt approvals live on the attempts. */
1064
+ approval: Schema.json({ nullable: true }),
1065
+ rejection: Schema.json({ nullable: true }),
1066
+ idempotency_key: Schema.text(),
1067
+ created_by: Schema.text(),
1068
+ created_at: Schema.timestamp(),
1069
+ updated_at: Schema.timestamp(),
1070
+ /** When the batch reached `complete` or `rejected`; null while it still owes a move. */
1071
+ completed_at: Schema.timestamp({ nullable: true })
1072
+ },
1073
+ primaryKey: ["id"],
1074
+ uniques: [["owner_id", "idempotency_key"]],
1075
+ indexes: [{ columns: [
1076
+ "owner_id",
1077
+ "status",
1078
+ "updated_at"
1079
+ ] }]
1080
+ }),
1081
+ batchItems: Schema.table(`${prefix}_batch_items`, {
1082
+ columns: {
1083
+ batch_id: Schema.text(),
1084
+ attachment_id: Schema.text(),
1085
+ /** The item's place in the batch, as `batches.create` received it. */
1086
+ position: Schema.integer(),
1087
+ /** The attempt carrying this item's plan; null until one lands. */
1088
+ attempt_id: Schema.text({ nullable: true }),
1089
+ /** Why the last planning pass stopped here; cleared when a plan lands. */
1090
+ plan_failure: Schema.text({ nullable: true })
1091
+ },
1092
+ primaryKey: ["batch_id", "attachment_id"],
1093
+ indexes: [{ columns: ["attempt_id"] }]
767
1094
  })
768
1095
  });
769
1096
  /**
@@ -813,6 +1140,17 @@ const attachmentsV1 = (prefix) => Schema.table(`${prefix}_attachments`, {
813
1140
  indexes: [{ columns: ["owner_id", "connection_id"] }]
814
1141
  });
815
1142
  const list = (tables) => [
1143
+ ...initial(tables),
1144
+ tables.batches,
1145
+ tables.batchItems
1146
+ ];
1147
+ /**
1148
+ * The tables the first migration creates.
1149
+ *
1150
+ * A migration is history: what it renders must not move, so a table added later is declared above
1151
+ * and created by its own migration rather than joining this list.
1152
+ */
1153
+ const initial = (tables) => [
816
1154
  tables.authorizations,
817
1155
  tables.connections,
818
1156
  tables.attachments,
@@ -823,7 +1161,7 @@ const list = (tables) => [
823
1161
  //#endregion
824
1162
  //#region src/capsule.ts
825
1163
  /**
826
- * DomainKit's CapsuleDB capsule: six tables and one `Storage.Service` implementation.
1164
+ * DomainKit's CapsuleDB capsule: eight tables and one `Storage.Service` implementation.
827
1165
  *
828
1166
  * The capsule is a plain value, so a host imports it, points `capsuledb emit` at it, or hands it
829
1167
  * to `Registry.layer` without running an Effect first.
@@ -844,7 +1182,7 @@ const make = (prefix = DEFAULT_PREFIX) => {
844
1182
  id: 1,
845
1183
  name: "create-storage",
846
1184
  risk: "additive",
847
- steps: list(tables).map((table) => Migration.createTable(table.name === tables.attachments.name ? attachmentsV1(prefix) : table.name === tables.authorizations.name ? authorizationsV1(prefix) : table))
1185
+ steps: initial(tables).map((table) => Migration.createTable(table.name === tables.attachments.name ? attachmentsV1(prefix) : table.name === tables.authorizations.name ? authorizationsV1(prefix) : table))
848
1186
  }),
849
1187
  Migration.make({
850
1188
  id: 2,
@@ -863,6 +1201,12 @@ const make = (prefix = DEFAULT_PREFIX) => {
863
1201
  type: "text",
864
1202
  nullable: true
865
1203
  })]
1204
+ }),
1205
+ Migration.make({
1206
+ id: 4,
1207
+ name: "batches",
1208
+ risk: "additive",
1209
+ steps: [Migration.createTable(tables.batches), Migration.createTable(tables.batchItems)]
866
1210
  })
867
1211
  ],
868
1212
  layer: Layer.effect(Storage.Service)(make$2(tables))
@@ -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 continuationHeaderCodec = codec(Storage.ContinuationHeader, \"continuation header\");\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 label: string | null;\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 label: row.label,\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\ntype ContinuationHeaderRow = Pick<\n ContinuationRow,\n \"owner_id\" | \"actor_id\" | \"provider\" | \"expires_at\"\n>;\n\nconst continuationHeaderOf = (row: ContinuationHeaderRow) =>\n continuationHeaderCodec.read({\n ownerId: row.owner_id,\n actorId: row.actor_id,\n provider: row.provider,\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 label = ${row.label},\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, label, 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.label},\n ${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 header: (id) =>\n Effect.gen(function* () {\n // No owner filter, unlike everything else in this module: the provider callback has to\n // learn whose flow it is finishing before it can resolve a principal to scope by. The\n // projection is the enforcement — `payload` is never selected, so the PKCE verifier\n // stays behind the owner-scoped `get`.\n const rows = yield* sql<ContinuationHeaderRow>`\n SELECT owner_id, actor_id, provider, expires_at\n FROM ${continuations} WHERE id = ${id}\n `;\n if (rows[0] === undefined) return yield* notFound(\"continuation\", id);\n const header = yield* continuationHeaderOf(rows[0]);\n const instant = yield* DateTime.now;\n return DateTime.toEpochMillis(header.expiresAt) <= DateTime.toEpochMillis(instant)\n ? yield* fail(new Reason.Expired({ entity: \"continuation\", id }))\n : header;\n }).pipe(guard(\"continuations.header\")),\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 /**\n * What the provider called the account when the credential was issued, so a UI names the\n * connection offline. Null names no account, which is also what rows written before the\n * column existed carry.\n */\n label: Schema.text({ nullable: true }),\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 authorizations table as the first migration created it, before `label`.\n *\n * Frozen for the same reason as `attachmentsV1`: migration 1 renders this shape, and the migration\n * that adds the column carries the difference.\n */\nexport const authorizationsV1 = (prefix: string): Schema.Table =>\n 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\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 {\n attachmentsV1,\n authorizationsV1,\n DEFAULT_PREFIX,\n list,\n make as makeTables,\n} 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\n ? attachmentsV1(prefix)\n : table.name === tables.authorizations.name\n ? authorizationsV1(prefix)\n : 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 // An installation that connected accounts before the column existed keeps those rows\n // unnamed: the provider named the account at connect time, and nothing here can name it\n // after the fact without a credential.\n Migration.make({\n id: 3,\n name: \"authorization-label\",\n risk: \"additive\",\n steps: [\n Migration.addColumn(tables.authorizations.name, \"label\", {\n type: \"text\",\n nullable: true,\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 \"./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,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O,YAAY,KAAK,mCAAmC,CACxE,CAAC,CACH,CACF,CACF;GACF,CAAC;GAID,UAAU,KAAK;IACb,IAAI;IACJ,MAAM;IACN,MAAM;IACN,OAAO,CACL,UAAU,UAAU,OAAO,eAAe,MAAM,SAAS;KACvD,MAAM;KACN,UAAU;IACZ,CAAC,CACH;GACF,CAAC;EACH;EACA,OAAO,MAAM,OAAO,QAAQ,OAAO,CAAC,CAACC,OAAY,MAAM,CAAC;CAC1D,CAAC;AACH;;AAGA,MAAa,UAAwE,KAAK;;;;;;;;;;;;;;AC5D1F,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 { type Approval, DomainKit, type Plan, 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 continuationHeaderCodec = codec(Storage.ContinuationHeader, \"continuation header\");\nconst attemptCodec = codec(Storage.Attempt, \"attempt\");\nconst batchCodec = codec(Storage.Batch, \"batch\");\nconst batchItemCodec = codec(Storage.BatchItem, \"batch item\");\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 label: string | null;\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 BatchRow {\n readonly id: string;\n readonly owner_id: string;\n readonly kind: string;\n readonly status: string;\n readonly digest: string | null;\n readonly approval: unknown;\n readonly rejection: unknown;\n readonly idempotency_key: string;\n readonly created_by: string;\n readonly created_at: unknown;\n readonly updated_at: unknown;\n readonly completed_at: unknown;\n}\n\ninterface BatchItemRow {\n readonly batch_id: string;\n readonly attachment_id: string;\n readonly position: number;\n readonly attempt_id: string | null;\n readonly plan_failure: string | null;\n}\n\n/** An item row with its attempt's status joined in; null while the item carries no plan. */\ninterface BatchItemStatusRow extends BatchItemRow {\n readonly attempt_status: string | null;\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 label: row.label,\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\ntype ContinuationHeaderRow = Pick<\n ContinuationRow,\n \"owner_id\" | \"actor_id\" | \"provider\" | \"expires_at\"\n>;\n\nconst continuationHeaderOf = (row: ContinuationHeaderRow) =>\n continuationHeaderCodec.read({\n ownerId: row.owner_id,\n actorId: row.actor_id,\n provider: row.provider,\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 batchOf = (row: BatchRow) =>\n batchCodec.read({\n id: row.id,\n ownerId: row.owner_id,\n kind: row.kind,\n status: row.status,\n digest: row.digest,\n approval: fromJsonOrNull(row.approval),\n rejection: fromJsonOrNull(row.rejection),\n idempotencyKey: row.idempotency_key,\n createdBy: row.created_by,\n createdAt: iso(row.created_at),\n updatedAt: iso(row.updated_at),\n completedAt: isoOrNull(row.completed_at),\n });\n\nconst batchItemOf = (row: BatchItemRow) =>\n batchItemCodec.read({\n batchId: row.batch_id,\n attachmentId: row.attachment_id,\n position: row.position,\n attemptId: row.attempt_id,\n planFailure: row.plan_failure,\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\nconst batchStale = (batch: Storage.Batch) =>\n fail(new Reason.BatchStale({ batchId: batch.id, status: batch.status, digest: batch.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 const batches = sql(tables.batches.name);\n const batchItems = sql(tables.batchItems.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 requireBatch = (owner: string, id: string) =>\n sql<BatchRow>`\n SELECT * FROM ${batches} WHERE id = ${id} AND owner_id = ${owner}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"batch\", id) : Effect.succeed(rows[0]),\n ),\n Effect.flatMap(batchOf),\n );\n\n /** The batch this principal owns, locked for the rest of the transaction. */\n const lockedBatch = (owner: string, id: string) =>\n sql<BatchRow>`\n SELECT * FROM ${batches} WHERE id = ${id} AND owner_id = ${owner} FOR UPDATE\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"batch\", id) : Effect.succeed(rows[0]),\n ),\n Effect.flatMap(batchOf),\n );\n\n const requireAttempt = (owner: string, id: string) =>\n sql<AttemptRow>`\n SELECT * FROM ${attempts} WHERE id = ${id} AND owner_id = ${owner}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined ? notFound(\"plan\", id) : Effect.succeed(rows[0]),\n ),\n );\n\n /**\n * A batch's items in `position` order, each with its attempt's status, which is what the\n * aggregate's own status is recomputed from. The batch was already read under its owner, and\n * the join carries the same filter so an item can only ever reach that owner's attempts.\n */\n const itemRows = (owner: string, batchId: string) =>\n sql<BatchItemStatusRow>`\n SELECT item.batch_id, item.attachment_id, item.\"position\", item.attempt_id,\n item.plan_failure, attempt.status AS attempt_status\n FROM ${batchItems} AS item\n LEFT JOIN ${attempts} AS attempt\n ON attempt.id = item.attempt_id AND attempt.owner_id = ${owner}\n WHERE item.batch_id = ${batchId}\n ORDER BY item.\"position\" ASC\n `;\n\n const aggregateOf = (\n owner: string,\n batch: Storage.Batch,\n ): Effect.Effect<Storage.BatchAggregate, Fail | SqlError.SqlError> =>\n itemRows(owner, batch.id).pipe(\n Effect.flatMap((rows) => Effect.forEach(rows, batchItemOf)),\n Effect.map((items) => ({ batch, items })),\n );\n\n /**\n * Write `batch` with its status recomputed from the items' attempts.\n *\n * Every transition ends here, inside the transaction that locked the row, so the stored status\n * and the owner-scoped unfinished index never disagree with the attempts they summarize.\n */\n const settled = (\n owner: string,\n batch: Storage.Batch,\n ): Effect.Effect<Storage.BatchAggregate, Fail | SqlError.SqlError> =>\n Effect.gen(function* () {\n const rows = yield* itemRows(owner, batch.id);\n const items = yield* Effect.forEach(rows, batchItemOf);\n const status = Storage.batchStatusOf({\n approved: batch.approval !== null,\n rejected: batch.rejection !== null,\n items: rows.map((row) =>\n row.attempt_id === null ? null : (row.attempt_status as Storage.AttemptStatus | null),\n ),\n });\n const instant = yield* DateTime.now;\n const next = new Storage.Batch({\n ...batch,\n status,\n completedAt: status === \"complete\" || status === \"rejected\" ? instant : null,\n updatedAt: instant,\n });\n const encoded = yield* batchCodec.write(next);\n yield* sql`\n UPDATE ${batches} SET\n status = ${encoded.status},\n digest = ${encoded.digest},\n approval = ${toJsonOrNull(encoded.approval)},\n rejection = ${toJsonOrNull(encoded.rejection)},\n completed_at = ${atOrNull(encoded.completedAt)},\n updated_at = ${at(encoded.updatedAt)}\n WHERE id = ${batch.id} AND owner_id = ${owner}\n `;\n return { batch: next, items };\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 label = ${row.label},\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, label, 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.label},\n ${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 header: (id) =>\n Effect.gen(function* () {\n // No owner filter, unlike everything else in this module: the provider callback has to\n // learn whose flow it is finishing before it can resolve a principal to scope by. The\n // projection is the enforcement — `payload` is never selected, so the PKCE verifier\n // stays behind the owner-scoped `get`.\n const rows = yield* sql<ContinuationHeaderRow>`\n SELECT owner_id, actor_id, provider, expires_at\n FROM ${continuations} WHERE id = ${id}\n `;\n if (rows[0] === undefined) return yield* notFound(\"continuation\", id);\n const header = yield* continuationHeaderOf(rows[0]);\n const instant = yield* DateTime.now;\n return DateTime.toEpochMillis(header.expiresAt) <= DateTime.toEpochMillis(instant)\n ? yield* fail(new Reason.Expired({ entity: \"continuation\", id }))\n : header;\n }).pipe(guard(\"continuations.header\")),\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 batches: {\n create: (input) =>\n Effect.flatMap(Principal.Service, ({ actorId, ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const replayed = (row: BatchRow) =>\n Effect.flatMap(batchOf(row), (batch) => aggregateOf(ownerId, batch));\n const existing = yield* sql<BatchRow>`\n SELECT * FROM ${batches}\n WHERE owner_id = ${ownerId} AND idempotency_key = ${input.idempotencyKey}\n `;\n // A retried create is the same batch, whatever the second call asks for.\n if (existing[0] !== undefined) return yield* replayed(existing[0]);\n if (input.attachmentIds.length === 0) {\n return yield* invalid(\"A batch needs at least one attachment\", \"attachmentIds\");\n }\n if (new Set(input.attachmentIds).size !== input.attachmentIds.length) {\n return yield* invalid(\"A batch holds one item per attachment\", \"attachmentIds\");\n }\n for (const attachmentId of input.attachmentIds) {\n yield* requireAttachment(ownerId, attachmentId);\n }\n const instant = yield* DateTime.now;\n const batch = new Storage.Batch({\n id: Storage.BatchId.make(yield* fresh(\"batch\")),\n ownerId,\n kind: input.kind,\n status: \"planning\",\n digest: null,\n approval: null,\n rejection: null,\n idempotencyKey: input.idempotencyKey,\n createdBy: actorId,\n createdAt: instant,\n updatedAt: instant,\n completedAt: null,\n });\n const encoded = yield* batchCodec.write(batch);\n // The unique key decides the race rather than the read above: a concurrent create\n // under the same key loses the insert and reads the batch it lost to.\n const inserted = yield* sql<{ readonly id: string }>`\n INSERT INTO ${batches} (\n id, owner_id, kind, status, digest, approval, rejection, idempotency_key,\n created_by, created_at, updated_at, completed_at\n ) VALUES (\n ${encoded.id}, ${encoded.ownerId}, ${encoded.kind}, ${encoded.status},\n ${encoded.digest}, ${toJsonOrNull(encoded.approval)},\n ${toJsonOrNull(encoded.rejection)}, ${encoded.idempotencyKey},\n ${encoded.createdBy}, ${at(encoded.createdAt)}, ${at(encoded.updatedAt)},\n ${atOrNull(encoded.completedAt)}\n ) ON CONFLICT (owner_id, idempotency_key) DO NOTHING RETURNING id\n `;\n if (inserted[0] === undefined) {\n const winner = yield* sql<BatchRow>`\n SELECT * FROM ${batches}\n WHERE owner_id = ${ownerId} AND idempotency_key = ${input.idempotencyKey}\n `;\n return winner[0] === undefined\n ? yield* notFound(\"batch\", input.idempotencyKey)\n : yield* replayed(winner[0]);\n }\n const items = input.attachmentIds.map(\n (attachmentId, position) =>\n new Storage.BatchItem({\n batchId: batch.id,\n attachmentId,\n position,\n attemptId: null,\n planFailure: null,\n }),\n );\n for (const item of items) {\n yield* sql`\n INSERT INTO ${batchItems} (\n batch_id, attachment_id, \"position\", attempt_id, plan_failure\n ) VALUES (\n ${item.batchId}, ${item.attachmentId}, ${item.position}, ${item.attemptId},\n ${item.planFailure}\n )\n `;\n }\n return { batch, items };\n }),\n ),\n ).pipe(guard(\"batches.create\")),\n get: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.flatMap(requireBatch(ownerId, id), (batch) => aggregateOf(ownerId, batch)),\n ).pipe(guard(\"batches.get\")),\n byIdempotencyKey: (key) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql<BatchRow>`\n SELECT * FROM ${batches}\n WHERE owner_id = ${ownerId} AND idempotency_key = ${key}\n `.pipe(\n Effect.flatMap((rows) =>\n rows[0] === undefined\n ? Effect.succeedNone\n : Effect.flatMap(batchOf(rows[0]), (batch) =>\n Effect.map(aggregateOf(ownerId, batch), Option.some),\n ),\n ),\n ),\n ).pipe(guard(\"batches.byIdempotencyKey\")),\n listUnfinished: () =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n Effect.gen(function* () {\n const rows = yield* sql<BatchRow>`\n SELECT * FROM ${batches}\n WHERE owner_id = ${ownerId} AND status NOT IN ('complete', 'rejected')\n ORDER BY updated_at DESC\n `;\n if (rows.length === 0) return [];\n const list = yield* Effect.forEach(rows, batchOf);\n // Items are pointers, so the whole index is two queries: no attempt is read here.\n const itemsRows = yield* sql<BatchItemRow>`\n SELECT batch_id, attachment_id, \"position\", attempt_id, plan_failure\n FROM ${batchItems}\n WHERE ${sql.in(\n \"batch_id\",\n list.map(({ id }) => id),\n )}\n ORDER BY \"position\" ASC\n `;\n const items = yield* Effect.forEach(itemsRows, batchItemOf);\n return list.map((batch) => ({\n batch,\n items: items.filter((item) => item.batchId === batch.id),\n }));\n }),\n ).pipe(guard(\"batches.listUnfinished\")),\n recordItemPlan: (id, attachmentId, attemptId) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const batch = yield* lockedBatch(ownerId, id);\n // The fence: a planning pass still in flight must not land state on a batch the\n // principal declined, or on one already bound to an approved digest.\n if (batch.status !== \"planning\" && batch.status !== \"planned\") {\n return yield* batchStale(batch);\n }\n const attempt = yield* requireAttempt(ownerId, attemptId);\n if (attempt.attachment_id !== attachmentId || attempt.kind !== batch.kind) {\n return yield* invalid(\n `Plan ${attemptId} does not belong to attachment ${attachmentId} in this batch`,\n \"attemptId\",\n );\n }\n const updated = yield* sql<{ readonly attachment_id: string }>`\n UPDATE ${batchItems} SET attempt_id = ${attemptId}, plan_failure = NULL\n WHERE batch_id = ${id} AND attachment_id = ${attachmentId}\n RETURNING attachment_id\n `;\n return updated[0] === undefined\n ? yield* notFound(\"attachment\", attachmentId)\n : yield* settled(ownerId, batch);\n }),\n ),\n ).pipe(guard(\"batches.recordItemPlan\")),\n recordItemPlanFailure: (id, attachmentId, message) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const batch = yield* lockedBatch(ownerId, id);\n if (batch.status !== \"planning\" && batch.status !== \"planned\") {\n return yield* batchStale(batch);\n }\n const updated = yield* sql<{ readonly attachment_id: string }>`\n UPDATE ${batchItems} SET attempt_id = NULL, plan_failure = ${message}\n WHERE batch_id = ${id} AND attachment_id = ${attachmentId}\n RETURNING attachment_id\n `;\n return updated[0] === undefined\n ? yield* notFound(\"attachment\", attachmentId)\n : yield* settled(ownerId, batch);\n }),\n ),\n ).pipe(guard(\"batches.recordItemPlanFailure\")),\n approve: (id, input) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const batch = yield* lockedBatch(ownerId, id);\n // Replaying the same approval is how a retried request stays safe.\n if (batch.approval !== null) {\n return batch.digest === input.digest\n ? yield* aggregateOf(ownerId, batch)\n : yield* batchStale(batch);\n }\n if (batch.status !== \"planned\") return yield* batchStale(batch);\n const items = yield* Effect.forEach(yield* itemRows(ownerId, id), batchItemOf);\n const pairs: Array<{\n readonly attemptId: Plan.PlanId;\n readonly approval: Approval.Model;\n }> = [];\n for (const item of items) {\n const supplied = input.approvals.find(\n (entry) => entry.attachmentId === item.attachmentId,\n );\n if (supplied === undefined) {\n return yield* invalid(\n `Batch ${id} has no approval for attachment ${item.attachmentId}`,\n \"approvals\",\n );\n }\n // The item has to still point at the attempt this approval names: anything else\n // means the batch was re-planned after the principal reviewed it.\n if (item.attemptId === null || item.attemptId !== supplied.approval.planId) {\n return yield* batchStale(batch);\n }\n pairs.push({ attemptId: item.attemptId, approval: supplied.approval });\n }\n const instant = yield* DateTime.now;\n // The per-attempt approvals and the batch's own are one transaction: a batch is\n // never approved without the approvals `attempts.apply` takes.\n for (const pair of pairs) {\n const current = yield* lockedAttempt(ownerId, pair.attemptId);\n if (current.approval?.id === pair.approval.id) continue;\n if (current.status !== \"planned\") return yield* stale(current);\n const next = new Storage.Attempt({\n ...current,\n status: \"approved\",\n approval: pair.approval,\n updatedAt: instant,\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 = ${pair.approval.id},\n updated_at = ${at(encoded.updatedAt)}\n WHERE id = ${pair.attemptId} AND owner_id = ${ownerId}\n `;\n }\n return yield* settled(\n ownerId,\n new Storage.Batch({\n ...batch,\n digest: input.digest,\n approval: { actorId: input.actorId, at: instant },\n }),\n );\n }),\n ),\n ).pipe(guard(\"batches.approve\")),\n reject: (id, input) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.gen(function* () {\n const batch = yield* lockedBatch(ownerId, id);\n // Terminal: a second rejection is the same outcome, so it returns the first one.\n if (batch.rejection !== null) return yield* aggregateOf(ownerId, batch);\n if (batch.status !== \"planning\" && batch.status !== \"planned\") {\n return yield* batchStale(batch);\n }\n const rows = yield* itemRows(ownerId, id);\n const instant = yield* DateTime.now;\n const rejection = {\n actorId: input.actorId,\n reason: input.reason,\n at: instant,\n };\n for (const row of rows) {\n if (row.attempt_id === null || row.attempt_status !== \"planned\") continue;\n const current = yield* lockedAttempt(ownerId, row.attempt_id);\n if (current.status !== \"planned\") continue;\n const next = new Storage.Attempt({\n ...current,\n status: \"rejected\",\n rejection,\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 = ${row.attempt_id} AND owner_id = ${ownerId}\n `;\n }\n return yield* settled(ownerId, new Storage.Batch({ ...batch, rejection }));\n }),\n ),\n ).pipe(guard(\"batches.reject\")),\n refresh: (id) =>\n Effect.flatMap(Principal.Service, ({ ownerId }) =>\n sql.withTransaction(\n Effect.flatMap(lockedBatch(ownerId, id), (batch) => settled(ownerId, batch)),\n ),\n ).pipe(guard(\"batches.refresh\")),\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 eight 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 readonly batches: Schema.Table;\n readonly batchItems: 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 eight 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 /**\n * What the provider called the account when the credential was issued, so a UI names the\n * connection offline. Null names no account, which is also what rows written before the\n * column existed carry.\n */\n label: Schema.text({ nullable: true }),\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 batches: Schema.table(`${prefix}_batches`, {\n columns: {\n id: Schema.text(),\n owner_id: Schema.text(),\n kind: Schema.text(),\n status: Schema.text(),\n /** SHA-256 over the items' `attachmentId:planDigest` pairs; set when the batch is approved. */\n digest: Schema.text({ nullable: true }),\n /** Who bound the digest, and when; the per-attempt approvals live on the attempts. */\n approval: Schema.json({ nullable: true }),\n rejection: Schema.json({ nullable: true }),\n idempotency_key: Schema.text(),\n created_by: Schema.text(),\n created_at: Schema.timestamp(),\n updated_at: Schema.timestamp(),\n /** When the batch reached `complete` or `rejected`; null while it still owes a move. */\n completed_at: Schema.timestamp({ nullable: true }),\n },\n primaryKey: [\"id\"],\n // One batch per key per tenant; `batches.create` reads the conflict as a replay.\n uniques: [[\"owner_id\", \"idempotency_key\"]],\n // The owner-scoped unfinished index, newest first.\n indexes: [{ columns: [\"owner_id\", \"status\", \"updated_at\"] }],\n }),\n batchItems: Schema.table(`${prefix}_batch_items`, {\n columns: {\n batch_id: Schema.text(),\n attachment_id: Schema.text(),\n /** The item's place in the batch, as `batches.create` received it. */\n position: Schema.integer(),\n /** The attempt carrying this item's plan; null until one lands. */\n attempt_id: Schema.text({ nullable: true }),\n /** Why the last planning pass stopped here; cleared when a plan lands. */\n plan_failure: Schema.text({ nullable: true }),\n },\n // One item per attachment per batch, which is what makes a replayed plan write idempotent.\n primaryKey: [\"batch_id\", \"attachment_id\"],\n indexes: [{ columns: [\"attempt_id\"] }],\n }),\n});\n\n/**\n * The authorizations table as the first migration created it, before `label`.\n *\n * Frozen for the same reason as `attachmentsV1`: migration 1 renders this shape, and the migration\n * that adds the column carries the difference.\n */\nexport const authorizationsV1 = (prefix: string): Schema.Table =>\n 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\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 ...initial(tables),\n tables.batches,\n tables.batchItems,\n];\n\n/**\n * The tables the first migration creates.\n *\n * A migration is history: what it renders must not move, so a table added later is declared above\n * and created by its own migration rather than joining this list.\n */\nexport const initial = (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: eight 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 {\n attachmentsV1,\n authorizationsV1,\n DEFAULT_PREFIX,\n initial,\n list,\n make as makeTables,\n} 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: initial(tables).map((table) =>\n Migration.createTable(\n table.name === tables.attachments.name\n ? attachmentsV1(prefix)\n : table.name === tables.authorizations.name\n ? authorizationsV1(prefix)\n : 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 // An installation that connected accounts before the column existed keeps those rows\n // unnamed: the provider named the account at connect time, and nothing here can name it\n // after the fact without a credential.\n Migration.make({\n id: 3,\n name: \"authorization-label\",\n risk: \"additive\",\n steps: [\n Migration.addColumn(tables.authorizations.name, \"label\", {\n type: \"text\",\n nullable: true,\n }),\n ],\n }),\n // The batch aggregate: many attempts planned together and approved once. Both tables are\n // new, so an installation that ran migrations 1 to 3 gains them without touching a row it\n // already holds.\n Migration.make({\n id: 4,\n name: \"batches\",\n risk: \"additive\",\n steps: [Migration.createTable(tables.batches), Migration.createTable(tables.batchItems)],\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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1
1
  {
2
2
  "name": "@domainkit/capsuledb",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
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.15.0"
48
+ "domainkit": "^0.16.0"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@effect/sql-pg": "4.0.0-rc.112",