2021-12-27 01:37:38 +00:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
2020-11-07 20:31:03 +00:00
|
|
|
import asyncdispatch, httpclient
|
|
|
|
|
|
|
|
type
|
|
|
|
HttpPool* = ref object
|
|
|
|
conns*: seq[AsyncHttpClient]
|
|
|
|
|
2022-01-02 10:21:03 +00:00
|
|
|
var maxConns: int
|
|
|
|
var proxy: Proxy
|
2020-11-07 20:31:03 +00:00
|
|
|
|
|
|
|
proc setMaxHttpConns*(n: int) =
|
|
|
|
maxConns = n
|
|
|
|
|
2021-09-30 16:03:07 +00:00
|
|
|
proc setHttpProxy*(url: string; auth: string) =
|
|
|
|
if url.len > 0:
|
|
|
|
proxy = newProxy(url, auth)
|
|
|
|
else:
|
|
|
|
proxy = nil
|
|
|
|
|
2020-11-07 20:31:03 +00:00
|
|
|
proc release*(pool: HttpPool; client: AsyncHttpClient) =
|
|
|
|
if pool.conns.len >= maxConns:
|
|
|
|
client.close()
|
|
|
|
elif client != nil:
|
|
|
|
pool.conns.insert(client)
|
|
|
|
|
|
|
|
template use*(pool: HttpPool; heads: HttpHeaders; body: untyped): untyped =
|
|
|
|
var c {.inject.}: AsyncHttpClient
|
|
|
|
|
|
|
|
if pool.conns.len == 0:
|
2021-09-30 16:03:07 +00:00
|
|
|
c = newAsyncHttpClient(headers=heads, proxy=proxy)
|
2020-11-07 20:31:03 +00:00
|
|
|
else:
|
|
|
|
c = pool.conns.pop()
|
|
|
|
c.headers = heads
|
|
|
|
|
|
|
|
try:
|
|
|
|
body
|
|
|
|
except ProtocolError:
|
|
|
|
# Twitter closed the connection, retry
|
|
|
|
body
|
|
|
|
finally:
|
|
|
|
pool.release(c)
|