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