http_pool.nim 881 B

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