@yaks/wake 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +325 -2
  3. package/_dist/cloudflare.d.ts +68 -0
  4. package/_dist/cloudflare.d.ts.map +1 -0
  5. package/_dist/comp.d.ts +59 -0
  6. package/_dist/comp.d.ts.map +1 -0
  7. package/_dist/deno.d.ts +40 -0
  8. package/_dist/deno.d.ts.map +1 -0
  9. package/_dist/due.d.ts +96 -0
  10. package/_dist/due.d.ts.map +1 -0
  11. package/_dist/every.d.ts +65 -0
  12. package/_dist/every.d.ts.map +1 -0
  13. package/_dist/graph.d.ts +4 -0
  14. package/_dist/graph.d.ts.map +1 -0
  15. package/_dist/held.d.ts +9 -0
  16. package/_dist/held.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +59 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/plugin.d.ts +20 -0
  20. package/_dist/plugin.d.ts.map +1 -0
  21. package/_dist/run.d.ts +24 -0
  22. package/_dist/run.d.ts.map +1 -0
  23. package/_dist/service.d.ts +9 -0
  24. package/_dist/service.d.ts.map +1 -0
  25. package/_dist/tick.d.ts +36 -0
  26. package/_dist/tick.d.ts.map +1 -0
  27. package/_dist/tools.d.ts +6 -0
  28. package/_dist/tools.d.ts.map +1 -0
  29. package/_dist/vocab.d.ts +7 -0
  30. package/_dist/vocab.d.ts.map +1 -0
  31. package/_dist/watch.d.ts +58 -0
  32. package/_dist/watch.d.ts.map +1 -0
  33. package/_dist/while.d.ts +43 -0
  34. package/_dist/while.d.ts.map +1 -0
  35. package/cloudflare.js +80 -0
  36. package/cloudflare.js.map +1 -0
  37. package/cloudflare.ts +113 -0
  38. package/comp.js +59 -0
  39. package/comp.js.map +1 -0
  40. package/comp.ts +139 -0
  41. package/deno.js +57 -0
  42. package/deno.js.map +1 -0
  43. package/deno.json +1 -0
  44. package/deno.ts +78 -0
  45. package/due.js +147 -0
  46. package/due.js.map +1 -0
  47. package/due.ts +180 -0
  48. package/every.js +203 -0
  49. package/every.js.map +1 -0
  50. package/every.ts +223 -0
  51. package/graph.js +10 -0
  52. package/graph.js.map +1 -0
  53. package/graph.ts +11 -0
  54. package/held.js +29 -0
  55. package/held.js.map +1 -0
  56. package/held.ts +42 -0
  57. package/mod.js +59 -0
  58. package/mod.js.map +1 -0
  59. package/mod.ts +60 -0
  60. package/package.json +49 -4
  61. package/plugin.js +87 -0
  62. package/plugin.js.map +1 -0
  63. package/plugin.ts +94 -0
  64. package/run.js +124 -0
  65. package/run.js.map +1 -0
  66. package/run.ts +117 -0
  67. package/service.js +28 -0
  68. package/service.js.map +1 -0
  69. package/service.ts +42 -0
  70. package/tick.js +168 -0
  71. package/tick.js.map +1 -0
  72. package/tick.ts +181 -0
  73. package/tools.js +83 -0
  74. package/tools.js.map +1 -0
  75. package/tools.ts +76 -0
  76. package/vocab.js +14 -0
  77. package/vocab.js.map +1 -0
  78. package/vocab.json +270 -0
  79. package/vocab.ts +16 -0
  80. package/watch.js +175 -0
  81. package/watch.js.map +1 -0
  82. package/watch.ts +193 -0
  83. package/while.js +159 -0
  84. package/while.js.map +1 -0
  85. package/while.ts +176 -0
package/cloudflare.ts ADDED
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Cloudflare decides when to run; the graph holds the schedules. A Cron Trigger
3
+ * calls `scheduled`, while a Durable Object can set its single alarm for a wake
4
+ * that falls before the next Cron Trigger. Neither imports a Cloudflare global,
5
+ * so Deno can exercise the same driver with a stand-in storage.
6
+ * @module
7
+ */
8
+
9
+ import type { Wake } from './comp.ts'
10
+ import { type Driver, tick, type Ticked } from './tick.js'
11
+
12
+ /** The instant Cloudflare scheduled, independent of delivery latency. */
13
+ export type Scheduled = { scheduledTime: number }
14
+
15
+ /** The alarm methods a Durable Object's storage provides. */
16
+ export type Alarm = {
17
+ getAlarm: () => Promise<number | null>
18
+ setAlarm: (at: number) => Promise<void>
19
+ }
20
+
21
+ // The runtime gives each object a single alarm. Calls within one handler can
22
+ // race, so the read/compare/write is serialized per storage object, even after
23
+ // one of them failed. A later wake must never overwrite an earlier one that is
24
+ // in the middle of being set.
25
+ let arming = new WeakMap<Alarm, Promise<unknown>>()
26
+
27
+ /**
28
+ * How long past its instant an alarm may still be held before it is taken as
29
+ * lost. The runtime retries a failing `alarm()` six times, with backoff, then
30
+ * gives up, and `getAlarm()` goes on answering the instant it gave up on; an
31
+ * object whose alarm kept running out of CPU held one for days, and nothing
32
+ * delivered it again.
33
+ */
34
+ export let LOST: number = 15 * 60_000
35
+
36
+ /**
37
+ * The alarm the runtime will deliver: null when none is set, or when the one
38
+ * set is more than `LOST` past its instant.
39
+ *
40
+ * ```ts
41
+ * import { armed, LOST } from '@yaks/wake/cloudflare'
42
+ * import { assertEquals } from '@std/assert'
43
+ *
44
+ * let storage = (at: number | null) => ({
45
+ * getAlarm: () => Promise.resolve(at),
46
+ * setAlarm: () => Promise.resolve(),
47
+ * })
48
+ * assertEquals(await armed(storage(900), 1000), 900)
49
+ * assertEquals(await armed(storage(1000 - LOST - 1), 1000), null)
50
+ * ```
51
+ */
52
+ export let armed = async (
53
+ storage: Alarm,
54
+ now: number = Date.now(),
55
+ ): Promise<number | null> => {
56
+ let at = await storage.getAlarm()
57
+ return lost(at, now) ? null : at
58
+ }
59
+
60
+ let lost = (at: number | null, now: number): at is number =>
61
+ at != null && at < now - LOST
62
+
63
+ /**
64
+ * A Worker's scheduled handler, reduced to the graph write every runtime
65
+ * shares. The event's cron string does not select a job: the due wake rows do.
66
+ *
67
+ * ```ts
68
+ * import { scheduled } from '@yaks/wake/cloudflare'
69
+ *
70
+ * // export default { scheduled: (event) => scheduled(graph, event) }
71
+ * ```
72
+ */
73
+ export let scheduled = (
74
+ graph: Driver,
75
+ event: Scheduled,
76
+ ): Promise<Ticked> => tick(graph, event.scheduledTime)
77
+
78
+ /**
79
+ * Set a Durable Object's alarm for one wake. An alarm that is already earlier
80
+ * is kept, because the object may hold other wakes. Returns whether this wake
81
+ * needs the alarm at all; a wake with no `at`, or a later one, leaves it alone.
82
+ * An alarm the runtime gave up on (`armed`) is set again for `now`, since the
83
+ * run it stood for is still owed.
84
+ *
85
+ * Call it when a wake is written. In the object's `alarm()`, call `tick(graph)`
86
+ * and then set the alarm for its next pending wake. `before` is for an
87
+ * application that also has a Cron Trigger: pass the time of the next trigger,
88
+ * and a wake falling after it is left for that trigger to fire rather than this
89
+ * object. An application whose alarm is its only clock leaves `before` out.
90
+ *
91
+ * ```ts
92
+ * import { arm } from '@yaks/wake/cloudflare'
93
+ *
94
+ * // await arm(ctx.storage, wake)
95
+ * ```
96
+ */
97
+ export let arm = (
98
+ storage: Alarm,
99
+ wake: Wake,
100
+ before = Infinity,
101
+ now: number = Date.now(),
102
+ ): Promise<boolean> => {
103
+ let pending = (arming.get(storage) ?? Promise.resolve()).then(async () => {
104
+ let at = wake.at ? Date.parse(wake.at) : NaN
105
+ if (!Number.isFinite(at) || at >= before) return false
106
+ let set = await storage.getAlarm()
107
+ if (lost(set, now)) await storage.setAlarm(Math.min(at, now))
108
+ else if (set == null || set > at) await storage.setAlarm(at)
109
+ return true
110
+ })
111
+ arming.set(storage, pending.catch(() => {}))
112
+ return pending
113
+ }
package/comp.js ADDED
@@ -0,0 +1,59 @@
1
+ // The two components this package ships, as one vocabulary document to load
2
+ // beside your own.
3
+ //
4
+ // wake{at, every, while, target, note, for, brief}
5
+ // when to come back, to what, and for
6
+ // whom
7
+ // fired{at} the last time it fired
8
+ // watch{query, tool, args, local, over, seen, changes}
9
+ // a query whose change it fires on
10
+ // occurrence{wake, at, call, error} one firing that did work
11
+ //
12
+ // One entity, one alarm. `at` is the whole schedule for a one-shot — a
13
+ // reminder on a calendar entry, a retry in ten minutes. Add `every` and the
14
+ // same row recurs: `at` is then the next instant, moved forward each time it
15
+ // is consumed, and a wake with no `at` left is one that has finished.
16
+ //
17
+ // `target` is what the wake is about, which is not always the entity that
18
+ // carries it: a wake on a calendar entry usually means that entry, while a wake
19
+ // created by a sweep means whatever the sweep found. It is deleted with what it
20
+ // points at (`death: cascade`), because a reminder about a deleted thing is not
21
+ // a reminder about anything — cancel the entry and the alarm goes with it.
22
+ //
23
+ // `every` and then `while` are declared last in the document on purpose, so
24
+ // that this table is an existing `wake` table plus appended columns — which is
25
+ // what an additive migration produces.
26
+ //
27
+ // `while` makes the recurrence conditional: `{match, every}` in order, the
28
+ // first whose query finds anything setting the cadence (./while.ts). A wake
29
+ // none of them holds, with no `every` of its own, sleeps until a write makes
30
+ // one hold.
31
+ //
32
+ // `fired` records the last firing, not every one: it is overwritten each time,
33
+ // so a recurring wake holds its most recent firing and a one-shot holds its
34
+ // only one. What happened at that instant is for the application to record;
35
+ // this package records only that it happened, which is what makes a repeated
36
+ // run detectable.
37
+ //
38
+ // The components themselves are declared in `./vocab.json` — plain JSON Schema,
39
+ // readable by anything that reads JSON.
40
+ //
41
+ // `for` is whom a wake was set for, which a host that runs work for people
42
+ // reads as the identity it runs as (./run.ts); `brief` is the words for a
43
+ // fresh session each firing. `watch` makes a wake fire only when a query's
44
+ // rows changed (./watch.ts), and `occurrence` is the record of one firing that
45
+ // ran a call (./run.ts). This file re-exports it under the name
46
+ // callers import and keeps the explanation of why it is shaped this way.
47
+ import doc from './vocab.json' with {
48
+ type: 'json'
49
+ };
50
+ /** The component holding when to come back. */ export let WAKE = 'wake';
51
+ /** The component recording when a wake last fired. */ export let FIRED = 'fired';
52
+ /** The component holding the query a wake watches. */ export let WATCH = 'watch';
53
+ /** The component recording one firing that did work. */ export let OCCURRENCE = 'occurrence';
54
+ /**
55
+ * The wake vocabulary, to load beside your own:
56
+ * `loadVocab([wakeDoc, ...mine])`. It declares nothing about what is being
57
+ * woken — that is an ordinary entity in your own vocabulary — only when.
58
+ */ export let wakeDoc = doc;
59
+ //# sourceMappingURL=comp.js.map
package/comp.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"comp.js","sources":["./comp.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,mBAAmB;AACnB,EAAE;AACF,qDAAqD;AACrD,+EAA+E;AAC/E,gDAAgD;AAChD,kEAAkE;AAClE,yDAAyD;AACzD,4EAA4E;AAC5E,oEAAoE;AACpE,EAAE;AACF,uEAAuE;AACvE,4EAA4E;AAC5E,6EAA6E;AAC7E,sEAAsE;AACtE,EAAE;AACF,0EAA0E;AAC1E,gFAAgF;AAChF,gFAAgF;AAChF,gFAAgF;AAChF,2EAA2E;AAC3E,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,uCAAuC;AACvC,EAAE;AACF,2EAA2E;AAC3E,4EAA4E;AAC5E,6EAA6E;AAC7E,YAAY;AACZ,EAAE;AACF,+EAA+E;AAC/E,4EAA4E;AAC5E,4EAA4E;AAC5E,6EAA6E;AAC7E,kBAAkB;AAClB,EAAE;AACF,gFAAgF;AAChF,wCAAwC;AACxC,EAAE;AACF,2EAA2E;AAC3E,0EAA0E;AAC1E,2EAA2E;AAC3E,+EAA+E;AAC/E,gEAAgE;AAChE,yEAAyE;AAIzE,OAAO,SAAS,oBAAoB;EAAE,MAAM;AAAO,EAAC;AAEpD,6CAA6C,GAC7C,OAAO,IAAI,OAAO,OAAM;AAExB,oDAAoD,GACpD,OAAO,IAAI,QAAQ,QAAO;AA2B1B,oDAAoD,GACpD,OAAO,IAAI,QAAQ,QAAO;AA0B1B,sDAAsD,GACtD,OAAO,IAAI,aAAa,aAAY;AAuBpC;;;;CAIC,GACD,OAAO,IAAI,UAAoB,IAAG"}
package/comp.ts ADDED
@@ -0,0 +1,139 @@
1
+ // The two components this package ships, as one vocabulary document to load
2
+ // beside your own.
3
+ //
4
+ // wake{at, every, while, target, note, for, brief}
5
+ // when to come back, to what, and for
6
+ // whom
7
+ // fired{at} the last time it fired
8
+ // watch{query, tool, args, local, over, seen, changes}
9
+ // a query whose change it fires on
10
+ // occurrence{wake, at, call, error} one firing that did work
11
+ //
12
+ // One entity, one alarm. `at` is the whole schedule for a one-shot — a
13
+ // reminder on a calendar entry, a retry in ten minutes. Add `every` and the
14
+ // same row recurs: `at` is then the next instant, moved forward each time it
15
+ // is consumed, and a wake with no `at` left is one that has finished.
16
+ //
17
+ // `target` is what the wake is about, which is not always the entity that
18
+ // carries it: a wake on a calendar entry usually means that entry, while a wake
19
+ // created by a sweep means whatever the sweep found. It is deleted with what it
20
+ // points at (`death: cascade`), because a reminder about a deleted thing is not
21
+ // a reminder about anything — cancel the entry and the alarm goes with it.
22
+ //
23
+ // `every` and then `while` are declared last in the document on purpose, so
24
+ // that this table is an existing `wake` table plus appended columns — which is
25
+ // what an additive migration produces.
26
+ //
27
+ // `while` makes the recurrence conditional: `{match, every}` in order, the
28
+ // first whose query finds anything setting the cadence (./while.ts). A wake
29
+ // none of them holds, with no `every` of its own, sleeps until a write makes
30
+ // one hold.
31
+ //
32
+ // `fired` records the last firing, not every one: it is overwritten each time,
33
+ // so a recurring wake holds its most recent firing and a one-shot holds its
34
+ // only one. What happened at that instant is for the application to record;
35
+ // this package records only that it happened, which is what makes a repeated
36
+ // run detectable.
37
+ //
38
+ // The components themselves are declared in `./vocab.json` — plain JSON Schema,
39
+ // readable by anything that reads JSON.
40
+ //
41
+ // `for` is whom a wake was set for, which a host that runs work for people
42
+ // reads as the identity it runs as (./run.ts); `brief` is the words for a
43
+ // fresh session each firing. `watch` makes a wake fire only when a query's
44
+ // rows changed (./watch.ts), and `occurrence` is the record of one firing that
45
+ // ran a call (./run.ts). This file re-exports it under the name
46
+ // callers import and keeps the explanation of why it is shaped this way.
47
+
48
+ import type { Eid, Entity } from 'jsr:@yaks/graph@0.2.36'
49
+ import type { VocabDoc } from 'jsr:@yaks/vocab@0.2.36'
50
+ import doc from './vocab.json' with { type: 'json' }
51
+
52
+ /** The component holding when to come back. */
53
+ export let WAKE = 'wake'
54
+
55
+ /** The component recording when a wake last fired. */
56
+ export let FIRED = 'fired'
57
+
58
+ /**
59
+ * A wake: a scheduled return to something, at a time or on a cadence.
60
+ */
61
+ export type Wake = {
62
+ /** when it is next due, an ISO instant — absent once it has finished */
63
+ at?: string | null
64
+ /** how it recurs: a duration, five cron fields or a `@` shorthand, optionally
65
+ * followed by an IANA zone (`0 9 * * 1-5 America/New_York`)
66
+ * (see {@link https://jsr.io/@yaks/wake/doc/~/next | next}) */
67
+ every?: string | null
68
+ /** how it recurs while something holds: in order, a query over the whole
69
+ * graph and the cadence it asks for while that query finds anything; the
70
+ * first that holds wins, else `every` does, else the wake sleeps
71
+ * (see {@link https://jsr.io/@yaks/wake/doc/~/cadence | cadence}) */
72
+ while?: { match: string; every: string }[] | null
73
+ /** what the wake is about — the entity carrying it, when absent */
74
+ target?: Eid | null
75
+ /** a line for whoever is woken: why the wake was set */
76
+ note?: string | null
77
+ /** the person it was set for, as whom it runs */
78
+ for?: Eid | null
79
+ /** words for a fresh session each firing, given its call's outcome */
80
+ brief?: string | null
81
+ }
82
+
83
+ /** The component holding the query a wake watches. */
84
+ export let WATCH = 'watch'
85
+
86
+ /** A query a wake watches: it fires only when its rows changed. */
87
+ export type Watch = {
88
+ /** the query, as graph_query takes it */
89
+ query: string
90
+ /** the reading tool it was subscribed to, whose declared query this is */
91
+ tool?: string | null
92
+ /** the arguments that tool was given */
93
+ args?: Record<string, unknown> | null
94
+ /** read over the store the wake is kept in, not all its person reaches */
95
+ local?: boolean | null
96
+ /** the graph its host reads it over, by the host's name for it, where it
97
+ * is neither the store the wake is kept in nor all its person reaches */
98
+ over?: string | null
99
+ /** each row the last look saw, by eid, with a digest of it */
100
+ seen?: Record<string, string> | null
101
+ /** what changed at the look the wake last fired for, in words */
102
+ changes?: string | null
103
+ /** keep successful changes as activity without waking a conversation */
104
+ record_only?: boolean | null
105
+ /** why its reader refused the query at the last look, until a look reads
106
+ * it again */
107
+ refused?: string | null
108
+ }
109
+
110
+ /** The component recording one firing that did work. */
111
+ export let OCCURRENCE = 'occurrence'
112
+
113
+ /** One firing of a wake that did work. */
114
+ export type Occurrence = {
115
+ /** the wake that fired */
116
+ wake: Eid
117
+ /** the instant it fired, ISO */
118
+ at: string
119
+ /** the call it made */
120
+ call?: Eid | null
121
+ /** the call's failure, kept while a helper checks it */
122
+ error?: string | null
123
+ }
124
+
125
+ /** What a fired wake records: when it last fired. */
126
+ export type Fired = {
127
+ /** the instant it fired, ISO */
128
+ at: string
129
+ }
130
+
131
+ /** A bundle carrying a wake, as {@link due} returns them. */
132
+ export type Waking = { entity: Entity } & { wake: Wake; fired?: Fired }
133
+
134
+ /**
135
+ * The wake vocabulary, to load beside your own:
136
+ * `loadVocab([wakeDoc, ...mine])`. It declares nothing about what is being
137
+ * woken — that is an ordinary entity in your own vocabulary — only when.
138
+ */
139
+ export let wakeDoc: VocabDoc = doc
package/deno.js ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * A long-running process can sleep until the next wake instead of polling at a
3
+ * fixed rate. The cap lets newly written wakes be noticed without a
4
+ * subscription, sleeping ones a write made hold among them, and keeps an empty
5
+ * graph and a far-off date within `setTimeout`'s range. Stopping aborts only
6
+ * the wait: a graph write already underway finishes its phases.
7
+ * @module
8
+ */ import { sleep, system } from "@yaks/fp";
9
+ import { soonest } from "./due.js";
10
+ import { rouse } from "./while.js";
11
+ import { tick } from "./tick.js";
12
+ /**
13
+ * Rouse and tick immediately, then sleep until the next due instant or the
14
+ * cap, whichever is sooner. A wake whose transaction was rejected on one pass
15
+ * stays due for the next; effects run through the graph. Uses only web timers
16
+ * and `AbortSignal`, available in Deno and Node alike.
17
+ *
18
+ * The first tick happens whatever the signal's state, so one that has already
19
+ * aborted produces exactly one pass — which is how a short-lived process fires
20
+ * what is overdue as it starts up.
21
+ *
22
+ * ```ts
23
+ * import { loop } from '@yaks/wake/deno'
24
+ *
25
+ * let stop = new AbortController()
26
+ * // let running = loop(graph, { signal: stop.signal })
27
+ * // stop.abort()
28
+ * // await running
29
+ * ```
30
+ */ export let loop = async (graph, opts = {})=>{
31
+ let cap = opts.cap ?? 60_000;
32
+ let clock = opts.clock ?? system;
33
+ if (!Number.isFinite(cap) || cap <= 0 || cap > 2_147_483_647) {
34
+ throw new RangeError('wake loop cap must be within setTimeout range');
35
+ }
36
+ // One pass first, always: a signal that is already aborted means a
37
+ // short-lived process — a one-off command run to fire whatever is overdue —
38
+ // and it still owes the graph the tick it was started for.
39
+ do {
40
+ let now = clock.now();
41
+ let { refused } = await rouse(graph, now);
42
+ let result = await tick(graph, now);
43
+ await opts.onTick?.({
44
+ ...result,
45
+ refused: [
46
+ ...refused,
47
+ ...result.refused
48
+ ]
49
+ });
50
+ if (opts.signal?.aborted) break;
51
+ // Keep the read at the tick's instant: a wake that became due while an
52
+ // effect ran needs a zero-delay pass, not a whole cap's extra wait.
53
+ let at = await soonest(graph, now);
54
+ await sleep(Math.min(cap, Math.max(0, (at ?? Infinity) - clock.now())), opts.signal, clock);
55
+ }while (!opts.signal?.aborted)
56
+ };
57
+ //# sourceMappingURL=deno.js.map
package/deno.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deno.js","sources":["./deno.ts"],"names":[],"mappings":"AAAA;;;;;;;CAOC,GAED,SAAqB,KAAK,EAAE,MAAM,wBAA6B;AAC/D,SAAS,OAAO,mBAAkB;AAClC,SAAS,KAAK,qBAAoB;AAClC,SAAsB,IAAI,oBAAgC;AAmB1D;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,IAAI,OAAO,OAChB,OACA,OAAiB,CAAC,CAAC;EAEnB,IAAI,MAAM,KAAK,GAAG,IAAI;EACtB,IAAI,QAAQ,KAAK,KAAK,IAAI;EAC1B,IAAI,CAAC,OAAO,QAAQ,CAAC,QAAQ,OAAO,KAAK,MAAM,eAAe;IAC5D,MAAM,IAAI,WAAW;EACvB;EACA,mEAAmE;EACnE,4EAA4E;EAC5E,2DAA2D;EAC3D,GAAG;IACD,IAAI,MAAM,MAAM,GAAG;IACnB,IAAI,EAAE,OAAO,EAAE,GAAG,MAAM,MAAM,OAAO;IACrC,IAAI,SAAS,MAAM,KAAK,OAAO;IAC/B,MAAM,KAAK,MAAM,GAAG;MAAE,GAAG,MAAM;MAAE,SAAS;WAAI;WAAY,OAAO,OAAO;OAAC;IAAC;IAC1E,IAAI,KAAK,MAAM,EAAE,SAAS;IAC1B,uEAAuE;IACvE,oEAAoE;IACpE,IAAI,KAAK,MAAM,QAAQ,OAAO;IAC9B,MAAM,MACJ,KAAK,GAAG,CAAC,KAAK,KAAK,GAAG,CAAC,GAAG,CAAC,MAAM,QAAQ,IAAI,MAAM,GAAG,MACtD,KAAK,MAAM,EACX;EAEJ,QAAS,CAAC,KAAK,MAAM,EAAE,QAAQ;AACjC,EAAC"}
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts","./testing.ts"]},"name":"@yaks/wake","version":"0.2.36","license":"Apache-2.0","description":"Stores one-shot and recurring schedules as graph components, marking due wakes as fired and advancing their next scheduled times.","exports":{".":"./mod.ts","./cloudflare":"./cloudflare.ts","./deno":"./deno.ts","./vocab":"./vocab.ts","./graph":"./graph.ts","./tools":"./tools.ts","./service":"./service.ts","./run":"./run.ts"},"imports":{"@yaks/wake":"./mod.ts","@yaks/wake/cloudflare":"./cloudflare.ts","@yaks/wake/deno":"./deno.ts","@yaks/wake/vocab":"./vocab.ts","@yaks/wake/graph":"./graph.ts","@yaks/wake/tools":"./tools.ts","@yaks/wake/service":"./service.ts","@yaks/wake/run":"./run.ts"}}
package/deno.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * A long-running process can sleep until the next wake instead of polling at a
3
+ * fixed rate. The cap lets newly written wakes be noticed without a
4
+ * subscription, sleeping ones a write made hold among them, and keeps an empty
5
+ * graph and a far-off date within `setTimeout`'s range. Stopping aborts only
6
+ * the wait: a graph write already underway finishes its phases.
7
+ * @module
8
+ */
9
+
10
+ import { type Clock, sleep, system } from '@yaks/fp'
11
+ import { soonest } from './due.js'
12
+ import { rouse } from './while.js'
13
+ import { type Driver, tick, type Ticked } from './tick.js'
14
+
15
+ /** The loop's lifetime, its maximum sleep, and a callback run after each
16
+ * tick. */
17
+ export type LoopOpts = {
18
+ /** abort to stop the loop and release its timer */
19
+ signal?: AbortSignal
20
+ /** maximum sleep in milliseconds (default one minute); also the retry
21
+ * interval for wakes whose transaction was rejected, and the delay while the
22
+ * graph has nothing scheduled */
23
+ cap?: number
24
+ /** called after each tick with the fired and rejected wakes, a wake its
25
+ * `while` could not arm among the rejected */
26
+ onTick?: (result: Ticked) => void | Promise<void>
27
+ /** the time each tick is at, and the timer the loop sleeps on (default the
28
+ * runtime's) */
29
+ clock?: Clock
30
+ }
31
+
32
+ /**
33
+ * Rouse and tick immediately, then sleep until the next due instant or the
34
+ * cap, whichever is sooner. A wake whose transaction was rejected on one pass
35
+ * stays due for the next; effects run through the graph. Uses only web timers
36
+ * and `AbortSignal`, available in Deno and Node alike.
37
+ *
38
+ * The first tick happens whatever the signal's state, so one that has already
39
+ * aborted produces exactly one pass — which is how a short-lived process fires
40
+ * what is overdue as it starts up.
41
+ *
42
+ * ```ts
43
+ * import { loop } from '@yaks/wake/deno'
44
+ *
45
+ * let stop = new AbortController()
46
+ * // let running = loop(graph, { signal: stop.signal })
47
+ * // stop.abort()
48
+ * // await running
49
+ * ```
50
+ */
51
+ export let loop = async (
52
+ graph: Driver,
53
+ opts: LoopOpts = {},
54
+ ): Promise<void> => {
55
+ let cap = opts.cap ?? 60_000
56
+ let clock = opts.clock ?? system
57
+ if (!Number.isFinite(cap) || cap <= 0 || cap > 2_147_483_647) {
58
+ throw new RangeError('wake loop cap must be within setTimeout range')
59
+ }
60
+ // One pass first, always: a signal that is already aborted means a
61
+ // short-lived process — a one-off command run to fire whatever is overdue —
62
+ // and it still owes the graph the tick it was started for.
63
+ do {
64
+ let now = clock.now()
65
+ let { refused } = await rouse(graph, now)
66
+ let result = await tick(graph, now)
67
+ await opts.onTick?.({ ...result, refused: [...refused, ...result.refused] })
68
+ if (opts.signal?.aborted) break
69
+ // Keep the read at the tick's instant: a wake that became due while an
70
+ // effect ran needs a zero-delay pass, not a whole cap's extra wait.
71
+ let at = await soonest(graph, now)
72
+ await sleep(
73
+ Math.min(cap, Math.max(0, (at ?? Infinity) - clock.now())),
74
+ opts.signal,
75
+ clock,
76
+ )
77
+ } while (!opts.signal?.aborted)
78
+ }
package/due.js ADDED
@@ -0,0 +1,147 @@
1
+ // The whole scheduling rule, as two nearly pure functions over a graph. There
2
+ // is no timer here and no loop: this module computes which wakes are due and
3
+ // what firing one writes, and the program running it arranges to be called — a
4
+ // Deno tick, a Durable Object `alarm()`, a browser tab, a cron job hitting a
5
+ // route. Every one of them calls the same two functions, which is the point.
6
+ //
7
+ // The rule is one predicate: a wake is due when its `at` has passed. That is
8
+ // all, and it holds no matter how long the process was down, because `at` is a
9
+ // stored property and not a running process's memory of when to come back.
10
+ //
11
+ // Firing one moves that row forward, and how it moves is what separates a
12
+ // cadence from a one-shot:
13
+ //
14
+ // recurring `at` becomes the next instant, so it stops being due
15
+ // one-shot `at` is cleared, so it can never be due again
16
+ //
17
+ // Both write `fired`. Neither deletes anything: that a wake fired is worth
18
+ // keeping, and an application that wants it gone deletes the entity itself.
19
+ // Clearing `at` rather than deleting the entity also means a finished wake can
20
+ // be set again by writing a new `at` — the same alarm clock, wound back up.
21
+ //
22
+ // Nothing here reads a clock it was not given. `now` is a parameter everywhere,
23
+ // which is why the tests take microseconds, and why two processes reading the
24
+ // same graph at the same instant agree.
25
+ import { after } from "@yaks/fp";
26
+ import { line, sub } from "@yaks/query";
27
+ import { FIRED, WAKE, WATCH } from "./comp.js";
28
+ import { recur } from "./every.js";
29
+ let iso = (t)=>new Date(t).toISOString();
30
+ /** The wake a bundle carries, or `undefined`. */ export let wakeOf = (b)=>b[WAKE] ?? undefined;
31
+ /**
32
+ * The wakes due at `now`, oldest first — every entity whose `wake.at` has
33
+ * passed, with the query it watches where it watches one.
34
+ *
35
+ * This is the only read the package makes, and it is an ordinary query, so an
36
+ * application that would rather run its own (a narrower filter, a page at a
37
+ * time) can: `.wake.at<=now&?watch`, read at the instant.
38
+ *
39
+ * ```ts
40
+ * import { due, ring } from '@yaks/wake'
41
+ *
42
+ * let now = Date.now()
43
+ * // let owed = due(storage, now)
44
+ * // for (let w of owed) graph.apply([ring(w, now)])
45
+ * ```
46
+ *
47
+ * It follows @yaks/graph's synchronous pass-through: over a synchronous storage
48
+ * it returns the bundles, and over an asynchronous one a promise for them.
49
+ */ export let due = (storage, now = Date.now())=>storage.read(line`${sub(owed)}&.order=${WAKE}.at`, {
50
+ now
51
+ });
52
+ /** The query clauses a due wake matches, with what it watches: read with the
53
+ * instant as the read's `now`. The instant is the clock a statement binds, not
54
+ * a word of the query, so every read of it is one statement (@yaks/sql
55
+ * `compile`). */ export let owed = line`.${WAKE}.at<=now&?${WATCH}`;
56
+ /**
57
+ * The next ISO instant after `now`, computed from a recurrence string or from a
58
+ * wake — `null` for a one-shot, or for a recurrence this package cannot parse.
59
+ * Given a string, a duration is counted from `now`; given a wake, the cadence
60
+ * keeps its original phase.
61
+ *
62
+ * A duration is counted from the wake's own `at`, so a cadence keeps its phase;
63
+ * a cron line is evaluated against the calendar. See
64
+ * {@link https://jsr.io/@yaks/wake/doc/~/recur | recur}.
65
+ *
66
+ * A fixed duration counts from the supplied instant:
67
+ *
68
+ * ```ts
69
+ * import { assertEquals } from '@std/assert'
70
+ * import { next } from '@yaks/wake'
71
+ *
72
+ * let from = Date.parse('2026-01-01T09:00:00Z')
73
+ * assertEquals(next('1d', from), '2026-01-02T09:00:00.000Z')
74
+ * ```
75
+ *
76
+ * A cron line reads its named calendar:
77
+ *
78
+ * ```ts
79
+ * import { assertEquals } from '@std/assert'
80
+ * import { next } from '@yaks/wake'
81
+ *
82
+ * let from = Date.parse('2026-01-01T09:00:00Z')
83
+ * assertEquals(next('@daily', from, 'America/Detroit'), '2026-01-02T05:00:00.000Z')
84
+ * ```
85
+ *
86
+ * A one-shot has no next instant:
87
+ *
88
+ * ```ts
89
+ * import { assertEquals } from '@std/assert'
90
+ * import { next } from '@yaks/wake'
91
+ *
92
+ * let from = Date.parse('2026-01-01T09:00:00Z')
93
+ * assertEquals(next({ at: '2026-01-01T09:00:00Z' }, from), null)
94
+ * ```
95
+ */ export let next = (wake, now = Date.now(), clock = {})=>{
96
+ let tz = typeof clock == 'string' ? clock : clock.tz;
97
+ if (typeof wake == 'string') {
98
+ let at = recur(wake, now, now, tz);
99
+ return at == null ? null : iso(at);
100
+ }
101
+ if (!wake.every || !wake.at) return null;
102
+ let from = Date.parse(wake.at);
103
+ if (Number.isNaN(from)) return null;
104
+ let at = recur(wake.every, from, now, tz);
105
+ return at == null ? null : iso(at);
106
+ };
107
+ /**
108
+ * The patch that fires a due wake: the `fired` value, plus its `at` moved on to
109
+ * the next instant — or cleared, when there is no next one. `every` is the
110
+ * cadence it goes on at, its own by default; `tick` passes the one its
111
+ * `while` chose.
112
+ *
113
+ * It returns a bundle rather than applying it. `tick` applies one such bundle
114
+ * per wake, and the graph's rules react to that write in their own phases.
115
+ *
116
+ * ```ts
117
+ * // let owed = due(storage, now)
118
+ * // for (let w of owed) graph.apply([ring(w, now)])
119
+ * ```
120
+ */ export let ring = (b, now = Date.now(), clock = {}, every = wakeOf(b)?.every)=>({
121
+ entity: b.entity,
122
+ [WAKE]: {
123
+ at: next({
124
+ ...wakeOf(b),
125
+ every
126
+ }, now, clock)
127
+ },
128
+ [FIRED]: {
129
+ at: iso(now)
130
+ }
131
+ });
132
+ /**
133
+ * The instant the scheduler should next run — the earliest `at` still in the
134
+ * future, or `null` when nothing is pending. This is what a Durable Object
135
+ * passes to `setAlarm()`, and what a server passes to `setTimeout`.
136
+ *
137
+ * An application may equally ignore this and poll on a fixed cadence; it is
138
+ * here so that one able to sleep until an exact instant does not have to poll.
139
+ */ export let soonest = (storage, now = Date.now())=>after(storage.read(line`.${WAKE}.at>now&.order=${WAKE}.at&.limit=1`, {
140
+ now
141
+ }), ([b])=>{
142
+ let at = wakeOf(b ?? {
143
+ entity: {}
144
+ })?.at;
145
+ return at ? Date.parse(at) : null;
146
+ });
147
+ //# sourceMappingURL=due.js.map
package/due.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"due.js","sources":["./due.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,6EAA6E;AAC7E,+EAA+E;AAC/E,6EAA6E;AAC7E,6EAA6E;AAC7E,EAAE;AACF,6EAA6E;AAC7E,+EAA+E;AAC/E,2EAA2E;AAC3E,EAAE;AACF,0EAA0E;AAC1E,2BAA2B;AAC3B,EAAE;AACF,qEAAqE;AACrE,8DAA8D;AAC9D,EAAE;AACF,2EAA2E;AAC3E,4EAA4E;AAC5E,+EAA+E;AAC/E,4EAA4E;AAC5E,EAAE;AACF,gFAAgF;AAChF,8EAA8E;AAC9E,wCAAwC;AAGxC,SAAS,KAAK,wBAA6B;AAC3C,SAAqB,IAAI,EAAE,GAAG,2BAAgC;AAC9D,SAAS,KAAK,EAAE,IAAI,EAAa,KAAK,oBAAmB;AACzD,SAAS,KAAK,qBAAoB;AAQlC,IAAI,MAAM,CAAC,IAAsB,IAAI,KAAK,GAAG,WAAW;AAOxD,+CAA+C,GAC/C,OAAO,IAAI,SAAS,CAAC,IAClB,CAAC,CAAC,KAAK,IAAI,UAA8B;AAE5C;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,IAAI,MAAM,CACf,SACA,MAAc,KAAK,GAAG,EAAE,GAExB,QAAQ,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,MAAM,QAAQ,EAAE,KAAK,GAAG,CAAC,EAAE;IAAE;EAAI,GAAE;AAE7D;;;eAGe,GACf,OAAO,IAAI,OAAc,IAAI,CAAC,CAAC,EAAE,KAAK,UAAU,EAAE,MAAM,CAAC,CAAA;AAEzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GACD,OAAO,IAAI,OAAO,CAChB,MACA,MAAc,KAAK,GAAG,EAAE,EACxB,QAAwB,CAAC,CAAC;EAE1B,IAAI,KAAK,OAAO,SAAS,WAAW,QAAQ,MAAM,EAAE;EACpD,IAAI,OAAO,QAAQ,UAAU;IAC3B,IAAI,KAAK,MAAM,MAAM,KAAK,KAAK;IAC/B,OAAO,MAAM,OAAO,OAAO,IAAI;EACjC;EACA,IAAI,CAAC,KAAK,KAAK,IAAI,CAAC,KAAK,EAAE,EAAE,OAAO;EACpC,IAAI,OAAO,KAAK,KAAK,CAAC,KAAK,EAAE;EAC7B,IAAI,OAAO,KAAK,CAAC,OAAO,OAAO;EAC/B,IAAI,KAAK,MAAM,KAAK,KAAK,EAAE,MAAM,KAAK;EACtC,OAAO,MAAM,OAAO,OAAO,IAAI;AACjC,EAAC;AAED;;;;;;;;;;;;;CAaC,GACD,OAAO,IAAI,OAAO,CAChB,GACA,MAAc,KAAK,GAAG,EAAE,EACxB,QAAe,CAAC,CAAC,EACjB,QAAmC,OAAO,IAAI,KAAK,GACxC,CAAC;IACZ,QAAQ,EAAE,MAAM;IAChB,CAAC,KAAK,EAAE;MAAE,IAAI,KAAK;QAAE,GAAG,OAAO,EAAE;QAAE;MAAM,GAAG,KAAK;IAAO;IACxD,CAAC,MAAM,EAAE;MAAE,IAAI,IAAI;IAAK;EAC1B,CAAC,EAAC;AAEF;;;;;;;CAOC,GACD,OAAO,IAAI,UAAU,CACnB,SACA,MAAc,KAAK,GAAG,EAAE,GAExB,MACE,QAAQ,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,eAAe,EAAE,KAAK,YAAY,CAAC,EAAE;IAAE;EAAI,IACrE,CAAC,CAAC,EAAE;IACF,IAAI,KAAK,OAAO,KAAK;MAAE,QAAQ,CAAC;IAAY,IAAI;IAChD,OAAO,KAAK,KAAK,KAAK,CAAC,MAAM;EAC/B,GACD"}