Files
piik/scripts/mirror-release.mjs
T
AAA 42588f3a8b fix(media): stabilize reconnects and quality recovery
This maintenance phase corrects connection and media recovery after startup deadlines, congestion and packet loss. Route selection remains a bounded operation; Pion and LiveKit continue to own congestion control, adaptation and retransmission.

Changes stay within existing owners:

- Preserve an untried SFU fallback when a connected P2P candidate produces no first frame before its deadline. Retire expired native preparations using the current edge identity.
- Correct paced output, probe accounting and partial-recovery demand. Negotiate RTX consistently for native forwarding and SFU publication, including repaired stream identifiers for simulcast.
- Return working IPv4 mappings without waiting for optional IPv6 work, and separate NAT observations by the local socket/address that produced them.
- Keep optional App availability separate from basic source selection; stabilize nickname/chat layouts and restore volume from zero correctly.
- Retry complete Gitee reads, including response bodies and hash verification. Ambiguous uploads remain single attempts and are reconciled against the remote inventory before rerunning.

Related: #468, #464, #471. The repairs affect paths discussed in these reports; incomplete field diagnostics do not establish that each report has the same cause, so this PR does not automatically close them.

## Validation

- Web type checks, production build and 1,624 tests passed. Go core, formatting, vet and local target builds passed.
- Delayed RTX recovery reproduced the defect before the fix; the repaired-SSRC mutation also fails the focused regression. Real Windows H.264 and VP8 capture passed the SFU gates, including settings, reload recovery and retirement.
- The media lifecycle gate passed all 14 trials across Browser/App pairings and P2P/SFU handoffs. Native connectivity, paced forwarding and negative-control checks passed.
- Responsive UI and current website architecture links were checked; Gitee's current release was independently downloaded and matched against the GitHub originals.
- [Platform candidate](https://github.com/TNTcraftHIM/Piik/actions/runs/38669095115): all five Apps, both Server architectures and container checks passed at `c534573b`. Subsequent tracked changes only update documentation, the complete-matrix CI budget and race-test coverage.
- [Full network comparison](https://github.com/TNTcraftHIM/Piik/actions/runs/38667624364) completed 70 trials before the batch's 45-minute limit. The [remaining scenario](https://github.com/TNTcraftHIM/Piik/actions/runs/38672805155) passed three paired repetitions; all 71 scenario/setting variants are covered, with 58 media and 13 expected/observed unavailable outcomes. Six negative controls passed, and owned resources were cleaned up. These are controlled observations, not a public success rate.
- The final validation also includes the shared forwarder under the Go race detector. The separate sole-active-output publication experiment still shows inconsistent recovery: two of four current-code repeats did not pass its recovery observation, so the limitation below remains open.

The native SFU allocator still has a measured recovery limitation when only its lowest rate-controlled encoding is active. Fixing that requires a supported upstream demand input; no second controller or allocator fork is introduced. Unmatched capture-failure reports and physical-platform coverage retain their documented evidence limits.

## Release notes

### 中文

这是一次连接与播放稳定性更新,重点改善重连、弱网后的画质恢复和下载镜像可靠性。与 Piik 2.0.0 保持兼容。

- 修复连接等待超时后过早跳过备用线路的问题,保留尚未尝试的媒体服务器兜底机会。
- 改善原生分享在网络拥塞后的画质恢复,并修复转发和媒体服务器发布链路上的视频重传协商遗漏。
- 修复原生观看准备超时后的清理与重试,以及音量从零恢复时的异常。
- 避免可选的 IPv6 端口映射拖慢 IPv4 准备,并修正多网卡环境下的 NAT 预测观测归属。
- 修复昵称编辑、聊天字数变化引起的布局移动;保持 App 提示简洁,并为更新提示补充官网备用下载入口。
- 修复 Gitee 镜像同步在传输中途断开时未重试的问题,校验通过后才完成镜像发布。

仍在跟进:部分原生媒体服务器链路的弱网后恢复仍可能偏慢;尚缺匹配诊断的采集失败反馈不能确认已解决。

### English

This maintenance update improves connection and playback recovery after interruptions and congestion, along with download-mirror reliability. It remains compatible with Piik 2.0.0.

- Preserve untried media-server fallback routes when a connection reaches its waiting deadline.
- Improve native sharing quality recovery after congestion and fix missing video retransmission negotiation in forwarding and media-server publication paths.
- Correct cleanup and retry after native viewing preparation expires, and restore playback volume correctly from zero.
- Prevent optional IPv6 port mapping from delaying IPv4 preparation, and associate NAT-prediction observations with the correct local interface.
- Stabilize nickname editing and chat counters, keep App guidance unobtrusive, and add the website's alternate downloads to update notices.
- Retry interrupted Gitee mirror transfers and complete publication only after verification succeeds.

Still under investigation: recovery after congestion can remain slow on some native media-server paths. Capture-failure reports without matching diagnostics are not claimed as resolved.
2026-10-14 22:57:17 -04:00

150 lines
7.7 KiB
JavaScript

import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { openAsBlob } from "node:fs";
import { setTimeout as delay } from "node:timers/promises";
import { readReleaseArtifacts } from "./release-artifacts.mjs";
const [directory, version, revision, option] = process.argv.slice(2);
if (option && option !== "--dry-run") {
throw new Error("Use mirror-release.mjs <artifacts> <version> <full-SHA> [--dry-run]");
}
const { files } = readReleaseArtifacts(directory, version, revision);
if (files.some((file) => file.size > 100_000_000)) throw new Error("Gitee's 100 MB attachment limit is exceeded");
const repository = "TNTcraftHIM/Piik";
const api = `https://gitee.com/api/v5/repos/${repository}`;
const marker = `<!-- piik-source: ${revision} -->`;
const token = process.env.GITEE_TOKEN?.trim();
function requireLatestSource() {
const latest = JSON.parse(execFileSync("gh", ["api", `repos/${repository}/releases/latest`],
{ encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 30_000 }));
if (latest.tag_name !== version || latest.target_commitish !== revision ||
latest.draft !== false || latest.prerelease !== false) {
throw new Error("Only the latest GitHub release may create or complete a Gitee mirror");
}
}
async function fetchResponse(url, options, timeout, consume) {
const attempts = (options.method ?? "GET") === "GET" ? 3 : 1;
for (let attempt = 1; ; attempt++) {
const signal = AbortSignal.timeout(timeout);
let response;
try {
response = await fetch(url, { ...options, signal });
// Receiving headers is not a completed read. Keep JSON decoding and the
// entire anonymous package/hash verification inside the same retry bound.
if (attempt === attempts || ![408, 429, 500, 502, 503, 504].includes(response.status)) {
return await consume(response);
}
} catch (error) {
if (attempt === attempts || !(signal.aborted || error instanceof TypeError || error?.name === "TimeoutError")) {
throw new Error(`Gitee ${options.method ?? "GET"} ${new URL(url).pathname}: ${error.message}`);
}
} finally {
if (response?.body && !response.bodyUsed) await response.body.cancel().catch(() => {});
}
console.log(`Retry Gitee read ${new URL(url).pathname}: ${attempt + 1}/${attempts}`);
await delay(attempt * 1_000);
}
}
async function request(path, method = "GET", body) {
const multipart = body instanceof FormData;
console.log(`Gitee ${method} ${path}`);
// A timed-out upload may already exist. Retry only reads; a script rerun
// reconciles attachment identities before any subsequent write.
return fetchResponse(api + path, {
method, redirect: "error",
headers: { Accept: "application/json", Authorization: `Bearer ${token}`,
...(!body || multipart ? {} : { "Content-Type": "application/json" }) },
body: body ? multipart ? body : JSON.stringify(body) : undefined,
}, multipart ? 180_000 : 20_000, async response => {
if (response.status === 404 && method === "GET") return null;
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
});
}
// Verify anonymously: credentials are never forwarded to attachment redirects.
async function verifyDownload(uploaded, file) {
const expectedURL = `https://gitee.com/${repository}/releases/download/${version}/${file.name}`;
if (uploaded?.size !== file.size || uploaded.browser_download_url !== expectedURL) {
throw new Error(`Mirror attachment metadata mismatch: ${file.name}`);
}
console.log(`Verify Gitee package: ${file.name} (${file.size} bytes)`);
await fetchResponse(expectedURL, {}, 180_000, async response => {
if (!response.ok || !response.body) throw new Error(`Mirror attachment is not anonymously downloadable: ${file.name}`);
const hash = createHash("sha256");
let size = 0;
for await (const chunk of response.body) {
size += chunk.length;
if (size > file.size) throw new Error(`Mirror attachment size mismatch: ${file.name}`);
hash.update(chunk);
}
if (size !== file.size || hash.digest("hex") !== file.sha256) {
throw new Error(`Mirror attachment checksum mismatch: ${file.name}`);
}
});
}
if (option === "--dry-run") {
console.log(JSON.stringify({ version, revision, files: files.length, bytes: files.reduce((sum, file) => sum + file.size, 0) }));
} else {
if (!token) throw new Error("GITEE_TOKEN must be supplied by the publisher's environment");
const source = JSON.parse(execFileSync("gh", ["api", `repos/${repository}/releases/tags/${version}`],
{ encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }));
if (source.draft !== false || source.prerelease !== false || source.tag_name !== version || source.target_commitish !== revision ||
source.html_url !== `https://github.com/${repository}/releases/tag/${version}`) {
throw new Error("Only an already-published matching GitHub stable release can be mirrored");
}
// Compare every byte identity with GitHub before creating or changing the mirror.
for (const file of files) {
const asset = source.assets.find((asset) => asset.name === file.name);
if (asset?.state !== "uploaded" || asset.size !== file.size || asset.digest !== `sha256:${file.sha256}`) {
throw new Error(`GitHub attachment checksum mismatch or unavailable: ${file.name}`);
}
}
let release = await request(`/releases/tags/${version}`);
if (release && (release.tag_name !== version ||
(release.prerelease !== false && release.prerelease !== true) ||
!release.body?.split(/\r?\n/).includes(marker))) {
throw new Error("Existing mirror release belongs to a different or unknown source revision");
}
const body = `${source.body ?? ""}\n\nSource: https://github.com/${repository}/commit/${revision}\n\n${marker}\n`;
if (!release || release.prerelease) requireLatestSource();
if (!release) {
const repo = await request("");
if (!repo || repo.private || !repo.default_branch) throw new Error("A public initialized Gitee mirror is required");
release = await request("/releases", "POST", {
tag_name: version, name: source.name || `Piik ${version}`, body, prerelease: true,
target_commitish: repo.default_branch,
});
}
if (!Number.isSafeInteger(release.id) || release.id <= 0) throw new Error("Invalid Gitee release identity");
const attachments = await request(`/releases/${release.id}/attach_files?per_page=100`);
if (!Array.isArray(attachments) || attachments.length >= 100) throw new Error("Unexpected mirror attachment list");
for (const file of files) {
let uploaded = attachments.find((asset) => asset.name === file.name);
if (!uploaded) {
if (!release.prerelease) throw new Error("Published mirror is incomplete; publish a corrected new version");
console.log(`Upload Gitee package: ${file.name} (${file.size} bytes)`);
const form = new FormData();
form.append("file", await openAsBlob(file.path), file.name);
uploaded = await request(`/releases/${release.id}/attach_files`, "POST", form);
}
await verifyDownload(uploaded, file);
}
// Gitee has no draft API. Its preview flag fences incomplete uploads from checks.
if (release.prerelease) {
// Uploads may take minutes; a newer GitHub release must not be displaced.
requireLatestSource();
const completed = await request(`/releases/${release.id}`, "PATCH", {
tag_name: version, name: source.name || `Piik ${version}`, body, prerelease: false,
});
if (completed.prerelease !== false || completed.tag_name !== version) {
throw new Error("Gitee did not confirm the completed stable mirror");
}
}
console.log(`Verified Gitee mirror ${version} from ${revision} (${files.length} attachments).`);
}