@niscorp/tide 0.1.6 → 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.cjs CHANGED
@@ -58,15 +58,11 @@ var RetrySchema = zod.z.object({
58
58
  var PolicySchema = zod.z.object({
59
59
  retry: RetrySchema.optional(),
60
60
  timeoutMs: zod.z.number().int().positive().default(3e4),
61
- // May a firing start while the previous one is unsettled? The long
62
- // billing run still going at the next tick must not double-start.
63
61
  overlap: zod.z.enum(["skip", "allow"]).default("skip"),
64
62
  catchUp: zod.z.enum(["run", "skip", "latest"]).default("run"),
65
- // How late is "missed"? Only `catchUp: 'skip'` reads it — 'run' opens
66
- // everything and 'latest' keeps the newest regardless of age. What
67
- // `catchUp` opens still passes `overlap`: occurrences missed together are
68
- // repeats of one another, so under 'skip' the oldest runs and the rest
69
- // are recorded as overlap skips.
63
+ // Read by `catchUp: 'skip'` only. What `catchUp` opens still passes
64
+ // `overlap`: occurrences missed together are repeats of one another, so
65
+ // under `overlap: 'skip'` the oldest runs and the rest are skipped.
70
66
  lateMs: zod.z.number().int().positive().default(36e5),
71
67
  order: zod.z.enum(["any", "serial"]).default("any")
72
68
  }).strict();
@@ -74,19 +70,15 @@ var DEFAULT_POLICY = PolicySchema.parse({});
74
70
  var FactKindSchema = zod.z.enum(["write", "signal", "manual", "run"]);
75
71
  var FactInputSchema = zod.z.object({
76
72
  kind: FactKindSchema,
77
- // write facts
78
73
  entity: zod.z.string().optional().describe("Which table or entity was written."),
79
74
  op: OpSchema.optional().describe('Ops are distinct stimuli \u2014 "only on create" is op: "insert".'),
80
75
  row: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("The row, as the write returned it."),
81
- // signal facts
82
76
  name: zod.z.string().optional().describe("Which named intake this arrived on."),
83
77
  payload: zod.z.unknown().optional().describe("The event body \u2014 validated at the HOST boundary before it gets here."),
84
- // run facts (minted by tide when a run settles — the fan-in mechanism)
85
78
  reflex: zod.z.string().optional(),
86
79
  runId: zod.z.string().optional(),
87
80
  occurrence: zod.z.string().optional().describe("The calendar key, when the clock was the cause."),
88
81
  stats: zod.z.object({ total: zod.z.number().int(), done: zod.z.number().int(), failed: zod.z.number().int() }).strict().optional(),
89
- // manual facts (minted by `fire`)
90
82
  target: zod.z.string().optional().describe("The one reflex a manual fact is aimed at."),
91
83
  by: zod.z.string().optional().describe("Who fired it \u2014 recorded on the firing as manual:<who>."),
92
84
  at: zod.z.number().int().describe("Supplied by the caller. Tide reads no clocks."),
@@ -471,8 +463,6 @@ var openRun = async (deps, loaded, input) => {
471
463
  const base = {
472
464
  reflexId: reflex.id,
473
465
  version,
474
- // Written down so the ledger is scopeable by an ordinary host rule
475
- // rather than by parsing reflex ids. Opaque to tide.
476
466
  as: reflex.as,
477
467
  cause: input.cause,
478
468
  occurrence: input.occurrence,
@@ -495,8 +485,6 @@ var openRun = async (deps, loaded, input) => {
495
485
  ...base,
496
486
  state: "skipped",
497
487
  settledAt: input.now,
498
- // Nothing waits on it and nothing announces it: a run that never
499
- // started has no settlement to report.
500
488
  drained: true,
501
489
  note: `overlap: the previous run (${unsettled.id}) is still unsettled`
502
490
  });
@@ -576,8 +564,6 @@ var matchFacts = async (deps, now, limit) => {
576
564
  now,
577
565
  occurrence: fact.occurrence,
578
566
  factIds: [fact.id],
579
- // A write, a signal or another reflex's settlement happened once and
580
- // will not happen again; a human pressing the button twice will.
581
567
  repeat: fact.kind === "manual"
582
568
  });
583
569
  if (run !== void 0) report.runsCreated += 1;
@@ -713,8 +699,6 @@ var commitFanout = async (deps, run, tasks, selected, now) => deps.store.transac
713
699
  {
714
700
  selected,
715
701
  total: written,
716
- // A zero-task run settles immediately and still announces itself —
717
- // "nothing was due" is an answer a digest may legitimately want.
718
702
  state: settledNow ? "settled" : "fanned",
719
703
  settledAt: settledNow ? now : void 0
720
704
  }
@@ -725,12 +709,9 @@ var taskOf = (unit, run, loaded, now) => ({
725
709
  runId: run.id,
726
710
  reflexId: loaded.reflex.id,
727
711
  unit: unit.unit,
728
- // UNIQUE(runId, unit) — the idempotency grain, written BEFORE the effect
729
- // runs. There is no path to the effect that skips this row.
730
712
  cause: run.cause,
731
713
  env: unit.env,
732
- // Carried, not looked up later: a swept run must not reset the chain
733
- // ceiling for work that is still in flight.
714
+ // Carried on the task: a swept run must not reset the chain ceiling.
734
715
  depth: run.depth,
735
716
  state: "pending",
736
717
  attempt: 0,
@@ -817,22 +798,13 @@ var claimTasks = async (deps, now, limit, token) => {
817
798
  where: {
818
799
  state: { in: ["pending", "retrying", "claimed"] },
819
800
  notBefore: { lte: now },
820
- // Either it was never claimed, or the claim has lapsed. Expressed as
821
- // one predicate because a second query would be a second decision.
822
801
  claimedUntil: { lte: now }
823
802
  },
824
- // `unit` is the tiebreaker, and it is not cosmetic. Every task of one
825
- // fan-out shares a `notBefore` and a `createdAt`, so with two keys the
826
- // order was whatever the storage engine felt like — insertion order in a
827
- // Map, heap order in Postgres. Two stores answering differently is the
828
- // thing the contract exists to prevent, and a headless check asserting on
829
- // the order effects ran in deserves the same answer everywhere.
803
+ // `unit` breaks ties: one fan-out's tasks share `notBefore` and `createdAt`,
804
+ // and two stores must order them the same way.
830
805
  order: [{ by: "notBefore" }, { by: "createdAt" }, { by: "unit" }],
831
806
  limit,
832
807
  set: { state: "claimed", token, claimedUntil: now + deps.leaseMs, attempt: { inc: 1 } },
833
- // `order: 'serial'` — at most one live claim per reflex, counting what
834
- // another claim already holds. Inside the claim, because a caller that
835
- // looks first and claims second loses the race to its own second tick.
836
808
  onePer: serialReflexIds.length === 0 ? void 0 : { column: "reflexId", held: { state: "claimed", claimedUntil: { gt: now } }, only: serialReflexIds }
837
809
  });
838
810
  };
@@ -868,21 +840,8 @@ var executeTasks = async (deps, now, limit) => {
868
840
  depth: task.depth,
869
841
  now,
870
842
  actor: deps.actorFor(reflex.as),
871
- // VALIDATED, and narrowed to two kinds.
872
- //
873
- // `emit` used to accept anything: a handler could emit `kind: 'manual'`
874
- // and fire a DISARMED reflex, because manual facts are checked before
875
- // enablement on purpose — arming gates triggers, not people. A handler
876
- // is not a person. `run` is tide's own bookkeeping and is minted by the
877
- // settler, so it is refused for the same reason.
878
- //
879
- // A malformed emit THROWS, inside the handler, so the attempt fails
880
- // visibly. The alternative is a fact that stores, matches nothing and
881
- // vanishes — a chain that silently stops one hop in.
882
- //
883
- // Depth is stamped from the task below — the handler never sets it,
884
- // because a handler that could choose its own depth could escape the
885
- // chain ceiling.
843
+ // `write` and `signal` only: a `manual` fact fires a disabled reflex, and
844
+ // `run` facts are minted by the settler alone.
886
845
  emit: (fact) => {
887
846
  if (fact.kind !== "write" && fact.kind !== "signal")
888
847
  throw new TideError("invalid_fact", `${reflex.id}: an effect may emit \`write\` or \`signal\` facts, not \`${fact.kind}\``);
@@ -924,8 +883,7 @@ var executeTasks = async (deps, now, limit) => {
924
883
  notBefore: next.state === "retrying" ? next.notBefore : task.notBefore,
925
884
  output,
926
885
  error,
927
- // A throwing attempt discards its buffer: otherwise every retry of an
928
- // emit-then-throw handler would double-mint facts and fire the chain twice.
886
+ // A failed attempt's emits are dropped: its retry would mint them again.
929
887
  emits: outcome === "ok" ? emits : [],
930
888
  at: now
931
889
  });
@@ -1012,8 +970,6 @@ var settleRuns = async (deps, now) => {
1012
970
  at: now,
1013
971
  depth: run.depth + 1,
1014
972
  cause: `run:${run.id}`,
1015
- // A settlement is news about THIS reflex's work — counts of rows it
1016
- // selected. Another tenant's digest has no business waking on it.
1017
973
  as: run.as
1018
974
  }, deps.maxChainFacts);
1019
975
  announceFact(deps.emit, admission);
@@ -1257,8 +1213,6 @@ var createTide = (config) => {
1257
1213
  if (!loaded.has(reflexId)) throw new TideError("unknown_reflex", `no reflex "${reflexId}" is loaded`);
1258
1214
  return ingest(
1259
1215
  { kind: "manual", target: reflexId, payload: options.input, by: options.by ?? "operator", at: options.now },
1260
- // Carried so the ledger reads consistently. Matching a manual fact does
1261
- // not depend on it — `target` names one reflex, which is narrower.
1262
1216
  { as: loaded.get(reflexId)?.reflex.as }
1263
1217
  );
1264
1218
  };
@@ -1318,19 +1272,14 @@ var createTide = (config) => {
1318
1272
  },
1319
1273
  fact: (id) => one("fact", id),
1320
1274
  causeChain,
1321
- // Clears the park AND records that a human overrode the ceiling —
1322
- // clearing the park alone is a ping-pong, because the depth that
1323
- // parked it has not changed and never will.
1275
+ // `released` as well: with `parked` alone cleared, the depth check would
1276
+ // park the fact again on the next advance.
1324
1277
  releaseParked: async (factId) => {
1325
1278
  const fact = await one("fact", factId);
1326
1279
  if (fact?.parked === void 0) return false;
1327
1280
  return config.store.cas("fact", factId, {}, { parked: void 0, released: true });
1328
1281
  }
1329
1282
  },
1330
- // RETENTION, and the one place the ledger shrinks. Runs cascade to their
1331
- // tasks in the store: a run and its members are one fact about the world,
1332
- // and keeping half destroys the UNIQUE(runId, unit) row that IS the "this
1333
- // unit already ran" record.
1334
1283
  sweep: async (now, retention) => {
1335
1284
  let removed = 0;
1336
1285
  if (retention.facts !== void 0)
@@ -1352,8 +1301,7 @@ var PRIMARY_KEY = {
1352
1301
  state: "reflexId"
1353
1302
  };
1354
1303
  var UNIQUE_BY = {
1355
- // `entity` is part of the key. Without it two polls over different tables
1356
- // that happened to agree on a cursor value silently ate each other's rows.
1304
+ // `entity` is in the key: two polls over different tables can agree on a cursor value.
1357
1305
  fact: { by: ["kind", "entity", "name", "dedupeKey"], when: "dedupeKey" },
1358
1306
  run: { by: ["reflexId", "cause"] },
1359
1307
  task: { by: ["runId", "unit"] },