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/src/pool.ts CHANGED
@@ -89,6 +89,19 @@ const CHANNEL_LIMIT = 6
89
89
  */
90
90
  const CHANNEL_WAIT_MS = 30_000
91
91
 
92
+ /**
93
+ * Idle time after which the shared BROWSE SFTP session is closed.
94
+ *
95
+ * Browsing is bursty (open a folder, look around, edit for a while, browse
96
+ * again), so a channel that survives only the burst costs one channel-open
97
+ * round trip per burst and saves one per request inside it. Two minutes covers
98
+ * the burst without keeping a channel slot parked for a five-minute pause. The
99
+ * slot it holds is the one a per-request session took, so peak channel usage
100
+ * against the server's MaxSessions does not change; the parked-slot trade-off
101
+ * is spelled out in withBrowseSftp's docstring.
102
+ */
103
+ const BROWSE_IDLE_MS = 2 * 60 * 1000
104
+
92
105
  interface Pooled {
93
106
  conn: Client
94
107
  timer: ReturnType<typeof setTimeout> | undefined
@@ -98,6 +111,25 @@ interface Pooled {
98
111
  held: number
99
112
  }
100
113
 
114
+ /**
115
+ * The per-alias BROWSE SFTP session (see `withBrowseSftp`).
116
+ *
117
+ * `active` counts operations in flight; the idle timer only runs at zero.
118
+ * `stale` means an operation hit its deadline, so the channel must not be
119
+ * reused once the current operations drain — a session whose request never
120
+ * answered is not worth trusting, and closing it under a peer still using it
121
+ * would fail that peer instead.
122
+ */
123
+ interface BrowseChannel {
124
+ session: SFTPWrapper | undefined
125
+ opening: Promise<SFTPWrapper> | undefined
126
+ active: number
127
+ stale: boolean
128
+ /** This channel holds one channel slot and one connection hold. */
129
+ leased: boolean
130
+ idle: ReturnType<typeof setTimeout> | undefined
131
+ }
132
+
101
133
  export interface ExecOptions {
102
134
  timeoutMs?: number
103
135
  /**
@@ -158,11 +190,16 @@ export class RemotePool {
158
190
  private readonly setsidProbes = new Map<string, Promise<boolean>>()
159
191
  /** Per-alias channel slots and the queue waiting for one (see acquireSlot). */
160
192
  private readonly slots = new Map<string, Slots>()
193
+ /** Per-alias BROWSE SFTP session (see withBrowseSftp). */
194
+ private readonly browsed = new Map<string, BrowseChannel>()
161
195
 
162
196
  constructor(private readonly store: RemoteStore) {}
163
197
 
164
198
  /** Drop one pooled connection (call after host update/delete). */
165
199
  drop(alias: string): void {
200
+ // Order matters: the open browse channel must give its slot and hold back
201
+ // while the pooled entry still exists, or the release would be a no-op.
202
+ this.evictBrowse(alias)
166
203
  const pooled = this.conns.get(alias)
167
204
  // The host entry can change under an alias, so the capability answer goes
168
205
  // with the connection; the next exec probes again.
@@ -485,21 +522,7 @@ export class RemotePool {
485
522
  // idle timer armed by a concurrent release() could evict it mid-call.
486
523
  this.hold(alias)
487
524
  try {
488
- // The session open needs its own deadline. It used to sit outside the
489
- // `withDeadline` below, and ssh2 has no channel-open timeout — a server
490
- // that never answers leaves this promise pending forever, which pins
491
- // `held` above zero and therefore blocks idle re-arming (the "SSH looks
492
- // dead" symptom) while the HTTP request hangs.
493
- const sftp = await withDeadline(
494
- new Promise<SFTPWrapper>((resolve, reject) => {
495
- conn.sftp((error, session) => {
496
- if (error !== undefined && error !== null) reject(error)
497
- else resolve(session)
498
- })
499
- }),
500
- SFTP_OP_TIMEOUT_MS,
501
- `SFTP session open timed out after ${SFTP_OP_TIMEOUT_MS / 1000}s`,
502
- )
525
+ const sftp = await this.openSession(conn)
503
526
  try {
504
527
  const limit = opts.timeoutMs ?? SFTP_OP_TIMEOUT_MS
505
528
  if (limit <= 0) return await fn(sftp)
@@ -517,6 +540,138 @@ export class RemotePool {
517
540
  }
518
541
  }
519
542
 
543
+ /**
544
+ * Run one bulk-transfer callback with a dedicated SFTP session, plus extra
545
+ * channel windows on demand (`addChannel`).
546
+ *
547
+ * Why extra channels: ssh2 (Channel.js `MAX_WINDOW`) and OpenSSH cap ONE SSH
548
+ * channel's window at 2 MiB, so a single channel can never hold 8 MiB of READs
549
+ * in flight however much concurrency the caller asks for; the rest queue
550
+ * client-side. Each extra session is another 2 MiB window. Measured against a
551
+ * real host (96 MiB file, 256 KiB chunks, same total concurrency):
552
+ * 1 channel 28.6 MiB/s, 2 channels 46.1, 4 channels 51.3 — two channels take
553
+ * most of the gain, four cost twice the channels for little more. Uploads
554
+ * showed no such gain (server-side write bound: 46.0 → 50.4 MiB/s), so only
555
+ * downloads spread out.
556
+ *
557
+ * `addChannel` is best-effort and late on purpose: a small download must not
558
+ * pay for a second channel, so the caller opens one only after it has the
559
+ * size. It never queues for a channel slot (a 30 s wait would stall a body that
560
+ * is already streaming) and a late call after the callback settled is a no-op.
561
+ * Every session opened here is closed, and every slot/hold released, when the
562
+ * callback settles — including a partially successful `addChannel`.
563
+ *
564
+ * There is no wall-clock deadline of its own: streaming is progress-bounded by
565
+ * the caller, and the caller also bounds the one-shot SFTP calls it makes
566
+ * around the stream (metadata phase, optional channel opens), because nothing
567
+ * there produces progress to watch.
568
+ */
569
+ async withTransferSftp<T>(
570
+ alias: string,
571
+ fn: (sftp: SFTPWrapper, addChannel: () => Promise<SFTPWrapper | undefined>) => Promise<T>,
572
+ ): Promise<T> {
573
+ const sessions: SFTPWrapper[] = []
574
+ let slots = 0
575
+ let holds = 0
576
+ /** Set when the callback settles: a late `addChannel` must not leak resources. */
577
+ let closed = false
578
+ let conn: Client
579
+ try {
580
+ // An SFTP session IS a channel, so each one takes a slot: the ceiling this
581
+ // protects is the server's MaxSessions, not our own bookkeeping.
582
+ await this.acquireSlot(alias)
583
+ slots += 1
584
+ conn = await this.acquire(alias)
585
+ // Hold BEFORE the first await (same reason as withSftp).
586
+ this.hold(alias)
587
+ holds += 1
588
+ sessions.push(await this.openSession(conn))
589
+ const addChannel = async (): Promise<SFTPWrapper | undefined> => {
590
+ if (closed) return undefined
591
+ // NEVER queue for an optional channel: a busy host would otherwise delay
592
+ // the body of a download that is already streaming by up to
593
+ // CHANNEL_WAIT_MS, which is worse than one channel.
594
+ if (!this.tryAcquireSlot(alias)) return undefined
595
+ slots += 1
596
+ this.hold(alias)
597
+ holds += 1
598
+ try {
599
+ const extra = await this.openSession(conn)
600
+ if (closed) {
601
+ // The transfer settled while this channel was opening; the finally
602
+ // already returned its slot and hold, so close it here.
603
+ try {
604
+ extra.end()
605
+ } catch {
606
+ // Already gone.
607
+ }
608
+ return undefined
609
+ }
610
+ sessions.push(extra)
611
+ return extra
612
+ } catch {
613
+ // The slot and hold this attempt took are released by the finally; one
614
+ // channel still streams the file, so this is not a failure.
615
+ return undefined
616
+ }
617
+ }
618
+ return await fn(sessions[0] as SFTPWrapper, addChannel)
619
+ } finally {
620
+ closed = true
621
+ for (const session of sessions) {
622
+ try {
623
+ session.end()
624
+ } catch {
625
+ // Ignore close errors.
626
+ }
627
+ }
628
+ for (let i = 0; i < holds; i += 1) this.release(alias)
629
+ for (let i = 0; i < slots; i += 1) this.releaseSlot(alias)
630
+ }
631
+ }
632
+
633
+ /**
634
+ * Run one callback on this alias's long-lived BROWSE SFTP session.
635
+ *
636
+ * Why: every list/stat/read used to open its own SFTP session, which is a
637
+ * whole channel-open round trip BEFORE the operation's own round trip. A single
638
+ * folder open is one list plus a stat per entry the explorer probes, and the
639
+ * panel's revision refresh re-lists every open directory, so that open/close
640
+ * churn sat directly on the click-to-pixels path. The session is shared by
641
+ * every browse request for the alias; ssh2 multiplexes concurrent requests
642
+ * over one channel by packet id (the same request map fastGet/fastPut use).
643
+ *
644
+ * Only read-only browse operations use it (`RemoteFiles.list/stat/read`):
645
+ * writes, uploads and downloads keep their own short-lived session, so a
646
+ * mutation never inherits a channel that a previous request may have left in
647
+ * an odd state.
648
+ *
649
+ * The session holds one channel slot and one connection hold while it exists,
650
+ * which is what a per-request session took too, so peak channel usage against
651
+ * the server's MaxSessions does not change. The trade-off is that the slot
652
+ * stays PARKED for up to `BROWSE_IDLE_MS` after the last request: the extras a
653
+ * bulk transfer asks for use `tryAcquireSlot`, so they never wait on it.
654
+ */
655
+ async withBrowseSftp<T>(alias: string, fn: (sftp: SFTPWrapper) => Promise<T>, opts: SftpOptions = {}): Promise<T> {
656
+ const lease = await this.leaseBrowse(alias)
657
+ const limit = opts.timeoutMs ?? SFTP_OP_TIMEOUT_MS
658
+ try {
659
+ if (limit <= 0) return await fn(lease.sftp)
660
+ return await withDeadline(fn(lease.sftp), limit, `SFTP operation on ${alias} timed out after ${limit / 1000}s`)
661
+ } catch (error) {
662
+ // A request that never answered stays queued inside ssh2, and this session
663
+ // was already handed to other browse operations. Mark it stale: the next
664
+ // lease retires it (leaseBrowse), and operations sharing it fail fast
665
+ // instead of waiting out their own deadlines.
666
+ if (error instanceof DeadlineError) {
667
+ lease.state.stale = true
668
+ }
669
+ throw error
670
+ } finally {
671
+ this.touchBrowse(alias, lease.state)
672
+ }
673
+ }
674
+
520
675
  /** Upload one local file to an absolute remote path (parallel fastPut). */
521
676
  async putFile(alias: string, localPath: string, remotePath: string): Promise<void> {
522
677
  // A bulk upload must NOT run under the per-operation deadline: the helper
@@ -550,7 +705,15 @@ export class RemotePool {
550
705
  timer.unref?.()
551
706
  }
552
707
  arm()
553
- sftp.fastPut(localPath, remotePath, { step: () => { arm() } }, (error) => {
708
+ // ssh2's fastPut defaults to 64 concurrent WRITEs but only 32 KiB per
709
+ // chunk; 256 KiB chunks amortise the two round trips per write (request
710
+ // + status) and are what the sibling Tauri tool measured fastest for the
711
+ // same library. Progress still arms the idle bound on every step.
712
+ sftp.fastPut(localPath, remotePath, {
713
+ concurrency: 64,
714
+ chunkSize: 256 * 1024,
715
+ step: () => { arm() },
716
+ }, (error) => {
554
717
  finish(error === undefined || error === null ? undefined : new Error(error.message))
555
718
  })
556
719
  })
@@ -560,6 +723,177 @@ export class RemotePool {
560
723
 
561
724
  // ------------------------------------------------------------ internals
562
725
 
726
+ /**
727
+ * Open one SFTP session under its own deadline.
728
+ *
729
+ * ssh2 has no channel-open timeout: a server that never answers leaves this
730
+ * promise pending forever, which pins the connection's hold count and blocks
731
+ * idle re-arming (the "SSH looks dead" symptom) while the HTTP request hangs.
732
+ */
733
+ private openSession(conn: Client): Promise<SFTPWrapper> {
734
+ return withDeadline(
735
+ new Promise<SFTPWrapper>((resolve, reject) => {
736
+ conn.sftp((error, session) => {
737
+ if (error !== undefined && error !== null) reject(error)
738
+ else resolve(session)
739
+ })
740
+ }),
741
+ SFTP_OP_TIMEOUT_MS,
742
+ `SFTP session open timed out after ${SFTP_OP_TIMEOUT_MS / 1000}s`,
743
+ )
744
+ }
745
+
746
+ /**
747
+ * Take the browse channel for one operation (open it on first use).
748
+ *
749
+ * The returned lease counts as one in-flight operation; the caller's `finally`
750
+ * calls touchBrowse(). An open failure takes neither a slot nor a hold, so a
751
+ * failed host does not leave the pool's accounting skewed.
752
+ */
753
+ private async leaseBrowse(alias: string): Promise<{ state: BrowseChannel; sftp: SFTPWrapper }> {
754
+ const state = this.browseState(alias)
755
+ // A session whose request hit its deadline is not trusted any more: retire it
756
+ // NOW instead of handing it to the request that just arrived. Waiting for the
757
+ // operations on it to drain looked safer, but any continuous browse traffic
758
+ // (a hover prefetch every few seconds is enough) keeps `active` above zero and
759
+ // postpones the retirement forever, so every subsequent list/stat/read paid
760
+ // the full 60 s deadline. Peers sharing the retired session fail fast (the
761
+ // close settles their requests) instead of waiting each of them out.
762
+ if (state.stale) {
763
+ this.evictBrowse(alias, state)
764
+ return this.leaseBrowse(alias)
765
+ }
766
+ if (state.idle !== undefined) {
767
+ clearTimeout(state.idle)
768
+ state.idle = undefined
769
+ }
770
+ if (state.session !== undefined) {
771
+ state.active += 1
772
+ return { state, sftp: state.session }
773
+ }
774
+ if (state.opening === undefined) state.opening = this.openBrowse(alias, state)
775
+ const opening = state.opening
776
+ try {
777
+ const sftp = await opening
778
+ state.active += 1
779
+ return { state, sftp }
780
+ } finally {
781
+ // Several callers may await the same open; clearing the shared field is
782
+ // safe because each of them holds its own reference to the promise, and
783
+ // the successful path has already stored `session` by now.
784
+ if (state.opening === opening) state.opening = undefined
785
+ }
786
+ }
787
+
788
+ /**
789
+ * Open the browse session: a channel slot + a connection hold + the SFTP
790
+ * session itself, all released together by evictBrowse().
791
+ */
792
+ private async openBrowse(alias: string, state: BrowseChannel): Promise<SFTPWrapper> {
793
+ await this.acquireSlot(alias)
794
+ let conn: Client
795
+ try {
796
+ conn = await this.acquire(alias)
797
+ } catch (error) {
798
+ this.releaseSlot(alias)
799
+ throw error
800
+ }
801
+ // Hold before the first await, for the same reason withSftp does: a
802
+ // concurrent release() must not arm idle eviction mid-open.
803
+ this.hold(alias)
804
+ state.leased = true
805
+ try {
806
+ const sftp = await this.openSession(conn)
807
+ // The host can be dropped while the session is opening: the slot and hold
808
+ // are already returned and nobody would ever close this channel, so refuse
809
+ // it instead of handing out a session on a dead connection.
810
+ if (this.browsed.get(alias) !== state || !state.leased) {
811
+ try {
812
+ sftp.end()
813
+ } catch {
814
+ // Already gone.
815
+ }
816
+ throw new Error(`host ${alias} was disconnected while opening the browse session`)
817
+ }
818
+ state.session = sftp
819
+ // The channel can die on its own (remote restart, network blip). Clearing
820
+ // bookkeeping here means the next browse operation reopens instead of
821
+ // talking to a dead wrapper; a close we initiated is ignored because the
822
+ // session has already been detached by evictBrowse().
823
+ sftp.on('close', () => {
824
+ if (state.session !== sftp) return
825
+ state.session = undefined
826
+ this.evictBrowse(alias, state)
827
+ })
828
+ return sftp
829
+ } catch (error) {
830
+ this.evictBrowse(alias, state)
831
+ throw error
832
+ }
833
+ }
834
+
835
+ /** One completed browse operation: idle-close the channel when it is unused. */
836
+ private touchBrowse(alias: string, state: BrowseChannel): void {
837
+ if (state.active > 0) state.active -= 1
838
+ if (state.active > 0) return
839
+ if (state.stale) {
840
+ // The operation that timed out has settled, so nobody else is using the
841
+ // channel: drop it now and let the next request open a fresh session.
842
+ this.evictBrowse(alias, state)
843
+ return
844
+ }
845
+ if (state.idle !== undefined) clearTimeout(state.idle)
846
+ state.idle = setTimeout(() => {
847
+ state.idle = undefined
848
+ // The state may have been evicted (and replaced by a NEW session) while
849
+ // this timer was pending — a tied eviction would close that successor.
850
+ if (state.active === 0) this.evictBrowse(alias, state)
851
+ }, BROWSE_IDLE_MS)
852
+ state.idle.unref?.()
853
+ }
854
+
855
+ /**
856
+ * Close the browse session and give its slot and hold back. Idempotent; every
857
+ * way the session can end (idle, open failure, channel close, connection drop)
858
+ * goes through here so the accounting cannot drift.
859
+ *
860
+ * `expected` ties the eviction to ONE session object: a timer or a channel
861
+ * `close` event that fires after the state was already replaced must not close
862
+ * its successor. Callers that end the connection (drop/dispose) omit it.
863
+ */
864
+ private evictBrowse(alias: string, expected?: BrowseChannel): void {
865
+ const state = this.browsed.get(alias)
866
+ if (state === undefined) return
867
+ if (expected !== undefined && state !== expected) return
868
+ this.browsed.delete(alias)
869
+ if (state.idle !== undefined) {
870
+ clearTimeout(state.idle)
871
+ state.idle = undefined
872
+ }
873
+ const session = state.session
874
+ state.session = undefined
875
+ if (session !== undefined) {
876
+ try {
877
+ session.end()
878
+ } catch {
879
+ // Already gone.
880
+ }
881
+ }
882
+ if (state.leased) {
883
+ state.leased = false
884
+ this.release(alias)
885
+ this.releaseSlot(alias)
886
+ }
887
+ }
888
+
889
+ private browseState(alias: string): BrowseChannel {
890
+ const existing = this.browsed.get(alias)
891
+ if (existing !== undefined) return existing
892
+ const created: BrowseChannel = { session: undefined, opening: undefined, active: 0, stale: false, leased: false, idle: undefined }
893
+ this.browsed.set(alias, created)
894
+ return created
895
+ }
896
+
563
897
  /**
564
898
  * Take one channel slot for `alias`, waiting FIFO when the limit is reached.
565
899
  * The wait is bounded: waiting forever behind a peer that never finishes is
@@ -591,6 +925,23 @@ export class RemotePool {
591
925
  })
592
926
  }
593
927
 
928
+ /**
929
+ * Take one channel slot only if one is free RIGHT NOW; never queue.
930
+ *
931
+ * Optional work (a bulk transfer's second channel) must not wait behind
932
+ * `CHANNEL_WAIT_MS` of other operations: a "best effort" extra channel that
933
+ * delays the body of an already-streaming download by 30 s is worse than the
934
+ * one channel the transfer would have used anyway. A queued waiter also blocks
935
+ * the attempt on purpose — it has been waiting longer, and stealing its slot
936
+ * would just move the wait.
937
+ */
938
+ private tryAcquireSlot(alias: string): boolean {
939
+ const state = this.slotState(alias)
940
+ if (state.active >= CHANNEL_LIMIT || state.queue.length > 0) return false
941
+ state.active += 1
942
+ return true
943
+ }
944
+
594
945
  /** Give a slot back, handing it straight to the longest-waiting operation. */
595
946
  private releaseSlot(alias: string): void {
596
947
  const state = this.slots.get(alias)
@@ -869,13 +1220,22 @@ function warnDetached(alias: string): void {
869
1220
  console.warn(`[dsh-remote-vs] exec timed out on ${alias}: the channel is closed but the remote command may still be running (no killable process group)`)
870
1221
  }
871
1222
 
1223
+ /**
1224
+ * An operation that ran out of its wall-clock budget.
1225
+ *
1226
+ * Tagged on purpose: callers have to tell "the remote never answered" from a real
1227
+ * remote failure (a missing path must not cost the session), and matching on the
1228
+ * message text would silently stop working the moment the template changed.
1229
+ */
1230
+ export class DeadlineError extends Error {}
1231
+
872
1232
  /**
873
1233
  * Reject when `promise` has not settled within `ms`, so a stalled remote
874
1234
  * callback cannot keep a session (and its pooled connection) alive forever.
875
1235
  */
876
1236
  function withDeadline<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
877
1237
  return new Promise<T>((resolve, reject) => {
878
- const timer = setTimeout(() => reject(new Error(message)), ms)
1238
+ const timer = setTimeout(() => reject(new DeadlineError(message)), ms)
879
1239
  timer.unref?.()
880
1240
  promise.then(
881
1241
  (value) => {