feat(core): add staged self-updates and unify application version

This commit is contained in:
手瓜一十雪 committed 2026-10-18 12:50:11 +08:00
1 parent c54aeffc77
commit 5032cbb8c0
45 files changed
+1860 -165

No files matched your search

+180
View File
@@ -0,0 +1,180 @@
import { APP_VERSION } from '@snowluma/common/version';
import { createLogger } from '@snowluma/common/logger';
import { createSingleFlightCache } from '@snowluma/common/single-flight-cache';
const log = createLogger('Update');
const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — comfortably under the rate limit
const FETCH_TIMEOUT_MS = 8_000;
const NOTES_MAX = 4_000; // cap the release-body we hand back to the client
export interface UpdateCheckResult {
/** The running build's version (no `v` prefix). */
current: string;
/** Latest stable release version, or null when the check did not complete. */
latest: string | null;
/** True only when `latest` is strictly newer than `current`. */
hasUpdate: boolean;
/** GitHub release page URL for the latest release. */
htmlUrl: string | null;
/** Release notes (markdown), truncated to {@link NOTES_MAX}. */
notes: string | null;
/** ISO timestamp the latest release was published. */
publishedAt: string | null;
/** When this result was produced (epoch ms). */
checkedAt: number;
/** Set when the check was skipped or failed; the UI degrades silently. */
error?: string;
}
interface GithubRelease {
tag_name?: string;
html_url?: string;
body?: string;
published_at?: string;
}
function isEnabled(): boolean {
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
}
/**
* Compare two dotted versions. Returns >0 if `a` is newer than `b`, <0 if
* older, 0 if equal. The numeric core (major.minor.patch) compares
* numerically; a prerelease (`-rc.1`) ranks below its release. Good enough
* for "is the latest stable strictly newer than what we run" — and avoids
* pulling in a `semver` runtime dependency (the dist bundle ships none).
*/
export function compareVersions(a: string, b: string): number {
const parse = (v: string) => {
const [core = '', pre = ''] = v.replace(/^v/, '').split('-', 2);
const nums = core.split('.').map((n) => parseInt(n, 10) || 0);
while (nums.length < 3) {
nums.push(0);
}
return { nums, pre };
};
const pa = parse(a);
const pb = parse(b);
for (let i = 0; i < 3; i++) {
if (pa.nums[i] !== pb.nums[i]) {
return pa.nums[i] - pb.nums[i];
}
}
if (pa.pre === pb.pre) {
return 0;
}
if (!pa.pre) {
return 1;
} // release > prerelease
if (!pb.pre) {
return -1;
}
return pa.pre < pb.pre ? -1 : 1;
}
// TTL + single-flight: cache good results for CACHE_TTL_MS (well under GitHub's
// 60 req/hr limit) and collapse concurrent checks onto one fetch. Error results
// are intentionally not cached (shouldCache) so the next check retries.
const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
ttlMs: CACHE_TTL_MS,
shouldCache: (r) => !r.error,
load: async (current) => {
const result = await fetchLatest(current);
if (result.error) {
log.debug('update check failed: %s', result.error);
} else if (result.hasUpdate) {
log.info('a newer release is available: v%s (running v%s)', result.latest, current);
}
return result;
},
});
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
const base: UpdateCheckResult = {
current,
latest: null,
hasUpdate: false,
htmlUrl: null,
notes: null,
publishedAt: null,
checkedAt: Date.now(),
};
try {
// `/releases/latest` already excludes drafts and prereleases, so this is
// stable-channel by construction.
const res = await fetch(LATEST_RELEASE_URL, {
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': `SnowLuma/${current}`,
'X-GitHub-Api-Version': '2022-11-28',
},
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!res.ok) {
return { ...base, error: `github ${res.status}` };
}
const rel = (await res.json()) as GithubRelease;
const tag = (rel.tag_name ?? '').trim();
if (!tag) {
return { ...base, error: 'no tag' };
}
const latest = tag.replace(/^v/, '');
return {
current,
latest,
hasUpdate: compareVersions(latest, current) > 0,
htmlUrl: rel.html_url ?? null,
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
publishedAt: rel.published_at ?? null,
checkedAt: Date.now(),
};
} catch (e) {
return { ...base, error: e instanceof Error ? e.message : 'network error' };
}
}
/**
* Get the update-availability result. Cached for {@link CACHE_TTL_MS}; pass
* `force` to bypass the cache (the WebUI's "立即检查" button). Never throws —
* failures come back as a result with `error` set and `hasUpdate: false`, and
* are not cached so the next check retries.
*/
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
const current = APP_VERSION;
if (!isEnabled()) {
return { ...emptyResult(current), error: 'disabled' };
}
return updateCache.get(current, { force });
}
function emptyResult(current: string): UpdateCheckResult {
return {
current,
latest: null,
hasUpdate: false,
htmlUrl: null,
notes: null,
publishedAt: null,
checkedAt: Date.now(),
};
}
+187
View File
@@ -0,0 +1,187 @@
import { createHash } from 'node:crypto';
import { createWriteStream } from 'node:fs';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { Readable, Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { unzipSync } from 'fflate';
import { x as extractTar } from 'tar';
import { isRuntimeEntry, readManifest } from './files';
interface ReleaseAsset {
url: string;
size: number;
digest: string;
}
export function assetName(version: string, target: string): string {
const platform = target.replace('win32', 'win');
return `SnowLuma-v${version}-${platform}-lite.${target.startsWith('win32') ? 'zip' : 'tar.gz'}`;
}
async function releaseAsset(version: string, target: string): Promise<ReleaseAsset> {
const name = assetName(version, target);
const response = await fetch(
`https://api.github.com/repos/SnowLuma/SnowLuma/releases/tags/v${version}`,
{
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': 'SnowLuma',
'X-GitHub-Api-Version': '2022-11-28',
},
signal: AbortSignal.timeout(15_000),
},
);
if (!response.ok) {
throw new Error(`获取更新失败: GitHub ${response.status}`);
}
const release: unknown = await response.json();
if (
!release ||
typeof release !== 'object' ||
!('assets' in release) ||
!Array.isArray(release.assets)
) {
throw new Error('发布信息无效');
}
const asset: unknown = release.assets.find(
(item: unknown) =>
item !== null && typeof item === 'object' && 'name' in item && item.name === name,
);
const url = `https://github.com/SnowLuma/SnowLuma/releases/download/v${version}/${name}`;
if (
!asset ||
typeof asset !== 'object' ||
!('size' in asset) ||
typeof asset.size !== 'number' ||
!Number.isSafeInteger(asset.size) ||
asset.size <= 0 ||
!('digest' in asset) ||
typeof asset.digest !== 'string' ||
!/^sha256:[a-f0-9]{64}$/.test(asset.digest)
) {
throw new Error('更新包不存在或缺少校验信息');
}
return { url, size: asset.size, digest: asset.digest };
}
export function archivePath(name: string): string {
const normalized = name.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/$/, '');
if (normalized === '.' || normalized === '') {
return '';
}
const parts = normalized.split('/');
if (
!isRuntimeEntry(parts[0]) ||
parts.some((part) => !part || part === '.' || part === '..' || /[:\0]/.test(part))
) {
throw new Error(`更新包路径无效: ${name}`);
}
return normalized;
}
export async function downloadUpdate(
directory: string,
version: string,
target: string,
): Promise<void> {
const asset = await releaseAsset(version, target);
const response = await fetch(asset.url, { signal: AbortSignal.timeout(10 * 60_000) });
if (!response.ok || !response.body) {
throw new Error(`下载更新失败: HTTP ${response.status}`);
}
const archive = path.join(directory, 'archive');
const hash = createHash('sha256');
let received = 0;
await pipeline(
Readable.fromWeb(response.body),
new Transform({
transform(chunk: Buffer, _encoding, callback) {
received += chunk.length;
if (received > asset.size) {
callback(new Error('更新包大小不匹配'));
return;
}
hash.update(chunk);
callback(null, chunk);
},
}),
createWriteStream(archive, { flags: 'wx' }),
);
if (received !== asset.size || `sha256:${hash.digest('hex')}` !== asset.digest) {
throw new Error('更新包校验失败');
}
const payload = path.join(directory, 'payload');
await mkdir(payload);
if (target.startsWith('win32')) {
const files = unzipSync(await readFile(archive), {
filter: (entry) => {
archivePath(entry.name);
return true;
},
});
for (const [name, bytes] of Object.entries(files)) {
const relative = archivePath(name);
if (!relative || name.endsWith('/')) {
continue;
}
const destination = path.join(payload, relative);
await mkdir(path.dirname(destination), { recursive: true });
await writeFile(destination, bytes, { flag: 'wx' });
}
} else {
let invalidEntry: Error | undefined;
await extractTar({
file: archive,
cwd: payload,
strict: true,
filter: (name, entry) => {
try {
archivePath(name);
if (
!('type' in entry) ||
(entry.type !== 'File' && entry.type !== 'Directory')
) {
throw new Error('更新包包含链接或特殊文件');
}
return true;
} catch (error) {
invalidEntry = error instanceof Error ? error : new Error(String(error));
return false;
}
},
});
if (invalidEntry) {
throw invalidEntry;
}
}
const manifest = await readManifest(payload);
if (manifest.version !== version || manifest.target !== target) {
throw new Error('更新包版本或平台不匹配');
}
}
+272
View File
@@ -0,0 +1,272 @@
import { access, cp, lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { constants, existsSync } from 'node:fs';
import os from 'node:os';
export const MANIFEST_FILE = 'release.json';
export async function updateDirectory(root: string, temporaryRoot = os.tmpdir()): Promise<string> {
const local = path.join(root, 'tmp', 'update');
// A locally staged update must remain discoverable if system tmp becomes available again.
if (existsSync(local)) {
return local;
}
const identity = createHash('sha256').update(path.resolve(root)).digest('hex').slice(0, 16);
const directory = path.join(temporaryRoot, `snowluma-update-${identity}`);
try {
await mkdir(directory, { recursive: true });
await access(directory, constants.W_OK);
return directory;
} catch (error) {
if (
!(error instanceof Error) ||
!('code' in error) ||
!['EACCES', 'EPERM', 'EROFS'].includes(String(error.code))
) {
throw error;
}
await mkdir(local, { recursive: true });
return local;
}
}
export interface ReleaseManifest {
version: string;
target: string;
entries: string[];
}
const runtimeEntries = new Set([
'native',
'client',
'package.json',
MANIFEST_FILE,
'launcher.bat',
'launcher.sh',
'check-node-version.cjs',
'EULA.md',
'PRIVACY.md',
]);
export function isRuntimeEntry(name: string): boolean {
return runtimeEntries.has(name) || /^[\w-]+\.mjs(?:\.map)?$/.test(name);
}
function entryList(value: unknown): value is string[] {
return (
Array.isArray(value) &&
value.every((entry) => typeof entry === 'string' && isRuntimeEntry(entry)) &&
new Set(value).size === value.length
);
}
export async function exists(file: string): Promise<boolean> {
try {
await lstat(file);
return true;
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
return false;
}
throw error;
}
}
export async function readManifest(root: string): Promise<ReleaseManifest> {
const value: unknown = JSON.parse(await readFile(path.join(root, MANIFEST_FILE), 'utf8'));
if (
!value ||
typeof value !== 'object' ||
!('version' in value) ||
typeof value.version !== 'string' ||
!/^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(value.version) ||
!('target' in value) ||
typeof value.target !== 'string' ||
!/^(win32-x64|linux-(x64|arm64))$/.test(value.target) ||
!('entries' in value) ||
!entryList(value.entries)
) {
throw new Error('更新包清单无效');
}
const entries = value.entries;
if (
![
'index.mjs',
'native',
'client',
'package.json',
MANIFEST_FILE,
'check-node-version.cjs',
'EULA.md',
'PRIVACY.md',
value.target.startsWith('win32') ? 'launcher.bat' : 'launcher.sh',
].every((entry) => entries.includes(entry))
) {
throw new Error('更新包清单无效');
}
return { version: value.version, target: value.target, entries: value.entries };
}
async function checkEntryTypes(root: string, entries: string[]): Promise<void> {
for (const entry of entries) {
const stat = await lstat(path.join(root, entry));
const directory = entry === 'native' || entry === 'client';
if (directory ? !stat.isDirectory() : !stat.isFile()) {
throw new Error(`更新包文件类型无效: ${entry}`);
}
}
}
interface Transaction {
entries: string[];
original: string[];
}
async function readTransaction(file: string): Promise<Transaction> {
const value: unknown = JSON.parse(await readFile(file, 'utf8'));
if (
!value ||
typeof value !== 'object' ||
!('entries' in value) ||
!entryList(value.entries) ||
!('original' in value) ||
!entryList(value.original)
) {
throw new Error('更新恢复记录无效');
}
const entries = value.entries;
if (value.original.some((entry) => !entries.includes(entry))) {
throw new Error('更新恢复记录无效');
}
return { entries: value.entries, original: value.original };
}
async function restore(root: string, pending: string, transaction: Transaction): Promise<void> {
for (const entry of transaction.entries) {
const backup = path.join(pending, 'backup', entry);
const destination = path.join(root, entry);
if (transaction.original.includes(entry)) {
await replaceEntry(backup, destination, path.join(root, '.update-install'));
} else {
await rm(destination, { recursive: true, force: true });
}
}
await rm(path.join(pending, 'transaction.json'));
}
async function replaceEntry(source: string, destination: string, temporary: string): Promise<void> {
await rm(temporary, { recursive: true, force: true });
await cp(source, temporary, { recursive: true });
// Files stay present until their replacement is ready, including the entry point.
if ((await lstat(source)).isDirectory()) {
await rm(destination, { recursive: true, force: true });
}
await rename(temporary, destination);
}
// Called before loading native libraries, after the previous process has exited.
export async function applyPendingUpdate(root: string): Promise<string | null> {
const directory = await updateDirectory(root);
const pending = path.join(directory, 'pending');
const completed = path.join(directory, 'completed');
await rm(completed, { recursive: true, force: true });
await rm(path.join(directory, 'downloading'), { recursive: true, force: true });
await rm(path.join(root, '.update-install'), { recursive: true, force: true });
if (!(await exists(pending))) {
await rm(directory, { recursive: true });
return null;
}
const journal = path.join(pending, 'transaction.json');
if (await exists(journal)) {
await restore(root, pending, await readTransaction(journal));
}
const payload = path.join(pending, 'payload');
const next = await readManifest(payload);
const current = await readManifest(root);
if (next.target !== current.target) {
throw new Error('更新包平台不匹配');
}
await checkEntryTypes(payload, next.entries);
const entries = [...new Set([...current.entries, ...next.entries])];
const original: string[] = [];
for (const entry of entries) {
if (await exists(path.join(root, entry))) {
if ((await lstat(path.join(root, entry))).isSymbolicLink()) {
throw new Error(`更新目标不能是符号链接: ${entry}`);
}
original.push(entry);
}
}
const transaction = { entries, original };
const backup = path.join(pending, 'backup');
await rm(backup, { recursive: true, force: true });
await mkdir(backup);
for (const entry of original) {
await cp(path.join(root, entry), path.join(backup, entry), { recursive: true });
}
await writeFile(`${journal}.tmp`, JSON.stringify(transaction));
await rename(`${journal}.tmp`, journal);
try {
for (const entry of next.entries) {
await replaceEntry(
path.join(payload, entry),
path.join(root, entry),
path.join(root, '.update-install'),
);
}
for (const entry of current.entries) {
if (!next.entries.includes(entry)) {
await rm(path.join(root, entry), { recursive: true, force: true });
}
}
// Renaming commits the transaction before cleanup, including across a crash.
await rename(pending, completed);
} catch (error) {
try {
await restore(root, pending, transaction);
} catch (restoreError) {
throw new AggregateError(
[error, restoreError],
'更新失败,恢复未完成;下次启动将继续恢复',
);
}
throw error;
}
await rm(directory, { recursive: true });
return next.version;
}
+101
View File
@@ -0,0 +1,101 @@
import { existsSync } from 'node:fs';
import { mkdir, rename, rm } from 'node:fs/promises';
import path from 'node:path';
import { createLogger } from '@snowluma/common/logger';
import { compareVersions } from './check';
import { downloadUpdate } from './download';
import { exists, MANIFEST_FILE, readManifest, updateDirectory } from './files';
const log = createLogger('Update');
export type UpdateState =
| { phase: 'unavailable'; message: string }
| { phase: 'idle' }
| { phase: 'downloading' | 'ready' | 'restarting'; version: string }
| { phase: 'error'; message: string };
export async function createUpdateService(
root: string | undefined,
current: string,
options: { download?: typeof downloadUpdate; isContainer?: boolean } = {},
) {
const download = options.download ?? downloadUpdate;
let state: UpdateState;
let target = '';
let staging = '';
if (!root || !existsSync(path.join(root, MANIFEST_FILE))) {
state = { phase: 'unavailable', message: '在线更新仅支持发行包' };
} else if (
options.isContainer ??
(existsSync('/.dockerenv') || Boolean(process.env.container))
) {
state = { phase: 'unavailable', message: '请更新容器镜像' };
} else {
const manifest = await readManifest(root);
target = manifest.target;
staging = await updateDirectory(root);
const pending = path.join(staging, 'pending', 'payload');
state = (await exists(pending))
? { phase: 'ready', version: (await readManifest(pending)).version }
: { phase: 'idle' };
}
const prepare = async (version: string): Promise<void> => {
const directory = path.join(staging, 'downloading');
try {
await rm(directory, { recursive: true, force: true });
await mkdir(directory, { recursive: true });
await download(directory, version, target);
await rm(path.join(directory, 'archive'));
await rename(directory, path.join(staging, 'pending'));
state = { phase: 'ready', version };
log.info('v%s 已下载,重启后应用', version);
} catch (error) {
log.error('下载更新失败: %s', error);
let message = error instanceof Error ? error.message : String(error);
try {
await rm(directory, { recursive: true, force: true });
} catch (cleanupError) {
message += `;清理更新文件失败: ${String(cleanupError)}`;
log.error('清理更新文件失败: %s', cleanupError);
}
state = { phase: 'error', message };
}
};
return {
status: () => ({ current, ...state }),
start(version: unknown) {
if (state.phase !== 'idle' && state.phase !== 'error') {
throw new Error(
state.phase === 'unavailable' ? state.message : '更新正在进行或等待重启',
);
}
if (
typeof version !== 'string' ||
!/^\d+\.\d+\.\d+$/.test(version) ||
compareVersions(version, current) <= 0
) {
throw new Error('请选择更新的正式版本');
}
state = { phase: 'downloading', version };
log.info('下载 v%s', version);
void prepare(version);
},
restart() {
if (state.phase !== 'ready') {
throw new Error('更新包尚未就绪');
}
state = { phase: 'restarting', version: state.version };
},
};
}
export type UpdateService = Awaited<ReturnType<typeof createUpdateService>>;
+75
View File
@@ -0,0 +1,75 @@
import { spawn } from 'node:child_process';
import path from 'node:path';
import { applyPendingUpdate } from './files';
export const RESTART_EXIT_CODE = 75;
export async function runApplication(root: string): Promise<void> {
let stopping = false;
let child: ReturnType<typeof spawn> | undefined;
const requestShutdown = () => {
if (child?.connected) {
child.send('shutdown', (error) => {
if (error) {
console.error('[App] 发送退出请求失败:', error);
}
});
}
};
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
process.on(signal, () => {
stopping = true;
if (process.platform === 'win32') {
requestShutdown();
} else {
child?.kill(signal);
}
});
}
try {
do {
const version = await applyPendingUpdate(root);
if (version) {
console.info(`[Update] 已更新至 v${version}`);
}
if (stopping) {
break;
}
const code = await new Promise<number>((resolve, reject) => {
child = spawn(
process.execPath,
[...process.execArgv, path.join(root, 'index.mjs'), ...process.argv.slice(2)],
{
stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
env: { ...process.env, SNOWLUMA_UPDATE_ROOT: root },
},
);
child.once('error', reject);
child.on('message', (message) => {
if (message === 'ready' && stopping) {
requestShutdown();
}
});
child.once('exit', (exitCode, signal) =>
resolve(exitCode ?? (signal === 'SIGINT' ? 130 : 143)),
);
});
child = undefined;
if (code !== RESTART_EXIT_CODE || stopping) {
process.exitCode = code === RESTART_EXIT_CODE ? 0 : code;
break;
}
} while (!stopping);
} catch (error) {
console.error('[Update] 启动失败:', error);
process.exitCode = 1;
}
}