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

main
ts 473 lines 18.2 KB
Raw
1 import * as datazone from "@distilled.cloud/aws/datazone";
2 import * as iam from "@distilled.cloud/aws/iam";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import { AWSEnvironment } from "../Environment.ts";
14 import { syncDataZoneTags, toTagRecord, unredact } from "./internal.ts";
15
16 /**
17 * Single sign-on configuration for a DataZone domain via IAM Identity Center.
18 */
19 export interface DomainSingleSignOn {
20 /** The SSO type — `IAM_IDC` to enable IAM Identity Center, `DISABLED` otherwise. */
21 type?: string;
22 /** How users are assigned — `AUTOMATIC` or `MANUAL`. */
23 userAssignment?: string;
24 /** The ARN of the IAM Identity Center instance. */
25 idcInstanceArn?: string;
26 }
27
28 export interface DomainProps {
29 /**
30 * Display name of the domain. If omitted, a deterministic physical name is
31 * generated from the app, stage, and logical ID. The name is mutable — it
32 * converges via `UpdateDomain` without replacement.
33 */
34 name?: string;
35 /**
36 * A description of the domain.
37 */
38 description?: string;
39 /**
40 * The ARN of an existing IAM role for DataZone to act on behalf of domain
41 * users (metadata catalog, search, etc.). When omitted, an execution role
42 * is created automatically with `datazone.amazonaws.com` trust and the
43 * `AmazonDataZoneDomainExecutionRolePolicy` managed policy attached.
44 */
45 domainExecutionRole?: string;
46 /**
47 * The ARN of the service role used by V2 (SageMaker Unified Studio)
48 * domains. Only relevant when `domainVersion` is `"V2"`.
49 */
50 serviceRole?: string;
51 /**
52 * The identifier of a KMS key to encrypt the domain with. Changing it
53 * triggers a replacement.
54 */
55 kmsKeyIdentifier?: string;
56 /**
57 * The version of the domain — `"V1"` (classic DataZone) or `"V2"`
58 * (SageMaker Unified Studio). Changing it triggers a replacement.
59 * @default "V1"
60 */
61 domainVersion?: string;
62 /**
63 * Single sign-on configuration via IAM Identity Center.
64 */
65 singleSignOn?: DomainSingleSignOn;
66 /**
67 * Tags to apply to the domain. Merged with internal Alchemy tags.
68 */
69 tags?: Record<string, string>;
70 }
71
72 export interface Domain extends Resource<
73 "AWS.DataZone.Domain",
74 DomainProps,
75 {
76 /** The unique identifier of the domain (`dzd_...`). */
77 domainId: string;
78 /** The ARN of the domain. */
79 domainArn: string;
80 /** The display name of the domain. */
81 name: string;
82 /** The status of the domain (`AVAILABLE` once settled). */
83 status: string;
84 /** The URL of the DataZone data portal for this domain. */
85 portalUrl: string | undefined;
86 /** The identifier of the root domain unit. */
87 rootDomainUnitId: string | undefined;
88 /** The ARN of the domain execution role. */
89 domainExecutionRole: string;
90 /**
91 * Name of the auto-created execution role. `undefined` when an explicit
92 * {@link DomainProps.domainExecutionRole} is used.
93 */
94 roleName: string | undefined;
95 }
96 > {}
97
98 /**
99 * An Amazon DataZone domain — the top-level container for data-governance
100 * projects, environments, glossaries, and assets.
101 *
102 * `Domain` owns the domain lifecycle. Domain creation is asynchronous
103 * (typically 1–2 minutes) and is polled to `AVAILABLE` with a bounded wait.
104 * An execution role is created automatically (trusted by
105 * `datazone.amazonaws.com`, with the `AmazonDataZoneDomainExecutionRolePolicy`
106 * managed policy) unless an explicit `domainExecutionRole` is supplied.
107 *
108 * ### Creating Domains
109 * **Example:** Minimal Domain
110 * ```typescript
111 * import * as DataZone from "@alchemy.run/aws/DataZone";
112 *
113 * const domain = yield* DataZone.Domain("governance", {
114 * description: "Company-wide data governance domain",
115 * });
116 * ```
117 *
118 * **Example:** Domain with an Explicit Execution Role
119 * ```typescript
120 * const domain = yield* DataZone.Domain("governance", {
121 * name: "acme-governance",
122 * domainExecutionRole: role.roleArn,
123 * tags: { Team: "data-platform" },
124 * });
125 * ```
126 *
127 * ### Using the Domain
128 * **Example:** Create a Project in the Domain
129 * ```typescript
130 * const project = yield* DataZone.Project("analytics", {
131 * domainId: domain.domainId,
132 * description: "Analytics team project",
133 * });
134 * ```
135 *
136 * @resource
137 */
138 export const Domain = Resource<Domain>("AWS.DataZone.Domain");
139
140 /** The domain never leaves a failed create — surface it as a typed error. */
141 export class DomainCreationFailed extends Data.TaggedError("AWS.DataZone.DomainCreationFailed")<{
142 readonly domainId: string;
143 readonly status: string;
144 }> {}
145
146 /** Domain status values indicating an in-flight transition to wait out. */
147 const DOMAIN_TRANSIENT = new Set(["CREATING", "DELETING"]);
148
149 /**
150 * A freshly created (or re-observed) IAM role is eventually consistent;
151 * `createDomain` / `updateDomain` can transiently reject a role DataZone
152 * cannot yet assume. Wrapped in an explicitly-typed helper so the
153 * `Effect.retry` conditional return type does not leak into declaration emit
154 * and widen the provider layer's requirement to `unknown` (see PATTERNS §7).
155 */
156 const retryWhileRoleAssumeFails = <A, E extends { _tag: string }, R>(
157 self: Effect.Effect<A, E, R>,
158 ): Effect.Effect<A, E, R> =>
159 Effect.retry(self, {
160 while: (e) =>
161 (e._tag === "ValidationException" || e._tag === "AccessDeniedException") &&
162 "message" in e &&
163 typeof e.message === "string" &&
164 (e.message.toLowerCase().includes("role") || e.message.toLowerCase().includes("assume")),
165 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
166 });
167
168 const DOMAIN_EXECUTION_MANAGED_POLICY =
169 "arn:aws:iam::aws:policy/service-role/AmazonDataZoneDomainExecutionRolePolicy";
170
171 export const DomainProvider = () =>
172 Provider.effect(
173 Domain,
174 Effect.gen(function* () {
175 const createName = Effect.fn(function* (id: string, props: DomainProps) {
176 return props.name ?? (yield* createPhysicalName({ id, maxLength: 64 }));
177 });
178
179 const createRoleName = (id: string) => createPhysicalName({ id, maxLength: 64 });
180
181 // A deleted (or never-existing) domain is reported by GetDomain as
182 // AccessDeniedException ("User is not permitted to perform operation:
183 // GetDomain"), NOT ResourceNotFoundException — DataZone evaluates
184 // domain-scoped authorization before existence. Both mean "absent".
185 const getDomainOrUndefined = Effect.fn(function* (identifier: string) {
186 return yield* datazone.getDomain({ identifier }).pipe(
187 Effect.catchTags({
188 ResourceNotFoundException: () => Effect.undefined,
189 AccessDeniedException: () => Effect.undefined,
190 }),
191 );
192 });
193
194 const findByName = Effect.fn(function* (name: string) {
195 const pages = yield* datazone.listDomains.pages({}).pipe(Stream.runCollect);
196 const summary = Array.from(pages)
197 .flatMap((page) => page.items ?? [])
198 .find(
199 (s) => unredact(s.name) === name && s.status !== "DELETING" && s.status !== "DELETED",
200 );
201 return summary?.id;
202 });
203
204 // Poll the domain to a settled (non-transient) status. V1 domains are
205 // usually AVAILABLE synchronously; V2 creation takes 1-2 minutes —
206 // bounded at ~3 minutes. An "absent" observation keeps polling: right
207 // after createDomain the creator's user profile can lag, surfacing the
208 // same AccessDenied that a deleted domain does.
209 const waitForSettled = Effect.fn(function* (identifier: string) {
210 return yield* getDomainOrUndefined(identifier).pipe(
211 Effect.repeat({
212 schedule: Schedule.fixed("5 seconds"),
213 until: (domain) => domain !== undefined && !DOMAIN_TRANSIENT.has(domain.status),
214 times: 36,
215 }),
216 );
217 });
218
219 // Poll the domain until it no longer exists. Domain deletion typically
220 // completes in 1-2 minutes — bounded at ~3 minutes.
221 const waitForGone = Effect.fn(function* (identifier: string) {
222 yield* getDomainOrUndefined(identifier).pipe(
223 Effect.repeat({
224 schedule: Schedule.fixed("5 seconds"),
225 until: (domain) => domain === undefined || domain.status === "DELETED",
226 times: 36,
227 }),
228 );
229 });
230
231 const domainArnOf = (region: string, accountId: string, domainId: string) =>
232 `arn:aws:datazone:${region}:${accountId}:domain/${domainId}`;
233
234 const ensureExecutionRole = Effect.fn(function* ({
235 id,
236 roleName,
237 accountId,
238 }: {
239 id: string;
240 roleName: string;
241 accountId: string;
242 }) {
243 const tags = yield* createInternalTags(id);
244 const role = yield* iam
245 .createRole({
246 RoleName: roleName,
247 AssumeRolePolicyDocument: JSON.stringify({
248 Version: "2012-10-17",
249 Statement: [
250 {
251 Effect: "Allow",
252 Principal: { Service: "datazone.amazonaws.com" },
253 Action: ["sts:AssumeRole", "sts:TagSession"],
254 Condition: {
255 StringEquals: { "aws:SourceAccount": accountId },
256 "ForAllValues:StringLike": { "aws:TagKeys": "datazone*" },
257 },
258 },
259 ],
260 }),
261 Tags: Object.entries(tags).map(([Key, Value]) => ({ Key, Value })),
262 })
263 .pipe(
264 Effect.catchTag("EntityAlreadyExistsException", () =>
265 iam.getRole({ RoleName: roleName }),
266 ),
267 );
268
269 yield* iam
270 .attachRolePolicy({
271 RoleName: roleName,
272 PolicyArn: DOMAIN_EXECUTION_MANAGED_POLICY,
273 })
274 .pipe(
275 // attaching an already-attached managed policy is a no-op, but
276 // tolerate racy duplicates anyway.
277 Effect.catchTag("InvalidInputException", () => Effect.void),
278 );
279
280 return role.Role.Arn;
281 });
282
283 return Domain.Provider.of({
284 stables: ["domainId", "domainArn", "rootDomainUnitId"],
285
286 list: () =>
287 Effect.gen(function* () {
288 const { region, accountId } = yield* AWSEnvironment.current;
289 const pages = yield* datazone.listDomains.pages({}).pipe(Stream.runCollect);
290 const summaries = Array.from(pages)
291 .flatMap((page) => page.items ?? [])
292 .filter((s) => s.status !== "DELETING" && s.status !== "DELETED");
293 return summaries.map((s) => ({
294 domainId: s.id,
295 domainArn: s.arn ?? domainArnOf(region, accountId, s.id),
296 name: unredact(s.name),
297 status: s.status,
298 portalUrl: s.portalUrl,
299 rootDomainUnitId: undefined as string | undefined,
300 domainExecutionRole: "",
301 roleName: undefined as string | undefined,
302 }));
303 }),
304
305 read: Effect.fn(function* ({ id, olds, output }) {
306 const { region, accountId } = yield* AWSEnvironment.current;
307 const domainId =
308 output?.domainId ??
309 (yield* findByName(output?.name ?? (yield* createName(id, olds ?? {}))));
310 if (domainId === undefined) return undefined;
311 const domain = yield* getDomainOrUndefined(domainId);
312 if (domain === undefined || domain.status === "DELETING" || domain.status === "DELETED") {
313 return undefined;
314 }
315 const attrs = {
316 domainId: domain.id,
317 domainArn: domain.arn ?? domainArnOf(region, accountId, domain.id),
318 name: domain.name ?? "",
319 status: domain.status,
320 portalUrl: domain.portalUrl,
321 rootDomainUnitId: domain.rootDomainUnitId,
322 domainExecutionRole: domain.domainExecutionRole,
323 roleName: output?.roleName,
324 };
325 const tags = toTagRecord(domain.tags);
326 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
327 }),
328
329 diff: Effect.fn(function* ({ news, olds }) {
330 if (!isResolved(news)) return undefined;
331 if (olds?.kmsKeyIdentifier !== news?.kmsKeyIdentifier) {
332 return { action: "replace" } as const;
333 }
334 if (olds?.domainVersion !== news?.domainVersion) {
335 return { action: "replace" } as const;
336 }
337 // name, description, execution role, service role, SSO, and tags
338 // all converge via updateDomain / tagResource.
339 }),
340
341 reconcile: Effect.fn(function* ({ id, news, output, session }) {
342 const { accountId, region } = yield* AWSEnvironment.current;
343 const name = yield* createName(id, news);
344 const internalTags = yield* createInternalTags(id);
345 const desiredTags = { ...news.tags, ...internalTags };
346
347 // Ensure the execution role first — the domain cannot exist without
348 // one. Managed unless an explicit domainExecutionRole is provided.
349 let executionRoleArn = news.domainExecutionRole;
350 let roleName = output?.roleName;
351 if (executionRoleArn === undefined) {
352 roleName = roleName ?? (yield* createRoleName(id));
353 executionRoleArn = yield* ensureExecutionRole({
354 id,
355 roleName,
356 accountId,
357 });
358 }
359
360 // 1. OBSERVE — cloud state is authoritative; output is only an id
361 // cache. Fall back to a name lookup after state loss.
362 let domain = output?.domainId ? yield* getDomainOrUndefined(output.domainId) : undefined;
363 if (domain === undefined) {
364 const foundId = yield* findByName(name);
365 if (foundId !== undefined) {
366 domain = yield* getDomainOrUndefined(foundId);
367 }
368 }
369
370 if (domain === undefined) {
371 // 2. ENSURE — create and wait out the async provisioning.
372 const created = yield* retryWhileRoleAssumeFails(
373 datazone.createDomain({
374 name,
375 description: news.description,
376 domainExecutionRole: executionRoleArn,
377 serviceRole: news.serviceRole,
378 kmsKeyIdentifier: news.kmsKeyIdentifier,
379 domainVersion: news.domainVersion,
380 singleSignOn: news.singleSignOn,
381 tags: desiredTags,
382 }),
383 );
384 domain = (yield* waitForSettled(created.id)) ?? undefined;
385 if (domain === undefined || domain.status !== "AVAILABLE") {
386 return yield* new DomainCreationFailed({
387 domainId: created.id,
388 status: domain?.status ?? "CREATING",
389 });
390 }
391 } else {
392 // 3. SYNC — wait out any in-flight transition, then converge the
393 // mutable aspects by diffing OBSERVED state against desired.
394 domain = (yield* waitForSettled(domain.id)) ?? domain;
395 const drifted =
396 domain.name !== name ||
397 (domain.description ?? undefined) !== (news.description ?? undefined) ||
398 domain.domainExecutionRole !== executionRoleArn ||
399 (news.serviceRole !== undefined && domain.serviceRole !== news.serviceRole);
400 if (drifted) {
401 yield* retryWhileRoleAssumeFails(
402 datazone.updateDomain({
403 identifier: domain.id,
404 name,
405 description: news.description,
406 domainExecutionRole: executionRoleArn,
407 serviceRole: news.serviceRole,
408 singleSignOn: news.singleSignOn,
409 }),
410 );
411 domain = (yield* getDomainOrUndefined(domain.id)) ?? domain;
412 }
413 }
414
415 const domainId = domain.id;
416 const domainArn = domain.arn ?? domainArnOf(region, accountId, domainId);
417
418 // 3b. SYNC TAGS — diff against OBSERVED cloud tags (create-time tags
419 // only apply on first create; adoption may carry foreign tags).
420 yield* syncDataZoneTags(domainArn, toTagRecord(domain.tags), desiredTags);
421
422 yield* session.note(domainId);
423 return {
424 domainId,
425 domainArn,
426 name: domain.name ?? name,
427 status: domain.status,
428 portalUrl: domain.portalUrl,
429 rootDomainUnitId: domain.rootDomainUnitId,
430 domainExecutionRole: executionRoleArn,
431 roleName,
432 };
433 }),
434
435 delete: Effect.fn(function* ({ output }) {
436 yield* datazone
437 .deleteDomain({
438 identifier: output.domainId,
439 skipDeletionCheck: true,
440 })
441 .pipe(
442 Effect.catchTags({
443 ResourceNotFoundException: () => Effect.void,
444 // an already-deleted domain surfaces as AccessDenied ("User is
445 // not permitted to perform operation: DeleteDomain") — DataZone
446 // checks domain-scoped auth before existence.
447 AccessDeniedException: () => Effect.void,
448 // a concurrent DELETING domain rejects a second delete — the
449 // wait below observes it through to gone either way.
450 ConflictException: () => Effect.void,
451 }),
452 );
453 yield* waitForGone(output.domainId);
454
455 // Tear down the managed execution role (absent when an explicit
456 // domainExecutionRole was supplied). Every step tolerates a
457 // partially or fully removed role.
458 if (output.roleName !== undefined) {
459 const roleName = output.roleName;
460 yield* iam
461 .detachRolePolicy({
462 RoleName: roleName,
463 PolicyArn: DOMAIN_EXECUTION_MANAGED_POLICY,
464 })
465 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
466 yield* iam
467 .deleteRole({ RoleName: roleName })
468 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
469 }
470 }),
471 });
472 }),
473 );