@velajs/cloudflare 1.30.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 +174 -0
- package/README.md +407 -77
- package/dist/bindings.js +93 -0
- package/dist/bindings.js.map +1 -0
- package/dist/cloudflare-application-CXDy9C1R.d.ts +199 -0
- package/dist/cloudflare-application.js +15 -34
- package/dist/cloudflare-application.js.map +1 -1
- package/dist/cloudflare-factory-CuFNUJJD.d.ts +241 -0
- package/dist/cloudflare-factory.js +227 -38
- package/dist/cloudflare-factory.js.map +1 -1
- package/dist/diagnostics.js +18 -0
- package/dist/diagnostics.js.map +1 -0
- 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 +136 -10
- 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 +211 -445
- package/dist/index.js +8 -13
- package/dist/{nonce.durable-object-Ci9AGssY.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -11
- package/dist/platform.js +22 -0
- package/dist/platform.js.map +1 -0
- package/dist/queue/cloudflare-queues.js +7 -7
- package/dist/queue/cloudflare-queues.js.map +1 -1
- package/dist/rate-limit/cloudflare-rate-limit.store.js +66 -27
- package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -1
- 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/schedule-diagnostics.js +8 -15
- package/dist/schedule-diagnostics.js.map +1 -1
- package/dist/services/kv-cache.store.js +33 -7
- package/dist/services/kv-cache.store.js.map +1 -1
- package/dist/storage/r2-storage.js +30 -0
- package/dist/storage/r2-storage.js.map +1 -0
- package/dist/storage.d.ts +28 -0
- package/dist/storage.js +2 -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 +148 -0
- package/dist/testing.js +188 -0
- package/dist/testing.js.map +1 -0
- package/dist/websocket/binding-gateways.js +33 -0
- package/dist/websocket/binding-gateways.js.map +1 -0
- package/dist/websocket/cf-room-registry.js +3 -1
- package/dist/websocket/cf-room-registry.js.map +1 -1
- package/dist/websocket/do-bootstrap.js +64 -40
- package/dist/websocket/do-bootstrap.js.map +1 -1
- package/dist/websocket/do-live.js +49 -90
- package/dist/websocket/do-live.js.map +1 -1
- package/dist/websocket/do-state.js.map +1 -1
- package/dist/websocket/live-driver.js +149 -0
- package/dist/websocket/live-driver.js.map +1 -0
- package/dist/websocket/room-id.js +11 -1
- package/dist/websocket/room-id.js.map +1 -1
- package/dist/websocket/websocket.durable-object.js +51 -18
- package/dist/websocket/websocket.durable-object.js.map +1 -1
- package/dist/websocket/worker-transport.js +80 -0
- package/dist/websocket/worker-transport.js.map +1 -0
- 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 +39 -6
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +0 -9
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +0 -6
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +0 -8
- package/dist/storage/r2-storage.driver.js +0 -67
- package/dist/storage/r2-storage.driver.js.map +0 -1
- package/dist/storage/storage-key-claim.js +0 -74
- package/dist/storage/storage-key-claim.js.map +0 -1
- package/dist/storage/storage-manager.service.js +0 -38
- package/dist/storage/storage-manager.service.js.map +0 -1
- package/dist/storage/storage.controller.js +0 -64
- package/dist/storage/storage.controller.js.map +0 -1
- package/dist/storage/storage.module.js +0 -25
- package/dist/storage/storage.module.js.map +0 -1
- package/dist/storage/storage.service.js +0 -64
- package/dist/storage/storage.service.js.map +0 -1
- package/dist/storage/storage.tokens.js +0 -7
- package/dist/storage/storage.tokens.js.map +0 -1
- package/dist/websocket/broadcast.js +0 -32
- package/dist/websocket/broadcast.js.map +0 -1
- package/dist/websocket/cloudflare-websocket.module.js +0 -25
- package/dist/websocket/cloudflare-websocket.module.js.map +0 -1
- package/dist/websocket/websocket-routing.js +0 -133
- package/dist/websocket/websocket-routing.js.map +0 -1
- package/dist/websocket/ws-server-holder.js +0 -38
- package/dist/websocket/ws-server-holder.js.map +0 -1
package/dist/testing.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { CloudflareApplication } from "./cloudflare-application.js";
|
|
2
|
+
import { cloudflareCreateOptions, configureCloudflareApplication } from "./cloudflare-factory.js";
|
|
3
|
+
import { dispatchEmail } from "./email/email-dispatch.js";
|
|
4
|
+
import { dispatchTail } from "./tail/tail-dispatch.js";
|
|
5
|
+
import { parseCronMetadata } from "@velajs/vela/module-kit";
|
|
6
|
+
import { env } from "cloudflare:workers";
|
|
7
|
+
import * as cloudflareTest from "cloudflare:test";
|
|
8
|
+
import { Test } from "@velajs/testing";
|
|
9
|
+
//#region src/testing.ts
|
|
10
|
+
const pool = cloudflareTest;
|
|
11
|
+
/**
|
|
12
|
+
* An Email Workers message (`ForwardableEmailMessage`) for tests, in the
|
|
13
|
+
* spirit of `cloudflare:test`'s `createMessageBatch()`: `raw`, `rawSize` and
|
|
14
|
+
* `headers` describe the message, and `setReject()`, `forward()` and `reply()`
|
|
15
|
+
* record what the handlers did (`rejectReason`, `forwards`, `replies`) instead
|
|
16
|
+
* of sending anything.
|
|
17
|
+
*
|
|
18
|
+
* ```ts
|
|
19
|
+
* const message = emailMessage({ from: 'ada@example.net', to: 'support@example.com', subject: 'Help' });
|
|
20
|
+
* await worker.email(message);
|
|
21
|
+
* expect(message.forwards).toEqual([{ rcptTo: 'team@example.com' }]);
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
function emailMessage(init) {
|
|
25
|
+
const headers = new Headers(init.headers);
|
|
26
|
+
if (!headers.has("from")) headers.set("from", init.from);
|
|
27
|
+
if (!headers.has("to")) headers.set("to", init.to);
|
|
28
|
+
if (init.subject !== void 0 && !headers.has("subject")) headers.set("subject", init.subject);
|
|
29
|
+
const raw = init.raw ?? `${[...headers].map(([name, value]) => `${name}: ${value}`).join("\r\n")}\r\n\r\n${init.text ?? ""}`;
|
|
30
|
+
const bytes = typeof raw === "string" ? new TextEncoder().encode(raw) : raw;
|
|
31
|
+
let rejectReason;
|
|
32
|
+
const forwards = [];
|
|
33
|
+
const replies = [];
|
|
34
|
+
return {
|
|
35
|
+
from: init.from,
|
|
36
|
+
to: init.to,
|
|
37
|
+
headers,
|
|
38
|
+
rawSize: bytes.byteLength,
|
|
39
|
+
raw: new ReadableStream({ start(controller) {
|
|
40
|
+
controller.enqueue(bytes.slice());
|
|
41
|
+
controller.close();
|
|
42
|
+
} }),
|
|
43
|
+
get rejectReason() {
|
|
44
|
+
return rejectReason;
|
|
45
|
+
},
|
|
46
|
+
forwards,
|
|
47
|
+
replies,
|
|
48
|
+
setReject(reason) {
|
|
49
|
+
rejectReason = reason;
|
|
50
|
+
},
|
|
51
|
+
async forward(rcptTo, forwardHeaders) {
|
|
52
|
+
forwards.push(forwardHeaders === void 0 ? { rcptTo } : {
|
|
53
|
+
rcptTo,
|
|
54
|
+
headers: forwardHeaders
|
|
55
|
+
});
|
|
56
|
+
return { messageId: `forward-${forwards.length}@vela.test` };
|
|
57
|
+
},
|
|
58
|
+
async reply(message) {
|
|
59
|
+
replies.push(message);
|
|
60
|
+
return { messageId: `reply-${replies.length}@vela.test` };
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A Tail Workers event (`TraceItem`) for tests: an `ok` fetch-less invocation
|
|
66
|
+
* of the Worker `producer`, with `overrides` applied.
|
|
67
|
+
*/
|
|
68
|
+
function traceItem(overrides = {}) {
|
|
69
|
+
return {
|
|
70
|
+
event: null,
|
|
71
|
+
eventTimestamp: Date.now(),
|
|
72
|
+
logs: [],
|
|
73
|
+
exceptions: [],
|
|
74
|
+
diagnosticsChannelEvents: [],
|
|
75
|
+
scriptName: "producer",
|
|
76
|
+
outcome: "ok",
|
|
77
|
+
executionModel: "stateless",
|
|
78
|
+
truncated: false,
|
|
79
|
+
cpuTime: 0,
|
|
80
|
+
wallTime: 0,
|
|
81
|
+
...overrides
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Build `rootModule` as `createCloudflareWorker(rootModule, options)` does
|
|
86
|
+
* (its adapters, then its `configure` hook), through `@velajs/testing`, and
|
|
87
|
+
* drive its Worker handlers inside the Workers Vitest pool.
|
|
88
|
+
*
|
|
89
|
+
* ```ts
|
|
90
|
+
* const worker = await createTestingWorker(AppModule, {
|
|
91
|
+
* overrides: (module) => module.overrideProvider(Mailer).useValue(fakeMailer),
|
|
92
|
+
* });
|
|
93
|
+
* const response = await worker.fetch('/todos');
|
|
94
|
+
* const result = await worker.queue('todo-events', [queueJob('todos', todoCreated, { id: '1' })]);
|
|
95
|
+
* await worker.scheduled('0 3 * * *');
|
|
96
|
+
* await worker.close();
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
async function createTestingWorker(rootModule, options = {}) {
|
|
100
|
+
const { env: env$1 = env, overrides, configure, ...appOptions } = options;
|
|
101
|
+
const builder = Test.createTestingModule({ imports: [rootModule] }, cloudflareCreateOptions({
|
|
102
|
+
...appOptions,
|
|
103
|
+
env: env$1
|
|
104
|
+
}));
|
|
105
|
+
const module = await (overrides ? overrides(builder) : builder).compile();
|
|
106
|
+
let app;
|
|
107
|
+
try {
|
|
108
|
+
app = await configureCloudflareApplication(new CloudflareApplication(await module.createApplication(), env$1), env$1, configure);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
await module.close();
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
const contexts = /* @__PURE__ */ new Set();
|
|
114
|
+
const context = () => {
|
|
115
|
+
const ctx = pool.createExecutionContext();
|
|
116
|
+
contexts.add(ctx);
|
|
117
|
+
return ctx;
|
|
118
|
+
};
|
|
119
|
+
const responses = /* @__PURE__ */ new Set();
|
|
120
|
+
return {
|
|
121
|
+
module,
|
|
122
|
+
env: env$1,
|
|
123
|
+
async fetch(input, init) {
|
|
124
|
+
const request = typeof input === "string" && input.startsWith("/") ? new Request(new URL(input, "http://localhost"), init) : new Request(input, init);
|
|
125
|
+
const response = await app.fetch(request, env$1, context());
|
|
126
|
+
responses.add(response);
|
|
127
|
+
return response;
|
|
128
|
+
},
|
|
129
|
+
async queue(queue, messages) {
|
|
130
|
+
const batch = pool.createMessageBatch(queue, messages.map((message) => ({
|
|
131
|
+
id: message.id ?? crypto.randomUUID(),
|
|
132
|
+
timestamp: message.timestamp ?? Date.now(),
|
|
133
|
+
attempts: message.attempts ?? 1,
|
|
134
|
+
body: message.body
|
|
135
|
+
})));
|
|
136
|
+
const ctx = context();
|
|
137
|
+
try {
|
|
138
|
+
await app.queue(batch, env$1, ctx);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
return {
|
|
141
|
+
...await pool.getQueueResult(batch, ctx),
|
|
142
|
+
outcome: "exception",
|
|
143
|
+
error
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
...await pool.getQueueResult(batch, ctx),
|
|
148
|
+
outcome: "ok"
|
|
149
|
+
};
|
|
150
|
+
},
|
|
151
|
+
async scheduled(cron, { scheduledTime } = {}) {
|
|
152
|
+
const declared = app.entrypoints.ofKind("schedule:cron", parseCronMetadata).map((entry) => entry.meta.expression);
|
|
153
|
+
if (!declared.includes(cron)) throw new Error(`No @Cron job declares ${JSON.stringify(cron)}. Declared: ${declared.map((expression) => JSON.stringify(expression)).join(", ") || "(none)"}.`);
|
|
154
|
+
const ctx = context();
|
|
155
|
+
await app.scheduled(pool.createScheduledController({
|
|
156
|
+
cron,
|
|
157
|
+
scheduledTime
|
|
158
|
+
}), env$1, ctx);
|
|
159
|
+
await pool.waitOnExecutionContext(ctx);
|
|
160
|
+
},
|
|
161
|
+
email: (message) => dispatchEmail(app, message),
|
|
162
|
+
tail: (events) => dispatchTail(app, events),
|
|
163
|
+
async close() {
|
|
164
|
+
await Promise.all([...responses].map((response) => response.bodyUsed ? void 0 : response.body?.cancel().catch(() => {})));
|
|
165
|
+
responses.clear();
|
|
166
|
+
await Promise.all([...contexts].map((ctx) => pool.waitOnExecutionContext(ctx)));
|
|
167
|
+
contexts.clear();
|
|
168
|
+
await module.close();
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
function queueJob(queue, job, data, { id = crypto.randomUUID(), attempts = 1 } = {}) {
|
|
173
|
+
return {
|
|
174
|
+
id,
|
|
175
|
+
attempts,
|
|
176
|
+
body: {
|
|
177
|
+
id,
|
|
178
|
+
queue,
|
|
179
|
+
name: typeof job === "string" ? job : job.name,
|
|
180
|
+
data,
|
|
181
|
+
attempt: attempts
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
//#endregion
|
|
186
|
+
export { createTestingWorker, emailMessage, queueJob, traceItem };
|
|
187
|
+
|
|
188
|
+
//# sourceMappingURL=testing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"testing.js","names":["workersEnv","env"],"sources":["../src/testing.ts"],"sourcesContent":["import './vela-env';\n// @ts-expect-error `cloudflare:test` is the virtual module of the Workers Vitest pool\n// (@cloudflare/vitest-plugin); it is typed below instead of by this package's build.\nimport * as cloudflareTest from 'cloudflare:test';\nimport { env as workersEnv } from 'cloudflare:workers';\nimport type { VelaEnv } from '@velajs/vela';\nimport { parseCronMetadata } from '@velajs/vela/module-kit';\nimport type { QueueJob, QueueJobDefinition, QueueJobInput } from '@velajs/vela/queue';\nimport { Test, type TestingModule, type TestingModuleBuilder } from '@velajs/testing';\nimport { CloudflareApplication } from './cloudflare-application';\nimport {\n cloudflareCreateOptions,\n configureCloudflareApplication,\n type CloudflareWorkerOptions,\n} from './cloudflare-factory';\nimport { dispatchEmail } from './email/email-dispatch';\nimport type { CloudflareRoot } from './root-module';\nimport { dispatchTail } from './tail/tail-dispatch';\n\n/** The `cloudflare:test` helpers this module drives (see @cloudflare/vitest-plugin). */\ninterface WorkersTestPool {\n createExecutionContext(): ExecutionContext;\n waitOnExecutionContext(ctx: ExecutionContext): Promise<void>;\n createScheduledController(options?: {\n scheduledTime?: Date | number;\n cron?: string;\n }): ScheduledController;\n createMessageBatch<Body>(\n queueName: string,\n messages: { id: string; timestamp: Date | number; attempts: number; body: Body }[],\n ): MessageBatch<Body>;\n getQueueResult(\n batch: MessageBatch,\n ctx: ExecutionContext,\n ): Promise<Omit<TestingQueueResult, 'error'>>;\n}\n\nconst pool: WorkersTestPool = cloudflareTest;\n\nexport interface TestingWorkerOptions extends CloudflareWorkerOptions {\n /**\n * The Workers environment the application is built for and every event\n * carries. Defaults to the test Worker's `env` from `cloudflare:workers`,\n * with the bindings the Vitest pool's Wrangler configuration declares.\n */\n env?: VelaEnv;\n /**\n * Adjust the testing module before it compiles: `overrideProvider`,\n * `overrideModule().useModule()`, enhancer overrides and `useMocker`.\n */\n overrides?: (module: TestingModuleBuilder) => TestingModuleBuilder;\n}\n\n/** One message of a {@link TestingWorker.queue} batch. */\nexport interface TestingQueueMessage<Body = unknown> {\n readonly body: Body;\n /** Defaults to a random UUID. */\n readonly id?: string;\n /** The delivery attempt, 1-based; defaults to 1. */\n readonly attempts?: number;\n readonly timestamp?: Date | number;\n}\n\n/** What the queue handler did with a batch: `cloudflare:test`'s `getQueueResult()`, plus its outcome. */\nexport interface TestingQueueResult {\n /** `'exception'` when the handler rejected: Cloudflare then retries every message it did not acknowledge. */\n readonly outcome: 'ok' | 'exception';\n /** The handler's rejection, when `outcome` is `'exception'`. */\n readonly error?: unknown;\n readonly ackAll: boolean;\n readonly retryBatch: { readonly retry: boolean; readonly delaySeconds?: number };\n /** Ids of the messages acknowledged one by one. */\n readonly explicitAcks: readonly string[];\n readonly retryMessages: readonly { readonly msgId: string; readonly delaySeconds?: number }[];\n}\n\n/** The Worker's `fetch`, `queue`, `scheduled`, `email` and `tail` handlers for one test application. */\nexport interface TestingWorker {\n /** The compiled testing module: `get()`, `resolveInRequest()`, the fluent `http` client. */\n readonly module: TestingModule;\n readonly env: VelaEnv;\n /** Send a request through the Worker's `fetch` handler; a path resolves against `http://localhost`. */\n fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;\n /** Deliver one batch of the physical `queue` to the Worker's `queue` handler. */\n queue(queue: string, messages: readonly TestingQueueMessage[]): Promise<TestingQueueResult>;\n /**\n * Fire the cron trigger `cron` and wait for its `@Cron` jobs. Rejects when\n * no job declares `cron`: Cloudflare delivers the literal trigger expression.\n */\n scheduled(cron: string, options?: { scheduledTime?: Date | number }): Promise<void>;\n /**\n * Deliver an Email Workers message (such as one from {@link emailMessage})\n * to the application's `@OnEmail()` handlers, as the Worker's `email`\n * handler does: a message no handler accepts is rejected.\n */\n email(message: ForwardableEmailMessage): Promise<void>;\n /** Deliver Tail Workers events (such as {@link traceItem}s) to its `@OnTail()` handlers. */\n tail(events: TraceItem[]): Promise<void>;\n /** Wait for background work (`waitUntil`) of every event, then close the application. */\n close(): Promise<void>;\n}\n\n/** An Email Workers message built by {@link emailMessage}, recording what handlers did with it. */\nexport interface TestingEmailMessage extends ForwardableEmailMessage {\n /** The reason passed to `setReject()`, when a handler rejected the message. */\n readonly rejectReason: string | undefined;\n /** The `forward()` calls, in order. */\n readonly forwards: readonly { readonly rcptTo: string; readonly headers?: Headers }[];\n /** The `reply()` calls, in order. */\n readonly replies: readonly (EmailMessage | EmailReplyMessageBuilder)[];\n}\n\n/** What {@link emailMessage} builds a message from. */\nexport interface TestingEmailInit {\n /** The envelope sender (`MAIL FROM`). */\n readonly from: string;\n /** The envelope recipient (`RCPT TO`), which `@OnEmail({ to })` routes on. */\n readonly to: string;\n readonly subject?: string;\n /** The plain-text body of the default raw message. */\n readonly text?: string;\n /** Further headers; `From`, `To` and `Subject` default from the fields above. */\n readonly headers?: HeadersInit;\n /** The raw RFC 5322 message; built from the headers and `text` by default. */\n readonly raw?: string | Uint8Array;\n}\n\n/**\n * An Email Workers message (`ForwardableEmailMessage`) for tests, in the\n * spirit of `cloudflare:test`'s `createMessageBatch()`: `raw`, `rawSize` and\n * `headers` describe the message, and `setReject()`, `forward()` and `reply()`\n * record what the handlers did (`rejectReason`, `forwards`, `replies`) instead\n * of sending anything.\n *\n * ```ts\n * const message = emailMessage({ from: 'ada@example.net', to: 'support@example.com', subject: 'Help' });\n * await worker.email(message);\n * expect(message.forwards).toEqual([{ rcptTo: 'team@example.com' }]);\n * ```\n */\nexport function emailMessage(init: TestingEmailInit): TestingEmailMessage {\n const headers = new Headers(init.headers);\n if (!headers.has('from')) headers.set('from', init.from);\n if (!headers.has('to')) headers.set('to', init.to);\n if (init.subject !== undefined && !headers.has('subject')) headers.set('subject', init.subject);\n const raw =\n init.raw ??\n `${[...headers].map(([name, value]) => `${name}: ${value}`).join('\\r\\n')}\\r\\n\\r\\n${init.text ?? ''}`;\n const bytes = typeof raw === 'string' ? new TextEncoder().encode(raw) : raw;\n let rejectReason: string | undefined;\n const forwards: { rcptTo: string; headers?: Headers }[] = [];\n const replies: (EmailMessage | EmailReplyMessageBuilder)[] = [];\n return {\n from: init.from,\n to: init.to,\n headers,\n rawSize: bytes.byteLength,\n raw: new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(bytes.slice());\n controller.close();\n },\n }),\n get rejectReason() {\n return rejectReason;\n },\n forwards,\n replies,\n setReject(reason: string): void {\n rejectReason = reason;\n },\n async forward(rcptTo: string, forwardHeaders?: Headers): Promise<EmailSendResult> {\n forwards.push(\n forwardHeaders === undefined ? { rcptTo } : { rcptTo, headers: forwardHeaders },\n );\n return { messageId: `forward-${forwards.length}@vela.test` };\n },\n async reply(message: EmailMessage | EmailReplyMessageBuilder): Promise<EmailSendResult> {\n replies.push(message);\n return { messageId: `reply-${replies.length}@vela.test` };\n },\n };\n}\n\n/**\n * A Tail Workers event (`TraceItem`) for tests: an `ok` fetch-less invocation\n * of the Worker `producer`, with `overrides` applied.\n */\nexport function traceItem(overrides: Partial<TraceItem> = {}): TraceItem {\n return {\n event: null,\n eventTimestamp: Date.now(),\n logs: [],\n exceptions: [],\n diagnosticsChannelEvents: [],\n scriptName: 'producer',\n outcome: 'ok',\n executionModel: 'stateless',\n truncated: false,\n cpuTime: 0,\n wallTime: 0,\n ...overrides,\n };\n}\n\n/**\n * Build `rootModule` as `createCloudflareWorker(rootModule, options)` does\n * (its adapters, then its `configure` hook), through `@velajs/testing`, and\n * drive its Worker handlers inside the Workers Vitest pool.\n *\n * ```ts\n * const worker = await createTestingWorker(AppModule, {\n * overrides: (module) => module.overrideProvider(Mailer).useValue(fakeMailer),\n * });\n * const response = await worker.fetch('/todos');\n * const result = await worker.queue('todo-events', [queueJob('todos', todoCreated, { id: '1' })]);\n * await worker.scheduled('0 3 * * *');\n * await worker.close();\n * ```\n */\nexport async function createTestingWorker(\n rootModule: CloudflareRoot,\n options: TestingWorkerOptions = {},\n): Promise<TestingWorker> {\n const { env = workersEnv, overrides, configure, ...appOptions } = options;\n const builder = Test.createTestingModule(\n { imports: [rootModule] },\n cloudflareCreateOptions({ ...appOptions, env }),\n );\n const module = await (overrides ? overrides(builder) : builder).compile();\n let app: CloudflareApplication;\n try {\n app = await configureCloudflareApplication(\n new CloudflareApplication(await module.createApplication(), env),\n env,\n configure,\n );\n } catch (error) {\n await module.close();\n throw error;\n }\n const contexts = new Set<ExecutionContext>();\n const context = (): ExecutionContext => {\n const ctx = pool.createExecutionContext();\n contexts.add(ctx);\n return ctx;\n };\n // A request completes once its response body is consumed: close() cancels\n // the bodies a test never read, so waiting for its background work ends.\n const responses = new Set<Response>();\n return {\n module,\n env,\n async fetch(input, init) {\n const request =\n typeof input === 'string' && input.startsWith('/')\n ? new Request(new URL(input, 'http://localhost'), init)\n : new Request(input, init);\n const response = await app.fetch(request, env, context());\n responses.add(response);\n return response;\n },\n async queue(queue, messages) {\n const batch = pool.createMessageBatch(\n queue,\n messages.map((message) => ({\n id: message.id ?? crypto.randomUUID(),\n timestamp: message.timestamp ?? Date.now(),\n attempts: message.attempts ?? 1,\n body: message.body,\n })),\n );\n const ctx = context();\n try {\n await app.queue(batch, env, ctx);\n } catch (error) {\n return { ...(await pool.getQueueResult(batch, ctx)), outcome: 'exception', error };\n }\n return { ...(await pool.getQueueResult(batch, ctx)), outcome: 'ok' };\n },\n async scheduled(cron, { scheduledTime } = {}) {\n const declared = app.entrypoints\n .ofKind('schedule:cron', parseCronMetadata)\n .map((entry) => entry.meta.expression);\n if (!declared.includes(cron)) {\n throw new Error(\n `No @Cron job declares ${JSON.stringify(cron)}. Declared: ` +\n `${declared.map((expression) => JSON.stringify(expression)).join(', ') || '(none)'}.`,\n );\n }\n const ctx = context();\n await app.scheduled(pool.createScheduledController({ cron, scheduledTime }), env, ctx);\n await pool.waitOnExecutionContext(ctx);\n },\n email: (message) => dispatchEmail(app, message),\n tail: (events) => dispatchTail(app, events),\n async close() {\n await Promise.all(\n [...responses].map((response) =>\n response.bodyUsed ? undefined : response.body?.cancel().catch(() => {}),\n ),\n );\n responses.clear();\n await Promise.all([...contexts].map((ctx) => pool.waitOnExecutionContext(ctx)));\n contexts.clear();\n await module.close();\n },\n };\n}\n\n/**\n * A queue message carrying a Vela job envelope, as `QueueClient.add()` sends\n * it: `queue` is the logical queue a `@Processor` handles, and `job` a job\n * definition (whose wire input `data` must match) or a job name.\n */\nexport function queueJob<const D extends QueueJobDefinition>(\n queue: string,\n job: D,\n data: QueueJobInput<D>,\n options?: { id?: string; attempts?: number },\n): TestingQueueMessage<QueueJob>;\nexport function queueJob(\n queue: string,\n job: string,\n data: unknown,\n options?: { id?: string; attempts?: number },\n): TestingQueueMessage<QueueJob>;\nexport function queueJob(\n queue: string,\n job: string | QueueJobDefinition,\n data: unknown,\n { id = crypto.randomUUID(), attempts = 1 }: { id?: string; attempts?: number } = {},\n): TestingQueueMessage<QueueJob> {\n const name = typeof job === 'string' ? job : job.name;\n return { id, attempts, body: { id, queue, name, data, attempt: attempts } };\n}\n"],"mappings":";;;;;;;;;AAqCA,MAAM,OAAwB;;;;;;;;;;;;;;AAuG9B,SAAgB,aAAa,MAA6C;CACxE,MAAM,UAAU,IAAI,QAAQ,KAAK,OAAO;CACxC,IAAI,CAAC,QAAQ,IAAI,MAAM,GAAG,QAAQ,IAAI,QAAQ,KAAK,IAAI;CACvD,IAAI,CAAC,QAAQ,IAAI,IAAI,GAAG,QAAQ,IAAI,MAAM,KAAK,EAAE;CACjD,IAAI,KAAK,YAAY,KAAA,KAAa,CAAC,QAAQ,IAAI,SAAS,GAAG,QAAQ,IAAI,WAAW,KAAK,OAAO;CAC9F,MAAM,M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|
+
import { WS_GATEWAY_METADATA, WS_SERVER } from "@velajs/vela/websocket";
|
|
3
|
+
//#region src/websocket/binding-gateways.ts
|
|
4
|
+
/**
|
|
5
|
+
* The application's gateways that name a `binding`, in discovery order, once
|
|
6
|
+
* per path. Read from decorator metadata, so lifecycle hooks can use it.
|
|
7
|
+
*/
|
|
8
|
+
function bindingGateways(discovery) {
|
|
9
|
+
const gateways = /* @__PURE__ */ new Map();
|
|
10
|
+
for (const { metatype, meta } of discovery.providersWithMeta(WS_GATEWAY_METADATA, { metadataOnly: true })) {
|
|
11
|
+
const path = meta.path ?? "";
|
|
12
|
+
if (typeof meta.binding !== "string" || gateways.has(path)) continue;
|
|
13
|
+
gateways.set(path, {
|
|
14
|
+
path,
|
|
15
|
+
binding: meta.binding,
|
|
16
|
+
name: metatype.name
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
return [...gateways.values()];
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* `WebSocketModule` mounts the Worker's upgrade routes. An application with a
|
|
23
|
+
* binding-backed gateway but without that module answers its upgrades with
|
|
24
|
+
* 404, so report each such gateway through the diagnostics policy.
|
|
25
|
+
*/
|
|
26
|
+
function reportUnservedGateways(container, discovery) {
|
|
27
|
+
if (container.has(WS_SERVER)) return;
|
|
28
|
+
for (const { name, binding, path } of bindingGateways(discovery)) reportDiagnostic(container, `[vela] ${name} is a @WebSocketGateway with binding '${binding}', but the application does not import WebSocketModule.forRoot() from @velajs/vela/websocket, so upgrades to '${path}' answer 404 instead of reaching its Durable Object.`);
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
export { bindingGateways, reportUnservedGateways };
|
|
32
|
+
|
|
33
|
+
//# sourceMappingURL=binding-gateways.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"binding-gateways.js","names":[],"sources":["../../src/websocket/binding-gateways.ts"],"sourcesContent":["import type { Container, DiscoveryService } from '@velajs/vela/module-kit';\nimport {\n WS_GATEWAY_METADATA,\n WS_SERVER,\n type WebSocketGatewayOptions,\n} from '@velajs/vela/websocket';\nimport { reportDiagnostic } from '../diagnostics';\n\n/** A gateway whose rooms live in Durable Objects: its path and namespace binding. */\nexport interface BindingGateway {\n path: string;\n binding: string;\n /** The gateway class name, for diagnostics. */\n name: string;\n}\n\n/**\n * The application's gateways that name a `binding`, in discovery order, once\n * per path. Read from decorator metadata, so lifecycle hooks can use it.\n */\nexport function bindingGateways(discovery: DiscoveryService): BindingGateway[] {\n const gateways = new Map<string, BindingGateway>();\n for (const { metatype, meta } of discovery.providersWithMeta<WebSocketGatewayOptions>(\n WS_GATEWAY_METADATA,\n { metadataOnly: true },\n )) {\n const path = meta.path ?? '';\n if (typeof meta.binding !== 'string' || gateways.has(path)) continue;\n gateways.set(path, {\n path,\n binding: meta.binding,\n name: metatype.name,\n });\n }\n return [...gateways.values()];\n}\n\n/**\n * `WebSocketModule` mounts the Worker's upgrade routes. An application with a\n * binding-backed gateway but without that module answers its upgrades with\n * 404, so report each such gateway through the diagnostics policy.\n */\nexport function reportUnservedGateways(container: Container, discovery: DiscoveryService): void {\n if (container.has(WS_SERVER)) return;\n for (const { name, binding, path } of bindingGateways(discovery)) {\n reportDiagnostic(\n container,\n `[vela] ${name} is a @WebSocketGateway with binding '${binding}', but the application ` +\n `does not import WebSocketModule.forRoot() from @velajs/vela/websocket, so upgrades ` +\n `to '${path}' answer 404 instead of reaching its Durable Object.`,\n );\n }\n}\n"],"mappings":";;;;;;;AAoBA,SAAgB,gBAAgB,WAA+C;CAC7E,MAAM,2BAAW,IAAI,IAA4B;CACjD,KAAK,MAAM,EAAE,UAAU,UAAU,UAAU,kBACzC,qBACA,EAAE,cAAc,KAAK,CACvB,GAAG;EACD,MAAM,OAAO,KAAK,QAAQ;EAC1B,IAAI,OAAO,KAAK,YAAY,YAAY,SAAS,IAAI,IAAI,GAAG;EAC5D,SAAS,IAAI,MAAM;GACjB;GACA,SAAS,KAAK;GACd,MAAM,SAAS;EACjB,CAAC;CACH;CACA,OAAO,CAAC,GAAG,SAAS,OAAO,CAAC;AAC9B;;;;;;AAOA,SAAgB,uBAAuB,WAAsB,WAAmC;CAC9F,IAAI,UAAU,IAAI,SAAS,GAAG;CAC9B,KAAK,MAAM,EAAE,MAAM,SAAS,UAAU,gBAAgB,SAAS,GAC7D,iBACE,WACA,UAAU,KAAK,wCAAwC,QAAQ,gHAEtD,KAAK,qDAChB;AAEJ"}
|
|
@@ -59,7 +59,9 @@ var CfRoomRegistry = class {
|
|
|
59
59
|
const seen = /* @__PURE__ */ new Set();
|
|
60
60
|
const selected = [];
|
|
61
61
|
for (const ws of targets) {
|
|
62
|
-
const
|
|
62
|
+
const stored = this.attachmentOf(ws);
|
|
63
|
+
if (cmd.gatewayPath !== void 0 && stored.path !== cmd.gatewayPath) continue;
|
|
64
|
+
const att = this.reconcileFrameLimit(ws, stored);
|
|
63
65
|
if (att.state === "pending" && this.#admitting.has(ws)) continue;
|
|
64
66
|
if (att.state !== "active" || att.expiresAtMs !== void 0 && (!Number.isSafeInteger(att.expiresAtMs) || att.expiresAtMs <= Date.now())) {
|
|
65
67
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cf-room-registry.js","names":[],"sources":["../../src/websocket/cf-room-registry.ts"],"sourcesContent":["import { WebSocketSendGate, type WebSocketSendPolicy } from '@velajs/vela/websocket';\nimport { socketAttachment, rejectedAttachment } from './ws-attachment';\nimport type { BroadcastCommand, RoomRegistry, WsClient } from '@velajs/vela/websocket';\nimport type { DoStateLike, WsAttachment, WsLike } from './do-state';\nimport { CfWsClient } from './cf-ws-client';\n\n/**\n * Core `RoomRegistry` backed by a Durable Object's hibernatable sockets. Room\n * membership lives in tags (hub room, set at accept) + the attachment (dynamic\n * `join()`), never in DO instance fields — so it survives hibernation with zero\n * rehydration.\n */\nexport class CfRoomRegistry implements RoomRegistry {\n readonly #sendGates = new WeakMap<WsLike, WebSocketSendGate>();\n // Sockets whose OnGatewayConnection hook is running in this instance. They\n // are still `pending`, so broadcasts skip them; any other pending socket\n // never finished admission and is closed when a broadcast reaches it.\n readonly #admitting = new WeakSet<WsLike>();\n #sendPolicyForPath?: (path: string) => WebSocketSendPolicy | undefined;\n\n setSendPolicyResolver(resolve: (path: string) => WebSocketSendPolicy | undefined): void {\n this.#sendPolicyForPath = resolve;\n }\n\n private deliveryAuthorizer?: (client: WsClient) => boolean | Promise<boolean>;\n private frameLimitForPath?: (path: string) => number | undefined;\n\n constructor(private readonly ctx: DoStateLike) {}\n\n setDeliveryAuthorizer(authorizer: (client: WsClient) => boolean | Promise<boolean>): void {\n this.deliveryAuthorizer = authorizer;\n }\n\n /** Reconcile pre-migration/woken attachments with authoritative gateway metadata. */\n setFrameLimitResolver(resolver: (path: string) => number | undefined): void {\n this.frameLimitForPath = resolver;\n }\n\n /**\n * Run `admit` (the connection hook) with `ws` marked as being admitted, so a\n * broadcast issued meanwhile (for example `server.emit()` announcing the new\n * connection) skips the still-pending socket instead of rejecting it.\n */\n async admitting<T>(ws: WsLike, admit: () => Promise<T>): Promise<T> {\n this.#admitting.add(ws);\n try {\n return await admit();\n } finally {\n this.#admitting.delete(ws);\n }\n }\n\n // CF sockets are registered with the DO by `acceptWebSocket`; nothing to track.\n register(_client: WsClient): void {}\n leaveAll(_client: WsClient): void {}\n\n join(client: WsClient, room: string): void | Promise<void> {\n return client.join(room);\n }\n\n leave(client: WsClient, room: string): void | Promise<void> {\n return client.leave(room);\n }\n\n localIdsInRoom(room: string): string[] {\n return this.socketsForRoom(room).map((ws) => this.attachmentOf(ws).connId);\n }\n\n deliverLocal(cmd: BroadcastCommand): void | Promise<void> {\n const excludeIds = new Set(cmd.exceptIds ?? []);\n const excludeRooms = cmd.exceptRooms ?? [];\n\n // Empty `rooms` => GLOBAL (every socket in this DO). Otherwise the union of\n // targeted rooms, deduped per connection.\n const targets =\n cmd.rooms.length === 0 ? this.ctx.getWebSockets() : this.collectRooms(cmd.rooms);\n\n const seen = new Set<string>();\n const selected: Array<{ ws: WsLike; client: WsClient }> = [];\n for (const ws of targets) {\n const
|
|
1
|
+
{"version":3,"file":"cf-room-registry.js","names":[],"sources":["../../src/websocket/cf-room-registry.ts"],"sourcesContent":["import { WebSocketSendGate, type WebSocketSendPolicy } from '@velajs/vela/websocket';\nimport { socketAttachment, rejectedAttachment } from './ws-attachment';\nimport type { BroadcastCommand, RoomRegistry, WsClient } from '@velajs/vela/websocket';\nimport type { DoStateLike, WsAttachment, WsLike } from './do-state';\nimport { CfWsClient } from './cf-ws-client';\n\n/**\n * Core `RoomRegistry` backed by a Durable Object's hibernatable sockets. Room\n * membership lives in tags (hub room, set at accept) + the attachment (dynamic\n * `join()`), never in DO instance fields — so it survives hibernation with zero\n * rehydration.\n */\nexport class CfRoomRegistry implements RoomRegistry {\n readonly #sendGates = new WeakMap<WsLike, WebSocketSendGate>();\n // Sockets whose OnGatewayConnection hook is running in this instance. They\n // are still `pending`, so broadcasts skip them; any other pending socket\n // never finished admission and is closed when a broadcast reaches it.\n readonly #admitting = new WeakSet<WsLike>();\n #sendPolicyForPath?: (path: string) => WebSocketSendPolicy | undefined;\n\n setSendPolicyResolver(resolve: (path: string) => WebSocketSendPolicy | undefined): void {\n this.#sendPolicyForPath = resolve;\n }\n\n private deliveryAuthorizer?: (client: WsClient) => boolean | Promise<boolean>;\n private frameLimitForPath?: (path: string) => number | undefined;\n\n constructor(private readonly ctx: DoStateLike) {}\n\n setDeliveryAuthorizer(authorizer: (client: WsClient) => boolean | Promise<boolean>): void {\n this.deliveryAuthorizer = authorizer;\n }\n\n /** Reconcile pre-migration/woken attachments with authoritative gateway metadata. */\n setFrameLimitResolver(resolver: (path: string) => number | undefined): void {\n this.frameLimitForPath = resolver;\n }\n\n /**\n * Run `admit` (the connection hook) with `ws` marked as being admitted, so a\n * broadcast issued meanwhile (for example `server.emit()` announcing the new\n * connection) skips the still-pending socket instead of rejecting it.\n */\n async admitting<T>(ws: WsLike, admit: () => Promise<T>): Promise<T> {\n this.#admitting.add(ws);\n try {\n return await admit();\n } finally {\n this.#admitting.delete(ws);\n }\n }\n\n // CF sockets are registered with the DO by `acceptWebSocket`; nothing to track.\n register(_client: WsClient): void {}\n leaveAll(_client: WsClient): void {}\n\n join(client: WsClient, room: string): void | Promise<void> {\n return client.join(room);\n }\n\n leave(client: WsClient, room: string): void | Promise<void> {\n return client.leave(room);\n }\n\n localIdsInRoom(room: string): string[] {\n return this.socketsForRoom(room).map((ws) => this.attachmentOf(ws).connId);\n }\n\n deliverLocal(cmd: BroadcastCommand): void | Promise<void> {\n const excludeIds = new Set(cmd.exceptIds ?? []);\n const excludeRooms = cmd.exceptRooms ?? [];\n\n // Empty `rooms` => GLOBAL (every socket in this DO). Otherwise the union of\n // targeted rooms, deduped per connection.\n const targets =\n cmd.rooms.length === 0 ? this.ctx.getWebSockets() : this.collectRooms(cmd.rooms);\n\n const seen = new Set<string>();\n const selected: Array<{ ws: WsLike; client: WsClient }> = [];\n for (const ws of targets) {\n const stored = this.attachmentOf(ws);\n // A gateway-scoped push never touches another gateway's sockets.\n if (cmd.gatewayPath !== undefined && stored.path !== cmd.gatewayPath) continue;\n const att = this.reconcileFrameLimit(ws, stored);\n // A socket still in its connection hook is not admitted yet: it receives no\n // room frames, and its own accept() settles it. Rejecting it here would\n // close every client whose handleConnection broadcasts to the room. Other\n // pending sockets fall through and are rejected below.\n if (att.state === 'pending' && this.#admitting.has(ws)) continue;\n if (\n att.state !== 'active' ||\n (att.expiresAtMs !== undefined &&\n (!Number.isSafeInteger(att.expiresAtMs) || att.expiresAtMs <= Date.now()))\n ) {\n try {\n att.state = 'rejected';\n ws.serializeAttachment(att);\n ws.close(1008, 'identity expired or connection rejected');\n } catch {\n // already closed or malformed attachment\n }\n continue;\n }\n if (seen.has(att.connId)) continue;\n seen.add(att.connId);\n if (excludeIds.has(att.connId)) continue;\n if (excludeRooms.some((r) => att.rooms.includes(r))) continue;\n selected.push({ ws, client: this.clientFor(ws) });\n }\n\n if (!this.deliveryAuthorizer) {\n for (const { client } of selected) client.sendRaw(cmd.frame);\n return;\n }\n return Promise.all(\n selected.map(async ({ ws, client }) => {\n let allowed = false;\n try {\n allowed = (await this.deliveryAuthorizer!(client)) === true;\n } catch {\n allowed = false;\n }\n if (allowed) client.sendRaw(cmd.frame);\n else this.reject(ws, 'delivery authorization revoked');\n }),\n ).then(() => undefined);\n }\n\n private collectRooms(rooms: string[]): WsLike[] {\n const set = new Set<WsLike>();\n for (const room of rooms) for (const ws of this.socketsForRoom(room)) set.add(ws);\n return [...set];\n }\n\n private socketsForRoom(room: string): WsLike[] {\n // Membership is the attachment's `rooms`, NOT the hibernation tag: tags are\n // immutable after acceptWebSocket, so a socket that left its hub room still\n // carries the tag. Since one DO ≈ one room, scanning all sockets in the DO\n // and filtering by attachment is both correct and cheap.\n return this.ctx.getWebSockets().filter((ws) => this.attachmentOf(ws).rooms.includes(room));\n }\n\n private attachmentOf(ws: WsLike): WsAttachment {\n return socketAttachment(ws) ?? rejectedAttachment();\n }\n\n /** Reconstruct a `WsClient` for a raw socket (e.g. inside gateway lifecycle scans). */\n clientFor(ws: WsLike): CfWsClient {\n this.reconcileFrameLimit(ws, this.attachmentOf(ws));\n let gate = this.#sendGates.get(ws);\n if (!gate) {\n gate = new WebSocketSendGate(this.#sendPolicyForPath?.(this.attachmentOf(ws).path));\n this.#sendGates.set(ws, gate);\n }\n return new CfWsClient(this.ctx, ws, gate);\n }\n\n private reconcileFrameLimit(ws: WsLike, attachment: WsAttachment): WsAttachment {\n const expected = this.frameLimitForPath?.(attachment.path);\n if (expected !== undefined && attachment.maxFrameBytes !== expected) {\n attachment.maxFrameBytes = expected;\n ws.serializeAttachment(attachment);\n }\n return attachment;\n }\n\n private reject(ws: WsLike, reason: string): void {\n try {\n const attachment = this.attachmentOf(ws);\n attachment.state = 'rejected';\n ws.serializeAttachment(attachment);\n ws.close(1008, reason);\n } catch {\n // already closed or malformed attachment\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,I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AqB,IAA0B;EAC7C,OAAO,iBAAiB,EAAE,KAAK,mBAAmB;CACpD;;CAGA,UAAU,IAAwB;EAChC,KAAK,oBAAoB,IAAI,KAAK,aAAa,EAAE,CAAC;EAClD,IAAI,OAAO,KAAK,WAAW,IAAI,EAAE;EACjC,IAAI,CAAC,MAAM;GACT,OAAO,IAAI,kBAAkB,KAAK,qBAAqB,KAAK,aAAa,EAAE,CAAC,CAAC,IAAI,CAAC;GAClF,KAAK,WAAW,IAAI,IAAI,IAAI;EAC9B;EACA,OAAO,IAAI,WAAW,KAAK,KAAK,IAAI,IAAI;CAC1C;CAEA,oBAA4B,IAAY,YAAwC;EAC9E,MAAM,WAAW,KAAK,oBAAoB,WAAW,IAAI;EACzD,IAAI,aAAa,KAAA,KAAa,WAAW,kBAAkB,UAAU;GACnE,WAAW,gBAAgB;GAC3B,GAAG,oBAAoB,UAAU;EACnC;EACA,OAAO;CACT;CAEA,OAAe,IAAY,QAAsB;EAC/C,IAAI;GACF,MAAM,aAAa,KAAK,aAAa,EAAE;GACvC,WAAW,QAAQ;GACnB,GAAG,oBAAoB,UAAU;GACjC,GAAG,MAAM,MAAM,MAAM;EACvB,QAAQ,CAER;CACF;AACF"}
|
|
@@ -1,54 +1,78 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { gatewayRoomObject } from "./worker-transport.js";
|
|
2
2
|
import { CfWsClient } from "./cf-ws-client.js";
|
|
3
|
-
import {
|
|
4
|
-
import { WsServerHolder } from "./ws-server-holder.js";
|
|
3
|
+
import { durableObjectLivePlatform, initDoLive } from "./do-live.js";
|
|
5
4
|
import { CfRoomRegistry } from "./cf-room-registry.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import { bootstrap } from "@velajs/vela/internal";
|
|
5
|
+
import { createDurableObjectContext } from "../durable-object/boot.js";
|
|
6
|
+
import { WsDispatcher, WsServerImpl, local, readWsEntrypointMeta } from "@velajs/vela/websocket";
|
|
9
7
|
//#region src/websocket/do-bootstrap.ts
|
|
8
|
+
/** Whether a Durable Object id names this object. */
|
|
9
|
+
function isThisObject(id, ctx) {
|
|
10
|
+
const equals = typeof id === "object" && id !== null ? Reflect.get(id, "equals") : void 0;
|
|
11
|
+
if (typeof equals === "function") return Reflect.apply(equals, id, [ctx.id]) === true;
|
|
12
|
+
return String(id) === ctx.id.toString();
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* A `Gateways` push from inside a WebSocket Durable Object: this object's own
|
|
16
|
+
* gateway room is delivered to its sockets; any other room goes to that
|
|
17
|
+
* room's object over its broadcast RPC, as from the Worker.
|
|
18
|
+
*/
|
|
19
|
+
async function deliverFromDurableObject(ctx, env, registry, { gatewayPath, binding, room, command }) {
|
|
20
|
+
const target = gatewayRoomObject(env, gatewayPath, binding, room);
|
|
21
|
+
if (isThisObject(target.id, ctx)) await registry.deliverLocal(command);
|
|
22
|
+
else await target.call("broadcast", command);
|
|
23
|
+
}
|
|
10
24
|
/**
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
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.
|
|
16
34
|
*/
|
|
17
35
|
async function buildDoRuntime(rootModule, ctx, options) {
|
|
18
|
-
const { container, routeManager, loader } = await bootstrap(rootModule, { configureContainer: (container) => {
|
|
19
|
-
registerCloudflareEnvironment(container, options.env);
|
|
20
|
-
} });
|
|
21
36
|
const registry = new CfRoomRegistry(ctx);
|
|
22
37
|
const driver = local();
|
|
23
38
|
driver.bind(registry);
|
|
24
39
|
const server = new WsServerImpl(driver);
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
const dispatcher = wsEntrypoints[0]?.meta.dispatcher ?? app.get(WsDispatcher);
|
|
37
|
-
registry.setSendPolicyResolver((path) => wsEntrypoints.find((entry) => entry.meta.path === path)?.meta.options.sendPolicy);
|
|
38
|
-
registry.setFrameLimitResolver((path) => dispatcher.getGatewayMaxFrameBytes(path));
|
|
39
|
-
registry.setDeliveryAuthorizer((client) => {
|
|
40
|
-
const path = client instanceof CfWsClient ? client.path : "";
|
|
41
|
-
return dispatcher.authorizeDelivery(path, client);
|
|
40
|
+
const context = await createDurableObjectContext(rootModule, {
|
|
41
|
+
env: options.env,
|
|
42
|
+
adapters: options.adapters,
|
|
43
|
+
state: options.state,
|
|
44
|
+
platform: () => ({
|
|
45
|
+
websocket: {
|
|
46
|
+
createServer: () => server,
|
|
47
|
+
deliver: (delivery) => deliverFromDurableObject(ctx, options.env, registry, delivery)
|
|
48
|
+
},
|
|
49
|
+
live: durableObjectLivePlatform(ctx)
|
|
50
|
+
})
|
|
42
51
|
});
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
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
|
+
}
|
|
52
76
|
}
|
|
53
77
|
//#endregion
|
|
54
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,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