@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 152 lines 5.96 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 logs from "@distilled.cloud/aws/cloudwatch-logs";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as HttpBody from "effect/http/HttpBody";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as Schedule from "effect/Schedule";
10 import LogEventSinkFunctionLive, { LogEventSinkFunction } from "./sink-handler.ts";
11
12 const { test } = Test.make({ providers: AWS.providers() });
13
14 class FunctionNotReady extends Data.TaggedError("FunctionNotReady") {}
15
16 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
17 readonly status: number;
18 }> {}
19
20 class EventsNotVisible extends Data.TaggedError("EventsNotVisible")<{
21 readonly missing: readonly string[];
22 }> {}
23
24 /** Poll the fixture's /ready route until it serves the resolved log target. */
25 const waitForReady = (url: string) =>
26 Effect.gen(function* () {
27 const response = yield* HttpClient.get(url);
28 if (response.status !== 200) {
29 return yield* Effect.fail(new FunctionNotReady());
30 }
31 // A fresh function URL can briefly 200 before the captured env (the log
32 // group name) has propagated — keep polling until it is a string.
33 const json = (yield* response.json) as any;
34 if (typeof json?.logGroupName === "string" && typeof json?.logStreamName === "string") {
35 return {
36 logGroupName: json.logGroupName as string,
37 logStreamName: json.logStreamName as string,
38 };
39 }
40 return yield* Effect.fail(new FunctionNotReady());
41 }).pipe(
42 Effect.retry({
43 while: (error) => error._tag === "FunctionNotReady",
44 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]),
45 }),
46 );
47
48 /** POST a JSON body to the fixture, retrying transient 5xx cold-start noise. */
49 const postJson = (url: string, body: unknown) =>
50 Effect.gen(function* () {
51 const response = yield* HttpClient.post(url, {
52 body: yield* HttpBody.json(body),
53 });
54 if (response.status >= 500) {
55 return yield* Effect.fail(new TransientUpstream({ status: response.status }));
56 }
57 return yield* response.json;
58 }).pipe(
59 Effect.retry({
60 while: (e) => e._tag === "TransientUpstream",
61 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(6)]),
62 }),
63 );
64
65 /**
66 * Out-of-band read: poll GetLogEvents until every marker is visible in the
67 * stream (ingestion lags a few seconds), returning the observed messages.
68 */
69 const waitForEvents = (logGroupName: string, logStreamName: string, markers: readonly string[]) =>
70 Effect.gen(function* () {
71 const result = yield* logs.getLogEvents({
72 logGroupName,
73 logStreamName,
74 startFromHead: true,
75 });
76 const messages = (result.events ?? []).map((event) => event.message ?? "");
77 const missing = markers.filter(
78 (marker) => !messages.some((message) => message.includes(marker)),
79 );
80 if (missing.length > 0) {
81 return yield* Effect.fail(new EventsNotVisible({ missing }));
82 }
83 return messages;
84 }).pipe(
85 Effect.retry({
86 // Ride out both ingestion lag and the brief post-create window where
87 // the stream is not yet describable.
88 while: (e) => e._tag === "EventsNotVisible" || e._tag === "ResourceNotFoundException",
89 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(30)]),
90 }),
91 );
92
93 test.provider(
94 "LogEventSink streams events through a deployed Lambda and drops rejected events",
95 (stack) =>
96 Effect.gen(function* () {
97 // Leading destroy reconciles away any partial deployment left behind by
98 // a previous crashed run (physical names are deterministic, so the
99 // re-deploy adopts and the trailing destroy cleans up).
100 yield* stack.destroy();
101
102 const fn = yield* stack.deploy(
103 LogEventSinkFunction.pipe(Effect.provide(LogEventSinkFunctionLive)),
104 );
105 const baseUrl = fn.functionUrl!.replace(/\/+$/, "");
106
107 const { logGroupName, logStreamName } = yield* waitForReady(`${baseUrl}/ready`);
108
109 // 25 markers through the sink in one request-scoped drain.
110 const markers = Array.from({ length: 25 }, (_, i) => `sink-${i}-${crypto.randomUUID()}`);
111 const response = yield* postJson(`${baseUrl}/sink`, {
112 messages: markers,
113 });
114 expect((response as any).ok).toBe(true);
115 expect((response as any).count).toBe(markers.length);
116
117 // Out-of-band: read the stream directly via distilled.
118 yield* waitForEvents(logGroupName, logStreamName, markers);
119
120 // Partial rejection: PutLogEvents has no transient per-event failure
121 // mode, so the partial-failure path the API supports is permanent
122 // rejection — an event >2h in the future is skipped by the API while
123 // the valid events in the same batch are still ingested. The sink must
124 // drop it (REJECT, no retry) and complete without error.
125 const validMarkers = Array.from({ length: 3 }, (_, i) => `valid-${i}-${crypto.randomUUID()}`);
126 const rejectedMarker = `rejected-${crypto.randomUUID()}`;
127 const rejectedResponse = yield* postJson(`${baseUrl}/sink-with-rejected`, {
128 valid: validMarkers,
129 rejected: rejectedMarker,
130 });
131 expect((rejectedResponse as any).ok).toBe(true);
132
133 const messages = yield* waitForEvents(logGroupName, logStreamName, validMarkers);
134 // The rejected (too-new) event was never ingested.
135 expect(messages.some((message) => message.includes(rejectedMarker))).toBe(false);
136
137 yield* stack.destroy();
138
139 // Assert the sink's log group is gone after the final destroy.
140 const remaining = yield* logs.describeLogGroups({
141 logGroupNamePrefix: logGroupName,
142 limit: 1,
143 });
144 expect((remaining.logGroups ?? []).some((group) => group.logGroupName === logGroupName)).toBe(
145 false,
146 );
147 }),
148 {
149 tags: ["provider:aws", "provider:aws:lambda", "provider:aws:logs", "live"],
150 timeout: 240_000,
151 },
152 );