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

main
ts 237 lines 7.48 KB
Raw
1 import * as agw2 from "@distilled.cloud/aws/apigatewayv2";
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 type { Providers } from "../Providers.ts";
8 import type { Api } from "./Api.ts";
9 import { collectAllPages, retryOnTooManyRequests } from "./common.ts";
10
11 export interface ApiMappingProps {
12 /**
13 * ID of the API being mapped. Usually derived from `api.apiId` by the
14 * {@link ApiMapping} wrapper.
15 */
16 apiId: string;
17 /**
18 * The custom domain name to map the API onto. Changing this triggers a
19 * replacement.
20 */
21 domainName: string;
22 /**
23 * The stage to serve at the mapping, e.g. `$default`.
24 */
25 stage: string;
26 /**
27 * The base path under the domain, e.g. `v1` serves the API at
28 * `https://{domainName}/v1`. Omit to serve at the domain root.
29 */
30 apiMappingKey?: string;
31 }
32
33 export interface ApiMapping extends Resource<
34 "AWS.ApiGatewayV2.ApiMapping",
35 ApiMappingProps,
36 {
37 /** The mapping identifier. */
38 apiMappingId: string;
39 /** The mapped API. */
40 apiId: string;
41 /** The custom domain name. */
42 domainName: string;
43 /** The mapped stage. */
44 stage: string;
45 /** The base path key. */
46 apiMappingKey: string | undefined;
47 },
48 never,
49 Providers
50 > {}
51
52 /**
53 * An API Gateway v2 API mapping — serves an API stage under a custom
54 * {@link DomainName}, optionally at a base path.
55 * ### Mapping APIs onto a domain
56 * **Example:** Map an API at the domain root
57 * ```typescript
58 * yield* ApiGatewayV2.ApiMapping("Root", {
59 * api,
60 * domainName: domain.domainName,
61 * stage: stage.stageName,
62 * });
63 * ```
64 *
65 * **Example:** Map a second API under /v2
66 * ```typescript
67 * yield* ApiGatewayV2.ApiMapping("V2", {
68 * api: apiV2,
69 * domainName: domain.domainName,
70 * stage: "$default",
71 * apiMappingKey: "v2",
72 * });
73 * ```
74 *
75 * @resource
76 */
77 export const ApiMappingResource = Resource<ApiMapping>("AWS.ApiGatewayV2.ApiMapping");
78
79 export interface ApiMappingInputProps extends Omit<
80 {
81 [K in keyof ApiMappingProps]?: Input<ApiMappingProps[K]>;
82 },
83 "apiId" | "domainName" | "stage"
84 > {
85 /**
86 * The `Api` being mapped (preferred). Alternatively pass a raw `apiId`.
87 */
88 api?: Api;
89 apiId?: Input<string>;
90 domainName: Input<string>;
91 stage: Input<string>;
92 }
93
94 /**
95 * User-facing wrapper for the ApiMapping resource. Accepts `api: Api` as
96 * the idiomatic way to map an API onto a domain.
97 */
98 export const ApiMapping = (id: string, props: ApiMappingInputProps) =>
99 Effect.gen(function* () {
100 const { api, ...rest } = props;
101 const apiId = rest.apiId ?? api?.apiId;
102 if (!apiId) {
103 return yield* Effect.die(
104 "ApiMapping requires either `api` (preferred) or an explicit `apiId`.",
105 );
106 }
107 return yield* ApiMappingResource(id, { ...rest, apiId } as any);
108 });
109
110 const snapshotFromMapping = (
111 domainName: string,
112 mapping: agw2.GetApiMappingResponse,
113 ): ApiMapping["Attributes"] => ({
114 apiMappingId: mapping.ApiMappingId!,
115 apiId: mapping.ApiId ?? "",
116 domainName,
117 stage: mapping.Stage ?? "",
118 apiMappingKey: mapping.ApiMappingKey === "" ? undefined : mapping.ApiMappingKey,
119 });
120
121 export const ApiMappingProvider = () =>
122 Provider.effect(
123 ApiMappingResource,
124 Effect.gen(function* () {
125 const getMappingSafe = (domainName: string, apiMappingId: string) =>
126 agw2
127 .getApiMapping({ DomainName: domainName, ApiMappingId: apiMappingId })
128 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
129
130 return ApiMappingResource.Provider.of({
131 stables: ["apiMappingId", "domainName"],
132
133 list: () =>
134 Effect.gen(function* () {
135 const domains = yield* collectAllPages((NextToken) =>
136 agw2.getDomainNames({ NextToken }),
137 );
138 const perDomain = yield* Effect.forEach(
139 domains.filter((domain) => domain.DomainName != null),
140 (domain) =>
141 collectAllPages((NextToken) =>
142 agw2.getApiMappings({
143 DomainName: domain.DomainName!,
144 NextToken,
145 }),
146 ).pipe(
147 Effect.map((items) =>
148 items
149 .filter((mapping) => mapping.ApiMappingId != null)
150 .map((mapping) => snapshotFromMapping(domain.DomainName!, mapping)),
151 ),
152 Effect.catchTag("NotFoundException", () =>
153 Effect.succeed([] as ApiMapping["Attributes"][]),
154 ),
155 ),
156 { concurrency: 5 },
157 );
158 return perDomain.flat();
159 }),
160
161 read: Effect.fn(function* ({ output }) {
162 if (!output?.domainName || !output.apiMappingId) return undefined;
163 const mapping = yield* getMappingSafe(output.domainName, output.apiMappingId);
164 if (!mapping?.ApiMappingId) return undefined;
165 return snapshotFromMapping(output.domainName, mapping);
166 }),
167
168 diff: Effect.fn(function* ({ news, olds }) {
169 if (!isResolved(news)) return undefined;
170 if (news.domainName !== olds.domainName) {
171 return { action: "replace" } as const;
172 }
173 }),
174
175 reconcile: Effect.fn(function* ({ news, output, session }) {
176 const domainName = output?.domainName ?? news.domainName;
177
178 // 1. OBSERVE
179 let observed = output?.apiMappingId
180 ? yield* getMappingSafe(domainName, output.apiMappingId)
181 : undefined;
182
183 // 2. ENSURE
184 if (!observed?.ApiMappingId) {
185 observed = yield* retryOnTooManyRequests(
186 agw2.createApiMapping({
187 DomainName: domainName,
188 ApiId: news.apiId,
189 Stage: news.stage,
190 ApiMappingKey: news.apiMappingKey,
191 }),
192 );
193 yield* session.note(`Created API mapping ${observed.ApiMappingId}`);
194 return snapshotFromMapping(domainName, observed);
195 }
196
197 // 3. SYNC
198 const snapshot = snapshotFromMapping(domainName, observed);
199 const drift =
200 snapshot.apiId !== news.apiId ||
201 snapshot.stage !== news.stage ||
202 snapshot.apiMappingKey !== news.apiMappingKey;
203 if (drift) {
204 yield* retryOnTooManyRequests(
205 agw2.updateApiMapping({
206 DomainName: domainName,
207 ApiMappingId: snapshot.apiMappingId,
208 ApiId: news.apiId,
209 Stage: news.stage,
210 ApiMappingKey: news.apiMappingKey,
211 }),
212 );
213 yield* session.note(`Updated API mapping ${snapshot.apiMappingId}`);
214 const final = yield* agw2.getApiMapping({
215 DomainName: domainName,
216 ApiMappingId: snapshot.apiMappingId,
217 });
218 return snapshotFromMapping(domainName, final);
219 }
220
221 return snapshot;
222 }),
223
224 delete: Effect.fn(function* ({ output, session }) {
225 yield* retryOnTooManyRequests(
226 agw2
227 .deleteApiMapping({
228 DomainName: output.domainName,
229 ApiMappingId: output.apiMappingId,
230 })
231 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
232 );
233 yield* session.note(`Deleted API mapping ${output.apiMappingId}`);
234 }),
235 });
236 }),
237 );