@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 618 lines 22.7 KB
Raw
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 * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { toWireMillis } from "alchemy/Util/Duration";
7 import type * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import type { RestApi } from "./RestApi.ts";
12
13 /**
14 * Integration configuration for an API Gateway method (passed to `putIntegration`).
15 */
16 export interface MethodIntegrationProps {
17 /** Integration type: `AWS`, `AWS_PROXY`, `HTTP`, `HTTP_PROXY`, or `MOCK`. */
18 type: ag.IntegrationType;
19 /** HTTP method used to call the backend (always `POST` for Lambda integrations). */
20 integrationHttpMethod?: string;
21 /** Integration endpoint URI (Lambda invocation ARN or HTTP URL). */
22 uri?: Input<string>;
23 /** `VPC_LINK` for private integrations, otherwise `INTERNET`. */
24 connectionType?: ag.ConnectionType;
25 /** ID of the `VpcLink` when `connectionType` is `VPC_LINK`. */
26 connectionId?: string;
27 /**
28 * IAM role ARN used by API Gateway for integration credentials.
29 *
30 * This is not a secret value; API Gateway stores an ARN or passthrough marker.
31 */
32 credentials?: string;
33 /** Maps integration request parameters from method request parameters. */
34 requestParameters?: { [key: string]: string | undefined };
35 /** Request body mapping templates keyed by content type. */
36 requestTemplates?: { [key: string]: string | undefined };
37 /** How unmapped content types pass through (`WHEN_NO_MATCH`, `WHEN_NO_TEMPLATES`, `NEVER`). */
38 passthroughBehavior?: string;
39 /** Cache namespace for integration responses. */
40 cacheNamespace?: string;
41 /** Request parameters whose values form the cache key. */
42 cacheKeyParameters?: string[];
43 /** Payload encoding conversion (`CONVERT_TO_BINARY` or `CONVERT_TO_TEXT`). */
44 contentHandling?: ag.ContentHandlingStrategy;
45 /**
46 * Integration timeout (e.g. `"29 seconds"` or `Duration.seconds(29)`;
47 * a bare number is milliseconds). Sent to the API in milliseconds
48 * (`timeoutInMillis`).
49 */
50 timeout?: Duration.Input;
51 /** TLS settings for HTTP integrations (e.g. `insecureSkipVerification`). */
52 tlsConfig?: ag.TlsConfig;
53 /** How the integration response is transferred to the client. */
54 responseTransferMode?: ag.ResponseTransferMode;
55 /** Target resource of the integration, where the API distinguishes one from `uri`. */
56 integrationTarget?: string;
57 }
58
59 export interface MethodProps {
60 /**
61 * The `RestApi` this method lives on. When supplied, the method auto-binds
62 * itself to the API so that any `Deployment` of this API waits for the
63 * method to be created before snapshotting.
64 *
65 * When `restApi` is provided, `resourceId` defaults to `restApi.rootResourceId`,
66 * which is the common case for methods on the API root (`/`). Pass an
67 * explicit `resourceId` when targeting a sub-path defined by
68 * `ApiGateway.Resource`.
69 *
70 * Passing a raw `restApiId` instead is still supported but opts out of
71 * automatic deployment ordering — you must then manage `Deployment.triggers`
72 * yourself.
73 */
74 restApi?: RestApi;
75 /**
76 * ID of the REST API. Usually derived from `restApi.restApiId`; supply
77 * explicitly only when not using `restApi`.
78 */
79 restApiId?: Input<string>;
80 /**
81 * ID of the API Gateway Resource this method attaches to. Defaults to
82 * `restApi.rootResourceId` when `restApi` is provided.
83 */
84 resourceId?: Input<string>;
85 /** HTTP verb, e.g. `GET`, `POST`, `ANY`. */
86 httpMethod: string;
87 /**
88 * Authorization type (`NONE`, `IAM`, `CUSTOM`, `COGNITO_USER_POOLS`, etc.).
89 * @default "NONE"
90 */
91 authorizationType?: string;
92 /** ID of the `Authorizer` when `authorizationType` is `CUSTOM` or `COGNITO_USER_POOLS`. */
93 authorizerId?: string;
94 /** Require callers to present an API key. */
95 apiKeyRequired?: boolean;
96 /** Friendly operation name (e.g. for SDK generation). */
97 operationName?: string;
98 /** Accepted request parameters; `true` marks a parameter required. */
99 requestParameters?: { [key: string]: boolean | undefined };
100 /** Request body models keyed by content type. */
101 requestModels?: { [key: string]: string | undefined };
102 /** ID of a request validator applied to this method. */
103 requestValidatorId?: string;
104 /** OAuth scopes for `COGNITO_USER_POOLS` authorization. */
105 authorizationScopes?: string[];
106 /** When set, `putIntegration` is applied after `putMethod`. */
107 integration?: MethodIntegrationProps;
108 }
109
110 export interface MethodType extends Resource<
111 "AWS.ApiGateway.Method",
112 MethodProps,
113 {
114 restApiId: string;
115 resourceId: string;
116 httpMethod: string;
117 authorizationType: string;
118 authorizerId: string | undefined;
119 apiKeyRequired: boolean | undefined;
120 operationName: string | undefined;
121 requestParameters: { [key: string]: boolean | undefined } | undefined;
122 requestModels: { [key: string]: string | undefined } | undefined;
123 requestValidatorId: string | undefined;
124 authorizationScopes: string[] | undefined;
125 integration: MethodIntegrationProps | undefined;
126 },
127 never,
128 Providers
129 > {}
130
131 /**
132 * An HTTP method on an API Gateway Resource.
133 *
134 * A `Method` is a single HTTP verb (`GET`, `POST`, `ANY`, …) attached to a
135 * REST API resource path. Most methods also carry an `integration` — the
136 * downstream target that actually handles the request (a Lambda function,
137 * an HTTP endpoint, a mock response, etc.).
138 * ### Binding to a RestApi
139 * Pass the `RestApi` value on `restApi`. This threads the API id through
140 * and registers the method as a `RestApiBinding` on the API, so that any
141 * `Deployment` of the same API is automatically ordered after this method
142 * completes. You do not need to manage `Deployment.triggers` yourself.
143 *
144 * **Example:** GET on the API root with a mock integration
145 * ```typescript
146 * yield* ApiGateway.Method("GetRoot", {
147 * restApi: api,
148 * httpMethod: "GET",
149 * authorizationType: "NONE",
150 * integration: { type: "MOCK" },
151 * });
152 * ```
153 *
154 * ### Lambda proxy integration
155 * For Lambda-backed APIs, the integration `uri` follows the
156 * `arn:aws:apigateway:<region>:lambda:path/2015-03-31/functions/<function-arn>/invocations`
157 * shape. Use `Output.map` to resolve the function ARN before building the
158 * URI, since the function's ARN is only known at deploy time.
159 *
160 * **Example:** ANY method with Lambda AWS_PROXY integration
161 * ```typescript
162 * import * as Output from "alchemy/Output";
163 *
164 * const invokeUri = Output.map(
165 * fn.functionArn,
166 * (arn) =>
167 * `arn:aws:apigateway:${region}:lambda:path/2015-03-31/functions/${arn}/invocations`,
168 * );
169 *
170 * yield* ApiGateway.Method("RootAny", {
171 * restApi: api,
172 * httpMethod: "ANY",
173 * authorizationType: "NONE",
174 * integration: {
175 * type: "AWS_PROXY",
176 * integrationHttpMethod: "POST",
177 * uri: invokeUri,
178 * },
179 * });
180 * ```
181 *
182 * ### Methods on sub-paths
183 * Attach a method to a nested path by creating an `ApiGateway.Resource` and
184 * passing its `resourceId` explicitly. `restApi` is still required so the
185 * method binds for deployment ordering.
186 *
187 * **Example:** Method on `/items`
188 * ```typescript
189 * const items = yield* ApiGateway.Resource("Items", {
190 * restApi: api,
191 * parentId: api.rootResourceId,
192 * pathPart: "items",
193 * });
194 *
195 * yield* ApiGateway.Method("ListItems", {
196 * restApi: api,
197 * resourceId: items.resourceId,
198 * httpMethod: "GET",
199 * authorizationType: "NONE",
200 * integration: { type: "MOCK" },
201 * });
202 * ```
203 *
204 * @resource
205 */
206 export const MethodResource = Resource<MethodType>("AWS.ApiGateway.Method");
207
208 /**
209 * `Input`-accepting mirror of {@link MethodProps} used by the `Method`
210 * wrapper function — see {@link MethodProps} for per-field documentation.
211 */
212 export interface MethodInputProps {
213 restApi?: RestApi;
214 restApiId?: Input<string>;
215 resourceId?: Input<string>;
216 httpMethod: Input<string>;
217 authorizationType?: Input<string>;
218 authorizerId?: Input<string>;
219 apiKeyRequired?: Input<boolean>;
220 operationName?: Input<string>;
221 requestParameters?: Input<MethodProps["requestParameters"]>;
222 requestModels?: Input<MethodProps["requestModels"]>;
223 requestValidatorId?: Input<string>;
224 authorizationScopes?: Input<string[]>;
225 integration?: Input<MethodIntegrationProps>;
226 }
227
228 const MethodImpl = (id: string, props: MethodInputProps) =>
229 Effect.gen(function* () {
230 const { restApi, ...rest } = props;
231 const restApiId = rest.restApiId ?? restApi?.restApiId;
232 const resourceId = rest.resourceId ?? restApi?.rootResourceId;
233 if (!restApiId || !resourceId) {
234 return yield* Effect.die(
235 "Method requires either `restApi` (preferred) or explicit " +
236 "`restApiId` and `resourceId`.",
237 );
238 }
239 const method = yield* MethodResource(id, {
240 ...rest,
241 restApiId,
242 resourceId,
243 } as any);
244 if (restApi) {
245 yield* restApi.bind`${method}`({
246 kind: "method",
247 methodId: method.LogicalId,
248 restApiId: method.restApiId,
249 resourceId: method.resourceId,
250 httpMethod: method.httpMethod,
251 });
252 }
253 return method;
254 });
255
256 /**
257 * User-facing wrapper for the Method resource. Accepts `restApi: RestApi`
258 * as the idiomatic way to attach a method — this both forwards the API id
259 * and registers the method as a binding on the RestApi so the scheduler
260 * orders `Deployment` after it.
261 */
262 export const Method = MethodImpl;
263
264 const putIntegrationRequest = (
265 restApiId: string,
266 resourceId: string,
267 httpMethod: string,
268 integration: MethodIntegrationProps,
269 ): ag.PutIntegrationRequest => ({
270 restApiId,
271 resourceId,
272 httpMethod,
273 type: integration.type,
274 integrationHttpMethod: integration.integrationHttpMethod,
275 uri: integration.uri as string,
276 connectionType: integration.connectionType,
277 connectionId: integration.connectionId,
278 credentials: integration.credentials,
279 requestParameters: integration.requestParameters,
280 requestTemplates: integration.requestTemplates,
281 passthroughBehavior: integration.passthroughBehavior,
282 cacheNamespace: integration.cacheNamespace,
283 cacheKeyParameters: integration.cacheKeyParameters,
284 contentHandling: integration.contentHandling,
285 timeoutInMillis: toWireMillis(integration.timeout),
286 tlsConfig: integration.tlsConfig,
287 responseTransferMode: integration.responseTransferMode,
288 integrationTarget: integration.integrationTarget,
289 });
290
291 const putMethod = (news: Input.ResolveProps<MethodProps>) =>
292 ag.putMethod({
293 restApiId: news.restApiId as string,
294 resourceId: news.resourceId as string,
295 httpMethod: news.httpMethod,
296 authorizationType: news.authorizationType ?? "NONE",
297 authorizerId: news.authorizerId,
298 apiKeyRequired: news.apiKeyRequired,
299 operationName: news.operationName,
300 requestParameters: news.requestParameters,
301 requestModels: news.requestModels,
302 requestValidatorId: news.requestValidatorId,
303 authorizationScopes: news.authorizationScopes,
304 });
305
306 const deleteIntegrationSafe = (p: { restApiId: string; resourceId: string; httpMethod: string }) =>
307 ag
308 .deleteIntegration({
309 restApiId: p.restApiId,
310 resourceId: p.resourceId,
311 httpMethod: p.httpMethod,
312 })
313 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
314
315 const deleteMethodSafe = (p: { restApiId: string; resourceId: string; httpMethod: string }) =>
316 ag
317 .deleteMethod({
318 restApiId: p.restApiId,
319 resourceId: p.resourceId,
320 httpMethod: p.httpMethod,
321 })
322 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
323
324 const readMethodSnapshot = (p: { restApiId: string; resourceId: string; httpMethod: string }) =>
325 Effect.gen(function* () {
326 const method = yield* ag
327 .getMethod({
328 restApiId: p.restApiId,
329 resourceId: p.resourceId,
330 httpMethod: p.httpMethod,
331 })
332 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
333 if (!method?.httpMethod) return undefined;
334
335 const integ = yield* ag
336 .getIntegration({
337 restApiId: p.restApiId,
338 resourceId: p.resourceId,
339 httpMethod: p.httpMethod,
340 })
341 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
342
343 const integration: MethodIntegrationProps | undefined = integ?.type
344 ? {
345 type: integ.type!,
346 integrationHttpMethod: integ.httpMethod,
347 uri: integ.uri,
348 connectionType: integ.connectionType,
349 connectionId: integ.connectionId,
350 credentials: integ.credentials,
351 requestParameters: integ.requestParameters,
352 requestTemplates: integ.requestTemplates,
353 passthroughBehavior: integ.passthroughBehavior,
354 cacheNamespace: integ.cacheNamespace,
355 cacheKeyParameters: integ.cacheKeyParameters,
356 contentHandling: integ.contentHandling,
357 // Wire milliseconds — a plain number is a valid `Duration.Input`,
358 // so the observed snapshot stays directly comparable to a desired
359 // spec normalized via `toWireMillis`.
360 timeout: integ.timeoutInMillis,
361 tlsConfig: integ.tlsConfig,
362 responseTransferMode: integ.responseTransferMode,
363 integrationTarget: integ.integrationTarget,
364 }
365 : undefined;
366
367 return {
368 restApiId: p.restApiId,
369 resourceId: p.resourceId,
370 httpMethod: p.httpMethod,
371 authorizationType: method.authorizationType ?? "NONE",
372 authorizerId: method.authorizerId,
373 apiKeyRequired: method.apiKeyRequired,
374 operationName: method.operationName,
375 requestParameters: method.requestParameters,
376 requestModels: method.requestModels,
377 requestValidatorId: method.requestValidatorId,
378 authorizationScopes: method.authorizationScopes,
379 integration,
380 };
381 });
382
383 export const MethodProvider = () =>
384 Provider.effect(
385 MethodResource,
386 Effect.gen(function* () {
387 return {
388 stables: ["restApiId", "resourceId", "httpMethod"] as const,
389 diff: Effect.fn(function* ({ news: newsIn, olds }) {
390 if (!isResolved(newsIn)) return;
391 const news = newsIn as Input.ResolveProps<MethodProps>;
392 if (
393 news.restApiId !== olds.restApiId ||
394 news.resourceId !== olds.resourceId ||
395 news.httpMethod !== olds.httpMethod
396 ) {
397 return { action: "replace" } as const;
398 }
399 }),
400 read: Effect.fn(function* ({ output }) {
401 if (!output) return undefined;
402 return yield* readMethodSnapshot({
403 restApiId: output.restApiId,
404 resourceId: output.resourceId,
405 httpMethod: output.httpMethod,
406 });
407 }),
408 // Methods are sub-resources keyed by (restApiId, resourceId,
409 // httpMethod) with no dedicated list-methods API. Enumerate every
410 // RestApi -> each Resource (embedding its method verbs) -> read each
411 // method snapshot so every item matches the exact `read` Attributes
412 // shape (including integration), directly usable by `delete`.
413 list: () =>
414 Effect.gen(function* () {
415 const restApis = yield* ag.getRestApis.pages({}).pipe(
416 Stream.runCollect,
417 Effect.map((chunk) =>
418 Array.from(chunk).flatMap((page) =>
419 (page.items ?? []).filter(
420 (api): api is ag.RestApi & { id: string } => api.id != null,
421 ),
422 ),
423 ),
424 );
425
426 const perApi = yield* Effect.forEach(
427 restApis,
428 (api) =>
429 Effect.gen(function* () {
430 const resources = yield* ag.getResources
431 .pages({ restApiId: api.id, embed: ["methods"] })
432 .pipe(
433 Stream.runCollect,
434 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.items ?? [])),
435 );
436
437 const keys = resources.flatMap((resource) =>
438 resource.id
439 ? Object.keys(resource.resourceMethods ?? {}).map((httpMethod) => ({
440 resourceId: resource.id as string,
441 httpMethod,
442 }))
443 : [],
444 );
445
446 const snaps = yield* Effect.forEach(
447 keys,
448 (key) =>
449 readMethodSnapshot({
450 restApiId: api.id,
451 resourceId: key.resourceId,
452 httpMethod: key.httpMethod,
453 }),
454 { concurrency: 10 },
455 );
456
457 return snaps.filter(
458 (snap): snap is NonNullable<typeof snap> => snap !== undefined,
459 );
460 }),
461 { concurrency: 5 },
462 );
463
464 return perApi.flat();
465 }),
466 reconcile: Effect.fn(function* ({ news: newsIn, output, session }) {
467 if (!isResolved(newsIn)) {
468 return yield* Effect.die("Method props were not resolved");
469 }
470 const news = newsIn as Input.ResolveProps<MethodProps>;
471 const authType = news.authorizationType ?? "NONE";
472 // Methods are keyed by (restApiId, resourceId, httpMethod). All
473 // three are stable across the resource's lifetime, so we read
474 // them out of `output` when present and fall back to `news`.
475 const restApiId = (output?.restApiId ?? news.restApiId) as string;
476 const resourceId = (output?.resourceId ?? news.resourceId) as string;
477 const httpMethod = output?.httpMethod ?? news.httpMethod;
478
479 // Observe — read live method + integration as a single snapshot.
480 // `output.*` fields are never trusted as proxies for cloud state;
481 // they're at most a cache for the natural-key tuple above.
482 let observed = yield* readMethodSnapshot({
483 restApiId,
484 resourceId,
485 httpMethod,
486 });
487
488 // Ensure — putMethod creates the method shape (auth type,
489 // request models, scopes, etc.). Some of those fields cannot be
490 // patched in place by `updateMethod`, so on a "recreate-needed"
491 // diff we drop the existing method and re-put. This is also the
492 // path used on first reconcile when nothing exists.
493 const needsRecreate =
494 observed !== undefined &&
495 (news.operationName !== observed.operationName ||
496 !deepEqual(news.requestParameters, observed.requestParameters) ||
497 !deepEqual(news.requestModels, observed.requestModels) ||
498 news.requestValidatorId !== observed.requestValidatorId ||
499 !deepEqual(news.authorizationScopes, observed.authorizationScopes));
500
501 if (observed === undefined || needsRecreate) {
502 if (needsRecreate) {
503 yield* deleteIntegrationSafe({
504 restApiId,
505 resourceId,
506 httpMethod,
507 });
508 yield* deleteMethodSafe({ restApiId, resourceId, httpMethod });
509 }
510 yield* putMethod({
511 ...news,
512 restApiId,
513 resourceId,
514 httpMethod,
515 });
516 if (news.integration) {
517 yield* ag.putIntegration(
518 putIntegrationRequest(restApiId, resourceId, httpMethod, news.integration),
519 );
520 }
521 yield* session.note(
522 needsRecreate
523 ? `Recreated method ${httpMethod}`
524 : `Put method ${httpMethod} on resource ${resourceId}`,
525 );
526 // Re-read to get the canonical observed state for the rest of
527 // the reconciler. After a recreate everything matches `news`,
528 // so the patch step below becomes a no-op.
529 observed = yield* readMethodSnapshot({
530 restApiId,
531 resourceId,
532 httpMethod,
533 });
534 if (!observed) {
535 return yield* Effect.die("getMethod missing after put");
536 }
537 }
538
539 // Sync patchable scalar fields — observed ↔ desired.
540 const patches: ag.PatchOperation[] = [];
541 if (authType !== observed.authorizationType) {
542 patches.push({
543 op: "replace",
544 path: "/authorizationType",
545 value: authType,
546 });
547 }
548 if (news.authorizerId !== observed.authorizerId) {
549 patches.push({
550 op: "replace",
551 path: "/authorizerId",
552 value: news.authorizerId ?? "",
553 });
554 }
555 if (news.apiKeyRequired !== observed.apiKeyRequired) {
556 patches.push({
557 op: "replace",
558 path: "/apiKeyRequired",
559 value: String(news.apiKeyRequired ?? false),
560 });
561 }
562 if (patches.length > 0) {
563 yield* ag.updateMethod({
564 restApiId,
565 resourceId,
566 httpMethod,
567 patchOperations: patches,
568 });
569 }
570
571 // Sync integration — putIntegration is an upsert; deleteIntegration
572 // tolerates missing integrations. Normalize the desired timeout to
573 // wire milliseconds so it compares against the observed snapshot.
574 const desiredIntegration = news.integration && {
575 ...news.integration,
576 timeout: toWireMillis(news.integration.timeout),
577 };
578 if (!deepEqual(desiredIntegration, observed.integration)) {
579 if (news.integration) {
580 yield* ag.putIntegration(
581 putIntegrationRequest(restApiId, resourceId, httpMethod, news.integration),
582 );
583 } else {
584 yield* deleteIntegrationSafe({
585 restApiId,
586 resourceId,
587 httpMethod,
588 });
589 }
590 }
591
592 yield* session.note(`Reconciled method ${httpMethod}`);
593 const snap = yield* readMethodSnapshot({
594 restApiId,
595 resourceId,
596 httpMethod,
597 });
598 if (!snap) {
599 return yield* Effect.die("getMethod missing after reconcile");
600 }
601 return snap;
602 }),
603 delete: Effect.fn(function* ({ output, session }) {
604 yield* deleteIntegrationSafe({
605 restApiId: output.restApiId,
606 resourceId: output.resourceId,
607 httpMethod: output.httpMethod,
608 });
609 yield* deleteMethodSafe({
610 restApiId: output.restApiId,
611 resourceId: output.resourceId,
612 httpMethod: output.httpMethod,
613 });
614 yield* session.note(`Deleted method ${output.httpMethod}`);
615 }),
616 };
617 }),
618 );