File size: 4,782 Bytes
1a25764
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
'use strict';

const net = require('net');

class RedisClient {
  constructor({ url, host = '127.0.0.1', port = 6379, db = 0, password } = {}) {
    if (url) {
      const parsed = new URL(url);
      host = parsed.hostname || host;
      port = parsed.port ? parseInt(parsed.port, 10) : port;
      if (parsed.password) password = parsed.password;
      const dbMatch = parsed.pathname.match(/^\/(\d+)$/);
      if (dbMatch) db = parseInt(dbMatch[1], 10);
    }
    this.host = host;
    this.port = port;
    this.db = db;
    this.password = password;
    this.socket = null;
    this.connected = false;
    this.queue = [];
    this.buffer = '';
    this._connecting = false;
  }

  _encode(...args) {
    let cmd = `*${args.length}\r\n`;
    for (const arg of args) {
      const s = String(arg);
      cmd += `$${Buffer.byteLength(s)}\r\n${s}\r\n`;
    }
    return cmd;
  }

  _parse(buf, offset = 0) {
    if (offset >= buf.length) return null;
    const type = buf[offset];

    const lineEnd = buf.indexOf('\r\n', offset);
    if (lineEnd === -1) return null;
    const line = buf.slice(offset + 1, lineEnd);

    switch (type) {
      case 43: {
        return { value: line, consumed: lineEnd + 2 };
      }
      case 45: {
        const err = new Error(line);
        return { value: err, consumed: lineEnd + 2, isError: true };
      }
      case 58: {
        return { value: parseInt(line, 10), consumed: lineEnd + 2 };
      }
      case 36: {
        const len = parseInt(line, 10);
        if (len === -1) return { value: null, consumed: lineEnd + 2 };
        const dataStart = lineEnd + 2;
        const dataEnd = dataStart + len;
        if (buf.length < dataEnd + 2) return null;
        return { value: buf.slice(dataStart, dataEnd), consumed: dataEnd + 2 };
      }
      case 42: {
        const count = parseInt(line, 10);
        if (count === -1) return { value: null, consumed: lineEnd + 2 };
        const arr = [];
        let pos = lineEnd + 2;
        for (let i = 0; i < count; i++) {
          const item = this._parse(buf, pos);
          if (!item) return null;
          arr.push(item.value);
          pos = item.consumed;
        }
        return { value: arr, consumed: pos };
      }
      default:
        throw new Error(`Unknown RESP type: ${String.fromCharCode(type)}`);
    }
  }

  _onData(data) {
    this._rawBuf = this._rawBuf
      ? Buffer.concat([this._rawBuf, data])
      : Buffer.from(data);

    let offset = 0;
    while (this.queue.length > 0) {
      const result = this._parse(this._rawBuf, offset);
      if (!result) break;
      offset = result.consumed;
      const { resolve, reject } = this.queue.shift();
      if (result.isError) {
        reject(result.value);
      } else {
        resolve(result.value);
      }
    }
    if (offset > 0) {
      this._rawBuf = this._rawBuf.slice(offset);
    }
  }

  connect() {
    if (this.connected || this._connecting) return Promise.resolve();
    this._connecting = true;

    return new Promise((resolve, reject) => {
      this.socket = net.createConnection({ host: this.host, port: this.port });
      this._rawBuf = null;

      this.socket.on('data', (d) => this._onData(d));
      this.socket.on('error', (err) => {
        this.connected = false;
        this._connecting = false;
        reject(err);
        while (this.queue.length) {
          this.queue.shift().reject(err);
        }
      });
      this.socket.on('close', () => {
        this.connected = false;
        this._connecting = false;
      });
      this.socket.on('connect', async () => {
        this.connected = true;
        this._connecting = false;
        try {
          if (this.password) {
            await this.send('AUTH', this.password);
          }
          if (this.db !== 0) {
            await this.send('SELECT', this.db);
          }
          resolve();
        } catch (err) {
          this.connected = false;
          reject(err);
        }
      });
    });
  }

  send(...args) {
    return new Promise((resolve, reject) => {
      this.queue.push({ resolve, reject });
      this.socket.write(this._encode(...args));
    });
  }

  ping() { return this.send('PING'); }
  auth(password) { return this.send('AUTH', password); }
  get(key) { return this.send('GET', key); }
  set(key, value, ...opts) { return this.send('SET', key, value, ...opts); }
  setex(key, seconds, value) { return this.send('SETEX', key, seconds, value); }
  incr(key) { return this.send('INCR', key); }
  expire(key, seconds) { return this.send('EXPIRE', key, seconds); }
  del(...keys) { return this.send('DEL', ...keys); }
  ttl(key) { return this.send('TTL', key); }

  quit() {
    return this.send('QUIT').finally(() => this.socket.destroy());
  }
}

module.exports = RedisClient;