-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathsshProcess.test.ts
More file actions
838 lines (701 loc) · 23.9 KB
/
sshProcess.test.ts
File metadata and controls
838 lines (701 loc) · 23.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
import find from "find-process";
import { vol } from "memfs";
import * as fsPromises from "node:fs/promises";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
SshProcessMonitor,
type SshProcessMonitorOptions,
} from "@/remote/sshProcess";
import { createMockLogger, MockStatusBar } from "../../mocks/testHelpers";
import type * as fs from "node:fs";
vi.mock("find-process", () => ({ default: vi.fn() }));
vi.mock("node:fs/promises", async () => {
const memfs: { fs: typeof fs } = await vi.importActual("memfs");
return memfs.fs.promises;
});
describe("SshProcessMonitor", () => {
let activeMonitors: SshProcessMonitor[] = [];
let statusBar: MockStatusBar;
beforeEach(() => {
vi.restoreAllMocks();
vol.reset();
activeMonitors = [];
statusBar = new MockStatusBar();
// Default: process found immediately
vi.mocked(find).mockResolvedValue([
{ pid: 999, ppid: 1, name: "ssh", cmd: "ssh host" },
]);
});
afterEach(() => {
vi.useRealTimers();
for (const m of activeMonitors) {
m.dispose();
}
activeMonitors = [];
vol.reset();
});
describe("process discovery", () => {
it("finds SSH process by port from Remote SSH logs", async () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
});
const monitor = createMonitor({ codeLogDir: "/logs/window1" });
const pid = await waitForEvent(monitor.onPidChange);
expect(find).toHaveBeenCalledWith("port", 12345);
expect(pid).toBe(999);
});
it("retries until process is found", async () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
});
// First 2 calls return nothing, third call finds the process
vi.mocked(find)
.mockResolvedValueOnce([])
.mockResolvedValueOnce([])
.mockResolvedValueOnce([
{ pid: 888, ppid: 1, name: "ssh", cmd: "ssh host" },
]);
const monitor = createMonitor({ codeLogDir: "/logs/window1" });
const pid = await waitForEvent(monitor.onPidChange);
expect(vi.mocked(find).mock.calls.length).toBeGreaterThanOrEqual(3);
expect(pid).toBe(888);
});
it("retries when Remote SSH log appears later", async () => {
// Start with no log file
vol.fromJSON({});
vi.mocked(find).mockResolvedValue([
{ pid: 777, ppid: 1, name: "ssh", cmd: "ssh host" },
]);
const monitor = createMonitor({ codeLogDir: "/logs/window1" });
// Add the log file after a delay
setTimeout(() => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 55555 ->",
});
}, 50);
const pid = await waitForEvent(monitor.onPidChange);
expect(find).toHaveBeenCalledWith("port", 55555);
expect(pid).toBe(777);
});
it("uses newest output_logging_ directory when multiple exist", async () => {
// Reverse alphabetical order means highest number/newest first
vol.fromJSON({
"/logs/output_logging_20240101/1-Remote - SSH.log":
"-> socksPort 11111 ->",
"/logs/output_logging_20240102/1-Remote - SSH.log":
"-> socksPort 22222 ->",
"/logs/output_logging_20240103/1-Remote - SSH.log":
"-> socksPort 33333 ->",
});
// Mock readdir to return directories in unsorted order (simulating Windows fs)
mockReaddirOrder("/logs", [
"output_logging_20240103",
"output_logging_20240101",
"output_logging_20240102",
"window1",
]);
const monitor = createMonitor({ codeLogDir: "/logs/window1" });
await waitForEvent(monitor.onPidChange);
expect(find).toHaveBeenCalledWith("port", 33333);
});
it("sorts output_logging_ directories using localeCompare for consistent ordering", async () => {
// localeCompare differs from default sort() for mixed case
vol.fromJSON({
"/logs/output_logging_a/1-Remote - SSH.log": "-> socksPort 11111 ->",
"/logs/output_logging_Z/1-Remote - SSH.log": "-> socksPort 22222 ->",
});
mockReaddirOrder("/logs", [
"output_logging_a",
"output_logging_Z",
"window1",
]);
const monitor = createMonitor({ codeLogDir: "/logs/window1" });
await waitForEvent(monitor.onPidChange);
// With localeCompare: ["a", "Z"] -> reversed -> "Z" first (port 22222)
// With plain sort(): ["Z", "a"] -> reversed -> "a" first (port 11111)
expect(find).toHaveBeenCalledWith("port", 22222);
});
it("falls back to output_logging_ when extension folder has no SSH log", async () => {
// Extension folder exists but doesn't have Remote SSH log
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/some-other-log.log": "",
"/logs/output_logging_20240101/1-Remote - SSH.log":
"-> socksPort 55555 ->",
});
const monitor = createMonitor({ codeLogDir: "/logs/window1" });
await waitForEvent(monitor.onPidChange);
expect(find).toHaveBeenCalledWith("port", 55555);
});
it("reconnects when network info becomes stale", async () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
"/network/999.json": JSON.stringify({
p2p: true,
latency: 10,
preferred_derp: "",
derp_latency: {},
upload_bytes_sec: 0,
download_bytes_sec: 0,
using_coder_connect: false,
}),
});
// First search finds PID 999, after reconnect finds PID 888
vi.mocked(find)
.mockResolvedValueOnce([{ pid: 999, ppid: 1, name: "ssh", cmd: "ssh" }])
.mockResolvedValue([{ pid: 888, ppid: 1, name: "ssh", cmd: "ssh" }]);
const monitor = createMonitor({
codeLogDir: "/logs/window1",
networkInfoPath: "/network",
networkPollInterval: 10,
});
// Initial PID
const firstPid = await waitForEvent(monitor.onPidChange);
expect(firstPid).toBe(999);
// Network info will become stale after 50ms (5 * networkPollInterval)
// Monitor keeps showing last status, only fires when PID actually changes
const pids: Array<number | undefined> = [];
monitor.onPidChange((pid) => pids.push(pid));
// Wait for reconnection to find new PID
await waitFor(() => pids.includes(888), 200);
// Should NOT fire undefined - we keep showing last status while searching
expect(pids).toContain(888);
});
it("resets backoff when port changes in log file", async () => {
vi.useFakeTimers();
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 11111 ->",
});
vi.mocked(find).mockResolvedValue([]);
const pollInterval = 100;
const logger = createMockLogger();
const monitor = createMonitor({
codeLogDir: "/logs/window1",
discoveryPollIntervalMs: pollInterval,
maxDiscoveryBackoffMs: 10_000,
logger,
});
const pids: Array<number | undefined> = [];
monitor.onPidChange((pid) => pids.push(pid));
// Backoff doubles each iteration: 100, 200, 400, 800, 1600, ...
// Total after 5 iterations = pollInterval * (2^5 - 1) = 3100ms
const fiveIterationsMs = pollInterval * (2 ** 5 - 1);
await vi.advanceTimersByTimeAsync(fiveIterationsMs - 1);
expect(logger.debug).toHaveBeenCalledWith(
"No process found listening on port 11111",
);
// Change port, simulates VS Code reconnection after sleep/wake
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 22222 ->",
});
// Trigger next iteration: detects port change, resets backoff, no pid
await vi.advanceTimersByTimeAsync(1);
expect(logger.debug).toHaveBeenCalledWith(
"SSH port changed in log file: 11111 -> 22222",
);
// Process becomes available
vi.mocked(find).mockResolvedValue([
{ pid: 555, ppid: 1, name: "ssh", cmd: "ssh" },
]);
// With reset backoff, process found within 2 poll intervals.
// Without reset, backoff would be pollInterval * 2^5 = 3200ms.
await vi.advanceTimersByTimeAsync(pollInterval * 2);
expect(pids).toContain(555);
});
it("does not fire event when same process is found after stale check", async () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
"/network/999.json": JSON.stringify({
p2p: true,
latency: 10,
preferred_derp: "",
derp_latency: {},
upload_bytes_sec: 0,
download_bytes_sec: 0,
using_coder_connect: false,
}),
});
// Always returns the same PID
vi.mocked(find).mockResolvedValue([
{ pid: 999, ppid: 1, name: "ssh", cmd: "ssh" },
]);
const monitor = createMonitor({
codeLogDir: "/logs/window1",
networkInfoPath: "/network",
networkPollInterval: 10,
});
// Wait for initial PID
await waitForEvent(monitor.onPidChange);
// Track subsequent events
const pids: Array<number | undefined> = [];
monitor.onPidChange((pid) => pids.push(pid));
// Wait long enough for stale check to trigger and re-find same process
await new Promise((r) => setTimeout(r, 100));
// No events should fire - same process found, no change
expect(pids).toEqual([]);
});
});
describe("log file discovery", () => {
it("finds log file matching PID pattern", async () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
"/proxy-logs/999.log": "",
"/proxy-logs/other.log": "",
});
const monitor = createMonitor({
codeLogDir: "/logs/window1",
proxyLogDir: "/proxy-logs",
});
const logPath = await waitForEvent(monitor.onLogFilePathChange);
expect(logPath).toBe(path.join("/proxy-logs", "999.log"));
expect(monitor.getLogFilePath()).toBe(
path.join("/proxy-logs", "999.log"),
);
});
it("finds log file with prefix pattern", async () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
"/proxy-logs/coder-ssh-999.log": "",
});
const monitor = createMonitor({
codeLogDir: "/logs/window1",
proxyLogDir: "/proxy-logs",
});
const logPath = await waitForEvent(monitor.onLogFilePathChange);
expect(logPath).toBe(path.join("/proxy-logs", "coder-ssh-999.log"));
});
it("returns undefined when no proxyLogDir set", async () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
"/proxy-logs/coder-ssh-999.log": "", // ignored
});
const monitor = createMonitor({
codeLogDir: "/logs/window1",
proxyLogDir: undefined,
});
// Wait for process to be found
await waitForEvent(monitor.onPidChange);
expect(monitor.getLogFilePath()).toBeUndefined();
});
it("checks log files in reverse alphabetical order", async () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
"/proxy-logs/2024-01-01-999.log": "",
"/proxy-logs/2024-01-02-999.log": "",
"/proxy-logs/2024-01-03-999.log": "",
});
// Mock readdir to return files in unsorted order (simulating Windows fs)
mockReaddirOrder("/proxy-logs", [
"2024-01-03-999.log",
"2024-01-01-999.log",
"2024-01-02-999.log",
]);
const monitor = createMonitor({
codeLogDir: "/logs/window1",
proxyLogDir: "/proxy-logs",
});
const logPath = await waitForEvent(monitor.onLogFilePathChange);
expect(logPath).toBe(path.join("/proxy-logs", "2024-01-03-999.log"));
});
it("sorts log files using localeCompare for consistent cross-platform ordering", async () => {
// localeCompare differs from default sort() for mixed case
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
"/proxy-logs/a-999.log": "",
"/proxy-logs/Z-999.log": "",
});
mockReaddirOrder("/proxy-logs", ["a-999.log", "Z-999.log"]);
const monitor = createMonitor({
codeLogDir: "/logs/window1",
proxyLogDir: "/proxy-logs",
});
const logPath = await waitForEvent(monitor.onLogFilePathChange);
// With localeCompare: ["a", "Z"] -> reversed -> "Z" first
// With plain sort(): ["Z", "a"] -> reversed -> "a" first (WRONG)
expect(logPath).toBe(path.join("/proxy-logs", "Z-999.log"));
});
});
describe("network status", () => {
it("shows P2P connection in status bar", async () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
"/network/999.json": JSON.stringify({
p2p: true,
latency: 25.5,
preferred_derp: "NYC",
derp_latency: { NYC: 10 },
upload_bytes_sec: 1024,
download_bytes_sec: 2048,
using_coder_connect: false,
}),
});
createMonitor({
codeLogDir: "/logs/window1",
networkInfoPath: "/network",
});
await waitFor(() => statusBar.text.includes("Direct"));
expect(statusBar.text).toContain("Direct");
expect(statusBar.text).toContain("25.50ms");
expect(statusBar.tooltip).toContain("peer-to-peer");
});
it("shows relay connection with DERP region", async () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
"/network/999.json": JSON.stringify({
p2p: false,
latency: 50,
preferred_derp: "SFO",
derp_latency: { SFO: 20, NYC: 40 },
upload_bytes_sec: 512,
download_bytes_sec: 1024,
using_coder_connect: false,
}),
});
createMonitor({
codeLogDir: "/logs/window1",
networkInfoPath: "/network",
});
await waitFor(() => statusBar.text.includes("SFO"));
expect(statusBar.text).toContain("SFO");
expect(statusBar.tooltip).toContain("relay");
});
it("shows Coder Connect status", async () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
"/network/999.json": JSON.stringify({
p2p: false,
latency: 0,
preferred_derp: "",
derp_latency: {},
upload_bytes_sec: 0,
download_bytes_sec: 0,
using_coder_connect: true,
}),
});
createMonitor({
codeLogDir: "/logs/window1",
networkInfoPath: "/network",
});
await waitFor(() => statusBar.text.includes("Coder Connect"));
expect(statusBar.text).toContain("Coder Connect");
});
});
describe("cleanup old network files", () => {
// Network cleanup: 1 hour threshold
const NETWORK_MAX_AGE_MS = 60 * 60 * 1000;
const setMtimeAgo = (filePath: string, ageMs: number) => {
const mtime = (Date.now() - ageMs) / 1000;
vol.utimesSync(filePath, mtime, mtime);
};
it("deletes old .json files but preserves recent and non-.json files", async () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
"/network/old.json": "{}",
"/network/recent.json": "{}",
"/network/old.log": "{}",
});
setMtimeAgo("/network/old.json", NETWORK_MAX_AGE_MS * 2);
setMtimeAgo("/network/old.log", NETWORK_MAX_AGE_MS * 2);
createMonitor({
codeLogDir: "/logs/window1",
networkInfoPath: "/network",
});
await vi.waitFor(() => {
const files = vol.readdirSync("/network");
expect(files).toHaveLength(2);
expect(files).toContain("old.log");
expect(files).toContain("recent.json");
});
});
it("does not throw when network directory is missing or empty", () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
});
vol.mkdirSync("/empty-network", { recursive: true });
expect(() =>
createMonitor({
codeLogDir: "/logs/window1",
networkInfoPath: "/nonexistent",
}),
).not.toThrow();
expect(() =>
createMonitor({
codeLogDir: "/logs/window1",
networkInfoPath: "/empty-network",
}),
).not.toThrow();
});
});
describe("cleanup proxy log files", () => {
// Proxy log cleanup: 7 day threshold, 20 files max
const LOG_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
const LOG_MAX_FILES = 20;
const setMtimeAgo = (filePath: string, ageMs: number) => {
const mtime = (Date.now() - ageMs) / 1000;
vol.utimesSync(filePath, mtime, mtime);
};
const logFileName = (i: number) =>
`coder-ssh-${i.toString().padStart(2, "0")}.log`;
const setupTest = (total: number, stale: number): string[] => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
});
vol.mkdirSync("/proxy-logs", { recursive: true });
const files = Array.from({ length: total }, (_, i) => logFileName(i + 1));
for (const name of files) {
vol.writeFileSync(`/proxy-logs/${name}`, "");
}
for (let i = 0; i < stale; i++) {
setMtimeAgo(`/proxy-logs/${files[i]}`, LOG_MAX_AGE_MS * 2);
}
return files;
};
interface StaleLogTestCase {
total: number;
stale: number;
expected: number;
desc: string;
}
it.each<StaleLogTestCase>([
{ total: 25, stale: 8, expected: 20, desc: "Deletes until limit" },
{ total: 25, stale: 3, expected: 22, desc: "Only deletes stale" },
{ total: 25, stale: 0, expected: 25, desc: "Keeps recent files" },
{ total: 15, stale: 5, expected: 15, desc: "Keeps under limit" },
])(
"$desc: $total files, $stale stale → $expected remaining",
async ({ total, stale, expected }) => {
setupTest(total, stale);
createMonitor({
codeLogDir: "/logs/window1",
proxyLogDir: "/proxy-logs",
});
await vi.waitFor(() => {
expect(vol.readdirSync("/proxy-logs")).toHaveLength(expected);
});
},
);
it("only matches coder-ssh*.log files", async () => {
const files = setupTest(25, 25);
// Add non-matching files
const nonMatchingFiles = [
"other.log",
"coder-ssh-config.json",
"readme.txt",
];
for (const f of nonMatchingFiles) {
const filePath = `/proxy-logs/${f}`;
vol.writeFileSync(filePath, "");
setMtimeAgo(filePath, LOG_MAX_AGE_MS * 2);
}
createMonitor({
codeLogDir: "/logs/window1",
proxyLogDir: "/proxy-logs",
});
await vi.waitFor(() => {
expect(vol.readdirSync("/proxy-logs")).toHaveLength(
LOG_MAX_FILES + nonMatchingFiles.length,
);
});
const remaining = vol.readdirSync("/proxy-logs") as string[];
// Non-matching files preserved
expect(remaining).toContain("other.log");
expect(remaining).toContain("coder-ssh-config.json");
expect(remaining).toContain("readme.txt");
// Oldest matching files deleted
expect(remaining).not.toContain(files[0]);
expect(remaining).toContain(files[24]);
});
it("does not throw when proxy log directory is missing or empty", () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
});
vol.mkdirSync("/empty-proxy-logs", { recursive: true });
expect(() =>
createMonitor({
codeLogDir: "/logs/window1",
proxyLogDir: "/nonexistent-proxy-logs",
}),
).not.toThrow();
expect(() =>
createMonitor({
codeLogDir: "/logs/window1",
proxyLogDir: "/empty-proxy-logs",
}),
).not.toThrow();
});
});
describe("missing file retry logic", () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
it("searches for new process after consecutive file read failures", async () => {
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
"/network/789.json": "{}",
});
// Set mtime far into the future so 789.json is always considered fresh
const FRESH_MTIME = Date.now() + 1_000_000;
vol.utimesSync(
"/network/789.json",
FRESH_MTIME / 1000,
FRESH_MTIME / 1000,
);
vi.mocked(find)
.mockResolvedValueOnce([{ pid: 123, ppid: 1, name: "ssh", cmd: "ssh" }])
.mockResolvedValueOnce([{ pid: 456, ppid: 1, name: "ssh", cmd: "ssh" }])
.mockResolvedValueOnce([{ pid: 789, ppid: 1, name: "ssh", cmd: "ssh" }])
// This will not be found since `789.json` is found and is not stale!
.mockResolvedValue([{ pid: 999, ppid: 1, name: "ssh", cmd: "ssh" }]);
const pollInterval = 10;
const monitor = createMonitor({
codeLogDir: "/logs/window1",
networkInfoPath: "/network",
networkPollInterval: pollInterval,
});
const pids: Array<number | undefined> = [];
monitor.onPidChange((pid) => pids.push(pid));
// Advance enough time for the monitor to cycle through PIDs 123, 456, and find 789
await vi.advanceTimersByTimeAsync(pollInterval * 100);
expect(pids).toEqual([123, 456, 789]);
});
});
describe("dispose", () => {
it("disposes status bar", () => {
const monitor = createMonitor();
monitor.dispose();
expect(statusBar.dispose).toHaveBeenCalled();
});
it("stops searching for process after dispose", async () => {
// Log file exists so port can be found and find() is called
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
});
// find() always returns empty - monitor will keep retrying
vi.mocked(find).mockResolvedValue([]);
const monitor = createMonitor({ codeLogDir: "/logs/window1" });
// Let a few poll cycles run
await new Promise((r) => setTimeout(r, 30));
const callsBeforeDispose = vi.mocked(find).mock.calls.length;
expect(callsBeforeDispose).toBeGreaterThan(0);
monitor.dispose();
// Wait and verify no new calls
await new Promise((r) => setTimeout(r, 50));
expect(vi.mocked(find).mock.calls.length).toBe(callsBeforeDispose);
});
it("does not fire log file event after dispose", async () => {
// Start with SSH log but no proxy log file
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
});
const monitor = createMonitor({
codeLogDir: "/logs/window1",
proxyLogDir: "/proxy-logs",
});
// Wait for PID - this starts the log file search loop
await waitForEvent(monitor.onPidChange);
const events: string[] = [];
monitor.onLogFilePathChange(() => events.push("logPath"));
monitor.dispose();
// Now add the log file that WOULD have been found
vol.fromJSON({
"/logs/ms-vscode-remote.remote-ssh/1-Remote - SSH.log":
"-> socksPort 12345 ->",
"/proxy-logs/999.log": "",
});
await new Promise((r) => setTimeout(r, 50));
expect(events).toEqual([]);
});
it("is idempotent - can be called multiple times", () => {
const monitor = createMonitor();
monitor.dispose();
monitor.dispose();
monitor.dispose();
// Should not throw, and dispose should only be called once on status bar
expect(statusBar.dispose).toHaveBeenCalledTimes(1);
});
});
function createMonitor(overrides: Partial<SshProcessMonitorOptions> = {}) {
const monitor = SshProcessMonitor.start({
sshHost: "coder-vscode--user--workspace",
networkInfoPath: "/network",
codeLogDir: "/logs/window1",
remoteSshExtensionId: "ms-vscode-remote.remote-ssh",
logger: createMockLogger(),
discoveryPollIntervalMs: 10,
maxDiscoveryBackoffMs: 100,
networkPollInterval: 10,
...overrides,
});
activeMonitors.push(monitor);
return monitor;
}
});
/**
* Helper to mock readdir returning files in a specific unsorted order.
* This is needed because memfs returns files in sorted order, which masks
* bugs in sorting logic.
*/
function mockReaddirOrder(dirPath: string, files: string[]): void {
const originalReaddir = fsPromises.readdir;
const mockImpl = (path: fs.PathLike): Promise<string[]> => {
if (path === dirPath) {
return Promise.resolve(files);
}
return originalReaddir(path);
};
vi.spyOn(fsPromises, "readdir").mockImplementation(
mockImpl as typeof fsPromises.readdir,
);
}
/** Wait for a VS Code event to fire once */
function waitForEvent<T>(
event: (listener: (e: T) => void) => { dispose(): void },
timeout = 1000,
): Promise<T> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
disposable.dispose();
reject(new Error(`waitForEvent timed out after ${timeout}ms`));
}, timeout);
const disposable = event((value) => {
clearTimeout(timer);
disposable.dispose();
resolve(value);
});
});
}
/** Poll for a condition to become true */
async function waitFor(
condition: () => boolean,
timeout = 1000,
interval = 5,
): Promise<void> {
const start = Date.now();
while (!condition()) {
if (Date.now() - start > timeout) {
throw new Error(`waitFor timed out after ${timeout}ms`);
}
await new Promise((r) => setTimeout(r, interval));
}
}