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

194 lines
6.4 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 { spawn } from 'node:child_process';
// Keep the daemon capability out of the environment inherited by unrelated workers.
const bridgeToken = process.env.PHOTOCRAFT_XIAOYI_BRIDGE_TOKEN;
delete process.env.PHOTOCRAFT_XIAOYI_BRIDGE_TOKEN;
const errors = {
'session-missing': '素材库未部署小壹知识库签发接口(HTTP 404),请联系管理员',
'session-unavailable': '素材库小壹知识库签发服务不可用(HTTP 503),请联系管理员核对配置',
unconfigured: '企业知识库宿主未配置',
network: '企业知识库网络不可达',
credential: '企业知识库用户凭据未配置或不可读取',
boundary: '企业知识库请求边界无效',
response: '企业知识库响应无效',
};
function transportError(category) {
const error = Error(errors[category] ?? errors.response);
error.network = category === 'network';
error.category = category;
return error;
}
// 按需读取 stdout,让文件写入速度通过管道约束宿主读取速度。
async function* frames(stdout) {
let pending = '';
for await (const chunk of stdout.setEncoding('utf8')) {
pending += chunk;
let end;
while ((end = pending.indexOf('\n')) !== -1) {
const line = pending.slice(0, end);
pending = pending.slice(end + 1);
let frame;
try { frame = JSON.parse(line); }
catch { throw transportError('response'); }
yield frame;
}
}
throw transportError('network');
}
export function createNativeKnowledgeFetch({
binary = process.env.PHOTOCRAFT_KNOWLEDGE_HOST, spawnProcess = spawn, maxHosts = 3, idleMs = 10 * 60_000,
} = {}) {
const hosts = new Set();
const queue = [];
function dispatch() {
while (queue.length) {
let host = [...hosts].find(item => !item.busy);
if (!host && hosts.size >= maxHosts) return;
const {resolve, reject, cleanup} = queue.shift();
cleanup();
try {
if (!host) {
const child = spawnProcess(binary, ['--jiansun-pi-rpc'], {
windowsHide:true, stdio:['pipe','pipe','ignore'],
...(bridgeToken ? {env:{...process.env, PHOTOCRAFT_XIAOYI_BRIDGE_TOKEN:bridgeToken}} : {}),
});
const current = {child, output:frames(child.stdout), busy:false};
host = current;
hosts.add(current);
child.once('close', () => { hosts.delete(current); dispatch(); });
child.on('error', () => child.stdout.destroy());
child.stdin.on('error', () => child.stdout.destroy());
}
clearTimeout(host.idleTimer);
host.busy = true;
resolve(host);
} catch (error) {
reject(error);
}
}
}
return async (address, init = {}) => {
const {signal, timeoutMs} = init;
signal?.throwIfAborted();
if (!binary) throw transportError('unconfigured');
const host = await new Promise((resolve, reject) => {
const abort = () => {
queue.splice(queue.indexOf(entry), 1);
reject(signal.reason);
};
const entry = {resolve, reject, cleanup: () => signal?.removeEventListener('abort', abort)};
signal?.addEventListener('abort', abort, {once:true});
queue.push(entry);
dispatch();
});
const timeout = timeoutMs === undefined ? undefined : AbortSignal.timeout(timeoutMs);
const active = signal && timeout ? AbortSignal.any([signal, timeout]) : signal ?? timeout;
const release = () => {
host.busy = false;
if (hosts.has(host)) {
host.idleTimer = setTimeout(() => {
hosts.delete(host);
host.child.stdin.end();
}, idleMs);
host.idleTimer.unref();
}
dispatch();
};
if (active?.aborted) {
release();
active.throwIfAborted();
}
return exchange(host, address, {...init, signal:active}, release, () => hosts.delete(host));
};
}
let defaultFetch;
export function nativeKnowledgeFetch(address, init) {
defaultFetch ??= createNativeKnowledgeFetch();
return defaultFetch(address, init);
}
async function exchange({child, output}, address, init, release, discard) {
const {signal} = init;
let request;
try {
const url = new URL(address);
request = {
method: 'knowledge-http', origin: url.origin, path: url.pathname + url.search + url.hash,
httpMethod: init.method, headers: Object.fromEntries(new Headers(init.headers)), body: init.body,
};
} catch (error) {
release();
throw error;
}
let finished = false;
const finish = () => {
if (finished) return;
finished = true;
signal?.removeEventListener('abort', abort);
child.unref?.();
child.stdin.unref?.();
child.stdout.unref?.();
release();
};
const abort = () => {
discard();
child.kill();
child.stdout.destroy();
};
child.ref?.();
child.stdin.ref?.();
child.stdout.ref?.();
signal?.addEventListener('abort', abort, {once:true});
const read = async () => {
let frame;
try {
frame = (await output.next()).value;
} catch (error) {
signal?.throwIfAborted();
throw typeof error.network === 'boolean' ? error : transportError('network');
}
signal?.throwIfAborted();
if (frame?.type === 'error') throw transportError(frame.category);
return frame;
};
try {
child.stdin.write(JSON.stringify(request) + '\n');
const headers = await read();
if (headers?.type !== 'headers') throw transportError('response');
if ([204, 205, 304].includes(headers.status)) {
if ((await read())?.type !== 'result') throw transportError('response');
const response = new Response(null, { status: headers.status, headers: headers.headers });
finish();
return response;
}
const body = new ReadableStream({
async pull(controller) {
try {
const frame = await read();
if (frame?.type === 'result') {
finish();
controller.close();
} else if (frame?.type === 'chunk') controller.enqueue(Buffer.from(frame.data, 'base64'));
else throw transportError('response');
} catch (error) {
abort();
finish();
controller.error(error);
}
},
cancel() { abort(); finish(); },
});
return new Response(body, { status: headers.status, headers: headers.headers });
} catch (error) {
abort();
finish();
signal?.throwIfAborted();
throw typeof error.network === 'boolean' ? error : transportError('response');
}
}