All files / lib commands-queue.ts

57.6% Statements 72/125
46.77% Branches 29/62
66.67% Functions 12/18
57.02% Lines 69/121

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 3281x 1x 1x                                                             1x   216x           216x 272x 272x     216x       73x 7x                           33x   33x   33x         33x         33x   200x 200x                                           200x   2x           33x 33x       398x   398x 398x                 188x             210x 210x   210x 1x     209x 209x             209x 1x         1x       1x       1x         209x 3x   206x                                                                                               36x 36x                                                                   226x   192x 192x   192x 209x 209x 209x           192x 192x     192x   192x 192x   192x 209x 209x 1x     209x   209x           192x       88x       202x       202x       9x   9x 9x                     32x 32x      
import LinkedList, { Node } from 'yallist';
import RedisParser from 'redis-parser';
import { AbortError } from './errors';
 
export interface QueueCommandOptions {
    asap?: boolean;
    signal?: AbortSignal;
    chainId?: Symbol;
}
 
interface CommandWaitingToBeSent extends CommandWaitingForReply {
    encodedCommand: string;
    chainId?: Symbol;
    abort?: {
        signal: AbortSignal;
        listener(): void;
    };
}
 
interface CommandWaitingForReply {
    resolve(reply?: any): void;
    reject(err: Error): void;
    onWrite?(): void;
}
 
export type CommandsQueueExecutor = (encodedCommands: string) => boolean | undefined;
 
export type PubSubSubscribeCommand = 'SUBSCRIBE' | 'PSUBSCRIBE';
 
export type PubSubUnsubscribeCommand = 'UNSUBSCRIBE' | 'PUNSUBSCRIBE';
 
export type PubSubListener = (message: string, channel: string) => unknown;
 
export default class RedisCommandsQueue {
    static encodeCommand(args: Array<string>): string {
        const encoded = [
            `*${args.length}`,
            `$${args[0].length}`,
            args[0]
        ];
 
        for (let i = 1; i < args.length; i++) {
            const str = args[i].toString();
            encoded.push(`$${str.length}`, str);
        }
 
        return encoded.join('\r\n') + '\r\n';
    }
 
    static #flushQueue<T extends CommandWaitingForReply>(queue: LinkedList<T>, err: Error): void {
        while (queue.length) {
            queue.shift()!.reject(err);
        }
    }
 
    static #emitPubSubMessage(listeners: Set<PubSubListener>, message: string, channel: string): void {
        for (const listener of listeners) {
            listener(message, channel);
        }
    }
 
    readonly #maxLength: number | null | undefined;
 
    readonly #executor: CommandsQueueExecutor;
 
    readonly #waitingToBeSent = new LinkedList<CommandWaitingToBeSent>();
 
    readonly #waitingForReply = new LinkedList<CommandWaitingForReply>();
 
    readonly #pubSubState = {
        subscribing: 0,
        subscribed: 0
    };
 
    readonly #pubSubListeners = {
        channels: <Map<string, Set<PubSubListener>>>new Map(),
        patterns: <Map<string, Set<PubSubListener>>>new Map()
    };
 
    readonly #parser = new RedisParser({
        returnReply: (reply: unknown) => {
            console.log(reply, this.#pubSubState);
            Iif (this.#pubSubState.subscribed && Array.isArray(reply)) {
                switch (reply[0]) {
                    case 'message':
                        return RedisCommandsQueue.#emitPubSubMessage(
                            this.#pubSubListeners.channels.get(reply[1])!,
                            reply[2],
                            reply[1]
                        );
                    
                    case 'pmessage':
                        return RedisCommandsQueue.#emitPubSubMessage(
                            this.#pubSubListeners.patterns.get(reply[1])!,
                            reply[3],
                            reply[2]
                        );
 
                    case 'subscribe':
                    case 'psubscribe':
                        return console.log(reply);
                }
            }
            
            this.#shiftWaitingForReply().resolve(reply);
        },
        returnError: (err: Error) => this.#shiftWaitingForReply().reject(err)
    });
 
    #chainInExecution: Symbol | undefined;
 
    constructor(maxLength: number | null | undefined, executor: CommandsQueueExecutor) {
        this.#maxLength = maxLength;
        this.#executor = executor;
    }
 
    #isQueueBlocked<T = void>(): Promise<T> | undefined {
        Iif (this.#pubSubState.subscribing || this.#pubSubState.subscribed) {
            return Promise.reject(new Error('Cannot send commands in PubSub mode'));
        } else Eif (!this.#maxLength) {
            return;
        }
 
        return this.#waitingToBeSent.length + this.#waitingForReply.length >= this.#maxLength ?
            Promise.reject(new Error('The queue is full')) :
            undefined;
    }
 
    addCommand<T = unknown>(args: Array<string>, options?: QueueCommandOptions): Promise<T> {
        return this.#isQueueBlocked<T>() || this.addEncodedCommand(
            RedisCommandsQueue.encodeCommand(args),
            options
        );
    }
 
    addEncodedCommand<T = unknown>(encodedCommand: string, options?: QueueCommandOptions): Promise<T> {
        const fullQueuePromise = this.#isQueueBlocked<T>();
        Iif (fullQueuePromise) {
            return fullQueuePromise;
        } else if (options?.signal?.aborted) {
            return Promise.reject(new AbortError());
        }
 
        return new Promise((resolve, reject) => {
            const node = new LinkedList.Node<CommandWaitingToBeSent>({
                encodedCommand,
                chainId: options?.chainId,
                resolve,
                reject
            });
 
            if (options?.signal) {
                const listener = () => {
                    this.#waitingToBeSent.removeNode(node);
                    node.value.reject(new AbortError());
                };
 
                Iif (options.signal.aborted) {
                    return listener();
                }
 
                node.value.abort = {
                    signal: options.signal,
                    listener
                };
                options.signal.addEventListener('abort', listener, {
                    once: true
                });
            }
 
            if (options?.asap) {
                this.#waitingToBeSent.unshiftNode(node);
            } else {
                this.#waitingToBeSent.pushNode(node);
            }
        });
    }
 
    subscribe(command: PubSubSubscribeCommand, channels: string | Array<string>, listener: PubSubListener): Promise<void> {
        const channelsToSubscribe: Array<string> = [],
            listeners = command === 'SUBSCRIBE' ? this.#pubSubListeners.channels : this.#pubSubListeners.patterns;
        for (const channel of (Array.isArray(channels) ? channels : [channels])) {
            if (listeners.has(channel)) {
                listeners.get(channel)!.add(listener);
                continue;
            }
 
            listeners.set(channel, new Set([listener]));
            channelsToSubscribe.push(channel);
        }
 
        if (!channelsToSubscribe.length) {
            return Promise.resolve();
        }
 
        return this.#pushSubscribeCommand(command, channelsToSubscribe);
    }
 
    #subscribe() {
        
    }
 
    #pushSubscribeCommand(command: PubSubSubscribeCommand, channels: Array<string>): Promise<void> {
        this.#pubSubState.subscribing += channels.length;
        return new Promise((resolve, reject) => {
            this.#waitingToBeSent.push({
                encodedCommand: RedisCommandsQueue.encodeCommand([command, ...channels]),
                resolve: () => {
                    this.#pubSubState.subscribing -= channels.length;
                    this.#pubSubState.subscribed += channels.length;
                    resolve();
                },
                reject: () => {
                    this.#pubSubState.subscribing -= channels.length;
                    reject();
                }
            });
        });
    }
 
    resubscribe(): Promise<any> | undefined {
        Eif (!this.#pubSubState.subscribed && !this.#pubSubState.subscribing) {
            return;
        }
 
        this.#pubSubState.subscribed = this.#pubSubState.subscribing = 0;
 
        return Promise.all([
            this.#pushSubscribeCommand('SUBSCRIBE', Object.keys(this.#pubSubListeners.channels)),
            this.#pushSubscribeCommand('PSUBSCRIBE', Object.keys(this.#pubSubListeners.patterns))
        ]);
    }
 
    unsubscribe(command: PubSubUnsubscribeCommand, channels: string | Array<string>, listener?: PubSubListener) {
        const listeners = command === 'UNSUBSCRIBE' ? this.#pubSubListeners.patterns : this.#pubSubListeners.channels,
            channelsToUnsubscribe = [];
        for (const channel of channels) {
            const set = listeners.get(channel);
            if (!set) continue;
 
            let shouldUnsubscribe = !listener;
            if (listener) {
                set.delete(listener);
                shouldUnsubscribe = set.size === 0;
            }
 
            if (shouldUnsubscribe) {
                channelsToUnsubscribe.push(channel);
                listeners.delete(channel);
            }
        }
 
        console.log([command, ...channelsToUnsubscribe]);
    }
 
    executeChunk(recommendedSize: number): boolean | undefined {
        if (!this.#waitingToBeSent.length) return;
 
        const encoded: Array<string> = [];
        let size = 0,
            lastCommandChainId: Symbol | undefined;
        for (const command of this.#waitingToBeSent) {
            encoded.push(command.encodedCommand);
            size += command.encodedCommand.length;
            Iif (size > recommendedSize) {
                lastCommandChainId = command.chainId;
                break;
            }
        }
 
        Eif (!lastCommandChainId && encoded.length === this.#waitingToBeSent.length) {
            lastCommandChainId = this.#waitingToBeSent.tail!.value.chainId;
        }
 
        lastCommandChainId ??= this.#waitingToBeSent.tail?.value.chainId;
 
        this.#executor(encoded.join(''));
        console.log(encoded.join('').replaceAll('\r\n', '\\r\\n'));
 
        for (let i = 0; i < encoded.length; i++) {
            const waitingToBeSent = this.#waitingToBeSent.shift()!;
            if (waitingToBeSent.abort) {
                waitingToBeSent.abort.signal.removeEventListener('abort', waitingToBeSent.abort.listener);
            }
 
            waitingToBeSent.onWrite?.();
 
            this.#waitingForReply.push({
                resolve: waitingToBeSent.resolve,
                reject: waitingToBeSent.reject
            });
        }
 
        this.#chainInExecution = lastCommandChainId;
    }
 
    parseResponse(data: Buffer): void {
        this.#parser.execute(data);
    }
 
    #shiftWaitingForReply(): CommandWaitingForReply {
        Iif (!this.#waitingForReply.length) {
            throw new Error('Got an unexpected reply from Redis');
        }
 
        return this.#waitingForReply.shift()!;
    }
 
    flushWaitingForReply(err: Error): void {
        RedisCommandsQueue.#flushQueue(this.#waitingForReply, err);
 
        Eif (!this.#chainInExecution) {
            return;
        }
 
        while (this.#waitingToBeSent.head?.value.chainId === this.#chainInExecution) {
            this.#waitingToBeSent.shift();
        }
 
        this.#chainInExecution = undefined;
    }
 
    flushAll(err: Error): void {
        RedisCommandsQueue.#flushQueue(this.#waitingForReply, err);
        RedisCommandsQueue.#flushQueue(this.#waitingToBeSent, err);
    }
};