http_pool.nim 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # SPDX-License-Identifier: AGPL-3.0-only
  2. import httpclient
  3. type
  4. HttpPool* = ref object
  5. conns*: seq[AsyncHttpClient]
  6. var
  7. maxConns: int
  8. proxy: Proxy
  9. proc setMaxHttpConns*(n: int) =
  10. maxConns = n
  11. proc setHttpProxy*(url: string; auth: string) =
  12. if url.len > 0:
  13. proxy = newProxy(url, auth)
  14. else:
  15. proxy = nil
  16. proc release*(pool: HttpPool; client: AsyncHttpClient; badClient=false) =
  17. if pool.conns.len >= maxConns or badClient:
  18. try: client.close()
  19. except: discard
  20. elif client != nil:
  21. pool.conns.insert(client)
  22. proc acquire*(pool: HttpPool; heads: HttpHeaders): AsyncHttpClient =
  23. if pool.conns.len == 0:
  24. result = newAsyncHttpClient(headers=heads, proxy=proxy)
  25. else:
  26. result = pool.conns.pop()
  27. result.headers = heads
  28. template use*(pool: HttpPool; heads: HttpHeaders; body: untyped): untyped =
  29. var
  30. c {.inject.} = pool.acquire(heads)
  31. badClient {.inject.} = false
  32. try:
  33. body
  34. except ProtocolError:
  35. # Twitter closed the connection, retry
  36. body
  37. finally:
  38. pool.release(c, badClient)