The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as agw2 from "@distilled.cloud/aws/apigatewayv2"; |
| 2 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { createInternalTags } from "alchemy/Tags"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import { AWSEnvironment } from "../Environment.ts"; |
| 9 | import type { Providers } from "../Providers.ts"; |
| 10 | import { apiArn, collectAllPages, retryOnTooManyRequests, syncTags, tagRecord } from "./common.ts"; |
| 11 | |
| 12 | export interface ApiProps { |
| 13 | /** |
| 14 | * Name of the API. If omitted, Alchemy generates a deterministic |
| 15 | * physical name from the app, stage, and logical ID. |
| 16 | */ |
| 17 | name?: string; |
| 18 | /** |
| 19 | * The API protocol. `HTTP` is the modern Lambda front door; `WEBSOCKET` |
| 20 | * is the real-time two-way protocol. Changing this triggers a |
| 21 | * replacement. |
| 22 | * @default "HTTP" |
| 23 | */ |
| 24 | protocolType?: "HTTP" | "WEBSOCKET"; |
| 25 | /** |
| 26 | * Description of the API. |
| 27 | */ |
| 28 | description?: string; |
| 29 | /** |
| 30 | * The route selection expression. Required by AWS for WebSocket APIs; |
| 31 | * defaults to `$request.body.action` when `protocolType` is `WEBSOCKET`. |
| 32 | * HTTP APIs must use `$request.method $request.path` (the AWS default). |
| 33 | */ |
| 34 | routeSelectionExpression?: string; |
| 35 | /** |
| 36 | * An API key selection expression (WebSocket APIs only). |
| 37 | */ |
| 38 | apiKeySelectionExpression?: string; |
| 39 | /** |
| 40 | * CORS configuration (HTTP APIs only). Synced in place; removing it |
| 41 | * deletes the CORS configuration from the API. |
| 42 | */ |
| 43 | corsConfiguration?: agw2.Cors; |
| 44 | /** |
| 45 | * Disable the default `execute-api` endpoint so the API is reachable |
| 46 | * only through custom domain names. |
| 47 | * @default false |
| 48 | */ |
| 49 | disableExecuteApiEndpoint?: boolean; |
| 50 | /** |
| 51 | * Avoid validating models when creating a deployment (WebSocket APIs |
| 52 | * only). |
| 53 | */ |
| 54 | disableSchemaValidation?: boolean; |
| 55 | /** |
| 56 | * The IP address types that can invoke the API. |
| 57 | * @default "ipv4" |
| 58 | */ |
| 59 | ipAddressType?: agw2.IpAddressType; |
| 60 | /** |
| 61 | * A version identifier for the API. |
| 62 | */ |
| 63 | version?: string; |
| 64 | /** |
| 65 | * User-defined tags (Alchemy internal tags are merged automatically). |
| 66 | */ |
| 67 | tags?: Record<string, string>; |
| 68 | } |
| 69 | |
| 70 | export interface Api extends Resource< |
| 71 | "AWS.ApiGatewayV2.Api", |
| 72 | ApiProps, |
| 73 | { |
| 74 | /** The API identifier. */ |
| 75 | apiId: string; |
| 76 | /** The default endpoint, e.g. `https://{apiId}.execute-api.{region}.amazonaws.com` (or `wss://...` for WebSocket APIs). */ |
| 77 | apiEndpoint: string; |
| 78 | /** The API name. */ |
| 79 | name: string; |
| 80 | /** The API protocol. */ |
| 81 | protocolType: string; |
| 82 | /** The route selection expression. */ |
| 83 | routeSelectionExpression: string | undefined; |
| 84 | description: string | undefined; |
| 85 | apiKeySelectionExpression: string | undefined; |
| 86 | corsConfiguration: agw2.Cors | undefined; |
| 87 | disableExecuteApiEndpoint: boolean | undefined; |
| 88 | disableSchemaValidation: boolean | undefined; |
| 89 | ipAddressType: string | undefined; |
| 90 | version: string | undefined; |
| 91 | tags: Record<string, string>; |
| 92 | }, |
| 93 | never, |
| 94 | Providers |
| 95 | > {} |
| 96 | |
| 97 | /** |
| 98 | * An Amazon API Gateway v2 API — the root of an HTTP API or WebSocket API. |
| 99 | * |
| 100 | * HTTP APIs are the modern, cheaper, faster front door for Lambda functions |
| 101 | * (compared to REST v1). WebSocket APIs provide two-way real-time messaging |
| 102 | * backed by Lambda route handlers. Child resources (`Integration`, `Route`, |
| 103 | * `Stage`, `Authorizer`) reference the API by passing `api` in their props. |
| 104 | * ### HTTP APIs |
| 105 | * For the common "HTTP API in front of a Lambda function" case, prefer the |
| 106 | * high-level {@link HttpApi} helper which wires up the integration, route, |
| 107 | * stage, and invoke permission in one call. |
| 108 | * |
| 109 | * **Example:** Minimal HTTP API |
| 110 | * ```typescript |
| 111 | * import * as ApiGatewayV2 from "@alchemy.run/aws/ApiGatewayV2"; |
| 112 | * |
| 113 | * const api = yield* ApiGatewayV2.Api("Api", {}); |
| 114 | * ``` |
| 115 | * |
| 116 | * **Example:** HTTP API with CORS |
| 117 | * ```typescript |
| 118 | * const api = yield* ApiGatewayV2.Api("Api", { |
| 119 | * corsConfiguration: { |
| 120 | * AllowOrigins: ["https://example.com"], |
| 121 | * AllowMethods: ["GET", "POST"], |
| 122 | * AllowHeaders: ["content-type"], |
| 123 | * MaxAge: 3600, |
| 124 | * }, |
| 125 | * }); |
| 126 | * ``` |
| 127 | * |
| 128 | * ### WebSocket APIs |
| 129 | * **Example:** WebSocket API |
| 130 | * ```typescript |
| 131 | * const api = yield* ApiGatewayV2.Api("WsApi", { |
| 132 | * protocolType: "WEBSOCKET", |
| 133 | * routeSelectionExpression: "$request.body.action", |
| 134 | * }); |
| 135 | * ``` |
| 136 | * |
| 137 | * ### Endpoint hardening |
| 138 | * **Example:** Disable the default execute-api endpoint |
| 139 | * ```typescript |
| 140 | * const api = yield* ApiGatewayV2.Api("Api", { |
| 141 | * disableExecuteApiEndpoint: true, |
| 142 | * }); |
| 143 | * ``` |
| 144 | * |
| 145 | * @resource |
| 146 | */ |
| 147 | export const Api = Resource<Api>("AWS.ApiGatewayV2.Api"); |
| 148 | |
| 149 | const generatedName = (id: string, props: ApiProps) => |
| 150 | props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 128 }); |
| 151 | |
| 152 | const defaultRouteSelectionExpression = (props: ApiProps) => |
| 153 | props.routeSelectionExpression ?? |
| 154 | (props.protocolType === "WEBSOCKET" ? "$request.body.action" : undefined); |
| 155 | |
| 156 | const snapshotFromApi = (api: agw2.GetApiResponse): Api["Attributes"] => ({ |
| 157 | apiId: api.ApiId!, |
| 158 | apiEndpoint: api.ApiEndpoint ?? "", |
| 159 | name: api.Name ?? "", |
| 160 | protocolType: api.ProtocolType ?? "HTTP", |
| 161 | routeSelectionExpression: api.RouteSelectionExpression, |
| 162 | description: api.Description, |
| 163 | apiKeySelectionExpression: api.ApiKeySelectionExpression, |
| 164 | corsConfiguration: api.CorsConfiguration, |
| 165 | disableExecuteApiEndpoint: api.DisableExecuteApiEndpoint, |
| 166 | disableSchemaValidation: api.DisableSchemaValidation, |
| 167 | ipAddressType: api.IpAddressType, |
| 168 | version: api.Version, |
| 169 | tags: tagRecord(api.Tags), |
| 170 | }); |
| 171 | |
| 172 | export const ApiProvider = () => |
| 173 | Provider.effect( |
| 174 | Api, |
| 175 | Effect.gen(function* () { |
| 176 | const getApiSafe = (apiId: string) => |
| 177 | agw2 |
| 178 | .getApi({ ApiId: apiId }) |
| 179 | .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined)); |
| 180 | |
| 181 | return Api.Provider.of({ |
| 182 | stables: ["apiId", "apiEndpoint"], |
| 183 | |
| 184 | list: () => |
| 185 | Effect.gen(function* () { |
| 186 | const items = yield* collectAllPages((NextToken) => agw2.getApis({ NextToken })); |
| 187 | return items.filter((api) => api.ApiId != null).map((api) => snapshotFromApi(api)); |
| 188 | }), |
| 189 | |
| 190 | read: Effect.fn(function* ({ output }) { |
| 191 | if (!output?.apiId) return undefined; |
| 192 | const api = yield* getApiSafe(output.apiId); |
| 193 | if (!api?.ApiId) return undefined; |
| 194 | return snapshotFromApi(api); |
| 195 | }), |
| 196 | |
| 197 | diff: Effect.fn(function* ({ news, olds }) { |
| 198 | if (!isResolved(news)) return undefined; |
| 199 | const oldProtocol = olds.protocolType ?? "HTTP"; |
| 200 | const newProtocol = news.protocolType ?? "HTTP"; |
| 201 | if (oldProtocol !== newProtocol) { |
| 202 | return { action: "replace" } as const; |
| 203 | } |
| 204 | }), |
| 205 | |
| 206 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 207 | const { region } = yield* AWSEnvironment.current; |
| 208 | const name = yield* generatedName(id, news); |
| 209 | const internalTags = yield* createInternalTags(id); |
| 210 | const desiredTags = { ...news.tags, ...internalTags }; |
| 211 | const routeSelectionExpression = defaultRouteSelectionExpression(news); |
| 212 | |
| 213 | // 1. OBSERVE — output is only a cache for the stable id; the |
| 214 | // cloud is authoritative. |
| 215 | let observed = output?.apiId ? yield* getApiSafe(output.apiId) : undefined; |
| 216 | |
| 217 | // 2. ENSURE — create if missing (greenfield or deleted |
| 218 | // out-of-band). |
| 219 | if (!observed?.ApiId) { |
| 220 | observed = yield* retryOnTooManyRequests( |
| 221 | agw2.createApi({ |
| 222 | Name: name, |
| 223 | ProtocolType: news.protocolType ?? "HTTP", |
| 224 | Description: news.description, |
| 225 | RouteSelectionExpression: routeSelectionExpression, |
| 226 | ApiKeySelectionExpression: news.apiKeySelectionExpression, |
| 227 | CorsConfiguration: news.corsConfiguration, |
| 228 | DisableExecuteApiEndpoint: news.disableExecuteApiEndpoint, |
| 229 | DisableSchemaValidation: news.disableSchemaValidation, |
| 230 | IpAddressType: news.ipAddressType, |
| 231 | Version: news.version, |
| 232 | Tags: desiredTags, |
| 233 | }), |
| 234 | ); |
| 235 | yield* session.note(`Created API ${observed.ApiId}`); |
| 236 | } |
| 237 | const apiId = observed.ApiId!; |
| 238 | const snapshot = snapshotFromApi(observed); |
| 239 | |
| 240 | // 3. SYNC — diff observed against desired per mutable aspect and |
| 241 | // apply only the delta. |
| 242 | const drift = |
| 243 | snapshot.name !== name || |
| 244 | snapshot.description !== news.description || |
| 245 | (routeSelectionExpression !== undefined && |
| 246 | snapshot.routeSelectionExpression !== routeSelectionExpression) || |
| 247 | snapshot.apiKeySelectionExpression !== news.apiKeySelectionExpression || |
| 248 | (news.corsConfiguration !== undefined && |
| 249 | !deepEqual(snapshot.corsConfiguration, news.corsConfiguration)) || |
| 250 | (snapshot.disableExecuteApiEndpoint ?? false) !== |
| 251 | (news.disableExecuteApiEndpoint ?? false) || |
| 252 | (news.disableSchemaValidation !== undefined && |
| 253 | snapshot.disableSchemaValidation !== news.disableSchemaValidation) || |
| 254 | (news.ipAddressType !== undefined && snapshot.ipAddressType !== news.ipAddressType) || |
| 255 | snapshot.version !== news.version; |
| 256 | if (drift) { |
| 257 | yield* retryOnTooManyRequests( |
| 258 | agw2.updateApi({ |
| 259 | ApiId: apiId, |
| 260 | Name: name, |
| 261 | Description: news.description, |
| 262 | RouteSelectionExpression: routeSelectionExpression, |
| 263 | ApiKeySelectionExpression: news.apiKeySelectionExpression, |
| 264 | CorsConfiguration: news.corsConfiguration, |
| 265 | DisableExecuteApiEndpoint: news.disableExecuteApiEndpoint, |
| 266 | DisableSchemaValidation: news.disableSchemaValidation, |
| 267 | IpAddressType: news.ipAddressType, |
| 268 | Version: news.version, |
| 269 | }), |
| 270 | ); |
| 271 | } |
| 272 | |
| 273 | // CORS removal is a separate API call — `updateApi` cannot clear |
| 274 | // an existing configuration. |
| 275 | if (news.corsConfiguration === undefined && snapshot.corsConfiguration !== undefined) { |
| 276 | yield* agw2 |
| 277 | .deleteCorsConfiguration({ ApiId: apiId }) |
| 278 | .pipe(Effect.catchTag("NotFoundException", () => Effect.void)); |
| 279 | } |
| 280 | |
| 281 | // 3b. SYNC TAGS — diff against OBSERVED cloud tags. |
| 282 | if (!deepEqual(snapshot.tags, desiredTags)) { |
| 283 | yield* syncTags({ |
| 284 | resourceArn: apiArn(region, apiId), |
| 285 | oldTags: snapshot.tags, |
| 286 | newTags: desiredTags, |
| 287 | }); |
| 288 | } |
| 289 | |
| 290 | // 4. RETURN — re-read so attributes reflect actual cloud state. |
| 291 | const final = yield* agw2.getApi({ ApiId: apiId }); |
| 292 | yield* session.note(`Reconciled API ${apiId}`); |
| 293 | return snapshotFromApi(final); |
| 294 | }), |
| 295 | |
| 296 | delete: Effect.fn(function* ({ output, session }) { |
| 297 | yield* retryOnTooManyRequests( |
| 298 | agw2 |
| 299 | .deleteApi({ ApiId: output.apiId }) |
| 300 | .pipe(Effect.catchTag("NotFoundException", () => Effect.void)), |
| 301 | ); |
| 302 | yield* session.note(`Deleted API ${output.apiId}`); |
| 303 | }), |
| 304 | }); |
| 305 | }), |
| 306 | ); |