@effect-agent/platform-cloudflare 0.1.0-beta.83 → 0.1.0-beta.85
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/Alarm.mjs +1 -1
- package/dist/Alarm.mjs.map +1 -1
- package/dist/BrowserRestCrawl.mjs +1 -1
- package/dist/BrowserRestCrawl.mjs.map +1 -1
- package/dist/CloudflareBindings.d.mts +6 -3
- package/dist/CloudflareBindings.mjs +14 -2
- package/dist/CloudflareBindings.mjs.map +1 -1
- package/dist/CloudflareMemory.d.mts +1 -1
- package/dist/CloudflareMemory.mjs +16 -9
- package/dist/CloudflareMemory.mjs.map +1 -1
- package/dist/CloudflareScheduling.mjs +15 -8
- package/dist/CloudflareScheduling.mjs.map +1 -1
- package/dist/CloudflareSubscriptions.mjs +12 -6
- package/dist/CloudflareSubscriptions.mjs.map +1 -1
- package/dist/CloudflareThreadClient.d.mts +256 -46
- package/dist/CloudflareThreadClient.mjs +11 -15
- package/dist/CloudflareThreadClient.mjs.map +1 -1
- package/dist/InteractiveBrowser.mjs +15 -15
- package/dist/InteractiveBrowser.mjs.map +1 -1
- package/dist/ProtectedBrowser.mjs +12 -12
- package/dist/ProtectedBrowser.mjs.map +1 -1
- package/dist/{ThreadObject-rVo6_oel.d.mts → ThreadObject-DZMkwIBh.d.mts} +29 -33
- package/dist/{ThreadObject-BpwkEc5E.mjs → ThreadObject-gyx8Qq03.mjs} +8 -9
- package/dist/ThreadObject-gyx8Qq03.mjs.map +1 -0
- package/dist/ThreadObject.d.mts +1 -1
- package/dist/ThreadObject.mjs +1 -1
- package/dist/WakeScheduler.mjs +7 -10
- package/dist/WakeScheduler.mjs.map +1 -1
- package/dist/{browser-session-lifecycle-CUbVfEgP.mjs → browser-session-lifecycle-CmbQABHC.mjs} +5 -5
- package/dist/browser-session-lifecycle-CmbQABHC.mjs.map +1 -0
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/src/Alarm.ts +6 -6
- package/src/BrowserRestCrawl.ts +1 -1
- package/src/CloudflareBindings.ts +20 -1
- package/src/CloudflareMemory.ts +25 -11
- package/src/CloudflareScheduling.ts +23 -9
- package/src/CloudflareSubscriptions.ts +18 -18
- package/src/CloudflareThreadClient.ts +14 -12
- package/src/InteractiveBrowser.ts +19 -22
- package/src/WakeScheduler.ts +12 -6
- package/src/internal/browser-session-lifecycle.ts +8 -8
- package/src/internal/message-delivery.ts +5 -6
- package/src/internal/transport.ts +8 -6
- package/src/protected-browser/binding.ts +1 -1
- package/src/protected-browser/policy.ts +29 -31
- package/dist/ThreadObject-BpwkEc5E.mjs.map +0 -1
- package/dist/browser-session-lifecycle-CUbVfEgP.mjs.map +0 -1
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
2
|
import { Principal } from "@effect-agent/thread/SubmissionLedger";
|
|
3
3
|
import { Clock, Context, Effect, Layer, Schema } from "effect";
|
|
4
|
+
import { DurableObject, DurableObjectState, RpcTargets } from "effect-cf";
|
|
4
5
|
import * as Memory from "@effect-agent/core/Memory";
|
|
5
6
|
import * as MemoryNamespace from "@effect-agent/core/MemoryNamespace";
|
|
6
7
|
import { MemoryNamespaceAddress } from "@effect-agent/core/MemoryNamespace";
|
|
@@ -11,7 +12,6 @@ import "@effect-agent/core/SemanticMemoryIndex";
|
|
|
11
12
|
import "@effect-agent/core/SemanticMemoryRevalidation";
|
|
12
13
|
import { defaultDoMemoryStorageLimits, doMemoryStoreLayerWithFailpoints } from "@effect-agent/storage-cloudflare/DoMemoryStore";
|
|
13
14
|
import { MemoryOwnerIdentity, MemoryOwnerRequest, MemoryOwnerResponse, MemoryRpcError, MemoryRpcLimits, decodeMemoryWire, defaultMemoryRpcLimits, encodeMemoryWire, handleMemoryOwnerRequest } from "@effect-agent/storage-cloudflare/MemoryProtocol";
|
|
14
|
-
import { DurableObject, DurableObjectState } from "effect-cf";
|
|
15
15
|
//#region src/CloudflareMemory.ts
|
|
16
16
|
var CloudflareMemory_exports = /* @__PURE__ */ __exportAll({
|
|
17
17
|
CloudflareMemoryClient: () => CloudflareMemoryClient,
|
|
@@ -30,17 +30,24 @@ const memoryObjectName = (namespace) => namespace.address;
|
|
|
30
30
|
* may have committed: reconcile by sending the identical operation ID and command.
|
|
31
31
|
*/
|
|
32
32
|
const makeMemoryClient = Effect.fn("CloudflareMemoryClient.make")(function* (access, principal, rpcLimits = defaultMemoryRpcLimits) {
|
|
33
|
-
const validated = yield* Schema.
|
|
33
|
+
const validated = yield* Schema.decodeEffect(MemoryRpcLimits)(rpcLimits).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
|
|
34
34
|
const bound = yield* Schema.decodeUnknownEffect(MemoryAccess.Wire)(access).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
|
|
35
|
-
principal = yield* Schema.
|
|
35
|
+
principal = yield* Schema.decodeEffect(Principal)(principal).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
|
|
36
36
|
const { namespace } = yield* MemoryObjectNamespace;
|
|
37
37
|
const call = Effect.fn("CloudflareMemoryClient.call")(function* (request) {
|
|
38
|
-
const decoded = yield* Schema.
|
|
38
|
+
const decoded = yield* Schema.decodeEffect(MemoryOwnerRequest)(request).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
|
|
39
39
|
const encoded = yield* encodeMemoryWire(MemoryOwnerRequest, decoded, validated.maxRequestBytes);
|
|
40
|
+
const unavailable = (cause) => {
|
|
41
|
+
const error = MemoryRpcError.make({ reason: "unavailable" });
|
|
42
|
+
error.cause = cause;
|
|
43
|
+
return error;
|
|
44
|
+
};
|
|
45
|
+
const address = memoryObjectName(bound.namespace);
|
|
46
|
+
const target = yield* RpcTargets.get(namespace, address, () => namespace.get(namespace.idFromName(address))).pipe(Effect.mapError(unavailable));
|
|
40
47
|
const raw = yield* Effect.tryPromise({
|
|
41
|
-
try: () =>
|
|
42
|
-
catch:
|
|
43
|
-
});
|
|
48
|
+
try: () => target.memory(encoded),
|
|
49
|
+
catch: unavailable
|
|
50
|
+
}).pipe(Effect.tapCause(() => RpcTargets.invalidate(target)));
|
|
44
51
|
const response = yield* decodeMemoryWire(MemoryOwnerResponse, raw, validated.maxResponseBytes);
|
|
45
52
|
if (response._tag === "Failed") return yield* response.failure;
|
|
46
53
|
if (!MemoryNamespace.equals(response.access.namespace, bound.namespace) || response.access.scope !== bound.scope) return yield* MemoryRpcError.make({ reason: "protocol" });
|
|
@@ -51,7 +58,7 @@ const makeMemoryClient = Effect.fn("CloudflareMemoryClient.make")(function* (acc
|
|
|
51
58
|
orElse: () => Effect.fail(MemoryRpcError.make({ reason: "timeout" }))
|
|
52
59
|
}));
|
|
53
60
|
const revalidate = Effect.fn("CloudflareMemoryClient.revalidate")(function* (lookup, limits) {
|
|
54
|
-
limits = yield* Schema.
|
|
61
|
+
limits = yield* Schema.decodeEffect(MemoryRecallLimits)(limits).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
|
|
55
62
|
const timeoutMillis = Math.min(validated.timeoutMillis, limits.timeoutMillis);
|
|
56
63
|
return yield* Effect.gen(function* () {
|
|
57
64
|
const response = yield* call({
|
|
@@ -181,7 +188,7 @@ const makeMemoryObject = (host, options = {}) => {
|
|
|
181
188
|
const runtime = Layer.effectContext(Effect.gen(function* () {
|
|
182
189
|
const state = yield* DurableObjectState.DurableObjectState;
|
|
183
190
|
const scope = yield* Effect.scope;
|
|
184
|
-
yield* Schema.
|
|
191
|
+
yield* Schema.decodeEffect(MemoryRpcLimits)(options.rpcLimits ?? defaultMemoryRpcLimits).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
|
|
185
192
|
return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope));
|
|
186
193
|
}));
|
|
187
194
|
return DurableObject.make(runtime, { rpc: { memory: (encoded) => handleMemoryOwnerRequest(encoded, options.rpcLimits) } });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CloudflareMemory.mjs","names":["EffectCfDurableObject"],"sources":["../src/CloudflareMemory.ts"],"sourcesContent":["import * as Memory from \"@effect-agent/core/Memory\";\nimport * as MemoryNamespace from \"@effect-agent/core/MemoryNamespace\";\nimport { MemoryNamespaceAddress } from \"@effect-agent/core/MemoryNamespace\";\nimport { type MemoryLookup, MemoryRecallLimits } from \"@effect-agent/core/MemoryReference\";\nimport { MemoryAccess } from \"@effect-agent/core/MemoryRevalidation\";\nimport {\n type MemoryReader,\n type MemoryWrite,\n MemoryKey,\n MemoryDocument,\n MemoryMutationFailpoint,\n MemoryStorageError,\n MemoryWriter,\n} from \"@effect-agent/core/MemoryStore\";\nimport {\n type MemoryIndexSearch,\n type SemanticMemoryProfile,\n} from \"@effect-agent/core/SemanticMemoryIndex\";\nimport { type SemanticCandidateLimits } from \"@effect-agent/core/SemanticMemoryRevalidation\";\nimport {\n type DoMemoryStorageLimits,\n defaultDoMemoryStorageLimits,\n doMemoryStoreLayerWithFailpoints,\n} from \"@effect-agent/storage-cloudflare/DoMemoryStore\";\nimport {\n type MemoryOwnerAuthorizer,\n decodeMemoryWire,\n defaultMemoryRpcLimits,\n encodeMemoryWire,\n handleMemoryOwnerRequest,\n MemoryOwnerIdentity,\n MemoryOwnerRequest,\n MemoryOwnerResponse,\n MemoryRpcError,\n MemoryRpcLimits,\n type MemoryOwnerFailure,\n} from \"@effect-agent/storage-cloudflare/MemoryProtocol\";\nimport { Principal } from \"@effect-agent/thread/SubmissionLedger\";\nimport { Clock, Context, Effect, Layer, Schema } from \"effect\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectState,\n type WorkerEnvironment,\n} from \"effect-cf\";\n\nexport interface MemoryObjectRpc extends Rpc.DurableObjectBranded {\n memory(encoded: string): Promise<string>;\n}\n\nexport class MemoryObjectNamespace extends Context.Service<\n MemoryObjectNamespace,\n {\n readonly namespace: DurableObjectNamespace<MemoryObjectRpc>;\n }\n>()(\"@effect-agent/platform-cloudflare/MemoryObjectNamespace\") {}\n\n/** Namespace version and identity are already canonicalized by MemoryNamespace. */\nexport const memoryObjectName = (namespace: MemoryNamespace.Any): string => namespace.address;\n\n/**\n * Effect-native, host-bound memory client. Recall revalidates the entire admitted lookup\n * in one RPC and renders it locally. No retries or per-source splitting occur here.\n * Interrupted callers stop waiting; the owner has its own deadline. A timed-out write\n * may have committed: reconcile by sending the identical operation ID and command.\n */\nconst makeMemoryClient = Effect.fn(\"CloudflareMemoryClient.make\")(function* <\n Namespace extends MemoryNamespace.Any,\n>(\n access: MemoryAccess<Namespace>,\n principal: Principal,\n rpcLimits: MemoryRpcLimits = defaultMemoryRpcLimits,\n) {\n const validated = yield* Schema.decodeUnknownEffect(MemoryRpcLimits)(rpcLimits).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n const bound = yield* Schema.decodeUnknownEffect(MemoryAccess.Wire)(access).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n principal = yield* Schema.decodeUnknownEffect(Principal)(principal).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n const { namespace } = yield* MemoryObjectNamespace;\n\n const call = Effect.fn(\"CloudflareMemoryClient.call\")(function* (request: MemoryOwnerRequest) {\n const decoded = yield* Schema.decodeUnknownEffect(MemoryOwnerRequest)(request).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n const encoded = yield* encodeMemoryWire(MemoryOwnerRequest, decoded, validated.maxRequestBytes);\n\n const raw = yield* Effect.tryPromise({\n try: () =>\n namespace.get(namespace.idFromName(memoryObjectName(bound.namespace))).memory(encoded),\n catch: () => MemoryRpcError.make({ reason: \"unavailable\" }),\n });\n\n const response = yield* decodeMemoryWire(MemoryOwnerResponse, raw, validated.maxResponseBytes);\n\n if (response._tag === \"Failed\") return yield* response.failure;\n if (\n !MemoryNamespace.equals(response.access.namespace, bound.namespace) ||\n response.access.scope !== bound.scope\n )\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return response;\n });\n\n const withinDeadline = <A, E, R>(effect: Effect.Effect<A, E, R>, timeoutMillis: number) =>\n effect.pipe(\n Effect.timeoutOrElse({\n duration: timeoutMillis,\n orElse: () => Effect.fail(MemoryRpcError.make({ reason: \"timeout\" })),\n }),\n );\n\n const revalidate = Effect.fn(\"CloudflareMemoryClient.revalidate\")(function* (\n lookup: MemoryLookup,\n limits: MemoryRecallLimits,\n ) {\n limits = yield* Schema.decodeUnknownEffect(MemoryRecallLimits)(limits).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n const timeoutMillis = Math.min(validated.timeoutMillis, limits.timeoutMillis);\n\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"Revalidate\",\n version: 1,\n access: bound,\n principal,\n lookup,\n limits,\n deadlineMillis: (yield* Clock.currentTimeMillis) + timeoutMillis,\n });\n\n if (response._tag !== \"Lookup\") return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return response.lookup;\n }).pipe((effect) => withinDeadline(effect, timeoutMillis));\n });\n\n const change = Effect.fn(\"CloudflareMemoryClient.change\")(function* (\n write: MemoryWrite<Namespace>,\n ) {\n if (!MemoryNamespace.equals(write.key.namespace, bound.namespace))\n return yield* MemoryRpcError.make({ reason: \"denied\" });\n\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"Change\",\n version: 1,\n access: bound,\n principal,\n write,\n deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,\n });\n\n if (response._tag !== \"Changed\" || response.document.key.id !== write.key.id)\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return yield* MemoryDocument.restore(access.namespace, response.document);\n }).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));\n });\n\n /**\n * Read one exact current document in one owner RPC. Null means absent; withdrawals return\n * tombstones. Denial, unavailable storage and deadlines fail typed, never become absence.\n * Reads begun after an acknowledged write observe it or a later revision. The owner checks\n * exact-key authority and active document scopes; source-dependent provenance policy remains\n * application-owned. No extraction, job draining, embedding, discovery or rendering occurs.\n */\n const get = Effect.fn(\"CloudflareMemoryClient.get\")(function* (key: MemoryKey<Namespace>) {\n const decodedKey = yield* Schema.decodeUnknownEffect(MemoryKey.Wire)(key).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n if (!MemoryNamespace.equals(decodedKey.namespace, bound.namespace))\n return yield* MemoryRpcError.make({ reason: \"denied\" });\n\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"Get\",\n version: 1,\n access: bound,\n principal,\n key: decodedKey,\n deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,\n });\n\n if (\n response._tag !== \"Document\" ||\n !MemoryNamespace.equals(response.key.namespace, bound.namespace) ||\n response.key.id !== decodedKey.id\n )\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n if (response.document === null) return null;\n if (\n response.document.key.id !== decodedKey.id ||\n response.document.source.id !== decodedKey.id ||\n (response.document._tag === \"ActiveMemoryDocument\" &&\n !response.document.scopes.includes(bound.scope))\n )\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n yield* encodeMemoryWire(MemoryDocument.Wire, response.document, validated.maxSourceBytes);\n\n return yield* MemoryDocument.restore(access.namespace, response.document);\n }).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));\n });\n\n const revalidateSemantic = Effect.fn(\"CloudflareMemoryClient.revalidateSemantic\")(function* (\n found: MemoryIndexSearch<Namespace>,\n profile: SemanticMemoryProfile,\n limits: SemanticCandidateLimits,\n ) {\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"RevalidateSemantic\",\n version: 1,\n access: bound,\n principal,\n found,\n profile,\n limits,\n deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,\n });\n\n if (response._tag !== \"Semantic\") return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return response.result;\n }).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));\n });\n\n /**\n * Revalidate in one owner RPC, then render whole passages within the caller's budget.\n * The bound source is essential: unavailable/stale results and matches that cannot fit\n * fail instead of silently producing empty context. No-match remains successful.\n * The single outcome has sourceId \"memory\". No embedding or candidate search is performed.\n * Use revalidate with Memory.recall for multiple readers sharing one output budget.\n */\n const recall = Effect.fn(\"CloudflareMemoryClient.recall\")(function* (\n lookup: MemoryLookup,\n limits: MemoryRecallLimits,\n estimateTokens?: (text: string) => number,\n ) {\n return yield* Memory.recall(\n [{ id: \"memory\", essential: true, read: revalidate(lookup, limits) }],\n limits,\n estimateTokens,\n );\n });\n\n return { get, recall, revalidate, revalidateSemantic, change };\n});\n\nexport const CloudflareMemoryClient = {\n /** Bind access and principal using the MemoryObjectNamespace supplied by the application. */\n make: makeMemoryClient,\n /** Use a resolved Worker or Durable Object binding without manual service provisioning. */\n fromBinding: Effect.fn(\"CloudflareMemoryClient.fromBinding\")(function* <\n Namespace extends MemoryNamespace.Any,\n >(\n binding: DurableObjectNamespace<MemoryObjectRpc>,\n options: {\n readonly access: MemoryAccess<Namespace>;\n readonly principal: Principal;\n readonly rpcLimits?: MemoryRpcLimits;\n },\n ) {\n return yield* makeMemoryClient(options.access, options.principal, options.rpcLimits).pipe(\n Effect.provideService(MemoryObjectNamespace, { namespace: binding }),\n );\n }),\n};\n\n/**\n * Optional activity-processor destination. Keeps domain write errors intact; transport,\n * authorization and deadline failures become the existing MemoryStorageError contract.\n * Receipts remain authoritative, including after caller interruption or lost replies.\n */\nexport const cloudflareMemoryWriterLayer = (\n access: MemoryAccess,\n principal: Principal,\n limits: MemoryRpcLimits = defaultMemoryRpcLimits,\n) =>\n Layer.effect(\n MemoryWriter,\n Effect.gen(function* () {\n const client = yield* CloudflareMemoryClient.make(access, principal, limits);\n\n return MemoryWriter.fromAdapter({\n change: (write) =>\n client.change(write).pipe(\n Effect.catchTag(\"MemoryRpcError\", (error) =>\n Effect.fail(\n MemoryStorageError.make({\n operation: `memory RPC ${error.reason}`,\n reason:\n error.reason === \"unavailable\" || error.reason === \"timeout\"\n ? \"unavailable\"\n : \"invalid-input\",\n }),\n ),\n ),\n Effect.catchTag([\"MemoryRecallError\", \"MemoryIndexError\", \"SemanticMemoryError\"], () =>\n Effect.fail(\n MemoryStorageError.make({ operation: \"memory RPC response\", reason: \"corrupt\" }),\n ),\n ),\n ),\n });\n }),\n );\n\ntype OwnerServices = MemoryReader | MemoryWriter | MemoryOwnerAuthorizer | MemoryOwnerIdentity;\n\nexport interface MemoryObjectInstance extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, OwnerServices>\n> {\n memory(encoded: string): Promise<string>;\n}\n\nexport interface MemoryObjectClass {\n new (ctx: globalThis.DurableObjectState, env: Cloudflare.Env): MemoryObjectInstance;\n}\n\n/**\n * Dedicated SQLite owner, independent of Thread lifetimes. The host binds authorization\n * after restoring its namespace definition from MemoryOwnerIdentity. Do not retain\n * cleanup-scoped resources in the host Layer; it lives for the DO incarnation.\n */\nconst makeMemoryObject = <E>(\n host: Layer.Layer<\n MemoryOwnerAuthorizer,\n E,\n MemoryOwnerIdentity | DurableObjectState.DurableObjectState | WorkerEnvironment\n >,\n options: {\n readonly storageLimits?: DoMemoryStorageLimits;\n readonly rpcLimits?: MemoryRpcLimits;\n readonly failpoints?: Layer.Layer<\n MemoryMutationFailpoint,\n never,\n DurableObjectState.DurableObjectState\n >;\n } = {},\n): MemoryObjectClass => {\n const identity = Layer.effect(\n MemoryOwnerIdentity,\n Effect.gen(function* () {\n const state = yield* DurableObjectState.DurableObjectState;\n\n const address = yield* Schema.decodeUnknownEffect(MemoryNamespaceAddress)(\n state.raw.id.name,\n ).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: \"denied\" })));\n\n return { namespace: MemoryNamespace.Any.make({ address }) };\n }),\n );\n\n const store = Layer.unwrap(\n Effect.map(DurableObjectState.DurableObjectState, (state) =>\n doMemoryStoreLayerWithFailpoints(\n state.raw.storage,\n options.storageLimits ?? defaultDoMemoryStorageLimits,\n ),\n ),\n ).pipe(Layer.provide(options.failpoints ?? MemoryMutationFailpoint.layer));\n\n const application = Layer.merge(store, host).pipe(Layer.provideMerge(identity));\n\n const runtime: Layer.Layer<\n OwnerServices,\n E | MemoryOwnerFailure,\n DurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* DurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n\n yield* Schema.decodeUnknownEffect(MemoryRpcLimits)(\n options.rpcLimits ?? defaultMemoryRpcLimits,\n ).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })));\n\n return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope));\n }),\n );\n\n const rpc = { memory: (encoded: string) => handleMemoryOwnerRequest(encoded, options.rpcLimits) };\n\n return EffectCfDurableObject.make<\n OwnerServices,\n E | MemoryOwnerFailure,\n never,\n never,\n typeof rpc\n >(runtime, { rpc });\n};\n\nexport const MemoryObject = {\n /** Build the SQLite Durable Object class with the application's owner authorization Layer. */\n make: makeMemoryObject,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,wBAAb,cAA2C,QAAQ,QAKjD,CAAC,CAAC,yDAAyD,CAAC,CAAC,CAAC;;AAGhE,MAAa,oBAAoB,cAA2C,UAAU;;;;;;;AAQtF,MAAM,mBAAmB,OAAO,GAAG,6BAA6B,CAAC,CAAC,WAGhE,QACA,WACA,YAA6B,wBAC7B;CACA,MAAM,YAAY,OAAO,OAAO,oBAAoB,eAAe,CAAC,CAAC,SAAS,CAAC,CAAC,KAC9E,OAAO,eAAe,eAAe,KAAK,EAAE,QAAQ,WAAW,CAAC,CAAC,CACnE;CAEA,MAAM,QAAQ,OAAO,OAAO,oBAAoB,aAAa,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,KACzE,OAAO,eAAe,eAAe,KAAK,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AW,MAAM,OACrB,qBACA,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO,mBAAmB;EAExC,MAAM,UAAU,OAAO,OAAO,oBAAoB,sBAAsB,CAAC,CACvE,MAAM,IAAI,GAAG,IACf,CAAC,CAAC,KAAK,OAAO,eAAe,eAAe,KAAK,EAAE,QAAQ,SAAS,CAAC,CAAC,CAAC;EAEvE,OAAO,EAAE,WAAW,gBAAgB,IAAI,KAAK,EAAE,QAAQ,CAAC,EAAE;CAC5D,CAAC,CACH;CAEA,MAAM,QAAQ,MAAM,OAClB,OAAO,IAAI,mBAAmB,qBAAqB,UACjD,iCACE,MAAM,IAAI,SACV,QAAQ,iBAAiB,4BAC3B,CACF,CACF,CAAC,CAAC,KAAK,MAAM,QAAQ,QAAQ,cAAc,wBAAwB,KAAK,CAAC;CAEzE,MAAM,cAAc,MAAM,MAAM,OAAO,IAAI,CAAC,CAAC,KAAK,MAAM,aAAa,QAAQ,CAAC;CAE9E,MAAM,UAIF,MAAM,cACR,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO,mBAAmB;EACxC,MAAM,QAAQ,OAAO,OAAO;EAE5B,OAAO,OAAO,oBAAoB,eAAe,CAAC,CAChD,QAAQ,aAAa,sBACvB,CAAC,CAAC,KAAK,OAAO,eAAe,eAAe,KAAK,EAAE,QAAQ,WAAW,CAAC,CAAC,CAAC;EAEzE,OAAO,OAAO,MAAM,sBAAsB,MAAM,eAAe,aAAa,KAAK,CAAC;CACpF,CAAC,CACH;CAIA,OAAOA,cAAsB,KAM3B,SAAS,EAAE,KAAA,EARC,SAAS,YAAoB,yBAAyB,SAAS,QAAQ,SAAS,EAQ/E,EAAE,CAAC;AACpB;AAEA,MAAa,eAAe;;AAE1B,MAAM,iBACR"}
|
|
1
|
+
{"version":3,"file":"CloudflareMemory.mjs","names":["EffectCfDurableObject"],"sources":["../src/CloudflareMemory.ts"],"sourcesContent":["import * as Memory from \"@effect-agent/core/Memory\";\nimport * as MemoryNamespace from \"@effect-agent/core/MemoryNamespace\";\nimport { MemoryNamespaceAddress } from \"@effect-agent/core/MemoryNamespace\";\nimport { type MemoryLookup, MemoryRecallLimits } from \"@effect-agent/core/MemoryReference\";\nimport { MemoryAccess } from \"@effect-agent/core/MemoryRevalidation\";\nimport {\n type MemoryReader,\n type MemoryWrite,\n MemoryKey,\n MemoryDocument,\n MemoryMutationFailpoint,\n MemoryStorageError,\n MemoryWriter,\n} from \"@effect-agent/core/MemoryStore\";\nimport {\n type MemoryIndexSearch,\n type SemanticMemoryProfile,\n} from \"@effect-agent/core/SemanticMemoryIndex\";\nimport { type SemanticCandidateLimits } from \"@effect-agent/core/SemanticMemoryRevalidation\";\nimport {\n type DoMemoryStorageLimits,\n defaultDoMemoryStorageLimits,\n doMemoryStoreLayerWithFailpoints,\n} from \"@effect-agent/storage-cloudflare/DoMemoryStore\";\nimport {\n type MemoryOwnerAuthorizer,\n decodeMemoryWire,\n defaultMemoryRpcLimits,\n encodeMemoryWire,\n handleMemoryOwnerRequest,\n MemoryOwnerIdentity,\n MemoryOwnerRequest,\n MemoryOwnerResponse,\n MemoryRpcError,\n MemoryRpcLimits,\n type MemoryOwnerFailure,\n} from \"@effect-agent/storage-cloudflare/MemoryProtocol\";\nimport { Principal } from \"@effect-agent/thread/SubmissionLedger\";\nimport { Clock, Context, Effect, Layer, Schema } from \"effect\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectState,\n RpcTargets,\n type WorkerEnvironment,\n} from \"effect-cf\";\n\nexport interface MemoryObjectRpc extends Rpc.DurableObjectBranded {\n memory(encoded: string): Promise<string>;\n}\n\nexport class MemoryObjectNamespace extends Context.Service<\n MemoryObjectNamespace,\n {\n readonly namespace: DurableObjectNamespace<MemoryObjectRpc>;\n }\n>()(\"@effect-agent/platform-cloudflare/MemoryObjectNamespace\") {}\n\n/** Namespace version and identity are already canonicalized by MemoryNamespace. */\nexport const memoryObjectName = (namespace: MemoryNamespace.Any): string => namespace.address;\n\n/**\n * Effect-native, host-bound memory client. Recall revalidates the entire admitted lookup\n * in one RPC and renders it locally. No retries or per-source splitting occur here.\n * Interrupted callers stop waiting; the owner has its own deadline. A timed-out write\n * may have committed: reconcile by sending the identical operation ID and command.\n */\nconst makeMemoryClient = Effect.fn(\"CloudflareMemoryClient.make\")(function* <\n Namespace extends MemoryNamespace.Any,\n>(\n access: MemoryAccess<Namespace>,\n principal: Principal,\n rpcLimits: MemoryRpcLimits = defaultMemoryRpcLimits,\n) {\n const validated = yield* Schema.decodeEffect(MemoryRpcLimits)(rpcLimits).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n const bound = yield* Schema.decodeUnknownEffect(MemoryAccess.Wire)(access).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n principal = yield* Schema.decodeEffect(Principal)(principal).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n const { namespace } = yield* MemoryObjectNamespace;\n\n const call = Effect.fn(\"CloudflareMemoryClient.call\")(function* (request: MemoryOwnerRequest) {\n const decoded = yield* Schema.decodeEffect(MemoryOwnerRequest)(request).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n const encoded = yield* encodeMemoryWire(MemoryOwnerRequest, decoded, validated.maxRequestBytes);\n\n const unavailable = (cause: unknown) => {\n const error = MemoryRpcError.make({ reason: \"unavailable\" });\n\n error.cause = cause;\n\n return error;\n };\n\n const address = memoryObjectName(bound.namespace);\n\n const target = yield* RpcTargets.get(namespace, address, () =>\n namespace.get(namespace.idFromName(address)),\n ).pipe(Effect.mapError(unavailable));\n\n const raw = yield* Effect.tryPromise({\n try: () => target.memory(encoded),\n catch: unavailable,\n }).pipe(Effect.tapCause(() => RpcTargets.invalidate(target)));\n\n const response = yield* decodeMemoryWire(MemoryOwnerResponse, raw, validated.maxResponseBytes);\n\n if (response._tag === \"Failed\") return yield* response.failure;\n if (\n !MemoryNamespace.equals(response.access.namespace, bound.namespace) ||\n response.access.scope !== bound.scope\n )\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return response;\n });\n\n const withinDeadline = <A, E, R>(effect: Effect.Effect<A, E, R>, timeoutMillis: number) =>\n effect.pipe(\n Effect.timeoutOrElse({\n duration: timeoutMillis,\n orElse: () => Effect.fail(MemoryRpcError.make({ reason: \"timeout\" })),\n }),\n );\n\n const revalidate = Effect.fn(\"CloudflareMemoryClient.revalidate\")(function* (\n lookup: MemoryLookup,\n limits: MemoryRecallLimits,\n ) {\n limits = yield* Schema.decodeEffect(MemoryRecallLimits)(limits).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n const timeoutMillis = Math.min(validated.timeoutMillis, limits.timeoutMillis);\n\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"Revalidate\",\n version: 1,\n access: bound,\n principal,\n lookup,\n limits,\n deadlineMillis: (yield* Clock.currentTimeMillis) + timeoutMillis,\n });\n\n if (response._tag !== \"Lookup\") return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return response.lookup;\n }).pipe((effect) => withinDeadline(effect, timeoutMillis));\n });\n\n const change = Effect.fn(\"CloudflareMemoryClient.change\")(function* (\n write: MemoryWrite<Namespace>,\n ) {\n if (!MemoryNamespace.equals(write.key.namespace, bound.namespace))\n return yield* MemoryRpcError.make({ reason: \"denied\" });\n\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"Change\",\n version: 1,\n access: bound,\n principal,\n write,\n deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,\n });\n\n if (response._tag !== \"Changed\" || response.document.key.id !== write.key.id)\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return yield* MemoryDocument.restore(access.namespace, response.document);\n }).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));\n });\n\n /**\n * Read one exact current document in one owner RPC. Null means absent; withdrawals return\n * tombstones. Denial, unavailable storage and deadlines fail typed, never become absence.\n * Reads begun after an acknowledged write observe it or a later revision. The owner checks\n * exact-key authority and active document scopes; source-dependent provenance policy remains\n * application-owned. No extraction, job draining, embedding, discovery or rendering occurs.\n */\n const get = Effect.fn(\"CloudflareMemoryClient.get\")(function* (key: MemoryKey<Namespace>) {\n const decodedKey = yield* Schema.decodeUnknownEffect(MemoryKey.Wire)(key).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n if (!MemoryNamespace.equals(decodedKey.namespace, bound.namespace))\n return yield* MemoryRpcError.make({ reason: \"denied\" });\n\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"Get\",\n version: 1,\n access: bound,\n principal,\n key: decodedKey,\n deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,\n });\n\n if (\n response._tag !== \"Document\" ||\n !MemoryNamespace.equals(response.key.namespace, bound.namespace) ||\n response.key.id !== decodedKey.id\n )\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n if (response.document === null) return null;\n if (\n response.document.key.id !== decodedKey.id ||\n response.document.source.id !== decodedKey.id ||\n (response.document._tag === \"ActiveMemoryDocument\" &&\n !response.document.scopes.includes(bound.scope))\n )\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n yield* encodeMemoryWire(MemoryDocument.Wire, response.document, validated.maxSourceBytes);\n\n return yield* MemoryDocument.restore(access.namespace, response.document);\n }).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));\n });\n\n const revalidateSemantic = Effect.fn(\"CloudflareMemoryClient.revalidateSemantic\")(function* (\n found: MemoryIndexSearch<Namespace>,\n profile: SemanticMemoryProfile,\n limits: SemanticCandidateLimits,\n ) {\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"RevalidateSemantic\",\n version: 1,\n access: bound,\n principal,\n found,\n profile,\n limits,\n deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,\n });\n\n if (response._tag !== \"Semantic\") return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return response.result;\n }).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));\n });\n\n /**\n * Revalidate in one owner RPC, then render whole passages within the caller's budget.\n * The bound source is essential: unavailable/stale results and matches that cannot fit\n * fail instead of silently producing empty context. No-match remains successful.\n * The single outcome has sourceId \"memory\". No embedding or candidate search is performed.\n * Use revalidate with Memory.recall for multiple readers sharing one output budget.\n */\n const recall = Effect.fn(\"CloudflareMemoryClient.recall\")(function* (\n lookup: MemoryLookup,\n limits: MemoryRecallLimits,\n estimateTokens?: (text: string) => number,\n ) {\n return yield* Memory.recall(\n [{ id: \"memory\", essential: true, read: revalidate(lookup, limits) }],\n limits,\n estimateTokens,\n );\n });\n\n return { get, recall, revalidate, revalidateSemantic, change };\n});\n\nexport const CloudflareMemoryClient = {\n /** Bind access and principal using the MemoryObjectNamespace supplied by the application. */\n make: makeMemoryClient,\n /** Use a resolved Worker or Durable Object binding without manual service provisioning. */\n fromBinding: Effect.fn(\"CloudflareMemoryClient.fromBinding\")(function* <\n Namespace extends MemoryNamespace.Any,\n >(\n binding: DurableObjectNamespace<MemoryObjectRpc>,\n options: {\n readonly access: MemoryAccess<Namespace>;\n readonly principal: Principal;\n readonly rpcLimits?: MemoryRpcLimits;\n },\n ) {\n return yield* makeMemoryClient(options.access, options.principal, options.rpcLimits).pipe(\n Effect.provideService(MemoryObjectNamespace, { namespace: binding }),\n );\n }),\n};\n\n/**\n * Optional activity-processor destination. Keeps domain write errors intact; transport,\n * authorization and deadline failures become the existing MemoryStorageError contract.\n * Receipts remain authoritative, including after caller interruption or lost replies.\n */\nexport const cloudflareMemoryWriterLayer = (\n access: MemoryAccess,\n principal: Principal,\n limits: MemoryRpcLimits = defaultMemoryRpcLimits,\n) =>\n Layer.effect(\n MemoryWriter,\n Effect.gen(function* () {\n const client = yield* CloudflareMemoryClient.make(access, principal, limits);\n\n return MemoryWriter.fromAdapter({\n change: (write) =>\n client.change(write).pipe(\n Effect.catchTag(\"MemoryRpcError\", (error) =>\n Effect.fail(\n MemoryStorageError.make({\n operation: `memory RPC ${error.reason}`,\n reason:\n error.reason === \"unavailable\" || error.reason === \"timeout\"\n ? \"unavailable\"\n : \"invalid-input\",\n }),\n ),\n ),\n Effect.catchTag([\"MemoryRecallError\", \"MemoryIndexError\", \"SemanticMemoryError\"], () =>\n Effect.fail(\n MemoryStorageError.make({ operation: \"memory RPC response\", reason: \"corrupt\" }),\n ),\n ),\n ),\n });\n }),\n );\n\ntype OwnerServices = MemoryReader | MemoryWriter | MemoryOwnerAuthorizer | MemoryOwnerIdentity;\n\nexport interface MemoryObjectInstance extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, OwnerServices>\n> {\n memory(encoded: string): Promise<string>;\n}\n\nexport interface MemoryObjectClass {\n new (ctx: globalThis.DurableObjectState, env: Cloudflare.Env): MemoryObjectInstance;\n}\n\n/**\n * Dedicated SQLite owner, independent of Thread lifetimes. The host binds authorization\n * after restoring its namespace definition from MemoryOwnerIdentity. Do not retain\n * cleanup-scoped resources in the host Layer; it lives for the DO incarnation.\n */\nconst makeMemoryObject = <E>(\n host: Layer.Layer<\n MemoryOwnerAuthorizer,\n E,\n MemoryOwnerIdentity | DurableObjectState.DurableObjectState | WorkerEnvironment\n >,\n options: {\n readonly storageLimits?: DoMemoryStorageLimits;\n readonly rpcLimits?: MemoryRpcLimits;\n readonly failpoints?: Layer.Layer<\n MemoryMutationFailpoint,\n never,\n DurableObjectState.DurableObjectState\n >;\n } = {},\n): MemoryObjectClass => {\n const identity = Layer.effect(\n MemoryOwnerIdentity,\n Effect.gen(function* () {\n const state = yield* DurableObjectState.DurableObjectState;\n\n const address = yield* Schema.decodeUnknownEffect(MemoryNamespaceAddress)(\n state.raw.id.name,\n ).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: \"denied\" })));\n\n return { namespace: MemoryNamespace.Any.make({ address }) };\n }),\n );\n\n const store = Layer.unwrap(\n Effect.map(DurableObjectState.DurableObjectState, (state) =>\n doMemoryStoreLayerWithFailpoints(\n state.raw.storage,\n options.storageLimits ?? defaultDoMemoryStorageLimits,\n ),\n ),\n ).pipe(Layer.provide(options.failpoints ?? MemoryMutationFailpoint.layer));\n\n const application = Layer.merge(store, host).pipe(Layer.provideMerge(identity));\n\n const runtime: Layer.Layer<\n OwnerServices,\n E | MemoryOwnerFailure,\n DurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* DurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n\n yield* Schema.decodeEffect(MemoryRpcLimits)(options.rpcLimits ?? defaultMemoryRpcLimits).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope));\n }),\n );\n\n const rpc = { memory: (encoded: string) => handleMemoryOwnerRequest(encoded, options.rpcLimits) };\n\n return EffectCfDurableObject.make<\n OwnerServices,\n E | MemoryOwnerFailure,\n never,\n never,\n typeof rpc\n >(runtime, { rpc });\n};\n\nexport const MemoryObject = {\n /** Build the SQLite Durable Object class with the application's owner authorization Layer. */\n make: makeMemoryObject,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkDA,IAAa,wBAAb,cAA2C,QAAQ,QAKjD,CAAC,CAAC,yDAAyD,CAAC,CAAC,CAAC;;AAGhE,MAAa,oBAAoB,cAA2C,UAAU;;;;;;;AAQtF,MAAM,mBAAmB,OAAO,GAAG,6BAA6B,CAAC,CAAC,WAGhE,QACA,WACA,YAA6B,wBAC7B;CACA,MAAM,YAAY,OAAO,OAAO,aAAa,eAAe,CAAC,CAAC,SAAS,CAAC,CAAC,KACvE,OAAO,eAAe,eAAe,KAAK,EAAE,QAAQ,WAAW,CAAC,CAAC,CACnE;CAEA,MAAM,QAAQ,OAAO,OAAO,oBAAoB,aAAa,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,KACzE,OAAO,eAAe,eAAe,KAAK,EAAE,QAAQ,WAA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yBAAyB,SAAS,QAAQ,SAAS,EAQ/E,EAAE,CAAC;AACpB;AAEA,MAAa,eAAe;;AAE1B,MAAM,iBACR"}
|
|
@@ -6,7 +6,7 @@ import "@effect-agent/thread/DurableAgentRuntime";
|
|
|
6
6
|
import { AdmissionFence } from "@effect-agent/thread/SubmissionLedger";
|
|
7
7
|
import { Clock, Context, DateTime, Effect, Layer, Schema } from "effect";
|
|
8
8
|
import { DefinitionDigests, PersistedJson } from "@effect-agent/thread/Records";
|
|
9
|
-
import { DurableObject, DurableObjectAlarm, DurableObjectState } from "effect-cf";
|
|
9
|
+
import { DurableObject, DurableObjectAlarm, DurableObjectState, RpcTargets } from "effect-cf";
|
|
10
10
|
import { DoScheduleAlarmControl, DoScheduleTransaction, scheduleStoreLayer } from "@effect-agent/storage-cloudflare/DoScheduleStore";
|
|
11
11
|
import { ScheduleAuthorizationError, ScheduleCapacityError, ScheduleConflict, ScheduleDestination, ScheduleFailpointError, ScheduleId, ScheduleNotFound, ScheduleOwner, ScheduleScope, ScheduleSnapshot, ScheduleSnapshotPage, ScheduleStorageError, ScheduleTimingRequest, ScheduleValidationError, defaultSchedulingLimits } from "@effect-agent/thread/Schedule";
|
|
12
12
|
import { scheduleOwnerKey } from "@effect-agent/thread/ScheduleTransition";
|
|
@@ -125,13 +125,20 @@ var CloudflareSchedulingClient = class {
|
|
|
125
125
|
operation: "Schedule Owner protocol",
|
|
126
126
|
reason: "corrupt"
|
|
127
127
|
})));
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
catch: () => ScheduleStorageError.make({
|
|
128
|
+
const unavailable = (cause) => {
|
|
129
|
+
const error = ScheduleStorageError.make({
|
|
131
130
|
operation: "call Schedule Owner",
|
|
132
131
|
reason: "unavailable"
|
|
133
|
-
})
|
|
134
|
-
|
|
132
|
+
});
|
|
133
|
+
error.cause = cause;
|
|
134
|
+
return error;
|
|
135
|
+
};
|
|
136
|
+
const address = scheduleOwnerKey(owner);
|
|
137
|
+
const target = yield* RpcTargets.get(namespace, address, () => namespace.get(namespace.idFromName(address))).pipe(Effect.mapError(unavailable));
|
|
138
|
+
const raw = yield* Effect.tryPromise({
|
|
139
|
+
try: () => target.schedule(encoded),
|
|
140
|
+
catch: unavailable
|
|
141
|
+
}).pipe(Effect.tapCause(() => RpcTargets.invalidate(target)));
|
|
135
142
|
const response = yield* decodeScheduleOwnerResponse(raw).pipe(Effect.mapError(() => ScheduleStorageError.make({
|
|
136
143
|
operation: "Schedule Owner protocol",
|
|
137
144
|
reason: "corrupt"
|
|
@@ -241,8 +248,8 @@ var CloudflareSchedulingClient = class {
|
|
|
241
248
|
var ScheduleOwnerIdentity = class extends Context.Service()("@effect-agent/platform-cloudflare/ScheduleOwnerIdentity") {};
|
|
242
249
|
const decodeOwnerName = Effect.fn("decodeScheduleOwnerName")(function* (name) {
|
|
243
250
|
if (name === null || name === void 0) return yield* ScheduleOwnerProtocolError.make({ message: "Schedule Owner objects require an idFromName identity" });
|
|
244
|
-
const tuple = yield* Schema.
|
|
245
|
-
return yield* Schema.
|
|
251
|
+
const tuple = yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String])))(name).pipe(Effect.mapError(() => ScheduleOwnerProtocolError.make({ message: "Schedule Owner object name is malformed" })));
|
|
252
|
+
return yield* Schema.decodeEffect(ScheduleOwner)({
|
|
246
253
|
tenantId: tuple[0],
|
|
247
254
|
ownerId: tuple[1]
|
|
248
255
|
}).pipe(Effect.mapError(() => ScheduleOwnerProtocolError.make({ message: "Schedule Owner object identity is invalid" })));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CloudflareScheduling.mjs","names":["ScheduleScopeSchema","ScheduleSnapshotPageSchema","EffectCfDurableObjectState","EffectCfDurableObject"],"sources":["../src/CloudflareScheduling.ts"],"sourcesContent":["import { AgentId } from \"@effect-agent/core/Identifiers\";\nimport {\n DoScheduleAlarmControl,\n DoScheduleTransaction,\n scheduleStoreLayer,\n} from \"@effect-agent/storage-cloudflare/DoScheduleStore\";\nimport { type DurableSubmitAgent } from \"@effect-agent/thread/DurableAgentRuntime\";\nimport { DefinitionDigests, PersistedJson } from \"@effect-agent/thread/Records\";\nimport {\n ScheduleAuthorizationError,\n type ScheduleAuthorizer,\n ScheduleCapacityError,\n ScheduleConflict,\n ScheduleDestination,\n ScheduleFailpointError,\n ScheduleId,\n type SchedulingLimits,\n ScheduleNotFound,\n ScheduleOwner,\n type ScheduleScope,\n ScheduleScope as ScheduleScopeSchema,\n ScheduleSnapshot,\n ScheduleSnapshotPage as ScheduleSnapshotPageSchema,\n ScheduleStorageError,\n ScheduleTimingRequest,\n ScheduleValidationError,\n defaultSchedulingLimits,\n} from \"@effect-agent/thread/Schedule\";\nimport { scheduleOwnerKey } from \"@effect-agent/thread/ScheduleTransition\";\nimport {\n Scheduling,\n ScheduleDriver,\n type ScheduleManagementFailure,\n ScheduleWakeNoop,\n} from \"@effect-agent/thread/Scheduling\";\nimport { AdmissionFence } from \"@effect-agent/thread/SubmissionLedger\";\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport { Clock, Context, DateTime, Effect, Layer, Schema } from \"effect\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectAlarm,\n DurableObjectState as EffectCfDurableObjectState,\n type WorkerEnvironment,\n} from \"effect-cf\";\n\nimport type { ThreadObjectNamespace } from \"./CloudflareBindings.ts\";\nimport { CloudflareThreadClient } from \"./CloudflareThreadClient.ts\";\nimport {\n cloudflarePreparedInputAdmissionLayer,\n cloudflareScheduledInputAdmissionLayer,\n} from \"./internal/prepared-admission.ts\";\n\nconst SCHEDULE_ALARM_TAG = \"effect-agent/ScheduleOwnerWake\";\nconst SCHEDULE_ALARM_ID = \"driver\";\n\nconst ScheduleAlarmPayload = Schema.Struct({\n schemaVersion: Schema.Literal(1),\n generation: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nexport class ScheduleAlarmProtocolError extends Schema.TaggedError<ScheduleAlarmProtocolError>()(\n \"ScheduleAlarmProtocolError\",\n { message: Schema.String },\n) {}\n\nconst boundedProtocolMessage = (message: string): string =>\n message.length <= 4_096 ? message : `${message.slice(0, 4_093)}...`;\n\nexport class ScheduleOwnerProtocolError extends Schema.TaggedError<ScheduleOwnerProtocolError>()(\n \"ScheduleOwnerProtocolError\",\n { message: Schema.String.check(Schema.isMaxLength(4_096)) },\n) {}\n\nconst ScheduleMutationRequestFields = {\n schemaVersion: Schema.Literal(1),\n agentId: AgentId,\n input: PersistedJson,\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n timing: ScheduleTimingRequest,\n destination: ScheduleDestination,\n deliveryPrincipal: ScheduleScopeSchema.fields.principal,\n definitions: DefinitionDigests,\n admissionGroup: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(256))),\n admissionFence: Schema.optionalKey(AdmissionFence),\n};\n\nconst ScheduleCreateRequest = Schema.TaggedStruct(\"Create\", ScheduleMutationRequestFields);\n\nconst ScheduleUpdateRequest = Schema.TaggedStruct(\"Update\", {\n ...ScheduleMutationRequestFields,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nconst ScheduleGetRequest = Schema.TaggedStruct(\"Get\", {\n schemaVersion: Schema.Literal(1),\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n});\n\nconst ScheduleListRequest = Schema.TaggedStruct(\"List\", {\n schemaVersion: Schema.Literal(1),\n scope: ScheduleScopeSchema,\n after: Schema.optionalKey(ScheduleId),\n limit: Schema.optionalKey(\n Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),\n ),\n});\n\nconst ScheduleControlRequest = Schema.TaggedStruct(\"Control\", {\n schemaVersion: Schema.Literal(1),\n operation: Schema.Literals([\"pause\", \"resume\", \"cancel\"]),\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nconst ScheduleRecoverRequest = Schema.TaggedStruct(\"Recover\", {\n schemaVersion: Schema.Literal(1),\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n expectedGeneration: Schema.Natural,\n});\n\nconst ScheduleOwnerRequest = Schema.Union([\n ScheduleRecoverRequest,\n ScheduleCreateRequest,\n ScheduleUpdateRequest,\n ScheduleGetRequest,\n ScheduleListRequest,\n ScheduleControlRequest,\n]);\n\ntype ScheduleOwnerRequest = typeof ScheduleOwnerRequest.Type;\n\nconst ScheduleOwnerFailure = Schema.Union([\n ScheduleValidationError,\n ScheduleAuthorizationError,\n ScheduleConflict,\n ScheduleNotFound,\n ScheduleCapacityError,\n ScheduleStorageError,\n ScheduleFailpointError,\n ScheduleOwnerProtocolError,\n]);\n\ntype ScheduleOwnerFailure = typeof ScheduleOwnerFailure.Type;\n\nconst ScheduleOwnerResponse = Schema.Union([\n Schema.TaggedStruct(\"Snapshot\", { value: ScheduleSnapshot }),\n Schema.TaggedStruct(\"Page\", { value: ScheduleSnapshotPageSchema }),\n Schema.TaggedStruct(\"Failed\", { failure: ScheduleOwnerFailure }),\n]);\n\ntype ScheduleOwnerResponse = typeof ScheduleOwnerResponse.Type;\n\nconst decodeScheduleOwnerRequest = Schema.decodeUnknownEffect(ScheduleOwnerRequest);\nconst encodeScheduleOwnerRequest = Schema.encodeEffect(ScheduleOwnerRequest);\nconst decodeScheduleOwnerResponse = Schema.decodeUnknownEffect(ScheduleOwnerResponse);\nconst encodeScheduleOwnerResponse = Schema.encodeEffect(ScheduleOwnerResponse);\n\nconst scheduleProtocolFailure = (message: string): ScheduleOwnerResponse => ({\n _tag: \"Failed\",\n failure: ScheduleOwnerProtocolError.make({ message: boundedProtocolMessage(message) }),\n});\n\nexport interface ScheduleOwnerObjectRpc extends Rpc.DurableObjectBranded {\n schedule(encoded: unknown): Promise<unknown>;\n}\n\nexport class ScheduleOwnerNamespace extends Context.Service<\n ScheduleOwnerNamespace,\n { readonly namespace: DurableObjectNamespace<ScheduleOwnerObjectRpc> }\n>()(\"@effect-agent/platform-cloudflare/ScheduleOwnerNamespace\") {}\n\nconst passthroughAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({\n definition: { id: agentId, input: PersistedJson },\n});\n\nconst requestOwner = (request: ScheduleOwnerRequest): ScheduleOwner => request.scope.owner;\n\n/** Provides the same authorized management service as NodeScheduling.layer. */\nexport class CloudflareSchedulingClient {\n static readonly layer: Layer.Layer<Scheduling, never, ScheduleOwnerNamespace> = Layer.effect(\n Scheduling,\n Effect.gen(function* () {\n const { namespace } = yield* ScheduleOwnerNamespace;\n\n const call = Effect.fn(\"CloudflareSchedulingClient.call\")(function* (\n owner: ScheduleOwner,\n request: ScheduleOwnerRequest,\n ): Effect.fn.Return<ScheduleOwnerResponse, ScheduleManagementFailure> {\n const encoded = yield* encodeScheduleOwnerRequest(request).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" }),\n ),\n );\n\n const raw = yield* Effect.tryPromise({\n try: () => namespace.get(namespace.idFromName(scheduleOwnerKey(owner))).schedule(encoded),\n catch: () =>\n ScheduleStorageError.make({\n operation: \"call Schedule Owner\",\n reason: \"unavailable\",\n }),\n });\n\n const response = yield* decodeScheduleOwnerResponse(raw).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" }),\n ),\n );\n\n if (response._tag !== \"Failed\") return response;\n\n return yield* response.failure._tag === \"ScheduleOwnerProtocolError\"\n ? ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" })\n : response.failure;\n });\n\n const encodeInput = Effect.fn(\"CloudflareSchedulingClient.encodeInput\")(function* <\n InputSchema extends Schema.Top,\n >(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n ): Effect.fn.Return<PersistedJson, ScheduleValidationError, InputSchema[\"EncodingServices\"]> {\n const encoded = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Unable to encode Agent input\",\n }),\n ),\n );\n\n return yield* Schema.decodeUnknownEffect(PersistedJson)(encoded).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Agent input does not satisfy the canonical persistence bounds\",\n }),\n ),\n );\n });\n\n const create: Scheduling[\"Service\"][\"create\"] = (agent, input, options) =>\n Effect.gen(function* () {\n const payload = yield* encodeInput(agent, input);\n\n const response = yield* call(options.scope.owner, {\n _tag: \"Create\",\n schemaVersion: 1,\n agentId: agent.definition.id,\n input: payload,\n ...options,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const update: Scheduling[\"Service\"][\"update\"] = (agent, input, options) =>\n Effect.gen(function* () {\n const payload = yield* encodeInput(agent, input);\n\n const response = yield* call(options.scope.owner, {\n _tag: \"Update\",\n schemaVersion: 1,\n agentId: agent.definition.id,\n input: payload,\n ...options,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const get: Scheduling[\"Service\"][\"get\"] = (scope, scheduleId) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"Get\",\n schemaVersion: 1,\n scope,\n scheduleId,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const list: Scheduling[\"Service\"][\"list\"] = (scope, options = {}) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"List\",\n schemaVersion: 1,\n scope,\n ...(options.after === undefined ? {} : { after: options.after }),\n ...(options.limit === undefined ? {} : { limit: options.limit }),\n });\n\n return response._tag === \"Page\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const control = (\n operation: \"pause\" | \"resume\" | \"cancel\",\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"Control\",\n schemaVersion: 1,\n operation,\n scope,\n scheduleId,\n expectedRevision,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n return Scheduling.of({\n create,\n update,\n get,\n list,\n pause: (scope, id, revision) => control(\"pause\", scope, id, revision),\n resume: (scope, id, revision) => control(\"resume\", scope, id, revision),\n recover: (scope, scheduleId, expectedRevision, expectedGeneration) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"Recover\",\n schemaVersion: 1,\n scope,\n scheduleId,\n expectedRevision,\n expectedGeneration,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n }),\n cancel: (scope, id, revision) => control(\"cancel\", scope, id, revision),\n });\n }),\n );\n}\n\nexport class ScheduleOwnerIdentity extends Context.Service<\n ScheduleOwnerIdentity,\n { readonly owner: ScheduleOwner }\n>()(\"@effect-agent/platform-cloudflare/ScheduleOwnerIdentity\") {}\n\nconst decodeOwnerName = Effect.fn(\"decodeScheduleOwnerName\")(function* (\n name: string | null | undefined,\n): Effect.fn.Return<ScheduleOwner, ScheduleOwnerProtocolError> {\n if (name === null || name === undefined) {\n return yield* ScheduleOwnerProtocolError.make({\n message: \"Schedule Owner objects require an idFromName identity\",\n });\n }\n\n const tuple = yield* Schema.decodeUnknownEffect(\n Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String])),\n )(name).pipe(\n Effect.mapError(() =>\n ScheduleOwnerProtocolError.make({ message: \"Schedule Owner object name is malformed\" }),\n ),\n );\n\n return yield* Schema.decodeUnknownEffect(ScheduleOwner)({\n tenantId: tuple[0],\n ownerId: tuple[1],\n }).pipe(\n Effect.mapError(() =>\n ScheduleOwnerProtocolError.make({ message: \"Schedule Owner object identity is invalid\" }),\n ),\n );\n});\n\nconst alarmStorageError = (operation: string) => (error: { readonly _tag: string }) =>\n ScheduleStorageError.make({\n operation,\n reason: error._tag === \"StorageOperationError\" ? \"unavailable\" : \"corrupt\",\n });\n\nconst transactionLayer: Layer.Layer<\n DoScheduleTransaction,\n never,\n DurableObjectAlarm.DurableObjectAlarm\n> = Layer.effect(\n DoScheduleTransaction,\n Effect.gen(function* () {\n const alarms = yield* DurableObjectAlarm.DurableObjectAlarm;\n\n return DoScheduleTransaction.of({\n run: (body) =>\n Effect.gen(function* () {\n const nowMillis = yield* Clock.currentTimeMillis;\n\n return yield* alarms\n .transaction((transaction) =>\n body((replacement) =>\n replacement.deadlineAtMillis === null\n ? transaction\n .cancelAlarm({ id: SCHEDULE_ALARM_ID, tag: SCHEDULE_ALARM_TAG })\n .pipe(Effect.mapError(alarmStorageError(\"cancel Schedule Owner alarm\")))\n : Effect.fromOption(\n DateTime.make(Math.max(replacement.deadlineAtMillis, nowMillis + 1)),\n ).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({\n operation: \"validate Schedule Owner alarm deadline\",\n reason: \"corrupt\",\n }),\n ),\n Effect.flatMap((runAt) =>\n transaction\n .scheduleAlarm({\n id: SCHEDULE_ALARM_ID,\n tag: SCHEDULE_ALARM_TAG,\n runAt,\n payload: {\n schemaVersion: 1,\n generation: replacement.generation,\n },\n })\n .pipe(\n Effect.mapError(alarmStorageError(\"schedule Schedule Owner alarm\")),\n ),\n ),\n ),\n ),\n )\n .pipe(\n Effect.catchTag(\"StorageOperationError\", () =>\n ScheduleStorageError.make({\n operation: \"commit Schedule Owner transaction\",\n reason: \"unavailable\",\n }),\n ),\n );\n }),\n });\n }),\n);\n\ntype ScheduleRuntimeServices =\n | Scheduling\n | ScheduleDriver\n | DoScheduleAlarmControl\n | ScheduleOwnerIdentity\n | DurableObjectAlarm.DurableObjectAlarm;\n\nconst ensureOwner = (\n expected: ScheduleOwner,\n request: ScheduleOwnerRequest,\n): Effect.Effect<void, ScheduleOwnerProtocolError> => {\n const observed = requestOwner(request);\n\n return observed.tenantId === expected.tenantId && observed.ownerId === expected.ownerId\n ? Effect.void\n : Effect.fail(\n ScheduleOwnerProtocolError.make({\n message: \"The request owner does not match the addressed Schedule Owner object\",\n }),\n );\n};\n\nconst handleScheduleRequest = Effect.fn(\"ScheduleOwner.handleRequest\")(function* (\n encoded: unknown,\n): Effect.fn.Return<unknown, never, Scheduling | ScheduleOwnerIdentity> {\n const decoded = yield* decodeScheduleOwnerRequest(encoded).pipe(Effect.result);\n\n if (decoded._tag === \"Failure\") {\n return yield* encodeScheduleOwnerResponse(\n scheduleProtocolFailure(\"The Schedule request could not be decoded\"),\n ).pipe(Effect.orDie);\n }\n const request = decoded.success;\n const { owner } = yield* ScheduleOwnerIdentity;\n const scheduling = yield* Scheduling;\n\n const response = yield* Effect.gen(function* () {\n yield* ensureOwner(owner, request);\n switch (request._tag) {\n case \"Create\": {\n const value = yield* scheduling.create(passthroughAgent(request.agentId), request.input, {\n scope: request.scope,\n scheduleId: request.scheduleId,\n timing: request.timing,\n destination: request.destination,\n deliveryPrincipal: request.deliveryPrincipal,\n definitions: request.definitions,\n ...(request.admissionGroup === undefined\n ? {}\n : { admissionGroup: request.admissionGroup }),\n ...(request.admissionFence === undefined\n ? {}\n : { admissionFence: request.admissionFence }),\n });\n\n return { _tag: \"Snapshot\" as const, value };\n }\n case \"Update\": {\n const value = yield* scheduling.update(passthroughAgent(request.agentId), request.input, {\n scope: request.scope,\n scheduleId: request.scheduleId,\n timing: request.timing,\n destination: request.destination,\n deliveryPrincipal: request.deliveryPrincipal,\n definitions: request.definitions,\n ...(request.admissionGroup === undefined\n ? {}\n : { admissionGroup: request.admissionGroup }),\n ...(request.admissionFence === undefined\n ? {}\n : { admissionFence: request.admissionFence }),\n expectedRevision: request.expectedRevision,\n });\n\n return { _tag: \"Snapshot\" as const, value };\n }\n case \"Get\":\n return {\n _tag: \"Snapshot\" as const,\n value: yield* scheduling.get(request.scope, request.scheduleId),\n };\n case \"List\":\n return {\n _tag: \"Page\" as const,\n value: yield* scheduling.list(request.scope, {\n ...(request.after === undefined ? {} : { after: request.after }),\n ...(request.limit === undefined ? {} : { limit: request.limit }),\n }),\n };\n case \"Recover\":\n return {\n _tag: \"Snapshot\" as const,\n value: yield* scheduling.recover(\n request.scope,\n request.scheduleId,\n request.expectedRevision,\n request.expectedGeneration,\n ),\n };\n case \"Control\": {\n const value =\n request.operation === \"pause\"\n ? yield* scheduling.pause(request.scope, request.scheduleId, request.expectedRevision)\n : request.operation === \"resume\"\n ? yield* scheduling.resume(\n request.scope,\n request.scheduleId,\n request.expectedRevision,\n )\n : yield* scheduling.cancel(\n request.scope,\n request.scheduleId,\n request.expectedRevision,\n );\n\n return { _tag: \"Snapshot\" as const, value };\n }\n }\n }).pipe(\n Effect.map((value): ScheduleOwnerResponse => value),\n Effect.catch((failure) =>\n Schema.is(ScheduleOwnerFailure)(failure)\n ? Effect.succeed({ _tag: \"Failed\" as const, failure })\n : Effect.succeed(\n scheduleProtocolFailure(\"The Schedule operation failed outside its public contract\"),\n ),\n ),\n );\n\n return yield* encodeScheduleOwnerResponse(response).pipe(Effect.orDie);\n});\n\n/** @internal The complete native alarm operation, including its event deadline. */\nexport const scheduleAlarmHandler = (limits: SchedulingLimits) =>\n DurableObjectAlarm.processDue(\n (event) =>\n Effect.gen(function* () {\n if (event.tag !== SCHEDULE_ALARM_TAG || event.id !== SCHEDULE_ALARM_ID) {\n return yield* ScheduleAlarmProtocolError.make({\n message: `Unsupported Schedule Owner alarm ${event.tag}/${event.id}`,\n });\n }\n yield* Schema.decodeUnknownEffect(ScheduleAlarmPayload)(event.payload).pipe(\n Effect.mapError(() =>\n ScheduleAlarmProtocolError.make({\n message: \"Unsupported Schedule Owner alarm payload version\",\n }),\n ),\n );\n const scheduling = yield* ScheduleDriver;\n const alarmControl = yield* DoScheduleAlarmControl;\n const { owner } = yield* ScheduleOwnerIdentity;\n const nowMillis = yield* Clock.currentTimeMillis;\n\n yield* alarmControl.prearm(nowMillis + limits.recoveryPollMillis);\n const pass = yield* scheduling.runDue(owner);\n\n if (pass.failed > 0) {\n yield* alarmControl.prearm((yield* Clock.currentTimeMillis) + limits.recoveryPollMillis);\n } else {\n yield* alarmControl.reconcile;\n }\n }),\n { mode: \"ordered\" },\n ).pipe(\n // Bound due acquisition and acknowledgement as well as admission. Prepared occurrences\n // and their replacement alarm survive interruption and retain their idempotency keys.\n Effect.timeout(\"14 minutes\"),\n Effect.asVoid,\n );\n\nexport interface ScheduleOwnerObjectInstance extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, ScheduleRuntimeServices>\n> {\n schedule(encoded: unknown): Promise<unknown>;\n alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void;\n}\n\nexport interface ScheduleOwnerObjectClass {\n new (ctx: DurableObjectState, env: Cloudflare.Env): ScheduleOwnerObjectInstance;\n}\n\n/**\n * The host Layer supplies authorization and routing and is cached for the object incarnation.\n * Cloudflare eviction does not guarantee its finalizers run. Do not acquire resources requiring\n * cleanup in this Layer; acquire them inside scoped `manage` / `prepare` operations instead.\n * Native services belong to effect-cf; the database and alarm runtime remain instance-owned.\n */\nexport const makeScheduleOwnerObjectClass = <E>(\n host: Layer.Layer<\n ScheduleAuthorizer | ThreadObjectNamespace,\n E,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment | ScheduleOwnerIdentity\n >,\n limits: SchedulingLimits = defaultSchedulingLimits,\n): ScheduleOwnerObjectClass => {\n const ownerLayer = Layer.effect(\n ScheduleOwnerIdentity,\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n\n return ScheduleOwnerIdentity.of({ owner: yield* decodeOwnerName(state.raw.id.name) });\n }),\n );\n\n const sqlLayer = Layer.unwrap(\n Effect.map(EffectCfDurableObjectState.DurableObjectState, (state) =>\n SqliteClient.layer({ storage: state.raw.storage }),\n ),\n );\n\n const application = Layer.merge(Scheduling.layer(limits), ScheduleDriver.layer(limits)).pipe(\n Layer.provideMerge(\n scheduleStoreLayer.pipe(Layer.provide(transactionLayer), Layer.provide(sqlLayer)),\n ),\n Layer.provide(\n cloudflareScheduledInputAdmissionLayer.pipe(\n Layer.provide(cloudflarePreparedInputAdmissionLayer),\n Layer.provide(CloudflareThreadClient.layer),\n ),\n ),\n Layer.provide(ScheduleWakeNoop),\n Layer.provide(BrowserCrypto.layer),\n Layer.provideMerge(DurableObjectAlarm.DurableObjectAlarm.layer),\n Layer.provide(host),\n Layer.provideMerge(ownerLayer),\n );\n\n const runtime: Layer.Layer<\n ScheduleRuntimeServices,\n E | ScheduleStorageError | ScheduleOwnerProtocolError | ScheduleValidationError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n\n return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope));\n }),\n );\n\n const rpc = {\n schedule: (encoded: unknown) => handleScheduleRequest(encoded),\n } satisfies EffectCfDurableObject.DurableObjectRpc<ScheduleRuntimeServices>;\n\n const Base = EffectCfDurableObject.make(runtime, {\n initialize: Effect.void,\n rpc,\n alarms: scheduleAlarmHandler(limits),\n });\n\n class ScheduleOwnerObject extends Base {\n override alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void {\n return super.alarm?.(alarmInfo);\n }\n }\n\n return ScheduleOwnerObject;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAE1B,MAAM,uBAAuB,OAAO,OAAO;CACzC,eAAe,OAAO,QAAQ,CAAC;CAC/B,YAAY,OA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D,MAAM,QAAQ,uBAAuB,KAAK,CAC5C,CACF,GACA,MAAM,QAAQ,gBAAgB,GAC9B,MAAM,QAAQ,cAAc,KAAK,GACjC,MAAM,aAAa,mBAAmB,mBAAmB,KAAK,GAC9D,MAAM,QAAQ,IAAI,GAClB,MAAM,aAAa,UAAU,CAC/B;CAEA,MAAM,UAIF,MAAM,cACR,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAOA,mBAA2B;EAChD,MAAM,QAAQ,OAAO,OAAO;EAE5B,OAAO,OAAO,MAAM,sBAAsB,MAAM,eAAe,aAAa,KAAK,CAAC;CACpF,CAAC,CACH;CAMA,MAAM,OAAOC,cAAsB,KAAK,SAAS;EAC/C,YAAY,OAAO;EACnB,KAAA,EALA,WAAW,YAAqB,sBAAsB,OAAO,EAK3D;EACF,QAAQ,qBAAqB,MAAM;CACrC,CAAC;CAED,MAAM,4BAA4B,KAAK;EACrC,MAAe,WAAuD;GACpE,OAAO,MAAM,QAAQ,SAAS;EAChC;CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"CloudflareScheduling.mjs","names":["ScheduleScopeSchema","ScheduleSnapshotPageSchema","EffectCfDurableObjectState","EffectCfDurableObject"],"sources":["../src/CloudflareScheduling.ts"],"sourcesContent":["import { AgentId } from \"@effect-agent/core/Identifiers\";\nimport {\n DoScheduleAlarmControl,\n DoScheduleTransaction,\n scheduleStoreLayer,\n} from \"@effect-agent/storage-cloudflare/DoScheduleStore\";\nimport { type DurableSubmitAgent } from \"@effect-agent/thread/DurableAgentRuntime\";\nimport { DefinitionDigests, PersistedJson } from \"@effect-agent/thread/Records\";\nimport {\n ScheduleAuthorizationError,\n type ScheduleAuthorizer,\n ScheduleCapacityError,\n ScheduleConflict,\n ScheduleDestination,\n ScheduleFailpointError,\n ScheduleId,\n type SchedulingLimits,\n ScheduleNotFound,\n ScheduleOwner,\n type ScheduleScope,\n ScheduleScope as ScheduleScopeSchema,\n ScheduleSnapshot,\n ScheduleSnapshotPage as ScheduleSnapshotPageSchema,\n ScheduleStorageError,\n ScheduleTimingRequest,\n ScheduleValidationError,\n defaultSchedulingLimits,\n} from \"@effect-agent/thread/Schedule\";\nimport { scheduleOwnerKey } from \"@effect-agent/thread/ScheduleTransition\";\nimport {\n Scheduling,\n ScheduleDriver,\n type ScheduleManagementFailure,\n ScheduleWakeNoop,\n} from \"@effect-agent/thread/Scheduling\";\nimport { AdmissionFence } from \"@effect-agent/thread/SubmissionLedger\";\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport { Clock, Context, DateTime, Effect, Layer, Schema } from \"effect\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectAlarm,\n RpcTargets,\n DurableObjectState as EffectCfDurableObjectState,\n type WorkerEnvironment,\n} from \"effect-cf\";\n\nimport type { ThreadObjectNamespace } from \"./CloudflareBindings.ts\";\nimport { CloudflareThreadClient } from \"./CloudflareThreadClient.ts\";\nimport {\n cloudflarePreparedInputAdmissionLayer,\n cloudflareScheduledInputAdmissionLayer,\n} from \"./internal/prepared-admission.ts\";\n\nconst SCHEDULE_ALARM_TAG = \"effect-agent/ScheduleOwnerWake\";\nconst SCHEDULE_ALARM_ID = \"driver\";\n\nconst ScheduleAlarmPayload = Schema.Struct({\n schemaVersion: Schema.Literal(1),\n generation: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nexport class ScheduleAlarmProtocolError extends Schema.TaggedError<ScheduleAlarmProtocolError>()(\n \"ScheduleAlarmProtocolError\",\n { message: Schema.String },\n) {}\n\nconst boundedProtocolMessage = (message: string): string =>\n message.length <= 4_096 ? message : `${message.slice(0, 4_093)}...`;\n\nexport class ScheduleOwnerProtocolError extends Schema.TaggedError<ScheduleOwnerProtocolError>()(\n \"ScheduleOwnerProtocolError\",\n { message: Schema.String.check(Schema.isMaxLength(4_096)) },\n) {}\n\nconst ScheduleMutationRequestFields = {\n schemaVersion: Schema.Literal(1),\n agentId: AgentId,\n input: PersistedJson,\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n timing: ScheduleTimingRequest,\n destination: ScheduleDestination,\n deliveryPrincipal: ScheduleScopeSchema.fields.principal,\n definitions: DefinitionDigests,\n admissionGroup: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(256))),\n admissionFence: Schema.optionalKey(AdmissionFence),\n};\n\nconst ScheduleCreateRequest = Schema.TaggedStruct(\"Create\", ScheduleMutationRequestFields);\n\nconst ScheduleUpdateRequest = Schema.TaggedStruct(\"Update\", {\n ...ScheduleMutationRequestFields,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nconst ScheduleGetRequest = Schema.TaggedStruct(\"Get\", {\n schemaVersion: Schema.Literal(1),\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n});\n\nconst ScheduleListRequest = Schema.TaggedStruct(\"List\", {\n schemaVersion: Schema.Literal(1),\n scope: ScheduleScopeSchema,\n after: Schema.optionalKey(ScheduleId),\n limit: Schema.optionalKey(\n Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),\n ),\n});\n\nconst ScheduleControlRequest = Schema.TaggedStruct(\"Control\", {\n schemaVersion: Schema.Literal(1),\n operation: Schema.Literals([\"pause\", \"resume\", \"cancel\"]),\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nconst ScheduleRecoverRequest = Schema.TaggedStruct(\"Recover\", {\n schemaVersion: Schema.Literal(1),\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n expectedGeneration: Schema.Natural,\n});\n\nconst ScheduleOwnerRequest = Schema.Union([\n ScheduleRecoverRequest,\n ScheduleCreateRequest,\n ScheduleUpdateRequest,\n ScheduleGetRequest,\n ScheduleListRequest,\n ScheduleControlRequest,\n]);\n\ntype ScheduleOwnerRequest = typeof ScheduleOwnerRequest.Type;\n\nconst ScheduleOwnerFailure = Schema.Union([\n ScheduleValidationError,\n ScheduleAuthorizationError,\n ScheduleConflict,\n ScheduleNotFound,\n ScheduleCapacityError,\n ScheduleStorageError,\n ScheduleFailpointError,\n ScheduleOwnerProtocolError,\n]);\n\ntype ScheduleOwnerFailure = typeof ScheduleOwnerFailure.Type;\n\nconst ScheduleOwnerResponse = Schema.Union([\n Schema.TaggedStruct(\"Snapshot\", { value: ScheduleSnapshot }),\n Schema.TaggedStruct(\"Page\", { value: ScheduleSnapshotPageSchema }),\n Schema.TaggedStruct(\"Failed\", { failure: ScheduleOwnerFailure }),\n]);\n\ntype ScheduleOwnerResponse = typeof ScheduleOwnerResponse.Type;\n\nconst decodeScheduleOwnerRequest = Schema.decodeUnknownEffect(ScheduleOwnerRequest);\nconst encodeScheduleOwnerRequest = Schema.encodeEffect(ScheduleOwnerRequest);\nconst decodeScheduleOwnerResponse = Schema.decodeUnknownEffect(ScheduleOwnerResponse);\nconst encodeScheduleOwnerResponse = Schema.encodeEffect(ScheduleOwnerResponse);\n\nconst scheduleProtocolFailure = (message: string): ScheduleOwnerResponse => ({\n _tag: \"Failed\",\n failure: ScheduleOwnerProtocolError.make({ message: boundedProtocolMessage(message) }),\n});\n\nexport interface ScheduleOwnerObjectRpc extends Rpc.DurableObjectBranded {\n schedule(encoded: unknown): Promise<unknown>;\n}\n\nexport class ScheduleOwnerNamespace extends Context.Service<\n ScheduleOwnerNamespace,\n { readonly namespace: DurableObjectNamespace<ScheduleOwnerObjectRpc> }\n>()(\"@effect-agent/platform-cloudflare/ScheduleOwnerNamespace\") {}\n\nconst passthroughAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({\n definition: { id: agentId, input: PersistedJson },\n});\n\nconst requestOwner = (request: ScheduleOwnerRequest): ScheduleOwner => request.scope.owner;\n\n/** Provides the same authorized management service as NodeScheduling.layer. */\nexport class CloudflareSchedulingClient {\n static readonly layer: Layer.Layer<Scheduling, never, ScheduleOwnerNamespace> = Layer.effect(\n Scheduling,\n Effect.gen(function* () {\n const { namespace } = yield* ScheduleOwnerNamespace;\n\n const call = Effect.fn(\"CloudflareSchedulingClient.call\")(function* (\n owner: ScheduleOwner,\n request: ScheduleOwnerRequest,\n ): Effect.fn.Return<ScheduleOwnerResponse, ScheduleManagementFailure> {\n const encoded = yield* encodeScheduleOwnerRequest(request).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" }),\n ),\n );\n\n const unavailable = (cause: unknown) => {\n const error = ScheduleStorageError.make({\n operation: \"call Schedule Owner\",\n reason: \"unavailable\",\n });\n\n error.cause = cause;\n\n return error;\n };\n\n const address = scheduleOwnerKey(owner);\n\n const target = yield* RpcTargets.get(namespace, address, () =>\n namespace.get(namespace.idFromName(address)),\n ).pipe(Effect.mapError(unavailable));\n\n const raw = yield* Effect.tryPromise({\n try: () => target.schedule(encoded),\n catch: unavailable,\n }).pipe(Effect.tapCause(() => RpcTargets.invalidate(target)));\n\n const response = yield* decodeScheduleOwnerResponse(raw).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" }),\n ),\n );\n\n if (response._tag !== \"Failed\") return response;\n\n return yield* response.failure._tag === \"ScheduleOwnerProtocolError\"\n ? ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" })\n : response.failure;\n });\n\n const encodeInput = Effect.fn(\"CloudflareSchedulingClient.encodeInput\")(function* <\n InputSchema extends Schema.Top,\n >(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n ): Effect.fn.Return<PersistedJson, ScheduleValidationError, InputSchema[\"EncodingServices\"]> {\n const encoded = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Unable to encode Agent input\",\n }),\n ),\n );\n\n return yield* Schema.decodeUnknownEffect(PersistedJson)(encoded).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Agent input does not satisfy the canonical persistence bounds\",\n }),\n ),\n );\n });\n\n const create: Scheduling[\"Service\"][\"create\"] = (agent, input, options) =>\n Effect.gen(function* () {\n const payload = yield* encodeInput(agent, input);\n\n const response = yield* call(options.scope.owner, {\n _tag: \"Create\",\n schemaVersion: 1,\n agentId: agent.definition.id,\n input: payload,\n ...options,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const update: Scheduling[\"Service\"][\"update\"] = (agent, input, options) =>\n Effect.gen(function* () {\n const payload = yield* encodeInput(agent, input);\n\n const response = yield* call(options.scope.owner, {\n _tag: \"Update\",\n schemaVersion: 1,\n agentId: agent.definition.id,\n input: payload,\n ...options,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const get: Scheduling[\"Service\"][\"get\"] = (scope, scheduleId) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"Get\",\n schemaVersion: 1,\n scope,\n scheduleId,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const list: Scheduling[\"Service\"][\"list\"] = (scope, options = {}) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"List\",\n schemaVersion: 1,\n scope,\n ...(options.after === undefined ? {} : { after: options.after }),\n ...(options.limit === undefined ? {} : { limit: options.limit }),\n });\n\n return response._tag === \"Page\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const control = (\n operation: \"pause\" | \"resume\" | \"cancel\",\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"Control\",\n schemaVersion: 1,\n operation,\n scope,\n scheduleId,\n expectedRevision,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n return Scheduling.of({\n create,\n update,\n get,\n list,\n pause: (scope, id, revision) => control(\"pause\", scope, id, revision),\n resume: (scope, id, revision) => control(\"resume\", scope, id, revision),\n recover: (scope, scheduleId, expectedRevision, expectedGeneration) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"Recover\",\n schemaVersion: 1,\n scope,\n scheduleId,\n expectedRevision,\n expectedGeneration,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n }),\n cancel: (scope, id, revision) => control(\"cancel\", scope, id, revision),\n });\n }),\n );\n}\n\nexport class ScheduleOwnerIdentity extends Context.Service<\n ScheduleOwnerIdentity,\n { readonly owner: ScheduleOwner }\n>()(\"@effect-agent/platform-cloudflare/ScheduleOwnerIdentity\") {}\n\nconst decodeOwnerName = Effect.fn(\"decodeScheduleOwnerName\")(function* (\n name: string | null | undefined,\n): Effect.fn.Return<ScheduleOwner, ScheduleOwnerProtocolError> {\n if (name === null || name === undefined) {\n return yield* ScheduleOwnerProtocolError.make({\n message: \"Schedule Owner objects require an idFromName identity\",\n });\n }\n\n const tuple = yield* Schema.decodeEffect(\n Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String])),\n )(name).pipe(\n Effect.mapError(() =>\n ScheduleOwnerProtocolError.make({ message: \"Schedule Owner object name is malformed\" }),\n ),\n );\n\n return yield* Schema.decodeEffect(ScheduleOwner)({\n tenantId: tuple[0],\n ownerId: tuple[1],\n }).pipe(\n Effect.mapError(() =>\n ScheduleOwnerProtocolError.make({ message: \"Schedule Owner object identity is invalid\" }),\n ),\n );\n});\n\nconst alarmStorageError = (operation: string) => (error: { readonly _tag: string }) =>\n ScheduleStorageError.make({\n operation,\n reason: error._tag === \"StorageOperationError\" ? \"unavailable\" : \"corrupt\",\n });\n\nconst transactionLayer: Layer.Layer<\n DoScheduleTransaction,\n never,\n DurableObjectAlarm.DurableObjectAlarm\n> = Layer.effect(\n DoScheduleTransaction,\n Effect.gen(function* () {\n const alarms = yield* DurableObjectAlarm.DurableObjectAlarm;\n\n return DoScheduleTransaction.of({\n run: (body) =>\n Effect.gen(function* () {\n const nowMillis = yield* Clock.currentTimeMillis;\n\n return yield* alarms\n .transaction((transaction) =>\n body((replacement) =>\n replacement.deadlineAtMillis === null\n ? transaction\n .cancelAlarm({ id: SCHEDULE_ALARM_ID, tag: SCHEDULE_ALARM_TAG })\n .pipe(Effect.mapError(alarmStorageError(\"cancel Schedule Owner alarm\")))\n : Effect.fromOption(\n DateTime.make(Math.max(replacement.deadlineAtMillis, nowMillis + 1)),\n ).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({\n operation: \"validate Schedule Owner alarm deadline\",\n reason: \"corrupt\",\n }),\n ),\n Effect.flatMap((runAt) =>\n transaction\n .scheduleAlarm({\n id: SCHEDULE_ALARM_ID,\n tag: SCHEDULE_ALARM_TAG,\n runAt,\n payload: {\n schemaVersion: 1,\n generation: replacement.generation,\n },\n })\n .pipe(\n Effect.mapError(alarmStorageError(\"schedule Schedule Owner alarm\")),\n ),\n ),\n ),\n ),\n )\n .pipe(\n Effect.catchTag(\"StorageOperationError\", () =>\n ScheduleStorageError.make({\n operation: \"commit Schedule Owner transaction\",\n reason: \"unavailable\",\n }),\n ),\n );\n }),\n });\n }),\n);\n\ntype ScheduleRuntimeServices =\n | Scheduling\n | ScheduleDriver\n | DoScheduleAlarmControl\n | ScheduleOwnerIdentity\n | DurableObjectAlarm.DurableObjectAlarm;\n\nconst ensureOwner = (\n expected: ScheduleOwner,\n request: ScheduleOwnerRequest,\n): Effect.Effect<void, ScheduleOwnerProtocolError> => {\n const observed = requestOwner(request);\n\n return observed.tenantId === expected.tenantId && observed.ownerId === expected.ownerId\n ? Effect.void\n : Effect.fail(\n ScheduleOwnerProtocolError.make({\n message: \"The request owner does not match the addressed Schedule Owner object\",\n }),\n );\n};\n\nconst handleScheduleRequest = Effect.fn(\"ScheduleOwner.handleRequest\")(function* (\n encoded: unknown,\n): Effect.fn.Return<unknown, never, Scheduling | ScheduleOwnerIdentity> {\n const decoded = yield* decodeScheduleOwnerRequest(encoded).pipe(Effect.result);\n\n if (decoded._tag === \"Failure\") {\n return yield* encodeScheduleOwnerResponse(\n scheduleProtocolFailure(\"The Schedule request could not be decoded\"),\n ).pipe(Effect.orDie);\n }\n const request = decoded.success;\n const { owner } = yield* ScheduleOwnerIdentity;\n const scheduling = yield* Scheduling;\n\n const response = yield* Effect.gen(function* () {\n yield* ensureOwner(owner, request);\n switch (request._tag) {\n case \"Create\": {\n const value = yield* scheduling.create(passthroughAgent(request.agentId), request.input, {\n scope: request.scope,\n scheduleId: request.scheduleId,\n timing: request.timing,\n destination: request.destination,\n deliveryPrincipal: request.deliveryPrincipal,\n definitions: request.definitions,\n ...(request.admissionGroup === undefined\n ? {}\n : { admissionGroup: request.admissionGroup }),\n ...(request.admissionFence === undefined\n ? {}\n : { admissionFence: request.admissionFence }),\n });\n\n return { _tag: \"Snapshot\" as const, value };\n }\n case \"Update\": {\n const value = yield* scheduling.update(passthroughAgent(request.agentId), request.input, {\n scope: request.scope,\n scheduleId: request.scheduleId,\n timing: request.timing,\n destination: request.destination,\n deliveryPrincipal: request.deliveryPrincipal,\n definitions: request.definitions,\n ...(request.admissionGroup === undefined\n ? {}\n : { admissionGroup: request.admissionGroup }),\n ...(request.admissionFence === undefined\n ? {}\n : { admissionFence: request.admissionFence }),\n expectedRevision: request.expectedRevision,\n });\n\n return { _tag: \"Snapshot\" as const, value };\n }\n case \"Get\":\n return {\n _tag: \"Snapshot\" as const,\n value: yield* scheduling.get(request.scope, request.scheduleId),\n };\n case \"List\":\n return {\n _tag: \"Page\" as const,\n value: yield* scheduling.list(request.scope, {\n ...(request.after === undefined ? {} : { after: request.after }),\n ...(request.limit === undefined ? {} : { limit: request.limit }),\n }),\n };\n case \"Recover\":\n return {\n _tag: \"Snapshot\" as const,\n value: yield* scheduling.recover(\n request.scope,\n request.scheduleId,\n request.expectedRevision,\n request.expectedGeneration,\n ),\n };\n case \"Control\": {\n const value =\n request.operation === \"pause\"\n ? yield* scheduling.pause(request.scope, request.scheduleId, request.expectedRevision)\n : request.operation === \"resume\"\n ? yield* scheduling.resume(\n request.scope,\n request.scheduleId,\n request.expectedRevision,\n )\n : yield* scheduling.cancel(\n request.scope,\n request.scheduleId,\n request.expectedRevision,\n );\n\n return { _tag: \"Snapshot\" as const, value };\n }\n }\n }).pipe(\n Effect.map((value): ScheduleOwnerResponse => value),\n Effect.catch((failure) =>\n Schema.is(ScheduleOwnerFailure)(failure)\n ? Effect.succeed({ _tag: \"Failed\" as const, failure })\n : Effect.succeed(\n scheduleProtocolFailure(\"The Schedule operation failed outside its public contract\"),\n ),\n ),\n );\n\n return yield* encodeScheduleOwnerResponse(response).pipe(Effect.orDie);\n});\n\n/** @internal The complete native alarm operation, including its event deadline. */\nexport const scheduleAlarmHandler = (limits: SchedulingLimits) =>\n DurableObjectAlarm.processDue(\n (event) =>\n Effect.gen(function* () {\n if (event.tag !== SCHEDULE_ALARM_TAG || event.id !== SCHEDULE_ALARM_ID) {\n return yield* ScheduleAlarmProtocolError.make({\n message: `Unsupported Schedule Owner alarm ${event.tag}/${event.id}`,\n });\n }\n yield* Schema.decodeUnknownEffect(ScheduleAlarmPayload)(event.payload).pipe(\n Effect.mapError(() =>\n ScheduleAlarmProtocolError.make({\n message: \"Unsupported Schedule Owner alarm payload version\",\n }),\n ),\n );\n const scheduling = yield* ScheduleDriver;\n const alarmControl = yield* DoScheduleAlarmControl;\n const { owner } = yield* ScheduleOwnerIdentity;\n const nowMillis = yield* Clock.currentTimeMillis;\n\n yield* alarmControl.prearm(nowMillis + limits.recoveryPollMillis);\n const pass = yield* scheduling.runDue(owner);\n\n if (pass.failed > 0) {\n yield* alarmControl.prearm((yield* Clock.currentTimeMillis) + limits.recoveryPollMillis);\n } else {\n yield* alarmControl.reconcile;\n }\n }),\n { mode: \"ordered\" },\n ).pipe(\n // Bound due acquisition and acknowledgement as well as admission. Prepared occurrences\n // and their replacement alarm survive interruption and retain their idempotency keys.\n Effect.timeout(\"14 minutes\"),\n Effect.asVoid,\n );\n\nexport interface ScheduleOwnerObjectInstance extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, ScheduleRuntimeServices>\n> {\n schedule(encoded: unknown): Promise<unknown>;\n alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void;\n}\n\nexport interface ScheduleOwnerObjectClass {\n new (ctx: DurableObjectState, env: Cloudflare.Env): ScheduleOwnerObjectInstance;\n}\n\n/**\n * The host Layer supplies authorization and routing and is cached for the object incarnation.\n * Cloudflare eviction does not guarantee its finalizers run. Do not acquire resources requiring\n * cleanup in this Layer; acquire them inside scoped `manage` / `prepare` operations instead.\n * Native services belong to effect-cf; the database and alarm runtime remain instance-owned.\n */\nexport const makeScheduleOwnerObjectClass = <E>(\n host: Layer.Layer<\n ScheduleAuthorizer | ThreadObjectNamespace,\n E,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment | ScheduleOwnerIdentity\n >,\n limits: SchedulingLimits = defaultSchedulingLimits,\n): ScheduleOwnerObjectClass => {\n const ownerLayer = Layer.effect(\n ScheduleOwnerIdentity,\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n\n return ScheduleOwnerIdentity.of({ owner: yield* decodeOwnerName(state.raw.id.name) });\n }),\n );\n\n const sqlLayer = Layer.unwrap(\n Effect.map(EffectCfDurableObjectState.DurableObjectState, (state) =>\n SqliteClient.layer({ storage: state.raw.storage }),\n ),\n );\n\n const application = Layer.merge(Scheduling.layer(limits), ScheduleDriver.layer(limits)).pipe(\n Layer.provideMerge(\n scheduleStoreLayer.pipe(Layer.provide(transactionLayer), Layer.provide(sqlLayer)),\n ),\n Layer.provide(\n cloudflareScheduledInputAdmissionLayer.pipe(\n Layer.provide(cloudflarePreparedInputAdmissionLayer),\n Layer.provide(CloudflareThreadClient.layer),\n ),\n ),\n Layer.provide(ScheduleWakeNoop),\n Layer.provide(BrowserCrypto.layer),\n Layer.provideMerge(DurableObjectAlarm.DurableObjectAlarm.layer),\n Layer.provide(host),\n Layer.provideMerge(ownerLayer),\n );\n\n const runtime: Layer.Layer<\n ScheduleRuntimeServices,\n E | ScheduleStorageError | ScheduleOwnerProtocolError | ScheduleValidationError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n\n return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope));\n }),\n );\n\n const rpc = {\n schedule: (encoded: unknown) => handleScheduleRequest(encoded),\n } satisfies EffectCfDurableObject.DurableObjectRpc<ScheduleRuntimeServices>;\n\n const Base = EffectCfDurableObject.make(runtime, {\n initialize: Effect.void,\n rpc,\n alarms: scheduleAlarmHandler(limits),\n });\n\n class ScheduleOwnerObject extends Base {\n override alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void {\n return super.alarm?.(alarmInfo);\n }\n }\n\n return ScheduleOwnerObject;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAE1B,MAAM,uBAAuB,OAAO,OAAO;CACzC,eAAe,OAAO,QAAQ,CAAC;CAC/B,YAAY,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;AACtD,CAAC;AAED,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA,EAAE,SAAS,OAAO,OAAO,CAC3B,CAAC,CAAC,CAAC;AAEH,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MAAM,QAAQ,QAAQ,CAAC,CAClF,GACA,MAAM,QACJ,uCAAuC,KACrC,MAAM,QAAQ,qCAAqC,GACnD,MAAM,QAAQ,uBAAuB,KAAK,CAC5C,CACF,GACA,MAAM,QAAQ,gBAAgB,GAC9B,MAAM,QAAQ,cAAc,KAAK,GACjC,MAAM,aAAa,mBAAmB,mBAAmB,KAAK,GAC9D,MAAM,QAAQ,IAAI,GAClB,MAAM,aAAa,UAAU,CAC/B;CAEA,MAAM,UAIF,MAAM,cACR,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAOA,mBAA2B;EAChD,MAAM,QAAQ,OAAO,OAAO;EAE5B,OAAO,OAAO,MAAM,sBAAsB,MAAM,eAAe,aAAa,KAAK,CAAC;CACpF,CAAC,CACH;CAMA,MAAM,OAAOC,cAAsB,KAAK,SAAS;EAC/C,YAAY,OAAO;EACnB,KAAA,EALA,WAAW,YAAqB,sBAAsB,OAAO,EAK3D;EACF,QAAQ,qBAAqB,MAAM;CACrC,CAAC;CAED,MAAM,4BAA4B,KAAK;EACrC,MAAe,WAAuD;GACpE,OAAO,MAAM,QAAQ,SAAS;EAChC;CACF;CAEA,OAAO;AACT"}
|
|
@@ -53,12 +53,15 @@ const makeSubscriptionPartitionAlarmHandler = Effect.fn("makeSubscriptionPartiti
|
|
|
53
53
|
tag: options.tag,
|
|
54
54
|
handle: (event) => Effect.gen(function* () {
|
|
55
55
|
if (event.tag !== options.tag) return yield* SubscriptionAlarmProtocolError.make({ message: "Ancillary alarm tag mismatch" });
|
|
56
|
-
const payload = yield* Schema.
|
|
56
|
+
const payload = yield* Schema.decodeEffect(options.payload)(event.payload).pipe(Effect.mapError(() => SubscriptionAlarmProtocolError.make({ message: "Invalid ancillary alarm payload" })));
|
|
57
57
|
yield* options.handle({
|
|
58
58
|
...event,
|
|
59
59
|
payload
|
|
60
60
|
});
|
|
61
|
-
}).pipe(Effect.scoped, Effect.
|
|
61
|
+
}).pipe(Effect.scoped, Effect.timeoutOrElse({
|
|
62
|
+
duration: options.timeoutMillis,
|
|
63
|
+
orElse: () => SubscriptionAlarmExtensionError.make({ code: "timeout" })
|
|
64
|
+
}), Effect.provideContext(services))
|
|
62
65
|
};
|
|
63
66
|
});
|
|
64
67
|
var SubscriptionPartitionProtocolError = class extends Schema.TaggedError()("SubscriptionPartitionProtocolError", { message: Schema.String.check(Schema.isMaxLength(4096)) }) {};
|
|
@@ -369,8 +372,8 @@ var CloudflareSubscriptionsClient = class {
|
|
|
369
372
|
var SubscriptionPartitionIdentity = class extends Context.Service()("@effect-agent/platform-cloudflare/SubscriptionPartitionIdentity") {};
|
|
370
373
|
const decodePartitionName = Effect.fn("decodeSubscriptionPartitionName")(function* (name) {
|
|
371
374
|
if (name === null || name === void 0) return yield* SubscriptionPartitionProtocolError.make({ message: "Subscription Partition objects require an idFromName identity" });
|
|
372
|
-
const tuple = yield* Schema.
|
|
373
|
-
return yield* Schema.
|
|
375
|
+
const tuple = yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String])))(name).pipe(Effect.mapError(() => SubscriptionPartitionProtocolError.make({ message: "Subscription Partition name is malformed" })));
|
|
376
|
+
return yield* Schema.decodeEffect(SourcePartition)({
|
|
374
377
|
tenantId: tuple[0],
|
|
375
378
|
address: tuple[1]
|
|
376
379
|
}).pipe(Effect.mapError(() => SubscriptionPartitionProtocolError.make({ message: "Subscription Partition identity is invalid" })));
|
|
@@ -467,14 +470,17 @@ const alarmHandler = (limits) => DurableObjectAlarm.processDue((event) => Effect
|
|
|
467
470
|
const matches = handlers.filter((handler) => handler.tag === event.tag);
|
|
468
471
|
const handler = matches[0];
|
|
469
472
|
if (event.tag.startsWith("effect-agent/") || matches.length !== 1 || handler === void 0) return yield* SubscriptionAlarmProtocolError.make({ message: "Unknown or ambiguous ancillary alarm tag" });
|
|
470
|
-
return yield* handler.handle(event).pipe(Effect.scoped, Effect.
|
|
473
|
+
return yield* handler.handle(event).pipe(Effect.scoped, Effect.timeoutOrElse({
|
|
474
|
+
duration: MAX_ANCILLARY_ALARM_MILLIS,
|
|
475
|
+
orElse: () => SubscriptionAlarmExtensionError.make({ code: "timeout" })
|
|
476
|
+
}));
|
|
471
477
|
}
|
|
472
478
|
if (event.id !== SUBSCRIPTION_ALARM_ID) return yield* SubscriptionAlarmProtocolError.make({ message: `Unsupported Subscription Partition alarm ${event.tag}/${event.id}` });
|
|
473
479
|
yield* Schema.decodeUnknownEffect(SubscriptionAlarmPayload)(event.payload).pipe(Effect.mapError(() => SubscriptionAlarmProtocolError.make({ message: "Unsupported subscription alarm payload" })));
|
|
474
480
|
const driver = yield* SubscriptionDriver;
|
|
475
481
|
const alarmControl = yield* DoSubscriptionAlarmControl;
|
|
476
482
|
yield* alarmControl.prearm((yield* Clock.currentTimeMillis) + limits.retryMillis);
|
|
477
|
-
if ((yield* driver.runDue.pipe(Effect.
|
|
483
|
+
if ((yield* driver.runDue.pipe(Effect.catchCauseIf((cause) => !Cause.hasInterrupts(cause), (cause) => Clock.currentTimeMillis.pipe(Effect.flatMap((time) => alarmControl.prearm(time + limits.retryMillis)), Effect.andThen(Effect.failCause(cause)))))).failed > 0) yield* alarmControl.prearm((yield* Clock.currentTimeMillis) + limits.retryMillis);
|
|
478
484
|
else yield* alarmControl.reconcile;
|
|
479
485
|
}), {
|
|
480
486
|
mode: "isolated",
|