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

main
ts 354 lines 12.6 KB
Raw
1 import * as efs from "@distilled.cloud/aws/efs";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { deepEqual, 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 { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13
14 export interface AccessPointPosixUser {
15 /** POSIX user ID applied to all file-system requests through this access point. */
16 uid: number;
17 /** POSIX group ID applied to all file-system requests through this access point. */
18 gid: number;
19 /** Secondary POSIX group IDs. */
20 secondaryGids?: number[];
21 }
22
23 export interface AccessPointRootDirectory {
24 /**
25 * Path on the file system to expose as the access point's root.
26 * @default "/"
27 */
28 path?: string;
29 /**
30 * Ownership and permissions EFS applies when it creates the root directory
31 * on first mount. Required if `path` does not already exist on the file
32 * system (which is always the case for a freshly created file system).
33 */
34 creationInfo?: {
35 /** POSIX user ID that owns the created root directory. */
36 ownerUid: number;
37 /** POSIX group ID that owns the created root directory. */
38 ownerGid: number;
39 /** Octal permissions of the created root directory, e.g. `"750"`. */
40 permissions: string;
41 };
42 }
43
44 export interface AccessPointProps {
45 /**
46 * ID of the EFS file system the access point exposes
47 * (e.g. `fileSystem.fileSystemId`). Cannot be changed after creation
48 * (replacement).
49 */
50 fileSystemId: string;
51 /**
52 * POSIX identity enforced for all requests through this access point.
53 * Cannot be changed after creation (replacement).
54 */
55 posixUser?: AccessPointPosixUser;
56 /**
57 * Directory on the file system exposed as the access point's root,
58 * optionally created on first mount with the given ownership/permissions.
59 * Cannot be changed after creation (replacement).
60 */
61 rootDirectory?: AccessPointRootDirectory;
62 /**
63 * Tags to apply to the access point. Merged with internal Alchemy tags.
64 */
65 tags?: Record<string, string>;
66 }
67
68 export interface AccessPoint extends Resource<
69 "AWS.EFS.AccessPoint",
70 AccessPointProps,
71 {
72 /** The ID of the access point (e.g. `fsap-0123456789abcdef0`). */
73 accessPointId: string;
74 /** The ARN of the access point. */
75 accessPointArn: string;
76 /** The ID of the EFS file system the access point belongs to. */
77 fileSystemId: string;
78 },
79 {},
80 Providers
81 > {}
82
83 /**
84 * An Amazon EFS access point — an application-specific entry point into a
85 * file system that enforces a POSIX identity and a root directory.
86 *
87 * Access points are how Lambda (and other serverless compute) mounts EFS:
88 * pass `accessPoint.accessPointArn` to a Lambda Function's
89 * `fileSystemConfigs`. The POSIX user and root directory are immutable —
90 * changing them replaces the access point.
91 * ### Creating Access Points
92 * **Example:** Access point with a POSIX identity and auto-created root
93 * ```typescript
94 * import * as AWS from "@alchemy.run/aws";
95 *
96 * const files = yield* AWS.EFS.FileSystem("Files");
97 * const accessPoint = yield* AWS.EFS.AccessPoint("FilesAccess", {
98 * fileSystemId: files.fileSystemId,
99 * posixUser: { uid: 1000, gid: 1000 },
100 * rootDirectory: {
101 * path: "/app",
102 * creationInfo: { ownerUid: 1000, ownerGid: 1000, permissions: "750" },
103 * },
104 * });
105 * ```
106 *
107 * ### Mounting into Lambda
108 * **Example:** Mount at /mnt/files
109 * ```typescript
110 * const fn = yield* AWS.Lambda.Function("Api", {
111 * main: "./src/handler.ts",
112 * vpc: { subnetIds: [subnetId], securityGroupIds: [securityGroupId] },
113 * fileSystemConfigs: [
114 * { arn: accessPoint.accessPointArn, localMountPath: "/mnt/files" },
115 * ],
116 * });
117 * ```
118 *
119 * @resource
120 */
121 export const AccessPoint = Resource<AccessPoint>("AWS.EFS.AccessPoint");
122
123 /**
124 * Internal marker error used to drive the bounded wait for an access point
125 * to reach the `available` lifecycle state.
126 */
127 export class AccessPointNotAvailable extends Data.TaggedError("AccessPointNotAvailable")<{
128 accessPointId: string;
129 state: string;
130 }> {}
131
132 /**
133 * Access points settle to `available` in seconds. Bounded poll (~60s),
134 * explicitly typed so declaration emit never widens the provider layer
135 * (see PATTERNS §7).
136 */
137 const retryUntilAccessPointAvailable = <E extends { _tag: string }, R>(
138 self: Effect.Effect<efs.AccessPointDescription, E, R>,
139 ): Effect.Effect<efs.AccessPointDescription, E | AccessPointNotAvailable, R> =>
140 Effect.retry(
141 Effect.flatMap(self, (ap) =>
142 ap.LifeCycleState === "available"
143 ? Effect.succeed(ap)
144 : Effect.fail(
145 new AccessPointNotAvailable({
146 accessPointId: ap.AccessPointId ?? "",
147 state: ap.LifeCycleState ?? "unknown",
148 }),
149 ),
150 ),
151 {
152 while: (e) => e._tag === "AccessPointNotAvailable",
153 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(30)]),
154 },
155 );
156
157 const efsTagsToRecord = (tags: readonly efs.Tag[] | undefined): Record<string, string> =>
158 Object.fromEntries((tags ?? []).map((t) => [t.Key, t.Value]));
159
160 const toWirePosixUser = (posixUser: AccessPointPosixUser | undefined): efs.PosixUser | undefined =>
161 posixUser === undefined
162 ? undefined
163 : {
164 Uid: posixUser.uid,
165 Gid: posixUser.gid,
166 ...(posixUser.secondaryGids !== undefined
167 ? { SecondaryGids: posixUser.secondaryGids }
168 : {}),
169 };
170
171 const toWireRootDirectory = (
172 rootDirectory: AccessPointRootDirectory | undefined,
173 ): efs.RootDirectory | undefined =>
174 rootDirectory === undefined
175 ? undefined
176 : {
177 ...(rootDirectory.path !== undefined ? { Path: rootDirectory.path } : {}),
178 ...(rootDirectory.creationInfo !== undefined
179 ? {
180 CreationInfo: {
181 OwnerUid: rootDirectory.creationInfo.ownerUid,
182 OwnerGid: rootDirectory.creationInfo.ownerGid,
183 Permissions: rootDirectory.creationInfo.permissions,
184 },
185 }
186 : {}),
187 };
188
189 export const AccessPointProvider = () =>
190 Provider.effect(
191 AccessPoint,
192 Effect.gen(function* () {
193 const createToken = Effect.fn(function* (id: string) {
194 return yield* createPhysicalName({ id, maxLength: 64 });
195 });
196
197 const findById = Effect.fn(function* (accessPointId: string) {
198 return yield* efs.describeAccessPoints({ AccessPointId: accessPointId }).pipe(
199 Effect.map((r) => r.AccessPoints?.[0]),
200 Effect.catchTag("AccessPointNotFound", () => Effect.undefined),
201 );
202 });
203
204 const findByToken = Effect.fn(function* (fileSystemId: string, token: string) {
205 return yield* efs.describeAccessPoints({ FileSystemId: fileSystemId }).pipe(
206 Effect.map((r) => r.AccessPoints?.find((ap) => ap.ClientToken === token)),
207 Effect.catchTag("FileSystemNotFound", () => Effect.undefined),
208 );
209 });
210
211 return AccessPoint.Provider.of({
212 stables: ["accessPointId", "accessPointArn", "fileSystemId"],
213
214 // Access points are only enumerable per file system, so walk every
215 // file system in the account/region.
216 list: () =>
217 Effect.gen(function* () {
218 const systems = yield* efs.describeFileSystems.items({}).pipe(
219 Stream.runCollect,
220 Effect.map((chunk) => Array.from(chunk)),
221 );
222 const perSystem = yield* Effect.forEach(
223 systems,
224 (fs) =>
225 efs.describeAccessPoints({ FileSystemId: fs.FileSystemId }).pipe(
226 Effect.map((r) =>
227 (r.AccessPoints ?? [])
228 .filter(
229 (ap) => ap.AccessPointId !== undefined && ap.LifeCycleState !== "deleted",
230 )
231 .map((ap) => ({
232 accessPointId: ap.AccessPointId!,
233 accessPointArn: ap.AccessPointArn!,
234 fileSystemId: ap.FileSystemId!,
235 })),
236 ),
237 Effect.catchTag("FileSystemNotFound", () => Effect.succeed([])),
238 ),
239 { concurrency: 5 },
240 );
241 return perSystem.flat();
242 }),
243
244 read: Effect.fn(function* ({ id, olds, output }) {
245 const ap = output?.accessPointId
246 ? yield* findById(output.accessPointId)
247 : olds?.fileSystemId
248 ? yield* findByToken(olds.fileSystemId, yield* createToken(id))
249 : undefined;
250 if (ap?.AccessPointId === undefined || ap.LifeCycleState === "deleted") {
251 return undefined;
252 }
253 const attrs = {
254 accessPointId: ap.AccessPointId,
255 accessPointArn: ap.AccessPointArn!,
256 fileSystemId: ap.FileSystemId!,
257 };
258 return (yield* hasAlchemyTags(id, efsTagsToRecord(ap.Tags))) ? attrs : Unowned(attrs);
259 }),
260
261 // posixUser, rootDirectory, and the file system are all immutable on
262 // an access point — any change replaces it. Only tags update in
263 // place.
264 diff: Effect.fn(function* ({ news, olds }) {
265 if (!isResolved(news) || olds === undefined) return undefined;
266 if (
267 news.fileSystemId !== olds.fileSystemId ||
268 !deepEqual(news.posixUser, olds.posixUser) ||
269 !deepEqual(news.rootDirectory, olds.rootDirectory)
270 ) {
271 return { action: "replace" } as const;
272 }
273 // undefined → default update path (tag sync)
274 }),
275
276 reconcile: Effect.fn(function* ({ id, news, output, session }) {
277 const token = yield* createToken(id);
278 const internalTags = yield* createInternalTags(id);
279
280 // 1. OBSERVE — output.accessPointId is only a cache; the client
281 // token is the deterministic identity within the file system.
282 let ap = output?.accessPointId
283 ? yield* findById(output.accessPointId)
284 : yield* findByToken(news.fileSystemId, token);
285 if (ap?.LifeCycleState === "deleted") {
286 ap = undefined;
287 }
288
289 // 2. ENSURE — create if missing. CreateAccessPoint is idempotent
290 // on the client token; a concurrent identical create surfaces
291 // the typed AccessPointAlreadyExists which we resolve by
292 // describing the winner.
293 if (ap === undefined) {
294 ap = yield* efs
295 .createAccessPoint({
296 ClientToken: token,
297 FileSystemId: news.fileSystemId,
298 PosixUser: toWirePosixUser(news.posixUser),
299 RootDirectory: toWireRootDirectory(news.rootDirectory),
300 Tags: Object.entries({ ...news.tags, ...internalTags }).map(([Key, Value]) => ({
301 Key,
302 Value,
303 })),
304 })
305 .pipe(
306 Effect.catchTag("AccessPointAlreadyExists", (e) =>
307 efs
308 .describeAccessPoints({ AccessPointId: e.AccessPointId })
309 .pipe(Effect.map((r) => r.AccessPoints![0])),
310 ),
311 );
312 }
313
314 const accessPointId = ap.AccessPointId!;
315
316 ap = yield* retryUntilAccessPointAvailable(
317 efs
318 .describeAccessPoints({ AccessPointId: accessPointId })
319 .pipe(Effect.map((r) => r.AccessPoints![0])),
320 );
321
322 // 3. SYNC tags — diff against OBSERVED cloud tags so adoption
323 // converges.
324 const observedTags = efsTagsToRecord(ap.Tags);
325 const { upsert, removed } = diffTags(observedTags, {
326 ...news.tags,
327 ...internalTags,
328 });
329 if (upsert.length > 0) {
330 yield* efs.tagResource({ ResourceId: accessPointId, Tags: upsert });
331 }
332 if (removed.length > 0) {
333 yield* efs.untagResource({
334 ResourceId: accessPointId,
335 TagKeys: removed,
336 });
337 }
338
339 yield* session.note(accessPointId);
340 return {
341 accessPointId,
342 accessPointArn: ap.AccessPointArn!,
343 fileSystemId: ap.FileSystemId!,
344 };
345 }),
346
347 delete: Effect.fn(function* ({ output }) {
348 yield* efs
349 .deleteAccessPoint({ AccessPointId: output.accessPointId })
350 .pipe(Effect.catchTag("AccessPointNotFound", () => Effect.void));
351 }),
352 });
353 }),
354 );