@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 191 lines 6.01 KB
Raw
1 import { fileURLToPath } from "node:url";
2 import * as AWS from "@alchemy.run/aws";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as Duration from "effect/Duration";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import * as Redacted from "effect/Redacted";
10 import * as Schedule from "effect/Schedule";
11
12 const { test } = Test.make({ providers: AWS.providers() });
13
14 const resolverHandlerPath = fileURLToPath(new URL("./resolver-handler.ts", import.meta.url));
15
16 /**
17 * The unit-resolver code: forward the field name + args to the Lambda
18 * data source and surface the invocation result as the field value.
19 */
20 const LAMBDA_RESOLVER_CODE = `
21 export function request(ctx) {
22 return {
23 operation: "Invoke",
24 payload: { field: ctx.info.fieldName, args: ctx.args },
25 };
26 }
27 export function response(ctx) {
28 return ctx.result;
29 }
30 `;
31
32 /** Pipeline step: same Lambda invocation, packaged as an AppSync Function. */
33 const PIPELINE_STEP_CODE = LAMBDA_RESOLVER_CODE;
34
35 /** Pipeline resolver: run the steps and return the last step's result. */
36 const PIPELINE_RESOLVER_CODE = `
37 export function request(ctx) {
38 return {};
39 }
40 export function response(ctx) {
41 return ctx.prev.result;
42 }
43 `;
44
45 const SCHEMA = `
46 type Query {
47 add(a: Int!, b: Int!): Int!
48 greet(name: String!): String!
49 double(n: Int!): Int!
50 }
51 schema { query: Query }
52 `;
53
54 /** Fresh AppSync endpoints/keys propagate within a few seconds. */
55 const edgePropagationRetry = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
56 effect.pipe(
57 Effect.retry({
58 schedule: Schedule.max([
59 Schedule.exponential(500).pipe(
60 Schedule.modifyDelay(({ duration }) =>
61 Effect.succeed(
62 Duration.isGreaterThan(duration, Duration.seconds(5))
63 ? Duration.seconds(5)
64 : duration,
65 ),
66 ),
67 ),
68 Schedule.recurs(10),
69 ]),
70 }),
71 );
72
73 const graphql = (url: string, apiKey: string, query: string) =>
74 HttpClient.execute(
75 HttpClientRequest.post(url).pipe(
76 HttpClientRequest.setHeader("x-api-key", apiKey),
77 HttpClientRequest.bodyJsonUnsafe({ query }),
78 ),
79 );
80
81 test.provider(
82 "GraphQL API over a Lambda data source (unit + pipeline resolvers, api key auth)",
83 (stack) =>
84 Effect.gen(function* () {
85 yield* stack.destroy();
86
87 const out = yield* stack.deploy(
88 Effect.gen(function* () {
89 const fn = yield* AWS.Lambda.Function("ResolverFn", {
90 main: resolverHandlerPath,
91 handler: "handler",
92 isExternal: true,
93 functionUrl: false,
94 });
95 const api = yield* AWS.AppSync.GraphqlApi("E2EApi", {
96 schema: SCHEMA,
97 });
98 const lambdaDS = yield* AWS.AppSync.DataSource("LambdaDS", {
99 api,
100 type: "AWS_LAMBDA",
101 lambdaConfig: { lambdaFunctionArn: fn.functionArn },
102 });
103 // UNIT resolvers with APPSYNC_JS runtime.
104 yield* AWS.AppSync.Resolver("AddResolver", {
105 api,
106 typeName: "Query",
107 fieldName: "add",
108 dataSource: lambdaDS,
109 code: LAMBDA_RESOLVER_CODE,
110 });
111 yield* AWS.AppSync.Resolver("GreetResolver", {
112 api,
113 typeName: "Query",
114 fieldName: "greet",
115 dataSource: lambdaDS,
116 code: LAMBDA_RESOLVER_CODE,
117 });
118 // PIPELINE resolver running one AppSync Function step.
119 const step = yield* AWS.AppSync.Function("InvokeStep", {
120 api,
121 dataSource: lambdaDS,
122 code: PIPELINE_STEP_CODE,
123 });
124 yield* AWS.AppSync.Resolver("DoubleResolver", {
125 api,
126 typeName: "Query",
127 fieldName: "double",
128 kind: "PIPELINE",
129 pipelineFunctionIds: [step.functionId],
130 code: PIPELINE_RESOLVER_CODE,
131 });
132 const key = yield* AWS.AppSync.ApiKey("Key", { api });
133 return {
134 apiId: api.apiId,
135 url: api.graphqlUrl,
136 apiKey: key.id,
137 };
138 }),
139 );
140
141 const apiKey = Redacted.value(out.apiKey);
142 expect(out.url).toContain("appsync-api");
143 expect(apiKey).toMatch(/^da2-/);
144
145 // 1. Unit resolver: the result is computed inside the Lambda.
146 const add = yield* edgePropagationRetry(
147 graphql(out.url, apiKey, "query { add(a: 2, b: 3) }").pipe(
148 Effect.flatMap((response) =>
149 response.status === 200
150 ? response.json
151 : Effect.fail(new Error(`add returned ${response.status}`)),
152 ),
153 Effect.flatMap((body: any) =>
154 body?.data?.add === undefined
155 ? Effect.fail(new Error(`no data.add: ${JSON.stringify(body)}`))
156 : Effect.succeed(body),
157 ),
158 ),
159 );
160 expect((add as any).data.add).toBe(5);
161
162 // 2. Unit resolver with a string result.
163 const greet = (yield* graphql(out.url, apiKey, 'query { greet(name: "Alchemy") }').pipe(
164 Effect.flatMap((response) => response.json),
165 )) as any;
166 expect(greet.data.greet).toBe("Hello, Alchemy! (from Lambda)");
167
168 // 3. Pipeline resolver: the step's Lambda result flows through
169 // ctx.prev.result.
170 const double = (yield* graphql(out.url, apiKey, "query { double(n: 21) }").pipe(
171 Effect.flatMap((response) => response.json),
172 )) as any;
173 expect(double.data.double).toBe(42);
174
175 // 4. Requests without the api key are rejected.
176 const unauthorized = yield* HttpClient.execute(
177 HttpClientRequest.post(out.url).pipe(
178 HttpClientRequest.bodyJsonUnsafe({
179 query: "query { add(a: 1, b: 1) }",
180 }),
181 ),
182 );
183 expect(unauthorized.status).toBeGreaterThanOrEqual(401);
184
185 yield* stack.destroy();
186 }),
187 {
188 tags: ["provider:aws", "provider:aws:appsync", "provider:aws:lambda", "live"],
189 timeout: 600_000,
190 },
191 );