-
Notifications
You must be signed in to change notification settings - Fork 374
/
application.ts
1278 lines (1168 loc) · 37.7 KB
/
application.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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Pomelo -- proto
* Copyright(c) 2012 xiechengchao <xiecc@163.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
import * as utils from './util/utils';
import { getLogger } from 'pinus-logger';
import * as Logger from 'pinus-logger';
let logger = getLogger('pinus', __filename);
import { EventEmitter } from 'events';
import { default as events, AppEvents } from './util/events';
import * as appUtil from './util/appUtil';
import * as Constants from './util/constants';
import * as appManager from './common/manager/appManager';
import * as fs from 'fs';
import * as path from 'path';
import * as util from 'util';
import { IComponent } from './interfaces/IComponent';
import { DictionaryComponent } from './components/dictionary';
import { PushSchedulerComponent } from './components/pushScheduler';
import { BackendSessionService } from './common/service/backendSessionService';
import { ChannelService, ChannelServiceOptions } from './common/service/channelService';
import { SessionComponent } from './components/session';
import { ServerComponent } from './components/server';
import { RemoteComponent } from './components/remote';
import { ProxyComponent, RouteMaps, RouteFunction } from './components/proxy';
import { ProtobufComponent } from './components/protobuf';
import { MonitorComponent } from './components/monitor';
import { MasterComponent } from './components/master';
import { ConnectorComponent } from './components/connector';
import { ConnectionComponent } from './components/connection';
import { SessionService } from './common/service/sessionService';
import { ObjectType } from './interfaces/define';
import { isFunction } from 'util';
import { IModule, IModuleFactory } from 'pinus-admin';
import { ChannelComponent } from './components/channel';
import { BackendSessionComponent } from './components/backendSession';
import { Session, MasterInfo, ApplicationEventContructor } from '../index';
import { ServerInfo, FRONTENDID } from './util/constants';
import { BeforeHandlerFilter, AfterHandlerFilter, IHandlerFilter } from './interfaces/IHandlerFilter';
import { TransactionCondictionFunction, TransactionHandlerFunction } from './common/manager/appManager';
import { RpcFilter, MailStationErrorHandler } from 'pinus-rpc/dist/lib/rpc-client/mailstation';
import { ILifeCycle } from './interfaces/ILifeCycle';
import { ModuleRecord } from './util/moduleUtil';
import { IPlugin } from './interfaces/IPlugin';
import { Cron } from './server/server';
import { ServerStartArgs } from './util/appUtil';
import { listEs6ClassMethods } from '../../pinus-rpc/dist/lib/util/utils';
export type ConfigureCallback = ()=>void;
export type AConfigureFunc1 = ()=>Promise<void> ;
export type AConfigureFunc2 = (env : string)=>Promise<void> ;
export type AConfigureFunc3 = (env : string, type : string)=>Promise<void>
export interface ApplicationOptions
{
base ?: string;
}
export type BeforeStopHookFunction = (app:Application , shutDown : ()=>void, cancelShutDownTimer : ()=>void)=>void;
/**
* Application states
*/
let STATE_INITED = 1; // app has inited
let STATE_START = 2; // app start
let STATE_STARTED = 3; // app has started
let STATE_STOPED = 4; // app has stoped
export class Application
{
loaded : IComponent[] = []; // loaded component list
components : {
__backendSession__ ?: BackendSessionComponent,
__channel__ ?: ChannelComponent,
__connection__ ?: ConnectionComponent,
__connector__ ?: ConnectorComponent,
__dictionary__ ?: DictionaryComponent,
__master__ ?: MasterComponent,
__monitor__ ?: MonitorComponent,
__protobuf__ ?: ProtobufComponent,
__proxy__ ?: ProxyComponent,
__remote__ ?: RemoteComponent,
__server__ ?: ServerComponent,
__session__ ?: SessionComponent,
__pushScheduler__ ?: PushSchedulerComponent,
[key:string] : IComponent
} = {}; // name -> component map
sessionService ?: SessionService;
backendSessionService ?: BackendSessionService;
channelService ?: ChannelService;
settings : {[key:string] : any}= {}; // collection keep set/get
event = new EventEmitter(); // event object to sub/pub events
// current server info
serverId : string; // current server id
serverType : string; // current server type
curServer : ServerInfo; // current server info
startTime : number; // current server start time
// global server infos
master : ServerStartArgs = null; // master server info
servers : {[id:string] : ServerInfo} = {}; // current global server info maps, id -> info
serverTypeMaps : {[type:string] : ServerInfo[]} = {}; // current global type maps, type -> [info]
serverTypes : string[] = []; // current global server type list
usedPlugins : IPlugin[] = []; // current server custom lifecycle callbacks
clusterSeq : {[serverType:string] : number} = {}; // cluster id seqence
state: number;
base : string;
startId : string;
type : string;
stopTimer : any;
/**
* Initialize the server.
*
* - setup default configuration
*/
init(opts ?: ApplicationOptions)
{
opts = opts || {};
let base = opts.base || path.dirname(require.main.filename);
this.set(Constants.RESERVED.BASE, base);
this.base = base;
appUtil.defaultConfiguration(this);
this.state = STATE_INITED;
logger.info('application inited: %j', this.getServerId());
};
/**
* Get application base path
*
* // cwd: /home/game/
* pinus start
* // app.getBase() -> /home/game
*
* @return {String} application base path
*
* @memberOf Application
*/
getBase()
{
return this.get(Constants.RESERVED.BASE);
};
/**
* Override require method in application
*
* @param {String} relative path of file
*
* @memberOf Application
*/
require(ph : string)
{
return require(path.join(this.getBase(), ph));
};
/**
* Configure logger with {$base}/config/log4js.json
*
* @param {Object} logger pinus-logger instance without configuration
*
* @memberOf Application
*/
configureLogger(logger : typeof Logger)
{
if (process.env.POMELO_LOGGER !== 'off')
{
let base = this.getBase();
let env = this.get(Constants.RESERVED.ENV);
let originPath = path.join(base, Constants.FILEPATH.LOG);
let presentPath = path.join(base, Constants.FILEPATH.CONFIG_DIR, env, path.basename(Constants.FILEPATH.LOG));
if (fs.existsSync(originPath))
{
logger.configure(originPath, { serverId: this.serverId, base: base });
} else if (fs.existsSync(presentPath))
{
logger.configure(presentPath, { serverId: this.serverId, base: base });
} else
{
console.error('logger file path configuration is error.');
}
}
};
/**
* add a filter to before and after filter
*
* @param {Object} filter provide before and after filter method.
* A filter should have two methods: before and after.
* @memberOf Application
*/
filter(filter: IHandlerFilter): void
{
this.before(filter);
this.after(filter);
};
/**
* Add before filter.
*
* @param {Object|Function} bf before fileter, bf(msg, session, next)
* @memberOf Application
*/
before(bf: BeforeHandlerFilter): void
{
addFilter(this, Constants.KEYWORDS.BEFORE_FILTER, bf);
};
/**
* Add after filter.
*
* @param {Object|Function} af after filter, `af(err, msg, session, resp, next)`
* @memberOf Application
*/
after(af: AfterHandlerFilter): void
{
addFilter(this, Constants.KEYWORDS.AFTER_FILTER, af);
};
/**
* add a global filter to before and after global filter
*
* @param {Object} filter provide before and after filter method.
* A filter should have two methods: before and after.
* @memberOf Application
*/
globalFilter(filter : IHandlerFilter)
{
this.globalBefore(filter);
this.globalAfter(filter);
};
/**
* Add global before filter.
*
* @param {Object|Function} bf before fileter, bf(msg, session, next)
* @memberOf Application
*/
globalBefore(bf : BeforeHandlerFilter)
{
addFilter(this, Constants.KEYWORDS.GLOBAL_BEFORE_FILTER, bf);
};
/**
* Add global after filter.
*
* @param {Object|Function} af after filter, `af(err, msg, session, resp, next)`
* @memberOf Application
*/
globalAfter(af : AfterHandlerFilter)
{
addFilter(this, Constants.KEYWORDS.GLOBAL_AFTER_FILTER, af);
};
/**
* Add rpc before filter.
*
* @param {Object|Function} bf before fileter, bf(serverId, msg, opts, next)
* @memberOf Application
*/
rpcBefore(bf : RpcFilter | RpcFilter[])
{
addFilter(this, Constants.KEYWORDS.RPC_BEFORE_FILTER, bf);
};
/**
* Add rpc after filter.
*
* @param {Object|Function} af after filter, `af(serverId, msg, opts, next)`
* @memberOf Application
*/
rpcAfter(af : RpcFilter | RpcFilter[])
{
addFilter(this, Constants.KEYWORDS.RPC_AFTER_FILTER, af);
};
/**
* add a rpc filter to before and after rpc filter
*
* @param {Object} filter provide before and after filter method.
* A filter should have two methods: before and after.
* @memberOf Application
*/
rpcFilter(filter : RpcFilter)
{
this.rpcBefore(filter);
this.rpcAfter(filter);
};
/**
* Load component
*
* @param {String} name (optional) name of the component
* @param {Object} component component instance or factory function of the component
* @param {[type]} opts (optional) construct parameters for the factory function
* @return {Object} app instance for chain invoke
* @memberOf Application
*/
load<T extends IComponent>(component : ObjectType<T>, opts ?: any) : T
load<T extends IComponent>(name : string, component : ObjectType<T>, opts ?: any) : T
load<T extends IComponent>(component : T, opts ?: any) : T
load<T extends IComponent>(name : string, component : T, opts ?: any) : T
load<T extends IComponent>(name : string | ObjectType<T>, component ?: ObjectType<T> | any | T, opts ?: any) : T
{
if (typeof name !== 'string')
{
opts = component;
component = name;
name = null;
}
if(isFunction(component))
{
component = new component(this, opts);
}
if (!name && typeof component.name === 'string')
{
name = component.name;
}
if (name && this.components[name as string])
{
// ignore duplicat component
logger.warn('ignore duplicate component: %j', name);
return;
}
this.loaded.push(component);
if (name)
{
// components with a name would get by name throught app.components later.
this.components[name as string] = component;
}
return component;
};
/**
* Load Configure json file to settings.(support different enviroment directory & compatible for old path)
*
* @param {String} key environment key
* @param {String} val environment value
* @param {Boolean} reload whether reload after change default false
* @return {Server|Mixed} for chaining, or the setting value
* @memberOf Application
*/
loadConfigBaseApp(key : string, val : string, reload = false)
{
let self = this;
let env = this.get(Constants.RESERVED.ENV);
let originPath = path.join(this.getBase(), val);
let presentPath = path.join(this.getBase(), Constants.FILEPATH.CONFIG_DIR, env, path.basename(val));
let realPath : string;
if (fs.existsSync(originPath))
{
realPath = originPath;
let file = require(originPath);
if (file[env])
{
file = file[env];
}
this.set(key, file);
} else if (fs.existsSync(presentPath))
{
realPath = presentPath;
let pfile = require(presentPath);
this.set(key, pfile);
} else
{
logger.error('invalid configuration with file path: %s', key);
}
if (!!realPath && !!reload)
{
fs.watch(realPath, function (event, filename)
{
if (event === 'change')
{
delete require.cache[require.resolve(realPath)];
self.loadConfigBaseApp(key, val);
}
});
}
};
/**
* Load Configure json file to settings.
*
* @param {String} key environment key
* @param {String} val environment value
* @return {Server|Mixed} for chaining, or the setting value
* @memberOf Application
*/
loadConfig(key : string, val : string)
{
let env = this.get(Constants.RESERVED.ENV);
let cfg = require(val);
if (cfg[env])
{
cfg = cfg[env];
}
this.set(key, cfg);
};
/**
* Set the route function for the specified server type.
*
* Examples:
*
* app.route('area', routeFunc);
*
* let routeFunc = function(session, msg, app, cb) {
* // all request to area would be route to the first area server
* let areas = app.getServersByType('area');
* cb(null, areas[0].id);
* };
*
* @param {String} serverType server type string
* @param {Function} routeFunc route function. routeFunc(session, msg, app, cb)
* @return {Object} current application instance for chain invoking
* @memberOf Application
*/
route(serverType : string, routeFunc : RouteFunction)
{
let routes = this.get(Constants.KEYWORDS.ROUTE);
if (!routes)
{
routes = {};
this.set(Constants.KEYWORDS.ROUTE, routes);
}
routes[serverType] = routeFunc;
return this;
};
/**
* Set before stop function. It would perform before servers stop.
*
* @param {Function} fun before close function
* @return {Void}
* @memberOf Application
*/
beforeStopHook(fun : BeforeStopHookFunction)
{
logger.warn('this method was deprecated in pinus 0.8');
if (!!fun && typeof fun === 'function')
{
this.set(Constants.KEYWORDS.BEFORE_STOP_HOOK, fun);
}
};
/**
* Start application. It would load the default components and start all the loaded components.
*
* @param {Function} cb callback function
* @memberOf Application
*/
start(cb ?: (err ?: Error , result ?: void)=>void)
{
this.startTime = Date.now();
if (this.state > STATE_INITED)
{
utils.invokeCallback(cb, new Error('application has already start.'));
return;
}
let self = this;
appUtil.startByType(self, function ()
{
appUtil.loadDefaultComponents(self);
let startUp = function ()
{
appUtil.optComponents(self.loaded, Constants.RESERVED.START, function (err)
{
self.state = STATE_START;
if (err)
{
utils.invokeCallback(cb, err);
} else
{
logger.info('%j enter after start...', self.getServerId());
self.afterStart(cb);
}
});
};
appUtil.optLifecycles(self.usedPlugins, Constants.LIFECYCLE.BEFORE_STARTUP, self, function (err)
{
if (err)
{
utils.invokeCallback(cb, err);
} else
{
startUp();
}
});
});
};
/**
* Lifecycle callback for after start.
*
* @param {Function} cb callback function
* @return {Void}
*/
afterStart(cb ?: (err?:Error)=>void)
{
if (this.state !== STATE_START)
{
utils.invokeCallback(cb, new Error('application is not running now.'));
return;
}
let self = this;
appUtil.optComponents(this.loaded, Constants.RESERVED.AFTER_START, function (err)
{
self.state = STATE_STARTED;
let id = self.getServerId();
if (!err)
{
logger.info('%j finish start', id);
}
appUtil.optLifecycles(self.usedPlugins, Constants.LIFECYCLE.AFTER_STARTUP, self, cb);
let usedTime = Date.now() - self.startTime;
logger.info('%j startup in %s ms', id, usedTime);
self.event.emit(events.START_SERVER, id);
});
};
/**
* Stop components.
*
* @param {Boolean} force whether stop the app immediately
*/
stop(force : boolean)
{
if (this.state > STATE_STARTED)
{
logger.warn('[pinus application] application is not running now.');
return;
}
this.state = STATE_STOPED;
let self = this;
this.stopTimer = setTimeout(function ()
{
process.exit(0);
}, Constants.TIME.TIME_WAIT_STOP);
let cancelShutDownTimer = function ()
{
if (!!self.stopTimer)
{
clearTimeout(self.stopTimer);
}
};
let shutDown = function ()
{
appUtil.stopComps(self.loaded, 0, force, function ()
{
cancelShutDownTimer();
if (force)
{
process.exit(0);
}
});
};
let fun = this.get(Constants.KEYWORDS.BEFORE_STOP_HOOK);
appUtil.optLifecycles(self.usedPlugins, Constants.LIFECYCLE.BEFORE_SHUTDOWN, self, function (err)
{
if (err)
{
console.error(`throw err when beforeShutdown ` , err.stack);
} else
{
if (!!fun)
{
utils.invokeCallback(fun, self, shutDown, cancelShutDownTimer);
} else
{
shutDown();
}
}
}, cancelShutDownTimer);
};
/**
* Assign `setting` to `val`, or return `setting`'s value.
*
* Example:
*
* app.set('key1', 'value1');
* app.get('key1'); // 'value1'
* app.key1; // undefined
*
* app.set('key2', 'value2', true);
* app.get('key2'); // 'value2'
* app.key2; // 'value2'
*
* @param {String} setting the setting of application
* @param {String} val the setting's value
* @param {Boolean} attach whether attach the settings to application
* @return {Server|Mixed} for chaining, or the setting value
* @memberOf Application
*/
set(setting: "channelService", val: ChannelService, attach?: boolean): Application;
set(setting: "sessionService", val: SessionService, attach?: boolean): Application;
set(setting: "channelConfig", val: ChannelServiceOptions, attach?: boolean): Application;
set(setting: "backendSessionService", val: BackendSessionComponent, attach?: boolean): Application;
set(setting: Constants.KEYWORDS.BEFORE_FILTER, val : BeforeHandlerFilter[], attach?: boolean): Application;
set(setting: Constants.KEYWORDS.AFTER_FILTER, val : AfterHandlerFilter[], attach?: boolean): Application;
set(setting: Constants.KEYWORDS.GLOBAL_BEFORE_FILTER, val : BeforeHandlerFilter[], attach?: boolean): Application;
set(setting: Constants.KEYWORDS.GLOBAL_AFTER_FILTER, val : AfterHandlerFilter[], attach?: boolean): Application;
set(setting: Constants.KEYWORDS.RPC_BEFORE_FILTER, val : RpcFilter | RpcFilter[], attach?: boolean): Application;
set(setting: Constants.KEYWORDS.RPC_AFTER_FILTER, val :RpcFilter | RpcFilter[], attach?: boolean): Application;
set(setting: Constants.RESERVED.RPC_ERROR_HANDLER, val : MailStationErrorHandler, attach?: boolean): Application;
set(setting: Constants.KEYWORDS.ROUTE, val : RouteMaps, attach?: boolean): Application;
set(setting: Constants.KEYWORDS.BEFORE_STOP_HOOK, val : BeforeStopHookFunction, attach?: boolean): Application;
set(setting: Constants.RESERVED.BASE, val : string, attach?: boolean): Application;
set(setting: Constants.RESERVED.ENV, val : string, attach?: boolean): Application;
set(setting: Constants.KEYWORDS.MODULE, val :{[key:string]:ModuleRecord}, attach?: boolean): Application;
set(setting: string, val: string | any, attach?: boolean): Application;
set(setting: string, val: string | any, attach?: boolean): Application
{
this.settings[setting] = val;
if(attach)
{
(this as any)[setting] = val;
}
return this;
};
/**
* Get property from setting
*
* @param {String} setting application setting
* @return {String} val
* @memberOf Application
*/
get(setting: "channelService"): ChannelService;
get(setting: "sessionService"): SessionService;
get(setting: "channelConfig"): ChannelServiceOptions;
get(setting: "backendSessionService"): BackendSessionComponent;
get(setting: Constants.KEYWORDS.BEFORE_FILTER): BeforeHandlerFilter[];
get(setting: Constants.KEYWORDS.AFTER_FILTER): AfterHandlerFilter[];
get(setting: Constants.KEYWORDS.GLOBAL_BEFORE_FILTER): BeforeHandlerFilter[];
get(setting: Constants.KEYWORDS.GLOBAL_AFTER_FILTER): AfterHandlerFilter[];
get(setting: Constants.KEYWORDS.RPC_BEFORE_FILTER): RpcFilter | RpcFilter[];
get(setting: Constants.KEYWORDS.RPC_AFTER_FILTER): RpcFilter | RpcFilter[];
get(setting: Constants.RESERVED.RPC_ERROR_HANDLER): MailStationErrorHandler;
get(setting: Constants.KEYWORDS.ROUTE): RouteMaps
get(setting: Constants.KEYWORDS.BEFORE_STOP_HOOK): BeforeStopHookFunction
get(setting: Constants.RESERVED.BASE): string;
get(setting: Constants.RESERVED.ENV): string;
get(setting: Constants.KEYWORDS.MODULE): {[key:string]:ModuleRecord};
get(setting: string): string | any;
get(setting: string): string | any
{
return this.settings[setting];
};
/**
* Check if `setting` is enabled.
*
* @param {String} setting application setting
* @return {Boolean}
* @memberOf Application
*/
enabled(setting : string)
{
return !!this.get(setting);
};
/**
* Check if `setting` is disabled.
*
* @param {String} setting application setting
* @return {Boolean}
* @memberOf Application
*/
disabled(setting : string)
{
return !this.get(setting);
};
/**
* Enable `setting`.
*
* @param {String} setting application setting
* @return {app} for chaining
* @memberOf Application
*/
enable(setting : string)
{
return this.set(setting, true);
};
/**
* Disable `setting`.
*
* @param {String} setting application setting
* @return {app} for chaining
* @memberOf Application
*/
disable(setting : string)
{
return this.set(setting, false);
};
/**
* Configure callback for the specified env and server type.
* When no env is specified that callback will
* be invoked for all environments and when no type is specified
* that callback will be invoked for all server types.
*
* Examples:
*
* app.configure(function(){
* // executed for all envs and server types
* });
*
* app.configure('development', function(){
* // executed development env
* });
*
* app.configure('development', 'connector', function(){
* // executed for development env and connector server type
* });
*
* @param {String} env application environment
* @param {Function} fn callback function
* @param {String} type server type
* @return {Application} for chaining
* @memberOf Application
*/
configure(fn : ConfigureCallback):Application;
configure(env : string, fn : ConfigureCallback):Application;
configure(env : string, type : string, fn : ConfigureCallback):Application
configure(env : string | ConfigureCallback, type ?: string | ConfigureCallback, fn ?: ConfigureCallback):Application
{
let args = [].slice.call(arguments);
fn = args.pop();
env = type = Constants.RESERVED.ALL;
if (args.length > 0)
{
env = args[0];
}
if (args.length > 1)
{
type = args[1];
}
if (env === Constants.RESERVED.ALL || contains(this.settings.env, env as string))
{
if (type === Constants.RESERVED.ALL || contains(this.settings.serverType, type as string))
{
fn.call(this);
}
}
return this;
};
/**
* Register admin modules. Admin modules is the extends point of the monitor system.
*
* @param {String} module (optional) module id or provoided by module.moduleId
* @param {Object} module module object or factory function for module
* @param {Object} opts construct parameter for module
* @memberOf Application
*/
registerAdmin(module : IModule, opts ?: any):void;
registerAdmin(moduleId : string, module ?: IModule, opts ?: any):void;
registerAdmin(module : IModuleFactory, opts ?: any):void;
registerAdmin(moduleId : string, module ?: IModuleFactory, opts ?: any):void;
registerAdmin(moduleId : string | IModule | IModuleFactory, module ?: IModule | IModuleFactory, opts ?: any)
{
let modules = this.get(Constants.KEYWORDS.MODULE);
if (!modules)
{
modules = {};
this.set(Constants.KEYWORDS.MODULE, modules);
}
if (typeof moduleId !== 'string')
{
opts = module;
module = moduleId;
if (module)
{
moduleId = ((module as IModuleFactory).moduleId);
if(!moduleId)
moduleId = (module as IModule).constructor.name;
}
}
if (!moduleId)
{
return;
}
modules[moduleId as string] = {
moduleId: moduleId as string,
module: module,
opts: opts
};
};
/**
* Use plugin.
*
* @param {Object} plugin plugin instance
* @param {[type]} opts (optional) construct parameters for the factory function
* @memberOf Application
*/
use(plugin : IPlugin, opts ?: any)
{
opts = opts || {};
if (!plugin)
{
throw new Error(`pluin is null!]`);
}
if (this.usedPlugins.indexOf(plugin) >= 0)
{
throw new Error(`pluin[${plugin.name} was used already!]`);
}
if(plugin.components)
{
for(let componentCtor of plugin.components)
{
this.load(componentCtor, opts);
}
}
if(plugin.events)
{
for(let eventCtor of plugin.events)
{
this.loadEvent(eventCtor, opts);
}
}
this.usedPlugins.push(plugin);
console.warn(`used Plugin : ${plugin.name}`);
};
/**
* Application transaction. Transcation includes conditions and handlers, if conditions are satisfied, handlers would be executed.
* And you can set retry times to execute handlers. The transaction log is in file logs/transaction.log.
*
* @param {String} name transaction name
* @param {Object} conditions functions which are called before transaction
* @param {Object} handlers functions which are called during transaction
* @param {Number} retry retry times to execute handlers if conditions are successfully executed
* @memberOf Application
*/
transaction(name : string, conditions : TransactionCondictionFunction[], handlers : TransactionHandlerFunction[], retry: number)
{
appManager.transaction(name, conditions, handlers, retry);
};
/**
* Get master server info.
*
* @return {Object} master server info, {id, host, port}
* @memberOf Application
*/
getMaster()
{
return this.master;
};
/**
* Get current server info.
*
* @return {Object} current server info, {id, serverType, host, port}
* @memberOf Application
*/
getCurServer()
{
return this.curServer;
};
/**
* Get current server id.
*
* @return {String|Number} current server id from servers.json
* @memberOf Application
*/
getServerId()
{
return this.serverId;
};
/**
* Get current server
* @returns ServerInfo
*/
getCurrentServer()
{
return this.curServer;
}
/**
* Get current server type.
*
* @return {String|Number} current server type from servers.json
* @memberOf Application
*/
getServerType()
{
return this.serverType;
};
/**
* Get all the current server infos.
*
* @return {Object} server info map, key: server id, value: server info
* @memberOf Application
*/
getServers()
{
return this.servers;
};
/**
* Get all server infos from servers.json.
*
* @return {Object} server info map, key: server id, value: server info
* @memberOf Application
*/
getServersFromConfig()
{
return this.get(Constants.KEYWORDS.SERVER_MAP);
};
/**
* Get all the server type.
*
* @return {Array} server type list
* @memberOf Application
*/
getServerTypes()
{
return this.serverTypes;
};
/**
* Get server info by server id from current server cluster.
*
* @param {String} serverId server id
* @return {Object} server info or undefined
* @memberOf Application
*/
getServerById(serverId : string)
{
return this.servers[serverId];
};
/**
* Get server info by server id from servers.json.
*
* @param {String} serverId server id
* @return {Object} server info or undefined
* @memberOf Application
*/
getServerFromConfig(serverId : string)
{
return this.get(Constants.KEYWORDS.SERVER_MAP)[serverId];
};
/**
* Get server infos by server type.
*
* @param {String} serverType server type
* @return {Array} server info list
* @memberOf Application
*/
getServersByType(serverType: string)