The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as ds from "@distilled.cloud/aws/directory-service"; |
| 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 { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Redacted from "effect/Redacted"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import { AWSEnvironment } from "../Environment.ts"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | import { readDirectoryTags, sameStringSet } from "./internal.ts"; |
| 15 | |
| 16 | export class DirectoryUnexpectedResponse extends Data.TaggedError("DirectoryUnexpectedResponse")<{ |
| 17 | readonly message: string; |
| 18 | readonly cause?: unknown; |
| 19 | }> {} |
| 20 | |
| 21 | /** The kind of managed directory to launch. */ |
| 22 | export type DirectoryFlavor = "SimpleAD" | "MicrosoftAD"; |
| 23 | |
| 24 | export interface DirectoryProps { |
| 25 | /** |
| 26 | * Which managed directory to launch — a Samba-based `"SimpleAD"` or an |
| 27 | * actual `"MicrosoftAD"` (AWS Managed Microsoft AD). Changing the flavor |
| 28 | * replaces the directory. |
| 29 | * @default "SimpleAD" |
| 30 | */ |
| 31 | type?: DirectoryFlavor; |
| 32 | /** |
| 33 | * Fully qualified domain name of the directory, e.g. `corp.example.com`. |
| 34 | * The domain does not need to be publicly resolvable. Changing the name |
| 35 | * replaces the directory. |
| 36 | */ |
| 37 | name: string; |
| 38 | /** |
| 39 | * NetBIOS short name of the directory, e.g. `CORP`. Changing the short |
| 40 | * name replaces the directory. |
| 41 | * @default the first label of `name` |
| 42 | */ |
| 43 | shortName?: string; |
| 44 | /** |
| 45 | * Password for the directory administrator account (`Administrator` for |
| 46 | * Simple AD, `Admin` for Microsoft AD). There is no API to change it after |
| 47 | * creation, so changing the password replaces the directory. |
| 48 | */ |
| 49 | password: Redacted.Redacted<string>; |
| 50 | /** |
| 51 | * Human-readable description of the directory. There is no update API, so |
| 52 | * changing the description replaces the directory. |
| 53 | */ |
| 54 | description?: string; |
| 55 | /** |
| 56 | * Size of a Simple AD directory — `"Small"` (up to ~500 users) or |
| 57 | * `"Large"` (up to ~5000 users). Ignored for Microsoft AD. Changing the |
| 58 | * size replaces the directory. |
| 59 | * @default "Small" |
| 60 | */ |
| 61 | size?: ds.DirectorySize; |
| 62 | /** |
| 63 | * Edition of a Microsoft AD directory — `"Standard"` or `"Enterprise"`. |
| 64 | * Ignored for Simple AD. Changing the edition replaces the directory. |
| 65 | * @default "Standard" |
| 66 | */ |
| 67 | edition?: ds.DirectoryEdition; |
| 68 | /** |
| 69 | * VPC the directory's domain controllers are placed into. Changing the |
| 70 | * VPC replaces the directory. |
| 71 | */ |
| 72 | vpcId: string; |
| 73 | /** |
| 74 | * Exactly two subnets in DIFFERENT Availability Zones of `vpcId` — one |
| 75 | * domain controller is launched into each. Changing the subnets replaces |
| 76 | * the directory. |
| 77 | */ |
| 78 | subnetIds: string[]; |
| 79 | /** |
| 80 | * User-defined tags for the directory. |
| 81 | */ |
| 82 | tags?: Record<string, string>; |
| 83 | } |
| 84 | |
| 85 | export interface Directory extends Resource< |
| 86 | "AWS.DirectoryService.Directory", |
| 87 | DirectoryProps, |
| 88 | { |
| 89 | /** The ID of the directory, e.g. `d-1234567890`. */ |
| 90 | directoryId: string; |
| 91 | /** The ARN of the directory, e.g. `arn:aws:ds:us-east-1:123456789012:directory/d-1234567890`. */ |
| 92 | directoryArn: string; |
| 93 | /** The fully qualified name of the directory. */ |
| 94 | directoryName: string; |
| 95 | /** The directory type, e.g. `SimpleAD` or `MicrosoftAD`. */ |
| 96 | type: string; |
| 97 | /** The current lifecycle stage of the directory, e.g. `Active`. */ |
| 98 | stage: string; |
| 99 | /** The size of a Simple AD directory (`Small` or `Large`). */ |
| 100 | size: string | undefined; |
| 101 | /** The edition of a Microsoft AD directory (`Standard` or `Enterprise`). */ |
| 102 | edition: string | undefined; |
| 103 | /** The directory alias used for the access URL. */ |
| 104 | alias: string | undefined; |
| 105 | /** The access URL of the directory, e.g. `<alias>.awsapps.com`. */ |
| 106 | accessUrl: string | undefined; |
| 107 | /** The IP addresses of the directory's DNS servers. */ |
| 108 | dnsIpAddrs: string[]; |
| 109 | /** The security group created for the directory's controllers. */ |
| 110 | securityGroupId: string | undefined; |
| 111 | /** The VPC the directory is deployed into. */ |
| 112 | vpcId: string | undefined; |
| 113 | /** The subnets hosting the directory's domain controllers. */ |
| 114 | subnetIds: string[]; |
| 115 | /** The Availability Zones the directory spans. */ |
| 116 | availabilityZones: string[]; |
| 117 | /** The tags attached to the directory. */ |
| 118 | tags: Record<string, string>; |
| 119 | }, |
| 120 | never, |
| 121 | Providers |
| 122 | > {} |
| 123 | |
| 124 | /** |
| 125 | * An AWS Directory Service managed directory — either Simple AD (Samba) or |
| 126 | * AWS Managed Microsoft AD. |
| 127 | * |
| 128 | * Directories are VPC-only and require two subnets in different Availability |
| 129 | * Zones. Provisioning is SLOW: Simple AD takes roughly 10 minutes and |
| 130 | * Microsoft AD 20-40 minutes, and directories bill hourly while they exist. |
| 131 | * Destroy directories you are not using. |
| 132 | * ### Creating a Directory |
| 133 | * **Example:** Simple AD Directory |
| 134 | * ```typescript |
| 135 | * const directory = yield* Directory("Corp", { |
| 136 | * name: "corp.example.com", |
| 137 | * password: Redacted.make("SuperSecret123!"), |
| 138 | * size: "Small", |
| 139 | * vpcId: vpc.vpcId, |
| 140 | * subnetIds: [subnetA.subnetId, subnetB.subnetId], |
| 141 | * }); |
| 142 | * ``` |
| 143 | * |
| 144 | * **Example:** Managed Microsoft AD Directory |
| 145 | * ```typescript |
| 146 | * const directory = yield* Directory("Corp", { |
| 147 | * type: "MicrosoftAD", |
| 148 | * name: "corp.example.com", |
| 149 | * shortName: "CORP", |
| 150 | * password: Redacted.make("SuperSecret123!"), |
| 151 | * edition: "Standard", |
| 152 | * vpcId: vpc.vpcId, |
| 153 | * subnetIds: [subnetA.subnetId, subnetB.subnetId], |
| 154 | * }); |
| 155 | * ``` |
| 156 | * |
| 157 | * ### Using the Directory |
| 158 | * **Example:** Read the DNS Addresses |
| 159 | * ```typescript |
| 160 | * const directory = yield* Directory("Corp", { ... }); |
| 161 | * // the directory-provided DNS servers, one per Availability Zone |
| 162 | * const dns = directory.dnsIpAddrs; |
| 163 | * ``` |
| 164 | * |
| 165 | * @resource |
| 166 | */ |
| 167 | export const Directory = Resource<Directory>("AWS.DirectoryService.Directory"); |
| 168 | |
| 169 | const DEFAULT_SIZE: ds.DirectorySize = "Small"; |
| 170 | const DEFAULT_EDITION: ds.DirectoryEdition = "Standard"; |
| 171 | |
| 172 | /** Stages from which a directory can never come back. */ |
| 173 | const isTerminalStage = (stage: string | undefined): boolean => |
| 174 | stage === "Deleting" || stage === "Deleted" || stage === "Failed"; |
| 175 | |
| 176 | class DirectoryNotReady extends Data.TaggedError("DirectoryNotReady")<{ |
| 177 | readonly directoryId: string; |
| 178 | readonly stage: string | undefined; |
| 179 | }> {} |
| 180 | |
| 181 | class DirectoryProvisioningFailed extends Data.TaggedError("DirectoryProvisioningFailed")<{ |
| 182 | readonly directoryId: string; |
| 183 | readonly stage: string | undefined; |
| 184 | readonly reason: string | undefined; |
| 185 | }> {} |
| 186 | |
| 187 | // Directory provisioning is slow (Simple AD ~10 min, Microsoft AD 20-40 |
| 188 | // min); poll every 30s with a ~50 min budget. Only DirectoryNotReady is |
| 189 | // retried — a Failed/Deleted stage aborts immediately. |
| 190 | const retryWhileNotReady = <A, E extends { readonly _tag: string }, R>( |
| 191 | self: Effect.Effect<A, E, R>, |
| 192 | ): Effect.Effect<A, E, R> => |
| 193 | Effect.retry(self, { |
| 194 | while: (e) => e._tag === "DirectoryNotReady", |
| 195 | schedule: Schedule.max([Schedule.fixed("30 seconds"), Schedule.recurs(100)]), |
| 196 | }); |
| 197 | |
| 198 | export const DirectoryProvider = () => |
| 199 | Provider.effect( |
| 200 | Directory, |
| 201 | Effect.gen(function* () { |
| 202 | const getById = Effect.fn(function* (directoryId: string) { |
| 203 | const response = yield* ds |
| 204 | .describeDirectories({ DirectoryIds: [directoryId] }) |
| 205 | .pipe(Effect.catchTag("EntityDoesNotExistException", () => Effect.undefined)); |
| 206 | return response?.DirectoryDescriptions?.[0]; |
| 207 | }); |
| 208 | |
| 209 | // Best-effort fallback for lost state: scan the account's directories |
| 210 | // for a live one with the desired domain name. |
| 211 | const findByName = Effect.fn(function* (name: string | undefined) { |
| 212 | if (name === undefined) return undefined; |
| 213 | const matches = yield* ds.describeDirectories.items({}).pipe( |
| 214 | Stream.filter((d) => d.Name === name && !isTerminalStage(d.Stage)), |
| 215 | Stream.take(1), |
| 216 | Stream.runCollect, |
| 217 | ); |
| 218 | return Array.from(matches)[0]; |
| 219 | }); |
| 220 | |
| 221 | const observe = Effect.fn(function* ( |
| 222 | directoryId: string | undefined, |
| 223 | name: string | undefined, |
| 224 | ) { |
| 225 | const found = directoryId ? yield* getById(directoryId) : yield* findByName(name); |
| 226 | return found !== undefined && !isTerminalStage(found.Stage) ? found : undefined; |
| 227 | }); |
| 228 | |
| 229 | const waitForActive = (directoryId: string) => |
| 230 | Effect.gen(function* () { |
| 231 | const directory = yield* getById(directoryId); |
| 232 | if (directory === undefined || isTerminalStage(directory.Stage)) { |
| 233 | return yield* new DirectoryProvisioningFailed({ |
| 234 | directoryId, |
| 235 | stage: directory?.Stage, |
| 236 | reason: directory?.StageReason, |
| 237 | }); |
| 238 | } |
| 239 | if (directory.Stage !== "Active") { |
| 240 | return yield* new DirectoryNotReady({ |
| 241 | directoryId, |
| 242 | stage: directory.Stage, |
| 243 | }); |
| 244 | } |
| 245 | return directory; |
| 246 | }).pipe(retryWhileNotReady); |
| 247 | |
| 248 | // Wait for a directory to leave a transitional stage before deleting. |
| 249 | // Ends when the directory is in a steady stage, already deleting, or |
| 250 | // gone. |
| 251 | const waitUntilSettled = Effect.fn(function* (directoryId: string) { |
| 252 | return yield* getById(directoryId).pipe( |
| 253 | Effect.flatMap((directory) => { |
| 254 | if ( |
| 255 | directory !== undefined && |
| 256 | (directory.Stage === "Requested" || |
| 257 | directory.Stage === "Creating" || |
| 258 | directory.Stage === "Created" || |
| 259 | directory.Stage === "Restoring" || |
| 260 | directory.Stage === "Updating") |
| 261 | ) { |
| 262 | return Effect.fail( |
| 263 | new DirectoryNotReady({ |
| 264 | directoryId, |
| 265 | stage: directory.Stage, |
| 266 | }), |
| 267 | ); |
| 268 | } |
| 269 | return Effect.succeed(directory); |
| 270 | }), |
| 271 | retryWhileNotReady, |
| 272 | ); |
| 273 | }); |
| 274 | |
| 275 | const toAttrs = Effect.fn(function* (directory: ds.DirectoryDescription) { |
| 276 | if (!directory.DirectoryId || !directory.Name) { |
| 277 | return yield* new DirectoryUnexpectedResponse({ |
| 278 | message: `directory '${directory.DirectoryId}' is missing its id or name`, |
| 279 | }); |
| 280 | } |
| 281 | const { accountId, region } = yield* AWSEnvironment.current; |
| 282 | return { |
| 283 | directoryId: directory.DirectoryId, |
| 284 | directoryArn: `arn:aws:ds:${region}:${accountId}:directory/${directory.DirectoryId}`, |
| 285 | directoryName: directory.Name, |
| 286 | type: directory.Type ?? "SimpleAD", |
| 287 | stage: directory.Stage ?? "Active", |
| 288 | size: directory.Size, |
| 289 | edition: directory.Edition, |
| 290 | alias: directory.Alias, |
| 291 | accessUrl: directory.AccessUrl, |
| 292 | dnsIpAddrs: [...(directory.DnsIpAddrs ?? [])], |
| 293 | securityGroupId: directory.VpcSettings?.SecurityGroupId, |
| 294 | vpcId: directory.VpcSettings?.VpcId, |
| 295 | subnetIds: [...(directory.VpcSettings?.SubnetIds ?? [])], |
| 296 | availabilityZones: [...(directory.VpcSettings?.AvailabilityZones ?? [])], |
| 297 | tags: yield* readDirectoryTags(directory.DirectoryId), |
| 298 | }; |
| 299 | }); |
| 300 | |
| 301 | return { |
| 302 | stables: ["directoryId", "directoryName"], |
| 303 | |
| 304 | diff: Effect.fn(function* ({ olds, news }) { |
| 305 | if (!isResolved(news)) return undefined; |
| 306 | const n = news; |
| 307 | const o = olds; |
| 308 | if (o === undefined || n === undefined) return undefined; |
| 309 | // Every launch property is create-only — there is no update API |
| 310 | // for the directory itself; only tags mutate in place. |
| 311 | const type = (p: DirectoryProps) => p.type ?? "SimpleAD"; |
| 312 | if (type(n) !== type(o)) return { action: "replace" } as const; |
| 313 | if (n.name !== o.name) return { action: "replace" } as const; |
| 314 | if (n.shortName !== o.shortName) { |
| 315 | return { action: "replace" } as const; |
| 316 | } |
| 317 | if (Redacted.value(n.password) !== Redacted.value(o.password)) { |
| 318 | return { action: "replace" } as const; |
| 319 | } |
| 320 | if (n.description !== o.description) { |
| 321 | return { action: "replace" } as const; |
| 322 | } |
| 323 | if (type(n) === "SimpleAD" && (n.size ?? DEFAULT_SIZE) !== (o.size ?? DEFAULT_SIZE)) { |
| 324 | return { action: "replace" } as const; |
| 325 | } |
| 326 | if ( |
| 327 | type(n) === "MicrosoftAD" && |
| 328 | (n.edition ?? DEFAULT_EDITION) !== (o.edition ?? DEFAULT_EDITION) |
| 329 | ) { |
| 330 | return { action: "replace" } as const; |
| 331 | } |
| 332 | if (n.vpcId !== o.vpcId) return { action: "replace" } as const; |
| 333 | if (!sameStringSet(n.subnetIds, o.subnetIds)) { |
| 334 | return { action: "replace" } as const; |
| 335 | } |
| 336 | }), |
| 337 | |
| 338 | read: Effect.fn(function* ({ id, olds, output }) { |
| 339 | const directory = yield* observe(output?.directoryId, olds?.name); |
| 340 | if (directory === undefined) return undefined; |
| 341 | const attrs = yield* toAttrs(directory); |
| 342 | return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs); |
| 343 | }), |
| 344 | |
| 345 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 346 | const props = news!; |
| 347 | const type = props.type ?? "SimpleAD"; |
| 348 | const internalTags = yield* createInternalTags(id); |
| 349 | const desiredTags = { ...internalTags, ...props.tags }; |
| 350 | |
| 351 | // 1. Observe — cloud state is authoritative; output only caches |
| 352 | // the directory id. |
| 353 | const observed = yield* observe(output?.directoryId, props.name); |
| 354 | |
| 355 | // 2. Ensure — create if missing. |
| 356 | let directoryId = observed?.DirectoryId; |
| 357 | if (directoryId === undefined) { |
| 358 | const tagList = Object.entries(desiredTags).map(([Key, Value]) => ({ |
| 359 | Key, |
| 360 | Value, |
| 361 | })); |
| 362 | const created = |
| 363 | type === "MicrosoftAD" |
| 364 | ? yield* ds.createMicrosoftAD({ |
| 365 | Name: props.name, |
| 366 | ShortName: props.shortName, |
| 367 | Password: props.password, |
| 368 | Description: props.description, |
| 369 | Edition: props.edition ?? DEFAULT_EDITION, |
| 370 | VpcSettings: { |
| 371 | VpcId: props.vpcId, |
| 372 | SubnetIds: props.subnetIds, |
| 373 | }, |
| 374 | Tags: tagList, |
| 375 | }) |
| 376 | : yield* ds.createDirectory({ |
| 377 | Name: props.name, |
| 378 | ShortName: props.shortName, |
| 379 | Password: props.password, |
| 380 | Description: props.description, |
| 381 | Size: props.size ?? DEFAULT_SIZE, |
| 382 | VpcSettings: { |
| 383 | VpcId: props.vpcId, |
| 384 | SubnetIds: props.subnetIds, |
| 385 | }, |
| 386 | Tags: tagList, |
| 387 | }); |
| 388 | if (created.DirectoryId === undefined) { |
| 389 | return yield* new DirectoryUnexpectedResponse({ |
| 390 | message: `Create${type} for '${props.name}' returned no DirectoryId`, |
| 391 | }); |
| 392 | } |
| 393 | directoryId = created.DirectoryId; |
| 394 | } |
| 395 | |
| 396 | // Provisioning is slow (Simple AD ~10 min, Microsoft AD 20-40 |
| 397 | // min); wait (bounded) for the directory to become Active so the |
| 398 | // returned attributes (DNS addresses, security group) are real. |
| 399 | const active = yield* waitForActive(directoryId); |
| 400 | |
| 401 | // 3. Sync tags — diff against OBSERVED cloud tags. |
| 402 | const observedTags = yield* readDirectoryTags(directoryId); |
| 403 | const { upsert, removed } = diffTags(observedTags, desiredTags); |
| 404 | if (upsert.length > 0) { |
| 405 | yield* ds.addTagsToResource({ |
| 406 | ResourceId: directoryId, |
| 407 | Tags: upsert, |
| 408 | }); |
| 409 | } |
| 410 | if (removed.length > 0) { |
| 411 | yield* ds.removeTagsFromResource({ |
| 412 | ResourceId: directoryId, |
| 413 | TagKeys: removed, |
| 414 | }); |
| 415 | } |
| 416 | |
| 417 | yield* session.note(directoryId); |
| 418 | return yield* toAttrs(active); |
| 419 | }), |
| 420 | |
| 421 | delete: Effect.fn(function* ({ output }) { |
| 422 | const directoryId = output.directoryId; |
| 423 | // A directory mid-create rejects deletion — wait (bounded) for it |
| 424 | // to settle first. Already deleting (or gone) is success. |
| 425 | const settled = yield* waitUntilSettled(directoryId).pipe( |
| 426 | Effect.orElseSucceed(() => undefined), |
| 427 | ); |
| 428 | if ( |
| 429 | settled === undefined || |
| 430 | settled.Stage === "Deleting" || |
| 431 | settled.Stage === "Deleted" |
| 432 | ) { |
| 433 | return; |
| 434 | } |
| 435 | yield* ds |
| 436 | .deleteDirectory({ DirectoryId: directoryId }) |
| 437 | .pipe(Effect.catchTag("EntityDoesNotExistException", () => Effect.void)); |
| 438 | }), |
| 439 | |
| 440 | list: () => |
| 441 | ds.describeDirectories.items({}).pipe( |
| 442 | Stream.runCollect, |
| 443 | Effect.flatMap((directories) => |
| 444 | Effect.forEach( |
| 445 | Array.from(directories).filter( |
| 446 | (d) => |
| 447 | d.DirectoryId !== undefined && |
| 448 | d.Name !== undefined && |
| 449 | !isTerminalStage(d.Stage), |
| 450 | ), |
| 451 | (d) => toAttrs(d), |
| 452 | { concurrency: 4 }, |
| 453 | ), |
| 454 | ), |
| 455 | ), |
| 456 | }; |
| 457 | }), |
| 458 | ); |