Record the existing local Harness implementation as the starting point for scoped audit corrections.
246 lines
12 KiB
JavaScript
246 lines
12 KiB
JavaScript
import fs from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import { execFileSync } from 'node:child_process';
|
|
|
|
const manifestName = 'build-manifest.json';
|
|
const packageKinds = new Set(['unsigned-local-development-portable', 'windows-local-verification']);
|
|
const cargoSignature = 'Signature: 8a477f597d28d172789f06886806bc55';
|
|
const incrementalLimit = 8 * 1024 ** 3;
|
|
const rollbackVersions = 2;
|
|
const compilerNames = /^(cargo|rustc|sccache|cc1|cc1plus|gcc|clang|cl|link|ld|ninja|msbuild)\.exe$/i;
|
|
const runtimeLibraries = new Set(['libgcc_s_seh-1.dll', 'libstdc++-6.dll', 'libwinpthread-1.dll']);
|
|
const packageRootFiles = new Set(['photocraft.exe', '启动客户端.cmd', '本地构建说明.txt', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md', ...runtimeLibraries]);
|
|
const windowsPath = value => String(value ?? '').replaceAll('/', '\\').toLowerCase();
|
|
|
|
function inUse(directory, processes) {
|
|
const prefix = windowsPath(directory) + '\\';
|
|
return processes.some(process => windowsPath(process.ExecutablePath).startsWith(prefix)
|
|
|| windowsPath(process.CommandLine).includes(prefix));
|
|
}
|
|
|
|
function unidentifiedClient(processes) {
|
|
return processes.some(process => /^photocraft\.exe$/i.test(process.Name ?? '') && !process.ExecutablePath && !process.CommandLine);
|
|
}
|
|
|
|
export function windowsProcesses() {
|
|
const script = '[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process | Select-Object Name,ExecutablePath,CommandLine | ConvertTo-Json -Compress';
|
|
const output = execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
|
|
encoding: 'utf8', windowsHide: true, timeout: 15000, maxBuffer: 16 * 1024 * 1024,
|
|
});
|
|
const rows = JSON.parse(output);
|
|
return Array.isArray(rows) ? rows : [rows];
|
|
}
|
|
|
|
function packageFile(name) {
|
|
return packageRootFiles.has(name)
|
|
|| /^agent\/(node\.exe|LICENSE-Node\.txt|package(?:-lock)?\.json|(?:src|scripts|node_modules|vendor\/pi-goal)\/.+)$/.test(name)
|
|
|| /^(?:assets|crates)\/(?:[^/]+\/)*(?:LICENSE[^/]*|OFL-[^/]+)\.txt$/.test(name);
|
|
}
|
|
|
|
async function stat(file) {
|
|
try { return await fs.lstat(file); }
|
|
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
}
|
|
|
|
async function tree(directory) {
|
|
const files = new Map();
|
|
const directories = [];
|
|
async function visit(folder) {
|
|
const info = await fs.lstat(folder);
|
|
if (!info.isDirectory() || info.isSymbolicLink()) throw Error('目录包含链接');
|
|
const entries = await fs.readdir(folder, { withFileTypes: true });
|
|
await Promise.all(entries.map(async entry => {
|
|
const full = path.join(folder, entry.name);
|
|
if (entry.isDirectory()) await visit(full);
|
|
else if (entry.isFile()) files.set(path.relative(directory, full).split(path.sep).join('/'), (await fs.lstat(full)).size);
|
|
else throw Error('目录包含链接或特殊文件');
|
|
}));
|
|
directories.push(folder);
|
|
}
|
|
await visit(directory);
|
|
return { files, directories };
|
|
}
|
|
|
|
async function readPackage(directory) {
|
|
const file = path.join(directory, manifestName);
|
|
if (!(await stat(file))?.isFile()) return;
|
|
const manifest = JSON.parse(await fs.readFile(file, 'utf8'));
|
|
const time = Date.parse(manifest.at);
|
|
if (!packageKinds.has(manifest.kind) || !Number.isFinite(time) || !Array.isArray(manifest.files)) return;
|
|
const files = new Map(manifest.files.map(file => [file.path, file.bytes]));
|
|
if (!files.has('photocraft.exe') || !files.has('agent/node.exe')) return;
|
|
if (!(await stat(path.join(directory, 'agent')))?.isDirectory()) return;
|
|
const executable = await stat(path.join(directory, 'photocraft.exe'));
|
|
const node = await stat(path.join(directory, 'agent', 'node.exe'));
|
|
const complete = executable?.isFile() && node?.isFile()
|
|
&& executable.size === files.get('photocraft.exe') && node.size === files.get('agent/node.exe');
|
|
return { directory, time, files, complete };
|
|
}
|
|
|
|
async function packageScope(latest) {
|
|
const parent = path.dirname(latest);
|
|
for (const directory of [parent, path.dirname(parent)]) {
|
|
if (path.basename(directory).toLowerCase() !== 'output') continue;
|
|
const projectFile = path.join(path.dirname(directory), 'package.json');
|
|
if (!(await stat(projectFile))?.isFile()) continue;
|
|
const project = JSON.parse(await fs.readFile(projectFile, 'utf8'));
|
|
if (project.name === 'youyidian-3d-material') return { directory, includeDatedFolders: true };
|
|
}
|
|
return { directory: parent, includeDatedFolders: false };
|
|
}
|
|
|
|
async function packageDirectories({ directory, includeDatedFolders }, latest) {
|
|
const children = async parent => (await fs.readdir(parent, { withFileTypes: true }))
|
|
.filter(entry => entry.isDirectory() && !entry.isSymbolicLink())
|
|
.map(entry => path.join(parent, entry.name));
|
|
const directories = await children(directory);
|
|
if (!includeDatedFolders) return directories;
|
|
const parent = path.dirname(latest);
|
|
const dated = directories.filter(folder => folder === parent || /(?:^|[-_])20\d{6}(?:[-_]|$)/.test(path.basename(folder)));
|
|
return directories.concat((await Promise.all(dated.map(children))).flat());
|
|
}
|
|
|
|
async function sharedRuntimeTargets(directories) {
|
|
async function resolveLink(link) {
|
|
return fs.realpath(link).catch(error => {
|
|
if (error.code !== 'ENOENT') throw error;
|
|
});
|
|
}
|
|
const sources = directories.concat(directories.map(directory => path.join(directory, 'client')));
|
|
const targets = await Promise.all(sources.map(async directory => {
|
|
const folder = await stat(directory);
|
|
if (folder?.isSymbolicLink()) return [await resolveLink(directory)];
|
|
if (!folder?.isDirectory()) return [];
|
|
|
|
const agent = path.join(directory, 'agent');
|
|
const paths = [agent, path.join(directory, 'assets'), path.join(directory, 'crates')];
|
|
if ((await stat(agent))?.isDirectory()) paths.push(path.join(agent, 'node_modules'));
|
|
return Promise.all(paths.map(async link => {
|
|
if ((await stat(link))?.isSymbolicLink()) return resolveLink(link);
|
|
}));
|
|
}));
|
|
return targets.flat().filter(Boolean).map(windowsPath);
|
|
}
|
|
|
|
|
|
async function prunePackages(latest, processes, result, dryRun, listProcesses) {
|
|
const scope = await packageScope(latest.directory);
|
|
const keep = new Set([latest.directory]);
|
|
const packages = [];
|
|
const directories = await packageDirectories(scope, latest.directory);
|
|
const shared = await sharedRuntimeTargets(directories);
|
|
for (const directory of directories) {
|
|
if (directory === latest.directory || inUse(directory, processes)
|
|
|| /^(?:rollback|daily-previous-program)$/i.test(path.basename(directory))) continue;
|
|
const candidatePath = windowsPath(directory);
|
|
if (shared.some(target => target === candidatePath || target.startsWith(candidatePath + '\\'))) continue;
|
|
try {
|
|
const candidate = await readPackage(directory);
|
|
if (candidate && candidate.time <= latest.time) packages.push(candidate);
|
|
} catch { result.skipped.push(directory); }
|
|
}
|
|
packages.sort((a, b) => b.time - a.time);
|
|
for (const item of packages.filter(item => item.complete).slice(0, rollbackVersions)) keep.add(item.directory);
|
|
for (const item of packages) {
|
|
const directory = item.directory;
|
|
if (keep.has(directory)) continue;
|
|
try {
|
|
const canonical = await fs.realpath(directory);
|
|
const relative = path.relative(scope.directory, canonical);
|
|
if (canonical !== directory || !relative || relative.startsWith('..') || path.isAbsolute(relative)) throw Error('运行包路径变动');
|
|
const actual = await tree(directory);
|
|
// Older Windows bundles copied these runtime DLLs after writing the manifest.
|
|
const matches = (name, bytes) => packageFile(name) && (item.files.has(name)
|
|
? item.files.get(name) === bytes : runtimeLibraries.has(name));
|
|
if ([...actual.files].some(([name, bytes]) => name !== manifestName && !matches(name, bytes))) {
|
|
result.skipped.push(directory);
|
|
continue;
|
|
}
|
|
if (!dryRun) {
|
|
const current = listProcesses();
|
|
if (unidentifiedClient(current) || inUse(directory, current)) {
|
|
result.skipped.push(directory);
|
|
continue;
|
|
}
|
|
// Unlink the executable first so a sharing violation preserves the whole package.
|
|
if (actual.files.has('photocraft.exe')) await fs.unlink(path.join(directory, 'photocraft.exe'));
|
|
const files = [...actual.files.keys()].filter(name => name !== 'photocraft.exe' && name !== manifestName);
|
|
for (let offset = 0; offset < files.length; offset += 64) {
|
|
await Promise.all(files.slice(offset, offset + 64).map(name => fs.unlink(path.join(directory, name))));
|
|
}
|
|
await fs.unlink(path.join(directory, manifestName));
|
|
for (const folder of actual.directories) await fs.rmdir(folder);
|
|
}
|
|
result.packages.push(directory);
|
|
result.bytes += [...actual.files.values()].reduce((total, bytes) => total + bytes, 0);
|
|
} catch { result.skipped.push(directory); }
|
|
}
|
|
}
|
|
|
|
async function pruneIncremental(binary, listProcesses, result, dryRun, limit) {
|
|
const compiling = () => listProcesses().some(process => compilerNames.test(process.Name ?? ''));
|
|
if (!binary || compiling()) return;
|
|
// A configured target directory can be a Windows junction to another drive.
|
|
binary = await fs.realpath(binary);
|
|
const profile = path.dirname(binary);
|
|
if (path.basename(binary).toLowerCase() !== 'photocraft.exe' || !['debug', 'release'].includes(path.basename(profile))) return;
|
|
let target;
|
|
for (const directory of [path.dirname(profile), path.dirname(path.dirname(profile))]) {
|
|
const tag = path.join(directory, 'CACHEDIR.TAG');
|
|
if ((await stat(tag))?.isFile() && (await fs.readFile(tag, 'utf8')).split(/\r?\n/)[0] === cargoSignature) {
|
|
target = directory;
|
|
break;
|
|
}
|
|
}
|
|
if (!target || await fs.realpath(target) !== target) return;
|
|
const directories = new Set([path.join(profile, 'incremental'), path.join(target, 'wasm32-unknown-unknown', 'debug', 'incremental')]);
|
|
const entries = [];
|
|
for (const directory of directories) {
|
|
if (!(await stat(directory))?.isDirectory() || await fs.realpath(directory) !== directory) continue;
|
|
for (const entry of await fs.readdir(directory, { withFileTypes: true })) {
|
|
if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
|
|
const candidate = path.join(directory, entry.name);
|
|
const actual = await tree(candidate);
|
|
const modified = (await fs.lstat(candidate)).mtimeMs;
|
|
entries.push({ candidate, directory, modified, bytes: [...actual.files.values()].reduce((total, bytes) => total + bytes, 0) });
|
|
}
|
|
}
|
|
let used = entries.reduce((total, entry) => total + entry.bytes, 0);
|
|
if (used > limit && !dryRun && compiling()) return;
|
|
for (const entry of entries.sort((a, b) => a.modified - b.modified)) {
|
|
if (used <= limit) break;
|
|
const canonical = await fs.realpath(entry.candidate);
|
|
if (canonical !== entry.candidate || path.dirname(canonical) !== entry.directory) continue;
|
|
if (!dryRun) await fs.rm(canonical, { recursive: true });
|
|
used -= entry.bytes;
|
|
result.incremental.push(canonical);
|
|
result.bytes += entry.bytes;
|
|
}
|
|
}
|
|
|
|
export async function maintainLocalBuilds({ destination, binary, dryRun = false, listProcesses = windowsProcesses, limit = incrementalLimit }) {
|
|
const latest = await fs.realpath(destination);
|
|
const latestPackage = await readPackage(latest);
|
|
if (!latestPackage?.complete) throw Error('最新本地包尚未就绪');
|
|
const processes = listProcesses();
|
|
const result = { packages: [], incremental: [], skipped: [], bytes: 0 };
|
|
if (unidentifiedClient(processes)) {
|
|
result.skipped.push(path.dirname(latest));
|
|
} else {
|
|
await prunePackages(latestPackage, processes, result, dryRun, listProcesses);
|
|
}
|
|
await pruneIncremental(binary && path.resolve(binary), listProcesses, result, dryRun, limit);
|
|
return result;
|
|
}
|
|
|
|
export async function maintainAfterPackaging(destination, binary) {
|
|
if (process.platform !== 'win32') return;
|
|
try {
|
|
const result = await maintainLocalBuilds({ destination, binary });
|
|
if (result.skipped.length) console.warn(`本地构建清理保留了 ${result.skipped.length} 个无法确认的目录。`);
|
|
return { packages: result.packages.length, incrementalEntries: result.incremental.length, bytes: result.bytes, skipped: result.skipped.length };
|
|
} catch (error) {
|
|
console.warn(`本地构建清理未完成:${error.message}`);
|
|
}
|
|
}
|