dsh-remote-go 0.1.0 → 0.3.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 +64 -95
- package/{client.js → dist/client.js} +7805 -5486
- package/dist/index.js +4 -0
- package/dist/src/admission.js +46 -0
- package/dist/src/api.js +442 -0
- package/dist/src/atomic-json.js +235 -0
- package/dist/src/bootstrap.js +106 -0
- package/dist/src/connect/attach.js +43 -0
- package/dist/src/connect/bootstrap.js +14 -0
- package/dist/src/connect/failures.js +44 -0
- package/dist/src/connect/guards.js +31 -0
- package/dist/src/connect/launch.js +80 -0
- package/dist/src/connect/links.js +70 -0
- package/dist/src/connect/ownership.js +220 -0
- package/dist/src/connect/pipeline.js +473 -0
- package/dist/src/connect/reattach.js +215 -0
- package/dist/src/connect/registry.js +11 -0
- package/dist/src/connect/repair.js +126 -0
- package/dist/src/connect/restart.js +316 -0
- package/dist/src/connect/stop.js +198 -0
- package/dist/src/connect/transport.js +109 -0
- package/dist/src/connect/verify.js +39 -0
- package/dist/src/connect/watchdog.js +76 -0
- package/dist/src/connect-log.js +162 -0
- package/dist/src/connect-progress.js +142 -0
- package/dist/src/constants.js +67 -0
- package/dist/src/context.js +117 -0
- package/dist/src/diagnostics.js +102 -0
- package/dist/src/download-jobs.js +230 -0
- package/dist/src/errors.js +243 -0
- package/dist/src/events.js +390 -0
- package/dist/src/host-lifecycle.js +504 -0
- package/dist/src/host-registry.js +232 -0
- package/dist/src/host-runtime.js +86 -0
- package/dist/src/host-view.js +75 -0
- package/dist/src/index.js +216 -0
- package/dist/src/kernel-adapter.js +434 -0
- package/dist/src/key-files.js +52 -0
- package/dist/src/known-hosts.js +125 -0
- package/dist/src/layout.js +43 -0
- package/dist/src/local-download.js +380 -0
- package/dist/src/local-ssh.js +30 -0
- package/dist/src/local-version.js +101 -0
- package/dist/src/node/download.js +160 -0
- package/dist/src/node-runtime.js +346 -0
- package/dist/src/probe.js +96 -0
- package/dist/src/prompts.js +270 -0
- package/dist/src/proxy/cookies.js +136 -0
- package/dist/src/proxy/headers.js +262 -0
- package/dist/src/proxy/http.js +142 -0
- package/dist/src/proxy/index.js +135 -0
- package/dist/src/proxy/limits.js +8 -0
- package/dist/src/proxy/routes.js +39 -0
- package/dist/src/proxy/upgrade.js +175 -0
- package/dist/src/redact.js +104 -0
- package/dist/src/remote-files.js +72 -0
- package/dist/src/remote-path.js +123 -0
- package/dist/src/remote-proc.js +339 -0
- package/dist/src/remote-web/registry.js +147 -0
- package/dist/src/remote-web/resolve.js +310 -0
- package/dist/src/remote-web/start.js +227 -0
- package/dist/src/remote-web/stop.js +93 -0
- package/dist/src/request-trust.js +87 -0
- package/dist/src/runtime/dispatch.js +310 -0
- package/dist/src/runtime/effects.js +91 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +120 -0
- package/dist/src/runtime/rules.js +565 -0
- package/dist/src/secrets.js +142 -0
- package/dist/src/service.js +406 -0
- package/dist/src/settings.js +144 -0
- package/dist/src/ssh-config.js +276 -0
- package/dist/src/ssh-failures.js +122 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +297 -0
- package/dist/src/ssh.js +477 -0
- package/dist/src/store.js +191 -0
- package/dist/src/tool-shared.js +181 -0
- package/dist/src/tools-exec-policy.js +167 -0
- package/dist/src/tools-exec.js +371 -0
- package/dist/src/tools-report.js +424 -0
- package/dist/src/tools.js +411 -0
- package/dist/src/tunnel.js +129 -0
- package/dist/src/util.js +149 -0
- package/dist/src/version.js +114 -0
- package/dist/src/watchdog-bus.js +29 -0
- package/dist/src/watchdog.js +156 -0
- package/index.js +5 -4
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +40 -21
- package/vendor/THIRD_PARTY_NOTICES.md +27 -1
- package/src/api.js +0 -340
- package/src/atomic-json.js +0 -208
- package/src/bootstrap.js +0 -100
- package/src/connect-log.js +0 -39
- package/src/connect-pipeline.js +0 -463
- package/src/connect-progress.js +0 -135
- package/src/constants.js +0 -31
- package/src/diagnostics.js +0 -157
- package/src/download-jobs.js +0 -217
- package/src/errors.js +0 -316
- package/src/host-lifecycle.js +0 -187
- package/src/host-registry.js +0 -145
- package/src/host-runtime.js +0 -53
- package/src/host-view.js +0 -51
- package/src/index.js +0 -162
- package/src/key-files.js +0 -49
- package/src/known-hosts.js +0 -94
- package/src/layout.js +0 -35
- package/src/local-download.js +0 -162
- package/src/local-ssh.js +0 -27
- package/src/local-version.js +0 -88
- package/src/node-runtime.js +0 -521
- package/src/probe.js +0 -89
- package/src/prompts.js +0 -132
- package/src/redact.js +0 -54
- package/src/remote-files.js +0 -71
- package/src/remote-path.js +0 -73
- package/src/remote-proc.js +0 -208
- package/src/remote-web.js +0 -300
- package/src/secrets.js +0 -79
- package/src/service.js +0 -250
- package/src/settings.js +0 -135
- package/src/ssh-config.js +0 -271
- package/src/ssh.js +0 -652
- package/src/store.js +0 -143
- package/src/tunnel.js +0 -73
- package/src/util.js +0 -153
- package/src/version.js +0 -103
- package/src/webapp.js +0 -28
- package/vendor/ssh2-entry.mjs +0 -12
- /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The re-attach to a remote web that restarted on its own (plugin-market update, supervisor,
|
|
3
|
+
* remote reboot): re-read the real pid/port, refresh `run/web.json`, rebuild the tunnel, take the
|
|
4
|
+
* new launch token and verify. The SSH session and the host entry are untouched.
|
|
5
|
+
*/
|
|
6
|
+
import { REMOTE_REATTACH_ATTEMPTS, REMOTE_REATTACH_INTERVAL_MS } from '../constants.js';
|
|
7
|
+
import { errors, toErrorView } from '../errors.js';
|
|
8
|
+
import { closeTunnel, endLinkWork, isLinkWorkCurrent } from '../host-lifecycle.js';
|
|
9
|
+
import { layoutForRuntime } from '../layout.js';
|
|
10
|
+
import { buildRunRegistryRecord } from '../remote-web/registry.js';
|
|
11
|
+
import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
|
|
12
|
+
import { createRuntimeEffects } from '../runtime/effects.js';
|
|
13
|
+
import { nowIso, sleep } from '../util.js';
|
|
14
|
+
import { normalizeVersion, versionsEqual } from '../version.js';
|
|
15
|
+
import { markConnected, recordRestart } from './attach.js';
|
|
16
|
+
import { SSH_CLOSED_DETAIL } from './failures.js';
|
|
17
|
+
import { LinkCancelled } from './guards.js';
|
|
18
|
+
import { rememberBound } from './ownership.js';
|
|
19
|
+
import { openTunnelFor } from './transport.js';
|
|
20
|
+
import { verifyRemoteUi } from './verify.js';
|
|
21
|
+
/**
|
|
22
|
+
* Re-attach to a remote web that restarted on its own (plugin-market update, supervisor,
|
|
23
|
+
* remote reboot): re-read the real pid/port, refresh `run/web.json`, rebuild the tunnel,
|
|
24
|
+
* take the new launch token and verify. The SSH session and the host entry are untouched.
|
|
25
|
+
*
|
|
26
|
+
* @param ctx - service context.
|
|
27
|
+
* @param runtime - host runtime the watchdog decided is unreachable.
|
|
28
|
+
* @param info - why the re-attach was requested.
|
|
29
|
+
* @returns whether the re-attach started.
|
|
30
|
+
*/
|
|
31
|
+
export async function reattachHost(ctx, runtime, info = {}) {
|
|
32
|
+
if (runtime.status !== 'connected' || runtime.ssh?.connected !== true || runtime.tunnel === null) {
|
|
33
|
+
return { accepted: false, reason: 'not-connected' };
|
|
34
|
+
}
|
|
35
|
+
if (runtime.connectPromise || runtime.linkBusy !== null)
|
|
36
|
+
return { accepted: false, reason: 'busy' };
|
|
37
|
+
// One transition owns `activity`/`epoch`, the `connecting` card and the action start (`run`);
|
|
38
|
+
// the token is the old `beginLinkWork` one so the late-write filter keeps its semantics.
|
|
39
|
+
const token = (Number(runtime.linkToken) || 0) + 1;
|
|
40
|
+
const reason = typeof info?.reason === 'string' && info.reason !== '' ? info.reason : 'remote-unreachable';
|
|
41
|
+
const event = { type: 'reattach.requested', token, reason };
|
|
42
|
+
await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
|
|
43
|
+
caller: 'script',
|
|
44
|
+
run: (activity, started) => {
|
|
45
|
+
if (activity !== 'reattach')
|
|
46
|
+
return;
|
|
47
|
+
const work = runReattach(ctx, runtime, info, started);
|
|
48
|
+
runtime.reattachPromise = work;
|
|
49
|
+
void work.finally(() => {
|
|
50
|
+
endLinkWork(runtime, started);
|
|
51
|
+
if (runtime.reattachPromise === work)
|
|
52
|
+
runtime.reattachPromise = null;
|
|
53
|
+
});
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
return { accepted: true };
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The action body: the re-attach re-reads the remote state, rewrites the run registry, rebuilds the
|
|
60
|
+
* tunnel and verifies the UI, so it spans all six slices exactly like its entry point — the same
|
|
61
|
+
* `ConnectCtx`, not a copied intersection (the gate's `godCtxParams` entries name it).
|
|
62
|
+
*/
|
|
63
|
+
async function runReattach(ctx, runtime, info, token) {
|
|
64
|
+
const log = (level, ...args) => ctx.progress.log(runtime, level, ...args);
|
|
65
|
+
const phase = (name, code, params) => ctx.progress.phase(runtime, name, code, params);
|
|
66
|
+
const layout = layoutForRuntime(runtime);
|
|
67
|
+
const profile = runtime.remote.profile ?? ctx.settings().bootstrap.profile;
|
|
68
|
+
const fromPort = runtime.remote.port;
|
|
69
|
+
const reason = typeof info?.reason === 'string' && info.reason !== '' ? info.reason : 'remote-unreachable';
|
|
70
|
+
let tunnelCreated = false;
|
|
71
|
+
try {
|
|
72
|
+
// `reattach.requested` already disarmed the timers and published the `restarting-remote` card.
|
|
73
|
+
log('info', `remote restart suspected: ${reason}; re-reading the remote state`);
|
|
74
|
+
// A restart takes a moment to print its new readiness line: retry before giving up.
|
|
75
|
+
const attempts = Math.max(1, Number(ctx.timers.reattachAttempts) || REMOTE_REATTACH_ATTEMPTS);
|
|
76
|
+
const intervalMs = Math.max(0, Number(ctx.timers.reattachIntervalMs ?? REMOTE_REATTACH_INTERVAL_MS) || 0);
|
|
77
|
+
let resolved = null;
|
|
78
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
79
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
80
|
+
return;
|
|
81
|
+
resolved = await ctx.deps.resolveRemote(runtime.ssh, layout, { profile });
|
|
82
|
+
if (resolved?.ok === true)
|
|
83
|
+
break;
|
|
84
|
+
log('debug', `re-attach: remote state not ready yet (${resolved?.reason ?? 'unreadable'}), attempt ${attempt}/${attempts}`);
|
|
85
|
+
if (attempt < attempts && intervalMs > 0)
|
|
86
|
+
await sleep(intervalMs);
|
|
87
|
+
}
|
|
88
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
89
|
+
return;
|
|
90
|
+
// `resolved?.ok !== true` is the same test as `!resolved || resolved.ok !== true`, and it is
|
|
91
|
+
// the form the compiler can narrow: with `strictNullChecks` off the disjunction's `!resolved`
|
|
92
|
+
// arm widens the branch back to the whole union.
|
|
93
|
+
if (resolved?.ok !== true) {
|
|
94
|
+
const detail = resolved?.reason === 'no-token'
|
|
95
|
+
? {
|
|
96
|
+
zh: '远端 DSH 仍在运行,但它这次重启没有留下可用的 launch token,无法自动重新挂载;请点「重启」或「重连」。',
|
|
97
|
+
en: 'The remote DSH is still running, but its restart left no usable launch token, so it cannot be re-attached; use "Restart" or Reconnect.',
|
|
98
|
+
}
|
|
99
|
+
: {
|
|
100
|
+
zh: `远端 DSH 重启后没有找到可以重新挂载的实例(${resolved?.reason ?? 'unreadable'});主机与配置已保留。`,
|
|
101
|
+
en: `No re-attachable remote DSH instance was found after the restart (${resolved?.reason ?? 'unreadable'}); the host and its settings are kept.`,
|
|
102
|
+
};
|
|
103
|
+
throw errors.remoteUnreachable(detail, {
|
|
104
|
+
technical: `reason=${resolved?.reason ?? 'unknown'} fromPort=${fromPort ?? 'unknown'}`,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
// A takeover needs the new launch token: a real DSH rejects `/?token=` and a cookie-less
|
|
108
|
+
// request, so an empty token can never be treated as success (B4).
|
|
109
|
+
if (typeof resolved.token !== 'string' || resolved.token === '') {
|
|
110
|
+
throw errors.remoteUnreachable({
|
|
111
|
+
zh: '远端 DSH 重启后没有留下可用的 launch token,无法自动重新挂载;请点「重启」或「重连」。',
|
|
112
|
+
en: 'The restarted remote DSH left no usable launch token, so it cannot be re-attached; use "Restart" or Reconnect.',
|
|
113
|
+
}, { technical: `reason=no-token source=${resolved.source ?? 'unknown'} port=${resolved.port ?? 'unknown'}` });
|
|
114
|
+
}
|
|
115
|
+
const targetVersion = ctx.localVersion();
|
|
116
|
+
const remoteVersion = typeof resolved.version === 'string' && resolved.version !== '' ? normalizeVersion(resolved.version) : null;
|
|
117
|
+
if (remoteVersion && targetVersion && !versionsEqual(remoteVersion, targetVersion)) {
|
|
118
|
+
// A different DSH under the same ~/.dsh would show a UI that does not match this machine;
|
|
119
|
+
// the user's remedy is the explicit restart, which launches the pinned version.
|
|
120
|
+
throw errors.versionMismatch(targetVersion, remoteVersion);
|
|
121
|
+
}
|
|
122
|
+
if (remoteVersion === null) {
|
|
123
|
+
log('warn', 're-attach: the running DSH version could not be proven; keeping it unknown, not assuming the local one');
|
|
124
|
+
}
|
|
125
|
+
// The pid that actually listens may differ from the wrapper this connection launched (npx
|
|
126
|
+
// spawns the DSH). Keep the kill right only for the pid we are now attached to.
|
|
127
|
+
if (runtime.launched instanceof Map) {
|
|
128
|
+
for (const pid of [...runtime.launched.keys()]) {
|
|
129
|
+
if (pid !== resolved.pid)
|
|
130
|
+
runtime.launched.delete(pid);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
log('info', `re-attach: found remote web pid=${resolved.pid} port=${resolved.port} (source=${resolved.source}); refreshing the run registry`);
|
|
134
|
+
const record = buildRunRegistryRecord({
|
|
135
|
+
pid: resolved.pid,
|
|
136
|
+
port: resolved.port,
|
|
137
|
+
// Never launder an unproven version into the registry.
|
|
138
|
+
version: remoteVersion ?? '',
|
|
139
|
+
profile,
|
|
140
|
+
dshHome: layout.dshHome,
|
|
141
|
+
origin: 'reattach',
|
|
142
|
+
});
|
|
143
|
+
const written = await ctx.deps.writeRegistry(runtime.ssh, layout, record);
|
|
144
|
+
if (written.ok === true)
|
|
145
|
+
log('info', `re-attach: run registry refreshed (pid ${record.pid}, port ${record.port})`);
|
|
146
|
+
else
|
|
147
|
+
log('warn', 're-attach: the run registry could not be refreshed:', written.output);
|
|
148
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
149
|
+
return;
|
|
150
|
+
phase('tunnel', 'tunneling');
|
|
151
|
+
await closeTunnel(runtime);
|
|
152
|
+
runtime.token = resolved.token;
|
|
153
|
+
runtime.remote = {
|
|
154
|
+
...runtime.remote,
|
|
155
|
+
version: remoteVersion,
|
|
156
|
+
uiReady: false,
|
|
157
|
+
localPort: null,
|
|
158
|
+
port: resolved.port,
|
|
159
|
+
pid: resolved.pid,
|
|
160
|
+
dshHome: resolved.dshHome ?? layout.dshHome,
|
|
161
|
+
profile: resolved.profile ?? profile,
|
|
162
|
+
startedAt: nowIso(),
|
|
163
|
+
};
|
|
164
|
+
const tunnel = await openTunnelFor(ctx, runtime, resolved.port);
|
|
165
|
+
tunnelCreated = true;
|
|
166
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
167
|
+
return;
|
|
168
|
+
phase('verifying', 'verifying');
|
|
169
|
+
await verifyRemoteUi(ctx, runtime, resolved.port, resolved.token, tunnel.localPort);
|
|
170
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
171
|
+
return;
|
|
172
|
+
if (ctx.settings().saveTokens)
|
|
173
|
+
await ctx.store.saveToken(runtime.id, resolved.token);
|
|
174
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
175
|
+
return;
|
|
176
|
+
// The re-attached instance is now the one this connection is bound to. It stays out of
|
|
177
|
+
// `launched` (a restart must not kill it), but the explicit stop action may end exactly it.
|
|
178
|
+
await rememberBound(ctx, runtime, resolved.pid, layout, profile, 'reattach');
|
|
179
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
180
|
+
return;
|
|
181
|
+
recordRestart(runtime, {
|
|
182
|
+
kind: 'remote-reattach',
|
|
183
|
+
fromPort,
|
|
184
|
+
toPort: resolved.port,
|
|
185
|
+
pid: resolved.pid,
|
|
186
|
+
reason,
|
|
187
|
+
source: resolved.source,
|
|
188
|
+
});
|
|
189
|
+
await markConnected(ctx, runtime);
|
|
190
|
+
log('info', `re-attached: remote ${runtime.remote.version ?? 'version unknown'} on 127.0.0.1:${runtime.tunnel?.localPort ?? tunnel.localPort} (remote port ${fromPort} -> ${resolved.port})`);
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
if (!isLinkWorkCurrent(runtime, token)) {
|
|
194
|
+
log('debug', 're-attach aborted: the link was replaced by a disconnect or reconnect');
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const view = error instanceof LinkCancelled
|
|
198
|
+
? toErrorView(errors.network(SSH_CLOSED_DETAIL, { technical: 'reason=ssh-closed during re-attach' }))
|
|
199
|
+
: toErrorView(error);
|
|
200
|
+
// The transition owns the error state, the listener release, the heartbeat disarm, the
|
|
201
|
+
// failure lines (`logFailure` reads the phase it is about to clear) and the publication.
|
|
202
|
+
const failure = { type: 'reattach.failed', view };
|
|
203
|
+
await dispatch(createRuntimeEffects(ctx), runtime, failure, scopeFactsFor(ctx, runtime, failure), {
|
|
204
|
+
caller: 'script',
|
|
205
|
+
emit: false,
|
|
206
|
+
});
|
|
207
|
+
ctx.emitState();
|
|
208
|
+
}
|
|
209
|
+
finally {
|
|
210
|
+
// A listener this action created must never outlive the action (see runRestart).
|
|
211
|
+
if (tunnelCreated && !isLinkWorkCurrent(runtime, token))
|
|
212
|
+
await closeTunnel(runtime);
|
|
213
|
+
endLinkWork(runtime, token);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { messageOf } from '../util.js';
|
|
2
|
+
export async function readRegistryQuietly(ctx, runtime, layout) {
|
|
3
|
+
try {
|
|
4
|
+
return await ctx.deps.readRegistry(runtime.ssh, layout);
|
|
5
|
+
}
|
|
6
|
+
catch (error) {
|
|
7
|
+
// swallow-ok: registry absence only means the restart cannot attribute the running pid
|
|
8
|
+
ctx.progress.log(runtime, 'debug', 'restart: registry read failed:', messageOf(error));
|
|
9
|
+
return null;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The listener rebuild for a host whose remote UI answers the SSH probe but whose proxied
|
|
3
|
+
* requests fail (B8): the tunnel, not the remote, is what broke.
|
|
4
|
+
*/
|
|
5
|
+
import { REMOTE_REPAIR_BACKOFF_MAX_MS, REMOTE_REPAIR_BACKOFF_MS } from '../constants.js';
|
|
6
|
+
import { errors } from '../errors.js';
|
|
7
|
+
import { beginLinkWork, endLinkWork, isLinkWorkCurrent } from '../host-lifecycle.js';
|
|
8
|
+
import { isPid, messageOf } from '../util.js';
|
|
9
|
+
import { noteRemoteUnreachable } from '../watchdog.js';
|
|
10
|
+
/**
|
|
11
|
+
* Rebuild the local listener for a host whose remote UI answers the SSH probe but whose
|
|
12
|
+
* proxied requests fail: the tunnel, not the remote, is what broke. Single-flight per host and
|
|
13
|
+
* owned by a link-work token, like restart/reattach: a disconnect, host removal or shutdown
|
|
14
|
+
* cancels it and the caller waits for `runtime.tunnelRepair` before tearing down.
|
|
15
|
+
*
|
|
16
|
+
* The replacement is created before the old listener closes, so there is no window without a
|
|
17
|
+
* listener. Its local port is a new random one, so `viewRev` is bumped: the carrier refetches
|
|
18
|
+
* `GET /hosts/:id/open` and navigates again (the desktop guest's URL is the loopback origin).
|
|
19
|
+
* Existing WebSockets/downloads are dropped by closing the old listener - documented.
|
|
20
|
+
*
|
|
21
|
+
* It reads five slices and never the persistence layer (`ctx.init`/`ctx.store`/`ctx.secrets`):
|
|
22
|
+
* the rebuild publishes through `ctx.emitState()` and logs through `ctx.progress`, so the type is
|
|
23
|
+
* `WatchdogCtx`, not the six-slice `ConnectCtx` the other five orchestration entries take. The
|
|
24
|
+
* architecture gate measures this, which is why this function is not in its `godCtxParams` list.
|
|
25
|
+
*
|
|
26
|
+
* @param ctx - the watchdog's five slices (state, config, transport, remote deps, reporter).
|
|
27
|
+
* @param runtime - connected host runtime.
|
|
28
|
+
* @returns whether the listener was rebuilt.
|
|
29
|
+
*/
|
|
30
|
+
export async function repairTunnel(ctx, runtime) {
|
|
31
|
+
if (ctx.state.disposed === true ||
|
|
32
|
+
runtime.desired !== 'connected' ||
|
|
33
|
+
runtime.status !== 'connected' ||
|
|
34
|
+
runtime.linkBusy !== null ||
|
|
35
|
+
runtime.tunnel === null) {
|
|
36
|
+
return { ok: false, reason: 'not-watchable' };
|
|
37
|
+
}
|
|
38
|
+
if (runtime.ssh?.connected !== true)
|
|
39
|
+
return { ok: false, reason: 'no-transport' };
|
|
40
|
+
if (runtime.tunnelRepair)
|
|
41
|
+
return runtime.tunnelRepair;
|
|
42
|
+
if (Date.now() < (Number(runtime.nextTunnelRepairAt) || 0)) {
|
|
43
|
+
return { ok: false, reason: 'backoff' };
|
|
44
|
+
}
|
|
45
|
+
const port = runtime.remote.port;
|
|
46
|
+
const previous = runtime.tunnel;
|
|
47
|
+
const token = beginLinkWork(runtime, 'repair');
|
|
48
|
+
const stillCurrent = () => isLinkWorkCurrent(runtime, token) &&
|
|
49
|
+
ctx.state.disposed !== true &&
|
|
50
|
+
runtime.desired === 'connected' &&
|
|
51
|
+
runtime.status === 'connected' &&
|
|
52
|
+
runtime.ssh?.connected === true;
|
|
53
|
+
let created = null;
|
|
54
|
+
let work = null;
|
|
55
|
+
let settled = null;
|
|
56
|
+
work = (async () => {
|
|
57
|
+
try {
|
|
58
|
+
if (runtime.ssh?.connected !== true)
|
|
59
|
+
throw errors.internal(new Error('the SSH transport is gone'));
|
|
60
|
+
if (!isPid(port) || port > 65535)
|
|
61
|
+
throw errors.internal(new Error(`invalid remote port for the tunnel: ${port}`));
|
|
62
|
+
const next = await ctx.deps.tunnelFactory({
|
|
63
|
+
ssh: runtime.ssh,
|
|
64
|
+
remotePort: port,
|
|
65
|
+
onError: () => noteRemoteUnreachable(ctx, runtime, 'tunnel'),
|
|
66
|
+
});
|
|
67
|
+
created = next;
|
|
68
|
+
const nextPort = Number(next?.localPort);
|
|
69
|
+
if (!Number.isInteger(nextPort) || !isPid(nextPort) || nextPort > 65535) {
|
|
70
|
+
throw errors.internal(new Error(`the rebuilt tunnel has no usable local port (${next?.localPort})`));
|
|
71
|
+
}
|
|
72
|
+
if (!stillCurrent())
|
|
73
|
+
return { ok: false, reason: 'cancelled' };
|
|
74
|
+
// Publish the replacement before closing the old listener: no no-listener window.
|
|
75
|
+
runtime.tunnel = next;
|
|
76
|
+
runtime.remote.localPort = nextPort;
|
|
77
|
+
try {
|
|
78
|
+
await previous.close();
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// swallow-ok: the old listener could already be gone; the new one is what matters
|
|
82
|
+
}
|
|
83
|
+
if (!stillCurrent())
|
|
84
|
+
return { ok: false, reason: 'cancelled' };
|
|
85
|
+
// The local port changed, so the carrier's view of the host did too.
|
|
86
|
+
runtime.remote.viewRev = (Number(runtime.remote.viewRev) || 0) + 1;
|
|
87
|
+
ctx.progress.log(runtime, 'info', `tunnel rebuilt after a failed request (remote port ${port}, local port ${previous.localPort} -> ${nextPort})`);
|
|
88
|
+
runtime.tunnelRepairFailures = 0;
|
|
89
|
+
runtime.nextTunnelRepairAt = 0;
|
|
90
|
+
ctx.emitState();
|
|
91
|
+
return { ok: true };
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
// swallow-ok: a failed rebuild is a typed, retryable reason (with backoff) for the caller;
|
|
95
|
+
// the old listener is still serving, so this is not a connection failure.
|
|
96
|
+
runtime.tunnelRepairFailures = (Number(runtime.tunnelRepairFailures) || 0) + 1;
|
|
97
|
+
const backoff = Math.min(REMOTE_REPAIR_BACKOFF_MAX_MS, REMOTE_REPAIR_BACKOFF_MS * 2 ** (runtime.tunnelRepairFailures - 1));
|
|
98
|
+
runtime.nextTunnelRepairAt = Date.now() + backoff;
|
|
99
|
+
ctx.progress.log(runtime, 'warn', 'tunnel rebuild failed:', messageOf(error));
|
|
100
|
+
return { ok: false, reason: 'rebuild-failed' };
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
// A listener this rebuild created must never outlive it: on a cancelled token (or if it
|
|
104
|
+
// was never published) close it here, and clear the view only when it owned the slot.
|
|
105
|
+
if (created !== null && (!isLinkWorkCurrent(runtime, token) || runtime.tunnel !== created)) {
|
|
106
|
+
if (runtime.tunnel === created) {
|
|
107
|
+
runtime.tunnel = null;
|
|
108
|
+
runtime.remote.localPort = null;
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
await created.close();
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
// swallow-ok: the unpublished listener is discarded; its close cannot fail the repair
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
endLinkWork(runtime, token);
|
|
118
|
+
}
|
|
119
|
+
})();
|
|
120
|
+
settled = work.finally(() => {
|
|
121
|
+
if (runtime.tunnelRepair === settled)
|
|
122
|
+
runtime.tunnelRepair = null;
|
|
123
|
+
});
|
|
124
|
+
runtime.tunnelRepair = settled;
|
|
125
|
+
return settled;
|
|
126
|
+
}
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The local restart of the managed remote web on the same SSH transport: stop exactly the instance
|
|
3
|
+
* this connection launched, `[start]` again on the same plan, rebuild the tunnel for the new
|
|
4
|
+
* random port, verify and resume.
|
|
5
|
+
*/
|
|
6
|
+
import { REMOTE_START_TIMEOUT_MS } from '../constants.js';
|
|
7
|
+
import { errors, toErrorView } from '../errors.js';
|
|
8
|
+
import { closeTunnel, endLinkWork, isLinkWorkCurrent } from '../host-lifecycle.js';
|
|
9
|
+
import { layoutForRuntime } from '../layout.js';
|
|
10
|
+
import { buildRunRegistryRecord } from '../remote-web/registry.js';
|
|
11
|
+
import { commandMatchesProfile } from '../remote-web/resolve.js';
|
|
12
|
+
import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
|
|
13
|
+
import { createRuntimeEffects } from '../runtime/effects.js';
|
|
14
|
+
import { isPid, messageOf, nowIso } from '../util.js';
|
|
15
|
+
import { markConnected, recordRestart, resumeConnected } from './attach.js';
|
|
16
|
+
import { planForRuntime } from './bootstrap.js';
|
|
17
|
+
import { SSH_CLOSED_DETAIL } from './failures.js';
|
|
18
|
+
import { LinkCancelled } from './guards.js';
|
|
19
|
+
import { resolveForeignConflict } from './launch.js';
|
|
20
|
+
import { OWNERSHIP_OPTIONS, proveOwnership, rememberLaunched } from './ownership.js';
|
|
21
|
+
import { readRegistryQuietly } from './registry.js';
|
|
22
|
+
import { openTunnelFor } from './transport.js';
|
|
23
|
+
import { verifyRemoteUi } from './verify.js';
|
|
24
|
+
/**
|
|
25
|
+
* Restart the managed remote web on the same SSH transport: stop the pid the run
|
|
26
|
+
* registry names, `[start]` again on the same plan, rebuild the tunnel for the new
|
|
27
|
+
* random port and verify. `[ssh]` / `[probe]` / `[bootstrap]` are not re-run, so a
|
|
28
|
+
* password or host-key prompt can never appear here.
|
|
29
|
+
*
|
|
30
|
+
* Only the instance this connection launched is stopped; a process the plugin did
|
|
31
|
+
* not start goes through the ordinary conflict prompt instead of being killed.
|
|
32
|
+
*
|
|
33
|
+
* Available while connected, and also from the `remote-unreachable` error state: that
|
|
34
|
+
* state deliberately keeps the SSH transport so the user can restart exactly when a
|
|
35
|
+
* remote re-attach found nothing to adopt (docs/design.md §5.6).
|
|
36
|
+
*
|
|
37
|
+
* @param ctx - service context.
|
|
38
|
+
* @param runtime - host runtime with a live transport.
|
|
39
|
+
* @returns whether the restart started.
|
|
40
|
+
*/
|
|
41
|
+
export async function restartHost(ctx, runtime) {
|
|
42
|
+
await ctx.init();
|
|
43
|
+
if (runtime.connectPromise || runtime.linkBusy !== null)
|
|
44
|
+
return { accepted: false, reason: 'busy' };
|
|
45
|
+
const connected = runtime.status === 'connected' && runtime.ssh?.connected === true && runtime.tunnel !== null;
|
|
46
|
+
const recoverable = runtime.status === 'error' &&
|
|
47
|
+
runtime.error?.code === 'remote-unreachable' &&
|
|
48
|
+
runtime.ssh?.connected === true &&
|
|
49
|
+
runtime.facts !== null;
|
|
50
|
+
if (!connected && !recoverable) {
|
|
51
|
+
throw errors.restartUnavailable();
|
|
52
|
+
}
|
|
53
|
+
// One transition owns `activity`/`epoch`, the `connecting` card and the action start (`run`).
|
|
54
|
+
// The token is the old `beginLinkWork` one: the rule adopts it (`epochAfter`) and hands it to the
|
|
55
|
+
// script, so the late-write filter keeps the exact semantics it had.
|
|
56
|
+
const token = (Number(runtime.linkToken) || 0) + 1;
|
|
57
|
+
const event = {
|
|
58
|
+
type: 'restart.requested',
|
|
59
|
+
token,
|
|
60
|
+
pid: runtime.remote.pid,
|
|
61
|
+
port: runtime.remote.port,
|
|
62
|
+
};
|
|
63
|
+
await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
|
|
64
|
+
caller: 'script',
|
|
65
|
+
run: (activity, started) => {
|
|
66
|
+
if (activity !== 'restart')
|
|
67
|
+
return;
|
|
68
|
+
const work = runRestart(ctx, runtime, started);
|
|
69
|
+
runtime.restartPromise = work;
|
|
70
|
+
void work.finally(() => {
|
|
71
|
+
endLinkWork(runtime, started);
|
|
72
|
+
if (runtime.restartPromise === work)
|
|
73
|
+
runtime.restartPromise = null;
|
|
74
|
+
});
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
return { accepted: true };
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The action body: proof of ownership, the conflict prompt, stop/start, the registry rewrite, the
|
|
81
|
+
* tunnel and the verify step all read the same six slices as its entry point, so it takes
|
|
82
|
+
* `ConnectCtx` rather than a second copy of the intersection (the gate's `godCtxParams` entry
|
|
83
|
+
* names it).
|
|
84
|
+
*/
|
|
85
|
+
async function runRestart(ctx, runtime, token) {
|
|
86
|
+
const log = (level, ...args) => ctx.progress.log(runtime, level, ...args);
|
|
87
|
+
const phase = (name, code, params) => ctx.progress.phase(runtime, name, code, params);
|
|
88
|
+
const layout = layoutForRuntime(runtime);
|
|
89
|
+
const profile = runtime.remote.profile ?? ctx.settings().bootstrap.profile;
|
|
90
|
+
const previousPort = runtime.remote.port;
|
|
91
|
+
// Restarting from the remote-unreachable error state has no tunnel to keep.
|
|
92
|
+
const hadTunnel = runtime.tunnel !== null;
|
|
93
|
+
let killable = false;
|
|
94
|
+
let stoppedOwn = false;
|
|
95
|
+
let started = false;
|
|
96
|
+
let tunnelCreated = false;
|
|
97
|
+
try {
|
|
98
|
+
// `restart.requested` already disarmed the heartbeat/reconnect/idle timers and published the
|
|
99
|
+
// `start`/`restarting-remote` card.
|
|
100
|
+
log('info', `restart requested (pid=${runtime.remote.pid ?? 'unknown'}, remote port=${previousPort ?? 'unknown'})`);
|
|
101
|
+
// Whether the running pid is ours to stop needs two independent proofs here: the registry
|
|
102
|
+
// names it (below) and this connection launched it with the same /proc identity
|
|
103
|
+
// (`OWNERSHIP_OPTIONS.restart`). A pid that a re-attach discovered, or one kept alongside, is
|
|
104
|
+
// hosted, never killed.
|
|
105
|
+
const registry = await readRegistryQuietly(ctx, runtime, layout);
|
|
106
|
+
const managedPid = Number(runtime.remote.pid ?? 0);
|
|
107
|
+
const registeredPid = Number(registry?.pid ?? 0);
|
|
108
|
+
const registered = registry !== null &&
|
|
109
|
+
registry.dshHome === layout.dshHome &&
|
|
110
|
+
registry.profile === profile &&
|
|
111
|
+
isPid(managedPid) &&
|
|
112
|
+
registeredPid === managedPid;
|
|
113
|
+
if (registered) {
|
|
114
|
+
const verdict = await proveOwnership(ctx, runtime, {
|
|
115
|
+
...OWNERSHIP_OPTIONS.restart,
|
|
116
|
+
pid: managedPid,
|
|
117
|
+
layout,
|
|
118
|
+
profile,
|
|
119
|
+
});
|
|
120
|
+
killable = verdict.ok === true;
|
|
121
|
+
if (verdict.ok !== true) {
|
|
122
|
+
log('warn', `restart: not stopping pid ${managedPid} (${verdict.reason}); only a process this connection launched is stopped`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
log('warn', `restart: the run registry does not name this connection's pid (${isPid(managedPid) ? managedPid : 'unknown'}); leaving the running instance alone`);
|
|
127
|
+
}
|
|
128
|
+
// A live instance this connection cannot stop and did not launch (typically the pid a
|
|
129
|
+
// re-attach discovered) still occupies this ~/.dsh + profile. It goes through the conflict
|
|
130
|
+
// prompt: restarting must never start a second instance silently next to it
|
|
131
|
+
// (docs/design.md §5.5). Pids this connection launched are its own current instance; the
|
|
132
|
+
// registry mismatch is the caller's existing "leave it alone" behavior, not a foreign one.
|
|
133
|
+
let knownProcess = null;
|
|
134
|
+
const launchedHere = runtime.launched instanceof Map && runtime.launched.has(managedPid);
|
|
135
|
+
if (!killable && !launchedHere && isPid(managedPid) && runtime.ssh?.connected === true) {
|
|
136
|
+
const identity = await ctx.deps.processIdentity(runtime.ssh, managedPid);
|
|
137
|
+
if (identity.ok === true) {
|
|
138
|
+
const sameHome = identity.dshHome === '' || identity.dshHome === layout.dshHome;
|
|
139
|
+
if (sameHome && commandMatchesProfile(identity.command, profile)) {
|
|
140
|
+
knownProcess = { pid: managedPid, command: identity.command };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
else if (identity.reason === 'unreadable') {
|
|
144
|
+
// Alive but not provable: asking is safer than starting a second instance.
|
|
145
|
+
knownProcess = { pid: managedPid, command: `dsh --profile ${profile}` };
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
149
|
+
return;
|
|
150
|
+
// Ask about foreign instances BEFORE anything is stopped: cancelling the prompt must not
|
|
151
|
+
// destroy the instance the user is currently connected to (docs/design.md §5.5).
|
|
152
|
+
const decision = await resolveForeignConflict(ctx, runtime, layout, profile, {
|
|
153
|
+
ignoredPids: Array.isArray(runtime.alongsidePids) ? runtime.alongsidePids : [],
|
|
154
|
+
knownProcess,
|
|
155
|
+
});
|
|
156
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
157
|
+
return;
|
|
158
|
+
// The prompt stopped the instance this connection was attached to: the old attachment is
|
|
159
|
+
// gone, so a later failure must not "resume" it.
|
|
160
|
+
if (decision === 'stop')
|
|
161
|
+
stoppedOwn = true;
|
|
162
|
+
if (killable) {
|
|
163
|
+
const stopped = await ctx.deps.stopWeb(runtime.ssh, layout, { pid: managedPid });
|
|
164
|
+
// A stop can take seconds; the link may have been dropped or replaced in the meantime.
|
|
165
|
+
// A late action must not write warning/connected state on top of that.
|
|
166
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
167
|
+
return;
|
|
168
|
+
stoppedOwn = stopped?.ok === true;
|
|
169
|
+
if (stoppedOwn) {
|
|
170
|
+
log('info', `restart: stopped the managed remote web pid=${managedPid}`);
|
|
171
|
+
if (runtime.launched instanceof Map)
|
|
172
|
+
runtime.launched.delete(managedPid);
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
// Never start a second instance next to one whose stop was not confirmed. The old
|
|
176
|
+
// tunnel is still open, so the host stays usable and the user can retry. The warning is
|
|
177
|
+
// action-scoped data with no transition of its own: it is set here and cleared by
|
|
178
|
+
// `connect.succeeded` once a fresh attach replaces the stale instance.
|
|
179
|
+
runtime.warning = {
|
|
180
|
+
zh: '远端受管 DSH 没有确认停止,本次没有启动新实例;请稍后重试,或先断开再重连。',
|
|
181
|
+
en: 'The managed remote DSH did not confirm its stop, so no new instance was started; retry shortly, or disconnect and reconnect.',
|
|
182
|
+
};
|
|
183
|
+
runtime.warningSource = 'restart-stop';
|
|
184
|
+
log('warn', `restart: the managed remote web did not confirm its stop; not launching a second instance (${String(stopped?.output ?? '').slice(0, 300) || 'no output'})`);
|
|
185
|
+
if (await resumeConnected(ctx, runtime, true))
|
|
186
|
+
return;
|
|
187
|
+
// The link changed under us, or there was no tunnel to keep (restart from the error
|
|
188
|
+
// state): never publish a fake "connected" state; explain instead of staying stuck.
|
|
189
|
+
if (isLinkWorkCurrent(runtime, token) && runtime.status === 'connecting') {
|
|
190
|
+
const failure = {
|
|
191
|
+
type: 'restart.failed',
|
|
192
|
+
phase: 'start',
|
|
193
|
+
view: toErrorView(errors.restartUnavailable({
|
|
194
|
+
zh: '远端受管 DSH 没有确认停止,本次没有启动新实例;请稍后重试。',
|
|
195
|
+
en: 'The managed remote DSH did not confirm its stop, so no new instance was started; retry shortly.',
|
|
196
|
+
})),
|
|
197
|
+
};
|
|
198
|
+
await dispatch(createRuntimeEffects(ctx), runtime, failure, scopeFactsFor(ctx, runtime, failure), {
|
|
199
|
+
caller: 'script',
|
|
200
|
+
keepLink: true,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
207
|
+
return;
|
|
208
|
+
const { plan, targetVersion, facts } = planForRuntime(ctx, runtime, profile);
|
|
209
|
+
phase('start', 'restarting-remote', { level: plan.level });
|
|
210
|
+
log('info', `restart: launching @deepseek-ai/dsh@${plan.start.targetVersion} with profile ${profile}`);
|
|
211
|
+
const webInfo = await ctx.deps.startWeb(runtime.ssh, {
|
|
212
|
+
plan,
|
|
213
|
+
layout,
|
|
214
|
+
profile,
|
|
215
|
+
timeoutMs: REMOTE_START_TIMEOUT_MS,
|
|
216
|
+
onLine: (line) => log('debug', `remote: ${line}`),
|
|
217
|
+
});
|
|
218
|
+
started = true;
|
|
219
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
220
|
+
return;
|
|
221
|
+
await rememberLaunched(ctx, runtime, webInfo.pid, layout, profile);
|
|
222
|
+
if (webInfo.browserCarrier === 'patched') {
|
|
223
|
+
log('info', 'the remote profile disables api-remotes (browser Remote-Event carrier); re-enabled it for this launch');
|
|
224
|
+
}
|
|
225
|
+
log('info', `restart: remote DSH started pid ${webInfo.pid ?? '?'}, port ${webInfo.port}`);
|
|
226
|
+
const record = buildRunRegistryRecord({
|
|
227
|
+
pid: webInfo.pid,
|
|
228
|
+
port: webInfo.port,
|
|
229
|
+
version: targetVersion,
|
|
230
|
+
profile,
|
|
231
|
+
dshHome: layout.dshHome,
|
|
232
|
+
startedAt: webInfo.startedAt,
|
|
233
|
+
});
|
|
234
|
+
const written = await ctx.deps.writeRegistry(runtime.ssh, layout, record);
|
|
235
|
+
if (written.ok === true)
|
|
236
|
+
log('info', `restart: run registry refreshed (pid ${record.pid}, port ${record.port})`);
|
|
237
|
+
else
|
|
238
|
+
log('warn', 'restart: the run registry could not be refreshed:', written.output);
|
|
239
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
240
|
+
return;
|
|
241
|
+
// The remote picked a random port again, so the old tunnel points at a dead port.
|
|
242
|
+
phase('tunnel', 'tunneling');
|
|
243
|
+
await closeTunnel(runtime);
|
|
244
|
+
runtime.token = webInfo.token;
|
|
245
|
+
runtime.remote = {
|
|
246
|
+
...runtime.remote,
|
|
247
|
+
version: targetVersion,
|
|
248
|
+
uiReady: false,
|
|
249
|
+
localPort: null,
|
|
250
|
+
port: webInfo.port,
|
|
251
|
+
pid: webInfo.pid ?? null,
|
|
252
|
+
dshHome: layout.dshHome,
|
|
253
|
+
profile,
|
|
254
|
+
bootstrapLevel: plan.level,
|
|
255
|
+
nodeVersion: facts.nodeVersion,
|
|
256
|
+
nodeSource: 'managed',
|
|
257
|
+
startedAt: webInfo.startedAt ?? nowIso(),
|
|
258
|
+
};
|
|
259
|
+
const tunnel = await openTunnelFor(ctx, runtime, webInfo.port);
|
|
260
|
+
tunnelCreated = true;
|
|
261
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
262
|
+
return;
|
|
263
|
+
phase('verifying', 'verifying');
|
|
264
|
+
await verifyRemoteUi(ctx, runtime, webInfo.port, webInfo.token, tunnel.localPort);
|
|
265
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
266
|
+
return;
|
|
267
|
+
if (ctx.settings().saveTokens)
|
|
268
|
+
await ctx.store.saveToken(runtime.id, webInfo.token);
|
|
269
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
270
|
+
return;
|
|
271
|
+
recordRestart(runtime, {
|
|
272
|
+
kind: 'local-restart',
|
|
273
|
+
fromPort: previousPort,
|
|
274
|
+
toPort: webInfo.port,
|
|
275
|
+
pid: webInfo.pid ?? null,
|
|
276
|
+
});
|
|
277
|
+
await markConnected(ctx, runtime);
|
|
278
|
+
log('info', `restart: connected again on 127.0.0.1:${runtime.tunnel?.localPort ?? tunnel.localPort} (remote port ${previousPort} -> ${webInfo.port})`);
|
|
279
|
+
}
|
|
280
|
+
catch (error) {
|
|
281
|
+
if (!isLinkWorkCurrent(runtime, token)) {
|
|
282
|
+
log('debug', 'restart aborted: the link was replaced by a disconnect or reconnect');
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
// Nothing this connection owned was stopped, so the previous attachment is still
|
|
286
|
+
// valid: cancelling a conflict prompt (or a failed relaunch) keeps the host usable.
|
|
287
|
+
if (!stoppedOwn && !started && hadTunnel && runtime.ssh?.connected === true && runtime.tunnel !== null) {
|
|
288
|
+
log('warn', `restart cancelled: ${messageOf(error)}; keeping the current remote instance`);
|
|
289
|
+
await resumeConnected(ctx, runtime);
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
const view = error instanceof LinkCancelled
|
|
293
|
+
? toErrorView(errors.network(SSH_CLOSED_DETAIL, { technical: 'reason=ssh-closed during restart' }))
|
|
294
|
+
: toErrorView(error);
|
|
295
|
+
// Phase is cleared with the status; capture it first so the log says where it stopped.
|
|
296
|
+
const failedPhase = runtime.phase;
|
|
297
|
+
// The transition owns the error state, the failure lines and the teardown; the caller keeps
|
|
298
|
+
// its own publication point (`emit:false`, emitted below exactly where it always was).
|
|
299
|
+
const failure = { type: 'restart.failed', view, phase: failedPhase };
|
|
300
|
+
await dispatch(createRuntimeEffects(ctx), runtime, failure, scopeFactsFor(ctx, runtime, failure), {
|
|
301
|
+
caller: 'script',
|
|
302
|
+
emit: false,
|
|
303
|
+
// Only a remote this restart launched is stopped; a restart that failed before the launch
|
|
304
|
+
// leaves the instance it never touched alone (the rule cannot tell the two apart).
|
|
305
|
+
teardown: { stopRemote: started && runtime.entry.keepAlive === 'stop' },
|
|
306
|
+
});
|
|
307
|
+
ctx.emitState();
|
|
308
|
+
}
|
|
309
|
+
finally {
|
|
310
|
+
// A listener this action created must never outlive the action: a disconnect (or a host
|
|
311
|
+
// removal) during the rebuild would otherwise leave it open with a disposed SSH channel.
|
|
312
|
+
if (tunnelCreated && !isLinkWorkCurrent(runtime, token))
|
|
313
|
+
await closeTunnel(runtime);
|
|
314
|
+
endLinkWork(runtime, token);
|
|
315
|
+
}
|
|
316
|
+
}
|