gongxiangp2/apps/detail-agent-pi/test/native-knowledge-http.test.mjs

208 lines
9.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import { EventEmitter, once } from 'node:events';
import { PassThrough } from 'node:stream';
import { setImmediate, setTimeout } from 'node:timers/promises';
import { createNativeKnowledgeFetch } from '../src/native-knowledge-http.mjs';
function fixture(writeFrames) {
const child = Object.assign(new EventEmitter(), { stdin: new PassThrough(), stdout: new PassThrough() });
let killed = false;
child.kill = () => {
killed = true;
child.stdout.destroy();
child.emit('close');
};
const ready = once(child.stdin, 'data').then(([bytes]) => JSON.parse(bytes));
const write = frame => child.stdout.write(JSON.stringify(frame) + '\n');
const produced = ready.then(async () => {
await writeFrames(write, child.stdout);
child.stdout.end();
child.emit('close');
});
const fetch = createNativeKnowledgeFetch({
binary: 'fake-host.exe',
spawnProcess(binary, args) {
assert.equal(binary, 'fake-host.exe');
assert.deepEqual(args, ['--jiansun-pi-rpc']);
return child;
},
});
return { fetch, ready, produced, killed: () => killed };
}
test('Pi 默认为知识库请求使用宿主通道,源码无凭据读取或注入路径', async () => {
const read = name => fs.readFile(new URL('../src/' + name, import.meta.url), 'utf8');
const [knowledge, transport] = await Promise.all([
read('enterprise-knowledge.mjs'), read('native-knowledge-http.mjs'),
]);
for (const source of [knowledge, transport]) {
assert.doesNotMatch(source, /EKB_API_KEY_FCD6FE6F|HKCU|reg\.exe|credentialProvider|Bearer|authorization/i);
}
assert.match(knowledge, /fetchImpl=nativeKnowledgeFetch/);
});
test('固定版本下载逐块读取,Pi 暂停消费时管道限制上游写入', async () => {
const count = 128;
let written = 0;
const bytes = Buffer.alloc(8192, 42);
const f = fixture(async (write, stdout) => {
write({ type: 'headers', status: 206, headers: { 'content-range': 'bytes 20-1048595/1048596' } });
for (; written < count; written++) {
if (!write({ type: 'chunk', data: bytes.toString('base64') })) await once(stdout, 'drain');
}
write({ type: 'result', value: {} });
});
const response = await f.fetch('http://knowledge.test/api/agent/files/test/download', {
method: 'GET', headers: { 'If-Match': 'fixed-version', Range: 'bytes=20-' },
});
await setImmediate();
assert.ok(written < count);
assert.deepEqual(await f.ready, {
method: 'knowledge-http', origin: 'http://knowledge.test', path: '/api/agent/files/test/download',
httpMethod: 'GET', headers: { 'if-match': 'fixed-version', range: 'bytes=20-' },
});
assert.equal(response.status, 206);
assert.equal(response.headers.get('content-range'), 'bytes 20-1048595/1048596');
let length = 0;
for await (const chunk of response.body) {
assert.deepEqual(chunk, bytes);
length += chunk.length;
}
assert.equal(length, count * bytes.length);
await f.produced;
});
test('知识库通道只返回固定错误文案,取消时终止等待中的子进程', async () => {
const failed = fixture(async write => {
write({ type: 'error', category: 'credential', error: 'synthetic raw upstream text' });
});
await assert.rejects(failed.fetch('http://knowledge.test/mcp', { method: 'POST' }),
{ message: '企业知识库用户凭据未配置或不可读取', network: false });
await failed.produced;
const controller = new AbortController();
const stalled = fixture(async (write, stdout) => {
write({ type: 'headers', status: 200, headers: {} });
await once(stdout, 'close');
});
const response = await stalled.fetch('http://knowledge.test/mcp', { method: 'POST', signal: controller.signal });
const reading = response.text();
controller.abort();
await assert.rejects(reading, { name: 'AbortError' });
await stalled.produced;
assert.equal(stalled.killed(), true);
});
test('签发端缺失或不可用时保留固定的 HTTP 诊断', async () => {
for (const [category, status] of [['session-missing', 404], ['session-unavailable', 503]]) {
const host = fixture(async write => {
write({ type: 'error', category, error: 'synthetic raw upstream text' });
});
await assert.rejects(host.fetch('http://knowledge.test/api/xiaoyi/v1/templates', { method: 'GET' }),
error => error.category === category && error.network === false && error.message.includes(`HTTP ${status}`));
await host.produced;
}
});
test('回环 Token 只传给知识库宿主子进程', async () => {
const name = 'PHOTOCRAFT_XIAOYI_BRIDGE_TOKEN';
process.env[name] = 'synthetic-bridge-token';
const { createNativeKnowledgeFetch: createFetch } = await import('../src/native-knowledge-http.mjs?bridge-test');
assert.equal(process.env[name], undefined);
const child = Object.assign(new EventEmitter(), { stdin: new PassThrough(), stdout: new PassThrough() });
child.stdin.once('data', bytes => {
assert.ok(!bytes.includes('synthetic-bridge-token'));
child.stdout.end('{"type":"headers","status":200,"headers":{}}\n{"type":"result"}\n');
});
const fetch = createFetch({ binary: 'fake-host.exe', spawnProcess(binary, args, options) {
assert.equal(options.env[name], 'synthetic-bridge-token');
return child;
} });
const response = await fetch('http://knowledge.test/api/xiaoyi/v1/templates', { method: 'GET' });
assert.equal(response.status, 200);
await response.text();
});
test('完整响应之后,同一宿主继续接收下一次请求', async () => {
const child = Object.assign(new EventEmitter(), {stdin:new PassThrough(),stdout:new PassThrough()});
const requests = [];
child.stdin.on('data', bytes => {
requests.push(JSON.parse(bytes));
child.stdout.write('{"type":"headers","status":200,"headers":{}}\n{"type":"result"}\n');
});
let spawned = 0;
const fetch = createNativeKnowledgeFetch({binary:'fake-host.exe',spawnProcess:() => { spawned++; return child; },maxHosts:1});
const replies = await Promise.all(Array.from({length:25}, async () => {
const response=await fetch('http://knowledge.test/mcp',{method:'POST'});
return response.text();
}));
assert.equal(replies.length,25);
assert.equal(requests.length,25);
assert.equal(spawned,1);
child.stdout.end();
});
test('空闲知识库宿主关闭输入管道并释放池位', async () => {
const idle = Promise.withResolvers();
const child = Object.assign(new EventEmitter(), {stdin:new PassThrough(),stdout:new PassThrough()});
child.stdin.on('finish',idle.resolve);
child.stdin.on('data',()=>child.stdout.write('{"type":"headers","status":200,"headers":{}}\n{"type":"result"}\n'));
const fetch = createNativeKnowledgeFetch({binary:'fake',spawnProcess:()=>child,idleMs:5});
await (await fetch('http://knowledge.test/mcp',{method:'POST'})).text();
const timeout = AbortSignal.timeout(1000);
await Promise.race([idle.promise,new Promise((_,reject)=>timeout.addEventListener('abort',()=>reject(timeout.reason)))]);
child.stdout.end();
});
test('下载占用宿主时小请求并行,队列取消不发送请求且等待不消耗超时', async () => {
const children = [], requests = [];
const fetch = createNativeKnowledgeFetch({binary:'fake', maxHosts:2, spawnProcess() {
const child = Object.assign(new EventEmitter(), {stdin:new PassThrough(),stdout:new PassThrough()});
child.kill = () => child.stdout.destroy();
child.stdin.on('data', bytes => {
const {path} = JSON.parse(bytes);
requests.push(path);
child.stdout.write('{"type":"headers","status":200,"headers":{}}\n');
if (!path.startsWith('/download')) child.stdout.write('{"type":"result"}\n');
});
children.push(child);
return child;
}});
const address = 'http://knowledge.test';
const first = await fetch(address+'/download-a');
assert.equal(await (await fetch(address+'/small')).text(), '');
const second = await fetch(address+'/download-b');
const controller = new AbortController();
const cancelled = fetch(address+'/cancelled',{signal:controller.signal});
const queued = fetch(address+'/queued',{timeoutMs:20});
controller.abort();
await assert.rejects(cancelled,{name:'AbortError'});
await setTimeout(40);
children[0].stdout.write('{"type":"result"}\n');
assert.equal(await first.text(),'');
assert.equal(await (await queued).text(),'');
assert.deepEqual(requests,['/download-a','/small','/download-b','/queued']);
await second.body.cancel();
children[0].stdout.end();
});
test('异常帧及其后残留数据随宿主丢弃', async () => {
let spawned = 0;
const fetch = createNativeKnowledgeFetch({binary:'fake',spawnProcess() {
const child = Object.assign(new EventEmitter(),{stdin:new PassThrough(),stdout:new PassThrough()});
child.kill = () => child.stdout.destroy();
const invalid = ++spawned === 1;
child.stdin.on('data', () => {
if (invalid) child.stdout.write('{"type":"unexpected"}\n');
child.stdout.write('{"type":"headers","status":204,"headers":{}}\n{"type":"result"}\n');
});
return child;
}});
await assert.rejects(fetch('http://knowledge.test/first'),{network:false});
assert.equal((await fetch('http://knowledge.test/second')).status,204);
assert.equal(spawned,2);
});