Cache ip address stringify in zeroconf (#92800)

stringify IPv6 addresses is expensive, and since zeroconf sees the same
ones over and over again an LRU can avoid the constant stringify
This commit is contained in:
J. Nick Koston 2023-05-14 11:07:38 -05:00 committed by GitHub
parent 637941df4d
commit e073f091b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -542,6 +542,12 @@ def async_get_homekit_discovery_domain(
return None return None
@lru_cache(maxsize=256) # matches to the cache in zeroconf itself
def _stringify_ip_address(ip_addr: IPv4Address | IPv6Address) -> str:
"""Stringify an IP address."""
return str(ip_addr)
def info_from_service(service: AsyncServiceInfo) -> ZeroconfServiceInfo | None: def info_from_service(service: AsyncServiceInfo) -> ZeroconfServiceInfo | None:
"""Return prepared info from mDNS entries.""" """Return prepared info from mDNS entries."""
properties: dict[str, Any] = {"_raw": {}} properties: dict[str, Any] = {"_raw": {}}
@ -569,7 +575,7 @@ def info_from_service(service: AsyncServiceInfo) -> ZeroconfServiceInfo | None:
host: str | None = None host: str | None = None
for ip_addr in ip_addresses: for ip_addr in ip_addresses:
if not ip_addr.is_link_local and not ip_addr.is_unspecified: if not ip_addr.is_link_local and not ip_addr.is_unspecified:
host = str(ip_addr) host = _stringify_ip_address(ip_addr)
break break
if not host: if not host:
return None return None
@ -577,7 +583,7 @@ def info_from_service(service: AsyncServiceInfo) -> ZeroconfServiceInfo | None:
assert service.server is not None, "server cannot be none if there are addresses" assert service.server is not None, "server cannot be none if there are addresses"
return ZeroconfServiceInfo( return ZeroconfServiceInfo(
host=host, host=host,
addresses=[str(ip_addr) for ip_addr in ip_addresses], addresses=[_stringify_ip_address(ip_addr) for ip_addr in ip_addresses],
port=service.port, port=service.port,
hostname=service.server, hostname=service.server,
type=service.type, type=service.type,