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/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as pushPipeline, c as attachmentHeader, d as dshHome, f as ensurePrivateDir, i as probe, l as require_lib, m as storePath, o as seedHelperCache, p as keysDir, r as helperAvailability, s as RemoteFiles, t as RemoteWorlds, u as aliasRoot } from "./worlds-oj65Hic-.js";
1
+ import { a as pushPipeline, c as attachmentHeader, d as dshHome, f as ensurePrivateDir, i as probe, l as require_lib, m as storePath, o as seedHelperCache, p as keysDir, r as helperAvailability, s as RemoteFiles, t as RemoteWorlds, u as aliasRoot } from "./worlds-C6Xha1mQ.js";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, writeSync } from "node:fs";
4
4
  import { createHash, randomUUID } from "node:crypto";
@@ -346,6 +346,18 @@ const CHANNEL_LIMIT = 6;
346
346
  * readable error that tells the user to retry.
347
347
  */
348
348
  const CHANNEL_WAIT_MS = 3e4;
349
+ /**
350
+ * Idle time after which the shared BROWSE SFTP session is closed.
351
+ *
352
+ * Browsing is bursty (open a folder, look around, edit for a while, browse
353
+ * again), so a channel that survives only the burst costs one channel-open
354
+ * round trip per burst and saves one per request inside it. Two minutes covers
355
+ * the burst without keeping a channel slot parked for a five-minute pause. The
356
+ * slot it holds is the one a per-request session took, so peak channel usage
357
+ * against the server's MaxSessions does not change; the parked-slot trade-off
358
+ * is spelled out in withBrowseSftp's docstring.
359
+ */
360
+ const BROWSE_IDLE_MS = 120 * 1e3;
349
361
  var RemotePool = class {
350
362
  store;
351
363
  conns = /* @__PURE__ */ new Map();
@@ -355,11 +367,14 @@ var RemotePool = class {
355
367
  setsidProbes = /* @__PURE__ */ new Map();
356
368
  /** Per-alias channel slots and the queue waiting for one (see acquireSlot). */
357
369
  slots = /* @__PURE__ */ new Map();
370
+ /** Per-alias BROWSE SFTP session (see withBrowseSftp). */
371
+ browsed = /* @__PURE__ */ new Map();
358
372
  constructor(store) {
359
373
  this.store = store;
360
374
  }
361
375
  /** Drop one pooled connection (call after host update/delete). */
362
376
  drop(alias) {
377
+ this.evictBrowse(alias);
363
378
  const pooled = this.conns.get(alias);
364
379
  this.setsidProbes.delete(alias);
365
380
  if (pooled === void 0) return;
@@ -686,12 +701,7 @@ var RemotePool = class {
686
701
  }
687
702
  this.hold(alias);
688
703
  try {
689
- const sftp = await withDeadline(new Promise((resolve, reject) => {
690
- conn.sftp((error, session) => {
691
- if (error !== void 0 && error !== null) reject(error);
692
- else resolve(session);
693
- });
694
- }), SFTP_OP_TIMEOUT_MS, `SFTP session open timed out after ${SFTP_OP_TIMEOUT_MS / 1e3}s`);
704
+ const sftp = await this.openSession(conn);
695
705
  try {
696
706
  const limit = opts.timeoutMs ?? SFTP_OP_TIMEOUT_MS;
697
707
  if (limit <= 0) return await fn(sftp);
@@ -706,6 +716,111 @@ var RemotePool = class {
706
716
  this.releaseSlot(alias);
707
717
  }
708
718
  }
719
+ /**
720
+ * Run one bulk-transfer callback with a dedicated SFTP session, plus extra
721
+ * channel windows on demand (`addChannel`).
722
+ *
723
+ * Why extra channels: ssh2 (Channel.js `MAX_WINDOW`) and OpenSSH cap ONE SSH
724
+ * channel's window at 2 MiB, so a single channel can never hold 8 MiB of READs
725
+ * in flight however much concurrency the caller asks for; the rest queue
726
+ * client-side. Each extra session is another 2 MiB window. Measured against a
727
+ * real host (96 MiB file, 256 KiB chunks, same total concurrency):
728
+ * 1 channel 28.6 MiB/s, 2 channels 46.1, 4 channels 51.3 — two channels take
729
+ * most of the gain, four cost twice the channels for little more. Uploads
730
+ * showed no such gain (server-side write bound: 46.0 → 50.4 MiB/s), so only
731
+ * downloads spread out.
732
+ *
733
+ * `addChannel` is best-effort and late on purpose: a small download must not
734
+ * pay for a second channel, so the caller opens one only after it has the
735
+ * size. It never queues for a channel slot (a 30 s wait would stall a body that
736
+ * is already streaming) and a late call after the callback settled is a no-op.
737
+ * Every session opened here is closed, and every slot/hold released, when the
738
+ * callback settles — including a partially successful `addChannel`.
739
+ *
740
+ * There is no wall-clock deadline of its own: streaming is progress-bounded by
741
+ * the caller, and the caller also bounds the one-shot SFTP calls it makes
742
+ * around the stream (metadata phase, optional channel opens), because nothing
743
+ * there produces progress to watch.
744
+ */
745
+ async withTransferSftp(alias, fn) {
746
+ const sessions = [];
747
+ let slots = 0;
748
+ let holds = 0;
749
+ /** Set when the callback settles: a late `addChannel` must not leak resources. */
750
+ let closed = false;
751
+ let conn;
752
+ try {
753
+ await this.acquireSlot(alias);
754
+ slots += 1;
755
+ conn = await this.acquire(alias);
756
+ this.hold(alias);
757
+ holds += 1;
758
+ sessions.push(await this.openSession(conn));
759
+ const addChannel = async () => {
760
+ if (closed) return void 0;
761
+ if (!this.tryAcquireSlot(alias)) return void 0;
762
+ slots += 1;
763
+ this.hold(alias);
764
+ holds += 1;
765
+ try {
766
+ const extra = await this.openSession(conn);
767
+ if (closed) {
768
+ try {
769
+ extra.end();
770
+ } catch {}
771
+ return;
772
+ }
773
+ sessions.push(extra);
774
+ return extra;
775
+ } catch {
776
+ return;
777
+ }
778
+ };
779
+ return await fn(sessions[0], addChannel);
780
+ } finally {
781
+ closed = true;
782
+ for (const session of sessions) try {
783
+ session.end();
784
+ } catch {}
785
+ for (let i = 0; i < holds; i += 1) this.release(alias);
786
+ for (let i = 0; i < slots; i += 1) this.releaseSlot(alias);
787
+ }
788
+ }
789
+ /**
790
+ * Run one callback on this alias's long-lived BROWSE SFTP session.
791
+ *
792
+ * Why: every list/stat/read used to open its own SFTP session, which is a
793
+ * whole channel-open round trip BEFORE the operation's own round trip. A single
794
+ * folder open is one list plus a stat per entry the explorer probes, and the
795
+ * panel's revision refresh re-lists every open directory, so that open/close
796
+ * churn sat directly on the click-to-pixels path. The session is shared by
797
+ * every browse request for the alias; ssh2 multiplexes concurrent requests
798
+ * over one channel by packet id (the same request map fastGet/fastPut use).
799
+ *
800
+ * Only read-only browse operations use it (`RemoteFiles.list/stat/read`):
801
+ * writes, uploads and downloads keep their own short-lived session, so a
802
+ * mutation never inherits a channel that a previous request may have left in
803
+ * an odd state.
804
+ *
805
+ * The session holds one channel slot and one connection hold while it exists,
806
+ * which is what a per-request session took too, so peak channel usage against
807
+ * the server's MaxSessions does not change. The trade-off is that the slot
808
+ * stays PARKED for up to `BROWSE_IDLE_MS` after the last request: the extras a
809
+ * bulk transfer asks for use `tryAcquireSlot`, so they never wait on it.
810
+ */
811
+ async withBrowseSftp(alias, fn, opts = {}) {
812
+ const lease = await this.leaseBrowse(alias);
813
+ const limit = opts.timeoutMs ?? SFTP_OP_TIMEOUT_MS;
814
+ try {
815
+ if (limit <= 0) return await fn(lease.sftp);
816
+ return await withDeadline(fn(lease.sftp), limit, `SFTP operation on ${alias} timed out after ${limit / 1e3}s`);
817
+ } catch (error) {
818
+ if (error instanceof DeadlineError) lease.state.stale = true;
819
+ throw error;
820
+ } finally {
821
+ this.touchBrowse(alias, lease.state);
822
+ }
823
+ }
709
824
  /** Upload one local file to an absolute remote path (parallel fastPut). */
710
825
  async putFile(alias, localPath, remotePath) {
711
826
  await this.withSftp(alias, async (sftp) => {
@@ -730,15 +845,164 @@ var RemotePool = class {
730
845
  timer.unref?.();
731
846
  };
732
847
  arm();
733
- sftp.fastPut(localPath, remotePath, { step: () => {
734
- arm();
735
- } }, (error) => {
848
+ sftp.fastPut(localPath, remotePath, {
849
+ concurrency: 64,
850
+ chunkSize: 256 * 1024,
851
+ step: () => {
852
+ arm();
853
+ }
854
+ }, (error) => {
736
855
  finish(error === void 0 || error === null ? void 0 : new Error(error.message));
737
856
  });
738
857
  });
739
858
  }, { timeoutMs: 0 });
740
859
  }
741
860
  /**
861
+ * Open one SFTP session under its own deadline.
862
+ *
863
+ * ssh2 has no channel-open timeout: a server that never answers leaves this
864
+ * promise pending forever, which pins the connection's hold count and blocks
865
+ * idle re-arming (the "SSH looks dead" symptom) while the HTTP request hangs.
866
+ */
867
+ openSession(conn) {
868
+ return withDeadline(new Promise((resolve, reject) => {
869
+ conn.sftp((error, session) => {
870
+ if (error !== void 0 && error !== null) reject(error);
871
+ else resolve(session);
872
+ });
873
+ }), SFTP_OP_TIMEOUT_MS, `SFTP session open timed out after ${SFTP_OP_TIMEOUT_MS / 1e3}s`);
874
+ }
875
+ /**
876
+ * Take the browse channel for one operation (open it on first use).
877
+ *
878
+ * The returned lease counts as one in-flight operation; the caller's `finally`
879
+ * calls touchBrowse(). An open failure takes neither a slot nor a hold, so a
880
+ * failed host does not leave the pool's accounting skewed.
881
+ */
882
+ async leaseBrowse(alias) {
883
+ const state = this.browseState(alias);
884
+ if (state.stale) {
885
+ this.evictBrowse(alias, state);
886
+ return this.leaseBrowse(alias);
887
+ }
888
+ if (state.idle !== void 0) {
889
+ clearTimeout(state.idle);
890
+ state.idle = void 0;
891
+ }
892
+ if (state.session !== void 0) {
893
+ state.active += 1;
894
+ return {
895
+ state,
896
+ sftp: state.session
897
+ };
898
+ }
899
+ if (state.opening === void 0) state.opening = this.openBrowse(alias, state);
900
+ const opening = state.opening;
901
+ try {
902
+ const sftp = await opening;
903
+ state.active += 1;
904
+ return {
905
+ state,
906
+ sftp
907
+ };
908
+ } finally {
909
+ if (state.opening === opening) state.opening = void 0;
910
+ }
911
+ }
912
+ /**
913
+ * Open the browse session: a channel slot + a connection hold + the SFTP
914
+ * session itself, all released together by evictBrowse().
915
+ */
916
+ async openBrowse(alias, state) {
917
+ await this.acquireSlot(alias);
918
+ let conn;
919
+ try {
920
+ conn = await this.acquire(alias);
921
+ } catch (error) {
922
+ this.releaseSlot(alias);
923
+ throw error;
924
+ }
925
+ this.hold(alias);
926
+ state.leased = true;
927
+ try {
928
+ const sftp = await this.openSession(conn);
929
+ if (this.browsed.get(alias) !== state || !state.leased) {
930
+ try {
931
+ sftp.end();
932
+ } catch {}
933
+ throw new Error(`host ${alias} was disconnected while opening the browse session`);
934
+ }
935
+ state.session = sftp;
936
+ sftp.on("close", () => {
937
+ if (state.session !== sftp) return;
938
+ state.session = void 0;
939
+ this.evictBrowse(alias, state);
940
+ });
941
+ return sftp;
942
+ } catch (error) {
943
+ this.evictBrowse(alias, state);
944
+ throw error;
945
+ }
946
+ }
947
+ /** One completed browse operation: idle-close the channel when it is unused. */
948
+ touchBrowse(alias, state) {
949
+ if (state.active > 0) state.active -= 1;
950
+ if (state.active > 0) return;
951
+ if (state.stale) {
952
+ this.evictBrowse(alias, state);
953
+ return;
954
+ }
955
+ if (state.idle !== void 0) clearTimeout(state.idle);
956
+ state.idle = setTimeout(() => {
957
+ state.idle = void 0;
958
+ if (state.active === 0) this.evictBrowse(alias, state);
959
+ }, BROWSE_IDLE_MS);
960
+ state.idle.unref?.();
961
+ }
962
+ /**
963
+ * Close the browse session and give its slot and hold back. Idempotent; every
964
+ * way the session can end (idle, open failure, channel close, connection drop)
965
+ * goes through here so the accounting cannot drift.
966
+ *
967
+ * `expected` ties the eviction to ONE session object: a timer or a channel
968
+ * `close` event that fires after the state was already replaced must not close
969
+ * its successor. Callers that end the connection (drop/dispose) omit it.
970
+ */
971
+ evictBrowse(alias, expected) {
972
+ const state = this.browsed.get(alias);
973
+ if (state === void 0) return;
974
+ if (expected !== void 0 && state !== expected) return;
975
+ this.browsed.delete(alias);
976
+ if (state.idle !== void 0) {
977
+ clearTimeout(state.idle);
978
+ state.idle = void 0;
979
+ }
980
+ const session = state.session;
981
+ state.session = void 0;
982
+ if (session !== void 0) try {
983
+ session.end();
984
+ } catch {}
985
+ if (state.leased) {
986
+ state.leased = false;
987
+ this.release(alias);
988
+ this.releaseSlot(alias);
989
+ }
990
+ }
991
+ browseState(alias) {
992
+ const existing = this.browsed.get(alias);
993
+ if (existing !== void 0) return existing;
994
+ const created = {
995
+ session: void 0,
996
+ opening: void 0,
997
+ active: 0,
998
+ stale: false,
999
+ leased: false,
1000
+ idle: void 0
1001
+ };
1002
+ this.browsed.set(alias, created);
1003
+ return created;
1004
+ }
1005
+ /**
742
1006
  * Take one channel slot for `alias`, waiting FIFO when the limit is reached.
743
1007
  * The wait is bounded: waiting forever behind a peer that never finishes is
744
1008
  * worse than a readable error naming the cause and what to do about it.
@@ -767,6 +1031,22 @@ var RemotePool = class {
767
1031
  state.queue.push(waiter);
768
1032
  });
769
1033
  }
1034
+ /**
1035
+ * Take one channel slot only if one is free RIGHT NOW; never queue.
1036
+ *
1037
+ * Optional work (a bulk transfer's second channel) must not wait behind
1038
+ * `CHANNEL_WAIT_MS` of other operations: a "best effort" extra channel that
1039
+ * delays the body of an already-streaming download by 30 s is worse than the
1040
+ * one channel the transfer would have used anyway. A queued waiter also blocks
1041
+ * the attempt on purpose — it has been waiting longer, and stealing its slot
1042
+ * would just move the wait.
1043
+ */
1044
+ tryAcquireSlot(alias) {
1045
+ const state = this.slotState(alias);
1046
+ if (state.active >= CHANNEL_LIMIT || state.queue.length > 0) return false;
1047
+ state.active += 1;
1048
+ return true;
1049
+ }
770
1050
  /** Give a slot back, handing it straight to the longest-waiting operation. */
771
1051
  releaseSlot(alias) {
772
1052
  const state = this.slots.get(alias);
@@ -1022,12 +1302,20 @@ function warnDetached(alias) {
1022
1302
  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)`);
1023
1303
  }
1024
1304
  /**
1305
+ * An operation that ran out of its wall-clock budget.
1306
+ *
1307
+ * Tagged on purpose: callers have to tell "the remote never answered" from a real
1308
+ * remote failure (a missing path must not cost the session), and matching on the
1309
+ * message text would silently stop working the moment the template changed.
1310
+ */
1311
+ var DeadlineError = class extends Error {};
1312
+ /**
1025
1313
  * Reject when `promise` has not settled within `ms`, so a stalled remote
1026
1314
  * callback cannot keep a session (and its pooled connection) alive forever.
1027
1315
  */
1028
1316
  function withDeadline(promise, ms, message) {
1029
1317
  return new Promise((resolve, reject) => {
1030
- const timer = setTimeout(() => reject(new Error(message)), ms);
1318
+ const timer = setTimeout(() => reject(new DeadlineError(message)), ms);
1031
1319
  timer.unref?.();
1032
1320
  promise.then((value) => {
1033
1321
  clearTimeout(timer);
@@ -1,4 +1,4 @@
1
- import { n as isWindowsAbsolute, u as aliasRoot } from "./worlds-oj65Hic-.js";
1
+ import { n as isWindowsAbsolute, u as aliasRoot } from "./worlds-C6Xha1mQ.js";
2
2
  import { FileSystem, FsError } from "@deepseek-ai/dsh-fs";
3
3
  //#region src/p2/router-fs.ts
4
4
  /**
@@ -11,7 +11,7 @@
11
11
  * them here keeps the check meaningful in both directions: every entry must
12
12
  * exist in both dictionaries, and nothing else may be unreferenced.
13
13
  */
14
- export declare const DYNAMIC_KEYS: readonly ["common.loading", "editor.saving", "editor.unsaved", "editor.saved", "scm.hunkStaged", "scm.hunkUnstaged", "scm.hunkReverted", "history.details", "history.content", "history.diff", "downloads.running"];
14
+ export declare const DYNAMIC_KEYS: readonly ["common.loading", "editor.saving", "editor.unsaved", "editor.saved", "scm.hunkStaged", "scm.hunkUnstaged", "scm.hunkReverted", "history.details", "history.content", "history.diff", "downloads.running", "downloads.indeterminate", "downloads.sizeUnknown"];
15
15
  export type Lang = 'zh' | 'en';
16
16
  export declare function detectLang(): Lang;
17
17
  export declare function makeT(lang: Lang): (key: string) => string;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * In-flight directory-listing requests, shared by the explorer's hover prefetch
3
+ * and the reads that follow it.
4
+ *
5
+ * Two rules the tree depends on:
6
+ * - JOIN only a request that started at the SAME revision. A listing read after
7
+ * a write must never be answered by a request issued before it, or pre-write
8
+ * rows paint as if they were final (a hover prefetch starts, a write lands,
9
+ * the click follows and joins the request that predates the write).
10
+ * - PAINT in request order. If a newer request supersedes an older one for the
11
+ * same directory, the older answer may still arrive; it must not overwrite the
12
+ * one the caller asked for.
13
+ *
14
+ * The cache itself stays in the component: this module only owns "which listing
15
+ * requests are on the wire and which answer may be stored".
16
+ */
17
+ import type { RemoteFileEntry } from '../protocol.ts';
18
+ export declare class ListingRequests {
19
+ private readonly keyOf;
20
+ private readonly load;
21
+ private readonly store;
22
+ private readonly inFlight;
23
+ /** Newest request per key: only its answer may be stored. */
24
+ private readonly newest;
25
+ private sequence;
26
+ /**
27
+ * @param keyOf - cache key for one directory (host alias + absolute path).
28
+ * @param load - performs the listing.
29
+ * @param store - applies a listing whose request is still the newest for its
30
+ * key; the component writes it into the listing cache.
31
+ */
32
+ constructor(keyOf: (dir: string) => string, load: (dir: string) => Promise<RemoteFileEntry[]>, store: (key: string, entries: RemoteFileEntry[]) => void);
33
+ /**
34
+ * List one directory, or join the request a hover prefetch already started.
35
+ *
36
+ * @param dir - absolute remote directory.
37
+ * @param revision - the explorer revision this read is meant to reflect. A
38
+ * request issued at another revision is never joined.
39
+ * @param fresh - start a new request even when one is in flight (a
40
+ * revalidation after a write, where joining the older read would be wrong).
41
+ */
42
+ request(dir: string, revision: number, fresh?: boolean): Promise<RemoteFileEntry[]>;
43
+ /** Whether a listing for `dir` is on the wire. */
44
+ busy(dir: string): boolean;
45
+ }
@@ -43,6 +43,8 @@ export declare class RemotePool {
43
43
  private readonly setsidProbes;
44
44
  /** Per-alias channel slots and the queue waiting for one (see acquireSlot). */
45
45
  private readonly slots;
46
+ /** Per-alias BROWSE SFTP session (see withBrowseSftp). */
47
+ private readonly browsed;
46
48
  constructor(store: RemoteStore);
47
49
  /** Drop one pooled connection (call after host update/delete). */
48
50
  drop(alias: string): void;
@@ -73,14 +75,109 @@ export declare class RemotePool {
73
75
  execChannel(alias: string, command: string): Promise<ClientChannel>;
74
76
  /** Run one callback with a fresh SFTP session (closed afterwards). */
75
77
  withSftp<T>(alias: string, fn: (sftp: SFTPWrapper) => Promise<T>, opts?: SftpOptions): Promise<T>;
78
+ /**
79
+ * Run one bulk-transfer callback with a dedicated SFTP session, plus extra
80
+ * channel windows on demand (`addChannel`).
81
+ *
82
+ * Why extra channels: ssh2 (Channel.js `MAX_WINDOW`) and OpenSSH cap ONE SSH
83
+ * channel's window at 2 MiB, so a single channel can never hold 8 MiB of READs
84
+ * in flight however much concurrency the caller asks for; the rest queue
85
+ * client-side. Each extra session is another 2 MiB window. Measured against a
86
+ * real host (96 MiB file, 256 KiB chunks, same total concurrency):
87
+ * 1 channel 28.6 MiB/s, 2 channels 46.1, 4 channels 51.3 — two channels take
88
+ * most of the gain, four cost twice the channels for little more. Uploads
89
+ * showed no such gain (server-side write bound: 46.0 → 50.4 MiB/s), so only
90
+ * downloads spread out.
91
+ *
92
+ * `addChannel` is best-effort and late on purpose: a small download must not
93
+ * pay for a second channel, so the caller opens one only after it has the
94
+ * size. It never queues for a channel slot (a 30 s wait would stall a body that
95
+ * is already streaming) and a late call after the callback settled is a no-op.
96
+ * Every session opened here is closed, and every slot/hold released, when the
97
+ * callback settles — including a partially successful `addChannel`.
98
+ *
99
+ * There is no wall-clock deadline of its own: streaming is progress-bounded by
100
+ * the caller, and the caller also bounds the one-shot SFTP calls it makes
101
+ * around the stream (metadata phase, optional channel opens), because nothing
102
+ * there produces progress to watch.
103
+ */
104
+ withTransferSftp<T>(alias: string, fn: (sftp: SFTPWrapper, addChannel: () => Promise<SFTPWrapper | undefined>) => Promise<T>): Promise<T>;
105
+ /**
106
+ * Run one callback on this alias's long-lived BROWSE SFTP session.
107
+ *
108
+ * Why: every list/stat/read used to open its own SFTP session, which is a
109
+ * whole channel-open round trip BEFORE the operation's own round trip. A single
110
+ * folder open is one list plus a stat per entry the explorer probes, and the
111
+ * panel's revision refresh re-lists every open directory, so that open/close
112
+ * churn sat directly on the click-to-pixels path. The session is shared by
113
+ * every browse request for the alias; ssh2 multiplexes concurrent requests
114
+ * over one channel by packet id (the same request map fastGet/fastPut use).
115
+ *
116
+ * Only read-only browse operations use it (`RemoteFiles.list/stat/read`):
117
+ * writes, uploads and downloads keep their own short-lived session, so a
118
+ * mutation never inherits a channel that a previous request may have left in
119
+ * an odd state.
120
+ *
121
+ * The session holds one channel slot and one connection hold while it exists,
122
+ * which is what a per-request session took too, so peak channel usage against
123
+ * the server's MaxSessions does not change. The trade-off is that the slot
124
+ * stays PARKED for up to `BROWSE_IDLE_MS` after the last request: the extras a
125
+ * bulk transfer asks for use `tryAcquireSlot`, so they never wait on it.
126
+ */
127
+ withBrowseSftp<T>(alias: string, fn: (sftp: SFTPWrapper) => Promise<T>, opts?: SftpOptions): Promise<T>;
76
128
  /** Upload one local file to an absolute remote path (parallel fastPut). */
77
129
  putFile(alias: string, localPath: string, remotePath: string): Promise<void>;
130
+ /**
131
+ * Open one SFTP session under its own deadline.
132
+ *
133
+ * ssh2 has no channel-open timeout: a server that never answers leaves this
134
+ * promise pending forever, which pins the connection's hold count and blocks
135
+ * idle re-arming (the "SSH looks dead" symptom) while the HTTP request hangs.
136
+ */
137
+ private openSession;
138
+ /**
139
+ * Take the browse channel for one operation (open it on first use).
140
+ *
141
+ * The returned lease counts as one in-flight operation; the caller's `finally`
142
+ * calls touchBrowse(). An open failure takes neither a slot nor a hold, so a
143
+ * failed host does not leave the pool's accounting skewed.
144
+ */
145
+ private leaseBrowse;
146
+ /**
147
+ * Open the browse session: a channel slot + a connection hold + the SFTP
148
+ * session itself, all released together by evictBrowse().
149
+ */
150
+ private openBrowse;
151
+ /** One completed browse operation: idle-close the channel when it is unused. */
152
+ private touchBrowse;
153
+ /**
154
+ * Close the browse session and give its slot and hold back. Idempotent; every
155
+ * way the session can end (idle, open failure, channel close, connection drop)
156
+ * goes through here so the accounting cannot drift.
157
+ *
158
+ * `expected` ties the eviction to ONE session object: a timer or a channel
159
+ * `close` event that fires after the state was already replaced must not close
160
+ * its successor. Callers that end the connection (drop/dispose) omit it.
161
+ */
162
+ private evictBrowse;
163
+ private browseState;
78
164
  /**
79
165
  * Take one channel slot for `alias`, waiting FIFO when the limit is reached.
80
166
  * The wait is bounded: waiting forever behind a peer that never finishes is
81
167
  * worse than a readable error naming the cause and what to do about it.
82
168
  */
83
169
  private acquireSlot;
170
+ /**
171
+ * Take one channel slot only if one is free RIGHT NOW; never queue.
172
+ *
173
+ * Optional work (a bulk transfer's second channel) must not wait behind
174
+ * `CHANNEL_WAIT_MS` of other operations: a "best effort" extra channel that
175
+ * delays the body of an already-streaming download by 30 s is worse than the
176
+ * one channel the transfer would have used anyway. A queued waiter also blocks
177
+ * the attempt on purpose — it has been waiting longer, and stealing its slot
178
+ * would just move the wait.
179
+ */
180
+ private tryAcquireSlot;
84
181
  /** Give a slot back, handing it straight to the longest-waiting operation. */
85
182
  private releaseSlot;
86
183
  private slotState;
@@ -112,3 +209,12 @@ export declare class RemotePool {
112
209
  private acquire;
113
210
  private dial;
114
211
  }
212
+ /**
213
+ * An operation that ran out of its wall-clock budget.
214
+ *
215
+ * Tagged on purpose: callers have to tell "the remote never answered" from a real
216
+ * remote failure (a missing path must not cost the session), and matching on the
217
+ * message text would silently stop working the moment the template changed.
218
+ */
219
+ export declare class DeadlineError extends Error {
220
+ }
@@ -23,6 +23,41 @@ export declare const UPLOAD_MAX_BYTES: number;
23
23
  * so progress is the bound — any chunk resets this clock.
24
24
  */
25
25
  export declare const DOWNLOAD_IDLE_MS = 60000;
26
+ /** Upload progress bound (no body bytes and no write acknowledgements). */
27
+ export declare const UPLOAD_IDLE_MS = 60000;
28
+ /**
29
+ * Parallel-transfer shape, shared by download and upload.
30
+ *
31
+ * A single `createReadStream`/`createWriteStream` keeps exactly ONE SFTP request
32
+ * in flight per round trip; measured against a real host that cost about 8x
33
+ * (4.4 MiB/s single stream vs 35.4 MiB/s for ssh2's pipelined fastGet on the
34
+ * same link). 256 KiB chunks with 32 in-flight requests (8 MiB of app-side
35
+ * buffers) are the same tuning ssh2's fastGet/fastPut use and bound the
36
+ * per-transfer memory; on top of that ssh2 holds up to one 2 MiB channel window
37
+ * per channel in flight, so a two-channel download peaks around 12 MiB.
38
+ */
39
+ export declare const TRANSFER_CHUNK_BYTES: number;
40
+ /** In-flight chunk window (also the per-transfer APP-side memory bound: 8 MiB). */
41
+ export declare const TRANSFER_CONCURRENCY = 32;
42
+ /**
43
+ * Channels a big download spreads its READ window over.
44
+ *
45
+ * ssh2 (Channel.js `MAX_WINDOW`) and OpenSSH cap ONE SSH channel's window at
46
+ * 2 MiB, so a single channel can never keep more than that many bytes of READs
47
+ * outstanding however large the requested concurrency is. Measured against a
48
+ * real host on a 96 MiB file with the same total concurrency (256 KiB chunks):
49
+ * 1 channel 28.6 MiB/s, 2 channels 46.1, 4 channels 51.3 — two channels take
50
+ * most of the gain at a quarter of the cost of four. Uploads showed no such
51
+ * gain (46.0 → 50.4 MiB/s: the server's write path is the bound), so uploads
52
+ * stay on one channel.
53
+ */
54
+ export declare const TRANSFER_SESSIONS = 2;
55
+ /**
56
+ * Below this size a second channel is not worth its channel-open round trip and
57
+ * channel slot: the file is only a handful of READ windows long, so the extra
58
+ * channel would mostly be opened and closed.
59
+ */
60
+ export declare const MULTI_CHANNEL_MIN_BYTES: number;
26
61
  /** Assert an absolute POSIX remote path and return its normalized form. */
27
62
  export declare function remotePath(path: string): string;
28
63
  /**