@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.
package/dist/index.d.cts CHANGED
@@ -270,6 +270,24 @@ type MemoryStore = TideStore & {
270
270
  };
271
271
  declare const createMemoryStore: () => MemoryStore;
272
272
 
273
+ type TideDriver = {
274
+ ingest: Tide['ingest'];
275
+ fire: (reflexId: string, options: {
276
+ now: number;
277
+ input?: unknown;
278
+ by?: string;
279
+ }) => Promise<Fact | undefined>;
280
+ wake: () => Promise<void>;
281
+ stop: () => Promise<void>;
282
+ };
283
+ type TideDriverConfig = {
284
+ tide: Tide;
285
+ now?: () => number;
286
+ janitorMs?: number;
287
+ retention?: Retention;
288
+ };
289
+ declare const createTideDriver: (config: TideDriverConfig) => TideDriver;
290
+
273
291
  type LocalParts = {
274
292
  year: number;
275
293
  month: number;
@@ -299,4 +317,4 @@ declare const anchorDraft: (draft: ReflexDraft, anchor: {
299
317
  tz: string;
300
318
  }) => Reflex;
301
319
 
302
- export { type AdvanceOptions, AdvanceReport, type Clock, type ClockOnce, ClockOnceSchema, type ClockRecurring, ClockRecurringSchema, ClockTriggerSchema, ClockUnitSchema, type Edge, Fact, FactInput, type GraphReport, LoadReport, type LocalDay, type LocalParts, ManualTriggerSchema, type MemoryStore, type Occurrence, type Op, OpSchema, type Policy, PolicySchema, type PreviewOptions, PreviewReport, Reflex, ReflexDraft, ReflexInput, ReflexState, Retention, type Retry, RetrySchema, Run, RunTriggerSchema, SignalTriggerSchema, Task, TaskState, type Tide, TideConfig, TideError, type TideErrorCode, TideStore, Timer, type Trigger, TriggerSchema, WEEKDAYS, type Weekday, WriteTriggerSchema, anchorDraft, createMemoryStore, createTide, daysInMonth, isTideError, occurrenceKey, occurrencesBetween, timerMs, versionOf, zonedParts, zonedToUtc };
320
+ export { type AdvanceOptions, AdvanceReport, type Clock, type ClockOnce, ClockOnceSchema, type ClockRecurring, ClockRecurringSchema, ClockTriggerSchema, ClockUnitSchema, type Edge, Fact, FactInput, type GraphReport, LoadReport, type LocalDay, type LocalParts, ManualTriggerSchema, type MemoryStore, type Occurrence, type Op, OpSchema, type Policy, PolicySchema, type PreviewOptions, PreviewReport, Reflex, ReflexDraft, ReflexInput, ReflexState, Retention, type Retry, RetrySchema, Run, RunTriggerSchema, SignalTriggerSchema, Task, TaskState, type Tide, TideConfig, type TideDriver, type TideDriverConfig, TideError, type TideErrorCode, TideStore, Timer, type Trigger, TriggerSchema, WEEKDAYS, type Weekday, WriteTriggerSchema, anchorDraft, createMemoryStore, createTide, createTideDriver, daysInMonth, isTideError, occurrenceKey, occurrencesBetween, timerMs, versionOf, zonedParts, zonedToUtc };
package/dist/index.d.ts CHANGED
@@ -270,6 +270,24 @@ type MemoryStore = TideStore & {
270
270
  };
271
271
  declare const createMemoryStore: () => MemoryStore;
272
272
 
273
+ type TideDriver = {
274
+ ingest: Tide['ingest'];
275
+ fire: (reflexId: string, options: {
276
+ now: number;
277
+ input?: unknown;
278
+ by?: string;
279
+ }) => Promise<Fact | undefined>;
280
+ wake: () => Promise<void>;
281
+ stop: () => Promise<void>;
282
+ };
283
+ type TideDriverConfig = {
284
+ tide: Tide;
285
+ now?: () => number;
286
+ janitorMs?: number;
287
+ retention?: Retention;
288
+ };
289
+ declare const createTideDriver: (config: TideDriverConfig) => TideDriver;
290
+
273
291
  type LocalParts = {
274
292
  year: number;
275
293
  month: number;
@@ -299,4 +317,4 @@ declare const anchorDraft: (draft: ReflexDraft, anchor: {
299
317
  tz: string;
300
318
  }) => Reflex;
301
319
 
302
- export { type AdvanceOptions, AdvanceReport, type Clock, type ClockOnce, ClockOnceSchema, type ClockRecurring, ClockRecurringSchema, ClockTriggerSchema, ClockUnitSchema, type Edge, Fact, FactInput, type GraphReport, LoadReport, type LocalDay, type LocalParts, ManualTriggerSchema, type MemoryStore, type Occurrence, type Op, OpSchema, type Policy, PolicySchema, type PreviewOptions, PreviewReport, Reflex, ReflexDraft, ReflexInput, ReflexState, Retention, type Retry, RetrySchema, Run, RunTriggerSchema, SignalTriggerSchema, Task, TaskState, type Tide, TideConfig, TideError, type TideErrorCode, TideStore, Timer, type Trigger, TriggerSchema, WEEKDAYS, type Weekday, WriteTriggerSchema, anchorDraft, createMemoryStore, createTide, daysInMonth, isTideError, occurrenceKey, occurrencesBetween, timerMs, versionOf, zonedParts, zonedToUtc };
320
+ export { type AdvanceOptions, AdvanceReport, type Clock, type ClockOnce, ClockOnceSchema, type ClockRecurring, ClockRecurringSchema, ClockTriggerSchema, ClockUnitSchema, type Edge, Fact, FactInput, type GraphReport, LoadReport, type LocalDay, type LocalParts, ManualTriggerSchema, type MemoryStore, type Occurrence, type Op, OpSchema, type Policy, PolicySchema, type PreviewOptions, PreviewReport, Reflex, ReflexDraft, ReflexInput, ReflexState, Retention, type Retry, RetrySchema, Run, RunTriggerSchema, SignalTriggerSchema, Task, TaskState, type Tide, TideConfig, type TideDriver, type TideDriverConfig, TideError, type TideErrorCode, TideStore, Timer, type Trigger, TriggerSchema, WEEKDAYS, type Weekday, WriteTriggerSchema, anchorDraft, createMemoryStore, createTide, createTideDriver, daysInMonth, isTideError, occurrenceKey, occurrencesBetween, timerMs, versionOf, zonedParts, zonedToUtc };
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
- import { isRecurring, ReflexSchema, FactInputSchema, clockOf, factOf, WEEKDAYS, isManual } from './chunk-UEG3UZDG.js';
2
- export { ClockOnceSchema, ClockRecurringSchema, ClockTriggerSchema, ClockUnitSchema, DRAFT_TRIGGERS, EffectRefSchema, FactInputSchema, FactKindSchema, ManualTriggerSchema, OpSchema, PolicySchema, ReflexDraftSchema, ReflexSchema, RetrySchema, RunTriggerSchema, SelectionSchema, SignalTriggerSchema, TimerSchema, TimerTriggerSchema, TriggerSchema, WEEKDAYS, WriteTriggerSchema, draftSchemaOf } from './chunk-UEG3UZDG.js';
1
+ import { UNIQUE_BY, PRIMARY_KEY, COMPARISON_OPS } from './chunk-7KHOAJNL.js';
2
+ export { COMPARISON_OPS, PRIMARY_KEY, UNIQUE_BY } from './chunk-7KHOAJNL.js';
3
+ import { isRecurring, ReflexSchema, FactInputSchema, clockOf, factOf, WEEKDAYS, isManual } from './chunk-4TXWZFRE.js';
4
+ export { ClockOnceSchema, ClockRecurringSchema, ClockTriggerSchema, ClockUnitSchema, DRAFT_TRIGGERS, EffectRefSchema, FactInputSchema, FactKindSchema, ManualTriggerSchema, OpSchema, PolicySchema, ReflexDraftSchema, ReflexSchema, RetrySchema, RunTriggerSchema, SelectionSchema, SignalTriggerSchema, TimerSchema, TimerTriggerSchema, TriggerSchema, WEEKDAYS, WriteTriggerSchema, draftSchemaOf } from './chunk-4TXWZFRE.js';
3
5
 
4
6
  // src/errors.ts
5
7
  var TideError = class extends Error {
@@ -276,8 +278,6 @@ var openRun = async (deps, loaded, input) => {
276
278
  const base = {
277
279
  reflexId: reflex.id,
278
280
  version,
279
- // Written down so the ledger is scopeable by an ordinary host rule
280
- // rather than by parsing reflex ids. Opaque to tide.
281
281
  as: reflex.as,
282
282
  cause: input.cause,
283
283
  occurrence: input.occurrence,
@@ -300,8 +300,6 @@ var openRun = async (deps, loaded, input) => {
300
300
  ...base,
301
301
  state: "skipped",
302
302
  settledAt: input.now,
303
- // Nothing waits on it and nothing announces it: a run that never
304
- // started has no settlement to report.
305
303
  drained: true,
306
304
  note: `overlap: the previous run (${unsettled.id}) is still unsettled`
307
305
  });
@@ -381,8 +379,6 @@ var matchFacts = async (deps, now, limit) => {
381
379
  now,
382
380
  occurrence: fact.occurrence,
383
381
  factIds: [fact.id],
384
- // A write, a signal or another reflex's settlement happened once and
385
- // will not happen again; a human pressing the button twice will.
386
382
  repeat: fact.kind === "manual"
387
383
  });
388
384
  if (run !== void 0) report.runsCreated += 1;
@@ -518,8 +514,6 @@ var commitFanout = async (deps, run, tasks, selected, now) => deps.store.transac
518
514
  {
519
515
  selected,
520
516
  total: written,
521
- // A zero-task run settles immediately and still announces itself —
522
- // "nothing was due" is an answer a digest may legitimately want.
523
517
  state: settledNow ? "settled" : "fanned",
524
518
  settledAt: settledNow ? now : void 0
525
519
  }
@@ -530,12 +524,9 @@ var taskOf = (unit, run, loaded, now) => ({
530
524
  runId: run.id,
531
525
  reflexId: loaded.reflex.id,
532
526
  unit: unit.unit,
533
- // UNIQUE(runId, unit) — the idempotency grain, written BEFORE the effect
534
- // runs. There is no path to the effect that skips this row.
535
527
  cause: run.cause,
536
528
  env: unit.env,
537
- // Carried, not looked up later: a swept run must not reset the chain
538
- // ceiling for work that is still in flight.
529
+ // Carried on the task: a swept run must not reset the chain ceiling.
539
530
  depth: run.depth,
540
531
  state: "pending",
541
532
  attempt: 0,
@@ -622,22 +613,13 @@ var claimTasks = async (deps, now, limit, token) => {
622
613
  where: {
623
614
  state: { in: ["pending", "retrying", "claimed"] },
624
615
  notBefore: { lte: now },
625
- // Either it was never claimed, or the claim has lapsed. Expressed as
626
- // one predicate because a second query would be a second decision.
627
616
  claimedUntil: { lte: now }
628
617
  },
629
- // `unit` is the tiebreaker, and it is not cosmetic. Every task of one
630
- // fan-out shares a `notBefore` and a `createdAt`, so with two keys the
631
- // order was whatever the storage engine felt like — insertion order in a
632
- // Map, heap order in Postgres. Two stores answering differently is the
633
- // thing the contract exists to prevent, and a headless check asserting on
634
- // the order effects ran in deserves the same answer everywhere.
618
+ // `unit` breaks ties: one fan-out's tasks share `notBefore` and `createdAt`,
619
+ // and two stores must order them the same way.
635
620
  order: [{ by: "notBefore" }, { by: "createdAt" }, { by: "unit" }],
636
621
  limit,
637
622
  set: { state: "claimed", token, claimedUntil: now + deps.leaseMs, attempt: { inc: 1 } },
638
- // `order: 'serial'` — at most one live claim per reflex, counting what
639
- // another claim already holds. Inside the claim, because a caller that
640
- // looks first and claims second loses the race to its own second tick.
641
623
  onePer: serialReflexIds.length === 0 ? void 0 : { column: "reflexId", held: { state: "claimed", claimedUntil: { gt: now } }, only: serialReflexIds }
642
624
  });
643
625
  };
@@ -673,21 +655,8 @@ var executeTasks = async (deps, now, limit) => {
673
655
  depth: task.depth,
674
656
  now,
675
657
  actor: deps.actorFor(reflex.as),
676
- // VALIDATED, and narrowed to two kinds.
677
- //
678
- // `emit` used to accept anything: a handler could emit `kind: 'manual'`
679
- // and fire a DISARMED reflex, because manual facts are checked before
680
- // enablement on purpose — arming gates triggers, not people. A handler
681
- // is not a person. `run` is tide's own bookkeeping and is minted by the
682
- // settler, so it is refused for the same reason.
683
- //
684
- // A malformed emit THROWS, inside the handler, so the attempt fails
685
- // visibly. The alternative is a fact that stores, matches nothing and
686
- // vanishes — a chain that silently stops one hop in.
687
- //
688
- // Depth is stamped from the task below — the handler never sets it,
689
- // because a handler that could choose its own depth could escape the
690
- // chain ceiling.
658
+ // `write` and `signal` only: a `manual` fact fires a disabled reflex, and
659
+ // `run` facts are minted by the settler alone.
691
660
  emit: (fact) => {
692
661
  if (fact.kind !== "write" && fact.kind !== "signal")
693
662
  throw new TideError("invalid_fact", `${reflex.id}: an effect may emit \`write\` or \`signal\` facts, not \`${fact.kind}\``);
@@ -729,8 +698,7 @@ var executeTasks = async (deps, now, limit) => {
729
698
  notBefore: next.state === "retrying" ? next.notBefore : task.notBefore,
730
699
  output,
731
700
  error,
732
- // A throwing attempt discards its buffer: otherwise every retry of an
733
- // emit-then-throw handler would double-mint facts and fire the chain twice.
701
+ // A failed attempt's emits are dropped: its retry would mint them again.
734
702
  emits: outcome === "ok" ? emits : [],
735
703
  at: now
736
704
  });
@@ -817,8 +785,6 @@ var settleRuns = async (deps, now) => {
817
785
  at: now,
818
786
  depth: run.depth + 1,
819
787
  cause: `run:${run.id}`,
820
- // A settlement is news about THIS reflex's work — counts of rows it
821
- // selected. Another tenant's digest has no business waking on it.
822
788
  as: run.as
823
789
  }, deps.maxChainFacts);
824
790
  announceFact(deps.emit, admission);
@@ -1062,8 +1028,6 @@ var createTide = (config) => {
1062
1028
  if (!loaded.has(reflexId)) throw new TideError("unknown_reflex", `no reflex "${reflexId}" is loaded`);
1063
1029
  return ingest(
1064
1030
  { kind: "manual", target: reflexId, payload: options.input, by: options.by ?? "operator", at: options.now },
1065
- // Carried so the ledger reads consistently. Matching a manual fact does
1066
- // not depend on it — `target` names one reflex, which is narrower.
1067
1031
  { as: loaded.get(reflexId)?.reflex.as }
1068
1032
  );
1069
1033
  };
@@ -1123,19 +1087,14 @@ var createTide = (config) => {
1123
1087
  },
1124
1088
  fact: (id) => one("fact", id),
1125
1089
  causeChain,
1126
- // Clears the park AND records that a human overrode the ceiling —
1127
- // clearing the park alone is a ping-pong, because the depth that
1128
- // parked it has not changed and never will.
1090
+ // `released` as well: with `parked` alone cleared, the depth check would
1091
+ // park the fact again on the next advance.
1129
1092
  releaseParked: async (factId) => {
1130
1093
  const fact = await one("fact", factId);
1131
1094
  if (fact?.parked === void 0) return false;
1132
1095
  return config.store.cas("fact", factId, {}, { parked: void 0, released: true });
1133
1096
  }
1134
1097
  },
1135
- // RETENTION, and the one place the ledger shrinks. Runs cascade to their
1136
- // tasks in the store: a run and its members are one fact about the world,
1137
- // and keeping half destroys the UNIQUE(runId, unit) row that IS the "this
1138
- // unit already ran" record.
1139
1098
  sweep: async (now, retention) => {
1140
1099
  let removed = 0;
1141
1100
  if (retention.facts !== void 0)
@@ -1149,23 +1108,6 @@ var createTide = (config) => {
1149
1108
  };
1150
1109
  };
1151
1110
 
1152
- // src/types.ts
1153
- var PRIMARY_KEY = {
1154
- fact: "id",
1155
- run: "id",
1156
- task: "id",
1157
- state: "reflexId"
1158
- };
1159
- var UNIQUE_BY = {
1160
- // `entity` is part of the key. Without it two polls over different tables
1161
- // that happened to agree on a cursor value silently ate each other's rows.
1162
- fact: { by: ["kind", "entity", "name", "dedupeKey"], when: "dedupeKey" },
1163
- run: { by: ["reflexId", "cause"] },
1164
- task: { by: ["runId", "unit"] },
1165
- state: { by: ["reflexId"] }
1166
- };
1167
- var COMPARISON_OPS = ["eq", "ne", "lt", "lte", "gt", "gte", "in", "notIn", "isNull"];
1168
-
1169
1111
  // src/store/memory.ts
1170
1112
  var ID_PREFIX = { fact: "fact", run: "run", task: "task", state: "st" };
1171
1113
  var isComparison = (value) => {
@@ -1315,6 +1257,100 @@ var createMemoryStore = () => {
1315
1257
  return store;
1316
1258
  };
1317
1259
 
1260
+ // src/driver.ts
1261
+ var DEFAULT_JANITOR_MS = 3e5;
1262
+ var MAX_STEPS_PER_DRAIN = 1e4;
1263
+ var LONGEST_TIMER_MS = 2 ** 31 - 1;
1264
+ var waitable = (ms) => Math.min(ms, LONGEST_TIMER_MS);
1265
+ var letProcessEnd = (timer) => {
1266
+ if (typeof timer !== "object" || timer === null || !("unref" in timer)) return;
1267
+ const unref = timer.unref;
1268
+ if (typeof unref === "function") Reflect.apply(unref, timer, []);
1269
+ };
1270
+ var progressOf = (report) => report.materialized + report.skippedOccurrences + report.factsMatched + report.runsCreated + report.tasksCreated + report.executed + report.reclaimed + report.runsSettled + report.parked;
1271
+ var createTideDriver = (config) => {
1272
+ const { tide } = config;
1273
+ const now = config.now ?? (() => Date.now());
1274
+ const janitorMs = waitable(config.janitorMs ?? DEFAULT_JANITOR_MS);
1275
+ let running = false;
1276
+ let queued = false;
1277
+ let stopped = false;
1278
+ let cycle;
1279
+ let scheduling;
1280
+ let timer;
1281
+ const drain = async () => {
1282
+ for (let steps = 0; steps < MAX_STEPS_PER_DRAIN; steps += 1) {
1283
+ const report = await tide.advance({ now: now() });
1284
+ if (progressOf(report) === 0) return;
1285
+ }
1286
+ console.error(`[tide:driver] a drain exceeded ${MAX_STEPS_PER_DRAIN} steps \u2014 stopping this pass; the janitor will resume it`);
1287
+ };
1288
+ const schedule = async () => {
1289
+ if (stopped) return;
1290
+ let due;
1291
+ try {
1292
+ due = await tide.nextDue(now());
1293
+ } catch (err) {
1294
+ if (!stopped) console.error("[tide:driver] next due", err);
1295
+ return;
1296
+ }
1297
+ if (stopped) return;
1298
+ if (timer !== void 0) clearTimeout(timer);
1299
+ if (due === void 0) return;
1300
+ const delay = due - now();
1301
+ timer = setTimeout(() => void wake(), delay > 0 ? waitable(delay) : janitorMs);
1302
+ letProcessEnd(timer);
1303
+ };
1304
+ const wake = () => {
1305
+ if (stopped) return Promise.resolve();
1306
+ queued = true;
1307
+ if (running) return cycle ?? Promise.resolve();
1308
+ running = true;
1309
+ cycle = (async () => {
1310
+ try {
1311
+ while (queued) {
1312
+ queued = false;
1313
+ await drain();
1314
+ }
1315
+ } catch (err) {
1316
+ console.error("[tide:driver]", err);
1317
+ } finally {
1318
+ running = false;
1319
+ cycle = void 0;
1320
+ scheduling = schedule();
1321
+ }
1322
+ })();
1323
+ return cycle;
1324
+ };
1325
+ const janitor = setInterval(() => {
1326
+ if (config.retention !== void 0) {
1327
+ void tide.sweep(now(), config.retention).catch((err) => console.error("[tide:driver] sweep", err));
1328
+ }
1329
+ void wake();
1330
+ }, janitorMs);
1331
+ letProcessEnd(janitor);
1332
+ return {
1333
+ ingest: async (fact, options) => {
1334
+ const stored = await tide.ingest(fact, options);
1335
+ if (stored !== void 0) void wake();
1336
+ return stored;
1337
+ },
1338
+ fire: async (reflexId, options) => {
1339
+ const fact = await tide.fire(reflexId, options);
1340
+ void wake();
1341
+ return fact;
1342
+ },
1343
+ wake,
1344
+ stop: async () => {
1345
+ stopped = true;
1346
+ clearInterval(janitor);
1347
+ if (timer !== void 0) clearTimeout(timer);
1348
+ await cycle;
1349
+ await scheduling;
1350
+ }
1351
+ };
1352
+ };
1353
+
1318
1354
  // src/engine/anchor.ts
1319
1355
  var timerMs = (timer) => (((timer.hours ?? 0) * 60 + (timer.minutes ?? 0)) * 60 + (timer.seconds ?? 0)) * 1e3;
1320
1356
  var pad22 = (value) => String(value).padStart(2, "0");
@@ -1328,6 +1364,6 @@ var anchorDraft = (draft, anchor) => {
1328
1364
  return ReflexSchema.parse({ ...draft, on: { clock: { at: localDateTime(fires, anchor.tz), tz: anchor.tz } } });
1329
1365
  };
1330
1366
 
1331
- export { COMPARISON_OPS, PRIMARY_KEY, TideError, UNIQUE_BY, anchorDraft, createMemoryStore, createTide, daysInMonth, isTideError, occurrenceKey, occurrencesBetween, timerMs, versionOf, zonedParts, zonedToUtc };
1367
+ export { TideError, anchorDraft, createMemoryStore, createTide, createTideDriver, daysInMonth, isTideError, occurrenceKey, occurrencesBetween, timerMs, versionOf, zonedParts, zonedToUtc };
1332
1368
  //# sourceMappingURL=index.js.map
1333
1369
  //# sourceMappingURL=index.js.map