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

main
ts 347 lines 13.6 KB
Raw
1 import * as GreengrassV2 from "@alchemy.run/aws/GreengrassV2";
2 import { Thing } from "@alchemy.run/aws/IoT";
3 import * as Lambda from "@alchemy.run/aws/Lambda";
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 const COMPONENT_NAME = "com.alchemy.test.GgBindings";
15 export const COMPONENT_VERSION = "1.0.0";
16
17 const recipe = JSON.stringify({
18 RecipeFormatVersion: "2020-01-25",
19 ComponentName: COMPONENT_NAME,
20 ComponentVersion: COMPONENT_VERSION,
21 ComponentDescription: "Alchemy GreengrassV2 bindings fixture component",
22 ComponentPublisher: "Alchemy",
23 Manifests: [
24 {
25 Platform: { os: "linux" },
26 Lifecycle: { run: "echo greengrass bindings fixture" },
27 },
28 ],
29 });
30
31 // A core device thing name that never exists — used to prove the
32 // core-device bindings' IAM + request plumbing via typed not-found errors.
33 const MISSING_CORE = "alchemy-gg-bindings-missing-core";
34
35 export class GreengrassTestFunction extends Lambda.Function<Lambda.Function>()(
36 "GreengrassTestFunction",
37 ) {}
38
39 /**
40 * Collapse a typed call into `{ ok: true }` or `{ ok: false, tag }`.
41 * Failures are logged (visible in CloudWatch) so unexpected tags are
42 * diagnosable without redeploying.
43 */
44 const probe = <A, E extends { readonly _tag: string }>(self: Effect.Effect<A, E>) =>
45 self.pipe(
46 Effect.map(() => ({ ok: true as const })),
47 Effect.catch((error) =>
48 Effect.logWarning(`probe failed: ${String(error)}`).pipe(
49 Effect.map(() => ({ ok: false as const, tag: error._tag })),
50 ),
51 ),
52 );
53
54 export default GreengrassTestFunction.make(
55 {
56 main,
57 functionUrl: true,
58 timeout: Duration.seconds(30),
59 },
60 Effect.gen(function* () {
61 // The component version + deployment the scoped bindings are bound to.
62 // The deployment targets an IoT thing with no live core device, so it
63 // stays ACTIVE in the cloud and never installs anything.
64 const component = yield* GreengrassV2.ComponentVersion("BindingComponent", {
65 recipe,
66 });
67 const core = yield* Thing("GgBindingCore", {});
68 const deployment = yield* GreengrassV2.Deployment("BindingRollout", {
69 targetArn: core.thingArn,
70 components: {
71 [COMPONENT_NAME]: { componentVersion: component.componentVersion },
72 },
73 });
74
75 // Event source: subscribe the host to Greengrass status events. The
76 // deploy proves the EventBridge rule + invoke permission wiring.
77 yield* GreengrassV2.consumeGreengrassEvents(
78 { kinds: ["deployment-status", "component-status"] },
79 (events) =>
80 Stream.runForEach(events, (event) =>
81 Effect.log(
82 `greengrass event: ${event["detail-type"]} on ${event.detail.coreDeviceThingName}`,
83 ),
84 ),
85 );
86
87 // Component-version-scoped bindings.
88 const getComponent = yield* GreengrassV2.GetComponent(component);
89 const describeComponent = yield* GreengrassV2.DescribeComponent(component);
90 const getArtifact = yield* GreengrassV2.GetComponentVersionArtifact(component);
91
92 // Deployment-scoped bindings.
93 const getDeployment = yield* GreengrassV2.GetDeployment(deployment);
94 const cancelDeployment = yield* GreengrassV2.CancelDeployment(deployment);
95
96 // Account-level bindings.
97 const listComponents = yield* GreengrassV2.ListComponents();
98 const listComponentVersions = yield* GreengrassV2.ListComponentVersions();
99 const listDeployments = yield* GreengrassV2.ListDeployments();
100 const listCoreDevices = yield* GreengrassV2.ListCoreDevices();
101 const getCoreDevice = yield* GreengrassV2.GetCoreDevice();
102 const deleteCoreDevice = yield* GreengrassV2.DeleteCoreDevice();
103 const listInstalledComponents = yield* GreengrassV2.ListInstalledComponents();
104 const listEffectiveDeployments = yield* GreengrassV2.ListEffectiveDeployments();
105 const listClientDevices = yield* GreengrassV2.ListClientDevicesAssociatedWithCoreDevice();
106 const associateClientDevices = yield* GreengrassV2.BatchAssociateClientDeviceWithCoreDevice();
107 const disassociateClientDevices =
108 yield* GreengrassV2.BatchDisassociateClientDeviceFromCoreDevice();
109 const getConnectivityInfo = yield* GreengrassV2.GetConnectivityInfo();
110 const updateConnectivityInfo = yield* GreengrassV2.UpdateConnectivityInfo();
111 const resolveComponentCandidates = yield* GreengrassV2.ResolveComponentCandidates();
112
113 const bound = {
114 getComponent,
115 describeComponent,
116 getArtifact,
117 getDeployment,
118 cancelDeployment,
119 listComponents,
120 listComponentVersions,
121 listDeployments,
122 listCoreDevices,
123 getCoreDevice,
124 deleteCoreDevice,
125 listInstalledComponents,
126 listEffectiveDeployments,
127 listClientDevices,
128 associateClientDevices,
129 disassociateClientDevices,
130 getConnectivityInfo,
131 updateConnectivityInfo,
132 resolveComponentCandidates,
133 };
134
135 return {
136 fetch: Effect.gen(function* () {
137 const request = yield* HttpServerRequest;
138 const url = new URL(request.originalUrl);
139 const pathname = url.pathname;
140
141 if (request.method === "GET" && pathname === "/bindings") {
142 return yield* HttpServerResponse.json({
143 bound: Object.keys(bound),
144 });
145 }
146
147 // Component-scoped read: the component version ARN is injected.
148 if (request.method === "GET" && pathname === "/component") {
149 const metadata = yield* describeComponent();
150 return yield* HttpServerResponse.json({
151 arn: metadata.arn,
152 componentName: metadata.componentName,
153 componentVersion: metadata.componentVersion,
154 state: metadata.status?.componentState,
155 });
156 }
157
158 // Fetch the raw recipe and prove it round-trips.
159 if (request.method === "GET" && pathname === "/recipe") {
160 const { recipe: bytes, recipeOutputFormat } = yield* getComponent({
161 recipeOutputFormat: "JSON",
162 });
163 const text = yield* Effect.sync(() => new TextDecoder().decode(bytes));
164 return yield* HttpServerResponse.json({
165 recipeOutputFormat,
166 hasName: text.includes(COMPONENT_NAME),
167 });
168 }
169
170 // The fixture component has no artifacts — the typed error proves
171 // IAM + request plumbing end-to-end.
172 if (request.method === "GET" && pathname === "/artifact") {
173 const result = yield* probe(getArtifact({ artifactName: "missing.zip" }));
174 return yield* HttpServerResponse.json(result);
175 }
176
177 // Deployment-scoped read: the deployment id is injected.
178 if (request.method === "GET" && pathname === "/deployment") {
179 const detail = yield* getDeployment();
180 return yield* HttpServerResponse.json({
181 deploymentId: detail.deploymentId,
182 deploymentStatus: detail.deploymentStatus,
183 targetArn: detail.targetArn,
184 isLatestForTarget: detail.isLatestForTarget,
185 });
186 }
187
188 // Account-level list, must include the fixture's deployment.
189 if (request.method === "GET" && pathname === "/deployments") {
190 const { deployments } = yield* listDeployments({
191 historyFilter: "LATEST_ONLY",
192 });
193 return yield* HttpServerResponse.json({
194 ids: (deployments ?? []).flatMap((d) =>
195 d.deploymentId === undefined ? [] : [d.deploymentId],
196 ),
197 });
198 }
199
200 // Account-level list, must include the fixture's component.
201 if (request.method === "GET" && pathname === "/components") {
202 const { components } = yield* listComponents({ scope: "PRIVATE" });
203 return yield* HttpServerResponse.json({
204 names: (components ?? []).flatMap((c) =>
205 c.componentName === undefined ? [] : [c.componentName],
206 ),
207 });
208 }
209
210 // List the fixture component's versions via its base ARN (derived
211 // at runtime from the version ARN).
212 if (request.method === "GET" && pathname === "/component-versions") {
213 const metadata = yield* describeComponent();
214 const baseArn = (metadata.arn ?? "").split(":versions:")[0]!;
215 const { componentVersions } = yield* listComponentVersions({
216 arn: baseArn,
217 });
218 return yield* HttpServerResponse.json({
219 versions: (componentVersions ?? []).flatMap((v) =>
220 v.componentVersion === undefined ? [] : [v.componentVersion],
221 ),
222 });
223 }
224
225 // Account-level list of core devices (usually empty in CI).
226 if (request.method === "GET" && pathname === "/core-devices") {
227 const { coreDevices } = yield* listCoreDevices();
228 return yield* HttpServerResponse.json({
229 count: (coreDevices ?? []).length,
230 });
231 }
232
233 // Core-device bindings probed against a thing name that never
234 // exists: typed not-found (never AccessDenied) proves IAM works.
235 if (request.method === "GET" && pathname === "/core-device-probes") {
236 const req = { coreDeviceThingName: MISSING_CORE };
237 return yield* HttpServerResponse.json({
238 getCoreDevice: yield* probe(getCoreDevice(req)),
239 deleteCoreDevice: yield* probe(deleteCoreDevice(req)),
240 listInstalledComponents: yield* probe(listInstalledComponents(req)),
241 listEffectiveDeployments: yield* probe(listEffectiveDeployments(req)),
242 listClientDevices: yield* probe(listClientDevices(req)),
243 associateClientDevices: yield* probe(
244 associateClientDevices({
245 ...req,
246 entries: [{ thingName: "alchemy-gg-bindings-client" }],
247 }),
248 ),
249 disassociateClientDevices: yield* probe(
250 disassociateClientDevices({
251 ...req,
252 entries: [{ thingName: "alchemy-gg-bindings-client" }],
253 }),
254 ),
255 });
256 }
257
258 // Real write+read on the fixture thing's connectivity info (the
259 // thing exists; no live core device is required).
260 if (request.method === "POST" && pathname === "/connectivity") {
261 const detail = yield* getDeployment();
262 const thingName = (detail.targetArn ?? "").split("/").pop()!;
263 yield* updateConnectivityInfo({
264 thingName,
265 connectivityInfo: [{ id: "fixture", hostAddress: "127.0.0.1", portNumber: 8883 }],
266 });
267 const { connectivityInfo } = yield* getConnectivityInfo({
268 thingName,
269 });
270 return yield* HttpServerResponse.json({
271 hostAddresses: (connectivityInfo ?? []).flatMap((info) =>
272 info.hostAddress === undefined ? [] : [info.hostAddress],
273 ),
274 });
275 }
276
277 // Dependency resolution against the fixture component.
278 if (request.method === "GET" && pathname === "/resolve") {
279 const result = yield* resolveComponentCandidates({
280 platform: {
281 attributes: { os: "linux", architecture: "amd64" },
282 },
283 componentCandidates: [
284 {
285 componentName: COMPONENT_NAME,
286 versionRequirements: { fixture: `=${COMPONENT_VERSION}` },
287 },
288 ],
289 }).pipe(
290 Effect.map((response) => ({
291 ok: true as const,
292 names: (response.resolvedComponentVersions ?? []).flatMap((v) =>
293 v.componentName === undefined ? [] : [v.componentName],
294 ),
295 })),
296 Effect.catch((error) =>
297 Effect.logWarning(`resolve failed: ${String(error)}`).pipe(
298 Effect.map(() => ({
299 ok: false as const,
300 names: [] as string[],
301 tag: error._tag,
302 })),
303 ),
304 ),
305 );
306 return yield* HttpServerResponse.json(result);
307 }
308
309 // Deployment-scoped write: cancel the fixture rollout (called last).
310 if (request.method === "POST" && pathname === "/cancel-deployment") {
311 const result = yield* probe(cancelDeployment());
312 return yield* HttpServerResponse.json(result);
313 }
314
315 return yield* HttpServerResponse.json(
316 { error: "Not found", method: request.method, pathname },
317 { status: 404 },
318 );
319 }).pipe(Effect.orDie),
320 };
321 }).pipe(
322 Effect.provide(
323 Layer.mergeAll(
324 Lambda.EventSource,
325 GreengrassV2.GetComponentHttp,
326 GreengrassV2.DescribeComponentHttp,
327 GreengrassV2.GetComponentVersionArtifactHttp,
328 GreengrassV2.GetDeploymentHttp,
329 GreengrassV2.CancelDeploymentHttp,
330 GreengrassV2.ListComponentsHttp,
331 GreengrassV2.ListComponentVersionsHttp,
332 GreengrassV2.ListDeploymentsHttp,
333 GreengrassV2.ListCoreDevicesHttp,
334 GreengrassV2.GetCoreDeviceHttp,
335 GreengrassV2.DeleteCoreDeviceHttp,
336 GreengrassV2.ListInstalledComponentsHttp,
337 GreengrassV2.ListEffectiveDeploymentsHttp,
338 GreengrassV2.ListClientDevicesAssociatedWithCoreDeviceHttp,
339 GreengrassV2.BatchAssociateClientDeviceWithCoreDeviceHttp,
340 GreengrassV2.BatchDisassociateClientDeviceFromCoreDeviceHttp,
341 GreengrassV2.GetConnectivityInfoHttp,
342 GreengrassV2.UpdateConnectivityInfoHttp,
343 GreengrassV2.ResolveComponentCandidatesHttp,
344 ),
345 ),
346 ),
347 );