Skip to content

Commit 8f45554

Browse files
authored
[miniflare] Add workflow introspection for exported Workflows (#17016)
1 parent 629f135 commit 8f45554

6 files changed

Lines changed: 196 additions & 2 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
"miniflare": minor
3+
---
4+
5+
Add `unsafeIntrospectWorkflow()` and `unsafeIntrospectWorkflowInstance()` for exported Workflows
6+
7+
They find a Workflow by its Worker's name and its class name, so code running in Node.js can introspect a Workflow on `ctx.exports` that has no `env` binding:
8+
9+
```ts
10+
const introspector = await mf.unsafeIntrospectWorkflow(
11+
"my-worker",
12+
"MyWorkflow"
13+
);
14+
```
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"miniflare": patch
3+
---
4+
5+
Name only the Workflow in the error for a second introspection session
6+
7+
For a Workflow declared in `exports`, the error said the session was "for binding" the Workflow's class. It now reads `Workflow "my-workflow" already has an active introspection session.`

‎packages/miniflare/src/index.ts‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ import zlib from "node:zlib";
1313
import { checkMacOSVersion } from "@cloudflare/cli-shared-helpers";
1414
import { removeDir, removeDirSync } from "@cloudflare/workers-utils/fs-helpers";
1515
import { formatZodError } from "@cloudflare/workers-utils/zod-format";
16+
import {
17+
WorkflowInstanceIntrospectorHandle,
18+
WorkflowIntrospectorHandle,
19+
} from "@cloudflare/workflows-shared/src/introspection";
1620
import { $ as colors$, bold, dim, green, yellow } from "kleur/colors";
1721
import stoppable from "stoppable";
1822
import { getGlobalDispatcher, Pool } from "undici";
@@ -51,6 +55,7 @@ import {
5155
getPersistPath,
5256
getStorageScope,
5357
getTriggersOfType,
58+
getWorkflowBindingServiceName,
5459
getWorkflowExporters,
5560
HELLO_WORLD_PLUGIN_NAME,
5661
HOST_CAPNP_CONNECT,
@@ -203,6 +208,11 @@ import type {
203208
R2Bucket,
204209
StreamBinding,
205210
} from "@cloudflare/workers-types/experimental";
211+
import type {
212+
WorkflowBinding,
213+
WorkflowInstanceIntrospector,
214+
WorkflowIntrospector,
215+
} from "@cloudflare/workflows-shared/src/types";
206216
import type { Process } from "@puppeteer/browsers";
207217
import type { Abortable } from "node:events";
208218
import type { Duplex, Transform, Writable } from "node:stream";
@@ -643,6 +653,21 @@ function getProxyBindingName(plugin: string, worker: string, binding: string) {
643653
binding,
644654
].join(":");
645655
}
656+
/**
657+
* @param worker The name of the Worker that exports the Workflow
658+
* @param className The Workflow's class name
659+
* @returns The name of the `ProxyServer` binding to the Workflow
660+
*/
661+
function getExportedWorkflowProxyBindingName(
662+
worker: string,
663+
className: string
664+
) {
665+
return getProxyBindingName(
666+
`${WORKFLOWS_PLUGIN_NAME}-export`,
667+
worker,
668+
className
669+
);
670+
}
646671
// Get whether a binding will need a proxy to be supported in Node (i.e. is
647672
// the implementation of this binding in `workerd`?). If this returns `false`,
648673
// there's no need to bind the binding to the `ProxyServer`.
@@ -2248,6 +2273,28 @@ export class Miniflare {
22482273
}
22492274
}
22502275

2276+
// An exported Workflow may have no `env` binding to proxy
2277+
for (const [className, workflow] of getExportsOfType(
2278+
workerOpts.config,
2279+
"workflow"
2280+
)) {
2281+
proxyBindings.push({
2282+
name: getExportedWorkflowProxyBindingName(workerName, className),
2283+
wrapped: {
2284+
moduleName: `${WORKFLOWS_PLUGIN_NAME}:local-wrapped-binding`,
2285+
innerBindings: [
2286+
{
2287+
name: "binding",
2288+
service: {
2289+
name: getWorkflowBindingServiceName(workflow.name),
2290+
entrypoint: "WorkflowBinding",
2291+
},
2292+
},
2293+
],
2294+
},
2295+
});
2296+
}
2297+
22512298
// Collect all services required by this worker
22522299
const unsafeEphemeralDurableObjects =
22532300
workerOpts.dev?.unsafeEphemeralDurableObjects ?? false;
@@ -3724,6 +3771,66 @@ export class Miniflare {
37243771
throw error;
37253772
}
37263773
}
3774+
/**
3775+
* Starts introspecting a Workflow that a Worker exports. The introspector
3776+
* covers every instance created while it's active, whether through an `env`
3777+
* binding or `ctx.exports`.
3778+
*
3779+
* @param workerName The name of the Worker that exports the Workflow
3780+
* @param className The Workflow's class name
3781+
* @returns The Workflow's introspector
3782+
*/
3783+
async unsafeIntrospectWorkflow(
3784+
workerName: string,
3785+
className: string
3786+
): Promise<WorkflowIntrospector> {
3787+
const introspector = new WorkflowIntrospectorHandle(
3788+
await this.#getExportedWorkflow(workerName, className)
3789+
);
3790+
await introspector.start();
3791+
return introspector;
3792+
}
3793+
/**
3794+
* Introspects an instance of a Workflow that a Worker exports.
3795+
*
3796+
* @param workerName The name of the Worker that exports the Workflow
3797+
* @param className The Workflow's class name
3798+
* @param instanceId The instance's ID
3799+
* @returns The instance's introspector
3800+
*/
3801+
async unsafeIntrospectWorkflowInstance(
3802+
workerName: string,
3803+
className: string,
3804+
instanceId: string
3805+
): Promise<WorkflowInstanceIntrospector> {
3806+
return new WorkflowInstanceIntrospectorHandle(
3807+
await this.#getExportedWorkflow(workerName, className),
3808+
instanceId
3809+
);
3810+
}
3811+
async #getExportedWorkflow(
3812+
workerName: string,
3813+
className: string
3814+
): Promise<WorkflowBinding> {
3815+
const proxyClient = await this._getProxyClient();
3816+
const workerOpts =
3817+
this.#workerOpts[this.#findAndAssertWorkerIndex(workerName)];
3818+
if (
3819+
!getExportsOfType(workerOpts.config, "workflow").some(
3820+
([exportName]) => exportName === className
3821+
)
3822+
) {
3823+
throw new TypeError(
3824+
`No Workflow class named ${JSON.stringify(
3825+
className
3826+
)} found in ${JSON.stringify(workerName)} worker.`
3827+
);
3828+
}
3829+
3830+
return proxyClient.env[
3831+
getExportedWorkflowProxyBindingName(workerName, className)
3832+
] as WorkflowBinding;
3833+
}
37273834
getKVNamespace(
37283835
bindingName: string,
37293836
workerName?: string

‎packages/miniflare/test/plugins/workflows/exports.spec.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,72 @@ describe("Workflows on ctx.exports", () => {
553553
}
554554
);
555555

556+
test("introspects the instances of an exported Workflow from Node.js", async ({
557+
expect,
558+
}) => {
559+
const mf = new Miniflare({
560+
workers: [worker("exporter", { exports: MY_WORKFLOW_EXPORT })],
561+
});
562+
useDispose(mf);
563+
const fetch: Fetch = (url) => mf.dispatchFetch(url);
564+
565+
const introspector = await mf.unsafeIntrospectWorkflow(
566+
"exporter",
567+
"MyWorkflow"
568+
);
569+
await expect(
570+
mf.unsafeIntrospectWorkflow("exporter", "MyWorkflow")
571+
).rejects.toThrow(
572+
'Workflow "my-workflow" already has an active introspection session.'
573+
);
574+
await introspector.modifyAll(async (modifier) => {
575+
await modifier.mockStepResult({ name: "step 0" }, "mocked");
576+
});
577+
await fetchJson(fetch, "/create?id=instance");
578+
const [instance] = await introspector.get();
579+
await instance?.waitForStatus("complete");
580+
expect(await instance?.getOutput()).toEqual(["mocked"]);
581+
await introspector.dispose();
582+
});
583+
584+
test("introspects an instance of an exported Workflow from Node.js", async ({
585+
expect,
586+
}) => {
587+
const mf = new Miniflare({
588+
workers: [worker("exporter", { exports: MY_WORKFLOW_EXPORT })],
589+
});
590+
useDispose(mf);
591+
const fetch: Fetch = (url) => mf.dispatchFetch(url);
592+
593+
const instance = await mf.unsafeIntrospectWorkflowInstance(
594+
"exporter",
595+
"MyWorkflow",
596+
"instance"
597+
);
598+
await instance.modify(async (modifier) => {
599+
await modifier.mockStepResult({ name: "step 0" }, "mocked");
600+
});
601+
await fetchJson(fetch, "/create?id=instance");
602+
await instance.waitForStatus("complete");
603+
expect(await instance.getOutput()).toEqual(["mocked"]);
604+
await instance.dispose();
605+
});
606+
607+
test("rejects introspecting a Workflow the Worker doesn't export", async ({
608+
expect,
609+
}) => {
610+
const mf = new Miniflare({
611+
workers: [worker("exporter", { exports: MY_WORKFLOW_EXPORT })],
612+
});
613+
useDispose(mf);
614+
615+
await expect(
616+
mf.unsafeIntrospectWorkflow("exporter", "OtherWorkflow")
617+
).rejects.toThrow(
618+
'No Workflow class named "OtherWorkflow" found in "exporter" worker.'
619+
);
620+
});
621+
556622
test("rejects two Workers exporting the same Workflow", async ({
557623
expect,
558624
}) => {

‎packages/workflows-shared/src/binding.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -874,7 +874,7 @@ export class WorkflowBinding extends WorkerEntrypoint<Env> {
874874
public async unsafeStartIntrospection(): Promise<string> {
875875
if (workflowIntrospectionSessions.has(this.env.WORKFLOW_NAME)) {
876876
throw new Error(
877-
`Workflow ${JSON.stringify(this.env.WORKFLOW_NAME)} already has an active introspection session for binding ${JSON.stringify(this.env.BINDING_NAME)}.`
877+
`Workflow ${JSON.stringify(this.env.WORKFLOW_NAME)} already has an active introspection session.`
878878
);
879879
}
880880

‎packages/wrangler/e2e/createTestHarness.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -888,7 +888,7 @@ describe("createTestHarness", () => {
888888
const workflow = await worker.introspectWorkflow("MODERATOR");
889889
onTestFinished(workflow.dispose);
890890
await expect(worker.introspectWorkflow("MODERATOR")).rejects.toThrow(
891-
`Workflow "moderator-workflow" already has an active introspection session for binding "MODERATOR".`
891+
`Workflow "moderator-workflow" already has an active introspection session.`
892892
);
893893
await workflow.modifyAll(async (modifier) => {
894894
await modifier.disableSleeps();

0 commit comments

Comments
 (0)