monsqlize 1.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 (77) hide show
  1. package/CHANGELOG.md +2474 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1368 -0
  4. package/index.d.ts +1052 -0
  5. package/lib/cache.js +491 -0
  6. package/lib/common/cursor.js +58 -0
  7. package/lib/common/docs-urls.js +72 -0
  8. package/lib/common/index-options.js +222 -0
  9. package/lib/common/log.js +60 -0
  10. package/lib/common/namespace.js +21 -0
  11. package/lib/common/normalize.js +33 -0
  12. package/lib/common/page-result.js +42 -0
  13. package/lib/common/runner.js +56 -0
  14. package/lib/common/server-features.js +231 -0
  15. package/lib/common/shape-builders.js +26 -0
  16. package/lib/common/validation.js +49 -0
  17. package/lib/connect.js +76 -0
  18. package/lib/constants.js +54 -0
  19. package/lib/count-queue.js +187 -0
  20. package/lib/distributed-cache-invalidator.js +259 -0
  21. package/lib/errors.js +157 -0
  22. package/lib/index.js +352 -0
  23. package/lib/logger.js +224 -0
  24. package/lib/model/examples/test.js +114 -0
  25. package/lib/mongodb/common/accessor-helpers.js +44 -0
  26. package/lib/mongodb/common/agg-pipeline.js +32 -0
  27. package/lib/mongodb/common/iid.js +27 -0
  28. package/lib/mongodb/common/lexicographic-expr.js +52 -0
  29. package/lib/mongodb/common/shape.js +31 -0
  30. package/lib/mongodb/common/sort.js +38 -0
  31. package/lib/mongodb/common/transaction-aware.js +24 -0
  32. package/lib/mongodb/connect.js +178 -0
  33. package/lib/mongodb/index.js +458 -0
  34. package/lib/mongodb/management/admin-ops.js +199 -0
  35. package/lib/mongodb/management/bookmark-ops.js +166 -0
  36. package/lib/mongodb/management/cache-ops.js +49 -0
  37. package/lib/mongodb/management/collection-ops.js +386 -0
  38. package/lib/mongodb/management/database-ops.js +201 -0
  39. package/lib/mongodb/management/index-ops.js +474 -0
  40. package/lib/mongodb/management/index.js +16 -0
  41. package/lib/mongodb/management/namespace.js +30 -0
  42. package/lib/mongodb/management/validation-ops.js +267 -0
  43. package/lib/mongodb/queries/aggregate.js +133 -0
  44. package/lib/mongodb/queries/chain.js +623 -0
  45. package/lib/mongodb/queries/count.js +88 -0
  46. package/lib/mongodb/queries/distinct.js +68 -0
  47. package/lib/mongodb/queries/find-and-count.js +183 -0
  48. package/lib/mongodb/queries/find-by-ids.js +235 -0
  49. package/lib/mongodb/queries/find-one-by-id.js +170 -0
  50. package/lib/mongodb/queries/find-one.js +61 -0
  51. package/lib/mongodb/queries/find-page.js +565 -0
  52. package/lib/mongodb/queries/find.js +161 -0
  53. package/lib/mongodb/queries/index.js +49 -0
  54. package/lib/mongodb/writes/delete-many.js +181 -0
  55. package/lib/mongodb/writes/delete-one.js +173 -0
  56. package/lib/mongodb/writes/find-one-and-delete.js +193 -0
  57. package/lib/mongodb/writes/find-one-and-replace.js +222 -0
  58. package/lib/mongodb/writes/find-one-and-update.js +223 -0
  59. package/lib/mongodb/writes/increment-one.js +243 -0
  60. package/lib/mongodb/writes/index.js +41 -0
  61. package/lib/mongodb/writes/insert-batch.js +498 -0
  62. package/lib/mongodb/writes/insert-many.js +218 -0
  63. package/lib/mongodb/writes/insert-one.js +171 -0
  64. package/lib/mongodb/writes/replace-one.js +199 -0
  65. package/lib/mongodb/writes/result-handler.js +236 -0
  66. package/lib/mongodb/writes/update-many.js +205 -0
  67. package/lib/mongodb/writes/update-one.js +207 -0
  68. package/lib/mongodb/writes/upsert-one.js +190 -0
  69. package/lib/multi-level-cache.js +189 -0
  70. package/lib/operators.js +330 -0
  71. package/lib/redis-cache-adapter.js +237 -0
  72. package/lib/transaction/CacheLockManager.js +161 -0
  73. package/lib/transaction/DistributedCacheLockManager.js +239 -0
  74. package/lib/transaction/Transaction.js +314 -0
  75. package/lib/transaction/TransactionManager.js +266 -0
  76. package/lib/transaction/index.js +10 -0
  77. package/package.json +111 -0
@@ -0,0 +1,161 @@
1
+ /**
2
+ * 缓存锁管理器
3
+ * 用于在事务执行期间锁定缓存键,防止脏数据写入缓存
4
+ */
5
+
6
+ class CacheLockManager {
7
+ constructor(options = {}) {
8
+ this.locks = new Map(); // key -> { sessionId, expiresAt }
9
+ this.maxDuration = options.maxDuration || 300000; // 5分钟默认
10
+ this.lockCleanupInterval = options.lockCleanupInterval || 10000; // 10秒清理一次
11
+ this.cleanupTimer = null;
12
+
13
+ // 启动自动清理
14
+ this._startCleanup();
15
+ }
16
+
17
+ /**
18
+ * 添加缓存锁
19
+ * @param {string} key - 缓存键(支持通配符 *)
20
+ * @param {Object} session - MongoDB session 对象
21
+ */
22
+ addLock(key, session) {
23
+ if (!session || !session.id) {
24
+ return;
25
+ }
26
+
27
+ const sessionId = session.id.toString();
28
+ const expiresAt = Date.now() + this.maxDuration;
29
+
30
+ this.locks.set(key, {
31
+ sessionId,
32
+ expiresAt,
33
+ lockedAt: Date.now()
34
+ });
35
+ }
36
+
37
+ /**
38
+ * 检查缓存键是否被锁定
39
+ * @param {string} key - 缓存键
40
+ * @returns {boolean}
41
+ */
42
+ isLocked(key) {
43
+ // 精确匹配
44
+ if (this.locks.has(key)) {
45
+ const lock = this.locks.get(key);
46
+ if (Date.now() < lock.expiresAt) {
47
+ return true;
48
+ }
49
+ // 过期自动删除
50
+ this.locks.delete(key);
51
+ }
52
+
53
+ // 通配符匹配
54
+ for (const [lockKey, lock] of this.locks.entries()) {
55
+ if (lockKey.includes('*')) {
56
+ const pattern = lockKey.replace(/\*/g, '.*');
57
+ const regex = new RegExp(`^${pattern}$`);
58
+ if (regex.test(key)) {
59
+ if (Date.now() < lock.expiresAt) {
60
+ return true;
61
+ }
62
+ // 过期自动删除
63
+ this.locks.delete(lockKey);
64
+ }
65
+ }
66
+ }
67
+
68
+ return false;
69
+ }
70
+
71
+ /**
72
+ * 释放指定 session 的所有锁
73
+ * @param {Object} session - MongoDB session 对象
74
+ */
75
+ releaseLocks(session) {
76
+ if (!session || !session.id) {
77
+ return;
78
+ }
79
+
80
+ const sessionId = session.id.toString();
81
+ const keysToDelete = [];
82
+
83
+ for (const [key, lock] of this.locks.entries()) {
84
+ if (lock.sessionId === sessionId) {
85
+ keysToDelete.push(key);
86
+ }
87
+ }
88
+
89
+ keysToDelete.forEach(key => this.locks.delete(key));
90
+ }
91
+
92
+ /**
93
+ * 清理过期的锁
94
+ * @private
95
+ */
96
+ _cleanupExpiredLocks() {
97
+ const now = Date.now();
98
+ const keysToDelete = [];
99
+
100
+ for (const [key, lock] of this.locks.entries()) {
101
+ if (now >= lock.expiresAt) {
102
+ keysToDelete.push(key);
103
+ }
104
+ }
105
+
106
+ if (keysToDelete.length > 0) {
107
+ keysToDelete.forEach(key => this.locks.delete(key));
108
+ }
109
+ }
110
+
111
+ /**
112
+ * 启动自动清理定时器
113
+ * @private
114
+ */
115
+ _startCleanup() {
116
+ if (this.cleanupTimer) {
117
+ return;
118
+ }
119
+
120
+ this.cleanupTimer = setInterval(() => {
121
+ this._cleanupExpiredLocks();
122
+ }, this.lockCleanupInterval);
123
+
124
+ // 防止定时器阻止进程退出
125
+ if (this.cleanupTimer.unref) {
126
+ this.cleanupTimer.unref();
127
+ }
128
+ }
129
+
130
+ /**
131
+ * 停止自动清理
132
+ */
133
+ stop() {
134
+ if (this.cleanupTimer) {
135
+ clearInterval(this.cleanupTimer);
136
+ this.cleanupTimer = null;
137
+ }
138
+ }
139
+
140
+ /**
141
+ * 获取当前锁的统计信息
142
+ */
143
+ getStats() {
144
+ return {
145
+ totalLocks: this.locks.size,
146
+ activeLocks: Array.from(this.locks.values()).filter(
147
+ lock => Date.now() < lock.expiresAt
148
+ ).length
149
+ };
150
+ }
151
+
152
+ /**
153
+ * 清除所有锁(用于测试)
154
+ */
155
+ clear() {
156
+ this.locks.clear();
157
+ }
158
+ }
159
+
160
+ module.exports = CacheLockManager;
161
+
@@ -0,0 +1,239 @@
1
+ /**
2
+ * 分布式缓存锁管理器
3
+ * 基于 Redis 实现跨实例的事务缓存锁,确保事务隔离性
4
+ *
5
+ * @example
6
+ * const lockManager = new DistributedCacheLockManager({
7
+ * redis: redisInstance,
8
+ * lockKeyPrefix: 'monsqlize:cache:lock:'
9
+ * });
10
+ *
11
+ * await lockManager.addLock('user:1', session);
12
+ * const isLocked = await lockManager.isLocked('user:1');
13
+ * await lockManager.releaseLocks(session);
14
+ */
15
+
16
+ class DistributedCacheLockManager {
17
+ /**
18
+ * @param {Object} options
19
+ * @param {Object} options.redis - ioredis 实例
20
+ * @param {string} [options.lockKeyPrefix='monsqlize:cache:lock:'] - 锁键前缀
21
+ * @param {number} [options.maxDuration=300000] - 锁最大持续时间(毫秒)
22
+ * @param {Object} [options.logger] - 日志记录器
23
+ */
24
+ constructor(options = {}) {
25
+ if (!options.redis) {
26
+ throw new Error('DistributedCacheLockManager requires a Redis instance');
27
+ }
28
+
29
+ this.redis = options.redis;
30
+ this.lockKeyPrefix = options.lockKeyPrefix || 'monsqlize:cache:lock:';
31
+ this.maxDuration = options.maxDuration || 300000; // 5 分钟默认
32
+ this.logger = options.logger;
33
+
34
+ // 统计信息
35
+ this.stats = {
36
+ locksAcquired: 0,
37
+ locksReleased: 0,
38
+ lockChecks: 0,
39
+ errors: 0
40
+ };
41
+
42
+ // 错误处理
43
+ this.redis.on('error', (err) => {
44
+ this.stats.errors++;
45
+ if (this.logger) {
46
+ this.logger.error('[DistributedCacheLockManager] Redis error:', err.message);
47
+ }
48
+ });
49
+ }
50
+
51
+ /**
52
+ * 添加分布式缓存锁
53
+ * @param {string} key - 缓存键(支持通配符 *)
54
+ * @param {Object} session - MongoDB session 对象
55
+ * @returns {Promise<boolean>} 是否成功获取锁
56
+ */
57
+ async addLock(key, session) {
58
+ if (!session || !session.id) {
59
+ if (this.logger) {
60
+ this.logger.warn('[DistributedCacheLockManager] Invalid session, skip lock');
61
+ }
62
+ return false;
63
+ }
64
+
65
+ const lockKey = this.lockKeyPrefix + key;
66
+ const sessionId = session.id.toString();
67
+ const ttlSeconds = Math.ceil(this.maxDuration / 1000);
68
+
69
+ try {
70
+ // 使用 SET NX EX 原子操作获取锁
71
+ const result = await this.redis.set(lockKey, sessionId, 'EX', ttlSeconds, 'NX');
72
+
73
+ if (result === 'OK') {
74
+ this.stats.locksAcquired++;
75
+ if (this.logger) {
76
+ this.logger.debug(`[DistributedCacheLockManager] Lock acquired: ${key}`);
77
+ }
78
+ return true;
79
+ }
80
+
81
+ return false;
82
+ } catch (error) {
83
+ this.stats.errors++;
84
+ if (this.logger) {
85
+ this.logger.error('[DistributedCacheLockManager] Add lock error:', error.message);
86
+ }
87
+ return false;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * 检查缓存键是否被锁定
93
+ * @param {string} key - 缓存键
94
+ * @returns {Promise<boolean>}
95
+ */
96
+ async isLocked(key) {
97
+ this.stats.lockChecks++;
98
+
99
+ try {
100
+ // 1. 检查精确匹配
101
+ const lockKey = this.lockKeyPrefix + key;
102
+ const exists = await this.redis.exists(lockKey);
103
+ if (exists) {
104
+ return true;
105
+ }
106
+
107
+ // 2. 检查通配符匹配
108
+ // 注意:KEYS 命令在大数据量下性能较差,这里使用 SCAN 会更好
109
+ // 但为了简单起见,暂时使用 KEYS,生产环境建议优化
110
+ const pattern = this.lockKeyPrefix + '*';
111
+ const keys = await this.redis.keys(pattern);
112
+
113
+ for (const foundKey of keys) {
114
+ const lockPattern = foundKey.replace(this.lockKeyPrefix, '');
115
+
116
+ // 检查是否是通配符模式
117
+ if (lockPattern.includes('*')) {
118
+ const regex = this._patternToRegex(lockPattern);
119
+ if (regex.test(key)) {
120
+ return true;
121
+ }
122
+ }
123
+ }
124
+
125
+ return false;
126
+ } catch (error) {
127
+ this.stats.errors++;
128
+ if (this.logger) {
129
+ this.logger.error('[DistributedCacheLockManager] Is locked check error:', error.message);
130
+ }
131
+ // 发生错误时保守处理:假设没有锁(允许操作继续)
132
+ return false;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * 释放指定 session 的所有锁
138
+ * @param {Object} session - MongoDB session 对象
139
+ * @returns {Promise<number>} 释放的锁数量
140
+ */
141
+ async releaseLocks(session) {
142
+ if (!session || !session.id) {
143
+ return 0;
144
+ }
145
+
146
+ const sessionId = session.id.toString();
147
+ const pattern = this.lockKeyPrefix + '*';
148
+
149
+ try {
150
+ const keys = await this.redis.keys(pattern);
151
+
152
+ if (keys.length === 0) {
153
+ return 0;
154
+ }
155
+
156
+ // 使用 Lua 脚本批量删除(原子操作)
157
+ // 只删除属于当前 session 的锁
158
+ const luaScript = `
159
+ local deletedCount = 0
160
+ for i, key in ipairs(KEYS) do
161
+ local value = redis.call('GET', key)
162
+ if value == ARGV[1] then
163
+ redis.call('DEL', key)
164
+ deletedCount = deletedCount + 1
165
+ end
166
+ end
167
+ return deletedCount
168
+ `;
169
+
170
+ const deleted = await this.redis.eval(
171
+ luaScript,
172
+ keys.length,
173
+ ...keys,
174
+ sessionId
175
+ );
176
+
177
+ this.stats.locksReleased += deleted;
178
+
179
+ if (this.logger && deleted > 0) {
180
+ this.logger.debug(`[DistributedCacheLockManager] Released ${deleted} locks for session ${sessionId}`);
181
+ }
182
+
183
+ return deleted;
184
+ } catch (error) {
185
+ this.stats.errors++;
186
+ if (this.logger) {
187
+ this.logger.error('[DistributedCacheLockManager] Release locks error:', error.message);
188
+ }
189
+ return 0;
190
+ }
191
+ }
192
+
193
+ /**
194
+ * 清理所有过期锁(Redis TTL 会自动清理,此方法保留用于手动清理)
195
+ * @returns {Promise<void>}
196
+ */
197
+ async cleanup() {
198
+ // Redis TTL 会自动清理过期的键
199
+ // 这里可以添加额外的清理逻辑,比如强制清理超时的锁
200
+ if (this.logger) {
201
+ this.logger.debug('[DistributedCacheLockManager] Cleanup called (Redis handles TTL automatically)');
202
+ }
203
+ }
204
+
205
+ /**
206
+ * 获取统计信息
207
+ * @returns {Object}
208
+ */
209
+ getStats() {
210
+ return {
211
+ ...this.stats,
212
+ lockKeyPrefix: this.lockKeyPrefix,
213
+ maxDuration: this.maxDuration
214
+ };
215
+ }
216
+
217
+ /**
218
+ * 将通配符模式转换为正则表达式
219
+ * @private
220
+ */
221
+ _patternToRegex(pattern) {
222
+ const escaped = pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
223
+ const wildcarded = escaped.replace(/\\\*/g, '.*');
224
+ return new RegExp(`^${wildcarded}$`);
225
+ }
226
+
227
+ /**
228
+ * 停止(清理资源)
229
+ * 注意:不关闭 Redis 连接,因为连接是外部传入的
230
+ */
231
+ stop() {
232
+ if (this.logger) {
233
+ this.logger.info('[DistributedCacheLockManager] Stopped');
234
+ }
235
+ }
236
+ }
237
+
238
+ module.exports = DistributedCacheLockManager;
239
+
@@ -0,0 +1,314 @@
1
+ /**
2
+ * Transaction 类
3
+ * 表示一个 MongoDB 事务
4
+ */
5
+
6
+ class Transaction {
7
+ constructor(session, options = {}) {
8
+ this.session = session;
9
+ this.id = `tx_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
10
+ this.state = 'pending';
11
+ this.cache = options.cache;
12
+ this.logger = options.logger;
13
+ this.timeout = options.timeout || 30000;
14
+ this.startTime = null;
15
+ this.timeoutTimer = null;
16
+
17
+ // 记录待失效的缓存(事务提交后才失效)
18
+ this.pendingInvalidations = new Set();
19
+
20
+ // 缓存锁管理器
21
+ this.lockManager = options.lockManager;
22
+ this.lockedKeys = new Set();
23
+
24
+ // ✨ 只读优化:追踪事务是否有写操作
25
+ this.hasWriteOperation = false;
26
+ this.operationCount = { read: 0, write: 0 };
27
+
28
+ // 关键:将 Transaction 实例存储到 session 的自定义属性
29
+ // 这样写操作可以通过 session.__monSQLizeTransaction 访问到 Transaction 实例
30
+ if (session) {
31
+ session.__monSQLizeTransaction = this;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * 开始事务
37
+ */
38
+ async start() {
39
+ if (this.state !== 'pending') {
40
+ throw new Error(`Cannot start transaction in state: ${this.state}`);
41
+ }
42
+
43
+ this.session.startTransaction();
44
+ this.state = 'active';
45
+ this.startTime = Date.now();
46
+
47
+ // 设置超时自动中止
48
+ if (this.timeout > 0) {
49
+ this.timeoutTimer = setTimeout(() => {
50
+ if (this.state === 'active') {
51
+ this.logger?.warn(`[Transaction] Timeout after ${this.timeout}ms, auto-aborting transaction ${this.id}`);
52
+ this.abort().catch(() => {});
53
+ }
54
+ }, this.timeout);
55
+ }
56
+
57
+ this.logger?.debug(`[Transaction] Started transaction ${this.id}`);
58
+ }
59
+
60
+ /**
61
+ * 提交事务
62
+ * 注意:缓存已在 recordInvalidation() 中失效,这里只释放锁
63
+ */
64
+ async commit() {
65
+ if (this.state !== 'active') {
66
+ throw new Error(`Cannot commit transaction in ${this.state} state`);
67
+ }
68
+
69
+ try {
70
+ // 1. 提交事务
71
+ await this.session.commitTransaction();
72
+ this.state = 'committed';
73
+
74
+ // 2. 释放缓存锁(允许重新缓存)
75
+ // 注意:缓存已在写操作时失效,这里不再失效
76
+ this._releaseLocks();
77
+
78
+ this.logger?.debug(`[Transaction] Committed transaction ${this.id}`);
79
+ } finally {
80
+ this._clearTimeout();
81
+ this.pendingInvalidations.clear();
82
+ }
83
+ }
84
+
85
+ /**
86
+ * 回滚事务
87
+ * 注意:
88
+ * - 缓存已在写操作时失效
89
+ * - 但数据实际未改变(事务回滚)
90
+ * - 释放锁后,下次查询会从数据库读取并重新缓存(正确的旧值)
91
+ */
92
+ async abort() {
93
+ if (this.state !== 'active' && this.state !== 'pending') {
94
+ return; // 已经结束或中止
95
+ }
96
+
97
+ try {
98
+ await this.session.abortTransaction();
99
+ this.state = 'aborted';
100
+ this.logger?.debug(`[Transaction] Aborted transaction ${this.id}`);
101
+ } finally {
102
+ this._clearTimeout();
103
+ // 释放缓存锁(允许重新缓存)
104
+ // 注意:缓存已在写时失效,不在这里失效
105
+ this._releaseLocks();
106
+ this.pendingInvalidations.clear();
107
+ }
108
+ }
109
+
110
+ /**
111
+ * 结束会话
112
+ */
113
+ async end() {
114
+ await this.session.endSession();
115
+ this._clearTimeout();
116
+ this._releaseLocks();
117
+ this.logger?.debug(`[Transaction] Ended session for transaction ${this.id}`);
118
+ }
119
+
120
+ /**
121
+ * 记录待失效的缓存
122
+ * 写操作应该调用此方法,立即失效缓存并添加锁
123
+ * @param {string} cachePattern - 缓存键模式(支持通配符)
124
+ * @param {Object} metadata - 操作元数据
125
+ * @param {string} metadata.operation - 操作类型:'read' | 'write'
126
+ * @param {Object} metadata.query - 查询条件(用于文档级别锁)
127
+ * @param {string} metadata.collection - 集合名称
128
+ * @param {boolean} metadata.useDocumentLock - 是否启用文档级别锁(默认:true)
129
+ */
130
+ async recordInvalidation(cachePattern, metadata = {}) {
131
+ if (this.state === 'active') {
132
+ const {
133
+ operation = 'write',
134
+ query = {},
135
+ collection = '',
136
+ useDocumentLock = true
137
+ } = metadata;
138
+
139
+ // ✨ 追踪操作类型
140
+ if (operation === 'read') {
141
+ this.operationCount.read++;
142
+ } else {
143
+ this.operationCount.write++;
144
+ this.hasWriteOperation = true;
145
+ }
146
+
147
+ // ✨ 只读优化:只读操作不失效缓存
148
+ if (operation === 'read') {
149
+ // 只添加缓存锁,不失效缓存
150
+ if (this.lockManager) {
151
+ this.lockManager.addLock(cachePattern, this.session);
152
+ this.lockedKeys.add(cachePattern);
153
+ this.logger?.debug(`[Transaction] Added cache lock (read-only): ${cachePattern}`);
154
+ }
155
+ this.pendingInvalidations.add(cachePattern);
156
+ return;
157
+ }
158
+
159
+ // 🚀 文档级别锁:尝试提取文档键
160
+ let lockPatterns = [cachePattern];
161
+ let usedDocumentLock = false;
162
+
163
+ if (useDocumentLock && collection && query) {
164
+ const docKeys = this._extractDocumentKeys(query);
165
+
166
+ // 如果成功提取文档键,且数量合理(<100个)
167
+ if (docKeys.length > 0 && docKeys.length < 100) {
168
+ lockPatterns = docKeys.map(key =>
169
+ this._buildDocumentLockPattern(collection, key)
170
+ );
171
+ usedDocumentLock = true;
172
+ this.logger?.debug(`[Transaction] Using document-level locks for ${docKeys.length} documents`);
173
+ } else if (docKeys.length >= 100) {
174
+ // 文档太多,回退到集合级别
175
+ lockPatterns = [this._buildCollectionLockPattern(collection)];
176
+ this.logger?.debug(`[Transaction] Too many documents (${docKeys.length}), falling back to collection-level lock`);
177
+ } else {
178
+ // 无法提取文档键,使用传入的模式(通常是集合级别)
179
+ this.logger?.debug(`[Transaction] Cannot extract document keys, using pattern: ${cachePattern}`);
180
+ }
181
+ }
182
+
183
+ // 步骤 1: 立即失效缓存(写时无效化)
184
+ if (this.cache) {
185
+ try {
186
+ let totalDeleted = 0;
187
+ for (const pattern of lockPatterns) {
188
+ const deleted = await this.cache.delPattern(pattern);
189
+ totalDeleted += deleted;
190
+ }
191
+ this.logger?.debug(`[Transaction] Immediately invalidated ${totalDeleted} cache keys (${usedDocumentLock ? 'document-level' : 'collection-level'})`);
192
+ } catch (err) {
193
+ this.logger?.warn(`[Transaction] Failed to invalidate cache: ${err.message}`);
194
+ }
195
+ }
196
+
197
+ // 步骤 2: 添加缓存锁
198
+ if (this.lockManager) {
199
+ for (const pattern of lockPatterns) {
200
+ this.lockManager.addLock(pattern, this.session);
201
+ this.lockedKeys.add(pattern);
202
+ }
203
+ this.logger?.debug(`[Transaction] Added ${lockPatterns.length} cache lock(s)`);
204
+ }
205
+
206
+ // 步骤 3: 记录到待处理列表
207
+ lockPatterns.forEach(p => this.pendingInvalidations.add(p));
208
+ }
209
+ }
210
+
211
+ /**
212
+ * 释放所有缓存锁
213
+ * @private
214
+ */
215
+ _releaseLocks() {
216
+ if (this.lockManager && this.session) {
217
+ this.lockManager.releaseLocks(this.session);
218
+ this.lockedKeys.clear();
219
+ this.logger?.debug(`[Transaction] Released all cache locks`);
220
+ }
221
+ }
222
+
223
+ /**
224
+ * 清除超时定时器
225
+ * @private
226
+ */
227
+ _clearTimeout() {
228
+ if (this.timeoutTimer) {
229
+ clearTimeout(this.timeoutTimer);
230
+ this.timeoutTimer = null;
231
+ }
232
+ }
233
+
234
+ /**
235
+ * 获取事务持续时间
236
+ */
237
+ getDuration() {
238
+ if (!this.startTime) return 0;
239
+ return Date.now() - this.startTime;
240
+ }
241
+
242
+ /**
243
+ * 🚀 文档级别锁:提取查询中的文档键
244
+ * @param {Object} query - MongoDB 查询条件
245
+ * @returns {Array} 文档键数组
246
+ * @private
247
+ */
248
+ _extractDocumentKeys(query) {
249
+ if (!query || typeof query !== 'object') {
250
+ return [];
251
+ }
252
+
253
+ const keys = [];
254
+
255
+ // 1. 简单的 _id 查询
256
+ if (query._id !== undefined && query._id !== null) {
257
+ if (Array.isArray(query._id)) {
258
+ // { _id: [1, 2, 3] }
259
+ keys.push(...query._id.map(id => String(id)));
260
+ } else if (query._id.$in && Array.isArray(query._id.$in)) {
261
+ // { _id: { $in: [1, 2, 3] } }
262
+ keys.push(...query._id.$in.map(id => String(id)));
263
+ } else if (typeof query._id === 'object' && query._id.constructor.name === 'ObjectId') {
264
+ // { _id: ObjectId("...") }
265
+ keys.push(String(query._id));
266
+ } else if (typeof query._id !== 'object' || query._id === null) {
267
+ // { _id: 1 } 或 { _id: "xxx" }
268
+ keys.push(String(query._id));
269
+ }
270
+ }
271
+
272
+ return keys;
273
+ }
274
+
275
+ /**
276
+ * 🚀 文档级别锁:构建文档级别的缓存模式
277
+ * @param {string} collection - 集合名称
278
+ * @param {string} docKey - 文档键
279
+ * @returns {string} 文档级别缓存模式
280
+ * @private
281
+ */
282
+ _buildDocumentLockPattern(collection, docKey) {
283
+ // 格式: *"collection":"collectionName"*"base":{"_id":"docKey"}*
284
+ return `*"collection":"${collection}"*"base":{"_id":"${docKey}"}*`;
285
+ }
286
+
287
+ /**
288
+ * 🚀 文档级别锁:构建集合级别的缓存模式(回退)
289
+ * @param {string} collection - 集合名称
290
+ * @returns {string} 集合级别缓存模式
291
+ * @private
292
+ */
293
+ _buildCollectionLockPattern(collection) {
294
+ // 格式: *"collection":"collectionName"*
295
+ return `*"collection":"${collection}"*`;
296
+ }
297
+
298
+ /**
299
+ * 🚀 获取事务统计信息
300
+ * @returns {Object} 统计信息
301
+ */
302
+ getStats() {
303
+ return {
304
+ id: this.id,
305
+ state: this.state,
306
+ duration: this.getDuration(),
307
+ hasWriteOperation: this.hasWriteOperation,
308
+ operationCount: { ...this.operationCount },
309
+ lockedKeysCount: this.lockedKeys.size
310
+ };
311
+ }
312
+ }
313
+
314
+ module.exports = Transaction;