diff --git a/pyproject.toml b/pyproject.toml index e984709..79415fa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ requires = [ [tool.poetry] name = "machine_access_control" -version = "0.15.0" +version = "0.15.1" description = "Decatur Makers Machine Access Control package" license = "MIT" authors = [ "Jason Antman " ] diff --git a/src/dm_mac/neongetter.py b/src/dm_mac/neongetter.py index 570ccac..15bce99 100644 --- a/src/dm_mac/neongetter.py +++ b/src/dm_mac/neongetter.py @@ -5,6 +5,7 @@ import logging import os import sys +import time from datetime import datetime from datetime import timedelta from typing import Any @@ -173,6 +174,10 @@ class NeonUserUpdater: BASE_URL: str = "https://api.neoncrm.com/v2/" MAX_PAGE_SIZE: int = 200 + #: Total attempts for the account search POST (transient failures only). + SEARCH_ATTEMPTS: int = 3 + #: Seconds to sleep before retry N (1-based) is ``N * SEARCH_BACKOFF_SEC``. + SEARCH_BACKOFF_SEC: int = 10 def __init__(self, dump_fields: bool = False): """Initialize NeonUserUpdater.""" @@ -310,6 +315,44 @@ def fields_to_get(self) -> List[Union[str, int, List[str]]]: logger.info("Fields to get from Neon API: %s", field_names) return field_names + def _post_search(self, url: str, data: Dict[str, Any]) -> requests.Response: + """ + POST the (read-only, so idempotent) account search, with retries. + + Connection errors, timeouts and HTTP 429/5xx are retried, up to + ``SEARCH_ATTEMPTS`` total attempts with linear backoff. Other 4xx + responses are returned immediately. After the final attempt, the last + exception is raised, or the last response returned (so the caller's + ``raise_for_status()`` fails as it always has). + """ + for attempt in range(1, self.SEARCH_ATTEMPTS + 1): + last: bool = attempt == self.SEARCH_ATTEMPTS + try: + r: requests.Response = self._sess.post( + url, timeout=self._timeout, json=data + ) + except (requests.ConnectionError, requests.Timeout) as ex: + if last: + raise + reason: str = f"{type(ex).__name__}: {ex}" + else: + if r.status_code != 429 and r.status_code < 500: + return r + if last: + return r + reason = f"HTTP {r.status_code}" + delay: int = attempt * self.SEARCH_BACKOFF_SEC + logger.warning( + "Neon account search attempt %d of %d failed (%s); " + "retrying in %d seconds", + attempt, + self.SEARCH_ATTEMPTS, + reason, + delay, + ) + time.sleep(delay) + raise AssertionError("unreachable") # pragma: no cover + def _get_users_page( self, page: int, fields: List[Union[str, int, List[str]]], cutoff: str ) -> Tuple[int, List[Dict[str, Any]]]: @@ -337,7 +380,7 @@ def _get_users_page( logger.debug( "POST %s with data: %s", url, json.dumps(data, sort_keys=True, indent=4) ) - r: requests.Response = self._sess.post(url, timeout=self._timeout, json=data) + r: requests.Response = self._post_search(url, data) try: r.raise_for_status() except Exception: diff --git a/tests/test_neongetter.py b/tests/test_neongetter.py index bd06072..0424e60 100644 --- a/tests/test_neongetter.py +++ b/tests/test_neongetter.py @@ -5,6 +5,7 @@ from base64 import b64encode from pathlib import Path from typing import Any +from typing import Dict from typing import List from typing import Tuple from typing import cast @@ -13,6 +14,7 @@ from unittest.mock import patch import pytest +import requests import responses from _pytest.capture import CaptureFixture from jsonschema.exceptions import ValidationError @@ -543,3 +545,87 @@ def test_dump_example_config( captured.out == json.dumps({"my": "config"}, sort_keys=True, indent=4) + "\n" ) + + +SEARCH_URL: str = "https://api.neoncrm.com/v2/accounts/search" +SEARCH_OK: Dict[str, Any] = { + "pagination": {"totalPages": 3}, + "searchResults": [{"Account ID": "1"}], +} + + +class TestSearchRetry: + """Test retry behavior of the account search POST.""" + + @pytest.fixture + def nuu(self) -> NeonUserUpdater: + """Return an updater with config loading stubbed out.""" + with patch(f"{pb}._load_and_validate_config", autospec=True): + with patch(f"{pbm}.env_var_or_die", return_value="x"): + return NeonUserUpdater() + + @responses.activate(registry=OrderedRegistry) + def test_retry_then_succeed( + self, nuu: NeonUserUpdater, caplog: pytest.LogCaptureFixture + ) -> None: + """A read timeout and an HTTP 500 are retried; then success.""" + responses.add( + responses.POST, SEARCH_URL, body=requests.exceptions.ReadTimeout("slow") + ) + responses.add(responses.POST, SEARCH_URL, status=500) + responses.add(responses.POST, SEARCH_URL, json=SEARCH_OK) + with patch(f"{pbm}.time.sleep") as m_sleep: + last, results = nuu._get_users_page(0, ["a"], "2026-01-01") + assert last == 2 + assert results == [{"Account ID": "1"}] + assert len(responses.calls) == 3 + assert m_sleep.mock_calls == [call(10), call(20)] + warnings = [r for r in caplog.records if r.levelname == "WARNING"] + assert len(warnings) == 2 + assert "attempt 1 of 3" in warnings[0].getMessage() + assert "ReadTimeout" in warnings[0].getMessage() + assert "HTTP 500" in warnings[1].getMessage() + + @responses.activate(registry=OrderedRegistry) + def test_retry_429(self, nuu: NeonUserUpdater) -> None: + """HTTP 429 is retried.""" + responses.add(responses.POST, SEARCH_URL, status=429) + responses.add(responses.POST, SEARCH_URL, json=SEARCH_OK) + with patch(f"{pbm}.time.sleep"): + nuu._get_users_page(0, ["a"], "2026-01-01") + assert len(responses.calls) == 2 + + @responses.activate(registry=OrderedRegistry) + def test_exhausted_timeout_raises(self, nuu: NeonUserUpdater) -> None: + """Persistent timeouts raise after all attempts.""" + for _ in range(3): + responses.add( + responses.POST, + SEARCH_URL, + body=requests.exceptions.ReadTimeout("slow"), + ) + with patch(f"{pbm}.time.sleep") as m_sleep: + with pytest.raises(requests.exceptions.ReadTimeout): + nuu._get_users_page(0, ["a"], "2026-01-01") + assert len(responses.calls) == 3 + assert m_sleep.call_count == 2 + + @responses.activate(registry=OrderedRegistry) + def test_exhausted_500_raises(self, nuu: NeonUserUpdater) -> None: + """Persistent HTTP 500 raises HTTPError after all attempts.""" + for _ in range(3): + responses.add(responses.POST, SEARCH_URL, status=500) + with patch(f"{pbm}.time.sleep"): + with pytest.raises(HTTPError): + nuu._get_users_page(0, ["a"], "2026-01-01") + assert len(responses.calls) == 3 + + @responses.activate(registry=OrderedRegistry) + def test_4xx_not_retried(self, nuu: NeonUserUpdater) -> None: + """A 403 is not retried.""" + responses.add(responses.POST, SEARCH_URL, status=403) + with patch(f"{pbm}.time.sleep") as m_sleep: + with pytest.raises(HTTPError): + nuu._get_users_page(0, ["a"], "2026-01-01") + assert len(responses.calls) == 1 + assert m_sleep.mock_calls == []