Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Workflows.ts

258 lines9.9 KB

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