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,565 @@
|
|
|
1
|
+
// find-page.js
|
|
2
|
+
// 统一的 findPage 实现:支持 after/before 游标、page 跳页(书签+少量 hops)、
|
|
3
|
+
// 可选 offset 兜底与 totals(none|async|sync|approx 占位)。
|
|
4
|
+
|
|
5
|
+
const crypto = require('crypto');
|
|
6
|
+
const { ErrorCodes, createError } = require('../../errors');
|
|
7
|
+
const { CACHE, PAGINATION } = require('../../constants');
|
|
8
|
+
const { ensureStableSort, reverseSort, pickAnchor } = require('../common/sort');
|
|
9
|
+
const { buildPagePipelineA } = require('../common/agg-pipeline');
|
|
10
|
+
const { decodeCursor } = require('../../common/cursor');
|
|
11
|
+
const { validateLimitAfterBefore, assertCursorSortCompatible } = require('../../common/validation');
|
|
12
|
+
const { makePageResult } = require('../../common/page-result');
|
|
13
|
+
const { normalizeSort } = require('../../common/normalize');
|
|
14
|
+
|
|
15
|
+
// —— Count 队列支持(高并发控制)——
|
|
16
|
+
let countQueue = null;
|
|
17
|
+
|
|
18
|
+
function getCountQueue(ctx) {
|
|
19
|
+
if (!countQueue && ctx.countQueue?.enabled) {
|
|
20
|
+
const CountQueue = require('../../count-queue');
|
|
21
|
+
countQueue = new CountQueue(ctx.countQueue);
|
|
22
|
+
}
|
|
23
|
+
return countQueue;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// —— 工具:稳定序列化与哈希 ——
|
|
27
|
+
function deepStableStringify(x) {
|
|
28
|
+
if (x === null || x === undefined) return 'null';
|
|
29
|
+
if (Array.isArray(x)) {
|
|
30
|
+
return `[${x.map(deepStableStringify).join(',')}]`;
|
|
31
|
+
}
|
|
32
|
+
if (typeof x === 'object') {
|
|
33
|
+
const keys = Object.keys(x).sort();
|
|
34
|
+
const entries = keys.map(k => `${JSON.stringify(k)}:${deepStableStringify(x[k])}`);
|
|
35
|
+
return `{${entries.join(',')}}`;
|
|
36
|
+
}
|
|
37
|
+
// primitives
|
|
38
|
+
return JSON.stringify(x);
|
|
39
|
+
}
|
|
40
|
+
const stableStringify = (o) => deepStableStringify(o);
|
|
41
|
+
const hash = (x) => crypto.createHash('sha256').update(String(x)).digest('hex');
|
|
42
|
+
|
|
43
|
+
// —— 去敏形状 ——
|
|
44
|
+
function shapeOfQuery(q) {
|
|
45
|
+
// 操作符/层级感知的去敏形状(不含具体值)
|
|
46
|
+
function walk(o, path = [], acc = []) {
|
|
47
|
+
if (!o || typeof o !== 'object') return acc;
|
|
48
|
+
const keys = Object.keys(o).sort();
|
|
49
|
+
for (const k of keys) {
|
|
50
|
+
const isOp = k.startsWith('$');
|
|
51
|
+
const key = isOp ? `$${k.slice(1)}` : k;
|
|
52
|
+
acc.push([...path, key].join('.'));
|
|
53
|
+
const v = o[k];
|
|
54
|
+
if (v && typeof v === 'object') walk(v, [...path, key], acc);
|
|
55
|
+
}
|
|
56
|
+
return acc;
|
|
57
|
+
}
|
|
58
|
+
return hash(JSON.stringify(walk(q)));
|
|
59
|
+
}
|
|
60
|
+
function shapeOfPipeline(p) {
|
|
61
|
+
// 记录阶段算子序列 + 顶层字段名集合(仍去敏)
|
|
62
|
+
const seq = (p || []).map(stage => {
|
|
63
|
+
const op = Object.keys(stage)[0];
|
|
64
|
+
const body = stage[op];
|
|
65
|
+
const keys = body && typeof body === 'object' ? Object.keys(body).sort() : [];
|
|
66
|
+
return { op, keys };
|
|
67
|
+
});
|
|
68
|
+
return hash(JSON.stringify(seq));
|
|
69
|
+
}
|
|
70
|
+
function buildKeyDimsAuto({ db, coll, sort, limit, query, pipeline }) {
|
|
71
|
+
return { db, coll, sort, limit, queryShape: shapeOfQuery(query), pipelineShape: shapeOfPipeline(pipeline) };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// —— 键构造 ——
|
|
75
|
+
function bookmarkKey(ns, keyDims) {
|
|
76
|
+
const payload = { db: keyDims.db, coll: keyDims.coll, sort: keyDims.sort, limit: keyDims.limit, q: keyDims.queryShape, p: keyDims.pipelineShape };
|
|
77
|
+
return `${ns}:bm:${hash(stableStringify(payload))}`;
|
|
78
|
+
}
|
|
79
|
+
function totalsKey(ns, keyDims) {
|
|
80
|
+
const payload = { db: keyDims.db, coll: keyDims.coll, sort: keyDims.sort, limit: keyDims.limit, q: keyDims.queryShape, p: keyDims.pipelineShape };
|
|
81
|
+
return `${ns}:tot:${hash(stableStringify(payload))}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// —— totals inflight 去重(窗口时间见 CACHE.TOTALS_INFLIGHT_WINDOW_MS) ——
|
|
85
|
+
const __totalsInflight = new Map(); // key -> { p: Promise, t0: number }
|
|
86
|
+
function withTotalsInflight(key, fn) {
|
|
87
|
+
const now = Date.now();
|
|
88
|
+
const hit = __totalsInflight.get(key);
|
|
89
|
+
if (hit && now - hit.t0 < CACHE.TOTALS_INFLIGHT_WINDOW_MS) return hit.p;
|
|
90
|
+
const p = (async () => {
|
|
91
|
+
try { return await fn(); }
|
|
92
|
+
finally { __totalsInflight.delete(key); }
|
|
93
|
+
})();
|
|
94
|
+
__totalsInflight.set(key, { p, t0: now });
|
|
95
|
+
return p;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function bmGet(cache, ns, keyDims, page) {
|
|
99
|
+
const key = `${bookmarkKey(ns, keyDims)}:${page}`;
|
|
100
|
+
const cursor = cache?.get ? (await cache.get(key)) : null;
|
|
101
|
+
// 验证游标是否有效
|
|
102
|
+
if (cursor && typeof cursor === 'string' && cursor.length > 0) {
|
|
103
|
+
return cursor;
|
|
104
|
+
}
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
async function bmSet(cache, ns, keyDims, page, cursor, ttlMs) {
|
|
108
|
+
const key = `${bookmarkKey(ns, keyDims)}:${page}`;
|
|
109
|
+
if (cache?.set) await cache.set(key, cursor, ttlMs);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// totals 计算 + 缓存:失败也写入 total:null(语义统一),并附加 error 字段
|
|
113
|
+
async function computeAndCacheTotal({ collection, cache, ns, keyDims, query, limit, hint, collation, maxTimeMS, ttlMs, logger, countQueue }) {
|
|
114
|
+
const key = totalsKey(ns, keyDims);
|
|
115
|
+
try {
|
|
116
|
+
let total;
|
|
117
|
+
|
|
118
|
+
// 使用队列控制并发(避免高并发下压垮数据库)
|
|
119
|
+
if (countQueue) {
|
|
120
|
+
total = await countQueue.execute(() =>
|
|
121
|
+
collection.countDocuments(query || {}, {
|
|
122
|
+
maxTimeMS,
|
|
123
|
+
...(hint ? { hint } : {}),
|
|
124
|
+
...(collation ? { collation } : {})
|
|
125
|
+
})
|
|
126
|
+
);
|
|
127
|
+
} else {
|
|
128
|
+
// 无队列,直接执行(不推荐用于生产环境)
|
|
129
|
+
total = await collection.countDocuments(query || {}, {
|
|
130
|
+
maxTimeMS,
|
|
131
|
+
...(hint ? { hint } : {}),
|
|
132
|
+
...(collation ? { collation } : {})
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const totalPages = Math.ceil(total / Math.max(1, limit || 1));
|
|
137
|
+
const payload = { total, totalPages, ts: Date.now() };
|
|
138
|
+
if (cache?.set) await cache.set(key, payload, ttlMs);
|
|
139
|
+
return payload;
|
|
140
|
+
} catch (e) {
|
|
141
|
+
// 失败:保持 async 语义一致,写入 total:null,并记录一次 warn(去敏)
|
|
142
|
+
try { logger && logger.warn && logger.warn('totals.count.failed', { ns, reason: String(e && (e.message || e)) }); } catch (_) { }
|
|
143
|
+
const payload = { total: null, totalPages: null, ts: Date.now(), error: 'count_failed' };
|
|
144
|
+
if (cache?.set) await cache.set(key, payload, ttlMs);
|
|
145
|
+
return payload;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function makeJumpTooFarError({ remaining, maxHops }) {
|
|
150
|
+
return createError(
|
|
151
|
+
ErrorCodes.JUMP_TOO_FAR,
|
|
152
|
+
'跳页跨度过大,maxHops 限制触发',
|
|
153
|
+
[{ path: ['page'], message: `remaining=${remaining}, maxHops=${maxHops}` }]
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function createFindPage(ctx) {
|
|
158
|
+
const { collection, getCache, getNamespace, defaults, logger, run } = ctx;
|
|
159
|
+
|
|
160
|
+
async function doFindPageOne({ options, stableSort, direction, parsedCursor }) {
|
|
161
|
+
const sortForQuery = direction === 'before' ? reverseSort(stableSort) : stableSort;
|
|
162
|
+
const pipeline = buildPagePipelineA({
|
|
163
|
+
query: options.query || {},
|
|
164
|
+
sort: sortForQuery,
|
|
165
|
+
limit: options.limit,
|
|
166
|
+
cursor: parsedCursor,
|
|
167
|
+
direction,
|
|
168
|
+
lookupPipeline: options.pipeline || []
|
|
169
|
+
});
|
|
170
|
+
const driverOpts = {
|
|
171
|
+
maxTimeMS: options.maxTimeMS ?? defaults.maxTimeMS,
|
|
172
|
+
allowDiskUse: options.allowDiskUse,
|
|
173
|
+
...(options.hint ? { hint: options.hint } : {}),
|
|
174
|
+
...(options.collation ? { collation: options.collation } : {}),
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
// 如果启用 explain,直接返回执行计划(不缓存,不进行分页处理)
|
|
178
|
+
if (options.explain) {
|
|
179
|
+
const verbosity = typeof options.explain === 'string' ? options.explain : 'queryPlanner';
|
|
180
|
+
const aggCursor = collection.aggregate(pipeline, driverOpts);
|
|
181
|
+
return await aggCursor.explain(verbosity);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// 如果启用流式返回
|
|
185
|
+
if (options.stream) {
|
|
186
|
+
if (options.batchSize !== undefined) driverOpts.batchSize = options.batchSize;
|
|
187
|
+
// 流式查询:��应该用 limit+1,直接使用 limit
|
|
188
|
+
const streamPipeline = buildPagePipelineA({
|
|
189
|
+
query: options.query || {},
|
|
190
|
+
sort: sortForQuery,
|
|
191
|
+
limit: options.limit, // 注意:这里不加1
|
|
192
|
+
cursor: parsedCursor,
|
|
193
|
+
direction,
|
|
194
|
+
lookupPipeline: options.pipeline || []
|
|
195
|
+
});
|
|
196
|
+
// 手动修改最后的 $limit 阶段,不使用 limit+1
|
|
197
|
+
const limitStageIndex = streamPipeline.findIndex(stage => stage.$limit !== undefined);
|
|
198
|
+
if (limitStageIndex >= 0) {
|
|
199
|
+
streamPipeline[limitStageIndex] = { $limit: options.limit };
|
|
200
|
+
}
|
|
201
|
+
return collection.aggregate(streamPipeline, driverOpts).stream();
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const rows = await (run ? run('findPage', options, () => collection.aggregate(pipeline, driverOpts).toArray()) : collection.aggregate(pipeline, driverOpts).toArray());
|
|
205
|
+
return makePageResult(rows, {
|
|
206
|
+
limit: options.limit,
|
|
207
|
+
stableSort,
|
|
208
|
+
direction,
|
|
209
|
+
hasCursor: !!parsedCursor,
|
|
210
|
+
pickAnchor,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return async function findPage(options = {}) {
|
|
215
|
+
const startTime = Date.now(); // 记录开始时间
|
|
216
|
+
const MAX_LIMIT = defaults?.findPageMaxLimit ?? 500;
|
|
217
|
+
// 基础校验:limit + after/before 互斥
|
|
218
|
+
validateLimitAfterBefore(options, { maxLimit: MAX_LIMIT });
|
|
219
|
+
|
|
220
|
+
// 如果启用流式模式,只支持简单的游标分页(after/before)或首页查询
|
|
221
|
+
// 不支持跳页和 totals 等复杂功能
|
|
222
|
+
if (options.stream) {
|
|
223
|
+
const { after, before, page } = options;
|
|
224
|
+
|
|
225
|
+
// 流式模式不支持跳页
|
|
226
|
+
if (Number.isInteger(page) && page > 1) {
|
|
227
|
+
throw createError(
|
|
228
|
+
ErrorCodes.STREAM_NO_JUMP,
|
|
229
|
+
'流式模式不支持跳页功能,请使用 after/before 游标分页'
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// 流式模式不支持 totals
|
|
234
|
+
if (options.totals?.mode && options.totals.mode !== 'none') {
|
|
235
|
+
throw createError(
|
|
236
|
+
ErrorCodes.STREAM_NO_TOTALS,
|
|
237
|
+
'流式模式不支持 totals 统计'
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// 流式模式不支持 explain
|
|
242
|
+
if (options.explain) {
|
|
243
|
+
throw createError(
|
|
244
|
+
ErrorCodes.STREAM_NO_EXPLAIN,
|
|
245
|
+
'流式模式不支持 explain 分析,请使用普通分页模式'
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const { sort } = options;
|
|
250
|
+
const stableSort = ensureStableSort(normalizeSort(sort) || { _id: 1 });
|
|
251
|
+
|
|
252
|
+
if (after || before) {
|
|
253
|
+
const parsedCursor = decodeCursor(after || before);
|
|
254
|
+
assertCursorSortCompatible(stableSort, parsedCursor && parsedCursor.s);
|
|
255
|
+
return doFindPageOne({
|
|
256
|
+
options,
|
|
257
|
+
stableSort,
|
|
258
|
+
direction: after ? 'after' : 'before',
|
|
259
|
+
parsedCursor
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// 首页流式查询
|
|
264
|
+
return doFindPageOne({
|
|
265
|
+
options,
|
|
266
|
+
stableSort,
|
|
267
|
+
direction: null,
|
|
268
|
+
parsedCursor: null
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// 如果启用 explain,直接返回执行计划(简化流程)
|
|
273
|
+
if (options.explain) {
|
|
274
|
+
const { sort } = options;
|
|
275
|
+
const stableSort = ensureStableSort(normalizeSort(sort) || { _id: 1 });
|
|
276
|
+
const parsedCursor = options.after ? decodeCursor(options.after) : options.before ? decodeCursor(options.before) : null;
|
|
277
|
+
const direction = options.after ? 'after' : options.before ? 'before' : null;
|
|
278
|
+
return await doFindPageOne({ options, stableSort, direction, parsedCursor });
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// 解析上下文
|
|
282
|
+
const cache = getCache && getCache();
|
|
283
|
+
const nsObj = getNamespace && getNamespace();
|
|
284
|
+
const ns = nsObj?.ns || `${defaults?.iid || ''}:${defaults?.type || ''}:${ctx.databaseName || ''}:${ctx.collectionName || ''}`;
|
|
285
|
+
|
|
286
|
+
const {
|
|
287
|
+
query = {},
|
|
288
|
+
pipeline: lookupPipeline = [],
|
|
289
|
+
sort,
|
|
290
|
+
limit,
|
|
291
|
+
after,
|
|
292
|
+
before,
|
|
293
|
+
page,
|
|
294
|
+
} = options;
|
|
295
|
+
|
|
296
|
+
// 互斥校验:page 与 after/before 不能同时出现
|
|
297
|
+
if ((after || before) && Number.isInteger(page)) {
|
|
298
|
+
const err = new Error('参数校验失败');
|
|
299
|
+
err.code = 'VALIDATION_ERROR';
|
|
300
|
+
err.details = [{ path: ['page'], type: 'any.conflict', message: 'page 与 after/before 互斥' }];
|
|
301
|
+
throw err;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const stableSort = ensureStableSort(normalizeSort(sort) || { _id: 1 });
|
|
305
|
+
|
|
306
|
+
// 辅助函数:添加 meta 信息
|
|
307
|
+
const attachMeta = (result) => {
|
|
308
|
+
if (options.meta) {
|
|
309
|
+
result.meta = {
|
|
310
|
+
op: 'findPage',
|
|
311
|
+
durationMs: Date.now() - startTime,
|
|
312
|
+
cacheHit: false
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
return result;
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
// 1) after/before:现有路径
|
|
319
|
+
if (after || before) {
|
|
320
|
+
const parsedCursor = decodeCursor(after || before);
|
|
321
|
+
assertCursorSortCompatible(stableSort, parsedCursor && parsedCursor.s);
|
|
322
|
+
const result = await doFindPageOne({ options, stableSort, direction: after ? 'after' : 'before', parsedCursor });
|
|
323
|
+
|
|
324
|
+
// 为游标分页添加 totals 支持
|
|
325
|
+
if (options.totals && options.totals.mode && options.totals.mode !== 'none') {
|
|
326
|
+
const keyDims = buildKeyDimsAuto({
|
|
327
|
+
db: ctx.databaseName,
|
|
328
|
+
coll: ctx.collectionName,
|
|
329
|
+
sort: stableSort,
|
|
330
|
+
limit,
|
|
331
|
+
query,
|
|
332
|
+
pipeline: lookupPipeline,
|
|
333
|
+
});
|
|
334
|
+
const out = await attachTotals({ collection, cache, ns, keyDims, limit, query, totals: options.totals, ctx });
|
|
335
|
+
result.totals = out;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
return attachMeta(result);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// 2) 无 page:首页
|
|
342
|
+
if (!Number.isInteger(page) || page < 1) {
|
|
343
|
+
const result = await doFindPageOne({ options, stableSort, direction: null, parsedCursor: null });
|
|
344
|
+
|
|
345
|
+
// 为首页添加 totals 支持
|
|
346
|
+
if (options.totals && options.totals.mode && options.totals.mode !== 'none') {
|
|
347
|
+
const keyDims = buildKeyDimsAuto({
|
|
348
|
+
db: ctx.databaseName,
|
|
349
|
+
coll: ctx.collectionName,
|
|
350
|
+
sort: stableSort,
|
|
351
|
+
limit,
|
|
352
|
+
query,
|
|
353
|
+
pipeline: lookupPipeline,
|
|
354
|
+
});
|
|
355
|
+
const out = await attachTotals({ collection, cache, ns, keyDims, limit, query, totals: options.totals, ctx });
|
|
356
|
+
result.totals = out;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
return attachMeta(result);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// —— 跳页模式 ——
|
|
363
|
+
const step = Number.isInteger(options.jump?.step) ? options.jump.step : (defaults?.bookmarks?.step ?? 10);
|
|
364
|
+
const maxHops = Number.isInteger(options.jump?.maxHops) ? options.jump.maxHops : (defaults?.bookmarks?.maxHops ?? 20);
|
|
365
|
+
const ttlMs = defaults?.bookmarks?.ttlMs ?? 6 * 3600_000;
|
|
366
|
+
const maxBookmarkPages = defaults?.bookmarks?.maxPages ?? 10000;
|
|
367
|
+
|
|
368
|
+
// 自动 keyDims
|
|
369
|
+
const keyDims = options.jump?.keyDims || buildKeyDimsAuto({
|
|
370
|
+
db: ctx.databaseName,
|
|
371
|
+
coll: ctx.collectionName,
|
|
372
|
+
sort: stableSort,
|
|
373
|
+
limit,
|
|
374
|
+
query,
|
|
375
|
+
pipeline: lookupPipeline,
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
// 2.1 可选:offset 兜底
|
|
379
|
+
if (options.offsetJump?.enable) {
|
|
380
|
+
const skip = (page - 1) * limit;
|
|
381
|
+
const maxSkip = options.offsetJump.maxSkip ?? 50_000;
|
|
382
|
+
if (skip <= maxSkip) {
|
|
383
|
+
const p = [];
|
|
384
|
+
if (query && Object.keys(query).length) p.push({ $match: query });
|
|
385
|
+
p.push({ $sort: stableSort }, { $skip: skip }, { $limit: limit + 1 });
|
|
386
|
+
if (lookupPipeline?.length) p.push(...lookupPipeline);
|
|
387
|
+
const driverOpts = {
|
|
388
|
+
maxTimeMS: options.maxTimeMS ?? defaults.maxTimeMS,
|
|
389
|
+
allowDiskUse: options.allowDiskUse,
|
|
390
|
+
...(options.hint ? { hint: options.hint } : {}),
|
|
391
|
+
...(options.collation ? { collation: options.collation } : {}),
|
|
392
|
+
};
|
|
393
|
+
const rows = await (run ? run('findPage', options, () => collection.aggregate(p, driverOpts).toArray()) : collection.aggregate(p, driverOpts).toArray());
|
|
394
|
+
const res = makePageResult(rows, { limit, stableSort, direction: null, hasCursor: false, pickAnchor });
|
|
395
|
+
if (res.pageInfo?.endCursor && page <= maxBookmarkPages) await bmSet(cache, ns, keyDims, page, res.pageInfo.endCursor, ttlMs);
|
|
396
|
+
if (res.pageInfo) res.pageInfo.currentPage = page;
|
|
397
|
+
// totals(可选)
|
|
398
|
+
if (options.totals && options.totals.mode && options.totals.mode !== 'none') {
|
|
399
|
+
const out = await attachTotals({ collection, cache, ns, keyDims, limit, query, totals: options.totals, ctx });
|
|
400
|
+
res.totals = out;
|
|
401
|
+
}
|
|
402
|
+
return attachMeta(res);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// 2.2 书签跳转
|
|
407
|
+
const pageIndex = page - 1;
|
|
408
|
+
const anchorPage = Math.floor(pageIndex / step) * step; // 0, step, 2*step, ...
|
|
409
|
+
const remaining = pageIndex - anchorPage; // 0..(step-1)
|
|
410
|
+
|
|
411
|
+
let current = null;
|
|
412
|
+
if (anchorPage > 0) {
|
|
413
|
+
const anchorCursor = await bmGet(cache, ns, keyDims, anchorPage);
|
|
414
|
+
if (anchorCursor) {
|
|
415
|
+
// 修复:从缓存获取书签后,需要构造完整的结果对象
|
|
416
|
+
// 直接使用游标进行查询以获取该页的数据
|
|
417
|
+
try {
|
|
418
|
+
const parsedAnchor = decodeCursor(anchorCursor);
|
|
419
|
+
current = await doFindPageOne({
|
|
420
|
+
options: { ...options, after: anchorCursor },
|
|
421
|
+
stableSort,
|
|
422
|
+
direction: 'after',
|
|
423
|
+
parsedCursor: parsedAnchor
|
|
424
|
+
});
|
|
425
|
+
// 保存当前页的游标,用于后续跳转
|
|
426
|
+
if (current.pageInfo?.endCursor && (anchorPage + 1) <= maxBookmarkPages) {
|
|
427
|
+
await bmSet(cache, ns, keyDims, anchorPage + 1, current.pageInfo.endCursor, ttlMs);
|
|
428
|
+
}
|
|
429
|
+
} catch (e) {
|
|
430
|
+
// 如果书签游标失效,重置 current,从头开始
|
|
431
|
+
current = null;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// 累计 hops 计数:限制"整次跳页"的连续 after 次数总和不超过 maxHops
|
|
437
|
+
let hops = 0;
|
|
438
|
+
|
|
439
|
+
if (!current) {
|
|
440
|
+
current = await doFindPageOne({ options, stableSort, direction: null, parsedCursor: null });
|
|
441
|
+
if (current.pageInfo?.endCursor && 1 <= maxBookmarkPages) await bmSet(cache, ns, keyDims, 1, current.pageInfo.endCursor, ttlMs);
|
|
442
|
+
for (let i = 1; i < anchorPage; i++) {
|
|
443
|
+
hops += 1; if (hops > maxHops) throw makeJumpTooFarError({ remaining: anchorPage - i, maxHops });
|
|
444
|
+
if (!current.pageInfo?.endCursor) break; // 没有更多数据
|
|
445
|
+
current = await doFindPageOne({
|
|
446
|
+
options: { ...options, after: current.pageInfo.endCursor },
|
|
447
|
+
stableSort,
|
|
448
|
+
direction: 'after',
|
|
449
|
+
parsedCursor: decodeCursor(current.pageInfo.endCursor)
|
|
450
|
+
});
|
|
451
|
+
const pNo = i + 1;
|
|
452
|
+
if (pNo % step === 0 && pNo <= maxBookmarkPages && current.pageInfo?.endCursor) await bmSet(cache, ns, keyDims, pNo, current.pageInfo.endCursor, ttlMs);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
for (let i = 0; i < remaining; i++) {
|
|
457
|
+
hops += 1; if (hops > maxHops) throw makeJumpTooFarError({ remaining: remaining - i, maxHops });
|
|
458
|
+
if (!current?.pageInfo?.endCursor) break; // 没有更多数据
|
|
459
|
+
current = await doFindPageOne({
|
|
460
|
+
options: { ...options, after: current.pageInfo.endCursor },
|
|
461
|
+
stableSort,
|
|
462
|
+
direction: 'after',
|
|
463
|
+
parsedCursor: decodeCursor(current.pageInfo.endCursor)
|
|
464
|
+
});
|
|
465
|
+
const pNo = anchorPage + 1 + i + 1;
|
|
466
|
+
if (pNo % step === 0 && pNo <= maxBookmarkPages && current.pageInfo?.endCursor) await bmSet(cache, ns, keyDims, pNo, current.pageInfo.endCursor, ttlMs);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
if (current?.pageInfo) current.pageInfo.currentPage = page;
|
|
470
|
+
|
|
471
|
+
// totals(可选)
|
|
472
|
+
if (options.totals && options.totals.mode && options.totals.mode !== 'none') {
|
|
473
|
+
const out = await attachTotals({ collection, cache, ns, keyDims, limit, query, totals: options.totals, ctx });
|
|
474
|
+
current.totals = out;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
return attachMeta(current);
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
// totals 附加逻辑:支持 sync/async/approx;async 返回短 token(keyHash),避免暴露命名空间
|
|
481
|
+
async function attachTotals({ collection, cache, ns, keyDims, limit, query, totals, ctx }) {
|
|
482
|
+
const mode = totals.mode || 'none';
|
|
483
|
+
const ttlMs = totals.ttlMs ?? 10 * 60_000;
|
|
484
|
+
const key = totalsKey(ns, keyDims);
|
|
485
|
+
const keyHash = key.split(':').pop(); // 仅最后一段哈希作为对外 token
|
|
486
|
+
|
|
487
|
+
// 获取 count 队列
|
|
488
|
+
const queue = getCountQueue(ctx);
|
|
489
|
+
|
|
490
|
+
if (mode === 'sync') {
|
|
491
|
+
const result = await computeAndCacheTotal({
|
|
492
|
+
collection, cache, ns, keyDims, query, limit,
|
|
493
|
+
hint: totals.hint,
|
|
494
|
+
collation: totals.collation,
|
|
495
|
+
maxTimeMS: totals.maxTimeMS ?? 2000,
|
|
496
|
+
ttlMs,
|
|
497
|
+
logger,
|
|
498
|
+
countQueue: queue // ← 传递队列
|
|
499
|
+
});
|
|
500
|
+
return { mode: 'sync', ...result };
|
|
501
|
+
} else if (mode === 'async') {
|
|
502
|
+
const cached = cache?.get ? await cache.get(key) : null;
|
|
503
|
+
if (cached) return { mode: 'async', ...cached, token: keyHash };
|
|
504
|
+
// 触发异步计算(去重 + 微任务队列)
|
|
505
|
+
const doAsync = () => withTotalsInflight(key, () => computeAndCacheTotal({
|
|
506
|
+
collection, cache, ns, keyDims, query, limit,
|
|
507
|
+
hint: totals.hint,
|
|
508
|
+
collation: totals.collation,
|
|
509
|
+
maxTimeMS: totals.maxTimeMS ?? 2000,
|
|
510
|
+
ttlMs,
|
|
511
|
+
logger,
|
|
512
|
+
countQueue: queue // ← 传递队列
|
|
513
|
+
})).catch(() => { });
|
|
514
|
+
if (typeof queueMicrotask === 'function') queueMicrotask(doAsync); else setTimeout(doAsync, 0);
|
|
515
|
+
return { mode: 'async', total: null, totalPages: null, token: keyHash };
|
|
516
|
+
} else if (mode === 'approx') {
|
|
517
|
+
// 近似:使用 estimatedDocumentCount(基于元数据,速度快但不考虑查询条件)
|
|
518
|
+
const cached = cache?.get ? await cache.get(key) : null;
|
|
519
|
+
if (cached) return { mode: 'approx', ...cached, approx: true };
|
|
520
|
+
|
|
521
|
+
try {
|
|
522
|
+
// 如果有查询条件,使用 countDocuments(精确但可能慢)
|
|
523
|
+
// 如果是空查询,使用 estimatedDocumentCount(快速但近似)
|
|
524
|
+
let total;
|
|
525
|
+
if (query && Object.keys(query).length > 0) {
|
|
526
|
+
// 有查询条件,使用精确统计(需要队列控制)
|
|
527
|
+
if (queue) {
|
|
528
|
+
total = await queue.execute(() =>
|
|
529
|
+
collection.countDocuments(query, {
|
|
530
|
+
maxTimeMS: totals.maxTimeMS ?? 2000,
|
|
531
|
+
...(totals.hint ? { hint: totals.hint } : {}),
|
|
532
|
+
...(totals.collation ? { collation: totals.collation } : {})
|
|
533
|
+
})
|
|
534
|
+
);
|
|
535
|
+
} else {
|
|
536
|
+
total = await collection.countDocuments(query, {
|
|
537
|
+
maxTimeMS: totals.maxTimeMS ?? 2000,
|
|
538
|
+
...(totals.hint ? { hint: totals.hint } : {}),
|
|
539
|
+
...(totals.collation ? { collation } : {})
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
} else {
|
|
543
|
+
// 空查询,使用快速近似统计(不需要队列,速度很快)
|
|
544
|
+
total = await collection.estimatedDocumentCount({
|
|
545
|
+
maxTimeMS: totals.maxTimeMS ?? 1000
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
const totalPages = Math.ceil(total / Math.max(1, limit || 1));
|
|
550
|
+
const payload = { total, totalPages, ts: Date.now(), approx: true };
|
|
551
|
+
if (cache?.set) await cache.set(key, payload, ttlMs);
|
|
552
|
+
return { mode: 'approx', ...payload };
|
|
553
|
+
} catch (e) {
|
|
554
|
+
// 失败降级
|
|
555
|
+
try { logger && logger.warn && logger.warn('totals.approx.failed', { ns, reason: String(e && (e.message || e)) }); } catch (_) { }
|
|
556
|
+
const payload = { total: null, totalPages: null, ts: Date.now(), error: 'approx_failed', approx: true };
|
|
557
|
+
if (cache?.set) await cache.set(key, payload, ttlMs);
|
|
558
|
+
return { mode: 'approx', ...payload };
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
return undefined;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
module.exports = { createFindPage, bookmarkKey, buildKeyDimsAuto, shapeOfQuery, shapeOfPipeline };
|