@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 213 lines 7.55 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 eventarc from "@distilled.cloud/gcp/eventarc_v1";
5 import * as firestore from "@distilled.cloud/gcp/firestore_v1";
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 { LOCATION } from "../src/resources.ts";
15
16 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
17 providers: GCP.providers(),
18 state: Alchemy.localState(),
19 });
20
21 const { getWhenReady } = Test;
22
23 // Out-of-band calls to the Google APIs resolve the same stored credentials
24 // the deploy uses, so the test runs against the configured profile.
25 const GcpHttp = Layer.mergeAll(GCP.GcpAuth, GCP.fromAuthProvider(), FetchHttpClient.layer);
26
27 const TRIGGER_PATH = "/__alchemy/eventarc/ordercreated";
28
29 // Kept outside the handle so teardown can verify even after a failed test.
30 let deployed: { project: string; auditorService: string; databaseName: string } | undefined;
31
32 // Deploy, tests and destroy all sit behind the same Docker guard.
33 describe("gcp-eventarc-firestore", () => {
34 const stack = beforeAll(
35 deploy(Stack).pipe(
36 Effect.tap((outputs) =>
37 Effect.sync(() => {
38 deployed = outputs;
39 }),
40 ),
41 ),
42 { timeout: 900_000 },
43 );
44
45 /** The example's trigger, found by its delivery path and target service. */
46 const findTrigger = (project: string, auditor: string) =>
47 eventarc
48 .listProjectsLocationsTriggers({
49 parent: `projects/${project}/locations/${LOCATION}`,
50 })
51 .pipe(
52 Effect.map((page) =>
53 (page.triggers ?? []).find(
54 (trigger) =>
55 trigger.destination?.cloudRun?.path === TRIGGER_PATH &&
56 trigger.destination.cloudRun.service === auditor,
57 ),
58 ),
59 Effect.orDie,
60 Effect.provide(GcpHttp),
61 );
62
63 // Destroy, then prove the trigger and the database are actually gone.
64 afterAll.skipIf(!!process.env.NO_DESTROY)(
65 Effect.gen(function* () {
66 yield* destroy(Stack);
67 if (deployed === undefined) return;
68 const { project, auditorService, databaseName } = deployed;
69
70 expect(yield* findTrigger(project, auditorService)).toBeUndefined();
71
72 const database = yield* firestore.getProjectsDatabases({ name: databaseName }).pipe(
73 Effect.map((db) => db.name),
74 Effect.catchTag("NotFound", () => Effect.succeed(undefined)),
75 Effect.orDie,
76 Effect.provide(GcpHttp),
77 );
78 expect(database).toBeUndefined();
79 }),
80 { timeout: 600_000 },
81 );
82
83 const baseUrlOf = (url: string | undefined) => {
84 if (url === undefined) throw new Error("the service has no URL");
85 return url.replace(/\/+$/, "");
86 };
87
88 const createOrder = (baseUrl: string, item: string, quantity: number) =>
89 HttpClient.execute(
90 HttpClientRequest.post(`${baseUrl}/orders`).pipe(
91 HttpClientRequest.bodyJsonUnsafe({ item, quantity }),
92 ),
93 );
94
95 /**
96 * A fresh deploy's project-level Firestore grant can take several minutes
97 * to propagate, and not to every IAM backend at once; until it has, the
98 * API answers 500 (Forbidden from Firestore).
99 */
100 const createOrderWhenGranted = (baseUrl: string, item: string, quantity: number) =>
101 createOrder(baseUrl, item, quantity).pipe(
102 Effect.repeat({
103 schedule: Schedule.spaced("10 seconds"),
104 until: (response) => response.status !== 500,
105 times: 42,
106 }),
107 );
108
109 /** The auditor's `audit/{id}` entry, polled every 10s up to `times`. */
110 const auditOf = (databaseName: string, id: string, times: number) =>
111 firestore
112 .getProjectsDatabasesDocuments({
113 name: `${databaseName}/documents/audit/${id}`,
114 })
115 .pipe(
116 Effect.retry({
117 while: (error) => error._tag === "NotFound",
118 schedule: Schedule.spaced("10 seconds"),
119 times,
120 }),
121 Effect.provide(GcpHttp),
122 );
123
124 test(
125 "the trigger watches created orders in the named database",
126 Effect.gen(function* () {
127 const { project, auditorService, databaseId } = yield* stack;
128 const trigger = yield* findTrigger(project, auditorService);
129 expect(trigger?.name).toEqual(expect.any(String));
130
131 const filters = Object.fromEntries(
132 (trigger?.eventFilters ?? []).map((filter) => [
133 filter.attribute,
134 { value: filter.value, operator: filter.operator },
135 ]),
136 );
137 expect(filters.type?.value).toEqual("google.cloud.firestore.document.v1.created");
138 expect(filters.database?.value).toEqual(databaseId);
139 expect(filters.document).toEqual({
140 value: "orders/{id}",
141 operator: "match-path-pattern",
142 });
143 }),
144 { timeout: 120_000 },
145 );
146
147 test(
148 "rejects an order without an item",
149 Effect.gen(function* () {
150 const { url } = yield* stack;
151 const baseUrl = baseUrlOf(url);
152 yield* getWhenReady(`${baseUrl}/`);
153
154 const res = yield* HttpClient.execute(
155 HttpClientRequest.post(`${baseUrl}/orders`).pipe(
156 HttpClientRequest.bodyJsonUnsafe({ quantity: 1 }),
157 ),
158 );
159 expect(res.status).toBe(400);
160 }),
161 { timeout: 120_000 },
162 );
163
164 test(
165 "every created order gets an audit entry from the change event",
166 Effect.gen(function* () {
167 const { url, databaseName } = yield* stack;
168 const baseUrl = baseUrlOf(url);
169 yield* getWhenReady(`${baseUrl}/`);
170
171 // Eventarc can take a couple of minutes after the trigger reports
172 // healthy before it starts routing events, and a Firestore event
173 // emitted before then is never delivered. Probe with throwaway orders
174 // until one is audited; after that, every order must be.
175 yield* Effect.gen(function* () {
176 const probe = yield* createOrderWhenGranted(baseUrl, "probe", 1);
177 const { id } = (yield* probe.json) as { id: string };
178 return yield* auditOf(databaseName, id, 6);
179 }).pipe(Effect.retry({ times: 6 }), Effect.orDie);
180
181 const first = yield* createOrderWhenGranted(baseUrl, "widget", 2);
182 expect(first.status).toBe(201);
183 const second = yield* createOrderWhenGranted(baseUrl, "gadget", 1);
184 expect(second.status).toBe(201);
185
186 const ids = [
187 ((yield* first.json) as { id: string }).id,
188 ((yield* second.json) as { id: string }).id,
189 ];
190
191 for (const id of ids) {
192 // The order is a real Firestore document.
193 const order = yield* firestore
194 .getProjectsDatabasesDocuments({
195 name: `${databaseName}/documents/orders/${id}`,
196 })
197 .pipe(Effect.orDie, Effect.provide(GcpHttp));
198 expect(order.fields?.item?.stringValue).toBeDefined();
199
200 // A failed delivery (e.g. the auditor's grant still propagating) is
201 // redelivered with backoff, so give each audit a few minutes.
202 const audit = yield* auditOf(databaseName, id, 30).pipe(Effect.orDie);
203 expect(audit.fields?.order?.stringValue).toEqual(`orders/${id}`);
204 expect(audit.fields?.eventType?.stringValue).toEqual(
205 "google.cloud.firestore.document.v1.created",
206 );
207 // The protobuf payload reached the handler as bytes.
208 expect(Number(audit.fields?.payloadBytes?.integerValue ?? 0)).toBeGreaterThan(0);
209 }
210 }),
211 { timeout: 900_000 },
212 );
213 });