@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 244 lines 8.86 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import * as Cause from "effect/Cause";
3 import * as Context from "effect/Context";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import * as Layer from "effect/Layer";
9 import * as Redacted from "effect/Redacted";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12
13 // Deterministic bucket for async synthesis output. Polly writes the audio
14 // with the CALLER's credentials, so the Lambda role is granted s3:PutObject
15 // on it via the AWS.S3.PutObject binding below.
16 export const BUCKET = "alchemy-test-polly-bindings";
17
18 // Lexicon names must match [0-9A-Za-z]{1,20} — exactly 20 characters.
19 export const LEXICON_NAME = "alchemyPollyBindings";
20
21 /** Checked-in W3C PLS document (never generated at test time). */
22 export const PLS_CONTENT = `<?xml version="1.0" encoding="UTF-8"?>
23 <lexicon version="1.0"
24 xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
25 alphabet="ipa" xml:lang="en-US">
26 <lexeme><grapheme>IaE</grapheme><alias>infrastructure as effects</alias></lexeme>
27 </lexicon>`;
28
29 export const SPEECH_TEXT = "Alchemy turns IaE into deployed infrastructure.";
30
31 export class PollyTestFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
32 "PollyTestFunction",
33 ) {}
34
35 /**
36 * Shared infrastructure for the Polly bindings fixture: the async-synthesis
37 * output bucket and the pronunciation lexicon the routes reference by name.
38 */
39 export class PollyFixtures extends Context.Service<
40 PollyFixtures,
41 {
42 bucket: AWS.S3.Bucket;
43 lexicon: AWS.Polly.Lexicon;
44 }
45 >()("PollyFixtures") {}
46
47 export const PollyFixturesLive = Layer.effect(
48 PollyFixtures,
49 Effect.gen(function* () {
50 const bucket = yield* AWS.S3.Bucket("PollyTaskOutput", {
51 bucketName: BUCKET,
52 forceDestroy: true,
53 });
54 const lexicon = yield* AWS.Polly.Lexicon("BindingsLexicon", {
55 lexiconName: LEXICON_NAME,
56 content: PLS_CONTENT,
57 });
58 return { bucket, lexicon };
59 }),
60 );
61
62 export default PollyTestFunction.make(
63 {
64 main: import.meta.url,
65 functionUrl: true,
66 timeout: Duration.minutes(2),
67 },
68 Effect.gen(function* () {
69 const { bucket, lexicon } = yield* PollyFixtures;
70
71 // --- bindings under test ---
72 const describeVoices = yield* AWS.Polly.DescribeVoices();
73 const listLexicons = yield* AWS.Polly.ListLexicons();
74 const getLexicon = yield* AWS.Polly.GetLexicon(lexicon);
75 const synthesizeSpeech = yield* AWS.Polly.SynthesizeSpeech();
76 const startSpeechSynthesisTask = yield* AWS.Polly.StartSpeechSynthesisTask();
77 const getSpeechSynthesisTask = yield* AWS.Polly.GetSpeechSynthesisTask();
78 const listSpeechSynthesisTasks = yield* AWS.Polly.ListSpeechSynthesisTasks();
79 const startSpeechSynthesisStream = yield* AWS.Polly.StartSpeechSynthesisStream();
80 // Grants the Lambda role s3:PutObject on the output bucket — Polly
81 // writes the async synthesis result with the caller's credentials.
82 yield* AWS.S3.PutObject(bucket);
83
84 const bound = {
85 describeVoices,
86 listLexicons,
87 getLexicon,
88 synthesizeSpeech,
89 startSpeechSynthesisTask,
90 getSpeechSynthesisTask,
91 listSpeechSynthesisTasks,
92 startSpeechSynthesisStream,
93 };
94
95 return {
96 fetch: Effect.gen(function* () {
97 const request = yield* HttpServerRequest;
98 const url = new URL(request.originalUrl);
99 const pathname = url.pathname;
100
101 // Cheap readiness route — no AWS call.
102 if (request.method === "GET" && pathname === "/ping") {
103 return yield* HttpServerResponse.json({
104 ok: true,
105 bound: Object.keys(bound),
106 });
107 }
108
109 if (request.method === "GET" && pathname === "/voices") {
110 const result = yield* describeVoices({ LanguageCode: "en-US" });
111 return yield* HttpServerResponse.json({
112 count: (result.Voices ?? []).length,
113 voiceIds: (result.Voices ?? []).map((voice) => voice.Id),
114 });
115 }
116
117 if (request.method === "GET" && pathname === "/lexicons") {
118 const result = yield* listLexicons();
119 return yield* HttpServerResponse.json({
120 names: (result.Lexicons ?? []).flatMap((lexicon) =>
121 lexicon.Name ? [lexicon.Name] : [],
122 ),
123 });
124 }
125
126 if (request.method === "GET" && pathname === "/lexicon-content") {
127 const result = yield* getLexicon();
128 const content = result.Lexicon?.Content;
129 const xml =
130 content === undefined
131 ? undefined
132 : Redacted.isRedacted(content)
133 ? Redacted.value(content)
134 : content;
135 return yield* HttpServerResponse.json({
136 name: result.Lexicon?.Name ?? null,
137 containsAlias: xml?.includes("infrastructure as effects") ?? false,
138 lexemesCount: result.LexiconAttributes?.LexemesCount ?? null,
139 });
140 }
141
142 if (request.method === "POST" && pathname === "/stream") {
143 const result = yield* startSpeechSynthesisStream({
144 Engine: "generative",
145 OutputFormat: "mp3",
146 VoiceId: "Matthew",
147 ActionStream: Stream.make(
148 { TextEvent: { Text: SPEECH_TEXT } },
149 { CloseStreamEvent: {} },
150 ),
151 });
152 const events = Array.from(yield* Stream.runCollect(result.EventStream!));
153 const audioBytes = events.reduce(
154 (total, event) => total + (event.AudioEvent?.AudioChunk?.length ?? 0),
155 0,
156 );
157 return yield* HttpServerResponse.json({
158 events: events.length,
159 audioBytes,
160 closed: events.some((event) => event.StreamClosedEvent !== undefined),
161 });
162 }
163
164 if (request.method === "GET" && pathname === "/synthesize") {
165 const result = yield* synthesizeSpeech({
166 Engine: "neural",
167 OutputFormat: "mp3",
168 VoiceId: "Joanna",
169 Text: SPEECH_TEXT,
170 LexiconNames: [LEXICON_NAME],
171 });
172 const chunks = yield* Stream.runCollect(result.AudioStream!);
173 const byteLength = Array.from(chunks).reduce((total, chunk) => total + chunk.length, 0);
174 return yield* HttpServerResponse.json({
175 contentType: result.ContentType,
176 byteLength,
177 });
178 }
179
180 if (request.method === "POST" && pathname === "/task") {
181 const started = yield* startSpeechSynthesisTask({
182 Engine: "neural",
183 OutputFormat: "mp3",
184 OutputS3BucketName: BUCKET,
185 OutputS3KeyPrefix: "task-output/",
186 VoiceId: "Joanna",
187 Text: SPEECH_TEXT,
188 });
189 const taskId = started.SynthesisTask?.TaskId!;
190
191 // A freshly started task can briefly 404; retry the typed tag,
192 // then poll (bounded) until the task leaves the queue.
193 const task = yield* getSpeechSynthesisTask({ TaskId: taskId }).pipe(
194 Effect.retry({
195 while: (e) => e._tag === "SynthesisTaskNotFoundException",
196 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(5)]),
197 }),
198 Effect.repeat({
199 schedule: Schedule.spaced("2 seconds"),
200 until: (r): boolean =>
201 r.SynthesisTask?.TaskStatus === "completed" ||
202 r.SynthesisTask?.TaskStatus === "failed",
203 times: 25,
204 }),
205 );
206
207 const listed = yield* listSpeechSynthesisTasks({ MaxResults: 10 });
208
209 return yield* HttpServerResponse.json({
210 taskId,
211 status: task.SynthesisTask?.TaskStatus ?? null,
212 statusReason: task.SynthesisTask?.TaskStatusReason ?? null,
213 outputUri: task.SynthesisTask?.OutputUri ?? null,
214 listedCount: (listed.SynthesisTasks ?? []).length,
215 });
216 }
217
218 return yield* HttpServerResponse.json(
219 { error: "Not found", method: request.method, pathname },
220 { status: 404 },
221 );
222 }).pipe(
223 // Surface every failure (typed error or defect) to the test as JSON
224 // instead of an opaque 500 — the test asserts `error` is absent.
225 Effect.catchCause((cause) => HttpServerResponse.json({ error: Cause.pretty(cause) })),
226 ),
227 };
228 }).pipe(
229 Effect.provide(
230 Layer.mergeAll(
231 AWS.Polly.DescribeVoicesHttp,
232 AWS.Polly.ListLexiconsHttp,
233 AWS.Polly.GetLexiconHttp,
234 AWS.Polly.SynthesizeSpeechHttp,
235 AWS.Polly.StartSpeechSynthesisTaskHttp,
236 AWS.Polly.GetSpeechSynthesisTaskHttp,
237 AWS.Polly.ListSpeechSynthesisTasksHttp,
238 AWS.Polly.StartSpeechSynthesisStreamHttp,
239 AWS.S3.PutObjectHttp,
240 PollyFixturesLive,
241 ),
242 ),
243 ),
244 );