-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
command.ts
458 lines (417 loc) 路 12 KB
/
command.ts
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import * as commands from "redis-commands";
import * as calculateSlot from "cluster-key-slot";
import asCallback from "standard-as-callback";
import {
convertBufferToString,
optimizeErrorStack,
toArg,
convertMapToArray,
convertObjectToArray,
} from "./utils";
import { flatten } from "./utils/lodash";
import { get as getPromise } from "./promiseContainer";
import { CallbackFunction, ICommand, CommandParameter } from "./types";
interface ICommandOptions {
/**
* Set the encoding of the reply, by default buffer will be returned.
*
* @type {(string | null)}
* @memberof ICommandOptions
*/
replyEncoding?: string | null;
errorStack?: Error;
keyPrefix?: string;
/**
* Force the command to be readOnly so it will also execute on slaves
*/
readOnly?: boolean;
}
type ArgumentTransformer = (args: any[]) => any[];
type ReplyTransformer = (reply: any) => any;
interface IFlagMap {
[flag: string]: { [command: string]: true };
}
export interface ICommandNameFlags {
// Commands that can be processed when client is in the subscriber mode
VALID_IN_SUBSCRIBER_MODE: [
"subscribe",
"psubscribe",
"unsubscribe",
"punsubscribe",
"ping",
"quit"
];
// Commands that are valid in monitor mode
VALID_IN_MONITOR_MODE: ["monitor", "auth"];
// Commands that will turn current connection into subscriber mode
ENTER_SUBSCRIBER_MODE: ["subscribe", "psubscribe"];
// Commands that may make current connection quit subscriber mode
EXIT_SUBSCRIBER_MODE: ["unsubscribe", "punsubscribe"];
// Commands that will make client disconnect from server TODO shutdown?
WILL_DISCONNECT: ["quit"];
}
/**
* Command instance
*
* It's rare that you need to create a Command instance yourself.
*
* @export
* @class Command
*
* @example
* ```js
* var infoCommand = new Command('info', null, function (err, result) {
* console.log('result', result);
* });
*
* redis.sendCommand(infoCommand);
*
* // When no callback provided, Command instance will have a `promise` property,
* // which will resolve/reject with the result of the command.
* var getCommand = new Command('get', ['foo']);
* getCommand.promise.then(function (result) {
* console.log('result', result);
* });
* ```
* @see {@link Redis#sendCommand} which can send a Command instance to Redis
*/
export default class Command implements ICommand {
public static FLAGS: {
[key in keyof ICommandNameFlags]: ICommandNameFlags[key];
} = {
VALID_IN_SUBSCRIBER_MODE: [
"subscribe",
"psubscribe",
"unsubscribe",
"punsubscribe",
"ping",
"quit",
],
VALID_IN_MONITOR_MODE: ["monitor", "auth"],
ENTER_SUBSCRIBER_MODE: ["subscribe", "psubscribe"],
EXIT_SUBSCRIBER_MODE: ["unsubscribe", "punsubscribe"],
WILL_DISCONNECT: ["quit"],
};
private static flagMap?: IFlagMap;
private static getFlagMap(): IFlagMap {
if (!this.flagMap) {
this.flagMap = Object.keys(Command.FLAGS).reduce((map, flagName) => {
map[flagName] = {};
Command.FLAGS[flagName].forEach((commandName) => {
map[flagName][commandName] = true;
});
return map;
}, {});
}
return this.flagMap;
}
/**
* Check whether the command has the flag
*
* @param {string} flagName
* @param {string} commandName
* @return {boolean}
*/
public static checkFlag<T extends keyof ICommandNameFlags>(
flagName: T,
commandName: string
): commandName is ICommandNameFlags[T][number] {
return !!this.getFlagMap()[flagName][commandName];
}
private static _transformer: {
argument: { [command: string]: ArgumentTransformer };
reply: { [command: string]: ReplyTransformer };
} = {
argument: {},
reply: {},
};
public static setArgumentTransformer(
name: string,
func: ArgumentTransformer
) {
this._transformer.argument[name] = func;
}
public static setReplyTransformer(name: string, func: ReplyTransformer) {
this._transformer.reply[name] = func;
}
public ignore?: boolean;
public isReadOnly?: boolean;
private replyEncoding: string | null;
private errorStack: Error;
public args: CommandParameter[];
private callback: CallbackFunction;
private transformed = false;
public isCustomCommand = false;
public inTransaction = false;
public pipelineIndex?: number;
private _commandTimeoutTimer?: NodeJS.Timeout;
private slot?: number | null;
private keys?: Array<string | Buffer>;
public isResolved = false;
public reject: (err: Error) => void;
public resolve: (result: any) => void;
public promise: Promise<any>;
/**
* Creates an instance of Command.
* @param {string} name Command name
* @param {(Array<string | Buffer | number>)} [args=[]] An array of command arguments
* @param {ICommandOptions} [options={}]
* @param {CallbackFunction} [callback] The callback that handles the response.
* If omit, the response will be handled via Promise
* @memberof Command
*/
constructor(
public name: string,
args: Array<
string | Buffer | number | Array<string | Buffer | number | any[]>
> = [],
options: ICommandOptions = {},
callback?: CallbackFunction
) {
this.replyEncoding = options.replyEncoding;
this.errorStack = options.errorStack;
this.args = flatten(args);
this.callback = callback;
this.initPromise();
if (options.keyPrefix) {
this._iterateKeys((key) => options.keyPrefix + key);
}
if (options.readOnly) {
this.isReadOnly = true;
}
}
private initPromise() {
const Promise = getPromise();
const promise = new Promise((resolve, reject) => {
if (!this.transformed) {
this.transformed = true;
const transformer = Command._transformer.argument[this.name];
if (transformer) {
this.args = transformer(this.args);
}
this.stringifyArguments();
}
this.resolve = this._convertValue(resolve);
if (this.errorStack) {
this.reject = (err) => {
reject(optimizeErrorStack(err, this.errorStack.stack, __dirname));
};
} else {
this.reject = reject;
}
});
this.promise = asCallback(promise, this.callback);
}
public getSlot() {
if (typeof this.slot === "undefined") {
const key = this.getKeys()[0];
this.slot = key == null ? null : calculateSlot(key);
}
return this.slot;
}
public getKeys(): Array<string | Buffer> {
return this._iterateKeys();
}
/**
* Iterate through the command arguments that are considered keys.
*
* @param {Function} [transform=(key) => key] The transformation that should be applied to
* each key. The transformations will persist.
* @returns {string[]} The keys of the command.
* @memberof Command
*/
private _iterateKeys(
transform: Function = (key) => key
): Array<string | Buffer> {
if (typeof this.keys === "undefined") {
this.keys = [];
if (commands.exists(this.name)) {
const keyIndexes = commands.getKeyIndexes(this.name, this.args);
for (const index of keyIndexes) {
this.args[index] = transform(this.args[index]);
this.keys.push(this.args[index] as string | Buffer);
}
}
}
return this.keys;
}
/**
* Convert command to writable buffer or string
*
* @return {string|Buffer}
* @see {@link Redis#sendCommand}
* @public
*/
public toWritable(): string | Buffer {
let bufferMode = false;
for (const arg of this.args) {
if (arg instanceof Buffer) {
bufferMode = true;
break;
}
}
let result;
const commandStr =
"*" +
(this.args.length + 1) +
"\r\n$" +
Buffer.byteLength(this.name) +
"\r\n" +
this.name +
"\r\n";
if (bufferMode) {
const buffers = new MixedBuffers();
buffers.push(commandStr);
for (const arg of this.args) {
if (arg instanceof Buffer) {
if (arg.length === 0) {
buffers.push("$0\r\n\r\n");
} else {
buffers.push("$" + arg.length + "\r\n");
buffers.push(arg);
buffers.push("\r\n");
}
} else {
buffers.push(
"$" +
Buffer.byteLength(arg as string | Buffer) +
"\r\n" +
arg +
"\r\n"
);
}
}
result = buffers.toBuffer();
} else {
result = commandStr;
for (const arg of this.args) {
result +=
"$" +
Buffer.byteLength(arg as string | Buffer) +
"\r\n" +
arg +
"\r\n";
}
}
return result;
}
stringifyArguments(): void {
for (let i = 0; i < this.args.length; ++i) {
const arg = this.args[i];
if (!(arg instanceof Buffer) && typeof arg !== "string") {
this.args[i] = toArg(arg);
}
}
}
/**
* Convert the value from buffer to the target encoding.
*
* @private
* @param {Function} resolve The resolve function of the Promise
* @returns {Function} A function to transform and resolve a value
* @memberof Command
*/
private _convertValue(resolve: Function): (result: any) => void {
return (value) => {
try {
const existingTimer = this._commandTimeoutTimer;
if (existingTimer) {
clearTimeout(existingTimer);
delete this._commandTimeoutTimer;
}
resolve(this.transformReply(value));
this.isResolved = true;
} catch (err) {
this.reject(err);
}
return this.promise;
};
}
/**
* Convert buffer/buffer[] to string/string[],
* and apply reply transformer.
*
* @memberof Command
*/
public transformReply(
result: Buffer | Buffer[]
): string | string[] | Buffer | Buffer[] {
if (this.replyEncoding) {
result = convertBufferToString(result, this.replyEncoding);
}
const transformer = Command._transformer.reply[this.name];
if (transformer) {
result = transformer(result);
}
return result;
}
/**
* Set the wait time before terminating the attempt to execute a command
* and generating an error.
*/
public setTimeout(ms: number) {
if (!this._commandTimeoutTimer) {
this._commandTimeoutTimer = setTimeout(() => {
if (!this.isResolved) {
this.reject(new Error("Command timed out"));
}
}, ms);
}
}
}
const msetArgumentTransformer = function (args) {
if (args.length === 1) {
if (typeof Map !== "undefined" && args[0] instanceof Map) {
return convertMapToArray(args[0]);
}
if (typeof args[0] === "object" && args[0] !== null) {
return convertObjectToArray(args[0]);
}
}
return args;
};
const hsetArgumentTransformer = function (args) {
if (args.length === 2) {
if (typeof Map !== "undefined" && args[1] instanceof Map) {
return [args[0]].concat(convertMapToArray(args[1]));
}
if (typeof args[1] === "object" && args[1] !== null) {
return [args[0]].concat(convertObjectToArray(args[1]));
}
}
return args;
};
Command.setArgumentTransformer("mset", msetArgumentTransformer);
Command.setArgumentTransformer("msetnx", msetArgumentTransformer);
Command.setArgumentTransformer("hset", hsetArgumentTransformer);
Command.setArgumentTransformer("hmset", hsetArgumentTransformer);
Command.setReplyTransformer("hgetall", function (result) {
if (Array.isArray(result)) {
const obj = {};
for (let i = 0; i < result.length; i += 2) {
obj[result[i]] = result[i + 1];
}
return obj;
}
return result;
});
class MixedBuffers {
length = 0;
items = [];
public push(x: string | Buffer) {
this.length += Buffer.byteLength(x);
this.items.push(x);
}
public toBuffer(): Buffer {
const result = Buffer.allocUnsafe(this.length);
let offset = 0;
for (const item of this.items) {
const length = Buffer.byteLength(item);
Buffer.isBuffer(item)
? (item as Buffer).copy(result, offset)
: result.write(item, offset, length);
offset += length;
}
return result;
}
}