dsh-remote-go 0.2.0 → 0.3.1
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 +11 -3
- package/{client.js → dist/client.js} +7144 -8367
- package/dist/index.js +4 -0
- package/dist/src/admission.js +21 -0
- package/dist/src/api.js +380 -0
- package/dist/src/atomic-json.js +201 -0
- package/dist/src/bootstrap.js +96 -0
- package/dist/src/connect/attach.js +21 -0
- package/dist/src/connect/bootstrap.js +8 -0
- package/dist/src/connect/failures.js +29 -0
- package/dist/src/connect/guards.js +36 -0
- package/dist/src/connect/launch.js +70 -0
- package/dist/src/connect/links.js +54 -0
- package/dist/src/connect/ownership.js +139 -0
- package/dist/src/connect/pipeline.js +376 -0
- package/dist/src/connect/reattach.js +191 -0
- package/dist/src/connect/registry.js +10 -0
- package/dist/src/connect/repair.js +97 -0
- package/dist/src/connect/restart.js +255 -0
- package/dist/src/connect/stop.js +164 -0
- package/dist/src/connect/transport.js +101 -0
- package/dist/src/connect/verify.js +30 -0
- package/dist/src/connect/watchdog.js +44 -0
- package/dist/src/connect-log.js +137 -0
- package/dist/src/connect-progress.js +110 -0
- package/dist/src/constants.js +29 -0
- package/dist/src/context.js +96 -0
- package/dist/src/diagnostics.js +133 -0
- package/dist/src/download-jobs.js +221 -0
- package/dist/src/errors.js +228 -0
- package/dist/src/events.js +326 -0
- package/dist/src/host-lifecycle.js +368 -0
- package/dist/src/host-registry.js +181 -0
- package/dist/src/host-runtime.js +77 -0
- package/dist/src/host-view.js +52 -0
- package/dist/src/index.js +196 -0
- package/dist/src/kernel-adapter.js +388 -0
- package/dist/src/key-files.js +39 -0
- package/dist/src/known-hosts.js +104 -0
- package/dist/src/layout.js +26 -0
- package/dist/src/local-download.js +311 -0
- package/dist/src/local-ssh.js +23 -0
- package/dist/src/local-version.js +87 -0
- package/dist/src/node/download.js +157 -0
- package/dist/src/node-runtime.js +327 -0
- package/dist/src/probe.js +95 -0
- package/dist/src/prompts.js +198 -0
- package/dist/src/proxy/cookies.js +102 -0
- package/dist/src/proxy/headers.js +167 -0
- package/dist/src/proxy/http.js +134 -0
- package/dist/src/proxy/index.js +121 -0
- package/dist/src/proxy/limits.js +6 -0
- package/dist/src/proxy/routes.js +32 -0
- package/dist/src/proxy/upgrade.js +160 -0
- package/dist/src/redact.js +85 -0
- package/dist/src/remote-files.js +60 -0
- package/dist/src/remote-path.js +82 -0
- package/dist/src/remote-proc.js +271 -0
- package/dist/src/remote-web/registry.js +107 -0
- package/dist/src/remote-web/resolve.js +229 -0
- package/dist/src/remote-web/start.js +190 -0
- package/dist/src/remote-web/stop.js +74 -0
- package/dist/src/request-trust.js +70 -0
- package/dist/src/runtime/dispatch.js +200 -0
- package/dist/src/runtime/effects.js +81 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +70 -0
- package/dist/src/runtime/rules.js +480 -0
- package/dist/src/secrets.js +119 -0
- package/dist/src/service.js +300 -0
- package/dist/src/settings.js +143 -0
- package/dist/src/ssh-config.js +257 -0
- package/dist/src/ssh-failures.js +71 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +258 -0
- package/dist/src/ssh.js +395 -0
- package/dist/src/store.js +174 -0
- package/dist/src/tool-shared.js +146 -0
- package/dist/src/tools-exec-policy.js +121 -0
- package/dist/src/tools-exec.js +307 -0
- package/dist/src/tools-report.js +357 -0
- package/dist/src/tools.js +337 -0
- package/dist/src/tunnel.js +111 -0
- package/dist/src/util.js +112 -0
- package/dist/src/version.js +108 -0
- package/dist/src/watchdog-bus.js +21 -0
- package/dist/src/watchdog.js +116 -0
- package/index.js +5 -4
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +37 -19
- package/src/admission.js +0 -43
- package/src/api.js +0 -536
- package/src/atomic-json.js +0 -225
- package/src/bootstrap.js +0 -113
- package/src/connect-log.js +0 -176
- package/src/connect-pipeline.js +0 -1900
- package/src/connect-progress.js +0 -155
- package/src/constants.js +0 -93
- package/src/diagnostics.js +0 -160
- package/src/download-jobs.js +0 -234
- package/src/errors.js +0 -412
- package/src/host-lifecycle.js +0 -604
- package/src/host-registry.js +0 -217
- package/src/host-runtime.js +0 -127
- package/src/host-view.js +0 -75
- package/src/index.js +0 -206
- package/src/key-files.js +0 -54
- package/src/known-hosts.js +0 -133
- package/src/layout.js +0 -53
- package/src/local-download.js +0 -381
- 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 -101
- package/src/prompts.js +0 -229
- package/src/redact.js +0 -68
- package/src/remote-files.js +0 -71
- package/src/remote-path.js +0 -137
- package/src/remote-proc.js +0 -343
- package/src/remote-proxy.js +0 -815
- package/src/remote-web.js +0 -751
- package/src/request-trust.js +0 -89
- package/src/secrets.js +0 -109
- package/src/service.js +0 -459
- package/src/settings.js +0 -163
- package/src/ssh-config.js +0 -271
- package/src/ssh.js +0 -731
- package/src/store.js +0 -193
- package/src/tools.js +0 -386
- package/src/tunnel.js +0 -132
- package/src/util.js +0 -153
- package/src/version.js +0 -103
- package/src/webapp.js +0 -43
- /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
/** At most this many live state streams; a new one evicts the oldest, so a leaking page cannot grow the set. */
|
|
2
|
+
export const MAX_SSE_CLIENTS = 8;
|
|
3
|
+
export const MAX_SSE_LOG_CLIENTS = 8;
|
|
4
|
+
const MAX_SSE_FRAME_BYTES = 1 * 1024 * 1024;
|
|
5
|
+
const MAX_SSE_BUFFERED_BYTES = 1 * 1024 * 1024;
|
|
6
|
+
export const MAX_LOG_FRAME_BYTES = 64 * 1024;
|
|
7
|
+
export const MAX_LOG_FRAME_ENTRIES = 120;
|
|
8
|
+
export const LOG_FLUSH_MS = 150;
|
|
9
|
+
const HEARTBEAT_MS = 15_000;
|
|
10
|
+
const SSE_COLON = ':';
|
|
11
|
+
/** Parse a `Last-Event-ID` header into a cursor: anything but exactly `instance:hostId:attempt:seq` with two safe
|
|
12
|
+
* integers is "no cursor", and the Client then gets a `reset` frame — always correct, if larger. */
|
|
13
|
+
export function parseEventId(value) {
|
|
14
|
+
if (typeof value !== 'string')
|
|
15
|
+
return null;
|
|
16
|
+
const parts = value.split(SSE_COLON);
|
|
17
|
+
if (parts.length !== 4)
|
|
18
|
+
return null;
|
|
19
|
+
const [instance, hostId, attempt, seq] = parts;
|
|
20
|
+
const parsedAttempt = Number(attempt);
|
|
21
|
+
const parsedSeq = Number(seq);
|
|
22
|
+
if (instance === '' || hostId === '')
|
|
23
|
+
return null;
|
|
24
|
+
if (!Number.isSafeInteger(parsedAttempt) || !Number.isSafeInteger(parsedSeq))
|
|
25
|
+
return null;
|
|
26
|
+
return { instance, hostId, attempt: parsedAttempt, seq: parsedSeq };
|
|
27
|
+
}
|
|
28
|
+
export function formatEventId(cursor) {
|
|
29
|
+
return [cursor.instance, cursor.hostId, cursor.attempt, cursor.seq].join(SSE_COLON);
|
|
30
|
+
}
|
|
31
|
+
function planFor(view, cursor, instance) {
|
|
32
|
+
// Every "cannot continue" case answers with the whole tail rather than a gap protocol: no cursor, another
|
|
33
|
+
// generation/host, another attempt (seq restarts at 1), or a cursor older than the oldest retained row (ring: 200).
|
|
34
|
+
const stale = cursor === null ||
|
|
35
|
+
cursor.instance !== instance ||
|
|
36
|
+
cursor.hostId !== view.hostId ||
|
|
37
|
+
cursor.attempt !== view.attempt ||
|
|
38
|
+
cursor.seq < view.firstSeq - 1;
|
|
39
|
+
if (stale)
|
|
40
|
+
return { entries: view.entries, reset: true, seq: view.seq };
|
|
41
|
+
const entries = view.entries.filter((entry) => typeof entry.seq === 'number' && entry.seq > cursor.seq);
|
|
42
|
+
if (entries.length === 0)
|
|
43
|
+
return null;
|
|
44
|
+
return { entries, reset: false, seq: entries[entries.length - 1].seq };
|
|
45
|
+
}
|
|
46
|
+
export function createEventHub(options) {
|
|
47
|
+
const { service, logger = console } = options;
|
|
48
|
+
const stateClients = new Set();
|
|
49
|
+
const logClients = new Set();
|
|
50
|
+
const dirtyHosts = new Set();
|
|
51
|
+
let flushTimer = null;
|
|
52
|
+
let disposed = false;
|
|
53
|
+
function openStream(res) {
|
|
54
|
+
res.writeHead(200, {
|
|
55
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
56
|
+
'cache-control': 'no-cache, no-transform',
|
|
57
|
+
connection: 'keep-alive',
|
|
58
|
+
'x-accel-buffering': 'no',
|
|
59
|
+
});
|
|
60
|
+
res.flushHeaders?.();
|
|
61
|
+
}
|
|
62
|
+
function writeTo(res, frame) {
|
|
63
|
+
if (res.writableEnded === true || res.destroyed === true)
|
|
64
|
+
return false;
|
|
65
|
+
if (res.writableLength > MAX_SSE_BUFFERED_BYTES) {
|
|
66
|
+
try {
|
|
67
|
+
res.end();
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
// swallow-ok: the response is already gone; the subscriber is dropped either way
|
|
71
|
+
}
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
res.write(frame);
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function broadcastStateChannel(frame) {
|
|
83
|
+
const bytes = Buffer.byteLength(frame);
|
|
84
|
+
if (bytes > MAX_SSE_FRAME_BYTES) {
|
|
85
|
+
logger.warn?.(`[dsh-remote-go] dropped an ${bytes}-byte SSE frame`);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
for (const res of [...stateClients]) {
|
|
89
|
+
if (!writeTo(res, frame))
|
|
90
|
+
stateClients.delete(res);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function sendLog(client, frame) {
|
|
94
|
+
const bytes = Buffer.byteLength(frame);
|
|
95
|
+
if (bytes > MAX_LOG_FRAME_BYTES) {
|
|
96
|
+
// The packer splits by size, so this is a defect rather than a load: log it and skip the frame
|
|
97
|
+
// instead of letting it grow the 1 MiB global gate.
|
|
98
|
+
logger.warn?.(`[dsh-remote-go] dropped an oversized ${bytes}-byte log frame`);
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
if (!writeTo(client.res, frame)) {
|
|
102
|
+
logClients.delete(client);
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
const logEndFrame = (hostId, attempt) => `event: log-end\ndata: ${JSON.stringify({ hostId, attempt })}\n\n`;
|
|
108
|
+
function logFrame(view, instance, seq, reset, entries) {
|
|
109
|
+
const frame = {
|
|
110
|
+
hostId: view.hostId,
|
|
111
|
+
instance,
|
|
112
|
+
attempt: view.attempt,
|
|
113
|
+
seq,
|
|
114
|
+
...(reset ? { reset: true } : {}),
|
|
115
|
+
visible: view.visible,
|
|
116
|
+
entries,
|
|
117
|
+
};
|
|
118
|
+
const id = formatEventId({ instance, hostId: view.hostId, attempt: view.attempt, seq });
|
|
119
|
+
return `event: log\nid: ${id}\ndata: ${JSON.stringify(frame)}\n\n`;
|
|
120
|
+
}
|
|
121
|
+
/** Split one host's rows into frames that respect both log caps (rows are already bounded by the ring, so the count
|
|
122
|
+
* cap is usually enough; the byte cap keeps long lines from crossing the global gate). */
|
|
123
|
+
function packFrames(view, plan) {
|
|
124
|
+
const instance = service.stateInstance;
|
|
125
|
+
if (plan.entries.length === 0)
|
|
126
|
+
return [logFrame(view, instance, plan.seq, plan.reset, [])];
|
|
127
|
+
const frames = [];
|
|
128
|
+
let index = 0;
|
|
129
|
+
let first = true;
|
|
130
|
+
while (index < plan.entries.length) {
|
|
131
|
+
const chunk = [];
|
|
132
|
+
let bytes = 0;
|
|
133
|
+
while (index < plan.entries.length && chunk.length < MAX_LOG_FRAME_ENTRIES) {
|
|
134
|
+
const entry = plan.entries[index];
|
|
135
|
+
const size = Buffer.byteLength(JSON.stringify(entry)) + 1;
|
|
136
|
+
const envelope = 320 + 2 * String(entry.seq).length;
|
|
137
|
+
if (chunk.length > 0 && bytes + size + envelope > MAX_LOG_FRAME_BYTES)
|
|
138
|
+
break;
|
|
139
|
+
chunk.push(entry);
|
|
140
|
+
bytes += size;
|
|
141
|
+
index += 1;
|
|
142
|
+
}
|
|
143
|
+
const last = chunk[chunk.length - 1];
|
|
144
|
+
const seq = last !== undefined ? last.seq : view.seq;
|
|
145
|
+
frames.push(logFrame(view, instance, seq, plan.reset && first, chunk));
|
|
146
|
+
first = false;
|
|
147
|
+
}
|
|
148
|
+
return frames;
|
|
149
|
+
}
|
|
150
|
+
function publishTo(client, view) {
|
|
151
|
+
const cursor = client.cursors.get(view.hostId) ?? null;
|
|
152
|
+
const instance = service.stateInstance;
|
|
153
|
+
const plan = planFor(view, cursor, instance);
|
|
154
|
+
if (plan !== null) {
|
|
155
|
+
for (const frame of packFrames(view, plan)) {
|
|
156
|
+
if (!sendLog(client, frame))
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (view.visible) {
|
|
160
|
+
client.cursors.set(view.hostId, { instance, hostId: view.hostId, attempt: view.attempt, seq: plan.seq });
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
client.cursors.delete(view.hostId);
|
|
164
|
+
sendLog(client, logEndFrame(view.hostId, view.attempt));
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (!view.visible && cursor !== null) {
|
|
168
|
+
sendLog(client, logFrame(view, instance, view.seq, false, []));
|
|
169
|
+
client.cursors.delete(view.hostId);
|
|
170
|
+
sendLog(client, logEndFrame(view.hostId, view.attempt));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
function publishHost(hostId) {
|
|
174
|
+
const visible = service.logView(hostId);
|
|
175
|
+
if (visible === null)
|
|
176
|
+
return;
|
|
177
|
+
for (const client of [...logClients])
|
|
178
|
+
publishTo(client, visible);
|
|
179
|
+
}
|
|
180
|
+
/** A state change can move hosts in and out of the log-visible set: both directions are discovered here. */
|
|
181
|
+
function reconcileLogs() {
|
|
182
|
+
const visible = new Set(service.logHostIds());
|
|
183
|
+
const ids = new Set(visible);
|
|
184
|
+
for (const client of logClients) {
|
|
185
|
+
for (const hostId of client.cursors.keys())
|
|
186
|
+
ids.add(hostId);
|
|
187
|
+
}
|
|
188
|
+
for (const hostId of ids) {
|
|
189
|
+
const view = service.logView(hostId);
|
|
190
|
+
if (view !== null) {
|
|
191
|
+
for (const client of [...logClients]) {
|
|
192
|
+
if (!visible.has(hostId) && !client.cursors.has(hostId))
|
|
193
|
+
continue;
|
|
194
|
+
publishTo(client, view);
|
|
195
|
+
}
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
for (const client of [...logClients]) {
|
|
199
|
+
const cursor = client.cursors.get(hostId);
|
|
200
|
+
if (cursor === undefined)
|
|
201
|
+
continue;
|
|
202
|
+
client.cursors.delete(hostId);
|
|
203
|
+
sendLog(client, logEndFrame(hostId, cursor.attempt));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
function broadcastState() {
|
|
208
|
+
broadcastStateChannel(`event: state\ndata: ${JSON.stringify(service.snapshot({ logs: false }))}\n\n`);
|
|
209
|
+
reconcileLogs();
|
|
210
|
+
}
|
|
211
|
+
function markDirty(hostId) {
|
|
212
|
+
if (disposed)
|
|
213
|
+
return;
|
|
214
|
+
dirtyHosts.add(hostId);
|
|
215
|
+
if (flushTimer !== null)
|
|
216
|
+
return;
|
|
217
|
+
flushTimer = setTimeout(() => {
|
|
218
|
+
flushTimer = null;
|
|
219
|
+
const hosts = [...dirtyHosts];
|
|
220
|
+
dirtyHosts.clear();
|
|
221
|
+
for (const hostId of hosts)
|
|
222
|
+
publishHost(hostId);
|
|
223
|
+
}, LOG_FLUSH_MS);
|
|
224
|
+
flushTimer.unref?.();
|
|
225
|
+
}
|
|
226
|
+
const onState = () => broadcastState();
|
|
227
|
+
const onLogs = (payload) => markDirty(payload.hostId);
|
|
228
|
+
const onDownload = (job) => broadcastStateChannel(`event: download\ndata: ${JSON.stringify(job)}\n\n`);
|
|
229
|
+
const onRemoteUnreachable = (event) => broadcastStateChannel(`event: remote-unreachable\ndata: ${JSON.stringify(event)}\n\n`);
|
|
230
|
+
service.on('state', onState);
|
|
231
|
+
service.on('logs', onLogs);
|
|
232
|
+
service.on('download', onDownload);
|
|
233
|
+
service.on('remote-unreachable', onRemoteUnreachable);
|
|
234
|
+
const heartbeat = setInterval(() => {
|
|
235
|
+
broadcastStateChannel('event: ping\ndata: {}\n\n');
|
|
236
|
+
for (const client of [...logClients]) {
|
|
237
|
+
if (!writeTo(client.res, 'event: ping\ndata: {}\n\n'))
|
|
238
|
+
logClients.delete(client);
|
|
239
|
+
}
|
|
240
|
+
}, HEARTBEAT_MS);
|
|
241
|
+
heartbeat.unref?.();
|
|
242
|
+
function evictOldest(clients, cap, close) {
|
|
243
|
+
while (clients.size >= cap) {
|
|
244
|
+
const oldest = clients.values().next().value;
|
|
245
|
+
if (oldest === undefined)
|
|
246
|
+
break;
|
|
247
|
+
clients.delete(oldest);
|
|
248
|
+
close(oldest);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return {
|
|
252
|
+
handleState(req, res) {
|
|
253
|
+
evictOldest(stateClients, MAX_SSE_CLIENTS, (client) => {
|
|
254
|
+
try {
|
|
255
|
+
client.end();
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
// swallow-ok: eviction closes a stream the browser already dropped
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
openStream(res);
|
|
262
|
+
res.write(`event: state\ndata: ${JSON.stringify(service.snapshot({ logs: false }))}\n\n`);
|
|
263
|
+
stateClients.add(res);
|
|
264
|
+
req.on('close', () => {
|
|
265
|
+
stateClients.delete(res);
|
|
266
|
+
});
|
|
267
|
+
},
|
|
268
|
+
handleLogs(req, res) {
|
|
269
|
+
evictOldest(logClients, MAX_SSE_LOG_CLIENTS, (client) => {
|
|
270
|
+
try {
|
|
271
|
+
client.res.end();
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
// swallow-ok: same eviction as the state channel; the stream is already gone
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
openStream(res);
|
|
278
|
+
const client = { res, cursors: new Map() };
|
|
279
|
+
const resume = parseEventId(req.headers['last-event-id']);
|
|
280
|
+
if (resume !== null)
|
|
281
|
+
client.cursors.set(resume.hostId, resume);
|
|
282
|
+
logClients.add(client);
|
|
283
|
+
for (const hostId of service.logHostIds()) {
|
|
284
|
+
const view = service.logView(hostId);
|
|
285
|
+
if (view !== null)
|
|
286
|
+
publishTo(client, view);
|
|
287
|
+
}
|
|
288
|
+
req.on('close', () => {
|
|
289
|
+
logClients.delete(client);
|
|
290
|
+
});
|
|
291
|
+
},
|
|
292
|
+
dispose() {
|
|
293
|
+
if (disposed)
|
|
294
|
+
return;
|
|
295
|
+
disposed = true;
|
|
296
|
+
service.removeListener('state', onState);
|
|
297
|
+
service.removeListener('logs', onLogs);
|
|
298
|
+
service.removeListener('download', onDownload);
|
|
299
|
+
service.removeListener('remote-unreachable', onRemoteUnreachable);
|
|
300
|
+
clearInterval(heartbeat);
|
|
301
|
+
if (flushTimer !== null) {
|
|
302
|
+
clearTimeout(flushTimer);
|
|
303
|
+
flushTimer = null;
|
|
304
|
+
}
|
|
305
|
+
dirtyHosts.clear();
|
|
306
|
+
for (const res of stateClients) {
|
|
307
|
+
try {
|
|
308
|
+
res.end();
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
// swallow-ok: dispose ends streams the browser may already have closed
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
stateClients.clear();
|
|
315
|
+
for (const client of logClients) {
|
|
316
|
+
try {
|
|
317
|
+
client.res.end();
|
|
318
|
+
}
|
|
319
|
+
catch {
|
|
320
|
+
// swallow-ok: the same dispose sweep on the log channel
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
logClients.clear();
|
|
324
|
+
},
|
|
325
|
+
};
|
|
326
|
+
}
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
/** Per-host lifecycle: the reconnect backoff, the idle-stop timer and the single teardown path. The reconnect timer is
|
|
2
|
+
* created through a callback, so this module never imports the pipeline; only the timer primitives live here. */
|
|
3
|
+
import { DEFAULT_IDLE_MINUTES, REMOTE_TUNNEL_REPAIR_SETTLE_MS } from './constants.js';
|
|
4
|
+
import { OWNERSHIP_OPTIONS, proveOwnership } from './connect/ownership.js';
|
|
5
|
+
import { errors, toErrorView } from './errors.js';
|
|
6
|
+
import { emptyRemote } from './host-runtime.js';
|
|
7
|
+
import { layoutForRuntime } from './layout.js';
|
|
8
|
+
import { cancelConflict, cancelHostKeyPrompt } from './prompts.js';
|
|
9
|
+
import { dispatch, scopeFactsFor } from './runtime/dispatch.js';
|
|
10
|
+
import { isPid, messageOf, randomDelay } from './util.js';
|
|
11
|
+
export function cancelReconnect(runtime) {
|
|
12
|
+
if (runtime.reconnectTimer) {
|
|
13
|
+
clearTimeout(runtime.reconnectTimer);
|
|
14
|
+
runtime.reconnectTimer = null;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function cancelIdleStop(runtime) {
|
|
18
|
+
if (runtime.idleTimer) {
|
|
19
|
+
clearTimeout(runtime.idleTimer);
|
|
20
|
+
runtime.idleTimer = null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export function beginLinkWork(runtime, kind) {
|
|
24
|
+
runtime.linkToken = (Number(runtime.linkToken) || 0) + 1;
|
|
25
|
+
runtime.linkBusy = kind;
|
|
26
|
+
return runtime.linkToken;
|
|
27
|
+
}
|
|
28
|
+
export function isLinkWorkCurrent(runtime, token) {
|
|
29
|
+
return runtime.linkToken === token;
|
|
30
|
+
}
|
|
31
|
+
export function endLinkWork(runtime, token) {
|
|
32
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
33
|
+
return;
|
|
34
|
+
runtime.linkBusy = null;
|
|
35
|
+
}
|
|
36
|
+
export function cancelLinkWork(runtime) {
|
|
37
|
+
runtime.linkToken = (Number(runtime.linkToken) || 0) + 1;
|
|
38
|
+
runtime.linkBusy = null;
|
|
39
|
+
}
|
|
40
|
+
export function cancelRemoteCheck(runtime) {
|
|
41
|
+
if (runtime.remoteCheckTimer) {
|
|
42
|
+
clearTimeout(runtime.remoteCheckTimer);
|
|
43
|
+
runtime.remoteCheckTimer = null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export function stopRemoteHeartbeat(runtime) {
|
|
47
|
+
if (runtime.heartbeatTimer) {
|
|
48
|
+
clearInterval(runtime.heartbeatTimer);
|
|
49
|
+
runtime.heartbeatTimer = null;
|
|
50
|
+
}
|
|
51
|
+
cancelRemoteCheck(runtime);
|
|
52
|
+
runtime.remoteFailures = 0;
|
|
53
|
+
runtime.remoteEpisode = false;
|
|
54
|
+
runtime.episodeSource = null;
|
|
55
|
+
runtime.episodeCooldownUntil = 0;
|
|
56
|
+
}
|
|
57
|
+
export function scheduleReconnect(ctx, runtime, onDue) {
|
|
58
|
+
cancelReconnect(runtime);
|
|
59
|
+
// Only `reconnect.scheduled` may arm the one retry timer: the connect-failure paths also ask for a
|
|
60
|
+
// retry, and honouring those here would run a second loop.
|
|
61
|
+
const skipped = { type: 'reconnect.skipped' };
|
|
62
|
+
const skip = () => {
|
|
63
|
+
void dispatch(effectsOf(ctx), runtime, skipped, scopeFactsFor(ctx, runtime, skipped), { caller: 'timer' });
|
|
64
|
+
};
|
|
65
|
+
if (ctx.state.disposed === true || runtime.desired !== 'connected')
|
|
66
|
+
return skip();
|
|
67
|
+
const settings = ctx.settings();
|
|
68
|
+
if (!runtime.entry.autoReconnect || !settings.autoReconnect.enabled)
|
|
69
|
+
return skip();
|
|
70
|
+
const maxAttempts = settings.autoReconnect.maxAttempts;
|
|
71
|
+
if (runtime.reconnectAttempts >= maxAttempts) {
|
|
72
|
+
const view = toErrorView(errors.network({
|
|
73
|
+
zh: `连接已断开,自动重连 ${maxAttempts} 次均失败。远端任务可能仍在运行。`,
|
|
74
|
+
en: `The connection dropped and ${maxAttempts} automatic retries failed. Remote tasks may still be running.`,
|
|
75
|
+
}));
|
|
76
|
+
const event = { type: 'reconnect.gaveup', maxAttempts, view };
|
|
77
|
+
void dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'timer' });
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const attempt = runtime.reconnectAttempts + 1;
|
|
81
|
+
const baseDelayMs = settings.autoReconnect.baseDelayMs;
|
|
82
|
+
const delay = randomDelay(baseDelayMs, baseDelayMs * 2 ** Math.min(attempt, 4));
|
|
83
|
+
const seconds = Math.round(delay / 100) / 10;
|
|
84
|
+
ctx.progress.log(runtime, 'warn', `link lost; retrying in ${seconds}s (attempt ${attempt}/${maxAttempts})`);
|
|
85
|
+
const scheduled = { type: 'reconnect.scheduled', attempt, max: maxAttempts, delayMs: delay };
|
|
86
|
+
void dispatch(effectsOf(ctx), runtime, scheduled, scopeFactsFor(ctx, runtime, scheduled), {
|
|
87
|
+
caller: 'timer',
|
|
88
|
+
armReconnect: (ms) => {
|
|
89
|
+
runtime.reconnectTimer = setTimeout(() => {
|
|
90
|
+
runtime.reconnectTimer = null;
|
|
91
|
+
onDue();
|
|
92
|
+
}, ms);
|
|
93
|
+
runtime.reconnectTimer.unref?.();
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
export function scheduleIdleStop(ctx, runtime) {
|
|
98
|
+
cancelIdleStop(runtime);
|
|
99
|
+
const minutes = Math.max(1, runtime.entry.idleMinutes ?? DEFAULT_IDLE_MINUTES);
|
|
100
|
+
runtime.idleTimer = setTimeout(() => {
|
|
101
|
+
runtime.idleTimer = null;
|
|
102
|
+
const event = { type: 'idle.elapsed' };
|
|
103
|
+
void dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'timer' }).then((result) => (result.ok ? stopRemoteForIdle(ctx, runtime) : undefined));
|
|
104
|
+
}, minutes * 60_000);
|
|
105
|
+
runtime.idleTimer.unref?.();
|
|
106
|
+
}
|
|
107
|
+
export async function stopRemoteForIdle(ctx, runtime, options = {}) {
|
|
108
|
+
// The timer is a policy for an idle host, never authority over a live link: a manual reconnect
|
|
109
|
+
// must not be torn down by the timer armed before it.
|
|
110
|
+
const linkLive = runtime.desired === 'connected' || runtime.status === 'connected' || runtime.tunnel !== null;
|
|
111
|
+
if (linkLive && options.shutdown !== true) {
|
|
112
|
+
ctx.progress.log(runtime, 'debug', 'idle stop skipped: the host is connected again');
|
|
113
|
+
return { ok: false, reason: 'still-wanted' };
|
|
114
|
+
}
|
|
115
|
+
const capturedSsh = runtime.ssh;
|
|
116
|
+
// The identity proof below awaits and the user may connect in that window: only this session may
|
|
117
|
+
// be released afterwards, never the new one.
|
|
118
|
+
const stillWanted = () => runtime.ssh !== capturedSsh ||
|
|
119
|
+
runtime.desired === 'connected' ||
|
|
120
|
+
runtime.status === 'connected' ||
|
|
121
|
+
runtime.tunnel !== null;
|
|
122
|
+
try {
|
|
123
|
+
if (capturedSsh?.connected !== true)
|
|
124
|
+
return { ok: false, reason: 'no-transport' };
|
|
125
|
+
const home = runtime.facts?.home ?? runtime.remoteHome ?? null;
|
|
126
|
+
if (typeof home !== 'string' || home.trim() === '') {
|
|
127
|
+
ctx.progress.log(runtime, 'warn', 'idle stop skipped: the remote home directory is unknown');
|
|
128
|
+
return { ok: false, reason: 'no-home' };
|
|
129
|
+
}
|
|
130
|
+
const layout = layoutForRuntime(runtime);
|
|
131
|
+
const pid = Number(runtime.remote.pid ?? runtime.remotePid ?? 0);
|
|
132
|
+
if (!isPid(pid))
|
|
133
|
+
return { ok: false, reason: 'pid-unknown' };
|
|
134
|
+
const proof = await proveOwnership(ctx, runtime, {
|
|
135
|
+
...OWNERSHIP_OPTIONS.idle,
|
|
136
|
+
pid,
|
|
137
|
+
layout,
|
|
138
|
+
profile: runtime.remote.profile ?? runtime.remoteProfile ?? '',
|
|
139
|
+
});
|
|
140
|
+
if (proof.ok !== true) {
|
|
141
|
+
ctx.progress.log(runtime, 'warn', `idle stop skipped: ${proof.reason}`);
|
|
142
|
+
return { ok: false, reason: proof.reason };
|
|
143
|
+
}
|
|
144
|
+
if (options.shutdown !== true && stillWanted()) {
|
|
145
|
+
ctx.progress.log(runtime, 'debug', 'idle stop skipped: the host is connected again');
|
|
146
|
+
return { ok: false, reason: 'still-wanted' };
|
|
147
|
+
}
|
|
148
|
+
const stopped = await ctx.deps.stopWeb(capturedSsh, layout, { pid });
|
|
149
|
+
if (stopped?.ok !== true) {
|
|
150
|
+
const why = stopped?.reason ?? 'unknown';
|
|
151
|
+
ctx.progress.log(runtime, 'warn', `idle stop did not confirm (${why}); the remote may still be running`);
|
|
152
|
+
return { ok: false, reason: stopped?.reason ?? 'not-confirmed' };
|
|
153
|
+
}
|
|
154
|
+
runtime.remotePid = null;
|
|
155
|
+
return { ok: true };
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
// swallow-ok: the idle stop is best effort; its failure is only a warning and the timer is gone
|
|
159
|
+
ctx.progress.log(runtime, 'warn', 'idle stop failed:', messageOf(error));
|
|
160
|
+
return { ok: false, reason: 'error' };
|
|
161
|
+
}
|
|
162
|
+
finally {
|
|
163
|
+
if (runtime.ssh === capturedSsh)
|
|
164
|
+
await disposeSsh(runtime);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
export async function closeTunnel(runtime) {
|
|
168
|
+
const tunnel = runtime.tunnel;
|
|
169
|
+
runtime.tunnel = null;
|
|
170
|
+
runtime.remote.localPort = null;
|
|
171
|
+
if (tunnel) {
|
|
172
|
+
try {
|
|
173
|
+
await tunnel.close();
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
// swallow-ok: teardown continues; a dead tunnel needs no second error
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
export async function disposeSsh(runtime) {
|
|
181
|
+
const ssh = runtime.ssh;
|
|
182
|
+
runtime.ssh = null;
|
|
183
|
+
const jump = runtime.jumpSsh;
|
|
184
|
+
runtime.jumpSsh = null;
|
|
185
|
+
if (ssh) {
|
|
186
|
+
try {
|
|
187
|
+
await ssh.dispose();
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
// swallow-ok: disposal must not stop the rest of the teardown
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (jump) {
|
|
194
|
+
try {
|
|
195
|
+
await jump.dispose();
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
// swallow-ok: the same disposal rule as the target transport
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
async function settleTunnelRepair(ctx, runtime) {
|
|
203
|
+
const repair = runtime.tunnelRepair;
|
|
204
|
+
if (!repair)
|
|
205
|
+
return;
|
|
206
|
+
const timeoutMs = Number(ctx.timers?.tunnelRepairSettleMs ?? REMOTE_TUNNEL_REPAIR_SETTLE_MS);
|
|
207
|
+
let timer = null;
|
|
208
|
+
const timeout = new Promise((resolve) => {
|
|
209
|
+
timer = setTimeout(() => resolve('timeout'), Math.max(0, timeoutMs));
|
|
210
|
+
timer.unref?.();
|
|
211
|
+
});
|
|
212
|
+
try {
|
|
213
|
+
const outcome = await Promise.race([repair, timeout]);
|
|
214
|
+
if (outcome === 'timeout') {
|
|
215
|
+
ctx.progress.log(runtime, 'warn', 'tunnel rebuild did not finish in time; abandoning it');
|
|
216
|
+
runtime.tunnelRepair = null;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
// swallow-ok: the rebuild reports its own failure; teardown must still proceed
|
|
221
|
+
}
|
|
222
|
+
finally {
|
|
223
|
+
if (timer !== null)
|
|
224
|
+
clearTimeout(timer);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
export async function teardownRuntime(ctx, runtime, options = {}) {
|
|
228
|
+
cancelConflict(runtime);
|
|
229
|
+
cancelHostKeyPrompt(runtime);
|
|
230
|
+
cancelLinkWork(runtime);
|
|
231
|
+
stopRemoteHeartbeat(runtime);
|
|
232
|
+
runtime.closing = true;
|
|
233
|
+
cancelIdleStop(runtime);
|
|
234
|
+
await settleTunnelRepair(ctx, runtime);
|
|
235
|
+
// Remember where the remote lives before the facts below are cleared: the idle policy and a later
|
|
236
|
+
// stop still need the real home, never a literal `~`.
|
|
237
|
+
if (typeof runtime.facts?.home === 'string' && runtime.facts.home.trim() !== '') {
|
|
238
|
+
runtime.remoteHome = runtime.facts.home;
|
|
239
|
+
}
|
|
240
|
+
if (typeof runtime.remote.profile === 'string' && runtime.remote.profile !== '') {
|
|
241
|
+
runtime.remoteProfile = runtime.remote.profile;
|
|
242
|
+
}
|
|
243
|
+
const boundPid = Number(runtime.remote.pid ?? 0);
|
|
244
|
+
if (isPid(boundPid))
|
|
245
|
+
runtime.remotePid = boundPid;
|
|
246
|
+
let remoteStopped = false;
|
|
247
|
+
if (options.stopRemote && runtime.ssh?.connected) {
|
|
248
|
+
try {
|
|
249
|
+
const result = await ctx.deps.stopWeb(runtime.ssh, layoutForRuntime(runtime), {
|
|
250
|
+
pid: runtime.remote.pid ?? undefined,
|
|
251
|
+
});
|
|
252
|
+
remoteStopped = result?.ok === true;
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
ctx.progress.log(runtime, 'warn', 'stop remote failed:', messageOf(error));
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (remoteStopped)
|
|
259
|
+
runtime.remotePid = null;
|
|
260
|
+
await closeTunnel(runtime);
|
|
261
|
+
if (!options.keepSshForIdle)
|
|
262
|
+
await disposeSsh(runtime);
|
|
263
|
+
if (!options.keepRemote) {
|
|
264
|
+
runtime.remote = { ...emptyRemote(), version: runtime.remote.version };
|
|
265
|
+
runtime.token = null;
|
|
266
|
+
runtime.facts = null;
|
|
267
|
+
runtime.exchange = null;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
export async function disconnectHost(ctx, runtime, options = {}) {
|
|
271
|
+
ctx.progress.log(runtime, 'info', `disconnect requested (keepAlive=${runtime.entry.keepAlive})`);
|
|
272
|
+
const event = {
|
|
273
|
+
type: 'disconnect.requested',
|
|
274
|
+
...(options.stopRemote === true ? { stopRemote: true } : {}),
|
|
275
|
+
...(options.stopped === true ? { stopped: true } : {}),
|
|
276
|
+
};
|
|
277
|
+
await dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'script' });
|
|
278
|
+
runtime.token = null;
|
|
279
|
+
return { ok: true };
|
|
280
|
+
}
|
|
281
|
+
export async function releaseRuntimeForShutdown(ctx, runtime, stopRemote) {
|
|
282
|
+
await settleTunnelRepair(ctx, runtime);
|
|
283
|
+
try {
|
|
284
|
+
if (stopRemote) {
|
|
285
|
+
await stopRemoteForIdle(ctx, runtime, { shutdown: true });
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
await closeTunnel(runtime);
|
|
289
|
+
await disposeSsh(runtime);
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
// swallow-ok: shutdown is best effort; every resource is released above
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
export async function shutdownAll(ctx) {
|
|
296
|
+
for (const runtime of ctx.state.runtimes.values()) {
|
|
297
|
+
const event = { type: 'shutdown' };
|
|
298
|
+
await dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'silent' });
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/** The effects of this module bound to one context: it owns the timers and the teardown path, so it builds the effect
|
|
302
|
+
* object instead of importing `effects.ts` (which imports it); `run`/`flushLogs` are unreachable but required. */
|
|
303
|
+
function effectsOf(ctx) {
|
|
304
|
+
return {
|
|
305
|
+
emit: () => ctx.emitState(),
|
|
306
|
+
log: (runtime, level, message) => ctx.progress.log(runtime, level, message),
|
|
307
|
+
logFailure: (runtime, phase, label, view) => ctx.progress.logFailure(runtime, view ?? runtime.error, { phase, label }),
|
|
308
|
+
arm: (runtime, timer) => {
|
|
309
|
+
if (timer === 'idle')
|
|
310
|
+
scheduleIdleStop(ctx, runtime);
|
|
311
|
+
},
|
|
312
|
+
disarm: (runtime, timer) => {
|
|
313
|
+
if (timer === 'reconnect')
|
|
314
|
+
cancelReconnect(runtime);
|
|
315
|
+
else if (timer === 'idle')
|
|
316
|
+
cancelIdleStop(runtime);
|
|
317
|
+
else
|
|
318
|
+
stopRemoteHeartbeat(runtime);
|
|
319
|
+
},
|
|
320
|
+
settlePrompts: (runtime) => {
|
|
321
|
+
cancelHostKeyPrompt(runtime);
|
|
322
|
+
cancelConflict(runtime);
|
|
323
|
+
},
|
|
324
|
+
closeLink: (runtime) => {
|
|
325
|
+
void closeTunnel(runtime);
|
|
326
|
+
},
|
|
327
|
+
teardown: async (runtime, options) => {
|
|
328
|
+
if (options.shutdown === true) {
|
|
329
|
+
await releaseRuntimeForShutdown(ctx, runtime, options.stopRemote === true);
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
await teardownRuntime(ctx, runtime, {
|
|
333
|
+
stopRemote: options.stopRemote === true,
|
|
334
|
+
keepRemote: options.keepRemote === true,
|
|
335
|
+
keepSshForIdle: options.keepSshForIdle === true,
|
|
336
|
+
});
|
|
337
|
+
},
|
|
338
|
+
apply: (runtime, patch) => {
|
|
339
|
+
if (patch.kind === 'mark-detached') {
|
|
340
|
+
runtime.remote.uiReady = false;
|
|
341
|
+
runtime.remote.localPort = null;
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
if (patch.kind === 'mark-ui-up') {
|
|
345
|
+
runtime.remote.uiReady = true;
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
if (patch.kind === 'mark-attached') {
|
|
349
|
+
runtime.remote.uiReady = true;
|
|
350
|
+
runtime.remote.viewRev = (Number(runtime.remote.viewRev) || 0) + 1;
|
|
351
|
+
runtime.tunnelRepairFailures = 0;
|
|
352
|
+
runtime.nextTunnelRepairAt = 0;
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
if (patch.kind === 'clear-conflict') {
|
|
356
|
+
runtime.conflict = null;
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
if (patch.kind === 'publish-active-host') {
|
|
360
|
+
ctx.state.activeHostId = patch.hostId;
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
runtime.remote.uiReady = patch.uiReady === true;
|
|
364
|
+
runtime.remote.localPort = patch.localPort;
|
|
365
|
+
},
|
|
366
|
+
flushLogs: () => { },
|
|
367
|
+
};
|
|
368
|
+
}
|