All files / packages/telemetry/src/state connection-pool.ts

75% Statements 15/20
33.33% Branches 2/6
85.71% Functions 6/7
83.33% Lines 15/18

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                            34x     20x       1x       7x       3x 3x 3x       1x 1x 1x                         11x 11x 5x 5x   11x      
import type { DriverIdentity } from '@ydbjs/core'
 
export type ConnectionState = {
	live: number
	pessimized: number
}
 
/**
 * Per-driver state of the gRPC connection pool, rebuilt from
 * `ydb:driver.connection.*` events. Keyed by `DriverIdentity` *reference*
 * (Map identity), so callers must pass the same identity object that the
 * publisher stamps on each payload.
 */
export class ConnectionPoolRegistry {
	#connections = new Map<DriverIdentity, ConnectionState>()
 
	connections(): ReadonlyMap<DriverIdentity, ConnectionState> {
		return this.#connections
	}
 
	driverClosed(driver: DriverIdentity): void {
		this.#connections.delete(driver)
	}
 
	connectionAdded(driver: DriverIdentity): void {
		this.#get(driver).live += 1
	}
 
	connectionPessimized(driver: DriverIdentity): void {
		let s = this.#get(driver)
		s.live = Math.max(0, s.live - 1)
		s.pessimized += 1
	}
 
	connectionUnpessimized(driver: DriverIdentity): void {
		let s = this.#get(driver)
		s.pessimized = Math.max(0, s.pessimized - 1)
		s.live += 1
	}
 
	// `retired` and `removed` collapse into one transition: the connection is
	// gone. The event doesn't carry the prior bucket, so we drain whichever
	// has stock.
	connectionRemoved(driver: DriverIdentity): void {
		let s = this.#get(driver)
		if (s.live > 0) s.live -= 1
		else if (s.pessimized > 0) s.pessimized -= 1
	}
 
	#get(driver: DriverIdentity): ConnectionState {
		let s = this.#connections.get(driver)
		if (!s) {
			s = { live: 0, pessimized: 0 }
			this.#connections.set(driver, s)
		}
		return s
	}
}