monsqlize 1.3.0 → 2.0.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.
Files changed (172) hide show
  1. package/CHANGELOG.md +56 -60
  2. package/LICENSE +201 -21
  3. package/README.md +537 -1828
  4. package/changelogs/README.md +160 -0
  5. package/changelogs/v2.0.0.md +222 -0
  6. package/dist/cjs/index.cjs +10600 -0
  7. package/dist/cjs/mongodb/common/transaction-aware.cjs +10 -0
  8. package/dist/cjs/transaction/CacheLockManager.cjs +100 -0
  9. package/dist/cjs/transaction/Transaction.cjs +158 -0
  10. package/dist/cjs/transaction/TransactionManager.cjs +298 -0
  11. package/dist/esm/index.mjs +10650 -0
  12. package/dist/types/base.d.ts +81 -0
  13. package/dist/types/collection.d.ts +1031 -0
  14. package/dist/types/expression.d.ts +115 -0
  15. package/dist/types/index.d.ts +23 -0
  16. package/dist/types/lock.d.ts +74 -0
  17. package/dist/types/model.d.ts +526 -0
  18. package/dist/types/mongodb.d.ts +49 -0
  19. package/dist/types/monsqlize.d.ts +491 -0
  20. package/dist/types/pool.d.ts +84 -0
  21. package/dist/types/runtime.d.ts +362 -0
  22. package/dist/types/saga.d.ts +143 -0
  23. package/dist/types/slow-query-log.d.ts +126 -0
  24. package/dist/types/sync.d.ts +103 -0
  25. package/dist/types/transaction.d.ts +132 -0
  26. package/package.json +67 -69
  27. package/index.d.ts +0 -206
  28. package/index.mjs +0 -52
  29. package/lib/cache-invalidation.js +0 -279
  30. package/lib/cache.js +0 -530
  31. package/lib/common/cursor.js +0 -59
  32. package/lib/common/docs-urls.js +0 -73
  33. package/lib/common/index-options.js +0 -223
  34. package/lib/common/log.js +0 -61
  35. package/lib/common/namespace.js +0 -22
  36. package/lib/common/normalize.js +0 -34
  37. package/lib/common/page-result.js +0 -43
  38. package/lib/common/runner.js +0 -57
  39. package/lib/common/server-features.js +0 -232
  40. package/lib/common/shape-builders.js +0 -27
  41. package/lib/common/validation.js +0 -113
  42. package/lib/connect.js +0 -99
  43. package/lib/constants.js +0 -55
  44. package/lib/count-queue.js +0 -188
  45. package/lib/distributed-cache-invalidator.js +0 -260
  46. package/lib/errors.js +0 -168
  47. package/lib/expression/cache/ExpressionCache.js +0 -114
  48. package/lib/expression/compiler/ExpressionCompiler.js +0 -1090
  49. package/lib/expression/compiler/ExpressionCompilerExtensions.js +0 -531
  50. package/lib/expression/detector.js +0 -84
  51. package/lib/expression/factory.js +0 -29
  52. package/lib/expression/index.js +0 -19
  53. package/lib/function-cache.js +0 -533
  54. package/lib/index.js +0 -1251
  55. package/lib/infrastructure/ConnectionPoolManager.js +0 -464
  56. package/lib/infrastructure/HealthChecker.js +0 -281
  57. package/lib/infrastructure/PoolConfig.js +0 -199
  58. package/lib/infrastructure/PoolSelector.js +0 -225
  59. package/lib/infrastructure/PoolStats.js +0 -244
  60. package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -212
  61. package/lib/infrastructure/ssh-tunnel.js +0 -41
  62. package/lib/infrastructure/uri-parser.js +0 -36
  63. package/lib/lock/Lock.js +0 -67
  64. package/lib/lock/errors.js +0 -28
  65. package/lib/lock/index.js +0 -13
  66. package/lib/logger.js +0 -225
  67. package/lib/model/examples/test.js +0 -311
  68. package/lib/model/features/defaults.js +0 -161
  69. package/lib/model/features/populate.js +0 -568
  70. package/lib/model/features/relations.js +0 -120
  71. package/lib/model/features/soft-delete.js +0 -349
  72. package/lib/model/features/version.js +0 -157
  73. package/lib/model/features/virtuals.js +0 -219
  74. package/lib/model/index.js +0 -1265
  75. package/lib/mongodb/common/accessor-helpers.js +0 -59
  76. package/lib/mongodb/common/agg-pipeline.js +0 -36
  77. package/lib/mongodb/common/aggregation-validator.js +0 -127
  78. package/lib/mongodb/common/iid.js +0 -28
  79. package/lib/mongodb/common/lexicographic-expr.js +0 -53
  80. package/lib/mongodb/common/shape.js +0 -32
  81. package/lib/mongodb/common/sort.js +0 -39
  82. package/lib/mongodb/common/transaction-aware.js +0 -25
  83. package/lib/mongodb/connect.js +0 -234
  84. package/lib/mongodb/index.js +0 -639
  85. package/lib/mongodb/management/admin-ops.js +0 -200
  86. package/lib/mongodb/management/bookmark-ops.js +0 -167
  87. package/lib/mongodb/management/cache-ops.js +0 -50
  88. package/lib/mongodb/management/collection-ops.js +0 -387
  89. package/lib/mongodb/management/database-ops.js +0 -202
  90. package/lib/mongodb/management/index-ops.js +0 -475
  91. package/lib/mongodb/management/index.js +0 -17
  92. package/lib/mongodb/management/namespace.js +0 -31
  93. package/lib/mongodb/management/validation-ops.js +0 -268
  94. package/lib/mongodb/queries/aggregate.js +0 -172
  95. package/lib/mongodb/queries/chain.js +0 -631
  96. package/lib/mongodb/queries/count.js +0 -99
  97. package/lib/mongodb/queries/distinct.js +0 -78
  98. package/lib/mongodb/queries/find-and-count.js +0 -193
  99. package/lib/mongodb/queries/find-by-ids.js +0 -236
  100. package/lib/mongodb/queries/find-one-by-id.js +0 -171
  101. package/lib/mongodb/queries/find-one.js +0 -71
  102. package/lib/mongodb/queries/find-page.js +0 -618
  103. package/lib/mongodb/queries/find.js +0 -171
  104. package/lib/mongodb/queries/index.js +0 -51
  105. package/lib/mongodb/queries/watch.js +0 -538
  106. package/lib/mongodb/writes/common/batch-retry.js +0 -65
  107. package/lib/mongodb/writes/delete-batch.js +0 -323
  108. package/lib/mongodb/writes/delete-many.js +0 -181
  109. package/lib/mongodb/writes/delete-one.js +0 -173
  110. package/lib/mongodb/writes/find-one-and-delete.js +0 -203
  111. package/lib/mongodb/writes/find-one-and-replace.js +0 -239
  112. package/lib/mongodb/writes/find-one-and-update.js +0 -240
  113. package/lib/mongodb/writes/increment-one.js +0 -259
  114. package/lib/mongodb/writes/index.js +0 -46
  115. package/lib/mongodb/writes/insert-batch.js +0 -508
  116. package/lib/mongodb/writes/insert-many.js +0 -223
  117. package/lib/mongodb/writes/insert-one.js +0 -169
  118. package/lib/mongodb/writes/replace-one.js +0 -226
  119. package/lib/mongodb/writes/result-handler.js +0 -237
  120. package/lib/mongodb/writes/update-batch.js +0 -416
  121. package/lib/mongodb/writes/update-many.js +0 -275
  122. package/lib/mongodb/writes/update-one.js +0 -273
  123. package/lib/mongodb/writes/upsert-one.js +0 -203
  124. package/lib/multi-level-cache.js +0 -244
  125. package/lib/operators.js +0 -330
  126. package/lib/redis-cache-adapter.js +0 -267
  127. package/lib/saga/SagaContext.js +0 -67
  128. package/lib/saga/SagaDefinition.js +0 -32
  129. package/lib/saga/SagaExecutor.js +0 -201
  130. package/lib/saga/SagaOrchestrator.js +0 -186
  131. package/lib/saga/index.js +0 -11
  132. package/lib/slow-query-log/base-storage.js +0 -70
  133. package/lib/slow-query-log/batch-queue.js +0 -97
  134. package/lib/slow-query-log/config-manager.js +0 -196
  135. package/lib/slow-query-log/index.js +0 -238
  136. package/lib/slow-query-log/mongodb-storage.js +0 -324
  137. package/lib/slow-query-log/query-hash.js +0 -39
  138. package/lib/sync/ChangeStreamSyncManager.js +0 -405
  139. package/lib/sync/ResumeTokenStore.js +0 -192
  140. package/lib/sync/SyncConfig.js +0 -127
  141. package/lib/sync/SyncTarget.js +0 -240
  142. package/lib/sync/index.js +0 -20
  143. package/lib/transaction/CacheLockManager.js +0 -162
  144. package/lib/transaction/DistributedCacheLockManager.js +0 -475
  145. package/lib/transaction/Transaction.js +0 -315
  146. package/lib/transaction/TransactionManager.js +0 -267
  147. package/lib/transaction/index.js +0 -11
  148. package/lib/utils/objectid-converter.js +0 -632
  149. package/types/README.md +0 -122
  150. package/types/base.ts +0 -94
  151. package/types/batch.ts +0 -187
  152. package/types/cache.ts +0 -71
  153. package/types/chain.ts +0 -254
  154. package/types/collection.ts +0 -357
  155. package/types/expression.ts +0 -109
  156. package/types/function-cache.d.ts +0 -135
  157. package/types/lock.ts +0 -95
  158. package/types/model/definition.ts +0 -152
  159. package/types/model/index.ts +0 -10
  160. package/types/model/instance.ts +0 -121
  161. package/types/model/relations.ts +0 -121
  162. package/types/model/virtuals.ts +0 -32
  163. package/types/monsqlize.ts +0 -245
  164. package/types/options.ts +0 -192
  165. package/types/pagination.ts +0 -154
  166. package/types/pool.ts +0 -125
  167. package/types/query.ts +0 -71
  168. package/types/saga.ts +0 -125
  169. package/types/stream.ts +0 -64
  170. package/types/sync.ts +0 -79
  171. package/types/transaction.ts +0 -79
  172. package/types/write.ts +0 -77
@@ -1,27 +0,0 @@
1
- /**
2
- * 通用慢日志形状构造器(去敏)
3
- * 仅保留安全元信息与标记位;真正的 query/projection/sort 形状由适配器层注入。
4
- */
5
-
6
- function buildCommonLogExtra(options) {
7
- const pick = (obj, fields) => Object.fromEntries((fields || []).filter(k => obj && k in obj).map(k => [k, obj[k]]));
8
- const meta = pick(options || {}, ['limit', 'skip', 'maxTimeMS', 'cache']);
9
-
10
- // 聚合阶段名(仅名称,避免输出参数)
11
- if (options?.pipeline && Array.isArray(options.pipeline)) {
12
- try {
13
- meta.pipelineStages = options.pipeline.map(p => Object.keys(p)[0]).slice(0, 30);
14
- } catch (_) { /* ignore */ }
15
- }
16
-
17
- // 游标标记
18
- if (options?.after || options?.before) {
19
- meta.hasCursor = true;
20
- meta.cursorDirection = options.after ? 'after' : 'before';
21
- }
22
-
23
- return meta;
24
- }
25
-
26
- module.exports = { buildCommonLogExtra };
27
-
@@ -1,113 +0,0 @@
1
- /**
2
- * 通用校验工具
3
- * - validateLimitAfterBefore: 校验 limit 合法与 after/before 互斥
4
- * - assertCursorSortCompatible: 校验游标中的排序与当前排序一致(字段与方向完全一致)
5
- */
6
-
7
- const { createValidationError, createCursorError } = require('../errors');
8
-
9
- /**
10
- * @param {{limit?:number, after?:string, before?:string}} opts
11
- * @param {{maxLimit?:number}} cfg
12
- */
13
- function validateLimitAfterBefore(opts, { maxLimit = 500 } = {}) {
14
- const { limit, after, before } = opts || {};
15
- if (!Number.isInteger(limit) || limit <= 0 || limit > maxLimit) {
16
- throw createValidationError([{ path:['limit'], type:'number.range', message:`1..${maxLimit}` }]);
17
- }
18
- if (after && before) {
19
- throw createValidationError([{ path:['after'], type:'any.conflict', message:'after/before 互斥' }]);
20
- }
21
- }
22
-
23
- /**
24
- * 校验游标排序与当前排序一致
25
- * @param {Record<string,1|-1>} currentSort
26
- * @param {Record<string,1|-1>|undefined} cursorSort
27
- */
28
- function assertCursorSortCompatible(currentSort, cursorSort) {
29
- const k1 = Object.keys(currentSort || {});
30
- const k2 = Object.keys(cursorSort || {});
31
- const same = k1.length === k2.length && k1.every(k => cursorSort && cursorSort[k] === currentSort[k]);
32
- if (!same) {
33
- // 使用专门的 CURSOR_SORT_MISMATCH 错误码
34
- const { ErrorCodes, createError } = require('../errors');
35
- throw createError(
36
- ErrorCodes.CURSOR_SORT_MISMATCH,
37
- '游标排序不匹配:游标中的排序与当前查询的排序不一致',
38
- [{
39
- path: ['cursor'],
40
- type: 'cursor.sort.mismatch',
41
- message: 'cursor sort mismatches current sort',
42
- cursorSort,
43
- currentSort
44
- }]
45
- );
46
- }
47
- }
48
-
49
- /**
50
- * 验证数值范围
51
- * @param {number} value - 要验证的数值
52
- * @param {number} min - 最小值(包含)
53
- * @param {number} max - 最大值(包含)
54
- * @param {string} name - 参数名称(用于错误消息)
55
- * @returns {number} 验证通过后的值
56
- * @throws {Error} 当值不在有效范围内时抛出 INVALID_ARGUMENT 错误
57
- */
58
- function validateRange(value, min, max, name) {
59
- const { ErrorCodes, createError } = require('../errors');
60
-
61
- // 检查是否为有效数字
62
- if (typeof value !== 'number' || isNaN(value)) {
63
- throw createError(
64
- ErrorCodes.INVALID_ARGUMENT,
65
- `${name} 必须是一个有效的数字`
66
- );
67
- }
68
-
69
- // 检查是否为有限数(排除 Infinity)
70
- if (!isFinite(value)) {
71
- throw createError(
72
- ErrorCodes.INVALID_ARGUMENT,
73
- `${name} 必须是有限数字`
74
- );
75
- }
76
-
77
- // 检查范围
78
- if (value < min || value > max) {
79
- throw createError(
80
- ErrorCodes.INVALID_ARGUMENT,
81
- `${name} 必须在 ${min} 到 ${max} 之间,当前值: ${value}`
82
- );
83
- }
84
-
85
- return value;
86
- }
87
-
88
- /**
89
- * 验证正整数
90
- * @param {number} value - 要验证的数值
91
- * @param {string} name - 参数名称(用于错误消息)
92
- * @returns {number} 验证通过后的值
93
- * @throws {Error} 当值不是正整数时抛出错误
94
- */
95
- function validatePositiveInteger(value, name) {
96
- const { ErrorCodes, createError } = require('../errors');
97
-
98
- if (!Number.isInteger(value) || value <= 0) {
99
- throw createError(
100
- ErrorCodes.INVALID_ARGUMENT,
101
- `${name} 必须是正整数,当前值: ${value}`
102
- );
103
- }
104
- return value;
105
- }
106
-
107
- module.exports = {
108
- validateLimitAfterBefore,
109
- assertCursorSortCompatible,
110
- validateRange,
111
- validatePositiveInteger
112
- };
113
-
package/lib/connect.js DELETED
@@ -1,99 +0,0 @@
1
- /**
2
- * 数据库连接管理器
3
- * 统一管理各种数据库的连接创建和实例化逻辑
4
- */
5
- const Mongo = require("./mongodb");
6
-
7
- module.exports = class ConnectionManager {
8
- /**
9
- * 支持的数据库类型映射
10
- */
11
- static get SUPPORTED_DATABASES() {
12
- return {
13
- mongodb: Mongo,
14
- };
15
- }
16
-
17
- /**
18
- * 创建数据库实例
19
- * @param {string} type - 数据库类型
20
- * @param {string} databaseName - 数据库名称
21
- * @param {Object} cache - 缓存实例(内存缓存)
22
- * @param {Object} logger - 日志记录器
23
- * @param {Object} [defaults] - 统一默认配置(如 maxTimeMS、namespace)
24
- * @returns {Object} 数据库实例
25
- * @throws {Error} 当数据库类型不支持或未实现时抛出错误
26
- */
27
- static createInstance(type, databaseName, cache, logger, defaults) {
28
- const SUPPORTED_DATABASES = this.SUPPORTED_DATABASES;
29
- // 验证数据库类型是否支持
30
- if (!(type in SUPPORTED_DATABASES)) {
31
- const supportedTypes = Object.keys(SUPPORTED_DATABASES).join(", ");
32
- throw new Error(
33
- `Invalid database type: ${type}. Supported types are: ${supportedTypes}`,
34
- );
35
- }
36
-
37
- // 检查是否已实现
38
- if (SUPPORTED_DATABASES[type] === null) {
39
- throw new Error(`${type} support not implemented yet`);
40
- }
41
-
42
- // 获取对应的数据库类
43
- const DatabaseClass = SUPPORTED_DATABASES[type];
44
-
45
- // 创建并返回实例
46
- return new DatabaseClass(type, databaseName, cache, logger, defaults);
47
- }
48
-
49
- /**
50
- * 连接数据库
51
- * @param {string} type - 数据库类型
52
- * @param {string} databaseName - 数据库名称
53
- * @param {Object} config - 数据库连接配置
54
- * @param {Object} cache - 缓存实例
55
- * @param {Object} logger - 日志记录器
56
- * @param {Object} [defaults] - 统一默认配置(如 maxTimeMS、namespace)
57
- * @param {Object} [poolManager] - 多连接池管理器(v1.0.8+)
58
- * @returns {{accessor: Function, instance: Object}} 访问器与底层适配器实例
59
- * @throws {Error} 连接失败时抛出错误
60
- */
61
- static async connect(
62
- type,
63
- databaseName,
64
- config,
65
- cache,
66
- logger,
67
- defaults,
68
- poolManager,
69
- ) {
70
- // 创建数据库实例
71
- const instance = this.createInstance(
72
- type,
73
- databaseName,
74
- cache,
75
- logger,
76
- defaults,
77
- );
78
-
79
- // 🆕 v1.0.8: 传递 poolManager 给实例
80
- if (poolManager) {
81
- instance.poolManager = poolManager;
82
- }
83
-
84
- // 建立连接
85
- await instance.connect(config);
86
-
87
- // ---------- 构建访问器 ----------
88
- const collection = (collectionName) =>
89
- instance.collection(databaseName, collectionName);
90
- const db = (databaseName) => {
91
- return {
92
- collection: (collectionName) =>
93
- instance.collection(databaseName, collectionName),
94
- };
95
- };
96
-
97
- return { collection, db, use: db, instance };
98
- }
99
- };
package/lib/constants.js DELETED
@@ -1,55 +0,0 @@
1
- /**
2
- * 统一常量定义
3
- * 集中管理所有魔法数字和配置常量
4
- */
5
-
6
- module.exports = {
7
- // 缓存相关
8
- CACHE: {
9
- DEFAULT_MAX_SIZE: 100000, // 默认最大缓存条目数
10
- DEFAULT_MAX_MEMORY: 0, // 默认最大内存(字节),0 表示不限制
11
- TOTALS_INFLIGHT_WINDOW_MS: 5000, // totals 去重窗口(毫秒)
12
- REMOTE_TIMEOUT_MS: 50, // 远端缓存操作超时(毫秒)
13
- },
14
-
15
- // 查询相关
16
- QUERY: {
17
- DEFAULT_SLOW_QUERY_MS: 500, // 慢查询阈值(毫秒)
18
- DEFAULT_FIND_LIMIT: 10, // find 默认 limit
19
- DEFAULT_FINDPAGE_MAX_LIMIT: 500, // findPage 最大 limit
20
- DEFAULT_MAX_TIME_MS: 30000, // 默认查询超时(毫秒)
21
- },
22
-
23
- // 分页相关
24
- PAGINATION: {
25
- DEFAULT_STEP: 10, // 书签密度:每隔多少页存一个书签
26
- DEFAULT_MAX_HOPS: 20, // 单次跳页最大 hops
27
- DEFAULT_MAX_SKIP: 50000, // offset 跳页最大 skip
28
- },
29
-
30
- // 流式查询相关
31
- STREAM: {
32
- DEFAULT_BATCH_SIZE: 1000, // 流式查询默认批次大小
33
- },
34
-
35
- // 连接相关
36
- CONNECTION: {
37
- DEFAULT_POOL_SIZE: 10, // 默认连接池大小
38
- CONNECTION_TIMEOUT_MS: 30000, // 连接超时(毫秒)
39
- },
40
-
41
- // 命名空间相关
42
- NAMESPACE: {
43
- DEFAULT_SCOPE: 'database', // 默认命名空间范围
44
- BOOKMARK_PREFIX: 'bm:', // 书签键前缀
45
- TOTALS_PREFIX: 'tot:', // 总数键前缀
46
- },
47
-
48
- // 日志相关
49
- LOG: {
50
- MAX_QUERY_SHAPE_LENGTH: 1000, // 查询形状最大长度(日志)
51
- MAX_ERROR_MESSAGE_LENGTH: 500, // 错误消息最大长度
52
- },
53
- };
54
-
55
-
@@ -1,188 +0,0 @@
1
- /**
2
- * Count 队列控制器
3
- * 限制同时执行的 count 数量,避免高并发下压垮数据库
4
- *
5
- * 使用场景:
6
- * - findPage 的 totals 统计
7
- * - 任何需要执行 countDocuments 的场景
8
- *
9
- * 核心功能:
10
- * 1. 并发控制 - 限制同时执行的 count 数量
11
- * 2. 队列管理 - 超出并发限制的请求排队等待
12
- * 3. 超时保护 - 防止请求长时间等待
13
- * 4. 统计监控 - 提供队列状态和统计信息
14
- */
15
- class CountQueue {
16
- constructor(options = {}) {
17
- // 默认并发数:CPU 核心数(最少 4,最多 16)
18
- const cpuCount = require('os').cpus().length;
19
- const defaultConcurrency = Math.max(4, Math.min(cpuCount, 16));
20
-
21
- this.concurrency = options.concurrency || defaultConcurrency;
22
- this.maxQueueSize = options.maxQueueSize || 10000; // 队列最大长度(增加到 10000)
23
- this.timeout = options.timeout || 60000; // 超时 60 秒(增加到 1 分钟)
24
-
25
- this.queue = []; // 等待队列
26
- this.running = 0; // 当前执行数
27
-
28
- // 统计信息
29
- this.stats = {
30
- executed: 0, // 已执行总数
31
- queued: 0, // 曾排队总数
32
- timeout: 0, // 超时次数
33
- rejected: 0, // 拒绝次数(队列满)
34
- avgWaitTime: 0, // 平均等待时间
35
- maxWaitTime: 0 // 最大等待时间
36
- };
37
- }
38
-
39
- /**
40
- * 执行 count 操作(带队列控制)
41
- * @param {Function} fn - count 操作函数
42
- * @returns {Promise<number>} count 结果
43
- * @throws {Error} 队列满或超时
44
- */
45
- async execute(fn) {
46
- const startTime = Date.now();
47
-
48
- // 检查是否需要排队
49
- if (this.running >= this.concurrency) {
50
- // 检查队列是否满了
51
- if (this.queue.length >= this.maxQueueSize) {
52
- this.stats.rejected++;
53
- throw new Error(`Count queue is full (${this.maxQueueSize})`);
54
- }
55
-
56
- this.stats.queued++;
57
- // 等待轮到自己
58
- await this._waitInQueue(startTime);
59
- }
60
-
61
- // 获得执行机会,增加 running
62
- this.running++;
63
- this.stats.executed++;
64
-
65
- try {
66
- // 带超时控制
67
- return await this._executeWithTimeout(fn);
68
- } finally {
69
- this.running--;
70
- // 唤醒队列中的下一个
71
- this._wakeNext();
72
- }
73
- }
74
-
75
- /**
76
- * 等待队列
77
- * @private
78
- */
79
- async _waitInQueue(startTime) {
80
- return new Promise((resolve, reject) => {
81
- const timer = setTimeout(() => {
82
- // 超时,从队列中移除
83
- const index = this.queue.findIndex(item => item.resolve === resolve);
84
- if (index !== -1) {
85
- this.queue.splice(index, 1);
86
- this.stats.timeout++;
87
- reject(new Error(`Count queue wait timeout (${this.timeout}ms)`));
88
- }
89
- }, this.timeout);
90
-
91
- this.queue.push({
92
- resolve: () => {
93
- const waitTime = Date.now() - startTime;
94
- this._updateWaitTimeStats(waitTime);
95
- resolve();
96
- },
97
- timer,
98
- startTime
99
- });
100
- });
101
- }
102
-
103
- /**
104
- * 唤醒队列中的下一个
105
- * @private
106
- */
107
- _wakeNext() {
108
- if (this.queue.length > 0) {
109
- const { resolve, timer } = this.queue.shift();
110
- clearTimeout(timer);
111
- resolve();
112
- }
113
- }
114
-
115
- /**
116
- * 带超时的执行
117
- * @private
118
- */
119
- async _executeWithTimeout(fn) {
120
- return Promise.race([
121
- fn(),
122
- new Promise((_, reject) =>
123
- setTimeout(() => reject(new Error(`Count execution timeout (${this.timeout}ms)`)), this.timeout)
124
- )
125
- ]);
126
- }
127
-
128
- /**
129
- * 更新等待时间统计
130
- * @private
131
- */
132
- _updateWaitTimeStats(waitTime) {
133
- // 计算平均等待时间
134
- const totalQueued = this.stats.queued;
135
- this.stats.avgWaitTime = (this.stats.avgWaitTime * (totalQueued - 1) + waitTime) / totalQueued;
136
-
137
- // 更新最大等待时间
138
- if (waitTime > this.stats.maxWaitTime) {
139
- this.stats.maxWaitTime = waitTime;
140
- }
141
- }
142
-
143
- /**
144
- * 获取统计信息
145
- * @returns {Object} 统计信息
146
- */
147
- getStats() {
148
- return {
149
- ...this.stats,
150
- running: this.running, // 当前执行中
151
- queuedNow: this.queue.length, // 当前排队中
152
- concurrency: this.concurrency, // 并发限制
153
- maxQueueSize: this.maxQueueSize // 队列容量
154
- };
155
- }
156
-
157
- /**
158
- * 重置统计信息
159
- */
160
- resetStats() {
161
- this.stats = {
162
- executed: 0,
163
- queued: 0,
164
- timeout: 0,
165
- rejected: 0,
166
- avgWaitTime: 0,
167
- maxWaitTime: 0
168
- };
169
- }
170
-
171
- /**
172
- * 清空队列(慎用)
173
- */
174
- clear() {
175
- // 拒绝所有等待中的请求
176
- while (this.queue.length > 0) {
177
- const item = this.queue.shift();
178
- clearTimeout(item.timer);
179
- // 注意:这里不能直接 resolve 错误
180
- // 因为队列项只存储了 resolve,没有 reject
181
- // 所以清空操作只是清理队列,不触发错误
182
- }
183
- }
184
- }
185
-
186
- module.exports = CountQueue;
187
-
188
-