Compare commits

...
7 Commits
Author SHA1 Message Date
illusia 9a12e2ee7b fix(release): package native files for console updates 2026-11-26 16:39:11 +08:00
illusia 3e4be94ae7 release: prepare v0.3.3 2026-11-26 16:30:40 +08:00
illusia 3339d09936 test(updater): stop recovery processes before removing fixtures 2026-11-26 16:20:55 +08:00
illusia 462bab57d2 fix(updater): honor launcher recovery locks during initialization 2026-11-26 16:20:03 +08:00
illusia 6bbc292056 fix(updater): lock launcher recovery and cancel failed downloads 2026-11-26 16:17:08 +08:00
ILLUSIA e3c71f07b1 Merge pull request #62 from OddTurtleHead/fix/updater-recovery-consistency
fix(updater): preserve recovery consistency across interrupted updates
2026-11-26 16:05:42 +08:00
OddTurtleHead cf1cc9fb94 fix(updater): preserve recovery consistency across interrupted updates
Keep health checks, rollback reporting, launcher recovery, and download failure handling consistent so verified updates cannot report false success or crash during recoverable I/O failures.
2026-11-25 23:51:16 +08:00
23 changed files with 751 additions and 90 deletions

No files matched your search

+33 -2
View File
@@ -9,7 +9,7 @@ on:
version: version:
description: Release version without the v prefix description: Release version without the v prefix
required: true required: true
default: 0.3.2 default: 0.3.3
type: string type: string
permissions: permissions:
@@ -214,7 +214,38 @@ jobs:
grep -q '"status":"ok"' <<<"$health" grep -q '"status":"ok"' <<<"$health"
grep -q "\"version\":\"$release_version\"" <<<"$health" grep -q "\"version\":\"$release_version\"" <<<"$health"
) )
tar -czf "$GITHUB_WORKSPACE/${package_name}.tar.gz" -C "$RUNNER_TEMP" "$package_name" # Native rebuilds can leave hard-linked objects and Python/toolchain
# symlinks in scratch directories. Ship independent files and keep
# build-only scratch paths out of the portable runtime archive.
tar --hard-dereference \
--exclude='*/@discordjs/opus/build-tmp-*' \
--exclude='*/node_gyp_bins' \
-czf "$GITHUB_WORKSPACE/${package_name}.tar.gz" -C "$RUNNER_TEMP" "$package_name"
# Verify the shipped tarball is accepted by the same extractor and
# package validator used by console updates, including .bin links.
node --input-type=module - "$GITHUB_WORKSPACE/${package_name}.tar.gz" "$RUNNER_TEMP/${package_name}-updater-check" "$release_version" <<'NODE'
import path from 'node:path';
import { rm } from 'node:fs/promises';
import { spawnSync } from 'node:child_process';
import { extractReleaseArchive } from './dist/updater/archive.js';
import { locatePackageRoot } from './dist/updater/code-swap.js';
const [archive, destination, version] = process.argv.slice(2);
try {
await extractReleaseArchive(archive, destination, path.basename(archive));
const root = locatePackageRoot(destination, version, 'linux');
const nativeSmoke = spawnSync(path.join(root, 'runtime', 'node'), ['--input-type=commonjs', '-e', `
const { OpusEncoder } = require('@discordjs/opus');
const encoder = new OpusEncoder(48000, 2);
const packet = encoder.encode(Buffer.alloc(3840));
if (encoder.decode(packet).length !== 3840) throw new Error('Packaged Opus codec failed');
`], { cwd: root, encoding: 'utf8', timeout: 15000 });
if (nativeSmoke.error) throw nativeSmoke.error;
if (nativeSmoke.status !== 0) throw new Error(nativeSmoke.stderr || 'Packaged Opus runtime failed');
console.log(`Console updater accepts ${path.basename(archive)}`);
} finally {
await rm(destination, { recursive: true, force: true });
}
NODE
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v4
with: with:
name: linux-${{ matrix.arch }} name: linux-${{ matrix.arch }}
+1 -1
View File
@@ -19,7 +19,7 @@
</p> </p>
</div> </div>
当前版本 / Current version: **[v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2)** · [更新内容 / Release notes](./docs/README.zh-CN.md#latest-release-notes) 当前版本 / Current version: **[v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3)** · [更新内容 / Release notes](./docs/README.zh-CN.md#latest-release-notes)
## 关于 WebSpeak · Overview ## 关于 WebSpeak · Overview
+15 -1
View File
@@ -13,7 +13,7 @@
WebSpeak ist ein selbst gehosteter Browserclient und ein Sprach-Gateway für TeamSpeak 3 und TeamSpeak 6. Nutzer verwenden Sprache, Chat und Bildschirmfreigabe im Browser; Betreiber verwalten Zielserver, Zugriff und Daten über die Webkonsole. WebSpeak ist ein selbst gehosteter Browserclient und ein Sprach-Gateway für TeamSpeak 3 und TeamSpeak 6. Nutzer verwenden Sprache, Chat und Bildschirmfreigabe im Browser; Betreiber verwalten Zielserver, Zugriff und Daten über die Webkonsole.
Stabile Version: [Hinweise zu v0.3.2](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Skin-Wiederherstellung, App-Bibliothek und Plugin-Formulare. Stabile Version: [Hinweise zu v0.3.3](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Konsolen-Updates, Wiederherstellung und bessere Skin-Kompatibilität.
@@ -341,6 +341,20 @@ Funktionale Plugins sind unabhängige Anwendungen mit Browserfunktionen und opti
<a id="latest-release-notes"></a> <a id="latest-release-notes"></a>
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
**Schwerpunkt: stabile Versionen prüfen und Updates direkt in der Verwaltung installieren.**
- Die Konsole prüft offizielle GitHub Releases; Administratoren wählen eine Version und bestätigen die Installation nach SHA-256-Prüfung. Die Installation unterstützt zunächst offizielle Linux-x64-Pakete im Vordergrund. Windows, Linux arm64, Docker, Quellinstallationen und von systemd, PM2 oder Supervisor verwaltete Instanzen können Versionen und Versionshinweise prüfen; die Installation bleibt manuell.
- Nur Programmdateien werden ersetzt. `data/`, `config.json`, `certs/`, installierte Skins und Plugins bleiben erhalten. Der Prozessneustart trennt Sprachsitzungen und Konsole kurzzeitig. SHA256SUMS.txt ist eine Integritätsprüfsumme, keine digitale Signatur.
- Gesundheitsprüfung, Rollback und Startwiederherstellung nach Unterbrechungen wurden gehärtet. Wiederherstellung und Update verwenden dieselbe Sperre. Größenlimits, Schreibfehler und Abbruch beenden Anfragen, geben Leser frei und bereinigen parallele Downloads.
- Skins können Wiederherstellungsbedienelemente über deklarierte Slots platzieren und Host-Bedienelemente über geschützte Variablen gestalten. Bei unbrauchbaren Werten greifen Standardlayout und -farben. Verbesserte Vermeidung verdeckter Elemente, Toast-Hit-Tests sowie Kompatibilität mit verzögertem Skin-Laden und Animationen; Wiederherstellungskürzel bleiben verfügbar.
- Enthält #60, #61, #62 und nachfolgende Korrekturen sowie aktualisierte Skin-Anleitungen und Beispiele. Danke an OddTurtleHead.
**Upgrade:** v0.3.2 und ältere Versionen zuerst manuell auf v0.3.3 aktualisieren. Danach sind Konsolen-Updates für künftige stabile Versionen auf unterstützten Installationen verfügbar. Daten vorher sichern. Docker: `docker compose pull && docker compose up -d` unter Beibehaltung des Datenvolumes. Verwaltete Dienste vor dem Dateiaustausch stoppen und anschließend neu starten.
Prüfung: 1102 automatisierte Tests, Frontend-/Backend-Builds und Docker-Startprüfung bestanden.
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14 ### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
- Drittanbieter-Skins können Host-Dekorationen gestalten. Der Host verwaltet Wiederherstellung und Freigabe, damit Nutzer zu einem integrierten Skin zurückkehren können. Danke an ph1gros für die TS3-Erkennung und Kompatibilitätshinweise (#46) und an OddTurtleHead für Host-Design und Skin-Wiederherstellung (#57). - Drittanbieter-Skins können Host-Dekorationen gestalten. Der Host verwaltet Wiederherstellung und Freigabe, damit Nutzer zu einem integrierten Skin zurückkehren können. Danke an ph1gros für die TS3-Erkennung und Kompatibilitätshinweise (#46) und an OddTurtleHead für Host-Design und Skin-Wiederherstellung (#57).
+15 -1
View File
@@ -13,7 +13,7 @@
WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Visitors join voice, chat and screen sharing in a browser; operators manage target servers, access policy and data through the administration console. WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Visitors join voice, chat and screen sharing in a browser; operators manage target servers, access policy and data through the administration console.
Stable release: [v0.3.2 notes](#latest-release-notes) · [Download packages](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Skin recovery, app library layouts, and plugin settings forms. Stable release: [v0.3.3 notes](#latest-release-notes) · [Download packages](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Console updates, reliable recovery, and skin compatibility improvements.
@@ -347,6 +347,20 @@ Functional plugins are independent applications using standard browser capabilit
<a id="latest-release-notes"></a> <a id="latest-release-notes"></a>
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
**Highlight: stable-release checks and one-click updates in the administration console.**
- Administrators can check official GitHub Releases, select a version and confirm installation. Packages must pass SHA-256 verification. Installation initially supports official Linux x64 packages running in the foreground. Windows, Linux arm64, Docker, source installs and instances managed by systemd, PM2 or Supervisor retain version checks and release-note links; installation follows their manual deployment procedure.
- Updates replace application files while preserving `data/`, `config.json`, `certs/`, installed skins and plugins. Installation restarts the process and briefly disconnects voice sessions and the console. SHA256SUMS.txt is an integrity checksum, not a digital signature.
- Hardened health checks, rollback and startup recovery after interrupted updates. Recovery shares the update lock, preventing a duplicate launch from rolling back a live update. Size-limit errors, disk-write failures and cancellation abort requests, release response readers and clean up sibling downloads.
- Skins can place recovery controls in declared slots and style host controls through protected tokens, with default placement and colours when unusable. Improved floating-control avoidance, hit-testing through toasts, late skin loading and animation compatibility; recovery shortcuts remain available.
- Includes #60, #61, #62 and follow-up maintenance fixes, plus updated skin development documentation and examples. Thanks to OddTurtleHead.
**Upgrading:** manually upgrade v0.3.2 or earlier to v0.3.3 first. Supported installs can then use the console for future stable releases. Back up data before upgrading. Docker uses `docker compose pull && docker compose up -d` with the data volume preserved. Stop managed services before replacing application files, then start them again.
Validation: 1,102 automated tests, frontend/backend builds and the Docker startup health check passed.
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14 ### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
- Third-party skins can style host decorations. The host manages recovery and authorization so users can switch back to a built-in skin. Thanks to ph1gros for the TS3 detection and compatibility work (#46), and OddTurtleHead for host theming and skin recovery (#57). - Third-party skins can style host decorations. The host manages recovery and authorization so users can switch back to a built-in skin. Thanks to ph1gros for the TS3 detection and compatibility work (#46), and OddTurtleHead for host theming and skin recovery (#57).
+15 -1
View File
@@ -13,7 +13,7 @@
WebSpeak はセルフホスト型の TeamSpeak 3 / TeamSpeak 6 ブラウザークライアント兼音声ゲートウェイです。ユーザーはブラウザーで音声、チャット、画面共有に参加でき、運営者は管理コンソールで接続先、アクセス方針、データを管理できます。 WebSpeak はセルフホスト型の TeamSpeak 3 / TeamSpeak 6 ブラウザークライアント兼音声ゲートウェイです。ユーザーはブラウザーで音声、チャット、画面共有に参加でき、運営者は管理コンソールで接続先、アクセス方針、データを管理できます。
安定版:[v0.3.2 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · スキンの復元、アプリライブラリの配置、プラグイン設定フォーム。 安定版:[v0.3.3 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · コンソール更新、復元処理、スキン互換性の改善。
@@ -276,6 +276,20 @@ relay.example.com {
<a id="latest-release-notes"></a> <a id="latest-release-notes"></a>
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
**主な変更:管理コンソールから安定版の確認とワンクリック更新が可能になりました。**
- 公式 GitHub Releases を確認し、管理者がバージョンを選んでインストールを承認します。パッケージは SHA-256 検証が必須です。自動インストールの対象は、フォアグラウンドで実行する公式 Linux x64 パッケージです。Windows、Linux arm64、Docker、ソース実行、systemd・PM2・Supervisor 管理の環境では、バージョン確認とリリースノートの閲覧ができ、インストールは手動です。
- 置き換えるのはプログラムファイルのみです。`data/`、`config.json`、`certs/`、インストール済みのスキンとプラグインは保持します。プロセスの再起動により、音声セッションと管理画面が一時的に切断されます。SHA256SUMS.txt は整合性のチェックサムであり、デジタル署名ではありません。
- ヘルスチェック、ロールバック、中断後の起動復元を強化しました。復元処理は更新処理とロックを共有し、重複起動による実行中の更新の巻き戻しを防ぎます。サイズ超過、書き込み失敗、キャンセル時にはリクエストと並列ダウンロードを中止し、読み取りストリームを解放します。
- 宣言したスロットと保護されたスタイル変数で、スキン内の復元入口とホスト操作部を調整できます。利用できない配置や色は標準に戻ります。浮動ボタンの重なり回避、通知の下にある要素の判定、スキンの遅延読み込みとアニメーションの互換性を改善し、復元ショートカットを維持しました。
- #60、#61、#62 と追加修正を収録し、スキン開発ガイドとサンプルを更新しました。OddTurtleHead の貢献に感謝します。
**更新方法:** v0.3.2 以前は、最初に v0.3.3 へ手動で更新してください。その後、対応する環境ではコンソールから今後の安定版をインストールできます。事前にデータをバックアップしてください。Docker はデータボリュームを保持して `docker compose pull && docker compose up -d` を実行します。サービス管理下では、停止してからプログラムファイルを置き換え、再起動してください。
検証:1102 件の自動テスト、フロントエンド・バックエンドのビルド、Docker 起動ヘルスチェックを通過。
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14 ### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
- サードパーティースキンでホストの装飾を変更できます。復元と許可の操作は WebSpeak が管理し、組み込みスキンに戻せます。TS3 判定と互換性情報の ph1gros(#46)、ホスト装飾と復元機能の OddTurtleHead(#57)に感謝します。 - サードパーティースキンでホストの装飾を変更できます。復元と許可の操作は WebSpeak が管理し、組み込みスキンに戻せます。TS3 判定と互換性情報の ph1gros(#46)、ホスト装飾と復元機能の OddTurtleHead(#57)に感謝します。
+15 -1
View File
@@ -13,7 +13,7 @@
WebSpeak — самостоятельно размещаемый браузерный клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. Пользователи подключаются к голосу, чату и демонстрации экрана через браузер, а оператор управляет серверами, доступом и данными в веб-консоли. WebSpeak — самостоятельно размещаемый браузерный клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. Пользователи подключаются к голосу, чату и демонстрации экрана через браузер, а оператор управляет серверами, доступом и данными в веб-консоли.
Стабильный выпуск: [изменения v0.3.2](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Восстановление темы, библиотека приложений и формы настройки плагинов. Стабильный выпуск: [изменения v0.3.3](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Обновление из консоли, восстановление и улучшенная совместимость скинов.
@@ -276,6 +276,20 @@ relay.example.com {
<a id="latest-release-notes"></a> <a id="latest-release-notes"></a>
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
**Главное: проверка стабильных версий и установка обновлений из консоли администратора.**
- Консоль проверяет официальные GitHub Releases; администратор выбирает версию и подтверждает установку после проверки SHA-256. Установка пока поддерживается для официальных пакетов Linux x64, запущенных в переднем плане. Windows, Linux arm64, Docker, исходники и экземпляры под управлением systemd, PM2 или Supervisor могут проверять версии и открывать примечания; установка остаётся ручной.
- Заменяются только файлы программы. `data/`, `config.json`, `certs/`, установленные скины и плагины сохраняются. Перезапуск ненадолго отключает голосовые сеансы и консоль. SHA256SUMS.txt — контрольная сумма целостности, а не цифровая подпись.
- Усилены проверка работоспособности, откат и восстановление запуска после прерванного обновления. Восстановление использует общую блокировку с обновлением, чтобы повторный запуск не откатывал активную установку. При превышении лимита, ошибке записи или отмене запросы прерываются, потоки освобождаются, параллельная загрузка отменяется.
- Скины могут размещать элементы восстановления в объявленных слотах и оформлять элементы хоста через защищённые переменные. При непригодном оформлении используются стандартные расположение и цвета. Улучшены обход перекрытий, проверка элементов под уведомлениями, поздняя загрузка скинов и совместимость анимаций; сочетания клавиш восстановления сохранены.
- Включены #60, #61, #62 и последующие исправления, обновлены руководство и примеры скинов. Спасибо OddTurtleHead.
**Переход:** v0.3.2 и более ранние версии сначала обновляются до v0.3.3 вручную. После этого поддерживаемые установки могут получать следующие стабильные версии через консоль. Сделайте резервную копию. Docker: `docker compose pull && docker compose up -d` с сохранением тома данных. Управляемую службу остановите перед заменой файлов, затем запустите снова.
Проверено: 1102 автоматических теста, сборки фронтенда и бэкенда, проверка запуска Docker.
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14 ### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
- Сторонние темы могут оформлять декоративные элементы. WebSpeak управляет восстановлением и разрешениями, чтобы пользователи могли вернуться к встроенной теме. Спасибо ph1gros за определение TS3 и сведения о совместимости (#46), а OddTurtleHead за оформление интерфейса и восстановление темы (#57). - Сторонние темы могут оформлять декоративные элементы. WebSpeak управляет восстановлением и разрешениями, чтобы пользователи могли вернуться к встроенной теме. Спасибо ph1gros за определение TS3 и сведения о совместимости (#46), а OddTurtleHead за оформление интерфейса и восстановление темы (#57).
+17 -3
View File
@@ -13,7 +13,7 @@
WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户通过浏览器加入语音、聊天和屏幕共享;部署者通过管理员控制台管理目标服务器、访问策略和数据。 WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户通过浏览器加入语音、聊天和屏幕共享;部署者通过管理员控制台管理目标服务器、访问策略和数据。
稳定版:[v0.3.2 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · 皮肤恢复入口、应用库布局和插件配置表单。 稳定版:[v0.3.3 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · 控制台一键更新、升级恢复与皮肤兼容性改进。
@@ -366,12 +366,26 @@ relay.example.com {
## 更新日志 ## 更新日志
<a id="live-update-2026-11-13"></a>
<a id="latest-release-notes"></a> <a id="latest-release-notes"></a>
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
**本次重点:管理员控制台新增正式版本检查与一键更新。**
- 管理员可检查官方 GitHub Releases,选择版本并确认安装;下载包必须通过 SHA-256 校验。首期自动安装支持前台运行的 Linux x64 官方发布包。Windows、Linux arm64、Docker、源码,以及 systemd、PM2、Supervisor 托管实例均保留版本检查和发行说明入口,安装仍按各部署方式手动完成。
- 更新仅替换程序文件,保留 `data/`、`config.json`、`certs/` 及已安装的皮肤和插件。安装会重启进程,语音会话和管理页面会短暂断开。SHA256SUMS.txt 是完整性校验和,不是数字签名。
- 加固升级健康检查、失败回滚和断电/进程中断后的启动恢复;恢复流程与更新进程共享锁,防止正常更新被重复启动误回滚。下载超限、写盘失败或取消时会中止请求、释放响应流,并清理并行下载。
- 皮肤可通过声明的布局槽位和受保护样式变量调整恢复入口与宿主控件的外观;不可读或不可用时回退到默认布局和样式。改进浮动入口的遮挡避让、提示消息穿透判断、皮肤延迟加载和动画兼容性,保留恢复快捷键。
- 纳入 #60、#61、#62 及后续维护修复,更新皮肤开发文档和示例。感谢 OddTurtleHead 的贡献。
**升级说明:** v0.3.2 及更早版本请先手动升级到 v0.3.3;之后可在支持的部署中使用控制台安装后续正式版。升级前请备份数据。Docker 使用 `docker compose pull && docker compose up -d` 并保留数据卷;服务托管实例请停止服务、替换程序文件后再启动。
验证:1102 项自动化测试通过,前后端构建及 Docker 启动健康检查通过。
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14 ### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
<a id="live-update-2026-11-13"></a>
- 第三方皮肤可以为宿主装饰添加样式。恢复入口和授权弹窗由宿主管理,应用皮肤后仍能切回内置皮肤。感谢 ph1gros 对 TS3 版本识别及兼容性文档的贡献(#46),以及 OddTurtleHead 对宿主装饰和皮肤恢复的贡献(#57)。 - 第三方皮肤可以为宿主装饰添加样式。恢复入口和授权弹窗由宿主管理,应用皮肤后仍能切回内置皮肤。感谢 ph1gros 对 TS3 版本识别及兼容性文档的贡献(#46),以及 OddTurtleHead 对宿主装饰和皮肤恢复的贡献(#57)。
- 日间、夜间和 ILLUSIA 的应用库在顶部工具栏展开。KAAK 3.1.134 将应用库放入最左侧图标栏,按钮与相邻控件对齐。固定应用排在列表前面。 - 日间、夜间和 ILLUSIA 的应用库在顶部工具栏展开。KAAK 3.1.134 将应用库放入最左侧图标栏,按钮与相邻控件对齐。固定应用排在列表前面。
- 插件后台提供字段编辑器,以及 P2P 文件传输、视频同看和 TSMusicBot 的配置表单。插件页面可以打开对应仓库。 - 插件后台提供字段编辑器,以及 P2P 文件传输、视频同看和 TSMusicBot 的配置表单。插件页面可以打开对应仓库。
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "webspeak-android-gateway", "name": "webspeak-android-gateway",
"version": "0.3.2", "version": "0.3.3",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "webspeak-android-gateway", "name": "webspeak-android-gateway",
"version": "0.3.2", "version": "0.3.3",
"dependencies": { "dependencies": {
"@honeybbq/teamspeak": "1.0.0-beta.23", "@honeybbq/teamspeak": "1.0.0-beta.23",
"express": "^4.21.2", "express": "^4.21.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "webspeak-android-gateway", "name": "webspeak-android-gateway",
"version": "0.3.2", "version": "0.3.3",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "index.cjs", "main": "index.cjs",
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "webspeak-webclient", "name": "webspeak-webclient",
"version": "0.3.2", "version": "0.3.3",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "webspeak-webclient", "name": "webspeak-webclient",
"version": "0.3.2", "version": "0.3.3",
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",
"dependencies": { "dependencies": {
"@discordjs/opus": "^0.10.0", "@discordjs/opus": "^0.10.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "webspeak-webclient", "name": "webspeak-webclient",
"version": "0.3.2", "version": "0.3.3",
"private": true, "private": true,
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",
"type": "module", "type": "module",
+100 -23
View File
@@ -28,8 +28,8 @@ code_missing() {
return 1 return 1
} }
# A backup can only repair an install if it recorded a swap and still holds # A backup can only repair a missing-code install if it is complete. Partial
# every entry needed to boot. Partial/legacy backups must be skipped. # backups are still resumable when they belong to the active task.
backup_is_complete() { backup_is_complete() {
[ -f "$1/.webspeak-swap.json" ] || return 1 [ -f "$1/.webspeak-swap.json" ] || return 1
for entry in $required_entries; do for entry in $required_entries; do
@@ -52,6 +52,86 @@ task_backup_can_repair() {
return 0 return 0
} }
state_file="$data_dir/updates/state.json"
lock_file="$data_dir/updates/update.lock"
read_update_task() {
task_id=""
task_status=""
if [ -f "$state_file" ]; then
task_id=$(sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
task_status=$(sed -n 's/.*"status"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
fi
case "$task_id" in
""|*[!A-Za-z0-9_-]*) task_id="" ;;
esac
}
read_update_task
process_start() {
# After the last ')' field 3 is first; starttime (field 22) is twentieth.
if [ -r "/proc/$1/stat" ]; then
sed 's/.*) //' "/proc/$1/stat" 2>/dev/null | awk '{print $20}'
fi
}
release_recovery_lock() {
if [ "${lock_owned:-0}" = 1 ] && [ "$(cat "$lock_file" 2>/dev/null)" = "$lock_payload" ]; then
rm -f -- "$lock_file"
fi
lock_owned=0
}
acquire_recovery_lock() {
# Share the updater's exclusive-create JSON lock. A distinct task id stops
# a delayed restart runner from taking this recovery lock over. Keep it for
# the entire restore, and only reclaim a proven-dead, unchanged owner.
mkdir -p "$data_dir/updates"
lock_owned=0
start=$(process_start "$$")
lock_payload="{\"pid\":$$,\"taskId\":\"recovery_$$\",\"createdAt\":\"\",\"processStart\":\"$start\"}"
for attempt in 1 2 3 4; do
if (umask 077; set -C; printf '%s\n' "$lock_payload" > "$lock_file") 2>/dev/null; then
lock_owned=1
trap 'release_recovery_lock' 0
trap 'exit 1' HUP INT TERM
return 0
fi
observed=$(cat "$lock_file" 2>/dev/null) || return 1
owner=$(printf '%s\n' "$observed" | sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\)[[:space:]]*[,}].*/\1/p' | head -n 1)
owner_task=$(printf '%s\n' "$observed" | sed -n 's/.*"taskId"[[:space:]]*:[[:space:]]*"\([^"]\{1,\}\)".*/\1/p' | head -n 1)
case "$owner" in ""|*[!0-9]*) return 1 ;; esac
[ -n "$owner_task" ] || return 1
if [ "$owner" != 0 ]; then
if kill -0 "$owner" 2>/dev/null || [ -d "/proc/$owner" ]; then
saved_start=$(printf '%s\n' "$observed" | sed -n 's/.*"processStart"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)
current_start=$(process_start "$owner")
# Unknown markers and inaccessible processes are conservatively live.
if [ -z "$saved_start" ] || [ -z "$current_start" ] || [ "$saved_start" = "$current_start" ]; then
return 1
fi
elif [ ! -d /proc ]; then
return 1
fi
fi
[ "$(cat "$lock_file" 2>/dev/null)" = "$observed" ] || continue
rm -f -- "$lock_file" || return 1
done
return 1
}
recovery_needed() {
if code_missing; then
return 0
fi
case "$task_status" in
downloading|verifying|extracting|staging|restarting)
[ -n "$task_id" ] && [ -d "$backups/$task_id" ] && [ -f "$backups/$task_id/.webspeak-swap.json" ]
return $?
;;
esac
return 1
}
restore_from_backup() { restore_from_backup() {
backup="$1" backup="$1"
# Move whatever partial new code the interrupted swap left in the install # Move whatever partial new code the interrupted swap left in the install
@@ -80,33 +160,29 @@ restore_from_backup() {
done done
} }
if code_missing; then if recovery_needed; then
if ! acquire_recovery_lock; then
echo "WebSpeak update or recovery is already running, or its lock cannot be verified; refusing to change application files." >&2
exit 75
fi
# The runner may have completed between the first state read and the lock.
read_update_task
fi
if [ "${lock_owned:-0}" = 1 ] && recovery_needed; then
restore_backup="" restore_backup=""
# The interrupted task is the source of truth: backups/<task.id> holds the # The interrupted task is the source of truth. Its backup may be partial
# exact version that was running before the swap. A successful earlier # while the old tree is being saved or while a previous recovery is still
# update leaves its backup behind (M1 does not clean it up), so picking the # consuming it, but it must never be replaced by an older complete backup.
# first or alphabetically smallest backup can resurrect a much older build. if [ -n "$task_id" ] && [ -d "$backups/$task_id" ]; then
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" candidate="$backups/$task_id"
if task_backup_can_repair "$candidate"; then if task_backup_can_repair "$candidate"; then
restore_backup="$candidate" restore_backup="$candidate"
fi fi
fi else
# No current task backup (e.g. state.json was lost): use the most recently
# 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.
# modified complete backup rather than whichever name happens to sort first.
if [ -z "$restore_backup" ]; then
for manifest in "$backups"/*/.webspeak-swap.json; do for manifest in "$backups"/*/.webspeak-swap.json; do
[ -f "$manifest" ] || continue [ -f "$manifest" ] || continue
backup="${manifest%/.webspeak-swap.json}" backup="${manifest%/.webspeak-swap.json}"
@@ -129,4 +205,5 @@ if code_missing; then
fi fi
fi fi
release_recovery_lock
exec "$PWD/runtime/node" "$PWD/dist/index.js" exec "$PWD/runtime/node" "$PWD/dist/index.js"
+5
View File
@@ -37,6 +37,11 @@ test("staged packages must be complete, regular files and version-matched", t =>
rmSync(path.join(missing, "runtime", "node")); rmSync(path.join(missing, "runtime", "node"));
assert.throws(() => validateStagedPackage(missing, { version: "0.4.0", platform: "linux" }), packageInvalid); assert.throws(() => validateStagedPackage(missing, { version: "0.4.0", platform: "linux" }), packageInvalid);
const missingLauncher = workspace(t);
createPackageFiles(missingLauncher, "0.4.0");
rmSync(path.join(missingLauncher, "start-webspeak.sh"));
assert.throws(() => validateStagedPackage(missingLauncher, { version: "0.4.0", platform: "linux" }), packageInvalid);
const linked = workspace(t); const linked = workspace(t);
createPackageFiles(linked, "0.4.0"); createPackageFiles(linked, "0.4.0");
rmSync(path.join(linked, "runtime", "node")); rmSync(path.join(linked, "runtime", "node"));
+13 -7
View File
@@ -56,6 +56,7 @@ export function validateStagedPackage(root: string, options: StagedPackageOption
requireEntry(root, "node_modules", "directory"); requireEntry(root, "node_modules", "directory");
requireEntry(root, "package.json", "file"); requireEntry(root, "package.json", "file");
requireEntry(root, options.platform === "win32" ? "runtime/node.exe" : "runtime/node", "file"); requireEntry(root, options.platform === "win32" ? "runtime/node.exe" : "runtime/node", "file");
requireEntry(root, options.platform === "win32" ? "start-webspeak.cmd" : "start-webspeak.sh", "file");
let manifest: unknown; let manifest: unknown;
try { manifest = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")); } try { manifest = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")); }
catch { throw new CodeSwapError("UPDATE_PACKAGE_INVALID", "Release package manifest is not valid JSON."); } catch { throw new CodeSwapError("UPDATE_PACKAGE_INVALID", "Release package manifest is not valid JSON."); }
@@ -145,10 +146,10 @@ function moveIfPresent(from: string, to: string): void {
} }
/** /**
* Backups written by this version contain only atomically moved entries. * Backups written by this version journal each entry before moving it. The
* The manifest records which entries were moved completely, so a backup that * journal may therefore contain an entry whose move never started, but it can
* was partially written by an older implementation (or tampered with) can be * never omit an entry that reached the backup. Recovery acts only on entries
* rejected instead of overwriting an intact install tree. * that actually exist in the backup, so a kill between journal and move is safe.
*/ */
const SWAP_MANIFEST = ".webspeak-swap.json"; const SWAP_MANIFEST = ".webspeak-swap.json";
@@ -203,10 +204,10 @@ export function swapCode(rootDir: string, stagedRoot: string, backupDir: string)
writeSwapManifest(backupDir, []); writeSwapManifest(backupDir, []);
for (const entry of CODE_ENTRIES) { for (const entry of CODE_ENTRIES) {
if (!existsSync(path.join(rootDir, entry))) continue; if (!existsSync(path.join(rootDir, entry))) continue;
moveIfPresent(path.join(rootDir, entry), path.join(backupDir, entry));
movedToBackup.push(entry); movedToBackup.push(entry);
swapWindowBarrier(entry);
writeSwapManifest(backupDir, movedToBackup); writeSwapManifest(backupDir, movedToBackup);
moveIfPresent(path.join(rootDir, entry), path.join(backupDir, entry));
swapWindowBarrier(entry);
} }
swapWindowBarrier(); swapWindowBarrier();
for (const entry of CODE_ENTRIES) { for (const entry of CODE_ENTRIES) {
@@ -216,7 +217,12 @@ export function swapCode(rootDir: string, stagedRoot: string, backupDir: string)
} }
} catch (error) { } catch (error) {
try { restoreMovedEntries(rootDir, backupDir, movedToBackup, movedToRoot); } try { restoreMovedEntries(rootDir, backupDir, movedToBackup, movedToRoot); }
catch { /* Report the original swap error; rollback failure is handled by the caller. */ } catch (rollbackError) {
throw new CodeSwapError(
"UPDATE_ROLLBACK_FAILED",
`${error instanceof Error ? error.message : "Release package swap failed."} Code rollback also failed: ${rollbackError instanceof Error ? rollbackError.message : "unknown error"}`,
);
}
if (error instanceof CodeSwapError) throw error; if (error instanceof CodeSwapError) throw error;
throw new CodeSwapError("UPDATE_SWAP_FAILED", error instanceof Error ? error.message : "Release package swap failed."); throw new CodeSwapError("UPDATE_SWAP_FAILED", error instanceof Error ? error.message : "Release package swap failed.");
} }
+73 -4
View File
@@ -2,9 +2,12 @@ import assert from "node:assert/strict";
import test, { type TestContext } from "node:test"; import test, { type TestContext } from "node:test";
import { spawn, type ChildProcess } from "node:child_process"; import { spawn, type ChildProcess } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import fs from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import { createServer } from "node:net"; import { createServer } from "node:net";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import path from "node:path"; import path from "node:path";
import { setCodeSwapCopyForTests } from "./code-swap.js";
import { runRestartPlan } from "./restart-runner.js"; import { runRestartPlan } from "./restart-runner.js";
const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds)); const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
@@ -27,13 +30,13 @@ async function waitFor(check: () => boolean, timeoutMs = 5_000): Promise<void> {
} }
} }
function appScript(version: string, port: number, pidFile: string): string { function appScript(version: string, port: number, pidFile: string, status = "ok"): string {
return `const http = require("node:http"); return `const http = require("node:http");
const { writeFileSync } = require("node:fs"); const { writeFileSync } = require("node:fs");
const server = http.createServer((request, response) => { const server = http.createServer((request, response) => {
if (request.url === "/api/health") { if (request.url === "/api/health") {
response.setHeader("content-type", "application/json"); response.setHeader("content-type", "application/json");
response.end(JSON.stringify({ status: "ok", version: ${JSON.stringify(version)} })); response.end(JSON.stringify({ status: ${JSON.stringify(status)}, version: ${JSON.stringify(version)} }));
return; return;
} }
response.statusCode = 404; response.statusCode = 404;
@@ -85,10 +88,10 @@ function runnerFixture(t: TestContext): RunnerFixture {
}; };
} }
function writePlan(fixture: RunnerFixture, port: number, pidFile: string, options: { targetVersion: string; reportedVersion: string; healthTimeoutMs?: number }) { function writePlan(fixture: RunnerFixture, port: number, pidFile: string, options: { targetVersion: string; reportedVersion: string; reportedStatus?: string; healthTimeoutMs?: number }) {
mkdirSync(path.dirname(fixture.statePath), { recursive: true }); mkdirSync(path.dirname(fixture.statePath), { recursive: true });
writeFileSync(fixture.lockPath, JSON.stringify({ pid: process.pid, taskId: fixture.taskId, createdAt: new Date().toISOString() })); writeFileSync(fixture.lockPath, JSON.stringify({ pid: process.pid, taskId: fixture.taskId, createdAt: new Date().toISOString() }));
writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript(options.reportedVersion, port, pidFile)); writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript(options.reportedVersion, port, pidFile, options.reportedStatus));
writeFileSync(fixture.planPath, JSON.stringify({ writeFileSync(fixture.planPath, JSON.stringify({
schemaVersion: 1, schemaVersion: 1,
taskId: fixture.taskId, taskId: fixture.taskId,
@@ -123,6 +126,21 @@ async function stopPidFile(pidFile: string): Promise<void> {
} }
} }
test("a runner refused by another lock owner leaves its files and state untouched", async t => {
const fixture = runnerFixture(t);
writePlan(fixture, await availablePort(), fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "2.0.0" });
const owner = JSON.stringify({ pid: process.pid, taskId: "recovery_owner", createdAt: new Date().toISOString() });
writeFileSync(fixture.lockPath, owner);
writeFileSync(fixture.statePath, JSON.stringify({ schemaVersion: 1, task: null }));
const before = readFileSync(fixture.statePath, "utf8");
assert.equal(await runRestartPlan(fixture.planPath), 1);
assert.equal(readFileSync(fixture.statePath, "utf8"), before);
assert.equal(readFileSync(fixture.lockPath, "utf8"), owner);
assert.equal(existsSync(fixture.backupDir), false);
assert.equal(existsSync(fixture.pidFile), false);
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "1.0.0");
});
test("a healthy target version completes the swap and leaves persistent state alone", { timeout: 20_000 }, async t => { test("a healthy target version completes the swap and leaves persistent state alone", { timeout: 20_000 }, async t => {
const fixture = runnerFixture(t); const fixture = runnerFixture(t);
const port = await availablePort(); const port = await availablePort();
@@ -148,6 +166,57 @@ test("a healthy target version completes the swap and leaves persistent state al
await waitFor(() => existsSync(fixture.pidFile)); await waitFor(() => existsSync(fixture.pidFile));
}); });
test("a failed in-process rollback is persisted as a rollback failure", { timeout: 20_000 }, async t => {
const fixture = runnerFixture(t);
const port = await availablePort();
writePlan(fixture, port, fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "2.0.0" });
const originalRename = fs.renameSync;
t.after(() => {
fs.renameSync = originalRename;
syncBuiltinESMExports();
setCodeSwapCopyForTests(null);
});
const exdev = () => Object.assign(new Error("cross-device link"), { code: "EXDEV" });
fs.renameSync = ((from, to) => {
if (from === path.join(fixture.rootDir, "dist") && to === path.join(fixture.backupDir, "dist")) throw exdev();
if (from === path.join(fixture.stagedRoot, "dist") && to === path.join(fixture.rootDir, "dist")) throw new Error("simulated staging failure");
if (from === path.join(fixture.backupDir, "dist") && to === path.join(fixture.rootDir, "dist")) throw exdev();
return originalRename(from, to);
}) as typeof fs.renameSync;
syncBuiltinESMExports();
let copies = 0;
setCodeSwapCopyForTests((from, to) => {
copies += 1;
if (copies === 2) throw new Error("simulated rollback copy failure");
fs.cpSync(from, to, { recursive: true });
});
assert.equal(await runRestartPlan(fixture.planPath), 1);
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
assert.equal(state.task.status, "failed");
assert.equal(state.task.rolledBack, false);
assert.equal(state.task.errorCode, "UPDATE_ROLLBACK_FAILED");
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), false);
assert.equal(existsSync(path.join(fixture.backupDir, "dist", "index.js")), true);
});
test("a target reporting the expected version with an error status is not accepted as healthy", { timeout: 20_000 }, async t => {
const fixture = runnerFixture(t);
const port = await availablePort();
writePlan(fixture, port, fixture.pidFile, {
targetVersion: "2.0.0", reportedVersion: "2.0.0", reportedStatus: "error", healthTimeoutMs: 500,
});
writeFileSync(path.join(fixture.rootDir, "dist", "index.js"), appScript("1.0.0", port, fixture.pidFile));
t.after(() => stopPidFile(fixture.pidFile));
assert.equal(await runRestartPlan(fixture.planPath), 1);
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
assert.equal(state.task.status, "failed");
assert.equal(state.task.rolledBack, true);
assert.equal(state.task.errorCode, "UPDATE_HEALTH_CHECK_FAILED");
assert.match(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), /version: "1\.0\.0"/);
});
test("a failed health check rolls back to the previous code and reports the failure", { timeout: 20_000 }, async t => { test("a failed health check rolls back to the previous code and reports the failure", { timeout: 20_000 }, async t => {
const fixture = runnerFixture(t); const fixture = runnerFixture(t);
const port = await availablePort(); const port = await availablePort();
+12 -3
View File
@@ -217,7 +217,7 @@ async function waitForVersion(plan: RestartPlan, version: string, timeoutMs: num
if (last?.status === "ok" && last.version === version) return last; if (last?.status === "ok" && last.version === version) return last;
await sleep(plan.pollIntervalMs); await sleep(plan.pollIntervalMs);
} }
return last?.version === version ? last : null; return null;
} }
function startApp(plan: RestartPlan): ChildProcess { function startApp(plan: RestartPlan): ChildProcess {
@@ -273,8 +273,6 @@ export async function runRestartPlan(planPath: string): Promise<number> {
const state = new StateWriter(plan); const state = new StateWriter(plan);
let swapped = false; let swapped = false;
let newApp: ChildProcess | undefined; let newApp: ChildProcess | undefined;
state.status("restarting");
state.step("restart", "running");
// Take over the update lock before doing anything else. The parent process // Take over the update lock before doing anything else. The parent process
// is about to exit and its lock would otherwise have a dead pid, letting a // is about to exit and its lock would otherwise have a dead pid, letting a
// second instance starting in this window roll the healthy code back. // second instance starting in this window roll the healthy code back.
@@ -285,6 +283,8 @@ export async function runRestartPlan(planPath: string): Promise<number> {
} catch (error) { } catch (error) {
throw new RunnerError("UPDATE_LOCK_FAILED", error instanceof Error ? error.message : "The update lock could not be taken over."); throw new RunnerError("UPDATE_LOCK_FAILED", error instanceof Error ? error.message : "The update lock could not be taken over.");
} }
state.status("restarting");
state.step("restart", "running");
await waitForParent(plan.waitForPid, plan.parentTimeoutMs); await waitForParent(plan.waitForPid, plan.parentTimeoutMs);
state.step("swap", "running"); state.step("swap", "running");
swapCode(plan.rootDir, plan.stagedRoot, plan.backupDir); swapCode(plan.rootDir, plan.stagedRoot, plan.backupDir);
@@ -303,12 +303,21 @@ export async function runRestartPlan(planPath: string): Promise<number> {
try { rmSync(plan.stagedRoot, { recursive: true, force: true }); } catch { /* Best effort. */ } try { rmSync(plan.stagedRoot, { recursive: true, force: true }); } catch { /* Best effort. */ }
return 0; return 0;
} catch (error) { } catch (error) {
// A recovery process or another update owns the tree. Without ownership
// this runner must not rewrite its state or start an app during recovery.
if (!releaseLock) return 1;
await stopApp(newApp); await stopApp(newApp);
const code = error instanceof RunnerError || error instanceof CodeSwapError const code = error instanceof RunnerError || error instanceof CodeSwapError
? error.code ? error.code
: "UPDATE_RESTART_FAILED"; : "UPDATE_RESTART_FAILED";
const message = error instanceof Error ? error.message : "The update could not be completed."; const message = error instanceof Error ? error.message : "The update could not be completed.";
state.step("restart", "failed", message); state.step("restart", "failed", message);
if (!swapped && code === "UPDATE_ROLLBACK_FAILED") {
state.rolledBack(false);
state.status("failed", { code, message });
releaseLock?.();
return 1;
}
let rolledBack = !swapped; let rolledBack = !swapped;
if (swapped) { if (swapped) {
state.step("rollback", "running"); state.step("rollback", "running");
+150 -2
View File
@@ -2,12 +2,13 @@ import assert from "node:assert/strict";
import { spawn, type ChildProcess } from "node:child_process"; import { spawn, type ChildProcess } from "node:child_process";
import { createServer } from "node:net"; import { createServer } from "node:net";
import test, { type TestContext } from "node:test"; import test, { type TestContext } from "node:test";
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import path from "node:path"; import path from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { UpdateService } from "./update-service.js"; import { UpdateService } from "./update-service.js";
import { CODE_ENTRIES } from "./code-swap.js"; import { CODE_ENTRIES, swapCode } from "./code-swap.js";
import { acquireUpdateLock, updateLockIsHeld } from "./update-state.js";
const SOURCE_DIR = path.dirname(fileURLToPath(import.meta.url)); const SOURCE_DIR = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(SOURCE_DIR, "..", ".."); const REPO_ROOT = path.resolve(SOURCE_DIR, "..", "..");
@@ -17,6 +18,71 @@ const TASK_ID = "upd_sigkill_window";
const logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } }; const logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
for (const lockKind of ["live", "unreadable"] as const) {
test(`launcher preserves a target while the update lock is ${lockKind}`, { timeout: 15_000, skip: process.platform !== "linux" }, async t => {
const fixture = buildFixture(t, await availablePort());
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
if (lockKind === "live") {
const release = acquireUpdateLock(lockPath, TASK_ID);
t.after(release);
assert.equal(updateLockIsHeld(lockPath, TASK_ID), true);
} else {
writeFileSync(lockPath, "{invalid");
}
const before = readFileSync(lockPath, "utf8");
const app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir, env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir }, stdio: "ignore",
});
t.after(() => stop(app));
await waitFor(() => app.exitCode !== null, "launcher did not refuse the held update lock", 5_000);
assert.equal(app.exitCode, 75);
assert.equal(readFileSync(lockPath, "utf8"), before);
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.4.0");
assert.equal(JSON.parse(readFileSync(path.join(fixture.backupDir, "package.json"), "utf8")).version, "0.3.2");
});
}
test("concurrent launchers cannot restore the same interrupted tree together", { timeout: 20_000, skip: process.platform !== "linux" }, async t => {
const port = await availablePort();
const fixture = buildFixture(t, port);
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
const bin = path.join(fixture.directory, "bin");
mkdirSync(bin);
// Pause the first real restore at mv, without adding a production test hook.
writeFileSync(path.join(bin, "mv"), `#!/bin/sh
printf '%s' "$$" > "$RECOVERY_TEST_BARRIER/entered"
attempt=0
while [ ! -f "$RECOVERY_TEST_BARRIER/resume" ] && [ "$attempt" -lt 200 ]; do
sleep 0.05
attempt=$((attempt + 1))
done
exec /bin/mv "$@"
`, { mode: 0o755 });
const env = { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir,
PATH: `${bin}${path.delimiter}${process.env.PATH}`, RECOVERY_TEST_BARRIER: fixture.barrierDir };
const first = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], { cwd: fixture.rootDir, env, stdio: "ignore" });
let second: ChildProcess | undefined;
try {
await waitFor(() => existsSync(path.join(fixture.barrierDir, "entered")), "first launcher did not start restoring");
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
assert.equal(updateLockIsHeld(lockPath), true);
const owner = readFileSync(lockPath, "utf8");
second = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], { cwd: fixture.rootDir, env, stdio: "ignore" });
await waitFor(() => second!.exitCode !== null, "second launcher did not refuse concurrent recovery", 5_000);
assert.equal(second.exitCode, 75);
assert.equal(readFileSync(lockPath, "utf8"), owner);
writeFileSync(path.join(fixture.barrierDir, "resume"), "");
await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), "first launcher did not finish recovery");
assert.equal(existsSync(lockPath), false);
} finally {
// Stop children before buildFixture's after hook removes their files.
writeFileSync(path.join(fixture.barrierDir, "resume"), "");
stop(first); stop(second);
await waitFor(() => !processAlive(first.pid) && !processAlive(second?.pid), "recovery processes did not stop", 5_000);
}
});
// Exercise a kill after every old entry's rename, before the manifest is // Exercise a kill after every old entry's rename, before the manifest is
// updated. In particular the backup is still partial for the first entries. // updated. In particular the backup is still partial for the first entries.
for (const entry of CODE_ENTRIES) { for (const entry of CODE_ENTRIES) {
@@ -81,6 +147,11 @@ async function healthVersion(port: number): Promise<string | null> {
} }
} }
function startedVersion(fixture: Fixture): string | null {
const { startedFile } = JSON.parse(readFileSync(fixture.markerFiles.config, "utf8")) as { startedFile: string };
return existsSync(startedFile) ? readFileSync(startedFile, "utf8") : null;
}
function processAlive(pid: number | undefined): boolean { function processAlive(pid: number | undefined): boolean {
if (!pid || pid <= 0) return false; if (!pid || pid <= 0) return false;
try { process.kill(pid, 0); return true; } try { process.kill(pid, 0); return true; }
@@ -309,6 +380,83 @@ test(
}, },
); );
test(
"launcher resumes a partial current backup instead of installing a stale complete backup",
{ timeout: 20_000 },
async t => {
const port = await availablePort();
const fixture = buildFixture(t, port, true);
const staleDir = path.join(fixture.dataDir, "updates", "backups", "aaa_stale_backup");
mkdirSync(fixture.backupDir, { recursive: true });
renameSync(path.join(fixture.rootDir, "dist"), path.join(fixture.backupDir, "dist"));
writeFileSync(path.join(fixture.backupDir, ".webspeak-swap.json"), JSON.stringify({ schemaVersion: 1, entries: ["dist"] }));
let app: ChildProcess | undefined;
t.after(() => stop(app));
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir,
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
stdio: "ignore",
});
await waitFor(() => startedVersion(fixture) !== null, "launcher did not resume the partial current backup");
assert.equal(startedVersion(fixture), "0.3.2");
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
assert.equal(JSON.parse(readFileSync(path.join(staleDir, "package.json"), "utf8")).version, "0.1.0");
assert.equal(existsSync(path.join(staleDir, "dist", "index.js")), true);
},
);
test(
"launcher resumes a rollback that already consumed part of the current backup",
{ timeout: 20_000 },
async t => {
const port = await availablePort();
const fixture = buildFixture(t, port);
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
for (const entry of ["runtime", "package.json"]) {
rmSync(path.join(fixture.rootDir, entry), { recursive: true, force: true });
renameSync(path.join(fixture.backupDir, entry), path.join(fixture.rootDir, entry));
}
mkdirSync(path.join(fixture.backupDir, "rejected"), { recursive: true });
renameSync(path.join(fixture.rootDir, "dist"), path.join(fixture.backupDir, "rejected", "dist"));
let app: ChildProcess | undefined;
t.after(() => stop(app));
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir,
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
stdio: "ignore",
});
await waitFor(() => startedVersion(fixture) !== null, "launcher did not resume the interrupted rollback");
assert.equal(startedVersion(fixture), "0.3.2");
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), true);
},
);
test(
"launcher rolls back an active fully swapped tree before starting the target",
{ timeout: 20_000 },
async t => {
const port = await availablePort();
const fixture = buildFixture(t, port);
writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript());
copyFileSync(process.execPath, path.join(fixture.stagedRoot, "runtime", "node"));
chmodSync(path.join(fixture.stagedRoot, "runtime", "node"), 0o755);
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
let app: ChildProcess | undefined;
t.after(() => stop(app));
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir,
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
stdio: "ignore",
});
await waitFor(() => startedVersion(fixture) !== null, "launcher did not resolve the active swapped tree");
assert.equal(startedVersion(fixture), "0.3.2");
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
},
);
test( test(
"recovery prefers the in-progress task backup over an older lexicographically-first backup", "recovery prefers the in-progress task backup over an older lexicographically-first backup",
{ timeout: 40_000 }, { timeout: 40_000 },
+1
View File
@@ -143,6 +143,7 @@ export function createPackageFiles(root: string, version: string, extra: Record<
writeFileSync(path.join(root, "dist", "index.js"), "// package entry\n", "utf8"); writeFileSync(path.join(root, "dist", "index.js"), "// package entry\n", "utf8");
writeFileSync(path.join(root, "web", "dist", "index.html"), "<!doctype html>\n", "utf8"); writeFileSync(path.join(root, "web", "dist", "index.html"), "<!doctype html>\n", "utf8");
writeFileSync(path.join(root, "runtime", "node"), "#!/bin/sh\nexit 0\n", { encoding: "utf8", mode: 0o755 }); writeFileSync(path.join(root, "runtime", "node"), "#!/bin/sh\nexit 0\n", { encoding: "utf8", mode: 0o755 });
writeFileSync(path.join(root, "start-webspeak.sh"), "#!/bin/sh\nexit 0\n", { encoding: "utf8", mode: 0o755 });
for (const [relative, contents] of Object.entries(extra)) { for (const [relative, contents] of Object.entries(extra)) {
const target = path.join(root, relative); const target = path.join(root, relative);
mkdirSync(path.dirname(target), { recursive: true }); mkdirSync(path.dirname(target), { recursive: true });
+199 -1
View File
@@ -1,6 +1,9 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { spawn } from "node:child_process"; import { spawn } from "node:child_process";
import { once } from "node:events"; import { once } from "node:events";
import fs from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import { Writable } from "node:stream";
import test, { type TestContext } from "node:test"; import test, { type TestContext } from "node:test";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
@@ -8,6 +11,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import type { Logger } from "../logger.js"; import type { Logger } from "../logger.js";
import { CHECKSUM_ASSET_NAME, OFFICIAL_REPOSITORY } from "./releases.js"; import { CHECKSUM_ASSET_NAME, OFFICIAL_REPOSITORY } from "./releases.js";
import { swapCode } from "./code-swap.js";
import { UpdateError, UpdateService, type UpdateErrorCode, type UpdateServiceOptions } from "./update-service.js"; import { UpdateError, UpdateService, type UpdateErrorCode, type UpdateServiceOptions } from "./update-service.js";
import { createPackageFiles, createTarGz, sha256Hex, type TarFixtureEntry } from "./test-support.js"; import { createPackageFiles, createTarGz, sha256Hex, type TarFixtureEntry } from "./test-support.js";
import { acquireUpdateLock, readUpdateState, writeUpdateState } from "./update-state.js"; import { acquireUpdateLock, readUpdateState, writeUpdateState } from "./update-state.js";
@@ -67,6 +71,7 @@ function packageArchive(version: string, extra: TarFixtureEntry[] = []): Buffer
{ name: "webspeak/web/dist/index.html", data: "<!doctype html>\n" }, { name: "webspeak/web/dist/index.html", data: "<!doctype html>\n" },
{ name: "webspeak/node_modules/.keep", data: "" }, { name: "webspeak/node_modules/.keep", data: "" },
{ name: "webspeak/runtime/node", data: "#!/bin/sh\nexit 0\n", mode: 0o755 }, { name: "webspeak/runtime/node", data: "#!/bin/sh\nexit 0\n", mode: 0o755 },
{ name: "webspeak/start-webspeak.sh", data: "#!/bin/sh\nexit 0\n", mode: 0o755 },
...extra, ...extra,
]); ]);
} }
@@ -269,6 +274,142 @@ test("unsafe archives are refused before any code is staged", async t => {
assert.equal(state.task?.errorCode, "UPDATE_ARCHIVE_UNSAFE"); assert.equal(state.task?.errorCode, "UPDATE_ARCHIVE_UNSAFE");
}); });
test("an asynchronous download write failure rejects the update without crashing the process", async t => {
const archive = packageArchive("0.4.0");
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
const release = releaseJson({
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: checksums },
],
});
const originalCreateWriteStream = fs.createWriteStream;
t.after(() => {
fs.createWriteStream = originalCreateWriteStream;
syncBuiltinESMExports();
});
fs.createWriteStream = (() => new Writable({
write(_chunk, _encoding, callback) {
setImmediate(() => callback(new Error("simulated ENOSPC")));
},
})) as unknown as typeof fs.createWriteStream;
syncBuiltinESMExports();
const cancelled = new Set<string>();
const responses: Response[] = [];
const signals: AbortSignal[] = [];
const stalledBody = (url: string) => new ReadableStream({
start(controller) { controller.enqueue(new Uint8Array([1, 2, 3])); },
pull() { return new Promise(() => {}); },
cancel() { cancelled.add(url); },
});
const fetch = (async (input: string | URL | Request, init?: RequestInit) => {
if (String(input) === RELEASE_LIST_URL) return new Response(JSON.stringify([release]), { status: 200 });
signals.push(init!.signal!);
const response = new Response(stalledBody(String(input)), { status: 200 });
responses.push(response);
return response;
}) as typeof globalThis.fetch;
const { service, launched } = createService(t, [], new Map(), { fetch });
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DOWNLOAD_FAILED"));
assert.equal(launched.length, 0);
assert.equal(cancelled.size, 2);
assert.ok(signals.every(signal => signal.aborted));
assert.ok(responses.every(response => !response.body!.locked));
});
test("a rejected asset aborts its stalled sibling before update cleanup returns", { timeout: 5_000 }, async t => {
const archive = packageArchive("0.4.0");
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
const release = releaseJson({ version: "0.4.0", assets: [{ name: ASSET_NAME, data: archive }, { name: CHECKSUM_ASSET_NAME, data: checksums }] });
const responses: Response[] = [], signals: AbortSignal[] = [];
let cancelled = 0;
const { service, dataDir } = createService(t, [], new Map(), { fetch: (async (input, init) => {
const url = String(input);
if (url === RELEASE_LIST_URL) return new Response(JSON.stringify([release]));
signals.push(init!.signal!);
const body = new ReadableStream<Uint8Array>({
start(controller) { controller.enqueue(new Uint8Array([1])); },
pull() { return new Promise(() => {}); },
cancel() { cancelled++; },
});
const response = new Response(body, { headers: url.endsWith(ASSET_NAME) ? { "content-length": String(513 * 1024 * 1024) } : {} });
responses.push(response);
return response;
}) as typeof fetch });
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DOWNLOAD_TOO_LARGE"));
assert.equal(cancelled, 2);
assert.ok(signals.every(signal => signal.aborted));
assert.ok(responses.every(response => !response.body!.locked));
assert.equal(existsSync(path.join(dataDir, "updates", "update.lock")), false);
});
test("download rejection cancels its body and releases the reader, including unread responses", async t => {
for (const declaredSize of [false, true]) {
let cancelled = false;
let signal: AbortSignal | null | undefined;
const body = new ReadableStream<Uint8Array>({
start(controller) { controller.enqueue(new Uint8Array([1, 2, 3])); },
cancel() { cancelled = true; },
});
const { service } = createService(t, [], new Map(), { fetch: (async (_input, init) => {
signal = init?.signal;
return new Response(body, { headers: declaredSize ? { "content-length": "3" } : {} });
}) as typeof fetch });
const target = path.join(workspace(t), "asset");
// A small injected byte limit exercises the production rejection path
// without allocating or writing a 512 MiB package in a regression test.
const download = service as unknown as { downloadAsset(asset: { name: string; url: string; size: number; digest: null }, destination: string, limit: number): Promise<unknown> };
await assert.rejects(download.downloadAsset({ name: ASSET_NAME,
url: `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, size: 3, digest: null }, target, 1),
updateErrorCode("UPDATE_DOWNLOAD_TOO_LARGE"));
assert.equal(cancelled, true);
assert.equal(body.locked, false);
assert.equal(signal?.aborted, true);
assert.equal(existsSync(target), false);
assert.equal(existsSync(`${target}.${process.pid}.tmp`), false);
}
});
test("a successful download releases its reader without aborting the request", async t => {
let signal: AbortSignal | null | undefined;
const response = new Response(new Uint8Array([1, 2, 3]));
const { service } = createService(t, [], new Map(), { fetch: (async (_input, init) => {
signal = init?.signal; return response;
}) as typeof fetch });
const target = path.join(workspace(t), "asset");
const download = service as unknown as { downloadAsset(asset: { name: string; url: string; size: number; digest: null }, destination: string, limit: number): Promise<unknown> };
await download.downloadAsset({ name: ASSET_NAME,
url: `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, size: 3, digest: null }, target, 4);
assert.deepEqual(readFileSync(target), Buffer.from([1, 2, 3]));
assert.equal(response.body!.locked, false);
assert.equal(signal?.aborted, false);
});
test("a download redirected outside GitHub is refused before it is written", async t => {
const archive = packageArchive("0.4.0");
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
const release = releaseJson({
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: checksums },
],
});
const fetch = (async (input: string | URL | Request) => {
const url = String(input);
if (url === RELEASE_LIST_URL) return new Response(JSON.stringify([release]), { status: 200 });
const response = new Response(url.endsWith(ASSET_NAME) ? new Uint8Array(archive) : new Uint8Array(checksums), { status: 200 });
if (url.endsWith(ASSET_NAME)) Object.defineProperty(response, "url", { value: "https://example.invalid/package.tar.gz" });
return response;
}) as typeof globalThis.fetch;
const { service, launched } = createService(t, [], new Map(), { fetch });
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_RELEASE_UNAVAILABLE"));
assert.equal(launched.length, 0);
});
test("a verified package is staged, persisted and handed to the restart runner", async t => { test("a verified package is staged, persisted and handed to the restart runner", async t => {
const archive = packageArchive("0.4.0"); const archive = packageArchive("0.4.0");
const checksums = Buffer.from(checksumText(ASSET_NAME, archive)); const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
@@ -400,7 +541,7 @@ test("initialization restores the previous code from an interrupted swap backup"
writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId, createdAt: "2026-01-01T00:00:00.000Z" })); writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
const restarted = new UpdateService({ const restarted = new UpdateService({
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.4.0", logger, rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.3.2", logger,
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()), platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
now: () => new Date("2026-01-01T00:10:00.000Z"), now: () => new Date("2026-01-01T00:10:00.000Z"),
}); });
@@ -415,6 +556,39 @@ test("initialization restores the previous code from an interrupted swap backup"
assert.equal(existsSync(lockPath), false); assert.equal(existsSync(lockPath), false);
}); });
test("initialization keeps a complete target tree consistent with the running target version", t => {
const fixture = createService(t, [], new Map());
const taskId = "upd_complete_target";
const statePath = path.join(fixture.dataDir, "updates", "state.json");
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
const backupDir = path.join(fixture.dataDir, "updates", "backups", taskId);
const stagedRoot = path.join(fixture.dataDir, "updates", "tasks", taskId, "staged");
createPackageFiles(stagedRoot, "0.4.0", { "dist/index.js": "// complete target code\n" });
swapCode(fixture.rootDir, stagedRoot, backupDir);
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: [],
},
});
writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
const restarted = new UpdateService({
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.4.0", logger,
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
now: () => new Date("2026-01-01T00:10:00.000Z"),
});
restarted.initialize();
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), "// complete target code\n");
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.4.0");
assert.equal(restarted.getStatus().task?.status, "succeeded");
assert.equal(restarted.getStatus().task?.rolledBack, false);
assert.equal(existsSync(lockPath), false);
});
test("initialization keeps a live task but reconciles it once its process is gone", async t => { test("initialization keeps a live task but reconciles it once its process is gone", async t => {
const fixture = createService(t, [], new Map()); const fixture = createService(t, [], new Map());
const running = { const running = {
@@ -444,6 +618,30 @@ test("initialization keeps a live task but reconciles it once its process is gon
assert.equal(restarted.getStatus().task?.errorCode, "UPDATE_INTERRUPTED"); assert.equal(restarted.getStatus().task?.errorCode, "UPDATE_INTERRUPTED");
}); });
test("initialization preserves an interrupted tree while a launcher recovery owns the lock", t => {
const fixture = createService(t, [], new Map());
const taskId = "upd_launcher_recovery";
const updates = path.join(fixture.dataDir, "updates");
const staged = path.join(updates, "tasks", taskId, "staged");
createPackageFiles(staged, "0.4.0");
const backup = path.join(updates, "backups", taskId);
swapCode(fixture.rootDir, staged, backup);
writeUpdateState(path.join(updates, "state.json"), { 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: [],
} });
const lockPath = path.join(updates, "update.lock");
const release = acquireUpdateLock(lockPath, "recovery_other_launcher");
t.after(release);
const owner = readFileSync(lockPath, "utf8");
fixture.service.initialize();
assert.equal(readFileSync(lockPath, "utf8"), owner);
assert.equal(fixture.service.getStatus().task?.status, "restarting");
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.4.0");
assert.equal(JSON.parse(readFileSync(path.join(backup, "package.json"), "utf8")).version, "0.3.2");
});
test("a replacement app can update again after the runner finishes its cached task", async t => { test("a replacement app can update again after the runner finishes its cached task", async t => {
const fixture = createService(t, [], new Map()); const fixture = createService(t, [], new Map());
const statePath = path.join(fixture.dataDir, "updates", "state.json"); const statePath = path.join(fixture.dataDir, "updates", "state.json");
+76 -29
View File
@@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url";
import type { Logger } from "../logger.js"; import type { Logger } from "../logger.js";
import type { UpdateCheckView, UpdateReleaseView, UpdateStatusView, UpdateTaskStatus, UpdateTaskView } from "../shared/update.js"; import type { UpdateCheckView, UpdateReleaseView, UpdateStatusView, UpdateTaskStatus, UpdateTaskView } from "../shared/update.js";
import { ArchiveError, extractReleaseArchive } from "./archive.js"; import { ArchiveError, extractReleaseArchive } from "./archive.js";
import { CodeSwapError, locatePackageRoot, restoreCode } from "./code-swap.js"; import { CodeSwapError, locatePackageRoot, restoreCode, validateStagedPackage } from "./code-swap.js";
import { detectDeployment, releaseAssetName, type DeploymentInfo } from "./deployment.js"; import { detectDeployment, releaseAssetName, type DeploymentInfo } from "./deployment.js";
import { import {
assertOfficialDownloadUrl, CHECKSUM_ASSET_NAME, GitHubReleaseSource, ReleaseSourceError, assertOfficialDownloadUrl, CHECKSUM_ASSET_NAME, GitHubReleaseSource, ReleaseSourceError,
@@ -162,7 +162,7 @@ export class UpdateService {
const task = this.state.task; const task = this.state.task;
// A live lock owner (for example a second process starting by mistake) // A live lock owner (for example a second process starting by mistake)
// must not have its in-flight task reconciled as interrupted. // must not have its in-flight task reconciled as interrupted.
if (!task || !isActiveTaskStatus(task.status) || !updateLockIsHeld(this.lockPath, task.id)) { if (!task || !isActiveTaskStatus(task.status) || !updateLockIsHeld(this.lockPath)) {
const recovered = task && isActiveTaskStatus(task.status) ? this.recoverInterruptedSwap(task) : null; const recovered = task && isActiveTaskStatus(task.status) ? this.recoverInterruptedSwap(task) : null;
const changed = recovered !== null || reconcileInterruptedState(this.state, this.options.currentVersion, this.now().toISOString()); const changed = recovered !== null || reconcileInterruptedState(this.state, this.options.currentVersion, this.now().toISOString());
if (changed) writeUpdateState(this.statePath, this.state); if (changed) writeUpdateState(this.statePath, this.state);
@@ -184,6 +184,15 @@ export class UpdateService {
private recoverInterruptedSwap(task: NonNullable<PersistedUpdateState["task"]>): boolean | null { private recoverInterruptedSwap(task: NonNullable<PersistedUpdateState["task"]>): boolean | null {
const backupDir = path.join(this.backupsDir, task.id); const backupDir = path.join(this.backupsDir, task.id);
if (!existsSync(backupDir)) return null; if (!existsSync(backupDir)) return null;
if (this.options.currentVersion === task.targetVersion) {
try {
validateStagedPackage(this.options.rootDir, { version: task.targetVersion, platform: this.options.platform });
return null;
} catch {
// A process can read the target version before every target entry is in
// place. Fall through to recovery when the on-disk tree is incomplete.
}
}
const now = this.now().toISOString(); const now = this.now().toISOString();
let restored = false; let restored = false;
try { try {
@@ -321,10 +330,22 @@ export class UpdateService {
const archivePath = path.join(downloadDirectory, assetName); const archivePath = path.join(downloadDirectory, assetName);
const checksumPath = path.join(downloadDirectory, CHECKSUM_ASSET_NAME); const checksumPath = path.join(downloadDirectory, CHECKSUM_ASSET_NAME);
this.startStep(task, "download"); this.startStep(task, "download");
const [archive, checksumFile] = await Promise.all([ const downloadsController = new AbortController();
this.downloadAsset(asset, archivePath, DOWNLOAD_LIMIT), const downloads = [
this.downloadAsset(checksumAsset, checksumPath, CHECKSUM_LIMIT), this.downloadAsset(asset, archivePath, DOWNLOAD_LIMIT, downloadsController.signal),
]); this.downloadAsset(checksumAsset, checksumPath, CHECKSUM_LIMIT, downloadsController.signal),
];
let archive: DownloadResult;
let checksumFile: DownloadResult;
try {
[archive, checksumFile] = await Promise.all(downloads);
} catch (error) {
downloadsController.abort();
// No sibling may still hold a response reader or write into the task
// directory when applyUpdate's failure cleanup removes that directory.
await Promise.allSettled(downloads);
throw error;
}
this.finishStep(task, "download", "succeeded"); this.finishStep(task, "download", "succeeded");
this.updateTaskStatus(task, "verifying"); this.updateTaskStatus(task, "verifying");
this.startStep(task, "checksum"); this.startStep(task, "checksum");
@@ -467,50 +488,76 @@ export class UpdateService {
if (value.toLowerCase() !== actual) throw new UpdateError("UPDATE_DIGEST_MISMATCH", "The package does not match the GitHub asset digest.", 422); if (value.toLowerCase() !== actual) throw new UpdateError("UPDATE_DIGEST_MISMATCH", "The package does not match the GitHub asset digest.", 422);
} }
private async downloadAsset(asset: ReleaseAsset, destination: string, limit: number): Promise<DownloadResult> { private async downloadAsset(asset: ReleaseAsset, destination: string, limit: number, cancelSignal?: AbortSignal): Promise<DownloadResult> {
try { assertOfficialDownloadUrl(asset.url, ...repositoryParts(this.options.repository)); } try { assertOfficialDownloadUrl(asset.url, ...repositoryParts(this.options.repository)); }
catch (error) { throw mapError(error); } catch (error) { throw mapError(error); }
let response: Response; let response: Response;
const controller = new AbortController();
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(this.options.downloadTimeoutMs ?? 300_000), ...(cancelSignal ? [cancelSignal] : [])]);
try { try {
response = await this.fetcher(asset.url, { response = await this.fetcher(asset.url, {
headers: { "user-agent": "WebSpeak-Console-Updater", accept: "application/octet-stream" }, headers: { "user-agent": "WebSpeak-Console-Updater", accept: "application/octet-stream" },
signal: AbortSignal.timeout(this.options.downloadTimeoutMs ?? 300_000), signal,
}); });
} catch (error) { } catch (error) {
controller.abort();
throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be downloaded.", 502); throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be downloaded.", 502);
} }
if (response.url) { let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
try { assertOfficialDownloadUrl(response.url, ...repositoryParts(this.options.repository)); } let stream: ReturnType<typeof createWriteStream> | undefined;
catch (error) { throw mapError(error); } let temporary: string | undefined;
} let onAbort: (() => void) | undefined;
if (!response.ok || !response.body) throw new UpdateError("UPDATE_DOWNLOAD_FAILED", `The release asset returned HTTP ${response.status}.`, 502);
const declared = Number(response.headers.get("content-length") ?? "");
if (Number.isFinite(declared) && declared > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
const temporary = `${destination}.${process.pid}.tmp`;
const hash = createHash("sha256");
const stream = createWriteStream(temporary, { mode: 0o600, flags: "wx" });
let bytes = 0;
try { try {
for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) { if (response.url) {
const buffer = Buffer.from(chunk); try { assertOfficialDownloadUrl(response.url, ...repositoryParts(this.options.repository)); }
catch (error) { throw mapError(error); }
}
if (!response.ok || !response.body) throw new UpdateError("UPDATE_DOWNLOAD_FAILED", `The release asset returned HTTP ${response.status}.`, 502);
const declared = Number(response.headers.get("content-length") ?? "");
if (Number.isFinite(declared) && declared > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
temporary = `${destination}.${process.pid}.tmp`;
const hash = createHash("sha256");
signal.throwIfAborted();
reader = response.body.getReader();
stream = createWriteStream(temporary, { mode: 0o600, flags: "wx" });
let bytes = 0;
let failStream!: (error: Error) => void;
const streamFailure = new Promise<Error>((resolve) => { failStream = resolve; });
stream.on("error", failStream);
onAbort = () => failStream(signal.reason instanceof Error ? signal.reason : new Error("Download aborted."));
signal.addEventListener("abort", onAbort, { once: true });
if (signal.aborted) onAbort();
const writer = stream;
const finished = new Promise<void>((resolve) => { writer.once("finish", resolve); });
while (true) {
const next = await Promise.race([reader.read(), streamFailure]);
if (next instanceof Error) throw next;
if (next.done) break;
const buffer = Buffer.from(next.value);
bytes += buffer.length; bytes += buffer.length;
if (bytes > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422); if (bytes > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
hash.update(buffer); hash.update(buffer);
if (!stream.write(buffer)) await new Promise<void>((resolve) => stream.once("drain", resolve)); if (!stream.write(buffer)) {
const drained = await Promise.race([streamFailure, new Promise<void>((resolve) => { writer.once("drain", resolve); })]);
if (drained instanceof Error) throw drained;
}
} }
stream.end(); stream.end();
await new Promise<void>((resolve, reject) => { const streamError = await Promise.race([finished.then(() => null), streamFailure]);
stream.once("finish", resolve); if (streamError) throw streamError;
stream.once("error", reject);
});
await rename(temporary, destination); await rename(temporary, destination);
return { sha256: hash.digest("hex"), bytes };
} catch (error) { } catch (error) {
stream.destroy(); controller.abort();
await rm(temporary, { force: true }).catch(() => undefined); await (reader ? reader.cancel() : response.body?.cancel())?.catch(() => undefined);
stream?.destroy();
if (temporary) await rm(temporary, { force: true }).catch(() => undefined);
if (error instanceof UpdateError) throw error; if (error instanceof UpdateError) throw error;
throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be saved.", 502); throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be saved.", 502);
} finally {
if (onAbort) signal.removeEventListener("abort", onAbort);
reader?.releaseLock();
} }
return { sha256: hash.digest("hex"), bytes };
} }
/** /**
+2 -2
View File
@@ -1,7 +1,7 @@
apply plugin: 'com.android.application' apply plugin: 'com.android.application'
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.3.2' def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.3.3'
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 302 def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 303
android { android {
namespace = "io.webspeak.client" namespace = "io.webspeak.client"
+2 -2
View File
@@ -25,7 +25,7 @@
"vite": "^6.4.3", "vite": "^6.4.3",
"vue-tsc": "^2.2.8" "vue-tsc": "^2.2.8"
}, },
"version": "0.3.2" "version": "0.3.3"
}, },
"node_modules/@babel/helper-string-parser": { "node_modules/@babel/helper-string-parser": {
"version": "7.27.1", "version": "7.27.1",
@@ -2952,5 +2952,5 @@
} }
} }
}, },
"version": "0.3.2" "version": "0.3.3"
} }
+1 -1
View File
@@ -27,5 +27,5 @@
"vite": "^6.4.3", "vite": "^6.4.3",
"vue-tsc": "^2.2.8" "vue-tsc": "^2.2.8"
}, },
"version": "0.3.2" "version": "0.3.3"
} }