fix(sftp): cancel stalled transfer preflights

This commit is contained in:
bincxz committed 2026-07-25 12:09:24 +08:00
1 parent a07f928ec4
commit 35ee1d4fdf
4 files changed
+220 -54

No files matched your search

+25 -13
View File
@@ -856,13 +856,16 @@ async function promoteScpStagedUpload(
existingMode,
assertCanPromote,
commitPromotion,
runCancelablePreflight,
signal,
) {
const { getScpBackendForClient } = require("./sftpBridge/scpBackend.cjs");
const backend = getScpBackendForClient(client);
let latest = null;
try {
latest = await backend.stat(targetPath, { encoding, signal });
latest = await runCancelablePreflight(
() => backend.stat(targetPath, { encoding, signal }),
);
} catch (error) {
if (!isRemoteMissingError(error)) throw error;
}
@@ -932,20 +935,26 @@ async function runRemoteUploadTransaction(client, localPath, remotePath, options
const commitPromotion = typeof options?.commitPromotion === "function"
? options.commitPromotion
: () => {};
const runCancelablePreflight = typeof options?.runCancelablePreflight === "function"
? options.runCancelablePreflight
: (operation) => operation();
const allowInPlaceFallback = options?.allowInPlaceFallback !== false;
const preserveStageOnUploadError = options?.preserveStageOnUploadError === true;
const { isScpModeClient, getScpBackendForClient } = require("./sftpBridge/scpBackend.cjs");
const scpMode = isScpModeClient(client);
const encodedPath = encodePath(remotePath, encoding);
const plan = scpMode
? await planScpRemoteUploadReplace(client, remotePath, encoding, signal)
: await planRemoteUploadReplace(client, encodedPath);
const plan = await runCancelablePreflight(() => (
scpMode
? planScpRemoteUploadReplace(client, remotePath, encoding, signal)
: planRemoteUploadReplace(client, encodedPath)
));
const fastPutOptions = { ...options };
delete fastPutOptions.expectedSize;
delete fastPutOptions.encoding;
delete fastPutOptions.uploadFile;
delete fastPutOptions.assertCanPromote;
delete fastPutOptions.commitPromotion;
delete fastPutOptions.runCancelablePreflight;
delete fastPutOptions.allowInPlaceFallback;
delete fastPutOptions.stagedPath;
delete fastPutOptions.backupPath;
@@ -1036,9 +1045,11 @@ async function runRemoteUploadTransaction(client, localPath, remotePath, options
try {
assertCanPromote();
if (Number.isFinite(expectedSize) && expectedSize >= 0) {
const stagedStat = scpMode
? await getScpBackendForClient(client).stat(stagedLogical, { encoding, signal })
: typeof client.stat === "function" ? await client.stat(encodedStagedPath) : null;
const stagedStat = await runCancelablePreflight(() => (
scpMode
? getScpBackendForClient(client).stat(stagedLogical, { encoding, signal })
: typeof client.stat === "function" ? client.stat(encodedStagedPath) : null
));
const stagedSize = Number(stagedStat?.size);
if (Number.isFinite(stagedSize) && stagedSize !== expectedSize) {
throw new Error(
@@ -1059,15 +1070,16 @@ async function runRemoteUploadTransaction(client, localPath, remotePath, options
plan.existingMode,
assertCanPromote,
commitPromotion,
runCancelablePreflight,
signal,
);
} else {
await assertStagedPromotionTargetSafe(
client,
encodedPath,
remotePath,
plan.destinationExisted,
);
await runCancelablePreflight(() => assertStagedPromotionTargetSafe(
client,
encodedPath,
remotePath,
plan.destinationExisted,
));
assertCanPromote();
// Apply the old mode to the stage before promotion. A failed chmod must not
// replace an executable final with a non-executable file and report success.
@@ -136,6 +136,42 @@ function createSessionChannel(options = {}) {
return { channel, fastPutCalls, remoteFiles, remoteMeta, chmodCalls };
}
test("downloadSftpToLocal aborts while initial SFTP metadata is stalled", async (t) => {
const tempRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), "netcatty-sftp-stat-abort-"));
t.after(async () => fs.promises.rm(tempRoot, { recursive: true, force: true }));
let markStatStarted;
const statStarted = new Promise((resolve) => { markStatStarted = resolve; });
const client = {
sftp: createSessionChannel().channel,
stat() {
markStatStarted();
return new Promise(() => {});
},
};
sftpBridge.init({
electronModule: {},
sessions: new Map(),
sftpClients: new Map([["stalled-stat", client]]),
});
const controller = new AbortController();
const download = sftpBridge.downloadSftpToLocal(null, {
sftpId: "stalled-stat",
remotePath: "/tmp/source.bin",
localPath: path.join(tempRoot, "target.bin"),
abortSignal: controller.signal,
});
await statStarted;
controller.abort();
await assert.rejects(
() => Promise.race([
download,
new Promise((_, reject) => setTimeout(() => reject(new Error("cancel timed out")), 500)),
]),
/cancel|abort/i,
);
});
test("session-backed uploadLocalToSftp uses pipelined fastPut on the raw SFTP channel", async (t) => {
const tempRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), "netcatty-session-upload-"));
t.after(async () => {
+73 -41
View File
@@ -2002,6 +2002,34 @@ async function startTransferNow(event, payload, onProgress) {
transfer.leasedSftpIds = leasedSftpIds;
const transferCreatedAt = Date.now();
const runCancelablePreflight = async (operation) => {
if (transfer.cancelled || transfer.signal?.aborted) {
throw new Error("Transfer cancelled");
}
let rejectCancellation;
const cancelled = new Promise((_, reject) => {
rejectCancellation = reject;
});
const previousAbort = transfer.abort;
const abortPreflight = () => {
try { previousAbort?.(); } finally {
rejectCancellation(new Error("Transfer cancelled"));
}
};
const signal = transfer.signal;
transfer.abort = abortPreflight;
signal?.addEventListener?.("abort", abortPreflight, { once: true });
try {
return await Promise.race([
Promise.resolve().then(operation),
cancelled,
]);
} finally {
signal?.removeEventListener?.("abort", abortPreflight);
if (transfer.abort === abortPreflight) transfer.abort = previousAbort;
}
};
// ── Progress/speed tracking ──────────────────────────────────────────────
// Keep progress monotonic and compute speed from a strict sliding window.
const speedSamples = [{ time: transferCreatedAt, bytes: transfer.checkpointBytes }]; // [{ time, bytes }]
@@ -2159,9 +2187,11 @@ async function startTransferNow(event, payload, onProgress) {
});
fileSize = st.size;
} else {
await requireSftpChannel(client);
const encodedSourcePath = encodePathForSession(sourceSftpId, sourcePath, sourceEncoding);
const stat = await client.stat(encodedSourcePath);
const stat = await runCancelablePreflight(async () => {
await requireSftpChannel(client);
const encodedSourcePath = encodePathForSession(sourceSftpId, sourcePath, sourceEncoding);
return client.stat(encodedSourcePath);
});
fileSize = stat.size;
}
}
@@ -2182,12 +2212,12 @@ async function startTransferNow(event, payload, onProgress) {
}
if (transfer.resumable && transfer.sourceFingerprint) {
const currentSourceFingerprint = await computeSourceFingerprint({
sourceType,
sourcePath,
sourceSftpId,
sourceEncoding,
});
const currentSourceFingerprint = await runCancelablePreflight(() => computeSourceFingerprint({
sourceType,
sourcePath,
sourceSftpId,
sourceEncoding,
}));
if (
transfer.sourceFingerprint
&& currentSourceFingerprint
@@ -2225,6 +2255,7 @@ async function startTransferNow(event, payload, onProgress) {
commitPromotion() {
transfer.completionCommitted = true;
},
runCancelablePreflight,
async uploadFile(encodedUploadPath, uploadTarget) {
const uploadTargetPath = uploadTarget.logicalPath;
const usesStage = uploadTarget.generatedStagePath === true;
@@ -2232,21 +2263,21 @@ async function startTransferNow(event, payload, onProgress) {
? { client, sftpId: targetSftpId, path: uploadTargetPath, encoding: targetEncoding }
: null;
transfer.checkpointBytes = usesStage && transfer.resumable
? await resolveRemoteResumeCheckpoint(
client,
targetSftpId,
uploadTargetPath,
targetEncoding,
transfer.checkpointBytes,
)
? await runCancelablePreflight(() => resolveRemoteResumeCheckpoint(
client,
targetSftpId,
uploadTargetPath,
targetEncoding,
transfer.checkpointBytes,
))
: 0;
sendProgress(transfer.checkpointBytes, fileSize, { force: true });
if (usesStage && transfer.checkpointBytes > 0) {
const verifyBytes = resumeContentVerifyBytes(transfer.checkpointBytes);
await assertMatchingResumeContent(
hashLocalPrefix(sourcePath, verifyBytes),
hashRemotePrefix(client, targetSftpId, uploadTargetPath, targetEncoding, verifyBytes),
);
await runCancelablePreflight(() => assertMatchingResumeContent(
hashLocalPrefix(sourcePath, verifyBytes),
hashRemotePrefix(client, targetSftpId, uploadTargetPath, targetEncoding, verifyBytes),
));
}
await uploadFile(
sourcePath,
@@ -2283,13 +2314,13 @@ async function startTransferNow(event, payload, onProgress) {
downloadTargetPath, transfer.checkpointBytes,
);
sendProgress(transfer.checkpointBytes, fileSize, { force: true });
{
await runCancelablePreflight(async () => {
const verifyBytes = resumeContentVerifyBytes(transfer.checkpointBytes);
await assertMatchingResumeContent(
hashRemotePrefix(client, sourceSftpId, sourcePath, sourceEncoding, verifyBytes),
hashLocalPrefix(downloadTargetPath, verifyBytes),
);
}
});
const downloadResult = await downloadFile(
encodedSourcePath,
downloadTargetPath,
@@ -2488,13 +2519,13 @@ async function startTransferNow(event, payload, onProgress) {
const encodedSourcePath = isScpModeClient(sourceClient)
? sourcePath
: encodePathForSession(sourceSftpId, sourcePath, sourceEncoding);
{
await runCancelablePreflight(async () => {
const verifyBytes = resumeContentVerifyBytes(transfer.downloadCheckpointBytes);
await assertMatchingResumeContent(
hashRemotePrefix(sourceClient, sourceSftpId, sourcePath, sourceEncoding, verifyBytes),
hashLocalPrefix(tempPath, verifyBytes),
);
}
});
const downloadProgress = (transferred, reportedTotal, options = {}) => {
if (
isScpModeClient(sourceClient)
@@ -2585,6 +2616,7 @@ async function startTransferNow(event, payload, onProgress) {
commitPromotion() {
transfer.completionCommitted = true;
},
runCancelablePreflight,
async uploadFile(encodedUploadPath, uploadTarget) {
const uploadTargetPath = uploadTarget.logicalPath;
const usesStage = uploadTarget.generatedStagePath === true;
@@ -2592,13 +2624,13 @@ async function startTransferNow(event, payload, onProgress) {
? { client: targetClient, sftpId: targetSftpId, path: uploadTargetPath, encoding: targetEncoding }
: null;
transfer.uploadCheckpointBytes = usesStage && transfer.resumable
? await resolveRemoteResumeCheckpoint(
targetClient,
targetSftpId,
uploadTargetPath,
targetEncoding,
transfer.uploadCheckpointBytes,
)
? await runCancelablePreflight(() => resolveRemoteResumeCheckpoint(
targetClient,
targetSftpId,
uploadTargetPath,
targetEncoding,
transfer.uploadCheckpointBytes,
))
: 0;
transfer.checkpointBytes = transfer.uploadCheckpointBytes;
// Overall progress for R2R upload stage is ~50% + upload/2.
@@ -2608,16 +2640,16 @@ async function startTransferNow(event, payload, onProgress) {
transfer.checkpointBytes = transfer.uploadCheckpointBytes;
if (usesStage && transfer.uploadCheckpointBytes > 0) {
const verifyBytes = resumeContentVerifyBytes(transfer.uploadCheckpointBytes);
await assertMatchingResumeContent(
hashLocalPrefix(tempPath, verifyBytes),
hashRemotePrefix(
targetClient,
targetSftpId,
uploadTargetPath,
targetEncoding,
verifyBytes,
),
);
await runCancelablePreflight(() => assertMatchingResumeContent(
hashLocalPrefix(tempPath, verifyBytes),
hashRemotePrefix(
targetClient,
targetSftpId,
uploadTargetPath,
targetEncoding,
verifyBytes,
),
));
}
await uploadFile(
tempPath,
+86
View File
@@ -343,6 +343,92 @@ test("in-place concurrent upload ignores cancellation while the remote handle cl
assert.equal(sender.sent.some((entry) => entry.channel === "netcatty:transfer:complete"), true);
});
test("SFTP download cancellation settles while initial metadata is stalled", async (t) => {
const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "netcatty-download-stat-cancel-"));
t.after(async () => fs.promises.rm(tempDir, { recursive: true, force: true }));
let markStatStarted;
const statStarted = new Promise((resolve) => { markStatStarted = resolve; });
const client = {
sftp: createFastSftp({}),
stat() {
markStatStarted();
return new Promise(() => {});
},
};
transferBridge.init({ sftpClients: new Map([["source", client]]) });
const sender = createSender();
const transferId = "download-stat-cancel";
const running = transferBridge.startTransfer({ sender }, {
transferId,
sourcePath: "/tmp/source.bin",
targetPath: path.join(tempDir, "target.bin"),
sourceType: "sftp",
targetType: "local",
sourceSftpId: "source",
resumable: true,
});
await statStarted;
await transferBridge.cancelTransfer(null, { transferId });
const result = await Promise.race([
running,
new Promise((_, reject) => setTimeout(() => reject(new Error("cancel timed out")), 500)),
]);
assert.match(result.error || "", /cancel/i);
assert.equal(sender.sent.some((entry) => entry.channel === "netcatty:transfer:cancelled"), true);
assert.equal(sender.sent.some((entry) => entry.channel === "netcatty:transfer:complete"), false);
});
test("server-to-server resume cancellation settles while source prefix verification is stalled", async (t) => {
const transferId = `server-prefix-cancel-${crypto.randomUUID()}`;
const sourcePath = "/source/payload.bin";
const tempPath = tempDirBridge.getTransferTempFilePath(transferId, path.basename(sourcePath));
await fs.promises.writeFile(tempPath, Buffer.from("abcd"));
t.after(async () => fs.promises.rm(tempPath, { force: true }));
let markPrefixStarted;
const prefixStarted = new Promise((resolve) => { markPrefixStarted = resolve; });
const sourceClient = {
sftp: createFastSftp({
createReadStream() {
markPrefixStarted();
return new PassThrough();
},
}),
};
const targetClient = { sftp: createFastSftp({}) };
transferBridge.init({
sftpClients: new Map([["source", sourceClient], ["target", targetClient]]),
});
const sender = createSender();
const running = transferBridge.startTransfer({ sender }, {
transferId,
sourcePath,
targetPath: "/target/payload.bin",
sourceType: "sftp",
targetType: "sftp",
sourceSftpId: "source",
targetSftpId: "target",
totalBytes: 8,
resumable: true,
sameHost: false,
resumeStage: "download",
checkpointBytes: 4,
downloadCheckpointBytes: 4,
});
await prefixStarted;
await transferBridge.cancelTransfer(null, { transferId });
const result = await Promise.race([
running,
new Promise((_, reject) => setTimeout(() => reject(new Error("cancel timed out")), 500)),
]);
assert.match(result.error || "", /cancel/i);
assert.equal(sender.sent.some((entry) => entry.channel === "netcatty:transfer:cancelled"), true);
assert.equal(sender.sent.some((entry) => entry.channel === "netcatty:transfer:complete"), false);
});
test("resumable SFTP uploads use the configured per-file request concurrency", async (t) => {
const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "netcatty-transfer-test-"));
t.after(async () => {