@bridgebrew/scheduler 0.0.0-stage → 0.0.2
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
package/tasks.ts
ADDED
|
@@ -0,0 +1,843 @@
|
|
|
1
|
+
// Scheduled tasks (research-040, revision): a task is a schedule and a typed action, owned by the scheduler. Plugins
|
|
2
|
+
// register their action types on the scheduler service (`demo.echo`, `sessions.prompt`); a task names one and its input.
|
|
3
|
+
// An enabled task has one entry of the scheduler's own (owner `scheduler`, key `task`), planned from its schedule; at
|
|
4
|
+
// each delivery the action runs once, never a retry. A fixed time missed by more than `MISSED_MS` is skipped to its next
|
|
5
|
+
// slot; an interval runs once (`catchUp: 'last'`). An action type not registered yet makes the delivery throw, so the
|
|
6
|
+
// core retries it after a minute (the plugin may load after the scheduler). A run records `lastRunAt`, `lastRunStatus`,
|
|
7
|
+
// `lastRunError`, `lastRunSummary` and `runCount` on the task.
|
|
8
|
+
// The tasks own their runs, not the core: a delivery starts the run and answers at once, so the core never retries a
|
|
9
|
+
// run. A task runs once at a time; a slot (or Run now) during a run makes one run right after it. A run has a deadline
|
|
10
|
+
// (the `runDeadline` setting): past it, its `signal` aborts and it is recorded `timed_out`; an action deaf to the
|
|
11
|
+
// signal keeps its task running until it ends, its answer refused (a JavaScript run cannot be stopped from outside, nor
|
|
12
|
+
// a blocked thread: that restarts the workspace, as any plugin). Three failed runs in a row (thrown or timed out), or an
|
|
13
|
+
// action answering `gone`, suspend the task with the reason: its entry is cancelled, its switch (`enabled`, the person's
|
|
14
|
+
// choice) untouched; only Resume lifts it, planning the next slot from now (nothing missed is replayed). A success and
|
|
15
|
+
// Resume reset the count. The count and the suspension are stored; whether a run is in progress is not (a run cut by a
|
|
16
|
+
// restart is not replayed). A task's `state`: `running`, else `off`, `suspended`, `waiting`.
|
|
17
|
+
import { createHash } from 'node:crypto';
|
|
18
|
+
import type { Context } from 'cordis';
|
|
19
|
+
import { z } from 'zod';
|
|
20
|
+
import type { Entry, ListQuery, Reference, ScheduleInput } from './core.ts';
|
|
21
|
+
import type { ActionType } from './server.ts';
|
|
22
|
+
import { scheduleLabel } from './view.ts';
|
|
23
|
+
|
|
24
|
+
/** The scheduler's owner of a task's entry, its key, and the domain of the record. */
|
|
25
|
+
const OWNER = 'scheduler';
|
|
26
|
+
const KEY = 'task';
|
|
27
|
+
const DOMAIN = 'scheduler/tasks';
|
|
28
|
+
/** An interval is at least a minute. */
|
|
29
|
+
const EVERY_MIN_MS = 60_000;
|
|
30
|
+
/** A fixed time this much later than its slot is skipped. */
|
|
31
|
+
const MISSED_MS = 10 * 60_000;
|
|
32
|
+
/** The most characters of a title and of a client request id. */
|
|
33
|
+
const TITLE_MAX = 120;
|
|
34
|
+
const REQUEST_MAX = 200;
|
|
35
|
+
/** The most characters of a prompt in the prompt shortcut. */
|
|
36
|
+
const PROMPT_MAX = 20_000;
|
|
37
|
+
/** Failed runs in a row that suspend a task. */
|
|
38
|
+
const FAILURES_MAX = 3;
|
|
39
|
+
|
|
40
|
+
const intervalSchedule = z.strictObject({
|
|
41
|
+
type: z.literal('interval'),
|
|
42
|
+
everyMs: z.number().int().min(EVERY_MIN_MS),
|
|
43
|
+
});
|
|
44
|
+
const fixedTimeSchedule = z.strictObject({
|
|
45
|
+
type: z.literal('fixed_time'),
|
|
46
|
+
timeOfDay: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'timeOfDay is HH:mm'),
|
|
47
|
+
/** 0 is Sunday, as JavaScript's `Date#getDay`. */
|
|
48
|
+
weekdays: z.array(z.number().int().min(0).max(6)).max(7).optional(),
|
|
49
|
+
});
|
|
50
|
+
/** A task's schedule: an interval of elapsed time, or a wall time on some weekdays. */
|
|
51
|
+
export const schedule = z.discriminatedUnion('type', [intervalSchedule, fixedTimeSchedule]);
|
|
52
|
+
export type Schedule = z.infer<typeof schedule>;
|
|
53
|
+
|
|
54
|
+
const runStatus = z.enum(['never', 'succeeded', 'failed', 'timed_out']);
|
|
55
|
+
type RunStatus = z.infer<typeof runStatus>;
|
|
56
|
+
const reference = z.strictObject({
|
|
57
|
+
domain: z.string().min(1),
|
|
58
|
+
id: z.string().min(1),
|
|
59
|
+
});
|
|
60
|
+
/** A task as the domain `scheduler/tasks` stores it, on `root`. */
|
|
61
|
+
export const taskSchema = z.strictObject({
|
|
62
|
+
title: z.string(),
|
|
63
|
+
enabled: z.boolean(),
|
|
64
|
+
schedule,
|
|
65
|
+
action: z.strictObject({ type: z.string().min(1), input: z.unknown() }),
|
|
66
|
+
/** What the action acts on (`sessions/sessions:<id>`): list and filter by it. */
|
|
67
|
+
subject: reference.optional(),
|
|
68
|
+
/** `agent:<session id>` for an agent, `person` for the UI. */
|
|
69
|
+
createdBy: z.string(),
|
|
70
|
+
clientRequestId: z.string().optional(),
|
|
71
|
+
/** The create's digest: the same `clientRequestId` with another create is refused (absent on older tasks). */
|
|
72
|
+
request: z.string().optional(),
|
|
73
|
+
lastRunAt: z.string().optional(),
|
|
74
|
+
lastRunStatus: runStatus,
|
|
75
|
+
lastRunError: z.string().optional(),
|
|
76
|
+
lastRunSummary: z.string().optional(),
|
|
77
|
+
runCount: z.number().int(),
|
|
78
|
+
/** Failed runs in a row (absent: none). */
|
|
79
|
+
failures: z.number().int().optional(),
|
|
80
|
+
/** Suspended by the scheduler (failures, `gone`) until the person resumes it. */
|
|
81
|
+
suspended: z.strictObject({ reason: z.string(), at: z.string() }).optional(),
|
|
82
|
+
});
|
|
83
|
+
export type Task = z.infer<typeof taskSchema>;
|
|
84
|
+
|
|
85
|
+
export interface Found<V> {
|
|
86
|
+
id: string;
|
|
87
|
+
node: string;
|
|
88
|
+
value: V;
|
|
89
|
+
}
|
|
90
|
+
/** The part of a storage object domain this plugin uses. */
|
|
91
|
+
export interface Records<V> {
|
|
92
|
+
get(id: string): Promise<Found<V> | undefined>;
|
|
93
|
+
query(options: { node: string; include: 'subtree' }): Promise<Found<V>[]>;
|
|
94
|
+
create(caller: Context, value: V, options: { node: string }): Promise<Found<V>>;
|
|
95
|
+
update(caller: Context, id: string, value: V): Promise<Found<V>>;
|
|
96
|
+
purge(caller: Context, id: string): Promise<void>;
|
|
97
|
+
}
|
|
98
|
+
/** The part of the scheduler core a task uses. */
|
|
99
|
+
export interface Planner {
|
|
100
|
+
schedule(owner: string, input: ScheduleInput): Promise<Entry>;
|
|
101
|
+
cancel(owner: string, input: { ref: Reference; key?: string }): Promise<number>;
|
|
102
|
+
list(query?: ListQuery): Entry[];
|
|
103
|
+
}
|
|
104
|
+
export interface Clock {
|
|
105
|
+
now(): number;
|
|
106
|
+
setTimeout(fn: () => void, ms: number): unknown;
|
|
107
|
+
clearTimeout(timer: unknown): void;
|
|
108
|
+
}
|
|
109
|
+
/** A delivery the scheduler makes: its entry, the occurrence (`scheduledFor`) and the scheduler's clock (`firedAt`). */
|
|
110
|
+
export interface Delivery {
|
|
111
|
+
entry: { ref: Reference; key: string };
|
|
112
|
+
scheduledFor: string;
|
|
113
|
+
firedAt: string;
|
|
114
|
+
}
|
|
115
|
+
interface Request {
|
|
116
|
+
actor?: string | undefined;
|
|
117
|
+
body?: Uint8Array | undefined;
|
|
118
|
+
query?: URLSearchParams | undefined;
|
|
119
|
+
}
|
|
120
|
+
/** The router, when the scheduler runs on one (a plugin's own test may not give it one). */
|
|
121
|
+
export interface Router {
|
|
122
|
+
route(
|
|
123
|
+
owner: Context,
|
|
124
|
+
input: { method: string; path: string; handle: (request: Request) => unknown },
|
|
125
|
+
): void;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const DAYS = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'] as const;
|
|
129
|
+
|
|
130
|
+
/** An instant as an iCalendar UTC timestamp (`20261024T230000Z`). */
|
|
131
|
+
const utcStamp = (at: Date) =>
|
|
132
|
+
at
|
|
133
|
+
.toISOString()
|
|
134
|
+
.replace(/[-:]/g, '')
|
|
135
|
+
.replace(/\.\d{3}/, '');
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The scheduler rule of `schedule`, starting at `start`.
|
|
139
|
+
*
|
|
140
|
+
* An interval keeps elapsed time across a daylight-saving change: its `DTSTART` is UTC (upstream issue 15768). A fixed
|
|
141
|
+
* time is a floating rule (no `TZID`), so it follows the scheduler's `timeZone`; its `DTSTART` is the day before
|
|
142
|
+
* `start` at that wall time, so its next occurrence is the first future slot.
|
|
143
|
+
*/
|
|
144
|
+
export function ruleOf(value: Schedule, start: Date): { ical: string } {
|
|
145
|
+
if (value.type === 'interval') {
|
|
146
|
+
const minutes = Math.round(value.everyMs / 60_000);
|
|
147
|
+
return {
|
|
148
|
+
ical: `DTSTART:${utcStamp(new Date(start.getTime() + value.everyMs))}\nRRULE:FREQ=MINUTELY;INTERVAL=${minutes}`,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
const day = new Date(
|
|
152
|
+
Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate()) - 86_400_000,
|
|
153
|
+
);
|
|
154
|
+
const date = day.toISOString().slice(0, 10).replace(/-/g, '');
|
|
155
|
+
const time = value.timeOfDay.replace(':', '');
|
|
156
|
+
const days = [...new Set(value.weekdays ?? [])].sort((a, b) => a - b).map((each) => DAYS[each]!);
|
|
157
|
+
const repeat = days.length ? `FREQ=WEEKLY;BYDAY=${days.join(',')}` : 'FREQ=DAILY';
|
|
158
|
+
return { ical: `DTSTART:${date}T${time}00\nRRULE:${repeat}` };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const refused = (code: string, message: string, status = 400) =>
|
|
162
|
+
Object.assign(new Error(message), { code, status, [Symbol.for('bridge.clientError')]: true });
|
|
163
|
+
const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
|
|
164
|
+
|
|
165
|
+
const actionBody = z.strictObject({
|
|
166
|
+
type: z.string().min(1),
|
|
167
|
+
input: z.unknown().optional(),
|
|
168
|
+
});
|
|
169
|
+
const createBody = z.strictObject({
|
|
170
|
+
/** A JSON object, or its text (OpenCode sends one). */
|
|
171
|
+
schedule: z.union([schedule, z.string().min(1)]),
|
|
172
|
+
action: actionBody.optional(),
|
|
173
|
+
/** The prompt shortcut: a prompt scheduled from the calling agent's session (a person names `session`); its type's
|
|
174
|
+
* `fromSession` makes the input, and `bindToCurrentThread: false` starts a new session per run. */
|
|
175
|
+
prompt: z.string().trim().min(1).max(PROMPT_MAX).optional(),
|
|
176
|
+
session: z.string().min(1).optional(),
|
|
177
|
+
title: z.string().trim().min(1).max(TITLE_MAX).optional(),
|
|
178
|
+
enabled: z.boolean().optional(),
|
|
179
|
+
bindToCurrentThread: z.boolean().optional(),
|
|
180
|
+
clientRequestId: z.string().min(1).max(REQUEST_MAX).optional(),
|
|
181
|
+
});
|
|
182
|
+
const updateBody = z.strictObject({
|
|
183
|
+
scheduledTaskId: z.string().min(1),
|
|
184
|
+
title: z.string().trim().min(1).max(TITLE_MAX).optional(),
|
|
185
|
+
schedule: z.union([schedule, z.string().min(1)]).optional(),
|
|
186
|
+
enabled: z.boolean().optional(),
|
|
187
|
+
action: actionBody.optional(),
|
|
188
|
+
});
|
|
189
|
+
const taskBody = z.strictObject({ scheduledTaskId: z.string().min(1) });
|
|
190
|
+
|
|
191
|
+
const CREATE_USAGE =
|
|
192
|
+
'POST /scheduler/tasks takes { schedule, action?: { type, input }, prompt?, session?, title?, enabled?, bindToCurrentThread?, clientRequestId? }';
|
|
193
|
+
const UPDATE_USAGE =
|
|
194
|
+
'POST /scheduler/tasks/update takes { scheduledTaskId, title?, schedule?, enabled?, action? }';
|
|
195
|
+
const TASK_USAGE = 'POST /scheduler/tasks/delete, /run and /resume take { scheduledTaskId }';
|
|
196
|
+
const SCHEDULE_USAGE =
|
|
197
|
+
"schedule is { type: 'interval', everyMs: at least 60000 } or { type: 'fixed_time', timeOfDay: 'HH:MM', weekdays?: 0-6 }";
|
|
198
|
+
|
|
199
|
+
const parse = <T>(schema: z.ZodType<T>, body: Uint8Array | undefined, usage: string): T => {
|
|
200
|
+
let parsed;
|
|
201
|
+
try {
|
|
202
|
+
parsed = schema.safeParse(JSON.parse(new TextDecoder().decode(body ?? new Uint8Array())));
|
|
203
|
+
} catch {}
|
|
204
|
+
if (!parsed?.success) throw refused('invalid_body', usage);
|
|
205
|
+
return parsed.data;
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
/** What `createTasks` gets from `server.ts`. */
|
|
209
|
+
export interface Deps {
|
|
210
|
+
ctx: Context;
|
|
211
|
+
clock: Clock;
|
|
212
|
+
records: Records<Task>;
|
|
213
|
+
/** The action types registered, by `<plugin>.<name>`. */
|
|
214
|
+
actions: Map<string, ActionType>;
|
|
215
|
+
planner: Planner;
|
|
216
|
+
/** Absent on a plugin's own test that does not give a router. */
|
|
217
|
+
router?: Router | undefined;
|
|
218
|
+
/** The scheduler's time zone (the `timeZone` setting, else the system's). */
|
|
219
|
+
zone: () => string;
|
|
220
|
+
/** How long a run has, in ms (the `runDeadline` setting). */
|
|
221
|
+
deadline: () => number;
|
|
222
|
+
log: (what: string) => (error: unknown) => void;
|
|
223
|
+
/** A line of task `id`'s history (bridge#209): logged with `subject: 'task:<id>'`, read back by its Logs tab. Best
|
|
224
|
+
* effort: nothing here reads it back to decide anything. */
|
|
225
|
+
history: (
|
|
226
|
+
id: string,
|
|
227
|
+
level: 'info' | 'warn' | 'error',
|
|
228
|
+
message: string,
|
|
229
|
+
data?: Record<string, unknown>,
|
|
230
|
+
) => void;
|
|
231
|
+
/** This plugin's key, which names its log file: the Logs tab reads it. */
|
|
232
|
+
key: string;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The scheduled tasks of this workspace: their routes, their scheduler entries, and the runs they ask for. */
|
|
236
|
+
export function createTasks({
|
|
237
|
+
ctx,
|
|
238
|
+
clock,
|
|
239
|
+
records,
|
|
240
|
+
actions,
|
|
241
|
+
planner,
|
|
242
|
+
router,
|
|
243
|
+
zone,
|
|
244
|
+
deadline,
|
|
245
|
+
log,
|
|
246
|
+
history,
|
|
247
|
+
key,
|
|
248
|
+
}: Deps) {
|
|
249
|
+
const refOf = (id: string) => ({ domain: DOMAIN, id });
|
|
250
|
+
const iso = (ms: number) => new Date(ms).toISOString();
|
|
251
|
+
const find = (id: string) => records.get(id);
|
|
252
|
+
const all = () => records.query({ node: 'root', include: 'subtree' });
|
|
253
|
+
const entryOf = (id: string) => planner.list({ owner: OWNER, key: KEY, ref: refOf(id) })[0];
|
|
254
|
+
/** Plans the task's entry from now (replacing one there). */
|
|
255
|
+
const plan = (id: string, value: Task) =>
|
|
256
|
+
planner.schedule(OWNER, {
|
|
257
|
+
ref: refOf(id),
|
|
258
|
+
key: KEY,
|
|
259
|
+
node: 'root',
|
|
260
|
+
rule: ruleOf(value.schedule, new Date(clock.now())),
|
|
261
|
+
catchUp: 'last',
|
|
262
|
+
label: value.title,
|
|
263
|
+
});
|
|
264
|
+
/** Cancels the task's entry; a scheduler failure is logged (the task keeps its record). */
|
|
265
|
+
const cancel = async (id: string) => {
|
|
266
|
+
try {
|
|
267
|
+
await planner.cancel(OWNER, { ref: refOf(id), key: KEY });
|
|
268
|
+
} catch (error) {
|
|
269
|
+
log(`scheduled task ${id}: entry not cancelled`)(error);
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
/** The schedule a body gives, as an object or its JSON text. */
|
|
273
|
+
const scheduleOf = (input: unknown): Schedule => {
|
|
274
|
+
let value = input;
|
|
275
|
+
if (typeof value === 'string') {
|
|
276
|
+
try {
|
|
277
|
+
value = JSON.parse(value);
|
|
278
|
+
} catch {
|
|
279
|
+
throw refused('invalid_body', SCHEDULE_USAGE, 400);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
const parsed = schedule.safeParse(value);
|
|
283
|
+
if (!parsed.success) throw refused('invalid_body', SCHEDULE_USAGE, 400);
|
|
284
|
+
return parsed.data;
|
|
285
|
+
};
|
|
286
|
+
/** A registered action type and its parsed input; an unknown type or a refused input is a 400. */
|
|
287
|
+
const actionOf = (typeId: string, raw: unknown) => {
|
|
288
|
+
const type = actions.get(typeId);
|
|
289
|
+
if (!type) throw refused('unknown_action', `no action type ${typeId}`, 400);
|
|
290
|
+
let input: unknown;
|
|
291
|
+
try {
|
|
292
|
+
input = type.parse(raw ?? {});
|
|
293
|
+
} catch (error) {
|
|
294
|
+
const code = (error as { code?: unknown } | undefined)?.code;
|
|
295
|
+
if (code === 'invalid_body' || code === undefined)
|
|
296
|
+
throw refused('invalid_body', messageOf(error), 400);
|
|
297
|
+
throw error;
|
|
298
|
+
}
|
|
299
|
+
return { typeId, type, input: input === undefined ? null : input };
|
|
300
|
+
};
|
|
301
|
+
/** The action of a prompt scheduled from `session`: its type's own `fromSession` makes the input, then parses it as
|
|
302
|
+
* any input. A new session per run (`bindToCurrentThread: false`) is `sessions.start`; else a prompt into
|
|
303
|
+
* that session. An unregistered type, or one that cannot make an input from a session, is a 400. */
|
|
304
|
+
const promptAction = async (
|
|
305
|
+
session: string,
|
|
306
|
+
prompt: string,
|
|
307
|
+
bindToCurrentThread: boolean | undefined,
|
|
308
|
+
) => {
|
|
309
|
+
const typeId = bindToCurrentThread === false ? 'sessions.start' : 'sessions.prompt';
|
|
310
|
+
const type = actions.get(typeId);
|
|
311
|
+
if (!type?.fromSession) throw refused('unknown_action', `no action type ${typeId}`, 400);
|
|
312
|
+
return actionOf(typeId, await type.fromSession(session, prompt));
|
|
313
|
+
};
|
|
314
|
+
const answer = async (found: Found<Task>) => {
|
|
315
|
+
const { value } = found;
|
|
316
|
+
const type = actions.get(value.action.type);
|
|
317
|
+
return {
|
|
318
|
+
scheduledTaskId: found.id,
|
|
319
|
+
title: value.title,
|
|
320
|
+
enabled: value.enabled,
|
|
321
|
+
schedule: value.schedule,
|
|
322
|
+
scheduleText: scheduleLabel(value.schedule),
|
|
323
|
+
action: value.action,
|
|
324
|
+
actionTitle: type?.title ?? value.action.type,
|
|
325
|
+
available: type !== undefined,
|
|
326
|
+
...(value.subject !== undefined && { subject: value.subject }),
|
|
327
|
+
state: running.has(found.id)
|
|
328
|
+
? 'running'
|
|
329
|
+
: !value.enabled
|
|
330
|
+
? 'off'
|
|
331
|
+
: value.suspended
|
|
332
|
+
? 'suspended'
|
|
333
|
+
: 'waiting',
|
|
334
|
+
...(running.has(found.id) && {
|
|
335
|
+
runningSince: running.get(found.id)!.since,
|
|
336
|
+
pastDeadline: running.get(found.id)!.pastDeadline,
|
|
337
|
+
}),
|
|
338
|
+
...(value.suspended && { suspendedReason: value.suspended.reason }),
|
|
339
|
+
failures: value.failures ?? 0,
|
|
340
|
+
nextRunAt: value.enabled && !value.suspended ? (entryOf(found.id)?.next ?? null) : null,
|
|
341
|
+
lastRunStatus: value.lastRunStatus,
|
|
342
|
+
...(value.lastRunAt !== undefined && { lastRunAt: value.lastRunAt }),
|
|
343
|
+
...(value.lastRunError !== undefined && { lastRunError: value.lastRunError }),
|
|
344
|
+
...(value.lastRunSummary !== undefined && { lastRunSummary: value.lastRunSummary }),
|
|
345
|
+
runCount: value.runCount,
|
|
346
|
+
createdBy: value.createdBy,
|
|
347
|
+
};
|
|
348
|
+
};
|
|
349
|
+
/** The runs in progress, by task: since when, past their deadline, and whether one more is asked for (`force`: Run
|
|
350
|
+
* now, which runs even off or suspended). */
|
|
351
|
+
const running = new Map<
|
|
352
|
+
string,
|
|
353
|
+
{
|
|
354
|
+
since: string;
|
|
355
|
+
pastDeadline: boolean;
|
|
356
|
+
again?: { force: boolean };
|
|
357
|
+
controller: AbortController;
|
|
358
|
+
}
|
|
359
|
+
>();
|
|
360
|
+
/** The plugin stopped: nothing more is started or recorded. */
|
|
361
|
+
let stopped = false;
|
|
362
|
+
/** A task's record changes one after another: a run's outcome, an edit, a Resume, a delete each read the record and
|
|
363
|
+
* write it whole, and two at once lost one (an edit, a Resume undone by a run ending meanwhile).
|
|
364
|
+
* ponytail: one queue for every task; one per task if writes ever pile up. */
|
|
365
|
+
let writes: Promise<unknown> = Promise.resolve();
|
|
366
|
+
const oneAtATime = <T>(change: () => Promise<T>): Promise<T> => {
|
|
367
|
+
const run = writes.then(change, change);
|
|
368
|
+
writes = run.catch(() => {});
|
|
369
|
+
return run;
|
|
370
|
+
};
|
|
371
|
+
/** The creates under way by caller and `clientRequestId`: a retry sent while the first create still runs waits for
|
|
372
|
+
* it, then finds its task, instead of making a second one. */
|
|
373
|
+
const creating = new Map<string, Promise<unknown>>();
|
|
374
|
+
const oneCreateAtATime = <T>(key: string, change: () => Promise<T>): Promise<T> => {
|
|
375
|
+
const run = (creating.get(key) ?? Promise.resolve()).then(change, change);
|
|
376
|
+
const settled = run.catch(() => {});
|
|
377
|
+
creating.set(key, settled);
|
|
378
|
+
void settled
|
|
379
|
+
.then(() => {
|
|
380
|
+
if (creating.get(key) === settled) creating.delete(key);
|
|
381
|
+
})
|
|
382
|
+
.catch(() => {});
|
|
383
|
+
return run;
|
|
384
|
+
};
|
|
385
|
+
/** Records a run's outcome, unless the plugin stopped meanwhile (a run cut by a reload is neither a success nor a
|
|
386
|
+
* failure). */
|
|
387
|
+
const record = (id: string, outcome: Parameters<typeof recordNow>[1]) =>
|
|
388
|
+
oneAtATime(async () => {
|
|
389
|
+
if (!stopped) await recordNow(id, outcome);
|
|
390
|
+
});
|
|
391
|
+
/** A run's record on the task as it is now (an edit during the run kept): its outcome, one more run, the failures in
|
|
392
|
+
* a row, a suspension at the third (or at `gone`). A task deleted meanwhile is left gone. */
|
|
393
|
+
const recordNow = async (
|
|
394
|
+
id: string,
|
|
395
|
+
outcome: {
|
|
396
|
+
at: string;
|
|
397
|
+
status: RunStatus;
|
|
398
|
+
error?: string | undefined;
|
|
399
|
+
summary?: string | undefined;
|
|
400
|
+
gone?: boolean;
|
|
401
|
+
},
|
|
402
|
+
) => {
|
|
403
|
+
const found = await find(id);
|
|
404
|
+
if (!found) return;
|
|
405
|
+
const {
|
|
406
|
+
lastRunError: _error,
|
|
407
|
+
lastRunSummary: _summary,
|
|
408
|
+
failures: was,
|
|
409
|
+
suspended: _suspended,
|
|
410
|
+
...rest
|
|
411
|
+
} = found.value;
|
|
412
|
+
const failures = outcome.status === 'succeeded' ? 0 : (was ?? 0) + 1;
|
|
413
|
+
const suspended =
|
|
414
|
+
found.value.suspended ??
|
|
415
|
+
(outcome.gone || failures >= FAILURES_MAX
|
|
416
|
+
? { reason: outcome.error ?? 'failed', at: iso(clock.now()) }
|
|
417
|
+
: undefined);
|
|
418
|
+
const value: Task = {
|
|
419
|
+
...rest,
|
|
420
|
+
lastRunAt: outcome.at,
|
|
421
|
+
lastRunStatus: outcome.status,
|
|
422
|
+
...(outcome.error !== undefined && { lastRunError: outcome.error }),
|
|
423
|
+
...(outcome.summary !== undefined && { lastRunSummary: outcome.summary }),
|
|
424
|
+
runCount: found.value.runCount + 1,
|
|
425
|
+
...(failures > 0 && { failures }),
|
|
426
|
+
...(suspended && { suspended }),
|
|
427
|
+
};
|
|
428
|
+
if (suspended && !found.value.suspended) {
|
|
429
|
+
await cancel(id);
|
|
430
|
+
history(id, 'warn', `Suspended: ${suspended.reason}`, {
|
|
431
|
+
event: 'suspended',
|
|
432
|
+
reason: suspended.reason,
|
|
433
|
+
failures,
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
await records.update(ctx, id, value);
|
|
437
|
+
};
|
|
438
|
+
/** Runs the task's action once at `at`, within its deadline, and records it; its start and end go to its history. */
|
|
439
|
+
const execute = async (found: Found<Task>, at: string, type: ActionType, forced: boolean) => {
|
|
440
|
+
const state = running.get(found.id)!;
|
|
441
|
+
const ms = deadline();
|
|
442
|
+
const trigger = forced ? 'run_now' : 'schedule';
|
|
443
|
+
const began = clock.now();
|
|
444
|
+
const said = trigger === 'run_now' ? 'Run now' : 'on schedule';
|
|
445
|
+
history(found.id, 'info', `Run started (${said})`, { event: 'run_started', trigger, at });
|
|
446
|
+
const ended = (
|
|
447
|
+
status: Exclude<RunStatus, 'never'>,
|
|
448
|
+
detail: { error?: string; summary?: string },
|
|
449
|
+
) => {
|
|
450
|
+
const durationMs = clock.now() - began;
|
|
451
|
+
const seconds = `${(durationMs / 1000).toFixed(1)} s`;
|
|
452
|
+
const text =
|
|
453
|
+
status === 'succeeded'
|
|
454
|
+
? `Run succeeded in ${seconds}${detail.summary ? `: ${detail.summary}` : ''}`
|
|
455
|
+
: status === 'timed_out'
|
|
456
|
+
? `Run timed out after ${seconds}: ${detail.error}`
|
|
457
|
+
: `Run failed after ${seconds}: ${detail.error}`;
|
|
458
|
+
history(found.id, status === 'succeeded' ? 'info' : 'warn', text, {
|
|
459
|
+
event: 'run_finished',
|
|
460
|
+
trigger,
|
|
461
|
+
at,
|
|
462
|
+
status,
|
|
463
|
+
durationMs,
|
|
464
|
+
...detail,
|
|
465
|
+
});
|
|
466
|
+
};
|
|
467
|
+
let late = false;
|
|
468
|
+
let timer: unknown;
|
|
469
|
+
const run = (async () =>
|
|
470
|
+
type.run(found.value.action.input, {
|
|
471
|
+
taskId: found.id,
|
|
472
|
+
title: found.value.title,
|
|
473
|
+
at,
|
|
474
|
+
zone: zone(),
|
|
475
|
+
signal: state.controller.signal,
|
|
476
|
+
}))();
|
|
477
|
+
try {
|
|
478
|
+
const result = await Promise.race([
|
|
479
|
+
run,
|
|
480
|
+
new Promise<never>((_, fail) => {
|
|
481
|
+
timer = clock.setTimeout(() => {
|
|
482
|
+
late = true;
|
|
483
|
+
const minutes = Math.round(ms / 60_000);
|
|
484
|
+
fail(new Error(`no answer within ${minutes} ${minutes === 1 ? 'minute' : 'minutes'}`));
|
|
485
|
+
}, ms);
|
|
486
|
+
}),
|
|
487
|
+
]);
|
|
488
|
+
const summary = result && typeof result.summary === 'string' ? result.summary : undefined;
|
|
489
|
+
ended('succeeded', summary === undefined ? {} : { summary });
|
|
490
|
+
await record(found.id, {
|
|
491
|
+
at,
|
|
492
|
+
status: 'succeeded',
|
|
493
|
+
...(summary !== undefined && { summary }),
|
|
494
|
+
});
|
|
495
|
+
} catch (error) {
|
|
496
|
+
if (!late) {
|
|
497
|
+
ended('failed', { error: messageOf(error) });
|
|
498
|
+
await record(found.id, {
|
|
499
|
+
at,
|
|
500
|
+
status: 'failed',
|
|
501
|
+
error: messageOf(error),
|
|
502
|
+
// What the task acts on no longer exists: suspend it instead of failing forever.
|
|
503
|
+
gone: (error as { code?: unknown } | undefined)?.code === 'gone',
|
|
504
|
+
});
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
state.pastDeadline = true;
|
|
508
|
+
state.controller.abort();
|
|
509
|
+
ended('timed_out', { error: messageOf(error) });
|
|
510
|
+
await record(found.id, { at, status: 'timed_out', error: messageOf(error) });
|
|
511
|
+
// Never two runs at once: the task stays running until the action really ends; its answer is refused.
|
|
512
|
+
await run.catch(() => {});
|
|
513
|
+
} finally {
|
|
514
|
+
clock.clearTimeout(timer);
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
/** Starts a run of task `id` at `at`, or asks for one more after the run in progress. `force` (Run now) runs it even
|
|
518
|
+
* off or suspended. */
|
|
519
|
+
const start = (id: string, at: string, force: boolean) => {
|
|
520
|
+
if (stopped) return;
|
|
521
|
+
const busy = running.get(id);
|
|
522
|
+
if (busy) {
|
|
523
|
+
if (!busy.again)
|
|
524
|
+
history(
|
|
525
|
+
id,
|
|
526
|
+
'info',
|
|
527
|
+
`Run queued after the one in progress (${force ? 'Run now' : 'on schedule'})`,
|
|
528
|
+
{
|
|
529
|
+
event: 'queued',
|
|
530
|
+
trigger: force ? 'run_now' : 'schedule',
|
|
531
|
+
},
|
|
532
|
+
);
|
|
533
|
+
busy.again = { force: force || (busy.again?.force ?? false) };
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
running.set(id, { since: at, pastDeadline: false, controller: new AbortController() });
|
|
537
|
+
void (async () => {
|
|
538
|
+
let when = at;
|
|
539
|
+
let forced = force;
|
|
540
|
+
for (;;) {
|
|
541
|
+
const found = await find(id);
|
|
542
|
+
const type = found && actions.get(found.value.action.type);
|
|
543
|
+
if (!found || !type || (!forced && (!found.value.enabled || found.value.suspended))) break;
|
|
544
|
+
await execute(found, when, type, forced);
|
|
545
|
+
const again = running.get(id)?.again;
|
|
546
|
+
if (!again || stopped) break;
|
|
547
|
+
when = iso(clock.now());
|
|
548
|
+
forced = again.force;
|
|
549
|
+
running.set(id, { since: when, pastDeadline: false, controller: new AbortController() });
|
|
550
|
+
}
|
|
551
|
+
})()
|
|
552
|
+
.catch(log(`scheduled task ${id}: run not recorded`))
|
|
553
|
+
.finally(() => running.delete(id));
|
|
554
|
+
};
|
|
555
|
+
|
|
556
|
+
if (router) {
|
|
557
|
+
router.route(ctx, {
|
|
558
|
+
method: 'GET',
|
|
559
|
+
path: '/scheduler/actions',
|
|
560
|
+
handle: () => ({
|
|
561
|
+
actions: [...actions].map(([type, action]) => ({
|
|
562
|
+
type,
|
|
563
|
+
title: action.title,
|
|
564
|
+
...(action.description !== undefined && { description: action.description }),
|
|
565
|
+
...(action.icon !== undefined && { icon: action.icon }),
|
|
566
|
+
input: action.input,
|
|
567
|
+
})),
|
|
568
|
+
}),
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
router.route(ctx, {
|
|
572
|
+
method: 'GET',
|
|
573
|
+
path: '/scheduler/actions/options',
|
|
574
|
+
handle: async ({ query }) => {
|
|
575
|
+
const typeId = query?.get('type') ?? '';
|
|
576
|
+
const kind = query?.get('kind') ?? '';
|
|
577
|
+
const type = actions.get(typeId);
|
|
578
|
+
if (!type) throw refused('unknown_action', `no action type ${typeId}`, 400);
|
|
579
|
+
// The input the form holds now, as JSON text; absent or unreadable: nothing to follow.
|
|
580
|
+
const text = query?.get('input');
|
|
581
|
+
let input: unknown;
|
|
582
|
+
if (text) {
|
|
583
|
+
try {
|
|
584
|
+
input = JSON.parse(text);
|
|
585
|
+
} catch {}
|
|
586
|
+
}
|
|
587
|
+
return { options: type.options ? await type.options(kind, input) : [] };
|
|
588
|
+
},
|
|
589
|
+
});
|
|
590
|
+
|
|
591
|
+
router.route(ctx, {
|
|
592
|
+
method: 'GET',
|
|
593
|
+
path: '/scheduler/tasks',
|
|
594
|
+
handle: async ({ query }) => {
|
|
595
|
+
const domain = query?.get('subjectDomain');
|
|
596
|
+
const id = query?.get('subjectId');
|
|
597
|
+
const found = await all();
|
|
598
|
+
return {
|
|
599
|
+
/** Where the tasks' history is: this workspace's file of this plugin (the Logs tab reads it). */
|
|
600
|
+
logs: { plugin: key },
|
|
601
|
+
tasks: await Promise.all(
|
|
602
|
+
found
|
|
603
|
+
.filter(
|
|
604
|
+
({ value }) =>
|
|
605
|
+
(domain == null || value.subject?.domain === domain) &&
|
|
606
|
+
(id == null || value.subject?.id === id),
|
|
607
|
+
)
|
|
608
|
+
.map(answer),
|
|
609
|
+
),
|
|
610
|
+
};
|
|
611
|
+
},
|
|
612
|
+
});
|
|
613
|
+
|
|
614
|
+
router.route(ctx, {
|
|
615
|
+
method: 'POST',
|
|
616
|
+
path: '/scheduler/tasks',
|
|
617
|
+
handle: async ({ actor, body }) => {
|
|
618
|
+
const wanted = parse(createBody, body, CREATE_USAGE);
|
|
619
|
+
const when = scheduleOf(wanted.schedule);
|
|
620
|
+
const createdBy = actor?.startsWith('agent:') ? actor : 'person';
|
|
621
|
+
const { clientRequestId } = wanted;
|
|
622
|
+
if (clientRequestId === undefined) return make();
|
|
623
|
+
// The create as it is meant, whatever its spelling: the schedule read, the session a prompt runs in, keys sorted.
|
|
624
|
+
const { clientRequestId: _key, schedule: _schedule, session: _session, ...rest } = wanted;
|
|
625
|
+
const meant = { ...rest, schedule: when, session: sessionOf() };
|
|
626
|
+
const request = createHash('sha256')
|
|
627
|
+
.update(
|
|
628
|
+
JSON.stringify(meant, (_name, each: unknown) =>
|
|
629
|
+
each && typeof each === 'object' && !Array.isArray(each)
|
|
630
|
+
? Object.fromEntries(Object.entries(each).sort(([a], [b]) => a.localeCompare(b)))
|
|
631
|
+
: each,
|
|
632
|
+
),
|
|
633
|
+
)
|
|
634
|
+
.digest('hex');
|
|
635
|
+
return oneCreateAtATime(`${createdBy}\n${clientRequestId}`, async () => {
|
|
636
|
+
const same = (await all()).find(
|
|
637
|
+
({ value }) =>
|
|
638
|
+
value.createdBy === createdBy && value.clientRequestId === clientRequestId,
|
|
639
|
+
);
|
|
640
|
+
if (!same) return make(request);
|
|
641
|
+
if (same.value.request !== undefined && same.value.request !== request)
|
|
642
|
+
throw refused(
|
|
643
|
+
'client_request_conflict',
|
|
644
|
+
`clientRequestId ${clientRequestId} named another scheduled task: give a new clientRequestId for a new task`,
|
|
645
|
+
409,
|
|
646
|
+
);
|
|
647
|
+
return answer(same);
|
|
648
|
+
});
|
|
649
|
+
function sessionOf() {
|
|
650
|
+
// The caller's own session, never an id it gives: a task cannot be planted into another session.
|
|
651
|
+
return actor?.startsWith('agent:') ? actor.slice('agent:'.length) : wanted.session;
|
|
652
|
+
}
|
|
653
|
+
async function make(request?: string) {
|
|
654
|
+
let action: ReturnType<typeof actionOf>;
|
|
655
|
+
if (wanted.action !== undefined) {
|
|
656
|
+
action = actionOf(wanted.action.type, wanted.action.input ?? {});
|
|
657
|
+
} else {
|
|
658
|
+
if (wanted.prompt === undefined) throw refused('invalid_body', CREATE_USAGE, 400);
|
|
659
|
+
const session = sessionOf();
|
|
660
|
+
if (!session)
|
|
661
|
+
throw refused(
|
|
662
|
+
'invalid_body',
|
|
663
|
+
'POST /scheduler/tasks from the UI takes the session a prompt runs in: give `session`',
|
|
664
|
+
400,
|
|
665
|
+
);
|
|
666
|
+
action = await promptAction(session, wanted.prompt, wanted.bindToCurrentThread);
|
|
667
|
+
}
|
|
668
|
+
const derived = action.type.titleOf?.(action.input);
|
|
669
|
+
const title = wanted.title ?? (derived && derived.trim() ? derived : action.type.title);
|
|
670
|
+
const subject = action.type.subject?.(action.input);
|
|
671
|
+
const value: Task = {
|
|
672
|
+
title,
|
|
673
|
+
enabled: wanted.enabled ?? true,
|
|
674
|
+
schedule: when,
|
|
675
|
+
action: { type: action.typeId, input: action.input },
|
|
676
|
+
...(subject !== undefined && { subject }),
|
|
677
|
+
createdBy,
|
|
678
|
+
...(wanted.clientRequestId !== undefined && {
|
|
679
|
+
clientRequestId: wanted.clientRequestId,
|
|
680
|
+
}),
|
|
681
|
+
...(request !== undefined && { request }),
|
|
682
|
+
lastRunStatus: 'never',
|
|
683
|
+
runCount: 0,
|
|
684
|
+
};
|
|
685
|
+
const made = await records.create(ctx, value, { node: 'root' });
|
|
686
|
+
try {
|
|
687
|
+
if (value.enabled) await plan(made.id, value);
|
|
688
|
+
} catch (error) {
|
|
689
|
+
await records.purge(ctx, made.id).catch(() => {});
|
|
690
|
+
throw error;
|
|
691
|
+
}
|
|
692
|
+
history(made.id, 'info', `Created by ${createdBy === 'person' ? 'you' : createdBy}`, {
|
|
693
|
+
event: 'created',
|
|
694
|
+
by: createdBy,
|
|
695
|
+
});
|
|
696
|
+
return answer(made);
|
|
697
|
+
}
|
|
698
|
+
},
|
|
699
|
+
});
|
|
700
|
+
|
|
701
|
+
router.route(ctx, {
|
|
702
|
+
method: 'POST',
|
|
703
|
+
path: '/scheduler/tasks/update',
|
|
704
|
+
handle: async ({ actor, body }) => {
|
|
705
|
+
const wanted = parse(updateBody, body, UPDATE_USAGE);
|
|
706
|
+
return oneAtATime(async () => {
|
|
707
|
+
const found = await find(wanted.scheduledTaskId);
|
|
708
|
+
if (!found)
|
|
709
|
+
throw refused('not_found', `no scheduled task ${wanted.scheduledTaskId}`, 404);
|
|
710
|
+
let action = found.value.action;
|
|
711
|
+
let subject = found.value.subject;
|
|
712
|
+
if (wanted.action !== undefined) {
|
|
713
|
+
const changed = actionOf(wanted.action.type, wanted.action.input ?? {});
|
|
714
|
+
action = { type: changed.typeId, input: changed.input };
|
|
715
|
+
// What the task acts on follows its action.
|
|
716
|
+
subject = changed.type.subject?.(changed.input);
|
|
717
|
+
}
|
|
718
|
+
const enabled = wanted.enabled ?? found.value.enabled;
|
|
719
|
+
const when =
|
|
720
|
+
wanted.schedule !== undefined ? scheduleOf(wanted.schedule) : found.value.schedule;
|
|
721
|
+
const { subject: _subject, ...base } = found.value;
|
|
722
|
+
const value: Task = {
|
|
723
|
+
...base,
|
|
724
|
+
...(wanted.title !== undefined && { title: wanted.title }),
|
|
725
|
+
schedule: when,
|
|
726
|
+
enabled,
|
|
727
|
+
action,
|
|
728
|
+
...(subject !== undefined && { subject }),
|
|
729
|
+
};
|
|
730
|
+
// A title or action change keeps the entry (and its next run); a schedule, a pause or a resume plans it anew.
|
|
731
|
+
const moved = wanted.schedule !== undefined || enabled !== found.value.enabled;
|
|
732
|
+
if (moved) await cancel(found.id);
|
|
733
|
+
const kept = await records.update(ctx, found.id, value);
|
|
734
|
+
if (enabled && !value.suspended) {
|
|
735
|
+
if (moved || !entryOf(found.id)) await plan(found.id, value);
|
|
736
|
+
}
|
|
737
|
+
const changed = (['title', 'schedule', 'action'] as const).filter(
|
|
738
|
+
(field) => JSON.stringify(value[field]) !== JSON.stringify(found.value[field]),
|
|
739
|
+
);
|
|
740
|
+
if (enabled !== found.value.enabled)
|
|
741
|
+
history(found.id, 'info', enabled ? 'Switched on' : 'Paused', {
|
|
742
|
+
event: enabled ? 'enabled' : 'paused',
|
|
743
|
+
by: actor ?? 'person',
|
|
744
|
+
});
|
|
745
|
+
if (changed.length)
|
|
746
|
+
history(found.id, 'info', `Edited: ${changed.join(', ')}`, {
|
|
747
|
+
event: 'edited',
|
|
748
|
+
changed,
|
|
749
|
+
by: actor ?? 'person',
|
|
750
|
+
});
|
|
751
|
+
return answer(kept);
|
|
752
|
+
});
|
|
753
|
+
},
|
|
754
|
+
});
|
|
755
|
+
|
|
756
|
+
router.route(ctx, {
|
|
757
|
+
method: 'POST',
|
|
758
|
+
path: '/scheduler/tasks/delete',
|
|
759
|
+
handle: async ({ body }) => {
|
|
760
|
+
const { scheduledTaskId } = parse(taskBody, body, TASK_USAGE);
|
|
761
|
+
return oneAtATime(async () => {
|
|
762
|
+
const found = await find(scheduledTaskId);
|
|
763
|
+
if (!found) throw refused('not_found', `no scheduled task ${scheduledTaskId}`, 404);
|
|
764
|
+
await cancel(scheduledTaskId);
|
|
765
|
+
await records.purge(ctx, scheduledTaskId);
|
|
766
|
+
running.get(scheduledTaskId)?.controller.abort();
|
|
767
|
+
history(scheduledTaskId, 'info', 'Deleted', { event: 'deleted' });
|
|
768
|
+
return { scheduledTaskId, deleted: true };
|
|
769
|
+
});
|
|
770
|
+
},
|
|
771
|
+
});
|
|
772
|
+
|
|
773
|
+
router.route(ctx, {
|
|
774
|
+
method: 'POST',
|
|
775
|
+
path: '/scheduler/tasks/run',
|
|
776
|
+
handle: async ({ body }) => {
|
|
777
|
+
const { scheduledTaskId } = parse(taskBody, body, TASK_USAGE);
|
|
778
|
+
const found = await find(scheduledTaskId);
|
|
779
|
+
if (!found) throw refused('not_found', `no scheduled task ${scheduledTaskId}`, 404);
|
|
780
|
+
const type = actions.get(found.value.action.type);
|
|
781
|
+
if (!type)
|
|
782
|
+
throw refused(
|
|
783
|
+
'action_unavailable',
|
|
784
|
+
`action type ${found.value.action.type} is not registered`,
|
|
785
|
+
409,
|
|
786
|
+
);
|
|
787
|
+
// Runs now even off or suspended (it lifts no suspension); its next planned run stays.
|
|
788
|
+
start(found.id, iso(clock.now()), true);
|
|
789
|
+
return answer(found);
|
|
790
|
+
},
|
|
791
|
+
});
|
|
792
|
+
|
|
793
|
+
router.route(ctx, {
|
|
794
|
+
method: 'POST',
|
|
795
|
+
path: '/scheduler/tasks/resume',
|
|
796
|
+
handle: async ({ actor, body }) => {
|
|
797
|
+
const { scheduledTaskId } = parse(taskBody, body, TASK_USAGE);
|
|
798
|
+
return oneAtATime(async () => {
|
|
799
|
+
const found = await find(scheduledTaskId);
|
|
800
|
+
if (!found) throw refused('not_found', `no scheduled task ${scheduledTaskId}`, 404);
|
|
801
|
+
if (!found.value.suspended) return answer(found);
|
|
802
|
+
const { suspended: _suspended, failures: _failures, ...value } = found.value;
|
|
803
|
+
const kept = await records.update(ctx, found.id, value);
|
|
804
|
+
// The next slot from now: nothing missed is replayed.
|
|
805
|
+
if (value.enabled) await plan(found.id, value);
|
|
806
|
+
history(found.id, 'info', 'Resumed', { event: 'resumed', by: actor ?? 'person' });
|
|
807
|
+
return answer(kept);
|
|
808
|
+
});
|
|
809
|
+
},
|
|
810
|
+
});
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/** A delivery of a task's entry: a fixed time more than `MISSED_MS` late is skipped; its action type not registered
|
|
814
|
+
* throws (the core retries it); else its run starts (or is merged into the one in progress), not awaited. */
|
|
815
|
+
const due = async (delivery: Delivery) => {
|
|
816
|
+
const { entry, scheduledFor, firedAt } = delivery;
|
|
817
|
+
if (entry.ref.domain !== DOMAIN || entry.key !== KEY) return;
|
|
818
|
+
const found = await find(entry.ref.id);
|
|
819
|
+
if (!found || !found.value.enabled || found.value.suspended) return;
|
|
820
|
+
if (
|
|
821
|
+
found.value.schedule.type === 'fixed_time' &&
|
|
822
|
+
Date.parse(firedAt) - Date.parse(scheduledFor) > MISSED_MS
|
|
823
|
+
) {
|
|
824
|
+
const minutes = Math.round((Date.parse(firedAt) - Date.parse(scheduledFor)) / 60_000);
|
|
825
|
+
history(found.id, 'info', `Slot of ${scheduledFor} skipped: ${minutes} minutes late`, {
|
|
826
|
+
event: 'slot_skipped',
|
|
827
|
+
scheduledFor,
|
|
828
|
+
firedAt,
|
|
829
|
+
});
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
// Not registered yet: throw, so the core retries after a minute (the plugin may load after the scheduler).
|
|
833
|
+
if (!actions.has(found.value.action.type))
|
|
834
|
+
throw new Error(`action type ${found.value.action.type} is not registered`);
|
|
835
|
+
start(found.id, firedAt, false);
|
|
836
|
+
};
|
|
837
|
+
/** The plugin stops (a reload, a restart): the runs in progress are signalled, none starts; one cut is not replayed. */
|
|
838
|
+
const stop = () => {
|
|
839
|
+
stopped = true;
|
|
840
|
+
for (const each of running.values()) each.controller.abort();
|
|
841
|
+
};
|
|
842
|
+
return { due, stop };
|
|
843
|
+
}
|