@velajs/cloudflare 1.31.0 → 1.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +62 -0
- package/README.md +154 -10
- package/dist/bindings.js +17 -1
- package/dist/bindings.js.map +1 -1
- package/dist/{cloudflare-factory-eGiet0mg.d.ts → cloudflare-application-CXDy9C1R.d.ts} +9 -98
- package/dist/cloudflare-application.js +8 -0
- package/dist/cloudflare-application.js.map +1 -1
- package/dist/cloudflare-factory-CuFNUJJD.d.ts +241 -0
- package/dist/cloudflare-factory.js +153 -20
- package/dist/cloudflare-factory.js.map +1 -1
- package/dist/durable-object/boot.js +76 -0
- package/dist/durable-object/boot.js.map +1 -0
- package/dist/durable-object/host-dispatch.js +134 -0
- package/dist/durable-object/host-dispatch.js.map +1 -0
- package/dist/durable-object/host-methods.js +47 -0
- package/dist/durable-object/host-methods.js.map +1 -0
- package/dist/durable-object/tokens.js +17 -0
- package/dist/durable-object/tokens.js.map +1 -0
- package/dist/durable-object/vela-durable-object.js +121 -0
- package/dist/durable-object/vela-durable-object.js.map +1 -0
- package/dist/durable-objects.d.ts +131 -9
- package/dist/durable-objects.js +3 -1
- package/dist/email/email-dispatch.js +65 -0
- package/dist/email/email-dispatch.js.map +1 -0
- package/dist/email/on-email.js +57 -0
- package/dist/email/on-email.js.map +1 -0
- package/dist/email.d.ts +51 -0
- package/dist/email.js +3 -0
- package/dist/entrypoint/vela-entrypoint.js +160 -0
- package/dist/entrypoint/vela-entrypoint.js.map +1 -0
- package/dist/entrypoints.d.ts +93 -0
- package/dist/entrypoints.js +2 -0
- package/dist/host/host-invoker.js +276 -0
- package/dist/host/host-invoker.js.map +1 -0
- package/dist/host/host-members.js +73 -0
- package/dist/host/host-members.js.map +1 -0
- package/dist/host-members-DECj_4yz.d.ts +13 -0
- package/dist/index.d.ts +72 -11
- package/dist/index.js +4 -3
- package/dist/root-module.js +19 -0
- package/dist/root-module.js.map +1 -0
- package/dist/rpc/entrypoint-error.js +145 -0
- package/dist/rpc/entrypoint-error.js.map +1 -0
- package/dist/tail/on-tail.js +46 -0
- package/dist/tail/on-tail.js.map +1 -0
- package/dist/tail/tail-dispatch.js +67 -0
- package/dist/tail/tail-dispatch.js.map +1 -0
- package/dist/tail.d.ts +39 -0
- package/dist/tail.js +2 -0
- package/dist/testing.d.ts +55 -3
- package/dist/testing.js +78 -1
- package/dist/testing.js.map +1 -1
- package/dist/websocket/do-bootstrap.js +40 -37
- package/dist/websocket/do-bootstrap.js.map +1 -1
- package/dist/websocket/websocket.durable-object.js +37 -8
- package/dist/websocket/websocket.durable-object.js.map +1 -1
- package/dist/worker-events.js +49 -0
- package/dist/worker-events.js.map +1 -0
- package/dist/workflow/vela-workflow.js +104 -0
- package/dist/workflow/vela-workflow.js.map +1 -0
- package/dist/workflows.d.ts +82 -0
- package/dist/workflows.js +2 -0
- package/package.json +23 -7
- package/dist/root-module-C23bUwt_.d.ts +0 -11
|
@@ -1,11 +1,9 @@
|
|
|
1
|
-
import { registerCloudflarePlatform } from "../platform.js";
|
|
2
1
|
import { gatewayRoomObject } from "./worker-transport.js";
|
|
3
2
|
import { CfWsClient } from "./cf-ws-client.js";
|
|
4
3
|
import { durableObjectLivePlatform, initDoLive } from "./do-live.js";
|
|
5
4
|
import { CfRoomRegistry } from "./cf-room-registry.js";
|
|
6
|
-
import {
|
|
5
|
+
import { createDurableObjectContext } from "../durable-object/boot.js";
|
|
7
6
|
import { WsDispatcher, WsServerImpl, local, readWsEntrypointMeta } from "@velajs/vela/websocket";
|
|
8
|
-
import { bootstrap } from "@velajs/vela/internal";
|
|
9
7
|
//#region src/websocket/do-bootstrap.ts
|
|
10
8
|
/** Whether a Durable Object id names this object. */
|
|
11
9
|
function isThisObject(id, ctx) {
|
|
@@ -24,52 +22,57 @@ async function deliverFromDurableObject(ctx, env, registry, { gatewayPath, bindi
|
|
|
24
22
|
else await target.call("broadcast", command);
|
|
25
23
|
}
|
|
26
24
|
/**
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
25
|
+
* The application context of a WebSocket Durable Object, booted as every
|
|
26
|
+
* Vela Durable Object is (`VelaFactory.createApplicationContext`, without the
|
|
27
|
+
* HTTP routes it never serves): its `env` is seeded as the global ENV before
|
|
28
|
+
* providers construct, next to this object's platform. `WebSocketModule`
|
|
29
|
+
* builds its server over this object's sockets, `Gateways` pushes to this
|
|
30
|
+
* object's room locally and forwards other rooms to their objects, and
|
|
31
|
+
* `LiveModule` delivers locally with a SQLite cursor log when the class is
|
|
32
|
+
* SQLite-backed. `onModuleInit`/`onApplicationBootstrap` run, so
|
|
33
|
+
* `WsDispatcher` discovers the gateways.
|
|
35
34
|
*/
|
|
36
35
|
async function buildDoRuntime(rootModule, ctx, options) {
|
|
37
36
|
const registry = new CfRoomRegistry(ctx);
|
|
38
37
|
const driver = local();
|
|
39
38
|
driver.bind(registry);
|
|
40
39
|
const server = new WsServerImpl(driver);
|
|
41
|
-
const
|
|
42
|
-
|
|
40
|
+
const context = await createDurableObjectContext(rootModule, {
|
|
41
|
+
env: options.env,
|
|
42
|
+
adapters: options.adapters,
|
|
43
|
+
state: options.state,
|
|
44
|
+
platform: () => ({
|
|
43
45
|
websocket: {
|
|
44
46
|
createServer: () => server,
|
|
45
47
|
deliver: (delivery) => deliverFromDurableObject(ctx, options.env, registry, delivery)
|
|
46
48
|
},
|
|
47
49
|
live: durableObjectLivePlatform(ctx)
|
|
48
|
-
})
|
|
49
|
-
} });
|
|
50
|
-
if (!container.has(WsDispatcher)) throw new Error("[vela] A WebSocket Durable Object serves the gateways of WebSocketModule: import WebSocketModule.forRoot() from @velajs/vela/websocket in the application it is built from.");
|
|
51
|
-
const app = new VelaApplication(container, routeManager);
|
|
52
|
-
app.setInstances(await loader.resolveAllInstances());
|
|
53
|
-
await app.callOnModuleInit();
|
|
54
|
-
await app.callOnApplicationBootstrap();
|
|
55
|
-
const wsEntrypoints = app.entrypoints.ofKind("websocket", readWsEntrypointMeta);
|
|
56
|
-
const dispatcher = wsEntrypoints[0]?.meta.dispatcher ?? app.get(WsDispatcher);
|
|
57
|
-
registry.setSendPolicyResolver((path) => wsEntrypoints.find((entry) => entry.meta.path === path)?.meta.options.sendPolicy);
|
|
58
|
-
registry.setFrameLimitResolver((path) => dispatcher.getGatewayMaxFrameBytes(path));
|
|
59
|
-
registry.setDeliveryAuthorizer((client) => {
|
|
60
|
-
const path = client instanceof CfWsClient ? client.path : "";
|
|
61
|
-
return dispatcher.authorizeDelivery(path, client);
|
|
50
|
+
})
|
|
62
51
|
});
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
dispatcher
|
|
67
|
-
registry
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
52
|
+
try {
|
|
53
|
+
if (!context.getContainer().has(WsDispatcher)) throw new Error("[vela] A WebSocket Durable Object serves the gateways of WebSocketModule: import WebSocketModule.forRoot() from @velajs/vela/websocket in the application it is built from.");
|
|
54
|
+
const wsEntrypoints = context.entrypoints.ofKind("websocket", readWsEntrypointMeta);
|
|
55
|
+
const dispatcher = wsEntrypoints[0]?.meta.dispatcher ?? context.get(WsDispatcher);
|
|
56
|
+
registry.setSendPolicyResolver((path) => wsEntrypoints.find((entry) => entry.meta.path === path)?.meta.options.sendPolicy);
|
|
57
|
+
registry.setFrameLimitResolver((path) => dispatcher.getGatewayMaxFrameBytes(path));
|
|
58
|
+
registry.setDeliveryAuthorizer((client) => {
|
|
59
|
+
const path = client instanceof CfWsClient ? client.path : "";
|
|
60
|
+
return dispatcher.authorizeDelivery(path, client);
|
|
61
|
+
});
|
|
62
|
+
const live = initDoLive(context, ctx, registry);
|
|
63
|
+
return {
|
|
64
|
+
container: context.getContainer(),
|
|
65
|
+
dispatcher,
|
|
66
|
+
registry,
|
|
67
|
+
server,
|
|
68
|
+
gatewayPaths: wsEntrypoints.map((ep) => ep.meta.path),
|
|
69
|
+
live,
|
|
70
|
+
close: (signal) => context.close(signal)
|
|
71
|
+
};
|
|
72
|
+
} catch (error) {
|
|
73
|
+
await context.dispose().catch(() => {});
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
73
76
|
}
|
|
74
77
|
//#endregion
|
|
75
78
|
export { buildDoRuntime };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"do-bootstrap.js","names":[],"sources":["../../src/websocket/do-bootstrap.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"do-bootstrap.js","names":[],"sources":["../../src/websocket/do-bootstrap.ts"],"sourcesContent":["import type { DynamicModule, Type, VelaEnv } from '@velajs/vela';\nimport type { Container, RuntimeAdapter } from '@velajs/vela/module-kit';\nimport { local, readWsEntrypointMeta, WsDispatcher, WsServerImpl } from '@velajs/vela/websocket';\nimport type { GatewayDelivery, WsServer } from '@velajs/vela/websocket';\nimport type { LiveEngine } from '@velajs/vela/live';\nimport { createDurableObjectContext } from '../durable-object/boot';\nimport { CfWsClient } from './cf-ws-client';\nimport { CfRoomRegistry } from './cf-room-registry';\nimport { durableObjectLivePlatform, initDoLive } from './do-live';\nimport type { DoStateLike } from './do-state';\nimport { gatewayRoomObject } from './worker-transport';\n\nexport interface DoRuntime {\n /** The Durable Object application's container. */\n container: Container;\n dispatcher: WsDispatcher;\n registry: CfRoomRegistry;\n /** The server gateways inject: it broadcasts to this object's hibernatable sockets. */\n server: WsServer;\n /** Gateway paths from `app.entrypoints.ofKind('websocket')` (discovery order). */\n gatewayPaths: string[];\n /** The live-query engine (undefined when the app doesn't import LiveModule). */\n live?: LiveEngine;\n close(signal?: string): Promise<void>;\n}\n\n/** Whether a Durable Object id names this object. */\nfunction isThisObject(id: unknown, ctx: DoStateLike): boolean {\n const equals: unknown =\n typeof id === 'object' && id !== null ? Reflect.get(id, 'equals') : undefined;\n if (typeof equals === 'function') return Reflect.apply(equals, id, [ctx.id]) === true;\n return String(id) === ctx.id.toString();\n}\n\n/**\n * A `Gateways` push from inside a WebSocket Durable Object: this object's own\n * gateway room is delivered to its sockets; any other room goes to that\n * room's object over its broadcast RPC, as from the Worker.\n */\nasync function deliverFromDurableObject(\n ctx: DoStateLike,\n env: VelaEnv,\n registry: CfRoomRegistry,\n { gatewayPath, binding, room, command }: GatewayDelivery,\n): Promise<void> {\n const target = gatewayRoomObject(env, gatewayPath, binding, room);\n if (isThisObject(target.id, ctx)) await registry.deliverLocal(command);\n else await target.call('broadcast', command);\n}\n\n/** Options of {@link buildDoRuntime}. */\nexport interface DoRuntimeOptions {\n /** The object's environment, seeded as `ENV`. */\n env: VelaEnv;\n /** Runtime adapters of the app definition; their `configureContainer` runs in the object. */\n adapters?: readonly RuntimeAdapter[];\n /** The object's native state, injected as `DO_STATE`, `DO_STORAGE` and `DO_ID`. */\n state?: DurableObjectState;\n}\n\n/**\n * The application context of a WebSocket Durable Object, booted as every\n * Vela Durable Object is (`VelaFactory.createApplicationContext`, without the\n * HTTP routes it never serves): its `env` is seeded as the global ENV before\n * providers construct, next to this object's platform. `WebSocketModule`\n * builds its server over this object's sockets, `Gateways` pushes to this\n * object's room locally and forwards other rooms to their objects, and\n * `LiveModule` delivers locally with a SQLite cursor log when the class is\n * SQLite-backed. `onModuleInit`/`onApplicationBootstrap` run, so\n * `WsDispatcher` discovers the gateways.\n */\nexport async function buildDoRuntime(\n rootModule: Type | DynamicModule,\n ctx: DoStateLike,\n options: DoRuntimeOptions,\n): Promise<DoRuntime> {\n const registry = new CfRoomRegistry(ctx);\n const driver = local();\n driver.bind(registry);\n const server = new WsServerImpl(driver);\n\n const context = await createDurableObjectContext(rootModule, {\n env: options.env,\n adapters: options.adapters,\n state: options.state,\n platform: () => ({\n websocket: {\n createServer: () => server,\n deliver: (delivery) => deliverFromDurableObject(ctx, options.env, registry, delivery),\n },\n live: durableObjectLivePlatform(ctx),\n }),\n });\n try {\n if (!context.getContainer().has(WsDispatcher)) {\n throw new Error(\n '[vela] A WebSocket Durable Object serves the gateways of WebSocketModule: import ' +\n 'WebSocketModule.forRoot() from @velajs/vela/websocket in the application it is built from.',\n );\n }\n\n // The entrypoint registry is the transport contract: one 'websocket' entry\n // per discovered gateway ({ meta: { path, dispatcher } }), built with the\n // context's lifecycle hooks.\n const wsEntrypoints = context.entrypoints.ofKind('websocket', readWsEntrypointMeta);\n const dispatcher = wsEntrypoints[0]?.meta.dispatcher ?? context.get(WsDispatcher);\n registry.setSendPolicyResolver(\n (path) => wsEntrypoints.find((entry) => entry.meta.path === path)?.meta.options.sendPolicy,\n );\n registry.setFrameLimitResolver((path) => dispatcher.getGatewayMaxFrameBytes(path));\n registry.setDeliveryAuthorizer((client) => {\n const path = client instanceof CfWsClient ? client.path : '';\n return dispatcher.authorizeDelivery(path, client);\n });\n\n // Live queries: replay hibernation-persisted subscriptions into the fresh engine.\n const live = initDoLive(context, ctx, registry);\n\n return {\n container: context.getContainer(),\n // Zero gateways still yields a live dispatcher (module imported, nothing\n // decorated) — fall back to resolving it directly.\n dispatcher,\n registry,\n server,\n gatewayPaths: wsEntrypoints.map((ep) => ep.meta.path),\n live,\n close: (signal?: string) => context.close(signal),\n };\n } catch (error) {\n await context.dispose().catch(() => {});\n throw error;\n }\n}\n"],"mappings":";;;;;;;;AA2BA,SAAS,aAAa,IAAa,KAA2B;CAC5D,MAAM,SACJ,OAAO,OAAO,YAAY,OAAO,OAAO,QAAQ,IAAI,IAAI,QAAQ,IAAI,KAAA;CACtE,IAAI,OAAO,WAAW,YAAY,OAAO,QAAQ,MAAM,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC,MAAM;CACjF,OAAO,OAAO,EAAE,MAAM,IAAI,GAAG,SAAS;AACxC;;;;;;AAOA,eAAe,yBACb,KACA,KACA,UACA,EAAE,aAAa,SAAS,MAAM,WACf;CACf,MAAM,SAAS,kBAAkB,KAAK,aAAa,SAAS,IAAI;CAChE,IAAI,aAAa,OAAO,IAAI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YAAY,CAAC,CAAC;EACtC,MAAM;CACR;AACF"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { FORWARDED_UPGRADE_HEADERS } from "./worker-transport.js";
|
|
2
|
+
import { CLOUDFLARE_DURABLE_OBJECT, registerDurableObject } from "../cloudflare-factory.js";
|
|
2
3
|
import { armDoPitr, readDoPitrBookmark } from "./do-pitr.js";
|
|
3
4
|
import { DoWebSocketHost } from "./do-websocket-host.js";
|
|
5
|
+
import { durableObjectDefinition, startDurableObject } from "../durable-object/boot.js";
|
|
4
6
|
import { buildDoRuntime } from "./do-bootstrap.js";
|
|
5
7
|
import { DurableObject } from "cloudflare:workers";
|
|
6
8
|
//#region src/websocket/websocket.durable-object.ts
|
|
@@ -11,13 +13,25 @@ const encoder = new TextEncoder();
|
|
|
11
13
|
function isIdentityField(value) {
|
|
12
14
|
return value !== null && value.length > 0 && encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES;
|
|
13
15
|
}
|
|
16
|
+
/** The RPC methods a WebSocket Durable Object exposes to the Worker and other objects. */
|
|
17
|
+
const WEBSOCKET_RPC_METHODS = [
|
|
18
|
+
"broadcast",
|
|
19
|
+
"invalidate",
|
|
20
|
+
"inspectLive",
|
|
21
|
+
"pitrCurrentBookmark",
|
|
22
|
+
"pitrBookmarkForTime",
|
|
23
|
+
"pitrArmRestore"
|
|
24
|
+
];
|
|
14
25
|
/**
|
|
15
26
|
* Base class for the WebSocket Durable Object. The user exports a named subclass
|
|
16
|
-
* (matching their `wrangler.toml` `class_name`) built from their `AppModule`,
|
|
17
|
-
*
|
|
27
|
+
* (matching their `wrangler.toml` `class_name`) built from their `AppModule`, a
|
|
28
|
+
* `DynamicModule` declared at module scope, or the app from
|
|
29
|
+
* `defineCloudflareApp`, whose runtime adapters the object shares:
|
|
18
30
|
*
|
|
19
31
|
* ```ts
|
|
20
|
-
*
|
|
32
|
+
* const app = defineCloudflareApp(AppModule);
|
|
33
|
+
* export class ChatRoom extends VelaWebSocketDurableObject(app) {}
|
|
34
|
+
* export default app.worker;
|
|
21
35
|
* ```
|
|
22
36
|
*
|
|
23
37
|
* It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot
|
|
@@ -26,10 +40,12 @@ function isIdentityField(value) {
|
|
|
26
40
|
* `WebSocketModule.forRoot()`: this object registers the platform that binds
|
|
27
41
|
* its server to these sockets, delivers live invalidations locally and keeps
|
|
28
42
|
* the live cursor log in its SQLite storage. The DO's `env` is the
|
|
29
|
-
* application's ENV, as in the Worker
|
|
43
|
+
* application's ENV, as in the Worker, and its application context injects
|
|
44
|
+
* `DO_STATE`, `DO_STORAGE` and `DO_ID` like every Vela Durable Object's.
|
|
30
45
|
*/
|
|
31
|
-
function VelaWebSocketDurableObject(
|
|
32
|
-
|
|
46
|
+
function VelaWebSocketDurableObject(root) {
|
|
47
|
+
const definition = durableObjectDefinition(root);
|
|
48
|
+
class VelaWsDurableObject extends DurableObject {
|
|
33
49
|
host;
|
|
34
50
|
liveEngine;
|
|
35
51
|
ready;
|
|
@@ -38,8 +54,12 @@ function VelaWebSocketDurableObject(rootModule) {
|
|
|
38
54
|
try {
|
|
39
55
|
ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));
|
|
40
56
|
} catch {}
|
|
41
|
-
this.ready = ctx
|
|
42
|
-
const runtime = await buildDoRuntime(rootModule, ctx, {
|
|
57
|
+
this.ready = startDurableObject(ctx, "WebSocket", async () => {
|
|
58
|
+
const runtime = await buildDoRuntime(definition.rootModule, ctx, {
|
|
59
|
+
env,
|
|
60
|
+
adapters: definition.adapters,
|
|
61
|
+
state: ctx
|
|
62
|
+
});
|
|
43
63
|
this.host = new DoWebSocketHost(ctx, runtime.dispatcher, runtime.registry, runtime.gatewayPaths);
|
|
44
64
|
this.liveEngine = runtime.live;
|
|
45
65
|
});
|
|
@@ -134,7 +154,16 @@ function VelaWebSocketDurableObject(rootModule) {
|
|
|
134
154
|
if (opts.restart === true) this.ctx.abort("vela PITR restore");
|
|
135
155
|
return result;
|
|
136
156
|
}
|
|
157
|
+
}
|
|
158
|
+
const descriptor = {
|
|
159
|
+
kind: "websocket",
|
|
160
|
+
rootModule: definition.rootModule,
|
|
161
|
+
methods: WEBSOCKET_RPC_METHODS,
|
|
162
|
+
durableObject: VelaWsDurableObject
|
|
137
163
|
};
|
|
164
|
+
Object.defineProperty(VelaWsDurableObject, CLOUDFLARE_DURABLE_OBJECT, { value: descriptor });
|
|
165
|
+
if (definition.app) registerDurableObject(definition.app, descriptor);
|
|
166
|
+
return VelaWsDurableObject;
|
|
138
167
|
}
|
|
139
168
|
//#endregion
|
|
140
169
|
export { VelaWebSocketDurableObject };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"websocket.durable-object.js","names":["FORWARDED"],"sources":["../../src/websocket/websocket.durable-object.ts"],"sourcesContent":["import { DurableObject } from 'cloudflare:workers';\nimport type { VelaEnv } from '@velajs/vela';\nimport type { BroadcastCommand } from '@velajs/vela/websocket';\nimport type {\n CommitStamp,\n InvalidationCommand,\n LiveEngine,\n LiveInspection,\n} from '@velajs/vela/live';\nimport { buildDoRuntime } from './do-bootstrap';\nimport { DoWebSocketHost, type WsConnectionPrincipal } from './do-websocket-host';\nimport { armDoPitr, readDoPitrBookmark } from './do-pitr';\nimport { FORWARDED_UPGRADE_HEADERS as FORWARDED } from './worker-transport';\nimport type { CloudflareRoot } from '../root-module';\nimport type {\n DoPitrArmOptions,\n DoPitrArmResult,\n DoPitrBookmarkRead,\n VelaDoPitrRpc,\n} from './do-pitr';\n\nconst PING = '{\"event\":\"$ping\"}';\nconst PONG = '{\"event\":\"$pong\"}';\nconst MAX_IDENTITY_FIELD_BYTES = 2048;\nconst encoder = new TextEncoder();\n\nfunction isIdentityField(value: string | null): value is string {\n return (\n value !== null &&\n value.length > 0 &&\n encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES\n );\n}\n\n/**\n * Base class for the WebSocket Durable Object. The user exports a named subclass\n * (matching their `wrangler.toml` `class_name`) built from their `AppModule`, or\n * from a `DynamicModule` declared at module scope:\n *\n * ```ts\n * export class ChatRoom extends VelaWebSocketDurableObject(AppModule) {}\n * ```\n *\n * It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot\n * bridge DO hibernation) and forwards every event into the runtime-agnostic\n * `WsDispatcher` via {@link DoWebSocketHost}. The application imports the core\n * `WebSocketModule.forRoot()`: this object registers the platform that binds\n * its server to these sockets, delivers live invalidations locally and keeps\n * the live cursor log in its SQLite storage. The DO's `env` is the\n * application's ENV, as in the Worker.\n */\nexport function VelaWebSocketDurableObject(rootModule: CloudflareRoot): new (\n ctx: DurableObjectState,\n env: VelaEnv,\n) => DurableObject<VelaEnv> &\n VelaDoPitrRpc & {\n broadcast(cmd: BroadcastCommand): Promise<void>;\n invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;\n inspectLive(): Promise<LiveInspection>;\n } {\n return class VelaWsDurableObject extends DurableObject<VelaEnv> {\n private host!: DoWebSocketHost;\n private liveEngine?: LiveEngine;\n private readonly ready: Promise<void>;\n\n constructor(ctx: DurableObjectState, env: VelaEnv) {\n super(ctx, env);\n // Application-level ping/pong answered WITHOUT waking a hibernated DO.\n try {\n ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));\n } catch {\n // Older runtimes without auto-response — fine, protocol pings still work.\n }\n this.ready = ctx.blockConcurrencyWhile(async () => {\n // The root is static, so constructing another instance declares no new\n // classes in the isolate-global metadata registry.\n const runtime = await buildDoRuntime(rootModule, ctx, { env });\n this.host = new DoWebSocketHost(\n ctx,\n runtime.dispatcher,\n runtime.registry,\n runtime.gatewayPaths,\n );\n this.liveEngine = runtime.live;\n });\n }\n\n /** Intra-worker RPC only; HTTP fetch never exposes this admin snapshot. */\n async inspectLive(): Promise<LiveInspection> {\n await this.ready;\n return this.liveEngine?.inspect() ?? { subscriptions: [], rooms: [] };\n }\n\n override async fetch(request: Request): Promise<Response> {\n await this.ready;\n if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {\n return new Response('Expected WebSocket upgrade', { status: 426 });\n }\n\n const url = new URL(request.url);\n // Headers are primary (carry auth + multi-gateway routing); fall back to the\n // DO's own name (set via idFromName(room)) and the single gateway path so a\n // plain `stub.fetch(request)` forward still works.\n const roomId = request.headers.get(FORWARDED.room) ?? this.ctx.id.name ?? url.pathname;\n const path = request.headers.get(FORWARDED.path) ?? this.host.defaultPath() ?? url.pathname;\n const userId = request.headers.get(FORWARDED.user) || undefined;\n const rawExpiresAtMs = request.headers.get(FORWARDED.expiresAtMs);\n const parsedExpiresAtMs = rawExpiresAtMs === null ? undefined : Number(rawExpiresAtMs);\n if (\n parsedExpiresAtMs !== undefined &&\n (!Number.isSafeInteger(parsedExpiresAtMs) || parsedExpiresAtMs <= 0)\n ) {\n return new Response('Invalid WebSocket identity expiry', { status: 403 });\n }\n\n const issuer = request.headers.get(FORWARDED.issuer);\n const subject = request.headers.get(FORWARDED.subject);\n const principalType = request.headers.get(FORWARDED.principalType);\n const tenantId = request.headers.get(FORWARDED.tenant);\n const hasPrincipalHeader =\n issuer !== null || subject !== null || principalType !== null || tenantId !== null;\n let principal: WsConnectionPrincipal | undefined;\n if (hasPrincipalHeader) {\n if (\n !isIdentityField(issuer) ||\n !isIdentityField(subject) ||\n (principalType !== 'user' && principalType !== 'service') ||\n !isIdentityField(tenantId) ||\n parsedExpiresAtMs === undefined ||\n (userId !== undefined && userId !== subject)\n ) {\n return new Response('Invalid WebSocket principal', { status: 403 });\n }\n principal = { issuer, subject, principalType, tenantId };\n } else if (parsedExpiresAtMs !== undefined) {\n return new Response('WebSocket identity tuple is missing', { status: 403 });\n }\n\n if (parsedExpiresAtMs !== undefined && parsedExpiresAtMs <= Date.now()) {\n return new Response('WebSocket identity expired', { status: 403 });\n }\n\n const { 0: client, 1: server } = new WebSocketPair();\n const accepted = await this.host.accept(\n server,\n path,\n roomId,\n userId,\n parsedExpiresAtMs,\n principal,\n );\n if (!accepted) return new Response('WebSocket connection rejected', { status: 403 });\n return new Response(null, { status: 101, webSocket: client });\n }\n\n override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {\n await this.ready;\n await this.host.onMessage(ws, message);\n }\n\n override async webSocketClose(ws: WebSocket, code: number, reason: string): Promise<void> {\n await this.ready;\n await this.host.onClose(ws, code, reason);\n }\n\n override async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n await this.ready;\n await this.host.onError(ws, error);\n }\n\n /** DO RPC — a `Gateways` push forwarded from the Worker or another room's object. */\n async broadcast(cmd: BroadcastCommand): Promise<void> {\n await this.ready;\n await this.host.broadcast(cmd);\n }\n\n /**\n * DO RPC — live tag invalidation forwarded from a Worker (durableObjectLive /\n * liveInvalidateToRoom). Appends to THIS log scope's cursor log and returns\n * the commit stamp (what `Vela-Commit-Cursor` carries); the subscription\n * refreshes fan out asynchronously.\n */\n async invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined> {\n await this.ready;\n return this.liveEngine?.applyInvalidation(cmd);\n }\n\n // -- Durable Object PITR (point-in-time recovery) RPC ---------------------\n //\n // GUARD / reachability: these are admin-privileged operations (a restore can\n // roll the DO's SQLite state back up to 30 days and, with `restart`, abort\n // the DO to apply it now). They are safe to expose here because a Durable\n // Object's RPC methods are NOT network-reachable: a `DurableObjectStub` is\n // obtainable ONLY from a Worker that binds this DO namespace, and RPC calls\n // travel Cloudflare's internal capability channel — never the public\n // internet. A WebSocket/HTTP client reaches only `fetch()` above, never these\n // methods. The security boundary is therefore the WORKER-SIDE studio admin\n // gate that fronts the `CloudflareDoTimeTravelPort` (master admin token + the\n // 428 confirm challenge) — the identical trust model as `broadcast()` /\n // `invalidate()` on this same DO. See `do-pitr.ts` for the storage wrappers.\n\n /** DO RPC — the current PITR bookmark (typed-unavailable on a non-SQLite DO). */\n async pitrCurrentBookmark(): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage);\n }\n\n /** DO RPC — the PITR bookmark closest to `time` (+ the current bookmark). */\n async pitrBookmarkForTime(time: number | string): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage, time);\n }\n\n /**\n * DO RPC — arm a PITR restore and return the undo bookmark. When `restart` is\n * requested, `ctx.abort()` is called AFTER the undo bookmark is computed so\n * the recovery applies on the immediately-following session; otherwise the\n * restore applies on the next natural restart (`restarted: false`).\n */\n async pitrArmRestore(opts: DoPitrArmOptions): Promise<DoPitrArmResult> {\n await this.ready;\n const result = await armDoPitr(this.ctx.storage, opts);\n if (opts.restart === true) this.ctx.abort('vela PITR restore');\n return result;\n }\n };\n}\n"],"mappings":";;;;;;AAqBA,MAAM,OAAO;AACb,MAAM,OAAO;AACb,MAAM,2BAA2B;AACjC,MAAM,UAAU,IAAI,YAAY;AAEhC,SAAS,gBAAgB,OAAuC;CAC9D,OACE,UAAU,QACV,MAAM,SAAS,KACf,QAAQ,OAAO,KAAK,CAAC,CAAC,cAAc;AAExC;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,2BAA2B,YAQvC;CACF,OAAO,MAAM,4BAA4B,cAAuB;EAC9D;EACA;EACA;EAEA,YAAY,KAAyB,KAAc;GACjD,MAAM,KAAK,GAAG;GAEd,IAAI;IACF,IAAI,yBAAyB,IAAI,6BAA6B,MAAM,IAAI,CAAC;GAC3E,QAAQ,CAER;GACA,KAAK,QAAQ,IAAI,sBAAsB,YAAY;IAGjD,MAAM,UAAU,MAAM,eAAe,YAAY,KAAK,EAAE,IAAI,CAAC;IAC7D,KAAK,OAAO,IAAI,gBACd,KACA,QAAQ,YACR,QAAQ,UACR,QAAQ,YACV;IACA,KAAK,aAAa,QAAQ;GAC5B,CAAC;EACH;;EAGA,MAAM,cAAuC;GAC3C,MAAM,KAAK;GACX,OAAO,KAAK,YAAY,QAAQ,KAAK;IAAE,eAAe,CAAC;IAAG,OAAO,CAAC;GAAE;EACtE;EAEA,MAAe,MAAM,SAAqC;GACxD,MAAM,KAAK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,IAAI,SAAS,IAAI;GACrD,IAAI,KAAK,YAAY,MAAM,KAAK,IAAI,MAAM,mBAAmB;GAC7D,OAAO;EACT;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"websocket.durable-object.js","names":["FORWARDED"],"sources":["../../src/websocket/websocket.durable-object.ts"],"sourcesContent":["import { DurableObject } from 'cloudflare:workers';\nimport type { VelaEnv } from '@velajs/vela';\nimport type { BroadcastCommand } from '@velajs/vela/websocket';\nimport type {\n CommitStamp,\n InvalidationCommand,\n LiveEngine,\n LiveInspection,\n} from '@velajs/vela/live';\nimport { buildDoRuntime } from './do-bootstrap';\nimport { DoWebSocketHost, type WsConnectionPrincipal } from './do-websocket-host';\nimport { armDoPitr, readDoPitrBookmark } from './do-pitr';\nimport { FORWARDED_UPGRADE_HEADERS as FORWARDED } from './worker-transport';\nimport {\n CLOUDFLARE_DURABLE_OBJECT,\n registerDurableObject,\n type CloudflareDurableObjectDescriptor,\n} from '../cloudflare-factory';\nimport {\n durableObjectDefinition,\n startDurableObject,\n type DurableObjectRoot,\n} from '../durable-object/boot';\nimport type {\n DoPitrArmOptions,\n DoPitrArmResult,\n DoPitrBookmarkRead,\n VelaDoPitrRpc,\n} from './do-pitr';\n\nconst PING = '{\"event\":\"$ping\"}';\nconst PONG = '{\"event\":\"$pong\"}';\nconst MAX_IDENTITY_FIELD_BYTES = 2048;\nconst encoder = new TextEncoder();\n\nfunction isIdentityField(value: string | null): value is string {\n return (\n value !== null &&\n value.length > 0 &&\n encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES\n );\n}\n\n/** The RPC methods a WebSocket Durable Object exposes to the Worker and other objects. */\nconst WEBSOCKET_RPC_METHODS = [\n 'broadcast',\n 'invalidate',\n 'inspectLive',\n 'pitrCurrentBookmark',\n 'pitrBookmarkForTime',\n 'pitrArmRestore',\n] as const;\n\n/**\n * Base class for the WebSocket Durable Object. The user exports a named subclass\n * (matching their `wrangler.toml` `class_name`) built from their `AppModule`, a\n * `DynamicModule` declared at module scope, or the app from\n * `defineCloudflareApp`, whose runtime adapters the object shares:\n *\n * ```ts\n * const app = defineCloudflareApp(AppModule);\n * export class ChatRoom extends VelaWebSocketDurableObject(app) {}\n * export default app.worker;\n * ```\n *\n * It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot\n * bridge DO hibernation) and forwards every event into the runtime-agnostic\n * `WsDispatcher` via {@link DoWebSocketHost}. The application imports the core\n * `WebSocketModule.forRoot()`: this object registers the platform that binds\n * its server to these sockets, delivers live invalidations locally and keeps\n * the live cursor log in its SQLite storage. The DO's `env` is the\n * application's ENV, as in the Worker, and its application context injects\n * `DO_STATE`, `DO_STORAGE` and `DO_ID` like every Vela Durable Object's.\n */\nexport function VelaWebSocketDurableObject(root: DurableObjectRoot): new (\n ctx: DurableObjectState,\n env: VelaEnv,\n) => DurableObject<VelaEnv> &\n VelaDoPitrRpc & {\n broadcast(cmd: BroadcastCommand): Promise<void>;\n invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;\n inspectLive(): Promise<LiveInspection>;\n } {\n const definition = durableObjectDefinition(root);\n class VelaWsDurableObject extends DurableObject<VelaEnv> {\n private host!: DoWebSocketHost;\n private liveEngine?: LiveEngine;\n private readonly ready: Promise<void>;\n\n constructor(ctx: DurableObjectState, env: VelaEnv) {\n super(ctx, env);\n // Application-level ping/pong answered WITHOUT waking a hibernated DO.\n try {\n ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));\n } catch {\n // Older runtimes without auto-response — fine, protocol pings still work.\n }\n this.ready = startDurableObject(ctx, 'WebSocket', async () => {\n // The root is static, so constructing another instance declares no new\n // classes in the isolate-global metadata registry.\n const runtime = await buildDoRuntime(definition.rootModule, ctx, {\n env,\n adapters: definition.adapters,\n state: ctx,\n });\n this.host = new DoWebSocketHost(\n ctx,\n runtime.dispatcher,\n runtime.registry,\n runtime.gatewayPaths,\n );\n this.liveEngine = runtime.live;\n });\n }\n\n /** Intra-worker RPC only; HTTP fetch never exposes this admin snapshot. */\n async inspectLive(): Promise<LiveInspection> {\n await this.ready;\n return this.liveEngine?.inspect() ?? { subscriptions: [], rooms: [] };\n }\n\n override async fetch(request: Request): Promise<Response> {\n await this.ready;\n if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {\n return new Response('Expected WebSocket upgrade', { status: 426 });\n }\n\n const url = new URL(request.url);\n // Headers are primary (carry auth + multi-gateway routing); fall back to the\n // DO's own name (set via idFromName(room)) and the single gateway path so a\n // plain `stub.fetch(request)` forward still works.\n const roomId = request.headers.get(FORWARDED.room) ?? this.ctx.id.name ?? url.pathname;\n const path = request.headers.get(FORWARDED.path) ?? this.host.defaultPath() ?? url.pathname;\n const userId = request.headers.get(FORWARDED.user) || undefined;\n const rawExpiresAtMs = request.headers.get(FORWARDED.expiresAtMs);\n const parsedExpiresAtMs = rawExpiresAtMs === null ? undefined : Number(rawExpiresAtMs);\n if (\n parsedExpiresAtMs !== undefined &&\n (!Number.isSafeInteger(parsedExpiresAtMs) || parsedExpiresAtMs <= 0)\n ) {\n return new Response('Invalid WebSocket identity expiry', { status: 403 });\n }\n\n const issuer = request.headers.get(FORWARDED.issuer);\n const subject = request.headers.get(FORWARDED.subject);\n const principalType = request.headers.get(FORWARDED.principalType);\n const tenantId = request.headers.get(FORWARDED.tenant);\n const hasPrincipalHeader =\n issuer !== null || subject !== null || principalType !== null || tenantId !== null;\n let principal: WsConnectionPrincipal | undefined;\n if (hasPrincipalHeader) {\n if (\n !isIdentityField(issuer) ||\n !isIdentityField(subject) ||\n (principalType !== 'user' && principalType !== 'service') ||\n !isIdentityField(tenantId) ||\n parsedExpiresAtMs === undefined ||\n (userId !== undefined && userId !== subject)\n ) {\n return new Response('Invalid WebSocket principal', { status: 403 });\n }\n principal = { issuer, subject, principalType, tenantId };\n } else if (parsedExpiresAtMs !== undefined) {\n return new Response('WebSocket identity tuple is missing', { status: 403 });\n }\n\n if (parsedExpiresAtMs !== undefined && parsedExpiresAtMs <= Date.now()) {\n return new Response('WebSocket identity expired', { status: 403 });\n }\n\n const { 0: client, 1: server } = new WebSocketPair();\n const accepted = await this.host.accept(\n server,\n path,\n roomId,\n userId,\n parsedExpiresAtMs,\n principal,\n );\n if (!accepted) return new Response('WebSocket connection rejected', { status: 403 });\n return new Response(null, { status: 101, webSocket: client });\n }\n\n override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {\n await this.ready;\n await this.host.onMessage(ws, message);\n }\n\n override async webSocketClose(ws: WebSocket, code: number, reason: string): Promise<void> {\n await this.ready;\n await this.host.onClose(ws, code, reason);\n }\n\n override async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n await this.ready;\n await this.host.onError(ws, error);\n }\n\n /** DO RPC — a `Gateways` push forwarded from the Worker or another room's object. */\n async broadcast(cmd: BroadcastCommand): Promise<void> {\n await this.ready;\n await this.host.broadcast(cmd);\n }\n\n /**\n * DO RPC — live tag invalidation forwarded from a Worker (durableObjectLive /\n * liveInvalidateToRoom). Appends to THIS log scope's cursor log and returns\n * the commit stamp (what `Vela-Commit-Cursor` carries); the subscription\n * refreshes fan out asynchronously.\n */\n async invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined> {\n await this.ready;\n return this.liveEngine?.applyInvalidation(cmd);\n }\n\n // -- Durable Object PITR (point-in-time recovery) RPC ---------------------\n //\n // GUARD / reachability: these are admin-privileged operations (a restore can\n // roll the DO's SQLite state back up to 30 days and, with `restart`, abort\n // the DO to apply it now). They are safe to expose here because a Durable\n // Object's RPC methods are NOT network-reachable: a `DurableObjectStub` is\n // obtainable ONLY from a Worker that binds this DO namespace, and RPC calls\n // travel Cloudflare's internal capability channel — never the public\n // internet. A WebSocket/HTTP client reaches only `fetch()` above, never these\n // methods. The security boundary is therefore the WORKER-SIDE studio admin\n // gate that fronts the `CloudflareDoTimeTravelPort` (master admin token + the\n // 428 confirm challenge) — the identical trust model as `broadcast()` /\n // `invalidate()` on this same DO. See `do-pitr.ts` for the storage wrappers.\n\n /** DO RPC — the current PITR bookmark (typed-unavailable on a non-SQLite DO). */\n async pitrCurrentBookmark(): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage);\n }\n\n /** DO RPC — the PITR bookmark closest to `time` (+ the current bookmark). */\n async pitrBookmarkForTime(time: number | string): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage, time);\n }\n\n /**\n * DO RPC — arm a PITR restore and return the undo bookmark. When `restart` is\n * requested, `ctx.abort()` is called AFTER the undo bookmark is computed so\n * the recovery applies on the immediately-following session; otherwise the\n * restore applies on the next natural restart (`restarted: false`).\n */\n async pitrArmRestore(opts: DoPitrArmOptions): Promise<DoPitrArmResult> {\n await this.ready;\n const result = await armDoPitr(this.ctx.storage, opts);\n if (opts.restart === true) this.ctx.abort('vela PITR restore');\n return result;\n }\n }\n\n const descriptor: CloudflareDurableObjectDescriptor = {\n kind: 'websocket',\n rootModule: definition.rootModule,\n methods: WEBSOCKET_RPC_METHODS,\n durableObject: VelaWsDurableObject,\n };\n // Static and non-enumerable: tools read it from the exported class.\n Object.defineProperty(VelaWsDurableObject, CLOUDFLARE_DURABLE_OBJECT, { value: descriptor });\n if (definition.app) registerDurableObject(definition.app, descriptor);\n return VelaWsDurableObject;\n}\n"],"mappings":";;;;;;;;AA8BA,MAAM,OAAO;AACb,MAAM,OAAO;AACb,MAAM,2BAA2B;AACjC,MAAM,UAAU,IAAI,YAAY;AAEhC,SAAS,gBAAgB,OAAuC;CAC9D,OACE,UAAU,QACV,MAAM,SAAS,KACf,QAAQ,OAAO,KAAK,CAAC,CAAC,cAAc;AAExC;;AAGA,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,2BAA2B,MAQvC;CACF,MAAM,aAAa,wBAAwB,IAAI;CAC/C,MAAM,4BAA4B,cAAuB;EACvD;EACA;EACA;EAEA,YAAY,KAAyB,KA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AAe,OAA+B;GAC1E,MAAM,KAAK;GACX,MAAM,KAAK,KAAK,QAAQ,IAAI,KAAK;EACnC;;EAGA,MAAM,UAAU,KAAsC;GACpD,MAAM,KAAK;GACX,MAAM,KAAK,KAAK,UAAU,GAAG;EAC/B;;;;;;;EAQA,MAAM,WAAW,KAA4D;GAC3E,MAAM,KAAK;GACX,OAAO,KAAK,YAAY,kBAAkB,GAAG;EAC/C;;EAiBA,MAAM,sBAAmD;GACvD,MAAM,KAAK;GACX,OAAO,mBAAmB,KAAK,IAAI,OAAO;EAC5C;;EAGA,MAAM,oBAAoB,MAAoD;GAC5E,MAAM,KAAK;GACX,OAAO,mBAAmB,KAAK,IAAI,SAAS,IAAI;EAClD;;;;;;;EAQA,MAAM,eAAe,MAAkD;GACrE,MAAM,KAAK;GACX,MAAM,SAAS,MAAM,UAAU,KAAK,IAAI,SAAS,IAAI;GACrD,IAAI,KAAK,YAAY,MAAM,KAAK,IAAI,MAAM,mBAAmB;GAC7D,OAAO;EACT;CACF;CAEA,MAAM,aAAgD;EACpD,MAAM;EACN,YAAY,WAAW;EACvB,SAAS;EACT,eAAe;CACjB;CAEA,OAAO,eAAe,qBAAqB,2BAA2B,EAAE,OAAO,WAAW,CAAC;CAC3F,IAAI,WAAW,KAAK,sBAAsB,WAAW,KAAK,UAAU;CACpE,OAAO;AACT"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
//#region src/worker-events.ts
|
|
2
|
+
/** How many optional events there are: `email` and `tail`. */
|
|
3
|
+
const EVENTS = 2;
|
|
4
|
+
const dispatchers = /* @__PURE__ */ new Map();
|
|
5
|
+
/** Each Worker's per-environment cache, while the Worker lives. */
|
|
6
|
+
const applications = /* @__PURE__ */ new WeakMap();
|
|
7
|
+
/**
|
|
8
|
+
* Workers defined before every event's module loaded: they get its handler
|
|
9
|
+
* when it does. workerd has no `WeakRef`, so they are held until then; a
|
|
10
|
+
* Worker entry defines one Worker, at module scope.
|
|
11
|
+
*/
|
|
12
|
+
const pending = /* @__PURE__ */ new Set();
|
|
13
|
+
/** Give `worker` the `name` handler, delivered by `dispatch`, unless its object already has one. */
|
|
14
|
+
function defineHandler(worker, name, dispatch) {
|
|
15
|
+
const application = applications.get(worker);
|
|
16
|
+
if (application === void 0 || Object.hasOwn(worker, name)) return;
|
|
17
|
+
Object.defineProperty(worker, name, {
|
|
18
|
+
enumerable: true,
|
|
19
|
+
configurable: true,
|
|
20
|
+
writable: true,
|
|
21
|
+
value: async (payload, env, ctx) => dispatch(() => application(env), payload, ctx)
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* @internal Give every Worker the `name` handler, delivered by `dispatcher`.
|
|
26
|
+
* The decorator modules of `@velajs/cloudflare/email` and
|
|
27
|
+
* `@velajs/cloudflare/tail` call it when they load, so a Worker has the
|
|
28
|
+
* handler exactly when its code declares such handlers.
|
|
29
|
+
*/
|
|
30
|
+
function registerWorkerEvent(name, dispatcher) {
|
|
31
|
+
dispatchers.set(name, dispatcher);
|
|
32
|
+
for (const worker of pending) defineHandler(worker, name, dispatcher);
|
|
33
|
+
if (dispatchers.size === EVENTS) pending.clear();
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* @internal Define the optional handlers of a Worker's exported object: one
|
|
37
|
+
* for each event a loaded module handles, and later ones as their modules
|
|
38
|
+
* load. An event no loaded module handles gets no handler, so the platform
|
|
39
|
+
* sees none. `application` is the Worker's per-environment cache.
|
|
40
|
+
*/
|
|
41
|
+
function defineWorkerEvents(worker, application) {
|
|
42
|
+
applications.set(worker, application);
|
|
43
|
+
for (const [name, dispatcher] of dispatchers) defineHandler(worker, name, dispatcher);
|
|
44
|
+
if (dispatchers.size < EVENTS) pending.add(worker);
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
export { defineWorkerEvents, registerWorkerEvent };
|
|
48
|
+
|
|
49
|
+
//# sourceMappingURL=worker-events.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker-events.js","names":[],"sources":["../src/worker-events.ts"],"sourcesContent":["import type { VelaEnv } from '@velajs/vela';\nimport type { CloudflareApplication } from './cloudflare-application';\n\n/** Worker handlers a feature subpath adds to every Worker when a module imports it. */\nexport type WorkerEventName = 'email' | 'tail';\n\n/**\n * @internal Deliver one platform event to the application built for its\n * environment: `application` returns it, built on first use (it rejects when\n * the application fails to start, and the next event retries), `payload` is\n * the handler's first argument (the email message, the tail events), `ctx`\n * the platform's execution context.\n */\nexport type WorkerEventDispatcher = (\n application: () => Promise<CloudflareApplication>,\n payload: unknown,\n ctx: ExecutionContext | undefined,\n) => Promise<void>;\n\ntype ApplicationCache = (env: VelaEnv) => Promise<CloudflareApplication>;\n\n/** How many optional events there are: `email` and `tail`. */\nconst EVENTS = 2;\n\nconst dispatchers = new Map<WorkerEventName, WorkerEventDispatcher>();\n/** Each Worker's per-environment cache, while the Worker lives. */\nconst applications = new WeakMap<object, ApplicationCache>();\n/**\n * Workers defined before every event's module loaded: they get its handler\n * when it does. workerd has no `WeakRef`, so they are held until then; a\n * Worker entry defines one Worker, at module scope.\n */\nconst pending = new Set<object>();\n\n/** Give `worker` the `name` handler, delivered by `dispatch`, unless its object already has one. */\nfunction defineHandler(\n worker: object,\n name: WorkerEventName,\n dispatch: WorkerEventDispatcher,\n): void {\n const application = applications.get(worker);\n if (application === undefined || Object.hasOwn(worker, name)) return;\n Object.defineProperty(worker, name, {\n enumerable: true,\n configurable: true,\n writable: true,\n value: async (payload: unknown, env: VelaEnv, ctx?: ExecutionContext): Promise<void> =>\n dispatch(() => application(env), payload, ctx),\n });\n}\n\n/**\n * @internal Give every Worker the `name` handler, delivered by `dispatcher`.\n * The decorator modules of `@velajs/cloudflare/email` and\n * `@velajs/cloudflare/tail` call it when they load, so a Worker has the\n * handler exactly when its code declares such handlers.\n */\nexport function registerWorkerEvent(\n name: WorkerEventName,\n dispatcher: WorkerEventDispatcher,\n): void {\n dispatchers.set(name, dispatcher);\n for (const worker of pending) defineHandler(worker, name, dispatcher);\n if (dispatchers.size === EVENTS) pending.clear();\n}\n\n/**\n * @internal Define the optional handlers of a Worker's exported object: one\n * for each event a loaded module handles, and later ones as their modules\n * load. An event no loaded module handles gets no handler, so the platform\n * sees none. `application` is the Worker's per-environment cache.\n */\nexport function defineWorkerEvents(worker: object, application: ApplicationCache): void {\n applications.set(worker, application);\n for (const [name, dispatcher] of dispatchers) defineHandler(worker, name, dispatcher);\n if (dispatchers.size < EVENTS) pending.add(worker);\n}\n"],"mappings":";;AAsBA,MAAM,SAAS;AAEf,MAAM,8BAAc,IAAI,IAA4C;;AAEpE,MAAM,+BAAe,IAAI,QAAkC;;;;;;AAM3D,MAAM,0BAAU,IAAI,IAAY;;AAGhC,SAAS,cACP,QACA,MACA,UACM;CACN,MAAM,cAAc,aAAa,IAAI,MAAM;CAC3C,IAAI,gBAAgB,KAAA,KAAa,OAAO,OAAO,QAAQ,IAAI,GAAG;CAC9D,OAAO,eAAe,QAAQ,MAAM;EAClC,YAAY;EACZ,cAAc;EACd,UAAU;EACV,OAAO,OAAO,SAAkB,KAAc,QAC5C,eAAe,YAAY,GAAG,GAAG,SAAS,GAAG;CACjD,CAAC;AACH;;;;;;;AAQA,SAAgB,oBACd,MACA,YACM;CACN,YAAY,IAAI,MAAM,UAAU;CAChC,KAAK,MAAM,UAAU,SAAS,cAAc,QAAQ,MAAM,UAAU;CACpE,IAAI,YAAY,SAAS,QAAQ,QAAQ,MAAM;AACjD;;;;;;;AAQA,SAAgB,mBAAmB,QAAgB,aAAqC;CACtF,aAAa,IAAI,QAAQ,WAAW;CACpC,KAAK,MAAM,CAAC,MAAM,eAAe,aAAa,cAAc,QAAQ,MAAM,UAAU;CACpF,IAAI,YAAY,OAAO,QAAQ,QAAQ,IAAI,MAAM;AACnD"}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { CLOUDFLARE_WORKFLOW, cloudflareApplication, isCloudflareApp, registerWorkflow } from "../cloudflare-factory.js";
|
|
2
|
+
import { HostInvoker, hostModuleId, platformSettlement } from "../host/host-invoker.js";
|
|
3
|
+
import { assertNotThenable, hasPrototypeMethod } from "../host/host-members.js";
|
|
4
|
+
import { WorkflowEntrypoint } from "cloudflare:workers";
|
|
5
|
+
//#region src/workflow/vela-workflow.ts
|
|
6
|
+
const workflowSettlement = platformSettlement(false);
|
|
7
|
+
/**
|
|
8
|
+
* Whether `error` is the Workflows engine interrupting a run: when an instance
|
|
9
|
+
* is paused, restarted or terminated, `step.do`, `step.sleep` and a retry wait
|
|
10
|
+
* reject with an `Error('Aborting engine: ...')`, and the engine recognizes
|
|
11
|
+
* the rejection of `run()` by that message. It must reach the engine as it is.
|
|
12
|
+
*/
|
|
13
|
+
function isEngineAbort(error) {
|
|
14
|
+
const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : void 0;
|
|
15
|
+
return typeof message === "string" && message.startsWith("Aborting engine:");
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A Workflow class (a `WorkflowEntrypoint`) whose `run(event, step)` is the
|
|
19
|
+
* `run` method of `host`, an `@Injectable()` class, resolved in the Worker's
|
|
20
|
+
* application for the run's environment: the same application the app's
|
|
21
|
+
* Worker handlers use. The host is added to the root module's providers, so
|
|
22
|
+
* it injects `ENV` and what the root module can see. Export a named subclass
|
|
23
|
+
* matching the Wrangler `class_name`:
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* @Injectable()
|
|
27
|
+
* export class SignupWorkflowHost {
|
|
28
|
+
* constructor(private readonly users: UsersService) {}
|
|
29
|
+
*
|
|
30
|
+
* async run(event: WorkflowEvent<{ email: string }>, step: WorkflowStep) {
|
|
31
|
+
* const user = await step.do('create user', () => this.users.create(event.payload.email));
|
|
32
|
+
* await step.sleep('grace period', '1 day');
|
|
33
|
+
* return step.do('send welcome', () => this.users.welcome(user.id));
|
|
34
|
+
* }
|
|
35
|
+
* }
|
|
36
|
+
* export class SignupWorkflow extends VelaWorkflow(app, SignupWorkflowHost) {}
|
|
37
|
+
* // Worker code: await env.SIGNUP_WORKFLOW.create({ params: { email } })
|
|
38
|
+
* ```
|
|
39
|
+
*
|
|
40
|
+
* - Each run executes in its own execution scope, so request-scoped providers
|
|
41
|
+
* are built per run, through the host's scoped guards, interceptors and
|
|
42
|
+
* exception filters (`getType()` is `'cf:workflow'`, `getPayload()` the
|
|
43
|
+
* event). The engine may run `run()` again for the same instance (after a
|
|
44
|
+
* sleep, an event or an eviction), replaying completed steps from their
|
|
45
|
+
* stored results: each call is a new run.
|
|
46
|
+
* - `event` and `step` are the platform's own objects, passed through
|
|
47
|
+
* untouched, so `step.do`, `step.sleep` and `step.waitForEvent` keep their
|
|
48
|
+
* retry and replay semantics.
|
|
49
|
+
* - A failure is reported (`edge: 'workflow'`) and rethrown as it is, so the
|
|
50
|
+
* engine applies its own semantics, including `NonRetryableError`. A scoped
|
|
51
|
+
* exception filter that catches it settles the run with what it returns.
|
|
52
|
+
* - The engine's own interruptions (an `Error('Aborting engine: ...')` that a
|
|
53
|
+
* step rejects with when the instance is paused, restarted or terminated)
|
|
54
|
+
* are not failures: they pass through unreported, and no filter sees them.
|
|
55
|
+
* - `host` must declare `run` on its prototype; a host whose prototype
|
|
56
|
+
* defines `then()` is rejected, since an instance would be a thenable.
|
|
57
|
+
*/
|
|
58
|
+
function VelaWorkflow(app, host) {
|
|
59
|
+
if (!isCloudflareApp(app)) throw new TypeError("VelaWorkflow() takes the app from defineCloudflareApp(AppModule, options): each run executes in the Worker application that app builds.");
|
|
60
|
+
if (typeof host !== "function") throw new TypeError("VelaWorkflow(app, Host) takes the @Injectable() host class.");
|
|
61
|
+
assertNotThenable(host);
|
|
62
|
+
if (!hasPrototypeMethod(host, "run")) throw new TypeError(`${host.name} has no prototype method run(event, step): declare run in the class body as the Workflow body, not as an accessor or an instance field.`);
|
|
63
|
+
const rootClass = typeof app.rootModule === "function" ? app.rootModule : app.rootModule.module;
|
|
64
|
+
const invokers = /* @__PURE__ */ new WeakMap();
|
|
65
|
+
const invokerOf = (application) => {
|
|
66
|
+
const existing = invokers.get(application);
|
|
67
|
+
if (existing) return existing;
|
|
68
|
+
const container = application.getContainer();
|
|
69
|
+
const invoker = new HostInvoker({
|
|
70
|
+
container,
|
|
71
|
+
host,
|
|
72
|
+
moduleId: hostModuleId(container, host, rootClass),
|
|
73
|
+
edge: "workflow"
|
|
74
|
+
});
|
|
75
|
+
invokers.set(application, invoker);
|
|
76
|
+
return invoker;
|
|
77
|
+
};
|
|
78
|
+
class VelaHostWorkflow extends WorkflowEntrypoint {
|
|
79
|
+
async run(event, step) {
|
|
80
|
+
const application = await cloudflareApplication(app, this.env);
|
|
81
|
+
return invokerOf(application).invoke({
|
|
82
|
+
kind: "cf:workflow",
|
|
83
|
+
method: "run",
|
|
84
|
+
args: [event, step],
|
|
85
|
+
payload: event,
|
|
86
|
+
settlement: workflowSettlement,
|
|
87
|
+
passthrough: isEngineAbort
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const descriptor = {
|
|
92
|
+
rootModule: app.rootModule,
|
|
93
|
+
host,
|
|
94
|
+
workflow: VelaHostWorkflow
|
|
95
|
+
};
|
|
96
|
+
registerWorkflow(app, descriptor);
|
|
97
|
+
Object.defineProperty(VelaHostWorkflow, "name", { value: `${host.name}Workflow` });
|
|
98
|
+
Object.defineProperty(VelaHostWorkflow, CLOUDFLARE_WORKFLOW, { value: descriptor });
|
|
99
|
+
return VelaHostWorkflow;
|
|
100
|
+
}
|
|
101
|
+
//#endregion
|
|
102
|
+
export { VelaWorkflow };
|
|
103
|
+
|
|
104
|
+
//# sourceMappingURL=vela-workflow.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vela-workflow.js","names":[],"sources":["../../src/workflow/vela-workflow.ts"],"sourcesContent":["import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from 'cloudflare:workers';\nimport type { Type, VelaEnv } from '@velajs/vela';\nimport type { EntrypointExecutionContext } from '@velajs/vela/module-kit';\nimport type { CloudflareApplication } from '../cloudflare-application';\nimport {\n CLOUDFLARE_WORKFLOW,\n cloudflareApplication,\n isCloudflareApp,\n registerWorkflow,\n type CloudflareApp,\n type CloudflareWorkflowDescriptor,\n} from '../cloudflare-factory';\nimport { HostInvoker, hostModuleId, platformSettlement } from '../host/host-invoker';\nimport { assertNotThenable, hasPrototypeMethod } from '../host/host-members';\n\n/**\n * A class `VelaWorkflow()` runs: an `@Injectable()` whose\n * `run(event, step)` is the Workflow's body, typed with the params in\n * `event.payload`.\n */\nexport interface WorkflowHost {\n run(event: never, step: never): unknown;\n}\n\n/**\n * The params a Workflow takes: the `event.payload` type of its host's\n * `run(event, step)`, or of the `run` of a class from `VelaWorkflow()`.\n * `workflow<WorkflowParams<SignupWorkflow>>({ binding })` types the binding\n * that creates its instances.\n */\nexport type WorkflowParams<Target> = Target extends abstract new (\n ...args: never[]\n) => infer Instance\n ? WorkflowParams<Instance>\n : Target extends { run(event: infer Event, ...rest: never[]): unknown }\n ? Event extends { readonly payload: infer Payload }\n ? Payload\n : unknown\n : never;\n\n/** What a Workflow host's `run(event, step)` resolves to: the instance's output. */\nexport type WorkflowOutput<Host extends WorkflowHost> = Awaited<ReturnType<Host['run']>>;\n\n/** The ExecutionContext guards, interceptors and filters receive around a Workflow run. */\nexport type WorkflowExecutionContext = EntrypointExecutionContext<'cf:workflow'>;\n\n/**\n * The class `VelaWorkflow(app, Host)` returns: export a named subclass of it,\n * matching the Wrangler `workflows` entry's `class_name`. It also carries its\n * `CloudflareWorkflowDescriptor` under the static `CLOUDFLARE_WORKFLOW` key,\n * for tools.\n */\nexport type VelaWorkflowClass<Host extends WorkflowHost> = new (\n ctx: ExecutionContext,\n env: VelaEnv,\n) => {\n // First, so a call resolves to the host's output rather than the base class's unknown.\n run(\n event: Readonly<WorkflowEvent<WorkflowParams<Host>>>,\n step: WorkflowStep,\n ): Promise<WorkflowOutput<Host>>;\n} & WorkflowEntrypoint<VelaEnv, WorkflowParams<Host>>;\n\n// A filter that catches a failure settles the run with what it returns;\n// managed work that fails after a successful run is reported, never retried.\nconst workflowSettlement = platformSettlement(false);\n\n/**\n * Whether `error` is the Workflows engine interrupting a run: when an instance\n * is paused, restarted or terminated, `step.do`, `step.sleep` and a retry wait\n * reject with an `Error('Aborting engine: ...')`, and the engine recognizes\n * the rejection of `run()` by that message. It must reach the engine as it is.\n */\nfunction isEngineAbort(error: unknown): boolean {\n const message: unknown =\n typeof error === 'object' && error !== null ? Reflect.get(error, 'message') : undefined;\n return typeof message === 'string' && message.startsWith('Aborting engine:');\n}\n\n/**\n * A Workflow class (a `WorkflowEntrypoint`) whose `run(event, step)` is the\n * `run` method of `host`, an `@Injectable()` class, resolved in the Worker's\n * application for the run's environment: the same application the app's\n * Worker handlers use. The host is added to the root module's providers, so\n * it injects `ENV` and what the root module can see. Export a named subclass\n * matching the Wrangler `class_name`:\n *\n * ```ts\n * @Injectable()\n * export class SignupWorkflowHost {\n * constructor(private readonly users: UsersService) {}\n *\n * async run(event: WorkflowEvent<{ email: string }>, step: WorkflowStep) {\n * const user = await step.do('create user', () => this.users.create(event.payload.email));\n * await step.sleep('grace period', '1 day');\n * return step.do('send welcome', () => this.users.welcome(user.id));\n * }\n * }\n * export class SignupWorkflow extends VelaWorkflow(app, SignupWorkflowHost) {}\n * // Worker code: await env.SIGNUP_WORKFLOW.create({ params: { email } })\n * ```\n *\n * - Each run executes in its own execution scope, so request-scoped providers\n * are built per run, through the host's scoped guards, interceptors and\n * exception filters (`getType()` is `'cf:workflow'`, `getPayload()` the\n * event). The engine may run `run()` again for the same instance (after a\n * sleep, an event or an eviction), replaying completed steps from their\n * stored results: each call is a new run.\n * - `event` and `step` are the platform's own objects, passed through\n * untouched, so `step.do`, `step.sleep` and `step.waitForEvent` keep their\n * retry and replay semantics.\n * - A failure is reported (`edge: 'workflow'`) and rethrown as it is, so the\n * engine applies its own semantics, including `NonRetryableError`. A scoped\n * exception filter that catches it settles the run with what it returns.\n * - The engine's own interruptions (an `Error('Aborting engine: ...')` that a\n * step rejects with when the instance is paused, restarted or terminated)\n * are not failures: they pass through unreported, and no filter sees them.\n * - `host` must declare `run` on its prototype; a host whose prototype\n * defines `then()` is rejected, since an instance would be a thenable.\n */\nexport function VelaWorkflow<Host extends WorkflowHost>(\n app: CloudflareApp,\n host: Type<Host>,\n): VelaWorkflowClass<Host> {\n if (!isCloudflareApp(app)) {\n throw new TypeError(\n 'VelaWorkflow() takes the app from defineCloudflareApp(AppModule, options): each run ' +\n 'executes in the Worker application that app builds.',\n );\n }\n if (typeof host !== 'function') {\n throw new TypeError('VelaWorkflow(app, Host) takes the @Injectable() host class.');\n }\n assertNotThenable(host);\n if (!hasPrototypeMethod(host, 'run')) {\n throw new TypeError(\n `${host.name} has no prototype method run(event, step): declare run in the class body ` +\n 'as the Workflow body, not as an accessor or an instance field.',\n );\n }\n const rootClass = typeof app.rootModule === 'function' ? app.rootModule : app.rootModule.module;\n const invokers = new WeakMap<CloudflareApplication, HostInvoker>();\n const invokerOf = (application: CloudflareApplication): HostInvoker => {\n const existing = invokers.get(application);\n if (existing) return existing;\n const container = application.getContainer();\n const invoker = new HostInvoker({\n container,\n host,\n moduleId: hostModuleId(container, host, rootClass),\n edge: 'workflow',\n });\n invokers.set(application, invoker);\n return invoker;\n };\n\n class VelaHostWorkflow extends WorkflowEntrypoint<VelaEnv, WorkflowParams<Host>> {\n override async run(\n event: Readonly<WorkflowEvent<WorkflowParams<Host>>>,\n step: WorkflowStep,\n ): Promise<unknown> {\n const application = await cloudflareApplication(app, this.env);\n return invokerOf(application).invoke({\n kind: 'cf:workflow',\n method: 'run',\n args: [event, step],\n payload: event,\n settlement: workflowSettlement,\n passthrough: isEngineAbort,\n });\n }\n }\n\n const descriptor: CloudflareWorkflowDescriptor = {\n rootModule: app.rootModule,\n host,\n workflow: VelaHostWorkflow,\n };\n registerWorkflow(app, descriptor);\n Object.defineProperty(VelaHostWorkflow, 'name', { value: `${host.name}Workflow` });\n Object.defineProperty(VelaHostWorkflow, CLOUDFLARE_WORKFLOW, { value: descriptor });\n // `run` resolves to the host's output; the class type says so for bindings and tests.\n return VelaHostWorkflow as unknown as VelaWorkflowClass<Host>;\n}\n"],"mappings":";;;;;AAiEA,MAAM,qBAAqB,mBAAmB,KAAK;;;;;;;AAQnD,SAAS,cAAc,OAAyB;CAC9C,MAAM,UACJ,OAAO,UAAU,YAAY,UAAU,OAAO,QAAQ,IAAI,OAAO,SAAS,IAAI,KAAA;CAChF,OAAO,OAAO,YAAY,YAAY,QAAQ,WAAW,kBAAkB;AAC7E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,aACd,KACA,MACyB;CACzB,IAAI,CAAC,gBAAgB,GAAG,GACtB,MAAM,IAAI,UACR,yIAEF;CAEF,IAAI,OAAO,SAAS,YAClB,MAAM,IAAI,UAAU,6DAA6D;CAEnF,kBAAkB,IAAI;CACtB,IAAI,CAAC,mBAAmB,MAAM,KAAK,GACjC,MAAM,IAAI,UACR,GAAG,KAAK,KAAK,wIAEf;CAEF,MAAM,YAAY,OAAO,IAAI,eAAe,aAAa,IAAI,aAAa,IAAI,WAAW;CACzF,MAAM,2BAAW,IAAI,QAA4C;CACjE,MAAM,aAAa,gBAAoD;EACrE,MAAM,WAAW,SAAS,IAAI,WAAW;EACzC,IAAI,UAAU,OAAO;EACrB,MAAM,YAAY,YAAY,aAAa;EAC3C,MAAM,UAAU,IAAI,YAAY;GAC9B;GACA;GACA,UAAU,aAAa,WAAW,MAAM,SAAS;GACjD,MAAM;EACR,CAAC;EACD,SAAS,IAAI,aAAa,OAAO;EACjC,OAAO;CACT;CAEA,MAAM,yBAAyB,mBAAkD;EAC/E,MAAe,IACb,OACA,MACkB;GAClB,MAAM,cAAc,MAAM,sBAAsB,KAAK,KAAK,GAAG;GAC7D,OAAO,UAAU,WAAW,CAAC,CAAC,OAAO;IACnC,MAAM;IACN,QAAQ;IACR,MAAM,CAAC,OAAO,IAAI;IAClB,SAAS;IACT,YAAY;IACZ,aAAa;GACf,CAAC;EACH;CACF;CAEA,MAAM,aAA2C;EAC/C,YAAY,IAAI;EAChB;EACA,UAAU;CACZ;CACA,iBAAiB,KAAK,UAAU;CAChC,OAAO,eAAe,kBAAkB,QAAQ,EAAE,OAAO,GAAG,KAAK,KAAK,UAAU,CAAC;CACjF,OAAO,eAAe,kBAAkB,qBAAqB,EAAE,OAAO,WAAW,CAAC;CAElF,OAAO;AACT"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import "./vela-env-DFvyoNT3.js";
|
|
2
|
+
import { a as CloudflareApp } from "./cloudflare-factory-CuFNUJJD.js";
|
|
3
|
+
import { WorkflowEntrypoint, WorkflowEvent, WorkflowStep } from "cloudflare:workers";
|
|
4
|
+
import { Type, VelaEnv } from "@velajs/vela";
|
|
5
|
+
import { EntrypointExecutionContext } from "@velajs/vela/module-kit";
|
|
6
|
+
//#region src/workflow/vela-workflow.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* A class `VelaWorkflow()` runs: an `@Injectable()` whose
|
|
9
|
+
* `run(event, step)` is the Workflow's body, typed with the params in
|
|
10
|
+
* `event.payload`.
|
|
11
|
+
*/
|
|
12
|
+
interface WorkflowHost {
|
|
13
|
+
run(event: never, step: never): unknown;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The params a Workflow takes: the `event.payload` type of its host's
|
|
17
|
+
* `run(event, step)`, or of the `run` of a class from `VelaWorkflow()`.
|
|
18
|
+
* `workflow<WorkflowParams<SignupWorkflow>>({ binding })` types the binding
|
|
19
|
+
* that creates its instances.
|
|
20
|
+
*/
|
|
21
|
+
type WorkflowParams<Target> = Target extends (abstract new (...args: never[]) => infer Instance) ? WorkflowParams<Instance> : Target extends {
|
|
22
|
+
run(event: infer Event, ...rest: never[]): unknown;
|
|
23
|
+
} ? Event extends {
|
|
24
|
+
readonly payload: infer Payload;
|
|
25
|
+
} ? Payload : unknown : never;
|
|
26
|
+
/** What a Workflow host's `run(event, step)` resolves to: the instance's output. */
|
|
27
|
+
type WorkflowOutput<Host extends WorkflowHost> = Awaited<ReturnType<Host['run']>>;
|
|
28
|
+
/** The ExecutionContext guards, interceptors and filters receive around a Workflow run. */
|
|
29
|
+
type WorkflowExecutionContext = EntrypointExecutionContext<'cf:workflow'>;
|
|
30
|
+
/**
|
|
31
|
+
* The class `VelaWorkflow(app, Host)` returns: export a named subclass of it,
|
|
32
|
+
* matching the Wrangler `workflows` entry's `class_name`. It also carries its
|
|
33
|
+
* `CloudflareWorkflowDescriptor` under the static `CLOUDFLARE_WORKFLOW` key,
|
|
34
|
+
* for tools.
|
|
35
|
+
*/
|
|
36
|
+
type VelaWorkflowClass<Host extends WorkflowHost> = new (ctx: ExecutionContext, env: VelaEnv) => {
|
|
37
|
+
run(event: Readonly<WorkflowEvent<WorkflowParams<Host>>>, step: WorkflowStep): Promise<WorkflowOutput<Host>>;
|
|
38
|
+
} & WorkflowEntrypoint<VelaEnv, WorkflowParams<Host>>;
|
|
39
|
+
/**
|
|
40
|
+
* A Workflow class (a `WorkflowEntrypoint`) whose `run(event, step)` is the
|
|
41
|
+
* `run` method of `host`, an `@Injectable()` class, resolved in the Worker's
|
|
42
|
+
* application for the run's environment: the same application the app's
|
|
43
|
+
* Worker handlers use. The host is added to the root module's providers, so
|
|
44
|
+
* it injects `ENV` and what the root module can see. Export a named subclass
|
|
45
|
+
* matching the Wrangler `class_name`:
|
|
46
|
+
*
|
|
47
|
+
* ```ts
|
|
48
|
+
* @Injectable()
|
|
49
|
+
* export class SignupWorkflowHost {
|
|
50
|
+
* constructor(private readonly users: UsersService) {}
|
|
51
|
+
*
|
|
52
|
+
* async run(event: WorkflowEvent<{ email: string }>, step: WorkflowStep) {
|
|
53
|
+
* const user = await step.do('create user', () => this.users.create(event.payload.email));
|
|
54
|
+
* await step.sleep('grace period', '1 day');
|
|
55
|
+
* return step.do('send welcome', () => this.users.welcome(user.id));
|
|
56
|
+
* }
|
|
57
|
+
* }
|
|
58
|
+
* export class SignupWorkflow extends VelaWorkflow(app, SignupWorkflowHost) {}
|
|
59
|
+
* // Worker code: await env.SIGNUP_WORKFLOW.create({ params: { email } })
|
|
60
|
+
* ```
|
|
61
|
+
*
|
|
62
|
+
* - Each run executes in its own execution scope, so request-scoped providers
|
|
63
|
+
* are built per run, through the host's scoped guards, interceptors and
|
|
64
|
+
* exception filters (`getType()` is `'cf:workflow'`, `getPayload()` the
|
|
65
|
+
* event). The engine may run `run()` again for the same instance (after a
|
|
66
|
+
* sleep, an event or an eviction), replaying completed steps from their
|
|
67
|
+
* stored results: each call is a new run.
|
|
68
|
+
* - `event` and `step` are the platform's own objects, passed through
|
|
69
|
+
* untouched, so `step.do`, `step.sleep` and `step.waitForEvent` keep their
|
|
70
|
+
* retry and replay semantics.
|
|
71
|
+
* - A failure is reported (`edge: 'workflow'`) and rethrown as it is, so the
|
|
72
|
+
* engine applies its own semantics, including `NonRetryableError`. A scoped
|
|
73
|
+
* exception filter that catches it settles the run with what it returns.
|
|
74
|
+
* - The engine's own interruptions (an `Error('Aborting engine: ...')` that a
|
|
75
|
+
* step rejects with when the instance is paused, restarted or terminated)
|
|
76
|
+
* are not failures: they pass through unreported, and no filter sees them.
|
|
77
|
+
* - `host` must declare `run` on its prototype; a host whose prototype
|
|
78
|
+
* defines `then()` is rejected, since an instance would be a thenable.
|
|
79
|
+
*/
|
|
80
|
+
export declare function VelaWorkflow<Host extends WorkflowHost>(app: CloudflareApp, host: Type<Host>): VelaWorkflowClass<Host>;
|
|
81
|
+
//#endregion
|
|
82
|
+
export type { VelaWorkflowClass, WorkflowExecutionContext, WorkflowHost, WorkflowOutput, WorkflowParams };
|