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,498 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* insertBatch 操作实现(改进版 - 支持重试机制)
|
|
3
|
+
* 分批批量插入大量文档到集合
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const { createError, ErrorCodes } = require("../../errors");
|
|
7
|
+
const CacheFactory = require("../../cache");
|
|
8
|
+
const { isInTransaction, getTransactionFromSession } = require("../common/transaction-aware");
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 创建 insertBatch 操作
|
|
12
|
+
* @param {Object} context - 模块上下文
|
|
13
|
+
* @param {Object} context.insertMany - insertMany 方法实例
|
|
14
|
+
* @param {Object} context.cache - 缓存实例
|
|
15
|
+
* @param {Object} context.logger - 日志实例
|
|
16
|
+
* @param {Object} context.defaults - 默认配置
|
|
17
|
+
* @param {string} context.collectionName - 集合名称
|
|
18
|
+
* @param {string} context.effectiveDbName - 数据库名称
|
|
19
|
+
* @param {string} context.instanceId - 实例ID
|
|
20
|
+
* @returns {Object} 包含 insertBatch 方法的对象
|
|
21
|
+
*/
|
|
22
|
+
function createInsertBatchOps(context) {
|
|
23
|
+
const { insertMany, cache, logger, defaults, collectionName, effectiveDbName: databaseName, instanceId } = context;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 分批批量插入多个文档
|
|
27
|
+
* @param {Array<Object>} documents - 要插入的文档数组(必需)
|
|
28
|
+
* @param {Object} [options] - 操作选项
|
|
29
|
+
* @param {number} [options.batchSize=1000] - 每批插入的文档数量
|
|
30
|
+
* @param {number} [options.concurrency=1] - 并发批次数(1=串行,>1=并行)
|
|
31
|
+
* @param {boolean} [options.ordered=false] - 批次内是否按顺序插入
|
|
32
|
+
* @param {Function} [options.onProgress] - 进度回调函数 (progress) => {}
|
|
33
|
+
* @param {string} [options.onError='stop'] - 错误处理策略: 'stop'/'skip'/'collect'/'retry'
|
|
34
|
+
* @param {number} [options.retryAttempts=3] - 失败批次最大重试次数(onError='retry'时有效)
|
|
35
|
+
* @param {number} [options.retryDelay=1000] - 重试延迟时间(毫秒)
|
|
36
|
+
* @param {Function} [options.onRetry] - 重试回调函数 (retryInfo) => {}
|
|
37
|
+
* @param {Object} [options.writeConcern] - 写关注选项
|
|
38
|
+
* @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
|
|
39
|
+
* @param {string} [options.comment] - 操作注释(用于日志追踪)
|
|
40
|
+
* @returns {Promise<Object>} 插入结果 { acknowledged, totalCount, insertedCount, batchCount, errors, retries, insertedIds }
|
|
41
|
+
*/
|
|
42
|
+
const insertBatch = async function insertBatch(documents, options = {}) {
|
|
43
|
+
const startTime = Date.now();
|
|
44
|
+
|
|
45
|
+
// 1. 参数验证
|
|
46
|
+
if (!Array.isArray(documents)) {
|
|
47
|
+
throw createError(
|
|
48
|
+
ErrorCodes.DOCUMENTS_REQUIRED,
|
|
49
|
+
"documents 必须是数组类型",
|
|
50
|
+
[{ field: "documents", type: "array.required", message: "documents 是必需参数且必须是数组" }]
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (documents.length === 0) {
|
|
55
|
+
throw createError(
|
|
56
|
+
ErrorCodes.DOCUMENTS_REQUIRED,
|
|
57
|
+
"documents 数组不能为空",
|
|
58
|
+
[{ field: "documents", type: "array.min", message: "documents 至少需要包含一个文档" }]
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 2. 提取并验证选项
|
|
63
|
+
const {
|
|
64
|
+
batchSize = 1000,
|
|
65
|
+
concurrency = 1,
|
|
66
|
+
ordered = false,
|
|
67
|
+
onProgress,
|
|
68
|
+
onError = "stop",
|
|
69
|
+
retryAttempts = 3,
|
|
70
|
+
retryDelay = 1000,
|
|
71
|
+
onRetry,
|
|
72
|
+
...insertOptions
|
|
73
|
+
} = options;
|
|
74
|
+
|
|
75
|
+
// 验证参数
|
|
76
|
+
if (typeof batchSize !== "number" || batchSize < 1) {
|
|
77
|
+
throw createError(
|
|
78
|
+
ErrorCodes.INVALID_PARAMETER,
|
|
79
|
+
"batchSize 必须是大于 0 的数字",
|
|
80
|
+
[{ field: "batchSize", type: "number.min", message: "batchSize 必须大于 0" }]
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (typeof concurrency !== "number" || concurrency < 1) {
|
|
85
|
+
throw createError(
|
|
86
|
+
ErrorCodes.INVALID_PARAMETER,
|
|
87
|
+
"concurrency 必须是大于 0 的数字",
|
|
88
|
+
[{ field: "concurrency", type: "number.min", message: "concurrency 必须大于 0" }]
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const validErrorStrategies = ["stop", "skip", "collect", "retry"];
|
|
93
|
+
if (!validErrorStrategies.includes(onError)) {
|
|
94
|
+
throw createError(
|
|
95
|
+
ErrorCodes.INVALID_PARAMETER,
|
|
96
|
+
`onError 必须是以下值之一: ${validErrorStrategies.join(", ")}`,
|
|
97
|
+
[{ field: "onError", type: "enum", message: `有效值: ${validErrorStrategies.join(", ")}` }]
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (typeof retryAttempts !== "number" || retryAttempts < 0) {
|
|
102
|
+
throw createError(
|
|
103
|
+
ErrorCodes.INVALID_PARAMETER,
|
|
104
|
+
"retryAttempts 必须是非负数",
|
|
105
|
+
[{ field: "retryAttempts", type: "number.min", message: "retryAttempts 必须 >= 0" }]
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (typeof retryDelay !== "number" || retryDelay < 0) {
|
|
110
|
+
throw createError(
|
|
111
|
+
ErrorCodes.INVALID_PARAMETER,
|
|
112
|
+
"retryDelay 必须是非负数",
|
|
113
|
+
[{ field: "retryDelay", type: "number.min", message: "retryDelay 必须 >= 0" }]
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// 3. 构建操作上下文
|
|
118
|
+
const operation = "insertBatch";
|
|
119
|
+
const ns = `${databaseName}.${collectionName}`;
|
|
120
|
+
const totalCount = documents.length;
|
|
121
|
+
const totalBatches = Math.ceil(totalCount / batchSize);
|
|
122
|
+
|
|
123
|
+
// 结果统计
|
|
124
|
+
const result = {
|
|
125
|
+
acknowledged: true,
|
|
126
|
+
totalCount,
|
|
127
|
+
insertedCount: 0,
|
|
128
|
+
batchCount: totalBatches,
|
|
129
|
+
errors: [],
|
|
130
|
+
retries: [], // 新增:重试记录
|
|
131
|
+
insertedIds: {}
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
logger.debug(`[${operation}] 开始分批插入`, {
|
|
135
|
+
ns,
|
|
136
|
+
totalCount,
|
|
137
|
+
batchSize,
|
|
138
|
+
totalBatches,
|
|
139
|
+
concurrency,
|
|
140
|
+
onError,
|
|
141
|
+
retryAttempts: onError === "retry" ? retryAttempts : 0
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
try {
|
|
145
|
+
// 4. 分割文档为批次
|
|
146
|
+
const batches = [];
|
|
147
|
+
for (let i = 0; i < documents.length; i += batchSize) {
|
|
148
|
+
batches.push({
|
|
149
|
+
index: batches.length,
|
|
150
|
+
documents: documents.slice(i, Math.min(i + batchSize, documents.length)),
|
|
151
|
+
startIndex: i
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// 5. 执行批次插入
|
|
156
|
+
if (concurrency === 1) {
|
|
157
|
+
await executeSequential(batches, result, insertOptions, onProgress, {
|
|
158
|
+
onError,
|
|
159
|
+
retryAttempts,
|
|
160
|
+
retryDelay,
|
|
161
|
+
onRetry,
|
|
162
|
+
logger,
|
|
163
|
+
insertMany
|
|
164
|
+
});
|
|
165
|
+
} else {
|
|
166
|
+
await executeConcurrent(batches, result, insertOptions, onProgress, concurrency, {
|
|
167
|
+
onError,
|
|
168
|
+
retryAttempts,
|
|
169
|
+
retryDelay,
|
|
170
|
+
onRetry,
|
|
171
|
+
logger,
|
|
172
|
+
insertMany
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// 6. 最终缓存失效
|
|
177
|
+
if (result.insertedCount > 0 && cache) {
|
|
178
|
+
try {
|
|
179
|
+
const nsObj = {
|
|
180
|
+
iid: instanceId,
|
|
181
|
+
type: "mongodb",
|
|
182
|
+
db: databaseName,
|
|
183
|
+
collection: collectionName
|
|
184
|
+
};
|
|
185
|
+
const pattern = CacheFactory.buildNamespacePattern(nsObj);
|
|
186
|
+
const deleted = await cache.delPattern(pattern);
|
|
187
|
+
|
|
188
|
+
if (deleted > 0) {
|
|
189
|
+
logger.debug(`[${operation}] 自动失效缓存: ${nsObj.db}.${nsObj.collection}, 删除 ${deleted} 个缓存键`);
|
|
190
|
+
}
|
|
191
|
+
} catch (cacheErr) {
|
|
192
|
+
logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns, error: cacheErr });
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// 7. 记录完成日志
|
|
197
|
+
const duration = Date.now() - startTime;
|
|
198
|
+
const slowThreshold = defaults.slowThreshold || 5000;
|
|
199
|
+
|
|
200
|
+
if (duration > slowThreshold) {
|
|
201
|
+
logger.warn(`[${operation}] 慢操作警告`, {
|
|
202
|
+
ns,
|
|
203
|
+
duration,
|
|
204
|
+
threshold: slowThreshold,
|
|
205
|
+
totalCount,
|
|
206
|
+
insertedCount: result.insertedCount,
|
|
207
|
+
batchCount: result.batchCount,
|
|
208
|
+
errorCount: result.errors.length,
|
|
209
|
+
retryCount: result.retries.length,
|
|
210
|
+
comment: insertOptions.comment
|
|
211
|
+
});
|
|
212
|
+
} else {
|
|
213
|
+
logger.debug(`[${operation}] 操作完成`, {
|
|
214
|
+
ns,
|
|
215
|
+
duration,
|
|
216
|
+
totalCount,
|
|
217
|
+
insertedCount: result.insertedCount,
|
|
218
|
+
batchCount: result.batchCount,
|
|
219
|
+
errorCount: result.errors.length,
|
|
220
|
+
retryCount: result.retries.length
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// 8. 如果有错误且策略是 stop,抛出错误
|
|
225
|
+
if (result.errors.length > 0 && onError === "stop") {
|
|
226
|
+
throw createError(
|
|
227
|
+
ErrorCodes.WRITE_ERROR,
|
|
228
|
+
`insertBatch 操作失败: 在批次 ${result.errors[0].batchIndex + 1}/${totalBatches} 遇到错误`,
|
|
229
|
+
result.errors,
|
|
230
|
+
result.errors[0].error
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return result;
|
|
235
|
+
|
|
236
|
+
} catch (error) {
|
|
237
|
+
const duration = Date.now() - startTime;
|
|
238
|
+
|
|
239
|
+
logger.error(`[${operation}] 操作失败`, {
|
|
240
|
+
ns,
|
|
241
|
+
duration,
|
|
242
|
+
error: error.message,
|
|
243
|
+
code: error.code,
|
|
244
|
+
totalCount,
|
|
245
|
+
insertedCount: result.insertedCount,
|
|
246
|
+
errorCount: result.errors.length,
|
|
247
|
+
retryCount: result.retries.length
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
if (error.code === ErrorCodes.WRITE_ERROR && result.errors.length > 0) {
|
|
251
|
+
throw error;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
throw createError(
|
|
255
|
+
ErrorCodes.WRITE_ERROR,
|
|
256
|
+
`insertBatch 操作失败: ${error.message}`,
|
|
257
|
+
null,
|
|
258
|
+
error
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* 执行单个批次插入(带重试)
|
|
265
|
+
*/
|
|
266
|
+
async function executeBatchWithRetry(batch, insertOptions, retryContext) {
|
|
267
|
+
const { onError, retryAttempts, retryDelay, onRetry, logger, insertMany } = retryContext;
|
|
268
|
+
|
|
269
|
+
let lastError = null;
|
|
270
|
+
let attempts = 0;
|
|
271
|
+
const maxAttempts = onError === "retry" ? retryAttempts + 1 : 1;
|
|
272
|
+
|
|
273
|
+
while (attempts < maxAttempts) {
|
|
274
|
+
try {
|
|
275
|
+
const batchResult = await insertMany(batch.documents, {
|
|
276
|
+
...insertOptions,
|
|
277
|
+
ordered: insertOptions.ordered !== undefined ? insertOptions.ordered : false
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
// 成功
|
|
281
|
+
return {
|
|
282
|
+
success: true,
|
|
283
|
+
batch,
|
|
284
|
+
result: batchResult,
|
|
285
|
+
attempts
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
} catch (error) {
|
|
289
|
+
lastError = error;
|
|
290
|
+
attempts++;
|
|
291
|
+
|
|
292
|
+
// 如果还可以重试
|
|
293
|
+
if (attempts < maxAttempts) {
|
|
294
|
+
logger.warn(`[insertBatch] 批次 ${batch.index + 1} 失败,准备重试 (${attempts}/${retryAttempts})`, {
|
|
295
|
+
error: error.message,
|
|
296
|
+
batchIndex: batch.index
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
// 触发重试回调
|
|
300
|
+
if (onRetry) {
|
|
301
|
+
onRetry({
|
|
302
|
+
batchIndex: batch.index,
|
|
303
|
+
attempt: attempts,
|
|
304
|
+
maxAttempts: retryAttempts,
|
|
305
|
+
error: error,
|
|
306
|
+
nextRetryDelay: retryDelay
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// 延迟后重试
|
|
311
|
+
if (retryDelay > 0) {
|
|
312
|
+
await new Promise(resolve => setTimeout(resolve, retryDelay));
|
|
313
|
+
}
|
|
314
|
+
} else {
|
|
315
|
+
// 重试次数用尽
|
|
316
|
+
logger.error(`[insertBatch] 批次 ${batch.index + 1} 重试失败,已达最大重试次数`, {
|
|
317
|
+
error: error.message,
|
|
318
|
+
attempts,
|
|
319
|
+
batchIndex: batch.index
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// 所有重试都失败
|
|
326
|
+
return {
|
|
327
|
+
success: false,
|
|
328
|
+
batch,
|
|
329
|
+
error: lastError,
|
|
330
|
+
attempts
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* 串行执行批次插入
|
|
336
|
+
*/
|
|
337
|
+
async function executeSequential(batches, result, insertOptions, onProgress, retryContext) {
|
|
338
|
+
for (const batch of batches) {
|
|
339
|
+
const batchResult = await executeBatchWithRetry(batch, insertOptions, retryContext);
|
|
340
|
+
|
|
341
|
+
if (batchResult.success) {
|
|
342
|
+
// 更新结果
|
|
343
|
+
result.insertedCount += batchResult.result.insertedCount;
|
|
344
|
+
|
|
345
|
+
// 合并 insertedIds
|
|
346
|
+
if (batchResult.result.insertedIds) {
|
|
347
|
+
for (const [localIndex, id] of Object.entries(batchResult.result.insertedIds)) {
|
|
348
|
+
const globalIndex = batch.startIndex + parseInt(localIndex);
|
|
349
|
+
result.insertedIds[globalIndex] = id;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// 记录重试信息
|
|
354
|
+
if (batchResult.attempts > 0) {
|
|
355
|
+
result.retries.push({
|
|
356
|
+
batchIndex: batch.index,
|
|
357
|
+
attempts: batchResult.attempts,
|
|
358
|
+
success: true
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
} else {
|
|
363
|
+
const errorInfo = {
|
|
364
|
+
batchIndex: batch.index,
|
|
365
|
+
batchStartIndex: batch.startIndex,
|
|
366
|
+
batchSize: batch.documents.length,
|
|
367
|
+
error: batchResult.error,
|
|
368
|
+
code: batchResult.error.code,
|
|
369
|
+
message: batchResult.error.message,
|
|
370
|
+
attempts: batchResult.attempts
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
result.errors.push(errorInfo);
|
|
374
|
+
|
|
375
|
+
// 记录重试信息
|
|
376
|
+
if (batchResult.attempts > 1) {
|
|
377
|
+
result.retries.push({
|
|
378
|
+
batchIndex: batch.index,
|
|
379
|
+
attempts: batchResult.attempts,
|
|
380
|
+
success: false
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// 根据错误策略处理
|
|
385
|
+
if (retryContext.onError === "stop") {
|
|
386
|
+
throw batchResult.error;
|
|
387
|
+
} else if (retryContext.onError === "skip" || retryContext.onError === "retry") {
|
|
388
|
+
retryContext.logger.warn(`[insertBatch] 跳过失败批次 ${batch.index + 1}/${batches.length}`, errorInfo);
|
|
389
|
+
} else if (retryContext.onError === "collect") {
|
|
390
|
+
retryContext.logger.warn(`[insertBatch] 收集错误,继续执行 ${batch.index + 1}/${batches.length}`, errorInfo);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// 触发进度回调
|
|
395
|
+
if (onProgress) {
|
|
396
|
+
onProgress({
|
|
397
|
+
currentBatch: batch.index + 1,
|
|
398
|
+
totalBatches: batches.length,
|
|
399
|
+
inserted: result.insertedCount,
|
|
400
|
+
total: result.totalCount,
|
|
401
|
+
percentage: Math.round((result.insertedCount / result.totalCount) * 100),
|
|
402
|
+
errors: result.errors.length,
|
|
403
|
+
retries: result.retries.length
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* 并发执行批次插入
|
|
411
|
+
*/
|
|
412
|
+
async function executeConcurrent(batches, result, insertOptions, onProgress, concurrency, retryContext) {
|
|
413
|
+
const executing = [];
|
|
414
|
+
const results = [];
|
|
415
|
+
|
|
416
|
+
for (let i = 0; i < batches.length; i++) {
|
|
417
|
+
const batch = batches[i];
|
|
418
|
+
|
|
419
|
+
const promise = executeBatchWithRetry(batch, insertOptions, retryContext);
|
|
420
|
+
|
|
421
|
+
results.push(promise);
|
|
422
|
+
executing.push(promise);
|
|
423
|
+
|
|
424
|
+
// 控制并发数量
|
|
425
|
+
if (executing.length >= concurrency) {
|
|
426
|
+
await Promise.race(executing);
|
|
427
|
+
executing.splice(0, executing.findIndex(p => p === promise) + 1);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// 等待当前批次
|
|
431
|
+
const batchResult = await promise;
|
|
432
|
+
|
|
433
|
+
// 更新结果
|
|
434
|
+
if (batchResult.success) {
|
|
435
|
+
result.insertedCount += batchResult.result.insertedCount;
|
|
436
|
+
|
|
437
|
+
if (batchResult.result.insertedIds) {
|
|
438
|
+
for (const [localIndex, id] of Object.entries(batchResult.result.insertedIds)) {
|
|
439
|
+
const globalIndex = batch.startIndex + parseInt(localIndex);
|
|
440
|
+
result.insertedIds[globalIndex] = id;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
if (batchResult.attempts > 0) {
|
|
445
|
+
result.retries.push({
|
|
446
|
+
batchIndex: batch.index,
|
|
447
|
+
attempts: batchResult.attempts,
|
|
448
|
+
success: true
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
} else {
|
|
452
|
+
const errorInfo = {
|
|
453
|
+
batchIndex: batch.index,
|
|
454
|
+
batchStartIndex: batch.startIndex,
|
|
455
|
+
batchSize: batch.documents.length,
|
|
456
|
+
error: batchResult.error,
|
|
457
|
+
code: batchResult.error.code,
|
|
458
|
+
message: batchResult.error.message,
|
|
459
|
+
attempts: batchResult.attempts
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
result.errors.push(errorInfo);
|
|
463
|
+
|
|
464
|
+
if (batchResult.attempts > 1) {
|
|
465
|
+
result.retries.push({
|
|
466
|
+
batchIndex: batch.index,
|
|
467
|
+
attempts: batchResult.attempts,
|
|
468
|
+
success: false
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
if (retryContext.onError === "stop") {
|
|
473
|
+
throw batchResult.error;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// 触发进度回调
|
|
478
|
+
if (onProgress) {
|
|
479
|
+
onProgress({
|
|
480
|
+
currentBatch: i + 1,
|
|
481
|
+
totalBatches: batches.length,
|
|
482
|
+
inserted: result.insertedCount,
|
|
483
|
+
total: result.totalCount,
|
|
484
|
+
percentage: Math.round((result.insertedCount / result.totalCount) * 100),
|
|
485
|
+
errors: result.errors.length,
|
|
486
|
+
retries: result.retries.length
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
await Promise.all(results);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
return { insertBatch };
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
module.exports = { createInsertBatchOps };
|
|
498
|
+
|