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 | 792x 792x 792x 20372x 20372x 20352x 20x 20372x 20372x | /** Chooses the pool a query runs on: the writer, or the next read replica in round-robin order. */
export class ReplicaRouter<P> {
/** Writer pool. */
readonly writer: P;
/** Read replica pools (may be empty). */
readonly readers: readonly P[];
#next = 0;
/**
* @param writer - Writer pool.
* @param readers - Read replica pools.
*/
constructor(writer: P, readers: readonly P[]) {
this.writer = writer;
this.readers = readers;
}
/**
* Pool for a query.
*
* @param route - `'read'` to use a replica when one is configured; anything else uses the writer.
* @returns Chosen pool.
*/
pool(route: 'read' | 'write' | undefined): P {
const readers = this.readers;
if (route !== 'read' || readers.length === 0) {
return this.writer;
}
const reader = readers[this.#next % readers.length] ?? this.writer;
this.#next += 1;
return reader;
}
}
|