Open History to see the last commit
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 const completeRun = Option.isSome(flags.run) && Option.isSome(flags.wait);
248 const completeChannel = Option.isSome(flags.workflow) && Option.isSome(flags.channel);
249 if (!completeRun && !completeChannel) {
250 return yield* new ThreadUsageError({
251 detail: "Address a signal with --run and --wait, or with --workflow and --channel.",
252 });
253 }
254 yield* withThreadTools(
255 { ...flags, json: false },
256 Effect.fn("cli.workflow.signal")(function* (tools) {
257 const { delivery } = yield* tools.call(
258 "t3_workflow",
259 {
260 action: "signal",
261 value,
262 ...(Option.isSome(flags.run) ? { runId: flags.run.value } : {}),
263 ...(Option.isSome(flags.wait) ? { wait: flags.wait.value } : {}),
264 ...(Option.isSome(flags.workflow) ? { workflow: flags.workflow.value } : {}),
265 ...(Option.isSome(flags.channel) ? { channel: flags.channel.value } : {}),
266 ...(Option.isSome(flags.id) ? { signalId: flags.id.value } : {}),
267 },
268 SignalResult,
269 );
270 yield* Console.log(
271 delivery === "delivered" ? "Delivered." : "Kept until a run waits for it.",
272 );
273 }),
274 );
275 }).pipe(reportThreadErrors),
276 ),
277);
278
279const questionsCommand = Command.make("questions", {
280 ...projectLocationFlags,
281 json: jsonFlag,
282}).pipe(
283 Command.withDescription("List the questions runs are waiting on a person to answer."),
284 Command.withHandler((flags) =>
285 withThreadTools(
286 flags,
287 Effect.fn("cli.workflow.questions")(function* (tools) {
288 const { questions } = yield* tools.call(
289 "t3_workflow",
290 { action: "questions" },
291 QuestionsResult,
292 );
293 if (flags.json) return yield* printJson(questions);
294 for (const question of questions) {
295 yield* Console.log(`${question.runId} ${question.name}`);
296 yield* printJson(question.request);
297 }
298 }),
299 ).pipe(reportThreadErrors),
300 ),
301);
302
303const hooksCommand = Command.make("hooks", {
304 ...projectLocationFlags,
305 json: jsonFlag,
306}).pipe(
307 Command.withDescription(
308 "List the URL paths that start runs. Each holds its hook's secret; add the server's origin.",
309 ),
310 Command.withHandler((flags) =>
311 withThreadTools(
312 flags,
313 Effect.fn("cli.workflow.hooks")(function* (tools) {
314 const { hooks } = yield* tools.call("t3_workflow", { action: "hooks" }, HooksResult);
315 if (flags.json) return yield* printJson(hooks);
316 for (const hook of hooks) {
317 yield* Console.log(`${hook.workflow} ${hook.name} ${hook.path}`);
318 }
319 }),
320 ).pipe(reportThreadErrors),
321 ),
322);
323
324const StoreResult = Schema.Struct({
325 entries: Schema.Array(Schema.Struct({ key: Schema.String, value: Schema.Json })),
326});
327const keyArgument = Argument.String("key").pipe(Argument.withDescription("The key in the store."));
328
329const storeListCommand = Command.make("list", {
330 ...projectLocationFlags,
331 prefix: Argument.String("prefix").pipe(
332 Argument.withDescription("Only keys that start with this."),
333 Argument.withDefault(""),
334 ),
335 json: jsonFlag,
336}).pipe(
337 Command.withDescription("List what workflows keep in the store."),
338 Command.withHandler((flags) =>
339 withThreadTools(
340 flags,
341 Effect.fn("cli.workflow.store.list")(function* (tools) {
342 const { entries } = yield* tools.call(
343 "t3_workflow",
344 { action: "store", ...(flags.prefix === "" ? {} : { key: flags.prefix }) },
345 StoreResult,
346 );
347 if (flags.json) return yield* printJson(entries);
348 for (const entry of entries) {
349 yield* Console.log(entry.key);
350 yield* printJson(entry.value);
351 }
352 }),
353 ).pipe(reportThreadErrors),
354 ),
355);
356
357const storeSetCommand = Command.make("set", {
358 ...projectLocationFlags,
359 key: keyArgument,
360 value: Argument.String("value").pipe(Argument.withDescription("The value, as JSON.")),
361}).pipe(
362 Command.withDescription("Set a key of the store, as a person flipping a switch does."),
363 Command.withHandler((flags) =>
364 Effect.gen(function* () {
365 const value = yield* jsonArgument(flags.value, "The value");
366 yield* withThreadTools(
367 { ...flags, json: false },
368 Effect.fn("cli.workflow.store.set")(function* (tools) {
369 yield* tools.call(
370 "t3_workflow",
371 { action: "store_set", key: flags.key, value },
372 StoreResult,
373 );
374 yield* Console.log(`Set ${flags.key}.`);
375 }),
376 );
377 }).pipe(reportThreadErrors),
378 ),
379);
380
381const storeDeleteCommand = Command.make("delete", {
382 ...projectLocationFlags,
383 key: keyArgument,
384}).pipe(
385 Command.withDescription("Delete a key of the store."),
386 Command.withHandler((flags) =>
387 withThreadTools(
388 { ...flags, json: false },
389 Effect.fn("cli.workflow.store.delete")(function* (tools) {
390 yield* tools.call("t3_workflow", { action: "store_delete", key: flags.key }, StoreResult);
391 yield* Console.log(`Deleted ${flags.key}.`);
392 }),
393 ).pipe(reportThreadErrors),
394 ),
395);
396
397const storeCommand = Command.make("store").pipe(
398 Command.withDescription("See and change what workflows keep between runs."),
399 Command.withSubcommands([storeListCommand, storeSetCommand, storeDeleteCommand]),
400);
401
402export const workflowCommand = Command.make("workflow").pipe(
403 Command.withDescription("Start, inspect and steer durable workflow runs on the running server."),
404 Command.withSubcommands([
405 startCommand,
406 listCommand,
407 showCommand,
408 resumeCommand,
409 cancelCommand,
410 signalCommand,
411 questionsCommand,
412 hooksCommand,
413 storeCommand,
414 ]),
415);