The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Namespace from "alchemy/Namespace"; |
| 2 | import * as Output from "alchemy/Output"; |
| 3 | import type lambda from "aws-lambda"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Layer from "effect/Layer"; |
| 6 | import type { Api } from "../ApiGatewayV2/Api.ts"; |
| 7 | import { IntegrationResource } from "../ApiGatewayV2/Integration.ts"; |
| 8 | import { RouteResource } from "../ApiGatewayV2/Route.ts"; |
| 9 | import { |
| 10 | WebSocketEventSource as AGW2WebSocketEventSource, |
| 11 | type WebSocketEvent, |
| 12 | type WebSocketEventSourceService, |
| 13 | type WebSocketResult, |
| 14 | type WebSocketRouteProps, |
| 15 | } from "../ApiGatewayV2/WebSocketEventSource.ts"; |
| 16 | import * as Lambda from "./Function.ts"; |
| 17 | import { Permission as LambdaPermission } from "./Permission.ts"; |
| 18 | |
| 19 | export const isWebSocketEvent = (event: any): event is lambda.APIGatewayProxyWebsocketEventV2 => |
| 20 | typeof event?.requestContext?.connectionId === "string" && |
| 21 | typeof event?.requestContext?.routeKey === "string" && |
| 22 | event?.requestContext?.messageDirection === "IN"; |
| 23 | |
| 24 | /** `$connect` → `connect` for stable, readable logical ids. */ |
| 25 | const sanitizeRouteKey = (routeKey: string) => routeKey.replace(/[^A-Za-z0-9]+/g, "") || "route"; |
| 26 | |
| 27 | /** |
| 28 | * Connects a WebSocket API route to the current Lambda function. |
| 29 | * |
| 30 | * At deploy time this layer materializes the `AWS_PROXY` Integration, the |
| 31 | * Route, and the API Gateway invoke Permission for each registered route |
| 32 | * key; at runtime it dispatches matching WebSocket proxy events to the |
| 33 | * registered handler. |
| 34 | * ### Handling WebSocket routes |
| 35 | * **Example:** Echo server |
| 36 | * ```typescript |
| 37 | * const connections = yield* AWS.ApiGatewayV2.ManageConnections(stage); |
| 38 | * |
| 39 | * yield* AWS.ApiGatewayV2.onWebSocketRoute(api, { routeKey: "$connect" }, () => |
| 40 | * Effect.succeed({ statusCode: 200 }), |
| 41 | * ); |
| 42 | * yield* AWS.ApiGatewayV2.onWebSocketRoute(api, { routeKey: "$default" }, (event) => |
| 43 | * connections |
| 44 | * .postToConnection({ |
| 45 | * ConnectionId: event.requestContext.connectionId, |
| 46 | * Data: `echo:${event.body ?? ""}`, |
| 47 | * }) |
| 48 | * .pipe( |
| 49 | * Effect.asVoid, |
| 50 | * Effect.catchTag("GoneException", () => Effect.void), |
| 51 | * Effect.orDie, |
| 52 | * ), |
| 53 | * ); |
| 54 | * ``` |
| 55 | * |
| 56 | * @binding |
| 57 | */ |
| 58 | export const WebSocketEventSource = Layer.effect( |
| 59 | AGW2WebSocketEventSource, |
| 60 | Effect.gen(function* () { |
| 61 | // this layer can only be used in a Lambda Function |
| 62 | const host = yield* Lambda.eventSourceHost("AWS.Lambda.WebSocketEventSource"); |
| 63 | const Integration = yield* IntegrationResource; |
| 64 | const Route = yield* RouteResource; |
| 65 | const Permission = yield* LambdaPermission; |
| 66 | |
| 67 | return Effect.fn(function* <Req = never>( |
| 68 | api: Api, |
| 69 | props: WebSocketRouteProps, |
| 70 | handler: (event: WebSocketEvent) => Effect.Effect<WebSocketResult, never, Req>, |
| 71 | ) { |
| 72 | // Deploy-time: materialize the Integration + Route + invoke |
| 73 | // Permission for this route key. Skipped once running inside the |
| 74 | // deployed Function (the global guard), where the only work is |
| 75 | // registering the runtime dispatcher below. Namespaced under the |
| 76 | // host for stable logical identity. |
| 77 | if (!globalThis.__ALCHEMY_RUNTIME__) { |
| 78 | yield* Namespace.push( |
| 79 | host.LogicalId, |
| 80 | Effect.gen(function* () { |
| 81 | const key = sanitizeRouteKey(props.routeKey); |
| 82 | |
| 83 | const integration = yield* Integration(`${api.LogicalId}-${key}-Integration`, { |
| 84 | apiId: api.apiId, |
| 85 | integrationType: "AWS_PROXY", |
| 86 | // WebSocket AWS_PROXY integrations require the full Lambda |
| 87 | // invocation URI. Region is derived from the function ARN |
| 88 | // so the binding needs no ambient environment. |
| 89 | integrationUri: Output.map( |
| 90 | Lambda.qualifiedArnOf(host), |
| 91 | (arn: string) => |
| 92 | `arn:aws:apigateway:${arn.split(":")[3]}:lambda:path/2015-03-31/functions/${arn}/invocations`, |
| 93 | ), |
| 94 | integrationMethod: "POST", |
| 95 | }); |
| 96 | |
| 97 | yield* Route(`${api.LogicalId}-${key}-Route`, { |
| 98 | apiId: api.apiId, |
| 99 | routeKey: props.routeKey, |
| 100 | target: Output.map(integration.integrationId, (id: string) => `integrations/${id}`), |
| 101 | }); |
| 102 | |
| 103 | yield* Permission(`${api.LogicalId}-${key}-Permission`, { |
| 104 | action: "lambda:InvokeFunction", |
| 105 | functionName: Lambda.qualifiedNameOf(host), |
| 106 | principal: "apigateway.amazonaws.com", |
| 107 | sourceArn: Output.map( |
| 108 | Output.all(host.functionArn, api.apiId), |
| 109 | ([fnArn, apiId]: [string, string]) => { |
| 110 | const [, , , region, accountId] = fnArn.split(":"); |
| 111 | return `arn:aws:execute-api:${region}:${accountId}:${apiId}/*`; |
| 112 | }, |
| 113 | ), |
| 114 | }); |
| 115 | }), |
| 116 | ); |
| 117 | } |
| 118 | |
| 119 | yield* host.listen( |
| 120 | Effect.gen(function* () { |
| 121 | return (event: any) => { |
| 122 | if (isWebSocketEvent(event) && event.requestContext.routeKey === props.routeKey) { |
| 123 | return handler(event).pipe( |
| 124 | Effect.map((result) => result ?? { statusCode: 200 }), |
| 125 | Effect.orDie, |
| 126 | ); |
| 127 | } |
| 128 | }; |
| 129 | }), |
| 130 | ); |
| 131 | }) as WebSocketEventSourceService; |
| 132 | }), |
| 133 | ); |