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

main
ts 233 lines 9.08 KB
Raw
1 import { expect } from "bun:test";
2 import * as Neon from "@alchemy.run/neon";
3 import * as SQL from "@alchemy.run/sql/Postgres";
4 import * as Test from "@alchemy.run/test/Bun";
5 import {
6 DeleteObjectCommand,
7 ListObjectsV2Command,
8 PutObjectCommand,
9 S3Client,
10 } from "@aws-sdk/client-s3";
11 import * as SDK from "@distilled.cloud/neon";
12 import * as Alchemy from "alchemy";
13 import * as Effect from "effect/Effect";
14 import * as Redacted from "effect/Redacted";
15
16 const { test } = Test.make({
17 providers: Neon.providers(),
18 state: Alchemy.localState(),
19 profile: process.env.ALCHEMY_PROFILE ?? "testing",
20 stage: "test-neon-compute-preview-isolation",
21 });
22 const configured = [
23 "PARENT_PROJECT_ID",
24 "PARENT_BRANCH_ID",
25 "PARENT_BUCKET_NAME",
26 "PREVIEW_BRANCH_ID",
27 ].every((name) => !!process.env[name]);
28
29 const makeStorageClient = Effect.fn(function* (
30 config: {
31 endpoint: string;
32 region: string;
33 accessKeyId: string;
34 secretAccessKey: Redacted.Redacted<string>;
35 },
36 bucket: string,
37 ) {
38 const client = yield* Effect.acquireRelease(
39 Effect.sync(
40 () =>
41 new S3Client({
42 endpoint: config.endpoint,
43 region: config.region,
44 forcePathStyle: true,
45 maxAttempts: 1,
46 requestChecksumCalculation: "WHEN_REQUIRED",
47 credentials: {
48 accessKeyId: config.accessKeyId,
49 secretAccessKey: Redacted.value(config.secretAccessKey),
50 },
51 }),
52 ),
53 (client) => Effect.sync(() => client.destroy()),
54 );
55 return {
56 metadata: (key: string) =>
57 Effect.tryPromise(() =>
58 client.send(new ListObjectsV2Command({ Bucket: bucket, Prefix: key, MaxKeys: 1 })),
59 ).pipe(
60 Effect.map((page) => {
61 const object = page.Contents?.find((object) => object.Key === key);
62 return object ? { ETag: object.ETag, ContentLength: object.Size } : undefined;
63 }),
64 ),
65 put: (key: string, body: string, options: { ContentType: string }) =>
66 Effect.tryPromise(() =>
67 client.send(
68 new PutObjectCommand({
69 Bucket: bucket,
70 Key: key,
71 Body: body,
72 ...options,
73 }),
74 ),
75 ),
76 delete: (key: string) =>
77 Effect.tryPromise(() => client.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }))),
78 };
79 });
80
81 const database = Effect.fn(function* (scope: { project_id: string; branch_id: string }) {
82 const databases = yield* SDK.listProjectBranchDatabases(scope);
83 const db = databases.databases.find((db) => db.name === "neondb");
84 if (!db) return yield* Effect.fail(new Error("Expected the tutorial neondb database"));
85 const connection = yield* SDK.getConnectionURI({
86 ...scope,
87 database_name: db.name,
88 role_name: db.owner_name,
89 });
90 return yield* SQL.Postgres({ url: Redacted.make(connection.uri) });
91 });
92
93 test.provider.skipIf(!configured)(
94 "preview explicitly enables its own upload trigger",
95 (stack) =>
96 Effect.gen(function* () {
97 yield* stack.destroy();
98 const childTriggers = yield* SDK.listProjectBranchTriggers({
99 project_id: process.env.PARENT_PROJECT_ID!,
100 branch_id: process.env.PREVIEW_BRANCH_ID!,
101 });
102 expect(
103 childTriggers.triggers.some(
104 (trigger) => trigger.name === "PreviewUploads" && trigger.enabled && !trigger.inherited,
105 ),
106 ).toBe(true);
107 yield* stack.destroy();
108 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie))),
109 { timeout: 120_000 },
110 );
111
112 test.provider.skipIf(!configured)(
113 "preview writes leave parent data and backend configuration unchanged",
114 (stack) =>
115 Effect.gen(function* () {
116 yield* stack.destroy();
117 const projectId = process.env.PARENT_PROJECT_ID!;
118 const parentId = process.env.PARENT_BRANCH_ID!;
119 const childId = process.env.PREVIEW_BRANCH_ID!;
120 const bucket = process.env.PARENT_BUCKET_NAME!;
121 expect(childId).not.toBe(parentId);
122 const parent = { project_id: projectId, branch_id: parentId };
123 const child = { project_id: projectId, branch_id: childId };
124 const observedChild = yield* SDK.getProjectBranch(child);
125 expect(observedChild.branch.parent_id).toBe(parentId);
126 const parentFunctions = yield* SDK.listProjectBranchFunctions({
127 ...parent,
128 limit: 1000,
129 });
130 const childFunctions = yield* SDK.listProjectBranchFunctions({
131 ...child,
132 limit: 1000,
133 });
134 expect(parentFunctions.functions.length).toBeGreaterThan(0);
135 expect(parentFunctions.pagination?.next).toBeUndefined();
136 expect(childFunctions.pagination?.next).toBeUndefined();
137 for (const fn of parentFunctions.functions)
138 expect(childFunctions.functions.some((inherited) => inherited.slug === fn.slug)).toBe(true);
139 const parentTriggers = yield* SDK.listProjectBranchTriggers(parent);
140 const childTriggers = yield* SDK.listProjectBranchTriggers(child);
141 const inherited = childTriggers.triggers.filter((trigger) => trigger.inherited);
142 expect(inherited.length).toBeGreaterThan(0);
143 expect(inherited.every((trigger) => !trigger.enabled)).toBe(true);
144 const parentDomains = yield* SDK.listProjectBranchCustomDomains(parent);
145 const childDomains = yield* SDK.listProjectBranchCustomDomains(child);
146 expect(childDomains.custom_domains).toEqual([]);
147 const credentials = yield* stack.deploy(
148 Effect.gen(function* () {
149 return {
150 parent: yield* Neon.Credential("ParentRead", {
151 branch: { projectId, branchId: parentId },
152 scopes: ["storage:read"],
153 }),
154 child: yield* Neon.Credential("ChildWrite", {
155 branch: { projectId, branchId: childId },
156 scopes: ["storage:read", "storage:write"],
157 }),
158 };
159 }),
160 );
161 const parentStorage = yield* SDK.getProjectBranchStorage(parent);
162 const childStorage = yield* SDK.getProjectBranchStorage(child);
163 const parentFiles = yield* makeStorageClient(
164 {
165 endpoint: parentStorage.s3_endpoint,
166 region: parentStorage.region,
167 accessKeyId: credentials.parent.tokenId,
168 secretAccessKey: credentials.parent.s3SecretAccessKey,
169 },
170 bucket,
171 );
172 const childFiles = yield* makeStorageClient(
173 {
174 endpoint: childStorage.s3_endpoint,
175 region: childStorage.region,
176 accessKeyId: credentials.child.tokenId,
177 secretAccessKey: credentials.child.s3SecretAccessKey,
178 },
179 bucket,
180 );
181 const parentSql = yield* database(parent);
182 const childSql = yield* database(child);
183 const baseline = yield* parentSql<{
184 id: string;
185 object_key: string;
186 status: string;
187 }>`SELECT id, object_key, status FROM uploads ORDER BY id`;
188 const sample = baseline.find((row) => row.status === "ready");
189 if (!sample)
190 return yield* Effect.fail(
191 new Error(
192 "Process a parent upload before forking; inherited file coverage must not be vacuous",
193 ),
194 );
195 expect((yield* childSql`SELECT id FROM uploads WHERE id = ${sample.id}`).length).toBe(1);
196 const original = yield* parentFiles.metadata(sample.object_key);
197 expect(original).toBeDefined();
198 expect((yield* childFiles.metadata(sample.object_key))?.ETag).toBe(original?.ETag);
199 const key = "tutorial-preview/isolation-probe.txt";
200 const id = "20000000-0000-4000-8000-000000000002";
201 expect(yield* parentFiles.metadata(key)).toBeUndefined();
202 expect(yield* childFiles.metadata(key)).toBeUndefined();
203 expect((yield* childSql`SELECT id FROM uploads WHERE id = ${id}`).length).toBe(0);
204 yield* Effect.gen(function* () {
205 yield* childFiles.put(key, "child only", { ContentType: "text/plain" });
206 yield* childSql`INSERT INTO uploads (id, owner_id, object_key, filename, content_type, expected_bytes)
207 VALUES (${id}, 'preview-isolation-probe', ${key}, 'isolation-probe.txt', 'text/plain', 10)`;
208 expect((yield* childFiles.metadata(key))?.ContentLength).toBe(10);
209 expect((yield* childSql`SELECT id FROM uploads WHERE id = ${id}`).length).toBe(1);
210 expect(yield* parentFiles.metadata(key)).toBeUndefined();
211 expect(yield* parentSql`SELECT id, object_key, status FROM uploads ORDER BY id`).toEqual(
212 baseline,
213 );
214 expect(yield* SDK.listProjectBranchTriggers(parent)).toEqual(parentTriggers);
215 expect(yield* SDK.listProjectBranchCustomDomains(parent)).toEqual(parentDomains);
216 }).pipe(
217 Effect.ensuring(
218 Effect.gen(function* () {
219 yield* childFiles.delete(key);
220 yield* childSql`DELETE FROM uploads WHERE id = ${id} AND owner_id = 'preview-isolation-probe'`;
221 }).pipe(Effect.orDie),
222 ),
223 );
224 yield* stack.destroy();
225 const active = (yield* SDK.listCredentials(child)).credentials.filter(
226 (credential) => !credential.revoked_at,
227 );
228 expect(active.some((credential) => credential.token_id === credentials.child.tokenId)).toBe(
229 false,
230 );
231 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie))),
232 { timeout: 120_000 },
233 );