mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-27 20:00:51 +00:00
fix(sftp): poison path gate after fastPut OPEN wait timeout
When a dead write OPEN leaves truncatingSharedWriteOpenGates unresolved, fail-closed fastPut timeout now marks that entry failed so later same-path uploads reject promptly instead of hanging on waitForPrior. Keep the barrier until a late OPEN release clears it; waitForPrior rejection no longer starts OPEN. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
This commit is contained in:
2 files changed
+287
-10
No files matched your search
@@ -336,16 +336,33 @@ function remoteOpenPathMatchesStaged(openPath, stagedRemote) {
|
||||
* if the stale OPEN lands after the retry has begun writing, the server
|
||||
* truncates the retry stage and a later size check can promote sparse data
|
||||
* (Codex P1 on 42a27ef7). Wait for any prior OPEN on the path to settle before
|
||||
* issuing another truncating OPEN; release on OPEN callback and on drain
|
||||
* force-complete so a dead channel cannot block retries forever.
|
||||
* issuing another truncating OPEN; release on OPEN callback so a late truncating
|
||||
* OPEN cannot race a retry. When an OPEN dies without a callback, fail() poisons
|
||||
* the entry so later waiters reject promptly (fail-closed) instead of hanging
|
||||
* forever on waitForPrior (#2755 / Codex P2 on dca41093).
|
||||
*
|
||||
* @type {Map<string, { promise: Promise<void>, resolve: () => void, released: boolean }>}
|
||||
* @type {Map<string, {
|
||||
* promise: Promise<void>,
|
||||
* resolve: () => void,
|
||||
* reject: (err: Error) => void,
|
||||
* released: boolean,
|
||||
* failed: boolean,
|
||||
* failError: Error | null,
|
||||
* }>}
|
||||
*/
|
||||
const truncatingSharedWriteOpenGates = new Map();
|
||||
/** @type {WeakMap<object, string>} */
|
||||
const truncatingSharedWriteSftpKeys = new WeakMap();
|
||||
let truncatingSharedWriteSftpSeq = 0;
|
||||
|
||||
function createPoisonedWriteOpenPathGateError(message) {
|
||||
const err = new Error(
|
||||
message || "Prior write OPEN never settled; path gate is fail-closed",
|
||||
);
|
||||
err.noTransferFallback = true;
|
||||
return err;
|
||||
}
|
||||
|
||||
function sharedWriteOpenPathKey(filePath) {
|
||||
if (Buffer.isBuffer(filePath)) return `b:${filePath.toString("hex")}`;
|
||||
return `s:${String(filePath ?? "")}`;
|
||||
@@ -387,25 +404,47 @@ function sharedWriteOpenSessionKey(sftp, transfer) {
|
||||
/**
|
||||
* @param {string | Buffer} filePath
|
||||
* @param {string} [sessionKey]
|
||||
* @returns {{ waitForPrior: Promise<void>, release: () => void }}
|
||||
* @returns {{ waitForPrior: Promise<void>, release: () => void, fail: (err?: Error) => void }}
|
||||
*/
|
||||
function beginTruncatingSharedWriteOpen(filePath, sessionKey = "unknown") {
|
||||
const key = `${sessionKey}|${sharedWriteOpenPathKey(filePath)}`;
|
||||
const prior = truncatingSharedWriteOpenGates.get(key);
|
||||
|
||||
// Poisoned prior: keep the fail-closed barrier. Do not replace the map entry
|
||||
// with a fresh waiter that could release and let a later OPEN race a still-
|
||||
// pending truncate. New callers fail promptly on waitForPrior.
|
||||
if (prior?.failed) {
|
||||
const err = prior.failError || createPoisonedWriteOpenPathGateError();
|
||||
return {
|
||||
waitForPrior: Promise.reject(err),
|
||||
release: () => {},
|
||||
fail: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
const waitForPrior = prior && !prior.released
|
||||
? prior.promise
|
||||
: Promise.resolve();
|
||||
|
||||
let resolve;
|
||||
const promise = new Promise((r) => {
|
||||
resolve = r;
|
||||
let reject;
|
||||
const promise = new Promise((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
// Avoid unhandledRejection when nobody awaits yet (fail before waiters attach).
|
||||
promise.catch(() => {});
|
||||
const entry = {
|
||||
promise,
|
||||
resolve: () => {
|
||||
resolve();
|
||||
},
|
||||
reject: (err) => {
|
||||
reject(err);
|
||||
},
|
||||
released: false,
|
||||
failed: false,
|
||||
failError: null,
|
||||
};
|
||||
truncatingSharedWriteOpenGates.set(key, entry);
|
||||
|
||||
@@ -415,10 +454,25 @@ function beginTruncatingSharedWriteOpen(filePath, sessionKey = "unknown") {
|
||||
if (truncatingSharedWriteOpenGates.get(key) === entry) {
|
||||
truncatingSharedWriteOpenGates.delete(key);
|
||||
}
|
||||
// Already failed: promise rejected; just drop the barrier once OPEN settled.
|
||||
if (entry.failed) return;
|
||||
entry.resolve();
|
||||
};
|
||||
|
||||
return { waitForPrior, release };
|
||||
const fail = (error) => {
|
||||
if (entry.released || entry.failed) return;
|
||||
const err = error instanceof Error
|
||||
? error
|
||||
: createPoisonedWriteOpenPathGateError(String(error?.message || error || ""));
|
||||
if (!err.noTransferFallback) err.noTransferFallback = true;
|
||||
entry.failed = true;
|
||||
entry.failError = err;
|
||||
// Keep entry in the map so later beginTruncatingSharedWriteOpen sees failed
|
||||
// and rejects promptly without clearing the fail-closed barrier.
|
||||
entry.reject(err);
|
||||
};
|
||||
|
||||
return { waitForPrior, release, fail };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1970,11 +2024,20 @@ async function uploadFile(
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
// Fail closed: do not fall through to another writer on the
|
||||
// same stage while a truncating OPEN may still land.
|
||||
// same stage while a truncating OPEN may still land. Poison the
|
||||
// shared path gate so a later same-path upload fails promptly
|
||||
// instead of awaiting the unresolved entry forever (Codex P2).
|
||||
const err = new Error(
|
||||
"Timed out waiting for prior write OPEN to settle before fastPut",
|
||||
);
|
||||
err.noTransferFallback = true;
|
||||
try {
|
||||
transfer._failPendingWriteOpenPathGate?.(
|
||||
createPoisonedWriteOpenPathGateError(
|
||||
"Prior write OPEN never settled; path gate is fail-closed",
|
||||
),
|
||||
);
|
||||
} catch { /* ignore */ }
|
||||
finish(reject, err);
|
||||
}, 2000);
|
||||
const onAbort = () => {
|
||||
@@ -2189,7 +2252,9 @@ function openSftpHandleForTransfer(sftp, filePath, flags, transfer, options = {}
|
||||
: null;
|
||||
// Expose a promise that resolves when this OPEN's path gate is released so
|
||||
// same-transfer fallbacks (fastPut) can wait instead of racing a still-
|
||||
// pending truncating OPEN (Codex P1 on 7872a304).
|
||||
// pending truncating OPEN (Codex P1 on 7872a304). Also expose fail so a
|
||||
// fail-closed fastPut timeout can poison the shared path gate for later
|
||||
// same-path waiters (Codex P2 on dca41093).
|
||||
if (pathGate && transfer && typeof transfer === "object") {
|
||||
let resolvePathGate;
|
||||
const pending = new Promise((resolve) => { resolvePathGate = resolve; });
|
||||
@@ -2200,6 +2265,10 @@ function openSftpHandleForTransfer(sftp, filePath, flags, transfer, options = {}
|
||||
transfer.pendingWriteOpenPathGate = null;
|
||||
}
|
||||
transfer._resolvePendingWriteOpenPathGate = null;
|
||||
transfer._failPendingWriteOpenPathGate = null;
|
||||
};
|
||||
transfer._failPendingWriteOpenPathGate = (error) => {
|
||||
try { pathGate.fail?.(error); } catch { /* ignore */ }
|
||||
};
|
||||
}
|
||||
// Re-check ownership at unlink time: a same-id retry may already own
|
||||
@@ -2721,7 +2790,16 @@ function openSftpHandleForTransfer(sftp, filePath, flags, transfer, options = {}
|
||||
});
|
||||
};
|
||||
|
||||
pathGate.waitForPrior.then(startOpen, startOpen);
|
||||
pathGate.waitForPrior.then(
|
||||
startOpen,
|
||||
(err) => {
|
||||
const error = err instanceof Error
|
||||
? err
|
||||
: createPoisonedWriteOpenPathGateError(String(err?.message || err || ""));
|
||||
if (!error.noTransferFallback) error.noTransferFallback = true;
|
||||
abandonGateWait(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -5142,6 +5142,205 @@ test("fastPut fallback fails closed when prior isolated write OPEN gate never se
|
||||
assert.equal(sender.sent.some((entry) => entry.channel === "netcatty:transfer:complete"), false);
|
||||
});
|
||||
|
||||
test("later same-path upload fails promptly after prior write OPEN gate is poisoned", async (t) => {
|
||||
// Codex P2 on dca41093: after the fail-closed fastPut gate timeout, the dead
|
||||
// OPEN's truncatingSharedWriteOpenGates entry must not leave a later in-place
|
||||
// upload blocked forever in pathGate.waitForPrior. Use a symlink destination
|
||||
// so both attempts OPEN the same final path (allowInPlaceFallback). Subsequent
|
||||
// waiters must fail promptly (noTransferFallback) while the barrier stays
|
||||
// fail-closed — they must not hang and must not issue another truncating OPEN.
|
||||
const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "netcatty-transfer-gate-fail-closed-"));
|
||||
t.after(async () => {
|
||||
await fs.promises.rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const payload = Buffer.alloc(TRANSFER_CHUNK_SIZE, 63);
|
||||
const localPath = path.join(tempDir, "upload.bin");
|
||||
const targetPath = "/tmp/upload-inplace-gate-fail-closed.bin";
|
||||
const remoteFiles = new Map([[targetPath, Buffer.from("old")]]);
|
||||
await fs.promises.writeFile(localPath, payload);
|
||||
|
||||
let isolatedChannelCount = 0;
|
||||
let firstOpenStarted = false;
|
||||
let firstOpenPath = null;
|
||||
let firstIsolated = null;
|
||||
let laterWriteOpens = 0;
|
||||
const symlinkLstat = (remotePath, callback) => {
|
||||
const key = String(remotePath);
|
||||
if (key.includes(".netcatty-backup-") || key.includes(".netcatty-upload-") || key.includes(".netcatty-")) {
|
||||
const error = new Error("ENOENT");
|
||||
error.code = 2;
|
||||
callback(error);
|
||||
return;
|
||||
}
|
||||
if (!remoteFiles.has(key)) {
|
||||
const error = new Error("ENOENT");
|
||||
error.code = 2;
|
||||
callback(error);
|
||||
return;
|
||||
}
|
||||
callback(null, {
|
||||
size: remoteFiles.get(key).length,
|
||||
mode: 0o120777,
|
||||
isDirectory: () => false,
|
||||
isSymbolicLink: () => true,
|
||||
});
|
||||
};
|
||||
const sharedSftp = createFastSftp({
|
||||
lstat: symlinkLstat,
|
||||
open(remotePath, flags, callback) {
|
||||
laterWriteOpens += 1;
|
||||
callback(null, Buffer.from(`shared-handle:${flags}:${remotePath}`));
|
||||
},
|
||||
write(_handle, _buffer, _offset, length, _position, callback) {
|
||||
callback(null);
|
||||
},
|
||||
close(_handle, callback) {
|
||||
callback(null);
|
||||
},
|
||||
createWriteStream() {
|
||||
throw new Error("stream fallback must not run after fail-closed path gate");
|
||||
},
|
||||
});
|
||||
|
||||
const client = {
|
||||
sftp: sharedSftp,
|
||||
async stat(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 };
|
||||
},
|
||||
rename() {
|
||||
return Promise.resolve();
|
||||
},
|
||||
async delete(remotePath) {
|
||||
remoteFiles.delete(String(remotePath));
|
||||
},
|
||||
client: {
|
||||
sftp(callback) {
|
||||
isolatedChannelCount += 1;
|
||||
if (isolatedChannelCount === 1) {
|
||||
firstIsolated = createFastSftp({
|
||||
lstat: symlinkLstat,
|
||||
open(remotePath, flags) {
|
||||
assert.equal(flags, "w");
|
||||
assert.equal(String(remotePath), targetPath, "first attempt must OPEN in-place final path");
|
||||
firstOpenPath = String(remotePath);
|
||||
firstOpenStarted = true;
|
||||
},
|
||||
write() {
|
||||
throw new Error("WRITE must not run after channel error during OPEN");
|
||||
},
|
||||
end() {},
|
||||
});
|
||||
callback(null, firstIsolated);
|
||||
return;
|
||||
}
|
||||
// Later isolated channels: OPEN must not be reached while the path gate
|
||||
// is fail-closed; count attempts if the barrier is incorrectly released.
|
||||
callback(null, createFastSftp({
|
||||
lstat: symlinkLstat,
|
||||
open(remotePath, flags, cb) {
|
||||
laterWriteOpens += 1;
|
||||
cb(null, Buffer.from(`isolated-handle:${flags}:${remotePath}`));
|
||||
},
|
||||
write(_handle, _buffer, _offset, length, _position, cb) {
|
||||
cb(null);
|
||||
},
|
||||
close(_handle, cb) {
|
||||
cb(null);
|
||||
},
|
||||
fastPut(_local, _remote, _opts, cb) {
|
||||
cb(null);
|
||||
},
|
||||
end() {},
|
||||
}));
|
||||
},
|
||||
},
|
||||
};
|
||||
transferBridge.init({ sftpClients: new Map([["target", client]]) });
|
||||
|
||||
const firstSender = createSender();
|
||||
const firstRunning = transferBridge.startTransfer(
|
||||
{ sender: firstSender },
|
||||
{
|
||||
transferId: "upload-inplace-gate-fail-closed-first",
|
||||
sourcePath: localPath,
|
||||
targetPath,
|
||||
sourceType: "local",
|
||||
targetType: "sftp",
|
||||
targetSftpId: "target",
|
||||
totalBytes: payload.length,
|
||||
resumable: false,
|
||||
skipAdmission: true,
|
||||
},
|
||||
);
|
||||
|
||||
const openReady = await waitUntil(() => firstOpenStarted, 2000);
|
||||
assert.ok(openReady, "expected concurrent-isolated in-place write OPEN to stall");
|
||||
assert.equal(firstOpenPath, targetPath);
|
||||
firstIsolated.emit("error", new Error("isolated SFTP channel died during OPEN"));
|
||||
|
||||
const firstResult = await Promise.race([
|
||||
firstRunning,
|
||||
new Promise((_, reject) => {
|
||||
setTimeout(
|
||||
() => reject(new Error("first transfer hung awaiting pendingWriteOpenPathGate before fastPut")),
|
||||
5000,
|
||||
);
|
||||
}),
|
||||
]);
|
||||
assert.match(firstResult.error || "", /Timed out waiting for prior write OPEN to settle before fastPut/i);
|
||||
|
||||
// Later same-path in-place upload must fail promptly — not hang on the
|
||||
// unresolved truncatingSharedWriteOpenGates entry (Codex P2).
|
||||
const laterSender = createSender();
|
||||
const laterStartedAt = Date.now();
|
||||
const laterRunning = transferBridge.startTransfer(
|
||||
{ sender: laterSender },
|
||||
{
|
||||
transferId: "upload-inplace-gate-fail-closed-later",
|
||||
sourcePath: localPath,
|
||||
targetPath,
|
||||
sourceType: "local",
|
||||
targetType: "sftp",
|
||||
targetSftpId: "target",
|
||||
totalBytes: payload.length,
|
||||
resumable: false,
|
||||
skipAdmission: true,
|
||||
},
|
||||
);
|
||||
const laterResult = await Promise.race([
|
||||
laterRunning,
|
||||
new Promise((_, reject) => {
|
||||
setTimeout(
|
||||
() => reject(new Error("later same-path upload hung on unresolved write OPEN path gate")),
|
||||
1500,
|
||||
);
|
||||
}),
|
||||
]);
|
||||
|
||||
assert.ok(
|
||||
Date.now() - laterStartedAt < 1500,
|
||||
"later upload must settle promptly after fail-closed path gate",
|
||||
);
|
||||
assert.ok(laterResult.error, "expected later upload to fail closed on unresolved path gate");
|
||||
assert.match(
|
||||
laterResult.error,
|
||||
/Timed out waiting for prior write OPEN|prior write OPEN never settled|write OPEN path gate/i,
|
||||
);
|
||||
assert.equal(
|
||||
laterWriteOpens,
|
||||
0,
|
||||
"fail-closed path gate must not allow a later truncating write OPEN",
|
||||
);
|
||||
assert.equal(laterSender.sent.some((entry) => entry.channel === "netcatty:transfer:complete"), false);
|
||||
});
|
||||
|
||||
test("shared upload OPEN drain unlinks late staged OPEN after channel-error force-complete", async (t) => {
|
||||
// Codex P2 on bd42c51c: late truncating OPEN after channel-error drain
|
||||
// force-complete is not a cancel (`transfer.cancelled` false). Non-resumable
|
||||
|
||||
Reference in new issue
Block a user