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