fix(mongodb): use dedicated count for legacy collections

This commit is contained in:
Guoyu Su authored and GitHub committed 2026-07-13 13:21:50 +08:00
1 parent 03bc87c77a
commit a99a34b4ab
28 files changed
+916 -19

No files matched your search

+71
View File
@@ -0,0 +1,71 @@
import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "vitest";
import type { ConnectionConfig } from "../src/connections.js";
import { executeQuery } from "../src/database.js";
const mongoConfig: ConnectionConfig = {
id: "mongo-bridge",
name: "mongo-bridge",
db_type: "mongodb",
host: "127.0.0.1",
port: 27017,
username: "",
password: "",
database: "app",
ssh_enabled: false,
ssl: false,
};
test("direct backend routes MongoDB count commands through the count bridge", async () => {
const tempDir = await mkdtemp(join(tmpdir(), "dbx-node-core-count-"));
const previousDataDir = process.env.DBX_DATA_DIR;
let requestBody: unknown;
const server = createServer((req, res) => {
assert.equal(req.url, "/data/mongo/count-documents");
let body = "";
req.setEncoding("utf8");
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
requestBody = JSON.parse(body);
res.writeHead(200, { "content-type": "application/json" });
res.end("42");
});
});
try {
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("expected TCP bridge address");
process.env.DBX_DATA_DIR = tempDir;
await writeFile(join(tempDir, "mcp-bridge-port"), String(address.port));
const result = await executeQuery(mongoConfig, "db.projects.count({ active: true })");
assert.deepEqual(requestBody, {
connection_id: "mongo-bridge",
connection_name: "mongo-bridge",
database: "app",
collection: "projects",
filter: '{ "active": true }',
mode: "legacy",
});
assert.deepEqual(result, {
columns: ["count"],
rows: [{ count: 42 }],
row_count: 1,
});
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
if (previousDataDir === undefined) delete process.env.DBX_DATA_DIR;
else process.env.DBX_DATA_DIR = previousDataDir;
await rm(tempDir, { recursive: true, force: true });
}
});
+4
View File
@@ -93,6 +93,7 @@ test("parseMongoCountDocumentsCommand accepts shell-style count commands", () =>
assert.deepEqual(parseMongoCountDocumentsCommand('db.projects.countDocuments({"active":true})'), {
collection: "projects",
filter: '{"active":true}',
mode: "accurate",
});
});
@@ -100,14 +101,17 @@ test("parseMongoCountDocumentsCommand accepts legacy count helpers", () => {
assert.deepEqual(parseMongoCountDocumentsCommand("db.projects.count({ active: true })"), {
collection: "projects",
filter: '{ "active": true }',
mode: "legacy",
});
assert.deepEqual(parseMongoCountDocumentsCommand('db.getCollection("audit.logs").count()'), {
collection: "audit.logs",
filter: "{}",
mode: "legacy",
});
assert.deepEqual(parseMongoCountDocumentsCommand("db.projects.find({ active: true }).count()"), {
collection: "projects",
filter: '{ "active": true }',
mode: "legacy",
});
assert.equal(parseMongoFindCommand("db.projects.find({ active: true }).count()"), null);
});
+59 -1
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import { afterEach, test } from "vitest";
import { loadConnections, resetWebAuthForTests } from "../src/web-backend.js";
import { executeQuery, loadConnections, resetWebAuthForTests } from "../src/web-backend.js";
const originalFetch = globalThis.fetch;
const originalWebUrl = process.env.DBX_WEB_URL;
@@ -123,3 +123,61 @@ test("web backend still allows DBX Web instances with password auth disabled", a
assert.deepEqual(await loadConnections(), []);
});
test("web backend routes MongoDB count commands through count-documents", async () => {
process.env.DBX_WEB_URL = "http://127.0.0.1:4224";
delete process.env.DBX_WEB_PASSWORD;
const calls: Array<{ url: string; init?: RequestInit }> = [];
globalThis.fetch = (async (input, init) => {
const url = String(input);
calls.push({ url, init });
if (url.endsWith("/api/auth/check")) {
return jsonResponse({ authenticated: true, required: false, setup_required: false });
}
if (url.endsWith("/api/connection/connect")) {
return jsonResponse({ ok: true });
}
if (url.endsWith("/api/mongo/count-documents")) {
assert.equal(init?.method, "POST");
assert.deepEqual(JSON.parse(String(init?.body)), {
connectionId: "mongo-web",
database: "app",
collection: "projects",
filter: '{"active":true}',
mode: "accurate",
});
return jsonResponse(42);
}
throw new Error(`unexpected request: ${url}`);
}) as typeof fetch;
const result = await executeQuery(
{
id: "mongo-web",
name: "mongo-web",
db_type: "mongodb",
host: "127.0.0.1",
port: 27017,
username: "",
password: "",
database: "app",
ssh_enabled: false,
ssl: false,
},
'db.projects.countDocuments({"active":true})',
);
assert.deepEqual(result, {
columns: ["count"],
rows: [{ count: 42 }],
row_count: 1,
});
assert.deepEqual(
calls.map((call) => call.url),
[
"http://127.0.0.1:4224/api/auth/check",
"http://127.0.0.1:4224/api/connection/connect",
"http://127.0.0.1:4224/api/mongo/count-documents",
],
);
});