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

main
ts 161 lines 6.09 KB
Raw
1 import * as ag from "@distilled.cloud/aws/api-gateway";
2 import { 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 * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9 import { retryOnApiStatusUpdating } from "./common.ts";
10
11 export interface GatewayResponseProps {
12 /** ID of the REST API the response mapping belongs to. */
13 restApiId: Input<string>;
14 /** The gateway response type to customize (e.g. `DEFAULT_4XX`, `ACCESS_DENIED`). */
15 responseType: ag.GatewayResponseType;
16 /** HTTP status code to return; defaults to the response type's standard code. */
17 statusCode?: string;
18 /** Response header parameters (e.g. `gatewayresponse.header.X-Foo`) as mapping expressions. */
19 responseParameters?: { [key: string]: string | undefined };
20 /** Response body mapping templates keyed by content type. */
21 responseTemplates?: { [key: string]: string | undefined };
22 }
23
24 /** @resource */
25 export interface GatewayResponse extends Resource<
26 "AWS.ApiGateway.GatewayResponse",
27 GatewayResponseProps,
28 {
29 restApiId: string;
30 responseType: ag.GatewayResponseType;
31 statusCode: string | undefined;
32 },
33 never,
34 Providers
35 > {}
36
37 /**
38 * Gateway response mapping for a REST API (e.g. DEFAULT_4XX, DEFAULT_5XX).
39 *
40 * ### Gateway responses
41 * **Example:** Default 4xx JSON body
42 * ```typescript
43 * yield* ApiGateway.GatewayResponse("Default4xx", {
44 * restApiId: api.restApiId,
45 * responseType: "DEFAULT_4XX",
46 * responseTemplates: { "application/json": '{"message":$context.error.messageString}' },
47 * });
48 * ```
49 */
50 const GatewayResponseResource = Resource<GatewayResponse>("AWS.ApiGateway.GatewayResponse");
51
52 export { GatewayResponseResource as GatewayResponse };
53
54 export const GatewayResponseProvider = () =>
55 Provider.effect(
56 GatewayResponseResource,
57 Effect.gen(function* () {
58 return {
59 stables: ["restApiId", "responseType"] as const,
60 diff: Effect.fn(function* ({ news: newsIn, olds }) {
61 if (!isResolved(newsIn)) return;
62 const news = newsIn as Input.ResolveProps<GatewayResponseProps>;
63 if (news.restApiId !== olds.restApiId || news.responseType !== olds.responseType) {
64 return { action: "replace" } as const;
65 }
66 }),
67 read: Effect.fn(function* ({ output }) {
68 if (!output) return undefined;
69 const g = yield* ag
70 .getGatewayResponse({
71 restApiId: output.restApiId,
72 responseType: output.responseType,
73 })
74 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
75 if (!g?.responseType) return undefined;
76 return {
77 restApiId: output.restApiId,
78 responseType: g.responseType!,
79 statusCode: g.statusCode,
80 };
81 }),
82 // GatewayResponses are sub-resources of a RestApi, so enumerate every
83 // RestApi first (paginated), then list the gateway responses per api.
84 list: () =>
85 Effect.gen(function* () {
86 const restApiIds = yield* ag.getRestApis.pages({}).pipe(
87 Stream.runCollect,
88 Effect.map((chunk) =>
89 Array.from(chunk).flatMap((page) =>
90 (page.items ?? []).map((a) => a.id).filter((id): id is string => id != null),
91 ),
92 ),
93 );
94 const rows = yield* Effect.forEach(
95 restApiIds,
96 (restApiId) =>
97 ag.getGatewayResponses({ restApiId }).pipe(
98 Effect.map((res) =>
99 (res.items ?? [])
100 .filter(
101 (
102 g,
103 ): g is ag.GatewayResponse & {
104 responseType: ag.GatewayResponseType;
105 } => g.responseType != null,
106 )
107 .map((g) => ({
108 restApiId,
109 responseType: g.responseType,
110 statusCode: g.statusCode,
111 })),
112 ),
113 Effect.catchTag("NotFoundException", () => Effect.succeed([])),
114 ),
115 { concurrency: 10 },
116 );
117 return rows.flat();
118 }),
119 reconcile: Effect.fn(function* ({ news: newsIn, output, session }) {
120 if (!isResolved(newsIn)) {
121 return yield* Effect.die("GatewayResponse props were not resolved");
122 }
123 const news = newsIn as Input.ResolveProps<GatewayResponseProps>;
124 const restApiId = (output?.restApiId ?? news.restApiId) as string;
125 const responseType = output?.responseType ?? news.responseType;
126
127 // Observe + Ensure + Sync as one atomic op.
128 // `putGatewayResponse` is an upsert: it creates the response if
129 // missing, replaces it if present. The reconciler is therefore a
130 // single put against the desired state regardless of whether
131 // `output` exists.
132 yield* retryOnApiStatusUpdating(
133 ag.putGatewayResponse({
134 restApiId,
135 responseType,
136 statusCode: news.statusCode,
137 responseParameters: news.responseParameters,
138 responseTemplates: news.responseTemplates,
139 }),
140 );
141 yield* session.note(`Reconciled gateway response ${responseType} on ${restApiId}`);
142 return {
143 restApiId,
144 responseType,
145 statusCode: news.statusCode,
146 };
147 }),
148 delete: Effect.fn(function* ({ output, session }) {
149 yield* retryOnApiStatusUpdating(
150 ag
151 .deleteGatewayResponse({
152 restApiId: output.restApiId,
153 responseType: output.responseType,
154 })
155 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
156 );
157 yield* session.note(`Deleted gateway response ${output.responseType}`);
158 }),
159 };
160 }),
161 );