feat: M0-M2 骨架落地(服务端/前端/宿主/数据库/积分引擎)
- server: Go 单二进制骨架,embed 内嵌前端,配置/迁移/HTTP 路由 - store: system.db + event.db 两套迁移,业务表 + 种子数据 - domain: 积分引擎(并列三口径/计分通道/流水/排名/破纪录)+ 68 个测试 - web: Vite + Vue 三入口骨架 + shared 层(类型/API/WebSocket 客户端) - console: Electron 宿主骨架(选屏/防熄屏/进程守护/托盘)
This commit is contained in:
1 parent
a61d793d79
commit
7d5d94f815
76 files changed
+10131
No files matched your search
@@ -0,0 +1,95 @@
|
||||
'use strict'
|
||||
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
|
||||
// 默认值写死在代码里:config.json 只覆盖要改的项。
|
||||
// 这样升级新增字段时老配置依然能用,现场也不容易配出半成品。
|
||||
const DEFAULTS = {
|
||||
server: {
|
||||
exe: 'scoreboard.exe',
|
||||
args: ['-config', 'config.yaml'],
|
||||
host: '127.0.0.1',
|
||||
port: 8080,
|
||||
autoStart: true,
|
||||
healthIntervalMs: 5000,
|
||||
restartDelayMs: 3000,
|
||||
// 0 表示无限重启;服务端是现场唯一进程,崩了必须拉起来
|
||||
maxRestarts: 0
|
||||
},
|
||||
display: {
|
||||
// all-secondary | all | specified
|
||||
selection: 'all-secondary',
|
||||
displays: [],
|
||||
pages: ['standings', 'medals', 'individual', 'results', 'records'],
|
||||
pageParam: 'page',
|
||||
kiosk: true,
|
||||
ignoreMouse: true,
|
||||
reloadEveryHours: 24,
|
||||
// 服务端迟迟没就绪时的兜底:超时后也把大屏开出来,避免现场一片黑
|
||||
waitForServerMs: 20000,
|
||||
backgroundColor: '#0b0f1a'
|
||||
},
|
||||
admin: {
|
||||
width: 1040,
|
||||
height: 760
|
||||
},
|
||||
log: {
|
||||
maxLines: 2000,
|
||||
file: 'logs/console.log',
|
||||
maxFileBytes: 4 * 1024 * 1024
|
||||
}
|
||||
}
|
||||
|
||||
function isPlainObject(value) {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function merge(base, override) {
|
||||
const out = isPlainObject(base) ? { ...base } : {}
|
||||
if (!isPlainObject(override)) return out
|
||||
for (const [key, value] of Object.entries(override)) {
|
||||
if (value === undefined) continue
|
||||
out[key] = isPlainObject(value) && isPlainObject(base[key]) ? merge(base[key], value) : value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function readJson(file) {
|
||||
try {
|
||||
const raw = fs.readFileSync(file, 'utf8')
|
||||
return { values: JSON.parse(raw), warning: null }
|
||||
} catch (err) {
|
||||
if (err.code === 'ENOENT') return { values: {}, warning: `配置文件不存在,使用内置默认值:${file}` }
|
||||
return { values: {}, warning: `配置文件无法解析,使用内置默认值:${file}(${err.message})` }
|
||||
}
|
||||
}
|
||||
|
||||
function loadConfig(configPath) {
|
||||
const { values, warning } = readJson(configPath)
|
||||
return {
|
||||
path: configPath,
|
||||
values: merge(DEFAULTS, values),
|
||||
warning
|
||||
}
|
||||
}
|
||||
|
||||
// 相对路径的 exe 需要按「部署包根目录」理解,而部署包根目录在不同形态下不同:
|
||||
// 开发时是 console/ 的上级,打包后是 exe 所在目录。逐个候选位置探测,避免写死。
|
||||
function resolveExecutable(exe, configPath) {
|
||||
if (!exe) return { path: null, candidates: [] }
|
||||
if (path.isAbsolute(exe)) return { path: exe, candidates: [exe] }
|
||||
|
||||
const configDir = path.dirname(configPath)
|
||||
const candidates = [
|
||||
configDir,
|
||||
process.cwd(),
|
||||
path.resolve(configDir, '..'),
|
||||
path.resolve(configDir, '..', 'dist')
|
||||
].map((dir) => path.resolve(dir, exe))
|
||||
|
||||
const found = candidates.find((candidate) => fs.existsSync(candidate))
|
||||
return { path: found || candidates[0], candidates: [...new Set(candidates)] }
|
||||
}
|
||||
|
||||
module.exports = { DEFAULTS, loadConfig, merge, resolveExecutable }
|
||||
@@ -0,0 +1,276 @@
|
||||
'use strict'
|
||||
|
||||
const os = require('os')
|
||||
const { BrowserWindow, screen } = require('electron')
|
||||
|
||||
const SELECTION = {
|
||||
ALL_SECONDARY: 'all-secondary',
|
||||
ALL: 'all',
|
||||
SPECIFIED: 'specified'
|
||||
}
|
||||
|
||||
// 大屏窗口管理:按显示器枚举结果开窗,绝不写死坐标。
|
||||
// 坐标一律用 DIP(display.bounds),页面内部再用 CSS 缩放适配,两边互不干扰。
|
||||
class DisplayManager {
|
||||
constructor({ values, server, log }) {
|
||||
this.display = values.display
|
||||
this.server = server
|
||||
this.log = log
|
||||
|
||||
this.enabled = false
|
||||
this.single = true
|
||||
this.boundSingle = null
|
||||
this.windows = new Map() // displayId -> { win, page, reloadTimer }
|
||||
this.screenListeners = []
|
||||
this.layoutTimer = null
|
||||
}
|
||||
|
||||
enable() {
|
||||
if (this.enabled) return
|
||||
this.enabled = true
|
||||
this.layout()
|
||||
}
|
||||
|
||||
pageFor(index) {
|
||||
const pages = Array.isArray(this.display.pages) && this.display.pages.length ? this.display.pages : ['standings']
|
||||
// 单屏没有编排可言,固定锁第一页(默认总积分榜)
|
||||
if (this.single) return pages[0]
|
||||
return pages[index % pages.length]
|
||||
}
|
||||
|
||||
pickDisplays() {
|
||||
const all = screen.getAllDisplays()
|
||||
const primary = screen.getPrimaryDisplay()
|
||||
|
||||
// 单屏机器上谈「扩展屏编排」没有意义,直接窗口化
|
||||
if (all.length <= 1) return { single: true, displays: all.slice(0, 1) }
|
||||
|
||||
const selection = this.display.selection || SELECTION.ALL_SECONDARY
|
||||
let picked
|
||||
if (selection === SELECTION.ALL) {
|
||||
picked = all.slice()
|
||||
} else if (selection === SELECTION.SPECIFIED) {
|
||||
picked = this.pickSpecified(all)
|
||||
} else {
|
||||
picked = all.filter((item) => item.id !== primary.id)
|
||||
}
|
||||
|
||||
// 只有整机就一块屏时才是「单屏测试模式」;笔记本 + 一块扩展屏属于多屏场景,
|
||||
// 扩展屏要正常 kiosk,不能退化成窗口化
|
||||
if (!picked.length) return { single: true, displays: [primary] }
|
||||
return { single: false, displays: picked }
|
||||
}
|
||||
|
||||
// displays 配置里可以写 display.id,也可以写 0 起的序号
|
||||
pickSpecified(all) {
|
||||
const wanted = Array.isArray(this.display.displays) ? this.display.displays : []
|
||||
const picked = []
|
||||
for (const key of wanted) {
|
||||
const match = typeof key === 'number' ? all.find((item) => item.id === key) || all[key] : all.find((item) => String(item.id) === String(key))
|
||||
if (match && !picked.includes(match)) picked.push(match)
|
||||
}
|
||||
return picked
|
||||
}
|
||||
|
||||
layout() {
|
||||
if (!this.enabled) return
|
||||
const { single, displays } = this.pickDisplays()
|
||||
this.single = single
|
||||
this.bindScreenListeners(single)
|
||||
|
||||
const wanted = new Set(displays.map((item) => item.id))
|
||||
for (const [displayId, entry] of [...this.windows]) {
|
||||
if (!wanted.has(displayId)) {
|
||||
this.destroyEntry(displayId, entry)
|
||||
}
|
||||
}
|
||||
|
||||
displays.forEach((display, index) => {
|
||||
const page = this.pageFor(index)
|
||||
const existing = this.windows.get(display.id)
|
||||
if (existing) {
|
||||
this.applyGeometry(existing.win, display, single)
|
||||
if (existing.page !== page) {
|
||||
existing.page = page
|
||||
this.loadPage(existing, display, page)
|
||||
}
|
||||
return
|
||||
}
|
||||
this.windows.set(display.id, this.createWindow(display, index, single, page))
|
||||
})
|
||||
|
||||
this.log.push('console', `大屏排布完成:${single ? '单屏窗口化' : `多屏 kiosk × ${displays.length}`},显示器 ${displays.map((d) => d.id).join(', ')}`)
|
||||
}
|
||||
|
||||
createWindow(display, index, single, page) {
|
||||
const bounds = display.bounds
|
||||
const win = new BrowserWindow({
|
||||
...this.geometryFor(display, single),
|
||||
show: false,
|
||||
frame: single,
|
||||
kiosk: !single && this.display.kiosk !== false,
|
||||
autoHideMenuBar: true,
|
||||
backgroundColor: this.display.backgroundColor || '#000000',
|
||||
title: `大屏 · ${page}`,
|
||||
webPreferences: {
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
// 大屏常年在后台焦点之外,默认节流会冻结动画和定时器
|
||||
backgroundThrottling: false
|
||||
}
|
||||
})
|
||||
|
||||
// 大屏页零交互控件;窗口层再兜一道,防止现场误触鼠标
|
||||
if (!single && this.display.ignoreMouse !== false) {
|
||||
win.setIgnoreMouseEvents(true)
|
||||
}
|
||||
|
||||
// F11 只在单屏模式下有意义(现场调试用),多屏 kiosk 不允许切走
|
||||
if (single) {
|
||||
win.webContents.on('before-input-event', (event, input) => {
|
||||
if (input.type === 'keyDown' && input.key === 'F11') {
|
||||
event.preventDefault()
|
||||
win.setFullScreen(!win.isFullScreen())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
win.once('ready-to-show', () => {
|
||||
if (!win.isDestroyed()) win.show()
|
||||
})
|
||||
|
||||
win.webContents.on('render-process-gone', (_event, details) => {
|
||||
this.log.push('console', `大屏渲染进程异常(display=${display.id},${details.reason}),将重载`)
|
||||
if (!win.isDestroyed()) win.webContents.reload()
|
||||
})
|
||||
|
||||
const entry = { win, page, reloadTimer: null }
|
||||
|
||||
// 无人值守跑 24h 以上,定时重载兜底内存与连接泄漏
|
||||
const hours = Number(this.display.reloadEveryHours) || 0
|
||||
if (hours > 0) {
|
||||
entry.reloadTimer = setInterval(() => {
|
||||
if (!win.isDestroyed()) win.webContents.reload()
|
||||
}, hours * 3600 * 1000)
|
||||
}
|
||||
|
||||
this.applyGeometry(win, display, single)
|
||||
this.loadPage(entry, display, page)
|
||||
this.log.push('console', `打开大屏窗口 display=${display.id} bounds=${bounds.width}x${bounds.height}@${bounds.x},${bounds.y} page=${page}`)
|
||||
return entry
|
||||
}
|
||||
|
||||
geometryFor(display, single) {
|
||||
const bounds = display.bounds
|
||||
if (!single) return { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height }
|
||||
// 单屏窗口化:不铺满,留出边距方便看管理窗口和调试
|
||||
const width = Math.round(bounds.width * 0.8)
|
||||
const height = Math.round(bounds.height * 0.8)
|
||||
return {
|
||||
x: bounds.x + Math.round((bounds.width - width) / 2),
|
||||
y: bounds.y + Math.round((bounds.height - height) / 2),
|
||||
width,
|
||||
height
|
||||
}
|
||||
}
|
||||
|
||||
applyGeometry(win, display, single) {
|
||||
if (!win || win.isDestroyed()) return
|
||||
if (single) {
|
||||
if (win.isKiosk()) win.setKiosk(false)
|
||||
if (win.isFullScreen()) win.setFullScreen(false)
|
||||
} else if (this.display.kiosk !== false) {
|
||||
win.setKiosk(true)
|
||||
}
|
||||
win.setBounds(this.geometryFor(display, single))
|
||||
}
|
||||
|
||||
loadPage(entry, display, page) {
|
||||
if (!entry || !entry.win || entry.win.isDestroyed()) return
|
||||
const url = this.urlFor(display, page)
|
||||
this.log.push('console', `大屏加载 ${url}`)
|
||||
entry.win.loadURL(url).catch((err) => {
|
||||
// 服务端还没起来时加载失败是正常的,健康检查通过后会重排重载
|
||||
this.log.push('console', `大屏加载失败(display=${display.id}):${err.message}`)
|
||||
})
|
||||
}
|
||||
|
||||
urlFor(display, page) {
|
||||
const params = new URLSearchParams()
|
||||
params.set(this.display.pageParam || 'page', page)
|
||||
// lock=1 告知页面锁死单页,不参与轮播
|
||||
params.set('lock', '1')
|
||||
params.set('screen', String(display.id))
|
||||
params.set('instance', `${os.hostname()}-${display.id}`)
|
||||
return `http://127.0.0.1:${this.server.port}/display?${params.toString()}`
|
||||
}
|
||||
|
||||
// 单屏模式要「行为冻结」:不跟随屏幕变化重排,所以连监听都不挂
|
||||
bindScreenListeners(single) {
|
||||
if (this.screenListeners.length && this.boundSingle === single) return
|
||||
this.unbindScreenListeners()
|
||||
this.boundSingle = single
|
||||
if (single) return
|
||||
|
||||
const schedule = () => {
|
||||
if (this.layoutTimer) clearTimeout(this.layoutTimer)
|
||||
// 分辨率/缩放变化会连续触发多次,防抖后再重排
|
||||
this.layoutTimer = setTimeout(() => {
|
||||
this.layoutTimer = null
|
||||
this.layout()
|
||||
}, 600)
|
||||
}
|
||||
|
||||
screen.on('display-metrics-changed', schedule)
|
||||
screen.on('display-added', schedule)
|
||||
screen.on('display-removed', schedule)
|
||||
this.screenListeners = [
|
||||
['display-metrics-changed', schedule],
|
||||
['display-added', schedule],
|
||||
['display-removed', schedule]
|
||||
]
|
||||
}
|
||||
|
||||
unbindScreenListeners() {
|
||||
for (const [event, handler] of this.screenListeners) {
|
||||
screen.removeListener(event, handler)
|
||||
}
|
||||
this.screenListeners = []
|
||||
}
|
||||
|
||||
destroyEntry(displayId, entry) {
|
||||
if (entry.reloadTimer) clearInterval(entry.reloadTimer)
|
||||
if (entry.win && !entry.win.isDestroyed()) entry.win.destroy()
|
||||
this.windows.delete(displayId)
|
||||
this.log.push('console', `关闭大屏窗口 display=${displayId}`)
|
||||
}
|
||||
|
||||
relayout() {
|
||||
if (!this.enabled) return
|
||||
for (const [, entry] of this.windows) {
|
||||
if (entry.win && !entry.win.isDestroyed()) entry.win.webContents.reload()
|
||||
}
|
||||
this.layout()
|
||||
}
|
||||
|
||||
getInfo() {
|
||||
return [...this.windows.entries()].map(([displayId, entry]) => ({
|
||||
displayId,
|
||||
page: entry.page,
|
||||
url: entry.win && !entry.win.isDestroyed() ? entry.win.webContents.getURL() : '',
|
||||
bounds: entry.win && !entry.win.isDestroyed() ? entry.win.getBounds() : null
|
||||
}))
|
||||
}
|
||||
|
||||
closeAll() {
|
||||
if (this.layoutTimer) clearTimeout(this.layoutTimer)
|
||||
this.unbindScreenListeners()
|
||||
for (const [displayId, entry] of [...this.windows]) {
|
||||
this.destroyEntry(displayId, entry)
|
||||
}
|
||||
this.enabled = false
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { DisplayManager, SELECTION }
|
||||
@@ -0,0 +1,299 @@
|
||||
'use strict'
|
||||
|
||||
const path = require('path')
|
||||
const {
|
||||
app,
|
||||
BrowserWindow,
|
||||
Menu,
|
||||
Tray,
|
||||
ipcMain,
|
||||
powerSaveBlocker,
|
||||
shell
|
||||
} = require('electron')
|
||||
|
||||
const { loadConfig, resolveExecutable } = require('./config')
|
||||
const { LogBus } = require('./log-bus')
|
||||
const { ServiceSupervisor } = require('./service')
|
||||
const { DisplayManager } = require('./displays')
|
||||
const { createTrayIcon } = require('./tray-icon')
|
||||
|
||||
// 现场只允许一个实例:两个 Console 会互相抢同一个服务端端口和同一块大屏
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
app.quit()
|
||||
} else {
|
||||
main()
|
||||
}
|
||||
|
||||
function main() {
|
||||
let cfg = null
|
||||
let log = null
|
||||
let service = null
|
||||
let displays = null
|
||||
let adminWindow = null
|
||||
let tray = null
|
||||
let powerBlockerId = null
|
||||
let displayFallbackTimer = null
|
||||
let displaysEnabled = false
|
||||
let quitting = false
|
||||
let shutdownDone = false
|
||||
|
||||
function resolveConfigPath() {
|
||||
if (process.env.SCOREBOARD_CONSOLE_CONFIG) {
|
||||
return path.resolve(process.env.SCOREBOARD_CONSOLE_CONFIG)
|
||||
}
|
||||
// 打包后 config.json 放在 exe 旁边,方便现场直接改,不藏在 asar 里
|
||||
if (app.isPackaged) {
|
||||
return path.join(path.dirname(app.getPath('exe')), 'config.json')
|
||||
}
|
||||
return path.join(__dirname, '..', 'config.json')
|
||||
}
|
||||
|
||||
function statusSnapshot() {
|
||||
const status = service ? service.status : { state: 'stopped', stateLabel: '已停止' }
|
||||
return {
|
||||
...status,
|
||||
configPath: cfg ? cfg.path : null,
|
||||
configWarning: cfg ? cfg.warning : null,
|
||||
displays: displays ? displays.getInfo() : [],
|
||||
powerSaveBlocked: powerBlockerId !== null ? powerSaveBlocker.isStarted(powerBlockerId) : false,
|
||||
appVersion: app.getVersion()
|
||||
}
|
||||
}
|
||||
|
||||
function sendToAdmin(channel, payload) {
|
||||
if (adminWindow && !adminWindow.isDestroyed()) {
|
||||
adminWindow.webContents.send(channel, payload)
|
||||
}
|
||||
}
|
||||
|
||||
function broadcastStatus() {
|
||||
sendToAdmin('service:status', statusSnapshot())
|
||||
}
|
||||
|
||||
function showAdmin() {
|
||||
if (!adminWindow || adminWindow.isDestroyed()) {
|
||||
createAdminWindow()
|
||||
return
|
||||
}
|
||||
if (adminWindow.isMinimized()) adminWindow.restore()
|
||||
adminWindow.show()
|
||||
adminWindow.focus()
|
||||
}
|
||||
|
||||
function createAdminWindow() {
|
||||
const { width, height } = cfg.values.admin
|
||||
adminWindow = new BrowserWindow({
|
||||
width,
|
||||
height,
|
||||
minWidth: 860,
|
||||
minHeight: 600,
|
||||
title: 'Scoreboard Console · 启动管理',
|
||||
backgroundColor: '#0f1420',
|
||||
show: false,
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, '..', 'renderer', 'preload.js'),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true
|
||||
}
|
||||
})
|
||||
|
||||
adminWindow.loadFile(path.join(__dirname, '..', 'renderer', 'index.html'))
|
||||
adminWindow.once('ready-to-show', () => adminWindow.show())
|
||||
|
||||
// 关窗只隐藏,服务端和守护逻辑要继续在托盘里跑
|
||||
adminWindow.on('close', (event) => {
|
||||
if (quitting) return
|
||||
event.preventDefault()
|
||||
adminWindow.hide()
|
||||
log.push('console', '管理窗口已最小化到托盘(服务端继续运行)')
|
||||
})
|
||||
|
||||
adminWindow.on('closed', () => {
|
||||
adminWindow = null
|
||||
})
|
||||
}
|
||||
|
||||
function ensureDisplays() {
|
||||
if (displaysEnabled || !displays) return
|
||||
displaysEnabled = true
|
||||
if (displayFallbackTimer) {
|
||||
clearTimeout(displayFallbackTimer)
|
||||
displayFallbackTimer = null
|
||||
}
|
||||
displays.enable()
|
||||
}
|
||||
|
||||
function buildTrayMenu() {
|
||||
const status = statusSnapshot()
|
||||
const busy = status.state === 'starting' || status.state === 'running' || status.state === 'stopping'
|
||||
return Menu.buildFromTemplate([
|
||||
{
|
||||
label: `服务端:${status.stateLabel}${status.healthy ? ' · 就绪' : ''}`,
|
||||
enabled: false
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{ label: '启动服务', enabled: !busy, click: () => service.start() },
|
||||
{ label: '停止服务', enabled: busy, click: () => service.stop() },
|
||||
{ label: '重启服务', enabled: busy, click: () => service.restart() },
|
||||
{ type: 'separator' },
|
||||
{ label: '打开管理端', click: () => showAdmin() },
|
||||
{
|
||||
label: '打开服务端管理面板',
|
||||
click: () => shell.openExternal(status.adminUrl || `http://127.0.0.1:${cfg.values.server.port}/admin`)
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '退出',
|
||||
click: () => {
|
||||
quitting = true
|
||||
app.quit()
|
||||
}
|
||||
}
|
||||
])
|
||||
}
|
||||
|
||||
function refreshTray() {
|
||||
if (!tray || tray.isDestroyed()) return
|
||||
const status = statusSnapshot()
|
||||
tray.setToolTip(`Scoreboard Console · ${status.stateLabel}${status.healthy ? ' · 就绪' : ''}`)
|
||||
tray.setContextMenu(buildTrayMenu())
|
||||
}
|
||||
|
||||
function createTray() {
|
||||
tray = new Tray(createTrayIcon())
|
||||
tray.setToolTip('Scoreboard Console')
|
||||
tray.setContextMenu(buildTrayMenu())
|
||||
tray.on('double-click', () => showAdmin())
|
||||
}
|
||||
|
||||
function registerIpc() {
|
||||
ipcMain.handle('service:get-status', () => statusSnapshot())
|
||||
ipcMain.handle('service:start', () => {
|
||||
service.start()
|
||||
return statusSnapshot()
|
||||
})
|
||||
ipcMain.handle('service:stop', async () => {
|
||||
await service.stop()
|
||||
return statusSnapshot()
|
||||
})
|
||||
ipcMain.handle('service:restart', async () => {
|
||||
await service.restart()
|
||||
return statusSnapshot()
|
||||
})
|
||||
ipcMain.handle('log:tail', () => (log ? log.tail() : []))
|
||||
ipcMain.handle('log:clear', () => {
|
||||
if (log) log.clear()
|
||||
return true
|
||||
})
|
||||
ipcMain.handle('display:relayout', () => {
|
||||
if (displays && displaysEnabled) displays.relayout()
|
||||
return statusSnapshot()
|
||||
})
|
||||
ipcMain.handle('app:open-external', (_event, url) => {
|
||||
// 只放行 http/https,避免管理窗口被注入的链接拉去执行本地协议
|
||||
if (typeof url === 'string' && /^https?:\/\//i.test(url)) {
|
||||
shell.openExternal(url)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
ipcMain.handle('app:open-admin-window', () => {
|
||||
showAdmin()
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
app.on('second-instance', () => showAdmin())
|
||||
|
||||
app.whenReady().then(() => {
|
||||
cfg = loadConfig(resolveConfigPath())
|
||||
log = new LogBus({
|
||||
maxLines: cfg.values.log.maxLines,
|
||||
file: path.resolve(path.dirname(cfg.path), cfg.values.log.file || 'logs/console.log'),
|
||||
maxFileBytes: cfg.values.log.maxFileBytes
|
||||
})
|
||||
|
||||
log.push('console', `Scoreboard Console v${app.getVersion()} 启动(配置:${cfg.path})`)
|
||||
if (cfg.warning) log.push('console', cfg.warning)
|
||||
|
||||
const resolved = resolveExecutable(cfg.values.server.exe, cfg.path)
|
||||
log.push('console', `服务端程序:${resolved.path}`)
|
||||
|
||||
service = new ServiceSupervisor({
|
||||
values: cfg.values,
|
||||
exePath: resolved.path,
|
||||
log
|
||||
})
|
||||
|
||||
displays = new DisplayManager({
|
||||
values: cfg.values,
|
||||
server: cfg.values.server,
|
||||
log
|
||||
})
|
||||
|
||||
log.onLine((line) => sendToAdmin('log:line', line))
|
||||
|
||||
service.on('status', (status) => {
|
||||
broadcastStatus()
|
||||
refreshTray()
|
||||
if (!status.healthy) return
|
||||
// 服务端恢复后必须让大屏重新加载,否则页面还停在断线兜底画面上
|
||||
if (displaysEnabled) displays.relayout()
|
||||
else ensureDisplays()
|
||||
})
|
||||
|
||||
createAdminWindow()
|
||||
createTray()
|
||||
registerIpc()
|
||||
|
||||
// 防熄屏要在服务端起来之前就生效,否则开机后第一段时间屏幕仍会休眠
|
||||
powerBlockerId = powerSaveBlocker.start('prevent-display-sleep')
|
||||
log.push('console', `防熄屏已启用(powerSaveBlocker=${powerBlockerId},生效=${powerSaveBlocker.isStarted(powerBlockerId)})`)
|
||||
|
||||
if (cfg.values.server.autoStart) {
|
||||
service.start()
|
||||
} else {
|
||||
log.push('console', '配置为不自动启动,等待手动启动服务端')
|
||||
}
|
||||
|
||||
// 服务端迟迟不健康(例如首次迁移很慢)也要把大屏开出来,别让现场只看到桌面
|
||||
const wait = Number(cfg.values.display.waitForServerMs) || 0
|
||||
if (wait > 0) {
|
||||
displayFallbackTimer = setTimeout(() => {
|
||||
displayFallbackTimer = null
|
||||
if (!displaysEnabled) {
|
||||
log.push('console', `等待服务端就绪超过 ${Math.round(wait / 1000)} 秒,先打开大屏窗口`)
|
||||
ensureDisplays()
|
||||
}
|
||||
}, wait)
|
||||
}
|
||||
})
|
||||
|
||||
// 常驻托盘:窗口全关也不退出,服务端要继续守着
|
||||
app.on('window-all-closed', () => {})
|
||||
|
||||
app.on('before-quit', (event) => {
|
||||
quitting = true
|
||||
if (shutdownDone) return
|
||||
event.preventDefault()
|
||||
|
||||
const finish = () => {
|
||||
if (displays) displays.closeAll()
|
||||
if (powerBlockerId !== null) powerSaveBlocker.stop(powerBlockerId)
|
||||
if (log) log.close()
|
||||
shutdownDone = true
|
||||
app.quit()
|
||||
}
|
||||
|
||||
if (service) {
|
||||
service.stop().then(finish).catch(finish)
|
||||
} else {
|
||||
finish()
|
||||
}
|
||||
})
|
||||
|
||||
app.on('quit', () => {
|
||||
if (service) service.dispose()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
'use strict'
|
||||
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
|
||||
// 日志总线:内存环形缓冲供管理窗口实时查看,同时落一份文件供现场排障。
|
||||
// 现场没有外网也没有终端,文件日志是事后定位问题的唯一线索。
|
||||
class LogBus {
|
||||
constructor(options = {}) {
|
||||
const { maxLines = 2000, file = null, maxFileBytes = 4 * 1024 * 1024 } = options
|
||||
this.maxLines = maxLines
|
||||
this.maxFileBytes = maxFileBytes
|
||||
this.lines = []
|
||||
this.listeners = new Set()
|
||||
// 子进程的输出是流式分片的,可能把一行拆到两次 data 事件里
|
||||
this.pending = new Map()
|
||||
this.stream = null
|
||||
if (file) this.openFile(file)
|
||||
}
|
||||
|
||||
openFile(file) {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true })
|
||||
if (fs.existsSync(file) && fs.statSync(file).size > this.maxFileBytes) {
|
||||
fs.renameSync(file, `${file}.1`)
|
||||
}
|
||||
this.stream = fs.createWriteStream(file, { flags: 'a' })
|
||||
} catch (err) {
|
||||
this.stream = null
|
||||
this.push('console', `日志文件不可写,仅保留内存日志:${err.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
append(source, chunk) {
|
||||
const text = `${this.pending.get(source) || ''}${String(chunk)}`
|
||||
const parts = text.split(/\r?\n/)
|
||||
// 最后一段是没有换行的残行,留到下一次拼接
|
||||
this.pending.set(source, parts.pop() || '')
|
||||
for (const part of parts) this.push(source, part)
|
||||
}
|
||||
|
||||
push(source, message) {
|
||||
const line = `[${new Date().toISOString()}] [${source}] ${message}`
|
||||
this.lines.push(line)
|
||||
if (this.lines.length > this.maxLines) {
|
||||
this.lines.splice(0, this.lines.length - this.maxLines)
|
||||
}
|
||||
if (this.stream) this.stream.write(`${line}\n`)
|
||||
for (const listener of this.listeners) {
|
||||
try {
|
||||
listener(line)
|
||||
} catch {
|
||||
// 单个订阅者出错不能拖垮日志链路
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tail() {
|
||||
return this.lines.slice()
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.lines = []
|
||||
}
|
||||
|
||||
onLine(listener) {
|
||||
this.listeners.add(listener)
|
||||
return () => this.listeners.delete(listener)
|
||||
}
|
||||
|
||||
close() {
|
||||
if (this.stream) {
|
||||
this.stream.end()
|
||||
this.stream = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { LogBus }
|
||||
@@ -0,0 +1,264 @@
|
||||
'use strict'
|
||||
|
||||
const fs = require('fs')
|
||||
const http = require('http')
|
||||
const path = require('path')
|
||||
const { EventEmitter } = require('events')
|
||||
const { spawn } = require('child_process')
|
||||
|
||||
const STATE_LABEL = {
|
||||
stopped: '已停止',
|
||||
starting: '启动中',
|
||||
running: '运行中',
|
||||
stopping: '停止中',
|
||||
crashed: '异常退出'
|
||||
}
|
||||
|
||||
// 服务端守护:拉起 scoreboard.exe、转发日志、健康探测、崩溃自动重启。
|
||||
// 现场无人值守,所以「崩了自动拉起」比「暴露复杂控制」更重要。
|
||||
class ServiceSupervisor extends EventEmitter {
|
||||
constructor({ values, exePath, log }) {
|
||||
super()
|
||||
this.values = values
|
||||
this.server = values.server
|
||||
this.exePath = exePath
|
||||
this.log = log
|
||||
|
||||
this.child = null
|
||||
this.state = 'stopped'
|
||||
this.healthy = false
|
||||
this.pid = null
|
||||
this.restarts = 0
|
||||
this.startedAt = null
|
||||
this.lastError = null
|
||||
|
||||
this.stopRequested = false
|
||||
this.healthTimer = null
|
||||
this.restartTimer = null
|
||||
this.forceKillTimer = null
|
||||
}
|
||||
|
||||
get status() {
|
||||
const host = this.healthHost()
|
||||
return {
|
||||
state: this.state,
|
||||
stateLabel: STATE_LABEL[this.state] || this.state,
|
||||
healthy: this.healthy,
|
||||
pid: this.pid,
|
||||
restarts: this.restarts,
|
||||
startedAt: this.startedAt,
|
||||
lastError: this.lastError,
|
||||
exePath: this.exePath,
|
||||
url: `http://${host}:${this.server.port}`,
|
||||
adminUrl: `http://${host}:${this.server.port}/admin`
|
||||
}
|
||||
}
|
||||
|
||||
// 服务端可能监听 0.0.0.0,本机探测要走回环地址
|
||||
healthHost() {
|
||||
const host = this.server.host || '127.0.0.1'
|
||||
return host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host
|
||||
}
|
||||
|
||||
emitStatus() {
|
||||
this.emit('status', this.status)
|
||||
}
|
||||
|
||||
setState(state, patch = {}) {
|
||||
const changed = this.state !== state
|
||||
this.state = state
|
||||
Object.assign(this, patch)
|
||||
if (changed) {
|
||||
this.log.push('console', `服务状态:${STATE_LABEL[state] || state}${this.lastError ? `(${this.lastError})` : ''}`)
|
||||
}
|
||||
this.emitStatus()
|
||||
}
|
||||
|
||||
start() {
|
||||
if (this.child || this.state === 'starting' || this.state === 'running') return this.status
|
||||
this.stopRequested = false
|
||||
|
||||
if (!this.exePath || !fs.existsSync(this.exePath)) {
|
||||
this.setState('crashed', {
|
||||
lastError: `未找到服务端程序:${this.exePath || this.server.exe}`
|
||||
})
|
||||
return this.status
|
||||
}
|
||||
|
||||
const args = Array.isArray(this.server.args) ? this.server.args : []
|
||||
// 工作目录取 exe 所在目录:部署包里 config.yaml / data/ 都跟 exe 平级
|
||||
const cwd = path.dirname(this.exePath)
|
||||
|
||||
this.lastError = null
|
||||
this.startedAt = new Date().toISOString()
|
||||
this.setState('starting')
|
||||
this.log.push('console', `启动服务端:${this.exePath} ${args.join(' ')}(cwd=${cwd})`)
|
||||
|
||||
let child
|
||||
try {
|
||||
child = spawn(this.exePath, args, {
|
||||
cwd,
|
||||
windowsHide: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe']
|
||||
})
|
||||
} catch (err) {
|
||||
this.setState('crashed', { lastError: `启动失败:${err.message}` })
|
||||
this.scheduleRestart()
|
||||
return this.status
|
||||
}
|
||||
|
||||
this.child = child
|
||||
this.pid = child.pid
|
||||
|
||||
if (child.stdout) {
|
||||
child.stdout.setEncoding('utf8')
|
||||
child.stdout.on('data', (chunk) => this.log.append('server', chunk))
|
||||
}
|
||||
if (child.stderr) {
|
||||
child.stderr.setEncoding('utf8')
|
||||
child.stderr.on('data', (chunk) => this.log.append('server!', chunk))
|
||||
}
|
||||
|
||||
child.on('error', (err) => {
|
||||
this.log.push('console', `服务端进程错误:${err.message}`)
|
||||
this.setState('crashed', { lastError: err.message })
|
||||
})
|
||||
|
||||
child.on('exit', (code, signal) => this.handleExit(code, signal))
|
||||
|
||||
this.setState('running')
|
||||
this.startHealthCheck()
|
||||
return this.status
|
||||
}
|
||||
|
||||
handleExit(code, signal) {
|
||||
if (this.forceKillTimer) {
|
||||
clearTimeout(this.forceKillTimer)
|
||||
this.forceKillTimer = null
|
||||
}
|
||||
this.stopHealthCheck()
|
||||
this.child = null
|
||||
this.pid = null
|
||||
this.healthy = false
|
||||
|
||||
const reason = signal ? `信号 ${signal}` : `退出码 ${code}`
|
||||
if (this.stopRequested) {
|
||||
this.log.push('console', `服务端已停止(${reason})`)
|
||||
this.setState('stopped', { lastError: null })
|
||||
return
|
||||
}
|
||||
|
||||
this.setState('crashed', { lastError: `服务端意外退出(${reason})` })
|
||||
this.scheduleRestart()
|
||||
}
|
||||
|
||||
scheduleRestart() {
|
||||
const max = Number(this.server.maxRestarts) || 0
|
||||
if (max > 0 && this.restarts >= max) {
|
||||
this.log.push('console', `已达到最大重启次数 ${max},不再自动拉起`)
|
||||
return
|
||||
}
|
||||
const delay = (Number(this.server.restartDelayMs) || 3000) * Math.min(this.restarts + 1, 5)
|
||||
this.restarts += 1
|
||||
this.log.push('console', `${Math.round(delay / 1000)} 秒后自动重启服务端(第 ${this.restarts} 次)`)
|
||||
this.emitStatus()
|
||||
if (this.restartTimer) clearTimeout(this.restartTimer)
|
||||
this.restartTimer = setTimeout(() => {
|
||||
this.restartTimer = null
|
||||
if (!this.stopRequested) this.start()
|
||||
}, delay)
|
||||
}
|
||||
|
||||
stop() {
|
||||
return new Promise((resolve) => {
|
||||
if (this.restartTimer) {
|
||||
clearTimeout(this.restartTimer)
|
||||
this.restartTimer = null
|
||||
}
|
||||
const child = this.child
|
||||
if (!child) {
|
||||
this.setState('stopped', { lastError: null })
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
|
||||
this.stopRequested = true
|
||||
this.setState('stopping')
|
||||
this.log.push('console', '正在停止服务端…')
|
||||
|
||||
child.once('exit', () => resolve())
|
||||
try {
|
||||
child.kill()
|
||||
} catch (err) {
|
||||
this.log.push('console', `发送停止信号失败:${err.message}`)
|
||||
}
|
||||
// Go 服务端有 10s 优雅关闭窗口,超过 5s 仍未退出就强杀,避免 Console 退不干净
|
||||
this.forceKillTimer = setTimeout(() => {
|
||||
if (this.child && this.pid) {
|
||||
this.log.push('console', '服务端未在 5 秒内退出,强制结束')
|
||||
try {
|
||||
this.child.kill('SIGKILL')
|
||||
} catch {
|
||||
// 进程可能已经没了
|
||||
}
|
||||
}
|
||||
}, 5000)
|
||||
})
|
||||
}
|
||||
|
||||
async restart() {
|
||||
await this.stop()
|
||||
this.restarts = 0
|
||||
return this.start()
|
||||
}
|
||||
|
||||
startHealthCheck() {
|
||||
this.stopHealthCheck()
|
||||
const interval = Number(this.server.healthIntervalMs) || 5000
|
||||
const tick = () => this.probe()
|
||||
setTimeout(tick, 800)
|
||||
this.healthTimer = setInterval(tick, interval)
|
||||
}
|
||||
|
||||
stopHealthCheck() {
|
||||
if (this.healthTimer) {
|
||||
clearInterval(this.healthTimer)
|
||||
this.healthTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
probe() {
|
||||
if (!this.child) return
|
||||
const request = http.get(
|
||||
{
|
||||
host: this.healthHost(),
|
||||
port: this.server.port,
|
||||
path: '/api/health',
|
||||
timeout: 2500
|
||||
},
|
||||
(response) => {
|
||||
response.resume()
|
||||
const ok = response.statusCode === 200
|
||||
this.setHealthy(ok)
|
||||
}
|
||||
)
|
||||
request.on('timeout', () => request.destroy())
|
||||
request.on('error', () => this.setHealthy(false))
|
||||
}
|
||||
|
||||
setHealthy(ok) {
|
||||
if (this.healthy === ok) return
|
||||
this.healthy = ok
|
||||
this.log.push('console', ok ? '服务端健康检查通过' : '服务端健康检查失败(等待重试)')
|
||||
this.emitStatus()
|
||||
}
|
||||
|
||||
dispose() {
|
||||
if (this.restartTimer) clearTimeout(this.restartTimer)
|
||||
if (this.forceKillTimer) clearTimeout(this.forceKillTimer)
|
||||
this.stopHealthCheck()
|
||||
this.removeAllListeners()
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { ServiceSupervisor, STATE_LABEL }
|
||||
@@ -0,0 +1,16 @@
|
||||
'use strict'
|
||||
|
||||
const { nativeImage } = require('electron')
|
||||
|
||||
// 托盘图标以 base64 内嵌:现场部署包只有 exe 和几个文件,
|
||||
// 少一个需要跟着走的资源文件就少一处「文件丢了图标不显示」的故障点。
|
||||
const ICON_PNG_BASE64 =
|
||||
'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABUklEQVR42u2XwUdEURTG5z9JSholJY2SklJSf0+0iKFFtIhoES0iWkSLiBaRDKNSKU2GjCRGEkkSSZsvb3GfnHPnzTm382Y1P36b9x33fKv37stkmiiYLf1AovnimatvhPjvxdMXX7AwaPnU6ScsVS2fLH4gDUXLJwrvSNO6BcaP3pCmicvHDl/RCGsWGD14QSP0Lh/Zf4aVFN8MKzC89wQrKb4ZVmBotworKb4ZVmBw5xFWUnwzrEBu+wFWUnwzrMDA1j00UqSZkxXo36xAI0WaOVmBvo07aKRIMycr0LtehkaKNHOyAj1rt9BIkWZO79uwe/UGUinSLLLmt6Br5Rp/pVhkkYlfxOzyJZwUi6zufaBz6RxOikUmuhV1LJ4hkuKeh2aqe2F7/oQdFD1zarOgmzE9qG2hGKvJgv8L6EGt84VYTWZWoGXuOFaTNX9qk/gFLmHiXP3t+GEAAAAASUVORK5CYII='
|
||||
|
||||
function createTrayIcon() {
|
||||
const image = nativeImage.createFromDataURL(`data:image/png;base64,${ICON_PNG_BASE64}`)
|
||||
// Windows 上托盘按 16px 显示,缩放交给系统会更模糊,这里直接给 16px
|
||||
return image.resize({ width: 16, height: 16 })
|
||||
}
|
||||
|
||||
module.exports = { createTrayIcon }
|
||||
Reference in new issue
Block a user