GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): a daily workflow schedule written another way keeps its … · patroza/t3code@b996cf2

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src/workflows
    • WorkflowEngine.ts
    • WorkflowStore.ts
    • Workflows.test.ts
    • triggers.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/workflows/WorkflowEngine.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/workflows/WorkflowEngine.ts
+22-3Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
import { checkOutput, rejectionText } from "../orchestration-v2/runOutput.ts";
3737
import * as ServerSettings from "../serverSettings.ts";
3838
import { isMissedFixedTimeRun, nextScheduledRunAt } from "../scheduledTasks/Schedule.ts";
39+
import { currentScheduleId } from "./triggers.ts";
3940
import { constantTimeEquals } from "../scheduledTasks/webhookVerification.ts";
4041
import {
4142
answerStamped,
@@ -371,11 +372,29 @@ const make = Effect.fn("WorkflowEngine.make")(function* (
371372
const latestDefinitions = [...new Set(registered.map(([definition]) => definition.name))].map(
372373
(name) => latest(name)![0],
373374
);
375+
// A daily schedule saved under an id that followed its spelling keeps that id, for its next
376+
// time and for the keys of its runs: a time it has started is then not started again.
377+
const savedIds = yield* store.triggerIds;
378+
const stateId = (
379+
definition: WorkflowDefinition,
380+
trigger: Exclude<WorkflowDefinition["triggers"][number], { readonly kind: "webhook" }>,
381+
) => {
382+
const prefix = `${definition.name}/`;
383+
const id = `${prefix}${trigger.id}`;
384+
if (trigger.kind !== "schedule" || savedIds.includes(id)) return id;
385+
const earlier = savedIds
386+
.filter(
387+
(saved) =>
388+
saved.startsWith(prefix) && currentScheduleId(saved.slice(prefix.length)) === trigger.id,
389+
)
390+
.toSorted();
391+
return earlier[0] ?? id;
392+
};
374393
// A schedule taken out and put back is new again: its first run is one interval away.
375394
yield* store.triggersKeep(
376395
latestDefinitions.flatMap((definition) =>
377396
definition.triggers.flatMap((trigger) =>
378-
trigger.kind === "webhook" ? [] : [`${definition.name}/${trigger.id}`],
397+
trigger.kind === "webhook" ? [] : [stateId(definition, trigger)],
379398
),
380399
),
381400
);
@@ -385,7 +404,7 @@ const make = Effect.fn("WorkflowEngine.make")(function* (
385404
for (const definition of latestDefinitions) {
386405
for (const trigger of definition.triggers) {
387406
if (trigger.kind !== "schedule") continue;
388-
const id = `${definition.name}/${trigger.id}`;
407+
const id = stateId(definition, trigger);
389408
const due = yield* store.triggerNext(id);
390409
if (due !== undefined) {
391410
const dueAt = DateTime.makeUnsafe(due);
@@ -435,7 +454,7 @@ const make = Effect.fn("WorkflowEngine.make")(function* (
435454
for (const definition of latestDefinitions) {
436455
for (const trigger of definition.triggers) {
437456
if (trigger.kind !== "issues" && trigger.kind !== "pullRequests") continue;
438-
const id = `${definition.name}/${trigger.id}`;
457+
const id = stateId(definition, trigger);
439458
const since = yield* store.triggerNext(id);
440459
if (since === undefined) {
441460
yield* store.triggerSet(id, DateTime.formatIso(now));
Collapse file

‎apps/server/src/workflows/WorkflowStore.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/workflows/WorkflowStore.ts
+6Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,7 @@ export class WorkflowStore extends Context.Service<
421421
readonly triggerNext: (triggerId: string) => Effect.Effect<string | undefined>;
422422
readonly triggerSet: (triggerId: string, nextAt: string) => Effect.Effect<void>;
423423
/** Forgets every trigger but these, so one that comes back starts over. */
424+
readonly triggerIds: Effect.Effect<ReadonlyArray<string>>;
424425
readonly triggersKeep: (triggerIds: ReadonlyArray<string>) => Effect.Effect<void>;
425426
/** The hook's token: the one kept for it, or `fresh` from now on. */
426427
readonly hookToken: (hookId: string, fresh: string) => Effect.Effect<string>;
@@ -1489,6 +1490,11 @@ export const make = Effect.gen(function* () {
14891490
ON CONFLICT (trigger_id) DO UPDATE SET next_at = excluded.next_at
14901491
`.pipe(Effect.orDie);
14911492
}),
1493+
triggerIds: sql<{ trigger_id: string }>`SELECT trigger_id FROM workflow_triggers`.pipe(
1494+
Effect.map((rows) => rows.map((row) => row.trigger_id)),
1495+
Effect.orDie,
1496+
Effect.withSpan("WorkflowStore.triggerIds"),
1497+
),
14921498
triggersKeep: Effect.fn("WorkflowStore.triggersKeep")(function* (triggerIds) {
14931499
const kept = yield* sql<{ trigger_id: string }>`SELECT trigger_id FROM workflow_triggers`;
14941500
for (const { trigger_id } of kept) {
Collapse file

‎apps/server/src/workflows/Workflows.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/workflows/Workflows.test.ts
+52-1Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import * as SqlClient from "effect/sql/SqlClient";
2020
import * as Stream from "effect/Stream";
2121
import * as TestClock from "effect/testing/TestClock";
2222

23-
import { daily, every, Tick, webhook, WebhookRequest } from "./triggers.ts";
23+
import { checkTriggers, daily, every, Tick, webhook, WebhookRequest } from "./triggers.ts";
2424
import { issues, pullRequests } from "./forgeApi.ts";
2525
import { cancel, runs, signalAll, start, withdraw } from "./stepServices.ts";
2626
import {
@@ -2397,6 +2397,57 @@ it("every accepts bigint nanoseconds and names short ones in its error", () => {
23972397
assert.throws(() => every(1_000n), /^every\(1000n\) is shorter than the shortest, one minute\.$/);
23982398
});
23992399

2400+
it("a workflow refuses two daily schedules that fire at the same times", () => {
2401+
const twice = /^workflow\("standup"\) lists the same schedule twice\. List it once\.$/;
2402+
const refused = (...triggers: ReadonlyArray<ReturnType<typeof daily>>) =>
2403+
assert.throws(() => checkTriggers("standup", triggers), twice);
2404+
refused(daily("9:00"), daily("09:00"));
2405+
refused(daily("09:00"), daily("09:00", { weekdays: [] }));
2406+
refused(daily("09:00"), daily("09:00", { weekdays: [6, 5, 4, 3, 2, 1, 0] }));
2407+
refused(daily("09:00", { weekdays: [3, 1, 1] }), daily("09:00", { weekdays: [1, 3] }));
2408+
checkTriggers("standup", [daily("09:00", { weekdays: [1] }), daily("09:00")]);
2409+
});
2410+
2411+
it.effect("a daily schedule written another way after a restart keeps its next time and runs", () =>
2412+
Effect.gen(function* () {
2413+
const { boot, database } = yield* harness();
2414+
const db = <A, E>(query: (sql: SqlClient.SqlClient) => Effect.Effect<A, E>) =>
2415+
Effect.flatMap(SqlClient.SqlClient, query).pipe(Effect.provide(database));
2416+
const standup = (...written: Parameters<typeof daily>) =>
2417+
[
2418+
workflow(
2419+
"standup",
2420+
{ version: 1, payload: Tick, triggers: [daily(...written)] },
2421+
() => Effect.void,
2422+
),
2423+
] as never;
2424+
const swept = Effect.flatMap(Workflows.Workflows, (workflows) => workflows.sweep).pipe(
2425+
Effect.andThen(
2426+
db((sql) => sql<{ idempotency_key: string }>`SELECT idempotency_key FROM workflow_runs`),
2427+
),
2428+
Effect.map((runs) => runs.map((run) => run.idempotency_key)),
2429+
);
2430+
const saved = db(
2431+
(sql) => sql<{ trigger_id: string; next_at: string }>`SELECT * FROM workflow_triggers`,
2432+
);
2433+
// Saved by a server from before ids stopped following the spelling.
2434+
assert.deepStrictEqual(yield* boot(swept, standup("09:00")), []);
2435+
const [first] = yield* saved;
2436+
yield* db((sql) => sql`UPDATE workflow_triggers SET trigger_id = 'standup/daily:9:00:all'`);
2437+
// Down until a minute past the time, which is within what a daily schedule catches up on.
2438+
yield* TestClock.setTime(Date.parse(first!.next_at) + 60_000);
2439+
const key = `trigger:standup/daily:9:00:all:${first!.next_at}`;
2440+
assert.deepStrictEqual(yield* boot(swept, standup("09:00")), [key]);
2441+
const [moved, ...others] = yield* saved;
2442+
assert.deepStrictEqual(others, []);
2443+
assert.equal(moved!.trigger_id, "standup/daily:9:00:all");
2444+
assert.isAbove(Date.parse(moved!.next_at), Date.parse(first!.next_at));
2445+
// A crash between the start and moving on left the time it had started: not started again.
2446+
yield* db((sql) => sql`UPDATE workflow_triggers SET next_at = ${first!.next_at}`);
2447+
assert.deepStrictEqual(yield* boot(swept, standup(" 9:00", { weekdays: [] })), [key]);
2448+
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
2449+
);
2450+
24002451
it.effect("the sweep deletes skipped runs past the number the settings keep", () =>
24012452
Effect.gen(function* () {
24022453
const exposed = exposedStore();
Collapse file

‎apps/server/src/workflows/triggers.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/workflows/triggers.ts
+33-5Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ export type WebhookRequest = typeof WebhookRequest.Type;
2222

2323
export interface ScheduleTrigger {
2424
readonly kind: "schedule";
25-
/** Stable across restarts: where this trigger's next time is kept. */
25+
/** The same for every spelling of one schedule, and across restarts. */
2626
readonly id: string;
2727
readonly schedule:
2828
| { readonly type: "interval"; readonly everyMs: number }
@@ -62,6 +62,29 @@ export const every = (interval: Duration.Input): Trigger<Tick> => {
6262
return { kind: "schedule", id: `every:${everyMs}`, schedule: { type: "interval", everyMs } };
6363
};
6464

65+
const dailyId = (time: { hour: number; minute: number }, weekdays: ReadonlyArray<number>) => {
66+
const pad = (part: number) => String(part).padStart(2, "0");
67+
// None and all seven are both every day, as the schedule reads them.
68+
const days = weekdays.length === 0 || weekdays.length === 7 ? "all" : weekdays.join(",");
69+
return `daily:${pad(time.hour)}:${pad(time.minute)}:${days}`;
70+
};
71+
72+
const WEEKDAY = /^[0-6]$/;
73+
74+
/**
75+
* The id `daily` gives now for one it gave when ids followed the spelling (`daily:9:00:all`,
76+
* `daily:09:00:3,1,1`), which saved next times and run keys may still carry. Any other id is
77+
* returned as it is.
78+
*/
79+
export const currentScheduleId = (id: string): string => {
80+
const written = /^daily:(.*):([^:]*)$/s.exec(id);
81+
const time = written === null ? null : parseTimeOfDay(written[1]!);
82+
if (written === null || time === null) return id;
83+
const days = written[2] === "all" || written[2] === "" ? [] : written[2]!.split(",");
84+
if (!days.every((day) => WEEKDAY.test(day))) return id;
85+
return dailyId(time, [...new Set(days.map(Number))].toSorted());
86+
};
87+
6588
/**
6689
* A run at a time of day (`"09:00"`) on the server's clock, on every day or on the given weekdays
6790
* (0 is Sunday). A time missed by more than ten minutes, for a server that was down, is skipped.
@@ -73,15 +96,20 @@ export const daily = (
7396
checkOptions(`daily("${timeOfDay}")`, options, ["weekdays"]);
7497
const weekdays = options?.weekdays;
7598
// Read once here: a time the schedule cannot read would otherwise never fire, without a word.
76-
if (parseTimeOfDay(timeOfDay) === null) {
99+
const time = parseTimeOfDay(timeOfDay);
100+
if (time === null) {
77101
throw new Error(`daily("${timeOfDay}") needs a 24-hour time such as "09:00".`);
78102
}
79-
if (weekdays?.some((day) => !Number.isInteger(day) || day < 0 || day > 6)) {
80-
throw new Error(`daily's weekdays are 0 (Sunday) to 6 (Saturday), not ${weekdays.join(", ")}.`);
103+
const days = [...new Set(weekdays)].toSorted();
104+
if (days.some((day) => !Number.isInteger(day) || day < 0 || day > 6)) {
105+
throw new Error(
106+
`daily's weekdays are 0 (Sunday) to 6 (Saturday), not ${weekdays?.join(", ")}.`,
107+
);
81108
}
82109
return {
83110
kind: "schedule",
84-
id: `daily:${timeOfDay}:${weekdays?.toSorted().join(",") ?? "all"}`,
111+
// From what the schedule reads, not how it was written: `"9:00"` and `"09:00"` are one time.
112+
id: dailyId(time, days),
85113
schedule: { type: "fixed_time", timeOfDay, ...(weekdays === undefined ? {} : { weekdays }) },
86114
};
87115
};

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.