dsh-apk-vm 0.12.0 → 0.12.2
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/CHANGELOG.md +64 -4
- package/DEMO.md +9 -6
- package/README.md +71 -13
- package/SECURITY.md +19 -2
- package/client.js +740 -16
- package/cordis.patch.yml +22 -0
- package/docs/PRIVACY.md +11 -0
- package/docs/README.md +17 -9
- package/docs/SUBMISSION.md +2 -1
- package/docs/screenshot-activity.png +0 -0
- package/docs/screenshot-apk-files.png +0 -0
- package/docs/screenshot-debug.png +0 -0
- package/docs/screenshot-device.png +0 -0
- package/docs/screenshot-environment.png +0 -0
- package/docs/screenshot-panel.png +0 -0
- package/icon.svg +18 -7
- package/index.js +505 -44
- package/lib/android.js +48 -1
- package/lib/emulator-inventory.js +1526 -0
- package/lib/instances.js +97 -1
- package/lib/media.js +820 -0
- package/lib/remote-instance.js +608 -0
- package/lib/remote.js +1180 -0
- package/package.json +20 -4
- package/scripts/check-version.mjs +30 -0
- package/docs/screenshot-sidebar.png +0 -0
package/lib/remote.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { spawn } from 'node:child_process';
|
|
10
10
|
import { existsSync } from 'node:fs';
|
|
11
|
+
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
11
12
|
import net from 'node:net';
|
|
12
13
|
import path from 'node:path';
|
|
13
14
|
|
|
@@ -41,6 +42,26 @@ function findFreePort() {
|
|
|
41
42
|
});
|
|
42
43
|
}
|
|
43
44
|
|
|
45
|
+
function isLocalPortFree(port) {
|
|
46
|
+
return new Promise((resolve) => {
|
|
47
|
+
const server = net.createServer();
|
|
48
|
+
server.once('error', () => resolve(false));
|
|
49
|
+
server.once('listening', () => server.close(() => resolve(true)));
|
|
50
|
+
try {
|
|
51
|
+
server.listen(port, '127.0.0.1');
|
|
52
|
+
} catch {
|
|
53
|
+
resolve(false);
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function sleep(ms) {
|
|
59
|
+
return new Promise((resolve) => {
|
|
60
|
+
const timer = setTimeout(resolve, Math.max(0, ms));
|
|
61
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
44
65
|
function waitForPort(port, timeoutMs = 20000) {
|
|
45
66
|
const deadline = Date.now() + timeoutMs;
|
|
46
67
|
return new Promise((resolve, reject) => {
|
|
@@ -166,3 +187,1162 @@ export function buildSshTunnelArgs(options) {
|
|
|
166
187
|
const tunnel = new SshAdbTunnel({ ...options, localPort: options.localPort || 15037 });
|
|
167
188
|
return tunnel.buildArgs();
|
|
168
189
|
}
|
|
190
|
+
|
|
191
|
+
// ---------------------------------------------------------------------------
|
|
192
|
+
// Remote VM host: profile store + bounded SSH helpers.
|
|
193
|
+
//
|
|
194
|
+
// The "remote VM" feature treats the SSH host as a proxy for the guest: the
|
|
195
|
+
// panel forwards a loopback port to the remote emulator's adb port, runs
|
|
196
|
+
// `adb connect 127.0.0.1:<localPort>` and attaches that device like any other
|
|
197
|
+
// adb device. Optionally the same SSH connection runs a *fixed* headless
|
|
198
|
+
// emulator command (`-no-window -no-audio -no-boot-anim -gpu
|
|
199
|
+
// swiftshader_indirect`) so the remote host can be a plain build box.
|
|
200
|
+
//
|
|
201
|
+
// Security notes:
|
|
202
|
+
// * only a fixed command shape is executed remotely; every value is validated
|
|
203
|
+
// and single-quote escaped, so a profile field can never inject a shell
|
|
204
|
+
// command;
|
|
205
|
+
// * the SSH key path is caller-owned; nothing is cached except the profile JSON
|
|
206
|
+
// under <profile>/.apk-vm/remote-profile.json;
|
|
207
|
+
// * `BatchMode=yes` is used, so a password prompt fails instead of hanging.
|
|
208
|
+
// ---------------------------------------------------------------------------
|
|
209
|
+
|
|
210
|
+
export const REMOTE_PROFILE_VERSION = 1;
|
|
211
|
+
/** Multi-profile book file format (one file can hold several hosts/AVDs). */
|
|
212
|
+
export const REMOTE_PROFILES_VERSION = 2;
|
|
213
|
+
const AVD_NAME_RE = /^[A-Za-z0-9._-]{1,64}$/;
|
|
214
|
+
const REMOTE_PATH_RE = /^[A-Za-z0-9._/+-]{1,500}$/;
|
|
215
|
+
const PROFILE_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
|
|
216
|
+
|
|
217
|
+
/** Quote one argument for a POSIX `sh` command line (single quotes). */
|
|
218
|
+
export function quoteRemoteArg(value) {
|
|
219
|
+
const text = String(value == null ? '' : value);
|
|
220
|
+
if (!text) throw new Error('remote command argument is empty');
|
|
221
|
+
if (/[\u0000-\u001f\u007f]/.test(text)) throw new Error('remote command argument contains control characters');
|
|
222
|
+
return `'${text.replace(/'/g, `'\\''`)}'`;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function optionalRemotePath(value, label) {
|
|
226
|
+
const text = String(value == null ? '' : value).trim();
|
|
227
|
+
if (!text) return '';
|
|
228
|
+
if (!REMOTE_PATH_RE.test(text)) throw new Error(`invalid ${label}: ${JSON.stringify(text.slice(0, 80))}`);
|
|
229
|
+
return text;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function optionalAvdName(value) {
|
|
233
|
+
const text = String(value == null ? '' : value).trim();
|
|
234
|
+
if (!text) return '';
|
|
235
|
+
if (!AVD_NAME_RE.test(text)) throw new Error(`invalid AVD name: ${JSON.stringify(text.slice(0, 80))}`);
|
|
236
|
+
return text;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Optional human-readable profile label (UTF-8, control characters rejected). */
|
|
240
|
+
function optionalProfileName(value) {
|
|
241
|
+
const text = String(value == null ? '' : value).trim();
|
|
242
|
+
if (!text) return '';
|
|
243
|
+
if (/[\u0000-\u001f\u007f]/.test(text)) throw new Error('invalid remote profile name');
|
|
244
|
+
return text.slice(0, 64);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Optional remote emulator console port (0 = auto-allocate). */
|
|
248
|
+
function optionalConsolePort(value) {
|
|
249
|
+
if (value == null || value === '' || value === 0 || value === '0') return 0;
|
|
250
|
+
return asConsolePort(value);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Normalize/validate a remote host profile (throws on invalid input). */
|
|
254
|
+
export function normalizeRemoteProfile(input = {}) {
|
|
255
|
+
const source = input && typeof input === 'object' ? input : {};
|
|
256
|
+
const profile = {
|
|
257
|
+
host: safeHost(source.host),
|
|
258
|
+
user: safeUser(source.user),
|
|
259
|
+
sshPort: asPort(source.sshPort, 22),
|
|
260
|
+
remotePort: asPort(source.remotePort, 5558),
|
|
261
|
+
localPort: source.localPort == null || source.localPort === '' ? 0 : asPort(source.localPort, 0),
|
|
262
|
+
consolePort: optionalConsolePort(source.consolePort),
|
|
263
|
+
name: optionalProfileName(source.name),
|
|
264
|
+
keyPath: String(source.keyPath == null ? '' : source.keyPath).trim() ? path.resolve(String(source.keyPath)) : '',
|
|
265
|
+
sshPath: String(source.sshPath == null ? '' : source.sshPath).trim() || 'ssh',
|
|
266
|
+
avdName: optionalAvdName(source.avdName),
|
|
267
|
+
emulatorPath: optionalRemotePath(source.emulatorPath, 'remote emulator path'),
|
|
268
|
+
sdkRoot: optionalRemotePath(source.sdkRoot, 'remote SDK root'),
|
|
269
|
+
launch: source.launch === true,
|
|
270
|
+
updatedAt: Date.now(),
|
|
271
|
+
};
|
|
272
|
+
if (profile.keyPath && !existsSync(profile.keyPath)) throw new Error(`SSH key not found: ${profile.keyPath}`);
|
|
273
|
+
if (!/^[A-Za-z0-9._/:-]{1,500}$/.test(profile.sshPath)) throw new Error(`invalid ssh executable: ${JSON.stringify(profile.sshPath)}`);
|
|
274
|
+
return profile;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** `<dataDir>/.apk-vm/remote-profile.json` — same convention as the app registry. */
|
|
278
|
+
export function defaultRemoteProfilePath(dataDir) {
|
|
279
|
+
return path.join(String(dataDir || process.cwd()), '.apk-vm', 'remote-profile.json');
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Small JSON profile store for the last used remote host. Tolerant of a missing
|
|
284
|
+
* or corrupt file: load() returns `{ok:true, profile:null}` instead of throwing,
|
|
285
|
+
* so a broken profile never bricks the panel.
|
|
286
|
+
*/
|
|
287
|
+
export class RemoteProfileStore {
|
|
288
|
+
constructor(options = {}) {
|
|
289
|
+
this.file = String(options.file || defaultRemoteProfilePath(process.cwd()));
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async load() {
|
|
293
|
+
let text;
|
|
294
|
+
try {
|
|
295
|
+
text = await readFile(this.file, 'utf8');
|
|
296
|
+
} catch (error) {
|
|
297
|
+
if (error && error.code === 'ENOENT') return { ok: true, profile: null };
|
|
298
|
+
return { ok: false, error: error && error.message ? error.message : String(error), profile: null };
|
|
299
|
+
}
|
|
300
|
+
try {
|
|
301
|
+
const parsed = JSON.parse(String(text).replace(/^\uFEFF/, ''));
|
|
302
|
+
const raw = parsed && typeof parsed === 'object' && parsed.profile && typeof parsed.profile === 'object' ? parsed.profile : parsed;
|
|
303
|
+
const profile = normalizeRemoteProfile(raw);
|
|
304
|
+
return { ok: true, profile };
|
|
305
|
+
} catch (error) {
|
|
306
|
+
return { ok: false, error: `remote profile is invalid: ${error.message}`, profile: null };
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async save(profile) {
|
|
311
|
+
const normalized = normalizeRemoteProfile(profile);
|
|
312
|
+
const payload = `${JSON.stringify({ version: REMOTE_PROFILE_VERSION, updatedAt: normalized.updatedAt, profile: normalized }, null, 2)}\n`;
|
|
313
|
+
try {
|
|
314
|
+
await mkdir(path.dirname(this.file), { recursive: true });
|
|
315
|
+
const temp = `${this.file}.${process.pid}.${Date.now()}.tmp`;
|
|
316
|
+
await writeFile(temp, payload, 'utf8');
|
|
317
|
+
await rename(temp, this.file);
|
|
318
|
+
return { ok: true, file: this.file };
|
|
319
|
+
} catch (error) {
|
|
320
|
+
return { ok: false, file: this.file, error: error && error.message ? error.message : String(error) };
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async clear() {
|
|
325
|
+
try {
|
|
326
|
+
await rm(this.file, { force: true });
|
|
327
|
+
return { ok: true };
|
|
328
|
+
} catch (error) {
|
|
329
|
+
return { ok: false, error: error && error.message ? error.message : String(error) };
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** `<dataDir>/.apk-vm/remote-profiles.json` — multi-profile book. */
|
|
335
|
+
export function defaultRemoteProfilesPath(dataDir) {
|
|
336
|
+
return path.join(String(dataDir || process.cwd()), '.apk-vm', 'remote-profiles.json');
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Stable identity for "same remote target", used to update instead of duplicate. */
|
|
340
|
+
function profileIdentity(profile) {
|
|
341
|
+
return [profile.host, profile.user, profile.sshPort, profile.avdName, profile.remotePort]
|
|
342
|
+
.map((part) => String(part == null ? '' : part).toLowerCase())
|
|
343
|
+
.join('|');
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function buildProfileId(profile) {
|
|
347
|
+
const avd = profile.avdName || `port${profile.remotePort}`;
|
|
348
|
+
const base = `${avd}-${profile.user || 'root'}-${profile.host}`
|
|
349
|
+
.toLowerCase()
|
|
350
|
+
.replace(/[^a-z0-9._-]+/g, '-')
|
|
351
|
+
.replace(/^-+|-+$/g, '')
|
|
352
|
+
.slice(0, 64);
|
|
353
|
+
return base || 'remote';
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function uniqueProfileId(entries, base) {
|
|
357
|
+
const used = new Set(entries.map((entry) => entry.id));
|
|
358
|
+
if (!used.has(base)) return base;
|
|
359
|
+
for (let suffix = 2; suffix < 1000; suffix += 1) {
|
|
360
|
+
const candidate = `${base.slice(0, 58)}-${suffix}`;
|
|
361
|
+
if (!used.has(candidate)) return candidate;
|
|
362
|
+
}
|
|
363
|
+
return `${base.slice(0, 50)}-${Date.now()}`;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Multi-profile JSON book for remote hosts (`<dataDir>/.apk-vm/remote-profiles.json`).
|
|
368
|
+
*
|
|
369
|
+
* Profiles are keyed by a stable `id` and a profile carrying the same
|
|
370
|
+
* host/user/sshPort/AVD identity is updated in place instead of duplicated.
|
|
371
|
+
* Writes are atomic (temp file + rename) and reads are tolerant of a missing,
|
|
372
|
+
* legacy single-profile or corrupt file, so a bad file can never brick the
|
|
373
|
+
* panel: `list()` reports the error but returns an empty list.
|
|
374
|
+
*/
|
|
375
|
+
export class RemoteProfileBook {
|
|
376
|
+
constructor(options = {}) {
|
|
377
|
+
this.file = String(options.file || defaultRemoteProfilesPath(process.cwd()));
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
async _read() {
|
|
381
|
+
let text;
|
|
382
|
+
try {
|
|
383
|
+
text = await readFile(this.file, 'utf8');
|
|
384
|
+
} catch (error) {
|
|
385
|
+
if (error && error.code === 'ENOENT') return { ok: true, recoverable: true, entries: [], error: null };
|
|
386
|
+
return {
|
|
387
|
+
ok: false,
|
|
388
|
+
recoverable: false,
|
|
389
|
+
entries: [],
|
|
390
|
+
error: error && error.message ? error.message : String(error),
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
try {
|
|
394
|
+
const parsed = JSON.parse(String(text).replace(/^\uFEFF/, ''));
|
|
395
|
+
let rawList;
|
|
396
|
+
if (Array.isArray(parsed)) rawList = parsed;
|
|
397
|
+
else if (parsed && Array.isArray(parsed.profiles)) rawList = parsed.profiles;
|
|
398
|
+
else if (parsed && typeof parsed === 'object' && parsed.profile && typeof parsed.profile === 'object') rawList = [parsed];
|
|
399
|
+
else if (parsed && typeof parsed === 'object' && parsed.host) rawList = [parsed];
|
|
400
|
+
else rawList = [];
|
|
401
|
+
const entries = [];
|
|
402
|
+
let skipped = 0;
|
|
403
|
+
for (const raw of rawList) {
|
|
404
|
+
try {
|
|
405
|
+
if (!raw || typeof raw !== 'object') throw new Error('entry is not an object');
|
|
406
|
+
const source = raw.profile && typeof raw.profile === 'object' ? raw.profile : raw;
|
|
407
|
+
const profile = normalizeRemoteProfile(source);
|
|
408
|
+
const id = typeof raw.id === 'string' && PROFILE_ID_RE.test(raw.id) ? raw.id : buildProfileId(profile);
|
|
409
|
+
entries.push({ id, profile });
|
|
410
|
+
} catch {
|
|
411
|
+
skipped += 1;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
const note = skipped ? `${skipped} invalid remote profile ${skipped === 1 ? 'entry was' : 'entries were'} skipped` : null;
|
|
415
|
+
return { ok: true, recoverable: true, entries, error: note };
|
|
416
|
+
} catch (error) {
|
|
417
|
+
return {
|
|
418
|
+
ok: true,
|
|
419
|
+
recoverable: true,
|
|
420
|
+
entries: [],
|
|
421
|
+
error: `remote profiles file is invalid: ${error && error.message ? error.message : String(error)}`,
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async _write(entries) {
|
|
427
|
+
const payload = `${JSON.stringify({
|
|
428
|
+
version: REMOTE_PROFILES_VERSION,
|
|
429
|
+
updatedAt: Date.now(),
|
|
430
|
+
profiles: entries.map(({ id, profile }) => ({ id, profile })),
|
|
431
|
+
}, null, 2)}\n`;
|
|
432
|
+
await mkdir(path.dirname(this.file), { recursive: true });
|
|
433
|
+
const temp = `${this.file}.${process.pid}.${Date.now()}.tmp`;
|
|
434
|
+
await writeFile(temp, payload, 'utf8');
|
|
435
|
+
await rename(temp, this.file);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** List every valid profile: `{ok, file, profiles:[{id, ...profile}], error}`. */
|
|
439
|
+
async list() {
|
|
440
|
+
const read = await this._read();
|
|
441
|
+
if (!read.ok) return { ok: false, file: this.file, profiles: [], error: read.error };
|
|
442
|
+
const profiles = read.entries.map(({ id, profile }) => ({ id, ...profile }));
|
|
443
|
+
profiles.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
|
|
444
|
+
return { ok: true, file: this.file, profiles, error: read.error };
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
async get(id) {
|
|
448
|
+
const wanted = String(id == null ? '' : id).trim();
|
|
449
|
+
const read = await this._read();
|
|
450
|
+
if (!read.ok) return { ok: false, file: this.file, id: wanted, profile: null, error: read.error };
|
|
451
|
+
const entry = read.entries.find((candidate) => candidate.id === wanted);
|
|
452
|
+
if (!entry) return { ok: true, file: this.file, id: wanted, profile: null, error: read.error };
|
|
453
|
+
return { ok: true, file: this.file, id: entry.id, profile: { id: entry.id, ...entry.profile }, error: read.error };
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Upsert a profile. `options.id` pins/overwrites one entry; otherwise an entry
|
|
458
|
+
* with the same remote identity is updated. Returns the stored profile.
|
|
459
|
+
*/
|
|
460
|
+
async save(input, options = {}) {
|
|
461
|
+
let profile;
|
|
462
|
+
try {
|
|
463
|
+
profile = normalizeRemoteProfile(input);
|
|
464
|
+
} catch (error) {
|
|
465
|
+
return {
|
|
466
|
+
ok: false,
|
|
467
|
+
file: this.file,
|
|
468
|
+
id: null,
|
|
469
|
+
profile: null,
|
|
470
|
+
error: error && error.message ? error.message : String(error),
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
if (options.name != null) {
|
|
474
|
+
try {
|
|
475
|
+
profile.name = optionalProfileName(options.name) || profile.name;
|
|
476
|
+
} catch (error) {
|
|
477
|
+
return { ok: false, file: this.file, id: null, profile: null, error: error.message };
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
const requestedId = options.id == null ? '' : String(options.id).trim();
|
|
481
|
+
if (requestedId && !PROFILE_ID_RE.test(requestedId)) {
|
|
482
|
+
return {
|
|
483
|
+
ok: false,
|
|
484
|
+
file: this.file,
|
|
485
|
+
id: null,
|
|
486
|
+
profile: null,
|
|
487
|
+
error: 'invalid remote profile id (letters, digits, dot, dash, underscore; max 64)',
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
const read = await this._read();
|
|
491
|
+
if (!read.ok && !read.recoverable) {
|
|
492
|
+
return { ok: false, file: this.file, id: null, profile: null, error: read.error };
|
|
493
|
+
}
|
|
494
|
+
const entries = read.entries;
|
|
495
|
+
const key = profileIdentity(profile);
|
|
496
|
+
let index = requestedId ? entries.findIndex((entry) => entry.id === requestedId) : -1;
|
|
497
|
+
if (index < 0) index = entries.findIndex((entry) => profileIdentity(entry.profile) === key);
|
|
498
|
+
const id = requestedId || (index >= 0 ? entries[index].id : uniqueProfileId(entries, buildProfileId(profile)));
|
|
499
|
+
const entry = { id, profile };
|
|
500
|
+
if (index >= 0) entries[index] = entry;
|
|
501
|
+
else entries.push(entry);
|
|
502
|
+
try {
|
|
503
|
+
await this._write(entries);
|
|
504
|
+
} catch (error) {
|
|
505
|
+
return {
|
|
506
|
+
ok: false,
|
|
507
|
+
file: this.file,
|
|
508
|
+
id,
|
|
509
|
+
profile: null,
|
|
510
|
+
error: error && error.message ? error.message : String(error),
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
return { ok: true, file: this.file, id, profile: { id, ...profile }, error: null };
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** Delete one saved profile by id (no-op when it is already gone). */
|
|
517
|
+
async forget(id) {
|
|
518
|
+
const wanted = String(id == null ? '' : id).trim();
|
|
519
|
+
if (!wanted) {
|
|
520
|
+
return { ok: false, file: this.file, removed: [], error: 'forget requires a remote profile id' };
|
|
521
|
+
}
|
|
522
|
+
if (!PROFILE_ID_RE.test(wanted)) {
|
|
523
|
+
return { ok: false, file: this.file, removed: [], error: 'invalid remote profile id' };
|
|
524
|
+
}
|
|
525
|
+
const read = await this._read();
|
|
526
|
+
if (!read.ok && !read.recoverable) {
|
|
527
|
+
return { ok: false, file: this.file, removed: [], error: read.error };
|
|
528
|
+
}
|
|
529
|
+
const removed = [];
|
|
530
|
+
const kept = [];
|
|
531
|
+
for (const entry of read.entries) {
|
|
532
|
+
if (entry.id === wanted) removed.push(entry.id);
|
|
533
|
+
else kept.push(entry);
|
|
534
|
+
}
|
|
535
|
+
if (!removed.length) return { ok: true, file: this.file, removed, error: null };
|
|
536
|
+
try {
|
|
537
|
+
await this._write(kept);
|
|
538
|
+
} catch (error) {
|
|
539
|
+
return {
|
|
540
|
+
ok: false,
|
|
541
|
+
file: this.file,
|
|
542
|
+
removed: [],
|
|
543
|
+
error: error && error.message ? error.message : String(error),
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
return { ok: true, file: this.file, removed, error: null };
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** Remove the whole profiles file. */
|
|
550
|
+
async clear() {
|
|
551
|
+
try {
|
|
552
|
+
await rm(this.file, { force: true });
|
|
553
|
+
return { ok: true, file: this.file, error: null };
|
|
554
|
+
} catch (error) {
|
|
555
|
+
return { ok: false, file: this.file, error: error && error.message ? error.message : String(error) };
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function asConsolePort(value) {
|
|
561
|
+
const n = Number(value);
|
|
562
|
+
if (!Number.isInteger(n) || n < 5554 || n > 5682 || n % 2 !== 0) {
|
|
563
|
+
throw new Error('remote emulator console port must be an even integer between 5554 and 5682');
|
|
564
|
+
}
|
|
565
|
+
return n;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* Validate optional extra emulator arguments (camera/mic flags from
|
|
570
|
+
* lib/media.js). They are our own strings, but are still rejected for control
|
|
571
|
+
* characters and quoted individually before interpolation.
|
|
572
|
+
*/
|
|
573
|
+
export function normalizeExtraEmulatorArgs(value) {
|
|
574
|
+
if (value == null) return [];
|
|
575
|
+
if (!Array.isArray(value)) throw new Error('extraEmulatorArgs must be an array of strings');
|
|
576
|
+
const args = [];
|
|
577
|
+
const seen = new Set();
|
|
578
|
+
for (const item of value) {
|
|
579
|
+
const text = String(item == null ? '' : item).trim();
|
|
580
|
+
if (!text) throw new Error('extra emulator arguments must be non-empty strings');
|
|
581
|
+
if (/[\u0000-\u001f\u007f]/.test(text)) throw new Error('extra emulator arguments must not contain control characters');
|
|
582
|
+
if (text.length > 200) throw new Error('extra emulator argument is too long (max 200 characters)');
|
|
583
|
+
if (seen.has(text)) continue;
|
|
584
|
+
seen.add(text);
|
|
585
|
+
args.push(text);
|
|
586
|
+
}
|
|
587
|
+
return args;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
const RESERVED_EMULATOR_FLAGS = new Set(['-avd', '-no-window', '-no-boot-anim', '-gpu', '-port']);
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Build the fixed remote command that starts a headless AVD. Returns
|
|
594
|
+
* `{command, consolePort, adbPort, logPath, extraArgs}`. All values are
|
|
595
|
+
* validated; the command is a single `nohup <emulator> -avd <avd> ... &` with
|
|
596
|
+
* no shell metacharacters from user input.
|
|
597
|
+
*
|
|
598
|
+
* `extraEmulatorArgs` (string[], runtime-only; camera/mic flags) are appended
|
|
599
|
+
* in order before `-port <consolePort>`. `enableAudio: true` omits the built-in
|
|
600
|
+
* `-no-audio` so the guest can record from a virtual microphone.
|
|
601
|
+
*/
|
|
602
|
+
export function buildRemoteEmulatorStartCommand(options = {}) {
|
|
603
|
+
const avdName = optionalAvdName(options.avdName);
|
|
604
|
+
if (!avdName) throw new Error('launch requires a remote AVD name');
|
|
605
|
+
const consolePort = asConsolePort(options.consolePort == null ? 5554 : options.consolePort);
|
|
606
|
+
const logPath = `/tmp/apk-vm-emulator-${consolePort}.log`;
|
|
607
|
+
const emulator = optionalRemotePath(options.emulatorPath, 'remote emulator path') || 'emulator';
|
|
608
|
+
const sdkRoot = optionalRemotePath(options.sdkRoot, 'remote SDK root');
|
|
609
|
+
const envPrefix = sdkRoot ? `ANDROID_SDK_ROOT=${quoteRemoteArg(sdkRoot)} ANDROID_HOME=${quoteRemoteArg(sdkRoot)} ` : '';
|
|
610
|
+
const extraArgs = normalizeExtraEmulatorArgs(options.extraEmulatorArgs);
|
|
611
|
+
const enableAudio = options.enableAudio === true;
|
|
612
|
+
const argv = [envPrefix + `nohup ${quoteRemoteArg(emulator)}`, '-avd', quoteRemoteArg(avdName), '-no-window'];
|
|
613
|
+
if (!enableAudio) argv.push('-no-audio');
|
|
614
|
+
argv.push('-no-boot-anim', '-gpu', 'swiftshader_indirect');
|
|
615
|
+
const reserved = new Set(RESERVED_EMULATOR_FLAGS);
|
|
616
|
+
reserved.add('-no-audio');
|
|
617
|
+
for (const arg of extraArgs) {
|
|
618
|
+
if (reserved.has(arg)) throw new Error(`extra emulator arguments must not override ${arg}`);
|
|
619
|
+
argv.push(quoteRemoteArg(arg));
|
|
620
|
+
}
|
|
621
|
+
argv.push('-port', String(consolePort));
|
|
622
|
+
const command = `${argv.join(' ')} > ${quoteRemoteArg(logPath)} 2>&1 & echo "started:$!"`;
|
|
623
|
+
return { command, consolePort, adbPort: consolePort + 1, logPath, extraArgs };
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/** Build the fixed remote command that kills an emulator started by the plugin. */
|
|
627
|
+
export function buildRemoteEmulatorStopCommand(options = {}) {
|
|
628
|
+
const consolePort = asConsolePort(options.consolePort == null ? 5554 : options.consolePort);
|
|
629
|
+
const serial = `emulator-${consolePort}`;
|
|
630
|
+
// Non-interactive SSH sessions do not inherit the login PATH, so resolve adb
|
|
631
|
+
// from the profile SDK root when it is known instead of relying on `adb`.
|
|
632
|
+
const adbPath = optionalRemotePath(options.adbPath, 'remote adb path') || 'adb';
|
|
633
|
+
return {
|
|
634
|
+
command: `${quoteRemoteArg(adbPath)} -s ${quoteRemoteArg(serial)} emu kill 2>&1 || true`,
|
|
635
|
+
consolePort,
|
|
636
|
+
serial,
|
|
637
|
+
adbPath,
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/** Assemble the local `ssh` argv that runs a single remote command. */
|
|
642
|
+
export function buildSshCommandArgs(options = {}, command) {
|
|
643
|
+
if (!command) throw new Error('buildSshCommandArgs requires a command');
|
|
644
|
+
const sv = new SshAdbTunnel({ ...options, localPort: 15037 });
|
|
645
|
+
const args = [
|
|
646
|
+
'-o',
|
|
647
|
+
'BatchMode=yes',
|
|
648
|
+
'-o',
|
|
649
|
+
'ConnectTimeout=20',
|
|
650
|
+
'-o',
|
|
651
|
+
'ServerAliveInterval=15',
|
|
652
|
+
'-p',
|
|
653
|
+
String(sv.sshPort),
|
|
654
|
+
];
|
|
655
|
+
if (sv.keyPath) args.push('-i', sv.keyPath);
|
|
656
|
+
args.push(`${sv.sshUser}@${sv.sshHost}`, command);
|
|
657
|
+
return args;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* Run one bounded remote command over SSH and return `{ok, code, stdout,
|
|
662
|
+
* stderr}`. Never throws for command failures; `options.exec` can be injected
|
|
663
|
+
* for hermetic tests (shape: `(file, args, {timeoutMs}) => {code,stdout,stderr}`).
|
|
664
|
+
*/
|
|
665
|
+
export async function runSshCommand(options, command, execOptions = {}) {
|
|
666
|
+
const args = buildSshCommandArgs(options, command);
|
|
667
|
+
const timeoutMs = Number.isFinite(execOptions.timeoutMs) ? Math.max(1000, execOptions.timeoutMs) : 30000;
|
|
668
|
+
const maxBytes = 64 * 1024;
|
|
669
|
+
if (typeof execOptions.exec === 'function') {
|
|
670
|
+
const result = await execOptions.exec('ssh', args, { timeoutMs, maxBytes });
|
|
671
|
+
return { ok: !result.error && result.code === 0, code: result.code, stdout: String(result.stdout || ''), stderr: String(result.stderr || ''), error: result.error || null };
|
|
672
|
+
}
|
|
673
|
+
return await new Promise((resolve) => {
|
|
674
|
+
let child;
|
|
675
|
+
try {
|
|
676
|
+
child = spawn('ssh', args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
677
|
+
} catch (error) {
|
|
678
|
+
resolve({ ok: false, code: null, stdout: '', stderr: '', error: error && error.message ? error.message : String(error) });
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
let stdout = '';
|
|
682
|
+
let stderr = '';
|
|
683
|
+
let settled = false;
|
|
684
|
+
const finish = (result) => {
|
|
685
|
+
if (settled) return;
|
|
686
|
+
settled = true;
|
|
687
|
+
clearTimeout(timer);
|
|
688
|
+
resolve(result);
|
|
689
|
+
};
|
|
690
|
+
const timer = setTimeout(() => {
|
|
691
|
+
try { child.kill(); } catch { /* ignore */ }
|
|
692
|
+
finish({ ok: false, code: null, stdout, stderr, error: `remote command timed out after ${timeoutMs}ms` });
|
|
693
|
+
}, timeoutMs);
|
|
694
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
695
|
+
child.stdout.on('data', (chunk) => {
|
|
696
|
+
if (stdout.length < maxBytes) stdout += chunk.toString('utf8').slice(0, maxBytes - stdout.length);
|
|
697
|
+
});
|
|
698
|
+
child.stderr.on('data', (chunk) => {
|
|
699
|
+
if (stderr.length < maxBytes) stderr += chunk.toString('utf8').slice(0, maxBytes - stderr.length);
|
|
700
|
+
});
|
|
701
|
+
child.once('error', (error) => finish({ ok: false, code: null, stdout, stderr, error: error.message }));
|
|
702
|
+
child.once('exit', (code) => finish({ ok: code === 0, code, stdout, stderr, error: null }));
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// ---------------------------------------------------------------------------
|
|
707
|
+
// Multi-session remote VM manager.
|
|
708
|
+
//
|
|
709
|
+
// One manager owns N independent remote sessions (N SSH tunnels + N network adb
|
|
710
|
+
// serials), each backed by a RemoteVmInstance and optionally registered into an
|
|
711
|
+
// InstanceManager so the existing per-instance HTTP routes can serve it.
|
|
712
|
+
//
|
|
713
|
+
// Everything that touches the outside world is injectable for hermetic tests:
|
|
714
|
+
// `tunnelFactory`, `instanceFactory`, `exec` (ssh), `runSsh`, `now`,
|
|
715
|
+
// `findFreePort`, `sleep`. A test can therefore create/inspect/destroy sessions
|
|
716
|
+
// without spawning ssh or an emulator.
|
|
717
|
+
// ---------------------------------------------------------------------------
|
|
718
|
+
|
|
719
|
+
const REMOTE_CONSOLE_PORTS = Object.freeze(Array.from({ length: 65 }, (_, index) => 5554 + index * 2));
|
|
720
|
+
/** Remote command that lists listening TCP ports (Ubuntu: ss, fallback netstat). */
|
|
721
|
+
export const REMOTE_LISTEN_COMMAND = 'ss -ltn 2>/dev/null || netstat -ltn 2>/dev/null || true';
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* Parse listening TCP ports from `ss -ltn` or `netstat -ltn` output.
|
|
725
|
+
* Tolerant by design: any line mentioning LISTEN contributes its `:port`
|
|
726
|
+
* columns, which also covers localized/column-shifted outputs.
|
|
727
|
+
*/
|
|
728
|
+
export function parseRemoteListeningPorts(text) {
|
|
729
|
+
const ports = [];
|
|
730
|
+
const seen = new Set();
|
|
731
|
+
for (const line of String(text == null ? '' : text).split(/\r?\n/)) {
|
|
732
|
+
if (!/\bLISTEN\b/i.test(line)) continue;
|
|
733
|
+
for (const match of line.matchAll(/:(\d{1,5})(?!\d)/g)) {
|
|
734
|
+
const port = Number(match[1]);
|
|
735
|
+
if (port > 0 && port <= 65535 && !seen.has(port)) {
|
|
736
|
+
seen.add(port);
|
|
737
|
+
ports.push(port);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
return ports;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
function sanitizeSessionId(value, fallback = 'remote') {
|
|
745
|
+
const text = String(value || fallback)
|
|
746
|
+
.trim()
|
|
747
|
+
.toLowerCase()
|
|
748
|
+
.replace(/[^a-z0-9._-]+/g, '-')
|
|
749
|
+
.replace(/^-+|-+$/g, '')
|
|
750
|
+
.slice(0, 48);
|
|
751
|
+
const id = text || fallback;
|
|
752
|
+
return id === 'default' ? `remote-${id}` : id;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function asPortOption(value, fallback) {
|
|
756
|
+
const n = Number(value);
|
|
757
|
+
if (!Number.isInteger(n) || n < 1 || n > 65535) return fallback;
|
|
758
|
+
return n;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/**
|
|
762
|
+
* Multi-session remote VM engine. Public API (all routes can call these):
|
|
763
|
+
*
|
|
764
|
+
* const manager = new RemoteSessionManager({ dataDir, instances, scrcpyJarPath, onSessionCreated });
|
|
765
|
+
* await manager.listProfiles(); // {ok, profiles}
|
|
766
|
+
* await manager.saveProfile(profile, {id}); // {} throws on invalid
|
|
767
|
+
* await manager.forgetProfile(id); // {} throws on invalid
|
|
768
|
+
* await manager.createSession({ profile, options }); // summary; throws on failure
|
|
769
|
+
* manager.list(); // [summary]
|
|
770
|
+
* await manager.state(); // {ok, sessions, profiles, ...}
|
|
771
|
+
* await manager.reconnect(id, {relaunch?});
|
|
772
|
+
* await manager.disconnectSession(id, {killRemote});
|
|
773
|
+
* await manager.removeSession(id, {killRemote});
|
|
774
|
+
* manager.getInstance(id); // RemoteVmInstance | null
|
|
775
|
+
* await manager.dispose();
|
|
776
|
+
*
|
|
777
|
+
* `onSessionCreated(instance, record)` (constructor option) or
|
|
778
|
+
* `options.onCreated(instance, record)` (per createSession call) is invoked
|
|
779
|
+
* once the session is registered; use it to add the RemoteVmInstance to an
|
|
780
|
+
* InstanceManager and register its HTTP routes.
|
|
781
|
+
*
|
|
782
|
+
* `createSession` options (runtime only; never persisted in the profile):
|
|
783
|
+
* launch/avdName/consolePort/remotePort/localPort, extraEmulatorArgs,
|
|
784
|
+
* enableAudio, id/name, attachInBackground, saveProfile, profileId,
|
|
785
|
+
* checkRemotePorts, connectTimeoutMs, launchTimeoutMs, portCheckTimeoutMs,
|
|
786
|
+
* connectRetryDelayMs, remoteStopTimeoutMs, scrcpy/adbPath/sdkRoot.
|
|
787
|
+
*/
|
|
788
|
+
export class RemoteSessionManager {
|
|
789
|
+
constructor(options = {}) {
|
|
790
|
+
this.options = options && typeof options === 'object' ? options : {};
|
|
791
|
+
this.dataDir = String(this.options.dataDir || process.cwd());
|
|
792
|
+
this.profileBook = this.options.profiles || new RemoteProfileBook({
|
|
793
|
+
file: this.options.profilesFile || defaultRemoteProfilesPath(this.dataDir),
|
|
794
|
+
});
|
|
795
|
+
this.tunnelFactory = typeof this.options.tunnelFactory === 'function'
|
|
796
|
+
? this.options.tunnelFactory
|
|
797
|
+
: (config) => new SshAdbTunnel(config);
|
|
798
|
+
this.instanceFactory = typeof this.options.instanceFactory === 'function' ? this.options.instanceFactory : null;
|
|
799
|
+
this.exec = typeof this.options.exec === 'function' ? this.options.exec : null;
|
|
800
|
+
this.runSsh = typeof this.options.runSsh === 'function' ? this.options.runSsh : runSshCommand;
|
|
801
|
+
this.now = typeof this.options.now === 'function' ? this.options.now : Date.now;
|
|
802
|
+
this.findFreePort = typeof this.options.findFreePort === 'function' ? this.options.findFreePort : findFreePort;
|
|
803
|
+
this.sleep = typeof this.options.sleep === 'function' ? this.options.sleep : sleep;
|
|
804
|
+
this.logSink = typeof this.options.log === 'function' ? this.options.log : null;
|
|
805
|
+
this.instances = this.options.instances && typeof this.options.instances === 'object' ? this.options.instances : null;
|
|
806
|
+
this.onSession = typeof this.options.onSession === 'function' ? this.options.onSession : null;
|
|
807
|
+
this.onSessionCreated = typeof this.options.onSessionCreated === 'function' ? this.options.onSessionCreated : null;
|
|
808
|
+
this.onDisconnected = typeof this.options.onDisconnected === 'function' ? this.options.onDisconnected : null;
|
|
809
|
+
this.maxSessions = Math.max(1, Math.min(16, Number(this.options.maxSessions) || 8));
|
|
810
|
+
this.consolePorts = Array.isArray(this.options.consolePorts) && this.options.consolePorts.length
|
|
811
|
+
? this.options.consolePorts.map(Number).filter((port) => Number.isInteger(port) && port % 2 === 0 && port >= 5554 && port <= 5682)
|
|
812
|
+
: [...REMOTE_CONSOLE_PORTS];
|
|
813
|
+
this.connectTimeoutMs = Math.max(1000, Number(this.options.connectTimeoutMs) || 180000);
|
|
814
|
+
this.launchTimeoutMs = Math.max(1000, Number(this.options.launchTimeoutMs) || 30000);
|
|
815
|
+
this.portCheckTimeoutMs = Math.max(1000, Number(this.options.portCheckTimeoutMs) || 10000);
|
|
816
|
+
this.remoteStopTimeoutMs = Math.max(1000, Number(this.options.remoteStopTimeoutMs) || 15000);
|
|
817
|
+
this.connectRetryDelayMs = Math.max(10, Number(this.options.connectRetryDelayMs) || 2000);
|
|
818
|
+
this.sessions = new Map();
|
|
819
|
+
this._lock = Promise.resolve();
|
|
820
|
+
this._disposed = false;
|
|
821
|
+
this._RemoteVmInstance = null;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
_log(line) {
|
|
825
|
+
if (this.logSink) this.logSink(line);
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
async _withLock(run) {
|
|
829
|
+
const previous = this._lock;
|
|
830
|
+
let release;
|
|
831
|
+
this._lock = new Promise((resolve) => {
|
|
832
|
+
release = resolve;
|
|
833
|
+
});
|
|
834
|
+
try {
|
|
835
|
+
await previous;
|
|
836
|
+
return await run();
|
|
837
|
+
} finally {
|
|
838
|
+
release();
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
_summarize(record) {
|
|
843
|
+
const tunnelStatus = record.tunnel && typeof record.tunnel.status === 'function' ? record.tunnel.status() : null;
|
|
844
|
+
const vm = record.instance && record.instance.vm ? record.instance.vm : null;
|
|
845
|
+
return {
|
|
846
|
+
ok: true,
|
|
847
|
+
id: record.id,
|
|
848
|
+
kind: 'remote',
|
|
849
|
+
state: record.state,
|
|
850
|
+
error: record.error || null,
|
|
851
|
+
profileId: record.profileId || null,
|
|
852
|
+
name: record.profile.name || null,
|
|
853
|
+
host: record.profile.host,
|
|
854
|
+
user: record.profile.user,
|
|
855
|
+
sshPort: record.profile.sshPort,
|
|
856
|
+
avdName: record.avdName || '',
|
|
857
|
+
serial: record.state === 'disconnected'
|
|
858
|
+
? null
|
|
859
|
+
: (record.serial || (vm && (vm._serialActive || vm.serial)) || (tunnelStatus && tunnelStatus.serial) || null),
|
|
860
|
+
localPort: record.localPort || (tunnelStatus && tunnelStatus.localPort) || 0,
|
|
861
|
+
remotePort: record.remotePort,
|
|
862
|
+
consolePort: record.consolePort || null,
|
|
863
|
+
launch: record.launchInfo ? { ...record.launchInfo } : null,
|
|
864
|
+
tunnel: tunnelStatus ? { ...tunnelStatus } : null,
|
|
865
|
+
vmState: vm ? vm._state || 'stopped' : null,
|
|
866
|
+
instanceId: record.instance ? record.instance.id : null,
|
|
867
|
+
createdAt: record.createdAt,
|
|
868
|
+
disconnectedAt: record.disconnectedAt || null,
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
list() {
|
|
873
|
+
return [...this.sessions.values()].map((record) => this._summarize(record));
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
get(id) {
|
|
877
|
+
const record = this.sessions.get(String(id));
|
|
878
|
+
return record ? this._summarize(record) : null;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
getInstance(id) {
|
|
882
|
+
const record = this.sessions.get(String(id));
|
|
883
|
+
return record ? record.instance : null;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
getSession(id) {
|
|
887
|
+
const record = this.sessions.get(String(id));
|
|
888
|
+
if (!record) return null;
|
|
889
|
+
return { ...this._summarize(record), instance: record.instance, tunnel: record.tunnel, profile: record.profile };
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
async state() {
|
|
893
|
+
const listed = await this.profileBook.list();
|
|
894
|
+
const sessions = this.list();
|
|
895
|
+
return {
|
|
896
|
+
ok: true,
|
|
897
|
+
sessions,
|
|
898
|
+
profiles: Array.isArray(listed.profiles) ? listed.profiles : [],
|
|
899
|
+
profilesFile: listed.file || this.profileBook.file || null,
|
|
900
|
+
profilesError: listed.error || null,
|
|
901
|
+
counts: {
|
|
902
|
+
sessions: sessions.length,
|
|
903
|
+
connected: sessions.filter((session) => session.state === 'connected').length,
|
|
904
|
+
},
|
|
905
|
+
maxSessions: this.maxSessions,
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
async remoteState() {
|
|
910
|
+
return this.state();
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
async listProfiles() {
|
|
914
|
+
return this.profileBook.list();
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
async getProfile(id) {
|
|
918
|
+
return this.profileBook.get(id);
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
async saveProfile(profile, options = {}) {
|
|
922
|
+
const saved = await this.profileBook.save(profile, options);
|
|
923
|
+
if (!saved.ok) throw new Error(saved.error || 'could not save the remote profile');
|
|
924
|
+
return saved;
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
async forgetProfile(id) {
|
|
928
|
+
const removed = await this.profileBook.forget(id);
|
|
929
|
+
if (!removed.ok) throw new Error(removed.error || 'could not forget the remote profile');
|
|
930
|
+
return removed;
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
async _remoteListeningPorts(profile, runtime) {
|
|
934
|
+
if (runtime.checkRemotePorts === false) return { ok: false, ports: [], error: 'remote port check disabled' };
|
|
935
|
+
const result = await this.runSsh(profile, REMOTE_LISTEN_COMMAND, {
|
|
936
|
+
timeoutMs: this.portCheckTimeoutMs,
|
|
937
|
+
exec: this.exec || undefined,
|
|
938
|
+
});
|
|
939
|
+
if (!result || result.ok !== true) {
|
|
940
|
+
return { ok: false, ports: [], error: (result && (result.error || result.stderr)) || 'remote port check failed' };
|
|
941
|
+
}
|
|
942
|
+
return { ok: true, ports: parseRemoteListeningPorts(result.stdout), error: null };
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/** Pick the first even console port not used by a session or listening remotely. */
|
|
946
|
+
async _pickConsolePort(profile, runtime) {
|
|
947
|
+
if (runtime.consolePort != null) return asConsolePort(runtime.consolePort);
|
|
948
|
+
const used = new Set();
|
|
949
|
+
for (const record of this.sessions.values()) {
|
|
950
|
+
const other = record.profile;
|
|
951
|
+
if (!other) continue;
|
|
952
|
+
if (other.host !== profile.host || other.user !== profile.user || other.sshPort !== profile.sshPort) continue;
|
|
953
|
+
if (record.consolePort) {
|
|
954
|
+
used.add(record.consolePort);
|
|
955
|
+
used.add(record.consolePort + 1);
|
|
956
|
+
}
|
|
957
|
+
if (record.remotePort) used.add(record.remotePort);
|
|
958
|
+
}
|
|
959
|
+
const checked = await this._remoteListeningPorts(profile, runtime);
|
|
960
|
+
const listening = new Set(checked.ports);
|
|
961
|
+
for (const candidate of this.consolePorts) {
|
|
962
|
+
if (used.has(candidate) || listening.has(candidate) || listening.has(candidate + 1)) continue;
|
|
963
|
+
return candidate;
|
|
964
|
+
}
|
|
965
|
+
throw new Error(
|
|
966
|
+
`no free remote emulator console port available on ${profile.host} ` +
|
|
967
|
+
`(tried ${this.consolePorts[0]}..${this.consolePorts[this.consolePorts.length - 1]})`,
|
|
968
|
+
);
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
async _findLocalPort() {
|
|
972
|
+
for (let attempt = 0; attempt < 32; attempt += 1) {
|
|
973
|
+
const candidate = await this.findFreePort();
|
|
974
|
+
if (Number.isInteger(candidate) && candidate > 0 && ![...this.sessions.values()].some((record) => record.localPort === candidate)) {
|
|
975
|
+
return candidate;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
throw new Error('could not allocate a free local loopback port for the SSH tunnel');
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
async _allocateLocalPort(profile, runtime) {
|
|
982
|
+
const requested = asPortOption(runtime.localPort, profile.localPort || 0);
|
|
983
|
+
if (requested) {
|
|
984
|
+
const inUseBySession = [...this.sessions.values()].some((record) => record.localPort === requested);
|
|
985
|
+
if (!inUseBySession && await isLocalPortFree(requested)) return requested;
|
|
986
|
+
this._log(`[remote] local port ${requested} is unavailable; allocating a free one`);
|
|
987
|
+
}
|
|
988
|
+
return this._findLocalPort();
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
async _runLaunch(profile, start) {
|
|
992
|
+
const result = await this.runSsh(profile, start.command, {
|
|
993
|
+
timeoutMs: this.launchTimeoutMs,
|
|
994
|
+
exec: this.exec || undefined,
|
|
995
|
+
});
|
|
996
|
+
if (!result || result.ok !== true) {
|
|
997
|
+
const detail = String((result && (result.stderr || result.stdout || result.error)) || 'ssh command failed')
|
|
998
|
+
.trim()
|
|
999
|
+
.slice(0, 500);
|
|
1000
|
+
throw new Error(
|
|
1001
|
+
`could not start the remote emulator on ${profile.host}: ${detail}; see ${start.logPath}`,
|
|
1002
|
+
);
|
|
1003
|
+
}
|
|
1004
|
+
return result;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
_runtimeOptions(input) {
|
|
1008
|
+
const runtime = input && typeof input === 'object' ? input : {};
|
|
1009
|
+
return {
|
|
1010
|
+
...runtime,
|
|
1011
|
+
launch: runtime.launch != null ? runtime.launch === true : null,
|
|
1012
|
+
extraEmulatorArgs: runtime.extraEmulatorArgs,
|
|
1013
|
+
enableAudio: runtime.enableAudio === true,
|
|
1014
|
+
connectTimeoutMs: Math.max(1000, Number(runtime.connectTimeoutMs) || this.connectTimeoutMs),
|
|
1015
|
+
launchTimeoutMs: Math.max(1000, Number(runtime.launchTimeoutMs) || this.launchTimeoutMs),
|
|
1016
|
+
portCheckTimeoutMs: Math.max(1000, Number(runtime.portCheckTimeoutMs) || this.portCheckTimeoutMs),
|
|
1017
|
+
connectRetryDelayMs: Math.max(10, Number(runtime.connectRetryDelayMs) || this.connectRetryDelayMs),
|
|
1018
|
+
remoteStopTimeoutMs: Math.max(1000, Number(runtime.remoteStopTimeoutMs) || this.remoteStopTimeoutMs),
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
_instanceArgs({ id, profile, tunnel, launchInfo, runtime }) {
|
|
1023
|
+
return {
|
|
1024
|
+
id,
|
|
1025
|
+
profile,
|
|
1026
|
+
tunnel,
|
|
1027
|
+
launchInfo,
|
|
1028
|
+
options: {
|
|
1029
|
+
...this.options.instanceOptions,
|
|
1030
|
+
sdkRoot: runtime.sdkRoot || this.options.sdkRoot,
|
|
1031
|
+
adbPath: runtime.adbPath || this.options.adbPath,
|
|
1032
|
+
scrcpyJarPath: runtime.scrcpyJarPath || this.options.scrcpyJarPath,
|
|
1033
|
+
scrcpyMaxSize: runtime.scrcpyMaxSize || this.options.scrcpyMaxSize,
|
|
1034
|
+
scrcpyBitrate: runtime.scrcpyBitrate || this.options.scrcpyBitrate,
|
|
1035
|
+
scrcpyMaxFps: runtime.scrcpyMaxFps || this.options.scrcpyMaxFps,
|
|
1036
|
+
connectTimeoutMs: runtime.connectTimeoutMs,
|
|
1037
|
+
connectRetryDelayMs: runtime.connectRetryDelayMs,
|
|
1038
|
+
remoteStopTimeoutMs: runtime.remoteStopTimeoutMs,
|
|
1039
|
+
exec: runtime.exec || this.exec || undefined,
|
|
1040
|
+
runSsh: this.runSsh,
|
|
1041
|
+
now: this.now,
|
|
1042
|
+
sleep: this.sleep,
|
|
1043
|
+
// Runtime-only media flags: AndroidVm stores them so a reconnect keeps
|
|
1044
|
+
// the camera/mic configuration (they are never persisted in the profile).
|
|
1045
|
+
extraEmulatorArgs: runtime.extraEmulatorArgs,
|
|
1046
|
+
enableAudio: runtime.enableAudio === true,
|
|
1047
|
+
vmOptions: runtime.vmOptions || this.options.vmOptions,
|
|
1048
|
+
},
|
|
1049
|
+
log: (line) => this._log(`[remote:${id}] ${line}`),
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
async _newInstance(args) {
|
|
1054
|
+
if (this.instanceFactory) return await this.instanceFactory(args);
|
|
1055
|
+
if (!this._RemoteVmInstance) {
|
|
1056
|
+
const module = await import('./remote-instance.js');
|
|
1057
|
+
this._RemoteVmInstance = module.RemoteVmInstance;
|
|
1058
|
+
}
|
|
1059
|
+
return new this._RemoteVmInstance(args);
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
_registerInstance(instance) {
|
|
1063
|
+
if (!this.instances || typeof this.instances.addRemoteInstance !== 'function') return;
|
|
1064
|
+
this.instances.addRemoteInstance(instance);
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
_unregisterInstance(id) {
|
|
1068
|
+
if (this.instances && typeof this.instances.removeInstance === 'function') {
|
|
1069
|
+
try {
|
|
1070
|
+
this.instances.removeInstance(id);
|
|
1071
|
+
} catch {
|
|
1072
|
+
/* best effort: a stale entry is removed by InstanceManager.destroy */
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
/**
|
|
1078
|
+
* Create + start one remote session.
|
|
1079
|
+
*
|
|
1080
|
+
* Accepts `{ profile }` (raw/partial profile object) or `{ profile: '<id>' }`
|
|
1081
|
+
* / `{ profileId: '<id>' }` for a saved profile. Throws an actionable error on
|
|
1082
|
+
* failure; nothing stays registered in that case.
|
|
1083
|
+
*/
|
|
1084
|
+
async createSession({ profile: profileInput, profileId: profileIdInput = null, options = {} } = {}) {
|
|
1085
|
+
if (this._disposed) throw new Error('RemoteSessionManager has been disposed');
|
|
1086
|
+
const runtime = this._runtimeOptions(options);
|
|
1087
|
+
let profile;
|
|
1088
|
+
let profileId = profileIdInput ? String(profileIdInput) : null;
|
|
1089
|
+
if (typeof profileInput === 'string') profileId = profileInput;
|
|
1090
|
+
if (profileId && (profileInput == null || typeof profileInput === 'string')) {
|
|
1091
|
+
const found = await this.profileBook.get(profileId);
|
|
1092
|
+
if (!found.ok) throw new Error(found.error || 'could not read the remote profiles file');
|
|
1093
|
+
if (!found.profile) throw new Error(`unknown remote profile: ${profileId}`);
|
|
1094
|
+
profile = normalizeRemoteProfile(found.profile);
|
|
1095
|
+
} else if (profileInput && typeof profileInput === 'object') {
|
|
1096
|
+
profile = normalizeRemoteProfile(profileInput);
|
|
1097
|
+
} else {
|
|
1098
|
+
throw new Error('createSession requires a remote profile object or profileId');
|
|
1099
|
+
}
|
|
1100
|
+
const launch = runtime.launch != null ? runtime.launch : profile.launch === true;
|
|
1101
|
+
if (launch) {
|
|
1102
|
+
const avdName = optionalAvdName(runtime.avdName || profile.avdName);
|
|
1103
|
+
if (!avdName) throw new Error('launch requires a remote AVD name (set the profile avdName)');
|
|
1104
|
+
profile = { ...profile, avdName };
|
|
1105
|
+
}
|
|
1106
|
+
if (this.sessions.size >= this.maxSessions) {
|
|
1107
|
+
throw new Error(`max remote sessions reached (${this.maxSessions}); disconnect one first`);
|
|
1108
|
+
}
|
|
1109
|
+
return this._withLock(async () => {
|
|
1110
|
+
// Re-check inside the lock: concurrent creates must not overbook ports.
|
|
1111
|
+
if (this.sessions.size >= this.maxSessions) {
|
|
1112
|
+
throw new Error(`max remote sessions reached (${this.maxSessions}); disconnect one first`);
|
|
1113
|
+
}
|
|
1114
|
+
let consolePort = 0;
|
|
1115
|
+
let remotePort;
|
|
1116
|
+
if (launch) {
|
|
1117
|
+
consolePort = await this._pickConsolePort(profile, runtime);
|
|
1118
|
+
remotePort = consolePort + 1;
|
|
1119
|
+
} else {
|
|
1120
|
+
consolePort = runtime.consolePort != null
|
|
1121
|
+
? asConsolePort(runtime.consolePort)
|
|
1122
|
+
: profile.consolePort || 0;
|
|
1123
|
+
remotePort = asPortOption(runtime.remotePort, profile.remotePort);
|
|
1124
|
+
if (runtime.remotePort == null && runtime.consolePort != null && remotePort === profile.remotePort) {
|
|
1125
|
+
remotePort = consolePort + 1;
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
const duplicate = [...this.sessions.values()].find((record) => {
|
|
1129
|
+
if (record.state !== 'connected' && record.state !== 'connecting') return false;
|
|
1130
|
+
if (record.profile.host !== profile.host || record.profile.user !== profile.user || record.profile.sshPort !== profile.sshPort) return false;
|
|
1131
|
+
if (launch) return record.avdName === profile.avdName;
|
|
1132
|
+
return record.remotePort === remotePort;
|
|
1133
|
+
});
|
|
1134
|
+
if (duplicate) {
|
|
1135
|
+
throw new Error(
|
|
1136
|
+
`remote ${launch ? `AVD ${profile.avdName}` : `adb port ${remotePort}`} on ${profile.host} ` +
|
|
1137
|
+
`is already used by session ${duplicate.id}`,
|
|
1138
|
+
);
|
|
1139
|
+
}
|
|
1140
|
+
const localPort = await this._allocateLocalPort(profile, runtime);
|
|
1141
|
+
let launchInfo = null;
|
|
1142
|
+
if (launch) {
|
|
1143
|
+
const start = buildRemoteEmulatorStartCommand({
|
|
1144
|
+
avdName: profile.avdName,
|
|
1145
|
+
consolePort,
|
|
1146
|
+
emulatorPath: profile.emulatorPath,
|
|
1147
|
+
sdkRoot: profile.sdkRoot,
|
|
1148
|
+
extraEmulatorArgs: runtime.extraEmulatorArgs,
|
|
1149
|
+
enableAudio: runtime.enableAudio,
|
|
1150
|
+
});
|
|
1151
|
+
await this._runLaunch(profile, start);
|
|
1152
|
+
launchInfo = {
|
|
1153
|
+
consolePort: start.consolePort,
|
|
1154
|
+
adbPort: start.adbPort,
|
|
1155
|
+
logPath: start.logPath,
|
|
1156
|
+
startedAt: this.now(),
|
|
1157
|
+
};
|
|
1158
|
+
}
|
|
1159
|
+
const tunnel = this.tunnelFactory({
|
|
1160
|
+
host: profile.host,
|
|
1161
|
+
user: profile.user,
|
|
1162
|
+
sshPort: profile.sshPort,
|
|
1163
|
+
keyPath: profile.keyPath,
|
|
1164
|
+
sshPath: profile.sshPath,
|
|
1165
|
+
remotePort,
|
|
1166
|
+
localPort,
|
|
1167
|
+
});
|
|
1168
|
+
let started;
|
|
1169
|
+
try {
|
|
1170
|
+
started = await tunnel.start();
|
|
1171
|
+
} catch (error) {
|
|
1172
|
+
try { await tunnel.stop(); } catch { /* best effort */ }
|
|
1173
|
+
this._log(`[remote] tunnel start failed for ${profile.host}: ${error && error.message ? error.message : error}`);
|
|
1174
|
+
throw new Error(`SSH tunnel from ${profile.host} failed: ${error && error.message ? error.message : String(error)}`);
|
|
1175
|
+
}
|
|
1176
|
+
const serial = (started && started.serial) || (tunnel.status ? tunnel.status().serial : null);
|
|
1177
|
+
if (!serial) {
|
|
1178
|
+
try { await tunnel.stop(); } catch { /* best effort */ }
|
|
1179
|
+
throw new Error('SSH tunnel started but did not expose a loopback adb serial');
|
|
1180
|
+
}
|
|
1181
|
+
const baseId = sanitizeSessionId(runtime.id || runtime.name || (profileId ? `remote-${profileId}` : `remote-${profile.avdName || profile.host}-${remotePort}`));
|
|
1182
|
+
let id = baseId;
|
|
1183
|
+
let suffix = 1;
|
|
1184
|
+
while (this.sessions.has(id)) id = `${baseId}-${suffix++}`;
|
|
1185
|
+
let instance;
|
|
1186
|
+
try {
|
|
1187
|
+
instance = await this._newInstance(this._instanceArgs({ id, profile, tunnel, launchInfo, runtime }));
|
|
1188
|
+
if (!instance || typeof instance.start !== 'function') throw new Error('remote instance factory returned an invalid instance');
|
|
1189
|
+
} catch (error) {
|
|
1190
|
+
try { await tunnel.stop(); } catch { /* best effort */ }
|
|
1191
|
+
throw new Error(`could not create the remote VM instance: ${error && error.message ? error.message : String(error)}`);
|
|
1192
|
+
}
|
|
1193
|
+
// HTTP callers should get their session summary back quickly; the
|
|
1194
|
+
// (potentially long) wait for Android boot continues in the background.
|
|
1195
|
+
// Pass `attachInBackground:false` to wait for boot inside createSession.
|
|
1196
|
+
const attachInBackground = runtime.attachInBackground !== false;
|
|
1197
|
+
try {
|
|
1198
|
+
if (attachInBackground) {
|
|
1199
|
+
await instance.start({ wait: false, attachInBackground: true });
|
|
1200
|
+
} else {
|
|
1201
|
+
await instance.start();
|
|
1202
|
+
}
|
|
1203
|
+
} catch (error) {
|
|
1204
|
+
try { if (typeof instance.stop === 'function') await instance.stop(); } catch { /* best effort */ }
|
|
1205
|
+
try { await tunnel.stop(); } catch { /* best effort */ }
|
|
1206
|
+
throw error;
|
|
1207
|
+
}
|
|
1208
|
+
const record = {
|
|
1209
|
+
id,
|
|
1210
|
+
profile,
|
|
1211
|
+
profileId,
|
|
1212
|
+
avdName: profile.avdName,
|
|
1213
|
+
tunnel,
|
|
1214
|
+
instance,
|
|
1215
|
+
launchInfo,
|
|
1216
|
+
consolePort: launchInfo ? consolePort : consolePort || null,
|
|
1217
|
+
remotePort,
|
|
1218
|
+
localPort: Number(tunnel.localPort) || Number(started.localPort) || localPort,
|
|
1219
|
+
serial,
|
|
1220
|
+
state: 'connected',
|
|
1221
|
+
error: null,
|
|
1222
|
+
runtime,
|
|
1223
|
+
createdAt: this.now(),
|
|
1224
|
+
};
|
|
1225
|
+
try {
|
|
1226
|
+
this._registerInstance(instance);
|
|
1227
|
+
} catch (error) {
|
|
1228
|
+
try { if (typeof instance.stop === 'function') await instance.stop(); } catch { /* best effort */ }
|
|
1229
|
+
try { await tunnel.stop(); } catch { /* best effort */ }
|
|
1230
|
+
throw new Error(`could not register the remote instance for routing: ${error && error.message ? error.message : String(error)}`);
|
|
1231
|
+
}
|
|
1232
|
+
this.sessions.set(id, record);
|
|
1233
|
+
this._log(
|
|
1234
|
+
`[remote] session ${id} connected (${profile.user}@${profile.host}, avd=${profile.avdName || '-'}, ` +
|
|
1235
|
+
`serial=${serial}, remote adb=${remotePort}, local=${record.localPort})`,
|
|
1236
|
+
);
|
|
1237
|
+
// Let the caller route the new instance: `onSessionCreated(instance,
|
|
1238
|
+
// record)` from the constructor options or `options.onCreated` per call.
|
|
1239
|
+
const onCreated = typeof runtime.onCreated === 'function' ? runtime.onCreated : this.onSessionCreated;
|
|
1240
|
+
if (onCreated) {
|
|
1241
|
+
try {
|
|
1242
|
+
onCreated(instance, record);
|
|
1243
|
+
} catch {
|
|
1244
|
+
/* observer callbacks are best effort */
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
const summary = this._summarize(record);
|
|
1248
|
+
if (this.onSession) {
|
|
1249
|
+
try {
|
|
1250
|
+
this.onSession(summary);
|
|
1251
|
+
} catch {
|
|
1252
|
+
/* observer callbacks are best effort */
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
return summary;
|
|
1256
|
+
});
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
async reconnect(id, options = {}) {
|
|
1260
|
+
if (this._disposed) throw new Error('RemoteSessionManager has been disposed');
|
|
1261
|
+
const record = this.sessions.get(String(id));
|
|
1262
|
+
if (!record) throw new Error(`unknown remote session: ${id}`);
|
|
1263
|
+
const runtime = this._runtimeOptions(options);
|
|
1264
|
+
return this._withLock(async () => {
|
|
1265
|
+
record.error = null;
|
|
1266
|
+
record.state = 'connecting';
|
|
1267
|
+
try {
|
|
1268
|
+
if (runtime.relaunch === true && record.launchInfo && record.launchInfo.consolePort) {
|
|
1269
|
+
await record.instance.stop({ killRemote: true }).catch(() => {});
|
|
1270
|
+
const start = buildRemoteEmulatorStartCommand({
|
|
1271
|
+
avdName: record.profile.avdName,
|
|
1272
|
+
consolePort: record.launchInfo.consolePort,
|
|
1273
|
+
emulatorPath: record.profile.emulatorPath,
|
|
1274
|
+
sdkRoot: record.profile.sdkRoot,
|
|
1275
|
+
extraEmulatorArgs: record.runtime.extraEmulatorArgs,
|
|
1276
|
+
enableAudio: record.runtime.enableAudio === true,
|
|
1277
|
+
});
|
|
1278
|
+
await this._runLaunch(record.profile, start);
|
|
1279
|
+
}
|
|
1280
|
+
await record.instance.start();
|
|
1281
|
+
record.state = 'connected';
|
|
1282
|
+
record.disconnectedAt = null;
|
|
1283
|
+
record.serial = record.instance.serial || record.serial;
|
|
1284
|
+
record.localPort = Number(record.tunnel.localPort) || record.localPort;
|
|
1285
|
+
} catch (error) {
|
|
1286
|
+
record.state = 'error';
|
|
1287
|
+
record.error = error && error.message ? error.message : String(error);
|
|
1288
|
+
throw error;
|
|
1289
|
+
}
|
|
1290
|
+
return this._summarize(record);
|
|
1291
|
+
});
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
/**
|
|
1295
|
+
* Stop the tunnel + detach the remote device. The session record is kept
|
|
1296
|
+
* (`state:'disconnected'`) unless `remove: true`, so `reconnect(id)` can
|
|
1297
|
+
* reopen it later.
|
|
1298
|
+
*/
|
|
1299
|
+
async disconnectSession(id, { killRemote = false, remove = false } = {}) {
|
|
1300
|
+
const record = this.sessions.get(String(id));
|
|
1301
|
+
if (!record) return { ok: true, id: String(id), kind: 'remote', disconnected: false, removed: false };
|
|
1302
|
+
return this._withLock(async () => {
|
|
1303
|
+
let stop = null;
|
|
1304
|
+
let stopError = null;
|
|
1305
|
+
try {
|
|
1306
|
+
if (typeof record.instance.stop === 'function') stop = await record.instance.stop({ killRemote: killRemote === true });
|
|
1307
|
+
} catch (error) {
|
|
1308
|
+
stopError = error && error.message ? error.message : String(error);
|
|
1309
|
+
record.error = stopError;
|
|
1310
|
+
}
|
|
1311
|
+
record.state = 'disconnected';
|
|
1312
|
+
record.disconnectedAt = this.now();
|
|
1313
|
+
record.serial = null;
|
|
1314
|
+
if (remove) {
|
|
1315
|
+
this.sessions.delete(record.id);
|
|
1316
|
+
this._unregisterInstance(record.id);
|
|
1317
|
+
}
|
|
1318
|
+
const summary = this._summarize(record);
|
|
1319
|
+
if (this.onDisconnected) {
|
|
1320
|
+
try {
|
|
1321
|
+
this.onDisconnected(summary);
|
|
1322
|
+
} catch {
|
|
1323
|
+
/* observer callbacks are best effort */
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
return { ...summary, disconnected: true, removed: remove === true, stop, stopError };
|
|
1327
|
+
});
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
async removeSession(id, { killRemote = false } = {}) {
|
|
1331
|
+
return this.disconnectSession(id, { killRemote, remove: true });
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
async dispose() {
|
|
1335
|
+
if (this._disposed) return;
|
|
1336
|
+
this._disposed = true;
|
|
1337
|
+
for (const record of [...this.sessions.values()]) {
|
|
1338
|
+
try {
|
|
1339
|
+
if (record.instance && typeof record.instance.stop === 'function') await record.instance.stop({ killRemote: false });
|
|
1340
|
+
} catch {
|
|
1341
|
+
/* best effort */
|
|
1342
|
+
}
|
|
1343
|
+
this._unregisterInstance(record.id);
|
|
1344
|
+
}
|
|
1345
|
+
this.sessions.clear();
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
|