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,260 +0,0 @@
1
- /**
2
- * 分布式缓存失效器
3
- * 基于 Redis Pub/Sub 实现跨实例的缓存失效通知
4
- *
5
- * @example
6
- * const invalidator = new DistributedCacheInvalidator({
7
- * redisUrl: 'redis://localhost:6379',
8
- * channel: 'monsqlize:cache:invalidate',
9
- * cache: multiLevelCacheInstance
10
- * });
11
- *
12
- * // 广播失效消息
13
- * await invalidator.invalidate('user:*');
14
- */
15
-
16
- class DistributedCacheInvalidator {
17
- /**
18
- * @param {Object} options
19
- * @param {string} [options.redisUrl] - Redis 连接 URL
20
- * @param {Object} [options.redis] - 已创建的 Redis 实例(与 redisUrl 二选一)
21
- * @param {string} [options.channel='monsqlize:cache:invalidate'] - Pub/Sub 频道
22
- * @param {string} [options.instanceId] - 实例 ID(自动生成)
23
- * @param {Object} options.cache - MultiLevelCache 实例
24
- * @param {Object} [options.logger] - 日志记录器
25
- */
26
- constructor(options = {}) {
27
- if (!options.cache) {
28
- throw new Error('DistributedCacheInvalidator requires a cache instance');
29
- }
30
-
31
- this.cache = options.cache;
32
- this.logger = options.logger;
33
- this.channel = options.channel || 'monsqlize:cache:invalidate';
34
- this.instanceId = options.instanceId || `instance-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
35
-
36
- // 初始化 Redis 连接
37
- this._initRedis(options);
38
-
39
- // 设置订阅
40
- this._setupSubscription();
41
-
42
- // 统计信息
43
- this.stats = {
44
- messagesSent: 0,
45
- messagesReceived: 0,
46
- invalidationsTriggered: 0,
47
- errors: 0
48
- };
49
- }
50
-
51
- /**
52
- * 初始化 Redis 连接
53
- * @private
54
- */
55
- _initRedis(options) {
56
- try {
57
- const Redis = require('ioredis');
58
-
59
- if (options.redis) {
60
- // 使用已有的 Redis 实例
61
- this.pub = options.redis;
62
- // 订阅需要单独的连接
63
- const redisConfig = options.redis.options || {};
64
- this.sub = new Redis({
65
- ...redisConfig,
66
- host: redisConfig.host || 'localhost',
67
- port: redisConfig.port || 6379
68
- });
69
- this._ownsConnections = false;
70
- } else if (options.redisUrl) {
71
- // 创建新的 Redis 连接
72
- this.pub = new Redis(options.redisUrl);
73
- this.sub = new Redis(options.redisUrl);
74
- this._ownsConnections = true;
75
- } else {
76
- // 默认本地连接
77
- this.pub = new Redis('redis://localhost:6379');
78
- this.sub = new Redis('redis://localhost:6379');
79
- this._ownsConnections = true;
80
- }
81
-
82
- // 错误处理
83
- this.pub.on('error', (err) => {
84
- this.stats.errors++;
85
- if (this.logger) {
86
- this.logger.error('[DistributedCacheInvalidator] Redis pub error:', err.message);
87
- }
88
- });
89
-
90
- this.sub.on('error', (err) => {
91
- this.stats.errors++;
92
- if (this.logger) {
93
- this.logger.error('[DistributedCacheInvalidator] Redis sub error:', err.message);
94
- }
95
- });
96
- } catch (error) {
97
- throw new Error(
98
- 'Failed to initialize Redis for DistributedCacheInvalidator. ' +
99
- 'Please ensure ioredis is installed: npm install ioredis'
100
- );
101
- }
102
- }
103
-
104
- /**
105
- * 设置订阅处理
106
- * @private
107
- */
108
- _setupSubscription() {
109
- this.sub.subscribe(this.channel, (err) => {
110
- if (err) {
111
- this.stats.errors++;
112
- if (this.logger) {
113
- this.logger.error('[DistributedCacheInvalidator] Subscribe error:', err.message);
114
- }
115
- } else {
116
- if (this.logger) {
117
- this.logger.info(`[DistributedCacheInvalidator] Subscribed to channel: ${this.channel}`);
118
- }
119
- }
120
- });
121
-
122
- this.sub.on('message', (channel, message) => {
123
- if (channel !== this.channel) return;
124
-
125
- this.stats.messagesReceived++;
126
-
127
- try {
128
- const data = JSON.parse(message);
129
-
130
- // 忽略自己发送的消息(避免重复失效)
131
- if (data.instanceId === this.instanceId) {
132
- return;
133
- }
134
-
135
- // 处理失效消息
136
- if (data.type === 'invalidate' && data.pattern) {
137
- this._handleInvalidation(data.pattern);
138
- }
139
- } catch (error) {
140
- this.stats.errors++;
141
- if (this.logger) {
142
- this.logger.error('[DistributedCacheInvalidator] Message parse error:', error.message);
143
- }
144
- }
145
- });
146
- }
147
-
148
- /**
149
- * 处理缓存失效
150
- * @private
151
- */
152
- async _handleInvalidation(pattern) {
153
- try {
154
- if (this.logger) {
155
- this.logger.debug(`[DistributedCacheInvalidator] Handling invalidation, pattern: ${pattern}`);
156
- }
157
-
158
- let deleted = 0;
159
-
160
- // 1. 失效本地缓存
161
- if (this.cache.local && typeof this.cache.local.delPattern === 'function') {
162
- deleted = await this.cache.local.delPattern(pattern);
163
- if (this.logger) {
164
- this.logger.debug(`[DistributedCacheInvalidator] Invalidated local cache: ${pattern}, deleted: ${deleted} keys`);
165
- }
166
- }
167
-
168
- // 2. 失效远端缓存(Redis)
169
- if (this.cache.remote && typeof this.cache.remote.delPattern === 'function') {
170
- const remoteDeleted = await this.cache.remote.delPattern(pattern);
171
- deleted += remoteDeleted;
172
- if (this.logger) {
173
- this.logger.debug(`[DistributedCacheInvalidator] Invalidated remote cache: ${pattern}, deleted: ${remoteDeleted} keys`);
174
- }
175
- }
176
-
177
- this.stats.invalidationsTriggered++;
178
-
179
- if (this.logger) {
180
- this.logger.info(`[DistributedCacheInvalidator] Total invalidated: ${pattern}, deleted: ${deleted} keys`);
181
- }
182
- } catch (error) {
183
- this.stats.errors++;
184
- if (this.logger) {
185
- this.logger.error('[DistributedCacheInvalidator] Invalidation error:', error.message);
186
- }
187
- }
188
- }
189
-
190
- /**
191
- * 广播缓存失效消息
192
- * @param {string} pattern - 缓存键模式(支持通配符 *)
193
- * @returns {Promise<void>}
194
- */
195
- async invalidate(pattern) {
196
- if (!pattern) return;
197
-
198
- const message = JSON.stringify({
199
- type: 'invalidate',
200
- pattern,
201
- instanceId: this.instanceId,
202
- timestamp: Date.now()
203
- });
204
-
205
- try {
206
- await this.pub.publish(this.channel, message);
207
- this.stats.messagesSent++;
208
-
209
- if (this.logger) {
210
- this.logger.debug(`[DistributedCacheInvalidator] Published invalidation: ${pattern}`);
211
- }
212
- } catch (error) {
213
- this.stats.errors++;
214
- if (this.logger) {
215
- this.logger.error('[DistributedCacheInvalidator] Publish error:', error.message);
216
- }
217
- throw error;
218
- }
219
- }
220
-
221
- /**
222
- * 获取统计信息
223
- * @returns {Object}
224
- */
225
- getStats() {
226
- return {
227
- ...this.stats,
228
- instanceId: this.instanceId,
229
- channel: this.channel
230
- };
231
- }
232
-
233
- /**
234
- * 关闭连接
235
- * @returns {Promise<void>}
236
- */
237
- async close() {
238
- try {
239
- // 取消订阅
240
- await this.sub.unsubscribe(this.channel);
241
-
242
- // 如果是自己创建的连接,才关闭
243
- if (this._ownsConnections) {
244
- await this.pub.quit();
245
- await this.sub.quit();
246
- }
247
-
248
- if (this.logger) {
249
- this.logger.info('[DistributedCacheInvalidator] Closed');
250
- }
251
- } catch (error) {
252
- if (this.logger) {
253
- this.logger.error('[DistributedCacheInvalidator] Close error:', error.message);
254
- }
255
- }
256
- }
257
- }
258
-
259
- module.exports = DistributedCacheInvalidator;
260
-
package/lib/errors.js DELETED
@@ -1,168 +0,0 @@
1
- /**
2
- * 统一错误码定义
3
- * 集中管理所有错误类型,确保错误处理的一致性
4
- */
5
-
6
- const ErrorCodes = {
7
- // 验证相关错误
8
- VALIDATION_ERROR: 'VALIDATION_ERROR',
9
- INVALID_ARGUMENT: 'INVALID_ARGUMENT',
10
- INVALID_COLLECTION_NAME: 'INVALID_COLLECTION_NAME',
11
- INVALID_DATABASE_NAME: 'INVALID_DATABASE_NAME',
12
-
13
- // 游标相关错误
14
- INVALID_CURSOR: 'INVALID_CURSOR',
15
- CURSOR_SORT_MISMATCH: 'CURSOR_SORT_MISMATCH',
16
-
17
- // 分页相关错误
18
- JUMP_TOO_FAR: 'JUMP_TOO_FAR',
19
- STREAM_NO_JUMP: 'STREAM_NO_JUMP',
20
- STREAM_NO_TOTALS: 'STREAM_NO_TOTALS',
21
- STREAM_NO_EXPLAIN: 'STREAM_NO_EXPLAIN',
22
-
23
- // 连接相关错误
24
- CONNECTION_TIMEOUT: 'CONNECTION_TIMEOUT',
25
- CONNECTION_FAILED: 'CONNECTION_FAILED',
26
- CONNECTION_CLOSED: 'CONNECTION_CLOSED',
27
-
28
- // 数据库相关错误
29
- DATABASE_ERROR: 'DATABASE_ERROR',
30
- QUERY_TIMEOUT: 'QUERY_TIMEOUT',
31
-
32
- // 缓存相关错误
33
- CACHE_ERROR: 'CACHE_ERROR',
34
- CACHE_TIMEOUT: 'CACHE_TIMEOUT',
35
-
36
- // 配置相关错误
37
- INVALID_CONFIG: 'INVALID_CONFIG',
38
- UNSUPPORTED_DATABASE: 'UNSUPPORTED_DATABASE',
39
-
40
- // 写操作相关错误
41
- WRITE_ERROR: 'WRITE_ERROR',
42
- DOCUMENT_REQUIRED: 'DOCUMENT_REQUIRED',
43
- DOCUMENTS_REQUIRED: 'DOCUMENTS_REQUIRED',
44
- DUPLICATE_KEY: 'DUPLICATE_KEY',
45
- WRITE_CONFLICT: 'WRITE_CONFLICT',
46
-
47
- // 🆕 v1.4.0: 锁相关错误
48
- LOCK_ACQUIRE_FAILED: 'LOCK_ACQUIRE_FAILED',
49
- LOCK_TIMEOUT: 'LOCK_TIMEOUT',
50
- };
51
-
52
- /**
53
- * 创建标准错误对象
54
- * @param {string} code - 错误码
55
- * @param {string} message - 错误消息
56
- * @param {Array} [details] - 详细错误信息
57
- * @param {Error} [cause] - 原始错误
58
- * @returns {Error} 标准错误对象
59
- */
60
- function createError(code, message, details, cause) {
61
- const error = new Error(message);
62
- error.code = code;
63
- if (details !== undefined) error.details = details;
64
- if (cause !== undefined) error.cause = cause;
65
- return error;
66
- }
67
-
68
- /**
69
- * 创建验证错误
70
- * @param {string|Array} messageOrDetails - 错误消息或验证错误详情(向后兼容)
71
- * @param {Array} [details] - 详细信息(当第一个参数是字符串时使用)
72
- * @returns {Error}
73
- */
74
- function createValidationError(messageOrDetails, details) {
75
- // 向后兼容:如果第一个参数是数组,当作 details 处理
76
- if (Array.isArray(messageOrDetails)) {
77
- return createError(
78
- ErrorCodes.VALIDATION_ERROR,
79
- '参数校验失败',
80
- messageOrDetails
81
- );
82
- }
83
-
84
- // 新用法:第一个参数是消息字符串
85
- return createError(
86
- ErrorCodes.VALIDATION_ERROR,
87
- messageOrDetails || '参数校验失败',
88
- details
89
- );
90
- }
91
-
92
- /**
93
- * 创建游标错误
94
- * @param {string} message - 错误消息
95
- * @param {Array} [details] - 详细信息
96
- * @returns {Error}
97
- */
98
- function createCursorError(message, details = null) {
99
- return createError(
100
- ErrorCodes.INVALID_CURSOR,
101
- message || '游标无效',
102
- details
103
- );
104
- }
105
-
106
- /**
107
- * 创建连接错误
108
- * @param {string} message - 错误消息
109
- * @param {Error} [cause] - 原始错误
110
- * @returns {Error}
111
- */
112
- function createConnectionError(message, cause = null) {
113
- return createError(
114
- ErrorCodes.CONNECTION_FAILED,
115
- message || '数据库连接失败',
116
- null,
117
- cause
118
- );
119
- }
120
-
121
- /**
122
- * 创建查询超时错误
123
- * @param {number} timeoutMs - 超时时间(毫秒)
124
- * @param {Error} [cause] - 原始错误
125
- * @returns {Error}
126
- */
127
- function createQueryTimeoutError(timeoutMs, cause = null) {
128
- return createError(
129
- ErrorCodes.QUERY_TIMEOUT,
130
- `查询超时 (${timeoutMs}ms)`,
131
- null,
132
- cause
133
- );
134
- }
135
-
136
- /**
137
- * 创建写操作错误
138
- * @param {string} operation - 操作名称
139
- * @param {string} message - 错误消息
140
- * @param {Error} [cause] - 原始错误
141
- * @returns {Error}
142
- */
143
- function createWriteError(operation, message, cause = null) {
144
- return createError(
145
- ErrorCodes.WRITE_ERROR,
146
- `${operation} 失败: ${message}`,
147
- null,
148
- cause
149
- );
150
- }
151
-
152
- // 🆕 v1.4.0: 导入锁错误类
153
- const { LockAcquireError, LockTimeoutError } = require('./lock/errors');
154
-
155
- module.exports = {
156
- ErrorCodes,
157
- createError,
158
- createValidationError,
159
- createCursorError,
160
- createConnectionError,
161
- createQueryTimeoutError,
162
- createWriteError,
163
- // 🆕 v1.4.0: 锁错误类
164
- LockAcquireError,
165
- LockTimeoutError,
166
- };
167
-
168
-
@@ -1,114 +0,0 @@
1
- /**
2
- * 表达式编译缓存
3
- * 使用 LRU 缓存策略
4
- */
5
-
6
- class ExpressionCache {
7
- /**
8
- * @param {Object} options - 缓存配置
9
- * @param {number} options.maxSize - 最大缓存数量,默认 1000
10
- * @param {boolean} options.enabled - 是否启用缓存,默认 true
11
- */
12
- constructor(options = {}) {
13
- this.maxSize = options.maxSize || 1000;
14
- this.enabled = options.enabled !== false;
15
- this.cache = new Map();
16
- this.stats = {
17
- hits: 0,
18
- misses: 0,
19
- evictions: 0
20
- };
21
- }
22
-
23
- /**
24
- * 生成缓存键
25
- * @param {string} expression - 表达式字符串
26
- * @param {string} targetDB - 目标数据库
27
- * @returns {string} 缓存键
28
- */
29
- _generateKey(expression, targetDB = 'mongodb') {
30
- return `${targetDB}:${expression}`;
31
- }
32
-
33
- /**
34
- * 获取缓存
35
- * @param {string} expression - 表达式字符串
36
- * @param {string} targetDB - 目标数据库
37
- * @returns {*} 缓存的编译结果,不存在则返回 null
38
- */
39
- get(expression, targetDB = 'mongodb') {
40
- if (!this.enabled) {
41
- return null;
42
- }
43
-
44
- const key = this._generateKey(expression, targetDB);
45
-
46
- if (this.cache.has(key)) {
47
- this.stats.hits++;
48
- // LRU: 将访问的项移到最后
49
- const value = this.cache.get(key);
50
- this.cache.delete(key);
51
- this.cache.set(key, value);
52
- return value;
53
- }
54
-
55
- this.stats.misses++;
56
- return null;
57
- }
58
-
59
- /**
60
- * 设置缓存
61
- * @param {string} expression - 表达式字符串
62
- * @param {*} compiled - 编译结果
63
- * @param {string} targetDB - 目标数据库
64
- */
65
- set(expression, compiled, targetDB = 'mongodb') {
66
- if (!this.enabled) {
67
- return;
68
- }
69
-
70
- const key = this._generateKey(expression, targetDB);
71
-
72
- // 如果缓存已满,删除最旧的项(Map 的第一个项)
73
- if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
74
- const firstKey = this.cache.keys().next().value;
75
- this.cache.delete(firstKey);
76
- this.stats.evictions++;
77
- }
78
-
79
- this.cache.set(key, compiled);
80
- }
81
-
82
- /**
83
- * 清空缓存
84
- */
85
- clear() {
86
- this.cache.clear();
87
- this.stats = {
88
- hits: 0,
89
- misses: 0,
90
- evictions: 0
91
- };
92
- }
93
-
94
- /**
95
- * 获取缓存统计
96
- * @returns {Object} 缓存统计
97
- */
98
- getStats() {
99
- const total = this.stats.hits + this.stats.misses;
100
- const hitRate = total > 0 ? (this.stats.hits / total * 100).toFixed(2) : '0.00';
101
-
102
- return {
103
- ...this.stats,
104
- size: this.cache.size,
105
- maxSize: this.maxSize,
106
- hitRate: `${hitRate}%`,
107
- enabled: this.enabled
108
- };
109
- }
110
- }
111
-
112
- module.exports = ExpressionCache;
113
-
114
-