@maiyunnet/kebab 9.29.5 → 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 (64) 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/abox/text.d.ts +2 -0
  5. package/abox/text.js +51 -0
  6. package/doc/kebab-rag.md +2700 -1270
  7. package/index.d.ts +12 -1
  8. package/index.js +1 -1
  9. package/lib/ai.d.ts +4 -0
  10. package/lib/ai.js +32 -16
  11. package/lib/cookie.d.ts +2 -0
  12. package/lib/cookie.js +47 -45
  13. package/lib/core.d.ts +26 -0
  14. package/lib/core.js +36 -13
  15. package/lib/cron.js +1 -8
  16. package/lib/crypto.js +20 -6
  17. package/lib/db/conn.d.ts +10 -1
  18. package/lib/db/conn.js +1 -5
  19. package/lib/db/pool.d.ts +10 -2
  20. package/lib/db/pool.js +0 -6
  21. package/lib/db/tran.d.ts +10 -1
  22. package/lib/db/tran.js +0 -5
  23. package/lib/db.d.ts +3 -3
  24. package/lib/fs.js +78 -31
  25. package/lib/kv.d.ts +216 -88
  26. package/lib/kv.js +520 -230
  27. package/lib/s3.d.ts +2 -0
  28. package/lib/s3.js +14 -27
  29. package/lib/session.d.ts +7 -0
  30. package/lib/session.js +23 -2
  31. package/lib/socket.d.ts +4 -1
  32. package/lib/socket.js +1 -0
  33. package/lib/sql.d.ts +0 -5
  34. package/lib/sql.js +48 -12
  35. package/lib/text.d.ts +32 -8
  36. package/lib/text.js +30 -17
  37. package/lib/turnstile.d.ts +6 -0
  38. package/lib/turnstile.js +16 -9
  39. package/lib/undici/response.d.ts +13 -3
  40. package/lib/undici/response.js +0 -1
  41. package/lib/undici.d.ts +33 -1
  42. package/lib/undici.js +72 -56
  43. package/lib/vector.d.ts +33 -19
  44. package/lib/vector.js +0 -1
  45. package/lib/ws.d.ts +1 -1
  46. package/lib/ws.js +85 -128
  47. package/lib/zip.js +46 -45
  48. package/package.json +2 -2
  49. package/sys/child.js +178 -146
  50. package/sys/cmd.js +196 -197
  51. package/sys/ctr.d.ts +14 -14
  52. package/sys/ctr.js +145 -59
  53. package/sys/master.js +111 -80
  54. package/sys/mod.d.ts +112 -51
  55. package/sys/mod.js +23 -51
  56. package/sys/monitor/files.d.ts +2 -1
  57. package/sys/monitor/files.js +77 -21
  58. package/sys/monitor/watchdog.d.ts +7 -0
  59. package/sys/monitor/watchdog.js +311 -203
  60. package/sys/monitor.d.ts +59 -54
  61. package/sys/monitor.js +742 -681
  62. package/sys/route.d.ts +4 -4
  63. package/sys/route.js +93 -52
  64. 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,49 +353,41 @@ 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 {
267
374
  return false;
268
375
  }
269
376
  }
270
- /**
271
- * --- 获取 json 对象 ---
272
- * @param key
273
- */
274
377
  async getJson(key) {
275
378
  const v = await this.get(key);
276
379
  if (v === null || v === false) {
277
380
  return v;
278
381
  }
279
- const r = lText.parseJson(v);
280
- return r;
382
+ return lText.parseJson(v);
281
383
  }
282
- /**
283
- * --- 原子获取并删除 JSON 对象 ---
284
- * @param key 键
285
- */
286
384
  async getDelJson(key) {
287
385
  const conn = await this._getConnection();
288
386
  if (!conn) {
289
387
  return false;
290
388
  }
291
389
  try {
292
- const value = await conn.getAndDel(this._etc.pre + key);
390
+ const value = await conn.getDel(this._pre + key);
293
391
  if (value === null) {
294
392
  return null;
295
393
  }
@@ -301,21 +399,19 @@ end`;
301
399
  }
302
400
  /**
303
401
  * --- 删除已存在的值 ---
304
- * @param keys
402
+ * @param keys 单个或序列
305
403
  */
306
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
+ }
307
409
  const conn = await this._getConnection();
308
410
  if (!conn) {
309
411
  return false;
310
412
  }
311
- if (typeof keys === 'string') {
312
- keys = [keys];
313
- }
314
- for (let k = 0; k < keys.length; ++k) {
315
- keys[k] = this._etc.pre + keys[k];
316
- }
317
413
  try {
318
- return await conn.del(keys) > 0 ? true : false;
414
+ return (await conn.del(list)) > 0;
319
415
  }
320
416
  catch {
321
417
  return false;
@@ -323,7 +419,7 @@ end`;
323
419
  }
324
420
  /**
325
421
  * --- 自增 ---
326
- * @param key
422
+ * @param key 键
327
423
  * @param num 整数或浮点正数
328
424
  */
329
425
  async incr(key, num = 1) {
@@ -334,14 +430,14 @@ end`;
334
430
  try {
335
431
  if (Number.isInteger(num)) {
336
432
  if (num === 1) {
337
- return await conn.incr(this._etc.pre + key);
433
+ return await conn.incr(this._pre + key);
338
434
  }
339
435
  else {
340
- return await conn.incr(this._etc.pre + key, num);
436
+ return await conn.incrBy(this._pre + key, num);
341
437
  }
342
438
  }
343
439
  else {
344
- return await conn.incrByFloat(this._etc.pre + key, num);
440
+ return Number(await conn.incrByFloat(this._pre + key, num));
345
441
  }
346
442
  }
347
443
  catch {
@@ -350,7 +446,7 @@ end`;
350
446
  }
351
447
  /**
352
448
  * --- 自减 ---
353
- * @param key
449
+ * @param key 键
354
450
  * @param num 整数或浮点正数
355
451
  */
356
452
  async decr(key, num = 1) {
@@ -361,14 +457,14 @@ end`;
361
457
  try {
362
458
  if (Number.isInteger(num)) {
363
459
  if (num === 1) {
364
- return await conn.decr(this._etc.pre + key);
460
+ return await conn.decr(this._pre + key);
365
461
  }
366
462
  else {
367
- return await conn.decr(this._etc.pre + key, num);
463
+ return await conn.decrBy(this._pre + key, num);
368
464
  }
369
465
  }
370
466
  else {
371
- return await conn.incrByFloat(this._etc.pre + key, -num);
467
+ return Number(await conn.incrByFloat(this._pre + key, -num));
372
468
  }
373
469
  }
374
470
  catch {
@@ -377,8 +473,8 @@ end`;
377
473
  }
378
474
  /**
379
475
  * --- 仅修改过期时间不修改值 ---
380
- * @param key
381
- * @param ttl
476
+ * @param key 键
477
+ * @param ttl 秒
382
478
  */
383
479
  async expire(key, ttl) {
384
480
  const conn = await this._getConnection();
@@ -386,7 +482,7 @@ end`;
386
482
  return false;
387
483
  }
388
484
  try {
389
- return await conn.expire(this._etc.pre + key, ttl);
485
+ return (await conn.expire(this._pre + key, ttl)) === 1;
390
486
  }
391
487
  catch {
392
488
  return false;
@@ -394,7 +490,7 @@ end`;
394
490
  }
395
491
  /**
396
492
  * --- 获取服务器上的所有 key 列表 ---
397
- * @param pattern
493
+ * @param pattern 匹配模式
398
494
  */
399
495
  async keys(pattern) {
400
496
  const conn = await this._getConnection();
@@ -402,12 +498,10 @@ end`;
402
498
  return false;
403
499
  }
404
500
  try {
405
- const r = await conn.keys(this._etc.pre + pattern);
406
- const pl = this._etc.pre.length;
501
+ const r = await conn.keys(this._pre + pattern);
502
+ const pl = this._pre.length;
407
503
  if (pl > 0) {
408
- for (let k = 0; k < r.length; ++k) {
409
- r[k] = r[k].slice(pl);
410
- }
504
+ return r.map(k => k.slice(pl));
411
505
  }
412
506
  return r;
413
507
  }
@@ -416,22 +510,27 @@ end`;
416
510
  }
417
511
  }
418
512
  /**
419
- * --- 根据条件获取服务器上的 keys ---
420
- * @param cursor
513
+ * --- 根据条件获取服务器上的 keys(兼容 Redis 数字串游标与 Kvrocks 字符串游标) ---
514
+ * @param cursor 游标,首次传 '0'(或 0)
421
515
  * @param pattern 例如 *
422
516
  * @param count 获取的条数
423
517
  */
424
- async scan(cursor = 0, pattern = '*', count = 10) {
518
+ async scan(cursor = '0', pattern = '*', count = 10) {
425
519
  const conn = await this._getConnection();
426
520
  if (!conn) {
427
521
  return false;
428
522
  }
429
523
  try {
430
- const r = await conn.scan(cursor, this._etc.pre + pattern, count);
431
- for (let i = 0; i < r.items.length; ++i) {
432
- r.items[i] = r.items[i].slice(this._etc.pre.length);
433
- }
434
- 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
+ };
435
534
  }
436
535
  catch {
437
536
  return false;
@@ -473,7 +572,7 @@ end`;
473
572
  * @param key key 名
474
573
  * @param field 字段名
475
574
  * @param val 值
476
- * @param mod 空,nx(key不存在才建立)
575
+ * @param mod 空,nx(field不存在才建立)
477
576
  */
478
577
  async hSet(key, field, val, mod = '') {
479
578
  const conn = await this._getConnection();
@@ -481,14 +580,13 @@ end`;
481
580
  return false;
482
581
  }
483
582
  try {
484
- if (typeof val !== 'string') {
485
- val = lText.stringifyJson(val);
486
- }
583
+ const payload = typeof val === 'string' ? val : lText.stringifyJson(val);
487
584
  if (mod === 'nx') {
488
- return await conn.hSetNX(this._etc.pre + key, field, val);
585
+ return (await conn.hSetNX(this._pre + key, field, payload)) === 1;
489
586
  }
490
587
  else {
491
- return await conn.hSet(this._etc.pre + key, field, val);
588
+ await conn.hSet(this._pre + key, field, payload);
589
+ return true;
492
590
  }
493
591
  }
494
592
  catch {
@@ -498,21 +596,23 @@ end`;
498
596
  /**
499
597
  * --- 批量设置哈希值 ---
500
598
  * @param key key 名
501
- * @param rows key / val 数组
599
+ * @param rows field / val 对象
502
600
  */
503
601
  async hMSet(key, rows) {
602
+ const entries = Object.entries(rows);
603
+ if (entries.length === 0) {
604
+ return true;
605
+ }
504
606
  const conn = await this._getConnection();
505
607
  if (!conn) {
506
608
  return false;
507
609
  }
508
610
  try {
509
- for (const i in rows) {
510
- const val = rows[i];
511
- if (typeof val === 'object') {
512
- rows[i] = lText.stringifyJson(val);
513
- }
611
+ const payload = {};
612
+ for (const [k, val] of entries) {
613
+ payload[k] = typeof val === 'object' ? lText.stringifyJson(val) : val;
514
614
  }
515
- await conn.hMSet(this._etc.pre + key, rows);
615
+ await conn.hSet(this._pre + key, payload);
516
616
  return true;
517
617
  }
518
618
  catch {
@@ -521,8 +621,8 @@ end`;
521
621
  }
522
622
  /**
523
623
  * --- 获取哈希值 ---
524
- * @param key
525
- * @param field
624
+ * @param key 键
625
+ * @param field 字段
526
626
  */
527
627
  async hGet(key, field) {
528
628
  const conn = await this._getConnection();
@@ -530,17 +630,13 @@ end`;
530
630
  return false;
531
631
  }
532
632
  try {
533
- return await conn.hGet(this._etc.pre + key, field);
633
+ const v = await conn.hGet(this._pre + key, field);
634
+ return v ?? null;
534
635
  }
535
636
  catch {
536
637
  return false;
537
638
  }
538
639
  }
539
- /**
540
- * --- 获取哈希 json 对象 ---
541
- * @param key
542
- * @param field
543
- */
544
640
  async hGetJson(key, field) {
545
641
  const v = await this.hGet(key, field);
546
642
  if (v === false) {
@@ -550,20 +646,28 @@ end`;
550
646
  return null;
551
647
  }
552
648
  const r = lText.parseJson(v);
553
- return r === false ? null : v;
649
+ return r === false ? null : r;
554
650
  }
555
651
  /**
556
652
  * --- 批量获取哈希值 ---
557
- * @param key
558
- * @param fields
653
+ * @param key 键
654
+ * @param fields 字段列表
559
655
  */
560
656
  async hMGet(key, fields) {
657
+ if (fields.length === 0) {
658
+ return {};
659
+ }
561
660
  const conn = await this._getConnection();
562
661
  if (!conn) {
563
662
  return false;
564
663
  }
565
664
  try {
566
- 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;
567
671
  }
568
672
  catch {
569
673
  return false;
@@ -571,7 +675,7 @@ end`;
571
675
  }
572
676
  /**
573
677
  * --- 批量获取哈希键值对 ---
574
- * @param key
678
+ * @param key 键
575
679
  */
576
680
  async hGetAll(key) {
577
681
  const conn = await this._getConnection();
@@ -579,7 +683,7 @@ end`;
579
683
  return false;
580
684
  }
581
685
  try {
582
- return await conn.hGetAll(this._etc.pre + key);
686
+ return await conn.hGetAll(this._pre + key);
583
687
  }
584
688
  catch {
585
689
  return false;
@@ -587,16 +691,19 @@ end`;
587
691
  }
588
692
  /**
589
693
  * --- 删除哈希键 ---
590
- * @param key
591
- * @param fields 值序列
694
+ * @param key 键
695
+ * @param fields 字段序列
592
696
  */
593
697
  async hDel(key, fields) {
698
+ if (Array.isArray(fields) && fields.length === 0) {
699
+ return 0;
700
+ }
594
701
  const conn = await this._getConnection();
595
702
  if (!conn) {
596
703
  return false;
597
704
  }
598
705
  try {
599
- return await conn.hDel(this._etc.pre + key, fields);
706
+ return await conn.hDel(this._pre + key, fields);
600
707
  }
601
708
  catch {
602
709
  return false;
@@ -604,8 +711,8 @@ end`;
604
711
  }
605
712
  /**
606
713
  * --- 判断哈希字段是否存在 ---
607
- * @param key
608
- * @param field
714
+ * @param key 键
715
+ * @param field 字段
609
716
  */
610
717
  async hExists(key, field) {
611
718
  const conn = await this._getConnection();
@@ -613,7 +720,7 @@ end`;
613
720
  return false;
614
721
  }
615
722
  try {
616
- return await conn.hExists(this._etc.pre + key, field);
723
+ return (await conn.hExists(this._pre + key, field)) === 1;
617
724
  }
618
725
  catch {
619
726
  return false;
@@ -632,10 +739,10 @@ end`;
632
739
  }
633
740
  try {
634
741
  if (Number.isInteger(increment)) {
635
- return await conn.hIncr(this._etc.pre + key, field, increment);
742
+ return await conn.hIncrBy(this._pre + key, field, increment);
636
743
  }
637
744
  else {
638
- return await conn.hIncrByFloat(this._etc.pre + key, field, increment);
745
+ return Number(await conn.hIncrByFloat(this._pre + key, field, increment));
639
746
  }
640
747
  }
641
748
  catch {
@@ -644,7 +751,7 @@ end`;
644
751
  }
645
752
  /**
646
753
  * --- 获取哈希所有字段 ---
647
- * @param key
754
+ * @param key 键
648
755
  */
649
756
  async hKeys(key) {
650
757
  const conn = await this._getConnection();
@@ -652,190 +759,376 @@ end`;
652
759
  return false;
653
760
  }
654
761
  try {
655
- return await conn.hKeys(this._etc.pre + key);
762
+ return await conn.hKeys(this._pre + key);
656
763
  }
657
764
  catch {
658
765
  return false;
659
766
  }
660
767
  }
768
+ /**
769
+ * --- 从列表左侧推入元素 ---
770
+ * @param key 键
771
+ * @param values 元素数组
772
+ */
661
773
  async lPush(key, values) {
774
+ if (values.length === 0) {
775
+ return 0;
776
+ }
662
777
  const conn = await this._getConnection();
663
778
  if (!conn) {
664
779
  return false;
665
780
  }
666
781
  try {
667
- return await conn.lPush(this._etc.pre + key, values);
782
+ return await conn.lPush(this._pre + key, values);
668
783
  }
669
784
  catch {
670
785
  return false;
671
786
  }
672
787
  }
788
+ /**
789
+ * --- 从列表右侧推入元素 ---
790
+ * @param key 键
791
+ * @param values 元素数组
792
+ */
673
793
  async rPush(key, values) {
794
+ if (values.length === 0) {
795
+ return 0;
796
+ }
674
797
  const conn = await this._getConnection();
675
798
  if (!conn) {
676
799
  return false;
677
800
  }
678
801
  try {
679
- return await conn.rPush(this._etc.pre + key, values);
802
+ return await conn.rPush(this._pre + key, values);
680
803
  }
681
804
  catch {
682
805
  return false;
683
806
  }
684
807
  }
808
+ /**
809
+ * --- 阻塞式在两个列表间移动元素(使用独立连接,避免阻塞共享连接) ---
810
+ * @param sourceKey 源列表键
811
+ * @param destKey 目标列表键
812
+ * @param soo 源端方向
813
+ * @param deo 目标端方向
814
+ * @param timeout 超时秒数,0 为无限等待
815
+ */
685
816
  async bLMove(sourceKey, destKey, soo, deo, timeout) {
686
- const conn = await this._getConnection();
687
- if (!conn) {
688
- return false;
689
- }
690
- try {
691
- return await conn.bLMove(this._etc.pre + sourceKey, this._etc.pre + destKey, soo, deo, timeout);
692
- }
693
- catch {
694
- return false;
695
- }
817
+ return this._runBlocking(timeout, async (blocking) => {
818
+ return blocking.blMove(this._pre + sourceKey, this._pre + destKey, soo, deo, timeout);
819
+ });
696
820
  }
821
+ /**
822
+ * --- 从列表左侧弹出元素 ---
823
+ * @param key 键
824
+ */
697
825
  async lPop(key) {
698
826
  const conn = await this._getConnection();
699
827
  if (!conn) {
700
828
  return false;
701
829
  }
702
830
  try {
703
- return await conn.lPop(this._etc.pre + key);
831
+ return await conn.lPop(this._pre + key);
704
832
  }
705
833
  catch {
706
834
  return false;
707
835
  }
708
836
  }
837
+ /**
838
+ * --- 从列表右侧弹出元素 ---
839
+ * @param key 键
840
+ */
709
841
  async rPop(key) {
710
842
  const conn = await this._getConnection();
711
843
  if (!conn) {
712
844
  return false;
713
845
  }
714
846
  try {
715
- return await conn.rPop(this._etc.pre + key);
847
+ return await conn.rPop(this._pre + key);
716
848
  }
717
849
  catch {
718
850
  return false;
719
851
  }
720
852
  }
853
+ /**
854
+ * --- 阻塞式从列表右侧弹出元素(使用独立连接,避免阻塞共享连接) ---
855
+ * @param key 单个或序列键
856
+ * @param timeout 超时秒数,0 为无限等待
857
+ */
721
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) {
722
882
  const conn = await this._getConnection();
723
883
  if (!conn) {
724
884
  return false;
725
885
  }
726
886
  try {
727
- if (typeof key === 'string') {
728
- key = [key];
729
- }
730
- return await conn.bRPop(key.map(item => this._etc.pre + item), timeout);
887
+ return await conn.lRange(this._pre + key, start, stop);
731
888
  }
732
889
  catch {
733
890
  return false;
734
891
  }
735
892
  }
736
- async lRange(key, start, stop) {
893
+ /**
894
+ * --- 获取列表长度 ---
895
+ * @param key 键
896
+ */
897
+ async lLen(key) {
737
898
  const conn = await this._getConnection();
738
899
  if (!conn) {
739
900
  return false;
740
901
  }
741
902
  try {
742
- return await conn.lRange(this._etc.pre + key, start, stop);
903
+ return await conn.lLen(this._pre + key);
743
904
  }
744
905
  catch {
745
906
  return false;
746
907
  }
747
908
  }
748
- async lLen(key) {
909
+ /**
910
+ * --- 添加有序集合元素 ---
911
+ */
912
+ async zAdd(key, scoreOrItems, memberOrOptions) {
749
913
  const conn = await this._getConnection();
750
914
  if (!conn) {
751
915
  return false;
752
916
  }
753
917
  try {
754
- 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);
755
947
  }
756
948
  catch {
757
949
  return false;
758
950
  }
759
951
  }
760
952
  /**
761
- * --- 添加有序集合元素 ---
953
+ * --- 查询有序集合成员及分数 ---
954
+ * @param key 键
955
+ * @param start 起点
956
+ * @param stop 终点
957
+ * @param options 范围与分页选项
762
958
  */
763
- async zAdd(key, scoreOrItems, memberOrOptions) {
959
+ async zRangeWithScores(key, start, stop, options) {
764
960
  const conn = await this._getConnection();
765
961
  if (!conn) {
766
962
  return false;
767
963
  }
768
964
  try {
769
- 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
+ }));
770
983
  }
771
984
  catch {
772
985
  return false;
773
986
  }
774
987
  }
775
- 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
+ }
776
997
  const conn = await this._getConnection();
777
998
  if (!conn) {
778
999
  return false;
779
1000
  }
780
1001
  try {
781
- return await conn.zRangeWithScores(this._etc.pre + key, start, stop, {
782
- 'by': options?.by,
783
- 'reverse': options?.rev,
784
- 'offset': options?.offset,
785
- 'count': options?.count,
786
- });
1002
+ return await conn.zRem(this._pre + key, members);
787
1003
  }
788
1004
  catch {
789
1005
  return false;
790
1006
  }
791
1007
  }
792
- async zRem(key, members) {
1008
+ /**
1009
+ * --- 在独立副本连接上执行阻塞命令,避免阻塞共享连接和触发默认 5 秒命令超时 ---
1010
+ * @param timeout 阻塞超时秒数,0 为无限等待
1011
+ * @param fn 实际执行函数
1012
+ */
1013
+ async _runBlocking(timeout, fn) {
793
1014
  const conn = await this._getConnection();
794
1015
  if (!conn) {
795
1016
  return false;
796
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
+ });
797
1030
  try {
798
- return await conn.zRem(this._etc.pre + key, members);
1031
+ await blocking.connect();
1032
+ return await fn(blocking);
799
1033
  }
800
1034
  catch {
801
1035
  return false;
802
1036
  }
1037
+ finally {
1038
+ blocking.destroy();
1039
+ }
803
1040
  }
804
1041
  /**
805
- * --- 从连接池中获取一个符合要求的连接 ---
1042
+ * --- 从连接池中获取一个符合要求的共享连接 ---
806
1043
  */
807
1044
  async _getConnection() {
808
- const item = connections.find(item => (item.host === this._etc.host) && (item.port === this._etc.port) && (item.index === this._etc.index));
809
- if (item) {
810
- 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
+ }
811
1062
  }
812
- // --- 没有找到合适的连接,创建一个 ---
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
+ });
813
1121
  try {
814
- const conn = redis.createCommandClient({
815
- 'host': this._etc.host,
816
- 'port': this._etc.port,
817
- });
818
- // --- 认证 ---
819
- if (this._etc.pwd) {
820
- 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;
821
1126
  }
822
- await conn.select(this._etc.index);
823
- conn.on('error', function (err) {
824
- lCore.debug('[KV][_getConnection][error]', err);
825
- }).on('end', () => {
826
- // --- 断线,不重要,会自动重连 ---
827
- }).on('close', () => {
828
- // --- 断线,不重要,会自动重连 ---
829
- });
830
- connections.push({
831
- 'host': this._etc.host,
832
- 'port': this._etc.port,
833
- 'index': this._etc.index,
834
- 'conn': conn,
835
- });
1127
+ initialized = true;
836
1128
  return conn;
837
1129
  }
838
1130
  catch {
1131
+ conn.destroy();
839
1132
  return null;
840
1133
  }
841
1134
  }
@@ -843,12 +1136,9 @@ end`;
843
1136
  /**
844
1137
  * --- 获取 Kv 对象 ---
845
1138
  * @param ctrEtc 控制器或配置信息
846
- * @param oetc 可用来覆盖 ctr 的一些选项,如 index
1139
+ * @param oetc 可用来覆盖 ctr 的部分连接选项
847
1140
  */
848
1141
  export function get(ctrEtc, oetc) {
849
1142
  const etc = ctrEtc instanceof sCtr.Ctr ? ctrEtc.getPrototype('_config').kv : ctrEtc;
850
- if (oetc) {
851
- Object.assign(etc, oetc);
852
- }
853
- return new Kv(etc);
1143
+ return new Kv(oetc ? { ...etc, ...oetc } : etc);
854
1144
  }