dsh-remote-vs 0.11.1 → 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/src/sftp.ts CHANGED
@@ -3,8 +3,9 @@
3
3
  * remote host; every entry point validates before touching the wire.
4
4
  */
5
5
  import { randomBytes } from 'node:crypto'
6
+ import type { ServerResponse } from 'node:http'
6
7
  import { posix } from 'node:path'
7
- import type { SFTPWrapper, Stats } from 'ssh2'
8
+ import type { OpenMode, SFTPWrapper, Stats } from 'ssh2'
8
9
  import type { RemotePool } from './pool.ts'
9
10
  import type { RemoteFileEntry, RemoteRead } from './protocol.ts'
10
11
 
@@ -24,6 +25,88 @@ export const LIST_ENTRY_CAP = 20000
24
25
  /** Largest single upload accepted (matches the client-side planner cap). */
25
26
  export const UPLOAD_MAX_BYTES = 2 * 1024 * 1024 * 1024
26
27
 
28
+ /**
29
+ * How long one download stream may make no progress before it is failed.
30
+ *
31
+ * A download has no wall-clock budget for the same reason an upload does not: a
32
+ * big file on a slow link is healthy for minutes. What must never happen is a
33
+ * silently dead stream pinning the SFTP session (and its channel slot) forever,
34
+ * so progress is the bound — any chunk resets this clock.
35
+ */
36
+ export const DOWNLOAD_IDLE_MS = 60_000
37
+
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
109
+
27
110
  /**
28
111
  * Cap for both per-path memory sets below (levels confirmed to exist, listings
29
112
  * already reported as truncated). Each only ever saves round trips or a repeat
@@ -49,6 +132,46 @@ export function remotePath(path: string): string {
49
132
  return normalized
50
133
  }
51
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
+
159
+ /**
160
+ * `Content-Disposition` for one attachment (RFC 6266 + RFC 5987).
161
+ *
162
+ * Receivers prefer `filename*` when both forms are present (RFC 6266 §4.3),
163
+ * which is why a non-ASCII remote name survives the round trip; the quoted
164
+ * ASCII copy is the fallback for clients that do not understand the extended
165
+ * form. Quotes and backslashes are stripped from that fallback so they cannot
166
+ * break the header.
167
+ */
168
+ export function attachmentHeader(fileName: string): string {
169
+ // eslint-disable-next-line no-control-regex -- stripping control bytes is the point
170
+ const fallback = fileName.replace(/[^\u0020-\u007e]/g, '_').replace(/["\\]/g, '_')
171
+ const encoded = encodeURIComponent(fileName).replace(/['()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)
172
+ return `attachment; filename="${fallback}"; filename*=UTF-8''${encoded}`
173
+ }
174
+
52
175
  export class RemoteFiles {
53
176
  /**
54
177
  * `alias + level` pairs confirmed to exist on the remote (insertion order,
@@ -62,7 +185,7 @@ export class RemoteFiles {
62
185
 
63
186
  async list(alias: string, dir: string): Promise<RemoteFileEntry[]> {
64
187
  const path = remotePath(dir)
65
- return this.pool.withSftp(alias, async (sftp) => {
188
+ return this.pool.withBrowseSftp(alias, async (sftp) => {
66
189
  let rows: ReaddirRow[]
67
190
  try {
68
191
  rows = await readdirAsync(sftp, path)
@@ -93,7 +216,7 @@ export class RemoteFiles {
93
216
 
94
217
  async stat(alias: string, file: string): Promise<RemoteFileEntry> {
95
218
  const path = remotePath(file)
96
- return this.pool.withSftp(alias, async (sftp) => {
219
+ return this.pool.withBrowseSftp(alias, async (sftp) => {
97
220
  const attrs = await lstatAsync(sftp, path)
98
221
  return toEntry(posix.dirname(path), posix.basename(path), attrs)
99
222
  })
@@ -101,7 +224,7 @@ export class RemoteFiles {
101
224
 
102
225
  async read(alias: string, file: string): Promise<RemoteRead> {
103
226
  const path = remotePath(file)
104
- return this.pool.withSftp(alias, async (sftp) => {
227
+ return this.pool.withBrowseSftp(alias, async (sftp) => {
105
228
  const attrs = await lstatAsync(sftp, path).catch(async (error: unknown) => {
106
229
  // The stat fails first for a path that is not there, so without this the
107
230
  // caller got a bare "No such file" naming no path, while `list` and
@@ -190,6 +313,9 @@ export class RemoteFiles {
190
313
  const path = remotePath(file)
191
314
  const dir = posix.dirname(path)
192
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).
193
319
  return this.pool.withSftp(alias, async (sftp) => {
194
320
  try {
195
321
  await this.withDirRetry(alias, dir, async () => {
@@ -207,6 +333,109 @@ export class RemoteFiles {
207
333
  await unlinkAsync(sftp, partial).catch(() => undefined)
208
334
  throw (await explainSftpFailure(sftp, path, 'file', error)) ?? error
209
335
  }
336
+ }, { timeoutMs: 0 })
337
+ }
338
+
339
+ /**
340
+ * Stream one remote file into an HTTP response (download to the local machine).
341
+ *
342
+ * Streaming, not `read()`: `read()` caps at 8 MiB because it answers a JSON
343
+ * editor read, while a download is whatever the user pointed at — a log, a
344
+ * binary, an artifact. The file is opened through one SFTP handle before the
345
+ * headers are written: symlinks are followed (lstat's size is the link
346
+ * target's string length, not the file's), directories are refused, and the
347
+ * content length comes from the same handle the body is read through. The
348
+ * session has no wall-clock deadline (see `DOWNLOAD_IDLE_MS`); the caller's
349
+ * response close and stream errors are both handled, so a cancelled download
350
+ * never leaves the SFTP session or its channel slot pinned.
351
+ *
352
+ * @param alias - host alias.
353
+ * @param file - absolute remote source path.
354
+ * @param res - HTTP response to write the file into.
355
+ */
356
+ async download(alias: string, file: string, res: ServerResponse): Promise<void> {
357
+ const path = remotePath(file)
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
+ )
370
+ // Same pre-check as read(): asking SFTP to open a directory yields a bare
371
+ // "Failure", while the stat that was needed anyway already says what the
372
+ // path is.
373
+ if (isDir(link.mode)) throw new Error(`not a file: ${path} is a directory`)
374
+ // A symlink must be OPENED, not trusted: lstat reports the LINK's size
375
+ // (the target string), while the body comes from the file the link names.
376
+ // Framing one against the other breaks the response for every symlink,
377
+ // and a link to a directory only fails once opened. One handle supplies
378
+ // the real type and length, and the stream below is bounded by that
379
+ // length so a file that grows mid-transfer cannot overrun the framing.
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 }]
390
+ try {
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
+ )
396
+ if (isDir(attrs.mode)) throw new Error(`not a file: ${path} is a directory`)
397
+ // The client can disappear while the stat is in flight; there is nobody
398
+ // left to stream to, and writing headers to a closed response would turn
399
+ // "user cancelled" into a spurious Host error.
400
+ if (res.destroyed) return
401
+ res.writeHead(200, {
402
+ 'content-type': 'application/octet-stream',
403
+ 'content-length': String(attrs.size),
404
+ 'content-disposition': attachmentHeader(posix.basename(path)),
405
+ 'cache-control': 'no-store',
406
+ 'x-content-type-options': 'nosniff',
407
+ })
408
+ if (attrs.size <= 0) {
409
+ res.end()
410
+ return
411
+ }
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
421
+ try {
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 })
428
+ } catch {
429
+ break
430
+ }
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)
436
+ } finally {
437
+ for (const channel of channels) await closeQuietly(channel.sftp, channel.handle)
438
+ }
210
439
  })
211
440
  }
212
441
 
@@ -472,6 +701,274 @@ function lstatAsync(sftp: SFTPWrapper, path: string): Promise<Stats> {
472
701
  })
473
702
  }
474
703
 
704
+ function statAsync(sftp: SFTPWrapper, path: string): Promise<Stats> {
705
+ return new Promise((resolve, reject) => {
706
+ sftp.stat(path, (error, attrs) => {
707
+ if (error !== undefined && error !== null) reject(error)
708
+ else resolve(attrs)
709
+ })
710
+ })
711
+ }
712
+
713
+ function openAsync(sftp: SFTPWrapper, path: string, flags: OpenMode = 'r'): Promise<Buffer> {
714
+ return new Promise((resolve, reject) => {
715
+ sftp.open(path, flags, (error, handle) => {
716
+ if (error !== undefined && error !== null) reject(error)
717
+ else resolve(handle)
718
+ })
719
+ })
720
+ }
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
+
918
+ function fstatAsync(sftp: SFTPWrapper, handle: Buffer): Promise<Stats> {
919
+ return new Promise((resolve, reject) => {
920
+ sftp.fstat(handle, (error, attrs) => {
921
+ if (error !== undefined && error !== null) reject(error)
922
+ else resolve(attrs)
923
+ })
924
+ })
925
+ }
926
+
927
+ function closeAsync(sftp: SFTPWrapper, handle: Buffer): Promise<void> {
928
+ return new Promise((resolve) => {
929
+ try {
930
+ sftp.close(handle, () => resolve())
931
+ } catch {
932
+ resolve()
933
+ }
934
+ })
935
+ }
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
+
952
+ /**
953
+ * Explain an `open` failure after lstat already saw a symlink: lstat reports
954
+ * the LINK's type, so "the thing at the end of the link is a directory" only
955
+ * shows up after the follow. `stat` follows the link and answers the question
956
+ * a raw SFTP status never does.
957
+ */
958
+ async function explainFollowFailure(sftp: SFTPWrapper, path: string, cause: unknown): Promise<Error | undefined> {
959
+ const code = (cause as { code?: number } | undefined)?.code
960
+ if (code !== SFTP_NO_SUCH_FILE && code !== SFTP_FAILURE) return undefined
961
+ let attrs: Stats
962
+ try {
963
+ attrs = await statAsync(sftp, path)
964
+ } catch (error) {
965
+ const followCode = (error as { code?: number } | undefined)?.code
966
+ return followCode === SFTP_NO_SUCH_FILE ? new Error(`no such file: ${path}`) : undefined
967
+ }
968
+ if (isDir(attrs.mode)) return new Error(`not a file: ${path} is a directory`)
969
+ return undefined
970
+ }
971
+
475
972
  /**
476
973
  * Read one window of a file.
477
974
  *
@@ -530,11 +1027,18 @@ function writeFileAsync(sftp: SFTPWrapper, path: string, data: Buffer): Promise<
530
1027
  }
531
1028
 
532
1029
  /**
533
- * Pipe a readable request body into one remote file.
1030
+ * Stream one readable request body into a new remote file with a bounded
1031
+ * parallel write window.
534
1032
  *
535
- * Destroys the write stream on any failure so a half-written upload cannot sit
536
- * on the wire after the response has already been sent, and counts bytes while
537
- * they pass so the caller can report and cap the transfer.
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.
538
1042
  *
539
1043
  * @param sftp - live SFTP session.
540
1044
  * @param path - absolute remote destination.
@@ -549,50 +1053,153 @@ function streamIntoFile(
549
1053
  maxBytes: number,
550
1054
  ): Promise<number> {
551
1055
  return new Promise<number>((resolve, reject) => {
552
- const out = sftp.createWriteStream(path)
553
- let bytes = 0
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
554
1066
  let settled = false
555
- const fail = (error: unknown): void => {
1067
+ let lastActivity = Date.now()
1068
+ let idle: ReturnType<typeof setInterval> | undefined
1069
+
1070
+ const finish = (error?: Error): void => {
556
1071
  if (settled) return
557
1072
  settled = true
1073
+ if (idle !== undefined) clearInterval(idle)
558
1074
  try {
559
- out.destroy()
1075
+ source.pause()
560
1076
  } catch {
561
- // Already closed: the original error is the one worth reporting.
1077
+ // Source already gone.
1078
+ }
1079
+ if (error === undefined) {
1080
+ resolve(received)
1081
+ return
562
1082
  }
563
- reject(error instanceof Error ? error : new Error(String(error)))
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)
564
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
1139
+ try {
1140
+ if (chunks.size + pendingWrites >= windowChunks * 2) source.pause()
1141
+ } catch {
1142
+ // Source already gone.
1143
+ }
1144
+ pump()
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
+
565
1157
  source.on('data', (chunk: Buffer) => {
566
- bytes += chunk.length
567
- if (bytes > maxBytes) {
568
- try {
569
- source.pause()
570
- } catch {
571
- // A destroyed source is exactly what we want next.
572
- }
573
- fail(new Error(`upload exceeds the ${formatBytes(maxBytes)} limit`))
1158
+ if (settled) return
1159
+ received += chunk.length
1160
+ if (received > maxBytes) {
1161
+ finish(new Error(`upload exceeds the ${formatBytes(maxBytes)} limit`))
1162
+ return
574
1163
  }
1164
+ lastActivity = Date.now()
1165
+ pushData(chunk)
575
1166
  })
576
- source.on('error', fail)
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)
1174
+ }
1175
+ maybeFinish()
1176
+ })
1177
+ source.on('error', (error: unknown) => finish(error instanceof Error ? error : new Error(String(error))))
577
1178
  // A client that gives up (the explorer's ✕, a closed tab) never sends 'end',
578
1179
  // and without this the promise below never settles: the SFTP session stays
579
1180
  // held, every later operation on that host queues behind it, and the next
580
1181
  // `stat` looks like a dead host (2026-10-20: an aborted 64 MB upload made the
581
1182
  // following drop sit at "正在读取拖放内容…" forever).
582
- const aborted = (): void => fail(new Error('upload aborted by the client'))
1183
+ const aborted = (): void => finish(new Error('upload aborted by the client'))
583
1184
  source.on('aborted', aborted)
584
1185
  source.on('close', () => {
585
1186
  // `complete` is false when the request ended before its body finished.
586
1187
  const complete = (source as unknown as { complete?: boolean }).complete
587
1188
  if (complete === false) aborted()
588
1189
  })
589
- out.on('error', fail)
590
- out.on('close', () => {
1190
+
1191
+ idle = setInterval(() => {
591
1192
  if (settled) return
592
- settled = true
593
- resolve(bytes)
594
- })
595
- source.pipe(out)
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))))
596
1203
  })
597
1204
  }
598
1205