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

workflow.ts

408 lines13.7 KB

1import { WorkflowHook, WorkflowRunStatus } from "@t3tools/contracts";
2import * as Console from "effect/Console";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6import { Argument, Command, Flag } from "effect/cli";
7​
8import * as Workflows from "../workflows/Workflows.ts";
9import { WorkflowRun, WorkflowStep } from "../workflows/WorkflowStore.ts";
10import { projectLocationFlags } from "./config.ts";
11import {
12 jsonFlag,
13 printJson,
14 reportThreadErrors,
15 type ThreadTools,
16 ThreadUsageError,
17 withThreadTools,
18} from "./thread.ts";
19​
20const RunResult = Schema.Struct({ run: WorkflowRun, steps: Schema.Array(WorkflowStep) });
21const RunsResult = Schema.Struct({ runs: Schema.Array(WorkflowRun) });
22const QuestionsResult = Schema.Struct({ questions: Schema.Array(Workflows.WorkflowQuestion) });
23const HooksResult = Schema.Struct({ hooks: Schema.Array(WorkflowHook) });
24const SignalResult = Schema.Struct({ delivery: Schema.Literals(["delivered", "buffered"]) });
25​
26const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Json));
27const jsonArgument = (text: string, what: string) =>
28 decodeJson(text).pipe(
29 Effect.mapError(() => new ThreadUsageError({ detail: `${what} is not valid JSON.` })),
30 );
31​
32const runLine = (run: WorkflowRun) =>
33 [run.runId, run.status.padEnd(9), run.workflow, run.title, run.detail ?? ""].join(" ").trimEnd();
34​
35const printRun = Effect.fn("cli.workflow.printRun")(function* (
36 result: typeof RunResult.Type,
37 json: boolean,
38) {
39 if (json) return yield* printJson(result);
40 yield* Console.log(runLine(result.run));
41 for (const step of result.steps) {
42 yield* Console.log(
43 ` ${step.status.padEnd(9)} ${step.kind.padEnd(5)} ${step.name}${
44 step.attempts > 1 ? ` (${step.attempts} tries)` : ""
45 }${step.environmentId === null ? "" : ` in ${step.environmentId}`}${
46 step.detail === null ? "" : ` ${step.detail}`
47 }`,
48 );
49 }
50 if (result.run.result !== null) yield* printJson(result.run.result);
51});
52​
53const runArgument = Argument.String("run").pipe(Argument.withDescription("Run id."));
54const readRun = (tools: ThreadTools, runId: string) =>
55 tools.call("t3_workflow", { action: "read", runId }, RunResult);
56​
57const startCommand = Command.make("start", {
58 ...projectLocationFlags,
59 workflow: Argument.String("workflow").pipe(Argument.withDescription("Workflow name.")),
60 input: Flag.String("input").pipe(
61 Flag.withDescription("The run's payload, as JSON. Defaults to {}."),
62 Flag.withDefault("{}"),
63 ),
64 key: Flag.String("key").pipe(
65 Flag.withDescription(
66 "Required. Names this run: starting again with the same key is the same run, not a second one.",
67 ),
68 ),
69 json: jsonFlag,
70}).pipe(
71 Command.withDescription("Start a workflow run and print it."),
72 Command.withHandler((flags) =>
73 Effect.gen(function* () {
74 const input = yield* jsonArgument(flags.input, "--input");
75 if (flags.key.trim() === "") {
76 return yield* new ThreadUsageError({ detail: "--key cannot be blank." });
77 }
78 yield* withThreadTools(
79 flags,
80 Effect.fn("cli.workflow.start")(function* (tools) {
81 const started = yield* tools.call(
82 "t3_workflow",
83 { action: "start", workflow: flags.workflow, input, idempotencyKey: flags.key },
84 RunResult,
85 );
86 yield* printRun(started, flags.json);
87 }),
88 );
89 }).pipe(reportThreadErrors),
90 ),
91);
92​
93const listCommand = Command.make("list", {
94 ...projectLocationFlags,
95 status: Flag.Literals("status", WorkflowRunStatus.literals).pipe(
96 Flag.withDescription(
97 "Only runs in this state. A skipped run is listed only with `skipped`, unless another run invoked it.",
98 ),
99 Flag.optional,
100 ),
101 json: jsonFlag,
102}).pipe(
103 Command.withDescription("List workflow runs, newest first."),
104 Command.withHandler((flags) =>
105 withThreadTools(
106 flags,
107 Effect.fn("cli.workflow.list")(function* (tools) {
108 const { runs } = yield* tools.call(
109 "t3_workflow",
110 {
111 action: "list",
112 ...(Option.isSome(flags.status) ? { status: flags.status.value } : {}),
113 },
114 RunsResult,
115 );
116 // A workflow skips what was never its to do, and that is most of what a trigger brings.
117 const listed = Option.isSome(flags.status)
118 ? runs
119 : runs.filter((run) => run.status !== "skipped" || run.parentRunId !== null);
120 if (flags.json) return yield* printJson(listed);
121 for (const run of listed) yield* Console.log(runLine(run));
122 }),
123 ).pipe(reportThreadErrors),
124 ),
125);
126​
127const showCommand = Command.make("show", {
128 ...projectLocationFlags,
129 run: runArgument,
130 json: jsonFlag,
131}).pipe(
132 Command.withDescription("Show a run and its steps."),
133 Command.withHandler((flags) =>
134 withThreadTools(
135 flags,
136 Effect.fn("cli.workflow.show")(function* (tools) {
137 yield* printRun(yield* readRun(tools, flags.run), flags.json);
138 }),
139 ).pipe(reportThreadErrors),
140 ),
141);
142​
143/** Why `action` would leave the run as it is, or undefined when it would act. */
144const noOpReason = (action: "resume" | "cancel", run: WorkflowRun) => {
145 if (action === "cancel") {
146 return run.endedAt === null
147 ? undefined
148 : `Run ${run.runId} is ${run.status}; nothing to cancel.`;
149 }
150 return run.status === "paused"
151 ? undefined
152 : `Run ${run.runId} is ${run.status}; nothing to resume.`;
153};
154​
155const steer = Effect.fn("cli.workflow.steer")(function* (
156 tools: ThreadTools,
157 action: "resume" | "cancel",
158 flags: { readonly run: string; readonly json: boolean; readonly reason: Option.Option<string> },
159) {
160 const before = yield* readRun(tools, flags.run);
161 const skipped = noOpReason(action, before.run);
162 if (skipped !== undefined) {
163 // Stderr, so --json output stays the run alone.
164 yield* Console.error(skipped);
165 return yield* printRun(before, flags.json);
166 }
167 const after = yield* tools.call(
168 "t3_workflow",
169 {
170 action,
171 runId: flags.run,
172 ...(Option.isSome(flags.reason) ? { reason: flags.reason.value } : {}),
173 },
174 RunResult,
175 );
176 yield* printRun(after, flags.json);
177});
178​
179const resumeCommand = Command.make("resume", {
180 ...projectLocationFlags,
181 run: runArgument,
182 json: jsonFlag,
183}).pipe(
184 Command.withDescription("Run a paused run's failed step again."),
185 Command.withHandler((flags) =>
186 withThreadTools(flags, (tools) =>
187 steer(tools, "resume", { ...flags, reason: Option.none() }),
188 ).pipe(reportThreadErrors),
189 ),
190);
191​
192const cancelCommand = Command.make("cancel", {
193 ...projectLocationFlags,
194 run: runArgument,
195 reason: Flag.String("reason").pipe(
196 Flag.withDescription("Why, kept as the run's detail."),
197 Flag.optional,
198 ),
199 json: jsonFlag,
200}).pipe(
201 Command.withDescription("Cancel a run."),
202 Command.withHandler((flags) =>
203 withThreadTools(flags, (tools) => steer(tools, "cancel", flags)).pipe(reportThreadErrors),
204 ),
205);
206​
207const signalCommand = Command.make("signal", {
208 ...projectLocationFlags,
209 value: Argument.String("value").pipe(
210 Argument.withDescription('What the wait receives, as JSON. A question takes {"choice": ...}.'),
211 ),
212 run: Flag.String("run").pipe(
213 Flag.withDescription("Run id. Pass with --wait, not with --workflow and --channel."),
214 Flag.optional,
215 ),
216 wait: Flag.String("wait").pipe(
217 Flag.withDescription("The wait's or question's name in that run."),
218 Flag.optional,
219 ),
220 workflow: Flag.String("workflow").pipe(
221 Flag.withDescription("Workflow name. Pass with --channel when the run is not known."),
222 Flag.optional,
223 ),
224 channel: Flag.String("channel").pipe(
225 Flag.withDescription("The channel the wait opened with."),
226 Flag.optional,
227 ),
228 id: Flag.String("id").pipe(
229 Flag.withDescription(
230 "Names this signal: sending it again with the same id is the same signal.",
231 ),
232 Flag.optional,
233 ),
234}).pipe(
235 Command.withDescription("Wake a waiting run, or answer its question."),
236 Command.withHandler((flags) =>
237 Effect.gen(function* () {
238 const value = yield* jsonArgument(flags.value, "The value");
239 const byRun = Option.isSome(flags.run) || Option.isSome(flags.wait);
240 const byChannel = Option.isSome(flags.workflow) || Option.isSome(flags.channel);
241 if (byRun && byChannel) {
242 return yield* new ThreadUsageError({
243 detail:
244 "Address a signal with --run and --wait, or with --workflow and --channel, not both.",
245 });
246 }
247 yield* withThreadTools(
248 { ...flags, json: false },
249 Effect.fn("cli.workflow.signal")(function* (tools) {
250 const { delivery } = yield* tools.call(
251 "t3_workflow",
252 {
253 action: "signal",
254 value,
255 ...(Option.isSome(flags.run) ? { runId: flags.run.value } : {}),
256 ...(Option.isSome(flags.wait) ? { wait: flags.wait.value } : {}),
257 ...(Option.isSome(flags.workflow) ? { workflow: flags.workflow.value } : {}),
258 ...(Option.isSome(flags.channel) ? { channel: flags.channel.value } : {}),
259 ...(Option.isSome(flags.id) ? { signalId: flags.id.value } : {}),
260 },
261 SignalResult,
262 );
263 yield* Console.log(
264 delivery === "delivered" ? "Delivered." : "Kept until a run waits for it.",
265 );
266 }),
267 );
268 }).pipe(reportThreadErrors),
269 ),
270);
271​
272const questionsCommand = Command.make("questions", {
273 ...projectLocationFlags,
274 json: jsonFlag,
275}).pipe(
276 Command.withDescription("List the questions runs are waiting on a person to answer."),
277 Command.withHandler((flags) =>
278 withThreadTools(
279 flags,
280 Effect.fn("cli.workflow.questions")(function* (tools) {
281 const { questions } = yield* tools.call(
282 "t3_workflow",
283 { action: "questions" },
284 QuestionsResult,
285 );
286 if (flags.json) return yield* printJson(questions);
287 for (const question of questions) {
288 yield* Console.log(`${question.runId} ${question.name}`);
289 yield* printJson(question.request);
290 }
291 }),
292 ).pipe(reportThreadErrors),
293 ),
294);
295​
296const hooksCommand = Command.make("hooks", {
297 ...projectLocationFlags,
298 json: jsonFlag,
299}).pipe(
300 Command.withDescription(
301 "List the URL paths that start runs. Each holds its hook's secret; add the server's origin.",
302 ),
303 Command.withHandler((flags) =>
304 withThreadTools(
305 flags,
306 Effect.fn("cli.workflow.hooks")(function* (tools) {
307 const { hooks } = yield* tools.call("t3_workflow", { action: "hooks" }, HooksResult);
308 if (flags.json) return yield* printJson(hooks);
309 for (const hook of hooks) {
310 yield* Console.log(`${hook.workflow} ${hook.name} ${hook.path}`);
311 }
312 }),
313 ).pipe(reportThreadErrors),
314 ),
315);
316​
317const StoreResult = Schema.Struct({
318 entries: Schema.Array(Schema.Struct({ key: Schema.String, value: Schema.Json })),
319});
320const keyArgument = Argument.String("key").pipe(Argument.withDescription("The key in the store."));
321​
322const storeListCommand = Command.make("list", {
323 ...projectLocationFlags,
324 prefix: Argument.String("prefix").pipe(
325 Argument.withDescription("Only keys that start with this."),
326 Argument.withDefault(""),
327 ),
328 json: jsonFlag,
329}).pipe(
330 Command.withDescription("List what workflows keep in the store."),
331 Command.withHandler((flags) =>
332 withThreadTools(
333 flags,
334 Effect.fn("cli.workflow.store.list")(function* (tools) {
335 const { entries } = yield* tools.call(
336 "t3_workflow",
337 { action: "store", ...(flags.prefix === "" ? {} : { key: flags.prefix }) },
338 StoreResult,
339 );
340 if (flags.json) return yield* printJson(entries);
341 for (const entry of entries) {
342 yield* Console.log(entry.key);
343 yield* printJson(entry.value);
344 }
345 }),
346 ).pipe(reportThreadErrors),
347 ),
348);
349​
350const storeSetCommand = Command.make("set", {
351 ...projectLocationFlags,
352 key: keyArgument,
353 value: Argument.String("value").pipe(Argument.withDescription("The value, as JSON.")),
354}).pipe(
355 Command.withDescription("Set a key of the store, as a person flipping a switch does."),
356 Command.withHandler((flags) =>
357 Effect.gen(function* () {
358 const value = yield* jsonArgument(flags.value, "The value");
359 yield* withThreadTools(
360 { ...flags, json: false },
361 Effect.fn("cli.workflow.store.set")(function* (tools) {
362 yield* tools.call(
363 "t3_workflow",
364 { action: "store_set", key: flags.key, value },
365 StoreResult,
366 );
367 yield* Console.log(`Set ${flags.key}.`);
368 }),
369 );
370 }).pipe(reportThreadErrors),
371 ),
372);
373​
374const storeDeleteCommand = Command.make("delete", {
375 ...projectLocationFlags,
376 key: keyArgument,
377}).pipe(
378 Command.withDescription("Delete a key of the store."),
379 Command.withHandler((flags) =>
380 withThreadTools(
381 { ...flags, json: false },
382 Effect.fn("cli.workflow.store.delete")(function* (tools) {
383 yield* tools.call("t3_workflow", { action: "store_delete", key: flags.key }, StoreResult);
384 yield* Console.log(`Deleted ${flags.key}.`);
385 }),
386 ).pipe(reportThreadErrors),
387 ),
388);
389​
390const storeCommand = Command.make("store").pipe(
391 Command.withDescription("See and change what workflows keep between runs."),
392 Command.withSubcommands([storeListCommand, storeSetCommand, storeDeleteCommand]),
393);
394​
395export const workflowCommand = Command.make("workflow").pipe(
396 Command.withDescription("Start, inspect and steer durable workflow runs on the running server."),
397 Command.withSubcommands([
398 startCommand,
399 listCommand,
400 showCommand,
401 resumeCommand,
402 cancelCommand,
403 signalCommand,
404 questionsCommand,
405 hooksCommand,
406 storeCommand,
407 ]),
408);