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

main
ts 200 lines 6.7 KB
Raw
1 import * as datasync from "@distilled.cloud/aws/datasync";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { createInternalTags } from "alchemy/Tags";
6 import * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9 import {
10 findLocationArnByUri,
11 readObservedTags,
12 retryWhileRoleNotAssumable,
13 syncTags,
14 } from "./internal.ts";
15
16 export interface LocationS3Props {
17 /**
18 * ARN of the S3 bucket this location points at, e.g.
19 * `arn:aws:s3:::my-bucket`. Cannot be changed after creation (replacement).
20 */
21 s3BucketArn: string;
22 /**
23 * ARN of the IAM role DataSync assumes to access the bucket. The role's
24 * trust policy must allow `datasync.amazonaws.com` and grant the relevant
25 * S3 permissions. Cannot be changed after creation (replacement).
26 */
27 bucketAccessRoleArn: string;
28 /**
29 * Prefix within the bucket to sync, e.g. `/data`. Cannot be changed after
30 * creation (replacement).
31 * @default "/" (the bucket root)
32 */
33 subdirectory?: string;
34 /**
35 * S3 storage class DataSync writes objects as when this location is a
36 * transfer destination. Cannot be changed after creation (replacement).
37 * @default "STANDARD"
38 */
39 s3StorageClass?: datasync.S3StorageClass;
40 /**
41 * ARNs of DataSync agents used to connect to an S3-on-Outposts bucket.
42 * Omit for standard S3 buckets.
43 */
44 agentArns?: string[];
45 /**
46 * Tags to apply to the location. Merged with internal Alchemy tags.
47 */
48 tags?: Record<string, string>;
49 }
50
51 export interface LocationS3 extends Resource<
52 "AWS.DataSync.LocationS3",
53 LocationS3Props,
54 {
55 /** ARN of the DataSync location. */
56 locationArn: string;
57 /** URI of the location (`s3://…`). */
58 locationUri: string;
59 },
60 {},
61 Providers
62 > {}
63
64 /**
65 * A DataSync location backed by an Amazon S3 bucket. Locations are the
66 * source and destination endpoints referenced by a {@link Task}.
67 *
68 * S3 locations are immutable apart from their tags: any change to the
69 * bucket, subdirectory, storage class, or access role replaces the location.
70 * Reconcile is idempotent across state loss — the location is re-discovered
71 * by its deterministic `s3://…` URI.
72 *
73 * ### Creating S3 Locations
74 * **Example:** Bucket root
75 * ```typescript
76 * import * as AWS from "@alchemy.run/aws";
77 *
78 * const source = yield* AWS.DataSync.LocationS3("Source", {
79 * s3BucketArn: bucket.bucketArn,
80 * bucketAccessRoleArn: role.roleArn,
81 * });
82 * ```
83 *
84 * **Example:** Prefix + storage class
85 * ```typescript
86 * const dest = yield* AWS.DataSync.LocationS3("Dest", {
87 * s3BucketArn: bucket.bucketArn,
88 * bucketAccessRoleArn: role.roleArn,
89 * subdirectory: "/archive",
90 * s3StorageClass: "STANDARD_IA",
91 * });
92 * ```
93 *
94 * @resource
95 */
96 export const LocationS3 = Resource<LocationS3>("AWS.DataSync.LocationS3");
97
98 const bucketNameOf = (bucketArn: string) => bucketArn.split(":::")[1] ?? "";
99
100 const expectedUriOf = (props: LocationS3Props): string => {
101 const name = bucketNameOf(props.s3BucketArn);
102 const sub = props.subdirectory ?? "/";
103 const normalized = sub.startsWith("/") ? sub : `/${sub}`;
104 return `s3://${name}${normalized}`;
105 };
106
107 export const LocationS3Provider = () =>
108 Provider.effect(
109 LocationS3,
110 Effect.gen(function* () {
111 const describe = Effect.fn(function* (locationArn: string) {
112 return yield* datasync
113 .describeLocationS3({ LocationArn: locationArn })
114 .pipe(Effect.catchTag("LocationNotFound", () => Effect.undefined));
115 });
116
117 return LocationS3.Provider.of({
118 stables: ["locationArn", "locationUri"],
119
120 list: () =>
121 datasync.listLocations.pages({}).pipe(
122 Stream.runCollect,
123 Effect.map((chunk) =>
124 Array.from(chunk)
125 .flatMap((p) => p.Locations ?? [])
126 .filter((l) => l.LocationUri?.startsWith("s3://"))
127 .map((l) => ({
128 locationArn: l.LocationArn!,
129 locationUri: l.LocationUri!,
130 })),
131 ),
132 ),
133
134 read: Effect.fn(function* ({ olds, output }) {
135 const arn = output?.locationArn ?? (yield* findLocationArnByUri(expectedUriOf(olds)));
136 if (arn === undefined) return undefined;
137 const loc = yield* describe(arn);
138 if (loc === undefined) return undefined;
139 return {
140 locationArn: loc.LocationArn!,
141 locationUri: loc.LocationUri!,
142 };
143 }),
144
145 diff: Effect.fn(function* ({ news, olds }) {
146 if (!isResolved(news)) return undefined;
147 const replaced =
148 news.s3BucketArn !== olds.s3BucketArn ||
149 news.bucketAccessRoleArn !== olds.bucketAccessRoleArn ||
150 (news.subdirectory ?? "/") !== (olds.subdirectory ?? "/") ||
151 (news.s3StorageClass ?? "STANDARD") !== (olds.s3StorageClass ?? "STANDARD");
152 if (replaced) return { action: "replace" } as const;
153 }),
154
155 reconcile: Effect.fn(function* ({ id, news, output, session }) {
156 const internalTags = yield* createInternalTags(id);
157 const desiredTags = { ...news.tags, ...internalTags };
158
159 // 1. OBSERVE — output cache, else re-discover by deterministic URI.
160 let arn = output?.locationArn ?? (yield* findLocationArnByUri(expectedUriOf(news)));
161 let loc = arn ? yield* describe(arn) : undefined;
162
163 // 2. ENSURE — create if missing.
164 if (loc === undefined) {
165 const created = yield* retryWhileRoleNotAssumable(
166 datasync.createLocationS3({
167 S3BucketArn: news.s3BucketArn,
168 S3Config: { BucketAccessRoleArn: news.bucketAccessRoleArn },
169 Subdirectory: news.subdirectory,
170 S3StorageClass: news.s3StorageClass,
171 AgentArns: news.agentArns,
172 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
173 Key,
174 Value,
175 })),
176 }),
177 );
178 arn = created.LocationArn!;
179 loc = yield* describe(arn);
180 }
181
182 // 3. SYNC tags against observed cloud state.
183 const observed = yield* readObservedTags(arn!);
184 yield* syncTags(arn!, observed, desiredTags);
185
186 yield* session.note(arn!);
187 return {
188 locationArn: loc!.LocationArn!,
189 locationUri: loc!.LocationUri!,
190 };
191 }),
192
193 delete: Effect.fn(function* ({ output }) {
194 yield* datasync
195 .deleteLocation({ LocationArn: output.locationArn })
196 .pipe(Effect.catchTag("LocationNotFound", () => Effect.void));
197 }),
198 });
199 }),
200 );