The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type * as cf from "@cloudflare/workers-types"; |
| 2 | import { |
| 3 | asEffectOrStream, |
| 4 | decodeRpcResult, |
| 5 | makeRpcErrorReviver, |
| 6 | RpcCallError, |
| 7 | type RpcErrorClass, |
| 8 | } from "alchemy/Rpc"; |
| 9 | import { isYieldableEffect } from "alchemy/Util/effect"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as HttpClient from "effect/http/HttpClient"; |
| 12 | import * as Layer from "effect/Layer"; |
| 13 | import { RpcClient, RpcSerialization, type Rpc, type RpcGroup } from "effect/rpc"; |
| 14 | import type * as RpcClientError from "effect/rpc/RpcClientError"; |
| 15 | import * as Schedule from "effect/Schedule"; |
| 16 | import { fromCloudflareFetcher } from "../Fetcher.ts"; |
| 17 | import { withRpcTraceContext } from "./internal/RpcTraceContext.ts"; |
| 18 | import { isPlaceholderReset } from "./Placeholder.ts"; |
| 19 | |
| 20 | // The transport-agnostic RPC wire protocol (envelopes, error types, stream |
| 21 | // encode/decode, `asEffectOrStream`, and the plain-`fetch` client/server) now |
| 22 | // lives in `src/Rpc.ts` so non-Cloudflare runtimes (e.g. Containers) can reuse |
| 23 | // it. Re-export it here so existing `Cloudflare.*` consumers keep working. |
| 24 | export * from "alchemy/Rpc"; |
| 25 | |
| 26 | /** |
| 27 | * Wrap a Cloudflare service-binding stub (or an `Effect` that resolves |
| 28 | * to one — useful when the stub depends on a service like |
| 29 | * `WorkerEnvironment` that's only available at *exec* phase) into an |
| 30 | * Effect-typed RPC client. |
| 31 | * |
| 32 | * `Service.fetch`/`Service.connect` are passed through eagerly when the |
| 33 | * stub is already resolved; everything else is treated as an RPC method |
| 34 | * whose dispatch is deferred until call time, so the user effect runs in |
| 35 | * the right runtime layer (which is what `bindWorker` actually wants — |
| 36 | * its methods are called at exec, even though it's *defined* at init). |
| 37 | */ |
| 38 | export const makeRpcStub = <Shape>( |
| 39 | stubSource: unknown, |
| 40 | options?: { |
| 41 | /** |
| 42 | * Declared error classes (see {@link RpcErrorClass}): failed method |
| 43 | * results whose `_tag` matches one are reconstructed as real class |
| 44 | * instances instead of the plain objects RPC serialization produces. |
| 45 | */ |
| 46 | readonly errors?: ReadonlyArray<RpcErrorClass> | undefined; |
| 47 | /** |
| 48 | * Append the caller's trace context to every call's arguments. Only for |
| 49 | * a callee known to strip it again — a Durable Object class bridged by |
| 50 | * the same bundle; anything else would get an extra argument. |
| 51 | */ |
| 52 | readonly traceContext?: boolean | undefined; |
| 53 | }, |
| 54 | ): Shape => { |
| 55 | const isLazy = isYieldableEffect(stubSource); |
| 56 | const eagerFetcher = isLazy ? undefined : fromCloudflareFetcher(stubSource as cf.Fetcher); |
| 57 | const proxyTarget: object = eagerFetcher ?? {}; |
| 58 | const revive = makeRpcErrorReviver(options?.errors); |
| 59 | |
| 60 | return new Proxy(proxyTarget, { |
| 61 | get: (target: any, prop) => { |
| 62 | if (!isLazy && prop in target) return target[prop]; |
| 63 | if (typeof prop !== "string" && typeof prop !== "symbol") { |
| 64 | return target[prop]; |
| 65 | } |
| 66 | return (...args: any[]) => |
| 67 | asEffectOrStream( |
| 68 | Effect.gen(function* () { |
| 69 | // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- untyped lazy stub source |
| 70 | const stub = isLazy ? yield* stubSource as Effect.Effect<any> : stubSource; |
| 71 | // The callee parents its spans on the caller's, like `traceparent` |
| 72 | // does for a `fetch` into the object. |
| 73 | const callArgs = options?.traceContext ? yield* withRpcTraceContext(args) : args; |
| 74 | return yield* Effect.tryPromise({ |
| 75 | try: () => (stub as any)[prop](...callArgs), |
| 76 | catch: (cause) => new RpcCallError({ method: String(prop), cause }), |
| 77 | }).pipe( |
| 78 | // Right after a deploy, an object can still start on the |
| 79 | // placeholder script, which runs none of the real code and |
| 80 | // resets itself so the next call gets the deployed code. The |
| 81 | // new code can take a while to reach every edge (~35s here). |
| 82 | Effect.retry({ |
| 83 | while: (error) => isPlaceholderReset(error.cause), |
| 84 | schedule: Schedule.min([ |
| 85 | Schedule.exponential("200 millis"), |
| 86 | Schedule.spaced("2 seconds"), |
| 87 | ]), |
| 88 | times: 20, |
| 89 | }), |
| 90 | Effect.flatMap((value) => decodeRpcResult(value, revive)), |
| 91 | ); |
| 92 | }), |
| 93 | ); |
| 94 | }, |
| 95 | }) as Shape; |
| 96 | }; |
| 97 | |
| 98 | export const bindEffectRpc = <Rpcs extends Rpc.Any>( |
| 99 | namespace: { |
| 100 | readonly getByName: ( |
| 101 | id: string, |
| 102 | options?: cf.DurableObjectNamespaceGetDurableObjectOptions, |
| 103 | ) => { readonly fetch: any }; |
| 104 | }, |
| 105 | group: RpcGroup.RpcGroup<Rpcs>, |
| 106 | options?: { |
| 107 | /** |
| 108 | * Override the rpc serialization layer. Defaults to NDJSON, which |
| 109 | * is required when any rpc in the group is a streaming rpc. |
| 110 | */ |
| 111 | readonly serialization?: Layer.Layer<RpcSerialization.RpcSerialization>; |
| 112 | }, |
| 113 | ): { |
| 114 | readonly getByName: ( |
| 115 | id: string, |
| 116 | options?: cf.DurableObjectNamespaceGetDurableObjectOptions, |
| 117 | ) => Effect.Effect< |
| 118 | RpcClient.RpcClient<Rpcs, RpcClientError.RpcClientError>, |
| 119 | never, |
| 120 | Rpc.MiddlewareClient<Rpcs> |
| 121 | >; |
| 122 | } => { |
| 123 | const serialization = options?.serialization ?? RpcSerialization.layerNdjson; |
| 124 | |
| 125 | return { |
| 126 | // Wrap the cached `RpcClient` Effect in a chainable Proxy so callers |
| 127 | // can `yield* counter.getByName(id).method(args)` directly. The proxy |
| 128 | // records the `.method(args)` ops and replays them against the |
| 129 | // resolved client when the chain is yielded. |
| 130 | getByName: Effect.fn(function* ( |
| 131 | id: string, |
| 132 | options?: cf.DurableObjectNamespaceGetDurableObjectOptions, |
| 133 | ) { |
| 134 | const httpClient = HttpClient.layerMergedContext( |
| 135 | Effect.sync(() => { |
| 136 | const stub = namespace.getByName(id, options); |
| 137 | return HttpClient.make((request) => stub.fetch(request)); |
| 138 | }), |
| 139 | ); |
| 140 | const protocol = RpcClient.layerProtocolHttp({ url: "http://alchemy-rpc/" }).pipe( |
| 141 | Layer.provide(serialization), |
| 142 | Layer.provide(httpClient), |
| 143 | ); |
| 144 | return yield* RpcClient.make(group).pipe(Effect.provide(protocol)); |
| 145 | }) as any, |
| 146 | }; |
| 147 | }; |