The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as appsync from "@distilled.cloud/aws/appsync"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { deepEqual, 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, hasAlchemyTags } from "alchemy/Tags"; |
| 8 | import { toWireMillis, toWireSeconds } from "alchemy/Util/Duration"; |
| 9 | import * as Data from "effect/Data"; |
| 10 | import type * as Duration from "effect/Duration"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as Schedule from "effect/Schedule"; |
| 13 | import * as Stream from "effect/Stream"; |
| 14 | import { AWSEnvironment } from "../Environment.ts"; |
| 15 | import type { Providers } from "../Providers.ts"; |
| 16 | import { retryConcurrentModification, syncAppSyncTags, tagRecord } from "./common.ts"; |
| 17 | |
| 18 | /** |
| 19 | * The primary authentication mode of a GraphQL API. |
| 20 | */ |
| 21 | export type AuthenticationType = |
| 22 | | "API_KEY" |
| 23 | | "AWS_IAM" |
| 24 | | "AMAZON_COGNITO_USER_POOLS" |
| 25 | | "OPENID_CONNECT" |
| 26 | | "AWS_LAMBDA"; |
| 27 | |
| 28 | export interface UserPoolAuthConfig { |
| 29 | /** The Cognito user pool ID. */ |
| 30 | userPoolId: string; |
| 31 | /** |
| 32 | * The region the user pool lives in. |
| 33 | * @default the ambient AWS region |
| 34 | */ |
| 35 | awsRegion?: string; |
| 36 | /** |
| 37 | * What to do for requests that don't match an `appIdClientRegex`. |
| 38 | * @default "ALLOW" |
| 39 | */ |
| 40 | defaultAction?: "ALLOW" | "DENY"; |
| 41 | /** Regular expression matching allowed user pool app client IDs. */ |
| 42 | appIdClientRegex?: string; |
| 43 | } |
| 44 | |
| 45 | export interface LambdaAuthorizerConfig { |
| 46 | /** |
| 47 | * The ARN of the Lambda authorizer function (or an alias/version |
| 48 | * qualified ARN). AppSync must be allowed to invoke it — attach a |
| 49 | * `Lambda.Permission` with principal `appsync.amazonaws.com`. |
| 50 | */ |
| 51 | authorizerUri: string; |
| 52 | /** |
| 53 | * How long AppSync caches an authorizer response, e.g. `"5 minutes"` or |
| 54 | * `Duration.seconds(300)` (0 disables caching, max 1 hour). Sent to AWS |
| 55 | * as whole seconds. |
| 56 | * @default "300 seconds" |
| 57 | */ |
| 58 | authorizerResultTtl?: Duration.Input; |
| 59 | /** Regular expression the authorization token must match before invoking. */ |
| 60 | identityValidationExpression?: string; |
| 61 | } |
| 62 | |
| 63 | export interface OpenIDConnectAuthConfig { |
| 64 | /** The OIDC issuer URL. */ |
| 65 | issuer: string; |
| 66 | /** The client identifier the token audience must match. */ |
| 67 | clientId?: string; |
| 68 | /** How long a token is valid after `iat`, e.g. `"1 hour"`. */ |
| 69 | iatTTL?: Duration.Input; |
| 70 | /** How long a token is valid after `auth_time`, e.g. `"1 hour"`. */ |
| 71 | authTTL?: Duration.Input; |
| 72 | } |
| 73 | |
| 74 | export interface AdditionalAuthProvider { |
| 75 | /** The authentication mode of this additional provider. */ |
| 76 | authenticationType: AuthenticationType; |
| 77 | /** Cognito user pool config (for `AMAZON_COGNITO_USER_POOLS`). */ |
| 78 | userPoolConfig?: Omit<UserPoolAuthConfig, "defaultAction">; |
| 79 | /** OIDC config (for `OPENID_CONNECT`). */ |
| 80 | openIDConnectConfig?: OpenIDConnectAuthConfig; |
| 81 | /** Lambda authorizer config (for `AWS_LAMBDA`). */ |
| 82 | lambdaAuthorizerConfig?: LambdaAuthorizerConfig; |
| 83 | } |
| 84 | |
| 85 | export interface ApiCacheConfig { |
| 86 | /** |
| 87 | * The cache instance type, e.g. `"SMALL"`, `"MEDIUM"`, `"LARGE"` (or the |
| 88 | * legacy `T2_SMALL`-style types). |
| 89 | */ |
| 90 | type: appsync.ApiCacheType; |
| 91 | /** |
| 92 | * Caching behavior: `"FULL_REQUEST_CACHING"` caches every resolver, |
| 93 | * `"PER_RESOLVER_CACHING"` caches only resolvers that opt in. |
| 94 | */ |
| 95 | behavior: appsync.ApiCachingBehavior; |
| 96 | /** TTL for cache entries, e.g. `"60 seconds"` (1 second–1 hour). */ |
| 97 | ttl: Duration.Input; |
| 98 | /** Encrypt cache entries in transit. Immutable after creation. */ |
| 99 | transitEncryptionEnabled?: boolean; |
| 100 | /** Encrypt cache entries at rest. Immutable after creation. */ |
| 101 | atRestEncryptionEnabled?: boolean; |
| 102 | /** |
| 103 | * Whether cache health metrics are emitted to CloudWatch. |
| 104 | * @default "DISABLED" |
| 105 | */ |
| 106 | healthMetricsConfig?: appsync.CacheHealthMetricsConfig; |
| 107 | } |
| 108 | |
| 109 | export interface GraphqlApiProps { |
| 110 | /** |
| 111 | * Name of the API. If omitted, a deterministic physical name is |
| 112 | * generated from the app, stage, and logical ID. Names are mutable. |
| 113 | */ |
| 114 | name?: string; |
| 115 | /** |
| 116 | * The primary authentication mode. |
| 117 | * @default "API_KEY" |
| 118 | */ |
| 119 | authenticationType?: AuthenticationType; |
| 120 | /** |
| 121 | * The GraphQL schema (SDL string). Applied via `startSchemaCreation` |
| 122 | * and awaited until the schema is active. Resolvers can only be |
| 123 | * attached to types/fields that exist in this schema. |
| 124 | */ |
| 125 | schema?: string; |
| 126 | /** |
| 127 | * Cognito user pool config — required when `authenticationType` is |
| 128 | * `AMAZON_COGNITO_USER_POOLS`. |
| 129 | */ |
| 130 | userPoolConfig?: UserPoolAuthConfig; |
| 131 | /** |
| 132 | * OIDC config — required when `authenticationType` is `OPENID_CONNECT`. |
| 133 | */ |
| 134 | openIDConnectConfig?: OpenIDConnectAuthConfig; |
| 135 | /** |
| 136 | * Lambda authorizer config — required when `authenticationType` is |
| 137 | * `AWS_LAMBDA`. |
| 138 | */ |
| 139 | lambdaAuthorizerConfig?: LambdaAuthorizerConfig; |
| 140 | /** |
| 141 | * Additional authentication modes beyond the primary one. |
| 142 | */ |
| 143 | additionalAuthenticationProviders?: AdditionalAuthProvider[]; |
| 144 | /** |
| 145 | * CloudWatch Logs configuration. Requires a role AppSync can assume |
| 146 | * with log-delivery permissions. |
| 147 | */ |
| 148 | logConfig?: appsync.LogConfig; |
| 149 | /** |
| 150 | * Whether AWS X-Ray tracing is enabled. |
| 151 | * @default false |
| 152 | */ |
| 153 | xrayEnabled?: boolean; |
| 154 | /** |
| 155 | * `GLOBAL` (public endpoint) or `PRIVATE` (VPC-only). Immutable — |
| 156 | * changing it triggers a replacement. |
| 157 | * @default "GLOBAL" |
| 158 | */ |
| 159 | visibility?: "GLOBAL" | "PRIVATE"; |
| 160 | /** |
| 161 | * `GRAPHQL` (standard) or `MERGED` (merged API). Immutable — changing |
| 162 | * it triggers a replacement. |
| 163 | * @default "GRAPHQL" |
| 164 | */ |
| 165 | apiType?: "GRAPHQL" | "MERGED"; |
| 166 | /** |
| 167 | * Whether introspection queries are allowed. |
| 168 | * @default "ENABLED" |
| 169 | */ |
| 170 | introspectionConfig?: "ENABLED" | "DISABLED"; |
| 171 | /** Maximum depth a query is allowed to reach (0 disables the limit). */ |
| 172 | queryDepthLimit?: number; |
| 173 | /** Maximum number of resolvers a query may invoke (0 disables the limit). */ |
| 174 | resolverCountLimit?: number; |
| 175 | /** |
| 176 | * Server-side API cache. **Cache instances bill hourly** while |
| 177 | * provisioned; omit to run without a cache. Provisioning is |
| 178 | * asynchronous (~10–20 minutes to reach `AVAILABLE`); reconcile does |
| 179 | * not wait for it. |
| 180 | */ |
| 181 | cache?: ApiCacheConfig; |
| 182 | /** |
| 183 | * Environment variables exposed to `APPSYNC_JS` resolver and function |
| 184 | * code via `ctx.env`. The whole map is replaced on each change; pass |
| 185 | * `{}` to clear all variables. When omitted, environment variables are |
| 186 | * left unmanaged. |
| 187 | */ |
| 188 | environmentVariables?: Record<string, string>; |
| 189 | /** |
| 190 | * Tags to apply to the API. Merged with internal Alchemy tags. |
| 191 | */ |
| 192 | tags?: Record<string, string>; |
| 193 | } |
| 194 | |
| 195 | export interface GraphqlApi extends Resource< |
| 196 | "AWS.AppSync.GraphqlApi", |
| 197 | GraphqlApiProps, |
| 198 | { |
| 199 | /** The unique API ID. */ |
| 200 | apiId: string; |
| 201 | /** The API's ARN. */ |
| 202 | apiArn: string; |
| 203 | /** The API name. */ |
| 204 | name: string; |
| 205 | /** The GraphQL endpoint (`https://{id}.appsync-api.{region}.amazonaws.com/graphql`). */ |
| 206 | graphqlUrl: string; |
| 207 | /** The real-time (WebSocket subscriptions) endpoint. */ |
| 208 | realtimeUrl: string | undefined; |
| 209 | /** The primary authentication mode. */ |
| 210 | authenticationType: AuthenticationType; |
| 211 | }, |
| 212 | never, |
| 213 | Providers |
| 214 | > {} |
| 215 | |
| 216 | /** |
| 217 | * An AWS AppSync GraphQL API. |
| 218 | * |
| 219 | * Owns the API, its SDL schema (applied via `startSchemaCreation` and |
| 220 | * awaited until active), its authentication modes, and an optional |
| 221 | * server-side cache. Pair with {@link DataSource}, {@link Resolver}, |
| 222 | * and {@link ApiKey} to serve GraphQL over Lambda or DynamoDB. |
| 223 | * ### Creating a GraphQL API |
| 224 | * **Example:** API-key authenticated API with a schema |
| 225 | * ```typescript |
| 226 | * import * as AppSync from "@alchemy.run/aws/AppSync"; |
| 227 | * |
| 228 | * const api = yield* AppSync.GraphqlApi("Api", { |
| 229 | * schema: ` |
| 230 | * type Query { hello: String! } |
| 231 | * schema { query: Query } |
| 232 | * `, |
| 233 | * }); |
| 234 | * const key = yield* AppSync.ApiKey("Key", { api }); |
| 235 | * ``` |
| 236 | * |
| 237 | * ### Authentication Modes |
| 238 | * **Example:** Lambda authorizer |
| 239 | * ```typescript |
| 240 | * const api = yield* AppSync.GraphqlApi("Api", { |
| 241 | * authenticationType: "AWS_LAMBDA", |
| 242 | * lambdaAuthorizerConfig: { authorizerUri: authorizer.functionArn }, |
| 243 | * schema, |
| 244 | * }); |
| 245 | * // AppSync must be allowed to invoke the authorizer: |
| 246 | * yield* AWS.Lambda.Permission("AppSyncInvoke", { |
| 247 | * functionName: authorizer.functionName, |
| 248 | * principal: "appsync.amazonaws.com", |
| 249 | * action: "lambda:InvokeFunction", |
| 250 | * sourceArn: api.apiArn, |
| 251 | * }); |
| 252 | * ``` |
| 253 | * |
| 254 | * **Example:** Cognito user pools as an additional auth mode |
| 255 | * ```typescript |
| 256 | * const api = yield* AppSync.GraphqlApi("Api", { |
| 257 | * authenticationType: "API_KEY", |
| 258 | * additionalAuthenticationProviders: [ |
| 259 | * { |
| 260 | * authenticationType: "AMAZON_COGNITO_USER_POOLS", |
| 261 | * userPoolConfig: { userPoolId: pool.userPoolId }, |
| 262 | * }, |
| 263 | * ], |
| 264 | * schema, |
| 265 | * }); |
| 266 | * ``` |
| 267 | * |
| 268 | * ### Caching |
| 269 | * **Example:** Full-request server-side cache (bills hourly!) |
| 270 | * ```typescript |
| 271 | * const api = yield* AppSync.GraphqlApi("Api", { |
| 272 | * schema, |
| 273 | * cache: { type: "SMALL", behavior: "FULL_REQUEST_CACHING", ttl: "60 seconds" }, |
| 274 | * }); |
| 275 | * ``` |
| 276 | * |
| 277 | * ### Environment Variables |
| 278 | * **Example:** Expose variables to resolver code via ctx.env |
| 279 | * ```typescript |
| 280 | * const api = yield* AppSync.GraphqlApi("Api", { |
| 281 | * schema, |
| 282 | * environmentVariables: { STAGE: "prod" }, |
| 283 | * }); |
| 284 | * // in APPSYNC_JS resolver code: |
| 285 | * // export function response(ctx) { return ctx.env.STAGE; } |
| 286 | * ``` |
| 287 | * |
| 288 | * @resource |
| 289 | */ |
| 290 | export const GraphqlApi = Resource<GraphqlApi>("AWS.AppSync.GraphqlApi"); |
| 291 | |
| 292 | /** Schema creation finished in the `FAILED` state. */ |
| 293 | export class SchemaCreationFailed extends Data.TaggedError("SchemaCreationFailed")<{ |
| 294 | readonly apiId: string; |
| 295 | readonly details: string | undefined; |
| 296 | }> {} |
| 297 | |
| 298 | /** Schema creation did not settle within the bounded polling window. */ |
| 299 | export class SchemaCreationTimedOut extends Data.TaggedError("SchemaCreationTimedOut")<{ |
| 300 | readonly apiId: string; |
| 301 | readonly status: string | undefined; |
| 302 | }> {} |
| 303 | |
| 304 | const toWireOidcConfig = ( |
| 305 | config: OpenIDConnectAuthConfig | undefined, |
| 306 | ): appsync.OpenIDConnectConfig | undefined => |
| 307 | config === undefined |
| 308 | ? undefined |
| 309 | : { |
| 310 | issuer: config.issuer, |
| 311 | clientId: config.clientId, |
| 312 | // The AppSync API expresses both token TTLs in milliseconds. |
| 313 | iatTTL: toWireMillis(config.iatTTL), |
| 314 | authTTL: toWireMillis(config.authTTL), |
| 315 | }; |
| 316 | |
| 317 | const toWireLambdaAuthorizerConfig = ( |
| 318 | config: LambdaAuthorizerConfig | undefined, |
| 319 | ): appsync.LambdaAuthorizerConfig | undefined => |
| 320 | config === undefined |
| 321 | ? undefined |
| 322 | : { |
| 323 | authorizerUri: config.authorizerUri, |
| 324 | // The wire field carries the unit; the prop is a Duration.Input. |
| 325 | authorizerResultTtlInSeconds: toWireSeconds(config.authorizerResultTtl), |
| 326 | identityValidationExpression: config.identityValidationExpression, |
| 327 | }; |
| 328 | |
| 329 | const toWireUserPoolConfig = ( |
| 330 | config: UserPoolAuthConfig | undefined, |
| 331 | region: string, |
| 332 | ): appsync.UserPoolConfig | undefined => |
| 333 | config === undefined |
| 334 | ? undefined |
| 335 | : { |
| 336 | userPoolId: config.userPoolId, |
| 337 | awsRegion: config.awsRegion ?? region, |
| 338 | defaultAction: config.defaultAction ?? "ALLOW", |
| 339 | appIdClientRegex: config.appIdClientRegex, |
| 340 | }; |
| 341 | |
| 342 | const toWireAdditionalProviders = ( |
| 343 | providers: AdditionalAuthProvider[] | undefined, |
| 344 | region: string, |
| 345 | ): appsync.AdditionalAuthenticationProvider[] | undefined => |
| 346 | providers === undefined |
| 347 | ? undefined |
| 348 | : providers.map((provider) => ({ |
| 349 | authenticationType: provider.authenticationType, |
| 350 | userPoolConfig: |
| 351 | provider.userPoolConfig === undefined |
| 352 | ? undefined |
| 353 | : { |
| 354 | userPoolId: provider.userPoolConfig.userPoolId, |
| 355 | awsRegion: provider.userPoolConfig.awsRegion ?? region, |
| 356 | appIdClientRegex: provider.userPoolConfig.appIdClientRegex, |
| 357 | }, |
| 358 | openIDConnectConfig: toWireOidcConfig(provider.openIDConnectConfig), |
| 359 | lambdaAuthorizerConfig: toWireLambdaAuthorizerConfig(provider.lambdaAuthorizerConfig), |
| 360 | })); |
| 361 | |
| 362 | /** |
| 363 | * Canonicalize the wire-facing auth/limit surface of an API so observed |
| 364 | * and desired states compare structurally (dropping undefined members). |
| 365 | */ |
| 366 | const authSurface = (api: { |
| 367 | name?: string; |
| 368 | authenticationType?: string; |
| 369 | userPoolConfig?: appsync.UserPoolConfig; |
| 370 | openIDConnectConfig?: appsync.OpenIDConnectConfig; |
| 371 | lambdaAuthorizerConfig?: appsync.LambdaAuthorizerConfig; |
| 372 | additionalAuthenticationProviders?: appsync.AdditionalAuthenticationProvider[]; |
| 373 | xrayEnabled?: boolean; |
| 374 | introspectionConfig?: string; |
| 375 | queryDepthLimit?: number; |
| 376 | resolverCountLimit?: number; |
| 377 | logConfig?: appsync.LogConfig; |
| 378 | }) => |
| 379 | JSON.parse( |
| 380 | JSON.stringify({ |
| 381 | name: api.name, |
| 382 | authenticationType: api.authenticationType, |
| 383 | userPoolConfig: api.userPoolConfig, |
| 384 | openIDConnectConfig: api.openIDConnectConfig, |
| 385 | lambdaAuthorizerConfig: { |
| 386 | ...api.lambdaAuthorizerConfig, |
| 387 | // AWS normalizes the TTL default (300) into the response |
| 388 | authorizerResultTtlInSeconds: |
| 389 | api.lambdaAuthorizerConfig === undefined |
| 390 | ? undefined |
| 391 | : (api.lambdaAuthorizerConfig.authorizerResultTtlInSeconds ?? 300), |
| 392 | }, |
| 393 | additionalAuthenticationProviders: api.additionalAuthenticationProviders?.map((p) => ({ |
| 394 | ...p, |
| 395 | lambdaAuthorizerConfig: |
| 396 | p.lambdaAuthorizerConfig === undefined |
| 397 | ? undefined |
| 398 | : { |
| 399 | ...p.lambdaAuthorizerConfig, |
| 400 | authorizerResultTtlInSeconds: |
| 401 | p.lambdaAuthorizerConfig.authorizerResultTtlInSeconds ?? 300, |
| 402 | }, |
| 403 | })), |
| 404 | xrayEnabled: api.xrayEnabled ?? false, |
| 405 | introspectionConfig: api.introspectionConfig ?? "ENABLED", |
| 406 | queryDepthLimit: api.queryDepthLimit ?? 0, |
| 407 | resolverCountLimit: api.resolverCountLimit ?? 0, |
| 408 | logConfig: api.logConfig, |
| 409 | }), |
| 410 | ); |
| 411 | |
| 412 | export const GraphqlApiProvider = () => |
| 413 | Provider.effect( |
| 414 | GraphqlApi, |
| 415 | Effect.gen(function* () { |
| 416 | const createName = Effect.fn(function* (id: string, props: Pick<GraphqlApiProps, "name">) { |
| 417 | return props.name ?? (yield* createPhysicalName({ id, maxLength: 64 })); |
| 418 | }); |
| 419 | |
| 420 | const getApiSafe = (apiId: string) => |
| 421 | appsync.getGraphqlApi({ apiId }).pipe( |
| 422 | Effect.map((response) => response.graphqlApi), |
| 423 | Effect.catchTag("NotFoundException", () => Effect.undefined), |
| 424 | ); |
| 425 | |
| 426 | /** Find an API by exact name (fallback when no apiId is cached). */ |
| 427 | const findApiByName = Effect.fn(function* (name: string) { |
| 428 | const pages = yield* appsync.listGraphqlApis.pages({}).pipe(Stream.runCollect); |
| 429 | return Array.from(pages) |
| 430 | .flatMap((page) => page.graphqlApis ?? []) |
| 431 | .find((api) => api.name === name); |
| 432 | }); |
| 433 | |
| 434 | const toAttributes = (api: appsync.GraphqlApi): GraphqlApi["Attributes"] => ({ |
| 435 | apiId: api.apiId!, |
| 436 | apiArn: api.arn!, |
| 437 | name: api.name!, |
| 438 | graphqlUrl: api.uris?.GRAPHQL ?? "", |
| 439 | realtimeUrl: api.uris?.REALTIME, |
| 440 | authenticationType: api.authenticationType as AuthenticationType, |
| 441 | }); |
| 442 | |
| 443 | /** |
| 444 | * Apply the SDL schema and poll until the creation settles. |
| 445 | * `startSchemaCreation` is asynchronous; polling is bounded (~60s — |
| 446 | * schema creation is normally seconds). |
| 447 | */ |
| 448 | const applySchema = Effect.fn(function* (apiId: string, schema: string) { |
| 449 | const definition = yield* Effect.sync(() => new TextEncoder().encode(schema)); |
| 450 | yield* retryConcurrentModification(appsync.startSchemaCreation({ apiId, definition })); |
| 451 | const final = yield* appsync.getSchemaCreationStatus({ apiId }).pipe( |
| 452 | Effect.repeat({ |
| 453 | schedule: Schedule.fixed("1 second"), |
| 454 | until: (response) => response.status !== "PROCESSING", |
| 455 | times: 60, |
| 456 | }), |
| 457 | ); |
| 458 | if (final.status === "FAILED") { |
| 459 | return yield* new SchemaCreationFailed({ |
| 460 | apiId, |
| 461 | details: final.details, |
| 462 | }); |
| 463 | } |
| 464 | if (final.status === "PROCESSING") { |
| 465 | return yield* new SchemaCreationTimedOut({ |
| 466 | apiId, |
| 467 | status: final.status, |
| 468 | }); |
| 469 | } |
| 470 | }); |
| 471 | |
| 472 | /** |
| 473 | * Converge the optional server-side cache: create when desired and |
| 474 | * missing, update on drift, delete when no longer desired. Creation |
| 475 | * is asynchronous and NOT awaited (10–20 minutes to AVAILABLE). |
| 476 | */ |
| 477 | const syncCache = Effect.fn(function* (apiId: string, desired: ApiCacheConfig | undefined) { |
| 478 | const observed = yield* appsync.getApiCache({ apiId }).pipe( |
| 479 | Effect.map((response) => response.apiCache), |
| 480 | Effect.catchTag("NotFoundException", () => Effect.undefined), |
| 481 | ); |
| 482 | if (desired === undefined) { |
| 483 | if (observed !== undefined) { |
| 484 | yield* retryConcurrentModification( |
| 485 | appsync |
| 486 | .deleteApiCache({ apiId }) |
| 487 | .pipe(Effect.catchTag("NotFoundException", () => Effect.void)), |
| 488 | ); |
| 489 | } |
| 490 | return; |
| 491 | } |
| 492 | // The wire TTL is whole seconds. |
| 493 | const desiredTtl = toWireSeconds(desired.ttl)!; |
| 494 | if (observed === undefined) { |
| 495 | yield* retryConcurrentModification( |
| 496 | appsync.createApiCache({ |
| 497 | apiId, |
| 498 | type: desired.type, |
| 499 | apiCachingBehavior: desired.behavior, |
| 500 | ttl: desiredTtl, |
| 501 | transitEncryptionEnabled: desired.transitEncryptionEnabled, |
| 502 | atRestEncryptionEnabled: desired.atRestEncryptionEnabled, |
| 503 | healthMetricsConfig: desired.healthMetricsConfig, |
| 504 | }), |
| 505 | ); |
| 506 | return; |
| 507 | } |
| 508 | const drifted = |
| 509 | observed.type !== desired.type || |
| 510 | observed.apiCachingBehavior !== desired.behavior || |
| 511 | observed.ttl !== desiredTtl || |
| 512 | (desired.healthMetricsConfig !== undefined && |
| 513 | observed.healthMetricsConfig !== desired.healthMetricsConfig); |
| 514 | if (drifted) { |
| 515 | yield* retryConcurrentModification( |
| 516 | appsync.updateApiCache({ |
| 517 | apiId, |
| 518 | type: desired.type, |
| 519 | apiCachingBehavior: desired.behavior, |
| 520 | ttl: desiredTtl, |
| 521 | healthMetricsConfig: desired.healthMetricsConfig, |
| 522 | }), |
| 523 | ); |
| 524 | } |
| 525 | }); |
| 526 | |
| 527 | /** |
| 528 | * Converge resolver environment variables (`ctx.env`). The AWS API |
| 529 | * replaces the whole map on PUT, so a single drift-guarded call |
| 530 | * suffices. Skipped entirely when the prop is unmanaged. |
| 531 | */ |
| 532 | const syncEnvironmentVariables = Effect.fn(function* ( |
| 533 | apiId: string, |
| 534 | desired: Record<string, string> | undefined, |
| 535 | ) { |
| 536 | if (desired === undefined) return; |
| 537 | const observed = yield* appsync |
| 538 | .getGraphqlApiEnvironmentVariables({ apiId }) |
| 539 | .pipe(Effect.map((response) => response.environmentVariables ?? {})); |
| 540 | if (!deepEqual(tagRecord(observed), desired)) { |
| 541 | yield* retryConcurrentModification( |
| 542 | appsync.putGraphqlApiEnvironmentVariables({ |
| 543 | apiId, |
| 544 | environmentVariables: desired, |
| 545 | }), |
| 546 | ); |
| 547 | } |
| 548 | }); |
| 549 | |
| 550 | return GraphqlApi.Provider.of({ |
| 551 | stables: ["apiId", "apiArn", "graphqlUrl", "realtimeUrl"], |
| 552 | |
| 553 | list: () => |
| 554 | Effect.gen(function* () { |
| 555 | const pages = yield* appsync.listGraphqlApis.pages({}).pipe(Stream.runCollect); |
| 556 | return Array.from(pages) |
| 557 | .flatMap((page) => page.graphqlApis ?? []) |
| 558 | .filter((api) => api.apiId != null) |
| 559 | .map(toAttributes); |
| 560 | }), |
| 561 | |
| 562 | read: Effect.fn(function* ({ id, olds, output }) { |
| 563 | const api = |
| 564 | output?.apiId !== undefined |
| 565 | ? yield* getApiSafe(output.apiId) |
| 566 | : yield* findApiByName(yield* createName(id, olds ?? {})); |
| 567 | if (api?.apiId == null) return undefined; |
| 568 | const attrs = toAttributes(api); |
| 569 | const tags = tagRecord(api.tags); |
| 570 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 571 | }), |
| 572 | |
| 573 | diff: Effect.fn(function* ({ news, olds }) { |
| 574 | if (!isResolved(news)) return undefined; |
| 575 | if ( |
| 576 | (news.visibility ?? "GLOBAL") !== (olds.visibility ?? "GLOBAL") || |
| 577 | (news.apiType ?? "GRAPHQL") !== (olds.apiType ?? "GRAPHQL") |
| 578 | ) { |
| 579 | return { action: "replace" } as const; |
| 580 | } |
| 581 | // name/auth/schema/cache/limits/tags converge via update |
| 582 | }), |
| 583 | |
| 584 | reconcile: Effect.fn(function* ({ id, news, olds, output, session }) { |
| 585 | const { region } = yield* AWSEnvironment.current; |
| 586 | const name = news.name ?? (yield* createName(id, news)); |
| 587 | const internalTags = yield* createInternalTags(id); |
| 588 | const desiredTags = { ...news.tags, ...internalTags }; |
| 589 | const authenticationType = news.authenticationType ?? "API_KEY"; |
| 590 | |
| 591 | const desired = { |
| 592 | name, |
| 593 | authenticationType, |
| 594 | userPoolConfig: toWireUserPoolConfig(news.userPoolConfig, region), |
| 595 | openIDConnectConfig: toWireOidcConfig(news.openIDConnectConfig), |
| 596 | lambdaAuthorizerConfig: toWireLambdaAuthorizerConfig(news.lambdaAuthorizerConfig), |
| 597 | additionalAuthenticationProviders: toWireAdditionalProviders( |
| 598 | news.additionalAuthenticationProviders, |
| 599 | region, |
| 600 | ), |
| 601 | xrayEnabled: news.xrayEnabled, |
| 602 | introspectionConfig: news.introspectionConfig, |
| 603 | queryDepthLimit: news.queryDepthLimit, |
| 604 | resolverCountLimit: news.resolverCountLimit, |
| 605 | logConfig: news.logConfig, |
| 606 | }; |
| 607 | |
| 608 | // 1. OBSERVE — the cached apiId is only a hint; fall back to a |
| 609 | // name scan so interrupted deploys converge. |
| 610 | let observed = |
| 611 | output?.apiId !== undefined |
| 612 | ? yield* getApiSafe(output.apiId) |
| 613 | : yield* findApiByName(name); |
| 614 | |
| 615 | // 2. ENSURE |
| 616 | let justCreated = false; |
| 617 | if (observed?.apiId == null) { |
| 618 | const created = yield* retryConcurrentModification( |
| 619 | appsync.createGraphqlApi({ |
| 620 | ...desired, |
| 621 | visibility: news.visibility, |
| 622 | apiType: news.apiType, |
| 623 | tags: desiredTags, |
| 624 | }), |
| 625 | ); |
| 626 | observed = created.graphqlApi!; |
| 627 | justCreated = true; |
| 628 | yield* session.note(`Created GraphQL API ${observed.apiId}`); |
| 629 | } |
| 630 | const apiId = observed.apiId!; |
| 631 | |
| 632 | // 3. SYNC — one update call when the observed auth/limit surface |
| 633 | // drifted from the desired one. |
| 634 | if (!justCreated && !deepEqual(authSurface(observed), authSurface(desired))) { |
| 635 | const updated = yield* retryConcurrentModification( |
| 636 | appsync.updateGraphqlApi({ apiId, ...desired }), |
| 637 | ); |
| 638 | observed = updated.graphqlApi ?? observed; |
| 639 | yield* session.note(`Updated GraphQL API ${apiId}`); |
| 640 | } |
| 641 | |
| 642 | // 3b. SYNC SCHEMA — `startSchemaCreation` replaces the schema |
| 643 | // wholesale (idempotent). Apply on first provision, on |
| 644 | // adoption, and whenever the desired SDL changed; the |
| 645 | // previous props are only a hint to skip the no-op call. |
| 646 | if ( |
| 647 | news.schema !== undefined && |
| 648 | (justCreated || output === undefined || olds?.schema !== news.schema) |
| 649 | ) { |
| 650 | yield* applySchema(apiId, news.schema); |
| 651 | yield* session.note(`Applied schema to ${apiId}`); |
| 652 | } |
| 653 | |
| 654 | // 3c. SYNC CACHE |
| 655 | yield* syncCache(apiId, news.cache); |
| 656 | |
| 657 | // 3d. SYNC ENVIRONMENT VARIABLES (ctx.env in resolver code). |
| 658 | yield* syncEnvironmentVariables(apiId, news.environmentVariables); |
| 659 | |
| 660 | // 3e. SYNC TAGS — against OBSERVED cloud tags. |
| 661 | if (observed.arn !== undefined) { |
| 662 | yield* syncAppSyncTags({ |
| 663 | resourceArn: observed.arn, |
| 664 | oldTags: tagRecord(observed.tags), |
| 665 | newTags: desiredTags, |
| 666 | }); |
| 667 | } |
| 668 | |
| 669 | yield* session.note(apiId); |
| 670 | return toAttributes(observed); |
| 671 | }), |
| 672 | |
| 673 | delete: Effect.fn(function* ({ output }) { |
| 674 | yield* retryConcurrentModification( |
| 675 | appsync |
| 676 | .deleteGraphqlApi({ apiId: output.apiId }) |
| 677 | .pipe(Effect.catchTag("NotFoundException", () => Effect.void)), |
| 678 | ); |
| 679 | }), |
| 680 | }); |
| 681 | }), |
| 682 | ); |