monsqlize 1.3.0 → 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 (172) hide show
  1. package/CHANGELOG.md +56 -60
  2. package/LICENSE +201 -21
  3. package/README.md +537 -1828
  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 +67 -69
  27. package/index.d.ts +0 -206
  28. package/index.mjs +0 -52
  29. package/lib/cache-invalidation.js +0 -279
  30. package/lib/cache.js +0 -530
  31. package/lib/common/cursor.js +0 -59
  32. package/lib/common/docs-urls.js +0 -73
  33. package/lib/common/index-options.js +0 -223
  34. package/lib/common/log.js +0 -61
  35. package/lib/common/namespace.js +0 -22
  36. package/lib/common/normalize.js +0 -34
  37. package/lib/common/page-result.js +0 -43
  38. package/lib/common/runner.js +0 -57
  39. package/lib/common/server-features.js +0 -232
  40. package/lib/common/shape-builders.js +0 -27
  41. package/lib/common/validation.js +0 -113
  42. package/lib/connect.js +0 -99
  43. package/lib/constants.js +0 -55
  44. package/lib/count-queue.js +0 -188
  45. package/lib/distributed-cache-invalidator.js +0 -260
  46. package/lib/errors.js +0 -168
  47. package/lib/expression/cache/ExpressionCache.js +0 -114
  48. package/lib/expression/compiler/ExpressionCompiler.js +0 -1090
  49. package/lib/expression/compiler/ExpressionCompilerExtensions.js +0 -531
  50. package/lib/expression/detector.js +0 -84
  51. package/lib/expression/factory.js +0 -29
  52. package/lib/expression/index.js +0 -19
  53. package/lib/function-cache.js +0 -533
  54. package/lib/index.js +0 -1251
  55. package/lib/infrastructure/ConnectionPoolManager.js +0 -464
  56. package/lib/infrastructure/HealthChecker.js +0 -281
  57. package/lib/infrastructure/PoolConfig.js +0 -199
  58. package/lib/infrastructure/PoolSelector.js +0 -225
  59. package/lib/infrastructure/PoolStats.js +0 -244
  60. package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -212
  61. package/lib/infrastructure/ssh-tunnel.js +0 -41
  62. package/lib/infrastructure/uri-parser.js +0 -36
  63. package/lib/lock/Lock.js +0 -67
  64. package/lib/lock/errors.js +0 -28
  65. package/lib/lock/index.js +0 -13
  66. package/lib/logger.js +0 -225
  67. package/lib/model/examples/test.js +0 -311
  68. package/lib/model/features/defaults.js +0 -161
  69. package/lib/model/features/populate.js +0 -568
  70. package/lib/model/features/relations.js +0 -120
  71. package/lib/model/features/soft-delete.js +0 -349
  72. package/lib/model/features/version.js +0 -157
  73. package/lib/model/features/virtuals.js +0 -219
  74. package/lib/model/index.js +0 -1265
  75. package/lib/mongodb/common/accessor-helpers.js +0 -59
  76. package/lib/mongodb/common/agg-pipeline.js +0 -36
  77. package/lib/mongodb/common/aggregation-validator.js +0 -127
  78. package/lib/mongodb/common/iid.js +0 -28
  79. package/lib/mongodb/common/lexicographic-expr.js +0 -53
  80. package/lib/mongodb/common/shape.js +0 -32
  81. package/lib/mongodb/common/sort.js +0 -39
  82. package/lib/mongodb/common/transaction-aware.js +0 -25
  83. package/lib/mongodb/connect.js +0 -234
  84. package/lib/mongodb/index.js +0 -639
  85. package/lib/mongodb/management/admin-ops.js +0 -200
  86. package/lib/mongodb/management/bookmark-ops.js +0 -167
  87. package/lib/mongodb/management/cache-ops.js +0 -50
  88. package/lib/mongodb/management/collection-ops.js +0 -387
  89. package/lib/mongodb/management/database-ops.js +0 -202
  90. package/lib/mongodb/management/index-ops.js +0 -475
  91. package/lib/mongodb/management/index.js +0 -17
  92. package/lib/mongodb/management/namespace.js +0 -31
  93. package/lib/mongodb/management/validation-ops.js +0 -268
  94. package/lib/mongodb/queries/aggregate.js +0 -172
  95. package/lib/mongodb/queries/chain.js +0 -631
  96. package/lib/mongodb/queries/count.js +0 -99
  97. package/lib/mongodb/queries/distinct.js +0 -78
  98. package/lib/mongodb/queries/find-and-count.js +0 -193
  99. package/lib/mongodb/queries/find-by-ids.js +0 -236
  100. package/lib/mongodb/queries/find-one-by-id.js +0 -171
  101. package/lib/mongodb/queries/find-one.js +0 -71
  102. package/lib/mongodb/queries/find-page.js +0 -618
  103. package/lib/mongodb/queries/find.js +0 -171
  104. package/lib/mongodb/queries/index.js +0 -51
  105. package/lib/mongodb/queries/watch.js +0 -538
  106. package/lib/mongodb/writes/common/batch-retry.js +0 -65
  107. package/lib/mongodb/writes/delete-batch.js +0 -323
  108. package/lib/mongodb/writes/delete-many.js +0 -181
  109. package/lib/mongodb/writes/delete-one.js +0 -173
  110. package/lib/mongodb/writes/find-one-and-delete.js +0 -203
  111. package/lib/mongodb/writes/find-one-and-replace.js +0 -239
  112. package/lib/mongodb/writes/find-one-and-update.js +0 -240
  113. package/lib/mongodb/writes/increment-one.js +0 -259
  114. package/lib/mongodb/writes/index.js +0 -46
  115. package/lib/mongodb/writes/insert-batch.js +0 -508
  116. package/lib/mongodb/writes/insert-many.js +0 -223
  117. package/lib/mongodb/writes/insert-one.js +0 -169
  118. package/lib/mongodb/writes/replace-one.js +0 -226
  119. package/lib/mongodb/writes/result-handler.js +0 -237
  120. package/lib/mongodb/writes/update-batch.js +0 -416
  121. package/lib/mongodb/writes/update-many.js +0 -275
  122. package/lib/mongodb/writes/update-one.js +0 -273
  123. package/lib/mongodb/writes/upsert-one.js +0 -203
  124. package/lib/multi-level-cache.js +0 -244
  125. package/lib/operators.js +0 -330
  126. package/lib/redis-cache-adapter.js +0 -267
  127. package/lib/saga/SagaContext.js +0 -67
  128. package/lib/saga/SagaDefinition.js +0 -32
  129. package/lib/saga/SagaExecutor.js +0 -201
  130. package/lib/saga/SagaOrchestrator.js +0 -186
  131. package/lib/saga/index.js +0 -11
  132. package/lib/slow-query-log/base-storage.js +0 -70
  133. package/lib/slow-query-log/batch-queue.js +0 -97
  134. package/lib/slow-query-log/config-manager.js +0 -196
  135. package/lib/slow-query-log/index.js +0 -238
  136. package/lib/slow-query-log/mongodb-storage.js +0 -324
  137. package/lib/slow-query-log/query-hash.js +0 -39
  138. package/lib/sync/ChangeStreamSyncManager.js +0 -405
  139. package/lib/sync/ResumeTokenStore.js +0 -192
  140. package/lib/sync/SyncConfig.js +0 -127
  141. package/lib/sync/SyncTarget.js +0 -240
  142. package/lib/sync/index.js +0 -20
  143. package/lib/transaction/CacheLockManager.js +0 -162
  144. package/lib/transaction/DistributedCacheLockManager.js +0 -475
  145. package/lib/transaction/Transaction.js +0 -315
  146. package/lib/transaction/TransactionManager.js +0 -267
  147. package/lib/transaction/index.js +0 -11
  148. package/lib/utils/objectid-converter.js +0 -632
  149. package/types/README.md +0 -122
  150. package/types/base.ts +0 -94
  151. package/types/batch.ts +0 -187
  152. package/types/cache.ts +0 -71
  153. package/types/chain.ts +0 -254
  154. package/types/collection.ts +0 -357
  155. package/types/expression.ts +0 -109
  156. package/types/function-cache.d.ts +0 -135
  157. package/types/lock.ts +0 -95
  158. package/types/model/definition.ts +0 -152
  159. package/types/model/index.ts +0 -10
  160. package/types/model/instance.ts +0 -121
  161. package/types/model/relations.ts +0 -121
  162. package/types/model/virtuals.ts +0 -32
  163. package/types/monsqlize.ts +0 -245
  164. package/types/options.ts +0 -192
  165. package/types/pagination.ts +0 -154
  166. package/types/pool.ts +0 -125
  167. package/types/query.ts +0 -71
  168. package/types/saga.ts +0 -125
  169. package/types/stream.ts +0 -64
  170. package/types/sync.ts +0 -79
  171. package/types/transaction.ts +0 -79
  172. package/types/write.ts +0 -77
@@ -1,281 +0,0 @@
1
- /**
2
- * HealthChecker - 连接池健康检查器
3
- *
4
- * 定期检查连接池健康状态,自动标记 up/down
5
- * 支持故障检测和自动恢复
6
- *
7
- * @module lib/infrastructure/HealthChecker
8
- * @since v1.0.8
9
- */
10
-
11
- /**
12
- * 健康状态
13
- * @typedef {Object} HealthStatus
14
- * @property {'up'|'down'|'checking'} status - 状态
15
- * @property {Date} lastCheck - 最后检查时间
16
- * @property {Error} [lastError] - 最后错误
17
- * @property {number} consecutiveFailures - 连续失败次数
18
- */
19
-
20
- /**
21
- * 健康检查器
22
- */
23
- class HealthChecker {
24
- /**
25
- * 构造函数
26
- *
27
- * @param {Object} options - 配置选项
28
- * @param {ConnectionPoolManager} options.poolManager - 连接池管理器
29
- * @param {Object} options.logger - 日志记录器
30
- */
31
- constructor(options = {}) {
32
- this._poolManager = options.poolManager;
33
- this._logger = options.logger || console;
34
-
35
- this._healthStatus = new Map(); // Map<poolName, HealthStatus>
36
- this._checkConfigs = new Map(); // Map<poolName, CheckConfig>
37
- this._intervals = new Map(); // Map<poolName, NodeJS.Timeout>
38
-
39
- this._started = false;
40
- }
41
-
42
- /**
43
- * 注册连接池
44
- *
45
- * @param {string} poolName - 连接池名称
46
- * @param {Object} config - 健康检查配置
47
- */
48
- register(poolName, config) {
49
- this._checkConfigs.set(poolName, config);
50
-
51
- // 初始化健康状态
52
- this._healthStatus.set(poolName, {
53
- status: 'up',
54
- lastCheck: new Date(),
55
- consecutiveFailures: 0
56
- });
57
-
58
- // 如果已启动,立即开始检查
59
- if (this._started) {
60
- this._startCheckForPool(poolName, config);
61
- }
62
- }
63
-
64
- /**
65
- * 注销连接池
66
- *
67
- * @param {string} poolName - 连接池名称
68
- */
69
- unregister(poolName) {
70
- // 停止检查
71
- this._stopCheckForPool(poolName);
72
-
73
- // 删除状态和配置
74
- this._healthStatus.delete(poolName);
75
- this._checkConfigs.delete(poolName);
76
- }
77
-
78
- /**
79
- * 启动所有健康检查
80
- */
81
- start() {
82
- if (this._started) {
83
- return;
84
- }
85
-
86
- this._started = true;
87
-
88
- // 为所有已注册的连接池启动检查
89
- for (const [poolName, config] of this._checkConfigs.entries()) {
90
- this._startCheckForPool(poolName, config);
91
- }
92
-
93
- this._logger.info('[HealthChecker] 健康检查已启动');
94
- }
95
-
96
- /**
97
- * 停止所有健康检查
98
- */
99
- stop() {
100
- if (!this._started) {
101
- return;
102
- }
103
-
104
- this._started = false;
105
-
106
- // 停止所有检查
107
- for (const poolName of this._intervals.keys()) {
108
- this._stopCheckForPool(poolName);
109
- }
110
-
111
- this._logger.info('[HealthChecker] 健康检查已停止');
112
- }
113
-
114
- /**
115
- * 为单个连接池启动检查
116
- *
117
- * @private
118
- */
119
- _startCheckForPool(poolName, config) {
120
- // 清除现有定时器
121
- this._stopCheckForPool(poolName);
122
-
123
- // 创建新定时器
124
- const interval = setInterval(async () => {
125
- await this._checkPool(poolName, config);
126
- }, config.interval);
127
-
128
- this._intervals.set(poolName, interval);
129
-
130
- // 立即执行一次检查
131
- setImmediate(async () => {
132
- await this._checkPool(poolName, config);
133
- });
134
- }
135
-
136
- /**
137
- * 为单个连接池停止检查
138
- *
139
- * @private
140
- */
141
- _stopCheckForPool(poolName) {
142
- const interval = this._intervals.get(poolName);
143
- if (interval) {
144
- clearInterval(interval);
145
- this._intervals.delete(poolName);
146
- }
147
- }
148
-
149
- /**
150
- * 检查单个连接池
151
- *
152
- * @private
153
- */
154
- async _checkPool(poolName, config) {
155
- const status = this._healthStatus.get(poolName);
156
- if (!status) {
157
- return;
158
- }
159
-
160
- // 更新状态为检查中
161
- status.status = 'checking';
162
- status.lastCheck = new Date();
163
-
164
- const retries = config.retries || 3;
165
- let success = false;
166
- let lastError = null;
167
-
168
- // 重试机制
169
- for (let attempt = 0; attempt < retries; attempt++) {
170
- try {
171
- const isHealthy = await this._pingPool(poolName, config.timeout);
172
- if (isHealthy) {
173
- success = true;
174
- break;
175
- }
176
- } catch (error) {
177
- lastError = error;
178
- }
179
-
180
- // 等待后重试
181
- if (attempt < retries - 1) {
182
- await this._sleep(1000);
183
- }
184
- }
185
-
186
- if (success) {
187
- // 健康检查成功
188
- const wasDown = status.status === 'down';
189
-
190
- status.status = 'up';
191
- status.consecutiveFailures = 0;
192
- delete status.lastError;
193
-
194
- if (wasDown) {
195
- this._logger.info(`[HealthChecker] 连接池已恢复: ${poolName}`);
196
- // TODO: 触发 onPoolUp 事件
197
- }
198
- } else {
199
- // 健康检查失败
200
- status.consecutiveFailures++;
201
- status.lastError = lastError;
202
-
203
- // 连续失败达到阈值,标记为 down
204
- if (status.consecutiveFailures >= retries) {
205
- const wasUp = status.status === 'up';
206
-
207
- status.status = 'down';
208
-
209
- if (wasUp) {
210
- this._logger.warn(`[HealthChecker] 连接池已故障: ${poolName}`, {
211
- consecutiveFailures: status.consecutiveFailures,
212
- error: lastError?.message
213
- });
214
- // TODO: 触发 onPoolDown 事件
215
- }
216
- }
217
- }
218
- }
219
-
220
- /**
221
- * Ping 连接池
222
- *
223
- * @private
224
- * @param {string} poolName - 连接池名称
225
- * @param {number} timeout - 超时时间
226
- * @returns {Promise<boolean>}
227
- */
228
- async _pingPool(poolName, timeout) {
229
- const client = this._poolManager._getPool(poolName);
230
- if (!client) {
231
- return false;
232
- }
233
-
234
- try {
235
- // 使用 Promise.race 实现超时
236
- const pingPromise = client.db('admin').command({ ping: 1 });
237
- const timeoutPromise = new Promise((_, reject) => {
238
- setTimeout(() => reject(new Error('Ping timeout')), timeout);
239
- });
240
-
241
- await Promise.race([pingPromise, timeoutPromise]);
242
- return true;
243
- } catch (error) {
244
- return false;
245
- }
246
- }
247
-
248
- /**
249
- * 获取连接池健康状态
250
- *
251
- * @param {string} poolName - 连接池名称
252
- * @returns {HealthStatus|null}
253
- */
254
- getStatus(poolName) {
255
- return this._healthStatus.get(poolName) || null;
256
- }
257
-
258
- /**
259
- * 获取所有健康状态
260
- *
261
- * @returns {Map<string, HealthStatus>}
262
- */
263
- getAllStatus() {
264
- return new Map(this._healthStatus);
265
- }
266
-
267
- /**
268
- * 睡眠
269
- *
270
- * @private
271
- * @param {number} ms - 毫秒
272
- * @returns {Promise<void>}
273
- */
274
- _sleep(ms) {
275
- return new Promise(resolve => setTimeout(resolve, ms));
276
- }
277
- }
278
-
279
- module.exports = HealthChecker;
280
-
281
-
@@ -1,199 +0,0 @@
1
- /**
2
- * PoolConfig - 连接池配置验证器
3
- *
4
- * 验证连接池配置的有效性
5
- *
6
- * @module lib/infrastructure/PoolConfig
7
- * @since v1.0.8
8
- */
9
-
10
- /**
11
- * 验证连接池配置
12
- *
13
- * @param {Object} config - 连接池配置
14
- * @throws {Error} 如果配置无效
15
- */
16
- function validatePoolConfig(config) {
17
- if (!config || typeof config !== 'object') {
18
- throw new Error('Pool config must be an object');
19
- }
20
-
21
- // 必需字段
22
- if (!config.name || typeof config.name !== 'string') {
23
- throw new Error('Pool config.name is required and must be a string');
24
- }
25
-
26
- if (!config.uri || typeof config.uri !== 'string') {
27
- throw new Error('Pool config.uri is required and must be a string');
28
- }
29
-
30
- // 验证 URI 格式
31
- if (!config.uri.startsWith('mongodb://') && !config.uri.startsWith('mongodb+srv://')) {
32
- throw new Error('Pool config.uri must start with mongodb:// or mongodb+srv://');
33
- }
34
-
35
- // 验证 role
36
- if (config.role) {
37
- const validRoles = ['primary', 'secondary', 'analytics', 'custom'];
38
- if (!validRoles.includes(config.role)) {
39
- throw new Error(`Pool config.role must be one of: ${validRoles.join(', ')}`);
40
- }
41
- }
42
-
43
- // 验证 weight
44
- if (config.weight !== undefined) {
45
- if (typeof config.weight !== 'number' || config.weight < 0) {
46
- throw new Error('Pool config.weight must be a non-negative number');
47
- }
48
- }
49
-
50
- // 验证 options
51
- if (config.options) {
52
- if (typeof config.options !== 'object') {
53
- throw new Error('Pool config.options must be an object');
54
- }
55
-
56
- // 验证数值选项
57
- const numericOptions = [
58
- 'maxPoolSize',
59
- 'minPoolSize',
60
- 'maxIdleTimeMS',
61
- 'waitQueueTimeoutMS',
62
- 'connectTimeoutMS',
63
- 'serverSelectionTimeoutMS'
64
- ];
65
-
66
- for (const key of numericOptions) {
67
- if (config.options[key] !== undefined) {
68
- if (typeof config.options[key] !== 'number' || config.options[key] < 0) {
69
- throw new Error(`Pool config.options.${key} must be a non-negative number`);
70
- }
71
- }
72
- }
73
- }
74
-
75
- // 验证 healthCheck
76
- if (config.healthCheck) {
77
- if (typeof config.healthCheck !== 'object') {
78
- throw new Error('Pool config.healthCheck must be an object');
79
- }
80
-
81
- if (config.healthCheck.enabled !== undefined && typeof config.healthCheck.enabled !== 'boolean') {
82
- throw new Error('Pool config.healthCheck.enabled must be a boolean');
83
- }
84
-
85
- const numericHealthOptions = ['interval', 'timeout', 'retries'];
86
- for (const key of numericHealthOptions) {
87
- if (config.healthCheck[key] !== undefined) {
88
- if (typeof config.healthCheck[key] !== 'number' || config.healthCheck[key] < 0) {
89
- throw new Error(`Pool config.healthCheck.${key} must be a non-negative number`);
90
- }
91
- }
92
- }
93
- }
94
-
95
- // 验证 tags
96
- if (config.tags) {
97
- if (!Array.isArray(config.tags)) {
98
- throw new Error('Pool config.tags must be an array');
99
- }
100
-
101
- for (const tag of config.tags) {
102
- if (typeof tag !== 'string') {
103
- throw new Error('Pool config.tags must be an array of strings');
104
- }
105
- }
106
- }
107
- }
108
-
109
- /**
110
- * 验证连接池配置(返回错误数组)
111
- *
112
- * @param {Object} config - 连接池配置
113
- * @returns {Array<string>} 错误消息数组,空数组表示验证通过
114
- */
115
- function validate(config) {
116
- const errors = [];
117
-
118
- if (!config || typeof config !== 'object') {
119
- errors.push('Pool config must be an object');
120
- return errors;
121
- }
122
-
123
- // 必需字段
124
- if (!config.name || typeof config.name !== 'string') {
125
- errors.push('Pool config.name is required and must be a string');
126
- }
127
-
128
- if (!config.uri || typeof config.uri !== 'string') {
129
- errors.push('Pool config.uri is required and must be a string');
130
- } else {
131
- // 验证 URI 格式
132
- if (!config.uri.startsWith('mongodb://') && !config.uri.startsWith('mongodb+srv://')) {
133
- errors.push('Pool config.uri must start with mongodb:// or mongodb+srv://');
134
- }
135
- }
136
-
137
- // 验证 role
138
- if (config.role) {
139
- const validRoles = ['primary', 'secondary', 'analytics', 'custom'];
140
- if (!validRoles.includes(config.role)) {
141
- errors.push(`Pool config.role must be one of: ${validRoles.join(', ')}`);
142
- }
143
- }
144
-
145
- // 验证 weight
146
- if (config.weight !== undefined) {
147
- if (typeof config.weight !== 'number' || config.weight < 0) {
148
- errors.push('Pool config.weight must be a non-negative number');
149
- }
150
- }
151
-
152
- // 验证 options
153
- if (config.options && typeof config.options !== 'object') {
154
- errors.push('Pool config.options must be an object');
155
- }
156
-
157
- // 验证 healthCheck
158
- if (config.healthCheck) {
159
- if (typeof config.healthCheck !== 'object') {
160
- errors.push('Pool config.healthCheck must be an object');
161
- } else {
162
- if (config.healthCheck.enabled !== undefined && typeof config.healthCheck.enabled !== 'boolean') {
163
- errors.push('Pool config.healthCheck.enabled must be a boolean');
164
- }
165
-
166
- const numericHealthOptions = ['interval', 'timeout', 'retries'];
167
- for (const key of numericHealthOptions) {
168
- if (config.healthCheck[key] !== undefined) {
169
- if (typeof config.healthCheck[key] !== 'number' || config.healthCheck[key] < 0) {
170
- errors.push(`Pool config.healthCheck.${key} must be a non-negative number`);
171
- }
172
- }
173
- }
174
- }
175
- }
176
-
177
- // 验证 tags
178
- if (config.tags) {
179
- if (!Array.isArray(config.tags)) {
180
- errors.push('Pool config.tags must be an array');
181
- } else {
182
- for (const tag of config.tags) {
183
- if (typeof tag !== 'string') {
184
- errors.push('Pool config.tags must be an array of strings');
185
- break;
186
- }
187
- }
188
- }
189
- }
190
-
191
- return errors;
192
- }
193
-
194
- module.exports = {
195
- validatePoolConfig,
196
- validate
197
- };
198
-
199
-
@@ -1,225 +0,0 @@
1
- /**
2
- * PoolSelector - 连接池智能选择器
3
- *
4
- * 根据策略选择合适的连接池
5
- * 支持:auto(自动)、roundRobin(轮询)、leastConnections(最少连接)、
6
- * weighted(加权)、manual(手动)
7
- *
8
- * @module lib/infrastructure/PoolSelector
9
- * @since v1.0.8
10
- */
11
-
12
- /**
13
- * 连接池选择器
14
- */
15
- class PoolSelector {
16
- /**
17
- * 构造函数
18
- *
19
- * @param {Object} options - 配置选项
20
- * @param {string} options.strategy - 选择策略
21
- * @param {Object} options.logger - 日志记录器
22
- */
23
- constructor(options = {}) {
24
- this._strategy = options.strategy || 'auto';
25
- this._logger = options.logger || console;
26
- this._roundRobinIndex = new Map(); // 轮询索引 Map<role, number>
27
- }
28
-
29
- /**
30
- * 选择连接池
31
- *
32
- * @param {Array<PoolConfig>} pools - 候选连接池列表
33
- * @param {Object} context - 上下文
34
- * @param {string} context.operation - 操作类型 ('read' | 'write')
35
- * @param {Map} context.healthStatus - 健康状态
36
- * @param {Object} context.stats - 统计信息
37
- * @param {Object} [context.poolPreference] - 连接池偏好
38
- * @returns {string} 选中的连接池名称
39
- * @throws {Error} 如果无可用连接池
40
- */
41
- select(pools, context) {
42
- if (!pools || pools.length === 0) {
43
- throw new Error('No available pools');
44
- }
45
-
46
- // 根据策略选择
47
- switch (this._strategy) {
48
- case 'auto':
49
- return this._selectByAuto(pools, context);
50
-
51
- case 'roundRobin':
52
- return this._selectByRoundRobin(pools, context);
53
-
54
- case 'leastConnections':
55
- return this._selectByLeastConnections(pools, context);
56
-
57
- case 'weighted':
58
- return this._selectByWeighted(pools, context);
59
-
60
- case 'manual':
61
- // 手动模式不应该到这里(应该在 ConnectionPoolManager 处理)
62
- return pools[0].name;
63
-
64
- default:
65
- this._logger.warn(`[PoolSelector] 未知策略: ${this._strategy},使用 auto`);
66
- return this._selectByAuto(pools, context);
67
- }
68
- }
69
-
70
- /**
71
- * 自动策略:读写分离 + 负载均衡
72
- *
73
- * @private
74
- */
75
- _selectByAuto(pools, context) {
76
- const { operation, poolPreference } = context;
77
-
78
- // 1. 根据操作类型过滤
79
- let candidates = pools;
80
-
81
- if (operation === 'read') {
82
- // 读操作优先使用 secondary
83
- const secondaries = pools.filter(p => p.role === 'secondary');
84
- if (secondaries.length > 0) {
85
- candidates = secondaries;
86
- }
87
- } else if (operation === 'write') {
88
- // 写操作优先使用 primary
89
- const primaries = pools.filter(p => p.role === 'primary');
90
- if (primaries.length > 0) {
91
- candidates = primaries;
92
- }
93
- }
94
-
95
- // 2. 根据 poolPreference 过滤
96
- if (poolPreference) {
97
- if (poolPreference.role) {
98
- const filtered = candidates.filter(p => p.role === poolPreference.role);
99
- if (filtered.length > 0) {
100
- candidates = filtered;
101
- }
102
- }
103
-
104
- if (poolPreference.tags && poolPreference.tags.length > 0) {
105
- const filtered = candidates.filter(p => {
106
- if (!p.tags) return false;
107
- return poolPreference.tags.some(tag => p.tags.includes(tag));
108
- });
109
- if (filtered.length > 0) {
110
- candidates = filtered;
111
- }
112
- }
113
- }
114
-
115
- // 3. 如果只剩一个,直接返回
116
- if (candidates.length === 1) {
117
- return candidates[0].name;
118
- }
119
-
120
- // 4. 多个候选,使用加权负载均衡
121
- return this._selectByWeighted(candidates, context);
122
- }
123
-
124
- /**
125
- * 轮询策略
126
- *
127
- * @private
128
- */
129
- _selectByRoundRobin(pools, context) {
130
- const { operation } = context;
131
- const key = operation || 'default';
132
-
133
- // 获取当前索引
134
- let index = this._roundRobinIndex.get(key) || 0;
135
-
136
- // 选择连接池
137
- const pool = pools[index % pools.length];
138
-
139
- // 更新索引
140
- this._roundRobinIndex.set(key, (index + 1) % pools.length);
141
-
142
- return pool.name;
143
- }
144
-
145
- /**
146
- * 最少连接策略
147
- *
148
- * @private
149
- */
150
- _selectByLeastConnections(pools, context) {
151
- const { stats } = context;
152
-
153
- if (!stats) {
154
- // 无统计信息,降级到轮询
155
- return this._selectByRoundRobin(pools, context);
156
- }
157
-
158
- let minConnections = Infinity;
159
- let selectedPool = pools[0];
160
-
161
- for (const pool of pools) {
162
- const poolStats = stats[pool.name];
163
- if (!poolStats) continue;
164
-
165
- const connections = poolStats.connections || 0;
166
- if (connections < minConnections) {
167
- minConnections = connections;
168
- selectedPool = pool;
169
- }
170
- }
171
-
172
- return selectedPool.name;
173
- }
174
-
175
- /**
176
- * 加权策略
177
- *
178
- * @private
179
- */
180
- _selectByWeighted(pools, context) {
181
- // 计算总权重
182
- let totalWeight = 0;
183
- for (const pool of pools) {
184
- totalWeight += (pool.weight || 1);
185
- }
186
-
187
- // 随机选择
188
- let random = Math.random() * totalWeight;
189
-
190
- for (const pool of pools) {
191
- const weight = pool.weight || 1;
192
- random -= weight;
193
-
194
- if (random <= 0) {
195
- return pool.name;
196
- }
197
- }
198
-
199
- // 降级(不应该到这里)
200
- return pools[0].name;
201
- }
202
-
203
- /**
204
- * 设置策略
205
- *
206
- * @param {string} strategy - 策略名称
207
- */
208
- setStrategy(strategy) {
209
- this._strategy = strategy;
210
- this._logger.info(`[PoolSelector] 策略已更改: ${strategy}`);
211
- }
212
-
213
- /**
214
- * 获取当前策略
215
- *
216
- * @returns {string}
217
- */
218
- getStrategy() {
219
- return this._strategy;
220
- }
221
- }
222
-
223
- module.exports = PoolSelector;
224
-
225
-