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

main
ts 180 lines 6.26 KB
Raw
1 import { describe, expect } from "bun:test";
2 import * as GCP from "@alchemy.run/gcp";
3 import * as Test from "@alchemy.run/test/Bun";
4 import * as redis from "@distilled.cloud/gcp/redis_v1";
5 import * as run from "@distilled.cloud/gcp/run_v2";
6 import * as Alchemy from "alchemy";
7 import * as Effect from "effect/Effect";
8 import * as FetchHttpClient from "effect/http/FetchHttpClient";
9 import * as HttpClient from "effect/http/HttpClient";
10 import * as HttpClientRequest from "effect/http/HttpClientRequest";
11 import * as Layer from "effect/Layer";
12 import * as Schedule from "effect/Schedule";
13 import Stack from "../alchemy.run.ts";
14 import { LIMIT, WINDOW_SECONDS } from "../src/Api.ts";
15
16 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
17 providers: GCP.providers(),
18 state: Alchemy.localState(),
19 });
20
21 // Out-of-band calls to the Google APIs resolve the same stored credentials
22 // the deploy uses, so the test runs against the configured profile.
23 const GcpHttp = Layer.mergeAll(GCP.GcpAuth, GCP.fromAuthProvider(), FetchHttpClient.layer);
24
25 interface Counter {
26 key: string;
27 count: number;
28 limit: number;
29 remaining: number;
30 limited: boolean;
31 resetInSeconds: number | null;
32 }
33
34 // Deploy, tests and destroy all sit behind the same Docker guard.
35 describe("gcp-memorystore-redis", () => {
36 // Memorystore takes several minutes to create; the image build and the
37 // Cloud Run rollout run after it.
38 const stack = beforeAll(deploy(Stack), { timeout: 1_200_000 });
39
40 afterAll.skipIf(!!process.env.NO_DESTROY)(
41 Effect.gen(function* () {
42 const outputs = yield* stack;
43 yield* destroy(Stack);
44 if (outputs === undefined) return;
45
46 // Destroy waits for the delete operation, so the instance is gone,
47 // not just DELETING.
48 const instance = yield* redis
49 .getProjectsLocationsInstances({ name: outputs.instanceName })
50 .pipe(
51 Effect.map(() => "present" as const),
52 Effect.catchTag("NotFound", () => Effect.succeed("gone" as const)),
53 Effect.orDie,
54 Effect.provide(GcpHttp),
55 );
56 expect(instance).toBe("gone");
57
58 const service = yield* run.getProjectsLocationsServices({ name: outputs.serviceName }).pipe(
59 Effect.map(() => "present" as const),
60 Effect.catchTag("NotFound", () => Effect.succeed("gone" as const)),
61 Effect.orDie,
62 Effect.provide(GcpHttp),
63 );
64 expect(service).toBe("gone");
65 }),
66 { timeout: 900_000 },
67 );
68
69 const baseUrlOf = (url: string | undefined) => {
70 if (url === undefined) throw new Error("the service has no URL");
71 return url.replace(/\/+$/, "");
72 };
73
74 /**
75 * Wait until the service answers *and* can reach Redis: `/count` hits
76 * the instance over the VPC, and answers 500 until the path is up.
77 */
78 const ready = (baseUrl: string) =>
79 HttpClient.execute(HttpClientRequest.get(`${baseUrl}/count/warmup`)).pipe(
80 Effect.repeat({
81 schedule: Schedule.spaced("5 seconds"),
82 until: (response) => response.status === 200,
83 times: 36,
84 }),
85 );
86
87 const hit = (baseUrl: string, key: string) =>
88 HttpClient.execute(HttpClientRequest.post(`${baseUrl}/hit/${key}`));
89
90 const count = (baseUrl: string, key: string) =>
91 HttpClient.execute(HttpClientRequest.get(`${baseUrl}/count/${key}`)).pipe(
92 Effect.flatMap((response) => response.json),
93 Effect.map((body) => body as unknown as Counter),
94 );
95
96 test(
97 "provisions a BASIC 1 GiB instance with AUTH on a private IP",
98 Effect.gen(function* () {
99 const { instanceName, redisHost } = yield* stack;
100 const instance = yield* redis
101 .getProjectsLocationsInstances({ name: instanceName })
102 .pipe(Effect.orDie, Effect.provide(GcpHttp));
103 expect(instance.state).toBe("READY");
104 expect(instance.tier).toBe("BASIC");
105 expect(instance.memorySizeGb).toBe(1);
106 expect(instance.authEnabled).toBe(true);
107 expect(instance.host).toEqual(redisHost);
108 // Memorystore only has a private address.
109 expect(redisHost).toMatch(/^(10|172|192)\./);
110 }),
111 { timeout: 60_000 },
112 );
113
114 test(
115 "counts hits, sets the window TTL, and enforces the limit",
116 Effect.gen(function* () {
117 const { url } = yield* stack;
118 expect(url).toMatch(/^https:\/\//);
119 const baseUrl = baseUrlOf(url);
120 const warm = yield* ready(baseUrl);
121 expect(warm.status).toBe(200);
122
123 const key = `integ-${crypto.randomUUID()}`;
124
125 const fresh = yield* count(baseUrl, key);
126 expect(fresh).toMatchObject({ key, count: 0, resetInSeconds: null });
127
128 for (let n = 1; n <= LIMIT; n++) {
129 const response = yield* hit(baseUrl, key);
130 expect(response.status).toBe(200);
131 const body = (yield* response.json) as unknown as Counter;
132 expect(body).toMatchObject({
133 key,
134 count: n,
135 limit: LIMIT,
136 remaining: LIMIT - n,
137 limited: false,
138 });
139 expect(body.resetInSeconds).toBeGreaterThan(0);
140 expect(body.resetInSeconds).toBeLessThanOrEqual(WINDOW_SECONDS);
141 }
142
143 const over = yield* hit(baseUrl, key);
144 expect(over.status).toBe(429);
145 expect(Number(over.headers["retry-after"])).toBeGreaterThan(0);
146 expect((yield* over.json) as unknown as Counter).toMatchObject({
147 count: LIMIT + 1,
148 remaining: 0,
149 limited: true,
150 });
151
152 // The window's TTL is set once, on the first hit, and ticks down.
153 const after = yield* count(baseUrl, key);
154 expect(after.count).toBe(LIMIT + 1);
155 expect(after.resetInSeconds).toBeGreaterThan(0);
156 expect(after.resetInSeconds).toBeLessThanOrEqual(WINDOW_SECONDS);
157
158 // Keys count independently.
159 const other = yield* hit(baseUrl, `${key}-other`);
160 expect(other.status).toBe(200);
161 expect(((yield* other.json) as unknown as Counter).count).toBe(1);
162 }),
163 { timeout: 300_000 },
164 );
165
166 test(
167 "rejects malformed keys and unknown routes",
168 Effect.gen(function* () {
169 const { url } = yield* stack;
170 const baseUrl = baseUrlOf(url);
171 yield* ready(baseUrl);
172
173 const bad = yield* hit(baseUrl, "no%20spaces");
174 expect(bad.status).toBe(404);
175 const unknown = yield* HttpClient.execute(HttpClientRequest.get(`${baseUrl}/hit/abc`));
176 expect(unknown.status).toBe(404);
177 }),
178 { timeout: 300_000 },
179 );
180 });