@vercel/board 0.31.0 → 0.33.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 (166) hide show
  1. package/README.md +25 -20
  2. package/dist/{access-CY5xVMIK.mjs → access-N3XmkKXg.mjs} +3 -3
  3. package/dist/access.d.mts +4 -5
  4. package/dist/access.mjs +5 -5
  5. package/dist/{actors-Bm-ojWWT.mjs → actors-ihyN47OV.mjs} +3 -3
  6. package/dist/{auth-DLYSt_-A.d.mts → auth-D6z3rMNj.d.mts} +11 -93
  7. package/dist/{auth-CyO2aw5n.mjs → auth-r-_PeZyw.mjs} +39 -151
  8. package/dist/{backend-Bob-5CM7.d.mts → backend-CWpyR1A7.d.mts} +81 -51
  9. package/dist/backend-local.d.mts +28 -0
  10. package/dist/backend-local.mjs +2 -0
  11. package/dist/{chat-provider-DkFp2hrh.mjs → chat-provider-9hCT654s.mjs} +2 -2
  12. package/dist/{chat-provider-BChYrrA7.d.mts → chat-provider-DJpFUaFv.d.mts} +2 -3
  13. package/dist/cli-commands.d.mts +1 -1
  14. package/dist/cli-commands.mjs +1 -1
  15. package/dist/cli-embedded.d.mts +2 -2
  16. package/dist/cli-embedded.mjs +2 -2
  17. package/dist/cli.mjs +6 -6
  18. package/dist/{commands-DK4W3HCJ.d.mts → commands-BOBQHVqM.d.mts} +14 -0
  19. package/dist/{commands-L1JSGz2Z.mjs → commands-CHoMl06v.mjs} +39 -12
  20. package/dist/{conformance-DK43HiHf.mjs → conformance-qKmGLTAT.mjs} +40 -5
  21. package/dist/conformance.d.mts +1 -1
  22. package/dist/conformance.mjs +1 -1
  23. package/dist/{engine-DurYIRt8.mjs → engine-JxgZiikU.mjs} +6 -8
  24. package/dist/{errors-CJXhhzvT.mjs → errors-Pk0XV1hK.mjs} +56 -2
  25. package/dist/{events-lujPA3gQ.mjs → events-IQg0k281.mjs} +2 -2
  26. package/dist/exports-BuKjVq2t.d.mts +4 -0
  27. package/dist/exports-gHDHlg0i.mjs +3207 -0
  28. package/dist/{external-D3p5T57R.mjs → external-CYe424fO.mjs} +1 -1
  29. package/dist/{folds-DLUzfibJ.d.mts → folds-DjFTiqIM.d.mts} +38 -44
  30. package/dist/index-CXvvYNYj.d.mts +11 -0
  31. package/dist/index.d.mts +9 -8
  32. package/dist/index.mjs +21 -8
  33. package/dist/index.node.d.mts +5 -6
  34. package/dist/index.node.mjs +3 -3
  35. package/dist/inspect/app.js +95 -95
  36. package/dist/{internal-CvsrprnU-zZMpDiRY.mjs → internal-CvsrprnU-CEPOUpAv.mjs} +63 -43
  37. package/dist/local-BbLjA5vI.mjs +8818 -0
  38. package/dist/{main-Dz-8komG.mjs → main-CQpCZJFw.mjs} +140 -36
  39. package/dist/{backend-a2/store-memory.mjs → memory-7RRnLa4X.mjs} +3 -3
  40. package/dist/middleware-BU7rVi9F.mjs +103 -0
  41. package/dist/{client-COfYrgfV.d.mts → provider-BlzUvcM9.d.mts} +665 -5
  42. package/dist/{schemas-DBmUO6pr.mjs → schemas-BG205xds.mjs} +2 -5
  43. package/dist/{serve-CTmow-YH.mjs → serve-D8_W4UN6.mjs} +33 -24
  44. package/dist/{node-BgeGcwX0.mjs → server-BiIUXWbU.mjs} +419 -6
  45. package/dist/{serving-DBFRo6U_.mjs → serving-D7rcUtSC.mjs} +1 -1
  46. package/dist/{sql-CT5xVuGr.mjs → sql-BQzKUqQt.mjs} +349 -114
  47. package/dist/sqlite-DCtZFEVm.mjs +30 -0
  48. package/dist/{sqlite-db-0WeSOEZN.mjs → sqlite-db-qLTs52Ny.mjs} +2 -3
  49. package/dist/{store-codec-pAG2oPgQ-SqDXlPBR.mjs → store-N8PXxDAS-BdL4Sq-f.mjs} +6 -2
  50. package/dist/{store-memory-B0PkVSuQ.mjs → store-memory-CKQVEzXN.mjs} +2 -4
  51. package/dist/store-memory-OdGsc-t_.mjs +2 -0
  52. package/dist/{store-polling-BZt2Rf3D-Div-bJ_D.mjs → store-polling-BZt2Rf3D-oh3aU_An.mjs} +1 -1
  53. package/dist/store-sqlite-CTxAVCcz.mjs +2 -0
  54. package/dist/{store-sqlite-D85t3tE7.mjs → store-sqlite-D6fIszST.mjs} +3 -4
  55. package/dist/sync-chat-sdk.d.mts +2 -2
  56. package/dist/sync-chat-sdk.mjs +2 -2
  57. package/dist/sync-github.d.mts +2 -2
  58. package/dist/sync-github.mjs +2 -2
  59. package/dist/sync-linear.d.mts +2 -3
  60. package/dist/sync-linear.mjs +2 -2
  61. package/dist/sync-slack.d.mts +3 -3
  62. package/dist/sync-slack.mjs +4 -4
  63. package/dist/sync.d.mts +2 -2
  64. package/dist/sync.mjs +2 -2
  65. package/dist/{watchers-hash-BjwlnGD9.mjs → targets-CknPGGVi.mjs} +40 -10
  66. package/dist/{tokens-Dnyd_y1n.mjs → tokens-DPKjl3jf.mjs} +15 -43
  67. package/docs/01-board/01-mounting.md +243 -288
  68. package/docs/01-board/03-identity.md +41 -50
  69. package/docs/01-board/04-messages.md +19 -16
  70. package/docs/01-board/05-reading.md +3 -3
  71. package/docs/01-board/06-watchers.md +58 -105
  72. package/docs/01-board/07-schedules.md +21 -41
  73. package/docs/01-board/08-middleware.md +11 -17
  74. package/docs/01-board/09-access.md +76 -313
  75. package/docs/01-board/10-local.md +81 -0
  76. package/docs/01-quickstart.md +49 -126
  77. package/docs/02-sync/01-overview.md +25 -80
  78. package/docs/02-sync/02-functions.md +10 -16
  79. package/docs/02-sync/03-slack.md +13 -26
  80. package/docs/02-sync/04-github.md +8 -20
  81. package/docs/02-sync/07-linear.md +6 -10
  82. package/docs/03-guides/02-inspector.md +3 -3
  83. package/docs/03-guides/03-ci.md +88 -128
  84. package/docs/03-guides/04-triage.md +7 -15
  85. package/docs/03-guides/05-agent-factory.md +30 -36
  86. package/docs/04-reference/01-cli.md +118 -32
  87. package/docs/04-reference/02-board.md +60 -74
  88. package/docs/04-reference/03-http.md +119 -57
  89. package/docs/04-reference/05-conformance.md +31 -45
  90. package/docs/index.md +41 -65
  91. package/package.json +12 -83
  92. package/dist/a2-DngWY2Eb.mjs +0 -4238
  93. package/dist/access-DPcrKIH_.d.mts +0 -37
  94. package/dist/backend-a2/blob-vercel.d.mts +0 -8
  95. package/dist/backend-a2/blob-vercel.mjs +0 -81
  96. package/dist/backend-a2/contract.d.mts +0 -828
  97. package/dist/backend-a2/contract.mjs +0 -5
  98. package/dist/backend-a2/scheduler-local.d.mts +0 -11
  99. package/dist/backend-a2/scheduler-local.mjs +0 -2
  100. package/dist/backend-a2/scheduler-qstash.d.mts +0 -79
  101. package/dist/backend-a2/scheduler-qstash.mjs +0 -522
  102. package/dist/backend-a2/scheduler-vercel.d.mts +0 -38
  103. package/dist/backend-a2/scheduler-vercel.mjs +0 -204
  104. package/dist/backend-a2/store-memory.d.mts +0 -11
  105. package/dist/backend-a2/store-postgres.d.mts +0 -38
  106. package/dist/backend-a2/store-postgres.mjs +0 -2977
  107. package/dist/backend-a2/store-redis-http.d.mts +0 -17
  108. package/dist/backend-a2/store-redis-http.mjs +0 -520
  109. package/dist/backend-a2/store-redis.d.mts +0 -31
  110. package/dist/backend-a2/store-redis.mjs +0 -88
  111. package/dist/backend-a2/store-sqlite.d.mts +0 -12
  112. package/dist/backend-a2/store-sqlite.mjs +0 -31
  113. package/dist/backend-a2.d.mts +0 -2633
  114. package/dist/backend-a2.mjs +0 -3
  115. package/dist/backend-http-BRrRbjRx.d.mts +0 -672
  116. package/dist/backend-http-CvUKOn-m.mjs +0 -585
  117. package/dist/backend-http-D8mUzuKQ.mjs +0 -18
  118. package/dist/backend-http.d.mts +0 -10
  119. package/dist/backend-http.mjs +0 -2
  120. package/dist/backend-http.node.d.mts +0 -10
  121. package/dist/backend-http.node.mjs +0 -2
  122. package/dist/backend-vercel-Ba8JDtqW.mjs +0 -86
  123. package/dist/backend-vercel-BaSEUdwg.d.mts +0 -674
  124. package/dist/backend-vercel-CmY9yZ9m.mjs +0 -1656
  125. package/dist/backend-vercel.d.mts +0 -9
  126. package/dist/backend-vercel.mjs +0 -11
  127. package/dist/backend-vercel.node.d.mts +0 -17
  128. package/dist/backend-vercel.node.mjs +0 -2
  129. package/dist/blob-Bx8QPWEd.d.mts +0 -40
  130. package/dist/blob-WbB2DJKn.mjs +0 -201
  131. package/dist/errors-2vGs49Db.d.mts +0 -16
  132. package/dist/exports-CWIdN0Ub.mjs +0 -1389
  133. package/dist/exports-FBOQWT7O.d.mts +0 -5
  134. package/dist/files-SniSmeEr.mjs +0 -47
  135. package/dist/folds-Cu9Q9zyQ.mjs +0 -207
  136. package/dist/index-Ho-ayyQL.d.mts +0 -11
  137. package/dist/index.default-BUcwDaAe.mjs +0 -12
  138. package/dist/local-C76Fy5ad.mjs +0 -44
  139. package/dist/middleware-BavYSDUa.mjs +0 -62
  140. package/dist/platform-B4TnJtWu-Do3agKr5.mjs +0 -32
  141. package/dist/project-CQ4VUibA.mjs +0 -124
  142. package/dist/provider-gynDUoyW.d.mts +0 -665
  143. package/dist/redis-tables-DHf85ixI.mjs +0 -3895
  144. package/dist/reducer-Bswr11ar-P324o9vn.mjs +0 -74
  145. package/dist/reducer-CYPHsSmd-BXjGiptm.d.mts +0 -170
  146. package/dist/reducers-DcENwtwZ.mjs +0 -538
  147. package/dist/retryable-lazy-DZWmHpii-DpTc5PIP.mjs +0 -19
  148. package/dist/scheduler-task-X1SToDjP-D2Il2rln.mjs +0 -69
  149. package/dist/server-B9gu0qi1-DI1WvcVK.d.mts +0 -391
  150. package/dist/server-DG8D6VV0.mjs +0 -17
  151. package/dist/server-DX7mM6nm-D7N_7bug.mjs +0 -3611
  152. package/dist/session-clear-XJYpmUpg-2q8l_FJR.mjs +0 -63
  153. package/dist/store-DEzcHZOA-B-5vhxef.d.mts +0 -540
  154. package/dist/store-N8PXxDAS-DWWgv-Vz.mjs +0 -5
  155. package/dist/store-memory-4IBl0Ztu.mjs +0 -2
  156. package/dist/store-presence-polling-JuAy2Ck2-Dh-g_KYM.mjs +0 -109
  157. package/dist/store-sqlite-iBTYYKBj.mjs +0 -2
  158. package/dist/stream-buffer-DrTyiIuo-Be10yOBR.mjs +0 -53
  159. package/dist/targets-Cgjs29T0.mjs +0 -33
  160. package/dist/types-CmrFjpml.d.mts +0 -102
  161. package/dist/wait-until-Dw4XrIDQ.mjs +0 -42
  162. package/docs/01-board/02-database.md +0 -258
  163. package/docs/04-reference/04-log.md +0 -247
  164. package/sql/postgres/board.sql +0 -145
  165. package/sql/postgres/notifications.sql +0 -24
  166. package/sql/postgres/schema.sql +0 -451
@@ -1,2977 +0,0 @@
1
- import { a as duplicateBatchError, c as sessionClearedError, l as supersededAttemptError, n as CLEAR_EVENT_TYPE, s as lastIndexMismatchError, t as A2Error } from "../session-clear-XJYpmUpg-2q8l_FJR.mjs";
2
- import { m as nullProtoRecord, n as NOTIFY_TIMINGS } from "../internal-CvsrprnU-zZMpDiRY.mjs";
3
- import { n as defaultSleep, r as pollingStream } from "../store-polling-BZt2Rf3D-Div-bJ_D.mjs";
4
- import { r as platformWaitUntil } from "../platform-B4TnJtWu-Do3agKr5.mjs";
5
- import { t as retryableLazy } from "../retryable-lazy-DZWmHpii-DpTc5PIP.mjs";
6
- import { r as sqlTables } from "../sql-CT5xVuGr.mjs";
7
- import { a as idleLogCursor, i as idempotentReplay, n as decodeCause, r as decodeReturnedEventIds, t as cursorKeyOf } from "../store-codec-pAG2oPgQ-SqDXlPBR.mjs";
8
- import { n as SYSTEM_CLOCK, t as RANDOM_IDS } from "../store-N8PXxDAS-DWWgv-Vz.mjs";
9
- import { t as pollPresence } from "../store-presence-polling-JuAy2Ck2-Dh-g_KYM.mjs";
10
- import { createHash } from "node:crypto";
11
- //#region ../../node_modules/.pnpm/experimental-a2@0.24.0_@upstash+qstash@2.12.0_@vercel+queue@0.7.0_ai@7.0.130_zod@4.6.5__b1e2c243a963f2620a5d202817417c26/node_modules/experimental-a2/dist/store-postgres.js
12
- const postgresNotificationChannel = ({ kind, sessionId }) => `a2_${kind}_${createHash("md5").update(sessionId).digest("hex")}`;
13
- function postgresNotifications(createConnection) {
14
- const channels = /* @__PURE__ */ new Map();
15
- const ending = /* @__PURE__ */ new Set();
16
- const end = (connection) => {
17
- if (!connection) return;
18
- const pending = connection.end().catch(() => {}).finally(() => {
19
- ending.delete(pending);
20
- });
21
- ending.add(pending);
22
- };
23
- let current;
24
- let task;
25
- let retry;
26
- let delay = 100;
27
- let connectedAt = 0;
28
- let closed = false;
29
- const queues = /* @__PURE__ */ new WeakMap();
30
- const query = ({ connection, text }) => {
31
- const result = (queues.get(connection) ?? Promise.resolve()).then(() => {
32
- if (current !== connection) throw new Error("Postgres listener disconnected");
33
- return connection.query(text);
34
- });
35
- queues.set(connection, result.catch(() => {}));
36
- return result;
37
- };
38
- const fail = ({ connection, error }) => {
39
- if (connection !== current) return;
40
- current = void 0;
41
- end(connection);
42
- for (const entry of channels.values()) {
43
- entry.listening = false;
44
- for (const watcher of entry.watchers) watcher.reject(error);
45
- }
46
- if (closed || channels.size === 0 || retry) return;
47
- if (Date.now() - connectedAt >= NOTIFY_TIMINGS.safetyReadMs) delay = 100;
48
- retry = defaultSleep(delay);
49
- delay = Math.min(delay * 2, NOTIFY_TIMINGS.safetyReadMs);
50
- retry.promise.then(() => {
51
- retry = void 0;
52
- reconcile();
53
- });
54
- };
55
- const reconcile = () => {
56
- if (closed || task || retry || channels.size === 0) return;
57
- let attempt;
58
- task = (async () => {
59
- if (!current) {
60
- connectedAt = Date.now();
61
- const connection = await createConnection();
62
- if (closed || channels.size === 0) {
63
- await connection.end();
64
- return;
65
- }
66
- current = connection;
67
- attempt = connection;
68
- connectedAt = Date.now();
69
- connection.onNotification(({ channel, payload }) => {
70
- if (current !== connection) return;
71
- for (const watcher of channels.get(channel)?.watchers ?? []) watcher.notify(payload ?? "");
72
- });
73
- connection.onError((error) => fail({
74
- connection,
75
- error
76
- }));
77
- connection.onEnd(() => fail({
78
- connection,
79
- error: /* @__PURE__ */ new Error("Postgres listener disconnected")
80
- }));
81
- await connection.connect();
82
- if (current !== connection) return;
83
- }
84
- const connection = current;
85
- attempt = connection;
86
- for (const [channel, entry] of channels) {
87
- if (entry.listening) continue;
88
- entry.listening = true;
89
- entry.ready = query({
90
- connection,
91
- text: `LISTEN "${channel.replaceAll("\"", "\"\"")}"`
92
- });
93
- await entry.ready;
94
- if (current !== connection) return;
95
- for (const watcher of entry.watchers) {
96
- watcher.resolve();
97
- watcher.notify("");
98
- }
99
- }
100
- })().catch((error) => {
101
- if (attempt === current) fail({
102
- connection: attempt,
103
- error
104
- });
105
- }).finally(() => {
106
- task = void 0;
107
- if ([...channels.values()].some((entry) => !entry.listening)) reconcile();
108
- });
109
- };
110
- return {
111
- watch({ channel, notify }) {
112
- let resolve;
113
- let reject;
114
- const ready = new Promise((yes, no) => {
115
- resolve = yes;
116
- reject = no;
117
- });
118
- const watcher = {
119
- notify,
120
- resolve,
121
- reject
122
- };
123
- let entry = channels.get(channel);
124
- if (!entry) {
125
- entry = {
126
- listening: false,
127
- watchers: /* @__PURE__ */ new Set()
128
- };
129
- channels.set(channel, entry);
130
- }
131
- entry.watchers.add(watcher);
132
- if (entry.listening) entry.ready?.then(resolve, reject);
133
- reconcile();
134
- let stopped = false;
135
- return {
136
- ready,
137
- stop() {
138
- if (stopped) return;
139
- stopped = true;
140
- resolve();
141
- entry.watchers.delete(watcher);
142
- if (entry.watchers.size > 0) return;
143
- channels.delete(channel);
144
- if (channels.size === 0) {
145
- retry?.cancel();
146
- const connection = current;
147
- current = void 0;
148
- end(connection);
149
- } else if (entry.listening) {
150
- const connection = current;
151
- if (connection) query({
152
- connection,
153
- text: `UNLISTEN "${channel.replaceAll("\"", "\"\"")}"`
154
- }).catch((error) => fail({
155
- connection,
156
- error
157
- }));
158
- }
159
- }
160
- };
161
- },
162
- async close() {
163
- closed = true;
164
- retry?.cancel();
165
- for (const entry of channels.values()) for (const watcher of entry.watchers) watcher.resolve();
166
- channels.clear();
167
- const connection = current;
168
- current = void 0;
169
- end(connection);
170
- await Promise.all(ending);
171
- }
172
- };
173
- }
174
- /**
175
- * The Postgres schema contract. A2 never runs DDL in a Postgres database:
176
- * `sql/postgres/schema.sql`, or the tables in `drizzle-schema.ts` next to it,
177
- * create
178
- * the tables, and `notifications.sql` the triggers `listenConnectionString`
179
- * needs. A store checks nothing up front. A query that finds a table or column
180
- * missing fails anyway, so the store only turns that failure into one that
181
- * says what to apply. Missing triggers fail no query, so a listening store
182
- * looks for them when its listener starts.
183
- */
184
- const PACKAGE = "node_modules/experimental-a2";
185
- const SEE_DOCS = `See ${PACKAGE}/docs/stores/04-postgres.mdx.`;
186
- /** Postgres error codes a store that hasn't been set up raises. */
187
- const UNDEFINED_TABLE = "42P01";
188
- const UNDEFINED_COLUMN = "42703";
189
- const UNDEFINED_FUNCTION = "42883";
190
- /** `a2_batch` refuses to run outside read committed. */
191
- const BATCH_ISOLATION = "A2002";
192
- const INSUFFICIENT_PRIVILEGE = "42501";
193
- /** NUL, which Postgres can't store: in jsonb (`\u0000`), or in text. */
194
- const UNTRANSLATABLE_CHARACTER = "22P05";
195
- const CHARACTER_NOT_IN_REPERTOIRE = "22021";
196
- /** The Postgres error in `error`'s cause chain, for clients that wrap theirs. */
197
- const postgresError = (error) => {
198
- for (let current = error, depth = 0; depth < 5; depth += 1) {
199
- if (typeof current !== "object" || current === null) return void 0;
200
- const { code, message, cause } = current;
201
- if (typeof code === "string" && /^[0-9A-Z]{5}$/.test(code)) return {
202
- code,
203
- message: typeof message === "string" ? message : code
204
- };
205
- current = cause;
206
- }
207
- };
208
- /** Explains a query that failed because A2's tables aren't set up, or on a NUL, or returns `error`. */
209
- const explainPostgresError = (error) => {
210
- const found = postgresError(error);
211
- if (found?.code === UNDEFINED_TABLE || found?.code === UNDEFINED_COLUMN || found?.code === UNDEFINED_FUNCTION) return new A2Error("STORE_NOT_CONFIGURED", `${found.message}: A2's tables or its function are missing, or from an earlier release, and A2 doesn't create or change them at runtime. Apply ${PACKAGE}/sql/postgres/schema.sql to this database, or migrate it to the tables in drizzle-schema.ts next to it, with schema.sql's a2_batch function. ${SEE_DOCS}`, { cause: error });
212
- if (found?.code === INSUFFICIENT_PRIVILEGE) return new A2Error("STORE_NOT_CONFIGURED", `${found.message}: the role this store connects as needs select, insert, update, and delete on A2's tables, and execute on a2_batch. Create them as that role, or grant it those privileges. ${SEE_DOCS}`, { cause: error });
213
- if (found?.code === UNTRANSLATABLE_CHARACTER || found?.code === CHARACTER_NOT_IN_REPERTOIRE) return new A2Error("INVALID_PAYLOAD", `${found.message}: Postgres can't store a NUL character (\\u0000) in text or jsonb, so nothing was written. Remove it before appending.`, { cause: error });
214
- if (found?.code === BATCH_ISOLATION) return new A2Error("STORE_NOT_CONFIGURED", `${found.message}: A2 reads what it locks in read committed, Postgres's default, and its connections here default to a stricter level. Set default_transaction_isolation to 'read committed' for the role or database this store connects to. ${SEE_DOCS}`, { cause: error });
215
- return error;
216
- };
217
- const explained = (promise) => promise.catch((error) => {
218
- throw explainPostgresError(error);
219
- });
220
- /** `client`, with every query's setup failures explained. */
221
- const explainingPostgresClient = (client) => ({
222
- query: (text, values) => explained(client.query(text, values)),
223
- ...client.connect && { connect: async () => {
224
- const connection = await client.connect();
225
- return {
226
- query: (text, values) => explained(connection.query(text, values)),
227
- release: () => connection.release()
228
- };
229
- } },
230
- ...client.end && { end: () => client.end() }
231
- });
232
- /** Fails when the triggers `listenConnectionString` listens to are missing. */
233
- const checkPostgresTriggers = async (client) => {
234
- const { rows } = await client.query(`select count(*) as triggers from pg_trigger
235
- where (tgname = 'a2_notify_events' and tgrelid = to_regclass('a2_events'))
236
- or (tgname = 'a2_notify_presence' and tgrelid = to_regclass('a2_presence'))`);
237
- if (Number(rows[0]?.["triggers"]) < 2) throw new A2Error("STORE_NOT_CONFIGURED", `listenConnectionString needs A2's notification triggers, which aren't in this Postgres database. After schema.sql, apply ${PACKAGE}/sql/postgres/notifications.sql to this database. ${SEE_DOCS}`);
238
- };
239
- const failure = (error) => error instanceof A2Error ? error : new A2Error("STORE_UNAVAILABLE", "Postgres subscription failed", { cause: error });
240
- function postgresNotificationScope(load) {
241
- const state = {
242
- shared: retryableLazy(load),
243
- stops: /* @__PURE__ */ new Set(),
244
- closed: false
245
- };
246
- const scope = {
247
- watch(options) {
248
- let stopped = false;
249
- let cancel;
250
- const cancelled = new Promise((resolve) => {
251
- cancel = resolve;
252
- });
253
- let subscription;
254
- const stop = () => {
255
- stopped = true;
256
- cancel();
257
- subscription?.stop();
258
- state.stops.delete(stop);
259
- };
260
- state.stops.add(stop);
261
- return {
262
- ready: Promise.race([cancelled, state.shared.get().then(async ({ value }) => {
263
- if (stopped || state.closed) return;
264
- subscription = value.watch(options);
265
- await subscription.ready;
266
- })]).catch((error) => {
267
- if (!stopped && !state.closed) throw failure(error);
268
- }),
269
- stop
270
- };
271
- },
272
- stream({ channel, read, startAfter }) {
273
- return { [Symbol.asyncIterator]() {
274
- let stopped = false;
275
- let after = startAfter;
276
- let buffer = [];
277
- let position = 0;
278
- let version = 0;
279
- let waiting;
280
- let lease;
281
- const stop = () => {
282
- stopped = true;
283
- buffer = [];
284
- position = 0;
285
- waiting?.cancel();
286
- lease?.stop();
287
- state.stops.delete(stop);
288
- };
289
- state.stops.add(stop);
290
- return {
291
- async next() {
292
- try {
293
- if (stopped || state.closed) return {
294
- done: true,
295
- value: void 0
296
- };
297
- lease ??= scope.watch({
298
- channel,
299
- notify: () => {
300
- version += 1;
301
- waiting?.cancel();
302
- }
303
- });
304
- await lease.ready;
305
- for (;;) {
306
- if (stopped || state.closed) return {
307
- done: true,
308
- value: void 0
309
- };
310
- const row = buffer[position];
311
- if (row) {
312
- after = row.index;
313
- buffer[position] = void 0;
314
- position += 1;
315
- if (position === buffer.length) {
316
- buffer = [];
317
- position = 0;
318
- }
319
- return {
320
- done: false,
321
- value: row
322
- };
323
- }
324
- const before = version;
325
- const rows = await read(after);
326
- if (stopped || state.closed) return {
327
- done: true,
328
- value: void 0
329
- };
330
- buffer = rows;
331
- position = 0;
332
- if (buffer.length || before !== version) continue;
333
- waiting = defaultSleep(NOTIFY_TIMINGS.safetyReadMs);
334
- await waiting.promise;
335
- }
336
- } catch (error) {
337
- if (stopped || state.closed) return {
338
- done: true,
339
- value: void 0
340
- };
341
- stop();
342
- throw failure(error);
343
- }
344
- },
345
- async return() {
346
- stop();
347
- return {
348
- done: true,
349
- value: void 0
350
- };
351
- }
352
- };
353
- } };
354
- },
355
- async close() {
356
- if (state.closed) return;
357
- state.closed = true;
358
- for (const stop of state.stops) stop();
359
- await (await state.shared.peek()?.catch(() => void 0))?.release();
360
- }
361
- };
362
- return scope;
363
- }
364
- function postgresPoolClient(pool) {
365
- let timer;
366
- let resolve;
367
- const finish = () => {
368
- clearTimeout(timer);
369
- timer = void 0;
370
- resolve?.();
371
- resolve = void 0;
372
- };
373
- const keepAlive = () => {
374
- const idleTimeout = pool.options.idleTimeoutMillis;
375
- if (pool.ending || pool.idleCount === 0 || typeof idleTimeout !== "number" || !Number.isFinite(idleTimeout) || idleTimeout <= 0) return;
376
- finish();
377
- const pending = new Promise((done) => {
378
- resolve = done;
379
- timer = setTimeout(finish, idleTimeout + 100);
380
- timer.unref();
381
- });
382
- platformWaitUntil(pending);
383
- };
384
- pool.on("remove", () => {
385
- if (pool.totalCount === 0) finish();
386
- });
387
- return {
388
- async query(text, values) {
389
- try {
390
- return await pool.query(text, values);
391
- } finally {
392
- keepAlive();
393
- }
394
- },
395
- async connect() {
396
- const client = await pool.connect();
397
- return {
398
- query: (text, values) => client.query(text, values),
399
- release() {
400
- try {
401
- client.release();
402
- } finally {
403
- keepAlive();
404
- }
405
- }
406
- };
407
- },
408
- async end() {
409
- try {
410
- await pool.end();
411
- } finally {
412
- finish();
413
- }
414
- }
415
- };
416
- }
417
- const registryKey = Symbol.for("experimental-a2.postgres-resources.v3");
418
- const registry = () => {
419
- let value = Reflect.get(globalThis, registryKey);
420
- if (!value) {
421
- value = {
422
- pools: /* @__PURE__ */ new Map(),
423
- injected: /* @__PURE__ */ new WeakMap(),
424
- listeners: /* @__PURE__ */ new Map(),
425
- identities: /* @__PURE__ */ new WeakMap(),
426
- nextIdentity: 0
427
- };
428
- Reflect.set(globalThis, registryKey, value);
429
- }
430
- return value;
431
- };
432
- const acquire = ({ cache, key, create }) => {
433
- let entry = cache.get(key);
434
- if (!entry) {
435
- entry = {
436
- value: create(),
437
- refs: 0
438
- };
439
- cache.set(key, entry);
440
- }
441
- entry.refs += 1;
442
- const held = entry;
443
- let released = false;
444
- return {
445
- value: entry.value,
446
- async release() {
447
- if (released) return;
448
- released = true;
449
- held.refs -= 1;
450
- if (held.refs !== 0) return;
451
- if (cache.get(key) === held) cache.delete(key);
452
- await held.value.close();
453
- }
454
- };
455
- };
456
- function postgresConnectionKey({ connectionString, defaults }) {
457
- const shared = registry();
458
- const visited = /* @__PURE__ */ new Set();
459
- const identity = (value) => {
460
- let id = shared.identities.get(value);
461
- if (id === void 0) {
462
- id = ++shared.nextIdentity;
463
- shared.identities.set(value, id);
464
- }
465
- return id;
466
- };
467
- const encode = (value) => {
468
- if (typeof value === "function") return ["reference", identity(value)];
469
- if (value === null || typeof value !== "object") return [typeof value, String(value)];
470
- if (Buffer.isBuffer(value)) return ["buffer", value.toString("base64")];
471
- const prototype = Object.getPrototypeOf(value);
472
- if (visited.has(value) || prototype !== Object.prototype && prototype !== null && !Array.isArray(value)) return ["reference", identity(value)];
473
- visited.add(value);
474
- const result = [Array.isArray(value) ? "array" : "object", Object.getOwnPropertyNames(value).toSorted().map((key) => [key, encode(Reflect.get(value, key))])];
475
- visited.delete(value);
476
- return result;
477
- };
478
- const environment = Object.keys(process.env).filter((key) => key.startsWith("PG")).toSorted().map((key) => [key, process.env[key]]);
479
- return createHash("sha256").update(JSON.stringify([
480
- connectionString,
481
- environment,
482
- encode(defaults)
483
- ])).digest("hex");
484
- }
485
- const queries = (raw) => {
486
- let pending = Promise.resolve();
487
- const initialized = /* @__PURE__ */ new Map();
488
- const exclusive = (fn) => {
489
- const result = pending.then(fn);
490
- pending = result.catch(() => {});
491
- return result;
492
- };
493
- return {
494
- raw,
495
- client: raw.connect ? raw : { query: (text, values) => exclusive(() => raw.query(text, values)) },
496
- exclusive,
497
- initialize({ key, run }) {
498
- const existing = initialized.get(key);
499
- if (existing) return existing;
500
- const attempt = run();
501
- initialized.set(key, attempt);
502
- attempt.catch(() => {
503
- if (initialized.get(key) === attempt) initialized.delete(key);
504
- });
505
- return attempt;
506
- },
507
- async close() {
508
- await pending;
509
- await raw.end?.();
510
- }
511
- };
512
- };
513
- const sharePostgresPool = ({ key, create }) => acquire({
514
- cache: registry().pools,
515
- key,
516
- create: () => queries(create())
517
- });
518
- const sharePostgresClient = (client) => acquire({
519
- cache: registry().injected,
520
- key: client,
521
- create: () => queries(client)
522
- });
523
- const sharePostgresListener = ({ key, create }) => acquire({
524
- cache: registry().listeners,
525
- key,
526
- create
527
- });
528
- /**
529
- * experimental-a2/store-postgres — postgres store backend (the production path).
530
- *
531
- * Implements the A2Store interface over any client that speaks the tiny
532
- * `PostgresClient` shape below — a `pg` Pool matches it structurally
533
- * (and is what `connectionString` creates, lazily; `pg` is an optional
534
- * peer dependency). The conformance suite in test/conformance is the
535
- * executable contract, run against PGlite (real Postgres, in-process)
536
- * and against a real server when `TEST_DATABASE_URL` is set.
537
- *
538
- * Semantics mirror the sqlite backend: `index` is stored as `idx`,
539
- * timestamps are epoch milliseconds written from the injected clock —
540
- * never SQL `now()`, and dispatch state lives on consumer cursors, not on
541
- * events. Streams poll by default; an optional direct connection enables
542
- * LISTEN/NOTIFY for events and presence. Appends serialize per session via
543
- * `pg_advisory_xact_lock`, so concurrent writers can't race the index
544
- * assignment, and each runs in one round trip (`a2_batch`, below), so the
545
- * lock is held only while the server runs it.
546
- *
547
- * Lock discipline. Completions lock their cursor first, then the session lock
548
- * when they append, or when their cursor goes idle (`completeAttempt`);
549
- * everything else that takes the session lock takes it first. Every
550
- * operation that locks a cursor row locks it only in the exact state it acts
551
- * on (a head, an attempt). Under the session lock, an append never writes a
552
- * cursor row that exists: a lane or log cursor's runs are rows keyed by the
553
- * head each run started at (its epoch), so starting an idle cursor inserts a
554
- * new run and retires the idle row with `skip locked`. An append therefore
555
- * never waits on a cursor row, in particular not on one a completion waiting
556
- * for the session lock holds, or one a clear left behind.
557
- */
558
- const asNumber = (value) => Number(value);
559
- const asNullableNumber = (value) => value === null || value === void 0 ? null : asNumber(value);
560
- /**
561
- * The session's latest clear marker, or 0, as a primary-key subquery. Read
562
- * it in a statement that runs after the operation's lock: a statement's
563
- * snapshot starts with the statement, so one that waited for the lock could
564
- * miss a clear that committed meanwhile.
565
- */
566
- const clearIndexOf = (session) => `coalesce((select clear_index from a2_clears where session_id = ${session}), 0)`;
567
- /**
568
- * Whether a served consumer has a cursor with a head in the session. A null
569
- * `served` array serves every consumer.
570
- */
571
- const pendingIn = (session, served) => `exists(
572
- select 1 from a2_cursors pending
573
- where pending.session_id = ${session}
574
- and pending.head > ${clearIndexOf(session)}
575
- and pending.failed_at is null
576
- and (${served}::text[] is null or pending.consumer = any(${served}::text[]))
577
- )`;
578
- /** A fresh head's dispatch columns, for `set` clauses. */
579
- const FRESH_DISPATCH = `
580
- attempt_count = 0, first_claimed_at = null, last_claimed_at = null,
581
- claim_holder = null, claim_expires_at = null, failure_count = 0,
582
- last_failed_at = null, last_failed_attempt = null, last_error = null,
583
- failed_at = null`;
584
- /** The head event's columns a claim, dead letter, or listing joins in, prefixed `e_`. */
585
- const HEAD_COLUMNS = `
586
- event.idx as e_idx, event.event_type as e_event_type,
587
- event.payload as e_payload, event.event_id as e_event_id,
588
- event.created_at as e_created_at, event.cause as e_cause`;
589
- const RECLAIM_BATCH = 256;
590
- /**
591
- * A cursor run reclaim deletes once the session is cleared through `$2`:
592
- * one from before the clear, or one a later run of its cursor replaced. A
593
- * log cursor's last run stays: it records that the consumer counts from the
594
- * marker.
595
- */
596
- const SUPERSEDED_CURSOR = `
597
- cur.session_id = $1 and (
598
- (cur.epoch < $2 and cur.kind <> 'log')
599
- or ((cur.head is null or cur.head <= $2) and exists (
600
- select 1 from a2_cursors later
601
- where later.session_id = cur.session_id
602
- and later.cursor_key = cur.cursor_key
603
- and later.consumer = cur.consumer
604
- and later.epoch > cur.epoch
605
- ))
606
- )`;
607
- /**
608
- * A value of `a2_batch`'s one parameter, `$1`: a JSON object the store builds
609
- * for each call. JSON null reads as SQL null.
610
- */
611
- const param = {
612
- text: (key) => `($1->>'${key}')`,
613
- bigint: (key) => `($1->>'${key}')::bigint`,
614
- int: (key) => `($1->>'${key}')::int`,
615
- boolean: (key) => `($1->>'${key}')::boolean`,
616
- jsonb: (key) => `nullif($1->'${key}', 'null'::jsonb)`,
617
- /** A JSON array of strings as text[], or null when the value isn't an array. */
618
- texts: (key) => `(case when jsonb_typeof($1->'${key}') = 'array'
619
- then array(select jsonb_array_elements_text($1->'${key}')) end)`
620
- };
621
- /** Every batch names its session. */
622
- const SESSION = param.text("session");
623
- /**
624
- * The next event after `after` a log cursor takes, as a scalar subquery:
625
- * `types` is its JSON array, or null for every type but the clear marker
626
- * (`clearType`). Each listed type is one probe of `a2_events_types`, so a
627
- * consumer of rare types never scans the events it skips.
628
- */
629
- const nextLogHead = ({ types, after, clearType = param.text("clearType") }) => `
630
- case when ${types} is null then (
631
- select event.idx from a2_events event
632
- where event.session_id = ${SESSION} and event.idx > ${after}
633
- and event.event_type <> ${clearType}
634
- order by event.idx limit 1
635
- ) else (
636
- select min(next.idx)
637
- from jsonb_array_elements_text(${types}) as wanted(event_type)
638
- cross join lateral (
639
- select event.idx from a2_events event
640
- where event.session_id = ${SESSION} and event.event_type = wanted.event_type
641
- and event.idx > ${after}
642
- order by event.idx limit 1
643
- ) next
644
- where wanted.event_type <> ${clearType}
645
- ) end`;
646
- /** The latest run of `target`'s cursor, as a lateral subquery. */
647
- const LATEST_RUN = (target) => `
648
- select cur.epoch, cur.position, cur.head from a2_cursors cur
649
- where cur.session_id = ${SESSION} and cur.cursor_key = ${target}.cursor_key
650
- and cur.consumer = ${target}.consumer
651
- order by cur.epoch desc limit 1`;
652
- /**
653
- * Retires the runs `target` replaces, those idle or superseded by the clear
654
- * marker `clearIndex`, skipping any another operation holds: a later reclaim
655
- * deletes those.
656
- */
657
- const RETIRE_RUNS = (target, clearIndex) => `
658
- idle as materialized (
659
- select cur.ctid from a2_cursors cur
660
- join ${target} on cur.cursor_key = ${target}.cursor_key
661
- and cur.consumer = ${target}.consumer
662
- where cur.session_id = ${SESSION}
663
- and (cur.head is null or cur.head <= ${clearIndex})
664
- for update of cur skip locked
665
- ), retired as (
666
- delete from a2_cursors old using idle where old.ctid = idle.ctid
667
- )`;
668
- const toDate = (ms) => ms === null || ms === void 0 ? null : new Date(asNumber(ms));
669
- const toEvent = (row) => ({
670
- id: row["event_id"],
671
- type: row["event_type"],
672
- payload: row["payload"],
673
- index: asNumber(row["idx"]),
674
- sessionId: row["session_id"],
675
- createdAt: new Date(asNumber(row["created_at"]))
676
- });
677
- const toStored = (row) => ({
678
- ...toEvent(row),
679
- cause: decodeCause(row["cause"])
680
- });
681
- const toDispatch = (row) => ({
682
- consumer: row["consumer"],
683
- lane: row["lane"] ?? null,
684
- firstClaimedAt: toDate(row["first_claimed_at"]),
685
- lastClaimedAt: toDate(row["last_claimed_at"]),
686
- attemptCount: asNumber(row["attempt_count"]),
687
- claimHolder: row["claim_holder"] ?? null,
688
- claimExpiresAt: toDate(row["claim_expires_at"]),
689
- failureCount: asNumber(row["failure_count"]),
690
- lastFailedAt: toDate(row["last_failed_at"]),
691
- lastFailedAttempt: asNullableNumber(row["last_failed_attempt"]),
692
- lastError: row["last_error"] ?? null,
693
- failedAt: toDate(row["failed_at"])
694
- });
695
- const freshDispatch = (consumer, lane) => ({
696
- consumer,
697
- lane,
698
- firstClaimedAt: null,
699
- lastClaimedAt: null,
700
- attemptCount: 0,
701
- claimHolder: null,
702
- claimExpiresAt: null,
703
- failureCount: 0,
704
- lastFailedAt: null,
705
- lastFailedAttempt: null,
706
- lastError: null,
707
- failedAt: null
708
- });
709
- /** A cursor row joined with its head event's `e_` columns. */
710
- const toHead = (row) => ({
711
- ...toStored({
712
- session_id: row["session_id"],
713
- idx: row["e_idx"],
714
- event_type: row["e_event_type"],
715
- payload: row["e_payload"],
716
- event_id: row["e_event_id"],
717
- created_at: row["e_created_at"],
718
- cause: row["e_cause"]
719
- }),
720
- ...toDispatch(row)
721
- });
722
- /** A cursor run as `cursors()` reports it, given the session's clear marker. */
723
- const toCursor = (row, clearIndex) => {
724
- const position = asNumber(row["position"]);
725
- if (row["kind"] !== "log" || asNumber(row["epoch"]) > clearIndex) return Object.assign(toDispatch(row), {
726
- position,
727
- head: asNullableNumber(row["head"])
728
- });
729
- return Object.assign(freshDispatch(row["consumer"], row["lane"]), {
730
- position: Math.max(position, clearIndex),
731
- head: null
732
- });
733
- };
734
- const compareText = (a, b) => a < b ? -1 : a > b ? 1 : 0;
735
- const byHead = (a, b) => a.index - b.index || compareText(a.consumer, b.consumer);
736
- /** Consumer, then lane, with concurrent cursors last by head. */
737
- const byCursor = (a, b) => compareText(a.consumer, b.consumer) || (a.lane === null ? b.lane === null ? (a.head ?? 0) - (b.head ?? 0) : 1 : b.lane === null ? -1 : compareText(a.lane, b.lane));
738
- const servedNames = (consumers) => consumers === void 0 ? null : consumers.map((consumer) => consumer.name);
739
- const wrap = async (fn) => {
740
- try {
741
- return await fn();
742
- } catch (err) {
743
- if (err instanceof A2Error || err instanceof TypeError) throw err;
744
- throw new A2Error("STORE_UNAVAILABLE", "postgres store operation failed", { cause: err });
745
- }
746
- };
747
- const jsonb = (value) => JSON.stringify(value) ?? "null";
748
- const loadPg = async () => import("pg").catch(() => {
749
- throw new A2Error("STORE_NOT_CONFIGURED", "Postgres connections created by A2 require the optional 'pg' package");
750
- });
751
- const createListener = ({ pg, connectionString }) => postgresNotifications(async () => {
752
- const listener = new pg.default.Client({
753
- connectionString,
754
- application_name: "a2-listener",
755
- connectionTimeoutMillis: 1e4
756
- });
757
- return {
758
- connect: () => listener.connect(),
759
- query: (text) => listener.query(text),
760
- end: () => listener.end(),
761
- onNotification: (callback) => {
762
- listener.on("notification", callback);
763
- },
764
- onError: (callback) => {
765
- listener.on("error", callback);
766
- },
767
- onEnd: (callback) => {
768
- listener.on("end", callback);
769
- }
770
- };
771
- });
772
- /** A finished or dead head's snapshot pins, and history no pin keeps. */
773
- const releasePins = async ({ query, sessionId, consumer, cursorKey, index }) => {
774
- await query(`delete from a2_snapshot_pins
775
- where session_id = $1 and event_index = $2
776
- and consumer = $3 and cursor_key = $4`, [
777
- sessionId,
778
- index,
779
- consumer,
780
- cursorKey
781
- ]);
782
- await query(`delete from a2_snapshot_history history
783
- where history.session_id = $1
784
- and not exists (
785
- select 1 from a2_snapshot_pins pin
786
- where pin.session_id = history.session_id
787
- and pin.reducer_name = history.reducer_name
788
- and pin.up_to_index = history.up_to_index
789
- )`, [sessionId]);
790
- };
791
- const lockSession = (query, sessionId) => query("select pg_advisory_xact_lock(hashtext($1))", [sessionId]);
792
- /** Whether the session has an event at `index`. */
793
- const hasEvent = async (query, sessionId, index) => (await query("select 1 from a2_events where session_id = $1 and idx = $2", [sessionId, index])).rows.length > 0;
794
- /**
795
- * The attempt-currency fence shared by consumer appends and clears, under
796
- * the session lock. The cursor is read locked (`for share` by an append,
797
- * `for update` by a clear, which then releases the head): it serializes
798
- * with every writer of the cursor (claims, completions, failures), so a
799
- * stale read cannot pass the fence against a takeover committing beside
800
- * it. The lock is only taken while the head and attempt still match.
801
- */
802
- const assertCurrentCause = async ({ query, sessionId, cause, clearIndex, lock }) => {
803
- if (cause.index <= clearIndex) throw supersededAttemptError(sessionId, cause);
804
- const { rows } = await query(`select 1 from a2_cursors
805
- where session_id = $1 and cursor_key = $2 and consumer = $3
806
- and head = $4 and attempt_count = $5 and failed_at is null
807
- for ${lock}`, [
808
- sessionId,
809
- cursorKeyOf(cause.lane, cause.index),
810
- cause.consumer,
811
- cause.index,
812
- cause.attempt
813
- ]);
814
- if (rows.length === 0) throw supersededAttemptError(sessionId, cause);
815
- };
816
- const BATCH = "select r from a2_batch($1::text[], $2::jsonb) as r";
817
- /**
818
- * Each statement as a batch sends it, whitespace collapsed: a batch sends all
819
- * its statements on every call. They hold no comments or spaced literals, and
820
- * they're this module's constants, so the cache stays this size.
821
- */
822
- const compacted = /* @__PURE__ */ new Map();
823
- const compact = (statement) => {
824
- let sent = compacted.get(statement);
825
- if (sent === void 0) {
826
- if (statement.includes("--")) throw new TypeError("a batch statement holds a comment");
827
- sent = statement.replace(/\s+/g, " ").trim();
828
- compacted.set(statement, sent);
829
- }
830
- return sent;
831
- };
832
- /** The SQLSTATE `a2_batch` raises an `abort` row with, as its detail. */
833
- const BATCH_ABORTED = "A2001";
834
- /** The row an aborted `a2_batch` call raised, from `error` or its cause chain. */
835
- const abortedBatch = (error) => {
836
- for (let current = error, depth = 0; depth < 5; depth += 1) {
837
- if (typeof current !== "object" || current === null) return void 0;
838
- const { code, detail, cause } = current;
839
- if (code === BATCH_ABORTED && typeof detail === "string") return JSON.parse(detail);
840
- current = cause;
841
- }
842
- };
843
- const LOCK_SESSION = `
844
- select jsonb_build_object('locked', true)
845
- from pg_advisory_xact_lock(hashtext(${SESSION}))`;
846
- const INDEX = param.bigint("index");
847
- const CONSUMER = param.text("consumer");
848
- /**
849
- * The index before the events this call inserted, the last `count` of the
850
- * session's: read under the session lock, after the insert.
851
- */
852
- const INSERTED_AFTER = `(
853
- select coalesce(max(idx), 0) - ${param.bigint("count")}
854
- from a2_events where session_id = ${SESSION})`;
855
- /**
856
- * An append's checks, under the session lock: the session's head and pending
857
- * state, and what its supplied `ids` say. Ids are unique per session. When
858
- * every event's id belongs to this session already, the batch is a retry: it
859
- * stops with the committed rows. Some owned aborts, as does scheduled work
860
- * from at or below the clear marker (`origin`). Rows below the marker own no
861
- * id. Both id outcomes carry the head, which a conditional append's conflict
862
- * reports when it moved.
863
- */
864
- const APPEND_CHECKS = `
865
- with boundary as materialized (
866
- select coalesce(max(idx), 0) as base,
867
- ${clearIndexOf(SESSION)} as clear_index,
868
- ${pendingIn(SESSION, param.texts("served"))} as has_pending
869
- from a2_events where session_id = ${SESSION}
870
- ), owned as materialized (
871
- select event.session_id, event.idx, event.event_type, event.payload,
872
- event.event_id, event.created_at, event.cause
873
- from a2_events event, boundary
874
- where event.session_id = ${SESSION}
875
- and event.event_id = any(${param.texts("ids")})
876
- and event.idx >= boundary.clear_index
877
- )
878
- select case
879
- when (select count(*) from owned) = ${param.bigint("count")} then
880
- jsonb_build_object('stop', 'replay', 'head', boundary.base,
881
- 'has_pending', boundary.has_pending,
882
- 'events', (select jsonb_agg(to_jsonb(owned) order by owned.idx)
883
- from owned))
884
- when exists (select 1 from owned) then
885
- jsonb_build_object('abort', 'mixed', 'head', boundary.base, 'owned',
886
- (select count(*) from owned))
887
- when ${param.bigint("origin")} <= boundary.clear_index then
888
- jsonb_build_object('abort', 'cleared')
889
- else jsonb_build_object('base', boundary.base,
890
- 'has_pending', boundary.has_pending)
891
- end
892
- from boundary`;
893
- /**
894
- * The attempt-currency fence of a consumer append, under the session lock.
895
- * Each cause's cursor is read `for share`: that serializes with every writer
896
- * of the cursor (claims, completions, failures), so a stale read cannot pass
897
- * the fence against a takeover committing beside it. A row is locked only
898
- * while its head and attempt still match. The first cause that fails aborts.
899
- */
900
- const FENCE = `
901
- with cause as (
902
- select * from jsonb_to_recordset($1->'causes')
903
- as cause(ord int, consumer text, cursor_key text, idx bigint, attempt int)
904
- ), held as materialized (
905
- select cause.ord from cause
906
- join a2_cursors cur
907
- on cur.session_id = ${SESSION} and cur.cursor_key = cause.cursor_key
908
- and cur.consumer = cause.consumer and cur.head = cause.idx
909
- and cur.attempt_count = cause.attempt and cur.failed_at is null
910
- where cause.idx > ${clearIndexOf(SESSION)}
911
- for share of cur
912
- )
913
- select jsonb_build_object('abort', 'superseded', 'ord', cause.ord)
914
- from cause where cause.ord not in (select ord from held)
915
- order by cause.ord limit 1`;
916
- /**
917
- * A conditional append's head check, under the session lock and after the
918
- * fences: it aborts with the head unless the head is `ifLastIndex`.
919
- */
920
- const IF_LAST_INDEX = `
921
- select jsonb_build_object('abort', 'moved', 'index', head.idx)
922
- from (select coalesce(max(idx), 0) as idx from a2_events
923
- where session_id = ${SESSION}) head
924
- where head.idx <> ${param.bigint("ifLastIndex")}`;
925
- /**
926
- * Frees the `ids` this session's rows below its clear marker hold, so the
927
- * batch can take them. It never waits on a row: a reclaim deleting one may
928
- * hold it, and one it skips aborts.
929
- */
930
- const REUSE_IDS = `
931
- with stale as materialized (
932
- select event.idx from a2_events event
933
- where event.session_id = ${SESSION}
934
- and event.event_id = any(${param.texts("ids")})
935
- and event.idx < ${clearIndexOf(SESSION)}
936
- order by event.idx
937
- for update skip locked
938
- ), deleted as (
939
- delete from a2_events event using stale
940
- where event.session_id = ${SESSION} and event.idx = stale.idx
941
- returning event.idx
942
- )
943
- select jsonb_build_object('abort', 'held')
944
- where (select count(*) from deleted) < (
945
- select count(*) from a2_events event
946
- where event.session_id = ${SESSION}
947
- and event.event_id = any(${param.texts("ids")})
948
- and event.idx < ${clearIndexOf(SESSION)})`;
949
- /** Inserts `events` after the session's head, under the session lock. */
950
- const INSERT_EVENTS = `
951
- with inserted as (
952
- insert into a2_events
953
- (session_id, idx, event_type, payload, event_id, created_at, cause)
954
- select ${SESSION}, base.base + event.ord, event.type,
955
- coalesce(event.payload, 'null'::jsonb), event.id,
956
- ${param.bigint("now")}, event.cause
957
- from (select coalesce(max(idx), 0) as base from a2_events
958
- where session_id = ${SESSION}) base,
959
- jsonb_to_recordset($1->'events')
960
- as event(ord bigint, type text, payload jsonb, id text, cause jsonb)
961
- returning 1
962
- )
963
- select jsonb_build_object('inserted', count(*)) from inserted`;
964
- /** A cursor for each concurrent target: the event alone. */
965
- const START_EVENTS = `
966
- with started as (
967
- insert into a2_cursors
968
- (session_id, consumer, cursor_key, epoch, lane, kind, position, head)
969
- select ${SESSION}, target.consumer, '#' || target.idx, target.idx, null,
970
- 'event', target.idx - 1, target.idx
971
- from (
972
- select single.consumer, ${INSERTED_AFTER} + single.ord as idx
973
- from jsonb_to_recordset($1->'singles')
974
- as single(consumer text, ord bigint)
975
- ) target
976
- on conflict do nothing
977
- returning 1
978
- )
979
- select jsonb_build_object('started', count(*)) from started`;
980
- /** Queues each lane target's event in its lane. */
981
- const QUEUE_LANES = `
982
- with queued as (
983
- insert into a2_lane_events (session_id, consumer, lane, idx)
984
- select ${SESSION}, queued.consumer, queued.lane,
985
- ${INSERTED_AFTER} + queued.ord
986
- from jsonb_to_recordset($1->'queued')
987
- as queued(consumer text, lane text, ord bigint)
988
- on conflict do nothing
989
- returning 1
990
- )
991
- select jsonb_build_object('queued', count(*)) from queued`;
992
- /**
993
- * Starts a run for each lane cursor the batch queues work for that has none
994
- * running: one that is idle, superseded by the clear marker, or new. It starts
995
- * at the lane's first event in the batch and counts from the marker.
996
- */
997
- const START_LANES = `
998
- with boundary as materialized (
999
- select ${INSERTED_AFTER} as base, ${clearIndexOf(SESSION)} as clear_index
1000
- ), target as (
1001
- select first.consumer, first.cursor_key, first.lane,
1002
- boundary.base + first.ord as idx
1003
- from boundary, jsonb_to_recordset($1->'lanes')
1004
- as first(consumer text, cursor_key text, lane text, ord bigint)
1005
- ), started as materialized (
1006
- select target.*, latest.position
1007
- from target
1008
- left join lateral (${LATEST_RUN("target")}) latest on true
1009
- where latest.head is null
1010
- or latest.head <= (select clear_index from boundary)
1011
- ), ${RETIRE_RUNS("started", "(select clear_index from boundary)")},
1012
- inserted as (
1013
- insert into a2_cursors
1014
- (session_id, consumer, cursor_key, epoch, lane, kind, position, head)
1015
- select ${SESSION}, started.consumer, started.cursor_key, started.idx,
1016
- started.lane, 'lane',
1017
- greatest(coalesce(started.position, 0),
1018
- (select clear_index from boundary)),
1019
- started.idx
1020
- from started
1021
- on conflict do nothing
1022
- returning 1
1023
- )
1024
- select jsonb_build_object('lanes', count(*)) from inserted`;
1025
- /**
1026
- * Starts a run for each served log cursor the batch carries types for that
1027
- * has none running. A missing cursor starts at the batch's first event of its
1028
- * types, or at the beginning of the log with backfill. One that exists starts
1029
- * at the next event it takes after its position: a deployment that does not
1030
- * serve the consumer may have appended some while it was idle. A cursor from
1031
- * before the clear marker counts from it.
1032
- */
1033
- const WAKE_LOGS = `
1034
- with boundary as materialized (
1035
- select ${INSERTED_AFTER} as base, ${clearIndexOf(SESSION)} as clear_index
1036
- ), target as (
1037
- select log.consumer, log.cursor_key, log.lane,
1038
- boundary.base + log.ord as first, log.types, log.backfill
1039
- from boundary, jsonb_to_recordset($1->'logs')
1040
- as log(consumer text, cursor_key text, lane text, ord bigint,
1041
- types jsonb, backfill boolean)
1042
- ), woken as materialized (
1043
- select target.*,
1044
- case when latest.epoch is not null
1045
- then greatest(latest.position,
1046
- (select clear_index from boundary))
1047
- when target.backfill then (select clear_index from boundary)
1048
- else (select base from boundary) end as position,
1049
- latest.epoch is not null or target.backfill as resumes
1050
- from target
1051
- left join lateral (${LATEST_RUN("target")}) latest on true
1052
- where latest.head is null
1053
- or latest.head <= (select clear_index from boundary)
1054
- ), ${RETIRE_RUNS("woken", "(select clear_index from boundary)")}, run as (
1055
- select woken.*,
1056
- case when woken.resumes then coalesce(${nextLogHead({
1057
- types: "woken.types",
1058
- after: "woken.position"
1059
- })}, woken.first) else woken.first end as head
1060
- from woken
1061
- ), inserted as (
1062
- insert into a2_cursors
1063
- (session_id, consumer, cursor_key, epoch, lane, kind, position, head,
1064
- types)
1065
- select ${SESSION}, run.consumer, run.cursor_key, run.head, run.lane, 'log',
1066
- run.position, run.head, run.types
1067
- from run
1068
- on conflict do nothing
1069
- returning 1
1070
- )
1071
- select jsonb_build_object('logs', count(*)) from inserted`;
1072
- /**
1073
- * The heads a claim may take, up to `through` when there is one, as
1074
- * `from ... where` for `cur`. `for update` makes a claim racing another wait
1075
- * and then re-check the row it waited for.
1076
- */
1077
- const ELIGIBLE = `
1078
- from a2_cursors cur
1079
- where cur.session_id = ${SESSION}
1080
- and cur.head > ${clearIndexOf(SESSION)}
1081
- and (${param.bigint("through")} is null
1082
- or cur.head <= ${param.bigint("through")})
1083
- and cur.failed_at is null
1084
- and (${param.texts("served")} is null
1085
- or cur.consumer = any(${param.texts("served")}))
1086
- and not exists (
1087
- select 1 from jsonb_to_recordset($1->'excluded')
1088
- as skip(consumer text, cursor_key text)
1089
- where skip.consumer = cur.consumer and skip.cursor_key = cur.cursor_key
1090
- )`;
1091
- /** A lapsed claim's takeover that spends the last failed attempt dead-letters the head instead. */
1092
- const EXHAUSTED = `(cur.claim_holder is not null
1093
- and cur.failure_count + 1 >= ${param.int("maxFailures")})`;
1094
- /**
1095
- * Claims every eligible head, returning each with its event. A head the claim
1096
- * waited on may have moved to an event its snapshot predates: that row comes
1097
- * back without one (`e_idx` null), for `claimAvailable` to read. It stops
1098
- * there unless one dead-lettered, whose pins `RELEASE_DEAD` then releases, or
1099
- * none was claimed, for `RETRY_AT`.
1100
- */
1101
- const CLAIM = `
1102
- with eligible as materialized (
1103
- select cur.consumer, cur.cursor_key, cur.epoch
1104
- ${ELIGIBLE}
1105
- and (cur.claim_expires_at is null
1106
- or cur.claim_expires_at <= ${param.bigint("now")})
1107
- order by cur.head, cur.consumer
1108
- for update of cur
1109
- ), claimed as (
1110
- update a2_cursors cur set
1111
- attempt_count = cur.attempt_count + 1,
1112
- failure_count = cur.failure_count
1113
- + case when cur.claim_holder is null then 0 else 1 end,
1114
- failed_at = case when ${EXHAUSTED} then ${param.bigint("now")}
1115
- else cur.failed_at end,
1116
- first_claimed_at = case when ${EXHAUSTED} then cur.first_claimed_at
1117
- else coalesce(cur.first_claimed_at, ${param.bigint("now")}) end,
1118
- last_claimed_at = case when ${EXHAUSTED} then cur.last_claimed_at
1119
- else ${param.bigint("now")} end,
1120
- claim_holder = case when ${EXHAUSTED} then null
1121
- else ${param.text("holder")} end,
1122
- claim_expires_at = case when ${EXHAUSTED} then null
1123
- else ${param.bigint("expiresAt")} end
1124
- from eligible
1125
- where cur.session_id = ${SESSION}
1126
- and cur.cursor_key = eligible.cursor_key
1127
- and cur.consumer = eligible.consumer
1128
- and cur.epoch = eligible.epoch
1129
- returning cur.*
1130
- ), heads as (
1131
- select claimed.*, ${HEAD_COLUMNS},
1132
- ${clearIndexOf(SESSION)} as clear_index,
1133
- (select coalesce(max(idx), 0) from a2_events
1134
- where session_id = ${SESSION}) as session_head
1135
- from claimed
1136
- left join a2_events event
1137
- on event.session_id = ${SESSION} and event.idx = claimed.head
1138
- )
1139
- select r from (
1140
- select 0 as ord, to_jsonb(heads) as r from heads
1141
- union all
1142
- select 1, jsonb_build_object('stop', 'claimed')
1143
- where exists (select 1 from heads)
1144
- and not exists (select 1 from heads where failed_at is not null)
1145
- ) claim
1146
- order by ord`;
1147
- /**
1148
- * Releases the pins of the heads dead-lettered at `now`, the claim's among
1149
- * them, in a snapshot after the claim's locks, with the history no other pin
1150
- * keeps.
1151
- */
1152
- const RELEASE_DEAD = `
1153
- with dead as materialized (
1154
- select cur.consumer, cur.cursor_key, cur.head from a2_cursors cur
1155
- where cur.session_id = ${SESSION} and cur.head is not null
1156
- and cur.failed_at = ${param.bigint("now")} and cur.claim_holder is null
1157
- ), unpinned as (
1158
- delete from a2_snapshot_pins pin using dead
1159
- where pin.session_id = ${SESSION} and pin.event_index = dead.head
1160
- and pin.consumer = dead.consumer and pin.cursor_key = dead.cursor_key
1161
- returning 1
1162
- ), unkept as (
1163
- delete from a2_snapshot_history history
1164
- where history.session_id = ${SESSION}
1165
- and exists (select 1 from dead)
1166
- and not exists (
1167
- select 1 from a2_snapshot_pins pin
1168
- where pin.session_id = history.session_id
1169
- and pin.reducer_name = history.reducer_name
1170
- and pin.up_to_index = history.up_to_index
1171
- and not exists (
1172
- select 1 from dead
1173
- where pin.event_index = dead.head
1174
- and pin.consumer = dead.consumer
1175
- and pin.cursor_key = dead.cursor_key)
1176
- )
1177
- returning 1
1178
- )
1179
- select jsonb_build_object('released', (select count(*) from unpinned))`;
1180
- /** When nothing was claimed: the earliest live claim or retry hold that blocks a head. */
1181
- const RETRY_AT = `
1182
- select jsonb_build_object('retry_at', min(cur.claim_expires_at))
1183
- ${ELIGIBLE}
1184
- and cur.claim_expires_at > ${param.bigint("now")}`;
1185
- /** The cursor row `alias` whose head this attempt holds. */
1186
- const heldBy = (alias) => `
1187
- ${alias}.session_id = ${SESSION}
1188
- and ${alias}.cursor_key = ${param.text("cursorKey")}
1189
- and ${alias}.consumer = ${CONSUMER} and ${alias}.head = ${INDEX}
1190
- and ${alias}.attempt_count = ${param.int("attempt")}
1191
- and ${alias}.failed_at is null and ${alias}.claim_holder is not null`;
1192
- /**
1193
- * Locks the cursor while this attempt holds its head, and stops unless it
1194
- * does: a completion locks its cursor first. A cleared head is never locked.
1195
- */
1196
- const HOLD = `
1197
- with boundary as materialized (
1198
- select ${clearIndexOf(SESSION)} as clear_index
1199
- ), held as materialized (
1200
- select cur.kind from a2_cursors cur, boundary
1201
- where ${heldBy("cur")} and ${INDEX} > boundary.clear_index
1202
- for update of cur
1203
- )
1204
- select case
1205
- when ${INDEX} <= boundary.clear_index then
1206
- jsonb_build_object('stop', 'superseded')
1207
- when not exists (select 1 from held) then
1208
- jsonb_build_object('stop', 'unheld')
1209
- else jsonb_build_object('held', (select kind from held limit 1))
1210
- end
1211
- from boundary`;
1212
- /** A log cursor's types once it moves: the served consumer's (`types`, when `retype`), else its own. */
1213
- const logTypesOf = (cur) => `(case when ${param.boolean("retype")} then ${param.jsonb("types")}
1214
- else ${cur}.types end)`;
1215
- /**
1216
- * The head cursor `cur` moves to from its head: its lane's next unfinished
1217
- * event, the next event of a log cursor's types, or none for a concurrent
1218
- * cursor. The lane's lookup is ordered by its whole key, so the lane's
1219
- * primary key serves it.
1220
- */
1221
- const nextHeadOf = (cur) => `
1222
- case ${cur}.kind
1223
- when 'lane' then (
1224
- select lane.idx from a2_lane_events lane
1225
- where lane.session_id = ${SESSION} and lane.consumer = ${cur}.consumer
1226
- and lane.lane = ${cur}.lane and not lane.done
1227
- and lane.idx > ${cur}.head
1228
- order by lane.consumer, lane.lane, lane.idx limit 1)
1229
- when 'log' then (${nextLogHead({
1230
- types: logTypesOf(cur),
1231
- after: `${cur}.head`
1232
- })})
1233
- end`;
1234
- /**
1235
- * Takes the session lock when the held cursor would go idle: a lane or log
1236
- * cursor with no next head. See `completeAttempt` for why a completion that
1237
- * moves to a next head needs no lock.
1238
- */
1239
- const LOCK_IF_IDLE = `
1240
- select jsonb_build_object('locked',
1241
- pg_advisory_xact_lock(hashtext(${SESSION}))::text is not null)
1242
- from a2_cursors cur
1243
- where ${heldBy("cur")} and cur.kind <> 'event'
1244
- and (${nextHeadOf("cur")}) is null`;
1245
- /**
1246
- * Moves the cursor `target` selects past its head `index`, if its head lies
1247
- * above the clear marker: marks the lane's event done (with this attempt's
1248
- * receipt, `receipt`), releases the head's snapshot pins with the history no
1249
- * other pin keeps, and gives the cursor its next head with fresh dispatch
1250
- * columns (a log or concurrent cursor keeps the receipt on the run). The
1251
- * marker and the next head are read in one snapshot, after the cursor's lock.
1252
- * Without a row it writes nothing, and stops if `stop`.
1253
- */
1254
- const advance = ({ target, receipt, missing }) => `
1255
- with target as materialized (
1256
- select cur.* from a2_cursors cur
1257
- where ${target} and ${INDEX} > ${clearIndexOf(SESSION)}
1258
- order by cur.cursor_key limit 1
1259
- for update of cur
1260
- ), done as (
1261
- update a2_lane_events lane set done = true${receipt ? `, completed_attempt = ${param.int("attempt")},
1262
- returned_event_ids = ${param.jsonb("ids")}` : ""}
1263
- from target
1264
- where target.kind = 'lane' and lane.session_id = ${SESSION}
1265
- and lane.consumer = target.consumer and lane.lane = target.lane
1266
- and lane.idx = target.head
1267
- returning 1
1268
- ), unpinned as (
1269
- delete from a2_snapshot_pins pin using target
1270
- where pin.session_id = ${SESSION} and pin.event_index = target.head
1271
- and pin.consumer = target.consumer and pin.cursor_key = target.cursor_key
1272
- returning 1
1273
- ), unkept as (
1274
- delete from a2_snapshot_history history using target
1275
- where history.session_id = ${SESSION}
1276
- and not exists (
1277
- select 1 from a2_snapshot_pins pin
1278
- where pin.session_id = history.session_id
1279
- and pin.reducer_name = history.reducer_name
1280
- and pin.up_to_index = history.up_to_index
1281
- and not (pin.event_index = target.head
1282
- and pin.consumer = target.consumer
1283
- and pin.cursor_key = target.cursor_key)
1284
- )
1285
- returning 1
1286
- ), moved as (
1287
- update a2_cursors cur
1288
- set position = target.head, head = ${nextHeadOf("target")},
1289
- ${FRESH_DISPATCH},
1290
- types = case when target.kind = 'log'
1291
- then ${logTypesOf("target")} else cur.types end${receipt ? `,
1292
- completed_idx = case when target.kind = 'lane'
1293
- then cur.completed_idx else target.head end,
1294
- completed_attempt = case when target.kind = 'lane'
1295
- then cur.completed_attempt
1296
- else ${param.int("attempt")} end,
1297
- returned_event_ids = case when target.kind = 'lane'
1298
- then cur.returned_event_ids
1299
- else ${param.jsonb("ids")} end` : ""}
1300
- from target
1301
- where cur.session_id = ${SESSION} and cur.cursor_key = target.cursor_key
1302
- and cur.consumer = target.consumer and cur.epoch = target.epoch
1303
- returning cur.head
1304
- )
1305
- select case when exists (select 1 from moved)
1306
- then jsonb_build_object('advanced', true)
1307
- else jsonb_build_object(${missing === "continue" ? `'advanced', false` : `'${missing}', 'superseded'`}) end`;
1308
- /** Completing a held head, once the cursor's lock is taken. */
1309
- const COMPLETE = advance({
1310
- target: heldBy("cur"),
1311
- receipt: true,
1312
- missing: "stop"
1313
- });
1314
- /**
1315
- * Completing a held head after appending its events, under the session lock:
1316
- * the head can't have moved, but if it had, the events must not stand.
1317
- */
1318
- const COMPLETE_APPENDED = advance({
1319
- target: heldBy("cur"),
1320
- receipt: true,
1321
- missing: "abort"
1322
- });
1323
- /**
1324
- * A completion's checks before it appends, under the session lock, which the
1325
- * cursor's lock preceded: a head the clear marker passed meanwhile stops, and
1326
- * a returned id a live row owns aborts.
1327
- */
1328
- const RETURN_CHECKS = `
1329
- select case
1330
- when ${INDEX} <= ${clearIndexOf(SESSION)} then
1331
- jsonb_build_object('stop', 'superseded')
1332
- when exists (
1333
- select 1 from a2_events event
1334
- where event.session_id = ${SESSION}
1335
- and event.event_id = any(${param.texts("ids")})
1336
- and event.idx >= ${clearIndexOf(SESSION)}
1337
- ) then jsonb_build_object('abort', 'owned')
1338
- else jsonb_build_object('base', (
1339
- select coalesce(max(idx), 0) from a2_events
1340
- where session_id = ${SESSION}))
1341
- end`;
1342
- /** The consumer's dead-lettered head at `index`, locked. */
1343
- const deadAt = (alias) => `
1344
- ${alias}.session_id = ${SESSION} and ${alias}.consumer = ${CONSUMER}
1345
- and ${alias}.head = ${INDEX} and ${alias}.failed_at is not null`;
1346
- /**
1347
- * Locks the dead letter, or stops: the statements after it act only on the
1348
- * row this one locked.
1349
- */
1350
- const LOCK_DEAD = `
1351
- with dead as materialized (
1352
- select cur.cursor_key from a2_cursors cur
1353
- where ${deadAt("cur")} and ${INDEX} > ${clearIndexOf(SESSION)}
1354
- order by cur.cursor_key limit 1
1355
- for update
1356
- )
1357
- select case when exists (select 1 from dead)
1358
- then jsonb_build_object('redriven', true)
1359
- else jsonb_build_object('stop', 'alive', 'redriven', false,
1360
- 'has_pending',
1361
- ${pendingIn(SESSION, param.texts("served"))}) end`;
1362
- /** Clears a dead letter, keeping its claim history and last failure. */
1363
- const RETRY_DEAD = `
1364
- with target as materialized (
1365
- select cur.cursor_key, cur.epoch from a2_cursors cur
1366
- where ${deadAt("cur")} and ${INDEX} > ${clearIndexOf(SESSION)}
1367
- order by cur.cursor_key limit 1
1368
- for update of cur
1369
- ), retried as (
1370
- update a2_cursors cur set failed_at = null, failure_count = 0
1371
- from target
1372
- where cur.session_id = ${SESSION} and cur.cursor_key = target.cursor_key
1373
- and cur.consumer = ${CONSUMER} and cur.epoch = target.epoch
1374
- returning 1
1375
- )
1376
- select jsonb_build_object('retried', count(*)) from retried`;
1377
- const SKIP_DEAD = advance({
1378
- target: deadAt("cur"),
1379
- receipt: false,
1380
- missing: "continue"
1381
- });
1382
- const PENDING = `
1383
- select jsonb_build_object('has_pending',
1384
- ${pendingIn(SESSION, param.texts("served"))})`;
1385
- /**
1386
- * One log cursor as `wakeLog` finds it: the session's head and clear marker,
1387
- * the cursor's latest run, where a run would start (`start`), and the next
1388
- * event it takes from there unless the run has a head. `retyped` says whether
1389
- * the run's types are stale. CTEs, for a `with`.
1390
- */
1391
- const LOG_CURSOR = `
1392
- boundary as materialized (
1393
- select coalesce(max(idx), 0) as session_head,
1394
- ${clearIndexOf(SESSION)} as clear_index
1395
- from a2_events where session_id = ${SESSION}
1396
- ), latest as materialized (
1397
- select boundary.*, cur.*,
1398
- case when cur.epoch is not null
1399
- then greatest(cur.position, boundary.clear_index)
1400
- when ${param.boolean("backfill")} then boundary.clear_index
1401
- else boundary.session_head end as start
1402
- from boundary
1403
- left join lateral (
1404
- select * from a2_cursors cur
1405
- where cur.session_id = ${SESSION}
1406
- and cur.cursor_key = ${param.text("cursorKey")}
1407
- and cur.consumer = ${CONSUMER}
1408
- order by cur.epoch desc limit 1
1409
- ) cur on true
1410
- ), found as materialized (
1411
- select latest.*,
1412
- latest.types is distinct from ${param.jsonb("types")} as retyped,
1413
- case when latest.head > latest.clear_index then null
1414
- else ${nextLogHead({
1415
- types: param.jsonb("types"),
1416
- after: "latest.start"
1417
- })} end as next_head
1418
- from latest
1419
- )`;
1420
- /**
1421
- * A run with a head gets no next one: it is left as it is, claim and all,
1422
- * and so is an idle run with nothing new to take. Only their types change.
1423
- */
1424
- const KEEPS_RUN = "found.epoch is not null and found.next_head is null";
1425
- /** No run yet, and nothing after the latest clear: none is started. */
1426
- const NO_RUN_NEEDED = "found.epoch is null and found.session_head = found.clear_index";
1427
- /** `wakeLog` without the lock: stops when there is nothing to write. */
1428
- const READ_LOG = `
1429
- with ${LOG_CURSOR}
1430
- select case when ${KEEPS_RUN} and not found.retyped
1431
- then jsonb_build_object('stop', 'unchanged',
1432
- 'cursor', to_jsonb(found))
1433
- when ${NO_RUN_NEEDED}
1434
- then jsonb_build_object('stop', 'empty', 'empty', true,
1435
- 'head', found.session_head)
1436
- else jsonb_build_object('stale', true) end
1437
- from found`;
1438
- /**
1439
- * `wakeLog` under the session lock. A kept run takes the consumer's types,
1440
- * unless another operation holds its row: the session lock is held, so this
1441
- * waits for none. Otherwise a run starts at `start`, retiring the runs it
1442
- * replaces. One with a head is keyed by it; one with nothing to run is idle
1443
- * at its position, as a run that finished its last head is, keyed by that
1444
- * position so the next run, which starts after it, sorts later.
1445
- */
1446
- const WAKE_LOG = `
1447
- with ${LOG_CURSOR}, held as materialized (
1448
- select cur.ctid from a2_cursors cur, found
1449
- where ${KEEPS_RUN} and found.retyped
1450
- and cur.session_id = ${SESSION}
1451
- and cur.cursor_key = ${param.text("cursorKey")}
1452
- and cur.consumer = ${CONSUMER} and cur.epoch = found.epoch
1453
- and cur.types is distinct from ${param.jsonb("types")}
1454
- for update of cur skip locked
1455
- ), retype as (
1456
- update a2_cursors cur set types = ${param.jsonb("types")} from held
1457
- where cur.ctid = held.ctid
1458
- ), target as (
1459
- select ${param.text("cursorKey")} as cursor_key, ${CONSUMER} as consumer
1460
- from found where not (${KEEPS_RUN}) and not (${NO_RUN_NEEDED})
1461
- ), ${RETIRE_RUNS("target", "(select clear_index from found)")}, started as (
1462
- insert into a2_cursors
1463
- (session_id, consumer, cursor_key, epoch, lane, kind, position, head,
1464
- types)
1465
- select ${SESSION}, target.consumer, target.cursor_key,
1466
- coalesce(found.next_head, found.start), ${param.text("lane")}, 'log',
1467
- found.start, found.next_head, ${param.jsonb("types")}
1468
- from found, target
1469
- returning *
1470
- )
1471
- select jsonb_build_object(
1472
- 'cursor', coalesce((select to_jsonb(started) from started),
1473
- to_jsonb(found)),
1474
- 'head', found.session_head, 'clear_index', found.clear_index,
1475
- 'empty', ${NO_RUN_NEEDED})
1476
- from found`;
1477
- /**
1478
- * The statements that start the cursor work a batch of `events` carries,
1479
- * with their parameters: each event by its position in the batch, from 1,
1480
- * since its index is assigned under the lock. `started` says whether it
1481
- * starts work for a served consumer.
1482
- */
1483
- const enqueue = (events, consumers) => {
1484
- const served = consumers && new Set(consumers.map(({ name }) => name));
1485
- let started = false;
1486
- const singles = [];
1487
- const queued = [];
1488
- const lanes = /* @__PURE__ */ new Map();
1489
- events.forEach((event, offset) => {
1490
- const ord = offset + 1;
1491
- for (const target of event.targets ?? []) {
1492
- if (!served || served.has(target.consumer)) started = true;
1493
- if (target.lane === null) {
1494
- singles.push({
1495
- consumer: target.consumer,
1496
- ord
1497
- });
1498
- continue;
1499
- }
1500
- queued.push({
1501
- consumer: target.consumer,
1502
- lane: target.lane,
1503
- ord
1504
- });
1505
- const key = cursorKeyOf(target.lane, ord);
1506
- const first = `${target.consumer}\u0000${key}`;
1507
- if (!lanes.has(first)) lanes.set(first, {
1508
- consumer: target.consumer,
1509
- cursor_key: key,
1510
- lane: target.lane,
1511
- ord
1512
- });
1513
- }
1514
- });
1515
- const logs = [];
1516
- for (const consumer of consumers ?? []) {
1517
- const log = consumer.log;
1518
- if (!log) continue;
1519
- const offset = events.findIndex((event) => event.type !== "a2.cleared" && (log.types === null || log.types.includes(event.type)));
1520
- if (offset === -1) continue;
1521
- logs.push({
1522
- consumer: consumer.name,
1523
- cursor_key: cursorKeyOf(log.lane, 0),
1524
- lane: log.lane,
1525
- ord: offset + 1,
1526
- types: log.types,
1527
- backfill: log.backfill
1528
- });
1529
- }
1530
- if (logs.length > 0) started = true;
1531
- return {
1532
- statements: [
1533
- singles.length > 0 && START_EVENTS,
1534
- queued.length > 0 && QUEUE_LANES,
1535
- queued.length > 0 && START_LANES,
1536
- logs.length > 0 && WAKE_LOGS
1537
- ],
1538
- params: {
1539
- singles,
1540
- queued,
1541
- lanes: [...lanes.values()],
1542
- logs,
1543
- clearType: CLEAR_EVENT_TYPE
1544
- },
1545
- started
1546
- };
1547
- };
1548
- /**
1549
- * The rows a batch inserted at `base + 1`, as the store returns them.
1550
- * `events` are what the batch sent.
1551
- */
1552
- const insertedRows = ({ sessionId, events, base, now }) => events.map((event, offset) => ({
1553
- id: event.id,
1554
- type: event.type,
1555
- payload: structuredClone(event.payload),
1556
- index: base + 1 + offset,
1557
- sessionId,
1558
- createdAt: new Date(now),
1559
- cause: event.cause ? { ...event.cause } : null
1560
- }));
1561
- /** A served log consumer's types, for a cursor that moves past its head. */
1562
- const retypeOf = (consumer, consumers) => {
1563
- const log = consumers?.find(({ name }) => name === consumer)?.log;
1564
- return log ? {
1565
- retype: true,
1566
- types: log.types
1567
- } : {
1568
- retype: false,
1569
- types: null
1570
- };
1571
- };
1572
- function postgres$1(options = {}) {
1573
- const clock = options.clock ?? SYSTEM_CLOCK;
1574
- const generateId = options.ids ?? RANDOM_IDS;
1575
- const instanceId = crypto.randomUUID();
1576
- let closed = false;
1577
- if (options.listenConnectionString === "") throw new TypeError("listenConnectionString must be a direct Postgres connection string");
1578
- if (!options.client && !options.connectionString) throw new TypeError("postgres() needs a connectionString or an injected client");
1579
- const injected = options.client ? sharePostgresClient(options.client) : void 0;
1580
- const connection = retryableLazy(async () => {
1581
- let lease = injected;
1582
- if (!lease) {
1583
- const pg = await loadPg();
1584
- const connectionString = options.connectionString;
1585
- const key = postgresConnectionKey({
1586
- connectionString,
1587
- defaults: pg.default.defaults
1588
- });
1589
- lease = sharePostgresPool({
1590
- key,
1591
- create: () => {
1592
- const pool = new pg.default.Pool({ connectionString });
1593
- pool.on("error", () => {});
1594
- return postgresPoolClient(pool);
1595
- }
1596
- });
1597
- }
1598
- return {
1599
- lease,
1600
- client: explainingPostgresClient(lease.value.client)
1601
- };
1602
- });
1603
- const client = async () => {
1604
- if (closed) throw new A2Error("STORE_UNAVAILABLE", "the store was closed");
1605
- const { client: explaining } = await connection.get();
1606
- if (closed) throw new A2Error("STORE_UNAVAILABLE", "the store was closed");
1607
- return explaining;
1608
- };
1609
- const notifications = options.listenConnectionString ? postgresNotificationScope(async () => {
1610
- const c = await client();
1611
- await (await connection.get()).lease.value.initialize({
1612
- key: "triggers",
1613
- run: () => checkPostgresTriggers(c)
1614
- });
1615
- const pg = await loadPg();
1616
- const connectionString = options.listenConnectionString;
1617
- const key = postgresConnectionKey({
1618
- connectionString,
1619
- defaults: pg.default.defaults
1620
- });
1621
- return sharePostgresListener({
1622
- key,
1623
- create: () => createListener({
1624
- pg,
1625
- connectionString
1626
- })
1627
- });
1628
- }) : void 0;
1629
- const presenceSubscriptions = /* @__PURE__ */ new Map();
1630
- const readStateBatch = async (requests, reducerName) => {
1631
- if (requests.length === 0) return [];
1632
- const c = await client();
1633
- const input = requests.map((request, position) => ({
1634
- position,
1635
- sessionId: request.sessionId,
1636
- throughIndex: request.throughIndex ?? null,
1637
- snapshotThroughIndex: request.snapshotThroughIndex ?? request.throughIndex ?? null
1638
- }));
1639
- const { rows } = await c.query(`with request as materialized (
1640
- select * from jsonb_to_recordset($1::jsonb) as value(
1641
- position integer,
1642
- "sessionId" text,
1643
- "throughIndex" bigint,
1644
- "snapshotThroughIndex" bigint
1645
- )
1646
- ), bounded as materialized (
1647
- select request.*, coalesce(clears.clear_index, 0) as clear_index
1648
- from request
1649
- left join a2_clears clears on clears.session_id = request."sessionId"
1650
- ), selected as materialized (
1651
- select request.position,
1652
- request."sessionId" as session_id,
1653
- request."throughIndex" as through_index,
1654
- request.clear_index,
1655
- head.up_to_index as head_index,
1656
- candidate.up_to_index as snapshot_index,
1657
- candidate.state as snapshot_state
1658
- from bounded request
1659
- left join a2_snapshots head
1660
- on head.session_id = request."sessionId"
1661
- and head.reducer_name = $2
1662
- and head.up_to_index >= request.clear_index
1663
- left join lateral (
1664
- select up_to_index, state from (
1665
- select head.up_to_index, head.state
1666
- where request."snapshotThroughIndex" is null
1667
- or head.up_to_index <= request."snapshotThroughIndex"
1668
- union all
1669
- select history.up_to_index, history.state
1670
- from a2_snapshot_history history
1671
- where history.session_id = request."sessionId"
1672
- and history.reducer_name = $2
1673
- and history.up_to_index >= request.clear_index
1674
- and (
1675
- request."snapshotThroughIndex" is null
1676
- or history.up_to_index <= request."snapshotThroughIndex"
1677
- )
1678
- ) candidates
1679
- order by up_to_index desc
1680
- limit 1
1681
- ) candidate on true
1682
- )
1683
- select selected.position, 0 as row_order, selected.session_id,
1684
- selected.head_index, selected.snapshot_index,
1685
- selected.snapshot_state, selected.clear_index,
1686
- null::bigint as idx, null::text as event_type,
1687
- null::jsonb as payload, null::text as event_id,
1688
- null::bigint as created_at
1689
- from selected
1690
- union all
1691
- select selected.position, 1 as row_order, event.session_id,
1692
- selected.head_index, null::bigint as snapshot_index,
1693
- null::jsonb as snapshot_state, selected.clear_index,
1694
- event.idx, event.event_type, event.payload,
1695
- event.event_id, event.created_at
1696
- from selected
1697
- join a2_events event on event.session_id = selected.session_id
1698
- where event.idx > greatest(
1699
- coalesce(selected.snapshot_index, 0),
1700
- selected.clear_index - 1
1701
- )
1702
- and (
1703
- selected.through_index is null
1704
- or event.idx <= selected.through_index
1705
- )
1706
- order by position, row_order, idx`, [jsonb(input), reducerName]);
1707
- const reads = requests.map(() => ({
1708
- headIndex: null,
1709
- snapshot: null,
1710
- events: []
1711
- }));
1712
- for (const row of rows) {
1713
- const read = reads[asNumber(row["position"])];
1714
- if (row["row_order"] === 0 || row["row_order"] === "0") {
1715
- const clearIndex = asNumber(row["clear_index"]);
1716
- if (clearIndex > 0) read.clearIndex = clearIndex;
1717
- read.headIndex = row["head_index"] === null ? null : asNumber(row["head_index"]);
1718
- if (row["snapshot_index"] !== null) read.snapshot = {
1719
- index: asNumber(row["snapshot_index"]),
1720
- state: row["snapshot_state"]
1721
- };
1722
- } else read.events.push(toEvent(row));
1723
- }
1724
- return reads;
1725
- };
1726
- const begin = notifications ? `begin; set local a2.presence_source = '${instanceId}'` : "begin";
1727
- const withTx = async (fn) => {
1728
- const c = await client();
1729
- if (c.connect) {
1730
- const conn = await c.connect();
1731
- try {
1732
- await conn.query(begin);
1733
- const result = await fn((text, values) => conn.query(text, values));
1734
- await conn.query("commit");
1735
- return result;
1736
- } catch (err) {
1737
- await conn.query("rollback").catch(() => {});
1738
- throw err;
1739
- } finally {
1740
- conn.release();
1741
- }
1742
- }
1743
- const resource = (await connection.get()).lease.value;
1744
- return resource.exclusive(async () => {
1745
- const raw = resource.raw;
1746
- await raw.query(begin);
1747
- try {
1748
- const result = await fn((text, values) => raw.query(text, values).catch((error) => {
1749
- throw explainPostgresError(error);
1750
- }));
1751
- await raw.query("commit");
1752
- return result;
1753
- } catch (err) {
1754
- await raw.query("rollback").catch(() => {});
1755
- throw err;
1756
- }
1757
- });
1758
- };
1759
- /**
1760
- * Runs `statements` (the falsy ones dropped) as one `a2_batch` call with
1761
- * `params`, and the session's id as `session`. Its rows come back in order;
1762
- * an aborted call throws what `abort` makes of the aborting row.
1763
- */
1764
- const run = async ({ sessionId, statements, params, abort = () => new A2Error("STORE_UNAVAILABLE", "postgres store operation failed") }) => {
1765
- const c = await client();
1766
- try {
1767
- const { rows } = await c.query(BATCH, [statements.flatMap((statement) => statement === false ? [] : [compact(statement)]), jsonb({
1768
- ...params,
1769
- session: sessionId
1770
- })]);
1771
- return rows.map((row) => row["r"]);
1772
- } catch (error) {
1773
- const reason = abortedBatch(error);
1774
- if (reason) throw abort(reason);
1775
- throw error;
1776
- }
1777
- };
1778
- /** Whether `index` is at or below the boundary, read in a fresh statement. */
1779
- const clearedAt = async ({ query, sessionId, index }) => {
1780
- const { rows } = await query(`select ${clearIndexOf("$1")} as clear_index`, [sessionId]);
1781
- return index <= asNumber(rows[0]?.["clear_index"]);
1782
- };
1783
- /**
1784
- * A completion that does not hold its head: a stale attempt, or a retry
1785
- * after an unknown acknowledgement, which replays the committed children.
1786
- * Takes no lock.
1787
- */
1788
- const settleUnheld = async ({ query, sessionId, consumer, lane, index, attempt, events }) => {
1789
- const superseded = { outcome: "superseded" };
1790
- const { rows: cursorRows } = await query(`select latest.kind, latest.head, covering.completed_idx,
1791
- covering.completed_attempt, covering.returned_event_ids
1792
- from (
1793
- select kind, head from a2_cursors
1794
- where session_id = $1 and cursor_key = $2 and consumer = $3
1795
- order by epoch desc limit 1
1796
- ) latest
1797
- left join lateral (
1798
- select completed_idx, completed_attempt, returned_event_ids
1799
- from a2_cursors
1800
- where session_id = $1 and cursor_key = $2 and consumer = $3
1801
- and epoch <= $4
1802
- order by epoch desc limit 1
1803
- ) covering on true`, [
1804
- sessionId,
1805
- cursorKeyOf(lane, index),
1806
- consumer,
1807
- index
1808
- ]);
1809
- const cursor = cursorRows[0];
1810
- if (!cursor) {
1811
- if (await hasEvent(query, sessionId, index)) return superseded;
1812
- if (await clearedAt({
1813
- query,
1814
- sessionId,
1815
- index
1816
- })) return superseded;
1817
- throw new TypeError(`no event at index ${index} in session '${sessionId}'`);
1818
- }
1819
- const ids = events.map((event) => event.id);
1820
- if (new Set(ids).size !== ids.length) throw new A2Error("PARTIAL_DUPLICATE_BATCH", "returned event batch contains the same event id more than once");
1821
- if (asNullableNumber(cursor["head"]) === index) return superseded;
1822
- let completion;
1823
- if (cursor["kind"] === "lane") {
1824
- const { rows } = await query(`select completed_attempt, returned_event_ids from a2_lane_events
1825
- where session_id = $1 and consumer = $2 and lane = $3 and idx = $4`, [
1826
- sessionId,
1827
- consumer,
1828
- lane,
1829
- index
1830
- ]);
1831
- completion = rows[0] && {
1832
- attempt: asNullableNumber(rows[0]["completed_attempt"]),
1833
- ids: rows[0]["returned_event_ids"]
1834
- };
1835
- } else if (asNullableNumber(cursor["completed_idx"]) === index) completion = {
1836
- attempt: asNullableNumber(cursor["completed_attempt"]),
1837
- ids: cursor["returned_event_ids"]
1838
- };
1839
- if (!completion || completion.attempt !== attempt) return superseded;
1840
- const returnedIds = completion.ids === null || completion.ids === void 0 ? null : decodeReturnedEventIds(completion.ids);
1841
- if (returnedIds === null || returnedIds.length !== ids.length || returnedIds.some((id, offset) => id !== ids[offset])) throw new A2Error("PARTIAL_DUPLICATE_BATCH", "completed attempt does not match the returned event batch");
1842
- if (events.length === 0) return {
1843
- outcome: "completed",
1844
- events: []
1845
- };
1846
- const { rows: existing } = await query(`select session_id, idx, event_type, payload, event_id, created_at, cause
1847
- from a2_events where session_id = $1 and event_id = any($2::text[])`, [sessionId, ids]);
1848
- const byId = new Map(existing.map((row) => [row["event_id"], row]));
1849
- const ordered = ids.map((id) => byId.get(id));
1850
- if (ordered.some((row) => !row) && await clearedAt({
1851
- query,
1852
- sessionId,
1853
- index
1854
- })) return superseded;
1855
- if (ordered.some((row) => {
1856
- const cause = row ? decodeCause(row["cause"]) : null;
1857
- return !row || cause?.consumer !== consumer || cause.lane !== lane || cause.index !== index || cause.attempt !== attempt;
1858
- })) throw new A2Error("PARTIAL_DUPLICATE_BATCH", "returned event retry does not match the committed batch");
1859
- return {
1860
- outcome: "completed",
1861
- events: idempotentReplay(events, ordered.map(toStored))
1862
- };
1863
- };
1864
- const store = {
1865
- async append(sessionId, events, appendOptions) {
1866
- const consumers = appendOptions?.consumers;
1867
- const served = servedNames(consumers);
1868
- if (events.length === 0) return wrap(async () => {
1869
- const { rows } = await (await client()).query(`select ${pendingIn("$1", "$2")} as has_pending`, [sessionId, served]);
1870
- return {
1871
- events: [],
1872
- hasPending: rows[0]?.["has_pending"] === true
1873
- };
1874
- });
1875
- return wrap(async () => {
1876
- const suppliedIds = events.filter((e) => e.id !== void 0).map((e) => e.id);
1877
- if (new Set(suppliedIds).size !== suppliedIds.length) throw new A2Error("PARTIAL_DUPLICATE_BATCH", "batch contains the same event id more than once");
1878
- const now = clock.now().getTime();
1879
- const rows = events.map((event, offset) => ({
1880
- ord: offset + 1,
1881
- id: event.id ?? generateId(),
1882
- type: event.type,
1883
- payload: event.payload,
1884
- cause: event.cause ?? null
1885
- }));
1886
- const causes = [...new Map(events.flatMap((event) => event.cause ? [[jsonb(event.cause), event.cause]] : [])).values()];
1887
- const work = enqueue(events, consumers);
1888
- const originIndex = appendOptions?.originIndex;
1889
- const ifLastIndex = appendOptions?.ifLastIndex;
1890
- const conditionalAt = (head) => ifLastIndex === void 0 ? void 0 : {
1891
- sessionId,
1892
- ifLastIndex,
1893
- head: asNumber(head)
1894
- };
1895
- const checked = (await run({
1896
- sessionId,
1897
- statements: [
1898
- LOCK_SESSION,
1899
- APPEND_CHECKS,
1900
- causes.length > 0 && FENCE,
1901
- ifLastIndex !== void 0 && IF_LAST_INDEX,
1902
- suppliedIds.length > 0 && REUSE_IDS,
1903
- INSERT_EVENTS,
1904
- ...work.statements
1905
- ],
1906
- params: {
1907
- ...work.params,
1908
- served,
1909
- ids: suppliedIds,
1910
- count: events.length,
1911
- origin: originIndex ?? null,
1912
- ifLastIndex: ifLastIndex ?? null,
1913
- causes: causes.map((cause, offset) => ({
1914
- ord: offset + 1,
1915
- consumer: cause.consumer,
1916
- cursor_key: cursorKeyOf(cause.lane, cause.index),
1917
- idx: cause.index,
1918
- attempt: cause.attempt
1919
- })),
1920
- events: rows,
1921
- now
1922
- },
1923
- abort: (reason) => {
1924
- switch (reason["abort"]) {
1925
- case "mixed": {
1926
- const owned = asNumber(reason["owned"]);
1927
- return duplicateBatchError(`batch mixes ${owned} already-appended and ${events.length - owned} fresh events`, conditionalAt(reason["head"]));
1928
- }
1929
- case "cleared": return sessionClearedError(`scheduled work from event ${originIndex} was cleared in session '${sessionId}'`);
1930
- case "superseded": return supersededAttemptError(sessionId, causes[asNumber(reason["ord"]) - 1]);
1931
- case "moved": return lastIndexMismatchError(sessionId, ifLastIndex, asNumber(reason["index"]));
1932
- case "held": return new A2Error("STORE_UNAVAILABLE", `an event id being reused is still held by cleared work in session '${sessionId}'`);
1933
- default: return new A2Error("STORE_UNAVAILABLE", "postgres store operation failed");
1934
- }
1935
- }
1936
- })).find((row) => row["stop"] === "replay" || "base" in row);
1937
- if (checked["stop"] === "replay") return {
1938
- events: idempotentReplay(events, checked["events"].map(toStored), conditionalAt(checked["head"])),
1939
- hasPending: checked["has_pending"] === true
1940
- };
1941
- return {
1942
- events: insertedRows({
1943
- sessionId,
1944
- events: rows,
1945
- base: asNumber(checked["base"]),
1946
- now
1947
- }),
1948
- hasPending: checked["has_pending"] === true || work.started
1949
- };
1950
- });
1951
- },
1952
- async wakeLog({ sessionId, consumer }) {
1953
- const { log } = consumer;
1954
- return wrap(async () => {
1955
- const found = (await run({
1956
- sessionId,
1957
- statements: [
1958
- READ_LOG,
1959
- LOCK_SESSION,
1960
- WAKE_LOG
1961
- ],
1962
- params: {
1963
- cursorKey: cursorKeyOf(log.lane, 0),
1964
- consumer: consumer.name,
1965
- lane: log.lane,
1966
- types: log.types,
1967
- backfill: log.backfill,
1968
- clearType: CLEAR_EVENT_TYPE
1969
- }
1970
- })).at(-1);
1971
- if (found["empty"] === true) {
1972
- const head = asNumber(found["head"]);
1973
- return {
1974
- cursor: idleLogCursor(consumer.name, log.lane, head),
1975
- head
1976
- };
1977
- }
1978
- const cursor = found["cursor"];
1979
- const clearIndex = asNumber(found["stop"] === "unchanged" ? cursor["clear_index"] : found["clear_index"]);
1980
- return {
1981
- cursor: toCursor(cursor, clearIndex),
1982
- head: asNumber(found["stop"] === "unchanged" ? cursor["session_head"] : found["head"])
1983
- };
1984
- });
1985
- },
1986
- async cursors(sessionId) {
1987
- return wrap(async () => {
1988
- const { rows } = await (await client()).query(`with boundary as materialized (
1989
- select ${clearIndexOf("$1")} as clear_index
1990
- )
1991
- select cur.*, boundary.clear_index
1992
- from a2_cursors cur, boundary
1993
- where cur.session_id = $1
1994
- and (
1995
- cur.head > boundary.clear_index
1996
- or (cur.kind <> 'event' and not exists (
1997
- select 1 from a2_cursors later
1998
- where later.session_id = cur.session_id
1999
- and later.cursor_key = cur.cursor_key
2000
- and later.consumer = cur.consumer
2001
- and later.epoch > cur.epoch
2002
- ) and (
2003
- cur.kind = 'log'
2004
- or (cur.head is null and cur.position > boundary.clear_index)
2005
- ))
2006
- )`, [sessionId]);
2007
- return rows.map((row) => toCursor(row, asNumber(row["clear_index"]))).toSorted(byCursor);
2008
- });
2009
- },
2010
- async read(sessionId, opts) {
2011
- return wrap(async () => {
2012
- const c = await client();
2013
- const conditions = ["session_id = $1"];
2014
- const params = [sessionId];
2015
- if (opts?.afterIndex !== void 0) {
2016
- params.push(opts.afterIndex);
2017
- conditions.push(`idx > $${params.length}`);
2018
- }
2019
- if (opts?.throughIndex !== void 0) {
2020
- params.push(opts.throughIndex);
2021
- conditions.push(`idx <= $${params.length}`);
2022
- }
2023
- conditions.push(`idx >= ${clearIndexOf("$1")}`);
2024
- const { rows } = await c.query(`select session_id, idx, event_type, payload, event_id, created_at, cause
2025
- from a2_events where ${conditions.join(" and ")} order by idx`, params);
2026
- return rows.map(toStored);
2027
- });
2028
- },
2029
- async readHistory(sessionId, opts) {
2030
- return wrap(async () => {
2031
- if (opts?.throughIndex !== void 0 && opts.throughIndex <= (opts.afterIndex ?? 0)) return [];
2032
- const c = await client();
2033
- const conditions = ["session_id = $1"];
2034
- const params = [sessionId];
2035
- if (opts?.afterIndex !== void 0) {
2036
- params.push(opts.afterIndex);
2037
- conditions.push(`idx > $${params.length}`);
2038
- }
2039
- if (opts?.throughIndex !== void 0) {
2040
- params.push(opts.throughIndex);
2041
- conditions.push(`idx <= $${params.length}`);
2042
- }
2043
- conditions.push(`idx >= ${clearIndexOf("$1")}`);
2044
- const { rows } = await c.query(`select session_id, idx, event_id, event_type, payload, created_at
2045
- from a2_events where ${conditions.join(" and ")} order by idx`, params);
2046
- return rows.map(toEvent);
2047
- });
2048
- },
2049
- async claimAvailable({ sessionId, holder, ttlMs, expiresAtMs, exclude = [], consumers, maxFailures, through }) {
2050
- return wrap(async () => {
2051
- const now = clock.now().getTime();
2052
- const results = await run({
2053
- sessionId,
2054
- statements: [
2055
- CLAIM,
2056
- RELEASE_DEAD,
2057
- RETRY_AT
2058
- ],
2059
- params: {
2060
- now,
2061
- served: servedNames(consumers),
2062
- excluded: exclude.map((ref) => ({
2063
- consumer: ref.consumer,
2064
- cursor_key: cursorKeyOf(ref.lane, ref.index)
2065
- })),
2066
- holder,
2067
- expiresAt: expiresAtMs ?? now + ttlMs,
2068
- maxFailures: maxFailures ?? null,
2069
- through: through ?? null
2070
- }
2071
- });
2072
- const rows = results.filter((row) => "e_idx" in row);
2073
- const unseen = rows.filter((row) => row["e_idx"] === null);
2074
- if (unseen.length > 0) {
2075
- const { rows: events } = await (await client()).query(`select ${HEAD_COLUMNS} from a2_events event
2076
- where event.session_id = $1 and event.idx = any($2::bigint[])`, [sessionId, unseen.map((row) => row["head"])]);
2077
- const byIndex = new Map(events.map((event) => [asNumber(event["e_idx"]), event]));
2078
- for (const row of unseen) Object.assign(row, byIndex.get(asNumber(row["head"])));
2079
- }
2080
- const heads = rows.filter((row) => row["e_idx"] !== null);
2081
- if (heads.length > 0) {
2082
- const events = heads.map((row) => {
2083
- const head = toHead(row);
2084
- const clearIndex = asNumber(row["clear_index"]);
2085
- if (clearIndex > 0) head.clearIndex = clearIndex;
2086
- return head;
2087
- }).toSorted(byHead);
2088
- return {
2089
- outcome: "claimed",
2090
- events,
2091
- head: Math.max(...heads.map((row) => asNumber(row["session_head"])), ...events.map((event) => event.index))
2092
- };
2093
- }
2094
- const retryAt = results.at(-1)["retry_at"];
2095
- return retryAt === null || retryAt === void 0 ? { outcome: "settled" } : {
2096
- outcome: "busy",
2097
- retryAt: new Date(asNumber(retryAt))
2098
- };
2099
- });
2100
- },
2101
- async renewClaims({ sessionId, holder, claims, ttlMs, expiresAtMs }) {
2102
- if (claims.length === 0) return {
2103
- renewed: [],
2104
- superseded: []
2105
- };
2106
- return wrap(async () => {
2107
- const c = await client();
2108
- const now = clock.now().getTime();
2109
- const expiresAt = expiresAtMs ?? now + ttlMs;
2110
- const ordered = claims.toSorted((a, b) => a.index - b.index || compareText(a.consumer, b.consumer));
2111
- const { rows } = await c.query(`with listed as (
2112
- select * from unnest($3::text[], $4::text[], $5::bigint[], $6::int[])
2113
- with ordinality as listed(consumer, cursor_key, idx, attempt, ord)
2114
- ), renewed as (
2115
- update a2_cursors cur set claim_expires_at = $7
2116
- from listed
2117
- where cur.session_id = $1
2118
- and cur.cursor_key = listed.cursor_key
2119
- and cur.consumer = listed.consumer
2120
- and cur.head = listed.idx
2121
- and listed.idx > ${clearIndexOf("$1")}
2122
- and cur.attempt_count = listed.attempt
2123
- and cur.failed_at is null
2124
- and cur.claim_holder = $2
2125
- and cur.claim_expires_at > $8
2126
- returning cur.cursor_key, cur.consumer, cur.head
2127
- )
2128
- select listed.ord, latest.head, latest.position, latest.attempt_count,
2129
- latest.epoch is not null as found,
2130
- exists(
2131
- select 1 from renewed
2132
- where renewed.cursor_key = listed.cursor_key
2133
- and renewed.consumer = listed.consumer
2134
- and renewed.head = listed.idx
2135
- ) as renewed,
2136
- listed.idx <= ${clearIndexOf("$1")} as cleared
2137
- from listed
2138
- left join lateral (
2139
- select cur.epoch, cur.head, cur.position, cur.attempt_count
2140
- from a2_cursors cur
2141
- where cur.session_id = $1
2142
- and cur.cursor_key = listed.cursor_key
2143
- and cur.consumer = listed.consumer
2144
- order by cur.epoch desc limit 1
2145
- ) latest on true
2146
- order by listed.ord`, [
2147
- sessionId,
2148
- holder,
2149
- ordered.map((claim) => claim.consumer),
2150
- ordered.map((claim) => cursorKeyOf(claim.lane, claim.index)),
2151
- ordered.map((claim) => claim.index),
2152
- ordered.map((claim) => claim.attempt),
2153
- expiresAt,
2154
- now
2155
- ]);
2156
- const renewed = [];
2157
- const superseded = [];
2158
- for (const row of rows) {
2159
- const { attempt, ...ref } = ordered[asNumber(row["ord"]) - 1];
2160
- if (row["renewed"] === true) {
2161
- renewed.push(ref);
2162
- continue;
2163
- }
2164
- if (row["cleared"] === true) {
2165
- superseded.push(ref);
2166
- continue;
2167
- }
2168
- if (row["found"] !== true) continue;
2169
- const head = asNullableNumber(row["head"]);
2170
- if (head !== ref.index && asNumber(row["position"]) < ref.index) continue;
2171
- if (head !== ref.index || asNumber(row["attempt_count"]) > attempt) superseded.push(ref);
2172
- }
2173
- return {
2174
- renewed,
2175
- superseded
2176
- };
2177
- });
2178
- },
2179
- async completeAttempt({ sessionId, consumer, lane, index, attempt, events, consumers }) {
2180
- return wrap(async () => {
2181
- const ids = events.map((event) => event.id);
2182
- const duplicated = new Set(ids).size !== ids.length;
2183
- const cause = {
2184
- consumer,
2185
- lane,
2186
- index,
2187
- attempt
2188
- };
2189
- const now = clock.now().getTime();
2190
- const rows = events.map((event, offset) => ({
2191
- ord: offset + 1,
2192
- id: event.id,
2193
- type: event.type,
2194
- payload: event.payload,
2195
- cause
2196
- }));
2197
- const work = events.length > 0 && !duplicated ? enqueue(events, consumers) : void 0;
2198
- const results = await run({
2199
- sessionId,
2200
- statements: duplicated ? [HOLD] : work ? [
2201
- HOLD,
2202
- LOCK_SESSION,
2203
- RETURN_CHECKS,
2204
- REUSE_IDS,
2205
- INSERT_EVENTS,
2206
- ...work.statements,
2207
- COMPLETE_APPENDED
2208
- ] : [
2209
- HOLD,
2210
- LOCK_IF_IDLE,
2211
- COMPLETE
2212
- ],
2213
- params: {
2214
- ...work?.params,
2215
- ...retypeOf(consumer, consumers),
2216
- cursorKey: cursorKeyOf(lane, index),
2217
- consumer,
2218
- index,
2219
- attempt,
2220
- ids,
2221
- count: events.length,
2222
- events: rows,
2223
- now,
2224
- clearType: CLEAR_EVENT_TYPE
2225
- },
2226
- abort: (reason) => reason["abort"] === "owned" ? new A2Error("PARTIAL_DUPLICATE_BATCH", "returned event batch contains an already-appended event id") : new A2Error("STORE_UNAVAILABLE", reason["abort"] === "held" ? `an event id being reused is still held by cleared work in session '${sessionId}'` : "postgres store operation failed")
2227
- });
2228
- const held = results[0];
2229
- if (held["stop"] === "superseded") return { outcome: "superseded" };
2230
- if (held["stop"] === "unheld") {
2231
- const c = await client();
2232
- return settleUnheld({
2233
- query: (text, values) => c.query(text, values),
2234
- sessionId,
2235
- consumer,
2236
- lane,
2237
- index,
2238
- attempt,
2239
- events
2240
- });
2241
- }
2242
- if (duplicated) throw new A2Error("PARTIAL_DUPLICATE_BATCH", "returned event batch contains the same event id more than once");
2243
- if (results.at(-1)["stop"] === "superseded") return { outcome: "superseded" };
2244
- const checked = results.find((row) => "base" in row);
2245
- return {
2246
- outcome: "completed",
2247
- events: checked ? insertedRows({
2248
- sessionId,
2249
- events: rows,
2250
- base: asNumber(checked["base"]),
2251
- now
2252
- }) : []
2253
- };
2254
- });
2255
- },
2256
- async failAttempt({ sessionId, consumer, lane, index, attempt, error, maxFailures, retryAfterMs }) {
2257
- return wrap(() => withTx(async (query) => {
2258
- const now = clock.now().getTime();
2259
- const cursorKey = cursorKeyOf(lane, index);
2260
- const { rows } = await query(`with current as materialized (
2261
- select cur.* from a2_cursors cur
2262
- where cur.session_id = $1 and cur.cursor_key = $2
2263
- and cur.consumer = $3 and cur.head = $4
2264
- and cur.head > ${clearIndexOf("$1")}
2265
- for update of cur
2266
- ), updated as (
2267
- update a2_cursors cur set
2268
- failure_count = cur.failure_count + 1,
2269
- last_error = $6,
2270
- last_failed_at = $8,
2271
- last_failed_attempt = $5,
2272
- failed_at = case
2273
- when cur.failure_count + 1 >= $7 then $8
2274
- else cur.failed_at
2275
- end,
2276
- claim_holder = null,
2277
- claim_expires_at = case
2278
- when cur.failure_count + 1 >= $7 then null
2279
- else $9::bigint
2280
- end
2281
- from current
2282
- where cur.session_id = $1 and cur.cursor_key = $2
2283
- and cur.consumer = $3 and cur.epoch = current.epoch
2284
- and current.attempt_count = $5
2285
- and current.failed_at is null
2286
- and current.claim_holder is not null
2287
- returning cur.failure_count, cur.failed_at
2288
- )
2289
- select case
2290
- when $4 <= ${clearIndexOf("$1")} then 'cleared'
2291
- when not exists (select 1 from current) then 'missing'
2292
- when exists (
2293
- select 1 from updated where failed_at is not null
2294
- ) then 'dead_lettered'
2295
- when exists (select 1 from updated) then 'failed'
2296
- when exists (
2297
- select 1 from current where attempt_count <> $5
2298
- ) then 'superseded'
2299
- when exists (
2300
- select 1 from current
2301
- where claim_holder is null and last_failed_attempt = $5
2302
- and failed_at is null
2303
- ) then 'failed'
2304
- when exists (
2305
- select 1 from current where failed_at is not null
2306
- ) then 'dead_lettered'
2307
- else 'superseded'
2308
- end as outcome,
2309
- coalesce(
2310
- (select failure_count from updated),
2311
- (select failure_count from current)
2312
- ) as failure_count`, [
2313
- sessionId,
2314
- cursorKey,
2315
- consumer,
2316
- index,
2317
- attempt,
2318
- error,
2319
- maxFailures,
2320
- now,
2321
- retryAfterMs === void 0 ? null : now + retryAfterMs
2322
- ]);
2323
- const row = rows[0];
2324
- if (row?.["outcome"] === "cleared") return {
2325
- outcome: "superseded",
2326
- failureCount: 0
2327
- };
2328
- if (!row || row["outcome"] === "missing") {
2329
- const { rows: cursorRows } = await query(`select 1 from a2_cursors
2330
- where session_id = $1 and cursor_key = $2 and consumer = $3`, [
2331
- sessionId,
2332
- cursorKey,
2333
- consumer
2334
- ]);
2335
- if (cursorRows.length > 0 || await hasEvent(query, sessionId, index) || await clearedAt({
2336
- query,
2337
- sessionId,
2338
- index
2339
- })) return {
2340
- outcome: "superseded",
2341
- failureCount: 0
2342
- };
2343
- throw new TypeError(`no event at index ${index} in session '${sessionId}'`);
2344
- }
2345
- if (row["outcome"] === "dead_lettered") await releasePins({
2346
- query,
2347
- sessionId,
2348
- consumer,
2349
- cursorKey,
2350
- index
2351
- });
2352
- return {
2353
- outcome: row["outcome"],
2354
- failureCount: asNumber(row["failure_count"])
2355
- };
2356
- }));
2357
- },
2358
- async deadLetters(sessionId) {
2359
- return wrap(async () => {
2360
- const { rows } = await (await client()).query(`select cur.*, ${HEAD_COLUMNS}
2361
- from a2_cursors cur
2362
- join a2_events event
2363
- on event.session_id = cur.session_id and event.idx = cur.head
2364
- where cur.session_id = $1
2365
- and cur.failed_at is not null
2366
- and cur.head > ${clearIndexOf("$1")}`, [sessionId]);
2367
- return rows.map(toHead).toSorted(byHead);
2368
- });
2369
- },
2370
- async redrive({ sessionId, consumer, index, action, consumers }) {
2371
- return wrap(async () => {
2372
- const results = await run({
2373
- sessionId,
2374
- statements: [
2375
- action === "skip" && LOCK_SESSION,
2376
- LOCK_DEAD,
2377
- action === "skip" ? SKIP_DEAD : RETRY_DEAD,
2378
- PENDING
2379
- ],
2380
- params: {
2381
- ...retypeOf(consumer, consumers),
2382
- consumer,
2383
- index,
2384
- served: servedNames(consumers),
2385
- clearType: CLEAR_EVENT_TYPE
2386
- }
2387
- });
2388
- return {
2389
- redriven: results.find((row) => "redriven" in row)?.["redriven"] === true,
2390
- hasPending: results.at(-1)["has_pending"] === true
2391
- };
2392
- });
2393
- },
2394
- async readState(sessionId, reducerName, stateOptions) {
2395
- return wrap(async () => (await readStateBatch([{
2396
- sessionId,
2397
- ...stateOptions?.throughIndex === void 0 ? {} : { throughIndex: stateOptions.throughIndex },
2398
- ...stateOptions?.snapshotThroughIndex === void 0 ? {} : { snapshotThroughIndex: stateOptions.snapshotThroughIndex }
2399
- }], reducerName))[0]);
2400
- },
2401
- async readStates(requests, reducerName) {
2402
- return wrap(() => readStateBatch(requests, reducerName));
2403
- },
2404
- async putSnapshots(sessionId, reducerName, writes) {
2405
- await wrap(() => withTx(async (query) => {
2406
- const requested = [...new Map(writes.map((write) => [write.index, write])).values()].toSorted((a, b) => a.index - b.index);
2407
- if (requested.length === 0) return;
2408
- await query("select pg_advisory_xact_lock(hashtext($1), hashtext($2))", [sessionId, reducerName]);
2409
- const { rows: headRows } = await query(`select boundary.clear_index, head.up_to_index, head.state, head.updated_at
2410
- from (select ${clearIndexOf("$1")} as clear_index) boundary
2411
- left join lateral (
2412
- select up_to_index, state, updated_at from a2_snapshots
2413
- where session_id = $1 and reducer_name = $2
2414
- for update
2415
- ) head on true`, [sessionId, reducerName]);
2416
- const clearIndex = asNumber(headRows[0]?.["clear_index"]);
2417
- const normalized = requested.filter((write) => write.index >= clearIndex);
2418
- if (normalized.length === 0) return;
2419
- const currentHead = headRows[0]?.["up_to_index"] == null ? void 0 : headRows[0];
2420
- const requestedPins = normalized.flatMap((write) => (write.pins ?? []).map((pin) => ({
2421
- eventIndex: pin.index,
2422
- consumer: pin.consumer,
2423
- cursorKey: cursorKeyOf(pin.lane, pin.index),
2424
- snapshotIndex: write.index
2425
- })));
2426
- if (requestedPins.length > 0) {
2427
- const heads = [...new Map(requestedPins.map((pin) => [`${pin.consumer}\u0000${pin.cursorKey}\u0000${pin.eventIndex}`, pin])).values()];
2428
- const { rows: live } = await query(`select cur.consumer, cur.cursor_key, cur.head
2429
- from a2_cursors cur
2430
- join unnest($2::text[], $3::text[], $4::bigint[])
2431
- as pin(consumer, cursor_key, idx)
2432
- on cur.consumer = pin.consumer
2433
- and cur.cursor_key = pin.cursor_key
2434
- and cur.head = pin.idx
2435
- where cur.session_id = $1 and cur.head > $5
2436
- and cur.failed_at is null
2437
- order by cur.cursor_key, cur.consumer
2438
- for share of cur`, [
2439
- sessionId,
2440
- heads.map((pin) => pin.consumer),
2441
- heads.map((pin) => pin.cursorKey),
2442
- heads.map((pin) => pin.eventIndex),
2443
- clearIndex
2444
- ]);
2445
- const unfinished = new Set(live.map((row) => `${String(row["consumer"])}\u0000${String(row["cursor_key"])}\u0000${asNumber(row["head"])}`));
2446
- const accepted = requestedPins.filter((pin) => unfinished.has(`${pin.consumer}\u0000${pin.cursorKey}\u0000${pin.eventIndex}`));
2447
- if (accepted.length > 0) await query(`insert into a2_snapshot_pins
2448
- (session_id, event_index, consumer, cursor_key, reducer_name, up_to_index)
2449
- select $1, pin."eventIndex", pin.consumer, pin."cursorKey",
2450
- $2, pin."snapshotIndex"
2451
- from jsonb_to_recordset($3::jsonb) as pin(
2452
- "eventIndex" bigint,
2453
- consumer text,
2454
- "cursorKey" text,
2455
- "snapshotIndex" bigint
2456
- )
2457
- on conflict do nothing`, [
2458
- sessionId,
2459
- reducerName,
2460
- jsonb(accepted)
2461
- ]);
2462
- }
2463
- const latestWrite = normalized.at(-1);
2464
- const writesHead = !currentHead || latestWrite.index >= asNumber(currentHead["up_to_index"]);
2465
- const advancesHead = !currentHead || latestWrite.index > asNumber(currentHead["up_to_index"]);
2466
- const finalHeadIndex = advancesHead ? latestWrite.index : asNumber(currentHead["up_to_index"]);
2467
- const { rows: pinRows } = await query(`select distinct up_to_index from a2_snapshot_pins
2468
- where session_id = $1 and reducer_name = $2
2469
- and up_to_index = any($3::bigint[])`, [
2470
- sessionId,
2471
- reducerName,
2472
- [.../* @__PURE__ */ new Set([...normalized.map((write) => write.index), ...currentHead ? [asNumber(currentHead["up_to_index"])] : []])]
2473
- ]);
2474
- const pinned = new Set(pinRows.map((row) => asNumber(row["up_to_index"])));
2475
- const historical = /* @__PURE__ */ new Map();
2476
- if (advancesHead && currentHead && asNumber(currentHead["up_to_index"]) >= clearIndex && pinned.has(asNumber(currentHead["up_to_index"]))) {
2477
- const index = asNumber(currentHead["up_to_index"]);
2478
- historical.set(index, {
2479
- index,
2480
- state: currentHead["state"],
2481
- updatedAt: asNumber(currentHead["updated_at"])
2482
- });
2483
- }
2484
- const updatedAt = clock.now().getTime();
2485
- for (const write of normalized) if (write.index < finalHeadIndex && pinned.has(write.index)) historical.set(write.index, {
2486
- index: write.index,
2487
- state: write.state,
2488
- updatedAt
2489
- });
2490
- if (historical.size > 0) await query(`insert into a2_snapshot_history
2491
- (session_id, reducer_name, up_to_index, state, updated_at)
2492
- select $1, $2, snapshot.index, snapshot.state, snapshot."updatedAt"
2493
- from jsonb_to_recordset($3::jsonb) as snapshot(
2494
- index bigint,
2495
- state jsonb,
2496
- "updatedAt" bigint
2497
- )
2498
- on conflict (session_id, reducer_name, up_to_index) do update set
2499
- state = excluded.state,
2500
- updated_at = excluded.updated_at`, [
2501
- sessionId,
2502
- reducerName,
2503
- jsonb([...historical.values()])
2504
- ]);
2505
- if (writesHead) {
2506
- await query(`insert into a2_snapshots
2507
- (session_id, reducer_name, up_to_index, state, updated_at)
2508
- values ($1, $2, $3, $4::jsonb, $5)
2509
- on conflict (session_id, reducer_name) do update set
2510
- up_to_index = excluded.up_to_index,
2511
- state = excluded.state,
2512
- updated_at = excluded.updated_at
2513
- where excluded.up_to_index >= a2_snapshots.up_to_index`, [
2514
- sessionId,
2515
- reducerName,
2516
- latestWrite.index,
2517
- jsonb(latestWrite.state),
2518
- clock.now().getTime()
2519
- ]);
2520
- await query(`delete from a2_snapshot_history
2521
- where session_id = $1 and reducer_name = $2 and up_to_index = $3`, [
2522
- sessionId,
2523
- reducerName,
2524
- latestWrite.index
2525
- ]);
2526
- }
2527
- }));
2528
- },
2529
- presence: {
2530
- async set(ns, participant, values, meta) {
2531
- const entries = Object.entries(values);
2532
- if (entries.length === 0) return;
2533
- await wrap(async () => {
2534
- const atMs = meta.at.getTime();
2535
- const nowMs = clock.now().getTime();
2536
- const expiresAtMs = nowMs + meta.ttlMs;
2537
- const applied = nullProtoRecord();
2538
- const write = async (query) => {
2539
- for (const [field, value] of entries) if ((await query(`insert into a2_presence
2540
- (ns, participant, field, value, seen, at, expires_at)
2541
- values ($1, $2, $3, $4::jsonb, $5, $6, $7)
2542
- on conflict (ns, participant, field) do update set
2543
- value = excluded.value,
2544
- seen = excluded.seen,
2545
- at = excluded.at,
2546
- expires_at = excluded.expires_at
2547
- where a2_presence.at <= excluded.at
2548
- or a2_presence.expires_at <= $8${notifications ? " returning field" : ""}`, [
2549
- ns,
2550
- participant,
2551
- field,
2552
- jsonb(value),
2553
- meta.seen,
2554
- atMs,
2555
- expiresAtMs,
2556
- nowMs
2557
- ])).rows.length) applied[field] = structuredClone(value);
2558
- };
2559
- if (notifications) await withTx(write);
2560
- else {
2561
- const c = await client();
2562
- await write((text, parameters) => c.query(text, parameters));
2563
- }
2564
- if (Object.keys(applied).length) {
2565
- const patch = {
2566
- participant,
2567
- values: applied,
2568
- seen: meta.seen,
2569
- at: new Date(atMs)
2570
- };
2571
- const subscription = presenceSubscriptions.get(ns);
2572
- subscription?.poll.update(patch);
2573
- for (const listener of subscription?.listeners ?? []) listener(patch);
2574
- }
2575
- });
2576
- },
2577
- async read(ns) {
2578
- return wrap(async () => {
2579
- const c = await client();
2580
- const now = clock.now().getTime();
2581
- const { rows } = await c.query(`with swept as (
2582
- delete from a2_presence
2583
- where ns = $1 and expires_at <= $2
2584
- )
2585
- select participant, field, value, seen, at, expires_at
2586
- from a2_presence
2587
- where ns = $1 and expires_at > $2 and value <> 'null'::jsonb
2588
- order by participant, field`, [ns, now]);
2589
- return rows.map((row) => ({
2590
- participant: row["participant"],
2591
- field: row["field"],
2592
- value: row["value"],
2593
- seen: asNumber(row["seen"]),
2594
- at: new Date(asNumber(row["at"])),
2595
- expiresAt: new Date(asNumber(row["expires_at"]))
2596
- }));
2597
- });
2598
- }
2599
- },
2600
- stream(sessionId, opts) {
2601
- const readAfter = (afterIndex) => wrap(async () => {
2602
- const { rows } = await (await client()).query(`select session_id, idx, event_type, payload, event_id, created_at
2603
- from a2_events
2604
- where session_id = $1 and idx > $2
2605
- and idx >= ${clearIndexOf("$1")}
2606
- order by idx`, [sessionId, afterIndex]);
2607
- return rows.map(toEvent);
2608
- });
2609
- if (notifications) return notifications.stream({
2610
- channel: postgresNotificationChannel({
2611
- kind: "events",
2612
- sessionId
2613
- }),
2614
- read: readAfter,
2615
- startAfter: opts?.startAfter ?? 0
2616
- });
2617
- return pollingStream(readAfter, opts?.startAfter !== void 0 ? { startAfter: opts.startAfter } : {});
2618
- },
2619
- async clear({ sessionId, ifLastIndex, cause }) {
2620
- return wrap(() => withTx(async (query) => {
2621
- await lockSession(query, sessionId);
2622
- const { rows: headRows } = await query(`select coalesce(max(idx), 0) as head,
2623
- ${clearIndexOf("$1")} as clear_index
2624
- from a2_events where session_id = $1`, [sessionId]);
2625
- const head = asNumber(headRows[0]?.["head"]);
2626
- const clearIndex = asNumber(headRows[0]?.["clear_index"]);
2627
- if (cause) await assertCurrentCause({
2628
- query,
2629
- sessionId,
2630
- cause,
2631
- clearIndex,
2632
- lock: "update"
2633
- });
2634
- if (ifLastIndex !== void 0 && clearIndex === ifLastIndex + 1) return {
2635
- cleared: true,
2636
- index: head,
2637
- clearIndex
2638
- };
2639
- if (ifLastIndex !== void 0 && ifLastIndex !== head) return {
2640
- cleared: false,
2641
- index: head,
2642
- clearIndex
2643
- };
2644
- if (head === 0 || clearIndex === head) return {
2645
- cleared: true,
2646
- index: head,
2647
- clearIndex
2648
- };
2649
- const marker = head + 1;
2650
- await query(`insert into a2_events
2651
- (session_id, idx, event_type, payload, event_id, created_at, cause)
2652
- values ($1, $2, $3, 'null'::jsonb, $4, $5, null)`, [
2653
- sessionId,
2654
- marker,
2655
- CLEAR_EVENT_TYPE,
2656
- generateId(),
2657
- clock.now().getTime()
2658
- ]);
2659
- await query(`with released as (
2660
- update a2_cursors
2661
- set head = null, ${FRESH_DISPATCH}
2662
- where session_id = $1 and cursor_key = $3 and consumer = $4
2663
- and head = $5
2664
- )
2665
- insert into a2_clears (session_id, clear_index) values ($1, $2)
2666
- on conflict (session_id) do update set clear_index = excluded.clear_index`, [
2667
- sessionId,
2668
- marker,
2669
- cause ? cursorKeyOf(cause.lane, cause.index) : null,
2670
- cause?.consumer ?? null,
2671
- cause?.index ?? null
2672
- ]);
2673
- return {
2674
- cleared: true,
2675
- index: marker,
2676
- clearIndex: marker
2677
- };
2678
- }));
2679
- },
2680
- async reclaim(sessionId) {
2681
- return wrap(() => withTx(async (query) => {
2682
- const { rows } = await query(`with boundary as materialized (
2683
- select ${clearIndexOf("$1")} as clear_index
2684
- ), batch as materialized (
2685
- select idx from a2_events
2686
- where session_id = $1
2687
- and idx < (select clear_index from boundary)
2688
- order by idx
2689
- limit $2
2690
- for update skip locked
2691
- ), deleted as (
2692
- delete from a2_events event using batch
2693
- where event.session_id = $1 and event.idx = batch.idx
2694
- returning event.idx
2695
- ), pins as (
2696
- delete from a2_snapshot_pins pin using deleted
2697
- where pin.session_id = $1 and pin.event_index = deleted.idx
2698
- ), lanes as materialized (
2699
- -- Each lane's queue through the batch, by the lane's own key.
2700
- select lane.ctid from a2_cursors cur
2701
- join a2_lane_events lane
2702
- on lane.session_id = cur.session_id
2703
- and lane.consumer = cur.consumer and lane.lane = cur.lane
2704
- where cur.session_id = $1 and cur.kind = 'lane'
2705
- and lane.idx <= (select max(idx) from batch)
2706
- for update of lane skip locked
2707
- ), gone_lanes as (
2708
- delete from a2_lane_events target using lanes
2709
- where target.ctid = lanes.ctid
2710
- ), singles as materialized (
2711
- select cur.ctid from a2_cursors cur
2712
- join batch on cur.cursor_key = '#' || batch.idx
2713
- where cur.session_id = $1 and cur.kind = 'event'
2714
- for update of cur skip locked
2715
- ), gone_singles as (
2716
- delete from a2_cursors target using singles
2717
- where target.ctid = singles.ctid
2718
- )
2719
- select (select count(*) from deleted) as deleted,
2720
- (select clear_index from boundary) as clear_index`, [sessionId, RECLAIM_BATCH]);
2721
- const deleted = asNumber(rows[0]?.["deleted"]);
2722
- const clearIndex = asNumber(rows[0]?.["clear_index"]);
2723
- if (clearIndex === 0) return {
2724
- deleted: 0,
2725
- done: true
2726
- };
2727
- const { rows: remaining } = await query("select 1 from a2_events where session_id = $1 and idx < $2 limit 1", [sessionId, clearIndex]);
2728
- if (remaining.length > 0) return {
2729
- deleted,
2730
- done: false
2731
- };
2732
- const { rows: swept } = await query(`with lanes as materialized (
2733
- select ctid from a2_lane_events
2734
- where session_id = $1 and idx < $2
2735
- for update skip locked
2736
- ), cursors as materialized (
2737
- select cur.ctid from a2_cursors cur
2738
- where ${SUPERSEDED_CURSOR}
2739
- for update skip locked
2740
- ), pins as materialized (
2741
- select ctid from a2_snapshot_pins
2742
- where session_id = $1 and up_to_index < $2
2743
- for update skip locked
2744
- ), history as materialized (
2745
- select ctid from a2_snapshot_history
2746
- where session_id = $1 and up_to_index < $2
2747
- for update skip locked
2748
- ), heads as materialized (
2749
- select ctid from a2_snapshots
2750
- where session_id = $1 and up_to_index < $2
2751
- for update skip locked
2752
- ), gone_lanes as (
2753
- delete from a2_lane_events target using lanes
2754
- where target.ctid = lanes.ctid
2755
- ), gone_cursors as (
2756
- delete from a2_cursors target using cursors
2757
- where target.ctid = cursors.ctid
2758
- ), gone_pins as (
2759
- delete from a2_snapshot_pins target using pins where target.ctid = pins.ctid
2760
- ), gone_history as (
2761
- delete from a2_snapshot_history target using history
2762
- where target.ctid = history.ctid
2763
- ), gone_heads as (
2764
- delete from a2_snapshots target using heads where target.ctid = heads.ctid
2765
- )
2766
- select (select count(*) from a2_lane_events
2767
- where session_id = $1 and idx < $2)
2768
- + (select count(*) from a2_cursors cur
2769
- where ${SUPERSEDED_CURSOR})
2770
- + (select count(*) from a2_snapshot_pins
2771
- where session_id = $1 and up_to_index < $2)
2772
- + (select count(*) from a2_snapshot_history
2773
- where session_id = $1 and up_to_index < $2)
2774
- + (select count(*) from a2_snapshots
2775
- where session_id = $1 and up_to_index < $2)
2776
- - (select count(*) from lanes)
2777
- - (select count(*) from cursors)
2778
- - (select count(*) from pins)
2779
- - (select count(*) from history)
2780
- - (select count(*) from heads) as skipped`, [sessionId, clearIndex]);
2781
- return {
2782
- deleted,
2783
- done: asNumber(swept[0]?.["skipped"]) === 0
2784
- };
2785
- }));
2786
- },
2787
- async close() {
2788
- if (closed) return;
2789
- closed = true;
2790
- for (const subscription of presenceSubscriptions.values()) subscription.stop();
2791
- presenceSubscriptions.clear();
2792
- await notifications?.close();
2793
- const opened = await connection.peek()?.catch(() => void 0);
2794
- await (injected ?? opened?.lease)?.release();
2795
- }
2796
- };
2797
- if (notifications) {
2798
- const presence = store.presence;
2799
- const read = presence.read;
2800
- presence.read = async (ns) => {
2801
- const subscription = presenceSubscriptions.get(ns);
2802
- await subscription?.ready;
2803
- await subscription?.poll.ready;
2804
- return subscription ? subscription.poll.snapshot(() => read(ns)) : read(ns);
2805
- };
2806
- presence.subscribe = (ns, onPatch) => {
2807
- if (closed) throw new A2Error("STORE_UNAVAILABLE", "the store was closed");
2808
- let subscription = presenceSubscriptions.get(ns);
2809
- if (!subscription) {
2810
- const listeners = /* @__PURE__ */ new Set();
2811
- let dirty = false;
2812
- let ended = false;
2813
- let waiting;
2814
- const lease = notifications.watch({
2815
- channel: postgresNotificationChannel({
2816
- kind: "presence",
2817
- sessionId: ns
2818
- }),
2819
- notify: (source) => {
2820
- if (source === instanceId) return;
2821
- dirty = true;
2822
- waiting?.cancel();
2823
- }
2824
- });
2825
- const poll = pollPresence({
2826
- read: async () => {
2827
- await lease.ready;
2828
- if (ended || closed) return [];
2829
- dirty = false;
2830
- return read(ns);
2831
- },
2832
- deliver: (patch) => {
2833
- for (const listener of listeners) listener(patch);
2834
- },
2835
- sleep: () => {
2836
- waiting = defaultSleep(dirty ? 0 : NOTIFY_TIMINGS.safetyReadMs);
2837
- return waiting;
2838
- }
2839
- });
2840
- lease.ready.catch(() => poll.stop());
2841
- subscription = {
2842
- listeners,
2843
- ready: lease.ready,
2844
- poll,
2845
- stop() {
2846
- ended = true;
2847
- poll.stop();
2848
- lease.stop();
2849
- waiting?.cancel();
2850
- }
2851
- };
2852
- presenceSubscriptions.set(ns, subscription);
2853
- }
2854
- subscription.listeners.add(onPatch);
2855
- let stopped = false;
2856
- return () => {
2857
- if (stopped) return;
2858
- stopped = true;
2859
- subscription.listeners.delete(onPatch);
2860
- if (subscription.listeners.size === 0) {
2861
- presenceSubscriptions.delete(ns);
2862
- subscription.stop();
2863
- }
2864
- };
2865
- };
2866
- }
2867
- return store;
2868
- }
2869
- //#endregion
2870
- //#region src/store/postgres-db.ts
2871
- const SCHEMA_FILE = "node_modules/@vercel/board/sql/postgres/schema.sql";
2872
- /** The board's own error for tables that aren't there: the fix is a file to apply. */
2873
- var TablesNotConfiguredError = class extends Error {
2874
- code = "STORE_NOT_CONFIGURED";
2875
- };
2876
- /** Missing tables or columns (42P01, 42703), or missing grants (42501), say what to apply. */
2877
- function explain(error) {
2878
- const code = error?.code;
2879
- if (code === "42P01" || code === "42703") return new TablesNotConfiguredError(`board's tables aren't in this database: apply ${SCHEMA_FILE}`, { cause: error });
2880
- if (code === "42501") return new TablesNotConfiguredError(`this database role can't use board's tables: grant it select, insert, update, and delete on them`, { cause: error });
2881
- return error;
2882
- }
2883
- /**
2884
- * The tables on Postgres, through a pool that `pool()` makes the first time it's
2885
- * needed. `owned`: closing the tables ends the pool.
2886
- */
2887
- function postgresDb(pool, options = { owned: true }) {
2888
- const run = async (queryable, query) => {
2889
- try {
2890
- return await queryable.query(query.text, query.values);
2891
- } catch (error) {
2892
- throw explain(error);
2893
- }
2894
- };
2895
- /** Runs `body` in a transaction, which commits when it returns true and rolls back otherwise. */
2896
- async function transaction(begin, body) {
2897
- const client = await (await pool()).connect();
2898
- try {
2899
- await client.query(begin);
2900
- const keep = await body(client);
2901
- await client.query(keep ? "commit" : "rollback");
2902
- return keep;
2903
- } catch (error) {
2904
- await client.query("rollback").catch(() => {});
2905
- throw error;
2906
- } finally {
2907
- client.release();
2908
- }
2909
- }
2910
- return {
2911
- dialect: "postgres",
2912
- all: async (query) => (await run(await pool(), query)).rows,
2913
- async read(queries) {
2914
- const rows = [];
2915
- await transaction("begin isolation level repeatable read read only", async (client) => {
2916
- for (const query of queries) rows.push((await run(client, query)).rows);
2917
- return true;
2918
- });
2919
- return rows;
2920
- },
2921
- commit: (claim, writes) => transaction("begin", async (client) => {
2922
- if ((await run(client, claim)).rows.length === 0) return false;
2923
- for (const write of writes) await run(client, write);
2924
- return true;
2925
- }),
2926
- async close() {
2927
- if (options.owned) await (await pool()).end();
2928
- }
2929
- };
2930
- }
2931
- //#endregion
2932
- //#region src/store/postgres.ts
2933
- /** `pg` is an optional peer, installed by the apps that use Postgres. */
2934
- const PG = "pg";
2935
- /**
2936
- * A board on Postgres (`npm i pg`). Apply `node_modules/@vercel/board/sql/postgres/schema.sql`
2937
- * before the first deploy: neither A2 nor board creates tables in Postgres.
2938
- */
2939
- function postgres(options) {
2940
- const listen = options.listenConnectionString ? { listenConnectionString: options.listenConnectionString } : {};
2941
- if ("client" in options) {
2942
- if (typeof options.client.connect !== "function") throw new TypeError("postgres({ client }) takes a pg Pool, which has connect()");
2943
- const log = postgres$1({
2944
- client: options.client,
2945
- ...listen
2946
- });
2947
- return {
2948
- log,
2949
- tables: sqlTables(postgresDb(async () => options.client, { owned: false })),
2950
- close: () => log.close()
2951
- };
2952
- }
2953
- const log = postgres$1({
2954
- connectionString: options.connectionString,
2955
- ...listen
2956
- });
2957
- let pool = null;
2958
- const open = () => pool ??= import(PG).then(({ default: pg }) => {
2959
- const opened = new pg.Pool({
2960
- connectionString: options.connectionString,
2961
- max: options.max ?? 5
2962
- });
2963
- opened.on("error", () => {});
2964
- return opened;
2965
- });
2966
- const tables = sqlTables(postgresDb(open));
2967
- return {
2968
- log,
2969
- tables,
2970
- async close() {
2971
- if (pool) await tables.close();
2972
- await log.close();
2973
- }
2974
- };
2975
- }
2976
- //#endregion
2977
- export { postgres };