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

main
ts 354 lines 13.6 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 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 type { Providers } from "../Providers.ts";
10 import type { Api } from "./Api.ts";
11 import { collectAllPages, retryOnTooManyRequests } from "./common.ts";
12
13 export interface IntegrationProps {
14 /**
15 * ID of the API this integration belongs to. Usually derived from
16 * `api.apiId` by the {@link Integration} wrapper.
17 */
18 apiId: string;
19 /**
20 * The integration type. `AWS_PROXY` (Lambda proxy) is the common case
21 * for both HTTP and WebSocket APIs; `HTTP_PROXY` forwards to an HTTP
22 * endpoint; `MOCK` (WebSocket only) returns a static response.
23 */
24 integrationType: agw2.IntegrationType;
25 /**
26 * The integration endpoint:
27 *
28 * - `AWS_PROXY` on an HTTP API — the Lambda function ARN.
29 * - `AWS_PROXY` on a WebSocket API — the full invocation URI
30 * (`arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/{functionArn}/invocations`).
31 * - `HTTP_PROXY` — the HTTP URL.
32 * - private integrations — the ELB listener / Cloud Map service ARN.
33 */
34 integrationUri?: string;
35 /**
36 * The HTTP method the integration uses when calling the backend
37 * (`POST` for Lambda; for `HTTP_PROXY` routes usually `ANY`).
38 */
39 integrationMethod?: string;
40 /**
41 * The Lambda event payload format for HTTP API `AWS_PROXY` integrations.
42 * `2.0` is the modern shape (same as Lambda Function URLs).
43 * @default "2.0" for HTTP AWS_PROXY (AWS defaults to "1.0" — the wrapper does not override; set explicitly)
44 */
45 payloadFormatVersion?: string;
46 /**
47 * `INTERNET` (default) or `VPC_LINK` for private integrations.
48 */
49 connectionType?: agw2.ConnectionType;
50 /**
51 * The VPC link ID when `connectionType` is `VPC_LINK`.
52 */
53 connectionId?: string;
54 /**
55 * IAM credentials ARN for the integration (or
56 * `arn:aws:iam::*:user/*` to use caller credentials).
57 */
58 credentialsArn?: string;
59 /** Description of the integration. */
60 description?: string;
61 /**
62 * AWS service integration subtype (e.g. `SQS-SendMessage`) for
63 * first-class AWS service integrations on HTTP APIs.
64 */
65 integrationSubtype?: string;
66 /** Passthrough behavior (WebSocket APIs only). */
67 passthroughBehavior?: agw2.PassthroughBehavior;
68 /** Request parameter mappings. */
69 requestParameters?: { [key: string]: string | undefined };
70 /** Request templates (WebSocket APIs only). */
71 requestTemplates?: { [key: string]: string | undefined };
72 /** Response parameter mappings (HTTP APIs). */
73 responseParameters?: {
74 [key: string]: { [key: string]: string | undefined } | undefined;
75 };
76 /** Template selection expression (WebSocket APIs only). */
77 templateSelectionExpression?: string;
78 /**
79 * Integration timeout (e.g. `"29 seconds"` or `Duration.seconds(29)`;
80 * a bare number is milliseconds). 50–29000 ms for WebSocket APIs,
81 * 50–30000 ms for HTTP APIs. Sent to the API in whole milliseconds
82 * (`TimeoutInMillis`).
83 */
84 timeout?: Duration.Input;
85 /** TLS configuration for private integrations. */
86 tlsConfig?: agw2.TlsConfigInput;
87 /** Content handling strategy (WebSocket APIs only). */
88 contentHandlingStrategy?: agw2.ContentHandlingStrategy;
89 }
90
91 export interface IntegrationType extends Resource<
92 "AWS.ApiGatewayV2.Integration",
93 IntegrationProps,
94 {
95 /** The API this integration belongs to. */
96 apiId: string;
97 /** The integration identifier. */
98 integrationId: string;
99 integrationType: agw2.IntegrationType;
100 integrationUri: string | undefined;
101 integrationMethod: string | undefined;
102 payloadFormatVersion: string | undefined;
103 connectionType: agw2.ConnectionType | undefined;
104 connectionId: string | undefined;
105 credentialsArn: string | undefined;
106 description: string | undefined;
107 integrationSubtype: string | undefined;
108 passthroughBehavior: agw2.PassthroughBehavior | undefined;
109 requestParameters: { [key: string]: string | undefined } | undefined;
110 requestTemplates: { [key: string]: string | undefined } | undefined;
111 responseParameters:
112 | { [key: string]: { [key: string]: string | undefined } | undefined }
113 | undefined;
114 templateSelectionExpression: string | undefined;
115 timeoutInMillis: number | undefined;
116 contentHandlingStrategy: agw2.ContentHandlingStrategy | undefined;
117 },
118 never,
119 Providers
120 > {}
121
122 /**
123 * An API Gateway v2 Integration — the backend target a Route forwards to.
124 *
125 * For HTTP APIs the common integration is `AWS_PROXY` with payload format
126 * `2.0`, pointing directly at a Lambda function ARN. For WebSocket APIs the
127 * `integrationUri` must be the full Lambda invocation URI.
128 * ### Lambda proxy integration (HTTP API)
129 * **Example:** AWS_PROXY integration with payload 2.0
130 * ```typescript
131 * const integration = yield* ApiGatewayV2.Integration("Fn", {
132 * api,
133 * integrationType: "AWS_PROXY",
134 * integrationUri: fn.functionArn,
135 * payloadFormatVersion: "2.0",
136 * });
137 * ```
138 *
139 * ### HTTP proxy integration
140 * **Example:** Forward to an external HTTP endpoint
141 * ```typescript
142 * const integration = yield* ApiGatewayV2.Integration("Upstream", {
143 * api,
144 * integrationType: "HTTP_PROXY",
145 * integrationUri: "https://example.com/{proxy}",
146 * integrationMethod: "ANY",
147 * payloadFormatVersion: "1.0",
148 * });
149 * ```
150 *
151 * @resource
152 */
153 export const IntegrationResource = Resource<IntegrationType>("AWS.ApiGatewayV2.Integration");
154
155 export interface IntegrationInputProps extends Omit<
156 {
157 [K in keyof IntegrationProps]?: Input<IntegrationProps[K]>;
158 },
159 "apiId" | "integrationType"
160 > {
161 /**
162 * The `Api` this integration belongs to (preferred). Alternatively pass
163 * a raw `apiId`.
164 */
165 api?: Api;
166 apiId?: Input<string>;
167 integrationType: Input<agw2.IntegrationType>;
168 }
169
170 /**
171 * User-facing wrapper for the Integration resource. Accepts `api: Api` as
172 * the idiomatic way to attach an integration to an API.
173 */
174 export const Integration = (id: string, props: IntegrationInputProps) =>
175 Effect.gen(function* () {
176 const { api, ...rest } = props;
177 const apiId = rest.apiId ?? api?.apiId;
178 if (!apiId) {
179 return yield* Effect.die(
180 "Integration requires either `api` (preferred) or an explicit `apiId`.",
181 );
182 }
183 return yield* IntegrationResource(id, { ...rest, apiId } as any);
184 });
185
186 const snapshotFromIntegration = (
187 apiId: string,
188 integ: agw2.GetIntegrationResult,
189 ): IntegrationType["Attributes"] => ({
190 apiId,
191 integrationId: integ.IntegrationId!,
192 integrationType: integ.IntegrationType ?? "AWS_PROXY",
193 integrationUri: integ.IntegrationUri,
194 integrationMethod: integ.IntegrationMethod,
195 payloadFormatVersion: integ.PayloadFormatVersion,
196 connectionType: integ.ConnectionType,
197 connectionId: integ.ConnectionId,
198 credentialsArn: integ.CredentialsArn,
199 description: integ.Description,
200 integrationSubtype: integ.IntegrationSubtype,
201 passthroughBehavior: integ.PassthroughBehavior,
202 requestParameters: integ.RequestParameters,
203 requestTemplates: integ.RequestTemplates,
204 responseParameters: integ.ResponseParameters,
205 templateSelectionExpression: integ.TemplateSelectionExpression,
206 timeoutInMillis: integ.TimeoutInMillis,
207 contentHandlingStrategy: integ.ContentHandlingStrategy,
208 });
209
210 const desiredRequest = (news: IntegrationProps) => ({
211 IntegrationType: news.integrationType,
212 IntegrationUri: news.integrationUri,
213 IntegrationMethod: news.integrationMethod,
214 PayloadFormatVersion: news.payloadFormatVersion,
215 ConnectionType: news.connectionType,
216 ConnectionId: news.connectionId,
217 CredentialsArn: news.credentialsArn,
218 Description: news.description,
219 IntegrationSubtype: news.integrationSubtype,
220 PassthroughBehavior: news.passthroughBehavior,
221 RequestParameters: news.requestParameters,
222 RequestTemplates: news.requestTemplates,
223 ResponseParameters: news.responseParameters,
224 TemplateSelectionExpression: news.templateSelectionExpression,
225 TimeoutInMillis: toWireMillis(news.timeout),
226 TlsConfig: news.tlsConfig,
227 ContentHandlingStrategy: news.contentHandlingStrategy,
228 });
229
230 export const IntegrationProvider = () =>
231 Provider.effect(
232 IntegrationResource,
233 Effect.gen(function* () {
234 const getIntegrationSafe = (apiId: string, integrationId: string) =>
235 agw2
236 .getIntegration({ ApiId: apiId, IntegrationId: integrationId })
237 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
238
239 return IntegrationResource.Provider.of({
240 stables: ["apiId", "integrationId"],
241
242 list: () =>
243 Effect.gen(function* () {
244 const apis = yield* collectAllPages((NextToken) => agw2.getApis({ NextToken }));
245 const perApi = yield* Effect.forEach(
246 apis.filter((api) => api.ApiId != null),
247 (api) =>
248 collectAllPages((NextToken) =>
249 agw2.getIntegrations({ ApiId: api.ApiId!, NextToken }),
250 ).pipe(
251 Effect.map((items) =>
252 items
253 .filter((integ) => integ.IntegrationId != null)
254 .map((integ) => snapshotFromIntegration(api.ApiId!, integ)),
255 ),
256 // API deleted between list and getIntegrations — skip it.
257 Effect.catchTag("NotFoundException", () =>
258 Effect.succeed([] as IntegrationType["Attributes"][]),
259 ),
260 ),
261 { concurrency: 5 },
262 );
263 return perApi.flat();
264 }),
265
266 read: Effect.fn(function* ({ output }) {
267 if (!output?.apiId || !output.integrationId) return undefined;
268 const integ = yield* getIntegrationSafe(output.apiId, output.integrationId);
269 if (!integ?.IntegrationId) return undefined;
270 return snapshotFromIntegration(output.apiId, integ);
271 }),
272
273 diff: Effect.fn(function* ({ news, olds }) {
274 if (!isResolved(news)) return undefined;
275 if (news.apiId !== olds.apiId) {
276 return { action: "replace" } as const;
277 }
278 }),
279
280 reconcile: Effect.fn(function* ({ news, output, session }) {
281 const apiId = output?.apiId ?? news.apiId;
282
283 // 1. OBSERVE
284 let observed = output?.integrationId
285 ? yield* getIntegrationSafe(apiId, output.integrationId)
286 : undefined;
287
288 // 2. ENSURE
289 if (!observed?.IntegrationId) {
290 observed = yield* retryOnTooManyRequests(
291 agw2.createIntegration({ ApiId: apiId, ...desiredRequest(news) }),
292 );
293 yield* session.note(`Created integration ${observed.IntegrationId}`);
294 return snapshotFromIntegration(apiId, observed);
295 }
296
297 // 3. SYNC — compare the observed snapshot against desired and
298 // update only on drift.
299 const snapshot = snapshotFromIntegration(apiId, observed);
300 const desired = desiredRequest(news);
301 const drift =
302 snapshot.integrationType !== desired.IntegrationType ||
303 snapshot.integrationUri !== desired.IntegrationUri ||
304 snapshot.integrationMethod !== desired.IntegrationMethod ||
305 (desired.PayloadFormatVersion !== undefined &&
306 snapshot.payloadFormatVersion !== desired.PayloadFormatVersion) ||
307 (desired.ConnectionType !== undefined &&
308 snapshot.connectionType !== desired.ConnectionType) ||
309 snapshot.connectionId !== desired.ConnectionId ||
310 snapshot.credentialsArn !== desired.CredentialsArn ||
311 snapshot.description !== desired.Description ||
312 snapshot.integrationSubtype !== desired.IntegrationSubtype ||
313 (desired.PassthroughBehavior !== undefined &&
314 snapshot.passthroughBehavior !== desired.PassthroughBehavior) ||
315 (desired.RequestParameters !== undefined &&
316 !deepEqual(snapshot.requestParameters, desired.RequestParameters)) ||
317 (desired.RequestTemplates !== undefined &&
318 !deepEqual(snapshot.requestTemplates, desired.RequestTemplates)) ||
319 (desired.ResponseParameters !== undefined &&
320 !deepEqual(snapshot.responseParameters, desired.ResponseParameters)) ||
321 snapshot.templateSelectionExpression !== desired.TemplateSelectionExpression ||
322 (desired.TimeoutInMillis !== undefined &&
323 snapshot.timeoutInMillis !== desired.TimeoutInMillis) ||
324 (desired.ContentHandlingStrategy !== undefined &&
325 snapshot.contentHandlingStrategy !== desired.ContentHandlingStrategy);
326 if (drift) {
327 const updated = yield* retryOnTooManyRequests(
328 agw2.updateIntegration({
329 ApiId: apiId,
330 IntegrationId: snapshot.integrationId,
331 ...desired,
332 }),
333 );
334 yield* session.note(`Updated integration ${snapshot.integrationId}`);
335 return snapshotFromIntegration(apiId, updated);
336 }
337
338 return snapshot;
339 }),
340
341 delete: Effect.fn(function* ({ output, session }) {
342 yield* retryOnTooManyRequests(
343 agw2
344 .deleteIntegration({
345 ApiId: output.apiId,
346 IntegrationId: output.integrationId,
347 })
348 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
349 );
350 yield* session.note(`Deleted integration ${output.integrationId}`);
351 }),
352 });
353 }),
354 );