@vercel/board 0.56.1 → 0.57.1

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