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

main
ts 150 lines 5.95 KB
Raw
1 import * as ApplicationAutoScaling from "@alchemy.run/aws/ApplicationAutoScaling";
2 import { Table } from "@alchemy.run/aws/DynamoDB";
3 import * as Lambda from "@alchemy.run/aws/Lambda";
4 import * as Output from "alchemy/Output";
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 Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import path from "pathe";
12
13 const main = path.resolve(import.meta.dirname, "handler.ts");
14
15 // The freshly attached IAM policy can take tens of seconds to propagate to
16 // the Application Auto Scaling endpoint after the fixture deploys — retry the
17 // typed AccessDeniedException on a short bounded schedule (~30s total).
18 const retryWhileIamPropagates = <A, E extends { _tag: string }, R>(
19 self: Effect.Effect<A, E, R>,
20 ): Effect.Effect<A, E, R> =>
21 Effect.retry(self, {
22 while: (e): boolean => e._tag === "AccessDeniedException",
23 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
24 });
25
26 export class ApplicationAutoScalingTestFunction extends Lambda.Function<Lambda.Function>()(
27 "ApplicationAutoScalingTestFunction",
28 ) {}
29
30 export default ApplicationAutoScalingTestFunction.make(
31 {
32 main,
33 functionUrl: true,
34 },
35 Effect.gen(function* () {
36 // A provisioned DynamoDB table is the cheapest, fastest real scalable
37 // resource (near-instant, free at 1 RCU/WCU).
38 const table = yield* Table("BindingsTable", {
39 partitionKey: "id",
40 attributes: { id: "S" },
41 billingMode: "PROVISIONED",
42 provisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 },
43 });
44 const target = yield* ApplicationAutoScaling.ScalableTarget("BindingsTarget", {
45 serviceNamespace: "dynamodb",
46 resourceId: Output.interpolate`table/${table.tableName}`,
47 scalableDimension: "dynamodb:table:ReadCapacityUnits",
48 minCapacity: 1,
49 maxCapacity: 5,
50 });
51 const policy = yield* ApplicationAutoScaling.ScalingPolicy("BindingsPolicy", {
52 serviceNamespace: target.serviceNamespace,
53 resourceId: target.resourceId,
54 scalableDimension: target.scalableDimension,
55 targetTracking: {
56 TargetValue: 70,
57 PredefinedMetricSpecification: {
58 PredefinedMetricType: "DynamoDBReadCapacityUtilization",
59 },
60 },
61 });
62
63 const describeScalingActivities =
64 yield* ApplicationAutoScaling.DescribeScalingActivities(target);
65 const getPredictiveScalingForecast =
66 yield* ApplicationAutoScaling.GetPredictiveScalingForecast(policy);
67
68 // Subscribe to scaling-activity state-change (scaled-to-max) events —
69 // creates the EventBridge rule + Lambda permission at deploy time.
70 yield* ApplicationAutoScaling.consumeScalingActivityEvents(target, {}, (events) =>
71 Stream.runForEach(events, (event) =>
72 Effect.log(
73 `${event["detail-type"]}: ${event.detail.resourceId} scaledToMax=${event.detail.scaledToMax}`,
74 ),
75 ),
76 );
77
78 const bound = {
79 describeScalingActivities,
80 getPredictiveScalingForecast,
81 };
82
83 return {
84 fetch: Effect.gen(function* () {
85 const request = yield* HttpServerRequest;
86 const url = new URL(request.originalUrl);
87 const pathname = url.pathname;
88
89 if (request.method === "GET" && pathname === "/bindings") {
90 return yield* HttpServerResponse.json({
91 bound: Object.keys(bound),
92 });
93 }
94
95 if (request.method === "GET" && pathname === "/scaling-activities") {
96 const result = yield* retryWhileIamPropagates(
97 describeScalingActivities({
98 MaxResults: 25,
99 IncludeNotScaledActivities: true,
100 }),
101 );
102 return yield* HttpServerResponse.json({
103 count: (result.ScalingActivities ?? []).length,
104 });
105 }
106
107 if (request.method === "GET" && pathname === "/forecast") {
108 // Predictive scaling exists only for ECS services — for a
109 // dynamodb-namespace target the live API PERMANENTLY rejects the
110 // read with AccessDeniedException "GetPredictiveScalingForecast
111 // is not supported.", which the distilled patch specializes into
112 // the typed PredictiveScalingForecastNotSupported. Do NOT retry
113 // it (it is not an IAM-propagation denial — retrying blows the
114 // Lambda timeout and surfaces as an opaque 502). Return the
115 // typed tag so the test proves the grant, the PolicyName
116 // injection, and the typed error union end-to-end.
117 const now = yield* Effect.sync(() => Date.now());
118 const tag = yield* getPredictiveScalingForecast({
119 StartTime: new Date(now),
120 EndTime: new Date(now + 2 * 60 * 60 * 1000),
121 }).pipe(
122 Effect.map(() => "Forecast"),
123 Effect.catchTag("PredictiveScalingForecastNotSupported", (e) => Effect.succeed(e._tag)),
124 // Return whatever typed tag the API produced so an unexpected
125 // error is observable in the test's assertion message instead
126 // of an opaque 500. (The deployed bundle resolves distilled via
127 // its built `lib/`, so until the coordinator rebuilds distilled
128 // the platform rejection still surfaces as the base
129 // AccessDeniedException tag in-Lambda.)
130 Effect.catch((e) => Effect.succeed(e._tag)),
131 );
132 return yield* HttpServerResponse.json({ tag });
133 }
134
135 return yield* HttpServerResponse.json(
136 { error: "Not found", method: request.method, pathname },
137 { status: 404 },
138 );
139 }).pipe(Effect.orDie),
140 };
141 }).pipe(
142 Effect.provide(
143 Layer.mergeAll(
144 Lambda.EventSource,
145 ApplicationAutoScaling.DescribeScalingActivitiesHttp,
146 ApplicationAutoScaling.GetPredictiveScalingForecastHttp,
147 ),
148 ),
149 ),
150 );