monsqlize 1.1.4 → 1.1.6

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 (148) hide show
  1. package/CHANGELOG.md +98 -2
  2. package/README.md +1 -0
  3. package/index.mjs +52 -0
  4. package/lib/cache-invalidation.js +279 -0
  5. package/lib/cache.js +41 -2
  6. package/lib/common/cursor.js +1 -0
  7. package/lib/common/docs-urls.js +1 -0
  8. package/lib/common/index-options.js +1 -0
  9. package/lib/common/log.js +1 -0
  10. package/lib/common/namespace.js +1 -0
  11. package/lib/common/normalize.js +1 -0
  12. package/lib/common/page-result.js +1 -0
  13. package/lib/common/runner.js +1 -0
  14. package/lib/common/server-features.js +1 -0
  15. package/lib/common/shape-builders.js +1 -0
  16. package/lib/common/validation.js +1 -0
  17. package/lib/connect.js +1 -0
  18. package/lib/constants.js +1 -0
  19. package/lib/count-queue.js +1 -0
  20. package/lib/distributed-cache-invalidator.js +1 -0
  21. package/lib/errors.js +1 -0
  22. package/lib/expression/cache/ExpressionCache.js +1 -0
  23. package/lib/expression/compiler/ExpressionCompiler.js +1 -0
  24. package/lib/expression/compiler/ExpressionCompilerExtensions.js +1 -0
  25. package/lib/expression/detector.js +1 -0
  26. package/lib/expression/factory.js +1 -0
  27. package/lib/expression/index.js +1 -0
  28. package/lib/function-cache.js +80 -56
  29. package/lib/index.js +10 -0
  30. package/lib/infrastructure/ConnectionPoolManager.js +1 -0
  31. package/lib/infrastructure/HealthChecker.js +1 -0
  32. package/lib/infrastructure/PoolConfig.js +1 -0
  33. package/lib/infrastructure/PoolSelector.js +1 -0
  34. package/lib/infrastructure/PoolStats.js +1 -0
  35. package/lib/infrastructure/ssh-tunnel-ssh2.js +1 -0
  36. package/lib/infrastructure/ssh-tunnel.js +1 -0
  37. package/lib/infrastructure/uri-parser.js +1 -0
  38. package/lib/lock/Lock.js +1 -0
  39. package/lib/lock/errors.js +1 -0
  40. package/lib/lock/index.js +1 -0
  41. package/lib/logger.js +1 -0
  42. package/lib/model/examples/test.js +1 -0
  43. package/lib/model/features/defaults.js +1 -0
  44. package/lib/model/features/populate.js +1 -0
  45. package/lib/model/features/relations.js +1 -0
  46. package/lib/model/features/soft-delete.js +1 -0
  47. package/lib/model/features/version.js +1 -0
  48. package/lib/model/features/virtuals.js +1 -0
  49. package/lib/model/index.js +1 -0
  50. package/lib/mongodb/common/accessor-helpers.js +1 -0
  51. package/lib/mongodb/common/agg-pipeline.js +1 -0
  52. package/lib/mongodb/common/aggregation-validator.js +1 -0
  53. package/lib/mongodb/common/iid.js +1 -0
  54. package/lib/mongodb/common/lexicographic-expr.js +1 -0
  55. package/lib/mongodb/common/shape.js +1 -0
  56. package/lib/mongodb/common/sort.js +1 -0
  57. package/lib/mongodb/common/transaction-aware.js +1 -0
  58. package/lib/mongodb/connect.js +1 -0
  59. package/lib/mongodb/index.js +3 -1
  60. package/lib/mongodb/management/admin-ops.js +1 -0
  61. package/lib/mongodb/management/bookmark-ops.js +1 -0
  62. package/lib/mongodb/management/cache-ops.js +1 -0
  63. package/lib/mongodb/management/collection-ops.js +1 -0
  64. package/lib/mongodb/management/database-ops.js +1 -0
  65. package/lib/mongodb/management/index-ops.js +1 -0
  66. package/lib/mongodb/management/index.js +1 -0
  67. package/lib/mongodb/management/namespace.js +1 -0
  68. package/lib/mongodb/management/validation-ops.js +1 -0
  69. package/lib/mongodb/queries/aggregate.js +1 -0
  70. package/lib/mongodb/queries/chain.js +1 -0
  71. package/lib/mongodb/queries/count.js +1 -0
  72. package/lib/mongodb/queries/distinct.js +1 -0
  73. package/lib/mongodb/queries/find-and-count.js +1 -0
  74. package/lib/mongodb/queries/find-by-ids.js +1 -0
  75. package/lib/mongodb/queries/find-one-by-id.js +1 -0
  76. package/lib/mongodb/queries/find-one.js +1 -0
  77. package/lib/mongodb/queries/find-page.js +1 -0
  78. package/lib/mongodb/queries/find.js +1 -0
  79. package/lib/mongodb/queries/index.js +1 -0
  80. package/lib/mongodb/queries/watch.js +1 -0
  81. package/lib/mongodb/writes/common/batch-retry.js +1 -0
  82. package/lib/mongodb/writes/delete-batch.js +1 -0
  83. package/lib/mongodb/writes/delete-many.js +21 -30
  84. package/lib/mongodb/writes/delete-one.js +21 -30
  85. package/lib/mongodb/writes/find-one-and-delete.js +1 -0
  86. package/lib/mongodb/writes/find-one-and-replace.js +1 -0
  87. package/lib/mongodb/writes/find-one-and-update.js +1 -0
  88. package/lib/mongodb/writes/increment-one.js +1 -0
  89. package/lib/mongodb/writes/index.js +1 -0
  90. package/lib/mongodb/writes/insert-batch.js +1 -0
  91. package/lib/mongodb/writes/insert-many.js +26 -30
  92. package/lib/mongodb/writes/insert-one.js +20 -31
  93. package/lib/mongodb/writes/replace-one.js +17 -6
  94. package/lib/mongodb/writes/result-handler.js +1 -0
  95. package/lib/mongodb/writes/update-batch.js +1 -0
  96. package/lib/mongodb/writes/update-many.js +31 -33
  97. package/lib/mongodb/writes/update-one.js +28 -34
  98. package/lib/mongodb/writes/upsert-one.js +22 -25
  99. package/lib/multi-level-cache.js +1 -0
  100. package/lib/operators.js +1 -1
  101. package/lib/redis-cache-adapter.js +1 -0
  102. package/lib/saga/SagaContext.js +1 -0
  103. package/lib/saga/SagaDefinition.js +1 -0
  104. package/lib/saga/SagaExecutor.js +1 -0
  105. package/lib/saga/SagaOrchestrator.js +1 -0
  106. package/lib/saga/index.js +1 -0
  107. package/lib/slow-query-log/base-storage.js +1 -0
  108. package/lib/slow-query-log/batch-queue.js +1 -0
  109. package/lib/slow-query-log/config-manager.js +1 -0
  110. package/lib/slow-query-log/index.js +1 -0
  111. package/lib/slow-query-log/mongodb-storage.js +1 -0
  112. package/lib/slow-query-log/query-hash.js +1 -0
  113. package/lib/sync/ChangeStreamSyncManager.js +1 -0
  114. package/lib/sync/ResumeTokenStore.js +1 -0
  115. package/lib/sync/SyncConfig.js +1 -0
  116. package/lib/sync/SyncTarget.js +1 -0
  117. package/lib/sync/index.js +1 -0
  118. package/lib/transaction/CacheLockManager.js +1 -0
  119. package/lib/transaction/DistributedCacheLockManager.js +1 -0
  120. package/lib/transaction/Transaction.js +1 -0
  121. package/lib/transaction/TransactionManager.js +1 -0
  122. package/lib/transaction/index.js +1 -0
  123. package/lib/utils/objectid-converter.js +1 -0
  124. package/package.json +3 -1
  125. package/types/README.md +122 -0
  126. package/types/base.ts +90 -0
  127. package/types/batch.ts +187 -0
  128. package/types/cache.ts +71 -0
  129. package/types/chain.ts +254 -0
  130. package/types/collection.ts +287 -0
  131. package/types/expression.ts +109 -0
  132. package/types/function-cache.d.ts +135 -0
  133. package/types/lock.ts +95 -0
  134. package/types/model/definition.ts +110 -0
  135. package/types/model/index.ts +10 -0
  136. package/types/model/instance.ts +96 -0
  137. package/types/model/relations.ts +121 -0
  138. package/types/model/virtuals.ts +32 -0
  139. package/types/monsqlize.ts +158 -0
  140. package/types/options.ts +192 -0
  141. package/types/pagination.ts +149 -0
  142. package/types/pool.ts +125 -0
  143. package/types/query.ts +71 -0
  144. package/types/saga.ts +125 -0
  145. package/types/stream.ts +64 -0
  146. package/types/sync.ts +79 -0
  147. package/types/transaction.ts +79 -0
  148. package/types/write.ts +77 -0
package/CHANGELOG.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # 变更日志 (CHANGELOG)
2
2
 
3
3
  > **说明**: 版本概览摘要,详细变更见 [changelogs/](./changelogs/) 目录
4
- > **最后更新**: 2026-02-09
4
+ > **最后更新**: 2026-02-11
5
5
 
6
6
  ---
7
7
 
@@ -9,6 +9,7 @@
9
9
 
10
10
  | 版本 | 日期 | 变更摘要 | 详细 |
11
11
  |------|------|---------|------|
12
+ | [v1.1.6](./changelogs/v1.1.6.md) | 2026-02-11 | 🎉 **重大功能**:精准缓存失效机制 + 🚨 upsert 缓存失效 Bug 修复 + 36个测试 (100%通过) | [查看](./changelogs/v1.1.6.md) |
12
13
  | [v1.1.4](./changelogs/v1.1.4.md) | 2026-02-09 | 🎉 重大功能:通用函数缓存 - 52个测试 (100%通过) + 多层缓存 delPattern 修复 | [查看](./changelogs/v1.1.4.md) |
13
14
  | [v1.1.3](./changelogs/v1.1.3.md) | 2026-02-03 | 📚 文档完善:多连接池文档优化 + 健康检查详解 + 验证体系规范 | [查看](./changelogs/v1.1.3.md) |
14
15
  | [v1.1.2](#v112---日志优化) | 2026-01-27 | 🔧 优化:ObjectId 转换日志默认静默 + Saga 日志修复 | [查看](#v112---日志优化) |
@@ -27,11 +28,106 @@
27
28
 
28
29
  ---
29
30
 
31
+ ## 🚨 重要更新
32
+
33
+ ### v1.1.6 - 精准缓存失效 + 严重 Bug 修复 🎉🔴
34
+
35
+ **发布日期**: 2026-02-11
36
+ **版本类型**: Feature + Critical Bug Fix
37
+ **重要性**: ⭐⭐⭐⭐⭐ **强烈推荐立即升级**
38
+
39
+ #### 🎉 新功能:精准缓存失效机制
40
+
41
+ **核心特性**:
42
+ - ✅ **精准失效**: 只清除受影响查询的缓存(vs 集合级别失效)
43
+ - ✅ **配置灵活**: 实例级别 + 查询级别配置,查询级别优先
44
+ - ✅ **智能跳过**: 自动跳过复杂查询($or、$expr、$regex等)
45
+ - ✅ **性能优化**: 批量删除、命名空间过滤、零拷贝
46
+
47
+ **性能提升**:
48
+ | 指标 | 旧方式 | 新方式 | 提升 |
49
+ |------|--------|--------|------|
50
+ | 缓存失效数量 | 100个 | ~1个 | ↓ 99% |
51
+ | 缓存命中率 | 随机 | 95%+ | ↑ 显著 |
52
+ | 数据库查询 | 100次 | 5次 | ↓ 95% |
53
+
54
+ **配置示例**:
55
+ ```javascript
56
+ // 实例配置(默认 false)
57
+ const msq = new MonSQLize({
58
+ cache: { autoInvalidate: false }
59
+ });
60
+
61
+ // 查询配置(优先)
62
+ await collection('users').find(
63
+ { status: 'active' },
64
+ { cache: 60000, autoInvalidate: true }
65
+ );
66
+ ```
67
+
68
+ **支持的操作符**: 等值、$in、$gt/$gte/$lt/$lte、$ne、$exists
69
+ **自动跳过**: $or、$nor、$expr、$where、$text、$regex
70
+
71
+ **已集成**: insertOne/Many, updateOne/Many, deleteOne/Many, upsertOne (7个写操作)
72
+
73
+ **ObjectId 完全支持** 🆕:
74
+ - ✅ 自动规范化 ObjectId 为字符串(缓存键层面)
75
+ - ✅ 缓存键 100% 一致性保证
76
+ - ✅ 支持 `_id` 和所有 ObjectId 字段
77
+ - ✅ 递归处理嵌套结构和数组
78
+ - ✅ 精准失效对 ObjectId 字段 100% 可靠
79
+
80
+ **测试覆盖**: 36个单元测试,100%通过,≥95%覆盖率
81
+
82
+ #### 🚨 修复的严重问题
83
+
84
+ **问题描述**:
85
+ - `updateOne({ upsert: true })`、`updateMany({ upsert: true })`、`replaceOne({ upsert: true })` 在**插入新文档时不会失效缓存**
86
+ - 导致后续查询返回**过时数据**(缓存中是空数组,但数据库中已有新数据)
87
+ - **影响**: 严重的数据一致性问题
88
+
89
+ **影响场景**:
90
+ - ❌ 用户注册后看不到新用户
91
+ - ❌ 订单创建后看不到新订单
92
+ - ❌ count/distinct 查询返回错误的数量
93
+ - ❌ 统计数据不准确
94
+
95
+ **修复的方法**:
96
+ 1. ✅ **updateOne** - 修复缓存失效条件 (第 146 行)
97
+ 2. ✅ **updateMany** - 修复缓存失效条件 (第 146 行)
98
+ 3. ✅ **replaceOne** - 修复缓存失效条件 (第 113 行,新发现)
99
+
100
+ **测试验证**:
101
+ - ✅ 新增 11 个测试用例,100% 通过
102
+ - ✅ 三轮彻底验证,所有场景覆盖
103
+
104
+ **升级建议**:
105
+ ```bash
106
+ # 如果你使用了 upsert,请立即升级
107
+ npm update monsqlize
108
+ ```
109
+
110
+ 📖 **详细分析**:
111
+ - [三轮验证报告](./reports/upsert-缓存失效-三轮验证报告.md)
112
+ - [问题深度分析](./reports/upsert-缓存失效机制分析报告.md)
113
+ - [完整修复总结](./reports/upsert-缓存失效-完整修复总结.md)
114
+
115
+ #### 其他改进
116
+
117
+ - ✅ function-cache 性能优化 (23-45% 提升)
118
+ - ✅ 新增 17 个复杂数据类型测试
119
+ - ✅ 代码质量提升 (A → A+)
120
+ - ✅ 全局 Map 监控机制
121
+ - ✅ 错误日志记录增强
122
+
123
+ ---
124
+
30
125
  ## 变更统计
31
126
 
32
127
  | 版本系列 | 版本数 | 主要改进方向 |
33
128
  |---------|-------|------------|
34
- | v1.0.x | 10 | 企业级功能、分布式支持、Model 层完善、Schema 验证、**统一表达式系统** 🆕 |
129
+ | v1.1.x | 5 | **数据一致性修复** 🆕、通用函数缓存、文档完善、日志优化、100% MongoDB 操作符 |
130
+ | v1.0.x | 10 | 企业级功能、分布式支持、Model 层完善、Schema 验证、统一表达式系统 |
35
131
 
36
132
  ---
37
133
 
package/README.md CHANGED
@@ -673,6 +673,7 @@ await orders.aggregate([
673
673
 
674
674
  - ✅ **TTL 过期策略** - 指定缓存时间
675
675
  - ✅ **LRU 淘汰策略** - 自动淘汰旧数据
676
+ - ✅ **精准失效 🆕** - 只清除受影响的缓存
676
677
  - ✅ **自动失效** - 写操作自动清理缓存
677
678
  - ✅ **并发去重** - 相同查询只执行一次
678
679
  - ✅ **多层缓存** - 内存 + Redis
package/index.mjs ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * monSQLize ES Module Entry Point
3
+ *
4
+ * 使用方式:
5
+ * ```javascript
6
+ * import MonSQLize from 'monsqlize';
7
+ * // 或
8
+ * import { MonSQLize } from 'monsqlize';
9
+ *
10
+ * const db = new MonSQLize({
11
+ * type: 'mongodb',
12
+ * config: { uri: 'mongodb://localhost:27017/mydb' }
13
+ * });
14
+ *
15
+ * await db.connect();
16
+ * ```
17
+ */
18
+
19
+ import { createRequire } from 'module';
20
+ const require = createRequire(import.meta.url);
21
+
22
+ // 使用 require 导入 CommonJS 模块
23
+ const MonSQLizeClass = require('./lib/index.js');
24
+ const Logger = require('./lib/logger.js');
25
+ const MemoryCache = require('./lib/cache.js');
26
+ const { createRedisCacheAdapter } = require('./lib/redis-cache-adapter.js');
27
+ const TransactionManager = require('./lib/transaction/TransactionManager.js');
28
+ const CacheLockManager = require('./lib/transaction/CacheLockManager.js');
29
+ const DistributedCacheInvalidator = require('./lib/distributed-cache-invalidator.js');
30
+ const { withCache, FunctionCache } = require('./lib/function-cache.js');
31
+
32
+ // 默认导出
33
+ export default MonSQLizeClass;
34
+
35
+ // 🆕 v1.0.9: 导出表达式函数
36
+ const { expr, createExpression } = MonSQLizeClass;
37
+
38
+ // 命名导出
39
+ export {
40
+ MonSQLizeClass as MonSQLize,
41
+ Logger,
42
+ MemoryCache,
43
+ createRedisCacheAdapter,
44
+ TransactionManager,
45
+ CacheLockManager,
46
+ DistributedCacheInvalidator,
47
+ expr, // 🆕 v1.0.9: 统一表达式函数
48
+ createExpression, // 🆕 v1.0.9: 表达式函数别名
49
+ withCache, // 🆕 v1.1.4: 函数缓存装饰器
50
+ FunctionCache // 🆕 v1.1.4: 函数缓存类
51
+ };
52
+
@@ -0,0 +1,279 @@
1
+ /**
2
+ * 缓存精准失效引擎
3
+ * @description 提供精准缓存失效功能,只清除受影响的查询缓存
4
+ * @module lib/cache-invalidation
5
+ */
6
+
7
+ const CacheFactory = require('./cache');
8
+
9
+ /**
10
+ * 缓存精准失效引擎
11
+ * @class
12
+ */
13
+ class CacheInvalidationEngine {
14
+ /**
15
+ * 判断文档字段值是否匹配查询条件
16
+ * @param {any} docValue - 文档字段值
17
+ * @param {any} queryValue - 查询条件值
18
+ * @returns {boolean} true=匹配, false=不匹配
19
+ *
20
+ * @example
21
+ * matchesField('active', 'active') // → true
22
+ * matchesField(25, { $gt: 20 }) // → true
23
+ * matchesField('test', { $in: ['test', 'demo'] }) // → true
24
+ */
25
+ static matchesField(docValue, queryValue) {
26
+ // 1. 简单等值匹配
27
+ if (typeof queryValue !== 'object' || queryValue === null) {
28
+ return docValue === queryValue;
29
+ }
30
+
31
+ // 2. $in 操作符
32
+ if (queryValue.$in && Array.isArray(queryValue.$in)) {
33
+ return queryValue.$in.includes(docValue);
34
+ }
35
+
36
+ // 3. $gt/$gte/$lt/$lte 操作符
37
+ if (queryValue.$gt !== undefined) {
38
+ return docValue > queryValue.$gt;
39
+ }
40
+ if (queryValue.$gte !== undefined) {
41
+ return docValue >= queryValue.$gte;
42
+ }
43
+ if (queryValue.$lt !== undefined) {
44
+ return docValue < queryValue.$lt;
45
+ }
46
+ if (queryValue.$lte !== undefined) {
47
+ return docValue <= queryValue.$lte;
48
+ }
49
+
50
+ // 4. $ne 操作符
51
+ if (queryValue.$ne !== undefined) {
52
+ return docValue !== queryValue.$ne;
53
+ }
54
+
55
+ // 5. $exists 操作符
56
+ if (queryValue.$exists !== undefined) {
57
+ const exists = docValue !== undefined;
58
+ return queryValue.$exists ? exists : !exists;
59
+ }
60
+
61
+ // 6. $eq 操作符(显式等值)
62
+ if (queryValue.$eq !== undefined) {
63
+ return docValue === queryValue.$eq;
64
+ }
65
+
66
+ // 7. 不支持的操作符 → 返回 false(跳过匹配)
67
+ return false;
68
+ }
69
+
70
+ /**
71
+ * 判断文档是否匹配查询条件
72
+ * @param {Object} doc - 写入的文档
73
+ * @param {Object} query - 查询条件
74
+ * @returns {boolean} true=匹配(需要失效), false=不匹配
75
+ *
76
+ * @example
77
+ * matchesQuery({ status: 'active' }, { status: 'active' }) // → true
78
+ * matchesQuery({ status: 'inactive' }, { status: 'active' }) // → false
79
+ * matchesQuery({ age: 25 }, { age: { $gt: 20 } }) // → true
80
+ */
81
+ static matchesQuery(doc, query) {
82
+ // 1. 空查询或 null/undefined → 匹配所有
83
+ if (!query || Object.keys(query).length === 0) {
84
+ return true;
85
+ }
86
+
87
+ // 2. 逐字段检查(AND 逻辑)
88
+ for (const [field, value] of Object.entries(query)) {
89
+ if (!this.matchesField(doc[field], value)) {
90
+ return false; // 任何字段不匹配 → 不失效
91
+ }
92
+ }
93
+
94
+ // 3. 所有字段都匹配 → 失效
95
+ return true;
96
+ }
97
+
98
+ /**
99
+ * 检测查询是否包含复杂操作符
100
+ * @param {Object} query - 查询条件
101
+ * @returns {boolean} true=包含复杂操作符
102
+ *
103
+ * @example
104
+ * hasComplexOperators({ $or: [...] }) // → true
105
+ * hasComplexOperators({ status: 'active' }) // → false
106
+ */
107
+ static hasComplexOperators(query) {
108
+ if (!query || typeof query !== 'object') {
109
+ return false;
110
+ }
111
+
112
+ // 复杂操作符列表(不支持精准失效)
113
+ const complexOps = [
114
+ '$or', // 逻辑或
115
+ '$nor', // 逻辑非或
116
+ '$and', // 逻辑与(保守跳过,可选支持)
117
+ '$expr', // 表达式求值
118
+ '$where', // JavaScript 函数
119
+ '$text', // 全文检索
120
+ '$regex', // 正则匹配
121
+ '$jsonSchema' // Schema 验证
122
+ ];
123
+
124
+ return complexOps.some(op => query[op] !== undefined);
125
+ }
126
+
127
+ /**
128
+ * 从缓存键中提取查询条件
129
+ * @param {string} cacheKey - 缓存键(stableStringify 序列化后的)
130
+ * @returns {Object|null} 查询条件对象,无法解析返回 null
131
+ *
132
+ * @example
133
+ * const key = '{"ns":{...},"op":"find","query":{"status":"active"},...}';
134
+ * extractQueryFromKey(key) // → { status: 'active' }
135
+ */
136
+ static extractQueryFromKey(cacheKey) {
137
+ try {
138
+ // 缓存键格式: stableStringify({ns, op, query, projection, ...})
139
+ // 注意:stableStringify 可能输出 undefined(不是有效 JSON),需要先替换
140
+ const sanitizedKey = cacheKey.replace(/:undefined/g, ':null');
141
+ const keyObj = JSON.parse(sanitizedKey);
142
+
143
+ // 提取 query 字段
144
+ if (keyObj && typeof keyObj === 'object' && keyObj.query !== undefined && keyObj.query !== null) {
145
+ return keyObj.query;
146
+ }
147
+
148
+ return null;
149
+ } catch (err) {
150
+ // 解析失败,返回 null
151
+ return null;
152
+ }
153
+ }
154
+
155
+ /**
156
+ * 合并 filter 和 update 构造文档(用于 upsert)
157
+ * @param {Object} filter - 查询条件
158
+ * @param {Object} update - 更新操作
159
+ * @returns {Object} 合并后的文档
160
+ *
161
+ * @example
162
+ * mergeFilterAndUpdate(
163
+ * { userId: 'user123' },
164
+ * { $set: { name: 'Alice', age: 25 } }
165
+ * ) // → { userId: 'user123', name: 'Alice', age: 25 }
166
+ */
167
+ static mergeFilterAndUpdate(filter, update) {
168
+ const doc = { ...filter };
169
+
170
+ if (!update || typeof update !== 'object') {
171
+ return doc;
172
+ }
173
+
174
+ // 提取 $set 字段
175
+ if (update.$set && typeof update.$set === 'object') {
176
+ Object.assign(doc, update.$set);
177
+ }
178
+
179
+ // 提取 $inc 字段(简化处理:假设增量字段也可能匹配)
180
+ if (update.$inc && typeof update.$inc === 'object') {
181
+ Object.assign(doc, update.$inc);
182
+ }
183
+
184
+ // 提取 $setOnInsert 字段(仅插入时)
185
+ if (update.$setOnInsert && typeof update.$setOnInsert === 'object') {
186
+ Object.assign(doc, update.$setOnInsert);
187
+ }
188
+
189
+ // 提取 $unset 字段(设为 undefined)
190
+ if (update.$unset && typeof update.$unset === 'object') {
191
+ for (const key of Object.keys(update.$unset)) {
192
+ doc[key] = undefined;
193
+ }
194
+ }
195
+
196
+ return doc;
197
+ }
198
+
199
+ /**
200
+ * 精准失效缓存
201
+ * @param {Object} cache - 缓存实例
202
+ * @param {Object} context - 失效上下文
203
+ * @param {string} context.instanceId - 实例ID
204
+ * @param {string} context.type - 数据库类型
205
+ * @param {string} context.db - 数据库名
206
+ * @param {string} context.collection - 集合名
207
+ * @param {Object} context.document - 受影响的文档
208
+ * @param {string} context.operation - 操作类型
209
+ * @returns {Promise<number>} 删除的缓存键数量
210
+ *
211
+ * @example
212
+ * await invalidatePrecise(cache, {
213
+ * instanceId: 'test',
214
+ * type: 'mongodb',
215
+ * db: 'shop',
216
+ * collection: 'users',
217
+ * document: { status: 'active', name: 'Alice' },
218
+ * operation: 'insertOne'
219
+ * })
220
+ */
221
+ static async invalidatePrecise(cache, context) {
222
+ const { instanceId, type, db, collection, document, operation } = context;
223
+
224
+ // 🆕 v1.1.6: 规范化 document 中的 ObjectId 为字符串
225
+ // 确保与缓存键中的 query 格式一致(缓存键生成时已规范化)
226
+ const CacheFactory = require('./cache');
227
+ const normalizedDocument = CacheFactory._normalizeObjectIds(document);
228
+
229
+ // Step 1: 构建 namespace 模式,获取集合的所有缓存键
230
+ const pattern = CacheFactory.buildNamespacePattern({
231
+ iid: instanceId,
232
+ type,
233
+ db,
234
+ collection
235
+ });
236
+ const allKeys = cache.keys(pattern);
237
+
238
+ // 没有缓存,直接返回
239
+ if (!allKeys || allKeys.length === 0) {
240
+ return 0;
241
+ }
242
+
243
+ // Step 2: 遍历每个缓存键,判断是否需要失效
244
+ const keysToDelete = [];
245
+
246
+ for (const key of allKeys) {
247
+ // Step 2.1: 解析查询条件
248
+ const query = this.extractQueryFromKey(key);
249
+ if (query === null) {
250
+ // 解析失败(返回 null),跳过该键
251
+ continue;
252
+ }
253
+
254
+ // Step 2.2: 检测是否包含复杂操作符
255
+ if (this.hasComplexOperators(query)) {
256
+ // 复杂查询,跳过失效(按 TTL 自然过期)
257
+ continue;
258
+ }
259
+
260
+ // Step 2.3: 判断文档是否匹配查询条件
261
+ if (this.matchesQuery(normalizedDocument, query)) {
262
+ // 匹配成功,标记为需要失效
263
+ keysToDelete.push(key);
264
+ }
265
+ }
266
+
267
+ // Step 3: 批量删除匹配的缓存键
268
+ if (keysToDelete.length > 0) {
269
+ const deleted = await cache.delMany(keysToDelete);
270
+ return deleted;
271
+ }
272
+
273
+ return 0;
274
+ }
275
+ }
276
+
277
+ module.exports = CacheInvalidationEngine;
278
+
279
+
package/lib/cache.js CHANGED
@@ -417,11 +417,50 @@ module.exports = class CacheFactory {
417
417
  * 构建缓存键对象的统一外壳(便于命名空间与版本升级)
418
418
  * 传入 base(核心区分字段)与可选 extra。
419
419
  */
420
+ /**
421
+ * 规范化对象中的 ObjectId 为字符串
422
+ * 用于确保缓存键的一致性,避免 ObjectId 实例与字符串不匹配
423
+ * @param {*} obj - 待规范化的对象
424
+ * @returns {*} 规范化后的对象
425
+ * @private
426
+ */
427
+ static _normalizeObjectIds(obj) {
428
+ if (!obj || typeof obj !== 'object') {
429
+ return obj;
430
+ }
431
+
432
+ // 处理 ObjectId 实例
433
+ try {
434
+ const { ObjectId } = require('mongodb');
435
+ if (obj instanceof ObjectId) {
436
+ return obj.toString();
437
+ }
438
+ } catch (err) {
439
+ // mongodb 包未安装或不可用,跳过
440
+ }
441
+
442
+ // 处理数组
443
+ if (Array.isArray(obj)) {
444
+ return obj.map(item => this._normalizeObjectIds(item));
445
+ }
446
+
447
+ // 处理普通对象
448
+ const normalized = {};
449
+ for (const [key, value] of Object.entries(obj)) {
450
+ normalized[key] = this._normalizeObjectIds(value);
451
+ }
452
+ return normalized;
453
+ }
454
+
420
455
  static buildCacheKey({ iid, type, db, collection, op, base = {} }) {
456
+ // 🆕 v1.1.6: 规范化 base 中的 ObjectId 为字符串
457
+ // 确保缓存键一致性,使精准失效能够正确匹配
458
+ const normalizedBase = this._normalizeObjectIds(base);
459
+
421
460
  return {
422
461
  ns: { p: 'monSQLize', v: 1, iid, type, db, collection },
423
462
  op,
424
- ...base,
463
+ ...normalizedBase,
425
464
  };
426
465
  }
427
466
 
@@ -488,4 +527,4 @@ module.exports = class CacheFactory {
488
527
  return this.readThrough(cache, ttl, key, fetcher);
489
528
  };
490
529
  }
491
- };
530
+ };
@@ -56,3 +56,4 @@ module.exports = {
56
56
  encodeCursor,
57
57
  decodeCursor,
58
58
  };
59
+
@@ -70,3 +70,4 @@ module.exports = {
70
70
  createErrorMessage
71
71
  };
72
72
 
73
+
@@ -220,3 +220,4 @@ module.exports = {
220
220
  generateIndexName
221
221
  };
222
222
 
223
+
package/lib/common/log.js CHANGED
@@ -58,3 +58,4 @@ async function withSlowQueryLog(logger, defaults, op, ns, options, exec, slowLog
58
58
  }
59
59
 
60
60
  module.exports = { getSlowQueryThreshold, withSlowQueryLog };
61
+
@@ -19,3 +19,4 @@ function resolveInstanceId(adapter, defaults, currentDb, initialDb, uri) {
19
19
  }
20
20
 
21
21
  module.exports = { resolveInstanceId };
22
+
@@ -31,3 +31,4 @@ function normalizeSort(s) {
31
31
  }
32
32
 
33
33
  module.exports = { normalizeProjection, normalizeSort };
34
+
@@ -40,3 +40,4 @@ function makePageResult(rows, { limit, stableSort, direction, hasCursor, pickAnc
40
40
  }
41
41
 
42
42
  module.exports = { makePageResult };
43
+
@@ -54,3 +54,4 @@ function createCachedRunner(cache, nsAll, logger, defaults, hooks = {}) {
54
54
  }
55
55
 
56
56
  module.exports = { createCachedRunner };
57
+
@@ -229,3 +229,4 @@ class ServerFeatures {
229
229
 
230
230
  module.exports = ServerFeatures;
231
231
 
232
+
@@ -24,3 +24,4 @@ function buildCommonLogExtra(options) {
24
24
  }
25
25
 
26
26
  module.exports = { buildCommonLogExtra };
27
+
@@ -110,3 +110,4 @@ module.exports = {
110
110
  validateRange,
111
111
  validatePositiveInteger
112
112
  };
113
+
package/lib/connect.js CHANGED
@@ -80,3 +80,4 @@ module.exports = class ConnectionManager {
80
80
  return { collection, db, instance };
81
81
  }
82
82
  };
83
+
package/lib/constants.js CHANGED
@@ -52,3 +52,4 @@ module.exports = {
52
52
  },
53
53
  };
54
54
 
55
+
@@ -185,3 +185,4 @@ class CountQueue {
185
185
 
186
186
  module.exports = CountQueue;
187
187
 
188
+
@@ -257,3 +257,4 @@ class DistributedCacheInvalidator {
257
257
  }
258
258
 
259
259
  module.exports = DistributedCacheInvalidator;
260
+
package/lib/errors.js CHANGED
@@ -165,3 +165,4 @@ module.exports = {
165
165
  LockTimeoutError,
166
166
  };
167
167
 
168
+
@@ -111,3 +111,4 @@ class ExpressionCache {
111
111
 
112
112
  module.exports = ExpressionCache;
113
113
 
114
+
@@ -1087,3 +1087,4 @@ class ExpressionCompiler {
1087
1087
 
1088
1088
  module.exports = ExpressionCompiler;
1089
1089
 
1090
+
@@ -528,3 +528,4 @@ module.exports = {
528
528
  _compileSetOperationFunction,
529
529
  _compileAdvancedOperationFunction
530
530
  };
531
+
@@ -81,3 +81,4 @@ module.exports = {
81
81
  hasExpressionInObject
82
82
  };
83
83
 
84
+
@@ -26,3 +26,4 @@ function createExpression(expression) {
26
26
 
27
27
  module.exports = createExpression;
28
28
 
29
+
@@ -16,3 +16,4 @@ module.exports.hasExpressionInPipeline = hasExpressionInPipeline;
16
16
  module.exports.hasExpressionInObject = hasExpressionInObject;
17
17
  module.exports.ExpressionCompiler = ExpressionCompiler;
18
18
 
19
+