Repository navigation
Expand file tree
/
Copy pathcluster.js
More file actions
129 lines (117 loc) · 4.44 KB
/
Copy pathcluster.js
File metadata and controls
129 lines (117 loc) · 4.44 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
// claude-code-hub 的资源感知型生产启动器。
//
// 每个 cluster worker 独占完整的请求生命周期。主进程只分发已接受的 socket
// 句柄,绝不传递请求正文或解析后的对象图,避免大请求跨越 IPC 序列化边界。
"use strict";
const cluster = require("node:cluster");
const path = require("node:path");
const { createClusterSupervisor } = require("./server-lib/cluster-supervisor");
const { createMemoryCoordinator } = require("./server-lib/memory-coordinator");
const { readResourceSnapshot } = require("./server-lib/resource-snapshot");
const {
createMulticorePlan,
detectRuntimeResources,
hasCrossProcessInvalidation,
} = require("./server-lib/multicore");
function log(level, msg, extra) {
const line = { ts: new Date().toISOString(), level, msg, ...(extra || {}) };
try {
process.stdout.write(`${JSON.stringify(line)}\n`);
} catch {
// 日志写入失败不应影响启动监督。
}
}
function loadLauncherEnvironment() {
try {
// worker 数必须在 Next 启动前确定。复用 Next 的 .env 加载语义,确保
// `bun run start` 与容器注入环境变量时行为一致。
const { loadEnvConfig } = require("@next/env");
loadEnvConfig(__dirname, process.env.NODE_ENV !== "production");
} catch (error) {
log("warn", "multicore_env_load_failed", {
error: String(error?.message || error),
});
}
}
function normalizeStandaloneEnvironment(env = process.env) {
// `off` 是紧急回滚入口。即使部署残留了内部 worker 标记,单进程也必须恢复
// 完整 owner 角色,不能误跳过迁移、队列 consumer 或后台调度器。
env.CCH_MULTICORE_ACTIVE = "0";
env.CCH_MULTICORE_WORKER_INDEX = "0";
env.CCH_MULTICORE_WORKER_COUNT = "1";
env.CCH_MULTICORE_BACKGROUND_OWNER = "1";
env.CCH_PROCESS_ROLE = "gateway-control";
delete env.CCH_MULTICORE_EFFECTIVE_VCPUS;
delete env.CCH_MULTICORE_EFFECTIVE_MEMORY_BYTES;
return env;
}
async function main() {
if (!cluster.isPrimary) {
throw new Error("cluster.js must only run as the primary process");
}
loadLauncherEnvironment();
const detected = detectRuntimeResources();
const resources = {
...detected,
effectiveMemoryBytes: Math.min(detected.effectiveMemoryBytes, readResourceSnapshot().availableRamBytes),
};
const plan = createMulticorePlan({ env: process.env, resources });
log("info", "multicore_plan_resolved", {
enabled: plan.enabled,
mode: plan.mode,
reason: plan.reason,
workerCount: plan.workerCount,
effectiveVcpus: resources.effectiveCpu,
cpuQuota: resources.cpuQuota,
cpusetVcpus: resources.cpusetCpu,
crossProcessInvalidation: hasCrossProcessInvalidation(process.env),
effectiveMemoryMiB: Math.floor(resources.effectiveMemoryBytes / (1024 * 1024)),
memoryPerWorkerMiB: plan.memoryPerWorkerBytes
? Math.floor(plan.memoryPerWorkerBytes / (1024 * 1024))
: null,
});
if (!plan.enabled) {
normalizeStandaloneEnvironment(process.env);
const { main: startServer } = require("./server");
await startServer();
return;
}
// 轮询调度比任由少数 keep-alive listener 获得大部分连接更均衡。Windows
// 保留原生策略;生产容器运行于 Linux,因此使用 SCHED_RR。
cluster.schedulingPolicy = process.platform === "win32" ? cluster.SCHED_NONE : cluster.SCHED_RR;
cluster.setupPrimary({
exec: path.join(__dirname, "server.js"),
execArgv: process.execArgv,
});
process.env.CCH_MEMORY_COORDINATED = "1";
const memory = createMemoryCoordinator({ log });
const readyWorkers = new Set();
cluster.on("fork", (worker) => {
memory.attach(worker);
worker.on("message", (message) => {
if (message?.type !== "cch:gateway-ready") return;
readyWorkers.add(worker.id);
if (readyWorkers.size === plan.workerCount) memory.resetBaseline();
});
worker.once("exit", () => readyWorkers.delete(worker.id));
});
const monitor = setInterval(() => memory.sample(), 1000);
monitor.unref();
log("info", "memory_plan_resolved", memory.snapshot());
createClusterSupervisor({
clusterModule: cluster,
plan,
processRef: process,
env: process.env,
log,
}).start();
}
module.exports = { loadLauncherEnvironment, main, normalizeStandaloneEnvironment };
if (require.main === module) {
main().catch((error) => {
log("error", "multicore_bootstrap_failed", {
error: String(error?.stack || error),
});
process.exit(1);
});
}