@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 117 lines 4.25 KB
Raw
1 import * as Data from "effect/Data";
2 import * as Effect from "effect/Effect";
3 import * as HttpClient from "effect/http/HttpClient";
4 import { HttpServerRequest } from "effect/http/HttpServerRequest";
5 import * as HttpServerResponse from "effect/http/HttpServerResponse";
6 import * as Schedule from "effect/Schedule";
7
8 /**
9 * Harness for GCP binding tests, the counterpart of the AWS Lambda binding
10 * fixtures (e.g. test/AWS/DynamoDB/handler.ts): each service's bindings run
11 * inside a deployed Effect-native Cloud Run service, as that service's own
12 * runtime service account, so the IAM grant every binding registers is what
13 * authorizes the call.
14 *
15 * Fixture side (`fixtures/bindings-host.ts`): build a `routes` record of
16 * probe Effects and serve it with {@link serveProbes}. Test side: call
17 * {@link callProbe} with the deployed URL and a route name.
18 */
19
20 /** What a probe route answers: the value, or the typed failure it hit. */
21 export type ProbeOutcome<A> =
22 | { readonly ok: true; readonly value: A }
23 | {
24 readonly ok: false;
25 readonly error: { readonly _tag: string; readonly message?: string };
26 };
27
28 export type Probe = Effect.Effect<unknown, { readonly _tag: string }, any>;
29
30 const toJsonSafe = (value: unknown): unknown =>
31 JSON.parse(
32 JSON.stringify(value, (_key, item) =>
33 item instanceof Uint8Array
34 ? { $bytes: Buffer.from(item).toString("base64") }
35 : typeof item === "bigint"
36 ? item.toString()
37 : item,
38 ) ?? "null",
39 );
40
41 /**
42 * Fixture-side `fetch`: `GET /probe/<name>` runs `routes[name]` and answers
43 * its {@link ProbeOutcome} as JSON. `GET /` answers 200 for readiness.
44 */
45 export const serveProbes = (routes: Record<string, Probe>) =>
46 Effect.gen(function* () {
47 const request = yield* HttpServerRequest;
48 const pathname = new URL(request.url, "http://host").pathname;
49 const name = /^\/probe\/([^/]+)$/.exec(pathname)?.[1];
50 if (name === undefined) return HttpServerResponse.text("ok");
51 const probe = routes[decodeURIComponent(name)];
52 if (probe === undefined) {
53 return HttpServerResponse.text(`no probe ${name}`, { status: 404 });
54 }
55 const outcome: ProbeOutcome<unknown> = yield* probe.pipe(
56 Effect.map((value) => ({ ok: true as const, value: toJsonSafe(value) })),
57 Effect.catch((error) =>
58 Effect.succeed({
59 ok: false as const,
60 error: {
61 _tag: error._tag,
62 message: (error as { readonly message?: string }).message,
63 },
64 }),
65 ),
66 );
67 return yield* HttpServerResponse.json(outcome);
68 });
69
70 class ProbeNotReady extends Data.TaggedError("ProbeNotReady")<{
71 readonly reason: string;
72 }> {
73 override get message() {
74 return this.reason;
75 }
76 }
77
78 /**
79 * Call a probe route on the deployed fixture. Retries (bounded, ~7 min) while
80 * the service is still starting (non-200) or the binding's fresh IAM grant is
81 * still propagating (the probe hit `Forbidden`/`PermissionDenied`), then
82 * returns the outcome.
83 */
84 export const callProbe = <A = unknown>(baseUrl: string, name: string) =>
85 HttpClient.get(`${baseUrl.replace(/\/+$/, "")}/probe/${name}`).pipe(
86 Effect.flatMap((response) =>
87 response.status === 200
88 ? (response.json as Effect.Effect<ProbeOutcome<A>, never>)
89 : Effect.fail(new ProbeNotReady({ reason: `HTTP ${response.status}` })),
90 ),
91 Effect.flatMap((outcome) =>
92 !outcome.ok &&
93 (outcome.error._tag === "Forbidden" || outcome.error._tag === "PermissionDenied")
94 ? Effect.fail(new ProbeNotReady({ reason: `IAM: ${outcome.error._tag}` }))
95 : Effect.succeed(outcome),
96 ),
97 Effect.mapError((error) =>
98 error._tag === "ProbeNotReady" ? error : new ProbeNotReady({ reason: String(error) }),
99 ),
100 Effect.retry({
101 while: (error) => error._tag === "ProbeNotReady",
102 schedule: Schedule.spaced("10 seconds"),
103 times: 42,
104 }),
105 );
106
107 /** {@link callProbe}, failing the test unless the probe succeeded. */
108 export const expectProbe = <A = unknown>(baseUrl: string, name: string) =>
109 callProbe<A>(baseUrl, name).pipe(
110 Effect.flatMap((outcome) =>
111 outcome.ok
112 ? Effect.succeed(outcome.value)
113 : Effect.die(
114 new Error(`probe ${name} failed: ${outcome.error._tag} ${outcome.error.message ?? ""}`),
115 ),
116 ),
117 );