monsqlize 1.3.1 → 2.0.1

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 (114) hide show
  1. package/CHANGELOG.md +506 -235
  2. package/LICENSE +201 -21
  3. package/README.md +542 -928
  4. package/changelogs/README.md +163 -0
  5. package/changelogs/v2.0.0.md +222 -0
  6. package/changelogs/v2.0.1.md +39 -0
  7. package/dist/cjs/index.cjs +10788 -0
  8. package/dist/cjs/mongodb/common/transaction-aware.cjs +10 -0
  9. package/dist/cjs/transaction/CacheLockManager.cjs +100 -0
  10. package/dist/cjs/transaction/Transaction.cjs +158 -0
  11. package/dist/cjs/transaction/TransactionManager.cjs +298 -0
  12. package/dist/esm/index.mjs +10838 -0
  13. package/dist/types/base.d.ts +81 -0
  14. package/dist/types/collection.d.ts +1031 -0
  15. package/dist/types/expression.d.ts +115 -0
  16. package/dist/types/index.d.ts +23 -0
  17. package/dist/types/lock.d.ts +74 -0
  18. package/dist/types/model.d.ts +530 -0
  19. package/dist/types/mongodb.d.ts +49 -0
  20. package/dist/types/monsqlize.d.ts +491 -0
  21. package/dist/types/pool.d.ts +84 -0
  22. package/dist/types/runtime.d.ts +362 -0
  23. package/dist/types/saga.d.ts +143 -0
  24. package/dist/types/slow-query-log.d.ts +126 -0
  25. package/dist/types/sync.d.ts +103 -0
  26. package/dist/types/transaction.d.ts +132 -0
  27. package/package.json +120 -117
  28. package/index.d.ts +0 -1289
  29. package/lib/cache.js +0 -491
  30. package/lib/common/cursor.js +0 -58
  31. package/lib/common/docs-urls.js +0 -72
  32. package/lib/common/index-options.js +0 -222
  33. package/lib/common/log.js +0 -60
  34. package/lib/common/namespace.js +0 -21
  35. package/lib/common/normalize.js +0 -33
  36. package/lib/common/page-result.js +0 -42
  37. package/lib/common/runner.js +0 -56
  38. package/lib/common/server-features.js +0 -231
  39. package/lib/common/shape-builders.js +0 -26
  40. package/lib/common/validation.js +0 -112
  41. package/lib/connect.js +0 -76
  42. package/lib/constants.js +0 -54
  43. package/lib/count-queue.js +0 -187
  44. package/lib/distributed-cache-invalidator.js +0 -259
  45. package/lib/errors.js +0 -167
  46. package/lib/index.js +0 -461
  47. package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -211
  48. package/lib/infrastructure/ssh-tunnel.js +0 -40
  49. package/lib/infrastructure/uri-parser.js +0 -35
  50. package/lib/lock/Lock.js +0 -66
  51. package/lib/lock/errors.js +0 -27
  52. package/lib/lock/index.js +0 -12
  53. package/lib/logger.js +0 -224
  54. package/lib/model/examples/test.js +0 -114
  55. package/lib/mongodb/common/accessor-helpers.js +0 -58
  56. package/lib/mongodb/common/agg-pipeline.js +0 -32
  57. package/lib/mongodb/common/iid.js +0 -27
  58. package/lib/mongodb/common/lexicographic-expr.js +0 -52
  59. package/lib/mongodb/common/shape.js +0 -31
  60. package/lib/mongodb/common/sort.js +0 -38
  61. package/lib/mongodb/common/transaction-aware.js +0 -24
  62. package/lib/mongodb/connect.js +0 -233
  63. package/lib/mongodb/index.js +0 -591
  64. package/lib/mongodb/management/admin-ops.js +0 -199
  65. package/lib/mongodb/management/bookmark-ops.js +0 -166
  66. package/lib/mongodb/management/cache-ops.js +0 -49
  67. package/lib/mongodb/management/collection-ops.js +0 -386
  68. package/lib/mongodb/management/database-ops.js +0 -201
  69. package/lib/mongodb/management/index-ops.js +0 -474
  70. package/lib/mongodb/management/index.js +0 -16
  71. package/lib/mongodb/management/namespace.js +0 -30
  72. package/lib/mongodb/management/validation-ops.js +0 -267
  73. package/lib/mongodb/queries/aggregate.js +0 -142
  74. package/lib/mongodb/queries/chain.js +0 -630
  75. package/lib/mongodb/queries/count.js +0 -98
  76. package/lib/mongodb/queries/distinct.js +0 -77
  77. package/lib/mongodb/queries/find-and-count.js +0 -192
  78. package/lib/mongodb/queries/find-by-ids.js +0 -235
  79. package/lib/mongodb/queries/find-one-by-id.js +0 -170
  80. package/lib/mongodb/queries/find-one.js +0 -70
  81. package/lib/mongodb/queries/find-page.js +0 -577
  82. package/lib/mongodb/queries/find.js +0 -170
  83. package/lib/mongodb/queries/index.js +0 -50
  84. package/lib/mongodb/queries/watch.js +0 -537
  85. package/lib/mongodb/writes/delete-many.js +0 -190
  86. package/lib/mongodb/writes/delete-one.js +0 -182
  87. package/lib/mongodb/writes/find-one-and-delete.js +0 -202
  88. package/lib/mongodb/writes/find-one-and-replace.js +0 -238
  89. package/lib/mongodb/writes/find-one-and-update.js +0 -239
  90. package/lib/mongodb/writes/increment-one.js +0 -252
  91. package/lib/mongodb/writes/index.js +0 -41
  92. package/lib/mongodb/writes/insert-batch.js +0 -507
  93. package/lib/mongodb/writes/insert-many.js +0 -227
  94. package/lib/mongodb/writes/insert-one.js +0 -180
  95. package/lib/mongodb/writes/replace-one.js +0 -215
  96. package/lib/mongodb/writes/result-handler.js +0 -236
  97. package/lib/mongodb/writes/update-many.js +0 -221
  98. package/lib/mongodb/writes/update-one.js +0 -223
  99. package/lib/mongodb/writes/upsert-one.js +0 -206
  100. package/lib/multi-level-cache.js +0 -189
  101. package/lib/operators.js +0 -330
  102. package/lib/redis-cache-adapter.js +0 -237
  103. package/lib/slow-query-log/base-storage.js +0 -69
  104. package/lib/slow-query-log/batch-queue.js +0 -96
  105. package/lib/slow-query-log/config-manager.js +0 -195
  106. package/lib/slow-query-log/index.js +0 -237
  107. package/lib/slow-query-log/mongodb-storage.js +0 -323
  108. package/lib/slow-query-log/query-hash.js +0 -38
  109. package/lib/transaction/CacheLockManager.js +0 -161
  110. package/lib/transaction/DistributedCacheLockManager.js +0 -474
  111. package/lib/transaction/Transaction.js +0 -314
  112. package/lib/transaction/TransactionManager.js +0 -266
  113. package/lib/transaction/index.js +0 -10
  114. package/lib/utils/objectid-converter.js +0 -566
package/lib/errors.js DELETED
@@ -1,167 +0,0 @@
1
- /**
2
- * 统一错误码定义
3
- * 集中管理所有错误类型,确保错误处理的一致性
4
- */
5
-
6
- const ErrorCodes = {
7
- // 验证相关错误
8
- VALIDATION_ERROR: 'VALIDATION_ERROR',
9
- INVALID_ARGUMENT: 'INVALID_ARGUMENT',
10
- INVALID_COLLECTION_NAME: 'INVALID_COLLECTION_NAME',
11
- INVALID_DATABASE_NAME: 'INVALID_DATABASE_NAME',
12
-
13
- // 游标相关错误
14
- INVALID_CURSOR: 'INVALID_CURSOR',
15
- CURSOR_SORT_MISMATCH: 'CURSOR_SORT_MISMATCH',
16
-
17
- // 分页相关错误
18
- JUMP_TOO_FAR: 'JUMP_TOO_FAR',
19
- STREAM_NO_JUMP: 'STREAM_NO_JUMP',
20
- STREAM_NO_TOTALS: 'STREAM_NO_TOTALS',
21
- STREAM_NO_EXPLAIN: 'STREAM_NO_EXPLAIN',
22
-
23
- // 连接相关错误
24
- CONNECTION_TIMEOUT: 'CONNECTION_TIMEOUT',
25
- CONNECTION_FAILED: 'CONNECTION_FAILED',
26
- CONNECTION_CLOSED: 'CONNECTION_CLOSED',
27
-
28
- // 数据库相关错误
29
- DATABASE_ERROR: 'DATABASE_ERROR',
30
- QUERY_TIMEOUT: 'QUERY_TIMEOUT',
31
-
32
- // 缓存相关错误
33
- CACHE_ERROR: 'CACHE_ERROR',
34
- CACHE_TIMEOUT: 'CACHE_TIMEOUT',
35
-
36
- // 配置相关错误
37
- INVALID_CONFIG: 'INVALID_CONFIG',
38
- UNSUPPORTED_DATABASE: 'UNSUPPORTED_DATABASE',
39
-
40
- // 写操作相关错误
41
- WRITE_ERROR: 'WRITE_ERROR',
42
- DOCUMENT_REQUIRED: 'DOCUMENT_REQUIRED',
43
- DOCUMENTS_REQUIRED: 'DOCUMENTS_REQUIRED',
44
- DUPLICATE_KEY: 'DUPLICATE_KEY',
45
- WRITE_CONFLICT: 'WRITE_CONFLICT',
46
-
47
- // 🆕 v1.4.0: 锁相关错误
48
- LOCK_ACQUIRE_FAILED: 'LOCK_ACQUIRE_FAILED',
49
- LOCK_TIMEOUT: 'LOCK_TIMEOUT',
50
- };
51
-
52
- /**
53
- * 创建标准错误对象
54
- * @param {string} code - 错误码
55
- * @param {string} message - 错误消息
56
- * @param {Array} [details] - 详细错误信息
57
- * @param {Error} [cause] - 原始错误
58
- * @returns {Error} 标准错误对象
59
- */
60
- function createError(code, message, details, cause) {
61
- const error = new Error(message);
62
- error.code = code;
63
- if (details !== undefined) error.details = details;
64
- if (cause !== undefined) error.cause = cause;
65
- return error;
66
- }
67
-
68
- /**
69
- * 创建验证错误
70
- * @param {string|Array} messageOrDetails - 错误消息或验证错误详情(向后兼容)
71
- * @param {Array} [details] - 详细信息(当第一个参数是字符串时使用)
72
- * @returns {Error}
73
- */
74
- function createValidationError(messageOrDetails, details) {
75
- // 向后兼容:如果第一个参数是数组,当作 details 处理
76
- if (Array.isArray(messageOrDetails)) {
77
- return createError(
78
- ErrorCodes.VALIDATION_ERROR,
79
- '参数校验失败',
80
- messageOrDetails
81
- );
82
- }
83
-
84
- // 新用法:第一个参数是消息字符串
85
- return createError(
86
- ErrorCodes.VALIDATION_ERROR,
87
- messageOrDetails || '参数校验失败',
88
- details
89
- );
90
- }
91
-
92
- /**
93
- * 创建游标错误
94
- * @param {string} message - 错误消息
95
- * @param {Array} [details] - 详细信息
96
- * @returns {Error}
97
- */
98
- function createCursorError(message, details = null) {
99
- return createError(
100
- ErrorCodes.INVALID_CURSOR,
101
- message || '游标无效',
102
- details
103
- );
104
- }
105
-
106
- /**
107
- * 创建连接错误
108
- * @param {string} message - 错误消息
109
- * @param {Error} [cause] - 原始错误
110
- * @returns {Error}
111
- */
112
- function createConnectionError(message, cause = null) {
113
- return createError(
114
- ErrorCodes.CONNECTION_FAILED,
115
- message || '数据库连接失败',
116
- null,
117
- cause
118
- );
119
- }
120
-
121
- /**
122
- * 创建查询超时错误
123
- * @param {number} timeoutMs - 超时时间(毫秒)
124
- * @param {Error} [cause] - 原始错误
125
- * @returns {Error}
126
- */
127
- function createQueryTimeoutError(timeoutMs, cause = null) {
128
- return createError(
129
- ErrorCodes.QUERY_TIMEOUT,
130
- `查询超时 (${timeoutMs}ms)`,
131
- null,
132
- cause
133
- );
134
- }
135
-
136
- /**
137
- * 创建写操作错误
138
- * @param {string} operation - 操作名称
139
- * @param {string} message - 错误消息
140
- * @param {Error} [cause] - 原始错误
141
- * @returns {Error}
142
- */
143
- function createWriteError(operation, message, cause = null) {
144
- return createError(
145
- ErrorCodes.WRITE_ERROR,
146
- `${operation} 失败: ${message}`,
147
- null,
148
- cause
149
- );
150
- }
151
-
152
- // 🆕 v1.4.0: 导入锁错误类
153
- const { LockAcquireError, LockTimeoutError } = require('./lock/errors');
154
-
155
- module.exports = {
156
- ErrorCodes,
157
- createError,
158
- createValidationError,
159
- createCursorError,
160
- createConnectionError,
161
- createQueryTimeoutError,
162
- createWriteError,
163
- // 🆕 v1.4.0: 锁错误类
164
- LockAcquireError,
165
- LockTimeoutError,
166
- };
167
-
package/lib/index.js DELETED
@@ -1,461 +0,0 @@
1
- const Logger = require('./logger');
2
- const ConnectionManager = require('./connect');
3
- const MemoryCache = require('./cache');
4
- const { createRedisCacheAdapter } = require('./redis-cache-adapter');
5
- const TransactionManager = require('./transaction/TransactionManager');
6
- const CacheLockManager = require('./transaction/CacheLockManager');
7
- const DistributedCacheInvalidator = require('./distributed-cache-invalidator');
8
- const { validateRange } = require('./common/validation');
9
-
10
- module.exports = class {
11
-
12
- /**
13
- * 初始化数据库连接配置
14
- * @param {Object} options - 数据库连接配置选项
15
- * @param {string} options.type - 数据库类型,支持 mongodb
16
- * @param {Object} options.config - 数据库连接配置
17
- * @param {Object} [options.cache] - 缓存配置选项
18
- * @param {Object} [options.logger] - 日志记录器
19
- * @param {number} [options.maxTimeMS] - 全局默认查询超时时间(毫秒)
20
- * @param {{instanceId?: string}} [options.namespace] - 命名空间设置(用于缓存隔离)
21
- * @throws {Error} 如果数据库类型无效则抛出错误
22
- */
23
- constructor(options) {
24
- if (!options.type || !['mongodb'].includes(options.type)) {
25
- throw new Error('Invalid database type. Supported types are: mongodb');
26
- }
27
- const { type = 'mongodb', databaseName, config, cache, logger } = options;
28
- this.type = type;
29
- this.databaseName = databaseName;
30
- this.config = config;
31
-
32
- // ✅ v1.3.0: 自动 ObjectId 转换配置
33
- this.autoConvertConfig = this._initAutoConvertConfig(
34
- options.autoConvertObjectId,
35
- options.type
36
- );
37
-
38
- // 🔧 修复:保存 distributed 配置到单独的变量
39
- this._cacheConfig = cache;
40
-
41
- // Count 队列配置(高并发控制,避免压垮数据库)
42
- // 默认值:
43
- // - enabled: true (默认启用)
44
- // - concurrency: CPU 核心数(最少 4,最多 16)
45
- // - maxQueueSize: 10000
46
- // - timeout: 60000ms (1分钟)
47
- this.countQueue = options.countQueue !== undefined ? options.countQueue : {
48
- enabled: true, // 默认启用
49
- concurrency: undefined, // undefined 则使用 CPU 核心数
50
- maxQueueSize: 10000, // 队列最大 10000
51
- timeout: 60000 // 超时 60 秒
52
- };
53
-
54
- // 使用缓存工厂获取有效的缓存实例
55
- this.cache = MemoryCache.getOrCreateCache(cache);
56
-
57
- // 使用 Logger 工具类创建日志记录器
58
- this.logger = Logger.create(logger);
59
-
60
- // 🔒 参数验证:防止 DoS 攻击(允许null值用于显式禁用)
61
- if (options.maxTimeMS !== undefined && options.maxTimeMS !== null) {
62
- validateRange(options.maxTimeMS, 1, 300000, 'maxTimeMS');
63
- }
64
- if (options.findLimit !== undefined && options.findLimit !== null) {
65
- validateRange(options.findLimit, 1, 10000, 'findLimit');
66
- }
67
- if (options.findPageMaxLimit !== undefined && options.findPageMaxLimit !== null) {
68
- validateRange(options.findPageMaxLimit, 1, 10000, 'findPageMaxLimit');
69
- }
70
- if (options.slowQueryMs !== undefined && options.slowQueryMs !== null && options.slowQueryMs !== -1) {
71
- validateRange(options.slowQueryMs, 0, 60000, 'slowQueryMs');
72
- }
73
-
74
- // 集中默认配置(库内默认 + 用户覆盖)
75
- const DEFAULTS = {
76
- maxTimeMS: 2000,
77
- findLimit: 10,
78
- slowQueryMs: 500,
79
- namespace: { scope: 'database' },
80
- // 深分页/聚合相关
81
- findPageMaxLimit: 500,
82
- cursorSecret: undefined,
83
- // 慢日志扩展
84
- log: { slowQueryTag: { event: 'slow_query', code: 'SLOW_QUERY' } },
85
- };
86
- const deepMerge = (base, patch) => {
87
- const out = { ...base };
88
- for (const k of Object.keys(patch || {})) {
89
- const v = patch[k];
90
- if (v && typeof v === 'object' && !Array.isArray(v)) {
91
- out[k] = deepMerge(base[k] || {}, v);
92
- } else if (v !== undefined) {
93
- out[k] = v;
94
- }
95
- }
96
- return out;
97
- };
98
- this.defaults = deepMerge(DEFAULTS, {
99
- maxTimeMS: options.maxTimeMS,
100
- findLimit: options.findLimit,
101
- namespace: options.namespace,
102
- slowQueryMs: options.slowQueryMs,
103
- // 新增可选项
104
- findPageMaxLimit: options.findPageMaxLimit,
105
- cursorSecret: options.cursorSecret,
106
- log: options.log,
107
- // 🔴 v1.3.1: 慢查询日志持久化存储配置
108
- slowQueryLog: options.slowQueryLog,
109
- });
110
- // 冻结默认配置,避免运行期被意外修改
111
- this.defaults = Object.freeze(this.defaults);
112
- }
113
-
114
- /**
115
- * 连接数据库并返回访问集合/表的对象
116
- * @returns {{collection: Function, db: Function}} 返回包含 collection 与 db 方法的对象
117
- * @throws {Error} 当连接失败时抛出错误
118
- */
119
- async connect() {
120
- // 如果已经有连接,直接返回访问对象
121
- if (this.dbInstance) {
122
- return this.dbInstance;
123
- }
124
-
125
- // 防止并发连接:使用连接锁
126
- if (this._connecting) {
127
- return this._connecting;
128
- }
129
-
130
- try {
131
- this._connecting = (async () => {
132
- // 使用 ConnectionManager 建立连接
133
- const { collection, db, instance } = await ConnectionManager.connect(
134
- this.type,
135
- this.databaseName,
136
- this.config,
137
- this.cache,
138
- this.logger,
139
- this.defaults,
140
- );
141
-
142
- // 保存连接状态(关键:缓存对象,保证多次调用幂等返回同一形态/引用)
143
- this.dbInstance = { collection, db };
144
- this._adapter = instance;
145
-
146
- // 初始化分布式缓存失效器(如果配置了)
147
- // 🔧 修复:使用 _cacheConfig 读取 distributed 配置
148
- if (this._cacheConfig &&
149
- typeof this._cacheConfig.distributed === 'object' &&
150
- this._cacheConfig.distributed.enabled !== false) {
151
- try {
152
- // 🆕 自动从 cache.remote 提取 Redis 实例(如果未配置)
153
- let redis = this._cacheConfig.distributed.redis;
154
- if (!redis && !this._cacheConfig.distributed.redisUrl) {
155
- // 尝试从 remote 缓存适配器中获取 Redis 实例
156
- if (this.cache.remote && typeof this.cache.remote.getRedisInstance === 'function') {
157
- redis = this.cache.remote.getRedisInstance();
158
- if (this.logger) {
159
- this.logger.info('[DistributedCache] Auto-detected Redis from cache.remote');
160
- }
161
- }
162
- }
163
-
164
- this._cacheInvalidator = new DistributedCacheInvalidator({
165
- redisUrl: this._cacheConfig.distributed.redisUrl,
166
- redis,
167
- channel: this._cacheConfig.distributed.channel,
168
- instanceId: this._cacheConfig.distributed.instanceId,
169
- cache: this.cache,
170
- logger: this.logger
171
- });
172
-
173
- // 🆕 关键:将 invalidate 方法注入到 MultiLevelCache
174
- if (this.cache && typeof this.cache.setPublish === 'function') {
175
- this.cache.setPublish((msg) => {
176
- if (msg && msg.type === 'invalidate' && msg.pattern) {
177
- this._cacheInvalidator.invalidate(msg.pattern).catch((err) => {
178
- this.logger.error('❌ Broadcast invalidation failed:', err.message);
179
- });
180
- }
181
- });
182
- this.logger.info('✅ Distributed cache invalidator initialized', {
183
- channel: this._cacheInvalidator.channel,
184
- integrated: true
185
- });
186
- } else {
187
- this.logger.warn('⚠️ Cache does not support setPublish, distributed invalidation disabled');
188
- }
189
- } catch (error) {
190
- this.logger.error('❌ Failed to initialize distributed cache invalidator:', error.message);
191
- }
192
- }
193
-
194
- // 初始化事务管理器和缓存锁管理器
195
- if (this.type === 'mongodb' && instance.client) {
196
- // 检查是否配置了分布式事务锁
197
- const useDistributedLock = this._cacheConfig &&
198
- typeof this._cacheConfig.transaction === 'object' &&
199
- this._cacheConfig.transaction.distributedLock &&
200
- this._cacheConfig.transaction.distributedLock.redis;
201
-
202
- if (useDistributedLock) {
203
- // 使用分布式缓存锁管理器
204
- const DistributedCacheLockManager = require('./transaction/DistributedCacheLockManager');
205
- this._lockManager = new DistributedCacheLockManager({
206
- redis: this._cacheConfig.transaction.distributedLock.redis,
207
- lockKeyPrefix: this._cacheConfig.transaction.distributedLock.keyPrefix || 'monsqlize:cache:lock:',
208
- maxDuration: 300000,
209
- logger: this.logger
210
- });
211
- this.logger.info('✅ Distributed cache lock manager initialized');
212
- } else {
213
- // 使用本地缓存锁管理器
214
- this._lockManager = new CacheLockManager({
215
- logger: this.logger,
216
- maxDuration: 300000, // 锁最长持续5分钟
217
- cleanupInterval: 10000 // 每10秒清理一次
218
- });
219
- }
220
-
221
- // 将锁管理器注入到缓存
222
- if (this.cache && typeof this.cache.setLockManager === 'function') {
223
- this.cache.setLockManager(this._lockManager);
224
- }
225
-
226
- // 创建事务管理器
227
- this._transactionManager = new TransactionManager(
228
- instance, // 传入完整的 adapter 实例
229
- this.cache,
230
- this.logger,
231
- {
232
- lockManager: this._lockManager
233
- }
234
- );
235
-
236
- this.logger.info('✅ Transaction manager initialized', {
237
- hasClient: !!instance.client,
238
- hasLockManager: !!this._lockManager,
239
- isDistributed: useDistributedLock
240
- });
241
-
242
- // 🆕 v1.4.0: 挂载业务锁 API(仅在使用分布式锁时可用)
243
- if (this._lockManager && typeof this._lockManager.withLock === 'function') {
244
- this.dbInstance.withLock = (key, callback, opts) =>
245
- this._lockManager.withLock(key, callback, opts);
246
- this.dbInstance.acquireLock = (key, opts) =>
247
- this._lockManager.acquireLock(key, opts);
248
- this.dbInstance.tryAcquireLock = (key, opts) =>
249
- this._lockManager.tryAcquireLock(key, opts);
250
- this.dbInstance.getLockStats = () =>
251
- this._lockManager.getStats();
252
-
253
- this.logger.info('✅ Business lock API initialized', {
254
- isDistributed: useDistributedLock
255
- });
256
- } else {
257
- this.logger.warn('⚠️ Business lock API not available (Redis required)', {
258
- hasLockManager: !!this._lockManager,
259
- isDistributed: useDistributedLock
260
- });
261
- }
262
- } else {
263
- this.logger.warn('⚠️ Transaction manager not initialized', {
264
- type: this.type,
265
- hasClient: !!instance.client
266
- });
267
- }
268
-
269
- return this.dbInstance;
270
- })();
271
-
272
- const result = await this._connecting;
273
- this._connecting = null;
274
- return result;
275
- } catch (err) {
276
- this._connecting = null;
277
- throw err;
278
- }
279
- }
280
-
281
- /**
282
- * 获取底层缓存实例(用于查看统计或手动失效)
283
- * @returns {Object} 缓存实例
284
- */
285
- getCache() {
286
- return this.cache;
287
- }
288
-
289
- /**
290
- * 获取当前实例的默认配置(只读视图)
291
- * @returns {{maxTimeMS?:number, findLimit?:number, namespace?:object, slowQueryMs?:number}}
292
- */
293
- getDefaults() {
294
- return { ...this.defaults };
295
- }
296
-
297
- /**
298
- * 关闭底层数据库连接(释放资源)
299
- */
300
- async close() {
301
- // 清理分布式缓存失效器
302
- if (this._cacheInvalidator && typeof this._cacheInvalidator.close === 'function') {
303
- await this._cacheInvalidator.close();
304
- this._cacheInvalidator = null;
305
- }
306
-
307
- // 清理事务管理器
308
- if (this._transactionManager && typeof this._transactionManager.destroy === 'function') {
309
- await this._transactionManager.destroy();
310
- this._transactionManager = null;
311
- }
312
-
313
- // 清理锁管理器
314
- if (this._lockManager && typeof this._lockManager.destroy === 'function') {
315
- this._lockManager.destroy();
316
- this._lockManager = null;
317
- }
318
-
319
- // 关闭数据库连接
320
- if (this._adapter && typeof this._adapter.close === 'function') {
321
- await this._adapter.close();
322
- }
323
-
324
- // 清理状态
325
- this.dbInstance = null;
326
- this._adapter = null;
327
- this._connecting = null;
328
- }
329
-
330
- /**
331
- * 健康检查(适配器透传)
332
- */
333
- async health() {
334
- if (this._adapter && typeof this._adapter.health === 'function') {
335
- return this._adapter.health();
336
- }
337
- return { status: 'down', connected: false };
338
- }
339
-
340
- /**
341
- * 查询慢查询日志(v1.3.1+)
342
- * @param {Object} filter - 查询条件 { db, collection, operation }
343
- * @param {Object} options - 查询选项 { sort, limit, skip }
344
- * @returns {Promise<Array>} 慢查询日志列表
345
- */
346
- async getSlowQueryLogs(filter, options) {
347
- if (this._adapter && typeof this._adapter.getSlowQueryLogs === 'function') {
348
- return this._adapter.getSlowQueryLogs(filter, options);
349
- }
350
- throw new Error('Slow query log feature is not enabled or not supported');
351
- }
352
-
353
- /**
354
- * 事件订阅(适配器透传)
355
- * @param {'connected'|'closed'|'error'|'slow-query'} event
356
- * @param {(payload:any)=>void} handler
357
- */
358
- on(event, handler) {
359
- if (this._adapter && typeof this._adapter.on === 'function') {
360
- this._adapter.on(event, handler);
361
- }
362
- }
363
-
364
-
365
- /**
366
- * 启动一个事务会话(手动管理)
367
- * @param {Object} options - 事务选项
368
- * @param {Object} [options.readConcern] - 读关注级别 { level: 'majority' | 'local' | 'snapshot' }
369
- * @param {string} [options.readPreference] - 读偏好
370
- * @param {boolean} [options.causalConsistency=true] - 因果一致性
371
- * @param {number} [options.timeout=30000] - 事务超时时间(毫秒)
372
- * @returns {Promise<Transaction>}
373
- */
374
- async startSession(options = {}) {
375
- if (!this._transactionManager) {
376
- throw new Error('Connection not established. Call connect() first.');
377
- }
378
- return this._transactionManager.startSession(options);
379
- }
380
-
381
- /**
382
- * 使用事务执行操作(自动管理,推荐)
383
- * @param {Function} callback - 事务回调函数,接收 Transaction 对象作为参数
384
- * @param {Object} options - 事务选项(同 startSession)
385
- * @param {number} [options.maxRetries=3] - 最大重试次数
386
- * @param {number} [options.retryDelay=100] - 重试延迟(毫秒)
387
- * @param {number} [options.retryBackoff=2] - 重试退避系数
388
- * @returns {Promise<any>} 返回 callback 的返回值
389
- */
390
- async withTransaction(callback, options = {}) {
391
- if (!this._transactionManager) {
392
- throw new Error('Connection not established. Call connect() first.');
393
- }
394
- return this._transactionManager.withTransaction(callback, options);
395
- }
396
-
397
- /** 取消事件订阅(适配器透传) */
398
- off(event, handler) {
399
- if (this._adapter && typeof this._adapter.off === 'function') {
400
- this._adapter.off(event, handler);
401
- }
402
- }
403
-
404
- /**
405
- * 导出工具函数:创建 Redis 缓存适配器
406
- * @static
407
- * @param {import('ioredis').Redis | import('ioredis').Cluster} client - Redis客户端
408
- * @param {Object} [options] - 配置选项
409
- * @returns {import('./cache').CacheLike} Redis缓存适配器
410
- */
411
- static createRedisCacheAdapter(client, options) {
412
- return createRedisCacheAdapter(client, options);
413
- }
414
-
415
- /**
416
- * 初始化 ObjectId 自动转换配置
417
- * @private
418
- * @param {boolean|Object} config - 用户配置
419
- * @param {string} dbType - 数据库类型
420
- * @returns {Object} 配置对象
421
- */
422
- _initAutoConvertConfig(config, dbType) {
423
- // 只在 MongoDB 类型下启用
424
- if (dbType !== 'mongodb') {
425
- return { enabled: false };
426
- }
427
-
428
- // 默认配置
429
- const defaults = {
430
- enabled: true,
431
- excludeFields: [],
432
- customFieldPatterns: [],
433
- maxDepth: 10,
434
- logLevel: 'warn'
435
- };
436
-
437
- // 用户禁用
438
- if (config === false) {
439
- return { enabled: false };
440
- }
441
-
442
- // 用户自定义配置
443
- if (typeof config === 'object' && config !== null) {
444
- return {
445
- enabled: config.enabled !== false,
446
- excludeFields: Array.isArray(config.excludeFields)
447
- ? config.excludeFields
448
- : defaults.excludeFields,
449
- customFieldPatterns: Array.isArray(config.customFieldPatterns)
450
- ? config.customFieldPatterns
451
- : defaults.customFieldPatterns,
452
- maxDepth: typeof config.maxDepth === 'number'
453
- ? config.maxDepth
454
- : defaults.maxDepth,
455
- logLevel: config.logLevel || defaults.logLevel
456
- };
457
- }
458
-
459
- return defaults;
460
- }
461
- };