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 // The sweep would quietly stretch a shorter one to a minute.
59 if (everyMs < 60_000) {
60 throw new Error(`${label} is shorter than the shortest, one minute.`);
61 }
62 return { kind: "schedule", id: `every:${everyMs}`, schedule: { type: "interval", everyMs } };
63};
64
65const 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
72const 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 */
79export 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
88/**
89 * A run at a time of day (`"09:00"`) on the server's clock, on every day or on the given weekdays
90 * (0 is Sunday). A time missed by more than ten minutes, for a server that was down, is skipped.
91 */
92export const daily = (
93 timeOfDay: string,
94 options?: { readonly weekdays?: ReadonlyArray<number> },
95): Trigger<Tick> => {
96 checkOptions(`daily("${timeOfDay}")`, options, ["weekdays"]);
97 const weekdays = options?.weekdays;
98 // Read once here: a time the schedule cannot read would otherwise never fire, without a word.
99 const time = parseTimeOfDay(timeOfDay);
100 if (time === null) {
101 throw new Error(`daily("${timeOfDay}") needs a 24-hour time such as "09:00".`);
102 }
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 );
108 }
109 return {
110 kind: "schedule",
111 // From what the schedule reads, not how it was written: `"9:00"` and `"09:00"` are one time.
112 id: dailyId(time, days),
113 schedule: { type: "fixed_time", timeOfDay, ...(weekdays === undefined ? {} : { weekdays }) },
114 };
115};
116
117/**
118 * A run for each request to this workflow's hook URL (`t3 workflow hooks` prints it). The run
119 * decides what the request means, `stop` included. Two requests for which `key` gives the same
120 * text are one run, which is how a sender's retries are told from new deliveries.
121 */
122export const webhook = (
123 name: string,
124 options?: { readonly key?: (request: WebhookRequest) => string | undefined },
125): Trigger<WebhookRequest> => {
126 checkOptions(`webhook("${name}")`, options, ["key"]);
127 return { kind: "webhook", name, key: options?.key };
128};
129
130/** Refuses two hooks of one name, or two triggers that would fire on the same thing. */
131export const checkTriggers = (
132 workflow: string,
133 triggers: ReadonlyArray<ScheduleTrigger | WebhookTrigger | OpenedTrigger>,
134) => {
135 const seen = new Set<string>();
136 for (const trigger of triggers) {
137 const id = trigger.kind === "webhook" ? `webhook:${trigger.name}` : trigger.id;
138 if (seen.has(id)) {
139 throw new Error(
140 trigger.kind === "webhook"
141 ? `workflow("${workflow}") has two hooks named "${trigger.name}". Give each its own name.`
142 : `workflow("${workflow}") lists the same ${trigger.kind === "schedule" ? "schedule" : "trigger"} twice. List it once.`,
143 );
144 }
145 seen.add(id);
146 }
147};
148
149const openedId = (
150 kind: OpenedTrigger["kind"],
151 options: {
152 readonly project: string;
153 readonly labels?: ReadonlyArray<string>;
154 readonly query?: string;
155 },
156) =>
157 // A tuple, so no label or query can be read as part of another.
158 JSON.stringify([kind, options.project, options.labels?.toSorted() ?? [], options.query ?? ""]);
159
160/**
161 * A run for each issue opened in the project's tracker from now on, with the issue as its
162 * payload (`Issue`). Issues that were already there when the workflow was first loaded start
163 * nothing. `labels` are ones the issue must carry, all of them; `query` is free text for the
164 * tracker. The tracker is asked about once a minute.
165 */
166export const issuesOpened = (options: {
167 readonly project: string;
168 readonly labels?: ReadonlyArray<string>;
169 readonly query?: string;
170}): Trigger<Issue> => {
171 checkOptions("issues.opened", options, ["project", "labels", "query"]);
172 return { kind: "issues", id: openedId("issues", options), ...options };
173};
174
175/**
176 * A run for each pull request opened against the project's repository from now on, with the pull
177 * request as its payload (`PullRequest`). `query` is free text for the host.
178 */
179export const pullRequestsOpened = (options: {
180 readonly project: string;
181 readonly query?: string;
182}): Trigger<PullRequest> => {
183 checkOptions("pullRequests.opened", options, ["project", "query"]);
184 return { kind: "pullRequests", id: openedId("pullRequests", options), ...options };
185};