All files / lib cluster-slots.ts

3.75% Statements 3/80
0% Branches 0/24
0% Functions 0/7
3.9% Lines 3/77

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 1911x 1x                     1x                                                                                                                                                                                                                                                                                                                                                                    
import calculateSlot from 'cluster-key-slot';
import RedisClient from './client';
import { RedisSocketOptions } from './socket';
import { RedisClusterMasterNode, RedisClusterReplicaNode } from './commands/CLUSTER_NODES';
import { RedisClusterOptions } from './cluster';
 
interface SlotClients {
    master: RedisClient;
    replicas: Array<RedisClient>;
    iterator: IterableIterator<RedisClient> | undefined;
}
 
export default class RedisClusterSlots {
    readonly #options: RedisClusterOptions;
    readonly #clientByKey = new Map<string, RedisClient>();
    readonly #slots: Array<SlotClients> = [];
 
    constructor(options: RedisClusterOptions) {
        this.#options = options;
    }
 
    async connect(): Promise<void> {
        for (const rootNode of this.#options.rootNodes) {
            try {
                await this.#discoverNodes(rootNode);
                return;
            } catch (err) {
                // this.emit('error', err);
            }
        }
 
        throw new Error('None of the root nodes is available');
    }
 
    async discover(startWith: RedisClient): Promise<void> {
        try {
            await this.#discoverNodes(startWith.options?.socket);
            return;
        } catch (err) {
            // this.emit('error', err);
        }
 
        for (const client of this.#clientByKey.values()) {
            if (client === startWith) continue;
            
            try {
                await this.#discoverNodes(client.options?.socket);
                return;
            } catch (err) {
                // this.emit('error', err);
            }
        }
 
        throw new Error('None of the cluster nodes is available');
    }
 
    async #discoverNodes(socketOptions?: RedisSocketOptions) {
        const client = RedisClient.create({
            socket: socketOptions
        });
 
        await client.connect();
 
        try {
            await this.#reset(await client.clusterNodes());
        } finally {
            await client.disconnect(); // TODO: catch error from disconnect?
        }
    }
 
    async #reset(masters: Array<RedisClusterMasterNode>): Promise<void> {
        // Override this.#slots and add not existing clients to this.#clientByKey
        const promises: Array<Promise<void>> = [],
            clientsInUse = new Set<string>();
        for (const master of masters) {
            const masterClient = this.#initiateClientForNode(master, false, clientsInUse, promises),
                replicasClients = this.#options.useReplicas ?
                    master.replicas.map(replica => this.#initiateClientForNode(replica, true, clientsInUse, promises)) :
                    [];
 
            for (const slot of master.slots) {
                for (let i = slot.from; i < slot.to; i++) {
                    this.#slots[i] = {
                        master: masterClient,
                        replicas: replicasClients,
                        iterator: undefined // will be initiated in use
                    };
                }
            }
        }
 
        // Remove unused clients from this.#clientBykey using clientsInUse
        for (const [key, client] of this.#clientByKey.entries()) {
            if (clientsInUse.has(key)) continue;
 
            // TODO: ignore error from `.disconnect`?
            promises.push(client.disconnect());
            this.#clientByKey.delete(key);
        }
    }
 
    #initiateClientForNode(node: RedisClusterMasterNode | RedisClusterReplicaNode, readonly: boolean, clientsInUse: Set<string>, promises: Array<Promise<void>>): RedisClient {
        clientsInUse.add(node.url);
 
        let client = this.#clientByKey.get(node.url);
        if (!client) {
            client = RedisClient.create({
                socket: {
                    host: node.host,
                    port: node.port
                },
                readonly
            });
            promises.push(client.connect());
            this.#clientByKey.set(node.url, client);
        }
 
        return client;
    }
 
    #getSlotMaster(slot: number): RedisClient {
        return this.#slots[slot].master;
    }
 
    *#slotIterator(slotNumber: number): IterableIterator<RedisClient> {
        const slot = this.#slots[slotNumber];
        yield slot.master;
 
        for (const replica of slot.replicas) {
            yield replica;
        }
    }
 
    #getSlotClient(slotNumber: number): RedisClient {
        const slot = this.#slots[slotNumber];
        if (!slot.iterator) {
            slot.iterator = this.#slotIterator(slotNumber);
        }
 
        const {done, value} = slot.iterator.next();
        if (done) {
            slot.iterator = undefined;
            return this.#getSlotClient(slotNumber);
        }
 
        return value;
    }
 
    #randomClientIterator?: IterableIterator<RedisClient>;
 
    #getRandomClient(): RedisClient {
        if (!this.#clientByKey.size) {
            throw new Error('Cluster is not connected');
        }
 
        if (!this.#randomClientIterator) {
            this.#randomClientIterator = this.#clientByKey.values();
        }
 
        const {done, value} = this.#randomClientIterator.next();
        if (done) {
            this.#randomClientIterator = undefined;
            return this.#getRandomClient();
        }
 
        return value;
    }
 
    getClient(firstKey?: string, isReadonly?: boolean): RedisClient {
        if (!firstKey) {
            return this.#getRandomClient();
        }
 
        const slot = calculateSlot(firstKey);
        if (!isReadonly || !this.#options.useReplicas) {
            return this.#getSlotMaster(slot);
        }
 
        return this.#getSlotClient(slot);
    }
 
    async disconnect(): Promise<void> {
        await Promise.all(
            [...this.#clientByKey.values()].map(client => client.disconnect())
        );
 
        this.#clientByKey.clear();
        this.#slots.splice(0);
    }
}