dsh-remote-go 0.1.0 → 0.2.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.md +56 -95
- package/client.js +3121 -330
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +12 -11
- package/src/admission.js +43 -0
- package/src/api.js +219 -23
- package/src/atomic-json.js +19 -2
- package/src/bootstrap.js +14 -1
- package/src/connect-log.js +145 -8
- package/src/connect-pipeline.js +1545 -108
- package/src/connect-progress.js +28 -8
- package/src/constants.js +65 -3
- package/src/diagnostics.js +3 -0
- package/src/download-jobs.js +17 -0
- package/src/errors.js +98 -2
- package/src/host-lifecycle.js +434 -17
- package/src/host-registry.js +78 -6
- package/src/host-runtime.js +74 -0
- package/src/host-view.js +28 -4
- package/src/index.js +47 -3
- package/src/key-files.js +6 -1
- package/src/known-hosts.js +50 -11
- package/src/layout.js +28 -10
- package/src/local-download.js +232 -13
- package/src/probe.js +13 -1
- package/src/prompts.js +114 -17
- package/src/redact.js +17 -3
- package/src/remote-files.js +2 -2
- package/src/remote-path.js +64 -0
- package/src/remote-proc.js +135 -0
- package/src/remote-proxy.js +815 -0
- package/src/remote-web.js +479 -28
- package/src/request-trust.js +89 -0
- package/src/secrets.js +38 -8
- package/src/service.js +222 -13
- package/src/settings.js +30 -2
- package/src/ssh.js +108 -29
- package/src/store.js +58 -8
- package/src/tools.js +386 -0
- package/src/tunnel.js +60 -1
- package/src/webapp.js +15 -0
- package/vendor/THIRD_PARTY_NOTICES.md +27 -1
- package/vendor/ssh2-entry.mjs +0 -12
package/src/host-lifecycle.js
CHANGED
|
@@ -1,12 +1,22 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Per-host lifecycle: the reconnect backoff, the idle-stop timer and the single teardown path; the reconnect timer gets a callback, so this never imports the pipeline.
|
|
3
3
|
*/
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
DEFAULT_IDLE_MINUTES,
|
|
6
|
+
REMOTE_EPISODE_COOLDOWN_MS,
|
|
7
|
+
REMOTE_HEARTBEAT_DEFAULT_SEC,
|
|
8
|
+
REMOTE_HEARTBEAT_MAX_SEC,
|
|
9
|
+
REMOTE_HEARTBEAT_MIN_SEC,
|
|
10
|
+
REMOTE_TUNNEL_REPAIR_SETTLE_MS,
|
|
11
|
+
REMOTE_UNREACHABLE_FAILURES,
|
|
12
|
+
} from './constants.js'
|
|
5
13
|
import { errors, toErrorView } from './errors.js'
|
|
6
14
|
import { emptyRemote } from './host-runtime.js'
|
|
7
|
-
import {
|
|
8
|
-
import { cancelConflict } from './prompts.js'
|
|
9
|
-
import {
|
|
15
|
+
import { layoutForRuntime } from './layout.js'
|
|
16
|
+
import { cancelConflict, cancelHostKeyPrompt } from './prompts.js'
|
|
17
|
+
import { isUiUp } from './remote-proc.js'
|
|
18
|
+
import { commandMatchesProfile } from './remote-web.js'
|
|
19
|
+
import { isPid, messageOf, randomDelay } from './util.js'
|
|
10
20
|
|
|
11
21
|
export function cancelReconnect(runtime) {
|
|
12
22
|
if (runtime.reconnectTimer) {
|
|
@@ -22,11 +32,238 @@ export function cancelIdleStop(runtime) {
|
|
|
22
32
|
}
|
|
23
33
|
}
|
|
24
34
|
|
|
35
|
+
/**
|
|
36
|
+
* One-shot link actions (a local restart, a remote re-attach, a tunnel rebuild) share a
|
|
37
|
+
* token so a disconnect, a dropped transport or a newer action can invalidate an older one:
|
|
38
|
+
* an action must never write state on top of whatever replaced it.
|
|
39
|
+
* @param {object} runtime - host runtime.
|
|
40
|
+
* @param {string} kind - `restart`, `reattach`, `repair` or `stop`.
|
|
41
|
+
* @returns {number} the token that owns the action.
|
|
42
|
+
*/
|
|
43
|
+
export function beginLinkWork(runtime, kind) {
|
|
44
|
+
runtime.linkToken = (Number(runtime.linkToken) || 0) + 1
|
|
45
|
+
runtime.linkBusy = kind
|
|
46
|
+
return runtime.linkToken
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function isLinkWorkCurrent(runtime, token) {
|
|
50
|
+
return runtime.linkToken === token
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function endLinkWork(runtime, token) {
|
|
54
|
+
if (!isLinkWorkCurrent(runtime, token)) return
|
|
55
|
+
runtime.linkBusy = null
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Invalidate whatever one-shot action was running; safe when there is none. */
|
|
59
|
+
export function cancelLinkWork(runtime) {
|
|
60
|
+
runtime.linkToken = (Number(runtime.linkToken) || 0) + 1
|
|
61
|
+
runtime.linkBusy = null
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Milliseconds between liveness probes, from settings (default 30s, disabled allowed). */
|
|
65
|
+
export function remoteHeartbeatIntervalSec(ctx) {
|
|
66
|
+
const raw = ctx.settings()?.remoteHeartbeat
|
|
67
|
+
const seconds = Number(raw?.intervalSec)
|
|
68
|
+
if (!Number.isFinite(seconds)) return REMOTE_HEARTBEAT_DEFAULT_SEC
|
|
69
|
+
return Math.min(REMOTE_HEARTBEAT_MAX_SEC, Math.max(REMOTE_HEARTBEAT_MIN_SEC, Math.round(seconds)))
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function cancelRemoteCheck(runtime) {
|
|
73
|
+
if (runtime.remoteCheckTimer) {
|
|
74
|
+
clearTimeout(runtime.remoteCheckTimer)
|
|
75
|
+
runtime.remoteCheckTimer = null
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Stop probing: called on connect, disconnect, re-attach and shutdown. */
|
|
80
|
+
export function stopRemoteHeartbeat(runtime) {
|
|
81
|
+
if (runtime.heartbeatTimer) {
|
|
82
|
+
clearInterval(runtime.heartbeatTimer)
|
|
83
|
+
runtime.heartbeatTimer = null
|
|
84
|
+
}
|
|
85
|
+
cancelRemoteCheck(runtime)
|
|
86
|
+
runtime.remoteFailures = 0
|
|
87
|
+
runtime.remoteEpisode = false
|
|
88
|
+
runtime.episodeSource = null
|
|
89
|
+
// A new attach starts a new episode budget; the cooldown only exists to damp one connection.
|
|
90
|
+
runtime.episodeCooldownUntil = 0
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Start the light liveness probe for a host that just became connected. */
|
|
94
|
+
export function startRemoteHeartbeat(ctx, runtime) {
|
|
95
|
+
stopRemoteHeartbeat(runtime)
|
|
96
|
+
const enabled = ctx.settings()?.remoteHeartbeat?.enabled !== false
|
|
97
|
+
if (!enabled) {
|
|
98
|
+
ctx.progress.log(runtime, 'debug', 'remote heartbeat: disabled by settings')
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
const intervalSec = remoteHeartbeatIntervalSec(ctx)
|
|
102
|
+
runtime.heartbeatTimer = setInterval(() => {
|
|
103
|
+
void remoteHeartbeatTick(ctx, runtime)
|
|
104
|
+
}, intervalSec * 1000)
|
|
105
|
+
runtime.heartbeatTimer.unref?.()
|
|
106
|
+
ctx.progress.log(runtime, 'debug', `remote heartbeat: probing every ${intervalSec}s`)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** A host is watchable only while it is really up and no one-shot action owns the link. */
|
|
110
|
+
function watchable(ctx, runtime) {
|
|
111
|
+
return (
|
|
112
|
+
ctx.state.disposed !== true &&
|
|
113
|
+
runtime.desired === 'connected' &&
|
|
114
|
+
runtime.status === 'connected' &&
|
|
115
|
+
runtime.linkBusy === null &&
|
|
116
|
+
runtime.ssh?.connected === true &&
|
|
117
|
+
runtime.tunnel !== null
|
|
118
|
+
)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Open a liveness episode at most once. Transient reports (a proxy/tunnel failure) are
|
|
123
|
+
* coalesced: after a confirmed-healthy episode the same kind of report is ignored for a
|
|
124
|
+
* cooldown window, so a flapping tunnel cannot emit suspected/recovered on every request.
|
|
125
|
+
* Returns whether a new episode was opened.
|
|
126
|
+
*/
|
|
127
|
+
function beginRemoteEpisode(ctx, runtime, source) {
|
|
128
|
+
if (runtime.remoteEpisode === true) return false
|
|
129
|
+
const transient = source === 'proxy' || source === 'tunnel'
|
|
130
|
+
if (transient && Date.now() < (Number(runtime.episodeCooldownUntil) || 0)) {
|
|
131
|
+
ctx.progress.log(runtime, 'debug', `remote-unreachable reported again (${source}); episode cooldown, ignoring`)
|
|
132
|
+
return false
|
|
133
|
+
}
|
|
134
|
+
runtime.remoteEpisode = true
|
|
135
|
+
runtime.episodeSource = source
|
|
136
|
+
ctx.progress.log(runtime, 'debug', `remote-unreachable suspected (${source}); confirming with probes`)
|
|
137
|
+
ctx.onRemoteUnreachable?.(runtime, { phase: 'suspected', source })
|
|
138
|
+
return true
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Reset the failure streak; report the recovery once when an episode was open. A transient
|
|
143
|
+
* episode also rebuilds the local listener: the remote answering the probe while the page
|
|
144
|
+
* got a 502 usually means the tunnel, not the remote, is what broke.
|
|
145
|
+
*/
|
|
146
|
+
async function clearRemoteEpisode(ctx, runtime, source) {
|
|
147
|
+
const wasOpen = runtime.remoteEpisode === true
|
|
148
|
+
const transient = runtime.episodeSource === 'proxy' || runtime.episodeSource === 'tunnel'
|
|
149
|
+
runtime.remoteEpisode = false
|
|
150
|
+
runtime.remoteFailures = 0
|
|
151
|
+
if (!wasOpen) return
|
|
152
|
+
runtime.episodeSource = null
|
|
153
|
+
if (transient) {
|
|
154
|
+
runtime.episodeCooldownUntil = Date.now() + REMOTE_EPISODE_COOLDOWN_MS
|
|
155
|
+
// The SSH probe only proves the remote side answers. Ask the local listener first: if it
|
|
156
|
+
// still serves, a single failed upstream connection is not a broken tunnel and rebuilding
|
|
157
|
+
// would drop live WebSockets for nothing.
|
|
158
|
+
let healthy = false
|
|
159
|
+
try {
|
|
160
|
+
healthy = (await ctx.deps.tunnelProbe?.(runtime.tunnel?.localPort ?? null)) === true
|
|
161
|
+
} catch {
|
|
162
|
+
// swallow-ok: a probe error means "not healthy"; the rebuild path reports its own failure
|
|
163
|
+
}
|
|
164
|
+
if (healthy) {
|
|
165
|
+
ctx.progress.log(runtime, 'debug', 'the local tunnel still answers; keeping the listener')
|
|
166
|
+
} else {
|
|
167
|
+
try {
|
|
168
|
+
const repaired = await ctx.repairTunnel?.(runtime)
|
|
169
|
+
if (repaired && repaired.ok !== true) {
|
|
170
|
+
ctx.progress.log(runtime, 'debug', `tunnel rebuild skipped (${repaired.reason ?? 'unknown'})`)
|
|
171
|
+
}
|
|
172
|
+
} catch (error) {
|
|
173
|
+
// swallow-ok: a failed repair is reported by the helper; the episode still recovers
|
|
174
|
+
ctx.progress.log(runtime, 'warn', 'tunnel rebuild failed:', messageOf(error))
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
ctx.progress.log(runtime, 'info', `remote heartbeat: the remote UI answers again (${source})`)
|
|
179
|
+
if (!watchable(ctx, runtime)) return
|
|
180
|
+
ctx.onRemoteUnreachable?.(runtime, { phase: 'recovered', source })
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function scheduleRemoteCheck(ctx, runtime, source, delayMs) {
|
|
184
|
+
if (runtime.remoteCheckTimer) return
|
|
185
|
+
runtime.remoteCheckTimer = setTimeout(() => {
|
|
186
|
+
runtime.remoteCheckTimer = null
|
|
187
|
+
void checkRemoteNow(ctx, runtime, source)
|
|
188
|
+
}, delayMs)
|
|
189
|
+
runtime.remoteCheckTimer.unref?.()
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Probe the connected host once and feed the consecutive-failure counter. One
|
|
194
|
+
* failed request is not a restart: the counter has to reach
|
|
195
|
+
* {@link REMOTE_UNREACHABLE_FAILURES} before a re-attach is requested.
|
|
196
|
+
*/
|
|
197
|
+
async function checkRemoteNow(ctx, runtime, source) {
|
|
198
|
+
if (!watchable(ctx, runtime) || typeof ctx.deps.remoteStatus !== 'function') return
|
|
199
|
+
const ssh = runtime.ssh
|
|
200
|
+
const port = runtime.remote.port
|
|
201
|
+
let status = null
|
|
202
|
+
try {
|
|
203
|
+
status = await ctx.deps.remoteStatus(ssh, port)
|
|
204
|
+
} catch {
|
|
205
|
+
// swallow-ok: an unreachable probe is a failed probe, handled by the same counter
|
|
206
|
+
status = null
|
|
207
|
+
}
|
|
208
|
+
// The transport may have gone away while the probe was in flight; the close handler owns that.
|
|
209
|
+
if (!watchable(ctx, runtime) || runtime.ssh !== ssh) return
|
|
210
|
+
if (isUiUp(status)) {
|
|
211
|
+
await clearRemoteEpisode(ctx, runtime, source)
|
|
212
|
+
return
|
|
213
|
+
}
|
|
214
|
+
runtime.remoteFailures = (Number(runtime.remoteFailures) || 0) + 1
|
|
215
|
+
ctx.progress.log(
|
|
216
|
+
runtime,
|
|
217
|
+
'debug',
|
|
218
|
+
`remote heartbeat: probe failed (HTTP ${status ?? 'none'}), ${runtime.remoteFailures}/${REMOTE_UNREACHABLE_FAILURES} (${source})`,
|
|
219
|
+
)
|
|
220
|
+
beginRemoteEpisode(ctx, runtime, source)
|
|
221
|
+
if (runtime.remoteFailures < REMOTE_UNREACHABLE_FAILURES) {
|
|
222
|
+
scheduleRemoteCheck(ctx, runtime, source, ctx.timers.remoteRecheckMs)
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
ctx.progress.log(
|
|
226
|
+
runtime,
|
|
227
|
+
'warn',
|
|
228
|
+
`remote-unreachable: ${runtime.remoteFailures} consecutive probes failed (${source}); re-attaching`,
|
|
229
|
+
)
|
|
230
|
+
ctx.onRemoteUnreachable?.(runtime, {
|
|
231
|
+
phase: 'confirmed',
|
|
232
|
+
source,
|
|
233
|
+
failures: runtime.remoteFailures,
|
|
234
|
+
})
|
|
235
|
+
cancelRemoteCheck(runtime)
|
|
236
|
+
ctx.requestReattach?.(runtime, { reason: `probe-failed-${runtime.remoteFailures}`, source })
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** One scheduled heartbeat tick. */
|
|
240
|
+
export async function remoteHeartbeatTick(ctx, runtime) {
|
|
241
|
+
if (!watchable(ctx, runtime)) return
|
|
242
|
+
if (runtime.remoteCheckTimer) return
|
|
243
|
+
await checkRemoteNow(ctx, runtime, 'heartbeat')
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* A proxy or tunnel failure was observed: report the episode once and confirm it
|
|
248
|
+
* with probes instead of treating one failed request as a remote restart.
|
|
249
|
+
*/
|
|
250
|
+
export function noteRemoteUnreachable(ctx, runtime, source) {
|
|
251
|
+
if (!watchable(ctx, runtime)) return
|
|
252
|
+
if (!beginRemoteEpisode(ctx, runtime, source)) return
|
|
253
|
+
scheduleRemoteCheck(ctx, runtime, source, ctx.timers.remoteConfirmDelayMs)
|
|
254
|
+
}
|
|
255
|
+
|
|
25
256
|
/**
|
|
26
257
|
* Arm the next reconnect attempt, or give up once the configured budget is spent.
|
|
27
258
|
*/
|
|
28
259
|
export function scheduleReconnect(ctx, runtime, onDue) {
|
|
29
260
|
cancelReconnect(runtime)
|
|
261
|
+
// A retry only makes sense while the user still wants the link: a disconnect, a host
|
|
262
|
+
// removal or a shutdown that raced the timer must not resurrect the connection.
|
|
263
|
+
if (ctx.state.disposed === true || runtime.desired !== 'connected') {
|
|
264
|
+
ctx.progress.set(runtime, { status: 'disconnected' })
|
|
265
|
+
return
|
|
266
|
+
}
|
|
30
267
|
const settings = ctx.settings()
|
|
31
268
|
if (!runtime.entry.autoReconnect || !settings.autoReconnect.enabled) {
|
|
32
269
|
ctx.progress.set(runtime, { status: 'disconnected' })
|
|
@@ -61,6 +298,8 @@ export function scheduleReconnect(ctx, runtime, onDue) {
|
|
|
61
298
|
runtime.reconnectTimer = null
|
|
62
299
|
onDue()
|
|
63
300
|
}, delay)
|
|
301
|
+
// A pending retry must never keep the host process alive on its own.
|
|
302
|
+
runtime.reconnectTimer.unref?.()
|
|
64
303
|
}
|
|
65
304
|
|
|
66
305
|
function scheduleIdleStop(ctx, runtime) {
|
|
@@ -68,28 +307,130 @@ function scheduleIdleStop(ctx, runtime) {
|
|
|
68
307
|
const minutes = Math.max(1, runtime.entry.idleMinutes ?? DEFAULT_IDLE_MINUTES)
|
|
69
308
|
runtime.idleTimer = setTimeout(() => {
|
|
70
309
|
runtime.idleTimer = null
|
|
71
|
-
void
|
|
310
|
+
void stopRemoteForIdle(ctx, runtime)
|
|
72
311
|
}, minutes * 60_000)
|
|
312
|
+
runtime.idleTimer.unref?.()
|
|
73
313
|
}
|
|
74
314
|
|
|
75
|
-
/**
|
|
76
|
-
|
|
315
|
+
/**
|
|
316
|
+
* Best-effort stop of the remote web for the idle policy, then drop the transport.
|
|
317
|
+
*
|
|
318
|
+
* The teardown that armed this timer clears `facts` and `remote`, so the stop has to use the
|
|
319
|
+
* home and pid remembered before that clearing: the old fallback built a layout with a
|
|
320
|
+
* literal `~`, whose `kill -0` is a no-op that still reported success (H1).
|
|
321
|
+
*
|
|
322
|
+
* The timer is a *policy for an idle host*, never authority over a live link: the user may
|
|
323
|
+
* have connected again (the timer would otherwise kill the link just brought up), and a pid
|
|
324
|
+
* that answers `/proc` is not proof it is still the process this connection started
|
|
325
|
+
* (review: idle-timer zombie / pid reuse). Shutdown is the one caller that deliberately
|
|
326
|
+
* overrides the "still wanted" guard, because it is stopping the whole host process.
|
|
327
|
+
*
|
|
328
|
+
* @param {object} ctx - service context.
|
|
329
|
+
* @param {object} runtime - host runtime that went idle.
|
|
330
|
+
* @param {{ shutdown?: boolean }} [options]
|
|
331
|
+
* @returns {Promise<{ ok: boolean, reason?: string }>} the stop verdict (best effort).
|
|
332
|
+
*/
|
|
333
|
+
export async function stopRemoteForIdle(ctx, runtime, options = {}) {
|
|
334
|
+
// A live link wins over the idle policy, whichever timer fired it. This is what keeps a
|
|
335
|
+
// manual reconnect from being torn down by the timer armed before it.
|
|
336
|
+
const linkLive = runtime.desired === 'connected' || runtime.status === 'connected' || runtime.tunnel !== null
|
|
337
|
+
if (linkLive && options.shutdown !== true) {
|
|
338
|
+
ctx.progress.log(runtime, 'debug', 'idle stop skipped: the host is connected again')
|
|
339
|
+
return { ok: false, reason: 'still-wanted' }
|
|
340
|
+
}
|
|
341
|
+
// The transport this call owns: the identity proof below awaits, and the user may connect
|
|
342
|
+
// in that window. Only this session may be released afterwards, never the new one.
|
|
343
|
+
const capturedSsh = runtime.ssh
|
|
344
|
+
const stillWanted = () =>
|
|
345
|
+
runtime.ssh !== capturedSsh ||
|
|
346
|
+
runtime.desired === 'connected' ||
|
|
347
|
+
runtime.status === 'connected' ||
|
|
348
|
+
runtime.tunnel !== null
|
|
77
349
|
try {
|
|
78
|
-
if (
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
350
|
+
if (capturedSsh?.connected !== true) return { ok: false, reason: 'no-transport' }
|
|
351
|
+
const home = runtime.facts?.home ?? runtime.remoteHome ?? null
|
|
352
|
+
if (typeof home !== 'string' || home.trim() === '') {
|
|
353
|
+
ctx.progress.log(runtime, 'warn', 'idle stop skipped: the remote home directory is unknown')
|
|
354
|
+
return { ok: false, reason: 'no-home' }
|
|
82
355
|
}
|
|
356
|
+
const layout = layoutForRuntime(runtime)
|
|
357
|
+
const pid = Number(runtime.remote.pid ?? runtime.remotePid ?? 0)
|
|
358
|
+
// Without a pid there is nothing this policy may signal: `stopRemoteWeb` would fall back
|
|
359
|
+
// to the run registry and could stop an instance this connection did not launch.
|
|
360
|
+
if (!isPid(pid)) return { ok: false, reason: 'pid-unknown' }
|
|
361
|
+
// Same `/proc` identity proof the explicit stop uses: a reused pid, another DSH home or
|
|
362
|
+
// another profile is not this connection's process and must not be signalled.
|
|
363
|
+
const proof = await proveIdleStopTarget(ctx, runtime, pid, layout)
|
|
364
|
+
if (proof.ok !== true) {
|
|
365
|
+
ctx.progress.log(runtime, 'warn', `idle stop skipped: ${proof.reason}`)
|
|
366
|
+
return { ok: false, reason: proof.reason }
|
|
367
|
+
}
|
|
368
|
+
// The user may have connected while the identity was read: the link wins again.
|
|
369
|
+
if (options.shutdown !== true && stillWanted()) {
|
|
370
|
+
ctx.progress.log(runtime, 'debug', 'idle stop skipped: the host is connected again')
|
|
371
|
+
return { ok: false, reason: 'still-wanted' }
|
|
372
|
+
}
|
|
373
|
+
const stopped = await ctx.deps.stopWeb(capturedSsh, layout, { pid })
|
|
374
|
+
if (stopped?.ok !== true) {
|
|
375
|
+
ctx.progress.log(
|
|
376
|
+
runtime,
|
|
377
|
+
'warn',
|
|
378
|
+
`idle stop did not confirm (${stopped?.reason ?? 'unknown'}); the remote may still be running`,
|
|
379
|
+
)
|
|
380
|
+
return { ok: false, reason: stopped?.reason ?? 'not-confirmed' }
|
|
381
|
+
}
|
|
382
|
+
runtime.remotePid = null
|
|
383
|
+
return { ok: true }
|
|
83
384
|
} catch (error) {
|
|
385
|
+
// swallow-ok: the idle stop is best effort; its failure is only a warning and the timer
|
|
386
|
+
// is already gone, so the host stays idle either way
|
|
84
387
|
ctx.progress.log(runtime, 'warn', 'idle stop failed:', messageOf(error))
|
|
388
|
+
return { ok: false, reason: 'error' }
|
|
85
389
|
} finally {
|
|
86
|
-
|
|
390
|
+
// Release only the transport this call captured: when a new connection owns the link by
|
|
391
|
+
// now, its session is not ours to dispose.
|
|
392
|
+
if (runtime.ssh === capturedSsh) await disposeSsh(runtime)
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** The `/proc` identity proof for the process the idle policy is about to stop. */
|
|
397
|
+
async function proveIdleStopTarget(ctx, runtime, pid, layout) {
|
|
398
|
+
const bound = Number(runtime.bound?.pid) === pid ? runtime.bound : null
|
|
399
|
+
const launched = runtime.launched instanceof Map ? runtime.launched.get(pid) : null
|
|
400
|
+
const proof = bound ?? launched
|
|
401
|
+
if (!proof) return { ok: false, reason: 'not-owned' }
|
|
402
|
+
let identity = null
|
|
403
|
+
try {
|
|
404
|
+
identity = await ctx.deps.processIdentity(runtime.ssh, pid)
|
|
405
|
+
} catch {
|
|
406
|
+
// swallow-ok: an unreadable identity means "cannot prove it is ours", so no signal
|
|
407
|
+
return { ok: false, reason: 'identity-unreadable' }
|
|
408
|
+
}
|
|
409
|
+
if (identity?.ok !== true) {
|
|
410
|
+
return {
|
|
411
|
+
ok: false,
|
|
412
|
+
reason: identity?.reason === 'missing' ? 'identity-missing' : `identity-${identity?.reason ?? 'unknown'}`,
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
if (typeof proof.startTime === 'string' && proof.startTime !== '' && identity.startTime !== proof.startTime) {
|
|
416
|
+
return { ok: false, reason: 'pid-reused' }
|
|
417
|
+
}
|
|
418
|
+
if (identity.dshHome !== '' && identity.dshHome !== layout.dshHome) {
|
|
419
|
+
return { ok: false, reason: 'dsh-home-mismatch' }
|
|
420
|
+
}
|
|
421
|
+
const profile = runtime.remote.profile ?? runtime.remoteProfile ?? null
|
|
422
|
+
if (typeof profile === 'string' && profile !== '' && !commandMatchesProfile(identity.command, profile)) {
|
|
423
|
+
return { ok: false, reason: 'profile-mismatch' }
|
|
87
424
|
}
|
|
425
|
+
return { ok: true }
|
|
88
426
|
}
|
|
89
427
|
|
|
90
428
|
export async function closeTunnel(runtime) {
|
|
91
429
|
const tunnel = runtime.tunnel
|
|
92
430
|
runtime.tunnel = null
|
|
431
|
+
// `localPort` is a view of the live listener: a closed tunnel must not leave a stale port
|
|
432
|
+
// behind (the proxy and diagnostics read this field).
|
|
433
|
+
runtime.remote.localPort = null
|
|
93
434
|
if (tunnel) {
|
|
94
435
|
try {
|
|
95
436
|
await tunnel.close()
|
|
@@ -120,19 +461,74 @@ export async function disposeSsh(runtime) {
|
|
|
120
461
|
* `keepRemote` preserves the remote facts so the card still describes what is
|
|
121
462
|
* running on the other side.
|
|
122
463
|
*/
|
|
464
|
+
/**
|
|
465
|
+
* Wait for an in-flight tunnel rebuild (if any) after the caller cancelled link work.
|
|
466
|
+
* The rebuild closes its own replacement in `finally` when its token is gone, so awaiting
|
|
467
|
+
* here is what makes disconnect / removeHost / shutdown leak-free. Bounded: a stuck rebuild
|
|
468
|
+
* must not delay teardown forever; its token is already cancelled, so it cannot publish.
|
|
469
|
+
* @param {object} ctx - service context.
|
|
470
|
+
* @param {object} runtime - host runtime.
|
|
471
|
+
*/
|
|
472
|
+
async function settleTunnelRepair(ctx, runtime) {
|
|
473
|
+
const repair = runtime.tunnelRepair
|
|
474
|
+
if (!repair) return
|
|
475
|
+
const timeoutMs = Number(ctx.timers?.tunnelRepairSettleMs ?? REMOTE_TUNNEL_REPAIR_SETTLE_MS)
|
|
476
|
+
let timer = null
|
|
477
|
+
const timeout = new Promise((resolve) => {
|
|
478
|
+
timer = setTimeout(() => resolve('timeout'), Math.max(0, timeoutMs))
|
|
479
|
+
timer.unref?.()
|
|
480
|
+
})
|
|
481
|
+
try {
|
|
482
|
+
const outcome = await Promise.race([repair, timeout])
|
|
483
|
+
if (outcome === 'timeout') {
|
|
484
|
+
ctx.progress.log(runtime, 'warn', 'tunnel rebuild did not finish in time; abandoning it')
|
|
485
|
+
// The rebuild was cancelled via cancelLinkWork; its own finally will close any listener
|
|
486
|
+
// it creates. Clear the slot so teardown never waits on it again.
|
|
487
|
+
runtime.tunnelRepair = null
|
|
488
|
+
}
|
|
489
|
+
} catch {
|
|
490
|
+
// swallow-ok: the rebuild reports its own failure; teardown must still proceed
|
|
491
|
+
} finally {
|
|
492
|
+
if (timer !== null) clearTimeout(timer)
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
123
496
|
export async function teardownRuntime(ctx, runtime, options = {}) {
|
|
124
497
|
cancelConflict(runtime)
|
|
498
|
+
// A prompt parked on the transport that is about to go away can never be answered: settle
|
|
499
|
+
// it now instead of letting the connect promise wait for its 120s timeout (M1).
|
|
500
|
+
cancelHostKeyPrompt(runtime)
|
|
501
|
+
cancelLinkWork(runtime)
|
|
502
|
+
stopRemoteHeartbeat(runtime)
|
|
125
503
|
runtime.closing = true
|
|
126
504
|
cancelIdleStop(runtime)
|
|
505
|
+
// A tunnel rebuild owns a listener it may be creating right now. Cancel it (above), then
|
|
506
|
+
// wait for it to clean up: otherwise the listener would be assigned after this teardown.
|
|
507
|
+
await settleTunnelRepair(ctx, runtime)
|
|
508
|
+
// Remember where the remote lives before the facts below are cleared: the idle policy and
|
|
509
|
+
// a later stop still need the real home, never a literal `~` (H1).
|
|
510
|
+
if (typeof runtime.facts?.home === 'string' && runtime.facts.home.trim() !== '') {
|
|
511
|
+
runtime.remoteHome = runtime.facts.home
|
|
512
|
+
}
|
|
513
|
+
if (typeof runtime.remote.profile === 'string' && runtime.remote.profile !== '') {
|
|
514
|
+
runtime.remoteProfile = runtime.remote.profile
|
|
515
|
+
}
|
|
516
|
+
const boundPid = Number(runtime.remote.pid ?? 0)
|
|
517
|
+
if (isPid(boundPid)) runtime.remotePid = boundPid
|
|
518
|
+
let remoteStopped = false
|
|
127
519
|
if (options.stopRemote && runtime.ssh?.connected) {
|
|
128
520
|
try {
|
|
129
|
-
await ctx.deps.stopWeb(runtime.ssh,
|
|
521
|
+
const result = await ctx.deps.stopWeb(runtime.ssh, layoutForRuntime(runtime), {
|
|
130
522
|
pid: runtime.remote.pid ?? undefined,
|
|
131
523
|
})
|
|
524
|
+
// Only a confirmed stop means the pid is gone; a refusal keeps the memory so a later
|
|
525
|
+
// stop can try again instead of reporting a process that never stopped.
|
|
526
|
+
remoteStopped = result?.ok === true
|
|
132
527
|
} catch (error) {
|
|
133
528
|
ctx.progress.log(runtime, 'warn', 'stop remote failed:', messageOf(error))
|
|
134
529
|
}
|
|
135
530
|
}
|
|
531
|
+
if (remoteStopped) runtime.remotePid = null
|
|
136
532
|
await closeTunnel(runtime)
|
|
137
533
|
if (!options.keepSshForIdle) await disposeSsh(runtime)
|
|
138
534
|
if (!options.keepRemote) {
|
|
@@ -146,14 +542,26 @@ export async function teardownRuntime(ctx, runtime, options = {}) {
|
|
|
146
542
|
/**
|
|
147
543
|
* Tear one host down and leave it idle: the keep-alive policy decides whether the
|
|
148
544
|
* remote web is stopped and whether the transport survives for a fast resume.
|
|
545
|
+
* `stopped` says the caller already stopped the remote web itself (the explicit
|
|
546
|
+
* "stop remote DSH" action): the policy must then neither arm an idle stop nor send
|
|
547
|
+
* a second stop signal. That second signal would be based on a pid captured several
|
|
548
|
+
* SSH round-trips earlier - a pid the action just proved is the right one (or that
|
|
549
|
+
* it is already gone), so re-signalling it is at best redundant and at worst kills
|
|
550
|
+
* an unrelated process after a pid reuse.
|
|
149
551
|
*/
|
|
150
552
|
export async function disconnectHost(ctx, runtime, options = {}) {
|
|
151
553
|
ctx.progress.log(runtime, 'info', `disconnect requested (keepAlive=${runtime.entry.keepAlive})`)
|
|
152
554
|
runtime.desired = 'idle'
|
|
153
555
|
cancelReconnect(runtime)
|
|
556
|
+
cancelLinkWork(runtime)
|
|
557
|
+
stopRemoteHeartbeat(runtime)
|
|
154
558
|
const policy = runtime.entry.keepAlive
|
|
155
|
-
const
|
|
156
|
-
|
|
559
|
+
const alreadyStopped = options.stopped === true
|
|
560
|
+
const stopRemote = alreadyStopped !== true && (options.stopRemote === true || policy === 'stop')
|
|
561
|
+
await teardownRuntime(ctx, runtime, {
|
|
562
|
+
stopRemote,
|
|
563
|
+
keepSshForIdle: policy === 'idle' && !stopRemote && !alreadyStopped,
|
|
564
|
+
})
|
|
157
565
|
runtime.status = 'disconnected'
|
|
158
566
|
runtime.phase = null
|
|
159
567
|
runtime.progress = null
|
|
@@ -161,7 +569,7 @@ export async function disconnectHost(ctx, runtime, options = {}) {
|
|
|
161
569
|
runtime.remote.localPort = null
|
|
162
570
|
runtime.token = null
|
|
163
571
|
ctx.progress.set(runtime, {})
|
|
164
|
-
if (policy === 'idle' && !stopRemote) scheduleIdleStop(ctx, runtime)
|
|
572
|
+
if (policy === 'idle' && !stopRemote && !alreadyStopped) scheduleIdleStop(ctx, runtime)
|
|
165
573
|
return { ok: true }
|
|
166
574
|
}
|
|
167
575
|
|
|
@@ -171,11 +579,20 @@ export async function disconnectHost(ctx, runtime, options = {}) {
|
|
|
171
579
|
*/
|
|
172
580
|
export async function shutdownAll(ctx) {
|
|
173
581
|
for (const runtime of ctx.state.runtimes.values()) {
|
|
582
|
+
// Mark the link dead before the first await: a dependent action must not start (or
|
|
583
|
+
// retry) while shutdown is still walking the list (L).
|
|
584
|
+
runtime.closing = true
|
|
585
|
+
runtime.desired = 'idle'
|
|
174
586
|
cancelReconnect(runtime)
|
|
175
587
|
cancelIdleStop(runtime)
|
|
588
|
+
cancelLinkWork(runtime)
|
|
589
|
+
cancelHostKeyPrompt(runtime)
|
|
590
|
+
cancelConflict(runtime)
|
|
591
|
+
stopRemoteHeartbeat(runtime)
|
|
592
|
+
await settleTunnelRepair(ctx, runtime)
|
|
176
593
|
try {
|
|
177
594
|
if (runtime.entry.keepAlive === 'stop') {
|
|
178
|
-
await
|
|
595
|
+
await stopRemoteForIdle(ctx, runtime, { shutdown: true })
|
|
179
596
|
} else {
|
|
180
597
|
await closeTunnel(runtime)
|
|
181
598
|
await disposeSsh(runtime)
|