@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 346 lines 12.3 KB
Raw
1 import * as Railway from "@alchemy.run/railway";
2 import { RailwayAuth } from "@alchemy.run/railway/AuthProvider";
3 import { fromAuthProvider } from "@alchemy.run/railway/Credentials";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import { fromCredentials } from "@distilled.cloud/aws/Credentials";
7 import * as AwsEndpoint from "@distilled.cloud/aws/Endpoint";
8 import type { RegionName } from "@distilled.cloud/aws/Region";
9 import * as S3 from "@distilled.cloud/aws/s3";
10 import { Query } from "@distilled.cloud/core/query";
11 import { GraphQLLive, Railway as RailwayApi } from "@distilled.cloud/railway";
12 import * as Alchemy from "alchemy";
13 import * as Data from "effect/Data";
14 import * as Effect from "effect/Effect";
15 import * as HttpClient from "effect/http/HttpClient";
16 import type * as HttpClientResponse from "effect/http/HttpClientResponse";
17 import * as Layer from "effect/Layer";
18 import * as Redacted from "effect/Redacted";
19 import { MinimumLogLevel } from "effect/References";
20 import * as Schedule from "effect/Schedule";
21 import * as Stream from "effect/Stream";
22 import { Site } from "./fixtures/bindings-shared.ts";
23 import BucketApi, { Data as BucketData, OBJECT_BODY, OBJECT_KEY } from "./fixtures/bucket-api.ts";
24 import RedisApi, { Cache, REDIS_VALUE } from "./fixtures/redis-api.ts";
25
26 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
27 providers: Railway.providers(),
28 });
29
30 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
31
32 const distilled = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
33 effect.pipe(
34 Effect.provide(Layer.merge(GraphQLLive, fromAuthProvider().pipe(Layer.provide(RailwayAuth)))),
35 );
36
37 class NotReady extends Data.TaggedError("NotReady")<{ status: number; body?: unknown }> {
38 override get message() {
39 return this.body === undefined
40 ? `status ${this.status}`
41 : `status ${this.status}: ${JSON.stringify(this.body)}`;
42 }
43 }
44
45 const asVariableMap = (value: unknown): Record<string, string> => {
46 if (value === null || typeof value !== "object" || Array.isArray(value)) {
47 return {};
48 }
49 const out: Record<string, string> = {};
50 for (const [key, item] of Object.entries(value)) {
51 if (typeof item === "string") {
52 out[key] = item;
53 }
54 }
55 return out;
56 };
57
58 const readBucketCredentials = Query.fn(
59 (bucketId: string, environmentId: string, projectId: string) =>
60 RailwayApi.bucketS3Credentials({ bucketId, environmentId, projectId }).pipe(
61 Query.map((creds) => ({
62 bucketName: creds.bucketName,
63 endpoint: creds.endpoint,
64 accessKeyId: creds.accessKeyId,
65 secretAccessKey: creds.secretAccessKey,
66 region: creds.region,
67 })),
68 ),
69 );
70
71 const readVariables = Query.fn((projectId: string, environmentId: string, serviceId: string) =>
72 RailwayApi.variables({ projectId, environmentId, serviceId, unrendered: true }),
73 );
74
75 const readServiceVariables = (projectId: string, environmentId: string, serviceId: string) =>
76 readVariables(projectId, environmentId, serviceId).pipe(
77 Effect.map(asVariableMap),
78 Effect.catchTag("RailwayNotFound", () => Effect.succeed({} as Record<string, string>)),
79 );
80
81 const firstCredentials = (bucketId: string, environmentId: string, projectId: string) =>
82 readBucketCredentials(bucketId, environmentId, projectId).pipe(
83 Effect.flatMap((items) => {
84 const first = items[0];
85 return first !== undefined
86 ? Effect.succeed(first)
87 : Effect.fail(new Error("missing bucket credentials"));
88 }),
89 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 8 }),
90 );
91
92 const withBucketS3 = <A, E, R>(
93 creds: {
94 accessKeyId: string;
95 secretAccessKey: Redacted.Redacted<string>;
96 endpoint: string;
97 region: string;
98 },
99 operation: Effect.Effect<A, E, R>,
100 ) =>
101 operation.pipe(
102 Effect.provide(
103 Layer.mergeAll(
104 fromCredentials(
105 {
106 accessKeyId: Redacted.make(creds.accessKeyId),
107 secretAccessKey: creds.secretAccessKey,
108 },
109 creds.region as RegionName,
110 ),
111 AwsEndpoint.of(creds.endpoint),
112 ),
113 ),
114 );
115
116 const Stack = Alchemy.Stack(
117 "RailwayBindingsFixture",
118 { providers: Railway.providers(), state: Alchemy.localState() },
119 Effect.gen(function* () {
120 const project = yield* Site;
121 const cache = yield* Cache;
122 const proxy = yield* Railway.TcpProxy("CacheProxy", {
123 redis: cache,
124 environment: cache,
125 applicationPort: Railway.REDIS_PORT,
126 });
127 const redisApi = yield* RedisApi;
128 const bucket = yield* BucketData;
129 const bucketApi = yield* BucketApi;
130 return {
131 redisProjectId: project.projectId,
132 redisEnvironmentId: cache.environmentId,
133 cacheServiceId: cache.serviceId,
134 proxyDomain: proxy.domain,
135 proxyPort: proxy.proxyPort,
136 redisUrl: redisApi.url,
137 redisServiceId: redisApi.serviceId,
138 bucketProjectId: project.projectId,
139 bucketEnvironmentId: bucket.environmentId,
140 bucketId: bucket.bucketId,
141 bucketUrl: bucketApi.url,
142 bucketServiceId: bucketApi.serviceId,
143 mode: "effect" as const,
144 };
145 }),
146 );
147
148 // Setup provisions Redis and deploys two runtime builds before tests can run.
149 const stack = beforeAll(deploy(Stack), { timeout: 180_000 });
150 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack), { timeout: 120_000 });
151
152 const retryTransient = {
153 while: (e: { _tag?: string; status?: number }) =>
154 e._tag === "NotReady" &&
155 (e.status === 0 ||
156 e.status === 404 ||
157 e.status === 500 ||
158 e.status === 502 ||
159 e.status === 503),
160 schedule: Schedule.exponential("500 millis").pipe(Schedule.upTo({ duration: "45 seconds" })),
161 times: 10,
162 } as const;
163
164 const readJson = (res: HttpClientResponse.HttpClientResponse): Effect.Effect<unknown, NotReady> =>
165 res.json.pipe(
166 Effect.catch(() => Effect.fail(new NotReady({ status: res.status }))),
167 Effect.flatMap((body) =>
168 res.status === 200
169 ? Effect.succeed(body)
170 : Effect.fail(new NotReady({ status: res.status, body })),
171 ),
172 );
173
174 const getJson = (url: string, path: string) =>
175 Effect.gen(function* () {
176 const client = yield* HttpClient.HttpClient;
177 return yield* client.get(`${url}${path}`).pipe(
178 Effect.timeoutOrElse({
179 duration: "8 seconds",
180 orElse: () => Effect.fail(new NotReady({ status: 0 })),
181 }),
182 Effect.flatMap(readJson),
183 Effect.mapError((e) => (e instanceof NotReady ? e : new NotReady({ status: 0, body: e }))),
184 Effect.retry(retryTransient),
185 );
186 });
187
188 const getText = (url: string) =>
189 Effect.gen(function* () {
190 const client = yield* HttpClient.HttpClient;
191 return yield* client.get(url).pipe(
192 Effect.timeoutOrElse({
193 duration: "8 seconds",
194 orElse: () => Effect.fail(new NotReady({ status: 0 })),
195 }),
196 Effect.flatMap((res) =>
197 res.status === 200
198 ? res.text.pipe(Effect.mapError(() => new NotReady({ status: res.status })))
199 : Effect.fail(new NotReady({ status: res.status })),
200 ),
201 Effect.mapError((e) => (e instanceof NotReady ? e : new NotReady({ status: 0, body: e }))),
202 Effect.retry(retryTransient),
203 );
204 });
205
206 describe(
207 "Railway Bindings",
208 {
209 tags: [
210 "provider:railway",
211 "provider:railway:bucket",
212 "provider:railway:project",
213 "provider:railway:projectenvironment",
214 "provider:railway:redis",
215 "provider:railway:service",
216 "provider:railway:tcpproxy",
217 "live",
218 ],
219 },
220 () => {
221 test(
222 "fixture is reachable over up.railway.app",
223 Effect.gen(function* () {
224 const out = yield* stack;
225 expect(out.redisUrl).toEqual(expect.any(String));
226 expect(out.redisUrl).toContain("up.railway.app");
227 expect(out.bucketUrl).toEqual(expect.any(String));
228 expect(out.bucketUrl).toContain("up.railway.app");
229
230 if (out.mode === "effect") {
231 const redisHealth = (yield* getJson(out.redisUrl!, "/health")) as { pong?: boolean };
232 expect(redisHealth.pong).toEqual(true);
233 const bucketHealth = (yield* getJson(out.bucketUrl!, "/health")) as { ok?: boolean };
234 expect(bucketHealth.ok).toEqual(true);
235 } else {
236 const redisBody = yield* getText(out.redisUrl!);
237 expect(redisBody.length).toBeGreaterThan(0);
238 const bucketBody = yield* getText(out.bucketUrl!);
239 expect(bucketBody.length).toBeGreaterThan(0);
240 }
241 }).pipe(logLevel),
242 { timeout: 120_000 },
243 );
244
245 describe("ReadWriteRedis", { tags: ["provider:railway:variable"] }, () => {
246 test(
247 "sets and gets a key",
248 Effect.gen(function* () {
249 const out = yield* stack;
250 if (out.mode === "effect") {
251 const written = (yield* getJson(out.redisUrl!, "/set")) as { ok?: boolean };
252 expect(written.ok).toEqual(true);
253 const read = (yield* getJson(out.redisUrl!, "/get")) as {
254 ok?: boolean;
255 value?: string;
256 };
257 expect(read.ok).toEqual(true);
258 expect(read.value).toEqual(REDIS_VALUE);
259 return;
260 }
261
262 // Public image fallback: docker push is impossible without a
263 // registry. ReadWriteRedis still packed REDIS_URL onto the
264 // Service; set/get runs over the public TCP proxy.
265 const cacheVars = yield* distilled(
266 readServiceVariables(out.redisProjectId, out.redisEnvironmentId, out.cacheServiceId),
267 );
268 const password = cacheVars[Railway.REDIS_PASSWORD_ENV];
269 expect(password !== undefined && password.length > 0).toEqual(true);
270
271 const url = Railway.redisConnectionUrl({
272 host: out.proxyDomain,
273 port: out.proxyPort,
274 password: password!,
275 });
276 const pong = yield* Railway.runRedisCommand(url, "PING").pipe(
277 Effect.retry({ schedule: Schedule.spaced("4 seconds"), times: 10 }),
278 );
279 expect(String(pong).toUpperCase()).toContain("PONG");
280 yield* Railway.runRedisCommand(url, "SET", ["marker", REDIS_VALUE]);
281 const got = yield* Railway.runRedisCommand(url, "GET", ["marker"]);
282 expect(got).toEqual(REDIS_VALUE);
283 }).pipe(logLevel),
284 { timeout: 120_000 },
285 );
286 });
287
288 describe(
289 "PutObject / GetObject",
290 { tags: ["provider:aws", "provider:aws:s3", "provider:railway:variable"] },
291 () => {
292 test(
293 "puts and gets an object",
294 Effect.gen(function* () {
295 const out = yield* stack;
296 if (out.mode === "effect") {
297 const put = (yield* getJson(out.bucketUrl!, "/put")) as { ok?: boolean };
298 expect(put.ok).toEqual(true);
299 const got = (yield* getJson(out.bucketUrl!, "/get")) as {
300 ok?: boolean;
301 text?: string;
302 };
303 expect(got.ok).toEqual(true);
304 expect(got.text).toEqual(OBJECT_BODY);
305 return;
306 }
307
308 // Public image fallback: docker push is impossible without a
309 // registry. PutObject/GetObject still packed AWS_* onto the
310 // Service; put/get runs over the S3 API from the test process.
311 const vars = yield* distilled(
312 readServiceVariables(
313 out.bucketProjectId,
314 out.bucketEnvironmentId,
315 out.bucketServiceId,
316 ),
317 );
318 expect((vars.AWS_ACCESS_KEY_ID ?? "").length).toBeGreaterThan(0);
319 expect((vars.BUCKET_NAME ?? "").length).toBeGreaterThan(0);
320
321 const creds = yield* distilled(
322 firstCredentials(out.bucketId, out.bucketEnvironmentId, out.bucketProjectId),
323 );
324 yield* withBucketS3(
325 creds,
326 S3.putObject({
327 Bucket: creds.bucketName,
328 Key: OBJECT_KEY,
329 Body: OBJECT_BODY,
330 ContentType: "text/plain",
331 }),
332 );
333 const got = yield* withBucketS3(
334 creds,
335 S3.getObject({ Bucket: creds.bucketName, Key: OBJECT_KEY }),
336 );
337 const text =
338 got.Body === undefined ? "" : yield* Stream.mkString(Stream.decodeText(got.Body));
339 expect(text).toEqual(OBJECT_BODY);
340 }).pipe(logLevel),
341 { timeout: 120_000 },
342 );
343 },
344 );
345 },
346 );