@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/records.ts
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The records of the timer module: a timer fired.
|
|
3
|
+
*
|
|
4
|
+
* A firing is an external input: it starts its own chain, and the root of that chain is the
|
|
5
|
+
* firing itself. What the record carries is enough to say which
|
|
6
|
+
* timer fired, when it was due and when it was written — the due time is the timer's own
|
|
7
|
+
* schedule, and the write time is when the host got to it.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { actionRef, queryOf, record } from "@niwa-labs/core";
|
|
11
|
+
import type { TypeQuery } from "@niwa-labs/core";
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
|
|
14
|
+
/** The name of a timer: its author gives it, and it becomes part of the seed of its firings. */
|
|
15
|
+
export const TimerId = z
|
|
16
|
+
.string()
|
|
17
|
+
.regex(/^\S+$/, "a timer id must be a non-empty string without whitespace")
|
|
18
|
+
.brand<"TimerId">();
|
|
19
|
+
export type TimerId = z.infer<typeof TimerId>;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The id of a timer. Constructed only here.
|
|
23
|
+
*
|
|
24
|
+
* @throws when the id is empty or has whitespace.
|
|
25
|
+
*/
|
|
26
|
+
export function timerId(value: string): TimerId {
|
|
27
|
+
const parsed = TimerId.safeParse(value);
|
|
28
|
+
if (!parsed.success) {
|
|
29
|
+
throw new TypeError(`a timer id must be a non-empty string without whitespace, got ${JSON.stringify(value)}`);
|
|
30
|
+
}
|
|
31
|
+
return parsed.data;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A timer fired.
|
|
36
|
+
*
|
|
37
|
+
* `timer` is the id of the timer, `due` the moment it was due (milliseconds since the epoch),
|
|
38
|
+
* and `at` the moment the firing was written.
|
|
39
|
+
*/
|
|
40
|
+
export const TimerFired = record(
|
|
41
|
+
"timer.fired",
|
|
42
|
+
z.object({
|
|
43
|
+
/** The id of the timer that fired. */
|
|
44
|
+
timer: z.string(),
|
|
45
|
+
/** When the timer was due, in milliseconds since the epoch. */
|
|
46
|
+
due: z.number(),
|
|
47
|
+
/** When the firing was written, in milliseconds since the epoch. */
|
|
48
|
+
at: z.number(),
|
|
49
|
+
}),
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
/** The data of a firing: which timer, when it was due, when it was written. */
|
|
53
|
+
export type TimerFiredData = z.infer<typeof TimerFired.schema>;
|
|
54
|
+
|
|
55
|
+
/** The firings of one timer: the query a trigger, a wait and a read of the history share. */
|
|
56
|
+
export function timerFiredQuery(timer: TimerId): TypeQuery<TimerFiredData> {
|
|
57
|
+
return queryOf(TimerFired, { timer });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The schema of a sleep key as the data of a record carries it: a non-empty string without whitespace. */
|
|
61
|
+
const SleepKeyText = z.string().regex(/^\S+$/, "a sleep key must be a non-empty string without whitespace");
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The key of one sleep: the invocation and the sleeping place.
|
|
65
|
+
*
|
|
66
|
+
* Branded: a bare string is not accepted where a sleep key is expected.
|
|
67
|
+
*/
|
|
68
|
+
export type SleepKey = string & { readonly __brand: "SleepKey" };
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The key of one sleep. Constructed only here.
|
|
72
|
+
*
|
|
73
|
+
* It becomes part of a record id, so it must be a non-empty string without whitespace.
|
|
74
|
+
*
|
|
75
|
+
* @throws when the key cannot be part of a record id.
|
|
76
|
+
*/
|
|
77
|
+
export function sleepKey(value: string): SleepKey {
|
|
78
|
+
const parsed = readSleepKey(value);
|
|
79
|
+
if (parsed === undefined) {
|
|
80
|
+
throw new TypeError(`a sleep key must be a non-empty string without whitespace, got ${JSON.stringify(value)}`);
|
|
81
|
+
}
|
|
82
|
+
return parsed;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** A sleep key, or undefined when what a record carries cannot be one. */
|
|
86
|
+
export function readSleepKey(value: unknown): SleepKey | undefined {
|
|
87
|
+
const parsed = SleepKeyText.safeParse(value);
|
|
88
|
+
return parsed.success ? (parsed.data as SleepKey) : undefined;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* A handler asked to sleep until a moment.
|
|
93
|
+
*
|
|
94
|
+
* The request says when the sleep ends (`at`) and which sleeping place asked for it (`key`).
|
|
95
|
+
* The key is written by the handler that sleeps, so the wake that ends the sleep is addressed
|
|
96
|
+
* to that one place.
|
|
97
|
+
*/
|
|
98
|
+
export const SleepRequested = record(
|
|
99
|
+
"timer.sleep.requested",
|
|
100
|
+
z.object({
|
|
101
|
+
/** When the sleep ends, in milliseconds since the epoch. */
|
|
102
|
+
at: z.number(),
|
|
103
|
+
/** The key of the sleeping place the wake is addressed to. */
|
|
104
|
+
key: SleepKeyText,
|
|
105
|
+
}),
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
/** The data of a sleep request: when the sleep ends and the key of the sleeping place. */
|
|
109
|
+
export type SleepRequestedData = z.infer<typeof SleepRequested.schema>;
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Ask the timers for the wake of a sleeping place at a moment: the command whose fact is a
|
|
113
|
+
* `timer.sleep.requested` record. A sleep is asked for by calling it as a step, so the request is
|
|
114
|
+
* the timers' own record and a replay does not ask again.
|
|
115
|
+
*/
|
|
116
|
+
export const timerSleepRequest = actionRef("timer.sleep.request", {
|
|
117
|
+
description: "Ask for the wake of a sleeping place at a moment, in milliseconds since the epoch.",
|
|
118
|
+
input: SleepRequested.schema,
|
|
119
|
+
output: z.object({}),
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* A sleep ended.
|
|
124
|
+
*
|
|
125
|
+
* The wake is addressed to one sleeping place, so the record carries the key of that place and
|
|
126
|
+
* nothing else: the moment it was written is the moment the sleep ended.
|
|
127
|
+
*/
|
|
128
|
+
export const TimerSlept = record(
|
|
129
|
+
"timer.slept",
|
|
130
|
+
z.object({
|
|
131
|
+
/** The key of the sleeping place that is woken. */
|
|
132
|
+
key: SleepKeyText,
|
|
133
|
+
}),
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
/** The data of a sleep that ended: the key of the sleeping place. */
|
|
137
|
+
export type TimerSleptData = z.infer<typeof TimerSlept.schema>;
|
|
138
|
+
|
|
139
|
+
const DAY_MS = 24 * 3_600_000;
|
|
140
|
+
|
|
141
|
+
/** A moment as a person reads a clock, in local time: the time, and the day when it is more than a day away. */
|
|
142
|
+
export function clockOf(at: number, now: number = Date.now()): string {
|
|
143
|
+
const date = new Date(at);
|
|
144
|
+
const time = date.toTimeString().slice(0, 8);
|
|
145
|
+
if (at - now < DAY_MS) return time;
|
|
146
|
+
const month = String(date.getMonth() + 1).padStart(2, "0");
|
|
147
|
+
const day = String(date.getDate()).padStart(2, "0");
|
|
148
|
+
return `${month}-${day} ${time}`;
|
|
149
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// The clock of one host: a test can move the time of a host and watch what it does with it.
|
|
2
|
+
//
|
|
3
|
+
// One host has one clock, and everything that reads the time or waits for
|
|
4
|
+
// it uses that clock:
|
|
5
|
+
//
|
|
6
|
+
// 1. a host with a test clock gets one: the time it sees is the time the test gave it
|
|
7
|
+
// 2. a daily timer fires exactly once per day of the test clock, and advancing seven days
|
|
8
|
+
// fires it seven times, without the test waiting in real time
|
|
9
|
+
// 3. a timer of the real clock still fires, and the timers of the real host still work
|
|
10
|
+
//
|
|
11
|
+
// Only the public API is used: the entries of the packages and "@niwa-labs/testing".
|
|
12
|
+
|
|
13
|
+
import { expect, test } from "bun:test";
|
|
14
|
+
|
|
15
|
+
import { seq } from "@niwa-labs/core";
|
|
16
|
+
import type { StoredRecord } from "@niwa-labs/core";
|
|
17
|
+
import { plugin } from "@niwa-labs/plugin";
|
|
18
|
+
import { createNiwa, tempHome, testClock } from "@niwa-labs/testing";
|
|
19
|
+
|
|
20
|
+
import { timers } from "../src/index.ts";
|
|
21
|
+
|
|
22
|
+
/** A day in milliseconds: the period of the daily timer. */
|
|
23
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
24
|
+
|
|
25
|
+
/** The time of day the daily timer fires at, in local time. */
|
|
26
|
+
const DAILY_AT = "03:17";
|
|
27
|
+
|
|
28
|
+
/** The id of the daily timer in this test. */
|
|
29
|
+
const TIMER_ID = "clock-daily";
|
|
30
|
+
|
|
31
|
+
/** The firings of the timer of a host, in the order they were written. */
|
|
32
|
+
async function firingsOf(records: readonly StoredRecord[]): Promise<Array<{ due: number; at: number }>> {
|
|
33
|
+
return records
|
|
34
|
+
.filter((record) => record.type === "timer.fired")
|
|
35
|
+
.map((record) => {
|
|
36
|
+
const data = record.data as { timer: string; due: number; at: number };
|
|
37
|
+
return { due: data.due, at: data.at };
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The records of the journal of a host, from the beginning. */
|
|
42
|
+
async function readAll(host: ReturnType<typeof createNiwa>): Promise<StoredRecord[]> {
|
|
43
|
+
return host.records.read();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
test("a host with a test clock reads the time of that clock", async () => {
|
|
47
|
+
const home = await tempHome();
|
|
48
|
+
// A moment that is not the real one: if the host read the real clock, this would not hold.
|
|
49
|
+
const start = 1_700_000_000_000;
|
|
50
|
+
const clock = testClock(start);
|
|
51
|
+
const niwa = createNiwa({ home: home.path, clock });
|
|
52
|
+
try {
|
|
53
|
+
await niwa.serve();
|
|
54
|
+
expect(clock.now()).toBe(start);
|
|
55
|
+
// The clock of the host is the one it was given: it only moves when the test says so.
|
|
56
|
+
expect(clock.now()).toBe(start);
|
|
57
|
+
await clock.advance(1000);
|
|
58
|
+
expect(clock.now()).toBe(start + 1000);
|
|
59
|
+
} finally {
|
|
60
|
+
await niwa.close();
|
|
61
|
+
await home.cleanup();
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("a daily timer fires once per day of the test clock: seven days are seven firings", async () => {
|
|
66
|
+
const home = await tempHome();
|
|
67
|
+
const start = new Date(2024, 0, 1, 0, 0, 0, 0).getTime();
|
|
68
|
+
const clock = testClock(start);
|
|
69
|
+
const niwa = createNiwa({ home: home.path, clock });
|
|
70
|
+
try {
|
|
71
|
+
niwa.use(timers([{ id: TIMER_ID, daily: DAILY_AT }]));
|
|
72
|
+
await niwa.serve();
|
|
73
|
+
|
|
74
|
+
// Seven days of the clock: seven firings, and no waiting in real time.
|
|
75
|
+
const before = Date.now();
|
|
76
|
+
await clock.advance(7 * DAY_MS);
|
|
77
|
+
const elapsed = Date.now() - before;
|
|
78
|
+
|
|
79
|
+
const firings = await firingsOf(await readAll(niwa));
|
|
80
|
+
expect(firings).toHaveLength(7);
|
|
81
|
+
|
|
82
|
+
// Each firing is its own record, and the due of one is the moment the day came.
|
|
83
|
+
const dues = firings.map((firing) => firing.due);
|
|
84
|
+
expect(new Set(dues).size).toBe(dues.length);
|
|
85
|
+
for (let day = 1; day <= 7; day += 1) {
|
|
86
|
+
expect(dues[day - 1]).toBe(new Date(2024, 0, day, 3, 17, 0, 0).getTime());
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// The week was watched, not waited for: a week of real time would have taken a week.
|
|
90
|
+
expect(elapsed).toBeLessThan(10_000);
|
|
91
|
+
|
|
92
|
+
// The work of the host did not fail while the clock moved.
|
|
93
|
+
expect(clock.failures()).toEqual([]);
|
|
94
|
+
} finally {
|
|
95
|
+
await niwa.close();
|
|
96
|
+
await home.cleanup();
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("a timer of the real clock still fires, and the real clock still moves", async () => {
|
|
101
|
+
const home = await tempHome();
|
|
102
|
+
const niwa = createNiwa({ home: home.path });
|
|
103
|
+
try {
|
|
104
|
+
niwa.use(timers([{ id: "clock-real", every: 100 }]));
|
|
105
|
+
await niwa.serve();
|
|
106
|
+
|
|
107
|
+
// The real clock is the default: the timer fires on its own, without a test moving it.
|
|
108
|
+
const deadline = Date.now() + 10_000;
|
|
109
|
+
let firings: Array<{ due: number; at: number }> = [];
|
|
110
|
+
while (Date.now() < deadline) {
|
|
111
|
+
firings = await firingsOf(await readAll(niwa));
|
|
112
|
+
if (firings.length >= 2) break;
|
|
113
|
+
await Bun.sleep(50);
|
|
114
|
+
}
|
|
115
|
+
expect(firings.length).toBeGreaterThanOrEqual(2);
|
|
116
|
+
// The firings carry the real time: the moment they were due is not in the past by much.
|
|
117
|
+
const now = Date.now();
|
|
118
|
+
for (const firing of firings) {
|
|
119
|
+
expect(firing.at).toBeLessThanOrEqual(now);
|
|
120
|
+
expect(now - firing.at).toBeLessThan(10_000);
|
|
121
|
+
}
|
|
122
|
+
} finally {
|
|
123
|
+
await niwa.close();
|
|
124
|
+
await home.cleanup();
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test("the timer of a host without a clock is the real one, and a timer at a moment still fires", async () => {
|
|
129
|
+
const home = await tempHome();
|
|
130
|
+
const niwa = createNiwa({ home: home.path });
|
|
131
|
+
try {
|
|
132
|
+
// A timer that fires once, at a moment a moment from now: the real clock carries it.
|
|
133
|
+
const due = Date.now() + 150;
|
|
134
|
+
niwa.use(timers([{ id: "clock-at", at: due }]));
|
|
135
|
+
await niwa.serve();
|
|
136
|
+
const deadline = Date.now() + 10_000;
|
|
137
|
+
let firings: Array<{ due: number; at: number }> = [];
|
|
138
|
+
while (Date.now() < deadline) {
|
|
139
|
+
firings = await firingsOf(await readAll(niwa));
|
|
140
|
+
if (firings.length >= 1) break;
|
|
141
|
+
await Bun.sleep(50);
|
|
142
|
+
}
|
|
143
|
+
expect(firings).toHaveLength(1);
|
|
144
|
+
expect(firings[0]?.due).toBe(due);
|
|
145
|
+
} finally {
|
|
146
|
+
await niwa.close();
|
|
147
|
+
await home.cleanup();
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test("a plugin's service sees the clock of the host", async () => {
|
|
152
|
+
const home = await tempHome();
|
|
153
|
+
const start = 1_700_000_000_000;
|
|
154
|
+
const clock = testClock(start);
|
|
155
|
+
const niwa = createNiwa({ home: home.path, clock });
|
|
156
|
+
const seen: number[] = [];
|
|
157
|
+
try {
|
|
158
|
+
niwa.use(
|
|
159
|
+
plugin("clock-watcher", (api) => {
|
|
160
|
+
api.service((ctx) => {
|
|
161
|
+
seen.push(ctx.now());
|
|
162
|
+
ctx.schedule(start + 500, () => {
|
|
163
|
+
seen.push(ctx.now());
|
|
164
|
+
});
|
|
165
|
+
return () => {};
|
|
166
|
+
});
|
|
167
|
+
}),
|
|
168
|
+
);
|
|
169
|
+
await niwa.serve();
|
|
170
|
+
expect(seen).toEqual([start]);
|
|
171
|
+
await clock.advance(500);
|
|
172
|
+
// The service was woken by the clock of the host, and it saw the time it was woken at.
|
|
173
|
+
expect(seen).toEqual([start, start + 500]);
|
|
174
|
+
} finally {
|
|
175
|
+
await niwa.close();
|
|
176
|
+
await home.cleanup();
|
|
177
|
+
}
|
|
178
|
+
});
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// What a declaration of a timer must be, and how a moment and the firings of a timer are named:
|
|
2
|
+
// whole milliseconds, a daily hour that a clock change moved, a wake date in one time zone, and
|
|
3
|
+
// the query of the firings of one timer.
|
|
4
|
+
|
|
5
|
+
import { expect, test } from "bun:test";
|
|
6
|
+
|
|
7
|
+
import { actionName } from "@niwa-labs/core";
|
|
8
|
+
import { createNiwa, eventually, tempHome, testClock } from "@niwa-labs/testing";
|
|
9
|
+
import type { StoredRecord } from "@niwa-labs/core";
|
|
10
|
+
|
|
11
|
+
import { clockOf, timer, timerFiredQuery, timerId, timers } from "../src/index.ts";
|
|
12
|
+
import type { TimerEntity } from "../src/index.ts";
|
|
13
|
+
|
|
14
|
+
type Host = ReturnType<typeof createNiwa>;
|
|
15
|
+
|
|
16
|
+
const LIST = actionName("timer.list");
|
|
17
|
+
|
|
18
|
+
const ofType = (records: readonly StoredRecord[], type: string): StoredRecord[] => records.filter((row) => row.type === type);
|
|
19
|
+
const listed = async (niwa: Host): Promise<TimerEntity[]> => ((await niwa.call(LIST, {})) as { timers: TimerEntity[] }).timers;
|
|
20
|
+
|
|
21
|
+
test("a period or a moment that is not a whole number of milliseconds is refused when it is declared", () => {
|
|
22
|
+
expect(() => timer.every(0.5)).toThrow("whole number");
|
|
23
|
+
expect(() => timers([{ id: "half", every: 0.5 }])).toThrow("whole number");
|
|
24
|
+
expect(() => timers([{ id: "late", at: 1.5 }])).toThrow("timestamp");
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test("a daily timer that a clock change moved to a later hour is back at its own hour the next day", async () => {
|
|
28
|
+
const zone = process.env.TZ;
|
|
29
|
+
process.env.TZ = "America/New_York";
|
|
30
|
+
const home = await tempHome();
|
|
31
|
+
// 2026-03-08 is the day the clocks go forward in New York: 02:30 does not exist.
|
|
32
|
+
const start = new Date(2026, 2, 8, 0, 0, 0, 0).getTime();
|
|
33
|
+
const clock = testClock(start);
|
|
34
|
+
const niwa = createNiwa({ home: home.path, clock });
|
|
35
|
+
try {
|
|
36
|
+
niwa.use(timers([{ id: "half-past-two", daily: "02:30" }]));
|
|
37
|
+
await niwa.serve();
|
|
38
|
+
await clock.advance(5 * 3_600_000);
|
|
39
|
+
await eventually(async () => ofType(await niwa.records.read(), "timer.fired").length === 1, 10_000, "no firing on the day of the change");
|
|
40
|
+
expect((await listed(niwa))[0]?.nextDue).toBe(new Date(2026, 2, 9, 2, 30, 0, 0).getTime());
|
|
41
|
+
} finally {
|
|
42
|
+
await niwa.close();
|
|
43
|
+
if (zone === undefined) delete process.env.TZ;
|
|
44
|
+
else process.env.TZ = zone;
|
|
45
|
+
await home.cleanup();
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("a moment far away is shown with the day and the time of one zone", () => {
|
|
50
|
+
const zone = process.env.TZ;
|
|
51
|
+
process.env.TZ = "America/New_York";
|
|
52
|
+
try {
|
|
53
|
+
const evening = new Date(2026, 0, 10, 21, 0, 0, 0).getTime();
|
|
54
|
+
expect(clockOf(evening, new Date(2026, 0, 1).getTime())).toBe("01-10 21:00:00");
|
|
55
|
+
} finally {
|
|
56
|
+
if (zone === undefined) delete process.env.TZ;
|
|
57
|
+
else process.env.TZ = zone;
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test("the firings of one timer are a query a trigger and a reader share", () => {
|
|
62
|
+
const query = timerFiredQuery(timerId("digest"));
|
|
63
|
+
expect(query.types.map((type) => type.name)).toEqual(["timer.fired"]);
|
|
64
|
+
expect(query.filter).toEqual({ timer: "digest" });
|
|
65
|
+
expect(timer.fired("digest").filter).toEqual(query.filter);
|
|
66
|
+
});
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// A timer goes on to its next due only when its firing is in the journal: a write that failed is
|
|
2
|
+
// tried again, and a due that is the moment of the start is a due that came.
|
|
3
|
+
|
|
4
|
+
import { expect, test } from "bun:test";
|
|
5
|
+
|
|
6
|
+
import { actionName } from "@niwa-labs/core";
|
|
7
|
+
import type { StoredRecord } from "@niwa-labs/core";
|
|
8
|
+
import { createNiwa, eventually, tempHome, testClock } from "@niwa-labs/testing";
|
|
9
|
+
|
|
10
|
+
import { timers } from "../src/index.ts";
|
|
11
|
+
import type { TimerEntity } from "../src/index.ts";
|
|
12
|
+
import { failing } from "./fixtures/failing-writes.ts";
|
|
13
|
+
|
|
14
|
+
type Host = ReturnType<typeof createNiwa>;
|
|
15
|
+
|
|
16
|
+
const START = 1_700_000_000_000;
|
|
17
|
+
const LIST = actionName("timer.list");
|
|
18
|
+
|
|
19
|
+
const ofType = (records: readonly StoredRecord[], type: string): StoredRecord[] => records.filter((row) => row.type === type);
|
|
20
|
+
const listed = async (niwa: Host): Promise<TimerEntity[]> => ((await niwa.call(LIST, {})) as { timers: TimerEntity[] }).timers;
|
|
21
|
+
|
|
22
|
+
test("a firing that could not be written keeps its due, and the timer fires when the write is tried again", async () => {
|
|
23
|
+
const home = await tempHome();
|
|
24
|
+
const clock = testClock(START);
|
|
25
|
+
const niwa = createNiwa({ home: home.path, clock });
|
|
26
|
+
const failures = { "timer.fired": 1 };
|
|
27
|
+
try {
|
|
28
|
+
niwa.use(failing(timers([{ id: "once", at: START + 1000 }]), failures));
|
|
29
|
+
await niwa.serve();
|
|
30
|
+
await clock.advance(1000);
|
|
31
|
+
expect(failures["timer.fired"]).toBe(0);
|
|
32
|
+
expect(ofType(await niwa.records.read(), "timer.fired")).toHaveLength(0);
|
|
33
|
+
// The timer is not done: it still has the due it could not fire.
|
|
34
|
+
expect((await listed(niwa))[0]).toMatchObject({ nextDue: START + 1000, lastFiring: null });
|
|
35
|
+
|
|
36
|
+
await clock.advance(1000);
|
|
37
|
+
await eventually(async () => ofType(await niwa.records.read(), "timer.fired").length === 1, 10_000, "the firing was not retried");
|
|
38
|
+
const [fired] = ofType(await niwa.records.read(), "timer.fired");
|
|
39
|
+
expect((fired?.data as { due: number }).due).toBe(START + 1000);
|
|
40
|
+
await eventually(async () => (await listed(niwa))[0]?.nextDue === null, 10_000, "the timer was not done");
|
|
41
|
+
expect(ofType(await niwa.records.read(), "timer.fired")).toHaveLength(1);
|
|
42
|
+
} finally {
|
|
43
|
+
await niwa.close();
|
|
44
|
+
await home.cleanup();
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("a timer whose due is the moment the host starts fires under the rule that skips missed dues", async () => {
|
|
49
|
+
const home = await tempHome();
|
|
50
|
+
const clock = testClock(START);
|
|
51
|
+
const niwa = createNiwa({ home: home.path, clock });
|
|
52
|
+
try {
|
|
53
|
+
niwa.use(timers([{ id: "now", at: START, missed: "skip" }]));
|
|
54
|
+
await niwa.serve();
|
|
55
|
+
await eventually(async () => ofType(await niwa.records.read(), "timer.fired").length === 1, 10_000, "the due of the moment was dropped");
|
|
56
|
+
} finally {
|
|
57
|
+
await niwa.close();
|
|
58
|
+
await home.cleanup();
|
|
59
|
+
}
|
|
60
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// The timers plugin with its service made to fail: the wrapper hands the service a context whose
|
|
2
|
+
// `emit` fails for the types a test names, and everything else is the real host and the real journal.
|
|
3
|
+
|
|
4
|
+
import type { RecordType } from "@niwa-labs/core";
|
|
5
|
+
import type { Plugin, PluginApi } from "@niwa-labs/plugin";
|
|
6
|
+
|
|
7
|
+
/** `inner` with the writes of its service made to fail: `failures` says how many writes of a type fail first. */
|
|
8
|
+
export function failing(inner: Plugin, failures: Record<string, number>): Plugin {
|
|
9
|
+
return {
|
|
10
|
+
...inner,
|
|
11
|
+
setup(api: PluginApi) {
|
|
12
|
+
inner.setup({
|
|
13
|
+
...api,
|
|
14
|
+
service: (start) =>
|
|
15
|
+
api.service((ctx) =>
|
|
16
|
+
start({
|
|
17
|
+
...ctx,
|
|
18
|
+
emit: async <T>(type: RecordType<T>, data: T, opts?: Parameters<typeof ctx.emit>[2]) => {
|
|
19
|
+
const left = failures[type.name] ?? 0;
|
|
20
|
+
if (left > 0) {
|
|
21
|
+
failures[type.name] = left - 1;
|
|
22
|
+
throw new Error("the write failed");
|
|
23
|
+
}
|
|
24
|
+
return ctx.emit(type, data, opts);
|
|
25
|
+
},
|
|
26
|
+
}),
|
|
27
|
+
),
|
|
28
|
+
});
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// The host program for the missed-dues scenario of the timer.
|
|
2
|
+
//
|
|
3
|
+
// A timer fires. With the host down at the due time, what happens after start is exactly what
|
|
4
|
+
// the timer's declared rule says, once.
|
|
5
|
+
//
|
|
6
|
+
// The host installs two plugins:
|
|
7
|
+
//
|
|
8
|
+
// "timers" — the scheduler: it writes the firings
|
|
9
|
+
// "ticks" — a handler of the trigger of the timer: it counts the firings it is woken by
|
|
10
|
+
//
|
|
11
|
+
// The timer itself comes from the command line, so the test can say how long the period is and
|
|
12
|
+
// what the rule about the missed dues is:
|
|
13
|
+
//
|
|
14
|
+
// argv[2] the home
|
|
15
|
+
// argv[3] the id of the timer
|
|
16
|
+
// argv[4] the period, in milliseconds
|
|
17
|
+
// argv[5] the rule about the missed dues: "once" or "skip"
|
|
18
|
+
//
|
|
19
|
+
// The handler of the trigger is what shows that a trigger is usable in `niwa.on`: it is woken
|
|
20
|
+
// by the firings of its own timer and by no others.
|
|
21
|
+
//
|
|
22
|
+
// The home directory comes from argv[2]. The test imports this file for the timer it declares,
|
|
23
|
+
// so the host only starts when the file is run directly.
|
|
24
|
+
|
|
25
|
+
import { plugin } from "@niwa-labs/plugin";
|
|
26
|
+
import type { MissedRule } from "@niwa-labs/plugin";
|
|
27
|
+
import { counter, createNiwa } from "@niwa-labs/testing";
|
|
28
|
+
|
|
29
|
+
import { timerFired, timers } from "../../src/index.ts";
|
|
30
|
+
|
|
31
|
+
/** The id of the timer the host runs. It is the same in every process of the scenario. */
|
|
32
|
+
export const TIMER_ID = "tick";
|
|
33
|
+
|
|
34
|
+
/** The period of the timer, in milliseconds: short, so the scenario does not take long. */
|
|
35
|
+
export const EVERY_MS = 500;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The plugin of the scenario: it counts the firings of the timer.
|
|
39
|
+
*
|
|
40
|
+
* The counter lives in the home, so the count survives the death of the process that wrote it.
|
|
41
|
+
*/
|
|
42
|
+
function makePlugin(home: string, id: string) {
|
|
43
|
+
return plugin("ticks", (api) => {
|
|
44
|
+
api.on(timerFired(id), () => {
|
|
45
|
+
counter(home, `fired:${id}`).hit();
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The plugin of the scheduler, with the timer the command line asks for. */
|
|
51
|
+
function makeTimers(id: string, every: number, missed: MissedRule) {
|
|
52
|
+
return timers([{ id, every, missed }]);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (import.meta.main) {
|
|
56
|
+
const home = process.argv[2];
|
|
57
|
+
const id = process.argv[3] ?? TIMER_ID;
|
|
58
|
+
const every = Number(process.argv[4] ?? EVERY_MS);
|
|
59
|
+
const missed = (process.argv[5] ?? "once") as MissedRule;
|
|
60
|
+
if (!home) {
|
|
61
|
+
console.error("usage: bun missed-dues-host.ts <home> <timer-id> <every-ms> <missed>");
|
|
62
|
+
process.exit(2);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const niwa = createNiwa({ home });
|
|
66
|
+
niwa.use(makeTimers(id, every, missed));
|
|
67
|
+
niwa.use(makePlugin(home, id));
|
|
68
|
+
await niwa.serve();
|
|
69
|
+
|
|
70
|
+
process.on("SIGTERM", () => {
|
|
71
|
+
void niwa.close().then(() => process.exit(0));
|
|
72
|
+
});
|
|
73
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// A timer fires. With the host down at the due time, what happens after start is exactly what
|
|
2
|
+
// the timer's declared rule says, once.
|
|
3
|
+
//
|
|
4
|
+
// Each scenario runs against real host processes (fixtures/missed-dues-host.ts):
|
|
5
|
+
//
|
|
6
|
+
// 1. the first host runs a timer of 500 ms; it fires, and the handler of the trigger is woken
|
|
7
|
+
// 2. the host is killed (SIGKILL): a real crash, so nothing fires while it is down
|
|
8
|
+
// 3. the host stays down for more than two periods, so several dues pass
|
|
9
|
+
// 4. the second host starts on the same home and the rule of the timer decides:
|
|
10
|
+
// - "once": the dues that passed are one firing, written after the restart
|
|
11
|
+
// - "skip": the dues that passed are no firing at all
|
|
12
|
+
// and in both cases the timer goes on with its period.
|
|
13
|
+
//
|
|
14
|
+
// Only the public API is used: the entries of the packages and "@niwa-labs/testing".
|
|
15
|
+
|
|
16
|
+
import { expect, test } from "bun:test";
|
|
17
|
+
|
|
18
|
+
import { issueId, recordId, seq } from "@niwa-labs/core";
|
|
19
|
+
import { counter, eventually, spawnHost, tempHome, connectAsOwner } from "@niwa-labs/testing";
|
|
20
|
+
|
|
21
|
+
import { EVERY_MS, TIMER_ID } from "./fixtures/missed-dues-host.ts";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
|
|
24
|
+
const HOST_SCRIPT = fileURLToPath(new URL("./fixtures/missed-dues-host.ts", import.meta.url));
|
|
25
|
+
|
|
26
|
+
/** How long the host stays down: long enough for more than two dues to pass. */
|
|
27
|
+
const DOWN_MS = EVERY_MS * 2.5;
|
|
28
|
+
|
|
29
|
+
/** How long the test waits for the journal to hold what the rule of the timer decides. */
|
|
30
|
+
const SETTLE_MS = 30_000;
|
|
31
|
+
|
|
32
|
+
interface Firing {
|
|
33
|
+
readonly id: string;
|
|
34
|
+
readonly timer: string;
|
|
35
|
+
readonly due: number;
|
|
36
|
+
readonly at: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The firings in the journal of a home, read through the public API. */
|
|
40
|
+
async function readFirings(home: string): Promise<Firing[]> {
|
|
41
|
+
const client = await connectAsOwner(home);
|
|
42
|
+
try {
|
|
43
|
+
const records = await client.records.read();
|
|
44
|
+
return records
|
|
45
|
+
.filter((record) => record.type === "timer.fired")
|
|
46
|
+
.map((record) => {
|
|
47
|
+
const data = record.data as { timer: string; due: number; at: number };
|
|
48
|
+
return { id: record.id, timer: data.timer, due: data.due, at: data.at };
|
|
49
|
+
});
|
|
50
|
+
} finally {
|
|
51
|
+
await client.close().catch(() => {});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Run the crash scenario with one rule; return what the journal holds after the restart. */
|
|
56
|
+
async function crashAndRestart(rule: "once" | "skip"): Promise<{ firings: Firing[]; restartedAt: number; woken: number }> {
|
|
57
|
+
const home = await tempHome();
|
|
58
|
+
const hosts: Array<ReturnType<typeof spawnHost>> = [];
|
|
59
|
+
const args = [TIMER_ID, String(EVERY_MS), rule];
|
|
60
|
+
// What the rule of the timer decides about the dues that passed while the host was down.
|
|
61
|
+
const expected = rule === "once" ? 1 : 0;
|
|
62
|
+
try {
|
|
63
|
+
const first = spawnHost(HOST_SCRIPT, home.path, args);
|
|
64
|
+
hosts.push(first);
|
|
65
|
+
await first.ready();
|
|
66
|
+
await eventually(() => counter(home.path, `fired:${TIMER_ID}`).count() >= 2, 10_000, "the timer should fire");
|
|
67
|
+
|
|
68
|
+
await first.kill();
|
|
69
|
+
await Bun.sleep(DOWN_MS);
|
|
70
|
+
|
|
71
|
+
const restartedAt = Date.now();
|
|
72
|
+
const second = spawnHost(HOST_SCRIPT, home.path, args);
|
|
73
|
+
hosts.push(second);
|
|
74
|
+
await second.ready();
|
|
75
|
+
// Two periods after the restart: enough for the settled dues and for one on the old period.
|
|
76
|
+
await eventually(
|
|
77
|
+
async () => (await readFirings(home.path)).filter((f) => f.due > restartedAt).length >= 2,
|
|
78
|
+
SETTLE_MS,
|
|
79
|
+
"the timer should go on with its period after the restart",
|
|
80
|
+
);
|
|
81
|
+
// The journal is read when it holds what the rule of the timer decides, not after a fixed
|
|
82
|
+
// wait: a host under load writes its records later than a moment allows for.
|
|
83
|
+
await eventually(
|
|
84
|
+
async () => settledDues(await readFirings(home.path), restartedAt).length === expected,
|
|
85
|
+
SETTLE_MS,
|
|
86
|
+
`the journal should hold ${String(expected)} firing(s) for the dues missed while the host was down`,
|
|
87
|
+
);
|
|
88
|
+
const firings = await readFirings(home.path);
|
|
89
|
+
// The handler is woken once per firing of its own timer.
|
|
90
|
+
await eventually(
|
|
91
|
+
() => counter(home.path, `fired:${TIMER_ID}`).count() >= firings.length,
|
|
92
|
+
SETTLE_MS,
|
|
93
|
+
"the handler of the trigger should be woken by every firing",
|
|
94
|
+
);
|
|
95
|
+
return { firings, restartedAt, woken: counter(home.path, `fired:${TIMER_ID}`).count() };
|
|
96
|
+
} finally {
|
|
97
|
+
for (const host of hosts) await host.kill().catch(() => {});
|
|
98
|
+
await home.cleanup();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The firings written after the restart for dues that passed while the host was down. */
|
|
103
|
+
function settledDues(firings: Firing[], restartedAt: number): Firing[] {
|
|
104
|
+
return firings.filter((f) => f.at >= restartedAt && f.due <= restartedAt);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
test("timer, rule once: the dues missed while the host was down are one firing", async () => {
|
|
108
|
+
const { firings, restartedAt, woken } = await crashAndRestart("once");
|
|
109
|
+
const settled = settledDues(firings, restartedAt);
|
|
110
|
+
// More than two dues passed during the downtime, and exactly one firing stands for them.
|
|
111
|
+
expect(settled).toHaveLength(1);
|
|
112
|
+
expect(settled[0]?.timer).toBe(TIMER_ID);
|
|
113
|
+
// A due is written once: every firing has its own id, the hash of the timer and the due.
|
|
114
|
+
expect(new Set(firings.map((f) => f.id)).size).toBe(firings.length);
|
|
115
|
+
for (const f of firings) expect(f.id).toBe(issueId("firing", recordId(`timer:${TIMER_ID}:${f.due}`), []));
|
|
116
|
+
// The timer went on: its next firings are on the period counted from the settled one.
|
|
117
|
+
expect(firings.filter((f) => f.due > restartedAt).length).toBeGreaterThanOrEqual(2);
|
|
118
|
+
expect(woken).toBeGreaterThanOrEqual(firings.length);
|
|
119
|
+
}, 120_000);
|
|
120
|
+
|
|
121
|
+
test("timer, rule skip: the dues missed while the host was down are no firing", async () => {
|
|
122
|
+
const { firings, restartedAt } = await crashAndRestart("skip");
|
|
123
|
+
expect(settledDues(firings, restartedAt)).toHaveLength(0);
|
|
124
|
+
expect(new Set(firings.map((f) => f.id)).size).toBe(firings.length);
|
|
125
|
+
// The timer went on with its period.
|
|
126
|
+
expect(firings.filter((f) => f.due > restartedAt).length).toBeGreaterThanOrEqual(2);
|
|
127
|
+
}, 120_000);
|