forked from BigBodyCobain/Shadowbroker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart-backend.js
More file actions
215 lines (190 loc) · 6.07 KB
/
Copy pathstart-backend.js
File metadata and controls
215 lines (190 loc) · 6.07 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
const { spawn, spawnSync } = require("child_process");
const path = require("path");
const fs = require("fs");
const backendDir = path.resolve(__dirname, "backend");
const isWindows = process.platform === "win32";
const configuredBasePython = String(process.env.BACKEND_BASE_PYTHON || process.env.PYTHON || "").trim();
const configuredVenvDir = String(process.env.BACKEND_VENV_DIR || "").trim();
const canonicalVenvDir = path.join(backendDir, "venv");
const venvMarkerPath = path.join(backendDir, ".venv-dir");
function venvPythonPath(dir) {
return isWindows
? path.join(dir, "Scripts", "python.exe")
: path.join(dir, "bin", "python3");
}
function readPersistedVenvDir() {
try {
const value = fs.readFileSync(venvMarkerPath, "utf8").trim();
if (!value) {
return "";
}
return path.isAbsolute(value) ? value : path.join(backendDir, value);
} catch {
return "";
}
}
function persistSelectedVenv(pythonBin) {
const envDir = path.dirname(path.dirname(pythonBin));
const relativeDir = path.relative(backendDir, envDir);
if (!relativeDir || relativeDir.startsWith("..") || path.isAbsolute(relativeDir)) {
return;
}
try {
fs.writeFileSync(venvMarkerPath, `${relativeDir}\n`, "utf8");
} catch {
// Best effort only. Startup should still succeed if the marker cannot be updated.
}
}
const explicitVenvCandidate = configuredVenvDir
? venvPythonPath(path.isAbsolute(configuredVenvDir) ? configuredVenvDir : path.join(backendDir, configuredVenvDir))
: "";
const persistedVenvDir = readPersistedVenvDir();
const persistedVenvCandidate = persistedVenvDir ? venvPythonPath(persistedVenvDir) : "";
const venvCandidates = [
explicitVenvCandidate,
persistedVenvCandidate,
...(isWindows
? [
path.join(backendDir, "venv", "Scripts", "python.exe"),
path.join(backendDir, "venv-repair", "Scripts", "python.exe"),
path.join(backendDir, ".venv", "Scripts", "python.exe"),
path.join(backendDir, ".venv-repair", "Scripts", "python.exe"),
]
: [
path.join(backendDir, "venv", "bin", "python3"),
path.join(backendDir, "venv-repair", "bin", "python3"),
path.join(backendDir, ".venv", "bin", "python3"),
path.join(backendDir, ".venv-repair", "bin", "python3"),
]),
].filter(Boolean);
const repairTargetDir = isWindows
? path.join(backendDir, "venv-repair")
: path.join(backendDir, "venv-repair");
function canRun(command, args) {
const result = spawnSync(command, args, {
cwd: backendDir,
env: process.env,
stdio: "ignore",
});
return !result.error && result.status === 0;
}
function canRunBackendPython(pythonBin) {
return (
canRun(pythonBin, ["-V"]) &&
canRun(pythonBin, ["-c", "import fastapi, uvicorn"])
);
}
function findBasePython() {
const candidates = isWindows
? [
[configuredBasePython, []],
["python", []],
["py", ["-3.11"]],
["py", ["-3"]],
]
: [
[configuredBasePython, []],
["python3", []],
["python", []],
];
for (const [command, prefixArgs] of candidates) {
if (!command) {
continue;
}
if (canRun(command, [...prefixArgs, "-V"])) {
return { command, prefixArgs };
}
}
return null;
}
function rebuildBackendVenv(targetDir, basePython) {
console.log(`[*] Preparing backend Python environment at ${targetDir}...`);
try {
fs.rmSync(targetDir, { recursive: true, force: true });
} catch (error) {
console.warn(`[*] Could not clear ${targetDir} cleanly (${error.code || error.message}). Trying a fresh repair path...`);
targetDir = `${targetDir}-${Date.now()}`;
}
let result = spawnSync(
basePython.command,
[...basePython.prefixArgs, "-m", "venv", targetDir],
{
cwd: backendDir,
env: process.env,
stdio: "inherit",
}
);
if (result.error || result.status !== 0) {
return null;
}
const repairedBin = isWindows
? path.join(targetDir, "Scripts", "python.exe")
: path.join(targetDir, "bin", "python3");
result = spawnSync(repairedBin, ["-m", "pip", "install", "-q", "."], {
cwd: backendDir,
env: process.env,
stdio: "inherit",
});
if (result.error || result.status !== 0) {
return null;
}
return canRunBackendPython(repairedBin) ? repairedBin : null;
}
function ensureBackendVenv() {
for (const candidate of venvCandidates) {
if (fs.existsSync(candidate) && canRunBackendPython(candidate)) {
persistSelectedVenv(candidate);
return candidate;
}
}
const hadExisting = venvCandidates.some((candidate) => fs.existsSync(candidate));
console.log(
hadExisting
? "[*] Backend venv exists but is stale. Rebuilding it automatically..."
: "[*] Backend venv is missing. Creating it automatically..."
);
const basePython = findBasePython();
if (!basePython) {
return null;
}
const preferredRebuildDir = persistedVenvDir || canonicalVenvDir;
const rebuilt = rebuildBackendVenv(hadExisting ? preferredRebuildDir : canonicalVenvDir, basePython);
if (rebuilt) {
persistSelectedVenv(rebuilt);
}
return rebuilt;
}
const venvBin = ensureBackendVenv();
if (!venvBin) {
console.error(`[!] Unable to prepare backend Python venv. Checked: ${venvCandidates.join(", ")}`);
console.error("[!] Install Python 3.10-3.12 and rerun start.sh/start.bat if the repair could not complete.");
process.exit(1);
}
const backendArgs = ["-m", "uvicorn", "main:app", "--timeout-keep-alive", "120"];
if (["1", "true", "yes"].includes(String(process.env.BACKEND_RELOAD || "").toLowerCase())) {
backendArgs.push("--reload");
}
console.log(`[*] Starting backend with: ${venvBin} ${backendArgs.join(" ")}`);
const backendProc = spawn(venvBin, backendArgs, {
cwd: backendDir,
stdio: "inherit",
env: process.env,
});
const cleanupAll = () => {
if (backendProc && !backendProc.killed) {
backendProc.kill();
}
};
process.on("exit", cleanupAll);
process.on("SIGINT", () => {
cleanupAll();
process.exit(0);
});
process.on("SIGTERM", () => {
cleanupAll();
process.exit(0);
});
backendProc.on("exit", (code) => {
cleanupAll();
process.exit(code ?? 0);
});