@niscorp/tide 0.1.11 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +85 -0
- package/DESIGN.md +45 -9
- package/DOCS.md +98 -36
- package/README.md +4 -2
- package/dist/agent.cjs +6 -3
- package/dist/agent.cjs.map +1 -1
- package/dist/agent.js +4 -2
- package/dist/agent.js.map +1 -1
- package/dist/{chunk-2HCRTQTB.js → chunk-SLLCUI65.js} +4 -4
- package/dist/chunk-SLLCUI65.js.map +1 -0
- package/dist/index.cjs +349 -295
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +349 -295
- package/dist/index.js.map +1 -1
- package/dist/migrations/index.cjs +2 -2
- package/dist/migrations/index.cjs.map +1 -1
- package/dist/migrations/index.js +1 -1
- package/dist/postgres.cjs +15 -13
- package/dist/postgres.cjs.map +1 -1
- package/dist/postgres.js +14 -12
- package/dist/postgres.js.map +1 -1
- package/package.json +5 -5
- package/dist/chunk-2HCRTQTB.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,120 @@
|
|
|
1
1
|
import { UNIQUE_BY, PRIMARY_KEY, COMPARISON_OPS } from './chunk-MGGWP6C7.js';
|
|
2
2
|
export { COMPARISON_OPS, PRIMARY_KEY, UNIQUE_BY } from './chunk-MGGWP6C7.js';
|
|
3
|
-
import { isRecurring, ReflexSchema, FactInputSchema, clockOf, factOf, WEEKDAYS, isManual } from './chunk-
|
|
4
|
-
export { ClockOnceSchema, ClockRecurringSchema, ClockTriggerSchema, ClockUnitSchema, DRAFT_TRIGGERS, EffectRefSchema, FactInputSchema, FactKindSchema, ManualTriggerSchema, OpSchema, PolicySchema, REFLEX_TRIGGERS, ReflexDraftSchema, ReflexSchema, RetrySchema, RunTriggerSchema, SelectionSchema, SignalTriggerSchema, TimeZoneSchema, TimerSchema, TimerTriggerSchema, TriggerSchema, WEEKDAYS, WriteTriggerSchema, draftSchemaOf, reflexSchemaOf } from './chunk-
|
|
3
|
+
import { isRecurring, ReflexSchema, FactInputSchema, clockOf, factOf, WEEKDAYS, isManual } from './chunk-SLLCUI65.js';
|
|
4
|
+
export { ClockOnceSchema, ClockRecurringSchema, ClockTriggerSchema, ClockUnitSchema, DRAFT_TRIGGERS, EffectRefSchema, FactInputSchema, FactKindSchema, ManualTriggerSchema, OpSchema, PolicySchema, REFLEX_TRIGGERS, ReflexDraftSchema, ReflexSchema, RetrySchema, RunTriggerSchema, SelectionSchema, SignalTriggerSchema, TimeZoneSchema, TimerSchema, TimerTriggerSchema, TriggerSchema, WEEKDAYS, WriteTriggerSchema, draftSchemaOf, reflexSchemaOf } from './chunk-SLLCUI65.js';
|
|
5
|
+
|
|
6
|
+
// src/engine/occurrence.ts
|
|
7
|
+
var DAY_MS = 864e5;
|
|
8
|
+
var MAX_DAYS_SCANNED = 3700;
|
|
9
|
+
var FORMATTERS = /* @__PURE__ */ new Map();
|
|
10
|
+
var formatterFor = (tz) => {
|
|
11
|
+
const cached = FORMATTERS.get(tz);
|
|
12
|
+
if (cached !== void 0) return cached;
|
|
13
|
+
const built = new Intl.DateTimeFormat("en-US", {
|
|
14
|
+
timeZone: tz,
|
|
15
|
+
hourCycle: "h23",
|
|
16
|
+
year: "numeric",
|
|
17
|
+
month: "2-digit",
|
|
18
|
+
day: "2-digit",
|
|
19
|
+
hour: "2-digit",
|
|
20
|
+
minute: "2-digit",
|
|
21
|
+
second: "2-digit"
|
|
22
|
+
});
|
|
23
|
+
FORMATTERS.set(tz, built);
|
|
24
|
+
return built;
|
|
25
|
+
};
|
|
26
|
+
var zonedParts = (instant, tz) => {
|
|
27
|
+
const parts = formatterFor(tz).formatToParts(new Date(instant));
|
|
28
|
+
const read = (type) => {
|
|
29
|
+
const found = parts.find((part) => part.type === type);
|
|
30
|
+
return found === void 0 ? 0 : Number(found.value);
|
|
31
|
+
};
|
|
32
|
+
return {
|
|
33
|
+
year: read("year"),
|
|
34
|
+
month: read("month"),
|
|
35
|
+
day: read("day"),
|
|
36
|
+
hour: read("hour"),
|
|
37
|
+
minute: read("minute"),
|
|
38
|
+
second: read("second")
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
var offsetAt = (instant, tz) => {
|
|
42
|
+
const parts = zonedParts(instant, tz);
|
|
43
|
+
const asIfUtc = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
|
|
44
|
+
return asIfUtc - Math.floor(instant / 1e3) * 1e3;
|
|
45
|
+
};
|
|
46
|
+
var rendersAs = (instant, tz, day, hour, minute) => {
|
|
47
|
+
const parts = zonedParts(instant, tz);
|
|
48
|
+
return parts.year === day.year && parts.month === day.month && parts.day === day.day && parts.hour === hour && parts.minute === minute;
|
|
49
|
+
};
|
|
50
|
+
var zonedToUtc = (day, hour, minute, tz) => {
|
|
51
|
+
const guess = Date.UTC(day.year, day.month - 1, day.day, hour, minute);
|
|
52
|
+
const before = offsetAt(guess - DAY_MS, tz);
|
|
53
|
+
const after = offsetAt(guess + DAY_MS, tz);
|
|
54
|
+
const candidates = before === after ? [guess - before] : [guess - before, guess - after];
|
|
55
|
+
const valid = candidates.filter((candidate) => rendersAs(candidate, tz, day, hour, minute));
|
|
56
|
+
return valid.length > 0 ? Math.min(...valid) : Math.max(...candidates);
|
|
57
|
+
};
|
|
58
|
+
var daysInMonth = (year, month) => new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
59
|
+
var weekdayOf = (day) => {
|
|
60
|
+
const index = new Date(Date.UTC(day.year, day.month - 1, day.day)).getUTCDay();
|
|
61
|
+
return WEEKDAYS[(index + 6) % 7] ?? "mon";
|
|
62
|
+
};
|
|
63
|
+
var splitInts = (value, separator) => value.split(separator).map((part) => Number(part));
|
|
64
|
+
var at2 = (values, index) => values[index] ?? 0;
|
|
65
|
+
var nextDay = (day) => {
|
|
66
|
+
const moved = new Date(Date.UTC(day.year, day.month - 1, day.day) + DAY_MS);
|
|
67
|
+
return { year: moved.getUTCFullYear(), month: moved.getUTCMonth() + 1, day: moved.getUTCDate() };
|
|
68
|
+
};
|
|
69
|
+
var ordinalOf = (day) => day.year * 1e4 + day.month * 100 + day.day;
|
|
70
|
+
var pad2 = (value) => String(value).padStart(2, "0");
|
|
71
|
+
var isDueOn = (clock, day) => {
|
|
72
|
+
if (clock.every === "day") return true;
|
|
73
|
+
if (clock.every === "week") return Array.isArray(clock.on) ? clock.on.some((one) => one === weekdayOf(day)) : weekdayOf(day) === clock.on;
|
|
74
|
+
if (clock.every === "month")
|
|
75
|
+
return typeof clock.on === "number" && day.day === Math.min(clock.on, daysInMonth(day.year, day.month));
|
|
76
|
+
if (typeof clock.on !== "string") return false;
|
|
77
|
+
const parts = splitInts(clock.on, "-");
|
|
78
|
+
const month = at2(parts, 0);
|
|
79
|
+
const dayOfMonth = at2(parts, 1);
|
|
80
|
+
return day.month === month && day.day === Math.min(dayOfMonth, daysInMonth(day.year, month));
|
|
81
|
+
};
|
|
82
|
+
var occurrenceKey = (clock, day) => {
|
|
83
|
+
if (clock.every === "year") return String(day.year);
|
|
84
|
+
if (clock.every === "month") return `${day.year}-${pad2(day.month)}`;
|
|
85
|
+
return `${day.year}-${pad2(day.month)}-${pad2(day.day)}`;
|
|
86
|
+
};
|
|
87
|
+
var occurrencesBetween = (clock, after, through, cap) => {
|
|
88
|
+
if (through <= after || cap <= 0) return [];
|
|
89
|
+
if (!isRecurring(clock)) {
|
|
90
|
+
const [date = "", time2 = ""] = clock.at.split("T");
|
|
91
|
+
const ymd = splitInts(date, "-");
|
|
92
|
+
const hms = splitInts(time2, ":");
|
|
93
|
+
const at = zonedToUtc({ year: at2(ymd, 0), month: at2(ymd, 1), day: at2(ymd, 2) }, at2(hms, 0), at2(hms, 1), clock.tz) + at2(hms, 2) * 1e3;
|
|
94
|
+
return at > after && at <= through ? [{ key: clock.at, at }] : [];
|
|
95
|
+
}
|
|
96
|
+
const time = splitInts(clock.at, ":");
|
|
97
|
+
const hour = at2(time, 0);
|
|
98
|
+
const minute = at2(time, 1);
|
|
99
|
+
const start = zonedParts(after, clock.tz);
|
|
100
|
+
const end = zonedParts(through, clock.tz);
|
|
101
|
+
const endOrdinal = ordinalOf(end);
|
|
102
|
+
const found = [];
|
|
103
|
+
let cursor = { year: start.year, month: start.month, day: start.day };
|
|
104
|
+
let scanned = 0;
|
|
105
|
+
while (ordinalOf(cursor) <= endOrdinal && scanned < MAX_DAYS_SCANNED) {
|
|
106
|
+
scanned += 1;
|
|
107
|
+
if (isDueOn(clock, cursor)) {
|
|
108
|
+
const at = zonedToUtc(cursor, hour, minute, clock.tz);
|
|
109
|
+
if (at > after && at <= through) {
|
|
110
|
+
found.push({ key: occurrenceKey(clock, cursor), at });
|
|
111
|
+
if (found.length >= cap) break;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
cursor = nextDay(cursor);
|
|
115
|
+
}
|
|
116
|
+
return found;
|
|
117
|
+
};
|
|
5
118
|
|
|
6
119
|
// src/errors.ts
|
|
7
120
|
var TideError = class extends Error {
|
|
@@ -161,7 +274,11 @@ var findCycles = (reflexes, edges) => {
|
|
|
161
274
|
|
|
162
275
|
// src/engine/admit.ts
|
|
163
276
|
var idOf = (candidate) => typeof candidate === "object" && candidate !== null && "id" in candidate && typeof candidate.id === "string" ? candidate.id : void 0;
|
|
164
|
-
var admitReflexes = (
|
|
277
|
+
var admitReflexes = ({
|
|
278
|
+
input,
|
|
279
|
+
effectsOf,
|
|
280
|
+
isolate
|
|
281
|
+
}) => {
|
|
165
282
|
const parsed = [];
|
|
166
283
|
const refused = [];
|
|
167
284
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -195,120 +312,6 @@ var admitReflexes = (input, effectsOf, isolate) => {
|
|
|
195
312
|
return { reflexes: kept, graph, refused };
|
|
196
313
|
};
|
|
197
314
|
|
|
198
|
-
// src/engine/occurrence.ts
|
|
199
|
-
var HALF_DAY_MS = 432e5;
|
|
200
|
-
var DAY_MS = 864e5;
|
|
201
|
-
var MAX_DAYS_SCANNED = 3700;
|
|
202
|
-
var FORMATTERS = /* @__PURE__ */ new Map();
|
|
203
|
-
var formatterFor = (tz) => {
|
|
204
|
-
const cached = FORMATTERS.get(tz);
|
|
205
|
-
if (cached !== void 0) return cached;
|
|
206
|
-
const built = new Intl.DateTimeFormat("en-US", {
|
|
207
|
-
timeZone: tz,
|
|
208
|
-
hourCycle: "h23",
|
|
209
|
-
year: "numeric",
|
|
210
|
-
month: "2-digit",
|
|
211
|
-
day: "2-digit",
|
|
212
|
-
hour: "2-digit",
|
|
213
|
-
minute: "2-digit",
|
|
214
|
-
second: "2-digit"
|
|
215
|
-
});
|
|
216
|
-
FORMATTERS.set(tz, built);
|
|
217
|
-
return built;
|
|
218
|
-
};
|
|
219
|
-
var zonedParts = (instant, tz) => {
|
|
220
|
-
const parts = formatterFor(tz).formatToParts(new Date(instant));
|
|
221
|
-
const read = (type) => {
|
|
222
|
-
const found = parts.find((part) => part.type === type);
|
|
223
|
-
return found === void 0 ? 0 : Number(found.value);
|
|
224
|
-
};
|
|
225
|
-
return {
|
|
226
|
-
year: read("year"),
|
|
227
|
-
month: read("month"),
|
|
228
|
-
day: read("day"),
|
|
229
|
-
hour: read("hour"),
|
|
230
|
-
minute: read("minute"),
|
|
231
|
-
second: read("second")
|
|
232
|
-
};
|
|
233
|
-
};
|
|
234
|
-
var offsetAt = (instant, tz) => {
|
|
235
|
-
const parts = zonedParts(instant, tz);
|
|
236
|
-
const asIfUtc = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
|
|
237
|
-
return asIfUtc - Math.floor(instant / 1e3) * 1e3;
|
|
238
|
-
};
|
|
239
|
-
var rendersAs = (instant, tz, day, hour, minute) => {
|
|
240
|
-
const parts = zonedParts(instant, tz);
|
|
241
|
-
return parts.year === day.year && parts.month === day.month && parts.day === day.day && parts.hour === hour && parts.minute === minute;
|
|
242
|
-
};
|
|
243
|
-
var zonedToUtc = (day, hour, minute, tz) => {
|
|
244
|
-
const guess = Date.UTC(day.year, day.month - 1, day.day, hour, minute);
|
|
245
|
-
const before = offsetAt(guess - HALF_DAY_MS, tz);
|
|
246
|
-
const after = offsetAt(guess + HALF_DAY_MS, tz);
|
|
247
|
-
const candidates = before === after ? [guess - before] : [guess - before, guess - after];
|
|
248
|
-
const valid = candidates.filter((candidate) => rendersAs(candidate, tz, day, hour, minute));
|
|
249
|
-
return valid.length > 0 ? Math.min(...valid) : Math.max(...candidates);
|
|
250
|
-
};
|
|
251
|
-
var daysInMonth = (year, month) => new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
252
|
-
var weekdayOf = (day) => {
|
|
253
|
-
const index = new Date(Date.UTC(day.year, day.month - 1, day.day)).getUTCDay();
|
|
254
|
-
return WEEKDAYS[(index + 6) % 7] ?? "mon";
|
|
255
|
-
};
|
|
256
|
-
var splitInts = (value, separator) => value.split(separator).map((part) => Number(part));
|
|
257
|
-
var at2 = (values, index) => values[index] ?? 0;
|
|
258
|
-
var nextDay = (day) => {
|
|
259
|
-
const moved = new Date(Date.UTC(day.year, day.month - 1, day.day) + DAY_MS);
|
|
260
|
-
return { year: moved.getUTCFullYear(), month: moved.getUTCMonth() + 1, day: moved.getUTCDate() };
|
|
261
|
-
};
|
|
262
|
-
var ordinalOf = (day) => day.year * 1e4 + day.month * 100 + day.day;
|
|
263
|
-
var pad2 = (value) => String(value).padStart(2, "0");
|
|
264
|
-
var isDueOn = (clock, day) => {
|
|
265
|
-
if (clock.every === "day") return true;
|
|
266
|
-
if (clock.every === "week") return Array.isArray(clock.on) ? clock.on.some((one) => one === weekdayOf(day)) : weekdayOf(day) === clock.on;
|
|
267
|
-
if (clock.every === "month")
|
|
268
|
-
return typeof clock.on === "number" && day.day === Math.min(clock.on, daysInMonth(day.year, day.month));
|
|
269
|
-
if (typeof clock.on !== "string") return false;
|
|
270
|
-
const parts = splitInts(clock.on, "-");
|
|
271
|
-
const month = at2(parts, 0);
|
|
272
|
-
const dayOfMonth = at2(parts, 1);
|
|
273
|
-
return day.month === month && day.day === Math.min(dayOfMonth, daysInMonth(day.year, month));
|
|
274
|
-
};
|
|
275
|
-
var occurrenceKey = (clock, day) => {
|
|
276
|
-
if (clock.every === "year") return String(day.year);
|
|
277
|
-
if (clock.every === "month") return `${day.year}-${pad2(day.month)}`;
|
|
278
|
-
return `${day.year}-${pad2(day.month)}-${pad2(day.day)}`;
|
|
279
|
-
};
|
|
280
|
-
var occurrencesBetween = (clock, after, through, cap) => {
|
|
281
|
-
if (through <= after || cap <= 0) return [];
|
|
282
|
-
if (!isRecurring(clock)) {
|
|
283
|
-
const [date = "", time2 = ""] = clock.at.split("T");
|
|
284
|
-
const ymd = splitInts(date, "-");
|
|
285
|
-
const hms = splitInts(time2, ":");
|
|
286
|
-
const at = zonedToUtc({ year: at2(ymd, 0), month: at2(ymd, 1), day: at2(ymd, 2) }, at2(hms, 0), at2(hms, 1), clock.tz) + at2(hms, 2) * 1e3;
|
|
287
|
-
return at > after && at <= through ? [{ key: clock.at, at }] : [];
|
|
288
|
-
}
|
|
289
|
-
const time = splitInts(clock.at, ":");
|
|
290
|
-
const hour = at2(time, 0);
|
|
291
|
-
const minute = at2(time, 1);
|
|
292
|
-
const start = zonedParts(after, clock.tz);
|
|
293
|
-
const end = zonedParts(through, clock.tz);
|
|
294
|
-
const endOrdinal = ordinalOf(end);
|
|
295
|
-
const found = [];
|
|
296
|
-
let cursor = { year: start.year, month: start.month, day: start.day };
|
|
297
|
-
let scanned = 0;
|
|
298
|
-
while (ordinalOf(cursor) <= endOrdinal && scanned < MAX_DAYS_SCANNED) {
|
|
299
|
-
scanned += 1;
|
|
300
|
-
if (isDueOn(clock, cursor)) {
|
|
301
|
-
const at = zonedToUtc(cursor, hour, minute, clock.tz);
|
|
302
|
-
if (at > after && at <= through) {
|
|
303
|
-
found.push({ key: occurrenceKey(clock, cursor), at });
|
|
304
|
-
if (found.length >= cap) break;
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
cursor = nextDay(cursor);
|
|
308
|
-
}
|
|
309
|
-
return found;
|
|
310
|
-
};
|
|
311
|
-
|
|
312
315
|
// src/engine/match.ts
|
|
313
316
|
var openRun = async (deps, loaded, input) => {
|
|
314
317
|
const { reflex, version } = loaded;
|
|
@@ -358,8 +361,8 @@ var openRun = async (deps, loaded, input) => {
|
|
|
358
361
|
var factAsRow = (fact) => ({ ...fact });
|
|
359
362
|
var reflexMatchesFact = (loaded, fact) => {
|
|
360
363
|
const { reflex } = loaded;
|
|
361
|
-
if (fact.kind === "manual") return fact.target === reflex.id;
|
|
362
364
|
if (fact.as !== reflex.as) return false;
|
|
365
|
+
if (fact.kind === "manual") return fact.target === reflex.id;
|
|
363
366
|
if (!reflex.enabled) return false;
|
|
364
367
|
if (fact.at < loaded.armedAt) return false;
|
|
365
368
|
if (isManual(reflex.on)) return false;
|
|
@@ -374,13 +377,11 @@ var reflexMatchesFact = (loaded, fact) => {
|
|
|
374
377
|
var matchFacts = async (deps, now, limit) => {
|
|
375
378
|
const report = { factsMatched: 0, runsCreated: 0, parked: 0 };
|
|
376
379
|
if (deps.reflexes().length === 0) return report;
|
|
377
|
-
const
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
});
|
|
383
|
-
for (const fact of due.filter((candidate) => (candidate.notBefore ?? candidate.at) <= now).slice(0, limit)) {
|
|
380
|
+
const waiting = { deliveredAt: { isNull: true }, parked: { isNull: true } };
|
|
381
|
+
const immediate = await deps.store.query({ table: "fact", where: { ...waiting, notBefore: { isNull: true }, at: { lte: now } }, order: [{ by: "at" }], limit });
|
|
382
|
+
const delayed = await deps.store.query({ table: "fact", where: { ...waiting, notBefore: { lte: now } }, order: [{ by: "at" }], limit });
|
|
383
|
+
const due = [...immediate, ...delayed].sort((left, right) => left.at - right.at).slice(0, limit);
|
|
384
|
+
for (const fact of due) {
|
|
384
385
|
if (fact.depth > deps.maxChainDepth && fact.released !== true) {
|
|
385
386
|
const reason = `chain depth ${fact.depth} exceeds maxChainDepth ${deps.maxChainDepth}`;
|
|
386
387
|
await deps.store.cas("fact", fact.id, {}, { parked: reason });
|
|
@@ -474,127 +475,6 @@ var materializeClocks = async (deps, now) => {
|
|
|
474
475
|
return report;
|
|
475
476
|
};
|
|
476
477
|
|
|
477
|
-
// src/engine/fanout.ts
|
|
478
|
-
var collectRows = async (source, cap) => {
|
|
479
|
-
const resolved = await source;
|
|
480
|
-
const rows = [];
|
|
481
|
-
if (Symbol.asyncIterator in Object(resolved)) {
|
|
482
|
-
for await (const row of resolved) {
|
|
483
|
-
rows.push(row);
|
|
484
|
-
if (rows.length > cap) throw new TideError("duplicate_unit", `selection exceeded maxFanOut (${cap})`);
|
|
485
|
-
}
|
|
486
|
-
return rows;
|
|
487
|
-
}
|
|
488
|
-
for (const row of resolved) {
|
|
489
|
-
rows.push(row);
|
|
490
|
-
if (rows.length > cap) throw new TideError("duplicate_unit", `selection exceeded maxFanOut (${cap})`);
|
|
491
|
-
}
|
|
492
|
-
return rows;
|
|
493
|
-
};
|
|
494
|
-
var unitsFrom = (rows, unitKey, base, reflexId) => {
|
|
495
|
-
const seen = /* @__PURE__ */ new Set();
|
|
496
|
-
return rows.map((row) => {
|
|
497
|
-
const raw = unitKey === void 0 ? void 0 : row[unitKey];
|
|
498
|
-
const unit = raw === void 0 || raw === null ? "" : String(raw);
|
|
499
|
-
if (seen.has(unit))
|
|
500
|
-
throw new TideError("duplicate_unit", `${reflexId}: duplicate unit key "${unit}" \u2014 the selection's unitKey is not unique`);
|
|
501
|
-
seen.add(unit);
|
|
502
|
-
return { unit, env: { ...base, row } };
|
|
503
|
-
});
|
|
504
|
-
};
|
|
505
|
-
var factRowsOf = async (deps, run) => {
|
|
506
|
-
const ids = run.factIds ?? [];
|
|
507
|
-
if (ids.length === 0) return [];
|
|
508
|
-
return deps.store.query({ table: "fact", where: { id: { in: [...ids] } } });
|
|
509
|
-
};
|
|
510
|
-
var fanOut = async (deps, now, limit) => {
|
|
511
|
-
let created = 0;
|
|
512
|
-
const pending = await deps.store.query({
|
|
513
|
-
table: "run",
|
|
514
|
-
where: { state: "pending" },
|
|
515
|
-
order: [{ by: "dueAt" }],
|
|
516
|
-
limit
|
|
517
|
-
});
|
|
518
|
-
for (const run of pending) {
|
|
519
|
-
const loaded = deps.find(run.reflexId);
|
|
520
|
-
if (loaded === void 0) {
|
|
521
|
-
await deps.store.cas("run", run.id, { state: "pending" }, { state: "skipped", settledAt: now, drained: true, note: "reflex is no longer loaded" });
|
|
522
|
-
continue;
|
|
523
|
-
}
|
|
524
|
-
try {
|
|
525
|
-
const facts = await factRowsOf(deps, run);
|
|
526
|
-
const units = await unitsForRun(deps, loaded, shapeOf(run), facts, now);
|
|
527
|
-
created += await commitFanout(deps, run, units.map((unit) => taskOf(unit, run, loaded, now)), units.length, now);
|
|
528
|
-
} catch (error) {
|
|
529
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
530
|
-
if (isTideError(error)) {
|
|
531
|
-
await deps.store.cas("run", run.id, { state: "pending" }, { state: "skipped", settledAt: now, drained: true, note: `fan-out refused: ${reason}` });
|
|
532
|
-
deps.emit({ type: "run.skipped", reflexId: run.reflexId, reason });
|
|
533
|
-
continue;
|
|
534
|
-
}
|
|
535
|
-
await deps.store.cas("run", run.id, { state: "pending" }, { note: `fan-out deferred: ${reason}` });
|
|
536
|
-
deps.emit({ type: "run.deferred", reflexId: run.reflexId, runId: run.id, reason });
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
return created;
|
|
540
|
-
};
|
|
541
|
-
var commitFanout = async (deps, run, tasks, selected, now) => deps.store.transact(async (tx) => {
|
|
542
|
-
const claimed = await tx.cas("run", run.id, { state: "pending" }, { state: "fanned" });
|
|
543
|
-
if (!claimed) return 0;
|
|
544
|
-
let written = 0;
|
|
545
|
-
for (const task of tasks) if (await tx.appendIfAbsent("task", task) !== void 0) written += 1;
|
|
546
|
-
const settledNow = written === 0;
|
|
547
|
-
await tx.cas(
|
|
548
|
-
"run",
|
|
549
|
-
run.id,
|
|
550
|
-
{},
|
|
551
|
-
{
|
|
552
|
-
selected,
|
|
553
|
-
total: written,
|
|
554
|
-
state: settledNow ? "settled" : "fanned",
|
|
555
|
-
settledAt: settledNow ? now : void 0
|
|
556
|
-
}
|
|
557
|
-
);
|
|
558
|
-
return written;
|
|
559
|
-
});
|
|
560
|
-
var taskOf = (unit, run, loaded, now) => ({
|
|
561
|
-
runId: run.id,
|
|
562
|
-
reflexId: loaded.reflex.id,
|
|
563
|
-
unit: unit.unit,
|
|
564
|
-
cause: run.cause,
|
|
565
|
-
env: unit.env,
|
|
566
|
-
// Carried on the task: a swept run must not reset the chain ceiling.
|
|
567
|
-
depth: run.depth,
|
|
568
|
-
state: "pending",
|
|
569
|
-
attempt: 0,
|
|
570
|
-
claimedUntil: 0,
|
|
571
|
-
notBefore: run.dueAt > now ? run.dueAt : now,
|
|
572
|
-
createdAt: now
|
|
573
|
-
});
|
|
574
|
-
var shapeOf = (run) => ({ cause: run.cause, occurrence: run.occurrence, dueAt: run.dueAt });
|
|
575
|
-
var unitsForRun = async (deps, loaded, run, facts, now) => {
|
|
576
|
-
const { reflex } = loaded;
|
|
577
|
-
const base = buildEnv({
|
|
578
|
-
params: reflex.params,
|
|
579
|
-
occurrence: run.occurrence === void 0 ? void 0 : { key: run.occurrence, at: run.dueAt },
|
|
580
|
-
fact: facts.length === 1 ? { ...facts[0] } : void 0,
|
|
581
|
-
facts: facts.length > 1 ? facts.map((fact) => ({ ...fact })) : void 0,
|
|
582
|
-
now
|
|
583
|
-
});
|
|
584
|
-
const carried = facts.map((fact) => fact.row).filter((row) => row !== void 0);
|
|
585
|
-
if (carried.length > 0 && reflex.select === void 0) return unitsFrom(carried, void 0, base, reflex.id);
|
|
586
|
-
if (reflex.select === void 0) return [{ unit: "", env: base }];
|
|
587
|
-
if (deps.select === void 0)
|
|
588
|
-
throw new TideError("store", `${reflex.id} has a selection but no \`select\` seam is wired`);
|
|
589
|
-
const query = evaluateTemplate(deps.transform, reflex.select.query, base);
|
|
590
|
-
const rows = await collectRows(
|
|
591
|
-
deps.select(query, { reflexId: reflex.id, now, actor: deps.actorFor(reflex.as), env: base }),
|
|
592
|
-
deps.maxFanOut
|
|
593
|
-
);
|
|
594
|
-
if (reflex.select.mode === "batch") return [{ unit: "", env: { ...base, rows } }];
|
|
595
|
-
return unitsFrom(rows, reflex.select.unitKey, base, reflex.id);
|
|
596
|
-
};
|
|
597
|
-
|
|
598
478
|
// src/engine/facts.ts
|
|
599
479
|
var rootOf = async (store, cause) => {
|
|
600
480
|
if (cause === void 0) return void 0;
|
|
@@ -648,6 +528,7 @@ var claimTasks = async (deps, now, limit, token) => {
|
|
|
648
528
|
return deps.store.claim({
|
|
649
529
|
table: "task",
|
|
650
530
|
where: {
|
|
531
|
+
reflexId: { in: deps.reflexes().map((loaded) => loaded.reflex.id) },
|
|
651
532
|
state: { in: ["pending", "retrying", "claimed"] },
|
|
652
533
|
notBefore: { lte: now },
|
|
653
534
|
claimedUntil: { lte: now }
|
|
@@ -660,7 +541,8 @@ var claimTasks = async (deps, now, limit, token) => {
|
|
|
660
541
|
onePer: serialReflexIds.length === 0 ? void 0 : { column: "reflexId", held: { state: "claimed", claimedUntil: { gt: now } }, only: serialReflexIds }
|
|
661
542
|
});
|
|
662
543
|
};
|
|
663
|
-
var
|
|
544
|
+
var leaseRenewed = async (deps, task, token, clock) => clock === void 0 || deps.store.cas("task", task.id, { token, attempt: task.attempt }, { claimedUntil: Math.max(task.claimedUntil, clock() + deps.leaseMs) });
|
|
545
|
+
var executeTasks = async (deps, now, limit, clock) => {
|
|
664
546
|
const report = { executed: 0, succeeded: 0, failed: 0, retrying: 0, reclaimed: 0 };
|
|
665
547
|
const lapsed = new Set(
|
|
666
548
|
(await deps.store.query({
|
|
@@ -678,6 +560,7 @@ var executeTasks = async (deps, now, limit) => {
|
|
|
678
560
|
}
|
|
679
561
|
const loaded = deps.find(task.reflexId);
|
|
680
562
|
if (loaded === void 0) continue;
|
|
563
|
+
if (!await leaseRenewed(deps, task, token, clock)) continue;
|
|
681
564
|
const { reflex } = loaded;
|
|
682
565
|
const registry = deps.effectsFor(reflex.as);
|
|
683
566
|
const handler = registry[reflex.effect.name];
|
|
@@ -804,29 +687,164 @@ var reopenTask = async (deps, taskId, now) => deps.store.transact(async (tx) =>
|
|
|
804
687
|
return true;
|
|
805
688
|
});
|
|
806
689
|
var settleRuns = async (deps, now) => {
|
|
807
|
-
const settled = await deps.store.
|
|
690
|
+
const settled = await deps.store.query({
|
|
808
691
|
table: "run",
|
|
809
692
|
where: { state: "settled", drained: { ne: true } },
|
|
810
693
|
order: [{ by: "settledAt" }],
|
|
811
|
-
limit: 200
|
|
812
|
-
set: { drained: true }
|
|
694
|
+
limit: 200
|
|
813
695
|
});
|
|
696
|
+
let drained = 0;
|
|
814
697
|
for (const run of settled) {
|
|
815
|
-
deps.
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
698
|
+
const admission = await deps.store.transact(async (tx) => {
|
|
699
|
+
if (!await tx.cas("run", run.id, { state: "settled", drained: { ne: true } }, { drained: true })) return void 0;
|
|
700
|
+
return admitFact(tx, {
|
|
701
|
+
kind: "run",
|
|
702
|
+
reflex: run.reflexId,
|
|
703
|
+
runId: run.id,
|
|
704
|
+
occurrence: run.occurrence,
|
|
705
|
+
stats: { total: run.total, done: run.done, failed: run.failed },
|
|
706
|
+
at: now,
|
|
707
|
+
depth: run.depth + 1,
|
|
708
|
+
cause: `run:${run.id}`,
|
|
709
|
+
as: run.as
|
|
710
|
+
}, deps.maxChainFacts);
|
|
711
|
+
}).catch(() => void 0);
|
|
712
|
+
if (admission === void 0) continue;
|
|
713
|
+
drained += 1;
|
|
714
|
+
deps.emit({ type: "run.settled", run: { ...run, drained: true } });
|
|
827
715
|
announceFact(deps.emit, admission);
|
|
828
716
|
}
|
|
829
|
-
return
|
|
717
|
+
return drained;
|
|
718
|
+
};
|
|
719
|
+
|
|
720
|
+
// src/engine/fanout.ts
|
|
721
|
+
var collectRows = async (source, cap) => {
|
|
722
|
+
const resolved = await source;
|
|
723
|
+
const rows = [];
|
|
724
|
+
if (Symbol.asyncIterator in Object(resolved)) {
|
|
725
|
+
for await (const row of resolved) {
|
|
726
|
+
rows.push(row);
|
|
727
|
+
if (rows.length > cap) throw new TideError("duplicate_unit", `selection exceeded maxFanOut (${cap})`);
|
|
728
|
+
}
|
|
729
|
+
return rows;
|
|
730
|
+
}
|
|
731
|
+
for (const row of resolved) {
|
|
732
|
+
rows.push(row);
|
|
733
|
+
if (rows.length > cap) throw new TideError("duplicate_unit", `selection exceeded maxFanOut (${cap})`);
|
|
734
|
+
}
|
|
735
|
+
return rows;
|
|
736
|
+
};
|
|
737
|
+
var unitsFrom = (rows, unitKey, base, reflexId) => {
|
|
738
|
+
const seen = /* @__PURE__ */ new Set();
|
|
739
|
+
return rows.map((row) => {
|
|
740
|
+
const raw = unitKey === void 0 ? void 0 : row[unitKey];
|
|
741
|
+
const unit = raw === void 0 || raw === null ? "" : String(raw);
|
|
742
|
+
if (seen.has(unit))
|
|
743
|
+
throw new TideError("duplicate_unit", `${reflexId}: duplicate unit key "${unit}" \u2014 the selection's unitKey is not unique`);
|
|
744
|
+
seen.add(unit);
|
|
745
|
+
return { unit, env: { ...base, row } };
|
|
746
|
+
});
|
|
747
|
+
};
|
|
748
|
+
var factRowsOf = async (deps, run) => {
|
|
749
|
+
const ids = run.factIds ?? [];
|
|
750
|
+
if (ids.length === 0) return [];
|
|
751
|
+
return deps.store.query({ table: "fact", where: { id: { in: [...ids] } } });
|
|
752
|
+
};
|
|
753
|
+
var fanOut = async (deps, now, limit) => {
|
|
754
|
+
let created = 0;
|
|
755
|
+
if (!deps.hasLoaded()) return created;
|
|
756
|
+
if (deps.deferred.size > 0) {
|
|
757
|
+
const still = await deps.store.query({ table: "run", where: { id: { in: [...deps.deferred.keys()] }, state: "pending" } });
|
|
758
|
+
const pendingIds = new Set(still.map((run) => run.id));
|
|
759
|
+
for (const runId of deps.deferred.keys()) if (!pendingIds.has(runId)) deps.deferred.delete(runId);
|
|
760
|
+
}
|
|
761
|
+
const waiting = new Set(
|
|
762
|
+
[...deps.deferred].filter(([, deferral]) => deferral.until > now && deps.find(deferral.reflexId) !== void 0).map(([runId]) => runId)
|
|
763
|
+
);
|
|
764
|
+
const page = await deps.store.query({ table: "run", where: { state: "pending" }, order: [{ by: "dueAt" }], limit: limit + waiting.size });
|
|
765
|
+
const pending = page.filter((run) => !waiting.has(run.id)).slice(0, limit);
|
|
766
|
+
for (const run of pending) {
|
|
767
|
+
const loaded = deps.find(run.reflexId);
|
|
768
|
+
if (loaded === void 0) {
|
|
769
|
+
await deps.store.cas("run", run.id, { state: "pending" }, { state: "skipped", settledAt: now, drained: true, note: "reflex is no longer loaded" });
|
|
770
|
+
continue;
|
|
771
|
+
}
|
|
772
|
+
try {
|
|
773
|
+
const facts = await factRowsOf(deps, run);
|
|
774
|
+
const units = await unitsForRun(deps, loaded, shapeOf(run), facts, now);
|
|
775
|
+
created += await commitFanout(deps, run, units.map((unit) => taskOf(unit, run, loaded, now)), units.length, now);
|
|
776
|
+
} catch (error) {
|
|
777
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
778
|
+
if (isTideError(error)) {
|
|
779
|
+
await deps.store.cas("run", run.id, { state: "pending" }, { state: "skipped", settledAt: now, drained: true, note: `fan-out refused: ${reason}` });
|
|
780
|
+
deps.emit({ type: "run.skipped", reflexId: run.reflexId, reason });
|
|
781
|
+
continue;
|
|
782
|
+
}
|
|
783
|
+
await deps.store.cas("run", run.id, { state: "pending" }, { note: `fan-out deferred: ${reason}` });
|
|
784
|
+
const count = (deps.deferred.get(run.id)?.count ?? 0) + 1;
|
|
785
|
+
const retry = loaded.reflex.policy.retry;
|
|
786
|
+
const wait = backoffFor(Math.min(count, retry?.max ?? 3), retry?.baseMs ?? 6e4, retry?.backoff ?? "exponential");
|
|
787
|
+
deps.deferred.set(run.id, { reflexId: run.reflexId, count, until: now + Math.min(wait, Number.MAX_SAFE_INTEGER) });
|
|
788
|
+
deps.emit({ type: "run.deferred", reflexId: run.reflexId, runId: run.id, reason });
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
return created;
|
|
792
|
+
};
|
|
793
|
+
var commitFanout = async (deps, run, tasks, selected, now) => deps.store.transact(async (tx) => {
|
|
794
|
+
const claimed = await tx.cas("run", run.id, { state: "pending" }, { state: "fanned" });
|
|
795
|
+
if (!claimed) return 0;
|
|
796
|
+
let written = 0;
|
|
797
|
+
for (const task of tasks) if (await tx.appendIfAbsent("task", task) !== void 0) written += 1;
|
|
798
|
+
const settledNow = written === 0;
|
|
799
|
+
await tx.cas(
|
|
800
|
+
"run",
|
|
801
|
+
run.id,
|
|
802
|
+
{},
|
|
803
|
+
{
|
|
804
|
+
selected,
|
|
805
|
+
total: written,
|
|
806
|
+
state: settledNow ? "settled" : "fanned",
|
|
807
|
+
settledAt: settledNow ? now : void 0
|
|
808
|
+
}
|
|
809
|
+
);
|
|
810
|
+
return written;
|
|
811
|
+
});
|
|
812
|
+
var taskOf = (unit, run, loaded, now) => ({
|
|
813
|
+
runId: run.id,
|
|
814
|
+
reflexId: loaded.reflex.id,
|
|
815
|
+
unit: unit.unit,
|
|
816
|
+
cause: run.cause,
|
|
817
|
+
env: unit.env,
|
|
818
|
+
// Carried on the task: a swept run must not reset the chain ceiling.
|
|
819
|
+
depth: run.depth,
|
|
820
|
+
state: "pending",
|
|
821
|
+
attempt: 0,
|
|
822
|
+
claimedUntil: 0,
|
|
823
|
+
notBefore: run.dueAt > now ? run.dueAt : now,
|
|
824
|
+
createdAt: now
|
|
825
|
+
});
|
|
826
|
+
var shapeOf = (run) => ({ cause: run.cause, occurrence: run.occurrence, dueAt: run.dueAt });
|
|
827
|
+
var unitsForRun = async (deps, loaded, run, facts, now) => {
|
|
828
|
+
const { reflex } = loaded;
|
|
829
|
+
const base = buildEnv({
|
|
830
|
+
params: reflex.params,
|
|
831
|
+
occurrence: run.occurrence === void 0 ? void 0 : { key: run.occurrence, at: run.dueAt },
|
|
832
|
+
fact: facts.length === 1 ? { ...facts[0] } : void 0,
|
|
833
|
+
facts: facts.length > 1 ? facts.map((fact) => ({ ...fact })) : void 0,
|
|
834
|
+
now
|
|
835
|
+
});
|
|
836
|
+
const carried = facts.map((fact) => fact.row).filter((row) => row !== void 0);
|
|
837
|
+
if (carried.length > 0 && reflex.select === void 0) return unitsFrom(carried, void 0, base, reflex.id);
|
|
838
|
+
if (reflex.select === void 0) return [{ unit: "", env: base }];
|
|
839
|
+
if (deps.select === void 0)
|
|
840
|
+
throw new TideError("store", `${reflex.id} has a selection but no \`select\` seam is wired`);
|
|
841
|
+
const query = evaluateTemplate(deps.transform, reflex.select.query, base);
|
|
842
|
+
const rows = await collectRows(
|
|
843
|
+
deps.select(query, { reflexId: reflex.id, now, actor: deps.actorFor(reflex.as), env: base }),
|
|
844
|
+
deps.maxFanOut
|
|
845
|
+
);
|
|
846
|
+
if (reflex.select.mode === "batch") return [{ unit: "", env: { ...base, rows } }];
|
|
847
|
+
return unitsFrom(rows, reflex.select.unitKey, base, reflex.id);
|
|
830
848
|
};
|
|
831
849
|
|
|
832
850
|
// src/engine/advance.ts
|
|
@@ -837,7 +855,7 @@ var runAdvance = async (deps, options) => {
|
|
|
837
855
|
const clocks = await materializeClocks(deps, now);
|
|
838
856
|
const matched = await matchFacts(deps, now, limit);
|
|
839
857
|
const tasksCreated = await fanOut(deps, now, limit);
|
|
840
|
-
const executed = await executeTasks(deps, now, limit);
|
|
858
|
+
const executed = await executeTasks(deps, now, limit, options.clock);
|
|
841
859
|
const runsSettled = await settleRuns(deps, now);
|
|
842
860
|
return {
|
|
843
861
|
now,
|
|
@@ -880,19 +898,20 @@ var nextDue = async (deps, now) => {
|
|
|
880
898
|
consider(delayed?.notBefore);
|
|
881
899
|
const [run] = await deps.store.query({ table: "run", where: { state: "pending" }, order: [{ by: "dueAt" }], limit: 1 });
|
|
882
900
|
consider(run?.dueAt);
|
|
901
|
+
const loaded = { in: deps.reflexes().map((entry) => entry.reflex.id) };
|
|
883
902
|
const [waiting] = await deps.store.query({
|
|
884
903
|
table: "task",
|
|
885
|
-
where: { state: { in: ["pending", "retrying"] } },
|
|
904
|
+
where: { reflexId: loaded, state: { in: ["pending", "retrying"] } },
|
|
886
905
|
order: [{ by: "notBefore" }],
|
|
887
906
|
limit: 1
|
|
888
907
|
});
|
|
889
908
|
consider(waiting?.notBefore);
|
|
890
|
-
const [claimed] = await deps.store.query({ table: "task", where: { state: "claimed" }, order: [{ by: "claimedUntil" }], limit: 1 });
|
|
909
|
+
const [claimed] = await deps.store.query({ table: "task", where: { reflexId: loaded, state: "claimed" }, order: [{ by: "claimedUntil" }], limit: 1 });
|
|
891
910
|
consider(claimed?.claimedUntil);
|
|
892
|
-
for (const
|
|
893
|
-
const clock = clockOf(
|
|
911
|
+
for (const loaded2 of deps.reflexes()) {
|
|
912
|
+
const clock = clockOf(loaded2.reflex.on);
|
|
894
913
|
if (clock !== void 0) {
|
|
895
|
-
const state = await stateOf(deps,
|
|
914
|
+
const state = await stateOf(deps, loaded2.reflex.id);
|
|
896
915
|
if (state?.materializedThrough === void 0) {
|
|
897
916
|
consider(now);
|
|
898
917
|
continue;
|
|
@@ -973,6 +992,20 @@ var DEFAULT_MAX_CHAIN_DEPTH = 24;
|
|
|
973
992
|
var DEFAULT_MAX_CHAIN_FACTS = 1e4;
|
|
974
993
|
var DEFAULT_MAX_FAN_OUT = 1e4;
|
|
975
994
|
var DEFAULT_LEASE_MS = 3e5;
|
|
995
|
+
var missingDateWarnings = (reflex) => {
|
|
996
|
+
const clock = clockOf(reflex.on);
|
|
997
|
+
if (clock === void 0 || isRecurring(clock)) return [];
|
|
998
|
+
const named = clock.at.slice(0, 10);
|
|
999
|
+
const [year = 0, month = 0, day = 0] = named.split("-").map(Number);
|
|
1000
|
+
const asWritten = /* @__PURE__ */ new Date(0);
|
|
1001
|
+
asWritten.setUTCFullYear(year, month - 1, day);
|
|
1002
|
+
if (asWritten.getUTCFullYear() === year && asWritten.getUTCMonth() === month - 1 && asWritten.getUTCDate() === day) return [];
|
|
1003
|
+
const [fires] = occurrencesBetween(clock, -Infinity, Infinity, 1);
|
|
1004
|
+
if (fires === void 0) return [];
|
|
1005
|
+
const local = zonedParts(fires.at, clock.tz);
|
|
1006
|
+
const on = [local.year, local.month, local.day].map((part, index) => String(part).padStart(index === 0 ? 4 : 2, "0")).join("-");
|
|
1007
|
+
return [`${reflex.id}: clock.at names ${named}, which does not exist \u2014 it fires on ${on}`];
|
|
1008
|
+
};
|
|
976
1009
|
var createTide = (config) => {
|
|
977
1010
|
const loaded = /* @__PURE__ */ new Map();
|
|
978
1011
|
let effectsCache;
|
|
@@ -982,6 +1015,7 @@ var createTide = (config) => {
|
|
|
982
1015
|
return effectsCache;
|
|
983
1016
|
};
|
|
984
1017
|
let tokens = 0;
|
|
1018
|
+
let hasLoaded = false;
|
|
985
1019
|
const deps = {
|
|
986
1020
|
store: config.store,
|
|
987
1021
|
transform: config.transform,
|
|
@@ -994,27 +1028,42 @@ var createTide = (config) => {
|
|
|
994
1028
|
leaseMs: config.leaseMs ?? DEFAULT_LEASE_MS,
|
|
995
1029
|
emit: config.onEvent ?? (() => void 0),
|
|
996
1030
|
reflexes: () => [...loaded.values()],
|
|
1031
|
+
hasLoaded: () => hasLoaded,
|
|
997
1032
|
find: (id) => loaded.get(id),
|
|
998
1033
|
nextToken: () => {
|
|
999
1034
|
tokens += 1;
|
|
1000
1035
|
return `tok_${tokens.toString(36)}`;
|
|
1001
|
-
}
|
|
1036
|
+
},
|
|
1037
|
+
deferred: /* @__PURE__ */ new Map()
|
|
1038
|
+
};
|
|
1039
|
+
const everLoaded = /* @__PURE__ */ new Set();
|
|
1040
|
+
let lastLoad = Promise.resolve();
|
|
1041
|
+
const load = (input, options) => {
|
|
1042
|
+
const turn = lastLoad.then(() => loadNow(input, options));
|
|
1043
|
+
lastLoad = turn.catch(() => void 0);
|
|
1044
|
+
return turn;
|
|
1002
1045
|
};
|
|
1003
|
-
const
|
|
1004
|
-
const { reflexes: parsed, graph, refused } = admitReflexes(input, mergedEffects, options?.isolate === true);
|
|
1046
|
+
const loadNow = async (input, options) => {
|
|
1047
|
+
const { reflexes: parsed, graph, refused } = admitReflexes({ input, effectsOf: mergedEffects, isolate: options?.isolate === true });
|
|
1005
1048
|
const previously = new Set(loaded.keys());
|
|
1006
1049
|
const next = /* @__PURE__ */ new Map();
|
|
1007
1050
|
for (const reflex of parsed) {
|
|
1008
1051
|
const stored = await stateOf(deps, reflex.id);
|
|
1009
1052
|
const armedAt = stored?.armedAt ?? options?.at ?? 0;
|
|
1010
1053
|
if (stored === void 0) await config.store.appendIfAbsent("state", { reflexId: reflex.id, armedAt });
|
|
1011
|
-
|
|
1054
|
+
const entering = !previously.has(reflex.id) && (options?.resume !== true || everLoaded.has(reflex.id));
|
|
1055
|
+
if (entering && stored?.materializedThrough !== void 0 && options?.at !== void 0)
|
|
1012
1056
|
await config.store.cas("state", reflex.id, {}, { materializedThrough: Math.max(stored.materializedThrough, options.at) });
|
|
1013
1057
|
next.set(reflex.id, { reflex, version: versionOf(reflex), armedAt });
|
|
1014
1058
|
}
|
|
1015
1059
|
loaded.clear();
|
|
1016
1060
|
for (const [id, entry] of next) loaded.set(id, entry);
|
|
1017
|
-
|
|
1061
|
+
for (const id of next.keys()) everLoaded.add(id);
|
|
1062
|
+
hasLoaded = true;
|
|
1063
|
+
const leaseWarnings = parsed.filter((reflex) => reflex.policy.timeoutMs >= deps.leaseMs).map(
|
|
1064
|
+
(reflex) => `${reflex.id}: timeoutMs ${reflex.policy.timeoutMs} is not shorter than leaseMs ${deps.leaseMs} \u2014 another instance may claim the task again while its effect still runs`
|
|
1065
|
+
);
|
|
1066
|
+
return { loaded: parsed.length, cycles: graph.cycles, blind: graph.blind, warnings: [...graph.warnings, ...leaseWarnings, ...parsed.flatMap(missingDateWarnings)], refused };
|
|
1018
1067
|
};
|
|
1019
1068
|
const mergedEffects = (parsed) => {
|
|
1020
1069
|
if (typeof config.effects !== "function") return config.effects ?? {};
|
|
@@ -1039,6 +1088,7 @@ var createTide = (config) => {
|
|
|
1039
1088
|
throw new TideError("invalid_fact", `fact did not parse: ${result.error.issues.map((i) => i.message).join("; ")}`, {
|
|
1040
1089
|
issues: result.error.issues
|
|
1041
1090
|
});
|
|
1091
|
+
if (result.data.kind === "run") throw new TideError("invalid_fact", "a run fact is minted by tide when a run settles; it is not ingested");
|
|
1042
1092
|
if (!watchable(result.data)) return void 0;
|
|
1043
1093
|
const admission = await admitFact(config.store, { ...result.data, cause: options?.cause, depth: options?.depth ?? 0, as: options?.as }, deps.maxChainFacts);
|
|
1044
1094
|
announceFact(deps.emit, admission);
|
|
@@ -1098,13 +1148,12 @@ var createTide = (config) => {
|
|
|
1098
1148
|
}),
|
|
1099
1149
|
task: (id) => one("task", id),
|
|
1100
1150
|
facts: async (filter) => {
|
|
1101
|
-
const
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
return filter?.limit === void 0 ? matched : matched.slice(0, filter.limit);
|
|
1151
|
+
const newest = { order: [{ by: "at", dir: "desc" }], limit: filter?.limit };
|
|
1152
|
+
if (filter?.reflexId === void 0) return config.store.query({ table: "fact", ...newest });
|
|
1153
|
+
const minted = await config.store.query({ table: "fact", where: { reflex: filter.reflexId }, ...newest });
|
|
1154
|
+
const aimed = await config.store.query({ table: "fact", where: { target: filter.reflexId }, ...newest });
|
|
1155
|
+
const matched = [...new Map([...minted, ...aimed].map((fact) => [fact.id, fact])).values()].sort((left, right) => right.at - left.at);
|
|
1156
|
+
return filter.limit === void 0 ? matched : matched.slice(0, filter.limit);
|
|
1108
1157
|
},
|
|
1109
1158
|
fact: (id) => one("fact", id),
|
|
1110
1159
|
causeChain,
|
|
@@ -1220,26 +1269,31 @@ var createMemoryStore = () => {
|
|
|
1220
1269
|
spec.order
|
|
1221
1270
|
);
|
|
1222
1271
|
const taken = /* @__PURE__ */ new Set();
|
|
1223
|
-
const restricted =
|
|
1272
|
+
const restricted = spec.onePer?.only ?? [];
|
|
1224
1273
|
if (spec.onePer !== void 0) {
|
|
1225
1274
|
for (const row of rowsOf(spec.table))
|
|
1226
1275
|
if (matches(row, spec.onePer.held)) taken.add(String(row[spec.onePer.column]));
|
|
1227
1276
|
}
|
|
1228
|
-
const
|
|
1277
|
+
const groupOf = (row) => spec.onePer === void 0 ? void 0 : String(row[spec.onePer.column]);
|
|
1278
|
+
const chosen = [];
|
|
1279
|
+
for (const group of restricted) {
|
|
1280
|
+
if (chosen.length >= spec.limit) break;
|
|
1281
|
+
if (taken.has(group)) continue;
|
|
1282
|
+
const first = candidates.find((row) => groupOf(row) === group);
|
|
1283
|
+
if (first === void 0) continue;
|
|
1284
|
+
taken.add(group);
|
|
1285
|
+
chosen.push(first);
|
|
1286
|
+
}
|
|
1229
1287
|
for (const row of candidates) {
|
|
1230
|
-
if (
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
taken.add(group);
|
|
1236
|
-
}
|
|
1237
|
-
}
|
|
1288
|
+
if (chosen.length >= spec.limit) break;
|
|
1289
|
+
const group = groupOf(row);
|
|
1290
|
+
if (group === void 0 || !restricted.includes(group)) chosen.push(row);
|
|
1291
|
+
}
|
|
1292
|
+
return sorted(chosen, spec.order).map((row) => {
|
|
1238
1293
|
const next = applied(row, spec.set);
|
|
1239
1294
|
tables[spec.table].set(keyOf(spec.table, next), next);
|
|
1240
|
-
|
|
1241
|
-
}
|
|
1242
|
-
return claimed;
|
|
1295
|
+
return next;
|
|
1296
|
+
});
|
|
1243
1297
|
};
|
|
1244
1298
|
const cas = async (table, id, expect, set) => {
|
|
1245
1299
|
const row = tables[table].get(id);
|
|
@@ -1301,7 +1355,7 @@ var createTideDriver = (config) => {
|
|
|
1301
1355
|
let timer;
|
|
1302
1356
|
const drain = async () => {
|
|
1303
1357
|
for (let steps = 0; steps < MAX_STEPS_PER_DRAIN; steps += 1) {
|
|
1304
|
-
const report = await tide.advance({ now: now() });
|
|
1358
|
+
const report = await tide.advance({ now: now(), clock: now });
|
|
1305
1359
|
if (progressOf(report) === 0) return;
|
|
1306
1360
|
}
|
|
1307
1361
|
console.error(`[tide:driver] a drain exceeded ${MAX_STEPS_PER_DRAIN} steps \u2014 stopping this pass; the janitor will resume it`);
|