@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 362 lines 13.6 KB
Raw
1 import { Region } from "@distilled.cloud/aws/Region";
2 import * as s3control from "@distilled.cloud/aws/s3-control";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
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
14 export interface MultiRegionAccessPointProps {
15 /**
16 * Name of the Multi-Region Access Point (3-50 characters, lowercase
17 * letters, numbers and hyphens). If omitted, a unique name is generated
18 * from the app, stage and logical ID.
19 *
20 * Changing the name replaces the Multi-Region Access Point.
21 * @default ${app}-${stage}-${id}
22 */
23 multiRegionAccessPointName?: string;
24 /**
25 * The buckets (at most one per region, up to 20 regions) the
26 * Multi-Region Access Point routes requests to.
27 *
28 * Changing the regions replaces the Multi-Region Access Point.
29 */
30 regions: {
31 /** Name of the bucket in one of the member regions. */
32 bucket: string;
33 /** Account ID that owns the bucket, for cross-account buckets. */
34 bucketAccountId?: string;
35 }[];
36 /**
37 * Block-public-access settings. AWS defaults every flag to `true` for
38 * Multi-Region Access Points when omitted.
39 *
40 * Changing these settings replaces the Multi-Region Access Point.
41 */
42 publicAccessBlock?: {
43 /** Block new public ACLs and uploading public objects. @default true */
44 blockPublicAcls?: boolean;
45 /** Ignore all public ACLs. @default true */
46 ignorePublicAcls?: boolean;
47 /** Block new policies that grant public access. @default true */
48 blockPublicPolicy?: boolean;
49 /** Restrict public policies to AWS principals. @default true */
50 restrictPublicBuckets?: boolean;
51 };
52 }
53
54 export interface MultiRegionAccessPoint extends Resource<
55 "AWS.S3Control.MultiRegionAccessPoint",
56 MultiRegionAccessPointProps,
57 {
58 /**
59 * Name of the Multi-Region Access Point.
60 */
61 multiRegionAccessPointName: string;
62 /**
63 * ARN of the Multi-Region Access Point (regionless, alias-addressed).
64 */
65 multiRegionAccessPointArn: string;
66 /**
67 * The S3-assigned alias of the Multi-Region Access Point. Requests are
68 * addressed to `${alias}.accesspoint.s3-global.amazonaws.com`.
69 */
70 alias: string | undefined;
71 /**
72 * Provisioning status of the Multi-Region Access Point at the time of
73 * the last deploy (`READY` once fully provisioned).
74 */
75 status: s3control.MultiRegionAccessPointStatus | undefined;
76 /**
77 * AWS account ID that owns the Multi-Region Access Point.
78 */
79 accountId: AccountID;
80 },
81 never,
82 Providers
83 > {}
84
85 /**
86 * An Amazon S3 Multi-Region Access Point — a single global endpoint that
87 * routes requests to buckets in multiple regions over the AWS global
88 * network.
89 *
90 * Provisioning is asynchronous and slow (several minutes); the provider
91 * submits the request and waits until the access point reaches `READY`.
92 * All control-plane requests are routed through `us-west-2`, as required
93 * by the Multi-Region Access Point API.
94 * ### Creating Multi-Region Access Points
95 * **Example:** Route between two regional buckets
96 * ```typescript
97 * import * as S3Control from "@alchemy.run/aws/S3Control";
98 *
99 * const mrap = yield* S3Control.MultiRegionAccessPoint("global", {
100 * regions: [
101 * { bucket: usWestBucket.bucketName },
102 * { bucket: euCentralBucket.bucketName },
103 * ],
104 * });
105 * ```
106 *
107 * **Example:** Single-region Multi-Region Access Point
108 * ```typescript
109 * const mrap = yield* S3Control.MultiRegionAccessPoint("global", {
110 * regions: [{ bucket: bucket.bucketName }],
111 * });
112 * ```
113 *
114 * @resource
115 */
116 export const MultiRegionAccessPoint = Resource<MultiRegionAccessPoint>(
117 "AWS.S3Control.MultiRegionAccessPoint",
118 );
119
120 /**
121 * Raised while a Multi-Region Access Point is still provisioning — retried
122 * by {@link retryWhileMrapTransitions} until it reaches `READY`.
123 */
124 export class MultiRegionAccessPointNotReady extends Data.TaggedError(
125 "MultiRegionAccessPointNotReady",
126 )<{ resourceName: string; status: string | undefined }> {}
127
128 /**
129 * Raised while a Multi-Region Access Point deletion is still in flight —
130 * retried by {@link retryWhileMrapTransitions} until the report disappears.
131 */
132 export class MultiRegionAccessPointNotDeleted extends Data.TaggedError(
133 "MultiRegionAccessPointNotDeleted",
134 )<{ resourceName: string; status: string | undefined }> {}
135
136 /**
137 * Multi-Region Access Point provisioning/deletion legitimately takes
138 * several minutes — poll every 15 seconds for up to ~20 minutes.
139 *
140 * Explicitly typed at module scope — inlining `Effect.retry` in a lifecycle
141 * op leaks `Retry.Return`'s conditional type into declaration emit, widening
142 * the provider layer to `unknown` and poisoning `AWS.providers()`.
143 */
144 const retryWhileMrapTransitions = <A, E extends { _tag: string }, R>(
145 self: Effect.Effect<A, E, R>,
146 ): Effect.Effect<A, E, R> =>
147 Effect.retry(self, {
148 while: (e) =>
149 e._tag === "MultiRegionAccessPointNotReady" || e._tag === "MultiRegionAccessPointNotDeleted",
150 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(80)]),
151 });
152
153 /**
154 * All Multi-Region Access Point control-plane requests are routed to the
155 * US West (Oregon) region regardless of the ambient region.
156 */
157 const inMrapRegion = <A, E, R>(
158 self: Effect.Effect<A, E, R>,
159 ): Effect.Effect<A, E, Exclude<R, Region>> =>
160 self.pipe(Effect.provideService(Region, Effect.succeed("us-west-2")));
161
162 export const MultiRegionAccessPointProvider = () =>
163 Provider.effect(
164 MultiRegionAccessPoint,
165 Effect.gen(function* () {
166 const createName = Effect.fn(function* (
167 id: string,
168 props: Pick<MultiRegionAccessPointProps, "multiRegionAccessPointName">,
169 ) {
170 // Multi-Region Access Point names: 3-50 chars, lowercase.
171 return (
172 props.multiRegionAccessPointName ??
173 (yield* createPhysicalName({ id, maxLength: 50, lowercase: true }))
174 );
175 });
176
177 const mrapArn = (accountId: string, alias: string | undefined) =>
178 `arn:aws:s3::${accountId}:accesspoint/${alias ?? ""}`;
179
180 const observeMrap = (accountId: string, name: string) =>
181 inMrapRegion(
182 s3control.getMultiRegionAccessPoint({ AccountId: accountId, Name: name }).pipe(
183 Effect.map((r) => r.AccessPoint),
184 Effect.catchTag("NoSuchMultiRegionAccessPoint", () => Effect.undefined),
185 ),
186 );
187
188 const toAttrs = (
189 name: string,
190 accountId: AccountID,
191 report: s3control.MultiRegionAccessPointReport | undefined,
192 ) => ({
193 multiRegionAccessPointName: name,
194 multiRegionAccessPointArn: mrapArn(accountId, report?.Alias),
195 alias: report?.Alias,
196 status: report?.Status,
197 accountId,
198 });
199
200 // Wait until the Multi-Region Access Point reaches READY. A report
201 // that is briefly missing right after the async create request is
202 // treated the same as a transitioning one.
203 const awaitReady = (accountId: string, name: string) =>
204 retryWhileMrapTransitions(
205 observeMrap(accountId, name).pipe(
206 Effect.flatMap((report) =>
207 report?.Status === "READY"
208 ? Effect.succeed(report)
209 : Effect.fail(
210 new MultiRegionAccessPointNotReady({
211 resourceName: name,
212 status: report?.Status,
213 }),
214 ),
215 ),
216 ),
217 );
218
219 const awaitGone = (accountId: string, name: string) =>
220 retryWhileMrapTransitions(
221 observeMrap(accountId, name).pipe(
222 Effect.flatMap((report) =>
223 report === undefined
224 ? Effect.void
225 : Effect.fail(
226 new MultiRegionAccessPointNotDeleted({
227 resourceName: name,
228 status: report.Status,
229 }),
230 ),
231 ),
232 ),
233 );
234
235 const canonProps = (props: MultiRegionAccessPointProps) =>
236 JSON.stringify({
237 regions: [...props.regions]
238 .map((r) => ({
239 bucket: r.bucket,
240 account: r.bucketAccountId ?? null,
241 }))
242 .sort((a, b) => a.bucket.localeCompare(b.bucket)),
243 pab: {
244 a: props.publicAccessBlock?.blockPublicAcls ?? true,
245 i: props.publicAccessBlock?.ignorePublicAcls ?? true,
246 p: props.publicAccessBlock?.blockPublicPolicy ?? true,
247 r: props.publicAccessBlock?.restrictPublicBuckets ?? true,
248 },
249 });
250
251 return MultiRegionAccessPoint.Provider.of({
252 stables: ["multiRegionAccessPointName", "multiRegionAccessPointArn", "alias", "accountId"],
253 // Multi-Region Access Points do not support tags; the deterministic
254 // name is the ownership scope.
255 list: () =>
256 Effect.gen(function* () {
257 const { accountId } = yield* AWSEnvironment.current;
258 const pages = yield* inMrapRegion(
259 s3control.listMultiRegionAccessPoints
260 .pages({ AccountId: accountId })
261 .pipe(Stream.runCollect),
262 );
263 return Array.from(pages).flatMap((page) =>
264 (page.AccessPoints ?? []).flatMap((report) =>
265 report.Name !== undefined ? [toAttrs(report.Name, accountId, report)] : [],
266 ),
267 );
268 }),
269 read: Effect.fn(function* ({ id, olds, output }) {
270 const { accountId } = yield* AWSEnvironment.current;
271 const name = output?.multiRegionAccessPointName ?? (yield* createName(id, olds ?? {}));
272 const report = yield* observeMrap(accountId, name);
273 if (report === undefined) return undefined;
274 return toAttrs(name, accountId, report);
275 }),
276 diff: Effect.fn(function* ({ id, news, olds }) {
277 if (!isResolved(news)) return undefined;
278 const oldName = yield* createName(id, olds ?? {});
279 const newName = yield* createName(id, news);
280 if (
281 oldName !== newName ||
282 (olds !== undefined && canonProps(olds) !== canonProps(news))
283 ) {
284 // Every property of a Multi-Region Access Point is create-only.
285 return { action: "replace" } as const;
286 }
287 }),
288 reconcile: Effect.fn(function* ({ id, news, output, session }) {
289 const { accountId } = yield* AWSEnvironment.current;
290 const name = output?.multiRegionAccessPointName ?? (yield* createName(id, news));
291
292 // 1. OBSERVE — cloud state is authoritative.
293 const report = yield* observeMrap(accountId, name);
294
295 // 2. ENSURE — submit the async create when missing. The client
296 // token only needs to be unique per submission; idempotency
297 // across crashed runs comes from observing before creating.
298 if (report === undefined) {
299 const clientToken = yield* Effect.sync(() => crypto.randomUUID());
300 yield* session.note(
301 `Creating Multi-Region Access Point ${name} (takes several minutes)...`,
302 );
303 yield* inMrapRegion(
304 s3control.createMultiRegionAccessPoint({
305 AccountId: accountId,
306 ClientToken: clientToken,
307 Details: {
308 Name: name,
309 Regions: news.regions.map((r) => ({
310 Bucket: r.bucket,
311 BucketAccountId: r.bucketAccountId,
312 })),
313 PublicAccessBlock: news.publicAccessBlock
314 ? {
315 BlockPublicAcls: news.publicAccessBlock.blockPublicAcls,
316 IgnorePublicAcls: news.publicAccessBlock.ignorePublicAcls,
317 BlockPublicPolicy: news.publicAccessBlock.blockPublicPolicy,
318 RestrictPublicBuckets: news.publicAccessBlock.restrictPublicBuckets,
319 }
320 : undefined,
321 },
322 }),
323 );
324 }
325
326 // 3. WAIT — converge to READY (also covers resuming a reconcile
327 // that crashed while a previous create was still in flight).
328 const ready = yield* awaitReady(accountId, name);
329
330 yield* session.note(name);
331 return toAttrs(name, accountId, ready);
332 }),
333 delete: Effect.fn(function* ({ output, session }) {
334 const { accountId } = yield* AWSEnvironment.current;
335 const name = output.multiRegionAccessPointName;
336
337 const report = yield* observeMrap(accountId, name);
338 if (report === undefined) return;
339
340 // Deletion is also asynchronous; only submit when the access
341 // point is not already being torn down.
342 if (report.Status !== "DELETING") {
343 const clientToken = yield* Effect.sync(() => crypto.randomUUID());
344 yield* session.note(
345 `Deleting Multi-Region Access Point ${name} (takes several minutes)...`,
346 );
347 yield* inMrapRegion(
348 s3control
349 .deleteMultiRegionAccessPoint({
350 AccountId: accountId,
351 ClientToken: clientToken,
352 Details: { Name: name },
353 })
354 .pipe(Effect.catchTag("NoSuchMultiRegionAccessPoint", () => Effect.void)),
355 );
356 }
357
358 yield* awaitGone(accountId, name);
359 }),
360 });
361 }),
362 );