-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathindex.ts
More file actions
820 lines (788 loc) · 25.6 KB
/
Copy pathindex.ts
File metadata and controls
820 lines (788 loc) · 25.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
import type {
RunResult,
WorkpoolOptions,
WorkpoolRetryOptions,
} from "@convex-dev/workpool";
import { parse } from "convex-helpers/validators";
import {
createFunctionHandle,
type FunctionArgs,
type FunctionReference,
type FunctionVisibility,
type GenericDataModel,
type GenericMutationCtx,
type GenericQueryCtx,
type PaginationOptions,
type PaginationResult,
type RegisteredMutation,
type ReturnValueForOptionalValidator,
} from "convex/server";
import type { ObjectType, PropertyValidators, Validator } from "convex/values";
import type { Step } from "../component/schema.js";
import type {
EventId,
OnCompleteArgs,
PublicWorkflow,
WorkflowId,
WorkflowStep,
} from "../types.js";
import { safeFunctionName } from "./safeFunctionName.js";
import type { IdsToStrings, WorkflowComponent } from "./types.js";
export type { WorkflowComponent } from "./types.js";
import type { WorkflowCtx } from "./workflowContext.js";
import { workflowMutation, type WorkflowArgs } from "./workflowMutation.js";
export {
vEventId,
vWorkflowId,
vWorkflowStep,
type EventId,
type WorkflowId,
type WorkflowStep,
} from "../types.js";
export type { RunOptions, WorkflowCtx } from "./workflowContext.js";
export type { WorkflowArgs } from "./workflowMutation.js";
export { vResultValidator } from "@convex-dev/workpool";
export type CallbackOptions<Context = unknown> =
| {
/**
* A mutation to run after the workflow succeeds, fails, or is canceled.
* The context type is for your use, feel free to provide a validator for it.
*
* If you don't need `context`, you can set the validator to optional
* with `v.optional(v.any())` and pass `context: undefined`.
*
* ```ts
* export const completion = internalMutation({
* args: {
* workflowId: vWorkflowId,
* result: vResultValidator,
* context: v.optional(v.any()),
* },
* handler: async (ctx, args) => {
* console.log(args.result, "Got Context back -> ", args.context);
* },
* });
* ```
*/
onComplete: FunctionReference<
"mutation",
FunctionVisibility,
OnCompleteArgs<Context>
>;
/**
* A context object to pass to the `onComplete` mutation.
* Useful for passing data from the enqueue site to the onComplete site.
*/
context: Context;
}
| {
onComplete?: undefined;
context?: undefined;
};
export type WorkflowDefinition<
ArgsValidator extends PropertyValidators,
ReturnsValidator extends Validator<any, "required", any> | void = any,
> = {
args?: ArgsValidator;
returns?: ReturnsValidator;
workpoolOptions?: WorkpoolRetryOptions;
};
export type WorkflowHandler<
ArgsValidator extends PropertyValidators,
ReturnsValidator extends Validator<any, "required", any> | void,
> = (
step: WorkflowCtx,
args: ObjectType<ArgsValidator>,
) => Promise<ReturnValueForOptionalValidator<ReturnsValidator>>;
export type WorkflowStatus =
| { type: "inProgress"; running: IdsToStrings<Step>[] }
| { type: "completed"; result: unknown }
| { type: "canceled" }
| { type: "failed"; error: string };
/**
* Define a new workflow with typed args and optional return validator.
*
* @example
* ```ts
* export const myWorkflow = defineWorkflow(components.workflow, {
* args: { amount: v.number() },
* returns: v.object({ total: v.number() }),
* }).handler(async (step, args) => {
* ...workflow implementation
* });
* ```
*
* Start the workflow from a mutation or action:
* ```ts
* const workflowId = await start(ctx, internal.myFile.myWorkflow, { amount: 42 });
* ```
* Or call it directly:
* ```ts
* const workflowId = await ctx.runMutation(internal.myFile.myWorkflow, { args: { ...myArgs } });
* ```
*/
export function defineWorkflow<
AV extends PropertyValidators,
RV extends Validator<any, "required", any> | void = void,
>(
component: WorkflowComponent,
config: WorkflowDefinition<AV, RV>,
): {
/**
* Define the workflow handler function.
* Returns a registered mutation to export from your Convex module.
*/
handler(
fn: (
step: WorkflowCtx,
args: ObjectType<AV>,
) => Promise<ReturnValueForOptionalValidator<RV>>,
): RegisteredMutation<"internal", WorkflowArgs<AV>, WorkflowId>;
} {
return {
handler: (fn) =>
workflowMutation(component, { ...config, handler: fn }, undefined),
};
}
// ── Standalone workflow management functions ─────────────────────────
// These take ctx first, then a workflow component, so they can be
// used without a WorkflowManager instance.
type StartOptions<Context = unknown> = CallbackOptions<Context> & {
/**
* By default, during creation the workflow will be initiated immediately.
* With `startAsync` set to true, the workflow will be created but will
* start asynchronously via the internal workpool.
* @default false
*/
startAsync?: boolean;
};
/**
* Start a workflow
*
* It will run asynchronously, returning a workflow ID to monitor the progress.
*
* By default it will start running the handler as part of "start" unless
* `startAsync` is set to true.
*
* ```ts
* const id = await start(ctx, internal.myFile.myWorkflow, { ...args }, {
* onComplete: internal.myFile.handleComplete,
* context: { ...passed through to onComplete },
* });
* ```
*
* @param ctx - The Convex mutation or action context.
* @param workflow - The workflow to start (e.g. `internal.myFile.myWorkflow`).
* @param args - The workflow arguments.
* @param options - Options like `onComplete`, `context`, `startAsync`.
* @returns The workflow ID.
*/
export async function start<
Context = unknown,
F extends FunctionReference<"mutation", "internal"> = FunctionReference<
"mutation",
"internal"
>,
>(
ctx: RunMutationCtx,
workflow: F,
args: FunctionArgs<F>["args"],
options?: StartOptions<Context>,
): Promise<WorkflowId> {
const formatted: Record<string, unknown> = { args };
if (options?.onComplete) {
formatted.onComplete = await createFunctionHandle(options.onComplete);
}
if (options?.context !== undefined) {
formatted.context = options.context;
}
if (options?.startAsync !== undefined) {
formatted.startAsync = options.startAsync;
}
return (await ctx.runMutation(
workflow as any,
formatted as any,
)) as unknown as WorkflowId;
}
/**
* Get a workflow's status.
*
* @param ctx - The Convex context.
* @param component - The workflow component.
* @param workflowId - The workflow ID.
* @returns The workflow status.
*/
export async function getStatus(
ctx: RunQueryCtx,
component: WorkflowComponent,
workflowId: WorkflowId,
): Promise<WorkflowStatus> {
const { workflow, inProgress } = await ctx.runQuery(
component.workflow.getStatus,
{ workflowId },
);
const running = inProgress.map((entry) => entry.step as IdsToStrings<Step>);
switch (workflow.runResult?.kind) {
case undefined:
return { type: "inProgress", running };
case "canceled":
return { type: "canceled" };
case "failed":
return { type: "failed", error: workflow.runResult.error };
case "success":
return { type: "completed", result: workflow.runResult.returnValue };
}
}
/**
* Cancel a running workflow.
*
* @param ctx - The Convex context.
* @param component - The workflow component.
* @param workflowId - The workflow ID.
*/
export async function cancel(
ctx: RunMutationCtx,
component: WorkflowComponent,
workflowId: WorkflowId,
): Promise<void> {
await ctx.runMutation(component.workflow.cancel, { workflowId });
}
/**
* Restart a previously-failed workflow.
*
* By default it will retry the handler using the existing history of steps.
* To restart from the beginning, pass `{from: 0}`.
* To restart from a named step or event: `{from: "myName"}`.
* To restart from a function call: `{from: internal.foo.bar}`.
*
* If the function or name were called multiple times, it will restart from
* the last invocation.
*
* @param ctx - The Convex context.
* @param component - The workflow component.
* @param workflowId - The workflow ID.
* @param options - Options for the retry.
* @param options.from - The step to retry from. Can be a step number,
* a step name, or the function / workflow `internal.foo.bar`.
* Steps from this point onwards will be deleted before restarting.
* If not provided, the handler will be re-executed using the existing
* history of steps.
* @param options.startAsync - If true, the workflow will be enqueued
* via the workpool instead of running immediately.
*/
export async function restart(
ctx: RunMutationCtx,
component: WorkflowComponent,
workflowId: WorkflowId,
options?: {
from?: number | string | FunctionReference<any, any>;
startAsync?: boolean;
},
): Promise<void> {
let from: number | string | undefined;
if (options?.from !== undefined) {
if (typeof options.from === "number" || typeof options.from === "string") {
from = options.from;
} else {
from = safeFunctionName(options.from);
}
}
await ctx.runMutation(component.workflow.restart, {
workflowId,
from,
startAsync: options?.startAsync,
});
}
/**
* Send an event to a workflow.
*
* @param ctx - From a mutation, action or workflow step.
* @param component - The workflow component.
* @param args - Either send an event by its ID, or by name and workflow ID.
* If you have a validator, you must provide a value.
* If you provide an error string, awaiting the event will throw an error.
*/
export async function sendEvent<T = null, Name extends string = string>(
ctx: RunMutationCtx,
component: WorkflowComponent,
args: (
| { workflowId: WorkflowId; name: Name; id?: EventId<Name> }
| { workflowId?: undefined; name?: Name; id: EventId<Name> }
) &
(
| { validator?: undefined; value?: T }
| { validator: Validator<T, any, any>; value: T }
| { error: string; value?: undefined }
),
): Promise<EventId<Name>> {
const result: RunResult =
"error" in args
? { kind: "failed", error: args.error }
: {
kind: "success" as const,
returnValue: args.validator
? parse(args.validator, args.value)
: "value" in args
? args.value
: null,
};
return (await ctx.runMutation(component.event.send, {
eventId: args.id,
result,
name: args.name,
workflowId: args.workflowId,
})) as EventId<Name>;
}
/**
* Create an event ahead of time, enabling awaiting a specific event by ID.
* @param ctx - From an action, mutation or workflow step.
* @param component - The workflow component.
* @param args - The name of the event and what workflow it belongs to.
* @returns The event ID, which can be used to send the event or await it.
*/
export async function createEvent<Name extends string>(
ctx: RunMutationCtx,
component: WorkflowComponent,
args: { name: Name; workflowId: WorkflowId },
): Promise<EventId<Name>> {
return (await ctx.runMutation(component.event.create, {
name: args.name,
workflowId: args.workflowId,
})) as EventId<Name>;
}
/**
* List workflows, including their name, args, return value etc.
*
* @param ctx - The Convex context from a query, mutation, or action.
* @param component - The workflow component.
* @param opts - How many workflows to fetch and in what order.
* e.g. `{ order: "desc", paginationOpts: { cursor: null, numItems: 10 } }`
* will get the last 10 workflows in descending order.
* Defaults to 100 workflows in ascending order.
* @returns The pagination result with per-workflow data.
*/
export async function list(
ctx: RunQueryCtx,
component: WorkflowComponent,
opts?: {
order?: "asc" | "desc";
paginationOpts?: PaginationOptions;
},
): Promise<PaginationResult<PublicWorkflow>> {
const workflows = await ctx.runQuery(component.workflow.list, {
order: opts?.order ?? "asc",
paginationOpts: opts?.paginationOpts ?? {
cursor: null,
numItems: 100,
},
});
return workflows as PaginationResult<PublicWorkflow>;
}
/**
* List workflows matching a specific name, including their args, return value etc.
*
* @param ctx - The Convex context from a query, mutation, or action.
* @param component - The workflow component.
* @param name - The workflow name to filter by.
* @param opts - How many workflows to fetch and in what order.
* e.g. `{ order: "desc", paginationOpts: { cursor: null, numItems: 10 } }`
* will get the last 10 workflows in descending order.
* Defaults to 100 workflows in ascending order.
* @returns The pagination result with per-workflow data.
*/
export async function listByName(
ctx: RunQueryCtx,
component: WorkflowComponent,
name: string,
opts?: {
order?: "asc" | "desc";
paginationOpts?: PaginationOptions;
},
): Promise<PaginationResult<PublicWorkflow>> {
const workflows = await ctx.runQuery(component.workflow.listByName, {
name,
order: opts?.order ?? "asc",
paginationOpts: opts?.paginationOpts ?? {
cursor: null,
numItems: 100,
},
});
return workflows as PaginationResult<PublicWorkflow>;
}
/**
* List the steps in a workflow, including their name, args, return value etc.
*
* @param ctx - The Convex context from a query, mutation, or action.
* @param component - The workflow component.
* @param workflowId - The workflow ID.
* @param opts - How many steps to fetch and in what order.
* e.g. `{ order: "desc", paginationOpts: { cursor: null, numItems: 10 } }`
* will get the last 10 steps in descending order.
* Defaults to 100 steps in ascending order.
* @returns The pagination result with per-step data.
*/
export async function listSteps(
ctx: RunQueryCtx,
component: WorkflowComponent,
workflowId: WorkflowId,
opts?: {
order?: "asc" | "desc";
paginationOpts?: PaginationOptions;
},
): Promise<PaginationResult<WorkflowStep>> {
const steps = await ctx.runQuery(component.workflow.listSteps, {
workflowId,
order: opts?.order ?? "asc",
paginationOpts: opts?.paginationOpts ?? {
cursor: null,
numItems: 100,
},
});
return steps as PaginationResult<WorkflowStep>;
}
/**
* Clean up a completed workflow's storage.
*
* @param ctx - The Convex context.
* @param component - The workflow component.
* @param workflowId - The workflow ID.
* @returns - Whether the workflow's state was cleaned up.
*/
export async function cleanup(
ctx: RunMutationCtx,
component: WorkflowComponent,
workflowId: WorkflowId,
): Promise<boolean> {
return await ctx.runMutation(component.workflow.cleanup, {
workflowId,
});
}
export class WorkflowManager {
constructor(
public component: WorkflowComponent,
public options?: {
workpoolOptions: WorkpoolOptions;
},
) {}
/**
* Define a new workflow.
*
* Start the workflow from a mutation or action:
* ```ts
* const workflowId = await start(ctx, internal.myFile.myWorkflow, { ...myArgs });
* ```
* Or call it directly:
* ```ts
* const workflowId = await ctx.runMutation(internal.myFile.myWorkflow, { args: { ...myArgs } });
* ```
*
* @param workflow - The workflow definition.
* @returns The workflow mutation.
*/
define<
ArgsValidator extends PropertyValidators,
ReturnsValidator extends Validator<unknown, "required", string> | void,
>(
workflow: WorkflowDefinition<ArgsValidator, ReturnsValidator> & {
handler: WorkflowHandler<ArgsValidator, ReturnsValidator>;
},
): RegisteredMutation<"internal", WorkflowArgs<ArgsValidator>, WorkflowId>;
define<
ArgsValidator extends PropertyValidators,
ReturnsValidator extends Validator<unknown, "required", string> | void,
>(
workflow: WorkflowDefinition<ArgsValidator, ReturnsValidator>,
): {
/**
* Define the workflow handler function.
* Returns a registered mutation to export from your Convex module.
*/
handler(
fn: (
step: WorkflowCtx,
args: ObjectType<ArgsValidator>,
) => Promise<ReturnValueForOptionalValidator<ReturnsValidator>>,
): RegisteredMutation<"internal", WorkflowArgs<ArgsValidator>, WorkflowId>;
};
define<
ArgsValidator extends PropertyValidators,
ReturnsValidator extends Validator<unknown, "required", string> | void,
>(
workflow: WorkflowDefinition<ArgsValidator, ReturnsValidator> & {
handler?: WorkflowHandler<ArgsValidator, ReturnsValidator>;
},
): unknown {
if (workflow.handler) {
return workflowMutation(
this.component,
workflow as WorkflowDefinition<ArgsValidator, ReturnsValidator> & {
handler: WorkflowHandler<ArgsValidator, ReturnsValidator>;
},
this.options?.workpoolOptions,
);
}
// Note: we're passing through more options than defineWorkflow claims
// to support, in order to get the maxParallelism / etc. in there.
// Direct users of defineWorkflow should instead configure those values
// via configuring the component directly.
return defineWorkflow<ArgsValidator, ReturnsValidator>(this.component, {
...workflow,
workpoolOptions: {
...this.options?.workpoolOptions,
...workflow.workpoolOptions,
},
});
}
/**
* Start a workflow.
*
* Alternative to `start` (`import { start } from "@convex-dev/workflow"`).
*
* This is slightly more efficient than calling `start` when passing
* `startAsync: true`, and slightly less efficient in the default case.
*
* @param ctx - The Convex context.
* @param workflow - The workflow to start (e.g. `internal.index.exampleWorkflow`).
* @param args - The workflow arguments.
* @returns The workflow ID.
*/
async start<
Context = unknown,
F extends FunctionReference<"mutation", "internal"> = FunctionReference<
"mutation",
"internal"
>,
>(
ctx: RunMutationCtx,
workflow: F,
args: FunctionArgs<F>["args"],
options?: CallbackOptions<Context> & {
/**
* By default, during creation the workflow will be initiated immediately.
* The benefit is that you catch errors earlier (e.g. passing a bad
* workflow reference or catch arg validation).
*
* With `startAsync` set to true, the workflow will be created but will
* start asynchronously via the internal workpool.
* You can use this to queue up a lot of work,
* or make `start` return faster (you still get a workflowId back).
* @default false
*/
startAsync?: boolean;
},
): Promise<WorkflowId> {
if (!options?.startAsync) {
return start(ctx, workflow, args, options);
}
const handle = await createFunctionHandle(workflow);
const onComplete = options?.onComplete
? {
fnHandle: await createFunctionHandle(options.onComplete),
context: options.context,
}
: undefined;
const workflowId = await ctx.runMutation(this.component.workflow.create, {
workflowName: safeFunctionName(workflow),
workflowHandle: handle,
workflowArgs: args,
maxParallelism: this.options?.workpoolOptions?.maxParallelism,
onComplete,
startAsync: true,
});
return workflowId as unknown as WorkflowId;
}
/**
* Get a workflow's status.
*
* @param ctx - The Convex context.
* @param workflowId - The workflow ID.
* @returns The workflow status.
*/
async status(
ctx: RunQueryCtx,
workflowId: WorkflowId,
): Promise<WorkflowStatus> {
return getStatus(ctx, this.component, workflowId);
}
/**
* Restart a previously-failed workflow.
*
* By default it will retry the handler using the existing history of steps.
* To restart from the beginning, pass `{from: 0}`.
* To restart from a named step or event: `{from: "myName"}`.
* To restart from a function call: `{from: internal.foo.bar}`.
*
* If the function or name were called multiple times, it will restart from
* the last invocation.
*
* @param ctx - The Convex context.
* @param workflowId - The workflow ID.
* @param options - Options for the retry.
* @param options.from - The step to retry from. Can be a step number,
* a step name, or the function / workflow `internal.foo.bar`.
* Steps from this point onwards will be deleted before restarting.
* If not provided, the handler will be re-executed using the existing
* history of steps.
* @param options.startAsync - If true, the workflow will be enqueued
* via the workpool instead of running immediately.
*/
async restart(
ctx: RunMutationCtx,
workflowId: WorkflowId,
options?: {
from?: number | string | FunctionReference<any, any>;
startAsync?: boolean;
},
): Promise<void> {
return restart(ctx, this.component, workflowId, options);
}
/**
* Cancel a running workflow.
*
* @param ctx - The Convex context.
* @param workflowId - The workflow ID.
*/
async cancel(ctx: RunMutationCtx, workflowId: WorkflowId) {
return cancel(ctx, this.component, workflowId);
}
/**
* List workflows, including their name, args, return value etc.
*
* @param ctx - The Convex context from a query, mutation, or action.
* @param opts - How many workflows to fetch and in what order.
* e.g. `{ order: "desc", paginationOpts: { cursor: null, numItems: 10 } }`
* will get the last 10 workflows in descending order.
* Defaults to 100 workflows in ascending order.
* @returns The pagination result with per-workflow data.
*/
async list(
ctx: RunQueryCtx,
opts?: {
order?: "asc" | "desc";
paginationOpts?: PaginationOptions;
},
): Promise<PaginationResult<PublicWorkflow>> {
return list(ctx, this.component, opts);
}
/**
* List workflows matching a specific name, including their args, return value etc.
*
* @param ctx - The Convex context from a query, mutation, or action.
* @param name - The workflow name to filter by.
* @param opts - How many workflows to fetch and in what order.
* e.g. `{ order: "desc", paginationOpts: { cursor: null, numItems: 10 } }`
* will get the last 10 workflows in descending order.
* Defaults to 100 workflows in ascending order.
* @returns The pagination result with per-workflow data.
*/
async listByName(
ctx: RunQueryCtx,
name: string,
opts?: {
order?: "asc" | "desc";
paginationOpts?: PaginationOptions;
},
): Promise<PaginationResult<PublicWorkflow>> {
return listByName(ctx, this.component, name, opts);
}
/**
* List the steps in a workflow, including their name, args, return value etc.
*
* @param ctx - The Convex context from a query, mutation, or action.
* @param workflowId - The workflow ID.
* @param opts - How many steps to fetch and in what order.
* e.g. `{ order: "desc", paginationOpts: { cursor: null, numItems: 10 } }`
* will get the last 10 steps in descending order.
* Defaults to 100 steps in ascending order.
* @returns The pagination result with per-step data.
*/
async listSteps(
ctx: RunQueryCtx,
workflowId: WorkflowId,
opts?: {
order?: "asc" | "desc";
paginationOpts?: PaginationOptions;
},
): Promise<PaginationResult<WorkflowStep>> {
return listSteps(ctx, this.component, workflowId, opts);
}
/**
* Clean up a completed workflow's storage.
*
* @param ctx - The Convex context.
* @param workflowId - The workflow ID.
* @returns - Whether the workflow's state was cleaned up.
*/
async cleanup(ctx: RunMutationCtx, workflowId: WorkflowId): Promise<boolean> {
return cleanup(ctx, this.component, workflowId);
}
/**
* Send an event to a workflow.
*
* @param ctx - From a mutation, action or workflow step.
* @param args - Either send an event by its ID, or by name and workflow ID.
* If you have a validator, you must provide a value.
* If you provide an error string, awaiting the event will throw an error.
*/
async sendEvent<T = null, Name extends string = string>(
ctx: RunMutationCtx,
args: (
| { workflowId: WorkflowId; name: Name; id?: EventId<Name> }
| { workflowId?: undefined; name?: Name; id: EventId<Name> }
) &
(
| { validator?: undefined; value?: T }
| { validator: Validator<T, any, any>; value: T }
| { error: string; value?: undefined }
),
): Promise<EventId<Name>> {
return sendEvent<T, Name>(ctx, this.component, args);
}
/**
* Create an event ahead of time, enabling awaiting a specific event by ID.
* @param ctx - From an action, mutation or workflow step.
* @param args - The name of the event and what workflow it belongs to.
* @returns The event ID, which can be used to send the event or await it.
*/
async createEvent<Name extends string>(
ctx: RunMutationCtx,
args: { name: Name; workflowId: WorkflowId },
): Promise<EventId<Name>> {
return createEvent(ctx, this.component, args);
}
}
/**
* Define an event specification: a name and a validator.
* This helps share definitions between workflow.sendEvent and ctx.awaitEvent.
* e.g.
* ```ts
* const approvalEvent = defineEvent({
* name: "approval",
* validator: v.object({ approved: v.boolean() }),
* });
* ```
* Then you can await it in a workflow:
* ```ts
* const result = await ctx.awaitEvent(approvalEvent);
* ```
* And send from somewhere else:
* ```ts
* await workflow.sendEvent(ctx, {
* ...approvalEvent,
* workflowId,
* value: { approved: true },
* });
* ```
*/
export function defineEvent<
Name extends string,
V extends Validator<unknown, "required", string>,
>(spec: { name: Name; validator: V }) {
return spec;
}
type RunQueryCtx = {
runQuery: GenericQueryCtx<GenericDataModel>["runQuery"];
};
type RunMutationCtx = {
runMutation: GenericMutationCtx<GenericDataModel>["runMutation"];
};