dsh-remote-vs 0.28.0 → 0.30.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 +63 -7
- package/README.md +51 -7
- package/lib/client.js +393 -112
- package/lib/index.js +2271 -160
- package/lib/p2-router-fs.js +1 -1
- package/lib/types/changes/recorder.d.ts +65 -10
- package/lib/types/changes/status.d.ts +48 -3
- package/lib/types/client/ConnectionsSection.d.ts +73 -0
- package/lib/types/client/HostsView.d.ts +139 -2
- package/lib/types/client/api.d.ts +65 -2
- package/lib/types/client/connection.d.ts +28 -1
- package/lib/types/client/scm/actions.d.ts +25 -1
- package/lib/types/forward.d.ts +11 -1
- package/lib/types/p2/helper-rpc.d.ts +48 -0
- package/lib/types/p2/worlds.d.ts +28 -0
- package/lib/types/pool.d.ts +337 -8
- package/lib/types/protocol.d.ts +218 -0
- package/lib/types/proxy.d.ts +136 -0
- package/lib/types/store.d.ts +81 -1
- package/lib/types/tools.d.ts +3 -0
- package/lib/{worlds-RG8K5eom.js → worlds-CRRZMZhg.js} +85 -6
- package/package.json +1 -1
- package/src/changes/recorder.ts +151 -15
- package/src/changes/status.ts +59 -4
- package/src/client/ConnectionStatus.tsx +19 -5
- package/src/client/ConnectionsSection.tsx +359 -0
- package/src/client/HostsView.tsx +552 -11
- package/src/client/MonitorView.tsx +14 -0
- package/src/client/PortsView.tsx +16 -0
- package/src/client/SettingsHosts.tsx +132 -6
- package/src/client/api.ts +102 -4
- package/src/client/connection.ts +76 -2
- package/src/client/i18n.ts +152 -2
- package/src/client/scm/actions.ts +63 -12
- package/src/client/vsc/vsc.css +281 -0
- package/src/forward.ts +38 -2
- package/src/importers.ts +125 -13
- package/src/keygen.ts +8 -1
- package/src/p2/helper-rpc.ts +73 -5
- package/src/p2/worlds.ts +48 -0
- package/src/pool.ts +1120 -100
- package/src/protocol.ts +228 -0
- package/src/proxy.ts +673 -0
- package/src/routes.ts +139 -5
- package/src/store.ts +335 -0
- package/src/tools.ts +47 -2
package/src/pool.ts
CHANGED
|
@@ -9,10 +9,20 @@
|
|
|
9
9
|
import { createHash } from 'node:crypto'
|
|
10
10
|
import { readFileSync } from 'node:fs'
|
|
11
11
|
import { StringDecoder } from 'node:string_decoder'
|
|
12
|
+
import type { Duplex } from 'node:stream'
|
|
12
13
|
import { Client, type ClientChannel, type SFTPWrapper } from 'ssh2'
|
|
13
|
-
import type { RemoteStore } from './store.ts'
|
|
14
|
+
import type { RemoteStore, ResolvedProxy } from './store.ts'
|
|
15
|
+
import { openProxySocket, ProxyError, type ProxyConfig, type ProxyFailure } from './proxy.ts'
|
|
14
16
|
import { DeadlineError } from './timeouts.ts'
|
|
15
|
-
import type {
|
|
17
|
+
import type {
|
|
18
|
+
EgressInfo,
|
|
19
|
+
RemoteConnectionStatus,
|
|
20
|
+
RemoteExecResult,
|
|
21
|
+
RemoteHostEntry,
|
|
22
|
+
RemoteHostPoolStats,
|
|
23
|
+
RemotePoolLane,
|
|
24
|
+
RemotePoolSlots,
|
|
25
|
+
} from './protocol.ts'
|
|
16
26
|
|
|
17
27
|
/**
|
|
18
28
|
* The budget-out type lives in `timeouts.ts` (both halves need it); re-exported
|
|
@@ -23,6 +33,62 @@ export { DeadlineError }
|
|
|
23
33
|
/** Idle time after which a pooled connection is closed. */
|
|
24
34
|
const IDLE_MS = 30 * 60 * 1000
|
|
25
35
|
|
|
36
|
+
/**
|
|
37
|
+
* How long a port forward waits for its DEDICATED connection before falling back.
|
|
38
|
+
*
|
|
39
|
+
* The dedicated connection is an optimization, so it must never become the reason
|
|
40
|
+
* a local socket waits: a server that silently DROPS the extra connection (a very
|
|
41
|
+
* common `MaxStartups` symptom) would otherwise cost the whole connect watchdog
|
|
42
|
+
* (45s) per forward channel, with the user staring at a hanging page. Three
|
|
43
|
+
* seconds is plenty for a second handshake to a host that is already reachable
|
|
44
|
+
* (the shared connection is up by definition); past that, use the shared one and
|
|
45
|
+
* let the abandoned dial finish in the background.
|
|
46
|
+
*
|
|
47
|
+
* Override with DSH_REMOTE_VS_FORWARD_BUDGET_MS (milliseconds, >= 10) so the gate
|
|
48
|
+
* does not spend three seconds per case.
|
|
49
|
+
*/
|
|
50
|
+
const FORWARD_DEDICATED_BUDGET_MS = (() => {
|
|
51
|
+
const raw = Number(process.env.DSH_REMOTE_VS_FORWARD_BUDGET_MS)
|
|
52
|
+
return Number.isFinite(raw) && raw >= 10 ? raw : 3_000
|
|
53
|
+
})()
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* How long a refused/timed-out dedicated forward connection is skipped per alias.
|
|
57
|
+
*
|
|
58
|
+
* A browser opens several forward channels per page; retrying the same refused
|
|
59
|
+
* handshake for every one of them is exactly the waiting we just removed. One
|
|
60
|
+
* minute covers the burst; `drop(alias)` (host edited/deleted) and a successful
|
|
61
|
+
* dedicated connection clear it immediately.
|
|
62
|
+
*/
|
|
63
|
+
const FORWARD_DEDICATED_BLOCK_MS = 60_000
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* How long a file operation waits for its DEDICATED SFTP connection before
|
|
67
|
+
* falling back to the shared one.
|
|
68
|
+
*
|
|
69
|
+
* Same argument as {@link FORWARD_DEDICATED_BUDGET_MS}, and it binds harder
|
|
70
|
+
* here: browsing fires one request per folder open (plus a stat per entry), so a
|
|
71
|
+
* server that silently DROPS the extra connection would otherwise stall the
|
|
72
|
+
* explorer for the whole connect watchdog on EVERY click. The dedicated
|
|
73
|
+
* connection is an optimization; it must never be what the user waits on.
|
|
74
|
+
*
|
|
75
|
+
* Override with DSH_REMOTE_VS_SFTP_BUDGET_MS (milliseconds, >= 10).
|
|
76
|
+
*/
|
|
77
|
+
const SFTP_DEDICATED_BUDGET_MS = (() => {
|
|
78
|
+
const raw = Number(process.env.DSH_REMOTE_VS_SFTP_BUDGET_MS)
|
|
79
|
+
return Number.isFinite(raw) && raw >= 10 ? raw : 3_000
|
|
80
|
+
})()
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* How long a refused dedicated SFTP connection is skipped per alias.
|
|
84
|
+
*
|
|
85
|
+
* Without it the fallback would be re-dialed by every browse request — the exact
|
|
86
|
+
* waiting the dedicated budget above just removed. One minute covers a burst of
|
|
87
|
+
* browsing; `drop(alias)` (host edited/deleted) and a successful dedicated
|
|
88
|
+
* connection clear it immediately.
|
|
89
|
+
*/
|
|
90
|
+
const SFTP_DEDICATED_BLOCK_MS = 60_000
|
|
91
|
+
|
|
26
92
|
/**
|
|
27
93
|
* Connection establishment timeout, including authentication.
|
|
28
94
|
*
|
|
@@ -102,21 +168,120 @@ const CONTROL_TIMEOUT_MS = 15_000
|
|
|
102
168
|
const GROUP_KILL_GRACE_MS = 3_000
|
|
103
169
|
|
|
104
170
|
/**
|
|
105
|
-
* Concurrent channels the pool opens per alias
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
171
|
+
* Concurrent EXEC channels the pool opens per alias on the SHARED connection.
|
|
172
|
+
*
|
|
173
|
+
* The server's own `MaxSessions` (10 on the hosts this was measured against) is
|
|
174
|
+
* the real ceiling, and a channel past it is refused HARD — ssh2 reports
|
|
175
|
+
* "administratively prohibited" and nobody retries, so the operation fails in a
|
|
176
|
+
* way that looks like a broken host. Queueing is the readable alternative, which
|
|
177
|
+
* is why every counted channel kind goes through a budget instead.
|
|
178
|
+
*
|
|
179
|
+
* The counting is now honest — every `conn.exec` channel takes a slot:
|
|
180
|
+
* - `runExec` (every ordinary command) and `execChannel` (the subprocess
|
|
181
|
+
* runtime's long-lived channels, see `p2/ssh-proc.ts`), both on this budget;
|
|
182
|
+
* - network verbs ({@link NET_CHANNEL_LIMIT}) and git commands
|
|
183
|
+
* ({@link GIT_CHANNEL_LIMIT}), on their own budgets on the same connection.
|
|
184
|
+
* PTY terminals, port forwards and SFTP sessions ride their OWN connections, so
|
|
185
|
+
* they cannot exhaust this allowance at all.
|
|
186
|
+
*
|
|
187
|
+
* **The arithmetic (shared connection, measured `MaxSessions` 10)**:
|
|
188
|
+
* counted channels are exec 4 + network 2 + git 3 = **9**. The tenth session is
|
|
189
|
+
* deliberately left free for the only channels that are still NOT counted: the
|
|
190
|
+
* pool's own housekeeping (`bare` — the one-shot `setsid` capability probe and
|
|
191
|
+
* the group kill). Those are transient, but they must never be refused, because
|
|
192
|
+
* a refused probe silently degrades the timeout path and a refused kill leaks a
|
|
193
|
+
* remote process. So 9 + 1 is a BOUNDED DESIGN, not spare headroom: a tenth
|
|
194
|
+
* counted channel would put the sum at 10 only as long as nothing transient ever
|
|
195
|
+
* fires — an assumption the pool cannot make.
|
|
196
|
+
*
|
|
197
|
+
* **Why 4 and not more** — this is a deliberate split of the same nine, not a
|
|
198
|
+
* reduction of it. The field call: "several workspaces / repositories scanning at
|
|
199
|
+
* once" is the common shape, while "an agent running many exec commands at once"
|
|
200
|
+
* is rarer, so one slot moved from exec to the git lane (git 2 → 3) and the
|
|
201
|
+
* network lane stayed at two (push and pull must not serialize). The known cost:
|
|
202
|
+
* exec concurrency drops from five to four, so an agent's background commands plus
|
|
203
|
+
* a monitor sample plus the process panel plus the listening-port enumeration can
|
|
204
|
+
* fill it and the fifth waits — bounded at 30 s with a readable message, and
|
|
205
|
+
* visible as `Shared 4/4 · N queued` in the monitor. If exec turns out to be the
|
|
206
|
+
* real bottleneck, move the slot back; the total must stay 9.
|
|
207
|
+
*
|
|
208
|
+
* The budget is PER CONNECTION, and the pool holds up to four connections per
|
|
209
|
+
* alias, so the other classes (PTY/forward/SFTP) keep their own ceilings.
|
|
210
|
+
*/
|
|
211
|
+
const CHANNEL_LIMIT = 4
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Concurrent SFTP sessions on the DEDICATED file connection.
|
|
215
|
+
*
|
|
216
|
+
* Deliberately its own number rather than {@link CHANNEL_LIMIT}: the shared
|
|
217
|
+
* connection's ceiling is tight because three budgets share it with the transient
|
|
218
|
+
* `bare` probe/kill, while the file connection carries nothing but SFTP sessions
|
|
219
|
+
* and has the whole `MaxSessions` (10) to itself. Six is what the transfer
|
|
220
|
+
* measurement landed on (the extra channel windows a download may open), and it is
|
|
221
|
+
* unchanged by the exec/network/git rebalance.
|
|
222
|
+
*/
|
|
223
|
+
const SFTP_CHANNEL_LIMIT = 6
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Concurrent NETWORK verbs (`git fetch` / `pull` / `push` / `sync`) per alias.
|
|
227
|
+
*
|
|
228
|
+
* They ride the SHARED connection (no fifth link: the traffic is not the problem,
|
|
229
|
+
* the HOLD TIME is) but get their own budget, because their timeout is measured
|
|
230
|
+
* in minutes — 20 by default. On the exec budget one stuck push pinned one of the
|
|
231
|
+
* exec slots for the whole budget, and a couple of them filled the table: status
|
|
232
|
+
* refreshes, the process panel, the monitor and every agent tool then queued 30 s
|
|
233
|
+
* and failed with "host is busy". With a separate table that can no longer happen.
|
|
234
|
+
*
|
|
235
|
+
* Two is enough for the real concurrency (a push and a pull side by side; `sync`
|
|
236
|
+
* runs its steps sequentially). A third verb waits, and says so in its own words
|
|
237
|
+
* (see `budgetOf`). The full per-connection arithmetic lives on
|
|
238
|
+
* {@link CHANNEL_LIMIT}: exec 4 + network 2 + git 3 = 9 counted, with one session
|
|
239
|
+
* left free for the transient `bare` probe/kill.
|
|
240
|
+
*/
|
|
241
|
+
const NET_CHANNEL_LIMIT = 2
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Concurrent GIT commands (`git status` / `diff` / `log` reads AND the local
|
|
245
|
+
* writes — commit, stage, discard, branch create/rename/delete, merge) per alias.
|
|
246
|
+
*
|
|
247
|
+
* Same argument as the network lane, from the other end of the timeout scale: a
|
|
248
|
+
* big repository's `git status` alone is allowed 300 s by default
|
|
249
|
+
* (`DEFAULT_GIT_TIMEOUT_MS`, up to 30 minutes), and every git command used to
|
|
250
|
+
* hold one of the exec slots for its whole run — while the monitor, the process
|
|
251
|
+
* panel, the ledger's own next scan and every agent tool queued behind it and
|
|
252
|
+
* answered "host is busy" after 30 s.
|
|
253
|
+
*
|
|
254
|
+
* NOTE the lane is "git commands", not "repository reads": the SCM panel sends its
|
|
255
|
+
* local writes (`git commit`, `git add`, `git restore`, branch verbs) here too,
|
|
256
|
+
* because they are git commands with a git timeout. They are fast, and they no
|
|
257
|
+
* longer occupy a slot out of the same few the monitor and the agent tools use.
|
|
258
|
+
*
|
|
259
|
+
* **Why three** (shared connection, measured `MaxSessions` 10):
|
|
260
|
+
* - counted channels: exec 4 + network 2 + git 3 = 9, plus the one session kept
|
|
261
|
+
* free for the transient `bare` probe/kill — see {@link CHANNEL_LIMIT};
|
|
262
|
+
* - three covers the load the field actually shows: several open workspaces or
|
|
263
|
+
* repositories scanning at once (each runs a tracked status AND, outside the
|
|
264
|
+
* client queue, an untracked walk), which is more common than an agent running
|
|
265
|
+
* many commands at the same instant — hence the extra slot came out of exec;
|
|
266
|
+
* - four would make 10 counted with the probe reserve gone; the surplus channel
|
|
267
|
+
* past `MaxSessions` is refused HARD by sshd ("administratively prohibited", no
|
|
268
|
+
* retry) — the exact failure these budgets exist to replace with a bounded
|
|
269
|
+
* queue. Raising this further means taking the slot from exec again.
|
|
111
270
|
*/
|
|
112
|
-
const
|
|
271
|
+
const GIT_CHANNEL_LIMIT = 3
|
|
113
272
|
|
|
114
273
|
/**
|
|
115
274
|
* How long an operation waits for a channel slot before failing. Bounded on
|
|
116
275
|
* purpose: queueing forever behind a peer that never finishes is worse than a
|
|
117
276
|
* readable error that tells the user to retry.
|
|
277
|
+
*
|
|
278
|
+
* Override with DSH_REMOTE_VS_CHANNEL_WAIT_MS (milliseconds, >= 10) so a gate can
|
|
279
|
+
* assert the "busy" message without waiting the production 30 s.
|
|
118
280
|
*/
|
|
119
|
-
const CHANNEL_WAIT_MS =
|
|
281
|
+
const CHANNEL_WAIT_MS = (() => {
|
|
282
|
+
const raw = Number(process.env.DSH_REMOTE_VS_CHANNEL_WAIT_MS)
|
|
283
|
+
return Number.isFinite(raw) && raw >= 10 ? raw : 30_000
|
|
284
|
+
})()
|
|
120
285
|
|
|
121
286
|
/**
|
|
122
287
|
* Idle time after which the shared BROWSE SFTP session is closed.
|
|
@@ -138,6 +303,22 @@ interface Pooled {
|
|
|
138
303
|
connecting: Promise<Client> | undefined
|
|
139
304
|
/** Live users (channels/sessions); idle eviction only fires at zero. */
|
|
140
305
|
held: number
|
|
306
|
+
/**
|
|
307
|
+
* SSH channels currently open on this connection (see `countChannel`).
|
|
308
|
+
*
|
|
309
|
+
* Tracked separately from `held` on purpose: the two happen to agree for the
|
|
310
|
+
* dedicated PTY/forward/SFTP connections (one hold per channel), but they do
|
|
311
|
+
* NOT for the shared one — a jump tunnel pins the jump host twice for its
|
|
312
|
+
* single channel — and `held` would otherwise be reported as a channel count
|
|
313
|
+
* that is simply wrong. Reported by `stats()`.
|
|
314
|
+
*/
|
|
315
|
+
channels: number
|
|
316
|
+
/**
|
|
317
|
+
* The route THIS connection was opened through (set on a successful dial,
|
|
318
|
+
* cleared with the entry). It answers "is this really going through the jump
|
|
319
|
+
* host?" with evidence from the live link instead of the stored config.
|
|
320
|
+
*/
|
|
321
|
+
egress?: EgressInfo
|
|
141
322
|
}
|
|
142
323
|
|
|
143
324
|
/**
|
|
@@ -156,9 +337,26 @@ interface BrowseChannel {
|
|
|
156
337
|
stale: boolean
|
|
157
338
|
/** This channel holds one channel slot and one connection hold. */
|
|
158
339
|
leased: boolean
|
|
340
|
+
/**
|
|
341
|
+
* Which connection class the lease sits on: the dedicated SFTP connection, or
|
|
342
|
+
* the shared one when its dial was refused (the fallback). The slot table and
|
|
343
|
+
* the hold map follow THIS, so a fallback session is accounted for on the
|
|
344
|
+
* shared connection it really rides — never on both.
|
|
345
|
+
*/
|
|
346
|
+
lane: SftpLane
|
|
159
347
|
idle: ReturnType<typeof setTimeout> | undefined
|
|
160
348
|
}
|
|
161
349
|
|
|
350
|
+
/**
|
|
351
|
+
* The two connection classes a file operation can ride.
|
|
352
|
+
*
|
|
353
|
+
* `sftp` is the dedicated connection (its own TCP link, its own channel budget);
|
|
354
|
+
* `shared` is the fallback everything used to ride. The distinction is
|
|
355
|
+
* load-bearing for accounting: hold, slot and health all depend on which one is
|
|
356
|
+
* really in use.
|
|
357
|
+
*/
|
|
358
|
+
type SftpLane = 'sftp' | 'shared'
|
|
359
|
+
|
|
162
360
|
/**
|
|
163
361
|
* Connection-level failures the status indicator must show.
|
|
164
362
|
*
|
|
@@ -209,6 +407,23 @@ export interface ExecOptions {
|
|
|
209
407
|
* recurse into the machinery that dispatched them.
|
|
210
408
|
*/
|
|
211
409
|
bare?: boolean
|
|
410
|
+
/**
|
|
411
|
+
* Which channel budget this command spends. Omitted means the shared exec
|
|
412
|
+
* budget — every caller that predates the split keeps that behaviour.
|
|
413
|
+
*
|
|
414
|
+
* `'network'` is for `git fetch/pull/push/sync`: those can hold a channel for
|
|
415
|
+
* the whole network timeout (20 minutes by default), so they get
|
|
416
|
+
* {@link NET_CHANNEL_LIMIT} slots of their own instead of eating the exec slots
|
|
417
|
+
* the rest of the app (status polls, monitor, agent tools) depends on.
|
|
418
|
+
*
|
|
419
|
+
* `'git'` is for GIT COMMANDS — the repository reads (`git status/diff/log`, the
|
|
420
|
+
* session ledger's scans) AND the local writes the SCM panel runs (`commit`,
|
|
421
|
+
* `stage`, `discard`, branch verbs, `merge`): a big tree's `git status` is
|
|
422
|
+
* allowed 300 s, so these get {@link GIT_CHANNEL_LIMIT} slots — otherwise one
|
|
423
|
+
* slow command parks an exec slot for minutes and the monitor/process panel/
|
|
424
|
+
* agent tools queue behind it.
|
|
425
|
+
*/
|
|
426
|
+
lane?: 'exec' | 'network' | 'git'
|
|
212
427
|
}
|
|
213
428
|
|
|
214
429
|
export interface ShellOptions {
|
|
@@ -216,6 +431,23 @@ export interface ShellOptions {
|
|
|
216
431
|
rows?: number
|
|
217
432
|
}
|
|
218
433
|
|
|
434
|
+
/**
|
|
435
|
+
* The transport one configured route hands to an ssh2 dial (see `openRoutedSocket`).
|
|
436
|
+
*
|
|
437
|
+
* `sock` is absent for a direct route, where ssh2 dials the target itself. When it
|
|
438
|
+
* IS present ssh2 must be given `{ sock }` and NOT `host`/`port`: supplying both
|
|
439
|
+
* lets ssh2 choose between "dial this host myself" and "ride the tunnel", and the
|
|
440
|
+
* choice is an implementation detail, not a feature.
|
|
441
|
+
*
|
|
442
|
+
* `release` is idempotent and is the OWNER's to call — a proxy socket has to be
|
|
443
|
+
* destroyed and a jump-host tunnel has to close its channel and give the jump
|
|
444
|
+
* host's hold back, or the next dial finds a pinned connection.
|
|
445
|
+
*/
|
|
446
|
+
export interface RoutedDial {
|
|
447
|
+
sock?: Duplex
|
|
448
|
+
release: () => void
|
|
449
|
+
}
|
|
450
|
+
|
|
219
451
|
export interface SftpOptions {
|
|
220
452
|
/**
|
|
221
453
|
* Wall-clock cap for the callback body. `0` disables it for an operation that
|
|
@@ -263,12 +495,94 @@ export class RemotePool {
|
|
|
263
495
|
* that refuses extra connections still gets a working terminal.
|
|
264
496
|
*/
|
|
265
497
|
private readonly shellConns = new Map<string, Pooled>()
|
|
498
|
+
/**
|
|
499
|
+
* Dedicated connections for `ssh -L` port forwards (one per alias).
|
|
500
|
+
*
|
|
501
|
+
* The other half of the same argument: a forwarded channel carries arbitrary
|
|
502
|
+
* TCP (a database, an SSH tunnel, a whole browser page), so it is long-lived
|
|
503
|
+
* and can move a lot of data. Multiplexed onto the shared connection it would
|
|
504
|
+
* queue ahead of exec/SFTP channels (SSH has no per-channel priority), and a
|
|
505
|
+
* remote service that stalls would hold the window `git status` needs. A
|
|
506
|
+
* terminal already gets its own connection (`shellConns`); forward traffic gets
|
|
507
|
+
* its own for exactly the same reason.
|
|
508
|
+
*
|
|
509
|
+
* Cost: one extra handshake per alias that actually receives a forwarded
|
|
510
|
+
* connection, plus one held TCP connection while any of its forward channels is
|
|
511
|
+
* open (the 30-minute idle eviction applies once the last one closes).
|
|
512
|
+
* `forwardOut` falls back to the shared connection when this one cannot be
|
|
513
|
+
* established (e.g. the server refuses extra connections), so a forward never
|
|
514
|
+
* stops working because of it — it only loses the isolation.
|
|
515
|
+
*/
|
|
516
|
+
private readonly forwardConns = new Map<string, Pooled>()
|
|
517
|
+
/**
|
|
518
|
+
* Dedicated connections for FILE operations (one per alias).
|
|
519
|
+
*
|
|
520
|
+
* The third instance of the same argument. Browse/read/write/upload/download
|
|
521
|
+
* used to ride the shared connection, which meant a `git status` burst or a
|
|
522
|
+
* long exec could sit in front of a directory refresh (SSH offers no
|
|
523
|
+
* per-channel priority), AND that the shared link's channel budget was shared
|
|
524
|
+
* with file I/O: a few in-flight git/search commands and the explorer could not
|
|
525
|
+
* open a channel at all. A file operation is exactly the traffic a user is
|
|
526
|
+
* watching (a folder must open, a save must land), so it gets its own
|
|
527
|
+
* connection and its own channel budget (`sftpSlots`).
|
|
528
|
+
*
|
|
529
|
+
* Cost: one extra handshake per alias that touches files, plus one held TCP
|
|
530
|
+
* connection while any of its channels is open (the 30-minute idle eviction
|
|
531
|
+
* applies once the last one ends). `acquireSftp` falls back to the
|
|
532
|
+
* shared connection when this one cannot be established — a host that refuses
|
|
533
|
+
* extra connections still serves files, it only loses the isolation.
|
|
534
|
+
*/
|
|
535
|
+
private readonly sftpConns = new Map<string, Pooled>()
|
|
536
|
+
/** Aliases whose dedicated-SFTP downgrade was already logged (once per alias). */
|
|
537
|
+
private readonly sftpFallbackNoted = new Set<string>()
|
|
538
|
+
/** alias -> timestamp until which the dedicated SFTP connection is skipped. */
|
|
539
|
+
private readonly sftpBlocked = new Map<string, number>()
|
|
540
|
+
/**
|
|
541
|
+
* Aliases whose file operations are DOWNGRADED right now (sticky until a
|
|
542
|
+
* dedicated connection succeeds again or the host is edited).
|
|
543
|
+
*
|
|
544
|
+
* Purely diagnostic: `stats()` reports it so the monitor page can say "these
|
|
545
|
+
* files are riding the shared connection" instead of leaving the user to
|
|
546
|
+
* wonder why a browse refresh still queues behind git.
|
|
547
|
+
*/
|
|
548
|
+
private readonly sftpFallback = new Set<string>()
|
|
549
|
+
/** Aliases whose dedicated-forward downgrade was already logged (once per alias). */
|
|
550
|
+
private readonly forwardFallbackNoted = new Set<string>()
|
|
551
|
+
/** alias -> timestamp until which the dedicated forward connection is skipped. */
|
|
552
|
+
private readonly forwardBlocked = new Map<string, number>()
|
|
266
553
|
/** TOFU fingerprints observed this process (alias -> sha256). */
|
|
267
554
|
private readonly hostKeys = new Map<string, string>()
|
|
268
555
|
/** Per-alias `setsid --wait` capability, probed once (see supportsSetsid). */
|
|
269
556
|
private readonly setsidProbes = new Map<string, Promise<boolean>>()
|
|
270
|
-
/**
|
|
557
|
+
/**
|
|
558
|
+
* Channel slots of the SHARED connection (see acquireSlot), and of the
|
|
559
|
+
* dedicated SFTP connection.
|
|
560
|
+
*
|
|
561
|
+
* Two tables because the budget is per connection (`MaxSessions` counts
|
|
562
|
+
* channels on one link): a fallback SFTP operation counts against the shared
|
|
563
|
+
* table — the connection it really rides — and never against both.
|
|
564
|
+
*/
|
|
271
565
|
private readonly slots = new Map<string, Slots>()
|
|
566
|
+
private readonly sftpSlots = new Map<string, Slots>()
|
|
567
|
+
/**
|
|
568
|
+
* Channel budget of the NETWORK verbs (see {@link NET_CHANNEL_LIMIT}).
|
|
569
|
+
*
|
|
570
|
+
* A third table on the SHARED connection: unlike the SFTP lane this is not about
|
|
571
|
+
* isolating bytes, it is about isolating TIME. A `git push` holds its channel
|
|
572
|
+
* for minutes, and the failure mode it caused — a full exec table, so every
|
|
573
|
+
* status refresh answered "host is busy" after 30 s — came from the two kinds
|
|
574
|
+
* sharing one ceiling.
|
|
575
|
+
*/
|
|
576
|
+
private readonly netSlots = new Map<string, Slots>()
|
|
577
|
+
/**
|
|
578
|
+
* Channel budget of the GIT COMMANDS (see {@link GIT_CHANNEL_LIMIT}).
|
|
579
|
+
*
|
|
580
|
+
* A fourth table on the SHARED connection, for the same reason as the network
|
|
581
|
+
* one — hold TIME, not traffic: a `git status` on a big tree may run for
|
|
582
|
+
* minutes, and a git command must not be the reason a monitor sample or an agent
|
|
583
|
+
* tool waits.
|
|
584
|
+
*/
|
|
585
|
+
private readonly gitSlots = new Map<string, Slots>()
|
|
272
586
|
/** Per-alias BROWSE SFTP session (see withBrowseSftp). */
|
|
273
587
|
private readonly browsed = new Map<string, BrowseChannel>()
|
|
274
588
|
/** Per-alias connection health for the browser's status chip (see status). */
|
|
@@ -284,16 +598,38 @@ export class RemotePool {
|
|
|
284
598
|
// The host entry can change under an alias, so the capability answer goes
|
|
285
599
|
// with the connection; the next exec probes again.
|
|
286
600
|
this.setsidProbes.delete(alias)
|
|
287
|
-
//
|
|
601
|
+
// All four connections belong to the host: an edit/removal must end all.
|
|
288
602
|
// (A transient error on ONE of them uses `evictFrom` for that map only, so
|
|
289
|
-
// a shared-connection blip does not take live terminals down with it.)
|
|
603
|
+
// a shared-connection blip does not take live terminals/forwards down with it.)
|
|
290
604
|
this.evictFrom(this.conns, alias)
|
|
291
605
|
this.evictFrom(this.shellConns, alias)
|
|
606
|
+
this.evictFrom(this.forwardConns, alias)
|
|
607
|
+
this.evictFrom(this.sftpConns, alias)
|
|
608
|
+
// Verdicts about the OLD connection do not survive the host: an edited host
|
|
609
|
+
// (now allowed, or with a new address) must be retried and may be reported.
|
|
610
|
+
this.forwardBlocked.delete(alias)
|
|
611
|
+
this.forwardFallbackNoted.delete(alias)
|
|
612
|
+
this.sftpBlocked.delete(alias)
|
|
613
|
+
this.sftpFallbackNoted.delete(alias)
|
|
614
|
+
this.sftpFallback.delete(alias)
|
|
615
|
+
// The old connection's channel budget goes with it too: this call ends the
|
|
616
|
+
// connections, so their in-flight operations can only fail, and a budget row
|
|
617
|
+
// left behind would make the NEXT connection start out looking busy.
|
|
618
|
+
this.sftpSlots.delete(alias)
|
|
619
|
+
this.netSlots.delete(alias)
|
|
620
|
+
this.gitSlots.delete(alias)
|
|
292
621
|
}
|
|
293
622
|
|
|
294
623
|
/** Close every pooled connection. */
|
|
295
624
|
dispose(): void {
|
|
296
|
-
for (const alias of new Set([
|
|
625
|
+
for (const alias of new Set([
|
|
626
|
+
...this.conns.keys(),
|
|
627
|
+
...this.shellConns.keys(),
|
|
628
|
+
...this.forwardConns.keys(),
|
|
629
|
+
...this.sftpConns.keys(),
|
|
630
|
+
])) {
|
|
631
|
+
this.drop(alias)
|
|
632
|
+
}
|
|
297
633
|
}
|
|
298
634
|
|
|
299
635
|
/**
|
|
@@ -317,28 +653,148 @@ export class RemotePool {
|
|
|
317
653
|
*/
|
|
318
654
|
status(): RemoteConnectionStatus[] {
|
|
319
655
|
const aliases = new Set<string>([...this.conns.keys(), ...this.health.keys()])
|
|
656
|
+
/** The host rows, read ONCE for the whole answer (see `configuredEgress`). */
|
|
657
|
+
const hosts = new Map<string, RemoteHostEntry>()
|
|
320
658
|
try {
|
|
321
|
-
for (const host of this.store.list())
|
|
659
|
+
for (const host of this.store.list()) {
|
|
660
|
+
aliases.add(host.alias)
|
|
661
|
+
hosts.set(host.alias, host)
|
|
662
|
+
}
|
|
322
663
|
} catch {
|
|
323
664
|
// Unreadable store: answer what the pool knows rather than failing the route.
|
|
324
665
|
}
|
|
325
666
|
return [...aliases].sort().map((alias) => {
|
|
326
667
|
const entry = this.health.get(alias)
|
|
327
668
|
const pooled = this.conns.get(alias)
|
|
669
|
+
// The route the HELD connection came through, else the one the stored
|
|
670
|
+
// configuration would take next — never both, so a live answer cannot be
|
|
671
|
+
// passed off as a configuration statement (or the other way round).
|
|
672
|
+
const egress = this.liveEgress(alias)
|
|
673
|
+
const configured = egress === undefined ? this.configuredEgress(alias, hosts.get(alias)) : undefined
|
|
328
674
|
return {
|
|
329
675
|
alias,
|
|
330
676
|
state: entry?.state ?? 'idle',
|
|
331
|
-
//
|
|
332
|
-
//
|
|
677
|
+
// "open" = any of the FOUR connection classes (shared / PTY / forward /
|
|
678
|
+
// SFTP) is fully dialed. `connecting` means a DIAL is in flight (the
|
|
679
|
+
// pooled entry exists before the Client does), so that is not an open
|
|
680
|
+
// connection yet.
|
|
333
681
|
open: (pooled !== undefined && pooled.connecting === undefined)
|
|
334
|
-
|| (this.shellConns.get(alias)?.connecting === undefined && this.shellConns.has(alias))
|
|
682
|
+
|| (this.shellConns.get(alias)?.connecting === undefined && this.shellConns.has(alias))
|
|
683
|
+
|| (this.forwardConns.get(alias)?.connecting === undefined && this.forwardConns.has(alias))
|
|
684
|
+
|| (this.sftpConns.get(alias)?.connecting === undefined && this.sftpConns.has(alias)),
|
|
335
685
|
...(entry?.okAt === undefined ? {} : { okAt: entry.okAt }),
|
|
336
686
|
...(entry?.errorAt === undefined ? {} : { errorAt: entry.errorAt }),
|
|
337
687
|
...(entry?.error === undefined ? {} : { error: entry.error }),
|
|
688
|
+
...(egress === undefined ? {} : { egress }),
|
|
689
|
+
...(configured === undefined ? {} : { configured }),
|
|
690
|
+
}
|
|
691
|
+
})
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/**
|
|
695
|
+
* Live pool shape per host: connections, channels, and channel-budget
|
|
696
|
+
* occupancy (see `RemoteHostPoolStats`).
|
|
697
|
+
*
|
|
698
|
+
* Same contract as `status()`: read-only and dial-free, so the monitor's poll
|
|
699
|
+
* reports what the pool already knows instead of creating work. Answers every
|
|
700
|
+
* alias the store knows PLUS every alias the pool holds something for — a host
|
|
701
|
+
* removed from the store still has a connection for a moment, and a page that
|
|
702
|
+
* shows connections must not hide exactly those.
|
|
703
|
+
*/
|
|
704
|
+
stats(): RemoteHostPoolStats[] {
|
|
705
|
+
const aliases = new Set<string>([
|
|
706
|
+
...this.conns.keys(),
|
|
707
|
+
...this.shellConns.keys(),
|
|
708
|
+
...this.forwardConns.keys(),
|
|
709
|
+
...this.sftpConns.keys(),
|
|
710
|
+
...this.health.keys(),
|
|
711
|
+
])
|
|
712
|
+
try {
|
|
713
|
+
for (const host of this.store.list()) aliases.add(host.alias)
|
|
714
|
+
} catch {
|
|
715
|
+
// Unreadable store: answer what the pool knows rather than failing the route.
|
|
716
|
+
}
|
|
717
|
+
return [...aliases].sort().map((alias) => {
|
|
718
|
+
const shared = this.conns.get(alias)
|
|
719
|
+
const sharedOpen = shared !== undefined && shared.connecting === undefined
|
|
720
|
+
return {
|
|
721
|
+
alias,
|
|
722
|
+
connections: {
|
|
723
|
+
shared: this.laneOf(this.conns, alias),
|
|
724
|
+
pty: this.laneOf(this.shellConns, alias),
|
|
725
|
+
forward: this.laneOf(this.forwardConns, alias),
|
|
726
|
+
sftp: this.laneOf(this.sftpConns, alias),
|
|
727
|
+
},
|
|
728
|
+
slots: this.slotsOf(this.slots.get(alias)),
|
|
729
|
+
// Absent while the dedicated SFTP connection has never been used: a zero
|
|
730
|
+
// budget would read as "it exists and is empty", which is a different
|
|
731
|
+
// statement from "this lane is not in play".
|
|
732
|
+
...(this.sftpSlots.has(alias) ? { sftpSlots: this.slotsOf(this.sftpSlots.get(alias), SFTP_CHANNEL_LIMIT) } : {}),
|
|
733
|
+
// Same rule for the network lane: no network verb running and none queued
|
|
734
|
+
// means there is no row (a queued verb implies a live row, because a waiter
|
|
735
|
+
// is only enqueued behind a full table).
|
|
736
|
+
...(this.netSlots.has(alias) ? { netSlots: this.slotsOf(this.netSlots.get(alias), NET_CHANNEL_LIMIT) } : {}),
|
|
737
|
+
// …and for git commands.
|
|
738
|
+
...(this.gitSlots.has(alias) ? { gitSlots: this.slotsOf(this.gitSlots.get(alias), GIT_CHANNEL_LIMIT) } : {}),
|
|
739
|
+
// Only a DIALED shared connection has a route to report (the same rule as
|
|
740
|
+
// `status()`): a route belongs to the link that took it.
|
|
741
|
+
...(sharedOpen && shared.egress !== undefined ? { egress: shared.egress } : {}),
|
|
742
|
+
...(this.sftpFallback.has(alias) ? { sftpFallback: true } : {}),
|
|
338
743
|
}
|
|
339
744
|
})
|
|
340
745
|
}
|
|
341
746
|
|
|
747
|
+
/** One lane of one host: dialed or not, its open channels, its pinned rounds. */
|
|
748
|
+
private laneOf(map: Map<string, Pooled>, alias: string): RemotePoolLane {
|
|
749
|
+
const pooled = map.get(alias)
|
|
750
|
+
if (pooled === undefined) return { open: false, channels: 0, held: 0 }
|
|
751
|
+
return {
|
|
752
|
+
// A dialing entry exists before its Client does (same rule as `status`).
|
|
753
|
+
open: pooled.connecting === undefined,
|
|
754
|
+
// A gate seeds a pooled entry by hand, and that literal has no counter
|
|
755
|
+
// (the map is plain JS at runtime): start it at zero instead of NaN.
|
|
756
|
+
channels: (pooled.channels as number | undefined) ?? 0,
|
|
757
|
+
held: pooled.held,
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/** One channel budget, as reported (a budget nobody touched is empty, not absent). */
|
|
762
|
+
private slotsOf(state: Slots | undefined, limit = CHANNEL_LIMIT): RemotePoolSlots {
|
|
763
|
+
return { active: state?.active ?? 0, queued: state?.queue.length ?? 0, limit }
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* The egress of the alias' LIVE connection, whichever class owns it.
|
|
768
|
+
*
|
|
769
|
+
* All four classes open through the same resolved route, so the first one that
|
|
770
|
+
* is up answers for the alias; the shared connection is preferred because it is
|
|
771
|
+
* the one exec/browse (the surface the chip describes) rides.
|
|
772
|
+
*/
|
|
773
|
+
private liveEgress(alias: string): EgressInfo | undefined {
|
|
774
|
+
for (const map of [this.conns, this.forwardConns, this.shellConns, this.sftpConns]) {
|
|
775
|
+
const pooled = map.get(alias)
|
|
776
|
+
if (pooled === undefined || pooled.connecting !== undefined) continue
|
|
777
|
+
if (pooled.egress !== undefined) return pooled.egress
|
|
778
|
+
}
|
|
779
|
+
return undefined
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/**
|
|
783
|
+
* The route the stored configuration resolves to, for an alias with NO live
|
|
784
|
+
* connection. Pure observation, and absorbed: a dangling jump chain or a
|
|
785
|
+
* half-configured proxy makes `resolveProxy` throw, and a status poll must
|
|
786
|
+
* answer "the stored route is broken, here is why" instead of failing — the
|
|
787
|
+
* chip still has to render, and a 500 would hide the reason it exists to show.
|
|
788
|
+
*/
|
|
789
|
+
private configuredEgress(alias: string, host: RemoteHostEntry | undefined): EgressInfo | undefined {
|
|
790
|
+
if (host === undefined) return undefined
|
|
791
|
+
try {
|
|
792
|
+
return egressOf(this.store.resolveProxy(alias), host)
|
|
793
|
+
} catch (error) {
|
|
794
|
+
return { ...storedEgress(host), problem: messageOf(error) }
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
|
|
342
798
|
/** Record a successful dial or transport-level operation. */
|
|
343
799
|
private markOk(alias: string): void {
|
|
344
800
|
this.health.set(alias, { state: 'ok', okAt: Date.now() })
|
|
@@ -423,12 +879,18 @@ export class RemotePool {
|
|
|
423
879
|
* of queueing. The pool's own housekeeping (`bare`: the setsid probe and the
|
|
424
880
|
* group kill) is exempt — a kill that waits behind user traffic would be a
|
|
425
881
|
* worse bug than the one it fixes.
|
|
882
|
+
*
|
|
883
|
+
* `opts.lane` picks the budget: network verbs (`git fetch/pull/push/sync`) have
|
|
884
|
+
* their own small one, so a 20-minute push cannot starve the exec slots.
|
|
885
|
+
* Acquisition and release read the SAME table — a mismatch would leak a slot on
|
|
886
|
+
* one budget and double-count on the other.
|
|
426
887
|
*/
|
|
427
888
|
async exec(alias: string, command: string, opts: ExecOptions = {}): Promise<RemoteExecResult> {
|
|
428
889
|
if (opts.bare === true) return this.runExec(alias, command, opts)
|
|
429
890
|
const started = Date.now()
|
|
891
|
+
const slots = this.execBudget(opts.lane)
|
|
430
892
|
try {
|
|
431
|
-
await this.acquireSlot(alias)
|
|
893
|
+
await this.acquireSlot(alias, slots)
|
|
432
894
|
} catch (error) {
|
|
433
895
|
return {
|
|
434
896
|
success: false, exitCode: null, timedOut: false, stdout: '', stderr: '',
|
|
@@ -448,10 +910,17 @@ export class RemotePool {
|
|
|
448
910
|
else if (result.success || result.exitCode !== null) this.markOk(alias)
|
|
449
911
|
return result
|
|
450
912
|
} finally {
|
|
451
|
-
this.releaseSlot(alias)
|
|
913
|
+
this.releaseSlot(alias, slots)
|
|
452
914
|
}
|
|
453
915
|
}
|
|
454
916
|
|
|
917
|
+
/** The channel budget an exec spends, by lane (see `ExecOptions.lane`). */
|
|
918
|
+
private execBudget(lane: ExecOptions['lane']): Map<string, Slots> {
|
|
919
|
+
if (lane === 'network') return this.netSlots
|
|
920
|
+
if (lane === 'git') return this.gitSlots
|
|
921
|
+
return this.slots
|
|
922
|
+
}
|
|
923
|
+
|
|
455
924
|
/** The exec body, run while the caller already holds a channel slot. */
|
|
456
925
|
private async runExec(alias: string, command: string, opts: ExecOptions = {}): Promise<RemoteExecResult> {
|
|
457
926
|
const started = Date.now()
|
|
@@ -583,6 +1052,7 @@ export class RemotePool {
|
|
|
583
1052
|
} else {
|
|
584
1053
|
stream = channel
|
|
585
1054
|
}
|
|
1055
|
+
this.countChannel(this.conns, alias, channel)
|
|
586
1056
|
channel.on('close', (code: number | null, signalName?: string | null) => {
|
|
587
1057
|
// An exit status is the server's proof the child is gone; the close
|
|
588
1058
|
// we send ourselves is not.
|
|
@@ -695,6 +1165,7 @@ export class RemotePool {
|
|
|
695
1165
|
if (dedicated) this.releaseIn(this.shellConns, alias)
|
|
696
1166
|
else this.release(alias)
|
|
697
1167
|
})
|
|
1168
|
+
this.countChannel(dedicated ? this.shellConns : this.conns, alias, channel)
|
|
698
1169
|
this.markOk(alias)
|
|
699
1170
|
return channel
|
|
700
1171
|
} catch (error) {
|
|
@@ -705,10 +1176,37 @@ export class RemotePool {
|
|
|
705
1176
|
}
|
|
706
1177
|
}
|
|
707
1178
|
|
|
708
|
-
/**
|
|
1179
|
+
/**
|
|
1180
|
+
* Open one exec channel. The caller owns the channel lifecycle.
|
|
1181
|
+
*
|
|
1182
|
+
* This channel spends an EXEC SLOT (same budget as `runExec`): it is a real
|
|
1183
|
+
* `conn.exec` session on the shared connection, so `MaxSessions` counts it
|
|
1184
|
+
* whether the pool does or not. The subprocess runtime opens these for every
|
|
1185
|
+
* command it runs (`p2/ssh-proc.ts`) and can have several in flight, which used
|
|
1186
|
+
* to be the one way to push the shared connection past its ceiling: sshd then
|
|
1187
|
+
* refuses the extra channel HARD — no retry, and the operation fails looking
|
|
1188
|
+
* like a broken host. A slot makes the surplus WAIT instead: bounded queue, then
|
|
1189
|
+
* a readable "busy" message naming the cause.
|
|
1190
|
+
*/
|
|
709
1191
|
async execChannel(alias: string, command: string): Promise<ClientChannel> {
|
|
710
|
-
const
|
|
1192
|
+
const slots = this.slots
|
|
1193
|
+
await this.acquireSlot(alias, slots)
|
|
1194
|
+
let conn: Client
|
|
1195
|
+
try {
|
|
1196
|
+
conn = await this.acquire(alias)
|
|
1197
|
+
} catch (error) {
|
|
1198
|
+
this.releaseSlot(alias, slots)
|
|
1199
|
+
throw error
|
|
1200
|
+
}
|
|
711
1201
|
this.hold(alias)
|
|
1202
|
+
let released = false
|
|
1203
|
+
/** Give the slot and the hold back exactly once (close and error may both fire). */
|
|
1204
|
+
const releaseOnce = (): void => {
|
|
1205
|
+
if (released) return
|
|
1206
|
+
released = true
|
|
1207
|
+
this.release(alias)
|
|
1208
|
+
this.releaseSlot(alias, slots)
|
|
1209
|
+
}
|
|
712
1210
|
try {
|
|
713
1211
|
const channel = await new Promise<ClientChannel>((resolve, reject) => {
|
|
714
1212
|
conn.exec(command, (error, stream) => {
|
|
@@ -716,11 +1214,13 @@ export class RemotePool {
|
|
|
716
1214
|
else resolve(stream)
|
|
717
1215
|
})
|
|
718
1216
|
})
|
|
719
|
-
channel.once('close',
|
|
1217
|
+
channel.once('close', releaseOnce)
|
|
1218
|
+
channel.once('error', releaseOnce)
|
|
1219
|
+
this.countChannel(this.conns, alias, channel)
|
|
720
1220
|
this.markOk(alias)
|
|
721
1221
|
return channel
|
|
722
1222
|
} catch (error) {
|
|
723
|
-
|
|
1223
|
+
releaseOnce()
|
|
724
1224
|
if (isConnectionFailure(error)) this.markError(alias, error)
|
|
725
1225
|
throw error
|
|
726
1226
|
}
|
|
@@ -743,9 +1243,47 @@ export class RemotePool {
|
|
|
743
1243
|
* debug their network. Real transport failures still arrive through the
|
|
744
1244
|
* pooled connection's own close/error events.
|
|
745
1245
|
*/
|
|
746
|
-
async forwardOut(
|
|
747
|
-
|
|
748
|
-
|
|
1246
|
+
async forwardOut(
|
|
1247
|
+
alias: string,
|
|
1248
|
+
dstHost: string,
|
|
1249
|
+
dstPort: number,
|
|
1250
|
+
srcPort = 0,
|
|
1251
|
+
opts: { dedicated?: boolean } = {},
|
|
1252
|
+
): Promise<{ channel: ClientChannel; dedicated: boolean }> {
|
|
1253
|
+
/**
|
|
1254
|
+
* Prefer the DEDICATED forward connection (see `forwardConns`). A host that
|
|
1255
|
+
* refuses the extra connection still forwards: the fallback is the shared
|
|
1256
|
+
* connection, i.e. exactly the old behaviour. The downgrade is logged once per
|
|
1257
|
+
* alias — a browser opens several forward channels per page, and one warning
|
|
1258
|
+
* per server refusal is information while one per channel is noise.
|
|
1259
|
+
*
|
|
1260
|
+
* Two short-circuits keep that preference from costing time:
|
|
1261
|
+
* - a recent refusal/timeout parks the alias for {@link FORWARD_DEDICATED_BLOCK_MS},
|
|
1262
|
+
* so the next channel goes straight to the shared connection;
|
|
1263
|
+
* - while a dedicated dial is already in flight, a second channel rides the
|
|
1264
|
+
* shared connection instead of waiting for the same handshake (it can only
|
|
1265
|
+
* be used by ONE `acquireIn` caller anyway).
|
|
1266
|
+
*/
|
|
1267
|
+
let conn: Client
|
|
1268
|
+
let dedicated = opts.dedicated !== false
|
|
1269
|
+
if (dedicated && this.forwardCoolingDown(alias)) dedicated = false
|
|
1270
|
+
if (dedicated && this.forwardConns.get(alias)?.connecting !== undefined) dedicated = false
|
|
1271
|
+
if (dedicated) {
|
|
1272
|
+
try {
|
|
1273
|
+
conn = await this.acquireForward(alias)
|
|
1274
|
+
this.holdIn(this.forwardConns, alias)
|
|
1275
|
+
// A real dedicated connection clears the cooldown: the host accepts them.
|
|
1276
|
+
this.forwardBlocked.delete(alias)
|
|
1277
|
+
} catch (error) {
|
|
1278
|
+
dedicated = false
|
|
1279
|
+
this.blockForward(alias, error)
|
|
1280
|
+
conn = await this.acquire(alias)
|
|
1281
|
+
this.hold(alias)
|
|
1282
|
+
}
|
|
1283
|
+
} else {
|
|
1284
|
+
conn = await this.acquire(alias)
|
|
1285
|
+
this.hold(alias)
|
|
1286
|
+
}
|
|
749
1287
|
/**
|
|
750
1288
|
* What the channel-open callback does after the deadline already answered.
|
|
751
1289
|
*
|
|
@@ -779,34 +1317,83 @@ export class RemotePool {
|
|
|
779
1317
|
CONTROL_TIMEOUT_MS,
|
|
780
1318
|
`forwarding channel to ${dstHost}:${dstPort} did not open within ${CONTROL_TIMEOUT_MS / 1000}s`,
|
|
781
1319
|
)
|
|
782
|
-
channel.once('close', () =>
|
|
783
|
-
|
|
784
|
-
|
|
1320
|
+
channel.once('close', () => {
|
|
1321
|
+
if (dedicated) this.releaseIn(this.forwardConns, alias)
|
|
1322
|
+
else this.release(alias)
|
|
1323
|
+
})
|
|
1324
|
+
this.countChannel(dedicated ? this.forwardConns : this.conns, alias, channel)
|
|
1325
|
+
// Only the SHARED path is evidence about the shared link. A dedicated
|
|
1326
|
+
// channel that opened says nothing about it (and the dedicated connection's
|
|
1327
|
+
// own failures never write health — see `acquireIn`'s `quiet`).
|
|
1328
|
+
if (!dedicated) this.markOk(alias)
|
|
1329
|
+
return { channel, dedicated }
|
|
785
1330
|
} catch (error) {
|
|
786
1331
|
settled = true
|
|
787
|
-
this.
|
|
1332
|
+
if (dedicated) this.releaseIn(this.forwardConns, alias)
|
|
1333
|
+
else this.release(alias)
|
|
1334
|
+
/**
|
|
1335
|
+
* NO `markError` here — deliberately.
|
|
1336
|
+
*
|
|
1337
|
+
* ssh2 reports EVERY direct-tcpip failure as
|
|
1338
|
+
* `(SSH) Channel open failure: <reason>`, and the pool's
|
|
1339
|
+
* `CONNECTION_ERROR_RE` matches `channel open fail`. A closed remote port or
|
|
1340
|
+
* `AllowTcpForwarding no` therefore LOOKS like a transport failure and used
|
|
1341
|
+
* to paint the connection chip red (sending the user to debug a healthy
|
|
1342
|
+
* network, and putting the editor into read-only). The function's contract
|
|
1343
|
+
* is the opposite: a channel-open refusal is the RULE's failure
|
|
1344
|
+
* (`forward.lastError`), while real transport failures surface through the
|
|
1345
|
+
* pooled connection's own close/error events.
|
|
1346
|
+
*/
|
|
788
1347
|
throw error
|
|
789
1348
|
}
|
|
790
1349
|
}
|
|
791
1350
|
|
|
1351
|
+
/**
|
|
1352
|
+
* Is this alias's dedicated forward connection in its short cooldown?
|
|
1353
|
+
*
|
|
1354
|
+
* Expired entries are dropped eagerly so the map cannot grow per alias forever.
|
|
1355
|
+
*/
|
|
1356
|
+
private forwardCoolingDown(alias: string): boolean {
|
|
1357
|
+
const until = this.forwardBlocked.get(alias)
|
|
1358
|
+
if (until === undefined) return false
|
|
1359
|
+
if (Date.now() >= until) {
|
|
1360
|
+
this.forwardBlocked.delete(alias)
|
|
1361
|
+
return false
|
|
1362
|
+
}
|
|
1363
|
+
return true
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
/** Park the dedicated connection for one alias and log the downgrade, once. */
|
|
1367
|
+
private blockForward(alias: string, error: unknown): void {
|
|
1368
|
+
this.forwardBlocked.set(alias, Date.now() + FORWARD_DEDICATED_BLOCK_MS)
|
|
1369
|
+
this.noteForwardFallback(alias, error)
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
/** Log one alias's forward downgrade to the shared connection, once. */
|
|
1373
|
+
private noteForwardFallback(alias: string, error: unknown): void {
|
|
1374
|
+
if (this.forwardFallbackNoted.has(alias)) return
|
|
1375
|
+
this.forwardFallbackNoted.add(alias)
|
|
1376
|
+
const detail = error instanceof Error ? error.message : String(error ?? '')
|
|
1377
|
+
// eslint-disable-next-line no-console
|
|
1378
|
+
console.warn(`[dsh-remote-vs] dedicated forward connection to ${alias} failed; using the shared one:`, detail)
|
|
1379
|
+
}
|
|
1380
|
+
|
|
792
1381
|
/** Run one callback with a fresh SFTP session (closed afterwards). */
|
|
793
1382
|
async withSftp<T>(alias: string, fn: (sftp: SFTPWrapper) => Promise<T>, opts: SftpOptions = {}): Promise<T> {
|
|
794
|
-
// An SFTP session IS a channel, so it takes a slot too
|
|
795
|
-
//
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
throw error
|
|
803
|
-
}
|
|
1383
|
+
// An SFTP session IS a channel, so it takes a slot too — on the budget of the
|
|
1384
|
+
// connection it really rides (the dedicated SFTP one, or the shared one when
|
|
1385
|
+
// that dial was refused). Never both: the slot protects ONE connection's
|
|
1386
|
+
// `MaxSessions` allowance.
|
|
1387
|
+
const lane = await this.acquireSftp(alias)
|
|
1388
|
+
const slots = this.laneSlots(lane.lane)
|
|
1389
|
+
const connMap = this.laneConns(lane.lane)
|
|
1390
|
+
await this.acquireSlot(alias, slots)
|
|
804
1391
|
// Hold BEFORE the first await: holding after it leaves a window where the
|
|
805
1392
|
// connection has no hold count and is not yet recorded as in use, so the
|
|
806
1393
|
// idle timer armed by a concurrent release() could evict it mid-call.
|
|
807
|
-
this.
|
|
1394
|
+
this.holdIn(connMap, alias)
|
|
808
1395
|
try {
|
|
809
|
-
const sftp = await this.openSession(conn)
|
|
1396
|
+
const sftp = await this.openSession(lane.conn, alias, connMap)
|
|
810
1397
|
try {
|
|
811
1398
|
const limit = opts.timeoutMs ?? SFTP_OP_TIMEOUT_MS
|
|
812
1399
|
const result = limit <= 0
|
|
@@ -825,8 +1412,8 @@ export class RemotePool {
|
|
|
825
1412
|
this.noteOpFailure(alias, error)
|
|
826
1413
|
throw error
|
|
827
1414
|
} finally {
|
|
828
|
-
this.
|
|
829
|
-
this.releaseSlot(alias)
|
|
1415
|
+
this.releaseIn(connMap, alias)
|
|
1416
|
+
this.releaseSlot(alias, slots)
|
|
830
1417
|
}
|
|
831
1418
|
}
|
|
832
1419
|
|
|
@@ -863,30 +1450,38 @@ export class RemotePool {
|
|
|
863
1450
|
const sessions: SFTPWrapper[] = []
|
|
864
1451
|
let slots = 0
|
|
865
1452
|
let holds = 0
|
|
1453
|
+
/** Which lane the transfer got; undefined until the acquisition succeeded. */
|
|
1454
|
+
let lane: SftpLane | undefined
|
|
866
1455
|
/** Set when the callback settles: a late `addChannel` must not leak resources. */
|
|
867
1456
|
let closed = false
|
|
868
|
-
let conn: Client
|
|
869
1457
|
try {
|
|
1458
|
+
// ONE lane decision for the whole transfer: every extra channel must ride
|
|
1459
|
+
// the same connection as the first one (a second connection would double
|
|
1460
|
+
// the handshake the transfer exists to amortise), and every session counts
|
|
1461
|
+
// on that connection's own budget.
|
|
1462
|
+
const lease = await this.acquireSftp(alias)
|
|
1463
|
+
lane = lease.lane
|
|
1464
|
+
const slotTable = this.laneSlots(lease.lane)
|
|
1465
|
+
const connMap = this.laneConns(lease.lane)
|
|
870
1466
|
// An SFTP session IS a channel, so each one takes a slot: the ceiling this
|
|
871
1467
|
// protects is the server's MaxSessions, not our own bookkeeping.
|
|
872
|
-
await this.acquireSlot(alias)
|
|
1468
|
+
await this.acquireSlot(alias, slotTable)
|
|
873
1469
|
slots += 1
|
|
874
|
-
conn = await this.acquire(alias)
|
|
875
1470
|
// Hold BEFORE the first await (same reason as withSftp).
|
|
876
|
-
this.
|
|
1471
|
+
this.holdIn(connMap, alias)
|
|
877
1472
|
holds += 1
|
|
878
|
-
sessions.push(await this.openSession(conn))
|
|
1473
|
+
sessions.push(await this.openSession(lease.conn, alias, connMap))
|
|
879
1474
|
const addChannel = async (): Promise<SFTPWrapper | undefined> => {
|
|
880
1475
|
if (closed) return undefined
|
|
881
1476
|
// NEVER queue for an optional channel: a busy host would otherwise delay
|
|
882
1477
|
// the body of a download that is already streaming by up to
|
|
883
1478
|
// CHANNEL_WAIT_MS, which is worse than one channel.
|
|
884
|
-
if (!this.tryAcquireSlot(alias)) return undefined
|
|
1479
|
+
if (!this.tryAcquireSlot(alias, slotTable)) return undefined
|
|
885
1480
|
slots += 1
|
|
886
|
-
this.
|
|
1481
|
+
this.holdIn(connMap, alias)
|
|
887
1482
|
holds += 1
|
|
888
1483
|
try {
|
|
889
|
-
const extra = await this.openSession(conn)
|
|
1484
|
+
const extra = await this.openSession(lease.conn, alias, connMap)
|
|
890
1485
|
if (closed) {
|
|
891
1486
|
// The transfer settled while this channel was opening; the finally
|
|
892
1487
|
// already returned its slot and hold, so close it here.
|
|
@@ -920,8 +1515,12 @@ export class RemotePool {
|
|
|
920
1515
|
// Ignore close errors.
|
|
921
1516
|
}
|
|
922
1517
|
}
|
|
923
|
-
|
|
924
|
-
|
|
1518
|
+
// The lane is decided inside the try; a failed acquisition took nothing, so
|
|
1519
|
+
// there is nothing to give back for it either.
|
|
1520
|
+
if (lane !== undefined) {
|
|
1521
|
+
for (let i = 0; i < holds; i += 1) this.releaseIn(this.laneConns(lane), alias)
|
|
1522
|
+
for (let i = 0; i < slots; i += 1) this.releaseSlot(alias, this.laneSlots(lane))
|
|
1523
|
+
}
|
|
925
1524
|
}
|
|
926
1525
|
}
|
|
927
1526
|
|
|
@@ -1046,8 +1645,11 @@ export class RemotePool {
|
|
|
1046
1645
|
* place that can still see the session, and a late one would otherwise leak a
|
|
1047
1646
|
* server-side channel that no slot or hold accounts for (the caller has long
|
|
1048
1647
|
* returned its own and moved on).
|
|
1648
|
+
*
|
|
1649
|
+
* `alias`/`map` name the connection the session rides, so the channel it holds
|
|
1650
|
+
* is counted on the right lane (see `countChannel`).
|
|
1049
1651
|
*/
|
|
1050
|
-
private openSession(conn: Client): Promise<SFTPWrapper> {
|
|
1652
|
+
private openSession(conn: Client, alias: string, map: Map<string, Pooled>): Promise<SFTPWrapper> {
|
|
1051
1653
|
return new Promise<SFTPWrapper>((resolve, reject) => {
|
|
1052
1654
|
let settled = false
|
|
1053
1655
|
const timer = setTimeout(() => {
|
|
@@ -1068,8 +1670,14 @@ export class RemotePool {
|
|
|
1068
1670
|
}
|
|
1069
1671
|
settled = true
|
|
1070
1672
|
clearTimeout(timer)
|
|
1071
|
-
if (error !== undefined && error !== null)
|
|
1072
|
-
|
|
1673
|
+
if (error !== undefined && error !== null) {
|
|
1674
|
+
reject(error)
|
|
1675
|
+
return
|
|
1676
|
+
}
|
|
1677
|
+
// Counted only when it is really handed over: a session that answers
|
|
1678
|
+
// after the deadline is closed above and was never one of ours.
|
|
1679
|
+
this.countChannel(map, alias, session as SFTPWrapper)
|
|
1680
|
+
resolve(session as SFTPWrapper)
|
|
1073
1681
|
}
|
|
1074
1682
|
try {
|
|
1075
1683
|
conn.sftp((error, session) => finish(error, session))
|
|
@@ -1125,22 +1733,23 @@ export class RemotePool {
|
|
|
1125
1733
|
/**
|
|
1126
1734
|
* Open the browse session: a channel slot + a connection hold + the SFTP
|
|
1127
1735
|
* session itself, all released together by evictBrowse().
|
|
1736
|
+
*
|
|
1737
|
+
* The lane is chosen HERE, once per session, and recorded on the state: the
|
|
1738
|
+
* eviction path must give the slot and the hold back to the connection that
|
|
1739
|
+
* actually served the session (dedicated SFTP, or the shared fallback).
|
|
1128
1740
|
*/
|
|
1129
1741
|
private async openBrowse(alias: string, state: BrowseChannel): Promise<SFTPWrapper> {
|
|
1130
|
-
await this.
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
this.releaseSlot(alias)
|
|
1136
|
-
throw error
|
|
1137
|
-
}
|
|
1742
|
+
const lane = await this.acquireSftp(alias)
|
|
1743
|
+
state.lane = lane.lane
|
|
1744
|
+
const slots = this.laneSlots(lane.lane)
|
|
1745
|
+
const connMap = this.laneConns(lane.lane)
|
|
1746
|
+
await this.acquireSlot(alias, slots)
|
|
1138
1747
|
// Hold before the first await, for the same reason withSftp does: a
|
|
1139
1748
|
// concurrent release() must not arm idle eviction mid-open.
|
|
1140
|
-
this.
|
|
1749
|
+
this.holdIn(connMap, alias)
|
|
1141
1750
|
state.leased = true
|
|
1142
1751
|
try {
|
|
1143
|
-
const sftp = await this.openSession(conn)
|
|
1752
|
+
const sftp = await this.openSession(lane.conn, alias, connMap)
|
|
1144
1753
|
// The host can be dropped while the session is opening: the slot and hold
|
|
1145
1754
|
// are already returned and nobody would ever close this channel, so refuse
|
|
1146
1755
|
// it instead of handing out a session on a dead connection.
|
|
@@ -1218,27 +1827,41 @@ export class RemotePool {
|
|
|
1218
1827
|
}
|
|
1219
1828
|
if (state.leased) {
|
|
1220
1829
|
state.leased = false
|
|
1221
|
-
|
|
1222
|
-
|
|
1830
|
+
// Back to the connection that served it: the dedicated SFTP one, or the
|
|
1831
|
+
// shared fallback (never both — that was the lane decision in openBrowse).
|
|
1832
|
+
this.releaseIn(this.laneConns(state.lane), alias)
|
|
1833
|
+
this.releaseSlot(alias, this.laneSlots(state.lane))
|
|
1223
1834
|
}
|
|
1224
1835
|
}
|
|
1225
1836
|
|
|
1226
1837
|
private browseState(alias: string): BrowseChannel {
|
|
1227
1838
|
const existing = this.browsed.get(alias)
|
|
1228
1839
|
if (existing !== undefined) return existing
|
|
1229
|
-
const created: BrowseChannel = {
|
|
1840
|
+
const created: BrowseChannel = {
|
|
1841
|
+
session: undefined,
|
|
1842
|
+
opening: undefined,
|
|
1843
|
+
active: 0,
|
|
1844
|
+
stale: false,
|
|
1845
|
+
leased: false,
|
|
1846
|
+
lane: 'shared',
|
|
1847
|
+
idle: undefined,
|
|
1848
|
+
}
|
|
1230
1849
|
this.browsed.set(alias, created)
|
|
1231
1850
|
return created
|
|
1232
1851
|
}
|
|
1233
1852
|
|
|
1234
1853
|
/**
|
|
1235
|
-
* Take one channel slot for `alias
|
|
1236
|
-
* The wait is bounded: waiting forever behind a peer
|
|
1237
|
-
* worse than a readable error naming the cause
|
|
1854
|
+
* Take one channel slot for `alias` on the budget `slots` names, waiting FIFO
|
|
1855
|
+
* when the limit is reached. The wait is bounded: waiting forever behind a peer
|
|
1856
|
+
* that never finishes is worse than a readable error naming the cause.
|
|
1857
|
+
*
|
|
1858
|
+
* `slots` defaults to the SHARED connection's exec budget — the table every
|
|
1859
|
+
* caller meant before the lanes existed; dedicated-lane callers pass theirs.
|
|
1238
1860
|
*/
|
|
1239
|
-
private async acquireSlot(alias: string): Promise<void> {
|
|
1240
|
-
const
|
|
1241
|
-
|
|
1861
|
+
private async acquireSlot(alias: string, slots: Map<string, Slots> = this.slots): Promise<void> {
|
|
1862
|
+
const { limit, noun } = this.budgetOf(slots)
|
|
1863
|
+
const state = this.slotState(alias, slots)
|
|
1864
|
+
if (state.active < limit) {
|
|
1242
1865
|
state.active += 1
|
|
1243
1866
|
return
|
|
1244
1867
|
}
|
|
@@ -1253,7 +1876,7 @@ export class RemotePool {
|
|
|
1253
1876
|
const index = state.queue.indexOf(waiter)
|
|
1254
1877
|
if (index >= 0) state.queue.splice(index, 1)
|
|
1255
1878
|
reject(new Error(
|
|
1256
|
-
`remote host ${alias} is busy: ${
|
|
1879
|
+
`remote host ${alias} is busy: ${limit} ${noun} already hold channels `
|
|
1257
1880
|
+ `(this one waited ${CHANNEL_WAIT_MS / 1000}s — retry once the earlier work finishes)`,
|
|
1258
1881
|
))
|
|
1259
1882
|
}, CHANNEL_WAIT_MS)
|
|
@@ -1262,6 +1885,25 @@ export class RemotePool {
|
|
|
1262
1885
|
})
|
|
1263
1886
|
}
|
|
1264
1887
|
|
|
1888
|
+
/**
|
|
1889
|
+
* The ceiling and the wording of one budget.
|
|
1890
|
+
*
|
|
1891
|
+
* The TABLE is the budget's identity: a caller that hands in a table gets that
|
|
1892
|
+
* budget's own ceiling AND its own nouns, so a full network lane says "2
|
|
1893
|
+
* network operations already hold channels" and a full git lane says "2 git
|
|
1894
|
+
* commands already hold channels" instead of borrowing the exec sentence — a
|
|
1895
|
+
* user reading "5 operations" about a two-slot lane would go looking for
|
|
1896
|
+
* operations that do not exist. A new budget is described here, once.
|
|
1897
|
+
*/
|
|
1898
|
+
private budgetOf(slots: Map<string, Slots>): { limit: number; noun: string } {
|
|
1899
|
+
if (slots === this.netSlots) return { limit: NET_CHANNEL_LIMIT, noun: 'network operations' }
|
|
1900
|
+
if (slots === this.gitSlots) return { limit: GIT_CHANNEL_LIMIT, noun: 'git commands' }
|
|
1901
|
+
// The dedicated file connection is not part of the shared-connection ledger,
|
|
1902
|
+
// so it keeps the ceiling the transfer measurement landed on.
|
|
1903
|
+
if (slots === this.sftpSlots) return { limit: SFTP_CHANNEL_LIMIT, noun: 'operations' }
|
|
1904
|
+
return { limit: CHANNEL_LIMIT, noun: 'operations' }
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1265
1907
|
/**
|
|
1266
1908
|
* Take one channel slot only if one is free RIGHT NOW; never queue.
|
|
1267
1909
|
*
|
|
@@ -1272,16 +1914,17 @@ export class RemotePool {
|
|
|
1272
1914
|
* the attempt on purpose — it has been waiting longer, and stealing its slot
|
|
1273
1915
|
* would just move the wait.
|
|
1274
1916
|
*/
|
|
1275
|
-
private tryAcquireSlot(alias: string): boolean {
|
|
1276
|
-
const
|
|
1277
|
-
|
|
1917
|
+
private tryAcquireSlot(alias: string, slots: Map<string, Slots> = this.slots): boolean {
|
|
1918
|
+
const { limit } = this.budgetOf(slots)
|
|
1919
|
+
const state = this.slotState(alias, slots)
|
|
1920
|
+
if (state.active >= limit || state.queue.length > 0) return false
|
|
1278
1921
|
state.active += 1
|
|
1279
1922
|
return true
|
|
1280
1923
|
}
|
|
1281
1924
|
|
|
1282
|
-
/** Give a slot back, handing it straight to the longest
|
|
1283
|
-
private releaseSlot(alias: string): void {
|
|
1284
|
-
const state =
|
|
1925
|
+
/** Give a slot back to its budget, handing it straight to the longest waiter. */
|
|
1926
|
+
private releaseSlot(alias: string, slots: Map<string, Slots> = this.slots): void {
|
|
1927
|
+
const state = slots.get(alias)
|
|
1285
1928
|
if (state === undefined) return
|
|
1286
1929
|
const waiter = state.queue.shift()
|
|
1287
1930
|
if (waiter !== undefined) {
|
|
@@ -1291,14 +1934,14 @@ export class RemotePool {
|
|
|
1291
1934
|
return
|
|
1292
1935
|
}
|
|
1293
1936
|
if (state.active > 0) state.active -= 1
|
|
1294
|
-
if (state.active === 0)
|
|
1937
|
+
if (state.active === 0) slots.delete(alias)
|
|
1295
1938
|
}
|
|
1296
1939
|
|
|
1297
|
-
private slotState(alias: string): Slots {
|
|
1298
|
-
const existing =
|
|
1940
|
+
private slotState(alias: string, slots: Map<string, Slots>): Slots {
|
|
1941
|
+
const existing = slots.get(alias)
|
|
1299
1942
|
if (existing !== undefined) return existing
|
|
1300
1943
|
const created: Slots = { active: 0, queue: [] }
|
|
1301
|
-
|
|
1944
|
+
slots.set(alias, created)
|
|
1302
1945
|
return created
|
|
1303
1946
|
}
|
|
1304
1947
|
|
|
@@ -1357,6 +2000,42 @@ export class RemotePool {
|
|
|
1357
2000
|
this.releaseIn(this.conns, alias)
|
|
1358
2001
|
}
|
|
1359
2002
|
|
|
2003
|
+
/**
|
|
2004
|
+
* Count one SSH channel that is now open on a pooled connection, and give the
|
|
2005
|
+
* number back when the channel closes.
|
|
2006
|
+
*
|
|
2007
|
+
* `held` is NOT this number (see `Pooled.channels`): a jump tunnel pins the
|
|
2008
|
+
* jump host twice for its single channel, and `stats()` reports both, so the
|
|
2009
|
+
* monitor page never prints a hold count as a channel count. The close listener
|
|
2010
|
+
* mutates the entry OBJECT it was registered on, so a channel that outlives its
|
|
2011
|
+
* entry cannot decrement the counter of a successor entry.
|
|
2012
|
+
*
|
|
2013
|
+
* The entry is looked up when the channel is COUNTED, so a session that answers
|
|
2014
|
+
* pathologically late (after `drop()` and a fresh dial) is charged to the
|
|
2015
|
+
* successor entry and given back when it closes. Accepted: the window needs a
|
|
2016
|
+
* reply that outlives a host edit, the number is diagnostic, and the pair is
|
|
2017
|
+
* still symmetric (one increment, one decrement).
|
|
2018
|
+
*/
|
|
2019
|
+
private countChannel(
|
|
2020
|
+
map: Map<string, Pooled>,
|
|
2021
|
+
alias: string,
|
|
2022
|
+
channel: { on?: (event: 'close', listener: () => void) => unknown },
|
|
2023
|
+
): void {
|
|
2024
|
+
const pooled = map.get(alias)
|
|
2025
|
+
// Nothing to count against, or a stand-in channel that cannot report its own
|
|
2026
|
+
// close: counting THAT would leave a number nothing can ever give back.
|
|
2027
|
+
if (pooled === undefined || typeof channel.on !== 'function') return
|
|
2028
|
+
// A gate seeds a pooled entry by hand, and that literal has no counter (the
|
|
2029
|
+
// map is plain JS at runtime): start it at zero instead of producing NaN.
|
|
2030
|
+
pooled.channels = ((pooled.channels as number | undefined) ?? 0) + 1
|
|
2031
|
+
let counted = true
|
|
2032
|
+
channel.on('close', () => {
|
|
2033
|
+
if (!counted) return
|
|
2034
|
+
counted = false
|
|
2035
|
+
if (pooled.channels > 0) pooled.channels -= 1
|
|
2036
|
+
})
|
|
2037
|
+
}
|
|
2038
|
+
|
|
1360
2039
|
private releaseIn(map: Map<string, Pooled>, alias: string): void {
|
|
1361
2040
|
const pooled = map.get(alias)
|
|
1362
2041
|
if (pooled === undefined) return
|
|
@@ -1379,14 +2058,138 @@ export class RemotePool {
|
|
|
1379
2058
|
return this.acquireIn(this.shellConns, alias)
|
|
1380
2059
|
}
|
|
1381
2060
|
|
|
1382
|
-
|
|
2061
|
+
/**
|
|
2062
|
+
* `acquire` for the dedicated port-forward connection map.
|
|
2063
|
+
*
|
|
2064
|
+
* `quiet`: a dedicated forward connection is an OPTIMIZATION. If the server
|
|
2065
|
+
* refuses it (MaxStartups, `MaxSessions`, a per-source limit) the forward still
|
|
2066
|
+
* works over the shared connection, so the shared link is healthy — painting
|
|
2067
|
+
* the connection chip red here would send the user to debug a network that is
|
|
2068
|
+
* fine (and `forwardOut` reports the rule's own error separately).
|
|
2069
|
+
*
|
|
2070
|
+
* The dial also gets its OWN short budget ({@link FORWARD_DEDICATED_BUDGET_MS}):
|
|
2071
|
+
* a server that silently drops the extra connection would otherwise make every
|
|
2072
|
+
* forward channel wait the full connect watchdog before falling back. The
|
|
2073
|
+
* abandoned dial keeps running — if it eventually succeeds the connection is
|
|
2074
|
+
* pooled and the next channel uses it; its failure is already handled inside
|
|
2075
|
+
* `acquireIn`.
|
|
2076
|
+
*/
|
|
2077
|
+
private async acquireForward(alias: string): Promise<Client> {
|
|
2078
|
+
const dialing = this.acquireIn(this.forwardConns, alias, true)
|
|
2079
|
+
try {
|
|
2080
|
+
return await withDeadline(
|
|
2081
|
+
dialing,
|
|
2082
|
+
FORWARD_DEDICATED_BUDGET_MS,
|
|
2083
|
+
`dedicated forward connection to ${alias} did not settle within ${FORWARD_DEDICATED_BUDGET_MS / 1000}s`,
|
|
2084
|
+
)
|
|
2085
|
+
} catch (error) {
|
|
2086
|
+
// The race's loser must never surface as an unhandled rejection: the pool
|
|
2087
|
+
// still owns it (its own success/failure updates the map).
|
|
2088
|
+
void dialing.catch(() => undefined)
|
|
2089
|
+
throw error
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
|
|
2093
|
+
/**
|
|
2094
|
+
* Take the connection a FILE operation should ride: the dedicated SFTP one,
|
|
2095
|
+
* else the shared one (recorded as the fallback).
|
|
2096
|
+
*
|
|
2097
|
+
* Same three-part shape as the PTY/forward precedents, for the same reasons:
|
|
2098
|
+
*
|
|
2099
|
+
* 1. `quiet` on the dial — a dedicated connection is an optional isolation, so
|
|
2100
|
+
* the server refusing it (MaxStartups, a per-user limit) says nothing about
|
|
2101
|
+
* the shared link and must not paint the connection chip red.
|
|
2102
|
+
* 2. A short own budget ({@link SFTP_DEDICATED_BUDGET_MS}) — browsing is one
|
|
2103
|
+
* request per folder, so waiting out the 45 s connect watchdog before falling
|
|
2104
|
+
* back would freeze the explorer. The abandoned dial keeps running: if it
|
|
2105
|
+
* eventually succeeds the connection is pooled and the next request uses it.
|
|
2106
|
+
* 3. A cooldown ({@link SFTP_DEDICATED_BLOCK_MS}) — without it every browse
|
|
2107
|
+
* request would pay that budget again. A success or `drop()` clears it.
|
|
2108
|
+
*
|
|
2109
|
+
* The shared fallback's own dial failure is NOT quiet (it is a real link
|
|
2110
|
+
* failure and `acquire` reports it as one).
|
|
2111
|
+
*/
|
|
2112
|
+
private async acquireSftp(alias: string): Promise<{ conn: Client; lane: SftpLane }> {
|
|
2113
|
+
if (!this.sftpCoolingDown(alias)) {
|
|
2114
|
+
const dialing = this.acquireIn(this.sftpConns, alias, true)
|
|
2115
|
+
try {
|
|
2116
|
+
const conn = await withDeadline(
|
|
2117
|
+
dialing,
|
|
2118
|
+
SFTP_DEDICATED_BUDGET_MS,
|
|
2119
|
+
`dedicated file connection to ${alias} did not settle within ${SFTP_DEDICATED_BUDGET_MS / 1000}s`,
|
|
2120
|
+
)
|
|
2121
|
+
// A real dedicated connection clears the downgrade: the host accepts them.
|
|
2122
|
+
this.sftpBlocked.delete(alias)
|
|
2123
|
+
this.sftpFallback.delete(alias)
|
|
2124
|
+
return { conn, lane: 'sftp' }
|
|
2125
|
+
} catch (error) {
|
|
2126
|
+
// The race's loser must never surface as an unhandled rejection: the pool
|
|
2127
|
+
// still owns it (its own success/failure updates the map).
|
|
2128
|
+
void dialing.catch(() => undefined)
|
|
2129
|
+
this.blockSftp(alias, error)
|
|
2130
|
+
}
|
|
2131
|
+
}
|
|
2132
|
+
const conn = await this.acquire(alias)
|
|
2133
|
+
this.sftpFallback.add(alias)
|
|
2134
|
+
return { conn, lane: 'shared' }
|
|
2135
|
+
}
|
|
2136
|
+
|
|
2137
|
+
/** The pooled map behind a lane: the dedicated SFTP connection, or the shared one. */
|
|
2138
|
+
private laneConns(lane: SftpLane): Map<string, Pooled> {
|
|
2139
|
+
return lane === 'sftp' ? this.sftpConns : this.conns
|
|
2140
|
+
}
|
|
2141
|
+
|
|
2142
|
+
/** The channel budget behind a lane: each connection has its own `MaxSessions`. */
|
|
2143
|
+
private laneSlots(lane: SftpLane): Map<string, Slots> {
|
|
2144
|
+
return lane === 'sftp' ? this.sftpSlots : this.slots
|
|
2145
|
+
}
|
|
2146
|
+
|
|
2147
|
+
/**
|
|
2148
|
+
* Is this alias's dedicated SFTP connection in its short cooldown?
|
|
2149
|
+
*
|
|
2150
|
+
* Expired entries are dropped eagerly so the map cannot grow per alias forever.
|
|
2151
|
+
*/
|
|
2152
|
+
private sftpCoolingDown(alias: string): boolean {
|
|
2153
|
+
const until = this.sftpBlocked.get(alias)
|
|
2154
|
+
if (until === undefined) return false
|
|
2155
|
+
if (Date.now() >= until) {
|
|
2156
|
+
this.sftpBlocked.delete(alias)
|
|
2157
|
+
return false
|
|
2158
|
+
}
|
|
2159
|
+
return true
|
|
2160
|
+
}
|
|
2161
|
+
|
|
2162
|
+
/** Park the dedicated SFTP connection for one alias and log the downgrade, once. */
|
|
2163
|
+
private blockSftp(alias: string, error: unknown): void {
|
|
2164
|
+
this.sftpBlocked.set(alias, Date.now() + SFTP_DEDICATED_BLOCK_MS)
|
|
2165
|
+
this.sftpFallback.add(alias)
|
|
2166
|
+
this.noteSftpFallback(alias, error)
|
|
2167
|
+
}
|
|
2168
|
+
|
|
2169
|
+
/** Log one alias's file-operation downgrade to the shared connection, once. */
|
|
2170
|
+
private noteSftpFallback(alias: string, error: unknown): void {
|
|
2171
|
+
if (this.sftpFallbackNoted.has(alias)) return
|
|
2172
|
+
this.sftpFallbackNoted.add(alias)
|
|
2173
|
+
const detail = error instanceof Error ? error.message : String(error ?? '')
|
|
2174
|
+
// eslint-disable-next-line no-console
|
|
2175
|
+
console.warn(`[dsh-remote-vs] dedicated file connection to ${alias} failed; using the shared one:`, detail)
|
|
2176
|
+
}
|
|
2177
|
+
|
|
2178
|
+
private async acquireIn(map: Map<string, Pooled>, alias: string, quiet = false): Promise<Client> {
|
|
1383
2179
|
const pooled = map.get(alias)
|
|
1384
2180
|
if (pooled !== undefined && pooled.connecting !== undefined) return pooled.connecting
|
|
1385
2181
|
if (pooled !== undefined) {
|
|
1386
2182
|
pooled.lastUse = Date.now()
|
|
1387
2183
|
return pooled.conn
|
|
1388
2184
|
}
|
|
1389
|
-
const entry: Pooled = {
|
|
2185
|
+
const entry: Pooled = {
|
|
2186
|
+
conn: undefined as unknown as Client,
|
|
2187
|
+
timer: undefined,
|
|
2188
|
+
lastUse: Date.now(),
|
|
2189
|
+
connecting: undefined,
|
|
2190
|
+
held: 0,
|
|
2191
|
+
channels: 0,
|
|
2192
|
+
}
|
|
1390
2193
|
map.set(alias, entry)
|
|
1391
2194
|
/**
|
|
1392
2195
|
* The entry object IS the ownership token: `drop()` deletes it and a later
|
|
@@ -1399,7 +2202,11 @@ export class RemotePool {
|
|
|
1399
2202
|
* so no idle timer arms, and `dispose()` only walks the map. Without the
|
|
1400
2203
|
* failure check, a failed OLD dial deletes the NEW entry by alias.
|
|
1401
2204
|
*/
|
|
1402
|
-
entry.connecting = this.dial(alias)
|
|
2205
|
+
entry.connecting = this.dial(alias, (egress) => {
|
|
2206
|
+
// The entry object is the ownership token (see just above): a dial that
|
|
2207
|
+
// lost the alias must not paint its route on whatever entry now holds it.
|
|
2208
|
+
if (map.get(alias) === entry) entry.egress = egress
|
|
2209
|
+
}).then(
|
|
1403
2210
|
(conn) => {
|
|
1404
2211
|
if (map.get(alias) !== entry) {
|
|
1405
2212
|
try {
|
|
@@ -1411,18 +2218,18 @@ export class RemotePool {
|
|
|
1411
2218
|
}
|
|
1412
2219
|
entry.conn = conn
|
|
1413
2220
|
entry.connecting = undefined
|
|
1414
|
-
this.markOk(alias)
|
|
2221
|
+
if (!quiet) this.markOk(alias)
|
|
1415
2222
|
conn.on('close', () => {
|
|
1416
2223
|
// The server went away: record it for the status chip, then evict so
|
|
1417
2224
|
// the next op redials. Our OWN drop() deleted the entry first, so a
|
|
1418
2225
|
// normal close (idle eviction, host removal) never lands here.
|
|
1419
2226
|
if (map.get(alias) !== entry) return
|
|
1420
|
-
this.markError(alias, new Error('connection closed'))
|
|
2227
|
+
if (!quiet) this.markError(alias, new Error('connection closed'))
|
|
1421
2228
|
this.evictFrom(map, alias)
|
|
1422
2229
|
})
|
|
1423
2230
|
conn.on('error', (error: Error) => {
|
|
1424
2231
|
if (map.get(alias) !== entry) return
|
|
1425
|
-
this.markError(alias, error)
|
|
2232
|
+
if (!quiet) this.markError(alias, error)
|
|
1426
2233
|
this.evictFrom(map, alias)
|
|
1427
2234
|
})
|
|
1428
2235
|
this.releaseIn(map, alias)
|
|
@@ -1430,7 +2237,7 @@ export class RemotePool {
|
|
|
1430
2237
|
},
|
|
1431
2238
|
(error) => {
|
|
1432
2239
|
if (map.get(alias) === entry) map.delete(alias)
|
|
1433
|
-
this.markError(alias, error)
|
|
2240
|
+
if (!quiet) this.markError(alias, error)
|
|
1434
2241
|
throw error
|
|
1435
2242
|
},
|
|
1436
2243
|
)
|
|
@@ -1443,6 +2250,9 @@ export class RemotePool {
|
|
|
1443
2250
|
if (pooled === undefined) return
|
|
1444
2251
|
map.delete(alias)
|
|
1445
2252
|
if (pooled.timer !== undefined) clearTimeout(pooled.timer)
|
|
2253
|
+
// The route belongs to the connection that just ended: leaving it behind
|
|
2254
|
+
// would let a closed link keep claiming the egress it once used.
|
|
2255
|
+
pooled.egress = undefined
|
|
1446
2256
|
try {
|
|
1447
2257
|
pooled.conn.end()
|
|
1448
2258
|
} catch {
|
|
@@ -1462,8 +2272,139 @@ export class RemotePool {
|
|
|
1462
2272
|
return new Client()
|
|
1463
2273
|
}
|
|
1464
2274
|
|
|
1465
|
-
|
|
2275
|
+
/**
|
|
2276
|
+
* Open the transport `alias`'s configured route requires, WITHOUT dialing SSH.
|
|
2277
|
+
*
|
|
2278
|
+
* This is the part of {@link dial} that turns a `ResolvedProxy` decision into a
|
|
2279
|
+
* socket: nothing for a direct route, a tunnel socket for a proxy, and a
|
|
2280
|
+
* `direct-tcpip` channel riding the jump host's pooled connection for a jump.
|
|
2281
|
+
* Extracted so a SECOND ssh2 dialer — p2's helper transport, which owns its own
|
|
2282
|
+
* `Client` — takes exactly the same route instead of a bare direct connection
|
|
2283
|
+
* (otherwise a host reachable only through a proxy or jump host answers exec and
|
|
2284
|
+
* SFTP but fails every file/Git fast path).
|
|
2285
|
+
*
|
|
2286
|
+
* `route` may be passed in when the caller has already resolved it and needs the
|
|
2287
|
+
* decision for its own purposes (`dial` reports the egress it settled on): the
|
|
2288
|
+
* default resolves it from the store.
|
|
2289
|
+
*
|
|
2290
|
+
* The returned `release` is IDEMPOTENT and belongs to the caller: it tears down
|
|
2291
|
+
* the tunnel (destroys the proxy socket / closes the channel and gives the jump
|
|
2292
|
+
* host's hold back). It must be called exactly once by whoever owns the socket —
|
|
2293
|
+
* on failure, on close, and on dispose. A direct route has nothing to release,
|
|
2294
|
+
* so it gets a no-op.
|
|
2295
|
+
*/
|
|
2296
|
+
private async openRoute(alias: string, route: ResolvedProxy = this.store.resolveProxy(alias)): Promise<RoutedDial> {
|
|
2297
|
+
const host: RemoteHostEntry = this.store.require(alias)
|
|
2298
|
+
/** The socket ssh2 will ride, when a proxy/jump built one. */
|
|
2299
|
+
let sock: Duplex | undefined
|
|
2300
|
+
/** Runs once: tears the tunnel down (close the channel, release the jump). */
|
|
2301
|
+
let releaseTunnel: (() => void) | undefined
|
|
2302
|
+
if (route.kind === 'proxy') {
|
|
2303
|
+
try {
|
|
2304
|
+
sock = await openProxySocket(route.proxy, host.host, host.port)
|
|
2305
|
+
} catch (error) {
|
|
2306
|
+
throw proxyDialError(error, route.proxy)
|
|
2307
|
+
}
|
|
2308
|
+
releaseTunnel = () => {
|
|
2309
|
+
try {
|
|
2310
|
+
sock?.destroy()
|
|
2311
|
+
} catch {
|
|
2312
|
+
// Already gone (ssh2 closes it with the connection).
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
} else if (route.kind === 'jump') {
|
|
2316
|
+
const via = route.viaAlias
|
|
2317
|
+
try {
|
|
2318
|
+
await this.acquire(via)
|
|
2319
|
+
this.hold(via)
|
|
2320
|
+
} catch (error) {
|
|
2321
|
+
throw new Error(`jump host "${via}" failed: ${messageOf(error)}`)
|
|
2322
|
+
}
|
|
2323
|
+
let channel: ClientChannel
|
|
2324
|
+
try {
|
|
2325
|
+
// Reuse the SHARED jump-host connection that `acquire`+`hold` just
|
|
2326
|
+
// established. `forwardOut` prefers a dedicated per-purpose connection by
|
|
2327
|
+
// default, which here would dial the SAME jump host a second time for a
|
|
2328
|
+
// tunnel that already holds the first one (an extra handshake per jump
|
|
2329
|
+
// dial, and a second connection to a host we are already connected to).
|
|
2330
|
+
channel = (await this.forwardOut(via, host.host, host.port, 0, { dedicated: false })).channel
|
|
2331
|
+
} catch (error) {
|
|
2332
|
+
this.release(via)
|
|
2333
|
+
throw new Error(`jump host "${via}" failed: ${messageOf(error)}`)
|
|
2334
|
+
}
|
|
2335
|
+
let released = false
|
|
2336
|
+
releaseTunnel = () => {
|
|
2337
|
+
if (released) return
|
|
2338
|
+
released = true
|
|
2339
|
+
try {
|
|
2340
|
+
channel.close()
|
|
2341
|
+
} catch {
|
|
2342
|
+
// Already gone.
|
|
2343
|
+
}
|
|
2344
|
+
this.release(via)
|
|
2345
|
+
}
|
|
2346
|
+
// A channel is a duplex stream: ssh2 never learns it is not a raw socket.
|
|
2347
|
+
sock = channel as unknown as Duplex
|
|
2348
|
+
}
|
|
2349
|
+
return {
|
|
2350
|
+
...(sock === undefined ? {} : { sock }),
|
|
2351
|
+
// A direct route has nothing to tear down; every other one does.
|
|
2352
|
+
release: releaseTunnel ?? (() => {}),
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
|
|
2356
|
+
/**
|
|
2357
|
+
* The routed transport for `alias`, for a caller that dials its OWN ssh2 client.
|
|
2358
|
+
*
|
|
2359
|
+
* Same decision, same error layering (`proxy auth failed: …`, `jump host "x"
|
|
2360
|
+
* failed: …`), same socket as a pooled connection would ride — p2's helper
|
|
2361
|
+
* transport uses this so "reachable only through the jump host" stops meaning
|
|
2362
|
+
* "exec works, files do not".
|
|
2363
|
+
*
|
|
2364
|
+
* **The caller owns the result**: when `sock` is set, ssh2 must be given `{ sock }`
|
|
2365
|
+
* and NOT `host`/`port` (both together let ssh2 choose between dialing the target
|
|
2366
|
+
* itself and riding the tunnel). `release` must be called exactly once — on
|
|
2367
|
+
* failure, on the connection's close, and on dispose — or the jump host's hold
|
|
2368
|
+
* leaks and the proxy socket stays open.
|
|
2369
|
+
*/
|
|
2370
|
+
async openRoutedSocket(alias: string): Promise<RoutedDial> {
|
|
2371
|
+
return this.openRoute(alias)
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
/**
|
|
2375
|
+
* Open one SSH connection, through whatever route the store resolves.
|
|
2376
|
+
*
|
|
2377
|
+
* Three routes, and only the first is the pre-proxy code path:
|
|
2378
|
+
* - `direct`: unchanged (`host` / `port` in the connect config);
|
|
2379
|
+
* - `proxy`: the proxy module builds the tunnel and ssh2 rides the returned
|
|
2380
|
+
* socket (`sock`), so `host`/`port` are deliberately omitted (ssh2 ignores
|
|
2381
|
+
* them when `sock` is present);
|
|
2382
|
+
* - `jump`: the tunnel is a `direct-tcpip` channel on the JUMP host's pooled
|
|
2383
|
+
* connection, held for as long as the client lives. Its close/error handlers
|
|
2384
|
+
* close that channel and give the hold back — a leak here would pin the jump
|
|
2385
|
+
* host's connection forever.
|
|
2386
|
+
*
|
|
2387
|
+
* Every failure is a DIAL failure, so it keeps the existing `markError`
|
|
2388
|
+
* semantics; only the message is layered, so the user can tell which hop broke:
|
|
2389
|
+
* `proxy auth failed: …`, `proxy refused: …`, `jump host "x" failed: …`.
|
|
2390
|
+
*
|
|
2391
|
+
* `report` receives the route this dial ACTUALLY settled on, once and only on
|
|
2392
|
+
* success — a caller that asked "did this go through the jump host?" must not
|
|
2393
|
+
* be answered from a configuration that may have changed since. It is a
|
|
2394
|
+
* callback rather than a wider return type so the seam keeps returning the
|
|
2395
|
+
* `Client` the existing callers (and gates) hand around.
|
|
2396
|
+
*/
|
|
2397
|
+
private async dial(alias: string, report?: (egress: EgressInfo) => void): Promise<Client> {
|
|
1466
2398
|
const host: RemoteHostEntry = this.store.require(alias)
|
|
2399
|
+
const route = this.store.resolveProxy(alias)
|
|
2400
|
+
const egress = egressOf(route, host)
|
|
2401
|
+
/**
|
|
2402
|
+
* The transport this connection rides. Resolved with the SAME route the egress
|
|
2403
|
+
* was computed from, so the reported hop and the socket can never disagree —
|
|
2404
|
+
* and `openRoute` builds it exactly the way this method used to inline
|
|
2405
|
+
* (proxy tunnel socket / jump-host `direct-tcpip` channel / nothing at all).
|
|
2406
|
+
*/
|
|
2407
|
+
const routed = await this.openRoute(alias, route)
|
|
1467
2408
|
return new Promise<Client>((resolve, reject) => {
|
|
1468
2409
|
const conn = this.makeClient()
|
|
1469
2410
|
let settled = false
|
|
@@ -1477,12 +2418,14 @@ export class RemotePool {
|
|
|
1477
2418
|
} catch {
|
|
1478
2419
|
// Ignore.
|
|
1479
2420
|
}
|
|
2421
|
+
routed.release()
|
|
1480
2422
|
reject(explainAuthError(host, error))
|
|
1481
2423
|
}
|
|
1482
2424
|
conn.on('ready', () => {
|
|
1483
2425
|
if (settled) return
|
|
1484
2426
|
settled = true
|
|
1485
2427
|
if (guard !== undefined) clearTimeout(guard)
|
|
2428
|
+
report?.(egress)
|
|
1486
2429
|
resolve(conn)
|
|
1487
2430
|
})
|
|
1488
2431
|
conn.on('error', (error: Error) => fail(error))
|
|
@@ -1494,6 +2437,10 @@ export class RemotePool {
|
|
|
1494
2437
|
* leave this promise pending forever while the caller held a channel slot.
|
|
1495
2438
|
*/
|
|
1496
2439
|
conn.on('close', () => fail(new Error('connection closed during SSH handshake')))
|
|
2440
|
+
// The tunnel belongs to the connection: however the client ends, the channel
|
|
2441
|
+
// and the jump host's hold go with it (idempotent; `fail` may have run).
|
|
2442
|
+
conn.once('close', () => routed.release())
|
|
2443
|
+
conn.once('error', () => routed.release())
|
|
1497
2444
|
// Last resort: the library reports nothing at all (neither ready, nor
|
|
1498
2445
|
// error, nor close). `readyTimeout` cannot cover it because ssh2 clears
|
|
1499
2446
|
// that timer as soon as the socket closes without emitting an error.
|
|
@@ -1535,11 +2482,13 @@ export class RemotePool {
|
|
|
1535
2482
|
return true
|
|
1536
2483
|
}
|
|
1537
2484
|
try {
|
|
2485
|
+
const transport = routed.sock === undefined
|
|
2486
|
+
? { host: host.host, port: host.port }
|
|
2487
|
+
: { sock: routed.sock }
|
|
1538
2488
|
if (host.auth.kind === 'key') {
|
|
1539
2489
|
const keyPath = host.auth.keyPath as string
|
|
1540
2490
|
conn.connect({
|
|
1541
|
-
|
|
1542
|
-
port: host.port,
|
|
2491
|
+
...transport,
|
|
1543
2492
|
username: host.user,
|
|
1544
2493
|
privateKey: readFileSync(keyPath),
|
|
1545
2494
|
passphrase: host.auth.passphrase,
|
|
@@ -1550,8 +2499,7 @@ export class RemotePool {
|
|
|
1550
2499
|
})
|
|
1551
2500
|
} else {
|
|
1552
2501
|
conn.connect({
|
|
1553
|
-
|
|
1554
|
-
port: host.port,
|
|
2502
|
+
...transport,
|
|
1555
2503
|
username: host.user,
|
|
1556
2504
|
password: host.auth.password,
|
|
1557
2505
|
tryKeyboard: true,
|
|
@@ -1568,6 +2516,78 @@ export class RemotePool {
|
|
|
1568
2516
|
}
|
|
1569
2517
|
}
|
|
1570
2518
|
|
|
2519
|
+
/**
|
|
2520
|
+
* The route one resolved proxy decision describes, in the shape the chip prints.
|
|
2521
|
+
*
|
|
2522
|
+
* `detail` is the HOP, never a sentence: the target `host:port` for a direct
|
|
2523
|
+
* connection, the proxy `host:port` for a tunnel, the jump host's alias for a
|
|
2524
|
+
* chain. The wording belongs to the localized client — a second English sentence
|
|
2525
|
+
* baked in here would leak into the Chinese tooltip.
|
|
2526
|
+
*/
|
|
2527
|
+
function egressOf(route: ResolvedProxy, host: RemoteHostEntry): EgressInfo {
|
|
2528
|
+
if (route.kind === 'proxy') {
|
|
2529
|
+
return {
|
|
2530
|
+
kind: 'proxy',
|
|
2531
|
+
detail: `${route.proxy.host}:${route.proxy.port}`,
|
|
2532
|
+
source: route.source,
|
|
2533
|
+
proxyKind: route.proxy.kind,
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
if (route.kind === 'jump') return { kind: 'jump', detail: route.viaAlias, viaAlias: route.viaAlias }
|
|
2537
|
+
return { kind: 'direct', detail: `${host.host}:${host.port}` }
|
|
2538
|
+
}
|
|
2539
|
+
|
|
2540
|
+
/**
|
|
2541
|
+
* Best-effort route from the STORED fields, for the one case `resolveProxy`
|
|
2542
|
+
* refuses to answer (a dangling jump chain, a self-jump, a proxy setting that
|
|
2543
|
+
* does not validate). The caller adds `problem` with the reason; the shape here
|
|
2544
|
+
* only says WHICH kind of route is broken, so the chip can name it.
|
|
2545
|
+
*/
|
|
2546
|
+
function storedEgress(host: RemoteHostEntry): EgressInfo {
|
|
2547
|
+
const jump = host.proxy?.jump?.viaAlias
|
|
2548
|
+
if (host.proxy?.mode === 'jump') {
|
|
2549
|
+
return { kind: 'jump', detail: jump ?? '', ...(jump === undefined ? {} : { viaAlias: jump }) }
|
|
2550
|
+
}
|
|
2551
|
+
const proxy = host.proxy?.proxy
|
|
2552
|
+
if (proxy !== undefined) {
|
|
2553
|
+
return { kind: 'proxy', detail: `${proxy.host}:${proxy.port}`, proxyKind: proxy.kind }
|
|
2554
|
+
}
|
|
2555
|
+
return { kind: 'direct', detail: `${host.host}:${host.port}` }
|
|
2556
|
+
}
|
|
2557
|
+
|
|
2558
|
+
/** Message of an unknown thrown value, without assuming it is an `Error`. */
|
|
2559
|
+
function messageOf(error: unknown): string {
|
|
2560
|
+
return error instanceof Error ? error.message : String(error ?? '')
|
|
2561
|
+
}
|
|
2562
|
+
|
|
2563
|
+
/**
|
|
2564
|
+
* Fixed prefix per proxy failure reason.
|
|
2565
|
+
*
|
|
2566
|
+
* The dial fails either way; the prefix is what tells the user WHICH layer broke —
|
|
2567
|
+
* their password, the proxy host, the tunnel policy, or the destination. The raw
|
|
2568
|
+
* detail is kept after it, so nothing is lost.
|
|
2569
|
+
*/
|
|
2570
|
+
const PROXY_FAILURE_PREFIX: Record<ProxyFailure, string> = {
|
|
2571
|
+
unreachable: 'proxy unreachable',
|
|
2572
|
+
timeout: 'proxy timed out',
|
|
2573
|
+
auth: 'proxy auth failed',
|
|
2574
|
+
refused: 'proxy refused',
|
|
2575
|
+
protocol: 'proxy protocol error',
|
|
2576
|
+
target: 'proxy target invalid',
|
|
2577
|
+
}
|
|
2578
|
+
|
|
2579
|
+
/** One proxy dial failure, with the layer in front of the original message. */
|
|
2580
|
+
function proxyDialError(error: unknown, proxy: ProxyConfig): Error {
|
|
2581
|
+
if (error instanceof ProxyError) {
|
|
2582
|
+
const prefix = PROXY_FAILURE_PREFIX[error.reason]
|
|
2583
|
+
// A bad destination is not the proxy's address; naming the proxy there would
|
|
2584
|
+
// send the user to the wrong field.
|
|
2585
|
+
const where = error.reason === 'target' ? '' : ` ${proxy.kind} proxy ${proxy.host}:${proxy.port}`
|
|
2586
|
+
return new Error(`${prefix}${where}: ${error.message}`)
|
|
2587
|
+
}
|
|
2588
|
+
return new Error(`proxy failed: ${proxy.kind} proxy ${proxy.host}:${proxy.port}: ${messageOf(error)}`)
|
|
2589
|
+
}
|
|
2590
|
+
|
|
1571
2591
|
/**
|
|
1572
2592
|
* Translate ssh2's generic auth failure into something actionable. Never
|
|
1573
2593
|
* includes secrets — only the entry shape and the likely server-side causes.
|