The best way to control Claude Code, Codex and more from any computer or phone

main
ts 184 lines 6.84 KB
Raw
1 import { HttpServer, type HttpEffect } from "alchemy/Http";
2 import * as Output from "alchemy/Output";
3 import { Platform } from "alchemy/Platform";
4 import { serveRpc } from "alchemy/Rpc";
5 import type { ProcessContext } from "alchemy/Runtime/Process";
6 import { packEnvValueKeepRedacted, unpackEnvValue } from "alchemy/RuntimeContext";
7 import * as Effect from "effect/Effect";
8 import * as Option from "effect/Option";
9 import { DurableObject } from "../Workers/DurableObject.ts";
10 import { Worker } from "../Workers/Worker.ts";
11 import { ContainerTypeId, type Container } from "./Container.ts";
12 import type {
13 ContainerApplication,
14 ContainerServices,
15 ContainerShape,
16 } from "./ContainerApplication.ts";
17 import {
18 containerApplicationSettings,
19 durableObjectContainerBinding,
20 isDurableObjectContainerResource,
21 workerContainerBinding,
22 } from "./ContainerConfiguration.ts";
23 import { declareDurableObjectApplication } from "./DurableObjectApplication.ts";
24
25 const toHttpUrl = (url: string) =>
26 url.startsWith("https:") ? `http:${url.slice("https:".length)}` : url;
27
28 /**
29 * workerd container ports reject TLS outright ("Connecting to a container
30 * using HTTPS is not currently supported") — but the common proxy pattern
31 * forwards the incoming Worker request, whose production URL is `https://`,
32 * straight to the port. The hop into the container is already secure, so
33 * downgrade the scheme before forwarding, exactly like Cloudflare's own
34 * `@cloudflare/containers` `containerFetch` does
35 * (`request.url.replace("https:", "http:")`).
36 */
37 export const httpSchemePort = <
38 P extends {
39 fetch: (...args: any[]) => any;
40 connect: (...args: any[]) => any;
41 },
42 >(
43 port: P,
44 ): P =>
45 ({
46 fetch: (input: RequestInfo | URL, init?: RequestInit) =>
47 input instanceof Request
48 ? port.fetch(toHttpUrl(input.url), input)
49 : port.fetch(toHttpUrl(String(input)), init),
50 connect: (address: any, options?: any) => port.connect(address, options),
51 }) as any as P;
52
53 const bindContainer = Effect.fn(function* <Shape, Req = never>(
54 containerEff:
55 | ContainerApplication<Shape>
56 | Effect.Effect<ContainerApplication<Shape>, never, Req>,
57 ) {
58 const namespace = yield* DurableObject;
59 const worker = yield* Worker;
60
61 const container = Effect.isEffect(containerEff) ? yield* containerEff : containerEff;
62
63 if (isDurableObjectContainerResource(container)) {
64 // The class has one container application. Every Container bound to it
65 // declares the same resource (deduped by id), attaches it to the
66 // namespace, and adds its application-wide settings; the Worker merges
67 // each Container's image into the class's `containers` entry.
68 const application = yield* declareDurableObjectApplication(worker, namespace.name);
69 yield* application.bind`${container.LogicalId}`({
70 durableObjects: { namespaceId: namespace.namespaceId },
71 container: {
72 id: container.LogicalId,
73 settings: containerApplicationSettings(container),
74 },
75 });
76 yield* worker.bind`${namespace.name}:${container.LogicalId}`({
77 containers: [durableObjectContainerBinding(namespace.name, application, container)],
78 });
79 return;
80 }
81
82 yield* container.bind`${namespace}`({
83 durableObjects: {
84 namespaceId: namespace.namespaceId,
85 },
86 });
87
88 yield* worker.bind`${container.LogicalId}`({
89 containers: [workerContainerBinding(namespace.name, container)],
90 });
91 });
92
93 export const ContainerPlatform: Platform<
94 ContainerApplication,
95 ContainerServices,
96 ContainerShape,
97 ProcessContext,
98 Container
99 > & { bind: typeof bindContainer } = Platform(
100 "Cloudflare.Container",
101 {
102 createRuntimeContext: (id: string): ProcessContext => {
103 const runners: Effect.Effect<void, never, any>[] = [];
104 const env: Record<string, any> = {};
105
106 const serve = <Req = never>(
107 handler: HttpEffect<Req>,
108 options?: { shape?: Record<string, unknown> },
109 ) =>
110 Effect.sync(() => {
111 // Containers have no native RPC transport (unlike a Cloudflare
112 // Worker's JSRPC), so expose the impl's non-`fetch` shape methods
113 // over the plain-`fetch` RPC protocol: requests to `/__rpc__/*` are
114 // dispatched to the matching shape method, everything else falls
115 // through to the user's `fetch` handler. The DO side talks to this
116 // via `makeFetchRpcStub` over the container's TCP port.
117 const finalHandler = options?.shape ? serveRpc(options.shape, handler) : handler;
118 runners.push(
119 Effect.gen(function* () {
120 const httpServer = yield* Effect.serviceOption(HttpServer).pipe(
121 Effect.map(Option.getOrUndefined),
122 );
123 if (httpServer) {
124 yield* httpServer.serve(finalHandler);
125 return yield* Effect.never;
126 } else {
127 // this should only happen at plantime, validate?
128 }
129 }).pipe(Effect.orDie),
130 );
131 });
132
133 return {
134 Type: ContainerTypeId,
135 LogicalId: id,
136 id,
137 env,
138 set: (bindingId: string, output: Output.Output) =>
139 Effect.sync(() => {
140 const key = bindingId.replaceAll(/[^a-zA-Z0-9]/g, "_");
141 // `packEnvValueKeepRedacted` keeps the Redacted wrapper on the
142 // outside so the provider can deploy secrets through the
143 // Secrets Store (referenced via `secrets`) instead of leaking
144 // them as plain `environmentVariables`, while the inner marker
145 // lets the runtime `get` accessor rebuild the wrapper after
146 // Cloudflare hands the value back as a plain env-var string.
147 // Mirrors `makeWorkerRuntimeContext`.
148 env[key] = output.pipe(Output.map(packEnvValueKeepRedacted));
149 return key;
150 }),
151 get: <T>(key: string) =>
152 // Read straight from `process.env` — see `unpackEnvValue` for why
153 // this must never resolve through `Config.String`.
154 Effect.sync(() => unpackEnvValue<T>(process.env[key]) as T),
155 run: ((effect: Effect.Effect<void, never, any>) =>
156 Effect.sync(() => {
157 runners.push(effect);
158 })) as unknown as ProcessContext["run"],
159 serve,
160 exports: Effect.sync(() => ({
161 default: Effect.forEach(
162 runners,
163 (eff) =>
164 Effect.forever(
165 eff.pipe(
166 // Log and ignore errors (daemon mode, it should just re-run)
167 Effect.tapError((err) => Effect.logError(err)),
168 Effect.ignore,
169 // TODO(sam): ignore cause? for now, let that actually kill the server
170 // Effect.ignoreCause
171 ),
172 ),
173 {
174 concurrency: "unbounded",
175 },
176 ),
177 })),
178 } as ProcessContext;
179 },
180 },
181 {
182 bind: bindContainer,
183 },
184 );