@maiyunnet/kebab 9.29.6 → 10.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 (52) hide show
  1. package/abox/proxy.js +24 -2
  2. package/abox/response.js +36 -17
  3. package/abox/session-login.js +1 -13
  4. package/doc/kebab-rag.md +1522 -1034
  5. package/index.d.ts +12 -1
  6. package/index.js +1 -1
  7. package/lib/ai.d.ts +4 -0
  8. package/lib/ai.js +32 -16
  9. package/lib/cookie.d.ts +2 -0
  10. package/lib/cookie.js +47 -45
  11. package/lib/core.d.ts +26 -0
  12. package/lib/core.js +36 -13
  13. package/lib/cron.js +1 -8
  14. package/lib/crypto.js +20 -6
  15. package/lib/db/conn.js +1 -0
  16. package/lib/fs.js +78 -31
  17. package/lib/kv.d.ts +182 -79
  18. package/lib/kv.js +518 -214
  19. package/lib/s3.d.ts +2 -0
  20. package/lib/s3.js +14 -27
  21. package/lib/session.d.ts +7 -0
  22. package/lib/session.js +23 -2
  23. package/lib/socket.d.ts +4 -1
  24. package/lib/socket.js +1 -0
  25. package/lib/sql.d.ts +0 -5
  26. package/lib/sql.js +48 -12
  27. package/lib/text.d.ts +10 -5
  28. package/lib/text.js +22 -12
  29. package/lib/turnstile.d.ts +6 -0
  30. package/lib/turnstile.js +16 -9
  31. package/lib/undici.d.ts +7 -1
  32. package/lib/undici.js +72 -36
  33. package/lib/ws.d.ts +1 -1
  34. package/lib/ws.js +85 -128
  35. package/lib/zip.js +46 -45
  36. package/package.json +2 -2
  37. package/sys/child.js +178 -146
  38. package/sys/cmd.js +196 -197
  39. package/sys/ctr.d.ts +14 -14
  40. package/sys/ctr.js +145 -59
  41. package/sys/master.js +111 -80
  42. package/sys/mod.d.ts +8 -2
  43. package/sys/mod.js +23 -11
  44. package/sys/monitor/files.d.ts +2 -1
  45. package/sys/monitor/files.js +77 -21
  46. package/sys/monitor/watchdog.d.ts +7 -0
  47. package/sys/monitor/watchdog.js +311 -203
  48. package/sys/monitor.d.ts +59 -54
  49. package/sys/monitor.js +742 -681
  50. package/sys/route.d.ts +4 -4
  51. package/sys/route.js +93 -52
  52. package/www/example/ctr/test.js +8 -8
package/lib/kv.js CHANGED
@@ -1,17 +1,104 @@
1
1
  /**
2
2
  * Project: Kebab, User: JianSuoQiYue
3
3
  * Date: 2019-5-30 19:25:22
4
- * Last: 2020-3-28 18:54:04, 2022-09-12 23:24:45, 2022-09-22 01:06:22, 2024-2-21 13:32:56, 2024-8-21 16:59:57, 2025-11-6 14:56:45
5
4
  */
6
5
  // --- 第三方 ---
7
- import * as redis from '@litert/redis';
6
+ import * as redis from 'redis';
8
7
  import * as lText from '#kebab/lib/text.js';
9
8
  import * as lCore from '#kebab/lib/core.js';
10
9
  import * as sCtr from '#kebab/sys/ctr.js';
11
- /** --- 连接列表(同一个 host、port、index 只有一个连接) --- */
10
+ /** --- 相同地址、数据库和凭据共用一次连接初始化 --- */
12
11
  const connections = [];
13
12
  /**
14
- * --- 键值存储操作类 ---
13
+ * --- 生成 TLS 配置的缓存区分键,避免不同证书或 servername 误用同一连接 ---
14
+ * @param tlsOpt TLS 配置
15
+ */
16
+ function getTlsKey(tlsOpt) {
17
+ if (!tlsOpt) {
18
+ return '';
19
+ }
20
+ if (tlsOpt === true) {
21
+ return '1';
22
+ }
23
+ const keys = Object.keys(tlsOpt).sort();
24
+ const normalized = {};
25
+ for (const key of keys) {
26
+ const val = tlsOpt[key];
27
+ normalized[key] = Buffer.isBuffer(val) ? val.toString('base64') : val;
28
+ }
29
+ return lText.stringifyJson(normalized);
30
+ }
31
+ /**
32
+ * --- 解析 CONFIG GET 返回值中的目标配置项 ---
33
+ * @param reply RESP2 数组或键值对象
34
+ * @param key 配置项名
35
+ */
36
+ function readConfigValue(reply, key) {
37
+ if (Array.isArray(reply)) {
38
+ for (let i = 0; i + 1 < reply.length; i += 2) {
39
+ if (String(reply[i]).toLowerCase() === key) {
40
+ return String(reply[i + 1]);
41
+ }
42
+ }
43
+ return null;
44
+ }
45
+ if (reply && typeof reply === 'object') {
46
+ const record = reply;
47
+ if (Object.hasOwn(record, key)) {
48
+ return String(record[key]);
49
+ }
50
+ }
51
+ return null;
52
+ }
53
+ /**
54
+ * --- 校验非 0 库在 Kvrocks 上是否真实支持多库隔离,防止静默串库 ---
55
+ * @param conn 已建连客户端
56
+ * @param dbIndex 目标数据库编号(> 0)
57
+ */
58
+ async function verifyMultiDbSupport(conn, dbIndex) {
59
+ let info;
60
+ try {
61
+ info = await conn.sendCommand(['INFO', 'server']);
62
+ }
63
+ catch {
64
+ // --- 部分受限 Redis 环境禁用了 INFO,按常规 Redis 放行 ---
65
+ return true;
66
+ }
67
+ if (typeof info !== 'string' || !info.includes('kvrocks_version:')) {
68
+ return true;
69
+ }
70
+ // --- 确认是 Kvrocks 后,校验 redis-databases 配置 ---
71
+ try {
72
+ const reply = await conn.sendCommand(['CONFIG', 'GET', 'redis-databases']);
73
+ const raw = readConfigValue(reply, 'redis-databases');
74
+ const count = raw === null ? NaN : Number.parseInt(raw, 10);
75
+ if (Number.isInteger(count)) {
76
+ if (count <= 0 || dbIndex >= count) {
77
+ lCore.display(`[KV] Kvrocks redis-databases=${count} does not support index=${dbIndex}; ` +
78
+ 'enable redis-databases in Kvrocks or set kv.dbPre=true.');
79
+ return false;
80
+ }
81
+ return true;
82
+ }
83
+ }
84
+ catch {
85
+ // --- CONFIG 被禁用时,退化检查 CLIENT INFO 中的 namespace ---
86
+ }
87
+ try {
88
+ const clientInfo = await conn.sendCommand(['CLIENT', 'INFO']);
89
+ if (typeof clientInfo === 'string' && new RegExp(`(?:^|\\s)namespace=db${dbIndex}(?:\\s|$)`).test(clientInfo)) {
90
+ return true;
91
+ }
92
+ }
93
+ catch {
94
+ // --- 忽略,进入安全拒绝 ---
95
+ }
96
+ lCore.display(`[KV] Unable to confirm Kvrocks multi-db isolation for index=${dbIndex}; ` +
97
+ 'enable redis-databases in Kvrocks or set kv.dbPre=true.');
98
+ return false;
99
+ }
100
+ /**
101
+ * --- 键值存储操作类(兼容 Redis 与 Kvrocks) ---
15
102
  *
16
103
  * @example
17
104
  * ```ts
@@ -25,18 +112,33 @@ const connections = [];
25
112
  export class Kv {
26
113
  /** --- 当前的 kv 连接信息 --- */
27
114
  _etc;
115
+ /** --- 实际向服务端选择的数据库编号 --- */
116
+ _db;
117
+ /** --- 实际生效的键名前缀(启用 dbPre 且 index > 0 时自动附带 db{index}:) --- */
118
+ _pre;
28
119
  constructor(etc) {
29
120
  this._etc = etc;
121
+ const index = etc.index || 0;
122
+ const useDbPre = Boolean(etc.dbPre && index > 0);
123
+ this._db = useDbPre ? 0 : index;
124
+ this._pre = useDbPre ? `db${index}:${etc.pre ?? ''}` : (etc.pre ?? '');
30
125
  }
31
126
  /**
32
- * --- 获取当前 Kv 配置的键名前缀 ---
33
- * @returns 原生 pipeline 不会自动添加的项目前缀
127
+ * --- 获取当前 Kv 实际生效的键名前缀 ---
128
+ * @returns 原生 pipeline / eval 不会自动添加的项目前缀
34
129
  */
35
130
  getPre() {
36
- return this._etc.pre;
131
+ return this._pre;
37
132
  }
38
133
  /**
39
- * --- 获取一个 pipeline 操作对象 ---
134
+ * --- 获取底层官方 redis 客户端实例(用于执行原生扩展命令) ---
135
+ * @returns 连接失败返回 null
136
+ */
137
+ async getClient() {
138
+ return this._getConnection();
139
+ }
140
+ /**
141
+ * --- 获取一个绑定在共享连接上的原生 multi / pipeline 对象(通过 execAsPipeline() 或 exec() 执行,无需关闭) ---
40
142
  * @returns 失败则返回 false
41
143
  */
42
144
  async pipeline() {
@@ -44,12 +146,39 @@ export class Kv {
44
146
  if (!conn) {
45
147
  return false;
46
148
  }
47
- return conn.createPipelineClient();
149
+ try {
150
+ return conn.multi();
151
+ }
152
+ catch {
153
+ return false;
154
+ }
155
+ }
156
+ /**
157
+ * --- 在共享连接上执行一个 Redis Lua 脚本 ---
158
+ * @param script Lua 源码
159
+ * @param keys 传给 KEYS 的完整键名,调用方需自行添加项目前缀
160
+ * @param args 传给 ARGV 的参数
161
+ * @returns Redis 原始结果,nil 返回 null,连接或执行失败返回 false
162
+ */
163
+ async eval(script, keys, args) {
164
+ const conn = await this._getConnection();
165
+ if (!conn) {
166
+ return false;
167
+ }
168
+ try {
169
+ return await conn.eval(script, {
170
+ 'keys': keys,
171
+ 'arguments': args,
172
+ });
173
+ }
174
+ catch {
175
+ return false;
176
+ }
48
177
  }
49
178
  /**
50
179
  * --- 设定一个值 ---
51
- * @param key
52
- * @param val
180
+ * @param key 键
181
+ * @param val 值
53
182
  * @param ttl 秒,0 为不限制
54
183
  * @param mod 设置模式: 空,nx(key不存在才建立),xx(key存在才修改)
55
184
  */
@@ -58,21 +187,23 @@ export class Kv {
58
187
  if (!conn) {
59
188
  return false;
60
189
  }
61
- if (typeof val !== 'string') {
62
- val = lText.stringifyJson(val);
190
+ const payload = typeof val === 'string' ? val : lText.stringifyJson(val);
191
+ const options = {};
192
+ if (ttl > 0) {
193
+ options.expiration = {
194
+ 'type': 'EX',
195
+ 'value': ttl,
196
+ };
197
+ }
198
+ if (mod === 'nx') {
199
+ options.condition = 'NX';
200
+ }
201
+ else if (mod === 'xx') {
202
+ options.condition = 'XX';
63
203
  }
64
204
  try {
65
- switch (mod) {
66
- case '': {
67
- return await conn.set(this._etc.pre + key, val, ttl === 0 ? undefined : ttl);
68
- }
69
- case 'nx': {
70
- return await conn.setNX(this._etc.pre + key, val, ttl === 0 ? undefined : ttl);
71
- }
72
- case 'xx': {
73
- return await conn.replace(this._etc.pre + key, val, ttl === 0 ? undefined : ttl);
74
- }
75
- }
205
+ const res = await conn.set(this._pre + key, payload, options);
206
+ return res === 'OK';
76
207
  }
77
208
  catch {
78
209
  return false;
@@ -80,8 +211,8 @@ export class Kv {
80
211
  }
81
212
  /**
82
213
  * --- 添加一个值,存在则不变 ---
83
- * @param key
84
- * @param val
214
+ * @param key 键
215
+ * @param val 值
85
216
  * @param ttl 秒,0 为不限制
86
217
  */
87
218
  async add(key, val, ttl = 0) {
@@ -107,7 +238,7 @@ export class Kv {
107
238
  return false;
108
239
  }
109
240
  try {
110
- return await conn.append(this._etc.pre + key, val) > 0 ? true : false;
241
+ return (await conn.append(this._pre + key, val)) > 0;
111
242
  }
112
243
  catch {
113
244
  return false;
@@ -115,55 +246,33 @@ export class Kv {
115
246
  }
116
247
  /**
117
248
  * --- 向已存在的值之前追加数据 ---
118
- * @param key
119
- * @param val
249
+ * @param key 键
250
+ * @param val 值
120
251
  */
121
252
  async prepend(key, val) {
122
- const conn = await this._getConnection();
123
- if (!conn) {
124
- return false;
125
- }
126
- try {
127
- const script = `local val = redis.call('GET', KEYS[1])
128
- if (val == false) then
253
+ const script = `local value = redis.call('GET', KEYS[1])
254
+ if not value then
129
255
  return 0
130
256
  end
131
- local r = redis.call('SET', KEYS[1], ARGV[1]..val)
132
- if (r) then
133
- return 1
134
- else
135
- return 0
136
- end`;
137
- let r = await conn.evalSHA('ea360f3f6508a243824ecda6be15db56df217873', [this._etc.pre + key], [val]);
138
- r = parseInt(r);
139
- if (r <= 0) {
140
- await conn.scriptLoad(script);
141
- r = await conn.evalSHA('ea360f3f6508a243824ecda6be15db56df217873', [this._etc.pre + key], [val]);
142
- r = parseInt(r);
143
- }
144
- return r > 0 ? true : false;
145
- }
146
- catch {
147
- return false;
148
- }
257
+ redis.call('SET', KEYS[1], ARGV[1] .. value, 'KEEPTTL')
258
+ return 1`;
259
+ return await this.eval(script, [this._pre + key], [val]) === 1;
149
260
  }
150
261
  /**
151
262
  * --- 检测 key 是否存在 ---
152
263
  * @param keys 单个或序列
153
264
  */
154
265
  async exists(keys) {
266
+ const list = (typeof keys === 'string' ? [keys] : keys).map(k => this._pre + k);
267
+ if (list.length === 0) {
268
+ return 0;
269
+ }
155
270
  const conn = await this._getConnection();
156
271
  if (!conn) {
157
272
  return 0;
158
273
  }
159
274
  try {
160
- if (typeof keys === 'string') {
161
- keys = [keys];
162
- }
163
- for (let k = 0; k < keys.length; ++k) {
164
- keys[k] = this._etc.pre + keys[k];
165
- }
166
- return await conn.mExists(keys);
275
+ return await conn.exists(list);
167
276
  }
168
277
  catch {
169
278
  return 0;
@@ -171,7 +280,7 @@ end`;
171
280
  }
172
281
  /**
173
282
  * --- 获取字符串 ---
174
- * @param key
283
+ * @param key 键
175
284
  * @returns 字符串 / false / null(即使存入时是 number,这个方法也只会返回字符串)
176
285
  */
177
286
  async get(key) {
@@ -180,7 +289,7 @@ end`;
180
289
  return null;
181
290
  }
182
291
  try {
183
- return await conn.get(this._etc.pre + key);
292
+ return await conn.get(this._pre + key);
184
293
  }
185
294
  catch {
186
295
  return false;
@@ -188,7 +297,7 @@ end`;
188
297
  }
189
298
  /**
190
299
  * --- 获取相应的剩余有效期秒数 ---
191
- * @param key
300
+ * @param key 键
192
301
  */
193
302
  async ttl(key) {
194
303
  const conn = await this._getConnection();
@@ -196,7 +305,7 @@ end`;
196
305
  return null;
197
306
  }
198
307
  try {
199
- return await conn.ttl(this._etc.pre + key);
308
+ return await conn.ttl(this._pre + key);
200
309
  }
201
310
  catch {
202
311
  return null;
@@ -204,7 +313,7 @@ end`;
204
313
  }
205
314
  /**
206
315
  * --- 获取相应的剩余有效期毫秒数 ---
207
- * @param key
316
+ * @param key 键
208
317
  */
209
318
  async pttl(key) {
210
319
  const conn = await this._getConnection();
@@ -212,7 +321,7 @@ end`;
212
321
  return null;
213
322
  }
214
323
  try {
215
- return await conn.pTTL(this._etc.pre + key);
324
+ return await conn.pTTL(this._pre + key);
216
325
  }
217
326
  catch {
218
327
  return null;
@@ -223,22 +332,19 @@ end`;
223
332
  * @param keys key 序列
224
333
  */
225
334
  async mGet(keys) {
335
+ if (keys.length === 0) {
336
+ return {};
337
+ }
226
338
  const conn = await this._getConnection();
227
339
  if (!conn) {
228
340
  return false;
229
341
  }
230
- for (let k = 0; k < keys.length; ++k) {
231
- keys[k] = this._etc.pre + keys[k];
232
- }
342
+ const list = keys.map(k => this._pre + k);
233
343
  const rtn = {};
234
344
  try {
235
- const pl = this._etc.pre.length;
236
- const r = await conn.mGet(keys);
237
- if (pl === 0) {
238
- return r;
239
- }
240
- for (const k in r) {
241
- rtn[k.slice(pl)] = r[k];
345
+ const values = await conn.mGet(list);
346
+ for (let i = 0; i < keys.length; ++i) {
347
+ rtn[keys[i]] = values[i] ?? null;
242
348
  }
243
349
  }
244
350
  catch {
@@ -247,20 +353,21 @@ end`;
247
353
  return rtn;
248
354
  }
249
355
  /**
250
- * --- 批量设置哈希值 ---
251
- * @param rows key / val 数组
356
+ * --- 批量设置键值 ---
357
+ * @param rows key / val 对象
252
358
  */
253
359
  async mSet(rows) {
360
+ const entries = Object.entries(rows);
361
+ if (entries.length === 0) {
362
+ return true;
363
+ }
254
364
  const conn = await this._getConnection();
255
365
  if (!conn) {
256
366
  return false;
257
367
  }
258
368
  try {
259
- const rtn = {};
260
- for (const key in rows) {
261
- rtn[this._etc.pre + key] = rows[key];
262
- }
263
- await conn.mSet(rtn);
369
+ const payload = entries.map(([k, v]) => [this._pre + k, v]);
370
+ await conn.mSet(payload);
264
371
  return true;
265
372
  }
266
373
  catch {
@@ -280,7 +387,7 @@ end`;
280
387
  return false;
281
388
  }
282
389
  try {
283
- const value = await conn.getAndDel(this._etc.pre + key);
390
+ const value = await conn.getDel(this._pre + key);
284
391
  if (value === null) {
285
392
  return null;
286
393
  }
@@ -292,21 +399,19 @@ end`;
292
399
  }
293
400
  /**
294
401
  * --- 删除已存在的值 ---
295
- * @param keys
402
+ * @param keys 单个或序列
296
403
  */
297
404
  async del(keys) {
405
+ const list = (typeof keys === 'string' ? [keys] : keys).map(k => this._pre + k);
406
+ if (list.length === 0) {
407
+ return false;
408
+ }
298
409
  const conn = await this._getConnection();
299
410
  if (!conn) {
300
411
  return false;
301
412
  }
302
- if (typeof keys === 'string') {
303
- keys = [keys];
304
- }
305
- for (let k = 0; k < keys.length; ++k) {
306
- keys[k] = this._etc.pre + keys[k];
307
- }
308
413
  try {
309
- return await conn.del(keys) > 0 ? true : false;
414
+ return (await conn.del(list)) > 0;
310
415
  }
311
416
  catch {
312
417
  return false;
@@ -314,7 +419,7 @@ end`;
314
419
  }
315
420
  /**
316
421
  * --- 自增 ---
317
- * @param key
422
+ * @param key 键
318
423
  * @param num 整数或浮点正数
319
424
  */
320
425
  async incr(key, num = 1) {
@@ -325,14 +430,14 @@ end`;
325
430
  try {
326
431
  if (Number.isInteger(num)) {
327
432
  if (num === 1) {
328
- return await conn.incr(this._etc.pre + key);
433
+ return await conn.incr(this._pre + key);
329
434
  }
330
435
  else {
331
- return await conn.incr(this._etc.pre + key, num);
436
+ return await conn.incrBy(this._pre + key, num);
332
437
  }
333
438
  }
334
439
  else {
335
- return await conn.incrByFloat(this._etc.pre + key, num);
440
+ return Number(await conn.incrByFloat(this._pre + key, num));
336
441
  }
337
442
  }
338
443
  catch {
@@ -341,7 +446,7 @@ end`;
341
446
  }
342
447
  /**
343
448
  * --- 自减 ---
344
- * @param key
449
+ * @param key 键
345
450
  * @param num 整数或浮点正数
346
451
  */
347
452
  async decr(key, num = 1) {
@@ -352,14 +457,14 @@ end`;
352
457
  try {
353
458
  if (Number.isInteger(num)) {
354
459
  if (num === 1) {
355
- return await conn.decr(this._etc.pre + key);
460
+ return await conn.decr(this._pre + key);
356
461
  }
357
462
  else {
358
- return await conn.decr(this._etc.pre + key, num);
463
+ return await conn.decrBy(this._pre + key, num);
359
464
  }
360
465
  }
361
466
  else {
362
- return await conn.incrByFloat(this._etc.pre + key, -num);
467
+ return Number(await conn.incrByFloat(this._pre + key, -num));
363
468
  }
364
469
  }
365
470
  catch {
@@ -368,8 +473,8 @@ end`;
368
473
  }
369
474
  /**
370
475
  * --- 仅修改过期时间不修改值 ---
371
- * @param key
372
- * @param ttl
476
+ * @param key 键
477
+ * @param ttl 秒
373
478
  */
374
479
  async expire(key, ttl) {
375
480
  const conn = await this._getConnection();
@@ -377,7 +482,7 @@ end`;
377
482
  return false;
378
483
  }
379
484
  try {
380
- return await conn.expire(this._etc.pre + key, ttl);
485
+ return (await conn.expire(this._pre + key, ttl)) === 1;
381
486
  }
382
487
  catch {
383
488
  return false;
@@ -385,7 +490,7 @@ end`;
385
490
  }
386
491
  /**
387
492
  * --- 获取服务器上的所有 key 列表 ---
388
- * @param pattern
493
+ * @param pattern 匹配模式
389
494
  */
390
495
  async keys(pattern) {
391
496
  const conn = await this._getConnection();
@@ -393,12 +498,10 @@ end`;
393
498
  return false;
394
499
  }
395
500
  try {
396
- const r = await conn.keys(this._etc.pre + pattern);
397
- const pl = this._etc.pre.length;
501
+ const r = await conn.keys(this._pre + pattern);
502
+ const pl = this._pre.length;
398
503
  if (pl > 0) {
399
- for (let k = 0; k < r.length; ++k) {
400
- r[k] = r[k].slice(pl);
401
- }
504
+ return r.map(k => k.slice(pl));
402
505
  }
403
506
  return r;
404
507
  }
@@ -407,22 +510,27 @@ end`;
407
510
  }
408
511
  }
409
512
  /**
410
- * --- 根据条件获取服务器上的 keys ---
411
- * @param cursor
513
+ * --- 根据条件获取服务器上的 keys(兼容 Redis 数字串游标与 Kvrocks 字符串游标) ---
514
+ * @param cursor 游标,首次传 '0'(或 0)
412
515
  * @param pattern 例如 *
413
516
  * @param count 获取的条数
414
517
  */
415
- async scan(cursor = 0, pattern = '*', count = 10) {
518
+ async scan(cursor = '0', pattern = '*', count = 10) {
416
519
  const conn = await this._getConnection();
417
520
  if (!conn) {
418
521
  return false;
419
522
  }
420
523
  try {
421
- const r = await conn.scan(cursor, this._etc.pre + pattern, count);
422
- for (let i = 0; i < r.items.length; ++i) {
423
- r.items[i] = r.items[i].slice(this._etc.pre.length);
424
- }
425
- return r;
524
+ const r = await conn.scan(String(cursor), {
525
+ 'MATCH': this._pre + pattern,
526
+ 'COUNT': count,
527
+ });
528
+ const pl = this._pre.length;
529
+ const items = pl > 0 ? r.keys.map(k => k.slice(pl)) : r.keys;
530
+ return {
531
+ 'cursor': r.cursor,
532
+ 'items': items,
533
+ };
426
534
  }
427
535
  catch {
428
536
  return false;
@@ -464,7 +572,7 @@ end`;
464
572
  * @param key key 名
465
573
  * @param field 字段名
466
574
  * @param val 值
467
- * @param mod 空,nx(key不存在才建立)
575
+ * @param mod 空,nx(field不存在才建立)
468
576
  */
469
577
  async hSet(key, field, val, mod = '') {
470
578
  const conn = await this._getConnection();
@@ -472,14 +580,13 @@ end`;
472
580
  return false;
473
581
  }
474
582
  try {
475
- if (typeof val !== 'string') {
476
- val = lText.stringifyJson(val);
477
- }
583
+ const payload = typeof val === 'string' ? val : lText.stringifyJson(val);
478
584
  if (mod === 'nx') {
479
- return await conn.hSetNX(this._etc.pre + key, field, val);
585
+ return (await conn.hSetNX(this._pre + key, field, payload)) === 1;
480
586
  }
481
587
  else {
482
- return await conn.hSet(this._etc.pre + key, field, val);
588
+ await conn.hSet(this._pre + key, field, payload);
589
+ return true;
483
590
  }
484
591
  }
485
592
  catch {
@@ -489,21 +596,23 @@ end`;
489
596
  /**
490
597
  * --- 批量设置哈希值 ---
491
598
  * @param key key 名
492
- * @param rows key / val 数组
599
+ * @param rows field / val 对象
493
600
  */
494
601
  async hMSet(key, rows) {
602
+ const entries = Object.entries(rows);
603
+ if (entries.length === 0) {
604
+ return true;
605
+ }
495
606
  const conn = await this._getConnection();
496
607
  if (!conn) {
497
608
  return false;
498
609
  }
499
610
  try {
500
- for (const i in rows) {
501
- const val = rows[i];
502
- if (typeof val === 'object') {
503
- rows[i] = lText.stringifyJson(val);
504
- }
611
+ const payload = {};
612
+ for (const [k, val] of entries) {
613
+ payload[k] = typeof val === 'object' ? lText.stringifyJson(val) : val;
505
614
  }
506
- await conn.hMSet(this._etc.pre + key, rows);
615
+ await conn.hSet(this._pre + key, payload);
507
616
  return true;
508
617
  }
509
618
  catch {
@@ -512,8 +621,8 @@ end`;
512
621
  }
513
622
  /**
514
623
  * --- 获取哈希值 ---
515
- * @param key
516
- * @param field
624
+ * @param key 键
625
+ * @param field 字段
517
626
  */
518
627
  async hGet(key, field) {
519
628
  const conn = await this._getConnection();
@@ -521,7 +630,8 @@ end`;
521
630
  return false;
522
631
  }
523
632
  try {
524
- return await conn.hGet(this._etc.pre + key, field);
633
+ const v = await conn.hGet(this._pre + key, field);
634
+ return v ?? null;
525
635
  }
526
636
  catch {
527
637
  return false;
@@ -540,16 +650,24 @@ end`;
540
650
  }
541
651
  /**
542
652
  * --- 批量获取哈希值 ---
543
- * @param key
544
- * @param fields
653
+ * @param key 键
654
+ * @param fields 字段列表
545
655
  */
546
656
  async hMGet(key, fields) {
657
+ if (fields.length === 0) {
658
+ return {};
659
+ }
547
660
  const conn = await this._getConnection();
548
661
  if (!conn) {
549
662
  return false;
550
663
  }
551
664
  try {
552
- return await conn.hMGet(this._etc.pre + key, fields);
665
+ const values = await conn.hmGet(this._pre + key, fields);
666
+ const rtn = {};
667
+ for (let i = 0; i < fields.length; ++i) {
668
+ rtn[fields[i]] = values[i] ?? null;
669
+ }
670
+ return rtn;
553
671
  }
554
672
  catch {
555
673
  return false;
@@ -557,7 +675,7 @@ end`;
557
675
  }
558
676
  /**
559
677
  * --- 批量获取哈希键值对 ---
560
- * @param key
678
+ * @param key 键
561
679
  */
562
680
  async hGetAll(key) {
563
681
  const conn = await this._getConnection();
@@ -565,7 +683,7 @@ end`;
565
683
  return false;
566
684
  }
567
685
  try {
568
- return await conn.hGetAll(this._etc.pre + key);
686
+ return await conn.hGetAll(this._pre + key);
569
687
  }
570
688
  catch {
571
689
  return false;
@@ -573,16 +691,19 @@ end`;
573
691
  }
574
692
  /**
575
693
  * --- 删除哈希键 ---
576
- * @param key
577
- * @param fields 值序列
694
+ * @param key 键
695
+ * @param fields 字段序列
578
696
  */
579
697
  async hDel(key, fields) {
698
+ if (Array.isArray(fields) && fields.length === 0) {
699
+ return 0;
700
+ }
580
701
  const conn = await this._getConnection();
581
702
  if (!conn) {
582
703
  return false;
583
704
  }
584
705
  try {
585
- return await conn.hDel(this._etc.pre + key, fields);
706
+ return await conn.hDel(this._pre + key, fields);
586
707
  }
587
708
  catch {
588
709
  return false;
@@ -590,8 +711,8 @@ end`;
590
711
  }
591
712
  /**
592
713
  * --- 判断哈希字段是否存在 ---
593
- * @param key
594
- * @param field
714
+ * @param key 键
715
+ * @param field 字段
595
716
  */
596
717
  async hExists(key, field) {
597
718
  const conn = await this._getConnection();
@@ -599,7 +720,7 @@ end`;
599
720
  return false;
600
721
  }
601
722
  try {
602
- return await conn.hExists(this._etc.pre + key, field);
723
+ return (await conn.hExists(this._pre + key, field)) === 1;
603
724
  }
604
725
  catch {
605
726
  return false;
@@ -618,10 +739,10 @@ end`;
618
739
  }
619
740
  try {
620
741
  if (Number.isInteger(increment)) {
621
- return await conn.hIncr(this._etc.pre + key, field, increment);
742
+ return await conn.hIncrBy(this._pre + key, field, increment);
622
743
  }
623
744
  else {
624
- return await conn.hIncrByFloat(this._etc.pre + key, field, increment);
745
+ return Number(await conn.hIncrByFloat(this._pre + key, field, increment));
625
746
  }
626
747
  }
627
748
  catch {
@@ -630,7 +751,7 @@ end`;
630
751
  }
631
752
  /**
632
753
  * --- 获取哈希所有字段 ---
633
- * @param key
754
+ * @param key 键
634
755
  */
635
756
  async hKeys(key) {
636
757
  const conn = await this._getConnection();
@@ -638,190 +759,376 @@ end`;
638
759
  return false;
639
760
  }
640
761
  try {
641
- return await conn.hKeys(this._etc.pre + key);
762
+ return await conn.hKeys(this._pre + key);
642
763
  }
643
764
  catch {
644
765
  return false;
645
766
  }
646
767
  }
768
+ /**
769
+ * --- 从列表左侧推入元素 ---
770
+ * @param key 键
771
+ * @param values 元素数组
772
+ */
647
773
  async lPush(key, values) {
774
+ if (values.length === 0) {
775
+ return 0;
776
+ }
648
777
  const conn = await this._getConnection();
649
778
  if (!conn) {
650
779
  return false;
651
780
  }
652
781
  try {
653
- return await conn.lPush(this._etc.pre + key, values);
782
+ return await conn.lPush(this._pre + key, values);
654
783
  }
655
784
  catch {
656
785
  return false;
657
786
  }
658
787
  }
788
+ /**
789
+ * --- 从列表右侧推入元素 ---
790
+ * @param key 键
791
+ * @param values 元素数组
792
+ */
659
793
  async rPush(key, values) {
794
+ if (values.length === 0) {
795
+ return 0;
796
+ }
660
797
  const conn = await this._getConnection();
661
798
  if (!conn) {
662
799
  return false;
663
800
  }
664
801
  try {
665
- return await conn.rPush(this._etc.pre + key, values);
802
+ return await conn.rPush(this._pre + key, values);
666
803
  }
667
804
  catch {
668
805
  return false;
669
806
  }
670
807
  }
808
+ /**
809
+ * --- 阻塞式在两个列表间移动元素(使用独立连接,避免阻塞共享连接) ---
810
+ * @param sourceKey 源列表键
811
+ * @param destKey 目标列表键
812
+ * @param soo 源端方向
813
+ * @param deo 目标端方向
814
+ * @param timeout 超时秒数,0 为无限等待
815
+ */
671
816
  async bLMove(sourceKey, destKey, soo, deo, timeout) {
672
- const conn = await this._getConnection();
673
- if (!conn) {
674
- return false;
675
- }
676
- try {
677
- return await conn.bLMove(this._etc.pre + sourceKey, this._etc.pre + destKey, soo, deo, timeout);
678
- }
679
- catch {
680
- return false;
681
- }
817
+ return this._runBlocking(timeout, async (blocking) => {
818
+ return blocking.blMove(this._pre + sourceKey, this._pre + destKey, soo, deo, timeout);
819
+ });
682
820
  }
821
+ /**
822
+ * --- 从列表左侧弹出元素 ---
823
+ * @param key 键
824
+ */
683
825
  async lPop(key) {
684
826
  const conn = await this._getConnection();
685
827
  if (!conn) {
686
828
  return false;
687
829
  }
688
830
  try {
689
- return await conn.lPop(this._etc.pre + key);
831
+ return await conn.lPop(this._pre + key);
690
832
  }
691
833
  catch {
692
834
  return false;
693
835
  }
694
836
  }
837
+ /**
838
+ * --- 从列表右侧弹出元素 ---
839
+ * @param key 键
840
+ */
695
841
  async rPop(key) {
696
842
  const conn = await this._getConnection();
697
843
  if (!conn) {
698
844
  return false;
699
845
  }
700
846
  try {
701
- return await conn.rPop(this._etc.pre + key);
847
+ return await conn.rPop(this._pre + key);
702
848
  }
703
849
  catch {
704
850
  return false;
705
851
  }
706
852
  }
853
+ /**
854
+ * --- 阻塞式从列表右侧弹出元素(使用独立连接,避免阻塞共享连接) ---
855
+ * @param key 单个或序列键
856
+ * @param timeout 超时秒数,0 为无限等待
857
+ */
707
858
  async bRPop(key, timeout) {
859
+ const list = (typeof key === 'string' ? [key] : key).map(item => this._pre + item);
860
+ if (list.length === 0) {
861
+ return {};
862
+ }
863
+ return this._runBlocking(timeout, async (blocking) => {
864
+ const res = await blocking.brPop(list, timeout);
865
+ if (!res) {
866
+ return {};
867
+ }
868
+ const pl = this._pre.length;
869
+ const outKey = pl > 0 && res.key.startsWith(this._pre) ? res.key.slice(pl) : res.key;
870
+ return {
871
+ [outKey]: res.element,
872
+ };
873
+ });
874
+ }
875
+ /**
876
+ * --- 获取列表指定区间元素 ---
877
+ * @param key 键
878
+ * @param start 起始位置
879
+ * @param stop 结束位置
880
+ */
881
+ async lRange(key, start, stop) {
708
882
  const conn = await this._getConnection();
709
883
  if (!conn) {
710
884
  return false;
711
885
  }
712
886
  try {
713
- if (typeof key === 'string') {
714
- key = [key];
715
- }
716
- return await conn.bRPop(key.map(item => this._etc.pre + item), timeout);
887
+ return await conn.lRange(this._pre + key, start, stop);
717
888
  }
718
889
  catch {
719
890
  return false;
720
891
  }
721
892
  }
722
- async lRange(key, start, stop) {
893
+ /**
894
+ * --- 获取列表长度 ---
895
+ * @param key 键
896
+ */
897
+ async lLen(key) {
723
898
  const conn = await this._getConnection();
724
899
  if (!conn) {
725
900
  return false;
726
901
  }
727
902
  try {
728
- return await conn.lRange(this._etc.pre + key, start, stop);
903
+ return await conn.lLen(this._pre + key);
729
904
  }
730
905
  catch {
731
906
  return false;
732
907
  }
733
908
  }
734
- async lLen(key) {
909
+ /**
910
+ * --- 添加有序集合元素 ---
911
+ */
912
+ async zAdd(key, scoreOrItems, memberOrOptions) {
735
913
  const conn = await this._getConnection();
736
914
  if (!conn) {
737
915
  return false;
738
916
  }
739
917
  try {
740
- return await conn.lLen(this._etc.pre + key);
918
+ if (typeof scoreOrItems === 'number') {
919
+ const count = await conn.zAdd(this._pre + key, {
920
+ 'score': scoreOrItems,
921
+ 'value': memberOrOptions,
922
+ });
923
+ return count > 0;
924
+ }
925
+ if (scoreOrItems.length === 0) {
926
+ return 0;
927
+ }
928
+ const items = scoreOrItems.map(item => ({
929
+ 'score': item.score,
930
+ 'value': item.member,
931
+ }));
932
+ const rawOpt = memberOrOptions;
933
+ const opts = {};
934
+ if (rawOpt?.condition) {
935
+ opts.condition = rawOpt.condition;
936
+ }
937
+ if (rawOpt?.comparison) {
938
+ opts.comparison = rawOpt.comparison;
939
+ }
940
+ if (rawOpt?.CH) {
941
+ opts.CH = true;
942
+ }
943
+ if (rawOpt?.INCR) {
944
+ return await conn.zAddIncr(this._pre + key, items, opts);
945
+ }
946
+ return await conn.zAdd(this._pre + key, items, opts);
741
947
  }
742
948
  catch {
743
949
  return false;
744
950
  }
745
951
  }
746
952
  /**
747
- * --- 添加有序集合元素 ---
953
+ * --- 查询有序集合成员及分数 ---
954
+ * @param key 键
955
+ * @param start 起点
956
+ * @param stop 终点
957
+ * @param options 范围与分页选项
748
958
  */
749
- async zAdd(key, scoreOrItems, memberOrOptions) {
959
+ async zRangeWithScores(key, start, stop, options) {
750
960
  const conn = await this._getConnection();
751
961
  if (!conn) {
752
962
  return false;
753
963
  }
754
964
  try {
755
- return await conn.zAdd(this._etc.pre + key, scoreOrItems, memberOrOptions);
965
+ const opts = {};
966
+ if (options?.by) {
967
+ opts.BY = options.by;
968
+ }
969
+ if (options?.rev) {
970
+ opts.REV = true;
971
+ }
972
+ if (options?.offset !== undefined && options?.count !== undefined) {
973
+ opts.LIMIT = {
974
+ 'offset': options.offset,
975
+ 'count': options.count,
976
+ };
977
+ }
978
+ const rows = await conn.zRangeWithScores(this._pre + key, start, stop, opts);
979
+ return rows.map(row => ({
980
+ 'member': row.value,
981
+ 'score': row.score,
982
+ }));
756
983
  }
757
984
  catch {
758
985
  return false;
759
986
  }
760
987
  }
761
- async zRangeWithScores(key, start, stop, options) {
988
+ /**
989
+ * --- 移除有序集合成员 ---
990
+ * @param key 键
991
+ * @param members 成员列表
992
+ */
993
+ async zRem(key, members) {
994
+ if (members.length === 0) {
995
+ return 0;
996
+ }
762
997
  const conn = await this._getConnection();
763
998
  if (!conn) {
764
999
  return false;
765
1000
  }
766
1001
  try {
767
- return await conn.zRangeWithScores(this._etc.pre + key, start, stop, {
768
- 'by': options?.by,
769
- 'reverse': options?.rev,
770
- 'offset': options?.offset,
771
- 'count': options?.count,
772
- });
1002
+ return await conn.zRem(this._pre + key, members);
773
1003
  }
774
1004
  catch {
775
1005
  return false;
776
1006
  }
777
1007
  }
778
- async zRem(key, members) {
1008
+ /**
1009
+ * --- 在独立副本连接上执行阻塞命令,避免阻塞共享连接和触发默认 5 秒命令超时 ---
1010
+ * @param timeout 阻塞超时秒数,0 为无限等待
1011
+ * @param fn 实际执行函数
1012
+ */
1013
+ async _runBlocking(timeout, fn) {
779
1014
  const conn = await this._getConnection();
780
1015
  if (!conn) {
781
1016
  return false;
782
1017
  }
1018
+ const blocking = conn.duplicate({
1019
+ 'commandOptions': {
1020
+ 'timeout': timeout > 0 ? timeout * 1000 + 5_000 : undefined,
1021
+ },
1022
+ 'socket': {
1023
+ ...conn.options?.socket,
1024
+ 'reconnectStrategy': false,
1025
+ },
1026
+ });
1027
+ blocking.on('error', function (err) {
1028
+ lCore.debug('[KV][_runBlocking][error]', err);
1029
+ });
783
1030
  try {
784
- return await conn.zRem(this._etc.pre + key, members);
1031
+ await blocking.connect();
1032
+ return await fn(blocking);
785
1033
  }
786
1034
  catch {
787
1035
  return false;
788
1036
  }
1037
+ finally {
1038
+ blocking.destroy();
1039
+ }
789
1040
  }
790
1041
  /**
791
- * --- 从连接池中获取一个符合要求的连接 ---
1042
+ * --- 从连接池中获取一个符合要求的共享连接 ---
792
1043
  */
793
1044
  async _getConnection() {
794
- const item = connections.find(item => (item.host === this._etc.host) && (item.port === this._etc.port) && (item.index === this._etc.index));
795
- if (item) {
796
- return item.conn;
1045
+ const { host, port, user, pwd, tls: tlsOpt } = this._etc;
1046
+ const db = this._db;
1047
+ const tlsKey = getTlsKey(tlsOpt);
1048
+ const cached = connections.find(item => item.host === host && item.port === port && item.index === db &&
1049
+ item.user === user && item.pwd === pwd && item.tls === tlsKey);
1050
+ if (cached) {
1051
+ const conn = await cached.ready;
1052
+ if (conn?.isOpen) {
1053
+ return conn;
1054
+ }
1055
+ const idx = connections.indexOf(cached);
1056
+ if (idx !== -1) {
1057
+ connections.splice(idx, 1);
1058
+ }
1059
+ if (!conn) {
1060
+ return null;
1061
+ }
797
1062
  }
798
- // --- 没有找到合适的连接,创建一个 ---
1063
+ // --- 并发首次建连共用同一次初始化 ---
1064
+ const ready = this._connect(host, port, db, user, pwd, tlsOpt).catch(() => null);
1065
+ const item = {
1066
+ 'host': host,
1067
+ 'port': port,
1068
+ 'index': db,
1069
+ 'user': user,
1070
+ 'pwd': pwd,
1071
+ 'tls': tlsKey,
1072
+ 'ready': ready,
1073
+ };
1074
+ connections.push(item);
1075
+ const conn = await ready;
1076
+ if (!conn) {
1077
+ const idx = connections.indexOf(item);
1078
+ if (idx !== -1) {
1079
+ connections.splice(idx, 1);
1080
+ }
1081
+ }
1082
+ return conn;
1083
+ }
1084
+ /**
1085
+ * --- 建立共享连接,统一走 RESP2 兼容 Redis 与 Kvrocks,并在非 0 库时校验 Kvrocks 多库隔离 ---
1086
+ */
1087
+ async _connect(host, port, index, user, pwd, tlsOpt) {
1088
+ let initialized = false;
1089
+ const reconnectStrategy = (retries) => {
1090
+ // --- 首次建连(含 AUTH / SELECT)失败立即返回,由上层按需重试,避免请求无限挂起 ---
1091
+ if (!initialized) {
1092
+ return false;
1093
+ }
1094
+ // --- 已就绪连接断线后自动退避重连,node-redis 会自动重发 AUTH / SELECT ---
1095
+ return Math.min(retries * 100, 3_000);
1096
+ };
1097
+ const conn = redis.createClient({
1098
+ 'RESP': 2,
1099
+ 'disableClientInfo': true,
1100
+ 'maintNotifications': 'disabled',
1101
+ 'database': index,
1102
+ 'username': user || undefined,
1103
+ 'password': pwd || undefined,
1104
+ 'socket': tlsOpt
1105
+ ? {
1106
+ ...(typeof tlsOpt === 'object' ? tlsOpt : {}),
1107
+ 'host': host,
1108
+ 'port': port,
1109
+ 'tls': true,
1110
+ 'reconnectStrategy': reconnectStrategy,
1111
+ }
1112
+ : {
1113
+ 'host': host,
1114
+ 'port': port,
1115
+ 'reconnectStrategy': reconnectStrategy,
1116
+ },
1117
+ });
1118
+ conn.on('error', function (err) {
1119
+ lCore.debug('[KV][_getConnection][error]', err);
1120
+ });
799
1121
  try {
800
- const conn = redis.createCommandClient({
801
- 'host': this._etc.host,
802
- 'port': this._etc.port,
803
- });
804
- // --- 认证 ---
805
- if (this._etc.pwd) {
806
- await conn.auth(this._etc.pwd, this._etc.user || undefined);
1122
+ await conn.connect();
1123
+ if (index > 0 && !await verifyMultiDbSupport(conn, index)) {
1124
+ conn.destroy();
1125
+ return null;
807
1126
  }
808
- await conn.select(this._etc.index);
809
- conn.on('error', function (err) {
810
- lCore.debug('[KV][_getConnection][error]', err);
811
- }).on('end', () => {
812
- // --- 断线,不重要,会自动重连 ---
813
- }).on('close', () => {
814
- // --- 断线,不重要,会自动重连 ---
815
- });
816
- connections.push({
817
- 'host': this._etc.host,
818
- 'port': this._etc.port,
819
- 'index': this._etc.index,
820
- 'conn': conn,
821
- });
1127
+ initialized = true;
822
1128
  return conn;
823
1129
  }
824
1130
  catch {
1131
+ conn.destroy();
825
1132
  return null;
826
1133
  }
827
1134
  }
@@ -829,12 +1136,9 @@ end`;
829
1136
  /**
830
1137
  * --- 获取 Kv 对象 ---
831
1138
  * @param ctrEtc 控制器或配置信息
832
- * @param oetc 可用来覆盖 ctr 的一些选项,如 index
1139
+ * @param oetc 可用来覆盖 ctr 的部分连接选项
833
1140
  */
834
1141
  export function get(ctrEtc, oetc) {
835
1142
  const etc = ctrEtc instanceof sCtr.Ctr ? ctrEtc.getPrototype('_config').kv : ctrEtc;
836
- if (oetc) {
837
- Object.assign(etc, oetc);
838
- }
839
- return new Kv(etc);
1143
+ return new Kv(oetc ? { ...etc, ...oetc } : etc);
840
1144
  }