@niscorp/tide 0.1.5 → 0.1.7

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.
@@ -0,0 +1,590 @@
1
+ 'use strict';
2
+
3
+ var postgres = require('@niscorp/strata/postgres');
4
+ var zod = require('zod');
5
+
6
+ // src/store/postgres/store.ts
7
+
8
+ // src/types.ts
9
+ var PRIMARY_KEY = {
10
+ fact: "id",
11
+ run: "id",
12
+ task: "id",
13
+ state: "reflexId"
14
+ };
15
+ var UNIQUE_BY = {
16
+ // `entity` is in the key: two polls over different tables can agree on a cursor value.
17
+ fact: { by: ["kind", "entity", "name", "dedupeKey"], when: "dedupeKey" },
18
+ run: { by: ["reflexId", "cause"] },
19
+ task: { by: ["runId", "unit"] },
20
+ state: { by: ["reflexId"] }
21
+ };
22
+ var WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
23
+ var HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
24
+ var MMDD = /^(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
25
+ var LOCAL_DATETIME = /^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/;
26
+ var ClockUnitSchema = zod.z.enum(["day", "week", "month", "year"]);
27
+ var ClockRecurringSchema = zod.z.object({
28
+ every: ClockUnitSchema.describe("The calendar period it repeats on. A repeating clock fires on every such period until the reflex is removed \u2014 only for a request that says it repeats."),
29
+ on: zod.z.union([zod.z.number().int().min(1).max(31), zod.z.enum(WEEKDAYS), zod.z.string().regex(MMDD)]).optional().describe('week \u2192 a weekday; month \u2192 1..31 (clamped to month end); year \u2192 "MM-DD". Omitted for day.'),
30
+ at: zod.z.string().regex(HHMM).describe('Local wall-clock time, "HH:MM".'),
31
+ tz: zod.z.string().describe("IANA timezone name.")
32
+ }).strict().superRefine((clock, ctx) => {
33
+ const fail = (message) => ctx.addIssue({ code: "custom", message, path: ["on"] });
34
+ if (clock.every === "day" && clock.on !== void 0) fail("a daily clock takes no `on`");
35
+ if (clock.every === "week" && !(typeof clock.on === "string" && WEEKDAYS.some((d) => d === clock.on)))
36
+ fail("a weekly clock needs `on` as a weekday (mon..sun)");
37
+ if (clock.every === "month" && typeof clock.on !== "number") fail("a monthly clock needs `on` as a day number");
38
+ if (clock.every === "year" && !(typeof clock.on === "string" && MMDD.test(clock.on)))
39
+ fail('a yearly clock needs `on` as "MM-DD"');
40
+ }).describe("Repeats: fires on every day, week, month or year, at a time of day, until the reflex is removed.");
41
+ var ClockOnceSchema = zod.z.object({
42
+ at: zod.z.string().regex(LOCAL_DATETIME).describe('A fixed local date and time, once: "YYYY-MM-DDTHH:MM" or, to the second, "YYYY-MM-DDTHH:MM:SS".'),
43
+ tz: zod.z.string().describe("IANA timezone name.")
44
+ }).strict().describe("Once: fires at one date and time, then never again.");
45
+ var ClockTriggerSchema = zod.z.object({ clock: zod.z.union([ClockRecurringSchema, ClockOnceSchema]) }).strict().describe("Fires on the calendar: once, at a date and time, or repeating at a time of day.");
46
+ var OpSchema = zod.z.enum(["insert", "update", "delete"]);
47
+ var WriteTriggerSchema = zod.z.object({
48
+ fact: zod.z.object({
49
+ entity: zod.z.string().describe("The table or entity whose writes wake this reflex."),
50
+ op: OpSchema.optional().describe('Narrow to one op \u2014 "only on create" is op: "insert".')
51
+ }).strict()
52
+ }).strict().describe("Fires when a row of an entity is written \u2014 created, changed or deleted.");
53
+ var SignalTriggerSchema = zod.z.object({ fact: zod.z.object({ signal: zod.z.string().describe("A named external intake.") }).strict() }).strict().describe("Fires when an event arrives from outside, on a named intake.");
54
+ var RunTriggerSchema = zod.z.object({
55
+ fact: zod.z.object({ run: zod.z.string().describe("A reflex id \u2014 fires when THAT reflex's run settles. Fan-in and dependency.") }).strict()
56
+ }).strict().describe("Fires when another reflex has run: one automation after another.");
57
+ var ManualTriggerSchema = zod.z.object({ manual: zod.z.object({}).strict() }).strict().describe("Fires only when somebody fires it by hand.");
58
+ zod.z.union([
59
+ ClockTriggerSchema,
60
+ WriteTriggerSchema,
61
+ SignalTriggerSchema,
62
+ RunTriggerSchema,
63
+ ManualTriggerSchema
64
+ ]);
65
+ var FactKindSchema = zod.z.enum(["write", "signal", "manual", "run"]);
66
+ zod.z.object({
67
+ kind: FactKindSchema,
68
+ entity: zod.z.string().optional().describe("Which table or entity was written."),
69
+ op: OpSchema.optional().describe('Ops are distinct stimuli \u2014 "only on create" is op: "insert".'),
70
+ row: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("The row, as the write returned it."),
71
+ name: zod.z.string().optional().describe("Which named intake this arrived on."),
72
+ payload: zod.z.unknown().optional().describe("The event body \u2014 validated at the HOST boundary before it gets here."),
73
+ reflex: zod.z.string().optional(),
74
+ runId: zod.z.string().optional(),
75
+ occurrence: zod.z.string().optional().describe("The calendar key, when the clock was the cause."),
76
+ stats: zod.z.object({ total: zod.z.number().int(), done: zod.z.number().int(), failed: zod.z.number().int() }).strict().optional(),
77
+ target: zod.z.string().optional().describe("The one reflex a manual fact is aimed at."),
78
+ by: zod.z.string().optional().describe("Who fired it \u2014 recorded on the firing as manual:<who>."),
79
+ at: zod.z.number().int().describe("Supplied by the caller. Tide reads no clocks."),
80
+ notBefore: zod.z.number().int().optional().describe("A delayed fact \u2014 timers as data, visible and queryable."),
81
+ dedupeKey: zod.z.string().optional().describe("Provider event ids. A repeat is refused and announced as fact.deduped; it is not an error."),
82
+ cause: zod.z.string().optional().describe("Set by tide when an effect emits \u2014 the causality chain.")
83
+ }).strict().superRefine((fact, ctx) => {
84
+ const require2 = (field, why) => {
85
+ if (fact[field] === void 0)
86
+ ctx.addIssue({ code: "custom", message: `a ${fact.kind} fact needs \`${String(field)}\` \u2014 ${why}`, path: [field] });
87
+ };
88
+ const refuse = (field) => {
89
+ if (fact[field] !== void 0)
90
+ ctx.addIssue({ code: "custom", message: `\`${String(field)}\` is not part of a ${fact.kind} fact`, path: [field] });
91
+ };
92
+ if (fact.kind === "write") {
93
+ require2("entity", "it is what a write trigger matches on");
94
+ refuse("name");
95
+ refuse("target");
96
+ refuse("runId");
97
+ }
98
+ if (fact.kind === "signal") {
99
+ require2("name", "it is which named intake this arrived on");
100
+ refuse("entity");
101
+ refuse("op");
102
+ refuse("target");
103
+ refuse("runId");
104
+ }
105
+ if (fact.kind === "manual") {
106
+ require2("target", "a manual fact is aimed at exactly one reflex");
107
+ refuse("entity");
108
+ refuse("name");
109
+ refuse("runId");
110
+ }
111
+ if (fact.kind === "run") {
112
+ require2("reflex", "it is whose run settled");
113
+ require2("runId", "it is which run settled");
114
+ refuse("entity");
115
+ refuse("name");
116
+ refuse("target");
117
+ }
118
+ });
119
+
120
+ // src/store/postgres/rows.ts
121
+ var SQL_TABLE = {
122
+ fact: "tide_fact",
123
+ run: "tide_run",
124
+ task: "tide_work",
125
+ state: "tide_reflex_state"
126
+ };
127
+ var COLUMN_OVERRIDES = { as: "as_who" };
128
+ var snake = (field) => COLUMN_OVERRIDES[field] ?? field.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
129
+ var camel = (column) => {
130
+ for (const [field, mapped] of Object.entries(COLUMN_OVERRIDES)) if (mapped === column) return field;
131
+ return column.replace(/_([a-z])/g, (_all, c) => c.toUpperCase());
132
+ };
133
+ var JSON_COLUMNS = /* @__PURE__ */ new Set(["row", "payload", "stats", "fact_ids", "env", "input", "output"]);
134
+ var BIGINT_COLUMNS = /* @__PURE__ */ new Set([
135
+ "at",
136
+ "not_before",
137
+ "delivered_at",
138
+ "depth",
139
+ "descendants",
140
+ "due_at",
141
+ "created_at",
142
+ "settled_at",
143
+ "claimed_until",
144
+ "armed_at",
145
+ "materialized_through",
146
+ "attempt",
147
+ "selected",
148
+ "total",
149
+ "done",
150
+ "failed"
151
+ ]);
152
+ var toColumn = (column, value) => {
153
+ if (value === void 0) return null;
154
+ if (JSON_COLUMNS.has(column)) return JSON.stringify(value);
155
+ return value;
156
+ };
157
+ var fromColumn = (column, value) => {
158
+ if (value === null) return void 0;
159
+ if (JSON_COLUMNS.has(column)) return typeof value === "string" ? JSON.parse(value) : value;
160
+ if (BIGINT_COLUMNS.has(column)) return Number(value);
161
+ return value;
162
+ };
163
+ var FactRowSchema = zod.z.object({
164
+ id: zod.z.string(),
165
+ kind: FactKindSchema,
166
+ entity: zod.z.string().optional(),
167
+ op: OpSchema.optional(),
168
+ row: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
169
+ name: zod.z.string().optional(),
170
+ payload: zod.z.unknown().optional(),
171
+ reflex: zod.z.string().optional(),
172
+ runId: zod.z.string().optional(),
173
+ occurrence: zod.z.string().optional(),
174
+ stats: zod.z.object({ total: zod.z.number(), done: zod.z.number(), failed: zod.z.number() }).optional(),
175
+ target: zod.z.string().optional(),
176
+ by: zod.z.string().optional(),
177
+ at: zod.z.number(),
178
+ notBefore: zod.z.number().optional(),
179
+ dedupeKey: zod.z.string().optional(),
180
+ cause: zod.z.string().optional(),
181
+ depth: zod.z.number(),
182
+ deliveredAt: zod.z.number().optional(),
183
+ parked: zod.z.string().optional(),
184
+ released: zod.z.boolean().optional(),
185
+ as: zod.z.string().optional(),
186
+ root: zod.z.string().optional(),
187
+ descendants: zod.z.number().optional()
188
+ });
189
+ var RunRowSchema = zod.z.object({
190
+ id: zod.z.string(),
191
+ reflexId: zod.z.string(),
192
+ version: zod.z.string(),
193
+ as: zod.z.string().optional(),
194
+ cause: zod.z.string(),
195
+ occurrence: zod.z.string().optional(),
196
+ factIds: zod.z.array(zod.z.string()).optional(),
197
+ state: zod.z.enum(["pending", "fanned", "settled", "skipped"]),
198
+ depth: zod.z.number(),
199
+ selected: zod.z.number().optional(),
200
+ total: zod.z.number(),
201
+ done: zod.z.number(),
202
+ failed: zod.z.number(),
203
+ dueAt: zod.z.number(),
204
+ createdAt: zod.z.number(),
205
+ settledAt: zod.z.number().optional(),
206
+ drained: zod.z.boolean().optional(),
207
+ note: zod.z.string().optional()
208
+ });
209
+ var TaskRowSchema = zod.z.object({
210
+ id: zod.z.string(),
211
+ runId: zod.z.string(),
212
+ reflexId: zod.z.string(),
213
+ unit: zod.z.string(),
214
+ cause: zod.z.string(),
215
+ env: zod.z.record(zod.z.string(), zod.z.unknown()),
216
+ depth: zod.z.number(),
217
+ state: zod.z.enum(["pending", "claimed", "retrying", "done", "failed"]),
218
+ attempt: zod.z.number(),
219
+ token: zod.z.string().optional(),
220
+ claimedUntil: zod.z.number(),
221
+ notBefore: zod.z.number(),
222
+ input: zod.z.unknown().optional(),
223
+ output: zod.z.unknown().optional(),
224
+ error: zod.z.string().optional(),
225
+ createdAt: zod.z.number(),
226
+ settledAt: zod.z.number().optional()
227
+ });
228
+ var StateRowSchema = zod.z.object({
229
+ reflexId: zod.z.string(),
230
+ armedAt: zod.z.number(),
231
+ materializedThrough: zod.z.number().optional()
232
+ });
233
+ var ROW_SCHEMAS = {
234
+ fact: FactRowSchema,
235
+ run: RunRowSchema,
236
+ task: TaskRowSchema,
237
+ state: StateRowSchema
238
+ };
239
+ var rowToEntity = (table, row) => {
240
+ const entity = {};
241
+ for (const [column, value] of Object.entries(row)) {
242
+ const mapped = fromColumn(column, value);
243
+ if (mapped !== void 0) entity[camel(column)] = mapped;
244
+ }
245
+ const read = ROW_SCHEMAS[table].safeParse(entity);
246
+ if (!read.success) {
247
+ const misfits = read.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
248
+ throw new Error(`tide store: a row of ${SQL_TABLE[table]} does not read as a ${table} (${misfits})`);
249
+ }
250
+ return read.data;
251
+ };
252
+
253
+ // src/store/postgres/compile.ts
254
+ var COMPARATORS = [
255
+ ["eq", "="],
256
+ ["ne", "<>"],
257
+ ["lt", "<"],
258
+ ["lte", "<="],
259
+ ["gt", ">"],
260
+ ["gte", ">="]
261
+ ];
262
+ var ComparisonSchema = zod.z.object({
263
+ eq: zod.z.unknown().optional(),
264
+ ne: zod.z.unknown().optional(),
265
+ lt: zod.z.unknown().optional(),
266
+ lte: zod.z.unknown().optional(),
267
+ gt: zod.z.unknown().optional(),
268
+ gte: zod.z.unknown().optional(),
269
+ in: zod.z.array(zod.z.unknown()).readonly().optional(),
270
+ notIn: zod.z.array(zod.z.unknown()).readonly().optional(),
271
+ isNull: zod.z.boolean().optional()
272
+ });
273
+ var comparisonOn = (field, test) => {
274
+ const read = ComparisonSchema.safeParse(test);
275
+ if (read.success) return read.data;
276
+ const misfits = read.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
277
+ throw new Error(`tide store: what "${field}" is compared with does not read as a comparison (${misfits})`);
278
+ };
279
+ var compileWhere = (where, start, alias = "") => {
280
+ const clauses = [];
281
+ const params = [];
282
+ const prefix = alias === "" ? "" : `${alias}.`;
283
+ const slot = (value) => {
284
+ params.push(value);
285
+ return `$${start + params.length - 1}`;
286
+ };
287
+ for (const [field, test] of Object.entries(where ?? {})) {
288
+ const column = `${prefix}${snake(field)}`;
289
+ const bare = snake(field);
290
+ if (test === null || typeof test !== "object" || Array.isArray(test)) {
291
+ clauses.push(test === void 0 ? `${column} IS NULL` : `${column} = ${slot(toColumn(bare, test))}`);
292
+ continue;
293
+ }
294
+ const comparison = comparisonOn(field, test);
295
+ for (const [op, symbol] of COMPARATORS) {
296
+ const operand = comparison[op];
297
+ if (operand === void 0) continue;
298
+ clauses.push(op === "ne" ? `(${column} IS NULL OR ${column} <> ${slot(toColumn(bare, operand))})` : `${column} ${symbol} ${slot(toColumn(bare, operand))}`);
299
+ }
300
+ if (comparison.in !== void 0) clauses.push(`${column} = ANY(${slot(comparison.in.map((value) => toColumn(bare, value)))})`);
301
+ if (comparison.notIn !== void 0) clauses.push(`NOT (${column} = ANY(${slot(comparison.notIn.map((value) => toColumn(bare, value)))}))`);
302
+ if (comparison.isNull !== void 0) clauses.push(comparison.isNull ? `${column} IS NULL` : `${column} IS NOT NULL`);
303
+ }
304
+ return { sql: clauses.length === 0 ? "TRUE" : clauses.join(" AND "), params };
305
+ };
306
+ var compileOrder = (order, alias = "") => {
307
+ if (order === void 0 || order.length === 0) return "";
308
+ const prefix = alias === "" ? "" : `${alias}.`;
309
+ return ` ORDER BY ${order.map((key) => `${prefix}${snake(key.by)} ${key.dir === "desc" ? "DESC" : "ASC"}`).join(", ")}`;
310
+ };
311
+ var sortRows = (rows, order) => {
312
+ if (order === void 0 || order.length === 0) return [...rows];
313
+ return [...rows].sort((left, right) => {
314
+ for (const key of order) {
315
+ const a = left[key.by];
316
+ const b = right[key.by];
317
+ const compared = typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
318
+ if (compared !== 0) return compared * (key.dir === "desc" ? -1 : 1);
319
+ }
320
+ return 0;
321
+ });
322
+ };
323
+ var compileSet = (set, start) => {
324
+ const assignments = [];
325
+ const params = [];
326
+ for (const [field, value] of Object.entries(set)) {
327
+ const column = snake(field);
328
+ if (value !== null && typeof value === "object" && "inc" in value) {
329
+ assignments.push(`${column} = coalesce(${column}, 0) + ${Number(value.inc)}`);
330
+ continue;
331
+ }
332
+ params.push(toColumn(column, value));
333
+ assignments.push(`${column} = $${start + params.length - 1}`);
334
+ }
335
+ return { sql: assignments.join(", "), params };
336
+ };
337
+
338
+ // src/store/postgres/claim.ts
339
+ var claimOver = ({ client, atomically, ready }) => async (spec) => {
340
+ await ready;
341
+ const table = SQL_TABLE[spec.table];
342
+ const order = compileOrder(spec.order, "c");
343
+ const take = async (db, extra, limit) => {
344
+ if (limit <= 0) return [];
345
+ const where = compileWhere({ ...spec.where, ...extra }, 1, "c");
346
+ const set = compileSet(spec.set, where.params.length + 1);
347
+ const result = await db.query(
348
+ `UPDATE ${table} SET ${set.sql}
349
+ WHERE ctid IN (
350
+ SELECT c.ctid FROM ${table} c WHERE ${where.sql}${order}
351
+ LIMIT ${Math.floor(limit)} FOR UPDATE SKIP LOCKED
352
+ )
353
+ RETURNING *`,
354
+ [...where.params, ...set.params]
355
+ );
356
+ return sortRows(result.rows.map((row) => rowToEntity(spec.table, row)), spec.order);
357
+ };
358
+ if (spec.onePer === void 0) return take(client, {}, spec.limit);
359
+ const { column, held, only } = spec.onePer;
360
+ const restricted = [...only];
361
+ const claimed = await take(client, { [column]: { notIn: restricted } }, spec.limit - restricted.length);
362
+ const takeOneOf = (group) => atomically(async (tx) => {
363
+ const lock = await tx.query("SELECT pg_try_advisory_xact_lock(hashtext($1), hashtext($2)) AS free", [`tide:${table}.${snake(column)}`, group]);
364
+ if (lock.rows[0]?.["free"] !== true) return [];
365
+ const busy = compileWhere({ ...held, [column]: group }, 1, "c");
366
+ const taken = await tx.query(`SELECT c.id FROM ${table} c WHERE ${busy.sql} LIMIT 1`, busy.params);
367
+ if (taken.rows.length > 0) return [];
368
+ return take(tx, { [column]: group }, 1);
369
+ });
370
+ for (const group of restricted) {
371
+ if (claimed.length >= spec.limit) break;
372
+ claimed.push(...await takeOneOf(group));
373
+ }
374
+ return claimed;
375
+ };
376
+
377
+ // src/store/postgres/tables.ts
378
+ var TIDE_TABLES = ["tide_fact", "tide_run", "tide_work", "tide_reflex_state"];
379
+ var TIDE_DDL = `
380
+ CREATE TABLE IF NOT EXISTS tide_fact (
381
+ id text PRIMARY KEY,
382
+ kind text NOT NULL CHECK (kind IN ('write','signal','manual','run')),
383
+ entity text,
384
+ op text CHECK (op IN ('insert','update','delete')),
385
+ row jsonb,
386
+ name text,
387
+ payload jsonb,
388
+ reflex text,
389
+ run_id text,
390
+ occurrence text,
391
+ stats jsonb,
392
+ target text,
393
+ by text,
394
+ at bigint NOT NULL,
395
+ not_before bigint,
396
+ dedupe_key text,
397
+ cause text,
398
+ depth integer NOT NULL DEFAULT 0,
399
+ delivered_at bigint,
400
+ parked text,
401
+ released boolean,
402
+ -- WHOSE FACT THIS IS. The identity of the reflex that minted it, absent on
403
+ -- anything the host ingested. The matcher refuses to hand a fact minted
404
+ -- under one identity to a reflex running under another, which is the only
405
+ -- thing standing between a carried row and somebody else's effect \u2014 tide is
406
+ -- the one place a row travels without being read, so no scope policy is
407
+ -- consulted on the way.
408
+ as_who text
409
+ );
410
+
411
+ -- A PARTIAL index, because a fact with no dedupeKey is not claiming to be
412
+ -- unique: it is a distinct occurrence of something, not a repeat of it.
413
+ -- entity is in the key: without it, two producers over different tables
414
+ -- that agreed on a key value silently ate each other's rows.
415
+ CREATE UNIQUE INDEX IF NOT EXISTS tide_fact_dedupe
416
+ ON tide_fact (kind, coalesce(entity,''), coalesce(name,''), dedupe_key)
417
+ WHERE dedupe_key IS NOT NULL;
418
+
419
+ -- The matcher's query, every advance.
420
+ CREATE INDEX IF NOT EXISTS tide_fact_due
421
+ ON tide_fact (at) WHERE delivered_at IS NULL AND parked IS NULL;
422
+ CREATE INDEX IF NOT EXISTS tide_fact_swept ON tide_fact (delivered_at);
423
+
424
+ CREATE TABLE IF NOT EXISTS tide_run (
425
+ id text PRIMARY KEY,
426
+ reflex_id text NOT NULL,
427
+ version text NOT NULL,
428
+ as_who text,
429
+ cause text NOT NULL,
430
+ occurrence text,
431
+ fact_ids jsonb,
432
+ state text NOT NULL CHECK (state IN ('pending','fanned','settled','skipped')),
433
+ depth integer NOT NULL DEFAULT 0,
434
+ selected integer,
435
+ total integer NOT NULL DEFAULT 0,
436
+ done integer NOT NULL DEFAULT 0,
437
+ failed integer NOT NULL DEFAULT 0,
438
+ due_at bigint NOT NULL,
439
+ created_at bigint NOT NULL,
440
+ settled_at bigint,
441
+ drained boolean,
442
+ note text,
443
+ -- THE IDEMPOTENCY. One constraint, every trigger kind: an occurrence
444
+ -- cannot open twice, a replayed fact cannot open twice, and two instances
445
+ -- ticking at the same moment contend instead of duplicating.
446
+ UNIQUE (reflex_id, cause)
447
+ );
448
+
449
+ CREATE INDEX IF NOT EXISTS tide_run_pending ON tide_run (state, due_at);
450
+ CREATE INDEX IF NOT EXISTS tide_run_ledger ON tide_run (reflex_id, created_at DESC);
451
+ CREATE INDEX IF NOT EXISTS tide_run_swept ON tide_run (settled_at);
452
+
453
+ CREATE TABLE IF NOT EXISTS tide_work (
454
+ id text PRIMARY KEY,
455
+ -- ON DELETE CASCADE, because a run and its work are one fact about the
456
+ -- world. Sweeping runs and leaving work destroys the UNIQUE(run_id, unit)
457
+ -- row that IS the "this unit already ran" record \u2014 and a restore then
458
+ -- re-charges the invoice.
459
+ run_id text NOT NULL REFERENCES tide_run(id) ON DELETE CASCADE,
460
+ reflex_id text NOT NULL,
461
+ unit text NOT NULL,
462
+ cause text NOT NULL,
463
+ env jsonb NOT NULL,
464
+ depth integer NOT NULL DEFAULT 0,
465
+ state text NOT NULL CHECK (state IN ('pending','claimed','retrying','done','failed')),
466
+ attempt integer NOT NULL DEFAULT 0,
467
+ token text,
468
+ -- Zero, never null, when unclaimed: "never claimed or lapsed" is then one
469
+ -- comparison rather than a disjunction.
470
+ claimed_until bigint NOT NULL DEFAULT 0,
471
+ not_before bigint NOT NULL,
472
+ input jsonb,
473
+ output jsonb,
474
+ error text,
475
+ created_at bigint NOT NULL,
476
+ settled_at bigint,
477
+ UNIQUE (run_id, unit)
478
+ );
479
+
480
+ CREATE INDEX IF NOT EXISTS tide_work_claimable ON tide_work (state, not_before, claimed_until);
481
+ CREATE INDEX IF NOT EXISTS tide_work_run ON tide_work (run_id);
482
+ CREATE INDEX IF NOT EXISTS tide_work_swept ON tide_work (settled_at);
483
+
484
+ CREATE TABLE IF NOT EXISTS tide_reflex_state (
485
+ reflex_id text PRIMARY KEY,
486
+ armed_at bigint NOT NULL DEFAULT 0,
487
+ materialized_through bigint
488
+ );
489
+
490
+ -- Polls are gone (the vex bridge pushes writes \u2014 a poll could only
491
+ -- re-discover them late), and their cursor state goes with them. IF EXISTS,
492
+ -- so a store created after the removal is not asked to drop what it never had.
493
+ ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_cursor;
494
+ ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_seen;
495
+ ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS polled_at;
496
+ `;
497
+ var statementsOf = (ddl) => ddl.split(";").map((chunk) => chunk.trim()).filter((chunk) => chunk.split("\n").some((line) => line.trim() !== "" && !line.trim().startsWith("--"))).map((sql) => ({ kind: "sql", sql }));
498
+ var TIDE_SEQUENCE = {
499
+ id: "nisc.moss.tide",
500
+ migrations: [
501
+ { description: "The tide store: facts, runs, work and reflex state, converged from any earlier shape", steps: statementsOf(TIDE_DDL) },
502
+ {
503
+ description: "A fact carries its chain root, and a root counts what its chain minted (tide maxChainFacts)",
504
+ steps: [
505
+ { kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS root text" },
506
+ { kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS descendants integer" }
507
+ ]
508
+ }
509
+ ]
510
+ };
511
+
512
+ // src/store/postgres/store.ts
513
+ var mintId = /* @__PURE__ */ (() => {
514
+ let sequence = 0;
515
+ return (table) => {
516
+ sequence += 1;
517
+ return `${table}_${Date.now().toString(36)}_${sequence.toString(36)}`;
518
+ };
519
+ })();
520
+ var createTideStore = (pool, options = {}) => {
521
+ const ready = options.migrate === false ? Promise.resolve() : postgres.migrate(pool, [TIDE_SEQUENCE]).then(() => void 0);
522
+ ready.catch(() => void 0);
523
+ const overPool = (fn) => {
524
+ if (pool.transaction === void 0)
525
+ throw new Error("tide store: this pool cannot transact \u2014 fan-out, attempt recording and a serial claim are transactions, not conventions");
526
+ return pool.transaction(fn);
527
+ };
528
+ const build = (client, atomically) => {
529
+ const store = {
530
+ query: async (spec) => {
531
+ await ready;
532
+ const where = compileWhere(spec.where, 1);
533
+ const limit = spec.limit === void 0 ? "" : ` LIMIT ${Math.max(0, Math.floor(spec.limit))}`;
534
+ const result = await client.query(
535
+ `SELECT * FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql}${compileOrder(spec.order)}${limit}`,
536
+ where.params
537
+ );
538
+ return result.rows.map((row) => rowToEntity(spec.table, row));
539
+ },
540
+ appendIfAbsent: async (table, input) => {
541
+ await ready;
542
+ const given = input;
543
+ const withId = PRIMARY_KEY[table] === "id" ? { ...given, id: input.id ?? mintId(table) } : given;
544
+ const entries = Object.entries(withId).filter(([, value]) => value !== void 0);
545
+ const columns = entries.map(([field]) => snake(field));
546
+ const params = entries.map(([field, value]) => toColumn(snake(field), value));
547
+ const unique = UNIQUE_BY[table];
548
+ const target = unique.when === void 0 ? `(${unique.by.map((column) => snake(column)).join(", ")})` : `(${unique.by.map((column) => column === "entity" || column === "name" ? `coalesce(${snake(column)},'')` : snake(column)).join(", ")}) WHERE ${snake(unique.when)} IS NOT NULL`;
549
+ const result = await client.query(
550
+ `INSERT INTO ${SQL_TABLE[table]} (${columns.join(", ")}) VALUES (${params.map((_value, index) => `$${index + 1}`).join(", ")})
551
+ ON CONFLICT ${target} DO NOTHING RETURNING *`,
552
+ params
553
+ );
554
+ const row = result.rows[0];
555
+ return row === void 0 ? void 0 : rowToEntity(table, row);
556
+ },
557
+ claim: claimOver({ client, atomically, ready }),
558
+ cas: async (table, id, expect, set) => {
559
+ await ready;
560
+ const key = snake(PRIMARY_KEY[table]);
561
+ const where = compileWhere(expect, 2);
562
+ const patch = compileSet(set, where.params.length + 2);
563
+ const result = await client.query(
564
+ `UPDATE ${SQL_TABLE[table]} SET ${patch.sql} WHERE ${key} = $1 AND ${where.sql} RETURNING ${key}`,
565
+ [id, ...where.params, ...patch.params]
566
+ );
567
+ return result.rows.length > 0;
568
+ },
569
+ remove: async (spec) => {
570
+ await ready;
571
+ const where = compileWhere(spec.where, 1);
572
+ const result = await client.query(`DELETE FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql} RETURNING ${snake(PRIMARY_KEY[spec.table])}`, where.params);
573
+ return result.rows.length;
574
+ },
575
+ transact: async (fn) => {
576
+ await ready;
577
+ return atomically((tx) => fn(build(tx, (inner) => inner(tx))));
578
+ }
579
+ };
580
+ return store;
581
+ };
582
+ return { ...build(pool, overPool), ready };
583
+ };
584
+
585
+ exports.TIDE_DDL = TIDE_DDL;
586
+ exports.TIDE_SEQUENCE = TIDE_SEQUENCE;
587
+ exports.TIDE_TABLES = TIDE_TABLES;
588
+ exports.createTideStore = createTideStore;
589
+ //# sourceMappingURL=postgres.cjs.map
590
+ //# sourceMappingURL=postgres.cjs.map