All files / lib client.ts

86.98% Statements 147/169
69.57% Branches 32/46
91.89% Functions 34/37
87.2% Lines 143/164

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 3981x 1x 1x   1x 1x 1x                                                                     1x   148x 357x 357x                   85x       4x             85x 85x             1x       12x       12x       85x 85x 85x 85x 85x 85x 85x 85x       85x 88x   88x 1x     88x       88x 2x     88x 88x         88x     85x 280x   9x 9x   88x   87x 87x   9x 84x       85x   382x         85x 6x   22x       6x   6x     85x 85x   6x           85x                     85x   2x 2x 1x 1x                     1x 1x   1x       1x         85x   1x   1x 5x 5x   5x   5x       4x                       1x 148x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x               1x               158x 158x 3x         2x       85x           2x 1x 1x     2x 2x     85x     2x     85x     1x     85x     3x 3x 3x       2x     85x     1x     85x     3x 3x 3x       375x 1x 1x   1x 1x         1x       374x 374x 374x       6x       1x 1x 10x 10x 10x 100x           1x 1x 1x 1x 1x 100x           84x 84x       473x 473x 3x         470x 470x   470x           1x 148x    
import RedisSocket, { RedisSocketOptions } from './socket';
import RedisCommandsQueue, { PubSubListener, PubSubSubscribeCommands, PubSubUnsubscribeCommands, QueueCommandOptions } from './commands-queue';
import COMMANDS from './commands/client';
import { RedisCommand, RedisModules, RedisReply } from './commands';
import RedisMultiCommand, { MultiQueuedCommand, RedisMultiCommandType } from './multi-command';
import EventEmitter from 'events';
import { CommandOptions, commandOptions, isCommandOptions } from './command-options';
import { RedisLuaScript, RedisLuaScripts } from './lua-script';
import { ScanOptions } from './commands/generic-transformers';
import { ScanCommandOptions } from './commands/SCAN';
 
export interface RedisClientOptions<M = RedisModules, S = RedisLuaScripts> {
    socket?: RedisSocketOptions;
    modules?: M;
    scripts?: S;
    commandsQueueMaxLength?: number;
    readonly?: boolean;
    legacyMode?: boolean;
}
 
export type RedisCommandSignature<C extends RedisCommand> =
    (...args: Parameters<C['transformArguments']> | [options: CommandOptions<ClientCommandOptions>, ...rest: Parameters<C['transformArguments']>]) => Promise<ReturnType<C['transformReply']>>;
 
type WithCommands = {
    [P in keyof typeof COMMANDS]: RedisCommandSignature<(typeof COMMANDS)[P]>;
};
 
type WithModules<M extends RedisModules> = {
    [P in keyof M[number]]: RedisCommandSignature<M[number][P]>;
};
 
type WithScripts<S extends RedisLuaScripts> = {
    [P in keyof S]: RedisCommandSignature<S[P]>;
};
 
export type RedisClientType<M extends RedisModules, S extends RedisLuaScripts> = WithCommands & WithModules<M> & WithScripts<S> & RedisClient<M, S>;
 
export interface ClientCommandOptions extends QueueCommandOptions {
    duplicateConnection?: boolean;
}
 
export default class RedisClient<M extends RedisModules = RedisModules, S extends RedisLuaScripts = RedisLuaScripts> extends EventEmitter {
    static defineCommand(on: any, name: string, command: RedisCommand): void {
        on[name] = async function (...args: Array<unknown>): Promise<unknown> {
            const options = isCommandOptions(args[0]) && args.shift();
            return command.transformReply(
                await this.sendCommand(
                    command.transformArguments(...args),
                    options
                )
            );
        };
    }
 
    static create<M extends RedisModules, S extends RedisLuaScripts>(options?: RedisClientOptions<M, S>): RedisClientType<M, S> {
        return <any>new RedisClient<M, S>(options);
    }
 
    static commandOptions(options: ClientCommandOptions): CommandOptions<ClientCommandOptions> {
        return commandOptions(options);
    };
 
    readonly #options?: RedisClientOptions<M, S>;
    readonly #socket: RedisSocket;
    readonly #queue: RedisCommandsQueue;
    readonly #Multi: typeof RedisMultiCommand & { new(): RedisMultiCommandType<M, S> };
    readonly #modern: Record<string, Function> = {};
    #selectedDB = 0;
 
    get options(): RedisClientOptions<M> | null | undefined {
        return this.#options;
    }
 
    get isOpen(): boolean {
        return this.#socket.isOpen;
    }
 
    get modern(): Record<string, Function> {
        Iif (!this.#options?.legacyMode) {
            throw new Error('the client is not in "legacy mode"');
        }
 
        return this.#modern;
    }
 
    constructor(options?: RedisClientOptions<M, S>) {
        super();
        this.#options = options;
        this.#socket = this.#initiateSocket();
        this.#queue = this.#initiateQueue();
        this.#Multi = this.#initiateMulti();
        this.#initiateModules();
        this.#initiateScripts();
        this.#legacyMode();
    }
 
    #initiateSocket(): RedisSocket {
        const socketInitiator = async (): Promise<void> => {
            const promises = [];
 
            if (this.#selectedDB !== 0) {
                promises.push((this as any).select(RedisClient.commandOptions({ asap: true }), this.#selectedDB));
            }
 
            Iif (this.#options?.readonly) {
                promises.push((this as any).readonly(RedisClient.commandOptions({ asap: true })));
            }
 
            if (this.#options?.socket?.password) {
                promises.push((this as any).auth(RedisClient.commandOptions({ asap: true }), this.#options?.socket));
            }
 
            const resubscribePromise = this.#queue.resubscribe();
            Iif (resubscribePromise) {
                promises.push(resubscribePromise);
                this.#tick();
            }
            
            await Promise.all(promises);
        };
 
        return new RedisSocket(socketInitiator, this.#options?.socket)
            .on('data', data => this.#queue.parseResponse(data))
            .on('error', err => {
                this.emit('error', err);
                this.#queue.flushWaitingForReply(err);
            })
            .on('connect', () => this.emit('connect'))
            .on('ready', () => {
                this.emit('ready');
                this.#tick();
            })
            .on('reconnecting', () => this.emit('reconnecting'))
            .on('end', () => this.emit('end'));
    }
 
    #initiateQueue(): RedisCommandsQueue {
        return new RedisCommandsQueue(
            this.#options?.commandsQueueMaxLength,
            (encodedCommands: string) => this.#socket.write(encodedCommands)
        );
    }
 
    #initiateMulti(): typeof RedisMultiCommand & { new(): RedisMultiCommandType<M, S> } {
        const executor = async (commands: Array<MultiQueuedCommand>): Promise<Array<RedisReply>> => {
            const promise = Promise.all(
                commands.map(({encodedCommand}) => {
                    return this.#queue.addEncodedCommand(encodedCommand);
                })
            );
 
            this.#tick();
 
            return await promise;
        };
 
        const options = this.#options;
        return <any>class extends RedisMultiCommand {
            constructor() {
                super(executor, options);
            }
        };
    }
 
    #initiateModules(): void {
        Eif (!this.#options?.modules) return;
 
        for (const m of this.#options.modules) {
            for (const [name, command] of Object.entries(m)) {
                RedisClient.defineCommand(this, name, command);
                this.#Multi.defineCommand(this.#Multi, name, command);
            }
        }
    }
 
    #initiateScripts(): void {
        if (!this.#options?.scripts) return;
 
        for (const [name, script] of Object.entries(this.#options.scripts)) {
            (this as any)[name] = async function (...args: Parameters<typeof script.transformArguments>): Promise<ReturnType<typeof script.transformReply>> {
                const options = isCommandOptions(args[0]) && args[0];
                return script.transformReply(
                    await this.#executeScript(script, [
                        script.NUMBER_OF_KEYS.toString(),
                        ...script.transformArguments(options ? args.slice(1) : args)
                    ])
                );
            };
        }
    }
 
    async #executeScript<S extends RedisLuaScript>(script: S, args: Array<string>): Promise<ReturnType<S['transformReply']>> {
        try {
            return await this.sendCommand(['EVALSHA', script.SHA, ...args]);        
        } catch (err: any) {
            Iif (!err?.message?.startsWith?.('NOSCRIPT')) {
                throw err;
            }
 
            return await this.sendCommand(['EVAL', script.SCRIPT, ...args]);
        }
    }
 
    #legacyMode(): void {
        if (!this.#options?.legacyMode) return;
 
        this.#modern.sendCommand = this.sendCommand.bind(this);
 
        (this as any).sendCommand = (...args: Array<unknown>): void => {
            const options = isCommandOptions(args[0]) && args.shift(),
                callback = typeof args[args.length - 1] === 'function' && (args.pop() as Function);
            
            this.#modern.sendCommand(args.flat(), options)
                .then((reply: unknown) => {
                    if (!callback) return;
 
                    // https://github.com/NodeRedis/node-redis#commands:~:text=minimal%20parsing
 
                    callback(null, reply);
                })
                .catch((err: Error) => {
                    if (!callback) {
                        this.emit('error', err);
                        return;
                    }
 
                    callback(err);
                })
        }
 
        for (const name of Object.keys(COMMANDS)) {
            this.#defineLegacyCommand(name);
        }
 
        // hard coded commands
        this.#defineLegacyCommand('SELECT');
        this.#defineLegacyCommand('select');
        this.#defineLegacyCommand('SUBSCRIBE');
        this.#defineLegacyCommand('subscribe');
        this.#defineLegacyCommand('PSUBSCRIBE');
        this.#defineLegacyCommand('pSubscribe');
        this.#defineLegacyCommand('UNSUBSCRIBE');
        this.#defineLegacyCommand('unsubscribe');
        this.#defineLegacyCommand('PUNSUBSCRIBE');
        this.#defineLegacyCommand('pUnsubscribe');
 
        Iif (this.#options?.modules) {
            for (const m of this.#options.modules) {
                for (const name of Object.keys(m)) {
                    this.#defineLegacyCommand(name);
                }
            }
        }
 
        Iif (this.#options?.scripts) {
            for (const name of Object.keys(this.#options.scripts)) {
                this.#defineLegacyCommand(name);
            }
        }
    }
 
    #defineLegacyCommand(name: string): void {
        this.#modern[name] = (this as any)[name];
        (this as any)[name] = function (...args: Array<unknown>): void {
            this.sendCommand(name, ...args);
        };
    }
 
    duplicate(): RedisClientType<M, S> {
        return RedisClient.create(this.#options);
    }
 
    async connect(): Promise<void> {
        await this.#socket.connect();
    }
 
    async SELECT(db: number): Promise<void>;
    async SELECT(options: CommandOptions<ClientCommandOptions>, db: number): Promise<void>;
    async SELECT(options?: any, db?: any): Promise<void> {
        if (!isCommandOptions(options)) {
            db = options;
            options = null;
        }
 
        await this.sendCommand(['SELECT', db.toString()], options);
        this.#selectedDB = db;
    }
 
    select = this.SELECT;
 
    SUBSCRIBE(channels: string | Array<string>, listener: PubSubListener): Promise<void> {
        return this.#subscribe(PubSubSubscribeCommands.SUBSCRIBE, channels, listener);
    }
 
    subscribe = this.SUBSCRIBE;
 
    PSUBSCRIBE(patterns: string | Array<string>, listener: PubSubListener): Promise<void> {
        return this.#subscribe(PubSubSubscribeCommands.PSUBSCRIBE, patterns, listener);
    }
 
    pSubscribe = this.PSUBSCRIBE;
 
    #subscribe(command: PubSubSubscribeCommands, channels: string | Array<string>, listener: PubSubListener): Promise<void> {
        const promise = this.#queue.subscribe(command, channels, listener);
        this.#tick();
        return promise;
    }
 
    UNSUBSCRIBE(channels?: string | Array<string>, listener?: PubSubListener): Promise<void> {
        return this.#unsubscribe(PubSubUnsubscribeCommands.UNSUBSCRIBE, channels, listener);
    }
 
    unsubscribe = this.UNSUBSCRIBE;
 
    PUNSUBSCRIBE(patterns?: string | Array<string>, listener?: PubSubListener): Promise<void> {
        return this.#unsubscribe(PubSubUnsubscribeCommands.PUNSUBSCRIBE, patterns, listener);
    }
 
    pUnsubscribe = this.PUNSUBSCRIBE;
 
    #unsubscribe(command: PubSubUnsubscribeCommands, channels?: string | Array<string>, listener?: PubSubListener): Promise<void> {
        const promise = this.#queue.unsubscribe(command, channels, listener);
        this.#tick();
        return promise;
    }
 
    async sendCommand<T = unknown>(args: Array<string>, options?: ClientCommandOptions): Promise<T> {
        if (options?.duplicateConnection) {
            const duplicate = this.duplicate();
            await duplicate.connect();
 
            try {
                return await duplicate.sendCommand(args, {
                    ...options,
                    duplicateConnection: false
                });
            } finally {
                await duplicate.disconnect();
            }
        }
 
        const promise = this.#queue.addCommand<T>(args, options);
        this.#tick();
        return await promise;
    }
 
    multi(): RedisMultiCommandType<M, S> {
        return new this.#Multi();
    }
 
    async* scanIterator(options?: ScanCommandOptions): AsyncIterable<string> {
        let cursor = 0;
        do {
            const reply = await (this as any).scan(cursor, options);
            cursor = reply.cursor;
            for (const key of reply.keys) {
                yield key;
            }
        } while (cursor !== 0)
    }
 
    async* sScanIterator(key: string, options?: ScanOptions): AsyncIterable<string> {
        let cursor = 0;
        do {
            const reply = await (this as any).sScan(key, cursor, options);
            cursor = reply.cursor;
            for (const key of reply.keys) {
                yield key;
            }
        } while (cursor !== 0)
    }
 
    disconnect(): Promise<void> {
        this.#queue.flushAll(new Error('Disconnecting'));
        return this.#socket.disconnect();
    }
 
    #tick(): void {
        const {chunkRecommendedSize} = this.#socket;
        if (!chunkRecommendedSize) {
            return;
        }
 
        // TODO: batch using process.nextTick? maybe socket.setNoDelay(false)?
 
        const isBuffering = this.#queue.executeChunk(chunkRecommendedSize);
        Iif (isBuffering === true) {
            this.#socket.once('drain', () => this.#tick());
        } else Iif (isBuffering === false) {
            this.#tick();
        }
    }
}
 
for (const [name, command] of Object.entries(COMMANDS)) {
    RedisClient.defineCommand(RedisClient.prototype, name, command);
}