@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,3611 +0,0 @@
1
- import { c as sessionClearedError, i as asStoreUnavailable, o as isSessionCleared, r as NonRetriableError, t as A2Error } from "./session-clear-XJYpmUpg-2q8l_FJR.mjs";
2
- import { n as cloneInitial, o as validateSync, r as foldEvent } from "./reducer-Bswr11ar-P324o9vn.mjs";
3
- import { _ as serverInternals, a as RESERVED_PARTICIPANT_IDS, c as STREAM_TIMINGS, d as drainSettledHooks, f as failedPreviousAttempt, g as runtimeConsumers, h as runtimeConsumerFactory, m as nullProtoRecord, o as SOCKET_TIMINGS, p as markSchedulerSendFailure, r as POLL_TIMINGS, s as STATE_CACHE, t as DRAIN_TIMINGS, v as stateTailReaders } from "./internal-CvsrprnU-zZMpDiRY.mjs";
4
- import { a as takeBuffered, i as presenceTombstones, n as isSerializedEvent, r as parseSerializedEvent, t as bufferedEvents } from "./stream-buffer-DrTyiIuo-Be10yOBR.mjs";
5
- import { i as streamActivities, n as defaultSleep, t as createStreamActivity } from "./store-polling-BZt2Rf3D-Div-bJ_D.mjs";
6
- import { r as platformWaitUntil, t as invocationDeadlineMs } from "./platform-B4TnJtWu-Do3agKr5.mjs";
7
- import { t as retryableLazy } from "./retryable-lazy-DZWmHpii-DpTc5PIP.mjs";
8
- //#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/reducer-runtime-DQwz_J59.js
9
- const runtimeKey = Symbol("a2.reducerRuntime");
10
- function encodeState(options) {
11
- const storage = options.reducer[runtimeKey]?.storage;
12
- return storage ? storage.encode(options.state) : options.state;
13
- }
14
- function decodeState(options) {
15
- const storage = options.reducer[runtimeKey]?.storage;
16
- return storage ? storage.decode(options.state) : options.state;
17
- }
18
- //#endregion
19
- //#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/bounded-cache-CPHWF-8h.js
20
- function boundedCache({ maxEntries, maxBytes }) {
21
- const entries = /* @__PURE__ */ new Map();
22
- let total = 0;
23
- const remove = (key) => {
24
- const entry = entries.get(key);
25
- if (!entry) return;
26
- entries.delete(key);
27
- total -= entry.bytes;
28
- };
29
- return {
30
- get(key) {
31
- const entry = entries.get(key);
32
- if (!entry) return void 0;
33
- entries.delete(key);
34
- entries.set(key, entry);
35
- return entry.value;
36
- },
37
- set(key, value, bytes) {
38
- remove(key);
39
- if (bytes > maxBytes / 4) return;
40
- entries.set(key, {
41
- value,
42
- bytes
43
- });
44
- total += bytes;
45
- for (const oldest of entries.keys()) {
46
- if (entries.size <= maxEntries && total <= maxBytes) break;
47
- remove(oldest);
48
- }
49
- },
50
- delete: remove,
51
- deleteWhere(match) {
52
- for (const key of entries.keys()) if (match(key)) remove(key);
53
- }
54
- };
55
- }
56
- //#endregion
57
- //#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/wire-BFE9sIQf.js
58
- /**
59
- * The wire format shared by server.fetch and experimental-a2/client
60
- * (browser side): events as JSON with ISO timestamps, and the A2Error
61
- * envelope. Internal module — both entry points re-export what's
62
- * public.
63
- */
64
- function eventToWire(event) {
65
- return {
66
- id: event.id,
67
- type: event.type,
68
- payload: event.payload,
69
- index: event.index,
70
- sessionId: event.sessionId,
71
- createdAt: event.createdAt.toISOString()
72
- };
73
- }
74
- const lastEncoding = (encode) => {
75
- let last;
76
- let text = "";
77
- return (value) => {
78
- if (value !== last) {
79
- text = encode(value);
80
- last = value;
81
- }
82
- return text;
83
- };
84
- };
85
- const isoJson = lastEncoding((ms) => JSON.stringify(new Date(ms).toISOString()));
86
- const sessionJson = lastEncoding((id) => JSON.stringify(id));
87
- const typeJson = lastEncoding((type) => JSON.stringify(type));
88
- /**
89
- * `JSON.stringify(eventToWire(event))` for the parsed event, built around the
90
- * stored payload text instead of parsing and re-serializing it.
91
- */
92
- function serializedEventToWireJson(event) {
93
- return `{"id":${JSON.stringify(event.id)},"type":${typeJson(event.type)},"payload":${event.payloadJson},"index":${event.index},"sessionId":${sessionJson(event.sessionId)},"createdAt":${isoJson(event.createdAtMs)}}`;
94
- }
95
- function wireVersion(value) {
96
- return value === "2" ? 2 : 1;
97
- }
98
- /**
99
- * Events already held by a stream join one write while it is shorter than
100
- * this many characters, so a write can exceed it by the event that crosses it.
101
- */
102
- const EVENT_WRITE_CHARS = 65536;
103
- /** Stream items that are events, as opposed to snapshot or presence frames. */
104
- function isStreamEvent(item) {
105
- return !("kind" in item) && !("snapshot" in item) && !("participant" in item);
106
- }
107
- /**
108
- * `first` and the events `iterator` already holds, encoded, until the batch
109
- * reaches `EVENT_WRITE_CHARS`; `last` is the batch's final event.
110
- */
111
- function heldEventBatch(options) {
112
- const { iterator, encode } = options;
113
- let last = options.first;
114
- const events = [encode(last)];
115
- let chars = events[0].length;
116
- while (chars < EVENT_WRITE_CHARS) {
117
- const held = takeBuffered(iterator);
118
- if (!held) break;
119
- const json = encode(held);
120
- events.push(json);
121
- chars += json.length + 1;
122
- last = held;
123
- }
124
- return {
125
- events,
126
- last
127
- };
128
- }
129
- /** One version 2 event as JSON, splicing a held row's stored payload. */
130
- function compactEventJson(event) {
131
- if (!isSerializedEvent(event)) return JSON.stringify({
132
- id: event.id,
133
- type: event.type,
134
- payload: event.payload,
135
- index: event.index,
136
- createdAt: event.createdAt.getTime()
137
- });
138
- return `{"id":${JSON.stringify(event.id)},"type":${typeJson(event.type)},"payload":${event.payloadJson},"index":${event.index},"createdAt":${event.createdAtMs}}`;
139
- }
140
- function presencePatchToWire(patch) {
141
- return {
142
- participant: patch.participant,
143
- values: patch.values,
144
- seen: patch.seen,
145
- at: patch.at.toISOString()
146
- };
147
- }
148
- function presenceSnapshotToWire(snapshot) {
149
- const wire = nullProtoRecord();
150
- for (const [participant, fields] of Object.entries(snapshot.snapshot)) {
151
- const wireFields = nullProtoRecord();
152
- for (const [field, entry] of Object.entries(fields)) {
153
- if (entry === void 0) continue;
154
- wireFields[field] = {
155
- value: entry.value,
156
- seen: entry.seen,
157
- at: entry.at.toISOString()
158
- };
159
- }
160
- wire[participant] = wireFields;
161
- }
162
- return { snapshot: wire };
163
- }
164
- const ERROR_STATUS = {
165
- INVALID_PAYLOAD: 400,
166
- FORBIDDEN: 403,
167
- UNKNOWN_EVENT_TYPE: 400,
168
- PARTIAL_DUPLICATE_BATCH: 400,
169
- SUPERSEDED_ATTEMPT: 409,
170
- SESSION_CLEARED: 409,
171
- LAST_INDEX_MISMATCH: 409,
172
- CLAIM_EXPIRED: 409,
173
- STORE_UNAVAILABLE: 503,
174
- STORE_NOT_CONFIGURED: 500,
175
- UNKNOWN_PRESENCE_FIELD: 400,
176
- PRESENCE_NOT_SUPPORTED: 500,
177
- CONSUMER_DEAD_LETTERED: 500
178
- };
179
- function errorStatus(code) {
180
- return ERROR_STATUS[isServerErrorCode(code) ? code : "STORE_UNAVAILABLE"];
181
- }
182
- function errorToWire(error) {
183
- const failure = asA2Error(error);
184
- const body = { error: {
185
- code: failure.code,
186
- message: failure.message
187
- } };
188
- if (failure.details !== void 0) body.error.details = failure.details;
189
- return body;
190
- }
191
- /** Wrap an arbitrary thrown value for the wire: known server codes pass through,
192
- * anything else becomes STORE_UNAVAILABLE — from the client's
193
- * perspective an unknown server failure is retryable-once, not a
194
- * protocol contract. */
195
- function asA2Error(error) {
196
- return error instanceof A2Error && isServerErrorCode(error.code) ? error : new A2Error("STORE_UNAVAILABLE", "internal error", { cause: error });
197
- }
198
- const isServerErrorCode = (code) => Object.hasOwn(ERROR_STATUS, code);
199
- function stateSnapshotToWire(frame) {
200
- return frame.state === void 0 ? {
201
- ...frame,
202
- state: null,
203
- stateUndefined: true
204
- } : frame;
205
- }
206
- const SOCKET_PING_FRAME = JSON.stringify({ kind: "ping" });
207
- /** One stream item as a socket frame — `sseResponse`'s framing over
208
- * the same codecs, with `kind` instead of an SSE event name. On a
209
- * multiplexed socket presence frames carry the `sessionId` tag; events
210
- * already carry theirs in the wire event. */
211
- function socketFrameFor(item, sessionId) {
212
- const tag = sessionId === void 0 ? {} : { sessionId };
213
- if ("kind" in item) return JSON.stringify(stateSnapshotToWire(item));
214
- if ("snapshot" in item) return JSON.stringify({
215
- kind: "presence-snapshot",
216
- ...presenceSnapshotToWire(item),
217
- ...tag
218
- });
219
- if ("participant" in item) return JSON.stringify({
220
- kind: "presence",
221
- ...presencePatchToWire(item),
222
- ...tag
223
- });
224
- return JSON.stringify({
225
- kind: "event",
226
- ...eventToWire(item)
227
- });
228
- }
229
- /** A version 2 batch frame from compact event JSON; a multiplexed
230
- * socket names the batch's session once. */
231
- function socketEventsFor(events, sessionId) {
232
- return `{"kind":"events",${sessionId === void 0 ? "" : `"sessionId":${JSON.stringify(sessionId)},`}"events":[${events.join(",")}]}`;
233
- }
234
- function socketAckFor(req, events, sessionId) {
235
- return JSON.stringify({
236
- kind: "ack",
237
- req,
238
- events: events.map(eventToWire),
239
- ...sessionId === void 0 ? {} : { sessionId }
240
- });
241
- }
242
- function socketErrorAckFor(req, error, sessionId) {
243
- return JSON.stringify({
244
- kind: "ack",
245
- req,
246
- ...errorToWire(error),
247
- ...sessionId === void 0 ? {} : { sessionId }
248
- });
249
- }
250
- function socketSubscribedFor(options) {
251
- const { sessionId, attempt } = options;
252
- return JSON.stringify({
253
- kind: "subscribed",
254
- sessionId,
255
- ...attempt === void 0 ? {} : { attempt }
256
- });
257
- }
258
- /** The subscription-over notice: with a `reason` the server rejected
259
- * or lost the session's stream, without one it ended cleanly. */
260
- function socketUnsubscribedFor(options) {
261
- const { sessionId, attempt, reason, error } = options;
262
- return JSON.stringify({
263
- kind: "unsubscribed",
264
- sessionId,
265
- ...attempt === void 0 ? {} : { attempt },
266
- ...reason === void 0 ? {} : { reason },
267
- ...error === void 0 ? {} : errorToWire(error)
268
- });
269
- }
270
- //#endregion
271
- //#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/server-DX7mM6nm.js
272
- /**
273
- * The push envelope's trust boundary for `{ sessionId, events, presence? }`,
274
- * shared verbatim by the HTTP
275
- * POST lane and the socket's push/presence frames so INVALID_PAYLOAD
276
- * shapes are one implementation. Internal module, not public API.
277
- */
278
- const invalidPushBody = (message) => new A2Error("INVALID_PAYLOAD", `malformed push body: ${message}`);
279
- const invalid = invalidPushBody;
280
- function parsePresenceSibling(value) {
281
- if (value === void 0) return void 0;
282
- if (value === null || typeof value !== "object" || Array.isArray(value)) throw invalid("presence must be an object when present");
283
- const { participant, values, seen, at } = value;
284
- if (typeof participant !== "string" || participant.length === 0) throw invalid("presence.participant must be a non-empty string");
285
- if (RESERVED_PARTICIPANT_IDS.has(participant)) throw invalid(`presence.participant must not be '${participant}'`);
286
- if (values === null || typeof values !== "object" || Array.isArray(values)) throw invalid("presence.values must be an object");
287
- if (seen !== void 0 && (typeof seen !== "number" || !Number.isFinite(seen) || seen < 0)) throw invalid("presence.seen must be a non-negative number when present");
288
- if (at !== void 0 && (typeof at !== "number" || !Number.isFinite(at) || at < 0 || at > 864e13)) throw invalid("presence.at must be a non-negative epoch-milliseconds timestamp within the Date range when present");
289
- const out = {
290
- participant,
291
- values
292
- };
293
- if (seen !== void 0) out.seen = seen;
294
- if (at !== void 0) out.at = at;
295
- return out;
296
- }
297
- /** The longest event id a push may carry: ids are indexed, and Postgres's index rows have a limit. */
298
- const MAX_PUSHED_ID = 256;
299
- /** A UUIDv5, the shape of the ids A2 derives (deterministic-id.ts). */
300
- const DERIVED_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
301
- /** The events half of the envelope, shared by the POST body and socket
302
- * `push` frames so INVALID_PAYLOAD shapes have one implementation. */
303
- function parsePushEvents(events) {
304
- if (!Array.isArray(events) || events.length === 0) throw invalid("events must be a non-empty array");
305
- return events.map((event, i) => {
306
- if (event === null || typeof event !== "object") throw invalid(`events[${i}] must be an object`);
307
- const { type, payload, id } = event;
308
- if (typeof type !== "string" || type.length === 0) throw invalid(`events[${i}].type must be a non-empty string`);
309
- if (id !== void 0 && typeof id !== "string") throw invalid(`events[${i}].id must be a string when present`);
310
- if (id !== void 0 && (id.length === 0 || id.length > MAX_PUSHED_ID)) throw invalid(`events[${i}].id must be 1-${MAX_PUSHED_ID} characters when present`);
311
- if (id !== void 0 && DERIVED_ID.test(id)) throw invalid(`events[${i}].id is shaped like the ids A2 derives for consumers (a UUIDv5); use crypto.randomUUID() or idempotentId()`);
312
- const out = {
313
- type,
314
- payload
315
- };
316
- if (id !== void 0) out.id = id;
317
- return out;
318
- });
319
- }
320
- /**
321
- * Validate the push envelope — `{ sessionId, events, presence? }` —
322
- * throwing `INVALID_PAYLOAD` on a malformed body. Payload validation
323
- * against the machine's schemas happens in `append` and `setPresence`,
324
- * not here. Either plane may appear alone: a presence-only push has no
325
- * (or empty) `events`.
326
- */
327
- async function parsePushBody(req) {
328
- let body;
329
- try {
330
- body = await req.json();
331
- } catch (cause) {
332
- throw new A2Error("INVALID_PAYLOAD", "push body is not valid JSON", { cause });
333
- }
334
- if (body === null || typeof body !== "object") throw invalid("expected an object");
335
- const { sessionId, events, presence } = body;
336
- if (typeof sessionId !== "string" || sessionId.length === 0) throw invalid("sessionId must be a non-empty string");
337
- const parsedPresence = parsePresenceSibling(presence);
338
- if (parsedPresence !== void 0 && (events === void 0 || Array.isArray(events) && events.length === 0)) return {
339
- sessionId,
340
- events: [],
341
- presence: parsedPresence
342
- };
343
- const parsed = parsePushEvents(events);
344
- return parsedPresence !== void 0 ? {
345
- sessionId,
346
- events: parsed,
347
- presence: parsedPresence
348
- } : {
349
- sessionId,
350
- events: parsed
351
- };
352
- }
353
- /**
354
- * The A2 socket protocol's server half (specs/a2-api.md §13): the
355
- * per-socket shell — teardown, backpressure, heartbeat, the malformed
356
- * budget, and the in-flight bound. `sessionSocket` binds one session to
357
- * one socket; `sessionsSocket` is the opt-in multiplexed handler. Only
358
- * `A2Socket`, the structural socket the platform hands over, is public.
359
- */
360
- const messageText = (data) => {
361
- if (typeof data === "string") return data;
362
- if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);
363
- if (ArrayBuffer.isView(data)) return new TextDecoder().decode(data);
364
- if (Array.isArray(data) && data.every(ArrayBuffer.isView)) {
365
- const decoder = new TextDecoder();
366
- let text = "";
367
- for (const part of data) text += decoder.decode(part, { stream: true });
368
- return text + decoder.decode();
369
- }
370
- return null;
371
- };
372
- /**
373
- * How many unparseable or invalid frames a socket may send before it
374
- * is closed (1008): the budget absorbs isolated client bugs without
375
- * letting a broken peer spin the validation path forever. Push frames
376
- * with a usable `req` never count — their failures are answered with
377
- * error acks, exactly like the POST path's 4xx bodies.
378
- */
379
- const MAX_MALFORMED_FRAMES = 5;
380
- function socketShell(socket, release, onFrame, deadlineAt) {
381
- let torn = false;
382
- let malformed = 0;
383
- let heartbeat;
384
- let deadline;
385
- const teardown = () => {
386
- if (torn) return;
387
- torn = true;
388
- if (heartbeat !== void 0) clearInterval(heartbeat);
389
- if (deadline !== void 0) clearTimeout(deadline);
390
- release();
391
- };
392
- const shutdown = (code, reason) => {
393
- if (torn) return;
394
- teardown();
395
- try {
396
- socket.close(code, reason);
397
- } catch {}
398
- };
399
- const send = (data) => {
400
- if (torn) return;
401
- if (typeof socket.bufferedAmount === "number" && socket.bufferedAmount > SOCKET_TIMINGS.disconnectWaterMarkBytes) {
402
- shutdown(1008, "backpressure: peer not reading");
403
- return;
404
- }
405
- try {
406
- socket.send(data);
407
- } catch {
408
- teardown();
409
- }
410
- };
411
- const malformedFrame = (reason) => {
412
- malformed += 1;
413
- if (malformed >= MAX_MALFORMED_FRAMES) shutdown(1008, `too many malformed frames (last: ${reason})`);
414
- };
415
- let inFlight = 0;
416
- const track = (work) => {
417
- inFlight += 1;
418
- work.finally(() => {
419
- inFlight -= 1;
420
- });
421
- };
422
- const handleMessage = (data) => {
423
- if (torn) return;
424
- const text = messageText(data);
425
- if (text === null) {
426
- malformedFrame("non-text frame");
427
- return;
428
- }
429
- let parsed;
430
- try {
431
- parsed = JSON.parse(text);
432
- } catch {
433
- malformedFrame("frame is not valid JSON");
434
- return;
435
- }
436
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
437
- malformedFrame("frame is not an object");
438
- return;
439
- }
440
- onFrame(parsed);
441
- };
442
- socket.on("message", handleMessage);
443
- socket.on("close", teardown);
444
- socket.on("error", teardown);
445
- heartbeat = setInterval(() => send(SOCKET_PING_FRAME), STREAM_TIMINGS.sseHeartbeatMs);
446
- heartbeat.unref?.();
447
- if (deadlineAt !== void 0) {
448
- deadline = setTimeout(() => shutdown(1e3, "deadline"), Math.max(0, deadlineAt - Date.now()));
449
- deadline.unref?.();
450
- }
451
- return {
452
- torn: () => torn,
453
- send,
454
- shutdown,
455
- malformedFrame,
456
- buffered: () => typeof socket.bufferedAmount === "number" ? socket.bufferedAmount : 0,
457
- overCap: () => inFlight >= SOCKET_TIMINGS.maxInFlightMessages,
458
- track
459
- };
460
- }
461
- const socketSubscription = (options) => {
462
- const { target, startAfter, presence, attempt } = options;
463
- return {
464
- target,
465
- iterator: (presence ? target.stream({
466
- startAfter,
467
- presence: true
468
- }) : target.stream({ startAfter }))[Symbol.asyncIterator](),
469
- stopped: false,
470
- ...attempt === void 0 ? {} : { attempt }
471
- };
472
- };
473
- const stopSubscription = (subscription) => {
474
- subscription.stopped = true;
475
- subscription.iterator.return?.()?.catch(() => {});
476
- };
477
- /**
478
- * Sends a subscription's items until it ends. With `batch`, an event and
479
- * the events its iterator already holds go out as one frame.
480
- */
481
- const pumpSubscription = async (options) => {
482
- const { shell, subscription, frameFor, batch } = options;
483
- for (;;) {
484
- while (!shell.torn() && !subscription.stopped && shell.buffered() > SOCKET_TIMINGS.highWaterMarkBytes) await new Promise((wake) => setTimeout(wake, SOCKET_TIMINGS.resumePollMs));
485
- if (shell.torn() || subscription.stopped) return;
486
- const { value, done } = await subscription.iterator.next();
487
- if (shell.torn() || subscription.stopped || done) return;
488
- if (!batch || !isStreamEvent(value)) {
489
- shell.send(frameFor(value));
490
- continue;
491
- }
492
- const { events } = heldEventBatch({
493
- first: value,
494
- iterator: subscription.iterator,
495
- encode: compactEventJson
496
- });
497
- shell.send(batch(events));
498
- }
499
- };
500
- const handleSocketPush = async (shell, target, sessionId, frame, req, ackSessionId, gatePush, activate) => {
501
- try {
502
- const events = parsePushEvents(frame["events"]);
503
- const denial = await gatePush?.(sessionId, events, void 0) ?? null;
504
- if (denial !== null) {
505
- shell.send(socketErrorAckFor(req, denial, ackSessionId));
506
- return;
507
- }
508
- activate();
509
- const appended = await target.append(...events);
510
- activate();
511
- shell.send(socketAckFor(req, appended, ackSessionId));
512
- } catch (error) {
513
- shell.send(socketErrorAckFor(req, asA2Error(error), ackSessionId));
514
- }
515
- };
516
- const applySocketPresence = async (shell, target, sessionId, frame, gatePush) => {
517
- if (typeof target.setPresence !== "function") {
518
- shell.malformedFrame("presence frame on a presence-less session");
519
- return;
520
- }
521
- let patch;
522
- try {
523
- patch = parsePresenceSibling(frame);
524
- } catch {
525
- shell.malformedFrame("invalid presence frame");
526
- return;
527
- }
528
- if (!patch) return;
529
- try {
530
- if ((await gatePush?.(sessionId, [], patch) ?? null) !== null) return;
531
- await target.setPresence(patch);
532
- } catch (error) {
533
- const failure = asA2Error(error);
534
- if (failure.code === "INVALID_PAYLOAD" || failure.code === "UNKNOWN_PRESENCE_FIELD") {
535
- shell.malformedFrame("invalid presence frame");
536
- return;
537
- }
538
- shell.shutdown(1011, "internal error");
539
- }
540
- };
541
- function sessionSocket(sessionId, session, socket, options) {
542
- const target = session;
543
- const subscription = socketSubscription({
544
- target,
545
- startAfter: options?.startAfter ?? 0,
546
- presence: options?.presence === true
547
- });
548
- const handleFrame = (frame) => {
549
- switch (frame["kind"]) {
550
- case "push": {
551
- const req = frame["req"];
552
- if (typeof req !== "number") {
553
- shell.malformedFrame("push frame without a numeric req");
554
- return;
555
- }
556
- if (frame["sessionId"] !== void 0) {
557
- shell.send(socketErrorAckFor(req, new A2Error("INVALID_PAYLOAD", "sessionId is not allowed on a single-session socket")));
558
- return;
559
- }
560
- if (shell.overCap()) {
561
- shell.send(socketErrorAckFor(req, new A2Error("STORE_UNAVAILABLE", "push shed: too many in flight on this socket")));
562
- return;
563
- }
564
- shell.track(handleSocketPush(shell, target, sessionId, frame, req, void 0, options?.gatePush, () => streamActivities.get(subscription.iterator)?.activate()));
565
- return;
566
- }
567
- case "presence":
568
- if (frame["sessionId"] !== void 0) {
569
- shell.malformedFrame("sessionId is not allowed on a single-session socket");
570
- return;
571
- }
572
- if (!shell.overCap()) shell.track(applySocketPresence(shell, target, sessionId, frame, options?.gatePush));
573
- return;
574
- default: return;
575
- }
576
- };
577
- const shell = socketShell(socket, () => stopSubscription(subscription), handleFrame, options?.deadline);
578
- pumpSubscription({
579
- shell,
580
- subscription,
581
- frameFor: socketFrameFor,
582
- ...options?.wire === 2 ? { batch: (events) => socketEventsFor(events) } : {}
583
- }).then(() => shell.shutdown(1e3), () => shell.shutdown(1011, "stream failed"));
584
- }
585
- const parseSubscribeEntries = (value) => {
586
- if (!Array.isArray(value) || value.length === 0) return null;
587
- const entries = [];
588
- for (const entry of value) {
589
- if (entry === null || typeof entry !== "object") return null;
590
- const { id, attempt, index, bootstrap, reducer } = entry;
591
- if (typeof id !== "string" || id.length === 0) return null;
592
- if (attempt !== void 0 && (typeof attempt !== "number" || !Number.isSafeInteger(attempt) || attempt < 0)) return null;
593
- if (reducer !== void 0 && (typeof reducer !== "string" || reducer.length === 0)) return null;
594
- const lane = {
595
- id,
596
- ...attempt === void 0 ? {} : { attempt }
597
- };
598
- if (bootstrap === true) {
599
- if (index !== void 0 || typeof reducer !== "string") return null;
600
- entries.push({
601
- ...lane,
602
- bootstrap: true,
603
- reducer
604
- });
605
- } else {
606
- if (bootstrap !== void 0 || typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) return null;
607
- entries.push({
608
- ...lane,
609
- index,
610
- ...reducer === void 0 ? {} : { reducer }
611
- });
612
- }
613
- }
614
- return entries;
615
- };
616
- /**
617
- * Speak the multiplexed A2 socket protocol (specs/a2-api.md §13)
618
- * against many sessions on one socket. `subscribe` frames open a
619
- * per-session pump at that session's own resume frontier; push and
620
- * presence frames route by `sessionId` through the same validation
621
- * seams as the POST lane; every down frame carries the `sessionId` it
622
- * belongs to. One heartbeat, one
623
- * malformed budget, one in-flight bound, one backpressure gauge — per
624
- * socket, shared by all sessions. A session's stream ending or failing
625
- * answers `unsubscribed` for that session; only the peer, the
626
- * deadline, the malformed budget, or backpressure closes the socket.
627
- */
628
- function sessionsSocket(resolve, socket, options) {
629
- const presence = options?.presence === true;
630
- const subscriptions = /* @__PURE__ */ new Map();
631
- const retire = (id, subscription) => {
632
- if (subscriptions.get(id) === subscription) subscriptions.delete(id);
633
- };
634
- const runSubscription = async (id, subscription) => {
635
- const { attempt } = subscription;
636
- try {
637
- await pumpSubscription({
638
- shell,
639
- subscription,
640
- frameFor: (item) => socketFrameFor(item, id),
641
- ...options?.wire === 2 ? { batch: (events) => socketEventsFor(events, id) } : {}
642
- });
643
- if (shell.torn() || subscription.stopped) return;
644
- retire(id, subscription);
645
- shell.send(socketUnsubscribedFor({
646
- sessionId: id,
647
- attempt
648
- }));
649
- } catch (error) {
650
- if (shell.torn() || subscription.stopped) return;
651
- retire(id, subscription);
652
- shell.send(socketUnsubscribedFor({
653
- sessionId: id,
654
- attempt,
655
- reason: "stream failed",
656
- error: asA2Error(error)
657
- }));
658
- }
659
- };
660
- const startSubscription = async (entry) => {
661
- const { id, attempt } = entry;
662
- const index = entry.index ?? 0;
663
- const existing = subscriptions.get(id);
664
- if (existing) {
665
- stopSubscription(existing);
666
- subscriptions.delete(id);
667
- }
668
- let session;
669
- try {
670
- session = await resolve(id, index, entry);
671
- } catch (error) {
672
- if (!shell.torn()) shell.send(socketUnsubscribedFor({
673
- sessionId: id,
674
- attempt,
675
- reason: "stream failed",
676
- error: asA2Error(error)
677
- }));
678
- return;
679
- }
680
- if (shell.torn()) return;
681
- if (session === null) {
682
- shell.send(socketUnsubscribedFor({
683
- sessionId: id,
684
- attempt,
685
- reason: "subscribe rejected",
686
- error: new A2Error("FORBIDDEN", "the subscription is not authorized")
687
- }));
688
- return;
689
- }
690
- const subscription = socketSubscription({
691
- target: session,
692
- startAfter: index,
693
- presence,
694
- attempt
695
- });
696
- subscriptions.set(id, subscription);
697
- shell.send(socketSubscribedFor({
698
- sessionId: id,
699
- attempt
700
- }));
701
- runSubscription(id, subscription);
702
- };
703
- let controlTail = Promise.resolve();
704
- const control = (work) => {
705
- controlTail = controlTail.then(work).catch(() => {});
706
- };
707
- const handlePush = async (frame, req, sessionId) => {
708
- const subscription = subscriptions.get(sessionId);
709
- if (subscription === void 0) {
710
- shell.send(socketErrorAckFor(req, new A2Error("STORE_UNAVAILABLE", "session is not subscribed on this socket"), sessionId));
711
- return;
712
- }
713
- await handleSocketPush(shell, subscription.target, sessionId, frame, req, sessionId, options?.gatePush, () => {
714
- const current = subscriptions.get(sessionId);
715
- if (current) streamActivities.get(current.iterator)?.activate();
716
- });
717
- };
718
- const handlePresence = async (frame, sessionId) => {
719
- const subscription = subscriptions.get(sessionId);
720
- if (subscription === void 0) return;
721
- await applySocketPresence(shell, subscription.target, sessionId, frame, options?.gatePush);
722
- };
723
- const handleFrame = (frame) => {
724
- switch (frame["kind"]) {
725
- case "subscribe": {
726
- const entries = parseSubscribeEntries(frame["sessions"]);
727
- if (entries === null) {
728
- shell.malformedFrame("malformed subscribe frame");
729
- return;
730
- }
731
- for (const entry of entries) control(() => startSubscription(entry));
732
- return;
733
- }
734
- case "unsubscribe": {
735
- const ids = frame["sessions"];
736
- if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === "string")) {
737
- shell.malformedFrame("malformed unsubscribe frame");
738
- return;
739
- }
740
- for (const id of ids) control(() => {
741
- const subscription = subscriptions.get(id);
742
- if (subscription === void 0) return;
743
- stopSubscription(subscription);
744
- subscriptions.delete(id);
745
- });
746
- return;
747
- }
748
- case "push": {
749
- const req = frame["req"];
750
- const sessionId = frame["sessionId"];
751
- if (shell.overCap()) {
752
- if (typeof req === "number") shell.send(socketErrorAckFor(req, new A2Error("STORE_UNAVAILABLE", "push shed: too many in flight on this socket"), typeof sessionId === "string" ? sessionId : void 0));
753
- else shell.malformedFrame("push frame without a numeric req");
754
- return;
755
- }
756
- if (typeof req !== "number") {
757
- shell.malformedFrame("push frame without a numeric req");
758
- return;
759
- }
760
- if (typeof sessionId !== "string" || sessionId.length === 0) {
761
- shell.send(socketErrorAckFor(req, new A2Error("INVALID_PAYLOAD", "push frame without a sessionId")));
762
- return;
763
- }
764
- shell.track(handlePush(frame, req, sessionId));
765
- return;
766
- }
767
- case "presence": {
768
- if (shell.overCap()) return;
769
- const sessionId = frame["sessionId"];
770
- if (typeof sessionId !== "string" || sessionId.length === 0) {
771
- shell.malformedFrame("presence frame without a sessionId");
772
- return;
773
- }
774
- shell.track(handlePresence(frame, sessionId));
775
- return;
776
- }
777
- default: return;
778
- }
779
- };
780
- const shell = socketShell(socket, () => {
781
- for (const subscription of subscriptions.values()) stopSubscription(subscription);
782
- subscriptions.clear();
783
- }, (frame) => handleFrame(frame), options?.deadline);
784
- }
785
- /**
786
- * The SSE response protocol — framing, heartbeat, deadline, and
787
- * teardown for the live stream lane. Internal module: `server.fetch` is
788
- * the sanctioned caller; the framing rules stay
789
- * documented on `sseResponse` because the client's parser (and the
790
- * stall watchdog) depend on them.
791
- */
792
- /**
793
- * Pipe a live event iterable into an SSE `Response`. Each event is one
794
- * frame — `id:` carries the event-log index, `data:` the JSON event.
795
- * Frames for events the iterable already holds are written together. With
796
- * `wire: 2` those events share one frame instead: `data:` is a JSON array of
797
- * `CompactWireEvent`s and `id:` the last one's index. A
798
- * `stream({ presence: true })` iterable also yields presence items,
799
- * which ride as named frames old clients skip: `event:
800
- * presence-snapshot` first (the map, ISO dates), then `event: presence`
801
- * per patch — no `id:`, presence never advances the resume frontier. A
802
- * disconnecting client cancels the stream, which closes the underlying
803
- * subscription. Two kinds of comment frames ride along: a `: connected`
804
- * prelude that flushes headers immediately, and a `: ping` heartbeat
805
- * every 15 seconds so clients (and proxies) can tell a quiet stream
806
- * from a dead connection — the session client's stall watchdog counts
807
- * on it. When the platform exposes an invocation deadline, the response
808
- * closes cleanly one second before it so the client reconnects without
809
- * a platform-timeout failure.
810
- */
811
- function sseResponse(iterable, options = {}) {
812
- const write = options.wire === 2 ? batchedFrames : eventFrames;
813
- const iterator = iterable[Symbol.asyncIterator]();
814
- const encoder = new TextEncoder();
815
- let heartbeat;
816
- let deadlineTimer;
817
- let closed = false;
818
- let iteratorReturned = false;
819
- let stopActivity;
820
- const stopTimers = () => {
821
- stopActivity?.();
822
- stopActivity = void 0;
823
- if (heartbeat !== void 0) clearInterval(heartbeat);
824
- if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
825
- heartbeat = void 0;
826
- deadlineTimer = void 0;
827
- };
828
- const returnIterator = async () => {
829
- if (iteratorReturned) return;
830
- iteratorReturned = true;
831
- await iterator.return?.();
832
- };
833
- const stream = new ReadableStream({
834
- start(controller) {
835
- controller.enqueue(encoder.encode(": connected\n\n"));
836
- const activity = streamActivities.get(iterator);
837
- if (activity) {
838
- const announce = (idle) => {
839
- if (closed) return;
840
- controller.enqueue(encoder.encode(`event: a2-activity\ndata: ${idle ? "idle" : "active"}\n\n`));
841
- };
842
- stopActivity = activity.subscribe(announce);
843
- if (activity.idle) announce(true);
844
- }
845
- heartbeat = setInterval(() => {
846
- try {
847
- controller.enqueue(encoder.encode(": ping\n\n"));
848
- } catch {
849
- stopTimers();
850
- }
851
- }, STREAM_TIMINGS.sseHeartbeatMs);
852
- heartbeat.unref?.();
853
- const invocationDeadline = invocationDeadlineMs();
854
- if (invocationDeadline !== null) {
855
- const delay = Math.max(0, invocationDeadline - Date.now() - STREAM_TIMINGS.sseDeadlineGraceMs);
856
- deadlineTimer = setTimeout(() => {
857
- if (closed) return;
858
- closed = true;
859
- stopTimers();
860
- returnIterator().catch(() => {});
861
- try {
862
- controller.close();
863
- } catch {}
864
- }, delay);
865
- deadlineTimer.unref?.();
866
- }
867
- },
868
- async pull(controller) {
869
- try {
870
- const { value, done } = await iterator.next();
871
- if (closed) return;
872
- if (done) {
873
- closed = true;
874
- stopTimers();
875
- controller.close();
876
- return;
877
- }
878
- controller.enqueue(encoder.encode(write(value, iterator)));
879
- } catch (error) {
880
- if (closed) return;
881
- closed = true;
882
- stopTimers();
883
- returnIterator().catch(() => {});
884
- throw error;
885
- }
886
- },
887
- async cancel() {
888
- if (closed) return;
889
- closed = true;
890
- stopTimers();
891
- await returnIterator();
892
- }
893
- });
894
- return new Response(stream, {
895
- status: 200,
896
- headers: {
897
- "content-type": "text/event-stream",
898
- "cache-control": "no-cache, no-transform",
899
- connection: "keep-alive"
900
- }
901
- });
902
- }
903
- /** Version 1: one frame per event, then each event the iterator holds. */
904
- function eventFrames(first, iterator) {
905
- let frames = frameFor(first);
906
- while (frames.length < EVENT_WRITE_CHARS) {
907
- const event = takeBuffered(iterator);
908
- if (!event) break;
909
- frames += frameFor(event);
910
- }
911
- return frames;
912
- }
913
- /**
914
- * Version 2: events this write carries share one frame, a JSON array whose
915
- * `id:` is its last index. Held events are always events, so only `first`
916
- * can be a snapshot or presence frame.
917
- */
918
- function batchedFrames(first, iterator) {
919
- const lead = isStreamEvent(first) ? "" : frameFor(first);
920
- const head = isStreamEvent(first) ? first : takeBuffered(iterator);
921
- if (!head) return lead;
922
- const { events, last } = heldEventBatch({
923
- first: head,
924
- iterator,
925
- encode: compactJsonLine
926
- });
927
- return `${lead}id: ${last.index}\ndata: [${events.join(",")}]\n\n`;
928
- }
929
- const compactJsonLine = (event) => isSerializedEvent(event) && /[\r\n]/.test(event.payloadJson) ? compactEventJson(parseSerializedEvent(event)) : compactEventJson(event);
930
- function frameFor(item) {
931
- if ("kind" in item) return `event: a2-snapshot\ndata: ${JSON.stringify(stateSnapshotToWire(item))}\n\n`;
932
- if ("snapshot" in item) return `event: presence-snapshot\ndata: ${JSON.stringify(presenceSnapshotToWire(item))}\n\n`;
933
- if ("participant" in item) return `event: presence\ndata: ${JSON.stringify(presencePatchToWire(item))}\n\n`;
934
- if (isSerializedEvent(item)) return /[\r\n]/.test(item.payloadJson) ? `id: ${item.index}\ndata: ${JSON.stringify(eventToWire(parseSerializedEvent(item)))}\n\n` : `id: ${item.index}\ndata: ${serializedEventToWireJson(item)}\n\n`;
935
- return `id: ${item.index}\ndata: ${JSON.stringify(eventToWire(item))}\n\n`;
936
- }
937
- function bootstrapStream(options) {
938
- return { [Symbol.asyncIterator]() {
939
- let closed = false;
940
- let index;
941
- let source;
942
- let stopActivity;
943
- const abort = new AbortController();
944
- const activity = createStreamActivity(() => {
945
- if (source) streamActivities.get(source)?.activate();
946
- });
947
- const iterator = {
948
- async next() {
949
- if (closed) return {
950
- done: true,
951
- value: void 0
952
- };
953
- if (index === void 0) {
954
- let cancel;
955
- const cancelled = new Promise((resolve) => {
956
- cancel = () => resolve(void 0);
957
- abort.signal.addEventListener("abort", cancel, { once: true });
958
- });
959
- try {
960
- const snapshot = await Promise.race([options.snapshot(), cancelled]);
961
- if (closed || snapshot === void 0) return {
962
- done: true,
963
- value: void 0
964
- };
965
- index = snapshot.index;
966
- return {
967
- done: false,
968
- value: snapshot
969
- };
970
- } finally {
971
- if (cancel) abort.signal.removeEventListener("abort", cancel);
972
- }
973
- }
974
- if (!source) {
975
- source = options.stream(index)[Symbol.asyncIterator]();
976
- const sourceActivity = streamActivities.get(source);
977
- if (sourceActivity) {
978
- activity.setIdle(sourceActivity.idle);
979
- stopActivity = sourceActivity.subscribe(activity.setIdle);
980
- }
981
- }
982
- const result = await source.next();
983
- return closed ? {
984
- done: true,
985
- value: void 0
986
- } : result;
987
- },
988
- async return() {
989
- if (closed) return {
990
- done: true,
991
- value: void 0
992
- };
993
- closed = true;
994
- abort.abort();
995
- stopActivity?.();
996
- await source?.return?.();
997
- return {
998
- done: true,
999
- value: void 0
1000
- };
1001
- }
1002
- };
1003
- streamActivities.set(iterator, activity);
1004
- bufferedEvents.set(iterator, () => closed || !source ? void 0 : takeBuffered(source));
1005
- return iterator;
1006
- } };
1007
- }
1008
- const serverFetchHooks = /* @__PURE__ */ new WeakMap();
1009
- const parseHistoryBounds = (gte, lte) => {
1010
- if (gte === null || lte === null) throw new A2Error("INVALID_PAYLOAD", "a history read takes both gte and lte");
1011
- const bounds = {
1012
- gte: Number(gte),
1013
- lte: Number(lte)
1014
- };
1015
- for (const [name, value] of Object.entries(bounds)) if (!Number.isSafeInteger(value) || value < 0) throw new A2Error("INVALID_PAYLOAD", `history ${name} must be a non-negative safe integer`);
1016
- if (bounds.gte > bounds.lte) throw new A2Error("INVALID_PAYLOAD", "history gte must be less than or equal to lte");
1017
- return bounds;
1018
- };
1019
- const parseResumeIndex = (raw) => {
1020
- if (raw === null) return 0;
1021
- const index = Number(raw);
1022
- if (!Number.isSafeInteger(index) || index < 0) throw new A2Error("INVALID_PAYLOAD", "stream index must be a non-negative safe integer");
1023
- return index;
1024
- };
1025
- const parseSubscription = (params) => {
1026
- const reducer = params.get("reducer");
1027
- const bootstrap = params.get("bootstrap");
1028
- const index = params.get("index");
1029
- if (reducer === "") throw new A2Error("INVALID_PAYLOAD", "empty reducer name");
1030
- if (bootstrap !== null) {
1031
- if (bootstrap !== "1" || index !== null || reducer === null) throw new A2Error("INVALID_PAYLOAD", "bootstrap requires a reducer and no index");
1032
- return {
1033
- bootstrap: true,
1034
- reducer
1035
- };
1036
- }
1037
- return {
1038
- index: parseResumeIndex(index),
1039
- ...reducer === null ? {} : { reducer }
1040
- };
1041
- };
1042
- const errorResponse = (error) => {
1043
- const a2error = asA2Error(error);
1044
- return Response.json(errorToWire(a2error), { status: errorStatus(a2error.code) });
1045
- };
1046
- const forbidden = () => new A2Error("FORBIDDEN", "the operation is not authorized");
1047
- const freezePush = (sessionId, events, presence, transport) => {
1048
- for (const event of events) Object.freeze(event);
1049
- Object.freeze(events);
1050
- if (presence !== void 0) {
1051
- Object.freeze(presence.values);
1052
- Object.freeze(presence);
1053
- }
1054
- return {
1055
- type: "push",
1056
- sessionId,
1057
- events,
1058
- ...presence === void 0 ? {} : { presence },
1059
- transport
1060
- };
1061
- };
1062
- function createServerFetch(server) {
1063
- const presence = Object.keys(server.contract.presence).length > 0;
1064
- const fetch = async (request, options) => {
1065
- const authorized = async (operation) => {
1066
- try {
1067
- return await options?.authorize?.(Object.freeze(operation)) !== false;
1068
- } catch (cause) {
1069
- throw new A2Error("STORE_UNAVAILABLE", "authorization failed", { cause });
1070
- }
1071
- };
1072
- const authorize = async (operation) => {
1073
- if (!await authorized(operation)) throw forbidden();
1074
- };
1075
- const validateIngress = async (context) => {
1076
- await serverFetchHooks.get(fetch)?.validateIngress?.(context);
1077
- };
1078
- const gateSocketPush = async (sessionId, events, pushedPresence) => {
1079
- try {
1080
- await authorize(freezePush(sessionId, events, pushedPresence, "websocket"));
1081
- await validateIngress({
1082
- sessionId,
1083
- events,
1084
- ...pushedPresence === void 0 ? {} : { presence: pushedPresence }
1085
- });
1086
- return null;
1087
- } catch (error) {
1088
- return asA2Error(error);
1089
- }
1090
- };
1091
- const selectedSession = (sessionId, selection) => {
1092
- const reducer = server.contract.reducer;
1093
- if (selection.reducer !== void 0 && reducer !== void 0 && reducer.name !== selection.reducer) throw new A2Error("INVALID_PAYLOAD", "client reducer does not match the public contract reducer");
1094
- const target = server.session(sessionId);
1095
- const streamTarget = target;
1096
- if (!selection.bootstrap) return streamTarget;
1097
- if (!reducer) throw new A2Error("INVALID_PAYLOAD", "contract has no public reducer");
1098
- return {
1099
- ...streamTarget,
1100
- stream: (streamOptions) => bootstrapStream({
1101
- snapshot: async () => {
1102
- const initial = await target.state(reducer);
1103
- return {
1104
- kind: "snapshot",
1105
- sessionId,
1106
- name: reducer.name,
1107
- index: initial.index,
1108
- state: encodeState({
1109
- reducer,
1110
- state: initial.state
1111
- }),
1112
- ...initial.clearIndex === void 0 ? {} : { clearIndex: initial.clearIndex }
1113
- };
1114
- },
1115
- stream: (index) => {
1116
- const bounds = {
1117
- startAfter: index,
1118
- presence: streamOptions.presence === true
1119
- };
1120
- return target.stream(bounds);
1121
- }
1122
- })
1123
- };
1124
- };
1125
- const attachMultiplexed = (wire) => (socket) => {
1126
- const deadline = invocationDeadlineMs();
1127
- sessionsSocket(async (sessionId, startAfter, selection = { index: startAfter }) => {
1128
- const operation = {
1129
- type: "stream",
1130
- sessionId,
1131
- startAfter,
1132
- ...selection.bootstrap ? { bootstrap: true } : {},
1133
- transport: "websocket"
1134
- };
1135
- return await authorized(operation) ? selectedSession(sessionId, selection) : null;
1136
- }, socket, {
1137
- presence,
1138
- wire,
1139
- ...deadline === null ? {} : { deadline },
1140
- gatePush: gateSocketPush
1141
- });
1142
- };
1143
- try {
1144
- if (request.method === "GET") {
1145
- if (request.headers.get("upgrade")?.toLowerCase() === "websocket") {
1146
- if (options?.upgradeWebSocket === void 0) return new Response("WebSocket upgrade requested, but server.fetch() has no upgrade implementation", { status: 426 });
1147
- const { searchParams } = new URL(request.url);
1148
- const wire = wireVersion(searchParams.get("wire"));
1149
- if (options.multiplexWebSocket === true) return await options.upgradeWebSocket(attachMultiplexed(wire));
1150
- const sessionId = searchParams.get("sessionId");
1151
- if (sessionId === null || sessionId.length === 0) throw new A2Error("INVALID_PAYLOAD", "missing sessionId");
1152
- const selection = parseSubscription(searchParams);
1153
- const startAfter = selection.index ?? 0;
1154
- await authorize({
1155
- type: "stream",
1156
- sessionId,
1157
- startAfter,
1158
- ...selection.bootstrap ? { bootstrap: true } : {},
1159
- transport: "websocket"
1160
- });
1161
- const target = selectedSession(sessionId, selection);
1162
- const attach = (socket) => {
1163
- const deadline = invocationDeadlineMs();
1164
- sessionSocket(sessionId, target, socket, {
1165
- startAfter,
1166
- presence,
1167
- wire,
1168
- ...deadline === null ? {} : { deadline },
1169
- gatePush: gateSocketPush
1170
- });
1171
- };
1172
- return await options.upgradeWebSocket(attach);
1173
- }
1174
- const { searchParams } = new URL(request.url);
1175
- const sessionId = searchParams.get("sessionId");
1176
- if (sessionId === null || sessionId.length === 0) throw new A2Error("INVALID_PAYLOAD", "missing sessionId");
1177
- const gteRaw = searchParams.get("gte");
1178
- const lteRaw = searchParams.get("lte");
1179
- if (gteRaw !== null || lteRaw !== null) {
1180
- const bounds = parseHistoryBounds(gteRaw, lteRaw);
1181
- await authorize({
1182
- type: "history",
1183
- sessionId,
1184
- ...bounds,
1185
- transport: "http"
1186
- });
1187
- const { events, clearIndex } = await server.historyPage(sessionId, bounds);
1188
- const first = Math.max(bounds.gte, (clearIndex ?? 0) + 1);
1189
- const covered = events.length === Math.max(0, bounds.lte - first + 1);
1190
- return Response.json(events.map(eventToWire), { headers: {
1191
- "a2-history-covered": String(covered),
1192
- ...clearIndex === void 0 ? {} : { "a2-clear-index": String(clearIndex) }
1193
- } });
1194
- }
1195
- const selection = parseSubscription(searchParams);
1196
- const startAfter = selection.index ?? 0;
1197
- await authorize({
1198
- type: "stream",
1199
- sessionId,
1200
- startAfter,
1201
- ...selection.bootstrap ? { bootstrap: true } : {},
1202
- transport: "http"
1203
- });
1204
- const target = selectedSession(sessionId, selection);
1205
- return sseResponse(presence ? target.stream({
1206
- startAfter,
1207
- presence: true
1208
- }) : target.stream({ startAfter }), { wire: wireVersion(searchParams.get("wire")) });
1209
- }
1210
- if (request.method === "POST") {
1211
- const body = await parsePushBody(request);
1212
- await authorize(freezePush(body.sessionId, body.events, body.presence, "http"));
1213
- await validateIngress({
1214
- sessionId: body.sessionId,
1215
- events: body.events,
1216
- ...body.presence === void 0 ? {} : { presence: body.presence }
1217
- });
1218
- const session = server.session(body.sessionId);
1219
- if (body.presence !== void 0) {
1220
- const target = session;
1221
- if (typeof target.setPresence !== "function") throw invalidPushBody("presence is not declared by this contract");
1222
- await target.setPresence(body.presence);
1223
- }
1224
- const appended = body.events.length === 0 ? [] : await session.append(...body.events);
1225
- return Response.json(appended.map(eventToWire));
1226
- }
1227
- return new Response("Method Not Allowed", {
1228
- status: 405,
1229
- headers: { allow: "GET, POST" }
1230
- });
1231
- } catch (error) {
1232
- return errorResponse(error);
1233
- }
1234
- };
1235
- return fetch;
1236
- }
1237
- /**
1238
- * Deterministic default ids for consumer `session.append` calls. A consumer
1239
- * re-run after a crash calls `session.append` again; giving
1240
- * each call a deterministic id — derived from the triggering event's id
1241
- * and the caller's stable name — makes the re-run a no-op via the store's
1242
- * per-session unique index on event ids.
1243
- *
1244
- * The id is a UUIDv5-shaped SHA-1 over
1245
- * `(namespace, triggerEventId, name, itemOrdinal)`, computed with
1246
- * WebCrypto so it runs on any platform a2 core targets.
1247
- */
1248
- const APPEND_NAMESPACE = "a2:handler-append:v2";
1249
- const RETURN_NAMESPACE = "a2:handler-return:v1";
1250
- const SCHEDULE_NAMESPACE = "a2:schedule:v1";
1251
- const SCHEDULED_EVENT_NAMESPACE = "a2:scheduled-event:v1";
1252
- const SCHEDULE_CLEAR_NAMESPACE = "a2:schedule-clear:v1";
1253
- async function deterministicIdFromInput(input) {
1254
- const digest = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(input));
1255
- const bytes = new Uint8Array(digest).slice(0, 16);
1256
- bytes[6] = (bytes[6] ?? 0) & 15 | 80;
1257
- bytes[8] = (bytes[8] ?? 0) & 63 | 128;
1258
- const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1259
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
1260
- }
1261
- async function deterministicId(parts) {
1262
- return deterministicIdFromInput(parts.join("\0"));
1263
- }
1264
- /**
1265
- * `consumer` keys the id on the consumer that appends, so two consumers of
1266
- * one event never collide. A2's own consumers pass none: their types are
1267
- * disjoint, so the event alone keys them.
1268
- */
1269
- async function deterministicEventId(triggerEventId, name, itemOrdinal, consumer) {
1270
- if (name.length === 0) throw new TypeError("append name must not be empty");
1271
- return deterministicId([
1272
- APPEND_NAMESPACE,
1273
- triggerEventId,
1274
- name,
1275
- itemOrdinal,
1276
- ...consumer === void 0 ? [] : [consumer]
1277
- ]);
1278
- }
1279
- async function deterministicReturnedEventId(triggerEventId, itemOrdinal, consumer) {
1280
- return deterministicId([
1281
- RETURN_NAMESPACE,
1282
- triggerEventId,
1283
- itemOrdinal,
1284
- ...consumer === void 0 ? [] : [consumer]
1285
- ]);
1286
- }
1287
- /**
1288
- * The id of a scheduled append. `clearIndex` is the lifetime the trigger was
1289
- * claimed in; it joins the input only when positive, so a trigger id reused
1290
- * after a clear schedules a distinct task while sessions never cleared keep
1291
- * the ids they always had.
1292
- */
1293
- async function deterministicScheduleId(contract, sessionId, triggerEventId, name, clearIndex = 0, consumer) {
1294
- return deterministicIdFromInput(JSON.stringify([
1295
- SCHEDULE_NAMESPACE,
1296
- contract,
1297
- sessionId,
1298
- triggerEventId,
1299
- name,
1300
- ...clearIndex > 0 ? [clearIndex] : [],
1301
- ...consumer === void 0 ? [] : [{ consumer }]
1302
- ]));
1303
- }
1304
- async function deterministicScheduleClearId({ contract, sessionId, triggerEventId, clearIndex, name, ifLastIndex, consumer }) {
1305
- return deterministicIdFromInput(JSON.stringify([
1306
- SCHEDULE_CLEAR_NAMESPACE,
1307
- contract,
1308
- sessionId,
1309
- triggerEventId,
1310
- clearIndex,
1311
- name,
1312
- ifLastIndex,
1313
- ...consumer === void 0 ? [] : [{ consumer }]
1314
- ]));
1315
- }
1316
- async function deterministicScheduledEventId(scheduleId, itemOrdinal) {
1317
- return deterministicId([
1318
- SCHEDULED_EVENT_NAMESPACE,
1319
- scheduleId,
1320
- itemOrdinal
1321
- ]);
1322
- }
1323
- /**
1324
- * The default when no telemetry is configured. Spans cost nothing, but
1325
- * `recordError` prints: it only ever receives errors a2 swallows by
1326
- * design, so without a configured sink the console is the one place
1327
- * they can surface. Passing `telemetry` replaces this sink wholesale.
1328
- */
1329
- const CONSOLE_TELEMETRY = { span: (name, attributes, fn) => fn({
1330
- setAttribute: () => {},
1331
- recordError: (error) => {
1332
- console.error(`[a2] error in ${name}`, attributes, error);
1333
- }
1334
- }) };
1335
- /**
1336
- * Deliver one authenticated scheduler append through an A2 server's ordinary
1337
- * top-level append path. Custom scheduler adapters call this after validating
1338
- * their transport envelope; application code normally uses `session.schedule`.
1339
- */
1340
- async function deliverSchedulerAppend(server, task) {
1341
- if (server.contract.name !== task.contract) throw new TypeError(`a2 scheduler: append task for contract '${task.contract}' cannot be delivered to '${server.contract.name}'`);
1342
- const { originIndex } = task;
1343
- if (originIndex !== void 0 && (!Number.isSafeInteger(originIndex) || originIndex < 1)) throw new TypeError("a2 scheduler: append task originIndex must be a positive safe integer");
1344
- const internals = serverInternals.get(server);
1345
- if (!internals) throw new TypeError(`a2 scheduler: server for contract '${task.contract}' cannot receive scheduled appends`);
1346
- await internals.schedulerAppend(task.sessionId, task.events, originIndex);
1347
- }
1348
- /**
1349
- * Deliver one authenticated scheduler clear: a conditional
1350
- * `clear({ ifLastIndex })` that resolves after its deletion finishes, so a
1351
- * provider retry resumes an interrupted deletion. Custom scheduler adapters
1352
- * call this after validating their transport envelope; application code uses
1353
- * `session.schedule.clear`.
1354
- */
1355
- async function deliverSchedulerClear(server, task) {
1356
- if (server.contract.name !== task.contract) throw new TypeError(`a2 scheduler: clear task for contract '${task.contract}' cannot be delivered to '${server.contract.name}'`);
1357
- if (task.kind !== "clear" || !Number.isSafeInteger(task.ifLastIndex) || task.ifLastIndex < 0) throw new TypeError("a2 scheduler: a clear task needs kind \"clear\" and a non-negative safe integer ifLastIndex");
1358
- const internals = serverInternals.get(server);
1359
- if (!internals) throw new TypeError(`a2 scheduler: server for contract '${task.contract}' cannot receive scheduled clears`);
1360
- await internals.schedulerClear(task.sessionId, task.ifLastIndex);
1361
- }
1362
- const CONSUMER_NAME = /^[a-z0-9][a-z0-9._:-]{0,127}$/i;
1363
- /** Define a consumer: a named reader of each session's log. */
1364
- function consumer(options) {
1365
- return defineConsumer(options, false);
1366
- }
1367
- /**
1368
- * `consumer()`, and for A2's own runtimes (`runtime`) a name under `a2.` and
1369
- * child ids without the name: their types are disjoint, so the event alone
1370
- * keys them, and regrouping A2's consumers never changes an id.
1371
- */
1372
- function defineConsumer(options, runtime) {
1373
- const contract = options?.contract;
1374
- if (!contract || typeof contract.name !== "string") throw new TypeError("consumer expects options with a contract");
1375
- const consumerName = options.name;
1376
- if (typeof consumerName !== "string" || !CONSUMER_NAME.test(consumerName)) throw new TypeError("consumer name must be 1-128 letters, digits, and . _ : - characters");
1377
- if (consumerName.startsWith("a2.") !== runtime) throw new TypeError(runtime ? `A2's own consumers are named under 'a2.'` : `consumer names starting with 'a2.' are reserved`);
1378
- const types = options.types === void 0 ? null : [...options.types];
1379
- if (types?.length === 0) throw new TypeError(`consumer '${consumerName}' lists no types; leave types out to take every type`);
1380
- for (const type of types ?? []) if (!Object.hasOwn(contract.events, type)) throw new TypeError(`contract '${contract.name}' has no event type '${String(type)}'`);
1381
- const lane = options.lane ?? null;
1382
- if (lane !== null && typeof lane !== "function" && (typeof lane !== "string" || lane.length === 0)) throw new TypeError(`lane for consumer '${consumerName}' must be a non-empty string or a function`);
1383
- const backfill = options.backfill ?? false;
1384
- if (backfill && typeof lane !== "string") throw new TypeError(`consumer '${consumerName}' backfills, so its lane must be a string`);
1385
- if (backfill && options.abortOn !== void 0) throw new TypeError(`consumer '${consumerName}' backfills, so it can't use abortOn`);
1386
- return { run(fn) {
1387
- if (typeof fn !== "function") throw new TypeError(`consumer '${consumerName}' needs a run function`);
1388
- const defined = {
1389
- name: consumerName,
1390
- contract: { name: contract.name },
1391
- spec: {
1392
- types,
1393
- lane,
1394
- backfill,
1395
- abortOn: options.abortOn ?? null,
1396
- run: fn
1397
- }
1398
- };
1399
- if (runtime) runtimeConsumers.add(defined);
1400
- return defined;
1401
- } };
1402
- }
1403
- runtimeConsumerFactory.define = (options) => defineConsumer(options, true);
1404
- /** A registered consumer as the store needs to know it. */
1405
- const storeConsumerOf = (registered) => registered.log ? {
1406
- name: registered.name,
1407
- log: registered.log
1408
- } : { name: registered.name };
1409
- const MAX_FAILURES = 10;
1410
- /** How long `consume` waits before looking again at a head it can't run. */
1411
- const CONSUME_WAIT_MIN_MS = 25;
1412
- const CONSUME_WAIT_MAX_MS = 1e3;
1413
- /**
1414
- * `task`, or a rejection with `signal`'s reason once it aborts. The task runs
1415
- * on either way, and its own failure is caught, so nothing goes unhandled.
1416
- */
1417
- const untilAborted = (task, signal) => {
1418
- if (!signal) return task;
1419
- task.catch(() => {});
1420
- if (signal.aborted) return Promise.reject(signal.reason);
1421
- return new Promise((resolve, reject) => {
1422
- const abort = () => reject(signal.reason);
1423
- signal.addEventListener("abort", abort, { once: true });
1424
- task.then(resolve, reject).finally(() => {
1425
- signal.removeEventListener("abort", abort);
1426
- });
1427
- });
1428
- };
1429
- /** How long an event waits after its `failureCount`th failed attempt. */
1430
- const failureRetryDelayMs = (failureCount) => Math.min(DRAIN_TIMINGS.failureRetryBaseMs * 2 ** Math.max(failureCount - 1, 0), DRAIN_TIMINGS.failureRetryMaxMs);
1431
- /** Abort a lost attempt's consumer and release its drain slot. */
1432
- function endSuperseded(entry, message) {
1433
- entry.supersede.abort(new A2Error("SUPERSEDED_ATTEMPT", message));
1434
- entry.fence({
1435
- status: "superseded",
1436
- opensLane: false,
1437
- appendsEvents: false
1438
- });
1439
- }
1440
- /** Pause between clear-deletion batches that found only locked rows. */
1441
- const RECLAIM_STALL_MS = 20;
1442
- const RECLAIM_STALL_LIMIT = 50;
1443
- /** Default: how long a presence value survives without a refreshing set. */
1444
- const PRESENCE_TTL_MS = 6e4;
1445
- function createDrainSignal() {
1446
- const listeners = /* @__PURE__ */ new Set();
1447
- return {
1448
- version: 0,
1449
- closed: false,
1450
- notify() {
1451
- this.version += 1;
1452
- for (const listener of listeners) listener();
1453
- listeners.clear();
1454
- },
1455
- wait(version) {
1456
- if (this.version !== version) return {
1457
- promise: Promise.resolve(),
1458
- cancel: () => {}
1459
- };
1460
- let resolve;
1461
- const promise = new Promise((done) => {
1462
- resolve = done;
1463
- });
1464
- listeners.add(resolve);
1465
- return {
1466
- promise,
1467
- cancel: () => listeners.delete(resolve)
1468
- };
1469
- }
1470
- };
1471
- }
1472
- function dispatchAbortEvent(hub, event) {
1473
- let relevant = false;
1474
- for (const subscription of hub.subscriptions) {
1475
- if (!subscription.types.has(event.type)) continue;
1476
- relevant = true;
1477
- if (subscription.matches(event)) subscription.controller.abort();
1478
- }
1479
- if (relevant) hub.seen.set(event.index, event);
1480
- }
1481
- function pruneAbortHub(hub) {
1482
- let minimum = Infinity;
1483
- const types = /* @__PURE__ */ new Set();
1484
- for (const subscription of hub.subscriptions) {
1485
- minimum = Math.min(minimum, subscription.triggerIndex);
1486
- for (const type of subscription.types) types.add(type);
1487
- }
1488
- for (const [index, event] of hub.seen) if (index <= minimum || !types.has(event.type)) hub.seen.delete(index);
1489
- }
1490
- /**
1491
- * Deadlines tighten the claim/watchdog window, and a passed deadline ends
1492
- * claiming: a claim then could not run, only lapse and be claimed again until
1493
- * the platform ends the process. A platform timeout otherwise follows the
1494
- * same path as any other process death: the in-flight event remains pending
1495
- * and a fresh invocation retries it.
1496
- */
1497
- function nextClaimWindow() {
1498
- const nowMs = Date.now();
1499
- const deadlineMs = invocationDeadlineMs();
1500
- const deadlineTtlMs = deadlineMs === null ? DRAIN_TIMINGS.claimTtlMs : deadlineMs - nowMs;
1501
- const deadlineCapped = deadlineMs !== null && deadlineTtlMs <= DRAIN_TIMINGS.claimTtlMs;
1502
- const ttlMs = Math.max(1, Math.min(DRAIN_TIMINGS.claimTtlMs, deadlineTtlMs));
1503
- const expiresAtMs = nowMs + ttlMs;
1504
- return {
1505
- ttlMs,
1506
- expiresAtMs,
1507
- watchdogAtMs: expiresAtMs + DRAIN_TIMINGS.watchdogGraceMs,
1508
- deadlineCapped,
1509
- pastDeadline: deadlineMs !== null && deadlineTtlMs <= 0
1510
- };
1511
- }
1512
- function schedulerSlot(dueAt) {
1513
- return Math.ceil(dueAt / 1e3) * 1e3;
1514
- }
1515
- function currentSchedulerSlot(now) {
1516
- return Math.floor(now / 1e3) * 1e3;
1517
- }
1518
- /**
1519
- * The namespace separator between machine name and session id in
1520
- * storage. Machines sharing one store backend (the dev-default sqlite
1521
- * file, a shared Postgres) must not collide on session ids; the machine
1522
- * name is what makes multi-machine apps unambiguous (a2-api.md §1), so
1523
- * it prefixes every storage key.
1524
- */
1525
- const NS = "";
1526
- const devDefaultStore = retryableLazy(() => import("./store-sqlite-iBTYYKBj.mjs").then((m) => m.sqlite()));
1527
- /** Waits for a scheduler arm for at most `schedulerArmTimeoutMs`. */
1528
- async function joinSchedulerArm(arm) {
1529
- let timeout = null;
1530
- try {
1531
- await Promise.race([arm, new Promise((_, reject) => {
1532
- timeout = setTimeout(() => {
1533
- reject(/* @__PURE__ */ new Error(`a2 scheduler arm timed out after ${DRAIN_TIMINGS.schedulerArmTimeoutMs}ms`));
1534
- }, DRAIN_TIMINGS.schedulerArmTimeoutMs);
1535
- })]);
1536
- } finally {
1537
- if (timeout) clearTimeout(timeout);
1538
- }
1539
- }
1540
- function environment() {
1541
- const env = typeof process === "undefined" ? void 0 : process.env?.["NODE_ENV"];
1542
- if (env === "test") return "test";
1543
- if (env === "production") return "production";
1544
- return "development";
1545
- }
1546
- function describeError(err) {
1547
- if (err instanceof Error) return err.stack ?? `${err.name}: ${err.message}`;
1548
- return String(err);
1549
- }
1550
- /**
1551
- * Comparison key for a presence value in the degraded-tier diff — an
1552
- * LWW tie can replace a value without moving its `seen`/`at` stamp.
1553
- */
1554
- function fingerprint(value) {
1555
- return JSON.stringify(value) ?? "";
1556
- }
1557
- function foldPresenceRows(rows) {
1558
- const map = nullProtoRecord();
1559
- for (const row of rows) (map[row.participant] ??= nullProtoRecord())[row.field] = {
1560
- value: row.value,
1561
- seen: row.seen,
1562
- at: row.at
1563
- };
1564
- return map;
1565
- }
1566
- /** One cursor head, as a map key. */
1567
- const headKey = (ref) => JSON.stringify([
1568
- ref.consumer,
1569
- ref.lane,
1570
- ref.index
1571
- ]);
1572
- const headRefOf = (head) => ({
1573
- consumer: head.consumer,
1574
- lane: head.lane,
1575
- index: head.index
1576
- });
1577
- const addSnapshotWrite = (writes, index, state, pin) => {
1578
- let write = writes.get(index);
1579
- if (!write) {
1580
- write = {
1581
- state: cloneInitial(state),
1582
- pins: /* @__PURE__ */ new Map()
1583
- };
1584
- writes.set(index, write);
1585
- }
1586
- if (pin !== void 0) write.pins.set(headKey(pin), pin);
1587
- };
1588
- /** Whether a registered consumer runs events of this type. */
1589
- const takes = (registered, type) => registered.types === null || registered.types.has(type);
1590
- /** Implement a contract: bind its vocabulary to storage and reactions. */
1591
- function createServer(options) {
1592
- const serverContract = options?.contract;
1593
- if (serverContract === null || typeof serverContract !== "object" || typeof serverContract.name !== "string" || serverContract.events === null) throw new TypeError("createServer expects options with a contract (see a2.contract)");
1594
- if (Object.hasOwn(options, "handlers")) throw new TypeError("createServer no longer takes handlers: write each as a consumer in `consumers` (see https://www.a2.dev/upgrades/0-21)");
1595
- const name = serverContract.name;
1596
- const defs = serverContract.events;
1597
- const presenceDefs = serverContract.presence;
1598
- const declaresPresence = Object.keys(presenceDefs).length > 0;
1599
- const presenceNotSupported = () => new A2Error("PRESENCE_NOT_SUPPORTED", `the contract '${name}' declares presence but the store backend for its server has no presence capability (A2Store.presence)`);
1600
- if (options.presence !== void 0) {
1601
- if (!declaresPresence) throw new TypeError(`the presence option requires a contract that declares presence fields — '${name}' has none`);
1602
- const { ttlMs } = options.presence;
1603
- if (ttlMs !== void 0 && (!Number.isInteger(ttlMs) || ttlMs <= 0)) throw new TypeError("presence.ttlMs must be a positive integer of milliseconds");
1604
- }
1605
- const presenceTtlMs = options.presence?.ttlMs ?? PRESENCE_TTL_MS;
1606
- let makeStore;
1607
- if (options.store) {
1608
- const explicit = options.store;
1609
- if (declaresPresence && !explicit.presence) throw presenceNotSupported();
1610
- makeStore = () => Promise.resolve(explicit);
1611
- } else {
1612
- const env = environment();
1613
- if (env === "production") {
1614
- const error = () => new A2Error("STORE_NOT_CONFIGURED", `the server for '${name}' has no store configured and NODE_ENV is 'production' — pass an explicit store backend (e.g. postgres from 'experimental-a2/store-postgres')`);
1615
- if (process.env["NEXT_PHASE"] !== "phase-production-build") throw error();
1616
- makeStore = () => Promise.reject(error());
1617
- } else makeStore = env === "test" ? () => import("./store-memory-4IBl0Ztu.mjs").then((m) => m.memory()) : devDefaultStore.get;
1618
- }
1619
- if (declaresPresence && !options.store) {
1620
- const inner = makeStore;
1621
- makeStore = async () => {
1622
- const store = await inner();
1623
- if (!store.presence) throw presenceNotSupported();
1624
- return store;
1625
- };
1626
- }
1627
- const resolveStore = retryableLazy(makeStore).get;
1628
- const telemetry = options.telemetry ?? CONSOLE_TELEMETRY;
1629
- const scheduler = options.scheduler;
1630
- const abortMatcherOf = (spec) => {
1631
- let abortOn = null;
1632
- if (spec !== void 0 && spec !== null) {
1633
- abortOn = /* @__PURE__ */ new Map();
1634
- const pairs = Array.isArray(spec) ? spec.map((abortType) => [abortType, true]) : Object.entries(spec);
1635
- for (const [abortType, matcher] of pairs) {
1636
- if (matcher === void 0) continue;
1637
- if (!Object.hasOwn(defs, abortType)) throw new TypeError(`contract '${name}' has no event type '${String(abortType)}' — cannot abort on it`);
1638
- abortOn.set(String(abortType), matcher);
1639
- }
1640
- if (abortOn.size === 0) abortOn = null;
1641
- }
1642
- return abortOn;
1643
- };
1644
- const laneContext = (sessionId, event) => ({
1645
- sessionId,
1646
- event: {
1647
- type: event.type,
1648
- payload: structuredClone(event.payload),
1649
- ...event.id === void 0 ? {} : { id: event.id }
1650
- }
1651
- });
1652
- const registeredConsumers = /* @__PURE__ */ new Map();
1653
- /** A consumer definition as the server runs it. */
1654
- const registrationOf = (defined) => {
1655
- const { types, lane, backfill, abortOn, run } = defined.spec;
1656
- const matcher = abortMatcherOf(abortOn);
1657
- return {
1658
- name: defined.name,
1659
- types: types === null ? null : new Set(types),
1660
- laneOf: typeof lane === "string" ? null : lane === null ? () => null : (sessionId, event) => {
1661
- const resolved = lane(laneContext(sessionId, event));
1662
- if (resolved !== null && (typeof resolved !== "string" || resolved.length === 0)) throw new TypeError(`lane for consumer '${defined.name}' must resolve to a non-empty string or null`);
1663
- return resolved;
1664
- },
1665
- log: typeof lane === "string" ? {
1666
- lane,
1667
- types: types === null ? null : [...types],
1668
- backfill
1669
- } : void 0,
1670
- abortOn: () => matcher,
1671
- run,
1672
- anonymousIds: runtimeConsumers.has(defined)
1673
- };
1674
- };
1675
- /** The definitions the server runs, so `consume` can tell its own from another. */
1676
- const definitions = /* @__PURE__ */ new Map();
1677
- /** A consumer written inline is `consumer()`'s options and `run`, on this contract. */
1678
- const definitionOf = (entry) => {
1679
- if (entry === null || typeof entry !== "object" || "spec" in entry || !("run" in entry)) return entry;
1680
- const { run, ...rest } = entry;
1681
- return consumer({
1682
- ...rest,
1683
- contract: serverContract
1684
- }).run(run);
1685
- };
1686
- for (const entry of options.consumers ?? []) {
1687
- const defined = definitionOf(entry);
1688
- if (defined?.contract?.name !== name || !defined.spec) throw new TypeError(`createServer for '${name}' got a consumer of another contract`);
1689
- if (registeredConsumers.has(defined.name)) throw new TypeError(`two consumers are named '${defined.name}'`);
1690
- registeredConsumers.set(defined.name, registrationOf(defined));
1691
- definitions.set(defined.name, defined);
1692
- }
1693
- const anonymousTypes = /* @__PURE__ */ new Map();
1694
- for (const registered of registeredConsumers.values()) {
1695
- if (!registered.anonymousIds) continue;
1696
- for (const type of registered.types ?? Object.keys(defs)) {
1697
- const other = anonymousTypes.get(type);
1698
- if (other !== void 0) throw new TypeError(`A2's consumers '${other}' and '${registered.name}' both take '${type}'`);
1699
- anonymousTypes.set(type, registered.name);
1700
- }
1701
- }
1702
- /** The consumers this server serves, as the store needs to know them. */
1703
- const storeConsumers = [...registeredConsumers.values()].map(storeConsumerOf);
1704
- /** Whether an event starts cursor work for any consumer. */
1705
- const startsWork = (event) => (event.targets?.length ?? 0) > 0 || [...registeredConsumers.values()].some((registered) => registered.log && takes(registered, event.type));
1706
- const prefix = `${name}${NS}`;
1707
- const nsId = (sessionId) => `${prefix}${sessionId}`;
1708
- const stripNs = (stored) => stored.slice(prefix.length);
1709
- const toPublic = (row) => ({
1710
- id: row.id,
1711
- type: row.type,
1712
- payload: row.payload,
1713
- index: row.index,
1714
- sessionId: stripNs(row.sessionId),
1715
- createdAt: row.createdAt
1716
- });
1717
- const inFlight = /* @__PURE__ */ new Set();
1718
- const track = (p) => {
1719
- inFlight.add(p);
1720
- const drop = () => {
1721
- inFlight.delete(p);
1722
- };
1723
- p.then(drop, drop);
1724
- };
1725
- const schedulerArmSlots = /* @__PURE__ */ new Map();
1726
- /**
1727
- * Start an optional scheduler arm without putting it on the execution path.
1728
- * The returned raw promise lets the initial append report failure; the
1729
- * tracked copy is always rejection-safe for heartbeat callers.
1730
- */
1731
- const startSchedulerArm = (sessionId, dueAt) => {
1732
- if (!scheduler) return null;
1733
- const slottedDueAt = schedulerSlot(dueAt);
1734
- const slotKey = JSON.stringify([sessionId, slottedDueAt]);
1735
- const existing = schedulerArmSlots.get(slotKey);
1736
- if (existing) return existing.promise;
1737
- const raw = Promise.resolve().then(() => scheduler.schedule({
1738
- version: 1,
1739
- kind: "drain",
1740
- contract: name,
1741
- sessionId,
1742
- dueAt: slottedDueAt
1743
- }));
1744
- const forget = setTimeout(() => {
1745
- if (schedulerArmSlots.get(slotKey)?.promise === raw) schedulerArmSlots.delete(slotKey);
1746
- }, Math.max(0, slottedDueAt - Date.now()) + 1e3);
1747
- forget.unref?.();
1748
- schedulerArmSlots.set(slotKey, {
1749
- promise: raw,
1750
- forget
1751
- });
1752
- raw.then(void 0, () => {
1753
- const current = schedulerArmSlots.get(slotKey);
1754
- if (current?.promise !== raw) return;
1755
- clearTimeout(current.forget);
1756
- schedulerArmSlots.delete(slotKey);
1757
- });
1758
- const safe = raw.catch(() => {});
1759
- track(safe);
1760
- platformWaitUntil(safe);
1761
- return raw;
1762
- };
1763
- const scheduledDrains = /* @__PURE__ */ new Map();
1764
- const scheduleDrain = (sessionId, watchdogDueAt) => {
1765
- const existing = scheduledDrains.get(sessionId);
1766
- if (existing && !existing.signal.closed) {
1767
- existing.signal.notify();
1768
- return;
1769
- }
1770
- if (existing) scheduledDrains.delete(sessionId);
1771
- const signal = createDrainSignal();
1772
- const p = new Promise((resolve) => {
1773
- queueMicrotask(() => {
1774
- drainSession(sessionId, {
1775
- watchdogDueAt,
1776
- signal
1777
- }).then(() => resolve()).catch(() => resolve());
1778
- });
1779
- }).finally(() => {
1780
- if (scheduledDrains.get(sessionId)?.promise === p) scheduledDrains.delete(sessionId);
1781
- });
1782
- scheduledDrains.set(sessionId, {
1783
- signal,
1784
- promise: p
1785
- });
1786
- track(p);
1787
- platformWaitUntil(p);
1788
- };
1789
- const validateEvents = (sessionId, events, resolveDispatchMetadata = true) => {
1790
- if (events.length === 0) throw new TypeError("append requires at least one event");
1791
- return events.map((e) => {
1792
- const schema = Object.hasOwn(defs, e.type) ? defs[e.type] : void 0;
1793
- if (!schema) throw new A2Error("UNKNOWN_EVENT_TYPE", `contract '${name}' has no event type '${String(e.type)}'`);
1794
- const result = validateSync(schema, e.payload, `event '${e.type}'`);
1795
- if (result.issues) throw new A2Error("INVALID_PAYLOAD", `invalid payload for event '${e.type}' on machine '${name}'`, { details: result.issues });
1796
- const validated = {
1797
- type: e.type,
1798
- payload: result.value
1799
- };
1800
- if (e.id !== void 0) validated.id = e.id;
1801
- if (!resolveDispatchMetadata) return validated;
1802
- const targets = [];
1803
- for (const registered of registeredConsumers.values()) {
1804
- if (!registered.laneOf || !takes(registered, e.type)) continue;
1805
- targets.push({
1806
- consumer: registered.name,
1807
- lane: registered.laneOf(sessionId, validated)
1808
- });
1809
- }
1810
- if (targets.length > 0) validated.targets = targets;
1811
- return validated;
1812
- });
1813
- };
1814
- /**
1815
- * Validate + write. `onAppended` runs inside the telemetry span, so
1816
- * the drain it schedules is created in the append's active context —
1817
- * with a real tracer, causal work remains connected.
1818
- */
1819
- const appendCore = (sessionId, events, source, mode, onAppended, cause, generatedIds, requireDurableInitialArm = false, condition = {}) => telemetry.span("a2.append", {
1820
- "a2.contract": name,
1821
- "a2.session_id": sessionId,
1822
- "a2.append.source": source,
1823
- "a2.append.mode": mode,
1824
- "a2.append.types": events.map((e) => String(e.type)).join(","),
1825
- "a2.append.count": events.length
1826
- }, async (span) => {
1827
- if (mode === "dispatch" && !scheduler) throw new TypeError("append.dispatch requires a configured scheduler adapter");
1828
- assertSessionId(sessionId);
1829
- const validated = validateEvents(sessionId, events);
1830
- if (cause) for (const [index, event] of validated.entries()) event.cause = generatedIds?.[index] ? {
1831
- ...cause,
1832
- batchSize: events.length
1833
- } : cause;
1834
- const store = await resolveStore();
1835
- let rows;
1836
- let shouldHealSession;
1837
- try {
1838
- const result = await store.append(nsId(sessionId), validated, {
1839
- consumers: storeConsumers,
1840
- ...condition
1841
- });
1842
- rows = result.events;
1843
- shouldHealSession = result.hasPending && !(source === "consumer" && !validated.some(startsWork));
1844
- } catch (err) {
1845
- throw asStoreUnavailable(err);
1846
- }
1847
- const appended = rows.map(toPublic);
1848
- const initialWatchdogAt = shouldHealSession && scheduler && source === "external" && mode === "inline" ? schedulerSlot(nextClaimWindow().watchdogAtMs) : void 0;
1849
- const initialArm = initialWatchdogAt !== void 0 ? startSchedulerArm(sessionId, initialWatchdogAt) : null;
1850
- const dispatchArm = shouldHealSession && mode === "dispatch" ? startSchedulerArm(sessionId, currentSchedulerSlot(Date.now())) : null;
1851
- if (shouldHealSession && mode === "inline") onAppended(appended, initialWatchdogAt);
1852
- if (dispatchArm) await dispatchArm;
1853
- if (initialArm) try {
1854
- await joinSchedulerArm(initialArm);
1855
- } catch (err) {
1856
- span.setAttribute("a2.append.armed", false);
1857
- span.recordError(err);
1858
- if (requireDurableInitialArm) throw err;
1859
- }
1860
- return appended;
1861
- });
1862
- const readHistory = async (sessionId, bounds) => {
1863
- const gte = bounds?.gte;
1864
- const lte = bounds?.lte;
1865
- assertHistoryIndex("gte", gte);
1866
- assertHistoryIndex("lte", lte);
1867
- if (gte !== void 0 && lte !== void 0 && gte > lte) throw new RangeError("history.gte must be less than or equal to history.lte");
1868
- if (lte === 0) return [];
1869
- const store = await resolveStore();
1870
- try {
1871
- const readOptions = gte === void 0 && lte === void 0 ? void 0 : {
1872
- ...gte === void 0 ? {} : { afterIndex: Math.max(0, gte - 1) },
1873
- ...lte === void 0 ? {} : { throughIndex: lte }
1874
- };
1875
- return (await (store.readHistory ? store.readHistory(nsId(sessionId), readOptions) : store.read(nsId(sessionId), readOptions))).filter((row) => (gte === void 0 || row.index >= gte) && (lte === void 0 || row.index <= lte));
1876
- } catch (err) {
1877
- throw asStoreUnavailable(err);
1878
- }
1879
- };
1880
- const readStoreState = async (store, sessionId, reducerName, throughIndex, snapshotThroughIndex) => {
1881
- try {
1882
- return await store.readState(nsId(sessionId), reducerName, throughIndex === void 0 && snapshotThroughIndex === void 0 ? void 0 : {
1883
- ...throughIndex === void 0 ? {} : { throughIndex },
1884
- ...snapshotThroughIndex === void 0 ? {} : { snapshotThroughIndex }
1885
- });
1886
- } catch (err) {
1887
- throw asStoreUnavailable(err);
1888
- }
1889
- };
1890
- const planStateReads = (batch) => {
1891
- const bySession = /* @__PURE__ */ new Map();
1892
- for (const entry of batch) {
1893
- const entries = bySession.get(entry.sessionId);
1894
- if (entries) entries.push(entry);
1895
- else bySession.set(entry.sessionId, [entry]);
1896
- }
1897
- const plans = [];
1898
- for (const [sessionId, entries] of bySession) {
1899
- const boundaries = entries.flatMap((entry) => entry.throughIndex === void 0 ? [] : [entry.throughIndex]);
1900
- const plan = {
1901
- sessionId,
1902
- entries
1903
- };
1904
- if (boundaries.length === entries.length) plan.throughIndex = Math.max(...boundaries);
1905
- if (boundaries.length > 0) plan.snapshotThroughIndex = Math.min(...boundaries);
1906
- plans.push(plan);
1907
- }
1908
- return plans;
1909
- };
1910
- const persistSnapshots = ({ store, reducer, sessionId, snapshots }) => {
1911
- const persistence = Promise.resolve().then(() => telemetry.span("a2.snapshot", {
1912
- "a2.contract": name,
1913
- "a2.session_id": sessionId,
1914
- "a2.snapshot.reducer": reducer.name,
1915
- "a2.snapshot.index": snapshots.at(-1).index,
1916
- "a2.snapshot.count": snapshots.length
1917
- }, async (span) => {
1918
- try {
1919
- await store.putSnapshots(nsId(sessionId), reducer.name, snapshots);
1920
- } catch (error) {
1921
- try {
1922
- span.recordError(error);
1923
- } catch (telemetryError) {
1924
- throw new AggregateError([error, telemetryError], "Snapshot write and error reporting failed", { cause: telemetryError });
1925
- }
1926
- }
1927
- })).catch((error) => {
1928
- console.error("[a2] error in a2.snapshot telemetry", {
1929
- sessionId,
1930
- reducer: reducer.name,
1931
- index: snapshots.at(-1).index
1932
- }, error);
1933
- });
1934
- track(persistence);
1935
- platformWaitUntil(persistence);
1936
- };
1937
- const stateCache = boundedCache(STATE_CACHE);
1938
- const cacheState = (key, next) => {
1939
- const current = stateCache.get(key);
1940
- if (current?.reducer === next.reducer && (current.index > next.index || current.index === next.index && current.persistedIndex >= next.persistedIndex)) return;
1941
- stateCache.set(key, next, next.bytes);
1942
- };
1943
- const writeSnapshots = ({ store, reducer, sessionId, writes }) => {
1944
- const snapshots = [...writes].toSorted(([a], [b]) => a - b).map(([index, write]) => {
1945
- const snapshot = {
1946
- index,
1947
- state: encodeState({
1948
- reducer,
1949
- state: write.state
1950
- })
1951
- };
1952
- if (write.pins.size > 0) snapshot.pins = [...write.pins.values()];
1953
- return snapshot;
1954
- });
1955
- if (snapshots.length > 0) persistSnapshots({
1956
- store,
1957
- reducer,
1958
- sessionId,
1959
- snapshots
1960
- });
1961
- return snapshots;
1962
- };
1963
- /**
1964
- * Folds `rows` from `position` in bound order, resolving each entry with a
1965
- * clone once the rows through its bound are folded. `visit` sees each
1966
- * entry's state before later rows are folded into it.
1967
- */
1968
- const foldEntries = ({ reducer, entries, rows, position, state, index, clearIndex, snapshot, visit }) => {
1969
- const start = position;
1970
- const ordered = entries.toSorted((a, b) => (a.throughIndex ?? Number.POSITIVE_INFINITY) - (b.throughIndex ?? Number.POSITIVE_INFINITY));
1971
- for (const entry of ordered) {
1972
- const target = entry.throughIndex ?? Number.POSITIVE_INFINITY;
1973
- while (position < rows.length && rows[position].index <= target) {
1974
- const row = rows[position];
1975
- state = foldEvent(reducer, state, toPublic(row));
1976
- index = row.index;
1977
- position += 1;
1978
- }
1979
- if (entry.triggerIndex !== void 0 && entry.triggerIndex <= clearIndex || entry.throughIndex !== void 0 && entry.throughIndex > 0 && entry.throughIndex < clearIndex) {
1980
- entry.reject(sessionClearedError(`session '${entry.sessionId}' was cleared at index ${clearIndex}`));
1981
- continue;
1982
- }
1983
- entry.span.setAttribute("a2.state.snapshot", snapshot);
1984
- entry.span.setAttribute("a2.state.folded", position - start);
1985
- entry.span.setAttribute("a2.state.index", index);
1986
- visit(entry, state, index, position - start);
1987
- entry.resolve({
1988
- state: cloneInitial(state),
1989
- index,
1990
- ...clearIndex > 0 && index >= clearIndex ? { clearIndex } : {}
1991
- });
1992
- }
1993
- return {
1994
- state,
1995
- index,
1996
- position
1997
- };
1998
- };
1999
- /**
2000
- * Events from `fromIndex` (inclusive) through `throughIndex` or the newest
2001
- * event, or null when the tail is too long to be worth folding in memory.
2002
- */
2003
- const readCachedTail = async (store, sessionId, fromIndex, throughIndex) => {
2004
- const readTail = stateTailReaders.get(store);
2005
- if (readTail) try {
2006
- return await readTail(nsId(sessionId), fromIndex, throughIndex);
2007
- } catch (err) {
2008
- throw asStoreUnavailable(err);
2009
- }
2010
- const limit = fromIndex + STATE_CACHE.maxTail;
2011
- const capped = throughIndex === void 0 || throughIndex > limit;
2012
- const rows = await readHistory(sessionId, {
2013
- gte: fromIndex,
2014
- lte: capped ? limit : throughIndex
2015
- });
2016
- return capped && rows.at(-1)?.index === limit ? null : rows;
2017
- };
2018
- /**
2019
- * Serves a plan from the cached state when every read is at or past the
2020
- * cached index. A read bounded at the cached index by an event whose id
2021
- * matches the cached one (a consumer's own trigger) needs no store request;
2022
- * any other read fetches the tail from the cached event onward and checks
2023
- * that event's id. Returns false when the store must answer instead.
2024
- */
2025
- const foldCachedPlan = async (store, reducer, plan) => {
2026
- const key = stateCacheKey(plan.sessionId, reducer.name);
2027
- const cached = stateCache.get(key);
2028
- if (cached?.reducer !== reducer) return false;
2029
- if (plan.entries.some((entry) => entry.throughIndex !== void 0 && entry.throughIndex < cached.index)) return false;
2030
- let rows = [];
2031
- if (plan.entries.some((entry) => entry.throughIndex !== cached.index || entry.throughEventId !== cached.lastId)) {
2032
- const tail = await readCachedTail(store, plan.sessionId, cached.index, plan.throughIndex);
2033
- if (!tail) return false;
2034
- if (tail[0]?.index !== cached.index || tail[0].id !== cached.lastId || tail.some((row, position) => position > 0 && isSessionCleared(row))) {
2035
- stateCache.delete(key);
2036
- return false;
2037
- }
2038
- rows = tail;
2039
- }
2040
- const writes = /* @__PURE__ */ new Map();
2041
- const folded = foldEntries({
2042
- reducer,
2043
- entries: plan.entries,
2044
- rows,
2045
- position: 1,
2046
- state: rows.length > 1 ? cloneInitial(cached.state) : cached.state,
2047
- index: cached.index,
2048
- clearIndex: cached.clearIndex,
2049
- snapshot: "memory",
2050
- visit: (entry, state, index) => {
2051
- if (entry.pin !== void 0) addSnapshotWrite(writes, index, state, entry.pin);
2052
- }
2053
- });
2054
- const added = Math.max(0, folded.position - 1);
2055
- const rewritesHead = folded.index - cached.persistedIndex >= STATE_CACHE.snapshotEvery;
2056
- if (rewritesHead && !writes.has(folded.index)) writes.set(folded.index, {
2057
- state: folded.state,
2058
- pins: /* @__PURE__ */ new Map()
2059
- });
2060
- const snapshots = writeSnapshots({
2061
- store,
2062
- reducer,
2063
- sessionId: plan.sessionId,
2064
- writes
2065
- });
2066
- const measure = rewritesHead || cached.unmeasured + added >= STATE_CACHE.measureEvery;
2067
- let grown = 0;
2068
- if (!measure) for (let position = 1; position < folded.position; position += 1) grown += JSON.stringify(rows[position].payload)?.length ?? 0;
2069
- cacheState(key, {
2070
- reducer,
2071
- index: folded.index,
2072
- lastId: added > 0 ? rows[folded.position - 1].id : cached.lastId,
2073
- state: folded.state,
2074
- bytes: measure ? measuredBytes(reducer, folded.state, folded.index, snapshots) : cached.bytes + grown,
2075
- unmeasured: measure ? 0 : cached.unmeasured + added,
2076
- persistedIndex: Math.max(cached.persistedIndex, snapshots.at(-1)?.index ?? 0),
2077
- clearIndex: cached.clearIndex
2078
- });
2079
- return true;
2080
- };
2081
- const foldStatePlan = async (store, reducer, plan, stateRead) => {
2082
- let state = cloneInitial(reducer.initialState);
2083
- let index = 0;
2084
- let snapshotOutcome = "miss";
2085
- const snap = stateRead.snapshot;
2086
- let rows = stateRead.events;
2087
- let clearIndex = stateRead.clearIndex ?? 0;
2088
- if (snap) {
2089
- let decoded;
2090
- try {
2091
- decoded = decodeState({
2092
- reducer,
2093
- state: snap.state
2094
- });
2095
- } catch {
2096
- snapshotOutcome = "rejected";
2097
- }
2098
- if (snapshotOutcome !== "rejected" && reducer.stateSchema) {
2099
- const result = validateSync(reducer.stateSchema, decoded, "the stateSchema");
2100
- if (result.issues) snapshotOutcome = "rejected";
2101
- else {
2102
- state = result.value;
2103
- index = snap.index;
2104
- snapshotOutcome = "hit";
2105
- }
2106
- } else if (snapshotOutcome !== "rejected") {
2107
- state = decoded;
2108
- index = snap.index;
2109
- snapshotOutcome = "hit";
2110
- }
2111
- }
2112
- if (snapshotOutcome === "rejected") {
2113
- try {
2114
- rows = await store.read(nsId(plan.sessionId), plan.throughIndex === void 0 ? void 0 : { throughIndex: plan.throughIndex });
2115
- } catch (err) {
2116
- throw asStoreUnavailable(err);
2117
- }
2118
- if (rows[0] && isSessionCleared(rows[0])) clearIndex = Math.max(clearIndex, rows[0].index);
2119
- }
2120
- const writes = /* @__PURE__ */ new Map();
2121
- const folded = foldEntries({
2122
- reducer,
2123
- entries: plan.entries,
2124
- rows,
2125
- position: 0,
2126
- state,
2127
- index,
2128
- clearIndex,
2129
- snapshot: snapshotOutcome,
2130
- visit: (entry, entryState, entryIndex, count) => {
2131
- if (entryIndex === 0) return;
2132
- if (count === 0 && entry.pin === void 0) return;
2133
- const advancesHead = stateRead.headIndex === null || entryIndex > stateRead.headIndex;
2134
- const repairsHead = snapshotOutcome === "rejected" && entryIndex === stateRead.headIndex;
2135
- if (!advancesHead && !repairsHead && entry.pin === void 0) return;
2136
- addSnapshotWrite(writes, entryIndex, entryState, entry.pin);
2137
- }
2138
- });
2139
- const snapshots = writeSnapshots({
2140
- store,
2141
- reducer,
2142
- sessionId: plan.sessionId,
2143
- writes
2144
- });
2145
- if (folded.position > 0 && STATE_CACHE.maxEntries > 0) cacheState(stateCacheKey(plan.sessionId, reducer.name), {
2146
- reducer,
2147
- index: folded.index,
2148
- lastId: rows[folded.position - 1].id,
2149
- state: folded.state,
2150
- bytes: measuredBytes(reducer, folded.state, folded.index, snapshots),
2151
- unmeasured: 0,
2152
- persistedIndex: Math.min(Math.max(stateRead.headIndex ?? 0, ...writes.keys()), folded.index),
2153
- clearIndex
2154
- });
2155
- };
2156
- const pendingStateReads = /* @__PURE__ */ new Map();
2157
- const flushStateReads = async (store, reducer, batch) => {
2158
- const plans = [];
2159
- await Promise.all(planStateReads(batch).map(async (plan) => {
2160
- try {
2161
- if (!await foldCachedPlan(store, reducer, plan)) plans.push(plan);
2162
- } catch (error) {
2163
- for (const entry of plan.entries) entry.reject(error);
2164
- }
2165
- }));
2166
- if (plans.length === 0) return;
2167
- let reads;
2168
- try {
2169
- reads = store.readStates ? await store.readStates(plans.map((plan) => ({
2170
- sessionId: nsId(plan.sessionId),
2171
- ...plan.throughIndex === void 0 ? {} : { throughIndex: plan.throughIndex },
2172
- ...plan.snapshotThroughIndex === void 0 ? {} : { snapshotThroughIndex: plan.snapshotThroughIndex }
2173
- })), reducer.name) : plans.map((plan) => readStoreState(store, plan.sessionId, reducer.name, plan.throughIndex, plan.snapshotThroughIndex));
2174
- if (reads.length !== plans.length) throw new TypeError("store.readStates must return one result per request");
2175
- } catch (error) {
2176
- const failure = asStoreUnavailable(error);
2177
- for (const plan of plans) for (const entry of plan.entries) entry.reject(failure);
2178
- return;
2179
- }
2180
- await Promise.all(plans.map(async (plan, position) => {
2181
- try {
2182
- await foldStatePlan(store, reducer, plan, await reads[position]);
2183
- } catch (error) {
2184
- for (const entry of plan.entries) entry.reject(error);
2185
- }
2186
- }));
2187
- };
2188
- const enqueueStateRead = (store, sessionId, reducer, bounds, span) => new Promise((resolve, reject) => {
2189
- const reducerName = reducer.name;
2190
- let batch = pendingStateReads.get(reducerName);
2191
- if (!batch) {
2192
- const opened = [];
2193
- pendingStateReads.set(reducerName, opened);
2194
- queueMicrotask(() => {
2195
- pendingStateReads.delete(reducerName);
2196
- flushStateReads(store, reducer, opened);
2197
- });
2198
- batch = opened;
2199
- }
2200
- batch.push({
2201
- sessionId,
2202
- ...bounds,
2203
- span,
2204
- resolve,
2205
- reject
2206
- });
2207
- });
2208
- const readState = async (sessionId, reducer, bounds) => {
2209
- const store = await resolveStore();
2210
- return telemetry.span("a2.state", {
2211
- "a2.contract": name,
2212
- "a2.session_id": sessionId,
2213
- "a2.state.reducer": reducer.name
2214
- }, (span) => enqueueStateRead(store, sessionId, reducer, bounds, span));
2215
- };
2216
- const makeSchedule = (sessionId, trigger) => {
2217
- const triggerEventId = trigger?.id ?? null;
2218
- /** Timers a consumer sets key on its name, except A2's own. */
2219
- const triggerConsumer = trigger && !registeredConsumers.get(trigger.consumer)?.anonymousIds ? trigger.consumer : void 0;
2220
- const triggerCreatedAt = trigger?.createdAt.getTime();
2221
- const clearIndex = trigger?.clearIndex ?? 0;
2222
- const schedule = async (scheduleName, timing, ...events) => {
2223
- if (!scheduler) throw new TypeError("session.schedule requires a configured scheduler adapter");
2224
- assertScheduleName(scheduleName);
2225
- if (events.length === 0) throw new TypeError("schedule requires at least one event");
2226
- const dueAt = scheduleDueAt(timing, triggerCreatedAt ?? Date.now());
2227
- const payloads = events.map((event) => cloneScheduledPayload(event.payload));
2228
- const snapshottedEvents = events.map((event, index) => event.id === void 0 ? {
2229
- type: event.type,
2230
- payload: payloads[index]
2231
- } : {
2232
- type: event.type,
2233
- payload: payloads[index],
2234
- id: event.id
2235
- });
2236
- const validated = validateEvents(sessionId, structuredClone(snapshottedEvents), false);
2237
- const scheduleId = await deterministicScheduleId(name, sessionId, triggerEventId, scheduleName, clearIndex, triggerConsumer);
2238
- const scheduledEvents = await Promise.all(validated.map(async (event, item) => ({
2239
- id: event.id ?? await deterministicScheduledEventId(scheduleId, item),
2240
- type: event.type,
2241
- payload: payloads[item]
2242
- })));
2243
- if (new Set(scheduledEvents.map((event) => event.id)).size !== scheduledEvents.length) throw new A2Error("PARTIAL_DUPLICATE_BATCH", "scheduled batch contains the same event id more than once");
2244
- try {
2245
- await scheduler.schedule({
2246
- version: 1,
2247
- kind: "append",
2248
- id: scheduleId,
2249
- contract: name,
2250
- sessionId,
2251
- dueAt,
2252
- events: scheduledEvents,
2253
- ...trigger ? { originIndex: trigger.index } : {}
2254
- });
2255
- } catch (error) {
2256
- throw markSchedulerSendFailure(error);
2257
- }
2258
- };
2259
- const clear = async (scheduleName, clearOptions) => {
2260
- if (!scheduler) throw new TypeError("session.schedule.clear requires a configured scheduler adapter");
2261
- assertScheduleName(scheduleName);
2262
- if (clearOptions === null || typeof clearOptions !== "object") throw new TypeError("schedule.clear requires an ifLastIndex");
2263
- const { ifLastIndex, ...timing } = clearOptions;
2264
- assertIfLastIndex(ifLastIndex);
2265
- const dueAt = scheduleDueAt(timing, triggerCreatedAt ?? Date.now());
2266
- const store = await resolveStore();
2267
- if (!store.clear || !store.reclaim) throw new TypeError("session.schedule.clear requires a store that supports clearing");
2268
- const id = await deterministicScheduleClearId({
2269
- contract: name,
2270
- sessionId,
2271
- triggerEventId,
2272
- clearIndex,
2273
- name: scheduleName,
2274
- ifLastIndex,
2275
- ...triggerConsumer === void 0 ? {} : { consumer: triggerConsumer }
2276
- });
2277
- try {
2278
- await scheduler.schedule({
2279
- version: 1,
2280
- kind: "clear",
2281
- id,
2282
- contract: name,
2283
- sessionId,
2284
- dueAt,
2285
- ifLastIndex
2286
- });
2287
- } catch (error) {
2288
- throw markSchedulerSendFailure(error);
2289
- }
2290
- };
2291
- return Object.assign(schedule, { clear });
2292
- };
2293
- const toSessionEvent = (id, event) => ({
2294
- id: event.id,
2295
- type: event.type,
2296
- payload: event.payload,
2297
- index: event.index,
2298
- sessionId: id,
2299
- createdAt: event.createdAt
2300
- });
2301
- const streamEvents = (id, startAfter) => {
2302
- let closed = false;
2303
- let inner;
2304
- let stopActivity;
2305
- const activity = createStreamActivity(() => {
2306
- if (inner && !closed) streamActivities.get(inner)?.activate();
2307
- });
2308
- let closing;
2309
- const close = () => {
2310
- closed = true;
2311
- closing ??= (async () => {
2312
- stopActivity?.();
2313
- await inner?.return?.();
2314
- })();
2315
- return closing;
2316
- };
2317
- const outer = async function* () {
2318
- const store = await resolveStore();
2319
- if (closed) return;
2320
- inner = store.stream(nsId(id), { startAfter })[Symbol.asyncIterator]();
2321
- const sourceActivity = streamActivities.get(inner);
2322
- if (sourceActivity) {
2323
- stopActivity = sourceActivity.subscribe(activity.setIdle);
2324
- activity.setIdle(sourceActivity.idle);
2325
- }
2326
- try {
2327
- for (;;) {
2328
- if (closed) return;
2329
- const result = await inner.next();
2330
- if (closed || result.done) return;
2331
- yield toSessionEvent(id, result.value);
2332
- }
2333
- } finally {
2334
- await close();
2335
- }
2336
- };
2337
- const iterator = outer();
2338
- return { [Symbol.asyncIterator]() {
2339
- const stream = {
2340
- next: () => iterator.next(),
2341
- async return() {
2342
- await close();
2343
- return iterator.return(void 0);
2344
- },
2345
- async throw(error) {
2346
- await close();
2347
- return iterator.throw(error);
2348
- }
2349
- };
2350
- streamActivities.set(stream, activity);
2351
- bufferedEvents.set(stream, () => {
2352
- const event = closed || !inner ? void 0 : takeBuffered(inner);
2353
- if (!event) return void 0;
2354
- if (!isSerializedEvent(event)) return toSessionEvent(id, event);
2355
- event.sessionId = id;
2356
- return event;
2357
- });
2358
- return stream;
2359
- } };
2360
- };
2361
- const requirePresence = (store) => {
2362
- if (!store.presence) throw presenceNotSupported();
2363
- return store.presence;
2364
- };
2365
- const setPresence = async (sessionId, patch, fallbackSeen) => {
2366
- if (typeof patch.participant !== "string" || patch.participant.length === 0) throw new TypeError("presence participant must be a non-empty string");
2367
- if (RESERVED_PARTICIPANT_IDS.has(patch.participant)) throw new TypeError(`presence participant must not be '${patch.participant}'`);
2368
- if (patch.at !== void 0 && (typeof patch.at !== "number" || !Number.isFinite(patch.at) || patch.at < 0 || patch.at > 864e13)) throw new TypeError("presence at must be non-negative epoch milliseconds within the Date range");
2369
- const validated = nullProtoRecord();
2370
- for (const [field, value] of Object.entries(patch.values)) {
2371
- if (value === void 0) continue;
2372
- const schema = Object.hasOwn(presenceDefs, field) ? presenceDefs[field] : RESERVED_PARTICIPANT_IDS.has(field) ? void 0 : presenceDefs["*"];
2373
- if (!schema) throw new A2Error("UNKNOWN_PRESENCE_FIELD", `contract '${name}' has no presence field '${field}'`);
2374
- if (value === null) {
2375
- validated[field] = null;
2376
- continue;
2377
- }
2378
- const result = validateSync(schema, value, `presence field '${field}'`);
2379
- if (result.issues) throw new A2Error("INVALID_PAYLOAD", `invalid value for presence field '${field}' on machine '${name}'`, { details: result.issues });
2380
- validated[field] = result.value;
2381
- }
2382
- const store = await resolveStore();
2383
- try {
2384
- await requirePresence(store).set(nsId(sessionId), patch.participant, validated, {
2385
- seen: patch.seen ?? fallbackSeen,
2386
- at: new Date(patch.at ?? Date.now()),
2387
- ttlMs: presenceTtlMs
2388
- });
2389
- } catch (err) {
2390
- throw asStoreUnavailable(err);
2391
- }
2392
- };
2393
- const readPresenceMap = async (sessionId) => {
2394
- const store = await resolveStore();
2395
- let rows;
2396
- try {
2397
- rows = await requirePresence(store).read(nsId(sessionId));
2398
- } catch (err) {
2399
- throw asStoreUnavailable(err);
2400
- }
2401
- return foldPresenceRows(rows);
2402
- };
2403
- /**
2404
- * The two-plane feed. Patches ride `subscribe` when the adapter has
2405
- * the push tier; without it the map is re-read and diffed whenever
2406
- * the event feed wakes, and at the poll idle ceiling while it is
2407
- * silent — degraded means later, not lost while watched.
2408
- */
2409
- const streamWithPresence = (id, startAfter) => {
2410
- const ns = nsId(id);
2411
- let closed = false;
2412
- let events;
2413
- let pendingEvent = null;
2414
- let unsubscribe;
2415
- let sleeper = null;
2416
- let wakeQueue = null;
2417
- let presenceInterval = Math.min(POLL_TIMINGS.activeFloorMs, POLL_TIMINGS.idleCeilingMs);
2418
- let presenceActivityVersion = 0;
2419
- let stopActivity;
2420
- const activity = createStreamActivity(() => {
2421
- if (closed) return;
2422
- presenceActivityVersion += 1;
2423
- presenceInterval = Math.min(POLL_TIMINGS.activeFloorMs, POLL_TIMINGS.idleCeilingMs);
2424
- sleeper?.cancel();
2425
- if (events) streamActivities.get(events)?.activate();
2426
- });
2427
- let closing;
2428
- const close = () => {
2429
- closed = true;
2430
- sleeper?.cancel();
2431
- wakeQueue?.();
2432
- closing ??= (async () => {
2433
- try {
2434
- stopActivity?.();
2435
- unsubscribe?.();
2436
- } finally {
2437
- await events?.return?.();
2438
- }
2439
- })();
2440
- return closing;
2441
- };
2442
- const outer = async function* () {
2443
- const store = await resolveStore();
2444
- if (closed) return;
2445
- const api = requirePresence(store);
2446
- const readRows = async () => {
2447
- try {
2448
- return await api.read(ns);
2449
- } catch (err) {
2450
- throw asStoreUnavailable(err);
2451
- }
2452
- };
2453
- const painted = /* @__PURE__ */ new Map();
2454
- const paintedDeletes = presenceTombstones();
2455
- const diffRows = (rows) => {
2456
- const patches = [];
2457
- const live = /* @__PURE__ */ new Map();
2458
- for (const row of rows) {
2459
- let liveFields = live.get(row.participant);
2460
- if (!liveFields) {
2461
- liveFields = /* @__PURE__ */ new Set();
2462
- live.set(row.participant, liveFields);
2463
- }
2464
- liveFields.add(row.field);
2465
- const stamp = {
2466
- seen: row.seen,
2467
- atMs: row.at.getTime(),
2468
- value: fingerprint(row.value)
2469
- };
2470
- const prior = painted.get(row.participant)?.get(row.field);
2471
- if (prior && prior.seen === stamp.seen && prior.atMs === stamp.atMs && prior.value === stamp.value) continue;
2472
- let paintedFields = painted.get(row.participant);
2473
- if (!paintedFields) {
2474
- paintedFields = /* @__PURE__ */ new Map();
2475
- painted.set(row.participant, paintedFields);
2476
- }
2477
- paintedFields.set(row.field, stamp);
2478
- patches.push({
2479
- participant: row.participant,
2480
- values: { [row.field]: row.value },
2481
- seen: row.seen,
2482
- at: row.at
2483
- });
2484
- }
2485
- for (const [participant, fields] of painted) {
2486
- for (const [field, prior] of fields) {
2487
- if (live.get(participant)?.has(field)) continue;
2488
- fields.delete(field);
2489
- patches.push({
2490
- participant,
2491
- values: { [field]: null },
2492
- seen: prior.seen,
2493
- at: new Date(prior.atMs)
2494
- });
2495
- }
2496
- if (fields.size === 0) painted.delete(participant);
2497
- }
2498
- return patches;
2499
- };
2500
- const paint = (patch) => {
2501
- let fields = painted.get(patch.participant);
2502
- for (const [field, value] of Object.entries(patch.values)) {
2503
- const write = {
2504
- participant: patch.participant,
2505
- field,
2506
- at: patch.at
2507
- };
2508
- if (value === null || value === void 0) {
2509
- fields?.delete(field);
2510
- if (value === null) paintedDeletes.keep(write);
2511
- continue;
2512
- }
2513
- paintedDeletes.drop(write);
2514
- if (!fields) {
2515
- fields = /* @__PURE__ */ new Map();
2516
- painted.set(patch.participant, fields);
2517
- }
2518
- fields.set(field, {
2519
- seen: patch.seen,
2520
- atMs: patch.at.getTime(),
2521
- value: fingerprint(value)
2522
- });
2523
- }
2524
- if (fields?.size === 0) painted.delete(patch.participant);
2525
- };
2526
- const queue = /* @__PURE__ */ new Map();
2527
- const enqueue = (patch) => {
2528
- if (closed) return;
2529
- activity.activate();
2530
- for (const [field, value] of Object.entries(patch.values)) {
2531
- if (value === void 0) continue;
2532
- let fields = queue.get(patch.participant);
2533
- if (!fields) {
2534
- fields = /* @__PURE__ */ new Map();
2535
- queue.set(patch.participant, fields);
2536
- }
2537
- const queued = fields.get(field);
2538
- if (queued && queued.at.getTime() > patch.at.getTime()) continue;
2539
- fields.set(field, {
2540
- value,
2541
- seen: patch.seen,
2542
- at: patch.at
2543
- });
2544
- }
2545
- wakeQueue?.();
2546
- };
2547
- const outdated = (write) => {
2548
- const prior = painted.get(write.participant)?.get(write.field);
2549
- return prior !== void 0 && prior.atMs > write.at.getTime() || paintedDeletes.outranks(write);
2550
- };
2551
- const dequeue = () => {
2552
- for (const [participant, fields] of queue) {
2553
- for (const [field, stamp] of fields) {
2554
- fields.delete(field);
2555
- if (fields.size === 0) queue.delete(participant);
2556
- if (outdated({
2557
- participant,
2558
- field,
2559
- at: stamp.at
2560
- })) continue;
2561
- return {
2562
- participant,
2563
- values: { [field]: stamp.value },
2564
- seen: stamp.seen,
2565
- at: stamp.at
2566
- };
2567
- }
2568
- queue.delete(participant);
2569
- }
2570
- return null;
2571
- };
2572
- try {
2573
- unsubscribe = api.subscribe?.(ns, enqueue);
2574
- events = store.stream(ns, { startAfter })[Symbol.asyncIterator]();
2575
- const sourceActivity = streamActivities.get(events);
2576
- if (sourceActivity) {
2577
- stopActivity = sourceActivity.subscribe(activity.setIdle);
2578
- activity.setIdle(sourceActivity.idle);
2579
- }
2580
- const snapshotRows = await readRows();
2581
- if (closed) return;
2582
- for (const row of snapshotRows) {
2583
- let fields = painted.get(row.participant);
2584
- if (!fields) {
2585
- fields = /* @__PURE__ */ new Map();
2586
- painted.set(row.participant, fields);
2587
- }
2588
- fields.set(row.field, {
2589
- seen: row.seen,
2590
- atMs: row.at.getTime(),
2591
- value: fingerprint(row.value)
2592
- });
2593
- }
2594
- yield { snapshot: foldPresenceRows(snapshotRows) };
2595
- for (;;) {
2596
- if (closed) return;
2597
- for (;;) {
2598
- const patch = dequeue();
2599
- if (!patch) break;
2600
- if (closed) return;
2601
- paint(patch);
2602
- yield patch;
2603
- }
2604
- pendingEvent ??= events.next();
2605
- let woke;
2606
- if (unsubscribe) {
2607
- const arrival = new Promise((resolve) => {
2608
- wakeQueue = resolve;
2609
- });
2610
- woke = await Promise.race([pendingEvent.then(() => "event"), arrival.then(() => "patch")]);
2611
- wakeQueue = null;
2612
- if (closed) return;
2613
- if (woke === "patch") continue;
2614
- } else {
2615
- sleeper = defaultSleep(presenceInterval);
2616
- woke = await Promise.race([pendingEvent.then(() => "event"), sleeper.promise.then(() => "tick")]);
2617
- sleeper.cancel();
2618
- sleeper = null;
2619
- }
2620
- if (closed) return;
2621
- if (woke === "event") {
2622
- const result = await pendingEvent;
2623
- pendingEvent = null;
2624
- if (closed || result.done) return;
2625
- activity.activate();
2626
- yield toSessionEvent(id, result.value);
2627
- }
2628
- if (!closed && !unsubscribe) {
2629
- const version = presenceActivityVersion;
2630
- const rows = await readRows();
2631
- if (closed) return;
2632
- const patches = diffRows(rows);
2633
- if (patches.length > 0) activity.activate();
2634
- else if (version === presenceActivityVersion) presenceInterval = Math.min(presenceInterval * 2, POLL_TIMINGS.idleCeilingMs);
2635
- for (const patch of patches) {
2636
- if (closed) return;
2637
- yield patch;
2638
- }
2639
- }
2640
- }
2641
- } finally {
2642
- pendingEvent?.catch(() => {});
2643
- await close();
2644
- wakeQueue = null;
2645
- }
2646
- };
2647
- const iterator = outer();
2648
- return { [Symbol.asyncIterator]() {
2649
- const stream = {
2650
- next: () => iterator.next(),
2651
- async return() {
2652
- await close();
2653
- return iterator.return(void 0);
2654
- },
2655
- async throw(error) {
2656
- await close();
2657
- return iterator.throw(error);
2658
- }
2659
- };
2660
- streamActivities.set(stream, activity);
2661
- bufferedEvents.set(stream, () => {
2662
- if (closed || !events || pendingEvent) return void 0;
2663
- const event = takeBuffered(events);
2664
- if (!event) return void 0;
2665
- if (!isSerializedEvent(event)) return toSessionEvent(id, event);
2666
- event.sessionId = id;
2667
- return event;
2668
- });
2669
- return stream;
2670
- } };
2671
- };
2672
- const reclaimAll = async (store, ns) => {
2673
- for (let stalls = 0;;) {
2674
- let batch;
2675
- try {
2676
- batch = await store.reclaim(ns);
2677
- } catch (err) {
2678
- throw asStoreUnavailable(err);
2679
- }
2680
- if (batch.done) return;
2681
- if (batch.deleted > 0) {
2682
- stalls = 0;
2683
- continue;
2684
- }
2685
- stalls += 1;
2686
- if (stalls === RECLAIM_STALL_LIMIT) throw new A2Error("STORE_UNAVAILABLE", `deleting the cleared history of session '${stripNs(ns)}' made no progress`);
2687
- await defaultSleep(RECLAIM_STALL_MS).promise;
2688
- }
2689
- };
2690
- const clearSession = async (sessionId, clearOptions, attempt) => {
2691
- const ifLastIndex = clearOptions?.ifLastIndex;
2692
- if (ifLastIndex !== void 0) assertIfLastIndex(ifLastIndex);
2693
- const store = await resolveStore();
2694
- if (!store.clear || !store.reclaim) throw new TypeError("session.clear requires a store that supports clearing");
2695
- const ns = nsId(sessionId);
2696
- let result;
2697
- try {
2698
- result = await store.clear({
2699
- sessionId: ns,
2700
- ...ifLastIndex === void 0 ? {} : { ifLastIndex },
2701
- ...attempt ? { cause: attempt.cause } : {}
2702
- });
2703
- } catch (err) {
2704
- throw asStoreUnavailable(err);
2705
- }
2706
- if (result.cleared) {
2707
- const cachePrefix = stateCacheKey(sessionId, "");
2708
- stateCache.deleteWhere((key) => key.startsWith(cachePrefix));
2709
- }
2710
- const deletion = reclaimAll(store, ns);
2711
- if (attempt) {
2712
- if (attempt.cause.index <= result.clearIndex) attempt.end();
2713
- const kept = deletion.catch(() => void 0);
2714
- track(kept);
2715
- platformWaitUntil(kept);
2716
- }
2717
- await deletion;
2718
- return {
2719
- cleared: result.cleared,
2720
- index: result.index
2721
- };
2722
- };
2723
- const redrivingStore = async (method) => {
2724
- const store = await resolveStore();
2725
- if (!store.deadLetters || !store.redrive) throw new TypeError(`session.${method} requires a store that supports redriving dead letters`);
2726
- return store;
2727
- };
2728
- const listDeadLetters = async (sessionId) => {
2729
- const store = await redrivingStore("deadLetters");
2730
- let rows;
2731
- try {
2732
- rows = await store.deadLetters(nsId(sessionId));
2733
- } catch (err) {
2734
- throw asStoreUnavailable(err);
2735
- }
2736
- return rows.flatMap((row) => row.failedAt === null ? [] : [{
2737
- ...toPublic(row),
2738
- consumer: row.consumer,
2739
- lane: row.lane,
2740
- attemptCount: row.attemptCount,
2741
- failureCount: row.failureCount,
2742
- lastError: row.lastError,
2743
- failedAt: row.failedAt
2744
- }]);
2745
- };
2746
- const redriveEvent = async (sessionId, target, redriveOptions) => {
2747
- const index = target?.index;
2748
- const redriven = target?.consumer;
2749
- assertRedriveIndex(index);
2750
- if (typeof redriven !== "string" || redriven.length === 0) throw new TypeError("redrive requires a consumer name");
2751
- const action = redriveOptions?.action;
2752
- if (action !== "retry" && action !== "skip") throw new TypeError("redrive requires action 'retry' or 'skip'");
2753
- return telemetry.span("a2.redrive", {
2754
- "a2.contract": name,
2755
- "a2.session_id": sessionId,
2756
- "a2.redrive.index": index,
2757
- "a2.redrive.consumer": redriven,
2758
- "a2.redrive.action": action
2759
- }, async (span) => {
2760
- const store = await redrivingStore("redrive");
2761
- let result;
2762
- try {
2763
- result = await store.redrive({
2764
- sessionId: nsId(sessionId),
2765
- consumer: redriven,
2766
- index,
2767
- action,
2768
- consumers: storeConsumers
2769
- });
2770
- } catch (err) {
2771
- throw asStoreUnavailable(err);
2772
- }
2773
- span.setAttribute("a2.redrive.redriven", result.redriven);
2774
- if (result.hasPending) {
2775
- const watchdogAt = scheduler ? schedulerSlot(nextClaimWindow().watchdogAtMs) : void 0;
2776
- const arm = watchdogAt === void 0 ? null : startSchedulerArm(sessionId, watchdogAt);
2777
- scheduleDrain(sessionId, watchdogAt);
2778
- if (arm) try {
2779
- await joinSchedulerArm(arm);
2780
- } catch (err) {
2781
- span.setAttribute("a2.redrive.armed", false);
2782
- span.recordError(err);
2783
- }
2784
- }
2785
- return { redriven: result.redriven };
2786
- });
2787
- };
2788
- /**
2789
- * `session.consume`: wakes the consumer's cursor, then drains only that
2790
- * consumer until its head lies past `through`. A head another invocation
2791
- * holds, or one waiting out a failure, is waited for; a dead-lettered head
2792
- * throws.
2793
- */
2794
- /** Per session, which consumer's running head is waiting in `consume` on which: a cycle never ends. */
2795
- const consumeWaits = /* @__PURE__ */ new Map();
2796
- const consumeSession = (sessionId, defined, consumeOptions = {}, trigger = null) => {
2797
- assertSessionId(sessionId);
2798
- if (defined?.contract?.name !== name || !defined.spec) throw new TypeError(`session.consume for '${name}' got a consumer of another contract`);
2799
- const own = definitions.get(defined.name);
2800
- if (own !== void 0 && own !== defined) throw new TypeError(`this server runs a different consumer named '${defined.name}'`);
2801
- if (defined.name === trigger?.consumer) throw new TypeError(`consumer '${defined.name}' can't consume itself: its own head is running`);
2802
- const registered = own ? registeredConsumers.get(defined.name) : registrationOf(defined);
2803
- const log = registered.log;
2804
- if (!log) throw new TypeError(`consumer '${defined.name}' needs a string lane to be consumed: only then does it have one position`);
2805
- const { through: requested, signal } = consumeOptions;
2806
- if (requested !== void 0) assertConsumeIndex(requested);
2807
- const waiter = trigger?.consumer;
2808
- const waits = waiter === void 0 ? void 0 : consumeWaits.get(sessionId) ?? consumeWaits.set(sessionId, /* @__PURE__ */ new Map()).get(sessionId);
2809
- let cycle = false;
2810
- if (waiter !== void 0 && waits) {
2811
- for (let next = defined.name; next !== void 0 && !cycle; next = waits.get(next)) cycle = next === waiter;
2812
- if (!cycle) waits.set(waiter, defined.name);
2813
- }
2814
- const storeConsumer = {
2815
- name: registered.name,
2816
- log
2817
- };
2818
- const consumed = telemetry.span("a2.consume", {
2819
- "a2.contract": name,
2820
- "a2.session_id": sessionId,
2821
- "a2.consume.consumer": registered.name
2822
- }, async (span) => {
2823
- const store = await resolveStore();
2824
- const ns = nsId(sessionId);
2825
- let woken = await store.wakeLog({
2826
- sessionId: ns,
2827
- consumer: storeConsumer
2828
- });
2829
- const through = Math.min(requested ?? woken.head, woken.head);
2830
- span.setAttribute("a2.consume.through", through);
2831
- const done = () => woken.cursor.head === null || woken.cursor.head > through;
2832
- if (cycle && !done()) throw new TypeError(`consumer '${waiter}' can't consume '${defined.name}' through ${through}: '${defined.name}' is waiting on it in session '${sessionId}'`);
2833
- let drains = 0;
2834
- let wait = CONSUME_WAIT_MIN_MS;
2835
- while (!done()) {
2836
- signal?.throwIfAborted();
2837
- const { cursor } = woken;
2838
- if (cursor.failedAt !== null) throw new A2Error("CONSUMER_DEAD_LETTERED", `consumer '${registered.name}' is dead-lettered at event ${cursor.head} in session '${sessionId}': ${cursor.lastError ?? "every attempt ended before it finished"}`);
2839
- drains += 1;
2840
- const drained = drainSession(sessionId, {
2841
- only: registered,
2842
- through
2843
- });
2844
- try {
2845
- await untilAborted(drained, signal);
2846
- } catch (error) {
2847
- if (signal?.aborted) drained.then(() => scheduleDrain(sessionId), () => {});
2848
- throw error;
2849
- }
2850
- const before = cursor;
2851
- woken = await store.wakeLog({
2852
- sessionId: ns,
2853
- consumer: storeConsumer
2854
- });
2855
- const moved = woken.cursor.head !== before.head || woken.cursor.attemptCount !== before.attemptCount;
2856
- if (done() || moved) {
2857
- wait = CONSUME_WAIT_MIN_MS;
2858
- continue;
2859
- }
2860
- const sleep = defaultSleep(wait);
2861
- const abort = () => sleep.cancel();
2862
- signal?.addEventListener("abort", abort, { once: true });
2863
- await sleep.promise;
2864
- signal?.removeEventListener("abort", abort);
2865
- wait = Math.min(wait * 2, CONSUME_WAIT_MAX_MS);
2866
- }
2867
- if (drains > 0 || own && woken.cursor.head !== null) scheduleDrain(sessionId);
2868
- const index = woken.cursor.head === null ? woken.head : woken.cursor.head - 1;
2869
- span.setAttribute("a2.consume.index", index);
2870
- span.setAttribute("a2.consume.drains", drains);
2871
- return { index };
2872
- });
2873
- return waiter === void 0 || cycle ? consumed : consumed.finally(() => {
2874
- waits?.delete(waiter);
2875
- if (waits?.size === 0) consumeWaits.delete(sessionId);
2876
- });
2877
- };
2878
- const makeSession = (id, append, trigger, attempt) => ({
2879
- id,
2880
- append,
2881
- consume: (defined, consumeOptions) => consumeSession(id, defined, consumeOptions, trigger),
2882
- schedule: makeSchedule(id, trigger),
2883
- clear: (clearOptions) => clearSession(id, clearOptions, attempt),
2884
- history: async (bounds) => (await readHistory(id, bounds)).filter((row) => !isSessionCleared(row)).map(toPublic),
2885
- state: (reducer = serverContract.reducer, stateOptions) => {
2886
- if (!reducer) throw new A2Error("INVALID_PAYLOAD", "contract has no public reducer");
2887
- const through = stateOptions?.through ?? trigger?.index;
2888
- if (through !== void 0 && through !== "latest") assertStateIndex(through);
2889
- const bounds = {};
2890
- if (through !== void 0 && through !== "latest") {
2891
- bounds.throughIndex = through;
2892
- if (trigger) bounds.pin = headRefOf(trigger);
2893
- if (through === trigger?.index && !attempt?.signal.aborted) bounds.throughEventId = trigger.id;
2894
- }
2895
- if (trigger) bounds.triggerIndex = trigger.index;
2896
- return readState(id, reducer, bounds);
2897
- },
2898
- stream: (opts) => {
2899
- const startAfter = opts?.startAfter ?? 0;
2900
- assertStreamIndex(startAfter);
2901
- return opts?.presence === true ? streamWithPresence(id, startAfter) : streamEvents(id, startAfter);
2902
- },
2903
- ...declaresPresence ? {
2904
- setPresence: (patch) => setPresence(id, patch, trigger?.index ?? 0),
2905
- presence: () => readPresenceMap(id)
2906
- } : {}
2907
- });
2908
- /** The consumer name a trigger's child ids key on, if any. */
2909
- const idConsumerOf = (trigger) => registeredConsumers.get(trigger.consumer)?.anonymousIds ? void 0 : trigger.consumer;
2910
- const makeCtx = (trigger, attempt, signal, endAttempt) => {
2911
- const publicSessionId = stripNs(trigger.sessionId);
2912
- const idConsumer = idConsumerOf(trigger);
2913
- const cause = {
2914
- consumer: trigger.consumer,
2915
- lane: trigger.lane,
2916
- index: trigger.index,
2917
- attempt
2918
- };
2919
- const append = async (appendName, ...events) => {
2920
- assertAppendName(appendName);
2921
- const generatedIds = events.map((event) => event.id === void 0);
2922
- const withIds = await Promise.all(events.map(async (event, item) => {
2923
- if (event.id !== void 0) return event;
2924
- const id = await deterministicEventId(trigger.id, appendName, item, idConsumer);
2925
- return {
2926
- ...event,
2927
- id
2928
- };
2929
- }));
2930
- return appendCore(publicSessionId, withIds, "consumer", "inline", (_rows, watchdogDueAt) => scheduleDrain(publicSessionId, watchdogDueAt), cause, generatedIds);
2931
- };
2932
- const ctx = {
2933
- event: toPublic(trigger),
2934
- attempt,
2935
- session: makeSession(publicSessionId, append, trigger, {
2936
- cause,
2937
- end: endAttempt,
2938
- signal
2939
- }),
2940
- signal
2941
- };
2942
- if (attempt > 1 && trigger.lastFailedAttempt === attempt - 1) failedPreviousAttempt.add(ctx);
2943
- return ctx;
2944
- };
2945
- const abortHubs = /* @__PURE__ */ new Map();
2946
- const createAbortHub = (store, ns, startAfter) => {
2947
- const hub = {
2948
- subscriptions: /* @__PURE__ */ new Set(),
2949
- seen: /* @__PURE__ */ new Map(),
2950
- startAfter,
2951
- ready: Promise.resolve(),
2952
- watch: null,
2953
- error: null,
2954
- iterator: null,
2955
- stopped: false
2956
- };
2957
- hub.ready = (async () => {
2958
- const existing = await store.read(ns, { afterIndex: startAfter });
2959
- for (const event of existing) dispatchAbortEvent(hub, event);
2960
- const tail = existing.at(-1)?.index ?? startAfter;
2961
- const iterator = store.stream(ns, { startAfter: tail })[Symbol.asyncIterator]();
2962
- hub.iterator = iterator;
2963
- hub.watch = (async () => {
2964
- for (;;) {
2965
- const { value, done } = await iterator.next();
2966
- if (done || value === void 0 || hub.stopped) return;
2967
- dispatchAbortEvent(hub, value);
2968
- }
2969
- })().catch((error) => {
2970
- hub.error = error;
2971
- });
2972
- })().catch((error) => {
2973
- hub.error = error;
2974
- if (abortHubs.get(ns) === hub) abortHubs.delete(ns);
2975
- throw error;
2976
- });
2977
- abortHubs.set(ns, hub);
2978
- return hub;
2979
- };
2980
- const subscribeAbort = async (store, ns, trigger, abortOn, attempt) => {
2981
- let hub = abortHubs.get(ns);
2982
- const created = hub === void 0;
2983
- if (!hub) hub = createAbortHub(store, ns, trigger.index);
2984
- const activeTypes = /* @__PURE__ */ new Set();
2985
- for (const active of hub.subscriptions) for (const type of active.types) activeTypes.add(type);
2986
- const publicTrigger = toPublic(trigger);
2987
- const subscription = {
2988
- controller: new AbortController(),
2989
- triggerIndex: trigger.index,
2990
- types: new Set(abortOn.keys()),
2991
- matches: (event) => {
2992
- if (event.index <= trigger.index) return false;
2993
- const matcher = abortOn.get(event.type);
2994
- if (matcher === void 0) return false;
2995
- return matcher === true ? true : matcher(toPublic(event), publicTrigger, { attempt });
2996
- }
2997
- };
2998
- hub.subscriptions.add(subscription);
2999
- if (!created && (trigger.index < hub.startAfter || [...subscription.types].some((type) => !activeTypes.has(type)))) {
3000
- const earlier = await store.read(ns, { afterIndex: trigger.index });
3001
- hub.startAfter = Math.min(hub.startAfter, trigger.index);
3002
- for (const event of earlier) dispatchAbortEvent(hub, event);
3003
- }
3004
- for (const event of hub.seen.values()) if (subscription.matches(event)) subscription.controller.abort();
3005
- await hub.ready;
3006
- if (hub.error !== null) throw hub.error;
3007
- return {
3008
- signal: subscription.controller.signal,
3009
- monitor: async (operation) => {
3010
- const outcome = await Promise.race([operation.then((value) => ({
3011
- type: "completed",
3012
- value
3013
- }), (error) => ({
3014
- type: "run-failed",
3015
- error
3016
- })), hub.watch.then(() => hub.error === null ? { type: "monitor-closed" } : {
3017
- type: "monitor-failed",
3018
- error: hub.error
3019
- })]);
3020
- if (outcome.type === "completed") return outcome.value;
3021
- if (outcome.type === "run-failed") throw outcome.error;
3022
- if (outcome.type === "monitor-failed") {
3023
- for (const active of hub.subscriptions) active.controller.abort(outcome.error);
3024
- await operation.catch(() => {});
3025
- throw outcome.error;
3026
- }
3027
- await operation.catch(() => {});
3028
- throw new Error("abort monitor closed while consumers were active");
3029
- },
3030
- close: async () => {
3031
- hub.subscriptions.delete(subscription);
3032
- if (hub.subscriptions.size > 0) {
3033
- pruneAbortHub(hub);
3034
- return;
3035
- }
3036
- hub.stopped = true;
3037
- abortHubs.delete(ns);
3038
- await hub.ready;
3039
- await hub.iterator?.return?.();
3040
- await hub.watch;
3041
- }
3042
- };
3043
- };
3044
- const returnedEvents = async (sessionId, trigger, result) => {
3045
- if (result === void 0) return [];
3046
- const events = Array.isArray(result) ? [...result] : [result];
3047
- if (events.length === 0) return [];
3048
- const idConsumer = idConsumerOf(trigger);
3049
- const withIds = await Promise.all(events.map(async (event, item) => {
3050
- const withId = { ...event };
3051
- withId.id = event.id ?? await deterministicReturnedEventId(trigger.id, item, idConsumer);
3052
- return withId;
3053
- }));
3054
- return validateEvents(sessionId, withIds).map((event) => Object.assign(event, {
3055
- id: event.id,
3056
- cause: {
3057
- consumer: trigger.consumer,
3058
- lane: trigger.lane,
3059
- index: trigger.index,
3060
- attempt: trigger.attemptCount
3061
- }
3062
- }));
3063
- };
3064
- const drainSession = async (sessionId, drainOptions = {}) => {
3065
- const result = await runDrain(sessionId, drainOptions);
3066
- if (result.settled && drainOptions.only === void 0) drainSettledHooks.get(self)?.(sessionId);
3067
- return result;
3068
- };
3069
- const runDrain = (sessionId, { watchdogDueAt, signal, handOffFailure = false, only, through } = {}) => telemetry.span("a2.drain", {
3070
- "a2.contract": name,
3071
- "a2.session_id": sessionId
3072
- }, async (span) => {
3073
- const store = await resolveStore();
3074
- const ns = nsId(sessionId);
3075
- const holder = crypto.randomUUID();
3076
- /** Running heads, keyed by `headKey`: one event can run for several consumers. */
3077
- const active = /* @__PURE__ */ new Map();
3078
- const excluded = /* @__PURE__ */ new Map();
3079
- let processed = 0;
3080
- let sawFailure = false;
3081
- let schedulerArm;
3082
- let heartbeat = null;
3083
- let lapseTimer = null;
3084
- let retryTimer = null;
3085
- let renewal = null;
3086
- let stopRenewing = false;
3087
- const lapseDue = () => {
3088
- lapseTimer = null;
3089
- const nowMs = Date.now();
3090
- for (const entry of active.values()) {
3091
- if (entry.lapsed || entry.expiresAtMs > nowMs) continue;
3092
- entry.lapsed = true;
3093
- entry.supersede.abort(new A2Error("CLAIM_EXPIRED", `the claim on event ${entry.ref.index} for consumer '${entry.ref.consumer}' in session '${sessionId}' lapsed without renewal`));
3094
- }
3095
- scheduleLapse();
3096
- };
3097
- const scheduleLapse = () => {
3098
- if (lapseTimer) {
3099
- clearTimeout(lapseTimer);
3100
- lapseTimer = null;
3101
- }
3102
- let next = Number.POSITIVE_INFINITY;
3103
- for (const entry of active.values()) if (!entry.lapsed) next = Math.min(next, entry.expiresAtMs);
3104
- if (next === Number.POSITIVE_INFINITY) return;
3105
- lapseTimer = setTimeout(lapseDue, Math.max(0, next - Date.now()));
3106
- lapseTimer.unref?.();
3107
- };
3108
- const scheduleRenewRetry = () => {
3109
- if (stopRenewing || retryTimer) return;
3110
- const nowMs = Date.now();
3111
- if (![...active.values()].some((entry) => !entry.lapsed && entry.expiresAtMs > nowMs)) return;
3112
- const delay = DRAIN_TIMINGS.renewRetryMs * (.5 + Math.random() * .5);
3113
- retryTimer = setTimeout(() => {
3114
- retryTimer = null;
3115
- renew();
3116
- }, delay);
3117
- retryTimer.unref?.();
3118
- };
3119
- const alignWatchdogAt = (minimumDueAt) => {
3120
- if (watchdogDueAt === void 0) return minimumDueAt;
3121
- return watchdogDueAt + Math.max(0, Math.ceil((minimumDueAt - watchdogDueAt) / DRAIN_TIMINGS.claimHeartbeatMs)) * DRAIN_TIMINGS.claimHeartbeatMs;
3122
- };
3123
- const requestWatchdog = (dueAt) => {
3124
- const arm = startSchedulerArm(sessionId, alignWatchdogAt(dueAt));
3125
- if (arm) schedulerArm = arm;
3126
- };
3127
- const renew = () => {
3128
- if (stopRenewing || renewal || active.size === 0) return renewal ?? Promise.resolve();
3129
- const window = nextClaimWindow();
3130
- requestWatchdog(window.watchdogAtMs);
3131
- const claims = [...active.values()].map((entry) => ({
3132
- ...entry.ref,
3133
- attempt: entry.attempt
3134
- }));
3135
- const operation = store.renewClaims({
3136
- sessionId: ns,
3137
- holder,
3138
- claims,
3139
- ttlMs: window.ttlMs,
3140
- ...window.deadlineCapped ? { expiresAtMs: window.expiresAtMs } : {}
3141
- }).then((result) => {
3142
- for (const ref of result.renewed) {
3143
- const entry = active.get(headKey(ref));
3144
- if (entry && !entry.lapsed) entry.expiresAtMs = window.expiresAtMs;
3145
- }
3146
- for (const ref of result.superseded) {
3147
- const entry = active.get(headKey(ref));
3148
- if (!entry || entry.completing) continue;
3149
- endSuperseded(entry, `a newer attempt owns event ${ref.index} for consumer '${ref.consumer}' in session '${sessionId}'`);
3150
- }
3151
- if (window.deadlineCapped) stopRenewing = true;
3152
- scheduleLapse();
3153
- }, () => {
3154
- scheduleRenewRetry();
3155
- });
3156
- let tracked;
3157
- tracked = operation.finally(() => {
3158
- if (renewal === tracked) renewal = null;
3159
- });
3160
- renewal = tracked;
3161
- return tracked;
3162
- };
3163
- /** Records a head the store dead-lettered on takeover; it never runs. */
3164
- const reportExhausted = (event) => telemetry.span("a2.event", {
3165
- "a2.contract": name,
3166
- "a2.session_id": sessionId,
3167
- "a2.event.type": event.type,
3168
- "a2.event.index": event.index,
3169
- "a2.event.id": event.id,
3170
- "a2.event.consumer": event.consumer,
3171
- "a2.event.attempt": event.attemptCount,
3172
- "a2.event.handled": registeredConsumers.has(event.consumer),
3173
- ...event.lane === null ? {} : { "a2.event.lane": event.lane }
3174
- }, async (eventSpan) => {
3175
- eventSpan.setAttribute("a2.event.outcome", "dead_lettered");
3176
- });
3177
- const runEvent = async (event, supersedeSignal, endAttempt, beginCompleting, sessionHead) => {
3178
- const registration = only?.name === event.consumer ? only : registeredConsumers.get(event.consumer);
3179
- const abortOn = registration?.abortOn(event.type) ?? null;
3180
- return telemetry.span("a2.event", {
3181
- "a2.contract": name,
3182
- "a2.session_id": sessionId,
3183
- "a2.event.type": event.type,
3184
- "a2.event.index": event.index,
3185
- "a2.event.id": event.id,
3186
- "a2.event.consumer": event.consumer,
3187
- "a2.event.attempt": event.attemptCount,
3188
- "a2.event.handled": registration !== void 0,
3189
- "a2.event.age_ms": Math.max(0, Date.now() - event.createdAt.getTime()),
3190
- ...sessionHead === void 0 ? {} : { "a2.event.lag": Math.max(0, sessionHead - event.index) },
3191
- ...event.lane === null ? {} : { "a2.event.lane": event.lane }
3192
- }, async (eventSpan) => {
3193
- let subscription;
3194
- let runSignal = supersedeSignal;
3195
- let completion;
3196
- let completing = false;
3197
- try {
3198
- if (abortOn) {
3199
- subscription = await subscribeAbort(store, ns, event, abortOn, event.attemptCount);
3200
- runSignal = AbortSignal.any([supersedeSignal, subscription.signal]);
3201
- }
3202
- const operation = registration?.run(makeCtx(event, event.attemptCount, runSignal, endAttempt));
3203
- const result = operation ? await (subscription ? subscription.monitor(operation) : operation) : void 0;
3204
- if (subscription) {
3205
- await subscription.close();
3206
- subscription = void 0;
3207
- }
3208
- const returned = await returnedEvents(sessionId, event, result);
3209
- await renewal;
3210
- completing = true;
3211
- beginCompleting();
3212
- completion = await telemetry.span("a2.commit", {
3213
- "a2.contract": name,
3214
- "a2.session_id": sessionId,
3215
- "a2.commit.operation": "complete",
3216
- "a2.commit.index": event.index,
3217
- "a2.commit.attempt": event.attemptCount
3218
- }, async (commitSpan) => {
3219
- const committed = await store.completeAttempt({
3220
- sessionId: ns,
3221
- consumer: event.consumer,
3222
- lane: event.lane,
3223
- index: event.index,
3224
- attempt: event.attemptCount,
3225
- events: returned,
3226
- consumers: storeConsumers
3227
- });
3228
- commitSpan.setAttribute("a2.commit.outcome", committed.outcome);
3229
- return committed;
3230
- });
3231
- } catch (err) {
3232
- if (supersedeSignal.aborted && err === supersedeSignal.reason) {
3233
- eventSpan.setAttribute("a2.event.outcome", "surrendered");
3234
- return {
3235
- status: "surrendered",
3236
- opensLane: false,
3237
- appendsEvents: false
3238
- };
3239
- }
3240
- const refused = completing && err instanceof A2Error && err.code === "PARTIAL_DUPLICATE_BATCH";
3241
- if (completing && !refused) throw err;
3242
- eventSpan.recordError(err);
3243
- const failure = await telemetry.span("a2.commit", {
3244
- "a2.contract": name,
3245
- "a2.session_id": sessionId,
3246
- "a2.commit.operation": "fail",
3247
- "a2.commit.index": event.index,
3248
- "a2.commit.attempt": event.attemptCount
3249
- }, async (commitSpan) => {
3250
- const result = await store.failAttempt({
3251
- sessionId: ns,
3252
- consumer: event.consumer,
3253
- lane: event.lane,
3254
- index: event.index,
3255
- attempt: event.attemptCount,
3256
- error: describeError(err),
3257
- maxFailures: err instanceof NonRetriableError || refused ? 1 : MAX_FAILURES,
3258
- retryAfterMs: failureRetryDelayMs(event.failureCount + 1)
3259
- });
3260
- commitSpan.setAttribute("a2.commit.outcome", result.outcome);
3261
- return result;
3262
- });
3263
- eventSpan.setAttribute("a2.event.outcome", failure.outcome);
3264
- return {
3265
- status: failure.outcome,
3266
- opensLane: false,
3267
- appendsEvents: false
3268
- };
3269
- } finally {
3270
- await subscription?.close();
3271
- }
3272
- eventSpan.setAttribute("a2.event.outcome", completion.outcome === "completed" ? "processed" : completion.outcome);
3273
- if (completion.outcome === "superseded") return {
3274
- status: "superseded",
3275
- opensLane: false,
3276
- appendsEvents: false
3277
- };
3278
- if (runSignal.aborted) eventSpan.setAttribute("a2.event.aborted", true);
3279
- return {
3280
- status: "processed",
3281
- opensLane: event.lane !== null,
3282
- appendsEvents: completion.events.length > 0
3283
- };
3284
- });
3285
- };
3286
- let claimAgain = false;
3287
- const start = (event, expiresAtMs, sessionHead) => {
3288
- const ref = headRefOf(event);
3289
- const key = headKey(ref);
3290
- const previous = active.get(key);
3291
- if (previous) endSuperseded(previous, `a newer attempt owns event ${event.index} for consumer '${event.consumer}' in session '${sessionId}'`);
3292
- const supersede = new AbortController();
3293
- let fence;
3294
- const fenced = new Promise((resolve) => {
3295
- fence = resolve;
3296
- });
3297
- const endAttempt = () => endSuperseded({
3298
- supersede,
3299
- fence
3300
- }, `event ${event.index} for consumer '${event.consumer}' in session '${sessionId}' was cleared`);
3301
- let entry;
3302
- const execution = Promise.race([runEvent(event, supersede.signal, endAttempt, () => {
3303
- entry.completing = true;
3304
- }, sessionHead), fenced]).then((eventOutcome) => {
3305
- if (active.get(key) === entry) active.delete(key);
3306
- if (eventOutcome.status === "processed") processed += 1;
3307
- if (eventOutcome.status === "failed") {
3308
- excluded.set(key, ref);
3309
- sawFailure = true;
3310
- }
3311
- claimAgain ||= eventOutcome.opensLane || eventOutcome.appendsEvents;
3312
- return eventOutcome;
3313
- });
3314
- entry = {
3315
- ref,
3316
- attempt: event.attemptCount,
3317
- execution,
3318
- supersede,
3319
- fence,
3320
- expiresAtMs,
3321
- lapsed: false,
3322
- completing: false
3323
- };
3324
- active.set(key, entry);
3325
- scheduleLapse();
3326
- if (!heartbeat && !stopRenewing) {
3327
- heartbeat = setInterval(() => void renew(), DRAIN_TIMINGS.claimHeartbeatMs);
3328
- heartbeat.unref?.();
3329
- }
3330
- };
3331
- let outcome = "settled";
3332
- let shouldClaim = true;
3333
- try {
3334
- for (;;) {
3335
- const signalVersion = signal?.version ?? 0;
3336
- let claim;
3337
- if (shouldClaim) {
3338
- const window = nextClaimWindow();
3339
- if (window.pastDeadline) {
3340
- outcome = "busy";
3341
- break;
3342
- }
3343
- claim = await telemetry.span("a2.claim", {
3344
- "a2.contract": name,
3345
- "a2.session_id": sessionId
3346
- }, async (claimSpan) => {
3347
- const result = await store.claimAvailable({
3348
- sessionId: ns,
3349
- holder,
3350
- ttlMs: window.ttlMs,
3351
- maxFailures: MAX_FAILURES,
3352
- ...window.deadlineCapped ? { expiresAtMs: window.expiresAtMs } : {},
3353
- consumers: only ? [storeConsumerOf(only)] : storeConsumers,
3354
- ...through === void 0 ? {} : { through },
3355
- ...excluded.size === 0 ? {} : { exclude: [...excluded.values()] }
3356
- });
3357
- claimSpan.setAttribute("a2.claim.outcome", result.outcome);
3358
- claimSpan.setAttribute("a2.claim.count", result.outcome === "claimed" ? result.events.length : 0);
3359
- return result;
3360
- });
3361
- if (claim.outcome === "claimed") {
3362
- const runnable = claim.events.filter((event) => event.failedAt === null);
3363
- for (const event of claim.events) if (event.failedAt !== null) await reportExhausted(event);
3364
- if (runnable.length > 0) requestWatchdog(window.watchdogAtMs);
3365
- if (window.deadlineCapped) stopRenewing = true;
3366
- for (const event of runnable) start(event, window.expiresAtMs, claim.head);
3367
- shouldClaim = false;
3368
- }
3369
- }
3370
- if (claim?.outcome === "claimed" && [...active.values()].some((entry) => entry.lapsed)) {
3371
- shouldClaim = true;
3372
- continue;
3373
- }
3374
- if (active.size > 0) {
3375
- const wake = signal?.wait(signalVersion);
3376
- const hasLapsed = [...active.values()].some((entry) => entry.lapsed);
3377
- const retry = claim?.outcome === "busy" && hasLapsed ? defaultSleep(Math.max(0, claim.retryAt.getTime() - Date.now())) : void 0;
3378
- const retryDue = await Promise.race([
3379
- ...[...active.values()].map((entry) => entry.execution.then(() => false)),
3380
- ...wake ? [wake.promise.then(() => false)] : [],
3381
- ...retry ? [retry.promise.then(() => true)] : []
3382
- ]);
3383
- wake?.cancel();
3384
- retry?.cancel();
3385
- shouldClaim = retryDue || claimAgain || active.size === 0 || hasLapsed || signal !== void 0 && signal.version !== signalVersion;
3386
- claimAgain = false;
3387
- continue;
3388
- }
3389
- if (!shouldClaim) {
3390
- shouldClaim = true;
3391
- continue;
3392
- }
3393
- if (claim === void 0) continue;
3394
- if (signal && signal.version !== signalVersion) continue;
3395
- if (claimAgain) {
3396
- claimAgain = false;
3397
- continue;
3398
- }
3399
- if (claim.outcome === "busy") {
3400
- requestWatchdog(claim.retryAt.getTime() + DRAIN_TIMINGS.watchdogGraceMs);
3401
- outcome = "busy";
3402
- } else if (sawFailure) outcome = "stalled";
3403
- if (signal) signal.closed = true;
3404
- break;
3405
- }
3406
- } catch (error) {
3407
- if (!handOffFailure || schedulerArm === void 0) throw error;
3408
- span.recordError(error);
3409
- outcome = "failed";
3410
- } finally {
3411
- if (signal) signal.closed = true;
3412
- stopRenewing = true;
3413
- if (heartbeat) clearInterval(heartbeat);
3414
- if (retryTimer) clearTimeout(retryTimer);
3415
- await renewal;
3416
- await Promise.allSettled([...active.values()].map((entry) => entry.execution));
3417
- if (lapseTimer) clearTimeout(lapseTimer);
3418
- }
3419
- span.setAttribute("a2.drain.processed", processed);
3420
- span.setAttribute("a2.drain.outcome", outcome);
3421
- return {
3422
- settled: outcome === "settled",
3423
- outcome,
3424
- processed,
3425
- ...schedulerArm ? { schedulerArm } : {}
3426
- };
3427
- });
3428
- const appendExternal = async (sessionId, mode, events, requireDurableInitialArm = false, condition = {}) => {
3429
- return appendCore(sessionId, events, "external", mode, (_rows, watchdogDueAt) => scheduleDrain(sessionId, watchdogDueAt), void 0, void 0, requireDurableInitialArm, condition);
3430
- };
3431
- const session = (id) => {
3432
- assertSessionId(id);
3433
- const appendInline = async (...events) => appendExternal(id, "inline", events);
3434
- const appendDispatch = async (...events) => appendExternal(id, "dispatch", events);
3435
- const appendIfLastIndex = async (index, ...events) => {
3436
- assertIfLastIndex(index);
3437
- if (events.length === 0) throw new TypeError("append.ifLastIndex requires at least one event");
3438
- return appendExternal(id, "inline", events, false, { ifLastIndex: index });
3439
- };
3440
- const append = Object.assign(appendInline, {
3441
- dispatch: appendDispatch,
3442
- ifLastIndex: appendIfLastIndex
3443
- });
3444
- return Object.assign(makeSession(id, append, null), {
3445
- deadLetters: () => listDeadLetters(id),
3446
- redrive: (target, redriveOptions) => redriveEvent(id, target, redriveOptions)
3447
- });
3448
- };
3449
- const historyPage = async (sessionId, bounds) => {
3450
- assertSessionId(sessionId);
3451
- const rows = await readHistory(sessionId, bounds);
3452
- const marker = rows[0] && isSessionCleared(rows[0]) ? rows[0] : void 0;
3453
- return {
3454
- events: (marker ? rows.slice(1) : rows).map(toPublic),
3455
- ...marker ? { clearIndex: marker.index } : {}
3456
- };
3457
- };
3458
- const self = {
3459
- contract: serverContract,
3460
- fetch: createServerFetch({
3461
- contract: serverContract,
3462
- session,
3463
- historyPage
3464
- }),
3465
- session,
3466
- async drain(sessionId) {
3467
- assertSessionId(sessionId);
3468
- const { settled } = await drainSession(sessionId);
3469
- return { settled };
3470
- }
3471
- };
3472
- serverInternals.set(self, {
3473
- settle: async () => {
3474
- while (inFlight.size > 0) await Promise.allSettled(inFlight);
3475
- },
3476
- schedulerDrain: (sessionId, opts) => {
3477
- assertSessionId(sessionId);
3478
- return drainSession(sessionId, {
3479
- watchdogDueAt: opts?.watchdogDueAt,
3480
- handOffFailure: true
3481
- });
3482
- },
3483
- schedulerAppend: async (sessionId, events, originIndex) => {
3484
- if (!scheduler) throw new TypeError("scheduled append delivery requires a configured scheduler adapter");
3485
- assertSessionId(sessionId);
3486
- try {
3487
- await appendExternal(sessionId, "inline", [...events], true, originIndex === void 0 ? {} : { originIndex });
3488
- } catch (error) {
3489
- if (originIndex !== void 0 && error instanceof A2Error && error.code === "SESSION_CLEARED") return;
3490
- throw error;
3491
- }
3492
- },
3493
- historyWithMarkers: async (sessionId, gte) => (await readHistory(sessionId, { gte })).map(toPublic),
3494
- schedulerClear: async (sessionId, ifLastIndex) => {
3495
- assertSessionId(sessionId);
3496
- assertIfLastIndex(ifLastIndex);
3497
- await clearSession(sessionId, { ifLastIndex }, void 0);
3498
- }
3499
- });
3500
- return self;
3501
- }
3502
- function assertSessionId(id) {
3503
- if (typeof id !== "string" || id.length === 0) throw new TypeError("session id must be a non-empty string");
3504
- if (id.includes(NS)) throw new TypeError("session id contains a reserved control character");
3505
- }
3506
- function assertHistoryIndex(name, value) {
3507
- if (value !== void 0 && (!Number.isSafeInteger(value) || value < 0)) throw new TypeError(`history.${name} must be a non-negative safe integer`);
3508
- }
3509
- function assertStreamIndex(value) {
3510
- if (!Number.isSafeInteger(value) || value < 0) throw new TypeError("stream.startAfter must be a non-negative safe integer");
3511
- }
3512
- function assertStateIndex(value) {
3513
- if (!Number.isSafeInteger(value) || value < 0) throw new TypeError("state.through must be a non-negative safe integer");
3514
- }
3515
- function assertConsumeIndex(value) {
3516
- if (!Number.isSafeInteger(value) || value < 0) throw new TypeError("consume through must be a non-negative safe integer");
3517
- }
3518
- function assertRedriveIndex(value) {
3519
- if (!Number.isSafeInteger(value) || value < 1) throw new TypeError("redrive requires a positive safe-integer index");
3520
- }
3521
- function assertIfLastIndex(value) {
3522
- if (!Number.isSafeInteger(value) || value < 0) throw new TypeError("ifLastIndex must be a non-negative safe integer");
3523
- }
3524
- function assertAppendName(name) {
3525
- if (typeof name !== "string" || name.length === 0) throw new TypeError("consumer append name must be a non-empty string");
3526
- }
3527
- function assertScheduleName(name) {
3528
- if (typeof name !== "string" || name.length === 0) throw new TypeError("schedule name must be a non-empty string");
3529
- }
3530
- const SCHEDULE_DELAY = /^(?:0|[1-9]\d*)(?:\.\d+)?(ms|s|m|h|d)$/;
3531
- const SCHEDULE_DELAY_MULTIPLIER = {
3532
- ms: 1,
3533
- s: 1e3,
3534
- m: 6e4,
3535
- h: 36e5,
3536
- d: 864e5
3537
- };
3538
- function scheduleDueAt(timing, baseTime) {
3539
- if (timing === null || typeof timing !== "object" || Array.isArray(timing)) throw new TypeError("schedule timing must contain exactly one of 'delay' or 'at'");
3540
- const record = timing;
3541
- const hasDelay = Object.hasOwn(record, "delay");
3542
- const hasAt = Object.hasOwn(record, "at");
3543
- if (hasDelay === hasAt) throw new TypeError("schedule timing must contain exactly one of 'delay' or 'at'");
3544
- let dueAt;
3545
- if (hasAt) {
3546
- const at = record["at"];
3547
- if (!(at instanceof Date) || !Number.isFinite(at.getTime())) throw new TypeError("schedule at must be a valid Date");
3548
- dueAt = at.getTime();
3549
- } else {
3550
- const delay = record["delay"];
3551
- if (typeof delay !== "string") throw new TypeError("schedule delay must use ms, s, m, h, or d (for example '30s')");
3552
- const match = SCHEDULE_DELAY.exec(delay);
3553
- const amount = match ? Number(delay.slice(0, -match[1].length)) : NaN;
3554
- if (!match || !Number.isFinite(amount) || amount <= 0) throw new TypeError("schedule delay must be positive and use ms, s, m, h, or d (for example '30s')");
3555
- dueAt = baseTime + amount * SCHEDULE_DELAY_MULTIPLIER[match[1]];
3556
- }
3557
- if (!Number.isFinite(dueAt)) throw new TypeError("schedule due time must be a finite epoch time");
3558
- return dueAt;
3559
- }
3560
- function assertScheduledPayload(payload) {
3561
- try {
3562
- if (isJsonValue(payload, /* @__PURE__ */ new WeakSet())) return;
3563
- } catch {}
3564
- throw new TypeError("session.schedule event payload must be JSON-serializable");
3565
- }
3566
- function cloneScheduledPayload(payload) {
3567
- assertScheduledPayload(payload);
3568
- try {
3569
- const cloned = structuredClone(payload);
3570
- const encoded = JSON.stringify(cloned);
3571
- if (encoded === void 0) throw new TypeError();
3572
- return JSON.parse(encoded);
3573
- } catch {
3574
- throw new TypeError("session.schedule event payload must be JSON-serializable");
3575
- }
3576
- }
3577
- function isJsonValue(value, ancestors) {
3578
- if (value === null) return true;
3579
- if (typeof value === "string" || typeof value === "boolean") return true;
3580
- if (typeof value === "number") return Number.isFinite(value) && !Object.is(value, -0);
3581
- if (typeof value !== "object") return false;
3582
- if (ancestors.has(value)) return false;
3583
- ancestors.add(value);
3584
- try {
3585
- if (Array.isArray(value)) {
3586
- const keys = Reflect.ownKeys(value);
3587
- if (keys.length !== value.length + 1 || !keys.includes("length")) return false;
3588
- for (let index = 0; index < value.length; index += 1) {
3589
- const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
3590
- if (!descriptor || !descriptor.enumerable || !("value" in descriptor) || !isJsonValue(descriptor.value, ancestors)) return false;
3591
- }
3592
- return true;
3593
- }
3594
- if (Object.getPrototypeOf(value) !== Object.prototype) return false;
3595
- for (const key of Reflect.ownKeys(value)) {
3596
- if (typeof key !== "string") return false;
3597
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
3598
- if (!descriptor || !descriptor.enumerable || !("value" in descriptor) || !isJsonValue(descriptor.value, ancestors)) return false;
3599
- }
3600
- return true;
3601
- } finally {
3602
- ancestors.delete(value);
3603
- }
3604
- }
3605
- const measuredBytes = (reducer, state, index, snapshots) => JSON.stringify(snapshots.find((snapshot) => snapshot.index === index)?.state ?? encodeState({
3606
- reducer,
3607
- state
3608
- }))?.length ?? 0;
3609
- const stateCacheKey = (sessionId, reducerName) => `${sessionId}\u0000${reducerName}`;
3610
- //#endregion
3611
- export { deliverSchedulerClear as i, createServer as n, deliverSchedulerAppend as r, consumer as t };