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); `already_delivered` is a
98 * retry of an id that already woke a wait, so it woke nothing.
99 */
100 readonly signal: (
101 address: WorkflowStore.SignalAddress,
102 value: Schema.Json,
103 options: {
104 readonly id: string;
105 readonly ttl?: Duration.Input;
106 /** Who sent it, kept with an answer to a question. */
107 readonly answeredBy?: string | undefined;
108 /** The client session that sent it, where one did. A name is shared; this is not. */
109 readonly answeredBySession?: string | undefined;
110 },
111 ) => Effect.Effect<"delivered" | "buffered" | "already_delivered", WorkflowInputError>;
112 /**
113 * Answer the question a run asks a person. One answer per time it is asked: a second, a
114 * double click, wakes nothing and is not kept for later.
115 */
116 readonly answer: (
117 runId: string,
118 name: string,
119 value: Schema.Json,
120 /** Who answered, as the server knows them; kept with the answer. */
121 answeredBy?: { readonly label: string; readonly sessionId?: string | undefined },
122 ) => Effect.Effect<void, WorkflowInputError>;
123 /** Run a paused run's failed step again. */
124 readonly resume: (runId: string) => Effect.Effect<void, WorkflowError>;
125 readonly cancel: (runId: string, reason?: string) => Effect.Effect<void, WorkflowError>;
126 /**
127 * End a run's open question unanswered, as its timeout would: its `ask` returns `None` and the
128 * run goes on. `not_open` when the question was answered, timed out or never asked.
129 */
130 readonly withdraw: (
131 runId: string,
132 name: string,
133 options: { readonly by: string; readonly reason?: string | undefined },
134 ) => Effect.Effect<"withdrawn" | "not_open", WorkflowError>;
135 readonly get: (runId: string) => Effect.Effect<
136 {
137 readonly run: WorkflowStore.WorkflowRun;
138 readonly steps: ReadonlyArray<WorkflowStore.WorkflowStep>;
139 readonly references: ReadonlyArray<WorkflowRunReference>;
140 },
141 WorkflowRunNotFoundError | WorkflowInputError
142 >;
143 readonly list: (filter?: {
144 readonly status?: WorkflowStore.WorkflowRunStatus;
145 /** Only runs their workflow tagged with this. */
146 readonly tag?: string;
147 /** Only runs about this: their subject's web address, or its key, such as a thread id. */
148 readonly subject?: string;
149 }) => Effect.Effect<ReadonlyArray<WorkflowStore.WorkflowRun>, WorkflowInputError>;
150 /**
151 * The runs about an item, by its web address (as `list` reads `subject`) or by the issue or
152 * pull request it is, and the questions they have open, for the item's own view: the runs
153 * list is the newest runs of every subject.
154 */
155 readonly about: (item: WorkflowRunsAboutInput) => Effect.Effect<
156 {
157 readonly runs: ReadonlyArray<WorkflowStore.WorkflowRun>;
158 readonly questions: ReadonlyArray<WorkflowQuestion>;
159 },
160 WorkflowInputError
161 >;
162 /** The run once `done` holds for it. Looks now, then on every change to the run. */
163 readonly waitFor: (
164 runId: string,
165 done: (run: WorkflowStore.WorkflowRun) => boolean,
166 ) => Effect.Effect<WorkflowStore.WorkflowRun>;
167 /** The questions runs are waiting on a person to answer, oldest first. */
168 readonly questions: Effect.Effect<ReadonlyArray<WorkflowQuestion>, WorkflowInputError>;
169 /** What each run that has not ended is a run of, however many: no list limit applies. */
170 readonly unfinished: Effect.Effect<
171 ReadonlyArray<{ readonly workflow: string; readonly version: number }>
172 >;
173 /** The hook URLs of the registered workflows. */
174 readonly hooks: Effect.Effect<ReadonlyArray<WorkflowHook>, WorkflowInputError>;
175 /**
176 * Start the run a request to a hook asks for. Nothing, for a hook or token that is not known.
177 * `deliveryId` names the delivery when its carrier vouches for one, so its retry is one run.
178 * A hook starts a bounded number of new runs a minute and is busy past that.
179 */
180 readonly deliver: (delivery: {
181 readonly hookId: string;
182 readonly token: string;
183 readonly request: WebhookRequest;
184 readonly deliveryId?: string;
185 }) => Effect.Effect<Option.Option<{ readonly runId: string }>, WorkflowError>;
186 /** What workflows keep in the store under keys starting with `prefix`, for a person to see. */
187 readonly stored: (
188 prefix: string,
189 ) => Effect.Effect<
190 ReadonlyArray<{ readonly key: string; readonly value: Schema.Json }>,
191 WorkflowInputError
192 >;
193 /** Set a key of the store from outside a run, as a person flipping a switch does. */
194 readonly storeSet: (key: string, value: Schema.Json) => Effect.Effect<void, WorkflowInputError>;
195 readonly storeDelete: (key: string) => Effect.Effect<void, WorkflowInputError>;
196 /** Recent runs and open questions now, then what changed of them after every change. */
197 readonly watch: Stream.Stream<WorkflowRunsUpdate>;
198 /** How much is going on, now and again whenever a count changes. */
199 readonly counts: Stream.Stream<WorkflowCounts>;
200 /**
201 * Deliver timeouts to waits past their deadline, drop expired mail, and resume paused runs
202 * whose rest is over. Runs by itself every few seconds.
203 */
204 readonly sweep: Effect.Effect<void>;
205 }
206>()("t3/workflows/Workflows") {}
207
208const refuse = Effect.fn("Workflows.disabled")(function* () {
209 return yield* new WorkflowInputError({
210 problem:
211 "This server defines no workflows yet. Add a file to the workflows folder of its T3 home.",
212 });
213});
214
215/** The service with nothing registered and no engine behind it. */
216export const disabled = Workflows.of({
217 start: refuse,
218 signal: refuse,
219 answer: refuse,
220 resume: refuse,
221 cancel: refuse,
222 withdraw: refuse,
223 get: Effect.fn("Workflows.get")(function* (runId) {
224 return yield* new WorkflowRunNotFoundError({ runId });
225 }),
226 list: Effect.fn("Workflows.list")(function* () {
227 return yield* Effect.succeed<ReadonlyArray<WorkflowStore.WorkflowRun>>([]);
228 }),
229 about: Effect.fn("Workflows.about")(function* () {
230 return yield* Effect.succeed({ runs: [], questions: [] });
231 }),
232 waitFor: Effect.fn("Workflows.waitFor")(function* () {
233 return yield* Effect.never;
234 }),
235 questions: Effect.succeed([]),
236 unfinished: Effect.succeed([]),
237 hooks: Effect.succeed([]),
238 deliver: Effect.fn("Workflows.deliver")(function* () {
239 return yield* Effect.succeed(Option.none<{ readonly runId: string }>());
240 }),
241 stored: Effect.fn("Workflows.stored")(function* () {
242 return yield* Effect.succeed<ReadonlyArray<{ key: string; value: Schema.Json }>>([]);
243 }),
244 storeSet: refuse,
245 storeDelete: refuse,
246 watch: Stream.concat(Stream.make({ workflows: [], runs: [], questions: [] }), Stream.never),
247 counts: Stream.concat(Stream.make({ needsYou: 0, active: 0, total: 0 }), Stream.never),
248 sweep: Effect.void,
249});
250export const layerDisabled = Layer.succeed(Workflows, disabled);
251
252/** What `watch` sends, as the whole list every time: for a client that did not ask for changes. */
253export const wholeLists = (updates: Stream.Stream<WorkflowRunsUpdate>) =>
254 updates.pipe(
255 Stream.mapAccum(
256 (): WorkflowRunsSnapshot | undefined => undefined,
257 (list, update) => {
258 const next = applyWorkflowRunsUpdate(list, update);
259 return [next, [next]] as const;
260 },
261 ),
262 );
263
264export const OFF =
265 '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).';
266
267const refuseOff = Effect.fn("Workflows.off")(function* () {
268 return yield* new WorkflowInputError({ problem: OFF });
269});
270
271/**
272 * The service while workflows are off: every request is refused, and a hook answers as one that
273 * is not there.
274 */
275export const off = Workflows.of({
276 ...disabled,
277 start: refuseOff,
278 signal: refuseOff,
279 answer: refuseOff,
280 resume: refuseOff,
281 cancel: refuseOff,
282 withdraw: refuseOff,
283 get: refuseOff,
284 list: refuseOff,
285 about: refuseOff,
286 questions: refuseOff(),
287 hooks: refuseOff(),
288 stored: refuseOff,
289 storeSet: refuseOff,
290 storeDelete: refuseOff,
291});