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

main
ts 326 lines 10.7 KB
Raw
1 import * as appsync from "@distilled.cloud/aws/appsync";
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 * as Effect from "effect/Effect";
7 import type { Providers } from "../Providers.ts";
8 import { retryConcurrentModification } from "./common.ts";
9 import type { AppSyncDataSource } from "./DataSource.ts";
10 import type { GraphqlApi } from "./GraphqlApi.ts";
11
12 /** The modern JavaScript resolver runtime. */
13 export const APPSYNC_JS: appsync.AppSyncRuntime = {
14 name: "APPSYNC_JS",
15 runtimeVersion: "1.0.0",
16 };
17
18 export interface ResolverProps {
19 /**
20 * ID of the GraphQL API. Usually derived from `api.apiId` by the
21 * {@link Resolver} wrapper.
22 */
23 apiId: string;
24 /**
25 * The schema type the resolver is attached to (e.g. `Query`,
26 * `Mutation`, or an object type). Changing it triggers a replacement.
27 */
28 typeName: string;
29 /**
30 * The field on {@link ResolverProps.typeName} this resolver serves.
31 * Changing it triggers a replacement.
32 */
33 fieldName: string;
34 /**
35 * Name of the data source a `UNIT` resolver targets. Not used by
36 * `PIPELINE` resolvers.
37 */
38 dataSourceName?: string;
39 /**
40 * The resolver kind.
41 * @default "UNIT"
42 */
43 kind?: "UNIT" | "PIPELINE";
44 /**
45 * `APPSYNC_JS` resolver code exporting `request(ctx)` and
46 * `response(ctx)`. When set, the runtime defaults to APPSYNC_JS 1.0.0.
47 */
48 code?: string;
49 /** VTL request mapping template (legacy alternative to `code`). */
50 requestMappingTemplate?: string;
51 /** VTL response mapping template (legacy alternative to `code`). */
52 responseMappingTemplate?: string;
53 /**
54 * Pipeline function IDs executed in order — required for `PIPELINE`
55 * resolvers. Pass `fn.functionId` outputs from {@link Function}.
56 */
57 pipelineFunctionIds?: string[];
58 /** Maximum batch size for batched Lambda invocations (0–2000). */
59 maxBatchSize?: number;
60 /** Per-resolver caching config (requires an API cache). */
61 cachingConfig?: appsync.CachingConfig;
62 }
63
64 export interface AppSyncResolver extends Resource<
65 "AWS.AppSync.Resolver",
66 ResolverProps,
67 {
68 /** The API this resolver belongs to. */
69 apiId: string;
70 /** The schema type the resolver is attached to. */
71 typeName: string;
72 /** The field the resolver serves. */
73 fieldName: string;
74 /** The resolver ARN. */
75 resolverArn: string;
76 /** The data source a UNIT resolver targets. */
77 dataSourceName: string | undefined;
78 /** The resolver kind. */
79 kind: "UNIT" | "PIPELINE";
80 },
81 never,
82 Providers
83 > {}
84
85 /**
86 * An AppSync resolver — attaches request/response logic to a schema field.
87 *
88 * `UNIT` resolvers target a single data source; `PIPELINE` resolvers run a
89 * sequence of {@link Function}s. The modern default is `APPSYNC_JS` code
90 * (a module exporting `request(ctx)` / `response(ctx)`); VTL mapping
91 * templates remain supported.
92 * ### Unit Resolvers
93 * **Example:** JavaScript unit resolver over a Lambda data source
94 * ```typescript
95 * const resolver = yield* AppSync.Resolver("AddResolver", {
96 * api,
97 * typeName: "Query",
98 * fieldName: "add",
99 * dataSource: lambdaDS,
100 * code: `
101 * export function request(ctx) {
102 * return { operation: "Invoke", payload: { args: ctx.args } };
103 * }
104 * export function response(ctx) {
105 * return ctx.result;
106 * }
107 * `,
108 * });
109 * ```
110 *
111 * ### Pipeline Resolvers
112 * **Example:** Pipeline resolver running one function
113 * ```typescript
114 * const fn = yield* AppSync.Function("Step", {
115 * api,
116 * dataSource: lambdaDS,
117 * code: fnCode,
118 * });
119 * const resolver = yield* AppSync.Resolver("PipelineResolver", {
120 * api,
121 * typeName: "Query",
122 * fieldName: "double",
123 * kind: "PIPELINE",
124 * pipelineFunctionIds: [fn.functionId],
125 * code: `
126 * export function request(ctx) { return {}; }
127 * export function response(ctx) { return ctx.prev.result; }
128 * `,
129 * });
130 * ```
131 *
132 * @resource
133 */
134 export const ResolverResource = Resource<AppSyncResolver>("AWS.AppSync.Resolver");
135
136 export interface ResolverInputProps extends Omit<
137 {
138 [K in keyof ResolverProps]?: Input<ResolverProps[K]>;
139 },
140 "apiId" | "typeName" | "fieldName" | "dataSourceName"
141 > {
142 /**
143 * The `GraphqlApi` this resolver belongs to (preferred). Alternatively
144 * pass a raw `apiId`.
145 */
146 api?: GraphqlApi;
147 apiId?: Input<string>;
148 typeName: Input<string>;
149 fieldName: Input<string>;
150 /**
151 * The data source a UNIT resolver targets (preferred). Alternatively
152 * pass a raw `dataSourceName`.
153 */
154 dataSource?: AppSyncDataSource;
155 dataSourceName?: Input<string>;
156 }
157
158 /**
159 * User-facing wrapper for the Resolver resource. Accepts `api: GraphqlApi`
160 * and `dataSource: DataSource` as the idiomatic way to wire a resolver.
161 */
162 export const Resolver = (id: string, props: ResolverInputProps) =>
163 Effect.gen(function* () {
164 const { api, dataSource, ...rest } = props;
165 const apiId = rest.apiId ?? api?.apiId;
166 if (!apiId) {
167 return yield* Effect.die(
168 "Resolver requires either `api` (preferred) or an explicit `apiId`.",
169 );
170 }
171 const dataSourceName = rest.dataSourceName ?? dataSource?.name;
172 return yield* ResolverResource(id, {
173 ...rest,
174 apiId,
175 dataSourceName,
176 } as any);
177 });
178
179 export const ResolverProvider = () =>
180 Provider.effect(
181 ResolverResource,
182 Effect.gen(function* () {
183 const getResolverSafe = (apiId: string, typeName: string, fieldName: string) =>
184 appsync.getResolver({ apiId, typeName, fieldName }).pipe(
185 Effect.map((response) => response.resolver),
186 Effect.catchTag("NotFoundException", () => Effect.undefined),
187 );
188
189 const desiredWire = (news: ResolverProps) => ({
190 dataSourceName: news.dataSourceName,
191 kind: news.kind ?? "UNIT",
192 code: news.code,
193 runtime: news.code !== undefined ? APPSYNC_JS : undefined,
194 requestMappingTemplate: news.requestMappingTemplate,
195 responseMappingTemplate: news.responseMappingTemplate,
196 pipelineConfig:
197 news.pipelineFunctionIds === undefined
198 ? undefined
199 : { functions: news.pipelineFunctionIds },
200 maxBatchSize: news.maxBatchSize,
201 cachingConfig: news.cachingConfig,
202 });
203
204 const surface = (resolver: {
205 dataSourceName?: string;
206 kind?: string;
207 code?: string;
208 runtime?: appsync.AppSyncRuntime;
209 requestMappingTemplate?: string;
210 responseMappingTemplate?: string;
211 pipelineConfig?: appsync.PipelineConfig;
212 maxBatchSize?: number;
213 cachingConfig?: appsync.CachingConfig;
214 }) =>
215 JSON.parse(
216 JSON.stringify({
217 dataSourceName: resolver.dataSourceName,
218 kind: resolver.kind ?? "UNIT",
219 code: resolver.code,
220 runtime: resolver.runtime,
221 requestMappingTemplate: resolver.requestMappingTemplate,
222 responseMappingTemplate: resolver.responseMappingTemplate,
223 pipelineFunctions: resolver.pipelineConfig?.functions ?? [],
224 maxBatchSize: resolver.maxBatchSize ?? 0,
225 cachingConfig: resolver.cachingConfig,
226 }),
227 );
228
229 const toAttributes = (
230 apiId: string,
231 resolver: appsync.Resolver,
232 ): AppSyncResolver["Attributes"] => ({
233 apiId,
234 typeName: resolver.typeName!,
235 fieldName: resolver.fieldName!,
236 resolverArn: resolver.resolverArn!,
237 dataSourceName: resolver.dataSourceName,
238 kind: (resolver.kind ?? "UNIT") as "UNIT" | "PIPELINE",
239 });
240
241 return ResolverResource.Provider.of({
242 stables: ["apiId", "typeName", "fieldName", "resolverArn"],
243
244 // Sub-resource keyed entirely by its GraphQL API (apiId/typeName) with no global
245 // enumeration API of its own — nuke reaches it through the parent's
246 // deletion, so enumeration returns empty per the ProviderService
247 // doctrine.
248 list: () => Effect.succeed([]),
249
250 read: Effect.fn(function* ({ olds, output }) {
251 const apiId = output?.apiId ?? olds?.apiId;
252 const typeName = output?.typeName ?? olds?.typeName;
253 const fieldName = output?.fieldName ?? olds?.fieldName;
254 if (apiId === undefined || typeName === undefined || fieldName === undefined) {
255 return undefined;
256 }
257 const resolver = yield* getResolverSafe(apiId, typeName, fieldName);
258 if (resolver?.resolverArn == null) return undefined;
259 return toAttributes(apiId, resolver);
260 }),
261
262 diff: Effect.fn(function* ({ news, olds }) {
263 if (!isResolved(news)) return undefined;
264 if (
265 news.apiId !== olds.apiId ||
266 news.typeName !== olds.typeName ||
267 news.fieldName !== olds.fieldName
268 ) {
269 return { action: "replace" } as const;
270 }
271 // data source / code / kind / pipeline converge via update
272 }),
273
274 reconcile: Effect.fn(function* ({ news, output, session }) {
275 const apiId = output?.apiId ?? news.apiId;
276 const typeName = news.typeName;
277 const fieldName = news.fieldName;
278 const desired = desiredWire(news);
279
280 // 1. OBSERVE
281 let observed = yield* getResolverSafe(apiId, typeName, fieldName);
282
283 if (observed?.resolverArn == null) {
284 // 2. ENSURE
285 const created = yield* retryConcurrentModification(
286 appsync.createResolver({
287 apiId,
288 typeName,
289 fieldName,
290 ...desired,
291 }),
292 );
293 observed = created.resolver!;
294 yield* session.note(`Created resolver ${typeName}.${fieldName}`);
295 } else if (!deepEqual(surface(observed), surface(desired))) {
296 // 3. SYNC
297 const updated = yield* retryConcurrentModification(
298 appsync.updateResolver({
299 apiId,
300 typeName,
301 fieldName,
302 ...desired,
303 }),
304 );
305 observed = updated.resolver ?? observed;
306 yield* session.note(`Updated resolver ${typeName}.${fieldName}`);
307 }
308
309 yield* session.note(`${typeName}.${fieldName}`);
310 return toAttributes(apiId, observed);
311 }),
312
313 delete: Effect.fn(function* ({ output }) {
314 yield* retryConcurrentModification(
315 appsync
316 .deleteResolver({
317 apiId: output.apiId,
318 typeName: output.typeName,
319 fieldName: output.fieldName,
320 })
321 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
322 );
323 }),
324 });
325 }),
326 );