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 repostspace from "@distilled.cloud/aws/repostspace"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Predicate from "effect/Predicate"; |
| 11 | import * as Redacted from "effect/Redacted"; |
| 12 | import * as Schedule from "effect/Schedule"; |
| 13 | import * as Stream from "effect/Stream"; |
| 14 | import type { Providers } from "../Providers.ts"; |
| 15 | |
| 16 | /** Unwrap a distilled sensitive value into its plain string. */ |
| 17 | const unwrapSensitive = ( |
| 18 | value: string | Redacted.Redacted<string> | undefined, |
| 19 | ): string | undefined => |
| 20 | value === undefined ? undefined : Redacted.isRedacted(value) ? Redacted.value(value) : value; |
| 21 | |
| 22 | export interface SpaceSupportedEmailDomains { |
| 23 | /** |
| 24 | * Whether the supported-email-domains feature is enabled for the |
| 25 | * private re:Post. |
| 26 | */ |
| 27 | enabled?: "ENABLED" | "DISABLED"; |
| 28 | /** |
| 29 | * Email domains allowed to join the private re:Post. |
| 30 | */ |
| 31 | allowedDomains?: string[]; |
| 32 | } |
| 33 | |
| 34 | export interface SpaceProps { |
| 35 | /** |
| 36 | * Display name of the private re:Post. Must be unique within the account. |
| 37 | * Changing the name replaces the space. |
| 38 | * @default a deterministic physical name derived from app, stage, and id |
| 39 | */ |
| 40 | name?: string; |
| 41 | /** |
| 42 | * Subdomain the private re:Post is served from |
| 43 | * (`https://{subdomain}-{random}.private.repost.aws`). Must be globally |
| 44 | * unique across AWS re:Post Private. Changing the subdomain replaces the |
| 45 | * space. |
| 46 | * @default a deterministic lowercase physical name derived from app, stage, and id |
| 47 | */ |
| 48 | subdomain?: string; |
| 49 | /** |
| 50 | * Pricing tier of the private re:Post — `"BASIC"` or `"STANDARD"`. |
| 51 | * Updated in place. |
| 52 | * @default "BASIC" |
| 53 | */ |
| 54 | tier?: repostspace.TierLevel; |
| 55 | /** |
| 56 | * Human-readable description of the private re:Post. |
| 57 | */ |
| 58 | description?: string; |
| 59 | /** |
| 60 | * ARN of a customer-managed KMS key used to encrypt the space's data. |
| 61 | * Changing the key replaces the space. |
| 62 | * @default an AWS-owned key |
| 63 | */ |
| 64 | userKMSKey?: string; |
| 65 | /** |
| 66 | * ARN of the IAM role that grants AWS re:Post Private access to |
| 67 | * resources in your account (e.g. for IAM Identity Center integration). |
| 68 | */ |
| 69 | roleArn?: string; |
| 70 | /** |
| 71 | * Email domains allowed to join the private re:Post without an explicit |
| 72 | * invite. |
| 73 | */ |
| 74 | supportedEmailDomains?: SpaceSupportedEmailDomains; |
| 75 | /** |
| 76 | * User-defined tags for the space. Merged with internal Alchemy tags. |
| 77 | */ |
| 78 | tags?: Record<string, string>; |
| 79 | } |
| 80 | |
| 81 | export interface Space extends Resource< |
| 82 | "AWS.RePostSpace.Space", |
| 83 | SpaceProps, |
| 84 | { |
| 85 | /** |
| 86 | * Unique ID of the private re:Post space. |
| 87 | */ |
| 88 | spaceId: string; |
| 89 | /** |
| 90 | * ARN of the space. |
| 91 | */ |
| 92 | spaceArn: string; |
| 93 | /** |
| 94 | * Display name of the space. |
| 95 | */ |
| 96 | name: string; |
| 97 | /** |
| 98 | * Current space status (e.g. `"CREATE_COMPLETED"`). |
| 99 | */ |
| 100 | status: string; |
| 101 | /** |
| 102 | * IAM Identity Center configuration status of the space |
| 103 | * (e.g. `"CONFIGURED"` / `"UNCONFIGURED"`). |
| 104 | */ |
| 105 | configurationStatus: string; |
| 106 | /** |
| 107 | * Client ID of the space's IAM Identity Center application. |
| 108 | */ |
| 109 | clientId: string; |
| 110 | /** |
| 111 | * ID of the IAM Identity Center identity store backing the space. |
| 112 | */ |
| 113 | identityStoreId: string | undefined; |
| 114 | /** |
| 115 | * ARN of the space's IAM Identity Center application. |
| 116 | */ |
| 117 | applicationArn: string | undefined; |
| 118 | /** |
| 119 | * Description of the space. |
| 120 | */ |
| 121 | description: string | undefined; |
| 122 | /** |
| 123 | * Subdomain the space is served from. |
| 124 | */ |
| 125 | vanityDomain: string; |
| 126 | /** |
| 127 | * Approval status of the vanity domain (e.g. `"PENDING"`, `"APPROVED"`). |
| 128 | */ |
| 129 | vanityDomainStatus: string; |
| 130 | /** |
| 131 | * AWS-generated domain the space is reachable on. |
| 132 | */ |
| 133 | randomDomain: string; |
| 134 | /** |
| 135 | * ARN of the customer-provided IAM role the space uses for account |
| 136 | * integrations (mirrors the `roleArn` prop). |
| 137 | */ |
| 138 | customerRoleArn: string | undefined; |
| 139 | /** |
| 140 | * Pricing tier of the space (`"BASIC"` or `"STANDARD"`). |
| 141 | */ |
| 142 | tier: string; |
| 143 | /** |
| 144 | * Storage limit of the space, in bytes. |
| 145 | */ |
| 146 | storageLimit: number; |
| 147 | /** |
| 148 | * Customer-managed KMS key encrypting the space's data, if any. |
| 149 | */ |
| 150 | userKMSKey: string | undefined; |
| 151 | /** |
| 152 | * Tags on the space (including internal Alchemy tags). |
| 153 | */ |
| 154 | tags: Record<string, string>; |
| 155 | }, |
| 156 | never, |
| 157 | Providers |
| 158 | > {} |
| 159 | |
| 160 | /** |
| 161 | * An AWS re:Post Private space — a private, organization-scoped version of |
| 162 | * AWS re:Post with curated Q&A, articles, and selected public content. |
| 163 | * |
| 164 | * re:Post Private is a paid feature (Basic or Standard tier) that requires |
| 165 | * AWS IAM Identity Center to be enabled in the account. Space provisioning |
| 166 | * is asynchronous and can take tens of minutes; the provider waits for the |
| 167 | * space to reach `CREATE_COMPLETED` before returning. |
| 168 | * ### Creating a Space |
| 169 | * **Example:** Basic Space |
| 170 | * ```typescript |
| 171 | * import * as RePostSpace from "@alchemy.run/aws/RePostSpace"; |
| 172 | * |
| 173 | * const space = yield* RePostSpace.Space("Support", { |
| 174 | * subdomain: "my-org-support", |
| 175 | * tier: "BASIC", |
| 176 | * }); |
| 177 | * ``` |
| 178 | * |
| 179 | * **Example:** Space with Description and Tags |
| 180 | * ```typescript |
| 181 | * const space = yield* RePostSpace.Space("Engineering", { |
| 182 | * name: "Engineering Knowledge Base", |
| 183 | * subdomain: "my-org-engineering", |
| 184 | * tier: "STANDARD", |
| 185 | * description: "Internal Q&A for the engineering org", |
| 186 | * tags: { team: "platform" }, |
| 187 | * }); |
| 188 | * ``` |
| 189 | * |
| 190 | * ### Encryption |
| 191 | * **Example:** Space with a Customer-Managed KMS Key |
| 192 | * ```typescript |
| 193 | * const space = yield* RePostSpace.Space("Secure", { |
| 194 | * subdomain: "my-org-secure", |
| 195 | * userKMSKey: key.keyArn, |
| 196 | * }); |
| 197 | * ``` |
| 198 | * |
| 199 | * @resource |
| 200 | */ |
| 201 | export const Space = Resource<Space>("AWS.RePostSpace.Space"); |
| 202 | |
| 203 | const DEFAULT_TIER = "BASIC"; |
| 204 | |
| 205 | /** |
| 206 | * Raised when a re:Post Private space enters a terminal failure state |
| 207 | * (`CREATE_FAILED`) or starts deleting while the provider is waiting for |
| 208 | * provisioning to complete. |
| 209 | */ |
| 210 | export class RePostSpaceProvisioningFailed extends Data.TaggedError( |
| 211 | "RePostSpaceProvisioningFailed", |
| 212 | )<{ spaceId: string; status: string }> {} |
| 213 | |
| 214 | /** Internal marker error driving the bounded readiness retry loop. */ |
| 215 | class RePostSpaceNotReady extends Data.TaggedError("RePostSpaceNotReady")<{ |
| 216 | spaceId: string; |
| 217 | status: string; |
| 218 | }> {} |
| 219 | |
| 220 | const sameStringSet = ( |
| 221 | a: readonly string[] | undefined, |
| 222 | b: readonly string[] | undefined, |
| 223 | ): boolean => { |
| 224 | const left = [...new Set(a ?? [])].sort(); |
| 225 | const right = [...new Set(b ?? [])].sort(); |
| 226 | return left.length === right.length && left.every((v, i) => v === right[i]); |
| 227 | }; |
| 228 | |
| 229 | export const SpaceProvider = () => |
| 230 | Provider.effect( |
| 231 | Space, |
| 232 | Effect.gen(function* () { |
| 233 | const toName = (id: string, props: Partial<SpaceProps>) => |
| 234 | props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 30 }); |
| 235 | |
| 236 | const toSubdomain = (id: string, props: Partial<SpaceProps>) => |
| 237 | props.subdomain |
| 238 | ? Effect.succeed(props.subdomain) |
| 239 | : createPhysicalName({ id, maxLength: 63, lowercase: true }); |
| 240 | |
| 241 | const getSpaceOrUndefined = Effect.fn(function* (spaceId: string) { |
| 242 | return yield* repostspace |
| 243 | .getSpace({ spaceId }) |
| 244 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 245 | }); |
| 246 | |
| 247 | // Locate a live (not deleting/deleted) space by display name. Space |
| 248 | // IDs are auto-assigned, so this is the fallback when the state |
| 249 | // output cache is absent (e.g. after a past persistence failure). |
| 250 | const findByName = Effect.fn(function* (name: string) { |
| 251 | const chunk = yield* repostspace.listSpaces.items({}).pipe(Stream.runCollect); |
| 252 | return Array.from(chunk).find( |
| 253 | (space) => unwrapSensitive(space.name) === name && !space.status.startsWith("DELETE"), |
| 254 | ); |
| 255 | }); |
| 256 | |
| 257 | const readSpaceTags = Effect.fn(function* (arn: string) { |
| 258 | const response = yield* repostspace |
| 259 | .listTagsForResource({ resourceArn: arn }) |
| 260 | .pipe(Effect.orElseSucceed(() => undefined)); |
| 261 | const tags: Record<string, string> = {}; |
| 262 | for (const [key, value] of Object.entries(response?.tags ?? {})) { |
| 263 | if (value !== undefined) tags[key] = value; |
| 264 | } |
| 265 | return tags; |
| 266 | }); |
| 267 | |
| 268 | // Explicitly-typed pipeable retry helper. Inlining `Effect.retry` in a |
| 269 | // provider lifecycle op leaks `Retry.Return`'s conditional into |
| 270 | // declaration emit and widens the provider layer to `unknown` R for |
| 271 | // every consumer of `AWS.providers()`. |
| 272 | const retryWhileSpaceNotReady = <A, E extends { readonly _tag: string }, R>( |
| 273 | self: Effect.Effect<A, E, R>, |
| 274 | ): Effect.Effect<A, E, R> => |
| 275 | Effect.retry(self, { |
| 276 | while: (e) => e._tag === "RePostSpaceNotReady", |
| 277 | schedule: Schedule.max([Schedule.fixed("30 seconds"), Schedule.recurs(80)]), |
| 278 | }); |
| 279 | |
| 280 | // Bounded readiness wait. Space provisioning is asynchronous and can |
| 281 | // take ~30 minutes; budget 40 min (80 * 30s). CREATE_FAILED and any |
| 282 | // DELETE* status are terminal failures and stop the retry loop. |
| 283 | const waitForCreated = Effect.fn(function* (spaceId: string) { |
| 284 | return yield* retryWhileSpaceNotReady( |
| 285 | Effect.gen(function* () { |
| 286 | const space = yield* repostspace.getSpace({ spaceId }); |
| 287 | if (space.status === "CREATE_FAILED" || space.status.startsWith("DELETE")) { |
| 288 | return yield* new RePostSpaceProvisioningFailed({ |
| 289 | spaceId, |
| 290 | status: space.status, |
| 291 | }); |
| 292 | } |
| 293 | if (space.status !== "CREATE_COMPLETED") { |
| 294 | return yield* new RePostSpaceNotReady({ spaceId, status: space.status }); |
| 295 | } |
| 296 | return space; |
| 297 | }), |
| 298 | ); |
| 299 | }); |
| 300 | |
| 301 | const toAttrs = Effect.fn(function* (space: repostspace.GetSpaceOutput) { |
| 302 | return { |
| 303 | spaceId: space.spaceId, |
| 304 | spaceArn: space.arn, |
| 305 | name: unwrapSensitive(space.name) ?? "", |
| 306 | status: space.status, |
| 307 | configurationStatus: space.configurationStatus, |
| 308 | clientId: space.clientId, |
| 309 | identityStoreId: space.identityStoreId, |
| 310 | applicationArn: space.applicationArn, |
| 311 | description: unwrapSensitive(space.description), |
| 312 | vanityDomain: space.vanityDomain, |
| 313 | vanityDomainStatus: space.vanityDomainStatus, |
| 314 | randomDomain: space.randomDomain, |
| 315 | customerRoleArn: space.customerRoleArn, |
| 316 | tier: space.tier, |
| 317 | storageLimit: space.storageLimit, |
| 318 | userKMSKey: space.userKMSKey, |
| 319 | tags: yield* readSpaceTags(space.arn), |
| 320 | }; |
| 321 | }); |
| 322 | |
| 323 | return Space.Provider.of({ |
| 324 | stables: ["spaceId", "spaceArn", "clientId"], |
| 325 | |
| 326 | list: () => |
| 327 | Effect.gen(function* () { |
| 328 | const chunk = yield* repostspace.listSpaces.items({}).pipe(Stream.runCollect); |
| 329 | const items = yield* Effect.forEach( |
| 330 | Array.from(chunk), |
| 331 | (space) => |
| 332 | repostspace.getSpace({ spaceId: space.spaceId }).pipe( |
| 333 | Effect.flatMap((full) => toAttrs(full)), |
| 334 | // A space can vanish between enumeration and hydration. |
| 335 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 336 | ), |
| 337 | { concurrency: 4 }, |
| 338 | ); |
| 339 | return items.filter(Predicate.isNotUndefined); |
| 340 | }), |
| 341 | |
| 342 | read: Effect.fn(function* ({ id, olds, output }) { |
| 343 | let spaceId = output?.spaceId; |
| 344 | if (spaceId === undefined) { |
| 345 | const name = yield* toName(id, olds ?? {}); |
| 346 | const found = yield* findByName(name); |
| 347 | spaceId = found?.spaceId; |
| 348 | } |
| 349 | if (spaceId === undefined) return undefined; |
| 350 | const space = yield* getSpaceOrUndefined(spaceId); |
| 351 | if (space === undefined || space.status.startsWith("DELETE")) { |
| 352 | return undefined; |
| 353 | } |
| 354 | const attrs = yield* toAttrs(space); |
| 355 | return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs); |
| 356 | }), |
| 357 | |
| 358 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 359 | if (!isResolved(news)) return undefined; |
| 360 | const n = news ?? {}; |
| 361 | const o = olds ?? {}; |
| 362 | // Create-only properties force a replacement. |
| 363 | if ((yield* toName(id, o)) !== (yield* toName(id, n))) { |
| 364 | return { action: "replace" } as const; |
| 365 | } |
| 366 | if ((yield* toSubdomain(id, o)) !== (yield* toSubdomain(id, n))) { |
| 367 | return { action: "replace" } as const; |
| 368 | } |
| 369 | if (n.userKMSKey !== o.userKMSKey) { |
| 370 | return { action: "replace" } as const; |
| 371 | } |
| 372 | // tier, description, roleArn, supportedEmailDomains update in place. |
| 373 | }), |
| 374 | |
| 375 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 376 | const props = news ?? {}; |
| 377 | const name = output?.name ?? (yield* toName(id, props)); |
| 378 | const internalTags = yield* createInternalTags(id); |
| 379 | const desiredTags = { ...internalTags, ...props.tags }; |
| 380 | const desiredTier = props.tier ?? DEFAULT_TIER; |
| 381 | |
| 382 | // 1. Observe — cloud state is authoritative; output is only an |
| 383 | // id cache. Fall through to a by-name lookup when the cached |
| 384 | // space no longer exists. |
| 385 | let spaceId = output?.spaceId; |
| 386 | if (spaceId !== undefined) { |
| 387 | const cached = yield* getSpaceOrUndefined(spaceId); |
| 388 | if (cached === undefined || cached.status.startsWith("DELETE")) { |
| 389 | spaceId = undefined; |
| 390 | } |
| 391 | } |
| 392 | if (spaceId === undefined) { |
| 393 | const found = yield* findByName(name); |
| 394 | spaceId = found?.spaceId; |
| 395 | } |
| 396 | |
| 397 | // 2. Ensure — create if missing; a ConflictException means a peer |
| 398 | // created it concurrently (or the name/subdomain is taken), so |
| 399 | // fall back to the by-name lookup. |
| 400 | if (spaceId === undefined) { |
| 401 | const subdomain = yield* toSubdomain(id, props); |
| 402 | spaceId = yield* repostspace |
| 403 | .createSpace({ |
| 404 | name, |
| 405 | subdomain, |
| 406 | tier: desiredTier, |
| 407 | description: props.description, |
| 408 | userKMSKey: props.userKMSKey, |
| 409 | roleArn: props.roleArn, |
| 410 | supportedEmailDomains: props.supportedEmailDomains, |
| 411 | tags: desiredTags, |
| 412 | }) |
| 413 | .pipe( |
| 414 | Effect.map((r) => r.spaceId), |
| 415 | Effect.catchTag("ConflictException", (error) => |
| 416 | findByName(name).pipe( |
| 417 | Effect.flatMap((existing) => |
| 418 | existing !== undefined |
| 419 | ? Effect.succeed(existing.spaceId) |
| 420 | : Effect.fail(error), |
| 421 | ), |
| 422 | ), |
| 423 | ), |
| 424 | ); |
| 425 | yield* session.note(`created space ${spaceId}, provisioning...`); |
| 426 | } |
| 427 | |
| 428 | // Provisioning is asynchronous — wait (bounded) for the space to |
| 429 | // become usable before syncing mutable aspects. |
| 430 | let observed = yield* waitForCreated(spaceId); |
| 431 | |
| 432 | // 3. Sync — compute the update delta from OBSERVED state and call |
| 433 | // updateSpace only when something actually changed. |
| 434 | const update: { |
| 435 | description?: string; |
| 436 | tier?: repostspace.TierLevel; |
| 437 | roleArn?: string; |
| 438 | supportedEmailDomains?: repostspace.SupportedEmailDomainsParameters; |
| 439 | } = {}; |
| 440 | let mutated = false; |
| 441 | if ( |
| 442 | props.description !== undefined && |
| 443 | props.description !== unwrapSensitive(observed.description) |
| 444 | ) { |
| 445 | update.description = props.description; |
| 446 | mutated = true; |
| 447 | } |
| 448 | if (props.tier !== undefined && props.tier !== observed.tier) { |
| 449 | update.tier = props.tier; |
| 450 | mutated = true; |
| 451 | } |
| 452 | if (props.roleArn !== undefined && props.roleArn !== observed.customerRoleArn) { |
| 453 | update.roleArn = props.roleArn; |
| 454 | mutated = true; |
| 455 | } |
| 456 | if (props.supportedEmailDomains !== undefined) { |
| 457 | const observedDomains = (observed.supportedEmailDomains?.allowedDomains ?? []).map( |
| 458 | (domain: string | Redacted.Redacted<string>) => unwrapSensitive(domain) ?? "", |
| 459 | ); |
| 460 | if ( |
| 461 | props.supportedEmailDomains.enabled !== observed.supportedEmailDomains?.enabled || |
| 462 | !sameStringSet(props.supportedEmailDomains.allowedDomains, observedDomains) |
| 463 | ) { |
| 464 | update.supportedEmailDomains = props.supportedEmailDomains; |
| 465 | mutated = true; |
| 466 | } |
| 467 | } |
| 468 | if (mutated) { |
| 469 | yield* repostspace.updateSpace({ spaceId, ...update }); |
| 470 | const refreshed = yield* getSpaceOrUndefined(spaceId); |
| 471 | if (refreshed !== undefined) observed = refreshed; |
| 472 | } |
| 473 | |
| 474 | // 3b. Sync tags — diff against OBSERVED cloud tags so adoption |
| 475 | // converges. |
| 476 | const observedTags = yield* readSpaceTags(observed.arn); |
| 477 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 478 | if (upsert.length > 0) { |
| 479 | yield* repostspace.tagResource({ |
| 480 | resourceArn: observed.arn, |
| 481 | tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])), |
| 482 | }); |
| 483 | } |
| 484 | if (removed.length > 0) { |
| 485 | yield* repostspace.untagResource({ |
| 486 | resourceArn: observed.arn, |
| 487 | tagKeys: removed, |
| 488 | }); |
| 489 | } |
| 490 | |
| 491 | yield* session.note(spaceId); |
| 492 | return yield* toAttrs(observed); |
| 493 | }), |
| 494 | |
| 495 | delete: Effect.fn(function* ({ output }) { |
| 496 | yield* repostspace |
| 497 | .deleteSpace({ spaceId: output.spaceId }) |
| 498 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 499 | }), |
| 500 | }); |
| 501 | }), |
| 502 | ); |