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