Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion packages/cli/src/actions/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ async function createDialect(provider: string, databaseUrl: string, outputPath:
}
}

function startServer(client: ClientContract<any, any>, schema: any, options: Options) {
export function createProxyApp(client: ClientContract<any, any>, schema: any): express.Application {
const app = express();
app.use(cors());
app.use(express.json({ limit: '5mb' }));
Expand All @@ -216,6 +216,12 @@ function startServer(client: ClientContract<any, any>, schema: any, options: Opt
res.json({ ...schema, zenstackVersion: getVersion() });
});

return app;
}

function startServer(client: ClientContract<any, any>, schema: any, options: Options) {
const app = createProxyApp(client, schema);

const server = app.listen(options.port, () => {
console.log(`ZenStack proxy server is running on port: ${options.port}`);
console.log(`You can visit ZenStack Studio at: ${colors.blue('https://studio.zenstack.dev')}`);
Expand Down
170 changes: 170 additions & 0 deletions packages/cli/test/proxy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { createTestClient } from '@zenstackhq/testtools';
import http from 'node:http';
import { afterEach, describe, expect, it } from 'vitest';
import { createProxyApp } from '../src/actions/proxy';

describe('CLI proxy tests', () => {
let server: http.Server | undefined;

afterEach(async () => {
await new Promise<void>((resolve) => {
if (server) {
server.close(() => resolve());
server = undefined;
} else {
resolve();
}
});
});
Comment on lines +9 to +18

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# First, check the file exists and show the afterEach block
echo "=== Lines 9-18 (afterEach) ==="
sed -n '9,18p' packages/cli/test/proxy.test.ts

echo -e "\n=== Full file structure and client creation sites ==="
rg -n 'createTestClient\(|afterEach|describe' packages/cli/test/proxy.test.ts | head -30

echo -e "\n=== Search for createTestClient calls with context ==="
rg -n -B2 -A2 'createTestClient\(' packages/cli/test/proxy.test.ts

echo -e "\n=== Search for $disconnect calls in this file ==="
rg -n '\$disconnect' packages/cli/test/proxy.test.ts || echo "No \$disconnect found"

echo -e "\n=== Repository-wide createTestClient usage ==="
rg -l 'createTestClient' packages --type=ts | head -5

echo -e "\n=== Check return type and definition of createTestClient ==="
rg -B2 -A10 'export.*createTestClient|function.*createTestClient' packages --type=ts | head -40

Repository: zenstackhq/zenstack

Length of output: 1539


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Check for disconnect calls for the created clients ==="
grep -n 'disconnect' packages/cli/test/proxy.test.ts || echo "No disconnect found in file"

echo -e "\n=== Check full test file to see if clients are used and cleaned up ==="
wc -l packages/cli/test/proxy.test.ts

echo -e "\n=== Show the context around each createTestClient call ==="
sed -n '35,45p' packages/cli/test/proxy.test.ts
echo "---"
sed -n '68,80p' packages/cli/test/proxy.test.ts
echo "---"
sed -n '119,130p' packages/cli/test/proxy.test.ts

echo -e "\n=== Find createTestClient definition ==="
rg -n 'export.*createTestClient|^export function createTestClient|^function createTestClient' packages --type=ts

echo -e "\n=== Look at createTestClient export and understand return type ==="
rg -B5 -A20 'createTestClient' packages/cli/src/test-client.ts 2>/dev/null | head -60 || echo "File may not exist, searching more broadly..."
rg -B3 -A15 'export.*function.*createTestClient' packages --type=ts | head -50

Repository: zenstackhq/zenstack

Length of output: 4089


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Find ClientContract definition ==="
rg -B5 -A15 'type ClientContract|interface ClientContract' packages --type=ts | head -80

echo -e "\n=== Search for $disconnect method definition ==="
rg -B3 -A8 '\$disconnect' packages --type=ts | head -100

echo -e "\n=== Check how other tests use createTestClient and cleanup ==="
rg -B2 -A5 'createTestClient' packages --type=ts | grep -A5 'disconnect\|afterEach\|cleanup' | head -50 || echo "No disconnect pattern found in other tests"

echo -e "\n=== Check test files that import createTestClient ==="
rg -l 'createTestClient' packages --type=ts | head -10
</script>

Repository: zenstackhq/zenstack

Length of output: 6819


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Search for disconnect method ==="
rg -n 'disconnect' packages/orm --type=ts | grep -v node_modules | head -30

echo -e "\n=== Search for ClientContract type definition ==="
rg -B10 -A25 'export.*type ClientContract' packages/orm --type=ts | head -100

echo -e "\n=== Look at other test files to see pattern of client cleanup ==="
fd -e test.ts -e test.tsx packages | head -5

echo -e "\n=== Check one other test file for cleanup patterns ==="
fd -e test.ts packages | head -1 | xargs head -100

echo -e "\n=== Check if there are any other afterEach or test cleanup patterns in CLI tests ==="
find packages/cli/test -name '*.test.ts' -exec grep -l 'afterEach\|afterAll' {} \;
</script>

Repository: zenstackhq/zenstack

Length of output: 3497


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Check ClientContract $disconnect method definition ==="
sed -n '200,210p' packages/orm/src/client/contract.ts

echo -e "\n=== Check client-impl disconnect implementation ==="
sed -n '334,350p' packages/orm/src/client/client-impl.ts

echo -e "\n=== Verify the three client creations are indeed at lines 37, 70, 121 ==="
sed -n '37p;70p;121p' packages/cli/test/proxy.test.ts

echo -e "\n=== Check if any client is used after creation and before test end ==="
sed -n '37,65p' packages/cli/test/proxy.test.ts | grep -E 'client\.|await|expect'

echo -e "\n=== Full context of test 1 (around line 37) ==="
sed -n '20,67p' packages/cli/test/proxy.test.ts

echo -e "\n=== Full context of test 2 (around line 70) ==="
sed -n '53,105p' packages/cli/test/proxy.test.ts

Repository: zenstackhq/zenstack

Length of output: 110


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Check ClientContract disconnect method definition ==="
sed -n '200,210p' packages/orm/src/client/contract.ts

echo "=== Check client-impl disconnect implementation ==="
sed -n '334,350p' packages/orm/src/client/client-impl.ts

echo "=== Verify the three client creations ==="
sed -n '37p;70p;121p' packages/cli/test/proxy.test.ts

echo "=== Check if any client is used after creation ==="
sed -n '37,65p' packages/cli/test/proxy.test.ts

echo "=== Full context of test 1 ==="
sed -n '20,67p' packages/cli/test/proxy.test.ts

echo "=== Full context of test 2 ==="
sed -n '53,105p' packages/cli/test/proxy.test.ts

echo "=== Full context of test 3 ==="
sed -n '105,150p' packages/cli/test/proxy.test.ts

Repository: zenstackhq/zenstack

Length of output: 8178


Disconnect test clients in teardown to avoid leaked database connections.

Each test creates a client via createTestClient() at lines 37, 70, and 121, but afterEach only closes the HTTP server. The clients maintain database connections through Kysely that are never cleaned up, causing connection leaks and potential test flakiness. Call $disconnect() for each created client during teardown.

💡 Suggested fix
 describe('CLI proxy tests', () => {
     let server: http.Server | undefined;
+    let clients: Array<Awaited<ReturnType<typeof createTestClient>>> = [];

     afterEach(async () => {
         await new Promise<void>((resolve) => {
             if (server) {
                 server.close(() => resolve());
                 server = undefined;
             } else {
                 resolve();
             }
         });
+        await Promise.all(clients.map((client) => client.$disconnect()));
+        clients = [];
     });
@@
-        const client = await createTestClient(zmodel);
+        const client = await createTestClient(zmodel);
+        clients.push(client);
@@
-        const client = await createTestClient(zmodel, {
+        const client = await createTestClient(zmodel, {
             skipValidationForComputedFields: true,
             omit: { User: { postCount: true } },
         });
+        clients.push(client);
@@
-        const client = await createTestClient(zmodel);
+        const client = await createTestClient(zmodel);
+        clients.push(client);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/test/proxy.test.ts` around lines 9 - 18, The test teardown
currently only closes the HTTP server (server.close) but never disconnects
Kysely clients created by createTestClient(), which leaks DB connections; modify
the test file to track created clients (e.g., push each result of
createTestClient() into a testClients array or a known client variable) and in
afterEach await Promise.all(testClients.map(c => c.$disconnect())) (or await
client.$disconnect() if a single client), then clear the references (set to
undefined/empty array) before resolving the teardown; update afterEach alongside
the existing server.close logic to ensure all clients are properly disconnected.


async function startAt(app: ReturnType<typeof createProxyApp>): Promise<string> {
return new Promise((resolve) => {
server = app.listen(0, () => {
const addr = server!.address() as { port: number };
resolve(`http://localhost:${addr.port}`);
});
});
}

it('should serve schema at /api/schema endpoint', async () => {
const zmodel = `
model User {
id String @id @default(cuid())
email String @unique
}
`;

const client = await createTestClient(zmodel);
const app = createProxyApp(client, client.$schema);
const baseUrl = await startAt(app);

const r = await fetch(`${baseUrl}/api/schema`);
expect(r.status).toBe(200);

const body = await r.json();
// schema fields are present
expect(body).toHaveProperty('models');
expect(body.models).toHaveProperty('User');
expect(body).toHaveProperty('provider');
// zenstackVersion is injected by the proxy; when running tests directly
// from source (no built dist/) getVersion() returns undefined and the
// key is omitted from JSON — tolerate that, but if present it must be a string.
if ('zenstackVersion' in body) {
expect(typeof body.zenstackVersion).toBe('string');
}
});

it('should omit computed fields from default query responses', async () => {
// postCount is a @computed field — the proxy must not try to SELECT it
// by default (it has no backing column in the DB).
const zmodel = `
model User {
id String @id @default(cuid())
name String
postCount Int @computed
}
`;

// Mirror what proxy.ts does: build omit config from the schema, then
// create the client with skipValidationForComputedFields.
const client = await createTestClient(zmodel, {
skipValidationForComputedFields: true,
omit: { User: { postCount: true } },
});

const app = createProxyApp(client, client.$schema);
const baseUrl = await startAt(app);

// Create a user via the proxy API.
const createRes = await fetch(`${baseUrl}/api/model/user/create`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ data: { name: 'Alice' } }),
});
expect(createRes.status).toBe(201);
const created = await createRes.json();

// The regular fields should be present …
expect(created.data).toHaveProperty('id');
expect(created.data).toHaveProperty('name', 'Alice');
// … but the computed field must be absent in the default response.
expect(created.data).not.toHaveProperty('postCount');

// A findMany should behave the same way.
const listRes = await fetch(`${baseUrl}/api/model/user/findMany`);
expect(listRes.status).toBe(200);
const list = await listRes.json();
expect(list.data).toHaveLength(1);
expect(list.data[0]).not.toHaveProperty('postCount');
});

it('should handle sequential transaction calls', async () => {
const zmodel = `
model User {
id String @id @default(cuid())
email String @unique
posts Post[]

@@allow('all', true)
}

model Post {
id String @id @default(cuid())
title String
author User? @relation(fields: [authorId], references: [id])
authorId String?

@@allow('all', true)
}
`;

const client = await createTestClient(zmodel);
const app = createProxyApp(client, client.$schema);
const baseUrl = await startAt(app);

const txRes = await fetch(`${baseUrl}/api/model/$transaction/sequential`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([
{
model: 'User',
op: 'create',
args: { data: { id: 'u1', email: 'alice@example.com' } },
},
{
model: 'Post',
op: 'create',
args: { data: { id: 'p1', title: 'Hello World', authorId: 'u1' } },
},
{
model: 'Post',
op: 'findMany',
args: { where: { authorId: 'u1' } },
},
]),
});
expect(txRes.status).toBe(200);
const tx = await txRes.json();

// Should return results for each operation in the transaction.
expect(Array.isArray(tx.data)).toBe(true);
expect(tx.data).toHaveLength(3);

// First result: created user
expect(tx.data[0]).toMatchObject({ id: 'u1', email: 'alice@example.com' });
// Second result: created post
expect(tx.data[1]).toMatchObject({ id: 'p1', title: 'Hello World', authorId: 'u1' });
// Third result: findMany — should find the newly created post
expect(Array.isArray(tx.data[2])).toBe(true);
expect(tx.data[2]).toHaveLength(1);
expect(tx.data[2][0]).toMatchObject({ id: 'p1', title: 'Hello World' });

// Confirm persisted outside transaction too.
const userRes = await fetch(
`${baseUrl}/api/model/user/findUnique?q=${encodeURIComponent(JSON.stringify({ where: { id: 'u1' } }))}`,
);
expect(userRes.status).toBe(200);
const user = await userRes.json();
expect(user.data).toMatchObject({ id: 'u1', email: 'alice@example.com' });
});
});
Loading