@relaybus/mongodb 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,75 +1,56 @@
1
1
  'use strict';
2
2
 
3
3
  var core = require('@relaybus/core');
4
+ var internal = require('@relaybus/core/internal');
4
5
 
5
6
  // src/mongo-event-store.ts
6
7
 
7
- // src/claim-scan.ts
8
- var ClaimScan = class {
9
- #keys = /* @__PURE__ */ new Map();
10
- /** Why the delivery must wait according to what this scan already knows, if it does. */
11
- verdict(orderingId, sequence) {
12
- const known = this.#keys.get(orderingId);
13
- if (known?.openSequence !== void 0 && sequence > known.openSequence) {
14
- return "open-predecessor";
15
- }
16
- return known?.leaseHeld === true ? "live-lease" : void 0;
17
- }
18
- /** Records an unfinished delivery of the key with this sequence. */
19
- noteOpen(orderingId, sequence) {
20
- const known = this.#know(orderingId);
21
- known.openSequence = Math.min(known.openSequence ?? sequence, sequence);
22
- }
23
- /** Records that this scan leased the delivery, which is now unfinished and holds a live lease. */
24
- noteClaimed(orderingId, sequence) {
25
- this.noteOpen(orderingId, sequence);
26
- this.#know(orderingId).leaseHeld = true;
27
- }
28
- /** Records that a live lease of the key blocks every delivery of it. */
29
- noteLeaseHeld(orderingId) {
30
- this.#know(orderingId).leaseHeld = true;
31
- }
32
- /** Remembers a delivery that waited behind an unfinished predecessor. */
33
- noteWaiting(orderingId, delivery) {
34
- if (delivery.status === "pending") {
35
- this.#know(orderingId).waiting.push(delivery._id);
36
- }
37
- }
38
- /**
39
- * Ids of the waiting deliveries of every key that accumulated at least
40
- * `minimum` of them. Shorter queues stay in the claim index: moving them out
41
- * and back would cost more than skipping them.
42
- */
43
- waitingBacklogs(minimum) {
44
- return [...this.#keys.values()].filter((known) => known.waiting.length >= minimum).flatMap((known) => known.waiting);
8
+ // src/lanes.ts
9
+ var LANE_COUNT = 256;
10
+ var FNV_OFFSET_BASIS = 2166136261;
11
+ var FNV_PRIME = 16777619;
12
+ var utf8 = new TextEncoder();
13
+ function laneOf(key, eventId) {
14
+ let hash = FNV_OFFSET_BASIS;
15
+ for (const byte of utf8.encode(key ?? eventId)) {
16
+ hash = Math.imul(hash ^ byte, FNV_PRIME);
45
17
  }
46
- #know(orderingId) {
47
- let known = this.#keys.get(orderingId);
48
- if (known === void 0) {
49
- known = { openSequence: void 0, leaseHeld: false, waiting: [] };
50
- this.#keys.set(orderingId, known);
51
- }
52
- return known;
18
+ return hash & LANE_COUNT - 1;
19
+ }
20
+ function formatLeaseToken(laneId, { epoch, claims }) {
21
+ return `${laneId}:${epoch}:${claims}`;
22
+ }
23
+ var LEASE_TOKEN_PATTERN = /^(\d{1,3}):(\d{1,15}):(\d{1,15})$/;
24
+ function parseLeaseToken(token) {
25
+ const match = LEASE_TOKEN_PATTERN.exec(token);
26
+ if (match === null || Number(match[1]) >= LANE_COUNT) {
27
+ return void 0;
53
28
  }
54
- };
55
- function orderingIdentity(handler, key) {
56
- return `${handler}\0${key}`;
29
+ return { laneId: Number(match[1]), epoch: Number(match[2]), claims: Number(match[3]) };
57
30
  }
58
- function toEventDocument(event, sequence) {
31
+
32
+ // src/documents.ts
33
+ function toEventDocument(event, {
34
+ sequence,
35
+ handlers,
36
+ createdAt
37
+ }) {
59
38
  const payloadJson = serializeWellFormed(event.payload, "payload");
60
39
  const headersJson = serializeWellFormed(event.headers, "headers");
61
40
  return {
62
41
  _id: event.id,
63
42
  type: event.type,
64
43
  source: event.source,
65
- key: event.key,
66
- sequence,
44
+ // Fields that are null or 0 are left out: every byte of a new document is written to the oplog too.
45
+ ...event.key === null ? {} : { key: event.key },
46
+ ...sequence === null ? {} : { sequence },
67
47
  ...payloadJson === void 0 ? {} : { payload: JSON.parse(payloadJson) },
68
48
  headers: JSON.parse(headersJson),
69
- correlationId: event.correlationId,
70
- causationId: event.causationId,
49
+ ...event.correlationId === null ? {} : { correlationId: event.correlationId },
50
+ ...event.causationId === null ? {} : { causationId: event.causationId },
71
51
  occurredAt: event.occurredAt,
72
- revision: 0
52
+ handlers,
53
+ createdAt
73
54
  };
74
55
  }
75
56
  var LONE_SURROGATE_ESCAPE = /(?<!\\)(?:\\\\)*\\ud[89a-f][0-9a-f]{2}/i;
@@ -90,48 +71,94 @@ function toEnvelope(document) {
90
71
  id: document._id,
91
72
  type: document.type,
92
73
  source: document.source,
93
- key: document.key,
74
+ key: document.key ?? null,
94
75
  payload: document.payload,
95
76
  headers: document.headers,
96
- correlationId: document.correlationId,
97
- causationId: document.causationId,
77
+ correlationId: document.correlationId ?? null,
78
+ causationId: document.causationId ?? null,
98
79
  occurredAt: document.occurredAt
99
80
  };
100
81
  }
101
- function toDeliveryDocument(delivery, event, ordering, now) {
82
+ function toDeliveryDocument(delivery, {
83
+ event,
84
+ ordering,
85
+ now
86
+ }) {
102
87
  return {
103
88
  _id: delivery.id,
104
89
  eventId: event.id,
105
90
  eventType: event.type,
106
91
  handler: delivery.handler,
107
92
  ...ordering.key === null || ordering.sequence === null ? {} : { key: ordering.key, sequence: ordering.sequence },
93
+ laneId: laneOf(ordering.key, event.id),
108
94
  status: "pending",
109
95
  lane: "ready",
110
96
  attempts: 0,
97
+ // No updatedAt (it equals createdAt): every byte of a new document is written to the oplog too.
111
98
  availableAt: delivery.availableAt,
112
99
  dueAt: delivery.availableAt,
113
- createdAt: now,
114
- updatedAt: now
100
+ createdAt: now
115
101
  };
116
102
  }
117
- function toDeliveryRecord(document, event) {
103
+ function toDeliveryRecord(document, {
104
+ event,
105
+ runningIn
106
+ }) {
118
107
  return {
119
108
  id: document._id,
120
109
  handler: document.handler,
121
- status: document.status,
122
- attempts: document.attempts,
110
+ status: runningIn === void 0 ? document.status : "processing",
111
+ attempts: runningIn === void 0 ? document.attempts : document.attempts + 1,
123
112
  availableAt: document.availableAt,
124
- leaseOwner: document.leaseOwner ?? null,
125
- leaseExpiresAt: document.leaseExpiresAt ?? null,
113
+ leaseOwner: runningIn === void 0 ? null : runningIn.owner,
114
+ leaseExpiresAt: runningIn === void 0 ? null : runningIn.leaseExpiresAt,
126
115
  lastError: document.lastError === void 0 ? null : toErrorInfo(document.lastError),
127
116
  createdAt: document.createdAt,
128
- updatedAt: document.updatedAt,
117
+ updatedAt: document.updatedAt ?? document.createdAt,
129
118
  completedAt: document.completedAt ?? null,
130
119
  event
131
120
  };
132
121
  }
122
+ function toCompletedDeliveryRecord(document, event) {
123
+ return {
124
+ id: document._id,
125
+ handler: document.handler,
126
+ status: "completed",
127
+ attempts: document.attempts,
128
+ availableAt: document.availableAt,
129
+ leaseOwner: null,
130
+ leaseExpiresAt: null,
131
+ lastError: null,
132
+ createdAt: document.createdAt,
133
+ updatedAt: document.completedAt,
134
+ completedAt: document.completedAt,
135
+ event
136
+ };
137
+ }
138
+ function toCompletedDeliveryDocument(document, completedAt) {
139
+ return {
140
+ _id: document._id,
141
+ eventId: document.eventId,
142
+ eventType: document.eventType,
143
+ handler: document.handler,
144
+ attempts: document.attempts + 1,
145
+ availableAt: document.availableAt,
146
+ createdAt: document.createdAt,
147
+ completedAt
148
+ };
149
+ }
133
150
  function toErrorInfo(error) {
134
- return error.stack === void 0 ? { name: error.name, message: error.message } : { name: error.name, message: error.message, stack: error.stack };
151
+ const info = {
152
+ name: error.name,
153
+ message: error.message
154
+ };
155
+ if (error.stack !== void 0) {
156
+ info.stack = error.stack;
157
+ }
158
+ if (error.code !== void 0) {
159
+ info.code = error.code;
160
+ }
161
+ return info;
135
162
  }
136
163
  var ILLEGAL_OPERATION = 20;
137
164
  function isTransactionsUnsupportedError(error) {
@@ -143,184 +170,97 @@ function createTransactionsUnsupportedError(cause) {
143
170
  { cause }
144
171
  );
145
172
  }
146
- var COLLECTION_PREFIX_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,39}$/;
147
- var DATABASE_NAME_PATTERN = /^[A-Za-z0-9_-]{1,63}$/;
148
- function assertCollectionPrefix(prefix) {
149
- if (!COLLECTION_PREFIX_PATTERN.test(prefix)) {
150
- throw new core.ConfigurationError(
151
- `collectionPrefix '${prefix}' must be 1-40 characters of letters, digits or '_', starting with a letter or '_'`
152
- );
173
+
174
+ // src/mongo-store-state.ts
175
+ async function runInTransaction(state, work) {
176
+ return runInTransactionWith(state, { work, transactionOptions: state.transactionOptions });
177
+ }
178
+ async function runInBudgetedTransaction(state, {
179
+ work,
180
+ timeoutMs
181
+ }) {
182
+ const budget = Math.ceil(timeoutMs);
183
+ return runInTransactionWith(state, {
184
+ work,
185
+ transactionOptions: { ...state.transactionOptions, maxCommitTimeMS: budget }
186
+ });
187
+ }
188
+ async function runInTransactionWith(state, {
189
+ work,
190
+ transactionOptions
191
+ }) {
192
+ try {
193
+ return await state.client.withSession(async (session) => {
194
+ let result;
195
+ await session.withTransaction(async () => {
196
+ result = await work(session);
197
+ }, transactionOptions);
198
+ return result;
199
+ });
200
+ } catch (error) {
201
+ if (isTransactionsUnsupportedError(error)) {
202
+ throw createTransactionsUnsupportedError(error);
203
+ }
204
+ throw error;
153
205
  }
154
206
  }
155
- function assertDatabaseName(name) {
156
- if (!DATABASE_NAME_PATTERN.test(name)) {
207
+ function leaseKey(deliveryId, leaseToken) {
208
+ return `${deliveryId}\0${leaseToken}`;
209
+ }
210
+ function assertInTransaction(session, operation) {
211
+ if (!session.inTransaction()) {
157
212
  throw new core.ConfigurationError(
158
- `database '${name}' must be 1-63 characters of letters, digits, '_' or '-'`
213
+ `MongoEventStore.${operation} needs a ClientSession inside a started transaction (session.withTransaction or startTransaction). Without one, MongoDB commits each write immediately and the write is no longer atomic with yours`
159
214
  );
160
215
  }
161
216
  }
217
+ function atCount(count) {
218
+ return count === 0 ? { $not: { $gt: 0 } } : count;
219
+ }
162
220
 
163
- // src/mongo-event-store.ts
164
- var DEFAULT_TRANSACTION_OPTIONS = {
165
- readConcern: { level: "snapshot" },
166
- writeConcern: { w: "majority" },
167
- readPreference: "primary"
168
- };
169
- var NAMESPACE_EXISTS = 48;
170
- var DEFAULT_PURGE_BATCH_SIZE = 500;
171
- var DEFAULT_LIST_LIMIT = 100;
172
- var MINIMUM_CANDIDATE_BATCH_SIZE = 32;
173
- var PARK_BACKLOG_THRESHOLD = 32;
174
- var PARK_UPDATE_CHUNK_SIZE = 1e3;
175
- var LEASE_FIELDS = { leaseOwner: "", leaseToken: "", leaseExpiresAt: "" };
176
- var FINISHED_FIELDS = { dueAt: "", lane: "" };
177
- var MongoEventStore = class {
178
- #client;
179
- #database;
180
- #events;
181
- #deliveries;
182
- #keySequences;
183
- #transactionOptions;
184
- #purgeBatchSize;
185
- #generateIdentifier;
186
- constructor(options) {
187
- const prefix = options.collectionPrefix ?? "relaybus_";
188
- assertCollectionPrefix(prefix);
189
- if (options.database !== void 0) {
190
- assertDatabaseName(options.database);
191
- }
192
- const purgeBatchSize = options.purgeBatchSize ?? DEFAULT_PURGE_BATCH_SIZE;
193
- if (!Number.isInteger(purgeBatchSize) || purgeBatchSize < 1) {
194
- throw new core.ConfigurationError(
195
- `purgeBatchSize must be a positive integer, received ${String(purgeBatchSize)}`
196
- );
197
- }
198
- this.#client = options.client;
199
- const database = options.client.db(options.database);
200
- this.#database = database;
201
- const collectionOptions = {
202
- readPreference: "primary",
203
- writeConcern: { w: "majority" }
204
- };
205
- this.#events = database.collection(`${prefix}events`, collectionOptions);
206
- this.#deliveries = database.collection(`${prefix}deliveries`, collectionOptions);
207
- this.#keySequences = database.collection(`${prefix}key_sequences`, collectionOptions);
208
- this.#transactionOptions = options.transactionOptions ?? DEFAULT_TRANSACTION_OPTIONS;
209
- this.#purgeBatchSize = purgeBatchSize;
210
- this.#generateIdentifier = options.generateIdentifier ?? (() => core.createUuidV7());
211
- }
212
- /**
213
- * Verifies the deployment supports transactions and creates the indexes.
214
- * Safe to run repeatedly and from several processes.
215
- *
216
- * @throws ConfigurationError when the server is a standalone mongod.
217
- */
218
- async setup() {
219
- const hello = await this.#client.db("admin").command({ hello: 1 });
220
- const supportsTransactions = typeof hello["setName"] === "string" || hello["msg"] === "isdbgrid";
221
- if (!supportsTransactions) {
222
- throw createTransactionsUnsupportedError(void 0);
223
- }
224
- for (const collection of [this.#events, this.#deliveries, this.#keySequences]) {
225
- await this.#createCollectionIfMissing(collection.collectionName);
226
- }
227
- await this.#deliveries.createIndexes([
228
- // Idempotent appends and lookups by event.
229
- { key: { eventId: 1, handler: 1 }, name: "event_handler", unique: true },
230
- // Claim: due work of a handler in due order. Holds ready deliveries only.
231
- {
232
- key: { handler: 1, dueAt: 1, _id: 1 },
233
- name: "claim",
234
- partialFilterExpression: { lane: "ready" }
235
- },
236
- // Ordering: unfinished predecessors of a keyed delivery, parked or not.
237
- {
238
- key: { handler: 1, key: 1, sequence: 1 },
239
- name: "ordering",
240
- partialFilterExpression: { dueAt: { $exists: true }, sequence: { $exists: true } }
241
- },
242
- // Parked deliveries: the lowest parked delivery of each key, to move it back once it is next.
243
- {
244
- key: { handler: 1, key: 1, sequence: 1 },
245
- name: "parked",
246
- partialFilterExpression: { lane: "parked" }
247
- },
248
- // Live leases: a keyed delivery may not start while another of its key is running.
249
- {
250
- key: { handler: 1, key: 1, dueAt: 1 },
251
- name: "running",
252
- partialFilterExpression: { status: "processing", key: { $exists: true } }
253
- },
254
- // Statistics: oldest due delivery across handlers.
255
- { key: { dueAt: 1 }, name: "due", partialFilterExpression: { dueAt: { $exists: true } } },
256
- // Purge of completed deliveries.
257
- {
258
- key: { completedAt: 1 },
259
- name: "completed",
260
- partialFilterExpression: { completedAt: { $exists: true } }
261
- },
262
- // Listing and status counts.
263
- { key: { status: 1, createdAt: 1 }, name: "status_created" },
264
- // Purge of dead deliveries.
265
- { key: { status: 1, updatedAt: 1 }, name: "status_updated" },
266
- { key: { handler: 1, createdAt: 1 }, name: "handler_created" },
267
- { key: { eventType: 1, createdAt: 1 }, name: "type_created" }
268
- ]);
269
- }
270
- async #createCollectionIfMissing(name) {
271
- try {
272
- await this.#database.createCollection(name);
273
- } catch (error) {
274
- if (!(typeof error === "object" && error !== null && "code" in error && error.code === NAMESPACE_EXISTS)) {
275
- throw error;
276
- }
277
- }
278
- }
279
- /**
280
- * Runs `work` in a transaction on a new session and commits when it resolves.
281
- *
282
- * `work` can run more than once. The driver restarts the whole callback after
283
- * a transient failure such as a write conflict, and re-sends only the commit
284
- * after an unknown commit result. A restart is safe for everything written
285
- * through the session, because the aborted attempt left nothing behind. It is
286
- * not safe for side effects outside the session (HTTP calls, other databases),
287
- * so keep those out of `work`; relaybus handlers are already at-least-once.
288
- *
289
- * @throws ConfigurationError when the deployment does not support transactions.
290
- */
291
- async transaction(work) {
292
- try {
293
- return await this.#client.withSession(async (session) => {
294
- let result;
295
- await session.withTransaction(async () => {
296
- result = await work(session);
297
- }, this.#transactionOptions);
298
- return result;
299
- });
300
- } catch (error) {
301
- if (isTransactionsUnsupportedError(error)) {
302
- throw createTransactionsUnsupportedError(error);
303
- }
304
- throw error;
305
- }
221
+ // src/mongo-append.ts
222
+ var MongoAppend = class {
223
+ #state;
224
+ constructor(state) {
225
+ this.#state = state;
306
226
  }
307
- async append(session, entries, now) {
227
+ /** Implements {@link MongoEventStore.append}. */
228
+ async append(session, { entries, now }) {
308
229
  assertInTransaction(session, "append");
309
230
  const eventIds = [...new Set(entries.map((entry) => entry.event.id))];
310
231
  const storedEvents = new Map(
311
- (await this.#events.find({ _id: { $in: eventIds } }, { session, projection: { key: 1, sequence: 1 } }).toArray()).map((stored) => [stored._id, stored])
312
- );
313
- const storedDeliveryKeys = new Set(
314
- (await this.#deliveries.find({ eventId: { $in: eventIds } }, { session, projection: { eventId: 1, handler: 1 } }).toArray()).map((stored) => deliveryPairKey(stored.eventId, stored.handler))
232
+ (await this.#state.events.find(
233
+ { _id: { $in: eventIds } },
234
+ { session, projection: { key: 1, sequence: 1, handlers: 1 } }
235
+ ).toArray()).map((stored) => [stored._id, stored])
315
236
  );
237
+ const plan = await this.#planAppend({ session, entries, storedEvents, now });
238
+ await this.#writeAppend({ session, plan, storedEvents, now });
239
+ return {
240
+ appendedEventIds: plan.appendedEventIds,
241
+ duplicateEventIds: plan.duplicateEventIds,
242
+ appendedDeliveryCount: plan.newDeliveries.length
243
+ };
244
+ }
245
+ /**
246
+ * Decides, in entry order, which events are new (taking their key sequence) and which deliveries
247
+ * each event still lacks.
248
+ */
249
+ async #planAppend(input) {
250
+ const { session, entries, storedEvents, now } = input;
316
251
  const appendedEventIds = [];
317
252
  const duplicateEventIds = [];
318
253
  const newEvents = [];
319
254
  const newDeliveries = [];
320
- const touchedEventIds = /* @__PURE__ */ new Set();
255
+ const knownHandlers = /* @__PURE__ */ new Map();
256
+ const addedHandlers = /* @__PURE__ */ new Map();
321
257
  const orderingByEventId = /* @__PURE__ */ new Map();
322
258
  for (const [eventId, stored] of storedEvents) {
323
- orderingByEventId.set(eventId, { key: stored.key, sequence: stored.sequence });
259
+ orderingByEventId.set(eventId, {
260
+ key: stored.key ?? null,
261
+ sequence: stored.sequence ?? null
262
+ });
263
+ knownHandlers.set(eventId, new Set(stored.handlers));
324
264
  }
325
265
  for (const { event, deliveries } of entries) {
326
266
  let ordering = orderingByEventId.get(event.id);
@@ -328,44 +268,61 @@ var MongoEventStore = class {
328
268
  const sequence = event.key === null ? null : await this.#nextSequence(event.key, session);
329
269
  ordering = { key: event.key, sequence };
330
270
  orderingByEventId.set(event.id, ordering);
331
- newEvents.push(toEventDocument(event, sequence));
271
+ knownHandlers.set(event.id, /* @__PURE__ */ new Set());
272
+ newEvents.push({ event, sequence });
332
273
  appendedEventIds.push(event.id);
333
274
  } else {
334
275
  duplicateEventIds.push(event.id);
335
276
  }
277
+ const handlers = knownHandlers.get(event.id);
336
278
  for (const delivery of deliveries) {
337
- const pairKey = deliveryPairKey(event.id, delivery.handler);
338
- if (storedDeliveryKeys.has(pairKey)) {
279
+ if (handlers.has(delivery.handler)) {
339
280
  continue;
340
281
  }
341
- storedDeliveryKeys.add(pairKey);
342
- newDeliveries.push(toDeliveryDocument(delivery, event, ordering, now));
343
- if (storedEvents.has(event.id)) {
344
- touchedEventIds.add(event.id);
345
- }
282
+ handlers.add(delivery.handler);
283
+ addedHandlers.set(event.id, [...addedHandlers.get(event.id) ?? [], delivery.handler]);
284
+ newDeliveries.push(toDeliveryDocument(delivery, { event, ordering, now }));
346
285
  }
347
286
  }
287
+ return { appendedEventIds, duplicateEventIds, newEvents, newDeliveries, addedHandlers };
288
+ }
289
+ /** Writes the new events, the handlers added to existing events and the new deliveries, in that order. */
290
+ async #writeAppend(input) {
291
+ const { session, plan, storedEvents, now } = input;
292
+ const { newEvents, newDeliveries, addedHandlers } = plan;
348
293
  if (newEvents.length > 0) {
349
- await this.#events.bulkWrite(
350
- newEvents.map((document) => ({
294
+ await this.#state.events.bulkWrite(
295
+ newEvents.map(({ event, sequence }) => {
296
+ const document = toEventDocument(event, {
297
+ sequence,
298
+ handlers: addedHandlers.get(event.id) ?? [],
299
+ createdAt: now
300
+ });
301
+ return {
302
+ updateOne: {
303
+ filter: { _id: document._id },
304
+ update: { $setOnInsert: document },
305
+ upsert: true
306
+ }
307
+ };
308
+ }),
309
+ { session, ordered: true }
310
+ );
311
+ }
312
+ const extendedEvents = [...addedHandlers].filter(([eventId]) => storedEvents.has(eventId));
313
+ if (extendedEvents.length > 0) {
314
+ await this.#state.events.bulkWrite(
315
+ extendedEvents.map(([eventId, handlers]) => ({
351
316
  updateOne: {
352
- filter: { _id: document._id },
353
- update: { $setOnInsert: document },
354
- upsert: true
317
+ filter: { _id: eventId },
318
+ update: { $inc: { revision: 1 }, $push: { handlers: { $each: handlers } } }
355
319
  }
356
320
  })),
357
321
  { session, ordered: true }
358
322
  );
359
323
  }
360
- if (touchedEventIds.size > 0) {
361
- await this.#events.updateMany(
362
- { _id: { $in: [...touchedEventIds] } },
363
- { $inc: { revision: 1 } },
364
- { session }
365
- );
366
- }
367
324
  if (newDeliveries.length > 0) {
368
- await this.#deliveries.bulkWrite(
325
+ await this.#state.deliveries.bulkWrite(
369
326
  newDeliveries.map((document) => ({
370
327
  updateOne: {
371
328
  filter: { eventId: document.eventId, handler: document.handler },
@@ -376,249 +333,1033 @@ var MongoEventStore = class {
376
333
  { session, ordered: true }
377
334
  );
378
335
  }
379
- return { appendedEventIds, duplicateEventIds, appendedDeliveryCount: newDeliveries.length };
380
336
  }
381
- async claim(request) {
382
- if (request.handlers.length === 0 || request.limit <= 0) {
383
- return [];
384
- }
385
- await this.#unparkNextDeliveries(request.handlers);
386
- const claimed = [];
387
- const scan = new ClaimScan();
388
- const candidates = this.#deliveries.find(
389
- { handler: { $in: [...request.handlers] }, dueAt: { $lte: request.now }, lane: "ready" },
390
- {
391
- sort: { dueAt: 1, _id: 1 },
392
- batchSize: Math.max(request.limit * 2, MINIMUM_CANDIDATE_BATCH_SIZE)
393
- }
337
+ /** Atomically increments the counter of `key`; conflicting appends of the key serialize here. */
338
+ async #nextSequence(key, session) {
339
+ const counter = await this.#state.keySequences.findOneAndUpdate(
340
+ { _id: key },
341
+ { $inc: { value: 1 } },
342
+ { upsert: true, returnDocument: "after", session }
394
343
  );
395
- try {
396
- for await (const candidate of candidates) {
397
- const leased = await this.#claimCandidate(candidate, request, scan);
398
- if (leased !== void 0) {
399
- claimed.push(leased);
400
- if (claimed.length >= request.limit) {
401
- break;
402
- }
403
- }
404
- }
405
- } finally {
406
- await candidates.close();
407
- }
408
- await this.#parkDeliveries(scan.waitingBacklogs(PARK_BACKLOG_THRESHOLD));
409
- return this.#toClaimedDeliveries(claimed, request.leaseExpiresAt);
344
+ return counter.value;
410
345
  }
411
- async extendLease(lease, leaseExpiresAt, now) {
412
- return this.#updateLeased(lease, void 0, {
413
- $set: { leaseExpiresAt, dueAt: leaseExpiresAt, updatedAt: now }
414
- });
346
+ };
347
+
348
+ // src/claim-scan.ts
349
+ var ClaimScan = class {
350
+ #keys = /* @__PURE__ */ new Map();
351
+ /** Whether an unfinished delivery this scan knows of comes before the delivery with `sequence`. */
352
+ waits(orderingId, sequence) {
353
+ const known = this.#keys.get(orderingId);
354
+ return known?.openSequence !== void 0 && sequence > known.openSequence;
415
355
  }
416
- async complete(lease, now, session) {
417
- if (session !== void 0) {
418
- assertInTransaction(session, "complete");
419
- }
420
- return this.#updateLeased(lease, session, {
421
- $set: { status: "completed", completedAt: now, updatedAt: now },
422
- $unset: { ...LEASE_FIELDS, ...FINISHED_FIELDS }
423
- });
356
+ /** Whether this scan already learned anything about the key. */
357
+ knows(orderingId) {
358
+ return this.#keys.has(orderingId);
424
359
  }
425
- async reschedule(lease, availableAt, error, now) {
426
- return this.#updateLeased(lease, void 0, {
427
- $set: {
428
- status: "pending",
429
- availableAt,
430
- dueAt: availableAt,
431
- lastError: toErrorInfo(error),
432
- updatedAt: now
433
- },
434
- $unset: LEASE_FIELDS
435
- });
360
+ /** Records an unfinished delivery of the key with this sequence. */
361
+ noteOpen(orderingId, sequence) {
362
+ const known = this.#know(orderingId);
363
+ known.openSequence = Math.min(known.openSequence ?? sequence, sequence);
436
364
  }
437
- async release(lease, now) {
438
- return this.#updateLeased(lease, void 0, {
439
- $set: { status: "pending", availableAt: now, dueAt: now, updatedAt: now },
440
- $inc: { attempts: -1 },
441
- $unset: LEASE_FIELDS
442
- });
365
+ /** Remembers a pending delivery of lane `laneId` that waited behind an unfinished predecessor. */
366
+ noteWaiting(orderingId, { deliveryId, laneId }) {
367
+ const known = this.#know(orderingId);
368
+ known.waiting.push(deliveryId);
369
+ known.laneId = laneId;
443
370
  }
444
- async bury(lease, error, now) {
445
- return this.#updateLeased(lease, void 0, {
446
- $set: { status: "dead", lastError: toErrorInfo(error), updatedAt: now },
447
- $unset: { ...LEASE_FIELDS, ...FINISHED_FIELDS }
448
- });
371
+ /**
372
+ * Ids of the waiting deliveries of every key that accumulated at least
373
+ * `minimum` of them, or that lives in one of `handedBack`. Shorter queues
374
+ * of a lane that stays held remain in the claim index: moving them out and
375
+ * back would cost more than skipping them. In a lane handed back they are
376
+ * all its due work, and leaving them ready would make every later claim take
377
+ * the lane for nothing.
378
+ */
379
+ waitingBacklogs(minimum, handedBack) {
380
+ return [...this.#keys.values()].filter((known) => known.waiting.length >= minimum || handedBack.has(known.laneId)).flatMap((known) => known.waiting);
449
381
  }
450
- async listDeliveries(query) {
451
- const filter = {
452
- ...query.status === void 0 ? {} : { status: String(query.status) },
453
- ...query.handler === void 0 ? {} : { handler: String(query.handler) },
454
- ...query.eventType === void 0 ? {} : { eventType: String(query.eventType) },
455
- ...query.eventId === void 0 ? {} : { eventId: String(query.eventId) }
456
- };
457
- const documents = await this.#deliveries.find(filter, { sort: { createdAt: 1, _id: 1 }, limit: query.limit ?? DEFAULT_LIST_LIMIT }).toArray();
458
- const events = await this.#readEnvelopes(documents.map((document) => document.eventId));
459
- return documents.map((document) => toDeliveryRecord(document, events.get(document.eventId)));
382
+ #know(orderingId) {
383
+ let known = this.#keys.get(orderingId);
384
+ if (known === void 0) {
385
+ known = { openSequence: void 0, waiting: [], laneId: void 0 };
386
+ this.#keys.set(orderingId, known);
387
+ }
388
+ return known;
460
389
  }
461
- async requeue(deliveryIds, now) {
462
- const result = await this.#deliveries.updateMany(
463
- { _id: { $in: deliveryIds.map(String) }, status: "dead" },
390
+ };
391
+ function orderingIdentity(handler, key) {
392
+ return `${handler}\0${key}`;
393
+ }
394
+
395
+ // src/mongo-claim.ts
396
+ var PARK_BACKLOG_THRESHOLD = 32;
397
+ var INITIAL_LANES_PER_ROUND = 4;
398
+ var LANES_PER_CANDIDATE_QUERY = 128;
399
+ function scopeOf(held) {
400
+ return new Map(
401
+ held.map((lane) => [
402
+ lane._id,
464
403
  {
465
- $set: {
466
- status: "pending",
467
- lane: "ready",
468
- attempts: 0,
469
- availableAt: now,
470
- dueAt: now,
471
- updatedAt: now
472
- }
404
+ laneId: lane._id,
405
+ epoch: lane.epoch,
406
+ listed: lane.inFlight,
407
+ revision: lane.revision ?? 0
473
408
  }
474
- );
475
- return result.modifiedCount;
409
+ ])
410
+ );
411
+ }
412
+ var MongoClaims = class {
413
+ #state;
414
+ #laneLeases;
415
+ #ordering;
416
+ #queries;
417
+ constructor(state, collaborators) {
418
+ this.#state = state;
419
+ this.#laneLeases = collaborators.laneLeases;
420
+ this.#ordering = collaborators.ordering;
421
+ this.#queries = collaborators.queries;
476
422
  }
477
- async purge(request) {
478
- const filters = [];
479
- if (request.completedBefore !== void 0) {
480
- filters.push({ status: "completed", completedAt: { $lt: request.completedBefore } });
423
+ /** Implements {@link MongoEventStore.claim}. */
424
+ async claim(request) {
425
+ if (request.handlers.length === 0 || request.limit <= 0) {
426
+ return [];
481
427
  }
482
- if (request.deadBefore !== void 0) {
483
- filters.push({ status: "dead", updatedAt: { $lt: request.deadBefore } });
428
+ const owner = request.leaseOwner;
429
+ const previous = this.#state.claimsInProgress.get(owner) ?? Promise.resolve();
430
+ const claimed = previous.then(() => this.#claimReconciled(request));
431
+ const settled = Promise.allSettled([claimed]);
432
+ this.#state.claimsInProgress.set(owner, settled);
433
+ void settled.then(() => {
434
+ if (this.#state.claimsInProgress.get(owner) === settled) {
435
+ this.#state.claimsInProgress.delete(owner);
436
+ }
437
+ });
438
+ return claimed;
439
+ }
440
+ /**
441
+ * Runs one claim and remembers what it hands out. When the claim fails at any
442
+ * point, also after its record reached the database without the reply
443
+ * reaching this process, the lanes this owner holds on this instance are
444
+ * reconciled: every listed delivery this instance has not handed out, or has
445
+ * handed out and seen settled, is taken out of them, so nothing stays listed
446
+ * as running that nobody runs.
447
+ */
448
+ async #claimReconciled(request) {
449
+ const owner = request.leaseOwner;
450
+ if (this.#state.unreconciledOwners.has(owner)) {
451
+ await this.#reconcileLanes(owner);
452
+ this.#state.unreconciledOwners.delete(owner);
484
453
  }
485
- let deletedDeliveries = 0;
486
- let deletedEvents = 0;
487
- for (const filter of filters) {
488
- const result = await this.#purgeMatching(filter);
489
- deletedDeliveries += result.deletedDeliveries;
490
- deletedEvents += result.deletedEvents;
454
+ try {
455
+ const claimed = await this.#claimNow(request);
456
+ for (const delivery of claimed) {
457
+ const { laneId, epoch } = parseLeaseToken(delivery.leaseToken);
458
+ this.#state.handedOut.set(leaseKey(delivery.deliveryId, delivery.leaseToken), {
459
+ deliveryId: delivery.deliveryId,
460
+ owner: request.leaseOwner,
461
+ laneId,
462
+ epoch
463
+ });
464
+ }
465
+ return claimed;
466
+ } catch (error) {
467
+ const [reconciled] = await Promise.allSettled([this.#reconcileLanes(owner)]);
468
+ if (reconciled.status === "rejected") {
469
+ this.#state.unreconciledOwners.add(owner);
470
+ }
471
+ throw error;
491
472
  }
492
- return { deletedDeliveries, deletedEvents };
493
473
  }
494
- async statistics(now) {
495
- const statuses = ["pending", "processing", "completed", "dead"];
496
- const [pending, processing, completed, dead] = await Promise.all(
497
- statuses.map((status) => this.#deliveries.countDocuments({ status }))
498
- );
499
- const oldestDue = await this.#deliveries.findOne(
500
- { dueAt: { $lte: now } },
501
- { sort: { dueAt: 1 }, projection: { dueAt: 1 } }
474
+ /**
475
+ * Takes every delivery this instance does not run out of the lanes `owner`
476
+ * holds on it: every listed delivery whose current claim (lane epoch and
477
+ * claim generation now) was not handed out by this instance, or was settled.
478
+ * One transaction, and the lanes are written first under their epoch and
479
+ * holder: a worker taking a lane over meanwhile conflicts with it, so its
480
+ * claim is never touched. The claim generation of every delivery taken out
481
+ * moves on, so no lease of those claims (a completion that failed and is
482
+ * retried later, say) can ever match a later claim of the same delivery.
483
+ * Registrations of this owner that are not the current claim of a listed
484
+ * delivery are dropped.
485
+ */
486
+ async #reconcileLanes(owner) {
487
+ await runInTransaction(this.#state, async (session) => {
488
+ const held = await this.#state.lanes.find({ owner, holder: this.#state.instanceId }, { session }).toArray();
489
+ const listed = held.flatMap((lane) => lane.inFlight);
490
+ const claimsById = new Map(
491
+ (await this.#state.deliveries.find(
492
+ { _id: { $in: listed }, status: "pending" },
493
+ { session, projection: { claims: 1 } }
494
+ ).toArray()).map((document) => [document._id, document.claims ?? 0])
495
+ );
496
+ const current = /* @__PURE__ */ new Set();
497
+ const unclaimed = held.map((lane) => ({
498
+ lane,
499
+ ids: lane.inFlight.filter((id) => {
500
+ const key = leaseKey(
501
+ id,
502
+ formatLeaseToken(lane._id, { epoch: lane.epoch, claims: claimsById.get(id) ?? 0 })
503
+ );
504
+ current.add(key);
505
+ return !this.#state.handedOut.has(key);
506
+ })
507
+ }));
508
+ for (const [key, entry] of this.#state.handedOut) {
509
+ if (entry.owner === owner && !current.has(key)) {
510
+ this.#state.handedOut.delete(key);
511
+ }
512
+ }
513
+ if (held.length === 0) {
514
+ return;
515
+ }
516
+ await this.#state.lanes.bulkWrite(
517
+ unclaimed.map(({ lane, ids }) => ({
518
+ updateOne: {
519
+ filter: { _id: lane._id, epoch: lane.epoch, holder: this.#state.instanceId },
520
+ update: { $pull: { inFlight: { $in: ids } }, $inc: { revision: 1 } }
521
+ }
522
+ })),
523
+ { session, ordered: false }
524
+ );
525
+ await this.#state.deliveries.updateMany(
526
+ { _id: { $in: unclaimed.flatMap((entry) => entry.ids) }, status: "pending" },
527
+ { $inc: { claims: 1 } },
528
+ { session }
529
+ );
530
+ });
531
+ }
532
+ async #claimNow(request) {
533
+ const [held] = await Promise.all([
534
+ this.#state.lanes.find({
535
+ owner: request.leaseOwner,
536
+ holder: this.#state.instanceId,
537
+ leaseExpiresAt: { $gt: request.now }
538
+ }).toArray(),
539
+ this.#ordering.unparkNextDeliveries(request.handlers)
540
+ ]);
541
+ await this.#laneLeases.chargeLost(held);
542
+ const scope = scopeOf(held);
543
+ const running = this.#loadRunning(held);
544
+ const scan = new ClaimScan();
545
+ const picked = [];
546
+ await this.#pickAcrossLanes({ request, scope, scan, running, picked });
547
+ const events = await this.#queries.readEnvelopes(picked.map((document) => document.eventId));
548
+ const runningIds = (await running).ids;
549
+ this.#forgetSettled(held, { runningIds, owner: request.leaseOwner });
550
+ const { recorded, handedBack } = await this.#laneLeases.recordClaim(scope, {
551
+ picked,
552
+ runningIds,
553
+ request
554
+ });
555
+ const claimed = await this.#releaseOvertaken(
556
+ picked.filter((document) => recorded.has(document.laneId)),
557
+ scope
502
558
  );
503
- return {
504
- pending,
505
- processing,
506
- completed,
507
- dead,
508
- oldestDueAt: oldestDue?.dueAt ?? null
559
+ await this.#ordering.parkWaiting(scan.waitingBacklogs(PARK_BACKLOG_THRESHOLD, handedBack));
560
+ return claimed.map((document) => ({
561
+ deliveryId: document._id,
562
+ leaseToken: formatLeaseToken(document.laneId, {
563
+ epoch: scope.get(document.laneId).epoch,
564
+ claims: document.claims ?? 0
565
+ }),
566
+ handler: document.handler,
567
+ attempt: document.attempts + 1,
568
+ leaseExpiresAt: request.leaseExpiresAt,
569
+ event: events.get(document.eventId)
570
+ }));
571
+ }
572
+ /** The deliveries still running in the held lanes, with their (handler, key) identities. */
573
+ #loadRunning(held) {
574
+ return this.#queries.findRunning(held.flatMap((lane) => lane.inFlight)).then((documents) => ({
575
+ ids: new Set(documents.map((document) => document._id)),
576
+ keys: new Set(
577
+ documents.flatMap(
578
+ (document) => document.key === void 0 ? [] : [orderingIdentity(document.handler, document.key)]
579
+ )
580
+ )
581
+ }));
582
+ }
583
+ /**
584
+ * Picks from the lanes in `scope`, then takes free lanes with due work, a few more each round
585
+ * (4, 8, 16, ...), and picks from them, until the claim is full or no free lane is left.
586
+ */
587
+ async #pickAcrossLanes(input) {
588
+ const { request, scope, scan, running, picked } = input;
589
+ const pickFrom = async (lanes) => {
590
+ for (let offset = 0; offset < lanes.length; offset += LANES_PER_CANDIDATE_QUERY) {
591
+ if (picked.length < request.limit) {
592
+ await this.#ordering.pickCandidates({
593
+ lanes: lanes.slice(offset, offset + LANES_PER_CANDIDATE_QUERY),
594
+ request,
595
+ scan,
596
+ running,
597
+ picked
598
+ });
599
+ }
600
+ }
509
601
  };
602
+ await pickFrom([...scope.values()]);
603
+ const passed = new Set(scope.keys());
604
+ for (let laneCount = INITIAL_LANES_PER_ROUND; picked.length < request.limit; laneCount *= 2) {
605
+ const free = await this.#laneLeases.findFreeLanes(request, {
606
+ laneCount,
607
+ passed: [...passed]
608
+ });
609
+ if (free.length === 0) {
610
+ break;
611
+ }
612
+ for (const laneId of free) {
613
+ passed.add(laneId);
614
+ }
615
+ const taken = await this.#laneLeases.takeLanes(free, request);
616
+ for (const lane of taken) {
617
+ scope.set(lane.laneId, lane);
618
+ }
619
+ await pickFrom(taken);
620
+ }
510
621
  }
511
- /** Atomically increments the counter of `key`; conflicting appends of the key serialize here. */
512
- async #nextSequence(key, session) {
513
- const counter = await this.#keySequences.findOneAndUpdate(
514
- { _id: key },
515
- { $inc: { value: 1 } },
516
- { upsert: true, returnDocument: "after", session }
622
+ /**
623
+ * Forgets the claims of `owner` that are listed in the held lanes but no longer pending:
624
+ * completed (a burial or retry would have unlisted it). Such a claim is settled, also when it was
625
+ * completed inside a caller's transaction that committed. Only this owner's registrations of the
626
+ * lane epochs it read: the same delivery may meanwhile have been requeued and handed out again,
627
+ * under another owner or lane epoch.
628
+ */
629
+ #forgetSettled(held, { runningIds, owner }) {
630
+ const gone = new Set(
631
+ held.flatMap(
632
+ (lane) => lane.inFlight.filter((id) => !runningIds.has(id)).map((id) => `${id}\0${lane._id}:${lane.epoch}`)
633
+ )
517
634
  );
518
- return counter.value;
635
+ for (const [key, entry] of this.#state.handedOut) {
636
+ if (entry.owner === owner && gone.has(`${entry.deliveryId}\0${entry.laneId}:${entry.epoch}`)) {
637
+ this.#state.handedOut.delete(key);
638
+ }
639
+ }
519
640
  }
520
- async #claimCandidate(candidate, request, scan) {
521
- const { key, sequence } = candidate;
522
- if (key === void 0) {
523
- return this.#lease(candidate, request);
641
+ /**
642
+ * Gives back the recorded keyed picks that a delivery requeued during the
643
+ * claim now precedes, without charging an attempt, and returns the rest. The
644
+ * claim checked their predecessors before recording them; a dead letter
645
+ * requeued in between would otherwise wait behind its own successor. Once a
646
+ * pick is recorded, a later requeue waits for it like for any running delivery.
647
+ */
648
+ async #releaseOvertaken(claimed, scope) {
649
+ const keyed = claimed.filter((document) => document.key !== void 0);
650
+ if (keyed.length === 0) {
651
+ return [...claimed];
524
652
  }
525
- const orderingId = orderingIdentity(candidate.handler, key);
526
- const known = scan.verdict(orderingId, sequence);
527
- if (known === "open-predecessor") {
528
- scan.noteWaiting(orderingId, candidate);
529
- return void 0;
653
+ const blockers = await this.#state.deliveries.find(
654
+ {
655
+ $or: keyed.map((document) => ({
656
+ handler: document.handler,
657
+ key: document.key,
658
+ sequence: { $lt: document.sequence },
659
+ dueAt: { $exists: true }
660
+ }))
661
+ },
662
+ { projection: { handler: 1, key: 1 } }
663
+ ).toArray();
664
+ const blocked = new Set(
665
+ blockers.map((blocker) => orderingIdentity(blocker.handler, blocker.key))
666
+ );
667
+ const overtaken = new Set(
668
+ keyed.filter((document) => blocked.has(orderingIdentity(document.handler, document.key))).map((document) => document._id)
669
+ );
670
+ if (overtaken.size === 0) {
671
+ return [...claimed];
530
672
  }
531
- if (known === "live-lease") {
532
- return void 0;
673
+ await this.#releasePicks(
674
+ claimed.filter((document) => overtaken.has(document._id)),
675
+ scope
676
+ );
677
+ return claimed.filter((document) => !overtaken.has(document._id));
678
+ }
679
+ /** Takes recorded picks out of their lanes' in-flight lists again, under the claim's epochs and record revisions. */
680
+ async #releasePicks(documents, scope) {
681
+ const idsByLane = /* @__PURE__ */ new Map();
682
+ for (const document of documents) {
683
+ idsByLane.set(document.laneId, [...idsByLane.get(document.laneId) ?? [], document._id]);
533
684
  }
534
- const predecessor = await this.#findUnfinishedPredecessor(candidate.handler, key, sequence);
535
- if (predecessor !== void 0) {
536
- scan.noteOpen(orderingId, predecessor);
537
- scan.noteWaiting(orderingId, candidate);
538
- return void 0;
685
+ await Promise.all(
686
+ [...idsByLane].map(
687
+ ([laneId, ids]) => this.#state.lanes.updateOne(
688
+ // Under the revision the record left: a pull that reaches the server late, after a
689
+ // reconciliation and a newer claim of the same delivery, matches nothing.
690
+ {
691
+ _id: laneId,
692
+ epoch: scope.get(laneId).epoch,
693
+ revision: scope.get(laneId).revision + 1
694
+ },
695
+ { $pull: { inFlight: { $in: ids } } }
696
+ )
697
+ )
698
+ );
699
+ }
700
+ };
701
+
702
+ // src/mongo-completion.ts
703
+ var FINISHED_FIELDS = { dueAt: "", lane: "" };
704
+ var MongoCompletion = class {
705
+ #state;
706
+ constructor(state) {
707
+ this.#state = state;
708
+ }
709
+ /** Implements {@link MongoEventStore.extendLease}. */
710
+ async extendLease(lease, leaseExpiresAt) {
711
+ const held = parseLeaseToken(lease.leaseToken);
712
+ if (held === void 0) {
713
+ return false;
539
714
  }
540
- if (await this.#hasLiveLease(candidate.handler, key, request.now)) {
541
- scan.noteLeaseHeld(orderingId);
542
- return void 0;
715
+ const deliveryId = String(lease.deliveryId);
716
+ return runInTransaction(this.#state, async (session) => {
717
+ const running = await this.#state.deliveries.findOne(ofClaim({ ...held, deliveryId }), {
718
+ session,
719
+ projection: { _id: 1 }
720
+ });
721
+ if (running === null) {
722
+ return false;
723
+ }
724
+ const renewed = await this.#state.lanes.updateOne(
725
+ { _id: held.laneId, epoch: held.epoch, inFlight: deliveryId },
726
+ { $max: { leaseExpiresAt } },
727
+ { session }
728
+ );
729
+ return renewed.matchedCount === 1;
730
+ });
731
+ }
732
+ /** Implements {@link MongoEventStore.complete}. */
733
+ async complete(lease, { now, session }) {
734
+ if (session !== void 0) {
735
+ assertInTransaction(session, "complete");
543
736
  }
544
- const leased = await this.#lease(candidate, request);
545
- if (leased === void 0) {
546
- return void 0;
737
+ return (await this.#completeLeases([lease], { now, session }))[0];
738
+ }
739
+ /** Implements {@link MongoEventStore.completeMany}. */
740
+ completeMany(leases, now) {
741
+ return this.#completeLeases(leases, { now, session: void 0 });
742
+ }
743
+ /** Implements {@link MongoEventStore.reschedule}. */
744
+ async reschedule(lease, {
745
+ availableAt,
746
+ error,
747
+ now
748
+ }) {
749
+ return this.#leaveFlight(lease, {
750
+ $set: { availableAt, dueAt: availableAt, lastError: toErrorInfo(error), updatedAt: now },
751
+ $inc: { attempts: 1, claims: 1 }
752
+ });
753
+ }
754
+ /** Implements {@link MongoEventStore.release}. */
755
+ async release(lease, now) {
756
+ return this.#leaveFlight(lease, {
757
+ $set: { availableAt: now, dueAt: now, updatedAt: now },
758
+ $inc: { claims: 1 }
759
+ });
760
+ }
761
+ /** Implements {@link MongoEventStore.bury}. */
762
+ async bury(lease, { error, now }) {
763
+ return this.#leaveFlight(lease, {
764
+ $set: { status: "dead", lastError: toErrorInfo(error), updatedAt: now },
765
+ $unset: FINISHED_FIELDS,
766
+ $inc: { attempts: 1, claims: 1 }
767
+ });
768
+ }
769
+ /**
770
+ * Runs `operation`, which ends the claims of `leases` (completion, retry,
771
+ * release, burial), and once it returned forgets exactly those leases as
772
+ * handed out. When it throws, they stay registered: the caller may retry
773
+ * with the same lease, which must still find its claim.
774
+ */
775
+ async #settle(leases, operation) {
776
+ const result = await operation();
777
+ for (const lease of leases) {
778
+ this.#state.handedOut.delete(leaseKey(String(lease.deliveryId), String(lease.leaseToken)));
547
779
  }
548
- const lateBlocker = await this.#findUnfinishedPredecessor(candidate.handler, key, sequence);
549
- if (lateBlocker !== void 0) {
550
- await this.#restore(candidate, leased);
551
- scan.noteOpen(orderingId, lateBlocker);
552
- return void 0;
780
+ return result;
781
+ }
782
+ /**
783
+ * Deletes the delivery of every lease whose lane still has the lease's epoch
784
+ * and lists the delivery, in one transaction (the caller's, when given).
785
+ * Returns one flag per lease, in order; a lease listed twice completes once.
786
+ */
787
+ async #completeLeases(leases, { now, session }) {
788
+ return session === void 0 ? this.#settle(leases, () => this.#completeIssued(leases, { now, session: void 0 })) : this.#completeIssued(leases, { now, session });
789
+ }
790
+ async #completeIssued(leases, { now, session }) {
791
+ const parsed = leases.map((lease) => parseLeaseToken(lease.leaseToken));
792
+ const issued = leases.flatMap(
793
+ (lease, index) => parsed[index] === void 0 ? [] : [{ deliveryId: String(lease.deliveryId), ...parsed[index] }]
794
+ );
795
+ let completed = /* @__PURE__ */ new Set();
796
+ if (issued.length > 0) {
797
+ if (session !== void 0) {
798
+ completed = await this.#deleteCompleted(issued, { now, session });
799
+ } else if (this.#state.completionHistory) {
800
+ completed = await runInTransaction(
801
+ this.#state,
802
+ (own) => this.#deleteCompleted(issued, { now, session: own })
803
+ );
804
+ } else {
805
+ completed = await this.#deleteFenced(issued, now);
806
+ }
553
807
  }
554
- scan.noteClaimed(orderingId, sequence);
555
- return leased;
808
+ return leases.map(
809
+ (lease, index) => parsed[index] !== void 0 && completed.delete(leaseIdentity({ deliveryId: String(lease.deliveryId), ...parsed[index] }))
810
+ );
811
+ }
812
+ /**
813
+ * Completion without a transaction, used when no history record has to be
814
+ * written with the deletion. The deliveries' claim generations are read
815
+ * first, then the lanes, and a delivery is deleted only if it still has the
816
+ * lease's generation. A takeover moves the generation of every delivery it
817
+ * takes from the previous owner on before it reads anything, and so do a
818
+ * retry, a release and a burial, so:
819
+ * - a takeover before the delivery read shows up in the lane read (new epoch);
820
+ * - a takeover between the two reads shows up in the lane read as well;
821
+ * - a takeover, retry, release or burial after the lane read changed the
822
+ * generation, so the delete matches nothing.
823
+ * A completion and a takeover (or the end of the claim) therefore never both succeed. Two concurrent
824
+ * completions of the same lease may both report true (the dispatcher never
825
+ * issues them); one call with a lease listed twice reports it once.
826
+ */
827
+ async #deleteFenced(issued, now) {
828
+ const ids = [...new Set(issued.map((lease) => lease.deliveryId))];
829
+ const documents = await this.#state.deliveries.find({ _id: { $in: ids }, status: "pending" }, { projection: { claims: 1, eventId: 1 } }).toArray();
830
+ const lanes = new Map(
831
+ (await this.#state.lanes.find(
832
+ { _id: { $in: [...new Set(issued.map((lease) => lease.laneId))] } },
833
+ { projection: { epoch: 1, inFlight: 1 } }
834
+ ).toArray()).map((lane) => [lane._id, lane])
835
+ );
836
+ const fenced = fencedLeases(issued, { lanes, documents });
837
+ if (fenced.length === 0) {
838
+ return /* @__PURE__ */ new Set();
839
+ }
840
+ await this.#markEventsCompleted(fenced, { documents, now });
841
+ const deleted = await this.#state.deliveries.deleteMany({ $or: fenced.map(ofClaim) });
842
+ return deleted.deletedCount === fenced.length ? new Set(fenced.map((lease) => leaseIdentity(lease))) : /* @__PURE__ */ new Set();
843
+ }
844
+ /**
845
+ * The transactional part of a completion. The lanes are only read: the
846
+ * conflict with a takeover comes from the deleted delivery documents, which a
847
+ * takeover writes before it reads them (see `MongoLaneLeases.takeLanes`).
848
+ * So whichever of the two commits second either fails with a write conflict
849
+ * and is retried against the new state, or waits for the first.
850
+ */
851
+ async #deleteCompleted(issued, { now, session }) {
852
+ const lanes = new Map(
853
+ (await this.#state.lanes.find(
854
+ { _id: { $in: [...new Set(issued.map((lease) => lease.laneId))] } },
855
+ { session, projection: { epoch: 1, inFlight: 1 } }
856
+ ).toArray()).map((lane) => [lane._id, lane])
857
+ );
858
+ const documents = await this.#state.deliveries.find(
859
+ { _id: { $in: [...new Set(issued.map((lease) => lease.deliveryId))] }, status: "pending" },
860
+ { session }
861
+ ).toArray();
862
+ const fenced = fencedLeases(issued, { lanes, documents });
863
+ if (fenced.length === 0) {
864
+ return /* @__PURE__ */ new Set();
865
+ }
866
+ await this.#markEventsCompleted(fenced, { documents, now, session });
867
+ await this.#state.deliveries.deleteMany({ $or: fenced.map(ofClaim) }, { session });
868
+ if (this.#state.completionHistory) {
869
+ const completedIds = new Set(fenced.map((lease) => lease.deliveryId));
870
+ await this.#state.completions.insertMany(
871
+ documents.filter((document) => completedIds.has(document._id)).map((document) => toCompletedDeliveryDocument(document, now)),
872
+ { session }
873
+ );
874
+ }
875
+ return new Set(fenced.map((lease) => leaseIdentity(lease)));
876
+ }
877
+ /**
878
+ * Records `now` as the latest completion of the events of the fenced
879
+ * deliveries (`$max`, so an earlier clock never moves it back). Written
880
+ * before the deletion, it can only be later than the real last completion
881
+ * (when the deletion then fails), which keeps the event longer, never shorter.
882
+ * Inside a transaction it is part of it: the transaction may hold the event
883
+ * already (a transactional handler that appended to its own event), and a
884
+ * write from outside would wait for it forever. Deliveries of one event that
885
+ * complete in concurrent transactions (fan-out to transactional handlers)
886
+ * therefore conflict on the event document, and one of them retries.
887
+ */
888
+ async #markEventsCompleted(fenced, {
889
+ documents,
890
+ now,
891
+ session
892
+ }) {
893
+ const completedIds = new Set(fenced.map((lease) => lease.deliveryId));
894
+ const eventIds = [
895
+ ...new Set(
896
+ documents.filter((document) => completedIds.has(document._id)).map((document) => document.eventId)
897
+ )
898
+ ];
899
+ await this.#state.events.updateMany(
900
+ { _id: { $in: eventIds } },
901
+ { $max: { completedAt: now } },
902
+ session === void 0 ? {} : { session }
903
+ );
556
904
  }
557
905
  /**
558
- * Takes the delivery with one conditional update that pins the exact state
559
- * that was selected, so a competing claimer, a finished lease, a reschedule
560
- * or a parking since then makes it match nothing.
906
+ * Applies `update` to a running delivery and takes it out of its lane's
907
+ * in-flight list, if the lane still has the lease's epoch. One transaction:
908
+ * the lane write fences the change against a takeover.
561
909
  */
562
- async #lease(candidate, request) {
563
- const leased = await this.#deliveries.findOneAndUpdate(
910
+ async #leaveFlight(lease, update) {
911
+ const held = parseLeaseToken(lease.leaseToken);
912
+ if (held === void 0) {
913
+ return false;
914
+ }
915
+ const deliveryId = String(lease.deliveryId);
916
+ const ofThisClaim = ofClaim({ ...held, deliveryId });
917
+ return this.#settle(
918
+ [lease],
919
+ () => this.#leaveFlightNow(held, { deliveryId, ofThisClaim, update })
920
+ );
921
+ }
922
+ async #leaveFlightNow(held, {
923
+ deliveryId,
924
+ ofThisClaim,
925
+ update
926
+ }) {
927
+ return runInTransaction(this.#state, async (session) => {
928
+ if (await this.#state.deliveries.findOne(ofThisClaim, { session, projection: { _id: 1 } }) === null) {
929
+ return false;
930
+ }
931
+ const fence = await this.#state.lanes.updateOne(
932
+ { _id: held.laneId, epoch: held.epoch, inFlight: deliveryId },
933
+ { $pull: { inFlight: deliveryId } },
934
+ { session }
935
+ );
936
+ if (fence.matchedCount === 0) {
937
+ return false;
938
+ }
939
+ const changed = await this.#state.deliveries.updateOne(ofThisClaim, update, { session });
940
+ return changed.matchedCount === 1;
941
+ });
942
+ }
943
+ };
944
+ function fencedLeases(issued, {
945
+ lanes,
946
+ documents
947
+ }) {
948
+ const claimsById = new Map(documents.map((document) => [document._id, document.claims ?? 0]));
949
+ const fenced = /* @__PURE__ */ new Map();
950
+ for (const lease of issued) {
951
+ const lane = lanes.get(lease.laneId);
952
+ if (claimsById.get(lease.deliveryId) === lease.claims && lane.epoch === lease.epoch && lane.inFlight.includes(lease.deliveryId)) {
953
+ fenced.set(leaseIdentity(lease), lease);
954
+ }
955
+ }
956
+ return [...fenced.values()];
957
+ }
958
+ function ofClaim(lease) {
959
+ return { _id: lease.deliveryId, status: "pending", claims: atCount(lease.claims) };
960
+ }
961
+ function leaseIdentity(lease) {
962
+ return `${lease.deliveryId}\0${formatLeaseToken(lease.laneId, { epoch: lease.epoch, claims: lease.claims })}`;
963
+ }
964
+
965
+ // src/mongo-lane-leases.ts
966
+ var MongoLaneLeases = class {
967
+ #state;
968
+ #queries;
969
+ constructor(state, collaborators) {
970
+ this.#state = state;
971
+ this.#queries = collaborators.queries;
972
+ }
973
+ /**
974
+ * Up to `laneCount` lanes nobody holds under a live lease that have a due,
975
+ * ready delivery of the requested handlers, the lane with the oldest such
976
+ * delivery first, leaving out `passed`. One round trip: the oldest delivery
977
+ * of each lane is one index probe on the server. A lane whose due deliveries
978
+ * all wait behind an unfinished predecessor is taken at most once: the claim
979
+ * that hands it back parks them (see `ClaimScan.waitingBacklogs`).
980
+ */
981
+ async findFreeLanes(request, { laneCount, passed }) {
982
+ const lanes = await this.#state.lanes.aggregate([
564
983
  {
565
- _id: candidate._id,
566
- status: candidate.status,
567
- lane: "ready",
568
- attempts: candidate.attempts,
569
- dueAt: candidate.dueAt
984
+ $match: {
985
+ _id: { $nin: passed },
986
+ $or: [{ leaseExpiresAt: null }, { leaseExpiresAt: { $lte: request.now } }]
987
+ }
570
988
  },
571
989
  {
572
- $set: {
573
- status: "processing",
574
- leaseOwner: request.leaseOwner,
575
- leaseToken: this.#generateIdentifier(),
576
- leaseExpiresAt: request.leaseExpiresAt,
577
- dueAt: request.leaseExpiresAt,
578
- updatedAt: request.now
579
- },
580
- $inc: { attempts: 1 }
990
+ $lookup: {
991
+ from: this.#state.deliveries.collectionName,
992
+ localField: "_id",
993
+ foreignField: "laneId",
994
+ pipeline: [
995
+ {
996
+ $match: {
997
+ handler: { $in: [...request.handlers] },
998
+ lane: "ready",
999
+ dueAt: { $lte: request.now }
1000
+ }
1001
+ },
1002
+ { $sort: { dueAt: 1, _id: 1 } },
1003
+ { $limit: 1 },
1004
+ { $project: { dueAt: 1 } }
1005
+ ],
1006
+ as: "oldest"
1007
+ }
581
1008
  },
582
- { returnDocument: "after" }
1009
+ { $unwind: "$oldest" },
1010
+ { $sort: { "oldest.dueAt": 1, "oldest._id": 1 } },
1011
+ { $limit: laneCount },
1012
+ { $project: { _id: 1 } }
1013
+ ]).toArray();
1014
+ return lanes.map((lane) => lane._id);
1015
+ }
1016
+ /**
1017
+ * Takes the lanes with one conditional write each, run in parallel; a lane
1018
+ * taken by someone else meanwhile is skipped. The same write moves the
1019
+ * previous owner's in-flight list to `lost`, which is charged before any
1020
+ * delivery of the lanes is read (see {@link MongoLaneLeases.chargeLost}).
1021
+ */
1022
+ async takeLanes(laneIds, request) {
1023
+ const after = await Promise.all(
1024
+ laneIds.map(
1025
+ (laneId) => this.#state.lanes.findOneAndUpdate(
1026
+ {
1027
+ _id: laneId,
1028
+ $or: [{ leaseExpiresAt: null }, { leaseExpiresAt: { $lte: request.now } }]
1029
+ },
1030
+ [
1031
+ {
1032
+ $set: {
1033
+ epoch: { $add: ["$epoch", 1] },
1034
+ owner: { $literal: request.leaseOwner },
1035
+ holder: { $literal: this.#state.instanceId },
1036
+ leaseExpiresAt: { $literal: request.leaseExpiresAt },
1037
+ // Each lost delivery keeps the epoch it was claimed under: the key of its charge.
1038
+ lost: {
1039
+ $setUnion: [
1040
+ { $ifNull: ["$lost", []] },
1041
+ { $map: { input: "$inFlight", in: { id: "$$this", epoch: "$epoch" } } }
1042
+ ]
1043
+ },
1044
+ inFlight: { $literal: [] }
1045
+ }
1046
+ }
1047
+ ],
1048
+ { returnDocument: "after" }
1049
+ )
1050
+ )
583
1051
  );
584
- return leased ?? void 0;
1052
+ const taken = after.filter((lane) => lane !== null);
1053
+ await this.chargeLost(taken);
1054
+ return taken.map((lane) => ({
1055
+ laneId: lane._id,
1056
+ epoch: lane.epoch,
1057
+ listed: lane.inFlight,
1058
+ revision: lane.revision ?? 0
1059
+ }));
585
1060
  }
586
- /** Puts a delivery that was leased a moment ago back exactly as it was selected. */
587
- async #restore(selected, leased) {
588
- const state = {
589
- status: selected.status,
590
- attempts: selected.attempts,
591
- dueAt: selected.dueAt,
592
- updatedAt: selected.updatedAt
1061
+ /**
1062
+ * Charges one attempt to every pending delivery listed in the `lost` lists of
1063
+ * `lanes` (deliveries whose lane was taken while they ran), then clears those
1064
+ * lists under the lanes' current epochs. The charge is a write on each lost
1065
+ * delivery that comes before any read of the lane's deliveries: a completion
1066
+ * of the previous owner deletes the same documents, so the two conflict and
1067
+ * cannot both succeed. The charge also moves the claim generation on, which
1068
+ * fences every lease of the lost claim, and records the lost claim
1069
+ * (`lostAt` = lane and epoch it was claimed under): a holder that charges the
1070
+ * list again after a failure before the clear skips deliveries already
1071
+ * charged for that claim.
1072
+ */
1073
+ async chargeLost(lanes) {
1074
+ const losing = lanes.filter((lane) => lane.lost.length > 0);
1075
+ if (losing.length === 0) {
1076
+ return;
1077
+ }
1078
+ const lost = losing.flatMap((lane) => lane.lost).sort((left, right) => left.epoch - right.epoch);
1079
+ await this.#state.deliveries.bulkWrite(
1080
+ lost.map(({ id, epoch }) => ({
1081
+ updateOne: {
1082
+ filter: { _id: id, status: "pending", lostAt: { $not: { $gte: epoch } } },
1083
+ update: { $inc: { attempts: 1, claims: 1 }, $set: { lostAt: epoch } }
1084
+ }
1085
+ })),
1086
+ { ordered: true }
1087
+ );
1088
+ await this.#state.lanes.bulkWrite(
1089
+ losing.map((lane) => ({
1090
+ updateOne: { filter: { _id: lane._id, epoch: lane.epoch }, update: { $set: { lost: [] } } }
1091
+ })),
1092
+ { ordered: false }
1093
+ );
1094
+ }
1095
+ /**
1096
+ * Records the picks in their lanes, one conditional write per lane and one
1097
+ * round trip for all of them, and frees the lanes that yielded nothing and run
1098
+ * nothing. A picked lane lists its running deliveries plus the new ones (ids
1099
+ * whose documents are gone are pruned) and its lease reaches
1100
+ * `request.leaseExpiresAt`. Returns the lanes whose picks were recorded: every
1101
+ * write is conditional on the claim's epoch, owner and store instance, so a
1102
+ * lane that changed hands, or was handed back by `relinquish`, in the meantime
1103
+ * keeps its deliveries for whoever takes it next.
1104
+ */
1105
+ async recordClaim(scope, {
1106
+ picked,
1107
+ runningIds,
1108
+ request
1109
+ }) {
1110
+ const picksByLane = /* @__PURE__ */ new Map();
1111
+ const handedBack = /* @__PURE__ */ new Set();
1112
+ for (const document of picked) {
1113
+ picksByLane.set(document.laneId, [...picksByLane.get(document.laneId) ?? [], document._id]);
1114
+ }
1115
+ const operations = [];
1116
+ for (const lane of scope.values()) {
1117
+ const gone = lane.listed.filter((id) => !runningIds.has(id));
1118
+ const ids = picksByLane.get(lane.laneId);
1119
+ if (ids !== void 0) {
1120
+ operations.push(
1121
+ recordInFlight({ lane, ids, gone, request, instanceId: this.#state.instanceId })
1122
+ );
1123
+ } else if (gone.length === lane.listed.length) {
1124
+ operations.push(
1125
+ freeLane(lane.laneId, { epoch: lane.epoch, revision: lane.revision, finished: gone })
1126
+ );
1127
+ handedBack.add(lane.laneId);
1128
+ }
1129
+ }
1130
+ if (operations.length === 0) {
1131
+ return { recorded: /* @__PURE__ */ new Set(), handedBack };
1132
+ }
1133
+ const result = await this.#state.lanes.bulkWrite(operations, { ordered: false });
1134
+ if (result.matchedCount === operations.length) {
1135
+ return { recorded: new Set(picksByLane.keys()), handedBack };
1136
+ }
1137
+ return {
1138
+ recorded: await this.#readRecorded(scope, { laneIds: [...picksByLane.keys()], request }),
1139
+ handedBack
593
1140
  };
594
- await this.#deliveries.updateOne(
595
- { _id: leased._id, status: "processing", leaseToken: leased.leaseToken },
596
- selected.status === "processing" ? {
597
- $set: {
598
- ...state,
599
- leaseOwner: selected.leaseOwner,
600
- leaseToken: selected.leaseToken,
601
- leaseExpiresAt: selected.leaseExpiresAt
1141
+ }
1142
+ /** The lanes of `laneIds` whose record of this claim applied, read back after a partial bulk write. */
1143
+ async #readRecorded(scope, { laneIds, request }) {
1144
+ const current = await this.#state.lanes.find(
1145
+ { _id: { $in: [...laneIds] } },
1146
+ { projection: { epoch: 1, owner: 1, holder: 1, revision: 1 } }
1147
+ ).toArray();
1148
+ return new Set(
1149
+ current.filter(
1150
+ (lane) => lane.epoch === scope.get(lane._id).epoch && lane.revision === scope.get(lane._id).revision + 1 && lane.owner === request.leaseOwner && lane.holder === this.#state.instanceId
1151
+ ).map((lane) => lane._id)
1152
+ );
1153
+ }
1154
+ /** Implements {@link MongoEventStore.relinquish}. */
1155
+ async relinquish(leaseOwner) {
1156
+ const held = await this.#state.lanes.find({ owner: String(leaseOwner), holder: this.#state.instanceId }).toArray();
1157
+ const runningIds = new Set(
1158
+ (await this.#queries.findRunning(held.flatMap((lane) => lane.inFlight))).map(
1159
+ (document) => document._id
1160
+ )
1161
+ );
1162
+ const idle = held.filter((lane) => lane.inFlight.every((id) => !runningIds.has(id)));
1163
+ if (idle.length > 0) {
1164
+ await this.#state.lanes.bulkWrite(
1165
+ idle.map(
1166
+ (lane) => freeLane(lane._id, {
1167
+ epoch: lane.epoch,
1168
+ revision: lane.revision ?? 0,
1169
+ finished: lane.inFlight
1170
+ })
1171
+ ),
1172
+ { ordered: false }
1173
+ );
1174
+ }
1175
+ }
1176
+ };
1177
+ function recordInFlight(input) {
1178
+ const { lane, ids, gone, request, instanceId } = input;
1179
+ return {
1180
+ updateOne: {
1181
+ filter: {
1182
+ _id: lane.laneId,
1183
+ epoch: lane.epoch,
1184
+ owner: request.leaseOwner,
1185
+ holder: instanceId,
1186
+ // A record that reaches the server late (after its claim failed and reconciled)
1187
+ // finds a newer revision and changes nothing.
1188
+ revision: atCount(lane.revision)
1189
+ },
1190
+ update: [
1191
+ {
1192
+ $set: {
1193
+ inFlight: {
1194
+ $concatArrays: [
1195
+ {
1196
+ $filter: {
1197
+ input: "$inFlight",
1198
+ cond: { $not: [{ $in: ["$$this", { $literal: gone }] }] }
1199
+ }
1200
+ },
1201
+ { $literal: ids }
1202
+ ]
1203
+ },
1204
+ leaseExpiresAt: { $max: ["$leaseExpiresAt", request.leaseExpiresAt] },
1205
+ revision: { $add: [{ $ifNull: ["$revision", 0] }, 1] }
1206
+ }
1207
+ }
1208
+ ]
1209
+ }
1210
+ };
1211
+ }
1212
+ function freeLane(laneId, {
1213
+ epoch,
1214
+ revision,
1215
+ finished
1216
+ }) {
1217
+ return {
1218
+ updateOne: {
1219
+ filter: {
1220
+ _id: laneId,
1221
+ epoch,
1222
+ revision: atCount(revision),
1223
+ inFlight: { $not: { $elemMatch: { $nin: [...finished] } } }
1224
+ },
1225
+ update: {
1226
+ $set: { owner: null, holder: null, leaseExpiresAt: null, inFlight: [] },
1227
+ $inc: { revision: 1 }
1228
+ }
1229
+ }
1230
+ };
1231
+ }
1232
+
1233
+ // src/mongo-ordering.ts
1234
+ var MINIMUM_CANDIDATE_BATCH_SIZE = 32;
1235
+ var PARK_UPDATE_CHUNK_SIZE = 1e3;
1236
+ var MongoOrdering = class {
1237
+ #state;
1238
+ constructor(state) {
1239
+ this.#state = state;
1240
+ }
1241
+ /**
1242
+ * Adds the claimable candidates of `lanes` to `picked`, in due order, until
1243
+ * `request.limit` is reached. A delivery is a candidate when it is ready, due
1244
+ * and not in flight in its lane. A keyed candidate is claimable only when
1245
+ * (a) no earlier delivery of its handler and key is pending (a running one is
1246
+ * still a pending document) and (b) no other delivery of them runs. Running
1247
+ * deliveries of a key live in the key's lane, which this owner holds, so the
1248
+ * running keys (loaded once from the held lanes) and this claim's own picks
1249
+ * are all of them.
1250
+ *
1251
+ * Candidates are read in pages with a limit, so no cursor is left open, and
1252
+ * the predecessors of the keys of a page are looked up in parallel, one
1253
+ * lookup per key.
1254
+ */
1255
+ async pickCandidates(input) {
1256
+ const { lanes, request, scan, running, picked } = input;
1257
+ const pageSize = Math.max((request.limit - picked.length) * 2, MINIMUM_CANDIDATE_BATCH_SIZE);
1258
+ const filter = {
1259
+ laneId: { $in: lanes.map((lane) => lane.laneId) },
1260
+ handler: { $in: [...request.handlers] },
1261
+ lane: "ready",
1262
+ dueAt: { $lte: request.now },
1263
+ _id: { $nin: lanes.flatMap((lane) => lane.listed) }
1264
+ };
1265
+ let after;
1266
+ for (; ; ) {
1267
+ const [page, { keys }] = await Promise.all([
1268
+ this.#state.deliveries.find(
1269
+ after === void 0 ? filter : {
1270
+ $and: [
1271
+ filter,
1272
+ {
1273
+ $or: [
1274
+ { dueAt: { $gt: after.dueAt } },
1275
+ { dueAt: after.dueAt, _id: { $gt: after._id } }
1276
+ ]
1277
+ }
1278
+ ]
1279
+ },
1280
+ { sort: { dueAt: 1, _id: 1 }, limit: pageSize }
1281
+ ).toArray(),
1282
+ running
1283
+ ]);
1284
+ if (await this.#pickFromPage(page, { request, scan, picked, keys })) {
1285
+ return;
1286
+ }
1287
+ if (page.length < pageSize) {
1288
+ return;
1289
+ }
1290
+ after = page.at(-1);
1291
+ }
1292
+ }
1293
+ /**
1294
+ * Adds the claimable candidates of `page` to `picked`. Looks up predecessors only for as many
1295
+ * candidates as the claim still needs, then more. True once the claim has `request.limit` picks.
1296
+ */
1297
+ async #pickFromPage(page, claim) {
1298
+ const { request, scan, picked, keys } = claim;
1299
+ for (let offset = 0; offset < page.length; ) {
1300
+ const slice = page.slice(offset, offset + request.limit - picked.length);
1301
+ offset += slice.length;
1302
+ await this.#notePredecessors(slice, scan);
1303
+ for (const candidate of slice) {
1304
+ if (isClaimable(candidate, { scan, blockedKeys: keys })) {
1305
+ picked.push(candidate);
1306
+ }
1307
+ }
1308
+ if (picked.length >= request.limit) {
1309
+ return true;
1310
+ }
1311
+ }
1312
+ return false;
1313
+ }
1314
+ /**
1315
+ * Looks up, in parallel and once per key, whether an unfinished delivery
1316
+ * precedes the earliest candidate of each keyed (handler, key) of `page` that
1317
+ * this claim knows nothing about yet, and tells `scan`. The earliest candidate
1318
+ * is itself unfinished, so every later candidate of its key waits at least for it.
1319
+ */
1320
+ async #notePredecessors(page, scan) {
1321
+ const earliest = /* @__PURE__ */ new Map();
1322
+ for (const candidate of page) {
1323
+ if (candidate.key !== void 0) {
1324
+ const orderingId = orderingIdentity(candidate.handler, candidate.key);
1325
+ const known = earliest.get(orderingId);
1326
+ if (!scan.knows(orderingId) && (known?.sequence ?? Infinity) > candidate.sequence) {
1327
+ earliest.set(orderingId, candidate);
602
1328
  }
603
- } : { $set: state, $unset: LEASE_FIELDS }
1329
+ }
1330
+ }
1331
+ await Promise.all(
1332
+ [...earliest].map(async ([orderingId, candidate]) => {
1333
+ const predecessor = await this.#findUnfinishedPredecessor(candidate.handler, {
1334
+ key: candidate.key,
1335
+ sequence: candidate.sequence
1336
+ });
1337
+ scan.noteOpen(orderingId, predecessor ?? candidate.sequence);
1338
+ })
604
1339
  );
605
1340
  }
1341
+ /**
1342
+ * Parks the waiting backlogs a claim found. Best effort: parking only saves
1343
+ * later claims work, so a failure is logged and the claim still returns its
1344
+ * batch; the next claim that meets the backlog parks it.
1345
+ */
1346
+ async parkWaiting(deliveryIds) {
1347
+ try {
1348
+ await this.#parkDeliveries(deliveryIds);
1349
+ } catch (error) {
1350
+ this.#state.logger.warn(
1351
+ `[MongoOrdering](parkWaiting) Parking waiting deliveries failed, a later claim parks them | count=${deliveryIds.length} | error=${String(error)}`
1352
+ );
1353
+ }
1354
+ }
606
1355
  /** Sequence of the lowest unfinished delivery of the handler and key before `sequence`, if any. */
607
- async #findUnfinishedPredecessor(handler, key, sequence) {
608
- const predecessor = await this.#deliveries.findOne(
1356
+ async #findUnfinishedPredecessor(handler, { key, sequence }) {
1357
+ const predecessor = await this.#state.deliveries.findOne(
609
1358
  { handler, key, sequence: { $lt: sequence }, dueAt: { $exists: true } },
610
1359
  { sort: { sequence: 1 }, projection: { sequence: 1 } }
611
1360
  );
612
1361
  return predecessor?.sequence;
613
1362
  }
614
- /** Whether some delivery of the handler and key runs under a lease that has not expired. */
615
- async #hasLiveLease(handler, key, now) {
616
- const running = await this.#deliveries.findOne(
617
- { handler, key, status: "processing", dueAt: { $gt: now } },
618
- { projection: { _id: 1 } }
619
- );
620
- return running !== null;
621
- }
622
1363
  /**
623
1364
  * Parks pending deliveries that waited behind an unfinished predecessor, which
624
1365
  * removes them from the claim index until their turn. Parking is a hint, not a
@@ -627,7 +1368,7 @@ var MongoEventStore = class {
627
1368
  */
628
1369
  async #parkDeliveries(deliveryIds) {
629
1370
  for (let offset = 0; offset < deliveryIds.length; offset += PARK_UPDATE_CHUNK_SIZE) {
630
- await this.#deliveries.updateMany(
1371
+ await this.#state.deliveries.updateMany(
631
1372
  {
632
1373
  _id: { $in: deliveryIds.slice(offset, offset + PARK_UPDATE_CHUNK_SIZE) },
633
1374
  status: "pending",
@@ -644,8 +1385,8 @@ var MongoEventStore = class {
644
1385
  * predecessor finishing while its followers were being parked, can delay a key
645
1386
  * until the next claim but never strand it.
646
1387
  */
647
- async #unparkNextDeliveries(handlers) {
648
- const anyParked = await this.#deliveries.findOne(
1388
+ async unparkNextDeliveries(handlers) {
1389
+ const anyParked = await this.#state.deliveries.findOne(
649
1390
  { handler: { $in: [...handlers] }, lane: "parked" },
650
1391
  // The sort lets the planner pick the small partial index over the handler's whole history.
651
1392
  { sort: { handler: 1, key: 1, sequence: 1 }, projection: { _id: 1 } }
@@ -653,103 +1394,809 @@ var MongoEventStore = class {
653
1394
  if (anyParked === null) {
654
1395
  return;
655
1396
  }
656
- for (const handler of new Set(handlers)) {
657
- let afterKey;
658
- for (; ; ) {
659
- const lowest = await this.#deliveries.findOne(
1397
+ const lowest = (await Promise.all(
1398
+ [...new Set(handlers)].map(
1399
+ (handler) => this.#state.deliveries.aggregate([
1400
+ { $match: { handler, lane: "parked" } },
1401
+ { $sort: { handler: 1, key: 1, sequence: 1 } },
660
1402
  {
661
- handler,
662
- lane: "parked",
663
- ...afterKey === void 0 ? {} : { key: { $gt: afterKey } }
664
- },
665
- { sort: { key: 1, sequence: 1 }, projection: { key: 1, sequence: 1 } }
666
- );
667
- if (lowest === null) {
668
- break;
669
- }
670
- afterKey = lowest.key;
671
- if (await this.#findUnfinishedPredecessor(handler, afterKey, lowest.sequence) === void 0) {
672
- await this.#deliveries.updateOne(
673
- { _id: lowest._id, lane: "parked" },
674
- { $set: { lane: "ready" } }
675
- );
676
- }
677
- }
1403
+ $group: { _id: "$key", id: { $first: "$_id" }, sequence: { $first: "$sequence" } }
1404
+ }
1405
+ ]).toArray().then((groups) => groups.map((group) => ({ ...group, handler })))
1406
+ )
1407
+ )).flat();
1408
+ const next = await Promise.all(
1409
+ lowest.map(
1410
+ async (parked) => await this.#findUnfinishedPredecessor(parked.handler, {
1411
+ key: parked._id,
1412
+ sequence: parked.sequence
1413
+ }) === void 0 ? [parked.id] : []
1414
+ )
1415
+ );
1416
+ const ready = next.flat();
1417
+ if (ready.length > 0) {
1418
+ await this.#state.deliveries.updateMany(
1419
+ { _id: { $in: ready }, lane: "parked" },
1420
+ { $set: { lane: "ready" } }
1421
+ );
678
1422
  }
679
1423
  }
680
- async #toClaimedDeliveries(leased, leaseExpiresAt) {
681
- const events = await this.#readEnvelopes(leased.map((document) => document.eventId));
682
- return leased.map((document) => ({
683
- deliveryId: document._id,
684
- leaseToken: document.leaseToken,
685
- handler: document.handler,
686
- attempt: document.attempts,
687
- leaseExpiresAt,
688
- event: events.get(document.eventId)
689
- }));
1424
+ };
1425
+ function isClaimable(candidate, { scan, blockedKeys }) {
1426
+ const { key, sequence } = candidate;
1427
+ if (key === void 0) {
1428
+ return true;
690
1429
  }
691
- async #readEnvelopes(eventIds) {
692
- const documents = await this.#events.find({ _id: { $in: [...new Set(eventIds)] } }).toArray();
693
- return new Map(documents.map((document) => [document._id, toEnvelope(document)]));
1430
+ const orderingId = orderingIdentity(candidate.handler, key);
1431
+ if (scan.waits(orderingId, sequence)) {
1432
+ scan.noteWaiting(orderingId, { deliveryId: candidate._id, laneId: candidate.laneId });
1433
+ return false;
694
1434
  }
695
- async #updateLeased(lease, session, update) {
696
- const result = await this.#deliveries.updateOne(
697
- { _id: lease.deliveryId, status: "processing", leaseToken: lease.leaseToken },
698
- update,
699
- session === void 0 ? {} : { session }
700
- );
701
- return result.matchedCount === 1;
1435
+ if (blockedKeys.has(orderingId)) {
1436
+ return false;
1437
+ }
1438
+ blockedKeys.add(orderingId);
1439
+ return true;
1440
+ }
1441
+
1442
+ // src/mongo-purge.ts
1443
+ var MongoPurge = class {
1444
+ #state;
1445
+ constructor(state) {
1446
+ this.#state = state;
1447
+ }
1448
+ /** Implements {@link MongoEventStore.purge}. */
1449
+ async purge(request) {
1450
+ const total = { deletedDeliveries: 0, deletedEvents: 0 };
1451
+ const steps = [];
1452
+ const { completedBefore, deadBefore } = request;
1453
+ if (completedBefore !== void 0) {
1454
+ steps.push(
1455
+ () => this.#purgeMatching(this.#purgeable(this.#state.deliveries.collectionName), {
1456
+ filter: { status: "completed", completedAt: { $lt: completedBefore } },
1457
+ completedBefore
1458
+ })
1459
+ );
1460
+ if (this.#state.completionHistory) {
1461
+ steps.push(
1462
+ () => this.#purgeMatching(this.#purgeable(this.#state.completions.collectionName), {
1463
+ filter: { completedAt: { $lt: completedBefore } },
1464
+ completedBefore
1465
+ })
1466
+ );
1467
+ }
1468
+ }
1469
+ if (deadBefore !== void 0) {
1470
+ steps.push(
1471
+ () => this.#purgeMatching(this.#purgeable(this.#state.deliveries.collectionName), {
1472
+ filter: { status: "dead", updatedAt: { $lt: deadBefore } },
1473
+ completedBefore
1474
+ })
1475
+ );
1476
+ }
1477
+ for (const step of steps) {
1478
+ const result = await step();
1479
+ total.deletedDeliveries += result.deletedDeliveries;
1480
+ total.deletedEvents += result.deletedEvents;
1481
+ }
1482
+ const orphanCutoff = [completedBefore, deadBefore].filter((cutoff) => cutoff !== void 0).sort((first, second) => first.getTime() - second.getTime())[0];
1483
+ if (orphanCutoff !== void 0) {
1484
+ total.deletedEvents += await this.#purgeOrphanEvents(orphanCutoff, completedBefore);
1485
+ }
1486
+ return total;
702
1487
  }
703
1488
  /**
704
- * Deletes batches of matching deliveries together with the events no delivery
705
- * references any more, each batch in one transaction, so a crash can never
706
- * leave an event without deliveries behind. An append adding a delivery to the
707
- * same event writes the event document, so the two conflict and one restarts
708
- * instead of leaving a delivery without event. A delivery requeued since the
709
- * batch was read conflicts with its deletion and is read again.
1489
+ * Deletes batches of matching documents (deliveries, or completion history
1490
+ * records) together with the events nothing references any more, each batch
1491
+ * in one transaction, so a crash can never leave an event without deliveries
1492
+ * behind. An append adding a delivery to the same event writes the event
1493
+ * document, so the two conflict and one restarts instead of leaving a delivery
1494
+ * without event. A delivery requeued since the batch was read conflicts with
1495
+ * its deletion and is read again.
710
1496
  */
711
- async #purgeMatching(filter) {
1497
+ async #purgeMatching(collection, {
1498
+ filter,
1499
+ completedBefore
1500
+ }) {
712
1501
  let deletedDeliveries = 0;
713
1502
  let deletedEvents = 0;
714
1503
  for (; ; ) {
715
- const step = await this.transaction(async (session) => {
716
- const batch = await this.#deliveries.find(filter, { session, projection: { eventId: 1 }, limit: this.#purgeBatchSize }).toArray();
1504
+ const step = await runInTransaction(this.#state, async (session) => {
1505
+ const batch = await collection.find(filter, { session, projection: { eventId: 1 }, limit: this.#state.purgeBatchSize }).toArray();
1506
+ if (batch.length === 0) {
1507
+ return { batchSize: 0, deletedDeliveries: 0, deletedEvents: 0 };
1508
+ }
717
1509
  const eventIds = [...new Set(batch.map((document) => document.eventId))];
718
- const deliveries = await this.#deliveries.deleteMany(
1510
+ const deleted = await collection.deleteMany(
719
1511
  { _id: { $in: batch.map((document) => document._id) } },
720
1512
  { session }
721
1513
  );
722
- const stillReferenced = new Set(
723
- (await this.#deliveries.find({ eventId: { $in: eventIds } }, { session, projection: { eventId: 1 } }).toArray()).map((document) => document.eventId)
724
- );
725
- const events = await this.#events.deleteMany(
726
- { _id: { $in: eventIds.filter((eventId) => !stillReferenced.has(eventId)) } },
1514
+ const stillReferenced = await this.#referencedEventIds(eventIds, session);
1515
+ const events = await this.#state.events.deleteMany(
1516
+ {
1517
+ _id: { $in: eventIds.filter((eventId) => !stillReferenced.has(eventId)) },
1518
+ // An event a delivery of which completed stays as deduplication record until
1519
+ // `completedBefore` passes its last completion, whatever this batch purged.
1520
+ $or: [
1521
+ { completedAt: { $exists: false } },
1522
+ ...completedBefore === void 0 ? [] : [{ completedAt: { $lt: completedBefore } }]
1523
+ ]
1524
+ },
727
1525
  { session }
728
1526
  );
729
1527
  return {
730
1528
  batchSize: batch.length,
731
- deletedDeliveries: deliveries.deletedCount,
1529
+ deletedDeliveries: deleted.deletedCount,
732
1530
  deletedEvents: events.deletedCount
733
1531
  };
734
1532
  });
735
1533
  deletedDeliveries += step.deletedDeliveries;
736
1534
  deletedEvents += step.deletedEvents;
737
- if (step.batchSize < this.#purgeBatchSize) {
1535
+ if (step.batchSize < this.#state.purgeBatchSize) {
738
1536
  return { deletedDeliveries, deletedEvents };
739
1537
  }
740
1538
  }
741
1539
  }
1540
+ /** A view of a collection that purge deletes from: deliveries or completion history records. */
1541
+ #purgeable(name) {
1542
+ return this.#state.database.collection(name, {
1543
+ readPreference: "primary",
1544
+ writeConcern: { w: "majority" }
1545
+ });
1546
+ }
1547
+ /** Those of `eventIds` that a delivery or a completion history record references. */
1548
+ async #referencedEventIds(eventIds, session) {
1549
+ const filter = { eventId: { $in: [...eventIds] } };
1550
+ const options = { session, projection: { eventId: 1 } };
1551
+ const references = [
1552
+ ...await this.#state.deliveries.find(filter, options).toArray(),
1553
+ ...this.#state.completionHistory ? await this.#state.completions.find(filter, options).toArray() : []
1554
+ ];
1555
+ return new Set(references.map((reference) => reference.eventId));
1556
+ }
1557
+ /**
1558
+ * Deletes, in batches, events created before `cutoff` that no delivery (or
1559
+ * completion history record) references. Each batch is found and deleted in
1560
+ * one transaction: an append adding a delivery to one of them writes the
1561
+ * event, so it conflicts with the deletion, which then restarts and sees the
1562
+ * delivery. Returns how many events were deleted.
1563
+ */
1564
+ async #purgeOrphanEvents(cutoff, completedBefore) {
1565
+ const references = [
1566
+ this.#state.deliveries.collectionName,
1567
+ ...this.#state.completionHistory ? [this.#state.completions.collectionName] : []
1568
+ ];
1569
+ let deletedEvents = 0;
1570
+ for (; ; ) {
1571
+ const step = await runInTransaction(this.#state, async (session) => {
1572
+ const orphans = await this.#state.events.aggregate(
1573
+ [
1574
+ {
1575
+ $match: {
1576
+ $or: [
1577
+ // Never completed (no subscribers, or every delivery dead): by age.
1578
+ { completedAt: { $exists: false }, createdAt: { $lt: cutoff } },
1579
+ // Completed: by the time of its last completion, and only under the completed cutoff.
1580
+ ...completedBefore === void 0 ? [] : [{ completedAt: { $lt: completedBefore } }]
1581
+ ]
1582
+ }
1583
+ },
1584
+ { $sort: { createdAt: 1, _id: 1 } },
1585
+ ...references.flatMap((from) => [
1586
+ {
1587
+ $lookup: {
1588
+ from,
1589
+ localField: "_id",
1590
+ foreignField: "eventId",
1591
+ pipeline: [{ $limit: 1 }, { $project: { _id: 1 } }],
1592
+ as: "references"
1593
+ }
1594
+ },
1595
+ { $match: { references: { $size: 0 } } }
1596
+ ]),
1597
+ { $limit: this.#state.purgeBatchSize },
1598
+ { $project: { _id: 1 } }
1599
+ ],
1600
+ { session }
1601
+ ).toArray();
1602
+ const deleted = await this.#state.events.deleteMany(
1603
+ { _id: { $in: orphans.map((orphan) => orphan._id) } },
1604
+ { session }
1605
+ );
1606
+ return { found: orphans.length, deleted: deleted.deletedCount };
1607
+ });
1608
+ deletedEvents += step.deleted;
1609
+ if (step.found < this.#state.purgeBatchSize) {
1610
+ return deletedEvents;
1611
+ }
1612
+ }
1613
+ }
1614
+ };
1615
+
1616
+ // src/mongo-queries.ts
1617
+ var DEFAULT_LIST_LIMIT = 100;
1618
+ var MongoQueries = class {
1619
+ #state;
1620
+ constructor(state) {
1621
+ this.#state = state;
1622
+ }
1623
+ /** Implements {@link MongoEventStore.listDeliveries}. */
1624
+ async listDeliveries(query) {
1625
+ const status = query.status === void 0 ? void 0 : String(query.status);
1626
+ const common = commonFilter(query);
1627
+ const limit = query.limit ?? DEFAULT_LIST_LIMIT;
1628
+ const lanes = await this.#state.lanes.find({ "inFlight.0": { $exists: true } }, { projection: { epoch: 0 } }).toArray();
1629
+ const listed = lanes.flatMap((lane) => lane.inFlight);
1630
+ const derivedStatuses = /* @__PURE__ */ new Map([
1631
+ ["processing", { status: "pending", _id: { $in: listed } }],
1632
+ ["pending", { status: "pending", _id: { $nin: listed } }]
1633
+ ]);
1634
+ const filter = {
1635
+ ...common,
1636
+ ...status === void 0 ? {} : derivedStatuses.get(status) ?? { status }
1637
+ };
1638
+ const sort = { createdAt: 1, _id: 1 };
1639
+ const documents = await this.#state.deliveries.find(filter, { sort, limit }).toArray();
1640
+ const history = this.#state.completionHistory && (status === void 0 || status === "completed") ? await this.#state.completions.find(common, { sort, limit }).toArray() : [];
1641
+ const events = await this.readEnvelopes([
1642
+ ...documents.map((document) => document.eventId),
1643
+ ...history.map((document) => document.eventId)
1644
+ ]);
1645
+ const laneById = new Map(lanes.map((lane) => [lane._id, lane]));
1646
+ const records = [
1647
+ ...documents.map((document) => {
1648
+ const lane = laneById.get(document.laneId);
1649
+ const runs = document.status === "pending" && lane?.inFlight.includes(document._id) === true;
1650
+ return toDeliveryRecord(document, {
1651
+ event: events.get(document.eventId),
1652
+ runningIn: runs ? lane : void 0
1653
+ });
1654
+ }),
1655
+ ...history.map(
1656
+ (document) => toCompletedDeliveryRecord(document, events.get(document.eventId))
1657
+ )
1658
+ ];
1659
+ return records.sort(
1660
+ (left, right) => left.createdAt.getTime() - right.createdAt.getTime() || compareText(left.id, right.id)
1661
+ ).slice(0, limit);
1662
+ }
1663
+ /** Implements {@link MongoEventStore.requeue}. */
1664
+ async requeue(deliveryIds, now) {
1665
+ const result = await this.#state.deliveries.updateMany(
1666
+ { _id: { $in: deliveryIds.map(String) }, status: "dead" },
1667
+ {
1668
+ $set: {
1669
+ status: "pending",
1670
+ lane: "ready",
1671
+ attempts: 0,
1672
+ availableAt: now,
1673
+ dueAt: now,
1674
+ updatedAt: now
1675
+ }
1676
+ }
1677
+ );
1678
+ return result.modifiedCount;
1679
+ }
1680
+ /** Implements {@link MongoEventStore.statistics}. */
1681
+ async statistics(now) {
1682
+ const lanes = await this.#state.lanes.find({ "inFlight.0": { $exists: true } }, { projection: { inFlight: 1, leaseExpiresAt: 1 } }).toArray();
1683
+ const [stored, dead, legacyCompleted, history, running] = await Promise.all([
1684
+ this.#state.deliveries.countDocuments({ status: "pending" }),
1685
+ this.#state.deliveries.countDocuments({ status: "dead" }),
1686
+ this.#state.deliveries.countDocuments({ status: "completed" }),
1687
+ this.#state.completionHistory ? this.#state.completions.countDocuments() : Promise.resolve(0),
1688
+ this.findRunning(lanes.flatMap((lane) => lane.inFlight))
1689
+ ]);
1690
+ const runningIds = new Set(running.map((document) => document._id));
1691
+ const waiting = await this.#state.deliveries.findOne(
1692
+ { dueAt: { $lte: now }, _id: { $nin: [...runningIds] } },
1693
+ { sort: { dueAt: 1 }, projection: { dueAt: 1 } }
1694
+ );
1695
+ const dueTimes = lanes.filter(
1696
+ (lane) => lane.leaseExpiresAt !== null && lane.leaseExpiresAt <= now && lane.inFlight.some((id) => runningIds.has(id))
1697
+ ).map((lane) => lane.leaseExpiresAt.getTime());
1698
+ if (waiting !== null) {
1699
+ dueTimes.push(waiting.dueAt.getTime());
1700
+ }
1701
+ return {
1702
+ // The counts are separate reads; a completion between them must not make this negative.
1703
+ pending: Math.max(0, stored - running.length),
1704
+ processing: running.length,
1705
+ completed: legacyCompleted + history,
1706
+ dead,
1707
+ oldestDueAt: dueTimes.length === 0 ? null : new Date(Math.min(...dueTimes))
1708
+ };
1709
+ }
1710
+ /** The listed deliveries that run: those whose document still exists as pending. */
1711
+ async findRunning(listed) {
1712
+ if (listed.length === 0) {
1713
+ return [];
1714
+ }
1715
+ return this.#state.deliveries.find(
1716
+ { _id: { $in: [...listed] }, status: "pending" },
1717
+ { projection: { handler: 1, key: 1, laneId: 1 } }
1718
+ ).toArray();
1719
+ }
1720
+ async readEnvelopes(eventIds) {
1721
+ const documents = await this.#state.events.find({ _id: { $in: [...new Set(eventIds)] } }).toArray();
1722
+ return new Map(documents.map((document) => [document._id, toEnvelope(document)]));
1723
+ }
742
1724
  };
743
- function deliveryPairKey(eventId, handler) {
744
- return `${eventId}\0${handler}`;
1725
+ function compareText(left, right) {
1726
+ return Number(left > right) - Number(left < right);
745
1727
  }
746
- function assertInTransaction(session, operation) {
747
- if (!session.inTransaction()) {
1728
+ function commonFilter(query) {
1729
+ return {
1730
+ ...query.handler === void 0 ? {} : { handler: String(query.handler) },
1731
+ ...query.eventType === void 0 ? {} : { eventType: String(query.eventType) },
1732
+ ...query.eventId === void 0 ? {} : { eventId: String(query.eventId) }
1733
+ };
1734
+ }
1735
+
1736
+ // src/mongo-schema.ts
1737
+ var NAMESPACE_EXISTS = 48;
1738
+ var INDEX_NOT_FOUND = 27;
1739
+ var UPGRADE_BATCH_SIZE = 1e3;
1740
+ var CLAIM_INDEX_KEY = { laneId: 1, dueAt: 1, _id: 1, handler: 1 };
1741
+ var OBSOLETE_INDEXES = ["running"];
1742
+ var LEASE_FIELDS = { leaseOwner: "", leaseToken: "", leaseExpiresAt: "" };
1743
+ var MongoSchema = class {
1744
+ #state;
1745
+ constructor(state) {
1746
+ this.#state = state;
1747
+ }
1748
+ /** Implements {@link MongoEventStore.setup}. */
1749
+ async setup() {
1750
+ const hello = await this.#state.client.db("admin").command({ hello: 1 });
1751
+ const supportsTransactions = typeof hello["setName"] === "string" || hello["msg"] === "isdbgrid";
1752
+ if (!supportsTransactions) {
1753
+ throw createTransactionsUnsupportedError(void 0);
1754
+ }
1755
+ const collectionNames = [
1756
+ this.#state.events.collectionName,
1757
+ this.#state.deliveries.collectionName,
1758
+ this.#state.keySequences.collectionName,
1759
+ this.#state.lanes.collectionName,
1760
+ ...this.#state.completionHistory ? [this.#state.completions.collectionName] : []
1761
+ ];
1762
+ for (const name of collectionNames) {
1763
+ await this.#createCollectionIfMissing(name);
1764
+ }
1765
+ if (await this.#state.lanes.countDocuments() < LANE_COUNT) {
1766
+ await this.#upgradeFromVersion010();
1767
+ await this.#seedLanes();
1768
+ }
1769
+ await this.#dropObsoleteIndexes();
1770
+ await this.#createIndexes();
1771
+ }
1772
+ /** Creates the indexes of every collection; existing indexes are left as they are. */
1773
+ async #createIndexes() {
1774
+ await this.#state.deliveries.createIndexes([
1775
+ // Idempotent appends and lookups by event.
1776
+ { key: { eventId: 1, handler: 1 }, name: "event_handler", unique: true },
1777
+ // Claim: due work of a lane in due order. Holds ready deliveries only. The handler is
1778
+ // last, so a query over many lanes and handlers stays a merge of one scan per lane.
1779
+ { key: CLAIM_INDEX_KEY, name: "claim", partialFilterExpression: { lane: "ready" } },
1780
+ // Ordering: unfinished predecessors of a keyed delivery, parked or not.
1781
+ {
1782
+ key: { handler: 1, key: 1, sequence: 1 },
1783
+ name: "ordering",
1784
+ partialFilterExpression: { dueAt: { $exists: true }, sequence: { $exists: true } }
1785
+ },
1786
+ // Parked deliveries: the lowest parked delivery of each key, to move it back once it is next.
1787
+ {
1788
+ key: { handler: 1, key: 1, sequence: 1 },
1789
+ name: "parked",
1790
+ partialFilterExpression: { lane: "parked" }
1791
+ },
1792
+ // Statistics: oldest due delivery across handlers.
1793
+ { key: { dueAt: 1 }, name: "due", partialFilterExpression: { dueAt: { $exists: true } } },
1794
+ // Purge of completed deliveries left by 0.1.0.
1795
+ {
1796
+ key: { completedAt: 1 },
1797
+ name: "completed",
1798
+ partialFilterExpression: { completedAt: { $exists: true } }
1799
+ },
1800
+ // Listing and status counts.
1801
+ { key: { status: 1, createdAt: 1 }, name: "status_created" },
1802
+ // Purge of dead deliveries.
1803
+ { key: { status: 1, updatedAt: 1 }, name: "status_updated" },
1804
+ { key: { handler: 1, createdAt: 1 }, name: "handler_created" },
1805
+ { key: { eventType: 1, createdAt: 1 }, name: "type_created" }
1806
+ ]);
1807
+ await this.#state.events.createIndexes([
1808
+ { key: { createdAt: 1, _id: 1 }, name: "created" },
1809
+ // Purge of events whose deliveries all completed: they are kept until `completedBefore` passes this.
1810
+ {
1811
+ key: { completedAt: 1, _id: 1 },
1812
+ name: "completed",
1813
+ partialFilterExpression: { completedAt: { $exists: true } }
1814
+ }
1815
+ ]);
1816
+ if (this.#state.completionHistory) {
1817
+ await this.#state.completions.createIndexes([
1818
+ { key: { completedAt: 1, _id: 1 }, name: "completed" },
1819
+ { key: { eventId: 1 }, name: "event" },
1820
+ { key: { createdAt: 1, _id: 1 }, name: "created" }
1821
+ ]);
1822
+ }
1823
+ }
1824
+ async #createCollectionIfMissing(name) {
1825
+ try {
1826
+ await this.#state.database.createCollection(name);
1827
+ } catch (error) {
1828
+ if (!hasErrorCode(error, NAMESPACE_EXISTS)) {
1829
+ throw error;
1830
+ }
1831
+ }
1832
+ }
1833
+ /**
1834
+ * Converts the documents of a 0.1.0 database; every step is idempotent, so a
1835
+ * run that crashed is simply repeated. Deliveries that were `processing`
1836
+ * become `pending`, due at once (their attempt stays counted, as a lost lease
1837
+ * would count it). The per-delivery lease fields go, every delivery gets its
1838
+ * lane, and every event learns which handlers it already has deliveries for
1839
+ * and when it was created. Deliveries completed under 0.1.0 stay as
1840
+ * `completed` documents until a purge removes them.
1841
+ */
1842
+ async #upgradeFromVersion010() {
1843
+ const legacy = this.#state.database.collection(this.#state.deliveries.collectionName);
1844
+ await legacy.updateMany({ status: "processing" }, [
1845
+ { $set: { status: "pending", lane: "ready", dueAt: "$availableAt" } }
1846
+ ]);
1847
+ await legacy.updateMany(
1848
+ {
1849
+ $or: [
1850
+ { leaseOwner: { $exists: true } },
1851
+ { leaseToken: { $exists: true } },
1852
+ { leaseExpiresAt: { $exists: true } }
1853
+ ]
1854
+ },
1855
+ { $unset: LEASE_FIELDS }
1856
+ );
1857
+ await inBatches(
1858
+ this.#state.deliveries.find(
1859
+ { laneId: { $exists: false } },
1860
+ { projection: { eventId: 1, key: 1 }, batchSize: UPGRADE_BATCH_SIZE }
1861
+ ),
1862
+ async (documents) => {
1863
+ await this.#state.deliveries.bulkWrite(
1864
+ documents.map((document) => ({
1865
+ updateOne: {
1866
+ filter: { _id: document._id },
1867
+ update: { $set: { laneId: laneOf(document.key ?? null, document.eventId) } }
1868
+ }
1869
+ })),
1870
+ { ordered: false }
1871
+ );
1872
+ }
1873
+ );
1874
+ await this.#upgradeEventsFromVersion010();
1875
+ }
1876
+ /** Tells every 0.1.0 event which handlers it already has deliveries for and when it was created. */
1877
+ async #upgradeEventsFromVersion010() {
1878
+ await inBatches(
1879
+ this.#state.events.find(
1880
+ { handlers: { $exists: false } },
1881
+ { projection: { occurredAt: 1 }, batchSize: UPGRADE_BATCH_SIZE }
1882
+ ),
1883
+ async (events) => {
1884
+ const known = new Map(
1885
+ (await this.#state.deliveries.aggregate([
1886
+ { $match: { eventId: { $in: events.map((event) => event._id) } } },
1887
+ {
1888
+ $group: {
1889
+ _id: "$eventId",
1890
+ handlers: { $addToSet: "$handler" },
1891
+ createdAt: { $min: "$createdAt" }
1892
+ }
1893
+ }
1894
+ ]).toArray()).map((group) => [group._id, group])
1895
+ );
1896
+ await this.#state.events.bulkWrite(
1897
+ events.map((event) => {
1898
+ const group = known.get(event._id);
1899
+ return {
1900
+ updateOne: {
1901
+ // Only an event nobody converted yet: another process may have finished and subscribed a handler.
1902
+ filter: { _id: event._id, handlers: { $exists: false } },
1903
+ update: {
1904
+ $set: group === void 0 ? { handlers: [], createdAt: event.occurredAt } : { handlers: group.handlers, createdAt: group.createdAt }
1905
+ }
1906
+ }
1907
+ };
1908
+ }),
1909
+ { ordered: false }
1910
+ );
1911
+ }
1912
+ );
1913
+ }
1914
+ /** Creates the lane documents that do not exist yet. */
1915
+ async #seedLanes() {
1916
+ await this.#state.lanes.bulkWrite(
1917
+ Array.from({ length: LANE_COUNT }, (_, laneId) => ({
1918
+ updateOne: {
1919
+ filter: { _id: laneId },
1920
+ update: {
1921
+ $setOnInsert: {
1922
+ epoch: 0,
1923
+ owner: null,
1924
+ holder: null,
1925
+ leaseExpiresAt: null,
1926
+ inFlight: [],
1927
+ lost: []
1928
+ }
1929
+ },
1930
+ upsert: true
1931
+ }
1932
+ })),
1933
+ { ordered: false }
1934
+ );
1935
+ }
1936
+ /** Drops the 0.1.0 indexes that no query uses, and a `claim` index with the 0.1.0 key. */
1937
+ async #dropObsoleteIndexes() {
1938
+ for (const index of await this.#state.deliveries.indexes()) {
1939
+ if (isObsoleteIndex(index)) {
1940
+ await this.#dropIndexIfPresent(index.name);
1941
+ }
1942
+ }
1943
+ }
1944
+ async #dropIndexIfPresent(name) {
1945
+ try {
1946
+ await this.#state.deliveries.dropIndex(name);
1947
+ } catch (error) {
1948
+ if (!hasErrorCode(error, INDEX_NOT_FOUND)) {
1949
+ throw error;
1950
+ }
1951
+ }
1952
+ }
1953
+ };
1954
+ function isObsoleteIndex(index) {
1955
+ return OBSOLETE_INDEXES.includes(index.name) || index.name === "claim" && Object.keys(index.key).join() !== Object.keys(CLAIM_INDEX_KEY).join();
1956
+ }
1957
+ async function inBatches(cursor, work) {
1958
+ let batch = [];
1959
+ for await (const document of cursor) {
1960
+ batch.push(document);
1961
+ if (batch.length === UPGRADE_BATCH_SIZE) {
1962
+ await work(batch);
1963
+ batch = [];
1964
+ }
1965
+ }
1966
+ if (batch.length > 0) {
1967
+ await work(batch);
1968
+ }
1969
+ }
1970
+ function hasErrorCode(error, code) {
1971
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
1972
+ }
1973
+ var COLLECTION_PREFIX_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,39}$/;
1974
+ var DATABASE_NAME_PATTERN = /^[A-Za-z0-9_-]{1,63}$/;
1975
+ function assertCollectionPrefix(prefix) {
1976
+ if (!COLLECTION_PREFIX_PATTERN.test(prefix)) {
748
1977
  throw new core.ConfigurationError(
749
- `MongoEventStore.${operation} needs a ClientSession inside a started transaction (session.withTransaction or startTransaction). Without one, MongoDB commits each write immediately and the write is no longer atomic with yours`
1978
+ `collectionPrefix '${prefix}' must be 1-40 characters of letters, digits or '_', starting with a letter or '_'`
750
1979
  );
751
1980
  }
752
1981
  }
1982
+ function assertDatabaseName(name) {
1983
+ if (!DATABASE_NAME_PATTERN.test(name)) {
1984
+ throw new core.ConfigurationError(
1985
+ `database '${name}' must be 1-63 characters of letters, digits, '_' or '-'`
1986
+ );
1987
+ }
1988
+ }
1989
+
1990
+ // src/mongo-event-store.ts
1991
+ var DEFAULT_TRANSACTION_OPTIONS = {
1992
+ readConcern: { level: "snapshot" },
1993
+ writeConcern: { w: "majority" },
1994
+ readPreference: "primary"
1995
+ };
1996
+ var DEFAULT_PURGE_BATCH_SIZE = 500;
1997
+ var MongoEventStore = class {
1998
+ #state;
1999
+ #schema;
2000
+ #appender;
2001
+ #claims;
2002
+ #laneLeases;
2003
+ #completion;
2004
+ #queries;
2005
+ #purger;
2006
+ constructor(options) {
2007
+ const prefix = options.collectionPrefix ?? "relaybus_";
2008
+ assertCollectionPrefix(prefix);
2009
+ if (options.database !== void 0) {
2010
+ assertDatabaseName(options.database);
2011
+ }
2012
+ const purgeBatchSize = internal.assertPositiveInteger(
2013
+ options.purgeBatchSize ?? DEFAULT_PURGE_BATCH_SIZE,
2014
+ "purgeBatchSize"
2015
+ );
2016
+ const database = options.client.db(options.database);
2017
+ const collectionOptions = {
2018
+ readPreference: "primary",
2019
+ writeConcern: { w: "majority" }
2020
+ };
2021
+ const state = {
2022
+ client: options.client,
2023
+ database,
2024
+ events: database.collection(`${prefix}events`, collectionOptions),
2025
+ deliveries: database.collection(`${prefix}deliveries`, collectionOptions),
2026
+ keySequences: database.collection(`${prefix}key_sequences`, collectionOptions),
2027
+ lanes: database.collection(`${prefix}lanes`, collectionOptions),
2028
+ completions: database.collection(`${prefix}completed_deliveries`, collectionOptions),
2029
+ completionHistory: options.completionHistory ?? false,
2030
+ transactionOptions: options.transactionOptions ?? DEFAULT_TRANSACTION_OPTIONS,
2031
+ purgeBatchSize,
2032
+ logger: options.logger ?? console,
2033
+ instanceId: core.createUuidV7(),
2034
+ claimsInProgress: /* @__PURE__ */ new Map(),
2035
+ handedOut: /* @__PURE__ */ new Map(),
2036
+ unreconciledOwners: /* @__PURE__ */ new Set()
2037
+ };
2038
+ this.#state = state;
2039
+ const queries = new MongoQueries(state);
2040
+ const ordering = new MongoOrdering(state);
2041
+ const laneLeases = new MongoLaneLeases(state, { queries });
2042
+ this.#schema = new MongoSchema(state);
2043
+ this.#appender = new MongoAppend(state);
2044
+ this.#claims = new MongoClaims(state, { laneLeases, ordering, queries });
2045
+ this.#laneLeases = laneLeases;
2046
+ this.#completion = new MongoCompletion(state);
2047
+ this.#queries = queries;
2048
+ this.#purger = new MongoPurge(state);
2049
+ }
2050
+ /**
2051
+ * Verifies the deployment supports transactions, creates the collections and
2052
+ * indexes and seeds the lane documents. Upgrades a 0.1.0 database in place
2053
+ * first (see `MongoSchema.#upgradeFromVersion010`); the seeded lanes
2054
+ * mark the upgrade as done, so later runs skip it. Safe to run repeatedly and
2055
+ * from several processes. Stop 0.1.0 workers before the first run.
2056
+ *
2057
+ * @throws ConfigurationError when the server is a standalone mongod.
2058
+ */
2059
+ setup() {
2060
+ return this.#schema.setup();
2061
+ }
2062
+ /**
2063
+ * Runs `work` in a transaction on a new session and commits when it resolves.
2064
+ *
2065
+ * `work` can run more than once. The driver restarts the whole callback after
2066
+ * a transient failure such as a write conflict, and re-sends only the commit
2067
+ * after an unknown commit result. A restart is safe for everything written
2068
+ * through the session, because the aborted attempt left nothing behind. It is
2069
+ * not safe for side effects outside the session (HTTP calls, other databases),
2070
+ * so keep those out of `work`; relaybus handlers are already at-least-once.
2071
+ *
2072
+ * With `options.timeoutMs` (from `bus.transaction`) the server bounds the commit with
2073
+ * `maxCommitTimeMS`; the bus aborts a transaction that ran past the budget before its commit.
2074
+ *
2075
+ * @throws ConfigurationError when the deployment does not support transactions.
2076
+ */
2077
+ transaction(work, options) {
2078
+ return options === void 0 ? runInTransaction(this.#state, work) : runInBudgetedTransaction(this.#state, { work, timeoutMs: options.timeoutMs });
2079
+ }
2080
+ /**
2081
+ * Writes the entries in `session`. An existing event gets a delivery only for
2082
+ * handlers it does not list yet; the added handlers are appended to its list
2083
+ * together with a `revision` increment, a real write that makes a concurrent
2084
+ * purge of the event conflict with this transaction.
2085
+ */
2086
+ // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature
2087
+ append(session, entries, now) {
2088
+ return this.#appender.append(session, { entries, now });
2089
+ }
2090
+ /**
2091
+ * Claims up to `limit` due deliveries. It claims from the lanes this owner
2092
+ * (and this store instance) holds under a live lease first, then takes free
2093
+ * lanes with due work, a few at a time (4, 8, 16, ...) and the lane with the
2094
+ * oldest due delivery first, so a worker holds only as many lanes as it
2095
+ * needs. It then records the batch with one write per lane and hands back the
2096
+ * lanes that yielded nothing and run nothing. No delivery document is
2097
+ * written, except for the attempt charged to deliveries of a lane taken over
2098
+ * and for parking (see `MongoOrdering.#parkDeliveries`).
2099
+ *
2100
+ * Taking a lane is one conditional `findOneAndUpdate` that also moves the
2101
+ * previous owner's in-flight list to the lane's `lost` list; a lane another
2102
+ * claimer took first is skipped, never waited for. Lost deliveries are charged
2103
+ * one attempt before anything is read from the lane, and `lost` is cleared
2104
+ * only after that. Whoever holds the lane next charges a `lost` list it finds
2105
+ * first, so a claim that fails anywhere after the take loses no charge; the
2106
+ * charge of a lost claim is recorded on the delivery, so charging the list
2107
+ * again after a failure before the clear charges nothing twice.
2108
+ * Nothing a failed claim did leaves a delivery listed as running.
2109
+ */
2110
+ claim(request) {
2111
+ return this.#claims.claim(request);
2112
+ }
2113
+ /**
2114
+ * Extends the lease of the lane a running delivery belongs to. The lane lease
2115
+ * never shrinks, so a repeated renewal with the same value still holds. An
2116
+ * expired lease nobody took over is still renewed, so `_now` is not needed.
2117
+ */
2118
+ // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature
2119
+ extendLease(lease, leaseExpiresAt, _now) {
2120
+ return this.#completion.extendLease(lease, leaseExpiresAt);
2121
+ }
2122
+ /**
2123
+ * Deletes the delivery (and records it in the completion history, when kept).
2124
+ * With `session` the deletion commits with the caller's transaction; without,
2125
+ * it runs in a transaction of its own. Returns false when the lease was lost.
2126
+ */
2127
+ // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature
2128
+ complete(lease, now, session) {
2129
+ return this.#completion.complete(lease, { now, session });
2130
+ }
2131
+ /**
2132
+ * Completes many leases with a fixed number of round trips, whatever lanes
2133
+ * they belong to: three commands without a completion history, one
2134
+ * transaction with it (see `MongoCompletion.#deleteFenced`).
2135
+ * Returns one flag per lease in input order; a lease listed twice completes
2136
+ * once, and a token this store cannot have issued is refused.
2137
+ */
2138
+ completeMany(leases, now) {
2139
+ return this.#completion.completeMany(leases, now);
2140
+ }
2141
+ /** Returns a running delivery to pending, due at `availableAt`, and counts the attempt that ended. */
2142
+ // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature
2143
+ reschedule(lease, availableAt, error, now) {
2144
+ return this.#completion.reschedule(lease, { availableAt, error, now });
2145
+ }
2146
+ /** Gives a running delivery back without counting the attempt: pending, due `now`. */
2147
+ release(lease, now) {
2148
+ return this.#completion.release(lease, now);
2149
+ }
2150
+ /** Moves a running delivery to dead and counts the attempt that ended. */
2151
+ // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature
2152
+ bury(lease, error, now) {
2153
+ return this.#completion.bury(lease, { error, now });
2154
+ }
2155
+ /**
2156
+ * Frees every lane `leaseOwner` holds that runs no delivery, so other workers
2157
+ * need not wait for the lease to expire. Lanes with running deliveries stay leased.
2158
+ */
2159
+ relinquish(leaseOwner) {
2160
+ return this.#laneLeases.relinquish(leaseOwner);
2161
+ }
2162
+ /**
2163
+ * Lists deliveries in creation order. A delivery is `processing` while its
2164
+ * document exists as `pending` and its lane lists it; its attempt count then
2165
+ * includes the running attempt, and owner and expiry are those of the lane
2166
+ * lease. Completion history records (when kept) are listed as `completed`.
2167
+ */
2168
+ listDeliveries(query) {
2169
+ return this.#queries.listDeliveries(query);
2170
+ }
2171
+ /** Moves dead deliveries back to pending with a fresh attempt budget. */
2172
+ requeue(deliveryIds, now) {
2173
+ return this.#queries.requeue(deliveryIds, now);
2174
+ }
2175
+ /**
2176
+ * Deletes, in batches of `purgeBatchSize`, dead deliveries last updated before
2177
+ * `deadBefore`, and completion history records (and `completed` documents left
2178
+ * by 0.1.0) completed before `completedBefore`, each batch in one transaction
2179
+ * together with the events it left without any reference. Finally, events
2180
+ * nothing references are deleted: one with a completed delivery once its last
2181
+ * completion is before `completedBefore` (never by `deadBefore` alone), one
2182
+ * that never had a completion (no subscribers, or only dead letters) once it
2183
+ * was created before the earliest given cutoff. The batch step applies the
2184
+ * same rule to events whose last completion is recorded.
2185
+ */
2186
+ purge(request) {
2187
+ return this.#purger.purge(request);
2188
+ }
2189
+ /**
2190
+ * Counts by derived status. `pending` excludes running deliveries; `completed`
2191
+ * counts history records and 0.1.0 `completed` documents. `oldestDueAt` is the
2192
+ * oldest instant at which a delivery became claimable: the due time of a
2193
+ * pending delivery nobody runs, or the lease expiry of a lane that still runs
2194
+ * deliveries.
2195
+ */
2196
+ statistics(now) {
2197
+ return this.#queries.statistics(now);
2198
+ }
2199
+ };
753
2200
 
754
2201
  exports.MongoEventStore = MongoEventStore;
755
2202
  //# sourceMappingURL=index.cjs.map