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.
This commit is contained in:
AAA authored and GitHub committed 2026-10-14 22:57:17 -04:00 Unverified
1 parent 3707e48225
commit 42588f3a8b
69 files changed
+1472 -347

No files matched your search

+1
View File
@@ -222,6 +222,7 @@ if (mode === "--race") {
runGoTests(process.env.PIIK_GO?.trim() || "go", [
"./internal/app/portmapping", "./internal/app/mediaedge",
"./internal/app/nativecontrol", "./internal/app/loopback",
"./internal/media/forwarding",
"./internal/server/app",
"github.com/netbirdio/go-nat/...", "github.com/jackpal/go-nat-pmp",
], ["-race", "-count=1", "-timeout=2m"]);
+201
View File
@@ -0,0 +1,201 @@
import { execFileSync, spawn } from "node:child_process";
import { createHash } from "node:crypto";
import { createSocket } from "node:dgram";
import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
import { networkInterfaces, tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { parseArgs } from "node:util";
import { cleanupRun, fetchJsonBefore, reservePort, waitForSample } from "./browser-gate-harness";
import { Endpoint } from "./network-lab/endpoint-client";
import type { MediaSample } from "./network-lab/page";
import { checkAppPath, checkContinuity, hasPicture } from "./network-lab/scenarios";
// Real UI/room/transport on loopback. NAT and bandwidth faults remain in the
// namespace laboratory; this gate isolates lifecycle ordering from reachability.
const { values } = parseArgs({ options: { cases: { type: "string" }, repeat: { type: "string", default: "1" },
negative: { type: "string" }, list: { type: "boolean" } } });
if (values.negative && !["frozen-picture", "cancel"].includes(values.negative)) throw new Error("Unknown negative control");
const cases = [
{ id: "browser-browser", host: false, viewer: false, sfu: false },
{ id: "app-browser", host: true, viewer: false, sfu: false },
{ id: "browser-app", host: false, viewer: true, sfu: false },
{ id: "app-app", host: true, viewer: true, sfu: false },
{ id: "sfu-browser", host: false, viewer: false, sfu: true },
{ id: "fallback-browser", host: false, viewer: false, sfu: false, fallback: true },
{ id: "fallback-app", host: true, viewer: false, sfu: false, fallback: true },
];
const selected = values.cases ? values.cases.split(",").map(id => {
const item = cases.find(value => value.id === id);
if (!item) throw new Error(`Unknown lifecycle case: ${id}`);
return item;
}) : cases;
const repeats = Number(values.repeat);
if (!Number.isInteger(repeats) || repeats < 1 || repeats > 20 || new Set(selected).size !== selected.length) throw new Error("Invalid repetition or duplicated case");
if (values.list) { process.stdout.write(JSON.stringify(cases, null, 2) + "\n"); process.exit(0); }
if (!process.env.CHROME_PATH) throw new Error("CHROME_PATH is required");
const root = resolve(import.meta.dirname, ".."), suffix = process.platform === "win32" ? ".exe" : "";
const localAddresses = Object.values(networkInterfaces()).flatMap(addresses => addresses?.map(value => value.address) ?? []);
const output = join(root, "build/media-lifecycle", new Date().toISOString().replaceAll(/[:.]/g, "-"));
await mkdir(output, { recursive: true });
const git = (...args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", windowsHide: true }).trim();
const binaries = await Promise.all(["server", "app"].map(async name => ({ name,
sha256: createHash("sha256").update(await readFile(join(root, `build/network-lab/bin/piik-${name}${suffix}`))).digest("hex") })));
await writeFile(join(output, "environment.json"), JSON.stringify({ commit: git("rev-parse", "HEAD"),
status: git("status", "--short"), platform: process.platform, arch: process.arch, binaries, selected, repeats }, null, 2));
const controller = new AbortController(), signal = controller.signal;
const interrupt = () => controller.abort(new Error("Lifecycle gate cancelled"));
process.once("SIGINT", interrupt); process.once("SIGTERM", interrupt);
// Deliberately do not inherit operator/product settings or credentials.
const env = { PATH: process.env.PATH, SystemRoot: process.env.SystemRoot, TEMP: process.env.TEMP,
TMP: process.env.TMP, HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE, CHROME_PATH: process.env.CHROME_PATH };
const summaries: Array<Record<string, unknown>> = [];
for (let iteration = 0; iteration < repeats && !signal.aborted; iteration++) for (const scenario of selected) {
if (signal.aborted) break;
const directory = join(output, `${scenario.id}-${iteration + 1}`); await mkdir(directory);
const port = await reservePort(), origin = `http://127.0.0.1:${port}`;
// Distinct approved origins prevent two local Apps from impersonating one
// another. Namespace trials already isolate their loopback services.
const viewerOrigin = scenario.host && scenario.viewer ? `http://localhost:${port}` : origin;
const udp = createSocket("udp4");
const mediaPort = await new Promise<number>((resolvePort, reject) => {
udp.once("error", reject); udp.bind(0, "127.0.0.1", () => { const port = udp.address().port; udp.close(() => resolvePort(port)); });
});
let serverLog = "";
const server = spawn(resolve(root, `build/network-lab/bin/piik-server${suffix}`), [], { cwd: directory, stdio: "pipe", windowsHide: true,
env: { ...env, PIIK_ENV: "development", PIIK_DEBUG: "route", ROOM_DATABASE_PATH: ":memory:",
LISTEN_HOST: "127.0.0.1", PORT: String(port), PUBLIC_BASE_URL: origin, ALLOWED_ORIGINS: [...new Set([origin, viewerOrigin])].join(","),
PIIK_LOG_DIR: join(directory, "logs"),
...((scenario.sfu || scenario.fallback) ? { SFU_LISTEN_HOST: "127.0.0.1", SFU_UDP_PORT: String(mediaPort),
SFU_PUBLIC_IP: "127.0.0.1", SFU_ONLY: String(scenario.sfu) } : {}) } });
let serverFailure: Error | undefined;
server.on("error", error => { serverFailure = error; });
server.stdout.on("data", data => { serverLog = (serverLog + data).slice(-128_000); });
server.stderr.on("data", data => { serverLog = (serverLog + data).slice(-128_000); });
const endpoints: Endpoint[] = [];
let versions: Array<{ browser: string; app: boolean; appPort: number | null }> = [];
const result = { scenario: scenario.id, iteration: iteration + 1, passed: false, stage: "startup", error: "",
versions: [] as typeof versions,
stages: [] as Array<{ name: string; firstPictureMs: number; route: string | null; peer: number }>,
samples: [] as Array<{ stage: string; host: MediaSample; viewer: MediaSample }>, cleanup: [] as unknown[] };
const stage = (name: string) => { result.stage = name; process.stdout.write(JSON.stringify({ case: scenario.id, stage: name }) + "\n"); };
const sample = async () => {
signal.throwIfAborted();
const [host, viewer] = await Promise.all(endpoints.map(endpoint => endpoint.call<MediaSample>("sample")));
result.samples.push({ stage: result.stage, host: host!, viewer: viewer! });
return { host: host!, viewer: viewer! };
};
const media = async (name: string, previousPeer?: number, expectedRoute = scenario.sfu ? "sfu" : "peer") => {
stage(name); const started = performance.now();
let first: MediaSample | undefined, firstAt = 0;
while (performance.now() - started < 40_000) {
const { viewer } = await sample();
if (viewer.events.some(event => event.reason === "route-exhausted")) throw new Error("Route exhausted");
if (hasPicture(viewer) && viewer.route === expectedRoute && viewer.playbackPeerId !== previousPeer) {
if (!first || first.playbackPeerId !== viewer.playbackPeerId) { first = viewer; firstAt = performance.now(); }
else if (performance.now() - firstAt >= 3000) {
checkContinuity(first, viewer);
if (viewer.errors.length) throw new Error(`Viewer errors: ${viewer.errors.join("; ")}`);
const last = result.samples.at(-1)!;
for (const [index, page] of [last.host, viewer].entries()) {
const appPort = versions[index]?.appPort;
if (appPort && !page.controlOrigins.includes(`ws://127.0.0.1:${appPort}`)) throw new Error("Page did not attach its own App");
}
if (scenario.host && expectedRoute === "peer") checkAppPath(last.host, "prepare-edge", localAddresses);
if (scenario.viewer && expectedRoute === "peer") checkAppPath(viewer, "receive-offer", localAddresses);
result.stages.push({ name, firstPictureMs: firstAt - started, route: viewer.route, peer: viewer.playbackPeerId });
return viewer;
}
} else first = undefined;
await delay(250, undefined, { signal });
}
throw new Error(`No sustained ${expectedRoute} media during ${name}`);
};
try {
await waitForSample(deadline => {
if (serverFailure) throw serverFailure;
return fetchJsonBefore<{ status: string }>(`${origin}/healthz`, deadline);
}, value => value.status === "ok", 15_000);
for (let index = 0; index < 2; index++) endpoints.push(new Endpoint(null,
await mkdtemp(join(tmpdir(), "piik-client-media-")), signal, env));
versions = await Promise.all(endpoints.map((endpoint, index) => endpoint.call<typeof versions[number]>("start", {
origin: index ? viewerOrigin : origin, app: index ? scenario.viewer : scenario.host })));
result.versions = versions;
await endpoints[0]!.call("navigate", { url: origin + (scenario.host ? "/#piik-client=1" : "/") });
const share = () => endpoints[0]!.call<string>("share", { sfuOnly: scenario.sfu });
const invitation = await share();
if (scenario.fallback) await endpoints[0]!.call("delay-peer-signals", { delayMs: 15000 });
await endpoints[1]!.call("navigate", { url: invitation.replace(origin, viewerOrigin) + (scenario.viewer ? "&piik-client=1" : "") });
let received = await media("initial", undefined, scenario.fallback ? "sfu" : undefined);
if (scenario.fallback) {
if (!result.samples.some(row => row.host.events.some(event => event.type === "test-signal-delayed"))) throw new Error("Signaling fault was not exercised");
await endpoints[1]!.call("reset-playback-progress");
received = await media("direct-continuation", received.playbackPeerId, "peer");
if (received.playbackProgress.renderedFrames < 30 || received.playbackProgress.maxFrameGapMs > 1500) {
throw new Error("Working SFU playback stalled during direct continuation");
}
}
if (values.negative === "cancel") {
stage("cancel-negative-control"); controller.abort(new Error("Lifecycle gate cancelled")); signal.throwIfAborted();
}
if (values.negative === "frozen-picture") {
stage("frozen-negative-control"); await endpoints[0]!.call("freeze-picture");
await delay(2000, undefined, { signal });
const frozen = (await sample()).viewer;
await delay(3000, undefined, { signal });
checkContinuity(frozen, (await sample()).viewer);
throw new Error("Frozen source incorrectly passed");
}
stage("quiet-source"); await endpoints[0]!.call("freeze-picture");
await delay(6000, undefined, { signal });
const quiet = await sample();
if (!quiet.host.sharing || quiet.viewer.playbackPeerId !== received.playbackPeerId) throw new Error("Quiet source retired a healthy route");
await endpoints[0]!.call("resume-picture");
const resumed = await media("source-resumed");
if (resumed.playbackPeerId !== received.playbackPeerId) throw new Error("Source repaint needed a new route");
stage("stop"); await endpoints[0]!.call("stop");
await share(); received = await media("reshare", received.playbackPeerId);
stage("viewer-reload"); await endpoints[1]!.call("reload");
received = await media("viewer-rejoined");
stage("host-reload"); await endpoints[0]!.call("reload"); await share();
received = await media("host-restarted", received.playbackPeerId);
stage("join-before-share"); await endpoints[0]!.call("stop"); await endpoints[1]!.call("reload");
await share(); await media("waiting-viewer-resumed");
if (!scenario.sfu) {
stage("replace-during-prepare"); await endpoints[0]!.call("stop");
await endpoints[0]!.call("delay-peer-signals", { delayMs: 8000 });
await share();
await waitForSample(sample, row => row.host.events.some(event => event.type === "test-signal-delayed" &&
event.at > row.host.at - 3000), 10_000);
await endpoints[0]!.call("stop");
await endpoints[0]!.call("delay-peer-signals", { delayMs: 0 });
await share(); received = await media("replacement-active");
// Release the old real SDP after the new share is active. Stale signaling
// must neither replace that route nor turn into a terminal page error.
await delay(8500, undefined, { signal });
const afterStale = await media("stale-signals-released");
if (received.playbackPeerId !== afterStale.playbackPeerId) throw new Error("Retired signaling replaced the current route");
}
await endpoints[0]!.call("stop"); result.passed = true;
} catch (error) { result.error = error instanceof Error ? error.message : String(error); }
finally {
await Promise.all(endpoints.map(async (endpoint, index) => {
await endpoint.call("screenshot", { output: join(directory, `${index}.png`) }, 5000).catch(() => {});
await writeFile(join(directory, `endpoint-${index}.json`), JSON.stringify(await endpoint.call("logs", {}, 5000).catch(String), null, 2));
result.cleanup.push(await endpoint.call("close", {}, 30_000).catch(error => ({ error: String(error) })));
}));
for (const endpoint of endpoints) result.cleanup.push(await cleanupRun({ chrome: null, native: null, cdp: null,
server: endpoint.process, profile: endpoint.profile, ports: [] }).catch(error => ({ error: String(error) })));
result.cleanup.push(await cleanupRun({ chrome: null, native: null, cdp: null, server, profile: null, ports: [port] }));
if (result.cleanup.some(item => !Object.values(item as object).every(flag => flag === true))) result.passed = false;
if (signal.aborted) { result.passed = false; result.error = "Cancelled"; }
await writeFile(join(directory, "result.json"), JSON.stringify(result, null, 2));
await writeFile(join(directory, "server.log"), serverLog);
const { samples: _samples, ...summary } = result; summaries.push(summary);
process.stdout.write(JSON.stringify(summary) + "\n");
}
}
process.off("SIGINT", interrupt); process.off("SIGTERM", interrupt);
await writeFile(join(output, "summary.json"), JSON.stringify(summaries, null, 2));
process.stdout.write(JSON.stringify({ report: output }) + "\n");
if (signal.aborted || summaries.some(result => !result.passed)) process.exitCode = 1;
+37 -22
View File
@@ -24,33 +24,45 @@ function requireLatestSource() {
}
}
async function fetchResponse(url, options, timeout) {
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 {
const response = await fetch(url, { ...options, signal: AbortSignal.timeout(timeout) });
if (attempt === attempts || ![408, 429, 500, 502, 503, 504].includes(response.status)) return response;
await response.body?.cancel();
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 || !(error instanceof TypeError || error?.name === "TimeoutError")) throw 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.
const response = await fetchResponse(api + path, {
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);
if (response.status === 404 && method === "GET") return null;
if (!response.ok) throw new Error(`Gitee ${method} ${path}: HTTP ${response.status}`);
return response.json();
}, 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.
@@ -59,18 +71,20 @@ async function verifyDownload(uploaded, file) {
if (uploaded?.size !== file.size || uploaded.browser_download_url !== expectedURL) {
throw new Error(`Mirror attachment metadata mismatch: ${file.name}`);
}
const response = await fetchResponse(expectedURL, {}, 180_000);
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}`);
}
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") {
@@ -113,6 +127,7 @@ if (option === "--dry-run") {
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);
+2 -42
View File
@@ -3,11 +3,11 @@ import { once } from "node:events";
import { access, mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { createInterface } from "node:readline";
import { parseArgs } from "node:util";
import { setTimeout as delay } from "node:timers/promises";
import { cleanupRun, withDeadline } from "./browser-gate-harness";
import { endpointWorker } from "./network-lab/endpoint";
import { Endpoint } from "./network-lab/endpoint-client";
import { command, LabNetwork, SITE_IP, SITE_IPV6, SITE_ORIGIN } from "./network-lab/network";
import { checkAppPath, checkCalibration, checkContinuity, checkFaultHit, checkMapping, checkQualityRecovery, hasPicture, selectScenarios, summarizeTrials, type Scenario, type TrialSummary } from "./network-lab/scenarios";
import { echoWorker, type ProbeResult } from "./network-lab/udp";
@@ -21,46 +21,6 @@ const { values } = parseArgs({ options: { worker: { type: "string" }, suite: { t
prediction: { type: "string", default: "on" },
ipv6: { type: "boolean" }, list: { type: "boolean" }, verify: { type: "boolean" }, negative: { type: "string" } } });
class Endpoint {
private id = 0;
private failure: Error | null = null;
private readonly pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();
readonly process: ChildProcessWithoutNullStreams;
constructor(namespace: string, readonly profile: string, private readonly signal: AbortSignal) {
this.process = spawn("ip", ["netns", "exec", namespace, process.execPath, "--import", "tsx", ENTRY, "--worker", "endpoint"],
{ cwd: ROOT, env: { ...labEnvironment(), PIIK_NETWORK_LAB_PROFILE: profile }, stdio: "pipe" });
this.process.stderr.on("data", data => process.stderr.write(data));
this.process.stdin.on("error", error => this.fail(error));
createInterface({ input: this.process.stdout }).on("line", line => {
try {
const reply = JSON.parse(line), pending = this.pending.get(reply.id);
if (!pending) return;
this.pending.delete(reply.id);
if (reply.error) pending.reject(new Error(reply.error)); else pending.resolve(reply.result);
} catch { this.fail(new Error("Invalid endpoint response")); }
});
this.process.on("error", error => this.fail(error));
this.process.on("exit", (code, signal) => this.fail(new Error(`Endpoint exited (${code ?? signal})`)));
}
private fail(error: Error): void { this.failure = error; for (const item of this.pending.values()) item.reject(error); this.pending.clear(); }
async call<T>(action: string, args: Record<string, unknown> = {}, timeout = 45_000): Promise<T> {
const id = ++this.id;
if (this.failure) throw this.failure;
const observeAbort = !["close", "logs", "screenshot"].includes(action);
if (observeAbort) this.signal.throwIfAborted();
const abort = () => this.pending.get(id)?.reject(new Error("Laboratory run cancelled"));
try {
return await withDeadline(() => new Promise<T>((resolveCall, reject) => {
this.pending.set(id, { resolve: value => resolveCall(value as T), reject });
if (observeAbort) this.signal.addEventListener("abort", abort, { once: true });
this.process.stdin.write(JSON.stringify({ id, action, ...args }) + "\n", error => {
if (error) { this.pending.delete(id); reject(error); }
});
}), Date.now() + timeout);
} finally { this.pending.delete(id); this.signal.removeEventListener("abort", abort); }
}
}
function labEnvironment(): NodeJS.ProcessEnv {
return { PATH: process.env.PATH, CHROME_PATH: process.env.CHROME_PATH, LANG: "C.UTF-8", TMPDIR: process.env.TMPDIR };
}
@@ -125,7 +85,7 @@ async function runCase(scenario: Scenario, seed: number, prediction: boolean, ou
await withDeadline(() => once(stun!.stdout, "data"), Date.now() + 5000);
}
for (let i = 0; i < (scenario.sibling ? 3 : 2); i++) endpoints.push(new Endpoint(network.endpoint(i),
await mkdtemp(join(tmpdir(), "piik-client-media-")), signal));
await mkdtemp(join(tmpdir(), "piik-client-media-")), signal, labEnvironment()));
stage("calibration");
const baselines = await Promise.all(endpoints.map(endpoint => endpoint.call<ProbeResult>("probe")));
result.mappingCalibration = baselines;
+47
View File
@@ -0,0 +1,47 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { resolve } from "node:path";
import { createInterface } from "node:readline";
import { withDeadline } from "../browser-gate-harness";
// Both laboratories use the same real UI worker. Only the network substrate differs.
export class Endpoint {
private id = 0;
private failure: Error | null = null;
private readonly pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();
readonly process: ChildProcessWithoutNullStreams;
constructor(namespace: string | null, readonly profile: string, private readonly signal: AbortSignal, env: NodeJS.ProcessEnv) {
const root = resolve(import.meta.dirname, "../..");
const args = [process.execPath, "--import", "tsx", resolve(root, "scripts/network-lab.ts"), "--worker", "endpoint"];
this.process = spawn(namespace ? "ip" : args.shift()!, namespace ? ["netns", "exec", namespace, ...args] : args,
{ cwd: root, env: { ...env, PIIK_NETWORK_LAB_PROFILE: profile }, stdio: "pipe", windowsHide: true });
this.process.stderr.on("data", data => process.stderr.write(data));
this.process.stdin.on("error", error => this.fail(error));
createInterface({ input: this.process.stdout }).on("line", line => {
try {
const reply = JSON.parse(line), pending = this.pending.get(reply.id);
if (!pending) return;
this.pending.delete(reply.id);
if (reply.error) pending.reject(new Error(reply.error)); else pending.resolve(reply.result);
} catch { this.fail(new Error("Invalid endpoint response")); }
});
this.process.on("error", error => this.fail(error));
this.process.on("exit", (code, signal) => this.fail(new Error(`Endpoint exited (${code ?? signal})`)));
}
private fail(error: Error): void { this.failure = error; for (const item of this.pending.values()) item.reject(error); this.pending.clear(); }
async call<T>(action: string, args: Record<string, unknown> = {}, timeout = 45_000): Promise<T> {
const id = ++this.id;
if (this.failure) throw this.failure;
const observeAbort = !["close", "logs", "screenshot"].includes(action);
if (observeAbort) this.signal.throwIfAborted();
const abort = () => this.pending.get(id)?.reject(new Error("Laboratory run cancelled"));
try {
return await withDeadline(() => new Promise<T>((resolveCall, reject) => {
this.pending.set(id, { resolve: value => resolveCall(value as T), reject });
if (observeAbort) this.signal.addEventListener("abort", abort, { once: true });
this.process.stdin.write(JSON.stringify({ id, action, ...args }) + "\n", error => {
if (error) { this.pending.delete(id); reject(error); }
});
}), Date.now() + timeout);
} finally { this.pending.delete(id); this.signal.removeEventListener("abort", abort); }
}
}
+33 -8
View File
@@ -34,7 +34,7 @@ export async function endpointWorker(): Promise<void> {
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; load?: boolean; ipv6?: boolean; prediction?: boolean; sfuOnly?: boolean; peer?: { address: string; port: number } };
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") {
@@ -51,8 +51,8 @@ export async function endpointWorker(): Promise<void> {
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"), ["--site", origin, "--debug", "--config", join(profile, "app.json")],
{ stdio: "pipe", env: { ...process.env, PIIK_CLIENT_GATE_NO_BROWSER: "true", PIIK_LOG_DIR: join(profile, "logs") } });
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();
@@ -68,18 +68,33 @@ export async function endpointWorker(): Promise<void> {
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 };
result = { browser: version.Browser, app: request.app === true, appPort: request.app ? ports[0] : null };
} else if (request.action === "navigate") {
page = await createPage(cdp!, request.url!, pageProbe);
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") {
await click('button[aria-controls="host-advanced-door"]');
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 {
} 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!,
@@ -98,12 +113,22 @@ export async function endpointWorker(): Promise<void> {
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 && value.natPrediction === request.prediction, 30_000);
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") {
+37 -5
View File
@@ -3,7 +3,18 @@
export const pageProbe = String.raw`(() => {
localStorage.setItem('piik:ui-lang','en'); localStorage.setItem('piik:ui-mode','text');
const peers=[], sockets=[], events=[], errors=[], controls=[];
let route=null,natPrediction=null,freezeCapture=()=>{};
let route=null,natPrediction=null,freezeCapture=()=>{},resumeCapture=()=>{},peerSignalDelay=0,peerSignalReleaseAt=0;
let observedVideo=null,frameCallback=0,renderedFrames=0,lastFrameAt=0,maxFrameGapMs=0;
const observeVideo=video=>{
if(video===observedVideo)return;
observedVideo?.cancelVideoFrameCallback(frameCallback);observedVideo=video;
if(!video)return;
const frame=now=>{
if(video!==observedVideo)return;
if(lastFrameAt)maxFrameGapMs=Math.max(maxFrameGapMs,now-lastFrameAt);
lastFrameAt=now;renderedFrames++;frameCallback=video.requestVideoFrameCallback(frame);
};frameCallback=video.requestVideoFrameCallback(frame);
};
const PC=RTCPeerConnection, WS=WebSocket;
const picture=document.createElement('canvas');picture.width=64;picture.height=36;
const pictureContext=picture.getContext('2d',{willReadFrequently:true});
@@ -30,7 +41,21 @@ export const pageProbe = String.raw`(() => {
record(events,value);
});
}
send(raw){if(this.url.includes('/control')){try{const m=JSON.parse(raw);record(controls,{type:m.type,connectionId:m.connectionId,punched:m.punched});}catch{}}super.send(raw);}
send(raw){
let m;try{m=JSON.parse(raw);}catch{}
if(this.url.includes('/control')){
if(m)record(controls,{type:m.type,connectionId:m.connectionId,punched:m.punched});
}else if(m?.type==='signal'&&peerSignalDelay>0){
// Delay real signaling once; never invent SDP, route state or readiness.
if(!peerSignalReleaseAt)peerSignalReleaseAt=performance.now()+peerSignalDelay;
const remaining=peerSignalReleaseAt-performance.now();
if(remaining>0){
record(events,{at:performance.now(),type:'test-signal-delayed',connectionId:m.connectionId});
setTimeout(()=>{if(this.readyState===WS.OPEN)super.send(raw);},remaining);return;
}
}
super.send(raw);
}
};
navigator.mediaDevices.getDisplayMedia=async()=>{
const canvas=document.createElement('canvas'); canvas.width=1280; canvas.height=720;
@@ -42,8 +67,9 @@ export const pageProbe = String.raw`(() => {
ctx.fillRect((x*64+frame*7)%1280,y*60,45,42);
}
ctx.fillStyle='#fff';ctx.font='70px sans-serif';ctx.fillText(String(frame++),80,540);};
draw();const timer=setInterval(draw,1000/30),stream=canvas.captureStream(30);
freezeCapture=()=>clearInterval(timer);
draw();let timer=setInterval(draw,1000/30);const stream=canvas.captureStream(30);
freezeCapture=()=>{clearInterval(timer);timer=null;};
resumeCapture=()=>{if(!timer)timer=setInterval(draw,1000/30);};
const video=stream.getVideoTracks()[0],stop=video.stop.bind(video);
video.stop=()=>{clearInterval(timer);stop();};
const ac=new AudioContext(),osc=ac.createOscillator(),dest=ac.createMediaStreamDestination();
@@ -52,7 +78,8 @@ export const pageProbe = String.raw`(() => {
sound.stop=()=>{if(stopped)return;stopped=true;osc.stop();void ac.close();stopSound();};
stream.addTrack(sound);return stream;
};
window.networkLab={freezeCapture:()=>freezeCapture(),async signalProbe(){
window.networkLab={freezeCapture:()=>freezeCapture(),resumeCapture:()=>resumeCapture(),delayPeerSignals:ms=>{peerSignalDelay=ms;peerSignalReleaseAt=0;},
resetPlaybackProgress:()=>{renderedFrames=0;lastFrameAt=performance.now();maxFrameGapMs=0;},async signalProbe(){
const socket=sockets.findLast(s=>!s.url.includes('/control')&&s.readyState===WS.OPEN);
if(!socket)return false;
return new Promise(resolve=>{
@@ -89,6 +116,7 @@ export const pageProbe = String.raw`(() => {
}
}
const video=document.querySelector('video');
observeVideo(video);
const playbackTrack=video?.srcObject?.getVideoTracks?.()[0];
const playbackPeerId=playbackTrack?peers.findIndex(peer=>peer.getReceivers().some(receiver=>receiver.track===playbackTrack)):-1;
let pictureHash=null;
@@ -99,8 +127,10 @@ export const pageProbe = String.raw`(() => {
}
return{at:performance.now(),width:video?.videoWidth||0,height:video?.videoHeight||0,
frames:video?.getVideoPlaybackQuality().totalVideoFrames||0,pictureHash,playbackPeerId,route,natPrediction,stats,events:[...events],errors:[...errors],controls:[...controls],
playbackProgress:{renderedFrames,lastFrameAt,maxFrameGapMs:Math.max(maxFrameGapMs,lastFrameAt?performance.now()-lastFrameAt:0)},
sharing:!!document.querySelector('button[aria-label="Stop sharing"]'),
controlOpen:sockets.some(s=>s.url.includes('/control')&&s.readyState===WS.OPEN),
controlOrigins:sockets.filter(s=>s.url.includes('/control')&&s.readyState===WS.OPEN).map(s=>new URL(s.url).origin),
peerStates:peers.map(p=>p.connectionState),text:document.body.innerText.slice(-2000)};
}};
})();`;
@@ -121,6 +151,8 @@ export interface MediaSample {
controls: Array<{ type: string; connectionId?: string }>;
sharing: boolean;
controlOpen: boolean;
controlOrigins: string[];
playbackProgress: { renderedFrames: number; lastFrameAt: number; maxFrameGapMs: number };
peerStates: string[];
text: string;
}
+1
View File
@@ -26,6 +26,7 @@
"access-privacy-gate.ts",
"browser-local-pool-probe.ts",
"network-lab.ts",
"media-lifecycle-gate.ts",
"app-browser-fanout-gate.ts",
"app-media-gate.ts",
"app-native-host-gate.ts",