import { randomUUID } from 'node:crypto'; import { ModelTransport } from './transport.mjs'; import { probeNetwork } from './network-probe.mjs'; const problem = (message, status = 409) => Object.assign(new Error(message), { status }); const terminal = new Set(['passed', 'partial', 'failed', 'cancelled', 'interrupted']); export class NetworkDiagnostics { constructor(hub, options = {}) { this.hub = hub; this.options = options; this.active = new Map(); this.jobs = structuredClone(hub.store.storage.meta('modelNetworkDiagnostics', [])); let changed = false; for (const job of this.jobs) if (!terminal.has(job.status)) { job.status = 'interrupted'; job.finishedAt = new Date().toISOString(); job.code = 'HOST_RESTARTED'; for (const trial of job.trials) if (['running', 'pending'].includes(trial.status)) trial.status = 'interrupted'; if (job.stages.dns?.status === 'running') job.stages.dns.status = 'interrupted'; changed = true; } if (changed) this.save(); } save() { this.hub.store.storage.transaction(() => this.hub.store.storage.setMeta('modelNetworkDiagnostics', this.jobs)); } view() { return { jobs: this.jobs.map(job => { const connection = this.hub.connections().find(row => row.id === job.connectionId); return { ...structuredClone(job), stale: !connection || connection.revision !== job.connectionRevision, currentConnectionRevision: connection?.revision ?? null }; }).reverse(), active: this.active.size, retained: 30, httpRequests: 0, modelRequests: 0 }; } start(input) { if (!input || Object.keys(input).length !== 2 || Object.keys(input).some(key => !['id', 'revision'].includes(key)) || !Number.isSafeInteger(input.revision)) throw problem('连接诊断需要所选连接及其原修订。', 400); if (this.closing || this.hub.provider.requestsClosing) throw problem('执行宿主正在停止连接诊断。'); if (this.active.size || this.hub.probing || this.hub.provider.activeRequests) throw problem('请等待正在执行的模型请求或连接诊断结束。'); const connection = this.hub.connection(input.id); if (connection.revision !== input.revision) throw problem('连接已变化,请刷新后重新选择诊断。'); const url = new URL(connection.baseUrl); if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw problem('连接地址无法用于网络诊断。', 400); const provider = this.hub.provider, customTransport = !!provider.fetcher; const transport = provider.transport ??= new ModelTransport(); const profile = structuredClone(transport.profile); const target = { endpoint: connection.baseUrl, origin: url.origin, host: url.hostname.replace(/^\[|\]$/g, ''), port: Number(url.port || (url.protocol === 'https:' ? 443 : 80)), scheme: url.protocol }; const budgetMs = this.options.budgetMs ?? Math.min(12000, profile.connectTimeoutMs + 2000); const job = { schemaVersion: 1, id: randomUUID(), connectionId: connection.id, connectionRevision: connection.revision, connectionName: connection.name, status: 'running', startedAt: new Date().toISOString(), finishedAt: null, target, transport: profile, route: { kind: 'direct-endpoint-only', proxyConfigured: profile.httpProxyConfigured || profile.httpsProxyConfigured, noProxyConfigured: profile.noProxyConfigured, customTransport, modelApiRouteVerified: false }, budgetMs, stages: {}, trials: [], elapsedMs: 0, httpRequests: 0, modelRequests: 0, credentialAccess: false }; const previous = this.jobs; this.jobs = [...this.jobs.slice(-29), job]; try { this.save(); } catch (error) { this.jobs = previous; throw error; } const controller = new AbortController(), operation = { job, controller, promise: null }; this.active.set(job.id, operation); const timer = setTimeout(() => controller.abort({ code: 'DIAGNOSTIC_DEADLINE' }), budgetMs); operation.promise = Promise.resolve().then(async () => { const result = await probeNetwork(target, profile, { ...this.options, ...(transport.connect?.lookup ? { lookup: transport.connect.lookup } : {}), signal: controller.signal, update: result => { Object.assign(job, result); this.save(); } }); Object.assign(job, result); if (controller.signal.aborted) { job.status = controller.signal.reason?.code === 'DIAGNOSTIC_DEADLINE' ? 'failed' : 'cancelled'; job.code = controller.signal.reason?.code; } else { const trials = job.trials.filter(row => row.status !== 'skipped'); const passed = trials.filter(row => row.status === 'passed').length; job.status = job.stages.dns.status !== 'passed' || !passed ? 'failed' : passed === trials.length ? 'passed' : 'partial'; } }).catch(() => { job.status = 'failed'; job.code = 'DIAGNOSTIC_INTERNAL_ERROR'; }).finally(() => { clearTimeout(timer); job.finishedAt = new Date().toISOString(); try { this.save(); } finally { this.active.delete(job.id); } }); operation.promise.catch(() => {}); return { job: this.view().jobs.find(row => row.id === job.id) }; } async stop(id, input) { if (!input || Object.keys(input).length) throw problem('停止诊断不接受额外参数。', 400); const job = this.jobs.find(row => row.id === id); if (!job) throw problem('连接诊断记录不存在。', 404); const operation = this.active.get(id); operation?.controller.abort({ code: 'DIAGNOSTIC_CANCELLED' }); await operation?.promise; return { job: this.view().jobs.find(row => row.id === id) }; } async stopAll() { this.closing = true; const operations = [...this.active.values()]; for (const operation of operations) operation.controller.abort({ code: 'HOST_STOPPED' }); await Promise.all(operations.map(operation => operation.promise)); } }