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.
- package/CHANGELOG.md +56 -60
- package/LICENSE +201 -21
- package/README.md +537 -1828
- package/changelogs/README.md +160 -0
- package/changelogs/v2.0.0.md +222 -0
- package/dist/cjs/index.cjs +10600 -0
- package/dist/cjs/mongodb/common/transaction-aware.cjs +10 -0
- package/dist/cjs/transaction/CacheLockManager.cjs +100 -0
- package/dist/cjs/transaction/Transaction.cjs +158 -0
- package/dist/cjs/transaction/TransactionManager.cjs +298 -0
- package/dist/esm/index.mjs +10650 -0
- package/dist/types/base.d.ts +81 -0
- package/dist/types/collection.d.ts +1031 -0
- package/dist/types/expression.d.ts +115 -0
- package/dist/types/index.d.ts +23 -0
- package/dist/types/lock.d.ts +74 -0
- package/dist/types/model.d.ts +526 -0
- package/dist/types/mongodb.d.ts +49 -0
- package/dist/types/monsqlize.d.ts +491 -0
- package/dist/types/pool.d.ts +84 -0
- package/dist/types/runtime.d.ts +362 -0
- package/dist/types/saga.d.ts +143 -0
- package/dist/types/slow-query-log.d.ts +126 -0
- package/dist/types/sync.d.ts +103 -0
- package/dist/types/transaction.d.ts +132 -0
- package/package.json +67 -69
- package/index.d.ts +0 -206
- package/index.mjs +0 -52
- package/lib/cache-invalidation.js +0 -279
- package/lib/cache.js +0 -530
- package/lib/common/cursor.js +0 -59
- package/lib/common/docs-urls.js +0 -73
- package/lib/common/index-options.js +0 -223
- package/lib/common/log.js +0 -61
- package/lib/common/namespace.js +0 -22
- package/lib/common/normalize.js +0 -34
- package/lib/common/page-result.js +0 -43
- package/lib/common/runner.js +0 -57
- package/lib/common/server-features.js +0 -232
- package/lib/common/shape-builders.js +0 -27
- package/lib/common/validation.js +0 -113
- package/lib/connect.js +0 -99
- package/lib/constants.js +0 -55
- package/lib/count-queue.js +0 -188
- package/lib/distributed-cache-invalidator.js +0 -260
- package/lib/errors.js +0 -168
- package/lib/expression/cache/ExpressionCache.js +0 -114
- package/lib/expression/compiler/ExpressionCompiler.js +0 -1090
- package/lib/expression/compiler/ExpressionCompilerExtensions.js +0 -531
- package/lib/expression/detector.js +0 -84
- package/lib/expression/factory.js +0 -29
- package/lib/expression/index.js +0 -19
- package/lib/function-cache.js +0 -533
- package/lib/index.js +0 -1251
- package/lib/infrastructure/ConnectionPoolManager.js +0 -464
- package/lib/infrastructure/HealthChecker.js +0 -281
- package/lib/infrastructure/PoolConfig.js +0 -199
- package/lib/infrastructure/PoolSelector.js +0 -225
- package/lib/infrastructure/PoolStats.js +0 -244
- package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -212
- package/lib/infrastructure/ssh-tunnel.js +0 -41
- package/lib/infrastructure/uri-parser.js +0 -36
- package/lib/lock/Lock.js +0 -67
- package/lib/lock/errors.js +0 -28
- package/lib/lock/index.js +0 -13
- package/lib/logger.js +0 -225
- package/lib/model/examples/test.js +0 -311
- package/lib/model/features/defaults.js +0 -161
- package/lib/model/features/populate.js +0 -568
- package/lib/model/features/relations.js +0 -120
- package/lib/model/features/soft-delete.js +0 -349
- package/lib/model/features/version.js +0 -157
- package/lib/model/features/virtuals.js +0 -219
- package/lib/model/index.js +0 -1265
- package/lib/mongodb/common/accessor-helpers.js +0 -59
- package/lib/mongodb/common/agg-pipeline.js +0 -36
- package/lib/mongodb/common/aggregation-validator.js +0 -127
- package/lib/mongodb/common/iid.js +0 -28
- package/lib/mongodb/common/lexicographic-expr.js +0 -53
- package/lib/mongodb/common/shape.js +0 -32
- package/lib/mongodb/common/sort.js +0 -39
- package/lib/mongodb/common/transaction-aware.js +0 -25
- package/lib/mongodb/connect.js +0 -234
- package/lib/mongodb/index.js +0 -639
- package/lib/mongodb/management/admin-ops.js +0 -200
- package/lib/mongodb/management/bookmark-ops.js +0 -167
- package/lib/mongodb/management/cache-ops.js +0 -50
- package/lib/mongodb/management/collection-ops.js +0 -387
- package/lib/mongodb/management/database-ops.js +0 -202
- package/lib/mongodb/management/index-ops.js +0 -475
- package/lib/mongodb/management/index.js +0 -17
- package/lib/mongodb/management/namespace.js +0 -31
- package/lib/mongodb/management/validation-ops.js +0 -268
- package/lib/mongodb/queries/aggregate.js +0 -172
- package/lib/mongodb/queries/chain.js +0 -631
- package/lib/mongodb/queries/count.js +0 -99
- package/lib/mongodb/queries/distinct.js +0 -78
- package/lib/mongodb/queries/find-and-count.js +0 -193
- package/lib/mongodb/queries/find-by-ids.js +0 -236
- package/lib/mongodb/queries/find-one-by-id.js +0 -171
- package/lib/mongodb/queries/find-one.js +0 -71
- package/lib/mongodb/queries/find-page.js +0 -618
- package/lib/mongodb/queries/find.js +0 -171
- package/lib/mongodb/queries/index.js +0 -51
- package/lib/mongodb/queries/watch.js +0 -538
- package/lib/mongodb/writes/common/batch-retry.js +0 -65
- package/lib/mongodb/writes/delete-batch.js +0 -323
- package/lib/mongodb/writes/delete-many.js +0 -181
- package/lib/mongodb/writes/delete-one.js +0 -173
- package/lib/mongodb/writes/find-one-and-delete.js +0 -203
- package/lib/mongodb/writes/find-one-and-replace.js +0 -239
- package/lib/mongodb/writes/find-one-and-update.js +0 -240
- package/lib/mongodb/writes/increment-one.js +0 -259
- package/lib/mongodb/writes/index.js +0 -46
- package/lib/mongodb/writes/insert-batch.js +0 -508
- package/lib/mongodb/writes/insert-many.js +0 -223
- package/lib/mongodb/writes/insert-one.js +0 -169
- package/lib/mongodb/writes/replace-one.js +0 -226
- package/lib/mongodb/writes/result-handler.js +0 -237
- package/lib/mongodb/writes/update-batch.js +0 -416
- package/lib/mongodb/writes/update-many.js +0 -275
- package/lib/mongodb/writes/update-one.js +0 -273
- package/lib/mongodb/writes/upsert-one.js +0 -203
- package/lib/multi-level-cache.js +0 -244
- package/lib/operators.js +0 -330
- package/lib/redis-cache-adapter.js +0 -267
- package/lib/saga/SagaContext.js +0 -67
- package/lib/saga/SagaDefinition.js +0 -32
- package/lib/saga/SagaExecutor.js +0 -201
- package/lib/saga/SagaOrchestrator.js +0 -186
- package/lib/saga/index.js +0 -11
- package/lib/slow-query-log/base-storage.js +0 -70
- package/lib/slow-query-log/batch-queue.js +0 -97
- package/lib/slow-query-log/config-manager.js +0 -196
- package/lib/slow-query-log/index.js +0 -238
- package/lib/slow-query-log/mongodb-storage.js +0 -324
- package/lib/slow-query-log/query-hash.js +0 -39
- package/lib/sync/ChangeStreamSyncManager.js +0 -405
- package/lib/sync/ResumeTokenStore.js +0 -192
- package/lib/sync/SyncConfig.js +0 -127
- package/lib/sync/SyncTarget.js +0 -240
- package/lib/sync/index.js +0 -20
- package/lib/transaction/CacheLockManager.js +0 -162
- package/lib/transaction/DistributedCacheLockManager.js +0 -475
- package/lib/transaction/Transaction.js +0 -315
- package/lib/transaction/TransactionManager.js +0 -267
- package/lib/transaction/index.js +0 -11
- package/lib/utils/objectid-converter.js +0 -632
- package/types/README.md +0 -122
- package/types/base.ts +0 -94
- package/types/batch.ts +0 -187
- package/types/cache.ts +0 -71
- package/types/chain.ts +0 -254
- package/types/collection.ts +0 -357
- package/types/expression.ts +0 -109
- package/types/function-cache.d.ts +0 -135
- package/types/lock.ts +0 -95
- package/types/model/definition.ts +0 -152
- package/types/model/index.ts +0 -10
- package/types/model/instance.ts +0 -121
- package/types/model/relations.ts +0 -121
- package/types/model/virtuals.ts +0 -32
- package/types/monsqlize.ts +0 -245
- package/types/options.ts +0 -192
- package/types/pagination.ts +0 -154
- package/types/pool.ts +0 -125
- package/types/query.ts +0 -71
- package/types/saga.ts +0 -125
- package/types/stream.ts +0 -64
- package/types/sync.ts +0 -79
- package/types/transaction.ts +0 -79
- package/types/write.ts +0 -77
|
@@ -1,315 +0,0 @@
|
|
|
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;
|
|
315
|
-
|
|
@@ -1,267 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 事务管理器
|
|
3
|
-
* 负责管理 MongoDB 事务的生命周期
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
const Transaction = require('./Transaction');
|
|
7
|
-
const CacheLockManager = require('./CacheLockManager');
|
|
8
|
-
|
|
9
|
-
class TransactionManager {
|
|
10
|
-
constructor(adapter, cache, logger, options = {}) {
|
|
11
|
-
this.adapter = adapter;
|
|
12
|
-
this.cache = cache;
|
|
13
|
-
this.logger = logger;
|
|
14
|
-
this.options = {
|
|
15
|
-
maxRetries: options.maxRetries || 3,
|
|
16
|
-
retryDelay: options.retryDelay || 100,
|
|
17
|
-
retryBackoff: options.retryBackoff || 2,
|
|
18
|
-
defaultTimeout: options.defaultTimeout || 30000,
|
|
19
|
-
enableRetry: options.enableRetry !== false,
|
|
20
|
-
...options
|
|
21
|
-
};
|
|
22
|
-
this.activeTransactions = new Map();
|
|
23
|
-
|
|
24
|
-
// ✨ 统计信息
|
|
25
|
-
this.stats = {
|
|
26
|
-
totalTransactions: 0,
|
|
27
|
-
successfulTransactions: 0,
|
|
28
|
-
failedTransactions: 0,
|
|
29
|
-
readOnlyTransactions: 0,
|
|
30
|
-
writeTransactions: 0,
|
|
31
|
-
durations: []
|
|
32
|
-
};
|
|
33
|
-
this.maxStatsSamples = options.maxStatsSamples || 1000;
|
|
34
|
-
|
|
35
|
-
// 使用传入的 lockManager 或创建新的
|
|
36
|
-
if (options.lockManager) {
|
|
37
|
-
this.lockManager = options.lockManager;
|
|
38
|
-
} else {
|
|
39
|
-
// 初始化缓存锁管理器
|
|
40
|
-
this.lockManager = new CacheLockManager({
|
|
41
|
-
logger: this.logger,
|
|
42
|
-
maxDuration: options.lockMaxDuration || 300000,
|
|
43
|
-
cleanupInterval: options.lockCleanupInterval || 10000
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
// 将锁管理器设置到缓存实例
|
|
47
|
-
if (cache && typeof cache.setLockManager === 'function') {
|
|
48
|
-
cache.setLockManager(this.lockManager);
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* 创建一个新的事务会话
|
|
55
|
-
* @param {Object} options - 会话选项
|
|
56
|
-
* @returns {Promise<Transaction>}
|
|
57
|
-
*/
|
|
58
|
-
async startSession(options = {}) {
|
|
59
|
-
const session = this.adapter.client.startSession({
|
|
60
|
-
causalConsistency: options.causalConsistency !== false,
|
|
61
|
-
defaultTransactionOptions: {
|
|
62
|
-
readConcern: options.readConcern,
|
|
63
|
-
writeConcern: options.writeConcern,
|
|
64
|
-
readPreference: options.readPreference
|
|
65
|
-
}
|
|
66
|
-
});
|
|
67
|
-
|
|
68
|
-
const transaction = new Transaction(session, {
|
|
69
|
-
cache: this.cache,
|
|
70
|
-
logger: this.logger,
|
|
71
|
-
lockManager: this.lockManager,
|
|
72
|
-
timeout: options.timeout || this.options.defaultTimeout,
|
|
73
|
-
...options
|
|
74
|
-
});
|
|
75
|
-
|
|
76
|
-
this.activeTransactions.set(transaction.id, transaction);
|
|
77
|
-
|
|
78
|
-
return transaction;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* 自动管理事务(推荐用法)
|
|
83
|
-
* @param {Function} callback - 事务回调函数
|
|
84
|
-
* @param {Object} options - 事务选项
|
|
85
|
-
* @returns {Promise<any>}
|
|
86
|
-
*/
|
|
87
|
-
async withTransaction(callback, options = {}) {
|
|
88
|
-
const maxRetries = options.maxRetries !== undefined
|
|
89
|
-
? options.maxRetries
|
|
90
|
-
: this.options.maxRetries;
|
|
91
|
-
|
|
92
|
-
const enableRetry = options.enableRetry !== undefined
|
|
93
|
-
? options.enableRetry
|
|
94
|
-
: this.options.enableRetry;
|
|
95
|
-
|
|
96
|
-
const retryDelay = options.retryDelay || this.options.retryDelay;
|
|
97
|
-
const retryBackoff = options.retryBackoff || this.options.retryBackoff;
|
|
98
|
-
|
|
99
|
-
let attempt = 0;
|
|
100
|
-
let lastError = null;
|
|
101
|
-
|
|
102
|
-
while (attempt <= maxRetries) {
|
|
103
|
-
const transaction = await this.startSession(options);
|
|
104
|
-
const startTime = Date.now();
|
|
105
|
-
|
|
106
|
-
try {
|
|
107
|
-
await transaction.start();
|
|
108
|
-
const result = await callback(transaction);
|
|
109
|
-
await transaction.commit();
|
|
110
|
-
|
|
111
|
-
// ✨ 记录统计信息(成功)
|
|
112
|
-
const duration = Date.now() - startTime;
|
|
113
|
-
this._recordStats(transaction, duration, true);
|
|
114
|
-
|
|
115
|
-
return result;
|
|
116
|
-
} catch (error) {
|
|
117
|
-
lastError = error;
|
|
118
|
-
|
|
119
|
-
// 回滚事务
|
|
120
|
-
try {
|
|
121
|
-
await transaction.abort();
|
|
122
|
-
} catch (abortError) {
|
|
123
|
-
// 忽略回滚错误
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// ✨ 记录统计信息(失败)
|
|
127
|
-
const duration = Date.now() - startTime;
|
|
128
|
-
this._recordStats(transaction, duration, false);
|
|
129
|
-
|
|
130
|
-
// 检查是否需要重试
|
|
131
|
-
if (enableRetry &&
|
|
132
|
-
attempt < maxRetries &&
|
|
133
|
-
this._isTransientError(error)) {
|
|
134
|
-
attempt++;
|
|
135
|
-
|
|
136
|
-
// 计算延迟时间(指数退避)
|
|
137
|
-
const delay = retryDelay * Math.pow(retryBackoff, attempt - 1);
|
|
138
|
-
|
|
139
|
-
this.logger?.info(`[TransactionManager] Retrying transaction (attempt ${attempt}/${maxRetries}) after ${delay}ms due to transient error: ${error.message}`);
|
|
140
|
-
|
|
141
|
-
// 等待后重试
|
|
142
|
-
await new Promise(resolve => setTimeout(resolve, delay));
|
|
143
|
-
|
|
144
|
-
continue;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
// 不重试,抛出错误
|
|
148
|
-
throw error;
|
|
149
|
-
} finally {
|
|
150
|
-
await transaction.end();
|
|
151
|
-
this.activeTransactions.delete(transaction.id);
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
// 达到最大重试次数
|
|
156
|
-
throw new Error(
|
|
157
|
-
`Transaction failed after ${maxRetries} retries: ${lastError.message}`
|
|
158
|
-
);
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/**
|
|
162
|
-
* 判断是否为瞬态错误(可重试)
|
|
163
|
-
* @private
|
|
164
|
-
*/
|
|
165
|
-
_isTransientError(error) {
|
|
166
|
-
if (!error) return false;
|
|
167
|
-
|
|
168
|
-
// MongoDB TransientTransactionError
|
|
169
|
-
if (error.hasErrorLabel && error.hasErrorLabel('TransientTransactionError')) {
|
|
170
|
-
return true;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
// 写冲突错误码
|
|
174
|
-
const transientErrorCodes = [
|
|
175
|
-
112, // WriteConflict
|
|
176
|
-
117, // ConflictingOperationInProgress
|
|
177
|
-
];
|
|
178
|
-
|
|
179
|
-
return transientErrorCodes.includes(error.code);
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* 获取所有活跃的事务
|
|
184
|
-
*/
|
|
185
|
-
getActiveTransactions() {
|
|
186
|
-
return Array.from(this.activeTransactions.values());
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/**
|
|
190
|
-
* 中止所有活跃的事务
|
|
191
|
-
*/
|
|
192
|
-
async abortAll() {
|
|
193
|
-
const transactions = this.getActiveTransactions();
|
|
194
|
-
await Promise.all(transactions.map(tx => tx.abort().catch(() => {})));
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/**
|
|
198
|
-
* ✨ 记录统计信息
|
|
199
|
-
* @param {Transaction} transaction - 事务实例
|
|
200
|
-
* @param {number} duration - 持续时间(毫秒)
|
|
201
|
-
* @param {boolean} success - 是否成功
|
|
202
|
-
* @private
|
|
203
|
-
*/
|
|
204
|
-
_recordStats(transaction, duration, success) {
|
|
205
|
-
this.stats.totalTransactions++;
|
|
206
|
-
|
|
207
|
-
if (success) {
|
|
208
|
-
this.stats.successfulTransactions++;
|
|
209
|
-
} else {
|
|
210
|
-
this.stats.failedTransactions++;
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
// 记录只读/写入事务
|
|
214
|
-
if (transaction.hasWriteOperation) {
|
|
215
|
-
this.stats.writeTransactions++;
|
|
216
|
-
} else {
|
|
217
|
-
this.stats.readOnlyTransactions++;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// 记录持续时间(环形缓冲)
|
|
221
|
-
this.stats.durations.push(duration);
|
|
222
|
-
if (this.stats.durations.length > this.maxStatsSamples) {
|
|
223
|
-
this.stats.durations.shift();
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* ✨ 获取统计信息
|
|
229
|
-
* @returns {Object} 统计信息
|
|
230
|
-
*/
|
|
231
|
-
getStats() {
|
|
232
|
-
const { durations } = this.stats;
|
|
233
|
-
|
|
234
|
-
// 计算统计值
|
|
235
|
-
let avgDuration = 0;
|
|
236
|
-
let p95Duration = 0;
|
|
237
|
-
let p99Duration = 0;
|
|
238
|
-
|
|
239
|
-
if (durations.length > 0) {
|
|
240
|
-
avgDuration = durations.reduce((a, b) => a + b, 0) / durations.length;
|
|
241
|
-
|
|
242
|
-
const sorted = [...durations].sort((a, b) => a - b);
|
|
243
|
-
const p95Index = Math.floor(sorted.length * 0.95);
|
|
244
|
-
const p99Index = Math.floor(sorted.length * 0.99);
|
|
245
|
-
p95Duration = sorted[p95Index] || 0;
|
|
246
|
-
p99Duration = sorted[p99Index] || 0;
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
return {
|
|
250
|
-
...this.stats,
|
|
251
|
-
averageDuration: avgDuration,
|
|
252
|
-
p95Duration,
|
|
253
|
-
p99Duration,
|
|
254
|
-
successRate: this.stats.totalTransactions > 0
|
|
255
|
-
? (this.stats.successfulTransactions / this.stats.totalTransactions * 100).toFixed(2) + '%'
|
|
256
|
-
: '0%',
|
|
257
|
-
readOnlyRatio: this.stats.totalTransactions > 0
|
|
258
|
-
? (this.stats.readOnlyTransactions / this.stats.totalTransactions * 100).toFixed(2) + '%'
|
|
259
|
-
: '0%',
|
|
260
|
-
sampleCount: durations.length
|
|
261
|
-
};
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
module.exports = TransactionManager;
|
|
266
|
-
|
|
267
|
-
|
package/lib/transaction/index.js
DELETED