528 lines
17 KiB
TypeScript
528 lines
17 KiB
TypeScript
import { SimpleEmitter } from './simpleEmitter'
|
||
import {
|
||
buildPrinterComponentWsUrl,
|
||
canConnectLoopbackPrinterFromBrowser,
|
||
preflightPrinterComponentConnection
|
||
} from './printerComponentConnection'
|
||
|
||
export type PrinterComponentStatus = 'connected' | 'disconnected'
|
||
|
||
export type PrinterComponentPort = {
|
||
name: string
|
||
port: string
|
||
}
|
||
|
||
export type PrinterComponentStatusItem = {
|
||
name: string
|
||
status: PrinterComponentStatus
|
||
}
|
||
|
||
/** 失败自动重连配置(分用户+仓库持久化后由 store 下发) */
|
||
export interface PrinterReconnectConfig {
|
||
/** 主开关:是否开启失败自动重连 */
|
||
enabled?: boolean
|
||
/** 排除自动尝试/自动重连的组件名(仅可手动重连) */
|
||
excluded?: string[]
|
||
/** 基础重连间隔(ms),默认 3000 */
|
||
intervalMs?: number
|
||
/** 退避上限(ms),默认 30000 */
|
||
maxIntervalMs?: number
|
||
/** 连续失败达到该次数后暂停自动重连,默认 5(0=不限) */
|
||
maxConsecutiveFailures?: number
|
||
}
|
||
|
||
type PrinterWebSocket = WebSocket & {
|
||
_manualClose?: boolean
|
||
}
|
||
|
||
/** 与 printserver/core/printerComponentCore.js 保持一致 */
|
||
export const DEFAULT_PRINTER_COMPONENTS: PrinterComponentPort[] = [
|
||
{ name: '抖音', port: '13888' },
|
||
{ name: '拼多多', port: '5000' },
|
||
{ name: '快手', port: '16888/ks/printer' },
|
||
{ name: '京东', port: '9113' },
|
||
{ name: '菜鸟', port: '13528' },
|
||
{ name: '视频号', port: '12705' },
|
||
{ name: '小红书', port: '10818' },
|
||
{ name: 'LODOP', port: '8000/c_webskt' }
|
||
]
|
||
|
||
const MESSAGE_EVENT_MAP: Record<string, string> = {
|
||
LODOP: 'lodopMessage',
|
||
抖音: 'douyinMessage',
|
||
拼多多: 'pinduoduoMessage',
|
||
快手: 'kuaishouMessage',
|
||
京东: 'jingdongMessage',
|
||
菜鸟: 'cainiaoMessage',
|
||
视频号: 'shipinhaoMessage',
|
||
小红书: 'xiaohongshuMessage'
|
||
}
|
||
|
||
/** 打印组件 WebSocket 长连接管理(浏览器版) */
|
||
export class PrinterComponentCore extends SimpleEmitter {
|
||
private components = new Map<string, PrinterWebSocket>()
|
||
private ports = new Map<string, string>()
|
||
private status = new Map<string, PrinterComponentStatus>()
|
||
private reconnectTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
||
private connectGeneration = new Map<string, number>()
|
||
private autoReconnectEnabled = false
|
||
/** 排除自动尝试/自动重连的组件名(仅可手动重连) */
|
||
private excludedComponents = new Set<string>()
|
||
/** 失败自动重连基础间隔(ms) */
|
||
private reconnectIntervalMs = 3000
|
||
/** 失败自动重连退避上限(ms) */
|
||
private maxReconnectIntervalMs = 30000
|
||
/** 连续失败达到该次数后暂停(0=不限) */
|
||
private maxConsecutiveFailures = 5
|
||
/** 各组件连续失败次数(每成功一次/手动重连重置) */
|
||
private attempts = new Map<string, number>()
|
||
/** 各组件是否已暂停自动重连(连续失败达上限) */
|
||
private paused = new Map<string, boolean>()
|
||
|
||
constructor(components: PrinterComponentPort[] = DEFAULT_PRINTER_COMPONENTS) {
|
||
super()
|
||
components.forEach((item) => {
|
||
this.ports.set(item.name, item.port)
|
||
this.status.set(item.name, 'disconnected')
|
||
})
|
||
}
|
||
|
||
initAll(): void {
|
||
if (!canConnectLoopbackPrinterFromBrowser()) {
|
||
DEFAULT_PRINTER_COMPONENTS.forEach((item) => {
|
||
this.status.set(item.name, 'disconnected')
|
||
})
|
||
this.emit('loopbackAccessBlocked', { reason: 'insecure_context' })
|
||
return
|
||
}
|
||
// 登录 / 整页刷新后的“一次连接”:对所有组件各尝试一次(保留已连接)。
|
||
// 逐组件“自动重连”开关(excluded)只影响“失败后的自动重连”,不影响这里的一次性连接。
|
||
this.forEachPort((item) => {
|
||
const existing = this.components.get(item.name)
|
||
if (existing?.readyState === WebSocket.OPEN || existing?.readyState === WebSocket.CONNECTING) return
|
||
this.initComponent(item.name)
|
||
})
|
||
}
|
||
|
||
initComponent(name: string): void {
|
||
const port = this.ports.get(name)
|
||
if (!port) return
|
||
|
||
const existing = this.components.get(name)
|
||
if (existing?.readyState === WebSocket.OPEN || existing?.readyState === WebSocket.CONNECTING) {
|
||
return
|
||
}
|
||
|
||
if (!canConnectLoopbackPrinterFromBrowser()) {
|
||
this.updateStatus(name, 'disconnected')
|
||
return
|
||
}
|
||
|
||
const url = buildPrinterComponentWsUrl(port)
|
||
|
||
const connect = () => {
|
||
const generation = (this.connectGeneration.get(name) ?? 0) + 1
|
||
this.connectGeneration.set(name, generation)
|
||
|
||
if (this.components.has(name)) {
|
||
const existing = this.components.get(name)!
|
||
try {
|
||
existing._manualClose = true
|
||
existing.close()
|
||
} catch {
|
||
// ignore
|
||
}
|
||
this.components.delete(name)
|
||
}
|
||
|
||
if (this.reconnectTimers.has(name)) {
|
||
clearTimeout(this.reconnectTimers.get(name))
|
||
this.reconnectTimers.delete(name)
|
||
}
|
||
|
||
void (async () => {
|
||
await preflightPrinterComponentConnection(port)
|
||
if (this.connectGeneration.get(name) !== generation) return
|
||
|
||
const ws = new WebSocket(url) as PrinterWebSocket
|
||
if (this.connectGeneration.get(name) !== generation) {
|
||
ws._manualClose = true
|
||
try {
|
||
ws.close()
|
||
} catch {
|
||
// ignore
|
||
}
|
||
return
|
||
}
|
||
this.attachWebSocket(name, ws, connect)
|
||
})()
|
||
}
|
||
|
||
connect()
|
||
}
|
||
|
||
private attachWebSocket(name: string, ws: PrinterWebSocket, connect: () => void): void {
|
||
ws.onopen = () => {
|
||
this.attempts.set(name, 0)
|
||
this.paused.delete(name)
|
||
this.updateStatus(name, 'connected')
|
||
this.emitReconnectState(name)
|
||
}
|
||
|
||
ws.onclose = () => {
|
||
this.updateStatus(name, 'disconnected')
|
||
if (!ws._manualClose && this.shouldAutoReconnect(name)) {
|
||
this.scheduleReconnect(name, connect)
|
||
}
|
||
}
|
||
|
||
ws.onmessage = (event: MessageEvent) => {
|
||
const msg = typeof event.data === 'string' ? event.data : String(event.data ?? '')
|
||
const eventName = MESSAGE_EVENT_MAP[name]
|
||
if (eventName) {
|
||
this.emit(eventName, msg)
|
||
} else {
|
||
this.emit('printerComponentMessage', { name, message: msg })
|
||
}
|
||
}
|
||
|
||
ws.onerror = () => {
|
||
this.updateStatus(name, 'disconnected')
|
||
if (!ws._manualClose && this.shouldAutoReconnect(name)) {
|
||
this.scheduleReconnect(name, connect)
|
||
}
|
||
}
|
||
|
||
this.components.set(name, ws)
|
||
}
|
||
|
||
private scheduleReconnect(name: string, connectFn: () => void): void {
|
||
if (!this.shouldAutoReconnect(name)) return
|
||
if (this.reconnectTimers.has(name)) return
|
||
if (this.paused.get(name)) return
|
||
|
||
const attempts = this.attempts.get(name) ?? 0
|
||
if (this.maxConsecutiveFailures > 0 && attempts >= this.maxConsecutiveFailures) {
|
||
// 连续失败达上限:暂停自动重连,避免对未安装控件高频无效请求(等待手动重连/重新启用)
|
||
this.paused.set(name, true)
|
||
this.emitReconnectState(name)
|
||
return
|
||
}
|
||
|
||
this.attempts.set(name, attempts + 1)
|
||
const delay = Math.min(
|
||
this.reconnectIntervalMs * Math.pow(2, attempts),
|
||
this.maxReconnectIntervalMs
|
||
)
|
||
this.reconnectTimers.set(
|
||
name,
|
||
setTimeout(() => {
|
||
this.reconnectTimers.delete(name)
|
||
connectFn()
|
||
}, delay)
|
||
)
|
||
this.emitReconnectState(name)
|
||
}
|
||
|
||
addComponent(name: string, wsInstance: PrinterWebSocket): void {
|
||
this.components.set(name, wsInstance)
|
||
}
|
||
|
||
getComponent(name: string): PrinterWebSocket | undefined {
|
||
return this.components.get(name)
|
||
}
|
||
|
||
/** 经已建立的长连接发送(与 printServer printer.js component.send 一致) */
|
||
sendMessage(name: string, body: string): void {
|
||
const ws = this.components.get(name)
|
||
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
||
throw new Error(`打印组件「${name}」未连接,请确认控件已启动并在连接面板重连`)
|
||
}
|
||
ws.send(body)
|
||
}
|
||
|
||
/** 指定组件 WebSocket 是否已 OPEN */
|
||
isComponentOpen(name: string): boolean {
|
||
return this.components.get(name)?.readyState === WebSocket.OPEN
|
||
}
|
||
|
||
/**
|
||
* 优先使用长连接发送;未连接时触发 initComponent 并等待握手(浏览器直打面单用)。
|
||
* 若已有 CONNECTING 中的连接则等待其完成,不重复 initComponent 以免断开已有 ws。
|
||
*/
|
||
async sendMessageWhenReady(name: string, body: string, timeoutMs = 8000): Promise<void> {
|
||
const openWs = this.components.get(name)
|
||
if (openWs?.readyState === WebSocket.OPEN) {
|
||
openWs.send(body)
|
||
return
|
||
}
|
||
|
||
if (!canConnectLoopbackPrinterFromBrowser()) {
|
||
throw new Error(
|
||
'当前页面无法访问本机打印组件。请使用 HTTPS 打开系统,或在 Chrome 站点设置中允许「本地网络」访问后重试。',
|
||
)
|
||
}
|
||
|
||
const port = this.ports.get(name)
|
||
if (!port) {
|
||
throw new Error(`未知打印组件: ${name}`)
|
||
}
|
||
|
||
const deadline = Date.now() + timeoutMs
|
||
|
||
const ensureConnection = async (): Promise<void> => {
|
||
const ws = this.components.get(name)
|
||
if (ws?.readyState === WebSocket.OPEN || ws?.readyState === WebSocket.CONNECTING) {
|
||
return
|
||
}
|
||
await preflightPrinterComponentConnection(port)
|
||
this.initComponent(name)
|
||
}
|
||
|
||
await ensureConnection()
|
||
|
||
while (Date.now() < deadline) {
|
||
const ws = this.components.get(name)
|
||
if (ws?.readyState === WebSocket.OPEN) {
|
||
ws.send(body)
|
||
return
|
||
}
|
||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||
}
|
||
|
||
throw new Error(`打印组件「${name}」连接超时,请确认已安装并启动对应平台打印控件`)
|
||
}
|
||
|
||
removeComponent(name: string): void {
|
||
const ws = this.components.get(name)
|
||
if (!ws) return
|
||
|
||
ws._manualClose = true
|
||
try {
|
||
ws.close()
|
||
} catch {
|
||
// ignore
|
||
}
|
||
this.components.delete(name)
|
||
this.status.set(name, 'disconnected')
|
||
|
||
if (this.reconnectTimers.has(name)) {
|
||
clearTimeout(this.reconnectTimers.get(name))
|
||
this.reconnectTimers.delete(name)
|
||
}
|
||
}
|
||
|
||
getAllComponents(): Array<{ name: string; ws: PrinterWebSocket }> {
|
||
return Array.from(this.components.entries()).map(([name, ws]) => ({ name, ws }))
|
||
}
|
||
|
||
getPort(name: string): string | undefined {
|
||
return this.ports.get(name)
|
||
}
|
||
|
||
getAllPorts(): PrinterComponentPort[] {
|
||
return Array.from(this.ports.entries()).map(([name, port]) => ({ name, port }))
|
||
}
|
||
|
||
getStatus(name: string): PrinterComponentStatus | undefined {
|
||
return this.status.get(name)
|
||
}
|
||
|
||
getAllStatus(): PrinterComponentStatusItem[] {
|
||
return Array.from(this.status.entries()).map(([name, status]) => ({ name, status }))
|
||
}
|
||
|
||
getAutoReconnectEnabled(): boolean {
|
||
return this.autoReconnectEnabled
|
||
}
|
||
|
||
setAutoReconnectEnabled(enabled: boolean): void {
|
||
this.applyConfig({ enabled })
|
||
}
|
||
|
||
/** 组件是否被排除自动尝试/自动重连(仅可手动重连) */
|
||
isComponentExcluded(name: string): boolean {
|
||
return this.excludedComponents.has(name)
|
||
}
|
||
|
||
/** 当前排除名单(供 store/UI) */
|
||
getExcludedNames(): string[] {
|
||
return Array.from(this.excludedComponents)
|
||
}
|
||
|
||
/** 是否参与失败自动重连(未排除) */
|
||
participatesAutoReconnect(name: string): boolean {
|
||
return !this.isComponentExcluded(name)
|
||
}
|
||
|
||
/** 失败自动重连判定:主开关开 且 未排除 */
|
||
shouldAutoReconnect(name: string): boolean {
|
||
return this.autoReconnectEnabled && !this.isComponentExcluded(name)
|
||
}
|
||
|
||
/**
|
||
* 应用(用户+仓库)重连配置:不关闭已 OPEN socket,只影响失败重连的参与范围与节奏。
|
||
* 注意:此处不做自动尝试——登录“一次连接”由 initAll 触发;开启后的即时尝试由 retryParticipatingOnce 显式触发。
|
||
*/
|
||
applyConfig(cfg: PrinterReconnectConfig): void {
|
||
const prevEnabled = this.autoReconnectEnabled
|
||
|
||
if (cfg.enabled !== undefined) this.autoReconnectEnabled = cfg.enabled
|
||
if (typeof cfg.intervalMs === 'number' && Number.isFinite(cfg.intervalMs) && cfg.intervalMs > 0) {
|
||
this.reconnectIntervalMs = cfg.intervalMs
|
||
}
|
||
if (typeof cfg.maxIntervalMs === 'number' && Number.isFinite(cfg.maxIntervalMs) && cfg.maxIntervalMs > 0) {
|
||
this.maxReconnectIntervalMs = cfg.maxIntervalMs
|
||
}
|
||
if (
|
||
typeof cfg.maxConsecutiveFailures === 'number' &&
|
||
Number.isInteger(cfg.maxConsecutiveFailures) &&
|
||
cfg.maxConsecutiveFailures >= 0
|
||
) {
|
||
this.maxConsecutiveFailures = cfg.maxConsecutiveFailures
|
||
}
|
||
if (cfg.excluded !== undefined) {
|
||
const next = new Set(cfg.excluded)
|
||
// 新增排除:清掉其挂起重连计时与失败计数
|
||
next.forEach((name) => {
|
||
if (!this.excludedComponents.has(name)) {
|
||
const timer = this.reconnectTimers.get(name)
|
||
if (timer) {
|
||
clearTimeout(timer)
|
||
this.reconnectTimers.delete(name)
|
||
}
|
||
this.attempts.delete(name)
|
||
this.paused.delete(name)
|
||
}
|
||
})
|
||
// 移出排除:重置计数,允许其后续重新参与自动尝试
|
||
this.excludedComponents.forEach((name) => {
|
||
if (!next.has(name)) {
|
||
this.attempts.delete(name)
|
||
this.paused.delete(name)
|
||
}
|
||
})
|
||
this.excludedComponents = next
|
||
}
|
||
|
||
if (this.autoReconnectEnabled && !prevEnabled) {
|
||
// 由关→开:重置失败计数,重新开始有界自动重连
|
||
this.attempts.clear()
|
||
this.paused.clear()
|
||
}
|
||
if (!this.autoReconnectEnabled) {
|
||
this.clearAllReconnectTimers()
|
||
}
|
||
|
||
this.emit('autoReconnectChange', { enabled: this.autoReconnectEnabled })
|
||
}
|
||
|
||
/**
|
||
* 对“参与自动重连且当前未连接/未暂停/无挂起重连”的组件做一次性尝试。
|
||
* 用于:用户开启失败自动重连、组件从排除中恢复、换仓配置变更后。
|
||
*/
|
||
retryParticipatingOnce(): void {
|
||
if (!this.autoReconnectEnabled) return
|
||
this.forEachPort((item) => {
|
||
const name = item.name
|
||
if (this.isComponentExcluded(name)) return
|
||
if (this.paused.get(name)) return
|
||
if (this.reconnectTimers.has(name)) return
|
||
const existing = this.components.get(name)
|
||
if (existing?.readyState === WebSocket.OPEN || existing?.readyState === WebSocket.CONNECTING) return
|
||
this.initComponent(name)
|
||
})
|
||
}
|
||
|
||
reconnectComponent(name: string): void {
|
||
// 手动重连不受排除限制,并重置失败计数/暂停
|
||
this.attempts.delete(name)
|
||
this.paused.delete(name)
|
||
this.initComponent(name)
|
||
}
|
||
|
||
reconnectAll(): void {
|
||
// 手动“全部重连”:不受排除限制
|
||
this.forEachPort((item) => {
|
||
this.attempts.delete(item.name)
|
||
this.paused.delete(item.name)
|
||
this.initComponent(item.name)
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 页面刷新后的“一次重连”:对**所有**组件(不看逐组件“自动重连”开关/排除名单)重置失败计数并各尝试一次(保留已连接)。
|
||
* 与“失败自动重连”主开关无关;排除名单只约束“失败后的自动重连”。已挂起的退避计时会先清除,避免重复链。
|
||
*/
|
||
reconnectOnceAll(): void {
|
||
this.forEachPort((item) => {
|
||
const name = item.name
|
||
const timer = this.reconnectTimers.get(name)
|
||
if (timer) {
|
||
clearTimeout(timer)
|
||
this.reconnectTimers.delete(name)
|
||
}
|
||
this.attempts.delete(name)
|
||
this.paused.delete(name)
|
||
const existing = this.components.get(name)
|
||
if (existing?.readyState === WebSocket.OPEN || existing?.readyState === WebSocket.CONNECTING) return
|
||
this.initComponent(name)
|
||
})
|
||
}
|
||
|
||
disconnectAll(): void {
|
||
this.clearAllReconnectTimers()
|
||
this.forEachPort((item) => {
|
||
const name = item.name
|
||
const generation = (this.connectGeneration.get(name) ?? 0) + 1
|
||
this.connectGeneration.set(name, generation)
|
||
const ws = this.components.get(name)
|
||
if (ws) {
|
||
ws._manualClose = true
|
||
try {
|
||
ws.close()
|
||
} catch {
|
||
// ignore
|
||
}
|
||
this.components.delete(name)
|
||
}
|
||
this.attempts.delete(name)
|
||
this.paused.delete(name)
|
||
this.updateStatus(name, 'disconnected')
|
||
})
|
||
}
|
||
|
||
private forEachPort(fn: (item: PrinterComponentPort) => void): void {
|
||
this.ports.forEach((port, name) => fn({ name, port }))
|
||
}
|
||
|
||
private emitReconnectState(name: string): void {
|
||
this.emit('printerReconnectStateChange', {
|
||
name,
|
||
attempts: this.attempts.get(name) ?? 0,
|
||
paused: this.paused.get(name) ?? false,
|
||
excluded: this.isComponentExcluded(name)
|
||
})
|
||
}
|
||
|
||
/** 各组件重连状态快照(供 UI/面板刷新) */
|
||
getReconnectState(): Record<string, { attempts: number; paused: boolean }> {
|
||
const out: Record<string, { attempts: number; paused: boolean }> = {}
|
||
this.ports.forEach((_port, name) => {
|
||
out[name] = { attempts: this.attempts.get(name) ?? 0, paused: this.paused.get(name) ?? false }
|
||
})
|
||
return out
|
||
}
|
||
|
||
private clearAllReconnectTimers(): void {
|
||
this.reconnectTimers.forEach((timer) => clearTimeout(timer))
|
||
this.reconnectTimers.clear()
|
||
}
|
||
|
||
private updateStatus(name: string, newStatus: PrinterComponentStatus): void {
|
||
if (this.status.get(name) === newStatus) return
|
||
this.status.set(name, newStatus)
|
||
this.emit('printerComponentStatusChange', { name, status: newStatus })
|
||
}
|
||
}
|