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

main
ts 188 lines 7.38 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { AWSEnvironment } from "@alchemy.run/aws/Environment";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as contacts from "@distilled.cloud/aws/ssm-contacts";
6 import * as incidents from "@distilled.cloud/aws/ssm-incidents";
7 import * as Effect from "effect/Effect";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as Result from "effect/Result";
10 import * as Schedule from "effect/Schedule";
11 import ContactsBindingsFunctionLive, { ContactsBindingsFunction } from "./bindings-handler.ts";
12
13 const { test } = Test.make({ providers: AWS.providers() });
14
15 // Ungated typed-error probes: prove the distilled error union carries the
16 // tags the runtime bindings depend on. On an account that has not onboarded
17 // Incident Manager every ssm-contacts call fails with the synthetic
18 // `IncidentManagerNotOnboarded` tag (patched from the overloaded
19 // ValidationException "Account not found for the request"); once onboarded,
20 // a missing engagement/rotation/channel is a plain
21 // `ResourceNotFoundException`.
22 test.provider(
23 "describeEngagement on a nonexistent engagement fails with a typed tag",
24 () =>
25 Effect.gen(function* () {
26 const { accountId, region } = yield* AWSEnvironment.current;
27 const error = yield* Effect.flip(
28 contacts.describeEngagement({
29 EngagementId: `arn:aws:ssm-contacts:${region}:${accountId}:engagement/alchemy-nonexistent-probe/00000000-0000-0000-0000-000000000000`,
30 }),
31 );
32 expect(["ResourceNotFoundException", "IncidentManagerNotOnboarded"]).toContain(error._tag);
33 }),
34 { tags: ["provider:aws", "provider:aws:ssmcontacts", "live"] },
35 );
36
37 test.provider(
38 "listRotationShifts on a nonexistent rotation fails with a typed tag",
39 () =>
40 Effect.gen(function* () {
41 const { accountId, region } = yield* AWSEnvironment.current;
42 const error = yield* Effect.flip(
43 contacts.listRotationShifts({
44 RotationId: `arn:aws:ssm-contacts:${region}:${accountId}:rotation/alchemy-nonexistent-probe`,
45 EndTime: new Date(Date.now() + 24 * 60 * 60 * 1000),
46 }),
47 );
48 // AWS reports an unresolvable rotation ARN as a ValidationException
49 // ("Invalid value provided - Invalid resource Arn ...") rather than a
50 // ResourceNotFoundException — typed as InvalidRotationArn.
51 expect([
52 "ResourceNotFoundException",
53 "IncidentManagerNotOnboarded",
54 "InvalidRotationArn",
55 ]).toContain(error._tag);
56 }),
57 { tags: ["provider:aws", "provider:aws:ssmcontacts", "live"] },
58 );
59
60 test.provider(
61 "sendActivationCode on a nonexistent channel fails with a typed tag",
62 () =>
63 Effect.gen(function* () {
64 const { accountId, region } = yield* AWSEnvironment.current;
65 const error = yield* Effect.flip(
66 contacts.sendActivationCode({
67 ContactChannelId: `arn:aws:ssm-contacts:${region}:${accountId}:contact-channel/alchemy-nonexistent-probe/11111111-1111-1111-1111-111111111111`,
68 }),
69 );
70 expect(["ResourceNotFoundException", "IncidentManagerNotOnboarded"]).toContain(error._tag);
71 }),
72 { tags: ["provider:aws", "provider:aws:ssmcontacts", "live"] },
73 );
74
75 // The bindings fixture needs the account-wide Incident Manager replication
76 // set. AWS deprecated CreateReplicationSet on Nov 7, 2025, so only accounts
77 // that were already onboarded can run the fixture — return the replication
78 // set ARN, or `undefined` when the account cannot be onboarded.
79 const ensureReplicationSet = Effect.gen(function* () {
80 const listed = yield* incidents.listReplicationSets({});
81 let arn = listed.replicationSetArns[0];
82 if (arn === undefined) {
83 const { region } = yield* AWSEnvironment.current;
84 const created = yield* Effect.result(
85 incidents.createReplicationSet({ regions: { [region]: {} } }),
86 );
87 if (Result.isFailure(created)) {
88 expect(created.failure._tag).toBe("UnsupportedOperationException");
89 return undefined;
90 }
91 arn = created.success.arn;
92 }
93 const status = yield* incidents.getReplicationSet({ arn }).pipe(
94 Effect.map((r) => r.replicationSet.status),
95 Effect.repeat({
96 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(60)]),
97 until: (status): boolean => status !== "CREATING" && status !== "UPDATING",
98 }),
99 );
100 expect(status).toBe("ACTIVE");
101 return arn;
102 });
103
104 // The runtime-binding fixture needs real contacts, which need the
105 // account-wide Incident Manager replication set — gated like the resource
106 // lifecycle test (AWS deprecated CreateReplicationSet on Nov 7, 2025, so
107 // only already-onboarded accounts can run this).
108 test.provider.skipIf(!process.env.AWS_TEST_INCIDENT_MANAGER)(
109 "bindings fixture: engagements, pages, rotation shifts, and overrides",
110 (stack) =>
111 Effect.gen(function* () {
112 const replicationSetArn = yield* ensureReplicationSet;
113 if (replicationSetArn === undefined) {
114 yield* Effect.logInfo(
115 "CreateReplicationSet is deprecated (Nov 7, 2025) and this account is not onboarded to Incident Manager — skipping the SSM Contacts bindings fixture",
116 );
117 return;
118 }
119 yield* stack.destroy();
120
121 const attrs = yield* stack.deploy(
122 Effect.gen(function* () {
123 return yield* ContactsBindingsFunction;
124 }).pipe(Effect.provide(ContactsBindingsFunctionLive)),
125 );
126 expect(attrs.functionUrl).toBeTruthy();
127 const baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
128
129 const client = yield* HttpClient.HttpClient;
130 const getJson = (path: string) =>
131 client
132 .get(`${baseUrl}${path}`)
133 .pipe(
134 Effect.flatMap((response) =>
135 response.status === 200
136 ? response.json
137 : Effect.flatMap(response.text, (body) =>
138 Effect.fail(new Error(`GET ${path} -> ${response.status}: ${body}`)),
139 ),
140 ),
141 );
142
143 // Lambda URL cold-start + IAM propagation on the fresh policy.
144 const bindings = (yield* getJson("/bindings").pipe(
145 Effect.retry({
146 schedule: Schedule.max([Schedule.exponential("2 seconds"), Schedule.recurs(30)]),
147 }),
148 )) as { bound: string[] };
149 expect(bindings.bound).toHaveLength(19);
150
151 const shifts = (yield* getJson("/shifts")) as { shifts: number; previewShifts: number };
152 expect(shifts.previewShifts).toBeGreaterThanOrEqual(0);
153
154 const override = (yield* getJson("/override")) as {
155 overrideId: string;
156 newContactIds: string[];
157 listed: number;
158 };
159 expect(override.overrideId).toBeTruthy();
160 expect(override.listed).toBeGreaterThanOrEqual(1);
161
162 const engage = (yield* getJson("/engage")) as {
163 engagementArn: string;
164 subject: string;
165 pages: number;
166 };
167 expect(engage.engagementArn).toContain(":engagement/");
168 expect(engage.subject).toBe("alchemy bindings fixture engagement");
169
170 const pages = (yield* getJson("/pages")) as { engagements: number; pages: number };
171 expect(pages.engagements).toBeGreaterThanOrEqual(1);
172
173 const channel = (yield* getJson("/channel")) as { ok: boolean };
174 expect(channel.ok).toBe(true);
175
176 yield* stack.destroy();
177 }),
178 {
179 tags: [
180 "provider:aws",
181 "provider:aws:lambda",
182 "provider:aws:ssmcontacts",
183 "provider:aws:ssmincidents",
184 "live",
185 ],
186 timeout: 600_000,
187 },
188 );