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
Vendored
+1
-1
@@ -1,2 +1,2 @@
|
||||
declare const __BUILD_WEBUI__: boolean;
|
||||
declare const __APP_VERSION__: string;
|
||||
declare const __PACKAGED__: boolean;
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getRuntimeIntegrity, HookManager } from '@snowluma/bridge';
|
||||
import { APP_VERSION } from '@snowluma/common/version';
|
||||
import { configureFileTransport } from '@snowluma/common/log-file-transport';
|
||||
import { closeLogger, createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
@@ -15,14 +16,20 @@ import {
|
||||
runMessageStoreMigrationWorker,
|
||||
} from '@snowluma/onebot/message-store-migration-worker';
|
||||
import { workerData } from 'node:worker_threads';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { BridgeManager } from './bridge/manager';
|
||||
import { createNotificationManager } from './notifications/manager';
|
||||
import { createStateWiring } from './webui/state-wiring';
|
||||
import { initWebUI } from './webui/server';
|
||||
import { bindSystemFaceCatalog } from './sys-face-catalog';
|
||||
import { readAppVersion, startNativeStageSync, tempStagePath } from './native-stage-sync';
|
||||
import { startNativeStageSync, tempStagePath } from './native-stage-sync';
|
||||
import { logRuntimeIntegrity } from './runtime-integrity-log';
|
||||
import { RESTART_EXIT_CODE, runApplication } from './update/startup';
|
||||
|
||||
const log = createLogger('App');
|
||||
const updateRoot =
|
||||
typeof __PACKAGED__ === 'undefined' ? undefined : path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
function installProcessGuards(): void {
|
||||
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
|
||||
@@ -54,7 +61,7 @@ async function main() {
|
||||
log.info('SnowLuma starting');
|
||||
logRuntimeIntegrity(getRuntimeIntegrity());
|
||||
const stopNativeStageSync = startNativeStageSync({
|
||||
version: readAppVersion(import.meta.url),
|
||||
version: APP_VERSION,
|
||||
dataDir: 'data',
|
||||
tempPath: tempStagePath(),
|
||||
});
|
||||
@@ -108,7 +115,6 @@ async function main() {
|
||||
process.env.SNOWLUMA_DEV_WEBUI === '1'
|
||||
) {
|
||||
try {
|
||||
const { initWebUI } = await import('./webui/server');
|
||||
const started = await initWebUI(
|
||||
runtimeConfig.webuiPort || 5099,
|
||||
oneBotManager,
|
||||
@@ -119,6 +125,10 @@ async function main() {
|
||||
tlsEnabled: runtimeConfig.webuiTls?.enabled,
|
||||
trustProxy: runtimeConfig.trustProxy,
|
||||
stateBus: stateWiring.bus,
|
||||
updateRoot,
|
||||
restart: () => {
|
||||
void shutdown('update', RESTART_EXIT_CODE);
|
||||
},
|
||||
},
|
||||
);
|
||||
stopWebUI = started.stop;
|
||||
@@ -131,14 +141,14 @@ async function main() {
|
||||
// SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path.
|
||||
let shutdownStarted = false;
|
||||
|
||||
const shutdown = (signal: string) => async () => {
|
||||
const shutdown = async (signal: string, requestedExitCode = 0) => {
|
||||
if (shutdownStarted) {
|
||||
return;
|
||||
}
|
||||
|
||||
shutdownStarted = true;
|
||||
log.warn(`Shutting down (${signal})...`);
|
||||
let exitCode = 0;
|
||||
let exitCode = requestedExitCode;
|
||||
|
||||
try {
|
||||
await oneBotManager.dispose();
|
||||
@@ -219,8 +229,24 @@ async function main() {
|
||||
process.exit(exitCode);
|
||||
};
|
||||
|
||||
process.on('SIGINT', shutdown('SIGINT'));
|
||||
process.on('SIGTERM', shutdown('SIGTERM'));
|
||||
process.on('SIGINT', () => {
|
||||
void shutdown('SIGINT');
|
||||
});
|
||||
process.on('SIGTERM', () => {
|
||||
void shutdown('SIGTERM');
|
||||
});
|
||||
|
||||
if (process.send) {
|
||||
process.on('message', (message) => {
|
||||
if (message === 'shutdown') {
|
||||
void shutdown('launcher');
|
||||
}
|
||||
});
|
||||
process.on('disconnect', () => {
|
||||
void shutdown('launcher disconnected');
|
||||
});
|
||||
process.send('ready');
|
||||
}
|
||||
}
|
||||
|
||||
function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
|
||||
@@ -245,6 +271,8 @@ if (isMessageStoreMigrationWorkerData(workerData)) {
|
||||
runMessageStoreMigrationWorker(workerData).catch(() => {
|
||||
process.exitCode = 1;
|
||||
});
|
||||
} else if (updateRoot && !process.env.SNOWLUMA_UPDATE_ROOT) {
|
||||
void runApplication(updateRoot);
|
||||
} else {
|
||||
installProcessGuards();
|
||||
main().catch(async (error) => {
|
||||
|
||||
@@ -109,25 +109,6 @@ export function tempStagePath(
|
||||
return `/tmp/sl-${uid}/${STAGE_FILE_NAME}`;
|
||||
}
|
||||
|
||||
export function readAppVersion(moduleUrl: string | URL = import.meta.url): string {
|
||||
if (typeof __APP_VERSION__ === 'string' && __APP_VERSION__) {
|
||||
return __APP_VERSION__;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = readFileSync(new URL('../package.json', moduleUrl), 'utf8');
|
||||
const version = JSON.parse(raw).version;
|
||||
|
||||
if (typeof version === 'string' && version.trim()) {
|
||||
return version.trim();
|
||||
}
|
||||
} catch {
|
||||
// Built layouts that do not sit next to a package manifest keep the fallback.
|
||||
}
|
||||
|
||||
return '0.0.0';
|
||||
}
|
||||
|
||||
export function errorCode(error: unknown): string {
|
||||
if (error && typeof error === 'object' && 'code' in error) {
|
||||
const code = (error as { code?: unknown }).code;
|
||||
|
||||
@@ -1,15 +1,4 @@
|
||||
// Advisory update check against the public GitHub Releases API.
|
||||
//
|
||||
// Strictly read-only (T0): SnowLuma never downloads or applies anything
|
||||
// itself — cross-platform self-update is a minefield (Windows locks loaded
|
||||
// .node/.dll/node.exe, Docker bakes the app into image layers, bare installs
|
||||
// have no supervisor). We only tell the WebUI that a newer *stable* release
|
||||
// exists and link the user to it; they download and apply manually.
|
||||
//
|
||||
// The result is cached to stay well under GitHub's 60 req/hr unauthenticated
|
||||
// rate limit, and every failure degrades silently (the UI just shows
|
||||
// "无法检查更新" rather than nagging).
|
||||
|
||||
import { APP_VERSION } from '@snowluma/common/version';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { createSingleFlightCache } from '@snowluma/common/single-flight-cache';
|
||||
|
||||
@@ -46,10 +35,6 @@ interface GithubRelease {
|
||||
published_at?: string;
|
||||
}
|
||||
|
||||
export function currentVersion(): string {
|
||||
return typeof __APP_VERSION__ === 'string' && __APP_VERSION__ ? __APP_VERSION__ : '0.0.0';
|
||||
}
|
||||
|
||||
function isEnabled(): boolean {
|
||||
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
|
||||
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
|
||||
@@ -173,7 +158,7 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
* are not cached so the next check retries.
|
||||
*/
|
||||
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
|
||||
const current = currentVersion();
|
||||
const current = APP_VERSION;
|
||||
|
||||
if (!isEnabled()) {
|
||||
return { ...emptyResult(current), error: 'disabled' };
|
||||
@@ -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('更新包版本或平台不匹配');
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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>>;
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { APP_VERSION } from '@snowluma/common/version';
|
||||
import { serve } from '@hono/node-server';
|
||||
import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
|
||||
@@ -77,7 +78,7 @@ import { restoreBackup, RestoreTransactionError, type RestorePhase } from './res
|
||||
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
|
||||
import { createFramePusher } from './debug-stream';
|
||||
import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools';
|
||||
import { sseResponse } from './sse-response';
|
||||
import { sseResponse as createSseResponse } from './sse-response';
|
||||
import { bindStateStream } from './state-stream';
|
||||
import type { StateBus, StateResource } from './state-bus';
|
||||
import { startConnectionDiffLoop } from './connection-diff-loop';
|
||||
@@ -99,7 +100,9 @@ import {
|
||||
sniffImageMime,
|
||||
writeBackgroundImage,
|
||||
} from './ui-config';
|
||||
import { currentVersion, getUpdateInfo } from './update-check';
|
||||
import { getUpdateInfo } from '../update/check';
|
||||
import { createUpdateService } from '../update/service';
|
||||
import { updateRoutes } from './update-routes';
|
||||
import { buildFullTraceDownload } from './log-export';
|
||||
import { loadNotificationsConfig, saveNotificationsConfig } from '../notifications/config';
|
||||
import type { NotificationManager } from '../notifications/manager';
|
||||
@@ -629,6 +632,8 @@ export async function initWebUI(
|
||||
tlsEnabled?: boolean;
|
||||
trustProxy?: string;
|
||||
stateBus?: StateBus;
|
||||
restart?: () => void;
|
||||
updateRoot?: string;
|
||||
} = {},
|
||||
): Promise<{ port: number; stop: () => Promise<void> }> {
|
||||
const host = listener.host || '127.0.0.1';
|
||||
@@ -747,6 +752,9 @@ export async function initWebUI(
|
||||
}
|
||||
|
||||
const app = new Hono();
|
||||
const shutdownStreams = new AbortController();
|
||||
const sseResponse = (...args: Parameters<typeof createSseResponse>) =>
|
||||
createSseResponse(args[0], args[1], shutdownStreams.signal);
|
||||
app.use('*', webuiSecurityHeaders);
|
||||
registerLoginRequestSecurity(app);
|
||||
const storageManagement = new StorageManagementService({
|
||||
@@ -1312,11 +1320,15 @@ export async function initWebUI(
|
||||
return c.json({ status: 'running' });
|
||||
});
|
||||
|
||||
// Advisory update check — compares the running build against the latest
|
||||
// GitHub stable release and links the user to it. Read-only: SnowLuma
|
||||
// never downloads or applies the update itself. `?force=1` bypasses the
|
||||
// server-side cache (the "立即检查" button). Never errors out — a failed
|
||||
// check returns `{ hasUpdate: false, error }` and the UI degrades quietly.
|
||||
const updater = await createUpdateService(
|
||||
listener.restart ? listener.updateRoot : undefined,
|
||||
APP_VERSION,
|
||||
);
|
||||
app.route(
|
||||
'/api/update',
|
||||
updateRoutes(updater, () => listener.restart?.()),
|
||||
);
|
||||
|
||||
app.get('/api/update/check', async (c) => {
|
||||
const force = c.req.query('force') === 'true' || c.req.query('force') === '1';
|
||||
return c.json(await getUpdateInfo(force));
|
||||
@@ -1397,7 +1409,7 @@ export async function initWebUI(
|
||||
|
||||
// ── System settings (WebUI listener) — Wave A1 ──
|
||||
// Listener-level changes (port/host/TLS) are persisted but apply only on the
|
||||
// next restart (no supervisor → no self-restart). The panel surfaces which
|
||||
// next restart. The panel surfaces which
|
||||
// fields are currently overridden by env so edits that won't take effect are
|
||||
// visible.
|
||||
const SYSTEM_CERT_PATH = path.join('config', 'cert.pem');
|
||||
@@ -1850,7 +1862,7 @@ export async function initWebUI(
|
||||
app.get('/api/logs/export/trace', (c) => {
|
||||
const exportedAt = new Date().toISOString();
|
||||
const download = buildFullTraceDownload(getLogSnapshot(), {
|
||||
version: currentVersion(),
|
||||
version: APP_VERSION,
|
||||
operatingSystem: os.platform(),
|
||||
architecture: os.arch(),
|
||||
nodeVersion: process.version,
|
||||
@@ -2344,6 +2356,7 @@ export async function initWebUI(
|
||||
port: finalPort,
|
||||
async stop() {
|
||||
connectionDiffLoop?.dispose();
|
||||
shutdownStreams.abort();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
listeningServer.close((err) => (err ? reject(err) : resolve()));
|
||||
});
|
||||
|
||||
@@ -32,7 +32,11 @@ export interface SseChannel {
|
||||
* previously hand-copied this ~40-line skeleton; a heartbeat-interval /
|
||||
* teardown-order / header change had to be kept in sync across all three.
|
||||
*/
|
||||
export function sseResponse(c: Context, start: (ch: SseChannel) => void): Response {
|
||||
export function sseResponse(
|
||||
c: Context,
|
||||
start: (ch: SseChannel) => void,
|
||||
shutdown?: AbortSignal,
|
||||
): Response {
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
@@ -91,6 +95,15 @@ export function sseResponse(c: Context, start: (ch: SseChannel) => void): Respon
|
||||
start(ch);
|
||||
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
shutdown?.addEventListener('abort', teardown, { once: true });
|
||||
cleanups.push(() => {
|
||||
c.req.raw.signal.removeEventListener('abort', teardown);
|
||||
shutdown?.removeEventListener('abort', teardown);
|
||||
});
|
||||
|
||||
if (shutdown?.aborted) {
|
||||
teardown();
|
||||
}
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Hono } from 'hono';
|
||||
import type { HttpBindings } from '@hono/node-server';
|
||||
import type { UpdateService } from '../update/service';
|
||||
|
||||
export function updateRoutes(service: UpdateService, restart: () => void) {
|
||||
const app = new Hono<{ Bindings: HttpBindings }>();
|
||||
app.get('/status', (c) => c.json(service.status()));
|
||||
app.post('/download', async (c) => {
|
||||
let body: unknown;
|
||||
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ message: '请求必须是 JSON 对象' }, 400);
|
||||
}
|
||||
|
||||
if (!body || typeof body !== 'object' || !('version' in body)) {
|
||||
return c.json({ message: '缺少更新版本' }, 400);
|
||||
}
|
||||
|
||||
try {
|
||||
service.start(body.version);
|
||||
return c.json(service.status(), 202);
|
||||
} catch (error) {
|
||||
return c.json({ message: error instanceof Error ? error.message : String(error) }, 409);
|
||||
}
|
||||
});
|
||||
app.post('/restart', (c) => {
|
||||
try {
|
||||
service.restart();
|
||||
c.env.outgoing.once('finish', restart);
|
||||
return c.json(service.status(), 202);
|
||||
} catch (error) {
|
||||
return c.json({ message: error instanceof Error ? error.message : String(error) }, 409);
|
||||
}
|
||||
});
|
||||
return app;
|
||||
}
|
||||
Reference in new issue
Block a user