"""Every 'no' a compartment says, counted by reason and kept with detail.
Split out of fleetmesh_node/compartment.py when it became a package; see that package's
docstring for why a refusal that is not recorded is indistinguishable from
silence.
"""
from __future__ import annotations
import collections
import threading
import time
from typing import Any, Callable, Counter, Deque, Mapping, NamedTuple, Optional, TypedDict
[docs]class Refusal(NamedTuple):
at: int
kind: str
subject: Optional[str]
why: str
detail: Mapping[str, Any]
[docs]class RefusalRecentSummary(TypedDict):
at: int
kind: str
subject: Optional[str]
why: str
detail: Mapping[str, Any]
[docs]class RefusalsStateReport(TypedDict):
total: int
by_reason: dict[str, int]
recent: list[RefusalRecentSummary]
[docs]class Refusals:
"""Every 'no' one compartment said, counted by reason and kept with detail.
Counted so a rate is visible; kept so the last few can be read. A reason is
a short stable string and never a formatted id, because a reason is a
category and the ids belong in the detail where they cannot explode the
key space.
"""
[docs] def __init__(self, name: Optional[str], keep: int = 200,
clock: Optional[Callable[[], int]] = None) -> None:
self.name: Optional[str] = name
self.keep: int = keep
# Stamps and windows read this clock when a caller gives no `at`/`now`.
# A compartment hands its own, so a refusal and the trouble() that
# reads it never disagree about what "now" is.
self.clock: Callable[[], int] = clock or (lambda: int(time.time()))
self._lock: threading.Lock = threading.Lock()
self.counts: Counter[str] = collections.Counter()
self.recent: Deque[Refusal] = collections.deque(maxlen=keep)
[docs] def refuse(
self,
kind: str,
why: str,
subject: Optional[str] = None,
detail: Optional[Mapping[str, Any]] = None,
at: Optional[int] = None,
) -> Refusal:
r = Refusal(int(at if at is not None else self.clock()), kind, subject, why, detail or {})
with self._lock:
self.counts['%s: %s' % (kind, why)] += 1
self.recent.append(r)
return r
[docs] def total(self) -> int:
return sum(self.counts.values())
[docs] def last(self, n: int = 5) -> list[Refusal]:
with self._lock:
return list(self.recent)[-n:]
[docs] def within(
self,
seconds: int,
now: Optional[int] = None,
kind: Optional[str] = None,
why: Optional[str] = None,
) -> list[Refusal]:
"""Refusals from the last `seconds`, which is what trouble means.
Trouble is what is wrong NOW. Reading the whole buffer reports a fault
that has been fixed until the buffer happens to roll, and an operator
who is shouted at about something already mended learns to stop reading
the shouting. The counts keep the history; this answers the present.
"""
cut = int(now if now is not None else self.clock()) - seconds
with self._lock:
rows = [r for r in self.recent if r.at >= cut]
if kind is not None:
rows = [r for r in rows if r.kind == kind]
if why is not None:
rows = [r for r in rows if r.why == why]
return rows
[docs] def state(self, n: int = 5) -> RefusalsStateReport:
return {
'total': self.total(),
'by_reason': dict(self.counts),
'recent': [
{
'at': r.at,
'kind': r.kind,
'subject': (r.subject or '')[:16] or None,
'why': r.why,
'detail': r.detail,
}
for r in self.last(n)
],
}
[docs]def why_detail(e: BaseException) -> dict[str, str]:
return {'error': '%s: %s' % (type(e).__name__, e)}