-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservices.ts
More file actions
496 lines (452 loc) · 14.3 KB
/
Copy pathservices.ts
File metadata and controls
496 lines (452 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
import type { BdsUpdaterConfig, DBConfig, QQBridgeConfig } from "@sfmc-bds/sdk/node/config";
import {
ensureCoreConfigs,
loadEnsuredConfig,
DEFAULT_BDS_UPDATER_CONFIG,
DEFAULT_DB_CONFIG,
DEFAULT_QQ_CONFIG,
} from "@sfmc-bds/sdk/node/config";
import {
clearBdsPidFile,
isProcessAlive,
probeBdsStatus,
readBdsPidFile,
writeBdsPidFile,
} from "@sfmc-bds/bds-tools/process-probe";
import { spawn, type ChildProcess, type IOType } from "node:child_process";
import { EventEmitter } from "node:events";
import fs from "node:fs";
import path from "node:path";
import { inferLevel, pushLog as pushUnifiedLog } from "./logs.js";
import { ROOT, spawnService, type ServiceId } from "./runtime.js";
import { ensurePackUpdateConfigFile } from "./pack-update/index.js";
import { t } from "./i18n/index.js";
export { ROOT } from "./runtime.js";
export interface LogLine {
time: Date;
text: string;
stream: "stdout" | "stderr";
}
export type ServiceName = "bds" | "db" | "qq" | "llbot";
export const SERVICE_NAMES: ServiceName[] = ["bds", "db", "qq", "llbot"];
export interface ServiceStatus {
name: ServiceName;
title: string;
running: boolean;
pid: number;
uptime: string;
ownership?: "managed" | "external";
}
/** 当前 db 健康探测端口(与 createServices 同步) */
let dbHealthPort = 3001;
async function probeDbHealth(port: number): Promise<boolean> {
try {
const res = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(2000) });
return res.ok;
} catch {
return false;
}
}
interface ServiceDef {
name: ServiceName;
title: string;
service?: ServiceId;
cmd?: string;
args?: string[];
cwd: string;
env?: Record<string, string>;
stopCommand?: string;
stopTimeout: number;
autoRestart: boolean;
restartDelay: number;
validate?: () => string | null;
/** 启动前钩子(如 BDS 装载一致性校验);失败则禁止 spawn */
beforeStart?: () => Promise<void>;
}
class Service {
name: ServiceName;
title: string;
proc: ChildProcess | null = null;
running = false;
pid = 0;
startTime: Date | null = null;
logs: LogLine[] = [];
events = new EventEmitter();
private def: ServiceDef;
private manualStop = false;
constructor(def: ServiceDef) {
this.name = def.name;
this.title = def.title;
this.def = def;
}
get uptime(): string {
if (!this.startTime || !this.running) return "—";
const ms = Date.now() - this.startTime.getTime();
const m = Math.floor(ms / 60000);
const h = Math.floor(m / 60);
if (h > 0) return `${h}h ${m % 60}m`;
if (m > 0) return `${m}m`;
return `${Math.floor(ms / 1000)}s`;
}
pushLog(text: string, stream: "stdout" | "stderr"): void {
const line: LogLine = { time: new Date(), text, stream };
this.logs.push(line);
if (this.logs.length > 2000) this.logs.splice(0, this.logs.length - 2000);
this.events.emit("log", line);
// stderr 视为 error; stdout 用 inferLevel 推断 (bare 子进程纯 text 时默认 info,
// BDS 等自带 [LEVEL] 标签的仍可正确推断)
const level = stream === "stderr" ? "error" : inferLevel(text);
pushUnifiedLog(text, this.name, level);
}
async start(): Promise<void> {
if (this.running) return;
if (this.name === "bds") {
const probe = await probeBdsStatus({ rootDir: ROOT });
if (probe.state !== "stopped") {
throw new Error(
t("svc.bdsAlreadyRunning", { pid: String(probe.pid), kind: t(probe.state === "managed" ? "svc.running" : "svc.runningExternal") })
);
}
}
if (this.def.validate) {
const v = this.def.validate();
if (v) throw new Error(v);
}
if (this.def.beforeStart) {
await this.def.beforeStart();
}
this.manualStop = false;
const spawnOpts = {
cwd: this.def.cwd,
stdio: ["pipe", "pipe", "pipe"] as Array<IOType>,
env: this.def.env ? { ...process.env, ...this.def.env } : process.env,
};
const child = this.def.service
? spawnService(this.def.service, this.def.args ?? [], spawnOpts)
: spawn(this.def.cmd as string, this.def.args ?? [], spawnOpts);
//child.unref();
this.proc = child;
this.pid = child.pid ?? 0;
this.running = true;
this.startTime = new Date();
if (this.name === "bds" && this.pid > 0) {
writeBdsPidFile(this.pid, ROOT);
}
this.events.emit("output", `started (PID ${this.pid})`, "info");
this.events.emit("state", { name: this.name, running: true, pid: this.pid });
child.on("error", (e) => {
this.events.emit("output", `process error: ${e.message}`, "error");
this.cleanup();
});
child.stdout?.on("data", (d: Buffer) => {
for (const line of d.toString().split("\n").filter(Boolean)) {
this.pushLog(line, "stdout");
}
});
child.stderr?.on("data", (d: Buffer) => {
for (const line of d.toString().split("\n").filter(Boolean)) {
this.pushLog(line, "stderr");
}
});
child.on("exit", (code) => {
this.events.emit("output", `exited (code: ${code})`, "info");
this.cleanup();
if (!this.manualStop && this.def.autoRestart) {
setTimeout(() => {
void this.start();
}, this.def.restartDelay);
}
});
}
async stop(): Promise<void> {
if (!this.proc || !this.running) return;
this.manualStop = true;
this.events.emit("output", "stopping...", "info");
if (this.def.stopCommand && this.proc.stdin) {
this.proc.stdin.write(this.def.stopCommand + "\n");
} else {
this.proc.kill("SIGTERM");
}
return new Promise((resolve) => {
const timeout = setTimeout(() => {
if (this.proc) {
this.events.emit("output", "force kill", "error");
try {
this.proc.kill("SIGKILL");
} catch {
/* ignore */
}
}
resolve();
}, this.def.stopTimeout);
this.proc?.on("exit", () => {
clearTimeout(timeout);
resolve();
});
});
}
forceStop(): void {
const child = this.proc;
this.manualStop = true;
this.cleanup();
if (!child) return;
try {
child.kill("SIGKILL");
} catch {
/* ignore */
}
}
async restart(): Promise<void> {
await this.stop();
await this.start();
}
getRecentLogs(n: number): LogLine[] {
return this.logs.slice(-n);
}
/**
* 探测发现进程已死后回写本地状态(不设 manualStop,以便 exit 回调仍可按需 autoRestart)。
*/
markStoppedFromProbe(): void {
if (!this.running && !this.proc) return;
this.cleanup();
}
private cleanup(): void {
const wasRunning = this.running || this.proc !== null;
const exitingPid = this.pid;
this.proc = null;
this.running = false;
this.pid = 0;
this.startTime = null;
if (this.name === "bds" && exitingPid > 0) {
const filePid = readBdsPidFile(ROOT);
if (filePid === exitingPid) {
clearBdsPidFile(ROOT);
}
}
if (wasRunning) {
this.events.emit("state", { name: this.name, running: false, pid: 0 });
}
}
}
function createServices(): Record<ServiceName, Service> {
/* 各服务/CLI 用 SDK ensureCoreConfigs 播种(含 $schema),不再从 configs-default 拷贝。 */
ensureCoreConfigs(ROOT, ["bds_updater", "qq_config", "db_config"]);
ensurePackUpdateConfigFile();
const bdsCfg = loadEnsuredConfig(
ROOT,
"bds_updater.json",
"bds_updater",
{ ...DEFAULT_BDS_UPDATER_CONFIG } as Record<string, unknown>
) as BdsUpdaterConfig;
const qqCfg = loadEnsuredConfig(
ROOT,
"qq_config.json",
"qq_config",
{ ...DEFAULT_QQ_CONFIG } as Record<string, unknown>
) as QQBridgeConfig;
const dbCfg = loadEnsuredConfig(
ROOT,
"db_config.json",
"db_config",
{ ...DEFAULT_DB_CONFIG } as Record<string, unknown>
) as DBConfig;
const bdsPath = bdsCfg.bds_path ?? ROOT;
const llbotEnabled = qqCfg.llbot_enabled !== false;
const llbotPath = qqCfg.llbot_path ?? "D:\\LLBot-CLI-win-x64\\llbot.exe";
const llbotCwd = qqCfg.llbot_cwd ?? "D:\\LLBot-CLI-win-x64";
const dbPort = dbCfg.db_port ?? 3001;
dbHealthPort = dbPort;
const bdsExe = path.resolve(bdsPath, "bedrock_server.exe");
return {
bds: new Service({
name: "bds",
title: "BDS",
cmd: bdsExe,
args: [],
cwd: bdsPath,
stopCommand: "stop",
stopTimeout: 30000,
autoRestart: bdsCfg.crash_restart !== false,
restartDelay: 5000,
validate: () => {
if (!fs.existsSync(bdsExe)) return `not found: ${bdsExe}`;
return null;
},
beforeStart: async () => {
/* 先装收件箱第三方包,再检查 CF 更新,再跑模块聚合闸门 */
const { scanAndInstallInbox } = await import("./world-packs.js");
await scanAndInstallInbox({ interactive: false });
const { runPackUpdatesOnBdsStart } = await import("./pack-update/index.js");
await runPackUpdatesOnBdsStart();
const { ensurePacksReady } = await import("./pack-lifecycle.js");
await ensurePacksReady();
},
}),
db: new Service({
name: "db",
title: "DB Server",
service: "db",
cwd: ROOT,
stopTimeout: 10000,
autoRestart: true,
restartDelay: 3000,
env: { DB_PORT: String(dbPort) },
}),
qq: new Service({
name: "qq",
title: "QQ Bridge",
service: "qq",
cwd: ROOT,
stopTimeout: 10000,
autoRestart: true,
restartDelay: 3000,
}),
llbot: new Service({
name: "llbot",
title: "LLBot",
cmd: llbotPath,
args: [],
cwd: llbotCwd,
stopTimeout: 10000,
autoRestart: false,
restartDelay: 5000,
validate: () => {
if (!llbotEnabled) return "LLBot disabled (llbot_enabled=false)";
if (!fs.existsSync(llbotPath)) return `not found: ${llbotPath}`;
return null;
},
}),
};
}
export let services: Record<ServiceName, Service> = createServices();
export function refreshServices(): void {
forceStopAll();
services = createServices();
}
export const START_ORDER: ServiceName[] = ["db", "qq", "llbot", "bds"];
export async function startAll(): Promise<void> {
for (const name of START_ORDER) {
const svc = services[name];
if (!svc) continue;
try {
await svc.start();
} catch (e) {
svc.events.emit("output", `start error: ${(e as Error).message}`, "error");
}
}
}
export async function stopAll(): Promise<void> {
const pending = [...START_ORDER]
.reverse()
.map((name) => services[name])
.filter((service): service is Service => Boolean(service?.running))
.map((service) => service.stop());
await Promise.allSettled(pending);
}
export function forceStopAll(): void {
for (const service of Object.values(services)) service.forceStop();
}
export type ServiceStateEvent = { name: ServiceName; running: boolean; pid: number };
/** 订阅任意服务启停(含探测回写);返回取消函数 */
export function onServiceStateChange(fn: (ev: ServiceStateEvent) => void): () => void {
const handler = (ev: ServiceStateEvent): void => {
fn(ev);
};
for (const service of Object.values(services)) {
service.events.on("state", handler);
}
return () => {
for (const service of Object.values(services)) {
service.events.off("state", handler);
}
};
}
/** 若本地标记 running 但 OS 进程已死,回收内存标志 */
async function reconcileManagedAlive(service: Service): Promise<boolean> {
if (!service.running) return false;
if (service.pid > 0 && !(await isProcessAlive(service.pid))) {
service.markStoppedFromProbe();
return false;
}
return service.running;
}
/**
* 统一运行态查询(权威入口):OS/健康探测 + 回写 Service 内存标志。
* status / Tab 发送目标 / remote / reload 等均应走此接口,勿直接读 `service.running`。
*/
export async function queryServicesRuntime(): Promise<ServiceStatus[]> {
return Promise.all(
SERVICE_NAMES.map(async (name) => {
const service = services[name];
let running = false;
let pid = 0;
let uptime = "—";
let ownership: "managed" | "external" | undefined;
if (name === "bds") {
const probe = await probeBdsStatus({
managedPid: service.pid,
hasStdin: Boolean(service.proc?.stdin),
rootDir: ROOT,
});
if (probe.state === "managed") {
running = true;
pid = probe.pid;
uptime = service.uptime;
ownership = "managed";
/* 探测为 managed 但本地已标停:保持探测结果,不强制改内存(stdin 仍可用) */
} else if (probe.state === "external") {
running = true;
pid = probe.pid;
ownership = "external";
/* 外部进程:本地 managed 句柄已失效则回收 */
if (service.running && service.pid !== probe.pid) {
service.markStoppedFromProbe();
} else if (service.running && !(await isProcessAlive(service.pid))) {
service.markStoppedFromProbe();
}
} else {
running = false;
if (service.running || service.proc) {
service.markStoppedFromProbe();
}
}
} else if (name === "db") {
const managed = await reconcileManagedAlive(service);
if (managed) {
running = true;
pid = service.pid;
uptime = service.uptime;
ownership = "managed";
} else if (await probeDbHealth(dbHealthPort)) {
running = true;
ownership = "external";
}
} else {
const managed = await reconcileManagedAlive(service);
if (managed) {
running = true;
pid = service.pid;
uptime = service.uptime;
ownership = "managed";
}
}
return {
name,
title: service.title,
running,
pid,
uptime,
...(ownership ? { ownership } : {}),
};
})
);
}
/** @deprecated 请用 queryServicesRuntime;保留别名以免破坏现有调用 */
export async function serviceStatus(): Promise<ServiceStatus[]> {
return queryServicesRuntime();
}
/** 单服务是否在跑(含外部实例) */
export async function isServiceRunning(name: ServiceName): Promise<boolean> {
const rows = await queryServicesRuntime();
return rows.some((r) => r.name === name && r.running);
}