|
| 1 | +import { |
| 2 | + actor, |
| 3 | + setup, |
| 4 | + type WorkflowStepContextOf, |
| 5 | + workflow, |
| 6 | +} from "@rivet-dev/workflows"; |
| 7 | + |
| 8 | +type BatchMessage = { |
| 9 | + payload: number; |
| 10 | +}; |
| 11 | +export const childWorkerActor = actor({ |
| 12 | + actions: { |
| 13 | + process: async (_c, payload: number) => payload * 3, |
| 14 | + }, |
| 15 | +}); |
| 16 | +export const orchestratorActor = workflow({ |
| 17 | + state: { |
| 18 | + lastTotal: 0, |
| 19 | + }, |
| 20 | + run: async (ctx) => { |
| 21 | + await ctx.step("start-children", async (step) => startChildren(step)); |
| 22 | + await ctx.loop("orchestrate-loop", async (loopCtx) => { |
| 23 | + const [message] = await loopCtx.queue.nextBatch("wait-batch", { |
| 24 | + timeout: 30000, |
| 25 | + }); |
| 26 | + if (!message) return; |
| 27 | + const batch = message.body as BatchMessage; |
| 28 | + const results = await loopCtx.join("collect-updates", { |
| 29 | + a: { |
| 30 | + run: async (joinCtx) => |
| 31 | + await joinCtx.step("run-child-a", async (step) => |
| 32 | + runChildWorker(step, "child-a", batch.payload), |
| 33 | + ), |
| 34 | + }, |
| 35 | + b: { |
| 36 | + run: async (joinCtx) => |
| 37 | + await joinCtx.step("run-child-b", async (step) => |
| 38 | + runChildWorker(step, "child-b", batch.payload), |
| 39 | + ), |
| 40 | + }, |
| 41 | + c: { |
| 42 | + run: async (joinCtx) => |
| 43 | + await joinCtx.step("run-child-c", async (step) => |
| 44 | + runChildWorker(step, "child-c", batch.payload), |
| 45 | + ), |
| 46 | + }, |
| 47 | + }); |
| 48 | + await loopCtx.step("reconcile", async (step) => { |
| 49 | + step.state.lastTotal = results.a + results.b + results.c; |
| 50 | + }); |
| 51 | + }); |
| 52 | + }, |
| 53 | + actions: { |
| 54 | + getState: (c) => c.state, |
| 55 | + }, |
| 56 | +}); |
| 57 | +async function startChildren( |
| 58 | + ctx: WorkflowStepContextOf<typeof orchestratorActor>, |
| 59 | +): Promise<void> { |
| 60 | + const client = ctx.client(); |
| 61 | + await client.childWorkerActor.getOrCreate(["child-a"]).process(0); |
| 62 | + await client.childWorkerActor.getOrCreate(["child-b"]).process(0); |
| 63 | + await client.childWorkerActor.getOrCreate(["child-c"]).process(0); |
| 64 | +} |
| 65 | +async function runChildWorker( |
| 66 | + ctx: WorkflowStepContextOf<typeof orchestratorActor>, |
| 67 | + workerId: "child-a" | "child-b" | "child-c", |
| 68 | + payload: number, |
| 69 | +): Promise<number> { |
| 70 | + const client = ctx.client(); |
| 71 | + return await client.childWorkerActor.getOrCreate([workerId]).process(payload); |
| 72 | +} |
| 73 | +export const registry = setup({ use: { orchestratorActor, childWorkerActor } }); |
0 commit comments