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

main
ts 308 lines 11.2 KB
Raw
1 import * as s3control from "@distilled.cloud/aws/s3-control";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Arr from "effect/Array";
7 import * as Effect from "effect/Effect";
8 import * as Order from "effect/Order";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { AWSEnvironment, type AccountID } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13 import type { RegionID } from "../Region.ts";
14
15 export interface ObjectLambdaAccessPointProps {
16 /**
17 * Name of the Object Lambda Access Point (3-45 characters, lowercase
18 * letters, numbers and hyphens). If omitted, a unique name is generated
19 * from the app, stage and logical ID.
20 *
21 * Changing the name replaces the access point.
22 * @default ${app}-${stage}-${id}
23 */
24 objectLambdaAccessPointName?: string;
25 /**
26 * ARN of the standard (supporting) access point that the Object Lambda
27 * Access Point reads through.
28 */
29 supportingAccessPoint: string;
30 /**
31 * The transformations to apply: which S3 actions to intercept
32 * (`GetObject`, `HeadObject`, `ListObjects`, `ListObjectsV2`) and the
33 * Lambda function that transforms them.
34 */
35 transformationConfigurations: s3control.ObjectLambdaTransformationConfiguration[];
36 /**
37 * Features the Lambda is allowed to pass through untransformed (e.g.
38 * `GetObject-Range`, `GetObject-PartNumber`, `HeadObject-Range`).
39 */
40 allowedFeatures?: s3control.ObjectLambdaAllowedFeature[];
41 /**
42 * Whether CloudWatch request metrics are enabled for the access point.
43 * @default false
44 */
45 cloudWatchMetricsEnabled?: boolean;
46 }
47
48 export interface ObjectLambdaAccessPoint extends Resource<
49 "AWS.S3Control.ObjectLambdaAccessPoint",
50 ObjectLambdaAccessPointProps,
51 {
52 /**
53 * Name of the Object Lambda Access Point.
54 */
55 objectLambdaAccessPointName: string;
56 /**
57 * ARN of the Object Lambda Access Point
58 * (service `s3-object-lambda`).
59 */
60 objectLambdaAccessPointArn: string;
61 /**
62 * The S3-assigned alias of the Object Lambda Access Point. The alias
63 * can be used anywhere a bucket name is accepted.
64 */
65 alias: string | undefined;
66 /**
67 * AWS region of the access point.
68 */
69 region: RegionID;
70 /**
71 * AWS account ID that owns the access point.
72 */
73 accountId: AccountID;
74 },
75 never,
76 Providers
77 > {}
78
79 /**
80 * An S3 Object Lambda Access Point — intercepts S3 `GetObject` /
81 * `HeadObject` / `ListObjects` requests through a supporting access point
82 * and transforms responses with a Lambda function (redaction, resizing,
83 * format conversion, ...).
84 * ### Creating Object Lambda Access Points
85 * **Example:** Transform GetObject responses with a Lambda
86 * ```typescript
87 * import * as S3Control from "@alchemy.run/aws/S3Control";
88 *
89 * const accessPoint = yield* S3Control.AccessPoint("data-ap", {
90 * bucket: bucket.bucketName,
91 * });
92 *
93 * const olap = yield* S3Control.ObjectLambdaAccessPoint("transform-ap", {
94 * supportingAccessPoint: accessPoint.accessPointArn,
95 * transformationConfigurations: [
96 * {
97 * Actions: ["GetObject"],
98 * ContentTransformation: {
99 * AwsLambda: { FunctionArn: transformer.functionArn },
100 * },
101 * },
102 * ],
103 * });
104 * ```
105 *
106 * **Example:** Pass Range/PartNumber through and enable metrics
107 * ```typescript
108 * const olap = yield* S3Control.ObjectLambdaAccessPoint("transform-ap", {
109 * supportingAccessPoint: accessPoint.accessPointArn,
110 * allowedFeatures: ["GetObject-Range", "GetObject-PartNumber"],
111 * cloudWatchMetricsEnabled: true,
112 * transformationConfigurations: [
113 * {
114 * Actions: ["GetObject"],
115 * ContentTransformation: {
116 * AwsLambda: { FunctionArn: transformer.functionArn },
117 * },
118 * },
119 * ],
120 * });
121 * ```
122 *
123 * @resource
124 */
125 export const ObjectLambdaAccessPoint = Resource<ObjectLambdaAccessPoint>(
126 "AWS.S3Control.ObjectLambdaAccessPoint",
127 );
128
129 /**
130 * Retry while a freshly-created Object Lambda Access Point has not
131 * propagated to reads yet.
132 *
133 * Explicitly typed at module scope — inlining `Effect.retry` in a lifecycle
134 * op leaks `Retry.Return`'s conditional type into declaration emit, widening
135 * the provider layer to `unknown` and poisoning `AWS.providers()`.
136 */
137 const retryWhileObjectLambdaPropagates = <A, E extends { _tag: string }, R>(
138 self: Effect.Effect<A, E, R>,
139 ): Effect.Effect<A, E, R> =>
140 Effect.retry(self, {
141 while: (e) => e._tag === "NoSuchAccessPoint",
142 schedule: Schedule.max([Schedule.fixed("1 second"), Schedule.recurs(10)]),
143 });
144
145 export const ObjectLambdaAccessPointProvider = () =>
146 Provider.effect(
147 ObjectLambdaAccessPoint,
148 Effect.gen(function* () {
149 const createName = Effect.fn(function* (
150 id: string,
151 props: Pick<ObjectLambdaAccessPointProps, "objectLambdaAccessPointName">,
152 ) {
153 // Object Lambda Access Point names: 3-45 chars, lowercase.
154 return (
155 props.objectLambdaAccessPointName ??
156 (yield* createPhysicalName({ id, maxLength: 45, lowercase: true }))
157 );
158 });
159
160 const objectLambdaArn = (region: string, accountId: string, name: string) =>
161 `arn:aws:s3-object-lambda:${region}:${accountId}:accesspoint/${name}`;
162
163 const observeAccessPoint = (accountId: string, name: string) =>
164 s3control
165 .getAccessPointForObjectLambda({ AccountId: accountId, Name: name })
166 .pipe(Effect.catchTag("NoSuchAccessPoint", () => Effect.undefined));
167
168 const desiredConfiguration = (
169 props: ObjectLambdaAccessPointProps,
170 ): s3control.ObjectLambdaConfiguration => ({
171 SupportingAccessPoint: props.supportingAccessPoint,
172 CloudWatchMetricsEnabled: props.cloudWatchMetricsEnabled ?? false,
173 AllowedFeatures: props.allowedFeatures,
174 TransformationConfigurations: props.transformationConfigurations,
175 });
176
177 // Canonical form ignoring member ordering so re-ordering never reads
178 // as drift.
179 const canon = (cfg: s3control.ObjectLambdaConfiguration) =>
180 JSON.stringify({
181 supportingAccessPoint: cfg.SupportingAccessPoint,
182 metrics: cfg.CloudWatchMetricsEnabled ?? false,
183 features: Arr.sort(cfg.AllowedFeatures ?? [], Order.String),
184 transformations: Arr.map(cfg.TransformationConfigurations, (transformation) => ({
185 actions: Arr.sort(transformation.Actions, Order.String),
186 lambda: transformation.ContentTransformation.AwsLambda,
187 })),
188 });
189
190 return ObjectLambdaAccessPoint.Provider.of({
191 stables: [
192 "objectLambdaAccessPointName",
193 "objectLambdaAccessPointArn",
194 "alias",
195 "region",
196 "accountId",
197 ],
198 list: () =>
199 Effect.gen(function* () {
200 const { accountId, region } = yield* AWSEnvironment.current;
201 const pages = yield* s3control.listAccessPointsForObjectLambda
202 .pages({ AccountId: accountId })
203 .pipe(Stream.runCollect);
204 return Array.from(pages).flatMap((page) =>
205 (page.ObjectLambdaAccessPointList ?? []).map((olap) => ({
206 objectLambdaAccessPointName: olap.Name,
207 objectLambdaAccessPointArn:
208 olap.ObjectLambdaAccessPointArn ?? objectLambdaArn(region, accountId, olap.Name),
209 alias: olap.Alias?.Value,
210 region,
211 accountId,
212 })),
213 );
214 }),
215 // Object Lambda Access Points do not support tags, so a read hit is
216 // treated as ours (ownership is scoped by the deterministic name).
217 read: Effect.fn(function* ({ id, olds, output }) {
218 const { accountId, region } = yield* AWSEnvironment.current;
219 const name = output?.objectLambdaAccessPointName ?? (yield* createName(id, olds ?? {}));
220 const live = yield* observeAccessPoint(accountId, name);
221 if (live === undefined) return undefined;
222 return {
223 objectLambdaAccessPointName: name,
224 objectLambdaAccessPointArn: objectLambdaArn(region, accountId, name),
225 alias: live.Alias?.Value,
226 region,
227 accountId,
228 };
229 }),
230 diff: Effect.fn(function* ({ id, news, olds }) {
231 if (!isResolved(news)) return undefined;
232 const oldName = yield* createName(id, olds ?? {});
233 const newName = yield* createName(id, news);
234 if (oldName !== newName) {
235 return { action: "replace" } as const;
236 }
237 // fall through: the configuration converges via
238 // PutAccessPointConfigurationForObjectLambda
239 }),
240 reconcile: Effect.fn(function* ({ id, news, output, session }) {
241 const { accountId, region } = yield* AWSEnvironment.current;
242 const name = output?.objectLambdaAccessPointName ?? (yield* createName(id, news));
243 const desired = desiredConfiguration(news);
244
245 // 1. OBSERVE — cloud state is authoritative.
246 let live = yield* observeAccessPoint(accountId, name);
247
248 // 2. ENSURE — create when missing; tolerate the AlreadyOwnedByYou
249 // race and wait out read propagation.
250 if (live === undefined) {
251 yield* s3control
252 .createAccessPointForObjectLambda({
253 AccountId: accountId,
254 Name: name,
255 Configuration: desired,
256 })
257 .pipe(Effect.catchTag("AccessPointAlreadyOwnedByYou", () => Effect.void));
258 live = yield* retryWhileObjectLambdaPropagates(
259 s3control.getAccessPointForObjectLambda({
260 AccountId: accountId,
261 Name: name,
262 }),
263 );
264 }
265
266 // 3. SYNC — diff the OBSERVED configuration against the desired
267 // one; apply only on drift.
268 const observedConfig = yield* retryWhileObjectLambdaPropagates(
269 s3control.getAccessPointConfigurationForObjectLambda({
270 AccountId: accountId,
271 Name: name,
272 }),
273 );
274 if (
275 observedConfig.Configuration === undefined ||
276 canon(observedConfig.Configuration) !== canon(desired)
277 ) {
278 yield* s3control.putAccessPointConfigurationForObjectLambda({
279 AccountId: accountId,
280 Name: name,
281 Configuration: desired,
282 });
283 }
284
285 yield* session.note(name);
286 return {
287 objectLambdaAccessPointName: name,
288 objectLambdaAccessPointArn: objectLambdaArn(region, accountId, name),
289 alias: live.Alias?.Value,
290 region,
291 accountId,
292 };
293 }),
294 delete: Effect.fn(function* ({ output }) {
295 const { accountId } = yield* AWSEnvironment.current;
296 yield* s3control
297 .deleteAccessPointForObjectLambda({
298 AccountId: accountId,
299 Name: output.objectLambdaAccessPointName,
300 })
301 .pipe(
302 // Idempotent delete — already gone is success.
303 Effect.catchTag("NoSuchAccessPoint", () => Effect.void),
304 );
305 }),
306 });
307 }),
308 );