From 0841e4e13434bd56b079cd317f419aef85baa1cf Mon Sep 17 00:00:00 2001 From: whyour Date: Sat, 21 Nov 2026 13:33:39 +0800 Subject: [PATCH] fix: handle cold dev startup and versioned dependency removal --- back/app.ts | 12 +- back/config/util.ts | 31 ++++- back/services/dependence.ts | 4 +- test/back/armv6-worker-readiness.test.cjs | 15 ++- test/back/linux-dependency-uninstall.test.cjs | 117 ++++++++++++++++++ test/back/node-dependency-uninstall.test.cjs | 49 ++++++++ 6 files changed, 211 insertions(+), 17 deletions(-) create mode 100644 test/back/linux-dependency-uninstall.test.cjs create mode 100644 test/back/node-dependency-uninstall.test.cjs diff --git a/back/app.ts b/back/app.ts index 5fae88bc..4bb33e50 100644 --- a/back/app.ts +++ b/back/app.ts @@ -42,11 +42,15 @@ class Application { } private startMasterProcess() { + // Source transpilation competes with the frontend's cold compilation in + // development. Keep a bounded wait without applying that budget to normal + // production startup. const readyTimeout = - process.arch === 'arm' && - Number( - (process.config.variables as { arm_version?: string | number }).arm_version, - ) === 6 + process.env.NODE_ENV === 'development' || + (process.arch === 'arm' && + Number( + (process.config.variables as { arm_version?: string | number }).arm_version, + ) === 6) ? 120000 : 30000; // Fork gRPC worker first and wait for it to be ready diff --git a/back/config/util.ts b/back/config/util.ts index cb8f7608..97f14733 100644 --- a/back/config/util.ts +++ b/back/config/util.ts @@ -861,7 +861,22 @@ export function getInstallCommand(type: DependenceTypes, name: string): string { export function getUninstallCommand( type: DependenceTypes, name: string, + linuxOsType?: 'Debian' | 'Ubuntu' | 'Alpine', ): string { + if (type === DependenceTypes.nodejs) { + // pnpm remove expects the installed name, not an install specifier. Start + // after the first character so a scoped name keeps its leading '@'. + const specifier = name.trim(); + const versionIndex = specifier.indexOf('@', 1); + const packageName = + versionIndex === -1 ? specifier : specifier.slice(0, versionIndex); + // Keep ordinary names identical to the process argv used by cancel's PID + // lookup, while passing unusual input literally to the shell. + const argument = /^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/i.test(packageName) + ? packageName + : shellQuote(packageName); + return `pnpm remove -g -- ${argument}`; + } if (type === DependenceTypes.python3) { name = name.trim(); if (isRequirementsFile(name)) { @@ -899,12 +914,16 @@ export function getUninstallCommand( PYTHON_VENV_DIR ? '' : ' --root-user-action=ignore' } -y -- ${shellQuote(packageName)}`; } - const baseCommands = { - [DependenceTypes.nodejs]: 'pnpm remove -g', - [DependenceTypes.linux]: - getOsTypeSync() === 'Alpine' ? 'apk del' : maybeSudo('apt-get remove -y'), - }; - return `${baseCommands[type]} ${name.trim()}`; + if ((linuxOsType || getOsTypeSync()) === 'Alpine') { + // apk del accepts package names, not the version constraints or repository + // tags accepted by apk add. Keep apt's version/architecture selectors intact. + const packageName = name.trim().split(/[<>=~@]/, 1)[0].trim(); + const argument = /^[a-z0-9][a-z0-9+_.-]*$/i.test(packageName) + ? packageName + : shellQuote(packageName); + return `apk del -- ${argument}`; + } + return `${maybeSudo('apt-get remove -y')} ${name.trim()}`; } export function isDemoEnv() { diff --git a/back/services/dependence.ts b/back/services/dependence.ts index 30eb0002..9b30407b 100644 --- a/back/services/dependence.ts +++ b/back/services/dependence.ts @@ -315,7 +315,7 @@ export default class DependenceService { } const linuxCommand = LINUX_DEPENDENCE_COMMAND[osType]; depInstallCommand = `${linuxCommand.install} ${doc.name.trim()}`; - depUnInstallCommand = `${linuxCommand.uninstall} ${doc.name.trim()}`; + depUnInstallCommand = getUninstallCommand(doc.type, doc.name, osType); } const pids = await Promise.all([ getPid(depInstallCommand), @@ -442,7 +442,7 @@ export default class DependenceService { if (isLinuxDependence) { command = isInstall ? `${linuxCommand.install} ${depName.trim()}` - : `${linuxCommand.uninstall} ${depName.trim()}`; + : getUninstallCommand(dependency.type, depName, osType); } const startTime = dayjs(); diff --git a/test/back/armv6-worker-readiness.test.cjs b/test/back/armv6-worker-readiness.test.cjs index c9b2a7bd..bec541fb 100644 --- a/test/back/armv6-worker-readiness.test.cjs +++ b/test/back/armv6-worker-readiness.test.cjs @@ -28,14 +28,18 @@ const compiled = ts.transpileModule( }, ).outputText; -for (const [arch, armVersion, timeout] of [ - ['arm', 6, 120000], - ['arm', 7, 30000], - ['arm64', undefined, 30000], +for (const [arch, armVersion, mode, timeout] of [ + ['arm', 6, 'production', 120000], + ['arm', 7, 'production', 30000], + ['arm64', undefined, 'production', 30000], + ['x64', undefined, 'production', 30000], + ['x64', undefined, undefined, 30000], + ['x64', undefined, 'development', 120000], + ['arm64', undefined, 'development', 120000], ]) { test(`${arch} v${ armVersion ?? '' - } waits for scheduler readiness before HTTP and job recovery`, async () => { + } ${mode ?? 'default'} waits for scheduler readiness before HTTP and job recovery`, async () => { const cluster = new EventEmitter(); const module = { exports: {} }; const logger = { info() {}, warn() {}, error() {} }; @@ -48,6 +52,7 @@ for (const [arch, armVersion, timeout] of [ compiled, )(module, cluster, logger, String, { arch, + env: { NODE_ENV: mode }, config: { variables: { arm_version: armVersion } }, exit() { assert.fail('unexpected application exit'); diff --git a/test/back/linux-dependency-uninstall.test.cjs b/test/back/linux-dependency-uninstall.test.cjs new file mode 100644 index 00000000..95e42391 --- /dev/null +++ b/test/back/linux-dependency-uninstall.test.cjs @@ -0,0 +1,117 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { EventEmitter } = require('node:events'); +const load = require('../helpers/load-security-module.cjs'); + +const types = { nodejs: 0, python3: 1, linux: 2 }; +const util = load('back/config/util.ts', { + './index': {}, + './const': {}, + '../loaders/logger': {}, + '../shared/utils': {}, + '../data/dependence': { DependenceTypes: types }, +}); + +for (const specifier of [ + 'tree', ' tree=2.3.2-r0 ', 'tree>=2.3', 'tree<=2.3', 'tree~2.3', + 'tree>2', 'tree<3', 'tree@testing', 'tree@testing=2.3.2-r0', +]) { + test(`apk uninstall removes the constraint from ${specifier}`, () => { + assert.equal(util.getUninstallCommand(2, specifier, 'Alpine'), 'apk del -- tree'); + }); +} + +for (const osType of ['Debian', 'Ubuntu']) { + for (const specifier of ['tree', 'tree=2.1.0-1', 'tree:amd64=1:2.1.0-1+b1', 'tree/stable']) { + test(`${osType} uninstall preserves ${specifier}, including sudo selection`, (t) => { + const original = process.env.QL_CONTAINER; + t.after(() => { + if (original === undefined) delete process.env.QL_CONTAINER; + else process.env.QL_CONTAINER = original; + }); + for (const container of ['false', 'true']) { + process.env.QL_CONTAINER = container; + assert.equal(util.getUninstallCommand(2, specifier, osType), + `${container === 'true' ? 'sudo ' : ''}apt-get remove -y ${specifier}`); + } + }); + } +} + +test('standalone Linux uninstall uses the detected OS when no override is supplied', (t) => { + const original = process.env.QL_OS_TYPE; + t.after(() => { + if (original === undefined) delete process.env.QL_OS_TYPE; + else process.env.QL_OS_TYPE = original; + }); + process.env.QL_OS_TYPE = 'Alpine'; + assert.equal(util.getUninstallCommand(2, 'tree=2.3.2-r0'), 'apk del -- tree'); +}); + +for (const osType of ['Alpine', 'Debian', 'Ubuntu']) { + for (const specifier of ['tree', 'tree=2.3.2-r0']) { + test(`${osType} service installs, uninstalls and cancels ${specifier} consistently`, async (t) => { + const original = process.env.QL_CONTAINER; + process.env.QL_CONTAINER = 'false'; + t.after(() => { + if (original === undefined) delete process.env.QL_CONTAINER; + else process.env.QL_CONTAINER = original; + }); + const install = `${osType === 'Alpine' ? 'apk add --no-check-certificate' : 'apt-get install -y'} ${specifier}`; + const uninstall = osType === 'Alpine' ? 'apk del -- tree' : `apt-get remove -y ${specifier}`; + const spawned = [], lookedUp = [], killed = [], removed = []; + const dep = { id: 1, name: specifier, type: 2, status: 1, log: [] }; + const Service = load('back/services/dependence.ts', { + '../config': {}, + '../config/util': { + ...util, + detectOS: async () => osType, + fileExist: async () => false, + getPid: async (command) => { + lookedUp.push(command); + return command === uninstall ? 77 : undefined; + }, + killTask: async (pid) => killed.push(pid), + }, + '../data/dependence': { + Dependence: class {}, + DependenceTypes: types, + DependenceStatus: { installed: 1, installing: 0, removing: 3, removed: 4, removeFailed: 5, cancelled: 7 }, + versionDependenceCommandTypes: { 0: '@', 1: '==', 2: '=' }, + DependenceModel: { + findAll: async () => [dep], + update: async (values) => Object.assign(dep, values), + destroy: async ({ where }) => removed.push(...where.id), + }, + }, + '../shared/pLimit': { + firstDependencyId: 1, + runDependeny: (_dep, fn) => fn(), + removeQueuedDependency() {}, + updateDepLog: (fn) => fn(), + }, + 'cross-spawn': { + spawn: (command) => { + spawned.push(command.trim()); + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + setImmediate(() => child.emit('exit', 0)); + return child; + }, + }, + './sock': class {}, + '../shared/i18n': { t: (text) => text, tf: (text) => text }, + }).default; + const service = new Service({}, { sendMessage() {} }); + await service.cancel([1]); + assert.deepEqual(lookedUp, [install, uninstall]); + assert.deepEqual(killed, [77]); + await service.installOrUninstallDependency(dep, true, true); + assert.equal(dep.status, 1); + await service.installOrUninstallDependency(dep, false); + assert.deepEqual(spawned, [install, uninstall]); + assert.deepEqual(removed, [1]); + }); + } +} diff --git a/test/back/node-dependency-uninstall.test.cjs b/test/back/node-dependency-uninstall.test.cjs new file mode 100644 index 00000000..4408aa63 --- /dev/null +++ b/test/back/node-dependency-uninstall.test.cjs @@ -0,0 +1,49 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { execFileSync, spawn } = require('node:child_process'); +const load = require('../helpers/load-security-module.cjs'); + +const api = load('back/config/util.ts', { + './index': {}, + './const': {}, + '../loaders/logger': {}, + '../shared/utils': {}, + '../data/dependence': { + DependenceTypes: { nodejs: 0, python3: 1, linux: 2 }, + }, +}); + +for (const [specifier, installedName] of [ + ['is-number@7.0.0', 'is-number'], + [' is-number@^7.0.0 ', 'is-number'], + ['is-number@latest', 'is-number'], + ['is-number', 'is-number'], + ['@scope/name@1.2.3-beta.1', '@scope/name'], + ['@scope/name@next', '@scope/name'], + ['@scope/name', '@scope/name'], + ['alias@npm:is-number@7.0.0', 'alias'], + ["literal'$(printf INJECTED)", "literal'$(printf INJECTED)"], +]) { + test(`Node uninstall passes the installed name literally: ${specifier}`, () => { + const command = api.getUninstallCommand(0, specifier); + const args = execFileSync('/bin/sh', [ + '-c', + 'pnpm() { printf "%s\\0" "$@"; }; ' + command, + ]).toString().split('\0').slice(0, -1); + assert.deepEqual(args, ['remove', '-g', '--', installedName]); + }); +} + +test('cancel can locate an uninstall process after shell argument parsing', async (t) => { + const name = `@ql-uninstall-fixture/worker-${process.pid}`; + const command = api.getUninstallCommand(0, `${name}@1.0.0`); + const worker = spawn(process.execPath, [ + '-e', 'setInterval(() => {}, 1000)', 'pnpm', 'remove', '-g', '--', name, + ], { stdio: 'ignore' }); + t.after(() => worker.kill()); + await new Promise((resolve, reject) => { + worker.once('spawn', resolve); + worker.once('error', reject); + }); + assert.equal(await api.getPid(command), worker.pid); +});