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 QBusinessSearchIndexInvalidProps extends Data.TaggedError( |
| 15 | "QBusinessSearchIndexInvalidProps", |
| 16 | )<{ |
| 17 | readonly message: string; |
| 18 | readonly cause?: unknown; |
| 19 | }> {} |
| 20 | |
| 21 | export class QBusinessSearchIndexUnexpectedResponse extends Data.TaggedError( |
| 22 | "QBusinessSearchIndexUnexpectedResponse", |
| 23 | )<{ |
| 24 | readonly message: string; |
| 25 | readonly cause?: unknown; |
| 26 | }> {} |
| 27 | |
| 28 | export type IndexStatus = qbusiness.IndexStatus; |
| 29 | export type IndexType = qbusiness.IndexType; |
| 30 | |
| 31 | export interface IndexProps { |
| 32 | /** |
| 33 | * The identifier of the Amazon Q Business application the index attaches |
| 34 | * to. Changing it replaces the index. |
| 35 | */ |
| 36 | applicationId: string; |
| 37 | /** |
| 38 | * Display name of the index. |
| 39 | * @default ${app}-${stage}-${id} |
| 40 | */ |
| 41 | displayName?: string; |
| 42 | /** |
| 43 | * A description of the index. |
| 44 | */ |
| 45 | description?: string; |
| 46 | /** |
| 47 | * The index tier — `STARTER` (single AZ) or `ENTERPRISE` (multi AZ). |
| 48 | * Changing it replaces the index. |
| 49 | * @default "STARTER" |
| 50 | */ |
| 51 | type?: IndexType; |
| 52 | /** |
| 53 | * Provisioned storage capacity units. Each unit stores 20,000 documents. |
| 54 | * @default 1 unit |
| 55 | */ |
| 56 | capacityConfiguration?: qbusiness.IndexCapacityConfiguration; |
| 57 | /** |
| 58 | * Configuration for document metadata attributes (search/display |
| 59 | * behavior). |
| 60 | */ |
| 61 | documentAttributeConfigurations?: qbusiness.DocumentAttributeConfiguration[]; |
| 62 | /** |
| 63 | * Tags to associate with the index. |
| 64 | */ |
| 65 | tags?: Record<string, string>; |
| 66 | } |
| 67 | |
| 68 | export interface Index extends Resource< |
| 69 | "AWS.QBusiness.Index", |
| 70 | IndexProps, |
| 71 | { |
| 72 | /** |
| 73 | * Service-assigned unique identifier of the index (unique within its |
| 74 | * application). |
| 75 | */ |
| 76 | indexId: string; |
| 77 | /** |
| 78 | * The identifier of the application the index belongs to. |
| 79 | */ |
| 80 | applicationId: string; |
| 81 | /** |
| 82 | * ARN of the index. |
| 83 | */ |
| 84 | indexArn: string; |
| 85 | /** |
| 86 | * The index's display name. |
| 87 | */ |
| 88 | displayName: string; |
| 89 | /** |
| 90 | * The provisioned index tier. |
| 91 | */ |
| 92 | type: IndexType | undefined; |
| 93 | /** |
| 94 | * Current lifecycle status of the index. |
| 95 | */ |
| 96 | status: IndexStatus | undefined; |
| 97 | /** |
| 98 | * Current tags reported for the index. |
| 99 | */ |
| 100 | tags: Record<string, string>; |
| 101 | }, |
| 102 | never, |
| 103 | Providers |
| 104 | > {} |
| 105 | |
| 106 | /** |
| 107 | * An Amazon Q Business index — the document store that data sources sync |
| 108 | * content into and retrievers query. |
| 109 | * |
| 110 | * :::caution |
| 111 | * An index bills hourly per provisioned capacity unit from the moment it |
| 112 | * becomes `ACTIVE`. Destroy test indexes promptly. |
| 113 | * ::: |
| 114 | * ### Creating Indexes |
| 115 | * **Example:** Starter Index |
| 116 | * ```typescript |
| 117 | * import * as AWS from "@alchemy.run/aws"; |
| 118 | * |
| 119 | * const index = yield* AWS.QBusiness.Index("Docs", { |
| 120 | * applicationId: app.applicationId, |
| 121 | * }); |
| 122 | * ``` |
| 123 | * |
| 124 | * **Example:** Enterprise Index with Extra Capacity |
| 125 | * ```typescript |
| 126 | * const index = yield* AWS.QBusiness.Index("Docs", { |
| 127 | * applicationId: app.applicationId, |
| 128 | * type: "ENTERPRISE", |
| 129 | * capacityConfiguration: { units: 2 }, |
| 130 | * }); |
| 131 | * ``` |
| 132 | * |
| 133 | * @resource |
| 134 | */ |
| 135 | export const Index = Resource<Index>("AWS.QBusiness.Index"); |
| 136 | |
| 137 | const createDisplayName = (id: string, props: { displayName?: string | undefined }) => |
| 138 | props.displayName |
| 139 | ? Effect.succeed(props.displayName) |
| 140 | : createPhysicalName({ id, maxLength: 100 }); |
| 141 | |
| 142 | const fetchTags = Effect.fn(function* (arn: string) { |
| 143 | const response = yield* qbusiness |
| 144 | .listTagsForResource({ resourceARN: arn }) |
| 145 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 146 | return Object.fromEntries((response?.tags ?? []).map((tag) => [tag.key, tag.value])); |
| 147 | }); |
| 148 | |
| 149 | interface IndexState { |
| 150 | attrs: Index["Attributes"]; |
| 151 | described: qbusiness.GetIndexResponse; |
| 152 | } |
| 153 | |
| 154 | const readIndexById = Effect.fn(function* (applicationId: string, indexId: string) { |
| 155 | const described = yield* qbusiness |
| 156 | .getIndex({ applicationId, indexId }) |
| 157 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 158 | if (!described || described.status === "DELETING") return undefined; |
| 159 | const arn = described.indexArn; |
| 160 | if (arn === undefined) return undefined; |
| 161 | const state: IndexState = { |
| 162 | described, |
| 163 | attrs: { |
| 164 | indexId: described.indexId ?? indexId, |
| 165 | applicationId: described.applicationId ?? applicationId, |
| 166 | indexArn: arn, |
| 167 | displayName: described.displayName ?? "", |
| 168 | type: described.type, |
| 169 | status: described.status, |
| 170 | tags: yield* fetchTags(arn), |
| 171 | }, |
| 172 | }; |
| 173 | return state; |
| 174 | }); |
| 175 | |
| 176 | const findIndexByName = Effect.fn(function* (applicationId: string, displayName: string) { |
| 177 | const summaries = yield* qbusiness.listIndices.pages({ applicationId }).pipe( |
| 178 | EffectStream.runCollect, |
| 179 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.indices ?? [])), |
| 180 | // The parent application may itself be gone. |
| 181 | Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([] as qbusiness.Index[])), |
| 182 | ); |
| 183 | const match = summaries.find( |
| 184 | (summary) => summary.displayName === displayName && summary.status !== "DELETING", |
| 185 | ); |
| 186 | if (!match?.indexId) return undefined; |
| 187 | return yield* readIndexById(applicationId, match.indexId); |
| 188 | }); |
| 189 | |
| 190 | /** |
| 191 | * An index still transitioning toward the awaited status — retried by |
| 192 | * {@link waitForIndexStatus}'s bounded schedule. |
| 193 | */ |
| 194 | class IndexNotReady extends Data.TaggedError("QBusinessIndexNotReady")<{ |
| 195 | readonly indexId: string; |
| 196 | readonly status: string | undefined; |
| 197 | }> {} |
| 198 | |
| 199 | /** |
| 200 | * An index whose asynchronous provisioning converged to the terminal |
| 201 | * `FAILED` status. |
| 202 | */ |
| 203 | export class IndexProvisioningFailed extends Data.TaggedError("QBusinessIndexProvisioningFailed")<{ |
| 204 | readonly indexId: string; |
| 205 | readonly message: string | undefined; |
| 206 | }> {} |
| 207 | |
| 208 | // Explicitly-typed retry wrapper — an inline `Effect.retry` in provider |
| 209 | // lifecycle code leaks `Retry.Return`'s conditional type into declaration |
| 210 | // emit and widens the provider layer to `unknown` for every consumer of |
| 211 | // `AWS.providers()`. |
| 212 | const retryWhileNotReady = <A, E extends { readonly _tag: string }, R>( |
| 213 | self: Effect.Effect<A, E, R>, |
| 214 | ): Effect.Effect<A, E, R> => |
| 215 | Effect.retry(self, { |
| 216 | while: (e) => e._tag === "QBusinessIndexNotReady", |
| 217 | // Index provisioning takes several minutes; poll every 15s up to ~30 min. |
| 218 | schedule: Schedule.max([Schedule.spaced("15 seconds"), Schedule.recurs(120)]), |
| 219 | }); |
| 220 | |
| 221 | const waitForIndexStatus = (applicationId: string, indexId: string, target: "ACTIVE" | "DELETED") => |
| 222 | retryWhileNotReady( |
| 223 | Effect.gen(function* () { |
| 224 | const described = yield* qbusiness |
| 225 | .getIndex({ applicationId, indexId }) |
| 226 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 227 | if (target === "DELETED") { |
| 228 | if (described === undefined) return; |
| 229 | return yield* new IndexNotReady({ indexId, status: described.status }); |
| 230 | } |
| 231 | if (described?.status === "ACTIVE") return; |
| 232 | if (described?.status === "FAILED") { |
| 233 | return yield* new IndexProvisioningFailed({ |
| 234 | indexId, |
| 235 | message: described.error?.errorMessage, |
| 236 | }); |
| 237 | } |
| 238 | return yield* new IndexNotReady({ indexId, status: described?.status }); |
| 239 | }), |
| 240 | ); |
| 241 | |
| 242 | export const IndexProvider = () => |
| 243 | Provider.effect( |
| 244 | Index, |
| 245 | Effect.gen(function* () { |
| 246 | return { |
| 247 | stables: ["indexId", "applicationId", "indexArn"], |
| 248 | // Keyed by a parent application; cannot be enumerated account-wide |
| 249 | // without iterating every application — treated as a sub-resource per |
| 250 | // the factory list() convention. |
| 251 | list: () => Effect.succeed([]), |
| 252 | read: Effect.fn(function* ({ id, olds, output }) { |
| 253 | const applicationId = output?.applicationId ?? olds?.applicationId; |
| 254 | if (applicationId === undefined) return undefined; |
| 255 | const state = output?.indexId |
| 256 | ? yield* readIndexById(applicationId, output.indexId) |
| 257 | : yield* findIndexByName(applicationId, yield* createDisplayName(id, olds ?? {})); |
| 258 | if (!state) return undefined; |
| 259 | return (yield* hasAlchemyTags(id, state.attrs.tags as Tags)) |
| 260 | ? state.attrs |
| 261 | : Unowned(state.attrs); |
| 262 | }), |
| 263 | diff: Effect.fn(function* ({ news, olds }) { |
| 264 | if (!isResolved(news)) return; |
| 265 | if (olds === undefined) return; |
| 266 | // The parent application and index tier are fixed at creation. |
| 267 | if ( |
| 268 | olds.applicationId !== news.applicationId || |
| 269 | (olds.type ?? "STARTER") !== (news.type ?? "STARTER") |
| 270 | ) { |
| 271 | return { action: "replace" } as const; |
| 272 | } |
| 273 | }), |
| 274 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 275 | if (!news) { |
| 276 | return yield* new QBusinessSearchIndexInvalidProps({ |
| 277 | message: "QBusiness Index requires props", |
| 278 | }); |
| 279 | } |
| 280 | const applicationId = news.applicationId; |
| 281 | const displayName = yield* createDisplayName(id, news); |
| 282 | const internalTags = yield* createInternalTags(id); |
| 283 | const desiredTags = { ...internalTags, ...news.tags }; |
| 284 | |
| 285 | // Observe — prefer the cached id; fall back to a name lookup so a |
| 286 | // create whose state failed to persist is adopted, not duplicated. |
| 287 | let state = output?.indexId |
| 288 | ? yield* readIndexById(applicationId, output.indexId) |
| 289 | : yield* findIndexByName(applicationId, displayName); |
| 290 | |
| 291 | // Ensure — create if missing, then wait for ACTIVE. |
| 292 | if (state === undefined) { |
| 293 | const created = yield* qbusiness.createIndex({ |
| 294 | applicationId, |
| 295 | displayName, |
| 296 | description: news.description, |
| 297 | type: news.type, |
| 298 | capacityConfiguration: news.capacityConfiguration, |
| 299 | tags: Object.entries(desiredTags).map(([key, value]) => ({ |
| 300 | key, |
| 301 | value, |
| 302 | })), |
| 303 | }); |
| 304 | if (!created.indexId) { |
| 305 | return yield* new QBusinessSearchIndexUnexpectedResponse({ |
| 306 | message: `CreateIndex for '${displayName}' returned no indexId`, |
| 307 | }); |
| 308 | } |
| 309 | yield* session.note(`Creating index ${displayName} (${created.indexId})...`); |
| 310 | yield* waitForIndexStatus(applicationId, created.indexId, "ACTIVE"); |
| 311 | state = yield* readIndexById(applicationId, created.indexId); |
| 312 | if (state === undefined) { |
| 313 | return yield* new QBusinessSearchIndexUnexpectedResponse({ |
| 314 | message: `failed to read created index ${displayName}`, |
| 315 | }); |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | // Sync mutable settings via UpdateIndex — only when drifted. |
| 320 | const described = state.described; |
| 321 | const desiredUnits = news.capacityConfiguration?.units; |
| 322 | const needsUpdate = |
| 323 | displayName !== described.displayName || |
| 324 | (news.description ?? "") !== (described.description ?? "") || |
| 325 | (desiredUnits !== undefined && |
| 326 | desiredUnits !== described.capacityConfiguration?.units) || |
| 327 | news.documentAttributeConfigurations !== undefined; |
| 328 | if (needsUpdate) { |
| 329 | yield* qbusiness.updateIndex({ |
| 330 | applicationId, |
| 331 | indexId: state.attrs.indexId, |
| 332 | displayName, |
| 333 | description: news.description, |
| 334 | capacityConfiguration: news.capacityConfiguration, |
| 335 | documentAttributeConfigurations: news.documentAttributeConfigurations, |
| 336 | }); |
| 337 | yield* waitForIndexStatus(applicationId, state.attrs.indexId, "ACTIVE"); |
| 338 | yield* session.note(`Updated index ${displayName}`); |
| 339 | } |
| 340 | |
| 341 | // Sync tags — diff against observed cloud tags. |
| 342 | const { removed, upsert } = diffTags(state.attrs.tags, desiredTags); |
| 343 | if (removed.length > 0) { |
| 344 | yield* qbusiness.untagResource({ |
| 345 | resourceARN: state.attrs.indexArn, |
| 346 | tagKeys: removed, |
| 347 | }); |
| 348 | } |
| 349 | if (upsert.length > 0) { |
| 350 | yield* qbusiness.tagResource({ |
| 351 | resourceARN: state.attrs.indexArn, |
| 352 | tags: upsert.map(({ Key, Value }) => ({ |
| 353 | key: Key, |
| 354 | value: Value, |
| 355 | })), |
| 356 | }); |
| 357 | } |
| 358 | |
| 359 | yield* session.note(state.attrs.indexArn); |
| 360 | |
| 361 | const final = yield* readIndexById(applicationId, state.attrs.indexId); |
| 362 | if (!final) { |
| 363 | return yield* new QBusinessSearchIndexUnexpectedResponse({ |
| 364 | message: `failed to read reconciled index ${displayName}`, |
| 365 | }); |
| 366 | } |
| 367 | return final.attrs; |
| 368 | }), |
| 369 | delete: Effect.fn(function* ({ output }) { |
| 370 | yield* qbusiness |
| 371 | .deleteIndex({ |
| 372 | applicationId: output.applicationId, |
| 373 | indexId: output.indexId, |
| 374 | }) |
| 375 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 376 | yield* waitForIndexStatus(output.applicationId, output.indexId, "DELETED"); |
| 377 | }), |
| 378 | }; |
| 379 | }), |
| 380 | ); |