A local-first multi-agent app development platform, built on PenguinHarness
Unify the download-source rule across both installers and the download page (#403)
Yaowei Zheng8e4a77d492a0
diff --git a/install.ps1 b/install.ps1index fe203239..118a7fca 100644--- a/install.ps1+++ b/install.ps1@@ -7,7 +7,8 @@# installer defaults to its own version, an unstamped source copy to latest# $env:PENGUIN_INSTALL_DIR = "<dir>" install dir; default $env:USERPROFILE\.penguin# $env:PENGUIN_ARCHIVE = "<file>" install a local Release zip without network access (same as -ArchivePath)-# $env:PENGUIN_DOWNLOAD_SOURCE = "auto|oss|github" choose the online source; default auto (OSS, then same-version GitHub)+# $env:PENGUIN_DOWNLOAD_SOURCE = "auto|oss|github" choose the online source; default auto+# (speed-probed, with the same-version other source as fallback)# $env:PENGUIN_DOWNLOAD_SPEED_PROBE = "0" disable same-version OSS/GitHub probe timing in auto mode# $env:PENGUIN_DOWNLOAD_BASE_URL = "https://..." exact online asset directory selected by the stable forwarder# $env:PENGUIN_DOWNLOAD_FALLBACK_BASE_URL = "https://..." fallback for PENGUIN_DOWNLOAD_BASE_URL@@ -43,11 +44,29 @@ $OssReleaseRoot = "$OssOrigin/releases"$GitHubReleaseRoot = "$Repo/releases/download"$GitHubLatestBase = "$Repo/releases/latest/download"$Asset = "penguin-win32-x64.zip"-$SpeedProbeTotalTimeoutSeconds = 16+# Auto-mode source selection, one rule shared by install.ps1, install.sh and the download page on+# penguin.ooo (packages/landing/src/lib/download-source.ts):+#+# 1. Measure GitHub on the release's large probe file. At or above+# $SpeedProbeGitHubMinBytesPerSecond it wins outright and OSS is never touched.+# 2. Only below that is OSS measured, and it takes over only when it is more than+# $SpeedProbeOssSwitchRatio of GitHub — a mirror that is merely a little quicker does not+# justify its bandwidth bill, and a slow GitHub download still resumes.+#+# GitHub is the free source, so every tie and every unmeasurable comparison stays there. The two+# constants are duplicated because these three implementations cannot import from each other — an+# installer is a standalone file fetched over the network. Change them in all three at once, which+# scripts/test-installer.sh pins.+#+# The total budget covers the whole probe: manifest, the small reachability pair, and up to two+# large probes. It is deliberately the sum of their caps, so the second large probe always gets its+# full window rather than being squeezed into declaring a healthy mirror unreachable.$SpeedProbeManifestTimeoutSeconds = 5$SpeedProbeSmallTimeoutSeconds = 5$SpeedProbeLargeTimeoutSeconds = 8+$SpeedProbeTotalTimeoutSeconds = 26$SpeedProbeGitHubMinBytesPerSecond = 262144+$SpeedProbeOssSwitchRatio = 1.5$PayloadName = "payload.zip"# The release workflow replaces this token with the immutable tag before publishing both the# standalone installer and the copy sealed inside the Windows bundle.@@ -197,6 +216,8 @@ function Read-ReleaseDownloadManifest([string]$Tag, [string]$ManifestPath, [Dateif ($Fields[1] -eq "small") { $SmallProbe = $Probe }if ($Fields[1] -eq "large") { $LargeProbe = $Probe }} elseif ($Fields[0] -eq "asset" -and $Fields.Count -eq 4 -and $Fields[1] -eq $Asset) {+ # Not part of the decision — an integrity check that this manifest belongs to a release which+ # actually carries this target's bundle, so a mismatched manifest cannot steer the probe.if (-not [Int64]::TryParse([string]$Fields[2], [ref]$AssetSize) -or $AssetSize -le 0) { return $null }}}@@ -246,15 +267,19 @@ function Invoke-ProbeDownload([PSCustomObject]@{ Ok = $true; Seconds = $Seconds }}-function Select-SpeedProbeSource(- [object]$GitHubProbe,- [Int64]$ProbeSize-) {- if ($GitHubProbe.Ok) {- $GitHubBytesPerSecond = [double]$ProbeSize / [Math]::Max([double]$GitHubProbe.Seconds, 0.001)- if ($GitHubBytesPerSecond -ge $SpeedProbeGitHubMinBytesPerSecond) { return "github" }- }- return "oss"+# Throughput a completed probe measured, in bytes per second; 0 when it did not complete, which+# sorts it below any real measurement in the comparison below.+function Get-ProbeBytesPerSecond([object]$Probe, [Int64]$ProbeSize) {+ if (-not $Probe.Ok) { return 0.0 }+ return [double]$ProbeSize / [Math]::Max([double]$Probe.Seconds, 0.001)+}++# The shared rule, in one place: GitHub clears the minimum and wins outright, otherwise the mirror+# has to beat it by the switch ratio to take over.+function Select-SpeedProbeSource([double]$GitHubBytesPerSecond, [double]$OssBytesPerSecond) {+ if ($GitHubBytesPerSecond -ge $SpeedProbeGitHubMinBytesPerSecond) { return "github" }+ if ($OssBytesPerSecond -gt ($GitHubBytesPerSecond * $SpeedProbeOssSwitchRatio)) { return "oss" }+ return "github"}function Select-SpeedProbeDownloadSources([string]$Tag, [string]$Tmp) {@@ -278,22 +303,29 @@ function Select-SpeedProbeDownloadSources([string]$Tag, [string]$Tmp) {}if (-not $OssSmall.Ok -and -not $GitHubSmall.Ok) { return $null }- if ($Manifest.AssetSize -lt 33554432) {- Write-Host "Selected OSS mirror (download source test did not need throughput probing)."- return [PSCustomObject]@{ BaseUrl = $OssBase; FallbackBaseUrl = $GitHubBase }+ $GitHubLarge = Invoke-ProbeDownload $GitHubBase $Manifest.LargeProbe $Tmp "github-large" $Deadline $SpeedProbeLargeTimeoutSeconds+ $GitHubBytesPerSecond = Get-ProbeBytesPerSecond $GitHubLarge $Manifest.LargeProbe.Size++ # OSS is measured only once GitHub has failed the minimum: above it GitHub has already won, and+ # the mirror's bandwidth is not spent on a probe that could not change the answer. Probing runs+ # one source at a time on purpose — two concurrent transfers share the link and would each read+ # as half as fast, which an absolute threshold cannot tolerate.+ $OssBytesPerSecond = 0.0+ if ($GitHubBytesPerSecond -lt $SpeedProbeGitHubMinBytesPerSecond) {+ $OssLarge = Invoke-ProbeDownload $OssBase $Manifest.LargeProbe $Tmp "oss-large" $Deadline $SpeedProbeLargeTimeoutSeconds+ $OssBytesPerSecond = Get-ProbeBytesPerSecond $OssLarge $Manifest.LargeProbe.Size}- $GitHubLarge = Invoke-ProbeDownload $GitHubBase $Manifest.LargeProbe $Tmp "github-large" $Deadline $SpeedProbeLargeTimeoutSeconds- $Choice = Select-SpeedProbeSource $GitHubLarge $Manifest.LargeProbe.Size- if ($Choice -eq "github") {- Write-Host "Selected GitHub (meets minimum download speed)."+ if ((Select-SpeedProbeSource $GitHubBytesPerSecond $OssBytesPerSecond) -eq "github") {+ if ($GitHubBytesPerSecond -ge $SpeedProbeGitHubMinBytesPerSecond) {+ Write-Host "Selected GitHub (meets minimum download speed)."+ } else {+ Write-Host "Selected GitHub (the OSS mirror was not enough faster to be worth switching)."+ }return [PSCustomObject]@{ BaseUrl = $GitHubBase; FallbackBaseUrl = $OssBase }}- if ($Choice -eq "oss") {- Write-Host "Selected OSS mirror (GitHub did not meet minimum download speed)."- return [PSCustomObject]@{ BaseUrl = $OssBase; FallbackBaseUrl = $GitHubBase }- }- return $null+ Write-Host "Selected OSS mirror (clearly faster than GitHub here)."+ return [PSCustomObject]@{ BaseUrl = $OssBase; FallbackBaseUrl = $GitHubBase }}function Restore-PreviousInstall(diff --git a/install.sh b/install.shindex 33d55ba6..0d6bc2b5 100644--- a/install.sh+++ b/install.sh@@ -8,7 +8,8 @@# installer defaults to its own version, an unstamped source copy to latest# PENGUIN_INSTALL_DIR=<dir> install dir; default ~/.penguin# PENGUIN_ARCHIVE=<file> install a local Release archive without network access (same as --archive <file>)-# PENGUIN_DOWNLOAD_SOURCE=auto|oss|github choose the online source; default auto (OSS, then same-version GitHub)+# PENGUIN_DOWNLOAD_SOURCE=auto|oss|github choose the online source; default auto (speed-probed,+# with the same-version other source as fallback)# PENGUIN_DOWNLOAD_SPEED_PROBE=0 disable same-version OSS/GitHub probe timing in auto mode# PENGUIN_DOWNLOAD_BASE_URL=<url> exact online asset directory selected by the stable forwarder# PENGUIN_DOWNLOAD_FALLBACK_BASE_URL=<url> fallback for PENGUIN_DOWNLOAD_BASE_URL@@ -42,11 +43,29 @@ SOURCE_MODE="${PENGUIN_DOWNLOAD_SOURCE:-auto}"DOWNLOAD_BASE_URL="${PENGUIN_DOWNLOAD_BASE_URL:-}"DOWNLOAD_FALLBACK_BASE_URL="${PENGUIN_DOWNLOAD_FALLBACK_BASE_URL:-}"DOWNLOAD_SPEED_PROBE="${PENGUIN_DOWNLOAD_SPEED_PROBE:-1}"-SPEED_PROBE_TOTAL_TIMEOUT_SECONDS=16+# Auto-mode source selection, one rule shared by install.sh, install.ps1 and the download page on+# penguin.ooo (packages/landing/src/lib/download-source.ts):+#+# 1. Measure GitHub on the release's large probe file. At or above+# SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND it wins outright and OSS is never touched.+# 2. Only below that is OSS measured, and it takes over only when it is more than+# SPEED_PROBE_OSS_SWITCH_RATIO_PERCENT of GitHub — a mirror that is merely a little quicker+# does not justify its bandwidth bill, and a slow GitHub download still resumes.+#+# GitHub is the free source, so every tie and every unmeasurable comparison stays there. The two+# constants are duplicated because these three implementations cannot import from each other — an+# installer is a standalone file fetched over the network. Change them in all three at once, which+# scripts/test-installer.sh pins.+#+# The total budget covers the whole probe: manifest, the small reachability pair, and up to two+# large probes. It is deliberately the sum of their caps, so the second large probe always gets its+# full window rather than being squeezed into declaring a healthy mirror unreachable.SPEED_PROBE_MANIFEST_TIMEOUT_SECONDS=5SPEED_PROBE_SMALL_TIMEOUT_SECONDS=5SPEED_PROBE_LARGE_TIMEOUT_SECONDS=8+SPEED_PROBE_TOTAL_TIMEOUT_SECONDS=26SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND=262144+SPEED_PROBE_OSS_SWITCH_RATIO_PERCENT=150SPEED_PROBE_STARTED_AT=0PAYLOAD_NAME="payload.tar.gz"# The release workflow replaces this token with the immutable tag before publishing both the@@ -331,6 +350,8 @@ load_release_download_manifest() {SPEED_PROBE_LARGE_PROBE="$(awk -F '\t' '$1 == "probe" && $2 == "large" { print $3; exit }' "$lrdm_manifest")"SPEED_PROBE_LARGE_SIZE="$(awk -F '\t' '$1 == "probe" && $2 == "large" { print $4; exit }' "$lrdm_manifest")"SPEED_PROBE_LARGE_HASH="$(awk -F '\t' '$1 == "probe" && $2 == "large" { print $5; exit }' "$lrdm_manifest")"+ # Not part of the decision — an integrity check that this manifest belongs to a release which+ # actually carries this target's bundle, so a mismatched manifest cannot steer the probe.SPEED_PROBE_ASSET_SIZE="$(awk -F '\t' -v asset="$ASSET" '$1 == "asset" && $2 == asset { print $3; exit }' "$lrdm_manifest")"for lrdm_file in "$SPEED_PROBE_SMALL_PROBE" "$SPEED_PROBE_LARGE_PROBE"; do@@ -406,26 +427,32 @@ probe_status() {fi}-select_speed_probe_source_from_metrics() {- sfm_github_metrics="$1"- awk -v github_min="$SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND" '- function read_metrics(path, out, line, fields) {- if ((getline line < path) <= 0) return 0- close(path)- split(line, fields, " ")- if (fields[1] != "ok") return 0- out["start"] = fields[2] + 0- out["total"] = fields[3] + 0- out["speed"] = fields[4] + 0- return 1- }- BEGIN {- github_ok = read_metrics(ARGV[1], github)- ARGV[1] = ""- if (github_ok && github["speed"] >= github_min) { print "github"; exit }- print "oss"- }- ' "$sfm_github_metrics"+# Throughput a completed probe measured, in whole bytes per second; 0 when it did not complete,+# which sorts it below any real measurement in the comparison below.+probe_bytes_per_second() {+ pbs_metrics="$1"+ if [ ! -f "$pbs_metrics" ]; then+ printf '%s\n' 0+ return 0+ fi+ awk 'NR == 1 && $1 == "ok" && $4 + 0 > 0 { printf "%d\n", $4 + 0; measured = 1 }+ END { if (!measured) print 0 }' "$pbs_metrics"+}++# The shared rule, in one place: GitHub clears the minimum and wins outright, otherwise the mirror+# has to beat it by the switch ratio to take over. A POSIX shell has no floating point, so the ratio+# is applied to the GitHub side as an integer percent — scaling the mirror's side instead could+# overflow a 32-bit shell on a fast link, while this one is bounded by the minimum itself.+select_speed_probe_source() {+ ssp_github_speed="$1"+ ssp_oss_speed="$2"+ if [ "$ssp_github_speed" -ge "$SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND" ]; then+ printf '%s\n' "github"+ elif [ "$ssp_oss_speed" -gt "$((ssp_github_speed * SPEED_PROBE_OSS_SWITCH_RATIO_PERCENT / 100))" ]; then+ printf '%s\n' "oss"+ else+ printf '%s\n' "github"+ fi}speed_probe_release_sources() {@@ -459,26 +486,34 @@ speed_probe_release_sources() {return 1fi- if [ "$SPEED_PROBE_ASSET_SIZE" -lt 33554432 ]; then- SPEED_PROBE_BASE_URL="$OSS_SPEED_PROBE_BASE_URL"- SPEED_PROBE_FALLBACK_BASE_URL="$GITHUB_SPEED_PROBE_BASE_URL"- echo "Selected OSS mirror (download source test did not need throughput probing)."- return 0- fi-GITHUB_PROBE_METRICS="$TMP/probe-github-$SPEED_PROBE_LARGE_PROBE.metrics"probe_download_source github "$GITHUB_SPEED_PROBE_BASE_URL" "$SPEED_PROBE_LARGE_PROBE" "$SPEED_PROBE_LARGE_SIZE" "$SPEED_PROBE_LARGE_HASH" "$GITHUB_PROBE_METRICS" "$SPEED_PROBE_LARGE_TIMEOUT_SECONDS"- brs_choice="$(select_speed_probe_source_from_metrics "$GITHUB_PROBE_METRICS")"+ brs_github_speed="$(probe_bytes_per_second "$GITHUB_PROBE_METRICS")"++ # OSS is measured only once GitHub has failed the minimum: above it GitHub has already won, and+ # the mirror's bandwidth is not spent on a probe that could not change the answer. Probing runs+ # one source at a time on purpose — two concurrent transfers share the link and would each read+ # as half as fast, which an absolute threshold cannot tolerate.+ brs_oss_speed=0+ if [ "$brs_github_speed" -lt "$SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND" ]; then+ OSS_PROBE_METRICS="$TMP/probe-oss-$SPEED_PROBE_LARGE_PROBE.metrics"+ probe_download_source oss "$OSS_SPEED_PROBE_BASE_URL" "$SPEED_PROBE_LARGE_PROBE" "$SPEED_PROBE_LARGE_SIZE" "$SPEED_PROBE_LARGE_HASH" "$OSS_PROBE_METRICS" "$SPEED_PROBE_LARGE_TIMEOUT_SECONDS"+ brs_oss_speed="$(probe_bytes_per_second "$OSS_PROBE_METRICS")"+ fi++ brs_choice="$(select_speed_probe_source "$brs_github_speed" "$brs_oss_speed")"if [ "$brs_choice" = "github" ]; thenSPEED_PROBE_BASE_URL="$GITHUB_SPEED_PROBE_BASE_URL"SPEED_PROBE_FALLBACK_BASE_URL="$OSS_SPEED_PROBE_BASE_URL"- echo "Selected GitHub (meets minimum download speed)."- elif [ "$brs_choice" = "oss" ]; then+ if [ "$brs_github_speed" -ge "$SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND" ]; then+ echo "Selected GitHub (meets minimum download speed)."+ else+ echo "Selected GitHub (the OSS mirror was not enough faster to be worth switching)."+ fi+ elseSPEED_PROBE_BASE_URL="$OSS_SPEED_PROBE_BASE_URL"SPEED_PROBE_FALLBACK_BASE_URL="$GITHUB_SPEED_PROBE_BASE_URL"- echo "Selected OSS mirror (GitHub did not meet minimum download speed)."- else- return 1+ echo "Selected OSS mirror (clearly faster than GitHub here)."fireturn 0}diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.mdindex 1604aec8..44ab89cc 100644--- a/packages/docs/content/cli.en.md+++ b/packages/docs/content/cli.en.md@@ -182,7 +182,7 @@ penguin update # upgrade to the latest release, after confirmingThe target flag is `--release`, not `--version`, because `-v, --version` is the CLI's own version flag and would take precedence.-Release discovery and tarball downloads honor `PENGUIN_DOWNLOAD_SOURCE=auto|oss|github`, using the same policy as the stable installer entry point. The default `auto` mode reads the OSS `latest.json`, prefers that immutable release, and falls back to the matching GitHub tag. Forced `oss` and `github` modes are strict; `--release <tag>` skips latest-version discovery while retaining the selected source policy. An explicit HTTPS `PENGUIN_DOWNLOAD_BASE_URL` has highest priority for installer and payload downloads, with an optional `PENGUIN_DOWNLOAD_FALLBACK_BASE_URL` for the payload.+Release discovery and tarball downloads honor `PENGUIN_DOWNLOAD_SOURCE=auto|oss|github`, using the same policy as the stable installer entry point. The default `auto` mode reads the OSS `latest.json`, prefers that immutable release, and falls back to the matching GitHub tag; the package itself is then served by whichever source the installer's speed probe picks. Forced `oss` and `github` modes are strict; `--release <tag>` skips latest-version discovery while retaining the selected source policy. An explicit HTTPS `PENGUIN_DOWNLOAD_BASE_URL` has highest priority for installer and payload downloads, with an optional `PENGUIN_DOWNLOAD_FALLBACK_BASE_URL` for the payload.| Install kind | How it upgrades || --- | --- |diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.mdindex 6d088dce..8c9bd421 100644--- a/packages/docs/content/cli.zh.md+++ b/packages/docs/content/cli.zh.md@@ -182,7 +182,7 @@ penguin update # 确认后升级到最新版目标版本参数叫 `--release` 而不是 `--version`,因为 `-v, --version` 是 CLI 自身的版本参数,会优先生效。-版本发现和 tarball 下载遵循 `PENGUIN_DOWNLOAD_SOURCE=auto|oss|github`,与稳定安装入口使用相同策略。默认的 `auto` 模式读取 OSS `latest.json`,优先选择该不可变版本,并按同一 tag 回退到 GitHub;强制 `oss` 或 `github` 时不会切换来源。`--release <tag>` 会跳过最新版查询,但仍遵循所选下载源策略。显式设置的 HTTPS `PENGUIN_DOWNLOAD_BASE_URL` 对安装脚本和发布包下载具有最高优先级,并可通过 `PENGUIN_DOWNLOAD_FALLBACK_BASE_URL` 为发布包配置后备地址。+版本发现和 tarball 下载遵循 `PENGUIN_DOWNLOAD_SOURCE=auto|oss|github`,与稳定安装入口使用相同策略。默认的 `auto` 模式读取 OSS `latest.json`,优先选择该不可变版本,并按同一 tag 回退到 GitHub;安装包本身则由安装器测速选出的来源提供。强制 `oss` 或 `github` 时不会切换来源。`--release <tag>` 会跳过最新版查询,但仍遵循所选下载源策略。显式设置的 HTTPS `PENGUIN_DOWNLOAD_BASE_URL` 对安装脚本和发布包下载具有最高优先级,并可通过 `PENGUIN_DOWNLOAD_FALLBACK_BASE_URL` 为发布包配置后备地址。| 安装方式 | 升级方式 || --- | --- |diff --git a/packages/docs/content/quickstart-cli.en.md b/packages/docs/content/quickstart-cli.en.mdindex 4a13e427..fef6ac96 100644--- a/packages/docs/content/quickstart-cli.en.md+++ b/packages/docs/content/quickstart-cli.en.md@@ -84,7 +84,7 @@ The three commands above cover nearly every case; the rest of the options and deThe script downloads the matching `penguin-{linux,darwin}-{x64,arm64}.tar.gz` — the canonical installer bundle, sealing the program payload (with an official Node.js runtime), the payload's SHA256 checksum and this same installer. The download is verified against its published `.sha256`, then the sealed payload checksum is verified again before anything is staged. Other POSIX platforms do **not** fall back automatically: the script exits and asks you to install Node.js >= 24 and re-run with `--universal`, which selects the runtime-less `penguin-universal.tar.gz` bundle (Windows is served by its own installer, not by `--universal`).-The stable entry point defaults to `PENGUIN_DOWNLOAD_SOURCE=auto`: it prefers an immutable OSS release directory only after that release has been completely uploaded and verified, then falls back to the matching GitHub Release if the metadata or download is unavailable. Set the variable to `oss` or `github` to force either source. Normal installer output names the source without printing the mirror's full URL.+The stable entry point defaults to `PENGUIN_DOWNLOAD_SOURCE=auto`: it resolves the target through an immutable OSS release directory only after that release has been completely uploaded and verified, and falls back to the matching GitHub Release if the metadata is unavailable. Which source then serves the package is measured, not assumed. The installer times a probe file on GitHub and keeps GitHub whenever it reaches 256 KB/s; only below that does it measure the OSS mirror, and it switches only when the mirror is more than 1.5x faster — a mirror that is merely a little quicker is not worth its bandwidth bill, and a slow GitHub download still resumes. Set `PENGUIN_DOWNLOAD_SPEED_PROBE=0` to skip the measurement, or `PENGUIN_DOWNLOAD_SOURCE` to `oss` or `github` to force either source. Normal installer output names the source without printing the mirror's full URL.The `penguin.ooo` stable entry resolves the current stable version each time it runs. A standalone script downloaded from a versioned GitHub or OSS Release is stamped with that Release tag and defaults to the same version, keeping the installer and package format matched; set `PENGUIN_VERSION` (or `--version` on POSIX) to override it explicitly. To pin a version on Windows, set the env var before running the installer:@@ -129,7 +129,7 @@ After the build, run `pnpm penguin <args>` inside the repo as the dev runner, or| Install dir | `~/.penguin` by default; override with the `PENGUIN_INSTALL_DIR` env var || Command entry | A symlink `~/.local/bin/penguin` is created (the script warns if `~/.local/bin` is not on PATH) || Version selection | `PENGUIN_VERSION=vX.Y.Z` env var, or the `--version vX.Y.Z` script flag; the stable entry defaults to the latest Release, while a versioned Release installer defaults to its own tag |-| Download source | `PENGUIN_DOWNLOAD_SOURCE=auto` (default), `oss`, or `github`; auto prefers OSS and falls back to the same GitHub version |+| Download source | `PENGUIN_DOWNLOAD_SOURCE=auto` (default), `oss`, or `github`; auto times a probe file and keeps the free GitHub download unless the OSS mirror is clearly faster, falling back to the same version on the other source (`PENGUIN_DOWNLOAD_SPEED_PROBE=0` skips the measurement) || Local archive | `PENGUIN_ARCHIVE=<file>` or `--archive <file>`; accepts a Release bundle (self-verifying via its sealed payload checksum) or a payload/legacy program archive with an adjacent `<file>.sha256` (renamed legacy files may use the platform asset's canonical `.sha256`) || Integrity check | Always on: online downloads are verified against the published `.sha256`, and bundle payloads against the checksum sealed inside the bundle || Upgrade | Re-run the install script; files are swapped atomically |diff --git a/packages/docs/content/quickstart-cli.zh.md b/packages/docs/content/quickstart-cli.zh.mdindex b0087adf..7058b166 100644--- a/packages/docs/content/quickstart-cli.zh.md+++ b/packages/docs/content/quickstart-cli.zh.md@@ -84,7 +84,7 @@ penguin chat脚本按平台下载 `penguin-{linux,darwin}-{x64,arm64}.tar.gz`——即标准安装包:包内封入程序负载(捆绑官方 Node.js 运行时)、负载的 SHA256 校验文件与同一个安装器。下载后先对照 Release 发布的 `.sha256` 校验外层,再校验包内封入的负载 checksum,然后才进入暂存安装。其他 POSIX 平台**不会自动回退**:脚本会退出并提示先安装 Node.js >= 24、再携带 `--universal` 重新执行,改用不含运行时的 `penguin-universal.tar.gz` 安装包(Windows 使用专属安装器,而不是 `--universal`)。-稳定入口默认使用 `PENGUIN_DOWNLOAD_SOURCE=auto`:优先选择已完整上传并验证的 OSS 不可变版本目录;元数据或下载不可用时,回退到同一版本的 GitHub Release。也可以将该变量设为 `oss` 或 `github` 来强制指定来源。安装器只显示来源名称,不在常规输出中打印镜像的完整 URL。+稳定入口默认使用 `PENGUIN_DOWNLOAD_SOURCE=auto`:先经已完整上传并验证的 OSS 不可变版本目录确定目标版本,元数据不可用时回退到同一版本的 GitHub Release。至于由哪个源提供安装包,则由实测决定,而非预设:安装器先对 GitHub 上的测速文件计时,达到 256 KB/s 即保持 GitHub;只有低于该值时才测量 OSS 镜像,且仅当镜像快出 1.5 倍以上才切换——仅快一点的镜像不值得其带宽成本,而较慢的 GitHub 下载仍可续传。设置 `PENGUIN_DOWNLOAD_SPEED_PROBE=0` 可跳过测速,设置 `PENGUIN_DOWNLOAD_SOURCE` 为 `oss` 或 `github` 可强制指定来源。安装器只显示来源名称,不在常规输出中打印镜像的完整 URL。`penguin.ooo` 稳定入口每次执行时都会解析当前稳定版本。从 GitHub 或 OSS 的版本化 Release 中直接下载的独立安装脚本会写入该 Release tag,并默认安装同一版本,确保安装器与安装包格式匹配;如需覆盖,可显式设置 `PENGUIN_VERSION`(POSIX 也可使用 `--version`)。Windows 上固定版本,在运行安装器前设置环境变量:@@ -129,7 +129,7 @@ pnpm install && pnpm build| 安装目录 | 默认 `~/.penguin`,可用环境变量 `PENGUIN_INSTALL_DIR` 覆盖 || 命令入口 | 创建符号链接 `~/.local/bin/penguin`(若 `~/.local/bin` 不在 PATH 上,脚本会给出提示) || 版本选择 | 环境变量 `PENGUIN_VERSION=vX.Y.Z`,或脚本参数 `--version vX.Y.Z`;稳定入口默认安装最新 Release,版本化 Release 安装器默认安装自身 tag |-| 下载来源 | `PENGUIN_DOWNLOAD_SOURCE=auto`(默认)、`oss` 或 `github`;自动模式优先 OSS,并按同一版本回退到 GitHub |+| 下载来源 | `PENGUIN_DOWNLOAD_SOURCE=auto`(默认)、`oss` 或 `github`;自动模式对测速文件计时,除非 OSS 镜像明显更快,否则保持免费的 GitHub 下载,并按同一版本回退到另一个源(`PENGUIN_DOWNLOAD_SPEED_PROBE=0` 可跳过测速) || 本地压缩包 | `PENGUIN_ARCHIVE=<file>` 或 `--archive <file>`;接受 Release 安装包(凭包内封入的负载 checksum 自校验),或旁边带 `<file>.sha256` 的负载 / 旧版程序压缩包(重命名的旧版文件可用平台标准名称的 `.sha256`) || 完整性校验 | 始终进行:在线下载对照发布的 `.sha256` 校验,安装包负载对照包内封入的 checksum 校验 || 升级 | 重新执行安装脚本即可,文件原子替换 |diff --git a/packages/landing/src/lib/download-source.ts b/packages/landing/src/lib/download-source.tsnew file mode 100644index 00000000..98a28433--- /dev/null+++ b/packages/landing/src/lib/download-source.ts@@ -0,0 +1,185 @@+/**+ * Which source the desktop download buttons point at — the browser half of the rule the installers+ * apply (see the matching block in install.sh and install.ps1):+ *+ * 1. Measure GitHub on the release's large probe file. At or above+ * SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND it wins outright and OSS is never touched.+ * 2. Only below that is OSS measured, and it takes over only when it is more than+ * SPEED_PROBE_OSS_SWITCH_RATIO of GitHub — a mirror that is merely a little quicker does not+ * justify its bandwidth bill, and a slow GitHub download still resumes.+ *+ * GitHub is the free source, so every tie and every unmeasurable comparison stays there. The two+ * constants are spelled out in all three places because none of them can import from the others —+ * an installer is a standalone file fetched over the network. Change them in all three at once,+ * which scripts/test-installer.sh pins.+ *+ * Throughput is read from the Resource Timing entry, not from the response body: GitHub's release+ * assets send no `access-control-allow-origin`, so a cross-origin read of them is blocked outright.+ * An opaque `no-cors` request still records a timing entry whose `duration` covers the whole+ * transfer even though the body stays unreadable. Both sources are measured that same way so the+ * two numbers are comparable — the alternative, reading OSS through CORS, would time the JS-side+ * buffering on one side only. GitHub's duration additionally covers the two redirect hops its+ * release URLs take, which can only make it read slower than it is, never faster.+ */++export const SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND = 262144;++/** How much faster the mirror has to be before its paid bandwidth beats a free GitHub download. */+export const SPEED_PROBE_OSS_SWITCH_RATIO = 1.5;++/** The installers' large-probe cap: a source that cannot deliver the probe in this long loses. */+export const SPEED_PROBE_TIMEOUT_MS = 8000;++export type DownloadSource = "github" | "oss";++export interface ReleaseProbe {+ /** Probe file name, identical on both sources. */+ file: string;+ /** Its exact size, the numerator of every measurement — the opaque body cannot be counted. */+ size: number;+}++/**+ * The shared rule, in one place: GitHub clears the minimum and wins outright, otherwise the mirror+ * has to beat it by the switch ratio to take over.+ */+export function selectDownloadSource(+ githubBytesPerSecond: number,+ ossBytesPerSecond: number,+): DownloadSource {+ if (githubBytesPerSecond >= SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND) return "github";+ return ossBytesPerSecond > githubBytesPerSecond * SPEED_PROBE_OSS_SWITCH_RATIO ? "oss" : "github";+}++const SAFE_ASSET_NAME = /^[A-Za-z0-9._+-]+$/;++/**+ * The large probe row of a release's download manifest, validated the way the installers validate+ * it: the header has to name this exact tag, and the file name has to be a plain asset name so a+ * tampered manifest cannot point the probe at another path.+ */+export function parseLargeProbe(manifest: string, tag: string): ReleaseProbe | null {+ const lines = manifest.split("\n");+ if (lines[0] !== `penguin-release-download-manifest\t1\t${tag}`) return null;+ for (const line of lines.slice(1)) {+ const fields = line.split("\t");+ if (fields[0] !== "probe" || fields[1] !== "large") continue;+ if (fields.length !== 5) return null;+ const file = fields[2] ?? "";+ const size = Number(fields[3]);+ if (!SAFE_ASSET_NAME.test(file) || file.includes("..")) return null;+ if (!Number.isSafeInteger(size) || size <= 0) return null;+ return { file, size };+ }+ return null;+}++/**+ * A fresh query string per probe: a cached hit would time the disk rather than the network, and it+ * keeps every measurement on a resource timing entry name of its own.+ */+function probeUrl(base: string, file: string): string {+ return `${base}/${file}?probe=${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;+}++/** The entry's duration in ms, or null when none is recorded before the deadline. */+function awaitResourceTiming(url: string, timeoutMs: number): Promise<number | null> {+ if (typeof PerformanceObserver === "undefined") return Promise.resolve(null);+ return new Promise((resolve) => {+ let observer: PerformanceObserver | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;+ const finish = (durationMs: number | null) => {+ if (timer !== null) clearTimeout(timer);+ observer?.disconnect();+ observer = null;+ resolve(durationMs);+ };+ observer = new PerformanceObserver((list) => {+ const entry = list.getEntries().find((candidate) => candidate.name === url);+ if (entry) finish(entry.duration);+ });+ timer = setTimeout(() => finish(null), timeoutMs);+ try {+ observer.observe({ type: "resource" });+ } catch {+ finish(null);+ }+ });+}++/** Bytes per second for one probe download; 0 when it did not complete inside the deadline. */+export async function measureBytesPerSecond(+ url: string,+ sizeBytes: number,+ timeoutMs: number = SPEED_PROBE_TIMEOUT_MS,+ signal?: AbortSignal,+): Promise<number> {+ const controller = new AbortController();+ const deadline = setTimeout(() => controller.abort(), timeoutMs);+ signal?.addEventListener("abort", () => controller.abort(), { once: true });+ if (signal?.aborted) controller.abort();+ const timing = awaitResourceTiming(url, timeoutMs);+ try {+ // An opaque fetch settles once the headers land, not once the body does. The timing entry is+ // what waits for the transfer to finish; the abort above is what bounds it, and stays armed+ // until then so a stalled body is cut off rather than measured.+ await fetch(url, { mode: "no-cors", cache: "no-store", signal: controller.signal });+ const durationMs = await timing;+ if (controller.signal.aborted || durationMs === null || durationMs <= 0) return 0;+ return Math.round((sizeBytes * 1000) / durationMs);+ } catch {+ return 0;+ } finally {+ clearTimeout(deadline);+ }+}++export interface ProbeSources {+ githubBase: string;+ ossBase: string;+}++/**+ * Applies the rule to one release. OSS is measured only once GitHub has failed the minimum: above+ * it GitHub has already won, and the mirror's bandwidth is not spent on a probe that could not+ * change the answer. The two run one after the other on purpose — concurrent transfers share the+ * link and would each read as half as fast, which an absolute threshold cannot tolerate.+ */+export async function probeDownloadSource(+ sources: ProbeSources,+ probe: ReleaseProbe,+ signal?: AbortSignal,+): Promise<DownloadSource> {+ const measure = (base: string) =>+ measureBytesPerSecond(probeUrl(base, probe.file), probe.size, SPEED_PROBE_TIMEOUT_MS, signal);+ const github = await measure(sources.githubBase);+ if (github >= SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND) return "github";+ return selectDownloadSource(github, await measure(sources.ossBase));+}++/**+ * The release's large probe row, read from the mirror — the one origin of the two that answers a+ * cross-origin read at all, and the same file the installers parse.+ */+export async function fetchLargeProbe(+ ossBase: string,+ tag: string,+ signal?: AbortSignal,+): Promise<ReleaseProbe | null> {+ try {+ const res = await fetch(`${ossBase}/release-download-manifest.tsv`, {+ signal,+ cache: "no-store",+ });+ return res.ok ? parseLargeProbe(await res.text(), tag) : null;+ } catch {+ return null;+ }+}++/** Data Saver is a request not to spend a megabyte on measuring; the unprobed default stands. */+export function probingAllowed(): boolean {+ if (typeof navigator === "undefined") return false;+ const connection = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection;+ return connection?.saveData !== true;+}diff --git a/packages/landing/src/pages/download.tsx b/packages/landing/src/pages/download.tsxindex f5a7da97..7f85942b 100644--- a/packages/landing/src/pages/download.tsx+++ b/packages/landing/src/pages/download.tsx@@ -1,13 +1,16 @@/*** Desktop download page. The buttons are static GitHub `releases/latest/download/<name>`* links by default — always valid because installer names are version-less — and swap to- * the OSS mirror's immutable per-tag URLs once the bucket's `latest.json` pointer- * resolves (validated the same way the installers validate it; any failure, e.g. CORS- * not configured on the bucket or the mirror unreachable, silently keeps the GitHub- * links). Plain-anchor downloads are never CORS-gated — only this version lookup is.- * Below the cards, a first-launch FAQ covers the unsigned builds — one collapsible item- * per platform (macOS quarantine removal, SmartScreen, AppImage execute bit), with the- * visitor's own platform pre-expanded.+ * the OSS mirror's immutable per-tag URLs only when the mirror earns them: the bucket's+ * `latest.json` pointer has to resolve (validated the same way the installers validate+ * it), and the speed probe in lib/download-source.ts has to find the mirror clearly+ * faster than GitHub here, by the same rule install.sh and install.ps1 apply. Any failure+ * along the way — CORS not configured on the bucket, the mirror unreachable, Data Saver+ * on — silently keeps the free GitHub links. Plain-anchor downloads are never CORS-gated;+ * only the version lookup and the probe are. Whatever the probe decides, the visitor can+ * still switch sources by hand below the cards. Below that, a first-launch FAQ covers the+ * unsigned builds — one collapsible item per platform (macOS quarantine removal,+ * SmartScreen, AppImage execute bit), with the visitor's own platform pre-expanded.*/import { useEffect, useState } from "react";import { Link } from "react-router";@@ -25,6 +28,8 @@ import {} from "../lib/links";import { detectPlatform } from "../lib/platform";import type { Platform } from "../lib/platform";+import { fetchLargeProbe, probeDownloadSource, probingAllowed } from "../lib/download-source";+import type { DownloadSource } from "../lib/download-source";import { Section } from "../components/section";import { CodeCard } from "../components/code-card";import { ChevronDownIcon, DownloadIcon, ExternalLinkIcon } from "../components/icons";@@ -78,26 +83,47 @@ function parseMirror(value: unknown): Mirror | null {export function DownloadPage() {const [mirror, setMirror] = useState<Mirror | null>(null);- const [forceGithub, setForceGithub] = useState(false);+ /** What the probe settled on; null while it is still running or never ran. */+ const [probed, setProbed] = useState<DownloadSource | null>(null);+ /** The visitor's own choice, which outranks the probe for the rest of the visit. */+ const [override, setOverride] = useState<DownloadSource | null>(null);useEffect(() => {const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), 5000);- fetch(OSS_LATEST_JSON_URL, { signal: controller.signal })- .then((res) => (res.ok ? res.json() : null))- .then((body: unknown) => {- const parsed = parseMirror(body);- if (parsed) setMirror(parsed);- })- .catch(() => {}) // The GitHub links already work; the mirror is a progressive upgrade.- .finally(() => clearTimeout(timer));+ const lookupTimer = setTimeout(() => controller.abort(), 5000);+ let cancelled = false;+ // Resolve the mirror, then measure. Every failure lands on GitHub, which the buttons already+ // point at — nothing here can leave the page without a working download.+ void (async () => {+ let found: Mirror | null = null;+ try {+ const res = await fetch(OSS_LATEST_JSON_URL, { signal: controller.signal });+ found = res.ok ? parseMirror(await res.json()) : null;+ } catch {+ found = null;+ }+ clearTimeout(lookupTimer);+ if (cancelled || !found) return;+ setMirror(found);+ if (!probingAllowed()) return;+ const probe = await fetchLargeProbe(found.base, found.tag, controller.signal);+ if (cancelled || !probe) return;+ const source = await probeDownloadSource(+ { githubBase: GITHUB_LATEST_DOWNLOAD, ossBase: found.base },+ probe,+ controller.signal,+ );+ if (!cancelled) setProbed(source);+ })();return () => {- clearTimeout(timer);+ cancelled = true;+ clearTimeout(lookupTimer);controller.abort();};}, []);const detected = detectPlatform();- const viaMirror = mirror !== null && !forceGithub;+ const selected: DownloadSource = override ?? probed ?? "github";+ const viaMirror = mirror !== null && selected === "oss";const hrefFor = (file: string) =>viaMirror ? `${mirror.base}/${file}` : `${GITHUB_LATEST_DOWNLOAD}/${file}`;@@ -149,8 +175,12 @@ export function DownloadPage() {<p>{viaMirror ? S.download.statusOss(mirror.tag) : S.download.statusGithub}{" "}{mirror !== null && (- <button type="button" className={textLink} onClick={() => setForceGithub(!forceGithub)}>- {forceGithub ? S.download.altOss : S.download.altGithub}+ <button+ type="button"+ className={textLink}+ onClick={() => setOverride(viaMirror ? "github" : "oss")}+ >+ {viaMirror ? S.download.altGithub : S.download.altOss}</button>)}</p>diff --git a/packages/landing/test/download-source.test.ts b/packages/landing/test/download-source.test.tsnew file mode 100644index 00000000..07016684--- /dev/null+++ b/packages/landing/test/download-source.test.ts@@ -0,0 +1,70 @@+/**+ * The download page's half of the shared auto-mode rule. The measurement itself needs a browser+ * (see lib/download-source.ts on why throughput is read from a Resource Timing entry), so what is+ * pinned here is the decision the measurements feed and the manifest parsing that names the probe.+ * The installers run the same table against their own implementations in scripts/test-installer.sh.+ */+import { describe, expect, it } from "vitest";+import {+ SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND,+ parseLargeProbe,+ selectDownloadSource,+} from "../src/lib/download-source";++const MIN = SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND;++describe("selectDownloadSource", () => {+ it("keeps GitHub at the minimum however fast the mirror is", () => {+ expect(selectDownloadSource(MIN, 100 * MIN)).toBe("github");+ expect(selectDownloadSource(MIN + 1, 100 * MIN)).toBe("github");+ });++ it("switches to the mirror only when it beats a below-minimum GitHub by more than 1.5x", () => {+ const github = MIN / 2;+ expect(selectDownloadSource(github, github * 1.51)).toBe("oss");+ expect(selectDownloadSource(github, github * 1.5)).toBe("github");+ expect(selectDownloadSource(github, github * 1.4)).toBe("github");+ expect(selectDownloadSource(github, github)).toBe("github");+ expect(selectDownloadSource(github, github / 2)).toBe("github");+ });++ it("treats an unmeasurable source as the slowest one, and a dead heat as free bandwidth", () => {+ expect(selectDownloadSource(0, 1)).toBe("oss");+ expect(selectDownloadSource(MIN / 2, 0)).toBe("github");+ expect(selectDownloadSource(0, 0)).toBe("github");+ });+});++const TAG = "v1.2.3";+const MANIFEST = [+ `penguin-release-download-manifest\t1\t${TAG}`,+ "probe\tsmall\tprobe-64k.bin\t65536\t" + "a".repeat(64),+ "probe\tlarge\tprobe-1m.bin\t1048576\t" + "b".repeat(64),+ "asset\tpenguin-desktop-win32-x64.exe\t104857600\t" + "c".repeat(64),+ "",+].join("\n");++describe("parseLargeProbe", () => {+ it("reads the large probe row of a manifest for this exact tag", () => {+ expect(parseLargeProbe(MANIFEST, TAG)).toEqual({ file: "probe-1m.bin", size: 1048576 });+ });++ it("refuses a manifest published for another tag", () => {+ expect(parseLargeProbe(MANIFEST, "v9.9.9")).toBeNull();+ });++ it("refuses a probe name that is not a plain asset name", () => {+ const escaped = MANIFEST.replace("probe-1m.bin", "../../etc/passwd");+ expect(parseLargeProbe(escaped, TAG)).toBeNull();+ });++ it("refuses a size that is not a positive integer", () => {+ expect(parseLargeProbe(MANIFEST.replace("\t1048576\t", "\t0\t"), TAG)).toBeNull();+ expect(parseLargeProbe(MANIFEST.replace("\t1048576\t", "\tlots\t"), TAG)).toBeNull();+ });++ it("returns null when the release carries no large probe at all", () => {+ const rows = MANIFEST.split("\n").filter((line) => !line.startsWith("probe\tlarge"));+ expect(parseLargeProbe(rows.join("\n"), TAG)).toBeNull();+ });+});diff --git a/scripts/test-installer.ps1 b/scripts/test-installer.ps1index a6275c88..374ffab8 100644--- a/scripts/test-installer.ps1+++ b/scripts/test-installer.ps1@@ -85,8 +85,14 @@ function global:Invoke-WebRequest {if ($f.Mode -eq "speed-probe-missing-manifest" -and $Uri -like "*/release-download-manifest.tsv") {throw "fixture missing release download manifest"}- if ($f.Mode -eq "speed-probe-github-below-threshold" -and $Uri -like "https://github.com/*/probe-1m.bin") {- Start-Sleep -Milliseconds 4300+ # 1 MiB in 6.0s is ~175 KB/s, under the 256 KB/s minimum; the mirror answering the same probe in+ # 5.0s is ~210 KB/s — faster than GitHub, but only 1.2x, short of the 1.5x switch ratio.+ if ($f.Mode -in @("speed-probe-oss-clearly-faster", "speed-probe-oss-not-worth-switching") -and+ $Uri -like "https://github.com/*/probe-1m.bin") {+ Start-Sleep -Milliseconds 6000+ }+ if ($f.Mode -eq "speed-probe-oss-not-worth-switching" -and $Uri -like "*aliyuncs.com/*/probe-1m.bin") {+ Start-Sleep -Milliseconds 5000}switch -Wildcard ($Uri) {"*/latest.json" {@@ -102,8 +108,8 @@ function global:Invoke-WebRequest {}}"*/release-download-manifest.tsv" {- if ($f.Mode -in @("speed-probe-small", "speed-probe-github-fast", "speed-probe-github-below-threshold")) {- $AssetSize = if ($f.Mode -eq "speed-probe-small") { 16777216 } else { 104857600 }+ if ($f.Mode -like "speed-probe-*") {+ $AssetSize = 104857600@("penguin-release-download-manifest`t1`tv0.0.0-test""probe`tsmall`tprobe-64k.bin`t65536`t$($f.Probe64Hash)"@@ -314,25 +320,30 @@ try {Assert-True ($stampedFallback.Requests[1] -like "https://github.com/*/releases/download/v0.0.0-test/penguin-win32-x64.zip") `"stamped installer did not fall back to the same GitHub version"- $speedProbeSmall = Invoke-OnlineCase "speed-probe-small" "speed-probe-small" "" $true 5 $StampedInstaller "1"- Assert-True (($speedProbeSmall.Requests | Out-String) -match 'release-download-manifest\.tsv') `+ $speedProbeGitHubFast = Invoke-OnlineCase "speed-probe-github-fast" "speed-probe-github-fast" "" $true 6 $StampedInstaller "1"+ Assert-True (($speedProbeGitHubFast.Requests | Out-String) -match 'release-download-manifest\.tsv') `"speed probe did not request the release download manifest"- Assert-True (($speedProbeSmall.Requests | Out-String) -match 'probe-64k\.bin') `+ Assert-True (($speedProbeGitHubFast.Requests | Out-String) -match 'probe-64k\.bin') `"speed probe did not request the small probe"- Assert-True ($speedProbeSmall.Requests[-2] -like "https://penguin-harness-releases.oss-cn-beijing.aliyuncs.com/*/penguin-win32-x64.zip") `- "small speed probe path did not keep the default OSS source"-- $speedProbeGitHubFast = Invoke-OnlineCase "speed-probe-github-fast" "speed-probe-github-fast" "" $true 6 $StampedInstaller "1"Assert-True ($speedProbeGitHubFast.Requests[-2] -like "https://github.com/*/releases/download/v0.0.0-test/penguin-win32-x64.zip") `"speed probe did not select GitHub when it met the minimum speed"+ Assert-True (-not (($speedProbeGitHubFast.Requests | Out-String) -match 'aliyuncs\.com/[^\r\n]*probe-1m\.bin')) `+ "speed probe spent the paid mirror's bandwidth even though GitHub already met the minimum"$speedProbeDefaultOn = Invoke-OnlineCase "speed-probe-default-on" "speed-probe-github-fast" "" $true 6 $StampedInstaller "__unset"Assert-True ($speedProbeDefaultOn.Requests[-2] -like "https://github.com/*/releases/download/v0.0.0-test/penguin-win32-x64.zip") `"speed probe was not enabled by default"- $speedProbeGitHubBelowThreshold = Invoke-OnlineCase "speed-probe-github-below-threshold" "speed-probe-github-below-threshold" "" $true 6 $StampedInstaller "1"- Assert-True ($speedProbeGitHubBelowThreshold.Requests[-2] -like "https://penguin-harness-releases.oss-cn-beijing.aliyuncs.com/*/penguin-win32-x64.zip") `- "speed probe did not keep OSS when GitHub was below the minimum speed"+ # Below the minimum the mirror is measured too, which is the seventh request of these two cases.+ $speedProbeOssFaster = Invoke-OnlineCase "speed-probe-oss-clearly-faster" "speed-probe-oss-clearly-faster" "" $true 7 $StampedInstaller "1"+ Assert-True (($speedProbeOssFaster.Requests | Out-String) -match 'aliyuncs\.com/[^\r\n]*probe-1m\.bin') `+ "speed probe did not measure the OSS mirror once GitHub was below the minimum speed"+ Assert-True ($speedProbeOssFaster.Requests[-2] -like "https://penguin-harness-releases.oss-cn-beijing.aliyuncs.com/*/penguin-win32-x64.zip") `+ "speed probe did not switch to OSS when it was clearly faster than a slow GitHub"++ $speedProbeOssMarginal = Invoke-OnlineCase "speed-probe-oss-not-worth-switching" "speed-probe-oss-not-worth-switching" "" $true 7 $StampedInstaller "1"+ Assert-True ($speedProbeOssMarginal.Requests[-2] -like "https://github.com/*/releases/download/v0.0.0-test/penguin-win32-x64.zip") `+ "speed probe left GitHub even though OSS was not faster by the switch ratio"$speedProbeMissing = Invoke-OnlineCase "speed-probe-missing-manifest" "speed-probe-missing-manifest" "" $true 4 $StampedInstaller "1"Assert-True (($speedProbeMissing.Output | Out-String) -match 'Download source test was inconclusive') `diff --git a/scripts/test-installer.sh b/scripts/test-installer.shindex 2b45e42f..ed2bd0b4 100755--- a/scripts/test-installer.sh+++ b/scripts/test-installer.sh@@ -17,6 +17,26 @@ fail_test() {exit 1}+# The auto-mode rule lives in three implementations that cannot import from each other: the two+# installers and the download page on penguin.ooo. Nothing but this check keeps their constants in+# step, so a threshold edited in one place fails here instead of shipping three different rules.+check_shared_constant() {+ csc_label="$1"+ csc_expected="$2"+ shift 2+ for csc_file in "$@"; do+ grep -qF "$csc_expected" "$ROOT_DIR/$csc_file" \+ || fail_test "$csc_file does not carry $csc_label as \"$csc_expected\""+ done+}++LANDING_RULE="packages/landing/src/lib/download-source.ts"+check_shared_constant "the GitHub minimum" "262144" install.sh install.ps1 "$LANDING_RULE"+# The same 1.5, written as an integer percent in install.sh because a POSIX shell has no floats.+check_shared_constant "the OSS switch ratio" "SPEED_PROBE_OSS_SWITCH_RATIO_PERCENT=150" install.sh+check_shared_constant "the OSS switch ratio" '$SpeedProbeOssSwitchRatio = 1.5' install.ps1+check_shared_constant "the OSS switch ratio" "SPEED_PROBE_OSS_SWITCH_RATIO = 1.5;" "$LANDING_RULE"+write_sha256() {file="$1"(cd "$(dirname "$file")" && sha256sum "$(basename "$file")" > "$(basename "$file").sha256")@@ -357,7 +377,7 @@ case "$MODE:$base" inprintf '%s\n' '{"schemaVersion":1,"tag":"v0.0.0-test","releaseBaseUrl":"https://penguin-harness-releases.oss-cn-beijing.aliyuncs.com/releases/v0.0.0-test"}' > "$output";;speed-probe-missing-manifest:release-download-manifest.tsv) exit 22 ;;- speed-probe-github-fast:release-download-manifest.tsv | speed-probe-github-below-threshold:release-download-manifest.tsv | speed-probe-missing-manifest-github:release-download-manifest.tsv)+ speed-probe-*:release-download-manifest.tsv){printf 'penguin-release-download-manifest\t1\tv0.0.0-test\n'printf 'probe\tsmall\tprobe-64k.bin\t65536\t%s\n' "$PROBE64_HASH"@@ -365,17 +385,17 @@ case "$MODE:$base" inprintf 'asset\t%s\t%s\t%s\n' "$HOST_ASSET" "$SPEED_PROBE_ASSET_SIZE" "$HOST_ASSET_HASH"} > "$output";;- speed-probe-github-fast:probe-64k.bin | speed-probe-github-below-threshold:probe-64k.bin) cp "$PROBE64" "$output" ;;- speed-probe-github-fast:probe-1m.bin | speed-probe-github-below-threshold:probe-1m.bin) cp "$PROBE1M" "$output" ;;- forwarder-oss:install.sh | forced-oss-payload:install.sh | forwarder-auto-github:install.sh | forwarder-invalid-metadata:install.sh | canonical:install.sh | speed-probe-github-fast:install.sh | speed-probe-github-below-threshold:install.sh) cp "$ROOT_DIR/install.sh" "$output" ;;+ speed-probe-*:probe-64k.bin) cp "$PROBE64" "$output" ;;+ speed-probe-*:probe-1m.bin) cp "$PROBE1M" "$output" ;;+ forwarder-oss:install.sh | forced-oss-payload:install.sh | forwarder-auto-github:install.sh | forwarder-invalid-metadata:install.sh | canonical:install.sh | speed-probe-*:install.sh) cp "$ROOT_DIR/install.sh" "$output" ;;404:penguin-*) exit 22 ;;network:penguin-*) exit 7 ;;outer-sha-mismatch:penguin-*.sha256) printf '%064d %s\n' 0 "${base%.sha256}" > "$output" ;;outer-sha-mismatch:penguin-*) cp "$ARTIFACT_DIR/$base" "$output" ;;inner-sha-mismatch:penguin-*.sha256) cp "$BAD_BUNDLE.sha256" "$output" ;;inner-sha-mismatch:penguin-*) cp "$BAD_BUNDLE" "$output" ;;- speed-probe-github-fast:penguin-*.sha256 | speed-probe-github-below-threshold:penguin-*.sha256 | speed-probe-missing-manifest:penguin-*.sha256) cp "$ARTIFACT_DIR/$base" "$output" ;;- speed-probe-github-fast:penguin-* | speed-probe-github-below-threshold:penguin-* | speed-probe-missing-manifest:penguin-*) cp "$ARTIFACT_DIR/$base" "$output" ;;+ speed-probe-*:penguin-*.sha256) cp "$ARTIFACT_DIR/$base" "$output" ;;+ speed-probe-*:penguin-*) cp "$ARTIFACT_DIR/$base" "$output" ;;primary-network:penguin-*.sha256) cp "$ARTIFACT_DIR/$base" "$output" ;;primary-network:penguin-*) cp "$ARTIFACT_DIR/$base" "$output" ;;forced-oss-payload:penguin-*.sha256) cp "$ARTIFACT_DIR/$base" "$output" ;;@@ -390,8 +410,12 @@ if [ -n "$writeout" ]; thencase "$MODE:$url" inspeed-probe-github-fast:https://github.com/*/probe-1m.bin) printf '%s' '0.020 0.120 8738133' ;;speed-probe-github-fast:*aliyuncs.com*/probe-1m.bin) printf '%s' '0.100 2.100 499321' ;;- speed-probe-github-below-threshold:https://github.com/*/probe-1m.bin) printf '%s' '0.020 4.287 245760' ;;- speed-probe-github-below-threshold:*aliyuncs.com*/probe-1m.bin) printf '%s' '0.020 5.140 204800' ;;+ # GitHub under the 262144 minimum, mirror well past 1.5x it: worth paying for.+ speed-probe-oss-clearly-faster:https://github.com/*/probe-1m.bin) printf '%s' '0.020 10.240 102400' ;;+ speed-probe-oss-clearly-faster:*aliyuncs.com*/probe-1m.bin) printf '%s' '0.020 3.413 307200' ;;+ # GitHub equally slow, mirror only 1.4x faster: not worth paying for, GitHub keeps it.+ speed-probe-oss-not-worth-switching:https://github.com/*/probe-1m.bin) printf '%s' '0.020 10.240 102400' ;;+ speed-probe-oss-not-worth-switching:*aliyuncs.com*/probe-1m.bin) printf '%s' '0.020 7.314 143360' ;;speed-probe-github-fast:*) printf '%s' '0.020 0.060 1092266' ;;*) printf '%s' '0.010 0.020 3276800' ;;esac@@ -473,9 +497,16 @@ grep -q "github.com/.*/releases/download/v0.0.0-test/$HOST_ASSET\$" "$WORK_DIR/srun_online_case speed-probe-default-on speed-probe-github-fast "" success 6 "" "" "$STAMPED_INSTALLER" auto __unsetgrep -q "github.com/.*/releases/download/v0.0.0-test/$HOST_ASSET\$" "$WORK_DIR/speed-probe-default-on.log" \|| fail_test "speed probe was not enabled by default"-run_online_case speed-probe-github-below-threshold speed-probe-github-below-threshold "" success 6 "" "" "$STAMPED_INSTALLER" auto 1-grep -q "penguin-harness-releases.oss-cn-beijing.aliyuncs.com/.*/$HOST_ASSET\$" "$WORK_DIR/speed-probe-github-below-threshold.log" \- || fail_test "speed probe did not keep OSS when GitHub was below the minimum speed"+# Below the minimum the mirror is measured too, which is the seventh request of these two cases.+run_online_case speed-probe-oss-clearly-faster speed-probe-oss-clearly-faster "" success 7 "" "" "$STAMPED_INSTALLER" auto 1+grep -q "aliyuncs.com/.*/probe-1m.bin\$" "$WORK_DIR/speed-probe-oss-clearly-faster.log" \+ || fail_test "speed probe did not measure the OSS mirror once GitHub was below the minimum speed"+grep -q "penguin-harness-releases.oss-cn-beijing.aliyuncs.com/.*/$HOST_ASSET\$" "$WORK_DIR/speed-probe-oss-clearly-faster.log" \+ || fail_test "speed probe did not switch to OSS when it was clearly faster than a slow GitHub"++run_online_case speed-probe-oss-not-worth-switching speed-probe-oss-not-worth-switching "" success 7 "" "" "$STAMPED_INSTALLER" auto 1+grep -q "github.com/.*/releases/download/v0.0.0-test/$HOST_ASSET\$" "$WORK_DIR/speed-probe-oss-not-worth-switching.log" \+ || fail_test "speed probe left GitHub even though OSS was not faster by the switch ratio"run_online_case speed-probe-missing-manifest speed-probe-missing-manifest "" success 4 "" "" "$STAMPED_INSTALLER" auto 1grep -q "Download source test was inconclusive" "$WORK_DIR/speed-probe-missing-manifest.output" \