2021-12-27 01:37:38 +00:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
2022-01-21 08:17:18 +00:00
|
|
|
import httpclient
|
2020-11-07 20:31:03 +00:00
|
|
|
|
|
|
|
type
|
|
|
|
HttpPool* = ref object
|
|
|
|
conns*: seq[AsyncHttpClient]
|
|
|
|
|
2022-01-23 01:29:03 +00:00
|
|
|
var
|
|
|
|
maxConns: int
|
|
|
|
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
|
|
|
|
|
2022-01-21 08:17:18 +00:00
|
|
|
proc release*(pool: HttpPool; client: AsyncHttpClient; badClient=false) =
|
|
|
|
if pool.conns.len >= maxConns or badClient:
|
|
|
|
try: client.close()
|
|
|
|
except: discard
|
2020-11-07 20:31:03 +00:00
|
|
|
elif client != nil:
|
|
|
|
pool.conns.insert(client)
|
|
|
|
|
2022-01-21 08:17:18 +00:00
|
|
|
proc acquire*(pool: HttpPool; heads: HttpHeaders): AsyncHttpClient =
|
2020-11-07 20:31:03 +00:00
|
|
|
if pool.conns.len == 0:
|
2022-01-21 08:17:18 +00:00
|
|
|
result = newAsyncHttpClient(headers=heads, proxy=proxy)
|
2020-11-07 20:31:03 +00:00
|
|
|
else:
|
2022-01-21 08:17:18 +00:00
|
|
|
result = pool.conns.pop()
|
|
|
|
result.headers = heads
|
|
|
|
|
|
|
|
template use*(pool: HttpPool; heads: HttpHeaders; body: untyped): untyped =
|
2022-01-23 01:29:03 +00:00
|
|
|
var
|
|
|
|
c {.inject.} = pool.acquire(heads)
|
|
|
|
badClient {.inject.} = false
|
2020-11-07 20:31:03 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
body
|
2023-08-29 21:58:03 +00:00
|
|
|
except BadClientError, ProtocolError:
|
|
|
|
# Twitter returned 503 or closed the connection, we need a new client
|
2023-04-21 12:41:30 +00:00
|
|
|
pool.release(c, true)
|
|
|
|
badClient = false
|
|
|
|
c = pool.acquire(heads)
|
|
|
|
body
|
2020-11-07 20:31:03 +00:00
|
|
|
finally:
|
2022-01-23 01:29:03 +00:00
|
|
|
pool.release(c, badClient)
|