@bridgebrew/scheduler 0.0.0-stage → 0.0.1
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/browser/browser.tsx +17 -0
- package/browser/scheduled-screen.tsx +1327 -0
- package/browser/tsconfig.json +14 -0
- package/core.ts +580 -0
- package/docs/en/index.mdx +105 -0
- package/docs/en/meta.json +4 -0
- package/docs/meta.json +4 -0
- package/package.json +332 -4
- package/rules.ts +122 -0
- package/server.ts +201 -0
- package/tasks.ts +843 -0
- package/tsconfig.json +1 -0
- package/view.ts +98 -0
- package/README.md +0 -3
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"//": "The page (its tests are typed with the tests project): its services through the Bridge checkout this repository links (../../bridge), the contracts of the plugins it uses from their folders here.",
|
|
3
|
+
"extends": "../.bridge/tsconfig.browser.json",
|
|
4
|
+
"include": [
|
|
5
|
+
".",
|
|
6
|
+
"../../bridge/packages/browser-boot/src/workspace.d.ts",
|
|
7
|
+
"../../bridge/vendor/types/client-build-environment.d.ts",
|
|
8
|
+
"../../shell/browser/shell.d.ts"
|
|
9
|
+
],
|
|
10
|
+
"exclude": [
|
|
11
|
+
"./**/*.test.ts",
|
|
12
|
+
"./**/*.test.tsx"
|
|
13
|
+
]
|
|
14
|
+
}
|
package/core.ts
ADDED
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
// The scheduler without Cordis (research-012): entries over a `Store`, fired on a `Clock`, delivered to their owner's
|
|
2
|
+
// handler. The plugin (`server.ts`) gives it the storage domain, the real clock, node events and the `timeZone`
|
|
3
|
+
// setting; tests give it a fake clock.
|
|
4
|
+
// Delivery is at least once: an occurrence is marked fired only once its owner's handler resolved; a throw, or no answer
|
|
5
|
+
// within the deadline (its `signal` aborted, a later answer ignored), retries it after 1, 5, 30, then every 60 minutes;
|
|
6
|
+
// an owner with no handler (not loaded) has its entries wait, delivered as soon as it registers one. Owners are
|
|
7
|
+
// delivered independently: one owner's due entries go one after another, so a hung handler holds only its own owner,
|
|
8
|
+
// and that only until its deadline. One tick runs at a time; a tick asked for meanwhile runs after it.
|
|
9
|
+
import { z } from 'zod';
|
|
10
|
+
import { compile, floating, rule, type Compiled, type Rule } from './rules.ts';
|
|
11
|
+
|
|
12
|
+
const LATE_MS = 60_000;
|
|
13
|
+
/** Between ticks however the timer fares: Node's timers stop while a Mac sleeps, the wall clock does not. */
|
|
14
|
+
export const HEARTBEAT_MS = 30_000;
|
|
15
|
+
/** The longest a `setTimeout` waits (2³¹−1 ms); a later fire re-arms. */
|
|
16
|
+
export const TIMER_MAX = 2_147_483_647;
|
|
17
|
+
/** A fired one-shot entry is kept this long (derived state, a past view), then purged. */
|
|
18
|
+
export const KEEP_FIRED_MS = 30 * 86_400_000;
|
|
19
|
+
/** `'all'` catch-up delivers at most this many missed occurrences of an entry; the rest are counted in `missed`. */
|
|
20
|
+
const CATCH_UP_MAX = 100;
|
|
21
|
+
const RETRY_MS = [60_000, 300_000, 1_800_000, 3_600_000];
|
|
22
|
+
/** How long a handler has to answer a delivery, unless `deadline` says otherwise. */
|
|
23
|
+
export const DEADLINE_MS = 600_000;
|
|
24
|
+
|
|
25
|
+
const reference = z.strictObject({
|
|
26
|
+
domain: z.string().min(1).max(200),
|
|
27
|
+
id: z.string().min(1).max(200),
|
|
28
|
+
});
|
|
29
|
+
export type Reference = z.infer<typeof reference>;
|
|
30
|
+
const catchUp = z.enum(['last', 'all', 'skip']);
|
|
31
|
+
const instant = z.iso.datetime({ offset: true });
|
|
32
|
+
const data = z
|
|
33
|
+
.unknown()
|
|
34
|
+
.refine(
|
|
35
|
+
(value) => value === undefined || (JSON.stringify(value) ?? '').length <= 4096,
|
|
36
|
+
'data takes at most 4 KiB of JSON',
|
|
37
|
+
)
|
|
38
|
+
.optional();
|
|
39
|
+
|
|
40
|
+
/** What `schedule` takes. */
|
|
41
|
+
const scheduleInput = z
|
|
42
|
+
.strictObject({
|
|
43
|
+
ref: reference,
|
|
44
|
+
key: z.string().min(1).max(100).optional(),
|
|
45
|
+
node: z.string().min(1).optional(),
|
|
46
|
+
for: z.string().min(1).optional(),
|
|
47
|
+
at: instant.optional(),
|
|
48
|
+
rule: rule.optional(),
|
|
49
|
+
catchUp: catchUp.optional(),
|
|
50
|
+
label: z.string().max(200).optional(),
|
|
51
|
+
data,
|
|
52
|
+
})
|
|
53
|
+
.refine(
|
|
54
|
+
(input) => (input.at === undefined) !== (input.rule === undefined),
|
|
55
|
+
'give exactly one of at and rule',
|
|
56
|
+
)
|
|
57
|
+
.refine(
|
|
58
|
+
(input) => input.catchUp === undefined || input.rule !== undefined,
|
|
59
|
+
'catchUp is for a rule',
|
|
60
|
+
);
|
|
61
|
+
export type ScheduleInput = z.input<typeof scheduleInput>;
|
|
62
|
+
|
|
63
|
+
/** An entry as stored (the domain's value). */
|
|
64
|
+
export const entryValue = z.strictObject({
|
|
65
|
+
owner: z.string(),
|
|
66
|
+
ref: reference,
|
|
67
|
+
key: z.string(),
|
|
68
|
+
node: z.string(),
|
|
69
|
+
for: z.string().optional(),
|
|
70
|
+
at: z.string().optional(),
|
|
71
|
+
rule: rule.optional(),
|
|
72
|
+
catchUp: catchUp.optional(),
|
|
73
|
+
label: z.string().optional(),
|
|
74
|
+
data,
|
|
75
|
+
/** The next fire (ISO, UTC); absent once done. */
|
|
76
|
+
next: z.string().optional(),
|
|
77
|
+
/** The last delivery. */
|
|
78
|
+
firedAt: z.string().optional(),
|
|
79
|
+
/** Failed deliveries of the current occurrence, and when the next try is. */
|
|
80
|
+
attempts: z.number().int().optional(),
|
|
81
|
+
retryAt: z.string().optional(),
|
|
82
|
+
createdAt: z.string(),
|
|
83
|
+
});
|
|
84
|
+
export type EntryValue = z.infer<typeof entryValue>;
|
|
85
|
+
export type Entry = EntryValue & { id: string };
|
|
86
|
+
|
|
87
|
+
/** What the owner's handler gets. */
|
|
88
|
+
export interface Due {
|
|
89
|
+
entry: Entry;
|
|
90
|
+
/** The occurrence delivered (ISO). */
|
|
91
|
+
scheduledFor: string;
|
|
92
|
+
firedAt: string;
|
|
93
|
+
/** Delivered more than a minute after `scheduledFor` (Bridge was off, asleep, or the owner was not loaded). */
|
|
94
|
+
late: boolean;
|
|
95
|
+
/** Occurrences skipped before this one (`catchUp: 'last'`, or past the `'all'` cap). */
|
|
96
|
+
missed: number;
|
|
97
|
+
/** Aborted when the delivery's deadline passes: the handler stops what it can, its answer no longer counts. */
|
|
98
|
+
signal: AbortSignal;
|
|
99
|
+
}
|
|
100
|
+
export type Handler = (due: Due) => unknown;
|
|
101
|
+
|
|
102
|
+
export interface Store {
|
|
103
|
+
all(): Promise<Entry[]>;
|
|
104
|
+
create(value: EntryValue): Promise<string>;
|
|
105
|
+
update(id: string, value: EntryValue): Promise<void>;
|
|
106
|
+
remove(id: string): Promise<void>;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface Clock {
|
|
110
|
+
now(): number;
|
|
111
|
+
setTimeout(fn: () => void, ms: number): unknown;
|
|
112
|
+
clearTimeout(timer: unknown): void;
|
|
113
|
+
setInterval(fn: () => void, ms: number): unknown;
|
|
114
|
+
clearInterval(timer: unknown): void;
|
|
115
|
+
}
|
|
116
|
+
export const realClock: Clock = {
|
|
117
|
+
now: () => Date.now(),
|
|
118
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
119
|
+
clearTimeout: (timer) => clearTimeout(timer as ReturnType<typeof setTimeout>),
|
|
120
|
+
setInterval: (fn, ms) => setInterval(fn, ms),
|
|
121
|
+
clearInterval: (timer) => clearInterval(timer as ReturnType<typeof setInterval>),
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
/** A refusal the caller can act on: `code`, an HTTP status. */
|
|
125
|
+
const refusal = (code: string, message: string, status = 400) =>
|
|
126
|
+
Object.assign(new Error(message), { code, status, [Symbol.for('bridge.clientError')]: true });
|
|
127
|
+
|
|
128
|
+
export interface Options {
|
|
129
|
+
store: Store;
|
|
130
|
+
clock?: Clock;
|
|
131
|
+
/** The zone of floating rules (the `timeZone` setting), read at each computation. */
|
|
132
|
+
zone: () => string;
|
|
133
|
+
/** How long a handler has to answer, in ms, read at each delivery (default `DEADLINE_MS`). */
|
|
134
|
+
deadline?: () => number;
|
|
135
|
+
/** After each delivery: the `scheduler/due` node event. */
|
|
136
|
+
emit?: (payload: {
|
|
137
|
+
node: string;
|
|
138
|
+
owner: string;
|
|
139
|
+
ref: Reference;
|
|
140
|
+
key: string;
|
|
141
|
+
scheduledFor: string;
|
|
142
|
+
firedAt: string;
|
|
143
|
+
late: boolean;
|
|
144
|
+
missed: number;
|
|
145
|
+
}) => void;
|
|
146
|
+
log?: (message: string) => void;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface ListQuery {
|
|
150
|
+
owner?: string;
|
|
151
|
+
domain?: string;
|
|
152
|
+
ref?: Reference;
|
|
153
|
+
key?: string;
|
|
154
|
+
for?: string;
|
|
155
|
+
until?: string;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export async function createScheduler({
|
|
159
|
+
store,
|
|
160
|
+
clock = realClock,
|
|
161
|
+
zone,
|
|
162
|
+
deadline = () => DEADLINE_MS,
|
|
163
|
+
emit = () => {},
|
|
164
|
+
log = () => {},
|
|
165
|
+
}: Options) {
|
|
166
|
+
const entries = new Map<string, Entry>();
|
|
167
|
+
for (const entry of await store.all()) entries.set(entry.id, entry);
|
|
168
|
+
const handlers = new Map<string, Handler>();
|
|
169
|
+
/** Bumped by each `schedule` and `cancel` of an entry: a delivery that sees it changed leaves the entry alone. */
|
|
170
|
+
const generations = new Map<string, number>();
|
|
171
|
+
/** Schedules and cancels one after another: each reads the entries, awaits the store, then changes them, and two at
|
|
172
|
+
* once made two entries of one `(owner, ref, key)` (audit L5-01).
|
|
173
|
+
* ponytail: one queue for every owner; per-key queues if scheduling throughput ever matters. */
|
|
174
|
+
let writes: Promise<unknown> = Promise.resolve();
|
|
175
|
+
const oneAtATime = <T>(change: () => Promise<T>): Promise<T> => {
|
|
176
|
+
const run = writes.then(change, change);
|
|
177
|
+
writes = run.catch(() => {});
|
|
178
|
+
return run;
|
|
179
|
+
};
|
|
180
|
+
const generation = (id: string) => generations.get(id) ?? 0;
|
|
181
|
+
const iso = (ms: number) => new Date(ms).toISOString();
|
|
182
|
+
const compiled = (value: Rule) => compile(value, zone());
|
|
183
|
+
/** The first fire of `value` after `after`; `undefined` when its series ended (or its rule no longer compiles). */
|
|
184
|
+
const nextOf = (value: EntryValue, after: number) => {
|
|
185
|
+
if (!value.rule) return undefined;
|
|
186
|
+
try {
|
|
187
|
+
return compiled(value.rule).next(after);
|
|
188
|
+
} catch (error) {
|
|
189
|
+
log(
|
|
190
|
+
`entry of ${value.owner} on ${value.ref.domain}/${value.ref.id}: ${error instanceof Error ? error.message : String(error)}`,
|
|
191
|
+
);
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
/** When `entry` is due: its retry, else its next fire. */
|
|
196
|
+
const dueAt = (entry: EntryValue) => Date.parse(entry.retryAt ?? entry.next ?? '') || undefined;
|
|
197
|
+
|
|
198
|
+
const write = async (id: string, value: EntryValue) => {
|
|
199
|
+
await store.update(id, value);
|
|
200
|
+
entries.set(id, { ...value, id });
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
// One tick at a time; one asked for while one runs runs after it.
|
|
204
|
+
let ticking: Promise<void> | undefined;
|
|
205
|
+
let again = false;
|
|
206
|
+
let disposed = false;
|
|
207
|
+
const tick = (): Promise<void> => {
|
|
208
|
+
if (disposed) return Promise.resolve();
|
|
209
|
+
if (ticking) {
|
|
210
|
+
again = true;
|
|
211
|
+
return ticking;
|
|
212
|
+
}
|
|
213
|
+
// `ticking` is cleared in the same step as the last `again` check, so a tick asked for in between is never lost.
|
|
214
|
+
ticking = (async () => {
|
|
215
|
+
try {
|
|
216
|
+
do {
|
|
217
|
+
again = false;
|
|
218
|
+
await run();
|
|
219
|
+
} while (again && !disposed);
|
|
220
|
+
} catch (error) {
|
|
221
|
+
log(`tick failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
222
|
+
} finally {
|
|
223
|
+
ticking = undefined;
|
|
224
|
+
arm();
|
|
225
|
+
}
|
|
226
|
+
})();
|
|
227
|
+
return ticking;
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
/** Delivers `due` of `entry` to its owner; resolves whether its handler took it (else the retry is stored). */
|
|
231
|
+
const deliver = async (entry: Entry, scheduledFor: number, missed: number, handler: Handler) => {
|
|
232
|
+
const now = clock.now();
|
|
233
|
+
const was = generation(entry.id);
|
|
234
|
+
const controller = new AbortController();
|
|
235
|
+
const due: Due = {
|
|
236
|
+
entry,
|
|
237
|
+
scheduledFor: iso(scheduledFor),
|
|
238
|
+
firedAt: iso(now),
|
|
239
|
+
late: now - scheduledFor > LATE_MS,
|
|
240
|
+
missed,
|
|
241
|
+
signal: controller.signal,
|
|
242
|
+
};
|
|
243
|
+
const ms = deadline();
|
|
244
|
+
let timer: unknown;
|
|
245
|
+
try {
|
|
246
|
+
await Promise.race([
|
|
247
|
+
(async () => handler(due))(),
|
|
248
|
+
new Promise((_, fail) => {
|
|
249
|
+
timer = clock.setTimeout(() => {
|
|
250
|
+
controller.abort();
|
|
251
|
+
fail(new Error(`no answer within ${ms} ms`));
|
|
252
|
+
}, ms);
|
|
253
|
+
}),
|
|
254
|
+
]);
|
|
255
|
+
} catch (error) {
|
|
256
|
+
const attempts = (entry.attempts ?? 0) + 1;
|
|
257
|
+
const retryAt = clock.now() + RETRY_MS[Math.min(attempts, RETRY_MS.length) - 1]!;
|
|
258
|
+
log(
|
|
259
|
+
`${entry.owner} failed on ${entry.ref.domain}/${entry.ref.id} (${entry.key}), try ${attempts}, again at ${iso(retryAt)}: ${error instanceof Error ? error.message : String(error)}`,
|
|
260
|
+
);
|
|
261
|
+
if (entries.has(entry.id) && generation(entry.id) === was)
|
|
262
|
+
await write(entry.id, { ...strip(entry), attempts, retryAt: iso(retryAt) });
|
|
263
|
+
return false;
|
|
264
|
+
} finally {
|
|
265
|
+
clock.clearTimeout(timer);
|
|
266
|
+
}
|
|
267
|
+
emit({
|
|
268
|
+
node: entry.node,
|
|
269
|
+
owner: entry.owner,
|
|
270
|
+
ref: entry.ref,
|
|
271
|
+
key: entry.key,
|
|
272
|
+
scheduledFor: due.scheduledFor,
|
|
273
|
+
firedAt: due.firedAt,
|
|
274
|
+
late: due.late,
|
|
275
|
+
missed,
|
|
276
|
+
});
|
|
277
|
+
return true;
|
|
278
|
+
};
|
|
279
|
+
const strip = ({ id: _id, ...value }: Entry): EntryValue => value;
|
|
280
|
+
const settled = ({ attempts: _attempts, retryAt: _retryAt, ...value }: EntryValue): EntryValue =>
|
|
281
|
+
value;
|
|
282
|
+
|
|
283
|
+
/** Owners whose due entries are being delivered, and those deliveries (awaited by `dispose`). */
|
|
284
|
+
const busy = new Map<string, Promise<void>>();
|
|
285
|
+
/** Whether `entry` is due now for a delivery that may start: its owner listens and is not busy. */
|
|
286
|
+
const ready = (entry: EntryValue, now: number) =>
|
|
287
|
+
handlers.has(entry.owner) && !busy.has(entry.owner) && (dueAt(entry) ?? Infinity) <= now;
|
|
288
|
+
|
|
289
|
+
/** Purges what is long done, then starts a delivery for each owner with due entries, without awaiting it. */
|
|
290
|
+
const run = async () => {
|
|
291
|
+
const now = clock.now();
|
|
292
|
+
for (const entry of [...entries.values()]) {
|
|
293
|
+
// Purge one-shot entries fired long ago (and ended series).
|
|
294
|
+
if (
|
|
295
|
+
entry.next === undefined &&
|
|
296
|
+
entry.firedAt &&
|
|
297
|
+
now - Date.parse(entry.firedAt) > KEEP_FIRED_MS
|
|
298
|
+
) {
|
|
299
|
+
entries.delete(entry.id);
|
|
300
|
+
await store.remove(entry.id);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
for (const owner of new Set(
|
|
304
|
+
[...entries.values()].filter((entry) => ready(entry, now)).map((entry) => entry.owner),
|
|
305
|
+
)) {
|
|
306
|
+
if (disposed) return;
|
|
307
|
+
const delivery = deliverOwner(owner, now)
|
|
308
|
+
.catch((error: unknown) =>
|
|
309
|
+
log(
|
|
310
|
+
`delivery to ${owner} failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
311
|
+
),
|
|
312
|
+
)
|
|
313
|
+
.finally(() => {
|
|
314
|
+
busy.delete(owner);
|
|
315
|
+
// What fell due for it meanwhile goes now, not on the next timer.
|
|
316
|
+
if ([...entries.values()].some((entry) => ready(entry, clock.now()))) void tick();
|
|
317
|
+
else arm();
|
|
318
|
+
});
|
|
319
|
+
busy.set(owner, delivery);
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
/** Delivers `owner`'s entries due at `now`, earliest first, one after another. */
|
|
324
|
+
const deliverOwner = async (owner: string, now: number) => {
|
|
325
|
+
for (const { id } of [...entries.values()]
|
|
326
|
+
.filter((entry) => entry.owner === owner)
|
|
327
|
+
.sort((a, b) => (dueAt(a) ?? Infinity) - (dueAt(b) ?? Infinity))) {
|
|
328
|
+
if (disposed) return;
|
|
329
|
+
// As it is now: an earlier delivery's handler may have cancelled or replaced it.
|
|
330
|
+
const entry = entries.get(id);
|
|
331
|
+
if (!entry || entry.next === undefined) continue;
|
|
332
|
+
const at = dueAt(entry);
|
|
333
|
+
if (at === undefined || at > now) continue;
|
|
334
|
+
const handler = handlers.get(entry.owner);
|
|
335
|
+
if (!handler) return;
|
|
336
|
+
const first = Date.parse(entry.next);
|
|
337
|
+
const was = generation(entry.id);
|
|
338
|
+
/** The entry now, unless it was replaced or cancelled meanwhile. */
|
|
339
|
+
const unchanged = () => (generation(entry.id) === was ? entries.get(entry.id) : undefined);
|
|
340
|
+
if (!entry.rule) {
|
|
341
|
+
if (await deliver(entry, first, 0, handler)) {
|
|
342
|
+
// Replaced meanwhile (a new `schedule` of the same key): the new one stands.
|
|
343
|
+
const current = unchanged();
|
|
344
|
+
if (current) {
|
|
345
|
+
const { next: _next, ...done } = settled(strip(current));
|
|
346
|
+
await write(entry.id, { ...done, firedAt: iso(clock.now()) });
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
// A rule: the occurrences due now, the first one (`next`) included.
|
|
352
|
+
const later = (() => {
|
|
353
|
+
try {
|
|
354
|
+
return compiled(entry.rule).between(first, now, CATCH_UP_MAX + 1);
|
|
355
|
+
} catch {
|
|
356
|
+
return [];
|
|
357
|
+
}
|
|
358
|
+
})();
|
|
359
|
+
const due = [first, ...later];
|
|
360
|
+
const policy = entry.catchUp ?? 'last';
|
|
361
|
+
let delivered: number | undefined;
|
|
362
|
+
let ok = true;
|
|
363
|
+
if (policy === 'all') {
|
|
364
|
+
for (const [index, occurrence] of due.slice(0, CATCH_UP_MAX).entries()) {
|
|
365
|
+
const missed =
|
|
366
|
+
index === CATCH_UP_MAX - 1 && due.length > CATCH_UP_MAX ? due.length - CATCH_UP_MAX : 0;
|
|
367
|
+
const current = unchanged();
|
|
368
|
+
if (!current || disposed) break;
|
|
369
|
+
if (!(ok = await deliver(current, occurrence, missed, handler))) break;
|
|
370
|
+
delivered = occurrence;
|
|
371
|
+
const following = due[index + 1];
|
|
372
|
+
// Replaced by its handler meanwhile: the new one stands, not overwritten.
|
|
373
|
+
const still = unchanged();
|
|
374
|
+
if (!still) break;
|
|
375
|
+
// Each delivery stored, so a stop between two keeps the rest due.
|
|
376
|
+
if (following !== undefined && index < CATCH_UP_MAX - 1)
|
|
377
|
+
await write(entry.id, {
|
|
378
|
+
...settled(strip(still)),
|
|
379
|
+
next: iso(following),
|
|
380
|
+
firedAt: iso(clock.now()),
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
} else {
|
|
384
|
+
const last = due[due.length - 1]!;
|
|
385
|
+
// `skip`: only an occurrence on time is delivered.
|
|
386
|
+
if (policy === 'last' || now - last <= LATE_MS) {
|
|
387
|
+
ok = await deliver(entry, last, due.length - 1, handler);
|
|
388
|
+
if (ok) delivered = last;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
const current = unchanged();
|
|
392
|
+
if (!ok || !current) continue;
|
|
393
|
+
const next = nextOf(current, Math.max(now, delivered ?? 0));
|
|
394
|
+
const { next: _next, ...rest } = settled(strip(current));
|
|
395
|
+
await write(entry.id, {
|
|
396
|
+
...rest,
|
|
397
|
+
...(next !== undefined && { next: iso(next) }),
|
|
398
|
+
...(delivered !== undefined ? { firedAt: iso(clock.now()) } : {}),
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
// The timer for the earliest due entry whose owner listens, and the heartbeat.
|
|
404
|
+
let timer: unknown;
|
|
405
|
+
const arm = () => {
|
|
406
|
+
if (timer !== undefined) clock.clearTimeout(timer);
|
|
407
|
+
timer = undefined;
|
|
408
|
+
if (disposed) return;
|
|
409
|
+
let earliest = Infinity;
|
|
410
|
+
for (const entry of entries.values()) {
|
|
411
|
+
const at = dueAt(entry);
|
|
412
|
+
if (at !== undefined && handlers.has(entry.owner) && !busy.has(entry.owner) && at < earliest)
|
|
413
|
+
earliest = at;
|
|
414
|
+
}
|
|
415
|
+
if (earliest === Infinity) return;
|
|
416
|
+
timer = clock.setTimeout(
|
|
417
|
+
() => {
|
|
418
|
+
timer = undefined;
|
|
419
|
+
void tick();
|
|
420
|
+
},
|
|
421
|
+
Math.min(TIMER_MAX, Math.max(0, earliest - clock.now())),
|
|
422
|
+
);
|
|
423
|
+
};
|
|
424
|
+
const heartbeat = clock.setInterval(() => {
|
|
425
|
+
const now = clock.now();
|
|
426
|
+
if ([...entries.values()].some((entry) => ready(entry, now))) void tick();
|
|
427
|
+
}, HEARTBEAT_MS);
|
|
428
|
+
|
|
429
|
+
const matches = (entry: Entry, query: ListQuery) =>
|
|
430
|
+
(query.owner === undefined || entry.owner === query.owner) &&
|
|
431
|
+
(query.domain === undefined || entry.ref.domain === query.domain) &&
|
|
432
|
+
(query.ref === undefined ||
|
|
433
|
+
(entry.ref.domain === query.ref.domain && entry.ref.id === query.ref.id)) &&
|
|
434
|
+
(query.key === undefined || entry.key === query.key) &&
|
|
435
|
+
(query.for === undefined || entry.for === query.for) &&
|
|
436
|
+
(query.until === undefined || (entry.next !== undefined && entry.next <= query.until));
|
|
437
|
+
|
|
438
|
+
return {
|
|
439
|
+
/** Creates or replaces `owner`'s entry for `(ref, key)`. */
|
|
440
|
+
async schedule(owner: string, input: unknown): Promise<Entry> {
|
|
441
|
+
const parsed = scheduleInput.safeParse(input);
|
|
442
|
+
if (!parsed.success)
|
|
443
|
+
throw refusal(
|
|
444
|
+
'invalid_entry',
|
|
445
|
+
parsed.error.issues
|
|
446
|
+
.map((issue) => `${issue.path.join('.') || 'entry'}: ${issue.message}`)
|
|
447
|
+
.join('; '),
|
|
448
|
+
);
|
|
449
|
+
const {
|
|
450
|
+
ref,
|
|
451
|
+
key = 'default',
|
|
452
|
+
node = 'root',
|
|
453
|
+
at,
|
|
454
|
+
rule: given,
|
|
455
|
+
catchUp: policy,
|
|
456
|
+
label,
|
|
457
|
+
data: payload,
|
|
458
|
+
for: person,
|
|
459
|
+
} = parsed.data;
|
|
460
|
+
let next: number | undefined;
|
|
461
|
+
if (given) {
|
|
462
|
+
try {
|
|
463
|
+
next = compiled(given).next(clock.now() - 1);
|
|
464
|
+
} catch (error) {
|
|
465
|
+
throw refusal('invalid_rule', error instanceof Error ? error.message : String(error));
|
|
466
|
+
}
|
|
467
|
+
if (next === undefined)
|
|
468
|
+
throw refusal('rule_ended', 'the rule has no occurrence from now on');
|
|
469
|
+
} else next = Date.parse(at!);
|
|
470
|
+
const value: EntryValue = {
|
|
471
|
+
owner,
|
|
472
|
+
ref,
|
|
473
|
+
key,
|
|
474
|
+
node,
|
|
475
|
+
...(person !== undefined && { for: person }),
|
|
476
|
+
...(at !== undefined && { at: iso(Date.parse(at)) }),
|
|
477
|
+
...(given && { rule: given }),
|
|
478
|
+
...(policy && { catchUp: policy }),
|
|
479
|
+
...(label !== undefined && { label }),
|
|
480
|
+
...(payload !== undefined && { data: payload }),
|
|
481
|
+
next: iso(next),
|
|
482
|
+
createdAt: iso(clock.now()),
|
|
483
|
+
};
|
|
484
|
+
return oneAtATime(async () => {
|
|
485
|
+
const same = [...entries.values()].find(
|
|
486
|
+
(entry) =>
|
|
487
|
+
entry.owner === owner &&
|
|
488
|
+
entry.key === key &&
|
|
489
|
+
entry.ref.domain === ref.domain &&
|
|
490
|
+
entry.ref.id === ref.id,
|
|
491
|
+
);
|
|
492
|
+
let id: string;
|
|
493
|
+
if (same) {
|
|
494
|
+
generations.set(same.id, generation(same.id) + 1);
|
|
495
|
+
await write((id = same.id), value);
|
|
496
|
+
} else entries.set((id = await store.create(value)), { ...value, id });
|
|
497
|
+
arm();
|
|
498
|
+
return { ...value, id };
|
|
499
|
+
});
|
|
500
|
+
},
|
|
501
|
+
/** Removes `owner`'s entries for `ref` (one `key`, or all); resolves to how many. */
|
|
502
|
+
async cancel(owner: string, input: { ref: Reference; key?: string }): Promise<number> {
|
|
503
|
+
return oneAtATime(async () => {
|
|
504
|
+
const gone = [...entries.values()].filter(
|
|
505
|
+
(entry) =>
|
|
506
|
+
entry.owner === owner &&
|
|
507
|
+
matches(entry, { ref: input.ref, ...(input.key !== undefined && { key: input.key }) }),
|
|
508
|
+
);
|
|
509
|
+
for (const entry of gone) {
|
|
510
|
+
generations.set(entry.id, generation(entry.id) + 1);
|
|
511
|
+
// Gone from memory once gone from the disk: a failed removal leaves both with it (audit L5-02).
|
|
512
|
+
await store.remove(entry.id);
|
|
513
|
+
entries.delete(entry.id);
|
|
514
|
+
}
|
|
515
|
+
if (gone.length) arm();
|
|
516
|
+
return gone.length;
|
|
517
|
+
});
|
|
518
|
+
},
|
|
519
|
+
/** Entries matching every field given: pending ones first by `next`, then fired ones newest first. */
|
|
520
|
+
list(query: ListQuery = {}): Entry[] {
|
|
521
|
+
return [...entries.values()]
|
|
522
|
+
.filter((entry) => matches(entry, query))
|
|
523
|
+
.map((entry) => ({ ...entry }))
|
|
524
|
+
.sort((a, b) =>
|
|
525
|
+
a.next && b.next
|
|
526
|
+
? a.next.localeCompare(b.next)
|
|
527
|
+
: a.next
|
|
528
|
+
? -1
|
|
529
|
+
: b.next
|
|
530
|
+
? 1
|
|
531
|
+
: (b.firedAt ?? '').localeCompare(a.firedAt ?? ''),
|
|
532
|
+
);
|
|
533
|
+
},
|
|
534
|
+
/** `value`'s fires in `[from, to)`, at most `take` (1000 at most): pure, schedules nothing. */
|
|
535
|
+
occurrences(value: unknown, range: { from: string; to: string; take?: number }): string[] {
|
|
536
|
+
const parsed = rule.safeParse(value);
|
|
537
|
+
if (!parsed.success)
|
|
538
|
+
throw refusal('invalid_rule', parsed.error.issues.map((issue) => issue.message).join('; '));
|
|
539
|
+
const from = Date.parse(range.from);
|
|
540
|
+
const to = Date.parse(range.to);
|
|
541
|
+
if (Number.isNaN(from) || Number.isNaN(to))
|
|
542
|
+
throw refusal('invalid_range', 'from and to are ISO instants');
|
|
543
|
+
let rules: Compiled;
|
|
544
|
+
try {
|
|
545
|
+
rules = compiled(parsed.data);
|
|
546
|
+
} catch (error) {
|
|
547
|
+
throw refusal('invalid_rule', error instanceof Error ? error.message : String(error));
|
|
548
|
+
}
|
|
549
|
+
return rules
|
|
550
|
+
.between(from - 1, to - 1, Math.min(1000, Math.max(1, range.take ?? 1000)))
|
|
551
|
+
.map(iso);
|
|
552
|
+
},
|
|
553
|
+
/** `owner`'s delivery; returns its removal. Due entries waiting for it are delivered now. */
|
|
554
|
+
handle(owner: string, fn: Handler) {
|
|
555
|
+
handlers.set(owner, fn);
|
|
556
|
+
void tick();
|
|
557
|
+
return () => {
|
|
558
|
+
if (handlers.get(owner) === fn) handlers.delete(owner);
|
|
559
|
+
};
|
|
560
|
+
},
|
|
561
|
+
/** Recomputes `next` of floating rules (the `timeZone` setting changed). */
|
|
562
|
+
async rezone() {
|
|
563
|
+
for (const entry of [...entries.values()]) {
|
|
564
|
+
if (!entry.rule || entry.next === undefined || !floating(entry.rule) || entry.retryAt)
|
|
565
|
+
continue;
|
|
566
|
+
const next = nextOf(entry, clock.now() - 1);
|
|
567
|
+
const { next: _next, ...rest } = strip(entry);
|
|
568
|
+
await write(entry.id, { ...rest, ...(next !== undefined && { next: iso(next) }) });
|
|
569
|
+
}
|
|
570
|
+
arm();
|
|
571
|
+
},
|
|
572
|
+
tick,
|
|
573
|
+
dispose() {
|
|
574
|
+
disposed = true;
|
|
575
|
+
if (timer !== undefined) clock.clearTimeout(timer);
|
|
576
|
+
clock.clearInterval(heartbeat);
|
|
577
|
+
return Promise.all([ticking, ...busy.values()]).then(() => {});
|
|
578
|
+
},
|
|
579
|
+
};
|
|
580
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Scheduled tasks
|
|
3
|
+
description: Run an action at a time of day or at a regular interval, such as a prompt sent to a session.
|
|
4
|
+
status: implemented
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
A scheduled task runs one action on a schedule: send a prompt to a session every
|
|
8
|
+
weekday at 09:00, or start a new session every two hours. Open **Scheduled** in
|
|
9
|
+
the sidebar to see every task of the workspace.
|
|
10
|
+
|
|
11
|
+
## Create a task
|
|
12
|
+
|
|
13
|
+
1. In **Scheduled**, select **New**.
|
|
14
|
+
2. Give the task a title, or leave it empty to use one made from the action.
|
|
15
|
+
3. Choose its schedule:
|
|
16
|
+
- **At a time**: a time of day, on the days you select. With no day
|
|
17
|
+
selected, it runs every day.
|
|
18
|
+
- **Every**: a number of minutes, hours or days, one minute at least.
|
|
19
|
+
4. Choose its **Action** and fill in the fields shown in the action's box.
|
|
20
|
+
5. Select **Create**.
|
|
21
|
+
|
|
22
|
+
The list shows each task's state and when it runs next. The switch on a task's
|
|
23
|
+
row pauses it or turns it back on.
|
|
24
|
+
|
|
25
|
+
## Actions
|
|
26
|
+
|
|
27
|
+
The plugins of the workspace provide the actions. Sessions provides two.
|
|
28
|
+
|
|
29
|
+
**Send a prompt to a session** sends the prompt into the session you choose. When
|
|
30
|
+
the agent is already working, the prompt waits in the session's queue. The
|
|
31
|
+
message shows the task's title.
|
|
32
|
+
|
|
33
|
+
**Start a new session** starts a new session at each run and sends it the prompt.
|
|
34
|
+
Choose its harness and, optionally, its project, model, effort and permissions.
|
|
35
|
+
Empty fields use the harness profile's defaults. **Ask** is not offered, because
|
|
36
|
+
nobody is there to answer a scheduled session.
|
|
37
|
+
|
|
38
|
+
The session title can use these variables:
|
|
39
|
+
|
|
40
|
+
| Variable | Becomes |
|
|
41
|
+
| ------------- | ------------------------------------ |
|
|
42
|
+
| `{{date}}` | The run's date, such as `2026-10-20` |
|
|
43
|
+
| `{{time}}` | The run's time, such as `09:30` |
|
|
44
|
+
| `{{weekday}}` | The run's day, such as `Tuesday` |
|
|
45
|
+
| `{{task}}` | The task's title |
|
|
46
|
+
|
|
47
|
+
With no title, the session is named `{{task}} · {{date}} {{time}}`.
|
|
48
|
+
|
|
49
|
+
## Follow and change a task
|
|
50
|
+
|
|
51
|
+
Select a task to open its card. Every field is edited in place.
|
|
52
|
+
|
|
53
|
+
- **State** says what the task is doing:
|
|
54
|
+
- **Waiting**, with when it runs next;
|
|
55
|
+
- **Running**, while its action runs;
|
|
56
|
+
- **Suspended**, with the reason and a **Resume** button;
|
|
57
|
+
- **Paused**, when its switch is off.
|
|
58
|
+
- **Run now** starts the action at once, even when the task is paused or
|
|
59
|
+
suspended. During a run, it runs once more right after it.
|
|
60
|
+
- **Last run** says whether the last run succeeded, failed or timed out, when it
|
|
61
|
+
ran, and why it failed.
|
|
62
|
+
- **Delete**, in the card's menu, removes the task.
|
|
63
|
+
|
|
64
|
+
A session's header shows **Scheduled** when tasks send prompts to it, with
|
|
65
|
+
**Run now** and **Pause** for each of them.
|
|
66
|
+
|
|
67
|
+
## What happens to missed runs
|
|
68
|
+
|
|
69
|
+
Times of day follow the scheduler's **Time zone** setting, the computer's zone
|
|
70
|
+
by default. When Bridge was off:
|
|
71
|
+
|
|
72
|
+
- a time of day missed by more than 10 minutes is skipped until its next slot;
|
|
73
|
+
- an interval runs once, then keeps its rhythm.
|
|
74
|
+
|
|
75
|
+
## Runs that fail or take too long
|
|
76
|
+
|
|
77
|
+
A task never runs twice at once. When its time comes during a run, it runs once
|
|
78
|
+
more right after that run, however many times came meanwhile. A task that runs
|
|
79
|
+
long holds no other task.
|
|
80
|
+
|
|
81
|
+
A run has 10 minutes, or the scheduler's **Run deadline** setting. Past it, the
|
|
82
|
+
action is told to stop and the run counts as timed out. An action that does not
|
|
83
|
+
stop keeps its task running until it ends, and its answer is not kept. Bridge
|
|
84
|
+
cannot stop an action that blocks the whole workspace: the workspace restarts,
|
|
85
|
+
as for any plugin.
|
|
86
|
+
|
|
87
|
+
A failed run is not retried. After three failed or timed-out runs in a row, the
|
|
88
|
+
task is suspended with the last error. A success resets the count. A task is
|
|
89
|
+
suspended at once when what its action acts on is gone, such as an archived
|
|
90
|
+
session.
|
|
91
|
+
|
|
92
|
+
A suspended task keeps its switch on, and turning it off and on does not lift
|
|
93
|
+
the suspension. **Resume** does: the task waits for its next time, and the runs
|
|
94
|
+
it missed are not replayed.
|
|
95
|
+
|
|
96
|
+
Turning a task off during a run lets the run end: the task shows **Running**
|
|
97
|
+
until then. A run cut by a restart of Bridge is not replayed.
|
|
98
|
+
|
|
99
|
+
## Ask an agent
|
|
100
|
+
|
|
101
|
+
An agent can schedule a prompt from its own session with `schedule_task`. By
|
|
102
|
+
default the prompt comes back into that session. With `bindToCurrentThread`
|
|
103
|
+
set to `false`, each run starts a new session like the agent's own. The agent
|
|
104
|
+
lists the tasks with `list_scheduled_tasks` and the available actions with
|
|
105
|
+
`list_action_types`. Its tasks appear in **Scheduled** like yours.
|