113 lines
5.5 KiB
TypeScript
113 lines
5.5 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
|
|
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { Client } from "@modelcontextprotocol/client";
|
|
import { InMemoryTransport } from "@modelcontextprotocol/server";
|
|
import { runCli } from "./runner.js";
|
|
import { createServer, HOSE_CLI_TOOL_NAME } from "../server.js";
|
|
import { startHttpServer } from "../http/server.js";
|
|
import * as helpers from "./helpers.js";
|
|
import * as shared from "./commands/platform/shared.js";
|
|
import * as records from "../domains/datalink/services.js";
|
|
|
|
describe("NDJSON output destinations across CLI, MCP and HTTP", () => {
|
|
const spies: Array<{ mockRestore(): void }> = [];
|
|
let directory: string;
|
|
let produced: number;
|
|
let directWrite: ReturnType<typeof spyOn>;
|
|
const command = ["platform", "records", "app", "entity", "--ndjson", "--raw"];
|
|
beforeEach(() => {
|
|
directory = mkdtempSync(join(tmpdir(), "hose-stream-test-"));
|
|
produced = 0;
|
|
spies.push(spyOn(helpers, "initCorpRuntime").mockImplementation(options => ({ selectedCorp: { id: "mock-corp" }, jsonMode: options?.jsonMode, outputOptions: options?.outputOptions }) as any));
|
|
spies.push(spyOn(shared, "resolveAppAndEntity").mockResolvedValue({ clients: { ekbClient: {} }, corpId: "mock-corp", platform: { id: "app" }, entity: { id: "entity", fields: [] } } as any));
|
|
spies.push(spyOn(records, "iterateAllEntityRecords").mockImplementation(async function* () {
|
|
produced++; yield { id: "r1", secret: "mock-secret" };
|
|
produced++; yield { id: "r2", active: true };
|
|
}));
|
|
directWrite = spyOn(process.stdout, "write").mockImplementation(() => true);
|
|
spies.push(directWrite);
|
|
});
|
|
afterEach(() => {
|
|
while (spies.length) spies.pop()!.mockRestore();
|
|
rmSync(directory, { recursive: true, force: true });
|
|
});
|
|
|
|
it("waits for the terminal destination before producing the next record", async () => {
|
|
let started!: () => void, release!: () => void;
|
|
const firstWrite = new Promise<void>(resolve => { started = resolve; });
|
|
const blocked = new Promise<void>(resolve => { release = resolve; });
|
|
const chunks: string[] = [];
|
|
const running = runCli(command, { writeStdout: async chunk => {
|
|
chunks.push(chunk);
|
|
if (chunks.length === 1) { started(); await blocked; }
|
|
} });
|
|
await firstWrite;
|
|
expect(produced).toBe(1);
|
|
release();
|
|
const result = await running;
|
|
expect(result.exitCode).toBe(0);
|
|
expect(chunks).toHaveLength(2);
|
|
expect(chunks[0]).not.toContain("mock-secret");
|
|
expect(JSON.parse(chunks[0]).secret).toBe("<redacted>");
|
|
expect(directWrite).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("writes actual NDJSON to output-file and returns a compact summary", async () => {
|
|
const outputFile = join(directory, "records.ndjson");
|
|
const result = await runCli([...command, "-o", outputFile]);
|
|
expect(result.exitCode).toBe(0);
|
|
const summary = JSON.parse(result.stdout);
|
|
const contents = readFileSync(outputFile, "utf8");
|
|
expect(summary.outputFile).toBe(outputFile);
|
|
expect(summary.records).toBe(2);
|
|
expect(summary.bytes).toBe(Buffer.byteLength(contents));
|
|
expect(contents.trim().split("\n").map(line => JSON.parse(line).id)).toEqual(["r1", "r2"]);
|
|
expect(contents).not.toContain("mock-secret");
|
|
expect(directWrite).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects embedded streaming without a destination before fetching records", async () => {
|
|
const result = await runCli([...command, "--json"]);
|
|
expect(result.exitCode).toBe(2);
|
|
expect(result.stdout).toContain("output-file");
|
|
expect(produced).toBe(0);
|
|
expect(directWrite).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("returns a proper MCP error rather than emitting record bytes on process stdout", async () => {
|
|
const server = createServer({ enabled: true });
|
|
const client = new Client({ name: "stream-test", version: "1" });
|
|
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
|
try {
|
|
await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
|
|
const result = await client.callTool({ name: HOSE_CLI_TOOL_NAME, arguments: { command: command.join(" ") } });
|
|
expect(result.isError).toBe(true);
|
|
expect(JSON.stringify(result.content)).toContain("output-file");
|
|
expect(produced).toBe(0);
|
|
expect(directWrite).not.toHaveBeenCalled();
|
|
} finally {
|
|
await Promise.allSettled([client.close(), server.close()]);
|
|
}
|
|
});
|
|
|
|
it("returns an HTTP error response instead of a successful empty result", async () => {
|
|
const server = await startHttpServer({ host: "127.0.0.1", port: 0, silent: true });
|
|
try {
|
|
const address = server.address() as { port: number };
|
|
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
if (process.env.HOSE_HTTP_TOKEN) headers.Authorization = `Bearer ${process.env.HOSE_HTTP_TOKEN.trim()}`;
|
|
const response = await fetch(`http://127.0.0.1:${address.port}/api/cli`, { method: "POST", headers, body: JSON.stringify({ command: command.join(" ") }) });
|
|
expect(response.status).toBe(400);
|
|
const result = await response.json() as { exitCode: number; stderr: string };
|
|
expect(result.exitCode).toBe(2);
|
|
expect(result.stderr).toContain("output-file");
|
|
expect(produced).toBe(0);
|
|
expect(directWrite).not.toHaveBeenCalled();
|
|
} finally {
|
|
await new Promise<void>(resolve => server.close(() => resolve()));
|
|
}
|
|
});
|
|
});
|