@midwayjs/core 3.13.0-beta.1 → 3.13.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2013 - Now midwayjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -4,6 +4,9 @@ const util_1 = require("../util/");
4
4
  exports.default = (appInfo) => {
5
5
  const isDevelopment = (0, util_1.isDevelopmentEnvironment)((0, util_1.getCurrentEnvironment)());
6
6
  return {
7
+ core: {
8
+ healthCheckTimeout: 1000,
9
+ },
7
10
  asyncContextManager: {
8
11
  enable: false,
9
12
  },
@@ -12,7 +15,9 @@ exports.default = (appInfo) => {
12
15
  level: 'info',
13
16
  },
14
17
  clients: {
15
- coreLogger: {},
18
+ coreLogger: {
19
+ level: isDevelopment ? 'info' : 'warn',
20
+ },
16
21
  appLogger: {
17
22
  aliasName: 'logger',
18
23
  },
@@ -20,6 +20,7 @@ export declare const FrameworkErrorEnum: {
20
20
  readonly DUPLICATE_CONTROLLER_PREFIX_OPTIONS: "MIDWAY_10016";
21
21
  readonly RETRY_OVER_MAX_TIME: "MIDWAY_10017";
22
22
  readonly INVOKE_METHOD_FORBIDDEN: "MIDWAY_10018";
23
+ readonly CODE_INVOKE_TIMEOUT: "MIDWAY_10019";
23
24
  };
24
25
  export declare class MidwayCommonError extends MidwayError {
25
26
  constructor(message: string);
@@ -78,4 +79,7 @@ export declare class MidwayRetryExceededMaxTimesError extends MidwayError {
78
79
  export declare class MidwayInvokeForbiddenError extends MidwayError {
79
80
  constructor(methodName: string, module?: any);
80
81
  }
82
+ export declare class MidwayCodeInvokeTimeoutError extends MidwayError {
83
+ constructor(methodName: string, timeout: number);
84
+ }
81
85
  //# sourceMappingURL=framework.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MidwayInvokeForbiddenError = exports.MidwayRetryExceededMaxTimesError = exports.MidwayDuplicateControllerOptionsError = exports.MidwayDuplicateClassNameError = exports.MidwayInconsistentVersionError = exports.MidwayUtilHttpClientTimeoutError = exports.MidwayMissingImportComponentError = exports.MidwaySingletonInjectRequestError = exports.MidwayUseWrongMethodError = exports.MidwayDuplicateRouteError = exports.MidwayResolverMissingError = exports.MidwayInvalidConfigError = exports.MidwayConfigMissingError = exports.MidwayFeatureNotImplementedError = exports.MidwayFeatureNoLongerSupportedError = exports.MidwayDefinitionNotFoundError = exports.MidwayParameterError = exports.MidwayCommonError = exports.FrameworkErrorEnum = void 0;
3
+ exports.MidwayCodeInvokeTimeoutError = exports.MidwayInvokeForbiddenError = exports.MidwayRetryExceededMaxTimesError = exports.MidwayDuplicateControllerOptionsError = exports.MidwayDuplicateClassNameError = exports.MidwayInconsistentVersionError = exports.MidwayUtilHttpClientTimeoutError = exports.MidwayMissingImportComponentError = exports.MidwaySingletonInjectRequestError = exports.MidwayUseWrongMethodError = exports.MidwayDuplicateRouteError = exports.MidwayResolverMissingError = exports.MidwayInvalidConfigError = exports.MidwayConfigMissingError = exports.MidwayFeatureNotImplementedError = exports.MidwayFeatureNoLongerSupportedError = exports.MidwayDefinitionNotFoundError = exports.MidwayParameterError = exports.MidwayCommonError = exports.FrameworkErrorEnum = void 0;
4
4
  const base_1 = require("./base");
5
5
  exports.FrameworkErrorEnum = (0, base_1.registerErrorCode)('midway', {
6
6
  UNKNOWN: 10000,
@@ -22,6 +22,7 @@ exports.FrameworkErrorEnum = (0, base_1.registerErrorCode)('midway', {
22
22
  DUPLICATE_CONTROLLER_PREFIX_OPTIONS: 10016,
23
23
  RETRY_OVER_MAX_TIME: 10017,
24
24
  INVOKE_METHOD_FORBIDDEN: 10018,
25
+ CODE_INVOKE_TIMEOUT: 10019,
25
26
  });
26
27
  class MidwayCommonError extends base_1.MidwayError {
27
28
  constructor(message) {
@@ -152,4 +153,10 @@ class MidwayInvokeForbiddenError extends base_1.MidwayError {
152
153
  }
153
154
  }
154
155
  exports.MidwayInvokeForbiddenError = MidwayInvokeForbiddenError;
156
+ class MidwayCodeInvokeTimeoutError extends base_1.MidwayError {
157
+ constructor(methodName, timeout) {
158
+ super(`Invoke "${methodName}" running timeout(${timeout}ms)`, exports.FrameworkErrorEnum.CODE_INVOKE_TIMEOUT);
159
+ }
160
+ }
161
+ exports.MidwayCodeInvokeTimeoutError = MidwayCodeInvokeTimeoutError;
155
162
  //# sourceMappingURL=framework.js.map
package/dist/index.d.ts CHANGED
@@ -33,14 +33,13 @@ export { AsyncContextManager, ASYNC_ROOT_CONTEXT, AsyncContext, } from './common
33
33
  export * from './decorator';
34
34
  export * from './decorator/decoratorManager';
35
35
  export * from './decorator/constant';
36
- export { safelyGet, safeRequire, loadModule, delegateTargetPrototypeMethod, delegateTargetMethod, delegateTargetProperties, delegateTargetAllPrototypeMethod, deprecatedOutput, transformRequestObjectByType, pathMatching, wrapMiddleware, wrapAsync, isTypeScriptEnvironment, } from './util/';
36
+ export { safelyGet, safeRequire, loadModule, delegateTargetPrototypeMethod, delegateTargetMethod, delegateTargetProperties, delegateTargetAllPrototypeMethod, deprecatedOutput, transformRequestObjectByType, pathMatching, wrapMiddleware, wrapAsync, isTypeScriptEnvironment, sleep, Utils, } from './util/';
37
37
  export { extend } from './util/extend';
38
38
  export * from './util/webRouterParam';
39
39
  export * from './util/contextUtil';
40
40
  export * from './util/pathToRegexp';
41
41
  export * from './util/httpclient';
42
42
  export { retryWithAsync, retryWith } from './util/retry';
43
- export { sleep, Utils } from './util/index';
44
43
  export { Types } from './util/types';
45
44
  export { PathFileUtil } from './util/pathFileUtil';
46
45
  export { FileUtils } from './util/fs';
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.FORMAT = exports.FileUtils = exports.PathFileUtil = exports.Types = exports.Utils = exports.sleep = exports.retryWith = exports.retryWithAsync = exports.extend = exports.isTypeScriptEnvironment = exports.wrapAsync = exports.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.loadModule = exports.safeRequire = exports.safelyGet = exports.ASYNC_ROOT_CONTEXT = exports.DataSourceManager = exports.WebRouterCollector = exports.MidwayServerlessFunctionService = exports.MidwayWebRouterService = exports.MidwayMockService = exports.MidwayDecoratorService = exports.MidwayMiddlewareService = exports.MidwayLifeCycleService = exports.MidwayAspectService = exports.MidwayFrameworkService = exports.MidwayLoggerService = exports.MidwayInformationService = exports.MidwayEnvironmentService = exports.MidwayConfigService = exports.FunctionalConfiguration = exports.createConfiguration = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
17
+ exports.FORMAT = exports.FileUtils = exports.PathFileUtil = exports.Types = exports.retryWith = exports.retryWithAsync = exports.extend = exports.Utils = exports.sleep = exports.isTypeScriptEnvironment = exports.wrapAsync = exports.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.loadModule = exports.safeRequire = exports.safelyGet = exports.ASYNC_ROOT_CONTEXT = exports.DataSourceManager = exports.WebRouterCollector = exports.MidwayServerlessFunctionService = exports.MidwayWebRouterService = exports.MidwayMockService = exports.MidwayDecoratorService = exports.MidwayMiddlewareService = exports.MidwayLifeCycleService = exports.MidwayAspectService = exports.MidwayFrameworkService = exports.MidwayLoggerService = exports.MidwayInformationService = exports.MidwayEnvironmentService = exports.MidwayConfigService = exports.FunctionalConfiguration = exports.createConfiguration = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
18
18
  __exportStar(require("./interface"), exports);
19
19
  __exportStar(require("./context/container"), exports);
20
20
  var requestContainer_1 = require("./context/requestContainer");
@@ -85,6 +85,8 @@ Object.defineProperty(exports, "pathMatching", { enumerable: true, get: function
85
85
  Object.defineProperty(exports, "wrapMiddleware", { enumerable: true, get: function () { return util_1.wrapMiddleware; } });
86
86
  Object.defineProperty(exports, "wrapAsync", { enumerable: true, get: function () { return util_1.wrapAsync; } });
87
87
  Object.defineProperty(exports, "isTypeScriptEnvironment", { enumerable: true, get: function () { return util_1.isTypeScriptEnvironment; } });
88
+ Object.defineProperty(exports, "sleep", { enumerable: true, get: function () { return util_1.sleep; } });
89
+ Object.defineProperty(exports, "Utils", { enumerable: true, get: function () { return util_1.Utils; } });
88
90
  var extend_1 = require("./util/extend");
89
91
  Object.defineProperty(exports, "extend", { enumerable: true, get: function () { return extend_1.extend; } });
90
92
  __exportStar(require("./util/webRouterParam"), exports);
@@ -94,9 +96,6 @@ __exportStar(require("./util/httpclient"), exports);
94
96
  var retry_1 = require("./util/retry");
95
97
  Object.defineProperty(exports, "retryWithAsync", { enumerable: true, get: function () { return retry_1.retryWithAsync; } });
96
98
  Object.defineProperty(exports, "retryWith", { enumerable: true, get: function () { return retry_1.retryWith; } });
97
- var index_1 = require("./util/index");
98
- Object.defineProperty(exports, "sleep", { enumerable: true, get: function () { return index_1.sleep; } });
99
- Object.defineProperty(exports, "Utils", { enumerable: true, get: function () { return index_1.Utils; } });
100
99
  var types_1 = require("./util/types");
101
100
  Object.defineProperty(exports, "Types", { enumerable: true, get: function () { return types_1.Types; } });
102
101
  var pathFileUtil_1 = require("./util/pathFileUtil");
@@ -392,8 +392,11 @@ export interface MidwayCoreDefaultConfig {
392
392
  debug?: {
393
393
  recordConfigMergeOrder?: boolean;
394
394
  };
395
- asyncContextManager: {
396
- enable: boolean;
395
+ asyncContextManager?: {
396
+ enable?: boolean;
397
+ };
398
+ core?: {
399
+ healthCheckTimeout?: number;
397
400
  };
398
401
  }
399
402
  export type ServiceFactoryConfigOption<OPTIONS> = {
@@ -436,6 +439,7 @@ export interface ILifeCycle extends Partial<IObjectLifeCycle> {
436
439
  onConfigLoad?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<any>;
437
440
  onReady?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<void>;
438
441
  onServerReady?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<void>;
442
+ onHealthCheck?(container: IMidwayContainer): Promise<HealthResult>;
439
443
  onStop?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<void>;
440
444
  }
441
445
  export type ObjectContext = {
@@ -945,5 +949,34 @@ export interface ISimulation {
945
949
  appTearDown?(app: IMidwayApplication): Promise<void>;
946
950
  enableCondition(): boolean | Promise<boolean>;
947
951
  }
952
+ export interface HealthResult {
953
+ /**
954
+ * health status
955
+ */
956
+ status: boolean;
957
+ /**
958
+ * failed reason
959
+ */
960
+ reason?: string;
961
+ }
962
+ export interface HealthResults {
963
+ /**
964
+ * health status
965
+ */
966
+ status: boolean;
967
+ /**
968
+ * first failed namespace
969
+ */
970
+ namespace: string;
971
+ /**
972
+ * first failed reason
973
+ */
974
+ reason?: string;
975
+ results?: Array<{
976
+ namespace: string;
977
+ status: boolean;
978
+ reason?: string;
979
+ }>;
980
+ }
948
981
  export {};
949
982
  //# sourceMappingURL=interface.d.ts.map
@@ -131,6 +131,7 @@ let MidwayFrameworkService = class MidwayFrameworkService {
131
131
  }
132
132
  global['MIDWAY_MAIN_FRAMEWORK'] = this.mainFramework =
133
133
  (_b = this.applicationManager.getFramework(mainNs)) !== null && _b !== void 0 ? _b : this.globalFrameworkList[0];
134
+ debug(`[core]: Current main Framework is "${mainNs}".`);
134
135
  }
135
136
  // init aspect module
136
137
  await this.aspectService.loadAspect();
@@ -146,6 +147,12 @@ let MidwayFrameworkService = class MidwayFrameworkService {
146
147
  return this.applicationManager.getFramework(namespaceOrFrameworkType);
147
148
  }
148
149
  async runFramework() {
150
+ const namespaceList = this.applicationContext.getNamespaceList();
151
+ // globalFrameworkList 需要基于 namespaceList 进行排序,不然会出现顺序问题
152
+ this.globalFrameworkList = this.globalFrameworkList.sort((a, b) => {
153
+ return (namespaceList.indexOf(a.getNamespace()) -
154
+ namespaceList.indexOf(b.getNamespace()));
155
+ });
149
156
  for (const frameworkInstance of this.globalFrameworkList) {
150
157
  // if enable, just init framework
151
158
  if (frameworkInstance.isEnable()) {
@@ -0,0 +1,14 @@
1
+ import { HealthResults, IMidwayContainer } from '../interface';
2
+ import { MidwayConfigService } from './configService';
3
+ import { MidwayLifeCycleService } from './lifeCycleService';
4
+ export declare class MidwayHealthService {
5
+ protected configService: MidwayConfigService;
6
+ protected lifeCycleService: MidwayLifeCycleService;
7
+ protected applicationContext: IMidwayContainer;
8
+ private healthCheckTimeout;
9
+ private healthCheckMethods;
10
+ protected init(): Promise<void>;
11
+ getStatus(): Promise<HealthResults>;
12
+ setCheckTimeout(timeout: number): void;
13
+ }
14
+ //# sourceMappingURL=healthService.d.ts.map
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.MidwayHealthService = void 0;
13
+ const decorator_1 = require("../decorator");
14
+ const interface_1 = require("../interface");
15
+ const configService_1 = require("./configService");
16
+ const lifeCycleService_1 = require("./lifeCycleService");
17
+ const util_1 = require("../util");
18
+ let MidwayHealthService = class MidwayHealthService {
19
+ constructor() {
20
+ this.healthCheckTimeout = 1000;
21
+ this.healthCheckMethods = [];
22
+ }
23
+ async init() {
24
+ const healthCheckTimeout = this.configService.getConfiguration('core.healthCheckTimeout') || 1000;
25
+ this.setCheckTimeout(healthCheckTimeout);
26
+ for (const lifecycleInstance of this.lifeCycleService.getLifecycleInstanceList()) {
27
+ if (lifecycleInstance.instance &&
28
+ lifecycleInstance.instance['onHealthCheck']) {
29
+ this.healthCheckMethods.push({
30
+ item: lifecycleInstance.instance['onHealthCheck'],
31
+ meta: {
32
+ namespace: lifecycleInstance.namespace,
33
+ },
34
+ });
35
+ }
36
+ }
37
+ }
38
+ async getStatus() {
39
+ const checkResult = await (0, util_1.createPromiseTimeoutInvokeChain)({
40
+ promiseItems: this.healthCheckMethods.map(item => {
41
+ return {
42
+ item: item.item(this.applicationContext),
43
+ meta: item.meta,
44
+ };
45
+ }),
46
+ timeout: this.healthCheckTimeout,
47
+ methodName: 'configuration.onHealthCheck',
48
+ onSuccess: (result, meta) => {
49
+ if (result['status'] !== undefined) {
50
+ return {
51
+ namespace: meta.namespace,
52
+ ...result,
53
+ };
54
+ }
55
+ else {
56
+ return {
57
+ status: false,
58
+ namespace: meta.namespace,
59
+ reason: 'configuration.onHealthCheck return value must be object and contain status field',
60
+ };
61
+ }
62
+ },
63
+ onFail: (err, meta) => {
64
+ return {
65
+ status: false,
66
+ namespace: meta.namespace,
67
+ reason: err.message,
68
+ };
69
+ },
70
+ });
71
+ const failedResult = checkResult.find(item => !item.status);
72
+ return {
73
+ status: !failedResult,
74
+ namespace: failedResult === null || failedResult === void 0 ? void 0 : failedResult.namespace,
75
+ reason: failedResult === null || failedResult === void 0 ? void 0 : failedResult.reason,
76
+ results: checkResult,
77
+ };
78
+ }
79
+ setCheckTimeout(timeout) {
80
+ this.healthCheckTimeout = timeout;
81
+ }
82
+ };
83
+ __decorate([
84
+ (0, decorator_1.Inject)(),
85
+ __metadata("design:type", configService_1.MidwayConfigService)
86
+ ], MidwayHealthService.prototype, "configService", void 0);
87
+ __decorate([
88
+ (0, decorator_1.Inject)(),
89
+ __metadata("design:type", lifeCycleService_1.MidwayLifeCycleService)
90
+ ], MidwayHealthService.prototype, "lifeCycleService", void 0);
91
+ __decorate([
92
+ (0, decorator_1.ApplicationContext)(),
93
+ __metadata("design:type", Object)
94
+ ], MidwayHealthService.prototype, "applicationContext", void 0);
95
+ __decorate([
96
+ (0, decorator_1.Init)(),
97
+ __metadata("design:type", Function),
98
+ __metadata("design:paramtypes", []),
99
+ __metadata("design:returntype", Promise)
100
+ ], MidwayHealthService.prototype, "init", null);
101
+ MidwayHealthService = __decorate([
102
+ (0, decorator_1.Provide)(),
103
+ (0, decorator_1.Scope)(interface_1.ScopeEnum.Singleton)
104
+ ], MidwayHealthService);
105
+ exports.MidwayHealthService = MidwayHealthService;
106
+ //# sourceMappingURL=healthService.js.map
@@ -7,10 +7,27 @@ export declare class MidwayLifeCycleService {
7
7
  protected frameworkService: MidwayFrameworkService;
8
8
  protected configService: MidwayConfigService;
9
9
  protected mockService: MidwayMockService;
10
+ private lifecycleInstanceList;
10
11
  constructor(applicationContext: IMidwayContainer);
11
12
  protected init(): Promise<void>;
12
13
  stop(): Promise<void>;
14
+ /**
15
+ * run some lifecycle in configuration
16
+ * @param lifecycleInstanceOrList
17
+ * @param lifecycle
18
+ * @param resultHandler
19
+ */
13
20
  private runContainerLifeCycle;
21
+ /**
22
+ * run object lifecycle
23
+ * @param lifecycleInstanceList
24
+ * @param lifecycle
25
+ */
14
26
  private runObjectLifeCycle;
27
+ getLifecycleInstanceList(): {
28
+ target: any;
29
+ namespace: string;
30
+ instance?: any;
31
+ }[];
15
32
  }
16
33
  //# sourceMappingURL=lifeCycleService.d.ts.map
@@ -21,6 +21,7 @@ const debug = (0, util_1.debuglog)('midway:debug');
21
21
  let MidwayLifeCycleService = class MidwayLifeCycleService {
22
22
  constructor(applicationContext) {
23
23
  this.applicationContext = applicationContext;
24
+ this.lifecycleInstanceList = [];
24
25
  }
25
26
  async init() {
26
27
  // exec simulator init
@@ -28,7 +29,6 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
28
29
  // run lifecycle
29
30
  const cycles = (0, decorator_1.listModule)(decorator_1.CONFIGURATION_KEY);
30
31
  debug(`[core]: Found Configuration length = ${cycles.length}`);
31
- const lifecycleInstanceList = [];
32
32
  for (const cycle of cycles) {
33
33
  if (cycle.target instanceof configuration_1.FunctionalConfiguration) {
34
34
  // 函数式写法
@@ -39,30 +39,30 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
39
39
  debug(`[core]: Lifecycle run ${cycle.namespace} init`);
40
40
  cycle.instance = await this.applicationContext.getAsync(cycle.target);
41
41
  }
42
- cycle.instance && lifecycleInstanceList.push(cycle);
42
+ cycle.instance && this.lifecycleInstanceList.push(cycle);
43
43
  }
44
44
  // bind object lifecycle
45
45
  await Promise.all([
46
- this.runObjectLifeCycle(lifecycleInstanceList, 'onBeforeObjectCreated'),
47
- this.runObjectLifeCycle(lifecycleInstanceList, 'onObjectCreated'),
48
- this.runObjectLifeCycle(lifecycleInstanceList, 'onObjectInit'),
49
- this.runObjectLifeCycle(lifecycleInstanceList, 'onBeforeObjectDestroy'),
46
+ this.runObjectLifeCycle(this.lifecycleInstanceList, 'onBeforeObjectCreated'),
47
+ this.runObjectLifeCycle(this.lifecycleInstanceList, 'onObjectCreated'),
48
+ this.runObjectLifeCycle(this.lifecycleInstanceList, 'onObjectInit'),
49
+ this.runObjectLifeCycle(this.lifecycleInstanceList, 'onBeforeObjectDestroy'),
50
50
  ]);
51
51
  // bind framework lifecycle
52
52
  // onAppError
53
53
  // exec onConfigLoad()
54
- await this.runContainerLifeCycle(lifecycleInstanceList, 'onConfigLoad', configData => {
54
+ await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onConfigLoad', configData => {
55
55
  if (configData) {
56
56
  this.configService.addObject(configData);
57
57
  }
58
58
  });
59
59
  await this.mockService.runSimulatorSetup();
60
60
  // exec onReady()
61
- await this.runContainerLifeCycle(lifecycleInstanceList, 'onReady');
61
+ await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onReady');
62
62
  // exec framework.run()
63
63
  await this.frameworkService.runFramework();
64
64
  // exec onServerReady()
65
- await this.runContainerLifeCycle(lifecycleInstanceList, 'onServerReady');
65
+ await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onServerReady');
66
66
  // clear config merge cache
67
67
  if (!this.configService.getConfiguration('debug.recordConfigMergeOrder')) {
68
68
  this.configService.clearConfigMergeOrder();
@@ -86,6 +86,12 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
86
86
  // stop framework
87
87
  await this.frameworkService.stopFramework();
88
88
  }
89
+ /**
90
+ * run some lifecycle in configuration
91
+ * @param lifecycleInstanceOrList
92
+ * @param lifecycle
93
+ * @param resultHandler
94
+ */
89
95
  async runContainerLifeCycle(lifecycleInstanceOrList, lifecycle, resultHandler) {
90
96
  if (Array.isArray(lifecycleInstanceOrList)) {
91
97
  for (const cycle of lifecycleInstanceOrList) {
@@ -108,6 +114,11 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
108
114
  }
109
115
  }
110
116
  }
117
+ /**
118
+ * run object lifecycle
119
+ * @param lifecycleInstanceList
120
+ * @param lifecycle
121
+ */
111
122
  async runObjectLifeCycle(lifecycleInstanceList, lifecycle) {
112
123
  for (const cycle of lifecycleInstanceList) {
113
124
  if (typeof cycle.instance[lifecycle] === 'function') {
@@ -116,6 +127,9 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
116
127
  }
117
128
  }
118
129
  }
130
+ getLifecycleInstanceList() {
131
+ return this.lifecycleInstanceList;
132
+ }
119
133
  };
120
134
  __decorate([
121
135
  (0, decorator_1.Inject)(),
package/dist/setup.js CHANGED
@@ -7,6 +7,7 @@ const decorator_1 = require("./decorator");
7
7
  const util = require("util");
8
8
  const slsFunctionService_1 = require("./service/slsFunctionService");
9
9
  const path_1 = require("path");
10
+ const healthService_1 = require("./service/healthService");
10
11
  const debug = util.debuglog('midway:debug');
11
12
  let stepIdx = 1;
12
13
  function printStepDebugInfo(stepInfo) {
@@ -134,6 +135,7 @@ async function prepareGlobalApplicationContextAsync(globalOptions) {
134
135
  applicationContext.bindClass(_1.MidwayMockService);
135
136
  applicationContext.bindClass(_1.MidwayWebRouterService);
136
137
  applicationContext.bindClass(slsFunctionService_1.MidwayServerlessFunctionService);
138
+ applicationContext.bindClass(healthService_1.MidwayHealthService);
137
139
  printStepDebugInfo('Binding preload module');
138
140
  // bind preload module
139
141
  if (globalOptions.preloadModules && globalOptions.preloadModules.length) {
@@ -227,6 +229,7 @@ function prepareGlobalApplicationContext(globalOptions) {
227
229
  applicationContext.bindClass(_1.MidwayMockService);
228
230
  applicationContext.bindClass(_1.MidwayWebRouterService);
229
231
  applicationContext.bindClass(slsFunctionService_1.MidwayServerlessFunctionService);
232
+ applicationContext.bindClass(healthService_1.MidwayHealthService);
230
233
  printStepDebugInfo('Binding preload module');
231
234
  // bind preload module
232
235
  if (globalOptions.preloadModules && globalOptions.preloadModules.length) {
@@ -123,6 +123,22 @@ export declare function generateRandomId(): string;
123
123
  export declare function merge(target: any, src: any): any;
124
124
  export declare function toAsyncFunction<T extends (...args: any[]) => any>(method: T): (...args: Parameters<T>) => Promise<ReturnType<T>>;
125
125
  export declare function isTypeScriptEnvironment(): boolean;
126
+ /**
127
+ * Create a Promise that resolves after the specified time
128
+ * @param options
129
+ */
130
+ export declare function createPromiseTimeoutInvokeChain<Result>(options: {
131
+ promiseItems: Array<Promise<any> | {
132
+ item: Promise<any>;
133
+ meta?: any;
134
+ timeout?: number;
135
+ }>;
136
+ timeout: number;
137
+ methodName: string;
138
+ onSuccess?: (result: any, meta: any) => Result | Promise<Result>;
139
+ onFail: (err: Error, meta: any) => Result | Promise<Result>;
140
+ isConcurrent?: boolean;
141
+ }): Promise<Result[]>;
126
142
  export declare const Utils: {
127
143
  sleep: typeof sleep;
128
144
  getParamNames: typeof getParamNames;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Utils = exports.isTypeScriptEnvironment = exports.toAsyncFunction = exports.merge = exports.generateRandomId = exports.getParamNames = exports.sleep = exports.wrapAsync = exports.isIncludeProperty = exports.wrapMiddleware = exports.pathMatching = exports.toPathMatch = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.getCurrentDateString = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetPrototypeMethod = exports.joinURLPath = exports.getUserHome = exports.parsePrefix = exports.safelyGet = exports.loadModule = exports.safeRequire = exports.getCurrentEnvironment = exports.isDevelopmentEnvironment = void 0;
3
+ exports.Utils = exports.createPromiseTimeoutInvokeChain = exports.isTypeScriptEnvironment = exports.toAsyncFunction = exports.merge = exports.generateRandomId = exports.getParamNames = exports.sleep = exports.wrapAsync = exports.isIncludeProperty = exports.wrapMiddleware = exports.pathMatching = exports.toPathMatch = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.getCurrentDateString = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetPrototypeMethod = exports.joinURLPath = exports.getUserHome = exports.parsePrefix = exports.safelyGet = exports.loadModule = exports.safeRequire = exports.getCurrentEnvironment = exports.isDevelopmentEnvironment = void 0;
4
4
  const path_1 = require("path");
5
5
  const fs_1 = require("fs");
6
6
  const util_1 = require("util");
@@ -496,6 +496,79 @@ function isTypeScriptEnvironment() {
496
496
  return TS_MODE_PROCESS_FLAG === 'true' || !!require.extensions['.ts'];
497
497
  }
498
498
  exports.isTypeScriptEnvironment = isTypeScriptEnvironment;
499
+ /**
500
+ * Create a Promise that resolves after the specified time
501
+ * @param options
502
+ */
503
+ async function createPromiseTimeoutInvokeChain(options) {
504
+ var _a;
505
+ if (!options.onSuccess) {
506
+ options.onSuccess = async (result) => {
507
+ return result;
508
+ };
509
+ }
510
+ options.isConcurrent = (_a = options.isConcurrent) !== null && _a !== void 0 ? _a : true;
511
+ options.promiseItems = options.promiseItems.map(item => {
512
+ if (item instanceof Promise) {
513
+ return { item };
514
+ }
515
+ else {
516
+ return item;
517
+ }
518
+ });
519
+ // filter promise
520
+ options.promiseItems = options.promiseItems.filter(item => {
521
+ return item['item'] instanceof Promise;
522
+ });
523
+ if (options.isConcurrent) {
524
+ // For each check item, we create a timeout Promise
525
+ const checkPromises = options.promiseItems.map(item => {
526
+ const timeoutPromise = new Promise((_, reject) => {
527
+ var _a;
528
+ // The timeout Promise fails after the specified time
529
+ setTimeout(() => {
530
+ var _a;
531
+ return reject(new error_1.MidwayCodeInvokeTimeoutError(options.methodName, (_a = item['timeout']) !== null && _a !== void 0 ? _a : options.timeout));
532
+ }, (_a = item['timeout']) !== null && _a !== void 0 ? _a : options.timeout);
533
+ });
534
+ // We use Promise.race to wait for either the check item or the timeout Promise
535
+ return (Promise.race([item['item'], timeoutPromise])
536
+ // If the check item Promise resolves, we set the result to success
537
+ .then(re => {
538
+ return options.onSuccess(re, item['meta']);
539
+ })
540
+ // If the timeout Promise resolves (i.e., the check item Promise did not resolve in time), we set the result to failure
541
+ .catch(err => {
542
+ return options.onFail(err, item['meta']);
543
+ }));
544
+ });
545
+ return Promise.all(checkPromises);
546
+ }
547
+ else {
548
+ const results = [];
549
+ for (const item of options.promiseItems) {
550
+ const timeoutPromise = new Promise((_, reject) => {
551
+ var _a;
552
+ setTimeout(() => {
553
+ var _a;
554
+ return reject(new error_1.MidwayCodeInvokeTimeoutError(options.methodName, (_a = item['timeout']) !== null && _a !== void 0 ? _a : options.timeout));
555
+ }, (_a = item['timeout']) !== null && _a !== void 0 ? _a : options.timeout);
556
+ });
557
+ try {
558
+ const result = await Promise.race([item['item'], timeoutPromise]).then(re => {
559
+ return options.onSuccess(re, item['meta']);
560
+ });
561
+ results.push(result);
562
+ }
563
+ catch (error) {
564
+ results.push(options.onFail(error, item['meta']));
565
+ break;
566
+ }
567
+ }
568
+ return results;
569
+ }
570
+ }
571
+ exports.createPromiseTimeoutInvokeChain = createPromiseTimeoutInvokeChain;
499
572
  exports.Utils = {
500
573
  sleep,
501
574
  getParamNames,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.13.0-beta.1",
3
+ "version": "3.13.0",
4
4
  "description": "midway core",
5
5
  "main": "dist/index.js",
6
6
  "typings": "dist/index.d.ts",
@@ -22,11 +22,11 @@
22
22
  ],
23
23
  "license": "MIT",
24
24
  "devDependencies": {
25
- "koa": "2.14.1",
25
+ "@midwayjs/logger": "^3.0.0",
26
+ "koa": "2.14.2",
26
27
  "mm": "3.3.0",
27
28
  "raw-body": "2.5.2",
28
- "sinon": "15.2.0",
29
- "@midwayjs/logger": "3.0.0"
29
+ "sinon": "15.2.0"
30
30
  },
31
31
  "dependencies": {
32
32
  "@midwayjs/glob": "^1.0.2",
@@ -42,5 +42,5 @@
42
42
  "engines": {
43
43
  "node": ">=12"
44
44
  },
45
- "gitHead": "a603d2348d6141f8f723901498f03a162a037708"
45
+ "gitHead": "9f55734afa5b08dcf46bc89493ec8edaa8c6202b"
46
46
  }