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

main
ts 482 lines 16.7 KB
Raw
1 import * as appsync from "@distilled.cloud/aws/appsync";
2 import * as iam from "@distilled.cloud/aws/iam";
3 import { deepEqual, isResolved } from "alchemy/Diff";
4 import type { Input } from "alchemy/Input";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { createInternalTags } from "alchemy/Tags";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import { AWSEnvironment } from "../Environment.ts";
12 import type { PolicyStatement } from "../IAM/Policy.ts";
13 import type { Providers } from "../Providers.ts";
14 import {
15 retryConcurrentModification,
16 retryWhileRolePropagates,
17 sanitizeAppSyncName,
18 } from "./common.ts";
19 import type { GraphqlApi } from "./GraphqlApi.ts";
20
21 /** The data source types supported by the resource. */
22 export type DataSourceType =
23 | "NONE"
24 | "AWS_LAMBDA"
25 | "AMAZON_DYNAMODB"
26 | "HTTP"
27 | "AMAZON_EVENTBRIDGE";
28
29 export interface LambdaDataSourceConfig {
30 /** ARN of the Lambda function this data source invokes. */
31 lambdaFunctionArn: string;
32 }
33
34 export interface DynamodbDataSourceConfig {
35 /** Name of the DynamoDB table. */
36 tableName: string;
37 /**
38 * Region the table lives in.
39 * @default the ambient AWS region
40 */
41 awsRegion?: string;
42 /** Use the caller's credentials instead of the service role. */
43 useCallerCredentials?: boolean;
44 /** Whether conflict detection (versioning) is enabled. */
45 versioned?: boolean;
46 }
47
48 export interface HttpDataSourceConfig {
49 /** The HTTP endpoint, e.g. `https://api.example.com`. */
50 endpoint: string;
51 }
52
53 export interface DataSourceProps {
54 /**
55 * ID of the GraphQL API this data source belongs to. Usually derived
56 * from `api.apiId` by the {@link DataSource} wrapper.
57 */
58 apiId: string;
59 /**
60 * Name of the data source (`[_A-Za-z][_0-9A-Za-z]*` — no dashes). If
61 * omitted, a deterministic name is generated from the app, stage, and
62 * logical ID (dashes sanitized to underscores). Changing the name
63 * triggers a replacement.
64 */
65 name?: string;
66 /** Description of the data source. */
67 description?: string;
68 /**
69 * The data source type. `NONE` (local compute), `AWS_LAMBDA`,
70 * `AMAZON_DYNAMODB`, `HTTP`, or `AMAZON_EVENTBRIDGE`.
71 */
72 type: DataSourceType;
73 /**
74 * The ARN of an existing IAM role AppSync assumes to access the target.
75 * When omitted (and the type needs one), a service role is created
76 * automatically with `appsync.amazonaws.com` trust and least-privilege
77 * access to the configured target.
78 */
79 serviceRoleArn?: string;
80 /**
81 * Additional IAM policy statements attached to the auto-created service
82 * role (ignored when {@link DataSourceProps.serviceRoleArn} is provided).
83 */
84 policyStatements?: PolicyStatement[];
85 /** Lambda target — required when `type` is `AWS_LAMBDA`. */
86 lambdaConfig?: LambdaDataSourceConfig;
87 /** DynamoDB target — required when `type` is `AMAZON_DYNAMODB`. */
88 dynamodbConfig?: DynamodbDataSourceConfig;
89 /** HTTP target — required when `type` is `HTTP`. */
90 httpConfig?: HttpDataSourceConfig;
91 }
92
93 export interface AppSyncDataSource extends Resource<
94 "AWS.AppSync.DataSource",
95 DataSourceProps,
96 {
97 /** The API this data source belongs to. */
98 apiId: string;
99 /** The data source name (referenced by resolvers and functions). */
100 name: string;
101 /** The data source ARN. */
102 dataSourceArn: string;
103 /** The data source type. */
104 type: DataSourceType;
105 /** The service role AppSync assumes, if any. */
106 serviceRoleArn: string | undefined;
107 /**
108 * Name of the auto-created service role. `undefined` when an explicit
109 * {@link DataSourceProps.serviceRoleArn} is used or no role is needed.
110 */
111 roleName: string | undefined;
112 },
113 never,
114 Providers
115 > {}
116
117 /**
118 * An AppSync data source — the target a resolver reads from or writes to.
119 *
120 * For `AWS_LAMBDA` and `AMAZON_DYNAMODB` targets a least-privilege service
121 * role is created automatically (unless an explicit `serviceRoleArn` is
122 * given): `lambda:InvokeFunction` on the function, or the DynamoDB
123 * read/write actions on the table and its indexes.
124 * ### Creating Data Sources
125 * **Example:** Lambda data source (auto-created invoke role)
126 * ```typescript
127 * const ds = yield* AppSync.DataSource("LambdaDS", {
128 * api,
129 * type: "AWS_LAMBDA",
130 * lambdaConfig: { lambdaFunctionArn: fn.functionArn },
131 * });
132 * ```
133 *
134 * **Example:** NONE data source (local compute)
135 * ```typescript
136 * const local = yield* AppSync.DataSource("Local", {
137 * api,
138 * type: "NONE",
139 * });
140 * ```
141 *
142 * **Example:** DynamoDB data source
143 * ```typescript
144 * const ds = yield* AppSync.DataSource("TableDS", {
145 * api,
146 * type: "AMAZON_DYNAMODB",
147 * dynamodbConfig: { tableName: table.tableName },
148 * });
149 * ```
150 *
151 * @resource
152 */
153 export const DataSourceResource = Resource<AppSyncDataSource>("AWS.AppSync.DataSource");
154
155 export interface DataSourceInputProps extends Omit<
156 {
157 [K in keyof DataSourceProps]?: Input<DataSourceProps[K]>;
158 },
159 "apiId" | "type"
160 > {
161 /**
162 * The `GraphqlApi` this data source belongs to (preferred). Alternatively
163 * pass a raw `apiId`.
164 */
165 api?: GraphqlApi;
166 apiId?: Input<string>;
167 type: Input<DataSourceType>;
168 }
169
170 /**
171 * User-facing wrapper for the DataSource resource. Accepts `api: GraphqlApi`
172 * as the idiomatic way to attach a data source to an API.
173 */
174 export const DataSource = (id: string, props: DataSourceInputProps) =>
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 "DataSource requires either `api` (preferred) or an explicit `apiId`.",
181 );
182 }
183 return yield* DataSourceResource(id, { ...rest, apiId } as any);
184 });
185
186 export const DataSourceProvider = () =>
187 Provider.effect(
188 DataSourceResource,
189 Effect.gen(function* () {
190 const createName = Effect.fn(function* (id: string, props: Pick<DataSourceProps, "name">) {
191 return props.name ?? sanitizeAppSyncName(yield* createPhysicalName({ id, maxLength: 64 }));
192 });
193
194 const getDataSourceSafe = (apiId: string, name: string) =>
195 appsync.getDataSource({ apiId, name }).pipe(
196 Effect.map((response) => response.dataSource),
197 Effect.catchTag("NotFoundException", () => Effect.undefined),
198 );
199
200 /**
201 * Least-privilege statements for the auto-created service role,
202 * derived from the configured target.
203 */
204 const buildRolePolicyStatements = (
205 news: DataSourceProps,
206 region: string,
207 accountId: string,
208 ): PolicyStatement[] => {
209 const statements: PolicyStatement[] = [];
210 if (news.type === "AWS_LAMBDA" && news.lambdaConfig !== undefined) {
211 const arn = news.lambdaConfig.lambdaFunctionArn;
212 statements.push({
213 Effect: "Allow",
214 Action: ["lambda:InvokeFunction"],
215 Resource: /:function:[^:]+:/.test(arn) ? [arn] : [arn, `${arn}:*`],
216 });
217 }
218 if (news.type === "AMAZON_DYNAMODB" && news.dynamodbConfig !== undefined) {
219 const tableRegion = news.dynamodbConfig.awsRegion ?? region;
220 const tableArn = `arn:aws:dynamodb:${tableRegion}:${accountId}:table/${news.dynamodbConfig.tableName}`;
221 statements.push({
222 Effect: "Allow",
223 Action: [
224 "dynamodb:BatchGetItem",
225 "dynamodb:BatchWriteItem",
226 "dynamodb:ConditionCheckItem",
227 "dynamodb:DeleteItem",
228 "dynamodb:GetItem",
229 "dynamodb:PutItem",
230 "dynamodb:Query",
231 "dynamodb:Scan",
232 "dynamodb:UpdateItem",
233 ],
234 Resource: [tableArn, `${tableArn}/index/*`],
235 });
236 }
237 statements.push(...(news.policyStatements ?? []));
238 return statements;
239 };
240
241 const needsServiceRole = (news: DataSourceProps): boolean =>
242 news.type === "AWS_LAMBDA" ||
243 news.type === "AMAZON_DYNAMODB" ||
244 news.type === "AMAZON_EVENTBRIDGE";
245
246 /**
247 * Ensure the auto-created service role exists with the
248 * `appsync.amazonaws.com` trust policy and the desired inline
249 * policy. Idempotent across reconciles.
250 */
251 const ensureServiceRole = Effect.fn(function* ({
252 id,
253 roleName,
254 statements,
255 }: {
256 id: string;
257 roleName: string;
258 statements: PolicyStatement[];
259 }) {
260 const tags = yield* createInternalTags(id);
261 const role = yield* iam
262 .createRole({
263 RoleName: roleName,
264 AssumeRolePolicyDocument: JSON.stringify({
265 Version: "2012-10-17",
266 Statement: [
267 {
268 Effect: "Allow",
269 Principal: { Service: "appsync.amazonaws.com" },
270 Action: "sts:AssumeRole",
271 },
272 ],
273 }),
274 Tags: Object.entries(tags).map(([Key, Value]) => ({ Key, Value })),
275 })
276 .pipe(
277 Effect.catchTag("EntityAlreadyExistsException", () =>
278 iam.getRole({ RoleName: roleName }),
279 ),
280 );
281
282 if (statements.length > 0) {
283 yield* iam.putRolePolicy({
284 RoleName: roleName,
285 PolicyName: `${roleName}-policy`,
286 PolicyDocument: JSON.stringify({
287 Version: "2012-10-17",
288 Statement: statements,
289 }),
290 });
291 } else {
292 yield* iam
293 .deleteRolePolicy({
294 RoleName: roleName,
295 PolicyName: `${roleName}-policy`,
296 })
297 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
298 }
299
300 return role.Role.Arn;
301 });
302
303 /** Delete the auto-created service role and its inline policies. */
304 const deleteServiceRole = Effect.fn(function* (roleName: string) {
305 yield* iam.listRolePolicies.items({ RoleName: roleName }).pipe(
306 Stream.mapEffect((policyName) =>
307 iam
308 .deleteRolePolicy({
309 RoleName: roleName,
310 PolicyName: policyName,
311 })
312 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)),
313 ),
314 Stream.runDrain,
315 Effect.catchTag("NoSuchEntityException", () => Effect.void),
316 );
317 yield* iam
318 .deleteRole({ RoleName: roleName })
319 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
320 });
321
322 const toWireConfigs = (news: DataSourceProps, region: string) => ({
323 lambdaConfig: news.lambdaConfig,
324 dynamodbConfig:
325 news.dynamodbConfig === undefined
326 ? undefined
327 : {
328 tableName: news.dynamodbConfig.tableName,
329 awsRegion: news.dynamodbConfig.awsRegion ?? region,
330 useCallerCredentials: news.dynamodbConfig.useCallerCredentials,
331 versioned: news.dynamodbConfig.versioned,
332 },
333 httpConfig: news.httpConfig,
334 });
335
336 const toAttributes = (
337 apiId: string,
338 ds: appsync.DataSource,
339 roleName: string | undefined,
340 ): AppSyncDataSource["Attributes"] => ({
341 apiId,
342 name: ds.name!,
343 dataSourceArn: ds.dataSourceArn!,
344 type: ds.type as DataSourceType,
345 serviceRoleArn: ds.serviceRoleArn,
346 roleName,
347 });
348
349 return DataSourceResource.Provider.of({
350 stables: ["apiId", "name", "dataSourceArn"],
351
352 // Sub-resource keyed entirely by its GraphQL API (apiId) with no global
353 // enumeration API of its own — nuke reaches it through the parent's
354 // deletion, so enumeration returns empty per the ProviderService
355 // doctrine.
356 list: () => Effect.succeed([]),
357
358 read: Effect.fn(function* ({ id, olds, output }) {
359 const apiId = output?.apiId ?? olds?.apiId;
360 if (apiId === undefined) return undefined;
361 const name = output?.name ?? (yield* createName(id, olds ?? {}));
362 const ds = yield* getDataSourceSafe(apiId, name);
363 if (ds?.name == null) return undefined;
364 return toAttributes(apiId, ds, output?.roleName);
365 }),
366
367 diff: Effect.fn(function* ({ id, news, olds }) {
368 if (!isResolved(news)) return undefined;
369 const oldName = yield* createName(id, olds ?? {});
370 const newName = yield* createName(id, news ?? {});
371 if (news.apiId !== olds.apiId || oldName !== newName) {
372 return { action: "replace" } as const;
373 }
374 // type/config/role converge via updateDataSource
375 }),
376
377 reconcile: Effect.fn(function* ({ id, news, output, session }) {
378 const { region, accountId } = yield* AWSEnvironment.current;
379 const apiId = output?.apiId ?? news.apiId;
380 const name = output?.name ?? (yield* createName(id, news));
381 const configs = toWireConfigs(news, region);
382
383 // Ensure the service role first — the data source cannot point
384 // at a Lambda/DynamoDB target without one.
385 let serviceRoleArn = news.serviceRoleArn;
386 let roleName: string | undefined;
387 if (serviceRoleArn === undefined && needsServiceRole(news)) {
388 roleName = yield* createPhysicalName({ id, maxLength: 64 });
389 serviceRoleArn = yield* ensureServiceRole({
390 id,
391 roleName,
392 statements: buildRolePolicyStatements(news, region, accountId),
393 });
394 }
395
396 // 1. OBSERVE
397 let observed = yield* getDataSourceSafe(apiId, name);
398
399 // 2. ENSURE — a fresh role can take a few seconds to become
400 // assumable by AppSync.
401 if (observed?.name == null) {
402 const created = yield* appsync
403 .createDataSource({
404 apiId,
405 name,
406 description: news.description,
407 type: news.type,
408 serviceRoleArn,
409 ...configs,
410 })
411 .pipe(retryConcurrentModification, retryWhileRolePropagates);
412 observed = created.dataSource!;
413 yield* session.note(`Created data source ${name}`);
414 } else {
415 // 3. SYNC — single update when the observed surface drifted.
416 const surface = (ds: {
417 description?: string;
418 type?: string;
419 serviceRoleArn?: string;
420 lambdaConfig?: appsync.LambdaDataSourceConfig;
421 dynamodbConfig?: appsync.DynamodbDataSourceConfig;
422 httpConfig?: appsync.HttpDataSourceConfig;
423 }) =>
424 JSON.parse(
425 JSON.stringify({
426 description: ds.description,
427 type: ds.type,
428 serviceRoleArn: ds.serviceRoleArn,
429 lambdaConfig: ds.lambdaConfig,
430 // AWS normalizes optional booleans into the response;
431 // mirror the defaults so no-ops stay no-ops.
432 dynamodbConfig:
433 ds.dynamodbConfig === undefined
434 ? undefined
435 : {
436 tableName: ds.dynamodbConfig.tableName,
437 awsRegion: ds.dynamodbConfig.awsRegion,
438 useCallerCredentials: ds.dynamodbConfig.useCallerCredentials ?? false,
439 versioned: ds.dynamodbConfig.versioned ?? false,
440 },
441 httpConfig: ds.httpConfig,
442 }),
443 );
444 const desired = surface({
445 description: news.description,
446 type: news.type,
447 serviceRoleArn,
448 ...configs,
449 });
450 if (!deepEqual(surface(observed), desired)) {
451 const updated = yield* appsync
452 .updateDataSource({
453 apiId,
454 name,
455 description: news.description,
456 type: news.type,
457 serviceRoleArn,
458 ...configs,
459 })
460 .pipe(retryConcurrentModification, retryWhileRolePropagates);
461 observed = updated.dataSource ?? observed;
462 yield* session.note(`Updated data source ${name}`);
463 }
464 }
465
466 yield* session.note(name);
467 return toAttributes(apiId, observed, roleName);
468 }),
469
470 delete: Effect.fn(function* ({ output }) {
471 yield* retryConcurrentModification(
472 appsync
473 .deleteDataSource({ apiId: output.apiId, name: output.name })
474 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
475 );
476 if (output.roleName !== undefined) {
477 yield* deleteServiceRole(output.roleName);
478 }
479 }),
480 });
481 }),
482 );