The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as qbusiness from "@distilled.cloud/aws/qbusiness"; |
| 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, type Tags } 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 * as EffectStream from "effect/Stream"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | |
| 14 | export class QBusinessApplicationInvalidProps extends Data.TaggedError( |
| 15 | "QBusinessApplicationInvalidProps", |
| 16 | )<{ |
| 17 | readonly message: string; |
| 18 | readonly cause?: unknown; |
| 19 | }> {} |
| 20 | |
| 21 | export class QBusinessApplicationUnexpectedResponse extends Data.TaggedError( |
| 22 | "QBusinessApplicationUnexpectedResponse", |
| 23 | )<{ |
| 24 | readonly message: string; |
| 25 | readonly cause?: unknown; |
| 26 | }> {} |
| 27 | |
| 28 | export type ApplicationStatus = qbusiness.ApplicationStatus; |
| 29 | export type IdentityType = qbusiness.IdentityType; |
| 30 | |
| 31 | /** |
| 32 | * Encryption-at-rest configuration for an Amazon Q Business application. |
| 33 | */ |
| 34 | export interface ApplicationEncryptionConfiguration { |
| 35 | /** |
| 36 | * The identifier of the customer-managed KMS key. Amazon Q Business does |
| 37 | * not support asymmetric keys. |
| 38 | */ |
| 39 | kmsKeyId?: string; |
| 40 | } |
| 41 | |
| 42 | export interface ApplicationProps { |
| 43 | /** |
| 44 | * Display name of the application. |
| 45 | * @default ${app}-${stage}-${id} |
| 46 | */ |
| 47 | displayName?: string; |
| 48 | /** |
| 49 | * The authentication type the application connects users with. |
| 50 | * `AWS_IAM_IDC` (IAM Identity Center) is the default and requires |
| 51 | * `identityCenterInstanceArn`. Changing it replaces the application. |
| 52 | * @default "AWS_IAM_IDC" |
| 53 | */ |
| 54 | identityType?: IdentityType; |
| 55 | /** |
| 56 | * ARN of the IAM Identity Center instance the application connects to. |
| 57 | * Required when `identityType` is `AWS_IAM_IDC` (the default). |
| 58 | */ |
| 59 | identityCenterInstanceArn?: string; |
| 60 | /** |
| 61 | * ARN of an IAM identity provider (SAML/OIDC) when `identityType` is |
| 62 | * `AWS_IAM_IDP_SAML` or `AWS_IAM_IDP_OIDC`. Changing it replaces the |
| 63 | * application. |
| 64 | */ |
| 65 | iamIdentityProviderArn?: string; |
| 66 | /** |
| 67 | * OIDC client IDs when `identityType` is `AWS_IAM_IDP_OIDC`. Changing |
| 68 | * them replaces the application. |
| 69 | */ |
| 70 | clientIdsForOIDC?: string[]; |
| 71 | /** |
| 72 | * ARN of the IAM role Amazon Q Business assumes to publish CloudWatch |
| 73 | * logs and metrics. |
| 74 | */ |
| 75 | roleArn?: string; |
| 76 | /** |
| 77 | * A description of the application. |
| 78 | */ |
| 79 | description?: string; |
| 80 | /** |
| 81 | * Encryption-at-rest configuration. Changing it replaces the application. |
| 82 | */ |
| 83 | encryptionConfiguration?: ApplicationEncryptionConfiguration; |
| 84 | /** |
| 85 | * Whether end users can upload files directly into chat conversations. |
| 86 | */ |
| 87 | attachmentsConfiguration?: qbusiness.AttachmentsConfiguration; |
| 88 | /** |
| 89 | * Whether end users can create and use Amazon Q Apps. |
| 90 | */ |
| 91 | qAppsConfiguration?: qbusiness.QAppsConfiguration; |
| 92 | /** |
| 93 | * Whether Amazon Q Business personalizes chat responses using details |
| 94 | * from the user's IAM Identity Center profile. |
| 95 | */ |
| 96 | personalizationConfiguration?: qbusiness.PersonalizationConfiguration; |
| 97 | /** |
| 98 | * Automatic-subscription settings for users of the application. |
| 99 | */ |
| 100 | autoSubscriptionConfiguration?: qbusiness.AutoSubscriptionConfiguration; |
| 101 | /** |
| 102 | * Amazon QuickSight identity configuration, when `identityType` is |
| 103 | * `AWS_QUICKSIGHT_IDP`. Changing it replaces the application. |
| 104 | */ |
| 105 | quickSightConfiguration?: qbusiness.QuickSightConfiguration; |
| 106 | /** |
| 107 | * Tags to associate with the application. |
| 108 | */ |
| 109 | tags?: Record<string, string>; |
| 110 | } |
| 111 | |
| 112 | export interface Application extends Resource< |
| 113 | "AWS.QBusiness.Application", |
| 114 | ApplicationProps, |
| 115 | { |
| 116 | /** |
| 117 | * Service-assigned unique identifier of the application. |
| 118 | */ |
| 119 | applicationId: string; |
| 120 | /** |
| 121 | * ARN of the application. |
| 122 | */ |
| 123 | applicationArn: string; |
| 124 | /** |
| 125 | * The application's display name. |
| 126 | */ |
| 127 | displayName: string; |
| 128 | /** |
| 129 | * Current lifecycle status of the application. |
| 130 | */ |
| 131 | status: ApplicationStatus | undefined; |
| 132 | /** |
| 133 | * The authentication type the application was created with. |
| 134 | */ |
| 135 | identityType: IdentityType | undefined; |
| 136 | /** |
| 137 | * ARN of the IAM Identity Center application created for this Amazon Q |
| 138 | * Business application (when `identityType` is `AWS_IAM_IDC`). |
| 139 | */ |
| 140 | identityCenterApplicationArn: string | undefined; |
| 141 | /** |
| 142 | * ARN of the IAM role used for CloudWatch logs/metrics. |
| 143 | */ |
| 144 | roleArn: string | undefined; |
| 145 | /** |
| 146 | * Current tags reported for the application. |
| 147 | */ |
| 148 | tags: Record<string, string>; |
| 149 | }, |
| 150 | never, |
| 151 | Providers |
| 152 | > {} |
| 153 | |
| 154 | /** |
| 155 | * An Amazon Q Business application — the top-level container that indices, |
| 156 | * retrievers, data sources, and web experiences attach to. |
| 157 | * |
| 158 | * :::caution |
| 159 | * Creating an application with the default `AWS_IAM_IDC` identity type |
| 160 | * requires an IAM Identity Center instance in the account (pass its ARN as |
| 161 | * `identityCenterInstanceArn`). |
| 162 | * ::: |
| 163 | * ### Creating Applications |
| 164 | * **Example:** Identity Center Application |
| 165 | * ```typescript |
| 166 | * import * as AWS from "@alchemy.run/aws"; |
| 167 | * |
| 168 | * const app = yield* AWS.QBusiness.Application("Assistant", { |
| 169 | * identityCenterInstanceArn: "arn:aws:sso:::instance/ssoins-1234567890abcdef", |
| 170 | * description: "Company knowledge assistant", |
| 171 | * }); |
| 172 | * ``` |
| 173 | * |
| 174 | * **Example:** Anonymous Application |
| 175 | * ```typescript |
| 176 | * const app = yield* AWS.QBusiness.Application("PublicAssistant", { |
| 177 | * identityType: "ANONYMOUS", |
| 178 | * }); |
| 179 | * ``` |
| 180 | * |
| 181 | * @resource |
| 182 | */ |
| 183 | export const Application = Resource<Application>("AWS.QBusiness.Application"); |
| 184 | |
| 185 | const createDisplayName = (id: string, props: { displayName?: string | undefined }) => |
| 186 | props.displayName |
| 187 | ? Effect.succeed(props.displayName) |
| 188 | : createPhysicalName({ id, maxLength: 100 }); |
| 189 | |
| 190 | const fetchTags = Effect.fn(function* (arn: string) { |
| 191 | const response = yield* qbusiness |
| 192 | .listTagsForResource({ resourceARN: arn }) |
| 193 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 194 | return Object.fromEntries((response?.tags ?? []).map((tag) => [tag.key, tag.value])); |
| 195 | }); |
| 196 | |
| 197 | interface ApplicationState { |
| 198 | attrs: Application["Attributes"]; |
| 199 | described: qbusiness.GetApplicationResponse; |
| 200 | } |
| 201 | |
| 202 | const readApplicationById = Effect.fn(function* (applicationId: string) { |
| 203 | const described = yield* qbusiness |
| 204 | .getApplication({ applicationId }) |
| 205 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 206 | if (!described || described.status === "DELETING") return undefined; |
| 207 | const arn = described.applicationArn; |
| 208 | if (arn === undefined) return undefined; |
| 209 | const state: ApplicationState = { |
| 210 | described, |
| 211 | attrs: { |
| 212 | applicationId: described.applicationId ?? applicationId, |
| 213 | applicationArn: arn, |
| 214 | displayName: described.displayName ?? "", |
| 215 | status: described.status, |
| 216 | identityType: described.identityType, |
| 217 | identityCenterApplicationArn: described.identityCenterApplicationArn, |
| 218 | roleArn: described.roleArn, |
| 219 | tags: yield* fetchTags(arn), |
| 220 | }, |
| 221 | }; |
| 222 | return state; |
| 223 | }); |
| 224 | |
| 225 | const findApplicationByName = Effect.fn(function* (displayName: string) { |
| 226 | const summaries = yield* qbusiness.listApplications.pages({}).pipe( |
| 227 | EffectStream.runCollect, |
| 228 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.applications ?? [])), |
| 229 | ); |
| 230 | const match = summaries.find( |
| 231 | (summary) => summary.displayName === displayName && summary.status !== "DELETING", |
| 232 | ); |
| 233 | if (!match?.applicationId) return undefined; |
| 234 | return yield* readApplicationById(match.applicationId); |
| 235 | }); |
| 236 | |
| 237 | /** |
| 238 | * An application still transitioning toward the awaited status — retried by |
| 239 | * {@link waitForApplicationStatus}'s bounded schedule. |
| 240 | */ |
| 241 | class ApplicationNotReady extends Data.TaggedError("ApplicationNotReady")<{ |
| 242 | readonly applicationId: string; |
| 243 | readonly status: string | undefined; |
| 244 | }> {} |
| 245 | |
| 246 | /** |
| 247 | * An application whose asynchronous provisioning converged to the terminal |
| 248 | * `FAILED` status. |
| 249 | */ |
| 250 | export class ApplicationProvisioningFailed extends Data.TaggedError( |
| 251 | "ApplicationProvisioningFailed", |
| 252 | )<{ |
| 253 | readonly applicationId: string; |
| 254 | readonly message: string | undefined; |
| 255 | }> {} |
| 256 | |
| 257 | // Explicitly-typed retry wrapper — an inline `Effect.retry` in provider |
| 258 | // lifecycle code leaks `Retry.Return`'s conditional type into declaration |
| 259 | // emit and widens the provider layer to `unknown` for every consumer of |
| 260 | // `AWS.providers()`. |
| 261 | const retryWhileNotReady = <A, E extends { readonly _tag: string }, R>( |
| 262 | self: Effect.Effect<A, E, R>, |
| 263 | ): Effect.Effect<A, E, R> => |
| 264 | Effect.retry(self, { |
| 265 | while: (e) => e._tag === "ApplicationNotReady", |
| 266 | // Application provisioning normally completes within a couple minutes; |
| 267 | // poll every 5s up to ~10 min. |
| 268 | schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(120)]), |
| 269 | }); |
| 270 | |
| 271 | // Deleting an application while dependent resources are still tearing down |
| 272 | // surfaces as ConflictException. Bounded retry through the window. |
| 273 | const retryThroughConflict = <A, E extends { readonly _tag: string }, R>( |
| 274 | self: Effect.Effect<A, E, R>, |
| 275 | ): Effect.Effect<A, E, R> => |
| 276 | Effect.retry(self, { |
| 277 | while: (e) => e._tag === "ConflictException", |
| 278 | schedule: Schedule.max([Schedule.spaced("10 seconds"), Schedule.recurs(10)]), |
| 279 | }); |
| 280 | |
| 281 | const waitForApplicationStatus = (applicationId: string, target: "ACTIVE" | "DELETED") => |
| 282 | retryWhileNotReady( |
| 283 | Effect.gen(function* () { |
| 284 | const described = yield* qbusiness |
| 285 | .getApplication({ applicationId }) |
| 286 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 287 | if (target === "DELETED") { |
| 288 | if (described === undefined) return; |
| 289 | return yield* new ApplicationNotReady({ applicationId, status: described.status }); |
| 290 | } |
| 291 | if (described?.status === "ACTIVE") return; |
| 292 | if (described?.status === "FAILED") { |
| 293 | return yield* new ApplicationProvisioningFailed({ |
| 294 | applicationId, |
| 295 | message: described.error?.errorMessage, |
| 296 | }); |
| 297 | } |
| 298 | return yield* new ApplicationNotReady({ applicationId, status: described?.status }); |
| 299 | }), |
| 300 | ); |
| 301 | |
| 302 | export const ApplicationProvider = () => |
| 303 | Provider.effect( |
| 304 | Application, |
| 305 | Effect.gen(function* () { |
| 306 | return { |
| 307 | stables: ["applicationId", "applicationArn"], |
| 308 | list: () => |
| 309 | Effect.gen(function* () { |
| 310 | const summaries = yield* qbusiness.listApplications.pages({}).pipe( |
| 311 | EffectStream.runCollect, |
| 312 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.applications ?? [])), |
| 313 | ); |
| 314 | const hydrated = yield* Effect.forEach( |
| 315 | summaries.flatMap((s) => (s.applicationId ? [s.applicationId] : [])), |
| 316 | (applicationId) => readApplicationById(applicationId), |
| 317 | { concurrency: 5 }, |
| 318 | ); |
| 319 | return hydrated.flatMap((state) => (state === undefined ? [] : [state.attrs])); |
| 320 | }), |
| 321 | read: Effect.fn(function* ({ id, olds, output }) { |
| 322 | const state = output?.applicationId |
| 323 | ? yield* readApplicationById(output.applicationId) |
| 324 | : yield* findApplicationByName(yield* createDisplayName(id, olds ?? {})); |
| 325 | if (!state) return undefined; |
| 326 | return (yield* hasAlchemyTags(id, state.attrs.tags as Tags)) |
| 327 | ? state.attrs |
| 328 | : Unowned(state.attrs); |
| 329 | }), |
| 330 | diff: Effect.fn(function* ({ news, olds }) { |
| 331 | if (!isResolved(news)) return; |
| 332 | if (olds === undefined) return; |
| 333 | // Identity wiring and encryption-at-rest are fixed at creation. |
| 334 | if ( |
| 335 | (olds.identityType ?? "AWS_IAM_IDC") !== (news.identityType ?? "AWS_IAM_IDC") || |
| 336 | olds.iamIdentityProviderArn !== news.iamIdentityProviderArn || |
| 337 | olds.encryptionConfiguration?.kmsKeyId !== news.encryptionConfiguration?.kmsKeyId || |
| 338 | olds.quickSightConfiguration?.clientNamespace !== |
| 339 | news.quickSightConfiguration?.clientNamespace || |
| 340 | JSON.stringify(olds.clientIdsForOIDC ?? []) !== |
| 341 | JSON.stringify(news.clientIdsForOIDC ?? []) |
| 342 | ) { |
| 343 | return { action: "replace" } as const; |
| 344 | } |
| 345 | }), |
| 346 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 347 | if (!news) { |
| 348 | return yield* new QBusinessApplicationInvalidProps({ |
| 349 | message: "QBusiness Application requires props", |
| 350 | }); |
| 351 | } |
| 352 | const displayName = yield* createDisplayName(id, news); |
| 353 | const internalTags = yield* createInternalTags(id); |
| 354 | const desiredTags = { ...internalTags, ...news.tags }; |
| 355 | |
| 356 | // Observe — prefer the cached id; fall back to a name lookup so a |
| 357 | // create whose state failed to persist is adopted, not duplicated. |
| 358 | let state = output?.applicationId |
| 359 | ? yield* readApplicationById(output.applicationId) |
| 360 | : yield* findApplicationByName(displayName); |
| 361 | |
| 362 | // Ensure — create if missing, then wait for ACTIVE. |
| 363 | if (state === undefined) { |
| 364 | const created = yield* qbusiness.createApplication({ |
| 365 | displayName, |
| 366 | identityType: news.identityType, |
| 367 | identityCenterInstanceArn: news.identityCenterInstanceArn, |
| 368 | iamIdentityProviderArn: news.iamIdentityProviderArn, |
| 369 | clientIdsForOIDC: news.clientIdsForOIDC, |
| 370 | roleArn: news.roleArn, |
| 371 | description: news.description, |
| 372 | encryptionConfiguration: news.encryptionConfiguration, |
| 373 | attachmentsConfiguration: news.attachmentsConfiguration, |
| 374 | qAppsConfiguration: news.qAppsConfiguration, |
| 375 | personalizationConfiguration: news.personalizationConfiguration, |
| 376 | quickSightConfiguration: news.quickSightConfiguration, |
| 377 | tags: Object.entries(desiredTags).map(([key, value]) => ({ |
| 378 | key, |
| 379 | value, |
| 380 | })), |
| 381 | }); |
| 382 | if (!created.applicationId) { |
| 383 | return yield* new QBusinessApplicationUnexpectedResponse({ |
| 384 | message: `CreateApplication for '${displayName}' returned no applicationId`, |
| 385 | }); |
| 386 | } |
| 387 | yield* session.note( |
| 388 | `Creating application ${displayName} (${created.applicationId})...`, |
| 389 | ); |
| 390 | yield* waitForApplicationStatus(created.applicationId, "ACTIVE"); |
| 391 | state = yield* readApplicationById(created.applicationId); |
| 392 | if (state === undefined) { |
| 393 | return yield* new QBusinessApplicationUnexpectedResponse({ |
| 394 | message: `failed to read created application ${displayName}`, |
| 395 | }); |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | // Sync mutable settings via UpdateApplication — only when drifted. |
| 400 | const described = state.described; |
| 401 | const needsUpdate = |
| 402 | displayName !== described.displayName || |
| 403 | (news.description ?? "") !== (described.description ?? "") || |
| 404 | (news.roleArn !== undefined && news.roleArn !== described.roleArn) || |
| 405 | (news.attachmentsConfiguration !== undefined && |
| 406 | news.attachmentsConfiguration.attachmentsControlMode !== |
| 407 | described.attachmentsConfiguration?.attachmentsControlMode) || |
| 408 | (news.qAppsConfiguration !== undefined && |
| 409 | news.qAppsConfiguration.qAppsControlMode !== |
| 410 | described.qAppsConfiguration?.qAppsControlMode) || |
| 411 | (news.personalizationConfiguration !== undefined && |
| 412 | news.personalizationConfiguration.personalizationControlMode !== |
| 413 | described.personalizationConfiguration?.personalizationControlMode) || |
| 414 | (news.autoSubscriptionConfiguration !== undefined && |
| 415 | (news.autoSubscriptionConfiguration.autoSubscribe !== |
| 416 | described.autoSubscriptionConfiguration?.autoSubscribe || |
| 417 | news.autoSubscriptionConfiguration.defaultSubscriptionType !== |
| 418 | described.autoSubscriptionConfiguration?.defaultSubscriptionType)); |
| 419 | if (needsUpdate) { |
| 420 | yield* qbusiness.updateApplication({ |
| 421 | applicationId: state.attrs.applicationId, |
| 422 | displayName, |
| 423 | description: news.description, |
| 424 | roleArn: news.roleArn, |
| 425 | identityCenterInstanceArn: news.identityCenterInstanceArn, |
| 426 | attachmentsConfiguration: news.attachmentsConfiguration, |
| 427 | qAppsConfiguration: news.qAppsConfiguration, |
| 428 | personalizationConfiguration: news.personalizationConfiguration, |
| 429 | autoSubscriptionConfiguration: news.autoSubscriptionConfiguration, |
| 430 | }); |
| 431 | yield* waitForApplicationStatus(state.attrs.applicationId, "ACTIVE"); |
| 432 | yield* session.note(`Updated application ${displayName}`); |
| 433 | } |
| 434 | |
| 435 | // Sync tags — diff against observed cloud tags. |
| 436 | const { removed, upsert } = diffTags(state.attrs.tags, desiredTags); |
| 437 | if (removed.length > 0) { |
| 438 | yield* qbusiness.untagResource({ |
| 439 | resourceARN: state.attrs.applicationArn, |
| 440 | tagKeys: removed, |
| 441 | }); |
| 442 | } |
| 443 | if (upsert.length > 0) { |
| 444 | yield* qbusiness.tagResource({ |
| 445 | resourceARN: state.attrs.applicationArn, |
| 446 | tags: upsert.map(({ Key, Value }) => ({ |
| 447 | key: Key, |
| 448 | value: Value, |
| 449 | })), |
| 450 | }); |
| 451 | } |
| 452 | |
| 453 | yield* session.note(state.attrs.applicationArn); |
| 454 | |
| 455 | const final = yield* readApplicationById(state.attrs.applicationId); |
| 456 | if (!final) { |
| 457 | return yield* new QBusinessApplicationUnexpectedResponse({ |
| 458 | message: `failed to read reconciled application ${displayName}`, |
| 459 | }); |
| 460 | } |
| 461 | return final.attrs; |
| 462 | }), |
| 463 | delete: Effect.fn(function* ({ output }) { |
| 464 | yield* retryThroughConflict( |
| 465 | qbusiness |
| 466 | .deleteApplication({ applicationId: output.applicationId }) |
| 467 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)), |
| 468 | ); |
| 469 | yield* waitForApplicationStatus(output.applicationId, "DELETED"); |
| 470 | }), |
| 471 | }; |
| 472 | }), |
| 473 | ); |