Open History to see the last commit
1// What starts a run by itself. A trigger hands its workflow one value, so a workflow that lists
2// a trigger takes that value as its payload: `Tick` for a schedule, `WebhookRequest` for a hook.
3import * as Duration from "effect/Duration";
4import * as Schema from "effect/Schema";
5
6import { parseTimeOfDay } from "../scheduledTasks/Schedule.ts";
7import { checkOptions, durationOf } from "./options.ts";
8import type { Issue, PullRequest } from "./WorkflowForge.ts";
9
10/** The time a scheduled run was due, which is not the time it started. */
11export const Tick = Schema.Struct({ scheduledAt: Schema.String });
12export type Tick = typeof Tick.Type;
13
14/** A request to a workflow's hook URL, as it arrived. Header names are lower case. */
15export const WebhookRequest = Schema.Struct({
16 method: Schema.String,
17 headers: Schema.Record(Schema.String, Schema.String),
18 query: Schema.String,
19 body: Schema.String,
20});
21export type WebhookRequest = typeof WebhookRequest.Type;
22
23export interface ScheduleTrigger {
24 readonly kind: "schedule";
25 /** The same for every spelling of one schedule, and across restarts. */
26 readonly id: string;
27 readonly schedule:
28 | { readonly type: "interval"; readonly everyMs: number }
29 | {
30 readonly type: "fixed_time";
31 readonly timeOfDay: string;
32 readonly weekdays?: ReadonlyArray<number>;
33 };
34}
35export interface WebhookTrigger {
36 readonly kind: "webhook";
37 readonly name: string;
38 readonly key: ((request: WebhookRequest) => string | undefined) | undefined;
39}
40/** New issues or pull requests of a project, which the engine looks for by itself. */
41export interface OpenedTrigger {
42 readonly kind: "issues" | "pullRequests";
43 /** Stable across restarts: where this trigger keeps how far it has looked. */
44 readonly id: string;
45 readonly project: string;
46 readonly labels?: ReadonlyArray<string> | undefined;
47 readonly query?: string | undefined;
48}
49/** `Fires` is what the trigger gives the run it starts. */
50export type Trigger<Fires> = (ScheduleTrigger | WebhookTrigger | OpenedTrigger) & {
51 readonly fires?: (value: Fires) => void;
52};
53
54/** A run every so often, counted from when the last one was started. At least a minute. */
55export const every = (interval: Duration.Input): Trigger<Tick> => {
56 const label = `every(${typeof interval === "bigint" ? `${interval}n` : JSON.stringify(interval)})`;
57 const everyMs = Duration.toMillis(durationOf(label, interval));
58 if (!Number.isFinite(everyMs)) {
59 throw new Error(`${label} needs a finite interval.`);
60 }
61 // The sweep would quietly stretch a shorter one to a minute.
62 if (everyMs < 60_000) {
63 throw new Error(`${label} is shorter than the shortest, one minute.`);
64 }
65 return { kind: "schedule", id: `every:${everyMs}`, schedule: { type: "interval", everyMs } };
66};
67
68const dailyId = (time: { hour: number; minute: number }, weekdays: ReadonlyArray<number>) => {
69 const pad = (part: number) => String(part).padStart(2, "0");
70 // None and all seven are both every day, as the schedule reads them.
71 const days = weekdays.length === 0 || weekdays.length === 7 ? "all" : weekdays.join(",");
72 return `daily:${pad(time.hour)}:${pad(time.minute)}:${days}`;
73};
74
75const WEEKDAY = /^[0-6]$/;
76
77/**
78 * The id `daily` gives now for one it gave when ids followed the spelling (`daily:9:00:all`,
79 * `daily:09:00:3,1,1`), which saved next times and run keys may still carry. Any other id is
80 * returned as it is.
81 */
82export const currentScheduleId = (id: string): string => {
83 const written = /^daily:(.*):([^:]*)$/s.exec(id);
84 const time = written === null ? null : parseTimeOfDay(written[1]!);
85 if (written === null || time === null) return id;
86 const days = written[2] === "all" || written[2] === "" ? [] : written[2]!.split(",");
87 if (!days.every((day) => WEEKDAY.test(day))) return id;
88 return dailyId(time, [...new Set(days.map(Number))].toSorted());
89};
90
91/**
92 * A run at a time of day (`"09:00"`) on the server's clock, on every day or on the given weekdays
93 * (0 is Sunday). A time missed by more than ten minutes, for a server that was down, is skipped.
94 */
95export const daily = (
96 timeOfDay: string,
97 options?: { readonly weekdays?: ReadonlyArray<number> },
98): Trigger<Tick> => {
99 checkOptions(`daily("${timeOfDay}")`, options, ["weekdays"]);
100 const weekdays = options?.weekdays;
101 // Read once here: a time the schedule cannot read would otherwise never fire, without a word.
102 const time = parseTimeOfDay(timeOfDay);
103 if (time === null) {
104 throw new Error(`daily("${timeOfDay}") needs a 24-hour time such as "09:00".`);
105 }
106 const days = [...new Set(weekdays)].toSorted();
107 if (days.some((day) => !Number.isInteger(day) || day < 0 || day > 6)) {
108 throw new Error(
109 `daily's weekdays are 0 (Sunday) to 6 (Saturday), not ${weekdays?.join(", ")}.`,
110 );
111 }
112 return {
113 kind: "schedule",
114 // From what the schedule reads, not how it was written: `"9:00"` and `"09:00"` are one time.
115 id: dailyId(time, days),
116 schedule: { type: "fixed_time", timeOfDay, ...(weekdays === undefined ? {} : { weekdays }) },
117 };
118};
119
120/**
121 * A run for each request to this workflow's hook URL (`t3 workflow hooks` prints it). The run
122 * decides what the request means, `stop` included. Two requests for which `key` gives the same
123 * text are one run, which is how a sender's retries are told from new deliveries.
124 */
125export const webhook = (
126 name: string,
127 options?: { readonly key?: (request: WebhookRequest) => string | undefined },
128): Trigger<WebhookRequest> => {
129 checkOptions(`webhook("${name}")`, options, ["key"]);
130 return { kind: "webhook", name, key: options?.key };
131};
132
133/** Refuses two hooks of one name, or two triggers that would fire on the same thing. */
134export const checkTriggers = (
135 workflow: string,
136 triggers: ReadonlyArray<ScheduleTrigger | WebhookTrigger | OpenedTrigger>,
137) => {
138 const seen = new Set<string>();
139 for (const trigger of triggers) {
140 // Labels are all-of, so repeats match the same issues; saved ids keep them to keep cursors.
141 const id =
142 trigger.kind === "webhook"
143 ? `webhook:${trigger.name}`
144 : trigger.kind === "issues"
145 ? openedId("issues", { ...trigger, labels: [...new Set(trigger.labels)] })
146 : trigger.id;
147 if (seen.has(id)) {
148 throw new Error(
149 trigger.kind === "webhook"
150 ? `workflow("${workflow}") has two hooks named "${trigger.name}". Give each its own name.`
151 : `workflow("${workflow}") lists the same ${trigger.kind === "schedule" ? "schedule" : "trigger"} twice. List it once.`,
152 );
153 }
154 seen.add(id);
155 }
156};
157
158const openedId = (
159 kind: OpenedTrigger["kind"],
160 options: Pick<OpenedTrigger, "project" | "labels" | "query">,
161) =>
162 // A tuple, so no label or query can be read as part of another.
163 JSON.stringify([kind, options.project, options.labels?.toSorted() ?? [], options.query ?? ""]);
164
165/**
166 * A run for each issue opened in the project's tracker from now on, with the issue as its
167 * payload (`Issue`). Issues that were already there when the workflow was first loaded start
168 * nothing. `labels` are ones the issue must carry, all of them; `query` is free text for the
169 * tracker. The tracker is asked about once a minute.
170 */
171export const issuesOpened = (options: {
172 readonly project: string;
173 readonly labels?: ReadonlyArray<string>;
174 readonly query?: string;
175}): Trigger<Issue> => {
176 checkOptions("issues.opened", options, ["project", "labels", "query"]);
177 return { kind: "issues", id: openedId("issues", options), ...options };
178};
179
180/**
181 * A run for each pull request opened against the project's repository from now on, with the pull
182 * request as its payload (`PullRequest`). `query` is free text for the host.
183 */
184export const pullRequestsOpened = (options: {
185 readonly project: string;
186 readonly query?: string;
187}): Trigger<PullRequest> => {
188 checkOptions("pullRequests.opened", options, ["project", "query"]);
189 return { kind: "pullRequests", id: openedId("pullRequests", options), ...options };
190};