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.
154 lines
11 KiB
TypeScript
154 lines
11 KiB
TypeScript
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
import { once } from "node:events";
|
|
import { readFile, writeFile } from "node:fs/promises";
|
|
import { join, resolve } from "node:path";
|
|
import { createInterface } from "node:readline";
|
|
import { CdpConnection, cleanupRun, createPage, evaluate, fetchJsonBefore, launchChrome, reservePort, waitForSample,
|
|
waitForVersion, type PageHandle } from "../browser-gate-harness";
|
|
import { readAppEndpoint } from "../app-gate-endpoint";
|
|
import { pageProbe, type MediaSample } from "./page";
|
|
import { filteringProbe, preparePeerProbe, udpProbe } from "./udp";
|
|
|
|
export async function endpointWorker(): Promise<void> {
|
|
let chrome: ChildProcessWithoutNullStreams | null = null, app: ChildProcessWithoutNullStreams | null = null;
|
|
let cdp: CdpConnection | null = null, page: PageHandle | null = null;
|
|
const profile = process.env.PIIK_NETWORK_LAB_PROFILE;
|
|
if (!profile) throw new Error("Parent-owned browser profile is required");
|
|
const ports: number[] = [];
|
|
let rendezvous: Awaited<ReturnType<typeof preparePeerProbe>> | null = null;
|
|
const logs: Record<string, string> = {};
|
|
const log = (name: string, data: Buffer) => { logs[name] = ((logs[name] ?? "") + data).slice(-64_000); };
|
|
let closed = false;
|
|
const cleanup = async () => {
|
|
if (closed) return;
|
|
closed = true;
|
|
rendezvous?.close();
|
|
return cleanupRun({ chrome, native: app, cdp, server: null, profile, ports });
|
|
};
|
|
const sample = () => evaluate<MediaSample>(cdp!, page!, "networkLab.sample()", Date.now() + 5000);
|
|
const click = async (selector: string) => {
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`Boolean(document.querySelector(${JSON.stringify(selector)}))`, deadline), Boolean, 10_000);
|
|
await evaluate(cdp!, page!, `document.querySelector(${JSON.stringify(selector)}).click()`, Date.now() + 5000);
|
|
};
|
|
try {
|
|
for await (const line of createInterface({ input: process.stdin })) {
|
|
const request = JSON.parse(line) as { id: number; action: string; origin?: string; app?: boolean;
|
|
url?: string; output?: string; delayMs?: number; load?: boolean; ipv6?: boolean; prediction?: boolean; sfuOnly?: boolean; peer?: { address: string; port: number } };
|
|
try {
|
|
let result: unknown;
|
|
if (request.action === "probe") {
|
|
result = await udpProbe(request.load === true, request.ipv6 === true);
|
|
} else if (request.action === "filter-probe") {
|
|
result = await filteringProbe();
|
|
} else if (request.action === "peer-prepare") {
|
|
rendezvous?.close(); rendezvous = await preparePeerProbe(); result = rendezvous.mapping;
|
|
} else if (request.action === "peer-probe") {
|
|
if (!rendezvous) throw new Error("Survey must precede peer probing");
|
|
result = await rendezvous.run(request.peer!);
|
|
} else if (request.action === "start") {
|
|
const origin = new URL(request.origin!).origin;
|
|
await waitForSample(deadline => fetchJsonBefore<{ status: string }>(`${origin}/healthz`, deadline),
|
|
value => value.status === "ok", 10_000);
|
|
if (request.app) {
|
|
app = spawn(resolve(`build/network-lab/bin/piik-app${process.platform === "win32" ? ".exe" : ""}`), ["--site", origin, "--debug", "--config", join(profile, "app.json")],
|
|
{ stdio: "pipe", windowsHide: true, env: { ...process.env, PIIK_CLIENT_GATE_NO_BROWSER: "true", PIIK_LOG_DIR: join(profile, "logs") } });
|
|
app.stderr.on("data", data => log("app", data));
|
|
await once(app, "spawn");
|
|
ports.push((await readAppEndpoint(app)).port); app.stdout.resume();
|
|
}
|
|
const debugPort = await reservePort(); ports.push(debugPort);
|
|
chrome = await launchChrome(process.env.CHROME_PATH!, debugPort, profile, [
|
|
"--headless=new", "--no-sandbox", "--disable-dev-shm-usage", "--no-first-run", "--no-default-browser-check",
|
|
"--no-proxy-server", "--autoplay-policy=no-user-gesture-required", "--disable-background-timer-throttling",
|
|
"--disable-renderer-backgrounding", "--disable-backgrounding-occluded-windows",
|
|
`--unsafely-treat-insecure-origin-as-secure=${origin}`,
|
|
]);
|
|
chrome.stdout.resume(); chrome.stderr.on("data", data => log("browser", data));
|
|
const version = await waitForVersion(debugPort, chrome);
|
|
cdp = await CdpConnection.connect(version.webSocketDebuggerUrl, Date.now() + 10_000);
|
|
await cdp.call("Browser.setPermission", { origin, permission: { name: "loopback-network" }, setting: "granted" }, undefined, Date.now() + 5000);
|
|
result = { browser: version.Browser, app: request.app === true, appPort: request.app ? ports[0] : null };
|
|
} else if (request.action === "navigate") {
|
|
if (page) {
|
|
const oldTimeOrigin = await evaluate<number>(cdp!, page!, "performance.timeOrigin", Date.now() + 5000);
|
|
const navigation = await cdp!.call<{ loaderId?: string; errorText?: string }>("Page.navigate", { url: request.url! }, page.sessionId, Date.now() + 5000);
|
|
if (navigation.errorText) throw new Error(navigation.errorText);
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`${navigation.loaderId ? `performance.timeOrigin !== ${oldTimeOrigin} && ` : ""}document.readyState === 'complete' && Boolean(window.networkLab)`, deadline), Boolean, 10_000);
|
|
} else page = await createPage(cdp!, request.url!, pageProbe);
|
|
result = true;
|
|
} else if (request.action === "reload") {
|
|
const oldTimeOrigin = await evaluate<number>(cdp!, page!, "performance.timeOrigin", Date.now() + 5000);
|
|
await cdp!.call("Page.reload", {}, page!.sessionId, Date.now() + 5000);
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`performance.timeOrigin !== ${oldTimeOrigin} && document.readyState === 'complete' && Boolean(window.networkLab)`, deadline), Boolean, 10_000);
|
|
result = true;
|
|
} else if (request.action === "share") {
|
|
const advanced = 'button[aria-controls="host-advanced-door"]';
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`Boolean(document.querySelector(${JSON.stringify(advanced)}))`, deadline), Boolean, 10_000);
|
|
if (await evaluate<boolean>(cdp!, page!, `document.querySelector(${JSON.stringify(advanced)}).getAttribute('aria-expanded') !== 'true'`, Date.now() + 5000)) await click(advanced);
|
|
const prediction = 'button[role="switch"][aria-label^="Enhanced NAT traversal"]';
|
|
if (request.sfuOnly) {
|
|
if (request.prediction) throw new Error("SFU-only cannot request NAT enhancement");
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`Boolean(document.querySelector('button[role="switch"][aria-label^="Server media"][aria-disabled="true"][aria-checked="true"]')) && !document.querySelector(${JSON.stringify(prediction)})`, deadline), Boolean, 10_000);
|
|
} else if (request.prediction !== undefined) {
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`document.querySelector(${JSON.stringify(prediction)})?.getAttribute('aria-disabled') !== 'true' && Boolean(document.querySelector(${JSON.stringify(prediction)}))`, deadline), Boolean, 10_000);
|
|
const checked = await evaluate<boolean>(cdp!, page!,
|
|
`document.querySelector(${JSON.stringify(prediction)}).getAttribute('aria-checked') === 'true'`, Date.now() + 5000);
|
|
if (checked !== request.prediction) await click(prediction);
|
|
}
|
|
// Browser-to-App encoded fanout is the production H264 path. VP8
|
|
// deliberately stays in the Browser and must not masquerade as App WAN.
|
|
await click(app ? 'button[aria-label^="H264"]' : 'button[aria-label^="VP8"]');
|
|
await click('button[aria-label="720p"]');
|
|
await click("button.lr-tv-big.is-action");
|
|
// Selecting Browser before App discovery completes intentionally uses
|
|
// Browser fanout. An App scenario waits for the real control session.
|
|
if (app) await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`Boolean(document.querySelector('.lr-source-picker-refresh:not(:disabled)')) && networkLab.sample().then(value => value.controlOpen)`,
|
|
deadline), Boolean, 10_000);
|
|
await click('button[data-source-tab="browser"]');
|
|
await click(".lr-source-option.is-browser");
|
|
await waitForSample(sample, value => value.sharing && value.width > 0 &&
|
|
(request.prediction === undefined || value.natPrediction === request.prediction), 30_000);
|
|
result = await evaluate<string>(cdp!, page!, "document.querySelector('.lr-invite-url').value", Date.now() + 5000);
|
|
} else if (request.action === "sample") {
|
|
result = await sample();
|
|
} else if (request.action === "delay-peer-signals") {
|
|
if (!Number.isInteger(request.delayMs) || request.delayMs! < 0 || request.delayMs! > 30_000) throw new Error("Invalid signal delay");
|
|
await evaluate(cdp!, page!, `networkLab.delayPeerSignals(${request.delayMs})`, Date.now() + 5000);
|
|
result = true;
|
|
} else if (request.action === "reset-playback-progress") {
|
|
await evaluate(cdp!, page!, "networkLab.resetPlaybackProgress()", Date.now() + 5000);
|
|
result = true;
|
|
} else if (request.action === "freeze-picture") {
|
|
result = await evaluate(cdp!, page!, "networkLab.freezeCapture()", Date.now() + 5000);
|
|
} else if (request.action === "resume-picture") {
|
|
result = await evaluate(cdp!, page!, "networkLab.resumeCapture()", Date.now() + 5000);
|
|
} else if (request.action === "signal-probe") {
|
|
result = await evaluate(cdp!, page!, "networkLab.signalProbe()", Date.now() + 5000);
|
|
} else if (request.action === "logs") {
|
|
if (app) logs.app = await readFile(join(profile, "logs", "client.log"), "utf8")
|
|
.then(text => text.slice(-64_000), error => String(error));
|
|
result = logs;
|
|
} else if (request.action === "stop") {
|
|
await click('button[aria-label="Stop sharing"]'); result = true;
|
|
} else if (request.action === "screenshot") {
|
|
const shot = await cdp!.call<{ data: string }>("Page.captureScreenshot", { format: "png" }, page!.sessionId, Date.now() + 5000);
|
|
await writeFile(request.output!, Buffer.from(shot.data, "base64")); result = true;
|
|
} else if (request.action === "close") {
|
|
result = await cleanup();
|
|
} else throw new Error("Unknown endpoint action");
|
|
process.stdout.write(JSON.stringify({ id: request.id, result }) + "\n");
|
|
if (closed) break;
|
|
} catch (error) {
|
|
process.stdout.write(JSON.stringify({ id: request.id, error: error instanceof Error ? error.message : String(error) }) + "\n");
|
|
}
|
|
}
|
|
} finally { await cleanup(); }
|
|
}
|