-
Notifications
You must be signed in to change notification settings - Fork 13
/
componentRegistry.ts
640 lines (564 loc) · 34 KB
/
componentRegistry.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
// Copyright 2020-2020 The Mandarine.TS Framework authors. All rights reserved. MIT license.
import { Log } from "../../logger/log.ts";
import { ControllerComponent } from "../../mvc-framework/core/internal/components/routing/controllerContext.ts";
import { MongoDBService } from "../../orm-core/nosql/mongoDbService.ts";
import { MandarineRepository } from "../../orm-core/repository/mandarineRepository.ts";
import { MysqlRepositoryProxy } from "../../orm-core/repository/repositoryMysqlProxy.ts";
import { PostgresRepositoryProxy } from "../../orm-core/repository/repositoryPostgresProxy.ts";
import { ApplicationContext } from "../application-context/mandarineApplicationContext.ts";
import { ComponentComponent } from "../components/component-component/componentComponent.ts";
import { RepositoryComponent } from "../components/repository-component/repositoryComponent.ts";
import { DI } from "../dependency-injection/di.ns.ts";
import { MicroserviceUserManager } from "../mandarine-native/microservices/microserviceUserManager.ts";
import { Authenticator } from "../mandarine-native/security/authenticatorDefault.ts";
import { TaskManager } from "../mandarine-native/tasks/taskManager.ts";
import { WebSocketClientManager } from "../mandarine-native/websocket/websocketClientManager.ts";
import { WebSocketServerManager } from "../mandarine-native/websocket/websocketServerManager.ts";
import { Mandarine } from "../Mandarine.ns.ts";
import { MandarineConstants } from "../mandarineConstants.ts";
import { Reflect } from "../reflectMetadata.ts";
import { CommonUtils } from "../utils/commonUtils.ts";
import { MicroserviceUtil } from "../utils/components/microserviceUtil.ts";
import { WebSocketClientUtil } from "../utils/components/websocketClient.ts";
import { WebSocketServerUtil } from "../utils/components/websocketServer.ts";
import { IndependentUtils } from "../utils/independentUtils.ts";
import { JsonUtils } from "../utils/jsonUtils.ts";
import { ReflectUtils } from "../utils/reflectUtils.ts";
/**
* This class is also known as the DI container.
* This class handles the addition, initialization and injection for all mandarine components
* This class is also responsible for connection repository methods to a repository proxy method in order to resolve queries
*/
export class ComponentsRegistry implements Mandarine.MandarineCore.IComponentsRegistry {
private components: Map<string, Mandarine.MandarineCore.ComponentRegistryContext> = new Map<string, Mandarine.MandarineCore.ComponentRegistryContext>();
private logger: Log = Log.getLogger(ComponentsRegistry);
constructor() {
this.components.set("MANDARINE_LOGGER", {
componentName: "MANDARINE_LOGGER",
componentInstance: new Log("-"),
componentType: Mandarine.MandarineCore.ComponentTypes.INTERNAL
});
this.components.set("MANDARINE_AUTHENTICATOR", {
componentName: "MANDARINE_AUTHENTICATOR",
componentInstance: new Authenticator(),
componentType: Mandarine.MandarineCore.ComponentTypes.INTERNAL
});
this.components.set("MANDARINE_WEBSOCKETSERVER_MANAGER", {
componentName: "MANDARINE_WEBSOCKETSERVER_MANAGER",
componentInstance: new WebSocketServerManager(),
componentType: Mandarine.MandarineCore.ComponentTypes.INTERNAL
});
this.components.set("MANDARINE_WEBSOCKETCLIENT_MANAGER", {
componentName: "MANDARINE_WEBSOCKETCLIENT_MANAGER",
componentInstance: new WebSocketClientManager(),
componentType: Mandarine.MandarineCore.ComponentTypes.INTERNAL
});
this.components.set("MANDARINE_TASK_MANAGER", {
componentName: "MANDARINE_TASK_MANAGER",
componentInstance: new TaskManager(),
componentType: Mandarine.MandarineCore.ComponentTypes.INTERNAL
});
this.components.set("MANDARINE_MICROSERVICE_MANAGER", {
componentName: "MANDARINE_MICROSERVICE_MANAGER",
componentInstance: new MicroserviceUserManager(),
componentType: Mandarine.MandarineCore.ComponentTypes.INTERNAL
});
const mongoDbConnectionUrl: string | undefined = Mandarine.Global.readConfigByDots("mandarine.services.mongodb.connectionURL");
if(mongoDbConnectionUrl) {
this.components.set("MANDARINE_MONGODB_SERVICE", {
componentName: "MANDARINE_MONGODB_SERVICE",
componentInstance: new MongoDBService(mongoDbConnectionUrl),
componentType: Mandarine.MandarineCore.ComponentTypes.INTERNAL
});
this.logger.info("MongoDB Service has been injected");
}
}
public register(componentName: string, componentInstance: any, componentType: Mandarine.MandarineCore.ComponentTypes, configuration: any): void {
let componentExist: boolean = this.exist(componentName);
if(componentExist) {
componentName = `${componentName}.${CommonUtils.generateUUID()}`;
} else {
let componentInstanceInitialized: any;
let componentHandler: any = componentInstance;
let isServiceType: boolean = false;
switch(componentType) {
case Mandarine.MandarineCore.ComponentTypes.CONTROLLER:
componentInstanceInitialized = new ControllerComponent(componentName, configuration.pathRoute, componentInstance, componentHandler);
break;
case Mandarine.MandarineCore.ComponentTypes.SERVICE:
componentInstanceInitialized = new ComponentComponent(componentName, componentHandler, Mandarine.MandarineCore.ComponentTypes.SERVICE);
break;
case Mandarine.MandarineCore.ComponentTypes.CONFIGURATION:
componentInstanceInitialized = new ComponentComponent(componentName, componentHandler, Mandarine.MandarineCore.ComponentTypes.CONFIGURATION);
break;
case Mandarine.MandarineCore.ComponentTypes.COMPONENT:
componentInstanceInitialized = new ComponentComponent(componentName, componentHandler, Mandarine.MandarineCore.ComponentTypes.COMPONENT);
break;
case Mandarine.MandarineCore.ComponentTypes.MIDDLEWARE:
componentInstanceInitialized = new ComponentComponent(componentName, componentHandler, Mandarine.MandarineCore.ComponentTypes.MIDDLEWARE, configuration);
break;
case Mandarine.MandarineCore.ComponentTypes.MANUAL_COMPONENT:
case Mandarine.MandarineCore.ComponentTypes.INTERNAL:
componentInstanceInitialized = componentInstance;
break;
case Mandarine.MandarineCore.ComponentTypes.REPOSITORY:
componentInstanceInitialized = new RepositoryComponent(componentName, componentHandler, configuration);
break;
case Mandarine.MandarineCore.ComponentTypes.CATCH:
componentInstanceInitialized = new ComponentComponent(componentName, componentHandler, Mandarine.MandarineCore.ComponentTypes.CATCH, configuration);
break;
case Mandarine.MandarineCore.ComponentTypes.GUARDS:
componentInstanceInitialized = new ComponentComponent(componentName, componentHandler, Mandarine.MandarineCore.ComponentTypes.GUARDS, configuration);
break;
case Mandarine.MandarineCore.ComponentTypes.WEBSOCKET:
componentInstanceInitialized = new ComponentComponent(componentName, componentHandler, Mandarine.MandarineCore.ComponentTypes.WEBSOCKET, configuration);
break;
case Mandarine.MandarineCore.ComponentTypes.MICROSERVICE:
componentInstanceInitialized = new ComponentComponent(componentName, componentHandler, Mandarine.MandarineCore.ComponentTypes.MICROSERVICE, configuration);
break;
}
switch(componentType) {
case Mandarine.MandarineCore.ComponentTypes.CONTROLLER:
case Mandarine.MandarineCore.ComponentTypes.SERVICE:
case Mandarine.MandarineCore.ComponentTypes.CONFIGURATION:
case Mandarine.MandarineCore.ComponentTypes.COMPONENT:
case Mandarine.MandarineCore.ComponentTypes.MIDDLEWARE:
case Mandarine.MandarineCore.ComponentTypes.CATCH:
case Mandarine.MandarineCore.ComponentTypes.GUARDS:
case Mandarine.MandarineCore.ComponentTypes.WEBSOCKET:
case Mandarine.MandarineCore.ComponentTypes.MICROSERVICE:
isServiceType = true;
break;
}
this.components.set(componentName, {
componentName: componentName,
componentInstance: componentInstanceInitialized,
componentType: componentType,
isServiceType: isServiceType
});
}
}
public get(itemName: string): Mandarine.MandarineCore.ComponentRegistryContext | undefined {
return this.components.get(itemName);
}
public clearComponentRegistry(): void {
const componentKeys = () => Array.from(this.components.keys());
const toDelete = componentKeys().filter((componentKey: string) => {
return this.components.get(componentKey)?.componentType != Mandarine.MandarineCore.ComponentTypes.INTERNAL;
});
toDelete.forEach((key: string) => this.components.delete(key));
}
public update(itemName: string, newValue: Mandarine.MandarineCore.ComponentRegistryContext | undefined): void {
if(newValue) {
this.components.set(itemName, newValue);
}
}
public exist(itemName: string): boolean {
if(this.components.get(itemName) != null) return true;
else return false;
}
public getAllComponentNames(): Array<string> {
return Array.from(this.components.keys());
}
public getAllComponentNamesByType(componentType: Mandarine.MandarineCore.ComponentTypes): Array<string> | undefined {
return Array.from(this.components.values()).filter(item => item.componentType == componentType).map(item => item.componentName || "");
}
public getComponents(): Mandarine.MandarineCore.ComponentRegistryContext[] {
return Array.from(this.components.values());
}
public getComponentsByComponentType(componentType: Mandarine.MandarineCore.ComponentTypes): Mandarine.MandarineCore.ComponentRegistryContext[] {
return Array.from(this.components.values()).filter(item => item.componentType == componentType);
}
public getControllers(): Mandarine.MandarineCore.ComponentRegistryContext[] {
return Array.from(this.components.values()).filter(item => item.componentType == Mandarine.MandarineCore.ComponentTypes.CONTROLLER);
}
public getAllRepositories(): Array<Mandarine.MandarineCore.ComponentRegistryContext> {
return this.getComponentsByComponentType(Mandarine.MandarineCore.ComponentTypes.REPOSITORY);
}
public getComponentByHandlerType(classType: any, requiredType?: Mandarine.MandarineCore.ComponentTypes): Mandarine.MandarineCore.ComponentRegistryContext | undefined {
try {
return this.getComponents().find((component: Mandarine.MandarineCore.ComponentRegistryContext) => {
let instance = undefined;
if(component.componentType == Mandarine.MandarineCore.ComponentTypes.MANUAL_COMPONENT || component.componentType == Mandarine.MandarineCore.ComponentTypes.INTERNAL) {
instance = component.componentInstance;
}else {
instance = component.componentInstance.getClassHandler();
}
// This verification should never be called as instance may have parameters in its constructor.
// When this method is used, it should be used after initialization of dependencies
if(!ReflectUtils.checkClassInitialized(instance)) instance = new instance();
return instance instanceof classType && ((requiredType) ? (component.componentType == requiredType) : true);
});
} catch {
return undefined;
}
}
public resolveDependencies(): void {
return DI.Factory.componentDependencyResolver(this);
}
public connectWebsocketClientProxy(websocketInstance: ComponentComponent): void {
let websocketTarget: any = websocketInstance.getClassHandler();
const metadataKeys: Array<string> = Reflect.getMetadataKeys(websocketTarget);
metadataKeys.filter(item => item.startsWith(MandarineConstants.REFLECTION_MANDARINE_WEBSOCKET_PROPERTY)).forEach((item) => {
const metadata: Mandarine.MandarineCore.Decorators.WebSocketProperty = Reflect.getMetadata(item, websocketTarget);
if(metadata) {
switch(metadata.property) {
case "onClose":
websocketInstance.getInternal<WebSocket>(MandarineConstants.COMPONENT_PROPERTY_WEBSOCKET).onclose = (event: CloseEvent) => {
websocketTarget[metadata.methodName](event);
}
break;
case "onOpen":
websocketInstance.getInternal<WebSocket>(MandarineConstants.COMPONENT_PROPERTY_WEBSOCKET).onopen = (event: Event) => {
websocketTarget[metadata.methodName](event);
}
break;
case "onMessage":
websocketInstance.getInternal<WebSocket>(MandarineConstants.COMPONENT_PROPERTY_WEBSOCKET).onmessage = (event: MessageEvent) => {
websocketTarget[metadata.methodName](event);
}
break;
case "onError":
websocketInstance.getInternal<WebSocket>(MandarineConstants.COMPONENT_PROPERTY_WEBSOCKET).onerror = (event: Event | ErrorEvent) => {
websocketTarget[metadata.methodName](event);
}
break;
case "send":
websocketTarget[metadata.methodName] = (data: string | ArrayBufferView | ArrayBuffer | Blob) => {
websocketInstance.getInternal<WebSocket>(MandarineConstants.COMPONENT_PROPERTY_WEBSOCKET).send(data);
}
break;
case "close":
websocketTarget[metadata.methodName] = (closeOptions?: { code?: number, reason?: string}) => {
WebSocketClientUtil.close(websocketInstance, closeOptions?.code, closeOptions?.reason);
}
break;
}
}
});
}
public connectWebsocketServerProxy(websocketInstance: ComponentComponent): void {
let websocketTarget: any = websocketInstance.getClassHandler();
const metadataKeys: Array<string> = Reflect.getMetadataKeys(websocketTarget);
metadataKeys.filter(item => item.startsWith(MandarineConstants.REFLECTION_MANDARINE_WEBSOCKET_PROPERTY)).forEach((item) => {
const metadata: Mandarine.MandarineCore.Decorators.WebSocketProperty = Reflect.getMetadata(item, websocketTarget);
if(metadata) {
const internalExists: boolean = websocketInstance.getInternal<Worker>(MandarineConstants.COMPONENT_PROPERTY_WEBSOCKET) !== undefined;
if(internalExists) {
switch(metadata.property) {
case "onMessage":
websocketInstance.getInternal<Worker>(MandarineConstants.COMPONENT_PROPERTY_WEBSOCKET).onmessage = (event: MessageEvent) => {
websocketTarget[metadata.methodName](event);
}
break;
case "onError":
websocketInstance.getInternal<Worker>(MandarineConstants.COMPONENT_PROPERTY_WEBSOCKET).onerror = (event: ErrorEvent) => {
event.preventDefault(); // Don't panic main thread since it should be handled already
websocketTarget[metadata.methodName](event);
}
break;
case "send":
throw new Error("Sending from WebSocket server to client is not implemented in Mandarine.");
case "close":
websocketTarget[metadata.methodName] = () => {
WebSocketServerUtil.unmount(websocketInstance);
}
break;
}
} else {
this.logger.warn("An operation related to a websocket server was executed, but the worker for the server is not available.");
}
}
});
}
private connectRepositoryToProxy(repositoryObject: Mandarine.MandarineCore.ComponentRegistryContext) {
let repositoryInstance: RepositoryComponent = repositoryObject.componentInstance;
let repositoryTarget: any = repositoryInstance.getClassHandler();
let repositoryMethods: Array<string> = ReflectUtils.getMethodsFromClass(repositoryTarget);
let mandarineRepositoryMethods: Array<string> = ReflectUtils.getMethodsFromClass(MandarineRepository);
repositoryMethods = repositoryMethods.concat(mandarineRepositoryMethods);
let repositoryProxy: Mandarine.ORM.RepositoryProxy;
let dialect: Mandarine.ORM.Dialect.Dialects = Mandarine.Global.getMandarineConfiguration().mandarine?.dataSource?.dialect;
if(dialect) {
switch(dialect) {
case Mandarine.ORM.Dialect.Dialects.POSTGRESQL:
repositoryProxy = new PostgresRepositoryProxy<any>(repositoryInstance.extraData.entity);
break;
case Mandarine.ORM.Dialect.Dialects.MYSQL:
repositoryProxy = new MysqlRepositoryProxy<any>(repositoryInstance.extraData.entity);
break;
default:
throw new Error(`${dialect} is not supported inside Mandarine's ORM`);
}
}
repositoryMethods.forEach((methodName) => {
if(ApplicationContext.getInstance().getEntityManager().getDataSource() == undefined) {
repositoryTarget.prototype[methodName] = (...args: Array<any>) => {
this.logger.compiler("A data source is required for repositories. Operation not supported", "warn");
return undefined;
}
return;
}
let manualQuery: { query: string, secure?: boolean } = Reflect.getMetadata(`${MandarineConstants.REFLECTION_MANDARINE_REPOSITORY_METHOD_MANUAL_QUERY}:${methodName}`, new repositoryTarget(), methodName);
if(manualQuery != undefined) {
repositoryTarget.prototype[methodName] = (...args: Array<any>) => {
return repositoryProxy.manualProxy(repositoryProxy, manualQuery.query, manualQuery.secure || false, args);
}
return;
}
switch(methodName) {
case 'findAll':
repositoryTarget.prototype[methodName] = () => {
return repositoryProxy.findAll(repositoryProxy);
}
return;
case 'countAll':
repositoryTarget.prototype[methodName] = () => {
return repositoryProxy.countAll(repositoryProxy);
}
return;
case 'deleteAll':
repositoryTarget.prototype[methodName] = () => {
return repositoryProxy.deleteAll(repositoryProxy);
}
return;
case 'save':
repositoryTarget.prototype[methodName] = (model: any) => {
return repositoryProxy.save(model);
}
return;
}
if(methodName.startsWith('find')) {
repositoryTarget.prototype[methodName] = (...args: Array<any>) => {
return repositoryProxy.mainProxy(repositoryProxy, methodName, "findBy", args);
}
} else if(methodName.startsWith('exists')) {
repositoryTarget.prototype[methodName] = (...args: Array<any>) => {
return repositoryProxy.mainProxy(repositoryProxy, methodName, "existsBy", args);
}
} else if(methodName.startsWith('delete')) {
repositoryTarget.prototype[methodName] = (...args: Array<any>) => {
return repositoryProxy.mainProxy(repositoryProxy, methodName, "deleteBy", args);
}
} else if(methodName.startsWith('count')) {
repositoryTarget.prototype[methodName] = (...args: Array<any>) => {
return repositoryProxy.mainProxy(repositoryProxy, methodName, "countBy", args);
}
}
});
repositoryInstance.classHandler = repositoryTarget;
return repositoryInstance;
}
public connectRepositoriesToProxy(): void {
let repositoriesArray = this.getAllRepositories();
repositoriesArray.forEach((repo: Mandarine.MandarineCore.ComponentRegistryContext) => {
const repoName = repo.componentName;
if(!repoName) return;
let componentInstance: RepositoryComponent = repo.componentInstance;
let newRepositoryProxy: any = this.connectRepositoryToProxy(repo);
let handler: any = newRepositoryProxy.getClassHandler();
componentInstance.classHandler = new handler();
this.update(repoName, repo);
});
if(ApplicationContext.CONTEXT_METADATA.engineMetadata?.orm) {
ApplicationContext.CONTEXT_METADATA.engineMetadata.orm.repositoriesAmount = repositoriesArray.length || 0;
}
}
public getRepositoryByHandlerType(classType: any): Mandarine.MandarineCore.ComponentRegistryContext | undefined {
return this.getAllRepositories().find((repo: Mandarine.MandarineCore.ComponentRegistryContext) => {
let component: RepositoryComponent = repo.componentInstance;
let instance = component.getClassHandler();
if(!ReflectUtils.checkClassInitialized(instance)) instance = new instance();
return instance instanceof classType;
});
}
public initializeControllers(): void {
this.getControllers().forEach((controller) => {
(<ControllerComponent>controller.componentInstance).initializeControllerFunctionality();
})
}
public initializeEventListeners(): void {
const serviceTypeComponents = this.getComponents().filter((item) => item.isServiceType === true);
serviceTypeComponents.forEach((component) => {
const instance = component.componentInstance.getClassHandler();
const metadataKeys: Array<string> = Reflect.getMetadataKeys(instance);
metadataKeys.filter(item => item.startsWith(MandarineConstants.REFLECTION_MANDARINE_EVENTLISTENER_DECORATOR)).forEach((item) => {
const metadata: Mandarine.MandarineCore.Decorators.EventListener = Reflect.getMetadata(item, instance);
if(metadata) {
const isAsyncFunc = instance[metadata.methodName] instanceof Mandarine.AsyncFunction;
if(isAsyncFunc) {
addEventListener(metadata.eventName, async () => await instance[metadata.methodName]())
} else {
addEventListener(metadata.eventName, () => instance[metadata.methodName]())
}
}
});
})
}
public initializeValueReaders(): void {
const serviceTypeComponents = this.getComponents().filter((item) => item.isServiceType === true);
serviceTypeComponents.forEach((component) => {
const instances = [component.componentInstance.getClassHandler(), component.componentInstance.getClassHandlerPrimitive()];
instances.forEach((instance) => {
const metadataKeys: Array<string> = Reflect.getMetadataKeys(instance);
metadataKeys.filter(item => item.startsWith(MandarineConstants.REFLECTION_MANDARINE_VALUE_DECORATOR)).forEach((item) => {
const metadata: Mandarine.MandarineCore.Decorators.Value = Reflect.getMetadata(item, instance);
if(metadata) {
let propertyObject = {};
if(metadata.scope == Mandarine.MandarineCore.ValueScopes.CONFIGURATION) propertyObject = Mandarine.Global.getMandarineConfiguration();
if(metadata.scope == Mandarine.MandarineCore.ValueScopes.ENVIRONMENTAL) propertyObject = Deno.env.toObject();
//onsole.log(propertyObject);
if(!instance[metadata.propertyName]) {
instance[metadata.propertyName] = IndependentUtils.readConfigByDots(propertyObject, metadata.configKey);
}
}
});
});
});
}
public initializeValueReaderWithCustomConfiguration(): void {
const serviceTypeComponents = this.getComponents().filter((item) => item.isServiceType === true);
serviceTypeComponents.forEach((component) => {
const instances = [component.componentInstance.getClassHandler(), component.componentInstance.getClassHandlerPrimitive()];
instances.forEach((instance) => {
const metadataKeys: Array<string> = Reflect.getMetadataKeys(instance);
metadataKeys.filter(item => item.startsWith(MandarineConstants.REFLECTION_MANDARINE_CONFIGURATION_PROPERTIES)).forEach((item) => {
const customConfigPath: string = Reflect.getMetadata(item, instance);
if(customConfigPath) {
metadataKeys.filter((item) => item.startsWith(MandarineConstants.REFLECTION_MANDARINE_VALUE_DECORATOR)).forEach((key) => {
const metadata: { configKey: string, scope: string, propertyName: string } = Reflect.getMetadata(key, instance);
const configuration = JsonUtils.toJson(customConfigPath, {
isFile: true,
allowEnvironmentalReferences: true,
handleException: (ex: any) => {
Mandarine.logger.warn(`Something happened while reading custom configuration file for @Value. ${ex} (${customConfigPath})`);
return {}
}
});
if(!instance[metadata.propertyName]) {
instance[metadata.propertyName] = IndependentUtils.readConfigByDots(configuration, metadata.configKey);
}
});
}
});
});
});
}
public initializeWebsocketComponents(): void {
const websocketComponents = this.getComponentsByComponentType(Mandarine.MandarineCore.ComponentTypes.WEBSOCKET);
websocketComponents.forEach((item) => {
// Create Websocket
let component: ComponentComponent = item.componentInstance;
const { url, protocols, type, port } = component.configuration;
try {
if(type === "client") {
WebSocketClientUtil.mount(component, url, protocols);
} else if(type === "server") {
WebSocketServerUtil.mount(component, port);
}
} catch(error) {
if(type === "client") {
this.logger.warn(`Websocket client component could not establish a connnection with host ${url}. You may retry manually.`, error);
} else if(type === "server") {
this.logger.warn(`Websocket server component could not be created in worker. `, error);
}
}
})
}
public initializeTasks(): void {
const serviceTypeComponents = this.getComponents().filter((item) => item.isServiceType === true);
const taskManagerDependency = ApplicationContext.getInstance().getDIFactory().getDependency<TaskManager>(TaskManager);
let cronTaskFound = false;
if(taskManagerDependency) {
serviceTypeComponents.forEach((component) => {
const instance = component.componentInstance.getClassHandler();
const metadataKeys: Array<string> = Reflect.getMetadataKeys(instance);
metadataKeys.filter(item => item.startsWith(MandarineConstants.REFLECTION_MANDARINE_SCHEDULED_DECORATOR)).forEach((item) => {
const metadata: Mandarine.MandarineCore.Decorators.ScheduledTask = Reflect.getMetadata(item, instance);
if(metadata) {
taskManagerDependency.getCronManager().create(metadata.cronExpression, () => instance[metadata.methodName](), metadata.timeZone);
cronTaskFound = true;
}
});
metadataKeys.filter(item => item.startsWith(MandarineConstants.REFLECTION_MANDARINE_TIMER_DECORATOR)).forEach((item) => {
const metadata: Mandarine.MandarineCore.Decorators.Timer = Reflect.getMetadata(item, instance);
if(metadata) {
taskManagerDependency.getTimerManager().create(component.componentInstance.getClassHandlerPrimitive(), metadata.methodName, metadata.fixedRate, () => instance[metadata.methodName]())
}
});
});
// Only begin CRON tasks interval checker if > one task actually exists
if(cronTaskFound) {
taskManagerDependency.getCronManager().beginTasks();
}
// ALL CRON TASKS ARE SETUP
this.logger.info("Task manager has been found and initialized");
}
}
public initializeMicroservices(): void {
const websocketComponents = this.getComponentsByComponentType(Mandarine.MandarineCore.ComponentTypes.MICROSERVICE);
const microserviceManager = Mandarine.Global.getMicroserviceManager();
websocketComponents.forEach(async (item) => {
// Create Websocket
let component: ComponentComponent = item.componentInstance;
component.addInternal("HEALTH_CHECKS_COUNTS", 0);
MicroserviceUtil.mount(component);
});
}
public connectMicroserviceToProxy(microserviceInstance: ComponentComponent): void {
let microserviceTarget: any = microserviceInstance.getClassHandler();
let microserviceWorkerItem = Mandarine.Global.getMicroserviceManager().getByComponent(microserviceInstance);
const microserviceWorker = microserviceWorkerItem?.worker;
if(microserviceWorker) {
const metadataKeys: Array<string> = Reflect.getMetadataKeys(microserviceTarget);
let [closeMethodName, onCloseMethodName, onOpenMethodName]: [any, any, any] = [undefined, undefined, undefined];
metadataKeys.filter(item => item.startsWith(MandarineConstants.REFLECTION_MANDARINE_MICROSERVICE_PROPERTY)).forEach((item) => {
const metadata: Mandarine.MandarineCore.Decorators.WebSocketProperty = Reflect.getMetadata(item, microserviceTarget);
if(metadata) {
switch(metadata.property) {
case "onClose":
onCloseMethodName = metadata.methodName;
break;
case "onOpen":
onOpenMethodName = metadata.methodName;
break;
case "onMessage":
microserviceWorker!.onmessage = (e: { [prop: string]: any }) => {
let { data } = e;
data = JSON.parse(data);
if(data.message === "ALIVE" && data.mandarine === "HEALTH-CHECK") {
microserviceInstance.addInternal("HEALTH_CHECKS_COUNTS", microserviceInstance.getInternal("HEALTH_CHECKS_COUNTS") + 1);
} else if(data.mandarine === "LISTENING-ERROR") {
this.logger.error("Microservice worker encountered an error. Closing connection. ", data.message)
microserviceWorker.terminate();
} else {
microserviceTarget[metadata.methodName](data);
}
}
break;
case "onError":
microserviceWorker!.onerror = (e: ErrorEvent) => {
e.preventDefault();
microserviceTarget[metadata.methodName](e);
}
break;
case "close":
closeMethodName = metadata.methodName;
break;
}
}
});
if(closeMethodName) {
microserviceTarget[closeMethodName] = () => {
microserviceWorker!.terminate();
microserviceTarget[onCloseMethodName](microserviceWorkerItem);
}
}
if(onOpenMethodName) {
microserviceTarget[onOpenMethodName](microserviceWorkerItem);
}
} else {
this.logger.debug("A microservice tried to connect to proxy, but no worker was found");
}
}
}