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

main
ts 155 lines 6.05 KB
Raw
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { waitUntil as nativeWaitUntil } from "@neon/functions";
3 import { safeHttpEffect } from "alchemy/Http";
4 import { makeEntrypointLayer, reifyBoundConfigProvider } from "alchemy/Runtime";
5 import { RuntimeContext } from "alchemy/RuntimeContext";
6 import { Self } from "alchemy/Self";
7 import { StackContext } from "alchemy/StackContext";
8 import * as ConfigProvider from "effect/ConfigProvider";
9 import * as Context from "effect/Context";
10 import * as Deferred from "effect/Deferred";
11 import * as Effect from "effect/Effect";
12 import * as Exit from "effect/Exit";
13 import * as FetchHttpClient from "effect/http/FetchHttpClient";
14 import * as EffectHttp from "effect/http/HttpEffect";
15 import * as HttpServerRequest from "effect/http/HttpServerRequest";
16 import * as HttpServerResponse from "effect/http/HttpServerResponse";
17 import * as Layer from "effect/Layer";
18 import * as Scope from "effect/Scope";
19 import { FunctionEnvironment, FunctionRequest } from "./FunctionEnvironment.ts";
20 import type { FunctionRuntimeContext } from "./FunctionRuntimeContext.ts";
21 import { FunctionUpgradeSockets } from "./FunctionUpgrade.ts";
22
23 const closeRequestScope = (scope: Scope.Closeable) => {
24 Scope.close(scope, Exit.void).pipe(
25 Effect.timeout("15 seconds"),
26 Effect.ignoreCause({ log: "Error" }),
27 Effect.runPromise,
28 nativeWaitUntil,
29 );
30 };
31
32 /** Build a Node-only Fetch bridge once per process, with a fresh scope for every request. */
33 export const makeFunctionBridge = (entrypoint: unknown) => {
34 const instanceScope = Scope.makeUnsafe();
35 const tag = Self as unknown as Context.Service<never, { RuntimeContext: FunctionRuntimeContext }>;
36 const platform = Layer.mergeAll(
37 NodeServices.layer,
38 FetchHttpClient.layer,
39 Layer.succeed(FunctionEnvironment, process.env),
40 Layer.succeed(
41 ConfigProvider.ConfigProvider,
42 reifyBoundConfigProvider(
43 ConfigProvider.orElse(
44 ConfigProvider.fromUnknown({ ALCHEMY_PHASE: "runtime" }),
45 ConfigProvider.fromEnv(),
46 ),
47 process.env,
48 ),
49 ),
50 Layer.succeed(StackContext, {
51 name: process.env.ALCHEMY_STACK_NAME ?? "NeonFunction",
52 stage: process.env.ALCHEMY_STAGE ?? "runtime",
53 bindings: {},
54 resources: {},
55 actions: {},
56 }),
57 );
58 const build = Layer.buildWithScope(
59 makeEntrypointLayer(tag, entrypoint).pipe(Layer.provideMerge(platform)),
60 instanceScope,
61 ).pipe(
62 Effect.flatMap((context) =>
63 tag.pipe(
64 Effect.flatMap((host) =>
65 host.RuntimeContext.handler.pipe(
66 Effect.map((handler) => ({
67 ...handler,
68 runtime: host.RuntimeContext,
69 built: context,
70 })),
71 ),
72 ),
73 Effect.provideContext(context),
74 ),
75 ),
76 Effect.cachedWithTTL((exit) => (Exit.isSuccess(exit) ? Infinity : 0)),
77 Effect.runSync,
78 );
79 const close = Scope.close(instanceScope, Exit.void).pipe(
80 Effect.timeout("4 seconds"),
81 Effect.ignoreCause({ log: "Error" }),
82 );
83 process.once("SIGINT", () => {
84 Effect.runFork(close);
85 });
86
87 return {
88 fetch: (request: Request) =>
89 Effect.gen(function* () {
90 const built = yield* build;
91 const response = yield* Deferred.make<Response>();
92 const services = Context.mergeAll(
93 built.built,
94 built.context,
95 Context.make(RuntimeContext, built.runtime),
96 Context.make(FunctionRequest, request),
97 Context.make(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(request)),
98 );
99 const handler = safeHttpEffect(built.dispatch(new URL(request.url).pathname)).pipe(
100 Effect.interruptible,
101 );
102 return yield* EffectHttp.toHandled(handler, (req, res) =>
103 Effect.gen(function* () {
104 const scope = yield* Effect.scope;
105 const context = yield* Effect.context<never>();
106 if (res.body._tag === "Raw" && res.body.body instanceof Response) {
107 // Neon attaches upgrade metadata to this exact object.
108 const socket = FunctionUpgradeSockets.get(res.body.body);
109 if (socket && socket.readyState !== socket.CLOSED) {
110 EffectHttp.scopeDisableClose(scope);
111 const onClose = () => closeRequestScope(scope as Scope.Closeable);
112 socket.addEventListener("close", onClose, { once: true });
113 request.signal.addEventListener("abort", onClose, {
114 once: true,
115 });
116 yield* Effect.addFinalizer(() =>
117 Effect.sync(() => {
118 socket.removeEventListener("close", onClose);
119 request.signal.removeEventListener("abort", onClose);
120 }),
121 );
122 if (request.signal.aborted) onClose();
123 }
124 yield* Deferred.succeed(response, res.body.body);
125 return;
126 }
127 const withoutBody = req.method === "HEAD";
128 const transferred = HttpServerResponse.omitsBody(res, withoutBody)
129 ? res
130 : EffectHttp.scopeTransferToStream(res);
131 const web = HttpServerResponse.toWeb(transferred, {
132 withoutBody,
133 context,
134 });
135 // The body outlives fetch; propagate actual request aborts to its producer.
136 yield* Deferred.succeed(
137 response,
138 res.body._tag === "Stream" && web.body
139 ? new Response(
140 web.body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>(), {
141 signal: request.signal,
142 }),
143 {
144 status: web.status,
145 statusText: web.statusText,
146 headers: web.headers,
147 },
148 )
149 : web,
150 );
151 }),
152 ).pipe(Effect.andThen(Deferred.await(response)), Effect.provideContext(services));
153 }).pipe((effect) => Effect.runPromise(effect, { signal: request.signal })),
154 };
155 };