@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 176 lines 6.89 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as eventbridge from "@distilled.cloud/aws/eventbridge";
5 import { Region } from "@distilled.cloud/aws/Region";
6 import * as SQS from "@distilled.cloud/aws/sqs";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
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 {
14 EndpointInfra,
15 EndpointTestFunction,
16 EndpointTestFunctionLive,
17 EndpointInfraLive,
18 type EndpointInfraOptions,
19 secondaryRegionOf,
20 } from "./fixtures/endpoint-handler.ts";
21
22 const { test } = Test.make({ providers: AWS.providers() });
23
24 const describeEndpoint = (name: string) =>
25 eventbridge
26 .describeEndpoint({ Name: name })
27 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)));
28
29 const describeBus = (name: string, region: string) =>
30 eventbridge.describeEventBus({ Name: name }).pipe(
31 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)),
32 Effect.provideService(Region, Effect.succeed(region)),
33 );
34
35 class FunctionNotReady extends Data.TaggedError("FunctionNotReady")<{ status: number }> {}
36 class EventNotDelivered extends Data.TaggedError("EventNotDelivered") {}
37
38 const deployFixture = (stack: Test.ScratchStack, options: EndpointInfraOptions) =>
39 stack.deploy(
40 Effect.gen(function* () {
41 const { primary, secondary, endpoint, queue } = yield* EndpointInfra;
42 const fn = yield* EndpointTestFunction;
43 return { primary, secondary, endpoint, queue, fn };
44 }).pipe(
45 Effect.provide(Layer.mergeAll(EndpointTestFunctionLive(options), EndpointInfraLive(options))),
46 ),
47 );
48
49 /**
50 * Publish through the endpoint from the Lambda (SigV4A-signed PutEvents) and
51 * wait for the event on the primary bus's sink queue. The rule is new, so
52 * events published before it propagates are dropped: re-publish each round.
53 */
54 const publishUntilReceived = Effect.fn(function* (
55 baseUrl: string,
56 queueUrl: string,
57 marker: string,
58 ) {
59 yield* HttpClient.get(`${baseUrl}/health`).pipe(
60 Effect.flatMap((res) =>
61 res.status === 200 ? Effect.void : Effect.fail(new FunctionNotReady({ status: res.status })),
62 ),
63 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 45 }),
64 );
65 return yield* Effect.gen(function* () {
66 const res = yield* HttpClient.execute(
67 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/publish`), { marker }),
68 );
69 const text = yield* res.text;
70 expect(res.status, text).toBe(200);
71 const published = JSON.parse(text) as {
72 failedEntryCount: number;
73 entries: Array<{ EventId?: string }>;
74 };
75 expect(published.failedEntryCount, text).toBe(0);
76 expect(published.entries[0]?.EventId).toBeTruthy();
77
78 const received = yield* SQS.receiveMessage({
79 QueueUrl: queueUrl,
80 MaxNumberOfMessages: 10,
81 WaitTimeSeconds: 5,
82 });
83 const match = (received.Messages ?? []).find((m) => m.Body?.includes(marker));
84 if (!match) return yield* new EventNotDelivered();
85 return JSON.parse(match.Body!) as { source: string; detail: { marker: string } };
86 }).pipe(
87 Effect.retry({
88 while: (e) => e._tag === "EventNotDelivered",
89 schedule: Schedule.spaced("3 seconds"),
90 times: 12,
91 }),
92 );
93 });
94
95 test.provider(
96 "global endpoint: create, publish through it, update in place, delete",
97 (stack) =>
98 Effect.gen(function* () {
99 yield* stack.destroy();
100 const secondaryRegion = secondaryRegionOf(yield* yield* Region);
101
102 const created = yield* deployFixture(stack, { description: "initial", replication: true });
103 const { endpoint, primary, secondary } = created;
104
105 expect(endpoint.endpointArn).toContain(`:endpoint/${endpoint.endpointName}`);
106 expect(endpoint.endpointUrl).toContain(endpoint.endpointId);
107 expect(endpoint.eventBusArns).toEqual([primary.eventBusArn, secondary.eventBusArn]);
108 // The secondary bus lives in the failover region under the same name.
109 expect(secondary.eventBusName).toBe(primary.eventBusName);
110 expect(secondary.eventBusArn).toContain(`:events:${secondaryRegion}:`);
111 expect((yield* describeBus(secondary.eventBusName, secondaryRegion))?.Arn).toBe(
112 secondary.eventBusArn,
113 );
114
115 const live = yield* describeEndpoint(endpoint.endpointName);
116 expect(live?.State).toBe("ACTIVE");
117 expect(live?.Description).toBe("initial");
118 expect(live?.ReplicationConfig?.State).toBe("ENABLED");
119 expect(live?.RoutingConfig?.FailoverConfig?.Secondary?.Route).toBe(secondaryRegion);
120 expect(live?.RoutingConfig?.FailoverConfig?.Primary?.HealthCheck).toMatch(
121 /^arn:aws:route53:::healthcheck\//,
122 );
123
124 // A caller signing for another region — any publisher after a
125 // failover, or one running in the secondary region — still reaches the
126 // endpoint: its SigV4A signature is valid in every region, where a
127 // region-scoped SigV4 one fails with "Credential should be scoped to a
128 // valid region".
129 const fromSecondary = yield* eventbridge
130 .putEvents({
131 EndpointId: endpoint.endpointId,
132 Entries: [
133 {
134 Source: "alchemy.test.endpoint",
135 DetailType: "FromSecondaryRegion",
136 Detail: "{}",
137 EventBusName: primary.eventBusName,
138 },
139 ],
140 })
141 .pipe(Effect.provideService(Region, Effect.succeed(secondaryRegion)));
142 expect(fromSecondary.FailedEntryCount ?? 0).toBe(0);
143
144 const event = yield* publishUntilReceived(
145 created.fn.functionUrl!.replace(/\/+$/, ""),
146 created.queue.queueUrl,
147 "through-global-endpoint",
148 );
149 expect(event.source).toBe("alchemy.test.endpoint");
150 expect(event.detail.marker).toBe("through-global-endpoint");
151
152 // Description and replication update in place: same endpoint id.
153 const updated = yield* deployFixture(stack, { description: "updated", replication: false });
154 expect(updated.endpoint.endpointId).toBe(endpoint.endpointId);
155 const afterUpdate = yield* describeEndpoint(endpoint.endpointName);
156 expect(afterUpdate?.State).toBe("ACTIVE");
157 expect(afterUpdate?.Description).toBe("updated");
158 expect(afterUpdate?.ReplicationConfig?.State).toBe("DISABLED");
159
160 yield* stack.destroy();
161
162 expect(yield* describeEndpoint(endpoint.endpointName)).toBeUndefined();
163 expect(yield* describeBus(secondary.eventBusName, secondaryRegion)).toBeUndefined();
164 expect(yield* describeBus(primary.eventBusName, yield* yield* Region)).toBeUndefined();
165 }),
166 {
167 tags: [
168 "provider:aws",
169 "provider:aws:eventbridge",
170 "provider:aws:lambda",
171 "provider:aws:route53",
172 "live",
173 ],
174 timeout: 420_000,
175 },
176 );