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

main
ts 338 lines 11.1 KB
Raw
1 import * as s3files from "@distilled.cloud/aws/s3files";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import {
11 retryWhileConflict,
12 S3FilesNotConverged,
13 toTagList,
14 toTagRecord,
15 untilSettled,
16 } from "./internal.ts";
17
18 /**
19 * POSIX identity enforced for all file system operations made through an
20 * access point.
21 */
22 export interface AccessPointPosixUser {
23 /**
24 * POSIX user id.
25 */
26 uid: number;
27 /**
28 * POSIX group id.
29 */
30 gid: number;
31 /**
32 * Secondary POSIX group ids.
33 */
34 secondaryGids?: number[];
35 }
36
37 /**
38 * Ownership and permissions applied when the access point's root directory
39 * is created on first use.
40 */
41 export interface AccessPointCreationPermissions {
42 /**
43 * POSIX user id that owns the root directory.
44 */
45 ownerUid: number;
46 /**
47 * POSIX group id that owns the root directory.
48 */
49 ownerGid: number;
50 /**
51 * POSIX permission mode for the root directory (e.g. `"0755"`).
52 */
53 permissions: string;
54 }
55
56 /**
57 * Root directory the access point exposes as its file system root.
58 */
59 export interface AccessPointRootDirectory {
60 /**
61 * Path within the file system to expose as the access point root.
62 * @default "/"
63 */
64 path?: string;
65 /**
66 * Ownership and mode applied if the service creates the root directory.
67 */
68 creationPermissions?: AccessPointCreationPermissions;
69 }
70
71 export interface AccessPointProps {
72 /**
73 * Id of the {@link FileSystem} the access point attaches to. Changing it
74 * replaces the access point.
75 */
76 fileSystemId: string;
77 /**
78 * POSIX identity enforced for all operations through the access point.
79 * Immutable — changing it replaces the access point.
80 */
81 posixUser?: AccessPointPosixUser;
82 /**
83 * Root directory the access point exposes. Immutable — changing it
84 * replaces the access point.
85 */
86 rootDirectory?: AccessPointRootDirectory;
87 /**
88 * Tags to apply to the access point. Merged with internal Alchemy tags.
89 */
90 tags?: Record<string, string>;
91 }
92
93 export interface AccessPoint extends Resource<
94 "AWS.S3Files.AccessPoint",
95 AccessPointProps,
96 {
97 /**
98 * Unique ID of the access point.
99 */
100 accessPointId: string;
101 /**
102 * ARN of the access point.
103 */
104 accessPointArn: string;
105 /**
106 * ID of the file system the access point attaches to.
107 */
108 fileSystemId: string;
109 /**
110 * Current lifecycle status of the access point (e.g. `AVAILABLE`).
111 */
112 status: string;
113 },
114 never,
115 Providers
116 > {}
117
118 /**
119 * An Amazon S3 File System Access Point — application-specific access to a
120 * {@link FileSystem} with POSIX user identity and root directory
121 * enforcement, for managing shared datasets in multi-tenant scenarios.
122 *
123 * ### Creating an Access Point
124 * **Example:** Basic Access Point
125 * ```typescript
126 * import * as AWS from "@alchemy.run/aws";
127 *
128 * const accessPoint = yield* AWS.S3Files.AccessPoint("AppAccess", {
129 * fileSystemId: fs.fileSystemId,
130 * });
131 * ```
132 *
133 * **Example:** Access Point with POSIX Identity and Root Directory
134 * ```typescript
135 * const accessPoint = yield* AWS.S3Files.AccessPoint("AppAccess", {
136 * fileSystemId: fs.fileSystemId,
137 * posixUser: { uid: 1000, gid: 1000 },
138 * rootDirectory: {
139 * path: "/app",
140 * creationPermissions: { ownerUid: 1000, ownerGid: 1000, permissions: "0755" },
141 * },
142 * });
143 * ```
144 *
145 * @resource
146 */
147 export const AccessPoint = Resource<AccessPoint>("AWS.S3Files.AccessPoint");
148
149 const replacementKey = (props: Partial<AccessPointProps>) =>
150 JSON.stringify({
151 fileSystemId: props.fileSystemId,
152 posixUser: props.posixUser,
153 rootDirectory: props.rootDirectory,
154 });
155
156 export const AccessPointProvider = () =>
157 Provider.effect(
158 AccessPoint,
159 Effect.gen(function* () {
160 const observe = (accessPointId: string) =>
161 s3files
162 .getAccessPoint({ accessPointId })
163 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
164
165 const toAttributes = (ap: s3files.GetAccessPointResponse) => ({
166 accessPointId: ap.accessPointId,
167 accessPointArn: ap.accessPointArn,
168 fileSystemId: ap.fileSystemId,
169 status: ap.status,
170 });
171
172 // State-loss / conflict fallback: scan the parent file system's access
173 // points for the one carrying this logical id's Alchemy tags.
174 const findByAlchemyTags = Effect.fn(function* (id: string, fileSystemId: string) {
175 const accessPoints = yield* s3files.listAccessPoints.items({ fileSystemId }).pipe(
176 Stream.runCollect,
177 Effect.map((c) => Array.from(c)),
178 Effect.catchTag("ResourceNotFoundException", () =>
179 Effect.succeed([] as s3files.ListAccessPointsDescription[]),
180 ),
181 );
182 for (const item of accessPoints) {
183 const ap = yield* observe(item.accessPointId);
184 if (ap !== undefined && (yield* hasAlchemyTags(id, toTagRecord(ap.tags)))) {
185 return ap;
186 }
187 }
188 return undefined;
189 });
190
191 const syncTags = Effect.fn(function* (
192 accessPointId: string,
193 current: Record<string, string>,
194 desired: Record<string, string>,
195 ) {
196 const { upsert, removed } = diffTags(current, desired);
197 if (upsert.length > 0) {
198 yield* s3files.tagResource({
199 resourceId: accessPointId,
200 tags: upsert.map((t) => ({ key: t.Key, value: t.Value })),
201 });
202 }
203 if (removed.length > 0) {
204 yield* s3files.untagResource({
205 resourceId: accessPointId,
206 tagKeys: removed,
207 });
208 }
209 });
210
211 return AccessPoint.Provider.of({
212 stables: ["accessPointId", "accessPointArn", "fileSystemId"],
213 list: () =>
214 Effect.gen(function* () {
215 const fileSystems = yield* s3files.listFileSystems.items({}).pipe(
216 Stream.runCollect,
217 Effect.map((c) => Array.from(c)),
218 );
219 const out: {
220 accessPointId: string;
221 accessPointArn: string;
222 fileSystemId: string;
223 status: string;
224 }[] = [];
225 for (const fs of fileSystems) {
226 const accessPoints = yield* s3files.listAccessPoints
227 .items({ fileSystemId: fs.fileSystemId })
228 .pipe(
229 Stream.runCollect,
230 Effect.map((c) => Array.from(c)),
231 // the parent can vanish between list and enumerate
232 Effect.catchTag("ResourceNotFoundException", () =>
233 Effect.succeed([] as s3files.ListAccessPointsDescription[]),
234 ),
235 );
236 for (const ap of accessPoints) {
237 out.push({
238 accessPointId: ap.accessPointId,
239 accessPointArn: ap.accessPointArn,
240 fileSystemId: ap.fileSystemId,
241 status: ap.status,
242 });
243 }
244 }
245 return out;
246 }),
247 read: Effect.fn(function* ({ id, olds, output }) {
248 const found =
249 output?.accessPointId !== undefined
250 ? yield* observe(output.accessPointId)
251 : olds?.fileSystemId !== undefined
252 ? yield* findByAlchemyTags(id, olds.fileSystemId)
253 : undefined;
254 if (found === undefined) return undefined;
255 const attrs = toAttributes(found);
256 return (yield* hasAlchemyTags(id, toTagRecord(found.tags))) ? attrs : Unowned(attrs);
257 }),
258 diff: Effect.fn(function* ({ news, olds }) {
259 if (!isResolved(news)) return undefined;
260 // There is no UpdateAccessPoint API — everything except tags is
261 // fixed at create time.
262 if (replacementKey(olds ?? {}) !== replacementKey(news ?? {})) {
263 return { action: "replace" } as const;
264 }
265 // fall through: engine default update (tags sync)
266 }),
267 reconcile: Effect.fn(function* ({ id, news, output, session }) {
268 const clientToken = yield* Effect.sync(() => crypto.randomUUID());
269 const internalTags = yield* createInternalTags(id);
270 const desiredTags = { ...news.tags, ...internalTags };
271
272 // 1. OBSERVE — cloud state is authoritative; output only caches
273 // the server-assigned access point id.
274 let live =
275 output?.accessPointId !== undefined
276 ? yield* observe(output.accessPointId)
277 : yield* findByAlchemyTags(id, news.fileSystemId);
278
279 // 2. ENSURE — create when missing; a concurrent create surfaces
280 // as ConflictException, which we treat as a race and re-find.
281 if (live === undefined) {
282 const created = yield* s3files
283 .createAccessPoint({
284 fileSystemId: news.fileSystemId,
285 posixUser: news.posixUser,
286 rootDirectory: news.rootDirectory,
287 clientToken,
288 tags: toTagList(desiredTags),
289 })
290 .pipe(Effect.catchTag("ConflictException", () => Effect.undefined));
291 live =
292 created !== undefined
293 ? yield* observe(created.accessPointId)
294 : yield* findByAlchemyTags(id, news.fileSystemId);
295 }
296 if (live === undefined) {
297 return yield* new S3FilesNotConverged({
298 resource: `access point on ${news.fileSystemId}`,
299 status: undefined,
300 });
301 }
302 const accessPointId = live.accessPointId;
303
304 // Wait (bounded) for the access point to leave `creating`.
305 const settled = yield* untilSettled(
306 observe(accessPointId),
307 (ap) => ap === undefined || ap.status !== "creating",
308 );
309 if (settled === undefined || settled.status !== "available") {
310 return yield* new S3FilesNotConverged({
311 resource: accessPointId,
312 status: settled?.status,
313 });
314 }
315
316 // 3. SYNC TAGS — diff against observed cloud tags so adoption and
317 // drift converge (create-time tags only apply on first create).
318 yield* syncTags(accessPointId, toTagRecord(settled.tags), desiredTags);
319
320 // 4. RETURN fresh attributes.
321 yield* session.note(accessPointId);
322 return toAttributes(settled);
323 }),
324 delete: Effect.fn(function* ({ output }) {
325 // Idempotent: gone or already deleting counts as success.
326 const live = yield* observe(output.accessPointId);
327 if (live === undefined || live.status === "deleting" || live.status === "deleted") {
328 return;
329 }
330 yield* retryWhileConflict(
331 s3files.deleteAccessPoint({
332 accessPointId: output.accessPointId,
333 }),
334 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
335 }),
336 });
337 }),
338 );