@operad-io/source-cron 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yinghai Zhao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
- # Temporary Holding Version
1
+ # @operad-io/source-cron
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **The cron trigger source.** Emits a tick for a cron rule. Part of [operad](https://github.com/operad-io/operad); `@operad-io/cli` installs it and a new home loads it.
4
+
5
+ ## Documentation
6
+
7
+ - User guide: [docs/user/index.md](https://github.com/operad-io/operad/blob/main/docs/user/index.md)
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "@operad-io/source-cron",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.0",
4
+ "description": "routines that start work on a schedule",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.ts"
8
+ },
9
+ "dependencies": {
10
+ "@operad-io/engine": "0.5.0"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/operad-io/operad.git",
15
+ "directory": "packages/source-cron"
16
+ },
17
+ "license": "MIT",
18
+ "files": [
19
+ "src",
20
+ "README.md",
21
+ "LICENSE"
22
+ ]
23
+ }
package/src/index.ts ADDED
@@ -0,0 +1,313 @@
1
+ import pkg from "../package.json" with { type: "json" };
2
+ import { definePlugin, type ActionTypeDefinition } from "@operad-io/engine";
3
+ import {
4
+ cronMinutesBetween,
5
+ latestCronMinute,
6
+ minuteStart,
7
+ parseCron,
8
+ } from "@operad-io/engine";
9
+ import type {
10
+ CronSchedule,
11
+ SourceContext,
12
+ SourceHandle,
13
+ TriggerRule,
14
+ } from "@operad-io/engine";
15
+ import { readCronState, ruleStateKey, writeCronState, type CronState } from "./state.ts";
16
+ import { routineToFlow, scheduledCommand, scheduledId } from "./schedules.ts";
17
+
18
+ export * from "./schedules.ts";
19
+
20
+ /** How often the running source checks the clock. */
21
+ const CHECK_INTERVAL_MS = 1_000;
22
+ /** A gap much larger than the check interval means the machine slept or the clock jumped. */
23
+ const WAKE_GAP_MS = 60_000;
24
+ /** How far back a catch-up looks. */
25
+ const CATCH_UP_DAYS = 7;
26
+ const DAY_MS = 24 * 60 * 60_000;
27
+
28
+ /** One cron rule and how far it has emitted. */
29
+ interface CronRule {
30
+ readonly rule: TriggerRule;
31
+ readonly schedule: CronSchedule;
32
+ readonly expression: string;
33
+ readonly paused: boolean;
34
+ last: number | null;
35
+ /** A rule with no recorded last time begins at its latest planned time. */
36
+ baseline: boolean;
37
+ }
38
+
39
+ /**
40
+ * The days to look back from `now` to reach `last`, so that a recorded last
41
+ * time stops the backward scan. Never wider than `limitDays` and never
42
+ * negative: a clock that jumped back asks for no scan at all.
43
+ */
44
+ function daysBackTo(
45
+ now: number,
46
+ last: number | null,
47
+ limitDays: number,
48
+ ): number {
49
+ if (last === null) return limitDays;
50
+ const days = (minuteStart(now) - last) / DAY_MS;
51
+ return Math.min(limitDays, Math.max(0, days));
52
+ }
53
+
54
+ /** The pure part: which minute a rule should emit next, if any. */
55
+ export function dueMinute(
56
+ schedule: CronSchedule,
57
+ last: number | null,
58
+ now: number,
59
+ lookbackDays = 366 * 2,
60
+ ): number | null {
61
+ if (last !== null) {
62
+ const candidate = latestCronMinute(
63
+ schedule,
64
+ now,
65
+ daysBackTo(now, last, lookbackDays),
66
+ );
67
+ if (candidate === null || candidate <= last) return null;
68
+ return candidate;
69
+ }
70
+ return latestCronMinute(schedule, now, lookbackDays);
71
+ }
72
+
73
+ /** The stable identity of a rule, independent of its position in the file. */
74
+ function ruleKey(rule: TriggerRule): string {
75
+ return ruleStateKey(rule);
76
+ }
77
+
78
+ /** One line for history naming the times a catch-up passed over. */
79
+ export function skippedLine(skipped: readonly number[]): string {
80
+ const shown =
81
+ skipped.length <= 100
82
+ ? skipped.map((minute) => new Date(minute).toISOString())
83
+ : [
84
+ ...skipped.slice(0, 50).map((minute) => new Date(minute).toISOString()),
85
+ `… ${skipped.length - 50} more …`,
86
+ ];
87
+ return `skipped ${shown.join(", ")}: only the latest missed run is caught up`;
88
+ }
89
+
90
+ /** The cron source, in a shape a test can drive with a fake clock. */
91
+ export class CronSource {
92
+ private readonly ctx: SourceContext;
93
+ private readonly rules: CronRule[];
94
+ private timer: ReturnType<typeof setInterval> | undefined;
95
+ private stopped = false;
96
+ private busy = false;
97
+ private lastCheck: number | undefined;
98
+
99
+ constructor(ctx: SourceContext) {
100
+ this.ctx = ctx;
101
+ const state = readCronState(ctx.home);
102
+ this.rules = [];
103
+ for (const rule of ctx.rules) {
104
+ if (rule.source !== "cron" || rule.schedule === undefined) continue;
105
+ const stored = state.rules[ruleKey(rule)];
106
+ const sameSchedule = stored !== undefined && stored.schedule === rule.schedule;
107
+ this.rules.push({
108
+ rule,
109
+ schedule: parseCron(rule.schedule),
110
+ expression: rule.schedule,
111
+ paused: rule.paused === true,
112
+ last: sameSchedule ? stored.last : null,
113
+ baseline: !sameSchedule,
114
+ });
115
+ }
116
+ }
117
+
118
+ /** Emits at most one tick per rule, for the latest missed minute. */
119
+ async poll(): Promise<void> {
120
+ if (this.stopped || this.busy) return;
121
+ this.busy = true;
122
+ try {
123
+ const now = this.ctx.clock();
124
+ const previous = this.lastCheck;
125
+ const catchUp = previous === undefined || now - previous > WAKE_GAP_MS;
126
+ // The latest planned minute cannot change before the next minute starts,
127
+ // so a poll in a minute already handled finds nothing and scans nothing.
128
+ if (
129
+ !catchUp &&
130
+ previous !== undefined &&
131
+ minuteStart(previous) === minuteStart(now)
132
+ ) {
133
+ return;
134
+ }
135
+ let changed = false;
136
+ for (const entry of this.rules) {
137
+ if (entry.baseline) {
138
+ entry.last =
139
+ latestCronMinute(entry.schedule, now, CATCH_UP_DAYS) ?? minuteStart(now);
140
+ entry.baseline = false;
141
+ changed = true;
142
+ continue;
143
+ }
144
+ if (entry.paused) {
145
+ // A pause does not collect missed times: its recorded minute follows
146
+ // the clock, so resuming waits for the next planned minute.
147
+ const latest =
148
+ latestCronMinute(
149
+ entry.schedule,
150
+ now,
151
+ daysBackTo(now, entry.last, CATCH_UP_DAYS),
152
+ ) ?? minuteStart(now);
153
+ if (entry.last === null || latest > entry.last) {
154
+ entry.last = latest;
155
+ changed = true;
156
+ }
157
+ continue;
158
+ }
159
+ if (catchUp) {
160
+ const result = this.catchUp(entry, now);
161
+ if (result.kind === "baseline") {
162
+ if (entry.last === null || result.last > entry.last) {
163
+ entry.last = result.last;
164
+ changed = true;
165
+ }
166
+ continue;
167
+ }
168
+ await this.emit(entry, result.minute, result.skipped, now);
169
+ entry.last = result.minute;
170
+ changed = true;
171
+ continue;
172
+ }
173
+ const minute = dueMinute(
174
+ entry.schedule,
175
+ entry.last,
176
+ now,
177
+ CATCH_UP_DAYS,
178
+ );
179
+ if (minute === null) continue;
180
+ await this.emit(entry, minute, [], now);
181
+ entry.last = minute;
182
+ changed = true;
183
+ }
184
+ if (changed) writeCronState(this.ctx.home, this.snapshot());
185
+ // A failed emit or state write leaves the minute unhandled, so the next
186
+ // poll tries it again instead of skipping it as already done.
187
+ this.lastCheck = now;
188
+ } finally {
189
+ this.busy = false;
190
+ }
191
+ }
192
+
193
+ /** Finds the latest planned time in the last 7 days, and what it passed over. */
194
+ private catchUp(
195
+ entry: CronRule,
196
+ now: number,
197
+ ):
198
+ | { kind: "tick"; minute: number; skipped: readonly number[] }
199
+ | { kind: "baseline"; last: number } {
200
+ const latest = latestCronMinute(
201
+ entry.schedule,
202
+ now,
203
+ daysBackTo(now, entry.last, CATCH_UP_DAYS),
204
+ );
205
+ if (latest === null) return { kind: "baseline", last: minuteStart(now) };
206
+ if (entry.last !== null && latest <= entry.last) {
207
+ return { kind: "baseline", last: entry.last };
208
+ }
209
+ const windowStart =
210
+ entry.last === null
211
+ ? minuteStart(now) - CATCH_UP_DAYS * DAY_MS
212
+ : Math.max(entry.last, minuteStart(now) - CATCH_UP_DAYS * DAY_MS);
213
+ if (latest <= windowStart) return { kind: "baseline", last: latest };
214
+ const skipped =
215
+ entry.last === null
216
+ ? []
217
+ : cronMinutesBetween(entry.schedule, windowStart, latest).slice(0, -1);
218
+ return { kind: "tick", minute: latest, skipped };
219
+ }
220
+
221
+ private async emit(
222
+ entry: CronRule,
223
+ minute: number,
224
+ skipped: readonly number[],
225
+ now: number,
226
+ ): Promise<void> {
227
+ const lateSecs = Math.floor((now - minute) / 1_000);
228
+ const late = minute < minuteStart(now) || skipped.length > 0;
229
+ await this.ctx.emit({
230
+ source: "cron",
231
+ key: `${scheduledId(entry.rule)}:${new Date(minute).toISOString()}`,
232
+ type: "tick",
233
+ ...(skipped.length === 0 ? {} : { summary: skippedLine(skipped) }),
234
+ ...(late
235
+ ? {
236
+ data: {
237
+ scheduledAt: new Date(minute).toISOString(),
238
+ lateSecs,
239
+ },
240
+ }
241
+ : {}),
242
+ });
243
+ }
244
+
245
+ private snapshot(): CronState {
246
+ const rules: Record<string, { schedule: string; last: number }> = {};
247
+ for (const entry of this.rules) {
248
+ if (entry.last === null) continue;
249
+ rules[ruleKey(entry.rule)] = {
250
+ schedule: entry.expression,
251
+ last: entry.last,
252
+ };
253
+ }
254
+ return { rules };
255
+ }
256
+
257
+ start(): SourceHandle {
258
+ this.timer = setInterval(() => {
259
+ void this.poll();
260
+ }, CHECK_INTERVAL_MS);
261
+ if (typeof this.timer === "object" && "unref" in this.timer) {
262
+ this.timer.unref();
263
+ }
264
+ return {
265
+ stop: () => {
266
+ this.stopped = true;
267
+ if (this.timer !== undefined) clearInterval(this.timer);
268
+ },
269
+ };
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Turns a routine that runs one command into a flow file the person can edit.
275
+ * It targets no object: the routine is named by its id, as `routines list`
276
+ * shows it, so a bot or client offers it when the person asks for more than one command.
277
+ */
278
+ const toFlowAction: ActionTypeDefinition = {
279
+ name: "to-flow",
280
+ args: {
281
+ type: "object",
282
+ properties: {
283
+ routine: { type: "string", minLength: 1, description: "The id of the routine, from the routines list." },
284
+ name: {
285
+ type: "string",
286
+ minLength: 1,
287
+ description: "The flow's file name, `<name>.flow.ts` in the home's flows; `routine-<id>` when left out.",
288
+ },
289
+ },
290
+ required: ["routine"],
291
+ additionalProperties: false,
292
+ },
293
+ when() {
294
+ return true;
295
+ },
296
+ run(ctx, args) {
297
+ const input = args as { readonly routine: string; readonly name?: string | undefined };
298
+ return routineToFlow(ctx.home, input.routine, input.name, Date.now());
299
+ },
300
+ };
301
+
302
+ export default definePlugin({
303
+ name: "cron",
304
+ kind: "source",
305
+ version: pkg.version,
306
+ commands: [scheduledCommand()],
307
+ actions: [toFlowAction],
308
+ start(ctx) {
309
+ const source = new CronSource(ctx);
310
+ void source.poll();
311
+ return source.start();
312
+ },
313
+ });
@@ -0,0 +1,642 @@
1
+ /** Managing the routines (scheduled flows) in `triggers.json`, from a client. */
2
+
3
+ import { messageOf } from "@operad-io/engine";
4
+ import { createHash } from "node:crypto";
5
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { writeJsonAtomicSync } from "@operad-io/engine/platform";
8
+ import {
9
+ cronMatches,
10
+ type CronField,
11
+ isMissingFile,
12
+ isRecord,
13
+ minuteStart,
14
+ openConfigLog,
15
+ parseCron,
16
+ parseTriggerRules,
17
+ readConfig,
18
+ type CommandContext,
19
+ type CommandDefinition,
20
+ type JsonValue,
21
+ type TriggerMode,
22
+ type TriggerRule,
23
+ } from "@operad-io/engine";
24
+ import {
25
+ baselineCronRule,
26
+ readCronState,
27
+ ruleStateKey,
28
+ writeCronState,
29
+ } from "./state.ts";
30
+
31
+ const DAY_MS = 24 * 60 * 60_000;
32
+ const MODES: readonly TriggerMode[] = ["observe", "candidate", "auto"];
33
+
34
+ /** A management call is refused, with a reason a client can show. */
35
+ export class ScheduleError extends Error {
36
+ constructor(message: string) {
37
+ super(message);
38
+ this.name = "ScheduleError";
39
+ }
40
+ }
41
+
42
+ /** How one scheduled flow last ran. */
43
+ export interface ScheduledLastRun {
44
+ readonly runId: string;
45
+ /** `done`, `failed`, `cancelled`, or `running` before the run ends. */
46
+ readonly result: string;
47
+ readonly reason?: string | undefined;
48
+ readonly endedAt?: number | undefined;
49
+ }
50
+
51
+ /** One scheduled flow as a client lists it. */
52
+ export interface ScheduledFlow {
53
+ /** The rule's stable identity; the id add, edit, pause, resume and remove take. */
54
+ readonly id: string;
55
+ readonly flow: string;
56
+ /** The command line of a routine that runs one command; the list shows it in place of the flow. */
57
+ readonly command?: string | undefined;
58
+ readonly schedule: string;
59
+ readonly params?: JsonValue | undefined;
60
+ readonly object: string;
61
+ readonly mode: TriggerMode;
62
+ readonly paused: boolean;
63
+ /** The next planned minute as an ISO time; null when paused. */
64
+ readonly nextRun: string | null;
65
+ readonly lastRun: ScheduledLastRun | null;
66
+ }
67
+
68
+ /** The stable identity of a scheduled rule, from the fields that decide what it starts. */
69
+ export function scheduledId(rule: TriggerRule): string {
70
+ return createHash("sha256").update(ruleStateKey(rule)).digest("hex").slice(0, 16);
71
+ }
72
+
73
+ /** The next planned minute after `now`, or null when none is within two years. */
74
+ export function nextScheduledMinute(expression: string, now: number): number | null {
75
+ let schedule: ReturnType<typeof parseCron>;
76
+ try {
77
+ schedule = parseCron(expression);
78
+ } catch {
79
+ return null;
80
+ }
81
+ const first = minuteStart(now) + 60_000;
82
+ const limit = minuteStart(now) + 366 * 2 * DAY_MS;
83
+ // Only a day the date fields allow is scanned by minute; the rest are skipped whole.
84
+ const anyTime: CronField = { values: new Set(range(60)), restricted: false };
85
+ const dayOnly = { ...schedule, minute: anyTime, hour: anyTime };
86
+ const day = new Date(first);
87
+ day.setHours(0, 0, 0, 0);
88
+ for (; day.getTime() <= limit; day.setDate(day.getDate() + 1)) {
89
+ if (!cronMatches(dayOnly, day)) continue;
90
+ for (const hour of [...schedule.hour.values].sort((a, b) => a - b)) {
91
+ for (const minute of [...schedule.minute.values].sort((a, b) => a - b)) {
92
+ const candidate = new Date(day);
93
+ candidate.setHours(hour, minute, 0, 0);
94
+ const time = candidate.getTime();
95
+ if (time < first || time > limit) continue;
96
+ if (cronMatches(schedule, candidate)) return time;
97
+ }
98
+ }
99
+ }
100
+ return null;
101
+ }
102
+
103
+ /** The flow a command routine starts. */
104
+ export const COMMAND_FLOW = "shell:command";
105
+ const SHELL_OFF = 'shell is off: run "operad plugin enable shell" first';
106
+
107
+ /** The command line a rule runs, when it starts the shell plugin's command flow. */
108
+ function commandOf(rule: TriggerRule): string | undefined {
109
+ if (rule.start.flow !== COMMAND_FLOW) return undefined;
110
+ const params = rule.start.params;
111
+ if (!isRecord(params)) return undefined;
112
+ return typeof params.command === "string" ? params.command : undefined;
113
+ }
114
+
115
+ /** The directory a command routine runs in: its own, or the home. */
116
+ function commandCwd(rule: TriggerRule, home: string): string {
117
+ const params = rule.start.params;
118
+ return isRecord(params) && typeof params.cwd === "string" ? params.cwd : home;
119
+ }
120
+
121
+ const HOME_FLOW_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
122
+
123
+ /** The text of a flow file that does exactly what a command routine does, with notes on how to grow it. */
124
+ export function routineFlowFile(name: string, command: string, cwd: string): string {
125
+ return `import { defineFlow } from "@operad-io/engine";
126
+
127
+ // Made from a routine that ran one command. It does the same: run the command, then end.
128
+ // Edit it freely; the routine now starts this flow as home:${name}.
129
+ export default defineFlow({
130
+ name: ${JSON.stringify(name)},
131
+ entry: "run",
132
+ steps: [
133
+ {
134
+ id: "run",
135
+ kind: "plugin",
136
+ params: { use: "shell/command", params: { line: ${JSON.stringify(command)}, cwd: ${JSON.stringify(cwd)} } },
137
+ replay: "unsafe",
138
+ // The step passes on exit code 0 and fails on any other code (or a timeout).
139
+ next: { pass: "end_done", fail: "end_failed", interrupted: "end_cancelled" },
140
+ },
141
+
142
+ // To add a step: copy the step above under a new id, change its line, and point
143
+ // another step's "next" at it. A step may call any loaded plugin: "<plugin>/<step>".
144
+ //
145
+ // To wait for a person: add a step like this, and point a "next" at "ask".
146
+ // Each key of its "next" is one of the choices.
147
+ // {
148
+ // id: "ask",
149
+ // kind: "wait_person",
150
+ // params: { prompt: "The command failed. Run it again?", choices: ["again", "stop"] },
151
+ // replay: "safe",
152
+ // next: { again: "run", stop: "end_failed" },
153
+ // },
154
+ //
155
+ // To branch on the exit code: a step only has the results pass and fail, so
156
+ // test the code in a step of its own. This one passes when the command exits 3:
157
+ // {
158
+ // id: "check_code",
159
+ // kind: "plugin",
160
+ // params: { use: "shell/command", params: { line: "./job; test $? -eq 3" } },
161
+ // replay: "unsafe",
162
+ // next: { pass: "end_done", fail: "end_failed", interrupted: "end_cancelled" },
163
+ // },
164
+
165
+ { id: "end_done", kind: "end", params: { status: "done" }, replay: "safe" },
166
+ { id: "end_failed", kind: "end", params: { status: "failed" }, replay: "safe" },
167
+ { id: "end_cancelled", kind: "end", params: { status: "cancelled" }, replay: "safe" },
168
+ ],
169
+ });
170
+ `;
171
+ }
172
+
173
+ function range(count: number): number[] {
174
+ return Array.from({ length: count }, (_, index) => index);
175
+ }
176
+
177
+ function triggersFile(home: string): string {
178
+ return join(home, "triggers.json");
179
+ }
180
+
181
+ function readRules(home: string): readonly TriggerRule[] {
182
+ const file = triggersFile(home);
183
+ let text: string;
184
+ try {
185
+ text = readFileSync(file, "utf8");
186
+ } catch (error) {
187
+ if (isMissingFile(error)) {
188
+ return [];
189
+ }
190
+ throw new ScheduleError(`cannot read ${file}: ${String(error)}`);
191
+ }
192
+ let raw: unknown;
193
+ try {
194
+ raw = JSON.parse(text);
195
+ } catch (error) {
196
+ throw new ScheduleError(`${file}: invalid JSON: ${String(error)}`);
197
+ }
198
+ return parseTriggerRules(raw, file);
199
+ }
200
+
201
+ function writeRules(home: string, rules: readonly TriggerRule[]): void {
202
+ writeJsonAtomicSync(triggersFile(home), rules, { space: 2 });
203
+ }
204
+
205
+ function scheduled(rules: readonly TriggerRule[]): readonly TriggerRule[] {
206
+ return rules.filter((rule) => rule.source === "cron" && rule.schedule !== undefined);
207
+ }
208
+
209
+ function found(rules: readonly TriggerRule[], id: string): TriggerRule {
210
+ const rule = scheduled(rules).find((entry) => scheduledId(entry) === id);
211
+ if (rule === undefined) throw new ScheduleError(`there is no routine "${id}"`);
212
+ return rule;
213
+ }
214
+
215
+ function checkedFlow(ctx: CommandContext, flow: string): string {
216
+ if (!ctx.flows.includes(flow)) {
217
+ throw new ScheduleError(`start.flow: unknown flow "${flow}"`);
218
+ }
219
+ return flow;
220
+ }
221
+
222
+ function checkedSchedule(expression: string): string {
223
+ const trimmed = expression.trim();
224
+ try {
225
+ parseCron(trimmed);
226
+ } catch (error) {
227
+ throw new ScheduleError(messageOf(error));
228
+ }
229
+ return trimmed;
230
+ }
231
+
232
+ function checkedMode(mode: string): TriggerMode {
233
+ const known = MODES.find((entry) => entry === mode);
234
+ if (known === undefined) {
235
+ throw new ScheduleError(`mode: must be ${MODES.map((item) => `"${item}"`).join(", ")}`);
236
+ }
237
+ return known;
238
+ }
239
+
240
+ function checkedObject(object: string): string {
241
+ const trimmed = object.trim();
242
+ if (trimmed.length === 0) throw new ScheduleError("object: must be a non-empty string");
243
+ return trimmed;
244
+ }
245
+
246
+ function checkedParams(text: string): JsonValue | undefined {
247
+ if (text.trim().length === 0) return undefined;
248
+ try {
249
+ return JSON.parse(text) as JsonValue;
250
+ } catch (error) {
251
+ throw new ScheduleError(`start.params: is not valid JSON: ${String(error)}`);
252
+ }
253
+ }
254
+
255
+ /** Replaces one rule, or throws when it is gone. */
256
+ function replace(
257
+ rules: readonly TriggerRule[],
258
+ id: string,
259
+ change: (rule: TriggerRule) => TriggerRule,
260
+ ): readonly TriggerRule[] {
261
+ let replaced = false;
262
+ const next = rules.map((rule) => {
263
+ if (scheduledId(rule) !== id) return rule;
264
+ replaced = true;
265
+ return change(rule);
266
+ });
267
+ if (!replaced) throw new ScheduleError(`there is no routine "${id}"`);
268
+ return next;
269
+ }
270
+
271
+ interface CronInput {
272
+ readonly inputId: string;
273
+ readonly source: string;
274
+ readonly sourceKey: string;
275
+ readonly time: number;
276
+ }
277
+
278
+ type RunLog = ReturnType<typeof openConfigLog>;
279
+
280
+ /** The last run each scheduled rule started, read from the log's inputs and run endings. */
281
+ async function lastRuns(
282
+ home: string,
283
+ ids: readonly string[],
284
+ ): Promise<ReadonlyMap<string, ScheduledLastRun>> {
285
+ const result = new Map<string, ScheduledLastRun>();
286
+ if (ids.length === 0) return result;
287
+ const config = await readConfig(home);
288
+ const log = openConfigLog(config);
289
+ try {
290
+ const latest = new Map<string, CronInput>();
291
+ for await (const input of log.readInputs()) {
292
+ if (input.source !== "cron") continue;
293
+ const id = ids.find((candidate) => input.sourceKey.startsWith(`${candidate}:`));
294
+ if (id === undefined) continue;
295
+ const current = latest.get(id);
296
+ if (current === undefined || input.time >= current.time) latest.set(id, input);
297
+ }
298
+ for (const [id, input] of latest) {
299
+ const run = (await log.runs({ startInputId: input.inputId }))[0];
300
+ if (run === undefined) continue;
301
+ result.set(id, await lastRunOf(log, run.runId, run.active));
302
+ }
303
+ } finally {
304
+ await log.close();
305
+ }
306
+ return result;
307
+ }
308
+
309
+ async function lastRunOf(
310
+ log: RunLog,
311
+ runId: string,
312
+ active: boolean,
313
+ ): Promise<ScheduledLastRun> {
314
+ if (active) return { runId, result: "running" };
315
+ let result = "done";
316
+ let reason: string | undefined;
317
+ let stepMessage: string | undefined;
318
+ let endedAt: number | undefined;
319
+ for await (const fact of log.read(runId)) {
320
+ if (fact.kind === "step_result" && isRecord(fact.payload) && isRecord(fact.payload.data)) {
321
+ const message = fact.payload.data.message;
322
+ stepMessage = typeof message === "string" && message.length > 0 ? message : undefined;
323
+ }
324
+ if (fact.kind !== "run_ended" || !isRecord(fact.payload)) continue;
325
+ if (typeof fact.payload.status === "string") result = fact.payload.status;
326
+ if (typeof fact.payload.reason === "string" && fact.payload.reason.length > 0) {
327
+ reason = fact.payload.reason;
328
+ }
329
+ endedAt = fact.time;
330
+ }
331
+ if (reason === undefined && result === "failed") reason = stepMessage;
332
+ return {
333
+ runId,
334
+ result,
335
+ ...(reason === undefined ? {} : { reason }),
336
+ ...(endedAt === undefined ? {} : { endedAt }),
337
+ };
338
+ }
339
+
340
+ async function listFlows(
341
+ home: string,
342
+ now: number,
343
+ ): Promise<readonly ScheduledFlow[]> {
344
+ const rules = scheduled(readRules(home));
345
+ const ids = rules.map(scheduledId);
346
+ const lasts = await lastRuns(home, ids);
347
+ return rules.map((rule) => {
348
+ const id = scheduledId(rule);
349
+ const schedule = rule.schedule ?? "";
350
+ const next = rule.paused === true ? null : nextScheduledMinute(schedule, now);
351
+ return {
352
+ id,
353
+ flow: rule.start.flow,
354
+ ...(commandOf(rule) === undefined ? {} : { command: commandOf(rule) }),
355
+ schedule,
356
+ ...(rule.start.params === undefined ? {} : { params: rule.start.params }),
357
+ object: rule.object,
358
+ mode: rule.mode,
359
+ paused: rule.paused === true,
360
+ nextRun: next === null ? null : new Date(next).toISOString(),
361
+ lastRun: lasts.get(id) ?? null,
362
+ };
363
+ });
364
+ }
365
+
366
+ function line(entry: ScheduledFlow): string {
367
+ const last =
368
+ entry.lastRun === null
369
+ ? "last none"
370
+ : `last ${entry.lastRun.result} ${entry.lastRun.runId}${entry.lastRun.reason === undefined ? "" : `: ${entry.lastRun.reason}`}`;
371
+ const next = entry.paused
372
+ ? "paused"
373
+ : entry.nextRun === null
374
+ ? "next none"
375
+ : `next ${entry.nextRun}`;
376
+ const params =
377
+ entry.params === undefined || entry.command !== undefined
378
+ ? ""
379
+ : ` params ${JSON.stringify(entry.params)}`;
380
+ const what = entry.command === undefined ? entry.flow : `command ${JSON.stringify(entry.command)}`;
381
+ return `${entry.id} ${what} ${entry.schedule} on ${entry.object} (${entry.mode}) ${next} ${last}${params}`;
382
+ }
383
+
384
+ interface ParsedArgs {
385
+ readonly positionals: readonly string[];
386
+ readonly values: ReadonlyMap<string, string>;
387
+ readonly flags: ReadonlySet<string>;
388
+ }
389
+
390
+ function parseArgs(argv: readonly string[]): ParsedArgs {
391
+ const positionals: string[] = [];
392
+ const values = new Map<string, string>();
393
+ const flags = new Set<string>();
394
+ for (let index = 0; index < argv.length; index += 1) {
395
+ const arg = argv[index];
396
+ if (arg === undefined) continue;
397
+ if (!arg.startsWith("--")) {
398
+ positionals.push(arg);
399
+ continue;
400
+ }
401
+ const equals = arg.indexOf("=");
402
+ if (equals >= 0) {
403
+ values.set(arg.slice(0, equals), arg.slice(equals + 1));
404
+ continue;
405
+ }
406
+ const next = argv[index + 1];
407
+ if (next !== undefined && !next.startsWith("--")) {
408
+ values.set(arg, next);
409
+ index += 1;
410
+ continue;
411
+ }
412
+ flags.add(arg);
413
+ }
414
+ return { positionals, values, flags };
415
+ }
416
+
417
+ function required(parsed: ParsedArgs, name: string): string {
418
+ const value = parsed.values.get(name);
419
+ if (value === undefined) throw new ScheduleError(`routines: ${name} is required`);
420
+ return value;
421
+ }
422
+
423
+ function oneId(parsed: ParsedArgs): string {
424
+ const id = parsed.positionals[0];
425
+ if (id === undefined) throw new ScheduleError("routines: needs a routine id");
426
+ if (parsed.positionals.length > 1) {
427
+ throw new ScheduleError("routines: takes one routine id");
428
+ }
429
+ return id;
430
+ }
431
+
432
+ /**
433
+ * Writes a command routine as a flow file of the home and points the routine at
434
+ * it. Both the `routines to-flow` command and the `to-flow` action run this.
435
+ */
436
+ export function routineToFlow(home: string, id: string, nameArg: string | undefined, now: number): string {
437
+ const rules = readRules(home);
438
+ const rule = found(rules, id);
439
+ const command = commandOf(rule);
440
+ if (command === undefined) {
441
+ throw new ScheduleError(`routine "${id}" does not run a command, so it has no flow file to make`);
442
+ }
443
+ const name = nameArg ?? `routine-${id}`;
444
+ if (!HOME_FLOW_NAME.test(name)) {
445
+ throw new ScheduleError(
446
+ `routines: --name "${name}" may use letters, digits, ".", "_" and "-" and must start with a letter or digit`,
447
+ );
448
+ }
449
+ const flows = join(home, "flows");
450
+ const file = join(flows, `${name}.flow.ts`);
451
+ const converted: TriggerRule = { ...rule, start: { flow: `home:${name}` } };
452
+ const convertedId = scheduledId(converted);
453
+ if (scheduled(rules).some((entry) => scheduledId(entry) === convertedId)) {
454
+ throw new ScheduleError(`a routine "${convertedId}" already exists`);
455
+ }
456
+ mkdirSync(flows, { recursive: true });
457
+ try {
458
+ writeFileSync(file, routineFlowFile(name, command, commandCwd(rule, home)), { flag: "wx" });
459
+ } catch (error) {
460
+ if (error instanceof Error && "code" in error && error.code === "EEXIST") {
461
+ throw new ScheduleError(`${file} already exists; choose another name or edit that file`);
462
+ }
463
+ throw new ScheduleError(`cannot write ${file}: ${String(error)}`);
464
+ }
465
+ try {
466
+ writeRules(home, replace(rules, id, () => converted));
467
+ } catch (error) {
468
+ // The routine is unchanged, so the file made for it goes too; a retry is not refused as existing.
469
+ rmSync(file, { force: true });
470
+ throw error;
471
+ }
472
+ baselineCronRule(home, converted, now);
473
+ return `wrote ${file}; the routine (${convertedId}) now runs home:${name}`;
474
+ }
475
+
476
+ /** The `routines` command: list, add, edit, pause, resume and remove. */
477
+ export function scheduledCommand(
478
+ options: { readonly now?: (() => number) | undefined } = {},
479
+ ): CommandDefinition {
480
+ const now = options.now ?? Date.now;
481
+ return {
482
+ name: "routines",
483
+ args: "list [--json] | add (--flow <flow> [--params <json>] | --command <line> [--cwd <dir>]) --schedule <expression> [--object <id>] [--mode <mode>] | edit <id> [--flow <flow>] [--schedule <expression>] [--params <json>] [--object <id>] [--mode <mode>] | to-flow <id> [--name <name>] | pause <id> | resume <id> | remove <id>",
484
+ async run(ctx, argv) {
485
+ const [sub, ...rest] = argv;
486
+ if (sub === undefined || sub === "help") {
487
+ throw new ScheduleError("routines: use list, add, edit, to-flow, pause, resume or remove");
488
+ }
489
+ const parsed = parseArgs(rest);
490
+
491
+ if (sub === "list") {
492
+ if (parsed.positionals.length > 0) {
493
+ throw new ScheduleError("routines list takes no id");
494
+ }
495
+ const entries = await listFlows(ctx.home, now());
496
+ if (parsed.flags.has("--json")) return entries;
497
+ if (entries.length === 0) return "no routines";
498
+ return entries.map(line).join("\n");
499
+ }
500
+
501
+ if (sub === "add") {
502
+ if (parsed.positionals.length > 0) {
503
+ throw new ScheduleError("routines add takes no id");
504
+ }
505
+ const commandArg = parsed.values.get("--command");
506
+ const cwdArg = parsed.values.get("--cwd");
507
+ let flow: string;
508
+ let params: JsonValue | undefined;
509
+ let defaultObject: string;
510
+ if (commandArg === undefined) {
511
+ if (cwdArg !== undefined) throw new ScheduleError("routines: --cwd needs --command");
512
+ flow = checkedFlow(ctx, required(parsed, "--flow"));
513
+ const paramsArg = parsed.values.get("--params");
514
+ params = paramsArg === undefined ? undefined : checkedParams(paramsArg);
515
+ defaultObject = `flow:${flow}`;
516
+ } else {
517
+ if (parsed.values.has("--flow") || parsed.values.has("--params")) {
518
+ throw new ScheduleError("routines: --command does not take --flow or --params");
519
+ }
520
+ if (commandArg.trim().length === 0) {
521
+ throw new ScheduleError("routines: --command: must be a non-empty string");
522
+ }
523
+ if (cwdArg !== undefined && cwdArg.length === 0) {
524
+ throw new ScheduleError("routines: --cwd: must be a non-empty string");
525
+ }
526
+ if (!ctx.flows.includes(COMMAND_FLOW)) throw new ScheduleError(SHELL_OFF);
527
+ flow = COMMAND_FLOW;
528
+ params = { command: commandArg, ...(cwdArg === undefined ? {} : { cwd: cwdArg }) };
529
+ // Two command routines at one time must not share an object, or the second is skipped.
530
+ const digest = createHash("sha256").update(JSON.stringify(params)).digest("hex").slice(0, 8);
531
+ defaultObject = `routine:${digest}`;
532
+ }
533
+ const schedule = checkedSchedule(required(parsed, "--schedule"));
534
+ const object = checkedObject(parsed.values.get("--object") ?? defaultObject);
535
+ const mode = checkedMode(parsed.values.get("--mode") ?? "auto");
536
+ const rule: TriggerRule = {
537
+ source: "cron",
538
+ type: "tick",
539
+ start: {
540
+ flow,
541
+ ...(params === undefined ? {} : { params }),
542
+ },
543
+ object,
544
+ mode,
545
+ schedule,
546
+ };
547
+ const rules = readRules(ctx.home);
548
+ const id = scheduledId(rule);
549
+ if (scheduled(rules).some((entry) => scheduledId(entry) === id)) {
550
+ throw new ScheduleError(`a routine "${id}" already exists`);
551
+ }
552
+ writeRules(ctx.home, [...rules, rule]);
553
+ baselineCronRule(ctx.home, rule, now());
554
+ return `routine ${commandArg === undefined ? flow : `command ${JSON.stringify(commandArg)}`} (${id}) every ${schedule}`;
555
+ }
556
+
557
+ if (sub === "edit") {
558
+ const id = oneId(parsed);
559
+ const flowArg = parsed.values.get("--flow");
560
+ const scheduleArg = parsed.values.get("--schedule");
561
+ const objectArg = parsed.values.get("--object");
562
+ const modeArg = parsed.values.get("--mode");
563
+ const paramsArg = parsed.values.get("--params");
564
+ let edited: TriggerRule | undefined;
565
+ const rules = replace(readRules(ctx.home), id, (rule) => {
566
+ const flow =
567
+ flowArg === undefined ? rule.start.flow : checkedFlow(ctx, flowArg);
568
+ const schedule =
569
+ scheduleArg === undefined ? rule.schedule : checkedSchedule(scheduleArg);
570
+ const params =
571
+ paramsArg === undefined ? rule.start.params : checkedParams(paramsArg);
572
+ edited = {
573
+ ...rule,
574
+ start: {
575
+ flow,
576
+ ...(params === undefined ? {} : { params }),
577
+ },
578
+ ...(objectArg === undefined ? {} : { object: checkedObject(objectArg) }),
579
+ ...(modeArg === undefined ? {} : { mode: checkedMode(modeArg) }),
580
+ ...(schedule === undefined ? {} : { schedule }),
581
+ };
582
+ return edited;
583
+ });
584
+ if (edited === undefined) throw new ScheduleError(`there is no routine "${id}"`);
585
+ const editedId = scheduledId(edited);
586
+ if (
587
+ editedId !== id &&
588
+ scheduled(rules).filter((entry) => scheduledId(entry) === editedId).length > 1
589
+ ) {
590
+ throw new ScheduleError(`a routine "${editedId}" already exists`);
591
+ }
592
+ writeRules(ctx.home, rules);
593
+ baselineCronRule(ctx.home, edited, now());
594
+ return `edited ${edited.start.flow} (${scheduledId(edited)})`;
595
+ }
596
+
597
+ if (sub === "to-flow") {
598
+ return routineToFlow(ctx.home, oneId(parsed), parsed.values.get("--name"), now());
599
+ }
600
+
601
+ if (sub === "pause" || sub === "resume") {
602
+ const id = oneId(parsed);
603
+ let changed: TriggerRule | undefined;
604
+ const rules = replace(readRules(ctx.home), id, (rule) => {
605
+ changed =
606
+ sub === "pause"
607
+ ? { ...rule, paused: true }
608
+ : rule.paused === undefined
609
+ ? rule
610
+ : (({ paused: _paused, ...rest }) => rest)(rule);
611
+ return changed;
612
+ });
613
+ if (changed === undefined) throw new ScheduleError(`there is no routine "${id}"`);
614
+ writeRules(ctx.home, rules);
615
+ baselineCronRule(ctx.home, changed, now());
616
+ return sub === "pause"
617
+ ? `paused ${changed.start.flow}`
618
+ : `resumed ${changed.start.flow}`;
619
+ }
620
+
621
+ if (sub === "remove") {
622
+ const id = oneId(parsed);
623
+ const rules = readRules(ctx.home);
624
+ const removed = found(rules, id);
625
+ writeRules(
626
+ ctx.home,
627
+ rules.filter((rule) => scheduledId(rule) !== id),
628
+ );
629
+ const state = readCronState(ctx.home);
630
+ const key = ruleStateKey(removed);
631
+ if (state.rules[key] !== undefined) {
632
+ const next = { ...state.rules };
633
+ delete next[key];
634
+ writeCronState(ctx.home, { rules: next });
635
+ }
636
+ return `removed ${removed.start.flow} (${id})`;
637
+ }
638
+
639
+ throw new ScheduleError(`routines: unknown action "${sub}"`);
640
+ },
641
+ };
642
+ }
package/src/state.ts ADDED
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The plugin's own state file, `<home>/cron/state.json`. It holds the last
3
+ * minute the source fired for each rule, keyed by the rule's stable identity.
4
+ * A rule whose schedule changed no longer matches its entry, so it starts fresh.
5
+ */
6
+
7
+ import { readFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import {
10
+ isRecord,
11
+ latestCronMinute,
12
+ parseCron,
13
+ type TriggerRule,
14
+ } from "@operad-io/engine";
15
+ import { writeJsonAtomicSync } from "@operad-io/engine/platform";
16
+
17
+ /** What the source remembers about one rule. */
18
+ export interface CronRuleState {
19
+ /** The schedule the last minute belongs to. */
20
+ readonly schedule: string;
21
+ /** The start of the last minute the rule fired, in epoch milliseconds. */
22
+ readonly last: number;
23
+ }
24
+
25
+ /** The rules' remembered state, by rule identity. */
26
+ export interface CronState {
27
+ readonly rules: Readonly<Record<string, CronRuleState>>;
28
+ }
29
+
30
+ /** The directory the plugin keeps its own files in. */
31
+ export function cronStateDirectory(home: string): string {
32
+ return join(home, "cron");
33
+ }
34
+
35
+ /** The file the last fired minutes are in. */
36
+ export function cronStatePath(home: string): string {
37
+ return join(cronStateDirectory(home), "state.json");
38
+ }
39
+
40
+ /** The stable identity of a rule, independent of its position in the file. */
41
+ export function ruleStateKey(rule: TriggerRule): string {
42
+ return JSON.stringify([
43
+ rule.source,
44
+ rule.type,
45
+ rule.start.flow,
46
+ rule.start.params ?? null,
47
+ rule.object,
48
+ rule.mode,
49
+ rule.schedule,
50
+ ]);
51
+ }
52
+
53
+ /** Starts a rule from the latest planned minute at or before `now`. */
54
+ export function baselineCronRule(
55
+ home: string,
56
+ rule: TriggerRule,
57
+ now: number,
58
+ ): void {
59
+ if (rule.schedule === undefined) return;
60
+ const last = latestCronMinute(parseCron(rule.schedule), now);
61
+ if (last === null) return;
62
+ const state = readCronState(home);
63
+ writeCronState(home, {
64
+ rules: {
65
+ ...state.rules,
66
+ [ruleStateKey(rule)]: { schedule: rule.schedule, last },
67
+ },
68
+ });
69
+ }
70
+
71
+ function ruleStateOf(value: unknown): CronRuleState | undefined {
72
+ if (!isRecord(value)) return undefined;
73
+ if (typeof value.schedule !== "string") return undefined;
74
+ if (typeof value.last !== "number" || !Number.isFinite(value.last)) return undefined;
75
+ return { schedule: value.schedule, last: value.last };
76
+ }
77
+
78
+ /** The recorded rule state; empty when the file is missing or unusable. */
79
+ export function readCronState(home: string): CronState {
80
+ let parsed: unknown;
81
+ try {
82
+ parsed = JSON.parse(readFileSync(cronStatePath(home), "utf8"));
83
+ } catch {
84
+ return { rules: {} };
85
+ }
86
+ if (!isRecord(parsed) || !isRecord(parsed.rules)) return { rules: {} };
87
+ const rules: Record<string, CronRuleState> = {};
88
+ for (const [key, value] of Object.entries(parsed.rules)) {
89
+ const state = ruleStateOf(value);
90
+ if (state !== undefined) rules[key] = state;
91
+ }
92
+ return { rules };
93
+ }
94
+
95
+ /** Records the rule state, replacing the file whole. */
96
+ export function writeCronState(home: string, state: CronState): void {
97
+ writeJsonAtomicSync(cronStatePath(home), state);
98
+ }