The best way to control Claude Code, Codex and more from any computer or phone

main
ts 305 lines 12.3 KB
Raw
1 import * as IAM from "@alchemy.run/aws/IAM";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as S3 from "@alchemy.run/aws/S3";
4 import * as Translate from "@alchemy.run/aws/Translate";
5 import * as Cause from "effect/Cause";
6 import * as Context from "effect/Context";
7 import * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 import { HttpServerRequest } from "effect/http/HttpServerRequest";
10 import * as HttpServerResponse from "effect/http/HttpServerResponse";
11 import * as Layer from "effect/Layer";
12 import * as Redacted from "effect/Redacted";
13 import * as Schedule from "effect/Schedule";
14
15 // Deterministic fixture names (bucket names are account-global; this suite
16 // owns them in the testing account).
17 export const FIXTURE_BUCKET_NAME = "alchemy-test-translate-bindings";
18 export const TERMINOLOGY_NAME = "alchemy-translate-bindings-glossary";
19
20 // Checked-in CSV terminology — never generated at test time. The first row
21 // is the language-code header; each subsequent row is a term pair.
22 export const TERMINOLOGY_CSV = ["en,es", "Alchemy,Alquimia"].join("\n");
23
24 // Well-formed-but-nonexistent 32-hex-digit job id used to drive the typed
25 // ResourceNotFoundException paths. An IAM gap would surface
26 // AccessDeniedException (reported as `error` by the handler), so a typed
27 // not-found tag proves the grant end-to-end.
28 const BOGUS_JOB_ID = "00000000000000000000000000000000";
29
30 export class TranslateTestFunction extends Lambda.Function<Lambda.Function>()(
31 "TranslateTestFunction",
32 ) {}
33
34 /**
35 * Shared infrastructure for the Translate bindings fixture: the batch-job
36 * S3 bucket, the data-access role Translate assumes for batch jobs, and the
37 * custom terminology the routes reference by name.
38 */
39 export class TranslateFixtures extends Context.Service<
40 TranslateFixtures,
41 {
42 bucket: S3.Bucket;
43 dataAccessRole: IAM.Role;
44 terminology: Translate.Terminology;
45 }
46 >()("TranslateFixtures") {}
47
48 export const TranslateFixturesLive = Layer.effect(
49 TranslateFixtures,
50 Effect.gen(function* () {
51 const bucket = yield* S3.Bucket("TranslateJobBucket", {
52 bucketName: FIXTURE_BUCKET_NAME,
53 forceDestroy: true,
54 });
55 // The role Amazon Translate assumes to read input documents and write
56 // batch translation results.
57 const dataAccessRole = yield* IAM.Role("TranslateDataAccessRole", {
58 assumeRolePolicyDocument: {
59 Version: "2012-10-17",
60 Statement: [
61 {
62 Effect: "Allow",
63 Principal: { Service: "translate.amazonaws.com" },
64 Action: ["sts:AssumeRole"],
65 },
66 ],
67 },
68 inlinePolicies: {
69 s3Access: {
70 Version: "2012-10-17",
71 Statement: [
72 {
73 Effect: "Allow",
74 Action: ["s3:GetObject", "s3:ListBucket", "s3:PutObject"],
75 Resource: [
76 `arn:aws:s3:::${FIXTURE_BUCKET_NAME}`,
77 `arn:aws:s3:::${FIXTURE_BUCKET_NAME}/*`,
78 ],
79 },
80 ],
81 },
82 },
83 });
84 const terminology = yield* Translate.Terminology("BindingsGlossary", {
85 terminologyName: TERMINOLOGY_NAME,
86 file: TERMINOLOGY_CSV,
87 format: "CSV",
88 });
89 return { bucket, dataAccessRole, terminology };
90 }),
91 );
92
93 export default TranslateTestFunction.make(
94 {
95 main: import.meta.url,
96 functionUrl: true,
97 // The job lifecycle route retries StartTextTranslationJob through
98 // fresh-role IAM propagation (bounded ~40s).
99 timeout: Duration.seconds(120),
100 },
101 Effect.gen(function* () {
102 const { bucket, dataAccessRole } = yield* TranslateFixtures;
103
104 // --- bindings under test ---
105 const translateText = yield* Translate.TranslateText();
106 const translateDocument = yield* Translate.TranslateDocument();
107 const listLanguages = yield* Translate.ListLanguages();
108 const getTerminology = yield* Translate.GetTerminology();
109 const listTerminologies = yield* Translate.ListTerminologies();
110 const getParallelData = yield* Translate.GetParallelData();
111 const listParallelData = yield* Translate.ListParallelData();
112 const startTextTranslationJob = yield* Translate.StartTextTranslationJob(dataAccessRole);
113 const describeTextTranslationJob = yield* Translate.DescribeTextTranslationJob();
114 const stopTextTranslationJob = yield* Translate.StopTextTranslationJob();
115 const listTextTranslationJobs = yield* Translate.ListTextTranslationJobs();
116 const putObject = yield* S3.PutObject(bucket);
117
118 return {
119 fetch: Effect.gen(function* () {
120 const request = yield* HttpServerRequest;
121 const url = new URL(request.originalUrl);
122 const pathname = url.pathname;
123
124 // Cheap readiness route — no Translate call.
125 if (request.method === "GET" && pathname === "/ping") {
126 return yield* HttpServerResponse.json({ ok: true });
127 }
128
129 // TranslateText — plain and with the fixture terminology applied.
130 if (request.method === "GET" && pathname === "/translate") {
131 const basic = yield* translateText({
132 Text: "Hello, world!",
133 SourceLanguageCode: "en",
134 TargetLanguageCode: "es",
135 });
136 // NOTE: with "Alchemy" as the sentence-initial subject the model
137 // treats it as a brand name and declines to substitute the term;
138 // mid-sentence it applies reliably (verified with the raw API).
139 const withTerminology = yield* translateText({
140 Text: "I love Alchemy so much.",
141 SourceLanguageCode: "en",
142 TargetLanguageCode: "es",
143 TerminologyNames: [TERMINOLOGY_NAME],
144 });
145 return yield* HttpServerResponse.json({
146 basic: basic.TranslatedText,
147 withTerminology: withTerminology.TranslatedText,
148 appliedTerminologies: (withTerminology.AppliedTerminologies ?? []).map((t) => t.Name),
149 });
150 }
151
152 // TranslateDocument — plain-text document, decode the Redacted blob.
153 if (request.method === "GET" && pathname === "/document") {
154 const result = yield* translateDocument({
155 Document: {
156 Content: new TextEncoder().encode("Good morning, friend."),
157 ContentType: "text/plain",
158 },
159 SourceLanguageCode: "en",
160 TargetLanguageCode: "es",
161 });
162 const content = result.TranslatedDocument.Content;
163 const bytes = Redacted.isRedacted(content) ? Redacted.value(content) : content;
164 return yield* HttpServerResponse.json({
165 translated: new TextDecoder().decode(bytes),
166 sourceLanguageCode: result.SourceLanguageCode,
167 targetLanguageCode: result.TargetLanguageCode,
168 });
169 }
170
171 if (request.method === "GET" && pathname === "/languages") {
172 const result = yield* listLanguages({ MaxResults: 500 });
173 return yield* HttpServerResponse.json({
174 count: (result.Languages ?? []).length,
175 codes: (result.Languages ?? []).map((l) => l.LanguageCode),
176 });
177 }
178
179 // GetTerminology + ListTerminologies against the fixture glossary.
180 if (request.method === "GET" && pathname === "/terminologies") {
181 const got = yield* getTerminology({ Name: TERMINOLOGY_NAME });
182 const listed = yield* listTerminologies({ MaxResults: 100 });
183 return yield* HttpServerResponse.json({
184 name: got.TerminologyProperties?.Name ?? null,
185 termCount: got.TerminologyProperties?.TermCount ?? null,
186 sourceLanguageCode: got.TerminologyProperties?.SourceLanguageCode ?? null,
187 downloadLocation: got.TerminologyDataLocation?.RepositoryType ?? null,
188 listedNames: (listed.TerminologyPropertiesList ?? []).flatMap((t) =>
189 t.Name ? [t.Name] : [],
190 ),
191 });
192 }
193
194 // ListParallelData + GetParallelData's typed not-found path.
195 if (request.method === "GET" && pathname === "/parallel-data") {
196 const listed = yield* listParallelData({ MaxResults: 100 });
197 const missingTag = yield* getParallelData({
198 Name: "alchemy-nonexistent-parallel-data",
199 }).pipe(
200 Effect.map(() => "Found"),
201 Effect.catchTag("ResourceNotFoundException", (e) => Effect.succeed(e._tag)),
202 );
203 return yield* HttpServerResponse.json({
204 listedCount: (listed.ParallelDataPropertiesList ?? []).length,
205 missingTag,
206 });
207 }
208
209 // ListTextTranslationJobs + the Describe/Stop typed not-found paths.
210 if (request.method === "GET" && pathname === "/jobs") {
211 const listed = yield* listTextTranslationJobs({ MaxResults: 5 });
212 const describeTag = yield* describeTextTranslationJob({
213 JobId: BOGUS_JOB_ID,
214 }).pipe(
215 Effect.map(() => "Found"),
216 Effect.catchTag("ResourceNotFoundException", (e) => Effect.succeed(e._tag)),
217 );
218 const stopTag = yield* stopTextTranslationJob({
219 JobId: BOGUS_JOB_ID,
220 }).pipe(
221 Effect.map(() => "Stopped"),
222 Effect.catchTag("ResourceNotFoundException", (e) => Effect.succeed(e._tag)),
223 );
224 return yield* HttpServerResponse.json({
225 listedCount: (listed.TextTranslationJobPropertiesList ?? []).length,
226 describeTag,
227 stopTag,
228 });
229 }
230
231 // Full real lifecycle for a batch translation job: seed the input
232 // object, start the job, describe it, then stop it (the job never
233 // needs to complete — that takes tens of minutes).
234 if (request.method === "POST" && pathname === "/job-lifecycle") {
235 yield* putObject({
236 Key: "translate-input/greeting.txt",
237 Body: "Hello, world!\nAlchemy deploys infrastructure.\n",
238 ContentType: "text/plain",
239 });
240 // A freshly created data-access role can take a few seconds to
241 // become assumable by Translate — surfaced as
242 // InvalidParameterValueException/InvalidRequestException.
243 // Bounded retry (8 × 5s).
244 const started = yield* startTextTranslationJob({
245 JobName: "alchemy-translate-bindings-lifecycle",
246 InputDataConfig: {
247 S3Uri: `s3://${FIXTURE_BUCKET_NAME}/translate-input/`,
248 ContentType: "text/plain",
249 },
250 OutputDataConfig: {
251 S3Uri: `s3://${FIXTURE_BUCKET_NAME}/translate-output/`,
252 },
253 SourceLanguageCode: "en",
254 TargetLanguageCodes: ["es"],
255 }).pipe(
256 Effect.retry({
257 while: (e): boolean =>
258 e._tag === "InvalidParameterValueException" || e._tag === "InvalidRequestException",
259 schedule: Schedule.spaced("5 seconds"),
260 times: 8,
261 }),
262 );
263 const jobId = started.JobId ?? "";
264 const described = yield* describeTextTranslationJob({
265 JobId: jobId,
266 });
267 const stopped = yield* stopTextTranslationJob({ JobId: jobId });
268 return yield* HttpServerResponse.json({
269 jobId,
270 startStatus: started.JobStatus ?? null,
271 describedStatus: described.TextTranslationJobProperties?.JobStatus ?? null,
272 stopStatus: stopped.JobStatus ?? null,
273 });
274 }
275
276 return yield* HttpServerResponse.json(
277 { error: "Not found", method: request.method, pathname },
278 { status: 404 },
279 );
280 }).pipe(
281 // Surface every failure (typed error or defect) to the test as JSON
282 // instead of an opaque 500 — the test asserts `error` is absent.
283 Effect.catchCause((cause) => HttpServerResponse.json({ error: Cause.pretty(cause) })),
284 ),
285 };
286 }).pipe(
287 Effect.provide(
288 Layer.mergeAll(
289 Translate.TranslateTextHttp,
290 Translate.TranslateDocumentHttp,
291 Translate.ListLanguagesHttp,
292 Translate.GetTerminologyHttp,
293 Translate.ListTerminologiesHttp,
294 Translate.GetParallelDataHttp,
295 Translate.ListParallelDataHttp,
296 Translate.StartTextTranslationJobHttp,
297 Translate.DescribeTextTranslationJobHttp,
298 Translate.StopTextTranslationJobHttp,
299 Translate.ListTextTranslationJobsHttp,
300 S3.PutObjectHttp,
301 TranslateFixturesLive,
302 ),
303 ),
304 ),
305 );