The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as ag from "@distilled.cloud/aws/api-gateway"; |
| 2 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 3 | import type { Input } from "alchemy/Input"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { createInternalTags, tagRecord } from "alchemy/Tags"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { AWSEnvironment } from "../Environment.ts"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | import { deleteRestApiAndWait, restApiArn, retryOnApiStatusUpdating, syncTags } from "./common.ts"; |
| 13 | |
| 14 | export interface RestApiProps { |
| 15 | /** |
| 16 | * Name of the REST API. |
| 17 | * |
| 18 | * If omitted, Alchemy generates a deterministic physical name. |
| 19 | */ |
| 20 | name?: string; |
| 21 | /** Description of the REST API. */ |
| 22 | description?: string; |
| 23 | /** A version identifier for the API. */ |
| 24 | version?: string; |
| 25 | /** ID of an existing REST API to clone the new API from. */ |
| 26 | cloneFrom?: string; |
| 27 | /** Media types treated as binary (e.g. `image/png`; a star-slash-star entry covers all types). */ |
| 28 | binaryMediaTypes?: string[]; |
| 29 | /** Minimum response size in bytes that triggers compression (0-10485760); unset disables compression. */ |
| 30 | minimumCompressionSize?: number; |
| 31 | /** |
| 32 | * Where API Gateway reads the API key on requests (`HEADER` or `AUTHORIZER`). |
| 33 | * @default "HEADER" |
| 34 | */ |
| 35 | apiKeySource?: ag.ApiKeySourceType; |
| 36 | /** Endpoint type for the API (EDGE, REGIONAL, or PRIVATE). */ |
| 37 | endpointConfiguration?: ag.EndpointConfiguration; |
| 38 | /** Resource policy document as a JSON string. */ |
| 39 | policy?: string; |
| 40 | /** |
| 41 | * Disable the default `execute-api` endpoint (serve only via custom domains). |
| 42 | * @default false |
| 43 | */ |
| 44 | disableExecuteApiEndpoint?: boolean; |
| 45 | /** Minimum TLS version served by the API endpoint. */ |
| 46 | securityPolicy?: ag.SecurityPolicy; |
| 47 | /** Access mode of the API endpoint. */ |
| 48 | endpointAccessMode?: ag.EndpointAccessMode; |
| 49 | /** User-defined tags (Alchemy internal tags are merged automatically). */ |
| 50 | tags?: Record<string, string>; |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Structured metadata a child resource attaches to its RestApi via `.bind`. |
| 55 | * |
| 56 | * These bindings are the mechanism by which Methods, Resources, Authorizers, |
| 57 | * and other REST-API-scoped children declare a reverse dependency on the API |
| 58 | * itself. The presence of any such binding is what forces `RestApi.create` to |
| 59 | * run *after* every child has been created — which is exactly the ordering |
| 60 | * CloudFormation asks users to write manually via `DependsOn`. |
| 61 | * |
| 62 | * Consumers should not construct these directly; the child resource |
| 63 | * constructors (e.g. `Method`, `Resource`) handle binding on behalf of the |
| 64 | * user. |
| 65 | */ |
| 66 | export type RestApiBinding = |
| 67 | | { |
| 68 | kind: "method"; |
| 69 | methodId: Input<string>; |
| 70 | restApiId: Input<string>; |
| 71 | resourceId: Input<string>; |
| 72 | httpMethod: Input<string>; |
| 73 | } |
| 74 | | { |
| 75 | kind: "resource"; |
| 76 | resourceId: Input<string>; |
| 77 | parentId: Input<string>; |
| 78 | pathPart: Input<string>; |
| 79 | } |
| 80 | | { |
| 81 | kind: "authorizer"; |
| 82 | authorizerId: Input<string>; |
| 83 | }; |
| 84 | |
| 85 | export interface RestApi extends Resource< |
| 86 | "AWS.ApiGateway.RestApi", |
| 87 | RestApiProps, |
| 88 | { |
| 89 | restApiId: string; |
| 90 | rootResourceId: string; |
| 91 | name: string; |
| 92 | description: string | undefined; |
| 93 | version: string | undefined; |
| 94 | binaryMediaTypes: string[] | undefined; |
| 95 | minimumCompressionSize: number | undefined; |
| 96 | apiKeySource: ag.ApiKeySourceType | undefined; |
| 97 | endpointConfiguration: ag.EndpointConfiguration | undefined; |
| 98 | policy: string | undefined; |
| 99 | disableExecuteApiEndpoint: boolean | undefined; |
| 100 | securityPolicy: ag.SecurityPolicy | undefined; |
| 101 | endpointAccessMode: ag.EndpointAccessMode | undefined; |
| 102 | tags: Record<string, string>; |
| 103 | }, |
| 104 | RestApiBinding, |
| 105 | Providers |
| 106 | > {} |
| 107 | |
| 108 | /** |
| 109 | * An Amazon API Gateway REST API (v1). |
| 110 | * |
| 111 | * `RestApi` is the root of an API Gateway v1 stack. Every other ApiGateway |
| 112 | * resource — `Resource`, `Method`, `Authorizer`, `Deployment`, `Stage` — |
| 113 | * hangs off a `RestApi`. The only identity you need to thread through your |
| 114 | * stack is the `RestApi` value itself: child resources accept `restApi: api` |
| 115 | * and register themselves back onto the API so that deployments and stages |
| 116 | * wait for them without any user-authored dependency lists. |
| 117 | * ### Getting started |
| 118 | * A minimal API Gateway stack is four pieces: the `RestApi`, one or more |
| 119 | * `Method`s, a `Deployment` that snapshots those methods, and a `Stage` that |
| 120 | * exposes the deployment at a URL. |
| 121 | * |
| 122 | * **Example:** Mock HTTP GET on the root path |
| 123 | * ```typescript |
| 124 | * import * as ApiGateway from "@alchemy.run/aws/ApiGateway"; |
| 125 | * |
| 126 | * const api = yield* ApiGateway.RestApi("Api", { |
| 127 | * endpointConfiguration: { types: ["REGIONAL"] }, |
| 128 | * }); |
| 129 | * |
| 130 | * yield* ApiGateway.Method("GetRoot", { |
| 131 | * restApi: api, |
| 132 | * httpMethod: "GET", |
| 133 | * authorizationType: "NONE", |
| 134 | * integration: { type: "MOCK" }, |
| 135 | * }); |
| 136 | * |
| 137 | * const deployment = yield* ApiGateway.Deployment("Release", { |
| 138 | * restApi: api, |
| 139 | * }); |
| 140 | * |
| 141 | * const stage = yield* ApiGateway.Stage("Prod", { |
| 142 | * restApi: api, |
| 143 | * stageName: "prod", |
| 144 | * deploymentId: deployment.deploymentId, |
| 145 | * }); |
| 146 | * ``` |
| 147 | * |
| 148 | * ### How dependencies flow |
| 149 | * Writing `restApi: api` on a child (rather than `restApiId: api.restApiId`) |
| 150 | * does two things: it threads the restApi id through, and it registers a |
| 151 | * `RestApiBinding` back onto the API. The Alchemy scheduler sees those |
| 152 | * bindings as reverse edges from children into the API, and `Deployment` |
| 153 | * reads them to express a transitive dependency on every child. You never |
| 154 | * have to write a `DependsOn` list or a `triggers` hash — adding a new |
| 155 | * `Method` automatically orders it before the next `Deployment`. |
| 156 | * |
| 157 | * ### Private REST APIs |
| 158 | * **Example:** Private REST API |
| 159 | * ```typescript |
| 160 | * const api = yield* ApiGateway.RestApi("PrivateApi", { |
| 161 | * endpointConfiguration: { |
| 162 | * types: ["PRIVATE"], |
| 163 | * vpcEndpointIds: [endpoint.vpcEndpointId], |
| 164 | * }, |
| 165 | * policy: JSON.stringify({ |
| 166 | * Version: "2012-10-17", |
| 167 | * Statement: [{ |
| 168 | * Effect: "Allow", |
| 169 | * Principal: "*", |
| 170 | * Action: "execute-api:Invoke", |
| 171 | * Resource: "*", |
| 172 | * }], |
| 173 | * }), |
| 174 | * }); |
| 175 | * ``` |
| 176 | * |
| 177 | * ### Binary payloads |
| 178 | * **Example:** Enable binary media types |
| 179 | * ```typescript |
| 180 | * const api = yield* ApiGateway.RestApi("BinaryApi", { |
| 181 | * binaryMediaTypes: ["application/octet-stream", "image/png"], |
| 182 | * minimumCompressionSize: 1024, |
| 183 | * }); |
| 184 | * ``` |
| 185 | * |
| 186 | * ### Endpoint hardening |
| 187 | * **Example:** Disable the default execute-api endpoint |
| 188 | * ```typescript |
| 189 | * const api = yield* ApiGateway.RestApi("CustomDomainOnlyApi", { |
| 190 | * endpointConfiguration: { types: ["REGIONAL"] }, |
| 191 | * disableExecuteApiEndpoint: true, |
| 192 | * }); |
| 193 | * ``` |
| 194 | * |
| 195 | * @resource |
| 196 | */ |
| 197 | export const RestApi = Resource<RestApi>("AWS.ApiGateway.RestApi"); |
| 198 | |
| 199 | const generatedName = (id: string, props: RestApiProps) => |
| 200 | props.name |
| 201 | ? Effect.succeed(props.name) |
| 202 | : createPhysicalName({ |
| 203 | id, |
| 204 | maxLength: 128, |
| 205 | }); |
| 206 | |
| 207 | const snapshotFromApi = (api: ag.RestApi) => ({ |
| 208 | restApiId: api.id!, |
| 209 | rootResourceId: api.rootResourceId!, |
| 210 | name: api.name ?? "", |
| 211 | description: api.description, |
| 212 | version: api.version, |
| 213 | binaryMediaTypes: api.binaryMediaTypes, |
| 214 | minimumCompressionSize: api.minimumCompressionSize, |
| 215 | apiKeySource: api.apiKeySource, |
| 216 | endpointConfiguration: api.endpointConfiguration, |
| 217 | policy: api.policy, |
| 218 | disableExecuteApiEndpoint: api.disableExecuteApiEndpoint, |
| 219 | securityPolicy: api.securityPolicy, |
| 220 | endpointAccessMode: api.endpointAccessMode, |
| 221 | tags: tagRecord(api.tags), |
| 222 | }); |
| 223 | |
| 224 | const patchReplace = (path: string, value: string): ag.PatchOperation => ({ |
| 225 | op: "replace", |
| 226 | path, |
| 227 | value, |
| 228 | }); |
| 229 | |
| 230 | const encodeJsonPointerSegment = (s: string) => s.replace(/~/g, "~0").replace(/\//g, "~1"); |
| 231 | |
| 232 | const binaryMediaTypePath = (mediaType: string) => |
| 233 | `/binaryMediaTypes/${encodeJsonPointerSegment(mediaType)}`; |
| 234 | |
| 235 | const buildBinaryMediaTypePatches = ( |
| 236 | prev: string[] | undefined, |
| 237 | next: string[] | undefined, |
| 238 | ): ag.PatchOperation[] => { |
| 239 | const prevSet = [...new Set(prev ?? [])]; |
| 240 | const nextSet = [...new Set(next ?? [])]; |
| 241 | const patches: ag.PatchOperation[] = []; |
| 242 | for (const m of prevSet) { |
| 243 | if (!nextSet.includes(m)) { |
| 244 | patches.push({ op: "remove", path: binaryMediaTypePath(m) }); |
| 245 | } |
| 246 | } |
| 247 | for (const m of nextSet) { |
| 248 | if (!prevSet.includes(m)) { |
| 249 | patches.push({ |
| 250 | op: "add", |
| 251 | path: binaryMediaTypePath(m), |
| 252 | value: m, |
| 253 | }); |
| 254 | } |
| 255 | } |
| 256 | return patches; |
| 257 | }; |
| 258 | |
| 259 | const buildUpdatePatches = ( |
| 260 | news: RestApiProps, |
| 261 | prev: RestApi["Attributes"], |
| 262 | ): ag.PatchOperation[] => { |
| 263 | const patches: ag.PatchOperation[] = []; |
| 264 | if (news.name !== undefined && news.name !== prev.name) { |
| 265 | patches.push(patchReplace("/name", news.name)); |
| 266 | } |
| 267 | if (news.description !== prev.description) { |
| 268 | patches.push(patchReplace("/description", news.description ?? "")); |
| 269 | } |
| 270 | if (news.version !== prev.version) { |
| 271 | patches.push(patchReplace("/version", news.version ?? "")); |
| 272 | } |
| 273 | patches.push(...buildBinaryMediaTypePatches(prev.binaryMediaTypes, news.binaryMediaTypes)); |
| 274 | if (news.minimumCompressionSize !== prev.minimumCompressionSize) { |
| 275 | patches.push( |
| 276 | patchReplace("/minimumCompressionSize", String(news.minimumCompressionSize ?? "")), |
| 277 | ); |
| 278 | } |
| 279 | if (news.apiKeySource !== prev.apiKeySource) { |
| 280 | patches.push(patchReplace("/apiKeySource", news.apiKeySource ?? "HEADER")); |
| 281 | } |
| 282 | if (news.policy !== prev.policy) { |
| 283 | patches.push(patchReplace("/policy", news.policy ?? "")); |
| 284 | } |
| 285 | if (news.disableExecuteApiEndpoint !== prev.disableExecuteApiEndpoint) { |
| 286 | patches.push( |
| 287 | patchReplace("/disableExecuteApiEndpoint", String(!!news.disableExecuteApiEndpoint)), |
| 288 | ); |
| 289 | } |
| 290 | if (news.securityPolicy !== prev.securityPolicy) { |
| 291 | patches.push(patchReplace("/securityPolicy", news.securityPolicy ?? "TLS_1_0")); |
| 292 | } |
| 293 | if (news.endpointAccessMode !== prev.endpointAccessMode) { |
| 294 | patches.push(patchReplace("/endpointAccessMode", news.endpointAccessMode ?? "")); |
| 295 | } |
| 296 | return patches; |
| 297 | }; |
| 298 | |
| 299 | export const RestApiProvider = () => |
| 300 | Provider.effect( |
| 301 | RestApi, |
| 302 | Effect.gen(function* () { |
| 303 | // Ensure — create the REST API in full and return its snapshot. Used by |
| 304 | // `precreate` (cycle members) and by `reconcile` when the API is |
| 305 | // missing (greenfield outside a cycle, or deleted out of band). |
| 306 | const createApi = Effect.fn(function* ( |
| 307 | id: string, |
| 308 | news: RestApiProps, |
| 309 | session: { note: (message: string) => Effect.Effect<void> }, |
| 310 | ) { |
| 311 | const name = yield* generatedName(id, news); |
| 312 | const internalTags = yield* createInternalTags(id); |
| 313 | const allTags = { ...news.tags, ...internalTags }; |
| 314 | const created = yield* retryOnApiStatusUpdating( |
| 315 | ag.createRestApi({ |
| 316 | name, |
| 317 | description: news.description, |
| 318 | version: news.version, |
| 319 | cloneFrom: news.cloneFrom, |
| 320 | binaryMediaTypes: news.binaryMediaTypes, |
| 321 | minimumCompressionSize: news.minimumCompressionSize, |
| 322 | apiKeySource: news.apiKeySource, |
| 323 | endpointConfiguration: news.endpointConfiguration, |
| 324 | policy: news.policy, |
| 325 | tags: allTags, |
| 326 | disableExecuteApiEndpoint: news.disableExecuteApiEndpoint, |
| 327 | securityPolicy: news.securityPolicy, |
| 328 | endpointAccessMode: news.endpointAccessMode, |
| 329 | }), |
| 330 | ); |
| 331 | if (!created.id || !created.rootResourceId) { |
| 332 | return yield* Effect.die("createRestApi missing id or rootResourceId"); |
| 333 | } |
| 334 | yield* session.note(`Created REST API ${created.id}`); |
| 335 | const full = yield* ag.getRestApi({ restApiId: created.id }); |
| 336 | return snapshotFromApi(full); |
| 337 | }); |
| 338 | |
| 339 | return { |
| 340 | stables: ["restApiId", "rootResourceId"] as const, |
| 341 | diff: Effect.fn(function* ({ news: newsIn, olds }) { |
| 342 | if (!isResolved(newsIn)) return; |
| 343 | const news = newsIn as RestApiProps; |
| 344 | if ( |
| 345 | // Endpoint type, private endpoint IDs, and IP address type are part |
| 346 | // of the REST API endpoint shape; replacing avoids partial endpoint |
| 347 | // drift that API Gateway cannot consistently patch in place. |
| 348 | !deepEqual(news.endpointConfiguration?.types, olds.endpointConfiguration?.types) || |
| 349 | !deepEqual( |
| 350 | news.endpointConfiguration?.vpcEndpointIds, |
| 351 | olds.endpointConfiguration?.vpcEndpointIds, |
| 352 | ) || |
| 353 | !deepEqual( |
| 354 | news.endpointConfiguration?.ipAddressType, |
| 355 | olds.endpointConfiguration?.ipAddressType, |
| 356 | ) |
| 357 | ) { |
| 358 | return { action: "replace" } as const; |
| 359 | } |
| 360 | }), |
| 361 | // Enumerate every REST API in the account/region. `getRestApis` is a |
| 362 | // paginated collection op (items field "items"); collect every page and |
| 363 | // map each item through the same snapshot helper `read` uses so each |
| 364 | // element is a complete `Attributes` shape. |
| 365 | list: () => |
| 366 | ag.getRestApis.pages({}).pipe( |
| 367 | Stream.runCollect, |
| 368 | Effect.map((chunk) => |
| 369 | Array.from(chunk).flatMap((page) => |
| 370 | (page.items ?? []) |
| 371 | .filter((api): api is ag.RestApi & { id: string } => api.id != null) |
| 372 | .map((api) => snapshotFromApi(api)), |
| 373 | ), |
| 374 | ), |
| 375 | ), |
| 376 | read: Effect.fn(function* ({ output }) { |
| 377 | if (!output?.restApiId) return undefined; |
| 378 | const api = yield* ag |
| 379 | .getRestApi({ restApiId: output.restApiId }) |
| 380 | .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined)); |
| 381 | if (!api?.id) return undefined; |
| 382 | return snapshotFromApi(api); |
| 383 | }), |
| 384 | // The REST API is brought up in two phases. `precreate` creates the |
| 385 | // REST API in full so child resources (`Method`, `Resource`, etc.) |
| 386 | // can resolve `api.restApiId` and start their own creates — this is |
| 387 | // the cycle-breaker that lets children register themselves back onto |
| 388 | // the API via `restApi.bind`. `create` then runs last — after every |
| 389 | // bound child — and is effectively a no-op that re-reads the API to |
| 390 | // publish the final snapshot. The key property is that any |
| 391 | // `Deployment` referencing `api.*` outputs will see a value produced |
| 392 | // only after every bound child has settled, because the bindings on |
| 393 | // the API force `create` to wait for them before returning. |
| 394 | precreate: Effect.fn(function* ({ id, news: newsIn, session }) { |
| 395 | if (!isResolved(newsIn)) { |
| 396 | return yield* Effect.die("RestApi props were not resolved"); |
| 397 | } |
| 398 | const news = newsIn as RestApiProps; |
| 399 | return yield* createApi(id, news, session); |
| 400 | }), |
| 401 | reconcile: Effect.fn(function* ({ id, news: newsIn, output, session }) { |
| 402 | const { region } = yield* AWSEnvironment.current; |
| 403 | if (!isResolved(newsIn)) { |
| 404 | return yield* Effect.die("RestApi props were not resolved"); |
| 405 | } |
| 406 | const news = newsIn as RestApiProps; |
| 407 | |
| 408 | // Observe — fetch live cloud state. `output` is treated as a |
| 409 | // cache for the stable id only. Only cycle members are precreated, |
| 410 | // so a greenfield create outside a cycle arrives without one. |
| 411 | const observed = output?.restApiId |
| 412 | ? yield* ag |
| 413 | .getRestApi({ restApiId: output.restApiId }) |
| 414 | .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined)) |
| 415 | : undefined; |
| 416 | // Ensure — create the API when it is missing. |
| 417 | const observedSnapshot = observed?.id |
| 418 | ? snapshotFromApi(observed) |
| 419 | : yield* createApi(id, news, session); |
| 420 | const restApiId = observedSnapshot.restApiId; |
| 421 | |
| 422 | // Sync mutable scalar fields — diff observed cloud state against |
| 423 | // desired and emit only the delta as PATCH operations. |
| 424 | const patches = buildUpdatePatches(news, observedSnapshot); |
| 425 | if (patches.length > 0) { |
| 426 | yield* retryOnApiStatusUpdating( |
| 427 | ag.updateRestApi({ |
| 428 | restApiId, |
| 429 | patchOperations: patches, |
| 430 | }), |
| 431 | ); |
| 432 | } |
| 433 | |
| 434 | // Sync tags — observed ↔ desired so adoption converges without |
| 435 | // fighting the existing tag set. |
| 436 | const internalTags = yield* createInternalTags(id); |
| 437 | const desiredTags = { ...news.tags, ...internalTags }; |
| 438 | if (!deepEqual(observedSnapshot.tags, desiredTags)) { |
| 439 | const arn = restApiArn(region, restApiId); |
| 440 | yield* syncTags({ |
| 441 | resourceArn: arn, |
| 442 | oldTags: observedSnapshot.tags, |
| 443 | newTags: desiredTags, |
| 444 | }); |
| 445 | } |
| 446 | |
| 447 | yield* session.note(`Reconciled REST API ${restApiId}`); |
| 448 | |
| 449 | // Re-read so the returned attributes reflect what's actually in |
| 450 | // the cloud after all sync steps. |
| 451 | const final = yield* ag.getRestApi({ restApiId }); |
| 452 | if (!final.id) { |
| 453 | return yield* Effect.die("getRestApi missing id after reconcile"); |
| 454 | } |
| 455 | return snapshotFromApi(final); |
| 456 | }), |
| 457 | delete: Effect.fn(function* ({ output, session }) { |
| 458 | yield* deleteRestApiAndWait(output.restApiId); |
| 459 | yield* session.note(`Deleted REST API ${output.restApiId}`); |
| 460 | }), |
| 461 | }; |
| 462 | }), |
| 463 | ); |