All files / lib socket.ts

84.34% Statements 70/83
75% Branches 24/32
78.57% Functions 11/14
84.15% Lines 69/82

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 2211x 1x 1x 1x                                                                   1x   86x 86x 86x               86x 86x     86x       6x       86x       86x       145x                 86x     1x       473x   470x       86x   86x 86x       86x       86x   86x 86x   2x 2x         89x 88x   88x 88x 88x   1x 1x 1x       87x       145x 59x     145x 145x   57x   57x       57x 57x 1x     56x 56x         145x 145x       145x 57x   88x       88x 3x       280x   88x           145x                           3x 3x   3x         382x       382x       84x       84x 84x 84x 84x 84x      
import EventEmitter from 'events';
import net from 'net';
import tls from 'tls';
import { setTimeout } from 'timers/promises';
 
interface RedisSocketCommonOptions {
    username?: string;
    password?: string;
    retryStrategy?(retries: number): number | Error;
}
 
interface RedisNetSocketOptions extends RedisSocketCommonOptions {
    port?: number;
    host?: string;
}
 
interface RedisUrlSocketOptions extends RedisSocketCommonOptions {
    url: string;
}
 
interface RedisUnixSocketOptions extends RedisSocketCommonOptions {
    path: string;
}
 
interface RedisTlsSocketOptions extends RedisNetSocketOptions {
    tls: tls.SecureContextOptions;
}
 
export type RedisSocketOptions = RedisNetSocketOptions | RedisUrlSocketOptions | RedisUnixSocketOptions | RedisTlsSocketOptions;
 
interface CreateSocketReturn<T> {
    connectEvent: string;
    socket: T;
}
 
export type RedisSocketInitiator = () => Promise<void>;
 
export default class RedisSocket extends EventEmitter {
    static #initiateOptions(options?: RedisSocketOptions): RedisSocketOptions {
        options ??= {};
        Eif (!RedisSocket.#isUnixSocket(options)) {
            Iif (RedisSocket.#isUrlSocket(options)) {
                const url = new URL(options.url);
                (options as RedisNetSocketOptions).port = Number(url.port);
                (options as RedisNetSocketOptions).host = url.hostname;
                options.username = url.username;
                options.password = url.password;
            }
 
            (options as RedisNetSocketOptions).port ??= 6379;
            (options as RedisNetSocketOptions).host ??= '127.0.0.1';
        }
 
        return options;
    }
 
    static #defaultRetryStrategy(retries: number): number {
        return Math.min(retries * 50, 500);
    }
 
    static #isUrlSocket(options: RedisSocketOptions): options is RedisUrlSocketOptions {
        return options.hasOwnProperty('url');
    }
 
    static #isUnixSocket(options: RedisSocketOptions): options is RedisUnixSocketOptions {
        return options.hasOwnProperty('path');
    }
 
    static #isTlsSocket(options: RedisSocketOptions): options is RedisTlsSocketOptions {
        return options.hasOwnProperty('tls');
    }
 
    readonly #initiator?: RedisSocketInitiator;
 
    readonly #options: RedisSocketOptions;
 
    #socket?: net.Socket | tls.TLSSocket;
 
    #isOpen = false;
 
    get isOpen(): boolean {
        return this.#isOpen;
    }
 
    get chunkRecommendedSize(): number {
        if (!this.#socket) return 0;
 
        return this.#socket.writableHighWaterMark - this.#socket.writableLength;
    }
 
    constructor(initiator?: RedisSocketInitiator, options?: RedisSocketOptions) {
        super();
 
        this.#initiator = initiator;
        this.#options = RedisSocket.#initiateOptions(options);
    }
 
    async connect(): Promise<void> {
        Iif (this.#isOpen) {
            throw new Error('Socket is connection/connecting');
        }
 
        this.#isOpen = true;
 
        try {
            await this.#connect();
        } catch (err) {
            this.#isOpen = false;
            throw err;
        }
    }
 
    async #connect(hadError?: boolean): Promise<void> {
        this.#socket = await this.#retryConnection(0, hadError);
        this.emit('connect');
 
        Eif (this.#initiator) {
            try {
                await this.#initiator();
            } catch (err) {
                this.#socket.end();
                this.#socket = undefined;
                throw err;
            }
        }
 
        this.emit('ready');
    }
 
    async #retryConnection(retries: number, hadError?: boolean): Promise<net.Socket | tls.TLSSocket> {
        if (retries > 0 || hadError) {
            this.emit('reconnecting');
        }
 
        try {
            return await this.#createSocket();
        } catch (err) {
            this.emit('error', err);
 
            Iif (!this.#isOpen) {
                throw err;
            }
 
            const retryIn = (this.#options?.retryStrategy ?? RedisSocket.#defaultRetryStrategy)(retries);
            if (retryIn instanceof Error) {
                throw retryIn;
            }
 
            await setTimeout(retryIn);
            return this.#retryConnection(retries + 1);
        }
    }
 
    #createSocket(): Promise<net.Socket | tls.TLSSocket> {
        return new Promise((resolve, reject) => {
            const {connectEvent, socket} = RedisSocket.#isTlsSocket(this.#options) ?
                this.#createTlsSocket() :
                this.#createNetSocket();
 
            socket
                .once('error', (err) => reject(err))
                .once(connectEvent, () => {
                    socket
                        .off('error', reject)
                        .once('error', (err: Error) => this.#onSocketError(err))
                        .once('close', hadError => {
                            if (!hadError && this.#isOpen) {
                                this.#onSocketError(new Error('Socket closed unexpectedly'));
                            }
                        })
                        .on('drain', () => this.emit('drain'))
                        .on('data', (data: Buffer) => this.emit('data', data));
 
                    resolve(socket);
                });
        });
    }
 
    #createNetSocket(): CreateSocketReturn<net.Socket> {
        return {
            connectEvent: 'connect',
            socket: net.connect(this.#options as net.NetConnectOpts) // TODO
        };
    }
 
    #createTlsSocket(): CreateSocketReturn<tls.TLSSocket> {
        return {
            connectEvent: 'secureConnect',
            socket: tls.connect(this.#options as tls.ConnectionOptions) // TODO
        };
    }
 
    #onSocketError(err: Error): void {
        this.#socket = undefined;
        this.emit('error', err);
 
        this.#connect(true)
            .catch(err => this.emit('error', err));
    }
 
    write(encodedCommands: string): boolean {
        Iif (!this.#socket) {
            throw new Error('Socket is closed');
        }
 
        return this.#socket.write(encodedCommands);
    }
 
    async disconnect(): Promise<void> {
        Iif (!this.#isOpen || !this.#socket) {
            throw new Error('Socket is closed');
        }
 
        this.#isOpen = false;
        this.#socket.end();
        await EventEmitter.once(this.#socket, 'end');
        this.#socket = undefined;
        this.emit('end');
    }
}