@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 415 lines 13.2 KB
Raw
1 import * as accountManagement from "@distilled.cloud/aws/account";
2 import * as organizations from "@distilled.cloud/aws/organizations";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { 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 type { Providers } from "../Providers.ts";
12 import {
13 collectPages,
14 readResourceTags,
15 retryOrganizations,
16 unredact,
17 updateResourceTags,
18 } from "./common.ts";
19
20 export class OrganizationsAccountOperationFailed extends Data.TaggedError(
21 "OrganizationsAccountOperationFailed",
22 )<{
23 readonly message: string;
24 readonly cause?: unknown;
25 }> {}
26
27 export class OrganizationsAccountUnexpectedResponse extends Data.TaggedError(
28 "OrganizationsAccountUnexpectedResponse",
29 )<{
30 readonly message: string;
31 readonly cause?: unknown;
32 }> {}
33
34 export type AccountId = string;
35 export type AccountArn = string;
36
37 export interface AccountProps {
38 /**
39 * Account email. Must be globally unique across AWS accounts.
40 */
41 email: string;
42 /**
43 * Friendly account name.
44 */
45 name: string;
46 /**
47 * Parent root or OU ID.
48 */
49 parentId: string;
50 /**
51 * Optional cross-account access role name created during account vending.
52 */
53 roleName?: string;
54 /**
55 * Whether IAM users can access billing information.
56 */
57 iamUserAccessToBilling?: organizations.IAMUserAccessToBilling;
58 /**
59 * Optional tags applied to the member account while it remains in the org.
60 */
61 tags?: Record<string, string>;
62 }
63
64 export interface Account extends Resource<
65 "AWS.Organizations.Account",
66 AccountProps,
67 {
68 /**
69 * 12-digit AWS account ID.
70 */
71 accountId: AccountId;
72 /**
73 * ARN of the member account.
74 */
75 accountArn: AccountArn;
76 /**
77 * Friendly account name.
78 */
79 name: string | undefined;
80 /**
81 * Email address associated with the account.
82 */
83 email: string | undefined;
84 /**
85 * ID of the parent root or OU.
86 */
87 parentId: string | undefined;
88 /**
89 * Account status (`ACTIVE`, `SUSPENDED`, or `PENDING_CLOSURE`).
90 */
91 status: organizations.AccountStatus | undefined;
92 /**
93 * Account state reported by AWS Organizations.
94 */
95 state: organizations.AccountState | undefined;
96 /**
97 * How the account joined the organization (`CREATED` or `INVITED`).
98 */
99 joinedMethod: organizations.AccountJoinedMethod | undefined;
100 /**
101 * When the account joined the organization.
102 */
103 joinedTimestamp: Date | undefined;
104 /**
105 * Tags on the member account.
106 */
107 tags: Record<string, string>;
108 },
109 never,
110 Providers
111 > {}
112
113 /**
114 * A member account created and managed by AWS Organizations.
115 *
116 * Account creation is asynchronous — the provider polls the vending request
117 * until the account ID is assigned. Must be deployed from the organization's
118 * management account. Changing `email` replaces the account; changing `name`
119 * updates it in place.
120 * ### Creating Member Accounts
121 * **Example:** Account Under the Organization Root
122 * ```typescript
123 * const root = yield* Root("Root", {});
124 *
125 * const dev = yield* Account("Dev", {
126 * name: "dev",
127 * email: "aws-dev@example.com",
128 * parentId: root.rootId,
129 * });
130 * ```
131 *
132 * **Example:** Account Inside an Organizational Unit
133 * ```typescript
134 * const workloads = yield* OrganizationalUnit("Workloads", {
135 * parentId: root.rootId,
136 * name: "workloads",
137 * });
138 *
139 * const prod = yield* Account("Prod", {
140 * name: "prod",
141 * email: "aws-prod@example.com",
142 * parentId: workloads.ouId,
143 * roleName: "OrganizationAccountAccessRole",
144 * tags: { environment: "prod" },
145 * });
146 * ```
147 *
148 * @resource
149 */
150 export const Account = Resource<Account>("AWS.Organizations.Account");
151
152 export const AccountProvider = () =>
153 Provider.effect(
154 Account,
155 Effect.gen(function* () {
156 return {
157 stables: ["accountId", "accountArn", "joinedMethod", "joinedTimestamp"],
158 diff: Effect.fn(function* ({ olds, news }) {
159 if (!isResolved(news)) return;
160 if (olds?.email !== news.email) {
161 return { action: "replace" } as const;
162 }
163 if (olds?.name !== news.name) {
164 return { action: "update" } as const;
165 }
166 }),
167 read: Effect.fn(function* ({ id, olds, output }) {
168 const state = output?.accountId
169 ? yield* readAccountById(output.accountId)
170 : olds
171 ? yield* readAccountByNameOrEmail({
172 name: olds.name,
173 email: olds.email,
174 })
175 : undefined;
176 if (!state) return undefined;
177 return (yield* hasAlchemyTags(id, state.tags)) ? state : Unowned(state);
178 }),
179 reconcile: Effect.fn(function* ({ id, news, output, session }) {
180 // Observe — locate the account by ID if known, else by
181 // name/email. We always fetch fresh: state persistence may have
182 // failed after a prior `createAccount`, leaving an account on AWS
183 // we have no record of.
184 let state = output?.accountId
185 ? yield* readAccountById(output.accountId)
186 : yield* readAccountByNameOrEmail({
187 name: news.name,
188 email: news.email,
189 });
190
191 // Ensure — create the account if it doesn't exist. Account
192 // creation is asynchronous: `createAccount` returns a
193 // `CreateAccountStatus` which we poll until the account ID is
194 // assigned (or the request fails).
195 if (!state) {
196 const createResponse = yield* retryOrganizations(
197 organizations.createAccount({
198 Email: news.email,
199 AccountName: news.name,
200 RoleName: news.roleName,
201 IamUserAccessToBilling: news.iamUserAccessToBilling,
202 }),
203 );
204
205 const requestId = createResponse.CreateAccountStatus?.Id;
206 if (requestId) {
207 const status = yield* waitForCreateAccount(requestId);
208 yield* session.note(status.AccountId ?? requestId);
209 state = status.AccountId
210 ? yield* readAccountById(status.AccountId)
211 : yield* readAccountByNameOrEmail({
212 name: news.name,
213 email: news.email,
214 });
215 } else {
216 state = yield* readAccountByNameOrEmail({
217 name: news.name,
218 email: news.email,
219 });
220 }
221 if (!state) {
222 return yield* new OrganizationsAccountUnexpectedResponse({
223 message: `account '${news.name}' not found after create`,
224 });
225 }
226 }
227
228 // Sync name — observed ↔ desired. Account name lives on the
229 // account-management service, not Organizations. The diff has
230 // already short-circuited any email change as a replacement.
231 if (state.name !== news.name) {
232 yield* retryAccountManagement(
233 accountManagement.putAccountName({
234 AccountId: state.accountId,
235 AccountName: news.name,
236 }),
237 );
238 }
239
240 // Sync parent — move the account if its observed parent differs
241 // from desired. We only move when we know the source parent (the
242 // API requires it).
243 if (state.parentId && state.parentId !== news.parentId) {
244 yield* retryOrganizations(
245 organizations.moveAccount({
246 AccountId: state.accountId,
247 SourceParentId: state.parentId,
248 DestinationParentId: news.parentId,
249 }),
250 );
251 }
252
253 // Sync tags — diff observed cloud tags against desired so
254 // adoption and drift converge. We baseline against `state.tags`
255 // (fetched fresh) instead of stale `olds`.
256 const tags = yield* updateResourceTags({
257 id,
258 resourceId: state.accountId,
259 olds: state.tags,
260 news: news.tags,
261 });
262
263 const updated = yield* readAccountById(state.accountId);
264 if (!updated) {
265 return yield* new OrganizationsAccountUnexpectedResponse({
266 message: `account '${state.accountId}' not found after reconcile`,
267 });
268 }
269
270 yield* session.note(updated.accountArn);
271 return {
272 ...updated,
273 tags,
274 };
275 }),
276 delete: Effect.fn(function* ({ output }) {
277 yield* retryOrganizations(
278 organizations
279 .removeAccountFromOrganization({
280 AccountId: output.accountId,
281 })
282 .pipe(
283 Effect.catchTags({
284 AccountNotFoundException: () => Effect.void,
285 AWSOrganizationsNotInUseException: () => Effect.void,
286 }),
287 ),
288 );
289 }),
290 // Enumerate every account in the organization (paginated), then
291 // hydrate each into the exact `read` Attributes shape (parent + tags)
292 // with bounded concurrency. Per-item not-found is already typed and
293 // swallowed inside `readAccountById`. When the caller's account is not
294 // the management account of an organization there is nothing to
295 // enumerate, so we return an empty array rather than throwing.
296 list: () =>
297 Effect.gen(function* () {
298 const accounts = yield* listAccounts();
299 const rows = yield* Effect.forEach(
300 accounts,
301 (account) => (account.Id ? readAccountById(account.Id) : Effect.undefined),
302 { concurrency: 10 },
303 );
304 return rows.filter((row): row is Account["Attributes"] => row !== undefined);
305 }).pipe(
306 Effect.catchTag("AWSOrganizationsNotInUseException", () =>
307 Effect.succeed([] as Account["Attributes"][]),
308 ),
309 ),
310 };
311 }),
312 );
313
314 const listAccounts = () =>
315 collectPages(
316 (NextToken) => organizations.listAccounts({ NextToken }),
317 (page) => page.Accounts,
318 ).pipe(retryOrganizations);
319
320 const readParentId = (childId: string) =>
321 collectPages(
322 (NextToken) => organizations.listParents({ ChildId: childId, NextToken }),
323 (page) => page.Parents,
324 ).pipe(
325 retryOrganizations,
326 Effect.map((parents) => parents[0]?.Id),
327 Effect.catchTag("ChildNotFoundException", () => Effect.undefined),
328 );
329
330 const readAccountById = Effect.fn(function* (accountId: string) {
331 const described = yield* retryOrganizations(
332 organizations.describeAccount({ AccountId: accountId }).pipe(
333 Effect.map((response) => response.Account),
334 Effect.catchTag("AccountNotFoundException", () => Effect.undefined),
335 ),
336 );
337
338 if (!described?.Id || !described.Arn) {
339 return undefined;
340 }
341
342 const [parentId, tags] = yield* Effect.all([
343 readParentId(described.Id),
344 readResourceTags(described.Id).pipe(
345 Effect.catchTag("TargetNotFoundException", () => Effect.succeed({})),
346 ),
347 ]);
348
349 return {
350 accountId: described.Id,
351 accountArn: described.Arn,
352 name: unredact(described.Name),
353 email: unredact(described.Email),
354 parentId,
355 status: described.Status,
356 state: described.State,
357 joinedMethod: described.JoinedMethod,
358 joinedTimestamp: described.JoinedTimestamp,
359 tags,
360 } satisfies Account["Attributes"];
361 });
362
363 const readAccountByNameOrEmail = Effect.fn(function* ({
364 name,
365 email,
366 }: Pick<AccountProps, "name" | "email">) {
367 const accounts = yield* listAccounts();
368 const match = accounts.find(
369 (candidate) => unredact(candidate.Name) === name || unredact(candidate.Email) === email,
370 );
371 return match?.Id ? yield* readAccountById(match.Id) : undefined;
372 });
373
374 const waitForCreateAccount = (requestId: string) =>
375 Effect.gen(function* () {
376 const status = yield* retryOrganizations(
377 organizations
378 .describeCreateAccountStatus({
379 CreateAccountRequestId: requestId,
380 })
381 .pipe(Effect.map((response) => response.CreateAccountStatus)),
382 );
383
384 if (!status?.State || status.State === "IN_PROGRESS") {
385 return yield* Effect.fail({ _tag: "CreateAccountInProgress" as const });
386 }
387
388 if (status.State === "FAILED") {
389 return yield* new OrganizationsAccountOperationFailed({
390 message: `account creation failed: ${status.FailureReason ?? "unknown failure"}`,
391 });
392 }
393
394 if (!status.AccountId) {
395 return yield* new OrganizationsAccountUnexpectedResponse({
396 message: "account creation succeeded without AccountId",
397 });
398 }
399
400 return status;
401 }).pipe(
402 Effect.retry({
403 while: (error: any) => error?._tag === "CreateAccountInProgress",
404 schedule: Schedule.max([Schedule.spaced("2 seconds"), Schedule.recurs(120)]),
405 }),
406 );
407
408 const retryAccountManagement = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
409 effect.pipe(
410 Effect.retry({
411 while: (error: any) =>
412 error?._tag === "TooManyRequestsException" || error?._tag === "InternalServerException",
413 schedule: Schedule.max([Schedule.exponential(200), Schedule.recurs(8)]),
414 }),
415 );