@nsshunt/stsappframework 3.0.103 → 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 +8 -10
  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 -11
  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_new/authDefs.ts +0 -37
  60. package/src_new/authutilsnode.ts +0 -375
  61. package/src_new/commonTypes.ts +0 -239
  62. package/src_new/index.ts +0 -22
  63. package/src_new/influxdb/influxDBManager.ts +0 -972
  64. package/src_new/influxdb/influxDBManagerAgent.ts +0 -316
  65. package/src_new/influxdb/influxDBManagerBase.ts +0 -111
  66. package/src_new/influxdb/influxDBManagerService.ts +0 -375
  67. package/src_new/instrumentationsubscriber.ts +0 -286
  68. package/src_new/kafka/IMKafkaManager.ts +0 -154
  69. package/src_new/kafka/kafkaconsumer.ts +0 -82
  70. package/src_new/kafka/kafkamanager.ts +0 -186
  71. package/src_new/kafka/kafkaproducer.ts +0 -58
  72. package/src_new/kafkatesting/config.ts +0 -10
  73. package/src_new/kafkatesting/consume.ts +0 -116
  74. package/src_new/kafkatesting/produce.ts +0 -155
  75. package/src_new/masterprocessbase.ts +0 -590
  76. package/src_new/middleware/serverNetworkMiddleware.ts +0 -240
  77. package/src_new/network.ts +0 -36
  78. package/src_new/processbase.ts +0 -413
  79. package/src_new/processoptions.ts +0 -164
  80. package/src_new/publishertransports/publishTransportDirect.ts +0 -45
  81. package/src_new/publishertransports/publishTransportUtils.ts +0 -53
  82. package/src_new/server.ts +0 -141
  83. package/src_new/serverprocessbase.ts +0 -393
  84. package/src_new/singleprocessbase.ts +0 -123
  85. package/src_new/socketIoServerHelper.ts +0 -177
  86. package/src_new/stscontrollerbase.ts +0 -15
  87. package/src_new/stslatencycontroller.ts +0 -27
  88. package/src_new/stslatencyroute.ts +0 -16
  89. package/src_new/stsrouterbase.ts +0 -22
  90. package/src_new/tcpclient/app.ts +0 -19
  91. package/src_new/tcpclient/app2.ts +0 -56
  92. package/src_new/tcpserver/app.ts +0 -11
  93. package/src_new/tcpserver/appConfig.ts +0 -65
  94. package/src_new/tcpserver/appmaster.ts +0 -522
  95. package/src_new/validation/errors.ts +0 -6
  96. package/src_new/webworkertesting/app.ts +0 -49
  97. package/src_new/webworkertesting/worker.ts +0 -24
  98. package/src_new/workerprocessbase.test.ts +0 -47
  99. package/src_new/workerprocessbase.ts +0 -187
  100. package/src_working/authDefs.ts +0 -37
  101. package/src_working/authutilsnode.ts +0 -373
  102. package/src_working/commonTypes.ts +0 -239
  103. package/src_working/index.ts +0 -22
  104. package/src_working/influxdb/influxDBManager.ts +0 -970
  105. package/src_working/influxdb/influxDBManagerAgent.ts +0 -314
  106. package/src_working/influxdb/influxDBManagerBase.ts +0 -109
  107. package/src_working/influxdb/influxDBManagerService.ts +0 -373
  108. package/src_working/instrumentationsubscriber.ts +0 -283
  109. package/src_working/kafka/IMKafkaManager.ts +0 -152
  110. package/src_working/kafka/kafkaconsumer.ts +0 -82
  111. package/src_working/kafka/kafkamanager.ts +0 -186
  112. package/src_working/kafka/kafkaproducer.ts +0 -58
  113. package/src_working/kafkatesting/config.ts +0 -10
  114. package/src_working/kafkatesting/consume.ts +0 -116
  115. package/src_working/kafkatesting/produce.ts +0 -153
  116. package/src_working/masterprocessbase.ts +0 -598
  117. package/src_working/middleware/serverNetworkMiddleware.ts +0 -240
  118. package/src_working/network.ts +0 -36
  119. package/src_working/processbase.ts +0 -411
  120. package/src_working/processoptions.ts +0 -164
  121. package/src_working/publishertransports/publishTransportDirect.ts +0 -45
  122. package/src_working/publishertransports/publishTransportUtils.ts +0 -53
  123. package/src_working/server.ts +0 -141
  124. package/src_working/serverprocessbase.ts +0 -393
  125. package/src_working/singleprocessbase.ts +0 -121
  126. package/src_working/socketIoServerHelper.ts +0 -177
  127. package/src_working/stscontrollerbase.ts +0 -15
  128. package/src_working/stslatencycontroller.ts +0 -27
  129. package/src_working/stslatencyroute.ts +0 -16
  130. package/src_working/stsrouterbase.ts +0 -22
  131. package/src_working/tcpclient/app.ts +0 -19
  132. package/src_working/tcpclient/app2.ts +0 -56
  133. package/src_working/tcpserver/app.ts +0 -11
  134. package/src_working/tcpserver/appConfig.ts +0 -65
  135. package/src_working/tcpserver/appmaster.ts +0 -544
  136. package/src_working/validation/errors.ts +0 -6
  137. package/src_working/webworkertesting/app.ts +0 -49
  138. package/src_working/webworkertesting/worker.ts +0 -24
  139. package/src_working/workerprocessbase.test.ts +0 -47
  140. package/src_working/workerprocessbase.ts +0 -185
@@ -1,522 +0,0 @@
1
- /* eslint @typescript-eslint/no-explicit-any: 0, @typescript-eslint/no-unused-vars: 0 */ // --> OFF
2
- import fs from "fs"
3
- import crypto from 'crypto';
4
- import jayson from 'jayson'
5
- import net from 'node:net'
6
- import tls from 'node:tls'
7
-
8
- import { JSONObject } from '@nsshunt/stsutils';
9
- import { MasterProcessBase } from './../masterprocessbase'
10
- import { ProcessOptions } from './../processoptions'
11
-
12
- import chalk from 'chalk';
13
-
14
- // Colour codes
15
- // ---------------------------------
16
- // Red - Error
17
- // Green - Vote YES
18
- // Yellow - Vote No
19
- // White - standard logging message
20
- // Magenta - node state change
21
- // Cyan - node term change
22
-
23
- export enum AppMasterRAFTState {
24
- IDLE = "IDLE",
25
- FOLLOWER = "FOLLOWER",
26
- CANDIDATE = "CANDIDATE",
27
- LEADER = "LEADER"
28
- }
29
-
30
- export interface IServiceDetail {
31
- host: string
32
- port: number
33
- }
34
-
35
- export interface ILogItem {
36
- term: number
37
- index: number
38
- data: JSONObject | null
39
- }
40
-
41
- export class AppMaster extends MasterProcessBase
42
- {
43
- #lastRequiredVotes = -1; // used for logging only
44
- #lastVotes = -1; // used for logging only
45
- #RAFTState: AppMasterRAFTState;
46
- #minElectionTimeout: number;
47
- #maxElectionTimeout: number;
48
- #electionTimeout: number;
49
- #heartBeatTimeout: number;
50
- #startRAFTProtocolTimeout: number;
51
- #votes: JSONObject; // keyed by service key (host:port)
52
- #services: IServiceDetail[];
53
- #thisService: IServiceDetail;
54
- #canidateTimeout: NodeJS.Timeout | null = null;
55
- #appendEntriesTimeout: NodeJS.Timeout | null = null;
56
- #voteRegister = 0;
57
- #server?: jayson.TlsServer;
58
- #serverPort: number;
59
- #votedLog: JSONObject = { }; // keyed by term number
60
- #appendedEntries: JSONObject = { };
61
- #leaderNode: IServiceDetail | null = null;
62
-
63
- #currentTerm: number;
64
- #log: ILogItem[];
65
- #currentIndex = 0;
66
-
67
- constructor(serviceConfig: ProcessOptions)
68
- {
69
- super(serviceConfig);
70
- this.#RAFTState = AppMasterRAFTState.IDLE;
71
- this.#currentTerm = 0;
72
- this.#votes = { };
73
- this.#services = [{
74
- host: "stscore.stsmda.org",
75
- port: 3006
76
- }, {
77
- host: "stscore.stsmda.org",
78
- port: 3007
79
- }, {
80
- host: "stscore.stsmda.org",
81
- port: 3008
82
- }]
83
-
84
- this.#thisService = this.#services[parseInt(process.env.SERVICE_INDEX as string)]; // set self service
85
- this.#serverPort = this.#thisService.port;
86
-
87
- //this.#thisService = this.#services[0]; // set self service
88
- this.#log = [ ]; // Need to get from storage - volume, redis, etc.
89
-
90
- // Set default config items
91
- this.#minElectionTimeout = 1000; //@@ config
92
- this.#maxElectionTimeout = 1200; //@@ config
93
- this.#startRAFTProtocolTimeout = 2000; //@@ config
94
- this.#electionTimeout = crypto.randomInt(this.#minElectionTimeout, this.#maxElectionTimeout);
95
- this.#heartBeatTimeout = 750; //@@ config - also must be smaller than electionTimeout
96
- }
97
-
98
- #GetTLSOptions = (): JSONObject => {
99
- return {
100
- key: fs.readFileSync(this.options.httpsServerKeyPath),
101
- cert: fs.readFileSync(this.options.httpsServerCertificatePath)
102
- };
103
- }
104
-
105
- #SetupRPCServer = async (socket: net.Socket): Promise<void> => {
106
- console.log('CONNECTED: ' + socket.remoteAddress + ':' + socket.remotePort + ' ' + process.pid);
107
-
108
- socket.on('close', function(data: any) {
109
- console.log('CLOSED: ' + socket.remoteAddress + ' ' + socket.remotePort + ' ' + process.pid);
110
- });
111
-
112
- socket.on('data', function(data: any) {
113
- console.log('DATA ' + socket.remoteAddress + ': ' + data);
114
- });
115
- }
116
-
117
- #GetLogPrefix = () => {
118
- return `${this.#thisService.host}:${this.#thisService.port}: currentTerm: [${this.#currentTerm}] index: [${this.#currentIndex}]: `;
119
- }
120
-
121
- #VoteYes = (callback: any, term: number, message: string) => {
122
- // Log the fact that I have now voted for this currentTerm
123
- this.#votedLog[term] = true;
124
- // Update my currentTerm
125
- this.#currentTerm = term;
126
- // Return my yes vote
127
- console.log(chalk.green(`${message} - Vote Yes`));
128
- callback(null, true); // YES vote
129
- }
130
-
131
- #VoteNo = (callback: any, term: number, message: string) => {
132
- // Log the fact that I have now voted for this currentTerm
133
- this.#votedLog[term] = true;
134
- // Return my yes vote
135
- console.log(chalk.yellow(`${message} - Vote No`));
136
- callback(null, false); // NO vote
137
- }
138
-
139
- #FindService = (host: string, port: number): IServiceDetail | null => {
140
- let retService = null;
141
- this.#services.forEach((service, index) => {
142
- if (service.host.localeCompare(host) === 0 && service.port === port) {
143
- retService = service;
144
- return;
145
- }
146
- });
147
- return retService;
148
- }
149
-
150
- #CheckMoreRecentTerm = (term: number, lastLogItemTerm: number, lastLogItemIndex: number) => {
151
- // Check if the request to vote is newer than my current term
152
- let msg = '';
153
- let retVal: boolean;
154
- if (term > this.#currentTerm) {
155
-
156
- msg = `${this.#GetLogPrefix()}: canidate term: [${term}] greater than my currentTerm: [${this.#currentTerm}]`;
157
- retVal = true;
158
- } else {
159
- // Check if the request to vote is older than my current term
160
- if (term === this.#currentTerm) {
161
- if (lastLogItemIndex > this.#currentIndex) {
162
- msg = `${this.#GetLogPrefix()}: canidate term: [${term}] the same as my currentTerm: [${this.#currentTerm}]. Canidate index: [${lastLogItemIndex}] greater than my index: [${this.#currentIndex}]`;
163
- retVal = true;
164
- } else if (lastLogItemIndex === this.#currentIndex) {
165
- msg = `${this.#GetLogPrefix()}: canidate term: [${term}] the same as my currentTerm: [${this.#currentTerm}]. Canidate index: [${lastLogItemIndex}] the same as my index: [${this.#currentIndex}]`;
166
- retVal = true;
167
- } else {
168
- msg = `${this.#GetLogPrefix()}: canidate term: [${term}] the same as my currentTerm: [${this.#currentTerm}]. Canidate index: [${lastLogItemIndex}] NOT greater than my index: [${this.#currentIndex}]`;
169
- retVal = false;
170
- }
171
- } else {
172
- msg = `${this.#GetLogPrefix()}: canidate term: [${term}] less than my currentTerm: [${this.#currentTerm}]`;
173
- retVal = false;
174
- }
175
- }
176
- return {
177
- msg,
178
- retVal
179
- }
180
- }
181
-
182
- #SetupJSONRPCServer = async (): Promise<jayson.TlsServer> => {
183
- const jaysonServer = new jayson.server();
184
-
185
- jaysonServer.method("appendEntries", async (args: any, callback: any) => {
186
- // Just received a message - reset my electionTimeout
187
- this.#ResetElectionTimeout();
188
-
189
- // Do something with this new log entry
190
-
191
- // Needs to check if current, otherwise get old entries and duplicate
192
-
193
- });
194
-
195
- jaysonServer.method("vote", async (args: any, callback: any) => {
196
- // Just received a message - reset my electionTimeout
197
- this.#ResetElectionTimeout();
198
-
199
- const term = args[0];
200
- const lastLogItemTerm = args[1];
201
- const lastLogItemIndex = args[2];
202
-
203
- // Now determine whether this requestror gets my vote
204
-
205
- // Check already voted
206
- if (this.#votedLog[term]) {
207
- this.#VoteNo(callback, term, `${this.#GetLogPrefix()}: Already voted - vote NO`)
208
- return;
209
- }
210
-
211
- // Check if the request to vote is newer than my current term
212
- const retVal = this.#CheckMoreRecentTerm(term, lastLogItemTerm, lastLogItemIndex);
213
- if (retVal.retVal === true) {
214
- this.#VoteYes(callback, term, retVal.msg);
215
- } else {
216
- this.#VoteNo(callback, term, retVal.msg);
217
- }
218
- });
219
-
220
- jaysonServer.method("appendEntry", async (args: any, callback: any) => {
221
- // Just received a message - reset my electionTimeout
222
- this.#ResetElectionTimeout();
223
-
224
- const host = args[0];
225
- const port = args[1];
226
- const term = args[2];
227
- const lastLogItemTerm = args[3];
228
- const lastLogItemIndex = args[4];
229
-
230
- if (this.#RAFTState.localeCompare(AppMasterRAFTState.CANDIDATE) === 0) {
231
- const retVal = this.#CheckMoreRecentTerm(term, lastLogItemTerm, lastLogItemIndex);
232
- if (retVal.retVal === true) {
233
- console.log(`${retVal.msg}`);
234
- console.log(chalk.magenta(`${this.#GetLogPrefix()}: New leader detected, Host: [${host}], Port: [${port}], while in CANDIDATE mode, reverting to FOLLOWER.`));
235
- // This sending node is the leader so revert to follower
236
- this.#currentTerm = term;
237
- this.#ChangeState(AppMasterRAFTState.FOLLOWER);
238
- } else {
239
- console.log(`${retVal.msg}`);
240
- console.log(chalk.magenta(`${this.#GetLogPrefix()}: appendEntry called but log is older than my current state, Host: [${host}], Port: [${port}].`));
241
- // Reject this RPC and continue in the CANDIDATE state
242
- callback(null, false);
243
- return;
244
- }
245
- } else if (this.#RAFTState.localeCompare(AppMasterRAFTState.LEADER) === 0) {
246
- console.log(chalk.red(`${this.#GetLogPrefix()}: appendEntry called while I am the current leader, rejecting RPC call.`));
247
- // Reject this RPC and continue in the LEADER state
248
- callback(null, false);
249
- return;
250
- } else {
251
- // FOLLOWER or IDLE
252
- if (this.#RAFTState.localeCompare(AppMasterRAFTState.IDLE) === 0) {
253
- this.#ChangeState(AppMasterRAFTState.FOLLOWER);
254
- }
255
- const retVal = this.#CheckMoreRecentTerm(term, lastLogItemTerm, lastLogItemIndex);
256
- if (retVal.retVal === true) {
257
- if (term > this.#currentTerm) {
258
- console.log(`${retVal.msg}`.cyan);
259
- this.#currentTerm = term;
260
- }
261
- } else {
262
- console.log(`${retVal.msg}`);
263
- console.log(chalk.magenta(`${this.#GetLogPrefix()}: appendEntry called but log is older than my current state, Host: [${host}], Port: [${port}].`));
264
- // Reject this RPC and continue in the CANDIDATE state
265
- callback(null, false);
266
- return;
267
- }
268
- }
269
-
270
- if (this.#leaderNode) {
271
- const sentLeaderService = this.#FindService(host, port);
272
- if (sentLeaderService) {
273
- if (sentLeaderService.host.localeCompare(this.#leaderNode.host) !== 0 || sentLeaderService.port !== this.#leaderNode.port) {
274
- this.#leaderNode = sentLeaderService;
275
- console.log(chalk.white(`${this.#GetLogPrefix()}: Leader Service: Host:[${this.#leaderNode.host}] Port: [${this.#leaderNode.port}]`));
276
- }
277
- }
278
- } else {
279
- this.#leaderNode = this.#FindService(host, port);
280
- if (this.#leaderNode) {
281
- console.log(chalk.white(`${this.#GetLogPrefix()}: Leader Service: Host:[${this.#leaderNode.host}] Port: [${this.#leaderNode.port}]`));
282
- }
283
- }
284
-
285
- // Now update the log if only more recent
286
- callback(null, true);
287
- });
288
-
289
- jaysonServer.method("ping", async function(args: any, callback: any) {
290
- // do something, do nothing
291
- console.log('server got ping');
292
- callback();
293
- });
294
-
295
- const server = jaysonServer.tls(this.#GetTLSOptions());
296
- //(server as tls.Server).on('secureConnection', this.#SetupRPCServer);
297
- //server.listen(this.options.listenPort, () => { // 'stscore.stsmda.org'
298
- server.listen(this.#serverPort, () => { // 'stscore.stsmda.org'
299
- console.log('JSON RPC 2.0 Server is running on port ' + this.options.listenPort + '.');
300
- }).on('listening', () =>
301
- {
302
- this.LogEx(`JSON RPC 2.0 live on ${this.options.endpoint}:${this.options.listenPort}${this.options.apiRoot}`);
303
- });
304
- return server;
305
- }
306
-
307
- #RequestVote = (service: IServiceDetail) => {
308
- const options: jayson.TcpClientOptions = {
309
- port: service.port,
310
- host: service.host
311
- };
312
-
313
- const client = jayson.client.tls(options);
314
-
315
- let lastLogItem: ILogItem;
316
- if (this.#log.length > 0) {
317
- lastLogItem = this.#log[this.#log.length-1];
318
- } else {
319
- lastLogItem = {
320
- term: 0,
321
- index: 0,
322
- data: null
323
- }
324
- }
325
-
326
- client.request('vote', [ this.#currentTerm, lastLogItem.term, lastLogItem.index ], (error: any, response: any) => {
327
- if (error) {
328
- //console.log(chalk.red(`vote attempt fail: [${JSON.stringify(options)}: ${error}]`));
329
- } else {
330
- // Log the result
331
- if (response.result === true) {
332
- this.#votes[this.#GetServiceKey(service)] = 1;
333
- }
334
- this.#CheckMajority();
335
- }
336
- });
337
- }
338
-
339
- #AppendEntry = (service: IServiceDetail) => {
340
- const options: jayson.TcpClientOptions = {
341
- port: service.port,
342
- host: service.host
343
- };
344
-
345
- const client = jayson.client.tls(options);
346
-
347
- let lastLogItem: ILogItem;
348
- if (this.#log.length > 0) {
349
- lastLogItem = this.#log[this.#log.length-1];
350
- } else {
351
- lastLogItem = {
352
- term: 0,
353
- index: 0,
354
- data: null
355
- }
356
- }
357
-
358
- client.request('appendEntry', [ this.#thisService.host, this.#thisService.port, this.#currentTerm, lastLogItem.term, lastLogItem.index ], (error: any, response: any) => {
359
- if (error) {
360
- //console.log(chalk.red(`appendEntry attempt fail: [${JSON.stringify(options)}: ${error}]`));
361
- } else {
362
- this.#appendedEntries[this.#GetServiceKey(service)] = 1;
363
- // Log the result
364
- /*
365
- if (response.result === true) {
366
- this.#votes[this.#GetServiceKey(service)] = 1;
367
- }
368
- */
369
- }
370
- });
371
- }
372
-
373
- #AppendEntries = () => {
374
- // Reset all appendEntries for this iteration
375
- this.#appendedEntries = { };
376
-
377
- // Reset all votes
378
- this.#services.forEach((service, index) => {
379
- this.#appendedEntries[this.#GetServiceKey(service)] = 0;
380
- });
381
-
382
- // Request vote for all other services - include my logs current item
383
- this.#services.forEach((service, index) => {
384
- if (service.host.localeCompare(this.#thisService.host) === 0 && service.port === this.#thisService.port) {
385
- // Myself
386
- this.#ResetElectionTimeout();
387
- this.#appendedEntries[this.#GetSelfServiceKey()] = 1;
388
- } else {
389
- // Send vote request
390
- this.#AppendEntry(service);
391
- }
392
- });
393
- }
394
-
395
- #GetServiceKey = (service: IServiceDetail) => {
396
- return `${service.host}:${service.port}`;
397
- }
398
-
399
- #GetSelfServiceKey = () => {
400
- return this.#GetServiceKey(this.#thisService);
401
- }
402
-
403
- // set interval ???
404
- #StartAppendEntries = () => {
405
- this.#AppendEntries();
406
- this.#appendEntriesTimeout = setTimeout(() => {
407
- // Now check if we still have majority
408
- const majority: boolean = this.#CheckMajorityWithCollection(this.#appendedEntries);
409
- if (majority) {
410
- this.#StartAppendEntries();
411
- } else {
412
- console.log(chalk.red(`${this.#GetLogPrefix()}: Not enough response for valid cluster state.`));
413
- }
414
- }, this.#heartBeatTimeout);
415
- }
416
-
417
- #Promote = () => {
418
- this.#ChangeState(AppMasterRAFTState.LEADER);
419
- console.log(chalk.green(`${this.#GetLogPrefix()}: New LEADER is elected: [${this.#GetSelfServiceKey()}]`));
420
- // As leader, now start the regular pings
421
- this.#StartAppendEntries();
422
- }
423
-
424
- #CheckMajority = () => {
425
- if (this.#CheckMajorityWithCollection(this.#votes)) {
426
- this.#Promote();
427
- }
428
- }
429
-
430
- #CheckMajorityWithCollection = (col: JSONObject): boolean => {
431
- let votes = 0;
432
- for (const [key, val] of Object.entries(col)) {
433
- votes += val;
434
- }
435
- const requiredVotes = Math.floor(this.#services.length / 2) + 1;
436
-
437
- if (requiredVotes !== this.#lastRequiredVotes || votes !== this.#lastVotes) {
438
- console.log(`${this.#GetLogPrefix()}votes: [${votes} need: [${requiredVotes}]`.cyan);
439
- this.#lastRequiredVotes = requiredVotes;
440
- this.#lastVotes = votes;
441
- }
442
-
443
- return votes >= requiredVotes;
444
- }
445
-
446
- #StartCanidateVote = () => {
447
-
448
- // Get the election timeout going again
449
- this.#StartElectionTimeout();
450
-
451
- console.log(`${this.#GetLogPrefix()}: Start CANDIDATE vote`.yellow);
452
- // Start in the CANDIDATE state
453
- this.#ChangeState(AppMasterRAFTState.CANDIDATE);
454
- // Reset votes
455
- this.#votes = { };
456
-
457
- // Reset all votes from all service instances
458
- this.#services.forEach((service, index) => {
459
- this.#votes[this.#GetServiceKey(service)] = 0;
460
- });
461
-
462
- // Start a new term
463
- this.#currentTerm++;
464
-
465
- // Request vote for all other services - include my logs current item
466
- this.#services.forEach((service, index) => {
467
- if (service.host.localeCompare(this.#thisService.host) === 0 && service.port === this.#thisService.port) {
468
- // Log the fact that I have now voted for this term
469
- this.#votedLog[this.#currentTerm] = true;
470
- // Log the result - Vote for myself
471
- this.#votes[this.#GetSelfServiceKey()] = 1;
472
- // Return my yes vote
473
- console.log(chalk.green(`${this.#GetLogPrefix()}: SELF VOTE: canidate currentTerm: [${this.#currentTerm}], vote YES`));
474
- this.#CheckMajority();
475
- } else {
476
- // Send vote request
477
- this.#RequestVote(service);
478
- }
479
- });
480
- }
481
-
482
- #ReceiveVoteRequest = () => {
483
- // Check if the request term and meta-data is more recent than me
484
-
485
- // If request more recent ...
486
- this.#voteRegister = 1;
487
- // Send vote back to requestor
488
- }
489
-
490
- #ResetElectionTimeout = () => {
491
- if (this.#canidateTimeout) {
492
- clearTimeout(this.#canidateTimeout);
493
- }
494
- this.#StartElectionTimeout();
495
- }
496
-
497
- #StartElectionTimeout = () => {
498
- if (this.#canidateTimeout) {
499
- clearTimeout(this.#canidateTimeout);
500
- }
501
- this.#canidateTimeout = setTimeout(() => {
502
- this.#StartCanidateVote();
503
- }, this.#electionTimeout).unref();
504
- }
505
-
506
- #StartRAFTService = async () => {
507
- this.LogEx(chalk.green(`---[ RAFT Protocol Starting ]---`));
508
- this.#server = await this.#SetupJSONRPCServer();
509
- this.#StartElectionTimeout();
510
- }
511
-
512
- #ChangeState(newState: AppMasterRAFTState) {
513
- this.LogEx(chalk.magenta(`${this.#GetLogPrefix()}: State Change, From: [${this.#RAFTState.toString()}] --> To: [${newState.toString()}]`));
514
- this.#RAFTState = newState;
515
- }
516
-
517
- MasterStarted(): void {
518
- setTimeout(() => {
519
- this.#StartRAFTService();
520
- }, this.#startRAFTProtocolTimeout).unref();
521
- }
522
- }
@@ -1,6 +0,0 @@
1
- export const AppFrameworkErrorCode = Object.freeze({
2
- APPFRAMEWORK_MISSING_PERMISSION: {
3
- code: 'STS_AF_0001',
4
- description: 'STS_AF_0001: Missing Permission(s).'
5
- },
6
- });
@@ -1,49 +0,0 @@
1
- /* eslint @typescript-eslint/no-explicit-any: 0, @typescript-eslint/no-unused-vars: 0 */ // --> OFF
2
- import cluster from 'cluster';
3
- import { Worker, MessageChannel } from 'worker_threads';
4
-
5
- if (cluster.isPrimary) {
6
- console.log(`Primary ${process.pid} is running`);
7
-
8
- // Fork workers.
9
- cluster.fork();
10
-
11
- cluster.on('exit', (worker, code, signal) => {
12
- console.log(`worker ${worker.process.pid} died`);
13
- });
14
-
15
- const fileName ='./dist/webworkertesting/worker.js';
16
-
17
- const publishCollectorWebWorker = new Worker(fileName);
18
- publishCollectorWebWorker.unref();
19
-
20
- publishCollectorWebWorker.postMessage({cmd: 'text', message: 'Hello World'});
21
-
22
- publishCollectorWebWorker.on('message', (data) => {
23
- console.log(`cluster.primary (${process.pid}): message from worker = [${JSON.stringify(data)}]`);
24
- });
25
-
26
- const { port1, port2 } = new MessageChannel();
27
-
28
- publishCollectorWebWorker.postMessage({cmd: 'portmessage', port: port2}, [ port2 ]);
29
- port1.postMessage('sending to port1');
30
- port1.on('message', (data) => {
31
- console.log(`cluster.primary (${process.pid}): message from message port = [${data}]`);
32
- });
33
-
34
-
35
- } else {
36
- console.log(`Worker ${process.pid} started`);
37
-
38
- const fileName ='./dist/webworkertesting/worker.js';
39
-
40
- const clusterWorker = new Worker(fileName);
41
- clusterWorker.unref();
42
-
43
- clusterWorker.postMessage({cmd: 'text', message: 'Hello World'});
44
-
45
- clusterWorker.on('message', (data: any) => {
46
- console.log(`cluster.worker (${process.pid}): message from worker = [${JSON.stringify(data)}]`);
47
- });
48
-
49
- }
@@ -1,24 +0,0 @@
1
- /* eslint @typescript-eslint/no-explicit-any: 0, @typescript-eslint/no-unused-vars: 0 */ // --> OFF
2
- import { matchesProperty } from 'lodash';
3
- import {
4
- Worker,
5
- isMainThread,
6
- parentPort,
7
- MessagePort
8
- } from 'worker_threads';
9
-
10
- let messagePort: MessagePort;
11
-
12
- parentPort?.on('message', (data: any) => {
13
- if (data.cmd.localeCompare('portmessage') === 0) {
14
- messagePort = data.port;
15
- messagePort.on('message', (data) => {
16
- console.log(`webWorker (${process.pid}): message from passed message port = [${data}]`);
17
- messagePort.postMessage(data);
18
- });
19
- } else {
20
- console.log(`webWorker (${process.pid}): message from parent = [${JSON.stringify(data)}]`);
21
- parentPort?.postMessage(data);
22
- }
23
- });
24
-
@@ -1,47 +0,0 @@
1
- import { beforeAll, afterAll, test, describe, expect } from 'vitest';
2
-
3
- describe("Test Latency Controller", () =>
4
- {
5
- beforeAll(async () =>
6
- {
7
- /*
8
- process.env.AS_ENDPOINT = testHelper.authHost;
9
- process.env.AS_HOST_PORT = testHelper.authPort;
10
- process.env.AS_PORT = testHelper.authPort;
11
-
12
- $ResetOptions();
13
- //goptions = $Options()
14
-
15
- //goptions.asendpoint = testHelper.authHost;
16
- //goptions.asport = testHelper.authPort;
17
-
18
- const appOptions = ServiceConfigOptions(true);
19
- appOptions.processExitOnTerminate = false;
20
- spb = new SingleProcessBase(appOptions)
21
- await spb.SetupServer();
22
- */
23
- }, 60000);
24
-
25
- afterAll(async () =>
26
- {
27
- /*
28
- await Sleep(500);
29
- await spb?.TerminateApplication();
30
- await Sleep(1000);
31
- spb = null;
32
-
33
- await testHelper.StopAuthService();
34
- await testHelper.StopDatabase();
35
- await testHelper.StopNetwork();
36
-
37
- await Sleep(2000);
38
- */
39
- }, 15000);
40
-
41
- test('Testing Module', async () =>
42
- {
43
- expect.assertions(1);
44
- expect(1).toEqual(1);
45
- });
46
- });
47
-