Open History to see the last commit
1import {
2 type WorkflowCounts,
3 type WorkflowHook,
4 WorkflowQuestion,
5 type WorkflowRunReference,
6 type WorkflowRunsAboutInput,
7 applyWorkflowRunsUpdate,
8 type WorkflowRunsSnapshot,
9 type WorkflowRunsUpdate,
10} from "@t3tools/contracts";
11import * as Context from "effect/Context";
12import type * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Schema from "effect/Schema";
17import * as Stream from "effect/Stream";
18
19import type { WebhookRequest } from "./triggers.ts";
20import type * as WorkflowStore from "./WorkflowStore.ts";
21
22/** Hook ids of workflows start with this; a scheduled task's hook id never does. */
23export const HOOK_PREFIX = "wf-";
24
25// The dot between the two parts is never in either, so no two hooks share an id.
26const hookPart = (part: string) => encodeURIComponent(part).replaceAll(".", "%2E");
27/** The id of the hook `name` of `workflow`, which its URL and its secret are kept by. */
28export const hookId = (workflow: string, name: string) =>
29 `${HOOK_PREFIX}${hookPart(workflow)}.${hookPart(name)}`;
30
31export class WorkflowNotRegisteredError extends Schema.TaggedError<WorkflowNotRegisteredError>()(
32 "WorkflowNotRegisteredError",
33 { workflow: Schema.String, version: Schema.optional(Schema.Number) },
34) {
35 override get message(): string {
36 return this.version === undefined
37 ? `No workflow named ${this.workflow} is registered.`
38 : `Version ${this.version} of workflow ${this.workflow} is not registered.`;
39 }
40}
41
42export class WorkflowRunNotFoundError extends Schema.TaggedError<WorkflowRunNotFoundError>()(
43 "WorkflowRunNotFoundError",
44 { runId: Schema.String },
45) {
46 override get message(): string {
47 return `Workflow run ${this.runId} was not found.`;
48 }
49}
50
51export class WorkflowInputError extends Schema.TaggedError<WorkflowInputError>()(
52 "WorkflowInputError",
53 { problem: Schema.String },
54) {
55 override get message(): string {
56 return this.problem;
57 }
58}
59
60/** A hook that has started as many runs as it may for now. */
61export class WorkflowHookBusyError extends Schema.TaggedError<WorkflowHookBusyError>()(
62 "WorkflowHookBusyError",
63 { hook: Schema.String },
64) {
65 override get message(): string {
66 return `Hook ${this.hook} has started as many runs as it may in a minute.`;
67 }
68}
69
70export { WorkflowQuestion };
71
72export type WorkflowError =
73 | WorkflowNotRegisteredError
74 | WorkflowRunNotFoundError
75 | WorkflowInputError
76 | WorkflowHookBusyError;
77
78export class Workflows extends Context.Service<
79 Workflows,
80 {
81 /** Start a run. A second start with the same key is the same run. */
82 readonly start: (
83 workflow: string,
84 input: unknown,
85 options: {
86 readonly idempotencyKey: string;
87 /** The run that waits for this one. A run started with a key has one parent or none. */
88 readonly parent?: WorkflowStore.RunParent;
89 /** The version to run, when the caller holds a definition. Without it, the newest. */
90 readonly version?: number;
91 /** What a new run is about. A start that finds its run already there leaves it be. */
92 readonly subject?: WorkflowStore.ReferenceInput;
93 },
94 ) => Effect.Effect<{ readonly runId: string }, WorkflowError>;
95 /**
96 * Say that something a run waits on happened. `delivered` woke a wait; `buffered` is kept for
97 * a wait that has not opened yet, for `ttl` (seven days by default).
98 */
99 readonly signal: (
100 address: WorkflowStore.SignalAddress,
101 value: Schema.Json,
102 options: {
103 readonly id: string;
104 readonly ttl?: Duration.Input;
105 /** Who sent it, kept with an answer to a question. */
106 readonly answeredBy?: string | undefined;
107 /** The client session that sent it, where one did. A name is shared; this is not. */
108 readonly answeredBySession?: string | undefined;
109 },
110 ) => Effect.Effect<"delivered" | "buffered", WorkflowInputError>;
111 /**
112 * Answer the question a run asks a person. One answer per time it is asked: a second, a
113 * double click, wakes nothing and is not kept for later.
114 */
115 readonly answer: (
116 runId: string,
117 name: string,
118 value: Schema.Json,
119 /** Who answered, as the server knows them; kept with the answer. */
120 answeredBy?: { readonly label: string; readonly sessionId?: string | undefined },
121 ) => Effect.Effect<void, WorkflowInputError>;
122 /** Run a paused run's failed step again. */
123 readonly resume: (runId: string) => Effect.Effect<void, WorkflowError>;
124 readonly cancel: (runId: string, reason?: string) => Effect.Effect<void, WorkflowError>;
125 /**
126 * End a run's open question unanswered, as its timeout would: its `ask` returns `None` and the
127 * run goes on. `not_open` when the question was answered, timed out or never asked.
128 */
129 readonly withdraw: (
130 runId: string,
131 name: string,
132 options: { readonly by: string; readonly reason?: string | undefined },
133 ) => Effect.Effect<"withdrawn" | "not_open", WorkflowError>;
134 readonly get: (runId: string) => Effect.Effect<
135 {
136 readonly run: WorkflowStore.WorkflowRun;
137 readonly steps: ReadonlyArray<WorkflowStore.WorkflowStep>;
138 readonly references: ReadonlyArray<WorkflowRunReference>;
139 },
140 WorkflowRunNotFoundError | WorkflowInputError
141 >;
142 readonly list: (filter?: {
143 readonly status?: WorkflowStore.WorkflowRunStatus;
144 /** Only runs their workflow tagged with this. */
145 readonly tag?: string;
146 /** Only runs about this: their subject's web address, or its key, such as a thread id. */
147 readonly subject?: string;
148 }) => Effect.Effect<ReadonlyArray<WorkflowStore.WorkflowRun>, WorkflowInputError>;
149 /**
150 * The runs about an item, by its web address (as `list` reads `subject`) or by the issue or
151 * pull request it is, and the questions they have open, for the item's own view: the runs
152 * list is the newest runs of every subject.
153 */
154 readonly about: (item: WorkflowRunsAboutInput) => Effect.Effect<
155 {
156 readonly runs: ReadonlyArray<WorkflowStore.WorkflowRun>;
157 readonly questions: ReadonlyArray<WorkflowQuestion>;
158 },
159 WorkflowInputError
160 >;
161 /** The run once `done` holds for it. Looks now, then on every change to the run. */
162 readonly waitFor: (
163 runId: string,
164 done: (run: WorkflowStore.WorkflowRun) => boolean,
165 ) => Effect.Effect<WorkflowStore.WorkflowRun>;
166 /** The questions runs are waiting on a person to answer, oldest first. */
167 readonly questions: Effect.Effect<ReadonlyArray<WorkflowQuestion>, WorkflowInputError>;
168 /** What each run that has not ended is a run of, however many: no list limit applies. */
169 readonly unfinished: Effect.Effect<
170 ReadonlyArray<{ readonly workflow: string; readonly version: number }>
171 >;
172 /** The hook URLs of the registered workflows. */
173 readonly hooks: Effect.Effect<ReadonlyArray<WorkflowHook>, WorkflowInputError>;
174 /**
175 * Start the run a request to a hook asks for. Nothing, for a hook or token that is not known.
176 * `deliveryId` names the delivery when its carrier vouches for one, so its retry is one run.
177 * A hook starts a bounded number of new runs a minute and is busy past that.
178 */
179 readonly deliver: (delivery: {
180 readonly hookId: string;
181 readonly token: string;
182 readonly request: WebhookRequest;
183 readonly deliveryId?: string;
184 }) => Effect.Effect<Option.Option<{ readonly runId: string }>, WorkflowError>;
185 /** What workflows keep in the store under keys starting with `prefix`, for a person to see. */
186 readonly stored: (
187 prefix: string,
188 ) => Effect.Effect<
189 ReadonlyArray<{ readonly key: string; readonly value: Schema.Json }>,
190 WorkflowInputError
191 >;
192 /** Set a key of the store from outside a run, as a person flipping a switch does. */
193 readonly storeSet: (key: string, value: Schema.Json) => Effect.Effect<void, WorkflowInputError>;
194 readonly storeDelete: (key: string) => Effect.Effect<void, WorkflowInputError>;
195 /** Recent runs and open questions now, then what changed of them after every change. */
196 readonly watch: Stream.Stream<WorkflowRunsUpdate>;
197 /** How much is going on, now and again whenever a count changes. */
198 readonly counts: Stream.Stream<WorkflowCounts>;
199 /**
200 * Deliver timeouts to waits past their deadline, drop expired mail, and resume paused runs
201 * whose rest is over. Runs by itself every few seconds.
202 */
203 readonly sweep: Effect.Effect<void>;
204 }
205>()("t3/workflows/Workflows") {}
206
207const refuse = Effect.fn("Workflows.disabled")(function* () {
208 return yield* new WorkflowInputError({
209 problem:
210 "This server defines no workflows yet. Add a file to the workflows folder of its T3 home.",
211 });
212});
213
214/** The service with nothing registered and no engine behind it. */
215export const disabled = Workflows.of({
216 start: refuse,
217 signal: refuse,
218 answer: refuse,
219 resume: refuse,
220 cancel: refuse,
221 withdraw: refuse,
222 get: Effect.fn("Workflows.get")(function* (runId) {
223 return yield* new WorkflowRunNotFoundError({ runId });
224 }),
225 list: Effect.fn("Workflows.list")(function* () {
226 return yield* Effect.succeed<ReadonlyArray<WorkflowStore.WorkflowRun>>([]);
227 }),
228 about: Effect.fn("Workflows.about")(function* () {
229 return yield* Effect.succeed({ runs: [], questions: [] });
230 }),
231 waitFor: Effect.fn("Workflows.waitFor")(function* () {
232 return yield* Effect.never;
233 }),
234 questions: Effect.succeed([]),
235 unfinished: Effect.succeed([]),
236 hooks: Effect.succeed([]),
237 deliver: Effect.fn("Workflows.deliver")(function* () {
238 return yield* Effect.succeed(Option.none<{ readonly runId: string }>());
239 }),
240 stored: Effect.fn("Workflows.stored")(function* () {
241 return yield* Effect.succeed<ReadonlyArray<{ key: string; value: Schema.Json }>>([]);
242 }),
243 storeSet: refuse,
244 storeDelete: refuse,
245 watch: Stream.concat(Stream.make({ workflows: [], runs: [], questions: [] }), Stream.never),
246 counts: Stream.concat(Stream.make({ needsYou: 0, active: 0, total: 0 }), Stream.never),
247 sweep: Effect.void,
248});
249export const layerDisabled = Layer.succeed(Workflows, disabled);
250
251/** What `watch` sends, as the whole list every time: for a client that did not ask for changes. */
252export const wholeLists = (updates: Stream.Stream<WorkflowRunsUpdate>) =>
253 updates.pipe(
254 Stream.mapAccum(
255 (): WorkflowRunsSnapshot | undefined => undefined,
256 (list, update) => {
257 const next = applyWorkflowRunsUpdate(list, update);
258 return [next, [next]] as const;
259 },
260 ),
261 );
262
263export const OFF =
264 'Workflows are off on this server. Turn them on in its Settings → Labs → Workflows, or without a desktop, set "workflowsEnabled": true in userdata/settings.json in its T3 home (~/.t3 by default).';
265
266const refuseOff = Effect.fn("Workflows.off")(function* () {
267 return yield* new WorkflowInputError({ problem: OFF });
268});
269
270/**
271 * The service while workflows are off: every request is refused, and a hook answers as one that
272 * is not there.
273 */
274export const off = Workflows.of({
275 ...disabled,
276 start: refuseOff,
277 signal: refuseOff,
278 answer: refuseOff,
279 resume: refuseOff,
280 cancel: refuseOff,
281 withdraw: refuseOff,
282 get: refuseOff,
283 list: refuseOff,
284 about: refuseOff,
285 questions: refuseOff(),
286 hooks: refuseOff(),
287 stored: refuseOff,
288 storeSet: refuseOff,
289 storeDelete: refuseOff,
290});