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

main
ts 316 lines 12.6 KB
Raw
1 import * as Backup from "@alchemy.run/aws/Backup";
2 import * as IAM from "@alchemy.run/aws/IAM";
3 import * as Lambda from "@alchemy.run/aws/Lambda";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import * as Stream from "effect/Stream";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "handler.ts");
12
13 // Deterministic fixture names — distinct from the lifecycle suite's vault so
14 // the two test files stay quota- and state-independent.
15 export const FIXTURE_VAULT_NAME = "alchemy-test-backup-bindings-vault";
16
17 // Well-formed-but-nonexistent identifiers used to drive typed error paths.
18 // An IAM gap would surface AccessDeniedException (a 500 through the
19 // handler's orDie), so a typed not-found tag proves the grant end-to-end.
20 const BOGUS_JOB_ID = "00000000-0000-0000-0000-000000000000";
21 const BOGUS_RECOVERY_POINT_ARN = "arn:aws:ec2:us-east-1::snapshot/snap-00000000000000000";
22
23 export class BackupTestFunction extends Lambda.Function<Lambda.Function>()("BackupTestFunction") {}
24
25 export default BackupTestFunction.make(
26 {
27 main,
28 functionUrl: true,
29 },
30 Effect.gen(function* () {
31 const vault = yield* Backup.BackupVault("BindingsVault", {
32 backupVaultName: FIXTURE_VAULT_NAME,
33 });
34 // The role AWS Backup assumes for backup/copy/restore jobs started by
35 // the runtime bindings.
36 const backupRole = yield* IAM.Role("BindingsBackupRole", {
37 assumeRolePolicyDocument: {
38 Version: "2012-10-17",
39 Statement: [
40 {
41 Effect: "Allow",
42 Principal: { Service: "backup.amazonaws.com" },
43 Action: ["sts:AssumeRole"],
44 },
45 ],
46 },
47 managedPolicyArns: [
48 "arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup",
49 "arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores",
50 ],
51 });
52
53 // --- vault-scoped bindings ---
54 const listRecoveryPointsByBackupVault = yield* Backup.ListRecoveryPointsByBackupVault(vault);
55 const describeRecoveryPoint = yield* Backup.DescribeRecoveryPoint(vault);
56 const getRecoveryPointRestoreMetadata = yield* Backup.GetRecoveryPointRestoreMetadata(vault);
57 // Bound (compile + IAM coverage) but not routed: needs a live recovery
58 // point to delete deterministically.
59 const deleteRecoveryPoint = yield* Backup.DeleteRecoveryPoint(vault);
60
61 // --- job-start bindings (vault/role injection) ---
62 // Bound but not routed to a live start: an on-demand job takes minutes
63 // and burns storage; StartRestoreJob is driven through its typed
64 // not-found path instead.
65 const startBackupJob = yield* Backup.StartBackupJob(vault, backupRole);
66 const startCopyJob = yield* Backup.StartCopyJob(vault, backupRole);
67 const startRestoreJob = yield* Backup.StartRestoreJob(backupRole);
68
69 // --- account-level bindings ---
70 const describeBackupJob = yield* Backup.DescribeBackupJob();
71 const listBackupJobs = yield* Backup.ListBackupJobs();
72 const stopBackupJob = yield* Backup.StopBackupJob();
73 const describeRestoreJob = yield* Backup.DescribeRestoreJob();
74 const listRestoreJobs = yield* Backup.ListRestoreJobs();
75 // Restore-testing validation flow — the canonical Backup runtime use:
76 // AWS invokes a validation Lambda after a restore test; it inspects the
77 // restored resource and reports the verdict.
78 const getRestoreJobMetadata = yield* Backup.GetRestoreJobMetadata();
79 const putRestoreValidationResult = yield* Backup.PutRestoreValidationResult();
80 const describeCopyJob = yield* Backup.DescribeCopyJob();
81 const listCopyJobs = yield* Backup.ListCopyJobs();
82 const listProtectedResources = yield* Backup.ListProtectedResources();
83 const describeProtectedResource = yield* Backup.DescribeProtectedResource();
84 const getSupportedResourceTypes = yield* Backup.GetSupportedResourceTypes();
85 const listRecoveryPointsByResource = yield* Backup.ListRecoveryPointsByResource();
86
87 // --- event source ---
88 // Deploy-time: creates the EventBridge rule (default bus, source
89 // aws.backup) targeting this Function. Runtime firing needs a real
90 // backup job, so the test only verifies the subscription deploys.
91 yield* Backup.consumeBackupEvents({ kinds: ["backup-job", "restore-job"] }, (events) =>
92 Stream.runForEach(events, (event) => Effect.log(`backup event: ${event.detail.state}`)),
93 );
94
95 const bound = {
96 listRecoveryPointsByBackupVault,
97 describeRecoveryPoint,
98 deleteRecoveryPoint,
99 getRecoveryPointRestoreMetadata,
100 startBackupJob,
101 startCopyJob,
102 startRestoreJob,
103 describeBackupJob,
104 listBackupJobs,
105 stopBackupJob,
106 describeRestoreJob,
107 listRestoreJobs,
108 getRestoreJobMetadata,
109 putRestoreValidationResult,
110 describeCopyJob,
111 listCopyJobs,
112 listProtectedResources,
113 describeProtectedResource,
114 getSupportedResourceTypes,
115 listRecoveryPointsByResource,
116 };
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 if (request.method === "GET" && pathname === "/bindings") {
125 return yield* HttpServerResponse.json({
126 bound: Object.keys(bound),
127 });
128 }
129
130 if (request.method === "GET" && pathname === "/list-recovery-points") {
131 const result = yield* listRecoveryPointsByBackupVault({
132 MaxResults: 25,
133 });
134 return yield* HttpServerResponse.json({
135 count: (result.RecoveryPoints ?? []).length,
136 });
137 }
138
139 if (request.method === "GET" && pathname === "/list-backup-jobs") {
140 const result = yield* listBackupJobs({ MaxResults: 25 });
141 return yield* HttpServerResponse.json({
142 count: (result.BackupJobs ?? []).length,
143 });
144 }
145
146 if (request.method === "GET" && pathname === "/list-restore-jobs") {
147 const result = yield* listRestoreJobs({ MaxResults: 25 });
148 return yield* HttpServerResponse.json({
149 count: (result.RestoreJobs ?? []).length,
150 });
151 }
152
153 if (request.method === "GET" && pathname === "/list-copy-jobs") {
154 const result = yield* listCopyJobs({ MaxResults: 25 });
155 return yield* HttpServerResponse.json({
156 count: (result.CopyJobs ?? []).length,
157 });
158 }
159
160 if (request.method === "GET" && pathname === "/list-protected-resources") {
161 const result = yield* listProtectedResources({ MaxResults: 25 });
162 return yield* HttpServerResponse.json({
163 count: (result.Results ?? []).length,
164 });
165 }
166
167 if (request.method === "GET" && pathname === "/supported-resource-types") {
168 const result = yield* getSupportedResourceTypes();
169 return yield* HttpServerResponse.json({
170 resourceTypes: result.ResourceTypes ?? [],
171 });
172 }
173
174 if (request.method === "GET" && pathname === "/describe-backup-job-not-found") {
175 // Exercises the typed not-found error path end-to-end.
176 const result = yield* describeBackupJob({
177 BackupJobId: BOGUS_JOB_ID,
178 }).pipe(
179 Effect.map(() => ({ found: true })),
180 Effect.catchTag(["ResourceNotFoundException", "InvalidParameterValueException"], () =>
181 Effect.succeed({ found: false }),
182 ),
183 );
184 return yield* HttpServerResponse.json(result);
185 }
186
187 if (request.method === "GET" && pathname === "/describe-recovery-point-not-found") {
188 // Exercises BackupVaultName injection + the typed not-found path.
189 const result = yield* describeRecoveryPoint({
190 RecoveryPointArn: BOGUS_RECOVERY_POINT_ARN,
191 }).pipe(
192 Effect.map(() => ({ found: true })),
193 Effect.catchTag(["ResourceNotFoundException", "InvalidParameterValueException"], () =>
194 Effect.succeed({ found: false }),
195 ),
196 );
197 return yield* HttpServerResponse.json(result);
198 }
199
200 if (request.method === "GET" && pathname === "/restore-metadata-not-found") {
201 const result = yield* getRecoveryPointRestoreMetadata({
202 RecoveryPointArn: BOGUS_RECOVERY_POINT_ARN,
203 }).pipe(
204 Effect.map(() => ({ found: true })),
205 Effect.catchTag(["ResourceNotFoundException", "InvalidParameterValueException"], () =>
206 Effect.succeed({ found: false }),
207 ),
208 );
209 return yield* HttpServerResponse.json(result);
210 }
211
212 if (request.method === "GET" && pathname === "/restore-job-metadata-not-found") {
213 const result = yield* getRestoreJobMetadata({
214 RestoreJobId: BOGUS_JOB_ID,
215 }).pipe(
216 Effect.map(() => ({ found: true })),
217 Effect.catchTag(["ResourceNotFoundException", "InvalidParameterValueException"], () =>
218 Effect.succeed({ found: false }),
219 ),
220 );
221 return yield* HttpServerResponse.json(result);
222 }
223
224 if (request.method === "POST" && pathname === "/put-restore-validation-not-found") {
225 // A verdict can only be posted against a live restore-test job;
226 // drive the binding through its typed error path instead — an IAM
227 // gap would surface AccessDeniedException (500), not a typed tag.
228 const tag = yield* putRestoreValidationResult({
229 RestoreJobId: BOGUS_JOB_ID,
230 ValidationStatus: "SUCCESSFUL",
231 }).pipe(
232 Effect.map(() => "Accepted"),
233 Effect.catchTag(
234 [
235 "ResourceNotFoundException",
236 "InvalidParameterValueException",
237 "MissingParameterValueException",
238 "InvalidRequestException",
239 ],
240 (e) => Effect.succeed(e._tag),
241 ),
242 );
243 return yield* HttpServerResponse.json({ tag });
244 }
245
246 if (request.method === "POST" && pathname === "/stop-backup-job-not-found") {
247 const tag = yield* stopBackupJob({ BackupJobId: BOGUS_JOB_ID }).pipe(
248 Effect.map(() => "Stopped"),
249 Effect.catchTag(
250 [
251 "ResourceNotFoundException",
252 "InvalidParameterValueException",
253 "InvalidRequestException",
254 ],
255 (e) => Effect.succeed(e._tag),
256 ),
257 );
258 return yield* HttpServerResponse.json({ tag });
259 }
260
261 if (request.method === "POST" && pathname === "/start-restore-not-found") {
262 // A real restore needs a live recovery point; drive the binding
263 // (role injection + IAM grant) through its typed error path — an
264 // IAM gap would surface AccessDeniedException (500) instead.
265 const tag = yield* startRestoreJob({
266 RecoveryPointArn: BOGUS_RECOVERY_POINT_ARN,
267 Metadata: {},
268 }).pipe(
269 Effect.map(() => "Started"),
270 Effect.catchTag(
271 [
272 "ResourceNotFoundException",
273 "InvalidParameterValueException",
274 "MissingParameterValueException",
275 "InvalidRequestException",
276 ],
277 (e) => Effect.succeed(e._tag),
278 ),
279 );
280 return yield* HttpServerResponse.json({ tag });
281 }
282
283 return yield* HttpServerResponse.json(
284 { error: "Not found", method: request.method, pathname },
285 { status: 404 },
286 );
287 }).pipe(Effect.orDie),
288 };
289 }).pipe(
290 Effect.provide(
291 Layer.mergeAll(
292 Lambda.EventSource,
293 Backup.ListRecoveryPointsByBackupVaultHttp,
294 Backup.DescribeRecoveryPointHttp,
295 Backup.DeleteRecoveryPointHttp,
296 Backup.GetRecoveryPointRestoreMetadataHttp,
297 Backup.StartBackupJobHttp,
298 Backup.StartCopyJobHttp,
299 Backup.StartRestoreJobHttp,
300 Backup.DescribeBackupJobHttp,
301 Backup.ListBackupJobsHttp,
302 Backup.StopBackupJobHttp,
303 Backup.DescribeRestoreJobHttp,
304 Backup.ListRestoreJobsHttp,
305 Backup.GetRestoreJobMetadataHttp,
306 Backup.PutRestoreValidationResultHttp,
307 Backup.DescribeCopyJobHttp,
308 Backup.ListCopyJobsHttp,
309 Backup.ListProtectedResourcesHttp,
310 Backup.DescribeProtectedResourceHttp,
311 Backup.GetSupportedResourceTypesHttp,
312 Backup.ListRecoveryPointsByResourceHttp,
313 ),
314 ),
315 ),
316 );