monsqlize 1.0.2 → 1.0.5

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.
@@ -0,0 +1,358 @@
1
+ /**
2
+ * updateBatch 操作实现
3
+ * 分批更新大量匹配的文档(基于流式查询)
4
+ */
5
+
6
+ const { createError, ErrorCodes } = require('../../errors');
7
+ const CacheFactory = require('../../cache');
8
+ const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
9
+ const { convertObjectIdStrings, convertUpdateDocument } = require('../../utils/objectid-converter');
10
+ const { executeBatchWithRetry } = require('./common/batch-retry');
11
+
12
+ /**
13
+ * 创建 updateBatch 操作
14
+ * @param {Object} context - 模块上下文
15
+ * @returns {Object} 包含 updateBatch 方法的对象
16
+ */
17
+ function createUpdateBatchOps(context) {
18
+ const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
19
+
20
+ const collectionName = collection.collectionName;
21
+ const nativeCollection = collection;
22
+
23
+ /**
24
+ * 分批更新大量匹配的文档
25
+ * @param {Object} filter - 筛选条件(必需)
26
+ * @param {Object} update - 更新操作(必需,使用更新操作符如 $set)
27
+ * @param {Object} [options] - 操作选项
28
+ * @param {number} [options.batchSize=1000] - 每批更新的文档数量
29
+ * @param {boolean} [options.estimateProgress=true] - 是否预先 count 获取总数
30
+ * @param {Function} [options.onProgress] - 进度回调函数 (progress) => {}
31
+ * @param {string} [options.onError='stop'] - 错误处理策略: 'stop'/'skip'/'collect'/'retry'
32
+ * @param {number} [options.retryAttempts=3] - 失败批次最大重试次数
33
+ * @param {number} [options.retryDelay=1000] - 重试延迟时间(毫秒)
34
+ * @param {Function} [options.onRetry] - 重试回调函数 (retryInfo) => {}
35
+ * @param {Object} [options.writeConcern] - 写关注选项
36
+ * @param {string} [options.comment] - 操作注释(用于日志追踪)
37
+ * @returns {Promise<Object>} 更新结果
38
+ *
39
+ * @example
40
+ * const result = await collection('orders').updateBatch(
41
+ * { status: 'pending', createdAt: { $lt: expiredDate } },
42
+ * { $set: { status: 'expired' } },
43
+ * {
44
+ * batchSize: 500,
45
+ * estimateProgress: true,
46
+ * onProgress: (p) => console.log(`进度: ${p.percentage}%`)
47
+ * }
48
+ * );
49
+ */
50
+ const updateBatch = async function updateBatch(filter, update, options = {}) {
51
+ const startTime = Date.now();
52
+
53
+ // 1. 参数验证
54
+ if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
55
+ throw createError(
56
+ ErrorCodes.INVALID_ARGUMENT,
57
+ 'filter 必须是对象类型',
58
+ [{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
59
+ );
60
+ }
61
+
62
+ if (!update || typeof update !== 'object' || Array.isArray(update)) {
63
+ throw createError(
64
+ ErrorCodes.INVALID_ARGUMENT,
65
+ 'update 必须是对象类型',
66
+ [{ field: 'update', type: 'object.required', message: 'update 是必需参数且必须是对象' }]
67
+ );
68
+ }
69
+
70
+ // 验证 update 包含更新操作符
71
+ const updateKeys = Object.keys(update);
72
+ if (updateKeys.length > 0 && !updateKeys.some(key => key.startsWith('$'))) {
73
+ throw createError(
74
+ ErrorCodes.INVALID_ARGUMENT,
75
+ 'update 必须使用更新操作符(如 $set, $inc 等)',
76
+ [{ field: 'update', type: 'object.invalid', message: '请使用 $set, $inc, $push 等更新操作符' }]
77
+ );
78
+ }
79
+
80
+ // 自动转换 ObjectId 字符串
81
+ const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
82
+ logger: context.logger,
83
+ excludeFields: context.autoConvertConfig?.excludeFields,
84
+ customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
85
+ maxDepth: context.autoConvertConfig?.maxDepth
86
+ });
87
+
88
+ const convertedUpdate = convertUpdateDocument(update, {
89
+ logger: context.logger,
90
+ excludeFields: context.autoConvertConfig?.excludeFields,
91
+ customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
92
+ maxDepth: context.autoConvertConfig?.maxDepth
93
+ });
94
+
95
+ // 解构选项
96
+ const {
97
+ batchSize = 1000,
98
+ estimateProgress = true,
99
+ onProgress,
100
+ onError = 'stop',
101
+ retryAttempts = 3,
102
+ retryDelay = 1000,
103
+ onRetry,
104
+ writeConcern,
105
+ comment
106
+ } = options;
107
+
108
+ // 2. 预先 count(可选)
109
+ const totalCount = estimateProgress
110
+ ? await nativeCollection.countDocuments(convertedFilter)
111
+ : null;
112
+
113
+ // 3. 初始化结果
114
+ const result = {
115
+ acknowledged: true,
116
+ totalCount,
117
+ matchedCount: 0,
118
+ modifiedCount: 0,
119
+ batchCount: 0,
120
+ errors: [],
121
+ retries: []
122
+ };
123
+
124
+ // 4. 🔴 关键:直接调用 context 的 find 流式方法
125
+ const stream = await context.find(convertedFilter, {
126
+ stream: true,
127
+ batchSize,
128
+ limit: 0, // 🔴 重要:禁用默认的 limit,否则只会查询默认的 10 条
129
+ comment: comment ? `${comment}:updateBatch` : 'updateBatch'
130
+ });
131
+
132
+ let batch = [];
133
+
134
+ return new Promise((resolve, reject) => {
135
+ // 5. 监听数据事件
136
+ stream.on('data', async (doc) => {
137
+ batch.push(doc._id);
138
+
139
+ // 达到批次大小,执行更新
140
+ if (batch.length >= batchSize) {
141
+ stream.pause();
142
+
143
+ try {
144
+ // 🔴 带重试的批量更新
145
+ const batchResult = await executeBatchWithRetry(
146
+ () => nativeCollection.updateMany(
147
+ { _id: { $in: batch } },
148
+ convertedUpdate,
149
+ { writeConcern }
150
+ ),
151
+ { onError, retryAttempts, retryDelay, onRetry, batchIndex: result.batchCount }
152
+ );
153
+
154
+ result.matchedCount += batchResult.result.matchedCount;
155
+ result.modifiedCount += batchResult.result.modifiedCount;
156
+ result.batchCount++;
157
+
158
+ // 记录重试信息
159
+ if (batchResult.attempts > 0) {
160
+ result.retries.push({
161
+ batchIndex: result.batchCount - 1,
162
+ attempts: batchResult.attempts,
163
+ success: true
164
+ });
165
+ }
166
+
167
+ batch = [];
168
+
169
+ // 🔴 进度回调
170
+ if (onProgress) {
171
+ onProgress({
172
+ currentBatch: result.batchCount,
173
+ totalBatches: totalCount ? Math.ceil(totalCount / batchSize) : null,
174
+ matched: result.matchedCount,
175
+ modified: result.modifiedCount,
176
+ total: totalCount,
177
+ percentage: totalCount ? Math.round((result.matchedCount / totalCount) * 100) : null,
178
+ errors: result.errors.length,
179
+ retries: result.retries.length
180
+ });
181
+ }
182
+
183
+ stream.resume();
184
+
185
+ } catch (error) {
186
+ // 🔴 错误处理
187
+ result.errors.push({
188
+ batchIndex: result.batchCount,
189
+ batchSize: batch.length,
190
+ error: error,
191
+ message: error.message
192
+ });
193
+
194
+ if (onError === 'stop') {
195
+ stream.destroy();
196
+ reject(createError(
197
+ ErrorCodes.WRITE_ERROR,
198
+ `updateBatch 操作失败: ${error.message}`,
199
+ null,
200
+ error
201
+ ));
202
+ return;
203
+ }
204
+
205
+ // skip 或 collect:清空批次,继续
206
+ batch = [];
207
+ result.batchCount++;
208
+ stream.resume();
209
+ }
210
+ }
211
+ });
212
+
213
+ // 6. 监听流结束事件
214
+ stream.on('end', async () => {
215
+ // 处理剩余的批次
216
+ if (batch.length > 0) {
217
+ try {
218
+ const batchResult = await executeBatchWithRetry(
219
+ () => nativeCollection.updateMany(
220
+ { _id: { $in: batch } },
221
+ convertedUpdate,
222
+ { writeConcern }
223
+ ),
224
+ { onError, retryAttempts, retryDelay, onRetry, batchIndex: result.batchCount }
225
+ );
226
+
227
+ result.matchedCount += batchResult.result.matchedCount;
228
+ result.modifiedCount += batchResult.result.modifiedCount;
229
+ result.batchCount++;
230
+
231
+ if (batchResult.attempts > 0) {
232
+ result.retries.push({
233
+ batchIndex: result.batchCount - 1,
234
+ attempts: batchResult.attempts,
235
+ success: true
236
+ });
237
+ }
238
+
239
+ // 最后一批的进度回调
240
+ if (onProgress) {
241
+ onProgress({
242
+ currentBatch: result.batchCount,
243
+ matched: result.matchedCount,
244
+ modified: result.modifiedCount,
245
+ total: totalCount,
246
+ percentage: totalCount ? 100 : null,
247
+ errors: result.errors.length,
248
+ retries: result.retries.length
249
+ });
250
+ }
251
+
252
+ } catch (error) {
253
+ result.errors.push({
254
+ batchIndex: result.batchCount,
255
+ batchSize: batch.length,
256
+ error: error,
257
+ message: error.message
258
+ });
259
+ }
260
+ }
261
+
262
+ // 7. 最终缓存失效
263
+ if (cache && result.modifiedCount > 0) {
264
+ try {
265
+ const ns = {
266
+ iid: instanceId,
267
+ type: 'mongodb',
268
+ db: databaseName,
269
+ collection: collectionName
270
+ };
271
+ const pattern = CacheFactory.buildNamespacePattern(ns);
272
+
273
+ // 检查是否在事务中
274
+ if (isInTransaction(options)) {
275
+ const tx = getTransactionFromSession(options.session);
276
+ if (tx && typeof tx.recordInvalidation === 'function') {
277
+ await tx.recordInvalidation(pattern, {
278
+ operation: 'write',
279
+ query: filter || {},
280
+ collection: collectionName
281
+ });
282
+ logger.debug(`[updateBatch] 事务中失效缓存: ${ns.db}.${ns.collection}`);
283
+ } else {
284
+ const deleted = await cache.delPattern(pattern);
285
+ if (deleted > 0) {
286
+ logger.debug(`[updateBatch] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
287
+ }
288
+ }
289
+ } else {
290
+ const deleted = await cache.delPattern(pattern);
291
+ if (deleted > 0) {
292
+ logger.debug(`[updateBatch] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
293
+ }
294
+ }
295
+ } catch (cacheErr) {
296
+ logger.warn(`[updateBatch] 缓存失效失败: ${cacheErr.message}`);
297
+ }
298
+ }
299
+
300
+ // 8. 慢查询日志
301
+ const duration = Date.now() - startTime;
302
+ const slowQueryMs = defaults.slowQueryMs || 1000;
303
+
304
+ if (duration > slowQueryMs) {
305
+ logger.warn(`[updateBatch] 慢操作警告`, {
306
+ ns: `${databaseName}.${collectionName}`,
307
+ duration,
308
+ threshold: slowQueryMs,
309
+ totalCount,
310
+ matchedCount: result.matchedCount,
311
+ modifiedCount: result.modifiedCount,
312
+ batchCount: result.batchCount,
313
+ errorCount: result.errors.length,
314
+ retryCount: result.retries.length,
315
+ comment
316
+ });
317
+ } else {
318
+ logger.debug(`[updateBatch] 操作完成`, {
319
+ ns: `${databaseName}.${collectionName}`,
320
+ duration,
321
+ matchedCount: result.matchedCount,
322
+ modifiedCount: result.modifiedCount,
323
+ batchCount: result.batchCount
324
+ });
325
+ }
326
+
327
+ resolve(result);
328
+ });
329
+
330
+ // 9. 监听流错误事件
331
+ stream.on('error', (error) => {
332
+ logger.error(`[updateBatch] 流式查询错误`, {
333
+ ns: `${databaseName}.${collectionName}`,
334
+ error: error.message,
335
+ code: error.code
336
+ });
337
+
338
+ result.errors.push({
339
+ batchIndex: result.batchCount,
340
+ error: error,
341
+ message: `流式查询错误: ${error.message}`
342
+ });
343
+
344
+ reject(createError(
345
+ ErrorCodes.WRITE_ERROR,
346
+ `updateBatch 流式查询失败: ${error.message}`,
347
+ null,
348
+ error
349
+ ));
350
+ });
351
+ });
352
+ };
353
+
354
+ return { updateBatch };
355
+ }
356
+
357
+ module.exports = { createUpdateBatchOps };
358
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "monsqlize",
3
- "version": "1.0.2",
3
+ "version": "1.0.5",
4
4
  "description": "A lightweight MongoDB ORM with multi-level caching, transaction support, and distributed features",
5
5
  "main": "lib/index.js",
6
6
  "module": "index.mjs",
@@ -68,9 +68,15 @@
68
68
  "type-check": "tsc",
69
69
  "postpublish": "echo '✅ 发布成功!请创建 GitHub Release: https://github.com/vextjs/monSQLize/releases/new?tag=v'$npm_package_version"
70
70
  },
71
+ "peerDependencies": {
72
+ "schema-dsl": "^1.0.0"
73
+ },
71
74
  "peerDependenciesMeta": {
72
75
  "ioredis": {
73
76
  "optional": true
77
+ },
78
+ "schema-dsl": {
79
+ "optional": true
74
80
  }
75
81
  },
76
82
  "optionalDependencies": {
@@ -114,4 +120,4 @@
114
120
  "mongodb": "^6.17.0",
115
121
  "ssh2": "^1.17.0"
116
122
  }
117
- }
123
+ }