@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 333 lines 11.7 KB
Raw
1 import * as agw2 from "@distilled.cloud/aws/apigatewayv2";
2 import { deepEqual, isResolved } from "alchemy/Diff";
3 import type { Input } from "alchemy/Input";
4 import * as Output from "alchemy/Output";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import type { Providers } from "../Providers.ts";
9 import type { Api } from "./Api.ts";
10 import { collectAllPages, retryOnTooManyRequests } from "./common.ts";
11 import type { IntegrationType } from "./Integration.ts";
12
13 export interface RouteProps {
14 /**
15 * ID of the API this route belongs to. Usually derived from `api.apiId`
16 * by the {@link Route} wrapper.
17 */
18 apiId: string;
19 /**
20 * The route key:
21 *
22 * - HTTP APIs — `"GET /items"`, `"ANY /{proxy+}"`, or `"$default"`.
23 * - WebSocket APIs — `"$connect"`, `"$disconnect"`, `"$default"`, or a
24 * custom action name matched by the API's route selection expression.
25 */
26 routeKey: string;
27 /**
28 * The route target, usually `integrations/{integrationId}`. Prefer the
29 * `integration` prop on the {@link Route} wrapper which formats this for
30 * you.
31 */
32 target?: string;
33 /**
34 * The authorization type: `NONE`, `AWS_IAM`, `JWT` (HTTP APIs), or
35 * `CUSTOM` (Lambda authorizer).
36 * @default "NONE"
37 */
38 authorizationType?: agw2.AuthorizationType;
39 /**
40 * The `Authorizer` id when `authorizationType` is `JWT` or `CUSTOM`.
41 */
42 authorizerId?: string;
43 /**
44 * Authorization scopes for JWT authorization.
45 */
46 authorizationScopes?: string[];
47 /** Whether an API key is required (WebSocket APIs only). */
48 apiKeyRequired?: boolean;
49 /** Operation name for the route. */
50 operationName?: string;
51 /** The model selection expression (WebSocket APIs only). */
52 modelSelectionExpression?: string;
53 /** Request models (WebSocket APIs only). */
54 requestModels?: { [key: string]: string | undefined };
55 /** Request parameter constraints (WebSocket APIs only). */
56 requestParameters?: {
57 [key: string]: agw2.ParameterConstraints | undefined;
58 };
59 /**
60 * The route response selection expression (WebSocket APIs only). Set to
61 * `$default` to enable two-way (request/response) routes.
62 */
63 routeResponseSelectionExpression?: string;
64 }
65
66 export interface RouteType extends Resource<
67 "AWS.ApiGatewayV2.Route",
68 RouteProps,
69 {
70 /** The API this route belongs to. */
71 apiId: string;
72 /** The route identifier. */
73 routeId: string;
74 /** The route key. */
75 routeKey: string;
76 target: string | undefined;
77 authorizationType: agw2.AuthorizationType | undefined;
78 authorizerId: string | undefined;
79 authorizationScopes: string[] | undefined;
80 apiKeyRequired: boolean | undefined;
81 operationName: string | undefined;
82 modelSelectionExpression: string | undefined;
83 requestModels: { [key: string]: string | undefined } | undefined;
84 requestParameters: { [key: string]: agw2.ParameterConstraints | undefined } | undefined;
85 routeResponseSelectionExpression: string | undefined;
86 },
87 never,
88 Providers
89 > {}
90
91 /**
92 * An API Gateway v2 Route — matches incoming requests (or WebSocket
93 * messages) and forwards them to an Integration.
94 * ### HTTP API routes
95 * **Example:** Catch-all $default route
96 * ```typescript
97 * yield* ApiGatewayV2.Route("Default", {
98 * api,
99 * routeKey: "$default",
100 * integration,
101 * });
102 * ```
103 *
104 * **Example:** Method + path route
105 * ```typescript
106 * yield* ApiGatewayV2.Route("ListItems", {
107 * api,
108 * routeKey: "GET /items",
109 * integration,
110 * });
111 * ```
112 *
113 * ### WebSocket routes
114 * **Example:** $connect route
115 * ```typescript
116 * yield* ApiGatewayV2.Route("Connect", {
117 * api,
118 * routeKey: "$connect",
119 * integration,
120 * });
121 * ```
122 *
123 * ### Securing routes
124 * **Example:** JWT-protected route
125 * ```typescript
126 * yield* ApiGatewayV2.Route("Secure", {
127 * api,
128 * routeKey: "GET /me",
129 * integration,
130 * authorizationType: "JWT",
131 * authorizerId: authorizer.authorizerId,
132 * });
133 * ```
134 *
135 * @resource
136 */
137 export const RouteResource = Resource<RouteType>("AWS.ApiGatewayV2.Route");
138
139 export interface RouteInputProps extends Omit<
140 {
141 [K in keyof RouteProps]?: Input<RouteProps[K]>;
142 },
143 "apiId" | "routeKey"
144 > {
145 /**
146 * The `Api` this route belongs to (preferred). Alternatively pass a raw
147 * `apiId`.
148 */
149 api?: Api;
150 apiId?: Input<string>;
151 routeKey: Input<string>;
152 /**
153 * The `Integration` this route targets. Formats `target` as
154 * `integrations/{integrationId}` for you. Alternatively pass a raw
155 * `target`.
156 */
157 integration?: IntegrationType;
158 }
159
160 /**
161 * User-facing wrapper for the Route resource. Accepts `api: Api` and
162 * `integration: Integration` as the idiomatic way to wire a route.
163 */
164 export const Route = (id: string, props: RouteInputProps) =>
165 Effect.gen(function* () {
166 const { api, integration, ...rest } = props;
167 const apiId = rest.apiId ?? api?.apiId;
168 if (!apiId) {
169 return yield* Effect.die("Route requires either `api` (preferred) or an explicit `apiId`.");
170 }
171 const target =
172 rest.target ??
173 (integration
174 ? Output.map(integration.integrationId, (id) => `integrations/${id}`)
175 : undefined);
176 return yield* RouteResource(id, { ...rest, apiId, target } as any);
177 });
178
179 const snapshotFromRoute = (apiId: string, route: agw2.GetRouteResult): RouteType["Attributes"] => ({
180 apiId,
181 routeId: route.RouteId!,
182 routeKey: route.RouteKey ?? "",
183 target: route.Target,
184 authorizationType: route.AuthorizationType,
185 authorizerId: route.AuthorizerId,
186 authorizationScopes: route.AuthorizationScopes,
187 apiKeyRequired: route.ApiKeyRequired,
188 operationName: route.OperationName,
189 modelSelectionExpression: route.ModelSelectionExpression,
190 requestModels: route.RequestModels,
191 requestParameters: route.RequestParameters,
192 routeResponseSelectionExpression: route.RouteResponseSelectionExpression,
193 });
194
195 const desiredRequest = (news: RouteProps) => ({
196 RouteKey: news.routeKey,
197 Target: news.target,
198 AuthorizationType: news.authorizationType,
199 AuthorizerId: news.authorizerId,
200 AuthorizationScopes: news.authorizationScopes,
201 ApiKeyRequired: news.apiKeyRequired,
202 OperationName: news.operationName,
203 ModelSelectionExpression: news.modelSelectionExpression,
204 RequestModels: news.requestModels,
205 RequestParameters: news.requestParameters,
206 RouteResponseSelectionExpression: news.routeResponseSelectionExpression,
207 });
208
209 export const RouteProvider = () =>
210 Provider.effect(
211 RouteResource,
212 Effect.gen(function* () {
213 const getRouteSafe = (apiId: string, routeId: string) =>
214 agw2
215 .getRoute({ ApiId: apiId, RouteId: routeId })
216 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
217
218 const findRouteByKey = (apiId: string, routeKey: string) =>
219 collectAllPages((NextToken) => agw2.getRoutes({ ApiId: apiId, NextToken })).pipe(
220 Effect.map((routes) => routes.find((route) => route.RouteKey === routeKey)),
221 );
222
223 return RouteResource.Provider.of({
224 stables: ["apiId", "routeId"],
225
226 list: () =>
227 Effect.gen(function* () {
228 const apis = yield* collectAllPages((NextToken) => agw2.getApis({ NextToken }));
229 const perApi = yield* Effect.forEach(
230 apis.filter((api) => api.ApiId != null),
231 (api) =>
232 collectAllPages((NextToken) =>
233 agw2.getRoutes({ ApiId: api.ApiId!, NextToken }),
234 ).pipe(
235 Effect.map((routes) =>
236 routes
237 .filter((route) => route.RouteId != null)
238 .map((route) => snapshotFromRoute(api.ApiId!, route)),
239 ),
240 Effect.catchTag("NotFoundException", () =>
241 Effect.succeed([] as RouteType["Attributes"][]),
242 ),
243 ),
244 { concurrency: 5 },
245 );
246 return perApi.flat();
247 }),
248
249 read: Effect.fn(function* ({ output }) {
250 if (!output?.apiId || !output.routeId) return undefined;
251 const route = yield* getRouteSafe(output.apiId, output.routeId);
252 if (!route?.RouteId) return undefined;
253 return snapshotFromRoute(output.apiId, route);
254 }),
255
256 diff: Effect.fn(function* ({ news, olds }) {
257 if (!isResolved(news)) return undefined;
258 if (news.apiId !== olds.apiId) {
259 return { action: "replace" } as const;
260 }
261 }),
262
263 reconcile: Effect.fn(function* ({ news, output, session }) {
264 const apiId = output?.apiId ?? news.apiId;
265
266 // 1. OBSERVE — by cached route id, falling back to a lookup by
267 // route key (covers a crash after create but before persist).
268 let observed = output?.routeId
269 ? yield* getRouteSafe(apiId, output.routeId)
270 : yield* findRouteByKey(apiId, news.routeKey);
271
272 // 2. ENSURE — create if missing; a ConflictException means the
273 // route key was created concurrently, so adopt it by key.
274 if (!observed?.RouteId) {
275 observed = yield* retryOnTooManyRequests(
276 agw2.createRoute({ ApiId: apiId, ...desiredRequest(news) }),
277 ).pipe(
278 Effect.catchTag("BadRequestException", (error) =>
279 // AWS reports a duplicate route key as a BadRequestException
280 // ("Route with key ... already exists") — a race with a
281 // concurrent reconciler. Adopt the existing route.
282 findRouteByKey(apiId, news.routeKey).pipe(
283 Effect.flatMap((existing) =>
284 existing ? Effect.succeed(existing) : Effect.fail(error),
285 ),
286 ),
287 ),
288 );
289 yield* session.note(`Created route ${news.routeKey} (${observed.RouteId})`);
290 }
291 const routeId = observed.RouteId!;
292 const snapshot = snapshotFromRoute(apiId, observed);
293
294 // 3. SYNC — update in place on drift (route key is mutable).
295 const desired = desiredRequest(news);
296 const drift =
297 snapshot.routeKey !== desired.RouteKey ||
298 snapshot.target !== desired.Target ||
299 (snapshot.authorizationType ?? "NONE") !== (desired.AuthorizationType ?? "NONE") ||
300 snapshot.authorizerId !== desired.AuthorizerId ||
301 (desired.AuthorizationScopes !== undefined &&
302 !deepEqual(snapshot.authorizationScopes, desired.AuthorizationScopes)) ||
303 (desired.ApiKeyRequired !== undefined &&
304 snapshot.apiKeyRequired !== desired.ApiKeyRequired) ||
305 snapshot.operationName !== desired.OperationName ||
306 snapshot.modelSelectionExpression !== desired.ModelSelectionExpression ||
307 (desired.RequestModels !== undefined &&
308 !deepEqual(snapshot.requestModels, desired.RequestModels)) ||
309 (desired.RequestParameters !== undefined &&
310 !deepEqual(snapshot.requestParameters, desired.RequestParameters)) ||
311 snapshot.routeResponseSelectionExpression !== desired.RouteResponseSelectionExpression;
312 if (drift) {
313 const updated = yield* retryOnTooManyRequests(
314 agw2.updateRoute({ ApiId: apiId, RouteId: routeId, ...desired }),
315 );
316 yield* session.note(`Updated route ${news.routeKey}`);
317 return snapshotFromRoute(apiId, updated);
318 }
319
320 return snapshot;
321 }),
322
323 delete: Effect.fn(function* ({ output, session }) {
324 yield* retryOnTooManyRequests(
325 agw2
326 .deleteRoute({ ApiId: output.apiId, RouteId: output.routeId })
327 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
328 );
329 yield* session.note(`Deleted route ${output.routeKey}`);
330 }),
331 });
332 }),
333 );