@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,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Utils = exports.findProjectEntryFileSync = exports.findProjectEntryFile = exports.isConfigurationExport = 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.loadModuleSync = exports.loadModule = exports.safeRequire = exports.getCurrentEnvironment = exports.isDevelopmentEnvironment = void 0;
3
+ exports.Utils = exports.findProjectEntryFileSync = exports.findProjectEntryFile = exports.isConfigurationExport = 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.loadModuleSync = 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");
@@ -458,11 +458,16 @@ function wrapAsync(handler) {
458
458
  };
459
459
  }
460
460
  exports.wrapAsync = wrapAsync;
461
- function sleep(sleepTime = 1000) {
461
+ function sleep(sleepTime = 1000, abortController) {
462
462
  return new Promise(resolve => {
463
- setTimeout(() => {
463
+ const timeoutHandler = setTimeout(() => {
464
464
  resolve();
465
465
  }, sleepTime);
466
+ if (abortController) {
467
+ abortController.signal.addEventListener('abort', () => {
468
+ clearTimeout(timeoutHandler);
469
+ });
470
+ }
466
471
  });
467
472
  }
468
473
  exports.sleep = sleep;
@@ -530,70 +535,6 @@ function isTypeScriptEnvironment() {
530
535
  return TS_MODE_PROCESS_FLAG === 'true' || !!require.extensions['.ts'];
531
536
  }
532
537
  exports.isTypeScriptEnvironment = isTypeScriptEnvironment;
533
- /**
534
- * Create a Promise that resolves after the specified time
535
- * @param options
536
- */
537
- async function createPromiseTimeoutInvokeChain(options) {
538
- if (!options.onSuccess) {
539
- options.onSuccess = async (result) => {
540
- return result;
541
- };
542
- }
543
- options.isConcurrent = options.isConcurrent ?? true;
544
- options.promiseItems = options.promiseItems.map(item => {
545
- if (item instanceof Promise) {
546
- return { item };
547
- }
548
- else {
549
- return item;
550
- }
551
- });
552
- // filter promise
553
- options.promiseItems = options.promiseItems.filter(item => {
554
- return item['item'] instanceof Promise;
555
- });
556
- if (options.isConcurrent) {
557
- // For each check item, we create a timeout Promise
558
- const checkPromises = options.promiseItems.map(item => {
559
- const timeoutPromise = new Promise((_, reject) => {
560
- // The timeout Promise fails after the specified time
561
- setTimeout(() => reject(new error_1.MidwayCodeInvokeTimeoutError(options.methodName, item['timeout'] ?? options.timeout)), item['timeout'] ?? options.timeout);
562
- });
563
- // We use Promise.race to wait for either the check item or the timeout Promise
564
- return (Promise.race([item['item'], timeoutPromise])
565
- // If the check item Promise resolves, we set the result to success
566
- .then(re => {
567
- return options.onSuccess(re, item['meta']);
568
- })
569
- // If the timeout Promise resolves (i.e., the check item Promise did not resolve in time), we set the result to failure
570
- .catch(err => {
571
- return options.onFail(err, item['meta']);
572
- }));
573
- });
574
- return Promise.all(checkPromises);
575
- }
576
- else {
577
- const results = [];
578
- for (const item of options.promiseItems) {
579
- const timeoutPromise = new Promise((_, reject) => {
580
- setTimeout(() => reject(new error_1.MidwayCodeInvokeTimeoutError(options.methodName, item['timeout'] ?? options.timeout)), item['timeout'] ?? options.timeout);
581
- });
582
- try {
583
- const result = await Promise.race([item['item'], timeoutPromise]).then(re => {
584
- return options.onSuccess(re, item['meta']);
585
- });
586
- results.push(result);
587
- }
588
- catch (error) {
589
- results.push(options.onFail(error, item['meta']));
590
- break;
591
- }
592
- }
593
- return results;
594
- }
595
- }
596
- exports.createPromiseTimeoutInvokeChain = createPromiseTimeoutInvokeChain;
597
538
  function getFileNameWithSuffix(fileName) {
598
539
  return isTypeScriptEnvironment() ? `${fileName}.ts` : `${fileName}.js`;
599
540
  }
@@ -0,0 +1,10 @@
1
+ declare function getIpv4Address(): string;
2
+ declare function getIpv6Address(): string;
3
+ declare function getHostname(): string;
4
+ export declare const NetworkUtils: {
5
+ getIpv4Address: typeof getIpv4Address;
6
+ getIpv6Address: typeof getIpv6Address;
7
+ getHostname: typeof getHostname;
8
+ };
9
+ export {};
10
+ //# sourceMappingURL=network.d.ts.map
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NetworkUtils = void 0;
4
+ const os = require("os");
5
+ // get ipv4 and ipv6 address
6
+ function getIpv4Address() {
7
+ const interfaces = os.networkInterfaces();
8
+ for (const key in interfaces) {
9
+ if (interfaces[key]) {
10
+ for (const item of interfaces[key]) {
11
+ if (item.family === 'IPv4' && !item.internal) {
12
+ return item.address;
13
+ }
14
+ }
15
+ }
16
+ }
17
+ return '';
18
+ }
19
+ function getIpv6Address() {
20
+ const interfaces = os.networkInterfaces();
21
+ for (const key in interfaces) {
22
+ if (interfaces[key]) {
23
+ for (const item of interfaces[key]) {
24
+ if (item.family === 'IPv6' && !item.internal) {
25
+ return item.address;
26
+ }
27
+ }
28
+ }
29
+ }
30
+ return '';
31
+ }
32
+ function getHostname() {
33
+ return os.hostname();
34
+ }
35
+ exports.NetworkUtils = {
36
+ getIpv4Address,
37
+ getIpv6Address,
38
+ getHostname,
39
+ };
40
+ //# sourceMappingURL=network.js.map
@@ -16,7 +16,7 @@ export declare function getFileContentSync(filePath: any, encoding?: BufferEncod
16
16
  */
17
17
  export declare function normalizePath(baseDir: any, p: any): any;
18
18
  export declare function getModuleRequirePathList(moduleName: string): string[];
19
- export declare const PathFileUtil: {
19
+ export declare const PathFileUtils: {
20
20
  isPath: typeof isPath;
21
21
  isPathEqual: typeof isPathEqual;
22
22
  getFileContentSync: typeof getFileContentSync;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PathFileUtil = exports.getModuleRequirePathList = exports.normalizePath = exports.getFileContentSync = exports.isPathEqual = exports.isPath = void 0;
3
+ exports.PathFileUtils = exports.getModuleRequirePathList = exports.normalizePath = exports.getFileContentSync = exports.isPathEqual = exports.isPath = void 0;
4
4
  const path_1 = require("path");
5
5
  const fs_1 = require("fs");
6
6
  function isPath(p) {
@@ -75,7 +75,7 @@ function getModuleRequirePathList(moduleName) {
75
75
  return modulePathList;
76
76
  }
77
77
  exports.getModuleRequirePathList = getModuleRequirePathList;
78
- exports.PathFileUtil = {
78
+ exports.PathFileUtils = {
79
79
  isPath,
80
80
  isPathEqual,
81
81
  getFileContentSync,
@@ -0,0 +1,57 @@
1
+ /// <reference types="node" />
2
+ /**
3
+ * Create a Promise that resolves after the specified time
4
+ * @param options
5
+ */
6
+ export declare function createPromiseTimeoutInvokeChain<Result>(options: {
7
+ /**
8
+ * The promise items to be executed
9
+ */
10
+ promiseItems: Array<{
11
+ /**
12
+ * The promise item function, it will be executed in the timeout chain, and accept the abortController from the function call
13
+ */
14
+ item: (...args: any[]) => Promise<any>;
15
+ /**
16
+ * The promise item name, it will be used in error message
17
+ */
18
+ itemName?: string;
19
+ /**
20
+ * The promise item meta, which will be passed to the onSuccess and onFail callback
21
+ */
22
+ meta?: any;
23
+ /**
24
+ * The promise item timeout time
25
+ */
26
+ timeout?: number;
27
+ }>;
28
+ /**
29
+ * The default promise item timeout time, it used to set the timeout time in promiseItems if not provided
30
+ */
31
+ itemTimeout?: number;
32
+ /**
33
+ * The total execution timeout time
34
+ */
35
+ timeout?: number;
36
+ /**
37
+ * The method name, just for error message
38
+ */
39
+ methodName: string;
40
+ /**
41
+ * The success callback, if not provided, will ignore the result
42
+ */
43
+ onSuccess?: (result: any, meta: any) => Result | Promise<Result>;
44
+ /**
45
+ * The fail callback, if not provided, will throw error
46
+ */
47
+ onFail?: (err: Error, meta: any) => Result | Promise<Result>;
48
+ /**
49
+ * Whether to execute concurrently, default is true, if false, will execute sequentially by for loop
50
+ */
51
+ isConcurrent?: boolean;
52
+ /**
53
+ * The abort controller, if provided, will abort the timeout waiting and stop the execution
54
+ */
55
+ abortController?: AbortController;
56
+ }): Promise<Result[]>;
57
+ //# sourceMappingURL=timeout.d.ts.map
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPromiseTimeoutInvokeChain = void 0;
4
+ const error_1 = require("../error");
5
+ /**
6
+ * Create a Promise that resolves after the specified time
7
+ * @param options
8
+ */
9
+ async function createPromiseTimeoutInvokeChain(options) {
10
+ if (!options.onSuccess) {
11
+ options.onSuccess = async (result) => {
12
+ return result;
13
+ };
14
+ }
15
+ options.isConcurrent = options.isConcurrent ?? true;
16
+ // abort controller
17
+ const abortController = options.abortController ?? new AbortController();
18
+ // total timeout
19
+ let totalExecutionTimeoutHandler;
20
+ const itemTimeoutHandlers = [];
21
+ let totalTimeoutPromise;
22
+ if (options.timeout) {
23
+ totalTimeoutPromise = new Promise((_, reject) => {
24
+ totalExecutionTimeoutHandler = setTimeout(() => {
25
+ reject(new error_1.MidwayCodeInvokeTimeoutError(options.methodName, options.timeout));
26
+ }, options.timeout);
27
+ });
28
+ }
29
+ abortController.signal.addEventListener('abort', () => {
30
+ itemTimeoutHandlers.forEach(handler => {
31
+ clearTimeout(handler);
32
+ });
33
+ if (totalExecutionTimeoutHandler) {
34
+ clearTimeout(totalExecutionTimeoutHandler);
35
+ }
36
+ });
37
+ const realPromiseItems = options.promiseItems.filter(item => {
38
+ return typeof item['item'] === 'function';
39
+ });
40
+ if (options.isConcurrent) {
41
+ // For each check item, we create a timeout Promise
42
+ const checkPromises = realPromiseItems.map(item => {
43
+ const itemTimeout = item['timeout'] ?? options.itemTimeout;
44
+ const timeoutPromise = itemTimeout
45
+ ? new Promise((_, reject) => {
46
+ // The timeout Promise fails after the specified time
47
+ itemTimeoutHandlers.push(setTimeout(() => reject(new error_1.MidwayCodeInvokeTimeoutError(options.methodName, itemTimeout, item['itemName'])), itemTimeout));
48
+ })
49
+ : null;
50
+ // We use Promise.race to wait for either the check item or the timeout Promise
51
+ return (Promise.race([
52
+ Promise.resolve(item['item'](abortController)),
53
+ timeoutPromise,
54
+ ])
55
+ // If the check item Promise resolves, we set the result to success
56
+ .then(re => {
57
+ return options.onSuccess(re, item['meta']);
58
+ })
59
+ // If the timeout Promise resolves (i.e., the check item Promise did not resolve in time), we set the result to failure
60
+ .catch(err => {
61
+ if (options.onFail) {
62
+ return options.onFail?.(err, item['meta']);
63
+ }
64
+ else {
65
+ throw err;
66
+ }
67
+ }));
68
+ });
69
+ if (totalTimeoutPromise) {
70
+ return Promise.race([Promise.all(checkPromises), totalTimeoutPromise])
71
+ .finally(() => {
72
+ abortController.abort();
73
+ })
74
+ .then(results => {
75
+ return results;
76
+ })
77
+ .finally(() => {
78
+ abortController.abort();
79
+ });
80
+ }
81
+ else {
82
+ return Promise.all(checkPromises)
83
+ .finally(() => {
84
+ abortController.abort();
85
+ })
86
+ .then(results => {
87
+ return results;
88
+ });
89
+ }
90
+ }
91
+ else {
92
+ // 串行执行
93
+ const results = [];
94
+ // 包装整个串行执行过程
95
+ const serialExecution = async () => {
96
+ for (const item of realPromiseItems) {
97
+ const itemTimeout = item['timeout'] ?? options.itemTimeout;
98
+ const timeoutPromise = itemTimeout
99
+ ? new Promise((_, reject) => {
100
+ itemTimeoutHandlers.push(setTimeout(() => reject(new error_1.MidwayCodeInvokeTimeoutError(options.methodName, itemTimeout, item['itemName'])), itemTimeout));
101
+ })
102
+ : null;
103
+ try {
104
+ const result = await Promise.race([
105
+ Promise.resolve(item['item'](abortController)),
106
+ timeoutPromise,
107
+ ].filter(Boolean));
108
+ results.push(await options.onSuccess(result, item['meta']));
109
+ }
110
+ catch (error) {
111
+ if (options.onFail) {
112
+ results.push(await options.onFail(error, item['meta']));
113
+ break;
114
+ }
115
+ else {
116
+ throw error;
117
+ }
118
+ }
119
+ }
120
+ return results;
121
+ };
122
+ // 将整个串行执行过程与总超时竞争
123
+ if (totalTimeoutPromise) {
124
+ return Promise.race([serialExecution(), totalTimeoutPromise])
125
+ .then(results => {
126
+ return results;
127
+ })
128
+ .finally(() => {
129
+ abortController.abort();
130
+ });
131
+ }
132
+ else {
133
+ return serialExecution()
134
+ .then(results => {
135
+ return results;
136
+ })
137
+ .finally(() => {
138
+ abortController.abort();
139
+ });
140
+ }
141
+ }
142
+ }
143
+ exports.createPromiseTimeoutInvokeChain = createPromiseTimeoutInvokeChain;
144
+ //# sourceMappingURL=timeout.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "4.0.0-alpha.1",
3
+ "version": "4.0.0-beta.2",
4
4
  "description": "midway core",
5
5
  "main": "dist/index.js",
6
6
  "typings": "dist/index.d.ts",
@@ -24,7 +24,7 @@
24
24
  "devDependencies": {
25
25
  "@midwayjs/logger": "^3.0.0",
26
26
  "eventsource": "2.0.2",
27
- "koa": "2.15.3",
27
+ "koa": "2.16.2",
28
28
  "mm": "3.4.0",
29
29
  "raw-body": "2.5.2",
30
30
  "sinon": "17.0.2"
@@ -40,7 +40,7 @@
40
40
  "url": "https://github.com/midwayjs/midway.git"
41
41
  },
42
42
  "engines": {
43
- "node": ">=16"
43
+ "node": ">=20"
44
44
  },
45
45
  "madge": {
46
46
  "detectiveOptions": {
@@ -61,5 +61,5 @@
61
61
  "types": "./dist/functional/index.d.ts"
62
62
  }
63
63
  },
64
- "gitHead": "14bb4da91805a1cf52f190c0d37a74b395dd6372"
64
+ "gitHead": "53bfef4c5279da5f09025e4610bdbf64f94f60bd"
65
65
  }