@nsshunt/stsappframework 3.0.104 → 3.0.105

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