@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
|
@@ -1,15 +1,6 @@
|
|
|
1
|
+
import { reportDiagnostic } from "./diagnostics.js";
|
|
1
2
|
import { cronDialectAmbiguity, parseCronMetadata, parseIntervalMetadata, scheduledJobComponents } from "@velajs/vela/module-kit";
|
|
2
3
|
//#region src/schedule-diagnostics.ts
|
|
3
|
-
const reported = /* @__PURE__ */ new Set();
|
|
4
|
-
/** `'throw'` fails the caller, `'log'` warns once per message in this isolate. */
|
|
5
|
-
function reportScheduleDiagnostic(container, message) {
|
|
6
|
-
const mode = container.getDiagnostics();
|
|
7
|
-
if (mode === "silent") return;
|
|
8
|
-
if (mode === "throw") throw new Error(message);
|
|
9
|
-
if (reported.has(message)) return;
|
|
10
|
-
reported.add(message);
|
|
11
|
-
console.warn(message);
|
|
12
|
-
}
|
|
13
4
|
function jobName(entry) {
|
|
14
5
|
return `${typeof entry.token === "function" ? entry.token.name : String(entry.token)}.${entry.meta.methodName}`;
|
|
15
6
|
}
|
|
@@ -20,7 +11,9 @@ function jobName(entry) {
|
|
|
20
11
|
function reportComponents(container, label, entry) {
|
|
21
12
|
const decorators = scheduledJobComponents(container, entry);
|
|
22
13
|
if (decorators.length === 0) return;
|
|
23
|
-
|
|
14
|
+
const named = decorators.length > 1 ? `${decorators.slice(0, -1).join(", ")} and ${decorators.at(-1)}` : decorators.join("");
|
|
15
|
+
const refused = decorators.includes("@UseGuards") ? ", and one that declares guards refuses to run" : "";
|
|
16
|
+
reportDiagnostic(container, `[vela] ${label} declares ${named}, which do not run for scheduled jobs: a direct job runs no guards, interceptors or filters${refused}. Use signed ScheduleModule dispatch and declare them on the signed route to run the job through the request pipeline.`);
|
|
24
17
|
}
|
|
25
18
|
/**
|
|
26
19
|
* Report schedule declarations a Workers cron trigger cannot honor as written:
|
|
@@ -38,12 +31,12 @@ function reportCloudflareScheduleDiagnostics(container, entrypoints) {
|
|
|
38
31
|
for (const entry of entrypoints.ofKind("schedule:cron", parseCronMetadata)) {
|
|
39
32
|
const cron = `@Cron('${entry.meta.expression}') on ${jobName(entry)}`;
|
|
40
33
|
const ambiguity = cronDialectAmbiguity(entry.meta);
|
|
41
|
-
if (ambiguity)
|
|
42
|
-
if (entry.meta.dialect === "unix")
|
|
43
|
-
if (entry.meta.timeZone === "local")
|
|
34
|
+
if (ambiguity) reportDiagnostic(container, `[vela] ${cron} declares no dialect, and ${ambiguity}. Workers deliver the trigger with Cloudflare semantics while Node reads it with Vela's unix dialect; declare { dialect: 'cloudflare' } so it fires on the same days on every runtime.`);
|
|
35
|
+
if (entry.meta.dialect === "unix") reportDiagnostic(container, `[vela] ${cron} declares dialect 'unix', but Cloudflare delivers its trigger with Cloudflare cron semantics (weekdays 1 = Sunday through 7 = Saturday). Declare { dialect: 'cloudflare' } and write the expression for Cloudflare.`);
|
|
36
|
+
if (entry.meta.timeZone === "local") reportDiagnostic(container, `[vela] ${cron} declares timeZone 'local', but Cloudflare cron triggers run in UTC. Remove timeZone or set it to 'UTC'.`);
|
|
44
37
|
reportComponents(container, cron, entry);
|
|
45
38
|
}
|
|
46
|
-
for (const entry of entrypoints.ofKind("schedule:interval", parseIntervalMetadata))
|
|
39
|
+
for (const entry of entrypoints.ofKind("schedule:interval", parseIntervalMetadata)) reportDiagnostic(container, `[vela] @Interval(${entry.meta.ms}) on ${jobName(entry)} never runs on Workers: cron triggers drive only @Cron jobs. Replace it with a @Cron job and a Wrangler trigger, or run it under ScheduleNodeModule on Node.`);
|
|
47
40
|
}
|
|
48
41
|
//#endregion
|
|
49
42
|
export { reportCloudflareScheduleDiagnostics };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schedule-diagnostics.js","names":[],"sources":["../src/schedule-diagnostics.ts"],"sourcesContent":["import {\n cronDialectAmbiguity,\n parseCronMetadata,\n parseIntervalMetadata,\n scheduledJobComponents,\n} from '@velajs/vela/module-kit';\nimport type { VelaApplication } from '@velajs/vela';\nimport type { Entrypoint, Container } from '@velajs/vela/module-kit';\
|
|
1
|
+
{"version":3,"file":"schedule-diagnostics.js","names":[],"sources":["../src/schedule-diagnostics.ts"],"sourcesContent":["import {\n cronDialectAmbiguity,\n parseCronMetadata,\n parseIntervalMetadata,\n scheduledJobComponents,\n} from '@velajs/vela/module-kit';\nimport type { VelaApplication } from '@velajs/vela';\nimport type { Entrypoint, Container } from '@velajs/vela/module-kit';\nimport { reportDiagnostic as reportScheduleDiagnostic } from './diagnostics';\n\nfunction jobName(entry: Entrypoint<{ methodName: string }>): string {\n const owner = typeof entry.token === 'function' ? entry.token.name : String(entry.token);\n return `${owner}.${entry.meta.methodName}`;\n}\n\n/**\n * Guards, interceptors and filters declared for a job never run on its\n * trigger, and a direct job that declares guards is refused on every trigger.\n */\nfunction reportComponents(\n container: Container,\n label: string,\n entry: Entrypoint<{ methodName: string }>,\n): void {\n const decorators = scheduledJobComponents(container, entry);\n if (decorators.length === 0) return;\n const named =\n decorators.length > 1\n ? `${decorators.slice(0, -1).join(', ')} and ${decorators.at(-1)!}`\n : decorators.join('');\n const refused = decorators.includes('@UseGuards')\n ? ', and one that declares guards refuses to run'\n : '';\n reportScheduleDiagnostic(\n container,\n `[vela] ${label} declares ${named}, which do not run for scheduled jobs: a direct job ` +\n `runs no guards, interceptors or filters${refused}. Use signed ScheduleModule dispatch ` +\n `and declare them on the signed route to run the job through the request pipeline.`,\n );\n}\n\n/**\n * Report schedule declarations a Workers cron trigger cannot honor as written:\n * a dialect-ambiguous `@Cron`, `dialect: 'unix'`, `timeZone: 'local'`,\n * `@Interval` jobs, and guards, interceptors or filters declared for a job\n * (a direct job that declares guards is refused when it fires).\n * The container's diagnostics policy applies: `'throw'` fails bootstrap and the\n * default `'log'` warns once per declaration, so the first event of a Worker\n * (which bootstraps the application) never fails because of these checks.\n * `vela deploy check` rejects the cron declarations, `@Interval` jobs and\n * guarded direct jobs before deployment (`ambiguous-cron-dialect`,\n * `incompatible-cron-options`, `unsupported-interval`, `scheduled-job-guards`).\n */\nexport function reportCloudflareScheduleDiagnostics(\n container: Container,\n entrypoints: VelaApplication['entrypoints'],\n): void {\n for (const entry of entrypoints.ofKind('schedule:cron', parseCronMetadata)) {\n const cron = `@Cron('${entry.meta.expression}') on ${jobName(entry)}`;\n const ambiguity = cronDialectAmbiguity(entry.meta);\n if (ambiguity) {\n reportScheduleDiagnostic(\n container,\n `[vela] ${cron} declares no dialect, and ${ambiguity}. Workers deliver the trigger ` +\n `with Cloudflare semantics while Node reads it with Vela's unix dialect; declare ` +\n `{ dialect: 'cloudflare' } so it fires on the same days on every runtime.`,\n );\n }\n if (entry.meta.dialect === 'unix') {\n reportScheduleDiagnostic(\n container,\n `[vela] ${cron} declares dialect 'unix', but Cloudflare delivers its trigger with ` +\n `Cloudflare cron semantics (weekdays 1 = Sunday through 7 = Saturday). Declare ` +\n `{ dialect: 'cloudflare' } and write the expression for Cloudflare.`,\n );\n }\n if (entry.meta.timeZone === 'local') {\n reportScheduleDiagnostic(\n container,\n `[vela] ${cron} declares timeZone 'local', but Cloudflare cron triggers run in UTC. ` +\n `Remove timeZone or set it to 'UTC'.`,\n );\n }\n reportComponents(container, cron, entry);\n }\n for (const entry of entrypoints.ofKind('schedule:interval', parseIntervalMetadata)) {\n reportScheduleDiagnostic(\n container,\n `[vela] @Interval(${entry.meta.ms}) on ${jobName(entry)} never runs on Workers: cron ` +\n `triggers drive only @Cron jobs. Replace it with a @Cron job and a Wrangler trigger, ` +\n `or run it under ScheduleNodeModule on Node.`,\n );\n }\n}\n"],"mappings":";;;AAUA,SAAS,QAAQ,OAAmD;CAElE,OAAO,GADO,OAAO,MAAM,UAAU,aAAa,MAAM,MAAM,OAAO,OAAO,MAAM,KAAK,EACvE,GAAG,MAAM,KAAK;AAChC;;;;;AAMA,SAAS,iBACP,WACA,OACA,OACM;CACN,MAAM,aAAa,uBAAuB,WAAW,KAAK;CAC1D,IAAI,WAAW,WAAW,GAAG;CAC7B,MAAM,QACJ,WAAW,SAAS,IAChB,GAAG,WAAW,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,OAAO,WAAW,GAAG,EAAE,MAC7D,WAAW,KAAK,EAAE;CACxB,MAAM,UAAU,WAAW,SAAS,YAAY,IAC5C,kDACA;CACJ,iBACE,WACA,UAAU,MAAM,YAAY,MAAM,6FACU,QAAQ,uHAEtD;AACF;;;;;;;;;;;;;AAcA,SAAgB,oCACd,WACA,aACM;CACN,KAAK,MAAM,SAAS,YAAY,OAAO,iBAAiB,iBAAiB,GAAG;EAC1E,MAAM,OAAO,UAAU,MAAM,KAAK,WAAW,QAAQ,QAAQ,KAAK;EAClE,MAAM,YAAY,qBAAqB,MAAM,IAAI;EACjD,IAAI,WACF,iBACE,WACA,UAAU,KAAK,4BAA4B,UAAU,uLAGvD;EAEF,IAAI,MAAM,KAAK,YAAY,QACzB,iBACE,WACA,UAAU,KAAK,oNAGjB;EAEF,IAAI,MAAM,KAAK,aAAa,SAC1B,iBACE,WACA,UAAU,KAAK,yGAEjB;EAEF,iBAAiB,WAAW,MAAM,KAAK;CACzC;CACA,KAAK,MAAM,SAAS,YAAY,OAAO,qBAAqB,qBAAqB,GAC/E,iBACE,WACA,oBAAoB,MAAM,KAAK,GAAG,OAAO,QAAQ,KAAK,EAAE,6JAG1D;AAEJ"}
|
|
@@ -1,13 +1,18 @@
|
|
|
1
|
+
import { kv } from "../bindings.js";
|
|
1
2
|
//#region src/services/kv-cache.store.ts
|
|
3
|
+
const namespaceOf = (source) => typeof source === "function" ? source : () => source;
|
|
2
4
|
/**
|
|
3
5
|
* Native KV JSON value store. Metadata retains logical expiry even when KV's
|
|
4
6
|
* physical retention rounds up to its 60-second minimum. Legacy values without
|
|
5
7
|
* metadata remain readable, but cannot safely backfill another tier.
|
|
6
8
|
*/
|
|
7
9
|
var KVCacheStore = class {
|
|
8
|
-
|
|
9
|
-
constructor(
|
|
10
|
-
this
|
|
10
|
+
#namespace;
|
|
11
|
+
constructor(namespace) {
|
|
12
|
+
this.#namespace = namespaceOf(namespace);
|
|
13
|
+
}
|
|
14
|
+
get ns() {
|
|
15
|
+
return this.#namespace();
|
|
11
16
|
}
|
|
12
17
|
async get(key) {
|
|
13
18
|
return (await this.getEntry(key))?.value;
|
|
@@ -62,9 +67,12 @@ var KVCacheStore = class {
|
|
|
62
67
|
* this is unsuitable for strict read-after-write or authorization revocation.
|
|
63
68
|
*/
|
|
64
69
|
var KVCacheInvalidationStore = class {
|
|
65
|
-
|
|
66
|
-
constructor(
|
|
67
|
-
this
|
|
70
|
+
#namespace;
|
|
71
|
+
constructor(namespace) {
|
|
72
|
+
this.#namespace = namespaceOf(namespace);
|
|
73
|
+
}
|
|
74
|
+
get ns() {
|
|
75
|
+
return this.#namespace();
|
|
68
76
|
}
|
|
69
77
|
async getVersion(key) {
|
|
70
78
|
const value = await this.ns.get(key, "json");
|
|
@@ -76,7 +84,25 @@ var KVCacheInvalidationStore = class {
|
|
|
76
84
|
await this.ns.put(key, JSON.stringify(crypto.randomUUID()));
|
|
77
85
|
}
|
|
78
86
|
};
|
|
87
|
+
/**
|
|
88
|
+
* `CacheModule`'s value store over the KV namespace named `binding`, read from
|
|
89
|
+
* each application's `ENV` when an operation needs it:
|
|
90
|
+
* `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.
|
|
91
|
+
*/
|
|
92
|
+
function kvCache(ref) {
|
|
93
|
+
const namespace = kv(ref);
|
|
94
|
+
return (env) => new KVCacheStore(() => namespace(env));
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* `CacheModule`'s generation store over a dedicated KV namespace named
|
|
98
|
+
* `binding`, without TTLs or lifecycle cleanup. Eventually consistent; see
|
|
99
|
+
* {@link KVCacheInvalidationStore}.
|
|
100
|
+
*/
|
|
101
|
+
function kvCacheInvalidation(ref) {
|
|
102
|
+
const namespace = kv(ref);
|
|
103
|
+
return (env) => new KVCacheInvalidationStore(() => namespace(env));
|
|
104
|
+
}
|
|
79
105
|
//#endregion
|
|
80
|
-
export { KVCacheInvalidationStore, KVCacheStore };
|
|
106
|
+
export { KVCacheInvalidationStore, KVCacheStore, kvCache, kvCacheInvalidation };
|
|
81
107
|
|
|
82
108
|
//# sourceMappingURL=kv-cache.store.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kv-cache.store.js","names":[],"sources":["../../src/services/kv-cache.store.ts"],"sourcesContent":["import type {\n
|
|
1
|
+
{"version":3,"file":"kv-cache.store.js","names":[],"sources":["../../src/services/kv-cache.store.ts"],"sourcesContent":["import type {\n CacheEntry,\n CacheEntryReader,\n CacheEntryWriter,\n CacheInvalidationStore,\n CacheStore,\n} from '@velajs/vela/cache';\nimport type { EnvFactory } from '@velajs/vela/module-kit';\nimport { kv } from '../bindings';\n\n/** A KV namespace, or a function that reads it when an operation needs it. */\nexport type KVNamespaceSource = KVNamespace | (() => KVNamespace);\n\nconst namespaceOf = (source: KVNamespaceSource): (() => KVNamespace) =>\n typeof source === 'function' ? source : () => source;\n\n/**\n * Native KV JSON value store. Metadata retains logical expiry even when KV's\n * physical retention rounds up to its 60-second minimum. Legacy values without\n * metadata remain readable, but cannot safely backfill another tier.\n */\nexport class KVCacheStore implements CacheStore, CacheEntryReader, CacheEntryWriter {\n readonly #namespace: () => KVNamespace;\n constructor(namespace: KVNamespaceSource) {\n this.#namespace = namespaceOf(namespace);\n }\n\n private get ns(): KVNamespace {\n return this.#namespace();\n }\n\n async get(key: string): Promise<unknown> {\n return (await this.getEntry(key))?.value;\n }\n\n async getEntry(key: string): Promise<{ value: unknown; expiresAt?: number } | undefined> {\n const { value, metadata } = await this.ns.getWithMetadata<unknown, unknown>(key, 'json');\n if (value === null) return undefined;\n if (typeof metadata === 'object' && metadata !== null && 'velaCacheExpiresAt' in metadata) {\n const expiresAt = metadata.velaCacheExpiresAt;\n if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt) || expiresAt <= Date.now())\n return undefined;\n return { value, expiresAt };\n }\n return { value };\n }\n\n async set(key: string, value: unknown, ttl?: number): Promise<void> {\n if (ttl !== undefined && (!Number.isFinite(ttl) || ttl < 0))\n throw new TypeError('Cache TTL must be finite and nonnegative.');\n if (ttl !== undefined) return this.setEntry(key, { value, expiresAt: Date.now() + ttl * 1000 });\n await this.ns.put(key, JSON.stringify(value));\n }\n\n async setEntry(key: string, entry: CacheEntry): Promise<void> {\n if (!Number.isFinite(entry.expiresAt)) throw new TypeError('Cache expiry must be finite.');\n const remaining = (entry.expiresAt - Date.now()) / 1000;\n if (remaining <= 0) return this.del(key);\n await this.ns.put(key, JSON.stringify(entry.value), {\n expirationTtl: Math.max(60, Math.ceil(remaining)),\n metadata: { velaCacheExpiresAt: entry.expiresAt },\n });\n }\n\n async del(key: string): Promise<void> {\n await this.ns.delete(key);\n }\n\n /** Namespace-wide, best effort. Use a dedicated value namespace; never use for scoped invalidation. */\n async clear(): Promise<void> {\n let cursor: string | undefined;\n do {\n const list = await this.ns.list(cursor ? { cursor } : undefined);\n await Promise.all(list.keys.map((entry) => this.ns.delete(entry.name)));\n cursor = list.list_complete ? undefined : list.cursor;\n } while (cursor);\n }\n}\n\n/**\n * Optional, eventually consistent generation store. Use a dedicated KV namespace\n * without TTL/lifecycle cleanup. Never delete/reset generations while entries can\n * survive. Concurrent writes and cached/negative reads prevent strong invalidation;\n * this is unsuitable for strict read-after-write or authorization revocation.\n */\nexport class KVCacheInvalidationStore implements CacheInvalidationStore {\n readonly #namespace: () => KVNamespace;\n constructor(namespace: KVNamespaceSource) {\n this.#namespace = namespaceOf(namespace);\n }\n\n private get ns(): KVNamespace {\n return this.#namespace();\n }\n\n async getVersion(key: string): Promise<string> {\n const value: unknown = await this.ns.get(key, 'json');\n if (value === null) return 'initial';\n if (typeof value !== 'string' || value.length === 0 || value.length > 2048)\n throw new TypeError('Invalid cache generation.');\n return value;\n }\n async invalidate(key: string): Promise<void> {\n await this.ns.put(key, JSON.stringify(crypto.randomUUID()));\n }\n}\n\n/**\n * `CacheModule`'s value store over the KV namespace named `binding`, read from\n * each application's `ENV` when an operation needs it:\n * `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.\n */\nexport function kvCache(ref: { binding: string }): EnvFactory<CacheStore> {\n const namespace = kv(ref);\n return (env) => new KVCacheStore(() => namespace(env));\n}\n\n/**\n * `CacheModule`'s generation store over a dedicated KV namespace named\n * `binding`, without TTLs or lifecycle cleanup. Eventually consistent; see\n * {@link KVCacheInvalidationStore}.\n */\nexport function kvCacheInvalidation(ref: { binding: string }): EnvFactory<CacheInvalidationStore> {\n const namespace = kv(ref);\n return (env) => new KVCacheInvalidationStore(() => namespace(env));\n}\n"],"mappings":";;AAaA,MAAM,eAAe,WACnB,OAAO,WAAW,aAAa,eAAe;;;;;;AAOhD,IAAa,eAAb,MAAoF;CAClF;CACA,YAAY,WAA8B;EACxC,KAAK,aAAa,YAAY,SAAS;CACzC;CAEA,IAAY,KAAkB;EAC5B,OAAO,KAAK,WAAW;CACzB;CAEA,MAAM,IAAI,KAA+B;EACvC,QAAQ,MAAM,KAAK,SAAS,GAAG,EAAA,EAAI;CACrC;CAEA,MAAM,SAAS,KAA0E;EACvF,MAAM,EAAE,OAAO,aAAa,MAAM,KAAK,GAAG,gBAAkC,KAAK,MAAM;EACvF,IAAI,UAAU,MAAM,OAAO,KAAA;EAC3B,IAAI,OAAO,aAAa,YAAY,aAAa,QAAQ,wBAAwB,UAAU;GACzF,MAAM,YAAY,SAAS;GAC3B,IAAI,OAAO,cAAc,YAAY,CAAC,OAAO,SAAS,SAAS,KAAK,aAAa,KAAK,IAAI,GACxF,OAAO,KAAA;GACT,OAAO;IAAE;IAAO;GAAU;EAC5B;EACA,OAAO,EAAE,MAAM;CACjB;CAEA,MAAM,IAAI,KAAa,OAAgB,KAA6B;EAClE,IAAI,QAAQ,KAAA,MAAc,CAAC,OAAO,SAAS,GAAG,KAAK,MAAM,IACvD,MAAM,IAAI,UAAU,2CAA2C;EACjE,IAAI,QAAQ,KAAA,GAAW,OAAO,KAAK,SAAS,KAAK;GAAE;GAAO,WAAW,KAAK,IAAI,IAAI,MAAM;EAAK,CAAC;EAC9F,MAAM,KAAK,GAAG,IAAI,KAAK,KAAK,UAAU,KAAK,CAAC;CAC9C;CAEA,MAAM,SAAS,KAAa,OAAkC;EAC5D,IAAI,CAAC,OAAO,SAAS,MAAM,SAAS,GAAG,MAAM,IAAI,UAAU,8BAA8B;EACzF,MAAM,aAAa,MAAM,YAAY,KAAK,IAAI,KAAK;EACnD,IAAI,aAAa,GAAG,OAAO,KAAK,IAAI,GAAG;EACvC,MAAM,KAAK,GAAG,IAAI,KAAK,KAAK,UAAU,MAAM,KAAK,GAAG;GAClD,eAAe,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC;GAChD,UAAU,EAAE,oBAAoB,MAAM,UAAU;EAClD,CAAC;CACH;CAEA,MAAM,IAAI,KAA4B;EACpC,MAAM,KAAK,GAAG,OAAO,GAAG;CAC1B;;CAGA,MAAM,QAAuB;EAC3B,IAAI;EACJ,GAAG;GACD,MAAM,OAAO,MAAM,KAAK,GAAG,KAAK,SAAS,EAAE,OAAO,IAAI,KAAA,CAAS;GAC/D,MAAM,QAAQ,IAAI,KAAK,KAAK,KAAK,UAAU,KAAK,GAAG,OAAO,MAAM,IAAI,CAAC,CAAC;GACtE,SAAS,KAAK,gBAAgB,KAAA,IAAY,KAAK;EACjD,SAAS;CACX;AACF;;;;;;;AAQA,IAAa,2BAAb,MAAwE;CACtE;CACA,YAAY,WAA8B;EACxC,KAAK,aAAa,YAAY,SAAS;CACzC;CAEA,IAAY,KAAkB;EAC5B,OAAO,KAAK,WAAW;CACzB;CAEA,MAAM,WAAW,KAA8B;EAC7C,MAAM,QAAiB,MAAM,KAAK,GAAG,IAAI,KAAK,MAAM;EACpD,IAAI,UAAU,MAAM,OAAO;EAC3B,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,KAAK,MAAM,SAAS,MACpE,MAAM,IAAI,UAAU,2BAA2B;EACjD,OAAO;CACT;CACA,MAAM,WAAW,KAA4B;EAC3C,MAAM,KAAK,GAAG,IAAI,KAAK,KAAK,UAAU,OAAO,WAAW,CAAC,CAAC;CAC5D;AACF;;;;;;AAOA,SAAgB,QAAQ,KAAkD;CACxE,MAAM,YAAY,GAAG,GAAG;CACxB,QAAQ,QAAQ,IAAI,mBAAmB,UAAU,GAAG,CAAC;AACvD;;;;;;AAOA,SAAgB,oBAAoB,KAA8D;CAChG,MAAM,YAAY,GAAG,GAAG;CACxB,QAAQ,QAAQ,IAAI,+BAA+B,UAAU,GAAG,CAAC;AACnE"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { r2 } from "../bindings.js";
|
|
2
|
+
import { r2Driver } from "@velajs/storage/drivers/r2";
|
|
3
|
+
//#region src/storage/r2-storage.ts
|
|
4
|
+
/**
|
|
5
|
+
* The native R2 driver for `@velajs/storage`, reading its bucket from the
|
|
6
|
+
* application's `ENV` by name:
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* StorageModule.forRoot({ driver: r2Storage({ binding: 'UPLOADS' }) })
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* `StorageModule` builds the driver on the first storage operation of each
|
|
13
|
+
* application, so a static module graph serves every environment and boot
|
|
14
|
+
* touches no binding. A missing or mistyped binding fails that operation with
|
|
15
|
+
* a message naming the binding and `r2_buckets`. Like `r2Driver`, it cannot
|
|
16
|
+
* presign uploads; serve downloads through `publicBaseUrl` or the module's
|
|
17
|
+
* `http: { download: 'proxy' }` controller.
|
|
18
|
+
*/
|
|
19
|
+
function r2Storage(options) {
|
|
20
|
+
const { binding, ...driver } = options;
|
|
21
|
+
const bucket = r2({ binding });
|
|
22
|
+
return (env) => r2Driver({
|
|
23
|
+
...driver,
|
|
24
|
+
bucket: bucket(env)
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
//#endregion
|
|
28
|
+
export { r2Storage };
|
|
29
|
+
|
|
30
|
+
//# sourceMappingURL=r2-storage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"r2-storage.js","names":[],"sources":["../../src/storage/r2-storage.ts"],"sourcesContent":["import type { EnvFactory } from '@velajs/vela/module-kit';\nimport type { StorageDriver } from '@velajs/storage';\nimport { r2Driver, type R2DriverOptions } from '@velajs/storage/drivers/r2';\nimport { r2 } from '../bindings';\n\n/** `r2Storage` options: the bucket's binding name and the native driver's settings. */\nexport interface R2StorageOptions extends Omit<R2DriverOptions, 'bucket'> {\n /** The bucket's binding name, declared under `r2_buckets` in the Wrangler configuration. */\n binding: string;\n}\n\n/**\n * The native R2 driver for `@velajs/storage`, reading its bucket from the\n * application's `ENV` by name:\n *\n * ```ts\n * StorageModule.forRoot({ driver: r2Storage({ binding: 'UPLOADS' }) })\n * ```\n *\n * `StorageModule` builds the driver on the first storage operation of each\n * application, so a static module graph serves every environment and boot\n * touches no binding. A missing or mistyped binding fails that operation with\n * a message naming the binding and `r2_buckets`. Like `r2Driver`, it cannot\n * presign uploads; serve downloads through `publicBaseUrl` or the module's\n * `http: { download: 'proxy' }` controller.\n */\nexport function r2Storage(options: R2StorageOptions): EnvFactory<StorageDriver<R2Bucket>> {\n const { binding, ...driver } = options;\n const bucket = r2({ binding });\n return (env) => r2Driver({ ...driver, bucket: bucket(env) });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0BA,SAAgB,UAAU,SAAgE;CACxF,MAAM,EAAE,SAAS,GAAG,WAAW;CAC/B,MAAM,SAAS,GAAG,EAAE,QAAQ,CAAC;CAC7B,QAAQ,QAAQ,SAAS;EAAE,GAAG;EAAQ,QAAQ,OAAO,GAAG;CAAE,CAAC;AAC7D"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import "./vela-env-DFvyoNT3.js";
|
|
2
|
+
import { EnvFactory } from "@velajs/vela/module-kit";
|
|
3
|
+
import { StorageDriver } from "@velajs/storage";
|
|
4
|
+
import { R2DriverOptions } from "@velajs/storage/drivers/r2";
|
|
5
|
+
//#region src/storage/r2-storage.d.ts
|
|
6
|
+
/** `r2Storage` options: the bucket's binding name and the native driver's settings. */
|
|
7
|
+
interface R2StorageOptions extends Omit<R2DriverOptions, 'bucket'> {
|
|
8
|
+
/** The bucket's binding name, declared under `r2_buckets` in the Wrangler configuration. */
|
|
9
|
+
binding: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The native R2 driver for `@velajs/storage`, reading its bucket from the
|
|
13
|
+
* application's `ENV` by name:
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* StorageModule.forRoot({ driver: r2Storage({ binding: 'UPLOADS' }) })
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* `StorageModule` builds the driver on the first storage operation of each
|
|
20
|
+
* application, so a static module graph serves every environment and boot
|
|
21
|
+
* touches no binding. A missing or mistyped binding fails that operation with
|
|
22
|
+
* a message naming the binding and `r2_buckets`. Like `r2Driver`, it cannot
|
|
23
|
+
* presign uploads; serve downloads through `publicBaseUrl` or the module's
|
|
24
|
+
* `http: { download: 'proxy' }` controller.
|
|
25
|
+
*/
|
|
26
|
+
export declare function r2Storage(options: R2StorageOptions): EnvFactory<StorageDriver<R2Bucket>>;
|
|
27
|
+
//#endregion
|
|
28
|
+
export type { R2StorageOptions };
|
package/dist/storage.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { registerWorkerEvent } from "../worker-events.js";
|
|
2
|
+
import { TAIL_METADATA, receiveTail } from "./tail-dispatch.js";
|
|
3
|
+
import { MetadataRegistry, registerEntrypointKind } from "@velajs/vela/module-kit";
|
|
4
|
+
//#region src/tail/on-tail.ts
|
|
5
|
+
registerEntrypointKind({
|
|
6
|
+
kind: "cf:tail",
|
|
7
|
+
metaKey: TAIL_METADATA,
|
|
8
|
+
level: "method"
|
|
9
|
+
});
|
|
10
|
+
registerWorkerEvent("tail", (application, events) => receiveTail(application, events));
|
|
11
|
+
/**
|
|
12
|
+
* Handle Tail Workers events (entrypoint kind `cf:tail`): the method of an
|
|
13
|
+
* `@Injectable()` provider receives each batch of `TraceItem`s that the
|
|
14
|
+
* Workers naming this one in `tail_consumers` produce:
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* @Injectable()
|
|
18
|
+
* export class ErrorTail {
|
|
19
|
+
* constructor(private readonly alerts: AlertsService) {}
|
|
20
|
+
*
|
|
21
|
+
* @OnTail()
|
|
22
|
+
* async observe(events: TraceItem[]): Promise<void> {
|
|
23
|
+
* const failed = events.filter((event) => event.outcome !== 'ok');
|
|
24
|
+
* if (failed.length > 0) await this.alerts.notify(failed);
|
|
25
|
+
* }
|
|
26
|
+
* }
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* Importing it gives the Worker (`app.worker`) its `tail` handler. Every
|
|
30
|
+
* `@OnTail()` handler receives every batch, each in its own execution scope
|
|
31
|
+
* through its scoped guards, interceptors and filters. A failure is reported
|
|
32
|
+
* (`edge: 'tail'`) and never thrown into the platform's tail loop. When the
|
|
33
|
+
* application fails to start, no ExceptionHandler exists to report through:
|
|
34
|
+
* the handler logs the error to the console and resolves, and the next batch
|
|
35
|
+
* retries the start.
|
|
36
|
+
*/
|
|
37
|
+
function OnTail() {
|
|
38
|
+
return (target, key) => {
|
|
39
|
+
if (typeof key !== "string") throw new TypeError("@OnTail() decorates a string-named method.");
|
|
40
|
+
MetadataRegistry.appendCustomClassMeta(target.constructor, TAIL_METADATA, { methodName: key });
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { OnTail };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=on-tail.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"on-tail.js","names":[],"sources":["../../src/tail/on-tail.ts"],"sourcesContent":["import { MetadataRegistry, registerEntrypointKind } from '@velajs/vela/module-kit';\nimport { registerWorkerEvent } from '../worker-events';\nimport { TAIL_METADATA, receiveTail, type OnTailMetadata } from './tail-dispatch';\n\n// The entrypoint kind, declared next to its decorator; importing the decorator\n// also gives every Worker of the isolate its `tail` handler.\nregisterEntrypointKind({ kind: 'cf:tail', metaKey: TAIL_METADATA, level: 'method' });\nregisterWorkerEvent('tail', (application, events) => receiveTail(application, events));\n\n/** A method decorator whose method receives a batch of Tail Workers events. */\nexport type OnTailDecorator = <Handler extends (events: TraceItem[]) => unknown>(\n target: object,\n key: string | symbol,\n descriptor: TypedPropertyDescriptor<Handler>,\n) => void;\n\n/**\n * Handle Tail Workers events (entrypoint kind `cf:tail`): the method of an\n * `@Injectable()` provider receives each batch of `TraceItem`s that the\n * Workers naming this one in `tail_consumers` produce:\n *\n * ```ts\n * @Injectable()\n * export class ErrorTail {\n * constructor(private readonly alerts: AlertsService) {}\n *\n * @OnTail()\n * async observe(events: TraceItem[]): Promise<void> {\n * const failed = events.filter((event) => event.outcome !== 'ok');\n * if (failed.length > 0) await this.alerts.notify(failed);\n * }\n * }\n * ```\n *\n * Importing it gives the Worker (`app.worker`) its `tail` handler. Every\n * `@OnTail()` handler receives every batch, each in its own execution scope\n * through its scoped guards, interceptors and filters. A failure is reported\n * (`edge: 'tail'`) and never thrown into the platform's tail loop. When the\n * application fails to start, no ExceptionHandler exists to report through:\n * the handler logs the error to the console and resolves, and the next batch\n * retries the start.\n */\nexport function OnTail(): OnTailDecorator {\n return (target, key) => {\n if (typeof key !== 'string') throw new TypeError('@OnTail() decorates a string-named method.');\n MetadataRegistry.appendCustomClassMeta<OnTailMetadata>(target.constructor, TAIL_METADATA, {\n methodName: key,\n });\n };\n}\n"],"mappings":";;;;AAMA,uBAAuB;CAAE,MAAM;CAAW,SAAS;CAAe,OAAO;AAAS,CAAC;AACnF,oBAAoB,SAAS,aAAa,WAAW,YAAY,aAAa,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCrF,SAAgB,SAA0B;CACxC,QAAQ,QAAQ,QAAQ;EACtB,IAAI,OAAO,QAAQ,UAAU,MAAM,IAAI,UAAU,4CAA4C;EAC7F,iBAAiB,sBAAsC,OAAO,aAAa,eAAe,EACxF,YAAY,IACd,CAAC;CACH;AACF"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { entrypointInvoker, observedSettlement } from "../host/host-invoker.js";
|
|
2
|
+
import { resolveErrorReporter } from "@velajs/vela/module-kit";
|
|
3
|
+
//#region src/tail/tail-dispatch.ts
|
|
4
|
+
/** The metadata key `@OnTail()` records its handlers under (entrypoint kind `cf:tail`). */
|
|
5
|
+
const TAIL_METADATA = "cloudflare:tail";
|
|
6
|
+
function handlerName(meta) {
|
|
7
|
+
const methodName = typeof meta === "object" && meta !== null ? Reflect.get(meta, "methodName") : void 0;
|
|
8
|
+
if (typeof methodName !== "string") throw new Error("Invalid @OnTail() metadata.");
|
|
9
|
+
return methodName;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The Worker's `tail` handler: {@link dispatchTail} to the application built
|
|
13
|
+
* for the event's environment. An application that fails to start has no
|
|
14
|
+
* ExceptionHandler to report through, so the error is logged to the console
|
|
15
|
+
* and the handler still resolves; the next batch retries the start.
|
|
16
|
+
*/
|
|
17
|
+
async function receiveTail(application, events) {
|
|
18
|
+
let started;
|
|
19
|
+
try {
|
|
20
|
+
started = await application();
|
|
21
|
+
} catch (error) {
|
|
22
|
+
console.error("[vela] tail events were not delivered: the application failed to start:", error);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
await dispatchTail(started, events);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Deliver a batch of Tail Workers events to every `@OnTail()` handler of the
|
|
29
|
+
* application, each in its own execution scope through its scoped guards,
|
|
30
|
+
* interceptors and filters. A failure, in a handler or around it, is reported
|
|
31
|
+
* (`edge: 'tail'`) and never reaches the platform: a failing tail handler
|
|
32
|
+
* must not fail the events it observes.
|
|
33
|
+
*/
|
|
34
|
+
async function dispatchTail(application, events) {
|
|
35
|
+
const container = application.getContainer();
|
|
36
|
+
const handlers = application.entrypoints.ofKind("cf:tail");
|
|
37
|
+
await Promise.all(handlers.map(async (entry) => {
|
|
38
|
+
let source = "an @OnTail() handler";
|
|
39
|
+
try {
|
|
40
|
+
const method = handlerName(entry.meta);
|
|
41
|
+
const invoker = entrypointInvoker(container, entry, "tail");
|
|
42
|
+
source = invoker.report("cf:tail", method).source ?? source;
|
|
43
|
+
if (!Array.isArray(events)) throw new TypeError("The tail handler received no events.");
|
|
44
|
+
await invoker.invoke({
|
|
45
|
+
kind: "cf:tail",
|
|
46
|
+
method,
|
|
47
|
+
args: [events],
|
|
48
|
+
payload: events,
|
|
49
|
+
settlement: observedSettlement
|
|
50
|
+
});
|
|
51
|
+
} catch (error) {
|
|
52
|
+
try {
|
|
53
|
+
resolveErrorReporter(container).report(error, {
|
|
54
|
+
edge: "tail",
|
|
55
|
+
source,
|
|
56
|
+
kind: "cf:tail"
|
|
57
|
+
});
|
|
58
|
+
} catch {
|
|
59
|
+
console.error(`[vela] tail error in ${source}:`, error);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
export { TAIL_METADATA, dispatchTail, receiveTail };
|
|
66
|
+
|
|
67
|
+
//# sourceMappingURL=tail-dispatch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tail-dispatch.js","names":[],"sources":["../../src/tail/tail-dispatch.ts"],"sourcesContent":["import { resolveErrorReporter, type EntrypointExecutionContext } from '@velajs/vela/module-kit';\nimport type { CloudflareApplication } from '../cloudflare-application';\nimport { entrypointInvoker, observedSettlement } from '../host/host-invoker';\n\n/** The metadata key `@OnTail()` records its handlers under (entrypoint kind `cf:tail`). */\nexport const TAIL_METADATA = 'cloudflare:tail';\n\n/** One `@OnTail()` handler. */\nexport interface OnTailMetadata {\n readonly methodName: string;\n}\n\n/** The ExecutionContext guards, interceptors and filters receive around an `@OnTail()` handler. */\nexport type TailExecutionContext = EntrypointExecutionContext<'cf:tail'>;\n\nfunction handlerName(meta: unknown): string {\n const methodName: unknown =\n typeof meta === 'object' && meta !== null ? Reflect.get(meta, 'methodName') : undefined;\n if (typeof methodName !== 'string') throw new Error('Invalid @OnTail() metadata.');\n return methodName;\n}\n\n/**\n * The Worker's `tail` handler: {@link dispatchTail} to the application built\n * for the event's environment. An application that fails to start has no\n * ExceptionHandler to report through, so the error is logged to the console\n * and the handler still resolves; the next batch retries the start.\n */\nexport async function receiveTail(\n application: () => Promise<CloudflareApplication>,\n events: unknown,\n): Promise<void> {\n let started: CloudflareApplication;\n try {\n started = await application();\n } catch (error) {\n console.error('[vela] tail events were not delivered: the application failed to start:', error);\n return;\n }\n await dispatchTail(started, events);\n}\n\n/**\n * Deliver a batch of Tail Workers events to every `@OnTail()` handler of the\n * application, each in its own execution scope through its scoped guards,\n * interceptors and filters. A failure, in a handler or around it, is reported\n * (`edge: 'tail'`) and never reaches the platform: a failing tail handler\n * must not fail the events it observes.\n */\nexport async function dispatchTail(\n application: CloudflareApplication,\n events: unknown,\n): Promise<void> {\n const container = application.getContainer();\n const handlers = application.entrypoints.ofKind('cf:tail');\n await Promise.all(\n handlers.map(async (entry) => {\n let source = 'an @OnTail() handler';\n try {\n const method = handlerName(entry.meta);\n const invoker = entrypointInvoker(container, entry, 'tail');\n source = invoker.report('cf:tail', method).source ?? source;\n if (!Array.isArray(events)) throw new TypeError('The tail handler received no events.');\n await invoker.invoke({\n kind: 'cf:tail',\n method,\n args: [events],\n payload: events,\n settlement: observedSettlement,\n });\n } catch (error) {\n try {\n resolveErrorReporter(container).report(error, { edge: 'tail', source, kind: 'cf:tail' });\n } catch {\n console.error(`[vela] tail error in ${source}:`, error);\n }\n }\n }),\n );\n}\n"],"mappings":";;;;AAKA,MAAa,gBAAgB;AAU7B,SAAS,YAAY,MAAuB;CAC1C,MAAM,aACJ,OAAO,SAAS,YAAY,SAAS,OAAO,QAAQ,IAAI,MAAM,YAAY,IAAI,KAAA;CAChF,IAAI,OAAO,eAAe,UAAU,MAAM,IAAI,MAAM,6BAA6B;CACjF,OAAO;AACT;;;;;;;AAQA,eAAsB,YACpB,aACA,QACe;CACf,IAAI;CACJ,IAAI;EACF,UAAU,MAAM,YAAY;CAC9B,SAAS,OAAO;EACd,QAAQ,MAAM,2EAA2E,KAAK;EAC9F;CACF;CACA,MAAM,aAAa,SAAS,MAAM;AACpC;;;;;;;;AASA,eAAsB,aACpB,aACA,QACe;CACf,MAAM,YAAY,YAAY,aAAa;CAC3C,MAAM,WAAW,YAAY,YAAY,OAAO,SAAS;CACzD,MAAM,QAAQ,IACZ,SAAS,IAAI,OAAO,UAAU;EAC5B,IAAI,SAAS;EACb,IAAI;GACF,MAAM,SAAS,YAAY,MAAM,IAAI;GACrC,MAAM,UAAU,kBAAkB,WAAW,OAAO,MAAM;GAC1D,SAAS,QAAQ,OAAO,WAAW,MAAM,CAAC,CAAC,UAAU;GACrD,IAAI,CAAC,MAAM,QAAQ,MAAM,GAAG,MAAM,IAAI,UAAU,sCAAsC;GACtF,MAAM,QAAQ,OAAO;IACnB,MAAM;IACN;IACA,MAAM,CAAC,MAAM;IACb,SAAS;IACT,YAAY;GACd,CAAC;EACH,SAAS,OAAO;GACd,IAAI;IACF,qBAAqB,SAAS,CAAC,CAAC,OAAO,OAAO;KAAE,MAAM;KAAQ;KAAQ,MAAM;IAAU,CAAC;GACzF,QAAQ;IACN,QAAQ,MAAM,wBAAwB,OAAO,IAAI,KAAK;GACxD;EACF;CACF,CAAC,CACH;AACF"}
|
package/dist/tail.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import "./vela-env-DFvyoNT3.js";
|
|
2
|
+
import "./cloudflare-application-CXDy9C1R.js";
|
|
3
|
+
import { EntrypointExecutionContext } from "@velajs/vela/module-kit";
|
|
4
|
+
//#region src/tail/on-tail.d.ts
|
|
5
|
+
/** A method decorator whose method receives a batch of Tail Workers events. */
|
|
6
|
+
type OnTailDecorator = <Handler extends (events: TraceItem[]) => unknown>(target: object, key: string | symbol, descriptor: TypedPropertyDescriptor<Handler>) => void;
|
|
7
|
+
/**
|
|
8
|
+
* Handle Tail Workers events (entrypoint kind `cf:tail`): the method of an
|
|
9
|
+
* `@Injectable()` provider receives each batch of `TraceItem`s that the
|
|
10
|
+
* Workers naming this one in `tail_consumers` produce:
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* @Injectable()
|
|
14
|
+
* export class ErrorTail {
|
|
15
|
+
* constructor(private readonly alerts: AlertsService) {}
|
|
16
|
+
*
|
|
17
|
+
* @OnTail()
|
|
18
|
+
* async observe(events: TraceItem[]): Promise<void> {
|
|
19
|
+
* const failed = events.filter((event) => event.outcome !== 'ok');
|
|
20
|
+
* if (failed.length > 0) await this.alerts.notify(failed);
|
|
21
|
+
* }
|
|
22
|
+
* }
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* Importing it gives the Worker (`app.worker`) its `tail` handler. Every
|
|
26
|
+
* `@OnTail()` handler receives every batch, each in its own execution scope
|
|
27
|
+
* through its scoped guards, interceptors and filters. A failure is reported
|
|
28
|
+
* (`edge: 'tail'`) and never thrown into the platform's tail loop. When the
|
|
29
|
+
* application fails to start, no ExceptionHandler exists to report through:
|
|
30
|
+
* the handler logs the error to the console and resolves, and the next batch
|
|
31
|
+
* retries the start.
|
|
32
|
+
*/
|
|
33
|
+
export declare function OnTail(): OnTailDecorator;
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/tail/tail-dispatch.d.ts
|
|
36
|
+
/** The ExecutionContext guards, interceptors and filters receive around an `@OnTail()` handler. */
|
|
37
|
+
type TailExecutionContext = EntrypointExecutionContext<'cf:tail'>;
|
|
38
|
+
//#endregion
|
|
39
|
+
export type { OnTailDecorator, TailExecutionContext };
|
package/dist/tail.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import "./vela-env-DFvyoNT3.js";
|
|
2
|
+
import { d as CloudflareWorkerOptions, y as CloudflareRoot } from "./cloudflare-factory-CuFNUJJD.js";
|
|
3
|
+
import { VelaEnv } from "@velajs/vela";
|
|
4
|
+
import { QueueJob, QueueJobDefinition, QueueJobInput } from "@velajs/vela/queue";
|
|
5
|
+
import { TestingModule, TestingModuleBuilder } from "@velajs/testing";
|
|
6
|
+
//#region src/testing.d.ts
|
|
7
|
+
export interface TestingWorkerOptions extends CloudflareWorkerOptions {
|
|
8
|
+
/**
|
|
9
|
+
* The Workers environment the application is built for and every event
|
|
10
|
+
* carries. Defaults to the test Worker's `env` from `cloudflare:workers`,
|
|
11
|
+
* with the bindings the Vitest pool's Wrangler configuration declares.
|
|
12
|
+
*/
|
|
13
|
+
env?: VelaEnv;
|
|
14
|
+
/**
|
|
15
|
+
* Adjust the testing module before it compiles: `overrideProvider`,
|
|
16
|
+
* `overrideModule().useModule()`, enhancer overrides and `useMocker`.
|
|
17
|
+
*/
|
|
18
|
+
overrides?: (module: TestingModuleBuilder) => TestingModuleBuilder;
|
|
19
|
+
}
|
|
20
|
+
/** One message of a {@link TestingWorker.queue} batch. */
|
|
21
|
+
export interface TestingQueueMessage<Body = unknown> {
|
|
22
|
+
readonly body: Body;
|
|
23
|
+
/** Defaults to a random UUID. */
|
|
24
|
+
readonly id?: string;
|
|
25
|
+
/** The delivery attempt, 1-based; defaults to 1. */
|
|
26
|
+
readonly attempts?: number;
|
|
27
|
+
readonly timestamp?: Date | number;
|
|
28
|
+
}
|
|
29
|
+
/** What the queue handler did with a batch: `cloudflare:test`'s `getQueueResult()`, plus its outcome. */
|
|
30
|
+
export interface TestingQueueResult {
|
|
31
|
+
/** `'exception'` when the handler rejected: Cloudflare then retries every message it did not acknowledge. */
|
|
32
|
+
readonly outcome: 'ok' | 'exception';
|
|
33
|
+
/** The handler's rejection, when `outcome` is `'exception'`. */
|
|
34
|
+
readonly error?: unknown;
|
|
35
|
+
readonly ackAll: boolean;
|
|
36
|
+
readonly retryBatch: {
|
|
37
|
+
readonly retry: boolean;
|
|
38
|
+
readonly delaySeconds?: number;
|
|
39
|
+
};
|
|
40
|
+
/** Ids of the messages acknowledged one by one. */
|
|
41
|
+
readonly explicitAcks: readonly string[];
|
|
42
|
+
readonly retryMessages: readonly {
|
|
43
|
+
readonly msgId: string;
|
|
44
|
+
readonly delaySeconds?: number;
|
|
45
|
+
}[];
|
|
46
|
+
}
|
|
47
|
+
/** The Worker's `fetch`, `queue`, `scheduled`, `email` and `tail` handlers for one test application. */
|
|
48
|
+
export interface TestingWorker {
|
|
49
|
+
/** The compiled testing module: `get()`, `resolveInRequest()`, the fluent `http` client. */
|
|
50
|
+
readonly module: TestingModule;
|
|
51
|
+
readonly env: VelaEnv;
|
|
52
|
+
/** Send a request through the Worker's `fetch` handler; a path resolves against `http://localhost`. */
|
|
53
|
+
fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
|
|
54
|
+
/** Deliver one batch of the physical `queue` to the Worker's `queue` handler. */
|
|
55
|
+
queue(queue: string, messages: readonly TestingQueueMessage[]): Promise<TestingQueueResult>;
|
|
56
|
+
/**
|
|
57
|
+
* Fire the cron trigger `cron` and wait for its `@Cron` jobs. Rejects when
|
|
58
|
+
* no job declares `cron`: Cloudflare delivers the literal trigger expression.
|
|
59
|
+
*/
|
|
60
|
+
scheduled(cron: string, options?: {
|
|
61
|
+
scheduledTime?: Date | number;
|
|
62
|
+
}): Promise<void>;
|
|
63
|
+
/**
|
|
64
|
+
* Deliver an Email Workers message (such as one from {@link emailMessage})
|
|
65
|
+
* to the application's `@OnEmail()` handlers, as the Worker's `email`
|
|
66
|
+
* handler does: a message no handler accepts is rejected.
|
|
67
|
+
*/
|
|
68
|
+
email(message: ForwardableEmailMessage): Promise<void>;
|
|
69
|
+
/** Deliver Tail Workers events (such as {@link traceItem}s) to its `@OnTail()` handlers. */
|
|
70
|
+
tail(events: TraceItem[]): Promise<void>;
|
|
71
|
+
/** Wait for background work (`waitUntil`) of every event, then close the application. */
|
|
72
|
+
close(): Promise<void>;
|
|
73
|
+
}
|
|
74
|
+
/** An Email Workers message built by {@link emailMessage}, recording what handlers did with it. */
|
|
75
|
+
export interface TestingEmailMessage extends ForwardableEmailMessage {
|
|
76
|
+
/** The reason passed to `setReject()`, when a handler rejected the message. */
|
|
77
|
+
readonly rejectReason: string | undefined;
|
|
78
|
+
/** The `forward()` calls, in order. */
|
|
79
|
+
readonly forwards: readonly {
|
|
80
|
+
readonly rcptTo: string;
|
|
81
|
+
readonly headers?: Headers;
|
|
82
|
+
}[];
|
|
83
|
+
/** The `reply()` calls, in order. */
|
|
84
|
+
readonly replies: readonly (EmailMessage | EmailReplyMessageBuilder)[];
|
|
85
|
+
}
|
|
86
|
+
/** What {@link emailMessage} builds a message from. */
|
|
87
|
+
export interface TestingEmailInit {
|
|
88
|
+
/** The envelope sender (`MAIL FROM`). */
|
|
89
|
+
readonly from: string;
|
|
90
|
+
/** The envelope recipient (`RCPT TO`), which `@OnEmail({ to })` routes on. */
|
|
91
|
+
readonly to: string;
|
|
92
|
+
readonly subject?: string;
|
|
93
|
+
/** The plain-text body of the default raw message. */
|
|
94
|
+
readonly text?: string;
|
|
95
|
+
/** Further headers; `From`, `To` and `Subject` default from the fields above. */
|
|
96
|
+
readonly headers?: HeadersInit;
|
|
97
|
+
/** The raw RFC 5322 message; built from the headers and `text` by default. */
|
|
98
|
+
readonly raw?: string | Uint8Array;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* An Email Workers message (`ForwardableEmailMessage`) for tests, in the
|
|
102
|
+
* spirit of `cloudflare:test`'s `createMessageBatch()`: `raw`, `rawSize` and
|
|
103
|
+
* `headers` describe the message, and `setReject()`, `forward()` and `reply()`
|
|
104
|
+
* record what the handlers did (`rejectReason`, `forwards`, `replies`) instead
|
|
105
|
+
* of sending anything.
|
|
106
|
+
*
|
|
107
|
+
* ```ts
|
|
108
|
+
* const message = emailMessage({ from: 'ada@example.net', to: 'support@example.com', subject: 'Help' });
|
|
109
|
+
* await worker.email(message);
|
|
110
|
+
* expect(message.forwards).toEqual([{ rcptTo: 'team@example.com' }]);
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
export declare function emailMessage(init: TestingEmailInit): TestingEmailMessage;
|
|
114
|
+
/**
|
|
115
|
+
* A Tail Workers event (`TraceItem`) for tests: an `ok` fetch-less invocation
|
|
116
|
+
* of the Worker `producer`, with `overrides` applied.
|
|
117
|
+
*/
|
|
118
|
+
export declare function traceItem(overrides?: Partial<TraceItem>): TraceItem;
|
|
119
|
+
/**
|
|
120
|
+
* Build `rootModule` as `createCloudflareWorker(rootModule, options)` does
|
|
121
|
+
* (its adapters, then its `configure` hook), through `@velajs/testing`, and
|
|
122
|
+
* drive its Worker handlers inside the Workers Vitest pool.
|
|
123
|
+
*
|
|
124
|
+
* ```ts
|
|
125
|
+
* const worker = await createTestingWorker(AppModule, {
|
|
126
|
+
* overrides: (module) => module.overrideProvider(Mailer).useValue(fakeMailer),
|
|
127
|
+
* });
|
|
128
|
+
* const response = await worker.fetch('/todos');
|
|
129
|
+
* const result = await worker.queue('todo-events', [queueJob('todos', todoCreated, { id: '1' })]);
|
|
130
|
+
* await worker.scheduled('0 3 * * *');
|
|
131
|
+
* await worker.close();
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
134
|
+
export declare function createTestingWorker(rootModule: CloudflareRoot, options?: TestingWorkerOptions): Promise<TestingWorker>;
|
|
135
|
+
/**
|
|
136
|
+
* A queue message carrying a Vela job envelope, as `QueueClient.add()` sends
|
|
137
|
+
* it: `queue` is the logical queue a `@Processor` handles, and `job` a job
|
|
138
|
+
* definition (whose wire input `data` must match) or a job name.
|
|
139
|
+
*/
|
|
140
|
+
export declare function queueJob<const D extends QueueJobDefinition>(queue: string, job: D, data: QueueJobInput<D>, options?: {
|
|
141
|
+
id?: string;
|
|
142
|
+
attempts?: number;
|
|
143
|
+
}): TestingQueueMessage<QueueJob>;
|
|
144
|
+
export declare function queueJob(queue: string, job: string, data: unknown, options?: {
|
|
145
|
+
id?: string;
|
|
146
|
+
attempts?: number;
|
|
147
|
+
}): TestingQueueMessage<QueueJob>;
|
|
148
|
+
//#endregion
|