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

main
ts 212 lines 7.36 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 { readObservedTags, retryWhileRoleNotAssumable, syncTags } from "./internal.ts";
10
11 export interface LocationEfsProps {
12 /**
13 * ARN of the Amazon EFS file system this location points at. Cannot be
14 * changed after creation (replacement).
15 */
16 efsFilesystemArn: string;
17 /**
18 * ARN of the subnet where DataSync creates the network interface used to
19 * mount the file system. The subnet must have an EFS mount target for the
20 * file system. Cannot be changed after creation (replacement).
21 */
22 subnetArn: string;
23 /**
24 * ARNs of the security groups applied to the DataSync network interface.
25 * Must allow NFS (2049) to the file system's mount target. Cannot be
26 * changed after creation (replacement).
27 */
28 securityGroupArns: string[];
29 /**
30 * Subdirectory within the file system to sync, e.g. `/data`. Cannot be
31 * changed after creation (replacement).
32 * @default the file-system root
33 */
34 subdirectory?: string;
35 /**
36 * ARN of an EFS access point DataSync mounts through. Cannot be changed
37 * after creation (replacement).
38 */
39 accessPointArn?: string;
40 /**
41 * ARN of the IAM role DataSync assumes to mount the file system (required
42 * when using an access point or in-transit encryption). Cannot be changed
43 * after creation (replacement).
44 */
45 fileSystemAccessRoleArn?: string;
46 /**
47 * Whether DataSync encrypts data in transit with TLS 1.2. Required when
48 * mounting through an access point. Cannot be changed after creation
49 * (replacement).
50 */
51 inTransitEncryption?: datasync.EfsInTransitEncryption;
52 /**
53 * Tags to apply to the location. Merged with internal Alchemy tags.
54 */
55 tags?: Record<string, string>;
56 }
57
58 export interface LocationEfs extends Resource<
59 "AWS.DataSync.LocationEfs",
60 LocationEfsProps,
61 {
62 /** ARN of the DataSync location. */
63 locationArn: string;
64 /** URI of the location (`efs://…`). */
65 locationUri: string;
66 },
67 {},
68 Providers
69 > {}
70
71 /**
72 * A DataSync location backed by an Amazon EFS file system. Used as a source
73 * or destination endpoint of a {@link Task}.
74 *
75 * EFS locations are immutable apart from their tags: any change to the file
76 * system, subnet, security groups, subdirectory, access point, or encryption
77 * replaces the location.
78 *
79 * ### Creating EFS Locations
80 * **Example:** File system + subnet + security group
81 * ```typescript
82 * import * as AWS from "@alchemy.run/aws";
83 *
84 * const location = yield* AWS.DataSync.LocationEfs("Files", {
85 * efsFilesystemArn: files.fileSystemArn,
86 * subnetArn: `arn:aws:ec2:${region}:${accountId}:subnet/${subnetId}`,
87 * securityGroupArns: [
88 * `arn:aws:ec2:${region}:${accountId}:security-group/${sgId}`,
89 * ],
90 * });
91 * ```
92 *
93 * ### Transferring Data
94 * **Example:** Back up EFS to S3
95 * ```typescript
96 * const dest = yield* AWS.DataSync.LocationS3("Backups", {
97 * s3BucketArn: bucket.bucketArn,
98 * bucketAccessRoleArn: role.roleArn,
99 * });
100 *
101 * const task = yield* AWS.DataSync.Task("EfsBackup", {
102 * sourceLocationArn: location.locationArn,
103 * destinationLocationArn: dest.locationArn,
104 * schedule: { ScheduleExpression: "cron(0 2 * * ? *)" },
105 * });
106 * ```
107 *
108 * @resource
109 */
110 export const LocationEfs = Resource<LocationEfs>("AWS.DataSync.LocationEfs");
111
112 export const LocationEfsProvider = () =>
113 Provider.effect(
114 LocationEfs,
115 Effect.gen(function* () {
116 const describe = Effect.fn(function* (locationArn: string) {
117 return yield* datasync
118 .describeLocationEfs({ LocationArn: locationArn })
119 .pipe(Effect.catchTag("LocationNotFound", () => Effect.undefined));
120 });
121
122 return LocationEfs.Provider.of({
123 stables: ["locationArn", "locationUri"],
124
125 list: () =>
126 datasync.listLocations.pages({}).pipe(
127 Stream.runCollect,
128 Effect.map((chunk) =>
129 Array.from(chunk)
130 .flatMap((p) => p.Locations ?? [])
131 .filter((l) => l.LocationUri?.startsWith("efs://"))
132 .map((l) => ({
133 locationArn: l.LocationArn!,
134 locationUri: l.LocationUri!,
135 })),
136 ),
137 ),
138
139 read: Effect.fn(function* ({ output }) {
140 if (output?.locationArn === undefined) return undefined;
141 const loc = yield* describe(output.locationArn);
142 if (loc === undefined) return undefined;
143 return {
144 locationArn: loc.LocationArn!,
145 locationUri: loc.LocationUri!,
146 };
147 }),
148
149 diff: Effect.fn(function* ({ news, olds }) {
150 if (!isResolved(news)) return undefined;
151 const replaced =
152 news.efsFilesystemArn !== olds.efsFilesystemArn ||
153 news.subnetArn !== olds.subnetArn ||
154 JSON.stringify(news.securityGroupArns) !== JSON.stringify(olds.securityGroupArns) ||
155 (news.subdirectory ?? "/") !== (olds.subdirectory ?? "/") ||
156 news.accessPointArn !== olds.accessPointArn ||
157 news.fileSystemAccessRoleArn !== olds.fileSystemAccessRoleArn ||
158 news.inTransitEncryption !== olds.inTransitEncryption;
159 if (replaced) return { action: "replace" } as const;
160 }),
161
162 reconcile: Effect.fn(function* ({ id, news, output, session }) {
163 const internalTags = yield* createInternalTags(id);
164 const desiredTags = { ...news.tags, ...internalTags };
165
166 // 1. OBSERVE — output cache is the identity (EFS location URIs are
167 // not deterministically reconstructable).
168 let arn = output?.locationArn;
169 let loc = arn ? yield* describe(arn) : undefined;
170
171 // 2. ENSURE — create if missing.
172 if (loc === undefined) {
173 const created = yield* retryWhileRoleNotAssumable(
174 datasync.createLocationEfs({
175 EfsFilesystemArn: news.efsFilesystemArn,
176 Ec2Config: {
177 SubnetArn: news.subnetArn,
178 SecurityGroupArns: news.securityGroupArns,
179 },
180 Subdirectory: news.subdirectory,
181 AccessPointArn: news.accessPointArn,
182 FileSystemAccessRoleArn: news.fileSystemAccessRoleArn,
183 InTransitEncryption: news.inTransitEncryption,
184 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
185 Key,
186 Value,
187 })),
188 }),
189 );
190 arn = created.LocationArn!;
191 loc = yield* describe(arn);
192 }
193
194 // 3. SYNC tags against observed cloud state.
195 const observed = yield* readObservedTags(arn!);
196 yield* syncTags(arn!, observed, desiredTags);
197
198 yield* session.note(arn!);
199 return {
200 locationArn: loc!.LocationArn!,
201 locationUri: loc!.LocationUri!,
202 };
203 }),
204
205 delete: Effect.fn(function* ({ output }) {
206 yield* datasync
207 .deleteLocation({ LocationArn: output.locationArn })
208 .pipe(Effect.catchTag("LocationNotFound", () => Effect.void));
209 }),
210 });
211 }),
212 );