diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 014d1b5a..b9a2f86f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -772,6 +772,18 @@ jobs: with: persist-credentials: false + # scripts/install.ps1 against fake web and process cmdlets, in both PowerShell editions. It + # needs no toolchain and no package, so it runs first here and does not wait for windows-cross. + - name: Install script regressions (Windows PowerShell 5.1) + timeout-minutes: 2 + shell: powershell + run: ./scripts/release/test_install_windows.ps1 + + - name: Install script regressions (PowerShell 7) + timeout-minutes: 2 + shell: pwsh + run: ./scripts/release/test_install_windows.ps1 + - name: Rust toolchain (rust-toolchain.toml) shell: bash run: | diff --git a/docs/acceptance.md b/docs/acceptance.md index 6a949365..4ac17fe7 100644 --- a/docs/acceptance.md +++ b/docs/acceptance.md @@ -168,7 +168,7 @@ | 发布提交不重复跑 CI、macOS 并入 CI(2026-09-28 用户反馈:一个 `chore: release` 触发三个工作流,测试和 lint 在前面已经跑过):`changed-code.sh` 在推送事件里把只改 `version` 字段的 `package.json` / `.release-please-manifest.json` 加 CHANGELOG 视为非代码改动,发布提交只跑 `verify-web`(它的 PR 在同一棵树上跑过完整 CI,发布运行构建并检查每个安装包);发布 PR 本身原先仍跑完整 CI,改为构建一次再晋升后也只跑 `verify-web`(见下一行);原 `macos.yml` 并入 `ci.yml` 的 `macos` 矩阵 job(推送 `main` 与手动运行,跳过 PR 与发布提交;当时 `CI Success` 不等它,2026-09-30 起改为等,见下一行),每次推送只剩 CI 与 Release 两个工作流;Release 仍单独存在:release-please 每次推送都要更新发布 PR,且发布需要 CI 不该有的写权限 | `.github/scripts/changed-code.sh`、`.github/workflows/{ci,release}.yml` | `scripts/release/test_changed_code.py@test_the_pushed_release_commit_runs_no_build`、`scripts/release/test_changed_code.py@test_release_pleases_pull_request_runs_no_build`、`scripts/release/test_changed_code.py@test_a_package_json_that_changes_more_than_the_version_is_code`、`scripts/release/test_changed_code.py@test_a_new_branch_and_other_events_run_everything`(另用真实 API 分类:0.0.4 发布提交 `code=false`,代码推送与发布 PR `code=true`) | [x] | | `CI Success` 等 `ci.yml` 的每个作业(2026-09-30 用户问:发版时有 CI 失败了,为什么还是发了版):根因是 `ci-success.needs` 里没有 `macos`,而候选的 `source-gate` 只认 `CI Success`;v0.0.5 的候选 36461665424 基于 06334e6,该提交的 main CI 运行 36461609860 里 `macos-x64` 失败、`CI Success` 却是绿的。现在除 `candidate-status`(负责写规则集状态)和 Codecov 上传外,每个作业都在 needs 里;规则放在 `.github/scripts/ci-success.sh`:文档快速通道可以跳过构建,macOS 两条腿只在 pull request 上允许跳过,推送和手动运行时必须通过;规则集 `release-candidate` 另外要求 `CI Success`(来源固定为 GitHub Actions) | `.github/workflows/ci.yml`(`ci-success`)、`.github/scripts/ci-success.sh`、`.github/workflows/release-candidate.yml`(`source-gate` 注释) | `scripts/release/test_release_workflows.py@test_regression_ci_success_needs_every_job_but_the_advisory_ones`(在修复前的 ci.yml 上失败:少了 `macos`)、`scripts/release/test_release_workflows.py@test_ci_success_decides_with_the_tested_script_and_the_event`、`scripts/release/test_ci_success.py@test_regression_a_red_mac_on_a_push_fails_ci_success`、`scripts/release/test_ci_success.py@test_regression_a_skipped_mac_on_a_push_with_code_fails`、`scripts/release/test_ci_success.py@test_the_macs_may_be_skipped_on_a_pull_request_only`、`scripts/release/test_ci_success.py@test_the_documentation_fast_path_skips_all_but_its_two_jobs` | [x] | | 发布改为构建一次再晋升(2026-09-28 用户选定方案 B;0.0.4 的三次同轮发布都失败了,第三次是重建已有标签时检出的旧树里没有后来加的发布脚本):`release.yml` 成为控制器,release-please 每次更新发布 PR 后派发 `release-candidate.yml`;候选先校验工作流与 PR 身份和 delta 证明(head 相对 `main` 只改 CHANGELOG、manifest 与三份 `package.json` 的版本号,任何模式都不能跳过,因为构建腿带着生产与签名 secrets),四条构建腿在根目录构建被构建的源码、用 `.release-tooling/` 里本工作流提交的发布脚本,`source-gate` 要求基点提交的 `CI Success`,`aggregate` 封存 `candidate-manifest.json` 并做证明,`gate` 在发布 PR head 上写 `Release candidate`;合并后控制器按该状态找到候选,校验身份、目标、大小、摘要与证明,校验 `.sig`,写 `latest.json` 与 `SHA256SUMS`,上传并核对远端字节后发布,全程不编译;新 ruleset `release-candidate` 要求该状态且 PR 与 `main` 同步(只有所有者可绕过,原 ruleset 的禁止删除与强推不受影响),普通 PR 由 `ci.yml` 的 `candidate-status` 写状态,删掉用不上的 `merge_group` 触发;AGENTS.md 规定 PR 一律 squash 合并(用户要求,超大改动或重构例外) | `.github/workflows/{release,release-candidate,ci}.yml`、`.github/scripts/{check-release-delta.py,changed-code.sh}`、`scripts/release/candidate.py`、`docs/runbook.md`、`AGENTS.md` | `scripts/release/test_check_release_delta.py@test_a_release_please_commit_on_the_base_is_proven`、`scripts/release/test_check_release_delta.py@test_an_update_branch_merge_of_the_moved_base_is_proven`、`scripts/release/test_check_release_delta.py@test_code_in_the_release_pr_is_refused_in_every_mode`、`scripts/release/test_check_release_delta.py@test_the_dry_run_escape_of_the_template_does_not_exist`、`scripts/release/test_candidate.py@test_a_complete_candidate_seals_verifies_and_lists_only_its_files`、`scripts/release/test_candidate.py@test_a_missing_leg_is_refused`、`scripts/release/test_candidate.py@test_bytes_changed_after_sealing_are_refused`、`scripts/release/test_candidate.py@test_a_file_planted_after_sealing_is_never_listed`、`scripts/release/test_candidate.py@test_the_identity_must_match_what_the_controller_resolved`、`scripts/release/test_candidate.py@test_a_dry_run_candidate_is_not_promotable`、`scripts/release/test_release_workflows.py@test_the_promote_job_installs_no_toolchain_and_runs_no_build`、`scripts/release/test_release_workflows.py@test_each_leg_builds_the_source_with_tooling_from_the_workflow_commit`、`scripts/release/test_release_workflows.py@test_the_sherpa_fingerprint_is_cleared_in_the_source_target`、`scripts/release/test_release_workflows.py@test_no_merge_queue_entry_without_a_candidate_status`、`scripts/release/test_release_workflows.py@test_pull_requests_that_are_not_releases_get_the_candidate_status`、`scripts/release/test_changed_code.py@test_the_same_diff_from_anyone_else_runs_the_full_ci`(另用真实发布 PR #10 做 delta 证明:`single-parent`,5 个文件,通过;0.0.4 用 backfill 候选 36453776250 发布,四条腿并行,Intel 腿 25.4 分钟是关键路径,晋升运行 36457093133 用时 2 分 14 秒,16 个资产,`gh attestation verify` 核对 dmg 与清单出自 `release-candidate.yml@main`、`latest.json` 与 `SHA256SUMS` 出自 `release.yml@main`。0.0.5 走完整条自动路径:release-please 开 PR #11 后控制器派发候选,delta 证明为 `single-parent`,head 上先是 pending,PR 在候选变绿前一直是 BLOCKED;PR 更新后旧候选被取消、旧 head 记为 failure;候选 36461665424 的 Intel 腿上传产物时 runner DNS 失败,`gh run rerun --failed` 只重跑这一条腿后通过;不带 `--admin` 的 squash 合并被规则放行,合并提交的 tree 等于候选的 tree,控制器运行 36467937767 在合并后 2 分 31 秒发布) | [x] | -| 一行命令安装(2026-09-28 用户要求,同日补充 macOS 两种芯片自动识别):`scripts/install.sh`(Linux 优先 deb、否则 AppImage;Mac 按芯片取 dmg,Rosetta 下也取原生包)与 `scripts/install.ps1`(Windows 静默按用户安装)只从同一个 Release 下载安装包与 `SHA256SUMS`,校验不过就不装;Mac 上装好后向 LaunchServices 登记并交给 Spotlight 索引(2026-09-29 用户反馈:命令行装完后启动台和搜索都找不到,要先 `open -a Voltip` 一次;访达复制的应用会自动登记,脚本复制的只在第一次启动时登记),`install-scripts.yml` 在应用启动前核对 LaunchServices 已列出它;deb 先刷新 apt 的包列表再装(2026-09-29 修复:0.0.4 首次实测时列表比镜像旧,依赖下载 404),刷新失败照样尝试安装;`install-scripts.yml` 在 Linux(deb 与 AppImage)、两种 Mac、Windows PowerShell 5.1 上真装一次并确认 `--version`,AppImage 那一项先装上桌面系统都有、AppImage 不带的图形 / 声音 / 字体 / X11 库 | `scripts/install.sh`、`scripts/install.ps1`、`.github/workflows/install-scripts.yml` | `scripts/release/test_install_script.py@test_the_package_lists_are_refreshed_before_the_install`、`scripts/release/test_install_script.py@test_a_failed_refresh_still_installs`、`scripts/release/test_install_script.py@test_a_checksum_mismatch_installs_nothing`、`scripts/release/test_install_script.py@test_regression_the_installed_app_is_registered_for_launchpad_and_spotlight`(另:运行 36458003579 对 0.0.4 的 Windows 与两种 Mac 通过、Linux 两项失败;修复后的运行 36459102013 里 AppImage 也通过,deb 装好后启动失败,原因是 0.0.4 的 deb 没有依赖它链接的 BLAS,见下一行;运行 36468357553 对 0.0.5 在五个平台上全部通过;运行 36505837626 对 0.0.6 五个平台通过,两种 Mac 上应用首次启动前 LaunchServices 已列出它,Intel 上 Spotlight 也找到了,Apple 芯片的 runner 3 分钟内还没索引完) | [x] | +| 一行命令安装(2026-09-28 用户要求,同日补充 macOS 两种芯片自动识别):`scripts/install.sh`(Linux 优先 deb、否则 AppImage;Mac 按芯片取 dmg,Rosetta 下也取原生包)与 `scripts/install.ps1`(Windows 静默按用户安装)只从同一个 Release 下载安装包与 `SHA256SUMS`,校验不过就不装;Mac 上装好后向 LaunchServices 登记并交给 Spotlight 索引(2026-09-29 用户反馈:命令行装完后启动台和搜索都找不到,要先 `open -a Voltip` 一次;访达复制的应用会自动登记,脚本复制的只在第一次启动时登记),`install-scripts.yml` 在应用启动前核对 LaunchServices 已列出它;deb 先刷新 apt 的包列表再装(2026-09-29 修复:0.0.4 首次实测时列表比镜像旧,依赖下载 404),刷新失败照样尝试安装;`install-scripts.yml` 在 Linux(deb 与 AppImage)、两种 Mac、Windows PowerShell 5.1 上真装一次并确认 `--version`,AppImage 那一项先装上桌面系统都有、AppImage 不带的图形 / 声音 / 字体 / X11 库;下载失败时报出下载地址和收到的错误(2026-11-17 用户反馈:Win11 上 v0.3.1 报「has no SHA256SUMS」,而发布中有这个文件),HTTP 4xx(408、429 除外)立即停止,其他错误最多尝试 3 次;慢速下载不会被中断,只有无法连接或 30 秒收不到数据才算失败 | `scripts/install.sh`、`scripts/install.ps1`、`.github/workflows/install-scripts.yml` | `scripts/release/test_install_script.py@test_the_package_lists_are_refreshed_before_the_install`、`scripts/release/test_install_script.py@test_a_failed_refresh_still_installs`、`scripts/release/test_install_script.py@test_a_checksum_mismatch_installs_nothing`、`scripts/release/test_install_script.py@test_regression_the_installed_app_is_registered_for_launchpad_and_spotlight`、`scripts/release/test_install_script.py@test_regression_checksum_download_errors_keep_the_url_and_http_status`、`scripts/release/test_install_script.py@test_regression_transient_downloads_stop_after_three_attempts`、`scripts/release/test_install_script.py@test_regression_a_slow_download_is_never_cut_off`、`scripts/release/test_install_windows.ps1@regression: a TLS failure keeps its cause and URL, and is tried again`、`scripts/release/test_install_windows.ps1@regression: a proxy refusal (407) is not called a missing checksum`、`scripts/release/test_install_windows.ps1@regression: an installer download cut off midway is tried again`(另:运行 36458003579 对 0.0.4 的 Windows 与两种 Mac 通过、Linux 两项失败;修复后的运行 36459102013 里 AppImage 也通过,deb 装好后启动失败,原因是 0.0.4 的 deb 没有依赖它链接的 BLAS,见下一行;运行 36468357553 对 0.0.5 在五个平台上全部通过;运行 36505837626 对 0.0.6 五个平台通过,两种 Mac 上应用首次启动前 LaunchServices 已列出它,Intel 上 Spotlight 也找到了,Apple 芯片的 runner 3 分钟内还没索引完);2026-11-17 Windows 真机(`scripts/windows-remote.sh`,Windows Server 2025):Windows PowerShell 5.1.26100 与 PowerShell 7.6.9 下 `scripts/release/test_install_windows.ps1` 全部通过;用真实 cmdlet 对本机故障服务器验证连接被拒、404、503、响应头不到、下载中途断开、慢速下载,并从 GitHub 实际下载 0.3.1 安装包,校验通过(安装与结束进程的命令已替换,未安装) | [x] | | Linux 包依赖二进制链接的每个系统库(2026-09-29,安装检查发现):transcribe.cpp 在 Linux 上会链接构建机上找到的系统 BLAS(host decoder 的 `cblas_sgemv`),于是 0.0.4 的二进制需要 `libblas.so.3`,deb 却没有依赖它,apt 装好后程序因缺库启动失败(AppImage 自带这个库,不受影响);deb 改为依赖 `libblas3 | libblas.so.3`,rpm 依赖 `libblas.so.3()(64bit)`;发布的 Linux 腿与 `make linux-x64` 出包前核对二进制链接的每个 soname 都在 `VOLTIP_LINUX_SONAMES` 里(由依赖、包内文件或系统运行库提供),多出任何一个就拒绝出包 | `apps/desktop/src-tauri/tauri.linux.conf.json`、`scripts/lib/artefact-checks.sh`、`.github/workflows/release-candidate.yml`、`scripts/build-linux-x64.sh` | `apps/desktop/src-tauri/tests/bundle.rs@regression_the_linux_packages_depend_on_the_blas_the_binary_links`、`scripts/release/test_artefact_checks.py@test_regression_what_0_0_4_links_is_accounted_for`、`scripts/release/test_artefact_checks.py@test_a_new_library_stops_the_build`、`scripts/release/test_artefact_checks.py@test_a_binary_without_a_dynamic_section_is_not_accounted_for`、`scripts/release/test_release_workflows.py@test_the_linux_leg_refuses_a_library_its_packages_do_not_depend_on`(0.0.5 的 Linux 腿通过核对;它的 deb 依赖 `libblas3 | libblas.so.3`,在干净的 Ubuntu 24.04 上用 apt 装好后能回答 `--version`,安装检查运行 36468357553) | [x] | | AppImage 里的文件每个用户都能读、能运行(2026-11-04,AppImage 目录 PR AppImage/appimage.github.io#10813 的测试:0.2.1 在 firejail `--appimage` 下报 `AppRun.wrapped: Permission denied`):tauri-bundler 2.9.4 把缓存的 `AppRun-x86_64` 写成 0770 并原样打进 AppImage;`make linux-x64` 与发布候选的 Linux 腿在打包前放好固定的 AppRun(`apprun-old` 发布,核对 SHA-256,权限 0755;缓存里内容不对就拒绝出包、不替换),打包后用 `--appimage-offset` 与 `unsquashfs -lln -o` 列出 AppImage 的条目,符号链接以外的条目缺少 o+r、或属主能执行而其他用户不能,就拒绝出包;CI 的 `verify-web` 装 `squashfs-tools`,让这些测试在 CI 上运行 | `scripts/lib/appimage.sh`、`scripts/build-linux-x64.sh`、`.github/workflows/release-candidate.yml`、`.github/workflows/ci.yml` | `scripts/release/test_appimage.py@test_regression_a_cached_file_with_mode_0770_becomes_0755_without_a_download`、`scripts/release/test_appimage.py@test_regression_an_apprun_wrapped_with_mode_0770_stops_the_build`、`scripts/release/test_appimage.py@test_a_cached_file_with_other_contents_fails_and_stays_as_it_is`、`scripts/release/test_appimage.py@test_the_pinned_apprun_goes_into_the_tools_directory`、`scripts/release/test_appimage.py@test_an_entry_other_users_cannot_read_or_run_fails`、`scripts/release/test_release_workflows.py@test_regression_the_linux_leg_bundles_an_apprun_every_user_can_run`、`scripts/release/test_release_workflows.py@test_regression_the_appimage_carries_an_apprun_every_user_can_run`、`scripts/release/test_release_workflows.py@test_the_web_gates_run_the_appimage_check_tests_with_squashfs_tools`(本机 `make linux-x64`,工具目录里是 0770 的 AppRun:修复前打出的 AppImage 里 `AppRun.wrapped` 为 `-rwxrwx---`,修复后的脚本复查它时拒绝出包;修复后重新打包为 `-rwxr-xr-x`,检查通过) | [~](候选腿只在发布 PR 上运行,第一次候选构建时确认;firejail 下的启动待 AppImage 目录重测) | | 真机 headless 运行(§13、§15.6):`--download-model` 用应用自己的下载器(源链、进度走 stderr、stdout 只有结果行、未知 id 为用法错误、全源失败为失败且 stdout 为空);日志只走 stderr、headless 不持有 stdout 锁(2026-09-26 修复:带真实模型的 `--transcribe-file` 曾在识别器第一条日志处死锁);慢源(低于 256 KiB/s 持续 15 s)换下一源并按 `Range` 续传、唯一可用的慢源在第二轮耐心下完;ggml CPU 基线钉为 Haswell 档,低于该档的处理器加载前拒绝而不是非法指令崩溃;`scripts/smoke-native-cli.ps1` 三平台同一脚本(Windows CI 便携 exe + NSIS 静默安装、Linux CI debug 二进制) | `apps/desktop/src-tauri/src/cli.rs`、`apps/desktop/src-tauri/src/lib.rs`、`crates/voltip-asr-local/src/{store,gguf}.rs`、`.cargo/config.toml`、`scripts/smoke-native-cli.ps1`、`.github/workflows/ci.yml` | `apps/desktop/src-tauri/tests/cli.rs@download_model_flag_parses_and_conflicts_with_the_other_actions`、`apps/desktop/src-tauri/tests/cli.rs@download_model_installs_through_the_source_chain_and_keeps_stdout_to_the_result_line`、`apps/desktop/src-tauri/tests/cli.rs@download_model_rejects_an_unknown_id_and_reports_a_dead_chain_with_an_empty_stdout`、`apps/desktop/src-tauri/tests/cli.rs@regression_headless_stdout_carries_only_the_output_and_logs_go_to_stderr`、`apps/desktop/src-tauri/tests/cli.rs@real_binary_transcribe_file_with_debug_logs_finishes_and_prints_json`、`crates/voltip-asr-local/tests/store.rs@a_source_below_the_speed_floor_hands_over_to_the_next_which_resumes_the_part`、`crates/voltip-asr-local/tests/store.rs@a_slow_source_that_is_the_only_working_one_still_finishes_on_the_second_pass`、`crates/voltip-asr-local/src/gguf.rs@regression_a_cpu_below_the_build_baseline_is_refused_with_a_reason` | [x](Linux CI 与本机实跑;Windows:`ci.yml` 的 windows-native 在 Windows Server 上跑便携 zip 与 NSIS 静默安装后的 exe,Tesla T4 真机上 Qwen3-ASR 走 Vulkan 见 `docs/acceptance/gpu/vulkan-windows-nvidia.txt`;macOS:CI 的 `macos` job 在 macos-15 / macos-15-intel 上跑 `.app` 内的二进制) | diff --git a/docs/site/guide/install.md b/docs/site/guide/install.md index dcf11a34..d8405288 100644 --- a/docs/site/guide/install.md +++ b/docs/site/guide/install.md @@ -22,6 +22,8 @@ curl -fsSL https://raw.githubusercontent.com/sunerpy/voltip/main/scripts/install The script picks the package for the computer and downloads it together with the release's `SHA256SUMS`. Nothing is installed unless the checksum matches. +If a download fails, the script shows the address and the error it received. Check that this computer, or its proxy, can open the [releases page](https://github.com/sunerpy/voltip/releases). + - **Windows**: the per-user installer runs silently, without an administrator prompt, and starts Voltip when it is done. - **Linux**: the `.deb` is installed through apt where apt is available, which asks for your password; otherwise the AppImage goes to `~/.local/bin` with an entry in the applications menu. - **macOS**: the dmg for the Mac's processor is chosen automatically, also from a Rosetta terminal. The app goes to `/Applications`, or to `~/Applications` when that folder is not writable. Installed this way, it opens without the Gatekeeper prompt. diff --git a/docs/site/zh/guide/install.md b/docs/site/zh/guide/install.md index 7e5ad0c1..6f63f835 100644 --- a/docs/site/zh/guide/install.md +++ b/docs/site/zh/guide/install.md @@ -22,6 +22,8 @@ curl -fsSL https://raw.githubusercontent.com/sunerpy/voltip/main/scripts/install 脚本会为这台电脑选择合适的安装包,并连同发布附带的 `SHA256SUMS` 一起下载。校验不通过时不会安装任何内容。 +下载失败时,脚本会显示下载地址和收到的错误。请检查这台电脑或所用代理能否打开[发布页](https://github.com/sunerpy/voltip/releases)。 + - **Windows**:静默运行按用户安装的安装器,不需要管理员授权,安装完成后自动启动 Voltip。 - **Linux**:有 apt 的系统通过 apt 安装 `.deb`,会要求输入密码;否则把 AppImage 放到 `~/.local/bin`,并添加到应用菜单。 - **macOS**:自动识别处理器类型(在 Rosetta 终端中同样适用),下载对应的 dmg,把应用放进 `/Applications`;没有写入权限时放进 `~/Applications`。用这种方式安装的应用,打开时不会被 Gatekeeper 拦下。 diff --git a/scripts/install.ps1 b/scripts/install.ps1 index f4fd6731..02c1c5b7 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -17,7 +17,6 @@ $Repo = "sunerpy/voltip" $ChecksumFile = "SHA256SUMS" function Stop-Install($Message) { - Write-Host "voltip-install: $Message" -ForegroundColor Red throw "voltip-install: $Message" } @@ -25,6 +24,42 @@ function Say($Message) { Write-Host "voltip-install: $Message" } +# One GET with the parameters Windows PowerShell 5.1 and PowerShell 7 share, up to three times. An +# HTTP 4xx other than 408 and 429 is final; anything else (a 5xx, a timeout, a refused, dropped or +# failed TLS connection) is tried again. A failed request does not mean that the release lacks the +# file, so the last error names the URL and keeps every inner message. -TimeoutSec bounds only the +# wait for the response headers. A download is never cut off for being slow, only when its data +# stops arriving: for 30 s where the cmdlet has -OperationTimeoutSeconds (PowerShell 7.4 and +# later); Windows PowerShell 5.1 gives up on a read after 300 s by itself. +function Invoke-InstallRequest([string]$Uri, [string]$OutFile) { + $Request = @{ + Uri = $Uri + UseBasicParsing = $true + TimeoutSec = 30 + Headers = @{ "User-Agent" = "voltip-install" } + } + if ((Get-Command Microsoft.PowerShell.Utility\Invoke-WebRequest).Parameters.ContainsKey('OperationTimeoutSeconds')) { + $Request.OperationTimeoutSeconds = 30 + } + for ($Attempt = 1; $Attempt -le 3; $Attempt++) { + try { + if ($OutFile) { Invoke-WebRequest @Request -OutFile $OutFile } else { Invoke-RestMethod @Request } + return + } catch { + $Status = $null + $Response = $_.Exception.PSObject.Properties['Response'] + if ($Response -and $Response.Value) { $Status = [int]$Response.Value.StatusCode } + $Detail = $_.Exception.Message + for ($Inner = $_.Exception.InnerException; $Inner; $Inner = $Inner.InnerException) { $Detail += " --> " + $Inner.Message } + if ($Status) { $Detail = "HTTP ${Status}: $Detail" } + $Final = $Status -ge 400 -and $Status -lt 500 -and $Status -notin @(408, 429) + if ($Final -or $Attempt -eq 3) { Stop-Install "could not download ${Uri}: $Detail" } + Say "could not download ${Uri} (attempt ${Attempt}/3): $Detail; retrying in 1s" + Start-Sleep -Seconds 1 + } + } +} + # Windows PowerShell 5.1 on an older Windows 10 may still offer TLS 1.0 only; GitHub needs 1.2. [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 @@ -38,9 +73,7 @@ if ($env:VOLTIP_VERSION) { $Version = $env:VOLTIP_VERSION -replace '^v', '' } else { Say "finding the latest release" - $Release = Invoke-RestMethod -UseBasicParsing ` - -Uri "https://api.github.com/repos/$Repo/releases/latest" ` - -Headers @{ "User-Agent" = "voltip-install" } + $Release = Invoke-InstallRequest -Uri "https://api.github.com/repos/$Repo/releases/latest" $Version = $Release.tag_name -replace '^v', '' } # The version goes into URLs and file names: digits and dots, and an optional pre-release tail. @@ -55,20 +88,21 @@ $TempDir = New-Item -ItemType Directory -Path (Join-Path $env:TEMP ("voltip-" + try { $Installer = Join-Path $TempDir $Asset $Checksums = Join-Path $TempDir $ChecksumFile - Say "downloading $Asset (Voltip $Version)" - try { - Invoke-WebRequest -UseBasicParsing -Uri "$BaseUrl/$ChecksumFile" -OutFile $Checksums - } catch { - Stop-Install "release v$Version has no $ChecksumFile (is $Version a Voltip release?)" - } + Say "downloading $ChecksumFile (Voltip $Version)" + Invoke-InstallRequest -Uri "$BaseUrl/$ChecksumFile" -OutFile $Checksums $Escaped = [Regex]::Escape($Asset) $Line = Get-Content $Checksums | Where-Object { $_ -match "^[0-9a-fA-F]{64}\s+\*?$Escaped$" } | Select-Object -First 1 - if (-not $Line) { Stop-Install "release v$Version has no $Asset" } - Invoke-WebRequest -UseBasicParsing -Uri "$BaseUrl/$Asset" -OutFile $Installer + if (-not $Line) { Stop-Install "$ChecksumFile has no checksum for $Asset in release v$Version" } + Say "downloading $Asset (Voltip $Version)" + Invoke-InstallRequest -Uri "$BaseUrl/$Asset" -OutFile $Installer $Expected = ($Line -split '\s+')[0].ToLowerInvariant() $Actual = (Get-FileHash -Algorithm SHA256 -Path $Installer).Hash.ToLowerInvariant() - if ($Actual -ne $Expected) { Stop-Install "checksum mismatch for ${Asset}: nothing was installed" } + # Windows PowerShell 5.1 can end a download whose connection closes early as if it were complete; + # the size downloaded tells that apart from a changed file. + if ($Actual -ne $Expected) { + Stop-Install "checksum mismatch for $Asset ($((Get-Item -LiteralPath $Installer).Length) bytes downloaded): nothing was installed" + } Say "SHA-256 matches $ChecksumFile" # A running Voltip holds its files; the installer would stop at it. diff --git a/scripts/install.sh b/scripts/install.sh index 1544a857..97176552 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -47,12 +47,16 @@ for arg in "$@"; do esac done +# download . A slow download is never cut off: it ends only when it +# cannot connect or its data stops arriving for 30 s. Timeouts and HTTP 408, 429, 500, 502, 503 +# and 504 are tried up to three times (wget also retries a dropped connection); other errors such +# as a 404 stop at once. The tool's own message, TLS and proxy failures included, stays on stderr. if command -v curl >/dev/null 2>&1; then - download() { curl -fsSL --retry 3 "$1" -o "$2"; } - fetch() { curl -fsSL --retry 3 "$1"; } + download() { curl -fsSL --connect-timeout 15 --speed-limit 1 --speed-time 30 --retry 2 --retry-delay 1 "$1" -o "$2"; } elif command -v wget >/dev/null 2>&1; then - download() { wget -qO "$2" "$1"; } - fetch() { wget -qO - "$1"; } + # --timeout bounds a stalled DNS lookup, connection or read, not the whole download. Keep its + # diagnostics: -q hides failures, and -nv hides the status of retried HTTP errors. + download() { wget --timeout=30 --tries=3 --waitretry=1 --retry-on-http-error=408,429,500,502,503,504 -O "$2" "$1"; } else err "curl or wget is required" fi @@ -93,7 +97,9 @@ if [ -n "${VOLTIP_VERSION:-}" ]; then version=$(printf '%s' "$VOLTIP_VERSION" | sed 's/^v//') else info "finding the latest release" - tag=$(fetch "https://api.github.com/repos/${REPO}/releases/latest" | + latest_url="https://api.github.com/repos/${REPO}/releases/latest" + metadata=$(download "$latest_url" -) || err "could not download $latest_url" + tag=$(printf '%s\n' "$metadata" | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -1) [ -n "$tag" ] || err "could not find the latest release" version=$(printf '%s' "$tag" | sed 's/^v//') @@ -117,16 +123,17 @@ cleanup() { } trap cleanup EXIT INT TERM -info "downloading ${asset} (Voltip ${version})" +info "downloading ${CHECKSUM_FILE} (Voltip ${version})" download "${base_url}/${CHECKSUM_FILE}" "$tmp/$CHECKSUM_FILE" || - err "release v${version} has no ${CHECKSUM_FILE} (is ${version} a Voltip release?)" + err "could not download ${base_url}/${CHECKSUM_FILE}" expected=$(awk -v name="$asset" '{ file = $2 sub(/^\*/, "", file) if (file == name) { print $1; exit } }' "$tmp/$CHECKSUM_FILE") -[ -n "$expected" ] || err "release v${version} has no ${asset}" -download "${base_url}/${asset}" "$tmp/$asset" || err "could not download ${asset}" +[ -n "$expected" ] || err "${CHECKSUM_FILE} has no checksum for ${asset}" +info "downloading ${asset} (Voltip ${version})" +download "${base_url}/${asset}" "$tmp/$asset" || err "could not download ${base_url}/${asset}" if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum "$tmp/$asset" | awk '{print $1}') diff --git a/scripts/release/test_install_script.py b/scripts/release/test_install_script.py index c01b97f6..15d0e34b 100644 --- a/scripts/release/test_install_script.py +++ b/scripts/release/test_install_script.py @@ -7,10 +7,17 @@ from __future__ import annotations import hashlib +import http.server +import json import os +import shutil +import signal import stat import subprocess +import sys import tempfile +import threading +import time import unittest from pathlib import Path @@ -32,7 +39,7 @@ done src="$FIXTURES/${url##*/}" [ -f "$src" ] || exit 22 -if [ -n "$out" ]; then cp "$src" "$out"; else cat "$src"; fi +if [ -n "$out" ] && [ "$out" != - ]; then cp "$src" "$out"; else cat "$src"; fi """, "apt-get": """#!/bin/sh echo "$*" >>"$APT_LOG" @@ -42,7 +49,10 @@ } -class DebInstall(unittest.TestCase): +class FakeRelease(unittest.TestCase): + """A release with the .deb, served by fake `curl` (or by a real tool in Downloads), installed + by fake `apt-get` and `sudo`.""" + def setUp(self) -> None: self._tmp = tempfile.TemporaryDirectory() self.addCleanup(self._tmp.cleanup) @@ -66,7 +76,7 @@ def write_sums(self, digest: str) -> None: ) def install(self, **env: str) -> tuple[int, list[str], str]: - done = subprocess.run( + with subprocess.Popen( ["sh", str(SCRIPT)], env={ **os.environ, @@ -77,12 +87,22 @@ def install(self, **env: str) -> tuple[int, list[str], str]: "VOLTIP_PACKAGE": "deb", **env, }, - capture_output=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, - ) + start_new_session=True, + ) as process: + try: + _, stderr = process.communicate(timeout=20) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.communicate() + raise calls = self.log.read_text(encoding="utf-8").splitlines() if self.log.exists() else [] - return done.returncode, calls, done.stderr + return process.returncode, calls, stderr + +class DebInstall(FakeRelease): def test_the_package_lists_are_refreshed_before_the_install(self) -> None: # Regression (install-scripts.yml, 0.0.4): with lists older than the mirror, apt asked for # dependency versions the mirror no longer had and failed with 404. @@ -106,6 +126,173 @@ def test_a_checksum_mismatch_installs_nothing(self) -> None: self.assertEqual(calls, []) +class Downloads: + """Exercise the real download tool against an owned, local fake release: only the tool's + destination URL is replaced, its own timeouts, retries and error messages stay real. The + installed package and apt stay fake, as in DebInstall. CurlDownloads and WgetDownloads run it.""" + + tool: str + + def serve(self, asset: str = "", status: int = 0, failures: int = 99) -> list[str]: + """Serve the release, failing `asset` with `status` the first `failures` times.""" + executable = shutil.which(self.tool) + if executable is None: + self.skipTest(f"{self.tool} is not installed") + requests: list[str] = [] + fixtures = self.fixtures + + class Release(http.server.BaseHTTPRequestHandler): + def do_GET(self) -> None: + name = self.path.rsplit("/", 1)[-1] + requests.append(name) + if name == asset and requests.count(name) <= failures: + self.send_error(status) + return + body = b'{"tag_name":"v0.0.4"}' if name == "latest" else (fixtures / name).read_bytes() + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args: object) -> None: + pass + + server = http.server.HTTPServer(("127.0.0.1", 0), Release) + server.timeout = 0.1 + stopped = threading.Event() + + def run() -> None: + deadline = time.monotonic() + 15 + while not stopped.is_set() and time.monotonic() < deadline: + server.handle_request() + + worker = threading.Thread(target=run, daemon=True) + worker.start() + + def stop() -> None: + stopped.set() + worker.join(timeout=2) + server.server_close() + + self.addCleanup(stop) + # The tool's arguments, one JSON list per run, before the URL is replaced. + self.runs_log = self.root / "runs.log" + (self.bin / self.tool).write_text( + f"#!{sys.executable}\nimport json, os, sys\n" + f"with open({str(self.runs_log)!r}, 'a', encoding='utf-8') as log:\n" + " log.write(json.dumps(sys.argv[1:]) + '\\n')\n" + f"args = ['http://127.0.0.1:{server.server_port}/' + arg.rsplit('/', 1)[-1] " + "if arg.startswith('https://') else arg for arg in sys.argv[1:]]\n" + "os.environ['no_proxy'] = os.environ['NO_PROXY'] = '127.0.0.1'\n" + f"os.execv({executable!r}, [{executable!r}, *args])\n", + encoding="utf-8", + ) + (self.bin / self.tool).chmod(0o755) + if self.tool == "wget": + (self.bin / "curl").unlink() + # No system PATH directory: each contains curl on the developer and CI hosts. + # Only the commands this fake .deb installation needs are made available. + for command in ("sh", "sed", "head", "grep", "mktemp", "rm", "awk", "chmod", "id"): + path = shutil.which(command) + assert path is not None, command + (self.bin / command).symlink_to(path) + for command in ("sha256sum", "shasum"): + if path := shutil.which(command): + (self.bin / command).symlink_to(path) + return requests + + def download(self, **env: str) -> tuple[int, list[str], str]: + return self.install(**({"PATH": str(self.bin)} if self.tool == "wget" else {}), **env) + + def runs(self) -> list[list[str]]: + return [json.loads(line) for line in self.runs_log.read_text(encoding="utf-8").splitlines()] + + def test_regression_checksum_download_errors_keep_the_url_and_http_status(self) -> None: + # User report 2026-11-17: v0.3.1 said "has no SHA256SUMS" even though the release + # carried it. install.sh had the same blanket error as the Windows installer. + requests = self.serve("SHA256SUMS", 403) + code, calls, stderr = self.download() + self.assertEqual(code, 1, stderr) + self.assertIn("https://github.com/sunerpy/voltip/releases/download/v0.0.4/SHA256SUMS", stderr) + self.assertIn("403", stderr) + self.assertNotIn("has no SHA256SUMS", stderr) + self.assertEqual(requests, ["SHA256SUMS"], "permanent errors are not retried") + self.assertEqual(calls, []) + + def test_regression_missing_checksums_keep_the_404_response(self) -> None: + requests = self.serve("SHA256SUMS", 404) + code, calls, stderr = self.download() + self.assertEqual(code, 1, stderr) + self.assertIn("404", stderr) + self.assertIn("/v0.0.4/SHA256SUMS", stderr) + self.assertEqual(requests, ["SHA256SUMS"]) + self.assertEqual(calls, []) + + def test_regression_latest_lookup_does_not_hide_a_download_failure(self) -> None: + requests = self.serve("latest", 403) + code, calls, stderr = self.download(VOLTIP_VERSION="") + self.assertEqual(code, 1, stderr) + self.assertIn("https://api.github.com/repos/sunerpy/voltip/releases/latest", stderr) + self.assertIn("403", stderr) + self.assertEqual(requests, ["latest"]) + self.assertEqual(calls, []) + + def test_regression_package_download_errors_name_the_failed_url(self) -> None: + self.serve(DEB, 404) + code, calls, stderr = self.download() + self.assertEqual(code, 1, stderr) + self.assertIn(f"https://github.com/sunerpy/voltip/releases/download/v0.0.4/{DEB}", stderr) + self.assertIn("404", stderr) + self.assertEqual(calls, []) + + def test_regression_transient_downloads_retry_and_still_require_the_checksum(self) -> None: + requests = self.serve("SHA256SUMS", 503, failures=1) + self.write_sums("f" * 64) + code, calls, stderr = self.download() + self.assertEqual(code, 1, stderr) + self.assertEqual(requests, ["SHA256SUMS", "SHA256SUMS", DEB]) + self.assertIn("checksum mismatch", stderr) + self.assertEqual(calls, []) + + def test_regression_transient_downloads_stop_after_three_attempts(self) -> None: + requests = self.serve("SHA256SUMS", 503) + code, calls, stderr = self.download() + self.assertEqual(code, 1, stderr) + self.assertEqual(requests, ["SHA256SUMS"] * 3) + self.assertIn("503", stderr) + self.assertIn("/v0.0.4/SHA256SUMS", stderr) + self.assertEqual(calls, []) + + def test_regression_a_slow_download_is_never_cut_off(self) -> None: + # Review 2026-11-17: curl's `--max-time 600` ended every attempt at a package download + # slower than about 200 KB/s for the 117 MiB AppImage (80 KB/s for the 47 MiB deb), and + # each retry started over; with curl 8.5, 1 MB at 100 KB/s under `--max-time 5` stopped + # three times at 500 000 bytes. Only a stall may end a download. Checked by the tool's + # arguments: a real slow download would take ten minutes. + self.serve() + code, calls, stderr = self.download(VOLTIP_VERSION="") + self.assertEqual(code, 0, stderr) + runs = self.runs() + urls = [next(arg for arg in run if arg.startswith("https://")) for run in runs] + self.assertEqual([url.rsplit("/", 1)[-1] for url in urls], ["latest", "SHA256SUMS", DEB]) + for run in runs: + with self.subTest(run=run): + if self.tool == "curl": + self.assertEqual([a for a in run if a in ("-m", "--max-time") or a.startswith("--max-time=")], []) + self.assertEqual(run[run.index("--speed-time") + 1], "30") + self.assertEqual(run[run.index("--speed-limit") + 1], "1") + else: + self.assertIn("--timeout=30", run) + + +class CurlDownloads(Downloads, FakeRelease): + tool = "curl" + + +class WgetDownloads(Downloads, FakeRelease): + tool = "wget" + + DMG = "Voltip_0.0.4_aarch64.dmg" # A Mac on Apple silicon: hdiutil "mounts" a directory holding Voltip.app, ditto copies it, and diff --git a/scripts/release/test_install_windows.ps1 b/scripts/release/test_install_windows.ps1 new file mode 100644 index 00000000..81456dd6 --- /dev/null +++ b/scripts/release/test_install_windows.ps1 @@ -0,0 +1,167 @@ +# Run with Windows PowerShell 5.1 or PowerShell 7: +# powershell -NoProfile -File scripts/release/test_install_windows.ps1 +# Exercises the whole `irm | iex` entry with fake HTTP and process ports; never downloads or +# executes a real installer. User report 2026-11-17: Win11 / v0.3.1 said "has no SHA256SUMS" +# even though the published file existed. A TLS/proxy error must retain its actual cause. +# Review 2026-11-17, with the real cmdlet in PowerShell 7.6.3: a connection that dropped after +# 1000 bytes ended the download at its first attempt (an AggregateException around "The response +# ended prematurely"), and a body that stopped after 1000 bytes held `Invoke-WebRequest +# -TimeoutSec 3` until the probe was killed at 280 s: -TimeoutSec bounds the response headers only. +$ErrorActionPreference = 'Stop' +Add-Type -AssemblyName System.Net.Http +$InstallerScript = Get-Content -Raw (Join-Path $PSScriptRoot '../install.ps1') +$TestRoot = Join-Path ([IO.Path]::GetTempPath()) ('voltip-install-tests-' + [guid]::NewGuid()) +$SavedEnvironment = @{} +foreach ($Name in @('TEMP', 'LOCALAPPDATA', 'PROCESSOR_ARCHITECTURE', 'PROCESSOR_ARCHITEW6432', 'VOLTIP_VERSION')) { + $SavedEnvironment[$Name] = [Environment]::GetEnvironmentVariable($Name, 'Process') +} +$Payload = [Text.Encoding]::UTF8.GetBytes('a fake Voltip Windows installer') +$Hasher = [Security.Cryptography.SHA256]::Create() +try { $Digest = [BitConverter]::ToString($Hasher.ComputeHash($Payload)).Replace('-', '').ToLowerInvariant() } +finally { $Hasher.Dispose() } +# PowerShell 7.4 added -OperationTimeoutSeconds, which ends a download whose data stops arriving. +$Edition = $PSVersionTable.PSVersion +$ReadLimit = if ($Edition.Major -gt 7 -or ($Edition.Major -eq 7 -and $Edition.Minor -ge 4)) { 30 } else { $null } + +function Assert-Install($Condition, $Message) { + if (-not $Condition) { throw $Message } +} + +function Invoke-FakeRequest($Uri, $OutFile, $TimeoutSec, $OperationTimeoutSeconds) { + $Target = if ($Uri -like '*/latest') { 'latest' } elseif ($Uri -like '*/SHA256SUMS') { 'sums' } else { 'exe' } + $script:Requests.Add([pscustomobject]@{ Target = $Target; Uri = $Uri; TimeoutSec = $TimeoutSec; ReadLimit = $OperationTimeoutSeconds }) + if ($Target -eq $script:Case.Target -and $script:Remaining -gt 0) { + $script:Remaining-- + if ($OutFile) { [IO.File]::WriteAllText($OutFile, 'partial failed download') } + switch ($script:Case.Failure) { + 'tls' { throw [Net.WebException]::new('Could not create SSL/TLS secure channel', [Net.WebExceptionStatus]::SecureChannelFailure) } + 'tls7' { throw [Net.Http.HttpRequestException]::new('The SSL connection could not be established', [Security.Authentication.AuthenticationException]::new('The remote certificate is invalid')) } + 'timeout' { throw [Net.WebException]::new('The operation has timed out', [Net.WebExceptionStatus]::Timeout) } + 'timeout7' { throw [Threading.Tasks.TaskCanceledException]::new('The request was canceled due to the configured timeout') } + 'connect7' { throw [Net.Http.HttpRequestException]::new('Connection refused') } + 'cut' { throw [AggregateException]::new([IO.IOException]::new('The response ended prematurely. (ResponseEnded)')) } + default { + # Both PowerShell editions expose HTTP status through Exception.Response.StatusCode. + $Failure = [Exception]::new('mock HTTP failure ' + $script:Case.Failure) + $Failure | Add-Member NoteProperty Response ([pscustomobject]@{ StatusCode = [int]$script:Case.Failure }) + throw $Failure + } + } + } + if ($Target -eq 'latest') { return [pscustomobject]@{ tag_name = 'v0.3.1' } } + if ($Target -eq 'sums') { + $Sum = if ($script:Case.Corrupt) { '0' * 64 } else { $Digest } + $Asset = if ($script:Case.MissingEntry) { 'other-file.exe' } else { 'Voltip_0.3.1_x64-setup.exe' } + [IO.File]::WriteAllText($OutFile, "$Sum $Asset`n") + } else { + [IO.File]::WriteAllBytes($OutFile, $Payload) + } +} + +function Invoke-WebRequest { + param($Uri, $OutFile, [switch]$UseBasicParsing, $TimeoutSec, $OperationTimeoutSeconds, $Headers) + Assert-Install $UseBasicParsing 'web requests must keep -UseBasicParsing for PowerShell 5.1' + Invoke-FakeRequest $Uri $OutFile $TimeoutSec $OperationTimeoutSeconds +} +function Invoke-RestMethod { + param($Uri, [switch]$UseBasicParsing, $TimeoutSec, $OperationTimeoutSeconds, $Headers) + Assert-Install $UseBasicParsing 'release requests must keep -UseBasicParsing' + Invoke-FakeRequest $Uri '' $TimeoutSec $OperationTimeoutSeconds +} +function Start-Sleep { param($Seconds) $script:Waits.Add($Seconds) } +function Get-Process { param($Name, $ErrorAction) return $null } +function Get-ItemProperty { param($Path, $ErrorAction) return $null } +function Start-Process { + param($FilePath, $ArgumentList, [switch]$Wait, [switch]$PassThru) + Assert-Install ($ArgumentList -eq '/S' -and $Wait -and $PassThru) 'only a silent fake install is allowed' + Assert-Install ((Get-FileHash -Algorithm SHA256 $FilePath).Hash.ToLowerInvariant() -eq $Digest) 'unverified installer reached Start-Process' + $script:Installed++ + return [pscustomobject]@{ ExitCode = 0 } +} + +# A 4xx answer other than 408 or 429 is final; every other failure is tried up to three times. +$Cases = @( + @{ Name = 'regression: a TLS failure keeps its cause and URL, and is tried again'; Target = 'sums'; Failure = 'tls'; Failures = 3; Attempts = 3; Error = 'SSL/TLS secure channel' }, + @{ Name = 'regression: a nested PowerShell 7 failure keeps every inner message'; Target = 'sums'; Failure = 'tls7'; Failures = 3; Attempts = 3; Error = 'remote certificate is invalid' }, + @{ Name = 'regression: a missing checksum file (404) is not tried again'; Target = 'sums'; Failure = '404'; Failures = 3; Attempts = 1; Error = '404' }, + @{ Name = 'regression: a proxy refusal (407) is not called a missing checksum'; Target = 'sums'; Failure = '407'; Failures = 3; Attempts = 1; Error = '407' }, + @{ Name = 'regression: a rate limit (429) is tried again'; Target = 'sums'; Failure = '429'; Failures = 1; Attempts = 2; Install = 1 }, + @{ Name = 'regression: a server error (503) is tried again'; Target = 'sums'; Failure = '503'; Failures = 1; Attempts = 2; Install = 1 }, + @{ Name = 'regression: a checksum timeout is tried again'; Target = 'sums'; Failure = 'timeout'; Failures = 1; Attempts = 2; Install = 1 }, + @{ Name = 'regression: an installer download cut off midway is tried again'; Target = 'exe'; Failure = 'cut'; Failures = 1; Attempts = 2; Install = 1 }, + @{ Name = 'regression: the latest lookup stops after three attempts'; Target = 'latest'; Failure = 'timeout7'; Failures = 3; Attempts = 3; Latest = $true; Error = 'configured timeout' }, + @{ Name = 'regression: checksum retry exhaustion never downloads the installer'; Target = 'sums'; Failure = 'connect7'; Failures = 3; Attempts = 3; Error = 'Connection refused' }, + @{ Name = 'regression: installer retry exhaustion installs nothing'; Target = 'exe'; Failure = 'cut'; Failures = 3; Attempts = 3; Error = 'ended prematurely' }, + @{ Name = 'regression: missing checksum entry installs nothing'; Target = 'none'; MissingEntry = $true; Error = 'has no checksum for Voltip_0.3.1_x64-setup.exe' }, + # A Windows Server 2025 machine, 2026-11-17: Windows PowerShell 5.1.26100 ended a download whose + # connection closed after 1000 of 100000 bytes as if it were complete; only the checksum caught it. + @{ Name = 'regression: a mismatched checksum names the size downloaded and installs nothing'; Target = 'none'; Corrupt = $true; Error = 'checksum mismatch for Voltip_0.3.1_x64-setup.exe (31 bytes downloaded)' }, + @{ Name = 'regression: latest release installs only after verification'; Target = 'none'; Latest = $true; Install = 1 } +) +$Failures = 0 +try { + New-Item -ItemType Directory -Path $TestRoot | Out-Null + foreach ($script:Case in $Cases) { + $CaseDir = Join-Path $TestRoot ([guid]::NewGuid().ToString() + ' with spaces') + New-Item -ItemType Directory -Path $CaseDir | Out-Null + $env:TEMP = $CaseDir + $env:LOCALAPPDATA = $CaseDir + $env:PROCESSOR_ARCHITECTURE = 'AMD64' + $env:PROCESSOR_ARCHITEW6432 = '' + $env:VOLTIP_VERSION = if ($Case.Latest) { '' } else { '0.3.1' } + $script:Remaining = [int]$Case.Failures + $script:Installed = 0 + $script:Requests = [Collections.Generic.List[object]]::new() + $script:Waits = [Collections.Generic.List[int]]::new() + $script:InstallFailure = $null + # Match the README entry, isolate its variables, and capture its host output as well as the + # final exception so a double error line cannot hide in a passing assertion. + $Messages = & { + try { Invoke-Expression $InstallerScript } catch { $script:InstallFailure = $_ } + } 6>&1 + $Log = ($Messages | Out-String) + try { + if ($Case.Error) { + Assert-Install ($null -ne $InstallFailure) 'installation unexpectedly succeeded' + $ErrorText = $InstallFailure.Exception.Message + Assert-Install ($ErrorText.Contains($Case.Error)) "lost original cause: $ErrorText" + Assert-Install (-not $Log.Contains($ErrorText)) 'the final error was printed twice' + Assert-Install (-not $ErrorText.Contains('has no SHA256SUMS')) "download failure misreported: $ErrorText" + if ($Case.Target -ne 'none') { + $FailedRequest = @($Requests | Where-Object { $_.Target -eq $Case.Target })[-1] + Assert-Install ($ErrorText.Contains($FailedRequest.Uri)) "missing download URL: $ErrorText" + } + } else { + Assert-Install ($null -eq $InstallFailure) "installation failed: $InstallFailure" + Assert-Install ($Log.Contains('SHA-256 matches SHA256SUMS')) 'verification did not finish' + } + Assert-Install ($Installed -eq [int]$Case.Install) "installer calls: $Installed" + if ($Case.Attempts) { + $Attempts = @($Requests | Where-Object { $_.Target -eq $Case.Target }).Count + Assert-Install ($Attempts -eq $Case.Attempts) "expected $($Case.Attempts) attempts, got $Attempts" + Assert-Install ($Waits.Count -eq ($Case.Attempts - 1)) 'unexpected retry waits' + } + # Every request waits 30 s for its response headers; where the cmdlet can (7.4 and later), + # a download also ends when its data stops arriving for 30 s. A slow one is never cut off. + foreach ($Request in $Requests) { + Assert-Install ($Request.TimeoutSec -eq 30) "unexpected header timeout for $($Request.Target): $($Request.TimeoutSec)" + Assert-Install ($Request.ReadLimit -eq $ReadLimit) "unexpected read timeout for $($Request.Target): $($Request.ReadLimit)" + } + if ($Case.Error -and $Case.Target -ne 'exe' -and -not $Case.Corrupt) { + Assert-Install (@($Requests | Where-Object { $_.Target -eq 'exe' }).Count -eq 0) 'installer downloaded after checksum failure' + } + Assert-Install (@(Get-ChildItem -LiteralPath $CaseDir -Force).Count -eq 0) 'temporary download files were not cleaned' + Write-Output "PASS: $($Case.Name)" + } catch { + $Failures++ + Write-Output "FAIL: $($Case.Name): $($_.Exception.Message)" + } + } +} finally { + foreach ($Name in $SavedEnvironment.Keys) { + [Environment]::SetEnvironmentVariable($Name, $SavedEnvironment[$Name], 'Process') + } + Remove-Item -LiteralPath $TestRoot -Recurse -Force -ErrorAction SilentlyContinue +} +if ($Failures) { throw "$Failures installer regression test(s) failed" } +Write-Output "$($Cases.Count) installer regression tests passed (PowerShell $($PSVersionTable.PSVersion))"