@rexezuge/runtime 1.9.4 → 1.11.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/README.md +96 -8
- package/dist/base/AbstractDurableObjectWorker.d.ts +5 -0
- package/dist/base/AbstractDurableObjectWorker.d.ts.map +1 -1
- package/dist/base/AbstractDurableObjectWorker.js.map +2 -2
- package/dist/base/AbstractEntrypointWorker.d.ts +26 -1
- package/dist/base/AbstractEntrypointWorker.d.ts.map +1 -1
- package/dist/base/AbstractEntrypointWorker.js +1 -1
- package/dist/base/AbstractEntrypointWorker.js.map +3 -3
- package/dist/base/AbstractQueueWorker.d.ts +5 -0
- package/dist/base/AbstractQueueWorker.d.ts.map +1 -1
- package/dist/base/AbstractQueueWorker.js.map +2 -2
- package/dist/base/AbstractWorkflowWorker.d.ts +5 -0
- package/dist/base/AbstractWorkflowWorker.d.ts.map +1 -1
- package/dist/base/AbstractWorkflowWorker.js.map +2 -2
- package/dist/base/finalMembers.d.ts +22 -0
- package/dist/base/finalMembers.d.ts.map +1 -0
- package/dist/base/finalMembers.js +1 -0
- package/dist/base/finalMembers.js.map +7 -0
- package/dist/cron/CronTasksDurableObject.d.ts +113 -0
- package/dist/cron/CronTasksDurableObject.d.ts.map +1 -0
- package/dist/cron/CronTasksDurableObject.js +1 -0
- package/dist/cron/CronTasksDurableObject.js.map +7 -0
- package/dist/cron/cronContract.d.ts +61 -0
- package/dist/cron/cronContract.d.ts.map +1 -0
- package/dist/cron/cronContract.js +1 -0
- package/dist/cron/cronContract.js.map +7 -0
- package/dist/cron/dispatchCronToDurableObject.d.ts +62 -0
- package/dist/cron/dispatchCronToDurableObject.d.ts.map +1 -0
- package/dist/cron/dispatchCronToDurableObject.js +1 -0
- package/dist/cron/dispatchCronToDurableObject.js.map +7 -0
- package/dist/cron/index.d.ts +6 -0
- package/dist/cron/index.d.ts.map +1 -0
- package/dist/cron/index.js +1 -0
- package/dist/cron/index.js.map +7 -0
- package/dist/email/EmailEventsDispatcher.d.ts +106 -0
- package/dist/email/EmailEventsDispatcher.d.ts.map +1 -0
- package/dist/email/EmailEventsDispatcher.js +1 -0
- package/dist/email/EmailEventsDispatcher.js.map +7 -0
- package/dist/index.d.ts +18 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +3 -3
- package/dist/scheduled/AbstractPruningTask.d.ts +115 -0
- package/dist/scheduled/AbstractPruningTask.d.ts.map +1 -0
- package/dist/scheduled/AbstractPruningTask.js +1 -0
- package/dist/scheduled/AbstractPruningTask.js.map +7 -0
- package/dist/scheduled/index.d.ts +2 -0
- package/dist/scheduled/index.d.ts.map +1 -1
- package/dist/scheduled/index.js.map +2 -2
- package/dist/testing.d.ts +9 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +1 -0
- package/dist/testing.js.map +7 -0
- package/package.json +7 -2
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @rexezuge/runtime
|
|
2
2
|
|
|
3
|
-
DI container, configuration, worker bases, logger, and KV cache for Cloudflare Workers.
|
|
3
|
+
DI container, configuration, worker bases, the standard cron Durable Object, pruning and queue→workflow dispatch, logger, and KV cache for Cloudflare Workers.
|
|
4
4
|
|
|
5
5
|
Zero dependencies (the one platform import is type-only, resolved through each consumer's generated wrangler types).
|
|
6
6
|
|
|
@@ -49,12 +49,12 @@ for (const warning of config.validate()) console.warn(warning); // warnings, nev
|
|
|
49
49
|
|
|
50
50
|
## 3. Worker bases
|
|
51
51
|
|
|
52
|
-
| Base | Extends for
|
|
53
|
-
| ----------------------------- |
|
|
54
|
-
| `AbstractEntrypointWorker` | HTTP + cron entrypoints (`onRequest
|
|
55
|
-
| `AbstractDurableObjectWorker` | Durable Object workers
|
|
56
|
-
| `AbstractQueueWorker` | Queue consumers
|
|
57
|
-
| `AbstractWorkflowWorker` | Workflows
|
|
52
|
+
| Base | Extends for |
|
|
53
|
+
| ----------------------------- | ------------------------------------------------------------- |
|
|
54
|
+
| `AbstractEntrypointWorker` | HTTP + cron entrypoints (`onRequest`, optional `onScheduled`) |
|
|
55
|
+
| `AbstractDurableObjectWorker` | Durable Object workers |
|
|
56
|
+
| `AbstractQueueWorker` | Queue consumers |
|
|
57
|
+
| `AbstractWorkflowWorker` | Workflows |
|
|
58
58
|
|
|
59
59
|
`fetch()` / `scheduled()` log-and-contain: an unhandled throw is a 500 response or a logged cron failure, never a platform crash. There is deliberately no `/__scheduled` HTTP branch — cron runs through the wrangler `triggers.crons` binding. The structural `WorkerExecutionContext` / `WorkerScheduledController` types mean this package typechecks without `@cloudflare/workers-types`.
|
|
60
60
|
|
|
@@ -78,7 +78,86 @@ class TokenRefresher extends AbstractDurableObjectWorker<Env> {
|
|
|
78
78
|
}
|
|
79
79
|
```
|
|
80
80
|
|
|
81
|
-
## 4.
|
|
81
|
+
## 4. Cron — `CronTasksDurableObject` and `dispatchCronToDurableObject`
|
|
82
|
+
|
|
83
|
+
The family's one cron pattern: `scheduled()` → `CronTasksDurableObject` → `TaskRegistry`.
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
// apps/api — the entry worker. `onScheduled` is optional since 1.10: naming the
|
|
87
|
+
// binding is enough; the default forwards each tick to idFromName('global').
|
|
88
|
+
class ApiWorker extends AbstractEntrypointWorker {
|
|
89
|
+
protected onRequest(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
|
90
|
+
return this.app.fetch(request, env, ctx);
|
|
91
|
+
}
|
|
92
|
+
protected override cronTasksNamespace(env: Env) {
|
|
93
|
+
return env.CRON_TASKS;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// apps/background — the Durable Object.
|
|
98
|
+
class CronTasks extends CronTasksDurableObject<Env> {
|
|
99
|
+
protected createRegistry(env: Env, run: CronRunContext): TaskRegistry {
|
|
100
|
+
return new TaskRegistry().register(1, new TokenRefreshTask()).register(2, new RunPruningTask());
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
The contract is owned by the base (`fetch` / `onRequest` are `@final` and refused at construction if redeclared):
|
|
106
|
+
`POST /run` with `{ cron, scheduledTime }` → 200 `completed` / 202 `already_running` / 500 `failed`; other methods 405, other paths 404.
|
|
107
|
+
The in-flight guard **expires** after `maxRunAgeMs()` (default `DEFAULT_MAX_RUN_AGE_MS`, 15 min) with an identity-safe `finally`, so a hung task cannot freeze the cron.
|
|
108
|
+
Phases run in ascending order under `allSettled`; a failure does not stop later phases, and the run rejects with a `CronRunError` (count-only message, causes on `.failures`).
|
|
109
|
+
|
|
110
|
+
A worker that schedules by hand calls `ctx.waitUntil(dispatchCronToDurableObject(env.CRON_TASKS, controller))` — it never rejects and returns `{ outcome, httpStatus }`.
|
|
111
|
+
|
|
112
|
+
## 5. `AbstractPruningTask`
|
|
113
|
+
|
|
114
|
+
Retention pruning through a DAO port (`PruningTarget.deleteOlderThan(cutoff, limit)`), batched (500 × 20 by default) and budget-aware:
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
class RunPruningTask extends AbstractPruningTask<Env> {
|
|
118
|
+
protected getTaskType() {
|
|
119
|
+
return 'prune_task_runs';
|
|
120
|
+
}
|
|
121
|
+
protected retentionDays(env: Env) {
|
|
122
|
+
return Number(env.TASK_RUN_RETENTION_DAYS ?? 30);
|
|
123
|
+
}
|
|
124
|
+
protected createTarget(env: Env) {
|
|
125
|
+
return new BackgroundTaskRunDAO(env.DB);
|
|
126
|
+
} // @rexezuge/d1
|
|
127
|
+
protected override budget() {
|
|
128
|
+
return this.meter;
|
|
129
|
+
} // optional: a SubrequestMeter
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
The cutoff defaults to unix seconds (`cutoffFor` to change it). An invalid retention (`NaN`, ≤ 0) fails the run instead of deleting; `null` records a disabled run.
|
|
134
|
+
The summary's `details` say why the loop stopped: `drained`, `batch_cap`, `budget` or `disabled`.
|
|
135
|
+
|
|
136
|
+
## 6. `EmailEventsDispatcher`
|
|
137
|
+
|
|
138
|
+
Queue → Workflow fan-out (`onQueue` is `@final`): deterministic instance ids (`emw_` + sha256 of `queue:messageId`), one `createBatch`, then a per-message fallback that acks duplicates and retries everything else. Nothing caught is logged.
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
class EmailEventsDispatcherWorker extends EmailEventsDispatcher<EmailQueueMessage> {
|
|
142
|
+
protected workflowFor(env: Env) {
|
|
143
|
+
return env.EMAIL_PROCESSING_WORKFLOW;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
## Extending
|
|
149
|
+
|
|
150
|
+
Strict and flexible halves, per [`docs/design-charter.md`](../../docs/design-charter.md):
|
|
151
|
+
|
|
152
|
+
| Class | Owned by the kit (`@final`) | Your hooks |
|
|
153
|
+
| ------------------------ | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
154
|
+
| `CronTasksDurableObject` | `fetch`, `onRequest`, expiry, phase order, envelope | `createRegistry`, `onRunStart` / `onRunComplete` / `onRunError`, `maxRunAgeMs`, `now`, `logger` |
|
|
155
|
+
| `AbstractPruningTask` | `handle`, `handleScheduledTask`, the batch loop | `retentionDays`, `createTarget`, `batchSize`, `maxBatches`, `budget`, `now`, `cutoffFor` |
|
|
156
|
+
| `EmailEventsDispatcher` | `queue`, `onQueue`, ack/retry policy | `workflowFor`, `paramsFor`, `instanceIdPrefix`, `isDuplicateInstanceError`, `logger` |
|
|
157
|
+
| `AbstractScheduledTask` | `handle` (run bookkeeping) | `handleScheduledTask`, `getTaskType`, `createRunRecorder`, `describeFailure`, `swallowErrors`, `logger` |
|
|
158
|
+
| Worker bases | `fetch` / `scheduled` / `queue` / `run` | `onRequest` / `onScheduled` / `cronTasksNamespace` / `onQueue` / `onWorkflow`, `reportUnhandled` |
|
|
159
|
+
|
|
160
|
+
## 7. Logger and KV cache
|
|
82
161
|
|
|
83
162
|
```ts
|
|
84
163
|
import { createLogger, KvCache } from '@rexezuge/runtime';
|
|
@@ -92,6 +171,15 @@ await cache.putText('session', 'sess:abc', 'payload', { ttlSeconds: 300 });
|
|
|
92
171
|
|
|
93
172
|
`KV_DOMAINS` / `buildKvKey` / `clampTtl` keep every repo's key shapes and TTL ceilings identical.
|
|
94
173
|
|
|
174
|
+
The logger's installed level and the KV circuit breaker are module-global. Suites
|
|
175
|
+
reset them with the test seams from the `/testing` subpath:
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
import { resetBreakerForTests, resetLogLevelForTests } from '@rexezuge/runtime/testing';
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
The same names on the root barrel are deprecated and removed in 2.0.
|
|
182
|
+
|
|
95
183
|
---
|
|
96
184
|
|
|
97
185
|
## Verifying this package
|
|
@@ -14,6 +14,11 @@ import { DurableObject } from 'cloudflare:workers';
|
|
|
14
14
|
* gets a parseable response.
|
|
15
15
|
*/
|
|
16
16
|
declare abstract class AbstractDurableObjectWorker<TEnv = Env> extends DurableObject<TEnv> {
|
|
17
|
+
/**
|
|
18
|
+
* @final Owns the error containment; extend through {@link onRequest}. Not
|
|
19
|
+
* refused at runtime in 1.x (that would break consumers), but outside the
|
|
20
|
+
* contract — see `docs/design-charter.md`.
|
|
21
|
+
*/
|
|
17
22
|
fetch(request: Request): Promise<Response>;
|
|
18
23
|
/**
|
|
19
24
|
* The sink for an unhandled rejection at this base's boundary. See
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AbstractDurableObjectWorker.d.ts","sourceRoot":"","sources":["../../src/base/AbstractDurableObjectWorker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGnD;;;;;;;;;;;;;GAaG;AACH,uBAAe,2BAA2B,CAAC,IAAI,GAAG,GAAG,CAAE,SAAQ,aAAa,CAAC,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"AbstractDurableObjectWorker.d.ts","sourceRoot":"","sources":["../../src/base/AbstractDurableObjectWorker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGnD;;;;;;;;;;;;;GAaG;AACH,uBAAe,2BAA2B,CAAC,IAAI,GAAG,GAAG,CAAE,SAAQ,aAAa,CAAC,IAAI,CAAC;IAChF;;;;OAIG;IACU,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC;IASvD;;;;OAIG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAIhE;;;OAGG;IACH,SAAS,CAAC,sBAAsB,IAAI,gBAAgB;IAOpD,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC;CAClE;AAED,OAAO,EAAE,2BAA2B,EAAE,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/base/AbstractDurableObjectWorker.ts"],
|
|
4
|
-
"sourcesContent": ["import { DurableObject } from 'cloudflare:workers';\nimport { BASE_WORKER_MESSAGES } from './baseWorkerError.ts';\n\n/**\n * The Durable Object base: one `fetch` entry, error containment inside it.\n *\n * Converged from the `AbstractDurableObjectWorker` copies in AWS-AccessBridge,\n * CalDAV-Bridge, ChordDHT-Tracker, Edge-Git, Mail-Meow and Mail-Otter (the\n * union is exactly Mail-Meow's shape: the fetch wrapper plus\n * `createExecutionContext` for handlers that need to forward `waitUntil`).\n * Durable-DAV's DO writes more context per handler, but the *base* is the same.\n *\n * A DO has no routing layer, so an unhandled rejection here would surface as a\n * raw 500 with no JSON body and no log. The catch is the boundary: it logs the\n * sanitized error and answers `{ error: 'Internal Error' }` so a caller always\n * gets a parseable response.\n */\nabstract class AbstractDurableObjectWorker<TEnv = Env> extends DurableObject<TEnv> {\n public async fetch(request: Request): Promise<Response> {\n try {\n return await this.onRequest(request);\n } catch (err: unknown) {\n this.reportUnhandled(BASE_WORKER_MESSAGES.durableObjectFetch, err);\n return Response.json({ error: 'Internal Error' }, { status: 500 });\n }\n }\n\n /**\n * The sink for an unhandled rejection at this base's boundary. See\n * `AbstractEntrypointWorker.reportUnhandled` — the base owns the static\n * message, the consumer owns whether the caught value may be logged as-is.\n */\n protected reportUnhandled(message: string, error: unknown): void {\n console.error(message, error);\n }\n\n /**\n * The platform `ExecutionContext` shape, forwards `waitUntil` into the DO's\n * own `ctx` so a handler can keep a task alive past the response.\n */\n protected createExecutionContext(): ExecutionContext {\n return {\n waitUntil: (promise: Promise<unknown>): void => this.ctx.waitUntil(promise),\n passThroughOnException: (): void => undefined,\n };\n }\n\n protected abstract onRequest(request: Request): Promise<Response>;\n}\n\nexport { AbstractDurableObjectWorker };\n"],
|
|
5
|
-
"mappings": "+EAAA,OAAS,iBAAAA,MAAqB,qBAC9B,OAAS,wBAAAC,MAA4B,uBAgBrC,MAAeC,UAAgDF,CAAmB,CAjBlF,MAiBkF,CAAAG,EAAA,
|
|
4
|
+
"sourcesContent": ["import { DurableObject } from 'cloudflare:workers';\nimport { BASE_WORKER_MESSAGES } from './baseWorkerError.ts';\n\n/**\n * The Durable Object base: one `fetch` entry, error containment inside it.\n *\n * Converged from the `AbstractDurableObjectWorker` copies in AWS-AccessBridge,\n * CalDAV-Bridge, ChordDHT-Tracker, Edge-Git, Mail-Meow and Mail-Otter (the\n * union is exactly Mail-Meow's shape: the fetch wrapper plus\n * `createExecutionContext` for handlers that need to forward `waitUntil`).\n * Durable-DAV's DO writes more context per handler, but the *base* is the same.\n *\n * A DO has no routing layer, so an unhandled rejection here would surface as a\n * raw 500 with no JSON body and no log. The catch is the boundary: it logs the\n * sanitized error and answers `{ error: 'Internal Error' }` so a caller always\n * gets a parseable response.\n */\nabstract class AbstractDurableObjectWorker<TEnv = Env> extends DurableObject<TEnv> {\n /**\n * @final Owns the error containment; extend through {@link onRequest}. Not\n * refused at runtime in 1.x (that would break consumers), but outside the\n * contract — see `docs/design-charter.md`.\n */\n public async fetch(request: Request): Promise<Response> {\n try {\n return await this.onRequest(request);\n } catch (err: unknown) {\n this.reportUnhandled(BASE_WORKER_MESSAGES.durableObjectFetch, err);\n return Response.json({ error: 'Internal Error' }, { status: 500 });\n }\n }\n\n /**\n * The sink for an unhandled rejection at this base's boundary. See\n * `AbstractEntrypointWorker.reportUnhandled` — the base owns the static\n * message, the consumer owns whether the caught value may be logged as-is.\n */\n protected reportUnhandled(message: string, error: unknown): void {\n console.error(message, error);\n }\n\n /**\n * The platform `ExecutionContext` shape, forwards `waitUntil` into the DO's\n * own `ctx` so a handler can keep a task alive past the response.\n */\n protected createExecutionContext(): ExecutionContext {\n return {\n waitUntil: (promise: Promise<unknown>): void => this.ctx.waitUntil(promise),\n passThroughOnException: (): void => undefined,\n };\n }\n\n protected abstract onRequest(request: Request): Promise<Response>;\n}\n\nexport { AbstractDurableObjectWorker };\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAS,iBAAAA,MAAqB,qBAC9B,OAAS,wBAAAC,MAA4B,uBAgBrC,MAAeC,UAAgDF,CAAmB,CAjBlF,MAiBkF,CAAAG,EAAA,oCAMzE,MAAM,MAAMC,EAAgB,CACjC,GAAI,CACF,OAAO,MAAM,KAAK,UAAUA,CAAO,CACrC,OAASC,EAAc,CACrB,YAAK,gBAAgBJ,EAAqB,mBAAoBI,CAAG,EAC1D,SAAS,KAAK,CAAE,MAAO,gBAAgB,EAAI,CAAE,OAAQ,GAAG,CAAE,CACnE,CACF,CAOU,gBAAgBC,EAAiBC,EAAc,CACvD,QAAQ,MAAMD,EAASC,CAAK,CAC9B,CAMU,wBAAsB,CAC9B,MAAO,CACL,UAAWJ,EAACK,GAAoC,KAAK,IAAI,UAAUA,CAAO,EAA/D,aACX,uBAAwBL,EAAA,IAAS,GAAT,0BAE5B",
|
|
6
6
|
"names": ["DurableObject", "BASE_WORKER_MESSAGES", "AbstractDurableObjectWorker", "__name", "request", "err", "message", "error", "promise"]
|
|
7
7
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { DurableObjectNamespaceLike } from '../cron/dispatchCronToDurableObject.ts';
|
|
1
2
|
/**
|
|
2
3
|
* Minimal Workers-compatible context types so backend-runtime typechecks
|
|
3
4
|
* without @cloudflare/workers-types. Apps pass the real ExecutionContext /
|
|
@@ -29,8 +30,18 @@ declare abstract class AbstractEntrypointWorker {
|
|
|
29
30
|
* Nothing needed it — `scheduled()` is wired through the platform by the
|
|
30
31
|
* `triggers.crons` entry in the wrangler config, which is how the cron
|
|
31
32
|
* actually runs.
|
|
33
|
+
*
|
|
34
|
+
* @final Owns the error envelope; extend through {@link onRequest}. A
|
|
35
|
+
* subclass override is not refused at runtime (that would break 1.x
|
|
36
|
+
* consumers) but is outside the contract — see `docs/design-charter.md`.
|
|
32
37
|
*/
|
|
33
38
|
fetch(request: Request, env: Env, ctx: WorkerExecutionContext): Promise<Response>;
|
|
39
|
+
/**
|
|
40
|
+
* The cron entry.
|
|
41
|
+
*
|
|
42
|
+
* @final Owns the error containment; extend through {@link onScheduled} or,
|
|
43
|
+
* for the family's standard cron, {@link cronTasksNamespace}.
|
|
44
|
+
*/
|
|
34
45
|
scheduled(event: WorkerScheduledController, env: Env, ctx: WorkerExecutionContext): Promise<void>;
|
|
35
46
|
/**
|
|
36
47
|
* The sink for an unhandled rejection at this base's boundaries.
|
|
@@ -43,7 +54,21 @@ declare abstract class AbstractEntrypointWorker {
|
|
|
43
54
|
*/
|
|
44
55
|
protected reportUnhandled(message: string, error: unknown): void;
|
|
45
56
|
protected abstract onRequest(request: Request, env: Env, ctx: WorkerExecutionContext): Promise<Response>;
|
|
46
|
-
|
|
57
|
+
/**
|
|
58
|
+
* The cron work. Optional since 1.10.
|
|
59
|
+
*
|
|
60
|
+
* The default implements the family pattern — `scheduled → CronTasksDurableObject
|
|
61
|
+
* → TaskRegistry`: when {@link cronTasksNamespace} names a binding, the tick is
|
|
62
|
+
* forwarded to its `idFromName('global')` instance inside `ctx.waitUntil`;
|
|
63
|
+
* otherwise it is a no-op, which is right for a worker with no cron trigger.
|
|
64
|
+
* Overriding it keeps working exactly as before.
|
|
65
|
+
*/
|
|
66
|
+
protected onScheduled(event: WorkerScheduledController, env: Env, ctx: WorkerExecutionContext): Promise<void>;
|
|
67
|
+
/**
|
|
68
|
+
* The cron Durable Object binding the default {@link onScheduled} forwards
|
|
69
|
+
* to, or `null` (the default) for none. Typically `return env.CRON_TASKS`.
|
|
70
|
+
*/
|
|
71
|
+
protected cronTasksNamespace(_env: Env): DurableObjectNamespaceLike | null;
|
|
47
72
|
}
|
|
48
73
|
export { AbstractEntrypointWorker };
|
|
49
74
|
export type { WorkerExecutionContext, WorkerScheduledController };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AbstractEntrypointWorker.d.ts","sourceRoot":"","sources":["../../src/base/AbstractEntrypointWorker.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"AbstractEntrypointWorker.d.ts","sourceRoot":"","sources":["../../src/base/AbstractEntrypointWorker.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,wCAAwC,CAAC;AAGzF;;;;;;;GAOG;AACH,UAAU,sBAAsB;IAC9B,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;IAC3C,sBAAsB,IAAI,IAAI,CAAC;CAChC;AAED,UAAU,yBAAyB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,IAAI,IAAI,CAAC;CACjB;AAED,uBAAe,wBAAwB;IACrC;;;;;;;;;;;;;;;;;OAiBG;IACU,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,sBAAsB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAS9F;;;;;OAKG;IACU,SAAS,CAAC,KAAK,EAAE,yBAAyB,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ9G;;;;;;;;OAQG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAIhE,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,sBAAsB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAExG;;;;;;;;OAQG;IACH,SAAS,CAAC,WAAW,CAAC,KAAK,EAAE,yBAAyB,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ7G;;;OAGG;IACH,SAAS,CAAC,kBAAkB,CAAC,IAAI,EAAE,GAAG,GAAG,0BAA0B,GAAG,IAAI;CAG3E;AAED,OAAO,EAAE,wBAAwB,EAAE,CAAC;AACpC,YAAY,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var a=Object.defineProperty;var c=(s,e)=>a(s,"name",{value:e,configurable:!0});import{dispatchCronToDurableObject as d}from"../cron/dispatchCronToDurableObject.js";import{BASE_WORKER_MESSAGES as o}from"./baseWorkerError.js";class h{static{c(this,"AbstractEntrypointWorker")}async fetch(e,r,n){try{return await this.onRequest(e,r,n)}catch(t){return this.reportUnhandled(o.fetch,t),new Response("Internal Error",{status:500})}}async scheduled(e,r,n){try{await this.onScheduled(e,r,n)}catch(t){this.reportUnhandled(o.scheduled,t)}}reportUnhandled(e,r){console.error(e,r)}onScheduled(e,r,n){const t=this.cronTasksNamespace(r);return t!==null&&n.waitUntil(d(t,{cron:e.cron,scheduledTime:e.scheduledTime})),Promise.resolve()}cronTasksNamespace(e){return null}}export{h as AbstractEntrypointWorker};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/base/AbstractEntrypointWorker.ts"],
|
|
4
|
-
"sourcesContent": ["import { BASE_WORKER_MESSAGES } from './baseWorkerError.ts';\n\n/**\n * Minimal Workers-compatible context types so backend-runtime typechecks\n * without @cloudflare/workers-types. Apps pass the real ExecutionContext /\n * ScheduledController which satisfy these structurally.\n *\n * Converged verbatim from `backend-runtime/src/base/AbstractEntrypointWorker.ts`\n * (identical in all nine repos).\n */\ninterface WorkerExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n passThroughOnException(): void;\n}\n\ninterface WorkerScheduledController {\n cron: string;\n scheduledTime: number;\n noRetry(): void;\n}\n\nabstract class AbstractEntrypointWorker {\n /**\n * The HTTP request path.\n *\n * There is deliberately no `/__scheduled` branch here. It used to run before\n * `onRequest`, which made `GET /__scheduled` an unauthenticated, un-rated\n * trigger for the scheduled work: it bypassed the app's security headers, its\n * request scope, and its rate limits, and any caller could fire the cron\n * Durable Object on demand. `noRetry` was a `(): void => undefined` stub, so\n * the retry semantics were lost too.\n *\n * Nothing needed it — `scheduled()` is wired through the platform by the\n * `triggers.crons` entry in the wrangler config, which is how the cron\n * actually runs.\n */\n public async fetch(request: Request, env: Env, ctx: WorkerExecutionContext): Promise<Response> {\n try {\n return await this.onRequest(request, env, ctx);\n } catch (err: unknown) {\n this.reportUnhandled(BASE_WORKER_MESSAGES.fetch, err);\n return new Response('Internal Error', { status: 500 });\n }\n }\n\n public async scheduled(event: WorkerScheduledController, env: Env, ctx: WorkerExecutionContext): Promise<void> {\n try {\n await this.onScheduled(event, env, ctx);\n } catch (err: unknown) {\n this.reportUnhandled(BASE_WORKER_MESSAGES.scheduled, err);\n }\n }\n\n /**\n * The sink for an unhandled rejection at this base's boundaries.\n *\n * Overridable because the default hands the caught value to `console.error`\n * verbatim, which is only safe when nothing in the call path can carry a\n * secret. A consumer whose entrypoint can transitively carry one overrides\n * this to a redacting sink, and keeps the static message as the argument, so\n * the redaction decision stays in the consumer where the threat model lives.\n */\n protected reportUnhandled(message: string, error: unknown): void {\n console.error(message, error);\n }\n\n protected abstract onRequest(request: Request, env: Env, ctx: WorkerExecutionContext): Promise<Response>;\n\n protected
|
|
5
|
-
"mappings": "+EAAA,OAAS,
|
|
6
|
-
"names": ["BASE_WORKER_MESSAGES", "AbstractEntrypointWorker", "__name", "request", "env", "ctx", "err", "event", "message", "error"]
|
|
4
|
+
"sourcesContent": ["import { dispatchCronToDurableObject } from '../cron/dispatchCronToDurableObject.ts';\nimport type { DurableObjectNamespaceLike } from '../cron/dispatchCronToDurableObject.ts';\nimport { BASE_WORKER_MESSAGES } from './baseWorkerError.ts';\n\n/**\n * Minimal Workers-compatible context types so backend-runtime typechecks\n * without @cloudflare/workers-types. Apps pass the real ExecutionContext /\n * ScheduledController which satisfy these structurally.\n *\n * Converged verbatim from `backend-runtime/src/base/AbstractEntrypointWorker.ts`\n * (identical in all nine repos).\n */\ninterface WorkerExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n passThroughOnException(): void;\n}\n\ninterface WorkerScheduledController {\n cron: string;\n scheduledTime: number;\n noRetry(): void;\n}\n\nabstract class AbstractEntrypointWorker {\n /**\n * The HTTP request path.\n *\n * There is deliberately no `/__scheduled` branch here. It used to run before\n * `onRequest`, which made `GET /__scheduled` an unauthenticated, un-rated\n * trigger for the scheduled work: it bypassed the app's security headers, its\n * request scope, and its rate limits, and any caller could fire the cron\n * Durable Object on demand. `noRetry` was a `(): void => undefined` stub, so\n * the retry semantics were lost too.\n *\n * Nothing needed it — `scheduled()` is wired through the platform by the\n * `triggers.crons` entry in the wrangler config, which is how the cron\n * actually runs.\n *\n * @final Owns the error envelope; extend through {@link onRequest}. A\n * subclass override is not refused at runtime (that would break 1.x\n * consumers) but is outside the contract — see `docs/design-charter.md`.\n */\n public async fetch(request: Request, env: Env, ctx: WorkerExecutionContext): Promise<Response> {\n try {\n return await this.onRequest(request, env, ctx);\n } catch (err: unknown) {\n this.reportUnhandled(BASE_WORKER_MESSAGES.fetch, err);\n return new Response('Internal Error', { status: 500 });\n }\n }\n\n /**\n * The cron entry.\n *\n * @final Owns the error containment; extend through {@link onScheduled} or,\n * for the family's standard cron, {@link cronTasksNamespace}.\n */\n public async scheduled(event: WorkerScheduledController, env: Env, ctx: WorkerExecutionContext): Promise<void> {\n try {\n await this.onScheduled(event, env, ctx);\n } catch (err: unknown) {\n this.reportUnhandled(BASE_WORKER_MESSAGES.scheduled, err);\n }\n }\n\n /**\n * The sink for an unhandled rejection at this base's boundaries.\n *\n * Overridable because the default hands the caught value to `console.error`\n * verbatim, which is only safe when nothing in the call path can carry a\n * secret. A consumer whose entrypoint can transitively carry one overrides\n * this to a redacting sink, and keeps the static message as the argument, so\n * the redaction decision stays in the consumer where the threat model lives.\n */\n protected reportUnhandled(message: string, error: unknown): void {\n console.error(message, error);\n }\n\n protected abstract onRequest(request: Request, env: Env, ctx: WorkerExecutionContext): Promise<Response>;\n\n /**\n * The cron work. Optional since 1.10.\n *\n * The default implements the family pattern — `scheduled → CronTasksDurableObject\n * → TaskRegistry`: when {@link cronTasksNamespace} names a binding, the tick is\n * forwarded to its `idFromName('global')` instance inside `ctx.waitUntil`;\n * otherwise it is a no-op, which is right for a worker with no cron trigger.\n * Overriding it keeps working exactly as before.\n */\n protected onScheduled(event: WorkerScheduledController, env: Env, ctx: WorkerExecutionContext): Promise<void> {\n const namespace = this.cronTasksNamespace(env);\n if (namespace !== null) {\n ctx.waitUntil(dispatchCronToDurableObject(namespace, { cron: event.cron, scheduledTime: event.scheduledTime }));\n }\n return Promise.resolve();\n }\n\n /**\n * The cron Durable Object binding the default {@link onScheduled} forwards\n * to, or `null` (the default) for none. Typically `return env.CRON_TASKS`.\n */\n protected cronTasksNamespace(_env: Env): DurableObjectNamespaceLike | null {\n return null;\n }\n}\n\nexport { AbstractEntrypointWorker };\nexport type { WorkerExecutionContext, WorkerScheduledController };\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAS,+BAAAA,MAAmC,yCAE5C,OAAS,wBAAAC,MAA4B,uBAqBrC,MAAeC,CAAwB,CAvBvC,MAuBuC,CAAAC,EAAA,iCAmB9B,MAAM,MAAMC,EAAkBC,EAAUC,EAA2B,CACxE,GAAI,CACF,OAAO,MAAM,KAAK,UAAUF,EAASC,EAAKC,CAAG,CAC/C,OAASC,EAAc,CACrB,YAAK,gBAAgBN,EAAqB,MAAOM,CAAG,EAC7C,IAAI,SAAS,iBAAkB,CAAE,OAAQ,GAAG,CAAE,CACvD,CACF,CAQO,MAAM,UAAUC,EAAkCH,EAAUC,EAA2B,CAC5F,GAAI,CACF,MAAM,KAAK,YAAYE,EAAOH,EAAKC,CAAG,CACxC,OAASC,EAAc,CACrB,KAAK,gBAAgBN,EAAqB,UAAWM,CAAG,CAC1D,CACF,CAWU,gBAAgBE,EAAiBC,EAAc,CACvD,QAAQ,MAAMD,EAASC,CAAK,CAC9B,CAaU,YAAYF,EAAkCH,EAAUC,EAA2B,CAC3F,MAAMK,EAAY,KAAK,mBAAmBN,CAAG,EAC7C,OAAIM,IAAc,MAChBL,EAAI,UAAUN,EAA4BW,EAAW,CAAE,KAAMH,EAAM,KAAM,cAAeA,EAAM,aAAa,CAAE,CAAC,EAEzG,QAAQ,QAAO,CACxB,CAMU,mBAAmBI,EAAS,CACpC,OAAO,IACT",
|
|
6
|
+
"names": ["dispatchCronToDurableObject", "BASE_WORKER_MESSAGES", "AbstractEntrypointWorker", "__name", "request", "env", "ctx", "err", "event", "message", "error", "namespace", "_env"]
|
|
7
7
|
}
|
|
@@ -19,6 +19,11 @@ import type { WorkerExecutionContext } from './AbstractEntrypointWorker.ts';
|
|
|
19
19
|
* full surface with no cast and no duplication of the platform's own types.
|
|
20
20
|
*/
|
|
21
21
|
declare abstract class AbstractQueueWorker<TBatch = unknown> {
|
|
22
|
+
/**
|
|
23
|
+
* @final Owns the error containment; extend through {@link onQueue}. Not
|
|
24
|
+
* refused at runtime in 1.x (that would break consumers), but outside the
|
|
25
|
+
* contract — see `docs/design-charter.md`.
|
|
26
|
+
*/
|
|
22
27
|
queue(batch: TBatch, env: Env, ctx: WorkerExecutionContext): Promise<void>;
|
|
23
28
|
/**
|
|
24
29
|
* The sink for an unhandled rejection at this base's boundary. See
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AbstractQueueWorker.d.ts","sourceRoot":"","sources":["../../src/base/AbstractQueueWorker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAG5E;;;;;;;;;;;;;;;;;;GAkBG;AACH,uBAAe,mBAAmB,CAAC,MAAM,GAAG,OAAO;
|
|
1
|
+
{"version":3,"file":"AbstractQueueWorker.d.ts","sourceRoot":"","sources":["../../src/base/AbstractQueueWorker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAG5E;;;;;;;;;;;;;;;;;;GAkBG;AACH,uBAAe,mBAAmB,CAAC,MAAM,GAAG,OAAO;IACjD;;;;OAIG;IACU,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;IASvF;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAIhE,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;CAChG;AAED,OAAO,EAAE,mBAAmB,EAAE,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/base/AbstractQueueWorker.ts"],
|
|
4
|
-
"sourcesContent": ["import type { WorkerExecutionContext } from './AbstractEntrypointWorker.ts';\nimport { BASE_WORKER_MESSAGES } from './baseWorkerError.ts';\n\n/**\n * The queue consumer base, converged from the `AbstractQueueWorker` copies in\n * Edge-Git and Mail-Otter (the only two repos with queue consumers).\n *\n * It rethrows after logging: a queue message that failed must be *retried* by\n * the platform, and a base that swallowed the rejection would turn a transient\n * handler failure into an acked, dropped message.\n *\n * **The batch is a type parameter, not a modelled shape.** This base never\n * reads the batch — it forwards it — so declaring a structural stand-in for it\n * bought nothing and cost correctness: the old `WorkerMessageBatch<T>` modelled\n * `messages: T[]`, which is wrong twice over (the platform's elements are\n * `Message<T>`, and a real batch also carries `queue`, `metadata`, `ackAll` and\n * `retryAll`). A consumer subclassing against that type lost `batch.queue` and\n * every `message.ack()`/`message.retry()`, and had to cast to get them back.\n *\n * Passing the platform `MessageBatch<Body>` as `TBatch` gives the handler the\n * full surface with no cast and no duplication of the platform's own types.\n */\nabstract class AbstractQueueWorker<TBatch = unknown> {\n public async queue(batch: TBatch, env: Env, ctx: WorkerExecutionContext): Promise<void> {\n try {\n await this.onQueue(batch, env, ctx);\n } catch (err: unknown) {\n this.reportUnhandled(BASE_WORKER_MESSAGES.queue, err);\n throw err;\n }\n }\n\n /**\n * The sink for an unhandled rejection at this base's boundary. See\n * `AbstractEntrypointWorker.reportUnhandled`.\n */\n protected reportUnhandled(message: string, error: unknown): void {\n console.error(message, error);\n }\n\n protected abstract onQueue(batch: TBatch, env: Env, ctx: WorkerExecutionContext): Promise<void>;\n}\n\nexport { AbstractQueueWorker };\n"],
|
|
5
|
-
"mappings": "+EACA,OAAS,wBAAAA,MAA4B,uBAqBrC,MAAeC,CAAmB,CArBlC,MAqBkC,CAAAC,EAAA,
|
|
4
|
+
"sourcesContent": ["import type { WorkerExecutionContext } from './AbstractEntrypointWorker.ts';\nimport { BASE_WORKER_MESSAGES } from './baseWorkerError.ts';\n\n/**\n * The queue consumer base, converged from the `AbstractQueueWorker` copies in\n * Edge-Git and Mail-Otter (the only two repos with queue consumers).\n *\n * It rethrows after logging: a queue message that failed must be *retried* by\n * the platform, and a base that swallowed the rejection would turn a transient\n * handler failure into an acked, dropped message.\n *\n * **The batch is a type parameter, not a modelled shape.** This base never\n * reads the batch — it forwards it — so declaring a structural stand-in for it\n * bought nothing and cost correctness: the old `WorkerMessageBatch<T>` modelled\n * `messages: T[]`, which is wrong twice over (the platform's elements are\n * `Message<T>`, and a real batch also carries `queue`, `metadata`, `ackAll` and\n * `retryAll`). A consumer subclassing against that type lost `batch.queue` and\n * every `message.ack()`/`message.retry()`, and had to cast to get them back.\n *\n * Passing the platform `MessageBatch<Body>` as `TBatch` gives the handler the\n * full surface with no cast and no duplication of the platform's own types.\n */\nabstract class AbstractQueueWorker<TBatch = unknown> {\n /**\n * @final Owns the error containment; extend through {@link onQueue}. Not\n * refused at runtime in 1.x (that would break consumers), but outside the\n * contract — see `docs/design-charter.md`.\n */\n public async queue(batch: TBatch, env: Env, ctx: WorkerExecutionContext): Promise<void> {\n try {\n await this.onQueue(batch, env, ctx);\n } catch (err: unknown) {\n this.reportUnhandled(BASE_WORKER_MESSAGES.queue, err);\n throw err;\n }\n }\n\n /**\n * The sink for an unhandled rejection at this base's boundary. See\n * `AbstractEntrypointWorker.reportUnhandled`.\n */\n protected reportUnhandled(message: string, error: unknown): void {\n console.error(message, error);\n }\n\n protected abstract onQueue(batch: TBatch, env: Env, ctx: WorkerExecutionContext): Promise<void>;\n}\n\nexport { AbstractQueueWorker };\n"],
|
|
5
|
+
"mappings": "+EACA,OAAS,wBAAAA,MAA4B,uBAqBrC,MAAeC,CAAmB,CArBlC,MAqBkC,CAAAC,EAAA,4BAMzB,MAAM,MAAMC,EAAeC,EAAUC,EAA2B,CACrE,GAAI,CACF,MAAM,KAAK,QAAQF,EAAOC,EAAKC,CAAG,CACpC,OAASC,EAAc,CACrB,WAAK,gBAAgBN,EAAqB,MAAOM,CAAG,EAC9CA,CACR,CACF,CAMU,gBAAgBC,EAAiBC,EAAc,CACvD,QAAQ,MAAMD,EAASC,CAAK,CAC9B",
|
|
6
6
|
"names": ["BASE_WORKER_MESSAGES", "AbstractQueueWorker", "__name", "batch", "env", "ctx", "err", "message", "error"]
|
|
7
7
|
}
|
|
@@ -23,6 +23,11 @@ import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers';
|
|
|
23
23
|
* bindings deliberately.
|
|
24
24
|
*/
|
|
25
25
|
declare abstract class AbstractWorkflowWorker<TPayload = unknown, TResult = unknown, TEnv = Env> extends WorkflowEntrypoint<TEnv, TPayload> {
|
|
26
|
+
/**
|
|
27
|
+
* @final Owns the error containment; extend through {@link onWorkflow}. Not
|
|
28
|
+
* refused at runtime in 1.x (that would break consumers), but outside the
|
|
29
|
+
* contract — see `docs/design-charter.md`.
|
|
30
|
+
*/
|
|
26
31
|
run(event: Readonly<WorkflowEvent<TPayload>>, step: WorkflowStep): Promise<TResult>;
|
|
27
32
|
/**
|
|
28
33
|
* The sink for an unhandled rejection at this base's boundary. See
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AbstractWorkflowWorker.d.ts","sourceRoot":"","sources":["../../src/base/AbstractWorkflowWorker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGtE;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,uBAAe,sBAAsB,CAAC,QAAQ,GAAG,OAAO,EAAE,OAAO,GAAG,OAAO,EAAE,IAAI,GAAG,GAAG,CAAE,SAAQ,kBAAkB,CAAC,IAAI,EAAE,QAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"AbstractWorkflowWorker.d.ts","sourceRoot":"","sources":["../../src/base/AbstractWorkflowWorker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGtE;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,uBAAe,sBAAsB,CAAC,QAAQ,GAAG,OAAO,EAAE,OAAO,GAAG,OAAO,EAAE,IAAI,GAAG,GAAG,CAAE,SAAQ,kBAAkB,CAAC,IAAI,EAAE,QAAQ,CAAC;IACjI;;;;OAIG;IACU,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,EAAE,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC;IAShG;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAIhE,SAAS,CAAC,QAAQ,CAAC,UAAU,CAAC,KAAK,EAAE,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,EAAE,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC;CAC9G;AAED,OAAO,EAAE,sBAAsB,EAAE,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/base/AbstractWorkflowWorker.ts"],
|
|
4
|
-
"sourcesContent": ["import { WorkflowEntrypoint } from 'cloudflare:workers';\nimport type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers';\nimport { BASE_WORKER_MESSAGES } from './baseWorkerError.ts';\n\n/**\n * The Workflow base, converged from the `AbstractWorkflowWorker` copies in\n * Edge-Git and Mail-Otter (Edge-Sonic ships the same shape as `runWorkflow.ts`\n * with a `WorkflowEntrypoint` wrapper around it).\n *\n * It extends the platform `WorkflowEntrypoint` because a workflow handler needs\n * `this.env` — it is where the bindings come from, and every step in a real\n * workflow builds a request scope from it. An earlier version of this file\n * modelled `WorkflowEventLike`/`WorkflowStepLike` as standalone structural\n * types and dropped the parent class, which removed `this.env` and reduced\n * `step.do` to `(name, callback)`. That is not a stricter shape, it is a lossy\n * one: it took away the per-step `retries`/`timeout` config that makes a step\n * retryable under the platform rather than a bare coroutine call. Both are\n * restored here, and the structural types are gone with them — the platform\n * types are the ones that were correct all along.\n *\n * `TEnv` is last and defaulted rather than first: every consumer in the family\n * writes `AbstractWorkflowWorker<TPayload, TResult>`, so leading with the env\n * type would silently reinterpret their payload as the environment. The default\n * is the ambient `Env`, which is what a handler wants unless it has narrowed its\n * bindings deliberately.\n */\nabstract class AbstractWorkflowWorker<TPayload = unknown, TResult = unknown, TEnv = Env> extends WorkflowEntrypoint<TEnv, TPayload> {\n public async run(event: Readonly<WorkflowEvent<TPayload>>, step: WorkflowStep): Promise<TResult> {\n try {\n return await this.onWorkflow(event, step);\n } catch (err: unknown) {\n this.reportUnhandled(BASE_WORKER_MESSAGES.workflow, err);\n throw err;\n }\n }\n\n /**\n * The sink for an unhandled rejection at this base's boundary. See\n * `AbstractEntrypointWorker.reportUnhandled`.\n */\n protected reportUnhandled(message: string, error: unknown): void {\n console.error(message, error);\n }\n\n protected abstract onWorkflow(event: Readonly<WorkflowEvent<TPayload>>, step: WorkflowStep): Promise<TResult>;\n}\n\nexport { AbstractWorkflowWorker };\n"],
|
|
5
|
-
"mappings": "+EAAA,OAAS,sBAAAA,MAA0B,qBAEnC,OAAS,wBAAAC,MAA4B,uBAwBrC,MAAeC,UAAkFF,CAAkC,CA1BnI,MA0BmI,CAAAG,EAAA,+
|
|
4
|
+
"sourcesContent": ["import { WorkflowEntrypoint } from 'cloudflare:workers';\nimport type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers';\nimport { BASE_WORKER_MESSAGES } from './baseWorkerError.ts';\n\n/**\n * The Workflow base, converged from the `AbstractWorkflowWorker` copies in\n * Edge-Git and Mail-Otter (Edge-Sonic ships the same shape as `runWorkflow.ts`\n * with a `WorkflowEntrypoint` wrapper around it).\n *\n * It extends the platform `WorkflowEntrypoint` because a workflow handler needs\n * `this.env` — it is where the bindings come from, and every step in a real\n * workflow builds a request scope from it. An earlier version of this file\n * modelled `WorkflowEventLike`/`WorkflowStepLike` as standalone structural\n * types and dropped the parent class, which removed `this.env` and reduced\n * `step.do` to `(name, callback)`. That is not a stricter shape, it is a lossy\n * one: it took away the per-step `retries`/`timeout` config that makes a step\n * retryable under the platform rather than a bare coroutine call. Both are\n * restored here, and the structural types are gone with them — the platform\n * types are the ones that were correct all along.\n *\n * `TEnv` is last and defaulted rather than first: every consumer in the family\n * writes `AbstractWorkflowWorker<TPayload, TResult>`, so leading with the env\n * type would silently reinterpret their payload as the environment. The default\n * is the ambient `Env`, which is what a handler wants unless it has narrowed its\n * bindings deliberately.\n */\nabstract class AbstractWorkflowWorker<TPayload = unknown, TResult = unknown, TEnv = Env> extends WorkflowEntrypoint<TEnv, TPayload> {\n /**\n * @final Owns the error containment; extend through {@link onWorkflow}. Not\n * refused at runtime in 1.x (that would break consumers), but outside the\n * contract — see `docs/design-charter.md`.\n */\n public async run(event: Readonly<WorkflowEvent<TPayload>>, step: WorkflowStep): Promise<TResult> {\n try {\n return await this.onWorkflow(event, step);\n } catch (err: unknown) {\n this.reportUnhandled(BASE_WORKER_MESSAGES.workflow, err);\n throw err;\n }\n }\n\n /**\n * The sink for an unhandled rejection at this base's boundary. See\n * `AbstractEntrypointWorker.reportUnhandled`.\n */\n protected reportUnhandled(message: string, error: unknown): void {\n console.error(message, error);\n }\n\n protected abstract onWorkflow(event: Readonly<WorkflowEvent<TPayload>>, step: WorkflowStep): Promise<TResult>;\n}\n\nexport { AbstractWorkflowWorker };\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAS,sBAAAA,MAA0B,qBAEnC,OAAS,wBAAAC,MAA4B,uBAwBrC,MAAeC,UAAkFF,CAAkC,CA1BnI,MA0BmI,CAAAG,EAAA,+BAM1H,MAAM,IAAIC,EAA0CC,EAAkB,CAC3E,GAAI,CACF,OAAO,MAAM,KAAK,WAAWD,EAAOC,CAAI,CAC1C,OAASC,EAAc,CACrB,WAAK,gBAAgBL,EAAqB,SAAUK,CAAG,EACjDA,CACR,CACF,CAMU,gBAAgBC,EAAiBC,EAAc,CACvD,QAAQ,MAAMD,EAASC,CAAK,CAC9B",
|
|
6
6
|
"names": ["WorkflowEntrypoint", "BASE_WORKER_MESSAGES", "AbstractWorkflowWorker", "__name", "event", "step", "err", "message", "error"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime enforcement of `@final` entry points.
|
|
3
|
+
*
|
|
4
|
+
* TypeScript has no `final` modifier, so a subclass can replace a base's
|
|
5
|
+
* public entry method and silently drop the orchestration it owns — the
|
|
6
|
+
* expiry guard, the error envelope, the run bookkeeping. The bases that own
|
|
7
|
+
* an invariant call this from their constructor: it walks the prototype chain
|
|
8
|
+
* from the concrete class up to (not including) the owning base and refuses
|
|
9
|
+
* to construct a subclass that redeclares one of the named members.
|
|
10
|
+
*
|
|
11
|
+
* A construction-time `TypeError` rather than a lint rule, because the
|
|
12
|
+
* failure must be loud in every repo regardless of its lint configuration, and
|
|
13
|
+
* a Durable Object or queue consumer that cannot be constructed fails its
|
|
14
|
+
* first request in every environment — including the test suite.
|
|
15
|
+
*
|
|
16
|
+
* @param instance The object under construction (`this`).
|
|
17
|
+
* @param owner The base class that owns the members.
|
|
18
|
+
* @param members The member names no subclass may redeclare.
|
|
19
|
+
*/
|
|
20
|
+
declare function assertFinalMembers(instance: object, owner: abstract new (...args: never[]) => unknown, members: readonly string[]): void;
|
|
21
|
+
export { assertFinalMembers };
|
|
22
|
+
//# sourceMappingURL=finalMembers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"finalMembers.d.ts","sourceRoot":"","sources":["../../src/base/finalMembers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,iBAAS,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,MAAM,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,OAAO,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAajI;AAED,OAAO,EAAE,kBAAkB,EAAE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var p=Object.defineProperty;var n=(o,e)=>p(o,"name",{value:e,configurable:!0});function a(o,e,s){let t=Object.getPrototypeOf(o);for(;t!==null&&t!==e.prototype;){for(const r of s)if(Object.prototype.hasOwnProperty.call(t,r)){const c=t.constructor.name;throw new TypeError(`${c} overrides ${r}(), which ${e.name} owns (@final). Extend it through the documented protected hooks instead.`)}t=Object.getPrototypeOf(t)}}n(a,"assertFinalMembers");export{a as assertFinalMembers};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/base/finalMembers.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Runtime enforcement of `@final` entry points.\n *\n * TypeScript has no `final` modifier, so a subclass can replace a base's\n * public entry method and silently drop the orchestration it owns — the\n * expiry guard, the error envelope, the run bookkeeping. The bases that own\n * an invariant call this from their constructor: it walks the prototype chain\n * from the concrete class up to (not including) the owning base and refuses\n * to construct a subclass that redeclares one of the named members.\n *\n * A construction-time `TypeError` rather than a lint rule, because the\n * failure must be loud in every repo regardless of its lint configuration, and\n * a Durable Object or queue consumer that cannot be constructed fails its\n * first request in every environment — including the test suite.\n *\n * @param instance The object under construction (`this`).\n * @param owner The base class that owns the members.\n * @param members The member names no subclass may redeclare.\n */\nfunction assertFinalMembers(instance: object, owner: abstract new (...args: never[]) => unknown, members: readonly string[]): void {\n let prototype: object | null = Object.getPrototypeOf(instance) as object | null;\n while (prototype !== null && prototype !== owner.prototype) {\n for (const member of members) {\n if (Object.prototype.hasOwnProperty.call(prototype, member)) {\n const subclass = (prototype as { constructor: { name: string } }).constructor.name;\n throw new TypeError(\n `${subclass} overrides ${member}(), which ${owner.name} owns (@final). Extend it through the documented protected hooks instead.`,\n );\n }\n }\n prototype = Object.getPrototypeOf(prototype) as object | null;\n }\n}\n\nexport { assertFinalMembers };\n"],
|
|
5
|
+
"mappings": "+EAmBA,SAASA,EAAmBC,EAAkBC,EAAmDC,EAA0B,CACzH,IAAIC,EAA2B,OAAO,eAAeH,CAAQ,EAC7D,KAAOG,IAAc,MAAQA,IAAcF,EAAM,WAAW,CAC1D,UAAWG,KAAUF,EACnB,GAAI,OAAO,UAAU,eAAe,KAAKC,EAAWC,CAAM,EAAG,CAC3D,MAAMC,EAAYF,EAAgD,YAAY,KAC9E,MAAM,IAAI,UACR,GAAGE,CAAQ,cAAcD,CAAM,aAAaH,EAAM,IAAI,2EAA2E,CAErI,CAEFE,EAAY,OAAO,eAAeA,CAAS,CAC7C,CACF,CAbSG,EAAAP,EAAA",
|
|
6
|
+
"names": ["assertFinalMembers", "instance", "owner", "members", "prototype", "member", "subclass", "__name"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { DurableObject } from 'cloudflare:workers';
|
|
2
|
+
import { AbstractDurableObjectWorker } from '../base/AbstractDurableObjectWorker.ts';
|
|
3
|
+
import type { Logger } from '../logger.ts';
|
|
4
|
+
import type { TaskRegistry } from '../scheduled/index.ts';
|
|
5
|
+
import type { CronRunContext } from './cronContract.ts';
|
|
6
|
+
/**
|
|
7
|
+
* The aggregate a run rejects with when one or more tasks failed.
|
|
8
|
+
*
|
|
9
|
+
* The message is a count, never the tasks' own messages: a task failure can
|
|
10
|
+
* carry provider text (a token, a signed URL), and this error reaches a log
|
|
11
|
+
* line. The causes are kept on `failures` for a hook that knows how to redact.
|
|
12
|
+
*/
|
|
13
|
+
declare class CronRunError extends Error {
|
|
14
|
+
readonly failures: readonly unknown[];
|
|
15
|
+
constructor(failures: readonly unknown[]);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The family's cron Durable Object.
|
|
19
|
+
*
|
|
20
|
+
* Converged from `apps/background/src/CronTasksWorker.ts` in AWS-AccessBridge
|
|
21
|
+
* (the one with `MAX_RUN_AGE_MS`), Mail-Meow, Mail-Bee, Mail-Otter,
|
|
22
|
+
* CalDAV-Bridge and ChordDHT-Tracker. The entry worker's `scheduled()` posts
|
|
23
|
+
* `{ cron, scheduledTime }` to `POST /run` on the single `idFromName('global')`
|
|
24
|
+
* instance (see `dispatchCronToDurableObject`), and this object serialises the
|
|
25
|
+
* runs.
|
|
26
|
+
*
|
|
27
|
+
* ## The contract (strict — owned here)
|
|
28
|
+
*
|
|
29
|
+
* | Request | Response |
|
|
30
|
+
* | ------------------------------- | ------------------------------------------- |
|
|
31
|
+
* | any path but `/run` | 404 `{ error: 'Not Found' }` |
|
|
32
|
+
* | `/run`, not `POST` | 405 `{ error: 'Method Not Allowed' }` |
|
|
33
|
+
* | `POST /run` while a run is live | 202 `{ status: 'already_running' }` |
|
|
34
|
+
* | `POST /run`, every task settled | 200 `{ status: 'completed' }` |
|
|
35
|
+
* | `POST /run`, any task rejected | 500 `{ status: 'failed' }` |
|
|
36
|
+
*
|
|
37
|
+
* The in-flight guard **expires** after {@link maxRunAgeMs}: the guard is
|
|
38
|
+
* in-memory, so a task whose upstream call never settles would otherwise make
|
|
39
|
+
* every later tick answer 202 until eviction — the cron that appears to run and
|
|
40
|
+
* never does. An expired run is abandoned, not cancelled (nothing can cancel a
|
|
41
|
+
* hung await), and its `finally` compares identity so a late settle cannot
|
|
42
|
+
* clear the guard of the run that replaced it.
|
|
43
|
+
*
|
|
44
|
+
* Phases run in the registry's ascending order; tasks inside one phase run in
|
|
45
|
+
* parallel under `allSettled`, so one failure neither aborts its phase-mates nor
|
|
46
|
+
* stops the later phases (pruning still runs behind a failed refresh). The run
|
|
47
|
+
* then rejects with a {@link CronRunError} so the verdict is still `failed`.
|
|
48
|
+
*
|
|
49
|
+
* `fetch` and `onRequest` are `@final`: a subclass that redeclares either is
|
|
50
|
+
* refused at construction.
|
|
51
|
+
*
|
|
52
|
+
* ## Extending (flexible)
|
|
53
|
+
*
|
|
54
|
+
* - {@link createRegistry} — required: the tasks for this run (it receives the
|
|
55
|
+
* cron expression, so one object can serve several schedules).
|
|
56
|
+
* - {@link onRunStart} / {@link onRunComplete} / {@link onRunError} — lifecycle
|
|
57
|
+
* hooks (e.g. AWS-AccessBridge starts its collection workflow in `onRunStart`).
|
|
58
|
+
* - {@link maxRunAgeMs}, {@link now}, {@link logger} — the expiry window, the
|
|
59
|
+
* clock and the log port.
|
|
60
|
+
*/
|
|
61
|
+
declare abstract class CronTasksDurableObject<TEnv = Env> extends AbstractDurableObjectWorker<TEnv> {
|
|
62
|
+
private currentRun;
|
|
63
|
+
constructor(ctx: ConstructorParameters<typeof DurableObject>[0], env: TEnv);
|
|
64
|
+
/**
|
|
65
|
+
* @final The `/run` contract. Not an extension point — see the class note.
|
|
66
|
+
*/
|
|
67
|
+
protected onRequest(request: Request): Promise<Response>;
|
|
68
|
+
/**
|
|
69
|
+
* The tasks for one run. Called once per accepted `POST /run`.
|
|
70
|
+
*/
|
|
71
|
+
protected abstract createRegistry(env: TEnv, run: CronRunContext): TaskRegistry;
|
|
72
|
+
/**
|
|
73
|
+
Runs before the first phase. A rejection fails the run.
|
|
74
|
+
*/
|
|
75
|
+
protected onRunStart(_run: CronRunContext): Promise<void> | void;
|
|
76
|
+
/**
|
|
77
|
+
Runs after every phase settled with no task failure.
|
|
78
|
+
*/
|
|
79
|
+
protected onRunComplete(_run: CronRunContext): Promise<void> | void;
|
|
80
|
+
/**
|
|
81
|
+
* Runs when the run failed, before the 500 is answered.
|
|
82
|
+
*
|
|
83
|
+
* The default logs a static line and the failure count only. Override to
|
|
84
|
+
* route the causes (`error.failures` on a {@link CronRunError}) through a
|
|
85
|
+
* redactor; a rejection from this hook is swallowed so it cannot mask the
|
|
86
|
+
* original failure.
|
|
87
|
+
*/
|
|
88
|
+
protected onRunError(run: CronRunContext, error: unknown): Promise<void> | void;
|
|
89
|
+
/**
|
|
90
|
+
How long a live run holds the `already_running` guard. Default 15 minutes.
|
|
91
|
+
*/
|
|
92
|
+
protected maxRunAgeMs(): number;
|
|
93
|
+
/**
|
|
94
|
+
The clock, in epoch milliseconds. Override to inject a test clock.
|
|
95
|
+
*/
|
|
96
|
+
protected now(): number;
|
|
97
|
+
/**
|
|
98
|
+
* The log port. Every line this class writes is a static message plus
|
|
99
|
+
* numeric or cron fields — never a caught value.
|
|
100
|
+
*/
|
|
101
|
+
protected logger(): Logger;
|
|
102
|
+
private execute;
|
|
103
|
+
private runPhases;
|
|
104
|
+
/**
|
|
105
|
+
* The request body, leniently: a malformed body still runs (with the current
|
|
106
|
+
* time and an empty cron), because a skipped tick is worse than a tick with
|
|
107
|
+
* synthesized metadata — but it is logged, since it means the trigger is wrong.
|
|
108
|
+
*/
|
|
109
|
+
private readRun;
|
|
110
|
+
private static answer;
|
|
111
|
+
}
|
|
112
|
+
export { CronRunError, CronTasksDurableObject };
|
|
113
|
+
//# sourceMappingURL=CronTasksDurableObject.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CronTasksDurableObject.d.ts","sourceRoot":"","sources":["../../src/cron/CronTasksDurableObject.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AAGrF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,KAAK,EAKV,YAAY,EACb,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,cAAc,EAAiB,MAAM,mBAAmB,CAAC;AAEvE;;;;;;GAMG;AACH,cAAM,YAAa,SAAQ,KAAK;aACK,QAAQ,EAAE,SAAS,OAAO,EAAE;gBAA5B,QAAQ,EAAE,SAAS,OAAO,EAAE;CAIhE;AAOD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,uBAAe,sBAAsB,CAAC,IAAI,GAAG,GAAG,CAAE,SAAQ,2BAA2B,CAAC,IAAI,CAAC;IACzF,OAAO,CAAC,UAAU,CAA0B;gBAEzB,GAAG,EAAE,qBAAqB,CAAC,OAAO,aAAa,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,IAAI;IAKjF;;OAEG;cACa,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC;IAmC9D;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,cAAc,GAAG,YAAY;IAE/E;;MAEE;IACF,SAAS,CAAC,UAAU,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI;IAIhE;;MAEE;IACF,SAAS,CAAC,aAAa,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI;IAInE;;;;;;;OAOG;IACH,SAAS,CAAC,UAAU,CAAC,GAAG,EAAE,cAAc,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI;IAK/E;;MAEE;IACF,SAAS,CAAC,WAAW,IAAI,MAAM;IAI/B;;MAEE;IACF,SAAS,CAAC,GAAG,IAAI,MAAM;IAIvB;;;OAGG;IACH,SAAS,CAAC,MAAM,IAAI,MAAM;YAIZ,OAAO;YAgBP,SAAS;IAevB;;;;OAIG;YACW,OAAO;IAerB,OAAO,CAAC,MAAM,CAAC,MAAM;CAGtB;AAED,OAAO,EAAE,YAAY,EAAE,sBAAsB,EAAE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var m=Object.defineProperty;var i=(l,t)=>m(l,"name",{value:t,configurable:!0});import{AbstractDurableObjectWorker as R}from"../base/AbstractDurableObjectWorker.js";import{assertFinalMembers as g}from"../base/finalMembers.js";import{createLogger as w}from"../logger.js";import{CRON_TASKS_RUN_PATH as p,DEFAULT_MAX_RUN_AGE_MS as y}from"./cronContract.js";class c extends Error{static{i(this,"CronRunError")}failures;constructor(t){super(`${t.length} scheduled task(s) failed`),this.failures=t,this.name="CronRunError"}}class o extends R{static{i(this,"CronTasksDurableObject")}currentRun=null;constructor(t,r){super(t,r),g(this,o,["fetch","onRequest"])}async onRequest(t){if(new URL(t.url).pathname!==p)return Response.json({error:"Not Found"},{status:404});if(t.method!=="POST")return Response.json({error:"Method Not Allowed"},{status:405,headers:{Allow:"POST"}});if(this.currentRun!==null){const a=this.now()-this.currentRun.startedAt,s=this.maxRunAgeMs();if(a<s)return o.answer("already_running",202);this.logger().warn("Expiring a cron run that outlived the maximum age; starting a new one",{ageMs:a,maxAgeMs:s}),this.currentRun=null}const e=this.now(),n={promise:this.execute(t,e),startedAt:e};this.currentRun=n;try{return await n.promise,o.answer("completed",200)}catch{return o.answer("failed",500)}finally{this.currentRun===n&&(this.currentRun=null)}}onRunStart(t){}onRunComplete(t){}onRunError(t,r){const e=r instanceof c?r.failures.length:1;this.logger().error("Cron task run failed",{cron:t.cron,failures:e})}maxRunAgeMs(){return y}now(){return Date.now()}logger(){return w("CronTasks")}async execute(t,r){const e=await this.readRun(t,r);try{await this.onRunStart(e),await this.runPhases(this.createRegistry(this.env,e),e),await this.onRunComplete(e)}catch(n){try{await this.onRunError(e,n)}catch{this.logger().warn("Cron onRunError hook rejected",{cron:e.cron})}throw n}}async runPhases(t,r){const e={cron:r.cron,scheduledTime:r.scheduledTime,noRetry:i(()=>{},"noRetry")},n=this.createExecutionContext(),a=this.env,s=[];for(const h of t.phases()){const d=t.tasksForPhase(h),f=await Promise.allSettled(d.map(u=>u.handle(e,a,n)));for(const u of f)u.status==="rejected"&&s.push(u.reason)}if(s.length>0)throw new c(s)}async readRun(t,r){let e={};try{const n=await t.json();n!==null&&typeof n=="object"&&(e=n)}catch{this.logger().warn("Cron trigger body was not valid JSON; falling back to defaults")}return{cron:typeof e.cron=="string"?e.cron:"",scheduledTime:typeof e.scheduledTime=="number"?e.scheduledTime:r,startedAt:r}}static answer(t,r){return Response.json({status:t},{status:r})}}export{c as CronRunError,o as CronTasksDurableObject};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/cron/CronTasksDurableObject.ts"],
|
|
4
|
+
"sourcesContent": ["import type { DurableObject } from 'cloudflare:workers';\nimport { AbstractDurableObjectWorker } from '../base/AbstractDurableObjectWorker.ts';\nimport { assertFinalMembers } from '../base/finalMembers.ts';\nimport { createLogger } from '../logger.ts';\nimport type { Logger } from '../logger.ts';\nimport type {\n AbstractScheduledTask,\n ExecutionContextLike,\n ScheduledControllerLike,\n ScheduledTaskEnv,\n TaskRegistry,\n} from '../scheduled/index.ts';\nimport { CRON_TASKS_RUN_PATH, DEFAULT_MAX_RUN_AGE_MS } from './cronContract.ts';\nimport type { CronRunContext, CronRunStatus } from './cronContract.ts';\n\n/**\n * The aggregate a run rejects with when one or more tasks failed.\n *\n * The message is a count, never the tasks' own messages: a task failure can\n * carry provider text (a token, a signed URL), and this error reaches a log\n * line. The causes are kept on `failures` for a hook that knows how to redact.\n */\nclass CronRunError extends Error {\n public constructor(public readonly failures: readonly unknown[]) {\n super(`${failures.length} scheduled task(s) failed`);\n this.name = 'CronRunError';\n }\n}\n\ninterface ActiveRun {\n readonly promise: Promise<void>;\n readonly startedAt: number;\n}\n\n/**\n * The family's cron Durable Object.\n *\n * Converged from `apps/background/src/CronTasksWorker.ts` in AWS-AccessBridge\n * (the one with `MAX_RUN_AGE_MS`), Mail-Meow, Mail-Bee, Mail-Otter,\n * CalDAV-Bridge and ChordDHT-Tracker. The entry worker's `scheduled()` posts\n * `{ cron, scheduledTime }` to `POST /run` on the single `idFromName('global')`\n * instance (see `dispatchCronToDurableObject`), and this object serialises the\n * runs.\n *\n * ## The contract (strict — owned here)\n *\n * | Request | Response |\n * | ------------------------------- | ------------------------------------------- |\n * | any path but `/run` | 404 `{ error: 'Not Found' }` |\n * | `/run`, not `POST` | 405 `{ error: 'Method Not Allowed' }` |\n * | `POST /run` while a run is live | 202 `{ status: 'already_running' }` |\n * | `POST /run`, every task settled | 200 `{ status: 'completed' }` |\n * | `POST /run`, any task rejected | 500 `{ status: 'failed' }` |\n *\n * The in-flight guard **expires** after {@link maxRunAgeMs}: the guard is\n * in-memory, so a task whose upstream call never settles would otherwise make\n * every later tick answer 202 until eviction — the cron that appears to run and\n * never does. An expired run is abandoned, not cancelled (nothing can cancel a\n * hung await), and its `finally` compares identity so a late settle cannot\n * clear the guard of the run that replaced it.\n *\n * Phases run in the registry's ascending order; tasks inside one phase run in\n * parallel under `allSettled`, so one failure neither aborts its phase-mates nor\n * stops the later phases (pruning still runs behind a failed refresh). The run\n * then rejects with a {@link CronRunError} so the verdict is still `failed`.\n *\n * `fetch` and `onRequest` are `@final`: a subclass that redeclares either is\n * refused at construction.\n *\n * ## Extending (flexible)\n *\n * - {@link createRegistry} — required: the tasks for this run (it receives the\n * cron expression, so one object can serve several schedules).\n * - {@link onRunStart} / {@link onRunComplete} / {@link onRunError} — lifecycle\n * hooks (e.g. AWS-AccessBridge starts its collection workflow in `onRunStart`).\n * - {@link maxRunAgeMs}, {@link now}, {@link logger} — the expiry window, the\n * clock and the log port.\n */\nabstract class CronTasksDurableObject<TEnv = Env> extends AbstractDurableObjectWorker<TEnv> {\n private currentRun: ActiveRun | null = null;\n\n public constructor(ctx: ConstructorParameters<typeof DurableObject>[0], env: TEnv) {\n super(ctx, env);\n assertFinalMembers(this, CronTasksDurableObject, ['fetch', 'onRequest']);\n }\n\n /**\n * @final The `/run` contract. Not an extension point — see the class note.\n */\n protected async onRequest(request: Request): Promise<Response> {\n const url = new URL(request.url);\n if (url.pathname !== CRON_TASKS_RUN_PATH) {\n return Response.json({ error: 'Not Found' }, { status: 404 });\n }\n if (request.method !== 'POST') {\n return Response.json({ error: 'Method Not Allowed' }, { status: 405, headers: { Allow: 'POST' } });\n }\n if (this.currentRun !== null) {\n const ageMs = this.now() - this.currentRun.startedAt;\n const maxAgeMs = this.maxRunAgeMs();\n if (ageMs < maxAgeMs) {\n return CronTasksDurableObject.answer('already_running', 202);\n }\n this.logger().warn('Expiring a cron run that outlived the maximum age; starting a new one', { ageMs, maxAgeMs });\n this.currentRun = null;\n }\n\n const startedAt = this.now();\n const run: ActiveRun = { promise: this.execute(request, startedAt), startedAt };\n this.currentRun = run;\n try {\n await run.promise;\n return CronTasksDurableObject.answer('completed', 200);\n } catch {\n // The failure was already reported through `onRunError`; the caught value\n // is not logged here because it may carry task text.\n return CronTasksDurableObject.answer('failed', 500);\n } finally {\n if (this.currentRun === run) {\n this.currentRun = null;\n }\n }\n }\n\n /**\n * The tasks for one run. Called once per accepted `POST /run`.\n */\n protected abstract createRegistry(env: TEnv, run: CronRunContext): TaskRegistry;\n\n /**\n Runs before the first phase. A rejection fails the run.\n */\n protected onRunStart(_run: CronRunContext): Promise<void> | void {\n // Default: nothing.\n }\n\n /**\n Runs after every phase settled with no task failure.\n */\n protected onRunComplete(_run: CronRunContext): Promise<void> | void {\n // Default: nothing.\n }\n\n /**\n * Runs when the run failed, before the 500 is answered.\n *\n * The default logs a static line and the failure count only. Override to\n * route the causes (`error.failures` on a {@link CronRunError}) through a\n * redactor; a rejection from this hook is swallowed so it cannot mask the\n * original failure.\n */\n protected onRunError(run: CronRunContext, error: unknown): Promise<void> | void {\n const failures = error instanceof CronRunError ? error.failures.length : 1;\n this.logger().error('Cron task run failed', { cron: run.cron, failures });\n }\n\n /**\n How long a live run holds the `already_running` guard. Default 15 minutes.\n */\n protected maxRunAgeMs(): number {\n return DEFAULT_MAX_RUN_AGE_MS;\n }\n\n /**\n The clock, in epoch milliseconds. Override to inject a test clock.\n */\n protected now(): number {\n return Date.now();\n }\n\n /**\n * The log port. Every line this class writes is a static message plus\n * numeric or cron fields — never a caught value.\n */\n protected logger(): Logger {\n return createLogger('CronTasks');\n }\n\n private async execute(request: Request, startedAt: number): Promise<void> {\n const run = await this.readRun(request, startedAt);\n try {\n await this.onRunStart(run);\n await this.runPhases(this.createRegistry(this.env, run), run);\n await this.onRunComplete(run);\n } catch (error: unknown) {\n try {\n await this.onRunError(run, error);\n } catch {\n this.logger().warn('Cron onRunError hook rejected', { cron: run.cron });\n }\n throw error;\n }\n }\n\n private async runPhases(registry: TaskRegistry, run: CronRunContext): Promise<void> {\n const event: ScheduledControllerLike = { cron: run.cron, scheduledTime: run.scheduledTime, noRetry: (): void => undefined };\n const ctx: ExecutionContextLike = this.createExecutionContext();\n const env = this.env as unknown as ScheduledTaskEnv;\n const failures: unknown[] = [];\n for (const phase of registry.phases()) {\n const tasks: readonly AbstractScheduledTask[] = registry.tasksForPhase(phase);\n const settled = await Promise.allSettled(tasks.map((task) => task.handle(event, env, ctx)));\n for (const result of settled) {\n if (result.status === 'rejected') failures.push(result.reason);\n }\n }\n if (failures.length > 0) throw new CronRunError(failures);\n }\n\n /**\n * The request body, leniently: a malformed body still runs (with the current\n * time and an empty cron), because a skipped tick is worse than a tick with\n * synthesized metadata — but it is logged, since it means the trigger is wrong.\n */\n private async readRun(request: Request, startedAt: number): Promise<CronRunContext> {\n let payload: { cron?: unknown; scheduledTime?: unknown } = {};\n try {\n const parsed: unknown = await request.json();\n if (parsed !== null && typeof parsed === 'object') payload = parsed;\n } catch {\n this.logger().warn('Cron trigger body was not valid JSON; falling back to defaults');\n }\n return {\n cron: typeof payload.cron === 'string' ? payload.cron : '',\n scheduledTime: typeof payload.scheduledTime === 'number' ? payload.scheduledTime : startedAt,\n startedAt,\n };\n }\n\n private static answer(status: CronRunStatus, httpStatus: number): Response {\n return Response.json({ status }, { status: httpStatus });\n }\n}\n\nexport { CronRunError, CronTasksDurableObject };\n"],
|
|
5
|
+
"mappings": "+EACA,OAAS,+BAAAA,MAAmC,yCAC5C,OAAS,sBAAAC,MAA0B,0BACnC,OAAS,gBAAAC,MAAoB,eAS7B,OAAS,uBAAAC,EAAqB,0BAAAC,MAA8B,oBAU5D,MAAMC,UAAqB,KAAK,CArBhC,MAqBgC,CAAAC,EAAA,qBACK,SAAnC,YAAmCC,EAA4B,CAC7D,MAAM,GAAGA,EAAS,MAAM,2BAA2B,EADlB,KAAA,SAAAA,EAEjC,KAAK,KAAO,cACd,EAoDF,MAAeC,UAA2CR,CAAiC,CA7E3F,MA6E2F,CAAAM,EAAA,+BACjF,WAA+B,KAEvC,YAAmBG,EAAqDC,EAAS,CAC/E,MAAMD,EAAKC,CAAG,EACdT,EAAmB,KAAMO,EAAwB,CAAC,QAAS,WAAW,CAAC,CACzE,CAKU,MAAM,UAAUG,EAAgB,CAExC,GADY,IAAI,IAAIA,EAAQ,GAAG,EACvB,WAAaR,EACnB,OAAO,SAAS,KAAK,CAAE,MAAO,WAAW,EAAI,CAAE,OAAQ,GAAG,CAAE,EAE9D,GAAIQ,EAAQ,SAAW,OACrB,OAAO,SAAS,KAAK,CAAE,MAAO,oBAAoB,EAAI,CAAE,OAAQ,IAAK,QAAS,CAAE,MAAO,MAAM,CAAE,CAAE,EAEnG,GAAI,KAAK,aAAe,KAAM,CAC5B,MAAMC,EAAQ,KAAK,IAAG,EAAK,KAAK,WAAW,UACrCC,EAAW,KAAK,YAAW,EACjC,GAAID,EAAQC,EACV,OAAOL,EAAuB,OAAO,kBAAmB,GAAG,EAE7D,KAAK,OAAM,EAAG,KAAK,wEAAyE,CAAE,MAAAI,EAAO,SAAAC,CAAQ,CAAE,EAC/G,KAAK,WAAa,IACpB,CAEA,MAAMC,EAAY,KAAK,IAAG,EACpBC,EAAiB,CAAE,QAAS,KAAK,QAAQJ,EAASG,CAAS,EAAG,UAAAA,CAAS,EAC7E,KAAK,WAAaC,EAClB,GAAI,CACF,aAAMA,EAAI,QACHP,EAAuB,OAAO,YAAa,GAAG,CACvD,MAAQ,CAGN,OAAOA,EAAuB,OAAO,SAAU,GAAG,CACpD,SACM,KAAK,aAAeO,IACtB,KAAK,WAAa,KAEtB,CACF,CAUU,WAAWC,EAAoB,CAEzC,CAKU,cAAcA,EAAoB,CAE5C,CAUU,WAAWD,EAAqBE,EAAc,CACtD,MAAMV,EAAWU,aAAiBZ,EAAeY,EAAM,SAAS,OAAS,EACzE,KAAK,OAAM,EAAG,MAAM,uBAAwB,CAAE,KAAMF,EAAI,KAAM,SAAAR,CAAQ,CAAE,CAC1E,CAKU,aAAW,CACnB,OAAOH,CACT,CAKU,KAAG,CACX,OAAO,KAAK,IAAG,CACjB,CAMU,QAAM,CACd,OAAOF,EAAa,WAAW,CACjC,CAEQ,MAAM,QAAQS,EAAkBG,EAAiB,CACvD,MAAMC,EAAM,MAAM,KAAK,QAAQJ,EAASG,CAAS,EACjD,GAAI,CACF,MAAM,KAAK,WAAWC,CAAG,EACzB,MAAM,KAAK,UAAU,KAAK,eAAe,KAAK,IAAKA,CAAG,EAAGA,CAAG,EAC5D,MAAM,KAAK,cAAcA,CAAG,CAC9B,OAASE,EAAgB,CACvB,GAAI,CACF,MAAM,KAAK,WAAWF,EAAKE,CAAK,CAClC,MAAQ,CACN,KAAK,OAAM,EAAG,KAAK,gCAAiC,CAAE,KAAMF,EAAI,IAAI,CAAE,CACxE,CACA,MAAME,CACR,CACF,CAEQ,MAAM,UAAUC,EAAwBH,EAAmB,CACjE,MAAMI,EAAiC,CAAE,KAAMJ,EAAI,KAAM,cAAeA,EAAI,cAAe,QAAST,EAAA,IAAS,GAAT,UAAqB,EACnHG,EAA4B,KAAK,uBAAsB,EACvDC,EAAM,KAAK,IACXH,EAAsB,CAAA,EAC5B,UAAWa,KAASF,EAAS,OAAM,EAAI,CACrC,MAAMG,EAA0CH,EAAS,cAAcE,CAAK,EACtEE,EAAU,MAAM,QAAQ,WAAWD,EAAM,IAAKE,GAASA,EAAK,OAAOJ,EAAOT,EAAKD,CAAG,CAAC,CAAC,EAC1F,UAAWe,KAAUF,EACfE,EAAO,SAAW,YAAYjB,EAAS,KAAKiB,EAAO,MAAM,CAEjE,CACA,GAAIjB,EAAS,OAAS,EAAG,MAAM,IAAIF,EAAaE,CAAQ,CAC1D,CAOQ,MAAM,QAAQI,EAAkBG,EAAiB,CACvD,IAAIW,EAAuD,CAAA,EAC3D,GAAI,CACF,MAAMC,EAAkB,MAAMf,EAAQ,KAAI,EACtCe,IAAW,MAAQ,OAAOA,GAAW,WAAUD,EAAUC,EAC/D,MAAQ,CACN,KAAK,OAAM,EAAG,KAAK,gEAAgE,CACrF,CACA,MAAO,CACL,KAAM,OAAOD,EAAQ,MAAS,SAAWA,EAAQ,KAAO,GACxD,cAAe,OAAOA,EAAQ,eAAkB,SAAWA,EAAQ,cAAgBX,EACnF,UAAAA,EAEJ,CAEQ,OAAO,OAAOa,EAAuBC,EAAkB,CAC7D,OAAO,SAAS,KAAK,CAAE,OAAAD,CAAM,EAAI,CAAE,OAAQC,CAAU,CAAE,CACzD",
|
|
6
|
+
"names": ["AbstractDurableObjectWorker", "assertFinalMembers", "createLogger", "CRON_TASKS_RUN_PATH", "DEFAULT_MAX_RUN_AGE_MS", "CronRunError", "__name", "failures", "CronTasksDurableObject", "ctx", "env", "request", "ageMs", "maxAgeMs", "startedAt", "run", "_run", "error", "registry", "event", "phase", "tasks", "settled", "task", "result", "payload", "parsed", "status", "httpStatus"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The wire contract between the entry worker's `scheduled()` and the cron
|
|
3
|
+
* Durable Object — one definition, so the two sides cannot drift.
|
|
4
|
+
*
|
|
5
|
+
* Converged from the `DURABLE_OBJECT_CRON_TASKS_RUN_URL` /
|
|
6
|
+
* `DURABLE_OBJECT_NAMESPACE_GLOBAL` constants in the consumers'
|
|
7
|
+
* `backend-runtime/src/constants/do/*.ts`.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
The path the cron Durable Object answers.
|
|
11
|
+
*/
|
|
12
|
+
declare const CRON_TASKS_RUN_PATH = "/run";
|
|
13
|
+
/**
|
|
14
|
+
* The URL the dispatcher posts to. The host is never resolved — a Durable
|
|
15
|
+
* Object stub routes on the object, not the hostname — so it is a reserved
|
|
16
|
+
* `.invalid` name that cannot accidentally reach the network.
|
|
17
|
+
*/
|
|
18
|
+
declare const CRON_TASKS_RUN_URL = "https://cron-tasks.invalid/run";
|
|
19
|
+
/**
|
|
20
|
+
The single instance name: one object serialises every tick.
|
|
21
|
+
*/
|
|
22
|
+
declare const CRON_TASKS_INSTANCE_NAME = "global";
|
|
23
|
+
/**
|
|
24
|
+
* How long a live run holds the `already_running` guard by default.
|
|
25
|
+
*
|
|
26
|
+
* Fifteen minutes, AWS-AccessBridge's value: generous against the family's
|
|
27
|
+
* 10-minute crons, so only a run that outlived more than one full tick is
|
|
28
|
+
* treated as wedged.
|
|
29
|
+
*/
|
|
30
|
+
declare const DEFAULT_MAX_RUN_AGE_MS: number;
|
|
31
|
+
/**
|
|
32
|
+
The body the dispatcher posts.
|
|
33
|
+
*/
|
|
34
|
+
interface CronRunRequestBody {
|
|
35
|
+
cron: string;
|
|
36
|
+
scheduledTime: number;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
The `status` field of every `/run` answer.
|
|
40
|
+
*/
|
|
41
|
+
type CronRunStatus = 'completed' | 'already_running' | 'failed';
|
|
42
|
+
/**
|
|
43
|
+
What a run's hooks are told about the run.
|
|
44
|
+
*/
|
|
45
|
+
interface CronRunContext {
|
|
46
|
+
/**
|
|
47
|
+
The cron expression that fired, or `''` when the trigger did not send one.
|
|
48
|
+
*/
|
|
49
|
+
readonly cron: string;
|
|
50
|
+
/**
|
|
51
|
+
The platform's scheduled time, epoch ms; the start time when absent.
|
|
52
|
+
*/
|
|
53
|
+
readonly scheduledTime: number;
|
|
54
|
+
/**
|
|
55
|
+
When this object accepted the run, epoch ms.
|
|
56
|
+
*/
|
|
57
|
+
readonly startedAt: number;
|
|
58
|
+
}
|
|
59
|
+
export { CRON_TASKS_INSTANCE_NAME, CRON_TASKS_RUN_PATH, CRON_TASKS_RUN_URL, DEFAULT_MAX_RUN_AGE_MS };
|
|
60
|
+
export type { CronRunContext, CronRunRequestBody, CronRunStatus };
|
|
61
|
+
//# sourceMappingURL=cronContract.d.ts.map
|