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

main
ts 529 lines 22.1 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as SNS from "@distilled.cloud/aws/sns";
5 import * as SQS from "@distilled.cloud/aws/sqs";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as HttpClientRequest from "effect/http/HttpClientRequest";
10 import * as Schedule from "effect/Schedule";
11 import { SNSApiFunction, SNSApiFunctionLive, TopicAndQueue } from "./handler.ts";
12
13 const { test } = Test.make({ providers: AWS.providers() });
14
15 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(14)]);
16
17 describe.sequential(
18 "SNS Bindings",
19 { tags: ["provider:aws", "provider:aws:lambda", "provider:aws:sns", "provider:aws:sqs", "live"] },
20 () => {
21 test.provider(
22 "exercises the SNS bindings surface against a live fixture",
23 (stack) =>
24 Effect.gen(function* () {
25 yield* Effect.logInfo("SNS test setup: destroying previous resources");
26 if (!process.env.NO_DESTROY) {
27 yield* stack.destroy();
28 }
29
30 yield* Effect.logInfo("SNS test setup: deploying fixture");
31 const deployed = yield* stack.deploy(
32 Effect.gen(function* () {
33 const { topic, queue, subscription } = yield* TopicAndQueue;
34
35 const apiFunction = yield* SNSApiFunction;
36
37 return { apiFunction, topic, queue, subscription };
38 }).pipe(Effect.provide(SNSApiFunctionLive)),
39 );
40
41 const baseUrl = deployed.apiFunction.functionUrl!.replace(/\/+$/, "");
42 const queueUrl = deployed.queue.queueUrl;
43 const topicArn = deployed.topic.topicArn;
44 const subscriptionArn = deployed.subscription.subscriptionArn;
45
46 // Gate on an IAM-backed binding call (read-only GetTopicAttributes),
47 // not the no-op `/ready` route. A fresh role's inline policy is
48 // eventually consistent: the function code can be live (200 on
49 // `/ready`) seconds before STS has propagated the `sns:*` grants, so a
50 // `/ready` gate lets the first `/publish` race the propagation window
51 // and 500 with AuthorizationErrorException. Hitting `/topic-attributes`
52 // here waits until the policy is actually live before any assertions.
53 const readinessUrl = `${baseUrl}/topic-attributes`;
54 yield* Effect.logInfo(
55 `SNS test setup: probing IAM readiness at ${readinessUrl} (150s bounded budget)`,
56 );
57
58 yield* HttpClient.get(readinessUrl).pipe(
59 Effect.timeout("8 seconds"),
60 Effect.flatMap((response) =>
61 response.status === 200
62 ? Effect.succeed(response)
63 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
64 ),
65 Effect.tap(() => Effect.logInfo("SNS test setup: fixture responded successfully")),
66 Effect.tapError((error) =>
67 Effect.logWarning(`SNS test setup: fixture not ready yet (${String(error)})`),
68 ),
69 Effect.retry({ schedule: readinessPolicy }),
70 );
71
72 const getJson = (path: string) =>
73 HttpClient.get(`${baseUrl}${path}`).pipe(
74 Effect.tap((response) =>
75 Effect.flatMap(response.text, (text) =>
76 Effect.logInfo(`GET ${path} -> ${text.slice(0, 400)}`),
77 ),
78 ),
79 Effect.flatMap((response) => response.json),
80 Effect.timeout("20 seconds"),
81 );
82
83 const postJson = (path: string, body: unknown) =>
84 HttpClient.execute(
85 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}${path}`), body),
86 ).pipe(
87 Effect.tap((response) => Effect.flatMap(response.text, Effect.logInfo)),
88 Effect.flatMap((response) => response.json),
89 Effect.timeout("20 seconds"),
90 );
91
92 const deleteJson = (path: string, body: unknown) =>
93 HttpClient.execute(
94 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.delete(`${baseUrl}${path}`), body),
95 ).pipe(
96 Effect.flatMap((response) => response.json),
97 Effect.timeout("20 seconds"),
98 );
99
100 const bufferedQueueMessages: Array<{
101 message: string;
102 topicArn: string;
103 subject?: string;
104 }> = [];
105
106 const waitForQueueMessage = Effect.fn(function* (
107 predicate: (body: { message: string; topicArn: string; subject?: string }) => boolean,
108 ) {
109 const takeBuffered = () => {
110 const index = bufferedQueueMessages.findIndex(predicate);
111 return index < 0 ? undefined : bufferedQueueMessages.splice(index, 1)[0];
112 };
113
114 return yield* Effect.gen(function* () {
115 const buffered = takeBuffered();
116 if (buffered) return buffered;
117
118 const result = yield* SQS.receiveMessage({
119 QueueUrl: queueUrl,
120 MaxNumberOfMessages: 10,
121 WaitTimeSeconds: 5,
122 VisibilityTimeout: 30,
123 });
124 const messages = (result.Messages ?? []).filter(
125 (message) => message.Body && message.ReceiptHandle,
126 );
127 if (messages.length === 0) {
128 return yield* Effect.fail(new QueueMessageNotReady());
129 }
130
131 yield* Effect.forEach(
132 messages,
133 (message) =>
134 SQS.deleteMessage({ QueueUrl: queueUrl, ReceiptHandle: message.ReceiptHandle! }),
135 { concurrency: "unbounded" },
136 );
137 bufferedQueueMessages.push(
138 ...messages.map(
139 (message) =>
140 JSON.parse(message.Body!) as {
141 message: string;
142 topicArn: string;
143 subject?: string;
144 },
145 ),
146 );
147
148 const received = takeBuffered();
149 return yield* received
150 ? Effect.succeed(received)
151 : Effect.fail(new QueueMessageNotReady());
152 }).pipe(
153 // Five-second long polls keep the complete retry window below 45s.
154 Effect.retry({
155 while: (error) => error._tag === "QueueMessageNotReady",
156 schedule: Schedule.recurs(8),
157 }),
158 );
159 });
160
161 const waitForQueueMessages = Effect.fn(function* (count: number) {
162 const bodies: Array<{ message: string; topicArn: string; subject?: string }> = [];
163
164 while (bodies.length < count) {
165 bodies.push(yield* waitForQueueMessage(() => true));
166 }
167
168 return bodies;
169 });
170
171 // Publish
172 yield* Effect.gen(function* () {
173 const marker = `publish-${crypto.randomUUID()}`;
174 const response = yield* postJson("/publish", {
175 message: marker,
176 subject: "PublishTest",
177 });
178
179 expect((response as any).MessageId).toBeTruthy();
180
181 const queued = yield* waitForQueueMessage((body) => body.message === marker);
182 expect((queued as any).topicArn).toBe(topicArn);
183 expect((queued as any).subject).toBe("PublishTest");
184 });
185
186 // PublishBatch
187 yield* Effect.gen(function* () {
188 const first = `batch-1-${crypto.randomUUID()}`;
189 const second = `batch-2-${crypto.randomUUID()}`;
190
191 const response = yield* postJson("/publish-batch", { messages: [first, second] });
192
193 expect(((response as any).Successful ?? []).length).toBe(2);
194
195 const bodies = yield* waitForQueueMessages(2);
196 const messages = bodies.map((body) => body.message);
197 expect(messages).toContain(first);
198 expect(messages).toContain(second);
199 });
200
201 // GetTopicAttributes
202 yield* Effect.gen(function* () {
203 const response = yield* getJson("/topic-attributes");
204 expect((response as any).Attributes.TopicArn).toBe(topicArn);
205 });
206
207 // SetTopicAttributes — eventual consistency. SNS can take a few
208 // seconds to propagate a SetTopicAttributes change, and during
209 // that window GetTopicAttributes may return a payload without
210 // the updated key. Poll briefly.
211 yield* Effect.gen(function* () {
212 yield* postJson("/topic-attributes", {
213 name: "DisplayName",
214 value: "updated-display-name",
215 });
216
217 yield* Effect.gen(function* () {
218 const response = yield* getJson("/topic-attributes");
219 const displayName = (response as any).Attributes?.DisplayName;
220 if (displayName !== "updated-display-name") {
221 return yield* Effect.fail(new TopicAttributeNotPropagated());
222 }
223 }).pipe(
224 Effect.retry({
225 while: (e) => e._tag === "TopicAttributeNotPropagated",
226 schedule: Schedule.max([Schedule.fixed("1 second"), Schedule.recurs(15)]),
227 }),
228 );
229 });
230
231 // AddPermission
232 yield* Effect.gen(function* () {
233 yield* postJson("/add-permission", {});
234 const response = yield* getJson("/topic-attributes");
235 expect((response as any).Attributes.Policy).toContain("FixturePublishPermission");
236 });
237
238 // RemovePermission
239 yield* Effect.gen(function* () {
240 yield* postJson("/add-permission", {});
241 yield* postJson("/remove-permission", {});
242 const response = yield* getJson("/topic-attributes");
243 expect((response as any).Attributes.Policy ?? "").not.toContain(
244 "FixturePublishPermission",
245 );
246 });
247
248 // GetDataProtectionPolicy
249 yield* Effect.gen(function* () {
250 const response = yield* getJson("/data-protection-policy");
251 if ((response as any).ok === false) {
252 expect((response as any).error).toBeTruthy();
253 } else {
254 expect(response).toBeDefined();
255 }
256 });
257
258 // PutDataProtectionPolicy
259 yield* Effect.gen(function* () {
260 const response = yield* postJson("/data-protection-policy", { policy: "{}" });
261 expect(response).toBeDefined();
262 });
263
264 // ListTopics (account-wide) — the alchemy binding wraps SNS's
265 // single-page `ListTopics` operation, which returns up to 100 topics.
266 // On a busy account our brand-new topic may simply be on a later page,
267 // so just assert the binding works (returns an Array of topics). Our
268 // specific ARN is verified via the topic-scoped `topic-attributes`
269 // call above.
270 yield* Effect.gen(function* () {
271 const response = yield* getJson("/topics");
272 const topics = (response as any).Topics ?? [];
273 expect(Array.isArray(topics)).toBe(true);
274 });
275
276 // ListSubscriptions (account-wide) — the alchemy binding wraps
277 // SNS's single-page `ListSubscriptions` operation, which returns
278 // up to 100 subscriptions. On a busy account our brand-new
279 // subscription may simply be on a later page. Just assert the
280 // binding works (returns an Array of subscriptions). Our specific
281 // ARN is verified via the topic-scoped call below.
282 yield* Effect.gen(function* () {
283 const response = yield* getJson("/subscriptions");
284 const subscriptions = (response as any).Subscriptions ?? [];
285 expect(Array.isArray(subscriptions)).toBe(true);
286 });
287
288 // ListSubscriptionsByTopic — scoped to the topic we just created,
289 // so propagation is tight. SNS still has eventual consistency on
290 // brand-new subscriptions; poll for ~30s.
291 yield* Effect.gen(function* () {
292 const arns = yield* Effect.gen(function* () {
293 const response = yield* getJson("/subscriptions-by-topic");
294 const arns = ((response as any).Subscriptions ?? []).map(
295 (subscription: any) => subscription.SubscriptionArn,
296 );
297 if (!arns.includes(subscriptionArn)) {
298 return yield* Effect.fail(new SubscriptionNotListed());
299 }
300 return arns;
301 }).pipe(
302 Effect.retry({
303 while: (e) => e._tag === "SubscriptionNotListed",
304 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(15)]),
305 }),
306 );
307 expect(arns).toContain(subscriptionArn);
308 });
309
310 // ListTagsForResource
311 yield* Effect.gen(function* () {
312 const response = yield* getJson("/tags");
313 const keys = ((response as any).Tags ?? []).map((tag: any) => tag.Key);
314 expect(keys).toContain("alchemy::stack");
315 expect(keys).toContain("alchemy::stage");
316 expect(keys).toContain("alchemy::id");
317 });
318
319 // TagResource
320 yield* Effect.gen(function* () {
321 yield* postJson("/tags", { key: "sns-binding-test", value: "true" });
322 const response = yield* getJson("/tags");
323 const tags = Object.fromEntries(
324 ((response as any).Tags ?? []).map((tag: any) => [tag.Key, tag.Value]),
325 );
326 expect(tags["sns-binding-test"]).toBe("true");
327 });
328
329 // UntagResource
330 yield* Effect.gen(function* () {
331 yield* postJson("/tags", { key: "sns-remove-test", value: "true" });
332 yield* deleteJson("/tags", { keys: ["sns-remove-test"] });
333 const response = yield* getJson("/tags");
334 const keys = ((response as any).Tags ?? []).map((tag: any) => tag.Key);
335 expect(keys).not.toContain("sns-remove-test");
336 });
337
338 // GetSubscriptionAttributes
339 yield* Effect.gen(function* () {
340 const response = yield* getJson("/subscription-attributes");
341 expect((response as any).Attributes.Protocol).toBe("sqs");
342 });
343
344 // SetSubscriptionAttributes
345 yield* Effect.gen(function* () {
346 const response = yield* postJson("/subscription-attributes", {
347 name: "RawMessageDelivery",
348 value: "true",
349 }).pipe(
350 Effect.flatMap(() => getJson("/subscription-attributes")),
351 Effect.ensuring(
352 postJson("/subscription-attributes", {
353 name: "RawMessageDelivery",
354 value: "false",
355 }).pipe(Effect.ignore),
356 ),
357 );
358 expect((response as any).Attributes.RawMessageDelivery).toBe("true");
359 });
360
361 // ConfirmSubscription
362 yield* Effect.gen(function* () {
363 const response = yield* postJson("/confirm-subscription", { token: "invalid-token" });
364 expect((response as any).ok).toBe(false);
365 expect((response as any).error).toBeTruthy();
366 });
367
368 // Subscribe + Unsubscribe — subscribe the notifications queue at
369 // runtime, assert a concrete ARN came back, then unsubscribe it in
370 // the same request so no stray subscription survives.
371 yield* Effect.gen(function* () {
372 const response = yield* postJson("/subscribe-cycle", {});
373 expect((response as any).ok).toBe(true);
374 expect((response as any).subscriptionArn).toContain("arn:aws:sns:");
375 });
376
377 // GetSMSAttributes
378 yield* Effect.gen(function* () {
379 const response = yield* getJson("/sms/attributes");
380 expect((response as any).attributes).toBeDefined();
381 });
382
383 // SetSMSAttributes — set the default type to Transactional (a safe
384 // idempotent default for the testing account) and read it back.
385 yield* Effect.gen(function* () {
386 yield* postJson("/sms/attributes", { type: "Transactional" });
387 const response = yield* getJson("/sms/attributes");
388 expect((response as any).attributes.DefaultSMSType).toBe("Transactional");
389 });
390
391 // ListPhoneNumbersOptedOut
392 yield* Effect.gen(function* () {
393 const response = yield* getJson("/sms/opted-out");
394 expect(Array.isArray((response as any).phoneNumbers)).toBe(true);
395 });
396
397 // CheckIfPhoneNumberIsOptedOut — reserved fictional number; never
398 // opted out.
399 yield* Effect.gen(function* () {
400 const response = yield* postJson("/sms/check-opt-out", { phoneNumber: "+15555550100" });
401 expect((response as any).isOptedOut).toBe(false);
402 });
403
404 // OptInPhoneNumber — the fictional number was never opted out, so
405 // SNS either succeeds (no-op) or rejects with a typed error; both
406 // prove the binding + IAM wiring.
407 yield* Effect.gen(function* () {
408 const response = yield* postJson("/sms/opt-in", { phoneNumber: "+15555550100" });
409 expect(response).toBeDefined();
410 });
411
412 // ListOriginationNumbers
413 yield* Effect.gen(function* () {
414 const response = yield* getJson("/sms/origination-numbers");
415 expect(Array.isArray((response as any).PhoneNumbers)).toBe(true);
416 });
417
418 // GetSMSSandboxAccountStatus
419 yield* Effect.gen(function* () {
420 const response = yield* getJson("/sms/sandbox-status");
421 expect(typeof (response as any).IsInSandbox).toBe("boolean");
422 });
423
424 // ListSMSSandboxPhoneNumbers
425 yield* Effect.gen(function* () {
426 const response = yield* getJson("/sms/sandbox-numbers");
427 expect(Array.isArray((response as any).PhoneNumbers)).toBe(true);
428 });
429
430 // CreateSMSSandboxPhoneNumber — malformed number surfaces the typed
431 // error (never sends a real OTP text).
432 yield* Effect.gen(function* () {
433 const response = yield* postJson("/sms/sandbox-create", {
434 phoneNumber: "not-a-phone-number",
435 });
436 expect((response as any).ok).toBe(false);
437 expect((response as any).error).toBeTruthy();
438 });
439
440 // VerifySMSSandboxPhoneNumber — unregistered number surfaces the
441 // typed error.
442 yield* Effect.gen(function* () {
443 const response = yield* postJson("/sms/sandbox-verify", {
444 phoneNumber: "+15555550100",
445 otp: "000000",
446 });
447 expect((response as any).ok).toBe(false);
448 expect((response as any).error).toBeTruthy();
449 });
450
451 // DeleteSMSSandboxPhoneNumber — unregistered number surfaces the
452 // typed error (idempotent wiring proof).
453 yield* Effect.gen(function* () {
454 const response = yield* postJson("/sms/sandbox-delete", {
455 phoneNumber: "+15555550100",
456 });
457 expect((response as any).ok).toBe(false);
458 expect((response as any).error).toBeTruthy();
459 });
460
461 // PublishSms — in the SMS sandbox the fictional number is not
462 // verified so SNS rejects with a typed error; out of the sandbox it
463 // accepts and returns a MessageId. Either proves the binding.
464 yield* Effect.gen(function* () {
465 const response = yield* postJson("/sms/publish", {
466 phoneNumber: "+15555550100",
467 message: "alchemy sns binding test",
468 });
469 const ok =
470 typeof (response as any).MessageId === "string" || (response as any).ok === false;
471 expect(ok).toBe(true);
472 });
473
474 // ListPlatformApplications
475 yield* Effect.gen(function* () {
476 const response = yield* getJson("/platform/applications");
477 expect(Array.isArray((response as any).PlatformApplications)).toBe(true);
478 });
479
480 // TopicSink — 12 messages > the PublishBatch limit of 10, so the
481 // batched sink must split the chunk into 2 sequential API calls
482 // (10 + 2) and every message must still arrive.
483 yield* Effect.gen(function* () {
484 const prefix = `sink-${crypto.randomUUID()}`;
485 const markers = Array.from({ length: 12 }, (_, i) => `${prefix}-${i}`);
486
487 const response = yield* postJson("/sink", { messages: markers });
488 expect((response as any).ok).toBe(true);
489
490 const received: string[] = [];
491 while (received.length < markers.length) {
492 const body = yield* waitForQueueMessage((candidate) =>
493 candidate.message.startsWith(prefix),
494 );
495 received.push(body.message);
496 }
497 expect(received.sort()).toEqual([...markers].sort());
498 });
499
500 if (!process.env.NO_DESTROY) {
501 yield* stack.destroy();
502 yield* assertTopicGone(topicArn);
503 }
504 }),
505 { timeout: 240_000 },
506 );
507 },
508 );
509
510 class TopicStillExists extends Data.TaggedError("TopicStillExists") {}
511
512 // Out-of-band proof the trailing destroy left nothing behind: the fixture
513 // topic must be observably gone (typed NotFoundException) after destroy.
514 const assertTopicGone = Effect.fn(function* (topicArn: string) {
515 yield* SNS.getTopicAttributes({ TopicArn: topicArn }).pipe(
516 Effect.flatMap(() => Effect.fail(new TopicStillExists())),
517 Effect.retry({
518 while: (error) => error._tag === "TopicStillExists",
519 schedule: Schedule.exponential(100),
520 times: 8,
521 }),
522 Effect.catchTag("NotFoundException", () => Effect.void),
523 Effect.catchTag("InvalidParameterException", () => Effect.void),
524 );
525 });
526
527 class QueueMessageNotReady extends Data.TaggedError("QueueMessageNotReady") {}
528 class SubscriptionNotListed extends Data.TaggedError("SubscriptionNotListed") {}
529 class TopicAttributeNotPropagated extends Data.TaggedError("TopicAttributeNotPropagated") {}