@midwayjs/core 4.0.0-alpha.1 → 4.0.0-beta.2

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 (59) hide show
  1. package/README.md +1 -1
  2. package/dist/baseFramework.d.ts +7 -4
  3. package/dist/baseFramework.js +12 -10
  4. package/dist/common/applicationManager.js +5 -1
  5. package/dist/common/dataListener.d.ts +5 -3
  6. package/dist/common/dataListener.js +12 -3
  7. package/dist/common/dataSourceManager.d.ts +18 -9
  8. package/dist/common/dataSourceManager.js +121 -71
  9. package/dist/common/serviceDiscovery/healthCheck.d.ts +66 -0
  10. package/dist/common/serviceDiscovery/healthCheck.js +207 -0
  11. package/dist/common/serviceDiscovery/loadBalancer.d.ts +21 -0
  12. package/dist/common/serviceDiscovery/loadBalancer.js +51 -0
  13. package/dist/common/serviceDiscovery/serviceDiscovery.d.ts +59 -0
  14. package/dist/common/serviceDiscovery/serviceDiscovery.js +104 -0
  15. package/dist/common/serviceFactory.d.ts +5 -2
  16. package/dist/common/serviceFactory.js +43 -8
  17. package/dist/config/config.default.js +3 -0
  18. package/dist/context/container.d.ts +4 -3
  19. package/dist/context/container.js +6 -2
  20. package/dist/context/definitionRegistry.d.ts +2 -0
  21. package/dist/context/definitionRegistry.js +9 -11
  22. package/dist/context/dynamicContainer.d.ts +17 -0
  23. package/dist/context/dynamicContainer.js +202 -0
  24. package/dist/context/managedResolverFactory.d.ts +1 -2
  25. package/dist/context/managedResolverFactory.js +14 -7
  26. package/dist/context/requestContainer.d.ts +1 -0
  27. package/dist/context/requestContainer.js +3 -0
  28. package/dist/decorator/metadataManager.d.ts +6 -2
  29. package/dist/definitions/objectCreator.js +3 -1
  30. package/dist/error/framework.d.ts +1 -1
  31. package/dist/error/framework.js +4 -2
  32. package/dist/error/http.d.ts +7 -0
  33. package/dist/error/http.js +11 -1
  34. package/dist/functional/configuration.d.ts +6 -6
  35. package/dist/functional/configuration.js +10 -10
  36. package/dist/functional/hooks.d.ts +3 -1
  37. package/dist/functional/hooks.js +11 -1
  38. package/dist/index.d.ts +5 -1
  39. package/dist/index.js +8 -2
  40. package/dist/interface.d.ts +180 -20
  41. package/dist/interface.js +15 -1
  42. package/dist/service/configService.d.ts +1 -1
  43. package/dist/service/configService.js +3 -2
  44. package/dist/service/healthService.d.ts +2 -0
  45. package/dist/service/healthService.js +15 -4
  46. package/dist/service/informationService.d.ts +3 -0
  47. package/dist/service/informationService.js +10 -0
  48. package/dist/service/lifeCycleService.d.ts +13 -7
  49. package/dist/service/lifeCycleService.js +49 -32
  50. package/dist/setup.js +8 -1
  51. package/dist/util/index.d.ts +2 -17
  52. package/dist/util/index.js +8 -67
  53. package/dist/util/network.d.ts +10 -0
  54. package/dist/util/network.js +40 -0
  55. package/dist/util/pathFileUtil.d.ts +1 -1
  56. package/dist/util/pathFileUtil.js +2 -2
  57. package/dist/util/timeout.d.ts +57 -0
  58. package/dist/util/timeout.js +144 -0
  59. package/package.json +4 -4
@@ -1,4 +1,5 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
2
3
  import type { AsyncContextManager } from './common/asyncContextManager';
3
4
  import type { LoggerFactory } from './common/loggerFactory';
4
5
  import type { ManagedResolverFactory } from './context/managedResolverFactory';
@@ -382,6 +383,10 @@ export interface MidwayCoreDefaultConfig {
382
383
  };
383
384
  core?: {
384
385
  healthCheckTimeout?: number;
386
+ configLoadTimeout?: number;
387
+ readyTimeout?: number;
388
+ serverReadyTimeout?: number;
389
+ stopTimeout?: number;
385
390
  };
386
391
  }
387
392
  export type ServiceFactoryConfigOption<OPTIONS> = {
@@ -397,38 +402,44 @@ export type ServiceFactoryConfigOption<OPTIONS> = {
397
402
  };
398
403
  export type CreateDataSourceInstanceOptions = {
399
404
  /**
400
- * @default false
405
+ * @deprecated
401
406
  */
402
407
  validateConnection?: boolean;
403
408
  /**
404
- * @default true
409
+ * @deprecated
405
410
  */
406
411
  cacheInstance?: boolean | undefined;
407
412
  };
408
- export type DataSourceManagerConfigOption<OPTIONS, ENTITY_CONFIG_KEY extends string = 'entities'> = {
409
- default?: OPTIONS;
413
+ export type BaseDataSourceManagerConfigOption<OPTIONS extends Record<string, any>, ENTITY_CONFIG_KEY extends string = 'entities'> = OPTIONS & {
414
+ validateConnection?: boolean;
415
+ customDataSourceClass?: any;
416
+ } & {
417
+ [key in ENTITY_CONFIG_KEY]?: any[];
418
+ };
419
+ export interface DataSourceManagerConfigOption<OPTIONS extends Record<string, any>, ENTITY_CONFIG_KEY extends string = 'entities'> extends CreateDataSourceInstanceOptions {
420
+ default?: BaseDataSourceManagerConfigOption<OPTIONS, ENTITY_CONFIG_KEY>;
410
421
  defaultDataSourceName?: string;
411
- dataSource?: {
412
- [key: string]: PowerPartial<{
413
- [keyName in ENTITY_CONFIG_KEY]: any[];
414
- }> & OPTIONS;
415
- };
416
- } & CreateDataSourceInstanceOptions;
422
+ dataSource?: BaseDataSourceManagerConfigOption<OPTIONS, ENTITY_CONFIG_KEY>;
423
+ }
417
424
  type ConfigType<T> = T extends (...args: any[]) => any ? Writable<PowerPartial<ReturnType<T>>> : Writable<PowerPartial<T>>;
418
425
  /**
419
426
  * Get definition from config
420
427
  */
421
428
  export type FileConfigOption<T, K = unknown> = K extends keyof ConfigType<T> ? Pick<ConfigType<T>, K> : ConfigType<T>;
429
+ export interface LifeCycleInvokeOptions {
430
+ abortController: AbortController;
431
+ timeout: number;
432
+ }
422
433
  /**
423
434
  * Lifecycle Definition
424
435
  * 生命周期定义
425
436
  */
426
437
  export interface ILifeCycle extends Partial<IObjectLifeCycle> {
427
- onConfigLoad?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<any>;
428
- onReady?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<void>;
429
- onServerReady?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<void>;
430
- onHealthCheck?(container: IMidwayContainer): Promise<HealthResult>;
431
- onStop?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<void>;
438
+ onConfigLoad?(container: IMidwayContainer, mainApp: IMidwayApplication, options: LifeCycleInvokeOptions): Promise<any>;
439
+ onReady?(container: IMidwayContainer, mainApp: IMidwayApplication, options: LifeCycleInvokeOptions): Promise<void>;
440
+ onServerReady?(container: IMidwayContainer, mainApp: IMidwayApplication, options: LifeCycleInvokeOptions): Promise<void>;
441
+ onHealthCheck?(container: IMidwayContainer, mainApp: IMidwayApplication, options: LifeCycleInvokeOptions): Promise<HealthResult>;
442
+ onStop?(container: IMidwayContainer, mainApp: IMidwayApplication, options: LifeCycleInvokeOptions): Promise<void>;
432
443
  }
433
444
  /**
434
445
  * Abstract Object Factory
@@ -544,6 +555,7 @@ export interface IObjectDefinitionRegistry {
544
555
  clearAll(): void;
545
556
  hasObject(identifier: ObjectIdentifier): boolean;
546
557
  registerObject(identifier: ObjectIdentifier, target: any): any;
558
+ removeObject(identifier: ObjectIdentifier): void;
547
559
  getObject(identifier: ObjectIdentifier): any;
548
560
  getIdentifierRelation(): IIdentifierRelationShip;
549
561
  setIdentifierRelation(identifierRelation: IIdentifierRelationShip): any;
@@ -581,8 +593,8 @@ export interface IMidwayGlobalContainer extends IMidwayContainer, WithFn<IObject
581
593
  objectCreateEventTarget: EventEmitter;
582
594
  getNamespaceList(): string[];
583
595
  addNamespace(namespace: string): void;
584
- bind<T>(target: T, options?: Partial<IObjectDefinition>): void;
585
- bind<T>(identifier: ObjectIdentifier, target: T, options?: Partial<IObjectDefinition>): void;
596
+ bind<T>(target: T, options?: Partial<IObjectDefinition>): IObjectDefinition | undefined;
597
+ bind<T>(identifier: ObjectIdentifier, target: T, options?: Partial<IObjectDefinition>): IObjectDefinition | undefined;
586
598
  bindClass(exports: any, options?: Partial<IObjectDefinition>): void;
587
599
  stop(): Promise<void>;
588
600
  getManagedResolverFactory(): ManagedResolverFactory;
@@ -597,6 +609,7 @@ export interface IMidwayContainer extends IObjectFactory {
597
609
  getDefinition(identifier: ObjectIdentifier): IObjectDefinition;
598
610
  hasObject(identifier: ObjectIdentifier): boolean;
599
611
  getObject<T>(identifier: ObjectIdentifier): T;
612
+ removeObject(identifier: ObjectIdentifier): void;
600
613
  /**
601
614
  * Set value to app attribute map
602
615
  * @param key
@@ -759,7 +772,7 @@ export interface IMidwayBaseApplication<CTX extends IMidwayContext> {
759
772
  * Get all configuration values or get the specified configuration through parameters
760
773
  * @param key config key
761
774
  */
762
- getConfig(key?: string): any;
775
+ getConfig<T = any>(key?: string): T;
763
776
  /**
764
777
  * Get default logger object or get the specified logger through parameters
765
778
  * @param name
@@ -832,7 +845,6 @@ export interface IMidwayBaseApplication<CTX extends IMidwayContext> {
832
845
  export type IMidwayApplication<T extends IMidwayContext = IMidwayContext, FrameworkApplication = unknown> = IMidwayBaseApplication<T> & FrameworkApplication;
833
846
  export type ModuleLoadType = 'commonjs' | 'esm';
834
847
  export interface IMidwayBootstrapOptions {
835
- [customPropertyKey: string]: any;
836
848
  baseDir?: string;
837
849
  appDir?: string;
838
850
  applicationContext?: IMidwayGlobalContainer;
@@ -857,7 +869,7 @@ export interface IMidwayFramework<APP extends IMidwayApplication<CTX>, CTX exten
857
869
  configurationOptions: CONFIG;
858
870
  configure(options?: CONFIG): CONFIG;
859
871
  isEnable(): boolean;
860
- initialize(options: Partial<IMidwayBootstrapOptions>): Promise<void>;
872
+ initialize(options: IMidwayBootstrapOptions): Promise<void>;
861
873
  run(): Promise<void>;
862
874
  stop(): Promise<void>;
863
875
  getApplication(): APP;
@@ -878,6 +890,7 @@ export interface IMidwayFramework<APP extends IMidwayApplication<CTX>, CTX exten
878
890
  useGuard(guard: CommonGuardUnion<CTX>): void;
879
891
  runGuard(ctx: CTX, supplierClz: new (...args: any[]) => any, methodName: string): Promise<boolean>;
880
892
  getNamespace(): string;
893
+ setFrameworkLoggerName(name: string): void;
881
894
  }
882
895
  export interface MidwayAppInfo {
883
896
  pkg: Record<string, any>;
@@ -908,6 +921,20 @@ export interface IServiceFactory<Client> {
908
921
  isMediumPriority(clientName: string): boolean;
909
922
  isLowPriority(clientName: string): boolean;
910
923
  }
924
+ export interface IDataSourceManager<DataSource, DataSourceConfig> {
925
+ createInstance(config: DataSourceConfig): Promise<DataSource | void>;
926
+ getDataSource(dataSourceName: string): DataSource;
927
+ getDataSourceNames(): string[];
928
+ getAllDataSources(): Map<string, DataSource>;
929
+ hasDataSource(dataSourceName: string): boolean;
930
+ isConnected(dataSourceName: string): Promise<boolean>;
931
+ getDefaultDataSourceName(): string;
932
+ stop(): Promise<void>;
933
+ getDataSourcePriority(dataSourceName: string): string;
934
+ isHighPriority(dataSourceName: string): boolean;
935
+ isMediumPriority(dataSourceName: string): boolean;
936
+ isLowPriority(dataSourceName: string): boolean;
937
+ }
911
938
  export interface ISimulation {
912
939
  setup?(): Promise<void>;
913
940
  tearDown?(): Promise<void>;
@@ -978,5 +1005,138 @@ export interface InjectionConfigurationOptions {
978
1005
  detector?: IFileDetector | false;
979
1006
  }
980
1007
  export type FunctionalConfigurationOptions = InjectionConfigurationOptions & ILifeCycle;
1008
+ /**
1009
+ * 负载均衡策略类型
1010
+ */
1011
+ export declare const LoadBalancerType: {
1012
+ readonly RANDOM: "random";
1013
+ readonly ROUND_ROBIN: "roundRobin";
1014
+ };
1015
+ export type LoadBalancerType = typeof LoadBalancerType[keyof typeof LoadBalancerType];
1016
+ export declare const ServiceDiscoveryHealthCheckType: {
1017
+ readonly SELF: "self";
1018
+ readonly TTL: "ttl";
1019
+ readonly HTTP: "http";
1020
+ readonly TCP: "tcp";
1021
+ readonly CUSTOM: "custom";
1022
+ };
1023
+ export type ServiceDiscoveryHealthCheckType = typeof ServiceDiscoveryHealthCheckType[keyof typeof ServiceDiscoveryHealthCheckType];
1024
+ /**
1025
+ * 基础健康检查配置
1026
+ */
1027
+ export interface BaseServiceDiscoveryHealthCheckOptions {
1028
+ /**
1029
+ * 检查间隔(毫秒)
1030
+ */
1031
+ interval?: number;
1032
+ /**
1033
+ * 检查超时时间(毫秒)
1034
+ */
1035
+ timeout?: number;
1036
+ /**
1037
+ * 最大重试次数
1038
+ */
1039
+ maxRetries?: number;
1040
+ /**
1041
+ * 重试间隔(毫秒)
1042
+ */
1043
+ retryInterval?: number;
1044
+ }
1045
+ /**
1046
+ * TTL 健康检查配置
1047
+ */
1048
+ export interface TTLServiceDiscoveryHealthCheckOptions extends BaseServiceDiscoveryHealthCheckOptions {
1049
+ /**
1050
+ * TTL 时间(秒)
1051
+ */
1052
+ ttl: number;
1053
+ }
1054
+ /**
1055
+ * HTTP 健康检查配置
1056
+ */
1057
+ export interface HTTPServiceDiscoveryHealthCheckOptions extends BaseServiceDiscoveryHealthCheckOptions {
1058
+ /**
1059
+ * 健康检查 URL
1060
+ */
1061
+ url: string;
1062
+ /**
1063
+ * HTTP 方法
1064
+ */
1065
+ method?: string;
1066
+ /**
1067
+ * HTTP 请求头
1068
+ */
1069
+ headers?: Record<string, string>;
1070
+ /**
1071
+ * 期望的 HTTP 状态码
1072
+ */
1073
+ expectedStatus?: number;
1074
+ }
1075
+ /**
1076
+ * TCP 健康检查配置
1077
+ */
1078
+ export interface TCPServiceDiscoveryHealthCheckOptions extends BaseServiceDiscoveryHealthCheckOptions {
1079
+ /**
1080
+ * 主机地址
1081
+ */
1082
+ host: string;
1083
+ /**
1084
+ * 端口号
1085
+ */
1086
+ port: number;
1087
+ }
1088
+ /**
1089
+ * 健康检查配置联合类型
1090
+ */
1091
+ export type ServiceDiscoveryHealthCheckOptions = TTLServiceDiscoveryHealthCheckOptions | HTTPServiceDiscoveryHealthCheckOptions | TCPServiceDiscoveryHealthCheckOptions;
1092
+ export interface ServiceDiscoveryBaseInstance {
1093
+ }
1094
+ export interface DefaultInstanceMetadata {
1095
+ id: string;
1096
+ serviceName: string;
1097
+ host: string;
1098
+ port: number;
1099
+ metadata: Record<string, any>;
1100
+ }
1101
+ /**
1102
+ * 健康检查结果
1103
+ */
1104
+ export interface ServiceDiscoveryHealthCheckResult {
1105
+ status: 'passing' | 'warning' | 'critical' | 'unknown';
1106
+ message?: string;
1107
+ timestamp: number;
1108
+ }
1109
+ export interface IServiceDiscoveryHealthCheck<ServiceInstance> {
1110
+ check(instance: ServiceInstance): Promise<ServiceDiscoveryHealthCheckResult>;
1111
+ }
1112
+ export interface ServiceDiscoveryOptions<ServiceInstance, serviceOptions = Record<string, any>> {
1113
+ serviceDiscoveryClient?: string;
1114
+ serviceOptions?: serviceOptions;
1115
+ loadBalancer?: LoadBalancerType | ILoadBalancer<ServiceInstance>;
1116
+ }
1117
+ /**
1118
+ * 负载均衡策略接口
1119
+ */
1120
+ export interface ILoadBalancer<ServiceInstance> {
1121
+ /**
1122
+ * 从服务实例列表中选择一个实例
1123
+ * @param instances 服务实例列表
1124
+ */
1125
+ select(instances: ServiceInstance[]): ServiceInstance;
1126
+ }
1127
+ export interface IServiceDiscoveryClient<ServiceInstance> {
1128
+ /**
1129
+ * 注册服务实例
1130
+ */
1131
+ register(instance: unknown): Promise<void>;
1132
+ /**
1133
+ * 上线服务实例
1134
+ */
1135
+ online(): Promise<void>;
1136
+ /**
1137
+ * 下线服务实例
1138
+ */
1139
+ offline(): Promise<void>;
1140
+ }
981
1141
  export {};
982
1142
  //# sourceMappingURL=interface.d.ts.map
package/dist/interface.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MidwayProcessTypeEnum = exports.ObjectLifeCycleEvent = exports.ServerlessTriggerType = exports.MSListenerType = exports.MSProviderType = exports.InjectModeEnum = exports.ScopeEnum = void 0;
3
+ exports.ServiceDiscoveryHealthCheckType = exports.LoadBalancerType = exports.MidwayProcessTypeEnum = exports.ObjectLifeCycleEvent = exports.ServerlessTriggerType = exports.MSListenerType = exports.MSProviderType = exports.InjectModeEnum = exports.ScopeEnum = void 0;
4
4
  var ScopeEnum;
5
5
  (function (ScopeEnum) {
6
6
  ScopeEnum["Singleton"] = "Singleton";
@@ -53,4 +53,18 @@ var MidwayProcessTypeEnum;
53
53
  MidwayProcessTypeEnum["APPLICATION"] = "APPLICATION";
54
54
  MidwayProcessTypeEnum["AGENT"] = "AGENT";
55
55
  })(MidwayProcessTypeEnum || (exports.MidwayProcessTypeEnum = MidwayProcessTypeEnum = {}));
56
+ /**
57
+ * 负载均衡策略类型
58
+ */
59
+ exports.LoadBalancerType = {
60
+ RANDOM: 'random',
61
+ ROUND_ROBIN: 'roundRobin',
62
+ };
63
+ exports.ServiceDiscoveryHealthCheckType = {
64
+ SELF: 'self',
65
+ TTL: 'ttl',
66
+ HTTP: 'http',
67
+ TCP: 'tcp',
68
+ CUSTOM: 'custom'
69
+ };
56
70
  //# sourceMappingURL=interface.js.map
@@ -23,7 +23,7 @@ export declare class MidwayConfigService implements IConfigService {
23
23
  private getEnvSet;
24
24
  private getConfigEnv;
25
25
  load(): void;
26
- getConfiguration(configKey?: string): any;
26
+ getConfiguration<T = any>(configKey?: string, defaultValue?: any): T;
27
27
  getConfigMergeOrder(): Array<ConfigMergeInfo>;
28
28
  private loadConfig;
29
29
  clearAllConfig(): void;
@@ -179,9 +179,10 @@ let MidwayConfigService = class MidwayConfigService {
179
179
  this.configuration = target;
180
180
  this.isReady = true;
181
181
  }
182
- getConfiguration(configKey) {
182
+ getConfiguration(configKey, defaultValue) {
183
183
  if (configKey) {
184
- return (0, util_1.safelyGet)(configKey, this.configuration);
184
+ const res = (0, util_1.safelyGet)(configKey, this.configuration);
185
+ return res === undefined ? defaultValue : res;
185
186
  }
186
187
  return this.configuration;
187
188
  }
@@ -1,7 +1,9 @@
1
1
  import { HealthResults, IMidwayContainer } from '../interface';
2
2
  import { MidwayConfigService } from './configService';
3
+ import { MidwayFrameworkService } from './frameworkService';
3
4
  export declare class MidwayHealthService {
4
5
  protected configService: MidwayConfigService;
6
+ protected frameworkService: MidwayFrameworkService;
5
7
  protected applicationContext: IMidwayContainer;
6
8
  private healthCheckTimeout;
7
9
  private healthCheckMethods;
@@ -13,7 +13,8 @@ exports.MidwayHealthService = void 0;
13
13
  const decorator_1 = require("../decorator");
14
14
  const interface_1 = require("../interface");
15
15
  const configService_1 = require("./configService");
16
- const util_1 = require("../util");
16
+ const timeout_1 = require("../util/timeout");
17
+ const frameworkService_1 = require("./frameworkService");
17
18
  let MidwayHealthService = class MidwayHealthService {
18
19
  constructor() {
19
20
  this.healthCheckTimeout = 1000;
@@ -35,14 +36,20 @@ let MidwayHealthService = class MidwayHealthService {
35
36
  }
36
37
  }
37
38
  async getStatus() {
38
- const checkResult = await (0, util_1.createPromiseTimeoutInvokeChain)({
39
+ const checkResult = await (0, timeout_1.createPromiseTimeoutInvokeChain)({
39
40
  promiseItems: this.healthCheckMethods.map(item => {
40
41
  return {
41
- item: item.item(this.applicationContext),
42
+ item: ab => {
43
+ return item.item(this.applicationContext, this.frameworkService.getMainApp(), {
44
+ abortController: ab,
45
+ timeout: this.healthCheckTimeout,
46
+ });
47
+ },
42
48
  meta: item.meta,
49
+ itemName: item.meta.namespace,
43
50
  };
44
51
  }),
45
- timeout: this.healthCheckTimeout,
52
+ itemTimeout: this.healthCheckTimeout,
46
53
  methodName: 'configuration.onHealthCheck',
47
54
  onSuccess: (result, meta) => {
48
55
  if (result['status'] !== undefined) {
@@ -84,6 +91,10 @@ __decorate([
84
91
  (0, decorator_1.Inject)(),
85
92
  __metadata("design:type", configService_1.MidwayConfigService)
86
93
  ], MidwayHealthService.prototype, "configService", void 0);
94
+ __decorate([
95
+ (0, decorator_1.Inject)(),
96
+ __metadata("design:type", frameworkService_1.MidwayFrameworkService)
97
+ ], MidwayHealthService.prototype, "frameworkService", void 0);
87
98
  __decorate([
88
99
  (0, decorator_1.ApplicationContext)(),
89
100
  __metadata("design:type", Object)
@@ -10,5 +10,8 @@ export declare class MidwayInformationService implements IInformationService {
10
10
  getPkg(): any;
11
11
  getProjectName(): string;
12
12
  getRoot(): string;
13
+ getHostname(): string;
14
+ getIpv4Address(): string;
15
+ getIpv6Address(): string;
13
16
  }
14
17
  //# sourceMappingURL=informationService.d.ts.map
@@ -15,6 +15,7 @@ const util_1 = require("../util");
15
15
  const path_1 = require("path");
16
16
  const decorator_1 = require("../decorator");
17
17
  const fs_1 = require("fs");
18
+ const network_1 = require("../util/network");
18
19
  let MidwayInformationService = class MidwayInformationService {
19
20
  init() {
20
21
  if (this.baseDir) {
@@ -55,6 +56,15 @@ let MidwayInformationService = class MidwayInformationService {
55
56
  const isDevelopmentEnv = (0, util_1.isDevelopmentEnvironment)((0, util_1.getCurrentEnvironment)());
56
57
  return isDevelopmentEnv ? this.getAppDir() : this.getHome();
57
58
  }
59
+ getHostname() {
60
+ return network_1.NetworkUtils.getHostname();
61
+ }
62
+ getIpv4Address() {
63
+ return network_1.NetworkUtils.getIpv4Address();
64
+ }
65
+ getIpv6Address() {
66
+ return network_1.NetworkUtils.getIpv6Address();
67
+ }
58
68
  };
59
69
  exports.MidwayInformationService = MidwayInformationService;
60
70
  __decorate([
@@ -3,6 +3,11 @@ import { MidwayFrameworkService } from './frameworkService';
3
3
  import { MidwayConfigService } from './configService';
4
4
  import { MidwayMockService } from './mockService';
5
5
  import { MidwayHealthService } from './healthService';
6
+ type LifecycleInstanceItem = {
7
+ target: any;
8
+ namespace: string;
9
+ instance?: any;
10
+ };
6
11
  export declare class MidwayLifeCycleService {
7
12
  readonly applicationContext: IMidwayContainer;
8
13
  protected frameworkService: MidwayFrameworkService;
@@ -17,19 +22,20 @@ export declare class MidwayLifeCycleService {
17
22
  * run some lifecycle in configuration
18
23
  * @param lifecycleInstanceOrList
19
24
  * @param lifecycle
20
- * @param resultHandler
25
+ * @param runOptions
21
26
  */
22
- private runContainerLifeCycle;
27
+ protected runContainerLifeCycle(lifecycleInstanceOrList: LifecycleInstanceItem[], lifecycle: string, runOptions?: {
28
+ resultHandler?: (result: any) => void;
29
+ timeout?: number;
30
+ }): Promise<void>;
31
+ private runLifeCycle;
23
32
  /**
24
33
  * run object lifecycle
25
34
  * @param lifecycleInstanceList
26
35
  * @param lifecycle
27
36
  */
28
37
  private runObjectLifeCycle;
29
- getLifecycleInstanceList(): {
30
- target: any;
31
- namespace: string;
32
- instance?: any;
33
- }[];
38
+ getLifecycleInstanceList(): LifecycleInstanceItem[];
34
39
  }
40
+ export {};
35
41
  //# sourceMappingURL=lifeCycleService.d.ts.map
@@ -19,6 +19,7 @@ const mockService_1 = require("./mockService");
19
19
  const healthService_1 = require("./healthService");
20
20
  const metadataManager_1 = require("../decorator/metadataManager");
21
21
  const performanceManager_1 = require("../common/performanceManager");
22
+ const timeout_1 = require("../util/timeout");
22
23
  const debug = (0, util_1.debuglog)('midway:debug');
23
24
  let MidwayLifeCycleService = class MidwayLifeCycleService {
24
25
  constructor(applicationContext) {
@@ -55,18 +56,25 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
55
56
  // bind framework lifecycle
56
57
  // onAppError
57
58
  // exec onConfigLoad()
58
- await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onConfigLoad', configData => {
59
- if (configData) {
60
- this.configService.addObject(configData);
61
- }
59
+ await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onConfigLoad', {
60
+ resultHandler: configData => {
61
+ if (configData) {
62
+ this.configService.addObject(configData);
63
+ }
64
+ },
65
+ timeout: this.configService.getConfiguration('core.configLoadTimeout'),
62
66
  });
63
67
  await this.mockService.runSimulatorSetup();
64
68
  // exec onReady()
65
- await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onReady');
69
+ await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onReady', {
70
+ timeout: this.configService.getConfiguration('core.readyTimeout'),
71
+ });
66
72
  // exec framework.run()
67
73
  await this.frameworkService.runFramework();
68
74
  // exec onServerReady()
69
- await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onServerReady');
75
+ await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onServerReady', {
76
+ timeout: this.configService.getConfiguration('core.serverReadyTimeout'),
77
+ });
70
78
  // clear config merge cache
71
79
  if (!this.configService.getConfiguration('debug.recordConfigMergeOrder')) {
72
80
  this.configService.clearConfigMergeOrder();
@@ -75,7 +83,9 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
75
83
  async stop() {
76
84
  await this.mockService.runSimulatorTearDown();
77
85
  // stop lifecycle
78
- await this.runContainerLifeCycle(this.lifecycleInstanceList.reverse(), 'onStop');
86
+ await this.runContainerLifeCycle(this.lifecycleInstanceList.reverse(), 'onStop', {
87
+ timeout: this.configService.getConfiguration('core.stopTimeout'),
88
+ });
79
89
  // stop framework
80
90
  await this.frameworkService.stopFramework();
81
91
  }
@@ -83,33 +93,40 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
83
93
  * run some lifecycle in configuration
84
94
  * @param lifecycleInstanceOrList
85
95
  * @param lifecycle
86
- * @param resultHandler
96
+ * @param runOptions
87
97
  */
88
- async runContainerLifeCycle(lifecycleInstanceOrList, lifecycle, resultHandler) {
89
- if (Array.isArray(lifecycleInstanceOrList)) {
90
- for (const cycle of lifecycleInstanceOrList) {
91
- if (typeof cycle.instance[lifecycle] === 'function') {
92
- debug(`[core]: Lifecycle run ${cycle.instance.constructor.name} ${lifecycle}`);
93
- performanceManager_1.MidwayInitializerPerformanceManager.lifecycleStart(cycle.namespace, lifecycle);
94
- const result = await cycle.instance[lifecycle](this.applicationContext, this.frameworkService.getMainApp());
95
- if (resultHandler) {
96
- resultHandler(result);
97
- }
98
- performanceManager_1.MidwayInitializerPerformanceManager.lifecycleEnd(cycle.namespace, lifecycle);
99
- }
100
- }
101
- }
102
- else {
103
- if (typeof lifecycleInstanceOrList[lifecycle] === 'function') {
104
- const name = lifecycleInstanceOrList.constructor.name;
105
- debug(`[core]: Lifecycle run ${name} ${lifecycle}`);
106
- performanceManager_1.MidwayInitializerPerformanceManager.lifecycleStart(name, lifecycle);
107
- const result = await lifecycleInstanceOrList[lifecycle](this.applicationContext, this.frameworkService.getMainApp());
108
- if (resultHandler) {
109
- resultHandler(result);
110
- }
111
- performanceManager_1.MidwayInitializerPerformanceManager.lifecycleEnd(name, lifecycle);
98
+ async runContainerLifeCycle(lifecycleInstanceOrList, lifecycle, runOptions) {
99
+ await (0, timeout_1.createPromiseTimeoutInvokeChain)({
100
+ promiseItems: lifecycleInstanceOrList.map(cycle => {
101
+ return {
102
+ item: async (ab) => {
103
+ return this.runLifeCycle(cycle, lifecycle, {
104
+ ...runOptions,
105
+ abortController: ab,
106
+ });
107
+ },
108
+ meta: { namespace: cycle.namespace },
109
+ itemName: cycle.namespace,
110
+ };
111
+ }),
112
+ itemTimeout: runOptions?.timeout,
113
+ isConcurrent: false,
114
+ methodName: `configuration.${lifecycle}`,
115
+ });
116
+ }
117
+ async runLifeCycle(cycle, lifecycle, runOptions) {
118
+ if (typeof cycle.instance[lifecycle] === 'function') {
119
+ debug(`[core]: Lifecycle run ${cycle.instance.constructor.name} ${lifecycle}`);
120
+ performanceManager_1.MidwayInitializerPerformanceManager.lifecycleStart(cycle.namespace, lifecycle);
121
+ const result = await cycle.instance[lifecycle](this.applicationContext, this.frameworkService.getMainApp(), {
122
+ timeout: runOptions.timeout,
123
+ abortController: runOptions.abortController,
124
+ });
125
+ if (runOptions?.resultHandler) {
126
+ runOptions.resultHandler(result);
112
127
  }
128
+ performanceManager_1.MidwayInitializerPerformanceManager.lifecycleEnd(cycle.namespace, lifecycle);
129
+ return result;
113
130
  }
114
131
  }
115
132
  /**
package/dist/setup.js CHANGED
@@ -12,8 +12,9 @@ const asyncContextManager_1 = require("./common/asyncContextManager");
12
12
  const performanceManager_1 = require("./common/performanceManager");
13
13
  const debug = util.debuglog('midway:debug');
14
14
  let stepIdx = 1;
15
+ let projectIdx = 1;
15
16
  function printStepDebugInfo(stepInfo) {
16
- debug(`\n\nStep ${stepIdx++}: ${stepInfo}\n`);
17
+ debug(`\n\nProject ${projectIdx} - Step ${stepIdx++}: ${stepInfo}\n`);
17
18
  }
18
19
  /**
19
20
  * midway framework main entry, this method bootstrap all service and framework.
@@ -67,19 +68,25 @@ async function initializeGlobalApplicationContext(globalOptions) {
67
68
  }
68
69
  exports.initializeGlobalApplicationContext = initializeGlobalApplicationContext;
69
70
  async function destroyGlobalApplicationContext(applicationContext) {
71
+ printStepDebugInfo('Ready to destroy applicationContext');
70
72
  const loggerService = await applicationContext.getAsync(_1.MidwayLoggerService);
71
73
  const loggerFactory = loggerService.getCurrentLoggerFactory();
74
+ printStepDebugInfo('Stopping lifecycle');
72
75
  // stop lifecycle
73
76
  const lifecycleService = await applicationContext.getAsync(_1.MidwayLifeCycleService);
74
77
  await lifecycleService.stop();
78
+ printStepDebugInfo('Stopping applicationContext');
75
79
  // stop container
76
80
  await applicationContext.stop();
81
+ printStepDebugInfo('Closing loggerFactory');
77
82
  loggerFactory.close();
83
+ printStepDebugInfo('Cleaning performance manager');
78
84
  performanceManager_1.MidwayPerformanceManager.cleanAll();
79
85
  global['MIDWAY_APPLICATION_CONTEXT'] = undefined;
80
86
  global['MIDWAY_MAIN_FRAMEWORK'] = undefined;
81
87
  // reset counter
82
88
  stepIdx = 1;
89
+ projectIdx++;
83
90
  }
84
91
  exports.destroyGlobalApplicationContext = destroyGlobalApplicationContext;
85
92
  /**
@@ -1,3 +1,4 @@
1
+ /// <reference types="node" />
1
2
  import { FunctionMiddleware, IgnoreMatcher } from '../interface';
2
3
  import { camelCase, pascalCase } from './camelCase';
3
4
  import { randomUUID } from './uuid';
@@ -121,7 +122,7 @@ export declare function pathMatching(options: {
121
122
  export declare function wrapMiddleware(mw: FunctionMiddleware<any, any>, options: any): (context: any, next: any, options?: any) => any;
122
123
  export declare function isIncludeProperty(obj: any, prop: string): boolean;
123
124
  export declare function wrapAsync(handler: any): (...args: any[]) => any;
124
- export declare function sleep(sleepTime?: number): Promise<void>;
125
+ export declare function sleep(sleepTime?: number, abortController?: AbortController): Promise<void>;
125
126
  /**
126
127
  * get parameter name from function
127
128
  * @param func
@@ -134,22 +135,6 @@ export declare function generateRandomId(): string;
134
135
  export declare function merge(target: any, src: any): any;
135
136
  export declare function toAsyncFunction<T extends (...args: any[]) => any>(method: T): (...args: Parameters<T>) => Promise<ReturnType<T>>;
136
137
  export declare function isTypeScriptEnvironment(): boolean;
137
- /**
138
- * Create a Promise that resolves after the specified time
139
- * @param options
140
- */
141
- export declare function createPromiseTimeoutInvokeChain<Result>(options: {
142
- promiseItems: Array<Promise<any> | {
143
- item: Promise<any>;
144
- meta?: any;
145
- timeout?: number;
146
- }>;
147
- timeout: number;
148
- methodName: string;
149
- onSuccess?: (result: any, meta: any) => Result | Promise<Result>;
150
- onFail: (err: Error, meta: any) => Result | Promise<Result>;
151
- isConcurrent?: boolean;
152
- }): Promise<Result[]>;
153
138
  export declare function isConfigurationExport(exports: any): boolean;
154
139
  export declare function findProjectEntryFile(appDir: string, baseDir: string, loadMode: 'commonjs' | 'esm'): Promise<any>;
155
140
  export declare function findProjectEntryFileSync(appDir: string, baseDir: string): any;