@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,3895 +0,0 @@
1
- import { c as externalMessageKey } from "./external-D3p5T57R.mjs";
2
- import { n as setOwn } from "./own-OwgPWdmh.mjs";
3
- import { a as duplicateBatchError, c as sessionClearedError, l as supersededAttemptError, n as CLEAR_EVENT_TYPE, s as lastIndexMismatchError, t as A2Error } from "./session-clear-XJYpmUpg-2q8l_FJR.mjs";
4
- import { m as nullProtoRecord, n as NOTIFY_TIMINGS, v as stateTailReaders } from "./internal-CvsrprnU-zZMpDiRY.mjs";
5
- import { i as presenceTombstones, n as isSerializedEvent, r as parseSerializedEvent, t as bufferedEvents } from "./stream-buffer-DrTyiIuo-Be10yOBR.mjs";
6
- import { i as streamActivities, n as defaultSleep, r as pollingStream, t as createStreamActivity } from "./store-polling-BZt2Rf3D-Div-bJ_D.mjs";
7
- import { t as retryableLazy } from "./retryable-lazy-DZWmHpii-DpTc5PIP.mjs";
8
- import { i as syncReads, n as project, r as projectSync, t as concernedMessageId } from "./project-CQ4VUibA.mjs";
9
- import { i as idempotentReplay, n as decodeCause } from "./store-codec-pAG2oPgQ-SqDXlPBR.mjs";
10
- import { t as pollPresence } from "./store-presence-polling-JuAy2Ck2-Dh-g_KYM.mjs";
11
- //#region ../../node_modules/.pnpm/experimental-a2@0.24.0_@upstash+qstash@2.12.0_@vercel+queue@0.7.0_ai@7.0.130_zod@4.6.5__b1e2c243a963f2620a5d202817417c26/node_modules/experimental-a2/dist/store-redis-notify-ys_-VrSP.js
12
- const key = ({ participant, field }) => JSON.stringify([participant, field]);
13
- function presenceRecovery({ read, deliver, isActive }) {
14
- const fields = /* @__PURE__ */ new Map();
15
- const deleted = presenceTombstones();
16
- const reading = /* @__PURE__ */ new Set();
17
- let generation = 0;
18
- let latest;
19
- const remember = ({ participant, field, seen, at }) => {
20
- const id = key({
21
- participant,
22
- field
23
- });
24
- const previous = fields.get(id);
25
- if (!previous || previous.at.getTime() < at.getTime() || previous.at.getTime() === at.getTime() && previous.seen !== seen) fields.set(id, {
26
- participant,
27
- field,
28
- seen,
29
- at
30
- });
31
- };
32
- const snapshot = async ({ reconcile }) => {
33
- const run = generation;
34
- const before = new Map(fields);
35
- const changed = /* @__PURE__ */ new Set();
36
- reading.add(changed);
37
- try {
38
- const rows = await read();
39
- if (!isActive()) return rows;
40
- if (run !== generation) return latest;
41
- const current = rows.filter((row) => !deleted.outranks(row));
42
- const live = /* @__PURE__ */ new Set();
43
- for (const row of current) {
44
- const id = key(row);
45
- live.add(id);
46
- if (changed.has(id)) continue;
47
- deleted.drop(row);
48
- remember(row);
49
- if (reconcile) deliver({
50
- participant: row.participant,
51
- values: { [row.field]: row.value },
52
- seen: row.seen,
53
- at: row.at
54
- });
55
- }
56
- if (reconcile) for (const [id, prior] of before) {
57
- if (live.has(id) || changed.has(id) || fields.get(id) !== prior) continue;
58
- fields.delete(id);
59
- deleted.keep(prior);
60
- deliver({
61
- participant: prior.participant,
62
- values: { [prior.field]: null },
63
- seen: prior.seen,
64
- at: prior.at
65
- });
66
- }
67
- return current;
68
- } finally {
69
- reading.delete(changed);
70
- if (reading.size === 0) latest = void 0;
71
- }
72
- };
73
- return {
74
- async read() {
75
- let pending = latest;
76
- while (pending) {
77
- await pending;
78
- if (latest === pending) break;
79
- pending = latest;
80
- }
81
- return snapshot({ reconcile: false });
82
- },
83
- async reconnect() {
84
- generation += 1;
85
- latest = snapshot({ reconcile: true });
86
- await latest;
87
- },
88
- update(patch) {
89
- for (const [field, value] of Object.entries(patch.values)) {
90
- if (value === void 0) continue;
91
- const write = {
92
- participant: patch.participant,
93
- field,
94
- at: patch.at
95
- };
96
- const id = key(write);
97
- const previous = fields.get(id);
98
- if (previous && previous.at.getTime() > patch.at.getTime()) continue;
99
- if (deleted.outranks(write)) continue;
100
- for (const changed of reading) changed.add(id);
101
- if (value === null) {
102
- fields.delete(id);
103
- deleted.keep(write);
104
- } else {
105
- deleted.drop(write);
106
- remember({
107
- ...write,
108
- seen: patch.seen
109
- });
110
- }
111
- }
112
- }
113
- };
114
- }
115
- const FEED_PAGE_SIZE = 1e3;
116
- const READ_CONCURRENCY = 16;
117
- /** The key layout this core writes; any other is rejected. */
118
- const REDIS_LAYOUT = "tagged-1";
119
- /**
120
- * Upstash runs a script under a database-wide lock unless it opts into
121
- * locking only its keys' hash tags. Redis and Valkey reject the flag, and
122
- * have no such lock to opt out of: one thread runs every command.
123
- */
124
- const KEY_LOCKING$1 = "#!lua flags=allow-key-locking";
125
- const READ_ONLY_KEY_LOCKING$1 = "#!lua flags=no-writes,allow-key-locking";
126
- const SHEBANG_REJECTED$1 = /shebang|unexpected symbol near '#'/i;
127
- const META_CHUNK_SIZE = 1e3;
128
- /** A head row's dispatch columns, in the order scripts return them. */
129
- const HEAD_COLUMNS = `{ 'd', 'fc', 'lc', 'ch', 'ce', 'a', 'lf', 'lfa', 'e', 'f' }`;
130
- /**
131
- * Issues a variadic command in calls of at most 1000 arguments, since Lua's
132
- * `unpack` is bounded by its stack, and concatenates table replies. An even
133
- * slice size keeps HSET's field/value pairs together.
134
- */
135
- const SLICED_LUA = `
136
- local function sliced(command, key, args)
137
- local results = {}
138
- for first = 1, #args, 1000 do
139
- local last = math.min(first + 999, #args)
140
- local reply
141
- if key then
142
- reply = redis.call(command, key, unpack(args, first, last))
143
- else
144
- reply = redis.call(command, unpack(args, first, last))
145
- end
146
- if type(reply) == 'table' then
147
- for _, value in ipairs(reply) do results[#results + 1] = value end
148
- end
149
- end
150
- return results
151
- end
152
- `;
153
- /**
154
- * Upstash bills every call a script makes, so scripts read the counter,
155
- * clear marker, typed-type index, and event-id owners with one MGET
156
- * (`read_bounds`), read rows with one HMGET per chunk
157
- * (`read_rows`), and buffer hash writes (`put`, `drop`) into one HSET and
158
- * one HDEL per hash (`flush`). Buffered writes are invisible to reads until
159
- * flushed, so a script must not read a field it has buffered. Every script
160
- * binds KEYS[1] to the session's counter and derives the session's other
161
- * keys, which share its hash tag.
162
- */
163
- const BASE_LUA = `${SLICED_LUA}
164
- local COUNTER = KEYS[1]
165
- local SESSION = string.sub(COUNTER, 1, -6)
166
- local LOG, CLEAR = SESSION .. 'log', SESSION .. 'clear'
167
- local META, READY, CURSORS = SESSION .. 'heads', SESSION .. 'runnable', SESSION .. 'cursors'
168
- local PIN_COUNTS, TYPED = SESSION .. 'pins', SESSION .. 'typed'
169
- local CLEAR_TYPE = '${CLEAR_EVENT_TYPE}'
170
- local total, boundary = 0, 0
171
- -- The event types typed log cursors read: type → { from, last }. The type's
172
- -- index holds every event of it above \`from\`, and no event of it lies above
173
- -- \`last\`.
174
- local typed, typed_dirty = {}, false
175
- -- One key per event id holds the index it names in this session. The
176
- -- \`id:\` namespace keeps a raw id from spelling another session key.
177
- local function id_key(id) return SESSION .. 'id:' .. id end
178
- -- Reads the counter, the latest clear marker, the typed types, and the
179
- -- owners of \`ids\` in one MGET. Returns each id's index, or false.
180
- local function read_bounds(ids)
181
- local keys = { COUNTER, CLEAR, TYPED }
182
- for _, id in ipairs(ids or {}) do keys[#keys + 1] = id_key(id) end
183
- local values = sliced('MGET', nil, keys)
184
- total = tonumber(values[1] or values[2] or '0')
185
- boundary = tonumber(values[2] or '0')
186
- if values[3] then typed = cjson.decode(values[3]) end
187
- local owners = {}
188
- for i = 4, #keys do owners[i - 3] = values[i] end
189
- return owners
190
- end
191
- -- Event-id owners from read_bounds: an id recorded below the latest clear
192
- -- is free.
193
- local function owners_of(values)
194
- local owners = {}
195
- for i = 1, #values do
196
- local owner = values[i]
197
- if owner and tonumber(owner) < boundary then owner = false end
198
- owners[i] = owner
199
- end
200
- return owners
201
- end
202
- local function entry_index(id) return tonumber(string.match(id, '^(%d+)')) end
203
- local function cid_of(consumer, tag)
204
- return tostring(string.len(consumer)) .. ':' .. consumer .. tag
205
- end
206
- local function parse_cid(cid)
207
- local colon = string.find(cid, ':', 1, true)
208
- local n = tonumber(string.sub(cid, 1, colon - 1))
209
- return string.sub(cid, colon + 1, colon + n), string.sub(cid, colon + n + 1)
210
- end
211
- -- A cursor's rows: its consumer, then '#' for an event cursor or 'L' .. lane
212
- -- for a lane or log cursor, as requests name it.
213
- local function row_of(consumer, tag)
214
- local kind = string.sub(tag, 1, 1)
215
- if kind == '#' then return cid_of(consumer, '#') end
216
- if kind == 'G' then return cid_of(consumer, 'L' .. string.sub(tag, 2)) end
217
- return cid_of(consumer, tag)
218
- end
219
- local function chunk_key(idx)
220
- return META .. ':' .. tostring(math.floor((idx - 1) / ${META_CHUNK_SIZE}))
221
- end
222
- local function row_name(idx, row, suffix)
223
- return tostring(idx) .. ':' .. row .. ':' .. suffix
224
- end
225
- -- Rows of (index, row) refs, aligned with refs; one HMGET per chunk.
226
- local function read_rows(refs, suffixes)
227
- local groups, order = {}, {}
228
- for position, ref in ipairs(refs) do
229
- local key = chunk_key(ref[1])
230
- local group = groups[key]
231
- if not group then
232
- group = { positions = {}, names = {} }
233
- groups[key] = group
234
- order[#order + 1] = key
235
- end
236
- group.positions[#group.positions + 1] = position
237
- for _, suffix in ipairs(suffixes) do
238
- group.names[#group.names + 1] = row_name(ref[1], ref[2], suffix)
239
- end
240
- end
241
- local rows = {}
242
- for _, key in ipairs(order) do
243
- local group = groups[key]
244
- local values = sliced('HMGET', key, group.names)
245
- for n, position in ipairs(group.positions) do
246
- local row = {}
247
- for column = 1, #suffixes do row[column] = values[(n - 1) * #suffixes + column] end
248
- rows[position] = row
249
- end
250
- end
251
- return rows
252
- end
253
- local writes, write_order, deletes, delete_order = {}, {}, {}, {}
254
- local function put(key, field, value)
255
- local fields = writes[key]
256
- if not fields then
257
- fields = {}
258
- writes[key] = fields
259
- write_order[#write_order + 1] = key
260
- end
261
- fields[#fields + 1] = field
262
- fields[#fields + 1] = value
263
- end
264
- local function drop(key, field)
265
- local fields = deletes[key]
266
- if not fields then
267
- fields = {}
268
- deletes[key] = fields
269
- delete_order[#delete_order + 1] = key
270
- end
271
- fields[#fields + 1] = field
272
- end
273
- local function flush()
274
- for _, key in ipairs(write_order) do sliced('HSET', key, writes[key]) end
275
- for _, key in ipairs(delete_order) do sliced('HDEL', key, deletes[key]) end
276
- writes, write_order, deletes, delete_order = {}, {}, {}, {}
277
- end
278
- local function put_row(idx, row, suffix, value)
279
- put(chunk_key(idx), row_name(idx, row, suffix), value)
280
- end
281
- local function drop_row(idx, row, suffix)
282
- drop(chunk_key(idx), row_name(idx, row, suffix))
283
- end
284
- -- A request names a cursor by tag: '#' for an event cursor, 'L' .. lane for a
285
- -- lane or log cursor. A claimed row records its kind: '#', or the cursor's tag.
286
- local function owns(kind, tag)
287
- if not kind then return false end
288
- if tag == '#' then return kind == '#' end
289
- return kind == tag or kind == 'G' .. string.sub(tag, 2)
290
- end
291
- local function cid_for(consumer, kind, idx)
292
- if kind == '#' then return cid_of(consumer, '#' .. tostring(idx)) end
293
- return cid_of(consumer, kind)
294
- end
295
- -- One type's index, named by the type's bytes in hex so no type can spell
296
- -- another key of the session.
297
- local function type_key(name)
298
- return SESSION .. 'type:' .. (string.gsub(name, '.', function(c)
299
- return string.format('%02x', string.byte(c))
300
- end))
301
- end
302
- local ready_changes, ready_order = {}, {}
303
- local function ready_set(cid, score)
304
- if ready_changes[cid] == nil then ready_order[#ready_order + 1] = cid end
305
- ready_changes[cid] = score
306
- end
307
- local function flush_ready()
308
- local adds, removes = {}, {}
309
- for _, cid in ipairs(ready_order) do
310
- local score = ready_changes[cid]
311
- if score then
312
- adds[#adds + 1] = score
313
- adds[#adds + 1] = cid
314
- else
315
- removes[#removes + 1] = cid
316
- end
317
- end
318
- sliced('ZADD', READY, adds)
319
- sliced('ZREM', READY, removes)
320
- ready_changes, ready_order = {}, {}
321
- end
322
- local function release_pins(idx, row, pins)
323
- if not pins or pins == '' then return end
324
- for _, ref in ipairs(cjson.decode(pins)) do
325
- local count = redis.call('HINCRBY', PIN_COUNTS, ref, -1)
326
- if count <= 0 then
327
- redis.call('HDEL', PIN_COUNTS, ref)
328
- local checkpoint = cjson.decode(ref)
329
- redis.call('ZREMRANGEBYSCORE', checkpoint[1], checkpoint[2], checkpoint[2])
330
- end
331
- end
332
- put_row(idx, row, 'pins', '')
333
- end
334
- `;
335
- /**
336
- * Cursor movement for scripts that add events or move cursors. Lane and log
337
- * cursor records are read once per script (`load_states`) and written back
338
- * once (`flush_states`). A record whose head lies at or below the latest clear
339
- * marker is idle, and a log cursor counts from the marker.
340
- *
341
- * A typed log cursor finds its next head in its types' indexes, one bounded
342
- * lookup per type, skipped when `typed` shows no newer event of it. When an
343
- * index does not reach back far enough yet (a typed backfill, or a type a
344
- * cursor newly reads), the lookup returns the type, and the script returns
345
- * `{ 'index', type, after }` before writing anything: the caller indexes
346
- * that type down to `after` (INDEX_TYPE_LUA, one page per call) and runs the
347
- * operation again.
348
- */
349
- const CURSOR_LUA = `
350
- local served_all, served_set, served_logs = true, {}, {}
351
- local pending_fast = false
352
- local function types_of(raw)
353
- if not raw or raw == '*' then return nil end
354
- local set = {}
355
- for _, name in ipairs(cjson.decode(raw)) do set[name] = true end
356
- return set
357
- end
358
- local function takes(types, kind)
359
- return kind ~= CLEAR_TYPE and (types == nil or types[kind] == true)
360
- end
361
- -- The served consumers: '' for every consumer, else [[name] or
362
- -- [name, lane, typesJson or '*', backfill]].
363
- local function use_served(raw)
364
- if raw == '' then return end
365
- served_all = false
366
- for _, entry in ipairs(cjson.decode(raw)) do
367
- served_set[entry[1]] = true
368
- if entry[2] then
369
- served_logs[#served_logs + 1] = {
370
- name = entry[1], lane = entry[2], ty = entry[3],
371
- types = types_of(entry[3]), backfill = entry[4] == 1,
372
- }
373
- end
374
- end
375
- end
376
- local function served_has(name) return served_all or served_set[name] == true end
377
- -- Whether a served consumer has a live head. Newest heads come first: a
378
- -- removed consumer's backlog is older than the work a deployment serves.
379
- local function has_pending()
380
- if pending_fast then return '1' end
381
- if served_all then return redis.call('ZCOUNT', READY, 1, '+inf') > 0 and '1' or '0' end
382
- if next(served_set) == nil then return '0' end
383
- local page = redis.call('ZREVRANGEBYSCORE', READY, '+inf', 1, 'LIMIT', 0, 32)
384
- for _, cid in ipairs(page) do
385
- if served_set[(parse_cid(cid))] then return '1' end
386
- end
387
- if #page < 32 then return '0' end
388
- for _, cid in ipairs(redis.call('ZREVRANGEBYSCORE', READY, '+inf', 1, 'LIMIT', 32, -1)) do
389
- if served_set[(parse_cid(cid))] then return '1' end
390
- end
391
- return '0'
392
- end
393
- local function targets_of(raw)
394
- if raw == '' then return {} end
395
- return cjson.decode(raw)
396
- end
397
- -- Starts indexing a type: every later event of it.
398
- local function register(name, from)
399
- typed[name] = { from, from }
400
- typed_dirty = true
401
- end
402
- -- The first stored event in (after, total] of a type in \`types\` (nil: any
403
- -- type), or false. Nil and a type when that type's index can't answer yet.
404
- local function stored_head(after, types)
405
- if types == nil then
406
- if after + 1 <= total then return after + 1 end
407
- return false
408
- end
409
- local best = false
410
- for name in pairs(types) do
411
- local entry = typed[name]
412
- if entry == nil then
413
- if after < total then return nil, name end
414
- register(name, total)
415
- elseif entry[2] > after then
416
- if entry[1] > after then return nil, name end
417
- local found = redis.call('ZRANGEBYSCORE', type_key(name),
418
- '(' .. tostring(after), tostring(total), 'LIMIT', 0, 1)
419
- if #found > 0 then
420
- local idx = tonumber(found[1])
421
- if not best or idx < best then best = idx end
422
- end
423
- end
424
- end
425
- return best
426
- end
427
- -- The first event after \`after\` a log cursor takes: stored, then in the
428
- -- batch being appended.
429
- local function next_log_head(after, types, batch)
430
- local head, missing = stored_head(after, types)
431
- if head == nil then return nil, missing end
432
- if head then return head end
433
- for _, event in ipairs(batch) do
434
- if event.idx > after and takes(types, event.type) then return event.idx end
435
- end
436
- return false
437
- end
438
- -- Indexes a batch's events of the types typed log cursors read.
439
- local function index_batch(batch)
440
- local adds, order = {}, {}
441
- for _, event in ipairs(batch) do
442
- local entry = typed[event.type]
443
- if entry then
444
- local list = adds[event.type]
445
- if not list then
446
- list = {}
447
- adds[event.type] = list
448
- order[#order + 1] = event.type
449
- end
450
- list[#list + 1] = event.idx
451
- list[#list + 1] = tostring(event.idx)
452
- entry[2] = event.idx
453
- typed_dirty = true
454
- end
455
- end
456
- for _, name in ipairs(order) do sliced('ZADD', type_key(name), adds[name]) end
457
- end
458
- local states, state_order = {}, {}
459
- local function load_states(cids)
460
- local need, names = {}, {}
461
- for _, cid in ipairs(cids) do
462
- local state = states[cid]
463
- if (state == nil or state.partial) and not need[cid] then
464
- need[cid] = true
465
- need[#need + 1] = cid
466
- names[#names + 1] = cid .. ':h'
467
- names[#names + 1] = cid .. ':p'
468
- names[#names + 1] = cid .. ':t'
469
- names[#names + 1] = cid .. ':ty'
470
- end
471
- end
472
- if #need == 0 then return end
473
- local values = sliced('HMGET', CURSORS, names)
474
- for n, cid in ipairs(need) do
475
- local h, p, t, ty = values[n * 4 - 3], values[n * 4 - 2], values[n * 4 - 1], values[n * 4]
476
- local tail = (t and t ~= '') and tonumber(t) or false
477
- local state = states[cid]
478
- if state then
479
- state.t = tail
480
- state.partial = nil
481
- else
482
- local _, tag = parse_cid(cid)
483
- state = {
484
- kind = string.sub(tag, 1, 1), exists = p ~= false,
485
- h = (h and h ~= '') and tonumber(h) or false,
486
- p = tonumber(p or '0'), t = tail, ty = ty or false,
487
- }
488
- if state.h and state.h <= boundary then state.h = false end
489
- if state.kind == 'G' and state.exists and state.p < boundary then state.p = boundary end
490
- states[cid] = state
491
- state_order[#state_order + 1] = cid
492
- end
493
- end
494
- end
495
- local function flush_states()
496
- for _, cid in ipairs(state_order) do
497
- local state = states[cid]
498
- if state.dirty then
499
- put(CURSORS, cid .. ':h', state.h and tostring(state.h) or '')
500
- put(CURSORS, cid .. ':p', tostring(state.p))
501
- if state.kind == 'L' then
502
- if not state.partial then put(CURSORS, cid .. ':t', state.t and tostring(state.t) or '') end
503
- elseif state.ty then
504
- put(CURSORS, cid .. ':ty', state.ty)
505
- end
506
- end
507
- end
508
- end
509
- -- Moves a cursor past its head \`idx\`. \`kind\` is the head row's kind;
510
- -- \`batch\` is the returned events, appended after the stored log. Writes
511
- -- nothing; returns nil and a type when that type's index must reach back
512
- -- to \`idx\` first.
513
- local function advance(consumer, kind, idx, row_next, batch)
514
- if kind == '#' then
515
- ready_set(cid_of(consumer, '#' .. tostring(idx)), false)
516
- return true
517
- end
518
- local cid = cid_of(consumer, kind)
519
- local state = states[cid]
520
- local next_head
521
- if string.sub(kind, 1, 1) == 'L' then
522
- next_head = row_next and tonumber(row_next) or false
523
- if not state then
524
- state = { kind = 'L', exists = true, p = idx, h = false, t = false, ty = false, partial = true }
525
- states[cid] = state
526
- state_order[#state_order + 1] = cid
527
- end
528
- if not next_head then
529
- state.t = false
530
- state.partial = nil
531
- end
532
- else
533
- local lane, raw = string.sub(kind, 2), nil
534
- for _, spec in ipairs(served_logs) do
535
- if spec.name == consumer and spec.lane == lane then raw = spec.ty end
536
- end
537
- if not raw then
538
- load_states({ cid })
539
- raw = states[cid].ty or '*'
540
- end
541
- local head, missing = next_log_head(idx, types_of(raw), batch)
542
- if head == nil then return nil, missing end
543
- next_head = head
544
- state = states[cid]
545
- if not state then
546
- state = { kind = 'G', exists = true, p = idx, h = false, t = false, ty = raw }
547
- states[cid] = state
548
- state_order[#state_order + 1] = cid
549
- end
550
- state.ty = raw
551
- end
552
- state.h = next_head
553
- state.p = idx
554
- state.exists = true
555
- state.dirty = true
556
- ready_set(cid, next_head)
557
- return true
558
- end
559
- -- Reads what an appended batch's cursor work needs: its lane targets'
560
- -- records, and the head of each served log consumer whose types it carries.
561
- -- Writes nothing; returns nil, a type, and an index when that type's index
562
- -- must reach back to the index first.
563
- local log_plan = {}
564
- local function plan(batch, base)
565
- local need = {}
566
- for _, event in ipairs(batch) do
567
- for _, target in ipairs(event.targets) do
568
- if target[2] ~= '#' then need[#need + 1] = cid_of(target[1], target[2]) end
569
- end
570
- end
571
- for _, spec in ipairs(served_logs) do
572
- for _, event in ipairs(batch) do
573
- if takes(spec.types, event.type) then
574
- local cid = cid_of(spec.name, 'G' .. spec.lane)
575
- log_plan[#log_plan + 1] = { spec = spec, first = event.idx, cid = cid }
576
- need[#need + 1] = cid
577
- break
578
- end
579
- end
580
- end
581
- load_states(need)
582
- for _, log in ipairs(log_plan) do
583
- local state, spec = states[log.cid], log.spec
584
- if not state.exists then
585
- if spec.backfill then
586
- local head, missing = stored_head(boundary, spec.types)
587
- if head == nil then return nil, missing, boundary end
588
- log.p, log.h = boundary, head or log.first
589
- else
590
- -- Nothing it takes is stored after its start: index its types from there.
591
- for name in pairs(spec.types or {}) do
592
- if typed[name] == nil then register(name, base) end
593
- end
594
- log.p, log.h = base, log.first
595
- end
596
- elseif not state.h then
597
- -- Not the batch's first: a deployment that doesn't serve this consumer
598
- -- may have appended events it takes since it went idle.
599
- local head, missing = stored_head(state.p, spec.types)
600
- if head == nil then return nil, missing, state.p end
601
- log.h = head or log.first
602
- end
603
- end
604
- return true
605
- end
606
- -- Starts the cursor work \`plan\` read: each event's targets, and each
607
- -- planned log cursor.
608
- local function enqueue(batch)
609
- for _, event in ipairs(batch) do
610
- for _, target in ipairs(event.targets) do
611
- local consumer, tag = target[1], target[2]
612
- if served_has(consumer) then pending_fast = true end
613
- if tag == '#' then
614
- ready_set(cid_of(consumer, '#' .. tostring(event.idx)), event.idx)
615
- else
616
- local cid = cid_of(consumer, tag)
617
- local state = states[cid]
618
- if state.h and state.t then
619
- put_row(state.t, row_of(consumer, tag), 'next', tostring(event.idx))
620
- else
621
- state.h = event.idx
622
- if state.p < boundary then state.p = boundary end
623
- ready_set(cid, event.idx)
624
- end
625
- state.t = event.idx
626
- state.exists = true
627
- state.dirty = true
628
- end
629
- end
630
- end
631
- for _, log in ipairs(log_plan) do
632
- pending_fast = true
633
- local state = states[log.cid]
634
- if not state.exists then
635
- state.exists, state.p, state.h = true, log.p, log.h
636
- ready_set(log.cid, log.h)
637
- elseif not state.h then
638
- state.h = log.h
639
- ready_set(log.cid, log.h)
640
- end
641
- state.ty = log.spec.ty
642
- state.dirty = true
643
- end
644
- end
645
- `;
646
- /**
647
- * KEYS: counter.
648
- * ARGV: sessionId, nowMs, n, served consumers, origin index or '',
649
- * ifLastIndex or '', then per event: id, type, payloadJson, causeJson or '',
650
- * targets.
651
- * Returns ['empty', hasPending] | ['ok', firstIndex, hasPending] |
652
- * ['dup', hasPending, head, ...indexes] | ['partial', count, head] |
653
- * ['superseded', position] | ['cleared', originIndex] | ['moved', head] |
654
- * ['index', type, after].
655
- */
656
- const APPEND_LUA = `${BASE_LUA}${CURSOR_LUA}
657
- local now, n = ARGV[2], tonumber(ARGV[3])
658
- use_served(ARGV[4])
659
- if n == 0 then return { 'empty', has_pending() } end
660
- local ids = {}
661
- for i = 1, n do ids[i] = ARGV[6 + (i - 1) * 5 + 1] end
662
- local owners = owners_of(read_bounds(ids))
663
- local base = total
664
- local dups = {}
665
- for i = 1, n do
666
- if owners[i] then dups[#dups + 1] = owners[i] end
667
- end
668
- if #dups == n then
669
- local res = { 'dup', has_pending(), tostring(total) }
670
- for i = 1, #dups do res[#res + 1] = dups[i] end
671
- return res
672
- end
673
- if #dups > 0 then return { 'partial', tostring(#dups), tostring(total) } end
674
- local origin = ARGV[5]
675
- if origin ~= '' and tonumber(origin) <= boundary then return { 'cleared', origin } end
676
- -- The attempt-currency fence: a cause's head row must still be its cursor's
677
- -- head, at that attempt, not dead-lettered.
678
- local refs, fenced = {}, {}
679
- for i = 1, n do
680
- local raw = ARGV[6 + (i - 1) * 5 + 4]
681
- if raw ~= '' then
682
- local cause = cjson.decode(raw)
683
- local index = tonumber(cause.index)
684
- if index <= boundary then return { 'superseded', tostring(i) } end
685
- local tag = type(cause.lane) == 'string' and ('L' .. cause.lane) or '#'
686
- refs[#refs + 1] = { index, row_of(cause.consumer, tag) }
687
- fenced[#fenced + 1] = {
688
- position = i, consumer = cause.consumer, attempt = tonumber(cause.attempt), tag = tag,
689
- }
690
- end
691
- end
692
- local rows = read_rows(refs, { 'd', 'f', 'p', 'l' })
693
- for k, cause in ipairs(fenced) do
694
- local row = rows[k]
695
- if tonumber(row[1] or '0') ~= cause.attempt or row[2] or row[3] or not owns(row[4], cause.tag) then
696
- return { 'superseded', tostring(cause.position) }
697
- end
698
- if served_has(cause.consumer) then pending_fast = true end
699
- end
700
- local expected = ARGV[6]
701
- if expected ~= '' and tonumber(expected) ~= total then return { 'moved', tostring(total) } end
702
- local batch = {}
703
- for i = 1, n do
704
- local o = 6 + (i - 1) * 5
705
- batch[i] = { idx = base + i, type = ARGV[o + 2], targets = targets_of(ARGV[o + 5]) }
706
- end
707
- local planned, missing, after = plan(batch, base)
708
- if not planned then return { 'index', missing, tostring(after) } end
709
- local marks = {}
710
- for i = 1, n do
711
- local o = 6 + (i - 1) * 5
712
- local field = tostring(base + i)
713
- redis.call('XADD', LOG, field .. '-0',
714
- 'id', ARGV[o + 1], 'type', ARGV[o + 2], 'payload', ARGV[o + 3],
715
- 'created_at', now, 'cause', ARGV[o + 4])
716
- marks[#marks + 1] = id_key(ARGV[o + 1])
717
- marks[#marks + 1] = field
718
- end
719
- index_batch(batch)
720
- enqueue(batch)
721
- marks[#marks + 1] = COUNTER
722
- marks[#marks + 1] = tostring(base + n)
723
- if typed_dirty then
724
- marks[#marks + 1] = TYPED
725
- marks[#marks + 1] = cjson.encode(typed)
726
- end
727
- sliced('MSET', nil, marks)
728
- flush_states()
729
- flush()
730
- flush_ready()
731
- return { 'ok', tostring(base + 1), has_pending() }
732
- `;
733
- /**
734
- * KEYS: counter.
735
- * ARGV: type, after. Indexes one page of the stored log below the type's
736
- * index, toward `after`, registering the type first if no cursor read it
737
- * yet. Returns ['1'] once the index reaches `after`, else ['0'].
738
- */
739
- const INDEX_TYPE_LUA = `${BASE_LUA}
740
- read_bounds()
741
- local name, after = ARGV[1], tonumber(ARGV[2])
742
- local entry = typed[name]
743
- if not entry then
744
- entry = { total, total }
745
- typed[name] = entry
746
- end
747
- -- Entries below the latest clear belong to an old lifetime: never indexed.
748
- local floor = math.max(after, boundary - 1)
749
- if entry[1] > floor then
750
- local entries = redis.call('XREVRANGE', LOG, tostring(entry[1]) .. '-0',
751
- tostring(floor + 1) .. '-0', 'COUNT', 256)
752
- local adds = {}
753
- for _, stored in ipairs(entries) do
754
- local fields = stored[2]
755
- for j = 1, #fields, 2 do
756
- if fields[j] == 'type' then
757
- if fields[j + 1] == name then
758
- local idx = entry_index(stored[1])
759
- adds[#adds + 1] = idx
760
- adds[#adds + 1] = tostring(idx)
761
- end
762
- break
763
- end
764
- end
765
- end
766
- sliced('ZADD', type_key(name), adds)
767
- if #entries < 256 then
768
- entry[1] = after
769
- else
770
- entry[1] = entry_index(entries[#entries][1]) - 1
771
- end
772
- elseif entry[1] > after then
773
- entry[1] = after
774
- end
775
- redis.call('SET', TYPED, cjson.encode(typed))
776
- return { entry[1] <= after and '1' or '0' }
777
- `;
778
- /**
779
- * KEYS: counter.
780
- * ARGV: holder, nowMs, expiresAtMs, maxFailures or '', served consumers,
781
- * the highest head to claim or '', excluded count, then per excluded head:
782
- * consumer, tag.
783
- * Live heads are the ready set's positive scores, so an empty one is enough
784
- * to report 'settled'. A claimed result ends with the clear marker.
785
- */
786
- const CLAIM_AVAILABLE_LUA = `${BASE_LUA}${CURSOR_LUA}
787
- local ready = redis.call('ZRANGEBYSCORE', READY, 1, ARGV[6] == '' and '+inf' or ARGV[6], 'WITHSCORES')
788
- if #ready == 0 then return { 'settled' } end
789
- read_bounds()
790
- local holder, now, expires_at = ARGV[1], tonumber(ARGV[2]), ARGV[3]
791
- local max_failures = tonumber(ARGV[4])
792
- use_served(ARGV[5])
793
- local excluded = {}
794
- for i = 1, tonumber(ARGV[7]) do
795
- excluded[ARGV[7 + (i - 1) * 2 + 1] .. '\\0' .. ARGV[7 + (i - 1) * 2 + 2]] = true
796
- end
797
- local candidates = {}
798
- for i = 1, #ready, 2 do
799
- local cid, idx = ready[i], tonumber(ready[i + 1])
800
- local consumer, tag = parse_cid(cid)
801
- local kind = string.sub(tag, 1, 1)
802
- local key = consumer .. '\\0' .. (kind == 'G' and ('L' .. string.sub(tag, 2)) or tag)
803
- if served_has(consumer) and not excluded[key] then
804
- candidates[#candidates + 1] = {
805
- idx, row_of(consumer, tag), consumer = consumer, cid = cid,
806
- kind = kind == '#' and '#' or tag,
807
- }
808
- end
809
- end
810
- local rows = read_rows(candidates, { 'd', 'fc', 'lc', 'ch', 'ce', 'a', 'lf', 'lfa', 'e', 'f', 'pins' })
811
- local takes_over, retry_at, wanted = {}, nil, {}
812
- for position, candidate in ipairs(candidates) do
813
- local row = rows[position]
814
- local expires = tonumber(row[5] or '0')
815
- if expires > now then
816
- if not retry_at or expires < retry_at then retry_at = expires end
817
- else
818
- takes_over[#takes_over + 1] = { candidate = candidate, row = row }
819
- wanted[candidate[1]] = true
820
- end
821
- end
822
- if #takes_over == 0 then
823
- if retry_at then return { 'busy', tostring(retry_at) } end
824
- return { 'settled' }
825
- end
826
- -- One XRANGE per run of consecutive claimed indexes.
827
- local indexes, entries = {}, {}
828
- for idx in pairs(wanted) do indexes[#indexes + 1] = idx end
829
- table.sort(indexes)
830
- local first = 1
831
- while first <= #indexes do
832
- local last = first
833
- while last < #indexes and indexes[last + 1] == indexes[last] + 1 do last = last + 1 end
834
- local range = redis.call('XRANGE', LOG, tostring(indexes[first]) .. '-0', tostring(indexes[last]) .. '-0')
835
- for _, entry in ipairs(range) do entries[entry_index(entry[1])] = entry end
836
- first = last + 1
837
- end
838
- for _, idx in ipairs(indexes) do
839
- if not entries[idx] then return { 'missing', tostring(idx) } end
840
- end
841
- local result = { 'claimed', tostring(#takes_over) }
842
- for _, take in ipairs(takes_over) do
843
- local candidate, row = take.candidate, take.row
844
- local idx, at = candidate[1], candidate[2]
845
- local attempt = tostring(tonumber(row[1] or '0') + 1)
846
- -- A claim still held here lapsed: its attempt never finished.
847
- local lapsed = row[4] ~= false
848
- local failures = tonumber(row[6] or '0')
849
- if lapsed then
850
- failures = failures + 1
851
- put_row(idx, at, 'a', tostring(failures))
852
- end
853
- put_row(idx, at, 'd', attempt)
854
- local columns
855
- if lapsed and max_failures and failures >= max_failures then
856
- -- That takeover spent the last failed attempt: dead-letter, unclaimed.
857
- -- Advancing the attempt fences the lapsed one; nothing runs.
858
- put_row(idx, at, 'f', ARGV[2])
859
- drop_row(idx, at, 'ch')
860
- drop_row(idx, at, 'ce')
861
- ready_set(candidate.cid, -idx)
862
- release_pins(idx, at, row[11])
863
- columns = { attempt, row[2], row[3], false, false, tostring(failures), row[7], row[8], row[9], ARGV[2] }
864
- else
865
- local first_claimed = row[2] or ARGV[2]
866
- put_row(idx, at, 'fc', first_claimed)
867
- put_row(idx, at, 'lc', ARGV[2])
868
- put_row(idx, at, 'ch', holder)
869
- put_row(idx, at, 'ce', expires_at)
870
- put_row(idx, at, 'l', candidate.kind)
871
- columns = { attempt, first_claimed, ARGV[2], holder, expires_at, tostring(failures), row[7], row[8], row[9], false }
872
- end
873
- result[#result + 1] = { candidate.consumer, candidate.kind, tostring(idx), columns, entries[idx] }
874
- end
875
- flush()
876
- flush_ready()
877
- result[#result + 1] = tostring(boundary)
878
- result[#result + 1] = tostring(total)
879
- return result
880
- `;
881
- /**
882
- * KEYS: counter.
883
- * ARGV: holder, nowMs, expiresAtMs, n, then per claim: consumer, tag, index,
884
- * attempt. Returns [renewedCount, ...renewed, ...superseded] as 1-based
885
- * positions in the request.
886
- */
887
- const RENEW_CLAIMS_LUA = `${BASE_LUA}
888
- read_bounds()
889
- local holder, now, expires_at = ARGV[1], tonumber(ARGV[2]), ARGV[3]
890
- local refs, items, superseded = {}, {}, {}
891
- for i = 1, tonumber(ARGV[4]) do
892
- local o = 4 + (i - 1) * 4
893
- local idx = tonumber(ARGV[o + 3])
894
- if idx <= boundary then
895
- superseded[#superseded + 1] = tostring(i)
896
- else
897
- local row = row_of(ARGV[o + 1], ARGV[o + 2])
898
- refs[#refs + 1] = { idx, row }
899
- items[#items + 1] = { position = i, idx = idx, row = row, tag = ARGV[o + 2], attempt = tonumber(ARGV[o + 4]) }
900
- end
901
- end
902
- local rows = read_rows(refs, { 'd', 'ce', 'p', 'f', 'ch', 'l' })
903
- local renewed = {}
904
- for k, item in ipairs(items) do
905
- local row = rows[k]
906
- local attempt = tonumber(row[1] or '0')
907
- if row[6] and not owns(row[6], item.tag) then
908
- -- Another cursor's head: this one never claimed it.
909
- elseif row[3] or attempt > item.attempt then
910
- superseded[#superseded + 1] = tostring(item.position)
911
- elseif attempt == item.attempt and tonumber(expires_at) > now and
912
- not row[4] and row[5] == holder and tonumber(row[2] or '0') > now then
913
- put_row(item.idx, item.row, 'ce', expires_at)
914
- renewed[#renewed + 1] = tostring(item.position)
915
- end
916
- end
917
- flush()
918
- local result = { tostring(#renewed) }
919
- for i = 1, #renewed do result[#result + 1] = renewed[i] end
920
- for i = 1, #superseded do result[#result + 1] = superseded[i] end
921
- return result
922
- `;
923
- /**
924
- * KEYS: counter.
925
- * ARGV: sessionId, nowMs, consumer, tag, index, attempt, child causeJson,
926
- * served consumers, returned idsJson, n, then per child: id, type,
927
- * payloadJson, targets.
928
- */
929
- const COMPLETE_ATTEMPT_LUA = `${BASE_LUA}${CURSOR_LUA}
930
- local now = ARGV[2]
931
- local consumer, tag, idx, attempt = ARGV[3], ARGV[4], tonumber(ARGV[5]), tonumber(ARGV[6])
932
- local at = row_of(consumer, tag)
933
- local n = tonumber(ARGV[10])
934
- local ids = {}
935
- for i = 1, n do ids[i] = ARGV[10 + (i - 1) * 4 + 1] end
936
- local owners = owners_of(read_bounds(ids))
937
- if idx <= boundary then return { 'superseded' } end
938
- if idx < 1 or idx > total then return { 'missing' } end
939
- local row = read_rows({ { idx, at } }, { 'd', 'p', 'pa', 'ri', 'ch', 'f', 'l', 'next', 'pins' })[1]
940
- if row[2] then
941
- -- The cursor moved past this head: a retry of its completion replays.
942
- if not owns(row[7], tag) then return { 'superseded' } end
943
- if not row[3] or tonumber(row[3]) ~= attempt then return { 'superseded' } end
944
- local recorded = cjson.decode(row[4] or '[]')
945
- if #recorded ~= n then return { 'partial' } end
946
- for i = 1, n do
947
- if recorded[i] ~= ARGV[10 + (i - 1) * 4 + 1] then return { 'partial' } end
948
- end
949
- local result = { 'duplicate' }
950
- for i = 1, n do
951
- if not owners[i] then return { 'partial' } end
952
- result[#result + 1] = owners[i]
953
- end
954
- return result
955
- end
956
- if tonumber(row[1] or '0') ~= attempt or not row[5] or row[6] or not owns(row[7], tag) then
957
- return { 'superseded' }
958
- end
959
- for i = 1, n do
960
- if owners[i] then return { 'partial' } end
961
- end
962
- use_served(ARGV[8])
963
- local batch = {}
964
- for i = 1, n do
965
- local o = 10 + (i - 1) * 4
966
- batch[i] = { idx = total + i, type = ARGV[o + 2], targets = targets_of(ARGV[o + 4]) }
967
- end
968
- local moved, missing = advance(consumer, row[7], idx, row[8], batch)
969
- if not moved then return { 'index', missing, tostring(idx) } end
970
- local planned, unindexed, after = plan(batch, total)
971
- if not planned then return { 'index', unindexed, tostring(after) } end
972
- put_row(idx, at, 'p', now)
973
- put_row(idx, at, 'pa', ARGV[6])
974
- put_row(idx, at, 'ri', ARGV[9])
975
- release_pins(idx, at, row[9])
976
- local marks = {}
977
- for i = 1, n do
978
- local o = 10 + (i - 1) * 4
979
- local field = tostring(total + i)
980
- redis.call('XADD', LOG, field .. '-0',
981
- 'id', ARGV[o + 1], 'type', ARGV[o + 2], 'payload', ARGV[o + 3],
982
- 'created_at', now, 'cause', ARGV[7])
983
- marks[#marks + 1] = id_key(ARGV[o + 1])
984
- marks[#marks + 1] = field
985
- end
986
- index_batch(batch)
987
- enqueue(batch)
988
- if n > 0 then
989
- marks[#marks + 1] = COUNTER
990
- marks[#marks + 1] = tostring(total + n)
991
- end
992
- if typed_dirty then
993
- marks[#marks + 1] = TYPED
994
- marks[#marks + 1] = cjson.encode(typed)
995
- end
996
- sliced('MSET', nil, marks)
997
- flush_states()
998
- flush()
999
- flush_ready()
1000
- return { 'ok', tostring(total + 1) }
1001
- `;
1002
- /**
1003
- * KEYS: counter.
1004
- * ARGV: consumer, tag, index, attempt, error, maxFailures, nowMs, retryAtMs
1005
- * or ''.
1006
- */
1007
- const FAIL_ATTEMPT_LUA = `${BASE_LUA}
1008
- read_bounds()
1009
- local consumer, tag, idx, attempt = ARGV[1], ARGV[2], tonumber(ARGV[3]), tonumber(ARGV[4])
1010
- local at = row_of(consumer, tag)
1011
- if idx <= boundary then return { 'superseded', '0' } end
1012
- if idx < 1 or idx > total then return { 'missing', '0' } end
1013
- local row = read_rows({ { idx, at } }, { 'a', 'd', 'p', 'f', 'lfa', 'ch', 'l', 'pins' })[1]
1014
- if row[3] or (row[7] and not owns(row[7], tag)) then return { 'superseded', '0' } end
1015
- local failures = tonumber(row[1] or '0')
1016
- if tonumber(row[2] or '0') ~= attempt then return { 'superseded', tostring(failures) } end
1017
- if not row[6] and row[5] and tonumber(row[5]) == attempt then
1018
- return { row[4] and 'dead_lettered' or 'failed', tostring(failures) }
1019
- end
1020
- if row[4] then return { 'dead_lettered', tostring(failures) } end
1021
- if not row[6] then return { 'superseded', tostring(failures) } end
1022
- failures = failures + 1
1023
- local dead = failures >= tonumber(ARGV[6])
1024
- put_row(idx, at, 'a', tostring(failures))
1025
- put_row(idx, at, 'e', ARGV[5])
1026
- put_row(idx, at, 'lf', ARGV[7])
1027
- put_row(idx, at, 'lfa', ARGV[4])
1028
- drop_row(idx, at, 'ch')
1029
- if dead then
1030
- put_row(idx, at, 'f', ARGV[7])
1031
- drop_row(idx, at, 'ce')
1032
- ready_set(cid_for(consumer, row[7], idx), -idx)
1033
- release_pins(idx, at, row[8])
1034
- elseif ARGV[8] ~= '' then
1035
- put_row(idx, at, 'ce', ARGV[8])
1036
- else
1037
- drop_row(idx, at, 'ce')
1038
- end
1039
- flush()
1040
- flush_ready()
1041
- return { dead and 'dead_lettered' or 'failed', tostring(failures) }
1042
- `;
1043
- /**
1044
- * KEYS: counter. ARGV: consumer, index, action, nowMs, served
1045
- * consumers. Returns [redriven, hasPending] | ['index', type, after]. Acts
1046
- * only on the consumer's dead-lettered head at the index, above the clear
1047
- * marker.
1048
- */
1049
- const REDRIVE_LUA = `${BASE_LUA}${CURSOR_LUA}
1050
- read_bounds()
1051
- use_served(ARGV[5])
1052
- local consumer, idx = ARGV[1], tonumber(ARGV[2])
1053
- local function result(redriven) return { redriven, has_pending() } end
1054
- if idx <= boundary or idx < 1 or idx > total then return result('0') end
1055
- local cid, tag = nil, nil
1056
- for _, member in ipairs(redis.call('ZRANGEBYSCORE', READY, -idx, -idx)) do
1057
- local owner, member_tag = parse_cid(member)
1058
- if owner == consumer then
1059
- cid, tag = member, member_tag
1060
- break
1061
- end
1062
- end
1063
- if not cid then return result('0') end
1064
- local kind = string.sub(tag, 1, 1) == '#' and '#' or tag
1065
- local at = row_of(consumer, tag)
1066
- if ARGV[3] == 'skip' then
1067
- local row = read_rows({ { idx, at } }, { 'next' })[1]
1068
- local moved, missing = advance(consumer, kind, idx, row[1], {})
1069
- if not moved then return { 'index', missing, tostring(idx) } end
1070
- put_row(idx, at, 'p', ARGV[4])
1071
- flush_states()
1072
- if typed_dirty then redis.call('SET', TYPED, cjson.encode(typed)) end
1073
- else
1074
- drop_row(idx, at, 'f')
1075
- drop_row(idx, at, 'a')
1076
- ready_set(cid, idx)
1077
- end
1078
- flush()
1079
- flush_ready()
1080
- return result('1')
1081
- `;
1082
- /**
1083
- * KEYS: counter. ARGV: consumer, lane, types JSON or '*', backfill
1084
- * ('1' or '0'). Brings one log cursor up to date without an append, as
1085
- * `plan` and `enqueue` would for an append carrying its types: a missing
1086
- * cursor starts at the clear marker with backfill, else at the head with
1087
- * nothing to run; an idle one takes the next stored event of its types; one
1088
- * with a head, claimed or not, keeps it. Records the types, and writes
1089
- * nothing when nothing changed. Returns ['ok', position, head or nil, head
1090
- * columns, session head] | ['index', type, after].
1091
- */
1092
- const WAKE_LOG_LUA = `${BASE_LUA}${CURSOR_LUA}
1093
- read_bounds()
1094
- local consumer, lane, ty = ARGV[1], ARGV[2], ARGV[3]
1095
- local types = types_of(ty)
1096
- local cid = cid_of(consumer, 'G' .. lane)
1097
- load_states({ cid })
1098
- local state = states[cid]
1099
- local had_head = state.h
1100
- -- Nothing after the latest clear: a missing cursor stays missing.
1101
- if not state.exists and total == boundary then
1102
- return { 'ok', tostring(boundary), false, {}, tostring(total) }
1103
- end
1104
- if not state.exists then
1105
- state.exists, state.p = true, total
1106
- if ARGV[4] == '1' then
1107
- local head, missing = stored_head(boundary, types)
1108
- if head == nil then return { 'index', missing, tostring(boundary) } end
1109
- state.p, state.h = boundary, head
1110
- else
1111
- -- Nothing it takes is stored after its start: index its types from there.
1112
- for name in pairs(types or {}) do
1113
- if typed[name] == nil then register(name, total) end
1114
- end
1115
- end
1116
- state.dirty = true
1117
- elseif not state.h then
1118
- -- A deployment that doesn't serve this consumer may have appended events
1119
- -- it takes since it went idle.
1120
- local head, missing = stored_head(state.p, types)
1121
- if head == nil then return { 'index', missing, tostring(state.p) } end
1122
- if head then state.h, state.dirty = head, true end
1123
- end
1124
- if state.ty ~= ty then state.ty, state.dirty = ty, true end
1125
- local columns = {}
1126
- if had_head then
1127
- columns = read_rows({ { state.h, row_of(consumer, 'G' .. lane) } }, ${HEAD_COLUMNS})[1]
1128
- elseif state.h then
1129
- ready_set(cid, state.h)
1130
- end
1131
- flush_states()
1132
- if typed_dirty then redis.call('SET', TYPED, cjson.encode(typed)) end
1133
- flush()
1134
- flush_ready()
1135
- return { 'ok', tostring(state.p), state.h and tostring(state.h) or false, columns, tostring(total) }
1136
- `;
1137
- /**
1138
- * KEYS: counter. Returns the dead-lettered heads above the clear
1139
- * marker as [consumer, tag, index, columns, entry] tuples.
1140
- */
1141
- const DEAD_LETTERS_LUA = `${BASE_LUA}
1142
- local dead = redis.call('ZRANGEBYSCORE', READY, '-inf', '(0', 'WITHSCORES')
1143
- if #dead == 0 then return {} end
1144
- read_bounds()
1145
- local refs, items = {}, {}
1146
- for i = 1, #dead, 2 do
1147
- local consumer, tag = parse_cid(dead[i])
1148
- local idx = -tonumber(dead[i + 1])
1149
- if idx > boundary then
1150
- refs[#refs + 1] = { idx, row_of(consumer, tag) }
1151
- items[#items + 1] = { consumer, tag, idx }
1152
- end
1153
- end
1154
- local rows = read_rows(refs, ${HEAD_COLUMNS})
1155
- local result = {}
1156
- for k, item in ipairs(items) do
1157
- local entries = redis.call('XRANGE', LOG, tostring(item[3]) .. '-0', tostring(item[3]) .. '-0')
1158
- if #entries > 0 then
1159
- result[#result + 1] = { item[1], item[2], tostring(item[3]), rows[k], entries[1] }
1160
- end
1161
- end
1162
- return result
1163
- `;
1164
- /**
1165
- * KEYS: counter. Returns every listed cursor as [consumer, tag,
1166
- * position, head or nil, columns]: lane and log cursors from the cursor
1167
- * hash, read against the clear marker, then the event cursors with a head.
1168
- */
1169
- const CURSORS_LUA = `${BASE_LUA}
1170
- read_bounds()
1171
- local listed = {}
1172
- local fields = redis.call('HGETALL', CURSORS)
1173
- local records, order = {}, {}
1174
- for i = 1, #fields, 2 do
1175
- local at = string.find(fields[i], ':[^:]*$')
1176
- local cid, suffix = string.sub(fields[i], 1, at - 1), string.sub(fields[i], at + 1)
1177
- if not records[cid] then
1178
- records[cid] = {}
1179
- order[#order + 1] = cid
1180
- end
1181
- records[cid][suffix] = fields[i + 1]
1182
- end
1183
- for _, cid in ipairs(order) do
1184
- local record = records[cid]
1185
- local consumer, tag = parse_cid(cid)
1186
- local head = (record.h and record.h ~= '') and tonumber(record.h) or false
1187
- local position = tonumber(record.p or '0')
1188
- if head and head <= boundary then head = false end
1189
- local kind = string.sub(tag, 1, 1)
1190
- if kind == 'G' and position < boundary then position = boundary end
1191
- if kind == 'G' or head or position > boundary then
1192
- listed[#listed + 1] = { consumer, tag, position, head }
1193
- end
1194
- end
1195
- local ready = redis.call('ZRANGE', READY, 0, -1, 'WITHSCORES')
1196
- for i = 1, #ready, 2 do
1197
- local consumer, tag = parse_cid(ready[i])
1198
- if string.sub(tag, 1, 1) == '#' then
1199
- local head = math.abs(tonumber(ready[i + 1]))
1200
- listed[#listed + 1] = { consumer, '#', head - 1, head }
1201
- end
1202
- end
1203
- local refs, positions = {}, {}
1204
- for position, cursor in ipairs(listed) do
1205
- if cursor[4] then
1206
- refs[#refs + 1] = { cursor[4], row_of(cursor[1], cursor[2]) }
1207
- positions[#refs] = position
1208
- end
1209
- end
1210
- local rows = read_rows(refs, ${HEAD_COLUMNS})
1211
- local columns = {}
1212
- for k, position in ipairs(positions) do columns[position] = rows[k] end
1213
- local result = {}
1214
- for position, cursor in ipairs(listed) do
1215
- result[#result + 1] = {
1216
- cursor[1], cursor[2], tostring(cursor[3]),
1217
- cursor[4] and tostring(cursor[4]) or false, columns[position] or {},
1218
- }
1219
- end
1220
- return result
1221
- `;
1222
- /**
1223
- * KEYS: counter, head, history.
1224
- * ARGV: write count, then per write: index, snapshot JSON, pin count, then
1225
- * per pin: consumer, tag, index; finally the reducer name. Writes from
1226
- * before the latest clear are dropped, and a head from before it is
1227
- * replaced as if absent. A pin holds only on an unfinished, live head: a
1228
- * claimed row says so itself, an unclaimed head by its cursor's ready score.
1229
- */
1230
- const PUT_SNAPSHOTS_LUA = `${BASE_LUA}
1231
- read_bounds()
1232
- local HEAD, HISTORY = KEYS[2], KEYS[3]
1233
- local entries, refs, pins = {}, {}, {}
1234
- local offset = 2
1235
- for w = 1, tonumber(ARGV[1]) do
1236
- local index = tonumber(ARGV[offset])
1237
- local pin_count = tonumber(ARGV[offset + 2])
1238
- local entry = { index = index, snapshot = ARGV[offset + 1], pins = {} }
1239
- for p = 1, pin_count do
1240
- local o = offset + 2 + (p - 1) * 3
1241
- local pin = { consumer = ARGV[o + 1], tag = ARGV[o + 2], idx = tonumber(ARGV[o + 3]) }
1242
- if index >= boundary and pin.idx > boundary and pin.idx <= total then
1243
- pin.row = row_of(pin.consumer, pin.tag)
1244
- refs[#refs + 1] = { pin.idx, pin.row }
1245
- pins[#pins + 1] = pin
1246
- entry.pins[#entry.pins + 1] = pin
1247
- end
1248
- end
1249
- entries[w] = entry
1250
- offset = offset + 3 + pin_count * 3
1251
- end
1252
- local function live(consumer, tag, idx)
1253
- return tonumber(redis.call('ZSCORE', READY, cid_of(consumer, tag)) or '0') == idx
1254
- end
1255
- local rows = read_rows(refs, { 'pins', 'p', 'f', 'l' })
1256
- local held, held_order = {}, {}
1257
- for k, pin in ipairs(pins) do
1258
- local row = rows[k]
1259
- local valid
1260
- if row[2] or row[3] then
1261
- valid = false
1262
- elseif row[4] then
1263
- valid = owns(row[4], pin.tag)
1264
- elseif pin.tag == '#' then
1265
- valid = live(pin.consumer, '#' .. tostring(pin.idx), pin.idx)
1266
- else
1267
- valid = live(pin.consumer, pin.tag, pin.idx) or
1268
- live(pin.consumer, 'G' .. string.sub(pin.tag, 2), pin.idx)
1269
- end
1270
- if valid then
1271
- local key = tostring(pin.idx) .. ':' .. pin.row
1272
- if not held[key] then
1273
- local list = (row[1] and row[1] ~= '') and cjson.decode(row[1]) or {}
1274
- local set = {}
1275
- for _, ref in ipairs(list) do set[ref] = true end
1276
- held[key] = { list = list, set = set, idx = pin.idx, row = pin.row }
1277
- held_order[#held_order + 1] = key
1278
- end
1279
- pin.held = held[key]
1280
- end
1281
- end
1282
- local snapshots = {}
1283
- for _, entry in ipairs(entries) do
1284
- local ref = cjson.encode({ HISTORY, tostring(entry.index) })
1285
- for _, pin in ipairs(entry.pins) do
1286
- if pin.held and not pin.held.set[ref] then
1287
- pin.held.set[ref] = true
1288
- pin.held.list[#pin.held.list + 1] = ref
1289
- pin.held.dirty = true
1290
- redis.call('HINCRBY', PIN_COUNTS, ref, 1)
1291
- end
1292
- end
1293
- if entry.index >= boundary then
1294
- snapshots[#snapshots + 1] = { index = entry.index, snapshot = entry.snapshot, ref = ref }
1295
- end
1296
- end
1297
- for _, key in ipairs(held_order) do
1298
- local row = held[key]
1299
- if row.dirty then put_row(row.idx, row.row, 'pins', cjson.encode(row.list)) end
1300
- end
1301
- flush()
1302
- if #snapshots == 0 then return 1 end
1303
-
1304
- local head = redis.call('GET', HEAD)
1305
- local head_index = nil
1306
- local registered = false
1307
- if head then
1308
- local record = cjson.decode(head)
1309
- head_index = tonumber(record['index'])
1310
- registered = record['r'] == 1
1311
- end
1312
- if head_index and head_index < boundary then
1313
- head, head_index, registered = nil, nil, false
1314
- redis.call('ZREMRANGEBYSCORE', HISTORY, '-inf', '(' .. boundary)
1315
- end
1316
- -- Deletion finds each reducer's keys through this set instead of a scan.
1317
- -- Heads written since carry the mark, so a reducer registers once.
1318
- if not registered then
1319
- redis.call('SADD', SESSION .. 'snap-reducers', ARGV[#ARGV])
1320
- end
1321
- local latest = snapshots[#snapshots]
1322
- local writes_head = not head_index or latest.index >= head_index
1323
- local advances = not head_index or latest.index > head_index
1324
- local final_head_index = advances and latest.index or head_index
1325
-
1326
- if advances and head and tonumber(redis.call('HGET', PIN_COUNTS, cjson.encode({ HISTORY, tostring(head_index) })) or '0') > 0 then
1327
- redis.call('ZREMRANGEBYSCORE', HISTORY, head_index, head_index)
1328
- redis.call('ZADD', HISTORY, head_index, head)
1329
- end
1330
-
1331
- for _, write in ipairs(snapshots) do
1332
- if write.index < final_head_index then
1333
- redis.call('ZREMRANGEBYSCORE', HISTORY, write.index, write.index)
1334
- if tonumber(redis.call('HGET', PIN_COUNTS, write.ref) or '0') > 0 then
1335
- redis.call('ZADD', HISTORY, write.index, write.snapshot)
1336
- end
1337
- end
1338
- end
1339
-
1340
- if writes_head then
1341
- redis.call('SET', HEAD, latest.snapshot)
1342
- redis.call('ZREMRANGEBYSCORE', HISTORY, latest.index, latest.index)
1343
- end
1344
- return 1
1345
- `;
1346
- /**
1347
- * Presence entries are `{"a":at,"e":expiresAt,"s":seen,"v":value}`, stamps
1348
- * first and both integers, so scripts read them with a pattern instead of
1349
- * decoding the value.
1350
- */
1351
- const PRESENCE_STAMPS_LUA = `
1352
- local function stamps(entry)
1353
- local a, e = string.match(entry, '^{"a":(%-?%d+),"e":(%-?%d+),')
1354
- return tonumber(a), tonumber(e)
1355
- end
1356
- `;
1357
- /**
1358
- * KEYS: presence hash. ARGV: atMs, ttlMs, nowMs, n, then per entry:
1359
- * hashField, entryJson (a null value is a tombstone). Field-wise LWW by the
1360
- * sender's `at`: an unexpired stored entry with a strictly newer stamp
1361
- * survives; ties go to the incoming write (memory-tier parity). Returns the applied 1-based entry
1362
- * positions. The whole-key PEXPIRE is the coarse bound, sound because core
1363
- * sends one uniform ttlMs; the per-entry `e` stamp is the fine bound (the
1364
- * injected storage clock at the applied set plus ttlMs — never the sender
1365
- * stamp), filtered on read against the same clock.
1366
- */
1367
- const PRESENCE_SET_LUA = `${SLICED_LUA}${PRESENCE_STAMPS_LUA}
1368
- local at, now, n = tonumber(ARGV[1]), tonumber(ARGV[3]), tonumber(ARGV[4])
1369
- local fields = {}
1370
- for i = 1, n do fields[i] = ARGV[4 + (i - 1) * 2 + 1] end
1371
- local stored = sliced('HMGET', KEYS[1], fields)
1372
- local applied, sets = {}, {}
1373
- for i = 1, n do
1374
- local a, e = false, false
1375
- if stored[i] then a, e = stamps(stored[i]) end
1376
- if not stored[i] or a <= at or e <= now then
1377
- sets[#sets + 1] = fields[i]
1378
- sets[#sets + 1] = ARGV[4 + (i - 1) * 2 + 2]
1379
- applied[#applied + 1] = tostring(i)
1380
- end
1381
- end
1382
- sliced('HSET', KEYS[1], sets)
1383
- if #applied > 0 then redis.call('PEXPIRE', KEYS[1], ARGV[2]) end
1384
- return applied
1385
- `;
1386
- /**
1387
- * KEYS: presence hash. ARGV: nowMs, then the fields a read saw expired.
1388
- * Deletes those still at or past their expiry, re-checked in this atomic
1389
- * step so a stale reader never sweeps a concurrently refreshed field.
1390
- */
1391
- const PRESENCE_PRUNE_LUA = `${SLICED_LUA}${PRESENCE_STAMPS_LUA}
1392
- local now = tonumber(ARGV[1])
1393
- local fields = {}
1394
- for i = 2, #ARGV do fields[#fields + 1] = ARGV[i] end
1395
- local stored = sliced('HMGET', KEYS[1], fields)
1396
- local stale = {}
1397
- for i = 1, #fields do
1398
- if stored[i] then
1399
- local _, e = stamps(stored[i])
1400
- if e <= now then stale[#stale + 1] = fields[i] end
1401
- end
1402
- end
1403
- sliced('HDEL', KEYS[1], stale)
1404
- return 1
1405
- `;
1406
- /**
1407
- * KEYS: counter, head, history. ARGV: snapshot frontier or ''.
1408
- * Returns one atomic multiversion-cache-plus-log-frontier read, with the
1409
- * clear boundary; checkpoints from before it are ignored.
1410
- */
1411
- const READ_STATE_LUA = `
1412
- local session = string.sub(KEYS[1], 1, -6)
1413
- local counts = redis.call('MGET', KEYS[1], session .. 'clear')
1414
- local boundary = tonumber(counts[2] or '0')
1415
- local head = redis.call('GET', KEYS[2])
1416
- local head_index = head and cjson.decode(head)['index'] or nil
1417
- if head and (type(head_index) ~= 'number' or head_index < 0 or head_index > 9007199254740991 or head_index ~= math.floor(head_index)) then
1418
- return redis.error_reply('invalid snapshot head index')
1419
- end
1420
- if head_index and head_index < boundary then
1421
- head = nil
1422
- head_index = nil
1423
- end
1424
- local cap = ARGV[1]
1425
- local snapshot = nil
1426
- if head_index and (cap == '' or head_index <= tonumber(cap)) then
1427
- snapshot = head
1428
- else
1429
- local upper = cap == '' and '+inf' or cap
1430
- local historical = redis.call('ZREVRANGEBYSCORE', KEYS[3], upper, boundary, 'LIMIT', 0, 1)
1431
- if #historical > 0 then snapshot = historical[1] end
1432
- end
1433
- return { head_index or '', snapshot or '', counts[1] or counts[2] or '0', tostring(boundary) }
1434
- `;
1435
- /**
1436
- * What reclaim removes once no entry is left below the latest clear: every
1437
- * registered reducer's checkpoints below the latest clear and the pin counts
1438
- * naming them (snapshot writes register each reducer in
1439
- * {prefix}:{session}:snap-reducers, so no key scan is needed), every head
1440
- * row below it (whole chunks, then the boundary chunk's older rows), the
1441
- * type indexes' older entries, and the lane cursors it left idle.
1442
- *
1443
- * A lifetime that ended empty then collapses to the clear marker, the log
1444
- * holding it (readers resuming before the marker still read it), and the log
1445
- * cursors the sweep reset to the marker. The counter reads from the marker
1446
- * when absent, type indexes rebuild lazily, and the marker's own id key goes
1447
- * too.
1448
- */
1449
- const SWEEP_LUA = `
1450
- local function sweep(boundary)
1451
- for _, reducer in ipairs(redis.call('SMEMBERS', SESSION .. 'snap-reducers')) do
1452
- local head_key = SESSION .. 'snap:' .. reducer
1453
- local head = redis.call('GET', head_key)
1454
- if head and tonumber(cjson.decode(head)['index']) < boundary then
1455
- redis.call('DEL', head_key)
1456
- end
1457
- redis.call('ZREMRANGEBYSCORE', SESSION .. 'snap-history:' .. reducer, '-inf', '(' .. boundary)
1458
- end
1459
- local counts = redis.call('HGETALL', PIN_COUNTS)
1460
- local stale = {}
1461
- for i = 1, #counts, 2 do
1462
- if tonumber(cjson.decode(counts[i])[2]) < boundary then stale[#stale + 1] = counts[i] end
1463
- end
1464
- sliced('HDEL', PIN_COUNTS, stale)
1465
- local raw = redis.call('GET', TYPED)
1466
- if raw then
1467
- for name in pairs(cjson.decode(raw)) do
1468
- redis.call('ZREMRANGEBYSCORE', type_key(name), '-inf', '(' .. boundary)
1469
- end
1470
- end
1471
- local last = math.floor((boundary - 1) / ${META_CHUNK_SIZE})
1472
- local chunks = {}
1473
- for chunk = 0, last - 1 do chunks[#chunks + 1] = META .. ':' .. tostring(chunk) end
1474
- sliced('UNLINK', nil, chunks)
1475
- local older = {}
1476
- for _, field in ipairs(redis.call('HKEYS', META .. ':' .. tostring(last))) do
1477
- local idx = tonumber(string.match(field, '^(%d+):'))
1478
- if idx and idx < boundary then older[#older + 1] = field end
1479
- end
1480
- sliced('HDEL', META .. ':' .. tostring(last), older)
1481
- local fields = redis.call('HGETALL', CURSORS)
1482
- local records, order = {}, {}
1483
- for i = 1, #fields, 2 do
1484
- local at = string.find(fields[i], ':[^:]*$')
1485
- local cid, suffix = string.sub(fields[i], 1, at - 1), string.sub(fields[i], at + 1)
1486
- if not records[cid] then
1487
- records[cid] = {}
1488
- order[#order + 1] = cid
1489
- end
1490
- records[cid][suffix] = fields[i + 1]
1491
- end
1492
- local idle, moved = {}, {}
1493
- for _, cid in ipairs(order) do
1494
- local record = records[cid]
1495
- local _, tag = parse_cid(cid)
1496
- local head = (record.h and record.h ~= '') and tonumber(record.h) or false
1497
- local position = tonumber(record.p or '0')
1498
- if head and head <= boundary then head = false end
1499
- if string.sub(tag, 1, 1) == 'G' then
1500
- if position < boundary then position = boundary end
1501
- moved[#moved + 1] = cid .. ':h'
1502
- moved[#moved + 1] = head and tostring(head) or ''
1503
- moved[#moved + 1] = cid .. ':p'
1504
- moved[#moved + 1] = tostring(position)
1505
- elseif not head and position <= boundary then
1506
- for suffix in pairs(record) do idle[#idle + 1] = cid .. ':' .. suffix end
1507
- elseif not head and record.h ~= '' then
1508
- moved[#moved + 1] = cid .. ':h'
1509
- moved[#moved + 1] = ''
1510
- end
1511
- end
1512
- sliced('HDEL', CURSORS, idle)
1513
- sliced('HSET', CURSORS, moved)
1514
- local count = redis.call('GET', COUNTER)
1515
- if not count or tonumber(count) ~= boundary or redis.call('ZCARD', READY) > 0 then
1516
- return
1517
- end
1518
- local stale = { COUNTER, TYPED, PIN_COUNTS, chunk_key(boundary) }
1519
- local reducers = SESSION .. 'snap-reducers'
1520
- for _, reducer in ipairs(redis.call('SMEMBERS', reducers)) do
1521
- stale[#stale + 1] = SESSION .. 'snap:' .. reducer
1522
- stale[#stale + 1] = SESSION .. 'snap-history:' .. reducer
1523
- end
1524
- stale[#stale + 1] = reducers
1525
- local types = redis.call('GET', TYPED)
1526
- if types then
1527
- for name in pairs(cjson.decode(types)) do stale[#stale + 1] = type_key(name) end
1528
- end
1529
- local marker = redis.call('XRANGE', LOG, boundary .. '-0', boundary .. '-0')[1]
1530
- if marker then
1531
- for i = 1, #marker[2], 2 do
1532
- if marker[2][i] == 'id' then stale[#stale + 1] = id_key(marker[2][i + 1]) end
1533
- end
1534
- end
1535
- sliced('UNLINK', nil, stale)
1536
- end
1537
- `;
1538
- /**
1539
- * KEYS: counter.
1540
- * ARGV: sessionId, nowMs, ifLastIndex or '', cause consumer or '', cause tag,
1541
- * cause index, cause attempt, marker id.
1542
- * Returns ['ok', cleared, head, boundary, appended?] | ['superseded'] |
1543
- * ['foreign']; `appended` is '1' when this call appended the marker.
1544
- * The marker joins the same log: the old lifetime's entries stay below it
1545
- * until reclaim deletes them, and every read of the log starts at the
1546
- * marker. (A stream can't be renamed aside: Upstash refuses RENAME on one.)
1547
- * The ready set is unlinked, so claims and pending checks see only the new
1548
- * lifetime. Type indexes keep their older entries until reclaim too:
1549
- * lookups start above the marker.
1550
- */
1551
- const CLEAR_LUA = `${BASE_LUA}
1552
- local marker_owner = owners_of(read_bounds({ ARGV[8] }))[1]
1553
- local head = total
1554
- if ARGV[4] ~= '' then
1555
- local idx = tonumber(ARGV[6])
1556
- if idx <= boundary then return { 'superseded' } end
1557
- local row = read_rows({ { idx, row_of(ARGV[4], ARGV[5]) } }, { 'd', 'f', 'p', 'l' })[1]
1558
- if tonumber(row[1] or '0') ~= tonumber(ARGV[7]) or row[2] or row[3] or not owns(row[4], ARGV[5]) then
1559
- return { 'superseded' }
1560
- end
1561
- end
1562
- local expected = ARGV[3]
1563
- if expected ~= '' and boundary == tonumber(expected) + 1 then
1564
- return { 'ok', '1', tostring(head), tostring(boundary) }
1565
- end
1566
- if expected ~= '' and tonumber(expected) ~= head then
1567
- return { 'ok', '0', tostring(head), tostring(boundary) }
1568
- end
1569
- if head == 0 or boundary == head then
1570
- return { 'ok', '1', tostring(head), tostring(boundary) }
1571
- end
1572
- if marker_owner then return { 'foreign' } end
1573
- local field = tostring(head + 1)
1574
- redis.call('UNLINK', READY)
1575
- redis.call('XADD', LOG, field .. '-0',
1576
- 'id', ARGV[8], 'type', CLEAR_TYPE, 'payload', 'null',
1577
- 'created_at', ARGV[2], 'cause', '')
1578
- redis.call('MSET', id_key(ARGV[8]), field, COUNTER, field, CLEAR, field)
1579
- return { 'ok', '1', field, field, '1' }
1580
- `;
1581
- /**
1582
- * KEYS: counter. ARGV: page size.
1583
- * The next deletion batch: up to a page of [index, id] pairs of the log's
1584
- * entries below the latest clear. With none left it sweeps what the old
1585
- * lifetimes left and returns nothing, so a retry finishes an interrupted
1586
- * deletion.
1587
- */
1588
- const RECLAIM_BATCH_LUA = `${BASE_LUA}${SWEEP_LUA}
1589
- local boundary = tonumber(redis.call('GET', CLEAR) or '0')
1590
- if boundary == 0 then return {} end
1591
- local entries = redis.call('XRANGE', LOG, '-', tostring(boundary - 1) .. '-0', 'COUNT', ARGV[1])
1592
- if #entries == 0 then
1593
- sweep(boundary)
1594
- return {}
1595
- end
1596
- local batch = {}
1597
- for _, entry in ipairs(entries) do
1598
- local fields = entry[2]
1599
- for i = 1, #fields, 2 do
1600
- if fields[i] == 'id' then
1601
- batch[#batch + 1] = string.match(entry[1], '^(%d+)')
1602
- batch[#batch + 1] = fields[i + 1]
1603
- break
1604
- end
1605
- end
1606
- end
1607
- return batch
1608
- `;
1609
- /**
1610
- * KEYS: counter.
1611
- * ARGV: sessionId, n, then per entry: index, id.
1612
- * Deletes the listed entries below the latest clear and their id records.
1613
- * An id record survives when it names another event, so an id reused in the
1614
- * new lifetime keeps its owner. Returns [deleted, done].
1615
- */
1616
- const RECLAIM_LUA = `${BASE_LUA}${SWEEP_LUA}
1617
- local boundary = tonumber(redis.call('GET', CLEAR) or '0')
1618
- local ids, indexes, stream_ids = {}, {}, {}
1619
- -- A concurrent reclaim may list the same batch; only XDEL says who removed it.
1620
- local removed = 0
1621
- for i = 1, tonumber(ARGV[2]) do
1622
- local field = ARGV[2 + (i - 1) * 2 + 1]
1623
- if tonumber(field) < boundary then
1624
- ids[#ids + 1] = ARGV[2 + (i - 1) * 2 + 2]
1625
- indexes[#ids] = tonumber(field)
1626
- stream_ids[#ids] = field .. '-0'
1627
- end
1628
- end
1629
- if #ids > 0 then
1630
- local keys = {}
1631
- for i = 1, #ids do keys[i] = id_key(ids[i]) end
1632
- local owners, stale = sliced('MGET', nil, keys), {}
1633
- for i = 1, #ids do
1634
- if owners[i] and tonumber(owners[i]) == indexes[i] then
1635
- stale[#stale + 1] = keys[i]
1636
- end
1637
- end
1638
- sliced('DEL', nil, stale)
1639
- removed = redis.call('XDEL', LOG, unpack(stream_ids))
1640
- end
1641
- local done = 0
1642
- if #redis.call('XRANGE', LOG, '-', tostring(boundary - 1) .. '-0', 'COUNT', 1) == 0 then
1643
- sweep(boundary)
1644
- done = 1
1645
- end
1646
- return { removed, done }
1647
- `;
1648
- const WAKE_PAYLOAD_LIMIT = 32768;
1649
- const encoder = new TextEncoder();
1650
- /**
1651
- * A wake-up announcing events through `frontier`. It carries them, so a
1652
- * caught-up reader applies them without reading the stream:
1653
- * `{"f":frontier,"t":createdAt,"e":[[index,id,type,payload],...]}`, with
1654
- * payloads inlined as their stored JSON text. One over WAKE_PAYLOAD_LIMIT
1655
- * bytes, or one without entries, announces only `{"f":frontier}`, and
1656
- * readers catch up with XRANGE.
1657
- */
1658
- const wakeMessage = (frontier, createdAt, entries) => {
1659
- const bare = `{"f":${frontier}}`;
1660
- if (entries.length === 0) return bare;
1661
- const carried = `{"f":${frontier},"t":${createdAt},"e":[${entries.map(([index, id, type, payload]) => `[${index},${JSON.stringify(id)},${JSON.stringify(type)},${payload}]`).join(",")}]}`;
1662
- return encoder.encode(carried).byteLength > WAKE_PAYLOAD_LIMIT ? bare : carried;
1663
- };
1664
- const fieldMap = (fields) => {
1665
- const map = {};
1666
- for (let i = 0; i + 1 < fields.length; i += 2) map[fields[i]] = fields[i + 1];
1667
- return map;
1668
- };
1669
- const entryIndex = (entryId) => Number(entryId.slice(0, entryId.indexOf("-")));
1670
- const toEvent = (sessionId, entry) => {
1671
- const fields = fieldMap(entry[1]);
1672
- return {
1673
- id: fields["id"],
1674
- type: fields["type"],
1675
- payload: JSON.parse(fields["payload"]),
1676
- index: entryIndex(entry[0]),
1677
- sessionId,
1678
- createdAt: new Date(Number(fields["created_at"]))
1679
- };
1680
- };
1681
- /**
1682
- * A stream entry's causal edge. Releases before consumers (0.17 to 0.20)
1683
- * recorded only the parent's index and attempt: their edge reads as the
1684
- * handlers table's, `a2.handlers`, as Postgres's upgrade names it, with no
1685
- * lane, since nothing reads an earlier release's lane.
1686
- */
1687
- const decodeStreamCause = (raw) => {
1688
- const parsed = JSON.parse(raw);
1689
- return decodeCause(parsed.consumer === void 0 ? {
1690
- consumer: "a2.handlers",
1691
- lane: null,
1692
- ...parsed
1693
- } : parsed);
1694
- };
1695
- /** A stream entry with its causal edge. */
1696
- const toStoredEvent = (sessionId, entry) => {
1697
- const cause = fieldMap(entry[1])["cause"];
1698
- return Object.assign(toEvent(sessionId, entry), { cause: cause === void 0 || cause === "" ? null : decodeStreamCause(cause) });
1699
- };
1700
- const fieldBytes = (name) => new TextEncoder().encode(name);
1701
- const ID_FIELD = fieldBytes("id");
1702
- const TYPE_FIELD = fieldBytes("type");
1703
- const PAYLOAD_FIELD = fieldBytes("payload");
1704
- const CREATED_AT_FIELD = fieldBytes("created_at");
1705
- const utf8 = new TextDecoder("utf-8", { ignoreBOM: true });
1706
- const isField = (name, field) => {
1707
- if (name.length !== field.length) return false;
1708
- for (let at = 0; at < field.length; at++) if (name[at] !== field[at]) return false;
1709
- return true;
1710
- };
1711
- const bytesToSerializedEvent = (sessionId, entry) => {
1712
- const values = entry[1];
1713
- let id;
1714
- let type;
1715
- let payloadJson;
1716
- let createdAt;
1717
- for (let at = 0; at + 1 < values.length; at += 2) {
1718
- const name = values[at];
1719
- if (isField(name, ID_FIELD)) id = utf8.decode(values[at + 1]);
1720
- else if (isField(name, TYPE_FIELD)) type = utf8.decode(values[at + 1]);
1721
- else if (isField(name, PAYLOAD_FIELD)) payloadJson = utf8.decode(values[at + 1]);
1722
- else if (isField(name, CREATED_AT_FIELD)) createdAt = utf8.decode(values[at + 1]);
1723
- }
1724
- return {
1725
- id,
1726
- type,
1727
- payloadJson,
1728
- index: entryIndex(utf8.decode(entry[0])),
1729
- sessionId,
1730
- createdAtMs: Number(createdAt)
1731
- };
1732
- };
1733
- const toSerializedEvent = (sessionId, entry) => {
1734
- const fields = fieldMap(entry[1]);
1735
- return {
1736
- id: fields["id"],
1737
- type: fields["type"],
1738
- payloadJson: fields["payload"],
1739
- index: entryIndex(entry[0]),
1740
- sessionId,
1741
- createdAtMs: Number(fields["created_at"])
1742
- };
1743
- };
1744
- const json = (value) => JSON.stringify(value) ?? "null";
1745
- /** How scripts name a cursor within its consumer: `#`, or `L` and its lane. */
1746
- const tagOf = (lane) => lane === null ? "#" : `L${lane}`;
1747
- /** The lane a cursor tag names: null for an event cursor. */
1748
- const laneOf = (tag) => tag.startsWith("#") ? null : tag.slice(1);
1749
- const targetsArg = (targets) => targets === void 0 || targets.length === 0 ? "" : JSON.stringify(targets.map((target) => [target.consumer, tagOf(target.lane)]));
1750
- /** A log consumer's types, as scripts read them; '*' takes every type. */
1751
- const logTypesArg = (types) => types === null ? "*" : JSON.stringify(types);
1752
- /** The served consumers, as scripts read them; '' serves every consumer. */
1753
- const servedArg = (consumers) => consumers === void 0 ? "" : JSON.stringify(consumers.map((consumer) => consumer.log ? [
1754
- consumer.name,
1755
- consumer.log.lane,
1756
- logTypesArg(consumer.log.types),
1757
- consumer.log.backfill ? 1 : 0
1758
- ] : [consumer.name]));
1759
- /** A head's dispatch state from a row's HEAD_COLUMNS. */
1760
- const dispatchOf = (consumer, lane, columns) => {
1761
- const column = (at) => {
1762
- const value = columns?.[at];
1763
- return value === null || value === void 0 ? null : String(value);
1764
- };
1765
- const date = (at) => {
1766
- const value = column(at);
1767
- return value === null ? null : new Date(Number(value));
1768
- };
1769
- const count = (at) => {
1770
- const value = column(at);
1771
- return value === null ? null : Number(value);
1772
- };
1773
- return {
1774
- consumer,
1775
- lane,
1776
- firstClaimedAt: date(1),
1777
- lastClaimedAt: date(2),
1778
- attemptCount: count(0) ?? 0,
1779
- claimHolder: column(3),
1780
- claimExpiresAt: date(4),
1781
- failureCount: count(5) ?? 0,
1782
- lastFailedAt: date(6),
1783
- lastFailedAttempt: count(7),
1784
- lastError: column(8),
1785
- failedAt: date(9)
1786
- };
1787
- };
1788
- const toHeadEvent = (sessionId, head) => ({
1789
- ...toStoredEvent(sessionId, head[4]),
1790
- ...dispatchOf(head[0], laneOf(head[1]), head[3])
1791
- });
1792
- const compareText = (a, b) => a < b ? -1 : a > b ? 1 : 0;
1793
- const byHead = (a, b) => a.index - b.index || compareText(a.consumer, b.consumer);
1794
- /** Consumer, then lane, with concurrent cursors last by head. */
1795
- const byCursor = (a, b) => compareText(a.consumer, b.consumer) || (a.lane === null ? b.lane === null ? (a.head ?? 0) - (b.head ?? 0) : 1 : b.lane === null ? -1 : compareText(a.lane, b.lane));
1796
- const toClaimAvailableResult = (sessionId, reply) => {
1797
- const outcome = String(reply[0]);
1798
- if (outcome === "claimed") {
1799
- const count = Number(reply[1]);
1800
- const events = reply.slice(2, 2 + count).map((head) => toHeadEvent(sessionId, head)).toSorted(byHead);
1801
- const clearIndex = Number(reply[2 + count] ?? 0);
1802
- if (clearIndex > 0) for (const event of events) event.clearIndex = clearIndex;
1803
- return {
1804
- outcome: "claimed",
1805
- events,
1806
- head: Number(reply[3 + count])
1807
- };
1808
- }
1809
- if (outcome === "busy") return {
1810
- outcome,
1811
- retryAt: new Date(Number(reply[1]))
1812
- };
1813
- if (outcome === "settled") return { outcome };
1814
- throw new TypeError(`claim referenced a missing event in session '${sessionId}'`);
1815
- };
1816
- const toIndex = ({ raw, sessionId, name }) => {
1817
- const index = Number(raw ?? 0);
1818
- if (!Number.isSafeInteger(index) || index < 0) throw new A2Error("STORE_UNAVAILABLE", `redis ${name} for session '${sessionId}' is invalid`);
1819
- return index;
1820
- };
1821
- /**
1822
- * A range read that met a gap. Reclaim deletes the entries below a clear, so
1823
- * a read whose bounds predate the clear finds nothing where it expected
1824
- * events; anywhere else a gap is corruption.
1825
- */
1826
- const rangeGap = (sessionId, message) => Object.assign(new A2Error("STORE_UNAVAILABLE", `redis event range for session '${sessionId}' ${message}`), { rangeGap: true });
1827
- const isRangeGap = (error) => error instanceof A2Error && error.rangeGap === true;
1828
- /**
1829
- * Run a whole read, bounds included. A gap means a clear raced it, so the
1830
- * read runs once more from fresh bounds. A second gap, from another clear or
1831
- * from corruption, surfaces as the retryable STORE_UNAVAILABLE.
1832
- */
1833
- const retryAfterGap = async (read) => {
1834
- try {
1835
- return await read();
1836
- } catch (error) {
1837
- if (!isRangeGap(error)) throw error;
1838
- return read();
1839
- }
1840
- };
1841
- const wrap = async (fn) => {
1842
- try {
1843
- return await fn();
1844
- } catch (err) {
1845
- if (err instanceof A2Error || err instanceof TypeError) throw err;
1846
- throw new A2Error("STORE_UNAVAILABLE", "redis store operation failed", { cause: err });
1847
- }
1848
- };
1849
- /**
1850
- * A session's key. Every key of a session shares one hash tag, so a script
1851
- * locks only its session on Upstash and stays in one slot on a cluster. The
1852
- * tag is the session id as JSON with its braces escaped: it can't end early,
1853
- * and no session's tag spells another's.
1854
- */
1855
- const redisSessionKey = ({ prefix, sessionId, suffix }) => `${prefix}:{${JSON.stringify(sessionId).replaceAll("{", "\\u007b").replaceAll("}", "\\u007d")}}:${suffix}`;
1856
- function createRedisStoreCore(options) {
1857
- const { call, callBytes, clock } = options;
1858
- const generateId = options.ids;
1859
- const prefix = options.keyPrefix;
1860
- if (prefix.includes("{") || prefix.includes("}")) throw new TypeError("a redis keyPrefix cannot contain braces: they would set the hash tag of every key");
1861
- const sessionKey = (sessionId, suffix) => redisSessionKey({
1862
- prefix,
1863
- sessionId,
1864
- suffix
1865
- });
1866
- const storeKey = (s) => sessionKey(s, "log");
1867
- const countKey = (s) => sessionKey(s, "count");
1868
- const clearKey = (s) => sessionKey(s, "clear");
1869
- const schemaKey = `${prefix}:schema`;
1870
- const snapKey = (s, r) => sessionKey(s, `snap:${r}`);
1871
- const snapHistoryKey = (s, r) => sessionKey(s, `snap-history:${r}`);
1872
- const presenceKey = (s) => sessionKey(s, "presence");
1873
- const notifyChannel = (s) => `${prefix}:${s}:notify`;
1874
- const presenceChannel = (s) => `${prefix}:${s}:presence`;
1875
- const layoutError = () => new A2Error("STORE_NOT_CONFIGURED", `the redis keys under prefix '${prefix}' hold an A2 layout other than '${REDIS_LAYOUT}', from another release; point the store at a fresh keyPrefix, or give the contract a new name so it starts new sessions`);
1876
- /**
1877
- * Once per store, before its first script: claim or check the prefix's
1878
- * layout, and ask the server whether scripts may lock only their keys.
1879
- * Only the server's own rejection of the flag means no; a transport error
1880
- * fails this attempt, and the next operation asks again.
1881
- */
1882
- const prepared = retryableLazy(async () => {
1883
- const [, keyLocking] = await Promise.all([(async () => {
1884
- await call("SET", schemaKey, REDIS_LAYOUT, "NX");
1885
- if (await call("GET", schemaKey) !== "tagged-1") throw layoutError();
1886
- })(), call("EVAL", `${KEY_LOCKING$1}\nreturn 1`, 1, schemaKey).then(() => true, (error) => {
1887
- if (SHEBANG_REJECTED$1.test(String(error?.message))) return false;
1888
- throw error;
1889
- })]);
1890
- return { keyLocking };
1891
- });
1892
- /** Runs a script; a `readOnly` one takes Upstash's shared lock. */
1893
- const runScript = async ({ script, keys, args, readOnly }) => {
1894
- const { keyLocking } = await prepared.get();
1895
- let source = script;
1896
- if (keyLocking) source = `${readOnly ? READ_ONLY_KEY_LOCKING$1 : KEY_LOCKING$1}\n${script}`;
1897
- return call("EVAL", source, keys.length, ...keys, ...args);
1898
- };
1899
- /** Runs a writing script over a session: KEYS start with its counter. */
1900
- const evalScript = (script, sessionId, keys, args) => runScript({
1901
- script,
1902
- keys: [countKey(sessionId), ...keys],
1903
- args,
1904
- readOnly: false
1905
- });
1906
- /**
1907
- * Publishes a write's wake-up after its script, never inside it: a script
1908
- * holds its lock while PUBLISH waits on subscribers. Wake-ups are hints (a
1909
- * lost one costs subscribers a catch-up read, never an event), so a failed
1910
- * publish is dropped and the write waits for it at most
1911
- * NOTIFY_TIMINGS.publishMs.
1912
- */
1913
- const publish = async (channel, message) => {
1914
- let timer;
1915
- await Promise.race([call("PUBLISH", channel, message).catch(() => void 0), new Promise((resolve) => {
1916
- timer = setTimeout(resolve, NOTIFY_TIMINGS.publishMs);
1917
- timer.unref?.();
1918
- })]);
1919
- clearTimeout(timer);
1920
- };
1921
- /**
1922
- * Runs a write that may need a type's index to reach further back first.
1923
- * Such a write returns ['index', type, after] having written nothing, and
1924
- * runs again once INDEX_TYPE_LUA has indexed that history, a page per call.
1925
- */
1926
- const indexing = async (sessionId, run) => {
1927
- for (;;) {
1928
- const reply = await run();
1929
- if (reply[0] !== "index") return reply;
1930
- for (;;) {
1931
- const [done] = await evalScript(INDEX_TYPE_LUA, sessionId, [], [String(reply[1]), Number(reply[2])]);
1932
- if (done === "1") break;
1933
- }
1934
- }
1935
- };
1936
- /** The frontier and clear marker, in one MGET. */
1937
- const readBounds = async (sessionId) => {
1938
- await prepared.get();
1939
- const [count, cleared] = await call("MGET", countKey(sessionId), clearKey(sessionId));
1940
- return {
1941
- frontier: toIndex({
1942
- raw: count ?? cleared,
1943
- sessionId,
1944
- name: "event count"
1945
- }),
1946
- clearIndex: toIndex({
1947
- raw: cleared,
1948
- sessionId,
1949
- name: "clear boundary"
1950
- })
1951
- };
1952
- };
1953
- const readClearIndex = async (sessionId) => {
1954
- await prepared.get();
1955
- return toIndex({
1956
- raw: await call("GET", clearKey(sessionId)),
1957
- sessionId,
1958
- name: "clear boundary"
1959
- });
1960
- };
1961
- const readEventPages = async (sessionId, afterIndex, throughIndex) => {
1962
- if (throughIndex <= afterIndex) return [];
1963
- const events = [];
1964
- let nextIndex = afterIndex + 1;
1965
- while (nextIndex <= throughIndex) {
1966
- const entries = await call("XRANGE", storeKey(sessionId), `${nextIndex}-0`, `${throughIndex}-0`, "COUNT", 256);
1967
- if (entries.length === 0) throw rangeGap(sessionId, `ended before index ${throughIndex}`);
1968
- for (let position = 0; position < entries.length; position += 1) {
1969
- const index = entryIndex(entries[position][0]);
1970
- if (index !== nextIndex + position || index > throughIndex) throw rangeGap(sessionId, "is not contiguous");
1971
- }
1972
- events.push(...entries.map((entry) => toEvent(sessionId, entry)));
1973
- nextIndex = events.at(-1).index + 1;
1974
- }
1975
- return events;
1976
- };
1977
- const readEventRange = async (sessionId, afterIndex, throughIndex) => {
1978
- const events = [];
1979
- for (let start = afterIndex; start < throughIndex; start += 256 * READ_CONCURRENCY) {
1980
- const ranges = Array.from({ length: Math.min(READ_CONCURRENCY, Math.ceil((throughIndex - start) / 256)) }, (_, position) => {
1981
- const after = start + position * 256;
1982
- return readEventPages(sessionId, after, Math.min(after + 256, throughIndex));
1983
- });
1984
- const results = await Promise.allSettled(ranges);
1985
- for (const result of results) {
1986
- if (result.status === "rejected") throw result.reason;
1987
- events.push(...result.value);
1988
- }
1989
- }
1990
- return events;
1991
- };
1992
- /** Bounded XRANGE pages restore the full-read contract on capped providers. */
1993
- const readRange = async (sessionId, afterIndex, throughIndex) => (await readBoundedRange(sessionId, afterIndex, throughIndex)).rows;
1994
- /** `readRange`, with the clear boundary its rows start at. */
1995
- const readBoundedRange = async (sessionId, afterIndex, throughIndex) => {
1996
- if (throughIndex !== void 0 && throughIndex <= afterIndex) return {
1997
- rows: [],
1998
- clearIndex: 0
1999
- };
2000
- const { frontier: currentFrontier, clearIndex } = await readBounds(sessionId);
2001
- const frontier = Math.min(throughIndex ?? currentFrontier, currentFrontier);
2002
- const after = Math.max(afterIndex, clearIndex - 1);
2003
- if (frontier <= after) return {
2004
- rows: [],
2005
- clearIndex
2006
- };
2007
- const rows = [];
2008
- let nextIndex = after + 1;
2009
- while (nextIndex <= frontier) {
2010
- const entries = await call("XRANGE", storeKey(sessionId), `${nextIndex}-0`, `${frontier}-0`, "COUNT", 256);
2011
- if (entries.length === 0) throw rangeGap(sessionId, `ended before index ${frontier}`);
2012
- const page = entries.map((entry) => toStoredEvent(sessionId, entry));
2013
- for (let position = 0; position < page.length; position += 1) if (page[position].index !== nextIndex + position) throw rangeGap(sessionId, "is not contiguous");
2014
- const lastIndex = page.at(-1).index;
2015
- if (lastIndex < nextIndex || lastIndex > frontier) throw new A2Error("STORE_UNAVAILABLE", `redis event range for session '${sessionId}' did not advance`);
2016
- rows.push(...page);
2017
- nextIndex = lastIndex + 1;
2018
- }
2019
- return {
2020
- rows,
2021
- clearIndex
2022
- };
2023
- };
2024
- const readStream = options.readStream;
2025
- return {
2026
- ...readStream ? { streamEvents: async function* ({ sessionId, afterIndex, signal }) {
2027
- try {
2028
- for await (const entries of readStream({
2029
- key: storeKey(sessionId),
2030
- from: `${afterIndex + 1}-0`,
2031
- signal
2032
- })) {
2033
- signal.throwIfAborted();
2034
- yield entries.map((entry) => toSerializedEvent(sessionId, entry));
2035
- }
2036
- } catch (cause) {
2037
- if (cause instanceof A2Error) throw cause;
2038
- throw new A2Error("STORE_UNAVAILABLE", "redis stream read failed", { cause });
2039
- }
2040
- } } : {},
2041
- async append(sessionId, events, appendOptions) {
2042
- return wrap(async () => {
2043
- const suppliedIds = events.filter((e) => e.id !== void 0).map((e) => e.id);
2044
- if (new Set(suppliedIds).size !== suppliedIds.length) throw new A2Error("PARTIAL_DUPLICATE_BATCH", "batch contains the same event id more than once");
2045
- const now = clock.now().getTime();
2046
- const ifLastIndex = appendOptions?.ifLastIndex;
2047
- const conditionalAt = (head) => ifLastIndex === void 0 ? void 0 : {
2048
- sessionId,
2049
- ifLastIndex,
2050
- head: Number(head)
2051
- };
2052
- const withIds = events.map((e) => ({
2053
- id: e.id ?? generateId(),
2054
- type: e.type,
2055
- payload: e.payload,
2056
- cause: e.cause ? { ...e.cause } : null,
2057
- targets: e.targets
2058
- }));
2059
- const payloads = withIds.map((e) => json(e.payload));
2060
- const reply = await indexing(sessionId, () => evalScript(APPEND_LUA, sessionId, [], [
2061
- sessionId,
2062
- now,
2063
- withIds.length,
2064
- servedArg(appendOptions?.consumers),
2065
- appendOptions?.originIndex ?? "",
2066
- ifLastIndex ?? "",
2067
- ...withIds.flatMap((e, i) => [
2068
- e.id,
2069
- e.type,
2070
- payloads[i],
2071
- e.cause ? json(e.cause) : "",
2072
- targetsArg(e.targets)
2073
- ])
2074
- ]));
2075
- const [verdict] = reply;
2076
- if (verdict === "empty") return {
2077
- events: [],
2078
- hasPending: reply[1] === "1"
2079
- };
2080
- if (verdict === "cleared") throw sessionClearedError(`scheduled work from event ${reply[1]} was cleared in session '${sessionId}'`);
2081
- if (verdict === "superseded") throw supersededAttemptError(sessionId, withIds[Number(reply[1]) - 1].cause);
2082
- if (verdict === "moved") throw lastIndexMismatchError(sessionId, ifLastIndex, Number(reply[1]));
2083
- if (verdict === "partial") throw duplicateBatchError(`batch mixes ${reply[1]} already-appended and ${events.length - Number(reply[1])} fresh events`, conditionalAt(reply[2]));
2084
- if (verdict === "dup") {
2085
- const hasPending = reply[1] === "1";
2086
- const firstIndex = Math.min(...reply.slice(3).map(Number));
2087
- const { rows: existing, clearIndex } = await retryAfterGap(() => readBoundedRange(sessionId, firstIndex - 1, firstIndex + events.length - 1));
2088
- if (firstIndex < clearIndex) throw new A2Error("STORE_UNAVAILABLE", `session '${sessionId}' was cleared while an append retry replayed; retry it`);
2089
- const replayed = idempotentReplay(events, existing, conditionalAt(reply[2]));
2090
- await publish(notifyChannel(sessionId), wakeMessage(firstIndex + events.length - 1, now, []));
2091
- return {
2092
- events: replayed,
2093
- hasPending
2094
- };
2095
- }
2096
- const base = Number(reply[1]) - 1;
2097
- await publish(notifyChannel(sessionId), wakeMessage(base + withIds.length, now, withIds.map((e, i) => [
2098
- base + 1 + i,
2099
- e.id,
2100
- e.type,
2101
- payloads[i]
2102
- ])));
2103
- return {
2104
- events: withIds.map((e, i) => ({
2105
- id: e.id,
2106
- type: e.type,
2107
- payload: structuredClone(e.payload),
2108
- index: base + 1 + i,
2109
- sessionId,
2110
- createdAt: new Date(now),
2111
- cause: e.cause
2112
- })),
2113
- hasPending: reply[2] === "1"
2114
- };
2115
- });
2116
- },
2117
- async cursors(sessionId) {
2118
- return wrap(async () => {
2119
- return (await runScript({
2120
- script: CURSORS_LUA,
2121
- keys: [countKey(sessionId)],
2122
- args: [],
2123
- readOnly: true
2124
- })).map(([consumer, tag, position, head, columns]) => Object.assign(dispatchOf(consumer, laneOf(tag), columns), {
2125
- position: Number(position),
2126
- head: head === null ? null : Number(head)
2127
- })).toSorted(byCursor);
2128
- });
2129
- },
2130
- async read(sessionId, opts) {
2131
- return wrap(() => retryAfterGap(() => readRange(sessionId, opts?.afterIndex ?? 0, opts?.throughIndex)));
2132
- },
2133
- async readHistory(sessionId, opts) {
2134
- const after = opts?.afterIndex ?? 0;
2135
- if (opts?.throughIndex !== void 0 && opts.throughIndex <= after) return [];
2136
- return wrap(() => retryAfterGap(async () => {
2137
- const { frontier, clearIndex } = await readBounds(sessionId);
2138
- return readEventRange(sessionId, Math.max(after, clearIndex - 1), Math.min(opts?.throughIndex ?? frontier, frontier));
2139
- }));
2140
- },
2141
- async claimAvailable({ sessionId, holder, ttlMs, expiresAtMs, exclude, consumers, maxFailures, through }) {
2142
- return wrap(async () => {
2143
- const now = clock.now().getTime();
2144
- const expiresAt = expiresAtMs ?? now + ttlMs;
2145
- const excluded = exclude ?? [];
2146
- const reply = await evalScript(CLAIM_AVAILABLE_LUA, sessionId, [], [
2147
- holder,
2148
- now,
2149
- expiresAt,
2150
- maxFailures ?? "",
2151
- servedArg(consumers),
2152
- through ?? "",
2153
- excluded.length,
2154
- ...excluded.flatMap((ref) => [ref.consumer, ref.lane === null ? `#${ref.index}` : `L${ref.lane}`])
2155
- ]);
2156
- return toClaimAvailableResult(sessionId, reply);
2157
- });
2158
- },
2159
- async renewClaims({ sessionId, holder, claims, ttlMs, expiresAtMs }) {
2160
- if (claims.length === 0) return {
2161
- renewed: [],
2162
- superseded: []
2163
- };
2164
- return wrap(async () => {
2165
- const now = clock.now().getTime();
2166
- const expiresAt = expiresAtMs ?? now + ttlMs;
2167
- const reply = await evalScript(RENEW_CLAIMS_LUA, sessionId, [], [
2168
- holder,
2169
- now,
2170
- expiresAt,
2171
- claims.length,
2172
- ...claims.flatMap((claim) => [
2173
- claim.consumer,
2174
- tagOf(claim.lane),
2175
- claim.index,
2176
- claim.attempt
2177
- ])
2178
- ]);
2179
- const renewedCount = Number(reply[0]);
2180
- const refs = reply.slice(1).map((position) => {
2181
- const { consumer, lane, index } = claims[Number(position) - 1];
2182
- return {
2183
- consumer,
2184
- lane,
2185
- index
2186
- };
2187
- });
2188
- return {
2189
- renewed: refs.slice(0, renewedCount).toSorted(byHead),
2190
- superseded: refs.slice(renewedCount).toSorted(byHead)
2191
- };
2192
- });
2193
- },
2194
- async completeAttempt({ sessionId, consumer, lane, index, attempt, events, consumers }) {
2195
- return wrap(async () => {
2196
- const ids = events.map((event) => event.id);
2197
- if (new Set(ids).size !== ids.length) throw new A2Error("PARTIAL_DUPLICATE_BATCH", "batch contains the same event id more than once");
2198
- const now = clock.now().getTime();
2199
- const cause = {
2200
- consumer,
2201
- lane,
2202
- index,
2203
- attempt
2204
- };
2205
- const payloads = events.map((event) => json(event.payload));
2206
- const reply = await indexing(sessionId, () => evalScript(COMPLETE_ATTEMPT_LUA, sessionId, [], [
2207
- sessionId,
2208
- now,
2209
- consumer,
2210
- tagOf(lane),
2211
- index,
2212
- attempt,
2213
- json(cause),
2214
- servedArg(consumers),
2215
- json(ids),
2216
- events.length,
2217
- ...events.flatMap((event, i) => [
2218
- event.id,
2219
- event.type,
2220
- payloads[i],
2221
- targetsArg(event.targets)
2222
- ])
2223
- ]));
2224
- const outcome = reply[0];
2225
- if (outcome === "missing") throw new TypeError(`no event at index ${index} in session '${sessionId}'`);
2226
- if (outcome === "partial") throw new A2Error("PARTIAL_DUPLICATE_BATCH", "returned event ids do not match the completed attempt");
2227
- if (outcome === "superseded") return { outcome };
2228
- if (outcome === "ok") {
2229
- const base = Number(reply[1]) - 1;
2230
- if (events.length > 0) await publish(notifyChannel(sessionId), wakeMessage(base + events.length, now, events.map((event, i) => [
2231
- base + 1 + i,
2232
- event.id,
2233
- event.type,
2234
- payloads[i]
2235
- ])));
2236
- return {
2237
- outcome: "completed",
2238
- events: events.map((event, i) => ({
2239
- id: event.id,
2240
- type: event.type,
2241
- payload: structuredClone(event.payload),
2242
- index: base + 1 + i,
2243
- sessionId,
2244
- createdAt: new Date(now),
2245
- cause: { ...cause }
2246
- }))
2247
- };
2248
- }
2249
- if (outcome === "duplicate") {
2250
- if (events.length === 0) return {
2251
- outcome: "completed",
2252
- events: []
2253
- };
2254
- const firstIndex = Math.min(...reply.slice(1).map(Number));
2255
- const { rows: existing, clearIndex } = await retryAfterGap(() => readBoundedRange(sessionId, firstIndex - 1, firstIndex + events.length - 1));
2256
- if (index <= clearIndex) return { outcome: "superseded" };
2257
- if (existing.some((row) => row.cause?.consumer !== consumer || row.cause.lane !== lane || row.cause.index !== index || row.cause.attempt !== attempt)) throw new A2Error("PARTIAL_DUPLICATE_BATCH", "returned event retry does not match the committed batch");
2258
- const replayed = idempotentReplay(events, existing);
2259
- await publish(notifyChannel(sessionId), wakeMessage(firstIndex + events.length - 1, now, []));
2260
- return {
2261
- outcome: "completed",
2262
- events: replayed
2263
- };
2264
- }
2265
- throw new TypeError(`unexpected completion outcome '${outcome}'`);
2266
- });
2267
- },
2268
- async failAttempt({ sessionId, consumer, lane, index, attempt, error, maxFailures, retryAfterMs }) {
2269
- return wrap(async () => {
2270
- const now = clock.now().getTime();
2271
- const reply = await evalScript(FAIL_ATTEMPT_LUA, sessionId, [], [
2272
- consumer,
2273
- tagOf(lane),
2274
- index,
2275
- attempt,
2276
- error,
2277
- maxFailures,
2278
- now,
2279
- retryAfterMs === void 0 ? "" : now + retryAfterMs
2280
- ]);
2281
- const outcome = reply[0];
2282
- if (outcome === "missing") throw new TypeError(`no event at index ${index} in session '${sessionId}'`);
2283
- return {
2284
- outcome,
2285
- failureCount: Number(reply[1])
2286
- };
2287
- });
2288
- },
2289
- async deadLetters(sessionId) {
2290
- return wrap(async () => {
2291
- return (await runScript({
2292
- script: DEAD_LETTERS_LUA,
2293
- keys: [countKey(sessionId)],
2294
- args: [],
2295
- readOnly: true
2296
- })).map((head) => toHeadEvent(sessionId, head)).toSorted(byHead);
2297
- });
2298
- },
2299
- async redrive({ sessionId, consumer, index, action, consumers }) {
2300
- return wrap(async () => {
2301
- const [redriven, hasPending] = await indexing(sessionId, () => evalScript(REDRIVE_LUA, sessionId, [], [
2302
- consumer,
2303
- index,
2304
- action,
2305
- clock.now().getTime(),
2306
- servedArg(consumers)
2307
- ]));
2308
- return {
2309
- redriven: redriven === "1",
2310
- hasPending: hasPending === "1"
2311
- };
2312
- });
2313
- },
2314
- async wakeLog({ sessionId, consumer }) {
2315
- return wrap(async () => {
2316
- const { name, log } = consumer;
2317
- const [, position, head, columns, sessionHead] = await indexing(sessionId, () => evalScript(WAKE_LOG_LUA, sessionId, [], [
2318
- name,
2319
- log.lane,
2320
- logTypesArg(log.types),
2321
- log.backfill ? 1 : 0
2322
- ]));
2323
- return {
2324
- cursor: Object.assign(dispatchOf(name, log.lane, columns), {
2325
- position: Number(position),
2326
- head: head === null ? null : Number(head)
2327
- }),
2328
- head: Number(sessionHead)
2329
- };
2330
- });
2331
- },
2332
- async readState(sessionId, reducerName, stateOptions) {
2333
- return wrap(() => retryAfterGap(async () => {
2334
- const reply = await runScript({
2335
- script: READ_STATE_LUA,
2336
- keys: [
2337
- countKey(sessionId),
2338
- snapKey(sessionId, reducerName),
2339
- snapHistoryKey(sessionId, reducerName)
2340
- ],
2341
- args: [stateOptions?.snapshotThroughIndex ?? stateOptions?.throughIndex ?? ""],
2342
- readOnly: true
2343
- });
2344
- const rawHead = reply[0];
2345
- const raw = reply[1];
2346
- const headIndex = rawHead === "" ? null : Number(rawHead);
2347
- const parsed = raw === "" ? null : JSON.parse(raw);
2348
- const currentFrontier = Number(reply[2]);
2349
- if (!Number.isSafeInteger(currentFrontier) || currentFrontier < 0 || headIndex !== null && (!Number.isSafeInteger(headIndex) || headIndex < 0) || parsed !== null && (!Number.isSafeInteger(parsed.index) || parsed.index < 0)) throw new A2Error("STORE_UNAVAILABLE", `redis state frontier for session '${sessionId}' is invalid`);
2350
- const frontier = Math.min(currentFrontier, stateOptions?.throughIndex ?? currentFrontier);
2351
- const snapshot = parsed;
2352
- const clearIndex = Number(reply[3] ?? 0);
2353
- const events = await readEventRange(sessionId, Math.max(snapshot?.index ?? 0, clearIndex - 1), frontier);
2354
- return {
2355
- ...clearIndex > 0 ? { clearIndex } : {},
2356
- headIndex,
2357
- snapshot: snapshot ? {
2358
- index: snapshot.index,
2359
- state: snapshot.state
2360
- } : null,
2361
- events
2362
- };
2363
- }));
2364
- },
2365
- async putSnapshots(sessionId, reducerName, writes) {
2366
- const byIndex = /* @__PURE__ */ new Map();
2367
- for (const write of writes) {
2368
- const existing = byIndex.get(write.index);
2369
- const pins = existing?.pins ?? /* @__PURE__ */ new Map();
2370
- for (const pin of write.pins ?? []) pins.set(JSON.stringify([
2371
- pin.consumer,
2372
- pin.lane,
2373
- pin.index
2374
- ]), pin);
2375
- if (existing) existing.state = write.state;
2376
- else byIndex.set(write.index, {
2377
- index: write.index,
2378
- state: write.state,
2379
- pins
2380
- });
2381
- }
2382
- const normalized = [...byIndex.values()].toSorted((a, b) => a.index - b.index);
2383
- if (normalized.length === 0) return;
2384
- await wrap(async () => {
2385
- const args = [normalized.length];
2386
- for (const write of normalized) args.push(write.index, json({
2387
- index: write.index,
2388
- state: write.state,
2389
- updatedAt: clock.now().getTime(),
2390
- r: 1
2391
- }), write.pins.size, ...[...write.pins.values()].flatMap((pin) => [
2392
- pin.consumer,
2393
- tagOf(pin.lane),
2394
- pin.index
2395
- ]));
2396
- await evalScript(PUT_SNAPSHOTS_LUA, sessionId, [snapKey(sessionId, reducerName), snapHistoryKey(sessionId, reducerName)], [...args, reducerName]);
2397
- });
2398
- },
2399
- presence: {
2400
- async set(ns, participant, values, meta) {
2401
- return wrap(async () => {
2402
- const entries = Object.entries(values);
2403
- if (entries.length === 0) return null;
2404
- const atMs = meta.at.getTime();
2405
- const nowMs = clock.now().getTime();
2406
- const expiresAtMs = nowMs + meta.ttlMs;
2407
- const applied = await runScript({
2408
- script: PRESENCE_SET_LUA,
2409
- keys: [presenceKey(ns)],
2410
- args: [
2411
- atMs,
2412
- meta.ttlMs,
2413
- nowMs,
2414
- entries.length,
2415
- ...entries.flatMap(([field, value]) => [JSON.stringify([participant, field]), json({
2416
- a: atMs,
2417
- e: expiresAtMs,
2418
- s: meta.seen,
2419
- v: value
2420
- })])
2421
- ],
2422
- readOnly: false
2423
- });
2424
- if (applied.length === 0) return null;
2425
- const appliedValues = nullProtoRecord();
2426
- const published = [];
2427
- for (const position of applied) {
2428
- const [field, value] = entries[Number(position) - 1];
2429
- appliedValues[field] = structuredClone(value);
2430
- published.push(`${json(field)}:${json(value)}`);
2431
- }
2432
- return {
2433
- patch: {
2434
- participant,
2435
- values: appliedValues,
2436
- seen: meta.seen,
2437
- at: new Date(atMs)
2438
- },
2439
- published: publish(presenceChannel(ns), `${json({
2440
- src: options.presenceSource,
2441
- participant,
2442
- seen: meta.seen,
2443
- at: atMs
2444
- }).slice(0, -1)},"values":{${published.join(",")}}}`)
2445
- };
2446
- });
2447
- },
2448
- async read(ns) {
2449
- return wrap(async () => {
2450
- const key = presenceKey(ns);
2451
- const reply = await call("HGETALL", key);
2452
- const nowMs = clock.now().getTime();
2453
- const rows = [];
2454
- const expired = [];
2455
- for (let i = 0; i + 1 < reply.length; i += 2) {
2456
- const entry = JSON.parse(reply[i + 1]);
2457
- if (entry.e <= nowMs) {
2458
- expired.push(reply[i]);
2459
- continue;
2460
- }
2461
- if (entry.v === null) continue;
2462
- const [participant, field] = JSON.parse(reply[i]);
2463
- rows.push({
2464
- participant,
2465
- field,
2466
- value: entry.v,
2467
- seen: entry.s,
2468
- at: new Date(entry.a),
2469
- expiresAt: new Date(entry.e)
2470
- });
2471
- }
2472
- if (expired.length > 0) await runScript({
2473
- script: PRESENCE_PRUNE_LUA,
2474
- keys: [key],
2475
- args: [nowMs, ...expired],
2476
- readOnly: false
2477
- }).catch(() => void 0);
2478
- return rows;
2479
- });
2480
- }
2481
- },
2482
- async readRange(sessionId, afterIndex, throughIndex) {
2483
- return wrap(() => readRange(sessionId, afterIndex, throughIndex));
2484
- },
2485
- async readTail(sessionId, fromIndex, throughIndex) {
2486
- return wrap(async () => {
2487
- const [newest, clearIndex] = await Promise.all([call("XREVRANGE", storeKey(sessionId), throughIndex === void 0 ? "+" : `${throughIndex}-0`, `${fromIndex}-0`, "COUNT", 256), readClearIndex(sessionId)]);
2488
- if (clearIndex > fromIndex) return null;
2489
- const page = newest.toReversed().map((entry) => toEvent(sessionId, entry));
2490
- for (let position = 1; position < page.length; position += 1) if (page[position].index !== page[position - 1].index + 1) throw new A2Error("STORE_UNAVAILABLE", `redis event range for session '${sessionId}' is not contiguous`);
2491
- const oldest = page[0]?.index;
2492
- return oldest === void 0 || oldest <= fromIndex ? page : null;
2493
- });
2494
- },
2495
- async clear({ sessionId, ifLastIndex, cause }) {
2496
- return wrap(async () => {
2497
- const markerId = generateId();
2498
- const now = clock.now().getTime();
2499
- const reply = await evalScript(CLEAR_LUA, sessionId, [], [
2500
- sessionId,
2501
- now,
2502
- ifLastIndex ?? "",
2503
- cause?.consumer ?? "",
2504
- cause ? tagOf(cause.lane) : "",
2505
- cause?.index ?? "",
2506
- cause?.attempt ?? "",
2507
- markerId
2508
- ]);
2509
- if (reply[0] === "superseded") throw supersededAttemptError(sessionId, cause);
2510
- if (reply[0] === "foreign") throw new A2Error("PARTIAL_DUPLICATE_BATCH", `the clear marker id '${markerId}' already exists`);
2511
- const head = Number(reply[2]);
2512
- if (reply[4] === "1") await publish(notifyChannel(sessionId), wakeMessage(head, now, [[
2513
- head,
2514
- markerId,
2515
- CLEAR_EVENT_TYPE,
2516
- "null"
2517
- ]]));
2518
- else if (reply[1] === "1" && head > 0) await publish(notifyChannel(sessionId), wakeMessage(head, now, []));
2519
- return {
2520
- cleared: reply[1] === "1",
2521
- index: Number(reply[2]),
2522
- clearIndex: Number(reply[3])
2523
- };
2524
- });
2525
- },
2526
- async reclaim(sessionId) {
2527
- return wrap(async () => {
2528
- const pairs = await evalScript(RECLAIM_BATCH_LUA, sessionId, [], [256]);
2529
- if (pairs.length === 0) return {
2530
- deleted: 0,
2531
- done: true
2532
- };
2533
- const [deleted, done] = await evalScript(RECLAIM_LUA, sessionId, [], [
2534
- sessionId,
2535
- pairs.length / 2,
2536
- ...pairs
2537
- ]);
2538
- return {
2539
- deleted: Number(deleted),
2540
- done: Number(done) === 1
2541
- };
2542
- });
2543
- },
2544
- clearIndex: (sessionId) => wrap(() => readClearIndex(sessionId)),
2545
- async readEvents(sessionId, afterIndex) {
2546
- return wrap(async () => {
2547
- return (await call("XRANGE", storeKey(sessionId), `${afterIndex + 1}-0`, "+", "COUNT", 256)).map((entry) => toEvent(sessionId, entry));
2548
- });
2549
- },
2550
- async readFeedPage(sessionId, afterIndex) {
2551
- return wrap(async () => {
2552
- const range = [
2553
- storeKey(sessionId),
2554
- `${afterIndex + 1}-0`,
2555
- "+",
2556
- "COUNT",
2557
- FEED_PAGE_SIZE
2558
- ];
2559
- if (callBytes) return (await callBytes("XRANGE", ...range)).map((entry) => bytesToSerializedEvent(sessionId, entry));
2560
- return (await call("XRANGE", ...range)).map((entry) => toSerializedEvent(sessionId, entry));
2561
- });
2562
- }
2563
- };
2564
- }
2565
- /** A feed that falls this far behind drops its inbox and catches up. */
2566
- const INBOX_BYTES = 524288;
2567
- /**
2568
- * Parses a wake-up message: `{"f":frontier}` or a bare frontier number
2569
- * announces events without carrying them; `{"f","t","e"}` carries them.
2570
- * Returns null for anything else, which callers treat as a hint to catch up.
2571
- */
2572
- const parseWake = (message) => {
2573
- let parsed;
2574
- try {
2575
- parsed = JSON.parse(message);
2576
- } catch {
2577
- return null;
2578
- }
2579
- if (typeof parsed === "number") return Number.isSafeInteger(parsed) ? {
2580
- frontier: parsed,
2581
- createdAt: 0,
2582
- entries: []
2583
- } : null;
2584
- if (typeof parsed !== "object" || parsed === null) return null;
2585
- const { f, t, e } = parsed;
2586
- if (typeof f !== "number" || !Number.isSafeInteger(f)) return null;
2587
- if (e === void 0) return {
2588
- frontier: f,
2589
- createdAt: 0,
2590
- entries: []
2591
- };
2592
- if (!Array.isArray(e) || typeof t !== "number" || !Number.isFinite(t)) return null;
2593
- for (const entry of e) if (!Array.isArray(entry) || entry.length !== 4 || !Number.isSafeInteger(entry[0]) || typeof entry[1] !== "string" || typeof entry[2] !== "string") return null;
2594
- return {
2595
- frontier: f,
2596
- createdAt: t,
2597
- entries: e
2598
- };
2599
- };
2600
- function createRedisNotifyStore(options) {
2601
- const { client, clock, ids, keyPrefix: prefix } = options;
2602
- const notifyChannel = (sessionId) => `${prefix}:${sessionId}:notify`;
2603
- const presenceChannel = (ns) => `${prefix}:${ns}:presence`;
2604
- const instanceId = crypto.randomUUID();
2605
- const core = createRedisStoreCore({
2606
- call: async (command, ...args) => {
2607
- return (await client()).call(command, ...args);
2608
- },
2609
- clock,
2610
- ids,
2611
- keyPrefix: prefix,
2612
- presenceSource: instanceId,
2613
- ...options.callBytes ? { callBytes: options.callBytes } : {},
2614
- ...options.readStream ? { readStream: options.readStream } : {}
2615
- });
2616
- let severed = false;
2617
- let subscriber = null;
2618
- /** channel → live event feeds, registered before they subscribe. */
2619
- const feeds = /* @__PURE__ */ new Map();
2620
- /** channel → refcounted subscription held for each live iterator. */
2621
- const subscriptions = /* @__PURE__ */ new Map();
2622
- const presenceSubscriptions = /* @__PURE__ */ new Map();
2623
- const pollingStreams = /* @__PURE__ */ new Set();
2624
- options.onReconnect?.((channel) => {
2625
- for (const feed of feeds.get(channel) ?? []) {
2626
- feed.dirty = true;
2627
- feed.wake?.();
2628
- }
2629
- presenceSubscriptions.get(channel)?.recovery?.reconnect().catch(() => {});
2630
- });
2631
- const deliverRemotePresence = ({ subscription, message }) => {
2632
- let parsed;
2633
- try {
2634
- parsed = JSON.parse(message);
2635
- } catch {
2636
- return;
2637
- }
2638
- if (parsed.src === instanceId) return;
2639
- const patch = {
2640
- participant: parsed.participant,
2641
- values: parsed.values,
2642
- seen: parsed.seen,
2643
- at: new Date(parsed.at)
2644
- };
2645
- subscription.recovery?.update(patch);
2646
- for (const listener of subscription.listeners) listener(patch);
2647
- };
2648
- const getSubscriber = () => {
2649
- subscriber ??= (async () => {
2650
- const conn = (await client()).duplicate();
2651
- conn.on("message", (channel, message) => {
2652
- for (const feed of feeds.get(channel) ?? []) {
2653
- if (feed.bytes + message.length <= INBOX_BYTES) {
2654
- feed.inbox.push(message);
2655
- feed.bytes += message.length;
2656
- } else {
2657
- feed.inbox.length = 0;
2658
- feed.held.length = 0;
2659
- feed.gapSince = void 0;
2660
- feed.bytes = 0;
2661
- feed.dirty = true;
2662
- }
2663
- feed.wake?.();
2664
- }
2665
- const subscription = presenceSubscriptions.get(channel);
2666
- if (subscription) deliverRemotePresence({
2667
- subscription,
2668
- message
2669
- });
2670
- });
2671
- return conn;
2672
- })();
2673
- return subscriber;
2674
- };
2675
- /**
2676
- * The subscriber, gated on connection readiness — for channel
2677
- * commands only (`close` uses the ungated promise, so it can never
2678
- * hang on an unreachable server). SUBSCRIBE carries redis's
2679
- * ok-loading flag, so ioredis writes it mid-handshake, ahead of the
2680
- * ready check's INFO — which then finds the connection already in
2681
- * subscriber mode and fails the check (a spurious error event plus
2682
- * a reconnect). ECHO has no such flag: it resolves only once the
2683
- * connection is ready, so every channel command chained behind it
2684
- * lands after the check.
2685
- */
2686
- let subscriberGate = null;
2687
- const gatedSubscriber = () => {
2688
- if (subscriberGate) return subscriberGate;
2689
- const gate = getSubscriber().then(async (conn) => {
2690
- await conn.call("echo", "ready");
2691
- return conn;
2692
- });
2693
- subscriberGate = gate;
2694
- gate.catch(() => {
2695
- if (subscriberGate === gate) subscriberGate = null;
2696
- });
2697
- return gate;
2698
- };
2699
- const acquireChannel = async (channel) => {
2700
- const existing = subscriptions.get(channel);
2701
- if (existing) {
2702
- existing.refs += 1;
2703
- try {
2704
- await existing.ready;
2705
- } catch (err) {
2706
- existing.refs -= 1;
2707
- throw err;
2708
- }
2709
- return;
2710
- }
2711
- const lease = {
2712
- refs: 1,
2713
- ready: gatedSubscriber().then(async (conn) => {
2714
- await conn.call("subscribe", channel);
2715
- if (subscriptions.get(channel) !== lease || severed) return;
2716
- const presence = presenceSubscriptions.get(channel);
2717
- if (options.polling?.() && presence) {
2718
- presence.recovery = void 0;
2719
- const ns = channel.slice(prefix.length + 1, -9);
2720
- presence.poll = pollPresence({
2721
- read: () => core.presence.read(ns),
2722
- deliver: (patch) => {
2723
- for (const listener of presence.listeners) listener(patch);
2724
- }
2725
- });
2726
- await presence.poll.ready;
2727
- }
2728
- })
2729
- };
2730
- subscriptions.set(channel, lease);
2731
- try {
2732
- await lease.ready;
2733
- } catch (err) {
2734
- if (subscriptions.get(channel) === lease) {
2735
- subscriptions.delete(channel);
2736
- const presence = presenceSubscriptions.get(channel);
2737
- presence?.poll?.stop();
2738
- if (presence) presence.poll = void 0;
2739
- }
2740
- throw err;
2741
- }
2742
- };
2743
- const releaseChannel = (channel) => {
2744
- const lease = subscriptions.get(channel);
2745
- if (!lease) return;
2746
- lease.refs -= 1;
2747
- if (lease.refs > 0) return;
2748
- subscriptions.delete(channel);
2749
- gatedSubscriber().then((conn) => conn.call("unsubscribe", channel)).catch(() => {});
2750
- };
2751
- const store = {
2752
- append: core.append,
2753
- cursors: core.cursors,
2754
- read: core.read,
2755
- readHistory: core.readHistory,
2756
- claimAvailable: core.claimAvailable,
2757
- renewClaims: core.renewClaims,
2758
- completeAttempt: core.completeAttempt,
2759
- failAttempt: core.failAttempt,
2760
- readState: core.readState,
2761
- putSnapshots: core.putSnapshots,
2762
- clear: core.clear,
2763
- reclaim: core.reclaim,
2764
- deadLetters: core.deadLetters,
2765
- redrive: core.redrive,
2766
- wakeLog: core.wakeLog,
2767
- presence: {
2768
- async set(ns, participant, values, meta) {
2769
- const applied = await core.presence.set(ns, participant, values, meta);
2770
- if (!applied) return;
2771
- const { patch } = applied;
2772
- const channel = presenceChannel(ns);
2773
- const subscription = presenceSubscriptions.get(channel);
2774
- if (subscription) {
2775
- subscription.poll?.update(patch);
2776
- subscription.recovery?.update(patch);
2777
- for (const listener of subscription.listeners) listener(patch);
2778
- }
2779
- await applied.published;
2780
- },
2781
- async read(ns) {
2782
- const channel = presenceChannel(ns);
2783
- await subscriptions.get(channel)?.ready;
2784
- const subscription = presenceSubscriptions.get(channel);
2785
- return subscription?.recovery?.read() ?? subscription?.poll?.snapshot(() => core.presence.read(ns)) ?? core.presence.read(ns);
2786
- },
2787
- subscribe(ns, onPatch) {
2788
- const channel = presenceChannel(ns);
2789
- let subscription = presenceSubscriptions.get(channel);
2790
- if (!subscription) {
2791
- subscription = { listeners: /* @__PURE__ */ new Set() };
2792
- presenceSubscriptions.set(channel, subscription);
2793
- if (options.onReconnect && !options.polling?.()) {
2794
- const current = subscription;
2795
- subscription.recovery = presenceRecovery({
2796
- read: () => core.presence.read(ns),
2797
- deliver: (patch) => {
2798
- for (const listener of current.listeners) listener(patch);
2799
- },
2800
- isActive: () => !severed && presenceSubscriptions.get(channel) === current
2801
- });
2802
- }
2803
- }
2804
- subscription.listeners.add(onPatch);
2805
- acquireChannel(channel).catch(() => {});
2806
- let stopped = false;
2807
- return () => {
2808
- if (stopped) return;
2809
- stopped = true;
2810
- subscription.listeners.delete(onPatch);
2811
- if (subscription.listeners.size === 0) {
2812
- subscription.poll?.stop();
2813
- presenceSubscriptions.delete(channel);
2814
- }
2815
- releaseChannel(channel);
2816
- };
2817
- }
2818
- },
2819
- stream(sessionId, opts) {
2820
- const startAfter = opts?.startAfter ?? 0;
2821
- const channel = notifyChannel(sessionId);
2822
- return { [Symbol.asyncIterator]() {
2823
- let last = startAfter;
2824
- let buffer = [];
2825
- let closed = false;
2826
- let subscribed = false;
2827
- let pending = null;
2828
- let poller;
2829
- let stopActivity;
2830
- let catchup;
2831
- let stoppingRead;
2832
- const stopRead = () => {
2833
- const reading = catchup;
2834
- catchup = void 0;
2835
- if (reading) {
2836
- reading.controller.abort();
2837
- stoppingRead = reading.iterator.return(void 0).then(() => void 0).catch(() => {});
2838
- }
2839
- return stoppingRead ?? Promise.resolve();
2840
- };
2841
- const nextRead = async (after) => {
2842
- if (!catchup) {
2843
- const controller = new AbortController();
2844
- catchup = {
2845
- controller,
2846
- delivered: false,
2847
- iterator: core.streamEvents({
2848
- sessionId,
2849
- afterIndex: after,
2850
- signal: controller.signal
2851
- })[Symbol.asyncIterator]()
2852
- };
2853
- }
2854
- const reading = catchup;
2855
- const result = await reading.iterator.next();
2856
- if (result.done && catchup === reading) {
2857
- catchup = void 0;
2858
- if (reading.delivered) feed.dirty = true;
2859
- } else if (!result.done) reading.delivered = true;
2860
- return result;
2861
- };
2862
- const feed = {
2863
- inbox: [],
2864
- bytes: 0,
2865
- dirty: true,
2866
- held: [],
2867
- gapSince: void 0,
2868
- wake: null,
2869
- stopRead
2870
- };
2871
- const activity = createStreamActivity(() => {
2872
- if (poller) streamActivities.get(poller)?.activate();
2873
- });
2874
- const release = () => {
2875
- stopRead();
2876
- stopActivity?.();
2877
- if (poller) {
2878
- poller.return?.();
2879
- pollingStreams.delete(poller);
2880
- }
2881
- if (!subscribed) return;
2882
- subscribed = false;
2883
- const set = feeds.get(channel);
2884
- set?.delete(feed);
2885
- if (set?.size === 0) feeds.delete(channel);
2886
- releaseChannel(channel);
2887
- };
2888
- /**
2889
- * Moves carried events that continue this feed's sequence into
2890
- * the buffer. Writers publish after their scripts, so concurrent
2891
- * writers' wake-ups can arrive out of order: they apply in index
2892
- * order, and one past a gap is held until the gap fills or
2893
- * NOTIFY_TIMINGS.reorderMs passes. A message without events past
2894
- * the buffer, or an unreadable one, marks the feed dirty so it
2895
- * catches up with XRANGE.
2896
- */
2897
- const applyInbox = () => {
2898
- const carried = feed.held.splice(0);
2899
- let announced = 0;
2900
- for (const message of feed.inbox.splice(0)) {
2901
- const wake = parseWake(message);
2902
- if (!wake) feed.dirty = true;
2903
- else if (wake.entries.length === 0) announced = Math.max(announced, wake.frontier);
2904
- else carried.push({
2905
- wake,
2906
- bytes: message.length
2907
- });
2908
- }
2909
- carried.sort((a, b) => a.wake.entries[0][0] - b.wake.entries[0][0]);
2910
- feed.bytes = 0;
2911
- for (const held of carried) {
2912
- if (held.wake.entries[0][0] > (buffer.at(-1)?.index ?? last) + 1) {
2913
- feed.held.push(held);
2914
- feed.bytes += held.bytes;
2915
- continue;
2916
- }
2917
- for (const [index, id, type, payload] of held.wake.entries) {
2918
- if (index <= (buffer.at(-1)?.index ?? last)) continue;
2919
- buffer.push({
2920
- id,
2921
- type,
2922
- payload,
2923
- index,
2924
- sessionId,
2925
- createdAt: new Date(held.wake.createdAt)
2926
- });
2927
- }
2928
- }
2929
- if (announced > (buffer.at(-1)?.index ?? last)) feed.dirty = true;
2930
- if (feed.held.length === 0) feed.gapSince = void 0;
2931
- else feed.gapSince ??= Date.now();
2932
- };
2933
- const iterator = {
2934
- async next() {
2935
- for (;;) {
2936
- if (closed) {
2937
- release();
2938
- return {
2939
- value: void 0,
2940
- done: true
2941
- };
2942
- }
2943
- const row = buffer.shift();
2944
- if (row) {
2945
- let event;
2946
- try {
2947
- event = isSerializedEvent(row) ? parseSerializedEvent(row) : row;
2948
- } catch (cause) {
2949
- buffer = [];
2950
- feed.dirty = true;
2951
- release();
2952
- throw new A2Error("STORE_UNAVAILABLE", "redis stream read failed", { cause });
2953
- }
2954
- last = row.index;
2955
- return {
2956
- value: event,
2957
- done: false
2958
- };
2959
- }
2960
- if (severed) {
2961
- release();
2962
- throw new A2Error("STORE_UNAVAILABLE", "the store was closed");
2963
- }
2964
- try {
2965
- if (!subscribed) {
2966
- subscribed = true;
2967
- let set = feeds.get(channel);
2968
- if (!set) {
2969
- set = /* @__PURE__ */ new Set();
2970
- feeds.set(channel, set);
2971
- }
2972
- set.add(feed);
2973
- const [, clearIndex] = await Promise.all([acquireChannel(channel), core.clearIndex(sessionId)]);
2974
- if (clearIndex - 1 > last) last = clearIndex - 1;
2975
- if (closed || severed) continue;
2976
- }
2977
- if (options.polling?.()) {
2978
- if (!poller) {
2979
- poller = pollingStream((after) => core.readEvents(sessionId, after), { startAfter: last })[Symbol.asyncIterator]();
2980
- pollingStreams.add(poller);
2981
- stopActivity = streamActivities.get(poller)?.subscribe(activity.setIdle);
2982
- }
2983
- const result = await poller.next();
2984
- if (!result.done) presenceSubscriptions.get(presenceChannel(sessionId))?.poll?.wake();
2985
- if (severed) throw new A2Error("STORE_UNAVAILABLE", "the store was closed");
2986
- return result;
2987
- }
2988
- if (catchup) {
2989
- const result = await nextRead(last);
2990
- if (closed || severed) continue;
2991
- if (!result.done) buffer = result.value;
2992
- continue;
2993
- }
2994
- applyInbox();
2995
- if (buffer.length > 0) continue;
2996
- if (feed.gapSince !== void 0 && Date.now() - feed.gapSince >= NOTIFY_TIMINGS.reorderMs) feed.dirty = true;
2997
- if (feed.dirty) {
2998
- feed.dirty = false;
2999
- feed.held.length = 0;
3000
- feed.gapSince = void 0;
3001
- if (core.streamEvents) {
3002
- const result = await nextRead(last);
3003
- if (closed || severed) continue;
3004
- if (!result.done) buffer = result.value;
3005
- continue;
3006
- }
3007
- buffer = await core.readFeedPage(sessionId, last);
3008
- if (buffer.length >= 1e3) feed.dirty = true;
3009
- continue;
3010
- }
3011
- const woken = new Promise((resolve) => {
3012
- feed.wake = () => resolve("wake");
3013
- });
3014
- const holding = feed.gapSince !== void 0;
3015
- pending = defaultSleep(holding ? Math.max(0, NOTIFY_TIMINGS.reorderMs - (Date.now() - feed.gapSince)) : NOTIFY_TIMINGS.safetyReadMs);
3016
- const outcome = await Promise.race([woken, pending.promise.then(() => "timer")]);
3017
- pending.cancel();
3018
- pending = null;
3019
- if (outcome === "timer" && !holding) feed.dirty = true;
3020
- } catch (err) {
3021
- release();
3022
- if (closed) return {
3023
- value: void 0,
3024
- done: true
3025
- };
3026
- if (err instanceof A2Error) throw err;
3027
- throw new A2Error("STORE_UNAVAILABLE", "redis store operation failed", { cause: err });
3028
- } finally {
3029
- feed.wake = null;
3030
- }
3031
- }
3032
- },
3033
- async return() {
3034
- closed = true;
3035
- pending?.cancel();
3036
- feed.wake?.();
3037
- release();
3038
- await stopRead();
3039
- return {
3040
- value: void 0,
3041
- done: true
3042
- };
3043
- }
3044
- };
3045
- streamActivities.set(iterator, activity);
3046
- bufferedEvents.set(iterator, () => {
3047
- if (closed) return void 0;
3048
- const row = buffer.shift();
3049
- if (row) last = row.index;
3050
- return row;
3051
- });
3052
- return iterator;
3053
- } };
3054
- },
3055
- async close() {
3056
- severed = true;
3057
- for (const subscription of presenceSubscriptions.values()) subscription.poll?.stop();
3058
- presenceSubscriptions.clear();
3059
- for (const poller of pollingStreams) poller.return?.();
3060
- pollingStreams.clear();
3061
- const reads = [];
3062
- for (const set of feeds.values()) for (const feed of set) {
3063
- feed.wake?.();
3064
- reads.push(feed.stopRead());
3065
- }
3066
- await Promise.allSettled(reads);
3067
- if (subscriber) (await subscriber.catch(() => null))?.disconnect();
3068
- await options.closeClient();
3069
- }
3070
- };
3071
- stateTailReaders.set(store, core.readTail);
3072
- return store;
3073
- }
3074
- //#endregion
3075
- //#region src/store/redis-tables.ts
3076
- /**
3077
- * Applies an event's writes if it's the one to apply: with `next`, only the very
3078
- * next index; otherwise any index past the position. The check and the writes are
3079
- * one script, so a retried or superseded attempt changes nothing. Every key it
3080
- * touches comes in KEYS: the position first, then the writes' own.
3081
- */
3082
- const APPLY = `
3083
- local pos = tonumber(redis.call('GET', KEYS[1]) or '-1')
3084
- local index = tonumber(ARGV[1])
3085
- if ARGV[2] == 'next' then
3086
- if pos ~= index - 1 then return 0 end
3087
- elseif pos >= index then
3088
- return 0
3089
- end
3090
- for _, op in ipairs(cjson.decode(ARGV[3])) do
3091
- redis.call(op[1], KEYS[op[2]], unpack(op, 3))
3092
- end
3093
- redis.call('SET', KEYS[1], ARGV[1])
3094
- return 1
3095
- `;
3096
- /**
3097
- * The scripts' shared part: which of a page of IDs match every group (one of
3098
- * its sets each) and the text. Upstash bills each command a script runs, so a
3099
- * page costs one ZMSCORE per set and one HMGET for the text, whatever its size.
3100
- */
3101
- const MATCHES = `
3102
- local function matching(spec, from, ids)
3103
- local ok = {}
3104
- for i = 1, #ids do ok[i] = true end
3105
- for _, group in ipairs(spec.groups) do
3106
- -- The set the page came from holds every ID in it.
3107
- if not (#group == 1 and KEYS[group[1]] == from) then
3108
- local any = {}
3109
- for _, key in ipairs(group) do
3110
- local scores = redis.call('ZMSCORE', KEYS[key], unpack(ids))
3111
- for i = 1, #ids do if scores[i] then any[i] = true end end
3112
- end
3113
- for i = 1, #ids do if not any[i] then ok[i] = false end end
3114
- end
3115
- end
3116
- local metas = nil
3117
- if spec.text ~= cjson.null then
3118
- metas = redis.call('HMGET', KEYS[3], unpack(ids))
3119
- for i = 1, #ids do
3120
- if ok[i] and not string.find(cjson.decode(metas[i]).t, spec.text, 1, true) then ok[i] = false end
3121
- end
3122
- end
3123
- return ok, metas
3124
- end
3125
- local function driver(spec)
3126
- local best, size = KEYS[spec.fallback], nil
3127
- for _, key in ipairs(spec.drivers) do
3128
- local n = redis.call('ZCARD', KEYS[key])
3129
- if size == nil or n < size then best, size = KEYS[key], n end
3130
- end
3131
- return best
3132
- end
3133
- `;
3134
- /**
3135
- * Messages that match, walking the smallest index set newest first (oldest first
3136
- * with \`asc\`) and testing the others a page at a time, until \`limit\` or until
3137
- * it has read \`budget\` IDs: Redis runs nothing else while a script runs, so a
3138
- * long read goes in several. Returns the position, the matches, and where to go
3139
- * on from (false when the set ran out). KEYS: position, messages, metas, then
3140
- * the sets.
3141
- */
3142
- const MESSAGES = `${MATCHES}
3143
- local spec = cjson.decode(ARGV[1])
3144
- local from = driver(spec)
3145
- local found, n, read = {}, 0, 0
3146
- local low, high = spec.min, spec.max
3147
- local more = true
3148
- while n < spec.limit do
3149
- if read >= spec.budget then break end
3150
- local count = math.min(200, spec.budget - read)
3151
- local ids
3152
- if spec.asc then ids = redis.call('ZRANGEBYSCORE', from, low, high, 'LIMIT', 0, count)
3153
- else ids = redis.call('ZREVRANGEBYSCORE', from, high, low, 'LIMIT', 0, count) end
3154
- if #ids == 0 then more = false break end
3155
- local ok = matching(spec, from, ids)
3156
- for i, id in ipairs(ids) do
3157
- read = read + 1
3158
- if spec.asc then low = '(' .. id else high = '(' .. id end
3159
- if ok[i] then
3160
- n = n + 1
3161
- found[n] = id
3162
- if n >= spec.limit then break end
3163
- end
3164
- end
3165
- end
3166
- local rows = {}
3167
- if n > 0 then rows = redis.call('HMGET', KEYS[2], unpack(found)) end
3168
- local next = false
3169
- if more and n < spec.limit then if spec.asc then next = low else next = high end end
3170
- return { redis.call('GET', KEYS[1]) or '0', rows, next }
3171
- `;
3172
- /**
3173
- * The latest threads in a channel, or across several, from their thread order
3174
- * sets: each set's first \`limit\`, merged. KEYS: position, then the sets.
3175
- */
3176
- const LATEST = `
3177
- local spec = cjson.decode(ARGV[1])
3178
- local roots = {}
3179
- for i = 2, #KEYS do
3180
- local ids
3181
- if spec.asc then ids = redis.call('ZRANGEBYSCORE', KEYS[i], spec.min, '+inf', 'WITHSCORES', 'LIMIT', 0, spec.limit)
3182
- else ids = redis.call('ZREVRANGEBYSCORE', KEYS[i], '+inf', spec.min, 'WITHSCORES', 'LIMIT', 0, spec.limit) end
3183
- for j = 1, #ids, 2 do roots[#roots + 1] = ids[j] roots[#roots + 1] = ids[j + 1] end
3184
- end
3185
- return { redis.call('GET', KEYS[1]) or '0', roots }
3186
- `;
3187
- /**
3188
- * The threads with a message that matches: every match's root, once, and its
3189
- * latest reply, reading at most \`budget\` IDs. Returns the position, the roots
3190
- * and their latest replies, and where to go on from. KEYS: position, messages,
3191
- * metas, summaries, then the sets.
3192
- */
3193
- const ROOTS = `${MATCHES}
3194
- local spec = cjson.decode(ARGV[1])
3195
- local from = driver(spec)
3196
- local roots, seen, read, high = {}, {}, 0, spec.max
3197
- while read < spec.budget do
3198
- local ids = redis.call('ZREVRANGEBYSCORE', from, high, '-inf', 'LIMIT', 0, math.min(200, spec.budget - read))
3199
- if #ids == 0 then return { redis.call('GET', KEYS[1]) or '0', roots, false } end
3200
- local ok, metas = matching(spec, from, ids)
3201
- local matched = {}
3202
- for i, id in ipairs(ids) do if ok[i] then matched[#matched + 1] = id end end
3203
- if #matched > 0 then
3204
- if metas then
3205
- local byId = {}
3206
- for i, id in ipairs(ids) do byId[id] = metas[i] end
3207
- metas = {}
3208
- for j, id in ipairs(matched) do metas[j] = byId[id] end
3209
- else
3210
- metas = redis.call('HMGET', KEYS[3], unpack(matched))
3211
- end
3212
- local fresh = {}
3213
- for j, id in ipairs(matched) do
3214
- local meta = cjson.decode(metas[j])
3215
- local root = id
3216
- if meta.re ~= cjson.null then root = tostring(meta.re) end
3217
- if not seen[root] then
3218
- seen[root] = true
3219
- fresh[#fresh + 1] = root
3220
- end
3221
- end
3222
- if #fresh > 0 then
3223
- local summaries = redis.call('HMGET', KEYS[4], unpack(fresh))
3224
- for j, root in ipairs(fresh) do
3225
- roots[#roots + 1] = root
3226
- roots[#roots + 1] = cjson.decode(summaries[j]).at
3227
- end
3228
- end
3229
- end
3230
- read = read + #ids
3231
- high = '(' .. ids[#ids]
3232
- end
3233
- return { redis.call('GET', KEYS[1]) or '0', roots, high }
3234
- `;
3235
- /** Each root, its reply count, and its latest reply (false when it has none). KEYS: messages, summaries. ARGV: the roots. */
3236
- const THREAD_ROWS = `
3237
- local summaries = redis.call('HMGET', KEYS[2], unpack(ARGV))
3238
- local lasts, slot = {}, {}
3239
- for i, root in ipairs(ARGV) do
3240
- summaries[i] = cjson.decode(summaries[i])
3241
- if tostring(summaries[i].at) ~= root then
3242
- lasts[#lasts + 1] = tostring(summaries[i].at)
3243
- slot[i] = #lasts
3244
- end
3245
- end
3246
- local rows = redis.call('HMGET', KEYS[1], unpack(ARGV))
3247
- local lastRows = {}
3248
- if #lasts > 0 then lastRows = redis.call('HMGET', KEYS[1], unpack(lasts)) end
3249
- local out = {}
3250
- for i = 1, #ARGV do
3251
- local last = false
3252
- if slot[i] then last = lastRows[slot[i]] end
3253
- out[i] = { rows[i], summaries[i].n, last }
3254
- end
3255
- return out
3256
- `;
3257
- /** Each message's latest version at or before ARGV[1]. KEYS: the version data, then each message's versions. */
3258
- const AT = `
3259
- local versions, slot = {}, {}
3260
- for i = 2, #KEYS do
3261
- local found = redis.call('ZREVRANGEBYSCORE', KEYS[i], ARGV[1], '-inf', 'LIMIT', 0, 1)
3262
- if #found > 0 then
3263
- versions[#versions + 1] = found[1]
3264
- slot[i - 1] = #versions
3265
- end
3266
- end
3267
- local data = {}
3268
- if #versions > 0 then data = redis.call('HMGET', KEYS[1], unpack(versions)) end
3269
- local out = {}
3270
- for i = 1, #KEYS - 1 do
3271
- if slot[i] then out[i] = data[slot[i]] else out[i] = false end
3272
- end
3273
- return out
3274
- `;
3275
- /** Each key's hash, whole. */
3276
- const HASHES = `
3277
- local out = {}
3278
- for i = 1, #KEYS do out[i] = redis.call('HGETALL', KEYS[i]) end
3279
- return out
3280
- `;
3281
- /**
3282
- * What an event reads before it applies, in one script so it reads the primary,
3283
- * where the position check runs: a replica can lag it. Nothing, when the
3284
- * position says it's not the one to apply (as APPLY checks). KEYS: position,
3285
- * messages, metas, summaries, sync threads, the copy's hash. ARGV: the index,
3286
- * the mode, the message, its root ('' to take the message's own), the sync
3287
- * thread, the copy ('' for none of each). Returns the message, its root's ID,
3288
- * the root, its summary, the sync thread, and the copy.
3289
- */
3290
- const BEFORE = `
3291
- local pos = tonumber(redis.call('GET', KEYS[1]) or '-1')
3292
- local index = tonumber(ARGV[1])
3293
- if ARGV[2] == 'next' then
3294
- if pos ~= index - 1 then return false end
3295
- elseif pos >= index then
3296
- return false
3297
- end
3298
- local message, root = false, ARGV[4]
3299
- if ARGV[3] ~= '' then
3300
- message = redis.call('HGET', KEYS[2], ARGV[3])
3301
- if message and root == '' then
3302
- local re = cjson.decode(redis.call('HGET', KEYS[3], ARGV[3])).re
3303
- if re ~= cjson.null then root = tostring(re) end
3304
- end
3305
- end
3306
- local rootData, summary = false, false
3307
- if root ~= '' then
3308
- rootData = redis.call('HGET', KEYS[2], root)
3309
- summary = redis.call('HGET', KEYS[4], root)
3310
- end
3311
- local thread, copy = false, false
3312
- if ARGV[5] ~= '' then thread = redis.call('HGET', KEYS[5], ARGV[5]) end
3313
- if ARGV[6] ~= '' then copy = redis.call('HGET', KEYS[6], ARGV[6]) end
3314
- return { message, root, rootData, summary, thread, copy }
3315
- `;
3316
- /** The newest reply in a thread that isn't deleted, other than ARGV (false when none). KEYS: the thread, metas. */
3317
- const NEWEST = `
3318
- local skip = {}
3319
- for _, id in ipairs(ARGV) do skip[id] = true end
3320
- local high = '+inf'
3321
- while true do
3322
- local ids = redis.call('ZREVRANGEBYSCORE', KEYS[1], high, '-inf', 'LIMIT', 0, 100)
3323
- if #ids == 0 then return false end
3324
- local metas = redis.call('HMGET', KEYS[2], unpack(ids))
3325
- for i, id in ipairs(ids) do
3326
- if not skip[id] and not cjson.decode(metas[i]).d then return id end
3327
- end
3328
- high = '(' .. ids[#ids]
3329
- end
3330
- `;
3331
- /** Every message in a set of IDs (a thread, or those carrying an attachment), a thousand to an HMGET. KEYS: the set, messages. */
3332
- const THREAD = `
3333
- local ids = redis.call('ZRANGE', KEYS[1], 0, -1)
3334
- local rows = {}
3335
- for first = 1, #ids, 1000 do
3336
- local part = redis.call('HMGET', KEYS[2], unpack(ids, first, math.min(first + 999, #ids)))
3337
- for i = 1, #part do rows[#rows + 1] = part[i] end
3338
- end
3339
- return rows
3340
- `;
3341
- /** The position and every channel, read together. KEYS: position, channels. */
3342
- const CHANNELS = `
3343
- return { redis.call('GET', KEYS[1]) or '0', redis.call('SMEMBERS', KEYS[2]) }
3344
- `;
3345
- /**
3346
- * Upstash runs a script under a lock on the whole database unless the script
3347
- * sets `allow-key-locking`, and then locks only the hash tags of its KEYS and
3348
- * refuses any other key. Every key of the tables shares one tag, so a script
3349
- * locks only its board's tables; a `no-writes` one takes the shared lock. Redis
3350
- * and Valkey reject the flag, and have no such lock: one thread runs every
3351
- * command. A2's Redis store does the same for its sessions.
3352
- */
3353
- const KEY_LOCKING = "#!lua flags=allow-key-locking";
3354
- const READ_ONLY_KEY_LOCKING = "#!lua flags=no-writes,allow-key-locking";
3355
- /** A server that doesn't know the flag (Redis 7, Valkey), or shebangs at all (Redis 6). */
3356
- const SHEBANG_REJECTED = /shebang|unexpected symbol near '#'/i;
3357
- const SEP = "";
3358
- /** How many IDs one query script reads before it hands back where it got to. */
3359
- const SCAN_BUDGET = 4e3;
3360
- /** JSON a script decodes: Redis's cjson refuses an escaped lone surrogate, so each goes out as U+FFFD. */
3361
- const luaJson = (value) => JSON.stringify(value, (_key, item) => typeof item === "string" ? item.toWellFormed() : item);
3362
- /** The label sets a message is in: each key, and each key with its value. */
3363
- const labelTokens = (labels) => Object.entries(labels).flatMap(([key, value]) => [`l${SEP}${key}`, `lv${SEP}${key}${SEP}${value}`]);
3364
- /** A message is in its own label sets and, for a reply, its root's: "on the message or its root" is one lookup. */
3365
- const inLabelSets = (own, root) => /* @__PURE__ */ new Set([...labelTokens(own), ...root ? labelTokens(root) : []]);
3366
- /** The tables' keys, `<prefix>:{<prefix>:board}:<name>`: one hash tag, its board's own. */
3367
- const tablesKeyBase = (prefix) => `${prefix}:{${prefix}:board}`;
3368
- /**
3369
- * The tables on Redis: messages, versions, and sync rows in hashes and sorted
3370
- * sets under `<prefix>:{<prefix>:board}`, and a sorted set per filter value,
3371
- * scored by message ID. Each event is two scripts, one that reads what it
3372
- * changes and one that checks the position and writes; each query is one
3373
- * script, which walks the smallest set that applies.
3374
- *
3375
- * Every key shares the hash tag `{<prefix>:board}`: the board's alone, since a
3376
- * prefix can't hold a brace, and never an A2 session's, which is a JSON string.
3377
- * Each script declares every key it touches. Keys of an earlier layout,
3378
- * `<prefix>:board:<name>`, have other names, so they're never read: the tables
3379
- * fill from the log.
3380
- */
3381
- function redisTables(send, prefix, options = {}) {
3382
- if (prefix.includes("{") || prefix.includes("}")) throw new TypeError("a Redis keyPrefix can't contain braces: they'd set every key's hash tag");
3383
- const call = (command, ...args) => send(command, ...args.map((arg) => typeof arg === "string" ? arg.toWellFormed() : arg));
3384
- const budget = options.scanBudget ?? SCAN_BUDGET;
3385
- const p = tablesKeyBase(prefix);
3386
- const k = {
3387
- pos: `${p}:pos`,
3388
- messages: `${p}:m`,
3389
- metas: `${p}:x`,
3390
- summaries: `${p}:s`,
3391
- events: `${p}:e`,
3392
- versionData: `${p}:vd`,
3393
- all: `${p}:i:all`,
3394
- channels: `${p}:channels`,
3395
- threads: `${p}:t`,
3396
- syncThreads: `${p}:st`,
3397
- externalThreads: `${p}:et`,
3398
- externalMessages: `${p}:em`,
3399
- versions: (id) => `${p}:v:${id}`,
3400
- channel: (channel) => `${p}:i:c:${channel}`,
3401
- channelThreads: (channel) => `${p}:t:c:${channel}`,
3402
- /** A root's thread, it and its replies; a reply's holds just it. */
3403
- thread: (id) => `${p}:i:r:${id}`,
3404
- byActor: (actor) => `${p}:i:ba:${actor}`,
3405
- byPrincipal: (principal) => `${p}:i:bp:${principal}`,
3406
- mention: (actor) => `${p}:i:mn:${actor}`,
3407
- attachment: (id) => `${p}:i:at:${id}`,
3408
- from: (from) => `${p}:i:f:${from}`,
3409
- label: (token) => `${p}:i:${token}`,
3410
- copies: (id) => `${p}:cp:${id}`
3411
- };
3412
- const parse = (value) => value === null || value === void 0 || value === false ? null : JSON.parse(String(value));
3413
- /**
3414
- * Whether the server takes `allow-key-locking`, asked once, before the first script. Only its
3415
- * rejection of the flag means no: a transport error decides nothing, and the next script asks again.
3416
- */
3417
- let keyLocking = null;
3418
- const locking = () => keyLocking ??= call("EVAL", `${KEY_LOCKING}\nreturn 1`, 1, k.pos).then(() => true, (error) => {
3419
- if (SHEBANG_REJECTED.test(String(error?.message ?? error))) return false;
3420
- keyLocking = null;
3421
- throw error;
3422
- });
3423
- const run = async (flags, script, keys, args) => call("EVAL", await locking() ? `${flags}\n${script}` : script, keys.length, ...keys, ...args);
3424
- /** A query: on Upstash it takes the shared lock, beside other reads. */
3425
- const evaluate = (script, keys, args) => run(READ_ONLY_KEY_LOCKING, script, keys, args);
3426
- /**
3427
- * An event's apply, and the reads its writes are worked out from: they run as writing scripts,
3428
- * so they read where the write that checks the position runs, whatever a provider does with a
3429
- * read-only one.
3430
- */
3431
- const evaluateWrite = (script, keys, args) => run(KEY_LOCKING, script, keys, args);
3432
- async function messagesOf(ids) {
3433
- const out = /* @__PURE__ */ new Map();
3434
- if (ids.length === 0) return out;
3435
- const rows = await call("HMGET", k.messages, ...ids);
3436
- ids.forEach((id, i) => {
3437
- const message = parse(rows[i]);
3438
- if (message) out.set(id, message);
3439
- });
3440
- return out;
3441
- }
3442
- /**
3443
- * What the event reads before it applies: its message, its root's summary and labels, and the
3444
- * sync rows it changes. Null when the position says it's not the one to apply.
3445
- */
3446
- async function before(event, id, mode) {
3447
- const posted = event.type === "message.posted";
3448
- const reads = syncReads(event);
3449
- const keys = [
3450
- k.pos,
3451
- k.messages,
3452
- k.metas,
3453
- k.summaries,
3454
- k.syncThreads,
3455
- reads.copy === null ? k.pos : k.copies(reads.copy[0])
3456
- ];
3457
- const args = [
3458
- event.index,
3459
- mode,
3460
- id === null || posted ? "" : String(id),
3461
- posted && event.payload.re !== null ? String(event.payload.re) : "",
3462
- reads.thread ?? "",
3463
- reads.copy?.[1] ?? ""
3464
- ];
3465
- const found = await evaluateWrite(BEFORE, keys, args);
3466
- if (!found) return null;
3467
- const [data, rootId, rootData, rootSummary, thread, copy] = found;
3468
- const sync = {
3469
- thread: parse(thread) ?? void 0,
3470
- copy: parse(copy) ?? void 0
3471
- };
3472
- if (id === null) return {
3473
- read: null,
3474
- sync
3475
- };
3476
- const message = parse(data) ?? void 0;
3477
- const summary = parse(rootSummary);
3478
- const root = summary ? {
3479
- replies: summary.n,
3480
- at: summary.at
3481
- } : void 0;
3482
- const read = {
3483
- message,
3484
- root,
3485
- rootLabels: parse(rootData)?.labels ?? null
3486
- };
3487
- if (event.type === "message.deleted" && message && !message.deleted && root?.at === id) {
3488
- const newest = await evaluateWrite(NEWEST, [k.thread(Number(rootId)), k.metas], [String(rootId), String(id)]);
3489
- read.previousLast = newest === null || newest === void 0 || newest === false ? null : Number(newest);
3490
- }
3491
- return {
3492
- read,
3493
- sync
3494
- };
3495
- }
3496
- /** A root's replies, when its labels changed: they're in its label sets too. */
3497
- async function repliesOf(read, change) {
3498
- const after = change.message?.after;
3499
- if (!after || after.re !== null || change.message.created || !change.message.terms) return [];
3500
- if (JSON.stringify(after.labels) === JSON.stringify(read.message.labels)) return [];
3501
- return (await evaluateWrite(THREAD, [k.thread(after.id), k.messages], [])).flatMap((row) => {
3502
- const message = parse(row);
3503
- return message && message.id !== after.id ? [message] : [];
3504
- });
3505
- }
3506
- /** The event's writes, as commands. */
3507
- function writes(event, read, replies, change, sync) {
3508
- const out = [];
3509
- const m = change.message?.after;
3510
- if (m && read) {
3511
- const id = String(m.id);
3512
- const created = change.message.created;
3513
- const meta = {
3514
- re: m.re,
3515
- c: m.channel,
3516
- t: m.text.toLowerCase(),
3517
- d: m.deleted
3518
- };
3519
- out.push([
3520
- "HSET",
3521
- k.messages,
3522
- id,
3523
- JSON.stringify(m)
3524
- ], [
3525
- "HSET",
3526
- k.metas,
3527
- id,
3528
- luaJson(meta)
3529
- ]);
3530
- out.push([
3531
- "ZADD",
3532
- k.versions(id),
3533
- String(event.index),
3534
- String(event.index)
3535
- ], [
3536
- "HSET",
3537
- k.versionData,
3538
- String(event.index),
3539
- JSON.stringify(m)
3540
- ]);
3541
- if (created) {
3542
- out.push([
3543
- "HSET",
3544
- k.events,
3545
- event.id,
3546
- id
3547
- ], [
3548
- "SADD",
3549
- k.channels,
3550
- m.channel
3551
- ]);
3552
- for (const key of [
3553
- k.all,
3554
- k.channel(m.channel),
3555
- k.thread(id),
3556
- k.byActor(m.by.actor),
3557
- k.byPrincipal(m.by.principal),
3558
- k.from(m.from ?? "board")
3559
- ]) out.push([
3560
- "ZADD",
3561
- key,
3562
- id,
3563
- id
3564
- ]);
3565
- if (m.re !== null) out.push([
3566
- "ZADD",
3567
- k.thread(m.re),
3568
- id,
3569
- id
3570
- ]);
3571
- }
3572
- if (change.message.terms) {
3573
- const old = read.message;
3574
- const rootLabels = m.re === null ? null : read.rootLabels;
3575
- const was = created ? /* @__PURE__ */ new Set() : inLabelSets(old.labels, rootLabels);
3576
- const is = inLabelSets(m.labels, rootLabels);
3577
- for (const token of was) if (!is.has(token)) out.push([
3578
- "ZREM",
3579
- k.label(token),
3580
- id
3581
- ]);
3582
- for (const token of is) if (!was.has(token)) out.push([
3583
- "ZADD",
3584
- k.label(token),
3585
- id,
3586
- id
3587
- ]);
3588
- const mentionedBefore = new Set(created ? [] : old.mentions);
3589
- const mentioned = new Set(m.mentions);
3590
- for (const actor of mentionedBefore) if (!mentioned.has(actor)) out.push([
3591
- "ZREM",
3592
- k.mention(actor),
3593
- id
3594
- ]);
3595
- for (const actor of mentioned) if (!mentionedBefore.has(actor)) out.push([
3596
- "ZADD",
3597
- k.mention(actor),
3598
- id,
3599
- id
3600
- ]);
3601
- const filesBefore = new Set(created ? [] : old.attachments.map((file) => file.id));
3602
- const files = new Set(m.attachments.map((file) => file.id));
3603
- for (const file of filesBefore) if (!files.has(file)) out.push([
3604
- "ZREM",
3605
- k.attachment(file),
3606
- id
3607
- ]);
3608
- for (const file of files) if (!filesBefore.has(file)) out.push([
3609
- "ZADD",
3610
- k.attachment(file),
3611
- id,
3612
- id
3613
- ]);
3614
- for (const reply of replies) {
3615
- const replyWas = inLabelSets(reply.labels, old.labels);
3616
- const replyIs = inLabelSets(reply.labels, m.labels);
3617
- for (const token of replyWas) if (!replyIs.has(token)) out.push([
3618
- "ZREM",
3619
- k.label(token),
3620
- String(reply.id)
3621
- ]);
3622
- for (const token of replyIs) if (!replyWas.has(token)) out.push([
3623
- "ZADD",
3624
- k.label(token),
3625
- String(reply.id),
3626
- String(reply.id)
3627
- ]);
3628
- }
3629
- }
3630
- }
3631
- if (change.summary) {
3632
- const { root, replies, at } = change.summary;
3633
- const channel = m?.channel ?? read?.message?.channel;
3634
- out.push([
3635
- "HSET",
3636
- k.summaries,
3637
- String(root),
3638
- JSON.stringify({
3639
- n: replies,
3640
- at
3641
- })
3642
- ], [
3643
- "ZADD",
3644
- k.threads,
3645
- String(at),
3646
- String(root)
3647
- ]);
3648
- if (channel !== void 0) out.push([
3649
- "ZADD",
3650
- k.channelThreads(channel),
3651
- String(at),
3652
- String(root)
3653
- ]);
3654
- }
3655
- if (sync.thread) out.push([
3656
- "HSET",
3657
- k.syncThreads,
3658
- sync.thread.key,
3659
- JSON.stringify(sync.thread.data)
3660
- ]);
3661
- for (const [external, thread] of sync.externalThreads) out.push([
3662
- "HSET",
3663
- k.externalThreads,
3664
- external,
3665
- thread
3666
- ]);
3667
- for (const [message, target, copy] of sync.copies) out.push([
3668
- "HSET",
3669
- k.copies(message),
3670
- target,
3671
- JSON.stringify(copy)
3672
- ]);
3673
- for (const [key, message] of sync.externalMessages) out.push([
3674
- "HSET",
3675
- k.externalMessages,
3676
- key,
3677
- String(message)
3678
- ]);
3679
- return out;
3680
- }
3681
- async function commit(event, mode) {
3682
- const found = await before(event, concernedMessageId(event), mode);
3683
- if (!found) return false;
3684
- const { read, sync: syncRead } = found;
3685
- const change = read ? project(read, event) : {};
3686
- const ops = writes(event, read, read ? await repliesOf(read, change) : [], change, projectSync(syncRead, event));
3687
- const keys = [k.pos];
3688
- const slots = /* @__PURE__ */ new Map();
3689
- const encoded = ops.map(([command, key, ...args]) => {
3690
- if (!slots.has(key)) slots.set(key, keys.push(key));
3691
- return [
3692
- command,
3693
- slots.get(key),
3694
- ...args
3695
- ];
3696
- });
3697
- return Number(await evaluateWrite(APPLY, keys, [
3698
- event.index,
3699
- mode,
3700
- luaJson(encoded)
3701
- ])) === 1;
3702
- }
3703
- /**
3704
- * The channels under `path`, and the position that list reflects. A read's
3705
- * position goes no further: a post in a channel newer than the list is past
3706
- * it, so the feed from that position carries it.
3707
- */
3708
- async function channelsUnder(path) {
3709
- const [at, all] = await evaluate(CHANNELS, [k.pos, k.channels], []);
3710
- return {
3711
- under: all.filter((c) => c.startsWith(`${path}/`)),
3712
- asOf: Number(at)
3713
- };
3714
- }
3715
- /** A filter as groups of sets, each group needing one: the query scripts' input, and the position it holds for. */
3716
- async function compile(filter, keys) {
3717
- const slot = (key) => keys.push(key);
3718
- const groups = [];
3719
- const group = (sets) => groups.push(sets.map(slot));
3720
- let asOf = Number.POSITIVE_INFINITY;
3721
- if (filter.channel) {
3722
- const { path, subtree } = filter.channel;
3723
- let under = [];
3724
- if (subtree) ({under, asOf} = await channelsUnder(path));
3725
- group([path, ...under].map(k.channel));
3726
- }
3727
- if (filter.channels) group(filter.channels.map(k.channel));
3728
- if (filter.re !== void 0) group([k.thread(filter.re)]);
3729
- if (filter.by) group([...filter.by.actors.map(k.byActor), ...filter.by.principals.map(k.byPrincipal)]);
3730
- if (filter.mentions) group(filter.mentions.map(k.mention));
3731
- if (filter.from !== void 0) group([k.from(filter.from)]);
3732
- for (const label of filter.labels ?? []) group(label.values === null ? [k.label(`l${SEP}${label.key}`)] : label.values.map((value) => k.label(`lv${SEP}${label.key}${SEP}${value}`)));
3733
- return {
3734
- spec: {
3735
- groups,
3736
- drivers: groups.filter((sets) => sets.length === 1).map((sets) => sets[0]),
3737
- fallback: slot(k.all),
3738
- text: filter.text ?? null
3739
- },
3740
- asOf
3741
- };
3742
- }
3743
- return {
3744
- async position() {
3745
- return Number(await call("GET", k.pos) ?? 0);
3746
- },
3747
- async apply(event) {
3748
- await commit(event, "any");
3749
- },
3750
- applyNext: (event) => commit(event, "next"),
3751
- async message(id) {
3752
- return (await messagesOf([id])).get(id) ?? null;
3753
- },
3754
- async byEventId(eventId) {
3755
- const id = await call("HGET", k.events, eventId);
3756
- return id === null || id === void 0 ? null : (await messagesOf([Number(id)])).get(Number(id)) ?? null;
3757
- },
3758
- async messagesAt(ids, index) {
3759
- const out = /* @__PURE__ */ new Map();
3760
- const wanted = [...new Set(ids)];
3761
- if (wanted.length === 0) return out;
3762
- const rows = await evaluate(AT, [k.versionData, ...wanted.map(k.versions)], [index]);
3763
- wanted.forEach((id, i) => {
3764
- const message = parse(rows[i]);
3765
- if (message) out.set(id, message);
3766
- });
3767
- return out;
3768
- },
3769
- async thread(root) {
3770
- const ids = (await call("ZRANGE", k.thread(root), 0, -1)).map(Number);
3771
- const found = await messagesOf(ids);
3772
- return ids.flatMap((id) => found.has(id) ? [found.get(id)] : []);
3773
- },
3774
- async messages(filter, page) {
3775
- const keys = [
3776
- k.pos,
3777
- k.messages,
3778
- k.metas
3779
- ];
3780
- const asc = page.after !== void 0;
3781
- const { spec: compiled, asOf } = await compile(filter, keys);
3782
- const spec = {
3783
- ...compiled,
3784
- limit: page.limit,
3785
- budget,
3786
- asc,
3787
- min: asc ? `(${page.after}` : "-inf",
3788
- max: page.before !== void 0 ? `(${page.before}` : "+inf"
3789
- };
3790
- let position = null;
3791
- const messages = [];
3792
- for (;;) {
3793
- const [at, rows, next] = await evaluate(MESSAGES, keys, [luaJson(spec)]);
3794
- position ??= Number(at);
3795
- for (const row of rows) messages.push(parse(row));
3796
- spec.limit = page.limit - messages.length;
3797
- if (next === null || spec.limit === 0) break;
3798
- if (asc) spec.min = next;
3799
- else spec.max = next;
3800
- }
3801
- return {
3802
- messages: asc ? messages : messages.reverse(),
3803
- position: Math.min(position, asOf)
3804
- };
3805
- },
3806
- async threads(filter, page) {
3807
- const asc = page.after !== void 0;
3808
- const { channel, channels, ...rest } = filter;
3809
- let position = null;
3810
- const roots = /* @__PURE__ */ new Map();
3811
- let asOf = Number.POSITIVE_INFINITY;
3812
- if (Object.keys(rest).length === 0 && !(channel && channels)) {
3813
- let under = [];
3814
- if (channel?.subtree) ({under, asOf} = await channelsUnder(channel.path));
3815
- const sets = channels ? channels.map(k.channelThreads) : channel ? [channel.path, ...under].map(k.channelThreads) : [k.threads];
3816
- const spec = {
3817
- limit: page.limit,
3818
- asc,
3819
- min: asc ? `(${page.after}` : "-inf"
3820
- };
3821
- const [at, pairs] = await evaluate(LATEST, [k.pos, ...sets], [luaJson(spec)]);
3822
- position = Number(at);
3823
- for (let i = 0; i < pairs.length; i += 2) roots.set(pairs[i], Number(pairs[i + 1]));
3824
- } else {
3825
- const keys = [
3826
- k.pos,
3827
- k.messages,
3828
- k.metas,
3829
- k.summaries
3830
- ];
3831
- const compiled = await compile(filter, keys);
3832
- asOf = compiled.asOf;
3833
- const spec = {
3834
- ...compiled.spec,
3835
- budget,
3836
- max: "+inf"
3837
- };
3838
- for (;;) {
3839
- const [at, pairs, next] = await evaluate(ROOTS, keys, [luaJson(spec)]);
3840
- position ??= Number(at);
3841
- for (let i = 0; i < pairs.length; i += 2) roots.set(String(pairs[i]), Number(pairs[i + 1]));
3842
- if (next === null) break;
3843
- spec.max = next;
3844
- }
3845
- }
3846
- const order = [...roots].filter(([, at]) => page.after === void 0 || at > page.after).sort(([, a], [, b]) => asc ? a - b : b - a).slice(0, page.limit).map(([root]) => root);
3847
- const threads = (order.length === 0 ? [] : await evaluate(THREAD_ROWS, [k.messages, k.summaries], order)).map(([root, replies, last]) => ({
3848
- root: parse(root),
3849
- replies: Number(replies),
3850
- last: parse(last)
3851
- }));
3852
- return {
3853
- threads: asc ? threads : threads.reverse(),
3854
- position: Math.min(position, asOf)
3855
- };
3856
- },
3857
- async syncOf(thread) {
3858
- return parse(await call("HGET", k.syncThreads, thread));
3859
- },
3860
- async threadOf(externalThread) {
3861
- const thread = await call("HGET", k.externalThreads, externalThread);
3862
- return thread === null || thread === void 0 ? null : String(thread);
3863
- },
3864
- async copiesOf(ids) {
3865
- const out = /* @__PURE__ */ new Map();
3866
- const wanted = [...new Set(ids)];
3867
- if (wanted.length === 0) return out;
3868
- const rows = await evaluate(HASHES, wanted.map(k.copies), []);
3869
- wanted.forEach((id, i) => {
3870
- const flat = rows[i] ?? [];
3871
- if (flat.length === 0) return;
3872
- const copies = {};
3873
- for (let at = 0; at < flat.length; at += 2) setOwn(copies, flat[at], JSON.parse(flat[at + 1]));
3874
- out.set(id, copies);
3875
- });
3876
- return out;
3877
- },
3878
- async messageOf(externalThread, platformMessage) {
3879
- const id = await call("HGET", k.externalMessages, externalMessageKey(externalThread, platformMessage));
3880
- return id === null || id === void 0 ? null : Number(id);
3881
- },
3882
- async externalThreads() {
3883
- return await call("HKEYS", k.externalThreads);
3884
- },
3885
- async withAttachment(attachment) {
3886
- return (await evaluate(THREAD, [k.attachment(attachment), k.messages], [])).flatMap((row) => {
3887
- const message = parse(row);
3888
- return message ? [message] : [];
3889
- });
3890
- },
3891
- async close() {}
3892
- };
3893
- }
3894
- //#endregion
3895
- export { createRedisNotifyStore as n, redisTables as t };