mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-23 00:20:45 +00:00
fix(sftp): recover from abandoned SFTP channel-open poison on lossy links (#3865)
A timed-out SFTP OPEN used to pin the connection forever when its callback never arrived. Wait up to 2s, then force-clear the gate and admit a new open. Late channels are still closed. After TIMEOUT or PENDING, skip the fastPut reopen and upload on the shared channel. Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
This commit is contained in:
4 files changed
+555
-18
No files matched your search
@@ -1,17 +1,30 @@
|
||||
"use strict";
|
||||
|
||||
// An abandoned OPEN cannot be cancelled in SSH, but its physical connection
|
||||
// may own unrelated terminals. Block only additional opens until its callback
|
||||
// or transport closure settles; retain no unbounded retry queue.
|
||||
// may own unrelated terminals. Hold further opens until the late callback,
|
||||
// transport closure, or a short abandon wait. If the callback never arrives,
|
||||
// force-clear the gate and admit a new open; the late channel is still closed
|
||||
// when its callback finally fires. Do not queue unbounded SSH channel requests
|
||||
// during the wait.
|
||||
const abandonedOpens = new WeakMap();
|
||||
|
||||
function wakeAbandonedWaiters(state) {
|
||||
const waiters = state?.waiters;
|
||||
if (!waiters || waiters.size === 0) return;
|
||||
state.waiters = new Set();
|
||||
for (const wake of waiters) {
|
||||
try { wake(); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
function abandonOpen(client, token) {
|
||||
let state = abandonedOpens.get(client);
|
||||
if (!state) {
|
||||
state = { tokens: new Set(), onClose: null };
|
||||
state = { tokens: new Set(), onClose: null, waiters: new Set() };
|
||||
state.onClose = () => {
|
||||
if (abandonedOpens.get(client) === state) abandonedOpens.delete(client);
|
||||
state.tokens.clear();
|
||||
wakeAbandonedWaiters(state);
|
||||
};
|
||||
abandonedOpens.set(client, state);
|
||||
client.once?.("close", state.onClose);
|
||||
@@ -24,9 +37,29 @@ function settleAbandonedOpen(client, token) {
|
||||
if (!state || !state.tokens.delete(token) || state.tokens.size > 0) return;
|
||||
abandonedOpens.delete(client);
|
||||
client.removeListener?.("close", state.onClose);
|
||||
wakeAbandonedWaiters(state);
|
||||
}
|
||||
|
||||
function forceClearAbandonedOpens(client) {
|
||||
const state = abandonedOpens.get(client);
|
||||
if (!state) return;
|
||||
abandonedOpens.delete(client);
|
||||
state.tokens.clear();
|
||||
try { client.removeListener?.("close", state.onClose); } catch { /* ignore */ }
|
||||
wakeAbandonedWaiters(state);
|
||||
}
|
||||
|
||||
const DEFAULT_SFTP_CHANNEL_OPEN_TIMEOUT_MS = 10_000;
|
||||
const DEFAULT_SFTP_CHANNEL_ABANDON_WAIT_MS = 2_000;
|
||||
|
||||
function resolveAbandonWaitMs(value) {
|
||||
if (value === undefined || value === null || value === "") {
|
||||
return DEFAULT_SFTP_CHANNEL_ABANDON_WAIT_MS;
|
||||
}
|
||||
const parsed = Number(value);
|
||||
if (!Number.isFinite(parsed)) return DEFAULT_SFTP_CHANNEL_ABANDON_WAIT_MS;
|
||||
return Math.max(0, parsed);
|
||||
}
|
||||
|
||||
function closeSftpChannel(channel) {
|
||||
if (!channel) return;
|
||||
@@ -43,17 +76,66 @@ function createSftpOpenAbortError(signal) {
|
||||
return error;
|
||||
}
|
||||
|
||||
function openBoundedSftpChannel(sshClient, options = {}) {
|
||||
if (!sshClient || typeof sshClient.sftp !== "function") {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
function createPendingOpenError() {
|
||||
const error = new Error("A previous SFTP channel open is still pending on this connection");
|
||||
error.code = "SFTP_CHANNEL_OPEN_PENDING";
|
||||
return error;
|
||||
}
|
||||
|
||||
function waitForAbandonedOpenAdmission(sshClient, options) {
|
||||
const state = abandonedOpens.get(sshClient);
|
||||
if (!state) return Promise.resolve();
|
||||
const abandonWaitMs = resolveAbandonWaitMs(options.abandonWaitMs);
|
||||
// A zero wait keeps the historical immediate rejection for callers that must
|
||||
// not block, and still lets upload fallback treat PENDING as a poisoned open.
|
||||
if (abandonWaitMs === 0) return Promise.reject(createPendingOpenError());
|
||||
|
||||
const signal = options.signal || null;
|
||||
if (signal?.aborted) return Promise.reject(createSftpOpenAbortError(signal));
|
||||
if (abandonedOpens.has(sshClient)) {
|
||||
const error = new Error("A previous SFTP channel open is still pending on this connection");
|
||||
error.code = "SFTP_CHANNEL_OPEN_PENDING";
|
||||
return Promise.reject(error);
|
||||
}
|
||||
const setTimeoutFn = options.setTimeoutFn || setTimeout;
|
||||
const clearTimeoutFn = options.clearTimeoutFn || clearTimeout;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
let timer = null;
|
||||
const cleanup = () => {
|
||||
state.waiters?.delete(onGateCleared);
|
||||
if (timer) clearTimeoutFn(timer);
|
||||
timer = null;
|
||||
signal?.removeEventListener?.("abort", onAbort);
|
||||
};
|
||||
const finish = (error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
cleanup();
|
||||
if (error) reject(error);
|
||||
else resolve();
|
||||
};
|
||||
const onGateCleared = () => finish();
|
||||
const onAbort = () => finish(createSftpOpenAbortError(signal));
|
||||
|
||||
if (!state.waiters) state.waiters = new Set();
|
||||
state.waiters.add(onGateCleared);
|
||||
if (abandonedOpens.get(sshClient) !== state) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
signal?.addEventListener?.("abort", onAbort, { once: true });
|
||||
if (signal?.aborted) {
|
||||
finish(createSftpOpenAbortError(signal));
|
||||
return;
|
||||
}
|
||||
// Referenced on purpose: an unreferenced timer can let Node exit while
|
||||
// this admission promise is still pending.
|
||||
timer = setTimeoutFn(() => {
|
||||
if (abandonedOpens.get(sshClient) === state) forceClearAbandonedOpens(sshClient);
|
||||
finish();
|
||||
}, abandonWaitMs);
|
||||
});
|
||||
}
|
||||
|
||||
function startBoundedSftpOpen(sshClient, options) {
|
||||
const signal = options.signal || null;
|
||||
const setTimeoutFn = options.setTimeoutFn || setTimeout;
|
||||
const clearTimeoutFn = options.clearTimeoutFn || clearTimeout;
|
||||
const timeoutMs = Math.max(
|
||||
@@ -117,7 +199,22 @@ function openBoundedSftpChannel(sshClient, options = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
function openBoundedSftpChannel(sshClient, options = {}) {
|
||||
if (!sshClient || typeof sshClient.sftp !== "function") {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
const signal = options.signal || null;
|
||||
if (signal?.aborted) return Promise.reject(createSftpOpenAbortError(signal));
|
||||
if (!abandonedOpens.has(sshClient)) {
|
||||
return startBoundedSftpOpen(sshClient, options);
|
||||
}
|
||||
return waitForAbandonedOpenAdmission(sshClient, options).then(() => (
|
||||
openBoundedSftpChannel(sshClient, options)
|
||||
));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_SFTP_CHANNEL_ABANDON_WAIT_MS,
|
||||
DEFAULT_SFTP_CHANNEL_OPEN_TIMEOUT_MS,
|
||||
closeSftpChannel,
|
||||
openBoundedSftpChannel,
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { EventEmitter, getEventListeners } = require("node:events");
|
||||
const { openBoundedSftpChannel } = require("./boundedSftpOpen.cjs");
|
||||
const {
|
||||
DEFAULT_SFTP_CHANNEL_ABANDON_WAIT_MS,
|
||||
openBoundedSftpChannel,
|
||||
} = require("./boundedSftpOpen.cjs");
|
||||
|
||||
function trackedTimerApi() {
|
||||
const active = new Set();
|
||||
@@ -94,9 +97,12 @@ for (const reason of ["timeout", "cancel"]) {
|
||||
if (reason === "cancel") controller.abort(new Error("cancelled"));
|
||||
await assert.rejects(opening);
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
await assert.rejects(openBoundedSftpChannel(sshClient, { timeoutMs: 5 }));
|
||||
await assert.rejects(
|
||||
openBoundedSftpChannel(sshClient, { timeoutMs: 5, abandonWaitMs: 0 }),
|
||||
(error) => error.code === "SFTP_CHANNEL_OPEN_PENDING",
|
||||
);
|
||||
}
|
||||
assert.equal(callbacks.length, 1, "retries must not allocate more abandoned SSH channel requests");
|
||||
assert.equal(callbacks.length, 1, "a zero abandon wait must not allocate more SSH channel requests");
|
||||
assert.equal(physicalCloses, 0, "existing terminal and SFTP channels remain connected");
|
||||
|
||||
const late = createChannel();
|
||||
@@ -174,10 +180,170 @@ test("all abandoned parallel opens must settle before admitting a new one", asyn
|
||||
await Promise.all([assert.rejects(first), assert.rejects(second)]);
|
||||
assert.equal(sshClient.listenerCount("close"), 1);
|
||||
callbacks[0](new Error("first failed"));
|
||||
await assert.rejects(openBoundedSftpChannel(sshClient), error => error.code === "SFTP_CHANNEL_OPEN_PENDING");
|
||||
await assert.rejects(
|
||||
openBoundedSftpChannel(sshClient, { abandonWaitMs: 0 }),
|
||||
(error) => error.code === "SFTP_CHANNEL_OPEN_PENDING",
|
||||
);
|
||||
callbacks[1](new Error("second failed"));
|
||||
assert.equal(sshClient.listenerCount("close"), 0);
|
||||
const next = openBoundedSftpChannel(sshClient);
|
||||
callbacks[2](null, createChannel());
|
||||
await next;
|
||||
});
|
||||
|
||||
function delay(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
function settleOpen(promise) {
|
||||
return promise.then((channel) => ({ channel }), (error) => ({ error }));
|
||||
}
|
||||
|
||||
test("abandon wait defaults to 2s", () => {
|
||||
assert.equal(DEFAULT_SFTP_CHANNEL_ABANDON_WAIT_MS, 2_000);
|
||||
});
|
||||
|
||||
test("omitted abandon wait does not admit a new open immediately", async () => {
|
||||
const callbacks = [];
|
||||
const sshClient = new EventEmitter();
|
||||
sshClient.sftp = (callback) => { callbacks.push(callback); };
|
||||
await assert.rejects(
|
||||
openBoundedSftpChannel(sshClient, { timeoutMs: 5 }),
|
||||
(error) => error.code === "SFTP_CHANNEL_OPEN_TIMEOUT",
|
||||
);
|
||||
const outcome = settleOpen(openBoundedSftpChannel(sshClient, { timeoutMs: 50 }));
|
||||
await delay(40);
|
||||
assert.equal(callbacks.length, 1, "the default abandon wait must still be holding");
|
||||
const late = createChannel();
|
||||
callbacks[0](null, late);
|
||||
assert.ok(late.endCalls > 0 || late.closeCalls > 0);
|
||||
await delay(20);
|
||||
assert.equal(callbacks.length, 2, "a late callback must release the next open");
|
||||
const healthy = createChannel();
|
||||
callbacks[1](null, healthy);
|
||||
const settled = await outcome;
|
||||
assert.equal(settled.channel, healthy);
|
||||
assert.equal(settled.error, undefined);
|
||||
});
|
||||
|
||||
test("abandon wait admits a new open when the late callback never arrives", async () => {
|
||||
const callbacks = [];
|
||||
const sshClient = new EventEmitter();
|
||||
sshClient.sftp = (callback) => {
|
||||
callbacks.push(callback);
|
||||
if (callbacks.length > 1) callback(null, createChannel());
|
||||
};
|
||||
await assert.rejects(
|
||||
openBoundedSftpChannel(sshClient, { timeoutMs: 10, abandonWaitMs: 20 }),
|
||||
(error) => error.code === "SFTP_CHANNEL_OPEN_TIMEOUT",
|
||||
);
|
||||
assert.equal(sshClient.listenerCount("close"), 1);
|
||||
|
||||
let pending = 0;
|
||||
let ok = 0;
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||
try {
|
||||
const channel = await openBoundedSftpChannel(sshClient, {
|
||||
timeoutMs: 50,
|
||||
abandonWaitMs: 30,
|
||||
});
|
||||
assert.ok(channel);
|
||||
ok += 1;
|
||||
} catch (error) {
|
||||
if (error?.code === "SFTP_CHANNEL_OPEN_PENDING") pending += 1;
|
||||
else throw error;
|
||||
}
|
||||
}
|
||||
assert.equal(ok, 5);
|
||||
assert.equal(pending, 0);
|
||||
assert.equal(sshClient.listenerCount("close"), 0, "force-clear must drop the close listener");
|
||||
|
||||
const late = createChannel();
|
||||
callbacks[0](null, late);
|
||||
assert.ok(late.endCalls > 0 || late.closeCalls > 0, "a late channel is still closed");
|
||||
assert.equal(sshClient.listenerCount("close"), 0);
|
||||
});
|
||||
|
||||
test("partially settled abandoned opens keep the gate until the rest arrive or the wait expires", async () => {
|
||||
const callbacks = [];
|
||||
const sshClient = new EventEmitter();
|
||||
sshClient.sftp = (callback) => { callbacks.push(callback); };
|
||||
const first = openBoundedSftpChannel(sshClient, { timeoutMs: 5, abandonWaitMs: 20 });
|
||||
const second = openBoundedSftpChannel(sshClient, { timeoutMs: 5, abandonWaitMs: 20 });
|
||||
await Promise.all([assert.rejects(first), assert.rejects(second)]);
|
||||
|
||||
const outcome = settleOpen(openBoundedSftpChannel(sshClient, {
|
||||
timeoutMs: 50,
|
||||
abandonWaitMs: 250,
|
||||
}));
|
||||
await delay(30);
|
||||
callbacks[0](new Error("first failed"));
|
||||
await delay(30);
|
||||
assert.equal(callbacks.length, 2, "one remaining abandoned open must keep the gate");
|
||||
callbacks[1](new Error("second failed"));
|
||||
await delay(20);
|
||||
assert.equal(callbacks.length, 3);
|
||||
const healthy = createChannel();
|
||||
callbacks[2](null, healthy);
|
||||
const settled = await outcome;
|
||||
assert.equal(settled.channel, healthy);
|
||||
});
|
||||
|
||||
test("abandon wait force-clears every outstanding token", async () => {
|
||||
const callbacks = [];
|
||||
let admitted = null;
|
||||
const sshClient = new EventEmitter();
|
||||
sshClient.sftp = (callback) => {
|
||||
callbacks.push(callback);
|
||||
if (callbacks.length > 2) {
|
||||
admitted = createChannel();
|
||||
callback(null, admitted);
|
||||
}
|
||||
};
|
||||
await Promise.all([
|
||||
assert.rejects(openBoundedSftpChannel(sshClient, { timeoutMs: 5 })),
|
||||
assert.rejects(openBoundedSftpChannel(sshClient, { timeoutMs: 5 })),
|
||||
]);
|
||||
const outcome = settleOpen(openBoundedSftpChannel(sshClient, {
|
||||
timeoutMs: 50,
|
||||
abandonWaitMs: 40,
|
||||
}));
|
||||
await delay(15);
|
||||
assert.equal(callbacks.length, 2);
|
||||
const settled = await outcome;
|
||||
assert.equal(settled.error, undefined, settled.error?.message);
|
||||
assert.equal(settled.channel, admitted);
|
||||
assert.equal(admitted.endCalls, 0);
|
||||
assert.equal(admitted.closeCalls, 0);
|
||||
assert.equal(callbacks.length, 3);
|
||||
for (const callback of callbacks.slice(0, 2)) {
|
||||
const late = createChannel();
|
||||
callback(null, late);
|
||||
assert.ok(late.endCalls > 0 || late.closeCalls > 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("cancel during the abandon wait does not admit another open or clear the gate", async () => {
|
||||
const callbacks = [];
|
||||
const sshClient = new EventEmitter();
|
||||
sshClient.sftp = (callback) => { callbacks.push(callback); };
|
||||
const controller = new AbortController();
|
||||
await assert.rejects(openBoundedSftpChannel(sshClient, { timeoutMs: 5 }));
|
||||
const outcome = settleOpen(openBoundedSftpChannel(sshClient, {
|
||||
timeoutMs: 50,
|
||||
abandonWaitMs: 400,
|
||||
signal: controller.signal,
|
||||
}));
|
||||
await delay(20);
|
||||
assert.equal(callbacks.length, 1);
|
||||
controller.abort(new Error("cancelled"));
|
||||
const settled = await outcome;
|
||||
assert.match(settled.error?.message || "", /cancelled/);
|
||||
assert.equal(callbacks.length, 1);
|
||||
assert.equal(getEventListeners(controller.signal, "abort").length, 0);
|
||||
await assert.rejects(
|
||||
openBoundedSftpChannel(sshClient, { abandonWaitMs: 0 }),
|
||||
(error) => error.code === "SFTP_CHANNEL_OPEN_PENDING",
|
||||
);
|
||||
assert.equal(callbacks.length, 1);
|
||||
});
|
||||
@@ -2065,6 +2065,23 @@ function isStaleOrClosedSharedChannelError(error, sftp) {
|
||||
return /channel closed/i.test(String(error.message || ""));
|
||||
}
|
||||
|
||||
// Test seam: shorten channel-open timeout / abandon wait. Production leaves this null.
|
||||
let isolatedSftpChannelOpenOptionsForTests = null;
|
||||
|
||||
function isolatedChannelOpenOptions(signal) {
|
||||
const options = { signal };
|
||||
const overrides = isolatedSftpChannelOpenOptionsForTests;
|
||||
if (!overrides || typeof overrides !== "object") return options;
|
||||
if (overrides.timeoutMs !== undefined) options.timeoutMs = overrides.timeoutMs;
|
||||
if (overrides.abandonWaitMs !== undefined) options.abandonWaitMs = overrides.abandonWaitMs;
|
||||
return options;
|
||||
}
|
||||
|
||||
function isPoisonedSftpChannelOpenError(error) {
|
||||
const code = error?.code;
|
||||
return code === "SFTP_CHANNEL_OPEN_TIMEOUT" || code === "SFTP_CHANNEL_OPEN_PENDING";
|
||||
}
|
||||
|
||||
async function openIsolatedSftpChannel(client, signal = null) {
|
||||
// The dedicated one-channel login already holds its only session channel.
|
||||
// Opening another SFTP subsystem drops that login, so stay on the browse channel.
|
||||
@@ -2072,7 +2089,7 @@ async function openIsolatedSftpChannel(client, signal = null) {
|
||||
return null;
|
||||
}
|
||||
const sshClient = client?.client;
|
||||
return openBoundedSftpChannel(sshClient, { signal });
|
||||
return openBoundedSftpChannel(sshClient, isolatedChannelOpenOptions(signal));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2712,6 +2729,7 @@ async function uploadFile(
|
||||
|
||||
// Prefer an isolated SFTP channel so cancellation cannot kill the browse session.
|
||||
let isolated = null;
|
||||
let isolatedOpenError = null;
|
||||
const preferSharedChannel = Number(fileSize) > 0
|
||||
&& Number(fileSize) <= SMALL_UPLOAD_SHARED_MAX_BYTES
|
||||
&& typeof sftp?.open === "function"
|
||||
@@ -2723,6 +2741,7 @@ async function uploadFile(
|
||||
);
|
||||
} catch (err) {
|
||||
rememberPipelineError(err);
|
||||
isolatedOpenError = err;
|
||||
console.warn(
|
||||
"[transferBridge] Failed to open isolated SFTP channel for upload:",
|
||||
err.message || String(err),
|
||||
@@ -2788,7 +2807,12 @@ async function uploadFile(
|
||||
}
|
||||
}
|
||||
|
||||
if (!isolated && !client.__netcattySudoMode && !preferSharedChannel) {
|
||||
// A timed-out or still-pending isolated OPEN has already spent the channel
|
||||
// deadline (or is waiting on an abandoned one). Reopening for fastPut only
|
||||
// pays another timeout or an immediate PENDING on a lossy link. Fall through
|
||||
// to the shared browse channel instead (#3155).
|
||||
const skipIsolatedFastPutReopen = isPoisonedSftpChannelOpenError(isolatedOpenError);
|
||||
if (!isolated && !skipIsolatedFastPutReopen && !client.__netcattySudoMode && !preferSharedChannel) {
|
||||
try {
|
||||
isolated = markDisposableUploadChannel(
|
||||
await openIsolatedSftpChannel(client, transfer?.signal),
|
||||
@@ -8284,6 +8308,11 @@ module.exports = {
|
||||
_setLocalPrefixHashStreamOverrideForTests: (override) => {
|
||||
localPrefixHashStreamOverrideForTests = override;
|
||||
},
|
||||
_setIsolatedSftpChannelOpenOptionsForTests: (options) => {
|
||||
isolatedSftpChannelOpenOptionsForTests = options && typeof options === "object"
|
||||
? options
|
||||
: null;
|
||||
},
|
||||
_hasLocalUploadAcknowledgedPrefixForTests: (transferId) => (
|
||||
localUploadAcknowledgedPrefix.has(String(transferId))
|
||||
),
|
||||
|
||||
@@ -10,6 +10,7 @@ const { EventEmitter } = require("node:events");
|
||||
const { PassThrough, Readable, Writable } = require("node:stream");
|
||||
|
||||
const transferBridge = require("./transferBridge.cjs");
|
||||
const { openBoundedSftpChannel } = require("./boundedSftpOpen.cjs");
|
||||
// Most download tests here drive the session slot / isolated pool with tiny
|
||||
// fixture files. Keep them on that path; the small-file exemption has its own
|
||||
// test below that restores the production threshold.
|
||||
@@ -14754,3 +14755,247 @@ test("small download does not open a fresh channel for ENOENT or EACCES", async
|
||||
assert.match(denied.error || "", /Permission denied|EACCES/);
|
||||
assert.equal(isolatedOpens, 0);
|
||||
});
|
||||
|
||||
test("channel-open timeout skips the fastPut reopen and uses the shared channel", async (t) => {
|
||||
// Lossy links abandon an isolated OPEN. Reopening for fastPut only waits out
|
||||
// the abandon gate and pays another timeout (or PENDING). The body must move
|
||||
// to the shared browse channel after the first poisoned open.
|
||||
const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "netcatty-sftp-open-poison-upload-"));
|
||||
t.after(async () => {
|
||||
transferBridge._setIsolatedSftpChannelOpenOptionsForTests(null);
|
||||
await fs.promises.rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
transferBridge._setIsolatedSftpChannelOpenOptionsForTests({
|
||||
timeoutMs: 20,
|
||||
abandonWaitMs: 30,
|
||||
});
|
||||
|
||||
const localPath = path.join(tempDir, "fresh.bin");
|
||||
const payload = Buffer.concat([
|
||||
Buffer.from("open-poison"),
|
||||
Buffer.alloc(SMALL_UPLOAD_SHARED_MAX_BYTES),
|
||||
]);
|
||||
await fs.promises.writeFile(localPath, payload);
|
||||
const targetPath = "/tmp/open-poison.bin";
|
||||
const remoteFiles = new Map();
|
||||
const lateChannels = [];
|
||||
let isolatedOpens = 0;
|
||||
let fastPutCalls = 0;
|
||||
let sharedWrites = 0;
|
||||
|
||||
const rememberFile = (sftp) => {
|
||||
sftp.lstat = (remotePath, callback) => {
|
||||
const key = String(remotePath);
|
||||
if (!remoteFiles.has(key)) {
|
||||
const error = new Error("ENOENT");
|
||||
error.code = 2;
|
||||
callback(error);
|
||||
return;
|
||||
}
|
||||
callback(null, {
|
||||
size: remoteFiles.get(key).length,
|
||||
mode: 0o100644,
|
||||
isDirectory: () => false,
|
||||
isSymbolicLink: () => false,
|
||||
});
|
||||
};
|
||||
sftp.open = (remotePath, _flags, callback) => {
|
||||
const key = String(remotePath);
|
||||
if (!remoteFiles.has(key)) remoteFiles.set(key, Buffer.alloc(0));
|
||||
callback(null, Buffer.from(key));
|
||||
};
|
||||
sftp.close = (_handle, callback) => callback(null);
|
||||
};
|
||||
|
||||
const shared = createFastSftp({});
|
||||
rememberFile(shared);
|
||||
shared.write = (handle, buffer, offset, length, position, callback) => {
|
||||
sharedWrites += 1;
|
||||
const key = handle.toString();
|
||||
const next = Buffer.alloc(Math.max(remoteFiles.get(key)?.length || 0, position + length));
|
||||
if (remoteFiles.has(key)) remoteFiles.get(key).copy(next);
|
||||
buffer.copy(next, position, offset, offset + length);
|
||||
remoteFiles.set(key, next);
|
||||
setImmediate(() => callback(null));
|
||||
};
|
||||
shared.fastPut = () => {
|
||||
fastPutCalls += 1;
|
||||
throw new Error("shared fastPut must not run after a poisoned channel open");
|
||||
};
|
||||
|
||||
const client = {
|
||||
sftp: shared,
|
||||
stat: async (remotePath) => {
|
||||
const key = String(remotePath);
|
||||
if (!remoteFiles.has(key)) {
|
||||
const error = new Error("ENOENT");
|
||||
error.code = 2;
|
||||
throw error;
|
||||
}
|
||||
return { size: remoteFiles.get(key).length, isDirectory: false };
|
||||
},
|
||||
delete: async (remotePath) => { remoteFiles.delete(String(remotePath)); },
|
||||
async rename(fromPath, toPath) {
|
||||
remoteFiles.set(String(toPath), remoteFiles.get(String(fromPath)));
|
||||
remoteFiles.delete(String(fromPath));
|
||||
},
|
||||
client: {
|
||||
sftp(callback) {
|
||||
isolatedOpens += 1;
|
||||
const late = createFastSftp({
|
||||
fastPut() {
|
||||
fastPutCalls += 1;
|
||||
throw new Error("fastPut reopen must not run after channel-open timeout");
|
||||
},
|
||||
end() { late.endCalls += 1; },
|
||||
close() { late.closeCalls += 1; },
|
||||
destroy() { late.destroyCalls += 1; },
|
||||
});
|
||||
late.endCalls = 0;
|
||||
late.closeCalls = 0;
|
||||
late.destroyCalls = 0;
|
||||
lateChannels.push({ callback, late });
|
||||
},
|
||||
},
|
||||
};
|
||||
transferBridge.init({ sftpClients: new Map([["target", client]]) });
|
||||
|
||||
const result = await transferBridge.startTransfer({ sender: createSender() }, {
|
||||
transferId: "upload-channel-open-timeout-shared",
|
||||
sourcePath: localPath,
|
||||
targetPath,
|
||||
sourceType: "local",
|
||||
targetType: "sftp",
|
||||
targetSftpId: "target",
|
||||
totalBytes: payload.length,
|
||||
resumable: false,
|
||||
skipAdmission: true,
|
||||
});
|
||||
|
||||
assert.equal(result.error, undefined, result.error);
|
||||
assert.equal(isolatedOpens, 1, "fastPut must not reopen an isolated channel after open timeout");
|
||||
assert.equal(fastPutCalls, 0);
|
||||
assert.ok(sharedWrites >= 1);
|
||||
assert.deepEqual(remoteFiles.get(targetPath), payload);
|
||||
|
||||
const abandoned = lateChannels[0];
|
||||
abandoned.callback(null, abandoned.late);
|
||||
assert.ok(
|
||||
abandoned.late.endCalls > 0 || abandoned.late.closeCalls > 0 || abandoned.late.destroyCalls > 0,
|
||||
"the abandoned channel is closed when its callback finally arrives",
|
||||
);
|
||||
});
|
||||
|
||||
test("pending channel-open skips the fastPut reopen and uses the shared channel", async (t) => {
|
||||
const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "netcatty-sftp-open-pending-upload-"));
|
||||
t.after(async () => {
|
||||
transferBridge._setIsolatedSftpChannelOpenOptionsForTests(null);
|
||||
await fs.promises.rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const localPath = path.join(tempDir, "fresh.bin");
|
||||
const payload = Buffer.concat([
|
||||
Buffer.from("open-pending"),
|
||||
Buffer.alloc(SMALL_UPLOAD_SHARED_MAX_BYTES),
|
||||
]);
|
||||
await fs.promises.writeFile(localPath, payload);
|
||||
const targetPath = "/tmp/open-pending.bin";
|
||||
const remoteFiles = new Map();
|
||||
let isolatedOpens = 0;
|
||||
let sharedWrites = 0;
|
||||
const warnings = [];
|
||||
const originalWarn = console.warn;
|
||||
console.warn = (...args) => {
|
||||
warnings.push(args.map((part) => String(part)).join(" "));
|
||||
originalWarn.apply(console, args);
|
||||
};
|
||||
t.after(() => { console.warn = originalWarn; });
|
||||
|
||||
const rememberFile = (sftp) => {
|
||||
sftp.lstat = (remotePath, callback) => {
|
||||
const key = String(remotePath);
|
||||
if (!remoteFiles.has(key)) {
|
||||
const error = new Error("ENOENT");
|
||||
error.code = 2;
|
||||
callback(error);
|
||||
return;
|
||||
}
|
||||
callback(null, {
|
||||
size: remoteFiles.get(key).length,
|
||||
mode: 0o100644,
|
||||
isDirectory: () => false,
|
||||
isSymbolicLink: () => false,
|
||||
});
|
||||
};
|
||||
sftp.open = (remotePath, _flags, callback) => {
|
||||
const key = String(remotePath);
|
||||
if (!remoteFiles.has(key)) remoteFiles.set(key, Buffer.alloc(0));
|
||||
callback(null, Buffer.from(key));
|
||||
};
|
||||
sftp.close = (_handle, callback) => callback(null);
|
||||
};
|
||||
const shared = createFastSftp({});
|
||||
rememberFile(shared);
|
||||
shared.write = (handle, buffer, offset, length, position, callback) => {
|
||||
sharedWrites += 1;
|
||||
const key = handle.toString();
|
||||
const next = Buffer.alloc(Math.max(remoteFiles.get(key)?.length || 0, position + length));
|
||||
if (remoteFiles.has(key)) remoteFiles.get(key).copy(next);
|
||||
buffer.copy(next, position, offset, offset + length);
|
||||
remoteFiles.set(key, next);
|
||||
setImmediate(() => callback(null));
|
||||
};
|
||||
|
||||
const sshClient = new EventEmitter();
|
||||
sshClient.sftp = (callback) => {
|
||||
isolatedOpens += 1;
|
||||
sshClient.pending = callback;
|
||||
};
|
||||
const client = {
|
||||
sftp: shared,
|
||||
stat: async (remotePath) => {
|
||||
const key = String(remotePath);
|
||||
if (!remoteFiles.has(key)) {
|
||||
const error = new Error("ENOENT");
|
||||
error.code = 2;
|
||||
throw error;
|
||||
}
|
||||
return { size: remoteFiles.get(key).length, isDirectory: false };
|
||||
},
|
||||
delete: async (remotePath) => { remoteFiles.delete(String(remotePath)); },
|
||||
async rename(fromPath, toPath) {
|
||||
remoteFiles.set(String(toPath), remoteFiles.get(String(fromPath)));
|
||||
remoteFiles.delete(String(fromPath));
|
||||
},
|
||||
client: sshClient,
|
||||
};
|
||||
|
||||
await assert.rejects(
|
||||
openBoundedSftpChannel(sshClient, { timeoutMs: 15 }),
|
||||
(error) => error.code === "SFTP_CHANNEL_OPEN_TIMEOUT",
|
||||
);
|
||||
assert.equal(isolatedOpens, 1);
|
||||
transferBridge._setIsolatedSftpChannelOpenOptionsForTests({ abandonWaitMs: 0 });
|
||||
transferBridge.init({ sftpClients: new Map([["target", client]]) });
|
||||
|
||||
const result = await transferBridge.startTransfer({ sender: createSender() }, {
|
||||
transferId: "upload-channel-open-pending-shared",
|
||||
sourcePath: localPath,
|
||||
targetPath,
|
||||
sourceType: "local",
|
||||
targetType: "sftp",
|
||||
targetSftpId: "target",
|
||||
totalBytes: payload.length,
|
||||
resumable: false,
|
||||
skipAdmission: true,
|
||||
});
|
||||
|
||||
assert.equal(result.error, undefined, result.error);
|
||||
assert.equal(isolatedOpens, 1, "PENDING must not allocate another isolated OPEN");
|
||||
assert.equal(
|
||||
warnings.some((line) => line.includes("Failed to reopen isolated SFTP channel for fastPut")),
|
||||
false,
|
||||
);
|
||||
assert.ok(sharedWrites >= 1);
|
||||
assert.deepEqual(remoteFiles.get(targetPath), payload);
|
||||
});
|
||||
Reference in new issue
Block a user