feat(core): add staged self-updates and unify application version
This commit is contained in:
1 parent
c54aeffc77
commit
5032cbb8c0
45 files changed
+1860
-165
No files matched your search
@@ -0,0 +1,37 @@
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import type { ReleaseManifest } from '../../src/update/files';
|
||||
|
||||
export async function releaseFixture(
|
||||
root: string,
|
||||
version: string,
|
||||
target = 'win32-x64',
|
||||
chunk = 'chunk.mjs',
|
||||
): Promise<ReleaseManifest> {
|
||||
const entries = [
|
||||
'index.mjs',
|
||||
'app.mjs',
|
||||
chunk,
|
||||
'native',
|
||||
'client',
|
||||
'package.json',
|
||||
'release.json',
|
||||
'EULA.md',
|
||||
'PRIVACY.md',
|
||||
'check-node-version.cjs',
|
||||
target.startsWith('win32') ? 'launcher.bat' : 'launcher.sh',
|
||||
];
|
||||
const manifest = { version, target, entries };
|
||||
await mkdir(path.join(root, 'native'), { recursive: true });
|
||||
await mkdir(path.join(root, 'client'), { recursive: true });
|
||||
|
||||
for (const file of entries.filter((entry) => !['native', 'client'].includes(entry))) {
|
||||
await writeFile(path.join(root, file), version);
|
||||
}
|
||||
|
||||
await writeFile(path.join(root, 'native', 'binding.node'), version);
|
||||
await writeFile(path.join(root, 'client', 'index.html'), version);
|
||||
await writeFile(path.join(root, 'package.json'), JSON.stringify({ version }));
|
||||
await writeFile(path.join(root, 'release.json'), JSON.stringify(manifest));
|
||||
return manifest;
|
||||
}
|
||||
@@ -7,6 +7,25 @@ function fakeCtx(signal: AbortSignal): Parameters<typeof sseResponse>[0] {
|
||||
}
|
||||
|
||||
describe('sseResponse', () => {
|
||||
it('finishes active streams and releases subscriptions during server shutdown', async () => {
|
||||
const request = new AbortController();
|
||||
const shutdown = new AbortController();
|
||||
let cleanups = 0;
|
||||
const response = sseResponse(
|
||||
fakeCtx(request.signal),
|
||||
(channel) => {
|
||||
channel.onClose(() => {
|
||||
cleanups++;
|
||||
});
|
||||
},
|
||||
shutdown.signal,
|
||||
);
|
||||
const reader = response.body!.getReader();
|
||||
shutdown.abort();
|
||||
expect(await reader.read()).toEqual({ done: true, value: undefined });
|
||||
request.abort();
|
||||
expect(cleanups).toBe(1);
|
||||
});
|
||||
it('returns an event-stream Response with the SSE headers', () => {
|
||||
const ac = new AbortController();
|
||||
const res = sseResponse(fakeCtx(ac.signal), () => {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { access, mkdtemp, rm } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { updateDirectory } from '../src/update/files';
|
||||
|
||||
vi.mock('node:fs/promises', async (original) => {
|
||||
const actual = await original<typeof import('node:fs/promises')>();
|
||||
return { ...actual, access: vi.fn(actual.access) };
|
||||
});
|
||||
|
||||
let root: string;
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-directory-test-'));
|
||||
});
|
||||
afterEach(async () => {
|
||||
vi.mocked(access).mockReset();
|
||||
const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
|
||||
vi.mocked(access).mockImplementation(actual.access);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('update staging directory', () => {
|
||||
it('isolates installations and reuses their staging directory', async () => {
|
||||
const directory = await updateDirectory(path.join(root, 'app'), root);
|
||||
expect(path.dirname(directory)).toBe(root);
|
||||
expect(await updateDirectory(path.join(root, 'app'), root)).toBe(directory);
|
||||
expect(await updateDirectory(path.join(root, 'other'), root)).not.toBe(directory);
|
||||
});
|
||||
|
||||
it('uses local tmp when system tmp is not writable and keeps it discoverable', async () => {
|
||||
vi.mocked(access).mockRejectedValueOnce(
|
||||
Object.assign(new Error('denied'), { code: 'EACCES' }),
|
||||
);
|
||||
const directory = await updateDirectory(root, root);
|
||||
expect(directory).toBe(path.join(root, 'tmp', 'update'));
|
||||
expect(await updateDirectory(root, root)).toBe(directory);
|
||||
});
|
||||
|
||||
it('surfaces unexpected filesystem failures', async () => {
|
||||
vi.mocked(access).mockRejectedValueOnce(
|
||||
Object.assign(new Error('I/O failure'), { code: 'EIO' }),
|
||||
);
|
||||
await expect(updateDirectory(root, root)).rejects.toThrow('I/O failure');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtemp, readFile, readdir, rm } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { zipSync } from 'fflate';
|
||||
import { c as createTar } from 'tar';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { archivePath, assetName, downloadUpdate } from '../src/update/download';
|
||||
import { readManifest } from '../src/update/files';
|
||||
import { releaseFixture } from './helpers/update-fixture';
|
||||
|
||||
let root: string;
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-download-test-'));
|
||||
});
|
||||
afterEach(async () => {
|
||||
vi.unstubAllGlobals();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function mockRelease(bytes: Uint8Array, target: string, digest?: string) {
|
||||
const name = assetName('2.0.0', target);
|
||||
const url = `https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}`;
|
||||
const fetchMock = vi.fn(async (input: string | URL | Request) => {
|
||||
if (String(input).startsWith('https://api.github.com/')) {
|
||||
return Response.json({
|
||||
assets: [
|
||||
{
|
||||
name,
|
||||
size: bytes.length,
|
||||
digest:
|
||||
digest ?? `sha256:${createHash('sha256').update(bytes).digest('hex')}`,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
expect(input).toBe(url);
|
||||
return new Response(new Uint8Array(bytes));
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
return fetchMock;
|
||||
}
|
||||
|
||||
describe('release downloads', () => {
|
||||
it.each(['win32-x64', 'linux-x64', 'linux-arm64'])(
|
||||
'downloads and validates the %s lite package',
|
||||
async (target) => {
|
||||
const source = path.join(root, 'source');
|
||||
await releaseFixture(source, '2.0.0', target);
|
||||
let bytes: Uint8Array;
|
||||
|
||||
if (target === 'win32-x64') {
|
||||
const files: Record<string, Uint8Array> = {};
|
||||
|
||||
const scan = async (directory: string) => {
|
||||
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||
const file = path.join(directory, entry.name);
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
await scan(file);
|
||||
} else {
|
||||
files[path.relative(source, file).replaceAll('\\', '/')] =
|
||||
await readFile(file);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await scan(source);
|
||||
bytes = zipSync(files);
|
||||
} else {
|
||||
const archive = path.join(root, 'fixture.tar.gz');
|
||||
await createTar({ file: archive, cwd: source, gzip: true }, ['.']);
|
||||
bytes = await readFile(archive);
|
||||
}
|
||||
|
||||
mockRelease(bytes, target);
|
||||
await downloadUpdate(root, '2.0.0', target);
|
||||
expect((await readManifest(path.join(root, 'payload'))).target).toBe(target);
|
||||
expect(await readFile(path.join(root, 'payload/client/index.html'), 'utf8')).toBe(
|
||||
'2.0.0',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects a digest mismatch before extracting', async () => {
|
||||
mockRelease(
|
||||
new TextEncoder().encode('bad archive'),
|
||||
'win32-x64',
|
||||
`sha256:${'0'.repeat(64)}`,
|
||||
);
|
||||
await expect(downloadUpdate(root, '2.0.0', 'win32-x64')).rejects.toThrow('校验失败');
|
||||
expect(await readdir(root)).toEqual(['archive']);
|
||||
});
|
||||
|
||||
it('rejects path traversal in a zip before writing payload files', async () => {
|
||||
mockRelease(zipSync({ '../outside': new Uint8Array([1]) }), 'win32-x64');
|
||||
await expect(downloadUpdate(root, '2.0.0', 'win32-x64')).rejects.toThrow('路径无效');
|
||||
expect(await readdir(path.join(root, 'payload'))).toEqual([]);
|
||||
});
|
||||
|
||||
it('reports HTTP failures', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => new Response('rate limited', { status: 403 })),
|
||||
);
|
||||
await expect(downloadUpdate(root, '2.0.0', 'win32-x64')).rejects.toThrow('GitHub 403');
|
||||
});
|
||||
|
||||
it.each([
|
||||
'../data',
|
||||
'/app.mjs',
|
||||
'native/../../data',
|
||||
'native/../data',
|
||||
'native/C:evil',
|
||||
'native\\..\\data',
|
||||
'config/runtime.json',
|
||||
])('rejects unsafe archive path %s', (name) => {
|
||||
expect(() => archivePath(name)).toThrow('路径无效');
|
||||
});
|
||||
|
||||
it('accepts the root-relative layout used by Linux release archives', () => {
|
||||
expect(archivePath('./')).toBe('');
|
||||
expect(archivePath('./native/binding.node')).toBe('native/binding.node');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['1.0.0', 'win32-x64'],
|
||||
['2.0.0', 'linux-x64'],
|
||||
])('rejects a package for version %s and target %s', async (version, target) => {
|
||||
const manifest = await releaseFixture(path.join(root, 'source'), version, target);
|
||||
const bytes = zipSync({
|
||||
'release.json': new TextEncoder().encode(JSON.stringify(manifest)),
|
||||
});
|
||||
mockRelease(bytes, 'win32-x64');
|
||||
await expect(downloadUpdate(root, '2.0.0', 'win32-x64')).rejects.toThrow(
|
||||
'版本或平台不匹配',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { builtinModules } from 'node:module';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { build, loadConfigFromFile } from 'vite';
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { exists, updateDirectory } from '../src/update/files';
|
||||
import { releaseFixture } from './helpers/update-fixture';
|
||||
|
||||
let compiled: string;
|
||||
let root: string;
|
||||
let staging: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
compiled = await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-build-'));
|
||||
const loaded = await loadConfigFromFile(
|
||||
{ command: 'build', mode: 'production' },
|
||||
fileURLToPath(new URL('../vite.config.ts', import.meta.url)),
|
||||
);
|
||||
|
||||
if (!loaded) {
|
||||
throw new Error('missing core build config');
|
||||
}
|
||||
|
||||
const config = loaded.config;
|
||||
const startup = fileURLToPath(new URL('../src/update/startup.ts', import.meta.url)).replaceAll(
|
||||
'\\',
|
||||
'/',
|
||||
);
|
||||
const files = fileURLToPath(new URL('../src/update/files.ts', import.meta.url)).replaceAll(
|
||||
'\\',
|
||||
'/',
|
||||
);
|
||||
const fixture = path.join(compiled, 'fixture.ts').replaceAll('\\', '/');
|
||||
await writeFile(fixture, '');
|
||||
|
||||
for (const version of ['1.0.0', '2.0.0']) {
|
||||
let loadedFixture = false;
|
||||
await build({
|
||||
...config,
|
||||
configFile: false,
|
||||
logLevel: 'silent',
|
||||
plugins: [
|
||||
{
|
||||
name: 'fixture-application',
|
||||
enforce: 'pre',
|
||||
load(id) {
|
||||
if (id.replaceAll('\\', '/') !== fixture) {
|
||||
return null;
|
||||
}
|
||||
|
||||
loadedFixture = true;
|
||||
return `
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { RESTART_EXIT_CODE, runApplication } from '${startup}';
|
||||
import { updateDirectory } from '${files}';
|
||||
const root = path.dirname(fileURLToPath(import.meta.url));
|
||||
if (!process.env.SNOWLUMA_UPDATE_ROOT) {
|
||||
await runApplication(root);
|
||||
} else {
|
||||
const version = '${version}';
|
||||
if (process.env.UPDATE_TEST_MODE === 'restart' && version === '1.0.0') {
|
||||
const staging = await updateDirectory(root);
|
||||
fs.cpSync(path.join(root, 'candidate'), path.join(staging, 'pending'), {recursive:true});
|
||||
fs.writeFileSync(path.join(root, 'old-pid'), String(process.pid));
|
||||
process.exit(RESTART_EXIT_CODE);
|
||||
}
|
||||
if (process.env.UPDATE_TEST_MODE === 'fail') {
|
||||
console.error('startup failed');
|
||||
process.exit(1);
|
||||
}
|
||||
let oldAlive = false;
|
||||
if (process.platform === 'win32' && fs.existsSync(path.join(root, 'old-pid'))) {
|
||||
try { process.kill(Number(fs.readFileSync(path.join(root, 'old-pid'), 'utf8')), 0); oldAlive = true; }
|
||||
catch (error) { if (error.code !== 'ESRCH') throw error; }
|
||||
}
|
||||
console.log(JSON.stringify({version, node:process.execPath, cwd:process.cwd(), args:process.argv.slice(2), oldAlive}));
|
||||
process.exit(0);
|
||||
}
|
||||
`;
|
||||
},
|
||||
generateBundle(_options, bundle) {
|
||||
expect(loadedFixture).toBe(true);
|
||||
const entry = bundle['index.mjs'];
|
||||
expect(entry.type).toBe('chunk');
|
||||
|
||||
if (entry.type !== 'chunk') {
|
||||
throw new Error('missing entry');
|
||||
}
|
||||
|
||||
expect(
|
||||
entry.imports.filter(
|
||||
(id) => !builtinModules.includes(id) && !id.startsWith('node:'),
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(entry.dynamicImports).toEqual([]);
|
||||
},
|
||||
},
|
||||
],
|
||||
build: {
|
||||
...config.build,
|
||||
outDir: path.join(compiled, version),
|
||||
lib: { entry: { index: fixture }, formats: ['es'], fileName: () => 'index.mjs' },
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await rm(compiled, { recursive: true, force: true });
|
||||
});
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-test-'));
|
||||
staging = await updateDirectory(root);
|
||||
await releaseFixture(root, '1.0.0');
|
||||
await cp(path.join(compiled, '1.0.0/index.mjs'), path.join(root, 'index.mjs'));
|
||||
});
|
||||
afterEach(async () => {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
await rm(staging, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function run(mode = '', args: string[] = []) {
|
||||
return new Promise<{ code: number | null; output: string }>((resolve, reject) => {
|
||||
const child = spawn(process.execPath, [path.join(root, 'index.mjs'), ...args], {
|
||||
cwd: os.tmpdir(),
|
||||
stdio: 'pipe',
|
||||
windowsHide: true,
|
||||
env: { ...process.env, UPDATE_TEST_MODE: mode },
|
||||
});
|
||||
let output = '';
|
||||
child.stdout.on('data', (data: Buffer) => {
|
||||
output += data.toString();
|
||||
});
|
||||
child.stderr.on('data', (data: Buffer) => {
|
||||
output += data.toString();
|
||||
});
|
||||
child.once('error', reject);
|
||||
child.once('close', (code) => {
|
||||
resolve({ code, output });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function candidate(directory: string) {
|
||||
await releaseFixture(path.join(directory, 'payload'), '2.0.0');
|
||||
await cp(path.join(compiled, '2.0.0/index.mjs'), path.join(directory, 'payload/index.mjs'));
|
||||
}
|
||||
|
||||
describe('packaged startup', () => {
|
||||
it('preserves the exact Node executable, arguments and working directory', async () => {
|
||||
const result = await run('', ['value with spaces']);
|
||||
expect(result.code, result.output).toBe(0);
|
||||
expect(JSON.parse(result.output)).toEqual({
|
||||
version: '1.0.0',
|
||||
node: process.execPath,
|
||||
cwd: os.tmpdir(),
|
||||
args: ['value with spaces'],
|
||||
oldAlive: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('waits for the old process to exit, applies the release, then executes the new code', async () => {
|
||||
await candidate(path.join(root, 'candidate'));
|
||||
const result = await run('restart', ['kept']);
|
||||
expect(result.code, result.output).toBe(0);
|
||||
expect(result.output).toContain('已更新至 v2.0.0');
|
||||
expect(JSON.parse(result.output.trim().split('\n').at(-1)!)).toMatchObject({
|
||||
version: '2.0.0',
|
||||
args: ['kept'],
|
||||
oldAlive: false,
|
||||
});
|
||||
expect(JSON.parse(await readFile(path.join(root, 'release.json'), 'utf8')).version).toBe(
|
||||
'2.0.0',
|
||||
);
|
||||
expect(await exists(staging)).toBe(false);
|
||||
});
|
||||
|
||||
it('applies an already staged update on ordinary startup', async () => {
|
||||
await candidate(path.join(staging, 'pending'));
|
||||
const result = await run();
|
||||
expect(result.code, result.output).toBe(0);
|
||||
expect(result.output).toContain('"version":"2.0.0"');
|
||||
expect(result.output).not.toContain('"version":"1.0.0"');
|
||||
});
|
||||
|
||||
it('propagates an application failure without restarting it', async () => {
|
||||
expect(await run('fail')).toEqual({ code: 1, output: 'startup failed\n' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
import * as fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { applyPendingUpdate, exists, readManifest, updateDirectory } from '../src/update/files';
|
||||
import { releaseFixture } from './helpers/update-fixture';
|
||||
|
||||
vi.mock('node:fs/promises', async (original) => {
|
||||
const actual = await original<typeof import('node:fs/promises')>();
|
||||
return { ...actual, rename: vi.fn(actual.rename) };
|
||||
});
|
||||
|
||||
let root: string;
|
||||
let staging: string;
|
||||
beforeEach(async () => {
|
||||
root = await fs.mkdtemp(path.join(os.tmpdir(), 'snowluma-update-test-'));
|
||||
await releaseFixture(root, '1.0.0', 'win32-x64', 'old.mjs');
|
||||
staging = await updateDirectory(root);
|
||||
await releaseFixture(path.join(staging, 'pending/payload'), '2.0.0', 'win32-x64', 'new.mjs');
|
||||
});
|
||||
afterEach(async () => {
|
||||
vi.mocked(fs.rename).mockReset();
|
||||
const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
|
||||
vi.mocked(fs.rename).mockImplementation(actual.rename);
|
||||
await fs.rm(root, { recursive: true, force: true });
|
||||
await fs.rm(staging, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('staged updates', () => {
|
||||
it('stages outside the installation and only renames replacements on the destination filesystem', async () => {
|
||||
expect(path.dirname(staging)).toBe(os.tmpdir());
|
||||
expect(staging.startsWith(root + path.sep)).toBe(false);
|
||||
const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
|
||||
vi.mocked(fs.rename).mockImplementation(async (source, destination) => {
|
||||
if (
|
||||
path.dirname(String(destination)) === root &&
|
||||
path.dirname(String(source)) !== root
|
||||
) {
|
||||
throw Object.assign(new Error('cross-device rename'), { code: 'EXDEV' });
|
||||
}
|
||||
|
||||
return actual.rename(source, destination);
|
||||
});
|
||||
expect(await applyPendingUpdate(root)).toBe('2.0.0');
|
||||
expect(await exists(path.join(root, '.update-install'))).toBe(false);
|
||||
expect(await exists(staging)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects an entry point replaced by a directory before touching the installed entry point', async () => {
|
||||
const entry = path.join(staging, 'pending/payload/index.mjs');
|
||||
await fs.rm(entry);
|
||||
await fs.mkdir(entry);
|
||||
await expect(applyPendingUpdate(root)).rejects.toThrow('文件类型无效');
|
||||
expect(await fs.readFile(path.join(root, 'index.mjs'), 'utf8')).toBe('1.0.0');
|
||||
});
|
||||
|
||||
it('cleans a download interrupted before staging', async () => {
|
||||
await fs.mkdir(path.join(staging, 'downloading'));
|
||||
await fs.writeFile(path.join(staging, 'downloading/archive'), 'partial');
|
||||
await fs.rm(path.join(staging, 'pending'), { recursive: true });
|
||||
expect(await applyPendingUpdate(root)).toBeNull();
|
||||
expect(await exists(staging)).toBe(false);
|
||||
});
|
||||
|
||||
it('replaces program files, removes obsolete chunks and preserves user data and Node', async () => {
|
||||
for (const file of [
|
||||
'config/runtime.json',
|
||||
'data/messages.db',
|
||||
'logs/current.log',
|
||||
'tmp/unrelated',
|
||||
'node.exe',
|
||||
'custom.mjs',
|
||||
]) {
|
||||
await fs.mkdir(path.dirname(path.join(root, file)), { recursive: true });
|
||||
await fs.writeFile(path.join(root, file), 'keep');
|
||||
}
|
||||
|
||||
expect(await applyPendingUpdate(root)).toBe('2.0.0');
|
||||
expect((await readManifest(root)).version).toBe('2.0.0');
|
||||
expect(await fs.readFile(path.join(root, 'native/binding.node'), 'utf8')).toBe('2.0.0');
|
||||
expect(await exists(path.join(root, 'old.mjs'))).toBe(false);
|
||||
expect(await exists(path.join(root, 'new.mjs'))).toBe(true);
|
||||
|
||||
for (const file of [
|
||||
'config/runtime.json',
|
||||
'data/messages.db',
|
||||
'logs/current.log',
|
||||
'tmp/unrelated',
|
||||
'node.exe',
|
||||
'custom.mjs',
|
||||
]) {
|
||||
expect(await fs.readFile(path.join(root, file), 'utf8')).toBe('keep');
|
||||
}
|
||||
|
||||
expect(await fs.readdir(path.join(root, 'tmp'))).toEqual(['unrelated']);
|
||||
expect(await applyPendingUpdate(root)).toBeNull();
|
||||
});
|
||||
|
||||
it('only installs files declared by the release manifest', async () => {
|
||||
await fs.writeFile(path.join(staging, 'pending/payload/unlisted.mjs'), 'ignored');
|
||||
expect(await applyPendingUpdate(root)).toBe('2.0.0');
|
||||
expect(await exists(path.join(root, 'unlisted.mjs'))).toBe(false);
|
||||
});
|
||||
|
||||
it('restores the entire old release after a replacement fails, then retries on next startup', async () => {
|
||||
const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
|
||||
let failed = false;
|
||||
vi.mocked(fs.rename).mockImplementation(async (source, destination) => {
|
||||
if (!failed && destination === path.join(root, 'client')) {
|
||||
failed = true;
|
||||
throw new Error('file locked');
|
||||
}
|
||||
|
||||
return actual.rename(source, destination);
|
||||
});
|
||||
await expect(applyPendingUpdate(root)).rejects.toThrow('file locked');
|
||||
expect((await readManifest(root)).version).toBe('1.0.0');
|
||||
expect(await fs.readFile(path.join(root, 'app.mjs'), 'utf8')).toBe('1.0.0');
|
||||
expect(await fs.readFile(path.join(root, 'client/index.html'), 'utf8')).toBe('1.0.0');
|
||||
expect(await exists(path.join(root, 'new.mjs'))).toBe(false);
|
||||
expect(await exists(path.join(staging, 'pending/payload'))).toBe(true);
|
||||
await expect(applyPendingUpdate(root)).resolves.toBe('2.0.0');
|
||||
});
|
||||
|
||||
it('recovers an interrupted transaction before retrying', async () => {
|
||||
const current = await readManifest(root);
|
||||
const next = await readManifest(path.join(staging, 'pending/payload'));
|
||||
const backup = path.join(staging, 'pending/backup');
|
||||
await fs.mkdir(backup);
|
||||
|
||||
for (const entry of current.entries) {
|
||||
await fs.cp(path.join(root, entry), path.join(backup, entry), { recursive: true });
|
||||
}
|
||||
|
||||
await fs.writeFile(
|
||||
path.join(staging, 'pending/transaction.json'),
|
||||
JSON.stringify({
|
||||
entries: [...new Set([...current.entries, ...next.entries])],
|
||||
original: current.entries,
|
||||
}),
|
||||
);
|
||||
await fs.writeFile(path.join(root, 'app.mjs'), 'interrupted');
|
||||
await fs.rm(path.join(root, 'native'), { recursive: true });
|
||||
await fs.writeFile(path.join(root, 'new.mjs'), 'partial');
|
||||
// Fail before installation so we can inspect the recovered release.
|
||||
const entry = path.join(staging, 'pending/payload/index.mjs');
|
||||
await fs.rm(entry);
|
||||
await fs.mkdir(entry);
|
||||
await expect(applyPendingUpdate(root)).rejects.toThrow('文件类型无效');
|
||||
expect(await fs.readFile(path.join(root, 'index.mjs'), 'utf8')).toBe('1.0.0');
|
||||
expect(await fs.readFile(path.join(root, 'app.mjs'), 'utf8')).toBe('1.0.0');
|
||||
expect(await fs.readFile(path.join(root, 'native/binding.node'), 'utf8')).toBe('1.0.0');
|
||||
expect(await exists(path.join(root, 'new.mjs'))).toBe(false);
|
||||
await fs.rm(entry, { recursive: true });
|
||||
await fs.writeFile(entry, '2.0.0');
|
||||
expect(await applyPendingUpdate(root)).toBe('2.0.0');
|
||||
});
|
||||
|
||||
it('cleans an already committed transaction without restoring its backup', async () => {
|
||||
await fs.rename(path.join(staging, 'pending'), path.join(staging, 'completed'));
|
||||
expect(await applyPendingUpdate(root)).toBeNull();
|
||||
expect(await exists(staging)).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['config', '../outside', 'node.exe', 'data', 'C:/outside'])(
|
||||
'rejects a manifest owning %s',
|
||||
async (entry) => {
|
||||
const payload = path.join(staging, 'pending/payload');
|
||||
const manifest = await readManifest(payload);
|
||||
manifest.entries.push(entry);
|
||||
await fs.writeFile(path.join(payload, 'release.json'), JSON.stringify(manifest));
|
||||
await expect(applyPendingUpdate(root)).rejects.toThrow('清单无效');
|
||||
expect((await readManifest(root)).version).toBe('1.0.0');
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects a release for a different platform before replacing anything', async () => {
|
||||
const payload = path.join(staging, 'pending/payload');
|
||||
await fs.rm(payload, { recursive: true });
|
||||
await releaseFixture(payload, '2.0.0', 'linux-x64');
|
||||
await expect(applyPendingUpdate(root)).rejects.toThrow('平台不匹配');
|
||||
expect((await readManifest(root)).version).toBe('1.0.0');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { updateDirectory } from '../src/update/files';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createUpdateService } from '../src/update/service';
|
||||
import { updateRoutes } from '../src/webui/update-routes';
|
||||
import { releaseFixture } from './helpers/update-fixture';
|
||||
|
||||
let root: string;
|
||||
let staging: string;
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-update-service-'));
|
||||
await releaseFixture(root, '1.0.0');
|
||||
staging = await updateDirectory(root);
|
||||
});
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
await rm(staging, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('update service', () => {
|
||||
it('stages a single download, survives a service reload and leaves running files alone', async () => {
|
||||
let finish!: () => void;
|
||||
const wait = new Promise<void>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
const download = vi.fn(async (directory: string, version: string, target: string) => {
|
||||
await wait;
|
||||
await releaseFixture(path.join(directory, 'payload'), version, target);
|
||||
await writeFile(path.join(directory, 'archive'), 'archive');
|
||||
});
|
||||
const service = await createUpdateService(root, '1.0.0', { download, isContainer: false });
|
||||
service.start('2.0.0');
|
||||
expect(service.status()).toEqual({
|
||||
current: '1.0.0',
|
||||
phase: 'downloading',
|
||||
version: '2.0.0',
|
||||
});
|
||||
expect(() => service.start('2.0.0')).toThrow('正在进行');
|
||||
finish();
|
||||
await vi.waitFor(() => expect(service.status().phase).toBe('ready'));
|
||||
expect(download).toHaveBeenCalledOnce();
|
||||
expect(await readdir(path.join(staging, 'pending'))).toEqual(['payload']);
|
||||
const reloaded = await createUpdateService(root, '1.0.0', { download, isContainer: false });
|
||||
expect(reloaded.status()).toEqual({ current: '1.0.0', phase: 'ready', version: '2.0.0' });
|
||||
reloaded.restart();
|
||||
expect(reloaded.status().phase).toBe('restarting');
|
||||
expect(() => reloaded.restart()).toThrow('尚未就绪');
|
||||
});
|
||||
|
||||
it('cleans a failed download and allows retry', async () => {
|
||||
const download = vi.fn(async (directory: string) => {
|
||||
await writeFile(path.join(directory, 'archive'), 'partial');
|
||||
throw new Error('connection reset');
|
||||
});
|
||||
const service = await createUpdateService(root, '1.0.0', { download, isContainer: false });
|
||||
service.start('2.0.0');
|
||||
await vi.waitFor(() =>
|
||||
expect(service.status()).toEqual({
|
||||
current: '1.0.0',
|
||||
phase: 'error',
|
||||
message: 'connection reset',
|
||||
}),
|
||||
);
|
||||
expect(await readdir(staging)).toEqual([]);
|
||||
expect(() => service.start('2.0.0')).not.toThrow();
|
||||
await vi.waitFor(() => expect(download).toHaveBeenCalledTimes(2));
|
||||
await vi.waitFor(() => expect(service.status().phase).toBe('error'));
|
||||
});
|
||||
|
||||
it.each(['1.0.0', '0.9.0', '2.0.0-rc.1', '../../outside', null])(
|
||||
'rejects invalid or older version %s',
|
||||
async (version) => {
|
||||
const download = vi.fn();
|
||||
const service = await createUpdateService(root, '1.0.0', {
|
||||
download,
|
||||
isContainer: false,
|
||||
});
|
||||
expect(() => service.start(version)).toThrow('正式版本');
|
||||
expect(download).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('does not enable updates for a source checkout', async () => {
|
||||
const service = await createUpdateService(undefined, '1.0.0');
|
||||
expect(service.status().phase).toBe('unavailable');
|
||||
expect(() => service.start('2.0.0')).toThrow('发行包');
|
||||
expect(() => service.restart()).toThrow('尚未就绪');
|
||||
});
|
||||
|
||||
it('does not update container image layers', async () => {
|
||||
const service = await createUpdateService(root, '1.0.0', { isContainer: true });
|
||||
expect(service.status()).toMatchObject({ phase: 'unavailable', message: '请更新容器镜像' });
|
||||
});
|
||||
|
||||
it('restarts only after the HTTP response has finished', async () => {
|
||||
await releaseFixture(path.join(staging, 'pending/payload'), '2.0.0');
|
||||
const service = await createUpdateService(root, '1.0.0', { isContainer: false });
|
||||
const restart = vi.fn();
|
||||
const outgoing = new EventEmitter();
|
||||
const app = updateRoutes(service, restart);
|
||||
const response = await app.request('/restart', { method: 'POST' }, { outgoing });
|
||||
expect(response.status).toBe(202);
|
||||
expect(await response.json()).toMatchObject({ phase: 'restarting' });
|
||||
expect(restart).not.toHaveBeenCalled();
|
||||
outgoing.emit('finish');
|
||||
expect(restart).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each(['{}', 'not json'])('rejects an invalid download request: %s', async (body) => {
|
||||
const service = await createUpdateService(root, '1.0.0', { isContainer: false });
|
||||
const app = updateRoutes(service, vi.fn());
|
||||
const response = await app.request('/download', { method: 'POST', body });
|
||||
expect(response.status).toBe(400);
|
||||
expect(service.status().phase).toBe('idle');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { compareVersions, currentVersion, getUpdateInfo } from '../src/webui/update-check';
|
||||
import { compareVersions, getUpdateInfo } from '../src/update/check';
|
||||
|
||||
const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
|
||||
const NOTES_MAX = 4_000;
|
||||
@@ -44,11 +44,7 @@ afterEach(() => {
|
||||
}
|
||||
});
|
||||
|
||||
describe('currentVersion', () => {
|
||||
it('falls back to 0.0.0 when the build-time version is unset', () => {
|
||||
expect(currentVersion()).toBe('0.0.0');
|
||||
});
|
||||
});
|
||||
vi.mock('@snowluma/common/version', () => ({ APP_VERSION: '0.0.0' }));
|
||||
|
||||
describe('compareVersions', () => {
|
||||
it.each([
|
||||
|
||||
Reference in new issue
Block a user