@dxos/phoenix 0.1.58-main.0009f6a

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/LICENSE ADDED
@@ -0,0 +1,8 @@
1
+ MIT License
2
+ Copyright (c) 2023 DXOS
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,294 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // packages/common/phoenix/src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ Phoenix: () => Phoenix,
34
+ WatchDog: () => WatchDog
35
+ });
36
+ module.exports = __toCommonJS(src_exports);
37
+
38
+ // packages/common/phoenix/src/phoenix.ts
39
+ var import_node_child_process = require("node:child_process");
40
+ var import_node_fs2 = require("node:fs");
41
+ var import_node_path = require("node:path");
42
+ var import_pkg_up = __toESM(require("pkg-up"));
43
+ var import_invariant = require("@dxos/invariant");
44
+ var import_log = require("@dxos/log");
45
+
46
+ // packages/common/phoenix/src/utils.ts
47
+ var import_node_fs = require("node:fs");
48
+ var import_async = require("@dxos/async");
49
+
50
+ // packages/common/phoenix/src/defs.ts
51
+ var WATCHDOG_START_TIMEOUT = 1e4;
52
+ var WATCHDOG_STOP_TIMEOUT = 1e3;
53
+ var WATCHDOG_CHECK_INTERVAL = 50;
54
+
55
+ // packages/common/phoenix/src/utils.ts
56
+ var waitForPidDeletion = async (pidFile) => (0, import_async.waitForCondition)({
57
+ condition: () => !(0, import_node_fs.existsSync)(pidFile),
58
+ timeout: WATCHDOG_STOP_TIMEOUT,
59
+ interval: WATCHDOG_CHECK_INTERVAL
60
+ });
61
+ var waitForPidFileBeingFilledWithInfo = async (pidFile) => (0, import_async.waitForCondition)({
62
+ condition: () => (0, import_node_fs.readFileSync)(pidFile, {
63
+ encoding: "utf-8"
64
+ }).includes("pid"),
65
+ timeout: WATCHDOG_START_TIMEOUT,
66
+ interval: WATCHDOG_CHECK_INTERVAL,
67
+ error: new Error("Lock file is not being propagated with info.")
68
+ });
69
+
70
+ // packages/common/phoenix/src/phoenix.ts
71
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/common/phoenix/src/phoenix.ts";
72
+ var Phoenix = class _Phoenix {
73
+ /**
74
+ * Starts detached watchdog process which starts and monitors selected command.
75
+ */
76
+ static async start(params) {
77
+ {
78
+ if ((0, import_node_fs2.existsSync)(params.pidFile)) {
79
+ await _Phoenix.stop(params.pidFile);
80
+ }
81
+ await waitForPidDeletion(params.pidFile);
82
+ }
83
+ {
84
+ [
85
+ params.logFile,
86
+ params.errFile,
87
+ params.pidFile
88
+ ].forEach((filename) => {
89
+ if (!(0, import_node_fs2.existsSync)(filename)) {
90
+ (0, import_node_fs2.mkdirSync)((0, import_node_path.dirname)(filename), {
91
+ recursive: true
92
+ });
93
+ (0, import_node_fs2.writeFileSync)(filename, "", {
94
+ encoding: "utf-8"
95
+ });
96
+ }
97
+ });
98
+ }
99
+ const watchdogPath = (0, import_node_path.join)((0, import_node_path.dirname)(import_pkg_up.default.sync({
100
+ cwd: __dirname
101
+ })), "bin", "watchdog");
102
+ const watchDog = (0, import_node_child_process.fork)(watchdogPath, [
103
+ JSON.stringify(params)
104
+ ], {
105
+ detached: true,
106
+ cwd: __dirname
107
+ });
108
+ watchDog.on("exit", (code, signal) => {
109
+ if (code && code !== 0) {
110
+ import_log.log.error("Monitor died unexpectedly", {
111
+ code,
112
+ signal
113
+ }, {
114
+ F: __dxlog_file,
115
+ L: 52,
116
+ S: this,
117
+ C: (f, a) => f(...a)
118
+ });
119
+ }
120
+ });
121
+ await waitForPidFileBeingFilledWithInfo(params.pidFile);
122
+ watchDog.disconnect();
123
+ watchDog.unref();
124
+ return _Phoenix.info(params.pidFile);
125
+ }
126
+ /**
127
+ * Stops detached watchdog process by PID info written down in PID file.
128
+ */
129
+ static async stop(pidFile, force = false) {
130
+ if (!(0, import_node_fs2.existsSync)(pidFile)) {
131
+ throw new Error("PID file does not exist");
132
+ }
133
+ const fileContent = (0, import_node_fs2.readFileSync)(pidFile, {
134
+ encoding: "utf-8"
135
+ });
136
+ if (!fileContent.includes("pid")) {
137
+ throw new Error("Invalid PID file content");
138
+ }
139
+ const { pid } = JSON.parse(fileContent);
140
+ const signal = force ? "SIGKILL" : "SIGINT";
141
+ try {
142
+ process.kill(pid, signal);
143
+ } catch (err) {
144
+ (0, import_invariant.invariant)(err instanceof Error, "Invalid error type", {
145
+ F: __dxlog_file,
146
+ L: 81,
147
+ S: this,
148
+ A: [
149
+ "err instanceof Error",
150
+ "'Invalid error type'"
151
+ ]
152
+ });
153
+ if (err.message.includes("ESRCH") || err.name.includes("ESRCH")) {
154
+ (0, import_node_fs2.unlinkSync)(pidFile);
155
+ } else {
156
+ throw err;
157
+ }
158
+ }
159
+ }
160
+ static info(pidFile) {
161
+ return JSON.parse((0, import_node_fs2.readFileSync)(pidFile, {
162
+ encoding: "utf-8"
163
+ }));
164
+ }
165
+ };
166
+
167
+ // packages/common/phoenix/src/watchdog.ts
168
+ var import_node_child_process2 = require("node:child_process");
169
+ var import_node_fs3 = require("node:fs");
170
+ var import_async2 = require("@dxos/async");
171
+ var import_invariant2 = require("@dxos/invariant");
172
+ var import_log2 = require("@dxos/log");
173
+ function _ts_decorate(decorators, target, key, desc) {
174
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
175
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
176
+ r = Reflect.decorate(decorators, target, key, desc);
177
+ else
178
+ for (var i = decorators.length - 1; i >= 0; i--)
179
+ if (d = decorators[i])
180
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
181
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
182
+ }
183
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/common/phoenix/src/watchdog.ts";
184
+ var WatchDog = class {
185
+ constructor(_params) {
186
+ this._params = _params;
187
+ this._restarts = 0;
188
+ }
189
+ async start() {
190
+ const { cwd, shell, env, command, args } = {
191
+ cwd: process.cwd(),
192
+ ...this._params
193
+ };
194
+ this._log(`Spawning process \`\`\`${command} ${args?.join(" ")}\`\`\``);
195
+ this._child = (0, import_node_child_process2.spawn)(command, args, {
196
+ cwd,
197
+ shell,
198
+ env,
199
+ stdio: "pipe"
200
+ });
201
+ this._child.stdout.on("data", (data) => {
202
+ this._log(String(data));
203
+ });
204
+ this._child.stderr.on("data", (data) => {
205
+ this._err(data);
206
+ });
207
+ this._child.on("close", async (code, signal) => {
208
+ if (code && code !== 0 && signal !== "SIGINT" && signal !== "SIGKILL") {
209
+ this._err(`Died unexpectedly with exit code ${code} (signal: ${signal}).`);
210
+ await this.restart();
211
+ }
212
+ this._log(`Stopped with exit code ${code} (signal: ${signal}).`);
213
+ if ((0, import_node_fs3.existsSync)(this._params.pidFile)) {
214
+ (0, import_node_fs3.unlinkSync)(this._params.pidFile);
215
+ }
216
+ });
217
+ const childInfo = {
218
+ pid: this._child.pid,
219
+ started: Date.now(),
220
+ restarts: this._restarts,
221
+ ...this._params
222
+ };
223
+ (0, import_node_fs3.writeFileSync)(this._params.pidFile, JSON.stringify(childInfo, void 0, 2), {
224
+ encoding: "utf-8"
225
+ });
226
+ await waitForPidFileBeingFilledWithInfo(this._params.pidFile);
227
+ }
228
+ /**
229
+ * Sends SIGKILL to the child process and the tree it spawned (if `killTree` param is `true`).
230
+ */
231
+ async kill() {
232
+ if (!this._child) {
233
+ return;
234
+ }
235
+ await this._killWithSignal("SIGKILL");
236
+ if ((0, import_node_fs3.existsSync)(this._params.pidFile)) {
237
+ (0, import_node_fs3.unlinkSync)(this._params.pidFile);
238
+ }
239
+ await waitForPidDeletion(this._params.pidFile);
240
+ }
241
+ async restart() {
242
+ await this.kill();
243
+ if (this._params.maxRestarts !== void 0 && this._restarts >= this._params.maxRestarts) {
244
+ this._err("Max restarts number is reached");
245
+ } else {
246
+ (0, import_log2.log)("Restarting...", void 0, {
247
+ F: __dxlog_file2,
248
+ L: 120,
249
+ S: this,
250
+ C: (f, a) => f(...a)
251
+ });
252
+ this._restarts++;
253
+ await this.start();
254
+ }
255
+ }
256
+ async _killWithSignal(signal) {
257
+ (0, import_invariant2.invariant)(this._child?.pid, "Child process has no pid.", {
258
+ F: __dxlog_file2,
259
+ L: 127,
260
+ S: this,
261
+ A: [
262
+ "this._child?.pid",
263
+ "'Child process has no pid.'"
264
+ ]
265
+ });
266
+ this._child.kill(signal);
267
+ this._child = void 0;
268
+ }
269
+ _log(message) {
270
+ (0, import_node_fs3.writeFileSync)(this._params.logFile, message + "\n", {
271
+ flag: "a+",
272
+ encoding: "utf-8"
273
+ });
274
+ }
275
+ _err(message) {
276
+ this._log(message);
277
+ (0, import_node_fs3.writeFileSync)(this._params.errFile, message + "\n", {
278
+ flag: "a+",
279
+ encoding: "utf-8"
280
+ });
281
+ }
282
+ };
283
+ _ts_decorate([
284
+ import_async2.synchronized
285
+ ], WatchDog.prototype, "start", null);
286
+ _ts_decorate([
287
+ import_async2.synchronized
288
+ ], WatchDog.prototype, "kill", null);
289
+ // Annotate the CommonJS export names for ESM import in node:
290
+ 0 && (module.exports = {
291
+ Phoenix,
292
+ WatchDog
293
+ });
294
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/index.ts", "../../../src/phoenix.ts", "../../../src/utils.ts", "../../../src/defs.ts", "../../../src/watchdog.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n// Inspired by https://github.com/foreversd/forever\n// Their copyright notice is included below.\n// Copyright (C) 2010 Charlie Robbins & the Contributors\n//\n\nexport * from './phoenix';\nexport * from './watchdog';\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { fork } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport pkgUp from 'pkg-up';\n\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { waitForPidDeletion, waitForPidFileBeingFilledWithInfo } from './utils';\nimport { ProcessInfo, WatchDogParams } from './watchdog';\n\n/**\n * Utils to start/stop detached process with errors and logs handling.\n */\nexport class Phoenix {\n /**\n * Starts detached watchdog process which starts and monitors selected command.\n */\n static async start(params: WatchDogParams) {\n {\n // Clear stale pid file.\n if (existsSync(params.pidFile)) {\n await Phoenix.stop(params.pidFile);\n }\n\n await waitForPidDeletion(params.pidFile);\n }\n\n {\n // Create log folders.\n [params.logFile, params.errFile, params.pidFile].forEach((filename) => {\n if (!existsSync(filename)) {\n mkdirSync(dirname(filename), { recursive: true });\n writeFileSync(filename, '', { encoding: 'utf-8' });\n }\n });\n }\n\n const watchdogPath = join(dirname(pkgUp.sync({ cwd: __dirname })!), 'bin', 'watchdog');\n\n const watchDog = fork(watchdogPath, [JSON.stringify(params)], {\n detached: true,\n cwd: __dirname,\n });\n\n watchDog.on('exit', (code, signal) => {\n if (code && code !== 0) {\n log.error('Monitor died unexpectedly', { code, signal });\n }\n });\n\n await waitForPidFileBeingFilledWithInfo(params.pidFile);\n\n watchDog.disconnect();\n watchDog.unref();\n\n return Phoenix.info(params.pidFile);\n }\n\n /**\n * Stops detached watchdog process by PID info written down in PID file.\n */\n static async stop(pidFile: string, force = false) {\n if (!existsSync(pidFile)) {\n throw new Error('PID file does not exist');\n }\n const fileContent = readFileSync(pidFile, { encoding: 'utf-8' });\n if (!fileContent.includes('pid')) {\n throw new Error('Invalid PID file content');\n }\n\n const { pid } = JSON.parse(fileContent);\n const signal: NodeJS.Signals = force ? 'SIGKILL' : 'SIGINT';\n try {\n process.kill(pid, signal);\n } catch (err) {\n invariant(err instanceof Error, 'Invalid error type');\n if (err.message.includes('ESRCH') || err.name.includes('ESRCH')) {\n // Process is already dead.\n unlinkSync(pidFile);\n } else {\n throw err;\n }\n }\n }\n\n static info(pidFile: string): ProcessInfo {\n return JSON.parse(readFileSync(pidFile, { encoding: 'utf-8' }));\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { existsSync, readFileSync } from 'node:fs';\n\nimport { waitForCondition } from '@dxos/async';\n\nimport { WATCHDOG_CHECK_INTERVAL, WATCHDOG_START_TIMEOUT, WATCHDOG_STOP_TIMEOUT } from './defs';\n\nexport const waitForPidCreation = async (pidFile: string) =>\n waitForCondition({\n condition: () => existsSync(pidFile),\n timeout: WATCHDOG_START_TIMEOUT,\n interval: WATCHDOG_CHECK_INTERVAL,\n });\n\nexport const waitForPidDeletion = async (pidFile: string) =>\n waitForCondition({\n condition: () => !existsSync(pidFile),\n timeout: WATCHDOG_STOP_TIMEOUT,\n interval: WATCHDOG_CHECK_INTERVAL,\n });\n\nexport const waitForPidFileBeingFilledWithInfo = async (pidFile: string) =>\n waitForCondition({\n condition: () => readFileSync(pidFile, { encoding: 'utf-8' }).includes('pid'),\n timeout: WATCHDOG_START_TIMEOUT,\n interval: WATCHDOG_CHECK_INTERVAL,\n error: new Error('Lock file is not being propagated with info.'),\n });\n", "//\n// Copyright 2023 DXOS.org\n//\n\nexport const LOCK_TIMEOUT = 1_000;\nexport const LOCK_CHECK_INTERVAL = 50;\nexport const WATCHDOG_START_TIMEOUT = 10_000;\nexport const WATCHDOG_STOP_TIMEOUT = 1_000;\nexport const WATCHDOG_CHECK_INTERVAL = 50;\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { ChildProcessWithoutNullStreams, spawn } from 'node:child_process';\nimport { existsSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { FileHandle } from 'node:fs/promises';\n\nimport { synchronized } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { waitForPidDeletion, waitForPidFileBeingFilledWithInfo } from './utils';\n\nexport type ProcessInfo = WatchDogParams & {\n pid?: number;\n started?: number;\n restarts?: number;\n running?: boolean;\n};\n\nexport type WatchDogParams = {\n profile?: string; // Human readable process identifier\n pidFile: string; // Path to PID file\n\n //\n // Log files and associated logging options for this instance\n //\n logFile: string; // Path to log output all logs\n errFile: string; // Path to log output from child stderr\n\n //\n // Basic configuration options\n //\n maxRestarts?: number | undefined; // Sets the maximum number of times a given script should run\n killTree?: boolean | undefined; // Kills the entire child process tree on `exit`\n\n //\n // Command to spawn as well as options and other vars\n // (env, cwd, etc) to pass along\n //\n command: string; // Binary to run (default: 'node')\n args?: string[] | undefined; // Additional arguments to pass to the script,\n\n //\n // More specific options to pass along to `child_process.spawn` which\n // will override anything passed to the `spawnWith` option\n //\n env?: NodeJS.ProcessEnv | undefined;\n cwd?: string | undefined;\n shell?: boolean | undefined;\n};\n\nexport class WatchDog {\n private _lock?: FileHandle;\n private _child?: ChildProcessWithoutNullStreams;\n private _restarts = 0;\n\n constructor(private readonly _params: WatchDogParams) {}\n\n @synchronized\n async start() {\n const { cwd, shell, env, command, args } = { cwd: process.cwd(), ...this._params };\n\n this._log(`Spawning process \\`\\`\\`${command} ${args?.join(' ')}\\`\\`\\``);\n this._child = spawn(command, args, { cwd, shell, env, stdio: 'pipe' });\n\n this._child.stdout.on('data', (data: Uint8Array) => {\n this._log(String(data));\n });\n this._child.stderr.on('data', (data: Uint8Array) => {\n this._err(data);\n });\n this._child.on('close', async (code: number, signal: number | NodeJS.Signals) => {\n if (code && code !== 0 && signal !== 'SIGINT' && signal !== 'SIGKILL') {\n this._err(`Died unexpectedly with exit code ${code} (signal: ${signal}).`);\n await this.restart();\n }\n this._log(`Stopped with exit code ${code} (signal: ${signal}).`);\n if (existsSync(this._params.pidFile)) {\n unlinkSync(this._params.pidFile);\n }\n });\n\n const childInfo: ProcessInfo = {\n pid: this._child.pid,\n started: Date.now(),\n restarts: this._restarts,\n ...this._params,\n };\n\n writeFileSync(this._params.pidFile, JSON.stringify(childInfo, undefined, 2), { encoding: 'utf-8' });\n\n await waitForPidFileBeingFilledWithInfo(this._params.pidFile);\n }\n\n /**\n * Sends SIGKILL to the child process and the tree it spawned (if `killTree` param is `true`).\n */\n @synchronized\n async kill() {\n if (!this._child) {\n return;\n }\n\n await this._killWithSignal('SIGKILL');\n\n if (existsSync(this._params.pidFile)) {\n unlinkSync(this._params.pidFile);\n }\n\n await waitForPidDeletion(this._params.pidFile);\n }\n\n async restart() {\n await this.kill();\n if (this._params.maxRestarts !== undefined && this._restarts >= this._params.maxRestarts) {\n this._err('Max restarts number is reached');\n } else {\n log('Restarting...');\n this._restarts++;\n await this.start();\n }\n }\n\n async _killWithSignal(signal: number | NodeJS.Signals) {\n invariant(this._child?.pid, 'Child process has no pid.');\n this._child.kill(signal);\n this._child = undefined;\n }\n\n private _log(message: string | Uint8Array) {\n writeFileSync(this._params.logFile, message + '\\n', {\n flag: 'a+',\n encoding: 'utf-8',\n });\n }\n\n private _err(message: string | Uint8Array) {\n this._log(message);\n writeFileSync(this._params.errFile, message + '\\n', {\n flag: 'a+',\n encoding: 'utf-8',\n });\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;ACIA,gCAAqB;AACrB,IAAAA,kBAA+E;AAC/E,uBAA8B;AAC9B,oBAAkB;AAElB,uBAA0B;AAC1B,iBAAoB;;;ACNpB,qBAAyC;AAEzC,mBAAiC;;;ACA1B,IAAMC,yBAAyB;AAC/B,IAAMC,wBAAwB;AAC9B,IAAMC,0BAA0B;;;ADShC,IAAMC,qBAAqB,OAAOC,gBACvCC,+BAAiB;EACfC,WAAW,MAAM,KAACC,2BAAWH,OAAAA;EAC7BI,SAASC;EACTC,UAAUC;AACZ,CAAA;AAEK,IAAMC,oCAAoC,OAAOR,gBACtDC,+BAAiB;EACfC,WAAW,UAAMO,6BAAaT,SAAS;IAAEU,UAAU;EAAQ,CAAA,EAAGC,SAAS,KAAA;EACvEP,SAASQ;EACTN,UAAUC;EACVM,OAAO,IAAIC,MAA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AO2B,KAAKjB,MAAAA;AACjB,SAAKV,SAASwB;EAChB;EAEQ1B,KAAKmC,SAA8B;AACzCZ,uCAAc,KAAKhC,QAAQ6C,SAASD,UAAU,MAAM;MAClDE,MAAM;MACNV,UAAU;IACZ,CAAA;EACF;EAEQjB,KAAKyB,SAA8B;AACzC,SAAKnC,KAAKmC,OAAAA;AACVZ,uCAAc,KAAKhC,QAAQ+C,SAASH,UAAU,MAAM;MAClDE,MAAM;MACNV,UAAU;IACZ,CAAA;EACF;AACF;;EArFGY;GAPUlD,SAAAA,WAAAA,SAAAA,IAAAA;;EA8CVkD;GA9CUlD,SAAAA,WAAAA,QAAAA,IAAAA;",
6
+ "names": ["import_node_fs", "WATCHDOG_START_TIMEOUT", "WATCHDOG_STOP_TIMEOUT", "WATCHDOG_CHECK_INTERVAL", "waitForPidDeletion", "pidFile", "waitForCondition", "condition", "existsSync", "timeout", "WATCHDOG_STOP_TIMEOUT", "interval", "WATCHDOG_CHECK_INTERVAL", "waitForPidFileBeingFilledWithInfo", "readFileSync", "encoding", "includes", "WATCHDOG_START_TIMEOUT", "error", "Error", "Phoenix", "start", "params", "existsSync", "pidFile", "stop", "waitForPidDeletion", "logFile", "errFile", "forEach", "filename", "mkdirSync", "dirname", "recursive", "writeFileSync", "encoding", "watchdogPath", "join", "pkgUp", "sync", "cwd", "__dirname", "watchDog", "fork", "JSON", "stringify", "detached", "on", "code", "signal", "log", "error", "waitForPidFileBeingFilledWithInfo", "disconnect", "unref", "info", "force", "Error", "fileContent", "readFileSync", "includes", "pid", "parse", "process", "kill", "err", "invariant", "message", "name", "unlinkSync", "import_node_child_process", "import_node_fs", "import_async", "import_invariant", "import_log", "WatchDog", "constructor", "_params", "_restarts", "start", "cwd", "shell", "env", "command", "args", "process", "_log", "join", "_child", "spawn", "stdio", "stdout", "on", "data", "String", "stderr", "_err", "code", "signal", "restart", "existsSync", "pidFile", "unlinkSync", "childInfo", "pid", "started", "Date", "now", "restarts", "writeFileSync", "JSON", "stringify", "undefined", "encoding", "waitForPidFileBeingFilledWithInfo", "kill", "_killWithSignal", "waitForPidDeletion", "maxRestarts", "log", "invariant", "message", "logFile", "flag", "errFile", "synchronized"]
7
+ }
@@ -0,0 +1 @@
1
+ {"inputs":{"packages/common/phoenix/src/defs.ts":{"bytes":1201,"imports":[],"format":"esm"},"packages/common/phoenix/src/utils.ts":{"bytes":3673,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"packages/common/phoenix/src/defs.ts","kind":"import-statement","original":"./defs"}],"format":"esm"},"packages/common/phoenix/src/phoenix.ts":{"bytes":10474,"imports":[{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"pkg-up","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"packages/common/phoenix/src/utils.ts","kind":"import-statement","original":"./utils"}],"format":"esm"},"packages/common/phoenix/src/watchdog.ts":{"bytes":14340,"imports":[{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"packages/common/phoenix/src/utils.ts","kind":"import-statement","original":"./utils"}],"format":"esm"},"packages/common/phoenix/src/index.ts":{"bytes":987,"imports":[{"path":"packages/common/phoenix/src/phoenix.ts","kind":"import-statement","original":"./phoenix"},{"path":"packages/common/phoenix/src/watchdog.ts","kind":"import-statement","original":"./watchdog"}],"format":"esm"}},"outputs":{"packages/common/phoenix/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":14468},"packages/common/phoenix/dist/lib/node/index.cjs":{"imports":[{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"pkg-up","kind":"require-call","external":true},{"path":"@dxos/invariant","kind":"require-call","external":true},{"path":"@dxos/log","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"@dxos/async","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"@dxos/async","kind":"require-call","external":true},{"path":"@dxos/invariant","kind":"require-call","external":true},{"path":"@dxos/log","kind":"require-call","external":true}],"exports":[],"entryPoint":"packages/common/phoenix/src/index.ts","inputs":{"packages/common/phoenix/src/index.ts":{"bytesInOutput":147},"packages/common/phoenix/src/phoenix.ts":{"bytesInOutput":3063},"packages/common/phoenix/src/utils.ts":{"bytesInOutput":646},"packages/common/phoenix/src/defs.ts":{"bytesInOutput":101},"packages/common/phoenix/src/watchdog.ts":{"bytesInOutput":3933}},"bytes":9727}}}
@@ -0,0 +1,6 @@
1
+ export declare const LOCK_TIMEOUT = 1000;
2
+ export declare const LOCK_CHECK_INTERVAL = 50;
3
+ export declare const WATCHDOG_START_TIMEOUT = 10000;
4
+ export declare const WATCHDOG_STOP_TIMEOUT = 1000;
5
+ export declare const WATCHDOG_CHECK_INTERVAL = 50;
6
+ //# sourceMappingURL=defs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defs.d.ts","sourceRoot":"","sources":["../../../src/defs.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,YAAY,OAAQ,CAAC;AAClC,eAAO,MAAM,mBAAmB,KAAK,CAAC;AACtC,eAAO,MAAM,sBAAsB,QAAS,CAAC;AAC7C,eAAO,MAAM,qBAAqB,OAAQ,CAAC;AAC3C,eAAO,MAAM,uBAAuB,KAAK,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from './phoenix';
2
+ export * from './watchdog';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAQA,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC"}
@@ -0,0 +1,16 @@
1
+ import { ProcessInfo, WatchDogParams } from './watchdog';
2
+ /**
3
+ * Utils to start/stop detached process with errors and logs handling.
4
+ */
5
+ export declare class Phoenix {
6
+ /**
7
+ * Starts detached watchdog process which starts and monitors selected command.
8
+ */
9
+ static start(params: WatchDogParams): Promise<ProcessInfo>;
10
+ /**
11
+ * Stops detached watchdog process by PID info written down in PID file.
12
+ */
13
+ static stop(pidFile: string, force?: boolean): Promise<void>;
14
+ static info(pidFile: string): ProcessInfo;
15
+ }
16
+ //# sourceMappingURL=phoenix.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"phoenix.d.ts","sourceRoot":"","sources":["../../../src/phoenix.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEzD;;GAEG;AACH,qBAAa,OAAO;IAClB;;OAEG;WACU,KAAK,CAAC,MAAM,EAAE,cAAc;IAyCzC;;OAEG;WACU,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,UAAQ;IAwBhD,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW;CAG1C"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=phoenix.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"phoenix.test.d.ts","sourceRoot":"","sources":["../../../src/phoenix.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,4 @@
1
+ export declare const TEST_DIR = "/tmp/dxos/testing/phoenix";
2
+ export declare const neverEndingProcess: () => void;
3
+ export declare const clearFiles: (...filenames: string[]) => void;
4
+ //# sourceMappingURL=testing-utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing-utils.d.ts","sourceRoot":"","sources":["../../../src/testing-utils.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,QAAQ,8BAA8B,CAAC;AAKpD,eAAO,MAAM,kBAAkB,YAG9B,CAAC;AAEF,eAAO,MAAM,UAAU,iBAAkB,MAAM,EAAE,SAMhD,CAAC"}
@@ -0,0 +1,4 @@
1
+ export declare const waitForPidCreation: (pidFile: string) => Promise<boolean>;
2
+ export declare const waitForPidDeletion: (pidFile: string) => Promise<boolean>;
3
+ export declare const waitForPidFileBeingFilledWithInfo: (pidFile: string) => Promise<boolean>;
4
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/utils.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,kBAAkB,YAAmB,MAAM,qBAKpD,CAAC;AAEL,eAAO,MAAM,kBAAkB,YAAmB,MAAM,qBAKpD,CAAC;AAEL,eAAO,MAAM,iCAAiC,YAAmB,MAAM,qBAMnE,CAAC"}
@@ -0,0 +1,37 @@
1
+ /// <reference types="node" />
2
+ export type ProcessInfo = WatchDogParams & {
3
+ pid?: number;
4
+ started?: number;
5
+ restarts?: number;
6
+ running?: boolean;
7
+ };
8
+ export type WatchDogParams = {
9
+ profile?: string;
10
+ pidFile: string;
11
+ logFile: string;
12
+ errFile: string;
13
+ maxRestarts?: number | undefined;
14
+ killTree?: boolean | undefined;
15
+ command: string;
16
+ args?: string[] | undefined;
17
+ env?: NodeJS.ProcessEnv | undefined;
18
+ cwd?: string | undefined;
19
+ shell?: boolean | undefined;
20
+ };
21
+ export declare class WatchDog {
22
+ private readonly _params;
23
+ private _lock?;
24
+ private _child?;
25
+ private _restarts;
26
+ constructor(_params: WatchDogParams);
27
+ start(): Promise<void>;
28
+ /**
29
+ * Sends SIGKILL to the child process and the tree it spawned (if `killTree` param is `true`).
30
+ */
31
+ kill(): Promise<void>;
32
+ restart(): Promise<void>;
33
+ _killWithSignal(signal: number | NodeJS.Signals): Promise<void>;
34
+ private _log;
35
+ private _err;
36
+ }
37
+ //# sourceMappingURL=watchdog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version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"file":"watchdog.test.d.ts","sourceRoot":"","sources":["../../../src/watchdog.test.ts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@dxos/phoenix",
3
+ "version": "0.1.58-main.0009f6a",
4
+ "description": "Basic node daemon.",
5
+ "homepage": "https://dxos.org",
6
+ "bugs": "https://github.com/dxos/dxos/issues",
7
+ "license": "MIT",
8
+ "author": "DXOS.org",
9
+ "main": "dist/lib/node/index.cjs",
10
+ "types": "dist/types/src/index.d.ts",
11
+ "files": [
12
+ "dist",
13
+ "src"
14
+ ],
15
+ "dependencies": {
16
+ "pkg-up": "^3.1.0",
17
+ "@dxos/async": "0.1.58-main.0009f6a",
18
+ "@dxos/context": "0.1.58-main.0009f6a",
19
+ "@dxos/invariant": "0.1.58-main.0009f6a",
20
+ "@dxos/keys": "0.1.58-main.0009f6a",
21
+ "@dxos/lock-file": "0.1.58-main.0009f6a",
22
+ "@dxos/log": "0.1.58-main.0009f6a",
23
+ "@dxos/node-std": "0.1.58-main.0009f6a",
24
+ "@dxos/util": "0.1.58-main.0009f6a"
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "^18.11.9",
28
+ "@types/ps-tree": "^1.1.2"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ }
33
+ }
package/src/defs.ts ADDED
@@ -0,0 +1,9 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ export const LOCK_TIMEOUT = 1_000;
6
+ export const LOCK_CHECK_INTERVAL = 50;
7
+ export const WATCHDOG_START_TIMEOUT = 10_000;
8
+ export const WATCHDOG_STOP_TIMEOUT = 1_000;
9
+ export const WATCHDOG_CHECK_INTERVAL = 50;
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+ // Inspired by https://github.com/foreversd/forever
5
+ // Their copyright notice is included below.
6
+ // Copyright (C) 2010 Charlie Robbins & the Contributors
7
+ //
8
+
9
+ export * from './phoenix';
10
+ export * from './watchdog';
@@ -0,0 +1,70 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { expect } from 'chai';
6
+ import { spawn } from 'node:child_process';
7
+ import { existsSync, readFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import waitForExpect from 'wait-for-expect';
10
+
11
+ import { Trigger } from '@dxos/async';
12
+ import { afterTest, describe, test } from '@dxos/test';
13
+
14
+ import { Phoenix } from './phoenix';
15
+ import { TEST_DIR, clearFiles, neverEndingProcess } from './testing-utils';
16
+
17
+ describe('DaemonManager', () => {
18
+ test('kill process by pid', async () => {
19
+ const child = spawn('node', ['-e', `(${neverEndingProcess.toString()})()`]);
20
+ const trigger = new Trigger();
21
+ child.on('exit', () => {
22
+ trigger.wake();
23
+ });
24
+
25
+ process.kill(child.pid!, 'SIGKILL');
26
+
27
+ await trigger.wait({ timeout: 1_000 });
28
+ });
29
+
30
+ // Fails on CI
31
+ test('start/stop detached watchdog', async () => {
32
+ const runId = Math.random().toString();
33
+ const pidFile = join(TEST_DIR, `pid-${runId}.pid`);
34
+ const logFile = join(TEST_DIR, `file-${runId}.log`);
35
+ const errFile = join(TEST_DIR, `err-${runId}.log`);
36
+ afterTest(() => clearFiles(pidFile, logFile, errFile));
37
+
38
+ // Start
39
+ {
40
+ const params = await Phoenix.start({
41
+ profile: runId,
42
+ command: 'node',
43
+ args: ['-e', `(${neverEndingProcess.toString()})()`],
44
+ maxRestarts: 0,
45
+ pidFile,
46
+ logFile,
47
+ errFile,
48
+ });
49
+
50
+ await waitForExpect(() => {
51
+ expect(existsSync(params.logFile)).to.be.true;
52
+ const logs = readFileSync(params.logFile, { encoding: 'utf-8' });
53
+ expect(logs).to.contain('neverEndingProcess started');
54
+ }, 1000);
55
+ }
56
+
57
+ // Stop
58
+ {
59
+ const info = Phoenix.info(pidFile);
60
+ expect(info.profile).to.equal(runId);
61
+
62
+ await Phoenix.stop(pidFile);
63
+
64
+ await waitForExpect(() => {
65
+ const logs = readFileSync(logFile, { encoding: 'utf-8' });
66
+ expect(logs).to.contain('Stopped with exit code');
67
+ }, 1000);
68
+ }
69
+ });
70
+ });
package/src/phoenix.ts ADDED
@@ -0,0 +1,94 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { fork } from 'node:child_process';
6
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
+ import pkgUp from 'pkg-up';
9
+
10
+ import { invariant } from '@dxos/invariant';
11
+ import { log } from '@dxos/log';
12
+
13
+ import { waitForPidDeletion, waitForPidFileBeingFilledWithInfo } from './utils';
14
+ import { ProcessInfo, WatchDogParams } from './watchdog';
15
+
16
+ /**
17
+ * Utils to start/stop detached process with errors and logs handling.
18
+ */
19
+ export class Phoenix {
20
+ /**
21
+ * Starts detached watchdog process which starts and monitors selected command.
22
+ */
23
+ static async start(params: WatchDogParams) {
24
+ {
25
+ // Clear stale pid file.
26
+ if (existsSync(params.pidFile)) {
27
+ await Phoenix.stop(params.pidFile);
28
+ }
29
+
30
+ await waitForPidDeletion(params.pidFile);
31
+ }
32
+
33
+ {
34
+ // Create log folders.
35
+ [params.logFile, params.errFile, params.pidFile].forEach((filename) => {
36
+ if (!existsSync(filename)) {
37
+ mkdirSync(dirname(filename), { recursive: true });
38
+ writeFileSync(filename, '', { encoding: 'utf-8' });
39
+ }
40
+ });
41
+ }
42
+
43
+ const watchdogPath = join(dirname(pkgUp.sync({ cwd: __dirname })!), 'bin', 'watchdog');
44
+
45
+ const watchDog = fork(watchdogPath, [JSON.stringify(params)], {
46
+ detached: true,
47
+ cwd: __dirname,
48
+ });
49
+
50
+ watchDog.on('exit', (code, signal) => {
51
+ if (code && code !== 0) {
52
+ log.error('Monitor died unexpectedly', { code, signal });
53
+ }
54
+ });
55
+
56
+ await waitForPidFileBeingFilledWithInfo(params.pidFile);
57
+
58
+ watchDog.disconnect();
59
+ watchDog.unref();
60
+
61
+ return Phoenix.info(params.pidFile);
62
+ }
63
+
64
+ /**
65
+ * Stops detached watchdog process by PID info written down in PID file.
66
+ */
67
+ static async stop(pidFile: string, force = false) {
68
+ if (!existsSync(pidFile)) {
69
+ throw new Error('PID file does not exist');
70
+ }
71
+ const fileContent = readFileSync(pidFile, { encoding: 'utf-8' });
72
+ if (!fileContent.includes('pid')) {
73
+ throw new Error('Invalid PID file content');
74
+ }
75
+
76
+ const { pid } = JSON.parse(fileContent);
77
+ const signal: NodeJS.Signals = force ? 'SIGKILL' : 'SIGINT';
78
+ try {
79
+ process.kill(pid, signal);
80
+ } catch (err) {
81
+ invariant(err instanceof Error, 'Invalid error type');
82
+ if (err.message.includes('ESRCH') || err.name.includes('ESRCH')) {
83
+ // Process is already dead.
84
+ unlinkSync(pidFile);
85
+ } else {
86
+ throw err;
87
+ }
88
+ }
89
+ }
90
+
91
+ static info(pidFile: string): ProcessInfo {
92
+ return JSON.parse(readFileSync(pidFile, { encoding: 'utf-8' }));
93
+ }
94
+ }
@@ -0,0 +1,23 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { existsSync, mkdirSync, unlinkSync } from 'node:fs';
6
+
7
+ export const TEST_DIR = '/tmp/dxos/testing/phoenix';
8
+ if (!existsSync(TEST_DIR)) {
9
+ mkdirSync(TEST_DIR, { recursive: true });
10
+ }
11
+
12
+ export const neverEndingProcess = () => {
13
+ console.log('neverEndingProcess started');
14
+ setTimeout(() => {}, 1_000_000);
15
+ };
16
+
17
+ export const clearFiles = (...filenames: string[]) => {
18
+ filenames.forEach((filename) => {
19
+ if (existsSync(filename)) {
20
+ unlinkSync(filename);
21
+ }
22
+ });
23
+ };
package/src/utils.ts ADDED
@@ -0,0 +1,31 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { existsSync, readFileSync } from 'node:fs';
6
+
7
+ import { waitForCondition } from '@dxos/async';
8
+
9
+ import { WATCHDOG_CHECK_INTERVAL, WATCHDOG_START_TIMEOUT, WATCHDOG_STOP_TIMEOUT } from './defs';
10
+
11
+ export const waitForPidCreation = async (pidFile: string) =>
12
+ waitForCondition({
13
+ condition: () => existsSync(pidFile),
14
+ timeout: WATCHDOG_START_TIMEOUT,
15
+ interval: WATCHDOG_CHECK_INTERVAL,
16
+ });
17
+
18
+ export const waitForPidDeletion = async (pidFile: string) =>
19
+ waitForCondition({
20
+ condition: () => !existsSync(pidFile),
21
+ timeout: WATCHDOG_STOP_TIMEOUT,
22
+ interval: WATCHDOG_CHECK_INTERVAL,
23
+ });
24
+
25
+ export const waitForPidFileBeingFilledWithInfo = async (pidFile: string) =>
26
+ waitForCondition({
27
+ condition: () => readFileSync(pidFile, { encoding: 'utf-8' }).includes('pid'),
28
+ timeout: WATCHDOG_START_TIMEOUT,
29
+ interval: WATCHDOG_CHECK_INTERVAL,
30
+ error: new Error('Lock file is not being propagated with info.'),
31
+ });
@@ -0,0 +1,38 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { expect } from 'chai';
6
+ import { existsSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+
9
+ import { afterTest, describe, test } from '@dxos/test';
10
+
11
+ import { TEST_DIR, clearFiles, neverEndingProcess } from './testing-utils';
12
+ import { WatchDog } from './watchdog';
13
+
14
+ describe('WatchDog', () => {
15
+ test('Start/stop process', async () => {
16
+ const runId = Math.random();
17
+ const pidFile = join(TEST_DIR, `pid-${runId}.pid`);
18
+ const logFile = join(TEST_DIR, `file-${runId}.log`);
19
+ const errFile = join(TEST_DIR, `err-${runId}.log`);
20
+ afterTest(() => clearFiles(pidFile, logFile, errFile));
21
+
22
+ const watchDog = new WatchDog({
23
+ command: 'node',
24
+ args: ['-e', `(${neverEndingProcess.toString()})()`],
25
+ pidFile,
26
+ logFile,
27
+ errFile,
28
+ });
29
+
30
+ expect(existsSync(pidFile)).to.be.false;
31
+ await watchDog.start();
32
+
33
+ expect(existsSync(pidFile)).to.be.true;
34
+
35
+ await watchDog.kill();
36
+ expect(existsSync(pidFile)).to.be.false;
37
+ });
38
+ });
@@ -0,0 +1,146 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { ChildProcessWithoutNullStreams, spawn } from 'node:child_process';
6
+ import { existsSync, unlinkSync, writeFileSync } from 'node:fs';
7
+ import { FileHandle } from 'node:fs/promises';
8
+
9
+ import { synchronized } from '@dxos/async';
10
+ import { invariant } from '@dxos/invariant';
11
+ import { log } from '@dxos/log';
12
+
13
+ import { waitForPidDeletion, waitForPidFileBeingFilledWithInfo } from './utils';
14
+
15
+ export type ProcessInfo = WatchDogParams & {
16
+ pid?: number;
17
+ started?: number;
18
+ restarts?: number;
19
+ running?: boolean;
20
+ };
21
+
22
+ export type WatchDogParams = {
23
+ profile?: string; // Human readable process identifier
24
+ pidFile: string; // Path to PID file
25
+
26
+ //
27
+ // Log files and associated logging options for this instance
28
+ //
29
+ logFile: string; // Path to log output all logs
30
+ errFile: string; // Path to log output from child stderr
31
+
32
+ //
33
+ // Basic configuration options
34
+ //
35
+ maxRestarts?: number | undefined; // Sets the maximum number of times a given script should run
36
+ killTree?: boolean | undefined; // Kills the entire child process tree on `exit`
37
+
38
+ //
39
+ // Command to spawn as well as options and other vars
40
+ // (env, cwd, etc) to pass along
41
+ //
42
+ command: string; // Binary to run (default: 'node')
43
+ args?: string[] | undefined; // Additional arguments to pass to the script,
44
+
45
+ //
46
+ // More specific options to pass along to `child_process.spawn` which
47
+ // will override anything passed to the `spawnWith` option
48
+ //
49
+ env?: NodeJS.ProcessEnv | undefined;
50
+ cwd?: string | undefined;
51
+ shell?: boolean | undefined;
52
+ };
53
+
54
+ export class WatchDog {
55
+ private _lock?: FileHandle;
56
+ private _child?: ChildProcessWithoutNullStreams;
57
+ private _restarts = 0;
58
+
59
+ constructor(private readonly _params: WatchDogParams) {}
60
+
61
+ @synchronized
62
+ async start() {
63
+ const { cwd, shell, env, command, args } = { cwd: process.cwd(), ...this._params };
64
+
65
+ this._log(`Spawning process \`\`\`${command} ${args?.join(' ')}\`\`\``);
66
+ this._child = spawn(command, args, { cwd, shell, env, stdio: 'pipe' });
67
+
68
+ this._child.stdout.on('data', (data: Uint8Array) => {
69
+ this._log(String(data));
70
+ });
71
+ this._child.stderr.on('data', (data: Uint8Array) => {
72
+ this._err(data);
73
+ });
74
+ this._child.on('close', async (code: number, signal: number | NodeJS.Signals) => {
75
+ if (code && code !== 0 && signal !== 'SIGINT' && signal !== 'SIGKILL') {
76
+ this._err(`Died unexpectedly with exit code ${code} (signal: ${signal}).`);
77
+ await this.restart();
78
+ }
79
+ this._log(`Stopped with exit code ${code} (signal: ${signal}).`);
80
+ if (existsSync(this._params.pidFile)) {
81
+ unlinkSync(this._params.pidFile);
82
+ }
83
+ });
84
+
85
+ const childInfo: ProcessInfo = {
86
+ pid: this._child.pid,
87
+ started: Date.now(),
88
+ restarts: this._restarts,
89
+ ...this._params,
90
+ };
91
+
92
+ writeFileSync(this._params.pidFile, JSON.stringify(childInfo, undefined, 2), { encoding: 'utf-8' });
93
+
94
+ await waitForPidFileBeingFilledWithInfo(this._params.pidFile);
95
+ }
96
+
97
+ /**
98
+ * Sends SIGKILL to the child process and the tree it spawned (if `killTree` param is `true`).
99
+ */
100
+ @synchronized
101
+ async kill() {
102
+ if (!this._child) {
103
+ return;
104
+ }
105
+
106
+ await this._killWithSignal('SIGKILL');
107
+
108
+ if (existsSync(this._params.pidFile)) {
109
+ unlinkSync(this._params.pidFile);
110
+ }
111
+
112
+ await waitForPidDeletion(this._params.pidFile);
113
+ }
114
+
115
+ async restart() {
116
+ await this.kill();
117
+ if (this._params.maxRestarts !== undefined && this._restarts >= this._params.maxRestarts) {
118
+ this._err('Max restarts number is reached');
119
+ } else {
120
+ log('Restarting...');
121
+ this._restarts++;
122
+ await this.start();
123
+ }
124
+ }
125
+
126
+ async _killWithSignal(signal: number | NodeJS.Signals) {
127
+ invariant(this._child?.pid, 'Child process has no pid.');
128
+ this._child.kill(signal);
129
+ this._child = undefined;
130
+ }
131
+
132
+ private _log(message: string | Uint8Array) {
133
+ writeFileSync(this._params.logFile, message + '\n', {
134
+ flag: 'a+',
135
+ encoding: 'utf-8',
136
+ });
137
+ }
138
+
139
+ private _err(message: string | Uint8Array) {
140
+ this._log(message);
141
+ writeFileSync(this._params.errFile, message + '\n', {
142
+ flag: 'a+',
143
+ encoding: 'utf-8',
144
+ });
145
+ }
146
+ }