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.
Files changed (77) hide show
  1. package/CHANGELOG.md +2474 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1368 -0
  4. package/index.d.ts +1052 -0
  5. package/lib/cache.js +491 -0
  6. package/lib/common/cursor.js +58 -0
  7. package/lib/common/docs-urls.js +72 -0
  8. package/lib/common/index-options.js +222 -0
  9. package/lib/common/log.js +60 -0
  10. package/lib/common/namespace.js +21 -0
  11. package/lib/common/normalize.js +33 -0
  12. package/lib/common/page-result.js +42 -0
  13. package/lib/common/runner.js +56 -0
  14. package/lib/common/server-features.js +231 -0
  15. package/lib/common/shape-builders.js +26 -0
  16. package/lib/common/validation.js +49 -0
  17. package/lib/connect.js +76 -0
  18. package/lib/constants.js +54 -0
  19. package/lib/count-queue.js +187 -0
  20. package/lib/distributed-cache-invalidator.js +259 -0
  21. package/lib/errors.js +157 -0
  22. package/lib/index.js +352 -0
  23. package/lib/logger.js +224 -0
  24. package/lib/model/examples/test.js +114 -0
  25. package/lib/mongodb/common/accessor-helpers.js +44 -0
  26. package/lib/mongodb/common/agg-pipeline.js +32 -0
  27. package/lib/mongodb/common/iid.js +27 -0
  28. package/lib/mongodb/common/lexicographic-expr.js +52 -0
  29. package/lib/mongodb/common/shape.js +31 -0
  30. package/lib/mongodb/common/sort.js +38 -0
  31. package/lib/mongodb/common/transaction-aware.js +24 -0
  32. package/lib/mongodb/connect.js +178 -0
  33. package/lib/mongodb/index.js +458 -0
  34. package/lib/mongodb/management/admin-ops.js +199 -0
  35. package/lib/mongodb/management/bookmark-ops.js +166 -0
  36. package/lib/mongodb/management/cache-ops.js +49 -0
  37. package/lib/mongodb/management/collection-ops.js +386 -0
  38. package/lib/mongodb/management/database-ops.js +201 -0
  39. package/lib/mongodb/management/index-ops.js +474 -0
  40. package/lib/mongodb/management/index.js +16 -0
  41. package/lib/mongodb/management/namespace.js +30 -0
  42. package/lib/mongodb/management/validation-ops.js +267 -0
  43. package/lib/mongodb/queries/aggregate.js +133 -0
  44. package/lib/mongodb/queries/chain.js +623 -0
  45. package/lib/mongodb/queries/count.js +88 -0
  46. package/lib/mongodb/queries/distinct.js +68 -0
  47. package/lib/mongodb/queries/find-and-count.js +183 -0
  48. package/lib/mongodb/queries/find-by-ids.js +235 -0
  49. package/lib/mongodb/queries/find-one-by-id.js +170 -0
  50. package/lib/mongodb/queries/find-one.js +61 -0
  51. package/lib/mongodb/queries/find-page.js +565 -0
  52. package/lib/mongodb/queries/find.js +161 -0
  53. package/lib/mongodb/queries/index.js +49 -0
  54. package/lib/mongodb/writes/delete-many.js +181 -0
  55. package/lib/mongodb/writes/delete-one.js +173 -0
  56. package/lib/mongodb/writes/find-one-and-delete.js +193 -0
  57. package/lib/mongodb/writes/find-one-and-replace.js +222 -0
  58. package/lib/mongodb/writes/find-one-and-update.js +223 -0
  59. package/lib/mongodb/writes/increment-one.js +243 -0
  60. package/lib/mongodb/writes/index.js +41 -0
  61. package/lib/mongodb/writes/insert-batch.js +498 -0
  62. package/lib/mongodb/writes/insert-many.js +218 -0
  63. package/lib/mongodb/writes/insert-one.js +171 -0
  64. package/lib/mongodb/writes/replace-one.js +199 -0
  65. package/lib/mongodb/writes/result-handler.js +236 -0
  66. package/lib/mongodb/writes/update-many.js +205 -0
  67. package/lib/mongodb/writes/update-one.js +207 -0
  68. package/lib/mongodb/writes/upsert-one.js +190 -0
  69. package/lib/multi-level-cache.js +189 -0
  70. package/lib/operators.js +330 -0
  71. package/lib/redis-cache-adapter.js +237 -0
  72. package/lib/transaction/CacheLockManager.js +161 -0
  73. package/lib/transaction/DistributedCacheLockManager.js +239 -0
  74. package/lib/transaction/Transaction.js +314 -0
  75. package/lib/transaction/TransactionManager.js +266 -0
  76. package/lib/transaction/index.js +10 -0
  77. package/package.json +111 -0
@@ -0,0 +1,49 @@
1
+ /**
2
+ * 通用校验工具
3
+ * - validateLimitAfterBefore: 校验 limit 合法与 after/before 互斥
4
+ * - assertCursorSortCompatible: 校验游标中的排序与当前排序一致(字段与方向完全一致)
5
+ */
6
+
7
+ const { createValidationError, createCursorError } = require('../errors');
8
+
9
+ /**
10
+ * @param {{limit?:number, after?:string, before?:string}} opts
11
+ * @param {{maxLimit?:number}} cfg
12
+ */
13
+ function validateLimitAfterBefore(opts, { maxLimit = 500 } = {}) {
14
+ const { limit, after, before } = opts || {};
15
+ if (!Number.isInteger(limit) || limit <= 0 || limit > maxLimit) {
16
+ throw createValidationError([{ path:['limit'], type:'number.range', message:`1..${maxLimit}` }]);
17
+ }
18
+ if (after && before) {
19
+ throw createValidationError([{ path:['after'], type:'any.conflict', message:'after/before 互斥' }]);
20
+ }
21
+ }
22
+
23
+ /**
24
+ * 校验游标排序与当前排序一致
25
+ * @param {Record<string,1|-1>} currentSort
26
+ * @param {Record<string,1|-1>|undefined} cursorSort
27
+ */
28
+ function assertCursorSortCompatible(currentSort, cursorSort) {
29
+ const k1 = Object.keys(currentSort || {});
30
+ const k2 = Object.keys(cursorSort || {});
31
+ const same = k1.length === k2.length && k1.every(k => cursorSort && cursorSort[k] === currentSort[k]);
32
+ if (!same) {
33
+ // 使用专门的 CURSOR_SORT_MISMATCH 错误码
34
+ const { ErrorCodes, createError } = require('../errors');
35
+ throw createError(
36
+ ErrorCodes.CURSOR_SORT_MISMATCH,
37
+ '游标排序不匹配:游标中的排序与当前查询的排序不一致',
38
+ [{
39
+ path: ['cursor'],
40
+ type: 'cursor.sort.mismatch',
41
+ message: 'cursor sort mismatches current sort',
42
+ cursorSort,
43
+ currentSort
44
+ }]
45
+ );
46
+ }
47
+ }
48
+
49
+ module.exports = { validateLimitAfterBefore, assertCursorSortCompatible };
package/lib/connect.js ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * 数据库连接管理器
3
+ * 统一管理各种数据库的连接创建和实例化逻辑
4
+ */
5
+ const Mongo = require('./mongodb');
6
+
7
+ module.exports = class ConnectionManager {
8
+
9
+ /**
10
+ * 支持的数据库类型映射
11
+ */
12
+ static get SUPPORTED_DATABASES() {
13
+ return {
14
+ 'mongodb': Mongo,
15
+ };
16
+ }
17
+
18
+ /**
19
+ * 创建数据库实例
20
+ * @param {string} type - 数据库类型
21
+ * @param {string} databaseName - 数据库名称
22
+ * @param {Object} cache - 缓存实例(内存缓存)
23
+ * @param {Object} logger - 日志记录器
24
+ * @param {Object} [defaults] - 统一默认配置(如 maxTimeMS、namespace)
25
+ * @returns {Object} 数据库实例
26
+ * @throws {Error} 当数据库类型不支持或未实现时抛出错误
27
+ */
28
+ static createInstance(type, databaseName, cache, logger, defaults) {
29
+ const SUPPORTED_DATABASES = this.SUPPORTED_DATABASES;
30
+ // 验证数据库类型是否支持
31
+ if (!(type in SUPPORTED_DATABASES)) {
32
+ const supportedTypes = Object.keys(SUPPORTED_DATABASES).join(', ');
33
+ throw new Error(`Invalid database type: ${type}. Supported types are: ${supportedTypes}`);
34
+ }
35
+
36
+ // 检查是否已实现
37
+ if (SUPPORTED_DATABASES[type] === null) {
38
+ throw new Error(`${type} support not implemented yet`);
39
+ }
40
+
41
+ // 获取对应的数据库类
42
+ const DatabaseClass = SUPPORTED_DATABASES[type];
43
+
44
+ // 创建并返回实例
45
+ return new DatabaseClass(type, databaseName, cache, logger, defaults);
46
+ }
47
+
48
+ /**
49
+ * 连接数据库
50
+ * @param {string} type - 数据库类型
51
+ * @param {string} databaseName - 数据库名称
52
+ * @param {Object} config - 数据库连接配置
53
+ * @param {Object} cache - 缓存实例
54
+ * @param {Object} logger - 日志记录器
55
+ * @param {Object} [defaults] - 统一默认配置(如 maxTimeMS、namespace)
56
+ * @returns {{accessor: Function, instance: Object}} 访问器与底层适配器实例
57
+ * @throws {Error} 连接失败时抛出错误
58
+ */
59
+ static async connect(type, databaseName, config, cache, logger, defaults) {
60
+ // 创建数据库实例
61
+ const instance = this.createInstance(type, databaseName, cache, logger, defaults);
62
+
63
+ // 建立连接
64
+ await instance.connect(config);
65
+
66
+ // ---------- 构建访问器 ----------
67
+ const collection = (collectionName) => instance.collection(databaseName, collectionName);
68
+ const db = (databaseName)=>{
69
+ return {
70
+ collection:(collectionName)=>instance.collection(databaseName, collectionName)
71
+ }
72
+ }
73
+
74
+ return { collection, db, instance };
75
+ }
76
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * 统一常量定义
3
+ * 集中管理所有魔法数字和配置常量
4
+ */
5
+
6
+ module.exports = {
7
+ // 缓存相关
8
+ CACHE: {
9
+ DEFAULT_MAX_SIZE: 100000, // 默认最大缓存条目数
10
+ DEFAULT_MAX_MEMORY: 0, // 默认最大内存(字节),0 表示不限制
11
+ TOTALS_INFLIGHT_WINDOW_MS: 5000, // totals 去重窗口(毫秒)
12
+ REMOTE_TIMEOUT_MS: 50, // 远端缓存操作超时(毫秒)
13
+ },
14
+
15
+ // 查询相关
16
+ QUERY: {
17
+ DEFAULT_SLOW_QUERY_MS: 500, // 慢查询阈值(毫秒)
18
+ DEFAULT_FIND_LIMIT: 10, // find 默认 limit
19
+ DEFAULT_FINDPAGE_MAX_LIMIT: 500, // findPage 最大 limit
20
+ DEFAULT_MAX_TIME_MS: 30000, // 默认查询超时(毫秒)
21
+ },
22
+
23
+ // 分页相关
24
+ PAGINATION: {
25
+ DEFAULT_STEP: 10, // 书签密度:每隔多少页存一个书签
26
+ DEFAULT_MAX_HOPS: 20, // 单次跳页最大 hops
27
+ DEFAULT_MAX_SKIP: 50000, // offset 跳页最大 skip
28
+ },
29
+
30
+ // 流式查询相关
31
+ STREAM: {
32
+ DEFAULT_BATCH_SIZE: 1000, // 流式查询默认批次大小
33
+ },
34
+
35
+ // 连接相关
36
+ CONNECTION: {
37
+ DEFAULT_POOL_SIZE: 10, // 默认连接池大小
38
+ CONNECTION_TIMEOUT_MS: 30000, // 连接超时(毫秒)
39
+ },
40
+
41
+ // 命名空间相关
42
+ NAMESPACE: {
43
+ DEFAULT_SCOPE: 'database', // 默认命名空间范围
44
+ BOOKMARK_PREFIX: 'bm:', // 书签键前缀
45
+ TOTALS_PREFIX: 'tot:', // 总数键前缀
46
+ },
47
+
48
+ // 日志相关
49
+ LOG: {
50
+ MAX_QUERY_SHAPE_LENGTH: 1000, // 查询形状最大长度(日志)
51
+ MAX_ERROR_MESSAGE_LENGTH: 500, // 错误消息最大长度
52
+ },
53
+ };
54
+
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Count 队列控制器
3
+ * 限制同时执行的 count 数量,避免高并发下压垮数据库
4
+ *
5
+ * 使用场景:
6
+ * - findPage 的 totals 统计
7
+ * - 任何需要执行 countDocuments 的场景
8
+ *
9
+ * 核心功能:
10
+ * 1. 并发控制 - 限制同时执行的 count 数量
11
+ * 2. 队列管理 - 超出并发限制的请求排队等待
12
+ * 3. 超时保护 - 防止请求长时间等待
13
+ * 4. 统计监控 - 提供队列状态和统计信息
14
+ */
15
+ class CountQueue {
16
+ constructor(options = {}) {
17
+ // 默认并发数:CPU 核心数(最少 4,最多 16)
18
+ const cpuCount = require('os').cpus().length;
19
+ const defaultConcurrency = Math.max(4, Math.min(cpuCount, 16));
20
+
21
+ this.concurrency = options.concurrency || defaultConcurrency;
22
+ this.maxQueueSize = options.maxQueueSize || 10000; // 队列最大长度(增加到 10000)
23
+ this.timeout = options.timeout || 60000; // 超时 60 秒(增加到 1 分钟)
24
+
25
+ this.queue = []; // 等待队列
26
+ this.running = 0; // 当前执行数
27
+
28
+ // 统计信息
29
+ this.stats = {
30
+ executed: 0, // 已执行总数
31
+ queued: 0, // 曾排队总数
32
+ timeout: 0, // 超时次数
33
+ rejected: 0, // 拒绝次数(队列满)
34
+ avgWaitTime: 0, // 平均等待时间
35
+ maxWaitTime: 0 // 最大等待时间
36
+ };
37
+ }
38
+
39
+ /**
40
+ * 执行 count 操作(带队列控制)
41
+ * @param {Function} fn - count 操作函数
42
+ * @returns {Promise<number>} count 结果
43
+ * @throws {Error} 队列满或超时
44
+ */
45
+ async execute(fn) {
46
+ const startTime = Date.now();
47
+
48
+ // 检查是否需要排队
49
+ if (this.running >= this.concurrency) {
50
+ // 检查队列是否满了
51
+ if (this.queue.length >= this.maxQueueSize) {
52
+ this.stats.rejected++;
53
+ throw new Error(`Count queue is full (${this.maxQueueSize})`);
54
+ }
55
+
56
+ this.stats.queued++;
57
+ // 等待轮到自己
58
+ await this._waitInQueue(startTime);
59
+ }
60
+
61
+ // 获得执行机会,增加 running
62
+ this.running++;
63
+ this.stats.executed++;
64
+
65
+ try {
66
+ // 带超时控制
67
+ return await this._executeWithTimeout(fn);
68
+ } finally {
69
+ this.running--;
70
+ // 唤醒队列中的下一个
71
+ this._wakeNext();
72
+ }
73
+ }
74
+
75
+ /**
76
+ * 等待队列
77
+ * @private
78
+ */
79
+ async _waitInQueue(startTime) {
80
+ return new Promise((resolve, reject) => {
81
+ const timer = setTimeout(() => {
82
+ // 超时,从队列中移除
83
+ const index = this.queue.findIndex(item => item.resolve === resolve);
84
+ if (index !== -1) {
85
+ this.queue.splice(index, 1);
86
+ this.stats.timeout++;
87
+ reject(new Error(`Count queue wait timeout (${this.timeout}ms)`));
88
+ }
89
+ }, this.timeout);
90
+
91
+ this.queue.push({
92
+ resolve: () => {
93
+ const waitTime = Date.now() - startTime;
94
+ this._updateWaitTimeStats(waitTime);
95
+ resolve();
96
+ },
97
+ timer,
98
+ startTime
99
+ });
100
+ });
101
+ }
102
+
103
+ /**
104
+ * 唤醒队列中的下一个
105
+ * @private
106
+ */
107
+ _wakeNext() {
108
+ if (this.queue.length > 0) {
109
+ const { resolve, timer } = this.queue.shift();
110
+ clearTimeout(timer);
111
+ resolve();
112
+ }
113
+ }
114
+
115
+ /**
116
+ * 带超时的执行
117
+ * @private
118
+ */
119
+ async _executeWithTimeout(fn) {
120
+ return Promise.race([
121
+ fn(),
122
+ new Promise((_, reject) =>
123
+ setTimeout(() => reject(new Error(`Count execution timeout (${this.timeout}ms)`)), this.timeout)
124
+ )
125
+ ]);
126
+ }
127
+
128
+ /**
129
+ * 更新等待时间统计
130
+ * @private
131
+ */
132
+ _updateWaitTimeStats(waitTime) {
133
+ // 计算平均等待时间
134
+ const totalQueued = this.stats.queued;
135
+ this.stats.avgWaitTime = (this.stats.avgWaitTime * (totalQueued - 1) + waitTime) / totalQueued;
136
+
137
+ // 更新最大等待时间
138
+ if (waitTime > this.stats.maxWaitTime) {
139
+ this.stats.maxWaitTime = waitTime;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * 获取统计信息
145
+ * @returns {Object} 统计信息
146
+ */
147
+ getStats() {
148
+ return {
149
+ ...this.stats,
150
+ running: this.running, // 当前执行中
151
+ queuedNow: this.queue.length, // 当前排队中
152
+ concurrency: this.concurrency, // 并发限制
153
+ maxQueueSize: this.maxQueueSize // 队列容量
154
+ };
155
+ }
156
+
157
+ /**
158
+ * 重置统计信息
159
+ */
160
+ resetStats() {
161
+ this.stats = {
162
+ executed: 0,
163
+ queued: 0,
164
+ timeout: 0,
165
+ rejected: 0,
166
+ avgWaitTime: 0,
167
+ maxWaitTime: 0
168
+ };
169
+ }
170
+
171
+ /**
172
+ * 清空队列(慎用)
173
+ */
174
+ clear() {
175
+ // 拒绝所有等待中的请求
176
+ while (this.queue.length > 0) {
177
+ const item = this.queue.shift();
178
+ clearTimeout(item.timer);
179
+ // 注意:这里不能直接 resolve 错误
180
+ // 因为队列项只存储了 resolve,没有 reject
181
+ // 所以清空操作只是清理队列,不触发错误
182
+ }
183
+ }
184
+ }
185
+
186
+ module.exports = CountQueue;
187
+
@@ -0,0 +1,259 @@
1
+ /**
2
+ * 分布式缓存失效器
3
+ * 基于 Redis Pub/Sub 实现跨实例的缓存失效通知
4
+ *
5
+ * @example
6
+ * const invalidator = new DistributedCacheInvalidator({
7
+ * redisUrl: 'redis://localhost:6379',
8
+ * channel: 'monsqlize:cache:invalidate',
9
+ * cache: multiLevelCacheInstance
10
+ * });
11
+ *
12
+ * // 广播失效消息
13
+ * await invalidator.invalidate('user:*');
14
+ */
15
+
16
+ class DistributedCacheInvalidator {
17
+ /**
18
+ * @param {Object} options
19
+ * @param {string} [options.redisUrl] - Redis 连接 URL
20
+ * @param {Object} [options.redis] - 已创建的 Redis 实例(与 redisUrl 二选一)
21
+ * @param {string} [options.channel='monsqlize:cache:invalidate'] - Pub/Sub 频道
22
+ * @param {string} [options.instanceId] - 实例 ID(自动生成)
23
+ * @param {Object} options.cache - MultiLevelCache 实例
24
+ * @param {Object} [options.logger] - 日志记录器
25
+ */
26
+ constructor(options = {}) {
27
+ if (!options.cache) {
28
+ throw new Error('DistributedCacheInvalidator requires a cache instance');
29
+ }
30
+
31
+ this.cache = options.cache;
32
+ this.logger = options.logger;
33
+ this.channel = options.channel || 'monsqlize:cache:invalidate';
34
+ this.instanceId = options.instanceId || `instance-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
35
+
36
+ // 初始化 Redis 连接
37
+ this._initRedis(options);
38
+
39
+ // 设置订阅
40
+ this._setupSubscription();
41
+
42
+ // 统计信息
43
+ this.stats = {
44
+ messagesSent: 0,
45
+ messagesReceived: 0,
46
+ invalidationsTriggered: 0,
47
+ errors: 0
48
+ };
49
+ }
50
+
51
+ /**
52
+ * 初始化 Redis 连接
53
+ * @private
54
+ */
55
+ _initRedis(options) {
56
+ try {
57
+ const Redis = require('ioredis');
58
+
59
+ if (options.redis) {
60
+ // 使用已有的 Redis 实例
61
+ this.pub = options.redis;
62
+ // 订阅需要单独的连接
63
+ const redisConfig = options.redis.options || {};
64
+ this.sub = new Redis({
65
+ ...redisConfig,
66
+ host: redisConfig.host || 'localhost',
67
+ port: redisConfig.port || 6379
68
+ });
69
+ this._ownsConnections = false;
70
+ } else if (options.redisUrl) {
71
+ // 创建新的 Redis 连接
72
+ this.pub = new Redis(options.redisUrl);
73
+ this.sub = new Redis(options.redisUrl);
74
+ this._ownsConnections = true;
75
+ } else {
76
+ // 默认本地连接
77
+ this.pub = new Redis('redis://localhost:6379');
78
+ this.sub = new Redis('redis://localhost:6379');
79
+ this._ownsConnections = true;
80
+ }
81
+
82
+ // 错误处理
83
+ this.pub.on('error', (err) => {
84
+ this.stats.errors++;
85
+ if (this.logger) {
86
+ this.logger.error('[DistributedCacheInvalidator] Redis pub error:', err.message);
87
+ }
88
+ });
89
+
90
+ this.sub.on('error', (err) => {
91
+ this.stats.errors++;
92
+ if (this.logger) {
93
+ this.logger.error('[DistributedCacheInvalidator] Redis sub error:', err.message);
94
+ }
95
+ });
96
+ } catch (error) {
97
+ throw new Error(
98
+ 'Failed to initialize Redis for DistributedCacheInvalidator. ' +
99
+ 'Please ensure ioredis is installed: npm install ioredis'
100
+ );
101
+ }
102
+ }
103
+
104
+ /**
105
+ * 设置订阅处理
106
+ * @private
107
+ */
108
+ _setupSubscription() {
109
+ this.sub.subscribe(this.channel, (err) => {
110
+ if (err) {
111
+ this.stats.errors++;
112
+ if (this.logger) {
113
+ this.logger.error('[DistributedCacheInvalidator] Subscribe error:', err.message);
114
+ }
115
+ } else {
116
+ if (this.logger) {
117
+ this.logger.info(`[DistributedCacheInvalidator] Subscribed to channel: ${this.channel}`);
118
+ }
119
+ }
120
+ });
121
+
122
+ this.sub.on('message', (channel, message) => {
123
+ if (channel !== this.channel) return;
124
+
125
+ this.stats.messagesReceived++;
126
+
127
+ try {
128
+ const data = JSON.parse(message);
129
+
130
+ // 忽略自己发送的消息(避免重复失效)
131
+ if (data.instanceId === this.instanceId) {
132
+ return;
133
+ }
134
+
135
+ // 处理失效消息
136
+ if (data.type === 'invalidate' && data.pattern) {
137
+ this._handleInvalidation(data.pattern);
138
+ }
139
+ } catch (error) {
140
+ this.stats.errors++;
141
+ if (this.logger) {
142
+ this.logger.error('[DistributedCacheInvalidator] Message parse error:', error.message);
143
+ }
144
+ }
145
+ });
146
+ }
147
+
148
+ /**
149
+ * 处理缓存失效
150
+ * @private
151
+ */
152
+ async _handleInvalidation(pattern) {
153
+ try {
154
+ if (this.logger) {
155
+ this.logger.debug(`[DistributedCacheInvalidator] Handling invalidation, pattern: ${pattern}`);
156
+ }
157
+
158
+ let deleted = 0;
159
+
160
+ // 1. 失效本地缓存
161
+ if (this.cache.local && typeof this.cache.local.delPattern === 'function') {
162
+ deleted = await this.cache.local.delPattern(pattern);
163
+ if (this.logger) {
164
+ this.logger.debug(`[DistributedCacheInvalidator] Invalidated local cache: ${pattern}, deleted: ${deleted} keys`);
165
+ }
166
+ }
167
+
168
+ // 2. 失效远端缓存(Redis)
169
+ if (this.cache.remote && typeof this.cache.remote.delPattern === 'function') {
170
+ const remoteDeleted = await this.cache.remote.delPattern(pattern);
171
+ deleted += remoteDeleted;
172
+ if (this.logger) {
173
+ this.logger.debug(`[DistributedCacheInvalidator] Invalidated remote cache: ${pattern}, deleted: ${remoteDeleted} keys`);
174
+ }
175
+ }
176
+
177
+ this.stats.invalidationsTriggered++;
178
+
179
+ if (this.logger) {
180
+ this.logger.info(`[DistributedCacheInvalidator] Total invalidated: ${pattern}, deleted: ${deleted} keys`);
181
+ }
182
+ } catch (error) {
183
+ this.stats.errors++;
184
+ if (this.logger) {
185
+ this.logger.error('[DistributedCacheInvalidator] Invalidation error:', error.message);
186
+ }
187
+ }
188
+ }
189
+
190
+ /**
191
+ * 广播缓存失效消息
192
+ * @param {string} pattern - 缓存键模式(支持通配符 *)
193
+ * @returns {Promise<void>}
194
+ */
195
+ async invalidate(pattern) {
196
+ if (!pattern) return;
197
+
198
+ const message = JSON.stringify({
199
+ type: 'invalidate',
200
+ pattern,
201
+ instanceId: this.instanceId,
202
+ timestamp: Date.now()
203
+ });
204
+
205
+ try {
206
+ await this.pub.publish(this.channel, message);
207
+ this.stats.messagesSent++;
208
+
209
+ if (this.logger) {
210
+ this.logger.debug(`[DistributedCacheInvalidator] Published invalidation: ${pattern}`);
211
+ }
212
+ } catch (error) {
213
+ this.stats.errors++;
214
+ if (this.logger) {
215
+ this.logger.error('[DistributedCacheInvalidator] Publish error:', error.message);
216
+ }
217
+ throw error;
218
+ }
219
+ }
220
+
221
+ /**
222
+ * 获取统计信息
223
+ * @returns {Object}
224
+ */
225
+ getStats() {
226
+ return {
227
+ ...this.stats,
228
+ instanceId: this.instanceId,
229
+ channel: this.channel
230
+ };
231
+ }
232
+
233
+ /**
234
+ * 关闭连接
235
+ * @returns {Promise<void>}
236
+ */
237
+ async close() {
238
+ try {
239
+ // 取消订阅
240
+ await this.sub.unsubscribe(this.channel);
241
+
242
+ // 如果是自己创建的连接,才关闭
243
+ if (this._ownsConnections) {
244
+ await this.pub.quit();
245
+ await this.sub.quit();
246
+ }
247
+
248
+ if (this.logger) {
249
+ this.logger.info('[DistributedCacheInvalidator] Closed');
250
+ }
251
+ } catch (error) {
252
+ if (this.logger) {
253
+ this.logger.error('[DistributedCacheInvalidator] Close error:', error.message);
254
+ }
255
+ }
256
+ }
257
+ }
258
+
259
+ module.exports = DistributedCacheInvalidator;