@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, 04:45 UTC

main
ts 221 lines 8.69 KB
Raw
1 import * as IAM from "@alchemy.run/aws/IAM";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as ResourceGroups from "@alchemy.run/aws/ResourceGroups";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import * as Layer from "effect/Layer";
9 import * as Stream from "effect/Stream";
10 import path from "pathe";
11
12 const main = path.resolve(import.meta.dirname, "handler.ts");
13
14 export class RGTestFunction extends Lambda.Function<Lambda.Function>()("RGTestFunction") {}
15
16 /** Return a typed error tag + message instead of failing the route. */
17 const tagOf = <A extends object, E extends { _tag: string; message?: string }>(
18 eff: Effect.Effect<A, E>,
19 ) =>
20 eff.pipe(
21 Effect.map((ok) => ({ ok })),
22 Effect.catch((e) => Effect.succeed({ errorTag: e._tag, message: e.message })),
23 );
24
25 export default RGTestFunction.make(
26 {
27 main,
28 functionUrl: true,
29 timeout: Duration.seconds(30),
30 },
31 Effect.gen(function* () {
32 // The group the group-scoped bindings are bound to. A capacity
33 // reservation pool group is one of the config types GroupResources /
34 // UngroupResources accept, and creating it is free (the pool starts
35 // empty and never acquires capacity).
36 const pool = yield* ResourceGroups.Group("BindingsPoolGroup", {
37 description: "alchemy resource-groups bindings fixture pool",
38 configuration: [
39 {
40 type: "AWS::ResourceGroups::Generic",
41 parameters: [
42 {
43 name: "allowed-resource-types",
44 values: ["AWS::EC2::CapacityReservation"],
45 },
46 ],
47 },
48 { type: "AWS::EC2::CapacityReservationPool" },
49 ],
50 });
51
52 // Role a tag-sync task would run as (tag-sync itself is gated: it is
53 // part of Group Lifecycle Events, in maintenance mode since 2026-07-30
54 // and closed to new customers, and even entitled accounts need an
55 // application group which CreateGroup cannot make — the /start-tag-sync
56 // route asserts the typed rejection).
57 const syncRole = yield* IAM.Role("BindingsTagSyncRole", {
58 assumeRolePolicyDocument: {
59 Version: "2012-10-17",
60 Statement: [
61 {
62 Effect: "Allow",
63 Principal: { Service: "resource-groups.amazonaws.com" },
64 Action: ["sts:AssumeRole"],
65 },
66 ],
67 },
68 });
69
70 // Event source: subscribe the host to group lifecycle events. The
71 // deploy proves the EventBridge rule + invoke permission wiring.
72 yield* ResourceGroups.consumeGroupEvents(
73 { kinds: ["state-change", "membership-change"] },
74 (events) =>
75 Stream.runForEach(events, (event) => Effect.log(`group event: ${event["detail-type"]}`)),
76 );
77
78 // --- group-scoped bindings ---
79 const listGroupResources = yield* ResourceGroups.ListGroupResources(pool);
80 const listGroupingStatuses = yield* ResourceGroups.ListGroupingStatuses(pool);
81 const groupResources = yield* ResourceGroups.GroupResources(pool);
82 const ungroupResources = yield* ResourceGroups.UngroupResources(pool);
83 const startTagSyncTask = yield* ResourceGroups.StartTagSyncTask(pool, syncRole);
84
85 // --- account-level bindings ---
86 const searchResources = yield* ResourceGroups.SearchResources();
87 const getAccountSettings = yield* ResourceGroups.GetAccountSettings();
88 const listTagSyncTasks = yield* ResourceGroups.ListTagSyncTasks();
89 const getTagSyncTask = yield* ResourceGroups.GetTagSyncTask();
90 const cancelTagSyncTask = yield* ResourceGroups.CancelTagSyncTask();
91
92 const bound = {
93 listGroupResources,
94 listGroupingStatuses,
95 groupResources,
96 ungroupResources,
97 startTagSyncTask,
98 searchResources,
99 getAccountSettings,
100 listTagSyncTasks,
101 getTagSyncTask,
102 cancelTagSyncTask,
103 };
104
105 return {
106 fetch: Effect.gen(function* () {
107 const request = yield* HttpServerRequest;
108 const url = new URL(request.originalUrl);
109 const pathname = url.pathname;
110
111 if (request.method === "GET" && pathname === "/bindings") {
112 return yield* HttpServerResponse.json({
113 bound: Object.keys(bound),
114 });
115 }
116
117 // Group-scoped read: the group name is injected from the binding.
118 if (request.method === "GET" && pathname === "/members") {
119 const { Resources } = yield* listGroupResources();
120 return yield* HttpServerResponse.json({
121 arns: (Resources ?? []).map((r) => r.Identifier?.ResourceArn),
122 });
123 }
124
125 // Group-scoped write: the API accepts the request and reports the
126 // per-resource outcome (a Lambda ARN is not poolable, so it lands
127 // in Failed with a typed error code — proving the full wire loop).
128 if (request.method === "POST" && pathname === "/group") {
129 const { arn } = (yield* request.json) as { arn: string };
130 const out = yield* groupResources({ ResourceArns: [arn] });
131 return yield* HttpServerResponse.json({
132 succeeded: out.Succeeded ?? [],
133 failedCodes: (out.Failed ?? []).map((f) => f.ErrorCode),
134 pending: (out.Pending ?? []).map((p) => p.ResourceArn),
135 });
136 }
137 if (request.method === "POST" && pathname === "/ungroup") {
138 const { arn } = (yield* request.json) as { arn: string };
139 const out = yield* ungroupResources({ ResourceArns: [arn] });
140 return yield* HttpServerResponse.json({
141 succeeded: out.Succeeded ?? [],
142 failedCodes: (out.Failed ?? []).map((f) => f.ErrorCode),
143 });
144 }
145
146 // Grouping statuses only exist for application groups (which
147 // CreateGroup cannot make) — the typed rejection proves the wire.
148 if (request.method === "GET" && pathname === "/grouping-statuses") {
149 return yield* HttpServerResponse.json(yield* tagOf(listGroupingStatuses()));
150 }
151
152 // Account-level ad-hoc query.
153 if (request.method === "GET" && pathname === "/search") {
154 const { ResourceIdentifiers } = yield* searchResources({
155 ResourceQuery: {
156 Type: "TAG_FILTERS_1_0",
157 Query: JSON.stringify({
158 ResourceTypeFilters: ["AWS::AllSupported"],
159 TagFilters: [{ Key: "alchemy::id", Values: ["RGTestFunction"] }],
160 }),
161 },
162 });
163 return yield* HttpServerResponse.json({
164 arns: (ResourceIdentifiers ?? []).map((r) => r.ResourceArn),
165 });
166 }
167
168 if (request.method === "GET" && pathname === "/account-settings") {
169 const { AccountSettings } = yield* getAccountSettings();
170 return yield* HttpServerResponse.json({
171 status: AccountSettings?.GroupLifecycleEventsStatus,
172 });
173 }
174
175 if (request.method === "GET" && pathname === "/tag-sync-tasks") {
176 const { TagSyncTasks } = yield* listTagSyncTasks({});
177 return yield* HttpServerResponse.json({
178 count: (TagSyncTasks ?? []).length,
179 });
180 }
181
182 // Tag-sync is application-group-only: the typed rejections prove
183 // IAM + wiring for the start/get/cancel operations.
184 if (request.method === "POST" && pathname === "/start-tag-sync") {
185 return yield* HttpServerResponse.json(
186 yield* tagOf(startTagSyncTask({ TagKey: "alchemy-rg-sync", TagValue: "on" })),
187 );
188 }
189 if (request.method === "GET" && pathname === "/tag-sync-task") {
190 const taskArn = url.searchParams.get("arn") ?? "";
191 return yield* HttpServerResponse.json(yield* tagOf(getTagSyncTask({ TaskArn: taskArn })));
192 }
193 if (request.method === "POST" && pathname === "/cancel-tag-sync") {
194 const { arn } = (yield* request.json) as { arn: string };
195 return yield* HttpServerResponse.json(yield* tagOf(cancelTagSyncTask({ TaskArn: arn })));
196 }
197
198 return yield* HttpServerResponse.json(
199 { error: "Not found", method: request.method, pathname },
200 { status: 404 },
201 );
202 }).pipe(Effect.orDie),
203 };
204 }).pipe(
205 Effect.provide(
206 Layer.mergeAll(
207 Lambda.EventSource,
208 ResourceGroups.ListGroupResourcesHttp,
209 ResourceGroups.ListGroupingStatusesHttp,
210 ResourceGroups.GroupResourcesHttp,
211 ResourceGroups.UngroupResourcesHttp,
212 ResourceGroups.StartTagSyncTaskHttp,
213 ResourceGroups.SearchResourcesHttp,
214 ResourceGroups.GetAccountSettingsHttp,
215 ResourceGroups.ListTagSyncTasksHttp,
216 ResourceGroups.GetTagSyncTaskHttp,
217 ResourceGroups.CancelTagSyncTaskHttp,
218 ),
219 ),
220 ),
221 );