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

main
ts 258 lines 8.78 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 as ResourceFactory, type Resource as ResourceType } 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 type { RestApi } from "./RestApi.ts";
10
11 export interface ApiGatewayResourceProps {
12 /**
13 * The `RestApi` this path segment belongs to. Binding via `restApi`
14 * registers this resource on the API so that any `Deployment` of the
15 * same API waits for it — and for the methods attached to it — before
16 * snapshotting.
17 */
18 restApi?: RestApi;
19 /**
20 * Identifier of the parent REST API. Usually derived from `restApi.restApiId`.
21 */
22 restApiId?: Input<string>;
23 /**
24 * Parent resource id (use `api.rootResourceId` for top-level paths, or
25 * the `resourceId` of another `ApiGateway.Resource` to nest deeper).
26 */
27 parentId: Input<string>;
28 /**
29 * Path segment (e.g. `items` or `{proxy+}`).
30 */
31 pathPart: string;
32 }
33
34 export interface ApiGatewayResource extends ResourceType<
35 "AWS.ApiGateway.Resource",
36 ApiGatewayResourceProps,
37 {
38 resourceId: string;
39 restApiId: string;
40 parentId: string;
41 pathPart: string;
42 },
43 never,
44 Providers
45 > {}
46
47 /**
48 * A path segment under a REST API resource tree.
49 *
50 * Resources form the URL hierarchy of a REST API: every path segment
51 * (`/items`, `/items/{id}`, `/{proxy+}`) is a `Resource` whose `parentId`
52 * points either at `api.rootResourceId` (for top-level paths) or at
53 * another `Resource`'s `resourceId` (for nested paths). Attach methods
54 * to a resource by passing its `resourceId` to `ApiGateway.Method`.
55 * ### Path resources
56 * **Example:** Top-level path
57 * ```typescript
58 * const items = yield* ApiGateway.Resource("Items", {
59 * restApi: api,
60 * parentId: api.rootResourceId,
61 * pathPart: "items",
62 * });
63 * ```
64 *
65 * **Example:** Nested path with a greedy proxy
66 * ```typescript
67 * const items = yield* ApiGateway.Resource("Items", {
68 * restApi: api,
69 * parentId: api.rootResourceId,
70 * pathPart: "items",
71 * });
72 *
73 * const anyItem = yield* ApiGateway.Resource("AnyItem", {
74 * restApi: api,
75 * parentId: items.resourceId,
76 * pathPart: "{proxy+}",
77 * });
78 * ```
79 *
80 * @resource
81 */
82 export const GatewayResource = ResourceFactory<ApiGatewayResource>("AWS.ApiGateway.Resource");
83
84 interface ApiGatewayResourceInputProps {
85 restApi?: RestApi;
86 restApiId?: Input<string>;
87 parentId: Input<string>;
88 pathPart: Input<string>;
89 }
90
91 /**
92 * User-facing wrapper. Accepts `restApi: RestApi` to register this resource
93 * as a binding on the API (so deployments wait for it transitively).
94 */
95 const ResourceImpl = (id: string, props: ApiGatewayResourceInputProps) =>
96 Effect.gen(function* () {
97 const { restApi, ...rest } = props;
98 const restApiId = rest.restApiId ?? restApi?.restApiId;
99 if (!restApiId) {
100 return yield* Effect.die(
101 "ApiGateway.Resource requires either `restApi` (preferred) or " + "explicit `restApiId`.",
102 );
103 }
104 const resource = yield* GatewayResource(id, {
105 ...rest,
106 restApiId,
107 } as any);
108 if (restApi) {
109 yield* restApi.bind`${resource}`({
110 kind: "resource",
111 resourceId: resource.resourceId,
112 parentId: resource.parentId,
113 pathPart: resource.pathPart,
114 });
115 }
116 return resource;
117 });
118
119 export const Resource = ResourceImpl;
120
121 export const ResourceProvider = () =>
122 Provider.effect(
123 GatewayResource,
124 Effect.gen(function* () {
125 return {
126 stables: ["resourceId", "restApiId", "parentId"] as const,
127 diff: Effect.fn(function* ({ news: newsIn, olds }) {
128 if (!isResolved(newsIn)) return;
129 const news = newsIn as Input.ResolveProps<ApiGatewayResourceProps>;
130 if (
131 news.restApiId !== olds.restApiId ||
132 news.pathPart !== olds.pathPart ||
133 news.parentId !== olds.parentId
134 ) {
135 return { action: "replace" } as const;
136 }
137 }),
138 list: () =>
139 Effect.gen(function* () {
140 // Enumerate parent RestApis, then list the resources under each.
141 const apiIds = yield* ag.getRestApis.pages({}).pipe(
142 Stream.runCollect,
143 Effect.map((chunk) =>
144 Array.from(chunk).flatMap((page) =>
145 (page.items ?? []).filter((api) => api.id != null).map((api) => api.id!),
146 ),
147 ),
148 );
149 const rows = yield* Effect.forEach(
150 apiIds,
151 (restApiId) =>
152 ag.getResources.pages({ restApiId }).pipe(
153 Stream.runCollect,
154 Effect.map((chunk) =>
155 Array.from(chunk).flatMap((page) =>
156 (page.items ?? [])
157 // The API root resource ("/") has no parentId/pathPart;
158 // it isn't a managed `Resource`, so skip it.
159 .filter((r) => r.id != null && r.parentId != null && r.pathPart != null)
160 .map((r) => ({
161 resourceId: r.id!,
162 restApiId,
163 parentId: r.parentId!,
164 pathPart: r.pathPart!,
165 })),
166 ),
167 ),
168 // A RestApi can vanish mid-enumeration; skip it.
169 Effect.catchTag("NotFoundException", () => Effect.succeed([])),
170 ),
171 { concurrency: 10 },
172 );
173 return rows.flat();
174 }),
175 read: Effect.fn(function* ({ output }) {
176 if (!output?.resourceId) return undefined;
177 const r = yield* ag
178 .getResource({
179 restApiId: output.restApiId,
180 resourceId: output.resourceId,
181 })
182 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
183 if (!r?.id) return undefined;
184 return {
185 resourceId: r.id,
186 restApiId: output.restApiId,
187 parentId: r.parentId!,
188 pathPart: r.pathPart!,
189 };
190 }),
191 reconcile: Effect.fn(function* ({ news: newsIn, output, session }) {
192 if (!isResolved(newsIn)) {
193 return yield* Effect.die("Resource props were not resolved");
194 }
195 const news = newsIn as Input.ResolveProps<ApiGatewayResourceProps>;
196 const restApiId = (output?.restApiId ?? news.restApiId) as string;
197
198 // Observe — fetch the live resource if we have a cached id. We
199 // never trust `output.pathPart` for diffing; we re-read the
200 // pathPart from cloud state every reconcile.
201 let observed = output?.resourceId
202 ? yield* ag
203 .getResource({
204 restApiId,
205 resourceId: output.resourceId,
206 })
207 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined))
208 : undefined;
209
210 // Ensure — create the resource if missing.
211 if (!observed?.id) {
212 const created = yield* ag.createResource({
213 restApiId: news.restApiId as string,
214 parentId: news.parentId as string,
215 pathPart: news.pathPart,
216 });
217 if (!created.id) {
218 return yield* Effect.die("createResource missing id");
219 }
220 yield* session.note(`Created API Gateway resource ${created.id} (${news.pathPart})`);
221 observed = yield* ag.getResource({
222 restApiId: news.restApiId as string,
223 resourceId: created.id,
224 });
225 }
226
227 const resourceId = observed.id!;
228
229 // Sync pathPart — observed ↔ desired. parentId moves are modeled
230 // as `replace` in `diff`, so we don't try to patch them here.
231 if (news.pathPart !== observed.pathPart) {
232 yield* ag.updateResource({
233 restApiId,
234 resourceId,
235 patchOperations: [{ op: "replace", path: "/pathPart", value: news.pathPart }],
236 });
237 yield* session.note(`Updated resource ${resourceId}`);
238 }
239
240 return {
241 resourceId,
242 restApiId,
243 parentId: observed.parentId!,
244 pathPart: news.pathPart,
245 };
246 }),
247 delete: Effect.fn(function* ({ output, session }) {
248 yield* ag
249 .deleteResource({
250 restApiId: output.restApiId,
251 resourceId: output.resourceId,
252 })
253 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
254 yield* session.note(`Deleted resource ${output.resourceId}`);
255 }),
256 };
257 }),
258 );