@niwa-labs/timer 0.0.0-stage → 0.0.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/LICENSE +21 -0
- package/README.md +2 -2
- package/package.json +35 -4
- package/src/cockpit/index.tsx +182 -0
- package/src/index.ts +970 -0
- package/src/records.ts +149 -0
- package/test/clock.test.ts +178 -0
- package/test/declarations.test.ts +66 -0
- package/test/firing-writes.test.ts +60 -0
- package/test/fixtures/failing-writes.ts +31 -0
- package/test/fixtures/missed-dues-host.ts +73 -0
- package/test/missed-dues.test.ts +127 -0
- package/test/schedule-state.test.ts +115 -0
- package/test/sleep-writes.test.ts +147 -0
- package/test/timer-list.test.ts +114 -0
- package/test/timer-sleep.test.ts +359 -0
- package/test/trigger.test.ts +57 -0
- package/tsconfig.json +15 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,970 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The timer module: wake at a moment or with a period.
|
|
3
|
+
*
|
|
4
|
+
* A timer is a declaration, not a thread. `timer.every(60000)` and `timer.at(date)` say when
|
|
5
|
+
* something should happen; the module turns that into records. A firing is an external input:
|
|
6
|
+
* it starts its own chain, and the root of that chain is the firing itself.
|
|
7
|
+
*
|
|
8
|
+
* **A trigger is a filter over the firing type.** `timer.fired("daily-digest")` is not a new
|
|
9
|
+
* record type: it is "timer.fired" narrowed to the firings of one timer (`{ timer: "daily-digest" }`).
|
|
10
|
+
* A handler of a trigger is woken by exactly those firings and by no others, so two plugins can
|
|
11
|
+
* watch two timers of the same host without seeing each other's. A trigger made with a schedule
|
|
12
|
+
* (`timer.daily("21:00")`) carries it: the plugin whose handler subscribes to it offers the timer, so
|
|
13
|
+
* subscribing is all it takes for the timer to be scheduled.
|
|
14
|
+
*
|
|
15
|
+
* **A firing is written once.** The id of a firing is `fire-<hash>` in the common id format, the
|
|
16
|
+
* hash of the timer and the moment it was due, never of the moment it was written. The same due
|
|
17
|
+
* time always has the same id, so a firing written twice (a host that restarted, a tick that
|
|
18
|
+
* overlapped) is the same record and not a second fact. A deterministic id makes a repeated write
|
|
19
|
+
* harmless.
|
|
20
|
+
*
|
|
21
|
+
* **What happens when the host was down.** Every timer says what to do with the dues it missed
|
|
22
|
+
* while the host was not running:
|
|
23
|
+
*
|
|
24
|
+
* - `"once"` (the default): after the host starts, the timer fires exactly once for all the
|
|
25
|
+
* dues it missed, and the schedule continues from that firing: a schedule holds one next due, and it
|
|
26
|
+
* is recomputed from the moment of the firing, so the missed slots collapse into one firing instead
|
|
27
|
+
* of being replayed.
|
|
28
|
+
* - `"skip"`: the missed dues are gone. The timer fires the next time it is due, and nothing is
|
|
29
|
+
* said about what was missed.
|
|
30
|
+
*
|
|
31
|
+
* Both rules say "once" in the sense that matters: a due time produces at most one firing, and a
|
|
32
|
+
* timer that was down for an hour does not wake up an hour later with an hour of firings queued
|
|
33
|
+
* behind it.
|
|
34
|
+
*
|
|
35
|
+
* The next due of every timer is kept in the state of the plugin, so the host knows after a
|
|
36
|
+
* restart which dues it missed.
|
|
37
|
+
*
|
|
38
|
+
* **A sleep is a wait, and a wait is durable.** `sleep(ms)` inside a handler says when the code
|
|
39
|
+
* may go on: the moment is read through the clock of the host, the wait is a step of the
|
|
40
|
+
* invocation, and the wake that ends it is a record in the journal. A host that is restarted in
|
|
41
|
+
* the middle of a sleep finds the handler waiting, and it wakes once — at the moment that was
|
|
42
|
+
* asked for, or at once when the moment passed while the host was down.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
import {
|
|
46
|
+
DeniedError,
|
|
47
|
+
EntityDescription,
|
|
48
|
+
IdIndex,
|
|
49
|
+
IntegrityError,
|
|
50
|
+
UnknownId,
|
|
51
|
+
action,
|
|
52
|
+
actionRef,
|
|
53
|
+
currentInvocation,
|
|
54
|
+
idSchema,
|
|
55
|
+
recordId,
|
|
56
|
+
seq,
|
|
57
|
+
shortInvocation,
|
|
58
|
+
shortRun,
|
|
59
|
+
stableJson,
|
|
60
|
+
timestamp,
|
|
61
|
+
} from "@niwa-labs/core";
|
|
62
|
+
import type {
|
|
63
|
+
Id,
|
|
64
|
+
InvocationScope,
|
|
65
|
+
JournalReader,
|
|
66
|
+
RecordId,
|
|
67
|
+
RecordType,
|
|
68
|
+
Step,
|
|
69
|
+
StoredRecord,
|
|
70
|
+
Timestamp,
|
|
71
|
+
} from "@niwa-labs/core";
|
|
72
|
+
import { fileURLToPath } from "node:url";
|
|
73
|
+
import { COCKPIT_MODULE, TIMER_OFFER, plugin, trigger } from "@niwa-labs/plugin";
|
|
74
|
+
import type { MissedRule, Plugin, ServiceContext, StateHandle, TimerDef, TimerOffer, Trigger } from "@niwa-labs/plugin";
|
|
75
|
+
import { z } from "zod";
|
|
76
|
+
|
|
77
|
+
import { SleepRequested, TimerFired, TimerId, TimerSlept, clockOf, readSleepKey, sleepKey, timerFiredQuery, timerId, timerSleepRequest } from "./records.ts";
|
|
78
|
+
import type {
|
|
79
|
+
SleepKey,
|
|
80
|
+
SleepRequestedData,
|
|
81
|
+
TimerFiredData,
|
|
82
|
+
TimerSleptData,
|
|
83
|
+
} from "./records.ts";
|
|
84
|
+
|
|
85
|
+
export { SleepRequested, TimerFired, TimerId, TimerSlept, clockOf, readSleepKey, sleepKey, timerFiredQuery, timerId, timerSleepRequest } from "./records.ts";
|
|
86
|
+
export type {
|
|
87
|
+
SleepKey,
|
|
88
|
+
SleepRequestedData,
|
|
89
|
+
TimerFiredData,
|
|
90
|
+
TimerSleptData,
|
|
91
|
+
};
|
|
92
|
+
// The definition of a timer and the point plugins offer one at (`TIMER_OFFER`) are the plugin layer's: a plugin that
|
|
93
|
+
// needs a timer offers it without importing this module.
|
|
94
|
+
export type { MissedRule, TimerDef };
|
|
95
|
+
|
|
96
|
+
/** How long a write that failed waits before it is tried again. */
|
|
97
|
+
const RETRY_MS = 1000;
|
|
98
|
+
|
|
99
|
+
/** The rule a timer uses when it says nothing: one firing for all the missed dues. */
|
|
100
|
+
export const DEFAULT_MISSED: MissedRule = "once";
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* A trigger: the firings of one timer.
|
|
104
|
+
*
|
|
105
|
+
* It is the type "timer.fired" with the filter `{ timer }`. A handler registered for it is woken by
|
|
106
|
+
* the firings of that timer and by no others, and the timers plugin is named as the one that writes them.
|
|
107
|
+
*/
|
|
108
|
+
export interface TimerTrigger extends Trigger<TimerFiredData> {
|
|
109
|
+
/** The id of the timer this trigger watches. */
|
|
110
|
+
readonly timer: TimerId;
|
|
111
|
+
/** The schedule of the timer, when the trigger declares one. */
|
|
112
|
+
readonly def?: TimerDef;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* A trigger that carries the schedule of its timer: what `every`, `at` and `daily` make. A plugin
|
|
117
|
+
* that subscribes to it offers the timer (`TIMER_OFFER`), so the timers plugin schedules it.
|
|
118
|
+
*/
|
|
119
|
+
export interface ScheduledTimerTrigger extends TimerTrigger {
|
|
120
|
+
readonly def: TimerDef;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The trigger of one timer: the firings of that timer, as a type a handler can be written for.
|
|
125
|
+
*
|
|
126
|
+
* The trigger carries the type it narrows, so a handler of it is named after the type by
|
|
127
|
+
* default — but two triggers of two timers are two handlers, so each carries its own name.
|
|
128
|
+
*/
|
|
129
|
+
export function timerFired(id: string): TimerTrigger {
|
|
130
|
+
return triggerOf(timerId(id), undefined);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** What a timer's author may add to the schedule: the id the timer is named by, and a description of it. */
|
|
134
|
+
export interface TimerOptions {
|
|
135
|
+
readonly id?: string;
|
|
136
|
+
readonly description?: string;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The trigger of a timer that fires every period.
|
|
141
|
+
*
|
|
142
|
+
* The id of the timer is the period by default: `every:60000`. Two timers with the same period
|
|
143
|
+
* are the same timer, so a second one needs an id of its own.
|
|
144
|
+
*/
|
|
145
|
+
export function every(ms: number, options: TimerOptions = {}): ScheduledTimerTrigger {
|
|
146
|
+
requirePeriod(ms);
|
|
147
|
+
const key = timerId(options.id ?? `every:${ms}`);
|
|
148
|
+
return triggerOf(key, { id: key, every: ms, ...describedBy(options) });
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* The trigger of a timer that fires once, at a moment.
|
|
153
|
+
*
|
|
154
|
+
* The id of the timer is the moment by default: `at:1735689600000`.
|
|
155
|
+
*/
|
|
156
|
+
export function at(moment: number | Date, options: TimerOptions = {}): ScheduledTimerTrigger {
|
|
157
|
+
const due = timestamp(moment instanceof Date ? moment.getTime() : moment);
|
|
158
|
+
const key = timerId(options.id ?? `at:${due}`);
|
|
159
|
+
return triggerOf(key, { id: key, at: due, ...describedBy(options) });
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The trigger of a timer that fires every day at a time of day, "HH:MM" in local time.
|
|
164
|
+
*
|
|
165
|
+
* The id of the timer is the time by default: `daily:21:00`.
|
|
166
|
+
*/
|
|
167
|
+
export function daily(time: string, options: TimerOptions = {}): ScheduledTimerTrigger {
|
|
168
|
+
const clock = parseTimeOfDay(time);
|
|
169
|
+
const key = timerId(options.id ?? `daily:${clock}`);
|
|
170
|
+
return triggerOf(key, { id: key, daily: clock, ...describedBy(options) });
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The description a timer's options carry, as the part of a definition it is. */
|
|
174
|
+
function describedBy(options: TimerOptions): { readonly description?: string } {
|
|
175
|
+
return options.description === undefined ? {} : { description: options.description };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** A trigger over one timer, with the schedule it declares and the offer of it. */
|
|
179
|
+
function triggerOf(id: TimerId, def: TimerDef): ScheduledTimerTrigger;
|
|
180
|
+
function triggerOf(id: TimerId, def: undefined): TimerTrigger;
|
|
181
|
+
function triggerOf(id: TimerId, def: TimerDef | undefined): TimerTrigger {
|
|
182
|
+
const base = trigger(TimerFired, {
|
|
183
|
+
name: `timer.fired:${id}`,
|
|
184
|
+
filter: timerFiredQuery(id).filter ?? {},
|
|
185
|
+
provider: "timers",
|
|
186
|
+
...(def === undefined ? {} : { offer: { key: TIMER_OFFER, value: def } }),
|
|
187
|
+
});
|
|
188
|
+
return { ...base, timer: id, ...(def === undefined ? {} : { def }) };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** The id of a firing: `fire-<hash>`. */
|
|
192
|
+
export type FiringId = Id<"firing">;
|
|
193
|
+
|
|
194
|
+
/** What a firing is born from: the timer and the moment it was due. */
|
|
195
|
+
function firingSeed(timer: string, due: number): RecordId {
|
|
196
|
+
return recordId(`timer:${timer}:${due}`);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The id of the firing of one timer at one due: `fire-<hash of the timer and the due>`.
|
|
201
|
+
*
|
|
202
|
+
* It is a function of the timer and the moment it was due, so the same firing written twice is
|
|
203
|
+
* the same record. The host writes it with this id, and the journal keeps one record per id.
|
|
204
|
+
*/
|
|
205
|
+
export function firingId(ids: IdIndex<"firing">, timer: TimerId, due: Timestamp): FiringId {
|
|
206
|
+
return ids.issue(firingSeed(timer, due));
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The id of the wake of one sleep: `timer:slept:${key}`.
|
|
211
|
+
*
|
|
212
|
+
* It is a function of the sleeping place, so a wake written twice is the same record: a host that
|
|
213
|
+
* restarts and finds the sleep still waiting writes the same wake, not a second one.
|
|
214
|
+
*/
|
|
215
|
+
export function sleptId(key: SleepKey): RecordId {
|
|
216
|
+
return recordId(`timer:slept:${key}`);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* The timers of niwa, as one name.
|
|
221
|
+
*
|
|
222
|
+
* `timer.daily("21:00")`, `timer.every(60000)` and `timer.at(date)` are the triggers a handler
|
|
223
|
+
* can be written for; `timer.fired(id)` is the trigger of a timer that was declared elsewhere.
|
|
224
|
+
*/
|
|
225
|
+
export const timer = {
|
|
226
|
+
/** A timer that fires once, at a moment. */
|
|
227
|
+
at,
|
|
228
|
+
/** A timer that fires every day at a time of day, "HH:MM" in local time. */
|
|
229
|
+
daily,
|
|
230
|
+
/** A timer that fires every period. */
|
|
231
|
+
every,
|
|
232
|
+
/** The firings of one timer, as a type a handler can be written for. */
|
|
233
|
+
fired: timerFired,
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* The key of one sleep: the invocation and the sleeping place.
|
|
238
|
+
*
|
|
239
|
+
* It is a function of the two, so the same sleeping place always has the same key, and two
|
|
240
|
+
* sleeping places of one invocation never have the same one.
|
|
241
|
+
*/
|
|
242
|
+
function sleepKeyOf(scope: InvocationScope, place: string): SleepKey {
|
|
243
|
+
return sleepKey(`${scope.invocation}:${place}`);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* How many sleeps one run of one invocation has asked for.
|
|
248
|
+
*
|
|
249
|
+
* It is the number of the sleeping place: a handler that sleeps twice has two places, and the
|
|
250
|
+
* wake of one is not the answer of the other. The count belongs to the run, so a replay of the
|
|
251
|
+
* handler reaches the same places again.
|
|
252
|
+
*/
|
|
253
|
+
const sleepsOf = new WeakMap<InvocationScope, number>();
|
|
254
|
+
|
|
255
|
+
/** The sleeping places one invocation has used, so a place is never slept at twice. */
|
|
256
|
+
const placesOf = new WeakMap<InvocationScope, Set<string>>();
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Sleep for `ms` milliseconds, and go on when the time has come.
|
|
260
|
+
*
|
|
261
|
+
* A sleep is a step, like a call: the moment is read through the clock of the host, so the code
|
|
262
|
+
* between the steps is reproducible, and the wait survives a restart. A host that was down while
|
|
263
|
+
* the sleep was running wakes the handler once — at the moment that was asked for, or at once when
|
|
264
|
+
* that moment passed while the host was down.
|
|
265
|
+
*
|
|
266
|
+
* The `key` names the sleeping place. One sleeping place is one sleep: a handler that sleeps
|
|
267
|
+
* twice may give the two sleeps two keys; without one, the sleeps are told apart by their
|
|
268
|
+
* number.
|
|
269
|
+
*
|
|
270
|
+
* @throws when the sleep is asked for outside an invocation: there is nothing to wait with, or
|
|
271
|
+
* when the key was used by an earlier sleep of the same invocation: the wake of a place comes once.
|
|
272
|
+
*/
|
|
273
|
+
export async function sleep(step: Step, ms: number, key?: string): Promise<void> {
|
|
274
|
+
if (!Number.isFinite(ms) || ms < 0) {
|
|
275
|
+
throw new TypeError(`a sleep must be a non-negative number of milliseconds, got ${String(ms)}`);
|
|
276
|
+
}
|
|
277
|
+
const scope = currentInvocation();
|
|
278
|
+
if (scope === undefined) {
|
|
279
|
+
throw new Error("a sleep is a step of an invocation: it cannot be made outside one");
|
|
280
|
+
}
|
|
281
|
+
const number = (sleepsOf.get(scope) ?? 0) + 1;
|
|
282
|
+
const waitKey = `timer.sleep-${number}`;
|
|
283
|
+
const named = key ?? waitKey;
|
|
284
|
+
const places = placesOf.get(scope) ?? new Set<string>();
|
|
285
|
+
if (places.has(named)) {
|
|
286
|
+
throw new Error(`the sleeping place "${named}" was slept at already in this invocation: a place is woken once, so a second sleep needs a key of its own`);
|
|
287
|
+
}
|
|
288
|
+
const place = sleepKeyOf(scope, named);
|
|
289
|
+
places.add(named);
|
|
290
|
+
placesOf.set(scope, places);
|
|
291
|
+
sleepsOf.set(scope, number);
|
|
292
|
+
const at = (await step.now()) + ms;
|
|
293
|
+
// The wait is begun before the request is written. The wake of a sleep can only be written
|
|
294
|
+
// after the request is, and a wait looks for the records that came after it began: a wait
|
|
295
|
+
// that began after the request could miss a wake that was written in between, and the handler
|
|
296
|
+
// would wait for ever.
|
|
297
|
+
const waiting = step.wait(TimerSlept, { filter: { key: place }, key: waitKey });
|
|
298
|
+
// The wait refuses when no wake has come, and the refusal is the suspension of the invocation.
|
|
299
|
+
// It is caught here, so the request can be written, and it is raised again below.
|
|
300
|
+
const settled = waiting.then(
|
|
301
|
+
(value) => ({ refused: false as const, value }),
|
|
302
|
+
(error: unknown) => ({ refused: true as const, error }),
|
|
303
|
+
);
|
|
304
|
+
await step(timerSleepRequest, { at, key: place }, { key: `timer.sleep-emit-${number}` });
|
|
305
|
+
const outcome = await settled;
|
|
306
|
+
if (outcome.refused) throw outcome.error;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* What a handler that sleeps needs the host to have: the timers plugin declares the two records
|
|
311
|
+
* of a sleep. A handler that calls `sleep` names them in `requires`, so a host without the timers
|
|
312
|
+
* refuses to serve instead of failing the handler (or waiting for ever) when a sleep is asked for.
|
|
313
|
+
*/
|
|
314
|
+
export const SLEEP_NEEDS: readonly RecordType<any>[] = [
|
|
315
|
+
{ ...SleepRequested, provider: "timers" },
|
|
316
|
+
{ ...TimerSlept, provider: "timers" },
|
|
317
|
+
];
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* What the plugin remembers about one timer: when it is due, and whether it is done.
|
|
321
|
+
*
|
|
322
|
+
* `schedule` is the schedule the due was computed for: a timer that is declared again with
|
|
323
|
+
* another schedule under the same id does not inherit the due of the old one.
|
|
324
|
+
*/
|
|
325
|
+
interface ScheduleEntry {
|
|
326
|
+
readonly id: string;
|
|
327
|
+
/** The next moment the timer is due, in milliseconds since the epoch. */
|
|
328
|
+
readonly due: number;
|
|
329
|
+
/** True when the timer has fired and will not fire again. */
|
|
330
|
+
readonly done: boolean;
|
|
331
|
+
/** The schedule the due belongs to, as `scheduleKey` writes it. */
|
|
332
|
+
readonly schedule: string;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* The schedule of every timer of the plugin: a list, not an object keyed by the id, because every
|
|
337
|
+
* valid id is a name an object treats specially (`constructor`, `__proto__`).
|
|
338
|
+
*/
|
|
339
|
+
type Schedule = ScheduleEntry[];
|
|
340
|
+
|
|
341
|
+
/** The remembered schedule by the id of the timer. */
|
|
342
|
+
function savedBy(memory: StateHandle<Schedule>): Map<string, ScheduleEntry> {
|
|
343
|
+
return new Map(memory.get().map((entry) => [entry.id, entry]));
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** The schedule of a definition as text, to tell whether a remembered due still belongs to it. */
|
|
347
|
+
function scheduleKey(def: TimerDef): string {
|
|
348
|
+
return stableJson(scheduleOf(def));
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** One timer, as the scheduler keeps it. */
|
|
352
|
+
interface Scheduled {
|
|
353
|
+
readonly id: TimerId;
|
|
354
|
+
readonly def: TimerDef;
|
|
355
|
+
readonly description: EntityDescription;
|
|
356
|
+
readonly missed: MissedRule;
|
|
357
|
+
/** The next moment the timer is due. Meaningless once the timer is done. */
|
|
358
|
+
due: Timestamp;
|
|
359
|
+
/** True when the timer has fired and will not fire again. */
|
|
360
|
+
done: boolean;
|
|
361
|
+
/** True while the firing of the due is being written. */
|
|
362
|
+
firing: boolean;
|
|
363
|
+
/** A failed write is not tried again before this moment. */
|
|
364
|
+
retryAt: number;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* The timers of one host, as a plugin.
|
|
369
|
+
*
|
|
370
|
+
* The plugin declares the firing type and runs one service: the scheduler. The service starts
|
|
371
|
+
* when the host starts serving and stops when it closes or the plugin is unloaded.
|
|
372
|
+
*
|
|
373
|
+
* The timers are given as plain definitions or as the triggers that declare them; a trigger
|
|
374
|
+
* carries its schedule with it.
|
|
375
|
+
*/
|
|
376
|
+
export function timers(defs: readonly (TimerDef | ScheduledTimerTrigger)[]): Plugin {
|
|
377
|
+
const listed = defs.map((def) => build(defOf(def)));
|
|
378
|
+
const ids = new Set<TimerId>();
|
|
379
|
+
for (const { id } of listed) {
|
|
380
|
+
if (ids.has(id)) throw new Error(`two timers have the id "${id}": a timer id must name one timer`);
|
|
381
|
+
ids.add(id);
|
|
382
|
+
}
|
|
383
|
+
return plugin("timers", (api) => {
|
|
384
|
+
api.offer(COCKPIT_MODULE, { id: "timers", entry: fileURLToPath(new URL("./cockpit/index.tsx", import.meta.url)) });
|
|
385
|
+
api.declare(TimerFired, SleepRequested, TimerSlept);
|
|
386
|
+
/**
|
|
387
|
+
* The timers of the host: the listed ones, then the ones the plugins offer (`TIMER_OFFER`). A listed
|
|
388
|
+
* timer wins over an offered one of the same id: the owner's list is how a plugin's schedule is changed.
|
|
389
|
+
* Read when the host serves, so the plugins that offer may be installed in any order.
|
|
390
|
+
*/
|
|
391
|
+
let known: Scheduled[] | undefined;
|
|
392
|
+
const scheduleOfHost = (): Scheduled[] => {
|
|
393
|
+
if (known !== undefined) return known;
|
|
394
|
+
const all = [...listed];
|
|
395
|
+
for (const { plugin: offeredBy, value } of api.offers(TIMER_OFFER)) {
|
|
396
|
+
const entry = build(defOf(value));
|
|
397
|
+
const same = all.find((one) => one.id === entry.id);
|
|
398
|
+
if (same === undefined) all.push(entry);
|
|
399
|
+
else if (stableJson(same.def) !== stableJson(entry.def)) {
|
|
400
|
+
console.error(`niwa: the timer "${entry.id}" that "${offeredBy}" offers is also listed, with another schedule: the listed one is used`);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
known = all;
|
|
404
|
+
return all;
|
|
405
|
+
};
|
|
406
|
+
const memory = api.state<Schedule>("schedule", ScheduleSchema, []);
|
|
407
|
+
/** The ids of the firings the journal holds, so a firing asked for again gets the id it has. */
|
|
408
|
+
const ledger = new FiringLedger(() => api.journal?.());
|
|
409
|
+
const firingIds = new IdIndex("firing", () => ledger.issued());
|
|
410
|
+
/**
|
|
411
|
+
* The sleeps that are asked for while the host serves, by the key of the sleeping place.
|
|
412
|
+
*
|
|
413
|
+
* It is set when the service starts: a sleep asked for before the service is up is found by
|
|
414
|
+
* the scan the service makes when it starts.
|
|
415
|
+
*/
|
|
416
|
+
let askSleep: ((data: SleepRequestedData) => void) | undefined;
|
|
417
|
+
api.service((ctx) => {
|
|
418
|
+
const journal = api.journal?.();
|
|
419
|
+
let stopped = false;
|
|
420
|
+
const saved = savedBy(memory);
|
|
421
|
+
const running: Scheduled[] = scheduleOfHost().map((entry) => {
|
|
422
|
+
const kept = saved.get(entry.id);
|
|
423
|
+
const state =
|
|
424
|
+
kept === undefined || kept.schedule !== scheduleKey(entry.def)
|
|
425
|
+
? { due: firstDue(entry, ctx.now()), done: false }
|
|
426
|
+
: settle(entry, kept, journal, firingIds);
|
|
427
|
+
return { ...entry, due: timestamp(state.due), done: state.done };
|
|
428
|
+
});
|
|
429
|
+
// The sleeps that are over, by the key of the sleeping place, and the wakes that are
|
|
430
|
+
// armed for the ones that are not.
|
|
431
|
+
const ended = new Set<SleepKey>();
|
|
432
|
+
// The wakes whose record is being written: not over until the write is confirmed.
|
|
433
|
+
const writing = new Set<SleepKey>();
|
|
434
|
+
const wakes = new Map<SleepKey, () => void>();
|
|
435
|
+
/**
|
|
436
|
+
* End one sleep: the wake is written for the sleeping place, and the handler that waits
|
|
437
|
+
* for it goes on.
|
|
438
|
+
*
|
|
439
|
+
* A wake that was written before is not written again: the id is a function of the
|
|
440
|
+
* sleeping place, so a host that restarts and finds the sleep still waiting writes the
|
|
441
|
+
* same record. The sleep is over only when the write is confirmed: a write that failed is
|
|
442
|
+
* tried again after a delay, so the handler is not left asleep.
|
|
443
|
+
*/
|
|
444
|
+
const wake = async (key: SleepKey): Promise<void> => {
|
|
445
|
+
if (stopped || ended.has(key) || writing.has(key)) return;
|
|
446
|
+
writing.add(key);
|
|
447
|
+
try {
|
|
448
|
+
await ctx.emit(TimerSlept, { key }, { id: sleptId(key) });
|
|
449
|
+
ended.add(key);
|
|
450
|
+
} catch (error) {
|
|
451
|
+
// Written in the meantime: the sleep is over.
|
|
452
|
+
if (error instanceof IntegrityError) {
|
|
453
|
+
ended.add(key);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
if (stopped) return;
|
|
457
|
+
console.error(
|
|
458
|
+
`niwa: the sleep "${key}" could not be woken, it is tried again: ${
|
|
459
|
+
error instanceof Error ? error.message : String(error)
|
|
460
|
+
}`,
|
|
461
|
+
);
|
|
462
|
+
armSleep(key, ctx.now() + RETRY_MS);
|
|
463
|
+
} finally {
|
|
464
|
+
writing.delete(key);
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
/**
|
|
468
|
+
* Arm the wake of one sleep: the clock of the host carries it.
|
|
469
|
+
*
|
|
470
|
+
* A moment that has passed is fired at once: the sleep is over, and the handler that
|
|
471
|
+
* waits for it goes on now.
|
|
472
|
+
*/
|
|
473
|
+
const armSleep = (key: SleepKey, at: number): void => {
|
|
474
|
+
wakes.get(key)?.();
|
|
475
|
+
wakes.delete(key);
|
|
476
|
+
if (at <= ctx.now()) {
|
|
477
|
+
void wake(key);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
// The promise is returned, so a clock that is moved by hand waits for the wake to be
|
|
481
|
+
// written instead of running past it.
|
|
482
|
+
const cancel = ctx.schedule(at, () => {
|
|
483
|
+
wakes.delete(key);
|
|
484
|
+
return wake(key);
|
|
485
|
+
});
|
|
486
|
+
wakes.set(key, cancel);
|
|
487
|
+
};
|
|
488
|
+
/**
|
|
489
|
+
* A sleep that is asked for: it is armed, unless it is over already.
|
|
490
|
+
*
|
|
491
|
+
* The wake of a sleep that was asked for twice is armed once: the key is the sleeping
|
|
492
|
+
* place, so the second request is the same sleep.
|
|
493
|
+
*/
|
|
494
|
+
askSleep = (data: SleepRequestedData): void => {
|
|
495
|
+
const key = readSleepKey(data.key);
|
|
496
|
+
if (key === undefined) return skipped("a sleep request", data.key);
|
|
497
|
+
if (stopped || ended.has(key)) return;
|
|
498
|
+
armSleep(key, data.at);
|
|
499
|
+
};
|
|
500
|
+
/**
|
|
501
|
+
* The sleeps the journal holds that are not over: they are the sleeps of a host that was
|
|
502
|
+
* down, and they are woken when their moment comes — or at once when it passed.
|
|
503
|
+
*/
|
|
504
|
+
const scan = (): void => {
|
|
505
|
+
for (const row of journal?.since(seq(0), [TimerSlept.name]) ?? []) {
|
|
506
|
+
const key = readSleepKey((row.data as TimerSleptData).key);
|
|
507
|
+
if (key === undefined) skipped("a wake", (row.data as TimerSleptData).key);
|
|
508
|
+
else ended.add(key);
|
|
509
|
+
}
|
|
510
|
+
for (const row of journal?.since(seq(0), [SleepRequested.name]) ?? []) {
|
|
511
|
+
const data = row.data as SleepRequestedData;
|
|
512
|
+
const key = readSleepKey(data.key);
|
|
513
|
+
if (key === undefined) {
|
|
514
|
+
skipped("a sleep request", data.key);
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (ended.has(key)) continue;
|
|
518
|
+
armSleep(key, data.at);
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
scan();
|
|
522
|
+
|
|
523
|
+
// The first tick settles what the host missed while it was down: the dues that are in the
|
|
524
|
+
// past are the ones the rule of the timer decides about.
|
|
525
|
+
let first = true;
|
|
526
|
+
// The wake that is armed for the next due: it is the clock of the host, so a host whose
|
|
527
|
+
// clock is moved by hand wakes when the clock says the due has come.
|
|
528
|
+
let cancel: (() => void) | undefined;
|
|
529
|
+
/** Arm the wake for the nearest due that is still to come. */
|
|
530
|
+
const arm = (): void => {
|
|
531
|
+
cancel?.();
|
|
532
|
+
cancel = undefined;
|
|
533
|
+
if (stopped) return;
|
|
534
|
+
let next: number | undefined;
|
|
535
|
+
for (const entry of running) {
|
|
536
|
+
// A timer whose firing is being written is armed again when the write is over.
|
|
537
|
+
if (entry.done || entry.firing) continue;
|
|
538
|
+
const at = Math.max(entry.due, entry.retryAt);
|
|
539
|
+
if (next === undefined || at < next) next = at;
|
|
540
|
+
}
|
|
541
|
+
if (next === undefined) return;
|
|
542
|
+
cancel = ctx.schedule(next, () => {
|
|
543
|
+
cancel = undefined;
|
|
544
|
+
return tick();
|
|
545
|
+
});
|
|
546
|
+
};
|
|
547
|
+
/**
|
|
548
|
+
* One tick: the dues that are due are fired, and the next wake is armed.
|
|
549
|
+
*
|
|
550
|
+
* The firings are written in parallel: a slow write must not hold up the other timers.
|
|
551
|
+
* The promise it returns settles when those writes are done, so a clock that moves by
|
|
552
|
+
* hand waits for them instead of running past them.
|
|
553
|
+
*
|
|
554
|
+
* A timer goes on to its next due only when its firing is confirmed in the journal: a write
|
|
555
|
+
* that failed leaves the due where it was, and it is tried again after a delay.
|
|
556
|
+
*/
|
|
557
|
+
const tick = (): Promise<void> => {
|
|
558
|
+
const now = ctx.now();
|
|
559
|
+
const written: Array<Promise<void>> = [];
|
|
560
|
+
for (const entry of running) {
|
|
561
|
+
if (entry.done || entry.firing || entry.due > now || entry.retryAt > now) continue;
|
|
562
|
+
const due = entry.due;
|
|
563
|
+
// The next due is computed from now, so a timer that was late does not queue up the
|
|
564
|
+
// dues it missed: it fires once and continues from there.
|
|
565
|
+
const following = nextDue(entry, now);
|
|
566
|
+
const advance = (): void => {
|
|
567
|
+
entry.due = following ?? due;
|
|
568
|
+
// A timer that fires once is done when it has fired. Its due stays a real moment:
|
|
569
|
+
// a state that holds "no due" would have to be written as null, and the journal
|
|
570
|
+
// would not read it back as the number it was.
|
|
571
|
+
entry.done = following === undefined;
|
|
572
|
+
entry.retryAt = 0;
|
|
573
|
+
remember(memory, [entry]);
|
|
574
|
+
};
|
|
575
|
+
// The rule of the timer decides about the dues that passed while the host was down; a
|
|
576
|
+
// due that is the moment of the start has not passed.
|
|
577
|
+
if (first && entry.missed === "skip" && due < now) {
|
|
578
|
+
advance();
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
// The schedule is remembered after the firing is written: a host that dies in between
|
|
582
|
+
// fires the same due again on its next start, with the same id, and that is one record.
|
|
583
|
+
entry.firing = true;
|
|
584
|
+
written.push(
|
|
585
|
+
fire(ctx, entry, due, now, journal, firingIds, () => stopped).then((confirmed) => {
|
|
586
|
+
entry.firing = false;
|
|
587
|
+
if (stopped) return;
|
|
588
|
+
// The timer is armed again whatever happens to its state: a timer that is not armed
|
|
589
|
+
// is a timer that is gone.
|
|
590
|
+
try {
|
|
591
|
+
if (confirmed) advance();
|
|
592
|
+
else entry.retryAt = ctx.now() + RETRY_MS;
|
|
593
|
+
} finally {
|
|
594
|
+
arm();
|
|
595
|
+
}
|
|
596
|
+
}),
|
|
597
|
+
);
|
|
598
|
+
}
|
|
599
|
+
first = false;
|
|
600
|
+
arm();
|
|
601
|
+
return Promise.all(written).then(() => undefined);
|
|
602
|
+
};
|
|
603
|
+
remember(memory, running);
|
|
604
|
+
// The first tick happens at once: a timer that was due while the host was down must not
|
|
605
|
+
// wait for the first wake to come.
|
|
606
|
+
void tick().catch((error: unknown) => {
|
|
607
|
+
console.error(
|
|
608
|
+
`niwa: the timer scheduler failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
609
|
+
);
|
|
610
|
+
});
|
|
611
|
+
return () => {
|
|
612
|
+
stopped = true;
|
|
613
|
+
cancel?.();
|
|
614
|
+
for (const cancelWake of wakes.values()) cancelWake();
|
|
615
|
+
wakes.clear();
|
|
616
|
+
};
|
|
617
|
+
});
|
|
618
|
+
/** The sleeps that are not over: the records that asked for them, by the sleeping place. */
|
|
619
|
+
const pendingSleeps = (): Array<{ at: number; row: StoredRecord }> => {
|
|
620
|
+
const journal = api.journal?.();
|
|
621
|
+
// A record whose key cannot be one is no sleep: the scan of the service reports it.
|
|
622
|
+
const ended = new Set(journal?.since(seq(0), [TimerSlept.name]).map((row) => (row.data as TimerSleptData).key));
|
|
623
|
+
const pending = new Map<string, { at: number; row: StoredRecord }>();
|
|
624
|
+
for (const row of journal?.since(seq(0), [SleepRequested.name]) ?? []) {
|
|
625
|
+
const data = row.data as SleepRequestedData;
|
|
626
|
+
if (readSleepKey(data.key) !== undefined && !ended.has(data.key)) pending.set(data.key, { at: data.at, row });
|
|
627
|
+
}
|
|
628
|
+
return [...pending.values()].sort((a, b) => a.at - b.at);
|
|
629
|
+
};
|
|
630
|
+
api.summarize(() => ({ sleeps: pendingSleeps().length }));
|
|
631
|
+
/** A timer as its owner sees it: what it is, when it is next due, the last firing of it. */
|
|
632
|
+
const entityOf = (entry: Scheduled): TimerEntity => {
|
|
633
|
+
const saved = savedBy(memory).get(entry.id);
|
|
634
|
+
const last = ledger.latestOf(entry.id);
|
|
635
|
+
return {
|
|
636
|
+
name: entry.id,
|
|
637
|
+
description: entry.description,
|
|
638
|
+
schedule: scheduleOf(entry.def),
|
|
639
|
+
missed: entry.missed,
|
|
640
|
+
nextDue: saved === undefined || saved.done ? null : saved.due,
|
|
641
|
+
lastFiring: last === undefined ? null : idSchema("firing").parse(last),
|
|
642
|
+
};
|
|
643
|
+
};
|
|
644
|
+
// The timers and the sleeps name the runs that asked: they are the owner's to see.
|
|
645
|
+
const onlyOwner = (caller: { kind: string; principal?: { kind: string } }): void => {
|
|
646
|
+
if (caller.kind === "client" && caller.principal?.kind !== "owner") throw new DeniedError("only the owner sees the pending sleeps and timers");
|
|
647
|
+
};
|
|
648
|
+
api.action(
|
|
649
|
+
action(timerList, {
|
|
650
|
+
// A read changes nothing: it may be made again.
|
|
651
|
+
recovery: "repeat",
|
|
652
|
+
effect: "read",
|
|
653
|
+
world: "niwa",
|
|
654
|
+
run: (_input, ctx) => {
|
|
655
|
+
onlyOwner(ctx.caller);
|
|
656
|
+
return {
|
|
657
|
+
sleeps: pendingSleeps().map(({ at, row }) => {
|
|
658
|
+
// The run that asked is the data of the record the chain began with; a handler that is no run is named by its invocation.
|
|
659
|
+
const asked = (api.journal?.()?.get(row.root)?.data as { run?: unknown } | undefined)?.run;
|
|
660
|
+
const who = typeof asked === "string" ? shortRun(asked) : row.actor.kind === "handler" ? shortInvocation(String(row.actor.invocation)) : row.actor.kind;
|
|
661
|
+
// The request is written by the sleep's step: its id is the step's operation, `<invocation>/<key>/emit/1`.
|
|
662
|
+
const label = String(row.id).replace(/\/emit\/\d+$/, "").split("/").at(-1)?.replace(/~arm$/, "").replace(/^label:/, "") ?? "";
|
|
663
|
+
return `${clockOf(at)} ${who} ${label}`;
|
|
664
|
+
}),
|
|
665
|
+
timers: scheduleOfHost().map(entityOf),
|
|
666
|
+
};
|
|
667
|
+
},
|
|
668
|
+
}),
|
|
669
|
+
);
|
|
670
|
+
api.action(
|
|
671
|
+
action(timerGet, {
|
|
672
|
+
recovery: "repeat",
|
|
673
|
+
effect: "read",
|
|
674
|
+
world: "niwa",
|
|
675
|
+
run: ({ name }, ctx) => {
|
|
676
|
+
onlyOwner(ctx.caller);
|
|
677
|
+
const entry = scheduleOfHost().find((one) => one.id === name);
|
|
678
|
+
if (entry === undefined) throw new UnknownId(name, "timer");
|
|
679
|
+
return entityOf(entry);
|
|
680
|
+
},
|
|
681
|
+
}),
|
|
682
|
+
);
|
|
683
|
+
// A sleep is asked for by this action, as a step of the handler that sleeps: the request is a
|
|
684
|
+
// record of the timers, written once.
|
|
685
|
+
api.action(
|
|
686
|
+
action(timerSleepRequest, {
|
|
687
|
+
recovery: "repeat",
|
|
688
|
+
effect: "record",
|
|
689
|
+
world: "niwa",
|
|
690
|
+
run: async (input, ctx) => {
|
|
691
|
+
await ctx.emit(SleepRequested, input);
|
|
692
|
+
return {};
|
|
693
|
+
},
|
|
694
|
+
}),
|
|
695
|
+
);
|
|
696
|
+
// A sleep that is asked for is armed at once: the wake is a record the waiting handler is
|
|
697
|
+
// woken by, and it is written when the moment of the sleep comes.
|
|
698
|
+
api.on(SleepRequested, { id: "timer-sleep" }, (data) => {
|
|
699
|
+
askSleep?.(data);
|
|
700
|
+
});
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
/** How a timer says when it fires. */
|
|
705
|
+
const TimerSchedule = z.discriminatedUnion("kind", [
|
|
706
|
+
z.object({ kind: z.literal("every"), ms: z.number() }),
|
|
707
|
+
z.object({ kind: z.literal("at"), at: z.number() }),
|
|
708
|
+
z.object({ kind: z.literal("daily"), time: z.string() }),
|
|
709
|
+
]);
|
|
710
|
+
type TimerSchedule = z.infer<typeof TimerSchedule>;
|
|
711
|
+
|
|
712
|
+
/** One timer as `timer.list` and `timer.get` show it. */
|
|
713
|
+
export const TimerEntity = z.object({
|
|
714
|
+
/** The author's name for the timer: what the firings carry and what `timer.get` takes. */
|
|
715
|
+
name: TimerId,
|
|
716
|
+
description: EntityDescription,
|
|
717
|
+
schedule: TimerSchedule,
|
|
718
|
+
/** What the timer does with the dues missed while the host was down. */
|
|
719
|
+
missed: z.enum(["once", "skip"]),
|
|
720
|
+
/** The next moment the timer is due, in milliseconds since the epoch; null when it is done. */
|
|
721
|
+
nextDue: z.number().nullable(),
|
|
722
|
+
/** The firing with the latest due, null when the timer has not fired. */
|
|
723
|
+
lastFiring: idSchema("firing").nullable(),
|
|
724
|
+
});
|
|
725
|
+
export type TimerEntity = z.infer<typeof TimerEntity>;
|
|
726
|
+
|
|
727
|
+
/** What `timer.list` shows: the pending sleeps, one line each, and the timers. */
|
|
728
|
+
export const timerList = actionRef("timer.list", {
|
|
729
|
+
description:
|
|
730
|
+
"The pending sleeps and the timers. A sleep is one line: the moment it ends, the run or invocation that asked and its label. A timer is its name, description, schedule, next due and the id of its last firing; take a name from here to get one.",
|
|
731
|
+
input: z.object({}),
|
|
732
|
+
output: z.object({ sleeps: z.array(z.string()), timers: z.array(TimerEntity) }),
|
|
733
|
+
});
|
|
734
|
+
|
|
735
|
+
/** One timer by its name. */
|
|
736
|
+
export const timerGet = actionRef("timer.get", {
|
|
737
|
+
description: "Get one timer by its name: its description, schedule, next due and the id of its last firing.",
|
|
738
|
+
input: z.object({ name: z.string().min(1) }),
|
|
739
|
+
output: TimerEntity,
|
|
740
|
+
});
|
|
741
|
+
|
|
742
|
+
/** The schedule of a timer, as data. */
|
|
743
|
+
function scheduleOf(def: TimerDef): TimerSchedule {
|
|
744
|
+
if (def.every !== undefined) return { kind: "every", ms: def.every };
|
|
745
|
+
if (def.daily !== undefined) return { kind: "daily", time: def.daily };
|
|
746
|
+
return { kind: "at", at: def.at };
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/** How a timer says when it fires, for a person who gave it no description. */
|
|
750
|
+
function scheduleText(def: TimerDef): string {
|
|
751
|
+
if (def.every !== undefined) return `every ${String(def.every)}ms`;
|
|
752
|
+
if (def.daily !== undefined) return `daily ${def.daily}`;
|
|
753
|
+
return `at ${new Date(def.at).toISOString()}`;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/** The definition of a timer, whether it came as a definition or as a trigger. */
|
|
757
|
+
function defOf(def: TimerOffer): TimerDef {
|
|
758
|
+
return "timer" in def ? def.def : def;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/** One timer, with its rule checked. */
|
|
762
|
+
function build(def: TimerDef): Scheduled {
|
|
763
|
+
const id = timerId(def.id);
|
|
764
|
+
const count = [def.every !== undefined, def.at !== undefined, def.daily !== undefined].filter(
|
|
765
|
+
Boolean,
|
|
766
|
+
).length;
|
|
767
|
+
if (count === 0) {
|
|
768
|
+
throw new Error(`timer "${id}" says neither "every", "at" nor "daily": it would never fire`);
|
|
769
|
+
}
|
|
770
|
+
if (count > 1) {
|
|
771
|
+
throw new Error(`timer "${id}" has more than one schedule: one timer has one schedule`);
|
|
772
|
+
}
|
|
773
|
+
if (def.every !== undefined) requirePeriod(def.every);
|
|
774
|
+
if (def.at !== undefined) timestamp(def.at);
|
|
775
|
+
if (def.daily !== undefined) parseTimeOfDay(def.daily);
|
|
776
|
+
const description = EntityDescription.safeParse(def.description ?? scheduleText(def));
|
|
777
|
+
if (!description.success) throw new TypeError(`timer "${id}" has a bad description: ${description.error.issues[0]?.message ?? "invalid"}`);
|
|
778
|
+
const missed = def.missed ?? DEFAULT_MISSED;
|
|
779
|
+
if (missed !== "once" && missed !== "skip") {
|
|
780
|
+
throw new Error(`timer "${id}" has an unknown missed rule "${String(missed)}"`);
|
|
781
|
+
}
|
|
782
|
+
return { id, def, description: description.data, missed, due: timestamp(0), done: false, firing: false, retryAt: 0 };
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/** A period is a positive whole number of milliseconds: the moments it makes are timestamps. */
|
|
786
|
+
function requirePeriod(ms: number): void {
|
|
787
|
+
if (!Number.isInteger(ms) || ms <= 0) {
|
|
788
|
+
throw new TypeError(
|
|
789
|
+
`a timer period must be a positive whole number of milliseconds, got ${String(ms)}`,
|
|
790
|
+
);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/** A time of day is "HH:MM" in local time. */
|
|
795
|
+
function parseTimeOfDay(time: string): string {
|
|
796
|
+
if (typeof time !== "string" || !/^\d{2}:\d{2}$/.test(time)) {
|
|
797
|
+
throw new TypeError(`a time of day must be "HH:MM", got ${JSON.stringify(time)}`);
|
|
798
|
+
}
|
|
799
|
+
const [hours, minutes] = time.split(":").map(Number);
|
|
800
|
+
if (hours === undefined || minutes === undefined || hours > 23 || minutes > 59) {
|
|
801
|
+
throw new TypeError(`a time of day must be "HH:MM" in 24 hours, got ${JSON.stringify(time)}`);
|
|
802
|
+
}
|
|
803
|
+
return time;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/** The schema of what the plugin remembers about its timers. */
|
|
807
|
+
const ScheduleSchema: z.ZodType<Schedule> = z.array(
|
|
808
|
+
z.object({ id: z.string(), due: z.number(), done: z.boolean(), schedule: z.string() }),
|
|
809
|
+
);
|
|
810
|
+
|
|
811
|
+
/** The first moment a timer is due, when the plugin does not know one yet. */
|
|
812
|
+
function firstDue(entry: Scheduled, now: Timestamp): Timestamp {
|
|
813
|
+
const { def } = entry;
|
|
814
|
+
if (def.every !== undefined) return timestamp(now + def.every);
|
|
815
|
+
if (def.daily !== undefined) return nextTimeOfDay(def.daily, now);
|
|
816
|
+
return timestamp(def.at as number);
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* Where a saved schedule stands, unless the due it points at already fired.
|
|
821
|
+
*
|
|
822
|
+
* The schedule is remembered after the firing is written, so a host that died in between left a
|
|
823
|
+
* schedule pointing at a due the journal already holds. That due is settled: the timer goes on
|
|
824
|
+
* exactly as the tick that wrote the firing would have, from the moment the firing carries.
|
|
825
|
+
* Each step follows one firing of the journal, so the walk is as long as the firings the
|
|
826
|
+
* schedule did not remember, not as the downtime.
|
|
827
|
+
*/
|
|
828
|
+
function settle(
|
|
829
|
+
entry: Scheduled,
|
|
830
|
+
saved: ScheduleEntry,
|
|
831
|
+
journal: JournalReader | undefined,
|
|
832
|
+
ids: IdIndex<"firing">,
|
|
833
|
+
): Pick<ScheduleEntry, "due" | "done"> {
|
|
834
|
+
let { due, done } = { due: saved.due, done: saved.done };
|
|
835
|
+
while (!done) {
|
|
836
|
+
const firing = journal?.get(recordId(firingId(ids, entry.id, timestamp(due))));
|
|
837
|
+
if (firing === undefined) break;
|
|
838
|
+
const at = (firing.data as TimerFiredData).at;
|
|
839
|
+
const following = nextDue(entry, timestamp(at));
|
|
840
|
+
if (following === undefined) {
|
|
841
|
+
done = true;
|
|
842
|
+
} else if (following > due) {
|
|
843
|
+
due = following;
|
|
844
|
+
} else {
|
|
845
|
+
break;
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
return { due, done };
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* The next moment a timer is due, given the moment it fired.
|
|
853
|
+
*
|
|
854
|
+
* A timer that fires once has no next due: the answer is undefined, and the timer is done.
|
|
855
|
+
*/
|
|
856
|
+
function nextDue(entry: Scheduled, now: Timestamp): Timestamp | undefined {
|
|
857
|
+
const { def } = entry;
|
|
858
|
+
if (def.every !== undefined) return timestamp(now + def.every);
|
|
859
|
+
if (def.daily !== undefined) return nextTimeOfDay(def.daily, now);
|
|
860
|
+
return undefined;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/** The next moment of a time of day, after `from`. */
|
|
864
|
+
function nextTimeOfDay(time: string, from: Timestamp): Timestamp {
|
|
865
|
+
const [hours, minutes] = time.split(":").map(Number);
|
|
866
|
+
const day = new Date(from);
|
|
867
|
+
day.setHours(hours ?? 0, minutes ?? 0, 0, 0);
|
|
868
|
+
if (day.getTime() <= from) {
|
|
869
|
+
day.setDate(day.getDate() + 1);
|
|
870
|
+
// The hour is set again: on the day a clock change skipped it, the first setting landed on
|
|
871
|
+
// the next hour, and the next day has its own.
|
|
872
|
+
day.setHours(hours ?? 0, minutes ?? 0, 0, 0);
|
|
873
|
+
}
|
|
874
|
+
return timestamp(day.getTime());
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/** What the plugin remembers about its timers. */
|
|
878
|
+
function remember(memory: StateHandle<Schedule>, running: readonly Scheduled[]): void {
|
|
879
|
+
memory.update((current) => {
|
|
880
|
+
const next = new Map(current.map((entry) => [entry.id, entry]));
|
|
881
|
+
for (const entry of running) {
|
|
882
|
+
next.set(entry.id, { id: entry.id, due: entry.due, done: entry.done, schedule: scheduleKey(entry.def) });
|
|
883
|
+
}
|
|
884
|
+
return [...next.values()];
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
/** A stored record that cannot be what it says it is: it is left out, and the log says so. */
|
|
889
|
+
function skipped(what: string, key: unknown): void {
|
|
890
|
+
console.error(`niwa: ${what} with the sleep key ${JSON.stringify(key)} is skipped: a sleep key is a non-empty string without whitespace`);
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* The firings the journal holds, read once and then followed: the ids they were issued, and the
|
|
895
|
+
* latest firing of each timer.
|
|
896
|
+
*
|
|
897
|
+
* Each question reads only the firings written since the last one, so a firing costs what it is,
|
|
898
|
+
* not the history behind it.
|
|
899
|
+
*/
|
|
900
|
+
class FiringLedger {
|
|
901
|
+
private cursor = seq(0);
|
|
902
|
+
private readonly entries: Array<{ id: string; seed: string }> = [];
|
|
903
|
+
private readonly latest = new Map<string, { id: string; due: number }>();
|
|
904
|
+
|
|
905
|
+
constructor(private readonly journal: () => JournalReader | undefined) {}
|
|
906
|
+
|
|
907
|
+
/** The ids issued to the firings, with the seeds they came from, in the order of the journal. */
|
|
908
|
+
issued(): readonly { id: string; seed: string }[] {
|
|
909
|
+
this.catchUp();
|
|
910
|
+
return this.entries;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/** The id of the latest firing of a timer: the one with the greatest due. */
|
|
914
|
+
latestOf(timer: string): string | undefined {
|
|
915
|
+
this.catchUp();
|
|
916
|
+
return this.latest.get(timer)?.id;
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
private catchUp(): void {
|
|
920
|
+
const journal = this.journal();
|
|
921
|
+
if (journal === undefined) return;
|
|
922
|
+
if (journal.last() < this.cursor) {
|
|
923
|
+
this.cursor = seq(0);
|
|
924
|
+
this.entries.length = 0;
|
|
925
|
+
this.latest.clear();
|
|
926
|
+
}
|
|
927
|
+
for (const row of journal.since(this.cursor, [TimerFired.name])) {
|
|
928
|
+
const data = row.data as TimerFiredData;
|
|
929
|
+
const id = String(row.id);
|
|
930
|
+
this.entries.push({ id, seed: firingSeed(data.timer, data.due) });
|
|
931
|
+
const last = this.latest.get(data.timer);
|
|
932
|
+
if (last === undefined || data.due > last.due) this.latest.set(data.timer, { id, due: data.due });
|
|
933
|
+
this.cursor = row.seq;
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
/**
|
|
939
|
+
* Write the firing of one timer.
|
|
940
|
+
*
|
|
941
|
+
* The id is the one of the timer and the due, so a firing written twice is the same record. The
|
|
942
|
+
* answer is whether the firing is in the journal: only then may the timer go on to its next due.
|
|
943
|
+
*/
|
|
944
|
+
async function fire(
|
|
945
|
+
ctx: ServiceContext,
|
|
946
|
+
entry: Scheduled,
|
|
947
|
+
due: Timestamp,
|
|
948
|
+
at: Timestamp,
|
|
949
|
+
journal: JournalReader | undefined,
|
|
950
|
+
ids: IdIndex<"firing">,
|
|
951
|
+
stopped: () => boolean,
|
|
952
|
+
): Promise<boolean> {
|
|
953
|
+
const id = recordId(firingId(ids, entry.id, due));
|
|
954
|
+
// The firing carries the moment it was written, so a second write of it is not the same
|
|
955
|
+
// content: the one that is already in the journal is the firing, and it is not written again.
|
|
956
|
+
if (journal?.get(id) !== undefined) return true;
|
|
957
|
+
try {
|
|
958
|
+
await ctx.emit(TimerFired, { timer: entry.id, due, at }, { id });
|
|
959
|
+
return true;
|
|
960
|
+
} catch (error) {
|
|
961
|
+
if (error instanceof IntegrityError) return true; // written in the meantime
|
|
962
|
+
if (stopped()) return false; // the host is closing
|
|
963
|
+
console.error(
|
|
964
|
+
`niwa: the timer "${entry.id}" could not write its firing, it is tried again: ${
|
|
965
|
+
error instanceof Error ? error.message : String(error)
|
|
966
|
+
}`,
|
|
967
|
+
);
|
|
968
|
+
return false;
|
|
969
|
+
}
|
|
970
|
+
}
|