GeezerVison is showing github.com — fix(server): a daily workflow schedule written another way keeps its … · patroza/t3code@b996cf2
File treeExpand file treeCollapse file tree Open diff view settings apps/server/src/workflows
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: apps/server/src/workflows/WorkflowEngine.ts +22-3Lines changed: 22 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -36,6 +36,7 @@ import { | 36 | 36 | import { checkOutput, rejectionText } from "../orchestration-v2/runOutput.ts"; | 37 | 37 | import * as ServerSettings from "../serverSettings.ts"; | 38 | 38 | import { isMissedFixedTimeRun, nextScheduledRunAt } from "../scheduledTasks/Schedule.ts"; | | 39 | +import { currentScheduleId } from "./triggers.ts"; | 39 | 40 | import { constantTimeEquals } from "../scheduledTasks/webhookVerification.ts"; | 40 | 41 | import { | 41 | 42 | answerStamped, | @@ -371,11 +372,29 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( | 371 | 372 | const latestDefinitions = [...new Set(registered.map(([definition]) => definition.name))].map( | 372 | 373 | (name) => latest(name)![0], | 373 | 374 | ); | | 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 | + }; | 374 | 393 | // A schedule taken out and put back is new again: its first run is one interval away. | 375 | 394 | yield* store.triggersKeep( | 376 | 395 | latestDefinitions.flatMap((definition) => | 377 | 396 | definition.triggers.flatMap((trigger) => | 378 | | - trigger.kind === "webhook" ? [] : [`${definition.name}/${trigger.id}`], | | 397 | + trigger.kind === "webhook" ? [] : [stateId(definition, trigger)], | 379 | 398 | ), | 380 | 399 | ), | 381 | 400 | ); | @@ -385,7 +404,7 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( | 385 | 404 | for (const definition of latestDefinitions) { | 386 | 405 | for (const trigger of definition.triggers) { | 387 | 406 | if (trigger.kind !== "schedule") continue; | 388 | | - const id = `${definition.name}/${trigger.id}`; | | 407 | + const id = stateId(definition, trigger); | 389 | 408 | const due = yield* store.triggerNext(id); | 390 | 409 | if (due !== undefined) { | 391 | 410 | const dueAt = DateTime.makeUnsafe(due); | @@ -435,7 +454,7 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( | 435 | 454 | for (const definition of latestDefinitions) { | 436 | 455 | for (const trigger of definition.triggers) { | 437 | 456 | if (trigger.kind !== "issues" && trigger.kind !== "pullRequests") continue; | 438 | | - const id = `${definition.name}/${trigger.id}`; | | 457 | + const id = stateId(definition, trigger); | 439 | 458 | const since = yield* store.triggerNext(id); | 440 | 459 | if (since === undefined) { | 441 | 460 | yield* store.triggerSet(id, DateTime.formatIso(now)); | |
Collapse file Copy file name to clipboardExpand all lines: apps/server/src/workflows/WorkflowStore.ts +6Lines changed: 6 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -421,6 +421,7 @@ export class WorkflowStore extends Context.Service< | 421 | 421 | readonly triggerNext: (triggerId: string) => Effect.Effect<string | undefined>; | 422 | 422 | readonly triggerSet: (triggerId: string, nextAt: string) => Effect.Effect<void>; | 423 | 423 | /** Forgets every trigger but these, so one that comes back starts over. */ | | 424 | + readonly triggerIds: Effect.Effect<ReadonlyArray<string>>; | 424 | 425 | readonly triggersKeep: (triggerIds: ReadonlyArray<string>) => Effect.Effect<void>; | 425 | 426 | /** The hook's token: the one kept for it, or `fresh` from now on. */ | 426 | 427 | readonly hookToken: (hookId: string, fresh: string) => Effect.Effect<string>; | @@ -1489,6 +1490,11 @@ export const make = Effect.gen(function* () { | 1489 | 1490 | ON CONFLICT (trigger_id) DO UPDATE SET next_at = excluded.next_at | 1490 | 1491 | `.pipe(Effect.orDie); | 1491 | 1492 | }), | | 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 | + ), | 1492 | 1498 | triggersKeep: Effect.fn("WorkflowStore.triggersKeep")(function* (triggerIds) { | 1493 | 1499 | const kept = yield* sql<{ trigger_id: string }>`SELECT trigger_id FROM workflow_triggers`; | 1494 | 1500 | for (const { trigger_id } of kept) { | |
Collapse file Copy file name to clipboardExpand all lines: apps/server/src/workflows/Workflows.test.ts +52-1Lines changed: 52 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -20,7 +20,7 @@ import * as SqlClient from "effect/sql/SqlClient"; | 20 | 20 | import * as Stream from "effect/Stream"; | 21 | 21 | import * as TestClock from "effect/testing/TestClock"; | 22 | 22 |
| 23 | | -import { daily, every, Tick, webhook, WebhookRequest } from "./triggers.ts"; | | 23 | +import { checkTriggers, daily, every, Tick, webhook, WebhookRequest } from "./triggers.ts"; | 24 | 24 | import { issues, pullRequests } from "./forgeApi.ts"; | 25 | 25 | import { cancel, runs, signalAll, start, withdraw } from "./stepServices.ts"; | 26 | 26 | import { | @@ -2397,6 +2397,57 @@ it("every accepts bigint nanoseconds and names short ones in its error", () => { | 2397 | 2397 | assert.throws(() => every(1_000n), /^every\(1000n\) is shorter than the shortest, one minute\.$/); | 2398 | 2398 | }); | 2399 | 2399 |
| | 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 | + | 2400 | 2451 | it.effect("the sweep deletes skipped runs past the number the settings keep", () => | 2401 | 2452 | Effect.gen(function* () { | 2402 | 2453 | const exposed = exposedStore(); | |
Collapse file Copy file name to clipboardExpand all lines: apps/server/src/workflows/triggers.ts +33-5Lines changed: 33 additions & 5 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -22,7 +22,7 @@ export type WebhookRequest = typeof WebhookRequest.Type; | 22 | 22 |
| 23 | 23 | export interface ScheduleTrigger { | 24 | 24 | 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. */ | 26 | 26 | readonly id: string; | 27 | 27 | readonly schedule: | 28 | 28 | | { readonly type: "interval"; readonly everyMs: number } | @@ -62,6 +62,29 @@ export const every = (interval: Duration.Input): Trigger<Tick> => { | 62 | 62 | return { kind: "schedule", id: `every:${everyMs}`, schedule: { type: "interval", everyMs } }; | 63 | 63 | }; | 64 | 64 |
| | 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 | + | 65 | 88 | /** | 66 | 89 | * A run at a time of day (`"09:00"`) on the server's clock, on every day or on the given weekdays | 67 | 90 | * (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 = ( | 73 | 96 | checkOptions(`daily("${timeOfDay}")`, options, ["weekdays"]); | 74 | 97 | const weekdays = options?.weekdays; | 75 | 98 | // 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) { | 77 | 101 | throw new Error(`daily("${timeOfDay}") needs a 24-hour time such as "09:00".`); | 78 | 102 | } | 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 | + ); | 81 | 108 | } | 82 | 109 | return { | 83 | 110 | 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), | 85 | 113 | schedule: { type: "fixed_time", timeOfDay, ...(weekdays === undefined ? {} : { weekdays }) }, | 86 | 114 | }; | 87 | 115 | }; | |
|