@milaboratories/pl-deployments 2.4.7 → 2.4.9

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.
Files changed (98) hide show
  1. package/dist/common/os_and_arch.cjs +39 -0
  2. package/dist/common/os_and_arch.cjs.map +1 -0
  3. package/dist/common/os_and_arch.d.ts +0 -1
  4. package/dist/common/os_and_arch.js +34 -0
  5. package/dist/common/os_and_arch.js.map +1 -0
  6. package/dist/common/pl_binary.cjs +34 -0
  7. package/dist/common/pl_binary.cjs.map +1 -0
  8. package/dist/common/pl_binary.d.ts +0 -1
  9. package/dist/common/pl_binary.js +30 -0
  10. package/dist/common/pl_binary.js.map +1 -0
  11. package/dist/common/pl_binary_download.cjs +172 -0
  12. package/dist/common/pl_binary_download.cjs.map +1 -0
  13. package/dist/common/pl_binary_download.d.ts +0 -1
  14. package/dist/common/pl_binary_download.js +148 -0
  15. package/dist/common/pl_binary_download.js.map +1 -0
  16. package/dist/common/pl_version.cjs +11 -0
  17. package/dist/common/pl_version.cjs.map +1 -0
  18. package/dist/common/pl_version.d.ts +0 -1
  19. package/dist/common/pl_version.js +9 -0
  20. package/dist/common/pl_version.js.map +1 -0
  21. package/dist/index.cjs +26 -0
  22. package/dist/index.cjs.map +1 -0
  23. package/dist/index.d.ts +0 -1
  24. package/dist/index.js +5 -64
  25. package/dist/index.js.map +1 -1
  26. package/dist/local/options.d.ts +0 -1
  27. package/dist/local/pid.cjs +24 -0
  28. package/dist/local/pid.cjs.map +1 -0
  29. package/dist/local/pid.d.ts +0 -1
  30. package/dist/local/pid.js +20 -0
  31. package/dist/local/pid.js.map +1 -0
  32. package/dist/local/pl.cjs +223 -0
  33. package/dist/local/pl.cjs.map +1 -0
  34. package/dist/local/pl.d.ts +0 -1
  35. package/dist/local/pl.js +198 -0
  36. package/dist/local/pl.js.map +1 -0
  37. package/dist/local/process.cjs +77 -0
  38. package/dist/local/process.cjs.map +1 -0
  39. package/dist/local/process.d.ts +1 -2
  40. package/dist/local/process.js +72 -0
  41. package/dist/local/process.js.map +1 -0
  42. package/dist/local/trace.cjs +27 -0
  43. package/dist/local/trace.cjs.map +1 -0
  44. package/dist/local/trace.d.ts +0 -1
  45. package/dist/local/trace.js +23 -0
  46. package/dist/local/trace.js.map +1 -0
  47. package/dist/package.json.cjs +7 -0
  48. package/dist/package.json.cjs.map +1 -0
  49. package/dist/package.json.js +5 -0
  50. package/dist/package.json.js.map +1 -0
  51. package/dist/ssh/__tests__/common-utils.d.ts +0 -1
  52. package/dist/ssh/connection_info.cjs +62 -0
  53. package/dist/ssh/connection_info.cjs.map +1 -0
  54. package/dist/ssh/connection_info.d.ts +0 -1
  55. package/dist/ssh/connection_info.js +55 -0
  56. package/dist/ssh/connection_info.js.map +1 -0
  57. package/dist/ssh/pl.cjs +500 -0
  58. package/dist/ssh/pl.cjs.map +1 -0
  59. package/dist/ssh/pl.d.ts +0 -1
  60. package/dist/ssh/pl.js +497 -0
  61. package/dist/ssh/pl.js.map +1 -0
  62. package/dist/ssh/pl_paths.cjs +67 -0
  63. package/dist/ssh/pl_paths.cjs.map +1 -0
  64. package/dist/ssh/pl_paths.d.ts +0 -1
  65. package/dist/ssh/pl_paths.js +50 -0
  66. package/dist/ssh/pl_paths.js.map +1 -0
  67. package/dist/ssh/ssh.cjs +621 -0
  68. package/dist/ssh/ssh.cjs.map +1 -0
  69. package/dist/ssh/ssh.d.ts +0 -1
  70. package/dist/ssh/ssh.js +619 -0
  71. package/dist/ssh/ssh.js.map +1 -0
  72. package/dist/ssh/supervisord.cjs +149 -0
  73. package/dist/ssh/supervisord.cjs.map +1 -0
  74. package/dist/ssh/supervisord.d.ts +0 -1
  75. package/dist/ssh/supervisord.js +140 -0
  76. package/dist/ssh/supervisord.js.map +1 -0
  77. package/package.json +16 -14
  78. package/src/common/pl_version.ts +3 -2
  79. package/src/local/pl.ts +6 -1
  80. package/src/local/process.ts +40 -3
  81. package/dist/common/os_and_arch.d.ts.map +0 -1
  82. package/dist/common/pl_binary.d.ts.map +0 -1
  83. package/dist/common/pl_binary_download.d.ts.map +0 -1
  84. package/dist/common/pl_version.d.ts.map +0 -1
  85. package/dist/index.d.ts.map +0 -1
  86. package/dist/index.mjs +0 -1366
  87. package/dist/index.mjs.map +0 -1
  88. package/dist/local/options.d.ts.map +0 -1
  89. package/dist/local/pid.d.ts.map +0 -1
  90. package/dist/local/pl.d.ts.map +0 -1
  91. package/dist/local/process.d.ts.map +0 -1
  92. package/dist/local/trace.d.ts.map +0 -1
  93. package/dist/ssh/__tests__/common-utils.d.ts.map +0 -1
  94. package/dist/ssh/connection_info.d.ts.map +0 -1
  95. package/dist/ssh/pl.d.ts.map +0 -1
  96. package/dist/ssh/pl_paths.d.ts.map +0 -1
  97. package/dist/ssh/ssh.d.ts.map +0 -1
  98. package/dist/ssh/supervisord.d.ts.map +0 -1
@@ -0,0 +1,223 @@
1
+ 'use strict';
2
+
3
+ var process$1 = require('./process.cjs');
4
+ var pl_binary = require('../common/pl_binary.cjs');
5
+ var tsHelpers = require('@milaboratories/ts-helpers');
6
+ var pid = require('./pid.cjs');
7
+ var trace = require('./trace.cjs');
8
+ var upath = require('upath');
9
+ var fsp = require('node:fs/promises');
10
+ var os = require('node:os');
11
+
12
+ function _interopNamespaceDefault(e) {
13
+ var n = Object.create(null);
14
+ if (e) {
15
+ Object.keys(e).forEach(function (k) {
16
+ if (k !== 'default') {
17
+ var d = Object.getOwnPropertyDescriptor(e, k);
18
+ Object.defineProperty(n, k, d.get ? d : {
19
+ enumerable: true,
20
+ get: function () { return e[k]; }
21
+ });
22
+ }
23
+ });
24
+ }
25
+ n.default = e;
26
+ return Object.freeze(n);
27
+ }
28
+
29
+ var os__namespace = /*#__PURE__*/_interopNamespaceDefault(os);
30
+
31
+ const LocalConfigYaml = 'config-local.yaml';
32
+ /**
33
+ * Represents a local running pl-core,
34
+ * and has methods to start, check if it's running, stop and wait for stopping it.
35
+ * Also, a hook on pl-core closed can be provided.
36
+ */
37
+ class LocalPl {
38
+ logger;
39
+ workingDir;
40
+ startOptions;
41
+ initialStartHistory;
42
+ onClose;
43
+ onError;
44
+ onCloseAndError;
45
+ onCloseAndErrorNoStop;
46
+ instance;
47
+ pid;
48
+ nRuns = 0;
49
+ lastRunHistory = {};
50
+ wasStopped = false;
51
+ constructor(logger, workingDir, startOptions, initialStartHistory, onClose, onError, onCloseAndError, onCloseAndErrorNoStop) {
52
+ this.logger = logger;
53
+ this.workingDir = workingDir;
54
+ this.startOptions = startOptions;
55
+ this.initialStartHistory = initialStartHistory;
56
+ this.onClose = onClose;
57
+ this.onError = onError;
58
+ this.onCloseAndError = onCloseAndError;
59
+ this.onCloseAndErrorNoStop = onCloseAndErrorNoStop;
60
+ }
61
+ async start() {
62
+ await trace.withTrace(this.logger, async (trace, t) => {
63
+ this.wasStopped = false;
64
+ const instance = process$1.processRun(this.logger, this.startOptions);
65
+ instance.on('error', (e) => {
66
+ this.logger.error(`error '${e}', while running platforma, started opts: ${JSON.stringify(this.debugInfo())}`);
67
+ // keep in mind there are no awaits here, it will be asynchronous
68
+ if (this.onError !== undefined)
69
+ void this.onError(this);
70
+ if (this.onCloseAndError !== undefined)
71
+ void this.onCloseAndError(this);
72
+ if (this.onCloseAndErrorNoStop !== undefined && !this.wasStopped)
73
+ void this.onCloseAndErrorNoStop(this);
74
+ });
75
+ instance.on('close', () => {
76
+ this.logger.warn(`platforma was closed, started opts: ${JSON.stringify(this.debugInfo())}`);
77
+ // keep in mind there are no awaits here, it will be asynchronous
78
+ if (this.onClose !== undefined)
79
+ void this.onClose(this);
80
+ if (this.onCloseAndError !== undefined)
81
+ void this.onCloseAndError(this);
82
+ if (this.onCloseAndErrorNoStop !== undefined && !this.wasStopped)
83
+ void this.onCloseAndErrorNoStop(this);
84
+ });
85
+ trace('started', true);
86
+ const pidFile = trace('pidFile', pid.filePid(this.workingDir));
87
+ trace('pid', tsHelpers.notEmpty(instance.pid));
88
+ trace('pidWritten', await pid.writePid(pidFile, tsHelpers.notEmpty(instance.pid)));
89
+ this.nRuns++;
90
+ this.instance = instance;
91
+ this.pid = instance.pid;
92
+ this.lastRunHistory = t;
93
+ });
94
+ }
95
+ stop() {
96
+ // TODO use this.instance to stop the process
97
+ this.wasStopped = true;
98
+ process$1.processStop(tsHelpers.notEmpty(this.pid));
99
+ }
100
+ async waitStopped() {
101
+ await process$1.processWaitStopped(tsHelpers.notEmpty(this.pid), 15000);
102
+ }
103
+ stopped() {
104
+ return this.wasStopped;
105
+ }
106
+ async isAlive() {
107
+ return await process$1.isProcessAlive(tsHelpers.notEmpty(this.pid));
108
+ }
109
+ debugInfo() {
110
+ return {
111
+ lastRunHistory: this.lastRunHistory,
112
+ nRuns: this.nRuns,
113
+ pid: this.pid,
114
+ workingDir: this.workingDir,
115
+ initialStartHistory: this.initialStartHistory,
116
+ wasStopped: this.wasStopped,
117
+ };
118
+ }
119
+ }
120
+ /**
121
+ * Starts pl-core, if the option was provided downloads a binary, reads license environments etc.
122
+ */
123
+ async function localPlatformaInit(logger, _ops) {
124
+ // filling-in default values
125
+ // Backend could consume a lot of CPU power,
126
+ // we want to keep at least a couple for UI and other apps to work.
127
+ const numCpu = Math.max(os__namespace.cpus().length - 2, 1);
128
+ const ops = mergeDefaultOps(_ops, numCpu);
129
+ return await trace.withTrace(logger, async (trace, t) => {
130
+ trace('startOptions', { ...ops, config: 'too wordy' });
131
+ const workDir = upath.resolve(ops.workingDir);
132
+ if (ops.closeOld) {
133
+ trace('closeOld', await localPlatformaReadPidAndStop(logger, workDir));
134
+ }
135
+ const configPath = upath.join(workDir, LocalConfigYaml);
136
+ logger.info(`writing configuration '${configPath}'...`);
137
+ await fsp.writeFile(configPath, ops.config);
138
+ const plBinPath = upath.join(workDir, 'binaries');
139
+ const baseBinaryPath = await pl_binary.resolveLocalPlBinaryPath(logger, plBinPath, ops.plBinary);
140
+ const binaryPath = trace('binaryPath', upath.join('binaries', baseBinaryPath));
141
+ const processOpts = plProcessOps(binaryPath, configPath, ops, workDir, process.env);
142
+ trace('processOpts', {
143
+ cmd: processOpts.cmd,
144
+ args: processOpts.args,
145
+ cwd: processOpts.opts.cwd,
146
+ });
147
+ const pl = new LocalPl(logger, ops.workingDir, processOpts, t, ops.onClose, ops.onError, ops.onCloseAndError, ops.onCloseAndErrorNoStop);
148
+ await pl.start();
149
+ return pl;
150
+ });
151
+ }
152
+ /** Reads a pid of the old pl-core if it was started in the same working directory,
153
+ * and closes it. */
154
+ async function localPlatformaReadPidAndStop(logger, workingDir) {
155
+ return await trace.withTrace(logger, async (trace, t) => {
156
+ const file = trace('pidFilePath', pid.filePid(workingDir));
157
+ const oldPid = trace('pid', await pid.readPid(file));
158
+ const alive = trace('wasAlive', await process$1.isProcessAlive(oldPid));
159
+ if (oldPid !== undefined && alive) {
160
+ trace('stopped', process$1.processStop(oldPid));
161
+ try {
162
+ trace('waitStopped', await process$1.processWaitStopped(oldPid, 15_000)); // larger, that 10s we provide to backend in config.
163
+ }
164
+ catch (_e) {
165
+ trace('forceStopped', process$1.processStop(oldPid, true));
166
+ trace('waitForceStopped', await process$1.processWaitStopped(oldPid, 5_000));
167
+ }
168
+ }
169
+ return t;
170
+ });
171
+ }
172
+ /** Gets default options for the whole init process
173
+ * and overrides them with the provided options. */
174
+ function mergeDefaultOps(ops, numCpu) {
175
+ const result = {
176
+ plBinary: pl_binary.newDefaultPlBinarySource(),
177
+ spawnOptions: {
178
+ env: {
179
+ GOMAXPROCS: String(numCpu),
180
+ },
181
+ },
182
+ closeOld: true,
183
+ };
184
+ if (ops.spawnOptions?.env) {
185
+ result.spawnOptions.env = { ...result.spawnOptions.env, ...ops.spawnOptions.env };
186
+ }
187
+ if (ops.spawnOptions) {
188
+ const withoutEnv = { ...ops.spawnOptions };
189
+ delete withoutEnv['env'];
190
+ result.spawnOptions = { ...result.spawnOptions, ...withoutEnv };
191
+ }
192
+ const withoutSpawnOps = { ...ops };
193
+ delete withoutSpawnOps['spawnOptions'];
194
+ return { ...result, ...withoutSpawnOps };
195
+ }
196
+ /** Gets default options for a platforma local binary
197
+ * and overrides them with the provided options. */
198
+ function plProcessOps(binaryPath, configPath, ops, workDir, defaultEnv) {
199
+ const result = {
200
+ cmd: binaryPath,
201
+ args: ['--config', configPath],
202
+ opts: {
203
+ env: { ...defaultEnv },
204
+ cwd: workDir,
205
+ stdio: ['pipe', 'ignore', 'inherit'],
206
+ windowsHide: true, // hide a terminal on Windows
207
+ },
208
+ };
209
+ if (ops.spawnOptions?.env) {
210
+ result.opts.env = { ...result.opts.env, ...ops.spawnOptions.env };
211
+ }
212
+ const withoutEnv = { ...ops.spawnOptions };
213
+ delete withoutEnv['env'];
214
+ result.opts = { ...result.opts, ...withoutEnv };
215
+ return result;
216
+ }
217
+
218
+ exports.LocalConfigYaml = LocalConfigYaml;
219
+ exports.LocalPl = LocalPl;
220
+ exports.localPlatformaInit = localPlatformaInit;
221
+ exports.mergeDefaultOps = mergeDefaultOps;
222
+ exports.plProcessOps = plProcessOps;
223
+ //# sourceMappingURL=pl.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pl.cjs","sources":["../../src/local/pl.ts"],"sourcesContent":["import type {\n ProcessOptions } from './process';\nimport {\n isProcessAlive,\n processStop,\n processWaitStopped,\n processRun,\n} from './process';\nimport type { PlBinarySource } from '../common/pl_binary';\nimport { newDefaultPlBinarySource, resolveLocalPlBinaryPath } from '../common/pl_binary';\nimport type { MiLogger } from '@milaboratories/ts-helpers';\nimport { notEmpty } from '@milaboratories/ts-helpers';\nimport type { ChildProcess, SpawnOptions } from 'node:child_process';\nimport { filePid, readPid, writePid } from './pid';\nimport type { Trace } from './trace';\nimport { withTrace } from './trace';\nimport upath from 'upath';\nimport fsp from 'node:fs/promises';\nimport type { Required } from 'utility-types';\nimport * as os from 'node:os';\n\nexport const LocalConfigYaml = 'config-local.yaml';\n\n/**\n * Represents a local running pl-core,\n * and has methods to start, check if it's running, stop and wait for stopping it.\n * Also, a hook on pl-core closed can be provided.\n */\nexport class LocalPl {\n private instance?: ChildProcess;\n public pid?: number;\n private nRuns: number = 0;\n private lastRunHistory: Trace = {};\n private wasStopped = false;\n\n constructor(\n private readonly logger: MiLogger,\n private readonly workingDir: string,\n private readonly startOptions: ProcessOptions,\n private readonly initialStartHistory: Trace,\n private readonly onClose?: (pl: LocalPl) => Promise<void>,\n private readonly onError?: (pl: LocalPl) => Promise<void>,\n private readonly onCloseAndError?: (pl: LocalPl) => Promise<void>,\n private readonly onCloseAndErrorNoStop?: (pl: LocalPl) => Promise<void>,\n ) {}\n\n async start() {\n await withTrace(this.logger, async (trace, t) => {\n this.wasStopped = false;\n const instance = processRun(this.logger, this.startOptions);\n instance.on('error', (e: any) => {\n this.logger.error(\n `error '${e}', while running platforma, started opts: ${JSON.stringify(this.debugInfo())}`,\n );\n\n // keep in mind there are no awaits here, it will be asynchronous\n if (this.onError !== undefined) void this.onError(this);\n if (this.onCloseAndError !== undefined) void this.onCloseAndError(this);\n if (this.onCloseAndErrorNoStop !== undefined && !this.wasStopped)\n void this.onCloseAndErrorNoStop(this);\n });\n instance.on('close', () => {\n this.logger.warn(`platforma was closed, started opts: ${JSON.stringify(this.debugInfo())}`);\n\n // keep in mind there are no awaits here, it will be asynchronous\n if (this.onClose !== undefined) void this.onClose(this);\n if (this.onCloseAndError !== undefined) void this.onCloseAndError(this);\n if (this.onCloseAndErrorNoStop !== undefined && !this.wasStopped)\n void this.onCloseAndErrorNoStop(this);\n });\n\n trace('started', true);\n\n const pidFile = trace('pidFile', filePid(this.workingDir));\n trace('pid', notEmpty(instance.pid));\n trace('pidWritten', await writePid(pidFile, notEmpty(instance.pid)));\n\n this.nRuns++;\n this.instance = instance;\n this.pid = instance.pid;\n this.lastRunHistory = t;\n });\n }\n\n stop() {\n // TODO use this.instance to stop the process\n this.wasStopped = true;\n processStop(notEmpty(this.pid));\n }\n\n async waitStopped() {\n await processWaitStopped(notEmpty(this.pid), 15000);\n }\n\n stopped() {\n return this.wasStopped;\n }\n\n async isAlive(): Promise<boolean> {\n return await isProcessAlive(notEmpty(this.pid));\n }\n\n debugInfo() {\n return {\n lastRunHistory: this.lastRunHistory,\n nRuns: this.nRuns,\n pid: this.pid,\n workingDir: this.workingDir,\n initialStartHistory: this.initialStartHistory,\n wasStopped: this.wasStopped,\n };\n }\n}\n\n/** Options to start a local pl-core. */\nexport type LocalPlOptions = {\n /** From what directory start a process. */\n readonly workingDir: string;\n /** A string representation of yaml config. */\n readonly config: string;\n /** How to get a binary, download it or get an existing one (default: download latest version) */\n readonly plBinary?: PlBinarySource;\n /** Additional options for a process, environments, stdout, stderr etc. */\n readonly spawnOptions?: SpawnOptions;\n /**\n * If the previous pl-core was started from the same directory,\n * we can check if it's still running and then stop it before starting a new one.\n * (default: true)\n */\n readonly closeOld?: boolean;\n\n readonly onClose?: (pl: LocalPl) => Promise<void>;\n readonly onError?: (pl: LocalPl) => Promise<void>;\n readonly onCloseAndError?: (pl: LocalPl) => Promise<void>;\n readonly onCloseAndErrorNoStop?: (pl: LocalPl) => Promise<void>;\n};\n\nexport type LocalPlOptionsFull = Required<LocalPlOptions, 'plBinary' | 'spawnOptions' | 'closeOld'>;\n\n/**\n * Starts pl-core, if the option was provided downloads a binary, reads license environments etc.\n */\nexport async function localPlatformaInit(logger: MiLogger, _ops: LocalPlOptions): Promise<LocalPl> {\n // filling-in default values\n\n // Backend could consume a lot of CPU power,\n // we want to keep at least a couple for UI and other apps to work.\n const numCpu = Math.max(os.cpus().length - 2, 1);\n const ops = mergeDefaultOps(_ops, numCpu);\n\n return await withTrace(logger, async (trace, t) => {\n trace('startOptions', { ...ops, config: 'too wordy' });\n\n const workDir = upath.resolve(ops.workingDir);\n\n if (ops.closeOld) {\n trace('closeOld', await localPlatformaReadPidAndStop(logger, workDir));\n }\n\n const configPath = upath.join(workDir, LocalConfigYaml);\n\n logger.info(`writing configuration '${configPath}'...`);\n await fsp.writeFile(configPath, ops.config);\n\n const plBinPath = upath.join(workDir, 'binaries');\n const baseBinaryPath = await resolveLocalPlBinaryPath(logger, plBinPath, ops.plBinary);\n const binaryPath = trace('binaryPath', upath.join('binaries', baseBinaryPath));\n\n const processOpts = plProcessOps(binaryPath, configPath, ops, workDir, process.env);\n trace('processOpts', {\n cmd: processOpts.cmd,\n args: processOpts.args,\n cwd: processOpts.opts.cwd,\n });\n\n const pl = new LocalPl(\n logger,\n ops.workingDir,\n processOpts,\n t,\n ops.onClose,\n ops.onError,\n ops.onCloseAndError,\n ops.onCloseAndErrorNoStop,\n );\n await pl.start();\n\n return pl;\n });\n}\n\n/** Reads a pid of the old pl-core if it was started in the same working directory,\n * and closes it. */\nasync function localPlatformaReadPidAndStop(\n logger: MiLogger,\n workingDir: string,\n): Promise<Record<string, any>> {\n return await withTrace(logger, async (trace, t) => {\n const file = trace('pidFilePath', filePid(workingDir));\n\n const oldPid = trace('pid', await readPid(file));\n const alive = trace('wasAlive', await isProcessAlive(oldPid));\n\n if (oldPid !== undefined && alive) {\n trace('stopped', processStop(oldPid));\n try {\n trace('waitStopped', await processWaitStopped(oldPid, 15_000)); // larger, that 10s we provide to backend in config.\n } catch (_e) {\n trace('forceStopped', processStop(oldPid, true));\n trace('waitForceStopped', await processWaitStopped(oldPid, 5_000));\n }\n }\n\n return t;\n });\n}\n\n/** Gets default options for the whole init process\n * and overrides them with the provided options. */\nexport function mergeDefaultOps(ops: LocalPlOptions, numCpu: number): LocalPlOptionsFull {\n const result: {\n plBinary: PlBinarySource;\n spawnOptions: SpawnOptions;\n closeOld: boolean;\n } = {\n plBinary: newDefaultPlBinarySource(),\n spawnOptions: {\n env: {\n GOMAXPROCS: String(numCpu),\n },\n },\n closeOld: true,\n };\n\n if (ops.spawnOptions?.env) {\n result.spawnOptions.env = { ...result.spawnOptions.env, ...ops.spawnOptions.env };\n }\n\n if (ops.spawnOptions) {\n const withoutEnv = { ...ops.spawnOptions };\n delete withoutEnv['env'];\n result.spawnOptions = { ...result.spawnOptions, ...withoutEnv };\n }\n\n const withoutSpawnOps = { ...ops };\n delete withoutSpawnOps['spawnOptions'];\n\n return { ...result, ...withoutSpawnOps };\n}\n\n/** Gets default options for a platforma local binary\n * and overrides them with the provided options. */\nexport function plProcessOps(\n binaryPath: any,\n configPath: string,\n ops: LocalPlOptionsFull,\n workDir: string,\n defaultEnv: Record<string, string | undefined>,\n): ProcessOptions {\n const result: ProcessOptions = {\n cmd: binaryPath,\n args: ['--config', configPath],\n opts: {\n env: { ...defaultEnv },\n cwd: workDir,\n stdio: ['pipe', 'ignore', 'inherit'],\n windowsHide: true, // hide a terminal on Windows\n },\n };\n\n if (ops.spawnOptions?.env) {\n result.opts.env = { ...result.opts.env, ...ops.spawnOptions.env };\n }\n\n const withoutEnv = { ...ops.spawnOptions };\n delete withoutEnv['env'];\n result.opts = { ...result.opts, ...withoutEnv };\n\n return result;\n}\n"],"names":["withTrace","processRun","filePid","notEmpty","writePid","processStop","processWaitStopped","isProcessAlive","os","resolveLocalPlBinaryPath","readPid","newDefaultPlBinarySource"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBO,MAAM,eAAe,GAAG;AAE/B;;;;AAIG;MACU,OAAO,CAAA;AAQC,IAAA,MAAA;AACA,IAAA,UAAA;AACA,IAAA,YAAA;AACA,IAAA,mBAAA;AACA,IAAA,OAAA;AACA,IAAA,OAAA;AACA,IAAA,eAAA;AACA,IAAA,qBAAA;AAdX,IAAA,QAAQ;AACT,IAAA,GAAG;IACF,KAAK,GAAW,CAAC;IACjB,cAAc,GAAU,EAAE;IAC1B,UAAU,GAAG,KAAK;AAE1B,IAAA,WAAA,CACmB,MAAgB,EAChB,UAAkB,EAClB,YAA4B,EAC5B,mBAA0B,EAC1B,OAAwC,EACxC,OAAwC,EACxC,eAAgD,EAChD,qBAAsD,EAAA;QAPtD,IAAA,CAAA,MAAM,GAAN,MAAM;QACN,IAAA,CAAA,UAAU,GAAV,UAAU;QACV,IAAA,CAAA,YAAY,GAAZ,YAAY;QACZ,IAAA,CAAA,mBAAmB,GAAnB,mBAAmB;QACnB,IAAA,CAAA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Ae,CAAC,cAAc,CAAC;AAEtC,IAAA,OAAO,EAAE,GAAG,MAAM,EAAE,GAAG,eAAe,EAAE;AAC1C;AAEA;AACmD;AAC7C,SAAU,YAAY,CAC1B,UAAe,EACf,UAAkB,EAClB,GAAuB,EACvB,OAAe,EACf,UAA8C,EAAA;AAE9C,IAAA,MAAM,MAAM,GAAmB;AAC7B,QAAA,GAAG,EAAE,UAAU;AACf,QAAA,IAAI,EAAE,CAAC,UAAU,EAAE,UAAU,CAAC;AAC9B,QAAA,IAAI,EAAE;AACJ,YAAA,GAAG,EAAE,EAAE,GAAG,UAAU,EAAE;AACtB,YAAA,GAAG,EAAE,OAAO;AACZ,YAAA,KAAK,EAAE,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,CAAC;YACpC,WAAW,EAAE,IAAI;AAClB,SAAA;KACF;AAED,IAAA,IAAI,GAAG,CAAC,YAAY,EAAE,GAAG,EAAE;QACzB,MAAM,CAAC,IAAI,CAAC,GAAG,GAAG,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,EAAE;IACnE;IAEA,MAAM,UAAU,GAAG,EAAE,GAAG,GAAG,CAAC,YAAY,EAAE;AAC1C,IAAA,OAAO,UAAU,CAAC,KAAK,CAAC;AACxB,IAAA,MAAM,CAAC,IAAI,GAAG,EAAE,GAAG,MAAM,CAAC,IAAI,EAAE,GAAG,UAAU,EAAE;AAE/C,IAAA,OAAO,MAAM;AACf;;;;;;;;"}
@@ -71,4 +71,3 @@ export declare function mergeDefaultOps(ops: LocalPlOptions, numCpu: number): Lo
71
71
  /** Gets default options for a platforma local binary
72
72
  * and overrides them with the provided options. */
73
73
  export declare function plProcessOps(binaryPath: any, configPath: string, ops: LocalPlOptionsFull, workDir: string, defaultEnv: Record<string, string | undefined>): ProcessOptions;
74
- //# sourceMappingURL=pl.d.ts.map
@@ -0,0 +1,198 @@
1
+ import { processStop, processWaitStopped, isProcessAlive, processRun } from './process.js';
2
+ import { newDefaultPlBinarySource, resolveLocalPlBinaryPath } from '../common/pl_binary.js';
3
+ import { notEmpty } from '@milaboratories/ts-helpers';
4
+ import { filePid, writePid, readPid } from './pid.js';
5
+ import { withTrace } from './trace.js';
6
+ import upath from 'upath';
7
+ import fsp from 'node:fs/promises';
8
+ import * as os from 'node:os';
9
+
10
+ const LocalConfigYaml = 'config-local.yaml';
11
+ /**
12
+ * Represents a local running pl-core,
13
+ * and has methods to start, check if it's running, stop and wait for stopping it.
14
+ * Also, a hook on pl-core closed can be provided.
15
+ */
16
+ class LocalPl {
17
+ logger;
18
+ workingDir;
19
+ startOptions;
20
+ initialStartHistory;
21
+ onClose;
22
+ onError;
23
+ onCloseAndError;
24
+ onCloseAndErrorNoStop;
25
+ instance;
26
+ pid;
27
+ nRuns = 0;
28
+ lastRunHistory = {};
29
+ wasStopped = false;
30
+ constructor(logger, workingDir, startOptions, initialStartHistory, onClose, onError, onCloseAndError, onCloseAndErrorNoStop) {
31
+ this.logger = logger;
32
+ this.workingDir = workingDir;
33
+ this.startOptions = startOptions;
34
+ this.initialStartHistory = initialStartHistory;
35
+ this.onClose = onClose;
36
+ this.onError = onError;
37
+ this.onCloseAndError = onCloseAndError;
38
+ this.onCloseAndErrorNoStop = onCloseAndErrorNoStop;
39
+ }
40
+ async start() {
41
+ await withTrace(this.logger, async (trace, t) => {
42
+ this.wasStopped = false;
43
+ const instance = processRun(this.logger, this.startOptions);
44
+ instance.on('error', (e) => {
45
+ this.logger.error(`error '${e}', while running platforma, started opts: ${JSON.stringify(this.debugInfo())}`);
46
+ // keep in mind there are no awaits here, it will be asynchronous
47
+ if (this.onError !== undefined)
48
+ void this.onError(this);
49
+ if (this.onCloseAndError !== undefined)
50
+ void this.onCloseAndError(this);
51
+ if (this.onCloseAndErrorNoStop !== undefined && !this.wasStopped)
52
+ void this.onCloseAndErrorNoStop(this);
53
+ });
54
+ instance.on('close', () => {
55
+ this.logger.warn(`platforma was closed, started opts: ${JSON.stringify(this.debugInfo())}`);
56
+ // keep in mind there are no awaits here, it will be asynchronous
57
+ if (this.onClose !== undefined)
58
+ void this.onClose(this);
59
+ if (this.onCloseAndError !== undefined)
60
+ void this.onCloseAndError(this);
61
+ if (this.onCloseAndErrorNoStop !== undefined && !this.wasStopped)
62
+ void this.onCloseAndErrorNoStop(this);
63
+ });
64
+ trace('started', true);
65
+ const pidFile = trace('pidFile', filePid(this.workingDir));
66
+ trace('pid', notEmpty(instance.pid));
67
+ trace('pidWritten', await writePid(pidFile, notEmpty(instance.pid)));
68
+ this.nRuns++;
69
+ this.instance = instance;
70
+ this.pid = instance.pid;
71
+ this.lastRunHistory = t;
72
+ });
73
+ }
74
+ stop() {
75
+ // TODO use this.instance to stop the process
76
+ this.wasStopped = true;
77
+ processStop(notEmpty(this.pid));
78
+ }
79
+ async waitStopped() {
80
+ await processWaitStopped(notEmpty(this.pid), 15000);
81
+ }
82
+ stopped() {
83
+ return this.wasStopped;
84
+ }
85
+ async isAlive() {
86
+ return await isProcessAlive(notEmpty(this.pid));
87
+ }
88
+ debugInfo() {
89
+ return {
90
+ lastRunHistory: this.lastRunHistory,
91
+ nRuns: this.nRuns,
92
+ pid: this.pid,
93
+ workingDir: this.workingDir,
94
+ initialStartHistory: this.initialStartHistory,
95
+ wasStopped: this.wasStopped,
96
+ };
97
+ }
98
+ }
99
+ /**
100
+ * Starts pl-core, if the option was provided downloads a binary, reads license environments etc.
101
+ */
102
+ async function localPlatformaInit(logger, _ops) {
103
+ // filling-in default values
104
+ // Backend could consume a lot of CPU power,
105
+ // we want to keep at least a couple for UI and other apps to work.
106
+ const numCpu = Math.max(os.cpus().length - 2, 1);
107
+ const ops = mergeDefaultOps(_ops, numCpu);
108
+ return await withTrace(logger, async (trace, t) => {
109
+ trace('startOptions', { ...ops, config: 'too wordy' });
110
+ const workDir = upath.resolve(ops.workingDir);
111
+ if (ops.closeOld) {
112
+ trace('closeOld', await localPlatformaReadPidAndStop(logger, workDir));
113
+ }
114
+ const configPath = upath.join(workDir, LocalConfigYaml);
115
+ logger.info(`writing configuration '${configPath}'...`);
116
+ await fsp.writeFile(configPath, ops.config);
117
+ const plBinPath = upath.join(workDir, 'binaries');
118
+ const baseBinaryPath = await resolveLocalPlBinaryPath(logger, plBinPath, ops.plBinary);
119
+ const binaryPath = trace('binaryPath', upath.join('binaries', baseBinaryPath));
120
+ const processOpts = plProcessOps(binaryPath, configPath, ops, workDir, process.env);
121
+ trace('processOpts', {
122
+ cmd: processOpts.cmd,
123
+ args: processOpts.args,
124
+ cwd: processOpts.opts.cwd,
125
+ });
126
+ const pl = new LocalPl(logger, ops.workingDir, processOpts, t, ops.onClose, ops.onError, ops.onCloseAndError, ops.onCloseAndErrorNoStop);
127
+ await pl.start();
128
+ return pl;
129
+ });
130
+ }
131
+ /** Reads a pid of the old pl-core if it was started in the same working directory,
132
+ * and closes it. */
133
+ async function localPlatformaReadPidAndStop(logger, workingDir) {
134
+ return await withTrace(logger, async (trace, t) => {
135
+ const file = trace('pidFilePath', filePid(workingDir));
136
+ const oldPid = trace('pid', await readPid(file));
137
+ const alive = trace('wasAlive', await isProcessAlive(oldPid));
138
+ if (oldPid !== undefined && alive) {
139
+ trace('stopped', processStop(oldPid));
140
+ try {
141
+ trace('waitStopped', await processWaitStopped(oldPid, 15_000)); // larger, that 10s we provide to backend in config.
142
+ }
143
+ catch (_e) {
144
+ trace('forceStopped', processStop(oldPid, true));
145
+ trace('waitForceStopped', await processWaitStopped(oldPid, 5_000));
146
+ }
147
+ }
148
+ return t;
149
+ });
150
+ }
151
+ /** Gets default options for the whole init process
152
+ * and overrides them with the provided options. */
153
+ function mergeDefaultOps(ops, numCpu) {
154
+ const result = {
155
+ plBinary: newDefaultPlBinarySource(),
156
+ spawnOptions: {
157
+ env: {
158
+ GOMAXPROCS: String(numCpu),
159
+ },
160
+ },
161
+ closeOld: true,
162
+ };
163
+ if (ops.spawnOptions?.env) {
164
+ result.spawnOptions.env = { ...result.spawnOptions.env, ...ops.spawnOptions.env };
165
+ }
166
+ if (ops.spawnOptions) {
167
+ const withoutEnv = { ...ops.spawnOptions };
168
+ delete withoutEnv['env'];
169
+ result.spawnOptions = { ...result.spawnOptions, ...withoutEnv };
170
+ }
171
+ const withoutSpawnOps = { ...ops };
172
+ delete withoutSpawnOps['spawnOptions'];
173
+ return { ...result, ...withoutSpawnOps };
174
+ }
175
+ /** Gets default options for a platforma local binary
176
+ * and overrides them with the provided options. */
177
+ function plProcessOps(binaryPath, configPath, ops, workDir, defaultEnv) {
178
+ const result = {
179
+ cmd: binaryPath,
180
+ args: ['--config', configPath],
181
+ opts: {
182
+ env: { ...defaultEnv },
183
+ cwd: workDir,
184
+ stdio: ['pipe', 'ignore', 'inherit'],
185
+ windowsHide: true, // hide a terminal on Windows
186
+ },
187
+ };
188
+ if (ops.spawnOptions?.env) {
189
+ result.opts.env = { ...result.opts.env, ...ops.spawnOptions.env };
190
+ }
191
+ const withoutEnv = { ...ops.spawnOptions };
192
+ delete withoutEnv['env'];
193
+ result.opts = { ...result.opts, ...withoutEnv };
194
+ return result;
195
+ }
196
+
197
+ export { LocalConfigYaml, LocalPl, localPlatformaInit, mergeDefaultOps, plProcessOps };
198
+ //# sourceMappingURL=pl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pl.js","sources":["../../src/local/pl.ts"],"sourcesContent":["import type {\n ProcessOptions } from './process';\nimport {\n isProcessAlive,\n processStop,\n processWaitStopped,\n processRun,\n} from './process';\nimport type { PlBinarySource } from '../common/pl_binary';\nimport { newDefaultPlBinarySource, resolveLocalPlBinaryPath } from '../common/pl_binary';\nimport type { MiLogger } from '@milaboratories/ts-helpers';\nimport { notEmpty } from '@milaboratories/ts-helpers';\nimport type { ChildProcess, SpawnOptions } from 'node:child_process';\nimport { filePid, readPid, writePid } from './pid';\nimport type { Trace } from './trace';\nimport { withTrace } from './trace';\nimport upath from 'upath';\nimport fsp from 'node:fs/promises';\nimport type { Required } from 'utility-types';\nimport * as os from 'node:os';\n\nexport const LocalConfigYaml = 'config-local.yaml';\n\n/**\n * Represents a local running pl-core,\n * and has methods to start, check if it's running, stop and wait for stopping it.\n * Also, a hook on pl-core closed can be provided.\n */\nexport class LocalPl {\n private instance?: ChildProcess;\n public pid?: number;\n private nRuns: number = 0;\n private lastRunHistory: Trace = {};\n private wasStopped = false;\n\n constructor(\n private readonly logger: MiLogger,\n private readonly workingDir: string,\n private readonly startOptions: ProcessOptions,\n private readonly initialStartHistory: Trace,\n private readonly onClose?: (pl: LocalPl) => Promise<void>,\n private readonly onError?: (pl: LocalPl) => Promise<void>,\n private readonly onCloseAndError?: (pl: LocalPl) => Promise<void>,\n private readonly onCloseAndErrorNoStop?: (pl: LocalPl) => Promise<void>,\n ) {}\n\n async start() {\n await withTrace(this.logger, async (trace, t) => {\n this.wasStopped = false;\n const instance = processRun(this.logger, this.startOptions);\n instance.on('error', (e: any) => {\n this.logger.error(\n `error '${e}', while running platforma, started opts: ${JSON.stringify(this.debugInfo())}`,\n );\n\n // keep in mind there are no awaits here, it will be asynchronous\n if (this.onError !== undefined) void this.onError(this);\n if (this.onCloseAndError !== undefined) void this.onCloseAndError(this);\n if (this.onCloseAndErrorNoStop !== undefined && !this.wasStopped)\n void this.onCloseAndErrorNoStop(this);\n });\n instance.on('close', () => {\n this.logger.warn(`platforma was closed, started opts: ${JSON.stringify(this.debugInfo())}`);\n\n // keep in mind there are no awaits here, it will be asynchronous\n if (this.onClose !== undefined) void this.onClose(this);\n if (this.onCloseAndError !== undefined) void this.onCloseAndError(this);\n if (this.onCloseAndErrorNoStop !== undefined && !this.wasStopped)\n void this.onCloseAndErrorNoStop(this);\n });\n\n trace('started', true);\n\n const pidFile = trace('pidFile', filePid(this.workingDir));\n trace('pid', notEmpty(instance.pid));\n trace('pidWritten', await writePid(pidFile, notEmpty(instance.pid)));\n\n this.nRuns++;\n this.instance = instance;\n this.pid = instance.pid;\n this.lastRunHistory = t;\n });\n }\n\n stop() {\n // TODO use this.instance to stop the process\n this.wasStopped = true;\n processStop(notEmpty(this.pid));\n }\n\n async waitStopped() {\n await processWaitStopped(notEmpty(this.pid), 15000);\n }\n\n stopped() {\n return this.wasStopped;\n }\n\n async isAlive(): Promise<boolean> {\n return await isProcessAlive(notEmpty(this.pid));\n }\n\n debugInfo() {\n return {\n lastRunHistory: this.lastRunHistory,\n nRuns: this.nRuns,\n pid: this.pid,\n workingDir: this.workingDir,\n initialStartHistory: this.initialStartHistory,\n wasStopped: this.wasStopped,\n };\n }\n}\n\n/** Options to start a local pl-core. */\nexport type LocalPlOptions = {\n /** From what directory start a process. */\n readonly workingDir: string;\n /** A string representation of yaml config. */\n readonly config: string;\n /** How to get a binary, download it or get an existing one (default: download latest version) */\n readonly plBinary?: PlBinarySource;\n /** Additional options for a process, environments, stdout, stderr etc. */\n readonly spawnOptions?: SpawnOptions;\n /**\n * If the previous pl-core was started from the same directory,\n * we can check if it's still running and then stop it before starting a new one.\n * (default: true)\n */\n readonly closeOld?: boolean;\n\n readonly onClose?: (pl: LocalPl) => Promise<void>;\n readonly onError?: (pl: LocalPl) => Promise<void>;\n readonly onCloseAndError?: (pl: LocalPl) => Promise<void>;\n readonly onCloseAndErrorNoStop?: (pl: LocalPl) => Promise<void>;\n};\n\nexport type LocalPlOptionsFull = Required<LocalPlOptions, 'plBinary' | 'spawnOptions' | 'closeOld'>;\n\n/**\n * Starts pl-core, if the option was provided downloads a binary, reads license environments etc.\n */\nexport async function localPlatformaInit(logger: MiLogger, _ops: LocalPlOptions): Promise<LocalPl> {\n // filling-in default values\n\n // Backend could consume a lot of CPU power,\n // we want to keep at least a couple for UI and other apps to work.\n const numCpu = Math.max(os.cpus().length - 2, 1);\n const ops = mergeDefaultOps(_ops, numCpu);\n\n return await withTrace(logger, async (trace, t) => {\n trace('startOptions', { ...ops, config: 'too wordy' });\n\n const workDir = upath.resolve(ops.workingDir);\n\n if (ops.closeOld) {\n trace('closeOld', await localPlatformaReadPidAndStop(logger, workDir));\n }\n\n const configPath = upath.join(workDir, LocalConfigYaml);\n\n logger.info(`writing configuration '${configPath}'...`);\n await fsp.writeFile(configPath, ops.config);\n\n const plBinPath = upath.join(workDir, 'binaries');\n const baseBinaryPath = await resolveLocalPlBinaryPath(logger, plBinPath, ops.plBinary);\n const binaryPath = trace('binaryPath', upath.join('binaries', baseBinaryPath));\n\n const processOpts = plProcessOps(binaryPath, configPath, ops, workDir, process.env);\n trace('processOpts', {\n cmd: processOpts.cmd,\n args: processOpts.args,\n cwd: processOpts.opts.cwd,\n });\n\n const pl = new LocalPl(\n logger,\n ops.workingDir,\n processOpts,\n t,\n ops.onClose,\n ops.onError,\n ops.onCloseAndError,\n ops.onCloseAndErrorNoStop,\n );\n await pl.start();\n\n return pl;\n });\n}\n\n/** Reads a pid of the old pl-core if it was started in the same working directory,\n * and closes it. */\nasync function localPlatformaReadPidAndStop(\n logger: MiLogger,\n workingDir: string,\n): Promise<Record<string, any>> {\n return await withTrace(logger, async (trace, t) => {\n const file = trace('pidFilePath', filePid(workingDir));\n\n const oldPid = trace('pid', await readPid(file));\n const alive = trace('wasAlive', await isProcessAlive(oldPid));\n\n if (oldPid !== undefined && alive) {\n trace('stopped', processStop(oldPid));\n try {\n trace('waitStopped', await processWaitStopped(oldPid, 15_000)); // larger, that 10s we provide to backend in config.\n } catch (_e) {\n trace('forceStopped', processStop(oldPid, true));\n trace('waitForceStopped', await processWaitStopped(oldPid, 5_000));\n }\n }\n\n return t;\n });\n}\n\n/** Gets default options for the whole init process\n * and overrides them with the provided options. */\nexport function mergeDefaultOps(ops: LocalPlOptions, numCpu: number): LocalPlOptionsFull {\n const result: {\n plBinary: PlBinarySource;\n spawnOptions: SpawnOptions;\n closeOld: boolean;\n } = {\n plBinary: newDefaultPlBinarySource(),\n spawnOptions: {\n env: {\n GOMAXPROCS: String(numCpu),\n },\n },\n closeOld: true,\n };\n\n if (ops.spawnOptions?.env) {\n result.spawnOptions.env = { ...result.spawnOptions.env, ...ops.spawnOptions.env };\n }\n\n if (ops.spawnOptions) {\n const withoutEnv = { ...ops.spawnOptions };\n delete withoutEnv['env'];\n result.spawnOptions = { ...result.spawnOptions, ...withoutEnv };\n }\n\n const withoutSpawnOps = { ...ops };\n delete withoutSpawnOps['spawnOptions'];\n\n return { ...result, ...withoutSpawnOps };\n}\n\n/** Gets default options for a platforma local binary\n * and overrides them with the provided options. */\nexport function plProcessOps(\n binaryPath: any,\n configPath: string,\n ops: LocalPlOptionsFull,\n workDir: string,\n defaultEnv: Record<string, string | undefined>,\n): ProcessOptions {\n const result: ProcessOptions = {\n cmd: binaryPath,\n args: ['--config', configPath],\n opts: {\n env: { ...defaultEnv },\n cwd: workDir,\n stdio: ['pipe', 'ignore', 'inherit'],\n windowsHide: true, // hide a terminal on Windows\n },\n };\n\n if (ops.spawnOptions?.env) {\n result.opts.env = { ...result.opts.env, ...ops.spawnOptions.env };\n }\n\n const withoutEnv = { ...ops.spawnOptions };\n delete withoutEnv['env'];\n result.opts = { ...result.opts, ...withoutEnv };\n\n return result;\n}\n"],"names":[],"mappings":";;;;;;;;;AAqBO,MAAM,eAAe,GAAG;AAE/B;;;;AAIG;MACU,OAAO,CAAA;AAQC,IAAA,MAAA;AACA,IAAA,UAAA;AACA,IAAA,YAAA;AACA,IAAA,mBAAA;AACA,IAAA,OAAA;AACA,IAAA,OAAA;AACA,IAAA,eAAA;AACA,IAAA,qBAAA;AAdX,IAAA,QAAQ;AACT,IAAA,GAAG;IACF,KAAK,GAAW,CAAC;IACjB,cAAc,GAAU,EAAE;IAC1B,UAAU,GAAG,KAAK;AAE1B,IAAA,WAAA,CACmB,MAAgB,EAChB,UAAkB,EAClB,YAA4B,EAC5B,mBAA0B,EAC1B,OAAwC,EACxC,OAAwC,EACxC,eAAgD,EAChD,qBAAsD,EAAA;QAPtD,IAAA,CAAA,MAAM,GAAN,MAAM;QACN,IAAA,CAAA,UAAU,GAAV,UAAU;QACV,IAAA,CAAA,YAAY,GAAZ,YAAY;QACZ,IAAA,CAAA,mBAAmB,GAAnB,mBA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CAAC;AAEtC,IAAA,OAAO,EAAE,GAAG,MAAM,EAAE,GAAG,eAAe,EAAE;AAC1C;AAEA;AACmD;AAC7C,SAAU,YAAY,CAC1B,UAAe,EACf,UAAkB,EAClB,GAAuB,EACvB,OAAe,EACf,UAA8C,EAAA;AAE9C,IAAA,MAAM,MAAM,GAAmB;AAC7B,QAAA,GAAG,EAAE,UAAU;AACf,QAAA,IAAI,EAAE,CAAC,UAAU,EAAE,UAAU,CAAC;AAC9B,QAAA,IAAI,EAAE;AACJ,YAAA,GAAG,EAAE,EAAE,GAAG,UAAU,EAAE;AACtB,YAAA,GAAG,EAAE,OAAO;AACZ,YAAA,KAAK,EAAE,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,CAAC;YACpC,WAAW,EAAE,IAAI;AAClB,SAAA;KACF;AAED,IAAA,IAAI,GAAG,CAAC,YAAY,EAAE,GAAG,EAAE;QACzB,MAAM,CAAC,IAAI,CAAC,GAAG,GAAG,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,EAAE;IACnE;IAEA,MAAM,UAAU,GAAG,EAAE,GAAG,GAAG,CAAC,YAAY,EAAE;AAC1C,IAAA,OAAO,UAAU,CAAC,KAAK,CAAC;AACxB,IAAA,MAAM,CAAC,IAAI,GAAG,EAAE,GAAG,MAAM,CAAC,IAAI,EAAE,GAAG,UAAU,EAAE;AAE/C,IAAA,OAAO,MAAM;AACf;;;;"}
@@ -0,0 +1,77 @@
1
+ 'use strict';
2
+
3
+ var node_child_process = require('node:child_process');
4
+ var tsHelpers = require('@milaboratories/ts-helpers');
5
+
6
+ function processRun(logger, opts) {
7
+ logger.info(`Running:
8
+ cmd: ${JSON.stringify([opts.cmd, ...opts.args])}
9
+ wd: ${opts.opts.cwd}`);
10
+ logger.info(' spawning child process');
11
+ return node_child_process.spawn(opts.cmd, opts.args, opts.opts);
12
+ }
13
+ // eslint-disable-next-line @typescript-eslint/require-await
14
+ async function isProcessAlive(pid) {
15
+ try {
16
+ process.kill(pid, 0);
17
+ // Check we look at 'platforma' to not kill wrong process.
18
+ const processName = getProcessName(pid);
19
+ if (process.platform === 'win32') {
20
+ return processName === 'platforma.exe'; // process name does not contain path to the file.
21
+ }
22
+ // Linux and Mac OS X behave differently (so can different Linux distributions).
23
+ // Process name can contain original path to the binary file or just its name.
24
+ return processName.endsWith('/platforma') || processName === 'platforma';
25
+ }
26
+ catch (_e) {
27
+ return false;
28
+ }
29
+ }
30
+ function getProcessName(pid) {
31
+ try {
32
+ if (process.platform === 'win32') {
33
+ // Windows: use tasklist command
34
+ const output = node_child_process.execSync(`tasklist /FI "PID eq ${pid}" /FO CSV /NH`, { encoding: 'utf8' });
35
+ const lines = output.trim().split('\n');
36
+ if (lines.length > 0 && lines[0].includes(',')) {
37
+ const parts = lines[0].split(',');
38
+ if (parts.length >= 1) {
39
+ // Remove quotes and get the executable name
40
+ const exeName = parts[0].replace(/^"|"$/g, '').trim();
41
+ return exeName;
42
+ }
43
+ }
44
+ }
45
+ else {
46
+ // Unix-like systems: use ps command
47
+ const output = node_child_process.execSync(`ps -p ${pid} -o comm=`, { encoding: 'utf8' });
48
+ const processName = output.trim();
49
+ return processName;
50
+ }
51
+ }
52
+ catch (_error) {
53
+ // If we can't get the process name, return empty string
54
+ return '';
55
+ }
56
+ return '';
57
+ }
58
+ function processStop(pid, force = false) {
59
+ return process.kill(pid, force ? 'SIGKILL' : 'SIGINT');
60
+ }
61
+ async function processWaitStopped(pid, maxMs) {
62
+ const sleepMs = 100;
63
+ let total = 0;
64
+ while (await isProcessAlive(pid)) {
65
+ await tsHelpers.sleep(sleepMs);
66
+ total += sleepMs;
67
+ if (total > maxMs) {
68
+ throw new Error(`The process did not stopped after ${maxMs} ms.`);
69
+ }
70
+ }
71
+ }
72
+
73
+ exports.isProcessAlive = isProcessAlive;
74
+ exports.processRun = processRun;
75
+ exports.processStop = processStop;
76
+ exports.processWaitStopped = processWaitStopped;
77
+ //# sourceMappingURL=process.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process.cjs","sources":["../../src/local/process.ts"],"sourcesContent":["import type { SpawnOptions, ChildProcess } from 'node:child_process';\nimport { spawn } from 'node:child_process';\nimport { execSync } from 'node:child_process';\nimport type { MiLogger } from '@milaboratories/ts-helpers';\nimport { sleep } from '@milaboratories/ts-helpers';\n\nexport type ProcessOptions = {\n cmd: string;\n args: string[];\n opts: SpawnOptions;\n};\n\nexport function processRun(logger: MiLogger, opts: ProcessOptions): ChildProcess {\n logger.info(`Running:\ncmd: ${JSON.stringify([opts.cmd, ...opts.args])}\nwd: ${opts.opts.cwd}`);\n\n logger.info(' spawning child process');\n return spawn(opts.cmd, opts.args, opts.opts);\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await\nexport async function isProcessAlive(pid: number) {\n try {\n process.kill(pid, 0);\n\n // Check we look at 'platforma' to not kill wrong process.\n const processName = getProcessName(pid);\n if (process.platform === 'win32') {\n return processName === 'platforma.exe'; // process name does not contain path to the file.\n }\n\n // Linux and Mac OS X behave differently (so can different Linux distributions).\n // Process name can contain original path to the binary file or just its name.\n return processName.endsWith('/platforma') || processName === 'platforma';\n } catch (_e) {\n return false;\n }\n}\n\nfunction getProcessName(pid: number): string {\n try {\n if (process.platform === 'win32') {\n // Windows: use tasklist command\n const output = execSync(`tasklist /FI \"PID eq ${pid}\" /FO CSV /NH`, { encoding: 'utf8' });\n const lines = output.trim().split('\\n');\n if (lines.length > 0 && lines[0].includes(',')) {\n const parts = lines[0].split(',');\n if (parts.length >= 1) {\n // Remove quotes and get the executable name\n const exeName = parts[0].replace(/^\"|\"$/g, '').trim();\n return exeName;\n }\n }\n } else {\n // Unix-like systems: use ps command\n const output = execSync(`ps -p ${pid} -o comm=`, { encoding: 'utf8' });\n const processName = output.trim();\n return processName;\n }\n } catch (_error) {\n // If we can't get the process name, return empty string\n return '';\n }\n return '';\n}\n\nexport function processStop(pid: number, force: boolean = false) {\n return process.kill(pid, force ? 'SIGKILL' : 'SIGINT');\n}\n\nexport async function processWaitStopped(pid: number, maxMs: number) {\n const sleepMs = 100;\n let total = 0;\n while (await isProcessAlive(pid)) {\n await sleep(sleepMs);\n total += sleepMs;\n if (total > maxMs) {\n throw new Error(`The process did not stopped after ${maxMs} ms.`);\n }\n }\n}\n"],"names":["spawn","execSync","sleep"],"mappings":";;;;;AAYM,SAAU,UAAU,CAAC,MAAgB,EAAE,IAAoB,EAAA;IAC/D,MAAM,CAAC,IAAI,CAAC,CAAA;AACP,KAAA,EAAA,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;AACzC,IAAA,EAAA,IAAI,CAAC,IAAI,CAAC,GAAG,CAAA,CAAE,CAAC;AAEpB,IAAA,MAAM,CAAC,IAAI,CAAC,0BAA0B,CAAC;AACvC,IAAA,OAAOA,wBAAK,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC;AAC9C;AAEA;AACO,eAAe,cAAc,CAAC,GAAW,EAAA;AAC9C,IAAA,IAAI;AACF,QAAA,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;;AAGpB,QAAA,MAAM,WAAW,GAAG,cAAc,CAAC,GAAG,CAAC;AACvC,QAAA,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;AAChC,YAAA,OAAO,WAAW,KAAK,eAAe,CAAC;QACzC;;;QAIA,OAAO,WAAW,CAAC,QAAQ,CAAC,YAAY,CAAC,IAAI,WAAW,KAAK,WAAW;IAC1E;IAAE,OAAO,EAAE,EAAE;AACX,QAAA,OAAO,KAAK;IACd;AACF;AAEA,SAAS,cAAc,CAAC,GAAW,EAAA;AACjC,IAAA,IAAI;AACF,QAAA,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;;AAEhC,YAAA,MAAM,MAAM,GAAGC,2BAAQ,CA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K,IAAI,OAAO;AAChB,QAAA,IAAI,KAAK,GAAG,KAAK,EAAE;AACjB,YAAA,MAAM,IAAI,KAAK,CAAC,qCAAqC,KAAK,CAAA,IAAA,CAAM,CAAC;QACnE;IACF;AACF;;;;;;;"}
@@ -7,6 +7,5 @@ export type ProcessOptions = {
7
7
  };
8
8
  export declare function processRun(logger: MiLogger, opts: ProcessOptions): ChildProcess;
9
9
  export declare function isProcessAlive(pid: number): Promise<boolean>;
10
- export declare function processStop(pid: number): true;
10
+ export declare function processStop(pid: number, force?: boolean): true;
11
11
  export declare function processWaitStopped(pid: number, maxMs: number): Promise<void>;
12
- //# sourceMappingURL=process.d.ts.map