Coverage for app / tools / web / health.py: 94%

53 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""How each search provider has been doing in this process, for an operator. 

2 

3A provider that runs out of credit or is rate-limited fails every search 

4until someone acts, and nothing a person reads in a chat names the engine 

5(``search.format_response``). So the service records each attempt here and 

6``/health`` serves it: when each provider last answered, last answered with 

7nothing, last failed and why, and how many times in a row it has failed. 

8Never a query, a result or a key. 

9 

10Per process: a restart forgets it, and each replica has its own. 

11""" 

12 

13from __future__ import annotations 

14 

15import threading 

16from dataclasses import dataclass 

17from datetime import datetime, timezone 

18from typing import Any 

19 

20from app.common.settings import Settings 

21from app.tools.web.models import ( 

22 AttemptOutcome, 

23 FailureReason, 

24 ProviderAttempt, 

25 ProviderName, 

26) 

27from app.util.time import utc_isoformat 

28 

29 

30@dataclass 

31class _ProviderState: 

32 last_answer_at: datetime | None = None 

33 last_empty_at: datetime | None = None 

34 last_failure_at: datetime | None = None 

35 last_failure_reason: FailureReason | None = None 

36 failures_in_a_row: int = 0 

37 

38 def as_dict(self) -> dict[str, Any]: 

39 return { 

40 "last_answer_at": _iso(self.last_answer_at), 

41 "last_empty_at": _iso(self.last_empty_at), 

42 "last_failure": ( 

43 { 

44 "reason": self.last_failure_reason.value, 

45 "at": _iso(self.last_failure_at), 

46 } 

47 if self.last_failure_reason is not None 

48 else None 

49 ), 

50 "failures_in_a_row": self.failures_in_a_row, 

51 } 

52 

53 

54def _iso(moment: datetime | None) -> str | None: 

55 return utc_isoformat(moment) if moment is not None else None 

56 

57 

58class ProviderHealth: 

59 """The record, safe to update from the threads ddgs runs in.""" 

60 

61 def __init__(self) -> None: 

62 self._lock = threading.Lock() 

63 self._states: dict[ProviderName, _ProviderState] = {} 

64 

65 def record(self, attempt: ProviderAttempt, *, at: datetime | None = None) -> None: 

66 if attempt.outcome is AttemptOutcome.SKIPPED: 

67 return 

68 now = at or datetime.now(timezone.utc).replace(tzinfo=None) 

69 with self._lock: 

70 state = self._states.setdefault(attempt.provider, _ProviderState()) 

71 if attempt.outcome is AttemptOutcome.FAILED: 

72 state.last_failure_at = now 

73 state.last_failure_reason = attempt.reason or FailureReason.ERROR 

74 state.failures_in_a_row += 1 

75 return 

76 # An answer, even an empty one, is the provider working. 

77 state.failures_in_a_row = 0 

78 if attempt.outcome is AttemptOutcome.ANSWERED: 

79 state.last_answer_at = now 

80 else: 

81 state.last_empty_at = now 

82 

83 def snapshot(self) -> dict[str, Any]: 

84 with self._lock: 

85 return { 

86 provider.value: state.as_dict() 

87 for provider, state in sorted( 

88 self._states.items(), key=lambda item: item[0].value 

89 ) 

90 } 

91 

92 def clear(self) -> None: 

93 with self._lock: 

94 self._states.clear() 

95 

96 

97HEALTH = ProviderHealth() 

98 

99 

100def status(settings: Settings) -> dict[str, Any]: 

101 """What ``/health`` serves: the providers a search asks, in order, 

102 whether a Brave key is set (never the key), and each provider's record.""" 

103 from app.tools.web.providers import ProviderConfigError, build_provider_chain 

104 

105 try: 

106 chain = [provider.name.value for provider in build_provider_chain(settings)] 

107 configured = True 

108 except ProviderConfigError: 

109 chain, configured = [], False 

110 return { 

111 "configured": configured, 

112 "chain": chain, 

113 "brave_key": bool(settings.brave_search_api_key), 

114 "providers": HEALTH.snapshot(), 

115 }