@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 214 lines 7.1 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import * as Output from "alchemy/Output";
3 import * as Effect from "effect/Effect";
4 import { HttpServerRequest } from "effect/http/HttpServerRequest";
5 import * as HttpServerResponse from "effect/http/HttpServerResponse";
6 import * as Layer from "effect/Layer";
7 import { MwaaNetwork } from "./network.ts";
8
9 export class MWAATestFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
10 "MWAATestFunction",
11 ) {}
12
13 /**
14 * Every route answers `{ …fields }` on success or `{ errorTag }` when the
15 * operation fails with a TYPED error — the test asserts on concrete fields
16 * (or a typed tag), which proves the binding wiring, the environment-name
17 * injection, and the IAM grants (environment-ARN-scoped for
18 * CliToken/GetEnvironment, Airflow-role-ARN-scoped for WebLoginToken and
19 * InvokeRestApi). An untyped error crashes into a 500.
20 */
21 const errorTagged = <A, E extends { _tag: string }, R>(
22 effect: Effect.Effect<A, E, R>,
23 ): Effect.Effect<A | { errorTag: string }, never, R> =>
24 effect.pipe(
25 Effect.map((a): A | { errorTag: string } => a),
26 Effect.catch((e) => Effect.succeed({ errorTag: e._tag })),
27 );
28
29 /**
30 * Environment-scoped binding fixture: deploys a real MWAA environment
31 * (~20-30 minutes to provision, billed hourly while it exists — skipped under
32 * `--fast`) plus its supporting cast (private VPC networking with a NAT
33 * gateway, versioned DAGs bucket, execution role) and a Lambda bound to all
34 * four MWAA bindings.
35 */
36 export default MWAATestFunction.make(
37 { main: import.meta.url, functionUrl: true },
38 Effect.gen(function* () {
39 const { subnetIds, securityGroupIds } = yield* MwaaNetwork(
40 "MWAABindingsNetwork",
41 "10.87.0.0/16",
42 );
43
44 const bucket = yield* AWS.S3.Bucket("MWAABindingsDags", {
45 versioning: "Enabled",
46 forceDestroy: true,
47 });
48
49 // The execution role Amazon MWAA and Airflow assume. Fixture-only wide
50 // grants; the interesting IAM (the scoped airflow:* statements) is what
51 // the bindings attach to the Lambda itself.
52 const role = yield* AWS.IAM.Role("MWAABindingsExecutionRole", {
53 assumeRolePolicyDocument: {
54 Version: "2012-10-17",
55 Statement: [
56 {
57 Effect: "Allow",
58 Principal: {
59 Service: ["airflow.amazonaws.com", "airflow-env.amazonaws.com"],
60 },
61 Action: ["sts:AssumeRole"],
62 },
63 ],
64 },
65 inlinePolicies: {
66 "mwaa-execution": {
67 Version: "2012-10-17",
68 Statement: [
69 {
70 Effect: "Allow",
71 Action: ["airflow:PublishMetrics"],
72 Resource: ["*"],
73 },
74 {
75 Effect: "Allow",
76 Action: ["s3:GetObject*", "s3:GetBucket*", "s3:List*"],
77 Resource: [bucket.bucketArn, Output.interpolate`${bucket.bucketArn}/*`],
78 },
79 {
80 Effect: "Allow",
81 Action: [
82 "logs:CreateLogStream",
83 "logs:CreateLogGroup",
84 "logs:PutLogEvents",
85 "logs:GetLogEvents",
86 "logs:GetLogRecord",
87 "logs:GetLogGroupFields",
88 "logs:GetQueryResults",
89 "logs:DescribeLogGroups",
90 ],
91 Resource: ["arn:aws:logs:*:*:log-group:airflow-*"],
92 },
93 {
94 Effect: "Allow",
95 Action: ["cloudwatch:PutMetricData"],
96 Resource: ["*"],
97 },
98 {
99 Effect: "Allow",
100 Action: [
101 "sqs:ChangeMessageVisibility",
102 "sqs:DeleteMessage",
103 "sqs:GetQueueAttributes",
104 "sqs:GetQueueUrl",
105 "sqs:ReceiveMessage",
106 "sqs:SendMessage",
107 ],
108 Resource: ["arn:aws:sqs:*:*:airflow-celery-*"],
109 },
110 ],
111 },
112 },
113 });
114
115 const environment = yield* AWS.MWAA.Environment("BindingsAirflow", {
116 executionRoleArn: role.roleArn,
117 sourceBucketArn: bucket.bucketArn,
118 dagS3Path: "dags",
119 subnetIds,
120 securityGroupIds,
121 environmentClass: "mw1.small",
122 maxWorkers: 2,
123 minWorkers: 1,
124 webserverAccessMode: "PUBLIC_ONLY",
125 tags: { fixture: "mwaa-bindings" },
126 });
127
128 const getEnvironment = yield* AWS.MWAA.GetEnvironment(environment);
129 const createCliToken = yield* AWS.MWAA.CreateCliToken(environment);
130 const createWebLoginToken = yield* AWS.MWAA.CreateWebLoginToken(environment);
131 const invokeRestApi = yield* AWS.MWAA.InvokeRestApi(environment);
132
133 const bound = {
134 getEnvironment,
135 createCliToken,
136 createWebLoginToken,
137 invokeRestApi,
138 };
139
140 return {
141 fetch: Effect.gen(function* () {
142 const request = yield* HttpServerRequest;
143 const url = new URL(request.originalUrl ?? request.url, "http://x");
144 const pathname = url.pathname;
145
146 if (pathname === "/bindings") {
147 return yield* HttpServerResponse.json({ bound: Object.keys(bound) });
148 }
149
150 if (pathname === "/environment") {
151 const result = yield* errorTagged(getEnvironment());
152 return yield* HttpServerResponse.json(
153 "errorTag" in result
154 ? result
155 : {
156 status: result.Environment?.Status,
157 webserverUrl: result.Environment?.WebserverUrl,
158 },
159 );
160 }
161
162 if (pathname === "/cli-token") {
163 const result = yield* errorTagged(createCliToken());
164 return yield* HttpServerResponse.json(
165 "errorTag" in result
166 ? result
167 : {
168 // Never echo the Redacted token itself.
169 hasToken: result.CliToken !== undefined,
170 hostname: result.WebServerHostname,
171 },
172 );
173 }
174
175 if (pathname === "/web-login-token") {
176 const result = yield* errorTagged(createWebLoginToken());
177 return yield* HttpServerResponse.json(
178 "errorTag" in result
179 ? result
180 : {
181 hasToken: result.WebToken !== undefined,
182 hostname: result.WebServerHostname,
183 airflowIdentity: result.AirflowIdentity,
184 },
185 );
186 }
187
188 if (pathname === "/dags") {
189 const result = yield* errorTagged(invokeRestApi({ Method: "GET", Path: "/dags" }));
190 return yield* HttpServerResponse.json(
191 "errorTag" in result
192 ? result
193 : {
194 statusCode: result.RestApiStatusCode,
195 totalEntries: (result.RestApiResponse as { total_entries?: number } | undefined)
196 ?.total_entries,
197 },
198 );
199 }
200
201 return yield* HttpServerResponse.json({ error: "Not found", pathname }, { status: 404 });
202 }).pipe(Effect.orDie),
203 };
204 }).pipe(
205 Effect.provide(
206 Layer.mergeAll(
207 AWS.MWAA.GetEnvironmentHttp,
208 AWS.MWAA.CreateCliTokenHttp,
209 AWS.MWAA.CreateWebLoginTokenHttp,
210 AWS.MWAA.InvokeRestApiHttp,
211 ),
212 ),
213 ),
214 );