@storyshelf/db-mysql 0.13.0 → 0.14.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.
Files changed (39) hide show
  1. package/README.md +22 -1
  2. package/dist/baseline-preparation.mjs +154 -0
  3. package/dist/baseline-preparation.mjs.map +1 -0
  4. package/dist/build-deletion-steps.mjs +98 -0
  5. package/dist/build-deletion-steps.mjs.map +1 -0
  6. package/dist/build-reference-lifecycle.mjs +157 -0
  7. package/dist/build-reference-lifecycle.mjs.map +1 -0
  8. package/dist/content-uses.mjs +192 -0
  9. package/dist/content-uses.mjs.map +1 -0
  10. package/dist/ddl.d.mts +1 -1
  11. package/dist/ddl.mjs +76 -0
  12. package/dist/ddl.mjs.map +1 -1
  13. package/dist/drizzle-factory-mysql.mjs +6 -2
  14. package/dist/drizzle-factory-mysql.mjs.map +1 -1
  15. package/dist/foreign-keys.mjs +57 -0
  16. package/dist/foreign-keys.mjs.map +1 -1
  17. package/dist/index.d.mts +9 -1
  18. package/dist/index.mjs +36 -10
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/lifecycle-transaction.mjs +105 -0
  21. package/dist/lifecycle-transaction.mjs.map +1 -0
  22. package/dist/migrate.mjs +11 -1
  23. package/dist/migrate.mjs.map +1 -1
  24. package/dist/planetscale.mjs +2 -2
  25. package/dist/planetscale.mjs.map +1 -1
  26. package/dist/retention-activation.mjs +127 -0
  27. package/dist/retention-activation.mjs.map +1 -0
  28. package/dist/schema/build.d.mts +17 -0
  29. package/dist/schema/build.mjs +2 -0
  30. package/dist/schema/build.mjs.map +1 -1
  31. package/dist/schema/git-connection.d.mts +505 -0
  32. package/dist/schema/git-connection.mjs +66 -0
  33. package/dist/schema/git-connection.mjs.map +1 -0
  34. package/dist/schema.d.mts +4 -1
  35. package/dist/schema.mjs +5 -2
  36. package/dist/schema.mjs.map +1 -1
  37. package/dist/tidb.mjs +2 -2
  38. package/dist/tidb.mjs.map +1 -1
  39. package/package.json +3 -2
package/README.md CHANGED
@@ -51,7 +51,28 @@ import { createPlanetscaleDatabase } from "@storyshelf/db-mysql/planetscale";
51
51
  import { createTidbDatabase } from "@storyshelf/db-mysql/tidb";
52
52
  ```
53
53
 
54
- Today both are thin aliases over the same `mysql2` pool: PlanetScale and TiDB Serverless speak the MySQL wire protocol, so the standard options above work unchanged (use `ssl` as your provider requires). They take the same options as `createMysqlDatabase`.
54
+ Today both are thin aliases over the same `mysql2` pool: PlanetScale and TiDB Serverless speak the MySQL wire protocol, so the standard options above work unchanged (use `ssl` as your provider requires). They take the same options as `createMysqlDatabase`. Neither provides build retention (see below): their locking was never proven.
55
+
56
+ ## Build retention
57
+
58
+ With `testing` on, build purge and branch GC need the fenced retention lifecycle (ADR 0039). This
59
+ adapter provides it only where it was proven against a real server:
60
+
61
+ - `createMysqlDatabase` with a **pool** (a `url`, `host` options, or an injected `mysql2` `Pool`);
62
+ - on **MySQL 8**, with the lifecycle tables on **InnoDB** and the binary log, if enabled, not
63
+ `STATEMENT`-based (`ROW`, the default, or `MIXED`).
64
+
65
+ Each lifecycle operation borrows its own pooled connection and runs at `READ COMMITTED`, whatever
66
+ the server's default isolation. Anything else keeps retention **off** (no automatic build deletion or
67
+ branch GC; admin purge answers `503`) and logs the reason once at boot: the PlanetScale and TiDB
68
+ presets, an injected single `Connection`, MariaDB, TiDB, Vitess, or another MySQL version.
69
+
70
+ Upgrading: the migration adds `builds.retention_state` (default `available`) and four lifecycle
71
+ tables; nothing is dropped, so the previous release keeps running on the new schema. The first boot
72
+ then pins the source build of every baseline before it turns retention on. Upgrade **every**
73
+ instance that shares the database before relying on purge: an older instance writes baselines
74
+ without the fence. A baseline whose recorded source build is being deleted or belongs to another
75
+ project pauses retention instead (the System page names both ids); fix the data and restart.
55
76
 
56
77
  ## Other exports
57
78
 
@@ -0,0 +1,154 @@
1
+ import "node:path";
2
+ import "node:url";
3
+ import.meta.url;
4
+ import { schema } from "./schema.mjs";
5
+ import { inTransaction } from "./lifecycle-transaction.mjs";
6
+ import { advance, lockFence } from "./build-reference-lifecycle.mjs";
7
+ import { BaselineSourceIntegrityError } from "@storyshelf/core/adapter/database";
8
+ import { resolveBaselineOrigin } from "@storyshelf/core/models";
9
+ // src/baseline-preparation.ts
10
+ /**
11
+ * Baseline preparation for MySQL (ADR 0039, "activation"): before the adapter exposes
12
+ * `buildReferenceLifecycle`, every baseline that records a source or a snapshot has its proven
13
+ * source build pinned, and pins that no baseline can justify are released. One transaction takes
14
+ * the same row locks as the fenced writers, in the same order (owners by key, then builds), so
15
+ * preparation can run beside live traffic and beside another instance that is booting: the second
16
+ * waits on the first's locks and finds nothing left to change.
17
+ *
18
+ * A recorded source that is tombstoned or belongs to another project stops the whole run with a
19
+ * {@link BaselineSourceIntegrityError}; the transaction rolls back and nothing is cleared or guessed.
20
+ */
21
+ /**
22
+ * Prepare the baseline pins in one transaction. `beforeCommit` runs after the last baseline and
23
+ * before the commit, so a test can fail the run at the point where everything is written. A
24
+ * deadlock is not retried here: the boot fails and the next boot prepares again from the start.
25
+ */
26
+ async function prepareBaselineReferences(pool, beforeCommit) {
27
+ return await inTransaction(pool, async (tx) => {
28
+ const outcomes = [];
29
+ for (const candidate of await candidates(tx)) {
30
+ const outcome = await prepareOwner(tx, candidate);
31
+ if (outcome) outcomes.push(outcome);
32
+ }
33
+ await beforeCommit?.();
34
+ return tally(outcomes);
35
+ }, false);
36
+ }
37
+ /** Baselines with provenance plus owners that hold a baseline pin, sorted like the fenced writers lock. */
38
+ async function candidates(tx) {
39
+ return (await tx.query(`SELECT project_id, id FROM baselines
40
+ WHERE source_build_id IS NOT NULL OR snapshot_id IS NOT NULL
41
+ UNION SELECT project_id, owner_id AS id FROM build_references WHERE owner_type = 'baseline'`)).map((row) => ({
42
+ projectId: String(row["project_id"]),
43
+ id: String(row["id"])
44
+ })).toSorted((left, right) => lockKey(left).localeCompare(lockKey(right)));
45
+ }
46
+ /** The order `replaceManyFencedReferences` locks owners in. */
47
+ function lockKey({ projectId, id }) {
48
+ return JSON.stringify([
49
+ projectId,
50
+ "baseline",
51
+ id
52
+ ]);
53
+ }
54
+ function tally(outcomes) {
55
+ const count = (kind) => outcomes.filter((outcome) => outcome === kind).length;
56
+ return {
57
+ protected: count("protected"),
58
+ unknown: count("unknown"),
59
+ unavailable: count("unavailable")
60
+ };
61
+ }
62
+ function ownerOf({ projectId, id }) {
63
+ return {
64
+ projectId,
65
+ type: "baseline",
66
+ id
67
+ };
68
+ }
69
+ /** Lock the owner's fence, then prepare its baseline; an owner without provenance loses its pins. */
70
+ async function prepareOwner(tx, candidate) {
71
+ await lockFence(tx, ownerOf(candidate));
72
+ const baseline = await tx.store.get(schema.baselines, candidate.id);
73
+ if (baseline && (baseline.sourceBuildId || baseline.snapshotId)) return await prepareBaseline(tx, baseline);
74
+ if (await releasePins(tx, ownerOf(candidate))) await advance(tx, ownerOf(candidate));
75
+ return null;
76
+ }
77
+ /** Drop every pin the owner holds; true when there was one. The caller advances the generation. */
78
+ async function releasePins(tx, owner) {
79
+ return await tx.run("DELETE FROM build_references WHERE project_id = ? AND owner_type = ? AND owner_id = ?", [
80
+ owner.projectId,
81
+ owner.type,
82
+ owner.id
83
+ ]) > 0;
84
+ }
85
+ async function prepareBaseline(tx, baseline) {
86
+ if (baseline.sourceBuildId && !await recordedSourcePresent(tx, baseline, baseline.sourceBuildId)) {
87
+ if (await releasePins(tx, ownerOf(baseline))) await advance(tx, ownerOf(baseline));
88
+ return "unavailable";
89
+ }
90
+ const source = await provenSource(tx, baseline);
91
+ if (!source) {
92
+ await setPreparedSource(tx, baseline, null);
93
+ return "unknown";
94
+ }
95
+ await pinAvailableSource(tx, baseline, source.id);
96
+ await setPreparedSource(tx, baseline, source.id);
97
+ return "protected";
98
+ }
99
+ /** The build that provably rendered the baseline's image, or null when its history is incomplete. */
100
+ async function provenSource(tx, baseline) {
101
+ return await resolveBaselineOrigin(baseline, {
102
+ baseline: async (key) => await tx.store.get(schema.baselines, key),
103
+ snapshot: async (key) => await tx.store.get(schema.snapshots, key),
104
+ build: async (key) => await tx.store.get(schema.builds, key)
105
+ });
106
+ }
107
+ /**
108
+ * Whether the build a baseline records as its source still has a row. A row in another project is
109
+ * an integrity problem, not a missing build: the record is neither kept nor cleared.
110
+ */
111
+ async function recordedSourcePresent(tx, baseline, buildId) {
112
+ const rows = await tx.query("SELECT project_id FROM builds WHERE id = ?", [buildId]);
113
+ if (rows.length === 0) return false;
114
+ if (rows[0]?.["project_id"] !== baseline.projectId) throw new BaselineSourceIntegrityError(baseline.id, buildId, "other-project");
115
+ return true;
116
+ }
117
+ async function setPreparedSource(tx, baseline, source) {
118
+ const removed = source === null && await releasePins(tx, ownerOf(baseline));
119
+ if ((baseline.sourceBuildId ?? null) === source && !removed) return;
120
+ await tx.run("UPDATE baselines SET source_build_id = ? WHERE id = ?", [source, baseline.id]);
121
+ await advance(tx, ownerOf(baseline));
122
+ }
123
+ /**
124
+ * Pin `buildId` for the baseline, replacing a pin on any other build. The build row is share-locked,
125
+ * which conflicts with a deletion claim's `FOR UPDATE`, so a tombstone cannot slip in after the
126
+ * check; a tombstoned build is never pinned. The owner's fence is held, so no writer changes its
127
+ * pins between the read and the insert.
128
+ */
129
+ async function pinAvailableSource(tx, baseline, buildId) {
130
+ const { id, projectId } = baseline;
131
+ if ((await tx.query("SELECT retention_state FROM builds WHERE id = ? AND project_id = ? FOR SHARE", [buildId, projectId]))[0]?.["retention_state"] !== "available") throw new BaselineSourceIntegrityError(id, buildId, "tombstoned");
132
+ const removed = await tx.run(`DELETE FROM build_references
133
+ WHERE project_id = ? AND owner_type = 'baseline' AND owner_id = ? AND build_id <> ?`, [
134
+ projectId,
135
+ id,
136
+ buildId
137
+ ]);
138
+ const present = await tx.query(`SELECT 1 FROM build_references
139
+ WHERE project_id = ? AND owner_type = 'baseline' AND owner_id = ? AND build_id = ?`, [
140
+ projectId,
141
+ id,
142
+ buildId
143
+ ]);
144
+ if (present.length === 0) await tx.run(`INSERT INTO build_references (project_id, owner_type, owner_id, build_id)
145
+ VALUES (?, 'baseline', ?, ?)`, [
146
+ projectId,
147
+ id,
148
+ buildId
149
+ ]);
150
+ if (present.length === 0 || removed > 0) await advance(tx, ownerOf(baseline));
151
+ }
152
+ export { prepareBaselineReferences };
153
+
154
+ //# sourceMappingURL=baseline-preparation.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"baseline-preparation.mjs","names":[],"sources":["../src/baseline-preparation.ts"],"sourcesContent":["/**\n * Baseline preparation for MySQL (ADR 0039, \"activation\"): before the adapter exposes\n * `buildReferenceLifecycle`, every baseline that records a source or a snapshot has its proven\n * source build pinned, and pins that no baseline can justify are released. One transaction takes\n * the same row locks as the fenced writers, in the same order (owners by key, then builds), so\n * preparation can run beside live traffic and beside another instance that is booting: the second\n * waits on the first's locks and finds nothing left to change.\n *\n * A recorded source that is tombstoned or belongs to another project stops the whole run with a\n * {@link BaselineSourceIntegrityError}; the transaction rolls back and nothing is cleared or guessed.\n */\nimport {\n BaselineSourceIntegrityError,\n type BuildReferenceOwner,\n} from \"@storyshelf/core/adapter/database\";\nimport { resolveBaselineOrigin } from \"@storyshelf/core/models\";\nimport type { Baseline, Build, Snapshot } from \"@storyshelf/core/schema\";\nimport { advance, lockFence } from \"./build-reference-lifecycle.ts\";\nimport { inTransaction, type LifecyclePool, type LifecycleTx } from \"./lifecycle-transaction.ts\";\nimport { schema } from \"./schema/index.ts\";\n\n/** What preparation did with one baseline. */\ntype Prepared = \"protected\" | \"unknown\" | \"unavailable\";\n\n/** Counts of {@link Prepared} outcomes: every baseline with a source or a snapshot is in exactly one. */\nexport interface PreparationResult {\n /** Baselines whose proven source build is now pinned. */\n protected: number;\n /** Baselines whose provenance cannot be proven; they stay unpinned and unknown. */\n unknown: number;\n /** Baselines whose recorded source build row is gone; the record is kept, nothing is pinned. */\n unavailable: number;\n}\n\n/** A baseline owner to visit: it records provenance, or a pin still names it. */\ninterface Candidate {\n projectId: string;\n id: string;\n}\n\n/**\n * Prepare the baseline pins in one transaction. `beforeCommit` runs after the last baseline and\n * before the commit, so a test can fail the run at the point where everything is written. A\n * deadlock is not retried here: the boot fails and the next boot prepares again from the start.\n */\nexport async function prepareBaselineReferences(\n pool: LifecyclePool,\n beforeCommit?: () => Promise<void>,\n): Promise<PreparationResult> {\n return await inTransaction(\n pool,\n async (tx) => {\n const outcomes: Prepared[] = [];\n for (const candidate of await candidates(tx)) {\n // oxlint-disable-next-line no-await-in-loop -- one owner at a time, in lock order: a failure must stop the rest before the rollback\n const outcome = await prepareOwner(tx, candidate);\n if (outcome) outcomes.push(outcome);\n }\n await beforeCommit?.();\n return tally(outcomes);\n },\n false,\n );\n}\n\n/** Baselines with provenance plus owners that hold a baseline pin, sorted like the fenced writers lock. */\nasync function candidates(tx: LifecycleTx): Promise<Candidate[]> {\n const rows = await tx.query(`SELECT project_id, id FROM baselines\n WHERE source_build_id IS NOT NULL OR snapshot_id IS NOT NULL\n UNION SELECT project_id, owner_id AS id FROM build_references WHERE owner_type = 'baseline'`);\n return rows\n .map((row) => ({ projectId: String(row[\"project_id\"]), id: String(row[\"id\"]) }))\n .toSorted((left, right) => lockKey(left).localeCompare(lockKey(right)));\n}\n\n/** The order `replaceManyFencedReferences` locks owners in. */\nfunction lockKey({ projectId, id }: Candidate): string {\n return JSON.stringify([projectId, \"baseline\", id]);\n}\n\nfunction tally(outcomes: readonly Prepared[]): PreparationResult {\n const count = (kind: Prepared): number => outcomes.filter((outcome) => outcome === kind).length;\n return {\n protected: count(\"protected\"),\n unknown: count(\"unknown\"),\n unavailable: count(\"unavailable\"),\n };\n}\n\nfunction ownerOf({ projectId, id }: Candidate): BuildReferenceOwner {\n return { projectId, type: \"baseline\", id };\n}\n\n/** Lock the owner's fence, then prepare its baseline; an owner without provenance loses its pins. */\nasync function prepareOwner(tx: LifecycleTx, candidate: Candidate): Promise<Prepared | null> {\n await lockFence(tx, ownerOf(candidate));\n // Read after the fence is held: at READ COMMITTED this sees what a writer committed before it.\n const baseline = (await tx.store.get(schema.baselines, candidate.id)) as Baseline | null;\n if (baseline && (baseline.sourceBuildId || baseline.snapshotId)) {\n return await prepareBaseline(tx, baseline);\n }\n // The baseline is gone or records neither a source nor a snapshot: the unfenced path (retention\n // off or not yet existing) could clear it or delete it without releasing its pin.\n if (await releasePins(tx, ownerOf(candidate))) await advance(tx, ownerOf(candidate));\n return null;\n}\n\n/** Drop every pin the owner holds; true when there was one. The caller advances the generation. */\nasync function releasePins(tx: LifecycleTx, owner: BuildReferenceOwner): Promise<boolean> {\n const removed = await tx.run(\n \"DELETE FROM build_references WHERE project_id = ? AND owner_type = ? AND owner_id = ?\",\n [owner.projectId, owner.type, owner.id],\n );\n return removed > 0;\n}\n\nasync function prepareBaseline(tx: LifecycleTx, baseline: Baseline): Promise<Prepared> {\n if (\n baseline.sourceBuildId &&\n !(await recordedSourcePresent(tx, baseline, baseline.sourceBuildId))\n ) {\n // The record stays (it is verified history), but nothing may pin a build for it.\n if (await releasePins(tx, ownerOf(baseline))) await advance(tx, ownerOf(baseline));\n return \"unavailable\";\n }\n const source = await provenSource(tx, baseline);\n if (!source) {\n await setPreparedSource(tx, baseline, null);\n return \"unknown\";\n }\n await pinAvailableSource(tx, baseline, source.id);\n await setPreparedSource(tx, baseline, source.id);\n return \"protected\";\n}\n\n/** The build that provably rendered the baseline's image, or null when its history is incomplete. */\nasync function provenSource(tx: LifecycleTx, baseline: Baseline): Promise<Build | null> {\n return await resolveBaselineOrigin(baseline, {\n baseline: async (key) => (await tx.store.get(schema.baselines, key)) as Baseline | null,\n snapshot: async (key) => (await tx.store.get(schema.snapshots, key)) as Snapshot | null,\n build: async (key) => (await tx.store.get(schema.builds, key)) as Build | null,\n });\n}\n\n/**\n * Whether the build a baseline records as its source still has a row. A row in another project is\n * an integrity problem, not a missing build: the record is neither kept nor cleared.\n */\nasync function recordedSourcePresent(\n tx: LifecycleTx,\n baseline: Baseline,\n buildId: string,\n): Promise<boolean> {\n const rows = await tx.query(\"SELECT project_id FROM builds WHERE id = ?\", [buildId]);\n if (rows.length === 0) return false;\n if (rows[0]?.[\"project_id\"] !== baseline.projectId) {\n throw new BaselineSourceIntegrityError(baseline.id, buildId, \"other-project\");\n }\n return true;\n}\n\nasync function setPreparedSource(\n tx: LifecycleTx,\n baseline: Baseline,\n source: string | null,\n): Promise<void> {\n const removed = source === null && (await releasePins(tx, ownerOf(baseline)));\n if ((baseline.sourceBuildId ?? null) === source && !removed) return;\n await tx.run(\"UPDATE baselines SET source_build_id = ? WHERE id = ?\", [source, baseline.id]);\n await advance(tx, ownerOf(baseline));\n}\n\n/**\n * Pin `buildId` for the baseline, replacing a pin on any other build. The build row is share-locked,\n * which conflicts with a deletion claim's `FOR UPDATE`, so a tombstone cannot slip in after the\n * check; a tombstoned build is never pinned. The owner's fence is held, so no writer changes its\n * pins between the read and the insert.\n */\nasync function pinAvailableSource(\n tx: LifecycleTx,\n baseline: Baseline,\n buildId: string,\n): Promise<void> {\n const { id, projectId } = baseline;\n const rows = await tx.query(\n \"SELECT retention_state FROM builds WHERE id = ? AND project_id = ? FOR SHARE\",\n [buildId, projectId],\n );\n if (rows[0]?.[\"retention_state\"] !== \"available\") {\n throw new BaselineSourceIntegrityError(id, buildId, \"tombstoned\");\n }\n const removed = await tx.run(\n `DELETE FROM build_references\n WHERE project_id = ? AND owner_type = 'baseline' AND owner_id = ? AND build_id <> ?`,\n [projectId, id, buildId],\n );\n const present = await tx.query(\n `SELECT 1 FROM build_references\n WHERE project_id = ? AND owner_type = 'baseline' AND owner_id = ? AND build_id = ?`,\n [projectId, id, buildId],\n );\n if (present.length === 0) {\n await tx.run(\n `INSERT INTO build_references (project_id, owner_type, owner_id, build_id)\n VALUES (?, 'baseline', ?, ?)`,\n [projectId, id, buildId],\n );\n }\n if (present.length === 0 || removed > 0) await advance(tx, ownerOf(baseline));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,eAAsB,0BACpB,MACA,cAC4B;CAC5B,OAAO,MAAM,cACX,MACA,OAAO,OAA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AAS;CAC7D,MAAM,GAAG,IAAI,yDAAyD,CAAC,QAAQ,SAAS,EAAE,CAAC;CAC3F,MAAM,QAAQ,IAAI,QAAQ,QAAQ,CAAC;AACrC;;;;;;;AAQA,eAAe,mBACb,IACA,UACA,SACe;CACf,MAAM,EAAE,IAAI,cAAc;CAK1B,KAAI,MAJe,GAAG,MACpB,gFACA,CAAC,SAAS,SAAS,CACrB,EAAA,CACS,EAAE,GAAG,uBAAuB,aACnC,MAAM,IAAI,6BAA6B,IAAI,SAAS,YAAY;CAElE,MAAM,UAAU,MAAM,GAAG,IACvB;4FAEA;EAAC;EAAW;EAAI;CAAO,CACzB;CACA,MAAM,UAAU,MAAM,GAAG,MACvB;2FAEA;EAAC;EAAW;EAAI;CAAO,CACzB;CACA,IAAI,QAAQ,WAAW,GACrB,MAAM,GAAG,IACP;uCAEA;EAAC;EAAW;EAAI;CAAO,CACzB;CAEF,IAAI,QAAQ,WAAW,KAAK,UAAU,GAAG,MAAM,QAAQ,IAAI,QAAQ,QAAQ,CAAC;AAC9E"}
@@ -0,0 +1,98 @@
1
+ import "node:path";
2
+ import "node:url";
3
+ import.meta.url;
4
+ import { chunks, inTransaction, nowInstant } from "./lifecycle-transaction.mjs";
5
+ // src/build-deletion-steps.ts
6
+ function recorded(value) {
7
+ return value !== null && value !== void 0;
8
+ }
9
+ /** Builds of the project that are `deleting`, in the order they were claimed. */
10
+ async function listDeleting(pool, projectId) {
11
+ return await inTransaction(pool, async ({ query }) => {
12
+ return (await query(`SELECT b.id, d.content_released_at, d.storage_deleted_at
13
+ FROM builds b LEFT JOIN build_deletions d ON d.build_id = b.id
14
+ WHERE b.project_id = ? AND b.retention_state = 'deleting'
15
+ ORDER BY COALESCE(d.created_at, b.updated_at), b.id`, [projectId])).map((row) => ({
16
+ projectId,
17
+ buildId: String(row["id"]),
18
+ contentReleased: recorded(row["content_released_at"]),
19
+ storageDeleted: recorded(row["storage_deleted_at"])
20
+ }));
21
+ });
22
+ }
23
+ /** Release each distinct hash once and mark the step, or report why it did not apply. */
24
+ async function releaseBuildContent(pool, projectId, buildId, hashes) {
25
+ return await inTransaction(pool, async (tx) => {
26
+ const state = await deletionState(tx, projectId, buildId);
27
+ if (state === null) return "not-deleting";
28
+ if (state.contentReleased) return "already-done";
29
+ const now = nowInstant();
30
+ await tx.run(`INSERT INTO build_deletions (build_id, project_id, created_at, updated_at)
31
+ VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE build_id = build_id`, [
32
+ buildId,
33
+ projectId,
34
+ now,
35
+ now
36
+ ]);
37
+ for (const slice of chunks([...new Set(hashes)])) await tx.run(`INSERT INTO build_content_releases (build_id, content_hash, released_at) VALUES ?
38
+ ON DUPLICATE KEY UPDATE released_at = released_at`, [slice.map((hash) => [
39
+ buildId,
40
+ hash,
41
+ now
42
+ ])]);
43
+ await tx.run("UPDATE content_uses SET released_at = ? WHERE build_id = ? AND released_at IS NULL", [now, buildId]);
44
+ await tx.run("UPDATE build_deletions SET content_released_at = ?, updated_at = ? WHERE build_id = ?", [
45
+ now,
46
+ now,
47
+ buildId
48
+ ]);
49
+ return "done";
50
+ });
51
+ }
52
+ /** Record that storage is deleted; the build must have released its content first. */
53
+ async function markStorageDeleted(pool, projectId, buildId) {
54
+ return await inTransaction(pool, async (tx) => {
55
+ const state = await deletionState(tx, projectId, buildId);
56
+ if (state === null) return "not-deleting";
57
+ if (!state.contentReleased) return "out-of-order";
58
+ if (state.storageDeleted) return "already-done";
59
+ const now = nowInstant();
60
+ await tx.run("UPDATE build_deletions SET storage_deleted_at = ?, updated_at = ? WHERE build_id = ?", [
61
+ now,
62
+ now,
63
+ buildId
64
+ ]);
65
+ return "done";
66
+ });
67
+ }
68
+ /**
69
+ * Remove the build's rows and its progress records in one transaction. `removeRows` is the caller's
70
+ * callback, so a deadlock is not retried here: it reaches the caller with everything rolled back.
71
+ */
72
+ async function completeDeletion(pool, projectId, buildId, removeRows) {
73
+ return await inTransaction(pool, async (tx) => {
74
+ const state = await deletionState(tx, projectId, buildId);
75
+ if (state === null) return "not-deleting";
76
+ if (!state.storageDeleted) return "out-of-order";
77
+ return { result: await removeRows(tx.store) };
78
+ }, false);
79
+ }
80
+ /**
81
+ * The recorded steps of a `deleting` build of the project, or null when it is not one. The build
82
+ * row stays locked until the transaction ends, so two cleaners take their steps one after another.
83
+ *
84
+ * Two statements, never one join locking only the build: the unlocked side of such a join is read
85
+ * from the statement's start, before the wait for the lock, and would miss the steps the previous
86
+ * holder committed. Read after the lock, at READ COMMITTED, the steps are current.
87
+ */
88
+ async function deletionState(tx, projectId, buildId) {
89
+ if ((await tx.query("SELECT retention_state FROM builds WHERE project_id = ? AND id = ? FOR UPDATE", [projectId, buildId]))[0]?.["retention_state"] !== "deleting") return null;
90
+ const steps = await tx.query("SELECT content_released_at, storage_deleted_at FROM build_deletions WHERE build_id = ?", [buildId]);
91
+ return {
92
+ contentReleased: recorded(steps[0]?.["content_released_at"]),
93
+ storageDeleted: recorded(steps[0]?.["storage_deleted_at"])
94
+ };
95
+ }
96
+ export { completeDeletion, listDeleting, markStorageDeleted, releaseBuildContent };
97
+
98
+ //# sourceMappingURL=build-deletion-steps.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build-deletion-steps.mjs","names":[],"sources":["../src/build-deletion-steps.ts"],"sourcesContent":["/** Durable progress of a claimed build's cleanup (ADR 0039 decision 2), under the build's row lock. */\nimport type { DeletingBuild, DeletionStepResult, TxStore } from \"@storyshelf/core/adapter/database\";\nimport {\n chunks,\n inTransaction,\n nowInstant,\n type LifecyclePool,\n type LifecycleTx,\n} from \"./lifecycle-transaction.ts\";\n\n/** What {@link deletionState} reads: the tombstone and the recorded steps. */\ninterface State {\n contentReleased: boolean;\n storageDeleted: boolean;\n}\n\nfunction recorded(value: unknown): boolean {\n return value !== null && value !== undefined;\n}\n\n/** Builds of the project that are `deleting`, in the order they were claimed. */\nexport async function listDeleting(\n pool: LifecyclePool,\n projectId: string,\n): Promise<DeletingBuild[]> {\n return await inTransaction(pool, async ({ query }) => {\n const rows = await query(\n `SELECT b.id, d.content_released_at, d.storage_deleted_at\n FROM builds b LEFT JOIN build_deletions d ON d.build_id = b.id\n WHERE b.project_id = ? AND b.retention_state = 'deleting'\n ORDER BY COALESCE(d.created_at, b.updated_at), b.id`,\n [projectId],\n );\n return rows.map((row) => ({\n projectId,\n buildId: String(row[\"id\"]),\n contentReleased: recorded(row[\"content_released_at\"]),\n storageDeleted: recorded(row[\"storage_deleted_at\"]),\n }));\n });\n}\n\n/** Release each distinct hash once and mark the step, or report why it did not apply. */\nexport async function releaseBuildContent(\n pool: LifecyclePool,\n projectId: string,\n buildId: string,\n hashes: readonly string[],\n): Promise<DeletionStepResult> {\n return await inTransaction(pool, async (tx) => {\n const state = await deletionState(tx, projectId, buildId);\n if (state === null) return \"not-deleting\";\n if (state.contentReleased) return \"already-done\";\n const now = nowInstant();\n await tx.run(\n `INSERT INTO build_deletions (build_id, project_id, created_at, updated_at)\n VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE build_id = build_id`,\n [buildId, projectId, now, now],\n );\n for (const slice of chunks([...new Set(hashes)])) {\n // oxlint-disable-next-line no-await-in-loop -- bounded statements, in order\n await tx.run(\n `INSERT INTO build_content_releases (build_id, content_hash, released_at) VALUES ?\n ON DUPLICATE KEY UPDATE released_at = released_at`,\n [slice.map((hash) => [buildId, hash, now])],\n );\n }\n // Every use the build holds, whatever its manifest lists; the blob stays for the grace period.\n await tx.run(\n \"UPDATE content_uses SET released_at = ? WHERE build_id = ? AND released_at IS NULL\",\n [now, buildId],\n );\n await tx.run(\n \"UPDATE build_deletions SET content_released_at = ?, updated_at = ? WHERE build_id = ?\",\n [now, now, buildId],\n );\n return \"done\";\n });\n}\n\n/** Record that storage is deleted; the build must have released its content first. */\nexport async function markStorageDeleted(\n pool: LifecyclePool,\n projectId: string,\n buildId: string,\n): Promise<DeletionStepResult> {\n return await inTransaction(pool, async (tx) => {\n const state = await deletionState(tx, projectId, buildId);\n if (state === null) return \"not-deleting\";\n if (!state.contentReleased) return \"out-of-order\";\n if (state.storageDeleted) return \"already-done\";\n const now = nowInstant();\n await tx.run(\n \"UPDATE build_deletions SET storage_deleted_at = ?, updated_at = ? WHERE build_id = ?\",\n [now, now, buildId],\n );\n return \"done\";\n });\n}\n\n/**\n * Remove the build's rows and its progress records in one transaction. `removeRows` is the caller's\n * callback, so a deadlock is not retried here: it reaches the caller with everything rolled back.\n */\nexport async function completeDeletion<T>(\n pool: LifecyclePool,\n projectId: string,\n buildId: string,\n removeRows: (tx: TxStore) => Promise<T>,\n): Promise<{ result: T } | \"not-deleting\" | \"out-of-order\"> {\n return await inTransaction(\n pool,\n async (tx) => {\n const state = await deletionState(tx, projectId, buildId);\n if (state === null) return \"not-deleting\";\n if (!state.storageDeleted) return \"out-of-order\";\n // The progress rows go with the build (ON DELETE CASCADE); a write that leaves it keeps them.\n return { result: await removeRows(tx.store) };\n },\n false,\n );\n}\n\n/**\n * The recorded steps of a `deleting` build of the project, or null when it is not one. The build\n * row stays locked until the transaction ends, so two cleaners take their steps one after another.\n *\n * Two statements, never one join locking only the build: the unlocked side of such a join is read\n * from the statement's start, before the wait for the lock, and would miss the steps the previous\n * holder committed. Read after the lock, at READ COMMITTED, the steps are current.\n */\nasync function deletionState(\n tx: LifecycleTx,\n projectId: string,\n buildId: string,\n): Promise<State | null> {\n const build = await tx.query(\n \"SELECT retention_state FROM builds WHERE project_id = ? AND id = ? FOR UPDATE\",\n [projectId, buildId],\n );\n if (build[0]?.[\"retention_state\"] !== \"deleting\") return null;\n const steps = await tx.query(\n \"SELECT content_released_at, storage_deleted_at FROM build_deletions WHERE build_id = ?\",\n [buildId],\n );\n return {\n contentReleased: recorded(steps[0]?.[\"content_released_at\"]),\n storageDeleted: recorded(steps[0]?.[\"storage_deleted_at\"]),\n };\n}\n"],"mappings":";;;;;AAgBA,SAAS,SAAS,OAAyB;CACzC,OAAO,UAAU,QAAQ,UAAU,KAAA;AACrC;;AAGA,eAAsB,aACpB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iBACpB,MACA,WACA,SACA,YAC0D;CAC1D,OAAO,MAAM,cACX,MACA,OAAO,OAAO;EACZ,MAAM,QAAQ,MAAM,cAAc,IAAI,WAAW,OAAO;EACxD,IAAI,UAAU,MAAM,OAAO;EAC3B,IAAI,CAAC,MAAM,gBAAgB,OAAO;EAElC,OAAO,EAAE,QAAQ,MAAM,WAAW,GAAG,KAAK,EAAE;CAC9C,GACA,KACF;AACF;;;;;;;;;AAUA,eAAe,cACb,IACA,WACA,SACuB;CAKvB,KAAI,MAJgB,GAAG,MACrB,iFACA,CAAC,WAAW,OAAO,CACrB,EAAA,CACU,EAAE,GAAG,uBAAuB,YAAY,OAAO;CACzD,MAAM,QAAQ,MAAM,GAAG,MACrB,0FACA,CAAC,OAAO,CACV;CACA,OAAO;EACL,iBAAiB,SAAS,MAAM,EAAE,GAAG,sBAAsB;EAC3D,gBAAgB,SAAS,MAAM,EAAE,GAAG,qBAAqB;CAC3D;AACF"}
@@ -0,0 +1,157 @@
1
+ import "node:path";
2
+ import "node:url";
3
+ import.meta.url;
4
+ import { inTransaction } from "./lifecycle-transaction.mjs";
5
+ import { completeDeletion, listDeleting, markStorageDeleted, releaseBuildContent } from "./build-deletion-steps.mjs";
6
+ import { abandonContentClaim, claimContent, contentUsage, finishContentCollection, holdsContentClaim, recordContentUses } from "./content-uses.mjs";
7
+ import { ReferenceGenerationConflict } from "@storyshelf/core/adapter/database";
8
+ // src/build-reference-lifecycle.ts
9
+ /**
10
+ * MySQL's implementation of the build retention lifecycle (ADR 0039), over InnoDB row locks taken
11
+ * in one fixed order (owners by key, then builds by id), the order Postgres uses:
12
+ *
13
+ * - an owner's `build_reference_generations` row is locked `FOR UPDATE`, which is the fence. It is
14
+ * created with `INSERT ... ON DUPLICATE KEY UPDATE`, which takes the row's exclusive lock at once:
15
+ * `INSERT IGNORE` would take a shared lock first, and two writers upgrading a shared lock to
16
+ * `FOR UPDATE` deadlock;
17
+ * - each referenced build row is locked `FOR SHARE`, which conflicts with {@link claimDeletion}'s
18
+ * `FOR UPDATE` of the same row, so an admission and a tombstone of one build cannot both win.
19
+ *
20
+ * Every transaction runs at READ COMMITTED on a connection of its own (`lifecycle-transaction.ts`).
21
+ */
22
+ /** The lifecycle over a mysql2/promise pool; each operation borrows a connection and opens its own transaction. */
23
+ function createBuildReferenceLifecycle(pool) {
24
+ return {
25
+ referenceGeneration: async (owner) => await referenceGeneration(pool, owner),
26
+ replaceManyFencedReferences: async (changes, writeDomain) => await replaceManyFencedReferences(pool, changes, writeDomain),
27
+ replaceFencedReferences: async (owner, generation, ids, writeDomain) => {
28
+ return {
29
+ result: (await replaceManyFencedReferences(pool, [{
30
+ owner,
31
+ expectedGeneration: generation,
32
+ buildIds: ids
33
+ }], writeDomain)).result,
34
+ generation: generation + 1
35
+ };
36
+ },
37
+ claimDeletion: async (projectId, buildId) => await claimDeletion(pool, projectId, buildId),
38
+ listDeleting: async (projectId) => await listDeleting(pool, projectId),
39
+ releaseBuildContent: async (projectId, buildId, hashes) => await releaseBuildContent(pool, projectId, buildId, hashes),
40
+ markStorageDeleted: async (projectId, buildId) => await markStorageDeleted(pool, projectId, buildId),
41
+ completeDeletion: async (projectId, buildId, removeRows) => await completeDeletion(pool, projectId, buildId, removeRows),
42
+ recordContentUses: async (projectId, buildId, hashes, staleBefore, sizes) => await recordContentUses(pool, projectId, buildId, hashes, staleBefore, sizes),
43
+ contentUsage: async (projectId) => await contentUsage(pool, projectId),
44
+ claimContent: async (token, idleBefore, staleBefore) => await claimContent(pool, token, idleBefore, staleBefore),
45
+ holdsContentClaim: async (hash, token) => await holdsContentClaim(pool, hash, token),
46
+ abandonContentClaim: async (hash, token) => {
47
+ await abandonContentClaim(pool, hash, token);
48
+ },
49
+ finishContentCollection: async (hash, token) => {
50
+ await finishContentCollection(pool, hash, token);
51
+ }
52
+ };
53
+ }
54
+ const OWNER = "project_id = ? AND owner_type = ? AND owner_id = ?";
55
+ function ownerParams(owner) {
56
+ return [
57
+ owner.projectId,
58
+ owner.type,
59
+ owner.id
60
+ ];
61
+ }
62
+ async function referenceGeneration(pool, owner) {
63
+ return await inTransaction(pool, async ({ query }) => {
64
+ const rows = await query(`SELECT generation FROM build_reference_generations WHERE ${OWNER}`, ownerParams(owner));
65
+ return Number(rows[0]?.["generation"] ?? 0);
66
+ });
67
+ }
68
+ /**
69
+ * Fence every owner, run the domain write, then replace the references and advance the fences. The
70
+ * domain write is the caller's: a deadlock is not retried here (it reaches the caller, with every
71
+ * write of the transaction rolled back).
72
+ */
73
+ async function replaceManyFencedReferences(pool, changes, writeDomain) {
74
+ validateFencedChanges(changes);
75
+ const normalized = changes.map((change) => ({
76
+ ...change,
77
+ ids: [...new Set(change.buildIds)].toSorted()
78
+ }));
79
+ return await inTransaction(pool, async (tx) => {
80
+ for (const change of byOwnerKey(normalized)) await fence(tx, change);
81
+ await lockAvailable(tx, normalized);
82
+ const result = await writeDomain(tx.store);
83
+ for (const change of normalized) await saveReferences(tx, change);
84
+ return {
85
+ result,
86
+ generations: normalized.map((change) => change.expectedGeneration + 1)
87
+ };
88
+ }, false);
89
+ }
90
+ function ownerKey({ owner }) {
91
+ return JSON.stringify([
92
+ owner.projectId,
93
+ owner.type,
94
+ owner.id
95
+ ]);
96
+ }
97
+ /** The lock order: owners by key, whatever order the caller listed them in. */
98
+ function byOwnerKey(changes) {
99
+ return changes.toSorted((left, right) => ownerKey(left).localeCompare(ownerKey(right)));
100
+ }
101
+ function validateFencedChanges(changes) {
102
+ const keys = changes.map(({ owner }) => JSON.stringify([
103
+ owner.projectId,
104
+ owner.type,
105
+ owner.id
106
+ ]));
107
+ if (new Set(keys).size !== keys.length) throw new Error("Duplicate reference owner");
108
+ for (const { expectedGeneration } of changes) if (!(Number.isSafeInteger(expectedGeneration) && expectedGeneration >= 0) || expectedGeneration >= Number.MAX_SAFE_INTEGER) throw new Error("Invalid reference generation");
109
+ }
110
+ /**
111
+ * Create the owner's generation row at zero if needed and hold its exclusive lock: the fence every
112
+ * writer, and preparation, takes first.
113
+ */
114
+ async function lockFence(tx, owner) {
115
+ await tx.run(`INSERT INTO build_reference_generations (project_id, owner_type, owner_id, generation)
116
+ VALUES (?, ?, ?, 0) ON DUPLICATE KEY UPDATE generation = generation`, ownerParams(owner));
117
+ const rows = await tx.query(`SELECT generation FROM build_reference_generations WHERE ${OWNER} FOR UPDATE`, ownerParams(owner));
118
+ return Number(rows[0]?.["generation"]);
119
+ }
120
+ /** Every reference mutation advances the owner's fence. */
121
+ async function advance(tx, owner) {
122
+ await tx.run(`UPDATE build_reference_generations SET generation = generation + 1 WHERE ${OWNER}`, ownerParams(owner));
123
+ }
124
+ /** Lock the owner's fence and reject a stale expectation. */
125
+ async function fence(tx, { owner, expectedGeneration }) {
126
+ if (await lockFence(tx, owner) !== expectedGeneration) throw new ReferenceGenerationConflict("Stale reference generation");
127
+ }
128
+ /** Share-lock every referenced build, in id order, and require each to be `available`. */
129
+ async function lockAvailable(tx, changes) {
130
+ const byProject = Map.groupBy(changes, ({ owner }) => owner.projectId);
131
+ const projects = [...byProject.keys()].toSorted();
132
+ for (const projectId of projects) {
133
+ const ids = [...new Set((byProject.get(projectId) ?? []).flatMap((change) => change.ids))];
134
+ if (ids.length === 0) continue;
135
+ if ((await tx.query(`SELECT id, retention_state FROM builds
136
+ WHERE project_id = ? AND id IN (?) ORDER BY id FOR SHARE`, [projectId, ids.toSorted()])).filter((row) => row["retention_state"] === "available").length !== ids.length) throw new Error("Referenced build is unavailable");
137
+ }
138
+ }
139
+ async function saveReferences(tx, { owner, ids }) {
140
+ await tx.run(`DELETE FROM build_references WHERE ${OWNER}`, ownerParams(owner));
141
+ if (ids.length > 0) await tx.run("INSERT INTO build_references (project_id, owner_type, owner_id, build_id) VALUES ?", [ids.map((id) => [...ownerParams(owner), id])]);
142
+ await advance(tx, owner);
143
+ }
144
+ /** Tombstone the build under its row lock, unless a reference protects it. */
145
+ async function claimDeletion(pool, projectId, buildId) {
146
+ return await inTransaction(pool, async ({ query, run }) => {
147
+ const build = await query("SELECT retention_state FROM builds WHERE project_id = ? AND id = ? FOR UPDATE", [projectId, buildId]);
148
+ if (build.length === 0) return "missing";
149
+ if (build[0]?.["retention_state"] !== "available") return "deleting";
150
+ if ((await query("SELECT 1 FROM build_references WHERE build_id = ? LIMIT 1", [buildId])).length > 0) return "protected";
151
+ await run("UPDATE builds SET retention_state = 'deleting' WHERE project_id = ? AND id = ?", [projectId, buildId]);
152
+ return "claimed";
153
+ });
154
+ }
155
+ export { advance, createBuildReferenceLifecycle, lockFence };
156
+
157
+ //# sourceMappingURL=build-reference-lifecycle.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build-reference-lifecycle.mjs","names":[],"sources":["../src/build-reference-lifecycle.ts"],"sourcesContent":["/**\n * MySQL's implementation of the build retention lifecycle (ADR 0039), over InnoDB row locks taken\n * in one fixed order (owners by key, then builds by id), the order Postgres uses:\n *\n * - an owner's `build_reference_generations` row is locked `FOR UPDATE`, which is the fence. It is\n * created with `INSERT ... ON DUPLICATE KEY UPDATE`, which takes the row's exclusive lock at once:\n * `INSERT IGNORE` would take a shared lock first, and two writers upgrading a shared lock to\n * `FOR UPDATE` deadlock;\n * - each referenced build row is locked `FOR SHARE`, which conflicts with {@link claimDeletion}'s\n * `FOR UPDATE` of the same row, so an admission and a tombstone of one build cannot both win.\n *\n * Every transaction runs at READ COMMITTED on a connection of its own (`lifecycle-transaction.ts`).\n */\nimport {\n ReferenceGenerationConflict,\n type BuildReferenceLifecycle,\n type BuildReferenceOwner,\n type FencedBuildReferenceChange,\n type TxStore,\n} from \"@storyshelf/core/adapter/database\";\nimport {\n completeDeletion,\n listDeleting,\n markStorageDeleted,\n releaseBuildContent,\n} from \"./build-deletion-steps.ts\";\nimport {\n abandonContentClaim,\n claimContent,\n contentUsage,\n finishContentCollection,\n holdsContentClaim,\n recordContentUses,\n} from \"./content-uses.ts\";\nimport { inTransaction, type LifecyclePool, type LifecycleTx } from \"./lifecycle-transaction.ts\";\n\ntype Change = FencedBuildReferenceChange & { ids: string[] };\n\n/** The lifecycle over a mysql2/promise pool; each operation borrows a connection and opens its own transaction. */\nexport function createBuildReferenceLifecycle(pool: LifecyclePool): BuildReferenceLifecycle {\n return {\n referenceGeneration: async (owner) => await referenceGeneration(pool, owner),\n replaceManyFencedReferences: async (changes, writeDomain) =>\n await replaceManyFencedReferences(pool, changes, writeDomain),\n replaceFencedReferences: async (owner, generation, ids, writeDomain) => {\n const changes = [{ owner, expectedGeneration: generation, buildIds: ids }];\n const updated = await replaceManyFencedReferences(pool, changes, writeDomain);\n return { result: updated.result, generation: generation + 1 };\n },\n claimDeletion: async (projectId, buildId) => await claimDeletion(pool, projectId, buildId),\n listDeleting: async (projectId) => await listDeleting(pool, projectId),\n releaseBuildContent: async (projectId, buildId, hashes) =>\n await releaseBuildContent(pool, projectId, buildId, hashes),\n markStorageDeleted: async (projectId, buildId) =>\n await markStorageDeleted(pool, projectId, buildId),\n completeDeletion: async (projectId, buildId, removeRows) =>\n await completeDeletion(pool, projectId, buildId, removeRows),\n recordContentUses: async (projectId, buildId, hashes, staleBefore, sizes) =>\n await recordContentUses(pool, projectId, buildId, hashes, staleBefore, sizes),\n contentUsage: async (projectId) => await contentUsage(pool, projectId),\n claimContent: async (token, idleBefore, staleBefore) =>\n await claimContent(pool, token, idleBefore, staleBefore),\n holdsContentClaim: async (hash, token) => await holdsContentClaim(pool, hash, token),\n abandonContentClaim: async (hash, token) => {\n await abandonContentClaim(pool, hash, token);\n },\n finishContentCollection: async (hash, token) => {\n await finishContentCollection(pool, hash, token);\n },\n };\n}\n\nconst OWNER = \"project_id = ? AND owner_type = ? AND owner_id = ?\";\n\nfunction ownerParams(owner: BuildReferenceOwner): string[] {\n return [owner.projectId, owner.type, owner.id];\n}\n\nasync function referenceGeneration(\n pool: LifecyclePool,\n owner: BuildReferenceOwner,\n): Promise<number> {\n return await inTransaction(pool, async ({ query }) => {\n const rows = await query(\n `SELECT generation FROM build_reference_generations WHERE ${OWNER}`,\n ownerParams(owner),\n );\n return Number(rows[0]?.[\"generation\"] ?? 0);\n });\n}\n\n/**\n * Fence every owner, run the domain write, then replace the references and advance the fences. The\n * domain write is the caller's: a deadlock is not retried here (it reaches the caller, with every\n * write of the transaction rolled back).\n */\nasync function replaceManyFencedReferences<T>(\n pool: LifecyclePool,\n changes: readonly FencedBuildReferenceChange[],\n writeDomain: (tx: TxStore) => Promise<T>,\n): Promise<{ result: T; generations: number[] }> {\n validateFencedChanges(changes);\n const normalized = changes.map((change) => ({\n ...change,\n ids: [...new Set(change.buildIds)].toSorted(),\n }));\n return await inTransaction(\n pool,\n async (tx) => {\n for (const change of byOwnerKey(normalized)) {\n // oxlint-disable-next-line no-await-in-loop -- locks are taken one at a time, in key order\n await fence(tx, change);\n }\n await lockAvailable(tx, normalized);\n const result = await writeDomain(tx.store);\n for (const change of normalized) {\n // oxlint-disable-next-line no-await-in-loop -- each owner's rows are replaced in turn\n await saveReferences(tx, change);\n }\n return { result, generations: normalized.map((change) => change.expectedGeneration + 1) };\n },\n false,\n );\n}\n\nfunction ownerKey({ owner }: Change): string {\n return JSON.stringify([owner.projectId, owner.type, owner.id]);\n}\n\n/** The lock order: owners by key, whatever order the caller listed them in. */\nfunction byOwnerKey(changes: readonly Change[]): Change[] {\n return changes.toSorted((left, right) => ownerKey(left).localeCompare(ownerKey(right)));\n}\n\nfunction validateFencedChanges(changes: readonly FencedBuildReferenceChange[]): void {\n const keys = changes.map(({ owner }) => JSON.stringify([owner.projectId, owner.type, owner.id]));\n if (new Set(keys).size !== keys.length) throw new Error(\"Duplicate reference owner\");\n for (const { expectedGeneration } of changes) {\n const valid = Number.isSafeInteger(expectedGeneration) && expectedGeneration >= 0;\n if (!valid || expectedGeneration >= Number.MAX_SAFE_INTEGER)\n throw new Error(\"Invalid reference generation\");\n }\n}\n\n/**\n * Create the owner's generation row at zero if needed and hold its exclusive lock: the fence every\n * writer, and preparation, takes first.\n */\nexport async function lockFence(tx: LifecycleTx, owner: BuildReferenceOwner): Promise<number> {\n await tx.run(\n `INSERT INTO build_reference_generations (project_id, owner_type, owner_id, generation)\n VALUES (?, ?, ?, 0) ON DUPLICATE KEY UPDATE generation = generation`,\n ownerParams(owner),\n );\n const rows = await tx.query(\n `SELECT generation FROM build_reference_generations WHERE ${OWNER} FOR UPDATE`,\n ownerParams(owner),\n );\n return Number(rows[0]?.[\"generation\"]);\n}\n\n/** Every reference mutation advances the owner's fence. */\nexport async function advance(tx: LifecycleTx, owner: BuildReferenceOwner): Promise<void> {\n await tx.run(\n `UPDATE build_reference_generations SET generation = generation + 1 WHERE ${OWNER}`,\n ownerParams(owner),\n );\n}\n\n/** Lock the owner's fence and reject a stale expectation. */\nasync function fence(tx: LifecycleTx, { owner, expectedGeneration }: Change): Promise<void> {\n if ((await lockFence(tx, owner)) !== expectedGeneration)\n throw new ReferenceGenerationConflict(\"Stale reference generation\");\n}\n\n/** Share-lock every referenced build, in id order, and require each to be `available`. */\nasync function lockAvailable(tx: LifecycleTx, changes: readonly Change[]): Promise<void> {\n const byProject = Map.groupBy(changes, ({ owner }) => owner.projectId);\n const projects = [...byProject.keys()].toSorted();\n for (const projectId of projects) {\n const ids = [...new Set((byProject.get(projectId) ?? []).flatMap((change) => change.ids))];\n if (ids.length === 0) continue;\n // oxlint-disable-next-line no-await-in-loop -- one project's builds at a time, in project order\n const rows = await tx.query(\n `SELECT id, retention_state FROM builds\n WHERE project_id = ? AND id IN (?) ORDER BY id FOR SHARE`,\n [projectId, ids.toSorted()],\n );\n const available = rows.filter((row) => row[\"retention_state\"] === \"available\");\n if (available.length !== ids.length) throw new Error(\"Referenced build is unavailable\");\n }\n}\n\nasync function saveReferences(tx: LifecycleTx, { owner, ids }: Change): Promise<void> {\n await tx.run(`DELETE FROM build_references WHERE ${OWNER}`, ownerParams(owner));\n if (ids.length > 0) {\n await tx.run(\n \"INSERT INTO build_references (project_id, owner_type, owner_id, build_id) VALUES ?\",\n [ids.map((id) => [...ownerParams(owner), id])],\n );\n }\n await advance(tx, owner);\n}\n\n/** Tombstone the build under its row lock, unless a reference protects it. */\nasync function claimDeletion(\n pool: LifecyclePool,\n projectId: string,\n buildId: string,\n): Promise<\"claimed\" | \"protected\" | \"deleting\" | \"missing\"> {\n return await inTransaction(pool, async ({ query, run }) => {\n const build = await query(\n \"SELECT retention_state FROM builds WHERE project_id = ? AND id = ? FOR UPDATE\",\n [projectId, buildId],\n );\n if (build.length === 0) return \"missing\";\n if (build[0]?.[\"retention_state\"] !== \"available\") return \"deleting\";\n const refs = await query(\"SELECT 1 FROM build_references WHERE build_id = ? LIMIT 1\", [\n buildId,\n ]);\n if (refs.length > 0) return \"protected\";\n await run(\"UPDATE builds SET retention_state = 'deleting' WHERE project_id = ? AND id = ?\", [\n projectId,\n buildId,\n ]);\n return \"claimed\";\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,8BAA8B,MAA8C;CAC1F,OAAO;EACL,qBAAqB,OAAO,UAAU,MAAM,oBAAoB,MAAM,KAAK;EAC3E,6BAA6B,OAAO,SAAS,gBAC3C,MAAM,4BAA4B,MAAM,SAAS,WAAW;EAC9D,yBAAyB,OAAO,OAAO,YAAY,KAAK,gBAAgB;GAGtE,OAAO;IAAE,SAAQ,MADK,4BAA4B,MAAM,CADvC;KAAE;KAAO,oBAAoB;KAAY,UAAU;IAAI,CACV,GAAG,WAAW,EAAA,CACnD;IAAQ,YAAY,aAAa;GAAE;EAC9D;EACA,eAAe,OAAO,WAAW,YAAY,MAAM,cAAc,MAAM,WAAW,OAAO;EACzF,cAAc,OAAO,cAAc,MAAM,aAAa,MAAM,SAAS;EACrE,qBAAqB,OAAO,WAAW,SAAS,WAC9C,MAAM,oBAAoB,MAAM,WAAW,SAAS,MAAM;EAC5D,oBAAoB,OAAO,WAAW,YACpC,MAAM,mBAAmB,MAAM,WAAW,OAAO;EACnD,kBAAkB,OAAO,WAAW,SAAS,eAC3C,MAAM,iBAAiB,MAAM,WAAW,SAAS,UAAU;EAC7D,mBAAmB,OAA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