dsh-remote-vs 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +2 -1
- package/README.md +2 -1
- package/lib/client.js +199 -14
- package/lib/index.js +299 -11
- package/lib/p2-router-fs.js +1 -1
- package/lib/types/client/i18n.d.ts +1 -1
- package/lib/types/client/listing-requests.d.ts +45 -0
- package/lib/types/pool.d.ts +106 -0
- package/lib/types/sftp.d.ts +35 -0
- package/lib/{worlds-oj65Hic-.js → worlds-C6Xha1mQ.js} +413 -90
- package/package.json +1 -1
- package/src/client/DownloadDock.tsx +6 -2
- package/src/client/RemoteExplorer.tsx +137 -12
- package/src/client/downloads.ts +5 -1
- package/src/client/i18n.ts +6 -1
- package/src/client/listing-requests.ts +84 -0
- package/src/client/vsc/kit.tsx +30 -3
- package/src/pool.ts +377 -17
- package/src/sftp.ts +502 -108
package/src/sftp.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import { randomBytes } from 'node:crypto'
|
|
6
6
|
import type { ServerResponse } from 'node:http'
|
|
7
7
|
import { posix } from 'node:path'
|
|
8
|
-
import type { SFTPWrapper, Stats } from 'ssh2'
|
|
8
|
+
import type { OpenMode, SFTPWrapper, Stats } from 'ssh2'
|
|
9
9
|
import type { RemotePool } from './pool.ts'
|
|
10
10
|
import type { RemoteFileEntry, RemoteRead } from './protocol.ts'
|
|
11
11
|
|
|
@@ -35,8 +35,77 @@ export const UPLOAD_MAX_BYTES = 2 * 1024 * 1024 * 1024
|
|
|
35
35
|
*/
|
|
36
36
|
export const DOWNLOAD_IDLE_MS = 60_000
|
|
37
37
|
|
|
38
|
-
/**
|
|
39
|
-
const
|
|
38
|
+
/** Upload progress bound (no body bytes and no write acknowledgements). */
|
|
39
|
+
export const UPLOAD_IDLE_MS = 60_000
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Parallel-transfer shape, shared by download and upload.
|
|
43
|
+
*
|
|
44
|
+
* A single `createReadStream`/`createWriteStream` keeps exactly ONE SFTP request
|
|
45
|
+
* in flight per round trip; measured against a real host that cost about 8x
|
|
46
|
+
* (4.4 MiB/s single stream vs 35.4 MiB/s for ssh2's pipelined fastGet on the
|
|
47
|
+
* same link). 256 KiB chunks with 32 in-flight requests (8 MiB of app-side
|
|
48
|
+
* buffers) are the same tuning ssh2's fastGet/fastPut use and bound the
|
|
49
|
+
* per-transfer memory; on top of that ssh2 holds up to one 2 MiB channel window
|
|
50
|
+
* per channel in flight, so a two-channel download peaks around 12 MiB.
|
|
51
|
+
*/
|
|
52
|
+
export const TRANSFER_CHUNK_BYTES = 256 * 1024
|
|
53
|
+
|
|
54
|
+
/** In-flight chunk window (also the per-transfer APP-side memory bound: 8 MiB). */
|
|
55
|
+
export const TRANSFER_CONCURRENCY = 32
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Deadline for a download's one-shot metadata calls (`lstat`, `open`, `fstat`).
|
|
59
|
+
*
|
|
60
|
+
* Nothing is streaming while they run, so there is no progress signal to watch
|
|
61
|
+
* and no idle watchdog can help: a server that never answers one would pin the
|
|
62
|
+
* transfer, its channels and its slots forever. The streaming phase stays
|
|
63
|
+
* progress-bounded (`DOWNLOAD_IDLE_MS`) because a big file on a slow link is
|
|
64
|
+
* healthy for minutes.
|
|
65
|
+
*/
|
|
66
|
+
const DOWNLOAD_META_TIMEOUT_MS = 60_000
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Deadline for the OPTIONAL second channel's handle open.
|
|
70
|
+
*
|
|
71
|
+
* This runs after the response headers are sent, so a hang here is worse than a
|
|
72
|
+
* missing second channel: the client is already reading a 200 body. Short on
|
|
73
|
+
* purpose — the fallback (one channel) is always correct.
|
|
74
|
+
*/
|
|
75
|
+
const EXTRA_CHANNEL_TIMEOUT_MS = 10_000
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* How long a handle close may take before it is abandoned.
|
|
79
|
+
*
|
|
80
|
+
* ssh2 only settles the CLOSE requests that were pending when a channel closed:
|
|
81
|
+
* a close issued on an already-dead channel never calls back (the payload is
|
|
82
|
+
* dropped or written to a stale recipient). Awaiting that forever would hang the
|
|
83
|
+
* transfer AFTER its body was delivered and pin both the channels and their
|
|
84
|
+
* slots — the session teardown that follows settles the request anyway, so the
|
|
85
|
+
* wait is abandoned and the pool's `finally` proceeds.
|
|
86
|
+
*/
|
|
87
|
+
const HANDLE_CLOSE_TIMEOUT_MS = 2_000
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Channels a big download spreads its READ window over.
|
|
91
|
+
*
|
|
92
|
+
* ssh2 (Channel.js `MAX_WINDOW`) and OpenSSH cap ONE SSH channel's window at
|
|
93
|
+
* 2 MiB, so a single channel can never keep more than that many bytes of READs
|
|
94
|
+
* outstanding however large the requested concurrency is. Measured against a
|
|
95
|
+
* real host on a 96 MiB file with the same total concurrency (256 KiB chunks):
|
|
96
|
+
* 1 channel 28.6 MiB/s, 2 channels 46.1, 4 channels 51.3 — two channels take
|
|
97
|
+
* most of the gain at a quarter of the cost of four. Uploads showed no such
|
|
98
|
+
* gain (46.0 → 50.4 MiB/s: the server's write path is the bound), so uploads
|
|
99
|
+
* stay on one channel.
|
|
100
|
+
*/
|
|
101
|
+
export const TRANSFER_SESSIONS = 2
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Below this size a second channel is not worth its channel-open round trip and
|
|
105
|
+
* channel slot: the file is only a handful of READ windows long, so the extra
|
|
106
|
+
* channel would mostly be opened and closed.
|
|
107
|
+
*/
|
|
108
|
+
export const MULTI_CHANNEL_MIN_BYTES = 4 * 1024 * 1024
|
|
40
109
|
|
|
41
110
|
/**
|
|
42
111
|
* Cap for both per-path memory sets below (levels confirmed to exist, listings
|
|
@@ -63,6 +132,30 @@ export function remotePath(path: string): string {
|
|
|
63
132
|
return normalized
|
|
64
133
|
}
|
|
65
134
|
|
|
135
|
+
/**
|
|
136
|
+
* Reject when `promise` has not settled within `ms`.
|
|
137
|
+
*
|
|
138
|
+
* The download's one-shot calls (`lstat`, `open`, `fstat`, an extra channel's
|
|
139
|
+
* handle) have no progress signal, so this is the only thing between a stalled
|
|
140
|
+
* server and a response — and two SFTP channels — pinned forever.
|
|
141
|
+
*/
|
|
142
|
+
function bounded<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
|
|
143
|
+
return new Promise<T>((resolve, reject) => {
|
|
144
|
+
const timer = setTimeout(() => reject(new Error(message)), ms)
|
|
145
|
+
timer.unref?.()
|
|
146
|
+
promise.then(
|
|
147
|
+
(value) => {
|
|
148
|
+
clearTimeout(timer)
|
|
149
|
+
resolve(value)
|
|
150
|
+
},
|
|
151
|
+
(error: unknown) => {
|
|
152
|
+
clearTimeout(timer)
|
|
153
|
+
reject(error instanceof Error ? error : new Error(String(error)))
|
|
154
|
+
},
|
|
155
|
+
)
|
|
156
|
+
})
|
|
157
|
+
}
|
|
158
|
+
|
|
66
159
|
/**
|
|
67
160
|
* `Content-Disposition` for one attachment (RFC 6266 + RFC 5987).
|
|
68
161
|
*
|
|
@@ -92,7 +185,7 @@ export class RemoteFiles {
|
|
|
92
185
|
|
|
93
186
|
async list(alias: string, dir: string): Promise<RemoteFileEntry[]> {
|
|
94
187
|
const path = remotePath(dir)
|
|
95
|
-
return this.pool.
|
|
188
|
+
return this.pool.withBrowseSftp(alias, async (sftp) => {
|
|
96
189
|
let rows: ReaddirRow[]
|
|
97
190
|
try {
|
|
98
191
|
rows = await readdirAsync(sftp, path)
|
|
@@ -123,7 +216,7 @@ export class RemoteFiles {
|
|
|
123
216
|
|
|
124
217
|
async stat(alias: string, file: string): Promise<RemoteFileEntry> {
|
|
125
218
|
const path = remotePath(file)
|
|
126
|
-
return this.pool.
|
|
219
|
+
return this.pool.withBrowseSftp(alias, async (sftp) => {
|
|
127
220
|
const attrs = await lstatAsync(sftp, path)
|
|
128
221
|
return toEntry(posix.dirname(path), posix.basename(path), attrs)
|
|
129
222
|
})
|
|
@@ -131,7 +224,7 @@ export class RemoteFiles {
|
|
|
131
224
|
|
|
132
225
|
async read(alias: string, file: string): Promise<RemoteRead> {
|
|
133
226
|
const path = remotePath(file)
|
|
134
|
-
return this.pool.
|
|
227
|
+
return this.pool.withBrowseSftp(alias, async (sftp) => {
|
|
135
228
|
const attrs = await lstatAsync(sftp, path).catch(async (error: unknown) => {
|
|
136
229
|
// The stat fails first for a path that is not there, so without this the
|
|
137
230
|
// caller got a bare "No such file" naming no path, while `list` and
|
|
@@ -220,6 +313,9 @@ export class RemoteFiles {
|
|
|
220
313
|
const path = remotePath(file)
|
|
221
314
|
const dir = posix.dirname(path)
|
|
222
315
|
const partial = `${path}.part-${randomBytes(4).toString('hex')}`
|
|
316
|
+
// No wall-clock deadline: a large body on a slow upload link is healthy for
|
|
317
|
+
// minutes; `streamIntoFile` bounds a dead transfer by progress instead
|
|
318
|
+
// (the old 60 s wrapper turned a healthy 64 MiB upload into a timeout).
|
|
223
319
|
return this.pool.withSftp(alias, async (sftp) => {
|
|
224
320
|
try {
|
|
225
321
|
await this.withDirRetry(alias, dir, async () => {
|
|
@@ -237,7 +333,7 @@ export class RemoteFiles {
|
|
|
237
333
|
await unlinkAsync(sftp, partial).catch(() => undefined)
|
|
238
334
|
throw (await explainSftpFailure(sftp, path, 'file', error)) ?? error
|
|
239
335
|
}
|
|
240
|
-
})
|
|
336
|
+
}, { timeoutMs: 0 })
|
|
241
337
|
}
|
|
242
338
|
|
|
243
339
|
/**
|
|
@@ -259,10 +355,18 @@ export class RemoteFiles {
|
|
|
259
355
|
*/
|
|
260
356
|
async download(alias: string, file: string, res: ServerResponse): Promise<void> {
|
|
261
357
|
const path = remotePath(file)
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
358
|
+
// Streaming itself has no wall clock (progress-bounded, see DOWNLOAD_IDLE_MS);
|
|
359
|
+
// the one-shot calls around it do, because they produce no progress to watch
|
|
360
|
+
// and a server that never answers one would hold the transfer (and its two
|
|
361
|
+
// channel slots) forever.
|
|
362
|
+
await this.pool.withTransferSftp(alias, async (sftp, addChannel) => {
|
|
363
|
+
const link = await bounded(
|
|
364
|
+
lstatAsync(sftp, path).catch(async (error: unknown) => {
|
|
365
|
+
throw (await explainSftpFailure(sftp, path, 'file', error)) ?? error
|
|
366
|
+
}),
|
|
367
|
+
DOWNLOAD_META_TIMEOUT_MS,
|
|
368
|
+
`listing ${path} timed out after ${DOWNLOAD_META_TIMEOUT_MS / 1000}s`,
|
|
369
|
+
)
|
|
266
370
|
// Same pre-check as read(): asking SFTP to open a directory yields a bare
|
|
267
371
|
// "Failure", while the stat that was needed anyway already says what the
|
|
268
372
|
// path is.
|
|
@@ -273,12 +377,22 @@ export class RemoteFiles {
|
|
|
273
377
|
// and a link to a directory only fails once opened. One handle supplies
|
|
274
378
|
// the real type and length, and the stream below is bounded by that
|
|
275
379
|
// length so a file that grows mid-transfer cannot overrun the framing.
|
|
276
|
-
const handle = await
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
380
|
+
const handle = await bounded(
|
|
381
|
+
openAsync(sftp, path).catch(async (error: unknown) => {
|
|
382
|
+
throw (await explainFollowFailure(sftp, path, error)) ?? error
|
|
383
|
+
}),
|
|
384
|
+
DOWNLOAD_META_TIMEOUT_MS,
|
|
385
|
+
`opening ${path} timed out after ${DOWNLOAD_META_TIMEOUT_MS / 1000}s`,
|
|
386
|
+
)
|
|
387
|
+
// Each SFTP session has its own handle space, so every extra channel needs
|
|
388
|
+
// its own handle on the same file; the first one is always open already.
|
|
389
|
+
const channels: Array<{ sftp: SFTPWrapper; handle: Buffer }> = [{ sftp, handle }]
|
|
280
390
|
try {
|
|
281
|
-
const attrs = await
|
|
391
|
+
const attrs = await bounded(
|
|
392
|
+
fstatAsync(sftp, handle),
|
|
393
|
+
DOWNLOAD_META_TIMEOUT_MS,
|
|
394
|
+
`stat of ${path} timed out after ${DOWNLOAD_META_TIMEOUT_MS / 1000}s`,
|
|
395
|
+
)
|
|
282
396
|
if (isDir(attrs.mode)) throw new Error(`not a file: ${path} is a directory`)
|
|
283
397
|
// The client can disappear while the stat is in flight; there is nobody
|
|
284
398
|
// left to stream to, and writing headers to a closed response would turn
|
|
@@ -295,75 +409,34 @@ export class RemoteFiles {
|
|
|
295
409
|
res.end()
|
|
296
410
|
return
|
|
297
411
|
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
streamed = true
|
|
308
|
-
await new Promise<void>((resolve, reject) => {
|
|
309
|
-
let settled = false
|
|
310
|
-
let idle: ReturnType<typeof setTimeout> | undefined
|
|
311
|
-
const finish = (error?: Error): void => {
|
|
312
|
-
if (settled) return
|
|
313
|
-
settled = true
|
|
314
|
-
if (idle !== undefined) clearTimeout(idle)
|
|
315
|
-
if (error === undefined) {
|
|
316
|
-
resolve()
|
|
317
|
-
return
|
|
318
|
-
}
|
|
319
|
-
res.destroy(error)
|
|
320
|
-
reject(error)
|
|
321
|
-
}
|
|
322
|
-
const arm = (): void => {
|
|
323
|
-
if (idle !== undefined) clearTimeout(idle)
|
|
324
|
-
idle = setTimeout(() => {
|
|
325
|
-
// `data` pauses while the pipe applies backpressure, so a slow
|
|
326
|
-
// browser or local disk is not a dead transfer: re-arm while the
|
|
327
|
-
// consumer still has buffered bytes to drain.
|
|
328
|
-
if (stream.isPaused() || res.writableLength > 0) {
|
|
329
|
-
arm()
|
|
330
|
-
return
|
|
331
|
-
}
|
|
332
|
-
try {
|
|
333
|
-
stream.destroy()
|
|
334
|
-
} catch {
|
|
335
|
-
// Ignore close errors; finish() still rejects.
|
|
336
|
-
}
|
|
337
|
-
finish(new Error(`download stalled: no bytes for ${DOWNLOAD_IDLE_MS / 1000}s`))
|
|
338
|
-
}, DOWNLOAD_IDLE_MS)
|
|
339
|
-
}
|
|
340
|
-
stream.on('data', arm)
|
|
341
|
-
res.on('drain', arm)
|
|
342
|
-
stream.on('error', (error: unknown) => {
|
|
343
|
-
finish(error instanceof Error ? error : new Error(String(error)))
|
|
344
|
-
})
|
|
345
|
-
// A closed response is the user/browser going away, not a Host
|
|
346
|
-
// failure: stop reading and let the session close instead of
|
|
347
|
-
// reporting an error.
|
|
348
|
-
res.on('close', () => {
|
|
349
|
-
if (res.writableEnded) return
|
|
412
|
+
if (attrs.size >= MULTI_CHANNEL_MIN_BYTES) {
|
|
413
|
+
// Best effort: a second channel (or a handle on it) that will not open
|
|
414
|
+
// just leaves the transfer on the first one, which is what it would
|
|
415
|
+
// have used anyway. Bounded, because this runs AFTER the headers are
|
|
416
|
+
// sent: an answer that never comes would otherwise hang the response
|
|
417
|
+
// and pin both channels forever (no progress signal exists yet).
|
|
418
|
+
for (let extra = 1; extra < TRANSFER_SESSIONS; extra += 1) {
|
|
419
|
+
const channel = await addChannel()
|
|
420
|
+
if (channel === undefined) break
|
|
350
421
|
try {
|
|
351
|
-
|
|
422
|
+
const extraHandle = await bounded(
|
|
423
|
+
openAsync(channel, path),
|
|
424
|
+
EXTRA_CHANNEL_TIMEOUT_MS,
|
|
425
|
+
`opening ${path} on the second channel timed out after ${EXTRA_CHANNEL_TIMEOUT_MS / 1000}s`,
|
|
426
|
+
)
|
|
427
|
+
channels.push({ sftp: channel, handle: extraHandle })
|
|
352
428
|
} catch {
|
|
353
|
-
|
|
429
|
+
break
|
|
354
430
|
}
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
})
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
// Parallel ordered reads; the writer here owns the response, never the
|
|
434
|
+
// handles, so the finally below always closes each one exactly once.
|
|
435
|
+
await pipeChannelsToResponse(channels, attrs.size, res)
|
|
361
436
|
} finally {
|
|
362
|
-
|
|
363
|
-
// created stream closes it itself (including on abort/destroy).
|
|
364
|
-
if (!streamed) await closeAsync(sftp, handle)
|
|
437
|
+
for (const channel of channels) await closeQuietly(channel.sftp, channel.handle)
|
|
365
438
|
}
|
|
366
|
-
}
|
|
439
|
+
})
|
|
367
440
|
}
|
|
368
441
|
|
|
369
442
|
async mkdir(alias: string, dir: string): Promise<void> {
|
|
@@ -637,15 +710,211 @@ function statAsync(sftp: SFTPWrapper, path: string): Promise<Stats> {
|
|
|
637
710
|
})
|
|
638
711
|
}
|
|
639
712
|
|
|
640
|
-
function openAsync(sftp: SFTPWrapper, path: string): Promise<Buffer> {
|
|
713
|
+
function openAsync(sftp: SFTPWrapper, path: string, flags: OpenMode = 'r'): Promise<Buffer> {
|
|
641
714
|
return new Promise((resolve, reject) => {
|
|
642
|
-
sftp.open(path,
|
|
715
|
+
sftp.open(path, flags, (error, handle) => {
|
|
643
716
|
if (error !== undefined && error !== null) reject(error)
|
|
644
717
|
else resolve(handle)
|
|
645
718
|
})
|
|
646
719
|
})
|
|
647
720
|
}
|
|
648
721
|
|
|
722
|
+
/** Read exactly `buffer.length` bytes at `position` (SFTP may answer short reads). */
|
|
723
|
+
async function readHandleFully(sftp: SFTPWrapper, handle: Buffer, buffer: Buffer, position: number): Promise<void> {
|
|
724
|
+
let filled = 0
|
|
725
|
+
while (filled < buffer.length) {
|
|
726
|
+
const read = await new Promise<number>((resolve, reject) => {
|
|
727
|
+
sftp.read(handle, buffer.subarray(filled), 0, buffer.length - filled, position + filled, (error, bytesRead) => {
|
|
728
|
+
if (error !== undefined && error !== null) reject(error)
|
|
729
|
+
else resolve(bytesRead)
|
|
730
|
+
})
|
|
731
|
+
})
|
|
732
|
+
if (read <= 0) throw new Error(`short read at ${position + filled}`)
|
|
733
|
+
filled += read
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* Copy an open remote file into an HTTP response with a bounded parallel read
|
|
739
|
+
* window spread over one or more SFTP channels.
|
|
740
|
+
*
|
|
741
|
+
* `res` must already carry its headers (including content-length). Workers pread
|
|
742
|
+
* 256 KiB chunks out of order into a bounded map, and one ordered writer copies
|
|
743
|
+
* them to the socket, so the response bytes stay ordered while up to
|
|
744
|
+
* `TRANSFER_CONCURRENCY` READs stay in flight. The chunk index picks the channel
|
|
745
|
+
* (`index % channels.length`) so the in-flight bytes are spread across the SSH
|
|
746
|
+
* channel windows instead of queueing behind one 2 MiB window. A closed response
|
|
747
|
+
* (user cancel) resolves quietly — the route treats that as a cancellation, not
|
|
748
|
+
* an error — and a no-progress watchdog fails a silently dead transfer.
|
|
749
|
+
*/
|
|
750
|
+
async function pipeChannelsToResponse(
|
|
751
|
+
channels: Array<{ sftp: SFTPWrapper; handle: Buffer }>,
|
|
752
|
+
size: number,
|
|
753
|
+
res: ServerResponse,
|
|
754
|
+
): Promise<void> {
|
|
755
|
+
const chunkBytes = TRANSFER_CHUNK_BYTES
|
|
756
|
+
const totalChunks = Math.ceil(size / chunkBytes)
|
|
757
|
+
const windowChunks = Math.min(TRANSFER_CONCURRENCY, totalChunks)
|
|
758
|
+
const ready = new Map<number, Buffer>()
|
|
759
|
+
const chunkWaiters = new Map<number, () => void>()
|
|
760
|
+
const slotWaiters: Array<() => void> = []
|
|
761
|
+
let slots = windowChunks
|
|
762
|
+
let nextRead = 0
|
|
763
|
+
let cancelled = false
|
|
764
|
+
let failure: Error | undefined
|
|
765
|
+
let lastActivity = Date.now()
|
|
766
|
+
|
|
767
|
+
const wakeSlots = (): void => {
|
|
768
|
+
for (const wake of slotWaiters.splice(0)) wake()
|
|
769
|
+
}
|
|
770
|
+
const wakeChunks = (): void => {
|
|
771
|
+
for (const wake of chunkWaiters.values()) wake()
|
|
772
|
+
chunkWaiters.clear()
|
|
773
|
+
}
|
|
774
|
+
const signalChunk = (index: number): void => {
|
|
775
|
+
const wake = chunkWaiters.get(index)
|
|
776
|
+
if (wake !== undefined) {
|
|
777
|
+
chunkWaiters.delete(index)
|
|
778
|
+
wake()
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
const fail = (error: unknown): void => {
|
|
782
|
+
if (failure !== undefined) return
|
|
783
|
+
failure = error instanceof Error ? error : new Error(String(error))
|
|
784
|
+
wakeSlots()
|
|
785
|
+
wakeChunks()
|
|
786
|
+
}
|
|
787
|
+
const acquire = async (): Promise<void> => {
|
|
788
|
+
while (slots <= 0) await new Promise<void>(resolve => slotWaiters.push(resolve))
|
|
789
|
+
slots -= 1
|
|
790
|
+
}
|
|
791
|
+
const release = (): void => {
|
|
792
|
+
slots += 1
|
|
793
|
+
const wake = slotWaiters.shift()
|
|
794
|
+
if (wake !== undefined) wake()
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* Channels whose READ failed. Their chunks are re-read on the first channel:
|
|
798
|
+
* the extra channel is an optimisation, so losing it must degrade the transfer
|
|
799
|
+
* to the single-channel shape it would have used anyway instead of failing a
|
|
800
|
+
* download the first channel can still finish. (A channel that STALLS rather
|
|
801
|
+
* than errors is not recoverable here: no bytes means the ordered writer has
|
|
802
|
+
* nothing to reorder, and the no-progress watchdog ends the transfer.)
|
|
803
|
+
*/
|
|
804
|
+
const failedChannels = new Set<number>()
|
|
805
|
+
const primary = channels[0] as { sftp: SFTPWrapper; handle: Buffer }
|
|
806
|
+
const channelFor = (index: number): { sftp: SFTPWrapper; handle: Buffer; slot: number } => {
|
|
807
|
+
const slot = channels.length > 1 ? index % channels.length : 0
|
|
808
|
+
if (slot === 0 || failedChannels.has(slot)) return { ...primary, slot }
|
|
809
|
+
return { ...(channels[slot] as { sftp: SFTPWrapper; handle: Buffer }), slot }
|
|
810
|
+
}
|
|
811
|
+
const worker = async (): Promise<void> => {
|
|
812
|
+
for (;;) {
|
|
813
|
+
if (cancelled || failure !== undefined) return
|
|
814
|
+
await acquire()
|
|
815
|
+
if (cancelled || failure !== undefined) {
|
|
816
|
+
release()
|
|
817
|
+
return
|
|
818
|
+
}
|
|
819
|
+
const index = nextRead++
|
|
820
|
+
if (index >= totalChunks) {
|
|
821
|
+
release()
|
|
822
|
+
return
|
|
823
|
+
}
|
|
824
|
+
const start = index * chunkBytes
|
|
825
|
+
const length = Math.min(chunkBytes, size - start)
|
|
826
|
+
const buffer = Buffer.allocUnsafe(length)
|
|
827
|
+
try {
|
|
828
|
+
const channel = channelFor(index)
|
|
829
|
+
try {
|
|
830
|
+
await readHandleFully(channel.sftp, channel.handle, buffer, start)
|
|
831
|
+
} catch (error) {
|
|
832
|
+
// A broken optional channel must not fail the whole file: retire it and
|
|
833
|
+
// read this chunk again through the primary one.
|
|
834
|
+
if (channel.slot === 0 || cancelled || failure !== undefined) throw error
|
|
835
|
+
failedChannels.add(channel.slot)
|
|
836
|
+
await readHandleFully(primary.sftp, primary.handle, buffer, start)
|
|
837
|
+
}
|
|
838
|
+
} catch (error) {
|
|
839
|
+
release()
|
|
840
|
+
fail(error)
|
|
841
|
+
return
|
|
842
|
+
}
|
|
843
|
+
lastActivity = Date.now()
|
|
844
|
+
ready.set(index, buffer)
|
|
845
|
+
signalChunk(index)
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
const waitChunk = (index: number): Promise<void> =>
|
|
849
|
+
new Promise<void>((resolve) => {
|
|
850
|
+
if (ready.has(index) || failure !== undefined) resolve()
|
|
851
|
+
else chunkWaiters.set(index, resolve)
|
|
852
|
+
})
|
|
853
|
+
const waitDrain = (): Promise<void> =>
|
|
854
|
+
new Promise<void>((resolve) => {
|
|
855
|
+
if (cancelled || failure !== undefined) {
|
|
856
|
+
resolve()
|
|
857
|
+
return
|
|
858
|
+
}
|
|
859
|
+
res.once('drain', resolve)
|
|
860
|
+
})
|
|
861
|
+
const onResponseClose = (): void => {
|
|
862
|
+
if (res.writableEnded) return
|
|
863
|
+
cancelled = true
|
|
864
|
+
wakeSlots()
|
|
865
|
+
wakeChunks()
|
|
866
|
+
}
|
|
867
|
+
res.on('close', onResponseClose)
|
|
868
|
+
const idle = setInterval(() => {
|
|
869
|
+
if (cancelled || failure !== undefined) return
|
|
870
|
+
if (Date.now() - lastActivity < DOWNLOAD_IDLE_MS) return
|
|
871
|
+
// Buffered output waiting on a slow socket is not a dead transfer.
|
|
872
|
+
if (res.writableLength > 0) {
|
|
873
|
+
lastActivity = Date.now()
|
|
874
|
+
return
|
|
875
|
+
}
|
|
876
|
+
fail(new Error(`download stalled: no bytes for ${DOWNLOAD_IDLE_MS / 1000}s`))
|
|
877
|
+
}, Math.min(5_000, DOWNLOAD_IDLE_MS))
|
|
878
|
+
idle.unref?.()
|
|
879
|
+
|
|
880
|
+
const workers = Array.from({ length: windowChunks }, () => worker())
|
|
881
|
+
try {
|
|
882
|
+
for (let index = 0; index < totalChunks; index += 1) {
|
|
883
|
+
if (cancelled) break
|
|
884
|
+
if (failure !== undefined) break
|
|
885
|
+
if (!ready.has(index)) await waitChunk(index)
|
|
886
|
+
if (cancelled) break
|
|
887
|
+
if (failure !== undefined) break
|
|
888
|
+
const buffer = ready.get(index)
|
|
889
|
+
if (buffer === undefined) continue
|
|
890
|
+
ready.delete(index)
|
|
891
|
+
if (!res.write(buffer)) await waitDrain()
|
|
892
|
+
release()
|
|
893
|
+
lastActivity = Date.now()
|
|
894
|
+
}
|
|
895
|
+
} finally {
|
|
896
|
+
clearInterval(idle)
|
|
897
|
+
res.removeListener('close', onResponseClose)
|
|
898
|
+
const drained = Promise.all(workers.map(workerPromise => workerPromise.catch(() => undefined)))
|
|
899
|
+
if (failure !== undefined || cancelled) {
|
|
900
|
+
// An in-flight READ cannot be aborted at the SFTP layer: do not block the
|
|
901
|
+
// request on it. The caller's `withSftp` finally closes the session, which
|
|
902
|
+
// settles those reads; the workers then find `cancelled` and exit.
|
|
903
|
+
cancelled = true
|
|
904
|
+
wakeSlots()
|
|
905
|
+
wakeChunks()
|
|
906
|
+
await Promise.race([drained, new Promise<void>((resolve) => setTimeout(resolve, 250))])
|
|
907
|
+
} else {
|
|
908
|
+
await drained
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
if (failure !== undefined) {
|
|
912
|
+
res.destroy(failure)
|
|
913
|
+
throw failure
|
|
914
|
+
}
|
|
915
|
+
if (!cancelled) res.end()
|
|
916
|
+
}
|
|
917
|
+
|
|
649
918
|
function fstatAsync(sftp: SFTPWrapper, handle: Buffer): Promise<Stats> {
|
|
650
919
|
return new Promise((resolve, reject) => {
|
|
651
920
|
sftp.fstat(handle, (error, attrs) => {
|
|
@@ -665,6 +934,21 @@ function closeAsync(sftp: SFTPWrapper, handle: Buffer): Promise<void> {
|
|
|
665
934
|
})
|
|
666
935
|
}
|
|
667
936
|
|
|
937
|
+
/**
|
|
938
|
+
* Close one handle, but never wait forever for a channel that is already gone.
|
|
939
|
+
*
|
|
940
|
+
* A close on a dead channel never calls back (see HANDLE_CLOSE_TIMEOUT_MS); the
|
|
941
|
+
* session teardown that follows settles it, so abandoning the wait is safe and
|
|
942
|
+
* keeps a delivered download (or a finished upload) from pinning its channels.
|
|
943
|
+
*/
|
|
944
|
+
function closeQuietly(sftp: SFTPWrapper, handle: Buffer): Promise<void> {
|
|
945
|
+
const abandoned = new Promise<void>((resolve) => {
|
|
946
|
+
const timer = setTimeout(resolve, HANDLE_CLOSE_TIMEOUT_MS)
|
|
947
|
+
timer.unref?.()
|
|
948
|
+
})
|
|
949
|
+
return Promise.race([closeAsync(sftp, handle), abandoned])
|
|
950
|
+
}
|
|
951
|
+
|
|
668
952
|
/**
|
|
669
953
|
* Explain an `open` failure after lstat already saw a symlink: lstat reports
|
|
670
954
|
* the LINK's type, so "the thing at the end of the link is a directory" only
|
|
@@ -743,11 +1027,18 @@ function writeFileAsync(sftp: SFTPWrapper, path: string, data: Buffer): Promise<
|
|
|
743
1027
|
}
|
|
744
1028
|
|
|
745
1029
|
/**
|
|
746
|
-
*
|
|
1030
|
+
* Stream one readable request body into a new remote file with a bounded
|
|
1031
|
+
* parallel write window.
|
|
747
1032
|
*
|
|
748
|
-
*
|
|
749
|
-
*
|
|
750
|
-
*
|
|
1033
|
+
* The mirror of `pipeChannelsToResponse`: incoming bytes are cut into
|
|
1034
|
+
* `TRANSFER_CHUNK_BYTES` pieces and up to `TRANSFER_CONCURRENCY` WRITEs are in
|
|
1035
|
+
* flight at their own offsets. A single `createWriteStream` keeps one WRITE per
|
|
1036
|
+
* round trip and was far slower on the same link (~1 MiB/s, so a 64 MiB body
|
|
1037
|
+
* could not even finish inside the old 60 s session deadline).
|
|
1038
|
+
*
|
|
1039
|
+
* The producer is paused while more than two windows of chunks are waiting, so
|
|
1040
|
+
* Host memory stays bounded. Aborted clients (no `end`) fail instead of hanging:
|
|
1041
|
+
* a stuck upload used to pin the SFTP session and block every later operation.
|
|
751
1042
|
*
|
|
752
1043
|
* @param sftp - live SFTP session.
|
|
753
1044
|
* @param path - absolute remote destination.
|
|
@@ -762,50 +1053,153 @@ function streamIntoFile(
|
|
|
762
1053
|
maxBytes: number,
|
|
763
1054
|
): Promise<number> {
|
|
764
1055
|
return new Promise<number>((resolve, reject) => {
|
|
765
|
-
const
|
|
766
|
-
|
|
1056
|
+
const chunkBytes = TRANSFER_CHUNK_BYTES
|
|
1057
|
+
const windowChunks = TRANSFER_CONCURRENCY
|
|
1058
|
+
const chunks = new Map<number, Buffer>()
|
|
1059
|
+
let nextChunk = 0
|
|
1060
|
+
let nextWrite = 0
|
|
1061
|
+
let pendingWrites = 0
|
|
1062
|
+
let received = 0
|
|
1063
|
+
let carry: Buffer | undefined
|
|
1064
|
+
let handle: Buffer | undefined
|
|
1065
|
+
let ended = false
|
|
767
1066
|
let settled = false
|
|
768
|
-
|
|
1067
|
+
let lastActivity = Date.now()
|
|
1068
|
+
let idle: ReturnType<typeof setInterval> | undefined
|
|
1069
|
+
|
|
1070
|
+
const finish = (error?: Error): void => {
|
|
769
1071
|
if (settled) return
|
|
770
1072
|
settled = true
|
|
1073
|
+
if (idle !== undefined) clearInterval(idle)
|
|
1074
|
+
try {
|
|
1075
|
+
source.pause()
|
|
1076
|
+
} catch {
|
|
1077
|
+
// Source already gone.
|
|
1078
|
+
}
|
|
1079
|
+
if (error === undefined) {
|
|
1080
|
+
resolve(received)
|
|
1081
|
+
return
|
|
1082
|
+
}
|
|
1083
|
+
try {
|
|
1084
|
+
(source as unknown as { destroy?: (error?: Error) => void }).destroy?.(error)
|
|
1085
|
+
} catch {
|
|
1086
|
+
// Already destroyed.
|
|
1087
|
+
}
|
|
1088
|
+
if (handle !== undefined) {
|
|
1089
|
+
const current = handle
|
|
1090
|
+
handle = undefined
|
|
1091
|
+
void closeQuietly(sftp, current)
|
|
1092
|
+
}
|
|
1093
|
+
reject(error)
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
const pump = (): void => {
|
|
1097
|
+
const current = handle
|
|
1098
|
+
if (settled || current === undefined) return
|
|
1099
|
+
while (pendingWrites < windowChunks && chunks.has(nextWrite)) {
|
|
1100
|
+
const index = nextWrite++
|
|
1101
|
+
const buffer = chunks.get(index)
|
|
1102
|
+
if (buffer === undefined) break
|
|
1103
|
+
chunks.delete(index)
|
|
1104
|
+
pendingWrites += 1
|
|
1105
|
+
sftp.write(current, buffer, 0, buffer.length, index * chunkBytes, (error) => {
|
|
1106
|
+
pendingWrites -= 1
|
|
1107
|
+
if (settled) return
|
|
1108
|
+
if (error !== undefined && error !== null) {
|
|
1109
|
+
finish(error instanceof Error ? error : new Error(String(error)))
|
|
1110
|
+
return
|
|
1111
|
+
}
|
|
1112
|
+
lastActivity = Date.now()
|
|
1113
|
+
pump()
|
|
1114
|
+
maybeFinish()
|
|
1115
|
+
try {
|
|
1116
|
+
if (chunks.size < windowChunks) source.resume()
|
|
1117
|
+
} catch {
|
|
1118
|
+
// Source ended.
|
|
1119
|
+
}
|
|
1120
|
+
})
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
const maybeFinish = (): void => {
|
|
1125
|
+
if (settled || !ended) return
|
|
1126
|
+
if (pendingWrites > 0 || chunks.size > 0) return
|
|
1127
|
+
const current = handle
|
|
1128
|
+
handle = undefined
|
|
1129
|
+
if (current === undefined) {
|
|
1130
|
+
finish()
|
|
1131
|
+
return
|
|
1132
|
+
}
|
|
1133
|
+
closeQuietly(sftp, current).then(() => finish(), () => finish())
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
const enqueue = (buffer: Buffer): void => {
|
|
1137
|
+
chunks.set(nextChunk, buffer)
|
|
1138
|
+
nextChunk += 1
|
|
771
1139
|
try {
|
|
772
|
-
|
|
1140
|
+
if (chunks.size + pendingWrites >= windowChunks * 2) source.pause()
|
|
773
1141
|
} catch {
|
|
774
|
-
//
|
|
1142
|
+
// Source already gone.
|
|
775
1143
|
}
|
|
776
|
-
|
|
1144
|
+
pump()
|
|
777
1145
|
}
|
|
1146
|
+
|
|
1147
|
+
const pushData = (chunk: Buffer): void => {
|
|
1148
|
+
const data = carry === undefined ? chunk : Buffer.concat([carry, chunk])
|
|
1149
|
+
let offset = 0
|
|
1150
|
+
while (data.length - offset >= chunkBytes) {
|
|
1151
|
+
enqueue(Buffer.from(data.subarray(offset, offset + chunkBytes)))
|
|
1152
|
+
offset += chunkBytes
|
|
1153
|
+
}
|
|
1154
|
+
carry = offset < data.length ? Buffer.from(data.subarray(offset)) : undefined
|
|
1155
|
+
}
|
|
1156
|
+
|
|
778
1157
|
source.on('data', (chunk: Buffer) => {
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
1158
|
+
if (settled) return
|
|
1159
|
+
received += chunk.length
|
|
1160
|
+
if (received > maxBytes) {
|
|
1161
|
+
finish(new Error(`upload exceeds the ${formatBytes(maxBytes)} limit`))
|
|
1162
|
+
return
|
|
1163
|
+
}
|
|
1164
|
+
lastActivity = Date.now()
|
|
1165
|
+
pushData(chunk)
|
|
1166
|
+
})
|
|
1167
|
+
source.on('end', () => {
|
|
1168
|
+
if (settled || ended) return
|
|
1169
|
+
ended = true
|
|
1170
|
+
if (carry !== undefined) {
|
|
1171
|
+
const tail = carry
|
|
1172
|
+
carry = undefined
|
|
1173
|
+
enqueue(tail)
|
|
787
1174
|
}
|
|
1175
|
+
maybeFinish()
|
|
788
1176
|
})
|
|
789
|
-
source.on('error',
|
|
1177
|
+
source.on('error', (error: unknown) => finish(error instanceof Error ? error : new Error(String(error))))
|
|
790
1178
|
// A client that gives up (the explorer's ✕, a closed tab) never sends 'end',
|
|
791
1179
|
// and without this the promise below never settles: the SFTP session stays
|
|
792
1180
|
// held, every later operation on that host queues behind it, and the next
|
|
793
1181
|
// `stat` looks like a dead host (2026-10-20: an aborted 64 MB upload made the
|
|
794
1182
|
// following drop sit at "正在读取拖放内容…" forever).
|
|
795
|
-
const aborted = (): void =>
|
|
1183
|
+
const aborted = (): void => finish(new Error('upload aborted by the client'))
|
|
796
1184
|
source.on('aborted', aborted)
|
|
797
1185
|
source.on('close', () => {
|
|
798
1186
|
// `complete` is false when the request ended before its body finished.
|
|
799
1187
|
const complete = (source as unknown as { complete?: boolean }).complete
|
|
800
1188
|
if (complete === false) aborted()
|
|
801
1189
|
})
|
|
802
|
-
|
|
803
|
-
|
|
1190
|
+
|
|
1191
|
+
idle = setInterval(() => {
|
|
804
1192
|
if (settled) return
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
})
|
|
808
|
-
|
|
1193
|
+
if (Date.now() - lastActivity < UPLOAD_IDLE_MS) return
|
|
1194
|
+
finish(new Error(`SFTP upload stalled: no progress for ${UPLOAD_IDLE_MS / 1000}s`))
|
|
1195
|
+
}, Math.min(5_000, UPLOAD_IDLE_MS))
|
|
1196
|
+
idle.unref?.()
|
|
1197
|
+
|
|
1198
|
+
openAsync(sftp, path, 'w').then((opened) => {
|
|
1199
|
+
handle = opened
|
|
1200
|
+
pump()
|
|
1201
|
+
maybeFinish()
|
|
1202
|
+
}, (error: unknown) => finish(error instanceof Error ? error : new Error(String(error))))
|
|
809
1203
|
})
|
|
810
1204
|
}
|
|
811
1205
|
|