加固小壹跨网络连接并透传模板表单字段
This commit is contained in:
parent
da93de994c
commit
ec83fa9f79
@ -5,6 +5,7 @@ import fs from 'node:fs/promises';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { nativeKnowledgeFetch } from './native-knowledge-http.mjs';
|
||||
import { knowledgeTiming, networkFailure, retryKnowledgeRead } from './knowledge-network.mjs';
|
||||
import origins from './enterprise-knowledge-origins.json' with { type: 'json' };
|
||||
import toolNames from './enterprise-tool-names.json' with { type: 'json' };
|
||||
|
||||
@ -40,7 +41,7 @@ function boundedJSON(raw, contentType) {
|
||||
try { return JSON.parse(payload); } catch { throw Error('企业知识库响应格式无效'); }
|
||||
}
|
||||
function httpFailure(status) {
|
||||
const label = status === 401 ? '认证失败' : status === 403 ? '无权限' : status === 404 ? '资料不存在或不可读取' : status === 410 ? '资料已下线' : status === 409 || status === 412 ? '版本冲突' : status === 428 ? '续读需要revision' : status === 429 ? '额度或访问频率受限' : '请求失败';
|
||||
const label = status === 401 ? '登录已失效,请重新登录' : status === 403 ? '无权限' : status === 404 ? '资料不存在或不可读取' : status === 410 ? '资料已下线' : status === 409 || status === 412 ? '版本冲突' : status === 428 ? '续读需要revision' : status === 429 ? '额度或访问频率受限' : status >= 500 ? '服务端异常,请稍后重试' : '请求失败';
|
||||
return `企业知识库${label}(HTTP ${status})`;
|
||||
}
|
||||
function toolFailure(reply) {
|
||||
@ -57,9 +58,10 @@ function toolFailure(reply) {
|
||||
}
|
||||
function failure(status, value={}, retryAfter) {
|
||||
const seconds=Number(value?.retryAfterSeconds??retryAfter);
|
||||
const reason = typeof value?.error === 'string' ? ':' + value.error : '';
|
||||
const reason = status < 500 && typeof value?.error === 'string' ? ':' + value.error : '';
|
||||
const error=Error(httpFailure(status)+reason+(status===429&&seconds>0?`,${Math.ceil(seconds)}秒后可重试`:''));
|
||||
error.status=status;
|
||||
error.code=value?.code;
|
||||
if(status===429&&Number.isFinite(seconds)&&seconds>0) { error.retryAfterSeconds=Math.ceil(seconds); error.usage=value.usage; }
|
||||
return error;
|
||||
}
|
||||
@ -77,22 +79,19 @@ async function request(origin,path,{body,session,protocol='2025-11-25',fetchImpl
|
||||
signal?.throwIfAborted();
|
||||
if (!path.startsWith('/') || path.startsWith('//')) throw Error('企业知识库路径无效');
|
||||
// The native pool starts its request timeout when a host becomes available.
|
||||
const timing = fetchImpl === nativeKnowledgeFetch ? {signal,timeoutMs} :
|
||||
{signal:AbortSignal.any([signal,AbortSignal.timeout(timeoutMs)].filter(Boolean))};
|
||||
const timing = knowledgeTiming(fetchImpl, signal, timeoutMs);
|
||||
let response;
|
||||
try { response=await fetchImpl(origin+path,{method:body===undefined?'GET':'POST',redirect:'manual',...timing,headers:{Accept:'application/json, text/event-stream',...(body===undefined?{}:{'Content-Type':'application/json'}),...(session?{'Mcp-Session-Id':session}:{}),'MCP-Protocol-Version':protocol},...(body===undefined?{}:{body:JSON.stringify(body)})}); }
|
||||
catch (cause) { signal?.throwIfAborted(); if(cause.network===false)throw cause; const error=Error('企业知识库网络不可达');error.network=true;throw error; }
|
||||
catch (cause) { throw networkFailure(cause, signal); }
|
||||
if ([401,403,404].includes(response.status)) {
|
||||
await response.body?.cancel();
|
||||
throw failure(response.status);
|
||||
}
|
||||
const reader=response.body?.getReader(); if (!reader) {if(!response.ok)throw failure(response.status);return {value:null,headers:response.headers};}
|
||||
let size=0;
|
||||
const chunks=[];
|
||||
for (;;) {
|
||||
const {done,value}=await reader.read().catch(cause => {
|
||||
signal?.throwIfAborted();
|
||||
if(cause.network===false)throw cause;
|
||||
const error=Error('企业知识库网络不可达');
|
||||
error.network=true;
|
||||
throw error;
|
||||
});
|
||||
const {done,value}=await reader.read().catch(cause => { throw networkFailure(cause, signal); });
|
||||
if (done) break;
|
||||
size+=value.byteLength;
|
||||
if (size>maxBytes) {
|
||||
@ -120,13 +119,15 @@ export class EnterpriseKnowledge {
|
||||
if (this.connection?.intranet === endpoints[0]) return this.connection;
|
||||
let origin;
|
||||
for (const candidate of endpoints) {
|
||||
try { const health=await request(candidate,'/healthz',{fetchImpl:this.fetchImpl,signal,timeoutMs:2500}); if (health.value?.status!=='ok'||health.value?.service!=='enterprise-knowledge-base') throw Error('企业知识库身份校验失败'); origin=candidate;break; }
|
||||
try { const health=await retryKnowledgeRead(() => request(candidate,'/healthz',{fetchImpl:this.fetchImpl,signal,timeoutMs:2500}),signal); if (health.value?.status!=='ok'||health.value?.service!=='enterprise-knowledge-base') throw Error('企业知识库身份校验失败'); origin=candidate;break; }
|
||||
catch(error) { signal?.throwIfAborted(); if (!error.network || candidate===endpoints.at(-1)) throw error; }
|
||||
}
|
||||
let seq=0, session, protocol='2025-11-25';
|
||||
const rpc=async(method,params,notification=false,options={})=>{
|
||||
const id=notification?undefined:++seq;
|
||||
const {value,headers}=await request(origin,'/mcp',{session,protocol,fetchImpl:this.fetchImpl,signal:options.signal,maxBytes:params?.name==='read_image'?12_000_000:2_000_000,body:{jsonrpc:'2.0',method,...(params?{params}:{}),...(id?{id}:{})}});
|
||||
const read=()=>request(origin,'/mcp',{session,protocol,fetchImpl:this.fetchImpl,signal:options.signal,maxBytes:params?.name==='read_image'?12_000_000:2_000_000,body:{jsonrpc:'2.0',method,...(params?{params}:{}),...(id?{id}:{})}});
|
||||
const {value,headers}=await (method==='tools/list'||method==='tools/call'&&names.includes(params.name)
|
||||
? retryKnowledgeRead(read, options.signal) : read());
|
||||
if(method==='initialize')session=headers.get('mcp-session-id')||undefined;
|
||||
if(notification) {if(value?.error)throw Error('企业知识库协议错误');return;}
|
||||
if(!value || value.jsonrpc!=='2.0'||value.id!==id||value.error||!value.result) throw Error('企业知识库协议错误');
|
||||
@ -227,12 +228,19 @@ export class EnterpriseKnowledge {
|
||||
if(received>=metadata.size){await fs.rm(part,{force:true});received=0;}
|
||||
const {origin}=reply;
|
||||
let response;
|
||||
try { response=await this.fetchImpl(origin+metadata.downloadPath,{method:'GET',redirect:'manual',signal,headers:{...metadata.downloadHeaders,...(received?{Range:`bytes=${received}-`}:{})}}); }
|
||||
try {
|
||||
response=await retryKnowledgeRead(async()=>{
|
||||
const reply=await this.fetchImpl(origin+metadata.downloadPath,{method:'GET',redirect:'manual',
|
||||
...knowledgeTiming(this.fetchImpl,signal,210_000),
|
||||
headers:{...metadata.downloadHeaders,...(received?{Range:`bytes=${received}-`}:{})}});
|
||||
if (![502,503,504].includes(reply.status)) return reply;
|
||||
const value=await reply.json().catch(error=>{if(!(error instanceof SyntaxError))throw error;});
|
||||
throw failure(reply.status,value,reply.headers.get('retry-after'));
|
||||
},signal);
|
||||
}
|
||||
catch (cause) {
|
||||
signal?.throwIfAborted();
|
||||
if(cause.network===false)throw cause;
|
||||
if(this.connection===connection)this.connection=undefined;
|
||||
throw Object.assign(Error('企业知识库附件下载中断,可继续同一版本',{cause}),{network:true});
|
||||
if(cause.network && this.connection===connection)this.connection=undefined;
|
||||
throw cause;
|
||||
}
|
||||
if(!response.ok){
|
||||
let value;try{value=await response.json();}catch{signal?.throwIfAborted();}
|
||||
@ -255,9 +263,9 @@ export class EnterpriseKnowledge {
|
||||
try {
|
||||
if(response.body)for await(const bytes of response.body){signal?.throwIfAborted();received+=bytes.byteLength;if(received>metadata.size)throw Error('企业知识库附件大小不匹配');await handle.writeFile(bytes);if(Date.now()-progressAt>=100||received===metadata.size){progressAt=Date.now();onProgress?.({phase:'download',fileId:args.fileId,received,total:metadata.size});}}
|
||||
} catch(error) {
|
||||
signal?.throwIfAborted();
|
||||
if(error.network && this.connection===connection)this.connection=undefined;
|
||||
throw error;
|
||||
const failure = networkFailure(error,signal);
|
||||
if(failure.network && this.connection===connection)this.connection=undefined;
|
||||
throw failure;
|
||||
}
|
||||
finally {await handle.close();}
|
||||
signal?.throwIfAborted();
|
||||
|
||||
@ -4,10 +4,11 @@ import {setTimeout as delay} from 'node:timers/promises';
|
||||
import { EnterpriseKnowledge } from './enterprise-knowledge.mjs';
|
||||
import { openXiaoyiSkills } from './xiaoyi-release.mjs';
|
||||
import { normalizeTemplateMapping } from './template-mapping.mjs';
|
||||
import { digest } from './store.mjs';
|
||||
import { atomic, digest } from './store.mjs';
|
||||
import { EnterpriseContext } from './enterprise-context.mjs';
|
||||
import {resourceRequest,resourceSnapshot} from './enterprise-resource-map.mjs';
|
||||
import {nativeKnowledgeFetch} from './native-knowledge-http.mjs';
|
||||
import {knowledgeTiming, retryKnowledgeRead, transientStatus} from './knowledge-network.mjs';
|
||||
import origins from './enterprise-knowledge-origins.json' with {type:'json'};
|
||||
|
||||
async function waitForQuota(read, task) {
|
||||
@ -17,7 +18,7 @@ async function waitForQuota(read, task) {
|
||||
task.signal?.throwIfAborted();
|
||||
try { return await read(); }
|
||||
catch(error) {
|
||||
if(error.network===true&&transientFailures<networkRetryMs.length){
|
||||
if(error.network===true&&!error.retryExhausted&&transientFailures<networkRetryMs.length){
|
||||
await delay(networkRetryMs[transientFailures++],undefined,{signal:task.signal});
|
||||
continue;
|
||||
}
|
||||
@ -347,6 +348,8 @@ function intakeMetadata(value) {
|
||||
if (!field || typeof field.id !== 'string' || !field.id.trim() || typeof field.label !== 'string' || !field.label.trim() ||
|
||||
!['text','number','select','boolean'].includes(field.type) ||
|
||||
(field.required !== undefined && typeof field.required !== 'boolean') ||
|
||||
(field.multiline !== undefined && typeof field.multiline !== 'boolean') ||
|
||||
(field.placeholder !== undefined && typeof field.placeholder !== 'string') ||
|
||||
(field.help !== undefined && typeof field.help !== 'string') ||
|
||||
(field.unit !== undefined && typeof field.unit !== 'string') ||
|
||||
(field.options !== undefined && (!Array.isArray(field.options) || field.options.some(option => typeof option !== 'string'))) ||
|
||||
@ -358,6 +361,8 @@ function intakeMetadata(value) {
|
||||
return {
|
||||
id:field.id, label:field.label, type:field.type,
|
||||
...(field.required !== undefined && {required:field.required}),
|
||||
...(field.multiline !== undefined && {multiline:field.multiline}),
|
||||
...(field.placeholder !== undefined && {placeholder:field.placeholder}),
|
||||
...(field.help !== undefined && {help:field.help}),
|
||||
...(field.unit !== undefined && {unit:field.unit}),
|
||||
...(field.options !== undefined && {options:field.options}),
|
||||
@ -430,20 +435,43 @@ export async function xiaoyiCatalog(input, {signal,fetch = nativeKnowledgeFetch,
|
||||
return origins[0];
|
||||
});
|
||||
}
|
||||
let response;
|
||||
const cache = input.root && path.join(input.root, 'catalog', 'index-' + digest(origin) + '.json');
|
||||
let rows, notice;
|
||||
try {
|
||||
response = await fetch(new URL('/api/xiaoyi/v1/templates', origin), {method:'GET',signal});
|
||||
rows = await retryKnowledgeRead(async () => {
|
||||
const response = await fetch(new URL('/api/xiaoyi/v1/templates', origin), {
|
||||
method:'GET', redirect:'manual', ...knowledgeTiming(fetch, signal, 45_000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const messages = {401:'小壹知识库连接已失效,请重新登录素材库',403:'当前连接无权读取模板目录,请联系知识库管理员'};
|
||||
if (messages[response.status]) {
|
||||
await response.body?.cancel();
|
||||
throw Object.assign(Error(messages[response.status]), {status:response.status});
|
||||
}
|
||||
const body = await response.json().catch(error => {
|
||||
if (!(error instanceof SyntaxError)) throw error;
|
||||
});
|
||||
const message = body?.code === 'knowledge_session_misconfigured' ? '小壹知识库自动授权配置错误,请联系管理员'
|
||||
: response.status >= 500 ? '模板目录服务端异常,请稍后重试' : '模板目录无法读取(HTTP ' + response.status + ')';
|
||||
throw Object.assign(Error(message), {status:response.status, code:body?.code, network:false});
|
||||
}
|
||||
const data = await response.json();
|
||||
if (!Array.isArray(data.items)) throw Error('小壹模板目录格式无效');
|
||||
return data.items;
|
||||
}, signal);
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
if (error.category === 'credential') throw Error('小壹知识库未连接,请在小壹设置中检测连接', {cause:error});
|
||||
throw error;
|
||||
if (!cache || !(error.network || error.retryable || transientStatus(error.status, error.code))) throw error;
|
||||
rows = await fs.readFile(cache, 'utf8').then(JSON.parse, e => {
|
||||
if (e.code !== 'ENOENT') throw e;
|
||||
});
|
||||
if (!Array.isArray(rows)) throw error;
|
||||
notice = error.message + '。正在使用本机缓存模板,表单草稿已保留。';
|
||||
}
|
||||
if (!response.ok) {
|
||||
const messages = {401:'小壹知识库连接已失效,请在小壹设置中检测连接',403:'当前连接无权读取模板目录,请联系知识库管理员'};
|
||||
throw Object.assign(Error(messages[response.status] ?? '模板目录读取失败(HTTP ' + response.status + ')'),{status:response.status});
|
||||
}
|
||||
const data = await response.json();
|
||||
if (!Array.isArray(data.items)) throw Error('小壹模板目录格式无效');
|
||||
const rows = data.items;
|
||||
signal?.throwIfAborted();
|
||||
if (cache && !notice) await atomic(cache, rows);
|
||||
const diagnostic = notice ? {notice} : {};
|
||||
const brandId = name => 'ekb:brand:' + name;
|
||||
const categoryId = name => 'ekb:category:' + name;
|
||||
if (input.action === 'choices' || input.action === 'brand') {
|
||||
@ -464,24 +492,24 @@ export async function xiaoyiCatalog(input, {signal,fetch = nativeKnowledgeFetch,
|
||||
if (input.action === 'brand') {
|
||||
const brand = brands.get(selected);
|
||||
if (!brand) throw Error('当前制作模板目录没有所选品牌');
|
||||
return {brand};
|
||||
return {brand,...diagnostic};
|
||||
}
|
||||
return {catalog:{kind:input.kind,items:input.kind === 'brands' ? [...brands.values()] : brands.get(selected)?.categories ?? []}};
|
||||
return {catalog:{kind:input.kind,items:input.kind === 'brands' ? [...brands.values()] : brands.get(selected)?.categories ?? []},...diagnostic};
|
||||
}
|
||||
const entries = rows.filter(item => item.brand === input.brandName && item.category === input.categoryName);
|
||||
if (input.action === 'catalog') {
|
||||
const query = input.query?.trim().toLocaleLowerCase() ?? '';
|
||||
return {items:entries.filter(item => !query || (item.name + ' ' + item.templateId).toLocaleLowerCase().includes(query))
|
||||
.map(item => ({id:item.templateId,key:item.templateId,name:item.name,brandId:input.brandId,categoryId:input.categoryId,
|
||||
...(item.intake != null && {intake:intakeMetadata(item.intake)})}))};
|
||||
...(item.intake != null && {intake:intakeMetadata(item.intake)})})),...diagnostic};
|
||||
}
|
||||
const item = entries.find(row => row.templateId === input.resourceSetId);
|
||||
if (!item) throw Error('所选模板已不在当前发布目录,请重新选择');
|
||||
const labels = {detail:'详情页',main_images:'主图',sku_images:'SKU'};
|
||||
const components = item.components.map(part => ({
|
||||
id:part.id,name:labels[part.id] ?? part.id,kind:part.id,status:'available',issues:[],previews:[]
|
||||
id:part.id,name:labels[part.id] ?? part.id,kind:part.id,status:'available',issues:notice ? [notice] : [],previews:[]
|
||||
}));
|
||||
if (input.action === 'resource-set') return {items:components};
|
||||
if (input.action === 'resource-set') return {items:components,...diagnostic};
|
||||
const component = components.find(part => part.id === input.componentId);
|
||||
if (!component) throw Error('当前模板没有所选组件');
|
||||
const projectDir = path.join(input.root,'catalog',digest([item.templateId,item.version]));
|
||||
@ -491,7 +519,7 @@ export async function xiaoyiCatalog(input, {signal,fetch = nativeKnowledgeFetch,
|
||||
knowledgeVersion:item.knowledgeVersion,metadataOnly:true,intake:intakeMetadata(item.intake),
|
||||
},{signal,fetch,onProgress});
|
||||
if (!packs[component.id]) throw Error('制作包缺少所选组件,请联系知识库管理员');
|
||||
return {items:[{...component,pack:packs[component.id]}]};
|
||||
return {items:[{...component,pack:packs[component.id]}],...diagnostic};
|
||||
}
|
||||
|
||||
export async function templateRequest(input,options) {
|
||||
|
||||
44
apps/detail-agent-pi/src/knowledge-network.mjs
Normal file
44
apps/detail-agent-pi/src/knowledge-network.mjs
Normal file
@ -0,0 +1,44 @@
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { nativeKnowledgeFetch } from './native-knowledge-http.mjs';
|
||||
|
||||
const timeoutCodes = new Set(['ETIMEDOUT', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT']);
|
||||
const connectionCodes = new Set(['ECONNRESET', 'ECONNREFUSED', 'EPIPE', 'EAI_AGAIN', 'ENOTFOUND', 'UND_ERR_SOCKET']);
|
||||
|
||||
export function knowledgeTiming(fetch, signal, timeoutMs) {
|
||||
if (fetch === nativeKnowledgeFetch) return {signal, timeoutMs};
|
||||
const timeout = AbortSignal.timeout(timeoutMs);
|
||||
return {signal: signal ? AbortSignal.any([signal, timeout]) : timeout};
|
||||
}
|
||||
|
||||
export function networkFailure(cause, signal) {
|
||||
signal?.throwIfAborted();
|
||||
if (cause.network === true && cause.category) return cause;
|
||||
const code = cause.code ?? cause.cause?.code;
|
||||
const timeout = cause.name === 'TimeoutError' || timeoutCodes.has(code);
|
||||
if (cause.network === false || !(timeout || cause.network || connectionCodes.has(code) ||
|
||||
cause instanceof TypeError && cause.cause)) return cause;
|
||||
const message = timeout
|
||||
? '企业知识库请求超时,请检查网络后重试'
|
||||
: '连不上企业知识库服务器,请检查网络、VPN 或代理';
|
||||
return Object.assign(Error(message, {cause}), {network:true, category:timeout ? 'timeout' : 'network'});
|
||||
}
|
||||
|
||||
export function transientStatus(status, code) {
|
||||
return [502, 503, 504].includes(status) && code !== 'knowledge_session_misconfigured';
|
||||
}
|
||||
|
||||
export async function retryKnowledgeRead(read, signal) {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
signal?.throwIfAborted();
|
||||
try { return await read(); }
|
||||
catch (cause) {
|
||||
const error = networkFailure(cause, signal);
|
||||
if (error.retryExhausted || !(error.network || error.retryable || transientStatus(error.status, error.code))) throw error;
|
||||
if (attempt === 2) {
|
||||
error.retryExhausted = true;
|
||||
throw error;
|
||||
}
|
||||
await delay(150 * (attempt + 1) + Math.random() * 80, undefined, {signal});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -175,6 +175,8 @@ export class Native98kBroker {
|
||||
if (sent) throw Error('每次模型调用只接受一个请求');
|
||||
sent = true;
|
||||
init.signal?.throwIfAborted();
|
||||
const timeout = AbortSignal.timeout(600_000);
|
||||
const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
|
||||
const url = new URL(typeof address === 'string' || address instanceof URL ? address : address.url);
|
||||
if (url.origin !== 'https://api.vip98k.com' || !['/v1/messages', '/v1/chat/completions', '/v1/responses'].includes(url.pathname) || init.method?.toUpperCase() !== 'POST' || typeof init.body !== 'string') throw Error('模型请求边界无效');
|
||||
let controller, resolveHeaders, rejectHeaders;
|
||||
@ -187,17 +189,18 @@ export class Native98kBroker {
|
||||
if (event.type === 'headers') {
|
||||
resolveHeaders(new Response(body, { status: event.status, headers: event.headers }));
|
||||
} else if (event.type === 'chunk') enqueue(Buffer.from(event.data, 'base64'));
|
||||
}, init.signal);
|
||||
}, signal);
|
||||
const abort = () => {
|
||||
if (!this.authority.error && this.active?.requestId === id) this.child?.kill();
|
||||
};
|
||||
init.signal?.addEventListener('abort', abort, {once:true});
|
||||
signal.addEventListener('abort', abort, {once:true});
|
||||
const completed = request().catch(error=>{
|
||||
if (timeout.aborted && !init.signal?.aborted) throw Error('模型请求超时,原请求待核查');
|
||||
if (error.retryPreparation || /^98k(?:连接|响应)中断$/u.test(error.message)) {
|
||||
throw Error('network error: '+error.message);
|
||||
}
|
||||
throw error;
|
||||
}).finally(()=>init.signal?.removeEventListener('abort',abort));
|
||||
}).finally(()=>signal.removeEventListener('abort',abort));
|
||||
completed.then(() => { try { controller.close(); } catch {} }, error => {
|
||||
rejectHeaders(error);
|
||||
try { controller.error(error); } catch {}
|
||||
|
||||
@ -65,7 +65,8 @@ export class NativeControlClient {
|
||||
}
|
||||
async openAndAuthenticate() {
|
||||
const { port, tokenFile, connectTimeoutMs } = this.connection;
|
||||
const socket = net.createConnection({ host: '127.0.0.1', port });
|
||||
// The native control protocol uses raw loopback TCP and bypasses HTTP(S) proxies.
|
||||
const socket = net.createConnection({ host: '127.0.0.1', port, keepAlive:true, keepAliveInitialDelay:20_000 });
|
||||
this.attach(socket);
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
|
||||
@ -7,8 +7,15 @@ delete process.env.PHOTOCRAFT_XIAOYI_BRIDGE_TOKEN;
|
||||
const errors = {
|
||||
'session-missing': '素材库未部署小壹知识库签发接口(HTTP 404),请联系管理员',
|
||||
'session-unavailable': '素材库小壹知识库签发服务不可用(HTTP 503),请联系管理员核对配置',
|
||||
'session-login': '素材库授权已失效,请重新登录',
|
||||
'session-forbidden': '当前账户无权使用小壹知识库',
|
||||
'session-network': '连不上素材库服务器,请检查网络、VPN 或代理',
|
||||
'session-timeout': '素材库换签请求超时,请检查网络后重试',
|
||||
unconfigured: '企业知识库宿主未配置',
|
||||
network: '企业知识库网络不可达',
|
||||
network: '连不上企业知识库服务器,请检查网络、VPN 或代理',
|
||||
timeout: '企业知识库请求超时,请检查网络后重试',
|
||||
server: '素材库换签服务端异常,请稍后重试',
|
||||
gateway: '小壹知识库服务端异常,请稍后重试',
|
||||
credential: '企业知识库用户凭据未配置或不可读取',
|
||||
boundary: '企业知识库请求边界无效',
|
||||
response: '企业知识库响应无效',
|
||||
@ -16,7 +23,9 @@ const errors = {
|
||||
|
||||
function transportError(category) {
|
||||
const error = Error(errors[category] ?? errors.response);
|
||||
error.network = category === 'network';
|
||||
error.retryExhausted = category === 'session-network' || category === 'session-timeout';
|
||||
error.retryable = category === 'gateway';
|
||||
error.network = category === 'network' || category === 'timeout' || error.retryExhausted;
|
||||
error.category = category;
|
||||
return error;
|
||||
}
|
||||
|
||||
@ -10,9 +10,10 @@ import { atomic, digest } from './store.mjs';
|
||||
import { loadSkills } from '@earendil-works/pi-coding-agent';
|
||||
import lockfile from 'proper-lockfile';
|
||||
import { nativeKnowledgeFetch } from './native-knowledge-http.mjs';
|
||||
import { knowledgeTiming, networkFailure, transientStatus } from './knowledge-network.mjs';
|
||||
import origins from './enterprise-knowledge-origins.json' with { type: 'json' };
|
||||
|
||||
const delays = [2000, 5000, 12000];
|
||||
const delays = [200, 500];
|
||||
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
|
||||
function fileAt(root, relative) {
|
||||
@ -38,21 +39,25 @@ async function matches(file, item) {
|
||||
}
|
||||
|
||||
async function httpError(response) {
|
||||
const body = await response.json().catch(() => ({}));
|
||||
const body = await response.json().catch(error => {
|
||||
if (error instanceof SyntaxError) return {};
|
||||
throw error;
|
||||
});
|
||||
const messages = {
|
||||
401: '小壹知识库连接已失效,请在小壹设置中检测连接',
|
||||
401: '小壹知识库连接已失效,请重新登录素材库后检测连接',
|
||||
403: '当前连接无权读取小壹知识,请联系知识库管理员',
|
||||
410: '此小壹知识版本已撤回。已完整校验的本地工程可继续使用原版本',
|
||||
};
|
||||
const message = body.code === 'not_published' ? '此模板还没有发布小壹版本'
|
||||
const message = body.code === 'knowledge_session_misconfigured' ? '小壹知识库自动授权配置错误,请联系管理员'
|
||||
: body.code === 'not_published' ? '此模板还没有发布小壹版本'
|
||||
: response.status === 404 && !body.code ? '当前知识库地址没有提供小壹制作通道,请联系知识库管理员'
|
||||
: messages[response.status] ?? body.error ?? '小壹知识库请求失败';
|
||||
: messages[response.status] ?? (response.status >= 500 ? '小壹知识库服务端异常,请稍后重试' : body.error ?? '小壹知识库请求失败');
|
||||
const retry = response.headers.get('retry-after');
|
||||
const retryMs = retry === null ? Number(body.retryAfterSeconds) * 1000
|
||||
: /^\d+$/.test(retry) ? Number(retry) * 1000 : Date.parse(retry) - Date.now();
|
||||
return Object.assign(Error(message), {
|
||||
status: response.status, code: body.code,
|
||||
retryable: response.status === 429 || response.status >= 500 && body.retryable !== false,
|
||||
retryable: response.status === 429 || transientStatus(response.status, body.code) && body.retryable !== false,
|
||||
retryMs: Number.isFinite(retryMs) ? Math.max(0, retryMs) : undefined,
|
||||
});
|
||||
}
|
||||
@ -70,10 +75,10 @@ export async function acquireXiaoyiRelease(options) {
|
||||
signal?.throwIfAborted();
|
||||
try {
|
||||
return await operation();
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
if (attempt >= delays.length || !(error.network || error.retryable)) throw error;
|
||||
await sleep(error.retryMs ?? delays[attempt], undefined, {signal});
|
||||
} catch (cause) {
|
||||
const error = networkFailure(cause, signal);
|
||||
if (attempt >= delays.length || error.retryExhausted || !(error.network || error.retryable)) throw error;
|
||||
await sleep(error.retryMs ?? delays[attempt] + Math.random() * 100, undefined, {signal});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -252,7 +257,9 @@ export async function openXiaoyiSkills(store, templateId, signal, finishedGoal,
|
||||
}
|
||||
const {manifest, root, productionProfiles} = await acquireXiaoyiRelease({
|
||||
templateId, directory, cache:store.xiaoyiCache ?? path.join(path.dirname(store.dir), 'xiaoyi-blobs'), signal, pinnedKnowledgeVersion, metadataOnly, onProgress:store.xiaoyiProgress,
|
||||
fetch:(route, init) => fetch(new URL(route, origin), init),
|
||||
fetch:(route, init) => fetch(new URL(route, origin), {
|
||||
...init, redirect:'manual', ...knowledgeTiming(fetch, signal, /\/bundle$|\/blobs\//.test(route) ? 240_000 : 45_000),
|
||||
}),
|
||||
});
|
||||
const entry = fileAt(root, manifest.entrypoint);
|
||||
const resource = loadSkills({cwd:store.dir, agentDir:store.dir, skillPaths:[entry], includeDefaults:false});
|
||||
|
||||
@ -5,6 +5,8 @@ import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import net from 'node:net';
|
||||
import {createInterface} from 'node:readline';
|
||||
import {execFile} from 'node:child_process';
|
||||
import {promisify} from 'node:util';
|
||||
import {NativeControlClient as NativeCanvas} from '../src/native-control-client.mjs';
|
||||
|
||||
const pause=ms=>new Promise(resolve=>setTimeout(resolve,ms));
|
||||
@ -34,6 +36,22 @@ async function fixture(handle,authorize=()=>true){
|
||||
};
|
||||
}
|
||||
|
||||
test('native loopback connects directly even with Node environment proxy enabled',async()=>{
|
||||
const f=await fixture(({reply})=>reply({revision:7}));
|
||||
try{
|
||||
const client=new URL('../src/native-control-client.mjs',import.meta.url).href;
|
||||
const code=`import {NativeControlClient} from ${JSON.stringify(client)};
|
||||
const bridge=await NativeControlClient.connect(${JSON.stringify({...f.options,connectTimeoutMs:2000,rpcTimeoutMs:2000})});
|
||||
try { console.log((await bridge.read()).revision); } finally { bridge.close(); }`;
|
||||
const proxy='http://127.0.0.1:9';
|
||||
const {stdout}=await promisify(execFile)(process.execPath,['--input-type=module','-e',code],{
|
||||
env:{...process.env,NODE_USE_ENV_PROXY:'1',HTTP_PROXY:proxy,HTTPS_PROXY:proxy,ALL_PROXY:proxy,NO_PROXY:''},timeout:8000,
|
||||
});
|
||||
assert.equal(stdout.trim(),'7');
|
||||
assert.equal(f.connections,1);
|
||||
}finally{await f.close();}
|
||||
});
|
||||
|
||||
test('an idle EOF reconnects and authenticates only before a new read/edit, preserving run and CAS',async()=>{
|
||||
let revision=7;
|
||||
const f=await fixture(({q,socket,reply})=>{
|
||||
|
||||
@ -112,11 +112,58 @@ test('honors Retry-After before retrying', async t => {
|
||||
assert.deepEqual(pauses,[7000]);
|
||||
});
|
||||
|
||||
test('backs off 2, 5 and 12 seconds and reports failure to start', async t => {
|
||||
test('backs off twice with jitter and reports a network diagnosis', async t => {
|
||||
const {options,pauses} = await fixture(t);
|
||||
options.fetch = async () => {throw Object.assign(Error('offline'),{network:true});};
|
||||
await assert.rejects(acquireXiaoyiRelease(options),/无法开工/);
|
||||
assert.deepEqual(pauses,[2000,5000,12000]);
|
||||
await assert.rejects(acquireXiaoyiRelease(options),/无法开工:连不上企业知识库服务器/);
|
||||
assert.equal(pauses.length,2);
|
||||
assert.ok(pauses[0] >= 200 && pauses[0] < 300);
|
||||
assert.ok(pauses[1] >= 500 && pauses[1] < 600);
|
||||
});
|
||||
|
||||
test('catalog retries a timeout and a 503, then preserves cached fields and the draft offline', async t => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'xiaoyi-catalog-offline-'));
|
||||
t.after(() => fs.rm(root,{recursive:true,force:true}));
|
||||
const fields = [
|
||||
{id:'description',label:'产品说明',type:'text',placeholder:'填写产品亮点',multiline:true},
|
||||
{id:'name',label:'名称',type:'text',placeholder:'',multiline:false},
|
||||
{id:'legacy',label:'旧字段',type:'text'},
|
||||
];
|
||||
const input = {root,action:'catalog',brandName:'品牌',categoryName:'椅子'};
|
||||
const draft = path.join(root,'draft.json');
|
||||
await fs.writeFile(draft,'{"description":"手工填写"}');
|
||||
let calls = 0;
|
||||
const fetch = async () => {
|
||||
calls++;
|
||||
if (calls === 1) throw new DOMException('fixture timeout','TimeoutError');
|
||||
if (calls === 2) return Response.json({}, {status:503});
|
||||
return Response.json({items:[{templateId:'CHAIR',name:'椅子',brand:'品牌',category:'椅子',
|
||||
intake:{version:1,productFields:fields,barcodeFields:[]}}]});
|
||||
};
|
||||
const online = await templateRequest(input,{fetch});
|
||||
assert.equal(calls,3);
|
||||
assert.deepEqual(online.items[0].intake.productFields,fields);
|
||||
calls = 0;
|
||||
const offline = await templateRequest(input,{fetch:async()=>{
|
||||
calls++;
|
||||
throw new TypeError('fetch failed',{cause:Object.assign(Error('reset'),{code:'ECONNRESET'})});
|
||||
}});
|
||||
assert.equal(calls,3);
|
||||
assert.deepEqual(offline.items,online.items);
|
||||
assert.match(offline.notice,/检查网络、VPN 或代理.*本机缓存模板.*草稿已保留/);
|
||||
assert.equal(await fs.readFile(draft,'utf8'),'{"description":"手工填写"}');
|
||||
for (const [status,code,diagnosis] of [
|
||||
[401,'authentication_required',/重新登录/],
|
||||
[403,'forbidden',/无权/],
|
||||
[503,'knowledge_session_misconfigured',/配置错误/],
|
||||
]) {
|
||||
calls = 0;
|
||||
await assert.rejects(templateRequest(input,{fetch:async()=>{
|
||||
calls++;
|
||||
return Response.json({code},{status});
|
||||
}}),diagnosis);
|
||||
assert.equal(calls,1);
|
||||
}
|
||||
});
|
||||
|
||||
test('a rejected range restarts the same bundle without a range header', async t => {
|
||||
|
||||
@ -362,18 +362,32 @@ fn adopt_open_mapping(
|
||||
fn remember_open(binding: &Value) -> bool {
|
||||
binding["autoResume"] != true
|
||||
}
|
||||
fn body(response: Response, limit: u64) -> R<(u16, Value)> {
|
||||
fn body(mut response: Response, limit: u64) -> R<(u16, Value)> {
|
||||
let status = response.status().as_u16();
|
||||
Ok((status, response_json(&mut response, limit).map_err(|error| error.to_string())?))
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum JsonResponseError {
|
||||
#[error("{}", read_network_message(.0))]
|
||||
Read(#[from] std::io::Error),
|
||||
#[error("服务响应超过客户端限制")]
|
||||
TooLarge,
|
||||
#[error("服务没有返回有效结果(HTTP {0})")]
|
||||
Invalid(u16),
|
||||
}
|
||||
|
||||
fn response_json(response: &mut Response, limit: u64) -> Result<Value, JsonResponseError> {
|
||||
let status = response.status().as_u16();
|
||||
if response.content_length().is_some_and(|n| n > limit) {
|
||||
return Err("服务响应超过客户端限制".into());
|
||||
return Err(JsonResponseError::TooLarge);
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
response.take(limit + 1).read_to_end(&mut bytes).map_err(|_| "服务连接中断")?;
|
||||
response.take(limit + 1).read_to_end(&mut bytes)?;
|
||||
if bytes.len() as u64 > limit {
|
||||
return Err("服务响应超过客户端限制".into());
|
||||
return Err(JsonResponseError::TooLarge);
|
||||
}
|
||||
let v = serde_json::from_slice(&bytes).map_err(|_| format!("服务没有返回有效结果(HTTP {status})"))?;
|
||||
Ok((status, v))
|
||||
serde_json::from_slice(&bytes).map_err(|_| JsonResponseError::Invalid(status))
|
||||
}
|
||||
/// The public retained-result endpoint returns the ORIGINAL JSON body. Some documented
|
||||
/// envelopes also nest that original body under `data`; never discard a raw images.data array.
|
||||
@ -409,23 +423,105 @@ fn upstream_bypass_enabled(value: Option<&str>) -> bool { value == Some("1") }
|
||||
struct NetworkClient {
|
||||
normal: Client,
|
||||
upstream: Client,
|
||||
direct: Client,
|
||||
bypass_upstream: bool,
|
||||
}
|
||||
|
||||
fn network_builder(timeout: Duration) -> reqwest::blocking::ClientBuilder {
|
||||
Client::builder()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.retry(reqwest::retry::never())
|
||||
.connect_timeout(timeout.min(Duration::from_secs(5)))
|
||||
.timeout(timeout)
|
||||
.tcp_keepalive(Duration::from_secs(20))
|
||||
.tcp_keepalive_interval(Duration::from_secs(5))
|
||||
.tcp_keepalive_retries(3)
|
||||
.pool_idle_timeout(Duration::from_secs(15))
|
||||
}
|
||||
|
||||
fn network_message(error: &reqwest::Error) -> &'static str {
|
||||
if error.is_timeout() { "请求超时,请检查网络后重试" }
|
||||
else if error.is_builder() { "网络请求配置无效,请检查连接地址" }
|
||||
else { "连不上服务器,请检查网络、VPN 或代理" }
|
||||
}
|
||||
|
||||
fn read_timed_out(error: &std::io::Error) -> bool {
|
||||
error.kind() == std::io::ErrorKind::TimedOut ||
|
||||
error.get_ref().and_then(|cause| cause.downcast_ref::<reqwest::Error>()).is_some_and(reqwest::Error::is_timeout)
|
||||
}
|
||||
|
||||
const READ_TIMEOUT: &str = "读取响应超时,请检查网络后重试";
|
||||
const READ_INTERRUPTED: &str = "服务连接中断,请检查网络、VPN 或代理";
|
||||
|
||||
fn read_network_message(error: &std::io::Error) -> &'static str {
|
||||
if read_timed_out(error) { READ_TIMEOUT } else { READ_INTERRUPTED }
|
||||
}
|
||||
|
||||
fn transient_status(status: u16) -> bool { matches!(status, 502..=504) }
|
||||
|
||||
impl NetworkClient {
|
||||
fn build(direct: bool) -> reqwest::Result<Client> {
|
||||
let builder = network_builder(Duration::from_secs(30));
|
||||
if direct { builder.no_proxy().build() } else { builder.build() }
|
||||
}
|
||||
|
||||
fn new(bypass_upstream: bool) -> R<Self> {
|
||||
let build = |direct: bool| {
|
||||
let builder = Client::builder().redirect(reqwest::redirect::Policy::none()).retry(reqwest::retry::never()).timeout(Duration::from_secs(30));
|
||||
(if direct { builder.no_proxy() } else { builder }).build().map_err(|_| "本机网络服务无法初始化".to_owned())
|
||||
};
|
||||
let build = |direct| Self::build(direct).map_err(|_| "本机网络服务无法初始化".to_owned());
|
||||
let normal = build(false)?;
|
||||
let upstream = if bypass_upstream { build(true)? } else { normal.clone() };
|
||||
Ok(Self { normal, upstream })
|
||||
let direct = build(true)?;
|
||||
let upstream = if bypass_upstream { direct.clone() } else { normal.clone() };
|
||||
Ok(Self { normal, upstream, direct, bypass_upstream })
|
||||
}
|
||||
fn is_upstream(raw: &str) -> bool {
|
||||
url::Url::parse(raw).ok().is_some_and(|url| url.scheme() == "https" && url.host_str() == Some("api.vip98k.com")
|
||||
&& url.port_or_known_default() == Some(443) && url.username().is_empty() && url.password().is_none())
|
||||
}
|
||||
fn is_loopback(url: &url::Url) -> bool {
|
||||
match url.host() {
|
||||
Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
|
||||
Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
|
||||
Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
fn client(&self, raw: &str) -> &Client {
|
||||
if Self::is_upstream(raw) { &self.upstream } else { &self.normal }
|
||||
if url::Url::parse(raw).is_ok_and(|url| Self::is_loopback(&url)) { &self.direct }
|
||||
else if Self::is_upstream(raw) { &self.upstream } else { &self.normal }
|
||||
}
|
||||
fn read(&self, request: reqwest::blocking::RequestBuilder) -> reqwest::Result<Response> {
|
||||
self.read_until(request, None)
|
||||
}
|
||||
fn read_until(&self, request: reqwest::blocking::RequestBuilder, deadline: Option<Instant>) -> reqwest::Result<Response> {
|
||||
self.read_with(request, deadline, |response| transient_status(response.status().as_u16()))
|
||||
}
|
||||
fn read_with(&self, request: reqwest::blocking::RequestBuilder, deadline: Option<Instant>, mut retry_status: impl FnMut(&mut Response) -> bool) -> reqwest::Result<Response> {
|
||||
let (client, request) = request.build_split();
|
||||
let request = request?;
|
||||
if request.method() != reqwest::Method::GET { return client.execute(request); }
|
||||
let retry = request.try_clone().expect("GET requests have replayable bodies");
|
||||
let direct = Self::is_loopback(request.url()) || self.bypass_upstream && Self::is_upstream(request.url().as_str());
|
||||
let mut result = client.execute(request);
|
||||
for delay in [Some(150), Some(350), None] {
|
||||
let retryable = match &mut result {
|
||||
Ok(response) => retry_status(response),
|
||||
Err(error) => error.is_timeout() || error.is_connect() || error.is_request(),
|
||||
};
|
||||
let Some(delay) = delay.filter(|_| retryable) else { break; };
|
||||
let pause = Duration::from_millis(delay + u64::from(Uuid::new_v4().as_bytes()[0] % 80));
|
||||
let remaining = deadline.map(|deadline| deadline.saturating_duration_since(Instant::now()));
|
||||
if remaining.is_some_and(|remaining| remaining <= pause) { break; }
|
||||
drop(result);
|
||||
std::thread::sleep(pause);
|
||||
// A fresh client also resolves again after a network or proxy switch.
|
||||
let fresh = Self::build(direct)?;
|
||||
let mut request = retry.try_clone().expect("GET requests have replayable bodies");
|
||||
if let Some(deadline) = deadline {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
*request.timeout_mut() = Some(request.timeout().copied().unwrap_or(Duration::from_secs(30)).min(remaining));
|
||||
}
|
||||
result = fresh.execute(request);
|
||||
}
|
||||
result
|
||||
}
|
||||
fn get(&self, url: impl std::fmt::Display) -> reqwest::blocking::RequestBuilder { let url = url.to_string(); self.client(&url).get(url) }
|
||||
fn post(&self, url: impl std::fmt::Display) -> reqwest::blocking::RequestBuilder { let url = url.to_string(); self.client(&url).post(url) }
|
||||
@ -434,7 +530,7 @@ impl NetworkClient {
|
||||
}
|
||||
#[cfg(test)]
|
||||
impl From<Client> for NetworkClient {
|
||||
fn from(client: Client) -> Self { Self { normal: client.clone(), upstream: client } }
|
||||
fn from(client: Client) -> Self { Self { normal: client.clone(), upstream: client.clone(), direct: client, bypass_upstream: false } }
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@ -522,6 +618,7 @@ impl PortalFailure {
|
||||
(401, _) => ("sign_in_required", "素材库授权已过期或被撤销,请重新连接;本机作品已保留".into()),
|
||||
(403, _) => ("forbidden", "当前账户没有素材库访问权限,请核对账户或联系管理员;本机作品已保留".into()),
|
||||
(404, _) => ("unavailable", "资源不存在或无权访问".into()),
|
||||
(500..=599, _) => ("unavailable", format!("素材库服务端异常(HTTP {status}),请稍后重试")),
|
||||
_ => ("unavailable", format!("素材库请求失败(HTTP {status})")),
|
||||
};
|
||||
Self { state, http_status: Some(status), message }
|
||||
@ -636,25 +733,22 @@ impl Backend {
|
||||
}
|
||||
fn portal_json(&self, path: &str) -> Result<Value, PortalFailure> {
|
||||
let token = self.auth["access_token"].as_str().ok_or_else(|| PortalFailure::local("sign_in_required", "请先在素材库登录"))?;
|
||||
let r = self
|
||||
.http
|
||||
.get(format!("{}/api/desktop/{path}", self.origin))
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
.map_err(|_| PortalFailure::local("unavailable", "素材库暂时无法连接,本机草稿已保留"))?;
|
||||
let request = self.http.get(format!("{}/api/desktop/{path}", self.origin)).bearer_auth(token)
|
||||
.timeout(Duration::from_secs(8));
|
||||
let mut payload = Ok(Value::Null);
|
||||
let r = self.http.read_with(request, None, |response| {
|
||||
let status = response.status().as_u16();
|
||||
if transient_status(status) { return true; }
|
||||
if status == 401 { self.revoke_access("auth_revoked"); return false; }
|
||||
payload = response_json(response, MAX_JSON);
|
||||
status == 200 && matches!(payload, Err(JsonResponseError::Read(_)))
|
||||
})
|
||||
.map_err(|error| PortalFailure::local("unavailable", format!("素材库{};本机草稿已保留", network_message(&error))))?;
|
||||
let status = r.status().as_u16();
|
||||
if status == 401 { self.revoke_access("auth_revoked"); }
|
||||
let (code, v) = body(r, MAX_JSON).map_err(|error| {
|
||||
if status != 200 {
|
||||
PortalFailure::http(status, None)
|
||||
} else {
|
||||
PortalFailure::local("unavailable", format!("素材库连接失败:{error}"))
|
||||
}
|
||||
})?;
|
||||
if code != 200 {
|
||||
return Err(PortalFailure::http(code, v["code"].as_str()));
|
||||
if status != 200 {
|
||||
return Err(PortalFailure::http(status, payload.as_ref().ok().and_then(|value| value["code"].as_str())));
|
||||
}
|
||||
Ok(v)
|
||||
payload.map_err(|error| PortalFailure::local("unavailable", format!("素材库{error};本机草稿已保留")))
|
||||
}
|
||||
fn json(&self, path: &str) -> R<Value> {
|
||||
self.portal_json(path).map_err(|failure| failure.message)
|
||||
@ -679,7 +773,7 @@ impl Backend {
|
||||
self.check_dispatch()?;
|
||||
match self.validate_connection() {
|
||||
// 素材库只负责登录。暂时连不上时沿用本机已有登录;授权撤销或换号仍会拦下。
|
||||
Err(failure) if failure.state == "unavailable" => {}
|
||||
Err(failure) if failure.state == "unavailable" && failure.http_status.is_none_or(|status| status >= 500) => {}
|
||||
result => result.map_err(|failure| match failure.state {
|
||||
"sign_in_required" if failure.http_status == Some(401) => AUTH_REVOKED.into(),
|
||||
"sign_in_required" if failure.message == "账户状态不一致,请重新授权" => ACCOUNT_CHANGED.into(),
|
||||
@ -854,9 +948,9 @@ impl Backend {
|
||||
let catalog = serde_json::from_slice(&bytes).map_err(|_| "本地模型目录格式无效")?;
|
||||
return Ok((catalog, json!({"source":"local","elapsedMs":start.elapsed().as_millis()})));
|
||||
}
|
||||
let response = self.http.get(format!("{UPSTREAM}/api/v2/catalog/models"))
|
||||
.header(reqwest::header::ACCEPT_ENCODING, "gzip")
|
||||
.send().map_err(|_| "98k公开模型目录暂不可用")?;
|
||||
let request = self.http.get(format!("{UPSTREAM}/api/v2/catalog/models"))
|
||||
.header(reqwest::header::ACCEPT_ENCODING, "gzip");
|
||||
let response = self.http.read(request).map_err(|error| catalog_transport_error(&error))?;
|
||||
let headers_ms = start.elapsed().as_millis();
|
||||
let status = response.status().as_u16();
|
||||
if status != 200 { return Err(format!("98k公开模型目录暂不可用(HTTP {status})")); }
|
||||
@ -911,7 +1005,8 @@ impl Backend {
|
||||
}
|
||||
}
|
||||
fn key_catalog(&self, key: &str) -> R<Vec<String>> {
|
||||
let response = self.http.get(format!("{UPSTREAM}/v1/models")).bearer_auth(key).send().map_err(|error| catalog_transport_error(&error))?;
|
||||
let request = self.http.get(format!("{UPSTREAM}/v1/models")).bearer_auth(key);
|
||||
let response = self.http.read(request).map_err(|error| catalog_transport_error(&error))?;
|
||||
if response.status().as_u16() == 401 { return Err("个人Key校验失败(HTTP 401)".into()); }
|
||||
let (status, value) = body(response, MAX_JSON).map_err(|error| format!("98k模型目录读取失败:{error}"))?;
|
||||
if status != 200 {
|
||||
@ -1058,7 +1153,8 @@ impl Backend {
|
||||
Ok(result)
|
||||
}
|
||||
fn authorization_config(&self, origin: &str) -> R<bool> {
|
||||
let (status, config) = body(self.http.get(format!("{origin}/api/desktop/config")).send().map_err(|_| "素材库暂时无法连接")?, MAX_JSON)?;
|
||||
let request = self.http.get(format!("{origin}/api/desktop/config")).timeout(Duration::from_secs(8));
|
||||
let (status, config) = body(self.http.read(request).map_err(|error| network_message(&error))?, MAX_JSON)?;
|
||||
authorization_enabled(status, &config)
|
||||
}
|
||||
fn login(&mut self, input: &Value, tx: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<Value> {
|
||||
@ -1134,7 +1230,8 @@ impl Backend {
|
||||
}
|
||||
fn bytes(&self, path: &str) -> R<Vec<u8>> {
|
||||
let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?;
|
||||
let r = self.http.get(format!("{}/api/desktop/{path}", self.origin)).bearer_auth(token).send().map_err(|_| "素材下载连接中断")?;
|
||||
let request = self.http.get(format!("{}/api/desktop/{path}", self.origin)).bearer_auth(token);
|
||||
let r = self.http.read(request).map_err(|error| network_message(&error))?;
|
||||
if r.status().as_u16() == 401 {
|
||||
self.revoke_access("auth_revoked");
|
||||
let _ = self.clone().renew_portal_session();
|
||||
@ -1425,7 +1522,7 @@ impl Backend {
|
||||
if !recover { transfer::redact(&mut task); }
|
||||
let response = if recover {
|
||||
let id = task["requestId"].as_str().filter(|s| Uuid::parse_str(s).is_ok()).ok_or("原请求没有可公开查询的编号;保持待核查,不会重发")?;
|
||||
self.http.get(format!("{UPSTREAM}/api/external/requests/{id}/result")).bearer_auth(key).send()
|
||||
self.http.read(self.http.get(format!("{UPSTREAM}/api/external/requests/{id}/result")).bearer_auth(key))
|
||||
} else {
|
||||
let system = format!(
|
||||
"你是由壹点详情页画布 Agent。使用中文,简洁,不虚构产品事实。只能修改当前已存在且未锁定的图层。返回严格 JSON:{{\"reply\":\"简短说明\",\"edits\":[{{\"command\":\"type.edit\",\"params\":{{\"layer\":数字图层ID,\"text\":\"新文字\"}},\"label\":\"修改标题\"}}]}}。最多20步。可用命令仅 type.edit(layer,text,size,color,name)、layer.translate(layer,dx,dy,整数像素)、layer.setProps(layer,name,opacity 0到1,visible)。不能执行文件、终端、代码、脚本、网络。未要求改变的参数保持原样。分析产品或生成图片的请求不要伪装成已完成。文档:{}",
|
||||
@ -1459,7 +1556,7 @@ impl Backend {
|
||||
r.send()
|
||||
};
|
||||
let result = (|| -> R<Value> {
|
||||
let response = response.map_err(|_| "98k连接中断,执行结果待核查")?;
|
||||
let response = response.map_err(|error| format!("{};原请求保留待核查", network_message(&error)))?;
|
||||
if !recover && let Some(id) = response.headers().get("x-request-id").and_then(|v| v.to_str().ok()).filter(|s| Uuid::parse_str(s).is_ok()) {
|
||||
task["requestId"] = json!(id);
|
||||
write_json(&file, &task)?;
|
||||
@ -2509,6 +2606,46 @@ mod tests {
|
||||
assert!(std::ptr::eq(cloned.client("https://api.vip98k.com/v1/models"), &cloned.upstream));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jiansun_loopback_http_bypasses_proxy_environment() {
|
||||
const FIXTURE: &str = "JIANSUN_LOOPBACK_HTTP_FIXTURE";
|
||||
if let Ok(url) = std::env::var(FIXTURE) {
|
||||
let http = NetworkClient::new(false).unwrap();
|
||||
assert!(http.get(url).timeout(Duration::from_secs(2)).send().unwrap().status().is_success());
|
||||
return;
|
||||
}
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let deadline = Instant::now() + Duration::from_secs(8);
|
||||
loop {
|
||||
match listener.accept() {
|
||||
Ok((mut stream, _)) => {
|
||||
stream.set_nonblocking(false).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
|
||||
let mut request = [0; 1024];
|
||||
assert!(stream.read(&mut request).unwrap() > 0);
|
||||
stream.write_all(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n").unwrap();
|
||||
return;
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock && Instant::now() < deadline =>
|
||||
std::thread::sleep(Duration::from_millis(10)),
|
||||
Err(error) => panic!("direct loopback connection missing: {error}"),
|
||||
}
|
||||
}
|
||||
});
|
||||
let bad_proxy = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let proxy = format!("http://{}", bad_proxy.local_addr().unwrap());
|
||||
let child = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.arg("jiansun_loopback_http_bypasses_proxy_environment")
|
||||
.env(FIXTURE, format!("http://{address}/"))
|
||||
.env("HTTP_PROXY", &proxy).env("HTTPS_PROXY", &proxy).env("ALL_PROXY", &proxy)
|
||||
.env("NO_PROXY", "").output().unwrap();
|
||||
assert!(child.status.success(), "{}", String::from_utf8_lossy(&child.stdout));
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_catalog_failure_exposes_only_fixed_categories() {
|
||||
let classify = |timeout, connect, messages: &[&str]| catalog_failure_category(timeout, connect, messages.iter().map(|s| (*s).to_owned()));
|
||||
@ -2541,7 +2678,9 @@ mod tests {
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let server = std::thread::spawn(move || {
|
||||
for (status, code) in [(401, Some("session_expired")), (403, Some("forbidden")),
|
||||
(503, Some("service_unavailable")), (502, None), (403, Some("feature_disabled"))] {
|
||||
(503, Some("service_unavailable")), (502, None), (403, Some("feature_disabled"))]
|
||||
.into_iter().flat_map(|entry| std::iter::repeat_n(entry, if transient_status(entry.0) { 3 } else { 1 }))
|
||||
{
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
let mut bytes = [0; 8192];
|
||||
|
||||
@ -1813,6 +1813,8 @@ fn transient_image_preflight(error: &str) -> bool {
|
||||
let Some(cause) = error.strip_prefix("本次生图未提交。") else { return false };
|
||||
let cause = cause.strip_prefix("模型权限检查失败:").unwrap_or(cause);
|
||||
matches!(cause, "服务连接中断" | "98k模型目录读取失败:服务连接中断" | "98k公开模型目录暂不可用")
|
||||
|| cause.strip_prefix("98k模型目录读取失败:").is_some_and(|error|
|
||||
matches!(error, super::READ_TIMEOUT | super::READ_INTERRUPTED))
|
||||
|| cause.starts_with("98k暂时无法连接(")
|
||||
|| [408, 429, 502, 503, 504].iter().any(|status| {
|
||||
cause == format!("98k公开模型目录暂不可用(HTTP {status})")
|
||||
|
||||
@ -143,15 +143,16 @@ fn download(backend: &Backend, root: &Path, latest: &Value, progress: impl Fn(u6
|
||||
if received < size {
|
||||
let query = release_query("version", &version);
|
||||
let endpoint = format!("{}/api/desktop/client-release/download?{query}", backend.origin);
|
||||
let response = backend.http.get(&endpoint).bearer_auth(token).send().map_err(|e| update_network_error(&e))?;
|
||||
let request = backend.http.get(&endpoint).bearer_auth(token).timeout(Duration::from_secs(8));
|
||||
let response = backend.http.read(request).map_err(|e| update_network_error(&e))?;
|
||||
if response.status() != StatusCode::FOUND {
|
||||
return Err(format!("素材库下载入口返回 HTTP {}", response.status().as_u16()));
|
||||
}
|
||||
let location = response.headers().get(header::LOCATION).and_then(|value| value.to_str().ok()).ok_or("素材库下载地址缺失")?;
|
||||
let target = response.url().join(location).map_err(|_| "素材库下载地址无效")?;
|
||||
let request = backend.http.get(target).timeout(Duration::from_secs(900));
|
||||
let mut response =
|
||||
if received == 0 { request } else { request.header(header::RANGE, format!("bytes={received}-")) }.send().map_err(|e| update_network_error(&e))?;
|
||||
let request = backend.http.get(target).timeout(Duration::from_secs(90));
|
||||
let request = if received == 0 { request } else { request.header(header::RANGE, format!("bytes={received}-")) };
|
||||
let mut response = backend.http.read(request).map_err(|e| update_network_error(&e))?;
|
||||
match response.status() {
|
||||
StatusCode::OK => {
|
||||
output.set_len(0).map_err(io_error)?;
|
||||
@ -170,7 +171,8 @@ fn download(backend: &Backend, root: &Path, latest: &Value, progress: impl Fn(u6
|
||||
let mut buffer = [0; 64 * 1024];
|
||||
let mut reported = Instant::now();
|
||||
loop {
|
||||
let count = response.read(&mut buffer).map_err(|_| "更新包下载中断,可重新下载续传")?;
|
||||
let count = response.read(&mut buffer)
|
||||
.map_err(|error| format!("{};可重新下载并续传", read_network_message(&error)))?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
@ -355,7 +357,7 @@ mod tests {
|
||||
run(backend, json!({"op":"check","request":1}), tx, egui::Context::default());
|
||||
let Event::Json(_, Ok(receipt)) = rx.recv().unwrap() else { panic!("missing update status") };
|
||||
assert_eq!(receipt["patch"]["status"], "error");
|
||||
assert!(receipt["patch"]["error"].as_str().unwrap().contains("无法连接"));
|
||||
assert!(receipt["patch"]["error"].as_str().unwrap().contains("连不上服务器"));
|
||||
assert!(receipt["patch"]["checkedAt"].is_string());
|
||||
}
|
||||
|
||||
|
||||
@ -98,7 +98,10 @@ fn intake(value: &Value) -> R<Value> {
|
||||
if field.get("required").is_some_and(|value| !value.is_boolean()) {
|
||||
return Err("资料字段的必填标记无效".into());
|
||||
}
|
||||
for optional in ["help", "unit"] {
|
||||
if field.get("multiline").is_some_and(|value| !value.is_boolean()) {
|
||||
return Err("资料字段的多行标记无效".into());
|
||||
}
|
||||
for optional in ["help", "unit", "placeholder"] {
|
||||
if let Some(value) = field.get(optional) { string(value, 500, "资料字段说明")?; }
|
||||
}
|
||||
if let Some(options) = field.get("options") {
|
||||
@ -710,7 +713,7 @@ mod tests {
|
||||
"templateId":value["templateSelection"]["id"],
|
||||
"schema":{"version":1,
|
||||
"productFields":[{"id":"length","label":"长度","type":"number","unit":"cm"}],
|
||||
"barcodeFields":[{"id":"size","label":"规格","type":"text"}]},
|
||||
"barcodeFields":[{"id":"size","label":"规格","type":"text","placeholder":"请输入规格","multiline":true}]},
|
||||
"productValues":{"length":"1e"},
|
||||
"barcodeValues":{"001 Foo, A/B;甲":{"size":"大号"},"CY001307N35V01":{"size":"小号"}}
|
||||
});
|
||||
|
||||
@ -851,12 +851,12 @@ impl Backend {
|
||||
}
|
||||
self.check_dispatch()?;
|
||||
let token = self.auth["access_token"].as_str().ok_or("请先在素材库登录")?;
|
||||
let response = self
|
||||
let request = self
|
||||
.http
|
||||
.get(format!("{}/api/desktop/session", self.origin))
|
||||
.bearer_auth(token)
|
||||
.timeout(recovery_timeout(deadline, Duration::from_secs(30))?)
|
||||
.send();
|
||||
.timeout(recovery_timeout(deadline, Duration::from_secs(8))?);
|
||||
let response = self.http.read_until(request, deadline);
|
||||
// 素材库暂时连不上或服务端出错时沿用本机登录,只有明确的授权撤销或换号才拦下。
|
||||
let Ok(response) = response else { return self.check_dispatch(); };
|
||||
if response.status().is_server_error() {
|
||||
@ -1200,9 +1200,9 @@ impl Backend {
|
||||
request = request.header("Idempotency-Key", id);
|
||||
}
|
||||
check()?;
|
||||
let response = request.send().map_err(|_| {
|
||||
let response = self.http.read_until(request, deadline).map_err(|error| {
|
||||
wait.set(Some(RecoveryWait::Network));
|
||||
"原请求只读查询连接中断,保留待核查;不会重发"
|
||||
format!("{};原请求保留待核查", network_message(&error))
|
||||
})?;
|
||||
check()?;
|
||||
if let Some(last) = diagnostic["attempts"].as_array_mut().and_then(|a| a.last_mut()) {
|
||||
@ -1279,7 +1279,7 @@ impl Backend {
|
||||
if self.exiting() { return Err("客户端正在退出,未提交生图请求".into()); }
|
||||
self.check_dispatch()?;
|
||||
progress("98k 正在生成图片…", true);
|
||||
client.execute(request).map_err(|_| "生成连接中断,结果待核查;不会重发".into())
|
||||
client.execute(request).map_err(|error| stream::transport_error(&error))
|
||||
})?;
|
||||
if let Some(seconds) = response.headers().get(reqwest::header::RETRY_AFTER).and_then(|value| value.to_str().ok()).and_then(|value| value.parse::<u64>().ok()) {
|
||||
t["retryAfterSeconds"] = json!(seconds);
|
||||
@ -1310,14 +1310,14 @@ impl Backend {
|
||||
let uid = t["upstreamTaskId"].as_str().filter(|s| protocol::token(s)).ok_or("任务号无效")?;
|
||||
progress(if recover { "正在等待原任务结果…" } else { "正在生成图片…" }, false);
|
||||
check()?;
|
||||
let response = self.http
|
||||
let request = self.http
|
||||
.get(format!("{UPSTREAM}/extensions/v1/tasks/{uid}/result"))
|
||||
.bearer_auth(key)
|
||||
.timeout(recovery_timeout(deadline, Duration::from_secs(30))?)
|
||||
.send()
|
||||
.map_err(|_| {
|
||||
.timeout(recovery_timeout(deadline, Duration::from_secs(30))?);
|
||||
let response = self.http.read_until(request, deadline)
|
||||
.map_err(|error| {
|
||||
wait.set(Some(RecoveryWait::Network));
|
||||
"任务查询连接中断"
|
||||
network_message(&error)
|
||||
})?;
|
||||
check()?;
|
||||
if response.status() == reqwest::StatusCode::GONE {
|
||||
@ -1364,9 +1364,10 @@ impl Backend {
|
||||
}
|
||||
self.image_validate(deadline)?;
|
||||
check()?;
|
||||
let response = self.http.get(url).timeout(recovery_timeout(deadline, Duration::from_secs(30))?).send().map_err(|_| {
|
||||
let request = self.http.get(url).timeout(recovery_timeout(deadline, Duration::from_secs(30))?);
|
||||
let response = self.http.read_until(request, deadline).map_err(|error| {
|
||||
wait.set(Some(RecoveryWait::Network));
|
||||
"图片下载连接中断,保留原结果后可重取"
|
||||
format!("{};原结果已保留,可重新下载", network_message(&error))
|
||||
})?;
|
||||
let code = response.status().as_u16();
|
||||
if let Some(observed) = observed_wait("asset", code, &Value::Null) {
|
||||
|
||||
@ -9,6 +9,7 @@ use std::{
|
||||
net::{Ipv4Addr, SocketAddrV4, TcpListener, TcpStream},
|
||||
process::Command,
|
||||
sync::{Arc, LazyLock, Mutex, OnceLock},
|
||||
sync::atomic::{AtomicU8, Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
@ -21,11 +22,15 @@ const XIAOYI_CURRENT: &str = "/api/xiaoyi/v1/templates/key-check/current";
|
||||
const ORIGINS: &str = include_str!("../../../../detail-agent-pi/src/enterprise-knowledge-origins.json");
|
||||
const INVALID: &str = "企业知识库请求边界无效";
|
||||
const CREDENTIAL: &str = "企业知识库用户凭据未配置或不可读取";
|
||||
const NETWORK: &str = "企业知识库网络不可达";
|
||||
const NETWORK: &str = "连不上企业知识库服务器,请检查网络、VPN 或代理";
|
||||
const TIMEOUT: &str = "企业知识库请求超时,请检查网络后重试";
|
||||
const RESPONSE: &str = "企业知识库响应无效";
|
||||
const XIAOYI_ORIGIN_REQUIRED: &str = "请通过公司内网或 HTTPS 连接小壹制作知识库";
|
||||
|
||||
const PORTAL_UNAVAILABLE: &str = "素材库暂时无法连接,请稍后重试";
|
||||
const PORTAL_UNAVAILABLE: &str = "连不上素材库服务器,请检查网络、VPN 或代理";
|
||||
const PORTAL_TIMEOUT: &str = "素材库换签请求超时,请检查网络后重试";
|
||||
const PORTAL_SERVER: &str = "素材库换签服务端异常,请稍后重试";
|
||||
const GATEWAY: &str = "小壹知识库服务端异常,请稍后重试";
|
||||
const PORTAL_LOGIN: &str = "素材库授权已失效,请重新登录";
|
||||
const PORTAL_FORBIDDEN: &str = "当前账户无权使用小壹知识库";
|
||||
const AUTOMATIC_INVALID: &str = "小壹知识库自动授权无效,请联系管理员";
|
||||
@ -41,6 +46,7 @@ struct Account {
|
||||
access: super::AccountAccess,
|
||||
http: super::NetworkClient,
|
||||
cached: Arc<Mutex<Option<(String, std::time::Instant)>>>,
|
||||
channel: Arc<AtomicU8>,
|
||||
}
|
||||
|
||||
static ACCOUNT: LazyLock<Mutex<Option<Account>>> = LazyLock::new(|| Mutex::new(None));
|
||||
@ -69,6 +75,7 @@ pub(super) fn set_account(backend: &super::Backend) {
|
||||
access: backend.access.clone(),
|
||||
http: backend.http.clone(),
|
||||
cached: Arc::new(Mutex::new(None)),
|
||||
channel: Arc::new(AtomicU8::new(0)),
|
||||
});
|
||||
}
|
||||
|
||||
@ -82,9 +89,8 @@ pub(super) fn clear_account(backend: &super::Backend) {
|
||||
}
|
||||
}
|
||||
|
||||
fn automatic_credential() -> R<String> {
|
||||
let account = ACCOUNT.lock().map_err(|_| PORTAL_UNAVAILABLE)?.clone().ok_or(PORTAL_LOGIN)?;
|
||||
account_credential(&account)
|
||||
fn current_account() -> R<Account> {
|
||||
ACCOUNT.lock().map_err(|_| PORTAL_UNAVAILABLE)?.clone().ok_or_else(|| PORTAL_LOGIN.into())
|
||||
}
|
||||
|
||||
fn account_credential(account: &Account) -> R<String> {
|
||||
@ -94,19 +100,38 @@ fn account_credential(account: &Account) -> R<String> {
|
||||
account.access.check().map_err(|_| PORTAL_LOGIN)?;
|
||||
return Ok(token.clone());
|
||||
}
|
||||
let response = account.http.get(format!("{}/api/desktop/knowledge/session", account.origin))
|
||||
.bearer_auth(&account.token).send().map_err(|_| PORTAL_UNAVAILABLE)?;
|
||||
let request = account.http.get(format!("{}/api/desktop/knowledge/session", account.origin))
|
||||
.bearer_auth(&account.token).timeout(Duration::from_secs(8));
|
||||
let mut misconfigured = false;
|
||||
let mut payload = Ok(Value::Null);
|
||||
let response = account.http.read_with(request, None, |response| {
|
||||
let status = response.status().as_u16();
|
||||
if status == 200 {
|
||||
payload = super::response_json(response, super::MAX_JSON);
|
||||
return matches!(payload, Err(super::JsonResponseError::Read(_))) && account.access.check().is_ok();
|
||||
}
|
||||
if status == 503 {
|
||||
misconfigured = super::response_json(response, 16 * 1024).is_ok_and(|value|
|
||||
value["code"] == "knowledge_session_misconfigured");
|
||||
}
|
||||
super::transient_status(status) && !misconfigured && account.access.check().is_ok()
|
||||
}).map_err(|error| if error.is_timeout() { PORTAL_TIMEOUT } else { PORTAL_UNAVAILABLE })?;
|
||||
let status = response.status().as_u16();
|
||||
account.access.check().map_err(|_| PORTAL_LOGIN)?;
|
||||
match status {
|
||||
404 => return Err(SESSION_MISSING.into()),
|
||||
503 => return Err(SESSION_UNAVAILABLE.into()),
|
||||
503 if misconfigured => return Err(SESSION_UNAVAILABLE.into()),
|
||||
401 => return Err(PORTAL_LOGIN.into()),
|
||||
403 => return Err(PORTAL_FORBIDDEN.into()),
|
||||
200 => {}
|
||||
_ => return Err(PORTAL_UNAVAILABLE.into()),
|
||||
500..=599 => return Err(PORTAL_SERVER.into()),
|
||||
_ => return Err(AUTOMATIC_INVALID.into()),
|
||||
}
|
||||
let (_, value) = super::body(response, super::MAX_JSON).map_err(|_| AUTOMATIC_INVALID)?;
|
||||
let value = payload.map_err(|error| match error {
|
||||
super::JsonResponseError::Read(error) if super::read_timed_out(&error) => PORTAL_TIMEOUT,
|
||||
super::JsonResponseError::Read(_) => PORTAL_UNAVAILABLE,
|
||||
_ => AUTOMATIC_INVALID,
|
||||
})?;
|
||||
account.access.check().map_err(|_| PORTAL_LOGIN)?;
|
||||
let token = value["token"].as_str().filter(|token| token.starts_with(TOKEN_PREFIX))
|
||||
.ok_or(AUTOMATIC_INVALID)?;
|
||||
@ -122,10 +147,16 @@ fn account_credential(account: &Account) -> R<String> {
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
fn verify_automatic_key(key: &str) -> Value {
|
||||
let mut result = match origins() {
|
||||
Ok(endpoints) => verify_xiaoyi_key(key, &endpoints, || Ok(false)),
|
||||
Err(_) => json!({"status":null,"saved":false,"error":INVALID}),
|
||||
fn verify_automatic_key() -> Value {
|
||||
let response: R<_> = (|| {
|
||||
let account = current_account()?;
|
||||
let [origin, _] = origins()?;
|
||||
let (response, _) = automatic_response(&account, &origin, XIAOYI_CURRENT, &json!({"headers":{}}))?;
|
||||
Ok(response)
|
||||
})();
|
||||
let mut result = match response {
|
||||
Ok(response) => verified_key_response(response, || Ok(false)),
|
||||
Err(error) => json!({"status":null,"saved":false,"error":error}),
|
||||
};
|
||||
match result["status"].as_u64() {
|
||||
Some(401) => result["error"] = json!("知识库自动授权已失效,请重新登录素材库。"),
|
||||
@ -136,13 +167,8 @@ fn verify_automatic_key(key: &str) -> Value {
|
||||
}
|
||||
|
||||
pub(super) fn automatic_status() -> Value {
|
||||
match automatic_credential() {
|
||||
Ok(key) => {
|
||||
let result = verify_automatic_key(&key);
|
||||
json!({"mode":"automatic","error":result["error"].as_str().unwrap_or_default()})
|
||||
}
|
||||
Err(error) => json!({"mode":"unavailable","error":error}),
|
||||
}
|
||||
let result = configure_for_account(&Value::Null);
|
||||
json!({"mode":result["mode"],"error":result["error"].as_str().unwrap_or_default()})
|
||||
}
|
||||
|
||||
pub(super) fn configure_for_account(input: &Value) -> Value {
|
||||
@ -151,14 +177,9 @@ pub(super) fn configure_for_account(input: &Value) -> Value {
|
||||
result["mode"] = json!("manual");
|
||||
return result;
|
||||
}
|
||||
match automatic_credential() {
|
||||
Ok(key) => {
|
||||
let mut result = verify_automatic_key(&key);
|
||||
result["mode"] = json!("automatic");
|
||||
result
|
||||
}
|
||||
Err(error) => json!({"mode":"unavailable","status":null,"saved":false,"error":error}),
|
||||
}
|
||||
let mut result = verify_automatic_key();
|
||||
result["mode"] = if result["status"].is_null() { json!("unavailable") } else { json!("automatic") };
|
||||
result
|
||||
}
|
||||
|
||||
|
||||
@ -219,15 +240,24 @@ pub(super) fn configure_xiaoyi(input: &Value) -> Value {
|
||||
}
|
||||
|
||||
fn verify_xiaoyi_key(key: &str, origins: &[String], save: impl FnOnce() -> R<bool>) -> Value {
|
||||
let Ok(client) = MCP_CLIENT.as_ref() else {
|
||||
return json!({"status":null,"saved":false,"error":NETWORK});
|
||||
};
|
||||
let mut diagnosis = NETWORK;
|
||||
let response = origins.iter().filter(|origin| allows_xiaoyi_origin(origin)).find_map(|origin| {
|
||||
client.get(format!("{origin}{XIAOYI_CURRENT}")).bearer_auth(key).send().ok()
|
||||
let client = MCP_CLIENT.get(origin).ok()?;
|
||||
match client.get(format!("{origin}{XIAOYI_CURRENT}")).bearer_auth(key).send() {
|
||||
Ok(response) => Some(response),
|
||||
Err(error) => {
|
||||
diagnosis = if error.is_timeout() { TIMEOUT } else { NETWORK };
|
||||
None
|
||||
}
|
||||
}
|
||||
});
|
||||
let Some(response) = response else {
|
||||
return json!({"status":null,"saved":false,"error":NETWORK});
|
||||
return json!({"status":null,"saved":false,"error":diagnosis});
|
||||
};
|
||||
verified_key_response(response, save)
|
||||
}
|
||||
|
||||
fn verified_key_response(response: reqwest::blocking::Response, save: impl FnOnce() -> R<bool>) -> Value {
|
||||
let status = response.status().as_u16();
|
||||
let accepted = match status {
|
||||
200 => response.json::<Value>().is_ok_and(|body| {
|
||||
@ -303,10 +333,10 @@ impl Route {
|
||||
Ok(Self::Download)
|
||||
}
|
||||
(Some("GET"), path)
|
||||
if input["body"].is_null()
|
||||
if input["body"].is_null() && !path.contains('#')
|
||||
&& regex::Regex::new(
|
||||
r"\A/api/xiaoyi/v1/(?:templates|templates/[A-Za-z0-9][A-Za-z0-9_.-]*/(?:current|releases/[A-Za-z0-9][A-Za-z0-9_.-]*/(?:manifest|bundle))|blobs/[a-f0-9]{64})\z"
|
||||
).map_err(|_| INVALID)?.is_match(path) =>
|
||||
).map_err(|_| INVALID)?.is_match(path.split_once('?').map_or(path, |(route, _)| route)) =>
|
||||
{
|
||||
if allows_xiaoyi_origin(origin) { Ok(Self::Xiaoyi) } else { Err(XIAOYI_ORIGIN_REQUIRED.into()) }
|
||||
}
|
||||
@ -343,7 +373,10 @@ pub(super) fn exchange(input: &Value, mut emit: impl FnMut(Value) -> R<()>) -> R
|
||||
let token = std::env::var(BRIDGE_TOKEN).map_err(|_| INVALID)?;
|
||||
return relay_bridge(port.to_str().ok_or(INVALID)?.parse().map_err(|_| INVALID)?, &token, input, &mut emit);
|
||||
}
|
||||
exchange_route(route, input, || Err(CREDENTIAL.into()), automatic_credential, &mut emit)
|
||||
if route == Route::Xiaoyi {
|
||||
return exchange_automatic(¤t_account()?, input, &mut emit);
|
||||
}
|
||||
exchange_route(route, input, || Err(CREDENTIAL.into()), || Err(INVALID.into()), &mut emit)
|
||||
})();
|
||||
emit_error(result, &mut emit)
|
||||
}
|
||||
@ -352,10 +385,14 @@ fn emit_error(result: R<()>, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> {
|
||||
if let Err(error) = result {
|
||||
let (category, message) = match error.as_str() {
|
||||
NETWORK => ("network", NETWORK),
|
||||
TIMEOUT => ("timeout", TIMEOUT),
|
||||
CREDENTIAL => ("credential", CREDENTIAL),
|
||||
PORTAL_LOGIN => ("credential", PORTAL_LOGIN),
|
||||
PORTAL_FORBIDDEN => ("credential", PORTAL_FORBIDDEN),
|
||||
PORTAL_UNAVAILABLE => ("network", PORTAL_UNAVAILABLE),
|
||||
PORTAL_LOGIN => ("session-login", PORTAL_LOGIN),
|
||||
PORTAL_FORBIDDEN => ("session-forbidden", PORTAL_FORBIDDEN),
|
||||
PORTAL_UNAVAILABLE => ("session-network", PORTAL_UNAVAILABLE),
|
||||
PORTAL_TIMEOUT => ("session-timeout", PORTAL_TIMEOUT),
|
||||
PORTAL_SERVER => ("server", PORTAL_SERVER),
|
||||
GATEWAY => ("gateway", GATEWAY),
|
||||
SESSION_MISSING => ("session-missing", SESSION_MISSING),
|
||||
SESSION_UNAVAILABLE => ("session-unavailable", SESSION_UNAVAILABLE),
|
||||
AUTOMATIC_INVALID => ("credential", AUTOMATIC_INVALID),
|
||||
@ -367,18 +404,111 @@ fn emit_error(result: R<()>, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// reqwest blocking applies the client timeout to each response read.
|
||||
static HEALTH_CLIENT: LazyLock<reqwest::Result<Client>> = LazyLock::new(|| client(2));
|
||||
static MCP_CLIENT: LazyLock<reqwest::Result<Client>> = LazyLock::new(|| client(15));
|
||||
static DOWNLOAD_CLIENT: LazyLock<reqwest::Result<Client>> = LazyLock::new(|| client(180));
|
||||
// The blocking timeout covers headers and each body read. Node bounds the complete exchange.
|
||||
struct KnowledgeClients {
|
||||
timeout_seconds: u64,
|
||||
direct: OnceLock<reqwest::Result<Client>>,
|
||||
https: OnceLock<reqwest::Result<Client>>,
|
||||
}
|
||||
|
||||
impl KnowledgeClients {
|
||||
const fn new(timeout_seconds: u64) -> Self {
|
||||
Self { timeout_seconds, direct: OnceLock::new(), https: OnceLock::new() }
|
||||
}
|
||||
|
||||
fn get(&self, origin: &str) -> R<&Client> {
|
||||
let https = url::Url::parse(origin).is_ok_and(|url| url.scheme() == "https" && !super::NetworkClient::is_loopback(&url));
|
||||
let cache = if https { &self.https } else { &self.direct };
|
||||
cache.get_or_init(|| {
|
||||
let builder = super::network_builder(Duration::from_secs(self.timeout_seconds)).pool_max_idle_per_host(0);
|
||||
if https { builder.build() } else { builder.no_proxy().connect_timeout(Duration::from_secs(2)).build() }
|
||||
}).as_ref().map_err(|_| NETWORK.into())
|
||||
}
|
||||
}
|
||||
static HEALTH_CLIENT: KnowledgeClients = KnowledgeClients::new(2);
|
||||
static MCP_CLIENT: KnowledgeClients = KnowledgeClients::new(15);
|
||||
static METADATA_CLIENT: KnowledgeClients = KnowledgeClients::new(12);
|
||||
static DOWNLOAD_CLIENT: KnowledgeClients = KnowledgeClients::new(180);
|
||||
|
||||
#[cfg(test)]
|
||||
fn client(timeout_seconds: u64) -> reqwest::Result<Client> {
|
||||
Client::builder()
|
||||
.no_proxy()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.retry(reqwest::retry::never())
|
||||
.timeout(Duration::from_secs(timeout_seconds))
|
||||
.build()
|
||||
super::network_builder(Duration::from_secs(timeout_seconds)).no_proxy().build()
|
||||
}
|
||||
|
||||
fn is_large(path: &str) -> bool {
|
||||
let path = path.split_once('?').map_or(path, |(route, _)| route);
|
||||
path.ends_with("/bundle") || path.starts_with("/api/xiaoyi/v1/blobs/")
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum KnowledgeChannel { Direct = 1, Portal = 2 }
|
||||
|
||||
fn secure_portal(origin: &str) -> bool {
|
||||
super::portal_origin(origin).is_ok_and(|canonical| canonical == origin)
|
||||
}
|
||||
|
||||
fn automatic_response(
|
||||
account: &Account, origin: &str, path: &str, input: &Value,
|
||||
) -> R<(reqwest::blocking::Response, String)> {
|
||||
use KnowledgeChannel::{Direct, Portal};
|
||||
if !allows_xiaoyi_origin(origin) { return Err(XIAOYI_ORIGIN_REQUIRED.into()); }
|
||||
let last = account.channel.load(Ordering::Relaxed);
|
||||
let preferred = if last == Portal as u8 { [Portal, Direct] } else { [Direct, Portal] };
|
||||
let mut diagnosis = NETWORK;
|
||||
for channel in preferred {
|
||||
account.access.check().map_err(|_| PORTAL_LOGIN)?;
|
||||
let clients = if is_large(path) { &DOWNLOAD_CLIENT } else { &METADATA_CLIENT };
|
||||
let (client, address, key) = match channel {
|
||||
Direct => {
|
||||
if last != Direct as u8 {
|
||||
match HEALTH_CLIENT.get(origin)?.get(format!("{origin}/healthz")).send() {
|
||||
Ok(response) if response.status().is_success() => {}
|
||||
Err(error) if error.is_timeout() => { diagnosis = TIMEOUT; continue; }
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
(clients.get(origin)?, format!("{origin}{path}"), account_credential(account)?)
|
||||
}
|
||||
Portal => {
|
||||
if !secure_portal(&account.origin) { continue; }
|
||||
let address = format!("{}/api/desktop/knowledge/proxy{path}", account.origin);
|
||||
(account.http.client(&address), address, account.token.clone())
|
||||
}
|
||||
};
|
||||
account.access.check().map_err(|_| PORTAL_LOGIN)?;
|
||||
let result = Route::Xiaoyi.request(client, address, input)?.bearer_auth(&key)
|
||||
.timeout(Duration::from_secs(clients.timeout_seconds)).send();
|
||||
let mut response = match result {
|
||||
Ok(response) => response,
|
||||
Err(error) => {
|
||||
diagnosis = if error.is_timeout() { TIMEOUT } else { NETWORK };
|
||||
continue;
|
||||
}
|
||||
};
|
||||
account.access.check().map_err(|_| PORTAL_LOGIN)?;
|
||||
let status = response.status().as_u16();
|
||||
if super::transient_status(status) {
|
||||
if status == 503 && super::response_json(&mut response, 16 * 1024)
|
||||
.is_ok_and(|value| value["code"] == "knowledge_session_misconfigured") {
|
||||
return Err(SESSION_UNAVAILABLE.into());
|
||||
}
|
||||
diagnosis = GATEWAY;
|
||||
continue;
|
||||
}
|
||||
if response.status().is_success() || status == 404 {
|
||||
account.channel.store(channel as u8, Ordering::Relaxed);
|
||||
}
|
||||
return Ok((response, key));
|
||||
}
|
||||
// Probe both routes again on the next read if neither was reachable.
|
||||
account.channel.store(0, Ordering::Relaxed);
|
||||
Err(diagnosis.into())
|
||||
}
|
||||
|
||||
fn exchange_automatic(account: &Account, input: &Value, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> {
|
||||
let (response, key) = automatic_response(account, input["origin"].as_str().ok_or(INVALID)?,
|
||||
input["path"].as_str().ok_or(INVALID)?, input)?;
|
||||
emit_response(response, Some(&key), emit)
|
||||
}
|
||||
|
||||
fn exchange_route(
|
||||
@ -388,13 +518,15 @@ fn exchange_route(
|
||||
xiaoyi_key: impl FnOnce() -> R<String>,
|
||||
emit: &mut impl FnMut(Value) -> R<()>,
|
||||
) -> R<()> {
|
||||
let url = format!("{}{}", input["origin"].as_str().ok_or(INVALID)?, input["path"].as_str().ok_or(INVALID)?);
|
||||
let origin = input["origin"].as_str().ok_or(INVALID)?;
|
||||
let path = input["path"].as_str().ok_or(INVALID)?;
|
||||
let client = match route {
|
||||
Route::Health => &HEALTH_CLIENT,
|
||||
Route::Mcp => &MCP_CLIENT,
|
||||
Route::Xiaoyi if !is_large(path) => &METADATA_CLIENT,
|
||||
Route::Download | Route::Xiaoyi => &DOWNLOAD_CLIENT,
|
||||
}.as_ref().map_err(|_| NETWORK)?;
|
||||
let request = route.request(client, url, input)?;
|
||||
}.get(origin)?;
|
||||
let request = route.request(client, format!("{origin}{path}"), input)?;
|
||||
let key = match route {
|
||||
Route::Health => None,
|
||||
Route::Xiaoyi => Some(xiaoyi_key()?),
|
||||
@ -451,6 +583,7 @@ fn serve_bridge(
|
||||
allowed_origins: impl FnOnce() -> R<[String; 2]>,
|
||||
) -> R<()> {
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).map_err(|_| NETWORK)?;
|
||||
stream.set_write_timeout(Some(Duration::from_secs(15))).map_err(|_| NETWORK)?;
|
||||
let result = (|| {
|
||||
let Some(Ok(line)) = super::pi::bounded_line(&mut BufReader::new(&stream))? else {
|
||||
return Err(INVALID.into());
|
||||
@ -470,16 +603,23 @@ fn serve_bridge(
|
||||
if route != Route::Xiaoyi {
|
||||
return Err(INVALID.into());
|
||||
}
|
||||
exchange_route(route, input, || Err(INVALID.into()), || match key {
|
||||
Some(key) => normalize_key(key.to_str().ok_or(CREDENTIAL)?),
|
||||
None => automatic_credential(),
|
||||
}, &mut |frame| writeln!(stream, "{frame}").map_err(|_| NETWORK.into()))
|
||||
let emit = &mut |frame| writeln!(stream, "{frame}").map_err(|_| NETWORK.into());
|
||||
match key {
|
||||
Some(key) => exchange_route(route, input, || Err(INVALID.into()), ||
|
||||
normalize_key(key.to_str().ok_or(CREDENTIAL)?), emit),
|
||||
None => exchange_automatic(¤t_account()?, input, emit),
|
||||
}
|
||||
})();
|
||||
emit_error(result, &mut |frame| writeln!(stream, "{frame}").map_err(|_| NETWORK.into()))
|
||||
}
|
||||
|
||||
fn relay_bridge(port: u16, token: &str, input: &Value, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> {
|
||||
let mut stream = TcpStream::connect(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port)).map_err(|_| NETWORK)?;
|
||||
// Raw loopback TCP never consults HTTP_PROXY or the Windows proxy settings.
|
||||
let address = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port).into();
|
||||
let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(3)).map_err(|_| NETWORK)?;
|
||||
let idle = if is_large(input["path"].as_str().ok_or(INVALID)?) { 210 } else { 45 };
|
||||
stream.set_read_timeout(Some(Duration::from_secs(idle))).map_err(|_| NETWORK)?;
|
||||
stream.set_write_timeout(Some(Duration::from_secs(5))).map_err(|_| NETWORK)?;
|
||||
writeln!(stream, "{}", json!({"authorization":token,"request":input})).map_err(|_| NETWORK)?;
|
||||
let mut reader = BufReader::new(stream);
|
||||
while let Some(Ok(line)) = super::pi::bounded_line(&mut reader)? {
|
||||
@ -495,7 +635,11 @@ fn relay_bridge(port: u16, token: &str, input: &Value, emit: &mut impl FnMut(Val
|
||||
|
||||
fn send(request: RequestBuilder, key: Option<&str>, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> {
|
||||
let request = if let Some(key) = key { request.bearer_auth(key) } else { request };
|
||||
let mut response = request.send().map_err(|_| NETWORK)?;
|
||||
let response = request.send().map_err(|error| if error.is_timeout() { TIMEOUT } else { NETWORK })?;
|
||||
emit_response(response, key, emit)
|
||||
}
|
||||
|
||||
fn emit_response(mut response: reqwest::blocking::Response, key: Option<&str>, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> {
|
||||
let secret = key.map(|value| Finder::new(value.as_bytes()));
|
||||
let mut headers = serde_json::Map::new();
|
||||
for name in ["content-type", "mcp-session-id", "mcp-protocol-version", "retry-after", "etag", "content-range", "content-length"] {
|
||||
@ -518,7 +662,7 @@ fn stream_body(body: &mut impl Read, secret: Option<&Finder<'_>>, emit: &mut imp
|
||||
let mut pending = Vec::with_capacity(8192 + overlap);
|
||||
let mut chunk = [0; 8192];
|
||||
loop {
|
||||
let count = body.read(&mut chunk).map_err(|_| NETWORK)?;
|
||||
let count = body.read(&mut chunk).map_err(|error| if super::read_timed_out(&error) { TIMEOUT } else { NETWORK })?;
|
||||
pending.extend_from_slice(&chunk[..count]);
|
||||
if secret.is_some_and(|needle| needle.find(&pending).is_some()) {
|
||||
return Err(RESPONSE.into());
|
||||
@ -578,6 +722,7 @@ mod tests {
|
||||
let account = Account {
|
||||
origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(),
|
||||
access: access.clone(), http: client.into(), cached: Arc::new(Mutex::new(None)),
|
||||
channel: Arc::new(AtomicU8::new(0)),
|
||||
};
|
||||
assert!(matches!(account_credential(&account), Ok(token) if token == TOKEN));
|
||||
server.join().unwrap();
|
||||
@ -589,8 +734,10 @@ mod tests {
|
||||
#[test]
|
||||
fn jiansun_missing_knowledge_signer_returns_http_diagnostics() {
|
||||
for (status, body, code, message) in [
|
||||
(401, "{}", "session-login", PORTAL_LOGIN),
|
||||
(403, "{}", "session-forbidden", PORTAL_FORBIDDEN),
|
||||
(404, r#"{"code":"not_found"}"#, "session-missing", SESSION_MISSING),
|
||||
(503, r#"{"code":"knowledge_session_unavailable"}"#, "session-unavailable", SESSION_UNAVAILABLE),
|
||||
(503, r#"{"code":"knowledge_session_misconfigured"}"#, "session-unavailable", SESSION_UNAVAILABLE),
|
||||
] {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
@ -607,6 +754,7 @@ mod tests {
|
||||
origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(),
|
||||
access: super::super::AccountAccess::default(), http: client(5).unwrap().into(),
|
||||
cached: Arc::new(Mutex::new(None)),
|
||||
channel: Arc::new(AtomicU8::new(0)),
|
||||
};
|
||||
let error = account_credential(&account).unwrap_err();
|
||||
assert_eq!(error, message);
|
||||
@ -618,6 +766,109 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jiansun_knowledge_signer_retries_reset_and_transient_503() {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let server = std::thread::spawn(move || {
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
for attempt in 0..3 {
|
||||
let mut stream = loop {
|
||||
match listener.accept() {
|
||||
Ok((stream, _)) => break stream,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock && std::time::Instant::now() < deadline =>
|
||||
std::thread::sleep(Duration::from_millis(10)),
|
||||
Err(error) => panic!("missing retry {attempt}: {error}"),
|
||||
}
|
||||
};
|
||||
stream.set_nonblocking(false).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
|
||||
let lines = BufReader::new(&mut stream).lines();
|
||||
assert!(lines.map(Result::unwrap).take_while(|line| !line.is_empty())
|
||||
.any(|line| line == "authorization: Bearer synthetic-desktop-session"));
|
||||
if attempt == 0 {
|
||||
stream.shutdown(std::net::Shutdown::Both).unwrap();
|
||||
continue;
|
||||
}
|
||||
let status = if attempt == 1 { 503 } else { 200 };
|
||||
let body = if attempt == 1 { "{}".into() } else {
|
||||
json!({"token":"ekb_xiaoyi_session_retry-fixture",
|
||||
"expiresAt":(chrono::Utc::now() + chrono::Duration::seconds(300)).to_rfc3339()}).to_string()
|
||||
};
|
||||
write!(stream, "HTTP/1.1 {status} Fixture\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();
|
||||
}
|
||||
});
|
||||
let account = Account {
|
||||
origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(),
|
||||
access: super::super::AccountAccess::default(), http: super::super::NetworkClient::new(false).unwrap(),
|
||||
cached: Arc::new(Mutex::new(None)),
|
||||
channel: Arc::new(AtomicU8::new(0)),
|
||||
};
|
||||
assert_eq!(account_credential(&account).unwrap(), "ekb_xiaoyi_session_retry-fixture");
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jiansun_public_knowledge_uses_sticky_portal_for_check_manifest_and_stream() {
|
||||
let closed = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let intranet_address = closed.local_addr().unwrap();
|
||||
let intranet = format!("http://{intranet_address}");
|
||||
drop(closed);
|
||||
|
||||
let portal = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let account = Account {
|
||||
origin: format!("http://{}", portal.local_addr().unwrap()),
|
||||
token: "synthetic-desktop-portal-session".into(), account_id: "test-user".into(),
|
||||
access: super::super::AccountAccess::default(), http: super::super::NetworkClient::new(false).unwrap(),
|
||||
cached: Arc::new(Mutex::new(None)), channel: Arc::new(AtomicU8::new(0)),
|
||||
};
|
||||
const MANIFEST: &str = "/api/xiaoyi/v1/templates/chair/releases/v1/manifest";
|
||||
const BUNDLE: &str = "/api/xiaoyi/v1/templates/chair/releases/v1/bundle";
|
||||
let bytes = vec![b'a'; 20_000];
|
||||
let expected = bytes.clone();
|
||||
let server = std::thread::spawn(move || {
|
||||
for (path, body) in [
|
||||
(XIAOYI_CURRENT, br#"{"version":"v1"}"#.as_slice()),
|
||||
(MANIFEST, br#"{"templateId":"chair"}"#.as_slice()),
|
||||
(BUNDLE, bytes.as_slice()),
|
||||
] {
|
||||
let (mut stream, _) = portal.accept().unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut lines = BufReader::new(&mut stream).lines();
|
||||
assert_eq!(lines.next().unwrap().unwrap(), format!("GET /api/desktop/knowledge/proxy{path} HTTP/1.1"));
|
||||
let headers = lines.map(Result::unwrap).take_while(|line| !line.is_empty()).collect::<Vec<_>>();
|
||||
assert!(headers.iter().any(|line| line == "authorization: Bearer synthetic-desktop-portal-session"));
|
||||
if path == BUNDLE { assert!(headers.iter().any(|line| line == "range: bytes=5-")); }
|
||||
let status = if path == BUNDLE { "206 Partial Content" } else { "200 OK" };
|
||||
write!(stream, "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).unwrap();
|
||||
for chunk in body.chunks(4096) { stream.write_all(chunk).unwrap(); }
|
||||
}
|
||||
});
|
||||
|
||||
let (response, _) = automatic_response(&account, &intranet, XIAOYI_CURRENT, &json!({"headers":{}})).unwrap();
|
||||
assert_eq!(verified_key_response(response, || Ok(false))["status"], 200);
|
||||
assert_eq!(account.channel.load(Ordering::Relaxed), KnowledgeChannel::Portal as u8);
|
||||
let recovered_intranet = TcpListener::bind(intranet_address).unwrap();
|
||||
recovered_intranet.set_nonblocking(true).unwrap();
|
||||
for (path, expected) in [(MANIFEST, br#"{"templateId":"chair"}"#.as_slice()), (BUNDLE, expected.as_slice())] {
|
||||
let mut frames = Vec::new();
|
||||
let headers = if path == BUNDLE { json!({"range":"bytes=5-"}) } else { json!({}) };
|
||||
exchange_automatic(&account, &json!({"origin":intranet,"path":path,"headers":headers}),
|
||||
&mut |frame| { frames.push(frame); Ok(()) }).unwrap();
|
||||
assert_eq!(frames[0]["status"], if path == BUNDLE { 206 } else { 200 });
|
||||
assert_eq!(frames.last().unwrap()["type"], "result");
|
||||
let streamed = frames.iter().filter_map(|frame| frame["data"].as_str())
|
||||
.flat_map(|chunk| STANDARD.decode(chunk).unwrap()).collect::<Vec<_>>();
|
||||
assert_eq!(streamed, expected);
|
||||
if path == BUNDLE { assert!(frames.len() > 3); }
|
||||
}
|
||||
assert_eq!(recovered_intranet.accept().unwrap_err().kind(), std::io::ErrorKind::WouldBlock);
|
||||
assert_eq!(automatic_response(&account, "http://218.93.9.38:20009", MANIFEST, &json!({"headers":{}}))
|
||||
.unwrap_err(), XIAOYI_ORIGIN_REQUIRED);
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jiansun_generic_key_has_no_configuration_or_import_entry() {
|
||||
let backend = include_str!("jiansun_backend.rs");
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
|
||||
use super::{Backend, R, Value, body, canvas_workspace, creation, json, project_file, read_json, write_json};
|
||||
use super::{Backend, R, Value, body, canvas_workspace, creation, json, network_message, project_file, read_json, write_json};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
|
||||
fs::{self, File},
|
||||
@ -519,9 +519,10 @@ impl Backend {
|
||||
let mut state = if state_file.exists() { read_json(&state_file)? } else { Value::Null };
|
||||
let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?;
|
||||
self.check_dispatch()?;
|
||||
let response = self.http.get(format!("{}/api/desktop/deliveries/{cloud_id}/detail", self.origin))
|
||||
.bearer_auth(token).timeout(Duration::from_secs(30)).send()
|
||||
.map_err(|_| "素材库提交记录暂时无法核对,请重新点击完结")?;
|
||||
let request = self.http.get(format!("{}/api/desktop/deliveries/{cloud_id}/detail", self.origin))
|
||||
.bearer_auth(token).timeout(Duration::from_secs(8));
|
||||
let response = self.http.read(request)
|
||||
.map_err(|error| format!("{};暂时无法核对提交记录,请重新点击完结", network_message(&error)))?;
|
||||
self.check_cloud_authority(response.status().as_u16())?;
|
||||
let (status, existing) = body(response, 2 * 1024 * 1024)?;
|
||||
if status != 200 {
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
//! Account-scoped prompt drafts. Mutations have durable identities; after an
|
||||
//! uncertain delivery only the server's read-only receipt can resolve them.
|
||||
use super::{json, Digest, R, Uuid, Value, Path, Read, fs, Backend, body, Sha256};
|
||||
use super::{json, Digest, R, Uuid, Value, Path, Read, fs, Backend, body, network_message, Sha256};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
|
||||
const CACHE_LIMIT: u64 = 16 * 1024 * 1024;
|
||||
static IO: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
@ -125,7 +126,9 @@ fn save(path: &Path, cache: &Cache) -> R<()> {
|
||||
|
||||
fn read_remote(b: &Backend, path: &str) -> R<(u16, Value)> {
|
||||
let token = b.auth["access_token"].as_str().ok_or("请先登录素材库")?;
|
||||
let response = b.http.get(format!("{}/api/desktop/{path}", b.origin)).bearer_auth(token).send().map_err(|_| "素材库连接不可用,本机提示词已保留")?;
|
||||
let request = b.http.get(format!("{}/api/desktop/{path}", b.origin)).bearer_auth(token)
|
||||
.timeout(Duration::from_secs(8));
|
||||
let response = b.http.read(request).map_err(|error| format!("{};本机提示词已保留", network_message(&error)))?;
|
||||
body(response, CACHE_LIMIT).map_err(|_| "素材库响应不可读取,本机提示词已保留".into())
|
||||
}
|
||||
|
||||
@ -520,16 +523,16 @@ mod tests {
|
||||
let server = std::thread::spawn(move || {
|
||||
let mut newer = prompt();
|
||||
newer.revision = 3;
|
||||
for step in 0..4 {
|
||||
for step in 0..6 {
|
||||
let (mut socket, _) = listener.accept().unwrap();
|
||||
socket.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
|
||||
let mut request = [0; 8192];
|
||||
let n = socket.read(&mut request).unwrap();
|
||||
let request = String::from_utf8_lossy(&request[..n]);
|
||||
if step == 2 { continue; } // refresh lost, after definite conflict
|
||||
let (status, value) = match step {
|
||||
0 => ("200 OK", json!({"prompts":[prompt()]})),
|
||||
1 => { assert!(request.starts_with("PUT ")); ("409 Conflict", json!({"code":"revision_conflict"})) },
|
||||
2..=4 => { assert!(request.starts_with("GET ")); ("503 Service Unavailable", json!({})) },
|
||||
_ => ("200 OK", json!({"prompts":[newer]})),
|
||||
};
|
||||
let body = value.to_string();
|
||||
|
||||
@ -611,12 +611,12 @@ impl Backend {
|
||||
}
|
||||
fn cloud_snapshot(&self, id: &str) -> R<Option<Value>> {
|
||||
let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?;
|
||||
let response = self
|
||||
let request = self
|
||||
.http
|
||||
.get(format!("{}/api/desktop/projects/desktop/{id}", self.origin))
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
.map_err(|_| "云端状态暂时无法核对,本机草稿保留")?;
|
||||
.bearer_auth(token).timeout(Duration::from_secs(8));
|
||||
let response = self.http.read(request)
|
||||
.map_err(|error| format!("{};本机草稿已保留", network_message(&error)))?;
|
||||
self.check_cloud_authority(response.status().as_u16())?;
|
||||
let (code, value) = body(response, MAX_JSON)?;
|
||||
if code == 404 {
|
||||
@ -707,9 +707,9 @@ impl Backend {
|
||||
let project = context["project"]["id"].as_str().and_then(|id| Uuid::parse_str(id).ok())
|
||||
.ok_or("云项目身份无效")?;
|
||||
let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?;
|
||||
let response = self.http.get(format!("{}/api/desktop/deliveries/{project}/detail", self.origin))
|
||||
.bearer_auth(token).timeout(Duration::from_secs(10)).send()
|
||||
.map_err(|_| "素材库连接失败,请稍后重试")?;
|
||||
let request = self.http.get(format!("{}/api/desktop/deliveries/{project}/detail", self.origin))
|
||||
.bearer_auth(token).timeout(Duration::from_secs(10));
|
||||
let response = self.http.read(request).map_err(|error| network_message(&error))?;
|
||||
self.check_cloud_authority(response.status().as_u16())?;
|
||||
let (status, value) = body(response, 16 * 1024)?;
|
||||
if status != 200 {
|
||||
@ -970,13 +970,13 @@ impl Backend {
|
||||
return Err("云端工程文件身份无效".into());
|
||||
}
|
||||
let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?;
|
||||
let response = self
|
||||
let request = self
|
||||
.http
|
||||
.get(format!("{}/api/desktop/projects/desktop/{id}/native/{source}", self.origin))
|
||||
.bearer_auth(token)
|
||||
.timeout(Duration::from_secs(300))
|
||||
.send()
|
||||
.map_err(|_| "工程下载中断,本机项目保留")?;
|
||||
.timeout(Duration::from_secs(90));
|
||||
let response = self.http.read(request)
|
||||
.map_err(|error| format!("{};本机项目已保留", network_message(&error)))?;
|
||||
self.check_cloud_authority(response.status().as_u16())?;
|
||||
if response.status().as_u16() != 200 {
|
||||
return Err(request_error(response.status().as_u16()));
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user