-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathWatchdogClient.ts
More file actions
85 lines (76 loc) · 2.22 KB
/
WatchdogClient.ts
File metadata and controls
85 lines (76 loc) · 2.22 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
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {spawn, type ChildProcess} from 'node:child_process';
import {fileURLToPath} from 'node:url';
import {logger} from '../logger.js';
import type {WatchdogMessage, OsType} from './types.js';
export class WatchdogClient {
#childProcess: ChildProcess;
constructor(
config: {
parentPid: number;
appVersion: string;
osType: OsType;
logFile?: string;
clearcutEndpoint?: string;
clearcutForceFlushIntervalMs?: number;
clearcutIncludePidHeader?: boolean;
},
options?: {spawn?: typeof spawn},
) {
const watchdogPath = fileURLToPath(
new URL('./watchdog/main.js', import.meta.url),
);
const args = [
watchdogPath,
`--parent-pid=${config.parentPid}`,
`--app-version=${config.appVersion}`,
`--os-type=${config.osType}`,
];
if (config.logFile) {
args.push(`--log-file=${config.logFile}`);
}
if (config.clearcutEndpoint) {
args.push(`--clearcut-endpoint=${config.clearcutEndpoint}`);
}
if (config.clearcutForceFlushIntervalMs) {
args.push(
`--clearcut-force-flush-interval-ms=${config.clearcutForceFlushIntervalMs}`,
);
}
if (config.clearcutIncludePidHeader) {
args.push('--clearcut-include-pid-header');
}
const spawner = options?.spawn ?? spawn;
this.#childProcess = spawner(process.execPath, args, {
stdio: ['pipe', 'ignore', 'ignore'],
detached: true,
});
this.#childProcess.unref();
this.#childProcess.on('error', err => {
logger('Watchdog process error:', err);
});
this.#childProcess.on('exit', (code, signal) => {
logger(`Watchdog exited with code ${code} and signal ${signal}`);
});
}
send(message: WatchdogMessage): void {
if (
this.#childProcess.stdin &&
!this.#childProcess.stdin.destroyed &&
this.#childProcess.pid
) {
try {
const line = JSON.stringify(message) + '\n';
this.#childProcess.stdin.write(line);
} catch (err) {
logger('Failed to write to watchdog stdin', err);
}
} else {
logger('Watchdog stdin not available, dropping message');
}
}
}