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 /** Stable across restarts: where this trigger's next time is kept. */
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 everyMs = Duration.toMillis(durationOf(`every(${JSON.stringify(interval)})`, interval));
57 // The sweep would quietly stretch a shorter one to a minute.
58 if (everyMs < 60_000) {
59 throw new Error(`every(${JSON.stringify(interval)}) is shorter than the shortest, one minute.`);
60 }
61 return { kind: "schedule", id: `every:${everyMs}`, schedule: { type: "interval", everyMs } };
62};
63
64/**
65 * A run at a time of day (`"09:00"`) on the server's clock, on every day or on the given weekdays
66 * (0 is Sunday). A time missed by more than ten minutes, for a server that was down, is skipped.
67 */
68export const daily = (
69 timeOfDay: string,
70 options?: { readonly weekdays?: ReadonlyArray<number> },
71): Trigger<Tick> => {
72 checkOptions(`daily("${timeOfDay}")`, options, ["weekdays"]);
73 const weekdays = options?.weekdays;
74 // Read once here: a time the schedule cannot read would otherwise never fire, without a word.
75 if (parseTimeOfDay(timeOfDay) === null) {
76 throw new Error(`daily("${timeOfDay}") needs a 24-hour time such as "09:00".`);
77 }
78 if (weekdays?.some((day) => !Number.isInteger(day) || day < 0 || day > 6)) {
79 throw new Error(`daily's weekdays are 0 (Sunday) to 6 (Saturday), not ${weekdays.join(", ")}.`);
80 }
81 return {
82 kind: "schedule",
83 id: `daily:${timeOfDay}:${weekdays?.toSorted().join(",") ?? "all"}`,
84 schedule: { type: "fixed_time", timeOfDay, ...(weekdays === undefined ? {} : { weekdays }) },
85 };
86};
87
88/**
89 * A run for each request to this workflow's hook URL (`t3 workflow hooks` prints it). The run
90 * decides what the request means, `stop` included. Two requests for which `key` gives the same
91 * text are one run, which is how a sender's retries are told from new deliveries.
92 */
93export const webhook = (
94 name: string,
95 options?: { readonly key?: (request: WebhookRequest) => string | undefined },
96): Trigger<WebhookRequest> => {
97 checkOptions(`webhook("${name}")`, options, ["key"]);
98 return { kind: "webhook", name, key: options?.key };
99};
100
101/** Refuses two hooks of one name, or two triggers that would fire on the same thing. */
102export const checkTriggers = (
103 workflow: string,
104 triggers: ReadonlyArray<ScheduleTrigger | WebhookTrigger | OpenedTrigger>,
105) => {
106 const seen = new Set<string>();
107 for (const trigger of triggers) {
108 const id = trigger.kind === "webhook" ? `webhook:${trigger.name}` : trigger.id;
109 if (seen.has(id)) {
110 throw new Error(
111 trigger.kind === "webhook"
112 ? `workflow("${workflow}") has two hooks named "${trigger.name}". Give each its own name.`
113 : `workflow("${workflow}") lists the same ${trigger.kind === "schedule" ? "schedule" : "trigger"} twice. List it once.`,
114 );
115 }
116 seen.add(id);
117 }
118};
119
120const openedId = (
121 kind: OpenedTrigger["kind"],
122 options: {
123 readonly project: string;
124 readonly labels?: ReadonlyArray<string>;
125 readonly query?: string;
126 },
127) =>
128 // A tuple, so no label or query can be read as part of another.
129 JSON.stringify([kind, options.project, options.labels?.toSorted() ?? [], options.query ?? ""]);
130
131/**
132 * A run for each issue opened in the project's tracker from now on, with the issue as its
133 * payload (`Issue`). Issues that were already there when the workflow was first loaded start
134 * nothing. `labels` are ones the issue must carry, all of them; `query` is free text for the
135 * tracker. The tracker is asked about once a minute.
136 */
137export const issuesOpened = (options: {
138 readonly project: string;
139 readonly labels?: ReadonlyArray<string>;
140 readonly query?: string;
141}): Trigger<Issue> => {
142 checkOptions("issues.opened", options, ["project", "labels", "query"]);
143 return { kind: "issues", id: openedId("issues", options), ...options };
144};
145
146/**
147 * A run for each pull request opened against the project's repository from now on, with the pull
148 * request as its payload (`PullRequest`). `query` is free text for the host.
149 */
150export const pullRequestsOpened = (options: {
151 readonly project: string;
152 readonly query?: string;
153}): Trigger<PullRequest> => {
154 checkOptions("pullRequests.opened", options, ["project", "query"]);
155 return { kind: "pullRequests", id: openedId("pullRequests", options), ...options };
156};