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,203 +0,0 @@
1
- /**
2
- * findOneAndDelete 操作实现
3
- * 原子地查找并删除单个文档
4
- */
5
-
6
- const { createError, ErrorCodes } = require('../../errors');
7
- const CacheFactory = require('../../cache');
8
- const { handleFindOneAndResult, wasDocumentModified } = require('./result-handler');
9
- const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
10
- const { convertObjectIdStrings } = require('../../utils/objectid-converter');
11
-
12
- /**
13
- * 创建 findOneAndDelete 操作
14
- * @param {Object} context - 模块上下文
15
- * @param {Object} context.db - MongoDB 数据库实例
16
- * @param {Object} context.cache - 缓存实例
17
- * @param {Object} context.logger - 日志实例
18
- * @param {Object} context.defaults - 默认配置
19
- * @param {string} context.collection - 集合名称
20
- * @param {string} context.effectiveDbName - 数据库名称
21
- * @param {string} context.instanceId - 实例ID
22
- * @returns {Object} 包含 findOneAndDelete 方法的对象
23
- */
24
- function createFindOneAndDeleteOps(context) {
25
- const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
26
-
27
- // 提取集合名称和原生 collection 对象
28
- const collectionName = collection.collectionName;
29
- const nativeCollection = collection;
30
-
31
- /**
32
- * 查找并删除单个文档(原子操作)
33
- * @param {Object} filter - 筛选条件(必需)
34
- * @param {Object} [options] - 操作选项
35
- * @param {Object} [options.projection] - 字段投影
36
- * @param {Object} [options.sort] - 排序条件
37
- * @param {number} [options.maxTimeMS] - 最大执行时间
38
- * @param {Object} [options.writeConcern] - 写关注选项
39
- * @param {string} [options.comment] - 操作注释(用于日志追踪)
40
- * @param {Object} [options.collation] - 排序规则
41
- * @param {Object} [options.hint] - 索引提示
42
- * @param {boolean} [options.includeResultMetadata=false] - 是否包含完整结果元数据
43
- * @returns {Promise<Object|null>} 返回被删除的文档或 null(未找到);includeResultMetadata=true 时返回 { value, ok, lastErrorObject }
44
- * @throws {Error} 当参数无效时
45
- *
46
- * @example
47
- * // 删除单个文档并返回
48
- * const deletedDoc = await collection("tasks").findOneAndDelete({
49
- * taskId: "task123"
50
- * });
51
- * if (deletedDoc) {
52
- * console.log("已删除任务:", deletedDoc.taskId);
53
- * }
54
- *
55
- * @example
56
- * // 删除最旧的待处理任务
57
- * const oldestTask = await collection("queue").findOneAndDelete(
58
- * { status: "pending" },
59
- * { sort: { createdAt: 1 } }
60
- * );
61
- *
62
- * @example
63
- * // 使用 projection 仅返回需要的字段
64
- * const deletedUser = await collection("users").findOneAndDelete(
65
- * { userId: "user123" },
66
- * { projection: { userId: 1, name: 1 } }
67
- * );
68
- *
69
- * @example
70
- * // 获取完整元数据
71
- * const result = await collection("sessions").findOneAndDelete(
72
- * { sessionId: "session123" },
73
- * { includeResultMetadata: true }
74
- * );
75
- * console.log("删除成功:", result.ok);
76
- * console.log("已删除的文档:", result.value);
77
- */
78
- const findOneAndDelete = async function findOneAndDelete(filter, options = {}) {
79
- const startTime = Date.now();
80
-
81
- // 1. 参数验证
82
- if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
83
- throw createError(
84
- ErrorCodes.INVALID_ARGUMENT,
85
- 'filter 必须是对象类型',
86
- [{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
87
- );
88
- }
89
-
90
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
91
- const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
92
- logger: context.logger,
93
- excludeFields: context.autoConvertConfig?.excludeFields,
94
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
95
- maxDepth: context.autoConvertConfig?.maxDepth
96
- });
97
-
98
- // 2. 构建操作上下文
99
- const operation = 'findOneAndDelete';
100
- const ns = `${databaseName}.${collectionName}`;
101
-
102
- try {
103
- // 3. 执行查找并删除操作
104
- // MongoDB 驱动 6.x: 默认返回文档,需要 includeResultMetadata=true 获取完整元数据
105
- const driverOptions = { ...options, includeResultMetadata: true };
106
- const result = await nativeCollection.findOneAndDelete(convertedFilter, driverOptions);
107
-
108
- // 4. 自动失效缓存(如果有文档被删除)
109
- // 使用安全的修改判断函数
110
- const documentWasDeleted = wasDocumentModified(result);
111
- if (cache && documentWasDeleted) {
112
- try {
113
- const ns = {
114
- iid: instanceId,
115
- type: 'mongodb',
116
- db: databaseName,
117
- collection: collectionName
118
- };
119
- const pattern = CacheFactory.buildNamespacePattern(ns);
120
-
121
- // 检查是否在事务中
122
- if (isInTransaction(options)) {
123
- // 事务中:调用 Transaction 的 recordInvalidation 方法
124
- const tx = getTransactionFromSession(options.session);
125
- if (tx && typeof tx.recordInvalidation === 'function') {
126
- // 🚀 传递 metadata 支持文档级别锁
127
- await tx.recordInvalidation(pattern, {
128
- operation: 'write',
129
- query: filter,
130
- collection: collectionName
131
- });
132
- logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
133
- } else {
134
- const deleted = await cache.delPattern(pattern);
135
- if (deleted > 0) {
136
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
137
- }
138
- }
139
- } else {
140
- // 非事务:直接失效缓存
141
- const deleted = await cache.delPattern(pattern);
142
- if (deleted > 0) {
143
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
144
- }
145
- }
146
- } catch (cacheErr) {
147
- logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
148
- }
149
- }
150
-
151
- // 5. 记录慢操作日志
152
- const duration = Date.now() - startTime;
153
- const slowQueryMs = defaults.slowQueryMs || 1000;
154
- const found = result && result.value !== null && result.value !== undefined;
155
-
156
- if (duration > slowQueryMs) {
157
- logger.warn(`[${operation}] 慢操作警告`, {
158
- ns,
159
- duration,
160
- threshold: slowQueryMs,
161
- filterKeys: Object.keys(filter),
162
- found,
163
- comment: options.comment
164
- });
165
- } else {
166
- logger.debug(`[${operation}] 操作完成`, {
167
- ns,
168
- duration,
169
- found
170
- });
171
- }
172
-
173
- // 6. 返回结果(使用统一的返回值处理函数)
174
- return handleFindOneAndResult(result, options, logger);
175
-
176
- } catch (error) {
177
- // 7. 错误处理
178
- const duration = Date.now() - startTime;
179
-
180
- logger.error(`[${operation}] 操作失败`, {
181
- ns,
182
- duration,
183
- error: error.message,
184
- code: error.code,
185
- filterKeys: Object.keys(filter)
186
- });
187
-
188
- // 其他错误
189
- throw createError(
190
- ErrorCodes.WRITE_ERROR,
191
- `findOneAndDelete 操作失败: ${error.message}`,
192
- null,
193
- error
194
- );
195
- }
196
- };
197
-
198
- return { findOneAndDelete };
199
- }
200
-
201
- module.exports = { createFindOneAndDeleteOps };
202
-
203
-
@@ -1,239 +0,0 @@
1
- /**
2
- * findOneAndReplace 操作实现
3
- * 原子地查找并替换单个文档
4
- */
5
-
6
- const { createError, ErrorCodes } = require('../../errors');
7
- const CacheFactory = require('../../cache');
8
- const { handleFindOneAndResult, wasDocumentModified } = require('./result-handler');
9
- const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
10
- const { convertObjectIdStrings } = require('../../utils/objectid-converter');
11
-
12
- /**
13
- * 创建 findOneAndReplace 操作
14
- * @param {Object} context - 模块上下文
15
- * @param {Object} context.db - MongoDB 数据库实例
16
- * @param {Object} context.cache - 缓存实例
17
- * @param {Object} context.logger - 日志实例
18
- * @param {Object} context.defaults - 默认配置
19
- * @param {string} context.collection - 集合名称
20
- * @param {string} context.effectiveDbName - 数据库名称
21
- * @param {string} context.instanceId - 实例ID
22
- * @returns {Object} 包含 findOneAndReplace 方法的对象
23
- */
24
- function createFindOneAndReplaceOps(context) {
25
- const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
26
-
27
- // 提取集合名称和原生 collection 对象
28
- const collectionName = collection.collectionName;
29
- const nativeCollection = collection;
30
-
31
- /**
32
- * 查找并替换单个文档(原子操作)
33
- * @param {Object} filter - 筛选条件(必需)
34
- * @param {Object} replacement - 替换文档(必需,不能包含更新操作符)
35
- * @param {Object} [options] - 操作选项
36
- * @param {Object} [options.projection] - 字段投影
37
- * @param {Object} [options.sort] - 排序条件
38
- * @param {boolean} [options.upsert=false] - 不存在时是否插入
39
- * @param {string} [options.returnDocument="before"] - 返回替换前("before")或替换后("after")的文档
40
- * @param {number} [options.maxTimeMS] - 最大执行时间
41
- * @param {Object} [options.writeConcern] - 写关注选项
42
- * @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
43
- * @param {string} [options.comment] - 操作注释(用于日志追踪)
44
- * @param {Object} [options.collation] - 排序规则
45
- * @param {Object} [options.hint] - 索引提示
46
- * @param {boolean} [options.includeResultMetadata=false] - 是否包含完整结果元数据
47
- * @returns {Promise<Object|null>} 返回文档或 null(未找到);includeResultMetadata=true 时返回 { value, ok, lastErrorObject }
48
- * @throws {Error} 当参数无效时
49
- *
50
- * @example
51
- * // 返回替换前的文档(默认)
52
- * const oldDoc = await collection("users").findOneAndReplace(
53
- * { userId: "user123" },
54
- * { userId: "user123", name: "Alice", age: 25, status: "active" }
55
- * );
56
- * console.log("Old doc:", oldDoc);
57
- *
58
- * @example
59
- * // 返回替换后的文档
60
- * const newDoc = await collection("users").findOneAndReplace(
61
- * { userId: "user123" },
62
- * { userId: "user123", name: "Alice", age: 26 },
63
- * { returnDocument: "after" }
64
- * );
65
- * console.log("New doc:", newDoc);
66
- *
67
- * @example
68
- * // 使用 upsert
69
- * const doc = await collection("config").findOneAndReplace(
70
- * { key: "theme" },
71
- * { key: "theme", value: "dark", updatedAt: new Date() },
72
- * { upsert: true, returnDocument: "after" }
73
- * );
74
- */
75
- const findOneAndReplace = async function findOneAndReplace(filter, replacement, options = {}) {
76
- const startTime = Date.now();
77
-
78
- // 1. 参数验证
79
- if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
80
- throw createError(
81
- ErrorCodes.INVALID_ARGUMENT,
82
- 'filter 必须是对象类型',
83
- [{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
84
- );
85
- }
86
-
87
- if (!replacement || typeof replacement !== 'object' || Array.isArray(replacement)) {
88
- throw createError(
89
- ErrorCodes.INVALID_ARGUMENT,
90
- 'replacement 必须是对象类型',
91
- [{ field: 'replacement', type: 'object.required', message: 'replacement 是必需参数且必须是对象' }]
92
- );
93
- }
94
-
95
- // 验证 replacement 不包含更新操作符
96
- const replacementKeys = Object.keys(replacement);
97
- if (replacementKeys.some(key => key.startsWith('$'))) {
98
- throw createError(
99
- ErrorCodes.INVALID_ARGUMENT,
100
- 'replacement 不能包含更新操作符(如 $set, $inc 等)',
101
- [{ field: 'replacement', type: 'object.invalid', message: 'findOneAndReplace 用于完整替换文档,请使用 findOneAndUpdate 进行部分更新' }]
102
- );
103
- }
104
-
105
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
106
- const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
107
- logger: context.logger,
108
- excludeFields: context.autoConvertConfig?.excludeFields,
109
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
110
- maxDepth: context.autoConvertConfig?.maxDepth
111
- });
112
-
113
- const convertedReplacement = convertObjectIdStrings(replacement, 'document', 0, new WeakSet(), {
114
- logger: context.logger,
115
- excludeFields: context.autoConvertConfig?.excludeFields,
116
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
117
- maxDepth: context.autoConvertConfig?.maxDepth
118
- });
119
-
120
- // 2. 构建操作上下文
121
- const operation = 'findOneAndReplace';
122
- const ns = `${databaseName}.${collectionName}`;
123
-
124
- try {
125
- // 3. 执行查找并替换操作
126
- // MongoDB 驱动 6.x: 默认返回文档,需要 includeResultMetadata=true 获取完整元数据
127
- const driverOptions = { ...options, includeResultMetadata: true };
128
- const result = await nativeCollection.findOneAndReplace(convertedFilter, convertedReplacement, driverOptions);
129
-
130
- // 4. 自动失效缓存(如果有文档被修改)
131
- // 使用安全的修改判断函数
132
- const wasModified = wasDocumentModified(result);
133
- if (cache && wasModified) {
134
- try {
135
- const ns = {
136
- iid: instanceId,
137
- type: 'mongodb',
138
- db: databaseName,
139
- collection: collectionName
140
- };
141
- const pattern = CacheFactory.buildNamespacePattern(ns);
142
-
143
- // 检查是否在事务中
144
- if (isInTransaction(options)) {
145
- // 事务中:调用 Transaction 的 recordInvalidation 方法
146
- const tx = getTransactionFromSession(options.session);
147
- if (tx && typeof tx.recordInvalidation === 'function') {
148
- // 🚀 传递 metadata 支持文档级别锁
149
- await tx.recordInvalidation(pattern, {
150
- operation: 'write',
151
- query: filter,
152
- collection: collectionName
153
- });
154
- logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
155
- } else {
156
- const deleted = await cache.delPattern(pattern);
157
- if (deleted > 0) {
158
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
159
- }
160
- }
161
- } else {
162
- // 非事务:直接失效缓存
163
- const deleted = await cache.delPattern(pattern);
164
- if (deleted > 0) {
165
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
166
- }
167
- }
168
- } catch (cacheErr) {
169
- logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
170
- }
171
- }
172
-
173
- // 5. 记录慢操作日志
174
- const duration = Date.now() - startTime;
175
- const slowQueryMs = defaults.slowQueryMs || 1000;
176
- if (duration > slowQueryMs) {
177
- logger.warn(`[${operation}] 慢操作警告`, {
178
- ns,
179
- duration,
180
- threshold: slowQueryMs,
181
- filterKeys: Object.keys(filter),
182
- replacementKeys: Object.keys(replacement),
183
- found: result && result.value !== null,
184
- upserted: result?.lastErrorObject?.upserted ? true : false,
185
- returnDocument: options.returnDocument || 'before',
186
- comment: options.comment
187
- });
188
- } else {
189
- logger.debug(`[${operation}] 操作完成`, {
190
- ns,
191
- duration,
192
- found: result && result.value !== null,
193
- upserted: result?.lastErrorObject?.upserted ? true : false,
194
- returnDocument: options.returnDocument || 'before'
195
- });
196
- }
197
-
198
- // 6. 返回结果(使用统一的返回值处理函数)
199
- return handleFindOneAndResult(result, options, logger);
200
-
201
- } catch (error) {
202
- // 7. 错误处理
203
- const duration = Date.now() - startTime;
204
-
205
- logger.error(`[${operation}] 操作失败`, {
206
- ns,
207
- duration,
208
- error: error.message,
209
- code: error.code,
210
- filterKeys: Object.keys(filter),
211
- replacementKeys: Object.keys(replacement)
212
- });
213
-
214
- // 识别特定错误类型
215
- if (error.code === 11000) {
216
- throw createError(
217
- ErrorCodes.DUPLICATE_KEY,
218
- '查找并替换失败:违反唯一性约束',
219
- [{ field: '_id', message: error.message }],
220
- error
221
- );
222
- }
223
-
224
- // 其他错误
225
- throw createError(
226
- ErrorCodes.WRITE_ERROR,
227
- `findOneAndReplace 操作失败: ${error.message}`,
228
- null,
229
- error
230
- );
231
- }
232
- };
233
-
234
- return { findOneAndReplace };
235
- }
236
-
237
- module.exports = { createFindOneAndReplaceOps };
238
-
239
-
@@ -1,240 +0,0 @@
1
- /**
2
- * findOneAndUpdate 操作实现
3
- * 原子地查找并更新单个文档
4
- */
5
-
6
- const { createError, ErrorCodes } = require('../../errors');
7
- const CacheFactory = require('../../cache');
8
- const { handleFindOneAndResult, wasDocumentModified } = require('./result-handler');
9
- const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
10
- const { convertObjectIdStrings, convertUpdateDocument } = require('../../utils/objectid-converter');
11
-
12
- /**
13
- * 创建 findOneAndUpdate 操作
14
- * @param {Object} context - 模块上下文
15
- * @param {Object} context.db - MongoDB 数据库实例
16
- * @param {Object} context.cache - 缓存实例
17
- * @param {Object} context.logger - 日志实例
18
- * @param {Object} context.defaults - 默认配置
19
- * @param {string} context.collection - 集合名称
20
- * @param {string} context.effectiveDbName - 数据库名称
21
- * @param {string} context.instanceId - 实例ID
22
- * @returns {Object} 包含 findOneAndUpdate 方法的对象
23
- */
24
- function createFindOneAndUpdateOps(context) {
25
- const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
26
-
27
- // 提取集合名称和原生 collection 对象
28
- const collectionName = collection.collectionName;
29
- const nativeCollection = collection;
30
-
31
- /**
32
- * 查找并更新单个文档(原子操作)
33
- * @param {Object} filter - 筛选条件(必需)
34
- * @param {Object} update - 更新操作(必需,使用更新操作符如 $set)
35
- * @param {Object} [options] - 操作选项
36
- * @param {Object} [options.projection] - 字段投影
37
- * @param {Object} [options.sort] - 排序条件
38
- * @param {boolean} [options.upsert=false] - 不存在时是否插入
39
- * @param {string} [options.returnDocument="before"] - 返回更新前("before")或更新后("after")的文档
40
- * @param {number} [options.maxTimeMS] - 最大执行时间
41
- * @param {Object} [options.writeConcern] - 写关注选项
42
- * @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
43
- * @param {string} [options.comment] - 操作注释(用于日志追踪)
44
- * @param {Object} [options.collation] - 排序规则
45
- * @param {Array|Object} [options.arrayFilters] - 数组过滤器
46
- * @param {Object} [options.hint] - 索引提示
47
- * @param {boolean} [options.includeResultMetadata=false] - 是否包含完整结果元数据
48
- * @returns {Promise<Object|null>} 返回文档或 null(未找到);includeResultMetadata=true 时返回 { value, ok, lastErrorObject }
49
- * @throws {Error} 当参数无效时
50
- *
51
- * @example
52
- * // 返回更新前的文档(默认)
53
- * const oldDoc = await collection("users").findOneAndUpdate(
54
- * { userId: "user123" },
55
- * { $set: { status: "active" } }
56
- * );
57
- * console.log("Old status:", oldDoc?.status);
58
- *
59
- * @example
60
- * // 返回更新后的文档
61
- * const newDoc = await collection("users").findOneAndUpdate(
62
- * { userId: "user123" },
63
- * { $inc: { loginCount: 1 } },
64
- * { returnDocument: "after" }
65
- * );
66
- * console.log("New login count:", newDoc?.loginCount);
67
- *
68
- * @example
69
- * // 使用 upsert + 排序
70
- * const doc = await collection("counters").findOneAndUpdate(
71
- * { name: "orderCounter" },
72
- * { $inc: { value: 1 } },
73
- * { upsert: true, returnDocument: "after", sort: { _id: -1 } }
74
- * );
75
- */
76
- const findOneAndUpdate = async function findOneAndUpdate(filter, update, options = {}) {
77
- const startTime = Date.now();
78
-
79
- // 1. 参数验证
80
- if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
81
- throw createError(
82
- ErrorCodes.INVALID_ARGUMENT,
83
- 'filter 必须是对象类型',
84
- [{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
85
- );
86
- }
87
-
88
- if (!update || typeof update !== 'object' || Array.isArray(update)) {
89
- throw createError(
90
- ErrorCodes.INVALID_ARGUMENT,
91
- 'update 必须是对象类型',
92
- [{ field: 'update', type: 'object.required', message: 'update 是必需参数且必须是对象' }]
93
- );
94
- }
95
-
96
- // 验证 update 包含更新操作符
97
- const updateKeys = Object.keys(update);
98
- if (updateKeys.length > 0 && !updateKeys.some(key => key.startsWith('$'))) {
99
- throw createError(
100
- ErrorCodes.INVALID_ARGUMENT,
101
- 'update 必须使用更新操作符(如 $set, $inc 等)',
102
- [{ field: 'update', type: 'object.invalid', message: '请使用 $set, $inc, $push 等更新操作符,或使用 findOneAndReplace 进行整体替换' }]
103
- );
104
- }
105
-
106
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
107
- const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
108
- logger: context.logger,
109
- excludeFields: context.autoConvertConfig?.excludeFields,
110
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
111
- maxDepth: context.autoConvertConfig?.maxDepth
112
- });
113
-
114
- const convertedUpdate = convertUpdateDocument(update, {
115
- logger: context.logger,
116
- excludeFields: context.autoConvertConfig?.excludeFields,
117
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
118
- maxDepth: context.autoConvertConfig?.maxDepth
119
- });
120
-
121
- // 2. 构建操作上下文
122
- const operation = 'findOneAndUpdate';
123
- const ns = `${databaseName}.${collectionName}`;
124
-
125
- try {
126
- // 3. 执行查找并更新操作
127
- // MongoDB 驱动 6.x: 默认返回文档,需要 includeResultMetadata=true 获取完整元数据
128
- const driverOptions = { ...options, includeResultMetadata: true };
129
- const result = await nativeCollection.findOneAndUpdate(convertedFilter, convertedUpdate, driverOptions);
130
-
131
- // 4. 自动失效缓存(如果有文档被修改)
132
- // 使用安全的修改判断函数
133
- const wasModified = wasDocumentModified(result);
134
- if (cache && wasModified) {
135
- try {
136
- const ns = {
137
- iid: instanceId,
138
- type: 'mongodb',
139
- db: databaseName,
140
- collection: collectionName
141
- };
142
- const pattern = CacheFactory.buildNamespacePattern(ns);
143
-
144
- // 检查是否在事务中
145
- if (isInTransaction(options)) {
146
- // 事务中:调用 Transaction 的 recordInvalidation 方法
147
- const tx = getTransactionFromSession(options.session);
148
- if (tx && typeof tx.recordInvalidation === 'function') {
149
- // 🚀 传递 metadata 支持文档级别锁
150
- await tx.recordInvalidation(pattern, {
151
- operation: 'write',
152
- query: filter,
153
- collection: collectionName
154
- });
155
- logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
156
- } else {
157
- const deleted = await cache.delPattern(pattern);
158
- if (deleted > 0) {
159
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
160
- }
161
- }
162
- } else {
163
- // 非事务:直接失效缓存
164
- const deleted = await cache.delPattern(pattern);
165
- if (deleted > 0) {
166
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
167
- }
168
- }
169
- } catch (cacheErr) {
170
- logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
171
- }
172
- }
173
-
174
- // 5. 记录慢操作日志
175
- const duration = Date.now() - startTime;
176
- const slowQueryMs = defaults.slowQueryMs || 1000;
177
- if (duration > slowQueryMs) {
178
- logger.warn(`[${operation}] 慢操作警告`, {
179
- ns,
180
- duration,
181
- threshold: slowQueryMs,
182
- filterKeys: Object.keys(filter),
183
- updateKeys: Object.keys(update),
184
- found: result && result.value !== null,
185
- upserted: result?.lastErrorObject?.upserted ? true : false,
186
- returnDocument: options.returnDocument || 'before',
187
- comment: options.comment
188
- });
189
- } else {
190
- logger.debug(`[${operation}] 操作完成`, {
191
- ns,
192
- duration,
193
- found: result && result.value !== null,
194
- upserted: result?.lastErrorObject?.upserted ? true : false,
195
- returnDocument: options.returnDocument || 'before'
196
- });
197
- }
198
-
199
- // 6. 返回结果(使用统一的返回值处理函数)
200
- return handleFindOneAndResult(result, options, logger);
201
-
202
- } catch (error) {
203
- // 7. 错误处理
204
- const duration = Date.now() - startTime;
205
-
206
- logger.error(`[${operation}] 操作失败`, {
207
- ns,
208
- duration,
209
- error: error.message,
210
- code: error.code,
211
- filterKeys: Object.keys(filter),
212
- updateKeys: Object.keys(update)
213
- });
214
-
215
- // 识别特定错误类型
216
- if (error.code === 11000) {
217
- throw createError(
218
- ErrorCodes.DUPLICATE_KEY,
219
- '查找并更新失败:违反唯一性约束',
220
- [{ field: '_id', message: error.message }],
221
- error
222
- );
223
- }
224
-
225
- // 其他错误
226
- throw createError(
227
- ErrorCodes.WRITE_ERROR,
228
- `findOneAndUpdate 操作失败: ${error.message}`,
229
- null,
230
- error
231
- );
232
- }
233
- };
234
-
235
- return { findOneAndUpdate };
236
- }
237
-
238
- module.exports = { createFindOneAndUpdateOps };
239
-
240
-