mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
fix(updater): recover interrupted swaps reliably across deployments
- Ship one POSIX launcher that repairs an interrupted code swap before Node starts, install it atomically before the swap, and keep it out of CODE_ENTRIES so it always survives at the install root. - Restore from the in-progress task backup (state.json task.id -> backups/<id>) first, then the newest complete backup, so a leftover older backup never resurrects an obsolete build. - Add exact-window SIGKILL recovery tests, including the stale-backup case. - Gate Linux arm64 apply behind a capability check; add five-language copy and i18n labels for arm64, lock and unavailable errors. - Harden the L2 runner handshake and recheck runner health before exit.
This commit is contained in:
1 parent
699e606da5
commit
82b58dbd61
16 files changed
+699
-24
No files matched your search
@@ -182,12 +182,9 @@ jobs:
|
||||
cp "$runtime_root/bin/node" "$package_root/runtime/node"
|
||||
cp "$runtime_root/LICENSE" "$package_root/runtime/NODE-LICENSE"
|
||||
chmod 0755 "$package_root/runtime/node"
|
||||
cat > "$package_root/start-webspeak.sh" <<'LAUNCHER'
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
cd -- "$(dirname -- "$0")"
|
||||
exec "$PWD/runtime/node" "$PWD/dist/index.js"
|
||||
LAUNCHER
|
||||
# Ship the exact launcher the self-update installer and recovery
|
||||
# tests use; never maintain a second launcher body in the workflow.
|
||||
cp "$GITHUB_WORKSPACE/scripts/start-webspeak.sh" "$package_root/start-webspeak.sh"
|
||||
chmod 0755 "$package_root/start-webspeak.sh"
|
||||
|
||||
smoke_root="$RUNNER_TEMP/${package_name}-smoke"
|
||||
|
||||
+1
-1
@@ -117,7 +117,7 @@ Do not run `docker compose down -v`; it removes the `webspeak-data` volume, incl
|
||||
|
||||
Download the matching `windows-x64.zip`, `linux-x64.tar.gz`, or `linux-arm64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Extract it and run the included launcher. Packages include the Node.js runtime and production dependencies. Docker images support amd64/arm64.
|
||||
|
||||
Linux x64 release packages that match the official `build-release.yml` layout can be upgraded from the administration console. It checks the official GitHub Releases, refuses a package without a matching `SHA256SUMS.txt` entry, replaces only application code and restarts the process. `SHA256SUMS.txt` is an integrity checksum only, not a digital signature. `data/`, `config.json`, `certs/`, installed skins and plugins are preserved. Export a backup before starting. Windows release packages can check for versions, but console apply is disabled until it is verified on a real Windows install; download the new package and replace it manually. Linux arm64 shares the same code path as x64 but has not been exercised in this environment. Docker and source deployments cannot apply an update from the console.
|
||||
Linux x64 release packages that match the official `build-release.yml` layout can be upgraded from the administration console. It checks the official GitHub Releases, refuses a package without a matching `SHA256SUMS.txt` entry, replaces only application code and restarts the process. `SHA256SUMS.txt` is an integrity checksum only, not a digital signature. `data/`, `config.json`, `certs/`, installed skins and plugins are preserved. Export a backup before starting. Windows release packages can check for versions, but console apply is disabled until it is verified on a real Windows install; download the new package and replace it manually. Linux arm64 packages can be checked, but console apply is disabled because the in-place swap has not been verified on real arm64 hardware; download the new package and replace it manually. Docker and source deployments cannot apply an update from the console.
|
||||
|
||||
Android APKs for `arm64-v8a`, `armeabi-v7a`, and `x86_64` are also attached. They use debug signing for sideload testing; they are not Google Play packages, and real-device voice still needs validation.
|
||||
|
||||
|
||||
@@ -134,7 +134,7 @@ docker compose up -d
|
||||
|
||||
从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载与系统和架构匹配的 `windows-x64.zip`、`linux-x64.tar.gz` 或 `linux-arm64.tar.gz`,解压后运行对应启动脚本。发布包自带 Node.js 运行时和生产依赖。Docker 镜像支持 amd64/arm64。
|
||||
|
||||
Linux x64 发布包(已按官方 `build-release.yml` 产物形态验证)可以在管理控制台直接升级:控制台只读取官方 GitHub Releases,缺少匹配的 `SHA256SUMS.txt` 条目时拒绝安装,校验通过后仅替换程序代码并重启进程。`SHA256SUMS.txt` 只是 SHA-256 校验和,不是数字签名。`data/`、`config.json`、`certs/`、已安装的皮肤和插件都会保留。开始前建议先导出备份。Windows 发布包可以检查版本,但控制台应用更新尚未经真实 Windows 环境验证,因此已禁用,请下载新包后手动替换。Linux arm64 与 x64 使用同一代码路径,但未在本环境实测。Docker 和源码运行不能在控制台应用更新。
|
||||
Linux x64 发布包(已按官方 `build-release.yml` 产物形态验证)可以在管理控制台直接升级:控制台只读取官方 GitHub Releases,缺少匹配的 `SHA256SUMS.txt` 条目时拒绝安装,校验通过后仅替换程序代码并重启进程。`SHA256SUMS.txt` 只是 SHA-256 校验和,不是数字签名。`data/`、`config.json`、`certs/`、已安装的皮肤和插件都会保留。开始前建议先导出备份。Windows 发布包可以检查版本,但控制台应用更新尚未经真实 Windows 环境验证,因此已禁用,请下载新包后手动替换。Linux arm64 发布包可以检查版本,但由于原地替换尚未在真实 arm64 硬件验证,控制台应用已禁用;请下载新版发布包后手动替换。Docker 和源码运行不能在控制台应用更新。
|
||||
|
||||
Release 同时提供 Android `arm64-v8a`、`armeabi-v7a` 和 `x86_64` APK。它们使用 debug 签名,可手动侧载测试;不是 Google Play 发布包,Android 真机语音仍需验收。
|
||||
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs",
|
||||
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs",
|
||||
"verify": "npm test && npm run build && npm run web:build",
|
||||
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
|
||||
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
|
||||
|
||||
Executable
+118
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env sh
|
||||
# WebSpeak official release launcher.
|
||||
#
|
||||
# This file is the single source of truth for the launcher shipped in release
|
||||
# packages: .github/workflows/build-release.yml copies it verbatim, and the
|
||||
# self-update pre-swap installer copies the same file from the staged package.
|
||||
# Keep it a plain POSIX shell script: it must be able to repair an interrupted
|
||||
# code swap before Node (dist/index.js) is available at all.
|
||||
set -eu
|
||||
|
||||
cd -- "$(dirname -- "$0")"
|
||||
|
||||
# Mirrors src/index.ts: a custom data directory is the only supported override.
|
||||
data_dir="${WEBSPEAK_DATA_DIR:-$PWD/data}"
|
||||
backups="$data_dir/updates/backups"
|
||||
|
||||
# Only executable code is swapped by the updater. data/, config.json, certs/,
|
||||
# identities, skins and plugins are deliberately never listed here.
|
||||
code_entries="dist web/dist node_modules runtime package.json package-lock.json README.md LICENSE config.example.json"
|
||||
required_entries="dist/index.js web/dist/index.html node_modules package.json runtime/node"
|
||||
|
||||
code_missing() {
|
||||
for entry in $required_entries; do
|
||||
if [ ! -e "$entry" ]; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# A backup can only repair an install if it recorded a swap and still holds
|
||||
# every entry needed to boot. Partial/legacy backups must be skipped.
|
||||
backup_is_complete() {
|
||||
[ -f "$1/.webspeak-swap.json" ] || return 1
|
||||
for entry in $required_entries; do
|
||||
[ -e "$1/$entry" ] || return 1
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
restore_from_backup() {
|
||||
backup="$1"
|
||||
# Move whatever partial new code the interrupted swap left in the install
|
||||
# root aside, so a later restore never mistakes it for the old tree.
|
||||
for entry in $code_entries; do
|
||||
if [ -e "$entry" ] && [ -e "$backup/$entry" ]; then
|
||||
rejected="$backup/rejected/$entry"
|
||||
rejected_parent="${rejected%/*}"
|
||||
mkdir -p "$rejected_parent"
|
||||
if [ -e "$rejected" ]; then
|
||||
rm -rf -- "$entry"
|
||||
else
|
||||
mv -- "$entry" "$rejected"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
# Put back every complete entry recorded by the swap manifest.
|
||||
for entry in $code_entries; do
|
||||
if [ ! -e "$entry" ] && [ -e "$backup/$entry" ]; then
|
||||
parent="${entry%/*}"
|
||||
if [ "$parent" != "$entry" ]; then
|
||||
mkdir -p "$parent"
|
||||
fi
|
||||
mv -- "$backup/$entry" "$entry"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
if code_missing; then
|
||||
restore_backup=""
|
||||
|
||||
# The interrupted task is the source of truth: backups/<task.id> holds the
|
||||
# exact version that was running before the swap. A successful earlier
|
||||
# update leaves its backup behind (M1 does not clean it up), so picking the
|
||||
# first or alphabetically smallest backup can resurrect a much older build.
|
||||
state_file="$data_dir/updates/state.json"
|
||||
task_id=""
|
||||
if [ -f "$state_file" ]; then
|
||||
task_id=$(sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
|
||||
fi
|
||||
# Task ids are generated as upd_<base36>_<hex>. Reject anything else so a
|
||||
# tampered state.json cannot become a path traversal or a glob pattern.
|
||||
case "$task_id" in
|
||||
""|*[!A-Za-z0-9_-]*) task_id="" ;;
|
||||
esac
|
||||
if [ -n "$task_id" ]; then
|
||||
candidate="$backups/$task_id"
|
||||
if backup_is_complete "$candidate"; then
|
||||
restore_backup="$candidate"
|
||||
fi
|
||||
fi
|
||||
|
||||
# No usable task backup (e.g. state.json was lost): use the most recently
|
||||
# modified complete backup rather than whichever name happens to sort first.
|
||||
if [ -z "$restore_backup" ]; then
|
||||
for manifest in "$backups"/*/.webspeak-swap.json; do
|
||||
[ -f "$manifest" ] || continue
|
||||
backup="${manifest%/.webspeak-swap.json}"
|
||||
backup_is_complete "$backup" || continue
|
||||
if [ -z "$restore_backup" ] || [ "$backup" -nt "$restore_backup" ]; then
|
||||
restore_backup="$backup"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
if [ -z "$restore_backup" ]; then
|
||||
echo "WebSpeak update was interrupted and automatic recovery from $backups failed." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
restore_from_backup "$restore_backup"
|
||||
if code_missing; then
|
||||
echo "WebSpeak update was interrupted and automatic recovery from $restore_backup failed." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
exec "$PWD/runtime/node" "$PWD/dist/index.js"
|
||||
@@ -73,6 +73,15 @@ async function main() {
|
||||
updateService,
|
||||
restartAfterUpdate: () => {
|
||||
void (async () => {
|
||||
if (!updateService.runnerStillHealthy()) {
|
||||
// 202 already promised a restart, but the helper died before this
|
||||
// process left. Stay up and reconcile instead of reporting success
|
||||
// and silently abandoning the update.
|
||||
logger.warn("The restart runner is no longer healthy; keeping this process and reconciling the update state");
|
||||
try { updateService.initialize(); }
|
||||
catch (error) { logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Update state could not be reconciled"); }
|
||||
return;
|
||||
}
|
||||
logger.info("Stopping for scheduled update");
|
||||
try { await webServer?.stop(); }
|
||||
catch (error) { logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Web server did not stop cleanly for update"); }
|
||||
|
||||
@@ -17,7 +17,10 @@ export const CODE_ENTRIES = [
|
||||
"README.md",
|
||||
"LICENSE",
|
||||
"config.example.json",
|
||||
"start-webspeak.sh",
|
||||
// start-webspeak.sh is deliberately absent: the launcher must stay at the
|
||||
// install root for the whole swap so an interrupted update can still be
|
||||
// recovered by running ./start-webspeak.sh. It is installed atomically by
|
||||
// the updater before the runner swaps any code.
|
||||
"start-webspeak.cmd",
|
||||
] as const;
|
||||
|
||||
@@ -114,6 +117,26 @@ export function setCodeSwapCopyForTests(copy: CopyEntry | null): void {
|
||||
copyEntry = copy ?? defaultCopyEntry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test-only fault-injection seam. When the named directory exists, the swap
|
||||
* pauses in the exact window between "old code moved aside" and "new code
|
||||
* moved in" so a test can SIGKILL the runner. Production never sets this
|
||||
* variable; it is a local barrier directory, not a URL or network switch.
|
||||
*/
|
||||
const SWAP_BARRIER_ENV = "WEBSPEAK_TEST_SWAP_BARRIER_DIR";
|
||||
|
||||
function swapWindowBarrier(): void {
|
||||
const directory = process.env[SWAP_BARRIER_ENV];
|
||||
if (!directory || !existsSync(directory)) return;
|
||||
writeFileSync(path.join(directory, "swap-window-reached"), String(process.pid));
|
||||
const resume = path.join(directory, "resume");
|
||||
const deadline = Date.now() + 30_000;
|
||||
const waiter = new Int32Array(new SharedArrayBuffer(4));
|
||||
while (!existsSync(resume) && Date.now() < deadline) {
|
||||
Atomics.wait(waiter, 0, 0, 20);
|
||||
}
|
||||
}
|
||||
|
||||
function moveIfPresent(from: string, to: string): void {
|
||||
if (!existsSync(from)) return;
|
||||
mkdirSync(path.dirname(to), { recursive: true });
|
||||
@@ -183,6 +206,7 @@ export function swapCode(rootDir: string, stagedRoot: string, backupDir: string)
|
||||
movedToBackup.push(entry);
|
||||
writeSwapManifest(backupDir, movedToBackup);
|
||||
}
|
||||
swapWindowBarrier();
|
||||
for (const entry of CODE_ENTRIES) {
|
||||
if (!existsSync(path.join(stagedRoot, entry))) continue;
|
||||
moveIfPresent(path.join(stagedRoot, entry), path.join(rootDir, entry));
|
||||
|
||||
@@ -77,7 +77,8 @@ test("a complete packaged tree is detected as a release package", t => {
|
||||
const info = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "arm64" });
|
||||
assert.equal(info.mode, "release-package");
|
||||
assert.equal(info.assetKind, "linux-arm64");
|
||||
assert.equal(info.applyAllowed, true);
|
||||
assert.equal(info.applyAllowed, false);
|
||||
assert.equal(info.reasonCode, "LINUX_ARM64_APPLY_UNVERIFIED");
|
||||
assert.equal(detectDeployment({ rootDir: root, env: { WEBSPEAK_DEPLOYMENT_MODE: "docker" }, isDocker: false, platform: "linux" }).mode, "docker");
|
||||
});
|
||||
|
||||
@@ -129,6 +130,20 @@ test("windows release packages are visible but apply stays disabled", t => {
|
||||
assert.equal(linux.reasonCode, null);
|
||||
});
|
||||
|
||||
test("linux arm64 release packages are checkable but apply is gated off", t => {
|
||||
const root = releasePackageRoot(t);
|
||||
const arm64 = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "arm64" });
|
||||
assert.equal(arm64.mode, "release-package");
|
||||
assert.equal(arm64.assetKind, "linux-arm64");
|
||||
assert.equal(arm64.applyAllowed, false);
|
||||
assert.equal(arm64.reasonCode, "LINUX_ARM64_APPLY_UNVERIFIED");
|
||||
assert.equal(arm64.upgradePath, "release-package");
|
||||
|
||||
const x64 = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "x64" });
|
||||
assert.equal(x64.applyAllowed, true);
|
||||
assert.equal(x64.reasonCode, null);
|
||||
});
|
||||
|
||||
test("unsupported platforms are visible but cannot apply", t => {
|
||||
const root = releasePackageRoot(t);
|
||||
const info = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "s390x" });
|
||||
|
||||
@@ -45,6 +45,12 @@ export function detectDeployment(options: DeploymentDetectionOptions): Deploymen
|
||||
// real Windows release package. Report versions, but never fake an apply.
|
||||
applyAllowed = false;
|
||||
reasonCode = "WINDOWS_APPLY_UNVERIFIED";
|
||||
} else if (platform === "linux" && architecture === "arm64") {
|
||||
// arm64 packages are built and can be checked, but the in-place swap has
|
||||
// only been exercised on x64. Gate on the detected capability itself so
|
||||
// "unverified" is never rendered as "can apply" in the UI.
|
||||
applyAllowed = false;
|
||||
reasonCode = "LINUX_ARM64_APPLY_UNVERIFIED";
|
||||
}
|
||||
return {
|
||||
mode,
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { createServer } from "node:net";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { UpdateService } from "./update-service.js";
|
||||
|
||||
const SOURCE_DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO_ROOT = path.resolve(SOURCE_DIR, "..", "..");
|
||||
const LAUNCHER_SOURCE = path.join(REPO_ROOT, "scripts", "start-webspeak.sh");
|
||||
const RUNNER_SOURCE = path.join(SOURCE_DIR, "restart-runner.ts");
|
||||
const TASK_ID = "upd_sigkill_window";
|
||||
|
||||
const logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
|
||||
|
||||
const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
|
||||
|
||||
async function availablePort(): Promise<number> {
|
||||
const server = createServer();
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address !== "string");
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
return address.port;
|
||||
}
|
||||
|
||||
async function waitFor(check: () => boolean | Promise<boolean>, message: string, timeoutMs = 15_000): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (!(await check())) {
|
||||
if (Date.now() > deadline) throw new Error(message);
|
||||
await sleep(25);
|
||||
}
|
||||
}
|
||||
|
||||
async function healthVersion(port: number): Promise<string | null> {
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(1_000) });
|
||||
if (!response.ok) return null;
|
||||
const body = await response.json() as { status?: string; version?: string };
|
||||
return body.status === "ok" ? body.version ?? null : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function processAlive(pid: number | undefined): boolean {
|
||||
if (!pid || pid <= 0) return false;
|
||||
try { process.kill(pid, 0); return true; }
|
||||
catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
|
||||
}
|
||||
|
||||
function stop(child: ChildProcess | undefined): void {
|
||||
if (!child || !processAlive(child.pid)) return;
|
||||
try { child.kill("SIGKILL"); } catch { /* Already gone. */ }
|
||||
}
|
||||
|
||||
/** The stub reports the version from package.json, as the real app does. */
|
||||
function appScript(): string {
|
||||
return `const http = require("node:http");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const config = JSON.parse(fs.readFileSync(path.join(process.cwd(), "config.json"), "utf8"));
|
||||
const version = JSON.parse(fs.readFileSync(path.join(process.cwd(), "package.json"), "utf8")).version;
|
||||
http.createServer((request, response) => {
|
||||
if (request.url === "/api/health") {
|
||||
response.setHeader("content-type", "application/json");
|
||||
response.end(JSON.stringify({ status: "ok", version }));
|
||||
return;
|
||||
}
|
||||
response.statusCode = 404;
|
||||
response.end();
|
||||
}).listen(config.port, "127.0.0.1", () => fs.writeFileSync(config.startedFile, version));
|
||||
`;
|
||||
}
|
||||
|
||||
interface Fixture {
|
||||
directory: string;
|
||||
rootDir: string;
|
||||
dataDir: string;
|
||||
stagedRoot: string;
|
||||
backupDir: string;
|
||||
barrierDir: string;
|
||||
port: number;
|
||||
markerFiles: Record<string, string>;
|
||||
}
|
||||
|
||||
function buildFixture(t: TestContext, port: number, withStaleBackup = false): Fixture {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-swap-recovery-"));
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
const rootDir = path.join(directory, "app");
|
||||
const dataDir = path.join(rootDir, "data");
|
||||
const updatesDir = path.join(dataDir, "updates");
|
||||
const stagedRoot = path.join(updatesDir, "tasks", TASK_ID, "staged");
|
||||
const backupDir = path.join(updatesDir, "backups", TASK_ID);
|
||||
const barrierDir = path.join(directory, "barrier");
|
||||
|
||||
for (const relative of ["dist", "web/dist", "node_modules", "runtime"]) {
|
||||
mkdirSync(path.join(rootDir, relative), { recursive: true });
|
||||
}
|
||||
writeFileSync(path.join(rootDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.3.2" }));
|
||||
writeFileSync(path.join(rootDir, "package-lock.json"), "{}");
|
||||
writeFileSync(path.join(rootDir, "README.md"), "old readme");
|
||||
writeFileSync(path.join(rootDir, "LICENSE"), "old license");
|
||||
writeFileSync(path.join(rootDir, "config.example.json"), "{}");
|
||||
writeFileSync(path.join(rootDir, "web", "dist", "index.html"), "<!doctype html>\n");
|
||||
writeFileSync(path.join(rootDir, "node_modules", ".keep"), "");
|
||||
writeFileSync(path.join(rootDir, "dist", "index.js"), appScript());
|
||||
copyFileSync(process.execPath, path.join(rootDir, "runtime", "node"));
|
||||
chmodSync(path.join(rootDir, "runtime", "node"), 0o755);
|
||||
// This is the same file CI ships and applyUpdate installs before the swap.
|
||||
copyFileSync(LAUNCHER_SOURCE, path.join(rootDir, "start-webspeak.sh"));
|
||||
chmodSync(path.join(rootDir, "start-webspeak.sh"), 0o755);
|
||||
|
||||
const markerFiles: Record<string, string> = {
|
||||
config: path.join(rootDir, "config.json"),
|
||||
database: path.join(dataDir, "webspeak.db"),
|
||||
identity: path.join(dataDir, "identity.key"),
|
||||
cert: path.join(rootDir, "certs", "cert.pem"),
|
||||
skin: path.join(dataDir, "skins", "skin.json"),
|
||||
plugin: path.join(dataDir, "plugins", "plugin.json"),
|
||||
};
|
||||
mkdirSync(path.dirname(markerFiles.database), { recursive: true });
|
||||
mkdirSync(path.dirname(markerFiles.identity), { recursive: true });
|
||||
mkdirSync(path.dirname(markerFiles.cert), { recursive: true });
|
||||
mkdirSync(path.dirname(markerFiles.skin), { recursive: true });
|
||||
mkdirSync(path.dirname(markerFiles.plugin), { recursive: true });
|
||||
writeFileSync(markerFiles.config, JSON.stringify({ port, startedFile: path.join(directory, "started.txt") }));
|
||||
for (const [key, value] of Object.entries(markerFiles)) {
|
||||
if (key !== "config") writeFileSync(value, `${key} preserved`);
|
||||
}
|
||||
|
||||
mkdirSync(updatesDir, { recursive: true });
|
||||
mkdirSync(stagedRoot, { recursive: true });
|
||||
mkdirSync(path.join(stagedRoot, "dist"), { recursive: true });
|
||||
mkdirSync(path.join(stagedRoot, "web", "dist"), { recursive: true });
|
||||
mkdirSync(path.join(stagedRoot, "node_modules"), { recursive: true });
|
||||
mkdirSync(path.join(stagedRoot, "runtime"), { recursive: true });
|
||||
writeFileSync(path.join(stagedRoot, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.4.0" }));
|
||||
writeFileSync(path.join(stagedRoot, "package-lock.json"), "{}");
|
||||
writeFileSync(path.join(stagedRoot, "README.md"), "new readme");
|
||||
writeFileSync(path.join(stagedRoot, "LICENSE"), "new license");
|
||||
writeFileSync(path.join(stagedRoot, "config.example.json"), "{}");
|
||||
writeFileSync(path.join(stagedRoot, "dist", "index.js"), "// new code marker\n");
|
||||
writeFileSync(path.join(stagedRoot, "web", "dist", "index.html"), "<!doctype html>\n");
|
||||
writeFileSync(path.join(stagedRoot, "node_modules", ".keep"), "");
|
||||
writeFileSync(path.join(stagedRoot, "runtime", "node"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
|
||||
copyFileSync(LAUNCHER_SOURCE, path.join(stagedRoot, "start-webspeak.sh"));
|
||||
|
||||
writeFileSync(path.join(updatesDir, "state.json"), JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
task: {
|
||||
id: TASK_ID, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
},
|
||||
}));
|
||||
writeFileSync(path.join(updatesDir, "update.lock"), JSON.stringify({ pid: 0, taskId: TASK_ID, createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
writeFileSync(path.join(updatesDir, "plan.json"), JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
taskId: TASK_ID,
|
||||
rootDir,
|
||||
statePath: path.join(updatesDir, "state.json"),
|
||||
lockPath: path.join(updatesDir, "update.lock"),
|
||||
stagedRoot,
|
||||
backupDir,
|
||||
fromVersion: "0.3.2",
|
||||
targetVersion: "0.4.0",
|
||||
nodePath: process.execPath,
|
||||
appEntry: path.join(rootDir, "dist", "index.js"),
|
||||
health: { protocol: "http", port, path: "/api/health" },
|
||||
waitForPid: null,
|
||||
parentTimeoutMs: 2_000,
|
||||
healthTimeoutMs: 300,
|
||||
pollIntervalMs: 50,
|
||||
appLogPath: path.join(updatesDir, "app.log"),
|
||||
}, null, 2));
|
||||
if (withStaleBackup) {
|
||||
// A complete backup from an earlier, already successful update. Its name
|
||||
// sorts before the in-progress task's id, so the old "first complete
|
||||
// backup wins" launcher logic would wrongly restore this older build.
|
||||
const staleDir = path.join(updatesDir, "backups", "aaa_stale_backup");
|
||||
for (const relative of ["dist", "web/dist", "node_modules", "runtime"]) {
|
||||
mkdirSync(path.join(staleDir, relative), { recursive: true });
|
||||
}
|
||||
writeFileSync(path.join(staleDir, "dist", "index.js"), appScript());
|
||||
writeFileSync(path.join(staleDir, "web", "dist", "index.html"), "<!doctype html>\n");
|
||||
writeFileSync(path.join(staleDir, "node_modules", ".keep"), "");
|
||||
writeFileSync(path.join(staleDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.1.0" }));
|
||||
writeFileSync(path.join(staleDir, "package-lock.json"), "{}");
|
||||
writeFileSync(path.join(staleDir, "README.md"), "stale readme");
|
||||
writeFileSync(path.join(staleDir, "LICENSE"), "stale license");
|
||||
writeFileSync(path.join(staleDir, "config.example.json"), "{}");
|
||||
copyFileSync(process.execPath, path.join(staleDir, "runtime", "node"));
|
||||
chmodSync(path.join(staleDir, "runtime", "node"), 0o755);
|
||||
writeFileSync(path.join(staleDir, ".webspeak-swap.json"), JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
entries: ["dist", "web/dist", "node_modules", "runtime", "package.json", "package-lock.json", "README.md", "LICENSE", "config.example.json"],
|
||||
}, null, 2));
|
||||
}
|
||||
|
||||
mkdirSync(barrierDir, { recursive: true });
|
||||
|
||||
return { directory, rootDir, dataDir, stagedRoot, backupDir, barrierDir, port, markerFiles };
|
||||
}
|
||||
|
||||
test(
|
||||
"SIGKILL in the exact swap window is recovered by the official launcher with data intact",
|
||||
{ timeout: 40_000 },
|
||||
async t => {
|
||||
const port = await availablePort();
|
||||
const fixture = buildFixture(t, port);
|
||||
let runner: ChildProcess | undefined;
|
||||
let app: ChildProcess | undefined;
|
||||
t.after(() => { stop(app); stop(runner); });
|
||||
|
||||
let runnerOutput = "";
|
||||
runner = spawn(process.execPath, ["--import", "tsx", RUNNER_SOURCE, path.join(fixture.dataDir, "updates", "plan.json")], {
|
||||
cwd: REPO_ROOT,
|
||||
env: { ...process.env, WEBSPEAK_TEST_SWAP_BARRIER_DIR: fixture.barrierDir },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
runner.stdout?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
|
||||
runner.stderr?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
|
||||
await waitFor(
|
||||
() => existsSync(path.join(fixture.barrierDir, "swap-window-reached")),
|
||||
`runner never reached the exact swap window: ${runnerOutput}`,
|
||||
);
|
||||
|
||||
// Precisely the failure state: old dist moved aside, new dist not yet in.
|
||||
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), false);
|
||||
assert.equal(existsSync(path.join(fixture.backupDir, "dist", "index.js")), true);
|
||||
assert.equal(existsSync(path.join(fixture.rootDir, "start-webspeak.sh")), true, "official launcher survived the swap");
|
||||
|
||||
stop(runner);
|
||||
await waitFor(() => !processAlive(runner?.pid), "runner did not die after SIGKILL", 5_000);
|
||||
|
||||
// Restart through the shipped launcher itself, not a harness wrapper.
|
||||
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
|
||||
cwd: fixture.rootDir,
|
||||
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
|
||||
stdio: "ignore",
|
||||
});
|
||||
await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), "official launcher did not restore a healthy install");
|
||||
|
||||
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), appScript());
|
||||
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
|
||||
assert.deepEqual(JSON.parse(readFileSync(fixture.markerFiles.config, "utf8")), { port, startedFile: path.join(fixture.directory, "started.txt") });
|
||||
for (const [key, file] of Object.entries(fixture.markerFiles)) {
|
||||
if (key !== "config") assert.equal(readFileSync(file, "utf8"), `${key} preserved`, `${key} survived recovery`);
|
||||
}
|
||||
assert.equal(existsSync(path.join(fixture.backupDir, "rejected", "dist")), false, "no partial new code in the install root");
|
||||
|
||||
// Once Node is up, the existing initialize() path records the real failure.
|
||||
stop(app);
|
||||
await waitFor(() => !processAlive(app?.pid), "app did not stop", 5_000);
|
||||
const service = new UpdateService({
|
||||
rootDir: fixture.rootDir,
|
||||
dataDir: fixture.dataDir,
|
||||
currentVersion: "0.3.2",
|
||||
logger,
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
env: {},
|
||||
isDocker: false,
|
||||
});
|
||||
service.initialize();
|
||||
const status = service.getStatus();
|
||||
assert.equal(status.task?.status, "failed");
|
||||
assert.equal(status.task?.errorCode, "UPDATE_INTERRUPTED");
|
||||
assert.equal(status.task?.rolledBack, true);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
"recovery prefers the in-progress task backup over an older lexicographically-first backup",
|
||||
{ timeout: 40_000 },
|
||||
async t => {
|
||||
const port = await availablePort();
|
||||
const fixture = buildFixture(t, port, true);
|
||||
const staleDir = path.join(fixture.dataDir, "updates", "backups", "aaa_stale_backup");
|
||||
let runner: ChildProcess | undefined;
|
||||
let app: ChildProcess | undefined;
|
||||
t.after(() => { stop(app); stop(runner); });
|
||||
|
||||
let runnerOutput = "";
|
||||
runner = spawn(process.execPath, ["--import", "tsx", RUNNER_SOURCE, path.join(fixture.dataDir, "updates", "plan.json")], {
|
||||
cwd: REPO_ROOT,
|
||||
env: { ...process.env, WEBSPEAK_TEST_SWAP_BARRIER_DIR: fixture.barrierDir },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
runner.stdout?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
|
||||
runner.stderr?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
|
||||
await waitFor(
|
||||
() => existsSync(path.join(fixture.barrierDir, "swap-window-reached")),
|
||||
`runner never reached the exact swap window: ${runnerOutput}`,
|
||||
);
|
||||
|
||||
// Old code is only in the current task's backup; the stale backup is
|
||||
// untouched and still sitting under a lexicographically earlier name.
|
||||
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), false);
|
||||
assert.equal(existsSync(path.join(fixture.backupDir, "dist", "index.js")), true);
|
||||
assert.equal(existsSync(path.join(staleDir, "dist", "index.js")), true);
|
||||
|
||||
stop(runner);
|
||||
await waitFor(() => !processAlive(runner?.pid), "runner did not die after SIGKILL", 5_000);
|
||||
|
||||
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
|
||||
cwd: fixture.rootDir,
|
||||
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
|
||||
stdio: "ignore",
|
||||
});
|
||||
await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), "launcher did not restore the current task's 0.3.2 build");
|
||||
|
||||
// The current task's version, not the stale 0.1.0 build, is back in place.
|
||||
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
|
||||
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), appScript());
|
||||
assert.equal(JSON.parse(readFileSync(path.join(staleDir, "package.json"), "utf8")).version, "0.1.0", "stale backup was not consumed");
|
||||
assert.equal(existsSync(path.join(staleDir, "dist", "index.js")), true, "stale backup is still intact");
|
||||
|
||||
assert.deepEqual(JSON.parse(readFileSync(fixture.markerFiles.config, "utf8")), { port, startedFile: path.join(fixture.directory, "started.txt") });
|
||||
for (const [key, file] of Object.entries(fixture.markerFiles)) {
|
||||
if (key !== "config") assert.equal(readFileSync(file, "utf8"), `${key} preserved`, `${key} survived recovery`);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -573,3 +573,92 @@ test("the real restart runner starts with every runtime module and survives the
|
||||
const log = readFileSync(path.join(updatesDir, "runner.log"), "utf8");
|
||||
assert.ok(!log.includes("ERR_MODULE_NOT_FOUND"), `runner log has no missing module: ${log}`);
|
||||
});
|
||||
|
||||
test("the runner handshake requires lock takeover and a later death is caught before exit", async t => {
|
||||
const directory = workspace(t);
|
||||
const compiled = path.join(directory, "compiled");
|
||||
await compileRunnerSources(compiled);
|
||||
const rootDir = path.join(directory, "app");
|
||||
createPackageFiles(rootDir, "0.3.2");
|
||||
const dataDir = path.join(directory, "data");
|
||||
const updatesDir = path.join(dataDir, "updates");
|
||||
mkdirSync(updatesDir, { recursive: true });
|
||||
const taskId = "upd_handshake";
|
||||
const statePath = path.join(updatesDir, "state.json");
|
||||
const lockPath = path.join(updatesDir, "update.lock");
|
||||
const planPath = path.join(updatesDir, "plan.json");
|
||||
const makeTask = () => ({
|
||||
id: taskId, status: "restarting" as const, fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
});
|
||||
const writePlan = () => writeFileSync(planPath, JSON.stringify({
|
||||
schemaVersion: 1, taskId, rootDir, statePath, lockPath,
|
||||
stagedRoot: path.join(updatesDir, "staged"),
|
||||
backupDir: path.join(updatesDir, "backups", taskId),
|
||||
fromVersion: "0.3.2", targetVersion: "0.4.0", nodePath: process.execPath,
|
||||
appEntry: path.join(rootDir, "dist", "index.js"),
|
||||
health: { protocol: "http", port: 39998, path: "/api/health" },
|
||||
waitForPid: process.pid, parentTimeoutMs: 60_000, healthTimeoutMs: 100, pollIntervalMs: 50,
|
||||
appLogPath: path.join(updatesDir, "app.log"),
|
||||
}, null, 2));
|
||||
writeUpdateState(statePath, { schemaVersion: 1, task: makeTask() });
|
||||
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
writePlan();
|
||||
|
||||
const service = new UpdateService({
|
||||
rootDir, dataDir, currentVersion: "0.3.2", logger, platform: "linux", architecture: "x64", env: {}, isDocker: false,
|
||||
fetch: fakeFetch([], new Map()), runnerSourceDir: compiled, runnerStartupTimeoutMs: 1_500,
|
||||
});
|
||||
const pid = await service.launchRunner(planPath, path.join(updatesDir, "runner"));
|
||||
t.after(() => stopProcess(pid));
|
||||
assert.equal(service.runnerStillHealthy(), true, "runner owns the lock right after the handshake");
|
||||
|
||||
await stopProcess(pid);
|
||||
assert.equal(service.runnerStillHealthy(), false, "a runner that died after 202 is caught before process.exit");
|
||||
});
|
||||
|
||||
test("a runner that cannot take over the lock never passes the handshake", async t => {
|
||||
const directory = workspace(t);
|
||||
const compiled = path.join(directory, "compiled");
|
||||
await compileRunnerSources(compiled);
|
||||
const rootDir = path.join(directory, "app");
|
||||
createPackageFiles(rootDir, "0.3.2");
|
||||
const dataDir = path.join(directory, "data");
|
||||
const updatesDir = path.join(dataDir, "updates");
|
||||
mkdirSync(updatesDir, { recursive: true });
|
||||
const taskId = "upd_bad_lock";
|
||||
const statePath = path.join(updatesDir, "state.json");
|
||||
const lockPath = path.join(updatesDir, "update.lock");
|
||||
const planPath = path.join(updatesDir, "plan.json");
|
||||
writeUpdateState(statePath, {
|
||||
schemaVersion: 1,
|
||||
task: {
|
||||
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
},
|
||||
});
|
||||
// A different task owns the lock: the runner must refuse to steal it.
|
||||
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, taskId: "upd_other", createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
writeFileSync(planPath, JSON.stringify({
|
||||
schemaVersion: 1, taskId, rootDir, statePath, lockPath,
|
||||
stagedRoot: path.join(updatesDir, "staged"),
|
||||
backupDir: path.join(updatesDir, "backups", taskId),
|
||||
fromVersion: "0.3.2", targetVersion: "0.4.0", nodePath: process.execPath,
|
||||
appEntry: path.join(rootDir, "dist", "index.js"),
|
||||
health: { protocol: "http", port: 39997, path: "/api/health" },
|
||||
waitForPid: process.pid, parentTimeoutMs: 60_000, healthTimeoutMs: 100, pollIntervalMs: 50,
|
||||
appLogPath: path.join(updatesDir, "app.log"),
|
||||
}, null, 2));
|
||||
|
||||
const service = new UpdateService({
|
||||
rootDir, dataDir, currentVersion: "0.3.2", logger, platform: "linux", architecture: "x64", env: {}, isDocker: false,
|
||||
fetch: fakeFetch([], new Map()), runnerSourceDir: compiled, runnerStartupTimeoutMs: 1_500,
|
||||
});
|
||||
await assert.rejects(
|
||||
service.launchRunner(planPath, path.join(updatesDir, "runner")),
|
||||
updateErrorCode("UPDATE_RUNNER_FAILED"),
|
||||
);
|
||||
assert.equal(service.runnerStillHealthy(), true, "no runner was recorded, so the guard is a no-op");
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import {
|
||||
closeSync, copyFileSync, createWriteStream, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync,
|
||||
chmodSync, closeSync, copyFileSync, createWriteStream, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync,
|
||||
} from "node:fs";
|
||||
import { rename, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
@@ -82,6 +82,29 @@ export interface UpdateServiceOptions {
|
||||
const CHECKSUM_LIMIT = 1024 * 1024;
|
||||
const DOWNLOAD_LIMIT = 512 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Install the recovery-capable launcher before the runner tears down dist/
|
||||
* and runtime/. The staged package ships the canonical script (same file CI
|
||||
* generates), so even the first upgrade from the old four-line launcher has
|
||||
* a self-healing ./start-webspeak.sh on the official path at all times.
|
||||
*/
|
||||
function installRecoveryLauncher(rootDir: string, stagedRoot: string): void {
|
||||
const source = path.join(stagedRoot, "start-webspeak.sh");
|
||||
// Source installs and hand-built test packages have no launcher; real
|
||||
// release packages always do.
|
||||
if (!existsSync(source)) return;
|
||||
const target = path.join(rootDir, "start-webspeak.sh");
|
||||
const temporary = `${target}.${process.pid}.tmp`;
|
||||
try {
|
||||
copyFileSync(source, temporary);
|
||||
chmodSync(temporary, 0o755);
|
||||
renameSync(temporary, target);
|
||||
} catch (error) {
|
||||
try { rmSync(temporary, { force: true }); } catch { /* Preserve the original error. */ }
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every local module the restart runner imports at runtime. The runner is
|
||||
* copied into an isolated directory under data/updates, so any omission here
|
||||
@@ -107,6 +130,7 @@ export class UpdateService {
|
||||
private state: PersistedUpdateState = emptyUpdateState();
|
||||
private applying = false;
|
||||
private releaseLock: (() => void) | null = null;
|
||||
private runnerPid: number | null = null;
|
||||
|
||||
constructor(private readonly options: UpdateServiceOptions) {
|
||||
this.deployment = detectDeployment({
|
||||
@@ -253,6 +277,7 @@ export class UpdateService {
|
||||
throw new UpdateError("UPDATE_IN_PROGRESS", "Another update task is already running.", 409);
|
||||
}
|
||||
this.applying = true;
|
||||
this.runnerPid = null;
|
||||
const taskId = `upd_${Date.now().toString(36)}_${randomBytes(6).toString("hex")}`;
|
||||
const startedAt = this.now().toISOString();
|
||||
const task: UpdateTaskView = {
|
||||
@@ -317,6 +342,7 @@ export class UpdateService {
|
||||
throw error;
|
||||
}
|
||||
this.finishStep(task, "stage", "succeeded");
|
||||
installRecoveryLauncher(this.options.rootDir, stagedRoot);
|
||||
const planPath = path.join(taskDirectory, "plan.json");
|
||||
const runnerDirectory = path.join(taskDirectory, "runner");
|
||||
const plan = {
|
||||
@@ -375,6 +401,7 @@ export class UpdateService {
|
||||
try { rmSync(taskDirectory, { recursive: true, force: true }); } catch { /* Best effort. */ }
|
||||
this.releaseLock?.();
|
||||
this.releaseLock = null;
|
||||
this.runnerPid = null;
|
||||
// A runner that died after taking over leaves its own pid in the lock.
|
||||
// Only a provably dead owner is removed; a live lock is left alone.
|
||||
clearStaleUpdateLock(this.lockPath);
|
||||
@@ -479,10 +506,11 @@ export class UpdateService {
|
||||
|
||||
/**
|
||||
* Copy the runner and all of its runtime imports into an isolated directory,
|
||||
* start it detached, and wait briefly to prove it did not die on startup.
|
||||
* start it detached, and wait until it has taken over the update lock.
|
||||
* A successful spawn alone is not enough: Node resolves the whole ESM module
|
||||
* graph before executing the helper, so a missing file only shows up as an
|
||||
* early exit. Returning here means the helper is actually running.
|
||||
* early exit. Ownership of the lock also proves the runner is alive after
|
||||
* its startup window and really controls this task before we promise 202.
|
||||
*/
|
||||
async launchRunner(planPath: string, runnerDirectory: string): Promise<number> {
|
||||
const sourceDirectory = this.options.runnerSourceDir ?? path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -507,7 +535,7 @@ export class UpdateService {
|
||||
nodePath = process.execPath;
|
||||
}
|
||||
const log = path.join(path.dirname(planPath), "runner.log");
|
||||
const graceMs = this.options.runnerStartupTimeoutMs ?? 750;
|
||||
const graceMs = this.options.runnerStartupTimeoutMs ?? 1_500;
|
||||
return new Promise<number>((resolve, reject) => {
|
||||
let child: ChildProcess;
|
||||
let fd: number | null = null;
|
||||
@@ -527,11 +555,11 @@ export class UpdateService {
|
||||
if (fd !== null) closeSync(fd);
|
||||
}
|
||||
let settled = false;
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
let poll: NodeJS.Timeout | undefined;
|
||||
const fail = (message: string) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
if (poll) clearInterval(poll);
|
||||
reject(new UpdateError("UPDATE_RUNNER_FAILED", message, 500));
|
||||
};
|
||||
child.once("error", (error) => fail(error.message));
|
||||
@@ -540,18 +568,54 @@ export class UpdateService {
|
||||
});
|
||||
child.once("spawn", () => {
|
||||
child.unref();
|
||||
timer = setTimeout(() => {
|
||||
const deadline = Date.now() + graceMs;
|
||||
poll = setInterval(() => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (!child.pid) {
|
||||
reject(new UpdateError("UPDATE_RUNNER_FAILED", "The restart runner did not report a process id.", 500));
|
||||
const pid = child.pid;
|
||||
if (!pid) {
|
||||
fail("The restart runner did not report a process id.");
|
||||
return;
|
||||
}
|
||||
resolve(child.pid);
|
||||
}, graceMs);
|
||||
if (Date.now() > deadline) {
|
||||
fail("The restart runner did not take over the update lock in time.");
|
||||
return;
|
||||
}
|
||||
if (!pidIsAlive(pid) || !lockOwnedBy(this.lockPath, pid)) return;
|
||||
settled = true;
|
||||
if (poll) clearInterval(poll);
|
||||
this.runnerPid = pid;
|
||||
resolve(pid);
|
||||
}, 25);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Last chance guard for the promise made with 202. The parent still exists
|
||||
* for a short window after the handshake, so re-check that the runner is
|
||||
* alive and still owns the lock before the caller exits the process.
|
||||
*/
|
||||
runnerStillHealthy(): boolean {
|
||||
const pid = this.runnerPid;
|
||||
// No runner was launched through this instance (source install, mocked
|
||||
// route test): there is nothing extra to verify.
|
||||
if (pid === null) return true;
|
||||
return pidIsAlive(pid) && lockOwnedBy(this.lockPath, pid);
|
||||
}
|
||||
}
|
||||
|
||||
function pidIsAlive(pid: number): boolean {
|
||||
try { process.kill(pid, 0); return true; }
|
||||
catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
|
||||
}
|
||||
|
||||
function lockOwnedBy(lockPath: string, pid: number): boolean {
|
||||
try {
|
||||
const record = JSON.parse(readFileSync(lockPath, "utf8")) as { pid?: unknown };
|
||||
return record?.pid === pid;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function repositoryParts(repository: string | undefined): [string, string] {
|
||||
|
||||
@@ -352,6 +352,7 @@ function blockedReasonText(code: string | null) {
|
||||
case 'PLATFORM_UNSUPPORTED': return tr('updateBlockedPlatform');
|
||||
case 'ARCH_UNSUPPORTED': return tr('updateBlockedArch');
|
||||
case 'WINDOWS_APPLY_UNVERIFIED': return tr('updateBlockedWindows');
|
||||
case 'LINUX_ARM64_APPLY_UNVERIFIED': return tr('updateBlockedArm64');
|
||||
case 'UPDATE_ASSET_UNAVAILABLE': return tr('updateAssetMissing');
|
||||
case 'UPDATE_CHECKSUM_MISSING': return tr('updateChecksumMissing');
|
||||
default: return tr('updateBlockedUnavailable');
|
||||
|
||||
@@ -57,7 +57,8 @@ const errorLabels: Record<string, AdminTranslationKey> = {
|
||||
UPDATE_ARCHIVE_UNSAFE: "updateErrorArchive", UPDATE_ARCHIVE_INVALID: "updateErrorArchive", UPDATE_ARCHIVE_LIMIT: "updateErrorArchive", UPDATE_ARCHIVE_UNSUPPORTED: "updateErrorArchive",
|
||||
UPDATE_PACKAGE_INVALID: "updateErrorPackage", UPDATE_DOWNLOAD_FAILED: "updateErrorDownload", UPDATE_DOWNLOAD_TOO_LARGE: "updateErrorDownload",
|
||||
UPDATE_FAILED: "updateErrorApply", UPDATE_ROLLBACK_FAILED: "updateErrorRollbackFailed", UPDATE_INTERRUPTED: "updateErrorInterrupted",
|
||||
UPDATE_SWAP_FAILED: "updateErrorSwap",
|
||||
UPDATE_SWAP_FAILED: "updateErrorSwap", UPDATE_LOCK_FAILED: "updateErrorLockFailed",
|
||||
UPDATE_UNAVAILABLE: "updateErrorUnavailable", UPDATE_RESTART_UNAVAILABLE: "updateErrorUnavailable",
|
||||
UPDATE_HEALTH_CHECK_FAILED: "updateErrorApply", UPDATE_ROLLBACK_HEALTH_FAILED: "updateErrorGeneric",
|
||||
UPDATE_RESTART_FAILED: "updateErrorGeneric", UPDATE_RESTART_TIMEOUT: "updateErrorGeneric", UPDATE_PLAN_INVALID: "updateErrorGeneric",
|
||||
UPDATE_NOT_SUPPORTED: "updateErrorGeneric", UPDATE_RELEASE_UNAVAILABLE: "updateErrorGeneric", UPDATE_ASSET_UNAVAILABLE: "updateErrorGeneric",
|
||||
|
||||
@@ -23,6 +23,7 @@ const zh = {
|
||||
updateBlockedSource: "源码运行没有捆绑运行时,控制台无法安全切换版本。请拉取源码后自行构建(npm ci && npm run build && npm run web:build),或改用发布包/Docker Compose。",
|
||||
updateBlockedPlatform: "当前平台没有官方发布包,只能检查版本。", updateBlockedArch: "当前架构没有官方发布包,只能检查版本。",
|
||||
updateBlockedWindows: "Windows 发布包的控制台更新尚未在真实 Windows 环境验证,已禁用;请下载新版发布包后手动替换。",
|
||||
updateBlockedArm64: "Linux arm64 发布包的控制台更新尚未在真实硬件实测,已禁用;请下载新版发布包后手动替换。",
|
||||
updateChecksumNotice: "SHA256SUMS.txt 只用于 SHA-256 完整性校验和,不是数字签名。",
|
||||
updateBlockedUnavailable: "此实例未启用控制台更新。", updateTaskTitle: "更新任务",
|
||||
updateStatusDownloading: "正在下载", updateStatusVerifying: "正在校验", updateStatusExtracting: "正在解包", updateStatusStaging: "正在暂存",
|
||||
@@ -35,6 +36,7 @@ const zh = {
|
||||
updateErrorRollbackFailed: "更新失败且自动回滚也失败。请按备份手动恢复上一版本。",
|
||||
updateErrorSwap: "替换程序文件失败,已尝试恢复上一版本;请查看日志。",
|
||||
updateErrorInProgress: "已有更新任务正在进行。", updateErrorGeneric: "更新未能完成,请查看日志。", updateStartedEvent: "已开始更新",
|
||||
updateErrorLockFailed: "无法接管更新锁,请确认没有其他更新任务在运行后重试。", updateErrorUnavailable: "此实例未启用控制台更新。",
|
||||
adminWsOverviewTitle: "WebSpeak 管理服务已就绪", adminWsOverviewLead: "先管理实例接入与访客体验;需要管理 TS 服务时,再按需配置独立连接。",
|
||||
adminWsManageLead: "接入策略、站点公告、语音传输、皮肤商店和浏览器会话。",
|
||||
adminTsManageLead: "服务器设置、频道、在线成员、服务器组和封禁。需单独配置 Query 凭据,常规语音连接不需要。",
|
||||
@@ -70,6 +72,7 @@ const en = {
|
||||
updateBlockedSource: "Source installs have no bundled runtime, so the console cannot switch versions safely. Pull the source and rebuild (npm ci && npm run build && npm run web:build), or use a release package/Docker Compose.",
|
||||
updateBlockedPlatform: "No official package exists for this platform; only version checks are available.", updateBlockedArch: "No official package exists for this architecture; only version checks are available.",
|
||||
updateBlockedWindows: "Console updates for Windows release packages are disabled until they are verified on a real Windows install. Download the new package and replace it manually.",
|
||||
updateBlockedArm64: "Console updates for Linux arm64 release packages are disabled until they are verified on real hardware. Download the new package and replace it manually.",
|
||||
updateChecksumNotice: "SHA256SUMS.txt is an integrity checksum only, not a digital signature.",
|
||||
updateBlockedUnavailable: "Console updates are not enabled for this instance.", updateTaskTitle: "Update task",
|
||||
updateStatusDownloading: "Downloading", updateStatusVerifying: "Verifying", updateStatusExtracting: "Extracting", updateStatusStaging: "Staging",
|
||||
@@ -82,6 +85,7 @@ const en = {
|
||||
updateErrorRollbackFailed: "The update failed and automatic rollback also failed. Restore the previous version manually from the backup.",
|
||||
updateErrorSwap: "Replacing application files failed; the previous version was restored where possible. Check the logs.",
|
||||
updateErrorInProgress: "Another update task is already running.", updateErrorGeneric: "The update could not be completed; check the logs.", updateStartedEvent: "Update started",
|
||||
updateErrorLockFailed: "The update lock could not be taken over; make sure no other update is running and try again.", updateErrorUnavailable: "Console updates are not enabled for this instance.",
|
||||
adminWsOverviewTitle: "WebSpeak management is ready", adminWsOverviewLead: "Manage instance access and the guest experience first. Configure an independent TS management connection when you need it.",
|
||||
adminWsManageLead: "Access policy, site announcements, voice transport, the skin store and browser sessions.",
|
||||
adminTsManageLead: "Server settings, channels, clients, server groups and bans. Separate Query credentials are required; ordinary voice connections do not need them.",
|
||||
@@ -116,6 +120,7 @@ const de = {
|
||||
updateBlockedSource: "Quellinstallationen haben keine mitgelieferte Laufzeit; die Konsole kann Versionen nicht sicher wechseln. Quellen aktualisieren und neu bauen (npm ci && npm run build && npm run web:build) oder Release-Paket/Docker Compose verwenden.",
|
||||
updateBlockedPlatform: "Für diese Plattform gibt es kein offizielles Paket; nur Versionsprüfungen sind möglich.", updateBlockedArch: "Für diese Architektur gibt es kein offizielles Paket; nur Versionsprüfungen sind möglich.",
|
||||
updateBlockedWindows: "Konsolen-Updates für Windows-Release-Pakete sind deaktiviert, bis sie auf einer echten Windows-Installation geprüft wurden. Laden Sie das neue Paket herunter und ersetzen Sie es manuell.",
|
||||
updateBlockedArm64: "Konsolen-Updates für Linux-arm64-Release-Pakete sind deaktiviert, bis sie auf echter Hardware geprüft wurden. Laden Sie das neue Paket herunter und ersetzen Sie es manuell.",
|
||||
updateChecksumNotice: "SHA256SUMS.txt ist nur eine Integritätsprüfsumme, keine digitale Signatur.",
|
||||
updateBlockedUnavailable: "Konsolen-Updates sind für diese Instanz nicht aktiviert.", updateTaskTitle: "Update-Aufgabe",
|
||||
updateStatusDownloading: "Wird heruntergeladen", updateStatusVerifying: "Wird geprüft", updateStatusExtracting: "Wird entpackt", updateStatusStaging: "Wird bereitgestellt",
|
||||
@@ -128,6 +133,7 @@ const de = {
|
||||
updateErrorRollbackFailed: "Das Update ist fehlgeschlagen und auch die automatische Wiederherstellung. Stellen Sie die vorherige Version manuell aus der Sicherung wieder her.",
|
||||
updateErrorSwap: "Das Ersetzen der Anwendungsdateien ist fehlgeschlagen; die vorherige Version wurde nach Möglichkeit wiederhergestellt. Protokolle prüfen.",
|
||||
updateErrorInProgress: "Eine andere Update-Aufgabe läuft bereits.", updateErrorGeneric: "Das Update konnte nicht abgeschlossen werden; Protokolle prüfen.", updateStartedEvent: "Update gestartet",
|
||||
updateErrorLockFailed: "Die Update-Sperre konnte nicht übernommen werden. Stellen Sie sicher, dass keine andere Update-Aufgabe läuft, und versuchen Sie es erneut.", updateErrorUnavailable: "Konsolen-Updates sind für diese Instanz nicht aktiviert.",
|
||||
adminWsOverviewTitle: "WebSpeak-Verwaltung ist bereit", adminWsOverviewLead: "Zuerst Instanzzugang und Gastoberfläche verwalten. Eine separate TS-Verbindung nur bei Bedarf einrichten.",
|
||||
adminWsManageLead: "Zugriffsregeln, Website-Ankündigungen, Sprachtransport, Skin-Store und Browsersitzungen.",
|
||||
adminTsManageLead: "Servereinstellungen, Kanäle, Mitglieder, Servergruppen und Sperren. Separate Query-Zugangsdaten sind nötig; normale Sprachverbindungen benötigen sie nicht.",
|
||||
@@ -162,6 +168,7 @@ const ru = {
|
||||
updateBlockedSource: "В установке из исходников нет встроенной среды выполнения, поэтому консоль не может безопасно сменить версию. Обновите исходники и пересоберите (npm ci && npm run build && npm run web:build) или используйте пакет релиза/Docker Compose.",
|
||||
updateBlockedPlatform: "Для этой платформы нет официального пакета; доступна только проверка версий.", updateBlockedArch: "Для этой архитектуры нет официального пакета; доступна только проверка версий.",
|
||||
updateBlockedWindows: "Обновление из консоли для релизных пакетов Windows отключено до проверки на реальной установке Windows. Скачайте новый пакет и замените его вручную.",
|
||||
updateBlockedArm64: "Обновление из консоли для релизных пакетов Linux arm64 отключено до проверки на реальном оборудовании. Скачайте новый пакет и замените его вручную.",
|
||||
updateChecksumNotice: "SHA256SUMS.txt — только контрольная сумма целостности, а не цифровая подпись.",
|
||||
updateBlockedUnavailable: "Обновление из консоли для этого экземпляра не включено.", updateTaskTitle: "Задача обновления",
|
||||
updateStatusDownloading: "Скачивание", updateStatusVerifying: "Проверка", updateStatusExtracting: "Распаковка", updateStatusStaging: "Подготовка",
|
||||
@@ -174,6 +181,7 @@ const ru = {
|
||||
updateErrorRollbackFailed: "Обновление не удалось, и автоматический откат тоже не удался. Восстановите предыдущую версию вручную из резервной копии.",
|
||||
updateErrorSwap: "Не удалось заменить файлы приложения; предыдущая версия восстановлена по возможности. Проверьте журналы.",
|
||||
updateErrorInProgress: "Другая задача обновления уже выполняется.", updateErrorGeneric: "Не удалось завершить обновление; проверьте журналы.", updateStartedEvent: "Обновление начато",
|
||||
updateErrorLockFailed: "Не удалось перехватить блокировку обновления. Убедитесь, что другая задача обновления не выполняется, и повторите попытку.", updateErrorUnavailable: "Обновление из консоли для этого экземпляра не включено.",
|
||||
adminWsOverviewTitle: "Управление WebSpeak готово", adminWsOverviewLead: "Настройте доступ и гостевой интерфейс. Отдельное управление TS подключайте по мере необходимости.",
|
||||
adminWsManageLead: "Политика доступа, объявления сайта, голосовой транспорт, магазин тем и сеансы браузеров.",
|
||||
adminTsManageLead: "Настройки сервера, каналы, участники, серверные группы и блокировки. Нужны отдельные данные Query; для обычного голосового подключения они не требуются.",
|
||||
@@ -208,6 +216,7 @@ const ja = {
|
||||
updateBlockedSource: "ソース実行には同梱ランタイムがないため、安全にバージョンを切り替えられません。ソースを取得して再ビルドする(npm ci && npm run build && npm run web:build)か、リリースパッケージ/Docker Compose を使用してください。",
|
||||
updateBlockedPlatform: "このプラットフォーム向けの公式パッケージがないため、バージョン確認のみ可能です。", updateBlockedArch: "このアーキテクチャ向けの公式パッケージがないため、バージョン確認のみ可能です。",
|
||||
updateBlockedWindows: "Windows リリースパッケージのコンソール更新は、実際の Windows 環境で検証するまで無効です。新しいパッケージをダウンロードして手動で置き換えてください。",
|
||||
updateBlockedArm64: "Linux arm64 リリースパッケージのコンソール更新は、実機で検証するまで無効です。新しいパッケージをダウンロードして手動で置き換えてください。",
|
||||
updateChecksumNotice: "SHA256SUMS.txt は整合性確認用のチェックサムであり、デジタル署名ではありません。",
|
||||
updateBlockedUnavailable: "このインスタンスではコンソール更新が有効になっていません。", updateTaskTitle: "更新タスク",
|
||||
updateStatusDownloading: "ダウンロード中", updateStatusVerifying: "検証中", updateStatusExtracting: "展開中", updateStatusStaging: "ステージング中",
|
||||
@@ -220,6 +229,7 @@ const ja = {
|
||||
updateErrorRollbackFailed: "更新に失敗し、自動ロールバックも失敗しました。バックアップから以前のバージョンを手動で復元してください。",
|
||||
updateErrorSwap: "アプリケーションのファイル置き換えに失敗しました。可能な範囲で以前のバージョンに戻しました。ログを確認してください。",
|
||||
updateErrorInProgress: "別の更新タスクが実行中です。", updateErrorGeneric: "更新を完了できませんでした。ログを確認してください。", updateStartedEvent: "更新を開始",
|
||||
updateErrorLockFailed: "更新ロックを引き継げませんでした。ほかの更新タスクが実行中でないことを確認して再試行してください。", updateErrorUnavailable: "このインスタンスではコンソール更新が有効になっていません。",
|
||||
adminWsOverviewTitle: "WebSpeak 管理を利用できます", adminWsOverviewLead: "まず接続方針と訪問者向け画面を管理します。必要な場合だけ、独立した TS 管理接続を設定します。",
|
||||
adminWsManageLead: "アクセス方針、サイトのお知らせ、音声転送、スキンストア、ブラウザー接続。",
|
||||
adminTsManageLead: "サーバー設定、チャンネル、メンバー、サーバーグループ、禁止リスト。専用 Query 認証情報が必要ですが、通常の音声接続には不要です。",
|
||||
|
||||
@@ -725,6 +725,19 @@ test("settings and operations render explicit localized sections with valid deep
|
||||
}
|
||||
});
|
||||
|
||||
test("update error codes resolve to their dedicated five-language labels", async () => {
|
||||
const { adminOrganizationCopy } = await vite.ssrLoadModule("/src/i18n/admin-organization.ts");
|
||||
await mount("/admin/server");
|
||||
for (const language of ["zh", "en", "de", "ru", "ja"]) {
|
||||
state.language = language;
|
||||
const copy = adminOrganizationCopy[language];
|
||||
assert.equal(state.i18n.errorText("UPDATE_LOCK_FAILED"), copy.updateErrorLockFailed);
|
||||
assert.equal(state.i18n.errorText("UPDATE_UNAVAILABLE"), copy.updateErrorUnavailable);
|
||||
assert.equal(state.i18n.errorText("UPDATE_RESTART_UNAVAILABLE"), copy.updateErrorUnavailable);
|
||||
assert.notEqual(state.i18n.errorText("UPDATE_LOCK_FAILED"), copy.updateErrorGeneric);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
test("loading saved custom Query ports never treats them as unsaved transport defaults", async () => {
|
||||
for (const [transport, queryPort] of [["ssh", 10011], ["tcp", 10022]]) {
|
||||
|
||||
Reference in new issue
Block a user