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

main
ts 239 lines 7.55 KB
Raw
1 import * as organizations from "@distilled.cloud/aws/organizations";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9 import {
10 collectPages,
11 readResourceTags,
12 retryOrganizations,
13 updateResourceTags,
14 } from "./common.ts";
15
16 export class RootUnexpectedResponse extends Data.TaggedError("RootUnexpectedResponse")<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export type RootId = string;
22 export type RootArn = string;
23
24 export interface RootProps {
25 /**
26 * Optional root ID to import explicitly.
27 * If omitted, Alchemy adopts the single organization root.
28 */
29 rootId?: string;
30 /**
31 * Optional root name to match when multiple roots are ever supported.
32 */
33 name?: string;
34 /**
35 * Optional tags to apply to the imported root.
36 */
37 tags?: Record<string, string>;
38 }
39
40 export interface Root extends Resource<
41 "AWS.Organizations.Root",
42 RootProps,
43 {
44 /**
45 * ID of the root (e.g. `r-examplerootid`).
46 */
47 rootId: RootId;
48 /**
49 * ARN of the root.
50 */
51 rootArn: RootArn;
52 /**
53 * Friendly name of the root (usually `Root`).
54 */
55 rootName: string;
56 /**
57 * Policy types and their enablement status on this root.
58 */
59 policyTypes: organizations.PolicyTypeSummary[];
60 /**
61 * Tags on the root.
62 */
63 tags: Record<string, string>;
64 },
65 never,
66 Providers
67 > {}
68
69 /**
70 * The organization root.
71 *
72 * `Root` is an import-style resource. It discovers the existing root returned by
73 * AWS Organizations and can reconcile root tags. Use `root.rootId` as the
74 * `parentId` for top-level {@link OrganizationalUnit}s and {@link Account}s,
75 * and as the `targetId`/`rootId` for {@link PolicyAttachment} and
76 * {@link RootPolicyType}.
77 * ### Importing the Root
78 * **Example:** Adopt the Organization Root
79 * ```typescript
80 * const organization = yield* Organization("Org", { featureSet: "ALL" });
81 * const root = yield* Root("Root", {});
82 * ```
83 *
84 * **Example:** Parent OUs and Accounts Under the Root
85 * ```typescript
86 * const workloads = yield* OrganizationalUnit("Workloads", {
87 * parentId: root.rootId,
88 * name: "workloads",
89 * });
90 *
91 * const sandbox = yield* Account("Sandbox", {
92 * name: "sandbox",
93 * email: "aws-sandbox@example.com",
94 * parentId: root.rootId,
95 * });
96 * ```
97 *
98 * @resource
99 */
100 export const Root = Resource<Root>("AWS.Organizations.Root");
101
102 export const RootProvider = () =>
103 Provider.effect(
104 Root,
105 Effect.gen(function* () {
106 return {
107 stables: ["rootId", "rootArn"],
108 // Enumerate every organization root via `listRoots` (paginated) and
109 // hydrate each into the exact `read` Attributes shape, fetching tags
110 // with bounded concurrency. Degrades to `[]` when the caller isn't an
111 // organization management account (the account isn't in an org, or
112 // lacks Organizations permissions) via the typed catches below.
113 list: () =>
114 Effect.gen(function* () {
115 const roots = yield* retryOrganizations(
116 organizations.listRoots.pages({}).pipe(
117 Stream.runCollect,
118 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Roots ?? [])),
119 ),
120 ).pipe(
121 Effect.catchTags({
122 AWSOrganizationsNotInUseException: () => Effect.succeed([]),
123 AccessDeniedException: () => Effect.succeed([]),
124 }),
125 );
126
127 const valid = roots.filter(
128 (
129 root,
130 ): root is typeof root & {
131 Id: string;
132 Arn: string;
133 Name: string;
134 } => root.Id != null && root.Arn != null && root.Name != null,
135 );
136
137 const attrs: (Root["Attributes"] | undefined)[] = yield* Effect.forEach(
138 valid,
139 Effect.fn(function* (root) {
140 if (!root.Id || !root.Arn || !root.Name) return undefined;
141 const tags = yield* readResourceTags(root.Id).pipe(
142 Effect.catchTag("TargetNotFoundException", () => Effect.succeed({})),
143 );
144 return {
145 rootId: root.Id,
146 rootArn: root.Arn,
147 rootName: root.Name,
148 policyTypes: root.PolicyTypes ?? [],
149 tags,
150 };
151 }),
152 { concurrency: 10 },
153 );
154 return attrs.filter((attr): attr is Root["Attributes"] => attr !== undefined);
155 }),
156 diff: Effect.fn(function* ({ olds, news, output }) {
157 if (!isResolved(news)) return;
158 // `rootId` and `name` only select which root to adopt. Adding,
159 // removing, or pinning one that matches the adopted root is a noop;
160 // only a selector pointing at a different root replaces.
161 if (news.rootId !== undefined && news.rootId !== (output?.rootId ?? olds?.rootId)) {
162 return { action: "replace" } as const;
163 }
164 if (news.name !== undefined && news.name !== (output?.rootName ?? olds?.name)) {
165 return { action: "replace" } as const;
166 }
167 }),
168 read: Effect.fn(function* ({ olds, output }) {
169 return yield* readRoot({
170 rootId: output?.rootId ?? olds?.rootId,
171 name: olds?.name,
172 });
173 }),
174 reconcile: Effect.fn(function* ({ id, news, output, session }) {
175 // Observe — discover the live root. `Root` is import-only: AWS
176 // creates the root for us when the organization is created, and we
177 // never create or delete it. We always look it up fresh.
178 const root = yield* readRoot({
179 rootId: output?.rootId ?? news.rootId,
180 name: news.name,
181 });
182 if (!root) {
183 return yield* new RootUnexpectedResponse({
184 message: output?.rootId
185 ? `organization root '${output.rootId}' not found`
186 : "organization root not found",
187 });
188 }
189
190 // Sync tags — diff observed cloud tags against desired. Using
191 // `root.tags` as the baseline (instead of stale `olds.tags`) keeps
192 // the reconciler convergent even on adoption or after drift.
193 const tags = yield* updateResourceTags({
194 id,
195 resourceId: root.rootId,
196 olds: root.tags,
197 news: news.tags,
198 });
199
200 yield* session.note(root.rootArn);
201 return {
202 ...root,
203 tags,
204 };
205 }),
206 delete: Effect.fn(function* () {}),
207 };
208 }),
209 );
210
211 const listRoots = () =>
212 collectPages(
213 (NextToken) => organizations.listRoots({ NextToken }),
214 (page) => page.Roots,
215 );
216
217 const readRoot = Effect.fn(function* ({ rootId, name }: { rootId?: string; name?: string }) {
218 const roots = yield* retryOrganizations(listRoots());
219 const root = roots.find(
220 (candidate) =>
221 (rootId ? candidate.Id === rootId : true) && (name ? candidate.Name === name : true),
222 );
223
224 if (!root?.Id || !root.Arn || !root.Name) {
225 return undefined;
226 }
227
228 const tags = yield* readResourceTags(root.Id).pipe(
229 Effect.catchTag("TargetNotFoundException", () => Effect.succeed({})),
230 );
231
232 return {
233 rootId: root.Id,
234 rootArn: root.Arn,
235 rootName: root.Name,
236 policyTypes: root.PolicyTypes ?? [],
237 tags,
238 } satisfies Root["Attributes"];
239 });