# Nim-Libp2p # Copyright (c) 2023 Status Research & Development GmbH # Licensed under either of # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) # * MIT license ([LICENSE-MIT](LICENSE-MIT)) # at your option. # This file may not be copied, modified, or distributed except according to # those terms. when (NimMajor, NimMinor) < (1, 4): {.push raises: [Defect].} else: {.push raises: [].} ## This module implements Pool of StreamTransport. import chronos const DefaultPoolSize* = 8 ## Default pool size type ConnectionFlags = enum None, Busy PoolItem = object transp*: StreamTransport flags*: set[ConnectionFlags] PoolState = enum Connecting, Connected, Closing, Closed TransportPool* = ref object ## Transports pool object transports: seq[PoolItem] busyCount: int state: PoolState bufferSize: int event: AsyncEvent TransportPoolError* = object of AsyncError proc waitAll[T](futs: seq[Future[T]]): Future[void] = ## Performs waiting for all Future[T]. var counter = len(futs) var retFuture = newFuture[void]("connpool.waitAllConnections") proc cb(udata: pointer) = dec(counter) if counter == 0: retFuture.complete() for fut in futs: fut.addCallback(cb) return retFuture proc newPool*(address: TransportAddress, poolsize: int = DefaultPoolSize, bufferSize = DefaultStreamBufferSize, ): Future[TransportPool] {.async.} = ## Establish pool of connections to address ``address`` with size ## ``poolsize``. var pool = new TransportPool pool.bufferSize = bufferSize pool.transports = newSeq[PoolItem](poolsize) var conns = newSeq[Future[StreamTransport]](poolsize) pool.state = Connecting for i in 0..