jsql-neo 6.8.3 → 6.8.6
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.
- package/README.md +1 -1
- package/bin/jsql +5 -2
- package/index.js +1 -1
- package/lib/bigint_json.js +12 -0
- package/lib/cache.js +20 -4
- package/lib/columnar_fast.js +3 -1
- package/lib/database.js +171 -47
- package/lib/date-types.js +4 -4
- package/lib/errors.js +4 -0
- package/lib/migrate.js +20 -8
- package/lib/mongo_server.js +238 -20
- package/lib/mysql_server.js +27 -22
- package/lib/nedb_compat.js +101 -11
- package/lib/pg_server.js +53 -12
- package/lib/redis_server.js +222 -77
- package/lib/sql.js +212 -35
- package/lib/sqlite_compat.js +17 -0
- package/lib/table.js +55 -12
- package/package.json +3 -3
- package/test/extra-coverage.test.js +4 -3
- package/test/issue-157-161.test.js +54 -0
- package/test/issue-162-179.test.js +220 -0
- package/test/issue-181-186.test.js +153 -0
- package/test/issue-187.test.js +36 -0
- package/test/issue-188-237.test.js +481 -0
- package/test/issue-63-68.test.js +2 -2
package/lib/redis_server.js
CHANGED
|
@@ -20,6 +20,62 @@ const net = require('net');
|
|
|
20
20
|
const fs = require('fs');
|
|
21
21
|
const path = require('path');
|
|
22
22
|
|
|
23
|
+
// Redis score/increment 必须是完整合法浮点数;parseFloat 会吞掉尾随垃圾("1abc" → 1)
|
|
24
|
+
function parseRedisFloat(raw) {
|
|
25
|
+
const s = String(raw).trim();
|
|
26
|
+
if (/^[+-]?inf(inity)?$/i.test(s)) return s.startsWith('-') ? -Infinity : Infinity;
|
|
27
|
+
if (!/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(s)) {
|
|
28
|
+
throw new Error('ERR value is not a valid float');
|
|
29
|
+
}
|
|
30
|
+
return Number(s);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// #175:索引必须是严格十进制整数;parseInt 会把 "x" 变 NaN、把 "1.5" 截断。
|
|
34
|
+
function parseRedisInt(raw) {
|
|
35
|
+
const s = String(raw).trim();
|
|
36
|
+
if (!/^-?\d+$/.test(s)) throw new Error('ERR value is not an integer or out of range');
|
|
37
|
+
const n = Number(s);
|
|
38
|
+
if (!Number.isSafeInteger(n)) throw new Error('ERR value is not an integer or out of range');
|
|
39
|
+
return n;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Redis glob:* / ? / [abc] / [!abc] / [a-c];其余正则元字符按字面转义
|
|
43
|
+
function globToRegex(pattern) {
|
|
44
|
+
const p = String(pattern);
|
|
45
|
+
let src = '^';
|
|
46
|
+
for (let i = 0; i < p.length; i++) {
|
|
47
|
+
const c = p[i];
|
|
48
|
+
if (c === '*') { src += '.*'; continue; }
|
|
49
|
+
if (c === '?') { src += '.'; continue; }
|
|
50
|
+
if (c === '[') {
|
|
51
|
+
const close = p.indexOf(']', i + 1);
|
|
52
|
+
if (close > i + 1) {
|
|
53
|
+
let body = p.slice(i + 1, close).replace(/\\/g, '\\\\');
|
|
54
|
+
if (body[0] === '!' || body[0] === '^') body = '^' + body.slice(1);
|
|
55
|
+
src += '[' + body + ']';
|
|
56
|
+
i = close;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
src += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
61
|
+
}
|
|
62
|
+
return new RegExp(src + '$');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// #225:bulk 载荷二进制安全。合法 UTF-8 仍按字符串保存(与历史行为/测试一致),
|
|
66
|
+
// 非法字节用 \u0001 前缀 + latin1 保真;回包时还原原始字节。
|
|
67
|
+
const BIN_PREFIX = '\u0001';
|
|
68
|
+
function decodeBulk(buf) {
|
|
69
|
+
const s = buf.toString('utf8');
|
|
70
|
+
if (Buffer.from(s, 'utf8').equals(buf)) return s;
|
|
71
|
+
return BIN_PREFIX + buf.toString('latin1');
|
|
72
|
+
}
|
|
73
|
+
function bulkToBuffer(v) {
|
|
74
|
+
const s = String(v);
|
|
75
|
+
if (s.startsWith(BIN_PREFIX)) return Buffer.from(s.slice(BIN_PREFIX.length), 'latin1');
|
|
76
|
+
return Buffer.from(s, 'utf8');
|
|
77
|
+
}
|
|
78
|
+
|
|
23
79
|
const TYPE_SIGNATURES = {
|
|
24
80
|
PING: 0, ECHO: 1, SET: -2, SETNX: 2, GET: 1, DEL: -1, EXISTS: -1, KEYS: 1,
|
|
25
81
|
TYPE: 1, EXPIRE: 2, TTL: 1, PERSIST: 1,
|
|
@@ -32,6 +88,9 @@ const TYPE_SIGNATURES = {
|
|
|
32
88
|
DBSIZE: 0, FLUSHALL: 0, FLUSHDB: 0, SELECT: 1, INFO: 0, AUTH: 1, QUIT: 0,
|
|
33
89
|
};
|
|
34
90
|
|
|
91
|
+
// #177:这些命令的成功回复是 RESP simple string;其余字符串结果一律走 bulk。
|
|
92
|
+
const SIMPLE_STRING_CMDS = new Set(['SET', 'MSET', 'SELECT', 'AUTH', 'FLUSHALL', 'FLUSHDB', 'TYPE']);
|
|
93
|
+
|
|
35
94
|
class RedisServer {
|
|
36
95
|
constructor(opts = {}) {
|
|
37
96
|
this.port = opts.port ?? 6379;
|
|
@@ -59,7 +118,9 @@ class RedisServer {
|
|
|
59
118
|
}
|
|
60
119
|
|
|
61
120
|
snapshotPath() {
|
|
62
|
-
|
|
121
|
+
// #187:':memory:' 是统一的纯内存哨兵,不能当成字面目录落盘
|
|
122
|
+
if (!this.dataDir || this.dataDir === ':memory:') return null;
|
|
123
|
+
return path.join(this.dataDir, 'data.rdb.json');
|
|
63
124
|
}
|
|
64
125
|
|
|
65
126
|
_restoreEntry(map, k, v) {
|
|
@@ -69,24 +130,64 @@ class RedisServer {
|
|
|
69
130
|
else map.set(k, v);
|
|
70
131
|
}
|
|
71
132
|
|
|
133
|
+
_applySnapshot(raw) {
|
|
134
|
+
if (raw && raw.__jsql_redis__ === 2 && raw.databases && typeof raw.databases === 'object') {
|
|
135
|
+
// v2:多 DB 快照 { __jsql_redis__: 2, databases: { "0": {...}, "1": {...} } }
|
|
136
|
+
for (const [idxStr, entries] of Object.entries(raw.databases)) {
|
|
137
|
+
const idx = Number(idxStr);
|
|
138
|
+
const map = this._dbs.get(idx);
|
|
139
|
+
if (!map || !entries || typeof entries !== 'object') continue;
|
|
140
|
+
for (const [k, v] of Object.entries(entries)) this._restoreEntry(map, k, v);
|
|
141
|
+
}
|
|
142
|
+
} else {
|
|
143
|
+
// v1:旧版只有单个 db,全部落到 0 号库
|
|
144
|
+
for (const [k, v] of Object.entries(raw || {})) this._restoreEntry(this._dbs.get(0), k, v);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
_reportLoadError(message) {
|
|
149
|
+
const err = new Error(message);
|
|
150
|
+
if (this.onError) {
|
|
151
|
+
try { this.onError(err); } catch (_) { /* 回调失败不影响启动 */ }
|
|
152
|
+
}
|
|
153
|
+
console.error('[jsql-neo] ' + message);
|
|
154
|
+
}
|
|
155
|
+
|
|
72
156
|
_load() {
|
|
73
157
|
const p = this.snapshotPath();
|
|
74
|
-
if (!p
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
158
|
+
if (!p) return;
|
|
159
|
+
const tmp = p + '.tmp';
|
|
160
|
+
let raw = null;
|
|
161
|
+
let source = null;
|
|
162
|
+
|
|
163
|
+
if (fs.existsSync(p)) {
|
|
164
|
+
try {
|
|
165
|
+
raw = JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
166
|
+
source = p;
|
|
167
|
+
} catch (e) {
|
|
168
|
+
// #179:快照损坏不能静默当空库;先保留现场,再尝试 .tmp
|
|
169
|
+
const backup = p + '.corrupt-' + Date.now();
|
|
170
|
+
try { fs.renameSync(p, backup); } catch (_) { /* 备份失败也要继续报告 */ }
|
|
171
|
+
this._reportLoadError(`redis snapshot corrupt (${p}): ${e.message}; backed up to ${backup}`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (!raw && fs.existsSync(tmp)) {
|
|
176
|
+
try {
|
|
177
|
+
raw = JSON.parse(fs.readFileSync(tmp, 'utf8'));
|
|
178
|
+
source = tmp;
|
|
179
|
+
} catch (e) {
|
|
180
|
+
const backup = tmp + '.corrupt-' + Date.now();
|
|
181
|
+
try { fs.renameSync(tmp, backup); } catch (_) {}
|
|
182
|
+
this._reportLoadError(`redis snapshot temp corrupt (${tmp}): ${e.message}; backed up to ${backup}`);
|
|
88
183
|
}
|
|
89
|
-
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
if (!raw) return;
|
|
187
|
+
this._applySnapshot(raw);
|
|
188
|
+
if (source === tmp) {
|
|
189
|
+
try { fs.renameSync(tmp, p); } catch (_) { /* 恢复失败不影响已加载数据 */ }
|
|
190
|
+
}
|
|
90
191
|
}
|
|
91
192
|
|
|
92
193
|
_scheduleSnapshot() {
|
|
@@ -139,8 +240,9 @@ class RedisServer {
|
|
|
139
240
|
execute(cmd, args) {
|
|
140
241
|
const sig = TYPE_SIGNATURES[cmd];
|
|
141
242
|
if (sig === undefined) throw new Error(`ERR unknown command '${cmd}'`);
|
|
142
|
-
|
|
143
|
-
if (sig
|
|
243
|
+
// #172:负 arity 表示最少参数个数,-2/-3 等也必须校验
|
|
244
|
+
if (sig >= 0 && args.length < sig) throw new Error(`ERR wrong number of arguments for '${cmd}' command`);
|
|
245
|
+
if (sig < 0 && args.length < -sig) throw new Error(`ERR wrong number of arguments for '${cmd}' command`);
|
|
144
246
|
switch (cmd) {
|
|
145
247
|
case 'PING': return args.length ? args[0] : 'PONG';
|
|
146
248
|
case 'ECHO': return args[0];
|
|
@@ -162,15 +264,24 @@ class RedisServer {
|
|
|
162
264
|
// Parse optional arguments: EX seconds | PX milliseconds | NX | XX
|
|
163
265
|
let ttl = null;
|
|
164
266
|
let nx = false, xx = false;
|
|
267
|
+
const seen = new Set();
|
|
165
268
|
for (let i = 2; i < args.length; i++) {
|
|
166
|
-
const opt = args[i].toUpperCase();
|
|
269
|
+
const opt = String(args[i]).toUpperCase();
|
|
270
|
+
if ((opt === 'EX' || opt === 'PX' || opt === 'NX' || opt === 'XX') && seen.has(opt)) {
|
|
271
|
+
throw new Error('ERR syntax error');
|
|
272
|
+
}
|
|
273
|
+
seen.add(opt);
|
|
167
274
|
if (opt === 'EX') {
|
|
168
|
-
const
|
|
169
|
-
if (
|
|
275
|
+
const raw = String(args[++i]).trim();
|
|
276
|
+
if (!/^[+-]?\d+$/.test(raw)) throw new Error("ERR invalid expire time in 'set' command");
|
|
277
|
+
const secs = Number(raw);
|
|
278
|
+
if (secs <= 0) throw new Error("ERR invalid expire time in 'set' command");
|
|
170
279
|
ttl = Date.now() + secs * 1000;
|
|
171
280
|
} else if (opt === 'PX') {
|
|
172
|
-
const
|
|
173
|
-
if (
|
|
281
|
+
const raw = String(args[++i]).trim();
|
|
282
|
+
if (!/^[+-]?\d+$/.test(raw)) throw new Error("ERR invalid expire time in 'set' command");
|
|
283
|
+
const ms = Number(raw);
|
|
284
|
+
if (ms <= 0) throw new Error("ERR invalid expire time in 'set' command");
|
|
174
285
|
ttl = Date.now() + ms;
|
|
175
286
|
} else if (opt === 'NX') {
|
|
176
287
|
nx = true;
|
|
@@ -180,6 +291,7 @@ class RedisServer {
|
|
|
180
291
|
throw new Error('ERR syntax error');
|
|
181
292
|
}
|
|
182
293
|
}
|
|
294
|
+
if (nx && xx) throw new Error('ERR syntax error');
|
|
183
295
|
const prev = this._get(key);
|
|
184
296
|
if (nx && prev) return null;
|
|
185
297
|
if (xx && !prev) return null;
|
|
@@ -219,7 +331,7 @@ class RedisServer {
|
|
|
219
331
|
return Buffer.byteLength(v.val, 'utf8');
|
|
220
332
|
}
|
|
221
333
|
case 'INCR': case 'DECR': case 'INCRBY': case 'DECRBY': {
|
|
222
|
-
const by = cmd === 'INCRBY' || cmd === 'DECRBY' ?
|
|
334
|
+
const by = cmd === 'INCRBY' || cmd === 'DECRBY' ? parseRedisInt(args[1]) : 1;
|
|
223
335
|
if (isNaN(by)) throw new Error('ERR value is not an integer or out of range');
|
|
224
336
|
const dir = cmd === 'DECR' || cmd === 'DECRBY' ? -1 : 1;
|
|
225
337
|
const v = this._get(args[0]);
|
|
@@ -233,19 +345,26 @@ class RedisServer {
|
|
|
233
345
|
return n;
|
|
234
346
|
}
|
|
235
347
|
case 'DEL': {
|
|
348
|
+
// #176:过期但尚未清理的键不应计入删除数
|
|
236
349
|
let n = 0;
|
|
237
|
-
for (const k of args)
|
|
350
|
+
for (const k of args) {
|
|
351
|
+
if (!this._get(k)) continue;
|
|
352
|
+
this.db.delete(k);
|
|
353
|
+
n++;
|
|
354
|
+
}
|
|
238
355
|
this._scheduleSnapshot();
|
|
239
356
|
return n;
|
|
240
357
|
}
|
|
241
358
|
case 'EXISTS': {
|
|
359
|
+
// Redis:重复 key 只计一次
|
|
242
360
|
let n = 0;
|
|
243
|
-
for (const k of args) if (this._get(k)) n++;
|
|
361
|
+
for (const k of new Set(args)) if (this._get(k)) n++;
|
|
244
362
|
return n;
|
|
245
363
|
}
|
|
246
364
|
case 'KEYS': {
|
|
247
365
|
const pat = args[0];
|
|
248
|
-
|
|
366
|
+
// #228:完整 glob(含 [abc]/[!abc]/[a-c]),与 Cache.keys 语义一致
|
|
367
|
+
const re = globToRegex(pat);
|
|
249
368
|
const keys = [];
|
|
250
369
|
for (const k of this.db.keys()) {
|
|
251
370
|
if (re.test(k) && this._get(k)) keys.push(k);
|
|
@@ -259,7 +378,7 @@ class RedisServer {
|
|
|
259
378
|
case 'EXPIRE': {
|
|
260
379
|
const v = this._get(args[0]);
|
|
261
380
|
if (!v) return 0;
|
|
262
|
-
const secs =
|
|
381
|
+
const secs = parseRedisInt(args[1]);
|
|
263
382
|
if (isNaN(secs)) throw new Error('ERR value is not an integer or out of range');
|
|
264
383
|
v.ttl = Date.now() + secs * 1000;
|
|
265
384
|
this._scheduleSnapshot();
|
|
@@ -275,6 +394,7 @@ class RedisServer {
|
|
|
275
394
|
const v = this._get(args[0]);
|
|
276
395
|
if (!v || !v.ttl) return 0;
|
|
277
396
|
v.ttl = null;
|
|
397
|
+
this._scheduleSnapshot();
|
|
278
398
|
return 1;
|
|
279
399
|
}
|
|
280
400
|
case 'HSET': {
|
|
@@ -284,7 +404,8 @@ class RedisServer {
|
|
|
284
404
|
const h = v ? { ...v.val } : {};
|
|
285
405
|
let n = 0;
|
|
286
406
|
for (let i = 1; i < args.length; i += 2) {
|
|
287
|
-
|
|
407
|
+
// #226:in 会遍历原型链,必须只判断自有字段
|
|
408
|
+
if (!Object.prototype.hasOwnProperty.call(h, args[i])) n++;
|
|
288
409
|
h[args[i]] = args[i + 1];
|
|
289
410
|
}
|
|
290
411
|
this.db.set(args[0], { type: 'hash', val: h, ttl: v ? v.ttl : null });
|
|
@@ -309,24 +430,30 @@ class RedisServer {
|
|
|
309
430
|
if (v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
310
431
|
let n = 0;
|
|
311
432
|
for (const f of args.slice(1)) if (v.val[f] !== undefined) { delete v.val[f]; n++; }
|
|
433
|
+
// #173:最后一个 field 删除后整个键也要删除
|
|
434
|
+
if (Object.keys(v.val).length === 0) this.db.delete(args[0]);
|
|
312
435
|
this._scheduleSnapshot();
|
|
313
436
|
return n;
|
|
314
437
|
}
|
|
315
438
|
case 'HEXISTS': {
|
|
316
439
|
const v = this._get(args[0]);
|
|
317
|
-
|
|
440
|
+
if (v && v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
441
|
+
return (v && v.val[args[1]] !== undefined) ? 1 : 0;
|
|
318
442
|
}
|
|
319
443
|
case 'HLEN': {
|
|
320
444
|
const v = this._get(args[0]);
|
|
321
|
-
|
|
445
|
+
if (v && v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
446
|
+
return v ? Object.keys(v.val).length : 0;
|
|
322
447
|
}
|
|
323
448
|
case 'HKEYS': {
|
|
324
449
|
const v = this._get(args[0]);
|
|
325
|
-
|
|
450
|
+
if (v && v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
451
|
+
return v ? Object.keys(v.val) : [];
|
|
326
452
|
}
|
|
327
453
|
case 'HVALS': {
|
|
328
454
|
const v = this._get(args[0]);
|
|
329
|
-
|
|
455
|
+
if (v && v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
456
|
+
return v ? Object.values(v.val) : [];
|
|
330
457
|
}
|
|
331
458
|
case 'LPUSH': case 'RPUSH': {
|
|
332
459
|
const v = this._get(args[0]);
|
|
@@ -373,7 +500,7 @@ class RedisServer {
|
|
|
373
500
|
const v = this._get(args[0]);
|
|
374
501
|
if (!v) return [];
|
|
375
502
|
if (v.type !== 'list') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
376
|
-
let start =
|
|
503
|
+
let start = parseRedisInt(args[1]), stop = parseRedisInt(args[2]);
|
|
377
504
|
const len = v.val.length;
|
|
378
505
|
if (start < 0) start = Math.max(0, len + start);
|
|
379
506
|
if (stop < 0) stop = len + stop;
|
|
@@ -384,7 +511,7 @@ class RedisServer {
|
|
|
384
511
|
const v = this._get(args[0]);
|
|
385
512
|
if (!v) return null;
|
|
386
513
|
if (v.type !== 'list') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
387
|
-
let i =
|
|
514
|
+
let i = parseRedisInt(args[1]);
|
|
388
515
|
if (i < 0) i = v.val.length + i;
|
|
389
516
|
return v.val[i] === undefined ? null : v.val[i];
|
|
390
517
|
}
|
|
@@ -392,7 +519,7 @@ class RedisServer {
|
|
|
392
519
|
const v = this._get(args[0]);
|
|
393
520
|
if (!v) return 0;
|
|
394
521
|
if (v.type !== 'list') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
395
|
-
const count =
|
|
522
|
+
const count = parseRedisInt(args[1]);
|
|
396
523
|
const target = args[2];
|
|
397
524
|
const out = [];
|
|
398
525
|
let removed = 0;
|
|
@@ -418,6 +545,8 @@ class RedisServer {
|
|
|
418
545
|
}
|
|
419
546
|
}
|
|
420
547
|
v.val = out;
|
|
548
|
+
// #173:列表删空后键也要删除
|
|
549
|
+
if (out.length === 0) this.db.delete(args[0]);
|
|
421
550
|
this._scheduleSnapshot();
|
|
422
551
|
return removed;
|
|
423
552
|
}
|
|
@@ -437,33 +566,35 @@ class RedisServer {
|
|
|
437
566
|
}
|
|
438
567
|
case 'SMEMBERS': {
|
|
439
568
|
const v = this._get(args[0]);
|
|
440
|
-
|
|
569
|
+
if (v && v.type !== 'set') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
570
|
+
return v ? [...v.val] : [];
|
|
441
571
|
}
|
|
442
572
|
case 'SISMEMBER': {
|
|
443
573
|
const v = this._get(args[0]);
|
|
444
|
-
|
|
574
|
+
if (v && v.type !== 'set') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
575
|
+
return (v && v.val.includes(args[1])) ? 1 : 0;
|
|
445
576
|
}
|
|
446
577
|
case 'SCARD': {
|
|
447
578
|
const v = this._get(args[0]);
|
|
448
|
-
|
|
579
|
+
if (v && v.type !== 'set') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
580
|
+
return v ? v.val.length : 0;
|
|
449
581
|
}
|
|
450
582
|
case 'ZADD': {
|
|
451
583
|
const key = args[0];
|
|
452
584
|
const v = this._get(key);
|
|
453
|
-
|
|
454
|
-
if (v && v.type === 'zset') zset = v.val;
|
|
455
|
-
else if (v) throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
456
|
-
else { this.db.set(key, { type: 'zset', val: {} }); zset = this.db.get(key).val; }
|
|
585
|
+
if (v && v.type !== 'zset') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
457
586
|
const rest = args.slice(1);
|
|
458
587
|
if (rest.length % 2 !== 0) throw new Error('ERR syntax error');
|
|
588
|
+
// #174:先完整校验所有 (score, member),任一非法则整条命令不产生变更
|
|
589
|
+
const zset = v ? { ...v.val } : {};
|
|
459
590
|
let added = 0;
|
|
460
591
|
for (let i = 0; i < rest.length; i += 2) {
|
|
461
|
-
const score =
|
|
592
|
+
const score = parseRedisFloat(rest[i]);
|
|
462
593
|
const member = rest[i + 1];
|
|
463
|
-
if (isNaN(score)) throw new Error('ERR value is not a valid float');
|
|
464
594
|
if (!(member in zset)) added++;
|
|
465
595
|
zset[member] = score;
|
|
466
596
|
}
|
|
597
|
+
this.db.set(key, { type: 'zset', val: zset, ttl: v ? v.ttl : null });
|
|
467
598
|
this._scheduleSnapshot();
|
|
468
599
|
return added;
|
|
469
600
|
}
|
|
@@ -471,8 +602,8 @@ class RedisServer {
|
|
|
471
602
|
const v = this._get(args[0]);
|
|
472
603
|
if (!v) return [];
|
|
473
604
|
if (v.type !== 'zset') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
474
|
-
const start =
|
|
475
|
-
const stop =
|
|
605
|
+
const start = parseRedisInt(args[1]);
|
|
606
|
+
const stop = parseRedisInt(args[2]);
|
|
476
607
|
const withScores = args[3] && args[3].toUpperCase() === 'WITHSCORES';
|
|
477
608
|
const entries = Object.entries(v.val).sort((a, b) => a[1] - b[1] || (a[0] < b[0] ? -1 : 1));
|
|
478
609
|
const from = start < 0 ? Math.max(0, entries.length + start) : start;
|
|
@@ -488,8 +619,8 @@ class RedisServer {
|
|
|
488
619
|
const v = this._get(args[0]);
|
|
489
620
|
if (!v) return [];
|
|
490
621
|
if (v.type !== 'zset') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
491
|
-
const start =
|
|
492
|
-
const stop =
|
|
622
|
+
const start = parseRedisInt(args[1]);
|
|
623
|
+
const stop = parseRedisInt(args[2]);
|
|
493
624
|
const withScores = args[3] && args[3].toUpperCase() === 'WITHSCORES';
|
|
494
625
|
const entries = Object.entries(v.val).sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? 1 : -1));
|
|
495
626
|
const from = start < 0 ? Math.max(0, entries.length + start) : start;
|
|
@@ -503,7 +634,8 @@ class RedisServer {
|
|
|
503
634
|
}
|
|
504
635
|
case 'ZSCORE': {
|
|
505
636
|
const v = this._get(args[0]);
|
|
506
|
-
if (
|
|
637
|
+
if (v && v.type !== 'zset') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
|
|
638
|
+
if (!v || !(args[1] in v.val)) return null;
|
|
507
639
|
// ZSCORE 的分数恒为 bulk string(含整数分数),不能落进 integer reply(#67)
|
|
508
640
|
return String(v.val[args[1]]);
|
|
509
641
|
}
|
|
@@ -521,13 +653,14 @@ class RedisServer {
|
|
|
521
653
|
for (const m of args.slice(1)) {
|
|
522
654
|
if (m in v.val) { delete v.val[m]; n++; }
|
|
523
655
|
}
|
|
656
|
+
// #173:最后一个成员删除后键也要删除
|
|
657
|
+
if (Object.keys(v.val).length === 0) this.db.delete(args[0]);
|
|
524
658
|
this._scheduleSnapshot();
|
|
525
659
|
return n;
|
|
526
660
|
}
|
|
527
661
|
case 'ZINCRBY': {
|
|
528
662
|
const key = args[0];
|
|
529
|
-
const inc =
|
|
530
|
-
if (isNaN(inc)) throw new Error('ERR value is not a valid float');
|
|
663
|
+
const inc = parseRedisFloat(args[1]);
|
|
531
664
|
const v = this._get(key);
|
|
532
665
|
let zset;
|
|
533
666
|
if (v && v.type === 'zset') zset = v.val;
|
|
@@ -684,7 +817,8 @@ class RedisServer {
|
|
|
684
817
|
if (len === -1) { parts.push(null); off = start; continue; } // $-1 null bulk
|
|
685
818
|
if (len < -1) throw new Error('ERR Protocol error: invalid bulk length');
|
|
686
819
|
if (buf.length < start + len + 2) return null; // 按字节判断
|
|
687
|
-
|
|
820
|
+
// #225:非法 UTF-8 字节用 latin1 保真,合法文本仍保持字符串
|
|
821
|
+
parts.push(decodeBulk(buf.slice(start, start + len)));
|
|
688
822
|
off = start + len + 2;
|
|
689
823
|
}
|
|
690
824
|
const cmd = String(parts[0] || '').toUpperCase();
|
|
@@ -705,26 +839,38 @@ class RedisServer {
|
|
|
705
839
|
if (this.password && !this._authedSockets.get(socket)) {
|
|
706
840
|
if (cmd === 'AUTH') {
|
|
707
841
|
const ok = this.execute('AUTH', args);
|
|
708
|
-
if (ok === 'OK')
|
|
709
|
-
|
|
842
|
+
if (ok === 'OK') {
|
|
843
|
+
this._authedSockets.set(socket, true);
|
|
844
|
+
socket.write('+OK\r\n');
|
|
845
|
+
} else {
|
|
846
|
+
this._send(socket, ok);
|
|
847
|
+
}
|
|
848
|
+
return;
|
|
710
849
|
}
|
|
711
850
|
return this._send(socket, new Error('NOAUTH Authentication required.'));
|
|
712
851
|
}
|
|
713
|
-
if (cmd === 'QUIT') {
|
|
852
|
+
if (cmd === 'QUIT') { socket.write('+OK\r\n'); socket.end(); return; }
|
|
714
853
|
if (cmd === 'GET') {
|
|
715
854
|
const r = this.execute(cmd, args);
|
|
716
855
|
if (r === null) {
|
|
717
856
|
this._send(socket, null);
|
|
718
857
|
} else {
|
|
719
858
|
// GET 返回值必须是 bulk string,即使内容是 "OK" 或 "PONG"
|
|
720
|
-
const buf =
|
|
721
|
-
socket.write('$' + buf.length + '\r\n'
|
|
859
|
+
const buf = bulkToBuffer(r);
|
|
860
|
+
socket.write(Buffer.concat([Buffer.from('$' + buf.length + '\r\n'), buf, Buffer.from('\r\n')]));
|
|
722
861
|
}
|
|
723
862
|
return;
|
|
724
863
|
}
|
|
725
864
|
const r = this.execute(cmd, args);
|
|
726
865
|
if (cmd === 'SELECT' && r === 'OK') this._selected.set(socket, this.selected);
|
|
727
|
-
|
|
866
|
+
// #177:只有命令级状态回复用 simple string;数据内容(ECHO/HGET/...)一律 bulk
|
|
867
|
+
if (cmd === 'PING' && args.length === 0) {
|
|
868
|
+
socket.write('+PONG\r\n');
|
|
869
|
+
} else if (typeof r === 'string' && SIMPLE_STRING_CMDS.has(cmd)) {
|
|
870
|
+
socket.write('+' + r + '\r\n');
|
|
871
|
+
} else {
|
|
872
|
+
this._send(socket, r);
|
|
873
|
+
}
|
|
728
874
|
} catch (e) {
|
|
729
875
|
this._send(socket, e);
|
|
730
876
|
} finally {
|
|
@@ -737,33 +883,32 @@ class RedisServer {
|
|
|
737
883
|
}
|
|
738
884
|
|
|
739
885
|
_send(socket, val) {
|
|
886
|
+
const CRLF = Buffer.from('\r\n');
|
|
887
|
+
const bulk = (v) => {
|
|
888
|
+
const b = bulkToBuffer(v);
|
|
889
|
+
return Buffer.concat([Buffer.from('$' + b.length + '\r\n', 'latin1'), b, CRLF]);
|
|
890
|
+
};
|
|
740
891
|
let out;
|
|
741
892
|
if (val instanceof Error) {
|
|
742
|
-
out = '-' + val.message + '\r\n';
|
|
893
|
+
out = Buffer.from('-' + val.message + '\r\n', 'utf8');
|
|
743
894
|
} else if (val === null) {
|
|
744
|
-
out = '$-1\r\n';
|
|
895
|
+
out = Buffer.from('$-1\r\n');
|
|
745
896
|
} else if (typeof val === 'number') {
|
|
746
897
|
// RESP integer reply 只能是十进制整数;小数必须走 bulk string(#67)。
|
|
747
|
-
// ZSCORE / ZINCRBY 的分数已在 handler 里转成字符串,这里是非整数数字的最后兜底。
|
|
748
898
|
out = Number.isInteger(val)
|
|
749
|
-
? ':' + val + '\r\n'
|
|
750
|
-
:
|
|
899
|
+
? Buffer.from(':' + val + '\r\n')
|
|
900
|
+
: bulk(val);
|
|
751
901
|
} else if (Array.isArray(val)) {
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
(v === null || v === undefined)
|
|
756
|
-
? '$-1\r\n'
|
|
757
|
-
: '$' + Buffer.byteLength(String(v), 'utf8') + '\r\n' + v + '\r\n'
|
|
758
|
-
).join('');
|
|
759
|
-
} else if (typeof val === 'string') {
|
|
760
|
-
if (val === 'OK' || val === 'PONG') {
|
|
761
|
-
out = '+' + val + '\r\n';
|
|
762
|
-
} else {
|
|
763
|
-
out = '$' + Buffer.byteLength(val, 'utf8') + '\r\n' + val + '\r\n';
|
|
902
|
+
const parts = [Buffer.from('*' + val.length + '\r\n')];
|
|
903
|
+
for (const v of val) {
|
|
904
|
+
parts.push((v === null || v === undefined) ? Buffer.from('$-1\r\n') : bulk(v));
|
|
764
905
|
}
|
|
906
|
+
out = Buffer.concat(parts);
|
|
907
|
+
} else if (typeof val === 'string') {
|
|
908
|
+
// 由调用方决定是否 simple string;这里默认按数据 bulk 编码
|
|
909
|
+
out = bulk(val);
|
|
765
910
|
} else {
|
|
766
|
-
out = '$-1\r\n';
|
|
911
|
+
out = Buffer.from('$-1\r\n');
|
|
767
912
|
}
|
|
768
913
|
socket.write(out);
|
|
769
914
|
}
|