The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as controltower from "@distilled.cloud/aws/controltower"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import * as Provider from "alchemy/Provider"; |
| 4 | import { Resource } from "alchemy/Resource"; |
| 5 | import { createInternalTags, hasAlchemyTags } from "alchemy/Tags"; |
| 6 | import * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import { canonicalJson, observeControlTowerTags, syncControlTowerTags } from "./internal.ts"; |
| 12 | |
| 13 | export interface LandingZoneProps { |
| 14 | /** |
| 15 | * The landing zone version, e.g. `"3.3"`. Updating the version upgrades |
| 16 | * the landing zone in place (an asynchronous operation that can take an |
| 17 | * hour or more). |
| 18 | */ |
| 19 | version: string; |
| 20 | /** |
| 21 | * The landing zone manifest JSON document — the full configuration of |
| 22 | * the landing zone (governed regions, organization structure, logging |
| 23 | * and access-management settings). See the AWS Control Tower User Guide |
| 24 | * for the manifest schema. |
| 25 | */ |
| 26 | manifest: Record<string, unknown>; |
| 27 | /** |
| 28 | * Remediation types enabled for the landing zone, e.g. |
| 29 | * `["INHERITANCE_DRIFT"]`. |
| 30 | */ |
| 31 | remediationTypes?: string[]; |
| 32 | /** |
| 33 | * Tags to apply to the landing zone. Merged with internal Alchemy tags. |
| 34 | */ |
| 35 | tags?: Record<string, string>; |
| 36 | } |
| 37 | |
| 38 | export interface LandingZone extends Resource< |
| 39 | "AWS.ControlTower.LandingZone", |
| 40 | LandingZoneProps, |
| 41 | { |
| 42 | /** |
| 43 | * The unique identifier of the landing zone (its ARN). |
| 44 | */ |
| 45 | landingZoneIdentifier: string; |
| 46 | /** |
| 47 | * The ARN of the landing zone. |
| 48 | */ |
| 49 | landingZoneArn: string; |
| 50 | /** |
| 51 | * The deployed landing zone version. |
| 52 | */ |
| 53 | version: string; |
| 54 | /** |
| 55 | * The landing zone deployment status (`ACTIVE`, `PROCESSING`, |
| 56 | * `FAILED`). |
| 57 | */ |
| 58 | status: string | undefined; |
| 59 | /** |
| 60 | * The most recent landing zone version available for upgrade. |
| 61 | */ |
| 62 | latestAvailableVersion: string | undefined; |
| 63 | /** |
| 64 | * The landing zone drift status (`IN_SYNC` or `DRIFTED`). |
| 65 | */ |
| 66 | driftStatus: string | undefined; |
| 67 | }, |
| 68 | never, |
| 69 | Providers |
| 70 | > {} |
| 71 | |
| 72 | /** |
| 73 | * An AWS Control Tower landing zone — the org-wide multi-account |
| 74 | * environment (organization structure, governed regions, centralized |
| 75 | * logging, and access management) that Control Tower governs. |
| 76 | * |
| 77 | * A landing zone is a singleton per AWS Organization and can only be |
| 78 | * managed from the Organizations management account. Creating, updating, |
| 79 | * and decommissioning a landing zone are asynchronous operations that can |
| 80 | * take an hour or more. |
| 81 | * ### Creating a Landing Zone |
| 82 | * **Example:** Landing Zone from a manifest |
| 83 | * ```typescript |
| 84 | * import * as ControlTower from "@alchemy.run/aws/ControlTower"; |
| 85 | * |
| 86 | * const landingZone = yield* ControlTower.LandingZone("LandingZone", { |
| 87 | * version: "3.3", |
| 88 | * manifest: { |
| 89 | * governedRegions: ["us-east-1", "us-west-2"], |
| 90 | * organizationStructure: { |
| 91 | * security: { name: "Security" }, |
| 92 | * sandbox: { name: "Sandbox" }, |
| 93 | * }, |
| 94 | * centralizedLogging: { |
| 95 | * accountId: "111122223333", |
| 96 | * configurations: { |
| 97 | * loggingBucket: { retentionDays: 365 }, |
| 98 | * accessLoggingBucket: { retentionDays: 365 }, |
| 99 | * }, |
| 100 | * enabled: true, |
| 101 | * }, |
| 102 | * securityRoles: { accountId: "444455556666" }, |
| 103 | * accessManagement: { enabled: true }, |
| 104 | * }, |
| 105 | * }); |
| 106 | * ``` |
| 107 | * |
| 108 | * ### Upgrading |
| 109 | * **Example:** Upgrade the landing zone version |
| 110 | * ```typescript |
| 111 | * const landingZone = yield* ControlTower.LandingZone("LandingZone", { |
| 112 | * version: "3.3", // bump to upgrade in place |
| 113 | * manifest, |
| 114 | * }); |
| 115 | * ``` |
| 116 | * |
| 117 | * @resource |
| 118 | */ |
| 119 | export const LandingZone = Resource<LandingZone>("AWS.ControlTower.LandingZone"); |
| 120 | |
| 121 | /** |
| 122 | * An asynchronous landing zone operation (CREATE / UPDATE / DELETE / |
| 123 | * RESET) converged to the terminal `FAILED` status. |
| 124 | */ |
| 125 | export class LandingZoneOperationFailed extends Data.TaggedError("LandingZoneOperationFailed")<{ |
| 126 | readonly operationIdentifier: string; |
| 127 | readonly status: string; |
| 128 | readonly statusMessage: string | undefined; |
| 129 | }> {} |
| 130 | |
| 131 | /** |
| 132 | * Internal signal that a landing zone operation is still `IN_PROGRESS`, |
| 133 | * consumed by {@link waitForLandingZoneOperation}'s bounded schedule. |
| 134 | */ |
| 135 | class LandingZoneOperationPending extends Data.TaggedError("LandingZoneOperationPending")<{ |
| 136 | readonly operationIdentifier: string; |
| 137 | readonly status: string | undefined; |
| 138 | }> {} |
| 139 | |
| 140 | // Explicitly-typed retry wrapper — an inline `Effect.retry` in provider |
| 141 | // lifecycle code leaks `Retry.Return`'s conditional type into declaration |
| 142 | // emit and widens the provider layer to `unknown` for every consumer of |
| 143 | // `AWS.providers()`. |
| 144 | const retryWhileLandingZoneOperationPending = <A, E extends { readonly _tag: string }, R>( |
| 145 | self: Effect.Effect<A, E, R>, |
| 146 | ): Effect.Effect<A, E, R> => |
| 147 | Effect.retry(self, { |
| 148 | while: (e) => e._tag === "LandingZoneOperationPending", |
| 149 | // Landing zone operations routinely take ~60 minutes; poll every 30s |
| 150 | // up to 90 minutes (bounded). |
| 151 | schedule: Schedule.max([Schedule.spaced("30 seconds"), Schedule.recurs(180)]), |
| 152 | }); |
| 153 | |
| 154 | const waitForLandingZoneOperation = (operationIdentifier: string) => |
| 155 | retryWhileLandingZoneOperationPending( |
| 156 | Effect.gen(function* () { |
| 157 | const { operationDetails } = yield* controltower.getLandingZoneOperation({ |
| 158 | operationIdentifier, |
| 159 | }); |
| 160 | if (operationDetails.status === "SUCCEEDED") { |
| 161 | return; |
| 162 | } |
| 163 | if (operationDetails.status === "FAILED") { |
| 164 | return yield* new LandingZoneOperationFailed({ |
| 165 | operationIdentifier, |
| 166 | status: operationDetails.status, |
| 167 | statusMessage: operationDetails.statusMessage, |
| 168 | }); |
| 169 | } |
| 170 | return yield* new LandingZoneOperationPending({ |
| 171 | operationIdentifier, |
| 172 | status: operationDetails.status, |
| 173 | }); |
| 174 | }), |
| 175 | ); |
| 176 | |
| 177 | // A landing zone is a singleton per organization — `listLandingZones` |
| 178 | // returns at most one ARN. |
| 179 | const findLandingZoneArn = controltower.listLandingZones.pages({}).pipe( |
| 180 | Stream.runCollect, |
| 181 | Effect.map((chunk) => |
| 182 | Array.from(chunk) |
| 183 | .flatMap((page) => page.landingZones) |
| 184 | .map((zone) => zone.arn) |
| 185 | .find((arn): arn is string => arn !== undefined), |
| 186 | ), |
| 187 | ); |
| 188 | |
| 189 | const readLandingZone = (landingZoneIdentifier: string) => |
| 190 | controltower.getLandingZone({ landingZoneIdentifier }).pipe( |
| 191 | Effect.map((r) => r.landingZone), |
| 192 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 193 | ); |
| 194 | |
| 195 | const toAttributes = ( |
| 196 | arn: string, |
| 197 | detail: controltower.LandingZoneDetail, |
| 198 | ): LandingZone["Attributes"] => ({ |
| 199 | landingZoneIdentifier: arn, |
| 200 | landingZoneArn: arn, |
| 201 | version: detail.version, |
| 202 | status: detail.status, |
| 203 | latestAvailableVersion: detail.latestAvailableVersion, |
| 204 | driftStatus: detail.driftStatus?.status, |
| 205 | }); |
| 206 | |
| 207 | export const LandingZoneProvider = () => |
| 208 | Provider.effect( |
| 209 | LandingZone, |
| 210 | Effect.gen(function* () { |
| 211 | return LandingZone.Provider.of({ |
| 212 | stables: ["landingZoneIdentifier", "landingZoneArn"], |
| 213 | // Decommissioning a landing zone dismantles org-wide governance |
| 214 | // (an irreversible, ~1 hour operation) — never do it from `nuke`. |
| 215 | nuke: { skip: true }, |
| 216 | list: () => |
| 217 | Effect.gen(function* () { |
| 218 | const arn = yield* findLandingZoneArn; |
| 219 | if (arn === undefined) return []; |
| 220 | const detail = yield* readLandingZone(arn); |
| 221 | if (detail === undefined) return []; |
| 222 | return [toAttributes(arn, detail)]; |
| 223 | }), |
| 224 | read: Effect.fn(function* ({ id, output }) { |
| 225 | const arn = output?.landingZoneArn ?? (yield* findLandingZoneArn); |
| 226 | if (arn === undefined) return undefined; |
| 227 | const detail = yield* readLandingZone(arn); |
| 228 | if (detail === undefined) return undefined; |
| 229 | const attrs = toAttributes(arn, detail); |
| 230 | const tags = yield* observeControlTowerTags(arn); |
| 231 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 232 | }), |
| 233 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 234 | // 1. Observe — the landing zone is an org singleton; enumerate |
| 235 | // rather than trusting a cached identifier. |
| 236 | let arn = output?.landingZoneArn ?? (yield* findLandingZoneArn); |
| 237 | let detail = arn === undefined ? undefined : yield* readLandingZone(arn); |
| 238 | |
| 239 | // 2. Ensure — create if missing and wait for the asynchronous |
| 240 | // operation to converge. |
| 241 | if (detail === undefined) { |
| 242 | const internalTags = yield* createInternalTags(id); |
| 243 | const created = yield* controltower.createLandingZone({ |
| 244 | version: news.version, |
| 245 | manifest: news.manifest, |
| 246 | remediationTypes: news.remediationTypes, |
| 247 | tags: { ...news.tags, ...internalTags }, |
| 248 | }); |
| 249 | arn = created.arn; |
| 250 | yield* session.note(`landing zone operation ${created.operationIdentifier}`); |
| 251 | yield* waitForLandingZoneOperation(created.operationIdentifier); |
| 252 | detail = yield* readLandingZone(arn); |
| 253 | } else { |
| 254 | // 3. Sync — version / manifest / remediation types are updated |
| 255 | // in place; diff observed cloud state against desired and |
| 256 | // skip the (very slow) update API on a no-op. |
| 257 | const versionChanged = detail.version !== news.version; |
| 258 | const manifestChanged = |
| 259 | canonicalJson(detail.manifest ?? {}) !== canonicalJson(news.manifest); |
| 260 | const remediationChanged = |
| 261 | news.remediationTypes !== undefined && |
| 262 | canonicalJson([...(detail.remediationTypes ?? [])].sort()) !== |
| 263 | canonicalJson([...news.remediationTypes].sort()); |
| 264 | if (versionChanged || manifestChanged || remediationChanged) { |
| 265 | const updated = yield* controltower.updateLandingZone({ |
| 266 | landingZoneIdentifier: arn!, |
| 267 | version: news.version, |
| 268 | manifest: news.manifest, |
| 269 | remediationTypes: news.remediationTypes, |
| 270 | }); |
| 271 | yield* session.note(`landing zone operation ${updated.operationIdentifier}`); |
| 272 | yield* waitForLandingZoneOperation(updated.operationIdentifier); |
| 273 | detail = yield* readLandingZone(arn!); |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | // 3b. Sync tags against observed cloud tags. |
| 278 | yield* syncControlTowerTags(arn!, id, news.tags); |
| 279 | |
| 280 | // 4. Return fresh attributes. |
| 281 | return detail === undefined |
| 282 | ? { |
| 283 | landingZoneIdentifier: arn!, |
| 284 | landingZoneArn: arn!, |
| 285 | version: news.version, |
| 286 | status: undefined, |
| 287 | latestAvailableVersion: undefined, |
| 288 | driftStatus: undefined, |
| 289 | } |
| 290 | : toAttributes(arn!, detail); |
| 291 | }), |
| 292 | delete: Effect.fn(function* ({ output, session }) { |
| 293 | const result = yield* controltower |
| 294 | .deleteLandingZone({ |
| 295 | landingZoneIdentifier: output.landingZoneArn, |
| 296 | }) |
| 297 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 298 | if (result !== undefined) { |
| 299 | yield* session.note(`landing zone operation ${result.operationIdentifier}`); |
| 300 | yield* waitForLandingZoneOperation(result.operationIdentifier); |
| 301 | } |
| 302 | }), |
| 303 | }); |
| 304 | }), |
| 305 | ); |