Files
cindy/scripts/file-peer-smoke.mjs
Dash da76c808aa fix(task-copy): 复制传输提速、取消立即生效、恢复进度不闪表单,进度改为“已传输” (#5381)
* perf(device-link): 直连附件上传多块并发、按二进制发送,任务复制进度改为“已传输”

接收端在 file-peer caps 中声明 streamAttachments 后,发送端最多保持 3 个 1 MiB
写入块在途,块内容作为 RPC 二进制正文发送,不再逐块等待确认、也不再经 base64
膨胀。接收端仍按顺序落盘并在 finish 校验大小与 SHA-256;未声明该能力的旧主机
继续走逐块 base64 路径。

任务复制进度文案从“上传进度…(尚未完成接收)”改为“已传输…”。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

* fix(task-copy): 取消复制立即中止正在发送的文件

此前取消只在文件之间的检查点生效,正在发送的文件(最大 2 GB 一段)要发完才停;
若这段走的是 OSS 中转,取消要等整段上传完,看起来像卡住、结束不了。

取消现在同时中止在途传输:直连上传在下一个 1 MiB 块前停止并通知接收端丢弃已收部分,
不计入直连失败冷却、也不改走 OSS;OSS 上传立即中止 PUT、不换传输栈重试并删除已签发
对象;大文件分段复制也一并停止。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

* fix(task-copy): 从任务顶部恢复复制进度时直接显示进度,不再先闪出发起复制的表单

顶部状态按钮把已知的复制状态交给弹窗作为初始状态;此前弹窗在第一次轮询返回前把状态当成未开始,先显示目标选择并开始统计文件。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

* fix(device-link): 慢链路上二进制正文按进度续期,排队中的上传也能立即取消

接收端在 RPC 正文头到达后,每收到一个二进制分片就重置 15 秒停滞计时器,
只有真正停住才断开连接;慢但仍在传的直连不再被固定 15 秒提前切断。

取消信号同时传入每台对端的传输队列:上传若仍排在其他预览或附件传输之后,
取消会让它立即退出队列,不再等无关传输完成。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

* fix(task-copy): 取消在建链与等待块确认时也立即生效,取消中提示改为“正在取消…”

直连上传的建链改为接收取消信号(中止建链、不计失败冷却);等待中的块请求在取消时
立即返回,迟到的回复忽略,连接保留以便把 cancel 送到目标端清理暂存。

取消中的五语提示去掉“当前文件发送完后停止”;产品规则同步取消语义与“已传输”文案。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

* fix(device-link): 直连上传在任意阶段取消都立即返回

取消信号覆盖整次上传调用(排队、能力探测、摘要、建链、块传输),调用方立即返回;被放弃的流程在下一个检查点退出,迟到结果被忽略,块阶段仍向目标端发出 cancel。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

* fix(task-copy): OSS 预签名可被取消,删除中转对象设期限,取消不再等无界网络请求

取消路径上最后两处无界等待:presign-put 改为随取消立即返回(预签名不创建对象,迟到结果无需清理);removeRemote 设 15 秒期限,上传被取消时不等它。复制取消后的清理因此也不会被无响应的 relay 卡住。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

* fix(task-copy): 取消后先释放源文件再返回,不再让调用方抢在清理前退出

撤回上一轮包住整次直连上传的外层竞速:它让调用方先返回、被放弃的上传仍在后台持有源文件,Windows 上随后删除暂存目录会失败。改为只给唯一缺少检查点的能力探测接入取消,其余等待本就响应取消;调用在 finally 关闭源文件之后才结束。OSS 流式上传被取消时同样等源文件流关闭后再返回。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

* fix(device-link): 取消后迟到的 begin 回复仍释放目标端 ticket

begin 已送达但回复晚于取消时,前台照常立即返回;迟到回复带回的 ticket 随即补发 cancel,目标端不再残留占用磁盘预算与条目上限的空暂存。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

* fix(device-link): OSS 换栈重试后取消,等所有源文件流关闭再返回

传输栈重试会为同一文件再开一个读流;取消时等待本次上传打开过的全部读流关闭,而不只是最后一个。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

* fix(device-link): 慢链路上排队块按进度续期,小文件预读可被取消

发送端:带正文的块请求在同一通道上有回复(即传输有进展)时重新计时,排在窗口
后面的块不再把前面块的传输时间算进自己的期限;慢但仍在传的直连不会被切断,
与接收端的停滞计时器对称。

OSS 小文件路径:整文件预读接入取消信号,取消时停止读取,并等读流关闭后再返回。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

* revert(device-link): 撤回发送端排队块按回复续期,极慢链路改为范围声明

上一轮在 runtime 内按回复重置块请求期限,但 Desktop main 的命令计时器仍是固定
45 秒、先于它触发,该机制在桌面端没有实际效果、只增加复杂度。撤回到固定期限;
新路径对慢链路的容忍度(约 70 KB/s)已优于原逐块路径(约 93 KB/s),更慢的链路
照旧回退 OSS,写入 PR 范围说明。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

* fix(device-link): RPC 二进制正文只接受发送端的 16 KiB 分帧

正文分片必须恰为 min(16384, 剩余字节),与 files-v2 接收路径一致;对端无法把 1 MiB 正文拆成大量极小帧耗尽 capture renderer 的 CPU 与内存。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

* fix(device-link): 建链信令请求不阻塞取消;补多 peer 故障半径用例

取消发生在直连建链的 offer 信令等待期间时,不再等该 RPC(最长约 30 秒)返回,迟到结果忽略;只中止本 peer 正在建立的连接。新增用例:取消对 peer A 的建链,peer B 已建连接上的在途传输照常完成且未被关闭。

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>

---------

Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>
2026-10-02 21:27:48 +08:00

234 lines
9.6 KiB
JavaScript

// Real browser checks against production transport code. No account or user files required.
import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const require = createRequire(
new URL("../apps/desktop/package.json", import.meta.url),
);
const { build } = require("esbuild");
const { chromium } = require("playwright-core");
const executablePath = process.argv[2];
if (!executablePath) throw new Error("Pass a Chrome executable");
// Acceptance runner supplies temporary loopback TURN credentials, never production secrets.
const iceServers = JSON.parse(process.env.CINDY_PEER_TEST_ICE ?? "[]");
const expectedPath = iceServers.length ? "relay" : "direct";
const output = await build({
entryPoints: [
path.join(root, "packages/device-link/src/filePeerRuntimeSource.ts"),
],
bundle: true,
write: false,
format: "iife",
globalName: "PeerRuntimeSource",
});
const browser = await chromium.launch({
executablePath,
headless: true,
chromiumSandbox: true,
});
try {
const page = await browser.newPage();
if (iceServers.length) await page.evaluate(() => {
const Native = window.RTCPeerConnection;
window.RTCPeerConnection = class extends Native {
constructor(config) { super({ ...config, iceTransportPolicy: "relay" }); }
};
});
await page.addScriptTag({ content: output.outputFiles[0].text });
await page.addScriptTag({
content: await page.evaluate(
() => PeerRuntimeSource.FILE_PEER_RUNTIME_SOURCE,
),
});
for (const streaming of [false, true]) {
const result = await page.evaluate(
async ({ large, streaming, benchmark, iceServers, expectedPath }) => {
const { createFilePeerRuntime } = CindyFilePeerRuntime;
let sourceSize = 0,
outputSize = 0,
sourceOffset = 0,
failWrite = false;
const ticket = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
const host = createFilePeerRuntime({
// Body requests echo a digest of the raw bytes so the client can verify them.
invoke: async (_id, value, body) =>
body
? JSON.stringify({
value,
length: body.length,
digest: body.reduce((sum, byte) => (sum * 31 + byte) >>> 0, 0),
})
: value,
read: async (_id, t, offset) => {
if (benchmark) await new Promise(resolve => setTimeout(resolve, 1));
if (t !== ticket || offset !== sourceOffset)
throw new Error("source offset");
const chunk = Uint8Array.from(
{ length: Math.min(16384, sourceSize - offset) },
(_, i) => ((offset + i) * 31) % 251,
);
sourceOffset += chunk.length;
return btoa(String.fromCharCode(...chunk));
},
write: async () => {
throw new Error("host write");
},
});
const client = createFilePeerRuntime({
read: async () => {
throw new Error("client read");
},
write: async (_sink, offset, data) => {
if (benchmark) await new Promise(resolve => setTimeout(resolve, 1));
if (failWrite) throw new Error("disk full");
if (offset !== outputSize) throw new Error("sink offset");
for (const c of atob(data)) {
if (c.charCodeAt(0) !== (outputSize * 31) % 251)
throw new Error("bytes differ");
outputSize++;
}
},
});
const setupStart = performance.now();
const offer = await client.offer("client", iceServers, streaming);
await client.answer("client", await host.accept("host", iceServers, offer));
const setupMs = Math.round(performance.now() - setupStart);
const stats = JSON.parse(await client.stats("client"));
if (stats.path !== expectedPath) throw new Error("unexpected selected ICE path");
if (streaming) {
const value = JSON.stringify({ text: "中文🙂".repeat(128 * 1024) });
if ((await client.invoke("client", value)) !== value)
throw new Error("fragmented RPC differs");
const replies = await Promise.all(
["a", "b", "c", "d"].map((value) => client.invoke("client", value)),
);
if (replies.join("") !== "abcd")
throw new Error("RPC correlation failed");
// Binary request bodies around the 16 KiB frame boundary, up to the 1 MiB block.
const withBody = (value, length) => {
const bytes = Uint8Array.from({ length }, (_, i) => (i * 7 + length) % 256);
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
const digest = bytes.reduce((sum, byte) => (sum * 31 + byte) >>> 0, 0);
return client
.invoke("client", value, undefined, btoa(binary))
.then((reply) => {
const r = JSON.parse(reply);
if (r.value !== value || r.length !== length || r.digest !== digest)
throw new Error("RPC body differs");
});
};
for (const length of [1, 16384, 16385, 1048576]) await withBody("body", length);
// Three bodies in flight beside a plain request stay correlated.
const [, plain] = await Promise.all([
withBody("first", 1048576),
client.invoke("client", "plain"),
withBody("second", 300000),
withBody("third", 1048576),
]);
if (plain !== "plain") throw new Error("RPC correlation with bodies failed");
const stats = JSON.parse(await client.stats("client"));
if (stats.path !== expectedPath || !stats.streaming)
throw new Error("selected path missing");
}
const sizes = [
0,
1,
16384,
16385,
262144,
262145,
1048576,
...(benchmark ? [8 * 1024 * 1024] : []),
...(large
? [large === "2g" ? 2 * 1024 * 1024 * 1024 : 101 * 1024 * 1024]
: []),
];
try {
const transfers = [];
for (const size of sizes) {
sourceSize = size;
sourceOffset = 0;
outputSize = 0;
const start = performance.now();
await Promise.all([
client.receive("client", ticket, size, "sink"),
...(streaming
? [client.invoke("client", "concurrent-read")]
: []),
]);
if (outputSize !== size) throw new Error("bytes differ");
const ms = Math.max(1, Math.round(performance.now() - start));
transfers.push({ size, ms, bytesPerSecond: Math.round(size * 1000 / ms) });
}
let diagnostics = null;
if (streaming) {
// Progress diagnostics describe the last transfer and carry no addresses or URLs.
const last = sizes[sizes.length - 1];
const rawReceiver = await client.stats("client");
const rawSender = await host.stats("host");
if (/"(?:address|ip|port|url|relatedAddress|relatedPort|foundation|usernameFragment)"/.test(rawReceiver + rawSender))
throw new Error("stats expose candidate addresses");
const receiver = JSON.parse(rawReceiver);
const sender = JSON.parse(rawSender);
const r = receiver.receive, s = sender.send;
if (!r || r.size !== last || r.received !== last || r.written !== last ||
r.writes !== Math.ceil(last / 16384) || r.queued !== 0 || !(r.queuedMax >= 1))
throw new Error("receive progress differs");
if (!s || s.sent !== last || s.reads !== Math.ceil(last / 16384) + 1 || !(s.creditWaitMs >= 0))
throw new Error("send progress differs");
if (!(receiver.pair?.bytesReceived >= last) || typeof receiver.channel?.bufferedAmount !== "number")
throw new Error("transport counters missing");
if (receiver.local?.candidateType === undefined || receiver.path !== expectedPath ||
!(receiver.candidates?.local?.[receiver.local.candidateType] >= 1) ||
!(receiver.candidates?.pairs?.succeeded >= 1) ||
typeof receiver.candidates?.localRelay !== "object")
throw new Error("candidate kind missing");
diagnostics = {
receive: r, send: s, pair: receiver.pair, local: receiver.local,
candidates: receiver.candidates,
};
}
sourceSize = 10;
sourceOffset = 0;
outputSize = 0;
failWrite = true;
let rejected = false;
try {
await client.receive("client", ticket, 10, "sink");
} catch {
rejected = true;
}
if (!rejected) throw new Error("incomplete sink accepted");
return {
streaming,
passedSizes: sizes,
diskFailureRejected: rejected,
rpc: streaming,
setupMs,
stats,
transfers,
diagnostics,
};
} finally {
host.dispose();
client.dispose();
}
},
{
large: process.argv.includes("--2g")
? "2g"
: process.argv.includes("--large"),
streaming,
benchmark: process.argv.includes('--benchmark'),
iceServers,
expectedPath,
},
);
console.log(JSON.stringify(result));
}
} finally {
await browser.close();
}