@mark1russell7/algebra 0.8.2 → 0.8.3

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/README.md CHANGED
@@ -61,6 +61,25 @@ const problems = replay(CONNECTION_MACHINE, recorded, { machine: CONNECTION_MACH
61
61
  // for example ["c1: app.machine.connection has no transition from OPEN on open to OPEN"]
62
62
  ```
63
63
 
64
+ ## The clock
65
+
66
+ `@mark1russell7/algebra/clock` gives the clock of a runtime and a fake clock for tests. The entry imports nothing: no `node:` module, no zod and no other package. Thus a client in a browser can use it. The service and collections read time through it.
67
+
68
+ | Export | What it does |
69
+ | --- | --- |
70
+ | `Clock` | `now()` gives the monotonic time in milliseconds. `after(ms, run)` starts `run` after `ms` and gives its `Cancel`. |
71
+ | `platformClock({ unref })` | A clock on `performance.now()` and `setTimeout`. With `unref: true`, its timers do not keep a Node process alive. |
72
+ | `realClock` | The clock of the platform with `unref: true`. |
73
+ | `fakeClock(start)` | A clock that moves only on `advance(ms)`. `block(ms)` moves it and starts no timer, as a blocked event loop does. `pending` counts the live timers. |
74
+
75
+ ```ts
76
+ import { fakeClock } from "@mark1russell7/algebra/clock";
77
+
78
+ const clock = fakeClock();
79
+ clock.after(30_000, () => cache.sweep());
80
+ await clock.advance(30_000); // the sweep runs, at 30 s exactly
81
+ ```
82
+
64
83
  ## Installation
65
84
 
66
85
  ```sh
@@ -0,0 +1,50 @@
1
+ //#region src/clock.d.ts
2
+ /**
3
+ * This function stops a timer that `Clock.after` started. A second use does nothing. A clock of
4
+ * the platform also gives `unref`: after it, the timer does not keep a Node process alive.
5
+ */
6
+ export type Cancel = (() => void) & {
7
+ readonly unref?: (() => void) | undefined;
8
+ };
9
+ /**
10
+ * A clock gives the monotonic time in milliseconds, and it starts a function after a delay. The
11
+ * runtime reads time only through a clock. Thus a test can give a fake clock, and the timing of
12
+ * the runtime is then exact and repeatable.
13
+ */
14
+ export interface Clock {
15
+ /** This method gives the monotonic time, in milliseconds. A step of the wall clock does not move it. */
16
+ now(): number;
17
+ /** This method starts `run` after `ms` milliseconds, and gives the function that stops it. */
18
+ after(ms: number, run: () => void): Cancel;
19
+ }
20
+ /** These options make a clock of the platform. */
21
+ export interface PlatformClockOptions {
22
+ /** True makes each timer not keep a Node process alive. The default is false, as with `setTimeout`. */
23
+ readonly unref?: boolean | undefined;
24
+ }
25
+ /**
26
+ * This function makes a clock of the platform: `performance.now()` and `setTimeout`. Each cancel
27
+ * that it gives also has `unref`. A delay longer than `setTimeout` takes waits in steps.
28
+ */
29
+ export declare const platformClock: (options?: PlatformClockOptions) => Clock;
30
+ /**
31
+ * This clock reads `performance.now()` and uses `setTimeout`. Its timers do not keep a Node
32
+ * process alive, thus a timer that is not stopped cannot stop the exit of the process.
33
+ */
34
+ export declare const realClock: Clock;
35
+ /** A fake clock moves only when a test tells it to. */
36
+ export interface FakeClock extends Clock {
37
+ /** This method moves the clock forward by `ms`, and it starts each timer that comes due, in sequence. */
38
+ advance(ms: number): Promise<void>;
39
+ /**
40
+ * This method moves the clock forward by `ms` and starts no timer, as a blocked event loop does.
41
+ * The next `advance` then starts each timer that came due during the block, late.
42
+ */
43
+ block(ms: number): void;
44
+ /** This count is the number of timers that are not stopped and not called. */
45
+ readonly pending: number;
46
+ }
47
+ /** This function makes a fake clock. Its time starts at `start` milliseconds. */
48
+ export declare const fakeClock: (start?: number) => FakeClock;
49
+ //#endregion
50
+ //# sourceMappingURL=clock.d.ts.map
package/build/clock.js ADDED
@@ -0,0 +1,89 @@
1
+ //#region src/clock.ts
2
+ /** This function gives the monotonic time: `performance.now()`, or `Date.now()` on a platform without `performance`. */
3
+ const monotonic = () => {
4
+ const performance = globalThis.performance;
5
+ return performance === void 0 ? Date.now() : performance.now();
6
+ };
7
+ /** This delay is the longest that `setTimeout` takes, in milliseconds. A longer delay starts the function after 1 ms. */
8
+ const LONGEST_DELAY = 2147483647;
9
+ /**
10
+ * This function makes a clock of the platform: `performance.now()` and `setTimeout`. Each cancel
11
+ * that it gives also has `unref`. A delay longer than `setTimeout` takes waits in steps.
12
+ */
13
+ const platformClock = (options = {}) => ({
14
+ now: monotonic,
15
+ after(ms, run) {
16
+ let unrefed = options.unref === true;
17
+ const arm = (left) => {
18
+ const step = left > LONGEST_DELAY ? setTimeout(() => timer = arm(left - LONGEST_DELAY), LONGEST_DELAY) : setTimeout(run, Math.max(0, left));
19
+ if (unrefed) step.unref?.();
20
+ return step;
21
+ };
22
+ let timer = arm(ms);
23
+ const unref = () => {
24
+ unrefed = true;
25
+ timer.unref?.();
26
+ };
27
+ return Object.assign(() => clearTimeout(timer), { unref });
28
+ }
29
+ });
30
+ /**
31
+ * This clock reads `performance.now()` and uses `setTimeout`. Its timers do not keep a Node
32
+ * process alive, thus a timer that is not stopped cannot stop the exit of the process.
33
+ */
34
+ const realClock = /* @__PURE__ */ platformClock({ unref: true });
35
+ /** This function lets the promises that are ready continue, before the clock moves again. */
36
+ const settle = async () => {
37
+ for (let turn = 0; turn < 64; turn += 1) await Promise.resolve();
38
+ };
39
+ /** This function makes a fake clock. Its time starts at `start` milliseconds. */
40
+ const fakeClock = (start = 0) => {
41
+ let now = start;
42
+ let sequence = 0;
43
+ const timers = [];
44
+ const due = (end) => {
45
+ let best;
46
+ for (const timer of timers) if (timer.live && timer.at <= end && (best === void 0 || timer.at < best.at || timer.at === best.at && timer.order < best.order)) best = timer;
47
+ return best;
48
+ };
49
+ return {
50
+ now: () => now,
51
+ after(ms, run) {
52
+ const timer = {
53
+ at: now + Math.max(0, ms),
54
+ order: sequence++,
55
+ run,
56
+ live: true
57
+ };
58
+ timers.push(timer);
59
+ return () => {
60
+ timer.live = false;
61
+ };
62
+ },
63
+ async advance(ms) {
64
+ const end = now + Math.max(0, ms);
65
+ await settle();
66
+ for (;;) {
67
+ const timer = due(end);
68
+ if (timer === void 0) break;
69
+ timer.live = false;
70
+ now = Math.max(now, timer.at);
71
+ timer.run();
72
+ await settle();
73
+ }
74
+ now = Math.max(now, end);
75
+ for (let at = timers.length - 1; at >= 0; at -= 1) if (!timers[at].live) timers.splice(at, 1);
76
+ await settle();
77
+ },
78
+ block(ms) {
79
+ now += Math.max(0, ms);
80
+ },
81
+ get pending() {
82
+ return timers.filter((timer) => timer.live).length;
83
+ }
84
+ };
85
+ };
86
+ //#endregion
87
+ export { fakeClock, platformClock, realClock };
88
+
89
+ //# sourceMappingURL=clock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clock.js","names":[],"sources":["../src/clock.ts"],"sourcesContent":["// @mark1russell7/algebra/clock: the clock of a runtime, and a fake clock for tests. It imports\n// nothing: no `node:` module, no zod and no other package. Thus a client in a browser can use it.\n// The service gives this clock again as @mark1russell7/service/clock.\n\n/**\n * This function stops a timer that `Clock.after` started. A second use does nothing. A clock of\n * the platform also gives `unref`: after it, the timer does not keep a Node process alive.\n */\nexport type Cancel = (() => void) & { readonly unref?: (() => void) | undefined };\n\n/**\n * A clock gives the monotonic time in milliseconds, and it starts a function after a delay. The\n * runtime reads time only through a clock. Thus a test can give a fake clock, and the timing of\n * the runtime is then exact and repeatable.\n */\nexport interface Clock {\n /** This method gives the monotonic time, in milliseconds. A step of the wall clock does not move it. */\n now(): number;\n /** This method starts `run` after `ms` milliseconds, and gives the function that stops it. */\n after(ms: number, run: () => void): Cancel;\n}\n\n/** These options make a clock of the platform. */\nexport interface PlatformClockOptions {\n /** True makes each timer not keep a Node process alive. The default is false, as with `setTimeout`. */\n readonly unref?: boolean | undefined;\n}\n\n/** This function gives the monotonic time: `performance.now()`, or `Date.now()` on a platform without `performance`. */\nconst monotonic = (): number => {\n const performance = (globalThis as { performance?: { now(): number } }).performance;\n return performance === undefined ? Date.now() : performance.now();\n};\n\n/** This delay is the longest that `setTimeout` takes, in milliseconds. A longer delay starts the function after 1 ms. */\nconst LONGEST_DELAY = 0x7fffffff;\n\n/**\n * This function makes a clock of the platform: `performance.now()` and `setTimeout`. Each cancel\n * that it gives also has `unref`. A delay longer than `setTimeout` takes waits in steps.\n */\nexport const platformClock = (options: PlatformClockOptions = {}): Clock => ({\n now: monotonic,\n after(ms, run) {\n let unrefed = options.unref === true;\n const arm = (left: number): ReturnType<typeof setTimeout> => {\n const step =\n left > LONGEST_DELAY ? setTimeout(() => (timer = arm(left - LONGEST_DELAY)), LONGEST_DELAY) : setTimeout(run, Math.max(0, left));\n if (unrefed) (step as { unref?: () => void }).unref?.();\n return step;\n };\n let timer = arm(ms);\n const unref = (): void => {\n unrefed = true;\n (timer as { unref?: () => void }).unref?.();\n };\n return Object.assign(() => clearTimeout(timer), { unref });\n },\n});\n\n/**\n * This clock reads `performance.now()` and uses `setTimeout`. Its timers do not keep a Node\n * process alive, thus a timer that is not stopped cannot stop the exit of the process.\n */\nexport const realClock: Clock = /* @__PURE__ */ platformClock({ unref: true });\n\n/** A fake clock moves only when a test tells it to. */\nexport interface FakeClock extends Clock {\n /** This method moves the clock forward by `ms`, and it starts each timer that comes due, in sequence. */\n advance(ms: number): Promise<void>;\n /**\n * This method moves the clock forward by `ms` and starts no timer, as a blocked event loop does.\n * The next `advance` then starts each timer that came due during the block, late.\n */\n block(ms: number): void;\n /** This count is the number of timers that are not stopped and not called. */\n readonly pending: number;\n}\n\n/** This function lets the promises that are ready continue, before the clock moves again. */\nconst settle = async (): Promise<void> => {\n for (let turn = 0; turn < 64; turn += 1) await Promise.resolve();\n};\n\n/** This function makes a fake clock. Its time starts at `start` milliseconds. */\nexport const fakeClock = (start = 0): FakeClock => {\n let now = start;\n let sequence = 0;\n const timers: Array<{ at: number; order: number; run: () => void; live: boolean }> = [];\n const due = (end: number) => {\n let best: (typeof timers)[number] | undefined;\n for (const timer of timers)\n if (timer.live && timer.at <= end && (best === undefined || timer.at < best.at || (timer.at === best.at && timer.order < best.order)))\n best = timer;\n return best;\n };\n return {\n now: () => now,\n after(ms, run): Cancel {\n const timer = { at: now + Math.max(0, ms), order: sequence++, run, live: true };\n timers.push(timer);\n return () => {\n timer.live = false;\n };\n },\n async advance(ms) {\n // a monotonic clock does not go back\n const end = now + Math.max(0, ms);\n await settle();\n for (;;) {\n const timer = due(end);\n if (timer === undefined) break;\n timer.live = false;\n // a timer that came due during a block runs late, at the time of the clock\n now = Math.max(now, timer.at);\n timer.run();\n await settle();\n }\n now = Math.max(now, end);\n for (let at = timers.length - 1; at >= 0; at -= 1) if (!timers[at]!.live) timers.splice(at, 1);\n await settle();\n },\n block(ms) {\n now += Math.max(0, ms);\n },\n get pending() {\n return timers.filter((timer) => timer.live).length;\n },\n };\n};\n"],"mappings":";;AA6BA,MAAM,kBAA0B;CAC9B,MAAM,cAAe,WAAmD;CACxE,OAAO,gBAAgB,KAAA,IAAY,KAAK,IAAI,IAAI,YAAY,IAAI;AAClE;;AAGA,MAAM,gBAAgB;;;;;AAMtB,MAAa,iBAAiB,UAAgC,CAAC,OAAc;CAC3E,KAAK;CACL,MAAM,IAAI,KAAK;EACb,IAAI,UAAU,QAAQ,UAAU;EAChC,MAAM,OAAO,SAAgD;GAC3D,MAAM,OACJ,OAAO,gBAAgB,iBAAkB,QAAQ,IAAI,OAAO,aAAa,GAAI,aAAa,IAAI,WAAW,KAAK,KAAK,IAAI,GAAG,IAAI,CAAC;GACjI,IAAI,SAAS,KAAiC,QAAQ;GACtD,OAAO;EACT;EACA,IAAI,QAAQ,IAAI,EAAE;EAClB,MAAM,cAAoB;GACxB,UAAU;GACV,MAAkC,QAAQ;EAC5C;EACA,OAAO,OAAO,aAAa,aAAa,KAAK,GAAG,EAAE,MAAM,CAAC;CAC3D;AACF;;;;;AAMA,MAAa,YAAmC,8BAAc,EAAE,OAAO,KAAK,CAAC;;AAgB7E,MAAM,SAAS,YAA2B;CACxC,KAAK,IAAI,OAAO,GAAG,OAAO,IAAI,QAAQ,GAAG,MAAM,QAAQ,QAAQ;AACjE;;AAGA,MAAa,aAAa,QAAQ,MAAiB;CACjD,IAAI,MAAM;CACV,IAAI,WAAW;CACf,MAAM,SAA+E,CAAC;CACtF,MAAM,OAAO,QAAgB;EAC3B,IAAI;EACJ,KAAK,MAAM,SAAS,QAClB,IAAI,MAAM,QAAQ,MAAM,MAAM,QAAQ,SAAS,KAAA,KAAa,MAAM,KAAK,KAAK,MAAO,MAAM,OAAO,KAAK,MAAM,MAAM,QAAQ,KAAK,QAC5H,OAAO;EACX,OAAO;CACT;CACA,OAAO;EACL,WAAW;EACX,MAAM,IAAI,KAAa;GACrB,MAAM,QAAQ;IAAE,IAAI,MAAM,KAAK,IAAI,GAAG,EAAE;IAAG,OAAO;IAAY;IAAK,MAAM;GAAK;GAC9E,OAAO,KAAK,KAAK;GACjB,aAAa;IACX,MAAM,OAAO;GACf;EACF;EACA,MAAM,QAAQ,IAAI;GAEhB,MAAM,MAAM,MAAM,KAAK,IAAI,GAAG,EAAE;GAChC,MAAM,OAAO;GACb,SAAS;IACP,MAAM,QAAQ,IAAI,GAAG;IACrB,IAAI,UAAU,KAAA,GAAW;IACzB,MAAM,OAAO;IAEb,MAAM,KAAK,IAAI,KAAK,MAAM,EAAE;IAC5B,MAAM,IAAI;IACV,MAAM,OAAO;GACf;GACA,MAAM,KAAK,IAAI,KAAK,GAAG;GACvB,KAAK,IAAI,KAAK,OAAO,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC,OAAO,GAAG,CAAE,MAAM,OAAO,OAAO,IAAI,CAAC;GAC7F,MAAM,OAAO;EACf;EACA,MAAM,IAAI;GACR,OAAO,KAAK,IAAI,GAAG,EAAE;EACvB;EACA,IAAI,UAAU;GACZ,OAAO,OAAO,QAAQ,UAAU,MAAM,IAAI,CAAC,CAAC;EAC9C;CACF;AACF"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/algebra",
4
- "version": "0.8.2",
4
+ "version": "0.8.3",
5
5
  "description": "State machines as data, and the timer algebra over them: closed forms for a machine's timers in exact rationals, detection as the first live timer, recovery after a stall, and the replay of a trace.",
6
6
  "keywords": [
7
7
  "state-machine",
@@ -33,6 +33,10 @@
33
33
  "types": "./build/index.d.ts",
34
34
  "default": "./build/index.js"
35
35
  },
36
+ "./clock": {
37
+ "types": "./build/clock.d.ts",
38
+ "default": "./build/clock.js"
39
+ },
36
40
  "./replay": {
37
41
  "types": "./build/replay.d.ts",
38
42
  "default": "./build/replay.js"