@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 232 lines 8.61 KB
Raw
1 import * as CloudFormation from "@alchemy.run/aws/CloudFormation";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Duration from "effect/Duration";
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 Result from "effect/Result";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "handler.ts");
12
13 /** Deterministic, account-unique export name for the fixture stack. */
14 export const FIXTURE_EXPORT_NAME = "AlchemyCfnBindingsExport";
15
16 // A tiny, free template: one SSM String parameter, one exported output.
17 const template = JSON.stringify({
18 Resources: {
19 Param: {
20 Type: "AWS::SSM::Parameter",
21 Properties: { Type: "String", Value: "cfn-bindings-fixture" },
22 },
23 },
24 Outputs: {
25 ParamName: {
26 Value: { Ref: "Param" },
27 Export: { Name: FIXTURE_EXPORT_NAME },
28 },
29 },
30 });
31
32 /**
33 * Probe helper: run the bound operation and report either the success
34 * projection or the typed error tag, so the test can assert that operations
35 * rejected by CloudFormation fail with a TYPED tag (never an untyped
36 * catch-all).
37 */
38 const tagOr = <A, E extends { _tag: string }, R>(
39 effect: Effect.Effect<A, E, R>,
40 onSuccess: (value: A) => Record<string, unknown>,
41 ) =>
42 Effect.result(effect).pipe(
43 Effect.map((result) =>
44 Result.isSuccess(result) ? onSuccess(result.success) : { errorTag: result.failure._tag },
45 ),
46 );
47
48 export class CfnTestFunction extends Lambda.Function<Lambda.Function>()("CfnTestFunction") {}
49
50 export default CfnTestFunction.make(
51 {
52 main,
53 functionUrl: true,
54 // Above the 3s AWS default: describe/list calls plus distilled's bounded
55 // retries must complete within the invocation.
56 timeout: Duration.seconds(30),
57 },
58 Effect.gen(function* () {
59 const stack = yield* CloudFormation.Stack("BindingsStack", {
60 templateBody: template,
61 });
62
63 const describeStacks = yield* CloudFormation.DescribeStacks(stack);
64 const describeStackEvents = yield* CloudFormation.DescribeStackEvents(stack);
65 const describeStackResources = yield* CloudFormation.DescribeStackResources(stack);
66 const listStackResources = yield* CloudFormation.ListStackResources(stack);
67 const getTemplate = yield* CloudFormation.GetTemplate(stack);
68 const detectStackDrift = yield* CloudFormation.DetectStackDrift(stack);
69 const describeStackResourceDrifts = yield* CloudFormation.DescribeStackResourceDrifts(stack);
70 const signalResource = yield* CloudFormation.SignalResource(stack);
71 const listExports = yield* CloudFormation.ListExports();
72 const listImports = yield* CloudFormation.ListImports();
73 const describeStackDriftDetectionStatus =
74 yield* CloudFormation.DescribeStackDriftDetectionStatus();
75 const validateTemplate = yield* CloudFormation.ValidateTemplate();
76
77 return {
78 fetch: Effect.gen(function* () {
79 const request = yield* HttpServerRequest;
80 const url = new URL(request.originalUrl);
81 const pathname = url.pathname;
82
83 if (request.method === "GET" && pathname === "/describe") {
84 const result = yield* describeStacks();
85 const live = result.Stacks?.[0];
86 return yield* HttpServerResponse.json({
87 stackId: live?.StackId,
88 status: live?.StackStatus,
89 outputs: Object.fromEntries(
90 (live?.Outputs ?? []).map((o) => [o.OutputKey, o.OutputValue]),
91 ),
92 });
93 }
94
95 if (request.method === "GET" && pathname === "/events") {
96 const result = yield* describeStackEvents();
97 return yield* HttpServerResponse.json({
98 count: (result.StackEvents ?? []).length,
99 statuses: (result.StackEvents ?? []).slice(0, 5).map((e) => e.ResourceStatus),
100 });
101 }
102
103 if (request.method === "GET" && pathname === "/resources") {
104 const result = yield* describeStackResources({
105 LogicalResourceId: "Param",
106 });
107 const resource = result.StackResources?.[0];
108 return yield* HttpServerResponse.json({
109 logicalId: resource?.LogicalResourceId,
110 physicalId: resource?.PhysicalResourceId,
111 type: resource?.ResourceType,
112 });
113 }
114
115 if (request.method === "GET" && pathname === "/list-resources") {
116 const result = yield* listStackResources();
117 return yield* HttpServerResponse.json({
118 types: (result.StackResourceSummaries ?? []).map((r) => r.ResourceType),
119 });
120 }
121
122 if (request.method === "GET" && pathname === "/template") {
123 const result = yield* getTemplate();
124 return yield* HttpServerResponse.json({
125 template: result.TemplateBody,
126 });
127 }
128
129 if (request.method === "POST" && pathname === "/drift") {
130 const result = yield* detectStackDrift();
131 return yield* HttpServerResponse.json({
132 detectionId: result.StackDriftDetectionId,
133 });
134 }
135
136 if (request.method === "GET" && pathname === "/drift-status") {
137 const detectionId = url.searchParams.get("id") ?? undefined;
138 const result = yield* describeStackDriftDetectionStatus({
139 StackDriftDetectionId: detectionId,
140 });
141 return yield* HttpServerResponse.json({
142 detectionStatus: result.DetectionStatus,
143 stackDriftStatus: result.StackDriftStatus,
144 });
145 }
146
147 if (request.method === "GET" && pathname === "/resource-drifts") {
148 const result = yield* describeStackResourceDrifts();
149 return yield* HttpServerResponse.json({
150 drifts: (result.StackResourceDrifts ?? []).map((d) => ({
151 logicalId: d.LogicalResourceId,
152 status: d.StackResourceDriftStatus,
153 })),
154 });
155 }
156
157 if (request.method === "GET" && pathname === "/exports") {
158 const result = yield* listExports();
159 return yield* HttpServerResponse.json({
160 names: (result.Exports ?? []).map((e) => e.Name),
161 });
162 }
163
164 if (request.method === "GET" && pathname === "/imports") {
165 const name = url.searchParams.get("name") ?? FIXTURE_EXPORT_NAME;
166 // Nothing imports the fixture export — CloudFormation rejects the
167 // call with a typed ValidationError, proving IAM + typed errors.
168 return yield* HttpServerResponse.json(
169 yield* tagOr(listImports({ ExportName: name }), (result) => ({
170 imports: result.Imports ?? [],
171 })),
172 );
173 }
174
175 if (request.method === "POST" && pathname === "/validate") {
176 const body = (yield* request.json) as unknown as {
177 template?: string;
178 };
179 return yield* HttpServerResponse.json(
180 yield* tagOr(
181 validateTemplate({
182 TemplateBody: body.template ?? template,
183 }),
184 (result) => ({
185 parameters: (result.Parameters ?? []).map((p) => p.ParameterKey),
186 capabilities: result.Capabilities ?? [],
187 }),
188 ),
189 );
190 }
191
192 if (request.method === "POST" && pathname === "/signal") {
193 // CloudFormation accepts (and ignores) signals for resources that
194 // are not waiting on a CreationPolicy — success proves the IAM +
195 // binding wiring; a rejection would surface as a typed tag.
196 return yield* HttpServerResponse.json(
197 yield* tagOr(
198 signalResource({
199 LogicalResourceId: "Param",
200 UniqueId: "cfn-bindings-test",
201 Status: "SUCCESS",
202 }),
203 () => ({ ok: true }),
204 ),
205 );
206 }
207
208 return yield* HttpServerResponse.json(
209 { error: "Not found", method: request.method, pathname },
210 { status: 404 },
211 );
212 }).pipe(Effect.orDie),
213 };
214 }).pipe(
215 Effect.provide(
216 Layer.mergeAll(
217 CloudFormation.DescribeStacksHttp,
218 CloudFormation.DescribeStackEventsHttp,
219 CloudFormation.DescribeStackResourcesHttp,
220 CloudFormation.ListStackResourcesHttp,
221 CloudFormation.GetTemplateHttp,
222 CloudFormation.DetectStackDriftHttp,
223 CloudFormation.DescribeStackResourceDriftsHttp,
224 CloudFormation.SignalResourceHttp,
225 CloudFormation.ListExportsHttp,
226 CloudFormation.ListImportsHttp,
227 CloudFormation.DescribeStackDriftDetectionStatusHttp,
228 CloudFormation.ValidateTemplateHttp,
229 ),
230 ),
231 ),
232 );