agents 0.24.0 → 0.26.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/dist/{agent-routing-B2XLNMxq.d.ts → agent-routing-0DR0Tk2v.d.ts} +205 -132
- package/dist/agent-routing.d.ts +1 -1
- package/dist/agent-routing.js.map +1 -1
- package/dist/agent-tool-types.d.ts +28 -22
- package/dist/agent-tool-types.js +23 -1
- package/dist/agent-tool-types.js.map +1 -1
- package/dist/{agent-tools-y7zLfw4Q.js → agent-tools-CdJC-8Dc.js} +72 -9
- package/dist/agent-tools-CdJC-8Dc.js.map +1 -0
- package/dist/{agent-tools-Dj5Mzlw7.d.ts → agent-tools-YrATZJu2.d.ts} +34 -20
- package/dist/agent-tools.d.ts +20 -18
- package/dist/agent-tools.js.map +1 -1
- package/dist/ai-fm7xx1BK.js +312 -0
- package/dist/ai-fm7xx1BK.js.map +1 -0
- package/dist/base64-redaction-C1Uu29t5.js +59 -0
- package/dist/base64-redaction-C1Uu29t5.js.map +1 -0
- package/dist/browser/ai-sdk.d.ts +90 -0
- package/dist/browser/ai-sdk.js +51 -0
- package/dist/browser/ai-sdk.js.map +1 -0
- package/dist/browser/ai.d.ts +4 -4
- package/dist/browser/ai.js +1 -347
- package/dist/browser/index.d.ts +81 -79
- package/dist/browser/index.js +361 -2
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/tanstack-ai.d.ts +96 -1
- package/dist/browser/tanstack-ai.js +62 -2
- package/dist/browser/tanstack-ai.js.map +1 -1
- package/dist/browser-DE3d-RLk.d.ts +275 -0
- package/dist/browser-tool-CQ10e6Kj.js +480 -0
- package/dist/browser-tool-CQ10e6Kj.js.map +1 -0
- package/dist/browser-tool-DuNdlwZ9.d.ts +73 -0
- package/dist/capability-B4WbF81e.js.map +1 -1
- package/dist/{capability-runner-BUBa6Ake.d.ts → capability-runner-DBAnGr6L.d.ts} +7 -2
- package/dist/chat/index.d.ts +340 -234
- package/dist/chat/index.js +592 -66
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/react.d.ts +42 -2
- package/dist/chat/react.js +191 -35
- package/dist/chat/react.js.map +1 -1
- package/dist/chat/transport.d.ts +1 -1
- package/dist/chat/transport.js +1 -1
- package/dist/chat-sdk/index.d.ts +17 -3
- package/dist/chat-sdk/index.js +28 -2
- package/dist/chat-sdk/index.js.map +1 -1
- package/dist/{client-C9DAjZIY.js → client-4OlMIJx-.js} +102 -29
- package/dist/client-4OlMIJx-.js.map +1 -0
- package/dist/{client-BxdkCuVy.d.ts → client-je3koD9Z.d.ts} +45 -10
- package/dist/client.d.ts +7 -5
- package/dist/client.js +2 -2
- package/dist/{connector-CptFKzRh.js → connector-58XDGvc3.js} +251 -120
- package/dist/connector-58XDGvc3.js.map +1 -0
- package/dist/{connector-CkQD4MK3.d.ts → connector-Cl-VqPmA.d.ts} +244 -146
- package/dist/context/index.d.ts +29 -0
- package/dist/context/index.js +64 -17
- package/dist/context/index.js.map +1 -1
- package/dist/current-agent-DhoDkSnH.js.map +1 -1
- package/dist/{current-agent-C4w86kcN.d.ts → current-agent-vAk_5JMt.d.ts} +4 -4
- package/dist/{durable-object-lifecycle-ei7M7lqB.d.ts → durable-object-lifecycle-HhgOMWq9.d.ts} +15 -7
- package/dist/harness/pi/index.d.ts +344 -0
- package/dist/harness/pi/index.js +873 -0
- package/dist/harness/pi/index.js.map +1 -0
- package/dist/images-iiTDSyRu.js +1631 -0
- package/dist/images-iiTDSyRu.js.map +1 -0
- package/dist/{index-Dlgtd3Mj.d.ts → index-BreL0YrQ.d.ts} +2 -2
- package/dist/index-kbSUIer3.d.ts +343 -0
- package/dist/index.d.ts +46 -44
- package/dist/index.js +1 -1
- package/dist/internal_context.d.ts +1 -1
- package/dist/lifecycle/index.d.ts +3 -3
- package/dist/lifecycle/index.js +1 -1
- package/dist/{lifecycle-Mm_jQh7r.js → lifecycle-CFu6OV03.js} +39 -10
- package/dist/{lifecycle-Mm_jQh7r.js.map → lifecycle-CFu6OV03.js.map} +1 -1
- package/dist/mcp/client/index.d.ts +20 -20
- package/dist/mcp/client/x402.js +21 -19
- package/dist/mcp/client/x402.js.map +1 -1
- package/dist/mcp/index.d.ts +35 -35
- package/dist/mcp/index.js +1 -1
- package/dist/{message-builder-BymO4N_D.js → message-builder-DAl9AhHH.js} +89 -4
- package/dist/message-builder-DAl9AhHH.js.map +1 -0
- package/dist/models/ai-sdk/index.d.ts +353 -0
- package/dist/models/ai-sdk/index.js +2443 -0
- package/dist/models/ai-sdk/index.js.map +1 -0
- package/dist/models/pi-ai/index.d.ts +313 -0
- package/dist/models/pi-ai/index.js +1795 -0
- package/dist/models/pi-ai/index.js.map +1 -0
- package/dist/observability/ai/index.js +20 -4
- package/dist/observability/ai/index.js.map +1 -1
- package/dist/{protocol-B0nh6KNf.js → protocol-kHsr-f0X.js} +26 -12
- package/dist/{protocol-B0nh6KNf.js.map → protocol-kHsr-f0X.js.map} +1 -1
- package/dist/queue/index.d.ts +3 -3
- package/dist/queue/index.js +1 -1
- package/dist/{queue-BC9F5cUo.js → queue-BB-zfIYF.js} +2 -2
- package/dist/{queue-BC9F5cUo.js.map → queue-BB-zfIYF.js.map} +1 -1
- package/dist/react.d.ts +6 -6
- package/dist/react.js +160 -64
- package/dist/react.js.map +1 -1
- package/dist/{retries-D9B2UCq3.d.ts → retries-CV6AkXmQ.d.ts} +18 -9
- package/dist/retries.d.ts +11 -9
- package/dist/retries.js +11 -1
- package/dist/retries.js.map +1 -1
- package/dist/routing/index.d.ts +2 -2
- package/dist/routing/index.js +1 -1
- package/dist/{scheduler-D_KHqxBa.js → scheduler-DZ3xQfeK.js} +2 -2
- package/dist/{scheduler-D_KHqxBa.js.map → scheduler-DZ3xQfeK.js.map} +1 -1
- package/dist/{scheduler-BGq6M5Kd.d.ts → scheduler-RdACNXDP.d.ts} +3 -3
- package/dist/schedules/index.d.ts +1 -1
- package/dist/schedules/index.js +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/sessions/index.d.ts +70 -3
- package/dist/sessions/index.js +276 -67
- package/dist/sessions/index.js.map +1 -1
- package/dist/skills/index.d.ts +29 -314
- package/dist/socket-address.d.ts +16 -0
- package/dist/socket-address.js +19 -0
- package/dist/socket-address.js.map +1 -0
- package/dist/{src-BNU3ZiJM.js → src-BZeu-SCD.js} +423 -115
- package/dist/src-BZeu-SCD.js.map +1 -0
- package/dist/state/index.d.ts +1 -1
- package/dist/state/index.js +1 -1
- package/dist/streams/index.d.ts +1 -1
- package/dist/streams/index.js +1 -1
- package/dist/{streams-BcE8JP2X.d.ts → streams-Cmkj9QfW.d.ts} +4 -2
- package/dist/{streams-CCPRV6dt.js → streams-DW-UCOUc.js} +9 -2
- package/dist/streams-DW-UCOUc.js.map +1 -0
- package/dist/sub-routing.d.ts +12 -12
- package/dist/tasks/index.d.ts +1 -1
- package/dist/tasks/index.js +1 -1
- package/dist/{tasks-D4nLqVSI.js → tasks-68DESxf0.js} +2 -2
- package/dist/{tasks-D4nLqVSI.js.map → tasks-68DESxf0.js.map} +1 -1
- package/dist/{tasks-V2lCT8ZV.d.ts → tasks-9YxYtByh.d.ts} +2 -2
- package/dist/transport-PfFnt-Ld.d.ts +525 -0
- package/dist/{types-DCD6BNZH.d.ts → types-BA4anrjI.d.ts} +2 -2
- package/dist/voice/index.d.ts +2 -2
- package/dist/websockets/index.d.ts +23 -6
- package/dist/websockets/index.js +1 -1
- package/dist/{websockets-D7IzWbZb.js → websockets-Ci-LZFHH.js} +45 -20
- package/dist/{websockets-D7IzWbZb.js.map → websockets-Ci-LZFHH.js.map} +1 -1
- package/dist/wire-types-CnMt6_HR.js.map +1 -1
- package/dist/wire-types-CrjKvDyi.d.ts +300 -0
- package/dist/workflow-types.d.ts +25 -25
- package/dist/workflows.d.ts +21 -21
- package/dist/workflows.js +1 -1
- package/dist/{ws-chat-transport-UNRIS2xl.d.ts → ws-chat-transport-BbT1A5Lc.d.ts} +51 -2
- package/dist/{ws-chat-transport-rWwta645.js → ws-chat-transport-cqMKq3IY.js} +143 -16
- package/dist/ws-chat-transport-cqMKq3IY.js.map +1 -0
- package/docs/agent-tools.md +29 -4
- package/docs/browse-the-web.md +87 -5
- package/docs/chat-agents.md +124 -16
- package/docs/context.md +27 -0
- package/docs/durable-execution.md +2 -0
- package/docs/harnesses/pi.md +173 -0
- package/docs/human-in-the-loop.md +4 -0
- package/docs/index.md +3 -0
- package/docs/lifecycle.md +20 -4
- package/docs/models-pi-ai.md +325 -0
- package/docs/models.md +504 -0
- package/docs/resumable-streaming.md +2 -0
- package/docs/routing.md +13 -13
- package/docs/sessions.md +36 -1
- package/docs/state.md +1 -0
- package/docs/sub-agents.md +9 -0
- package/package.json +40 -2
- package/dist/agent-tools-y7zLfw4Q.js.map +0 -1
- package/dist/browser/ai.js.map +0 -1
- package/dist/client-C9DAjZIY.js.map +0 -1
- package/dist/client-tools-aIBO0Fk7.d.ts +0 -53
- package/dist/connector-CptFKzRh.js.map +0 -1
- package/dist/message-builder-BymO4N_D.js.map +0 -1
- package/dist/src-BNU3ZiJM.js.map +0 -1
- package/dist/streams-CCPRV6dt.js.map +0 -1
- package/dist/ws-chat-transport-rWwta645.js.map +0 -1
|
@@ -86,6 +86,14 @@ declare function isDurableObjectCodeUpdateReset(error: unknown): boolean;
|
|
|
86
86
|
* deliberately do not qualify.
|
|
87
87
|
*/
|
|
88
88
|
declare function isDurableObjectStorageReset(error: unknown): boolean;
|
|
89
|
+
/**
|
|
90
|
+
* Whether an error (or anything in its `cause` chain) is a Durable Object
|
|
91
|
+
* reset — a superseded isolate ({@link isDurableObjectCodeUpdateReset}) or a
|
|
92
|
+
* storage reset ({@link isDurableObjectStorageReset}). The isolate is going
|
|
93
|
+
* away, so live chat recovery must not schedule a retry for it: the restart's
|
|
94
|
+
* own recovery owns the turn.
|
|
95
|
+
*/
|
|
96
|
+
declare function isDurableObjectResetError(error: unknown): boolean;
|
|
89
97
|
/**
|
|
90
98
|
* Whether an error (or anything in its `cause` chain, or a raw error-message
|
|
91
99
|
* string) is a Durable Object memory-limit reset — see
|
|
@@ -129,16 +137,17 @@ declare function isPlatformFailure(error: unknown): boolean;
|
|
|
129
137
|
declare function isPlatformTransientError(error: unknown): boolean;
|
|
130
138
|
//#endregion
|
|
131
139
|
export {
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
140
|
+
isDurableObjectStorageReset as a,
|
|
141
|
+
isPlatformTransientError as c,
|
|
142
|
+
tryN as d,
|
|
143
|
+
validateRetryOptions as f,
|
|
144
|
+
isDurableObjectResetError as i,
|
|
145
|
+
jitterBackoff as l,
|
|
137
146
|
isDurableObjectCodeUpdateReset as n,
|
|
138
|
-
|
|
147
|
+
isErrorRetryable as o,
|
|
139
148
|
isDurableObjectMemoryLimitReset as r,
|
|
140
|
-
|
|
149
|
+
isPlatformFailure as s,
|
|
141
150
|
RetryOptions as t,
|
|
142
|
-
|
|
151
|
+
resolveRetryConfig as u
|
|
143
152
|
};
|
|
144
|
-
//# sourceMappingURL=retries-
|
|
153
|
+
//# sourceMappingURL=retries-CV6AkXmQ.d.ts.map
|
package/dist/retries.d.ts
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
import {
|
|
2
|
-
a as
|
|
3
|
-
c as
|
|
4
|
-
d as
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
a as isDurableObjectStorageReset,
|
|
3
|
+
c as isPlatformTransientError,
|
|
4
|
+
d as tryN,
|
|
5
|
+
f as validateRetryOptions,
|
|
6
|
+
i as isDurableObjectResetError,
|
|
7
|
+
l as jitterBackoff,
|
|
7
8
|
n as isDurableObjectCodeUpdateReset,
|
|
8
|
-
o as
|
|
9
|
+
o as isErrorRetryable,
|
|
9
10
|
r as isDurableObjectMemoryLimitReset,
|
|
10
|
-
s as
|
|
11
|
+
s as isPlatformFailure,
|
|
11
12
|
t as RetryOptions,
|
|
12
|
-
u as
|
|
13
|
-
} from "./retries-
|
|
13
|
+
u as resolveRetryConfig
|
|
14
|
+
} from "./retries-CV6AkXmQ.js";
|
|
14
15
|
export {
|
|
15
16
|
RetryOptions,
|
|
16
17
|
isDurableObjectCodeUpdateReset,
|
|
17
18
|
isDurableObjectMemoryLimitReset,
|
|
19
|
+
isDurableObjectResetError,
|
|
18
20
|
isDurableObjectStorageReset,
|
|
19
21
|
isErrorRetryable,
|
|
20
22
|
isPlatformFailure,
|
package/dist/retries.js
CHANGED
|
@@ -189,6 +189,16 @@ function isDurableObjectStorageReset(error) {
|
|
|
189
189
|
return false;
|
|
190
190
|
}
|
|
191
191
|
/**
|
|
192
|
+
* Whether an error (or anything in its `cause` chain) is a Durable Object
|
|
193
|
+
* reset — a superseded isolate ({@link isDurableObjectCodeUpdateReset}) or a
|
|
194
|
+
* storage reset ({@link isDurableObjectStorageReset}). The isolate is going
|
|
195
|
+
* away, so live chat recovery must not schedule a retry for it: the restart's
|
|
196
|
+
* own recovery owns the turn.
|
|
197
|
+
*/
|
|
198
|
+
function isDurableObjectResetError(error) {
|
|
199
|
+
return isDurableObjectCodeUpdateReset(error) || isDurableObjectStorageReset(error);
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
192
202
|
* Whether an error (or anything in its `cause` chain, or a raw error-message
|
|
193
203
|
* string) is a Durable Object memory-limit reset — see
|
|
194
204
|
* {@link MEMORY_LIMIT_RESET_PATTERN}. Unlike {@link isPlatformTransientError},
|
|
@@ -244,6 +254,6 @@ function isPlatformTransientError(error) {
|
|
|
244
254
|
return false;
|
|
245
255
|
}
|
|
246
256
|
//#endregion
|
|
247
|
-
export { isDurableObjectCodeUpdateReset, isDurableObjectMemoryLimitReset, isDurableObjectStorageReset, isErrorRetryable, isPlatformFailure, isPlatformTransientError, jitterBackoff, resolveRetryConfig, tryN, validateRetryOptions };
|
|
257
|
+
export { isDurableObjectCodeUpdateReset, isDurableObjectMemoryLimitReset, isDurableObjectResetError, isDurableObjectStorageReset, isErrorRetryable, isPlatformFailure, isPlatformTransientError, jitterBackoff, resolveRetryConfig, tryN, validateRetryOptions };
|
|
248
258
|
|
|
249
259
|
//# sourceMappingURL=retries.js.map
|
package/dist/retries.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retries.js","names":[],"sources":["../src/retries.ts"],"sourcesContent":["/**\n * Retry options for schedule(), scheduleEvery(), queue(), and this.retry().\n */\nexport interface RetryOptions {\n /** Max number of attempts (including the first). Default: 3 */\n maxAttempts?: number;\n /** Base delay in ms for exponential backoff. Default: 100 */\n baseDelayMs?: number;\n /** Max delay cap in ms. Default: 3000 */\n maxDelayMs?: number;\n}\n\n/**\n * Internal options for tryN -- extends RetryOptions with a shouldRetry predicate.\n */\ninterface TryNOptions extends RetryOptions {\n /**\n * Predicate to determine if an error should be retried.\n * Receives the error and the next attempt number (so callers can\n * make attempt-aware decisions).\n * If not provided, all errors are retried.\n */\n shouldRetry?: (err: unknown, nextAttempt: number) => boolean;\n}\n\n/**\n * Validate retry options eagerly so invalid config fails at enqueue/schedule time\n * rather than at execution time. Checks individual field ranges, enforces integer\n * maxAttempts, and validates cross-field constraints after resolving against\n * defaults when provided.\n */\n/** Fill unset per-call retry options from a required set of defaults. */\nexport function resolveRetryConfig(\n retry: RetryOptions | undefined,\n defaults: Required<RetryOptions>\n): Required<RetryOptions> {\n return {\n maxAttempts: retry?.maxAttempts ?? defaults.maxAttempts,\n baseDelayMs: retry?.baseDelayMs ?? defaults.baseDelayMs,\n maxDelayMs: retry?.maxDelayMs ?? defaults.maxDelayMs\n };\n}\n\nexport function validateRetryOptions(\n options: RetryOptions,\n defaults?: Required<RetryOptions>\n): void {\n if (options.maxAttempts !== undefined) {\n if (!Number.isFinite(options.maxAttempts) || options.maxAttempts < 1) {\n throw new Error(\"retry.maxAttempts must be >= 1\");\n }\n if (!Number.isInteger(options.maxAttempts)) {\n throw new Error(\"retry.maxAttempts must be an integer\");\n }\n }\n if (options.baseDelayMs !== undefined) {\n if (!Number.isFinite(options.baseDelayMs) || options.baseDelayMs <= 0) {\n throw new Error(\"retry.baseDelayMs must be > 0\");\n }\n }\n if (options.maxDelayMs !== undefined) {\n if (!Number.isFinite(options.maxDelayMs) || options.maxDelayMs <= 0) {\n throw new Error(\"retry.maxDelayMs must be > 0\");\n }\n }\n\n // Resolve against defaults (when provided) so that cross-field checks\n // catch e.g. { baseDelayMs: 5000 } against default maxDelayMs: 3000.\n const resolvedBase = options.baseDelayMs ?? defaults?.baseDelayMs;\n const resolvedMax = options.maxDelayMs ?? defaults?.maxDelayMs;\n if (\n resolvedBase !== undefined &&\n resolvedMax !== undefined &&\n resolvedBase > resolvedMax\n ) {\n throw new Error(\"retry.baseDelayMs must be <= retry.maxDelayMs\");\n }\n}\n\n/**\n * Returns the number of milliseconds to wait before retrying a request.\n * Uses the \"Full Jitter\" approach from\n * https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/\n *\n * @param attempt The current attempt number (1-indexed).\n * @param baseDelayMs Base delay multiplier in ms.\n * @param maxDelayMs Maximum delay cap in ms.\n * @returns Milliseconds to wait before retrying.\n */\nexport function jitterBackoff(\n attempt: number,\n baseDelayMs: number,\n maxDelayMs: number\n): number {\n const upperBoundMs = Math.min(2 ** attempt * baseDelayMs, maxDelayMs);\n return Math.floor(Math.random() * upperBoundMs);\n}\n\n/**\n * Retry an async function up to `n` total attempts with jittered exponential backoff.\n *\n * @param n Total number of attempts (must be a finite integer >= 1).\n * @param fn The async function to retry. Receives the current attempt number (1-indexed).\n * @param options Retry configuration.\n * @returns The result of `fn` on success.\n * @throws The last error if all attempts fail or `shouldRetry` returns false.\n */\nexport async function tryN<T>(\n n: number,\n fn: (attempt: number) => Promise<T>,\n options?: TryNOptions\n): Promise<T> {\n if (!Number.isFinite(n) || n < 1) {\n throw new Error(\"retry.maxAttempts must be >= 1\");\n }\n n = Math.floor(n);\n\n const rawBase = options?.baseDelayMs ?? 100;\n const rawMax = options?.maxDelayMs ?? 3000;\n\n if (!Number.isFinite(rawBase) || rawBase <= 0) {\n throw new Error(\"retry.baseDelayMs must be > 0\");\n }\n if (!Number.isFinite(rawMax) || rawMax <= 0) {\n throw new Error(\"retry.maxDelayMs must be > 0\");\n }\n\n const baseDelayMs = Math.floor(rawBase);\n const maxDelayMs = Math.floor(rawMax);\n\n if (baseDelayMs > maxDelayMs) {\n throw new Error(\"retry.baseDelayMs must be <= retry.maxDelayMs\");\n }\n\n let attempt = 1;\n while (true) {\n try {\n return await fn(attempt);\n } catch (err) {\n const nextAttempt = attempt + 1;\n if (\n nextAttempt > n ||\n (options?.shouldRetry && !options.shouldRetry(err, nextAttempt))\n ) {\n throw err;\n }\n const delay = jitterBackoff(attempt, baseDelayMs, maxDelayMs);\n await new Promise((resolve) => setTimeout(resolve, delay));\n attempt = nextAttempt;\n }\n }\n}\n\n/**\n * Returns true if the given error is retryable according to Durable Object error handling.\n * See https://developers.cloudflare.com/durable-objects/best-practices/error-handling/\n *\n * An error is retryable if it has `retryable: true` but is NOT an overloaded error.\n */\nexport function isErrorRetryable(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) {\n return false;\n }\n const msg = String(err);\n const typed = err as { retryable?: boolean; overloaded?: boolean };\n return (\n Boolean(typed.retryable) &&\n !typed.overloaded &&\n !msg.includes(\"Durable Object is overloaded\")\n );\n}\n\n/**\n * The \"superseded isolate\" platform messages — the invocation is running on an\n * isolate the platform has replaced with a new version (a deploy / code\n * update). For the rest of that invocation every operation throws the same\n * error (code never reloads mid-invocation), so in-process retries are futile;\n * but the next fresh invocation runs the new code and succeeds.\n *\n * workerd surfaces this as a plain `Error` with one of a few messages, all the\n * same failure class — a message match is the only signal:\n * - \"Durable Object reset because its code was updated.\" (DO storage op on a\n * superseded isolate / deploy bounce)\n * - \"This script has been upgraded. Please send a new request to connect to\n * the new version.\" (a stub/connection to a superseded script; the message\n * literally instructs the caller to retry on the new version)\n *\n * The match stays close to the verbatim platform strings (rather than a loose\n * \"upgraded\"/\"reset\" substring) so an ordinary application error that happens\n * to mention those words is NOT misclassified as a supersede.\n */\nconst SUPERSEDED_ISOLATE_PATTERN =\n /reset because its code was updated|this script has been upgraded/i;\n\n/**\n * The \"Network connection lost.\" platform transient — the connection between\n * the isolate and its storage (or another DO) dropped. Unlike a supersede this\n * MAY succeed on an in-process retry (a momentary blip), so it must not skip\n * the in-process retry budget — but during a deploy-reset window it never\n * succeeds in-process and surfaces interleaved with the supersede messages\n * (SQL ops throw `SqlError: SQL query failed: Network connection lost.` while\n * KV ops throw the reset message), so on retry exhaustion it must be treated\n * as the platform's failure, not the callback's.\n */\nconst CONNECTION_LOST_PATTERN = /network connection lost/i;\n\n/**\n * The exact Durable Object storage-reset platform signal. Keep this narrow:\n * ordinary SQL and generic internal errors are application failures. This is a\n * transient storage reset, not a memory-limit poison pill.\n */\nconst STORAGE_RESET_PATTERN =\n /Internal error in Durable Object storage caused object to be reset/i;\n\n/**\n * The Durable Object memory-limit reset — the isolate exceeded its 128 MB limit\n * and was reset by the platform (workerd surfaces this verbatim as\n * \"Durable Object's isolate exceeded its memory limit and was reset.\"; the D1\n * sibling is \"D1 DB's isolate exceeded its memory limit and was reset.\").\n *\n * The match is the broad shared fragment \"exceeded its memory limit\" rather than\n * the full \"...and was reset\" sentence: real-world surfacings truncate or reword\n * the tail (some log pipelines clip the message; D1/storage wrappers re-prefix\n * it), and a customer-reported loop (#1825) showed lines carrying only the\n * \"exceeded its memory limit\" fragment. Missing a surfacing here means the\n * circuit breaker never engages, so we err toward the broader match — and even a\n * false positive is fail-safe (a tightly-bounded retry-then-seal, not data loss).\n *\n * This is DELIBERATELY a separate class from `SUPERSEDED_ISOLATE_PATTERN` /\n * {@link isPlatformTransientError}, and is NOT folded into them. A supersede or\n * connection-lost transient means \"re-run the same work and it succeeds on a\n * healthy isolate\" — those classes can be deferred and retried *indefinitely*. A\n * memory-limit reset is the opposite: re-running the SAME memory-heavy work\n * deterministically re-OOMs (the footprint, not the platform, is the cause), so\n * deferring it indefinitely would PRESERVE the one-shot row and re-run the\n * doomed work forever (amplifying the loop and cost — see #1825). It is a\n * poison-pill signal: callers must bound retries tightly and then SEAL.\n *\n * Accordingly the schedule executor (`_executeScheduleCallback`) and the\n * alarm-boundary circuit breaker (`Agent.alarm`) treat it as its OWN class: a\n * memory-limit reset is re-thrown (row preserved) so it reaches the breaker,\n * which tolerates a few strikes (`maxAlarmMemoryLimitStrikes`) and then seals +\n * purges the looping row — i.e. *bounded* deferral, never the unbounded deferral\n * the transient classes get.\n */\nconst MEMORY_LIMIT_RESET_PATTERN = /exceeded its memory limit/i;\n\nfunction errorMessageOf(error: unknown): string {\n return error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"\";\n}\n\n/**\n * Iterate an error and its `cause` chain (depth-limited so a cyclic chain\n * can't spin). Wrappers like `SqlError` carry the original platform error in\n * `cause` and may not propagate signal properties (e.g. the CF `retryable`\n * flag), so classification must look through them.\n */\nfunction* selfAndCauses(error: unknown): Generator<unknown> {\n let current = error;\n for (let depth = 0; depth < 8 && current != null; depth++) {\n yield current;\n current =\n typeof current === \"object\"\n ? (current as { cause?: unknown }).cause\n : undefined;\n }\n}\n\n/**\n * Whether an error (or anything in its `cause` chain) is a transient\n * \"superseded isolate\" failure — see `SUPERSEDED_ISOLATE_PATTERN`. In-process\n * retries are futile for this class; the work must be deferred to a fresh\n * invocation, which runs the new code and succeeds.\n */\nexport function isDurableObjectCodeUpdateReset(error: unknown): boolean {\n for (const e of selfAndCauses(error)) {\n if (SUPERSEDED_ISOLATE_PATTERN.test(errorMessageOf(e))) return true;\n }\n return false;\n}\n\n/**\n * Whether an error (or anything in its `cause` chain) carries the exact\n * Durable Object storage-reset platform fragment. Generic SQL/internal errors\n * deliberately do not qualify.\n */\nexport function isDurableObjectStorageReset(error: unknown): boolean {\n for (const e of selfAndCauses(error)) {\n if (STORAGE_RESET_PATTERN.test(errorMessageOf(e))) return true;\n }\n return false;\n}\n\n/**\n * Whether an error (or anything in its `cause` chain, or a raw error-message\n * string) is a Durable Object memory-limit reset — see\n * {@link MEMORY_LIMIT_RESET_PATTERN}. Unlike {@link isPlatformTransientError},\n * re-running the same work re-OOMs deterministically, so callers must NOT defer\n * it like a transient; they should bound retries tightly and then seal (#1825).\n */\nexport function isDurableObjectMemoryLimitReset(error: unknown): boolean {\n for (const e of selfAndCauses(error)) {\n if (MEMORY_LIMIT_RESET_PATTERN.test(errorMessageOf(e))) return true;\n }\n return false;\n}\n\n/**\n * Whether an error (or anything in its `cause` chain) is a transient failure\n * of the PLATFORM rather than of the code that threw it:\n *\n * - a superseded-isolate reset (\"reset because its code was updated\" /\n * \"this script has been upgraded\") — a deploy replaced the isolate;\n * - an error the platform itself flags `retryable: true` (excluding\n * overloaded errors, where retrying the same object won't help) — see\n * `isErrorRetryable`;\n * - \"Network connection lost.\" — the storage/stub connection dropped. The\n * CF `retryable` flag does not survive error wrappers (e.g. `SqlError`\n * copies only the message + `cause`) and is absent in some local-dev\n * shapes, so the verbatim message is matched as well;\n * - the exact \"Internal error in Durable Object storage caused object to be\n * reset\" platform fragment. Generic internal and SQL errors remain fatal.\n *\n * Used to decide whether failed work should be RE-RUN LATER (platform\n * transient — the same work succeeds once the platform recovers, typically\n * seconds after a deploy) versus ABANDONED as genuinely failing (application\n * error — re-running yields the same failure). A genuine application error\n * carries none of these signals, so it is never misclassified by this check.\n */\n/**\n * Whether a failure is the PLATFORM's rather than the application's — any\n * platform transient (see {@link isPlatformTransientError}, which includes\n * superseded-isolate resets) or a memory-limit reset. Failed work in this\n * class must be PRESERVED and deferred, never completed as an application\n * failure. The two sub-classes defer differently: transients re-run\n * indefinitely (the platform recovers), while memory-limit deferral is\n * bounded by the alarm circuit breaker (#1825).\n */\nexport function isPlatformFailure(error: unknown): boolean {\n return (\n isPlatformTransientError(error) || isDurableObjectMemoryLimitReset(error)\n );\n}\n\nexport function isPlatformTransientError(error: unknown): boolean {\n for (const e of selfAndCauses(error)) {\n const message = errorMessageOf(e);\n if (SUPERSEDED_ISOLATE_PATTERN.test(message)) return true;\n if (CONNECTION_LOST_PATTERN.test(message)) return true;\n if (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S;EACzD,MAAM;EACN,UACE,OAAO,YAAY,WACd,QAAgC,QACjC,KAAA;CACR;AACF;;;;;;;AAQA,SAAgB,+BAA+B,OAAyB;CACtE,KAAK,MAAM,KAAK,cAAc,KAAK,GACjC,IAAI,2BAA2B,KAAK,eAAe,CAAC,CAAC,GAAG,OAAO;CAEjE,OAAO;AACT;;;;;;AAOA,SAAgB,4BAA4B,OAAyB;CACnE,KAAK,MAAM,KAAK,cAAc,KAAK,GACjC,IAAI,sBAAsB,KAAK,eAAe,CAAC,CAAC,GAAG,OAAO;CAE5D,OAAO;AACT;;;;;;;;AASA,SAAgB,gCAAgC,OAAyB;CACvE,KAAK,MAAM,KAAK,cAAc,KAAK,GACjC,IAAI,2BAA2B,KAAK,eAAe,CAAC,CAAC,GAAG,OAAO;CAEjE,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,kBAAkB,OAAyB;CACzD,OACE,yBAAyB,KAAK,KAAK,gCAAgC,KAAK;AAE5E;AAEA,SAAgB,yBAAyB,OAAyB;CAChE,KAAK,MAAM,KAAK,cAAc,KAAK,GAAG;EACpC,MAAM,UAAU,eAAe,CAAC;EAChC,IAAI,2BAA2B,KAAK,OAAO,GAAG,OAAO;EACrD,IAAI,wBAAwB,KAAK,OAAO,GAAG,OAAO;EAClD,IAAI,sBAAsB,KAAK,OAAO,GAAG,OAAO;EAChD,IAAI,iBAAiB,CAAC,GAAG,OAAO;CAClC;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"retries.js","names":[],"sources":["../src/retries.ts"],"sourcesContent":["/**\n * Retry options for schedule(), scheduleEvery(), queue(), and this.retry().\n */\nexport interface RetryOptions {\n /** Max number of attempts (including the first). Default: 3 */\n maxAttempts?: number;\n /** Base delay in ms for exponential backoff. Default: 100 */\n baseDelayMs?: number;\n /** Max delay cap in ms. Default: 3000 */\n maxDelayMs?: number;\n}\n\n/**\n * Internal options for tryN -- extends RetryOptions with a shouldRetry predicate.\n */\ninterface TryNOptions extends RetryOptions {\n /**\n * Predicate to determine if an error should be retried.\n * Receives the error and the next attempt number (so callers can\n * make attempt-aware decisions).\n * If not provided, all errors are retried.\n */\n shouldRetry?: (err: unknown, nextAttempt: number) => boolean;\n}\n\n/**\n * Validate retry options eagerly so invalid config fails at enqueue/schedule time\n * rather than at execution time. Checks individual field ranges, enforces integer\n * maxAttempts, and validates cross-field constraints after resolving against\n * defaults when provided.\n */\n/** Fill unset per-call retry options from a required set of defaults. */\nexport function resolveRetryConfig(\n retry: RetryOptions | undefined,\n defaults: Required<RetryOptions>\n): Required<RetryOptions> {\n return {\n maxAttempts: retry?.maxAttempts ?? defaults.maxAttempts,\n baseDelayMs: retry?.baseDelayMs ?? defaults.baseDelayMs,\n maxDelayMs: retry?.maxDelayMs ?? defaults.maxDelayMs\n };\n}\n\nexport function validateRetryOptions(\n options: RetryOptions,\n defaults?: Required<RetryOptions>\n): void {\n if (options.maxAttempts !== undefined) {\n if (!Number.isFinite(options.maxAttempts) || options.maxAttempts < 1) {\n throw new Error(\"retry.maxAttempts must be >= 1\");\n }\n if (!Number.isInteger(options.maxAttempts)) {\n throw new Error(\"retry.maxAttempts must be an integer\");\n }\n }\n if (options.baseDelayMs !== undefined) {\n if (!Number.isFinite(options.baseDelayMs) || options.baseDelayMs <= 0) {\n throw new Error(\"retry.baseDelayMs must be > 0\");\n }\n }\n if (options.maxDelayMs !== undefined) {\n if (!Number.isFinite(options.maxDelayMs) || options.maxDelayMs <= 0) {\n throw new Error(\"retry.maxDelayMs must be > 0\");\n }\n }\n\n // Resolve against defaults (when provided) so that cross-field checks\n // catch e.g. { baseDelayMs: 5000 } against default maxDelayMs: 3000.\n const resolvedBase = options.baseDelayMs ?? defaults?.baseDelayMs;\n const resolvedMax = options.maxDelayMs ?? defaults?.maxDelayMs;\n if (\n resolvedBase !== undefined &&\n resolvedMax !== undefined &&\n resolvedBase > resolvedMax\n ) {\n throw new Error(\"retry.baseDelayMs must be <= retry.maxDelayMs\");\n }\n}\n\n/**\n * Returns the number of milliseconds to wait before retrying a request.\n * Uses the \"Full Jitter\" approach from\n * https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/\n *\n * @param attempt The current attempt number (1-indexed).\n * @param baseDelayMs Base delay multiplier in ms.\n * @param maxDelayMs Maximum delay cap in ms.\n * @returns Milliseconds to wait before retrying.\n */\nexport function jitterBackoff(\n attempt: number,\n baseDelayMs: number,\n maxDelayMs: number\n): number {\n const upperBoundMs = Math.min(2 ** attempt * baseDelayMs, maxDelayMs);\n return Math.floor(Math.random() * upperBoundMs);\n}\n\n/**\n * Retry an async function up to `n` total attempts with jittered exponential backoff.\n *\n * @param n Total number of attempts (must be a finite integer >= 1).\n * @param fn The async function to retry. Receives the current attempt number (1-indexed).\n * @param options Retry configuration.\n * @returns The result of `fn` on success.\n * @throws The last error if all attempts fail or `shouldRetry` returns false.\n */\nexport async function tryN<T>(\n n: number,\n fn: (attempt: number) => Promise<T>,\n options?: TryNOptions\n): Promise<T> {\n if (!Number.isFinite(n) || n < 1) {\n throw new Error(\"retry.maxAttempts must be >= 1\");\n }\n n = Math.floor(n);\n\n const rawBase = options?.baseDelayMs ?? 100;\n const rawMax = options?.maxDelayMs ?? 3000;\n\n if (!Number.isFinite(rawBase) || rawBase <= 0) {\n throw new Error(\"retry.baseDelayMs must be > 0\");\n }\n if (!Number.isFinite(rawMax) || rawMax <= 0) {\n throw new Error(\"retry.maxDelayMs must be > 0\");\n }\n\n const baseDelayMs = Math.floor(rawBase);\n const maxDelayMs = Math.floor(rawMax);\n\n if (baseDelayMs > maxDelayMs) {\n throw new Error(\"retry.baseDelayMs must be <= retry.maxDelayMs\");\n }\n\n let attempt = 1;\n while (true) {\n try {\n return await fn(attempt);\n } catch (err) {\n const nextAttempt = attempt + 1;\n if (\n nextAttempt > n ||\n (options?.shouldRetry && !options.shouldRetry(err, nextAttempt))\n ) {\n throw err;\n }\n const delay = jitterBackoff(attempt, baseDelayMs, maxDelayMs);\n await new Promise((resolve) => setTimeout(resolve, delay));\n attempt = nextAttempt;\n }\n }\n}\n\n/**\n * Returns true if the given error is retryable according to Durable Object error handling.\n * See https://developers.cloudflare.com/durable-objects/best-practices/error-handling/\n *\n * An error is retryable if it has `retryable: true` but is NOT an overloaded error.\n */\nexport function isErrorRetryable(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) {\n return false;\n }\n const msg = String(err);\n const typed = err as { retryable?: boolean; overloaded?: boolean };\n return (\n Boolean(typed.retryable) &&\n !typed.overloaded &&\n !msg.includes(\"Durable Object is overloaded\")\n );\n}\n\n/**\n * The \"superseded isolate\" platform messages — the invocation is running on an\n * isolate the platform has replaced with a new version (a deploy / code\n * update). For the rest of that invocation every operation throws the same\n * error (code never reloads mid-invocation), so in-process retries are futile;\n * but the next fresh invocation runs the new code and succeeds.\n *\n * workerd surfaces this as a plain `Error` with one of a few messages, all the\n * same failure class — a message match is the only signal:\n * - \"Durable Object reset because its code was updated.\" (DO storage op on a\n * superseded isolate / deploy bounce)\n * - \"This script has been upgraded. Please send a new request to connect to\n * the new version.\" (a stub/connection to a superseded script; the message\n * literally instructs the caller to retry on the new version)\n *\n * The match stays close to the verbatim platform strings (rather than a loose\n * \"upgraded\"/\"reset\" substring) so an ordinary application error that happens\n * to mention those words is NOT misclassified as a supersede.\n */\nconst SUPERSEDED_ISOLATE_PATTERN =\n /reset because its code was updated|this script has been upgraded/i;\n\n/**\n * The \"Network connection lost.\" platform transient — the connection between\n * the isolate and its storage (or another DO) dropped. Unlike a supersede this\n * MAY succeed on an in-process retry (a momentary blip), so it must not skip\n * the in-process retry budget — but during a deploy-reset window it never\n * succeeds in-process and surfaces interleaved with the supersede messages\n * (SQL ops throw `SqlError: SQL query failed: Network connection lost.` while\n * KV ops throw the reset message), so on retry exhaustion it must be treated\n * as the platform's failure, not the callback's.\n */\nconst CONNECTION_LOST_PATTERN = /network connection lost/i;\n\n/**\n * The exact Durable Object storage-reset platform signal. Keep this narrow:\n * ordinary SQL and generic internal errors are application failures. This is a\n * transient storage reset, not a memory-limit poison pill.\n */\nconst STORAGE_RESET_PATTERN =\n /Internal error in Durable Object storage caused object to be reset/i;\n\n/**\n * The Durable Object memory-limit reset — the isolate exceeded its 128 MB limit\n * and was reset by the platform (workerd surfaces this verbatim as\n * \"Durable Object's isolate exceeded its memory limit and was reset.\"; the D1\n * sibling is \"D1 DB's isolate exceeded its memory limit and was reset.\").\n *\n * The match is the broad shared fragment \"exceeded its memory limit\" rather than\n * the full \"...and was reset\" sentence: real-world surfacings truncate or reword\n * the tail (some log pipelines clip the message; D1/storage wrappers re-prefix\n * it), and a customer-reported loop (#1825) showed lines carrying only the\n * \"exceeded its memory limit\" fragment. Missing a surfacing here means the\n * circuit breaker never engages, so we err toward the broader match — and even a\n * false positive is fail-safe (a tightly-bounded retry-then-seal, not data loss).\n *\n * This is DELIBERATELY a separate class from `SUPERSEDED_ISOLATE_PATTERN` /\n * {@link isPlatformTransientError}, and is NOT folded into them. A supersede or\n * connection-lost transient means \"re-run the same work and it succeeds on a\n * healthy isolate\" — those classes can be deferred and retried *indefinitely*. A\n * memory-limit reset is the opposite: re-running the SAME memory-heavy work\n * deterministically re-OOMs (the footprint, not the platform, is the cause), so\n * deferring it indefinitely would PRESERVE the one-shot row and re-run the\n * doomed work forever (amplifying the loop and cost — see #1825). It is a\n * poison-pill signal: callers must bound retries tightly and then SEAL.\n *\n * Accordingly the schedule executor (`_executeScheduleCallback`) and the\n * alarm-boundary circuit breaker (`Agent.alarm`) treat it as its OWN class: a\n * memory-limit reset is re-thrown (row preserved) so it reaches the breaker,\n * which tolerates a few strikes (`maxAlarmMemoryLimitStrikes`) and then seals +\n * purges the looping row — i.e. *bounded* deferral, never the unbounded deferral\n * the transient classes get.\n */\nconst MEMORY_LIMIT_RESET_PATTERN = /exceeded its memory limit/i;\n\nfunction errorMessageOf(error: unknown): string {\n return error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"\";\n}\n\n/**\n * Iterate an error and its `cause` chain (depth-limited so a cyclic chain\n * can't spin). Wrappers like `SqlError` carry the original platform error in\n * `cause` and may not propagate signal properties (e.g. the CF `retryable`\n * flag), so classification must look through them.\n */\nfunction* selfAndCauses(error: unknown): Generator<unknown> {\n let current = error;\n for (let depth = 0; depth < 8 && current != null; depth++) {\n yield current;\n current =\n typeof current === \"object\"\n ? (current as { cause?: unknown }).cause\n : undefined;\n }\n}\n\n/**\n * Whether an error (or anything in its `cause` chain) is a transient\n * \"superseded isolate\" failure — see `SUPERSEDED_ISOLATE_PATTERN`. In-process\n * retries are futile for this class; the work must be deferred to a fresh\n * invocation, which runs the new code and succeeds.\n */\nexport function isDurableObjectCodeUpdateReset(error: unknown): boolean {\n for (const e of selfAndCauses(error)) {\n if (SUPERSEDED_ISOLATE_PATTERN.test(errorMessageOf(e))) return true;\n }\n return false;\n}\n\n/**\n * Whether an error (or anything in its `cause` chain) carries the exact\n * Durable Object storage-reset platform fragment. Generic SQL/internal errors\n * deliberately do not qualify.\n */\nexport function isDurableObjectStorageReset(error: unknown): boolean {\n for (const e of selfAndCauses(error)) {\n if (STORAGE_RESET_PATTERN.test(errorMessageOf(e))) return true;\n }\n return false;\n}\n\n/**\n * Whether an error (or anything in its `cause` chain) is a Durable Object\n * reset — a superseded isolate ({@link isDurableObjectCodeUpdateReset}) or a\n * storage reset ({@link isDurableObjectStorageReset}). The isolate is going\n * away, so live chat recovery must not schedule a retry for it: the restart's\n * own recovery owns the turn.\n */\nexport function isDurableObjectResetError(error: unknown): boolean {\n return (\n isDurableObjectCodeUpdateReset(error) || isDurableObjectStorageReset(error)\n );\n}\n\n/**\n * Whether an error (or anything in its `cause` chain, or a raw error-message\n * string) is a Durable Object memory-limit reset — see\n * {@link MEMORY_LIMIT_RESET_PATTERN}. Unlike {@link isPlatformTransientError},\n * re-running the same work re-OOMs deterministically, so callers must NOT defer\n * it like a transient; they should bound retries tightly and then seal (#1825).\n */\nexport function isDurableObjectMemoryLimitReset(error: unknown): boolean {\n for (const e of selfAndCauses(error)) {\n if (MEMORY_LIMIT_RESET_PATTERN.test(errorMessageOf(e))) return true;\n }\n return false;\n}\n\n/**\n * Whether an error (or anything in its `cause` chain) is a transient failure\n * of the PLATFORM rather than of the code that threw it:\n *\n * - a superseded-isolate reset (\"reset because its code was updated\" /\n * \"this script has been upgraded\") — a deploy replaced the isolate;\n * - an error the platform itself flags `retryable: true` (excluding\n * overloaded errors, where retrying the same object won't help) — see\n * `isErrorRetryable`;\n * - \"Network connection lost.\" — the storage/stub connection dropped. The\n * CF `retryable` flag does not survive error wrappers (e.g. `SqlError`\n * copies only the message + `cause`) and is absent in some local-dev\n * shapes, so the verbatim message is matched as well;\n * - the exact \"Internal error in Durable Object storage caused object to be\n * reset\" platform fragment. Generic internal and SQL errors remain fatal.\n *\n * Used to decide whether failed work should be RE-RUN LATER (platform\n * transient — the same work succeeds once the platform recovers, typically\n * seconds after a deploy) versus ABANDONED as genuinely failing (application\n * error — re-running yields the same failure). A genuine application error\n * carries none of these signals, so it is never misclassified by this check.\n */\n/**\n * Whether a failure is the PLATFORM's rather than the application's — any\n * platform transient (see {@link isPlatformTransientError}, which includes\n * superseded-isolate resets) or a memory-limit reset. Failed work in this\n * class must be PRESERVED and deferred, never completed as an application\n * failure. The two sub-classes defer differently: transients re-run\n * indefinitely (the platform recovers), while memory-limit deferral is\n * bounded by the alarm circuit breaker (#1825).\n */\nexport function isPlatformFailure(error: unknown): boolean {\n return (\n isPlatformTransientError(error) || isDurableObjectMemoryLimitReset(error)\n );\n}\n\nexport function isPlatformTransientError(error: unknown): boolean {\n for (const e of selfAndCauses(error)) {\n const message = errorMessageOf(e);\n if (SUPERSEDED_ISOLATE_PATTERN.test(message)) return true;\n if (CONNECTION_LOST_PATTERN.test(message)) return true;\n if (STORAGE_RESET_PATTERN.test(message)) return true;\n if (isErrorRetryable(e)) return true;\n }\n return false;\n}\n"],"mappings":";;;;;;;;AAgCA,SAAgB,mBACd,OACA,UACwB;CACxB,OAAO;EACL,aAAa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AK,GACjC,IAAI,2BAA2B,KAAK,eAAe,CAAC,CAAC,GAAG,OAAO;CAEjE,OAAO;AACT;;;;;;AAOA,SAAgB,4BAA4B,OAAyB;CACnE,KAAK,MAAM,KAAK,cAAc,KAAK,GACjC,IAAI,sBAAsB,KAAK,eAAe,CAAC,CAAC,GAAG,OAAO;CAE5D,OAAO;AACT;;;;;;;;AASA,SAAgB,0BAA0B,OAAyB;CACjE,OACE,+BAA+B,KAAK,KAAK,4BAA4B,KAAK;AAE9E;;;;;;;;AASA,SAAgB,gCAAgC,OAAyB;CACvE,KAAK,MAAM,KAAK,cAAc,KAAK,GACjC,IAAI,2BAA2B,KAAK,eAAe,CAAC,CAAC,GAAG,OAAO;CAEjE,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,kBAAkB,OAAyB;CACzD,OACE,yBAAyB,KAAK,KAAK,gCAAgC,KAAK;AAE5E;AAEA,SAAgB,yBAAyB,OAAyB;CAChE,KAAK,MAAM,KAAK,cAAc,KAAK,GAAG;EACpC,MAAM,UAAU,eAAe,CAAC;EAChC,IAAI,2BAA2B,KAAK,OAAO,GAAG,OAAO;EACrD,IAAI,wBAAwB,KAAK,OAAO,GAAG,OAAO;EAClD,IAAI,sBAAsB,KAAK,OAAO,GAAG,OAAO;EAChD,IAAI,iBAAiB,CAAC,GAAG,OAAO;CAClC;CACA,OAAO;AACT"}
|
package/dist/routing/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
r as CapabilityWebSocketUpgradeContext,
|
|
3
3
|
s as LifecycleCapability,
|
|
4
4
|
t as CapabilityRequestContext
|
|
5
|
-
} from "../capability-runner-
|
|
5
|
+
} from "../capability-runner-DBAnGr6L.js";
|
|
6
6
|
import {
|
|
7
7
|
a as routeAgentRequest,
|
|
8
8
|
c as Agent,
|
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
n as AgentOptions,
|
|
11
11
|
r as RoutingRetryOptions,
|
|
12
12
|
t as AgentGetOptions
|
|
13
|
-
} from "../agent-routing-
|
|
13
|
+
} from "../agent-routing-0DR0Tk2v.js";
|
|
14
14
|
|
|
15
15
|
//#region src/routing/routed-agents.d.ts
|
|
16
16
|
/** A public entry in an {@link RoutedAgents}. */
|
package/dist/routing/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { getAgentByName, routeAgentRequest } from "../agent-routing.js";
|
|
2
2
|
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "../classPrivateFieldGet2-DZBYAB34.js";
|
|
3
|
-
import { t as LifecycleCapability } from "../capability-B4WbF81e.js";
|
|
4
3
|
import { t as _classPrivateMethodInitSpec } from "../classPrivateMethodInitSpec-qMjJ6sHQ.js";
|
|
4
|
+
import { t as LifecycleCapability } from "../capability-B4WbF81e.js";
|
|
5
5
|
//#region src/routing/routed-agents.ts
|
|
6
6
|
/**
|
|
7
7
|
* Catalog of the entries an owning Durable Object has created, keyed by
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-DZBYAB34.js";
|
|
2
|
-
import { t as LifecycleCapability } from "./capability-B4WbF81e.js";
|
|
3
2
|
import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-qMjJ6sHQ.js";
|
|
3
|
+
import { t as LifecycleCapability } from "./capability-B4WbF81e.js";
|
|
4
4
|
import { isDurableObjectCodeUpdateReset, isPlatformFailure, resolveRetryConfig, tryN, validateRetryOptions } from "./retries.js";
|
|
5
5
|
import { parseCronExpression } from "cron-schedule";
|
|
6
6
|
//#region src/schedules/schedule-timing.ts
|
|
@@ -655,4 +655,4 @@ function _emitCreated(result) {
|
|
|
655
655
|
//#endregion
|
|
656
656
|
export { setSchedulerCallbackResolver as n, Scheduler as t };
|
|
657
657
|
|
|
658
|
-
//# sourceMappingURL=scheduler-
|
|
658
|
+
//# sourceMappingURL=scheduler-DZ3xQfeK.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduler-D_KHqxBa.js","names":[],"sources":["../src/schedules/schedule-timing.ts","../src/schedules/scheduler.ts"],"sourcesContent":["/**\n * Pure timing rules for persistent schedules.\n *\n * A `ScheduleTiming` is the parsed \"when and how it runs\" half of a\n * `Schedule` — everything except identity, callback, and payload. Parsing\n * user-facing inputs here keeps Scheduler's storage code to one insert path.\n */\n\nimport { parseCronExpression } from \"cron-schedule\";\n\n/** Longest allowed gap between interval executions: 30 days. */\nexport const MAX_INTERVAL_SECONDS = 30 * 24 * 60 * 60;\n\n/** When and how one schedule runs; a `Schedule` minus identity and payload. */\nexport type ScheduleTiming =\n | {\n /** One-time execution at a specific date. */\n readonly type: \"scheduled\";\n /** Unix timestamp in seconds. */\n readonly time: number;\n }\n | {\n /** One-time execution after a relative delay. */\n readonly type: \"delayed\";\n /** Unix timestamp in seconds. */\n readonly time: number;\n /** Delay from creation in seconds. */\n readonly delayInSeconds: number;\n }\n | {\n /** Recurring execution from a cron expression. */\n readonly type: \"cron\";\n /** Unix timestamp in seconds for the next execution. */\n readonly time: number;\n /** Cron expression defining the recurrence. */\n readonly cron: string;\n }\n | {\n /** Recurring execution at a fixed interval. */\n readonly type: \"interval\";\n /** Unix timestamp in seconds for the next execution. */\n readonly time: number;\n /** Number of seconds between executions. */\n readonly intervalSeconds: number;\n };\n\n/** True when this timing repeats and therefore deduplicates by default. */\nexport function isRecurring(timing: ScheduleTiming): boolean {\n return timing.type === \"cron\" || timing.type === \"interval\";\n}\n\n/**\n * Next wall-clock execution time for a cron expression.\n *\n * @param cron - A standard cron expression.\n * @param nowMs - Current epoch time in milliseconds.\n * @returns The next execution epoch time in milliseconds.\n * @throws For an unparseable cron expression.\n */\nexport function nextCronTimeMs(cron: string, nowMs: number): number {\n return parseCronExpression(cron).getNextDate(new Date(nowMs)).getTime();\n}\n\n/**\n * Parse a user-facing `when` into schedule timing.\n *\n * A `Date` runs once at that date, a number runs once after that many\n * seconds, and a string is a recurring cron expression.\n *\n * @param when - The requested execution time or recurrence.\n * @param nowMs - Current epoch time in milliseconds.\n * @param callback - Callback name, used only in error messages.\n * @returns The parsed timing.\n * @throws For a `when` value that is not a `Date`, number, or string.\n */\nexport function parseWhen(\n when: Date | string | number,\n nowMs: number,\n callback: string\n): ScheduleTiming {\n if (when instanceof Date) {\n return { type: \"scheduled\", time: Math.floor(when.getTime() / 1000) };\n }\n if (typeof when === \"number\") {\n return {\n type: \"delayed\",\n time: Math.floor((nowMs + when * 1000) / 1000),\n delayInSeconds: when\n };\n }\n if (typeof when === \"string\") {\n return {\n type: \"cron\",\n time: Math.floor(nextCronTimeMs(when, nowMs) / 1000),\n cron: when\n };\n }\n throw new Error(\n `Invalid schedule type: ${JSON.stringify(when)}(${typeof when}) trying to schedule ${callback}`\n );\n}\n\n/**\n * Reject an interval outside the supported range.\n *\n * @param intervalSeconds - The requested gap between executions.\n * @throws For a non-positive interval or one longer than 30 days.\n */\nexport function validateIntervalSeconds(intervalSeconds: number): void {\n if (typeof intervalSeconds !== \"number\" || intervalSeconds <= 0) {\n throw new Error(\"intervalSeconds must be a positive number\");\n }\n if (intervalSeconds > MAX_INTERVAL_SECONDS) {\n throw new Error(\n `intervalSeconds cannot exceed ${MAX_INTERVAL_SECONDS} seconds (30 days)`\n );\n }\n}\n\n/**\n * Parse a fixed interval into schedule timing.\n *\n * @param intervalSeconds - Seconds between executions.\n * @param nowMs - Current epoch time in milliseconds.\n * @returns The parsed timing with the first execution one interval from now.\n * @throws For an interval outside the supported range.\n */\nexport function parseInterval(\n intervalSeconds: number,\n nowMs: number\n): ScheduleTiming {\n validateIntervalSeconds(intervalSeconds);\n return {\n type: \"interval\",\n time: Math.floor((nowMs + intervalSeconds * 1000) / 1000),\n intervalSeconds\n };\n}\n","/**\n * Lifecycle scheduling vocabulary. Scheduler validates schedules, resolves\n * named callbacks, and pushes jobs into the Lifecycle-owned job queue;\n * Lifecycle runs the alarm event loop, retry policy, and physical alarm\n * arming. Scheduler owns no storage of its own — each schedule is one job\n * whose `fn` is the callback name and whose payload carries the schedule's\n * timing vocabulary.\n */\n\nimport {\n LifecycleCapability,\n type LifecycleRouteAddress,\n type LifecycleRouteContext\n} from \"../lifecycle/capability\";\nimport type {\n LifecycleJob,\n LifecycleJobContext,\n LifecycleJobOutcome\n} from \"../lifecycle/job-queue\";\nimport {\n isDurableObjectCodeUpdateReset,\n isPlatformFailure,\n resolveRetryConfig,\n tryN,\n validateRetryOptions\n} from \"../retries\";\nimport type { RetryOptions } from \"../retries\";\nimport type { SchedulerEventType, SchedulerOptions } from \"./options\";\nimport {\n isRecurring,\n nextCronTimeMs,\n parseInterval,\n parseWhen,\n validateIntervalSeconds,\n type ScheduleTiming\n} from \"./schedule-timing\";\nimport type {\n RecoveryLoopScheduleOptions,\n Schedule,\n ScheduleCriteria,\n ScheduleOptions,\n ScheduleStorageRow,\n SchedulerCallbacks,\n SchedulerHandlers,\n SchedulerPayload\n} from \"./types\";\n\n/**\n * A resolved fallback handler for a callback name outside the registered map.\n */\ntype ResolvedSchedulerCallback = (\n payload: unknown,\n schedule: Schedule<unknown>\n) => unknown;\n\nconst schedulerCallbackResolvers = new WeakMap<\n object,\n (name: string) => ResolvedSchedulerCallback | undefined\n>();\n\n/**\n * @internal Supply a composition-root fallback for callback names outside the\n * registered map. Agent uses this to keep its historical name-based\n * scheduling API (`this.schedule(60, \"methodName\")`) working: the resolver\n * looks the method up on the Agent, and the resolved handler still runs\n * inside the Lifecycle host boundary.\n */\nexport function setSchedulerCallbackResolver(\n scheduler: Scheduler<never>,\n resolver: (name: string) => ResolvedSchedulerCallback | undefined\n): void {\n schedulerCallbackResolvers.set(scheduler, resolver);\n}\n\nconst SCHEDULE_SCHEMA_VERSION_KEY = \"cf_agents:schedules_schema_version\";\n/** Version 2: schedule rows live in the Lifecycle job queue. */\nconst CURRENT_SCHEDULE_SCHEMA_VERSION = 2;\n\n/**\n * Legacy schedule callbacks whose rows drive chat recovery loops from before\n * the job queue carried breaker membership. The migration is the one place\n * allowed to know legacy names (it already drops `_cf_keepAliveHeartbeat`\n * rows by name): a recovery row migrated without its `recoveryLoop` flag\n * would escape the alarm memory-limit breaker (#1825) and could re-trigger\n * a doomed loop on an upgraded object.\n */\nconst LEGACY_RECOVERY_LOOP_CALLBACKS = new Set([\n \"_chatRecoveryContinue\",\n \"_chatRecoveryRetry\"\n]);\n\nconst DEFAULT_RETRY: Required<RetryOptions> = {\n maxAttempts: 3,\n baseDelayMs: 100,\n maxDelayMs: 3000\n};\n\n/**\n * The schedule timing vocabulary carried in one job's payload. The callback\n * name is the job's `fn`; the user payload rides in `payload`.\n */\ntype SchedulerJobPayload = {\n readonly payload: unknown;\n readonly type: \"scheduled\" | \"delayed\" | \"cron\" | \"interval\";\n /** The caller-supplied retry override, unresolved, for public projection.\n The job's own retry options are fully resolved against the Scheduler\n defaults at push so the Lifecycle driver applies the configured\n policy. */\n readonly retry?: RetryOptions;\n readonly delayInSeconds?: number;\n readonly cron?: string;\n readonly intervalSeconds?: number;\n readonly owner_path?: string | null;\n readonly owner_path_key?: string | null;\n};\n\ntype SchedulerRouteMessage =\n | {\n readonly type: \"schedule\";\n readonly when: Date | string | number;\n readonly callback: string;\n readonly payload?: unknown;\n readonly options?: ScheduleOptions;\n }\n | {\n readonly type: \"every\";\n readonly intervalSeconds: number;\n readonly callback: string;\n readonly payload?: unknown;\n readonly options?: ScheduleOptions;\n }\n | { readonly type: \"get\" | \"cancel\"; readonly id: string }\n | { readonly type: \"list\"; readonly criteria?: ScheduleCriteria }\n | {\n readonly type: \"dispatch\";\n readonly id: string;\n readonly fn: string;\n readonly job: SchedulerJobPayload;\n readonly retry?: RetryOptions;\n };\n\ntype InsertResult<T> = {\n readonly schedule: Schedule<T>;\n readonly created: boolean;\n};\n\nfunction isSchedulerJobPayload(value: unknown): value is SchedulerJobPayload {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as SchedulerJobPayload).type === \"string\"\n );\n}\n\n/**\n * Persistent task scheduling for a Lifecycle Object.\n *\n * Register callbacks in the constructor and install the instance with\n * `Lifecycle.use()`. Scheduler validates schedules and pushes them into the\n * Lifecycle job queue; Lifecycle owns the physical alarm and the alarm\n * event loop, and Scheduler runs registered callbacks through Lifecycle's\n * host invocation boundary when its jobs come due.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Scheduler<\n Handlers extends SchedulerHandlers = SchedulerCallbacks\n> extends LifecycleCapability {\n readonly #handlers: SchedulerHandlers;\n readonly #retryDefaults: Required<RetryOptions>;\n readonly #hungScheduleTimeoutSeconds: number;\n readonly #onError: ((error: unknown) => void | Promise<void>) | undefined;\n readonly #warnedStartupCallbacks = new Set<string>();\n\n /**\n * Create a persistent Scheduler.\n *\n * @param options - Registered callbacks plus optional retry,\n * hung-interval, and error policy. Registering `callbacks` types\n * {@link set} and {@link every} against the map — names and\n * payloads are checked where the handlers are declared and where they are\n * scheduled. Names outside the map are rejected unless a composition-root\n * resolver supplies them — the internal aperture behind `Agent`'s\n * name-based scheduling API.\n */\n constructor(options: SchedulerOptions<Handlers> = {}) {\n super(\"scheduler\");\n this.#handlers = options.callbacks ?? {};\n // Retry defaults are resolved, not validated, here: a host whose\n // historically tolerated invalid retry config throws at construction\n // would brick every entry point of its Durable Object. Invalid defaults\n // surface per execution as schedule:error instead, and per-schedule\n // retry overrides are still validated when each schedule is created.\n this.#retryDefaults = resolveRetryConfig(options.retry, DEFAULT_RETRY);\n this.#hungScheduleTimeoutSeconds = options.hungScheduleTimeoutSeconds ?? 30;\n this.#onError = options.onError;\n }\n\n // ── Lifecycle capability hooks ───────────────────────────────────────────\n\n /** Migrate legacy schedule storage into the Lifecycle job queue. */\n async onStart(): Promise<void> {\n this.#warnedStartupCallbacks.clear();\n const storage = this.lifecycle.storage;\n const version =\n (await storage.get<number>(SCHEDULE_SCHEMA_VERSION_KEY)) ?? 0;\n if (version >= CURRENT_SCHEDULE_SCHEMA_VERSION) return;\n\n await this.#migrateLegacyScheduleTable(storage);\n await storage.put(\n SCHEDULE_SCHEMA_VERSION_KEY,\n CURRENT_SCHEDULE_SCHEMA_VERSION\n );\n }\n\n /**\n * Move every `cf_agents_schedules` row into the job queue and drop the\n * table. Idempotent: a missing table means a fresh object or a completed\n * migration. Times convert from epoch seconds to epoch milliseconds.\n */\n async #migrateLegacyScheduleTable(\n storage: DurableObjectStorage\n ): Promise<void> {\n const tables = storage.sql\n .exec(\n \"SELECT name FROM sqlite_master WHERE type='table' AND name='cf_agents_schedules'\"\n )\n .toArray();\n if (tables.length === 0) return;\n\n const rows = storage.sql\n .exec(\"SELECT * FROM cf_agents_schedules\")\n .toArray() as unknown as ScheduleStorageRow[];\n for (const row of rows) {\n // Keep-alive heartbeats stopped using schedule rows long ago; drop\n // orphans instead of migrating them.\n if (row.callback === \"_cf_keepAliveHeartbeat\") continue;\n let payload: unknown;\n try {\n payload =\n typeof row.payload === \"string\" ? JSON.parse(row.payload) : undefined;\n } catch (error) {\n console.error(\n `Skipping schedule \"${row.id}\" during job-queue migration: ` +\n \"its payload is not valid JSON\",\n error\n );\n continue;\n }\n let retry: RetryOptions | undefined;\n try {\n retry =\n typeof row.retry_options === \"string\"\n ? (JSON.parse(row.retry_options) as RetryOptions)\n : undefined;\n } catch {\n retry = undefined;\n }\n await this.lifecycle.jobs.push({\n id: row.id,\n fn: row.callback,\n time: row.time * 1000,\n payload: {\n payload,\n retry,\n type: row.type,\n delayInSeconds: row.delayInSeconds ?? undefined,\n cron: row.cron ?? undefined,\n intervalSeconds: row.intervalSeconds ?? undefined,\n owner_path: row.owner_path ?? null,\n owner_path_key: row.owner_path_key ?? null\n } satisfies SchedulerJobPayload,\n retry: resolveRetryConfig(retry, this.#retryDefaults),\n singleflight: row.type === \"interval\",\n hungTimeoutSeconds: this.#hungScheduleTimeoutSeconds,\n recoveryLoop: LEGACY_RECOVERY_LOOP_CALLBACKS.has(row.callback)\n });\n }\n storage.sql.exec(\"DROP TABLE cf_agents_schedules\");\n }\n\n /** Drive one due schedule job dispatched by the Lifecycle event loop. */\n async onJob(\n context: LifecycleJobContext\n ): Promise<LifecycleJobOutcome | void> {\n const { job, attempt } = context;\n const timing = job.payload;\n if (!isSchedulerJobPayload(timing)) {\n console.error(`Malformed schedule job ${job.id}; dropping it`);\n return undefined;\n }\n\n if (attempt === 1) {\n this.#emit(\"schedule:execute\", { callback: job.fn, id: job.id });\n } else {\n this.#emit(\"schedule:retry\", {\n callback: job.fn,\n id: job.id,\n attempt,\n maxAttempts: resolveRetryConfig(job.retry, this.#retryDefaults)\n .maxAttempts\n });\n }\n\n if (timing.owner_path) {\n // A routed schedule executes inside its owning Lifecycle; retries run\n // there too, so this dispatch is a single routed attempt.\n try {\n await this.lifecycle.routes.to(\n {\n key: timing.owner_path_key ?? timing.owner_path,\n data: timing.owner_path\n },\n {\n type: \"dispatch\",\n id: job.id,\n fn: job.fn,\n job: timing,\n retry: job.retry\n } satisfies SchedulerRouteMessage\n );\n } catch (error) {\n if (isPlatformFailure(error)) {\n // Preserve the job; Lifecycle defers platform-class failures to a\n // fresh invocation or the memory-limit breaker.\n throw error;\n }\n console.error(\n `error dispatching scheduled callback \"${job.fn}\"`,\n error\n );\n this.#emit(\"schedule:error\", {\n callback: job.fn,\n id: job.id,\n error: error instanceof Error ? error.message : String(error),\n attempts: 0\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n // Leave the job due so a later alarm cycle can retry dispatch, for\n // example once a transport can resolve its owner again.\n return \"yield\";\n }\n return this.#recurrenceOutcome(timing);\n }\n\n const handler = this.#resolveCallback(job.fn);\n if (!handler) {\n console.error(`callback ${job.fn} not found`);\n return this.#recurrenceOutcome(timing);\n }\n const schedule = this.#jobToSchedule<unknown>(job, timing);\n await this.lifecycle.runInHostContext(() =>\n handler(timing.payload, schedule)\n );\n return this.#recurrenceOutcome(timing);\n }\n\n /** Observe one schedule's terminal application failure. */\n async onJobError(\n context: LifecycleJobContext,\n error: unknown\n ): Promise<LifecycleJobOutcome | void> {\n const { job } = context;\n const timing = job.payload;\n if (!isSchedulerJobPayload(timing)) return undefined;\n const { maxAttempts } = resolveRetryConfig(job.retry, this.#retryDefaults);\n console.error(\n `error executing callback \"${job.fn}\" after ${maxAttempts} attempts`,\n error\n );\n this.#emit(\"schedule:error\", {\n callback: job.fn,\n id: job.id,\n error: error instanceof Error ? error.message : String(error),\n attempts: maxAttempts\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n return this.#recurrenceOutcome(timing);\n }\n\n /** Advance a recurring schedule; complete a one-shot. */\n #recurrenceOutcome(timing: SchedulerJobPayload): LifecycleJobOutcome {\n if (timing.type === \"cron\") {\n return { rescheduleAt: nextCronTimeMs(timing.cron ?? \"\", Date.now()) };\n }\n if (timing.type === \"interval\") {\n return {\n rescheduleAt: Date.now() + (timing.intervalSeconds ?? 0) * 1000\n };\n }\n return undefined;\n }\n\n /** Handle Scheduler protocol messages routed by another Lifecycle. */\n async onRoute(context: LifecycleRouteContext): Promise<unknown> {\n const message = context.payload as SchedulerRouteMessage;\n const owner = context.source ?? null;\n switch (message.type) {\n case \"schedule\":\n return this.#insert(\n owner,\n parseWhen(message.when, Date.now(), message.callback),\n message.callback,\n message.payload,\n message.options\n );\n case \"every\":\n return this.#insert(\n owner,\n parseInterval(message.intervalSeconds, Date.now()),\n message.callback,\n message.payload,\n message.options\n );\n case \"get\":\n return this.#getForOwner(owner, message.id);\n case \"list\":\n return this.#listForOwner(owner, message.criteria);\n case \"cancel\":\n return this.#cancelForOwner(owner, message.id);\n case \"dispatch\":\n await this.#executeRouted(\n message.id,\n message.fn,\n message.job,\n message.retry\n );\n return true;\n default:\n throw new Error(\"Unknown routed Scheduler message\");\n }\n }\n\n /**\n * Execute a routed schedule locally with the historical retry handling.\n * Runs on the owning (facet) Scheduler, outside the root's event loop, so\n * it applies its own in-process retry budget. Platform-class failures on a\n * one-shot re-throw so the root preserves the job and the durable alarm\n * retries on a fresh invocation.\n */\n async #executeRouted(\n id: string,\n fn: string,\n timing: SchedulerJobPayload,\n retry: RetryOptions | undefined\n ): Promise<void> {\n const handler = this.#resolveCallback(fn);\n if (!handler) {\n console.error(`callback ${fn} not found`);\n return;\n }\n const { maxAttempts, baseDelayMs, maxDelayMs } = resolveRetryConfig(\n retry,\n this.#retryDefaults\n );\n const isOneShot = timing.type === \"delayed\" || timing.type === \"scheduled\";\n const schedule = this.#payloadToSchedule<unknown>(id, fn, timing);\n try {\n await tryN(\n maxAttempts,\n async (attempt) => {\n if (attempt > 1) {\n this.#emit(\"schedule:retry\", {\n callback: fn,\n id,\n attempt,\n maxAttempts\n });\n }\n await this.lifecycle.runInHostContext(() =>\n handler(timing.payload, schedule)\n );\n },\n {\n baseDelayMs,\n maxDelayMs,\n shouldRetry: (error) =>\n !(isOneShot && isDurableObjectCodeUpdateReset(error))\n }\n );\n } catch (error) {\n if (isOneShot && isPlatformFailure(error)) {\n throw error;\n }\n console.error(\n `error executing callback \"${fn}\" after ${maxAttempts} attempts`,\n error\n );\n this.#emit(\"schedule:error\", {\n callback: fn,\n id,\n error: error instanceof Error ? error.message : String(error),\n attempts: maxAttempts\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n }\n }\n\n // ── Scheduling API ───────────────────────────────────────────────────────\n\n /** Set a delayed, dated, or cron schedule for a registered callback. */\n async set<Name extends keyof Handlers & string>(\n when: Date | string | number,\n callback: Name,\n payload?: SchedulerPayload<Handlers[Name]>,\n options?: ScheduleOptions\n ): Promise<Schedule<SchedulerPayload<Handlers[Name]>>> {\n await this.lifecycle.ready();\n this.#validateSchedule(when, callback, options);\n const result = this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"schedule\",\n when,\n callback,\n payload,\n options\n } satisfies SchedulerRouteMessage)) as InsertResult<\n SchedulerPayload<Handlers[Name]>\n >)\n : await this.#insert<SchedulerPayload<Handlers[Name]>>(\n null,\n parseWhen(when, Date.now(), callback),\n callback,\n payload,\n options\n );\n this.#emitCreated(result);\n return result.schedule;\n }\n\n /** Set a fixed-interval schedule for a registered callback. */\n async every<Name extends keyof Handlers & string>(\n intervalSeconds: number,\n callback: Name,\n payload?: SchedulerPayload<Handlers[Name]>,\n options?: ScheduleOptions\n ): Promise<Schedule<SchedulerPayload<Handlers[Name]>>> {\n await this.lifecycle.ready();\n this.#validateInterval(intervalSeconds, callback, options?.retry);\n const result = this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"every\",\n intervalSeconds,\n callback,\n payload,\n options\n } satisfies SchedulerRouteMessage)) as InsertResult<\n SchedulerPayload<Handlers[Name]>\n >)\n : await this.#insert<SchedulerPayload<Handlers[Name]>>(\n null,\n parseInterval(intervalSeconds, Date.now()),\n callback,\n payload,\n options\n );\n this.#emitCreated(result);\n return result.schedule;\n }\n\n /** Get a schedule by ID. Works inside routed sub-agents. */\n async get(id: string): Promise<Schedule<unknown> | undefined> {\n await this.lifecycle.ready();\n return this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"get\",\n id\n } satisfies SchedulerRouteMessage)) as Schedule<unknown> | undefined)\n : this.#getForOwner(null, id);\n }\n\n /** List schedules matching criteria. Works inside routed sub-agents. */\n async list(criteria: ScheduleCriteria = {}): Promise<Schedule<unknown>[]> {\n await this.lifecycle.ready();\n return this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"list\",\n criteria\n } satisfies SchedulerRouteMessage)) as Schedule<unknown>[])\n : this.#listForOwner(null, criteria);\n }\n\n /**\n * Cancel one schedule owned by this Scheduler.\n *\n * @param id - ID of the schedule to cancel.\n * @returns True when a schedule was cancelled, false when none matched.\n */\n async cancel(id: string): Promise<boolean> {\n await this.lifecycle.ready();\n const result = this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"cancel\",\n id\n } satisfies SchedulerRouteMessage)) as {\n ok: boolean;\n callback?: string;\n })\n : await this.#cancelForOwner(null, id);\n if (result.ok && result.callback) {\n this.#emit(\"schedule:cancel\", { callback: result.callback, id });\n }\n return result.ok;\n }\n\n // ── Host-owned policy apertures ──────────────────────────────────────────\n\n /**\n * @internal Synchronous read backing Agent's deprecated `getSchedule()`.\n * Not part of the primitive's contract — use {@link get}. Cannot cross\n * Durable Object boundaries and throws inside routed sub-agents.\n */\n __DO_NOT_USE_WILL_REMOVE__getSchedule<T = string>(\n id: string\n ): Schedule<T> | undefined {\n if (this.lifecycle.routes.source) {\n throw new Error(\n \"getSchedule() is synchronous and cannot read routed schedule storage. \" +\n \"Use await getScheduleById(id) on Agent, or await scheduler.get(id) \" +\n \"on a standalone Scheduler.\"\n );\n }\n return this.#getForOwner(null, id);\n }\n\n /**\n * @internal Synchronous read backing Agent's deprecated `getSchedules()`.\n * Not part of the primitive's contract — use {@link list}. Cannot cross\n * Durable Object boundaries and throws inside routed sub-agents.\n */\n __DO_NOT_USE_WILL_REMOVE__getSchedules<T = string>(\n criteria: ScheduleCriteria = {}\n ): Schedule<T>[] {\n if (this.lifecycle.routes.source) {\n throw new Error(\n \"getSchedules() is synchronous and cannot read routed schedule storage. \" +\n \"Use await listSchedules(criteria) on Agent, or await \" +\n \"scheduler.list(criteria) on a standalone Scheduler.\"\n );\n }\n return this.#listForOwner(null, criteria);\n }\n\n /** @internal Remove schedules owned by one routed Lifecycle subtree. */\n async __DO_NOT_USE_WILL_BREAK__cleanupRoutePrefix(\n prefix: string\n ): Promise<void> {\n for (const { job, timing } of this.#ownedJobs()) {\n const ownerKey = timing.owner_path_key ?? timing.owner_path;\n if (!timing.owner_path || ownerKey === null || ownerKey === undefined) {\n continue;\n }\n if (ownerKey !== prefix && !ownerKey.startsWith(`${prefix}/`)) continue;\n this.#emit(\"schedule:cancel\", { callback: job.fn, id: job.id });\n await this.lifecycle.jobs.cancel(job.id);\n }\n }\n\n // ── Validation ───────────────────────────────────────────────────────────\n\n #validateSchedule(\n when: Date | string | number,\n callback: string,\n options?: ScheduleOptions\n ): void {\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n if (!this.#hasCallback(callback)) {\n throw new Error(\n `Unknown scheduled callback \"${callback}\": not registered on this Scheduler`\n );\n }\n if (options?.retry) {\n validateRetryOptions(options.retry, this.#retryDefaults);\n }\n if (\n !(when instanceof Date) &&\n typeof when !== \"number\" &&\n typeof when !== \"string\"\n ) {\n throw new Error(\n `Invalid schedule type: ${JSON.stringify(when)}(${typeof when}) trying to schedule ${callback}`\n );\n }\n this.#warnWhenScheduledDuringStartup(when, callback, options);\n }\n\n #validateInterval(\n intervalSeconds: number,\n callback: string,\n retry?: RetryOptions\n ): void {\n validateIntervalSeconds(intervalSeconds);\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n if (!this.#hasCallback(callback)) {\n throw new Error(\n `Unknown scheduled callback \"${callback}\": not registered on this Scheduler`\n );\n }\n if (retry) validateRetryOptions(retry, this.#retryDefaults);\n }\n\n /**\n * A non-idempotent one-shot created during startup accumulates one row per\n * Durable Object wake, whether it came from the host's onStart or another\n * startup hook. Warn once per callback; an explicit `idempotent` choice\n * (either value) opts out.\n */\n #warnWhenScheduledDuringStartup(\n when: Date | string | number,\n callback: string,\n options?: ScheduleOptions\n ): void {\n if (this.lifecycle.status() !== \"starting\") return;\n if (options?.idempotent !== undefined) return;\n if (typeof when === \"string\") return;\n if (this.#warnedStartupCallbacks.has(callback)) return;\n this.#warnedStartupCallbacks.add(callback);\n console.warn(\n `Scheduling \"${callback}\" during startup (e.g. onStart()) without ` +\n `{ idempotent: true } creates a new row on every Durable Object ` +\n `restart, which can cause duplicate executions. Pass ` +\n `{ idempotent: true } to deduplicate, or use an interval schedule ` +\n `for recurring tasks.`\n );\n }\n\n /** Resolve a name to its registered or composition-root-supplied handler. */\n #resolveCallback(name: string): ResolvedSchedulerCallback | undefined {\n const handler = this.#handlers[name];\n if (handler) {\n // SAFETY: registered handlers are constrained with `never` parameters\n // so concrete handler types satisfy the map under contravariance; the\n // payload passed at dispatch was persisted with this handler's name.\n return handler as ResolvedSchedulerCallback;\n }\n return schedulerCallbackResolvers.get(this)?.(name);\n }\n\n /** True when a name resolves to a runnable callback. */\n #hasCallback(name: string): boolean {\n return this.#resolveCallback(name) !== undefined;\n }\n\n // ── Jobs ─────────────────────────────────────────────────────────────────\n\n /** Every schedule job this Scheduler owns, with its parsed vocabulary. */\n #ownedJobs(): Array<{ job: LifecycleJob; timing: SchedulerJobPayload }> {\n const owned: Array<{ job: LifecycleJob; timing: SchedulerJobPayload }> = [];\n for (const job of this.lifecycle.jobs.list()) {\n if (isSchedulerJobPayload(job.payload)) {\n owned.push({ job, timing: job.payload });\n }\n }\n return owned;\n }\n\n /**\n * Push a schedule job for the given owner, or return the existing job\n * when an idempotent request matches one. One-shot timings deduplicate only\n * when `idempotent: true` is passed; recurring timings deduplicate unless\n * `idempotent: false` opts out. `created: false` marks a dedup hit so\n * callers suppress the `schedule:create` event.\n */\n async #insert<T = string>(\n owner: LifecycleRouteAddress | null,\n timing: ScheduleTiming,\n callback: string,\n payload: unknown,\n options?: ScheduleOptions\n ): Promise<InsertResult<T>> {\n // Recurring timings deduplicate unless explicitly opted out; one-shot\n // timings deduplicate on any truthy value (historic Agent behavior).\n const idempotent = isRecurring(timing)\n ? options?.idempotent !== false\n : Boolean(options?.idempotent);\n // Not part of public ScheduleOptions. See RecoveryLoopScheduleOptions.\n const recoveryLoop = (\n options as Partial<RecoveryLoopScheduleOptions> | undefined\n )?.recoveryLoop;\n\n if (idempotent) {\n const existing = this.#findMatchingJob(\n owner?.key ?? null,\n timing,\n callback,\n JSON.stringify(payload)\n );\n if (existing) {\n // A dedup hit onto a row without breaker membership the caller asks\n // for (a row migrated from the legacy schedule table) re-pushes the\n // same durable intent in place with the flag — otherwise the row\n // would escape the alarm memory-limit breaker (#1825) forever.\n if (recoveryLoop && !existing.job.recoveryLoop) {\n await this.lifecycle.jobs.push({\n id: existing.job.id,\n fn: existing.job.fn,\n time: existing.job.time,\n payload: existing.job.payload,\n retry: existing.job.retry,\n singleflight: existing.job.singleflight,\n exclusive: existing.job.exclusive,\n hungTimeoutSeconds: this.#hungScheduleTimeoutSeconds,\n recoveryLoop: true\n });\n }\n // A dedup hit still re-arms so a lost physical alarm recovers, as\n // idempotent re-scheduling on startup historically guaranteed.\n await this.lifecycle.jobs.rearm();\n return {\n schedule: this.#jobToSchedule<T>(existing.job, existing.timing),\n created: false\n };\n }\n }\n\n const jobPayload: SchedulerJobPayload = {\n payload,\n retry: options?.retry,\n type: timing.type,\n delayInSeconds:\n timing.type === \"delayed\" ? timing.delayInSeconds : undefined,\n cron: timing.type === \"cron\" ? timing.cron : undefined,\n intervalSeconds:\n timing.type === \"interval\" ? timing.intervalSeconds : undefined,\n owner_path: owner?.data ?? null,\n owner_path_key: owner?.key ?? null\n };\n const job = await this.lifecycle.jobs.push({\n fn: callback,\n time: timing.time * 1000,\n payload: jobPayload,\n retry: resolveRetryConfig(options?.retry, this.#retryDefaults),\n singleflight: timing.type === \"interval\",\n hungTimeoutSeconds: this.#hungScheduleTimeoutSeconds,\n recoveryLoop\n });\n\n return {\n schedule: {\n id: job.id,\n callback,\n // SAFETY: payload is optional at the call site; historical API shape\n // types an omitted payload as the schedule's payload type.\n payload: payload as T,\n retry: options?.retry,\n ...timing\n },\n created: true\n };\n }\n\n /** Find the job an idempotent insert deduplicates onto, if any. */\n #findMatchingJob(\n ownerKey: string | null,\n timing: ScheduleTiming,\n callback: string,\n payloadJson: string\n ): { job: LifecycleJob; timing: SchedulerJobPayload } | undefined {\n for (const owned of this.#ownedJobs()) {\n const { job, timing: candidate } = owned;\n if (candidate.type !== timing.type) continue;\n if (job.fn !== callback) continue;\n if ((candidate.owner_path_key ?? null) !== ownerKey) continue;\n if (JSON.stringify(candidate.payload) !== payloadJson) continue;\n if (timing.type === \"cron\" && candidate.cron !== timing.cron) continue;\n if (\n timing.type === \"interval\" &&\n candidate.intervalSeconds !== timing.intervalSeconds\n ) {\n continue;\n }\n return owned;\n }\n return undefined;\n }\n\n #jobToSchedule<T>(\n job: LifecycleJob,\n timing: SchedulerJobPayload\n ): Schedule<T> {\n return this.#payloadToSchedule<T>(\n job.id,\n job.fn,\n timing,\n Math.floor(job.time / 1000)\n );\n }\n\n #payloadToSchedule<T>(\n id: string,\n fn: string,\n timing: SchedulerJobPayload,\n timeSeconds?: number\n ): Schedule<T> {\n const base = {\n callback: fn,\n id,\n payload: timing.payload as T,\n retry: timing.retry\n };\n const time = timeSeconds ?? 0;\n switch (timing.type) {\n case \"scheduled\":\n return { ...base, time, type: \"scheduled\" };\n case \"delayed\":\n return {\n ...base,\n delayInSeconds: timing.delayInSeconds ?? 0,\n time,\n type: \"delayed\"\n };\n case \"cron\":\n return { ...base, cron: timing.cron ?? \"\", time, type: \"cron\" };\n case \"interval\":\n return {\n ...base,\n intervalSeconds: timing.intervalSeconds ?? 0,\n time,\n type: \"interval\"\n };\n }\n }\n\n #getForOwner<T = string>(\n owner: LifecycleRouteAddress | null,\n id: string\n ): Schedule<T> | undefined {\n const ownerKey = owner?.key ?? null;\n const job = this.lifecycle.jobs.get(id);\n if (!job || !isSchedulerJobPayload(job.payload)) return undefined;\n if ((job.payload.owner_path_key ?? null) !== ownerKey) return undefined;\n return this.#jobToSchedule<T>(job, job.payload);\n }\n\n #listForOwner<T = string>(\n owner: LifecycleRouteAddress | null,\n criteria: ScheduleCriteria = {}\n ): Schedule<T>[] {\n const ownerKey = owner?.key ?? null;\n const startSeconds = criteria.timeRange\n ? Math.floor((criteria.timeRange.start ?? new Date(0)).getTime() / 1000)\n : null;\n const endSeconds = criteria.timeRange\n ? Math.floor(\n (criteria.timeRange.end ?? new Date(999999999999999)).getTime() / 1000\n )\n : null;\n\n const schedules: Schedule<T>[] = [];\n for (const { job, timing } of this.#ownedJobs()) {\n if ((timing.owner_path_key ?? null) !== ownerKey) continue;\n if (criteria.id && job.id !== criteria.id) continue;\n if (criteria.type && timing.type !== criteria.type) continue;\n const timeSeconds = Math.floor(job.time / 1000);\n if (startSeconds !== null && timeSeconds < startSeconds) continue;\n if (endSeconds !== null && timeSeconds > endSeconds) continue;\n schedules.push(this.#jobToSchedule<T>(job, timing));\n }\n return schedules;\n }\n\n async #cancelForOwner(\n owner: LifecycleRouteAddress | null,\n id: string\n ): Promise<{ ok: boolean; callback?: string }> {\n const ownerKey = owner?.key ?? null;\n const job = this.lifecycle.jobs.get(id);\n if (!job || !isSchedulerJobPayload(job.payload)) return { ok: false };\n if ((job.payload.owner_path_key ?? null) !== ownerKey) {\n return { ok: false };\n }\n const callback = job.fn;\n await this.lifecycle.jobs.cancel(id);\n return { ok: true, callback };\n }\n\n // ── Events ───────────────────────────────────────────────────────────────\n\n #emit(type: SchedulerEventType, payload: Record<string, unknown>): void {\n this.lifecycle.events.emit(type, payload);\n }\n\n #emitCreated(result: InsertResult<unknown>): void {\n if (!result.created) return;\n this.#emit(\"schedule:create\", {\n callback: result.schedule.callback,\n id: result.schedule.id\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAWA,MAAa,uBAAuB,MAAU,KAAK;;AAoCnD,SAAgB,YAAY,QAAiC;CAC3D,OAAO,OAAO,SAAS,UAAU,OAAO,SAAS;AACnD;;;;;;;;;AAUA,SAAgB,eAAe,MAAc,OAAuB;CAClE,OAAO,oBAAoB,IAAI,CAAC,CAAC,YAAY,IAAI,KAAK,KAAK,CAAC,CAAC,CAAC,QAAQ;AACxE;;;;;;;;;;;;;AAcA,SAAgB,UACd,MACA,OACA,UACgB;CAChB,IAAI,gBAAgB,MAClB,OAAO;EAAE,MAAM;EAAa,MAAM,KAAK,MAAM,KAAK,QAAQ,IAAI,GAAI;CAAE;CAEtE,IAAI,OAAO,SAAS,UAClB,OAAO;EACL,MAAM;EACN,MAAM,KAAK,OAAO,QAAQ,OAAO,OAAQ,GAAI;EAC7C,gBAAgB;CAClB;CAEF,IAAI,OAAO,SAAS,UAClB,OAAO;EACL,MA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AA,CAAA,KAAA,MAAuB,KAAK,MAAM,CAAC;CACpD;CACA,OAAO;AACT;AAEA,eAAA,gBACE,OACA,IAC6C;CAC7C,MAAM,WAAW,OAAO,OAAO;CAC/B,MAAM,MAAM,KAAK,UAAU,KAAK,IAAI,EAAE;CACtC,IAAI,CAAC,OAAO,CAAC,sBAAsB,IAAI,OAAO,GAAG,OAAO,EAAE,IAAI,MAAM;CACpE,KAAK,IAAI,QAAQ,kBAAkB,UAAU,UAC3C,OAAO,EAAE,IAAI,MAAM;CAErB,MAAM,WAAW,IAAI;CACrB,MAAM,KAAK,UAAU,KAAK,OAAO,EAAE;CACnC,OAAO;EAAE,IAAI;EAAM;CAAS;AAC9B;AAIA,SAAA,MAAM,MAA0B,SAAwC;CACtE,KAAK,UAAU,OAAO,KAAK,MAAM,OAAO;AAC1C;AAEA,SAAA,aAAa,QAAqC;CAChD,IAAI,CAAC,OAAO,SAAS;CACrB,kBAAA,kBAAA,MAAA,KAAA,CAAA,CAAA,KAAA,MAAW,mBAAmB;EAC5B,UAAU,OAAO,SAAS;EAC1B,IAAI,OAAO,SAAS;CACtB,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"scheduler-DZ3xQfeK.js","names":[],"sources":["../src/schedules/schedule-timing.ts","../src/schedules/scheduler.ts"],"sourcesContent":["/**\n * Pure timing rules for persistent schedules.\n *\n * A `ScheduleTiming` is the parsed \"when and how it runs\" half of a\n * `Schedule` — everything except identity, callback, and payload. Parsing\n * user-facing inputs here keeps Scheduler's storage code to one insert path.\n */\n\nimport { parseCronExpression } from \"cron-schedule\";\n\n/** Longest allowed gap between interval executions: 30 days. */\nexport const MAX_INTERVAL_SECONDS = 30 * 24 * 60 * 60;\n\n/** When and how one schedule runs; a `Schedule` minus identity and payload. */\nexport type ScheduleTiming =\n | {\n /** One-time execution at a specific date. */\n readonly type: \"scheduled\";\n /** Unix timestamp in seconds. */\n readonly time: number;\n }\n | {\n /** One-time execution after a relative delay. */\n readonly type: \"delayed\";\n /** Unix timestamp in seconds. */\n readonly time: number;\n /** Delay from creation in seconds. */\n readonly delayInSeconds: number;\n }\n | {\n /** Recurring execution from a cron expression. */\n readonly type: \"cron\";\n /** Unix timestamp in seconds for the next execution. */\n readonly time: number;\n /** Cron expression defining the recurrence. */\n readonly cron: string;\n }\n | {\n /** Recurring execution at a fixed interval. */\n readonly type: \"interval\";\n /** Unix timestamp in seconds for the next execution. */\n readonly time: number;\n /** Number of seconds between executions. */\n readonly intervalSeconds: number;\n };\n\n/** True when this timing repeats and therefore deduplicates by default. */\nexport function isRecurring(timing: ScheduleTiming): boolean {\n return timing.type === \"cron\" || timing.type === \"interval\";\n}\n\n/**\n * Next wall-clock execution time for a cron expression.\n *\n * @param cron - A standard cron expression.\n * @param nowMs - Current epoch time in milliseconds.\n * @returns The next execution epoch time in milliseconds.\n * @throws For an unparseable cron expression.\n */\nexport function nextCronTimeMs(cron: string, nowMs: number): number {\n return parseCronExpression(cron).getNextDate(new Date(nowMs)).getTime();\n}\n\n/**\n * Parse a user-facing `when` into schedule timing.\n *\n * A `Date` runs once at that date, a number runs once after that many\n * seconds, and a string is a recurring cron expression.\n *\n * @param when - The requested execution time or recurrence.\n * @param nowMs - Current epoch time in milliseconds.\n * @param callback - Callback name, used only in error messages.\n * @returns The parsed timing.\n * @throws For a `when` value that is not a `Date`, number, or string.\n */\nexport function parseWhen(\n when: Date | string | number,\n nowMs: number,\n callback: string\n): ScheduleTiming {\n if (when instanceof Date) {\n return { type: \"scheduled\", time: Math.floor(when.getTime() / 1000) };\n }\n if (typeof when === \"number\") {\n return {\n type: \"delayed\",\n time: Math.floor((nowMs + when * 1000) / 1000),\n delayInSeconds: when\n };\n }\n if (typeof when === \"string\") {\n return {\n type: \"cron\",\n time: Math.floor(nextCronTimeMs(when, nowMs) / 1000),\n cron: when\n };\n }\n throw new Error(\n `Invalid schedule type: ${JSON.stringify(when)}(${typeof when}) trying to schedule ${callback}`\n );\n}\n\n/**\n * Reject an interval outside the supported range.\n *\n * @param intervalSeconds - The requested gap between executions.\n * @throws For a non-positive interval or one longer than 30 days.\n */\nexport function validateIntervalSeconds(intervalSeconds: number): void {\n if (typeof intervalSeconds !== \"number\" || intervalSeconds <= 0) {\n throw new Error(\"intervalSeconds must be a positive number\");\n }\n if (intervalSeconds > MAX_INTERVAL_SECONDS) {\n throw new Error(\n `intervalSeconds cannot exceed ${MAX_INTERVAL_SECONDS} seconds (30 days)`\n );\n }\n}\n\n/**\n * Parse a fixed interval into schedule timing.\n *\n * @param intervalSeconds - Seconds between executions.\n * @param nowMs - Current epoch time in milliseconds.\n * @returns The parsed timing with the first execution one interval from now.\n * @throws For an interval outside the supported range.\n */\nexport function parseInterval(\n intervalSeconds: number,\n nowMs: number\n): ScheduleTiming {\n validateIntervalSeconds(intervalSeconds);\n return {\n type: \"interval\",\n time: Math.floor((nowMs + intervalSeconds * 1000) / 1000),\n intervalSeconds\n };\n}\n","/**\n * Lifecycle scheduling vocabulary. Scheduler validates schedules, resolves\n * named callbacks, and pushes jobs into the Lifecycle-owned job queue;\n * Lifecycle runs the alarm event loop, retry policy, and physical alarm\n * arming. Scheduler owns no storage of its own — each schedule is one job\n * whose `fn` is the callback name and whose payload carries the schedule's\n * timing vocabulary.\n */\n\nimport {\n LifecycleCapability,\n type LifecycleRouteAddress,\n type LifecycleRouteContext\n} from \"../lifecycle/capability\";\nimport type {\n LifecycleJob,\n LifecycleJobContext,\n LifecycleJobOutcome\n} from \"../lifecycle/job-queue\";\nimport {\n isDurableObjectCodeUpdateReset,\n isPlatformFailure,\n resolveRetryConfig,\n tryN,\n validateRetryOptions\n} from \"../retries\";\nimport type { RetryOptions } from \"../retries\";\nimport type { SchedulerEventType, SchedulerOptions } from \"./options\";\nimport {\n isRecurring,\n nextCronTimeMs,\n parseInterval,\n parseWhen,\n validateIntervalSeconds,\n type ScheduleTiming\n} from \"./schedule-timing\";\nimport type {\n RecoveryLoopScheduleOptions,\n Schedule,\n ScheduleCriteria,\n ScheduleOptions,\n ScheduleStorageRow,\n SchedulerCallbacks,\n SchedulerHandlers,\n SchedulerPayload\n} from \"./types\";\n\n/**\n * A resolved fallback handler for a callback name outside the registered map.\n */\ntype ResolvedSchedulerCallback = (\n payload: unknown,\n schedule: Schedule<unknown>\n) => unknown;\n\nconst schedulerCallbackResolvers = new WeakMap<\n object,\n (name: string) => ResolvedSchedulerCallback | undefined\n>();\n\n/**\n * @internal Supply a composition-root fallback for callback names outside the\n * registered map. Agent uses this to keep its historical name-based\n * scheduling API (`this.schedule(60, \"methodName\")`) working: the resolver\n * looks the method up on the Agent, and the resolved handler still runs\n * inside the Lifecycle host boundary.\n */\nexport function setSchedulerCallbackResolver(\n scheduler: Scheduler<never>,\n resolver: (name: string) => ResolvedSchedulerCallback | undefined\n): void {\n schedulerCallbackResolvers.set(scheduler, resolver);\n}\n\nconst SCHEDULE_SCHEMA_VERSION_KEY = \"cf_agents:schedules_schema_version\";\n/** Version 2: schedule rows live in the Lifecycle job queue. */\nconst CURRENT_SCHEDULE_SCHEMA_VERSION = 2;\n\n/**\n * Legacy schedule callbacks whose rows drive chat recovery loops from before\n * the job queue carried breaker membership. The migration is the one place\n * allowed to know legacy names (it already drops `_cf_keepAliveHeartbeat`\n * rows by name): a recovery row migrated without its `recoveryLoop` flag\n * would escape the alarm memory-limit breaker (#1825) and could re-trigger\n * a doomed loop on an upgraded object.\n */\nconst LEGACY_RECOVERY_LOOP_CALLBACKS = new Set([\n \"_chatRecoveryContinue\",\n \"_chatRecoveryRetry\"\n]);\n\nconst DEFAULT_RETRY: Required<RetryOptions> = {\n maxAttempts: 3,\n baseDelayMs: 100,\n maxDelayMs: 3000\n};\n\n/**\n * The schedule timing vocabulary carried in one job's payload. The callback\n * name is the job's `fn`; the user payload rides in `payload`.\n */\ntype SchedulerJobPayload = {\n readonly payload: unknown;\n readonly type: \"scheduled\" | \"delayed\" | \"cron\" | \"interval\";\n /** The caller-supplied retry override, unresolved, for public projection.\n The job's own retry options are fully resolved against the Scheduler\n defaults at push so the Lifecycle driver applies the configured\n policy. */\n readonly retry?: RetryOptions;\n readonly delayInSeconds?: number;\n readonly cron?: string;\n readonly intervalSeconds?: number;\n readonly owner_path?: string | null;\n readonly owner_path_key?: string | null;\n};\n\ntype SchedulerRouteMessage =\n | {\n readonly type: \"schedule\";\n readonly when: Date | string | number;\n readonly callback: string;\n readonly payload?: unknown;\n readonly options?: ScheduleOptions;\n }\n | {\n readonly type: \"every\";\n readonly intervalSeconds: number;\n readonly callback: string;\n readonly payload?: unknown;\n readonly options?: ScheduleOptions;\n }\n | { readonly type: \"get\" | \"cancel\"; readonly id: string }\n | { readonly type: \"list\"; readonly criteria?: ScheduleCriteria }\n | {\n readonly type: \"dispatch\";\n readonly id: string;\n readonly fn: string;\n readonly job: SchedulerJobPayload;\n readonly retry?: RetryOptions;\n };\n\ntype InsertResult<T> = {\n readonly schedule: Schedule<T>;\n readonly created: boolean;\n};\n\nfunction isSchedulerJobPayload(value: unknown): value is SchedulerJobPayload {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as SchedulerJobPayload).type === \"string\"\n );\n}\n\n/**\n * Persistent task scheduling for a Lifecycle Object.\n *\n * Register callbacks in the constructor and install the instance with\n * `Lifecycle.use()`. Scheduler validates schedules and pushes them into the\n * Lifecycle job queue; Lifecycle owns the physical alarm and the alarm\n * event loop, and Scheduler runs registered callbacks through Lifecycle's\n * host invocation boundary when its jobs come due.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Scheduler<\n Handlers extends SchedulerHandlers = SchedulerCallbacks\n> extends LifecycleCapability {\n readonly #handlers: SchedulerHandlers;\n readonly #retryDefaults: Required<RetryOptions>;\n readonly #hungScheduleTimeoutSeconds: number;\n readonly #onError: ((error: unknown) => void | Promise<void>) | undefined;\n readonly #warnedStartupCallbacks = new Set<string>();\n\n /**\n * Create a persistent Scheduler.\n *\n * @param options - Registered callbacks plus optional retry,\n * hung-interval, and error policy. Registering `callbacks` types\n * {@link set} and {@link every} against the map — names and\n * payloads are checked where the handlers are declared and where they are\n * scheduled. Names outside the map are rejected unless a composition-root\n * resolver supplies them — the internal aperture behind `Agent`'s\n * name-based scheduling API.\n */\n constructor(options: SchedulerOptions<Handlers> = {}) {\n super(\"scheduler\");\n this.#handlers = options.callbacks ?? {};\n // Retry defaults are resolved, not validated, here: a host whose\n // historically tolerated invalid retry config throws at construction\n // would brick every entry point of its Durable Object. Invalid defaults\n // surface per execution as schedule:error instead, and per-schedule\n // retry overrides are still validated when each schedule is created.\n this.#retryDefaults = resolveRetryConfig(options.retry, DEFAULT_RETRY);\n this.#hungScheduleTimeoutSeconds = options.hungScheduleTimeoutSeconds ?? 30;\n this.#onError = options.onError;\n }\n\n // ── Lifecycle capability hooks ───────────────────────────────────────────\n\n /** Migrate legacy schedule storage into the Lifecycle job queue. */\n async onStart(): Promise<void> {\n this.#warnedStartupCallbacks.clear();\n const storage = this.lifecycle.storage;\n const version =\n (await storage.get<number>(SCHEDULE_SCHEMA_VERSION_KEY)) ?? 0;\n if (version >= CURRENT_SCHEDULE_SCHEMA_VERSION) return;\n\n await this.#migrateLegacyScheduleTable(storage);\n await storage.put(\n SCHEDULE_SCHEMA_VERSION_KEY,\n CURRENT_SCHEDULE_SCHEMA_VERSION\n );\n }\n\n /**\n * Move every `cf_agents_schedules` row into the job queue and drop the\n * table. Idempotent: a missing table means a fresh object or a completed\n * migration. Times convert from epoch seconds to epoch milliseconds.\n */\n async #migrateLegacyScheduleTable(\n storage: DurableObjectStorage\n ): Promise<void> {\n const tables = storage.sql\n .exec(\n \"SELECT name FROM sqlite_master WHERE type='table' AND name='cf_agents_schedules'\"\n )\n .toArray();\n if (tables.length === 0) return;\n\n const rows = storage.sql\n .exec(\"SELECT * FROM cf_agents_schedules\")\n .toArray() as unknown as ScheduleStorageRow[];\n for (const row of rows) {\n // Keep-alive heartbeats stopped using schedule rows long ago; drop\n // orphans instead of migrating them.\n if (row.callback === \"_cf_keepAliveHeartbeat\") continue;\n let payload: unknown;\n try {\n payload =\n typeof row.payload === \"string\" ? JSON.parse(row.payload) : undefined;\n } catch (error) {\n console.error(\n `Skipping schedule \"${row.id}\" during job-queue migration: ` +\n \"its payload is not valid JSON\",\n error\n );\n continue;\n }\n let retry: RetryOptions | undefined;\n try {\n retry =\n typeof row.retry_options === \"string\"\n ? (JSON.parse(row.retry_options) as RetryOptions)\n : undefined;\n } catch {\n retry = undefined;\n }\n await this.lifecycle.jobs.push({\n id: row.id,\n fn: row.callback,\n time: row.time * 1000,\n payload: {\n payload,\n retry,\n type: row.type,\n delayInSeconds: row.delayInSeconds ?? undefined,\n cron: row.cron ?? undefined,\n intervalSeconds: row.intervalSeconds ?? undefined,\n owner_path: row.owner_path ?? null,\n owner_path_key: row.owner_path_key ?? null\n } satisfies SchedulerJobPayload,\n retry: resolveRetryConfig(retry, this.#retryDefaults),\n singleflight: row.type === \"interval\",\n hungTimeoutSeconds: this.#hungScheduleTimeoutSeconds,\n recoveryLoop: LEGACY_RECOVERY_LOOP_CALLBACKS.has(row.callback)\n });\n }\n storage.sql.exec(\"DROP TABLE cf_agents_schedules\");\n }\n\n /** Drive one due schedule job dispatched by the Lifecycle event loop. */\n async onJob(\n context: LifecycleJobContext\n ): Promise<LifecycleJobOutcome | void> {\n const { job, attempt } = context;\n const timing = job.payload;\n if (!isSchedulerJobPayload(timing)) {\n console.error(`Malformed schedule job ${job.id}; dropping it`);\n return undefined;\n }\n\n if (attempt === 1) {\n this.#emit(\"schedule:execute\", { callback: job.fn, id: job.id });\n } else {\n this.#emit(\"schedule:retry\", {\n callback: job.fn,\n id: job.id,\n attempt,\n maxAttempts: resolveRetryConfig(job.retry, this.#retryDefaults)\n .maxAttempts\n });\n }\n\n if (timing.owner_path) {\n // A routed schedule executes inside its owning Lifecycle; retries run\n // there too, so this dispatch is a single routed attempt.\n try {\n await this.lifecycle.routes.to(\n {\n key: timing.owner_path_key ?? timing.owner_path,\n data: timing.owner_path\n },\n {\n type: \"dispatch\",\n id: job.id,\n fn: job.fn,\n job: timing,\n retry: job.retry\n } satisfies SchedulerRouteMessage\n );\n } catch (error) {\n if (isPlatformFailure(error)) {\n // Preserve the job; Lifecycle defers platform-class failures to a\n // fresh invocation or the memory-limit breaker.\n throw error;\n }\n console.error(\n `error dispatching scheduled callback \"${job.fn}\"`,\n error\n );\n this.#emit(\"schedule:error\", {\n callback: job.fn,\n id: job.id,\n error: error instanceof Error ? error.message : String(error),\n attempts: 0\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n // Leave the job due so a later alarm cycle can retry dispatch, for\n // example once a transport can resolve its owner again.\n return \"yield\";\n }\n return this.#recurrenceOutcome(timing);\n }\n\n const handler = this.#resolveCallback(job.fn);\n if (!handler) {\n console.error(`callback ${job.fn} not found`);\n return this.#recurrenceOutcome(timing);\n }\n const schedule = this.#jobToSchedule<unknown>(job, timing);\n await this.lifecycle.runInHostContext(() =>\n handler(timing.payload, schedule)\n );\n return this.#recurrenceOutcome(timing);\n }\n\n /** Observe one schedule's terminal application failure. */\n async onJobError(\n context: LifecycleJobContext,\n error: unknown\n ): Promise<LifecycleJobOutcome | void> {\n const { job } = context;\n const timing = job.payload;\n if (!isSchedulerJobPayload(timing)) return undefined;\n const { maxAttempts } = resolveRetryConfig(job.retry, this.#retryDefaults);\n console.error(\n `error executing callback \"${job.fn}\" after ${maxAttempts} attempts`,\n error\n );\n this.#emit(\"schedule:error\", {\n callback: job.fn,\n id: job.id,\n error: error instanceof Error ? error.message : String(error),\n attempts: maxAttempts\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n return this.#recurrenceOutcome(timing);\n }\n\n /** Advance a recurring schedule; complete a one-shot. */\n #recurrenceOutcome(timing: SchedulerJobPayload): LifecycleJobOutcome {\n if (timing.type === \"cron\") {\n return { rescheduleAt: nextCronTimeMs(timing.cron ?? \"\", Date.now()) };\n }\n if (timing.type === \"interval\") {\n return {\n rescheduleAt: Date.now() + (timing.intervalSeconds ?? 0) * 1000\n };\n }\n return undefined;\n }\n\n /** Handle Scheduler protocol messages routed by another Lifecycle. */\n async onRoute(context: LifecycleRouteContext): Promise<unknown> {\n const message = context.payload as SchedulerRouteMessage;\n const owner = context.source ?? null;\n switch (message.type) {\n case \"schedule\":\n return this.#insert(\n owner,\n parseWhen(message.when, Date.now(), message.callback),\n message.callback,\n message.payload,\n message.options\n );\n case \"every\":\n return this.#insert(\n owner,\n parseInterval(message.intervalSeconds, Date.now()),\n message.callback,\n message.payload,\n message.options\n );\n case \"get\":\n return this.#getForOwner(owner, message.id);\n case \"list\":\n return this.#listForOwner(owner, message.criteria);\n case \"cancel\":\n return this.#cancelForOwner(owner, message.id);\n case \"dispatch\":\n await this.#executeRouted(\n message.id,\n message.fn,\n message.job,\n message.retry\n );\n return true;\n default:\n throw new Error(\"Unknown routed Scheduler message\");\n }\n }\n\n /**\n * Execute a routed schedule locally with the historical retry handling.\n * Runs on the owning (facet) Scheduler, outside the root's event loop, so\n * it applies its own in-process retry budget. Platform-class failures on a\n * one-shot re-throw so the root preserves the job and the durable alarm\n * retries on a fresh invocation.\n */\n async #executeRouted(\n id: string,\n fn: string,\n timing: SchedulerJobPayload,\n retry: RetryOptions | undefined\n ): Promise<void> {\n const handler = this.#resolveCallback(fn);\n if (!handler) {\n console.error(`callback ${fn} not found`);\n return;\n }\n const { maxAttempts, baseDelayMs, maxDelayMs } = resolveRetryConfig(\n retry,\n this.#retryDefaults\n );\n const isOneShot = timing.type === \"delayed\" || timing.type === \"scheduled\";\n const schedule = this.#payloadToSchedule<unknown>(id, fn, timing);\n try {\n await tryN(\n maxAttempts,\n async (attempt) => {\n if (attempt > 1) {\n this.#emit(\"schedule:retry\", {\n callback: fn,\n id,\n attempt,\n maxAttempts\n });\n }\n await this.lifecycle.runInHostContext(() =>\n handler(timing.payload, schedule)\n );\n },\n {\n baseDelayMs,\n maxDelayMs,\n shouldRetry: (error) =>\n !(isOneShot && isDurableObjectCodeUpdateReset(error))\n }\n );\n } catch (error) {\n if (isOneShot && isPlatformFailure(error)) {\n throw error;\n }\n console.error(\n `error executing callback \"${fn}\" after ${maxAttempts} attempts`,\n error\n );\n this.#emit(\"schedule:error\", {\n callback: fn,\n id,\n error: error instanceof Error ? error.message : String(error),\n attempts: maxAttempts\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n }\n }\n\n // ── Scheduling API ───────────────────────────────────────────────────────\n\n /** Set a delayed, dated, or cron schedule for a registered callback. */\n async set<Name extends keyof Handlers & string>(\n when: Date | string | number,\n callback: Name,\n payload?: SchedulerPayload<Handlers[Name]>,\n options?: ScheduleOptions\n ): Promise<Schedule<SchedulerPayload<Handlers[Name]>>> {\n await this.lifecycle.ready();\n this.#validateSchedule(when, callback, options);\n const result = this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"schedule\",\n when,\n callback,\n payload,\n options\n } satisfies SchedulerRouteMessage)) as InsertResult<\n SchedulerPayload<Handlers[Name]>\n >)\n : await this.#insert<SchedulerPayload<Handlers[Name]>>(\n null,\n parseWhen(when, Date.now(), callback),\n callback,\n payload,\n options\n );\n this.#emitCreated(result);\n return result.schedule;\n }\n\n /** Set a fixed-interval schedule for a registered callback. */\n async every<Name extends keyof Handlers & string>(\n intervalSeconds: number,\n callback: Name,\n payload?: SchedulerPayload<Handlers[Name]>,\n options?: ScheduleOptions\n ): Promise<Schedule<SchedulerPayload<Handlers[Name]>>> {\n await this.lifecycle.ready();\n this.#validateInterval(intervalSeconds, callback, options?.retry);\n const result = this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"every\",\n intervalSeconds,\n callback,\n payload,\n options\n } satisfies SchedulerRouteMessage)) as InsertResult<\n SchedulerPayload<Handlers[Name]>\n >)\n : await this.#insert<SchedulerPayload<Handlers[Name]>>(\n null,\n parseInterval(intervalSeconds, Date.now()),\n callback,\n payload,\n options\n );\n this.#emitCreated(result);\n return result.schedule;\n }\n\n /** Get a schedule by ID. Works inside routed sub-agents. */\n async get(id: string): Promise<Schedule<unknown> | undefined> {\n await this.lifecycle.ready();\n return this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"get\",\n id\n } satisfies SchedulerRouteMessage)) as Schedule<unknown> | undefined)\n : this.#getForOwner(null, id);\n }\n\n /** List schedules matching criteria. Works inside routed sub-agents. */\n async list(criteria: ScheduleCriteria = {}): Promise<Schedule<unknown>[]> {\n await this.lifecycle.ready();\n return this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"list\",\n criteria\n } satisfies SchedulerRouteMessage)) as Schedule<unknown>[])\n : this.#listForOwner(null, criteria);\n }\n\n /**\n * Cancel one schedule owned by this Scheduler.\n *\n * @param id - ID of the schedule to cancel.\n * @returns True when a schedule was cancelled, false when none matched.\n */\n async cancel(id: string): Promise<boolean> {\n await this.lifecycle.ready();\n const result = this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"cancel\",\n id\n } satisfies SchedulerRouteMessage)) as {\n ok: boolean;\n callback?: string;\n })\n : await this.#cancelForOwner(null, id);\n if (result.ok && result.callback) {\n this.#emit(\"schedule:cancel\", { callback: result.callback, id });\n }\n return result.ok;\n }\n\n // ── Host-owned policy apertures ──────────────────────────────────────────\n\n /**\n * @internal Synchronous read backing Agent's deprecated `getSchedule()`.\n * Not part of the primitive's contract — use {@link get}. Cannot cross\n * Durable Object boundaries and throws inside routed sub-agents.\n */\n __DO_NOT_USE_WILL_REMOVE__getSchedule<T = string>(\n id: string\n ): Schedule<T> | undefined {\n if (this.lifecycle.routes.source) {\n throw new Error(\n \"getSchedule() is synchronous and cannot read routed schedule storage. \" +\n \"Use await getScheduleById(id) on Agent, or await scheduler.get(id) \" +\n \"on a standalone Scheduler.\"\n );\n }\n return this.#getForOwner(null, id);\n }\n\n /**\n * @internal Synchronous read backing Agent's deprecated `getSchedules()`.\n * Not part of the primitive's contract — use {@link list}. Cannot cross\n * Durable Object boundaries and throws inside routed sub-agents.\n */\n __DO_NOT_USE_WILL_REMOVE__getSchedules<T = string>(\n criteria: ScheduleCriteria = {}\n ): Schedule<T>[] {\n if (this.lifecycle.routes.source) {\n throw new Error(\n \"getSchedules() is synchronous and cannot read routed schedule storage. \" +\n \"Use await listSchedules(criteria) on Agent, or await \" +\n \"scheduler.list(criteria) on a standalone Scheduler.\"\n );\n }\n return this.#listForOwner(null, criteria);\n }\n\n /** @internal Remove schedules owned by one routed Lifecycle subtree. */\n async __DO_NOT_USE_WILL_BREAK__cleanupRoutePrefix(\n prefix: string\n ): Promise<void> {\n for (const { job, timing } of this.#ownedJobs()) {\n const ownerKey = timing.owner_path_key ?? timing.owner_path;\n if (!timing.owner_path || ownerKey === null || ownerKey === undefined) {\n continue;\n }\n if (ownerKey !== prefix && !ownerKey.startsWith(`${prefix}/`)) continue;\n this.#emit(\"schedule:cancel\", { callback: job.fn, id: job.id });\n await this.lifecycle.jobs.cancel(job.id);\n }\n }\n\n // ── Validation ───────────────────────────────────────────────────────────\n\n #validateSchedule(\n when: Date | string | number,\n callback: string,\n options?: ScheduleOptions\n ): void {\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n if (!this.#hasCallback(callback)) {\n throw new Error(\n `Unknown scheduled callback \"${callback}\": not registered on this Scheduler`\n );\n }\n if (options?.retry) {\n validateRetryOptions(options.retry, this.#retryDefaults);\n }\n if (\n !(when instanceof Date) &&\n typeof when !== \"number\" &&\n typeof when !== \"string\"\n ) {\n throw new Error(\n `Invalid schedule type: ${JSON.stringify(when)}(${typeof when}) trying to schedule ${callback}`\n );\n }\n this.#warnWhenScheduledDuringStartup(when, callback, options);\n }\n\n #validateInterval(\n intervalSeconds: number,\n callback: string,\n retry?: RetryOptions\n ): void {\n validateIntervalSeconds(intervalSeconds);\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n if (!this.#hasCallback(callback)) {\n throw new Error(\n `Unknown scheduled callback \"${callback}\": not registered on this Scheduler`\n );\n }\n if (retry) validateRetryOptions(retry, this.#retryDefaults);\n }\n\n /**\n * A non-idempotent one-shot created during startup accumulates one row per\n * Durable Object wake, whether it came from the host's onStart or another\n * startup hook. Warn once per callback; an explicit `idempotent` choice\n * (either value) opts out.\n */\n #warnWhenScheduledDuringStartup(\n when: Date | string | number,\n callback: string,\n options?: ScheduleOptions\n ): void {\n if (this.lifecycle.status() !== \"starting\") return;\n if (options?.idempotent !== undefined) return;\n if (typeof when === \"string\") return;\n if (this.#warnedStartupCallbacks.has(callback)) return;\n this.#warnedStartupCallbacks.add(callback);\n console.warn(\n `Scheduling \"${callback}\" during startup (e.g. onStart()) without ` +\n `{ idempotent: true } creates a new row on every Durable Object ` +\n `restart, which can cause duplicate executions. Pass ` +\n `{ idempotent: true } to deduplicate, or use an interval schedule ` +\n `for recurring tasks.`\n );\n }\n\n /** Resolve a name to its registered or composition-root-supplied handler. */\n #resolveCallback(name: string): ResolvedSchedulerCallback | undefined {\n const handler = this.#handlers[name];\n if (handler) {\n // SAFETY: registered handlers are constrained with `never` parameters\n // so concrete handler types satisfy the map under contravariance; the\n // payload passed at dispatch was persisted with this handler's name.\n return handler as ResolvedSchedulerCallback;\n }\n return schedulerCallbackResolvers.get(this)?.(name);\n }\n\n /** True when a name resolves to a runnable callback. */\n #hasCallback(name: string): boolean {\n return this.#resolveCallback(name) !== undefined;\n }\n\n // ── Jobs ─────────────────────────────────────────────────────────────────\n\n /** Every schedule job this Scheduler owns, with its parsed vocabulary. */\n #ownedJobs(): Array<{ job: LifecycleJob; timing: SchedulerJobPayload }> {\n const owned: Array<{ job: LifecycleJob; timing: SchedulerJobPayload }> = [];\n for (const job of this.lifecycle.jobs.list()) {\n if (isSchedulerJobPayload(job.payload)) {\n owned.push({ job, timing: job.payload });\n }\n }\n return owned;\n }\n\n /**\n * Push a schedule job for the given owner, or return the existing job\n * when an idempotent request matches one. One-shot timings deduplicate only\n * when `idempotent: true` is passed; recurring timings deduplicate unless\n * `idempotent: false` opts out. `created: false` marks a dedup hit so\n * callers suppress the `schedule:create` event.\n */\n async #insert<T = string>(\n owner: LifecycleRouteAddress | null,\n timing: ScheduleTiming,\n callback: string,\n payload: unknown,\n options?: ScheduleOptions\n ): Promise<InsertResult<T>> {\n // Recurring timings deduplicate unless explicitly opted out; one-shot\n // timings deduplicate on any truthy value (historic Agent behavior).\n const idempotent = isRecurring(timing)\n ? options?.idempotent !== false\n : Boolean(options?.idempotent);\n // Not part of public ScheduleOptions. See RecoveryLoopScheduleOptions.\n const recoveryLoop = (\n options as Partial<RecoveryLoopScheduleOptions> | undefined\n )?.recoveryLoop;\n\n if (idempotent) {\n const existing = this.#findMatchingJob(\n owner?.key ?? null,\n timing,\n callback,\n JSON.stringify(payload)\n );\n if (existing) {\n // A dedup hit onto a row without breaker membership the caller asks\n // for (a row migrated from the legacy schedule table) re-pushes the\n // same durable intent in place with the flag — otherwise the row\n // would escape the alarm memory-limit breaker (#1825) forever.\n if (recoveryLoop && !existing.job.recoveryLoop) {\n await this.lifecycle.jobs.push({\n id: existing.job.id,\n fn: existing.job.fn,\n time: existing.job.time,\n payload: existing.job.payload,\n retry: existing.job.retry,\n singleflight: existing.job.singleflight,\n exclusive: existing.job.exclusive,\n hungTimeoutSeconds: this.#hungScheduleTimeoutSeconds,\n recoveryLoop: true\n });\n }\n // A dedup hit still re-arms so a lost physical alarm recovers, as\n // idempotent re-scheduling on startup historically guaranteed.\n await this.lifecycle.jobs.rearm();\n return {\n schedule: this.#jobToSchedule<T>(existing.job, existing.timing),\n created: false\n };\n }\n }\n\n const jobPayload: SchedulerJobPayload = {\n payload,\n retry: options?.retry,\n type: timing.type,\n delayInSeconds:\n timing.type === \"delayed\" ? timing.delayInSeconds : undefined,\n cron: timing.type === \"cron\" ? timing.cron : undefined,\n intervalSeconds:\n timing.type === \"interval\" ? timing.intervalSeconds : undefined,\n owner_path: owner?.data ?? null,\n owner_path_key: owner?.key ?? null\n };\n const job = await this.lifecycle.jobs.push({\n fn: callback,\n time: timing.time * 1000,\n payload: jobPayload,\n retry: resolveRetryConfig(options?.retry, this.#retryDefaults),\n singleflight: timing.type === \"interval\",\n hungTimeoutSeconds: this.#hungScheduleTimeoutSeconds,\n recoveryLoop\n });\n\n return {\n schedule: {\n id: job.id,\n callback,\n // SAFETY: payload is optional at the call site; historical API shape\n // types an omitted payload as the schedule's payload type.\n payload: payload as T,\n retry: options?.retry,\n ...timing\n },\n created: true\n };\n }\n\n /** Find the job an idempotent insert deduplicates onto, if any. */\n #findMatchingJob(\n ownerKey: string | null,\n timing: ScheduleTiming,\n callback: string,\n payloadJson: string\n ): { job: LifecycleJob; timing: SchedulerJobPayload } | undefined {\n for (const owned of this.#ownedJobs()) {\n const { job, timing: candidate } = owned;\n if (candidate.type !== timing.type) continue;\n if (job.fn !== callback) continue;\n if ((candidate.owner_path_key ?? null) !== ownerKey) continue;\n if (JSON.stringify(candidate.payload) !== payloadJson) continue;\n if (timing.type === \"cron\" && candidate.cron !== timing.cron) continue;\n if (\n timing.type === \"interval\" &&\n candidate.intervalSeconds !== timing.intervalSeconds\n ) {\n continue;\n }\n return owned;\n }\n return undefined;\n }\n\n #jobToSchedule<T>(\n job: LifecycleJob,\n timing: SchedulerJobPayload\n ): Schedule<T> {\n return this.#payloadToSchedule<T>(\n job.id,\n job.fn,\n timing,\n Math.floor(job.time / 1000)\n );\n }\n\n #payloadToSchedule<T>(\n id: string,\n fn: string,\n timing: SchedulerJobPayload,\n timeSeconds?: number\n ): Schedule<T> {\n const base = {\n callback: fn,\n id,\n payload: timing.payload as T,\n retry: timing.retry\n };\n const time = timeSeconds ?? 0;\n switch (timing.type) {\n case \"scheduled\":\n return { ...base, time, type: \"scheduled\" };\n case \"delayed\":\n return {\n ...base,\n delayInSeconds: timing.delayInSeconds ?? 0,\n time,\n type: \"delayed\"\n };\n case \"cron\":\n return { ...base, cron: timing.cron ?? \"\", time, type: \"cron\" };\n case \"interval\":\n return {\n ...base,\n intervalSeconds: timing.intervalSeconds ?? 0,\n time,\n type: \"interval\"\n };\n }\n }\n\n #getForOwner<T = string>(\n owner: LifecycleRouteAddress | null,\n id: string\n ): Schedule<T> | undefined {\n const ownerKey = owner?.key ?? null;\n const job = this.lifecycle.jobs.get(id);\n if (!job || !isSchedulerJobPayload(job.payload)) return undefined;\n if ((job.payload.owner_path_key ?? null) !== ownerKey) return undefined;\n return this.#jobToSchedule<T>(job, job.payload);\n }\n\n #listForOwner<T = string>(\n owner: LifecycleRouteAddress | null,\n criteria: ScheduleCriteria = {}\n ): Schedule<T>[] {\n const ownerKey = owner?.key ?? null;\n const startSeconds = criteria.timeRange\n ? Math.floor((criteria.timeRange.start ?? new Date(0)).getTime() / 1000)\n : null;\n const endSeconds = criteria.timeRange\n ? Math.floor(\n (criteria.timeRange.end ?? new Date(999999999999999)).getTime() / 1000\n )\n : null;\n\n const schedules: Schedule<T>[] = [];\n for (const { job, timing } of this.#ownedJobs()) {\n if ((timing.owner_path_key ?? null) !== ownerKey) continue;\n if (criteria.id && job.id !== criteria.id) continue;\n if (criteria.type && timing.type !== criteria.type) continue;\n const timeSeconds = Math.floor(job.time / 1000);\n if (startSeconds !== null && timeSeconds < startSeconds) continue;\n if (endSeconds !== null && timeSeconds > endSeconds) continue;\n schedules.push(this.#jobToSchedule<T>(job, timing));\n }\n return schedules;\n }\n\n async #cancelForOwner(\n owner: LifecycleRouteAddress | null,\n id: string\n ): Promise<{ ok: boolean; callback?: string }> {\n const ownerKey = owner?.key ?? null;\n const job = this.lifecycle.jobs.get(id);\n if (!job || !isSchedulerJobPayload(job.payload)) return { ok: false };\n if ((job.payload.owner_path_key ?? null) !== ownerKey) {\n return { ok: false };\n }\n const callback = job.fn;\n await this.lifecycle.jobs.cancel(id);\n return { ok: true, callback };\n }\n\n // ── Events ───────────────────────────────────────────────────────────────\n\n #emit(type: SchedulerEventType, payload: Record<string, unknown>): void {\n this.lifecycle.events.emit(type, payload);\n }\n\n #emitCreated(result: InsertResult<unknown>): void {\n if (!result.created) return;\n this.#emit(\"schedule:create\", {\n callback: result.schedule.callback,\n id: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,mBAAmB;EAC5B,UAAU,OAAO,SAAS;EAC1B,IAAI,OAAO,SAAS;CACtB,CAAC;AACH"}
|
|
@@ -3,8 +3,8 @@ import {
|
|
|
3
3
|
d as LifecycleRouteContext,
|
|
4
4
|
s as LifecycleCapability,
|
|
5
5
|
v as LifecycleJobOutcome
|
|
6
|
-
} from "./capability-runner-
|
|
7
|
-
import { t as RetryOptions } from "./retries-
|
|
6
|
+
} from "./capability-runner-DBAnGr6L.js";
|
|
7
|
+
import { t as RetryOptions } from "./retries-CV6AkXmQ.js";
|
|
8
8
|
|
|
9
9
|
//#region src/schedules/types.d.ts
|
|
10
10
|
/**
|
|
@@ -220,4 +220,4 @@ export {
|
|
|
220
220
|
SchedulerCallbacks as s,
|
|
221
221
|
Scheduler as t
|
|
222
222
|
};
|
|
223
|
-
//# sourceMappingURL=scheduler-
|
|
223
|
+
//# sourceMappingURL=scheduler-RdACNXDP.d.ts.map
|
package/dist/schedules/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as Scheduler } from "../scheduler-
|
|
1
|
+
import { t as Scheduler } from "../scheduler-DZ3xQfeK.js";
|
|
2
2
|
export { Scheduler };
|
package/dist/serializable.d.ts
CHANGED