@nsshunt/stsappframework 3.0.104 → 3.0.106

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 (124) hide show
  1. package/dist/influxdb/influxDBManager.js +16 -17
  2. package/dist/influxdb/influxDBManager.js.map +1 -1
  3. package/dist/influxdb/influxDBManagerAgent.js +9 -13
  4. package/dist/influxdb/influxDBManagerAgent.js.map +1 -1
  5. package/dist/influxdb/influxDBManagerBase.js +2 -6
  6. package/dist/influxdb/influxDBManagerBase.js.map +1 -1
  7. package/dist/influxdb/influxDBManagerService.js +10 -14
  8. package/dist/influxdb/influxDBManagerService.js.map +1 -1
  9. package/dist/instrumentationsubscriber.js +11 -15
  10. package/dist/instrumentationsubscriber.js.map +1 -1
  11. package/dist/kafka/IMKafkaManager.js +2 -6
  12. package/dist/kafka/IMKafkaManager.js.map +1 -1
  13. package/dist/kafkatesting/produce.js +1 -5
  14. package/dist/kafkatesting/produce.js.map +1 -1
  15. package/dist/processbase.js +7 -8
  16. package/dist/processbase.js.map +1 -1
  17. package/dist/server.js +1 -1
  18. package/dist/server.js.map +1 -1
  19. package/dist/tcpclient/app2.js +2 -2
  20. package/dist/tcpserver/appmaster.js +39 -16
  21. package/dist/tcpserver/appmaster.js.map +1 -1
  22. package/package.json +7 -7
  23. package/src/influxdb/influxDBManager.ts +16 -18
  24. package/src/influxdb/influxDBManagerAgent.ts +9 -11
  25. package/src/influxdb/influxDBManagerBase.ts +2 -4
  26. package/src/influxdb/influxDBManagerService.ts +10 -12
  27. package/src/instrumentationsubscriber.ts +11 -14
  28. package/src/kafka/IMKafkaManager.ts +2 -4
  29. package/src/kafkatesting/produce.ts +1 -3
  30. package/src/processbase.ts +7 -9
  31. package/src/server.ts +1 -1
  32. package/src/tcpclient/app2.ts +2 -2
  33. package/src/tcpserver/appmaster.ts +39 -17
  34. package/types/influxdb/influxDBManager.d.ts.map +1 -1
  35. package/types/influxdb/influxDBManagerAgent.d.ts.map +1 -1
  36. package/types/influxdb/influxDBManagerBase.d.ts.map +1 -1
  37. package/types/influxdb/influxDBManagerService.d.ts.map +1 -1
  38. package/types/instrumentationsubscriber.d.ts.map +1 -1
  39. package/types/kafka/IMKafkaManager.d.ts.map +1 -1
  40. package/types/processbase.d.ts +2 -2
  41. package/types/processbase.d.ts.map +1 -1
  42. package/types/tcpserver/appmaster.d.ts.map +1 -1
  43. package/src_working/authDefs.ts +0 -37
  44. package/src_working/authutilsnode.ts +0 -373
  45. package/src_working/commonTypes.ts +0 -239
  46. package/src_working/index.ts +0 -22
  47. package/src_working/influxdb/influxDBManager.ts +0 -970
  48. package/src_working/influxdb/influxDBManagerAgent.ts +0 -314
  49. package/src_working/influxdb/influxDBManagerBase.ts +0 -109
  50. package/src_working/influxdb/influxDBManagerService.ts +0 -373
  51. package/src_working/instrumentationsubscriber.ts +0 -283
  52. package/src_working/kafka/IMKafkaManager.ts +0 -152
  53. package/src_working/kafka/kafkaconsumer.ts +0 -82
  54. package/src_working/kafka/kafkamanager.ts +0 -186
  55. package/src_working/kafka/kafkaproducer.ts +0 -58
  56. package/src_working/kafkatesting/config.ts +0 -10
  57. package/src_working/kafkatesting/consume.ts +0 -116
  58. package/src_working/kafkatesting/produce.ts +0 -153
  59. package/src_working/masterprocessbase.ts +0 -598
  60. package/src_working/middleware/serverNetworkMiddleware.ts +0 -240
  61. package/src_working/network.ts +0 -36
  62. package/src_working/processbase.ts +0 -411
  63. package/src_working/processoptions.ts +0 -164
  64. package/src_working/publishertransports/publishTransportDirect.ts +0 -45
  65. package/src_working/publishertransports/publishTransportUtils.ts +0 -53
  66. package/src_working/server.ts +0 -141
  67. package/src_working/serverprocessbase.ts +0 -393
  68. package/src_working/singleprocessbase.ts +0 -121
  69. package/src_working/socketIoServerHelper.ts +0 -177
  70. package/src_working/stscontrollerbase.ts +0 -15
  71. package/src_working/stslatencycontroller.ts +0 -27
  72. package/src_working/stslatencyroute.ts +0 -16
  73. package/src_working/stsrouterbase.ts +0 -22
  74. package/src_working/tcpclient/app.ts +0 -19
  75. package/src_working/tcpclient/app2.ts +0 -56
  76. package/src_working/tcpserver/app.ts +0 -11
  77. package/src_working/tcpserver/appConfig.ts +0 -65
  78. package/src_working/tcpserver/appmaster.ts +0 -544
  79. package/src_working/validation/errors.ts +0 -6
  80. package/src_working/webworkertesting/app.ts +0 -49
  81. package/src_working/webworkertesting/worker.ts +0 -24
  82. package/src_working/workerprocessbase.test.ts +0 -47
  83. package/src_working/workerprocessbase.ts +0 -185
  84. package/src_working2/authDefs.ts +0 -37
  85. package/src_working2/authutilsnode.ts +0 -375
  86. package/src_working2/commonTypes.ts +0 -239
  87. package/src_working2/index.ts +0 -22
  88. package/src_working2/influxdb/influxDBManager.ts +0 -972
  89. package/src_working2/influxdb/influxDBManagerAgent.ts +0 -316
  90. package/src_working2/influxdb/influxDBManagerBase.ts +0 -111
  91. package/src_working2/influxdb/influxDBManagerService.ts +0 -375
  92. package/src_working2/instrumentationsubscriber.ts +0 -286
  93. package/src_working2/kafka/IMKafkaManager.ts +0 -154
  94. package/src_working2/kafka/kafkaconsumer.ts +0 -82
  95. package/src_working2/kafka/kafkamanager.ts +0 -186
  96. package/src_working2/kafka/kafkaproducer.ts +0 -58
  97. package/src_working2/kafkatesting/config.ts +0 -10
  98. package/src_working2/kafkatesting/consume.ts +0 -116
  99. package/src_working2/kafkatesting/produce.ts +0 -155
  100. package/src_working2/masterprocessbase.ts +0 -590
  101. package/src_working2/middleware/serverNetworkMiddleware.ts +0 -240
  102. package/src_working2/network.ts +0 -36
  103. package/src_working2/processbase.ts +0 -415
  104. package/src_working2/processoptions.ts +0 -164
  105. package/src_working2/publishertransports/publishTransportDirect.ts +0 -45
  106. package/src_working2/publishertransports/publishTransportUtils.ts +0 -53
  107. package/src_working2/server.ts +0 -141
  108. package/src_working2/serverprocessbase.ts +0 -393
  109. package/src_working2/singleprocessbase.ts +0 -123
  110. package/src_working2/socketIoServerHelper.ts +0 -177
  111. package/src_working2/stscontrollerbase.ts +0 -15
  112. package/src_working2/stslatencycontroller.ts +0 -27
  113. package/src_working2/stslatencyroute.ts +0 -16
  114. package/src_working2/stsrouterbase.ts +0 -22
  115. package/src_working2/tcpclient/app.ts +0 -19
  116. package/src_working2/tcpclient/app2.ts +0 -56
  117. package/src_working2/tcpserver/app.ts +0 -11
  118. package/src_working2/tcpserver/appConfig.ts +0 -65
  119. package/src_working2/tcpserver/appmaster.ts +0 -522
  120. package/src_working2/validation/errors.ts +0 -6
  121. package/src_working2/webworkertesting/app.ts +0 -49
  122. package/src_working2/webworkertesting/worker.ts +0 -24
  123. package/src_working2/workerprocessbase.test.ts +0 -47
  124. package/src_working2/workerprocessbase.ts +0 -187
@@ -1,240 +0,0 @@
1
- /* eslint @typescript-eslint/no-explicit-any: 0, @typescript-eslint/no-unused-vars: 0 */ // --> OFF
2
- import chalk from 'chalk'; // Note: Do NOT upgrade beyond 4.1.2 as the ESM version (5.0.0+) breaks this entire codebase
3
- import { Request, Response, NextFunction } from 'express'
4
- import { Socket } from 'node:net'
5
- import { TinyEmitter } from 'tiny-emitter';
6
-
7
- import debugModule from 'debug'
8
- import { STSOptionsBase } from '@nsshunt/stsutils';
9
- const debug = debugModule(`proc:${process.pid}`);
10
-
11
- import { v4 as uuidv4 } from 'uuid';
12
- import onHeaders from 'on-headers';
13
-
14
- export enum ServerNetworkMiddlewareEventName {
15
- UpdateInstrument_SERVER_NET_VAL = 'UpdateInstrument_SERVER_NET_VAL' // request net stats
16
- }
17
-
18
- export interface ISocketRecord {
19
- id: string
20
- socket: Socket,
21
- currentBytesRead: number
22
- currentBytesWritten: number
23
- lastBytesRead: number
24
- lastBytesWritten: number
25
- requestBytesRead: number
26
- requestBytesWritten: number
27
- originalUrl: string
28
- eventName: string
29
- }
30
-
31
- export type ServerNetworkMiddlewareEventFunc = (data: ISocketRecord) => void;
32
-
33
- export interface IServerNetworkMiddleware {
34
- name: string
35
- outputDebug: boolean
36
- }
37
-
38
- export class ServerNetworkMiddleware extends STSOptionsBase
39
- {
40
- #tinyEmitter: TinyEmitter = new TinyEmitter();
41
- #socketCollection: Record<string, ISocketRecord> = { };
42
- #id: string = '';
43
- #debug: any;
44
-
45
- constructor(options: IServerNetworkMiddleware) {
46
- super(options);
47
- if (options.outputDebug) {
48
- this.#debug = debug;
49
- } else {
50
- this.#debug = () => { };
51
- }
52
- }
53
-
54
- on(eventName: ServerNetworkMiddlewareEventName, callBackFn: ServerNetworkMiddlewareEventFunc) {
55
- this.#tinyEmitter.on(eventName, callBackFn);
56
- }
57
-
58
- GetSocketRecord = (socket: Socket): ISocketRecord | null => {
59
- for (const [, socketRecord] of Object.entries(this.#socketCollection)) {
60
- if (socketRecord.socket === socket) {
61
- return socketRecord;
62
- }
63
- }
64
- return null;
65
- }
66
-
67
- UpdateNetworkStats = (workingSocketRecord: ISocketRecord, eventName: string, req: Request) => {
68
- workingSocketRecord.originalUrl = req.originalUrl;
69
- workingSocketRecord.eventName = eventName;
70
-
71
- workingSocketRecord.currentBytesRead = req.socket.bytesRead;
72
- workingSocketRecord.currentBytesWritten = req.socket.bytesWritten;
73
-
74
- workingSocketRecord.requestBytesRead = workingSocketRecord.currentBytesRead - workingSocketRecord.lastBytesRead;
75
- workingSocketRecord.requestBytesWritten = workingSocketRecord.currentBytesWritten - workingSocketRecord.lastBytesWritten;
76
-
77
- //this.#debug(chalk.gray(`totalBytesRead: [${workingSocketRecord.id}] [${workingSocketRecord.originalUrl}] [${eventName}] [${workingSocketRecord.requestBytesRead}]`));
78
- //this.#debug(chalk.gray(`totalBytesWritten: [${workingSocketRecord.id}] [${workingSocketRecord.originalUrl}] [${eventName}] [${workingSocketRecord.requestBytesWritten}]`));
79
-
80
- const workingSocketEventRecord = { ...workingSocketRecord };
81
- delete (workingSocketEventRecord as any).socket;
82
- this.#debug(chalk.gray(`Sending event: [${JSON.stringify(workingSocketEventRecord)}]`));
83
- this.#tinyEmitter.emit(ServerNetworkMiddlewareEventName.UpdateInstrument_SERVER_NET_VAL, workingSocketEventRecord);
84
-
85
- workingSocketRecord.lastBytesRead = workingSocketRecord.currentBytesRead;
86
- workingSocketRecord.lastBytesWritten = workingSocketRecord.currentBytesWritten;
87
- }
88
-
89
- #GetRequestContentSize = (req: Request) => {
90
- try {
91
- let contentLength = 0;
92
- if ((req as any)['_contentLength']) {
93
- contentLength = (req as any)['_contentLength'];
94
- } else {
95
- if (req.headers['content-length']) {
96
- contentLength = parseInt(req.headers['content-length'])
97
- }
98
- }
99
- return contentLength;
100
- } catch (error) {
101
- this.#debug(chalk.red(`ServerNetworkMiddleware:#GetRequestContentSize(): Error: [${error}]`));
102
- return 0;
103
- }
104
- }
105
-
106
- Middleware = (req: Request, res: Response, next: NextFunction) => {
107
- let workingSocketRecord: ISocketRecord | null = null;
108
-
109
- workingSocketRecord = this.GetSocketRecord(req.socket);
110
-
111
- if (!workingSocketRecord) {
112
- this.#id = uuidv4();
113
- workingSocketRecord = {
114
- id: `${(this.options as IServerNetworkMiddleware).name}_${this.#id.toString()}`,
115
- socket: req.socket,
116
- currentBytesRead: 0,
117
- currentBytesWritten: 0,
118
- lastBytesRead: 0,
119
- lastBytesWritten: 0,
120
- requestBytesRead: 0,
121
- requestBytesWritten: 0,
122
- originalUrl: req.originalUrl,
123
- eventName: '',
124
- };
125
-
126
- this.#socketCollection[workingSocketRecord.id] = workingSocketRecord;
127
-
128
- this.#debug(chalk.gray(`Adding new socket to recordset: ID: [${workingSocketRecord.id}], originalUrl: [${workingSocketRecord.originalUrl}]`));
129
-
130
- workingSocketRecord.socket.on('data', () => {
131
- const socketRecord = this.GetSocketRecord((workingSocketRecord as ISocketRecord).socket);
132
- if (socketRecord) {
133
- this.#debug(chalk.gray(`Socket data event: ID: [${socketRecord.id}], originalUrl: [${socketRecord.originalUrl}]`));
134
- this.UpdateNetworkStats(socketRecord, 'socket_data', req);
135
- } else {
136
- this.#debug(chalk.magenta(`Socket data event: Could not find socket within recordset`));
137
- }
138
- });
139
-
140
- workingSocketRecord.socket.on('close', () => {
141
- const socketRecord = this.GetSocketRecord((workingSocketRecord as ISocketRecord).socket);
142
- if (socketRecord) {
143
- this.#debug(chalk.gray(`Socket close event: ID: [${socketRecord.id}], originalUrl: [${socketRecord.originalUrl}]`));
144
- this.UpdateNetworkStats(socketRecord, 'socket_close', req);
145
- delete this.#socketCollection[socketRecord.id];
146
- this.#debug(chalk.gray(`Socket removed from recordset: ID: [${socketRecord.id}], originalUrl: [${socketRecord.originalUrl}]`));
147
- } else {
148
- this.#debug(chalk.magenta(`Socket close event: Could not find socket within recordset`));
149
- }
150
- });
151
-
152
- workingSocketRecord.socket.on('end', () => {
153
- const socketRecord = this.GetSocketRecord((workingSocketRecord as ISocketRecord).socket);
154
- if (socketRecord) {
155
- this.#debug(chalk.gray(`Socket end event: ID: [${socketRecord.id}], originalUrl: [${socketRecord.originalUrl}]`));
156
- this.UpdateNetworkStats(socketRecord, 'socket_end', req);
157
- } else {
158
- this.#debug(chalk.magenta(`Socket end event: Could not find socket within recordset`));
159
- }
160
- });
161
- }
162
-
163
- // The following gets the payload size from adding _contentLength or content-length to the header size.
164
- // From brief observations, this appears to be about 80 bytes short from what is reported by the socket writtenBytes.
165
- onHeaders(res, () => {
166
- let contentLength = 0;
167
- if ((res as any)['_contentLength']) {
168
- contentLength = (res as any)['_contentLength'];
169
- } else {
170
- if (res.hasHeader('content-length')) {
171
- contentLength = parseInt(res.getHeader('content-length') as string);
172
- }
173
- }
174
-
175
- // Ensure that the client does NOT cache the response
176
- res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); // HTTP 1.1
177
- res.setHeader('Pragma', 'no-cache'); // HTTP 1.0
178
- res.setHeader('Expires', '0'); // Proxies
179
-
180
- const headerLength = JSON.stringify(res.getHeaders()).length;
181
- const totalSize = contentLength + headerLength;
182
-
183
- this.#debug(chalk.white.bgBlue(`contentLength: [${contentLength}], headerLength: [${headerLength}], total Size: [${totalSize}]`));
184
- });
185
-
186
- // This event is the one where bytesWritten is generally recorded
187
- req.on('end', () => {
188
- const socketRecord = this.GetSocketRecord(req.socket);
189
- if (socketRecord) {
190
- this.#debug(chalk.gray(`Request end event: ID: [${socketRecord.id}], originalUrl: [${socketRecord.originalUrl}]`))
191
- this.UpdateNetworkStats(socketRecord, 'req_end', req);
192
- } else {
193
- this.#debug(chalk.magenta(`Request end event: Could not find socket within recordset`));
194
- }
195
- });
196
-
197
- req.on('close', () => {
198
- const socketRecord = this.GetSocketRecord(req.socket);
199
- if (socketRecord) {
200
- this.#debug(chalk.gray(`Request close event: ID: [${socketRecord.id}], originalUrl: [${socketRecord.originalUrl}]`));
201
- this.UpdateNetworkStats(socketRecord, 'req_close', req);
202
- } else {
203
- this.#debug(chalk.magenta(`Request close event: Could not find socket within recordset`));
204
- }
205
- });
206
-
207
- /* These methods are also available but from testing they provide no specific value add, i.e. the calculated numbers are always 0.
208
- req.on('data', () => {
209
- workingSocketRecord = this.GetSocketRecord(req.socket);
210
- if (workingSocketRecord) {
211
- this.#debug(chalk.gray(`Request close event: ID: [${workingSocketRecord.id}], originalUrl: [${workingSocketRecord.originalUrl}]`));
212
- this.UpdateNetworkStats(workingSocketRecord, 'data', req);
213
- } else {
214
- this.#debug(chalk.magenta(`Request close event: Could not find socket within recordset`));
215
- }
216
- });
217
-
218
- req.on('readable', () => {
219
- workingSocketRecord = this.GetSocketRecord(req.socket);
220
- if (workingSocketRecord) {
221
- this.#debug(chalk.gray(`Request close event: ID: [${workingSocketRecord.id}], originalUrl: [${workingSocketRecord.originalUrl}]`));
222
- this.UpdateNetworkStats(workingSocketRecord, 'readable', req);
223
- } else {
224
- this.#debug(chalk.magenta(`Request close event: Could not find socket within recordset`));
225
- }
226
- });
227
- */
228
-
229
- const inHeadersLength = JSON.stringify(req.headers).length;
230
- const inContentLength = this.#GetRequestContentSize(req);
231
- const inTotal = inHeadersLength + inContentLength;
232
-
233
- this.#debug(chalk.white.bgGray(`inHeadersLength: [${inHeadersLength}], inContentLength: [${inContentLength}], inTotal: [${inTotal}]`));
234
-
235
- // This event is the one where bytesRead is generally recorded
236
- this.UpdateNetworkStats(workingSocketRecord, 'middleware', req);
237
-
238
- next();
239
- }
240
- }
@@ -1,36 +0,0 @@
1
- import os from 'os'
2
-
3
- export type NetworkInterfaces = Record<string, string[]>
4
-
5
- export function GetNetworkInterfaces(): NetworkInterfaces {
6
- const nets = os.networkInterfaces();
7
- const results: NetworkInterfaces = { };
8
- for (const name of Object.keys(nets)) {
9
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
- for (const net of nets[name] as any) {
11
- // Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
12
- if (net.family === 'IPv4' && !net.internal) {
13
- if (!results[name]) {
14
- results[name] = [];
15
- }
16
- results[name].push(net.address);
17
- }
18
- }
19
- }
20
- return results;
21
- }
22
-
23
- export function GetFirstNetworkInterface(): string | null {
24
- const nics: NetworkInterfaces = GetNetworkInterfaces();
25
- let hostaddr = null;
26
- for (const nic in nics)
27
- {
28
- const val: string[] = nics[nic];
29
- if (val.length > 0)
30
- {
31
- hostaddr = val[0];
32
- break;
33
- }
34
- }
35
- return hostaddr;
36
- }
@@ -1,415 +0,0 @@
1
- /* eslint @typescript-eslint/no-explicit-any: 0, @typescript-eslint/no-unused-vars: 0 */ // --> OFF
2
- import pidusage from 'pidusage'
3
- import { memoryUsage, exit } from 'process'
4
- import path from 'node:path';
5
- import cluster from 'node:cluster'
6
- import colors from 'colors'
7
- import si from 'systeminformation' // https://systeminformation.io/
8
- import { GetFirstNetworkInterface } from './network'
9
-
10
- import chalk from 'chalk';
11
-
12
- import debugModule from 'debug'
13
- const debug = debugModule(`proc:${process.pid}:processBase`);
14
-
15
- import { Gauge, InstrumentBaseTelemetry, InstrumentGaugeTelemetry, InstrumentObjectTelemetry, InstrumentLogTelemetry } from '@nsshunt/stsinstrumentation'
16
-
17
- import { PGAccessLayer, PGPoolManager, PGPoolManagerEventName } from '@nsshunt/stsdatamanagement'
18
-
19
- import { $Options } from '@nsshunt/stsconfig'
20
- const goptions = $Options()
21
-
22
- import { ProcessOptions, STSServerType } from './processoptions'
23
- import { STSOptionsBase, JSONObject } from '@nsshunt/stsutils'
24
- import { StatusCodes } from 'http-status-codes'
25
-
26
- import { PublishInstrumentControllerV2, IPublishInstrumentControllerOptionsV2, InstrumentDefinitions,
27
- IWorkerFactory, TransportType, IPublishTransportRESTServerOptions,
28
- CreateServiceProcessContext, PublishTransportRESTServerV2, IPublisherTransport } from '@nsshunt/stspublisherserver'
29
-
30
- //import { PublishCollectorInProcessWorkerFactory } from './processcollectorinprocessworker'
31
-
32
- import { Worker } from 'worker_threads';
33
-
34
- import os from 'os';
35
-
36
- import { IProcessBase, ISocketIoServerHelper, logFunction } from './commonTypes'
37
- import { TimeSeriesDuplicatePolicies } from 'redis';
38
-
39
- import { STSDefaultClientToServerEvents, STSDefaultServerToClientEvents } from '@nsshunt/stssocketio-client'
40
-
41
- //import ProcessBrokerWorker from './processbrokerworker.js?worker'
42
-
43
- import { PublishTransportDirect } from './publishertransports/publishTransportDirect'
44
-
45
- export abstract class ProcessBase extends STSOptionsBase implements IProcessBase
46
- {
47
- #instrumentController: PublishInstrumentControllerV2 | null = null;
48
- #systemInformationInterval: NodeJS.Timer | null = null;
49
- #socketIoServerHelper: ISocketIoServerHelper<STSDefaultClientToServerEvents, STSDefaultServerToClientEvents> | null = null;
50
- #accessLayer: PGAccessLayer | null = null;
51
- #poolManager: PGPoolManager | null = null;
52
- #logEx: logFunction | null = null;
53
-
54
- constructor(options: ProcessOptions)
55
- {
56
- super(options);
57
-
58
- if (options.serviceName) {
59
- this.options.serviceProcessContext = CreateServiceProcessContext(options.serviceName, options.serviceVersion, options.serviceInstanceId,
60
- os.hostname(), process.pid, options.isMaster ? process.pid : process.ppid)
61
- }
62
- }
63
-
64
- override get options(): ProcessOptions {
65
- return super.options as ProcessOptions;
66
- }
67
-
68
- get shuttingDown(): boolean {
69
- return false;
70
- }
71
-
72
- #log(appName: any): logFunction {
73
- return (msg) =>
74
- {
75
- let prefix = '';
76
- let col = null;
77
-
78
- if (cluster.isPrimary)
79
- {
80
- prefix = 'M';
81
- col = chalk.bold.cyan;
82
- //col = colors.bold.cyan; // chalk.bold.cyan;
83
- } else {
84
- prefix = 'W';
85
- col = chalk.green;
86
- //col = colors.green; // chalk.green;
87
- }
88
- const msgEx = col(`${prefix}(${process.pid}) [${appName}]: ${msg}`);
89
- debug(msgEx);
90
-
91
- this.UpdateInstrument(Gauge.LOGGER, {
92
- LogMessage: msgEx
93
- } as InstrumentLogTelemetry);
94
- };
95
- }
96
-
97
- #GetRootFolder = (): string => {
98
- const mainpath = require.resolve('@nsshunt/stsutils');
99
- const anotherDir = path.dirname(mainpath);
100
- const sSplit = anotherDir.split('/')
101
- const result = sSplit.slice(0, -5) // Remove the last 4 path elements, this will be 'node_modules/@nsshunt/stsutils/dist'
102
- return result.join('/');
103
- }
104
-
105
- #ServiceCollectorWorkerFactory: IWorkerFactory = {
106
- createWorker: (): Worker => {
107
- const fileName = this.#GetRootFolder() + '/stsappframework/dist/processcollectorworker.js';
108
-
109
- //@@ check for copy env like
110
- // const envCopy = { ...process.env };
111
- const publishCollectorWebWorker = new Worker(fileName, {
112
- workerData: 500 // ??
113
- // ,env: envCopy
114
- });
115
-
116
- publishCollectorWebWorker.unref();
117
-
118
- return publishCollectorWebWorker;
119
- },
120
- /*
121
- createInProcessWorker: (): PublishCollectorWorker => {
122
- return PublishCollectorInProcessWorkerFactory();
123
- },
124
- */
125
- options: {
126
- transportType: TransportType.RESTAPI,
127
- url: `${goptions.imendpoint}:${goptions.import}${goptions.imapiroot}/publishmessage`,
128
- publishdebug: goptions.publishdebug,
129
- // socketPath: '/var/run/sts/stsrest01.sock'
130
- agentOptions: {
131
- keepAlive: goptions.keepAlive,
132
- maxSockets: goptions.maxSockets,
133
- maxTotalSockets: goptions.maxTotalSockets,
134
- maxFreeSockets: goptions.maxFreeSockets,
135
- timeout: goptions.timeout,
136
- rejectUnauthorized: goptions.isProduction // Allows self signed certs in non production mode(s)
137
- }
138
- } as IPublishTransportRESTServerOptions
139
- }
140
-
141
- #ServiceBrokerWorkerFactory: IWorkerFactory = {
142
- createWorker: (): Worker => {
143
- const fileName = this.#GetRootFolder() + '/stsappframework/dist/processbrokerworker.js';
144
-
145
- //@@ check for copy env like
146
- // const envCopy = { ...process.env };
147
- const publishBrokerWebWorker = new Worker(fileName, {
148
- //workerData: this.options.serviceProcessContext
149
- // ,env: envCopy
150
- });
151
-
152
- publishBrokerWebWorker.unref();
153
-
154
- return publishBrokerWebWorker;
155
- }
156
- /*
157
- createInProcessWorker: (): PublishBrokerWorker => {
158
- return PublishBrokerInProcessWorkerFactory();
159
- },
160
- */
161
- }
162
-
163
- SetupInstrumentation()
164
- {
165
- if (!this.options.serviceProcessContext) {
166
- return;
167
- }
168
-
169
- let publisherTransport: IPublisherTransport
170
-
171
- if (goptions.observabilityPublishMode.localeCompare('PROXY') === 0) {
172
- const publishTransportOptions: IPublishTransportRESTServerOptions = {
173
- transportType: TransportType.RESTAPI,
174
- url: `${goptions.imendpoint}:${goptions.import}${goptions.imapiroot}/publishmessage`,
175
- publishdebug: goptions.publishdebug,
176
- // socketPath: '/var/run/sts/stsrest01.sock'
177
- agentOptions: {
178
- keepAlive: goptions.keepAlive,
179
- maxSockets: goptions.maxSockets,
180
- maxTotalSockets: goptions.maxTotalSockets,
181
- maxFreeSockets: goptions.maxFreeSockets,
182
- timeout: goptions.timeout,
183
- rejectUnauthorized: goptions.isProduction // Allows self signed certs in non production mode(s)
184
- }
185
- };
186
- publisherTransport = new PublishTransportRESTServerV2(publishTransportOptions);
187
- } else {
188
- publisherTransport = new PublishTransportDirect();
189
- }
190
-
191
- const instrumentControllerOptions: IPublishInstrumentControllerOptionsV2 = {
192
- processContext: this.options.serviceProcessContext,
193
- //payloadType: InstrumentPayloadType.service,
194
- consoleLogging: this.options.consoleLogging,
195
- instrumentLogging: this.options.instrumentLogging,
196
- httpServer: (this.options.serverType === STSServerType.EXPRESS || this.options.serverType === STSServerType.EXPRESS_TLS),
197
- instrumentationObservationInterval: this.options.instrumentationObservationInterval,
198
- instrumentationTimeWindow: this.options.instrumentationTimeWindow,
199
- instrumentDefinitions: this.GetAdditionalInstruments(),
200
- publisherTransport
201
- }
202
-
203
- this.#instrumentController = new PublishInstrumentControllerV2(instrumentControllerOptions);
204
- }
205
-
206
- GetAdditionalInstruments(): InstrumentDefinitions {
207
- return [ ];
208
- }
209
-
210
- CollectAdditionalTelemetry(): void { // eslint-disable @typescript-eslint/no-empty-function
211
-
212
- }
213
-
214
- ProcessStartup = () =>
215
- {
216
- // use this as well
217
- // performance.eventLoopUtilization([utilization1[, utilization2]])
218
- // https://nodejs.org/api/perf_hooks.html#perf_hooksmonitoreventloopdelayoptions
219
- this.#systemInformationInterval = setInterval(() => {
220
- pidusage(process.pid, (err, stats) => {
221
-
222
- if (this.#instrumentController) {
223
- this.#instrumentController.UpdateInstrument(Gauge.CPU_LOAD_GAUGE, {
224
- val: stats.cpu
225
- } as InstrumentGaugeTelemetry);
226
- }
227
- });
228
-
229
- // https://nodejs.org/api/process.html#processmemoryusage
230
- const usage = memoryUsage();
231
- const telemetry: JSONObject = {
232
- r: usage.rss,
233
- t: usage.heapTotal,
234
- u: usage.heapUsed,
235
- x: usage.external,
236
- a: usage.arrayBuffers,
237
- }
238
-
239
- this.UpdateInstrument(Gauge.OBJECT_GAUGE, {
240
- val: telemetry
241
- } as InstrumentObjectTelemetry);
242
-
243
- this.CollectAdditionalTelemetry();
244
-
245
- }, goptions.systemInformationInterval).unref();
246
-
247
- this.#logEx = this.#log(this.options.serviceName);
248
-
249
- if (this.options.useDatabase) {
250
- // Get the accessLayer to force DB connection test
251
- this.accessLayer;
252
- }
253
- }
254
-
255
- UpdateInstrument = (instrumentName: Gauge, telemetry: InstrumentBaseTelemetry) => {
256
- if (this.#instrumentController) {
257
- this.#instrumentController.UpdateInstrument(instrumentName, telemetry);
258
- }
259
- }
260
-
261
- get InstrumentController(): PublishInstrumentControllerV2 | null {
262
- return this.#instrumentController;
263
- }
264
-
265
- LogEx = (message: any) => {
266
- if (this.#logEx) {
267
- this.#logEx(message);
268
- } else {
269
- console.log('')
270
- console.log('************* Attempt to log before _logex set ***************')
271
- console.log(message)
272
- console.log('')
273
- }
274
- }
275
-
276
- InstrumentExists(instrumentName: Gauge): boolean
277
- {
278
- if (this.#instrumentController) {
279
- return this.#instrumentController.InstrumentExists(instrumentName);
280
- }
281
- return false;
282
- }
283
-
284
- ProcessTerminate = async () =>
285
- {
286
- if (this.#systemInformationInterval) {
287
- clearInterval(this.#systemInformationInterval);
288
- }
289
- this.#systemInformationInterval = null;
290
- }
291
-
292
- /**
293
- * UIController (instance of UIController) to manage a console based user interface associated for this node application.
294
- * @returns UIController instance to manage a console based user interface associated for this node application.
295
- */
296
- GetUIController(): any {
297
- return null;
298
- }
299
-
300
- get socketIoServerHelper(): ISocketIoServerHelper<STSDefaultClientToServerEvents, STSDefaultServerToClientEvents> | null
301
- {
302
- return this.#socketIoServerHelper;
303
- }
304
-
305
- set socketIoServerHelper(value: ISocketIoServerHelper<STSDefaultClientToServerEvents, STSDefaultServerToClientEvents> | null)
306
- {
307
- this.#socketIoServerHelper = value;
308
- }
309
-
310
- #UpdatePGPoolManagerInstrument = (data: any) => {
311
- this.UpdateInstrument(Gauge.CONNECTION_POOL_TOTAL_GAUGE, {
312
- val: data.totalCount
313
- } as InstrumentGaugeTelemetry);
314
-
315
- this.UpdateInstrument(Gauge.CONNECTION_POOL_IDLE_GAUGE, {
316
- val: data.idleCount
317
- } as InstrumentGaugeTelemetry);
318
-
319
- this.UpdateInstrument(Gauge.CONNECTION_POOL_WAITING_GAUGE, {
320
- val: data.waitingCount
321
- } as InstrumentGaugeTelemetry);
322
- }
323
-
324
- async TerminateDatabase() {
325
- if (this.#accessLayer && this.#poolManager) {
326
- this.#poolManager.off(PGPoolManagerEventName.UpdateInstruments, this.#UpdatePGPoolManagerInstrument)
327
- await this.#accessLayer.enddatabase();
328
- }
329
- }
330
-
331
- get accessLayer(): PGAccessLayer | null
332
- {
333
- if (this.options.useDatabase) {
334
- if (this.#accessLayer === null) {
335
- this.#poolManager = new PGPoolManager();
336
- this.#accessLayer = new PGAccessLayer(this.#poolManager);
337
- (async () => {
338
- try {
339
- const retVal = await (this.accessLayer as PGAccessLayer).getResourceCount();
340
- if (retVal.status !== StatusCodes.OK) {
341
- this.LogEx(chalk.red(`Unable to get resources from the database. Is the database running? [${JSON.stringify(retVal)}]`));
342
- exit(1);
343
- } else {
344
- this.LogEx(chalk.green(`Database connection successful. Resources: [${retVal.detail.count}]`));
345
- }
346
- } catch (error) {
347
- this.LogEx(chalk.red(`Unable to get resources from the database. Is the database running? Error: [${error}]`));
348
- exit(1);
349
- }
350
- })();
351
- this.#poolManager.on(PGPoolManagerEventName.UpdateInstruments, this.#UpdatePGPoolManagerInstrument)
352
- }
353
- return this.#accessLayer;
354
- }
355
- return null;
356
- }
357
-
358
- GetNumCPUs = async (): Promise<number> => {
359
- // https://systeminformation.io/
360
- const valueObject = {
361
- cpu: '*'
362
- }
363
-
364
- const sysinfo = await si.get(valueObject);
365
- let numCPUs = 2;
366
- if (goptions.useCPUs > 0) {
367
- if (goptions.useCPUs >= 1) {
368
- numCPUs = goptions.useCPUs;
369
- } else {
370
- numCPUs = Math.round(sysinfo.cpu.cores * goptions.useCPUs);
371
- }
372
- } else {
373
- numCPUs = sysinfo.cpu.physicalCores;
374
- }
375
- return numCPUs;
376
- }
377
-
378
- LogSystemTelemetry = async () => {
379
- // https://systeminformation.io/
380
- const valueObject = {
381
- system: '*',
382
- osInfo: '*',
383
- cpu: '*',
384
- mem: '*'
385
- }
386
-
387
- const sysinfo = await si.get(valueObject);
388
- const numCPUs = await this.GetNumCPUs();
389
- const hostname = sysinfo.osInfo.hostname;
390
-
391
- const hostaddr = GetFirstNetworkInterface();
392
- if (hostaddr !== null) {
393
- this.LogEx(`Host Address: ${hostaddr}`);
394
- } else {
395
- this.LogEx(`Unknown Host Address.`);
396
- }
397
- this.LogEx(`Server starting with ${numCPUs} Cores/Threads`);
398
-
399
- this.LogEx(`Hostname: ${hostname}`);
400
- this.LogEx(`System: ${JSON.stringify(sysinfo.system)}`);
401
- this.LogEx(`OS Info: ${JSON.stringify(sysinfo.osInfo)}`);
402
- this.LogEx(`CPU: ${JSON.stringify(sysinfo.cpu)}`);
403
- this.LogEx(`Memory: ${JSON.stringify(sysinfo.mem)}`);
404
- }
405
-
406
- GetSignalColour = (signal: any) => {
407
- let msgcolor = null;
408
- if (signal === 'SIGINT') {
409
- msgcolor = chalk.yellow;
410
- } else {
411
- msgcolor = chalk.red;
412
- }
413
- return msgcolor;
414
- };
415
- }