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

main
ts 221 lines 8.28 KB
Raw
1 import * as lf from "@distilled.cloud/aws/lakeformation";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource as AlchemyResource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Stream from "effect/Stream";
7 import type { Providers } from "../Providers.ts";
8
9 export interface ResourceProps {
10 /**
11 * ARN of the S3 location to register with Lake Formation (e.g.
12 * `arn:aws:s3:::my-bucket` or `arn:aws:s3:::my-bucket/prefix`). Changing it
13 * replaces the registration.
14 */
15 resourceArn: string;
16 /**
17 * IAM role Lake Formation uses to vend credentials for the location. When
18 * omitted, the `AWSServiceRoleForLakeFormationDataAccess` service-linked
19 * role is used (and created on first registration).
20 */
21 roleArn?: string;
22 /**
23 * Register using the Lake Formation service-linked role. Only meaningful
24 * when `roleArn` is omitted.
25 * @default true when `roleArn` is omitted
26 */
27 useServiceLinkedRole?: boolean;
28 /**
29 * Whether to register the location with federation (Redshift data sharing).
30 * @default false
31 */
32 withFederation?: boolean;
33 /**
34 * Allow both Lake Formation permissions and IAM/S3 policies to govern
35 * access to the location (hybrid access mode).
36 * @default false
37 */
38 hybridAccessEnabled?: boolean;
39 }
40
41 export interface Resource extends AlchemyResource<
42 "AWS.LakeFormation.Resource",
43 ResourceProps,
44 {
45 resourceArn: string;
46 roleArn: string | undefined;
47 withFederation: boolean | undefined;
48 hybridAccessEnabled: boolean | undefined;
49 },
50 {},
51 Providers
52 > {}
53
54 /**
55 * Registers an S3 location as managed by AWS Lake Formation, so Lake
56 * Formation can vend temporary credentials for data stored there
57 * (`DATA_LOCATION_ACCESS` grants, governed tables, etc.).
58 *
59 * ### Registering Locations
60 * **Example:** Register a Bucket with the Service-Linked Role
61 * ```typescript
62 * import * as AWS from "@alchemy.run/aws";
63 *
64 * const bucket = yield* AWS.S3.Bucket("DataLake", {});
65 * const location = yield* AWS.LakeFormation.Resource("DataLakeLocation", {
66 * resourceArn: bucket.bucketArn,
67 * });
68 * ```
69 *
70 * **Example:** Register with a Custom Data-Access Role
71 * ```typescript
72 * const location = yield* AWS.LakeFormation.Resource("DataLakeLocation", {
73 * resourceArn: bucket.bucketArn,
74 * roleArn: dataAccessRole.roleArn,
75 * hybridAccessEnabled: true,
76 * });
77 * ```
78 *
79 * @resource
80 */
81 export const Resource = AlchemyResource<Resource>("AWS.LakeFormation.Resource");
82
83 export const ResourceProvider = () =>
84 Provider.effect(
85 Resource,
86 Effect.gen(function* () {
87 const observe = Effect.fn(function* (resourceArn: string) {
88 return yield* lf.describeResource({ ResourceArn: resourceArn }).pipe(
89 Effect.map((r) => r.ResourceInfo),
90 Effect.catchTag("EntityNotFoundException", () => Effect.undefined),
91 );
92 });
93
94 return Resource.Provider.of({
95 stables: ["resourceArn"],
96
97 list: () =>
98 Effect.gen(function* () {
99 const pages = yield* lf.listResources.pages({}).pipe(Stream.runCollect);
100 return Array.from(pages)
101 .flatMap((page) => page.ResourceInfoList ?? [])
102 .filter((info) => info.ResourceArn !== undefined)
103 .map((info) => ({
104 resourceArn: info.ResourceArn!,
105 roleArn: info.RoleArn,
106 withFederation: info.WithFederation,
107 hybridAccessEnabled: info.HybridAccessEnabled,
108 }));
109 }),
110
111 read: Effect.fn(function* ({ olds, output }) {
112 const resourceArn = output?.resourceArn ?? olds?.resourceArn;
113 if (resourceArn === undefined) return undefined;
114 const info = yield* observe(resourceArn);
115 if (info === undefined) return undefined;
116 // Registrations are not taggable, so ownership cannot be verified —
117 // return the attributes directly.
118 return {
119 resourceArn,
120 roleArn: info.RoleArn,
121 withFederation: info.WithFederation,
122 hybridAccessEnabled: info.HybridAccessEnabled,
123 };
124 }),
125
126 diff: Effect.fn(function* ({ news, olds }) {
127 if (!isResolved(news)) return undefined;
128 if (news.resourceArn !== olds.resourceArn) {
129 return { action: "replace" } as const;
130 }
131 // roleArn / withFederation / hybridAccessEnabled → update
132 }),
133
134 reconcile: Effect.fn(function* ({ news, session }) {
135 const resourceArn = news.resourceArn;
136 const register = lf.registerResource({
137 ResourceArn: resourceArn,
138 UseServiceLinkedRole:
139 news.roleArn !== undefined ? undefined : (news.useServiceLinkedRole ?? true),
140 RoleArn: news.roleArn,
141 WithFederation: news.withFederation,
142 HybridAccessEnabled: news.hybridAccessEnabled,
143 });
144
145 // 1. OBSERVE
146 let info = yield* observe(resourceArn);
147
148 // 2. ENSURE
149 if (info === undefined) {
150 yield* register.pipe(Effect.catchTag("AlreadyExistsException", () => Effect.void));
151 info = yield* observe(resourceArn);
152 } else {
153 // 3. SYNC — role and registration flags, observed vs desired.
154 const desiredRole = news.roleArn;
155 const roleDrift = desiredRole !== undefined && desiredRole !== info.RoleArn;
156 const hybridDrift =
157 news.hybridAccessEnabled !== undefined &&
158 news.hybridAccessEnabled !== (info.HybridAccessEnabled ?? false);
159 const federationDrift =
160 news.withFederation !== undefined &&
161 news.withFederation !== (info.WithFederation ?? false);
162 if (roleDrift || hybridDrift || federationDrift) {
163 const slrManaged =
164 info.RoleArn?.includes("/aws-service-role/lakeformation.amazonaws.com/") ?? false;
165 if (slrManaged) {
166 // UpdateResource rejects registrations held by the
167 // service-linked role ("Resource managed by Service Linked
168 // Role") — recreate the registration in place instead.
169 yield* lf.deregisterResource({ ResourceArn: resourceArn }).pipe(
170 Effect.catchTags({
171 EntityNotFoundException: () => Effect.void,
172 // spurious error on the last SLR location — the
173 // deregistration still succeeds (see delete below)
174 LastServiceLinkedRoleRegistration: () => Effect.void,
175 }),
176 );
177 yield* register;
178 } else {
179 const updateRole = desiredRole ?? info.RoleArn;
180 if (updateRole !== undefined) {
181 yield* lf.updateResource({
182 ResourceArn: resourceArn,
183 RoleArn: updateRole,
184 WithFederation: news.withFederation,
185 HybridAccessEnabled: news.hybridAccessEnabled,
186 });
187 }
188 }
189 info = yield* observe(resourceArn);
190 }
191 }
192
193 yield* session.note(resourceArn);
194 return {
195 resourceArn,
196 roleArn: info?.RoleArn,
197 withFederation: info?.WithFederation,
198 hybridAccessEnabled: info?.HybridAccessEnabled,
199 };
200 }),
201
202 delete: Effect.fn(function* ({ output }) {
203 yield* lf.deregisterResource({ ResourceArn: output.resourceArn }).pipe(
204 Effect.catchTags({
205 EntityNotFoundException: () => Effect.void,
206 // Deregistering the LAST location registered with the
207 // service-linked role returns "Must manually delete
208 // service-linked role to deregister last S3 location" even
209 // though the registration IS removed (verified live). Verify
210 // and only re-fail if the registration is still present.
211 LastServiceLinkedRoleRegistration: (error) =>
212 lf.describeResource({ ResourceArn: output.resourceArn }).pipe(
213 Effect.flatMap(() => Effect.fail(error)),
214 Effect.catchTag("EntityNotFoundException", () => Effect.void),
215 ),
216 }),
217 );
218 }),
219 });
220 }),
221 );