feat: speed up question and answer history with a cython pxd (#1234) · python-zeroconf/python-zeroconf@703ecb2
@@ -20,24 +20,29 @@
2020 USA
2121"""
222223-from typing import Dict, Set, Tuple
23+from typing import Dict, List, Set, Tuple
24242525from ._dns import DNSQuestion, DNSRecord
2626from .const import _DUPLICATE_QUESTION_INTERVAL
27272828# The QuestionHistory is used to implement Duplicate Question Suppression
2929# https://datatracker.ietf.org/doc/html/rfc6762#section-7.3
303031+_float = float
32+31333234class QuestionHistory:
35+"""Remember questions and known answers."""
36+3337def __init__(self) -> None:
38+"""Init a new QuestionHistory."""
3439self._history: Dict[DNSQuestion, Tuple[float, Set[DNSRecord]]] = {}
354036-def add_question_at_time(self, question: DNSQuestion, now: float, known_answers: Set[DNSRecord]) -> None:
41+def add_question_at_time(self, question: DNSQuestion, now: _float, known_answers: Set[DNSRecord]) -> None:
3742"""Remember a question with known answers."""
3843self._history[question] = (now, known_answers)
394440-def suppresses(self, question: DNSQuestion, now: float, known_answers: Set[DNSRecord]) -> bool:
45+def suppresses(self, question: DNSQuestion, now: _float, known_answers: Set[DNSRecord]) -> bool:
4146"""Check to see if a question should be suppressed.
42474348 https://datatracker.ietf.org/doc/html/rfc6762#section-7.3
@@ -59,12 +64,16 @@ def suppresses(self, question: DNSQuestion, now: float, known_answers: Set[DNSRe
5964return False
6065return True
616662-def async_expire(self, now: float) -> None:
67+def async_expire(self, now: _float) -> None:
6368"""Expire the history of old questions."""
64-removes = [
65- question
66-for question, now_known_answers in self._history.items()
67-if now - now_known_answers[0] > _DUPLICATE_QUESTION_INTERVAL
68-]
69+removes: List[DNSQuestion] = []
70+for question, now_known_answers in self._history.items():
71+than, _ = now_known_answers
72+if now - than > _DUPLICATE_QUESTION_INTERVAL:
73+ removes.append(question)
6974for question in removes:
7075del self._history[question]
76+77+def clear(self) -> None:
78+"""Clear the history."""
79+self._history.clear()