-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathbuild-backend.mjs
More file actions
637 lines (561 loc) · 18.8 KB
/
build-backend.mjs
File metadata and controls
637 lines (561 loc) · 18.8 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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import {
copyTree,
createPythonInstallEnv,
prunePythonBytecodeArtifacts,
resolveAndValidateRuntimeSource,
resolveRuntimePython,
} from './runtime-layout-utils.mjs';
import {
resolveExpectedRuntimeVersion,
validateRuntimePython,
} from './runtime-version-utils.mjs';
import {
patchLinuxRuntimeRpaths,
pruneLinuxTkinterRuntime,
} from './runtime-linux-compat-utils.mjs';
import { isWindowsArm64BundledRuntime } from './runtime-arch-utils.mjs';
import { generateRuntimeCoreLock } from './runtime-core-lock.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const projectRoot = path.resolve(__dirname, '..', '..');
const sourceDir = process.env.ASTRBOT_SOURCE_DIR
? path.resolve(process.env.ASTRBOT_SOURCE_DIR)
: null;
const outputDir = path.join(projectRoot, 'resources', 'backend');
const appDir = path.join(outputDir, 'app');
const runtimeDir = path.join(outputDir, 'python');
const manifestPath = path.join(outputDir, 'runtime-manifest.json');
const runtimeCoreLockPath = path.join(appDir, 'runtime-core-lock.json');
const launcherPath = path.join(outputDir, 'launch_backend.py');
const launcherTemplatePath = path.join(__dirname, 'templates', 'launch_backend.py');
const importScannerScriptPath = path.join(__dirname, 'tools', 'scan_imports.py');
const runtimeSource =
process.env.ASTRBOT_DESKTOP_BACKEND_RUNTIME ||
process.env.ASTRBOT_DESKTOP_CPYTHON_HOME;
const requirePipProbe = process.env.ASTRBOT_DESKTOP_REQUIRE_PIP === '1';
const requiredSourceEntries = ['astrbot', 'main.py', 'requirements.txt'];
const optionalSourceEntries = ['changelogs'];
const requireSourceDir = () => {
if (!sourceDir) {
throw new Error('Missing ASTRBOT_SOURCE_DIR for backend build.');
}
if (!fs.existsSync(path.join(sourceDir, 'main.py'))) {
throw new Error(`Invalid ASTRBOT_SOURCE_DIR: ${sourceDir}. main.py not found.`);
}
return sourceDir;
};
const prepareOutputDirs = () => {
fs.rmSync(outputDir, { recursive: true, force: true });
fs.mkdirSync(outputDir, { recursive: true });
fs.mkdirSync(appDir, { recursive: true });
};
const resolveImportScannerPythonExecutable = () => {
if (process.env.ASTRBOT_DESKTOP_IMPORT_SCANNER_PYTHON) {
return process.env.ASTRBOT_DESKTOP_IMPORT_SCANNER_PYTHON;
}
if (process.env.PYTHON) {
return process.env.PYTHON;
}
return process.platform === 'win32' ? 'python' : 'python3';
};
const IMPORT_SCANNER_TIMEOUT_MS = 30_000;
const importScannerCache = new Map();
const buildScannerCacheKey = (filePath) => {
try {
const stat = fs.statSync(filePath);
return `${filePath}:${stat.mtimeMs}:${stat.size}`;
} catch {
return '';
}
};
const invokeScannerProcess = (filePath) => {
const scannerPython = resolveImportScannerPythonExecutable();
return spawnSync(scannerPython, [importScannerScriptPath, filePath], {
encoding: 'utf8',
windowsHide: true,
timeout: IMPORT_SCANNER_TIMEOUT_MS,
});
};
const parseScannerOutput = (result) => {
if (result.error) {
return { ok: false, type: 'process', reason: result.error };
}
if (result.status !== 0) {
const details = result.stderr?.trim() || `exit code ${result.status}`;
return { ok: false, type: 'exit', reason: new Error(details) };
}
try {
const parsed = JSON.parse(result.stdout || '[]');
if (!Array.isArray(parsed)) {
throw new Error('scanner output is not an array');
}
return { ok: true, value: parsed };
} catch (error) {
return {
ok: false,
type: 'json',
reason: error instanceof Error ? error : new Error(String(error)),
};
}
};
const warnImportScannerFailure = (filePath, details) => {
console.warn(
`[build-backend] failed to scan imports for ${path.basename(filePath)}: ${details}`,
);
};
const runImportScanner = (filePath) => {
const cacheKey = buildScannerCacheKey(filePath);
if (cacheKey && importScannerCache.has(cacheKey)) {
return importScannerCache.get(cacheKey);
}
const result = invokeScannerProcess(filePath);
if (result.error) {
if (result.error.code === 'ETIMEDOUT') {
console.warn(
`[build-backend] import scanner timed out after ${IMPORT_SCANNER_TIMEOUT_MS}ms for ${path.basename(filePath)}; skipping import analysis for this file.`,
);
return [];
}
warnImportScannerFailure(filePath, result.error.message || 'unknown process error');
return [];
}
const parsedOutput = parseScannerOutput(result);
if (!parsedOutput.ok) {
if (parsedOutput.type === 'json') {
console.warn(
`[build-backend] invalid import scanner output for ${path.basename(filePath)}: ${parsedOutput.reason.message}`,
);
} else {
warnImportScannerFailure(filePath, parsedOutput.reason.message);
}
return [];
}
if (cacheKey) {
importScannerCache.set(cacheKey, parsedOutput.value);
}
return parsedOutput.value;
};
const addRootModule = (imports, relativeBareImports, name, fromRelativeBareImport = false) => {
if (typeof name !== 'string') {
return;
}
const rootModule = name.split('.')[0].trim();
if (!rootModule || rootModule === '*') {
return;
}
imports.add(rootModule);
if (fromRelativeBareImport) {
relativeBareImports.add(rootModule);
}
};
const handleImportDescriptor = (descriptor, imports, relativeBareImports) => {
if (typeof descriptor.module === 'string' && descriptor.module.trim()) {
addRootModule(imports, relativeBareImports, descriptor.module);
}
};
const handleFromDescriptor = (descriptor, imports, relativeBareImports) => {
const level = Number.isInteger(descriptor.level) ? descriptor.level : 0;
const moduleSpec = typeof descriptor.module === 'string' ? descriptor.module.trim() : '';
const names = Array.isArray(descriptor.names) ? descriptor.names : [];
if (level > 0) {
if (moduleSpec) {
addRootModule(imports, relativeBareImports, moduleSpec);
return;
}
for (const importedName of names) {
if (typeof importedName !== 'string') {
continue;
}
addRootModule(imports, relativeBareImports, importedName, true);
}
return;
}
if (moduleSpec) {
addRootModule(imports, relativeBareImports, moduleSpec);
}
};
const extractImportedRootModules = (filePath) => {
const imports = new Set();
const relativeBareImports = new Set();
for (const descriptor of runImportScanner(filePath)) {
if (!descriptor || typeof descriptor !== 'object') {
continue;
}
if (descriptor.kind === 'import') {
handleImportDescriptor(descriptor, imports, relativeBareImports);
continue;
}
if (descriptor.kind === 'from') {
handleFromDescriptor(descriptor, imports, relativeBareImports);
}
}
return { imports, relativeBareImports };
};
const buildModuleCandidate = (resolvedSourceDir, entry) => {
if (entry.isFile() && path.extname(entry.name) === '.py') {
return {
name: path.basename(entry.name, '.py'),
relativePath: entry.name,
scanPath: path.join(resolvedSourceDir, entry.name),
isPackage: false,
};
}
if (!entry.isDirectory()) {
return null;
}
const initPath = path.join(resolvedSourceDir, entry.name, '__init__.py');
if (!fs.existsSync(initPath)) {
return null;
}
return {
name: entry.name,
relativePath: entry.name,
scanPath: initPath,
isPackage: true,
};
};
const choosePreferredModule = (existingModule, candidateModule) => {
if (!existingModule) {
return {
module: candidateModule,
warning: '',
};
}
if (existingModule.isPackage && !candidateModule.isPackage) {
return {
module: candidateModule,
warning:
`[build-backend] both module file and package found for "${candidateModule.name}", ` +
`preferring ${candidateModule.relativePath}`,
};
}
if (!existingModule.isPackage && candidateModule.isPackage) {
return {
module: existingModule,
warning:
`[build-backend] both module file and package found for "${candidateModule.name}", ` +
`preferring ${existingModule.relativePath}`,
};
}
return {
module: existingModule,
warning: '',
};
};
const listAvailableRootModules = (resolvedSourceDir) => {
// The desktop bundle currently tracks root-level modules/packages under sourceDir.
// Nested package-only relative imports are not traversed as independent entries because
// top-level package directories are copied as whole trees once selected.
const modules = new Map();
const entries = fs.readdirSync(resolvedSourceDir, { withFileTypes: true });
for (const entry of entries) {
const candidateModule = buildModuleCandidate(resolvedSourceDir, entry);
if (!candidateModule) {
continue;
}
const { module, warning } = choosePreferredModule(
modules.get(candidateModule.name),
candidateModule,
);
if (warning) {
console.warn(warning);
}
modules.set(candidateModule.name, module);
}
return modules;
};
const logUnresolvedImports = (unresolvedImports, entryFile) => {
if (unresolvedImports.length === 0) {
return;
}
const decorated = unresolvedImports
.map(({ file, module }) => `${file} -> ${module}`)
.sort()
.join(', ');
console.warn(
`[build-backend] unresolved root module imports while scanning ${entryFile}: ` +
`${decorated} ` +
'(these may be stdlib/third-party imports; verify local helper modules are present when needed).',
);
};
const visitFileAndCollectImports = (currentFile) => {
if (!fs.existsSync(currentFile)) {
return null;
}
return extractImportedRootModules(currentFile);
};
const handleImportedModule = ({
importedModule,
availableModules,
relativeBareImports,
currentFile,
entryFile,
required,
queue,
unresolvedImports,
}) => {
const moduleEntry = availableModules.get(importedModule);
if (!moduleEntry) {
if (!relativeBareImports.has(importedModule)) {
unresolvedImports.push({
file: path.basename(currentFile),
module: importedModule,
});
}
return;
}
if (moduleEntry.relativePath === entryFile) {
return;
}
if (!required.has(moduleEntry.relativePath)) {
required.add(moduleEntry.relativePath);
queue.push(moduleEntry.scanPath);
}
};
const resolveRequiredRootPythonFiles = (resolvedSourceDir, entryFile = 'main.py') => {
const availableModules = listAvailableRootModules(resolvedSourceDir);
const required = new Set();
const visitedFiles = new Set();
const unresolvedImports = [];
const queue = [path.join(resolvedSourceDir, entryFile)];
while (queue.length > 0) {
const currentFile = queue.shift();
if (!currentFile || visitedFiles.has(currentFile)) {
continue;
}
visitedFiles.add(currentFile);
const importsInfo = visitFileAndCollectImports(currentFile);
if (!importsInfo) {
continue;
}
const { imports: importedModules, relativeBareImports } = importsInfo;
for (const importedModule of importedModules) {
handleImportedModule({
importedModule,
availableModules,
relativeBareImports,
currentFile,
entryFile,
required,
queue,
unresolvedImports,
});
}
}
logUnresolvedImports(unresolvedImports, entryFile);
return Array.from(required).sort();
};
const copyAppSources = (resolvedSourceDir) => {
const requiredEntries = new Set(requiredSourceEntries);
for (const relativePath of resolveRequiredRootPythonFiles(resolvedSourceDir, 'main.py')) {
requiredEntries.add(relativePath);
}
for (const relativePath of requiredEntries) {
const sourcePath = path.join(resolvedSourceDir, relativePath);
const targetPath = path.join(appDir, relativePath);
if (!fs.existsSync(sourcePath)) {
throw new Error(`Backend source path does not exist: ${sourcePath}`);
}
copyTree(sourcePath, targetPath);
}
// Changelog files are used by dashboard changelog APIs; keep build resilient for older sources.
for (const relativePath of optionalSourceEntries) {
const sourcePath = path.join(resolvedSourceDir, relativePath);
if (!fs.existsSync(sourcePath)) {
continue;
}
const targetPath = path.join(appDir, relativePath);
copyTree(sourcePath, targetPath);
}
};
const prepareRuntimeExecutable = (runtimeSourceReal) => {
copyTree(runtimeSourceReal, runtimeDir, { dereference: true });
const runtimePython = resolveRuntimePython({ runtimeRoot: runtimeDir, outputDir });
if (!runtimePython) {
throw new Error(
`Cannot find Python executable in runtime: ${runtimeDir}. Expected python under bin/ or Scripts/.`,
);
}
return runtimePython;
};
const writeLauncherScript = () => {
if (!fs.existsSync(launcherTemplatePath)) {
throw new Error(`Launcher template does not exist: ${launcherTemplatePath}`);
}
const content = fs.readFileSync(launcherTemplatePath, 'utf8');
fs.writeFileSync(launcherPath, content, 'utf8');
};
const writeRuntimeManifest = (runtimePython) => {
const manifest = {
mode: 'cpython-runtime',
python: runtimePython.relative,
entrypoint: path.basename(launcherPath),
app: path.relative(outputDir, appDir),
};
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2), 'utf8');
};
const installRuntimeDependencies = (runtimePython) => {
const requirementsPath = path.join(appDir, 'requirements.txt');
if (!fs.existsSync(requirementsPath)) {
throw new Error(`Backend requirements file does not exist: ${requirementsPath}`);
}
const runPipInstall = (pipArgs) => {
const installArgs = [
'-m',
'pip',
'--disable-pip-version-check',
'install',
'--no-compile',
...pipArgs,
];
return spawnSync(runtimePython.absolute, installArgs, {
cwd: outputDir,
stdio: 'inherit',
env: createPythonInstallEnv(),
windowsHide: true,
});
};
const isWindowsArm64 = isWindowsArm64BundledRuntime();
if (isWindowsArm64) {
// Prefer prebuilt wheels and avoid compiling cryptography from source on Windows ARM64.
// Fallback versions are configured by env var, for example:
// ASTRBOT_DESKTOP_CRYPTOGRAPHY_FALLBACK_VERSIONS="43.0.3,42.0.8,41.0.7"
const fallbackVersionsRaw = (
process.env.ASTRBOT_DESKTOP_CRYPTOGRAPHY_FALLBACK_VERSIONS || ''
).trim();
const cryptographyFallbackVersions = Array.from(
new Set(
fallbackVersionsRaw
.split(/[,\s]+/)
.map((value) => value.trim())
.filter(Boolean),
),
);
const installAttempts =
cryptographyFallbackVersions.length > 0 ? cryptographyFallbackVersions : [null];
let installSucceeded = false;
let lastFailureDetail = '';
for (const version of installAttempts) {
const pipArgs = ['--prefer-binary', '--only-binary=cryptography'];
if (version) {
const constraintsPath = path.join(
outputDir,
`constraints-win-arm64-cryptography-${version}.txt`,
);
fs.writeFileSync(constraintsPath, `cryptography==${version}\n`, 'utf8');
pipArgs.push('--constraint', constraintsPath);
console.log(
`Installing backend dependencies on Windows ARM64 with cryptography fallback ${version} (binary only).`,
);
} else {
console.log(
'Installing backend dependencies on Windows ARM64 with cryptography binary-only mode (no fallback pin).',
);
}
pipArgs.push('-r', requirementsPath);
const installResult = runPipInstall(pipArgs);
if (installResult.error) {
lastFailureDetail = installResult.error.message;
continue;
}
if (installResult.status === 0) {
installSucceeded = true;
break;
}
lastFailureDetail = `exit code ${installResult.status}`;
}
if (!installSucceeded) {
throw new Error(
`Backend runtime dependency installation failed on Windows ARM64 after cryptography binary/fallback attempts (${lastFailureDetail || 'unknown error'}). ` +
'Set ASTRBOT_DESKTOP_CRYPTOGRAPHY_FALLBACK_VERSIONS to control fallback versions.',
);
}
} else {
const installResult = runPipInstall(['-r', requirementsPath]);
if (installResult.error) {
throw new Error(
`Failed to install backend runtime dependencies: ${installResult.error.message}`,
);
}
if (installResult.status !== 0) {
throw new Error(
`Backend runtime dependency installation failed with exit code ${installResult.status}.`,
);
}
}
if (process.platform === 'win32') {
const msvcRuntimeResult = runPipInstall(['--only-binary=:all:', 'msvc-runtime']);
if (msvcRuntimeResult.error) {
throw new Error(
`Failed to install Windows MSVC runtime package: ${msvcRuntimeResult.error.message}`,
);
}
if (msvcRuntimeResult.status !== 0) {
throw new Error(
`Windows MSVC runtime installation failed with exit code ${msvcRuntimeResult.status}.`,
);
}
}
const bytecodeCleanupStats = prunePythonBytecodeArtifacts(runtimeDir);
if (
bytecodeCleanupStats.removedCacheDirs > 0 ||
bytecodeCleanupStats.removedBytecodeFiles > 0 ||
bytecodeCleanupStats.removedOrphanBytecodeFiles > 0
) {
console.log(
'[build-backend] removed Python bytecode artifacts ' +
`(${bytecodeCleanupStats.removedCacheDirs} cache dirs, ` +
`${bytecodeCleanupStats.removedBytecodeFiles} cached files, ` +
`${bytecodeCleanupStats.removedOrphanBytecodeFiles} orphan files).`,
);
}
};
const main = () => {
const resolvedSourceDir = requireSourceDir();
const runtimeSourceReal = resolveAndValidateRuntimeSource({
projectRoot,
outputDir,
runtimeSource,
});
const expectedRuntimeConstraint = resolveExpectedRuntimeVersion({
sourceDir: resolvedSourceDir,
});
const sourceRuntimePython = resolveRuntimePython({
runtimeRoot: runtimeSourceReal,
outputDir,
});
if (!sourceRuntimePython) {
throw new Error(
`Cannot find Python executable in runtime source: ${runtimeSourceReal}. Expected python under bin/ or Scripts/.`,
);
}
validateRuntimePython({
pythonExecutable: sourceRuntimePython.absolute,
expectedRuntimeConstraint,
requirePipProbe,
});
prepareOutputDirs();
copyAppSources(resolvedSourceDir);
const runtimePython = prepareRuntimeExecutable(runtimeSourceReal);
installRuntimeDependencies(runtimePython);
generateRuntimeCoreLock({
runtimePython,
outputPath: runtimeCoreLockPath,
});
pruneLinuxTkinterRuntime(runtimeDir);
patchLinuxRuntimeRpaths(runtimeDir);
writeLauncherScript();
writeRuntimeManifest(runtimePython);
console.log(`Prepared CPython backend runtime in ${outputDir}`);
console.log(`Runtime source: ${runtimeSourceReal}`);
console.log(`Python executable: ${runtimePython.relative}`);
};
try {
main();
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
process.exit(1);
}