// 设备级单活调度器:整机同一时刻只运行一个插件进程(对齐 Python scheduler.py)。 // active.json 同路径同格式(跨端共享);switching/running 均视为忙;启动失败回滚空闲。 "use strict"; const fs = require("fs"); const path = require("path"); const config = require("./config"); const { nowStr } = require("./crypto"); const { makeLogger } = require("./logger"); const logger = makeLogger("scheduler"); const ACTIVE_PATH = path.join(config.APP_DATA, "active.json"); function readActive() { try { if (!fs.existsSync(ACTIVE_PATH)) return {}; const d = JSON.parse(fs.readFileSync(ACTIVE_PATH, "utf-8")); return d && typeof d === "object" ? d : {}; } catch (e) { return {}; } } function isBusy() { const s = readActive().status; return s === "running" || s === "switching"; } function writeActive(fields) { const d = { ...readActive(), ...fields }; d.userId = d.userId ?? ""; d.pluginId = d.pluginId ?? ""; d.version = d.version ?? ""; d.status = d.status ?? "idle"; d.startedAt = d.startedAt ?? ""; d.runId = d.runId ?? ""; try { fs.mkdirSync(config.APP_DATA, { recursive: true }); const tmp = ACTIVE_PATH + ".tmp"; fs.writeFileSync(tmp, JSON.stringify(d), "utf-8"); fs.renameSync(tmp, ACTIVE_PATH); // 原子写 } catch (e) { logger.warning(`写 active.json 失败:${e.message}`); } } function initActive() { fs.mkdirSync(config.APP_DATA, { recursive: true }); if (!fs.existsSync(ACTIVE_PATH)) { writeActive({ userId: "", pluginId: "", version: "", status: "idle", runId: "", startedAt: "" }); } else { const s = readActive().status; if (s === "running" || s === "switching") { logger.warning("检测到上次异常退出残留的运行状态(running/switching),复位为空闲"); writeActive({ status: "idle", userId: "", pluginId: "", version: "", runId: "", startedAt: "" }); } } } function current() { return readActive(); } function isActive(pluginId) { const a = readActive(); return a.status === "running" && a.pluginId === pluginId; } // ==================== 设备级单活(Promise 门闩) ==================== const _waiters = []; function _wake() { const ws = _waiters.splice(0); for (const r of ws) r(); } async function waitIdle() { while (isBusy()) { await new Promise((resolve) => _waiters.push(resolve)); } } // 抢占链(原子门闩):把「检查空闲 → 写 switching → 拉起 → 写 running」这段临界区串行化, // 保证同一时刻只有一个 requestStart 能进入启动段(不同平台命名空间并发提交时也不会双开进程)。 let _claimChain = Promise.resolve(); // 阻塞等待设备空闲后启动:startFn 负责拉起子进程并返回 run_id(不可阻塞)。 // 启动失败回滚"空闲"并唤醒等待者。 function requestStart(user, pluginId, version, startFn) { const run = _claimChain.then(async () => { await waitIdle(); writeActive({ status: "switching", startedAt: nowStr() }); try { const runId = await startFn(); writeActive({ userId: user, pluginId, version, status: "running", runId, startedAt: nowStr() }); return { ok: true, run_id: runId }; } catch (e) { writeActive({ status: "idle" }); _wake(); return { ok: false, error: `启动失败:${e.message}` }; } }); // 无论成功失败都推进链,避免一次异常卡死后续排队请求 _claimChain = run.then( () => {}, () => {} ); return run; } // 运行结束:若 active 仍是该插件则回空闲并唤醒等待者(幂等) function markDone(pluginId, runId) { const a = readActive(); if (a.pluginId === pluginId && (a.runId === runId || a.status === "running")) { writeActive({ status: "idle", userId: "", pluginId: "", version: "", runId: "", startedAt: "" }); _wake(); } } // ==================== 平台命名空间并发闸(同平台串行,保护共享 cookies) ==================== const _nsQueues = {}; const _nsInflight = {}; function nsLocked(platform) { const key = (platform || "").trim() || "local"; return (_nsInflight[key] || 0) > 0; } async function withNsLock(platform, fn) { const key = (platform || "").trim() || "local"; const prev = _nsQueues[key] || Promise.resolve(); const run = prev.then(async () => { _nsInflight[key] = (_nsInflight[key] || 0) + 1; try { return await fn(); } finally { _nsInflight[key] = (_nsInflight[key] || 0) - 1; } }); _nsQueues[key] = run.catch(() => {}); return run; } module.exports = { ACTIVE_PATH, readActive, isBusy, writeActive, initActive, current, isActive, requestStart, markDone, nsLocked, withNsLock, };