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
57export { WorkflowQuestion };
58
59export type WorkflowError =
60 | WorkflowNotRegisteredError
61 | WorkflowRunNotFoundError
62 | WorkflowInputError;
63
64export class Workflows extends Context.Service<
65 Workflows,
66 {
67 /** Start a run. A second start with the same key is the same run. */
68 readonly start: (
69 workflow: string,
70 input: unknown,
71 options: {
72 readonly idempotencyKey: string;
73 /** The run that waits for this one. A run started with a key has one parent or none. */
74 readonly parent?: WorkflowStore.RunParent;
75 /** The version to run, when the caller holds a definition. Without it, the newest. */
76 readonly version?: number;
77 },
78 ) => Effect.Effect<{ readonly runId: string }, WorkflowError>;
79 /**
80 * Say that something a run waits on happened. `delivered` woke a wait; `buffered` is kept for
81 * a wait that has not opened yet, for `ttl` (seven days by default).
82 */
83 readonly signal: (
84 address: WorkflowStore.SignalAddress,
85 value: Schema.Json,
86 options: { readonly id: string; readonly ttl?: Duration.Input },
87 ) => Effect.Effect<"delivered" | "buffered", WorkflowInputError>;
88 /**
89 * Answer the question a run asks a person. One answer per time it is asked: a second, a
90 * double click, wakes nothing and is not kept for later.
91 */
92 readonly answer: (
93 runId: string,
94 name: string,
95 value: Schema.Json,
96 ) => Effect.Effect<void, WorkflowInputError>;
97 /** Run a paused run's failed step again. */
98 readonly resume: (runId: string) => Effect.Effect<void, WorkflowError>;
99 readonly cancel: (runId: string, reason?: string) => Effect.Effect<void, WorkflowError>;
100 readonly get: (runId: string) => Effect.Effect<
101 {
102 readonly run: WorkflowStore.WorkflowRun;
103 readonly steps: ReadonlyArray<WorkflowStore.WorkflowStep>;
104 readonly references: ReadonlyArray<WorkflowRunReference>;
105 },
106 WorkflowRunNotFoundError | WorkflowInputError
107 >;
108 readonly list: (filter?: {
109 readonly status?: WorkflowStore.WorkflowRunStatus;
110 }) => Effect.Effect<ReadonlyArray<WorkflowStore.WorkflowRun>, WorkflowInputError>;
111 /** The run once `done` holds for it. Looks now, then on every change to the run. */
112 readonly waitFor: (
113 runId: string,
114 done: (run: WorkflowStore.WorkflowRun) => boolean,
115 ) => Effect.Effect<WorkflowStore.WorkflowRun>;
116 /** The questions runs are waiting on a person to answer, oldest first. */
117 readonly questions: Effect.Effect<ReadonlyArray<WorkflowQuestion>, WorkflowInputError>;
118 /** What each run that has not ended is a run of, however many: no list limit applies. */
119 readonly unfinished: Effect.Effect<
120 ReadonlyArray<{ readonly workflow: string; readonly version: number }>
121 >;
122 /** The hook URLs of the registered workflows. */
123 readonly hooks: Effect.Effect<ReadonlyArray<WorkflowHook>, WorkflowInputError>;
124 /**
125 * Start the run a request to a hook asks for. Nothing, for a hook or token that is not known.
126 * `deliveryId` names the delivery when its carrier vouches for one, so its retry is one run.
127 */
128 readonly deliver: (delivery: {
129 readonly hookId: string;
130 readonly token: string;
131 readonly request: WebhookRequest;
132 readonly deliveryId?: string;
133 }) => Effect.Effect<Option.Option<{ readonly runId: string }>, WorkflowError>;
134 /** What workflows keep in the store under keys starting with `prefix`, for a person to see. */
135 readonly stored: (
136 prefix: string,
137 ) => Effect.Effect<
138 ReadonlyArray<{ readonly key: string; readonly value: Schema.Json }>,
139 WorkflowInputError
140 >;
141 /** Set a key of the store from outside a run, as a person flipping a switch does. */
142 readonly storeSet: (key: string, value: Schema.Json) => Effect.Effect<void, WorkflowInputError>;
143 readonly storeDelete: (key: string) => Effect.Effect<void, WorkflowInputError>;
144 /** Recent runs and open questions, now and again after every change. */
145 readonly watch: Stream.Stream<WorkflowRunsSnapshot>;
146 /** How much is going on, now and again whenever a count changes. */
147 readonly counts: Stream.Stream<WorkflowCounts>;
148 /**
149 * Deliver timeouts to waits past their deadline, drop expired mail, and resume paused runs
150 * whose rest is over. Runs by itself every few seconds.
151 */
152 readonly sweep: Effect.Effect<void>;
153 }
154>()("t3/workflows/Workflows") {}
155
156const refuse = Effect.fn("Workflows.disabled")(function* () {
157 return yield* new WorkflowInputError({
158 problem:
159 "This server defines no workflows yet. Add a file to the workflows folder of its T3 home.",
160 });
161});
162
163/** The service with nothing registered and no engine behind it. */
164export const disabled = Workflows.of({
165 start: refuse,
166 signal: refuse,
167 answer: refuse,
168 resume: refuse,
169 cancel: refuse,
170 get: Effect.fn("Workflows.get")(function* (runId) {
171 return yield* new WorkflowRunNotFoundError({ runId });
172 }),
173 list: Effect.fn("Workflows.list")(function* () {
174 return yield* Effect.succeed<ReadonlyArray<WorkflowStore.WorkflowRun>>([]);
175 }),
176 waitFor: Effect.fn("Workflows.waitFor")(function* () {
177 return yield* Effect.never;
178 }),
179 questions: Effect.succeed([]),
180 unfinished: Effect.succeed([]),
181 hooks: Effect.succeed([]),
182 deliver: Effect.fn("Workflows.deliver")(function* () {
183 return yield* Effect.succeed(Option.none<{ readonly runId: string }>());
184 }),
185 stored: Effect.fn("Workflows.stored")(function* () {
186 return yield* Effect.succeed<ReadonlyArray<{ key: string; value: Schema.Json }>>([]);
187 }),
188 storeSet: refuse,
189 storeDelete: refuse,
190 watch: Stream.concat(Stream.make({ workflows: [], runs: [], questions: [] }), Stream.never),
191 counts: Stream.concat(Stream.make({ needsYou: 0, active: 0, total: 0 }), Stream.never),
192 sweep: Effect.void,
193});
194export const layerDisabled = Layer.succeed(Workflows, disabled);
195
196export const OFF =
197 '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).';
198
199const refuseOff = Effect.fn("Workflows.off")(function* () {
200 return yield* new WorkflowInputError({ problem: OFF });
201});
202
203/**
204 * The service while workflows are off: every request is refused, and a hook answers as one that
205 * is not there.
206 */
207export const off = Workflows.of({
208 ...disabled,
209 start: refuseOff,
210 signal: refuseOff,
211 answer: refuseOff,
212 resume: refuseOff,
213 cancel: refuseOff,
214 get: refuseOff,
215 list: refuseOff,
216 questions: refuseOff(),
217 hooks: refuseOff(),
218 stored: refuseOff,
219 storeSet: refuseOff,
220 storeDelete: refuseOff,
221});