@relaybus/postgres 0.2.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
@@ -2,32 +2,131 @@
2
2
 
3
3
  var crypto = require('crypto');
4
4
  var core = require('@relaybus/core');
5
+ var internal = require('@relaybus/core/internal');
5
6
  var pg = require('pg');
6
7
 
8
+ // src/pg-executor.ts
9
+
10
+ // src/transaction-timeouts.ts
11
+ function budgetSettingsSql({ value, sessionTimeouts, scope }) {
12
+ const local = scope === "transaction";
13
+ const statementTimeout = `SELECT set_config('statement_timeout', ${value}, ${local})`;
14
+ if (!sessionTimeouts) {
15
+ return statementTimeout;
16
+ }
17
+ return `${statementTimeout}, set_config('idle_in_transaction_session_timeout', ${value}, ${local}), CASE WHEN current_setting('server_version_num')::int >= 170000 THEN set_config('transaction_timeout', ${value}, ${local}) END`;
18
+ }
19
+ var SESSION_DEFAULTS_SQL = "SELECT set_config(name, reset_val, false) FROM pg_settings WHERE name IN ('statement_timeout', 'idle_in_transaction_session_timeout', 'transaction_timeout')";
20
+ function budgetValue(timeoutMs) {
21
+ return `${Math.ceil(timeoutMs)}ms`;
22
+ }
23
+ function inBudgetedTransaction(state, {
24
+ work,
25
+ timeoutMs
26
+ }) {
27
+ const { executor } = state;
28
+ if (executor.transactionWithBudget !== void 0) {
29
+ return executor.transactionWithBudget(work, timeoutMs);
30
+ }
31
+ const sql = budgetSettingsSql({
32
+ value: "$1",
33
+ sessionTimeouts: executor.sessionTimeouts === true,
34
+ scope: "transaction"
35
+ });
36
+ return executor.transaction(async (transaction) => {
37
+ await state.query({ sql, parameters: [budgetValue(timeoutMs)], transaction });
38
+ return work(transaction);
39
+ });
40
+ }
41
+
7
42
  // src/pg-executor.ts
8
43
  var FOREIGN_SESSION_ERRORS = /* @__PURE__ */ new Set(["26000", "42P05"]);
44
+ var STATEMENT_NAME_DIGITS = 24;
9
45
  var PgExecutor = class {
10
46
  #pool;
11
47
  #logger;
12
48
  #names = /* @__PURE__ */ new Map();
13
49
  #preparing = true;
50
+ #sessionBudget;
51
+ /** The budget each connection keeps at session level (`sessionBudget`); absent for the defaults. */
52
+ #sessionValues = /* @__PURE__ */ new WeakMap();
14
53
  constructor(pool, options = {}) {
15
54
  this.#pool = pool;
16
55
  this.#logger = options.logger ?? console;
56
+ this.#sessionBudget = options.sessionBudget === true;
57
+ }
58
+ /** The connection listens for `error` during the transaction, so a server-ended session fails the transaction instead of the process. */
59
+ sessionTimeouts = true;
60
+ transaction(work) {
61
+ return this.#transaction(
62
+ work,
63
+ (client) => this.#sessionBudget && (!this.#preparing || this.#sessionValues.has(client)) ? { begin: `BEGIN; ${SESSION_DEFAULTS_SQL}`, sessionValue: null } : { begin: "BEGIN" }
64
+ );
65
+ }
66
+ /**
67
+ * Sends `BEGIN` and the budget settings as one simple query (the value as a literal: the simple
68
+ * query protocol has no parameters), so the budget costs no round trip. With `sessionBudget` a
69
+ * connection that already keeps this budget only gets `BEGIN`.
70
+ */
71
+ transactionWithBudget(work, timeoutMs) {
72
+ const value = budgetValue(timeoutMs);
73
+ const settings = (scope) => budgetSettingsSql({ value: `'${value}'`, sessionTimeouts: true, scope });
74
+ return this.#transaction(work, (client) => {
75
+ if (!this.#keepsSessionBudget()) {
76
+ return { begin: `BEGIN; ${settings("transaction")}` };
77
+ }
78
+ return this.#sessionValues.get(client) === value ? { begin: "BEGIN" } : { begin: `BEGIN; ${settings("session")}`, sessionValue: value };
79
+ });
17
80
  }
18
- async transaction(work) {
81
+ #recordSession(client, sessionValue) {
82
+ if (sessionValue === null) {
83
+ this.#sessionValues.delete(client);
84
+ } else if (sessionValue !== void 0) {
85
+ this.#sessionValues.set(client, sessionValue);
86
+ }
87
+ }
88
+ /** A pooler that hands out other server sessions (noticed by prepared statements) shares session settings. */
89
+ #keepsSessionBudget() {
90
+ return this.#sessionBudget && this.#preparing;
91
+ }
92
+ async #transaction(work, start) {
19
93
  const client = await this.#pool.connect();
94
+ let released = false;
95
+ const release = (destroy) => {
96
+ if (released) {
97
+ return;
98
+ }
99
+ released = true;
100
+ client.removeListener("error", onSessionEnded);
101
+ if (destroy) {
102
+ client.release(true);
103
+ } else {
104
+ client.release();
105
+ }
106
+ };
107
+ const onSessionEnded = (error) => {
108
+ this.#logger.warn(
109
+ `[PgExecutor](transaction) The server ended the session of an open transaction, the transaction fails | error=${error.message}`
110
+ );
111
+ release(true);
112
+ };
113
+ client.on("error", onSessionEnded);
114
+ const { begin, sessionValue } = start(client);
20
115
  try {
21
- await client.query("BEGIN");
116
+ await client.query(begin);
22
117
  const result = await work(client);
23
- await client.query("COMMIT");
24
- client.release();
118
+ const { command } = await client.query("COMMIT");
119
+ if (command === "COMMIT") {
120
+ this.#recordSession(client, sessionValue);
121
+ }
122
+ release(false);
25
123
  return result;
26
124
  } catch (error) {
27
- await this.#rollbackAndRelease(client);
125
+ await this.#rollbackAndRelease(client, release);
28
126
  throw error;
29
127
  }
30
128
  }
129
+ // eslint-disable-next-line relaybus/max-two-params -- PostgresExecutor port signature
31
130
  async query(sql, parameters, transaction, options) {
32
131
  const queryable = transaction ?? this.#pool;
33
132
  const values = [...parameters];
@@ -56,18 +155,18 @@ var PgExecutor = class {
56
155
  #nameOf(sql) {
57
156
  let name = this.#names.get(sql);
58
157
  if (name === void 0) {
59
- name = `relaybus_${crypto.createHash("sha256").update(sql).digest("hex").slice(0, 24)}`;
158
+ name = `relaybus_${crypto.createHash("sha256").update(sql).digest("hex").slice(0, STATEMENT_NAME_DIGITS)}`;
60
159
  this.#names.set(sql, name);
61
160
  }
62
161
  return name;
63
162
  }
64
163
  /** A client whose rollback fails is in an unknown state, so it is destroyed instead of reused. */
65
- async #rollbackAndRelease(client) {
164
+ async #rollbackAndRelease(client, release) {
66
165
  try {
67
166
  await client.query("ROLLBACK");
68
- client.release();
167
+ release(false);
69
168
  } catch {
70
- client.release(true);
169
+ release(true);
71
170
  }
72
171
  }
73
172
  };
@@ -139,8 +238,9 @@ function resolvePostgresNames(options = {}) {
139
238
  }
140
239
  };
141
240
  }
241
+ var CHANNEL_HASH_DIGITS = 32;
142
242
  function channelName(readable) {
143
- return readable.length <= MAXIMUM_CHANNEL_LENGTH ? readable : `relaybus_${crypto.createHash("sha256").update(readable).digest("hex").slice(0, 32)}`;
243
+ return readable.length <= MAXIMUM_CHANNEL_LENGTH ? readable : `relaybus_${crypto.createHash("sha256").update(readable).digest("hex").slice(0, CHANNEL_HASH_DIGITS)}`;
144
244
  }
145
245
 
146
246
  // src/sql-fragments.ts
@@ -152,9 +252,21 @@ function laneExpression(keyExpression, eventIdExpression) {
152
252
  }
153
253
 
154
254
  // src/schema.ts
255
+ var SCHEMA_MARKER_DIGITS = 32;
155
256
  function createPostgresSchemaStatements(options = {}) {
156
257
  const names = resolvePostgresNames(options);
157
- const statements = [
258
+ const statements = [...eventAndDeliveryStatements(names), ...laneAndCompletionStatements(names)];
259
+ if (names.completionHistory) {
260
+ statements.push(...completionHistoryStatements(names));
261
+ }
262
+ if (names.schema !== "public") {
263
+ statements.unshift(`CREATE SCHEMA IF NOT EXISTS ${names.quotedSchema}`);
264
+ }
265
+ statements.push(`COMMENT ON TABLE ${names.lanes} IS '${postgresSchemaMarker(statements)}'`);
266
+ return statements;
267
+ }
268
+ function eventAndDeliveryStatements(names) {
269
+ return [
158
270
  `CREATE TABLE IF NOT EXISTS ${names.events} (
159
271
  id text PRIMARY KEY,
160
272
  type text NOT NULL,
@@ -198,7 +310,11 @@ function createPostgresSchemaStatements(options = {}) {
198
310
  `CREATE INDEX IF NOT EXISTS ${names.indexes.deliveryLaneDue} ON ${names.deliveries} (lane, available_at, id) WHERE status = 'pending'`,
199
311
  `CREATE INDEX IF NOT EXISTS ${names.indexes.deliveryKeyPending} ON ${names.deliveries} (lane, handler, key, sequence) WHERE key IS NOT NULL AND status = 'pending'`,
200
312
  `CREATE INDEX IF NOT EXISTS ${names.indexes.deliveryCompleted} ON ${names.deliveries} (completed_at, id) WHERE status = 'completed'`,
201
- `CREATE INDEX IF NOT EXISTS ${names.indexes.deliveryDead} ON ${names.deliveries} (updated_at, id) WHERE status = 'dead'`,
313
+ `CREATE INDEX IF NOT EXISTS ${names.indexes.deliveryDead} ON ${names.deliveries} (updated_at, id) WHERE status = 'dead'`
314
+ ];
315
+ }
316
+ function laneAndCompletionStatements(names) {
317
+ return [
202
318
  `CREATE TABLE IF NOT EXISTS ${names.lanes} (
203
319
  lane smallint PRIMARY KEY CHECK (lane >= 0 AND lane < ${LANE_COUNT}),
204
320
  epoch bigint NOT NULL DEFAULT 0,
@@ -215,9 +331,10 @@ function createPostgresSchemaStatements(options = {}) {
215
331
  `CREATE INDEX IF NOT EXISTS ${names.indexes.eventCompletionsCompleted} ON ${names.eventCompletions} (completed_at, event_id)`,
216
332
  `INSERT INTO ${names.lanes} (lane) SELECT generate_series(0, ${LANE_COUNT - 1})::smallint ON CONFLICT (lane) DO NOTHING`
217
333
  ];
218
- if (names.completionHistory) {
219
- statements.push(
220
- `CREATE TABLE IF NOT EXISTS ${names.completions} (
334
+ }
335
+ function completionHistoryStatements(names) {
336
+ return [
337
+ `CREATE TABLE IF NOT EXISTS ${names.completions} (
221
338
  id text COLLATE "C" PRIMARY KEY,
222
339
  event_id text NOT NULL REFERENCES ${names.events} (id) ON DELETE CASCADE,
223
340
  handler text NOT NULL,
@@ -226,17 +343,11 @@ function createPostgresSchemaStatements(options = {}) {
226
343
  created_at timestamptz NOT NULL,
227
344
  completed_at timestamptz NOT NULL
228
345
  )`,
229
- `CREATE INDEX IF NOT EXISTS ${names.indexes.completionCompleted} ON ${names.completions} (completed_at, id)`
230
- );
231
- }
232
- if (names.schema !== "public") {
233
- statements.unshift(`CREATE SCHEMA IF NOT EXISTS ${names.quotedSchema}`);
234
- }
235
- statements.push(`COMMENT ON TABLE ${names.lanes} IS '${postgresSchemaMarker(statements)}'`);
236
- return statements;
346
+ `CREATE INDEX IF NOT EXISTS ${names.indexes.completionCompleted} ON ${names.completions} (completed_at, id)`
347
+ ];
237
348
  }
238
349
  function postgresSchemaMarker(statements) {
239
- return `relaybus schema ${crypto.createHash("sha256").update(statements.join(";")).digest("hex").slice(0, 32)}`;
350
+ return `relaybus schema ${crypto.createHash("sha256").update(statements.join(";")).digest("hex").slice(0, SCHEMA_MARKER_DIGITS)}`;
240
351
  }
241
352
  function upgradeFromVersion010(names) {
242
353
  return `DO $relaybus_upgrade$
@@ -265,8 +376,6 @@ function createPostgresSchemaSql(options = {}) {
265
376
  return `${createPostgresSchemaStatements(options).join(";\n\n")};
266
377
  `;
267
378
  }
268
-
269
- // src/notification-listener.ts
270
379
  var RECONNECT_DELAY_MS = 1e3;
271
380
  var NotificationListener = class {
272
381
  #connect;
@@ -277,8 +386,8 @@ var NotificationListener = class {
277
386
  #drop;
278
387
  #reconnectTimer;
279
388
  #closed = false;
280
- constructor(connect, channel, listener, logger) {
281
- this.#connect = connect;
389
+ constructor(connect2, channel, listener, logger) {
390
+ this.#connect = connect2;
282
391
  this.#channel = channel;
283
392
  this.#listener = listener;
284
393
  this.#logger = logger;
@@ -334,30 +443,33 @@ var NotificationListener = class {
334
443
  listening = true;
335
444
  }
336
445
  #scheduleReconnect() {
337
- this.#reconnectTimer = setTimeout(() => {
338
- this.#reconnectTimer = void 0;
339
- this.start().then(
340
- () => {
341
- if (!this.#closed) {
342
- this.#listener();
446
+ this.#reconnectTimer = internal.schedule(core.systemClock, {
447
+ run: () => {
448
+ this.#reconnectTimer = void 0;
449
+ this.start().then(
450
+ () => {
451
+ if (!this.#closed) {
452
+ this.#listener();
453
+ }
454
+ },
455
+ (error) => {
456
+ this.#logger.warn(
457
+ `[NotificationListener](scheduleReconnect) Listening again failed, retrying | channel=${this.#channel} | error=${error instanceof Error ? error.message : String(error)}`
458
+ );
459
+ if (!this.#closed) {
460
+ this.#scheduleReconnect();
461
+ }
343
462
  }
344
- },
345
- (error) => {
346
- this.#logger.warn(
347
- `[NotificationListener](scheduleReconnect) Listening again failed, retrying | channel=${this.#channel} | error=${error instanceof Error ? error.message : String(error)}`
348
- );
349
- if (!this.#closed) {
350
- this.#scheduleReconnect();
351
- }
352
- }
353
- );
354
- }, RECONNECT_DELAY_MS);
355
- this.#reconnectTimer.unref();
463
+ );
464
+ },
465
+ delayMs: RECONNECT_DELAY_MS,
466
+ unref: true
467
+ });
356
468
  }
357
469
  /** Stops listening for good and ends the connection. */
358
470
  async close() {
359
471
  this.#closed = true;
360
- clearTimeout(this.#reconnectTimer);
472
+ this.#reconnectTimer?.();
361
473
  const drop = this.#drop;
362
474
  this.#drop = void 0;
363
475
  await drop?.();
@@ -391,7 +503,7 @@ function mapEventEnvelope(row) {
391
503
  occurredAt: new Date(text(row, "event_occurred_at"))
392
504
  };
393
505
  }
394
- function formatLeaseToken(lane, epoch, claims) {
506
+ function formatLeaseToken(lane, { epoch, claims }) {
395
507
  return `${lane}:${epoch}:${claims}`;
396
508
  }
397
509
  var LEASE_TOKEN_PATTERN = /^(\d{1,3}):(\d{1,18}):(\d{1,9})$/;
@@ -405,11 +517,10 @@ function parseLeaseToken(token) {
405
517
  function mapClaimedDelivery(row, leaseExpiresAt) {
406
518
  return {
407
519
  deliveryId: text(row, "delivery_id"),
408
- leaseToken: formatLeaseToken(
409
- readCount(row, "lane"),
410
- text(row, "epoch"),
411
- readCount(row, "claims")
412
- ),
520
+ leaseToken: formatLeaseToken(readCount(row, "lane"), {
521
+ epoch: text(row, "epoch"),
522
+ claims: readCount(row, "claims")
523
+ }),
413
524
  handler: text(row, "handler"),
414
525
  attempt: readCount(row, "attempt"),
415
526
  leaseExpiresAt,
@@ -437,614 +548,1140 @@ function mapOldestDueAt(rows) {
437
548
  return nullableDate(rows[0], "oldest_due_at");
438
549
  }
439
550
 
440
- // src/statements.ts
441
- var DEFAULT_LIST_LIMIT = 100;
442
- function eventColumns(alias) {
443
- return `${alias}.id AS event_id,
444
- ${alias}.type AS event_type,
445
- ${alias}.source AS event_source,
446
- ${alias}.key AS event_key,
447
- ${alias}.payload::text AS event_payload,
448
- ${alias}.headers::text AS event_headers,
449
- ${alias}.correlation_id AS event_correlation_id,
450
- ${alias}.causation_id AS event_causation_id,
451
- ${isoText(`${alias}.occurred_at`)} AS event_occurred_at`;
452
- }
453
- function countChanged(dml) {
454
- return `WITH changed AS (${dml} RETURNING 1) SELECT count(*)::int AS count FROM changed`;
455
- }
456
- var CLAIM_SCAN_WINDOW = 256;
457
- var LANE_SCAN_WINDOW = 64;
458
- var LANE_DEPTH_CAP = 16;
459
- var INITIAL_FREE_LANES = 4;
460
- var FREE_LANE_SURPLUS = 16;
461
- var HANDLER_PREDICATE = `delivery.handler = ANY (ARRAY(SELECT jsonb_array_elements_text($2::jsonb)))`;
462
- var LANE_LIST = `ARRAY(SELECT jsonb_array_elements_text($4::jsonb)::smallint)`;
463
- var PostgresStatements = class {
464
- #names;
465
- constructor(names) {
466
- this.#names = names;
551
+ // src/postgres-append.ts
552
+ var NOTIFICATION_INTERVAL_MS = 10;
553
+ var PostgresAppend = class {
554
+ #state;
555
+ constructor(state) {
556
+ this.#state = state;
467
557
  }
468
- /**
469
- * Lock advisory key text for {@link setupLock}. It is derived from the schema
470
- * name only, so stores with different table prefixes in one schema also
471
- * serialize their `CREATE SCHEMA IF NOT EXISTS`, which is not race-free.
472
- */
473
- get setupLockKey() {
474
- return `relaybus:${this.#names.schema}`;
558
+ /** Implements {@link PostgresEventStore.append}. */
559
+ async append(transaction, { entries, now }) {
560
+ const plan = planAppend(entries);
561
+ if (plan.events.length === 0) {
562
+ return { appendedEventIds: [], duplicateEventIds: [], appendedDeliveryCount: 0 };
563
+ }
564
+ const createdAt = now.toISOString();
565
+ const wakeAt = this.#wakeAt(plan.deliveries, { now, transaction });
566
+ const handlersByEvent = handlersByEventOf(plan.deliveries);
567
+ const keyCounts = keyCountsOf(plan.events);
568
+ const fresh = await this.#state.query({
569
+ sql: this.#state.statements.append.insertFreshEvents,
570
+ parameters: [
571
+ JSON.stringify(
572
+ plan.events.map((event, ordinal) => ({
573
+ ordinal,
574
+ ...toEventRow(event, { sequence: null, handlers: handlersByEvent.get(event.id) ?? [] })
575
+ }))
576
+ ),
577
+ createdAt,
578
+ JSON.stringify(plan.deliveries),
579
+ JSON.stringify([...keyCounts].map(([key, count]) => ({ key, count }))),
580
+ wakeAt
581
+ ],
582
+ transaction
583
+ });
584
+ const insertedEventIds = new Set(
585
+ fresh.filter((row) => row["inserted"] === true).map((row) => row["id"])
586
+ );
587
+ let appendedDeliveryCount = readCount(fresh[0], "deliveries");
588
+ const remaining = plan.deliveries.filter(
589
+ (delivery) => !insertedEventIds.has(delivery.event_id)
590
+ );
591
+ if (remaining.length > 0) {
592
+ appendedDeliveryCount += await this.#appendToExistingEvents(transaction, {
593
+ plan,
594
+ fresh,
595
+ deliveries: remaining,
596
+ handlersByEvent,
597
+ insertedEventIds,
598
+ createdAt,
599
+ wakeAt
600
+ });
601
+ }
602
+ return { ...splitOutcomes(plan, insertedEventIds), appendedDeliveryCount };
475
603
  }
476
604
  /**
477
- * Whether the lane table carries `marker` as its comment, that is whether the schema statements
478
- * that produce that marker already ran. Takes no table lock. Parameters: `[marker]`.
605
+ * The time the publishing statements notify the dispatchers for (deliveries due by then wake them),
606
+ * or `null` for no notification. An append in a transaction of the caller's always notifies, at its
607
+ * commit. In a transaction of this store, only the first append within {@link NOTIFICATION_INTERVAL_MS}
608
+ * does; the others leave the wake-up to {@link #wakeAfterCommit}, which runs once their transaction
609
+ * committed, so no committed delivery waits for the poll.
479
610
  */
480
- get schemaCurrent() {
481
- return `SELECT EXISTS (
482
- SELECT 1 FROM pg_catalog.pg_class AS c
483
- JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace
484
- JOIN pg_catalog.pg_description AS d
485
- ON d.objoid = c.oid AND d.classoid = 'pg_catalog.pg_class'::regclass AND d.objsubid = 0
486
- WHERE n.nspname = '${this.#names.schema}' AND c.relname = '${this.#names.lanesTableName}' AND d.description = $1::text
487
- ) AS current`;
488
- }
489
- get setupLock() {
490
- return "SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))";
611
+ #wakeAt(deliveries, { now, transaction }) {
612
+ if (!this.#state.notifies || !deliveries.some((delivery) => Date.parse(delivery.available_at) <= now.getTime())) {
613
+ return null;
614
+ }
615
+ const own = this.#state.ownTransactions.get(transaction);
616
+ if (own !== void 0 && Date.now() - this.#state.lastNotificationAt < NOTIFICATION_INTERVAL_MS) {
617
+ own.wake = true;
618
+ return null;
619
+ }
620
+ this.#state.lastNotificationAt = Date.now();
621
+ return now.toISOString();
491
622
  }
492
623
  /**
493
- * Publishes in one statement: reserves the sequences of the keys (`[{ key, count }]` in `$4`, locked in
494
- * key order: each row lock is held until the publishing transaction ends, which makes sequence order equal commit order for a key), numbers the keyed events in entry order (`ordinal`), inserts
495
- * the events of `$1` that do not exist yet and the deliveries of `$3` that belong to them, and sends one
496
- * wake-up notification when a delivery it inserted is due at `$5`. Parameters:
497
- * `[eventsJson, createdAt, deliveriesJson, keyCountsJson, now]`. Returns one row per event of `$1`: its
498
- * id, its sequence, whether this statement inserted it, and (on every row) how many deliveries it
499
- * inserted. Deliveries of events that already existed are left to {@link insertDeliveries}.
624
+ * Wakes the dispatchers for a committed transaction whose appends sent no notification: at once when
625
+ * none was sent within {@link NOTIFICATION_INTERVAL_MS}, otherwise once when the interval ends. A
626
+ * wake-up already scheduled covers this transaction too, since it is sent after this commit. Nothing is
627
+ * sent once the store is closed or the `pg` pool behind it is ending: no dispatcher can be woken through
628
+ * it then, and the deliveries are found by polling.
500
629
  */
501
- get insertFreshEvents() {
502
- const events = this.#names.events;
503
- return `WITH reserved AS (
504
- INSERT INTO ${this.#names.keySequences} AS reserved (key, sequence)
505
- SELECT requested.key, requested.count
506
- FROM jsonb_to_recordset($4::jsonb) AS requested (key text, count bigint)
507
- ORDER BY requested.key
508
- ON CONFLICT (key) DO UPDATE SET sequence = reserved.sequence + EXCLUDED.sequence
509
- RETURNING reserved.key AS key, reserved.sequence AS sequence
510
- ), incoming AS (
511
- SELECT incoming.*,
512
- CASE WHEN incoming.key IS NULL THEN NULL ELSE
513
- reserved.sequence - count(*) OVER (PARTITION BY incoming.key)
514
- + row_number() OVER (PARTITION BY incoming.key ORDER BY incoming.ordinal)
515
- END AS sequence
516
- FROM jsonb_to_recordset($1::jsonb) AS incoming (
517
- ordinal int, id text, type text, source text, key text, payload jsonb, headers jsonb,
518
- correlation_id text, causation_id text, occurred_at timestamptz, handlers text[])
519
- LEFT JOIN reserved ON reserved.key = incoming.key
520
- ), inserted_events AS (
521
- INSERT INTO ${events}
522
- (id, type, source, key, sequence, payload, headers, correlation_id, causation_id, occurred_at, created_at, handlers)
523
- SELECT incoming.id, incoming.type, incoming.source, incoming.key, incoming.sequence,
524
- COALESCE(incoming.payload, 'null'::jsonb), COALESCE(incoming.headers, '{}'::jsonb),
525
- incoming.correlation_id, incoming.causation_id, incoming.occurred_at, $2::timestamptz,
526
- COALESCE(incoming.handlers, '{}')
527
- FROM incoming
528
- ORDER BY incoming.id
529
- ON CONFLICT (id) DO NOTHING
530
- RETURNING id, key, sequence
531
- ), inserted_deliveries AS (
532
- INSERT INTO ${this.#names.deliveries}
533
- (id, event_id, handler, lane, status, attempts, available_at, key, sequence, created_at, updated_at)
534
- SELECT delivery.id, delivery.event_id, delivery.handler, ${laneExpression("event.key", "event.id")}, 'pending', 0,
535
- delivery.available_at, event.key, event.sequence, $2::timestamptz, $2::timestamptz
536
- FROM jsonb_to_recordset($3::jsonb) AS delivery (id text, event_id text, handler text, available_at timestamptz)
537
- JOIN inserted_events AS event ON event.id = delivery.event_id
538
- ORDER BY delivery.event_id, delivery.handler
539
- ON CONFLICT (event_id, handler) DO NOTHING
540
- RETURNING available_at
541
- ), ${this.#wakeUp("inserted_deliveries", "$5")}
542
- SELECT incoming.id, incoming.sequence::text AS sequence,
543
- incoming.id IN (SELECT inserted_events.id FROM inserted_events) AS inserted,
544
- (SELECT count(*) FROM inserted_deliveries)::int AS deliveries
545
- FROM incoming
546
- WHERE (SELECT count(*) FROM woken) >= 0`;
547
- }
548
- /** One wake-up notification on {@link PostgresNames.notificationChannel}, outside any publishing transaction. */
549
- get notify() {
550
- return `SELECT pg_notify('${this.#names.notificationChannel}', '')`;
630
+ wakeAfterCommit() {
631
+ if (this.#state.trailingNotification !== void 0 || this.#state.closed) {
632
+ return;
633
+ }
634
+ this.#state.trailingNotification = internal.schedule(core.systemClock, {
635
+ run: () => {
636
+ this.#state.trailingNotification = void 0;
637
+ if (this.#state.pool?.ending === true) {
638
+ return;
639
+ }
640
+ this.#state.lastNotificationAt = Date.now();
641
+ this.#state.query({ sql: this.#state.statements.append.notify, parameters: [] }).catch((error) => {
642
+ this.#state.logger.error(
643
+ `[PostgresAppend](wakeAfterCommit) Waking the dispatchers failed, they find the deliveries when they poll | error=${error instanceof Error ? error.message : String(error)}`
644
+ );
645
+ });
646
+ },
647
+ delayMs: Math.max(0, this.#state.lastNotificationAt + NOTIFICATION_INTERVAL_MS - Date.now())
648
+ });
551
649
  }
552
650
  /**
553
- * A CTE `woken` that sends one notification on {@link PostgresNames.notificationChannel} when a row of
554
- * `inserted` is due at `now`. PostgreSQL delivers it when the transaction commits, merges the same
555
- * notification sent twice in one transaction, and drops it on rollback. The statement must reference
556
- * `woken` for it to run.
651
+ * Adds the deliveries of events the publishing statement found already stored. An event that already
652
+ * exists may be getting the same new handler from another transaction at this very moment. Whoever
653
+ * holds the event decides, so the freshness check of the insert sees what the other transaction
654
+ * committed, even if its delivery has completed since. An existing event that a purge removed
655
+ * meanwhile is inserted again (with the sequence reserved for it) instead of being skipped; its id is
656
+ * added to `insertedEventIds`. Returns how many deliveries were inserted.
557
657
  */
558
- #wakeUp(inserted, now) {
559
- return `woken AS (
560
- SELECT pg_notify('${this.#names.notificationChannel}', '') FROM (
561
- SELECT 1 FROM ${inserted} WHERE ${inserted}.available_at <= ${now}::timestamptz LIMIT 1
562
- ) AS due
563
- )`;
658
+ async #appendToExistingEvents(transaction, input) {
659
+ const { plan, fresh, deliveries, handlersByEvent, insertedEventIds, createdAt, wakeAt } = input;
660
+ const sequences = new Map(
661
+ fresh.map((row) => [row["id"], row["sequence"]])
662
+ );
663
+ const reinserted = [];
664
+ let existing = plan.events.filter((event) => !insertedEventIds.has(event.id)).map(
665
+ (event) => toEventRow(event, {
666
+ sequence: sequences.get(event.id),
667
+ handlers: handlersByEvent.get(event.id) ?? []
668
+ })
669
+ );
670
+ while (existing.length > 0) {
671
+ const locked = new Set(
672
+ (await this.#state.query({
673
+ sql: this.#state.statements.append.lockExistingEvents,
674
+ parameters: [JSON.stringify(existing.map((row) => row.id).sort())],
675
+ transaction
676
+ })).map((row) => row["id"])
677
+ );
678
+ const gone = existing.filter((row) => !locked.has(row.id));
679
+ if (gone.length > 0) {
680
+ const inserted2 = await this.#state.query({
681
+ sql: this.#state.statements.append.insertEvents,
682
+ parameters: [JSON.stringify(gone), createdAt],
683
+ transaction
684
+ });
685
+ for (const row of inserted2) {
686
+ insertedEventIds.add(row["id"]);
687
+ reinserted.push(row["id"]);
688
+ }
689
+ }
690
+ existing = gone.filter((row) => !insertedEventIds.has(row.id));
691
+ }
692
+ const inserted = await this.#state.query({
693
+ sql: this.#state.statements.append.insertDeliveries,
694
+ parameters: [JSON.stringify(deliveries), createdAt, JSON.stringify(reinserted), wakeAt],
695
+ transaction
696
+ });
697
+ return inserted.length;
564
698
  }
565
- /**
566
- * Parameters: `[eventsJson, createdAt]`. Returns the ids that were inserted.
567
- * `handlers` is the list of handlers the event gets deliveries for: it
568
- * outlives the deliveries, which are deleted when they complete.
569
- */
570
- get insertEvents() {
571
- return `INSERT INTO ${this.#names.events}
572
- (id, type, source, key, sequence, payload, headers, correlation_id, causation_id, occurred_at, created_at, handlers)
573
- SELECT incoming.id, incoming.type, incoming.source, incoming.key, incoming.sequence,
574
- COALESCE(incoming.payload, 'null'::jsonb), COALESCE(incoming.headers, '{}'::jsonb),
575
- incoming.correlation_id, incoming.causation_id, incoming.occurred_at, $2::timestamptz,
576
- COALESCE(incoming.handlers, '{}')
577
- FROM jsonb_to_recordset($1::jsonb) AS incoming (
578
- id text, type text, source text, key text, sequence bigint, payload jsonb, headers jsonb,
579
- correlation_id text, causation_id text, occurred_at timestamptz, handlers text[])
580
- ORDER BY incoming.id
581
- ON CONFLICT (id) DO NOTHING
582
- RETURNING id`;
699
+ };
700
+ function planAppend(entries) {
701
+ const events = [];
702
+ const deliveries = [];
703
+ const outcomes = [];
704
+ const seenEventIds = /* @__PURE__ */ new Set();
705
+ const seenDeliveries = /* @__PURE__ */ new Set();
706
+ for (const { event, deliveries: newDeliveries } of entries) {
707
+ const repeated = seenEventIds.has(event.id);
708
+ seenEventIds.add(event.id);
709
+ outcomes.push({ eventId: event.id, repeated });
710
+ if (!repeated) {
711
+ events.push(event);
712
+ }
713
+ for (const delivery of newDeliveries) {
714
+ const identity = `${event.id}\0${delivery.handler}`;
715
+ if (!seenDeliveries.has(identity)) {
716
+ seenDeliveries.add(identity);
717
+ deliveries.push({
718
+ id: delivery.id,
719
+ event_id: event.id,
720
+ handler: delivery.handler,
721
+ available_at: delivery.availableAt.toISOString()
722
+ });
723
+ }
724
+ }
725
+ }
726
+ return { events, deliveries, outcomes };
727
+ }
728
+ function toEventRow(event, {
729
+ sequence,
730
+ handlers
731
+ }) {
732
+ return {
733
+ id: event.id,
734
+ type: event.type,
735
+ source: event.source,
736
+ key: event.key,
737
+ sequence,
738
+ payload: event.payload,
739
+ headers: event.headers,
740
+ correlation_id: event.correlationId,
741
+ causation_id: event.causationId,
742
+ occurred_at: event.occurredAt.toISOString(),
743
+ handlers
744
+ };
745
+ }
746
+ function handlersByEventOf(deliveries) {
747
+ const handlersByEvent = /* @__PURE__ */ new Map();
748
+ for (const delivery of deliveries) {
749
+ handlersByEvent.set(delivery.event_id, [
750
+ ...handlersByEvent.get(delivery.event_id) ?? [],
751
+ delivery.handler
752
+ ]);
753
+ }
754
+ return handlersByEvent;
755
+ }
756
+ function keyCountsOf(events) {
757
+ const keyCounts = /* @__PURE__ */ new Map();
758
+ for (const event of events) {
759
+ if (event.key !== null) {
760
+ keyCounts.set(event.key, (keyCounts.get(event.key) ?? 0) + 1);
761
+ }
762
+ }
763
+ return keyCounts;
764
+ }
765
+ function splitOutcomes(plan, insertedEventIds) {
766
+ const appendedEventIds = [];
767
+ const duplicateEventIds = [];
768
+ for (const { eventId, repeated } of plan.outcomes) {
769
+ (!repeated && insertedEventIds.has(eventId) ? appendedEventIds : duplicateEventIds).push(
770
+ eventId
771
+ );
772
+ }
773
+ return { appendedEventIds, duplicateEventIds };
774
+ }
775
+ var ReconcileFailedError = class extends core.RelayBusError {
776
+ name = "ReconcileFailedError";
777
+ code = "RELAYBUS_POSTGRES_RECONCILE_FAILED";
778
+ };
779
+
780
+ // src/postgres-store-state.ts
781
+ function handedOutKey(deliveryId, leaseToken) {
782
+ return `${deliveryId}\0${leaseToken}`;
783
+ }
784
+
785
+ // src/postgres-claim.ts
786
+ var INITIAL_LANES_PER_ROUND = 4;
787
+ var MAXIMUM_STALE_CLAIM_ATTEMPTS = 3;
788
+ var PostgresClaims = class {
789
+ #state;
790
+ constructor(state) {
791
+ this.#state = state;
792
+ }
793
+ /** Implements {@link PostgresEventStore.claim}. */
794
+ claim(request) {
795
+ if (request.handlers.length === 0 || !(request.limit > 0)) {
796
+ return Promise.resolve([]);
797
+ }
798
+ return this.#serialized(request.leaseOwner, () => this.#claim(request));
583
799
  }
584
800
  /**
585
- * Locks events that were not inserted by the current append, in id order, so
586
- * that appends adding handlers to the same event run one after the other.
587
- * Parameters: `[eventIdsJson]`. `FOR NO KEY UPDATE` conflicts with itself and
588
- * not with the foreign key checks of other inserts.
801
+ * Runs `work` after the earlier claims of the same owner on this store settled. The
802
+ * bookkeeping of what was handed out and the reconciliation of a failed claim need
803
+ * one claim at a time per owner (the dispatcher claims one batch at a time anyway;
804
+ * `runOnce` next to a running dispatcher is what this guards against).
589
805
  */
590
- get lockExistingEvents() {
591
- return `SELECT id FROM ${this.#names.events}
592
- WHERE id = ANY (ARRAY(SELECT jsonb_array_elements_text($1::jsonb)))
593
- ORDER BY id
594
- FOR NO KEY UPDATE`;
806
+ #serialized(owner, work) {
807
+ const previous = this.#state.ownerQueues.get(owner) ?? Promise.resolve();
808
+ const run = previous.then(work, work);
809
+ const tail = run.then(
810
+ () => void 0,
811
+ () => void 0
812
+ );
813
+ this.#state.ownerQueues.set(owner, tail);
814
+ void tail.then(() => {
815
+ if (this.#state.ownerQueues.get(owner) === tail) {
816
+ this.#state.ownerQueues.delete(owner);
817
+ }
818
+ });
819
+ return run;
820
+ }
821
+ async #claim(request) {
822
+ await this.#assertReconciled(request.leaseOwner);
823
+ const heldFirst = this.#state.drainingOwners.has(request.leaseOwner);
824
+ let rows = await this.#claimFirst(request, heldFirst);
825
+ const heldLanes = new Set(JSON.parse(rows[0]["examined_lanes"]));
826
+ const claimed = this.#takeClaimed(rows, request.leaseOwner);
827
+ if (heldFirst && claimed.length < request.limit && rows[0]["stale"] !== true) {
828
+ const freeRows = await this.#claimFreeLanesAfterHeld(request, claimed);
829
+ if (freeRows === void 0) {
830
+ return this.#handOutInDueOrder(claimed, { request, heldLanes });
831
+ }
832
+ rows = freeRows;
833
+ }
834
+ if (claimed.length < request.limit && leftWorkBehind(rows[0])) {
835
+ await this.#claimMoreLanes(request, claimed);
836
+ }
837
+ return this.#handOutInDueOrder(claimed, { request, heldLanes });
838
+ }
839
+ /** Reconciles first when an earlier reconciliation of `owner` failed; refuses to claim while it still fails. */
840
+ async #assertReconciled(owner) {
841
+ if (this.#state.unreconciled.has(owner) && !await this.#reconcile(owner)) {
842
+ throw new ReconcileFailedError(
843
+ `[PostgresEventStore](claim) Giving back unreturned deliveries still fails, so no claim is made | owner=${owner}`
844
+ );
845
+ }
846
+ }
847
+ /** The first claim statement: from the held lanes only when `heldFirst`, else from held and free lanes. */
848
+ async #claimFirst(request, heldFirst) {
849
+ try {
850
+ return await this.#claimInOneStatement(
851
+ request,
852
+ heldFirst ? this.#state.statements.lanes.claimHeldLanes : this.#state.statements.lanes.claimLanes
853
+ );
854
+ } catch (error) {
855
+ await this.#reconcile(request.leaseOwner);
856
+ throw error;
857
+ }
595
858
  }
596
859
  /**
597
- * Parameters: `[deliveriesJson, createdAt, insertedEventIdsJson, now]`. Key and
598
- * sequence are copied from the stored event, so a delivery added later to an
599
- * existing event keeps the event's position in its key and lands in the same
600
- * lane. Returns the ids that were inserted.
601
- *
602
- * The deliveries of events this call just inserted are all new. For an event
603
- * that already existed, a handler gets a delivery only if the event does not
604
- * list it yet: a completed delivery is deleted, but its handler stays listed,
605
- * so a redelivered or republished event never runs a handler twice. The
606
- * handlers added to an existing event are appended to its list.
860
+ * After a held-lanes claim came up short: claims the rest from held and free lanes and adds it to
861
+ * `claimed`. Returns the statement's rows, or undefined when it failed after something was claimed
862
+ * already, which is then handed out as it is.
607
863
  */
608
- get insertDeliveries() {
609
- const events = this.#names.events;
610
- const insertedEvents = `ARRAY(SELECT jsonb_array_elements_text($3::jsonb))`;
611
- return `WITH incoming AS (
612
- SELECT incoming.id, incoming.event_id, incoming.handler, incoming.available_at
613
- FROM jsonb_to_recordset($1::jsonb) AS incoming (id text, event_id text, handler text, available_at timestamptz)
614
- ), fresh AS (
615
- SELECT incoming.*, event.key, event.sequence, ${laneExpression("event.key", "event.id")} AS lane
616
- FROM incoming
617
- JOIN ${events} AS event ON event.id = incoming.event_id
618
- WHERE event.id = ANY (${insertedEvents}) OR NOT incoming.handler = ANY (event.handlers)
619
- ), inserted AS (
620
- INSERT INTO ${this.#names.deliveries}
621
- (id, event_id, handler, lane, status, attempts, available_at, key, sequence, created_at, updated_at)
622
- SELECT fresh.id, fresh.event_id, fresh.handler, fresh.lane, 'pending', 0, fresh.available_at,
623
- fresh.key, fresh.sequence, $2::timestamptz, $2::timestamptz
624
- FROM fresh
625
- ORDER BY fresh.event_id, fresh.handler
626
- ON CONFLICT (event_id, handler) DO NOTHING
627
- RETURNING id, event_id, handler, available_at
628
- ), extended AS (
629
- UPDATE ${events} AS event SET handlers = event.handlers || added.handlers
630
- FROM (
631
- SELECT inserted.event_id, array_agg(inserted.handler) AS handlers FROM inserted
632
- WHERE inserted.event_id <> ALL (${insertedEvents}) GROUP BY inserted.event_id
633
- ) AS added
634
- WHERE event.id = added.event_id
635
- RETURNING event.id
636
- ), ${this.#wakeUp("inserted", "$4")}
637
- SELECT id FROM inserted WHERE (SELECT count(*) FROM woken) >= 0`;
864
+ async #claimFreeLanesAfterHeld(request, claimed) {
865
+ let rows;
866
+ try {
867
+ rows = await this.#claimInOneStatement(
868
+ { ...request, limit: request.limit - claimed.length },
869
+ this.#state.statements.lanes.claimLanes
870
+ );
871
+ } catch (error) {
872
+ await this.#reconcile(request.leaseOwner);
873
+ if (claimed.length === 0) {
874
+ this.#state.drainingOwners.delete(request.leaseOwner);
875
+ throw error;
876
+ }
877
+ this.#state.logger.error(
878
+ `[PostgresClaims](claimFreeLanesAfterHeld) Claiming from free lanes failed, returning the deliveries already claimed | claimed=${claimed.length} | error=${error instanceof Error ? error.message : String(error)}`
879
+ );
880
+ return void 0;
881
+ }
882
+ claimed.push(...this.#takeClaimed(rows, request.leaseOwner));
883
+ return rows;
884
+ }
885
+ /** Takes more lanes round by round and adds what they give to `claimed`; keeps what was claimed when that fails. */
886
+ async #claimMoreLanes(request, claimed) {
887
+ try {
888
+ const more = await this.#claimMore(request, claimed.length);
889
+ this.#handOut(more, request.leaseOwner);
890
+ claimed.push(...more);
891
+ } catch (error) {
892
+ await this.#reconcile(request.leaseOwner);
893
+ if (claimed.length === 0) {
894
+ throw error;
895
+ }
896
+ this.#state.logger.error(
897
+ `[PostgresClaims](claimMoreLanes) Taking more lanes failed, returning the deliveries already claimed | claimed=${claimed.length} | error=${error instanceof Error ? error.message : String(error)}`
898
+ );
899
+ }
900
+ }
901
+ /** The deliveries a claim statement picked, registered as handed out to `leaseOwner`. */
902
+ #takeClaimed(rows, leaseOwner) {
903
+ const claimed = rows.filter((row) => row["delivery_id"] !== null);
904
+ this.#forgetFinished(rows[0], { leaseOwner, claimed });
905
+ this.#handOut(claimed, leaseOwner);
906
+ return claimed;
907
+ }
908
+ #handOutInDueOrder(claimed, {
909
+ request,
910
+ heldLanes
911
+ }) {
912
+ if (claimed.length >= request.limit && claimed.every((row) => heldLanes.has(readCount(row, "lane")))) {
913
+ this.#state.drainingOwners.add(request.leaseOwner);
914
+ } else {
915
+ this.#state.drainingOwners.delete(request.leaseOwner);
916
+ }
917
+ claimed.sort(compareDue);
918
+ return claimed.map((row) => mapClaimedDelivery(row, request.leaseExpiresAt));
638
919
  }
639
920
  /**
640
- * A claim in one statement, the only one in the common case. Parameters:
641
- * `[now, handlersJson, limit, leaseOwner, leaseExpiresAt, generation]`.
642
- *
643
- * 1. **Held lanes.** The lanes this owner holds under a live lease whose `claim_floor` is exactly the
644
- * generation are locked `FOR NO KEY UPDATE` in lane order. A lane above it was raised by a
645
- * reconciliation, so a statement of a claim whose caller gave up (a client timeout does not cancel
646
- * the statement on the server) and that reaches the server late records nothing; a lane below it was
647
- * taken by such a late statement after the reconciliation, and its listed deliveries were never
648
- * handed out. A lane that another transaction of this owner is changing makes the statement wait;
649
- * the statement then reports `stale` and does nothing (see the `stale` CTE).
650
- * 2. **Free lanes**, only when the held lanes yield fewer than `limit`: the free lanes with a due
651
- * delivery (one index probe per free lane) are ranked by their oldest due delivery; the first
652
- * {@link INITIAL_FREE_LANES} that can give something now, and further ones until what they can give
653
- * (estimated from their first {@link LANE_DEPTH_CAP} due deliveries) covers what is still wanted, are locked
654
- * `FOR UPDATE SKIP LOCKED`, so a lane another claimer has is skipped, never waited
655
- * for. A lane that still runs deliveries of an expired lease is left to the transaction of
656
- * {@link takeFreeLanes}, which charges their lost attempts (`takeover_waiting`); so is any lane whose
657
- * locked row differs from what the statement's snapshot saw. A lane that runs nothing and did not
658
- * change cannot have had a delivery written since the snapshot, so its deliveries can be read here.
659
- * 3. **Picks** follow the rules of {@link claim}: the fast window of each lane, and for lanes whose
660
- * window filled up while the batch is not full, the heads of all keys (a loose index scan per lane).
661
- * 4. **Writes**: one update per lane. A held lane records its picks; a taken lane gets a new epoch, the
662
- * owner, the lease and its picks; a taken lane that yielded nothing is not written. Held lanes that
663
- * picked nothing, run nothing and have no full scan window are freed.
664
- *
665
- * Always returns one row per picked delivery, or one row whose `delivery_id` is null. `running_ids`
666
- * (JSON text) lists the deliveries the held lanes still run, `examined_lanes` the held lanes.
921
+ * Runs `statement` (`LaneStatements.claimLanes` or its held-lane form), again when it reports that it waited for a lane lock and
922
+ * read deliveries with an older snapshot than the lane it got. A held lane is only locked by an
923
+ * operation of its own owner (another claim, a reschedule), so a few attempts are enough.
667
924
  */
668
- get claimLanes() {
669
- return this.#claimLanes(true);
925
+ async #claimInOneStatement(request, statement) {
926
+ const parameters = [
927
+ request.now.toISOString(),
928
+ JSON.stringify(request.handlers),
929
+ request.limit,
930
+ request.leaseOwner,
931
+ request.leaseExpiresAt.toISOString(),
932
+ this.#generation(request.leaseOwner).toString()
933
+ ];
934
+ let rows = await this.#state.query({ sql: statement, parameters });
935
+ for (let attempt = 1; attempt < MAXIMUM_STALE_CLAIM_ATTEMPTS && rows[0]["stale"] === true; attempt += 1) {
936
+ rows = await this.#state.query({ sql: statement, parameters });
937
+ }
938
+ return rows;
670
939
  }
671
940
  /**
672
- * {@link claimLanes} limited to the lanes the owner holds: the same parameters, rows and writes, without
673
- * looking at free lanes (`takeover_waiting` and `unexamined_free_lanes` are false). A worker draining a
674
- * backlog finds its batch in the lanes it holds; this statement is about half as costly to plan, and
675
- * the caller runs {@link claimLanes} after it only when it came up short.
941
+ * Second step of {@link PostgresEventStore.claim}, in one transaction: takes free lanes a few at a
942
+ * time, lanes to take over included (their lost attempts are charged first), and records the batch.
943
+ * `alreadyClaimed` deliveries of the first step are in flight, so they are not picked again.
676
944
  */
677
- get claimHeldLanes() {
678
- return this.#claimLanes(false);
679
- }
680
- #claimLanes(includeFreeLanes) {
681
- const deliveries = this.#names.deliveries;
682
- const lanes = this.#names.lanes;
683
- const freeLane = (alias) => `(${alias}.lease_expires_at IS NULL OR ${alias}.lease_expires_at <= $1::timestamptz
684
- OR (${alias}.lease_owner = $4::text AND ${alias}.claim_floor < $6::bigint))`;
685
- const free = includeFreeLanes ? `), free_lanes AS MATERIALIZED (
686
- -- The oldest due delivery of each free lane: one index probe per free lane, bounded by the due time,
687
- -- so deliveries scheduled for later are never read.
688
- SELECT lane.lane, lane.epoch, lane.in_flight, lane.lease_owner, lane.lease_expires_at,
689
- oldest.available_at, oldest.id, NOT ${this.#noRunningDelivery("lane")} AS running
690
- FROM ${lanes} AS lane
691
- CROSS JOIN LATERAL (
692
- SELECT delivery.available_at, delivery.id
693
- FROM ${deliveries} AS delivery
694
- WHERE delivery.lane = lane.lane AND delivery.status = 'pending'
695
- AND delivery.available_at <= $1::timestamptz AND ${HANDLER_PREDICATE}
696
- ORDER BY delivery.available_at, delivery.id
697
- LIMIT 1
698
- ) AS oldest
699
- WHERE (SELECT count FROM wanted) > 0 AND ${freeLane("lane")}
700
- ORDER BY oldest.available_at, oldest.id
701
- LIMIT (SELECT count FROM wanted) + ${FREE_LANE_SURPLUS}
702
- ), free_depth AS MATERIALIZED (
703
- -- What each candidate lane can give now, from its first due deliveries: unkeyed ones, and of a key its
704
- -- lowest one when nothing earlier of the key is pending. Lanes that can give nothing are passed over;
705
- -- of the others, the first ${INITIAL_FREE_LANES} are taken, and further ones until they cover what is
706
- -- still wanted, so the earliest due work of the free lanes comes first.
707
- SELECT runnable.lane,
708
- row_number() OVER (ORDER BY runnable.available_at, runnable.id) AS rank,
709
- sum(runnable.count) OVER (ORDER BY runnable.available_at, runnable.id ROWS UNBOUNDED PRECEDING) - runnable.count AS due_before
710
- FROM (
711
- SELECT lane_candidate.lane, lane_candidate.available_at, lane_candidate.id, depth.count
712
- FROM free_lanes AS lane_candidate
713
- CROSS JOIN LATERAL (
714
- -- A full window that shows nothing runnable may hide runnable work behind it: such a lane counts
715
- -- once, and the claim looks behind its blocked deliveries.
716
- SELECT GREATEST(count(*) FILTER (
717
- WHERE due.key IS NULL OR (due.position = 1 AND NOT EXISTS (
718
- SELECT 1 FROM ${deliveries} AS earlier
719
- WHERE earlier.lane = due.lane AND earlier.handler = due.handler AND earlier.key = due.key
720
- AND earlier.status = 'pending' AND earlier.key IS NOT NULL AND earlier.sequence < due.sequence
721
- ))
722
- ), CASE WHEN count(*) >= ${LANE_DEPTH_CAP} THEN 1 ELSE 0 END) AS count
723
- FROM (
724
- SELECT window_rows.*,
725
- row_number() OVER (PARTITION BY window_rows.handler, window_rows.key ORDER BY window_rows.sequence) AS position
726
- FROM (
727
- SELECT delivery.lane, delivery.handler, delivery.key, delivery.sequence FROM ${deliveries} AS delivery
728
- WHERE delivery.lane = lane_candidate.lane AND delivery.status = 'pending'
729
- AND delivery.available_at <= $1::timestamptz AND ${HANDLER_PREDICATE}
730
- ORDER BY delivery.available_at, delivery.id
731
- LIMIT ${LANE_DEPTH_CAP}
732
- ) AS window_rows
733
- ) AS due
734
- ) AS depth
735
- WHERE NOT lane_candidate.running AND depth.count > 0
736
- ) AS runnable
737
- ), free_locked AS MATERIALIZED (
738
- SELECT lane.lane, lane.epoch, lane.in_flight, lane.lease_owner, lane.lease_expires_at
739
- FROM ${lanes} AS lane
740
- WHERE lane.lane IN (
741
- SELECT chosen.lane FROM free_depth AS chosen
742
- WHERE chosen.rank <= ${INITIAL_FREE_LANES} OR chosen.due_before < (SELECT count FROM wanted)
743
- )
744
- AND ${freeLane("lane")}
745
- ORDER BY lane.lane
746
- FOR UPDATE SKIP LOCKED
747
- ), free_scope AS MATERIALIZED (
748
- -- A lane whose locked row is not the one the snapshot saw changed hands meanwhile: left for a later claim.
749
- SELECT locked.lane, locked.epoch + 1 AS epoch, '{}'::text[] AS in_flight
750
- FROM free_locked AS locked
751
- JOIN free_lanes AS seen ON seen.lane = locked.lane
752
- WHERE locked.epoch = seen.epoch AND locked.in_flight = seen.in_flight
753
- AND locked.lease_owner IS NOT DISTINCT FROM seen.lease_owner
754
- AND locked.lease_expires_at IS NOT DISTINCT FROM seen.lease_expires_at
755
- ), ${this.#candidates("free", "free_scope", null, "(SELECT count FROM wanted)")}` : `), free_lanes AS (
756
- SELECT NULL::smallint AS lane, NULL::bigint AS epoch, NULL::text[] AS in_flight, false AS running WHERE false
757
- ), free_scope AS (
758
- SELECT NULL::smallint AS lane, NULL::bigint AS epoch WHERE false
759
- ), free_candidates AS (
760
- SELECT NULL::text AS id, NULL::smallint AS lane, NULL::timestamptz AS available_at WHERE false
761
- )`;
762
- return `WITH held AS MATERIALIZED (
763
- SELECT lane.lane, lane.epoch, lane.in_flight
764
- FROM ${lanes} AS lane
765
- WHERE lane.lease_owner = $4::text AND lane.lease_expires_at > $1::timestamptz
766
- AND lane.claim_floor = $6::bigint
767
- ORDER BY lane.lane
768
- FOR NO KEY UPDATE
769
- ), stale AS (
770
- -- A claim that waited for a lane lock sees the new lane row but reads deliveries with the snapshot it took
771
- -- before the wait: whatever changed the lane meanwhile (a reschedule, a release) may also have changed
772
- -- deliveries it cannot see. The statement then does nothing and reports it, and the caller runs it again.
773
- SELECT EXISTS (
774
- SELECT 1 FROM held
775
- JOIN ${lanes} AS before ON before.lane = held.lane
776
- WHERE before.epoch <> held.epoch OR before.in_flight IS DISTINCT FROM held.in_flight
777
- ) AS value
778
- ), held_scope AS MATERIALIZED (
779
- SELECT held.lane, held.epoch, held.in_flight FROM held WHERE NOT (SELECT value FROM stale)
780
- ), held_running AS MATERIALIZED (
781
- SELECT delivery.handler, delivery.key
782
- FROM held_scope
783
- CROSS JOIN LATERAL unnest(held_scope.in_flight) AS flying (id)
784
- JOIN ${deliveries} AS delivery ON delivery.id = flying.id
785
- WHERE delivery.status = 'pending' AND delivery.key IS NOT NULL
786
- ), ${this.#candidates("held", "held_scope", "held_running", "$3::int")}, wanted AS MATERIALIZED (
787
- SELECT CASE WHEN (SELECT value FROM stale) THEN 0
788
- ELSE $3::int - (SELECT count(*) FROM held_candidates)::int END AS count
789
- ${free}, claim_scope AS MATERIALIZED (
790
- SELECT held_scope.lane, held_scope.epoch FROM held_scope
791
- UNION ALL
792
- SELECT free_scope.lane, free_scope.epoch FROM free_scope
793
- ), picked_rows AS MATERIALIZED (
794
- SELECT candidates.available_at AS due_at, delivery.id AS delivery_id, delivery.lane::int AS lane,
795
- scope.epoch::text AS epoch, delivery.claims AS claims, delivery.handler, delivery.key AS delivery_key, delivery.sequence::text AS sequence, (delivery.attempts + 1)::int AS attempt,
796
- ${eventColumns("event")}
797
- FROM (
798
- SELECT held_candidates.id, held_candidates.lane, held_candidates.available_at FROM held_candidates
799
- UNION ALL
800
- SELECT free_candidates.id, free_candidates.lane, free_candidates.available_at FROM free_candidates
801
- ) AS candidates
802
- JOIN claim_scope AS scope ON scope.lane = candidates.lane
803
- JOIN ${deliveries} AS delivery ON delivery.id = candidates.id
804
- JOIN ${this.#names.events} AS event ON event.id = delivery.event_id
805
- ), by_lane AS (
806
- SELECT picked_rows.lane, array_agg(picked_rows.delivery_id) AS ids FROM picked_rows GROUP BY picked_rows.lane
807
- ), still_running AS (
808
- -- The retained ids come from the locked \`held\` rows, not from the lane table: a claim that waited for the lock
809
- -- must see the in-flight list the claim before it recorded, which the statement snapshot may not.
810
- SELECT held.lane, array_agg(delivery.id) AS ids
811
- FROM by_lane
812
- JOIN held ON held.lane = by_lane.lane
813
- CROSS JOIN LATERAL unnest(held.in_flight) AS flying (id)
814
- JOIN ${deliveries} AS delivery ON delivery.id = flying.id AND delivery.status = 'pending'
815
- GROUP BY held.lane
816
- ), extended AS (
817
- UPDATE ${lanes} AS lane
818
- SET in_flight = COALESCE(still_running.ids, '{}') || by_lane.ids,
819
- lease_expires_at = GREATEST(lane.lease_expires_at, $5::timestamptz)
820
- FROM by_lane
821
- JOIN held_scope ON held_scope.lane = by_lane.lane
822
- LEFT JOIN still_running ON still_running.lane = by_lane.lane
823
- WHERE lane.lane = by_lane.lane
824
- RETURNING lane.lane
825
- ), taken AS (
826
- UPDATE ${lanes} AS lane
827
- SET epoch = free_scope.epoch, lease_owner = $4::text, lease_expires_at = $5::timestamptz,
828
- in_flight = by_lane.ids, claim_floor = $6::bigint
829
- FROM free_scope
830
- JOIN by_lane ON by_lane.lane = free_scope.lane
831
- WHERE lane.lane = free_scope.lane
832
- RETURNING lane.lane
833
- ), saturated_lanes AS (
834
- SELECT held_window.lane FROM held_window GROUP BY held_window.lane HAVING count(*) >= ${LANE_SCAN_WINDOW}
835
- ), freed AS (
836
- UPDATE ${lanes} AS lane
837
- SET lease_owner = NULL, lease_expires_at = NULL, in_flight = '{}'
838
- FROM held
839
- WHERE lane.lane = held.lane
840
- AND lane.lane NOT IN (SELECT lane FROM by_lane)
841
- AND lane.lane NOT IN (SELECT lane FROM saturated_lanes)
842
- AND (SELECT count(*) FROM held_window) < ${CLAIM_SCAN_WINDOW}
843
- AND NOT (SELECT value FROM stale)
844
- AND ${this.#noRunningDelivery("lane")}
845
- RETURNING lane.lane
846
- )
847
- SELECT (SELECT value FROM stale) AS stale,
848
- EXISTS (SELECT 1 FROM free_lanes WHERE free_lanes.running) AS takeover_waiting,
849
- (SELECT count(*) FROM free_lanes) = (SELECT count FROM wanted) + ${FREE_LANE_SURPLUS} AS unexamined_free_lanes,
850
- (
851
- SELECT COALESCE(jsonb_agg(delivery.id), '[]'::jsonb)
852
- FROM held
853
- CROSS JOIN LATERAL unnest(held.in_flight) AS flying (id)
854
- JOIN ${deliveries} AS delivery ON delivery.id = flying.id AND delivery.status = 'pending'
855
- )::text AS running_ids,
856
- (SELECT COALESCE(jsonb_agg(held.lane), '[]'::jsonb) FROM held)::text AS examined_lanes,
857
- picked.*
858
- FROM (SELECT 1) AS anchor
859
- LEFT JOIN picked_rows AS picked ON true
860
- ORDER BY picked.due_at, picked.delivery_id`;
945
+ async #claimMore(request, alreadyClaimed) {
946
+ const now = request.now.toISOString();
947
+ const leaseExpiresAt = request.leaseExpiresAt.toISOString();
948
+ const handlers = JSON.stringify(request.handlers);
949
+ const generation = this.#generation(request.leaseOwner).toString();
950
+ return this.#state.executor.transaction(async (transaction) => {
951
+ const claimed = [];
952
+ const remaining = () => request.limit - alreadyClaimed - claimed.length;
953
+ const takenLanes = /* @__PURE__ */ new Set();
954
+ for (let laneCount = INITIAL_LANES_PER_ROUND; remaining() > 0; ) {
955
+ const taken = await this.#state.query({
956
+ sql: this.#state.statements.lanes.takeFreeLanes,
957
+ parameters: [now, handlers, laneCount, request.leaseOwner, leaseExpiresAt, generation],
958
+ transaction
959
+ });
960
+ if (taken.length === 0) {
961
+ break;
962
+ }
963
+ const lanes = taken.map((row) => readCount(row, "lane"));
964
+ for (const lane of lanes) {
965
+ takenLanes.add(lane);
966
+ }
967
+ claimed.push(
968
+ ...await this.#pickDeliveries(
969
+ [now, handlers, remaining(), JSON.stringify(lanes)],
970
+ transaction
971
+ )
972
+ );
973
+ laneCount *= 2;
974
+ }
975
+ await this.#recordClaim(claimed, { lanes: takenLanes, request, transaction });
976
+ return claimed;
977
+ });
978
+ }
979
+ /**
980
+ * The generation of the owner's claim statements. It only grows, also across restarts (it starts at the
981
+ * clock), and a reconciliation moves it up, which fences off every earlier statement still in flight.
982
+ */
983
+ #generation(owner, advance = false) {
984
+ const current = this.#state.generations.get(owner) ?? BigInt(Date.now());
985
+ const next = advance ? current + GENERATION_STEP > BigInt(Date.now()) ? current + GENERATION_STEP : BigInt(Date.now()) : current;
986
+ this.#state.generations.set(owner, next);
987
+ return next;
988
+ }
989
+ /** Remembers the claims handed to the caller of `claim` until they are settled. */
990
+ #handOut(rows, leaseOwner) {
991
+ for (const row of rows) {
992
+ const claim = mapClaimedDelivery(row, /* @__PURE__ */ new Date(0));
993
+ this.#state.handedOut.set(handedOutKey(claim.deliveryId, claim.leaseToken), {
994
+ owner: leaseOwner,
995
+ deliveryId: claim.deliveryId,
996
+ ...parseLeaseToken(claim.leaseToken)
997
+ });
998
+ }
999
+ }
1000
+ /**
1001
+ * Drops the registrations of the owner's held lanes whose delivery no longer runs there
1002
+ * (completed inside the caller's transaction, deleted, or listed no more). Registrations of
1003
+ * lanes this claim did not see stay: their tokens may still be valid.
1004
+ */
1005
+ #forgetFinished(row, {
1006
+ leaseOwner,
1007
+ claimed
1008
+ }) {
1009
+ const heldLanes = new Set(JSON.parse(row["examined_lanes"]));
1010
+ const running = /* @__PURE__ */ new Set([
1011
+ ...JSON.parse(row["running_ids"]),
1012
+ ...claimed.map((picked) => picked["delivery_id"])
1013
+ ]);
1014
+ for (const [key, entry] of this.#state.handedOut) {
1015
+ if (entry.owner === leaseOwner && heldLanes.has(entry.lane) && !running.has(entry.deliveryId)) {
1016
+ this.#state.handedOut.delete(key);
1017
+ }
1018
+ }
1019
+ }
1020
+ /**
1021
+ * After a claim failed, possibly after the database recorded its batch: gives back the recorded
1022
+ * deliveries that were never handed out, keeping exactly the claims handed out and not settled.
1023
+ * A failure is remembered and retried before the owner's next claim: other deliveries keep
1024
+ * renewing the lane, so an unreturned one would otherwise never be recovered.
1025
+ */
1026
+ async #reconcile(leaseOwner) {
1027
+ const generation = this.#generation(leaseOwner, true);
1028
+ const handedOut = [...this.#state.handedOut.values()].filter((entry) => entry.owner === leaseOwner).map(({ deliveryId, lane, epoch, claims }) => ({ id: deliveryId, lane, epoch, claims }));
1029
+ try {
1030
+ await this.#state.query({
1031
+ sql: this.#state.statements.claim.reconcileClaims,
1032
+ parameters: [leaseOwner, JSON.stringify(handedOut), generation.toString()]
1033
+ });
1034
+ this.#state.unreconciled.delete(leaseOwner);
1035
+ return true;
1036
+ } catch (error) {
1037
+ this.#state.unreconciled.add(leaseOwner);
1038
+ this.#state.logger.error(
1039
+ `[PostgresClaims](reconcile) Giving back unreturned deliveries failed, it is retried before the next claim | owner=${leaseOwner} | error=${error instanceof Error ? error.message : String(error)}`
1040
+ );
1041
+ return false;
1042
+ }
1043
+ }
1044
+ /** Fast claim, then the slow one when the fast window was full of blocked followers. */
1045
+ async #pickDeliveries(parameters, transaction) {
1046
+ const limit = parameters[2];
1047
+ const fastRows = await this.#state.query({
1048
+ sql: this.#state.statements.claim.claim,
1049
+ parameters,
1050
+ transaction
1051
+ });
1052
+ const picked = fastRows.filter((row) => row["delivery_id"] !== null);
1053
+ if (picked.length < limit && fastRows[0]["window_saturated"] === true) {
1054
+ const slowRows = await this.#state.query({
1055
+ sql: this.#state.statements.claim.claimBehindBlockedKeys,
1056
+ parameters,
1057
+ transaction
1058
+ });
1059
+ const pickedIds = new Set(picked.map((row) => row["delivery_id"]));
1060
+ picked.push(
1061
+ ...slowRows.filter(
1062
+ (row) => row["delivery_id"] !== null && !pickedIds.has(row["delivery_id"])
1063
+ )
1064
+ );
1065
+ const seenKeys = /* @__PURE__ */ new Set();
1066
+ const kept = [...picked].sort((left, right) => compareSequence(left, right)).filter((row) => {
1067
+ if (row["delivery_key"] === null) {
1068
+ return true;
1069
+ }
1070
+ const group = `${row["handler"]}\0${row["delivery_key"]}`;
1071
+ return !seenKeys.has(group) && Boolean(seenKeys.add(group));
1072
+ });
1073
+ kept.sort(compareDue);
1074
+ return kept.slice(0, limit);
1075
+ }
1076
+ return picked;
1077
+ }
1078
+ /** Writes the picked ids into their lane rows and frees the lanes that picked nothing. */
1079
+ async #recordClaim(claimed, {
1080
+ lanes,
1081
+ request,
1082
+ transaction
1083
+ }) {
1084
+ const idsByLane = /* @__PURE__ */ new Map();
1085
+ for (const row of claimed) {
1086
+ const lane = readCount(row, "lane");
1087
+ idsByLane.set(lane, [...idsByLane.get(lane) ?? [], row["delivery_id"]]);
1088
+ }
1089
+ const idleLanes = [...lanes].filter((lane) => !idsByLane.has(lane));
1090
+ if (idsByLane.size === 0 && idleLanes.length === 0) {
1091
+ return;
1092
+ }
1093
+ await this.#state.query({
1094
+ sql: this.#state.statements.claim.recordClaim,
1095
+ parameters: [
1096
+ JSON.stringify([...idsByLane].map(([lane, ids]) => ({ lane, ids }))),
1097
+ JSON.stringify(idleLanes),
1098
+ request.leaseOwner,
1099
+ request.leaseExpiresAt.toISOString()
1100
+ ],
1101
+ transaction
1102
+ });
1103
+ }
1104
+ };
1105
+ var GENERATION_STEP = 1n;
1106
+ function leftWorkBehind(row) {
1107
+ return row["takeover_waiting"] === true || row["unexamined_free_lanes"] === true || row["stale"] === true;
1108
+ }
1109
+ function compareSequence(left, right) {
1110
+ const first = sequenceOf(left);
1111
+ const second = sequenceOf(right);
1112
+ return Number(first > second) - Number(first < second);
1113
+ }
1114
+ function sequenceOf(row) {
1115
+ return BigInt(row["sequence"] ?? 0);
1116
+ }
1117
+ function compareDue(left, right) {
1118
+ return compareText(left["due_at"], right["due_at"]) || compareText(left["delivery_id"], right["delivery_id"]);
1119
+ }
1120
+ function compareText(left, right) {
1121
+ return Number(left > right) - Number(left < right);
1122
+ }
1123
+
1124
+ // src/postgres-completion.ts
1125
+ var PostgresCompletion = class {
1126
+ #state;
1127
+ constructor(state) {
1128
+ this.#state = state;
1129
+ }
1130
+ /** Implements {@link PostgresEventStore.extendLease}. */
1131
+ extendLease(lease, leaseExpiresAt) {
1132
+ return this.#whenIssued(
1133
+ lease,
1134
+ (held) => this.#changed(this.#state.statements.completion.extendLease, [
1135
+ lease.deliveryId,
1136
+ held.lane,
1137
+ held.epoch,
1138
+ held.claims,
1139
+ leaseExpiresAt.toISOString()
1140
+ ])
1141
+ );
1142
+ }
1143
+ /** Implements {@link PostgresEventStore.complete}. */
1144
+ async complete(lease, { now, transaction }) {
1145
+ return (await this.#completeLeases([lease], { now, transaction }))[0];
1146
+ }
1147
+ /** Implements {@link PostgresEventStore.completeMany}. */
1148
+ completeMany(leases, now) {
1149
+ return this.#completeLeases(leases, { now, transaction: void 0 });
1150
+ }
1151
+ /** Implements {@link PostgresEventStore.reschedule}. */
1152
+ reschedule(lease, {
1153
+ availableAt,
1154
+ error,
1155
+ now
1156
+ }) {
1157
+ return this.#settled(
1158
+ lease,
1159
+ this.#whenIssued(
1160
+ lease,
1161
+ (held) => this.#changed(this.#state.statements.completion.reschedule, [
1162
+ lease.deliveryId,
1163
+ held.lane,
1164
+ held.epoch,
1165
+ held.claims,
1166
+ availableAt.toISOString(),
1167
+ JSON.stringify(error),
1168
+ now.toISOString()
1169
+ ])
1170
+ )
1171
+ );
1172
+ }
1173
+ /** Implements {@link PostgresEventStore.bury}. */
1174
+ bury(lease, { error, now }) {
1175
+ return this.#settled(
1176
+ lease,
1177
+ this.#whenIssued(
1178
+ lease,
1179
+ (held) => this.#changed(this.#state.statements.completion.bury, [
1180
+ lease.deliveryId,
1181
+ held.lane,
1182
+ held.epoch,
1183
+ held.claims,
1184
+ JSON.stringify(error),
1185
+ now.toISOString()
1186
+ ])
1187
+ )
1188
+ );
1189
+ }
1190
+ /** Implements {@link PostgresEventStore.release}. */
1191
+ release(lease, now) {
1192
+ return this.#settled(
1193
+ lease,
1194
+ this.#whenIssued(
1195
+ lease,
1196
+ (held) => this.#changed(this.#state.statements.completion.release, [
1197
+ lease.deliveryId,
1198
+ held.lane,
1199
+ held.epoch,
1200
+ held.claims,
1201
+ now.toISOString()
1202
+ ])
1203
+ )
1204
+ );
1205
+ }
1206
+ /** Forgets a handed-out lease once the store answered about it (any answer: the claim is over or fenced out). */
1207
+ async #settled(lease, work) {
1208
+ const result = await work;
1209
+ this.#state.handedOut.delete(handedOutKey(lease.deliveryId, lease.leaseToken));
1210
+ return result;
1211
+ }
1212
+ async #changed(sql, parameters) {
1213
+ const rows = await this.#state.query({ sql, parameters });
1214
+ return readCount(rows[0], "count") > 0;
1215
+ }
1216
+ /** Runs `operation` for a lease this store issued; any other token cannot be held. */
1217
+ async #whenIssued(lease, operation) {
1218
+ const held = parseLeaseToken(lease.leaseToken);
1219
+ return held !== void 0 && await operation(held);
1220
+ }
1221
+ /**
1222
+ * Deletes the delivery of every lease that is still the current claim of its
1223
+ * delivery. Returns one flag per lease, in order. Results are matched to leases
1224
+ * by position, so two leases of one delivery (a stale and a current one) get
1225
+ * their own answers; a lease listed twice completes once, at its first position.
1226
+ */
1227
+ async #completeLeases(leases, { now, transaction }) {
1228
+ const issued = [];
1229
+ const seen = /* @__PURE__ */ new Set();
1230
+ leases.forEach((lease, ord) => {
1231
+ const held = parseLeaseToken(lease.leaseToken);
1232
+ const identity = `${lease.deliveryId}\0${lease.leaseToken}`;
1233
+ if (held !== void 0 && !seen.has(identity)) {
1234
+ seen.add(identity);
1235
+ issued.push({ ord, id: lease.deliveryId, ...held });
1236
+ }
1237
+ });
1238
+ const completed = /* @__PURE__ */ new Set();
1239
+ if (issued.length > 0) {
1240
+ const rows = await this.#state.query({
1241
+ sql: this.#state.statements.completion.complete,
1242
+ parameters: [JSON.stringify(issued), now.toISOString()],
1243
+ transaction
1244
+ });
1245
+ for (const row of rows) {
1246
+ completed.add(readCount(row, "ord"));
1247
+ }
1248
+ }
1249
+ if (transaction === void 0) {
1250
+ for (const lease of leases) {
1251
+ this.#state.handedOut.delete(handedOutKey(lease.deliveryId, lease.leaseToken));
1252
+ }
1253
+ }
1254
+ return leases.map((_, ord) => completed.has(ord));
1255
+ }
1256
+ };
1257
+ var OwnedConnections = class {
1258
+ #clients = /* @__PURE__ */ new Set();
1259
+ /**
1260
+ * The `Client` class for a pool the store creates: every connection is tracked from the moment it
1261
+ * is created, so one still connecting or authenticating is destroyed too.
1262
+ */
1263
+ clientClass() {
1264
+ const owned = this;
1265
+ return class OwnedClient extends pg.Client {
1266
+ constructor(config) {
1267
+ super(config);
1268
+ owned.track(this);
1269
+ }
1270
+ };
1271
+ }
1272
+ /** Tracks one connection until it ends. */
1273
+ track(client) {
1274
+ this.#clients.add(client);
1275
+ client.once("end", () => this.#clients.delete(client));
1276
+ }
1277
+ /**
1278
+ * Destroys the socket of every tracked connection. Its queries fail with "Connection terminated"
1279
+ * and the pool drops it. The server ends the session when it next talks to the client.
1280
+ */
1281
+ destroyAll() {
1282
+ for (const client of this.#clients) {
1283
+ client.on("error", () => void 0);
1284
+ client.connection.stream.destroy();
1285
+ }
1286
+ this.#clients.clear();
1287
+ }
1288
+ };
1289
+
1290
+ // src/postgres-maintenance.ts
1291
+ var PostgresMaintenance = class {
1292
+ #state;
1293
+ constructor(state) {
1294
+ this.#state = state;
1295
+ }
1296
+ /** Implements {@link PostgresEventStore.relinquish}. */
1297
+ async relinquish(leaseOwner) {
1298
+ await this.#state.query({
1299
+ sql: this.#state.statements.claim.relinquish,
1300
+ parameters: [leaseOwner]
1301
+ });
1302
+ }
1303
+ /** Implements {@link PostgresEventStore.listDeliveries}. */
1304
+ async listDeliveries(query) {
1305
+ const statement = this.#state.statements.queries.listDeliveries(query);
1306
+ const rows = await this.#state.executor.query(statement.sql, statement.parameters);
1307
+ return rows.map(mapDeliveryRecord);
1308
+ }
1309
+ /** Implements {@link PostgresEventStore.requeue}. */
1310
+ async requeue(deliveryIds, now) {
1311
+ const rows = await this.#state.query({
1312
+ sql: this.#state.statements.queries.requeue,
1313
+ parameters: [JSON.stringify(deliveryIds), now.toISOString()]
1314
+ });
1315
+ return readCount(rows[0], "count");
1316
+ }
1317
+ /** Implements {@link PostgresEventStore.statistics}. */
1318
+ async statistics(now) {
1319
+ const stored = { pending: 0, dead: 0, completed: 0 };
1320
+ for (const row of await this.#state.query({
1321
+ sql: this.#state.statements.queries.countByStatus,
1322
+ parameters: []
1323
+ })) {
1324
+ stored[row["status"]] = readCount(row, "count");
1325
+ }
1326
+ const [running] = await this.#state.query({
1327
+ sql: this.#state.statements.queries.countRunning,
1328
+ parameters: []
1329
+ });
1330
+ const processing = readCount(running, "count");
1331
+ let completed = stored["completed"];
1332
+ if (this.#state.completionHistory) {
1333
+ const [history] = await this.#state.query({
1334
+ sql: this.#state.statements.queries.countCompletionHistory,
1335
+ parameters: []
1336
+ });
1337
+ completed += readCount(history, "count");
1338
+ }
1339
+ const oldestDue = await this.#state.query({
1340
+ sql: this.#state.statements.queries.oldestDue,
1341
+ parameters: [now.toISOString()]
1342
+ });
1343
+ return {
1344
+ // The counts come from separate statements; a delivery that finishes in between must not make this negative.
1345
+ pending: Math.max(0, stored["pending"] - processing),
1346
+ processing,
1347
+ completed,
1348
+ dead: stored["dead"],
1349
+ oldestDueAt: mapOldestDueAt(oldestDue)
1350
+ };
1351
+ }
1352
+ /** Implements {@link PostgresEventStore.purge}. */
1353
+ async purge(request) {
1354
+ const total = { deletedDeliveries: 0, deletedEvents: 0 };
1355
+ const batches = [
1356
+ [
1357
+ this.#state.statements.purge.purgeCompletedBatch(),
1358
+ request.completedBefore,
1359
+ this.#state.statements.purge.deleteOrphanEventsWithoutCompletion
1360
+ ],
1361
+ [
1362
+ this.#state.statements.purge.purgeDeadBatch(),
1363
+ request.deadBefore,
1364
+ this.#state.statements.purge.deleteOrphanEventsWithoutCompletion
1365
+ ]
1366
+ ];
1367
+ if (this.#state.completionHistory) {
1368
+ batches.push([
1369
+ this.#state.statements.purge.purgeCompletionHistoryBatch(),
1370
+ request.completedBefore,
1371
+ this.#state.statements.purge.deleteOrphanEventsWithoutCompletion
1372
+ ]);
1373
+ }
1374
+ for (const [sql, cutoff, deleteOrphans] of batches) {
1375
+ if (cutoff === void 0) {
1376
+ continue;
1377
+ }
1378
+ let deletedInBatch = this.#state.purgeBatchSize;
1379
+ while (deletedInBatch === this.#state.purgeBatchSize) {
1380
+ const batch = await this.#purgeBatch(sql, { cutoff, deleteOrphans });
1381
+ deletedInBatch = batch.deletedDeliveries;
1382
+ total.deletedDeliveries += batch.deletedDeliveries;
1383
+ total.deletedEvents += batch.deletedEvents;
1384
+ }
1385
+ }
1386
+ const orphanCutoff = [request.completedBefore, request.deadBefore].filter((cutoff) => cutoff !== void 0).sort((first, second) => first.getTime() - second.getTime())[0];
1387
+ if (orphanCutoff !== void 0) {
1388
+ total.deletedEvents += await this.#purgeOrphanEvents(
1389
+ this.#state.statements.purge.lockOrphanEventsBatch,
1390
+ {
1391
+ deleteStatement: this.#state.statements.purge.deleteOrphanEventsWithoutCompletion,
1392
+ cutoff: orphanCutoff,
1393
+ recheckCutoff: false
1394
+ }
1395
+ );
1396
+ }
1397
+ if (request.completedBefore !== void 0) {
1398
+ total.deletedEvents += await this.#purgeOrphanEvents(
1399
+ this.#state.statements.purge.lockCompletedOrphanEventsBatch,
1400
+ {
1401
+ deleteStatement: this.#state.statements.purge.deleteExpiredCompletedOrphanEvents,
1402
+ cutoff: request.completedBefore,
1403
+ recheckCutoff: true
1404
+ }
1405
+ );
1406
+ }
1407
+ return total;
1408
+ }
1409
+ async #purgeOrphanEvents(lockStatement, {
1410
+ deleteStatement,
1411
+ cutoff,
1412
+ recheckCutoff
1413
+ }) {
1414
+ let deletedEvents = 0;
1415
+ let removedInBatch = this.#state.purgeBatchSize;
1416
+ while (removedInBatch === this.#state.purgeBatchSize) {
1417
+ removedInBatch = await this.#state.executor.transaction(async (transaction) => {
1418
+ const locked = await this.#state.query({
1419
+ sql: lockStatement,
1420
+ parameters: [cutoff.toISOString(), this.#state.purgeBatchSize],
1421
+ transaction
1422
+ });
1423
+ const ids = JSON.stringify(locked.map((row) => row["id"]));
1424
+ const removed = await this.#state.query({
1425
+ sql: deleteStatement,
1426
+ parameters: recheckCutoff ? [ids, cutoff.toISOString()] : [ids],
1427
+ transaction
1428
+ });
1429
+ return readCount(removed[0], "count");
1430
+ });
1431
+ deletedEvents += removedInBatch;
1432
+ }
1433
+ return deletedEvents;
1434
+ }
1435
+ async #purgeBatch(sql, { cutoff, deleteOrphans }) {
1436
+ return this.#state.executor.transaction(async (transaction) => {
1437
+ const deleted = await this.#state.query({
1438
+ sql,
1439
+ parameters: [cutoff.toISOString(), this.#state.purgeBatchSize],
1440
+ transaction
1441
+ });
1442
+ if (deleted.length === 0) {
1443
+ return { deletedDeliveries: 0, deletedEvents: 0 };
1444
+ }
1445
+ const eventIds = JSON.stringify([
1446
+ ...new Set(deleted.map((row) => row["event_id"]))
1447
+ ]);
1448
+ const locked = await this.#state.query({
1449
+ sql: this.#state.statements.purge.lockEvents,
1450
+ parameters: [eventIds],
1451
+ transaction
1452
+ });
1453
+ const removed = await this.#state.query({
1454
+ sql: deleteOrphans,
1455
+ parameters: [JSON.stringify(locked.map((row) => row["id"]))],
1456
+ transaction
1457
+ });
1458
+ return { deletedDeliveries: deleted.length, deletedEvents: readCount(removed[0], "count") };
1459
+ });
1460
+ }
1461
+ };
1462
+
1463
+ // src/statements-append.ts
1464
+ var AppendStatements = class {
1465
+ #names;
1466
+ constructor(names) {
1467
+ this.#names = names;
861
1468
  }
862
1469
  /**
863
- * The head (lowest pending sequence) of every key of every wanted handler in the lane `scope.lane`,
864
- * as a subquery returning `(id, lane, available_at, handler, key)`. A loose index scan on the
865
- * pending-key index hops from key to key of a handler, and after its last key on to the first key of
866
- * the next wanted handler, so the cost follows the number of keys, not the number of followers. The
867
- * handlers are walked inside the recursion instead of joined to it: a join multiplied the planner's
868
- * cost estimate by the handler count, which pushed the claim statements over `jit_above_cost`, and
869
- * compiling them took longer than running them.
1470
+ * Publishes in one statement: reserves the sequences of the keys (`[{ key, count }]` in `$4`, locked in
1471
+ * key order: each row lock is held until the publishing transaction ends, which makes sequence order equal commit order for a key), numbers the keyed events in entry order (`ordinal`), inserts
1472
+ * the events of `$1` that do not exist yet and the deliveries of `$3` that belong to them, and sends one
1473
+ * wake-up notification when a delivery it inserted is due at `$5`. Parameters:
1474
+ * `[eventsJson, createdAt, deliveriesJson, keyCountsJson, now]`. Returns one row per event of `$1`: its
1475
+ * id, its sequence, whether this statement inserted it, and (on every row) how many deliveries it
1476
+ * inserted. Deliveries of events that already existed are left to {@link insertDeliveries}.
870
1477
  */
871
- #keyHeads(scope) {
872
- const deliveries = this.#names.deliveries;
873
- const pending = `candidate.lane = ${scope}.lane AND candidate.status = 'pending'`;
874
- const nextHandler = (after) => `(SELECT min(wanted.handler) FROM jsonb_array_elements_text($2::jsonb) AS wanted (handler)${after === "" ? "" : ` WHERE wanted.handler > ${after}`})`;
875
- return `
876
- WITH RECURSIVE hops (handler, key) AS (
877
- SELECT ${nextHandler("")}, NULL::text
878
- UNION ALL
879
- SELECT CASE WHEN next.key IS NULL THEN ${nextHandler("hops.handler")} ELSE hops.handler END, next.key
880
- FROM hops
881
- CROSS JOIN LATERAL (
882
- SELECT CASE WHEN hops.key IS NULL
883
- THEN (SELECT candidate.key FROM ${deliveries} AS candidate
884
- WHERE ${pending} AND candidate.handler = hops.handler AND candidate.key IS NOT NULL
885
- ORDER BY candidate.key LIMIT 1)
886
- ELSE (SELECT candidate.key FROM ${deliveries} AS candidate
887
- WHERE ${pending} AND candidate.handler = hops.handler AND candidate.key > hops.key
888
- ORDER BY candidate.key LIMIT 1)
889
- END AS key
890
- OFFSET 0
891
- ) AS next
892
- WHERE hops.handler IS NOT NULL
893
- )
894
- SELECT lowest.id, lowest.lane, lowest.available_at, lowest.handler, lowest.key
895
- FROM hops
896
- CROSS JOIN LATERAL (
897
- SELECT candidate.id, candidate.lane, candidate.available_at, candidate.handler, candidate.key
898
- FROM ${deliveries} AS candidate
899
- WHERE ${pending} AND candidate.handler = hops.handler AND candidate.key = hops.key
900
- ORDER BY candidate.sequence LIMIT 1
901
- ) AS lowest
902
- WHERE hops.key IS NOT NULL
903
- `;
1478
+ get insertFreshEvents() {
1479
+ const events = this.#names.events;
1480
+ return `WITH reserved AS (
1481
+ INSERT INTO ${this.#names.keySequences} AS reserved (key, sequence)
1482
+ SELECT requested.key, requested.count
1483
+ FROM jsonb_to_recordset($4::jsonb) AS requested (key text, count bigint)
1484
+ ORDER BY requested.key
1485
+ ON CONFLICT (key) DO UPDATE SET sequence = reserved.sequence + EXCLUDED.sequence
1486
+ RETURNING reserved.key AS key, reserved.sequence AS sequence
1487
+ ), incoming AS (
1488
+ SELECT incoming.*,
1489
+ CASE WHEN incoming.key IS NULL THEN NULL ELSE
1490
+ reserved.sequence - count(*) OVER (PARTITION BY incoming.key)
1491
+ + row_number() OVER (PARTITION BY incoming.key ORDER BY incoming.ordinal)
1492
+ END AS sequence
1493
+ FROM jsonb_to_recordset($1::jsonb) AS incoming (
1494
+ ordinal int, id text, type text, source text, key text, payload jsonb, headers jsonb,
1495
+ correlation_id text, causation_id text, occurred_at timestamptz, handlers text[])
1496
+ LEFT JOIN reserved ON reserved.key = incoming.key
1497
+ ), inserted_events AS (
1498
+ INSERT INTO ${events}
1499
+ (id, type, source, key, sequence, payload, headers, correlation_id, causation_id, occurred_at, created_at, handlers)
1500
+ SELECT incoming.id, incoming.type, incoming.source, incoming.key, incoming.sequence,
1501
+ COALESCE(incoming.payload, 'null'::jsonb), COALESCE(incoming.headers, '{}'::jsonb),
1502
+ incoming.correlation_id, incoming.causation_id, incoming.occurred_at, $2::timestamptz,
1503
+ COALESCE(incoming.handlers, '{}')
1504
+ FROM incoming
1505
+ ORDER BY incoming.id
1506
+ ON CONFLICT (id) DO NOTHING
1507
+ RETURNING id, key, sequence
1508
+ ), inserted_deliveries AS (
1509
+ INSERT INTO ${this.#names.deliveries}
1510
+ (id, event_id, handler, lane, status, attempts, available_at, key, sequence, created_at, updated_at)
1511
+ SELECT delivery.id, delivery.event_id, delivery.handler, ${laneExpression("event.key", "event.id")}, 'pending', 0,
1512
+ delivery.available_at, event.key, event.sequence, $2::timestamptz, $2::timestamptz
1513
+ FROM jsonb_to_recordset($3::jsonb) AS delivery (id text, event_id text, handler text, available_at timestamptz)
1514
+ JOIN inserted_events AS event ON event.id = delivery.event_id
1515
+ ORDER BY delivery.event_id, delivery.handler
1516
+ ON CONFLICT (event_id, handler) DO NOTHING
1517
+ RETURNING available_at
1518
+ ), ${this.#wakeUp("inserted_deliveries", "$5")}
1519
+ SELECT incoming.id, incoming.sequence::text AS sequence,
1520
+ incoming.id IN (SELECT inserted_events.id FROM inserted_events) AS inserted,
1521
+ (SELECT count(*) FROM inserted_deliveries)::int AS deliveries
1522
+ FROM incoming
1523
+ WHERE (SELECT count(*) FROM woken) >= 0`;
1524
+ }
1525
+ /** One wake-up notification on {@link PostgresNames.notificationChannel}, outside any publishing transaction. */
1526
+ get notify() {
1527
+ return `SELECT pg_notify('${this.#names.notificationChannel}', '')`;
904
1528
  }
905
1529
  /**
906
- * CTEs that pick up to `limit` claimable deliveries from the lanes of the CTE `scope` (columns `lane`,
907
- * `epoch`, `in_flight`), named after `prefix`; the result is `<prefix>_candidates (id, lane, available_at)`.
908
- * The rules are those of {@link claim}. The fast window reads the first {@link LANE_SCAN_WINDOW} due
909
- * deliveries of each lane (at most {@link CLAIM_SCAN_WINDOW} together); of a key, only the lowest sequence
910
- * in the window can be its head, so only that one is checked for an earlier pending delivery. Only when
911
- * that yields fewer than `limit` are the lanes whose window filled up looked at again with a loose index
912
- * scan over the heads of all their keys. `running` names the CTE of the keyed deliveries running in the
913
- * lanes, or is null when nothing runs there.
1530
+ * A CTE `woken` that sends one notification on {@link PostgresNames.notificationChannel} when a row of
1531
+ * `inserted` is due at `now`. PostgreSQL delivers it when the transaction commits, merges the same
1532
+ * notification sent twice in one transaction, and drops it on rollback. The statement must reference
1533
+ * `woken` for it to run.
914
1534
  */
915
- #candidates(prefix, scope, running, limit) {
916
- const deliveries = this.#names.deliveries;
917
- const notRunning = (alias) => running === null ? "true" : `NOT EXISTS (SELECT 1 FROM ${running} AS running WHERE running.handler = ${alias}.handler AND running.key = ${alias}.key)`;
918
- return `${prefix}_window AS MATERIALIZED (
919
- SELECT recent.id, recent.lane, recent.available_at, recent.handler, recent.key, recent.sequence
920
- FROM ${scope}
921
- CROSS JOIN LATERAL (
922
- SELECT delivery.id, delivery.lane, delivery.available_at, delivery.handler, delivery.key, delivery.sequence
923
- FROM ${deliveries} AS delivery
924
- WHERE delivery.lane = ${scope}.lane AND delivery.status = 'pending'
925
- AND delivery.available_at <= $1::timestamptz AND ${HANDLER_PREDICATE}
926
- AND delivery.id <> ALL (${scope}.in_flight)
927
- ORDER BY delivery.available_at, delivery.id
928
- LIMIT ${LANE_SCAN_WINDOW}
929
- ) AS recent
930
- ORDER BY recent.available_at, recent.id
931
- LIMIT ${CLAIM_SCAN_WINDOW}
932
- ), ${prefix}_fast AS MATERIALIZED (
933
- SELECT picked.id, picked.lane, picked.available_at FROM (
934
- SELECT unkeyed.id, unkeyed.lane, unkeyed.available_at FROM ${prefix}_window AS unkeyed WHERE unkeyed.key IS NULL
935
- UNION ALL
936
- SELECT head.id, head.lane, head.available_at
937
- FROM (
938
- SELECT DISTINCT ON (keyed.handler, keyed.key) keyed.id, keyed.lane, keyed.available_at, keyed.handler, keyed.key, keyed.sequence
939
- FROM ${prefix}_window AS keyed
940
- WHERE keyed.key IS NOT NULL
941
- ORDER BY keyed.handler, keyed.key, keyed.sequence
942
- ) AS head
943
- WHERE NOT EXISTS (
944
- SELECT 1 FROM ${deliveries} AS earlier
945
- WHERE earlier.lane = head.lane AND earlier.handler = head.handler AND earlier.key = head.key
946
- AND earlier.status = 'pending' AND earlier.key IS NOT NULL AND earlier.sequence < head.sequence
947
- ) AND ${notRunning("head")}
948
- ) AS picked
949
- ORDER BY picked.available_at, picked.id
950
- LIMIT ${limit}
951
- ), ${prefix}_saturated AS MATERIALIZED (
952
- SELECT ${scope}.lane, ${scope}.in_flight FROM ${scope}
953
- WHERE (SELECT count(*) FROM ${prefix}_fast) < ${limit}
954
- AND ((SELECT count(*) FROM ${prefix}_window) >= ${CLAIM_SCAN_WINDOW}
955
- OR ${scope}.lane IN (
956
- SELECT full_lane.lane FROM ${prefix}_window AS full_lane
957
- GROUP BY full_lane.lane HAVING count(*) >= ${LANE_SCAN_WINDOW}
958
- ))
959
- ), ${prefix}_heads AS MATERIALIZED (
960
- SELECT head.id, head.lane, head.available_at, head.handler, head.key
961
- FROM ${prefix}_saturated AS scope
962
- CROSS JOIN LATERAL (${this.#keyHeads("scope")}) AS head
963
- ), ${prefix}_keyed AS MATERIALIZED (
964
- SELECT heads.id, heads.lane, heads.available_at
965
- FROM ${prefix}_heads AS heads
966
- JOIN ${prefix}_saturated AS scope ON scope.lane = heads.lane
967
- WHERE heads.available_at <= $1::timestamptz AND heads.id <> ALL (scope.in_flight) AND ${notRunning("heads")}
968
- ORDER BY heads.available_at, heads.id
969
- LIMIT ${limit}
970
- ), ${prefix}_unkeyed AS MATERIALIZED (
971
- SELECT recent.id, recent.lane, recent.available_at
972
- FROM ${prefix}_saturated AS scope
973
- CROSS JOIN LATERAL (
974
- SELECT delivery.id, delivery.lane, delivery.available_at
975
- FROM ${deliveries} AS delivery
976
- WHERE delivery.lane = scope.lane AND delivery.key IS NULL AND delivery.status = 'pending'
977
- AND delivery.available_at <= $1::timestamptz AND ${HANDLER_PREDICATE}
978
- AND delivery.id <> ALL (scope.in_flight)
979
- ORDER BY delivery.available_at, delivery.id
980
- LIMIT ${limit}
981
- ) AS recent
982
- ORDER BY recent.available_at, recent.id
983
- LIMIT ${limit}
984
- ), ${prefix}_candidates AS MATERIALIZED (
985
- SELECT chosen.id, chosen.lane, chosen.available_at FROM (
986
- SELECT fast.id, fast.lane, fast.available_at FROM ${prefix}_fast AS fast
987
- UNION
988
- SELECT keyed.id, keyed.lane, keyed.available_at FROM ${prefix}_keyed AS keyed
989
- UNION
990
- SELECT unkeyed.id, unkeyed.lane, unkeyed.available_at FROM ${prefix}_unkeyed AS unkeyed
991
- ) AS chosen
992
- ORDER BY chosen.available_at, chosen.id
993
- LIMIT ${limit}
1535
+ #wakeUp(inserted, now) {
1536
+ return `woken AS (
1537
+ SELECT pg_notify('${this.#names.notificationChannel}', '') FROM (
1538
+ SELECT 1 FROM ${inserted} WHERE ${inserted}.available_at <= ${now}::timestamptz LIMIT 1
1539
+ ) AS due
994
1540
  )`;
995
1541
  }
996
1542
  /**
997
- * Takes up to `$3` free lanes (no lease, or an expired one) that have a due
998
- * delivery of the requested handlers, the ones with the oldest due delivery
999
- * first. Parameters: `[now, handlersJson, laneCount, leaseOwner, leaseExpiresAt, generation]`.
1000
- * The lane gets the owner's `generation` as its `claim_floor`. A lane the owner itself holds under a live
1001
- * lease with a lower floor was taken by a claim statement that reached the server after its caller gave up
1002
- * and the owner reconciled (or by an earlier incarnation of the same owner): it is taken over like the lane of a
1003
- * crashed worker, so its listed deliveries are charged an attempt.
1004
- *
1005
- * A taken lane gets a new epoch, which fences everything the previous owner
1006
- * still holds. Deliveries the previous owner had in flight are the ones whose
1007
- * attempt was never recorded (a claim writes no delivery row), so each of
1008
- * them is charged one attempt here: a worker that crashes with a poison
1009
- * message still runs it into the retry limit. Lanes another claimer has locked
1010
- * are skipped, never waited for.
1543
+ * Parameters: `[eventsJson, createdAt]`. Returns the ids that were inserted.
1544
+ * `handlers` is the list of handlers the event gets deliveries for: it
1545
+ * outlives the deliveries, which are deleted when they complete.
1011
1546
  */
1012
- get takeFreeLanes() {
1013
- const deliveries = this.#names.deliveries;
1014
- const lanes = this.#names.lanes;
1015
- return `WITH picked AS (
1016
- -- in_flight is read here, from the locked version of the lane: a settlement that committed after the
1017
- -- statement took its snapshot has taken its delivery out of the list already and must not be charged again.
1018
- SELECT free.lane, free.in_flight
1019
- FROM ${lanes} AS free
1020
- CROSS JOIN LATERAL (
1021
- SELECT delivery.available_at, delivery.id
1022
- FROM ${deliveries} AS delivery
1023
- WHERE delivery.lane = free.lane AND delivery.status = 'pending'
1024
- AND delivery.available_at <= $1::timestamptz AND ${HANDLER_PREDICATE}
1025
- ORDER BY delivery.available_at, delivery.id
1026
- LIMIT 1
1027
- ) AS oldest
1028
- WHERE free.lease_expires_at IS NULL OR free.lease_expires_at <= $1::timestamptz
1029
- OR (free.lease_owner = $4::text AND free.claim_floor < $6::bigint)
1030
- ORDER BY oldest.available_at, oldest.id
1031
- LIMIT $3::int
1032
- FOR UPDATE OF free SKIP LOCKED
1033
- ), charged AS (
1034
- UPDATE ${deliveries} AS delivery SET attempts = delivery.attempts + 1, claims = delivery.claims + 1
1547
+ get insertEvents() {
1548
+ return `INSERT INTO ${this.#names.events}
1549
+ (id, type, source, key, sequence, payload, headers, correlation_id, causation_id, occurred_at, created_at, handlers)
1550
+ SELECT incoming.id, incoming.type, incoming.source, incoming.key, incoming.sequence,
1551
+ COALESCE(incoming.payload, 'null'::jsonb), COALESCE(incoming.headers, '{}'::jsonb),
1552
+ incoming.correlation_id, incoming.causation_id, incoming.occurred_at, $2::timestamptz,
1553
+ COALESCE(incoming.handlers, '{}')
1554
+ FROM jsonb_to_recordset($1::jsonb) AS incoming (
1555
+ id text, type text, source text, key text, sequence bigint, payload jsonb, headers jsonb,
1556
+ correlation_id text, causation_id text, occurred_at timestamptz, handlers text[])
1557
+ ORDER BY incoming.id
1558
+ ON CONFLICT (id) DO NOTHING
1559
+ RETURNING id`;
1560
+ }
1561
+ /**
1562
+ * Locks events that were not inserted by the current append, in id order, so
1563
+ * that appends adding handlers to the same event run one after the other.
1564
+ * Parameters: `[eventIdsJson]`. `FOR NO KEY UPDATE` conflicts with itself and
1565
+ * not with the foreign key checks of other inserts.
1566
+ */
1567
+ get lockExistingEvents() {
1568
+ return `SELECT id FROM ${this.#names.events}
1569
+ WHERE id = ANY (ARRAY(SELECT jsonb_array_elements_text($1::jsonb)))
1570
+ ORDER BY id
1571
+ FOR NO KEY UPDATE`;
1572
+ }
1573
+ /**
1574
+ * Parameters: `[deliveriesJson, createdAt, insertedEventIdsJson, now]`. Key and
1575
+ * sequence are copied from the stored event, so a delivery added later to an
1576
+ * existing event keeps the event's position in its key and lands in the same
1577
+ * lane. Returns the ids that were inserted.
1578
+ *
1579
+ * The deliveries of events this call just inserted are all new. For an event
1580
+ * that already existed, a handler gets a delivery only if the event does not
1581
+ * list it yet: a completed delivery is deleted, but its handler stays listed,
1582
+ * so a redelivered or republished event never runs a handler twice. The
1583
+ * handlers added to an existing event are appended to its list.
1584
+ */
1585
+ get insertDeliveries() {
1586
+ const events = this.#names.events;
1587
+ const insertedEvents = `ARRAY(SELECT jsonb_array_elements_text($3::jsonb))`;
1588
+ return `WITH incoming AS (
1589
+ SELECT incoming.id, incoming.event_id, incoming.handler, incoming.available_at
1590
+ FROM jsonb_to_recordset($1::jsonb) AS incoming (id text, event_id text, handler text, available_at timestamptz)
1591
+ ), fresh AS (
1592
+ SELECT incoming.*, event.key, event.sequence, ${laneExpression("event.key", "event.id")} AS lane
1593
+ FROM incoming
1594
+ JOIN ${events} AS event ON event.id = incoming.event_id
1595
+ WHERE event.id = ANY (${insertedEvents}) OR NOT incoming.handler = ANY (event.handlers)
1596
+ ), inserted AS (
1597
+ INSERT INTO ${this.#names.deliveries}
1598
+ (id, event_id, handler, lane, status, attempts, available_at, key, sequence, created_at, updated_at)
1599
+ SELECT fresh.id, fresh.event_id, fresh.handler, fresh.lane, 'pending', 0, fresh.available_at,
1600
+ fresh.key, fresh.sequence, $2::timestamptz, $2::timestamptz
1601
+ FROM fresh
1602
+ ORDER BY fresh.event_id, fresh.handler
1603
+ ON CONFLICT (event_id, handler) DO NOTHING
1604
+ RETURNING id, event_id, handler, available_at
1605
+ ), extended AS (
1606
+ UPDATE ${events} AS event SET handlers = event.handlers || added.handlers
1035
1607
  FROM (
1036
- SELECT unnest(picked.in_flight) AS id FROM picked
1037
- ) AS lost
1038
- WHERE delivery.id = lost.id AND delivery.status = 'pending'
1039
- RETURNING delivery.id
1040
- ), taken AS (
1041
- UPDATE ${lanes} AS lane
1042
- SET epoch = lane.epoch + 1, lease_owner = $4::text, lease_expires_at = $5::timestamptz, in_flight = '{}',
1043
- claim_floor = $6::bigint
1044
- FROM picked WHERE lane.lane = picked.lane
1045
- RETURNING lane.lane, lane.epoch
1046
- )
1047
- SELECT lane::int AS lane, epoch::text AS epoch FROM taken ORDER BY lane`;
1608
+ SELECT inserted.event_id, array_agg(inserted.handler) AS handlers FROM inserted
1609
+ WHERE inserted.event_id <> ALL (${insertedEvents}) GROUP BY inserted.event_id
1610
+ ) AS added
1611
+ WHERE event.id = added.event_id
1612
+ RETURNING event.id
1613
+ ), ${this.#wakeUp("inserted", "$4")}
1614
+ SELECT id FROM inserted WHERE (SELECT count(*) FROM woken) >= 0`;
1615
+ }
1616
+ };
1617
+
1618
+ // src/statement-fragments.ts
1619
+ var CLAIM_SCAN_WINDOW = 256;
1620
+ var LANE_SCAN_WINDOW = 64;
1621
+ var LANE_DEPTH_CAP = 16;
1622
+ var INITIAL_FREE_LANES = 4;
1623
+ var HANDLER_PREDICATE = `delivery.handler = ANY (ARRAY(SELECT jsonb_array_elements_text($2::jsonb)))`;
1624
+ function eventColumns(alias) {
1625
+ return `${alias}.id AS event_id,
1626
+ ${alias}.type AS event_type,
1627
+ ${alias}.source AS event_source,
1628
+ ${alias}.key AS event_key,
1629
+ ${alias}.payload::text AS event_payload,
1630
+ ${alias}.headers::text AS event_headers,
1631
+ ${alias}.correlation_id AS event_correlation_id,
1632
+ ${alias}.causation_id AS event_causation_id,
1633
+ ${isoText(`${alias}.occurred_at`)} AS event_occurred_at`;
1634
+ }
1635
+ function countChanged(dml) {
1636
+ return `WITH changed AS (${dml} RETURNING 1) SELECT count(*)::int AS count FROM changed`;
1637
+ }
1638
+ function keyHeads(names, scope) {
1639
+ const deliveries = names.deliveries;
1640
+ const pending = `candidate.lane = ${scope}.lane AND candidate.status = 'pending'`;
1641
+ const nextHandler = (after) => `(SELECT min(wanted.handler) FROM jsonb_array_elements_text($2::jsonb) AS wanted (handler)${after === "" ? "" : ` WHERE wanted.handler > ${after}`})`;
1642
+ return `
1643
+ WITH RECURSIVE hops (handler, key) AS (
1644
+ SELECT ${nextHandler("")}, NULL::text
1645
+ UNION ALL
1646
+ SELECT CASE WHEN next.key IS NULL THEN ${nextHandler("hops.handler")} ELSE hops.handler END, next.key
1647
+ FROM hops
1648
+ CROSS JOIN LATERAL (
1649
+ SELECT CASE WHEN hops.key IS NULL
1650
+ THEN (SELECT candidate.key FROM ${deliveries} AS candidate
1651
+ WHERE ${pending} AND candidate.handler = hops.handler AND candidate.key IS NOT NULL
1652
+ ORDER BY candidate.key LIMIT 1)
1653
+ ELSE (SELECT candidate.key FROM ${deliveries} AS candidate
1654
+ WHERE ${pending} AND candidate.handler = hops.handler AND candidate.key > hops.key
1655
+ ORDER BY candidate.key LIMIT 1)
1656
+ END AS key
1657
+ OFFSET 0
1658
+ ) AS next
1659
+ WHERE hops.handler IS NOT NULL
1660
+ )
1661
+ SELECT lowest.id, lowest.lane, lowest.available_at, lowest.handler, lowest.key
1662
+ FROM hops
1663
+ CROSS JOIN LATERAL (
1664
+ SELECT candidate.id, candidate.lane, candidate.available_at, candidate.handler, candidate.key
1665
+ FROM ${deliveries} AS candidate
1666
+ WHERE ${pending} AND candidate.handler = hops.handler AND candidate.key = hops.key
1667
+ ORDER BY candidate.sequence LIMIT 1
1668
+ ) AS lowest
1669
+ WHERE hops.key IS NOT NULL
1670
+ `;
1671
+ }
1672
+ function noRunningDelivery(names, laneAlias) {
1673
+ return `NOT EXISTS (
1674
+ SELECT 1 FROM unnest(${laneAlias}.in_flight) AS flying (id)
1675
+ JOIN ${names.deliveries} AS delivery ON delivery.id = flying.id AND delivery.status = 'pending'
1676
+ )`;
1677
+ }
1678
+
1679
+ // src/statements-claim.ts
1680
+ var LANE_LIST = `ARRAY(SELECT jsonb_array_elements_text($4::jsonb)::smallint)`;
1681
+ var ClaimStatements = class {
1682
+ #names;
1683
+ constructor(names) {
1684
+ this.#names = names;
1048
1685
  }
1049
1686
  /**
1050
1687
  * Fast claim: picks from the first {@link CLAIM_SCAN_WINDOW} due deliveries of
@@ -1116,7 +1753,7 @@ ${this.#pickedRows(`((SELECT count(*) FROM due_window) >= ${CLAIM_SCAN_WINDOW} O
1116
1753
  heads AS MATERIALIZED (
1117
1754
  SELECT head.id, head.lane, head.available_at, head.handler, head.key
1118
1755
  FROM scope
1119
- CROSS JOIN LATERAL (${this.#keyHeads("scope")}) AS head
1756
+ CROSS JOIN LATERAL (${keyHeads(this.#names, "scope")}) AS head
1120
1757
  ), keyed AS MATERIALIZED (
1121
1758
  SELECT heads.id, heads.lane, heads.available_at
1122
1759
  FROM heads
@@ -1235,18 +1872,11 @@ ORDER BY picked.due_at, picked.delivery_id`;
1235
1872
  SET lease_owner = NULL, lease_expires_at = NULL, in_flight = '{}'
1236
1873
  WHERE lane.lane = ANY (ARRAY(SELECT jsonb_array_elements_text($2::jsonb)::smallint))
1237
1874
  AND lane.lease_owner = $3::text
1238
- AND ${this.#noRunningDelivery("lane")}
1875
+ AND ${noRunningDelivery(this.#names, "lane")}
1239
1876
  RETURNING lane.lane
1240
1877
  )
1241
1878
  SELECT (SELECT count(*) FROM extended)::int AS extended, (SELECT count(*) FROM freed)::int AS freed`;
1242
1879
  }
1243
- /** True when none of the lane's listed deliveries exists as a pending row. */
1244
- #noRunningDelivery(laneAlias) {
1245
- return `NOT EXISTS (
1246
- SELECT 1 FROM unnest(${laneAlias}.in_flight) AS flying (id)
1247
- JOIN ${this.#names.deliveries} AS delivery ON delivery.id = flying.id AND delivery.status = 'pending'
1248
- )`;
1249
- }
1250
1880
  /**
1251
1881
  * Keeps in the in-flight lists of the lanes `$1` holds only the claims in `$2`
1252
1882
  * (`[{ id, lane, epoch, claims }]`, the ones this store handed out and nobody
@@ -1289,7 +1919,15 @@ WHERE lane.lane = owned.lane AND lane.lease_owner = $1::text AND lane.claim_floo
1289
1919
  UPDATE ${this.#names.lanes} AS lane
1290
1920
  SET lease_owner = NULL, lease_expires_at = NULL, in_flight = '{}'
1291
1921
  FROM owned
1292
- WHERE lane.lane = owned.lane AND lane.lease_owner = $1::text AND ${this.#noRunningDelivery("lane")}`;
1922
+ WHERE lane.lane = owned.lane AND lane.lease_owner = $1::text AND ${noRunningDelivery(this.#names, "lane")}`;
1923
+ }
1924
+ };
1925
+
1926
+ // src/statements-completion.ts
1927
+ var CompletionStatements = class {
1928
+ #names;
1929
+ constructor(names) {
1930
+ this.#names = names;
1293
1931
  }
1294
1932
  /**
1295
1933
  * Extends the lease of the lane a running delivery belongs to; the lane lease
@@ -1407,919 +2045,929 @@ SELECT ord FROM completed`;
1407
2045
  )
1408
2046
  SELECT count(*)::int AS count FROM changed`;
1409
2047
  }
1410
- /** Parameters: `[deliveryIdsJson, now]`. The dead rows are locked in id order first. */
1411
- get requeue() {
1412
- const deliveries = this.#names.deliveries;
1413
- return countChanged(`WITH dead AS MATERIALIZED (
1414
- SELECT delivery.id FROM ${deliveries} AS delivery
1415
- WHERE delivery.id = ANY (ARRAY(SELECT jsonb_array_elements_text($1::jsonb))) AND delivery.status = 'dead'
1416
- ORDER BY delivery.id
1417
- FOR NO KEY UPDATE
1418
- )
1419
- UPDATE ${deliveries} AS delivery
1420
- SET status = 'pending', attempts = 0, available_at = $2::timestamptz, updated_at = $2::timestamptz
1421
- FROM dead
1422
- WHERE delivery.id = dead.id AND delivery.status = 'dead'`);
2048
+ };
2049
+
2050
+ // src/statements-lanes.ts
2051
+ var FREE_LANE_SURPLUS = 16;
2052
+ function notRunning(running, alias) {
2053
+ return running === null ? "true" : `NOT EXISTS (SELECT 1 FROM ${running} AS running WHERE running.handler = ${alias}.handler AND running.key = ${alias}.key)`;
2054
+ }
2055
+ var freeLane = (alias) => `(${alias}.lease_expires_at IS NULL OR ${alias}.lease_expires_at <= $1::timestamptz
2056
+ OR (${alias}.lease_owner = $4::text AND ${alias}.claim_floor < $6::bigint))`;
2057
+ var NO_FREE_LANES = `), free_lanes AS (
2058
+ SELECT NULL::smallint AS lane, NULL::bigint AS epoch, NULL::text[] AS in_flight, false AS running WHERE false
2059
+ ), free_scope AS (
2060
+ SELECT NULL::smallint AS lane, NULL::bigint AS epoch WHERE false
2061
+ ), free_candidates AS (
2062
+ SELECT NULL::text AS id, NULL::smallint AS lane, NULL::timestamptz AS available_at WHERE false
2063
+ )`;
2064
+ var LaneStatements = class {
2065
+ #names;
2066
+ constructor(names) {
2067
+ this.#names = names;
1423
2068
  }
1424
2069
  /**
1425
- * Builds the filtered, creation-ordered listing. A delivery is `processing`
1426
- * while its row exists as `pending` and its lane lists its id; its attempt
1427
- * count, lease owner and lease expiry then come from the claim and the lane.
1428
- * Records of the completion history (when kept) are listed as `completed`.
2070
+ * A claim in one statement, the only one in the common case. Parameters:
2071
+ * `[now, handlersJson, limit, leaseOwner, leaseExpiresAt, generation]`.
2072
+ *
2073
+ * 1. **Held lanes.** The lanes this owner holds under a live lease whose `claim_floor` is exactly the
2074
+ * generation are locked `FOR NO KEY UPDATE` in lane order. A lane above it was raised by a
2075
+ * reconciliation, so a statement of a claim whose caller gave up (a client timeout does not cancel
2076
+ * the statement on the server) and that reaches the server late records nothing; a lane below it was
2077
+ * taken by such a late statement after the reconciliation, and its listed deliveries were never
2078
+ * handed out. A lane that another transaction of this owner is changing makes the statement wait;
2079
+ * the statement then reports `stale` and does nothing (see the `stale` CTE).
2080
+ * 2. **Free lanes**, only when the held lanes yield fewer than `limit`: the free lanes with a due
2081
+ * delivery (one index probe per free lane) are ranked by their oldest due delivery; the first
2082
+ * {@link INITIAL_FREE_LANES} that can give something now, and further ones until what they can give
2083
+ * (estimated from their first {@link LANE_DEPTH_CAP} due deliveries) covers what is still wanted, are locked
2084
+ * `FOR UPDATE SKIP LOCKED`, so a lane another claimer has is skipped, never waited
2085
+ * for. A lane that still runs deliveries of an expired lease is left to the transaction of
2086
+ * {@link takeFreeLanes}, which charges their lost attempts (`takeover_waiting`); so is any lane whose
2087
+ * locked row differs from what the statement's snapshot saw. A lane that runs nothing and did not
2088
+ * change cannot have had a delivery written since the snapshot, so its deliveries can be read here.
2089
+ * 3. **Picks** follow the rules of `ClaimStatements.claim`: the fast window of each lane, and for lanes whose
2090
+ * window filled up while the batch is not full, the heads of all keys (a loose index scan per lane).
2091
+ * 4. **Writes**: one update per lane. A held lane records its picks; a taken lane gets a new epoch, the
2092
+ * owner, the lease and its picks; a taken lane that yielded nothing is not written. Held lanes that
2093
+ * picked nothing, run nothing and have no full scan window are freed.
2094
+ *
2095
+ * Always returns one row per picked delivery, or one row whose `delivery_id` is null. `running_ids`
2096
+ * (JSON text) lists the deliveries the held lanes still run, `examined_lanes` the held lanes.
1429
2097
  */
1430
- listDeliveries(query) {
1431
- const parameters = [];
1432
- const bind = (value) => {
1433
- parameters.push(value);
1434
- return `$${parameters.length}::${typeof value === "number" ? "int" : "text"}`;
1435
- };
1436
- const filters = {
1437
- handler: query.handler === void 0 ? void 0 : bind(query.handler),
1438
- eventType: query.eventType === void 0 ? void 0 : bind(query.eventType),
1439
- eventId: query.eventId === void 0 ? void 0 : bind(query.eventId),
1440
- status: query.status === void 0 ? void 0 : bind(query.status)
1441
- };
1442
- const limit = bind(query.limit ?? DEFAULT_LIST_LIMIT);
1443
- const common = (alias) => [
1444
- ...filters.handler === void 0 ? [] : [`${alias}.handler = ${filters.handler}`],
1445
- ...filters.eventType === void 0 ? [] : [`event.type = ${filters.eventType}`],
1446
- ...filters.eventId === void 0 ? [] : [`${alias}.event_id = ${filters.eventId}`]
1447
- ];
1448
- const inFlight = `(delivery.status = 'pending' AND delivery.id = ANY (lane.in_flight))`;
1449
- const whereCurrent = [
1450
- ...common("delivery"),
1451
- ...filters.status === void 0 ? [] : [
1452
- `(CASE WHEN ${inFlight} THEN 'processing' ELSE delivery.status END) = ${filters.status}`
1453
- ]
1454
- ];
1455
- const current = `SELECT delivery.id AS delivery_id, delivery.handler,
1456
- CASE WHEN ${inFlight} THEN 'processing' ELSE delivery.status END AS status,
1457
- (delivery.attempts + CASE WHEN ${inFlight} THEN 1 ELSE 0 END)::int AS attempts,
1458
- ${isoText("delivery.available_at")} AS available_at,
1459
- CASE WHEN ${inFlight} THEN lane.lease_owner END AS lease_owner,
1460
- CASE WHEN ${inFlight} THEN ${isoText("lane.lease_expires_at")} END AS lease_expires_at,
1461
- delivery.last_error::text AS last_error,
1462
- ${isoText("delivery.created_at")} AS created_at,
1463
- ${isoText("delivery.updated_at")} AS updated_at,
1464
- ${isoText("delivery.completed_at")} AS completed_at,
1465
- ${eventColumns("event")}
1466
- FROM ${this.#names.deliveries} AS delivery
1467
- JOIN ${this.#names.lanes} AS lane ON lane.lane = delivery.lane
1468
- JOIN ${this.#names.events} AS event ON event.id = delivery.event_id
1469
- ${whereCurrent.length === 0 ? "" : `WHERE ${whereCurrent.join(" AND ")}`}`;
1470
- const includeHistory = this.#names.completionHistory && (query.status === void 0 || query.status === "completed");
1471
- if (!includeHistory) {
1472
- return {
1473
- sql: `${current}
1474
- ORDER BY delivery.created_at, delivery.id
1475
- LIMIT ${limit}`,
1476
- parameters
1477
- };
1478
- }
1479
- const history = `SELECT done.id AS delivery_id, done.handler, 'completed' AS status, done.attempts,
1480
- ${isoText("done.available_at")} AS available_at,
1481
- NULL AS lease_owner,
1482
- NULL AS lease_expires_at,
1483
- NULL AS last_error,
1484
- ${isoText("done.created_at")} AS created_at,
1485
- ${isoText("done.completed_at")} AS updated_at,
1486
- ${isoText("done.completed_at")} AS completed_at,
1487
- ${eventColumns("event")}
1488
- FROM ${this.#names.completions} AS done
1489
- JOIN ${this.#names.events} AS event ON event.id = done.event_id
1490
- ${common("done").length === 0 ? "" : `WHERE ${common("done").join(" AND ")}`}`;
1491
- return {
1492
- sql: `SELECT * FROM (
1493
- ${current}
1494
- UNION ALL
1495
- ${history}
1496
- ) AS listed
1497
- ORDER BY created_at, delivery_id
1498
- LIMIT ${limit}`,
1499
- parameters
1500
- };
2098
+ get claimLanes() {
2099
+ return this.#claimLanes(true);
1501
2100
  }
1502
2101
  /**
1503
- * Counts of rows by stored status (`pending` includes running deliveries;
1504
- * `completed` rows exist only after an upgrade from 0.1.0). Each count is
1505
- * answered from a partial index.
2102
+ * {@link claimLanes} limited to the lanes the owner holds: the same parameters, rows and writes, without
2103
+ * looking at free lanes (`takeover_waiting` and `unexamined_free_lanes` are false). A worker draining a
2104
+ * backlog finds its batch in the lanes it holds; this statement is about half as costly to plan, and
2105
+ * the caller runs {@link claimLanes} after it only when it came up short.
1506
2106
  */
1507
- get countByStatus() {
1508
- const deliveries = this.#names.deliveries;
1509
- return ["pending", "dead", "completed"].map(
1510
- (status) => `SELECT '${status}' AS status, count(*)::text AS count FROM ${deliveries} WHERE status = '${status}'`
1511
- ).join("\nUNION ALL\n");
2107
+ get claimHeldLanes() {
2108
+ return this.#claimLanes(false);
1512
2109
  }
1513
- /** Deliveries that are running: listed by a lane and still pending as rows. */
1514
- get countRunning() {
1515
- return `SELECT count(*)::text AS count
1516
- FROM ${this.#names.lanes} AS lane
1517
- CROSS JOIN LATERAL unnest(lane.in_flight) AS flying (id)
1518
- JOIN ${this.#names.deliveries} AS delivery ON delivery.id = flying.id AND delivery.status = 'pending'`;
2110
+ #claimLanes(includeFreeLanes) {
2111
+ const free = includeFreeLanes ? this.#freeLaneChoice() + this.#freeLaneDepth() + this.#freeLaneTake() : NO_FREE_LANES;
2112
+ return this.#heldLanes() + free + this.#claimPicks() + this.#claimRecord() + this.#claimRelease();
1519
2113
  }
1520
- get countCompletionHistory() {
1521
- return `SELECT count(*)::text AS count FROM ${this.#names.completions}`;
2114
+ /** Locks the held lanes, detects a stale snapshot and picks from the held lanes; ends with `wanted`. */
2115
+ #heldLanes() {
2116
+ const deliveries = this.#names.deliveries;
2117
+ const lanes = this.#names.lanes;
2118
+ return `WITH held AS MATERIALIZED (
2119
+ SELECT lane.lane, lane.epoch, lane.in_flight
2120
+ FROM ${lanes} AS lane
2121
+ WHERE lane.lease_owner = $4::text AND lane.lease_expires_at > $1::timestamptz
2122
+ AND lane.claim_floor = $6::bigint
2123
+ ORDER BY lane.lane
2124
+ FOR NO KEY UPDATE
2125
+ ), stale AS (
2126
+ -- A claim that waited for a lane lock sees the new lane row but reads deliveries with the snapshot it took
2127
+ -- before the wait: whatever changed the lane meanwhile (a reschedule, a release) may also have changed
2128
+ -- deliveries it cannot see. The statement then does nothing and reports it, and the caller runs it again.
2129
+ SELECT EXISTS (
2130
+ SELECT 1 FROM held
2131
+ JOIN ${lanes} AS before ON before.lane = held.lane
2132
+ WHERE before.epoch <> held.epoch OR before.in_flight IS DISTINCT FROM held.in_flight
2133
+ ) AS value
2134
+ ), held_scope AS MATERIALIZED (
2135
+ SELECT held.lane, held.epoch, held.in_flight FROM held WHERE NOT (SELECT value FROM stale)
2136
+ ), held_running AS MATERIALIZED (
2137
+ SELECT delivery.handler, delivery.key
2138
+ FROM held_scope
2139
+ CROSS JOIN LATERAL unnest(held_scope.in_flight) AS flying (id)
2140
+ JOIN ${deliveries} AS delivery ON delivery.id = flying.id
2141
+ WHERE delivery.status = 'pending' AND delivery.key IS NOT NULL
2142
+ ), ${this.#candidates("held", { scope: "held_scope", running: "held_running", limit: "$3::int" })}, wanted AS MATERIALIZED (
2143
+ SELECT CASE WHEN (SELECT value FROM stale) THEN 0
2144
+ ELSE $3::int - (SELECT count(*) FROM held_candidates)::int END AS count
2145
+ `;
1522
2146
  }
1523
- /**
1524
- * Oldest instant at which a delivery became claimable: `available_at` of a
1525
- * pending delivery that nobody runs, or the lease expiry of a lane that runs
1526
- * deliveries. Parameters: `[now]`.
1527
- */
1528
- get oldestDue() {
2147
+ /** The oldest due delivery of each free lane, at most the number still wanted plus a surplus. */
2148
+ #freeLaneChoice() {
1529
2149
  const deliveries = this.#names.deliveries;
1530
2150
  const lanes = this.#names.lanes;
1531
- return `SELECT ${isoText("min(due.due_at)")} AS oldest_due_at FROM (
1532
- SELECT waiting.available_at AS due_at
2151
+ return `), free_lanes AS MATERIALIZED (
2152
+ -- The oldest due delivery of each free lane: one index probe per free lane, bounded by the due time,
2153
+ -- so deliveries scheduled for later are never read.
2154
+ SELECT lane.lane, lane.epoch, lane.in_flight, lane.lease_owner, lane.lease_expires_at,
2155
+ oldest.available_at, oldest.id, NOT ${noRunningDelivery(this.#names, "lane")} AS running
1533
2156
  FROM ${lanes} AS lane
1534
2157
  CROSS JOIN LATERAL (
1535
- SELECT delivery.available_at FROM ${deliveries} AS delivery
2158
+ SELECT delivery.available_at, delivery.id
2159
+ FROM ${deliveries} AS delivery
1536
2160
  WHERE delivery.lane = lane.lane AND delivery.status = 'pending'
1537
- AND delivery.available_at <= $1::timestamptz AND delivery.id <> ALL (lane.in_flight)
1538
- ORDER BY delivery.available_at LIMIT 1
1539
- ) AS waiting
1540
- UNION ALL
1541
- SELECT lane.lease_expires_at AS due_at
1542
- FROM ${lanes} AS lane
1543
- WHERE lane.lease_expires_at <= $1::timestamptz AND NOT ${this.#noRunningDelivery("lane")}
1544
- ) AS due`;
2161
+ AND delivery.available_at <= $1::timestamptz AND ${HANDLER_PREDICATE}
2162
+ ORDER BY delivery.available_at, delivery.id
2163
+ LIMIT 1
2164
+ ) AS oldest
2165
+ WHERE (SELECT count FROM wanted) > 0 AND ${freeLane("lane")}
2166
+ ORDER BY oldest.available_at, oldest.id
2167
+ LIMIT (SELECT count FROM wanted) + ${FREE_LANE_SURPLUS}
2168
+ `;
1545
2169
  }
1546
- /**
1547
- * Deletes one bounded batch of purgeable deliveries (or of the completion
1548
- * history) and returns the event id of each deleted row. Parameters:
1549
- * `[cutoff, batchSize]`. `FOR UPDATE SKIP LOCKED` keeps purge from waiting
1550
- * on, or being waited on by, anything.
1551
- */
1552
- purgeCompletedBatch() {
1553
- return this.#purgeBatch(
1554
- this.#names.deliveries,
1555
- `status = 'completed' AND completed_at < $1::timestamptz`,
1556
- "completed_at"
1557
- );
2170
+ /** What each free candidate lane can give now, and their order. */
2171
+ #freeLaneDepth() {
2172
+ const deliveries = this.#names.deliveries;
2173
+ return `), free_depth AS MATERIALIZED (
2174
+ -- What each candidate lane can give now, from its first due deliveries: unkeyed ones, and of a key its
2175
+ -- lowest one when nothing earlier of the key is pending. Lanes that can give nothing are passed over;
2176
+ -- of the others, the first ${INITIAL_FREE_LANES} are taken, and further ones until they cover what is
2177
+ -- still wanted, so the earliest due work of the free lanes comes first.
2178
+ SELECT runnable.lane,
2179
+ row_number() OVER (ORDER BY runnable.available_at, runnable.id) AS rank,
2180
+ sum(runnable.count) OVER (ORDER BY runnable.available_at, runnable.id ROWS UNBOUNDED PRECEDING) - runnable.count AS due_before
2181
+ FROM (
2182
+ SELECT lane_candidate.lane, lane_candidate.available_at, lane_candidate.id, depth.count
2183
+ FROM free_lanes AS lane_candidate
2184
+ CROSS JOIN LATERAL (
2185
+ -- A full window that shows nothing runnable may hide runnable work behind it: such a lane counts
2186
+ -- once, and the claim looks behind its blocked deliveries.
2187
+ SELECT GREATEST(count(*) FILTER (
2188
+ WHERE due.key IS NULL OR (due.position = 1 AND NOT EXISTS (
2189
+ SELECT 1 FROM ${deliveries} AS earlier
2190
+ WHERE earlier.lane = due.lane AND earlier.handler = due.handler AND earlier.key = due.key
2191
+ AND earlier.status = 'pending' AND earlier.key IS NOT NULL AND earlier.sequence < due.sequence
2192
+ ))
2193
+ ), CASE WHEN count(*) >= ${LANE_DEPTH_CAP} THEN 1 ELSE 0 END) AS count
2194
+ FROM (
2195
+ SELECT window_rows.*,
2196
+ row_number() OVER (PARTITION BY window_rows.handler, window_rows.key ORDER BY window_rows.sequence) AS position
2197
+ FROM (
2198
+ SELECT delivery.lane, delivery.handler, delivery.key, delivery.sequence FROM ${deliveries} AS delivery
2199
+ WHERE delivery.lane = lane_candidate.lane AND delivery.status = 'pending'
2200
+ AND delivery.available_at <= $1::timestamptz AND ${HANDLER_PREDICATE}
2201
+ ORDER BY delivery.available_at, delivery.id
2202
+ LIMIT ${LANE_DEPTH_CAP}
2203
+ ) AS window_rows
2204
+ ) AS due
2205
+ ) AS depth
2206
+ WHERE NOT lane_candidate.running AND depth.count > 0
2207
+ ) AS runnable
2208
+ `;
1558
2209
  }
1559
- purgeCompletionHistoryBatch() {
1560
- return this.#purgeBatch(
1561
- this.#names.completions,
1562
- `completed_at < $1::timestamptz`,
1563
- "completed_at"
1564
- );
2210
+ /** Locks the chosen free lanes that did not change hands and picks from them. */
2211
+ #freeLaneTake() {
2212
+ const lanes = this.#names.lanes;
2213
+ return `), free_locked AS MATERIALIZED (
2214
+ SELECT lane.lane, lane.epoch, lane.in_flight, lane.lease_owner, lane.lease_expires_at
2215
+ FROM ${lanes} AS lane
2216
+ WHERE lane.lane IN (
2217
+ SELECT chosen.lane FROM free_depth AS chosen
2218
+ WHERE chosen.rank <= ${INITIAL_FREE_LANES} OR chosen.due_before < (SELECT count FROM wanted)
2219
+ )
2220
+ AND ${freeLane("lane")}
2221
+ ORDER BY lane.lane
2222
+ FOR UPDATE SKIP LOCKED
2223
+ ), free_scope AS MATERIALIZED (
2224
+ -- A lane whose locked row is not the one the snapshot saw changed hands meanwhile: left for a later claim.
2225
+ SELECT locked.lane, locked.epoch + 1 AS epoch, '{}'::text[] AS in_flight
2226
+ FROM free_locked AS locked
2227
+ JOIN free_lanes AS seen ON seen.lane = locked.lane
2228
+ WHERE locked.epoch = seen.epoch AND locked.in_flight = seen.in_flight
2229
+ AND locked.lease_owner IS NOT DISTINCT FROM seen.lease_owner
2230
+ AND locked.lease_expires_at IS NOT DISTINCT FROM seen.lease_expires_at
2231
+ ), ${this.#candidates("free", { scope: "free_scope", running: null, limit: "(SELECT count FROM wanted)" })}`;
1565
2232
  }
1566
- purgeDeadBatch() {
1567
- return this.#purgeBatch(
1568
- this.#names.deliveries,
1569
- `status = 'dead' AND updated_at < $1::timestamptz`,
1570
- "updated_at"
1571
- );
2233
+ /** The picked deliveries of held and taken lanes with their events, and the picks per lane. */
2234
+ #claimPicks() {
2235
+ const deliveries = this.#names.deliveries;
2236
+ return `, claim_scope AS MATERIALIZED (
2237
+ SELECT held_scope.lane, held_scope.epoch FROM held_scope
2238
+ UNION ALL
2239
+ SELECT free_scope.lane, free_scope.epoch FROM free_scope
2240
+ ), picked_rows AS MATERIALIZED (
2241
+ SELECT candidates.available_at AS due_at, delivery.id AS delivery_id, delivery.lane::int AS lane,
2242
+ scope.epoch::text AS epoch, delivery.claims AS claims, delivery.handler, delivery.key AS delivery_key, delivery.sequence::text AS sequence, (delivery.attempts + 1)::int AS attempt,
2243
+ ${eventColumns("event")}
2244
+ FROM (
2245
+ SELECT held_candidates.id, held_candidates.lane, held_candidates.available_at FROM held_candidates
2246
+ UNION ALL
2247
+ SELECT free_candidates.id, free_candidates.lane, free_candidates.available_at FROM free_candidates
2248
+ ) AS candidates
2249
+ JOIN claim_scope AS scope ON scope.lane = candidates.lane
2250
+ JOIN ${deliveries} AS delivery ON delivery.id = candidates.id
2251
+ JOIN ${this.#names.events} AS event ON event.id = delivery.event_id
2252
+ ), by_lane AS (
2253
+ SELECT picked_rows.lane, array_agg(picked_rows.delivery_id) AS ids FROM picked_rows GROUP BY picked_rows.lane
2254
+ `;
1572
2255
  }
1573
- /**
1574
- * Selects and locks one bounded batch of events created before the cutoff
1575
- * that no delivery references and that never had a delivery complete (those
1576
- * are measured from their completion, see {@link lockCompletedOrphanEventsBatch}).
1577
- * Parameters: `[cutoff, batchSize]`. The ids go through
1578
- * {@link deleteOrphanEventsWithoutCompletion} or {@link deleteExpiredCompletedOrphanEvents}, which re-check under a fresh snapshot.
1579
- */
1580
- get lockOrphanEventsBatch() {
1581
- return `SELECT event.id FROM ${this.#names.events} AS event
1582
- WHERE event.created_at < $1::timestamptz
1583
- AND ${this.#unreferenced("event")}
1584
- AND NOT EXISTS (SELECT 1 FROM ${this.#names.eventCompletions} AS completion WHERE completion.event_id = event.id)
1585
- ORDER BY event.created_at, event.id
1586
- LIMIT $2::int
1587
- FOR UPDATE OF event SKIP LOCKED`;
2256
+ /** Records the picks in the held lanes and takes the free lanes that yielded picks. */
2257
+ #claimRecord() {
2258
+ const deliveries = this.#names.deliveries;
2259
+ const lanes = this.#names.lanes;
2260
+ return `), still_running AS (
2261
+ -- The retained ids come from the locked \`held\` rows, not from the lane table: a claim that waited for the lock
2262
+ -- must see the in-flight list the claim before it recorded, which the statement snapshot may not.
2263
+ SELECT held.lane, array_agg(delivery.id) AS ids
2264
+ FROM by_lane
2265
+ JOIN held ON held.lane = by_lane.lane
2266
+ CROSS JOIN LATERAL unnest(held.in_flight) AS flying (id)
2267
+ JOIN ${deliveries} AS delivery ON delivery.id = flying.id AND delivery.status = 'pending'
2268
+ GROUP BY held.lane
2269
+ ), extended AS (
2270
+ UPDATE ${lanes} AS lane
2271
+ SET in_flight = COALESCE(still_running.ids, '{}') || by_lane.ids,
2272
+ lease_expires_at = GREATEST(lane.lease_expires_at, $5::timestamptz)
2273
+ FROM by_lane
2274
+ JOIN held_scope ON held_scope.lane = by_lane.lane
2275
+ LEFT JOIN still_running ON still_running.lane = by_lane.lane
2276
+ WHERE lane.lane = by_lane.lane
2277
+ RETURNING lane.lane
2278
+ ), taken AS (
2279
+ UPDATE ${lanes} AS lane
2280
+ SET epoch = free_scope.epoch, lease_owner = $4::text, lease_expires_at = $5::timestamptz,
2281
+ in_flight = by_lane.ids, claim_floor = $6::bigint
2282
+ FROM free_scope
2283
+ JOIN by_lane ON by_lane.lane = free_scope.lane
2284
+ WHERE lane.lane = free_scope.lane
2285
+ RETURNING lane.lane
2286
+ `;
1588
2287
  }
1589
- /**
1590
- * Like {@link lockOrphanEventsBatch} for events that had a delivery complete:
1591
- * they go once their last completion is older than the cutoff, however old the
1592
- * event itself is. Parameters: `[cutoff, batchSize]`.
1593
- */
1594
- get lockCompletedOrphanEventsBatch() {
1595
- return `SELECT event.id FROM ${this.#names.events} AS event
1596
- JOIN ${this.#names.eventCompletions} AS completion ON completion.event_id = event.id
1597
- WHERE completion.completed_at < $1::timestamptz
1598
- AND ${this.#unreferenced("event")}
1599
- ORDER BY completion.completed_at, event.id
1600
- LIMIT $2::int
1601
- FOR UPDATE OF event SKIP LOCKED`;
2288
+ /** Frees the held lanes that yielded nothing and run nothing, and selects the result rows. */
2289
+ #claimRelease() {
2290
+ const deliveries = this.#names.deliveries;
2291
+ const lanes = this.#names.lanes;
2292
+ return `), saturated_lanes AS (
2293
+ SELECT held_window.lane FROM held_window GROUP BY held_window.lane HAVING count(*) >= ${LANE_SCAN_WINDOW}
2294
+ ), freed AS (
2295
+ UPDATE ${lanes} AS lane
2296
+ SET lease_owner = NULL, lease_expires_at = NULL, in_flight = '{}'
2297
+ FROM held
2298
+ WHERE lane.lane = held.lane
2299
+ AND lane.lane NOT IN (SELECT lane FROM by_lane)
2300
+ AND lane.lane NOT IN (SELECT lane FROM saturated_lanes)
2301
+ AND (SELECT count(*) FROM held_window) < ${CLAIM_SCAN_WINDOW}
2302
+ AND NOT (SELECT value FROM stale)
2303
+ AND ${noRunningDelivery(this.#names, "lane")}
2304
+ RETURNING lane.lane
2305
+ )
2306
+ SELECT (SELECT value FROM stale) AS stale,
2307
+ EXISTS (SELECT 1 FROM free_lanes WHERE free_lanes.running) AS takeover_waiting,
2308
+ (SELECT count(*) FROM free_lanes) = (SELECT count FROM wanted) + ${FREE_LANE_SURPLUS} AS unexamined_free_lanes,
2309
+ (
2310
+ SELECT COALESCE(jsonb_agg(delivery.id), '[]'::jsonb)
2311
+ FROM held
2312
+ CROSS JOIN LATERAL unnest(held.in_flight) AS flying (id)
2313
+ JOIN ${deliveries} AS delivery ON delivery.id = flying.id AND delivery.status = 'pending'
2314
+ )::text AS running_ids,
2315
+ (SELECT COALESCE(jsonb_agg(held.lane), '[]'::jsonb) FROM held)::text AS examined_lanes,
2316
+ picked.*
2317
+ FROM (SELECT 1) AS anchor
2318
+ LEFT JOIN picked_rows AS picked ON true
2319
+ ORDER BY picked.due_at, picked.delivery_id`;
1602
2320
  }
1603
2321
  /**
1604
- * Locks the given events, skipping any that a concurrent transaction is
1605
- * referencing from a new delivery (a foreign key check holds `FOR KEY
1606
- * SHARE`, which conflicts with this lock). Parameters: `[eventIdsJson]`.
2322
+ * CTEs that pick up to `limit` claimable deliveries from the lanes of the CTE `scope` (columns `lane`,
2323
+ * `epoch`, `in_flight`), named after `prefix`; the result is `<prefix>_candidates (id, lane, available_at)`.
2324
+ * The rules are those of `ClaimStatements.claim`. The fast window reads the first {@link LANE_SCAN_WINDOW} due
2325
+ * deliveries of each lane (at most {@link CLAIM_SCAN_WINDOW} together); of a key, only the lowest sequence
2326
+ * in the window can be its head, so only that one is checked for an earlier pending delivery. Only when
2327
+ * that yields fewer than `limit` are the lanes whose window filled up looked at again with a loose index
2328
+ * scan over the heads of all their keys. `running` names the CTE of the keyed deliveries running in the
2329
+ * lanes, or is null when nothing runs there.
1607
2330
  */
1608
- get lockEvents() {
1609
- return `SELECT id FROM ${this.#names.events}
1610
- WHERE id = ANY (ARRAY(SELECT jsonb_array_elements_text($1::jsonb)))
1611
- FOR UPDATE SKIP LOCKED`;
2331
+ #candidates(prefix, {
2332
+ scope,
2333
+ running,
2334
+ limit
2335
+ }) {
2336
+ const spec = { prefix, scope, running, limit };
2337
+ return this.#fastCandidates(spec) + this.#slowCandidates(spec);
2338
+ }
2339
+ /** The fast window of each lane and the claimable deliveries in it (`<prefix>_window`, `<prefix>_fast`). */
2340
+ #fastCandidates({ prefix, scope, running, limit }) {
2341
+ const deliveries = this.#names.deliveries;
2342
+ return `${prefix}_window AS MATERIALIZED (
2343
+ SELECT recent.id, recent.lane, recent.available_at, recent.handler, recent.key, recent.sequence
2344
+ FROM ${scope}
2345
+ CROSS JOIN LATERAL (
2346
+ SELECT delivery.id, delivery.lane, delivery.available_at, delivery.handler, delivery.key, delivery.sequence
2347
+ FROM ${deliveries} AS delivery
2348
+ WHERE delivery.lane = ${scope}.lane AND delivery.status = 'pending'
2349
+ AND delivery.available_at <= $1::timestamptz AND ${HANDLER_PREDICATE}
2350
+ AND delivery.id <> ALL (${scope}.in_flight)
2351
+ ORDER BY delivery.available_at, delivery.id
2352
+ LIMIT ${LANE_SCAN_WINDOW}
2353
+ ) AS recent
2354
+ ORDER BY recent.available_at, recent.id
2355
+ LIMIT ${CLAIM_SCAN_WINDOW}
2356
+ ), ${prefix}_fast AS MATERIALIZED (
2357
+ SELECT picked.id, picked.lane, picked.available_at FROM (
2358
+ SELECT unkeyed.id, unkeyed.lane, unkeyed.available_at FROM ${prefix}_window AS unkeyed WHERE unkeyed.key IS NULL
2359
+ UNION ALL
2360
+ SELECT head.id, head.lane, head.available_at
2361
+ FROM (
2362
+ SELECT DISTINCT ON (keyed.handler, keyed.key) keyed.id, keyed.lane, keyed.available_at, keyed.handler, keyed.key, keyed.sequence
2363
+ FROM ${prefix}_window AS keyed
2364
+ WHERE keyed.key IS NOT NULL
2365
+ ORDER BY keyed.handler, keyed.key, keyed.sequence
2366
+ ) AS head
2367
+ WHERE NOT EXISTS (
2368
+ SELECT 1 FROM ${deliveries} AS earlier
2369
+ WHERE earlier.lane = head.lane AND earlier.handler = head.handler AND earlier.key = head.key
2370
+ AND earlier.status = 'pending' AND earlier.key IS NOT NULL AND earlier.sequence < head.sequence
2371
+ ) AND ${notRunning(running, "head")}
2372
+ ) AS picked
2373
+ ORDER BY picked.available_at, picked.id
2374
+ LIMIT ${limit}
2375
+ `;
1612
2376
  }
1613
2377
  /**
1614
- * Deletes events that no delivery references and whose last completion is older than
1615
- * `$2`, checked again under the fresh snapshot of this statement: a completion recorded
1616
- * after the sweep selected the event moves its time and keeps the event. Parameters:
1617
- * `[eventIdsJson, cutoff]`.
2378
+ * For lanes whose window filled up while the fast pick came up short: the heads of all their keys and
2379
+ * their unkeyed deliveries, then the union with the fast pick (`<prefix>_candidates`).
1618
2380
  */
1619
- get deleteExpiredCompletedOrphanEvents() {
1620
- return countChanged(`DELETE FROM ${this.#names.events} AS event
1621
- WHERE event.id = ANY (ARRAY(SELECT jsonb_array_elements_text($1::jsonb)))
1622
- AND ${this.#unreferenced("event")}
1623
- AND EXISTS (
1624
- SELECT 1 FROM ${this.#names.eventCompletions} AS completion
1625
- WHERE completion.event_id = event.id AND completion.completed_at < $2::timestamptz
1626
- )`);
2381
+ #slowCandidates({ prefix, scope, running, limit }) {
2382
+ const deliveries = this.#names.deliveries;
2383
+ return `), ${prefix}_saturated AS MATERIALIZED (
2384
+ SELECT ${scope}.lane, ${scope}.in_flight FROM ${scope}
2385
+ WHERE (SELECT count(*) FROM ${prefix}_fast) < ${limit}
2386
+ AND ((SELECT count(*) FROM ${prefix}_window) >= ${CLAIM_SCAN_WINDOW}
2387
+ OR ${scope}.lane IN (
2388
+ SELECT full_lane.lane FROM ${prefix}_window AS full_lane
2389
+ GROUP BY full_lane.lane HAVING count(*) >= ${LANE_SCAN_WINDOW}
2390
+ ))
2391
+ ), ${prefix}_heads AS MATERIALIZED (
2392
+ SELECT head.id, head.lane, head.available_at, head.handler, head.key
2393
+ FROM ${prefix}_saturated AS scope
2394
+ CROSS JOIN LATERAL (${keyHeads(this.#names, "scope")}) AS head
2395
+ ), ${prefix}_keyed AS MATERIALIZED (
2396
+ SELECT heads.id, heads.lane, heads.available_at
2397
+ FROM ${prefix}_heads AS heads
2398
+ JOIN ${prefix}_saturated AS scope ON scope.lane = heads.lane
2399
+ WHERE heads.available_at <= $1::timestamptz AND heads.id <> ALL (scope.in_flight) AND ${notRunning(running, "heads")}
2400
+ ORDER BY heads.available_at, heads.id
2401
+ LIMIT ${limit}
2402
+ ), ${prefix}_unkeyed AS MATERIALIZED (
2403
+ SELECT recent.id, recent.lane, recent.available_at
2404
+ FROM ${prefix}_saturated AS scope
2405
+ CROSS JOIN LATERAL (
2406
+ SELECT delivery.id, delivery.lane, delivery.available_at
2407
+ FROM ${deliveries} AS delivery
2408
+ WHERE delivery.lane = scope.lane AND delivery.key IS NULL AND delivery.status = 'pending'
2409
+ AND delivery.available_at <= $1::timestamptz AND ${HANDLER_PREDICATE}
2410
+ AND delivery.id <> ALL (scope.in_flight)
2411
+ ORDER BY delivery.available_at, delivery.id
2412
+ LIMIT ${limit}
2413
+ ) AS recent
2414
+ ORDER BY recent.available_at, recent.id
2415
+ LIMIT ${limit}
2416
+ ), ${prefix}_candidates AS MATERIALIZED (
2417
+ SELECT chosen.id, chosen.lane, chosen.available_at FROM (
2418
+ SELECT fast.id, fast.lane, fast.available_at FROM ${prefix}_fast AS fast
2419
+ UNION
2420
+ SELECT keyed.id, keyed.lane, keyed.available_at FROM ${prefix}_keyed AS keyed
2421
+ UNION
2422
+ SELECT unkeyed.id, unkeyed.lane, unkeyed.available_at FROM ${prefix}_unkeyed AS unkeyed
2423
+ ) AS chosen
2424
+ ORDER BY chosen.available_at, chosen.id
2425
+ LIMIT ${limit}
2426
+ )`;
1627
2427
  }
1628
2428
  /**
1629
- * Deletes locked events that no delivery references and that never had a delivery complete.
1630
- * It must run as a statement of its own after {@link lockEvents}: it then takes a fresh
1631
- * snapshot that includes every delivery committed before the lock was granted, so an event
1632
- * that just gained a delivery is never cascaded away. Keeps events that had a delivery complete:
1633
- * deleting dead letters must not shorten the retention of completed work.
2429
+ * Takes up to `$3` free lanes (no lease, or an expired one) that have a due
2430
+ * delivery of the requested handlers, the ones with the oldest due delivery
2431
+ * first. Parameters: `[now, handlersJson, laneCount, leaseOwner, leaseExpiresAt, generation]`.
2432
+ * The lane gets the owner's `generation` as its `claim_floor`. A lane the owner itself holds under a live
2433
+ * lease with a lower floor was taken by a claim statement that reached the server after its caller gave up
2434
+ * and the owner reconciled (or by an earlier incarnation of the same owner): it is taken over like the lane of a
2435
+ * crashed worker, so its listed deliveries are charged an attempt.
2436
+ *
2437
+ * A taken lane gets a new epoch, which fences everything the previous owner
2438
+ * still holds. Deliveries the previous owner had in flight are the ones whose
2439
+ * attempt was never recorded (a claim writes no delivery row), so each of
2440
+ * them is charged one attempt here: a worker that crashes with a poison
2441
+ * message still runs it into the retry limit. Lanes another claimer has locked
2442
+ * are skipped, never waited for.
1634
2443
  */
1635
- get deleteOrphanEventsWithoutCompletion() {
1636
- return countChanged(`DELETE FROM ${this.#names.events} AS event
1637
- WHERE event.id = ANY (ARRAY(SELECT jsonb_array_elements_text($1::jsonb)))
1638
- AND ${this.#unreferenced("event")}
1639
- AND NOT EXISTS (SELECT 1 FROM ${this.#names.eventCompletions} AS completion WHERE completion.event_id = event.id)`);
1640
- }
1641
- /** True when no delivery and no completion history record references the event. */
1642
- #unreferenced(eventAlias) {
1643
- const history = this.#names.completionHistory ? ` AND NOT EXISTS (SELECT 1 FROM ${this.#names.completions} AS done WHERE done.event_id = ${eventAlias}.id)` : "";
1644
- return `NOT EXISTS (SELECT 1 FROM ${this.#names.deliveries} AS delivery WHERE delivery.event_id = ${eventAlias}.id)${history}`;
1645
- }
1646
- #purgeBatch(table, condition, orderColumn) {
1647
- return `WITH batch AS MATERIALIZED (
1648
- SELECT id FROM ${table}
1649
- WHERE ${condition}
1650
- ORDER BY ${orderColumn}, id
1651
- LIMIT $2::int
1652
- FOR UPDATE SKIP LOCKED
1653
- ), deleted AS (
1654
- DELETE FROM ${table} AS delivery USING batch WHERE delivery.id = batch.id RETURNING delivery.event_id
2444
+ get takeFreeLanes() {
2445
+ const deliveries = this.#names.deliveries;
2446
+ const lanes = this.#names.lanes;
2447
+ return `WITH picked AS (
2448
+ -- in_flight is read here, from the locked version of the lane: a settlement that committed after the
2449
+ -- statement took its snapshot has taken its delivery out of the list already and must not be charged again.
2450
+ SELECT free.lane, free.in_flight
2451
+ FROM ${lanes} AS free
2452
+ CROSS JOIN LATERAL (
2453
+ SELECT delivery.available_at, delivery.id
2454
+ FROM ${deliveries} AS delivery
2455
+ WHERE delivery.lane = free.lane AND delivery.status = 'pending'
2456
+ AND delivery.available_at <= $1::timestamptz AND ${HANDLER_PREDICATE}
2457
+ ORDER BY delivery.available_at, delivery.id
2458
+ LIMIT 1
2459
+ ) AS oldest
2460
+ WHERE free.lease_expires_at IS NULL OR free.lease_expires_at <= $1::timestamptz
2461
+ OR (free.lease_owner = $4::text AND free.claim_floor < $6::bigint)
2462
+ ORDER BY oldest.available_at, oldest.id
2463
+ LIMIT $3::int
2464
+ FOR UPDATE OF free SKIP LOCKED
2465
+ ), charged AS (
2466
+ UPDATE ${deliveries} AS delivery SET attempts = delivery.attempts + 1, claims = delivery.claims + 1
2467
+ FROM (
2468
+ SELECT unnest(picked.in_flight) AS id FROM picked
2469
+ ) AS lost
2470
+ WHERE delivery.id = lost.id AND delivery.status = 'pending'
2471
+ RETURNING delivery.id
2472
+ ), taken AS (
2473
+ UPDATE ${lanes} AS lane
2474
+ SET epoch = lane.epoch + 1, lease_owner = $4::text, lease_expires_at = $5::timestamptz, in_flight = '{}',
2475
+ claim_floor = $6::bigint
2476
+ FROM picked WHERE lane.lane = picked.lane
2477
+ RETURNING lane.lane, lane.epoch
1655
2478
  )
1656
- SELECT event_id FROM deleted`;
2479
+ SELECT lane::int AS lane, epoch::text AS epoch FROM taken ORDER BY lane`;
1657
2480
  }
1658
2481
  };
1659
-
1660
- // src/postgres-event-store.ts
1661
- var WAKE_UPS = ["notify", "poll"];
1662
- var DEFAULT_PURGE_BATCH_SIZE = 1e3;
1663
- var INITIAL_LANES_PER_ROUND = 4;
1664
- var MAXIMUM_STALE_CLAIM_ATTEMPTS = 3;
1665
- var NOTIFICATION_INTERVAL_MS = 10;
1666
- function handedOutKey(deliveryId, leaseToken) {
1667
- return `${deliveryId}\0${leaseToken}`;
1668
- }
1669
- var PostgresEventStore = class {
1670
- #executor;
1671
- #statements;
1672
- #schemaStatements;
1673
- #setupLockKey;
1674
- #schemaMarker;
1675
- #purgeBatchSize;
1676
- #completionHistory;
1677
- #logger;
1678
- /** Passed with every statement whose text is fixed: asks the executor to prepare it (`preparedStatements`). */
1679
- #queryOptions;
1680
- #notifies;
1681
- /** Every claim handed to a caller and not settled yet, by delivery id and exact lease token. */
1682
- #handedOut = /* @__PURE__ */ new Map();
1683
- #unreconciled = /* @__PURE__ */ new Set();
1684
- #generations = /* @__PURE__ */ new Map();
1685
- #ownerQueues = /* @__PURE__ */ new Map();
1686
- /** Owners whose last claim was filled from the lanes they held. */
1687
- #drainingOwners = /* @__PURE__ */ new Set();
1688
- #ownedPool;
1689
- /** The `pg` pool behind the store, when it has one: listening for notifications needs a connection of its own. */
1690
- #pool;
1691
- #notificationChannel;
1692
- #lastNotificationAt = Number.NEGATIVE_INFINITY;
1693
- #trailingNotification;
1694
- /** Set by `close()`: a transaction that commits afterwards schedules no wake-up. */
1695
- #closed = false;
1696
- /** The transactions `transaction` runs right now, and whether one of their appends left its wake-up for after the commit. */
1697
- #ownTransactions = /* @__PURE__ */ new Map();
1698
- constructor(options) {
1699
- const sources = [options.pool, options.connectionString, options.executor].filter(
1700
- (source) => source !== void 0
1701
- );
1702
- if (sources.length !== 1) {
1703
- throw new core.ConfigurationError(
1704
- "PostgresEventStore needs exactly one of pool, connectionString or executor"
1705
- );
1706
- }
1707
- const purgeBatchSize = options.purgeBatchSize ?? DEFAULT_PURGE_BATCH_SIZE;
1708
- if (!Number.isInteger(purgeBatchSize) || purgeBatchSize < 1) {
1709
- throw new core.ConfigurationError(
1710
- `purgeBatchSize must be a positive integer, received ${String(purgeBatchSize)}`
1711
- );
1712
- }
1713
- const wakeUp = options.wakeUp ?? "notify";
1714
- if (!WAKE_UPS.includes(wakeUp)) {
1715
- throw new core.ConfigurationError(`wakeUp must be 'notify' or 'poll', received ${String(wakeUp)}`);
1716
- }
1717
- const preparedStatements = options.preparedStatements ?? true;
1718
- if (typeof preparedStatements !== "boolean") {
1719
- throw new core.ConfigurationError(
1720
- `preparedStatements must be a boolean, received ${String(preparedStatements)}`
1721
- );
1722
- }
1723
- this.#notifies = wakeUp === "notify";
1724
- this.#queryOptions = preparedStatements ? { prepare: true } : void 0;
1725
- const names = resolvePostgresNames(options);
1726
- this.#statements = new PostgresStatements(names);
1727
- this.#schemaStatements = createPostgresSchemaStatements(options);
1728
- this.#setupLockKey = this.#statements.setupLockKey;
1729
- this.#schemaMarker = postgresSchemaMarker(this.#schemaStatements.slice(0, -1));
1730
- this.#purgeBatchSize = purgeBatchSize;
1731
- this.#completionHistory = names.completionHistory;
1732
- this.#logger = options.logger ?? console;
1733
- this.#notificationChannel = names.notificationChannel;
1734
- if (options.executor !== void 0) {
1735
- this.#executor = options.executor;
1736
- this.#pool = void 0;
1737
- } else {
1738
- const pool = options.pool ?? new pg.Pool({ ...options.poolConfig, connectionString: options.connectionString });
1739
- if (options.pool === void 0) {
1740
- const logger = options.logger ?? console;
1741
- pool.on("error", (error) => {
1742
- logger.error(
1743
- `[PostgresEventStore](constructor) Idle connection failed, the pool replaces it | error=${error.message}`
1744
- );
1745
- });
1746
- this.#ownedPool = pool;
1747
- }
1748
- this.#pool = pool;
1749
- this.#executor = new PgExecutor(pool, {
1750
- logger: this.#logger
1751
- });
1752
- }
1753
- }
1754
- /**
1755
- * Creates the schema, tables and indexes if they do not exist. Safe to call
1756
- * from many processes at once: a transaction-scoped advisory lock serializes
1757
- * the DDL, so racing `CREATE TABLE IF NOT EXISTS` statements cannot collide.
1758
- * When the lane table already carries the marker of the current statements
1759
- * ({@link postgresSchemaMarker}) nothing runs and no table is locked, so instances
1760
- * that start next to running dispatchers cannot deadlock with their claims.
1761
- * Skip it (`setupStore: false`) when a migration tool applies
1762
- * `createPostgresSchemaSql()` instead.
1763
- */
1764
- async setup() {
1765
- if (await this.#schemaIsCurrent()) {
1766
- return;
1767
- }
1768
- await this.#executor.transaction(async (transaction) => {
1769
- await this.#executor.query(this.#statements.setupLock, [this.#setupLockKey], transaction);
1770
- if (await this.#schemaIsCurrent(transaction)) {
1771
- return;
1772
- }
1773
- for (const statement of this.#schemaStatements) {
1774
- await this.#executor.query(statement, [], transaction);
1775
- }
1776
- });
1777
- }
1778
- async #schemaIsCurrent(transaction) {
1779
- const rows = await this.#executor.query(
1780
- this.#statements.schemaCurrent,
1781
- [this.#schemaMarker],
1782
- transaction
1783
- );
1784
- return rows[0]["current"] === true;
1785
- }
1786
- async transaction(work) {
1787
- const own = { wake: false };
1788
- const result = await this.#executor.transaction(async (transaction) => {
1789
- this.#ownTransactions.set(transaction, own);
1790
- try {
1791
- return await work(transaction);
1792
- } finally {
1793
- this.#ownTransactions.delete(transaction);
1794
- }
1795
- });
1796
- if (own.wake) {
1797
- this.#wakeAfterCommit();
1798
- }
1799
- return result;
1800
- }
1801
- /**
1802
- * Writes the entries in `transaction`, normally with one statement
1803
- * ({@link PostgresStatements.insertFreshEvents}): keyed events reserve their sequence numbers (locking
1804
- * the key rows in sorted order, so publishers cannot deadlock inside one call), then the new events and
1805
- * their deliveries are inserted, ordered by primary key, and one notification wakes the dispatchers
1806
- * when a delivery is due now. Events that already existed get their missing handlers' deliveries in
1807
- * two more statements. Two transactions that append keys in opposite order across several calls can
1808
- * still deadlock (40P01); the database rolls one back and the caller retries.
1809
- * A duplicate event id still consumes a sequence number; gaps are harmless
1810
- * because only the order of sequences matters.
1811
- */
1812
- async append(transaction, entries, now) {
1813
- const plan = planAppend(entries);
1814
- if (plan.events.length === 0) {
1815
- return { appendedEventIds: [], duplicateEventIds: [], appendedDeliveryCount: 0 };
1816
- }
1817
- const createdAt = now.toISOString();
1818
- const wakeAt = this.#wakeAt(plan.deliveries, now, transaction);
1819
- const handlersByEvent = /* @__PURE__ */ new Map();
1820
- for (const delivery of plan.deliveries) {
1821
- handlersByEvent.set(delivery.event_id, [
1822
- ...handlersByEvent.get(delivery.event_id) ?? [],
1823
- delivery.handler
1824
- ]);
1825
- }
1826
- const keyCounts = /* @__PURE__ */ new Map();
1827
- for (const event of plan.events) {
1828
- if (event.key !== null) {
1829
- keyCounts.set(event.key, (keyCounts.get(event.key) ?? 0) + 1);
1830
- }
1831
- }
1832
- const fresh = await this.#query(
1833
- this.#statements.insertFreshEvents,
1834
- [
1835
- JSON.stringify(
1836
- plan.events.map((event, ordinal) => ({
1837
- ordinal,
1838
- ...toEventRow(event, null, handlersByEvent.get(event.id) ?? [])
1839
- }))
1840
- ),
1841
- createdAt,
1842
- JSON.stringify(plan.deliveries),
1843
- JSON.stringify([...keyCounts].map(([key, count]) => ({ key, count }))),
1844
- wakeAt
1845
- ],
1846
- transaction
1847
- );
1848
- const insertedEventIds = new Set(
1849
- fresh.filter((row) => row["inserted"] === true).map((row) => row["id"])
1850
- );
1851
- let appendedDeliveryCount = readCount(fresh[0], "deliveries");
1852
- const remaining = plan.deliveries.filter(
1853
- (delivery) => !insertedEventIds.has(delivery.event_id)
1854
- );
1855
- if (remaining.length > 0) {
1856
- appendedDeliveryCount += await this.#appendToExistingEvents(
1857
- transaction,
1858
- plan,
1859
- fresh,
1860
- remaining,
1861
- handlersByEvent,
1862
- insertedEventIds,
1863
- createdAt,
1864
- wakeAt
1865
- );
1866
- }
1867
- const appendedEventIds = [];
1868
- const duplicateEventIds = [];
1869
- for (const { eventId, repeated } of plan.outcomes) {
1870
- (!repeated && insertedEventIds.has(eventId) ? appendedEventIds : duplicateEventIds).push(
1871
- eventId
1872
- );
1873
- }
1874
- return { appendedEventIds, duplicateEventIds, appendedDeliveryCount };
2482
+
2483
+ // src/statements-purge.ts
2484
+ var PurgeStatements = class {
2485
+ #names;
2486
+ constructor(names) {
2487
+ this.#names = names;
1875
2488
  }
1876
2489
  /**
1877
- * The time the publishing statements notify the dispatchers for (deliveries due by then wake them),
1878
- * or `null` for no notification. An append in a transaction of the caller's always notifies, at its
1879
- * commit. In a transaction of this store, only the first append within {@link NOTIFICATION_INTERVAL_MS}
1880
- * does; the others leave the wake-up to {@link #wakeAfterCommit}, which runs once their transaction
1881
- * committed, so no committed delivery waits for the poll.
2490
+ * Deletes one bounded batch of purgeable deliveries (or of the completion
2491
+ * history) and returns the event id of each deleted row. Parameters:
2492
+ * `[cutoff, batchSize]`. `FOR UPDATE SKIP LOCKED` keeps purge from waiting
2493
+ * on, or being waited on by, anything.
1882
2494
  */
1883
- #wakeAt(deliveries, now, transaction) {
1884
- if (!this.#notifies || !deliveries.some((delivery) => Date.parse(delivery.available_at) <= now.getTime())) {
1885
- return null;
1886
- }
1887
- const own = this.#ownTransactions.get(transaction);
1888
- if (own !== void 0 && Date.now() - this.#lastNotificationAt < NOTIFICATION_INTERVAL_MS) {
1889
- own.wake = true;
1890
- return null;
1891
- }
1892
- this.#lastNotificationAt = Date.now();
1893
- return now.toISOString();
2495
+ purgeCompletedBatch() {
2496
+ return this.#purgeBatch(this.#names.deliveries, {
2497
+ condition: `status = 'completed' AND completed_at < $1::timestamptz`,
2498
+ orderColumn: "completed_at"
2499
+ });
2500
+ }
2501
+ purgeCompletionHistoryBatch() {
2502
+ return this.#purgeBatch(this.#names.completions, {
2503
+ condition: `completed_at < $1::timestamptz`,
2504
+ orderColumn: "completed_at"
2505
+ });
2506
+ }
2507
+ purgeDeadBatch() {
2508
+ return this.#purgeBatch(this.#names.deliveries, {
2509
+ condition: `status = 'dead' AND updated_at < $1::timestamptz`,
2510
+ orderColumn: "updated_at"
2511
+ });
1894
2512
  }
1895
2513
  /**
1896
- * Wakes the dispatchers for a committed transaction whose appends sent no notification: at once when
1897
- * none was sent within {@link NOTIFICATION_INTERVAL_MS}, otherwise once when the interval ends. A
1898
- * wake-up already scheduled covers this transaction too, since it is sent after this commit. Nothing is
1899
- * sent once the store is closed or the `pg` pool behind it is ending: no dispatcher can be woken through
1900
- * it then, and the deliveries are found by polling.
2514
+ * Selects and locks one bounded batch of events created before the cutoff
2515
+ * that no delivery references and that never had a delivery complete (those
2516
+ * are measured from their completion, see {@link lockCompletedOrphanEventsBatch}).
2517
+ * Parameters: `[cutoff, batchSize]`. The ids go through
2518
+ * {@link deleteOrphanEventsWithoutCompletion} or {@link deleteExpiredCompletedOrphanEvents}, which re-check under a fresh snapshot.
1901
2519
  */
1902
- #wakeAfterCommit() {
1903
- if (this.#trailingNotification !== void 0 || this.#closed) {
1904
- return;
1905
- }
1906
- this.#trailingNotification = setTimeout(
1907
- () => {
1908
- this.#trailingNotification = void 0;
1909
- if (this.#pool?.ending === true) {
1910
- return;
1911
- }
1912
- this.#lastNotificationAt = Date.now();
1913
- this.#query(this.#statements.notify, []).catch((error) => {
1914
- this.#logger.error(
1915
- `[PostgresEventStore](wakeAfterCommit) Waking the dispatchers failed, they find the deliveries when they poll | error=${error instanceof Error ? error.message : String(error)}`
1916
- );
1917
- });
1918
- },
1919
- Math.max(0, this.#lastNotificationAt + NOTIFICATION_INTERVAL_MS - Date.now())
1920
- );
2520
+ get lockOrphanEventsBatch() {
2521
+ return `SELECT event.id FROM ${this.#names.events} AS event
2522
+ WHERE event.created_at < $1::timestamptz
2523
+ AND ${this.#unreferenced("event")}
2524
+ AND NOT EXISTS (SELECT 1 FROM ${this.#names.eventCompletions} AS completion WHERE completion.event_id = event.id)
2525
+ ORDER BY event.created_at, event.id
2526
+ LIMIT $2::int
2527
+ FOR UPDATE OF event SKIP LOCKED`;
1921
2528
  }
1922
2529
  /**
1923
- * Adds the deliveries of events the publishing statement found already stored. An event that already
1924
- * exists may be getting the same new handler from another transaction at this very moment. Whoever
1925
- * holds the event decides, so the freshness check of the insert sees what the other transaction
1926
- * committed, even if its delivery has completed since. An existing event that a purge removed
1927
- * meanwhile is inserted again (with the sequence reserved for it) instead of being skipped; its id is
1928
- * added to `insertedEventIds`. Returns how many deliveries were inserted.
2530
+ * Like {@link lockOrphanEventsBatch} for events that had a delivery complete:
2531
+ * they go once their last completion is older than the cutoff, however old the
2532
+ * event itself is. Parameters: `[cutoff, batchSize]`.
1929
2533
  */
1930
- async #appendToExistingEvents(transaction, plan, fresh, deliveries, handlersByEvent, insertedEventIds, createdAt, wakeAt) {
1931
- const sequences = new Map(
1932
- fresh.map((row) => [row["id"], row["sequence"]])
1933
- );
1934
- const reinserted = [];
1935
- let existing = plan.events.filter((event) => !insertedEventIds.has(event.id)).map(
1936
- (event) => toEventRow(event, sequences.get(event.id), handlersByEvent.get(event.id) ?? [])
1937
- );
1938
- while (existing.length > 0) {
1939
- const locked = new Set(
1940
- (await this.#query(
1941
- this.#statements.lockExistingEvents,
1942
- [JSON.stringify(existing.map((row) => row.id).sort())],
1943
- transaction
1944
- )).map((row) => row["id"])
1945
- );
1946
- const gone = existing.filter((row) => !locked.has(row.id));
1947
- if (gone.length > 0) {
1948
- const inserted2 = await this.#query(
1949
- this.#statements.insertEvents,
1950
- [JSON.stringify(gone), createdAt],
1951
- transaction
1952
- );
1953
- for (const row of inserted2) {
1954
- insertedEventIds.add(row["id"]);
1955
- reinserted.push(row["id"]);
1956
- }
1957
- }
1958
- existing = gone.filter((row) => !insertedEventIds.has(row.id));
1959
- }
1960
- const inserted = await this.#query(
1961
- this.#statements.insertDeliveries,
1962
- [JSON.stringify(deliveries), createdAt, JSON.stringify(reinserted), wakeAt],
1963
- transaction
1964
- );
1965
- return inserted.length;
2534
+ get lockCompletedOrphanEventsBatch() {
2535
+ return `SELECT event.id FROM ${this.#names.events} AS event
2536
+ JOIN ${this.#names.eventCompletions} AS completion ON completion.event_id = event.id
2537
+ WHERE completion.completed_at < $1::timestamptz
2538
+ AND ${this.#unreferenced("event")}
2539
+ ORDER BY completion.completed_at, event.id
2540
+ LIMIT $2::int
2541
+ FOR UPDATE OF event SKIP LOCKED`;
1966
2542
  }
1967
2543
  /**
1968
- * Claims up to `limit` due deliveries, normally with one statement
1969
- * ({@link PostgresStatements.claimLanes}): from the lanes this owner already holds, then from free lanes
1970
- * it takes in the same statement, recording the batch in the lane rows. A claim that would have to take
1971
- * over a lane whose previous holder still runs deliveries under an expired lease continues in a
1972
- * transaction that charges their lost attempts first, taking free lanes a few at a time (4, 8, 16, ...);
1973
- * so does a claim whose statement kept seeing a lane it holds change under it, and one that came up
1974
- * short with more free lanes left than it looked at. The step that fails after
1975
- * the first one has recorded deliveries returns those instead of failing: a recorded delivery nobody
1976
- * received would be held for a whole lease. See {@link PostgresStatements.claim} for the rules a delivery
1977
- * must satisfy.
2544
+ * Locks the given events, skipping any that a concurrent transaction is
2545
+ * referencing from a new delivery (a foreign key check holds `FOR KEY
2546
+ * SHARE`, which conflicts with this lock). Parameters: `[eventIdsJson]`.
1978
2547
  */
1979
- claim(request) {
1980
- if (request.handlers.length === 0 || !(request.limit > 0)) {
1981
- return Promise.resolve([]);
1982
- }
1983
- return this.#serialized(request.leaseOwner, () => this.#claim(request));
2548
+ get lockEvents() {
2549
+ return `SELECT id FROM ${this.#names.events}
2550
+ WHERE id = ANY (ARRAY(SELECT jsonb_array_elements_text($1::jsonb)))
2551
+ FOR UPDATE SKIP LOCKED`;
1984
2552
  }
1985
2553
  /**
1986
- * Runs `work` after the earlier claims of the same owner on this store settled. The
1987
- * bookkeeping of what was handed out and the reconciliation of a failed claim need
1988
- * one claim at a time per owner (the dispatcher claims one batch at a time anyway;
1989
- * `runOnce` next to a running dispatcher is what this guards against).
2554
+ * Deletes events that no delivery references and whose last completion is older than
2555
+ * `$2`, checked again under the fresh snapshot of this statement: a completion recorded
2556
+ * after the sweep selected the event moves its time and keeps the event. Parameters:
2557
+ * `[eventIdsJson, cutoff]`.
1990
2558
  */
1991
- #serialized(owner, work) {
1992
- const previous = this.#ownerQueues.get(owner) ?? Promise.resolve();
1993
- const run = previous.then(work, work);
1994
- const tail = run.then(
1995
- () => void 0,
1996
- () => void 0
1997
- );
1998
- this.#ownerQueues.set(owner, tail);
1999
- void tail.then(() => {
2000
- if (this.#ownerQueues.get(owner) === tail) {
2001
- this.#ownerQueues.delete(owner);
2002
- }
2003
- });
2004
- return run;
2559
+ get deleteExpiredCompletedOrphanEvents() {
2560
+ return countChanged(`DELETE FROM ${this.#names.events} AS event
2561
+ WHERE event.id = ANY (ARRAY(SELECT jsonb_array_elements_text($1::jsonb)))
2562
+ AND ${this.#unreferenced("event")}
2563
+ AND EXISTS (
2564
+ SELECT 1 FROM ${this.#names.eventCompletions} AS completion
2565
+ WHERE completion.event_id = event.id AND completion.completed_at < $2::timestamptz
2566
+ )`);
2005
2567
  }
2006
- async #claim(request) {
2007
- if (this.#unreconciled.has(request.leaseOwner) && !await this.#reconcile(request.leaseOwner)) {
2008
- throw new Error(
2009
- `[PostgresEventStore](claim) Giving back unreturned deliveries still fails, so no claim is made | owner=${request.leaseOwner}`
2010
- );
2011
- }
2012
- const heldFirst = this.#drainingOwners.has(request.leaseOwner);
2013
- let rows;
2014
- try {
2015
- rows = await this.#claimInOneStatement(
2016
- request,
2017
- heldFirst ? this.#statements.claimHeldLanes : this.#statements.claimLanes
2018
- );
2019
- } catch (error) {
2020
- await this.#reconcile(request.leaseOwner);
2021
- throw error;
2022
- }
2023
- const heldLanes = new Set(JSON.parse(rows[0]["examined_lanes"]));
2024
- const claimed = this.#takeClaimed(rows, request.leaseOwner);
2025
- if (heldFirst && claimed.length < request.limit && rows[0]["stale"] !== true) {
2026
- try {
2027
- rows = await this.#claimInOneStatement(
2028
- { ...request, limit: request.limit - claimed.length },
2029
- this.#statements.claimLanes
2030
- );
2031
- } catch (error) {
2032
- await this.#reconcile(request.leaseOwner);
2033
- if (claimed.length === 0) {
2034
- this.#drainingOwners.delete(request.leaseOwner);
2035
- throw error;
2036
- }
2037
- this.#logger.error(
2038
- `[PostgresEventStore](claim) Claiming from free lanes failed, returning the deliveries already claimed | claimed=${claimed.length} | error=${error instanceof Error ? error.message : String(error)}`
2039
- );
2040
- return this.#handOutInDueOrder(claimed, request, heldLanes);
2041
- }
2042
- claimed.push(...this.#takeClaimed(rows, request.leaseOwner));
2043
- }
2044
- if (claimed.length < request.limit && (rows[0]["takeover_waiting"] === true || rows[0]["unexamined_free_lanes"] === true || rows[0]["stale"] === true)) {
2045
- try {
2046
- const more = await this.#claimMore(request, claimed.length);
2047
- this.#handOut(more, request.leaseOwner);
2048
- claimed.push(...more);
2049
- } catch (error) {
2050
- await this.#reconcile(request.leaseOwner);
2051
- if (claimed.length === 0) {
2052
- throw error;
2053
- }
2054
- this.#logger.error(
2055
- `[PostgresEventStore](claim) Taking more lanes failed, returning the deliveries already claimed | claimed=${claimed.length} | error=${error instanceof Error ? error.message : String(error)}`
2056
- );
2057
- }
2568
+ /**
2569
+ * Deletes locked events that no delivery references and that never had a delivery complete.
2570
+ * It must run as a statement of its own after {@link lockEvents}: it then takes a fresh
2571
+ * snapshot that includes every delivery committed before the lock was granted, so an event
2572
+ * that just gained a delivery is never cascaded away. Keeps events that had a delivery complete:
2573
+ * deleting dead letters must not shorten the retention of completed work.
2574
+ */
2575
+ get deleteOrphanEventsWithoutCompletion() {
2576
+ return countChanged(`DELETE FROM ${this.#names.events} AS event
2577
+ WHERE event.id = ANY (ARRAY(SELECT jsonb_array_elements_text($1::jsonb)))
2578
+ AND ${this.#unreferenced("event")}
2579
+ AND NOT EXISTS (SELECT 1 FROM ${this.#names.eventCompletions} AS completion WHERE completion.event_id = event.id)`);
2580
+ }
2581
+ /** True when no delivery and no completion history record references the event. */
2582
+ #unreferenced(eventAlias) {
2583
+ const history = this.#names.completionHistory ? ` AND NOT EXISTS (SELECT 1 FROM ${this.#names.completions} AS done WHERE done.event_id = ${eventAlias}.id)` : "";
2584
+ return `NOT EXISTS (SELECT 1 FROM ${this.#names.deliveries} AS delivery WHERE delivery.event_id = ${eventAlias}.id)${history}`;
2585
+ }
2586
+ #purgeBatch(table, { condition, orderColumn }) {
2587
+ return `WITH batch AS MATERIALIZED (
2588
+ SELECT id FROM ${table}
2589
+ WHERE ${condition}
2590
+ ORDER BY ${orderColumn}, id
2591
+ LIMIT $2::int
2592
+ FOR UPDATE SKIP LOCKED
2593
+ ), deleted AS (
2594
+ DELETE FROM ${table} AS delivery USING batch WHERE delivery.id = batch.id RETURNING delivery.event_id
2595
+ )
2596
+ SELECT event_id FROM deleted`;
2597
+ }
2598
+ };
2599
+
2600
+ // src/statements-queries.ts
2601
+ var DEFAULT_LIST_LIMIT = 100;
2602
+ function bindListFilters(query) {
2603
+ const parameters = [];
2604
+ const bind = (value) => {
2605
+ parameters.push(value);
2606
+ return `$${parameters.length}::${typeof value === "number" ? "int" : "text"}`;
2607
+ };
2608
+ const filters = {
2609
+ handler: query.handler === void 0 ? void 0 : bind(query.handler),
2610
+ eventType: query.eventType === void 0 ? void 0 : bind(query.eventType),
2611
+ eventId: query.eventId === void 0 ? void 0 : bind(query.eventId),
2612
+ status: query.status === void 0 ? void 0 : bind(query.status)
2613
+ };
2614
+ const limit = bind(query.limit ?? DEFAULT_LIST_LIMIT);
2615
+ return { parameters, filters, limit };
2616
+ }
2617
+ function listConditions(filters, alias) {
2618
+ return [
2619
+ ...filters.handler === void 0 ? [] : [`${alias}.handler = ${filters.handler}`],
2620
+ ...filters.eventType === void 0 ? [] : [`event.type = ${filters.eventType}`],
2621
+ ...filters.eventId === void 0 ? [] : [`${alias}.event_id = ${filters.eventId}`]
2622
+ ];
2623
+ }
2624
+ var QueryStatements = class {
2625
+ #names;
2626
+ constructor(names) {
2627
+ this.#names = names;
2628
+ }
2629
+ /** Parameters: `[deliveryIdsJson, now]`. The dead rows are locked in id order first. */
2630
+ get requeue() {
2631
+ const deliveries = this.#names.deliveries;
2632
+ return countChanged(`WITH dead AS MATERIALIZED (
2633
+ SELECT delivery.id FROM ${deliveries} AS delivery
2634
+ WHERE delivery.id = ANY (ARRAY(SELECT jsonb_array_elements_text($1::jsonb))) AND delivery.status = 'dead'
2635
+ ORDER BY delivery.id
2636
+ FOR NO KEY UPDATE
2637
+ )
2638
+ UPDATE ${deliveries} AS delivery
2639
+ SET status = 'pending', attempts = 0, available_at = $2::timestamptz, updated_at = $2::timestamptz
2640
+ FROM dead
2641
+ WHERE delivery.id = dead.id AND delivery.status = 'dead'`);
2642
+ }
2643
+ /**
2644
+ * Builds the filtered, creation-ordered listing. A delivery is `processing`
2645
+ * while its row exists as `pending` and its lane lists its id; its attempt
2646
+ * count, lease owner and lease expiry then come from the claim and the lane.
2647
+ * Records of the completion history (when kept) are listed as `completed`.
2648
+ */
2649
+ listDeliveries(query) {
2650
+ const { parameters, filters, limit } = bindListFilters(query);
2651
+ const current = this.#currentDeliveries(filters);
2652
+ const includeHistory = this.#names.completionHistory && (query.status === void 0 || query.status === "completed");
2653
+ if (!includeHistory) {
2654
+ return {
2655
+ sql: `${current}
2656
+ ORDER BY delivery.created_at, delivery.id
2657
+ LIMIT ${limit}`,
2658
+ parameters
2659
+ };
2058
2660
  }
2059
- return this.#handOutInDueOrder(claimed, request, heldLanes);
2661
+ const history = this.#completionHistory(filters);
2662
+ return {
2663
+ sql: `SELECT * FROM (
2664
+ ${current}
2665
+ UNION ALL
2666
+ ${history}
2667
+ ) AS listed
2668
+ ORDER BY created_at, delivery_id
2669
+ LIMIT ${limit}`,
2670
+ parameters
2671
+ };
2672
+ }
2673
+ /** The deliveries that still exist, with a running one reported as `processing`. */
2674
+ #currentDeliveries(filters) {
2675
+ const inFlight = `(delivery.status = 'pending' AND delivery.id = ANY (lane.in_flight))`;
2676
+ const whereCurrent = [
2677
+ ...listConditions(filters, "delivery"),
2678
+ ...filters.status === void 0 ? [] : [
2679
+ `(CASE WHEN ${inFlight} THEN 'processing' ELSE delivery.status END) = ${filters.status}`
2680
+ ]
2681
+ ];
2682
+ return `SELECT delivery.id AS delivery_id, delivery.handler,
2683
+ CASE WHEN ${inFlight} THEN 'processing' ELSE delivery.status END AS status,
2684
+ (delivery.attempts + CASE WHEN ${inFlight} THEN 1 ELSE 0 END)::int AS attempts,
2685
+ ${isoText("delivery.available_at")} AS available_at,
2686
+ CASE WHEN ${inFlight} THEN lane.lease_owner END AS lease_owner,
2687
+ CASE WHEN ${inFlight} THEN ${isoText("lane.lease_expires_at")} END AS lease_expires_at,
2688
+ delivery.last_error::text AS last_error,
2689
+ ${isoText("delivery.created_at")} AS created_at,
2690
+ ${isoText("delivery.updated_at")} AS updated_at,
2691
+ ${isoText("delivery.completed_at")} AS completed_at,
2692
+ ${eventColumns("event")}
2693
+ FROM ${this.#names.deliveries} AS delivery
2694
+ JOIN ${this.#names.lanes} AS lane ON lane.lane = delivery.lane
2695
+ JOIN ${this.#names.events} AS event ON event.id = delivery.event_id
2696
+ ${whereCurrent.length === 0 ? "" : `WHERE ${whereCurrent.join(" AND ")}`}`;
2060
2697
  }
2061
- /** The deliveries a claim statement picked, registered as handed out to `leaseOwner`. */
2062
- #takeClaimed(rows, leaseOwner) {
2063
- const claimed = rows.filter((row) => row["delivery_id"] !== null);
2064
- this.#forgetFinished(rows[0], leaseOwner, claimed);
2065
- this.#handOut(claimed, leaseOwner);
2066
- return claimed;
2698
+ /** The completion history records, listed as `completed`. */
2699
+ #completionHistory(filters) {
2700
+ const common = (alias) => listConditions(filters, alias);
2701
+ return `SELECT done.id AS delivery_id, done.handler, 'completed' AS status, done.attempts,
2702
+ ${isoText("done.available_at")} AS available_at,
2703
+ NULL AS lease_owner,
2704
+ NULL AS lease_expires_at,
2705
+ NULL AS last_error,
2706
+ ${isoText("done.created_at")} AS created_at,
2707
+ ${isoText("done.completed_at")} AS updated_at,
2708
+ ${isoText("done.completed_at")} AS completed_at,
2709
+ ${eventColumns("event")}
2710
+ FROM ${this.#names.completions} AS done
2711
+ JOIN ${this.#names.events} AS event ON event.id = done.event_id
2712
+ ${common("done").length === 0 ? "" : `WHERE ${common("done").join(" AND ")}`}`;
2067
2713
  }
2068
- #handOutInDueOrder(claimed, request, heldLanes) {
2069
- if (claimed.length >= request.limit && claimed.every((row) => heldLanes.has(readCount(row, "lane")))) {
2070
- this.#drainingOwners.add(request.leaseOwner);
2071
- } else {
2072
- this.#drainingOwners.delete(request.leaseOwner);
2073
- }
2074
- claimed.sort(compareDue);
2075
- return claimed.map((row) => mapClaimedDelivery(row, request.leaseExpiresAt));
2714
+ /**
2715
+ * Counts of rows by stored status (`pending` includes running deliveries;
2716
+ * `completed` rows exist only after an upgrade from 0.1.0). Each count is
2717
+ * answered from a partial index.
2718
+ */
2719
+ get countByStatus() {
2720
+ const deliveries = this.#names.deliveries;
2721
+ return ["pending", "dead", "completed"].map(
2722
+ (status) => `SELECT '${status}' AS status, count(*)::text AS count FROM ${deliveries} WHERE status = '${status}'`
2723
+ ).join("\nUNION ALL\n");
2724
+ }
2725
+ /** Deliveries that are running: listed by a lane and still pending as rows. */
2726
+ get countRunning() {
2727
+ return `SELECT count(*)::text AS count
2728
+ FROM ${this.#names.lanes} AS lane
2729
+ CROSS JOIN LATERAL unnest(lane.in_flight) AS flying (id)
2730
+ JOIN ${this.#names.deliveries} AS delivery ON delivery.id = flying.id AND delivery.status = 'pending'`;
2731
+ }
2732
+ get countCompletionHistory() {
2733
+ return `SELECT count(*)::text AS count FROM ${this.#names.completions}`;
2076
2734
  }
2077
2735
  /**
2078
- * Runs `statement` ({@link PostgresStatements.claimLanes} or its held-lane form), again when it reports that it waited for a lane lock and
2079
- * read deliveries with an older snapshot than the lane it got. A held lane is only locked by an
2080
- * operation of its own owner (another claim, a reschedule), so a few attempts are enough.
2736
+ * Oldest instant at which a delivery became claimable: `available_at` of a
2737
+ * pending delivery that nobody runs, or the lease expiry of a lane that runs
2738
+ * deliveries. Parameters: `[now]`.
2081
2739
  */
2082
- async #claimInOneStatement(request, statement) {
2083
- const parameters = [
2084
- request.now.toISOString(),
2085
- JSON.stringify(request.handlers),
2086
- request.limit,
2087
- request.leaseOwner,
2088
- request.leaseExpiresAt.toISOString(),
2089
- this.#generation(request.leaseOwner).toString()
2090
- ];
2091
- let rows = await this.#query(statement, parameters);
2092
- for (let attempt = 1; attempt < MAXIMUM_STALE_CLAIM_ATTEMPTS && rows[0]["stale"] === true; attempt += 1) {
2093
- rows = await this.#query(statement, parameters);
2094
- }
2095
- return rows;
2740
+ get oldestDue() {
2741
+ const deliveries = this.#names.deliveries;
2742
+ const lanes = this.#names.lanes;
2743
+ return `SELECT ${isoText("min(due.due_at)")} AS oldest_due_at FROM (
2744
+ SELECT waiting.available_at AS due_at
2745
+ FROM ${lanes} AS lane
2746
+ CROSS JOIN LATERAL (
2747
+ SELECT delivery.available_at FROM ${deliveries} AS delivery
2748
+ WHERE delivery.lane = lane.lane AND delivery.status = 'pending'
2749
+ AND delivery.available_at <= $1::timestamptz AND delivery.id <> ALL (lane.in_flight)
2750
+ ORDER BY delivery.available_at LIMIT 1
2751
+ ) AS waiting
2752
+ UNION ALL
2753
+ SELECT lane.lease_expires_at AS due_at
2754
+ FROM ${lanes} AS lane
2755
+ WHERE lane.lease_expires_at <= $1::timestamptz AND NOT ${noRunningDelivery(this.#names, "lane")}
2756
+ ) AS due`;
2757
+ }
2758
+ };
2759
+
2760
+ // src/statements-setup.ts
2761
+ var SetupStatements = class {
2762
+ #names;
2763
+ constructor(names) {
2764
+ this.#names = names;
2096
2765
  }
2097
2766
  /**
2098
- * Second step of {@link PostgresEventStore.claim}, in one transaction: takes free lanes a few at a
2099
- * time, lanes to take over included (their lost attempts are charged first), and records the batch.
2100
- * `alreadyClaimed` deliveries of the first step are in flight, so they are not picked again.
2767
+ * Lock advisory key text for {@link setupLock}. It is derived from the schema
2768
+ * name only, so stores with different table prefixes in one schema also
2769
+ * serialize their `CREATE SCHEMA IF NOT EXISTS`, which is not race-free.
2101
2770
  */
2102
- async #claimMore(request, alreadyClaimed) {
2103
- const now = request.now.toISOString();
2104
- const leaseExpiresAt = request.leaseExpiresAt.toISOString();
2105
- const handlers = JSON.stringify(request.handlers);
2106
- const generation = this.#generation(request.leaseOwner).toString();
2107
- return this.#executor.transaction(async (transaction) => {
2108
- const claimed = [];
2109
- const remaining = () => request.limit - alreadyClaimed - claimed.length;
2110
- const takenLanes = /* @__PURE__ */ new Set();
2111
- for (let laneCount = INITIAL_LANES_PER_ROUND; remaining() > 0; ) {
2112
- const taken = await this.#query(
2113
- this.#statements.takeFreeLanes,
2114
- [now, handlers, laneCount, request.leaseOwner, leaseExpiresAt, generation],
2115
- transaction
2116
- );
2117
- if (taken.length === 0) {
2118
- break;
2119
- }
2120
- const lanes = taken.map((row) => readCount(row, "lane"));
2121
- for (const lane of lanes) {
2122
- takenLanes.add(lane);
2123
- }
2124
- claimed.push(
2125
- ...await this.#pickDeliveries(
2126
- [now, handlers, remaining(), JSON.stringify(lanes)],
2127
- transaction
2128
- )
2129
- );
2130
- laneCount *= 2;
2131
- }
2132
- await this.#recordClaim(claimed, takenLanes, request, transaction);
2133
- return claimed;
2134
- });
2771
+ get setupLockKey() {
2772
+ return `relaybus:${this.#names.schema}`;
2135
2773
  }
2136
2774
  /**
2137
- * The generation of the owner's claim statements. It only grows, also across restarts (it starts at the
2138
- * clock), and a reconciliation moves it up, which fences off every earlier statement still in flight.
2775
+ * Whether the lane table carries `marker` as its comment, that is whether the schema statements
2776
+ * that produce that marker already ran. Takes no table lock. Parameters: `[marker]`.
2139
2777
  */
2140
- #generation(owner, advance = false) {
2141
- const current = this.#generations.get(owner) ?? BigInt(Date.now());
2142
- const next = advance ? current + 1n > BigInt(Date.now()) ? current + 1n : BigInt(Date.now()) : current;
2143
- this.#generations.set(owner, next);
2144
- return next;
2778
+ get schemaCurrent() {
2779
+ return `SELECT EXISTS (
2780
+ SELECT 1 FROM pg_catalog.pg_class AS c
2781
+ JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace
2782
+ JOIN pg_catalog.pg_description AS d
2783
+ ON d.objoid = c.oid AND d.classoid = 'pg_catalog.pg_class'::regclass AND d.objsubid = 0
2784
+ WHERE n.nspname = '${this.#names.schema}' AND c.relname = '${this.#names.lanesTableName}' AND d.description = $1::text
2785
+ ) AS current`;
2145
2786
  }
2146
- /** Forgets a handed-out lease once the store answered about it (any answer: the claim is over or fenced out). */
2147
- async #settled(lease, work) {
2148
- const result = await work;
2149
- this.#handedOut.delete(handedOutKey(lease.deliveryId, lease.leaseToken));
2150
- return result;
2787
+ get setupLock() {
2788
+ return "SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))";
2151
2789
  }
2152
- /** Remembers the claims handed to the caller of `claim` until they are settled. */
2153
- #handOut(rows, leaseOwner) {
2154
- for (const row of rows) {
2155
- const claim = mapClaimedDelivery(row, /* @__PURE__ */ new Date(0));
2156
- this.#handedOut.set(handedOutKey(claim.deliveryId, claim.leaseToken), {
2157
- owner: leaseOwner,
2158
- deliveryId: claim.deliveryId,
2159
- ...parseLeaseToken(claim.leaseToken)
2160
- });
2161
- }
2790
+ };
2791
+
2792
+ // src/statements.ts
2793
+ var PostgresStatements = class {
2794
+ setup;
2795
+ append;
2796
+ lanes;
2797
+ claim;
2798
+ completion;
2799
+ queries;
2800
+ purge;
2801
+ constructor(names) {
2802
+ this.setup = new SetupStatements(names);
2803
+ this.append = new AppendStatements(names);
2804
+ this.lanes = new LaneStatements(names);
2805
+ this.claim = new ClaimStatements(names);
2806
+ this.completion = new CompletionStatements(names);
2807
+ this.queries = new QueryStatements(names);
2808
+ this.purge = new PurgeStatements(names);
2162
2809
  }
2163
- /**
2164
- * Drops the registrations of the owner's held lanes whose delivery no longer runs there
2165
- * (completed inside the caller's transaction, deleted, or listed no more). Registrations of
2166
- * lanes this claim did not see stay: their tokens may still be valid.
2167
- */
2168
- #forgetFinished(row, leaseOwner, claimed) {
2169
- const heldLanes = new Set(JSON.parse(row["examined_lanes"]));
2170
- const running = /* @__PURE__ */ new Set([
2171
- ...JSON.parse(row["running_ids"]),
2172
- ...claimed.map((picked) => picked["delivery_id"])
2173
- ]);
2174
- for (const [key, entry] of this.#handedOut) {
2175
- if (entry.owner === leaseOwner && heldLanes.has(entry.lane) && !running.has(entry.deliveryId)) {
2176
- this.#handedOut.delete(key);
2177
- }
2178
- }
2810
+ };
2811
+
2812
+ // src/postgres-event-store.ts
2813
+ var WAKE_UPS = ["notify", "poll"];
2814
+ var DEFAULT_PURGE_BATCH_SIZE = 1e3;
2815
+ var PostgresEventStore = class {
2816
+ #state;
2817
+ #appender;
2818
+ #claims;
2819
+ #completion;
2820
+ #maintenance;
2821
+ #owned = new OwnedConnections();
2822
+ constructor(options) {
2823
+ const { purgeBatchSize, wakeUp, queryOptions } = resolveStoreSettings(options);
2824
+ const names = resolvePostgresNames(options);
2825
+ const statements = new PostgresStatements(names);
2826
+ const schemaStatements = createPostgresSchemaStatements(options);
2827
+ const logger = options.logger ?? console;
2828
+ const { executor, pool, ownedPool } = connect(options, { logger, owned: this.#owned });
2829
+ const state = {
2830
+ executor,
2831
+ statements,
2832
+ schemaStatements,
2833
+ setupLockKey: statements.setup.setupLockKey,
2834
+ schemaMarker: postgresSchemaMarker(schemaStatements.slice(0, -1)),
2835
+ purgeBatchSize,
2836
+ completionHistory: names.completionHistory,
2837
+ logger,
2838
+ queryOptions,
2839
+ notifies: wakeUp === "notify",
2840
+ query: ({ sql, parameters, transaction }) => executor.query(sql, parameters, transaction, queryOptions),
2841
+ handedOut: /* @__PURE__ */ new Map(),
2842
+ unreconciled: /* @__PURE__ */ new Set(),
2843
+ generations: /* @__PURE__ */ new Map(),
2844
+ ownerQueues: /* @__PURE__ */ new Map(),
2845
+ drainingOwners: /* @__PURE__ */ new Set(),
2846
+ ownedPool,
2847
+ pool,
2848
+ notificationChannel: names.notificationChannel,
2849
+ lastNotificationAt: Number.NEGATIVE_INFINITY,
2850
+ trailingNotification: void 0,
2851
+ closed: false,
2852
+ ownTransactions: /* @__PURE__ */ new Map()
2853
+ };
2854
+ this.#state = state;
2855
+ this.#appender = new PostgresAppend(state);
2856
+ this.#claims = new PostgresClaims(state);
2857
+ this.#completion = new PostgresCompletion(state);
2858
+ this.#maintenance = new PostgresMaintenance(state);
2179
2859
  }
2180
2860
  /**
2181
- * After a claim failed, possibly after the database recorded its batch: gives back the recorded
2182
- * deliveries that were never handed out, keeping exactly the claims handed out and not settled.
2183
- * A failure is remembered and retried before the owner's next claim: other deliveries keep
2184
- * renewing the lane, so an unreturned one would otherwise never be recovered.
2861
+ * Creates the schema, tables and indexes if they do not exist. Safe to call
2862
+ * from many processes at once: a transaction-scoped advisory lock serializes
2863
+ * the DDL, so racing `CREATE TABLE IF NOT EXISTS` statements cannot collide.
2864
+ * When the lane table already carries the marker of the current statements
2865
+ * ({@link postgresSchemaMarker}) nothing runs and no table is locked, so instances
2866
+ * that start next to running dispatchers cannot deadlock with their claims.
2867
+ * Skip it (`setupStore: false`) when a migration tool applies
2868
+ * `createPostgresSchemaSql()` instead.
2185
2869
  */
2186
- async #reconcile(leaseOwner) {
2187
- const generation = this.#generation(leaseOwner, true);
2188
- const handedOut = [...this.#handedOut.values()].filter((entry) => entry.owner === leaseOwner).map(({ deliveryId, lane, epoch, claims }) => ({ id: deliveryId, lane, epoch, claims }));
2189
- try {
2190
- await this.#query(this.#statements.reconcileClaims, [
2191
- leaseOwner,
2192
- JSON.stringify(handedOut),
2193
- generation.toString()
2194
- ]);
2195
- this.#unreconciled.delete(leaseOwner);
2196
- return true;
2197
- } catch (error) {
2198
- this.#unreconciled.add(leaseOwner);
2199
- this.#logger.error(
2200
- `[PostgresEventStore](reconcile) Giving back unreturned deliveries failed, it is retried before the next claim | owner=${leaseOwner} | error=${error instanceof Error ? error.message : String(error)}`
2201
- );
2202
- return false;
2870
+ async setup() {
2871
+ if (await this.#schemaIsCurrent()) {
2872
+ return;
2203
2873
  }
2204
- }
2205
- /** Fast claim, then the slow one when the fast window was full of blocked followers. */
2206
- async #pickDeliveries(parameters, transaction) {
2207
- const limit = parameters[2];
2208
- const fastRows = await this.#query(this.#statements.claim, parameters, transaction);
2209
- const picked = fastRows.filter((row) => row["delivery_id"] !== null);
2210
- if (picked.length < limit && fastRows[0]["window_saturated"] === true) {
2211
- const slowRows = await this.#query(
2212
- this.#statements.claimBehindBlockedKeys,
2213
- parameters,
2874
+ await this.#state.executor.transaction(async (transaction) => {
2875
+ await this.#state.executor.query(
2876
+ this.#state.statements.setup.setupLock,
2877
+ [this.#state.setupLockKey],
2214
2878
  transaction
2215
2879
  );
2216
- const pickedIds = new Set(picked.map((row) => row["delivery_id"]));
2217
- picked.push(
2218
- ...slowRows.filter(
2219
- (row) => row["delivery_id"] !== null && !pickedIds.has(row["delivery_id"])
2220
- )
2221
- );
2222
- const seenKeys = /* @__PURE__ */ new Set();
2223
- const kept = [...picked].sort((left, right) => compareSequence(left, right)).filter((row) => {
2224
- if (row["delivery_key"] === null) {
2225
- return true;
2226
- }
2227
- const group = `${row["handler"]}\0${row["delivery_key"]}`;
2228
- return !seenKeys.has(group) && Boolean(seenKeys.add(group));
2229
- });
2230
- kept.sort(compareDue);
2231
- return kept.slice(0, limit);
2232
- }
2233
- return picked;
2880
+ if (await this.#schemaIsCurrent(transaction)) {
2881
+ return;
2882
+ }
2883
+ for (const statement of this.#state.schemaStatements) {
2884
+ await this.#state.executor.query(statement, [], transaction);
2885
+ }
2886
+ });
2234
2887
  }
2235
- /** Writes the picked ids into their lane rows and frees the lanes that picked nothing. */
2236
- async #recordClaim(claimed, lanes, request, transaction) {
2237
- const idsByLane = /* @__PURE__ */ new Map();
2238
- for (const row of claimed) {
2239
- const lane = readCount(row, "lane");
2240
- idsByLane.set(lane, [...idsByLane.get(lane) ?? [], row["delivery_id"]]);
2241
- }
2242
- const idleLanes = [...lanes].filter((lane) => !idsByLane.has(lane));
2243
- if (idsByLane.size === 0 && idleLanes.length === 0) {
2244
- return;
2888
+ async #schemaIsCurrent(transaction) {
2889
+ const rows = await this.#state.executor.query(
2890
+ this.#state.statements.setup.schemaCurrent,
2891
+ [this.#state.schemaMarker],
2892
+ transaction
2893
+ );
2894
+ return rows[0]["current"] === true;
2895
+ }
2896
+ /**
2897
+ * Runs `work` in a transaction of the executor. With `options.timeoutMs` (from `bus.transaction`)
2898
+ * the server holds the transaction to the budget: `statement_timeout`, and for executors with
2899
+ * `sessionTimeouts` (`pg`) also `idle_in_transaction_session_timeout` and, on PostgreSQL 17+,
2900
+ * `transaction_timeout`, all scoped to the transaction. An executor with `transactionWithBudget`
2901
+ * (`PgExecutor`) sets them with `BEGIN`, so the budget costs no round trip; on a pool the store
2902
+ * created they are kept per connection and sent only when the connection does not have them yet.
2903
+ */
2904
+ async transaction(work, options) {
2905
+ const own = { wake: false };
2906
+ const tracked = async (transaction) => {
2907
+ this.#state.ownTransactions.set(transaction, own);
2908
+ try {
2909
+ return await work(transaction);
2910
+ } finally {
2911
+ this.#state.ownTransactions.delete(transaction);
2912
+ }
2913
+ };
2914
+ const result = await (options === void 0 ? this.#state.executor.transaction(tracked) : inBudgetedTransaction(this.#state, { work: tracked, timeoutMs: options.timeoutMs }));
2915
+ if (own.wake) {
2916
+ this.#appender.wakeAfterCommit();
2245
2917
  }
2246
- await this.#query(
2247
- this.#statements.recordClaim,
2248
- [
2249
- JSON.stringify([...idsByLane].map(([lane, ids]) => ({ lane, ids }))),
2250
- JSON.stringify(idleLanes),
2251
- request.leaseOwner,
2252
- request.leaseExpiresAt.toISOString()
2253
- ],
2254
- transaction
2255
- );
2918
+ return result;
2919
+ }
2920
+ /**
2921
+ * Writes the entries in `transaction`, normally with one statement
2922
+ * (`AppendStatements.insertFreshEvents`): keyed events reserve their sequence numbers (locking
2923
+ * the key rows in sorted order, so publishers cannot deadlock inside one call), then the new events and
2924
+ * their deliveries are inserted, ordered by primary key, and one notification wakes the dispatchers
2925
+ * when a delivery is due now. Events that already existed get their missing handlers' deliveries in
2926
+ * two more statements. Two transactions that append keys in opposite order across several calls can
2927
+ * still deadlock (40P01); the database rolls one back and the caller retries.
2928
+ * A duplicate event id still consumes a sequence number; gaps are harmless
2929
+ * because only the order of sequences matters.
2930
+ */
2931
+ // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature
2932
+ append(transaction, entries, now) {
2933
+ return this.#appender.append(transaction, { entries, now });
2934
+ }
2935
+ /**
2936
+ * Claims up to `limit` due deliveries, normally with one statement
2937
+ * (`LaneStatements.claimLanes`): from the lanes this owner already holds, then from free lanes
2938
+ * it takes in the same statement, recording the batch in the lane rows. A claim that would have to take
2939
+ * over a lane whose previous holder still runs deliveries under an expired lease continues in a
2940
+ * transaction that charges their lost attempts first, taking free lanes a few at a time (4, 8, 16, ...);
2941
+ * so does a claim whose statement kept seeing a lane it holds change under it, and one that came up
2942
+ * short with more free lanes left than it looked at. The step that fails after
2943
+ * the first one has recorded deliveries returns those instead of failing: a recorded delivery nobody
2944
+ * received would be held for a whole lease. See `ClaimStatements.claim` for the rules a delivery
2945
+ * must satisfy.
2946
+ */
2947
+ claim(request) {
2948
+ return this.#claims.claim(request);
2256
2949
  }
2257
2950
  extendLease(lease, leaseExpiresAt) {
2258
- return this.#whenIssued(
2259
- lease,
2260
- (held) => this.#changed(this.#statements.extendLease, [
2261
- lease.deliveryId,
2262
- held.lane,
2263
- held.epoch,
2264
- held.claims,
2265
- leaseExpiresAt.toISOString()
2266
- ])
2267
- );
2951
+ return this.#completion.extendLease(lease, leaseExpiresAt);
2268
2952
  }
2269
- async complete(lease, now, transaction) {
2270
- return (await this.#completeLeases([lease], now, transaction))[0];
2953
+ // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature
2954
+ complete(lease, now, transaction) {
2955
+ return this.#completion.complete(lease, { now, transaction });
2271
2956
  }
2272
2957
  completeMany(leases, now) {
2273
- return this.#completeLeases(leases, now, void 0);
2958
+ return this.#completion.completeMany(leases, now);
2274
2959
  }
2960
+ // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature
2275
2961
  reschedule(lease, availableAt, error, now) {
2276
- return this.#settled(
2277
- lease,
2278
- this.#whenIssued(
2279
- lease,
2280
- (held) => this.#changed(this.#statements.reschedule, [
2281
- lease.deliveryId,
2282
- held.lane,
2283
- held.epoch,
2284
- held.claims,
2285
- availableAt.toISOString(),
2286
- JSON.stringify(error),
2287
- now.toISOString()
2288
- ])
2289
- )
2290
- );
2962
+ return this.#completion.reschedule(lease, { availableAt, error, now });
2291
2963
  }
2964
+ // eslint-disable-next-line relaybus/max-two-params -- EventStore port signature
2292
2965
  bury(lease, error, now) {
2293
- return this.#settled(
2294
- lease,
2295
- this.#whenIssued(
2296
- lease,
2297
- (held) => this.#changed(this.#statements.bury, [
2298
- lease.deliveryId,
2299
- held.lane,
2300
- held.epoch,
2301
- held.claims,
2302
- JSON.stringify(error),
2303
- now.toISOString()
2304
- ])
2305
- )
2306
- );
2966
+ return this.#completion.bury(lease, { error, now });
2307
2967
  }
2308
2968
  /** Returns a leased delivery to pending, due now, without counting the attempt. */
2309
2969
  release(lease, now) {
2310
- return this.#settled(
2311
- lease,
2312
- this.#whenIssued(
2313
- lease,
2314
- (held) => this.#changed(this.#statements.release, [
2315
- lease.deliveryId,
2316
- held.lane,
2317
- held.epoch,
2318
- held.claims,
2319
- now.toISOString()
2320
- ])
2321
- )
2322
- );
2970
+ return this.#completion.release(lease, now);
2323
2971
  }
2324
2972
  /**
2325
2973
  * Calls `listener` soon after a transaction that published deliveries due at once commits, in any
@@ -2331,38 +2979,33 @@ var PostgresEventStore = class {
2331
2979
  * wakes its own dispatcher).
2332
2980
  */
2333
2981
  async watchNewDeliveries(listener) {
2334
- if (this.#pool === void 0 || !this.#notifies) {
2982
+ if (this.#state.pool === void 0 || !this.#state.notifies) {
2335
2983
  return void 0;
2336
2984
  }
2337
- const options = this.#pool.options;
2985
+ const options = this.#state.pool.options;
2338
2986
  const watcher = new NotificationListener(
2339
2987
  async () => {
2340
2988
  const client = new pg.Client(options);
2989
+ this.#owned.track(client);
2341
2990
  await client.connect();
2342
2991
  return client;
2343
2992
  },
2344
- this.#notificationChannel,
2993
+ this.#state.notificationChannel,
2345
2994
  listener,
2346
- this.#logger
2995
+ this.#state.logger
2347
2996
  );
2348
2997
  await watcher.start();
2349
2998
  return () => watcher.close();
2350
2999
  }
2351
3000
  /** Frees the lanes `leaseOwner` holds that run no delivery, so other workers need not wait for the lease to expire. */
2352
- async relinquish(leaseOwner) {
2353
- await this.#query(this.#statements.relinquish, [leaseOwner]);
3001
+ relinquish(leaseOwner) {
3002
+ return this.#maintenance.relinquish(leaseOwner);
2354
3003
  }
2355
- async listDeliveries(query) {
2356
- const statement = this.#statements.listDeliveries(query);
2357
- const rows = await this.#executor.query(statement.sql, statement.parameters);
2358
- return rows.map(mapDeliveryRecord);
3004
+ listDeliveries(query) {
3005
+ return this.#maintenance.listDeliveries(query);
2359
3006
  }
2360
- async requeue(deliveryIds, now) {
2361
- const rows = await this.#query(this.#statements.requeue, [
2362
- JSON.stringify(deliveryIds),
2363
- now.toISOString()
2364
- ]);
2365
- return readCount(rows[0], "count");
3007
+ requeue(deliveryIds, now) {
3008
+ return this.#maintenance.requeue(deliveryIds, now);
2366
3009
  }
2367
3010
  /**
2368
3011
  * Deletes purgeable deliveries in batches of `purgeBatchSize`, one short
@@ -2373,239 +3016,94 @@ var PostgresEventStore = class {
2373
3016
  * was subscribed. Events that a concurrent publish is attaching a delivery
2374
3017
  * to are skipped and kept.
2375
3018
  */
2376
- async purge(request) {
2377
- const total = { deletedDeliveries: 0, deletedEvents: 0 };
2378
- const batches = [
2379
- [
2380
- this.#statements.purgeCompletedBatch(),
2381
- request.completedBefore,
2382
- this.#statements.deleteOrphanEventsWithoutCompletion
2383
- ],
2384
- [
2385
- this.#statements.purgeDeadBatch(),
2386
- request.deadBefore,
2387
- this.#statements.deleteOrphanEventsWithoutCompletion
2388
- ]
2389
- ];
2390
- if (this.#completionHistory) {
2391
- batches.push([
2392
- this.#statements.purgeCompletionHistoryBatch(),
2393
- request.completedBefore,
2394
- this.#statements.deleteOrphanEventsWithoutCompletion
2395
- ]);
2396
- }
2397
- for (const [sql, cutoff, deleteOrphans] of batches) {
2398
- if (cutoff === void 0) {
2399
- continue;
2400
- }
2401
- let deletedInBatch = this.#purgeBatchSize;
2402
- while (deletedInBatch === this.#purgeBatchSize) {
2403
- const batch = await this.#purgeBatch(sql, cutoff, deleteOrphans);
2404
- deletedInBatch = batch.deletedDeliveries;
2405
- total.deletedDeliveries += batch.deletedDeliveries;
2406
- total.deletedEvents += batch.deletedEvents;
2407
- }
2408
- }
2409
- const orphanCutoff = [request.completedBefore, request.deadBefore].filter((cutoff) => cutoff !== void 0).sort((first, second) => first.getTime() - second.getTime())[0];
2410
- if (orphanCutoff !== void 0) {
2411
- total.deletedEvents += await this.#purgeOrphanEvents(
2412
- this.#statements.lockOrphanEventsBatch,
2413
- this.#statements.deleteOrphanEventsWithoutCompletion,
2414
- orphanCutoff,
2415
- false
2416
- );
2417
- }
2418
- if (request.completedBefore !== void 0) {
2419
- total.deletedEvents += await this.#purgeOrphanEvents(
2420
- this.#statements.lockCompletedOrphanEventsBatch,
2421
- this.#statements.deleteExpiredCompletedOrphanEvents,
2422
- request.completedBefore,
2423
- true
2424
- );
2425
- }
2426
- return total;
2427
- }
2428
- async statistics(now) {
2429
- const stored = { pending: 0, dead: 0, completed: 0 };
2430
- for (const row of await this.#query(this.#statements.countByStatus, [])) {
2431
- stored[row["status"]] = readCount(row, "count");
2432
- }
2433
- const [running] = await this.#query(this.#statements.countRunning, []);
2434
- const processing = readCount(running, "count");
2435
- let completed = stored["completed"];
2436
- if (this.#completionHistory) {
2437
- const [history] = await this.#query(this.#statements.countCompletionHistory, []);
2438
- completed += readCount(history, "count");
2439
- }
2440
- const oldestDue = await this.#query(this.#statements.oldestDue, [now.toISOString()]);
2441
- return {
2442
- // The counts come from separate statements; a delivery that finishes in between must not make this negative.
2443
- pending: Math.max(0, stored["pending"] - processing),
2444
- processing,
2445
- completed,
2446
- dead: stored["dead"],
2447
- oldestDueAt: mapOldestDueAt(oldestDue)
2448
- };
2449
- }
2450
- /** Ends the pool this store created from `connectionString`. Pools and executors you passed in stay open. */
2451
- async close() {
2452
- this.#closed = true;
2453
- clearTimeout(this.#trailingNotification);
2454
- this.#trailingNotification = void 0;
2455
- const pool = this.#ownedPool;
2456
- this.#ownedPool = void 0;
2457
- await pool?.end();
2458
- }
2459
- /** Runs a statement of {@link PostgresStatements} whose text never changes, prepared when `preparedStatements` is on. */
2460
- #query(sql, parameters, transaction) {
2461
- return this.#executor.query(sql, parameters, transaction, this.#queryOptions);
3019
+ purge(request) {
3020
+ return this.#maintenance.purge(request);
2462
3021
  }
2463
- async #changed(sql, parameters) {
2464
- const rows = await this.#query(sql, parameters);
2465
- return readCount(rows[0], "count") > 0;
2466
- }
2467
- /** Runs `operation` for a lease this store issued; any other token cannot be held. */
2468
- async #whenIssued(lease, operation) {
2469
- const held = parseLeaseToken(lease.leaseToken);
2470
- return held !== void 0 && await operation(held);
3022
+ statistics(now) {
3023
+ return this.#maintenance.statistics(now);
2471
3024
  }
2472
3025
  /**
2473
- * Deletes the delivery of every lease that is still the current claim of its
2474
- * delivery. Returns one flag per lease, in order. Results are matched to leases
2475
- * by position, so two leases of one delivery (a stale and a current one) get
2476
- * their own answers; a lease listed twice completes once, at its first position.
3026
+ * Ends the pool this store created from `connectionString`. Pools and executors you passed in stay
3027
+ * open. Once `options.signal` aborts (the shutdown deadline passed), the connections the store opened
3028
+ * itself are destroyed: queries still running on them fail at once instead of holding the shutdown.
2477
3029
  */
2478
- async #completeLeases(leases, now, transaction) {
2479
- const issued = [];
2480
- const seen = /* @__PURE__ */ new Set();
2481
- leases.forEach((lease, ord) => {
2482
- const held = parseLeaseToken(lease.leaseToken);
2483
- const identity = `${lease.deliveryId}\0${lease.leaseToken}`;
2484
- if (held !== void 0 && !seen.has(identity)) {
2485
- seen.add(identity);
2486
- issued.push({ ord, id: lease.deliveryId, ...held });
2487
- }
2488
- });
2489
- const completed = /* @__PURE__ */ new Set();
2490
- if (issued.length > 0) {
2491
- const rows = await this.#query(
2492
- this.#statements.complete,
2493
- [JSON.stringify(issued), now.toISOString()],
2494
- transaction
2495
- );
2496
- for (const row of rows) {
2497
- completed.add(readCount(row, "ord"));
2498
- }
3030
+ async close(options = {}) {
3031
+ this.#state.closed = true;
3032
+ this.#state.trailingNotification?.();
3033
+ this.#state.trailingNotification = void 0;
3034
+ const pool = this.#state.ownedPool;
3035
+ this.#state.ownedPool = void 0;
3036
+ const { signal } = options;
3037
+ const force = () => this.#owned.destroyAll();
3038
+ if (signal?.aborted === true) {
3039
+ force();
2499
3040
  }
2500
- if (transaction === void 0) {
2501
- for (const lease of leases) {
2502
- this.#handedOut.delete(handedOutKey(lease.deliveryId, lease.leaseToken));
2503
- }
3041
+ signal?.addEventListener("abort", force, { once: true });
3042
+ try {
3043
+ await pool?.end();
3044
+ } finally {
3045
+ signal?.removeEventListener("abort", force);
2504
3046
  }
2505
- return leases.map((_, ord) => completed.has(ord));
2506
3047
  }
2507
- async #purgeOrphanEvents(lockStatement, deleteStatement, cutoff, recheckCutoff) {
2508
- let deletedEvents = 0;
2509
- let removedInBatch = this.#purgeBatchSize;
2510
- while (removedInBatch === this.#purgeBatchSize) {
2511
- removedInBatch = await this.#executor.transaction(async (transaction) => {
2512
- const locked = await this.#query(
2513
- lockStatement,
2514
- [cutoff.toISOString(), this.#purgeBatchSize],
2515
- transaction
2516
- );
2517
- const ids = JSON.stringify(locked.map((row) => row["id"]));
2518
- const removed = await this.#query(
2519
- deleteStatement,
2520
- recheckCutoff ? [ids, cutoff.toISOString()] : [ids],
2521
- transaction
2522
- );
2523
- return readCount(removed[0], "count");
2524
- });
2525
- deletedEvents += removedInBatch;
2526
- }
2527
- return deletedEvents;
3048
+ };
3049
+ function resolveStoreSettings(options) {
3050
+ const sources = [options.pool, options.connectionString, options.executor].filter(
3051
+ (source) => source !== void 0
3052
+ );
3053
+ if (sources.length !== 1) {
3054
+ throw new core.ConfigurationError(
3055
+ "PostgresEventStore needs exactly one of pool, connectionString or executor"
3056
+ );
2528
3057
  }
2529
- async #purgeBatch(sql, cutoff, deleteOrphans) {
2530
- return this.#executor.transaction(async (transaction) => {
2531
- const deleted = await this.#query(
2532
- sql,
2533
- [cutoff.toISOString(), this.#purgeBatchSize],
2534
- transaction
2535
- );
2536
- if (deleted.length === 0) {
2537
- return { deletedDeliveries: 0, deletedEvents: 0 };
2538
- }
2539
- const eventIds = JSON.stringify([
2540
- ...new Set(deleted.map((row) => row["event_id"]))
2541
- ]);
2542
- const locked = await this.#query(this.#statements.lockEvents, [eventIds], transaction);
2543
- const removed = await this.#query(
2544
- deleteOrphans,
2545
- [JSON.stringify(locked.map((row) => row["id"]))],
2546
- transaction
2547
- );
2548
- return { deletedDeliveries: deleted.length, deletedEvents: readCount(removed[0], "count") };
2549
- });
3058
+ const purgeBatchSize = internal.assertPositiveInteger(
3059
+ options.purgeBatchSize ?? DEFAULT_PURGE_BATCH_SIZE,
3060
+ "purgeBatchSize"
3061
+ );
3062
+ const wakeUp = options.wakeUp ?? "notify";
3063
+ if (!WAKE_UPS.includes(wakeUp)) {
3064
+ throw new core.ConfigurationError(`wakeUp must be 'notify' or 'poll', received ${String(wakeUp)}`);
2550
3065
  }
2551
- };
2552
- function planAppend(entries) {
2553
- const events = [];
2554
- const deliveries = [];
2555
- const outcomes = [];
2556
- const seenEventIds = /* @__PURE__ */ new Set();
2557
- const seenDeliveries = /* @__PURE__ */ new Set();
2558
- for (const { event, deliveries: newDeliveries } of entries) {
2559
- const repeated = seenEventIds.has(event.id);
2560
- seenEventIds.add(event.id);
2561
- outcomes.push({ eventId: event.id, repeated });
2562
- if (!repeated) {
2563
- events.push(event);
2564
- }
2565
- for (const delivery of newDeliveries) {
2566
- const identity = `${event.id}\0${delivery.handler}`;
2567
- if (!seenDeliveries.has(identity)) {
2568
- seenDeliveries.add(identity);
2569
- deliveries.push({
2570
- id: delivery.id,
2571
- event_id: event.id,
2572
- handler: delivery.handler,
2573
- available_at: delivery.availableAt.toISOString()
2574
- });
2575
- }
2576
- }
3066
+ const preparedStatements = options.preparedStatements ?? true;
3067
+ if (typeof preparedStatements !== "boolean") {
3068
+ throw new core.ConfigurationError(
3069
+ `preparedStatements must be a boolean, received ${String(preparedStatements)}`
3070
+ );
2577
3071
  }
2578
- return { events, deliveries, outcomes };
2579
- }
2580
- function toEventRow(event, sequence, handlers) {
2581
3072
  return {
2582
- id: event.id,
2583
- type: event.type,
2584
- source: event.source,
2585
- key: event.key,
2586
- sequence,
2587
- payload: event.payload,
2588
- headers: event.headers,
2589
- correlation_id: event.correlationId,
2590
- causation_id: event.causationId,
2591
- occurred_at: event.occurredAt.toISOString(),
2592
- handlers
3073
+ purgeBatchSize,
3074
+ wakeUp,
3075
+ queryOptions: preparedStatements ? { prepare: true } : void 0
2593
3076
  };
2594
3077
  }
2595
- function compareSequence(left, right) {
2596
- const first = BigInt(left["sequence"] ?? 0);
2597
- const second = BigInt(right["sequence"] ?? 0);
2598
- return Number(first > second) - Number(first < second);
2599
- }
2600
- function compareDue(left, right) {
2601
- return compareText(left["due_at"], right["due_at"]) || compareText(left["delivery_id"], right["delivery_id"]);
2602
- }
2603
- function compareText(left, right) {
2604
- return Number(left > right) - Number(left < right);
3078
+ function connect(options, { logger, owned }) {
3079
+ if (options.executor !== void 0) {
3080
+ return { executor: options.executor, pool: void 0, ownedPool: void 0 };
3081
+ }
3082
+ const pool = options.pool ?? new pg.Pool({
3083
+ ...options.poolConfig,
3084
+ connectionString: options.connectionString,
3085
+ Client: owned.clientClass()
3086
+ });
3087
+ let ownedPool;
3088
+ if (options.pool === void 0) {
3089
+ const poolLogger = options.logger ?? console;
3090
+ pool.on("error", (error) => {
3091
+ poolLogger.error(
3092
+ `[PostgresEventStore](connect) Idle connection failed, the pool replaces it | error=${error.message}`
3093
+ );
3094
+ });
3095
+ ownedPool = pool;
3096
+ }
3097
+ const executor = new PgExecutor(pool, {
3098
+ logger,
3099
+ sessionBudget: ownedPool !== void 0 && options.preparedStatements !== false
3100
+ });
3101
+ return { executor, pool, ownedPool };
2605
3102
  }
2606
3103
 
2607
3104
  exports.PgExecutor = PgExecutor;
2608
3105
  exports.PostgresEventStore = PostgresEventStore;
3106
+ exports.ReconcileFailedError = ReconcileFailedError;
2609
3107
  exports.createPostgresSchemaSql = createPostgresSchemaSql;
2610
3108
  exports.createPostgresSchemaStatements = createPostgresSchemaStatements;
2611
3109
  exports.resolvePostgresNames = resolvePostgresNames;