Skip to content

Add asynchronous Prometheus client - #336

Open
git-arunjain wants to merge 2 commits into
4n4nd:masterfrom
git-arunjain:add-async-prometheus-client
Open

git-arunjain wants to merge 2 commits into
4n4nd:masterfrom
git-arunjain:add-async-prometheus-client

Conversation

@git-arunjain

Copy link
Copy Markdown

Summary

  • Add AsyncPrometheusConnect using aiohttp.
  • Implement asynchronous Prometheus API methods.
  • Support retries, authentication, proxies and timeouts.
  • Add async context manager support.
  • Export and document the new client.
  • Add asynchronous unit tests.

Testing

  • 30 async tests passed.
  • 10 existing mocked-network tests passed.
  • Black formatting check passed.
  • pip check passed.

Closes #298

@4n4nd

4n4nd commented Nov 11, 2026 •

Copy link
Copy Markdown
Owner

Thanks for this @git-arunjain — it's a thorough piece of work, and I appreciate that it comes with real tests and docs. I checked out the branch and ran it locally (Python 3.13 / aiohttp 3.14.5): 30 tests + 12 subtests pass, flake8 with the repo's pre-commit args is clean, and black --check --line-length 100 is clean.

A few things need fixing before this can go in. The first one is the important one.


Blocking

1. The default-configured client has every timeout disabled and will hang forever

_request always passes timeout= explicitly (async_prometheus_connect.py:149, and again at :238 in check_prometheus_connection).

aiohttp's signature is timeout: ClientTimeout | _SENTINEL = sentinel, and it only falls back to the session default if timeout is sentinel. An explicit None is not the sentinel — it takes the else branch and becomes ClientTimeout(total=None), discarding aiohttp's own DEFAULT_TIMEOUT(total=300, sock_connect=30).

Since timeout defaults to None in the constructor, the out-of-the-box client runs with every timeout switched off. Repro against a server that accepts the connection and never replies:

async def blackhole(request):
    await asyncio.sleep(3600)

async with AsyncPrometheusConnect(url=str(srv.make_url(""))) as p:  # default timeout=None
    await asyncio.wait_for(p.custom_query("up"), timeout=4)
default client: NO timeout fired in 4s -> hangs
timeout kwarg aiohttp received: None

A consequence worth noting: the asyncio.TimeoutError arm of the retry handler at :169 is unreachable under the default configuration.

In fairness this isn't a regression — PrometheusConnect hangs the same way, because requests also treats timeout=None as "no timeout". But aiohttp hands you a sane default for free and this actively throws it away. Simplest fix is to omit the kwarg entirely when there's no timeout configured:

kwargs = {}
if request_timeout is not None:
    kwargs["timeout"] = aiohttp.ClientTimeout(total=request_timeout)
async with session.request(..., **kwargs) as response:

or set it once on the session in _get_session().

Related, same area: timeout=0 passes the constructor's timeout < 0 check and then also means "no timeout", because aiohttp's TimeoutHandle.start() only arms a timer if timeout is not None and timeout > 0. Either reject <= 0 or document that 0 disables timeouts.

2. aiohttp should be an optional extra, not a core dependency

requirements-core.txt is read verbatim into install_requires by setup.py:get_install_requires(), so this makes aiohttp mandatory for every user of the library, including sync-only ones.

That runs against the slim-install work in 0.7.0 — see the note in README.md:

Starting from version 0.7.0, pandas, numpy, and matplotlib are optional dependencies. If you only need PrometheusConnect without DataFrame support or plotting capabilities, you can install the minimal version which significantly reduces memory footprint and installation time, especially on Alpine-based Docker images.

Measured cost on a clean env: 7 new packages, ~1 MB of wheels (aiohttp, aiohappyeyeballs, aiosignal, attrs, frozenlist, multidict, propcache) — four of them C extensions that compile from source on musl/Alpine when no musllinux wheel matches.

We also have tests/test_lazy_imports.py, which asserts that importing PrometheusConnect doesn't pull in the heavy optional deps. That test encodes the principle this change breaks.

The good news is your lazy __getattr__ in __init__.py already does exactly the right thing — I verified:

aiohttp in sys.modules after sync-only use:  False
aiohttp in sys.modules after async access:   True

So the extra works cleanly. Could you:

  • add "async": ["aiohttp>=3.9,<4"] to extras_require in setup.py (and into "all"), and drop it from requirements-core.txt — keep it in requirements.txt so CI still installs it;
  • guard the import aiohttp with a friendly ImportError, same pattern as get_metric_aggregation uses for numpy;
  • extend tests/test_lazy_imports.py to cover aiohttp;
  • add a README install bullet next to [dataframe] / [analytics] / [plot].

3. Environment proxy and TLS configuration is silently ignored

aiohttp.ClientSession() defaults to trust_env=False; requests.Session() defaults to trust_env=True. So HTTPS_PROXY, NO_PROXY, REQUESTS_CA_BUNDLE and netrc all work today with PrometheusConnect and silently stop working on switching to AsyncPrometheusConnect — no error, the request just goes direct. In a locked-down network that's either a connection failure or egress on an unintended path. Please pass trust_env=True at :94.

Separately, _get_proxy() at :103 only probes <scheme>, <scheme>_proxy and all. requests also accepts scheme+host keys like {"https://prometheus.internal": "http://proxy:3128"}; with that dict _get_proxy() returns None and the proxy is bypassed silently. Either validate unknown keys or document the supported shapes.

4. pre-commit fails on the new module

prometheus_api_client/async_prometheus_connect.py:33 in public method `__init__`:
        D107: Missing docstring in __init__

PrometheusConnect.__init__ has one. GitHub Actions won't catch this (it only runs flake8 --select=E9,F63,F7,F82 plus pytest), but pre-commit run --all-files does, which the README asks contributors to run. One-line fix.


Should fix

5. Parameter precedence is inverted relative to the sync client

Sync builds params={**{"query": q, "start": start, "end": end, "step": step}, **params} (prometheus_connect.py:524) — the caller's params win. The async version reverses it at :187, :213 and :332, so the built-ins win.

That means custom_query_range(q, t0, t1, step="15", params={"step": "60"}) resolves to step=60 on the sync client and step=15 on the async one, silently, with no error. test_custom_query_does_not_allow_params_to_override_query locks the new behaviour in deliberately — and it's arguably the safer design — but the two clients shouldn't disagree. Either match sync, or reject conflicting keys explicitly so a port fails loudly instead of returning different numbers.

6. method="POST" doesn't actually put the query in the body

Verified against a local server with method="POST":

{'method': 'POST', 'qs': 'query=up####################', 'body': '', 'ctype': 'application/octet-stream'}

The query goes in the URL, the body is empty, and the Content-Type is application/octet-stream. POST support exists precisely so that long PromQL queries don't hit URL-length limits, so as written it buys nothing. test_post_method only asserts request.method == "POST", so it passes.

This reproduces the same bug in the sync client (prometheus_connect.py:473-482 also passes params= for POST), so I'm not asking you to fix mine — but since this module is new, let's get it right here: use data=params for POST on the query endpoints, keep params= for the GET-only ones (series, labels, label/*/values), and assert the body in the test.

7. _request guesses the response shape

isinstance(data, dict) and "result" in data at :155 auto-unwraps. /api/v1/metadata returns data as a dict keyed by metric name, so a Prometheus scraping a metric literally named result makes get_metric_metadata receive a list and die on .items(). Narrow, but the sync client never guesses — each method unwraps explicitly. Prefer passing the intent in, e.g. _request(..., unwrap="result").

8. No way to supply a client cert or a custom CA

PrometheusConnect takes session: Session = None and threads cert= / verify= through every call. AsyncPrometheusConnect builds its session internally at :94 and hardcodes ssl=not self.disable_ssl, so for mTLS or a private CA the only options are "no verification at all" or "guaranteed handshake failure". Reaching in to set prom._session doesn't work either, since _get_session() replaces it whenever it's closed. An ssl / ssl_context parameter passed through to session.request(ssl=...) would cover it; a session= injection point would also help testing.

9. store_locally=True does blocking filesystem I/O inside the coroutine

_store_metric_values_local at :506 is synchronous — os.makedirs plus open(...).write() — and isn't offloaded, so every chunk stalls the whole event loop for the duration of the write. On an NFS-mounted volume or with multi-MB payloads that blocks every other task in the process, which defeats the point of an async client. await asyncio.to_thread(...) around the write.

Also import json at :341 sits inside the while loop; bz2/math/os are imported at module top, and prometheus_connect.py imports json at module level.

10. get_metric_range_data fetches chunks strictly sequentially

The while start < end loop at :327 awaits each chunk in turn, so 24 hourly chunks cost 24 serial round-trips — identical to the sync client. These queries are independent; this is the one place where async genuinely wins. Compute the boundaries first, then asyncio.gather over them (semaphore-bounded if you want to cap concurrency) and extend data in boundary order.

11. The retry except clause is too broad

except (aiohttp.ClientError, asyncio.TimeoutError) at :169 catches the base class of InvalidURL, ClientConnectorCertificateError, TooManyRedirects and ContentTypeError. Two consequences with the defaults (retry=3, backoff=1.0):

  • a TLS certificate-verification failure — permanent — burns 4 connection attempts and sleeps 1+2+4 = 7s before raising;
  • a reverse proxy returning a 200 HTML error page makes await response.json() at :152 raise ContentTypeError inside the try, so it's retried 4x and then surfaces as ContentTypeError rather than PrometheusApiClientException — callers following our docstrings catch only the latter.

The sync client's urllib3.Retry(status_forcelist=RETRY_ON_STATUS) retries only connection errors and the listed statuses. Move response.json() out of the retry block and narrow the except to connection/timeout errors.

12. check_prometheus_connection bypasses _request

It re-implements the session fetch, timeout wrapping, auth, proxy and ssl plumbing at :222-240, apparently only because its URL is {url}/ rather than {url}/api/v1/.... The cost: it never retries (the sync client's HTTPAdapter(max_retries=retry) mount does retry it — and this is the call most likely to hit a just-starting endpoint), it skips _request's timeout validation, and any future fix to _request has to be applied twice. Worth generalizing _request to take a base-relative path.

13. auth and proxy are unvalidated

The constructor validates url, method, retry, retry_backoff_factor and timeout exhaustively, then leaves these two to fail on the first request. auth=("user", "pass", "extra") constructs fine and only explodes at aiohttp.BasicAuth(*self.auth); a requests.auth.HTTPBasicAuth object — valid for PrometheusConnect — passes the isinstance(auth, tuple) check, is returned as-is, and raises an opaque TypeError from inside aiohttp. Worth normalizing both in __init__.


Non-blocking

  • Duplication. Roughly 400 lines of transport-independent logic are copied from prometheus_connect.py: _store_metric_values_local / _metric_filename verbatim, the ~60-line numpy aggregation dispatch, and the label_config → selector builder (twice within this file alone). The retry policy is re-hardcoded as literals when MAX_REQUEST_RETRIES / RETRY_BACKOFF_FACTOR / RETRY_ON_STATUS already exist at prometheus_connect.py:20-24. The drift is already visible in this PR — items 5 and 7 above, plus get_metric_range_data(start_time=t, end_time=t) raising ValueError where sync returns []. Every future fix now has to land twice and eventually will land once. A follow-up PR lifting the pure helpers into a shared module would be very welcome; at minimum please import the constants.
  • No logging. The sync module emits _LOGGER.debug for start/end/chunk/query; this one is silent, which makes chunked range queries harder to debug.
  • get_label_values interpolates label_name into the URL path unescaped at :266 (urllib.parse.quote(label_name, safe="")). Same latent issue exists at prometheus_connect.py:225.
  • _request never checks payload["status"] == "success" or surfaces payload["warnings"].
  • get_series sends float timestamps while custom_query_range sends rounded ints — pick one.
  • timeout is only accepted per-call on custom_query / custom_query_range; everything else uses the constructor value only.
  • retry: int + retry_backoff_factor here vs a urllib3.Retry object on the sync client — passing a Retry raises ValueError. Fine to keep the simpler API, but worth a docstring note for people porting.
  • The new heading in docs/source/prometheus_api_client.rst doesn't escape underscores the way its neighbours do.

What I particularly liked

  • It fixes two real bugs that exist on the sync side. start_time/end_time default to None and resolve at call time, avoiding the mutable-default-at-import bug at prometheus_connect.py:299-300 (where datetime.now() is evaluated once, at import). And current_chunk = min(chunk_seconds, end - start) avoids permanently mutating chunk_seconds the way :360-361 does. I'd happily take both of those as a separate PR against the sync client.
  • Constructor validation is genuinely thorough — the bool-vs-int and NaN/inf checks are the kind of thing that usually gets skipped.
  • Lazy session creation, close(), and async with are all properly tested, including close-and-recreate.
  • The tests add no new test dependencies and need no network — a real aiohttp.test_utils.TestServer plus stdlib IsolatedAsyncioTestCase. That's exactly right for this repo, and a nice improvement on the existing suite's reliance on a live demo endpoint.
  • test_get_series_uses_get_with_post_configuration is a good test to have thought of.

Happy to help with any of the above if you'd like a hand — items 1, 3 and 4 are all a couple of lines each, and item 2 is mostly mechanical.


Used AI to review this PR :)

@git-arunjain

Copy link
Copy Markdown
Author

Thanks for this @git-arunjain — it's a thorough piece of work, and I appreciate that it comes with real tests and docs. I checked out the branch and ran it locally (Python 3.13 / aiohttp 3.14.5): 30 tests + 12 subtests pass, flake8 with the repo's pre-commit args is clean, and black --check --line-length 100 is clean.

A few things need fixing before this can go in. The first one is the important one.

Blocking

1. The default-configured client has every timeout disabled and will hang forever

_request always passes timeout= explicitly (async_prometheus_connect.py:149, and again at :238 in check_prometheus_connection).

aiohttp's signature is timeout: ClientTimeout | _SENTINEL = sentinel, and it only falls back to the session default if timeout is sentinel. An explicit None is not the sentinel — it takes the else branch and becomes ClientTimeout(total=None), discarding aiohttp's own DEFAULT_TIMEOUT(total=300, sock_connect=30).

Since timeout defaults to None in the constructor, the out-of-the-box client runs with every timeout switched off. Repro against a server that accepts the connection and never replies:

async def blackhole(request):
await asyncio.sleep(3600)

async with AsyncPrometheusConnect(url=str(srv.make_url(""))) as p: # default timeout=None
await asyncio.wait_for(p.custom_query("up"), timeout=4)

default client: NO timeout fired in 4s -> hangs
timeout kwarg aiohttp received: None

A consequence worth noting: the asyncio.TimeoutError arm of the retry handler at :169 is unreachable under the default configuration.

In fairness this isn't a regression — PrometheusConnect hangs the same way, because requests also treats timeout=None as "no timeout". But aiohttp hands you a sane default for free and this actively throws it away. Simplest fix is to omit the kwarg entirely when there's no timeout configured:

kwargs = {}
if request_timeout is not None:
kwargs["timeout"] = aiohttp.ClientTimeout(total=request_timeout)
async with session.request(..., **kwargs) as response:
or set it once on the session in _get_session().

Related, same area: timeout=0 passes the constructor's timeout < 0 check and then also means "no timeout", because aiohttp's TimeoutHandle.start() only arms a timer if timeout is not None and timeout > 0. Either reject <= 0 or document that 0 disables timeouts.

2. aiohttp should be an optional extra, not a core dependency

requirements-core.txt is read verbatim into install_requires by setup.py:get_install_requires(), so this makes aiohttp mandatory for every user of the library, including sync-only ones.

That runs against the slim-install work in 0.7.0 — see the note in README.md:

Starting from version 0.7.0, pandas, numpy, and matplotlib are optional dependencies. If you only need PrometheusConnect without DataFrame support or plotting capabilities, you can install the minimal version which significantly reduces memory footprint and installation time, especially on Alpine-based Docker images.

Measured cost on a clean env: 7 new packages, ~1 MB of wheels (aiohttp, aiohappyeyeballs, aiosignal, attrs, frozenlist, multidict, propcache) — four of them C extensions that compile from source on musl/Alpine when no musllinux wheel matches.

We also have tests/test_lazy_imports.py, which asserts that importing PrometheusConnect doesn't pull in the heavy optional deps. That test encodes the principle this change breaks.

The good news is your lazy __getattr__ in __init__.py already does exactly the right thing — I verified:

aiohttp in sys.modules after sync-only use:  False
aiohttp in sys.modules after async access:   True

So the extra works cleanly. Could you:

  • add "async": ["aiohttp>=3.9,<4"] to extras_require in setup.py (and into "all"), and drop it from requirements-core.txt — keep it in requirements.txt so CI still installs it;
  • guard the import aiohttp with a friendly ImportError, same pattern as get_metric_aggregation uses for numpy;
  • extend tests/test_lazy_imports.py to cover aiohttp;
  • add a README install bullet next to [dataframe] / [analytics] / [plot].

3. Environment proxy and TLS configuration is silently ignored

aiohttp.ClientSession() defaults to trust_env=False; requests.Session() defaults to trust_env=True. So HTTPS_PROXY, NO_PROXY, REQUESTS_CA_BUNDLE and netrc all work today with PrometheusConnect and silently stop working on switching to AsyncPrometheusConnect — no error, the request just goes direct. In a locked-down network that's either a connection failure or egress on an unintended path. Please pass trust_env=True at :94.

Separately, _get_proxy() at :103 only probes <scheme>, <scheme>_proxy and all. requests also accepts scheme+host keys like {"https://prometheus.internal": "http://proxy:3128"}; with that dict _get_proxy() returns None and the proxy is bypassed silently. Either validate unknown keys or document the supported shapes.

4. pre-commit fails on the new module

prometheus_api_client/async_prometheus_connect.py:33 in public method `__init__`:
        D107: Missing docstring in __init__

PrometheusConnect.__init__ has one. GitHub Actions won't catch this (it only runs flake8 --select=E9,F63,F7,F82 plus pytest), but pre-commit run --all-files does, which the README asks contributors to run. One-line fix.

Should fix

5. Parameter precedence is inverted relative to the sync client

Sync builds params={**{"query": q, "start": start, "end": end, "step": step}, **params} (prometheus_connect.py:524) — the caller's params win. The async version reverses it at :187, :213 and :332, so the built-ins win.

That means custom_query_range(q, t0, t1, step="15", params={"step": "60"}) resolves to step=60 on the sync client and step=15 on the async one, silently, with no error. test_custom_query_does_not_allow_params_to_override_query locks the new behaviour in deliberately — and it's arguably the safer design — but the two clients shouldn't disagree. Either match sync, or reject conflicting keys explicitly so a port fails loudly instead of returning different numbers.

6. method="POST" doesn't actually put the query in the body

Verified against a local server with method="POST":

{'method': 'POST', 'qs': 'query=up####################', 'body': '', 'ctype': 'application/octet-stream'}

The query goes in the URL, the body is empty, and the Content-Type is application/octet-stream. POST support exists precisely so that long PromQL queries don't hit URL-length limits, so as written it buys nothing. test_post_method only asserts request.method == "POST", so it passes.

This reproduces the same bug in the sync client (prometheus_connect.py:473-482 also passes params= for POST), so I'm not asking you to fix mine — but since this module is new, let's get it right here: use data=params for POST on the query endpoints, keep params= for the GET-only ones (series, labels, label/*/values), and assert the body in the test.

7. _request guesses the response shape

isinstance(data, dict) and "result" in data at :155 auto-unwraps. /api/v1/metadata returns data as a dict keyed by metric name, so a Prometheus scraping a metric literally named result makes get_metric_metadata receive a list and die on .items(). Narrow, but the sync client never guesses — each method unwraps explicitly. Prefer passing the intent in, e.g. _request(..., unwrap="result").

8. No way to supply a client cert or a custom CA

PrometheusConnect takes session: Session = None and threads cert= / verify= through every call. AsyncPrometheusConnect builds its session internally at :94 and hardcodes ssl=not self.disable_ssl, so for mTLS or a private CA the only options are "no verification at all" or "guaranteed handshake failure". Reaching in to set prom._session doesn't work either, since _get_session() replaces it whenever it's closed. An ssl / ssl_context parameter passed through to session.request(ssl=...) would cover it; a session= injection point would also help testing.

9. store_locally=True does blocking filesystem I/O inside the coroutine

_store_metric_values_local at :506 is synchronous — os.makedirs plus open(...).write() — and isn't offloaded, so every chunk stalls the whole event loop for the duration of the write. On an NFS-mounted volume or with multi-MB payloads that blocks every other task in the process, which defeats the point of an async client. await asyncio.to_thread(...) around the write.

Also import json at :341 sits inside the while loop; bz2/math/os are imported at module top, and prometheus_connect.py imports json at module level.

10. get_metric_range_data fetches chunks strictly sequentially

The while start < end loop at :327 awaits each chunk in turn, so 24 hourly chunks cost 24 serial round-trips — identical to the sync client. These queries are independent; this is the one place where async genuinely wins. Compute the boundaries first, then asyncio.gather over them (semaphore-bounded if you want to cap concurrency) and extend data in boundary order.

11. The retry except clause is too broad

except (aiohttp.ClientError, asyncio.TimeoutError) at :169 catches the base class of InvalidURL, ClientConnectorCertificateError, TooManyRedirects and ContentTypeError. Two consequences with the defaults (retry=3, backoff=1.0):

  • a TLS certificate-verification failure — permanent — burns 4 connection attempts and sleeps 1+2+4 = 7s before raising;
  • a reverse proxy returning a 200 HTML error page makes await response.json() at :152 raise ContentTypeError inside the try, so it's retried 4x and then surfaces as ContentTypeError rather than PrometheusApiClientException — callers following our docstrings catch only the latter.

The sync client's urllib3.Retry(status_forcelist=RETRY_ON_STATUS) retries only connection errors and the listed statuses. Move response.json() out of the retry block and narrow the except to connection/timeout errors.

12. check_prometheus_connection bypasses _request

It re-implements the session fetch, timeout wrapping, auth, proxy and ssl plumbing at :222-240, apparently only because its URL is {url}/ rather than {url}/api/v1/.... The cost: it never retries (the sync client's HTTPAdapter(max_retries=retry) mount does retry it — and this is the call most likely to hit a just-starting endpoint), it skips _request's timeout validation, and any future fix to _request has to be applied twice. Worth generalizing _request to take a base-relative path.

13. auth and proxy are unvalidated

The constructor validates url, method, retry, retry_backoff_factor and timeout exhaustively, then leaves these two to fail on the first request. auth=("user", "pass", "extra") constructs fine and only explodes at aiohttp.BasicAuth(*self.auth); a requests.auth.HTTPBasicAuth object — valid for PrometheusConnect — passes the isinstance(auth, tuple) check, is returned as-is, and raises an opaque TypeError from inside aiohttp. Worth normalizing both in __init__.

Non-blocking

  • Duplication. Roughly 400 lines of transport-independent logic are copied from prometheus_connect.py: _store_metric_values_local / _metric_filename verbatim, the ~60-line numpy aggregation dispatch, and the label_config → selector builder (twice within this file alone). The retry policy is re-hardcoded as literals when MAX_REQUEST_RETRIES / RETRY_BACKOFF_FACTOR / RETRY_ON_STATUS already exist at prometheus_connect.py:20-24. The drift is already visible in this PR — items 5 and 7 above, plus get_metric_range_data(start_time=t, end_time=t) raising ValueError where sync returns []. Every future fix now has to land twice and eventually will land once. A follow-up PR lifting the pure helpers into a shared module would be very welcome; at minimum please import the constants.
  • No logging. The sync module emits _LOGGER.debug for start/end/chunk/query; this one is silent, which makes chunked range queries harder to debug.
  • get_label_values interpolates label_name into the URL path unescaped at :266 (urllib.parse.quote(label_name, safe="")). Same latent issue exists at prometheus_connect.py:225.
  • _request never checks payload["status"] == "success" or surfaces payload["warnings"].
  • get_series sends float timestamps while custom_query_range sends rounded ints — pick one.
  • timeout is only accepted per-call on custom_query / custom_query_range; everything else uses the constructor value only.
  • retry: int + retry_backoff_factor here vs a urllib3.Retry object on the sync client — passing a Retry raises ValueError. Fine to keep the simpler API, but worth a docstring note for people porting.
  • The new heading in docs/source/prometheus_api_client.rst doesn't escape underscores the way its neighbours do.

What I particularly liked

  • It fixes two real bugs that exist on the sync side. start_time/end_time default to None and resolve at call time, avoiding the mutable-default-at-import bug at prometheus_connect.py:299-300 (where datetime.now() is evaluated once, at import). And current_chunk = min(chunk_seconds, end - start) avoids permanently mutating chunk_seconds the way :360-361 does. I'd happily take both of those as a separate PR against the sync client.
  • Constructor validation is genuinely thorough — the bool-vs-int and NaN/inf checks are the kind of thing that usually gets skipped.
  • Lazy session creation, close(), and async with are all properly tested, including close-and-recreate.
  • The tests add no new test dependencies and need no network — a real aiohttp.test_utils.TestServer plus stdlib IsolatedAsyncioTestCase. That's exactly right for this repo, and a nice improvement on the existing suite's reliance on a live demo endpoint.
  • test_get_series_uses_get_with_post_configuration is a good test to have thought of.

Happy to help with any of the above if you'd like a hand — items 1, 3 and 4 are all a couple of lines each, and item 2 is mostly mechanical.

Used AI to review this PR :)

Thanks @4n4nd for the detailed review. I've pushed an update addressing the four blocking items:

  • Preserved aiohttp's default timeout when no explicit timeout is configured and rejected zero timeouts.
  • Made aiohttp an optional async extra and included it in all.
  • Enabled environment proxy support and added SSL context configuration.
  • Added the missing constructor docstring.

Extended the lazy-import tests to cover the optional aiohttp dependency. The async tests and lazy-import tests are passing.
Left the additional suggestions for follow-up improvements

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Async Version of PrometheusConnect

2 participants