@zingage/scheduling 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +184 -5
  2. package/dist/batcher.d.ts +231 -0
  3. package/dist/batcher.d.ts.map +1 -0
  4. package/dist/batcher.js +391 -0
  5. package/dist/batcher.js.map +1 -0
  6. package/dist/collapsed-task-creator.d.ts +235 -0
  7. package/dist/collapsed-task-creator.d.ts.map +1 -0
  8. package/dist/collapsed-task-creator.js +491 -0
  9. package/dist/collapsed-task-creator.js.map +1 -0
  10. package/dist/index.d.ts +6 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +5 -0
  13. package/dist/index.js.map +1 -1
  14. package/dist/logger.d.ts +16 -0
  15. package/dist/logger.d.ts.map +1 -0
  16. package/dist/logger.js +14 -0
  17. package/dist/logger.js.map +1 -0
  18. package/dist/pending-promises-tracker.d.ts +32 -0
  19. package/dist/pending-promises-tracker.d.ts.map +1 -0
  20. package/dist/pending-promises-tracker.js +60 -0
  21. package/dist/pending-promises-tracker.js.map +1 -0
  22. package/dist/performance-now.d.ts +14 -0
  23. package/dist/performance-now.d.ts.map +1 -0
  24. package/dist/performance-now.js +10 -0
  25. package/dist/performance-now.js.map +1 -0
  26. package/dist/scheduling-contract-error.d.ts +9 -0
  27. package/dist/scheduling-contract-error.d.ts.map +1 -0
  28. package/dist/scheduling-contract-error.js +9 -0
  29. package/dist/scheduling-contract-error.js.map +1 -0
  30. package/dist/wrap-with-task-collapsing.d.ts +30 -0
  31. package/dist/wrap-with-task-collapsing.d.ts.map +1 -0
  32. package/dist/wrap-with-task-collapsing.js +80 -0
  33. package/dist/wrap-with-task-collapsing.js.map +1 -0
  34. package/package.json +10 -4
  35. package/src/batcher.ts +614 -0
  36. package/src/collapsed-task-creator.ts +774 -0
  37. package/src/index.ts +22 -0
  38. package/src/logger.ts +32 -0
  39. package/src/pending-promises-tracker.ts +62 -0
  40. package/src/performance-now.ts +21 -0
  41. package/src/scheduling-contract-error.ts +8 -0
  42. package/src/wrap-with-task-collapsing.ts +103 -0
package/src/index.ts CHANGED
@@ -10,3 +10,25 @@ export {
10
10
  } from "./time-slicing.js";
11
11
  export { timeSlicedSort } from "./time-sliced-sort.js";
12
12
  export { timeSlicedFind, timeSlicedSome } from "./time-sliced-search.js";
13
+ export {
14
+ CollapsedTaskCreator,
15
+ type ScheduleTasks,
16
+ type SharedTaskView,
17
+ type TaskRequestOutcome,
18
+ type TaskRequestOutcomes,
19
+ type TaskStartReason,
20
+ } from "./collapsed-task-creator.js";
21
+ export { wrapWithTaskCollapsing } from "./wrap-with-task-collapsing.js";
22
+ export {
23
+ Batcher,
24
+ DEFAULT_MAX_BATCH_SIZE,
25
+ type BatchHandle,
26
+ type BatchItem,
27
+ type BatchOptions,
28
+ type DispatchedItem,
29
+ type DispatchInfo,
30
+ type Enqueued,
31
+ } from "./batcher.js";
32
+ export { PendingPromisesTracker } from "./pending-promises-tracker.js";
33
+ export { SchedulingContractError } from "./scheduling-contract-error.js";
34
+ export type { Logger, SchedulingComponentName } from "./logger.js";
package/src/logger.ts ADDED
@@ -0,0 +1,32 @@
1
+ import { default as debug } from "debug";
2
+
3
+ /** The components in this package that write log lines. */
4
+ export type SchedulingComponentName = "batcher" | "collapsed-task-creator";
5
+
6
+ /**
7
+ * The signature of a custom log function. `Batcher` and
8
+ * `wrapWithTaskCollapsing` accept one, and call it when they log a message.
9
+ *
10
+ * A logger that accepts more component names, such as a logger shared with
11
+ * other packages, is also a valid `Logger`.
12
+ */
13
+ export type Logger = (
14
+ component: SchedulingComponentName,
15
+ level: "trace" | "debug" | "info" | "warn" | "error" | "fatal",
16
+ message: string,
17
+ data?: unknown,
18
+ ) => void;
19
+
20
+ /** A logger that writes to the `debug` namespace `@zingage/scheduling:<name>`. */
21
+ function debugLogger(name: SchedulingComponentName): Logger {
22
+ const write = debug(`@zingage/scheduling:${name}`);
23
+ return (_, level, message, data) => {
24
+ write(`(${level}) ${message} %O`, data);
25
+ };
26
+ }
27
+
28
+ /** The default logger of each component. */
29
+ export const defaultLoggersByComponent = {
30
+ batcher: debugLogger("batcher"),
31
+ "collapsed-task-creator": debugLogger("collapsed-task-creator"),
32
+ } satisfies Record<SchedulingComponentName, Logger>;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Tracks promises until they settle, so that an owner's `close` can wait for
3
+ * the work it accepted.
4
+ *
5
+ * Each tracked promise leaves the tracker when it settles. Tracking never
6
+ * creates an unhandled rejection: the tracker observes a rejection, but the
7
+ * caller still owns the promise and its rejection.
8
+ *
9
+ * The tracker has no closed state. Each owner decides what new work does
10
+ * after its own `close` starts, and in what order it drains its trackers.
11
+ */
12
+ export class PendingPromisesTracker {
13
+ readonly #pending = new Set<Promise<unknown>>();
14
+
15
+ /** The number of tracked promises that have not settled yet. */
16
+ get size(): number {
17
+ return this.#pending.size;
18
+ }
19
+
20
+ /** Tracks `promise` until it settles, and returns it unchanged. */
21
+ // oxlint-disable-next-line typescript/promise-function-async -- Returns the same promise it tracks.
22
+ track<T>(promise: Promise<T>): Promise<T> {
23
+ this.#pending.add(promise);
24
+ const untrack = () => {
25
+ this.#pending.delete(promise);
26
+ };
27
+ // oxlint-disable-next-line no-void -- Untracks on settle; the caller owns the promise and its rejection.
28
+ void promise.then(untrack, untrack);
29
+ return promise;
30
+ }
31
+
32
+ /**
33
+ * Calls `start` and tracks its result. The promise is tracked before
34
+ * `start` runs, so a `drain` that `start` itself triggers synchronously
35
+ * still waits for it. A synchronous throw from `start` becomes a rejection.
36
+ */
37
+ // oxlint-disable-next-line typescript/promise-function-async -- Returns the tracked promise, and must call start synchronously.
38
+ run<T>(start: () => Promise<T>): Promise<T> {
39
+ const { promise, resolve, reject } = Promise.withResolvers<T>();
40
+ // oxlint-disable-next-line no-void -- track returns the same promise, which run returns.
41
+ void this.track(promise);
42
+ try {
43
+ resolve(start());
44
+ } catch (error) {
45
+ reject(error);
46
+ }
47
+ return promise;
48
+ }
49
+
50
+ /**
51
+ * Resolves once no tracked promise is pending, including promises tracked
52
+ * while it waits. It loops because settling work can start more work, for
53
+ * example a producer that reads other keys from its own wrapper. It never
54
+ * rejects.
55
+ */
56
+ async drain(): Promise<void> {
57
+ // oxlint-disable-next-line zingage/no-restricted-syntax -- Loops until nothing is pending, because settling work can track more.
58
+ while (this.#pending.size > 0) {
59
+ await Promise.allSettled(this.#pending);
60
+ }
61
+ }
62
+ }
@@ -0,0 +1,21 @@
1
+ import type { Tagged } from "type-fest";
2
+ import { instantiateTaggedType } from "type-party/runtime/tagged-types.js";
3
+
4
+ /**
5
+ * A reading of `performance.now()`, in milliseconds since the time origin.
6
+ *
7
+ * The tag keeps other numbers out of a parameter that expects a reading of
8
+ * this clock. Examples are a `Date.now()` time, which uses a different
9
+ * origin, and a duration.
10
+ */
11
+ export type PerformanceNow = Tagged<number, "PerformanceNow">;
12
+
13
+ /** Reads `performance.now()`. */
14
+ export function performanceNow(): PerformanceNow {
15
+ return instantiateTaggedType<PerformanceNow>(performance.now());
16
+ }
17
+
18
+ /** The milliseconds that passed between `start` and now. */
19
+ export function msSince(start: PerformanceNow): number {
20
+ return performance.now() - start;
21
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Reports that a caller broke a contract of this package. Examples are a
3
+ * `dispatch` or `schedule` callback that returns the wrong number of results,
4
+ * and a `schedule` callback that requests a key it is starting a task for.
5
+ */
6
+ export class SchedulingContractError extends Error {
7
+ override readonly name: string = "SchedulingContractError";
8
+ }
@@ -0,0 +1,103 @@
1
+ import {
2
+ CollapsedTaskCreator,
3
+ type TaskStartReason,
4
+ } from "./collapsed-task-creator.js";
5
+ import { defaultLoggersByComponent, type Logger } from "./logger.js";
6
+
7
+ // The creator reserves `undefined` for inputs that never share work, but here
8
+ // `undefined` is an ordinary key. So it stands in for `undefined` with a
9
+ // key that no caller can produce.
10
+ const undefinedKey = Symbol("undefined key");
11
+
12
+ /**
13
+ * The "started" log line for each reason a call starts a task. A call here
14
+ * has no signal, so its task is never cancelled, and its key is never
15
+ * `undefined` for the creator. But every reason has a line, so the log stays
16
+ * accurate if that changes.
17
+ */
18
+ const startedMessages: Record<TaskStartReason, string> = {
19
+ noPendingTask:
20
+ "started new task b/c there was no in-progress task for these args",
21
+ pendingTaskTooOld:
22
+ "started new task; there _was_ an in-progress one, but it's too old",
23
+ pendingTaskCancelled:
24
+ "started new task; there _was_ an in-progress one, but it was cancelled",
25
+ noKey: "started new task b/c these args have no key",
26
+ };
27
+
28
+ /**
29
+ * Wraps a function that starts a task and returns a promise for its result.
30
+ * The returned function behaves like the original, except that a call reuses
31
+ * the promise of an earlier call if and only if: 1) the calls have the same
32
+ * key, which `makeKey` derives from their arguments [a la memoize]; 2) less
33
+ * than `collapseTasksMs` milliseconds have passed since the earlier call
34
+ * started its task [a la throttle]; and 3) that task is still running
35
+ * [unique]. Otherwise, the call calls through to the original function. So it
36
+ * is sort of a combination of memoize, throttle, and promise chaining.
37
+ *
38
+ * It runs on {@link CollapsedTaskCreator}: each call is one task request,
39
+ * whose input carries the call's arguments and key. See that class for why
40
+ * these semantics are useful.
41
+ *
42
+ * It does not support task cancellation. A call takes no `AbortSignal`, so no
43
+ * individual caller can cancel a task that other callers share. Users who
44
+ * need cancellation should use `CollapsedTaskCreator` directly.
45
+ *
46
+ * @param taskCreator The task creation function
47
+ * @param collapseTasksMs The number of milliseconds up until which, if a caller
48
+ * tries to start the same task while a previous version of the task is still
49
+ * running, the promise for the result of the currently-running task will be
50
+ * returned instead.
51
+ * @param makeKey A function for converting the arguments passed to the task
52
+ * creation into a cache key, like in your standard memoize implementation.
53
+ * @param logger Receives the trace lines that each call writes.
54
+ */
55
+ export function wrapWithTaskCollapsing<Args extends unknown[], Key, Result>(
56
+ taskCreator: (...args: Args) => Promise<Result>,
57
+ collapseTasksMs: number,
58
+ makeKey: (args: Args) => Key,
59
+ logger: Logger = defaultLoggersByComponent["collapsed-task-creator"],
60
+ ) {
61
+ const logTrace = logger.bind(null, "collapsed-task-creator", "trace");
62
+
63
+ // The creator's input carries the key, so `makeKey` runs once per call and
64
+ // every log line below can include the key.
65
+ const creator = new CollapsedTaskCreator({
66
+ collapseTasksMs,
67
+ makeKey: ({ taskKey }: { args: Args; taskKey: Key }) =>
68
+ taskKey === undefined ? undefinedKey : taskKey,
69
+ schedule: (toStart) =>
70
+ toStart.map(({ input: { args, taskKey }, startReason }) => {
71
+ logTrace(startedMessages[startReason], args);
72
+ const taskRes = taskCreator(...args);
73
+ logTrace("pending = new state for taskKey/args", { args, taskKey });
74
+ return {
75
+ result: taskRes.finally(() => {
76
+ logTrace("completed = new state for taskKey/args", {
77
+ args,
78
+ taskKey,
79
+ });
80
+ }),
81
+ handle: undefined,
82
+ };
83
+ }),
84
+ });
85
+
86
+ return async (...args: Args) => {
87
+ const taskKey = makeKey(args);
88
+ logTrace("requested = new state for taskKey/args", { args, taskKey });
89
+
90
+ const [{ result, rode }] = creator.startOrRideTasks([
91
+ { input: { args, taskKey } },
92
+ ]);
93
+
94
+ if (rode) {
95
+ logTrace(
96
+ "reusing result from prior, still-in-progress run of task for args/taskKey",
97
+ { args, taskKey },
98
+ );
99
+ }
100
+
101
+ return result;
102
+ };
103
+ }