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

main
ts 171 lines 6.56 KB
Raw
1 /**
2 * Runtime bootstrap for Effect-native `GCP.CloudFunctions.Function`. The
3 * generated entry imports this module and the user's `main`, and exports
4 * {@link makeHandler}'s result as the Functions Framework target.
5 *
6 * The Node.js Functions Framework owns the HTTP server, so the program's
7 * `HttpServer` here is a capture: `serve` records the composed handler
8 * (event-source listeners, then the user's `fetch`) and each framework
9 * request is bridged into it as a web `Request`. The program — built once
10 * per instance, like the Cloud Run bootstrap — runs in the background for
11 * the instance's lifetime.
12 *
13 * Runtime credentials come from the metadata server: the function's
14 * runtime service account.
15 */
16 import { NodeServices } from "@effect/platform-node";
17 import { HttpServer, safeHttpEffect } from "alchemy/Http";
18 import { reifyBoundConfigProvider } from "alchemy/Runtime";
19 import { entrypointLayer, resolveProgram, stackFromEnv } from "alchemy/Runtime/Bootstrap";
20 import * as ConfigProvider from "effect/ConfigProvider";
21 import * as Deferred from "effect/Deferred";
22 import * as Effect from "effect/Effect";
23 import * as Exit from "effect/Exit";
24 import * as FetchHttpClient from "effect/http/FetchHttpClient";
25 import * as EffectHttp from "effect/http/HttpEffect";
26 import * as HttpServerRequest from "effect/http/HttpServerRequest";
27 import * as HttpServerResponse from "effect/http/HttpServerResponse";
28 import * as Layer from "effect/Layer";
29 import * as Logger from "effect/Logger";
30 import * as Scope from "effect/Scope";
31 import { fromMetadataServer } from "../MetadataCredentials.ts";
32
33 /** Web-standard dispatcher over the program's composed HTTP handler. */
34 type Dispatch = (request: Request) => Promise<Response>;
35
36 /** The subset of the Functions Framework (Express) request/response used. */
37 interface FrameworkRequest {
38 method: string;
39 originalUrl?: string;
40 url: string;
41 headers: Record<string, string | string[] | undefined>;
42 rawBody?: Uint8Array;
43 }
44 interface FrameworkResponse {
45 status(code: number): FrameworkResponse;
46 setHeader(name: string, value: string | string[]): void;
47 end(body?: Uint8Array): void;
48 }
49
50 const toWebRequest = (req: FrameworkRequest): Request => {
51 const headers = new Headers();
52 for (const [name, value] of Object.entries(req.headers)) {
53 if (value === undefined) continue;
54 for (const item of Array.isArray(value) ? value : [value]) {
55 headers.append(name, item);
56 }
57 }
58 const host = headers.get("x-forwarded-host") ?? headers.get("host");
59 const url = `https://${host ?? "function"}${req.originalUrl ?? req.url}`;
60 const hasBody = req.method !== "GET" && req.method !== "HEAD";
61 return new Request(url, {
62 method: req.method,
63 headers,
64 body: hasBody && req.rawBody ? new Uint8Array(req.rawBody) : undefined,
65 });
66 };
67
68 const writeResponse = async (res: FrameworkResponse, response: Response) => {
69 res.status(response.status);
70 const cookies = response.headers.getSetCookie();
71 if (cookies.length > 0) res.setHeader("set-cookie", cookies);
72 response.headers.forEach((value, name) => {
73 if (name !== "set-cookie") res.setHeader(name, value);
74 });
75 res.end(new Uint8Array(await response.arrayBuffer()));
76 };
77
78 /**
79 * `HttpServer` whose `serve` publishes a dispatcher instead of binding a
80 * port. Requests run under the program's context and their own scope.
81 */
82 const captureServer = (dispatch: Deferred.Deferred<Dispatch>) =>
83 Layer.succeed(HttpServer, {
84 serve: (handler) =>
85 Effect.gen(function* () {
86 const context = yield* Effect.context<any>();
87 const safe = safeHttpEffect(handler as any);
88 const run: Dispatch = (webRequest) =>
89 Effect.runPromiseWith(context)(
90 Effect.gen(function* () {
91 const request = HttpServerRequest.fromWeb(webRequest);
92 const scope = yield* Scope.make();
93 const out = yield* Deferred.make<Response>();
94 yield* EffectHttp.toHandled(safe, (req, response) =>
95 Deferred.succeed(
96 out,
97 HttpServerResponse.toWeb(EffectHttp.scopeTransferToStream(response), {
98 withoutBody: req.method === "HEAD",
99 context,
100 }),
101 ),
102 ).pipe(
103 Effect.provideService(HttpServerRequest.HttpServerRequest, request),
104 Effect.provideService(Scope.Scope, scope),
105 );
106 const response = yield* Deferred.await(out);
107 yield* Scope.close(scope, Exit.void);
108 return response;
109 }),
110 );
111 yield* Deferred.succeed(dispatch, run);
112 }) as any,
113 });
114
115 /**
116 * Build the Functions Framework target for `entrypoint`. The program starts
117 * when the framework loads the module and is reused by every request on
118 * the instance.
119 */
120 export const makeHandler = (entrypoint: unknown) => {
121 const start = (): Promise<Dispatch> => {
122 const dispatch = Deferred.makeUnsafe<Dispatch>();
123 const platform = Layer.mergeAll(
124 NodeServices.layer,
125 FetchHttpClient.layer,
126 Logger.layer([Logger.consolePretty()]),
127 );
128 const program = resolveProgram("program", { telemetry: true }).pipe(
129 Effect.provide(
130 entrypointLayer(entrypoint).pipe(
131 Layer.provideMerge(stackFromEnv),
132 Layer.provideMerge(fromMetadataServer()),
133 Layer.provideMerge(captureServer(dispatch)),
134 Layer.provideMerge(platform),
135 Layer.provideMerge(
136 Layer.succeed(
137 ConfigProvider.ConfigProvider,
138 reifyBoundConfigProvider(ConfigProvider.fromEnv(), process.env),
139 ),
140 ),
141 ),
142 ),
143 Effect.scoped,
144 );
145 Effect.runFork(
146 program.pipe(
147 Effect.tapCause((cause) => Effect.logError("Cloud Function program failed", cause)),
148 // A program that ends (or fails) without serving never answers;
149 // fail pending and future requests instead of hanging them.
150 Effect.onExit(() =>
151 Deferred.die(dispatch, new Error("Cloud Function program exited without serving HTTP")),
152 ),
153 ) as Effect.Effect<unknown>,
154 );
155 return dispatch.pipe(Deferred.await, Effect.runPromise);
156 };
157
158 const ready = start();
159 // Surface a failed boot through the requests, not an unhandled rejection.
160 ready.catch(() => undefined);
161
162 return async (req: FrameworkRequest, res: FrameworkResponse) => {
163 try {
164 const dispatch = await ready;
165 await writeResponse(res, await dispatch(toWebRequest(req)));
166 } catch (error) {
167 console.error("Cloud Function request failed", error);
168 res.status(500).end();
169 }
170 };
171 };