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
| 1 | import * as organizations from "@distilled.cloud/aws/organizations"; |
| 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 { hasAlchemyTags } from "alchemy/Tags"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import type { Providers } from "../Providers.ts"; |
| 10 | import { |
| 11 | collectPages, |
| 12 | createName, |
| 13 | readResourceTags, |
| 14 | retryOrganizations, |
| 15 | updateResourceTags, |
| 16 | } from "./common.ts"; |
| 17 | |
| 18 | export class OrganizationalUnitUnexpectedResponse extends Data.TaggedError( |
| 19 | "OrganizationalUnitUnexpectedResponse", |
| 20 | )<{ |
| 21 | readonly message: string; |
| 22 | readonly cause?: unknown; |
| 23 | }> {} |
| 24 | |
| 25 | export type OrganizationalUnitId = string; |
| 26 | export type OrganizationalUnitArn = string; |
| 27 | |
| 28 | export interface OrganizationalUnitProps { |
| 29 | /** |
| 30 | * Parent root or OU ID. |
| 31 | */ |
| 32 | parentId: string; |
| 33 | /** |
| 34 | * OU name. If omitted, Alchemy generates one. |
| 35 | */ |
| 36 | name?: string; |
| 37 | /** |
| 38 | * Optional tags applied to the OU. |
| 39 | */ |
| 40 | tags?: Record<string, string>; |
| 41 | } |
| 42 | |
| 43 | export interface OrganizationalUnit extends Resource< |
| 44 | "AWS.Organizations.OrganizationalUnit", |
| 45 | OrganizationalUnitProps, |
| 46 | { |
| 47 | /** |
| 48 | * ID of the OU (e.g. `ou-examplerootid-exampleouid`). |
| 49 | */ |
| 50 | ouId: OrganizationalUnitId; |
| 51 | /** |
| 52 | * ARN of the OU. |
| 53 | */ |
| 54 | ouArn: OrganizationalUnitArn; |
| 55 | /** |
| 56 | * Name of the OU. |
| 57 | */ |
| 58 | name: string; |
| 59 | /** |
| 60 | * ID of the parent root or OU. |
| 61 | */ |
| 62 | parentId: string | undefined; |
| 63 | /** |
| 64 | * Tags on the OU. |
| 65 | */ |
| 66 | tags: Record<string, string>; |
| 67 | }, |
| 68 | never, |
| 69 | Providers |
| 70 | > {} |
| 71 | |
| 72 | /** |
| 73 | * An AWS Organizations organizational unit. |
| 74 | * ### Creating OUs |
| 75 | * **Example:** Nested OU |
| 76 | * ```typescript |
| 77 | * const workloads = yield* OrganizationalUnit("Workloads", { |
| 78 | * parentId: root.rootId, |
| 79 | * name: "workloads", |
| 80 | * }); |
| 81 | * ``` |
| 82 | * |
| 83 | * @resource |
| 84 | */ |
| 85 | export const OrganizationalUnit = Resource<OrganizationalUnit>( |
| 86 | "AWS.Organizations.OrganizationalUnit", |
| 87 | ); |
| 88 | |
| 89 | export const OrganizationalUnitProvider = () => |
| 90 | Provider.effect( |
| 91 | OrganizationalUnit, |
| 92 | Effect.gen(function* () { |
| 93 | return { |
| 94 | stables: ["ouId", "ouArn"], |
| 95 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 96 | if (!isResolved(news)) return; |
| 97 | const oldName = yield* toName(id, olds ?? {}); |
| 98 | const newName = yield* toName(id, news ?? {}); |
| 99 | |
| 100 | if (olds?.parentId !== news?.parentId) { |
| 101 | return { action: "replace" } as const; |
| 102 | } |
| 103 | |
| 104 | if (oldName !== newName) { |
| 105 | return { action: "update" } as const; |
| 106 | } |
| 107 | }), |
| 108 | // OUs form a tree: enumerate roots, then recursively fan out over |
| 109 | // `listOrganizationalUnitsForParent` (bounded concurrency) to discover |
| 110 | // every OU. Each discovered OU is hydrated through `readOUById` so the |
| 111 | // element shape exactly matches `read`. When the account isn't an |
| 112 | // organization management account, the typed |
| 113 | // `AWSOrganizationsNotInUseException` / `AccessDeniedException` degrade |
| 114 | // to `[]` rather than throwing. |
| 115 | list: () => |
| 116 | Effect.gen(function* () { |
| 117 | const roots = yield* listAllRoots(); |
| 118 | const rootIds = roots |
| 119 | .map((root) => root.Id) |
| 120 | .filter((rootId): rootId is string => rootId !== undefined); |
| 121 | const ouIds = yield* collectDescendantOUIds(rootIds); |
| 122 | const hydrated = yield* Effect.forEach(ouIds, (ouId) => readOUById(ouId), { |
| 123 | concurrency: 10, |
| 124 | }); |
| 125 | const result: OrganizationalUnit["Attributes"][] = hydrated.filter( |
| 126 | (ou): ou is NonNullable<typeof ou> => ou !== undefined, |
| 127 | ); |
| 128 | return result; |
| 129 | }).pipe( |
| 130 | Effect.catchTags({ |
| 131 | AWSOrganizationsNotInUseException: () => |
| 132 | Effect.succeed([] as OrganizationalUnit["Attributes"][]), |
| 133 | AccessDeniedException: () => Effect.succeed([] as OrganizationalUnit["Attributes"][]), |
| 134 | }), |
| 135 | ), |
| 136 | read: Effect.fn(function* ({ id, olds, output }) { |
| 137 | const state = output?.ouId |
| 138 | ? yield* readOUById(output.ouId) |
| 139 | : olds?.parentId |
| 140 | ? yield* readOUByParentAndName({ |
| 141 | parentId: olds.parentId, |
| 142 | name: yield* toName(id, olds ?? {}), |
| 143 | }) |
| 144 | : undefined; |
| 145 | if (!state) return undefined; |
| 146 | return (yield* hasAlchemyTags(id, state.tags)) ? state : Unowned(state); |
| 147 | }), |
| 148 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 149 | const name = yield* toName(id, news); |
| 150 | |
| 151 | // Observe — locate the OU by ID if known, else by parent+name. |
| 152 | // We fetch fresh so the reconciler converges over drift, adoption, |
| 153 | // and partial prior runs. `output.ouId` is treated only as a |
| 154 | // cache. |
| 155 | let state = output?.ouId |
| 156 | ? yield* readOUById(output.ouId) |
| 157 | : yield* readOUByParentAndName({ |
| 158 | parentId: news.parentId, |
| 159 | name, |
| 160 | }); |
| 161 | |
| 162 | // Ensure — create the OU if missing. Tolerate |
| 163 | // `DuplicateOrganizationalUnitException` as adoption when a peer |
| 164 | // reconciler created it concurrently. |
| 165 | if (!state) { |
| 166 | yield* retryOrganizations( |
| 167 | organizations |
| 168 | .createOrganizationalUnit({ |
| 169 | ParentId: news.parentId, |
| 170 | Name: name, |
| 171 | }) |
| 172 | .pipe(Effect.catchTag("DuplicateOrganizationalUnitException", () => Effect.void)), |
| 173 | ); |
| 174 | state = yield* readOUByParentAndName({ |
| 175 | parentId: news.parentId, |
| 176 | name, |
| 177 | }); |
| 178 | if (!state) { |
| 179 | return yield* new OrganizationalUnitUnexpectedResponse({ |
| 180 | message: `organizational unit '${name}' not found after create`, |
| 181 | }); |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | // Sync name — observed ↔ desired. `parentId` is replacement-only, |
| 186 | // so the diff has handled any cross-parent move. |
| 187 | if (state.name !== name) { |
| 188 | yield* retryOrganizations( |
| 189 | organizations.updateOrganizationalUnit({ |
| 190 | OrganizationalUnitId: state.ouId, |
| 191 | Name: name, |
| 192 | }), |
| 193 | ); |
| 194 | } |
| 195 | |
| 196 | // Sync tags — diff observed cloud tags against desired so |
| 197 | // adoption and drift converge correctly without trusting `olds`. |
| 198 | const tags = yield* updateResourceTags({ |
| 199 | id, |
| 200 | resourceId: state.ouId, |
| 201 | olds: state.tags, |
| 202 | news: news.tags, |
| 203 | }); |
| 204 | |
| 205 | const updated = yield* readOUById(state.ouId); |
| 206 | if (!updated) { |
| 207 | return yield* new OrganizationalUnitUnexpectedResponse({ |
| 208 | message: `organizational unit '${state.ouId}' not found after reconcile`, |
| 209 | }); |
| 210 | } |
| 211 | |
| 212 | yield* session.note(updated.ouArn); |
| 213 | return { |
| 214 | ...updated, |
| 215 | tags, |
| 216 | }; |
| 217 | }), |
| 218 | delete: Effect.fn(function* ({ output }) { |
| 219 | yield* retryOrganizations( |
| 220 | organizations |
| 221 | .deleteOrganizationalUnit({ |
| 222 | OrganizationalUnitId: output.ouId, |
| 223 | }) |
| 224 | .pipe(Effect.catchTag("OrganizationalUnitNotFoundException", () => Effect.void)), |
| 225 | ); |
| 226 | }), |
| 227 | }; |
| 228 | }), |
| 229 | ); |
| 230 | |
| 231 | const toName = (id: string, props: { name?: string } = {}) => createName(id, props.name, 128); |
| 232 | |
| 233 | const listOUsForParent = (parentId: string) => |
| 234 | collectPages( |
| 235 | (NextToken) => |
| 236 | organizations.listOrganizationalUnitsForParent({ |
| 237 | ParentId: parentId, |
| 238 | NextToken, |
| 239 | }), |
| 240 | (page) => page.OrganizationalUnits, |
| 241 | ).pipe(retryOrganizations); |
| 242 | |
| 243 | const listAllRoots = () => |
| 244 | collectPages( |
| 245 | (NextToken) => organizations.listRoots({ NextToken }), |
| 246 | (page) => page.Roots, |
| 247 | ).pipe(retryOrganizations); |
| 248 | |
| 249 | // Walk the OU tree breadth-first. Each level fans out across its parents with |
| 250 | // bounded concurrency so a wide/deep org doesn't issue an unbounded burst. |
| 251 | const collectDescendantOUIds = ( |
| 252 | parentIds: readonly string[], |
| 253 | ): Effect.Effect< |
| 254 | string[], |
| 255 | Effect.Error<ReturnType<typeof listOUsForParent>>, |
| 256 | Effect.Services<ReturnType<typeof listOUsForParent>> |
| 257 | > => |
| 258 | Effect.gen(function* () { |
| 259 | if (parentIds.length === 0) return []; |
| 260 | const childLists = yield* Effect.forEach( |
| 261 | parentIds, |
| 262 | (parentId) => |
| 263 | listOUsForParent(parentId).pipe( |
| 264 | // The OU was deleted after its parent was listed — skip its subtree. |
| 265 | Effect.catchTag("ParentNotFoundException", () => |
| 266 | Effect.succeed<organizations.OrganizationalUnit[]>([]), |
| 267 | ), |
| 268 | ), |
| 269 | { concurrency: 10 }, |
| 270 | ); |
| 271 | const childIds = childLists |
| 272 | .flat() |
| 273 | .map((ou) => ou.Id) |
| 274 | .filter((ouId): ouId is string => ouId !== undefined); |
| 275 | const descendants = yield* collectDescendantOUIds(childIds); |
| 276 | return [...childIds, ...descendants]; |
| 277 | }); |
| 278 | |
| 279 | const readParentId = (childId: string) => |
| 280 | collectPages( |
| 281 | (NextToken) => organizations.listParents({ ChildId: childId, NextToken }), |
| 282 | (page) => page.Parents, |
| 283 | ).pipe( |
| 284 | retryOrganizations, |
| 285 | Effect.map((parents) => parents[0]?.Id), |
| 286 | ); |
| 287 | |
| 288 | const readOUById = Effect.fn(function* (ouId: string) { |
| 289 | const described = yield* retryOrganizations( |
| 290 | organizations |
| 291 | .describeOrganizationalUnit({ |
| 292 | OrganizationalUnitId: ouId, |
| 293 | }) |
| 294 | .pipe( |
| 295 | Effect.map((response) => response.OrganizationalUnit), |
| 296 | Effect.catchTag("OrganizationalUnitNotFoundException", () => Effect.undefined), |
| 297 | ), |
| 298 | ); |
| 299 | |
| 300 | if (!described?.Id || !described.Arn || !described.Name) { |
| 301 | return undefined; |
| 302 | } |
| 303 | |
| 304 | const [parentId, tags] = yield* Effect.all([ |
| 305 | readParentId(described.Id).pipe( |
| 306 | Effect.catchTag("ChildNotFoundException", () => Effect.undefined), |
| 307 | ), |
| 308 | readResourceTags(described.Id).pipe( |
| 309 | Effect.catchTag("TargetNotFoundException", () => Effect.succeed({})), |
| 310 | ), |
| 311 | ]); |
| 312 | |
| 313 | return { |
| 314 | ouId: described.Id, |
| 315 | ouArn: described.Arn, |
| 316 | name: described.Name, |
| 317 | parentId, |
| 318 | tags, |
| 319 | } satisfies OrganizationalUnit["Attributes"]; |
| 320 | }); |
| 321 | |
| 322 | const readOUByParentAndName = Effect.fn(function* ({ |
| 323 | parentId, |
| 324 | name, |
| 325 | }: { |
| 326 | parentId: string; |
| 327 | name: string; |
| 328 | }) { |
| 329 | const match = (yield* listOUsForParent(parentId)).find((ou) => ou.Name === name); |
| 330 | return match?.Id ? yield* readOUById(match.Id) : undefined; |
| 331 | }); |