Skip to content

Commit

Permalink
feat: optimizing sending answers to questions (#1227)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco committed Aug 22, 2023
1 parent a0e754c commit cd7b56b
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/zeroconf/_handlers.py
Expand Up @@ -23,6 +23,7 @@
import itertools
import random
from collections import deque
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Dict,
Expand Down Expand Up @@ -71,6 +72,8 @@
_MULTICAST_DELAY_RANDOM_INTERVAL = (20, 120)
_RESPOND_IMMEDIATE_TYPES = {_TYPE_NSEC, _TYPE_SRV, *_ADDRESS_RECORD_TYPES}

NAME_GETTER = attrgetter('name')


class QuestionAnswers(NamedTuple):
ucast: _AnswerWithAdditionalsType
Expand Down Expand Up @@ -109,13 +112,13 @@ def construct_outgoing_unicast_answers(

def _add_answers_additionals(out: DNSOutgoing, answers: _AnswerWithAdditionalsType) -> None:
# Find additionals and suppress any additionals that are already in answers
sending: Set[DNSRecord] = set(answers.keys())
sending: Set[DNSRecord] = set(answers)
# Answers are sorted to group names together to increase the chance
# that similar names will end up in the same packet and can reduce the
# overall size of the outgoing response via name compression
for answer, additionals in sorted(answers.items(), key=lambda kv: kv[0].name):
for answer in sorted(answers, key=NAME_GETTER):
out.add_answer_at_time(answer, 0)
for additional in additionals:
for additional in answers[answer]:
if additional not in sending:
out.add_additional_answer(additional)
sending.add(additional)
Expand Down

0 comments on commit cd7b56b

Please sign in to comment.