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

main
ts 289 lines 10.9 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import * as Output from "alchemy/Output";
3 import * as Context from "effect/Context";
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 Result from "effect/Result";
10 import * as Schedule from "effect/Schedule";
11
12 // Bindings fixture: an S3 bucket + access point plus a Lambda that exercises
13 // the nine ungated S3 Control runtime bindings against them — the three
14 // access-point-scoped reads, the account-level access point listing, and the
15 // full S3 Batch Operations job loop (create suspended → describe → bump
16 // priority → cancel → list).
17 export class S3ControlBindingsFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
18 "S3ControlBindingsFunction",
19 ) {}
20
21 export class BoundAccessPoint extends Context.Service<
22 BoundAccessPoint,
23 {
24 accessPoint: AWS.S3Control.AccessPoint;
25 bucket: AWS.S3.Bucket;
26 batchRole: AWS.IAM.Role;
27 }
28 >()("BoundAccessPoint") {}
29
30 export const BoundAccessPointLive = Layer.effect(
31 BoundAccessPoint,
32 Effect.gen(function* () {
33 const bucket = yield* AWS.S3.Bucket("S3ControlBindingsBucket", {});
34 const accessPoint = yield* AWS.S3Control.AccessPoint("S3ControlBindingsAccessPoint", {
35 bucket: bucket.bucketName,
36 });
37 // Execution role handed to S3 Batch Operations via CreateJob. The job is
38 // cancelled while suspended, so the role's policy only needs to satisfy
39 // create-time validation.
40 const batchRole = yield* AWS.IAM.Role("S3ControlBindingsBatchRole", {
41 assumeRolePolicyDocument: {
42 Version: "2012-10-17",
43 Statement: [
44 {
45 Effect: "Allow",
46 Principal: { Service: "batchoperations.s3.amazonaws.com" },
47 Action: ["sts:AssumeRole"],
48 },
49 ],
50 },
51 inlinePolicies: {
52 BatchAccess: {
53 Version: "2012-10-17",
54 Statement: [
55 {
56 Effect: "Allow",
57 Action: ["s3:ListBucket", "s3:GetObject", "s3:PutObjectTagging"],
58 Resource: [bucket.bucketArn, Output.interpolate`${bucket.bucketArn}/*`],
59 },
60 ],
61 },
62 },
63 });
64 return { accessPoint, bucket, batchRole };
65 }),
66 );
67
68 export default S3ControlBindingsFunction.make(
69 {
70 main: import.meta.url,
71 functionUrl: true,
72 timeout: Duration.seconds(120),
73 },
74 Effect.gen(function* () {
75 const { accessPoint, bucket, batchRole } = yield* BoundAccessPoint;
76
77 const getAccessPoint = yield* AWS.S3Control.GetAccessPoint(accessPoint);
78 const getAccessPointPolicy = yield* AWS.S3Control.GetAccessPointPolicy(accessPoint);
79 const getAccessPointPolicyStatus = yield* AWS.S3Control.GetAccessPointPolicyStatus(accessPoint);
80 const listAccessPoints = yield* AWS.S3Control.ListAccessPoints();
81 const createJob = yield* AWS.S3Control.CreateJob();
82 const describeJob = yield* AWS.S3Control.DescribeJob();
83 const listJobs = yield* AWS.S3Control.ListJobs();
84 const updateJobStatus = yield* AWS.S3Control.UpdateJobStatus();
85 const updateJobPriority = yield* AWS.S3Control.UpdateJobPriority();
86
87 const bound = {
88 getAccessPoint,
89 getAccessPointPolicy,
90 getAccessPointPolicyStatus,
91 listAccessPoints,
92 createJob,
93 describeJob,
94 listJobs,
95 updateJobStatus,
96 updateJobPriority,
97 };
98
99 const bucketName = yield* bucket.bucketName;
100 const bucketArn = yield* bucket.bucketArn;
101 const batchRoleArn = yield* batchRole.roleArn;
102
103 return {
104 fetch: Effect.gen(function* () {
105 const request = yield* HttpServerRequest;
106 const url = new URL(request.originalUrl);
107 const pathname = url.pathname;
108
109 if (request.method === "GET" && pathname === "/bindings") {
110 return yield* HttpServerResponse.json({
111 bound: Object.keys(bound),
112 });
113 }
114
115 if (request.method === "GET" && pathname === "/access-point") {
116 const live = yield* getAccessPoint();
117 return yield* HttpServerResponse.json({
118 name: live.Name,
119 bucket: live.Bucket,
120 networkOrigin: live.NetworkOrigin,
121 });
122 }
123
124 if (request.method === "GET" && pathname === "/policy") {
125 const result = yield* getAccessPointPolicy().pipe(
126 Effect.map((r) => ({ hasPolicy: r.Policy !== undefined })),
127 // A fresh access point has no policy — the typed tag proves the
128 // binding round-trips.
129 Effect.catchTag("NoSuchAccessPointPolicy", () => Effect.succeed({ hasPolicy: false })),
130 );
131 return yield* HttpServerResponse.json(result);
132 }
133
134 if (request.method === "GET" && pathname === "/policy-status") {
135 const result = yield* getAccessPointPolicyStatus().pipe(
136 Effect.map((r) => ({
137 isPublic: r.PolicyStatus?.IsPublic ?? false,
138 hasPolicy: true,
139 })),
140 Effect.catchTag("NoSuchAccessPointPolicy", () =>
141 Effect.succeed({ isPublic: false, hasPolicy: false }),
142 ),
143 );
144 return yield* HttpServerResponse.json(result);
145 }
146
147 if (request.method === "GET" && pathname === "/access-points") {
148 const page = yield* listAccessPoints({
149 Bucket: yield* bucketName,
150 });
151 return yield* HttpServerResponse.json({
152 names: (page.AccessPointList ?? []).map((ap) => ap.Name),
153 });
154 }
155
156 if (request.method === "GET" && pathname === "/job-lifecycle") {
157 // Wrapped in Effect.result so a failing step surfaces its typed
158 // tag in the JSON body instead of an opaque 500.
159 const outcome = yield* Effect.result(
160 Effect.gen(function* () {
161 // 1. CREATE — a suspended (ConfirmationRequired) tagging job over a
162 // generated manifest; nothing executes because it is cancelled
163 // below. Cancelled jobs are inert metadata that S3 expires
164 // automatically after 90 days.
165 const token = yield* Effect.sync(() => crypto.randomUUID());
166 const created = yield* createJob({
167 ClientRequestToken: token,
168 ConfirmationRequired: true,
169 Priority: 1,
170 RoleArn: yield* batchRoleArn,
171 Operation: {
172 S3PutObjectTagging: {
173 TagSet: [{ Key: "alchemy-sweep", Value: "true" }],
174 },
175 },
176 Report: { Enabled: false },
177 ManifestGenerator: {
178 S3JobManifestGenerator: {
179 SourceBucket: yield* bucketArn,
180 EnableManifestOutput: false,
181 },
182 },
183 });
184 const jobId = created.JobId!;
185
186 // 2. DESCRIBE — poll (bounded) until the job settles out of
187 // New/Preparing into a stable state.
188 const settledStates = [
189 "Suspended",
190 "Failed",
191 "Complete",
192 "Cancelled",
193 "Ready",
194 "Active",
195 ];
196 const settled = yield* describeJob({ JobId: jobId }).pipe(
197 Effect.map((r) => ({ status: r.Job?.Status as string })),
198 Effect.repeat({
199 schedule: Schedule.spaced("2 seconds"),
200 until: (r): boolean => settledStates.includes(r.status),
201 times: 25,
202 }),
203 );
204
205 // 3. PRIORITY — a settled ConfirmationRequired job refuses
206 // priority changes with the typed
207 // JobStatusTransitionForbidden tag; either outcome proves
208 // the binding (and the distilled patch) end-to-end.
209 const priorityOutcome = yield* updateJobPriority({
210 JobId: jobId,
211 Priority: 5,
212 }).pipe(
213 Effect.map(() => "updated" as const),
214 Effect.catchTag("JobStatusTransitionForbidden", () =>
215 Effect.succeed("JobStatusTransitionForbidden" as const),
216 ),
217 );
218
219 // 4. CANCEL — a suspended job cancels; a job that already
220 // settled terminally (Failed/Complete) refuses with the
221 // typed tag. Both prove the UpdateJobStatus binding.
222 const cancelOutcome = yield* updateJobStatus({
223 JobId: jobId,
224 RequestedJobStatus: "Cancelled",
225 StatusUpdateReason: "alchemy sweep test",
226 }).pipe(
227 Effect.map((r) => (r.Status ?? "Cancelled") as string),
228 Effect.catchTag("JobStatusTransitionForbidden", () =>
229 Effect.succeed("JobStatusTransitionForbidden" as const),
230 ),
231 );
232
233 // Observe the job's final state after the cancel attempt.
234 const final = yield* describeJob({ JobId: jobId });
235 const finalStatus = final.Job?.Status ?? "Cancelled";
236
237 // 5. LIST — the job is observable in the account listing.
238 // NOTE: a single status value only — distilled's SigV4 signer
239 // currently mis-signs repeated query params
240 // (jobStatuses=A&jobStatuses=B → SignatureDoesNotMatch).
241 const listed = yield* listJobs({
242 JobStatuses: [finalStatus],
243 });
244
245 return {
246 ok: true as const,
247 jobId,
248 settledStatus: settled.status,
249 priorityOutcome,
250 cancelOutcome,
251 finalStatus: finalStatus as string,
252 listedJobIds: (listed.Jobs ?? []).map((j) => j.JobId),
253 };
254 }),
255 );
256
257 if (Result.isFailure(outcome)) {
258 return yield* HttpServerResponse.json({
259 ok: false as const,
260 tag: outcome.failure._tag,
261 message: `${String(outcome.failure)} ${JSON.stringify(outcome.failure)}`,
262 });
263 }
264 return yield* HttpServerResponse.json(outcome.success);
265 }
266
267 return yield* HttpServerResponse.json(
268 { error: "Not found", method: request.method, pathname },
269 { status: 404 },
270 );
271 }).pipe(Effect.orDie),
272 };
273 }).pipe(
274 Effect.provide(
275 Layer.mergeAll(
276 AWS.S3Control.GetAccessPointHttp,
277 AWS.S3Control.GetAccessPointPolicyHttp,
278 AWS.S3Control.GetAccessPointPolicyStatusHttp,
279 AWS.S3Control.ListAccessPointsHttp,
280 AWS.S3Control.CreateJobHttp,
281 AWS.S3Control.DescribeJobHttp,
282 AWS.S3Control.ListJobsHttp,
283 AWS.S3Control.UpdateJobStatusHttp,
284 AWS.S3Control.UpdateJobPriorityHttp,
285 BoundAccessPointLive,
286 ),
287 ),
288 ),
289 );