blastdns 2.0.2__cp315-cp315-win32.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- blastdns/__init__.py +20 -0
- blastdns/_native.cp315-win32.pyd +0 -0
- blastdns/client.py +317 -0
- blastdns/exceptions.py +21 -0
- blastdns/models.py +134 -0
- blastdns/tests/test_batching.py +139 -0
- blastdns/tests/test_client.py +458 -0
- blastdns/tests/test_exceptions.py +77 -0
- blastdns/tests/test_mock_client.py +171 -0
- blastdns/tests/test_zone_transfer.py +102 -0
- blastdns/zone_transfer.py +28 -0
- blastdns-2.0.2.dist-info/METADATA +766 -0
- blastdns-2.0.2.dist-info/RECORD +16 -0
- blastdns-2.0.2.dist-info/WHEEL +4 -0
- blastdns-2.0.2.dist-info/licenses/LICENSE +662 -0
- blastdns-2.0.2.dist-info/sboms/blastdns.cyclonedx.json +6254 -0
blastdns/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from .client import Client, ClientConfig, MockClient, get_system_resolvers, init_logging
|
|
2
|
+
from .models import DNSError, DNSResult, DNSResultOrError
|
|
3
|
+
from .exceptions import BlastDNSError, ConfigurationError, NoResolversError, ResolverError
|
|
4
|
+
from .zone_transfer import zone_transfer
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"ClientConfig",
|
|
8
|
+
"Client",
|
|
9
|
+
"MockClient",
|
|
10
|
+
"DNSResult",
|
|
11
|
+
"DNSError",
|
|
12
|
+
"DNSResultOrError",
|
|
13
|
+
"get_system_resolvers",
|
|
14
|
+
"init_logging",
|
|
15
|
+
"BlastDNSError",
|
|
16
|
+
"ConfigurationError",
|
|
17
|
+
"NoResolversError",
|
|
18
|
+
"ResolverError",
|
|
19
|
+
"zone_transfer",
|
|
20
|
+
]
|
|
Binary file
|
blastdns/client.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
import orjson
|
|
4
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
5
|
+
|
|
6
|
+
from . import _native # type: ignore
|
|
7
|
+
from .models import DNSError, DNSResult, DNSResultOrError, ResolverStats
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"ClientConfig",
|
|
11
|
+
"Client",
|
|
12
|
+
"MockClient",
|
|
13
|
+
"get_system_resolvers",
|
|
14
|
+
"init_logging",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def init_logging(filter: Optional[str] = None) -> bool:
|
|
19
|
+
"""Send blastdns's internal logs to stderr.
|
|
20
|
+
|
|
21
|
+
Without this, nothing the engine logs is visible from Python: resolver
|
|
22
|
+
diagnostics, purgatory sentences, TCP refetches on truncation, and adaptive
|
|
23
|
+
rate changes are all discarded. Call it once, early.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
filter: A ``RUST_LOG``-style directive, e.g. ``"blastdns=debug"``.
|
|
27
|
+
Defaults to reading ``RUST_LOG`` from the environment.
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
bool: False if a log subscriber is already installed, in which case that
|
|
31
|
+
one stays in charge. Not an error.
|
|
32
|
+
|
|
33
|
+
Example:
|
|
34
|
+
blastdns.init_logging("blastdns=debug")
|
|
35
|
+
"""
|
|
36
|
+
return _native.init_logging(filter)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def get_system_resolvers() -> list[str]:
|
|
40
|
+
"""Get system DNS resolver IP addresses from OS configuration.
|
|
41
|
+
|
|
42
|
+
Works on Unix, Windows, macOS, and Android.
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
list[str]: List of system resolver IP addresses (e.g., ["8.8.8.8", "1.1.1.1"])
|
|
46
|
+
|
|
47
|
+
Example:
|
|
48
|
+
resolvers = get_system_resolvers()
|
|
49
|
+
for ip in resolvers:
|
|
50
|
+
print(f"System resolver: {ip}")
|
|
51
|
+
"""
|
|
52
|
+
return _native.get_system_resolvers_py()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ClientConfig(BaseModel):
|
|
56
|
+
"""Configuration for a :class:`Client`.
|
|
57
|
+
|
|
58
|
+
Throughput is governed by three independent limits: ``max_concurrency`` caps
|
|
59
|
+
total queries in flight, ``max_inflight_per_resolver`` caps how many any one
|
|
60
|
+
resolver receives at once (the politeness bound), and ``rate_limit`` caps the
|
|
61
|
+
dispatch rate outright. The tightest one binds.
|
|
62
|
+
|
|
63
|
+
With ``adaptive`` on (the default), pacing also backs off on its own: when a
|
|
64
|
+
resolver starts losing queries, its rate retreats below the rate at which that
|
|
65
|
+
began. ``rate_limit`` is an additional hard cap, not a replacement for it, so
|
|
66
|
+
adaptation happens whether or not one is set.
|
|
67
|
+
|
|
68
|
+
Unknown keys are rejected rather than ignored, so a stale or misspelled
|
|
69
|
+
option fails loudly instead of silently falling back to a default.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
model_config = ConfigDict(extra="forbid")
|
|
73
|
+
|
|
74
|
+
max_inflight_per_resolver: int = Field(default=2, ge=1)
|
|
75
|
+
max_concurrency: int = Field(default=256, ge=1)
|
|
76
|
+
rate_limit: Optional[float] = Field(default=None, gt=0)
|
|
77
|
+
adaptive: bool = Field(default=True)
|
|
78
|
+
resolver_probe: bool = Field(default=False)
|
|
79
|
+
persistent_socket: bool = Field(default=False)
|
|
80
|
+
request_timeout_ms: int = Field(default=1000, ge=1)
|
|
81
|
+
max_retries: int = Field(default=10, ge=0)
|
|
82
|
+
purgatory_threshold: int = Field(default=10, ge=0)
|
|
83
|
+
"""Consecutive failures before a resolver is benched. 0 disables benching, as
|
|
84
|
+
does a ``purgatory_sentence_ms`` of 0."""
|
|
85
|
+
purgatory_sentence_ms: int = Field(default=1000, ge=0)
|
|
86
|
+
cache_capacity: int = Field(default=10000, ge=0)
|
|
87
|
+
cache_min_ttl_secs: int = Field(default=10, ge=0)
|
|
88
|
+
cache_max_ttl_secs: int = Field(default=86400, ge=0)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class Client:
|
|
92
|
+
"""Async DNS client backed by the Rust BlastDNS engine.
|
|
93
|
+
|
|
94
|
+
This is a thin, ergonomic wrapper around the native Rust client. It accepts a
|
|
95
|
+
list of DNS resolvers and an optional `ClientConfig`, and exposes a single
|
|
96
|
+
async `resolve` method that returns JSON-shaped Python dictionaries matching
|
|
97
|
+
the CLI output shown in the README.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
def __init__(self, resolvers, config=None):
|
|
101
|
+
if _native is None:
|
|
102
|
+
raise RuntimeError(
|
|
103
|
+
"blastdns native module is unavailable. "
|
|
104
|
+
"Build it via `maturin develop --features python` "
|
|
105
|
+
"or `cargo build --features python` before using Client."
|
|
106
|
+
)
|
|
107
|
+
config_json = (config or ClientConfig()).model_dump_json()
|
|
108
|
+
self._inner = _native.Client(list(resolvers), config_json)
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def resolvers(self) -> list[str]:
|
|
112
|
+
"""Get the list of resolvers being used by this client.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
list[str]: List of resolver addresses (e.g., ["8.8.8.8:53", "1.1.1.1:53"])
|
|
116
|
+
|
|
117
|
+
Example:
|
|
118
|
+
client = Client(["8.8.8.8"])
|
|
119
|
+
print(client.resolvers) # ["8.8.8.8:53"]
|
|
120
|
+
"""
|
|
121
|
+
return self._inner.resolvers
|
|
122
|
+
|
|
123
|
+
def stats(self) -> list[ResolverStats]:
|
|
124
|
+
"""Cumulative per-resolver counters, one entry per configured resolver.
|
|
125
|
+
|
|
126
|
+
Every dispatched query lands in exactly one of ``answered``, ``empty``,
|
|
127
|
+
``timeout``, or ``error``, so diffing two snapshots accounts for a batch
|
|
128
|
+
in full and reveals queries that never came back.
|
|
129
|
+
|
|
130
|
+
Example:
|
|
131
|
+
before = {s.resolver: s for s in client.stats()}
|
|
132
|
+
async for host, rdtype, answers in client.resolve_batch(hosts, "A"):
|
|
133
|
+
...
|
|
134
|
+
after = client.stats()
|
|
135
|
+
"""
|
|
136
|
+
return [ResolverStats.model_validate(s) for s in orjson.loads(self._inner.stats())]
|
|
137
|
+
|
|
138
|
+
async def resolve(self, host, record_type=None) -> list[str]:
|
|
139
|
+
"""Resolve a hostname to DNS records, returning simplified rdata strings.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
host: Hostname to resolve (IP addresses are auto-formatted for PTR queries)
|
|
143
|
+
record_type: Record type string ("A", "AAAA", "MX", etc.). Defaults to "A"
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
list[str]: List of rdata strings (e.g., ["93.184.216.34"] for A records).
|
|
147
|
+
|
|
148
|
+
Example:
|
|
149
|
+
ips = await client.resolve("example.com", "A")
|
|
150
|
+
for ip in ips:
|
|
151
|
+
print(ip)
|
|
152
|
+
"""
|
|
153
|
+
return await self._inner.resolve(host, record_type)
|
|
154
|
+
|
|
155
|
+
async def resolve_full(self, host, record_type=None) -> DNSResult:
|
|
156
|
+
"""Resolve a hostname to DNS records, returning full DNS response.
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
host: Hostname to resolve (IP addresses are auto-formatted for PTR queries)
|
|
160
|
+
record_type: Record type string ("A", "AAAA", "MX", etc.). Defaults to "A"
|
|
161
|
+
|
|
162
|
+
Returns:
|
|
163
|
+
DNSResult: A Pydantic model containing the host and DNS response with
|
|
164
|
+
typed fields for header, queries, answers, etc.
|
|
165
|
+
|
|
166
|
+
Example:
|
|
167
|
+
result = await client.resolve_full("example.com", "A")
|
|
168
|
+
print(result.host)
|
|
169
|
+
for answer in result.response.answers:
|
|
170
|
+
print(answer.rdata)
|
|
171
|
+
"""
|
|
172
|
+
raw = await self._inner.resolve_full(host, record_type)
|
|
173
|
+
response_data = orjson.loads(raw)
|
|
174
|
+
return DNSResult.model_validate({"host": host, "response": response_data})
|
|
175
|
+
|
|
176
|
+
async def resolve_multi(self, host, record_types) -> dict[str, list[str]]:
|
|
177
|
+
"""Resolve multiple record types for a single hostname in parallel, returning simplified results.
|
|
178
|
+
|
|
179
|
+
Args:
|
|
180
|
+
host: Hostname to resolve
|
|
181
|
+
record_types: List of record type strings (e.g. ["A", "AAAA", "MX"])
|
|
182
|
+
|
|
183
|
+
Returns:
|
|
184
|
+
dict[str, list[str]]: Dictionary mapping record type to list of rdata strings.
|
|
185
|
+
Only successful queries with answers are included.
|
|
186
|
+
|
|
187
|
+
Example:
|
|
188
|
+
results = await client.resolve_multi("example.com", ["A", "AAAA", "MX"])
|
|
189
|
+
if "A" in results:
|
|
190
|
+
for ip in results["A"]:
|
|
191
|
+
print(ip)
|
|
192
|
+
"""
|
|
193
|
+
return await self._inner.resolve_multi(host, record_types)
|
|
194
|
+
|
|
195
|
+
async def resolve_multi_full(self, host, record_types) -> dict[str, DNSResultOrError]:
|
|
196
|
+
"""Resolve multiple record types for a single hostname in parallel, returning full results.
|
|
197
|
+
|
|
198
|
+
Args:
|
|
199
|
+
host: Hostname to resolve
|
|
200
|
+
record_types: List of record type strings (e.g. ["A", "AAAA", "MX"])
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
dict[str, DNSResultOrError]: Dictionary mapping record type to result.
|
|
204
|
+
Successful resolutions return DNSResult,
|
|
205
|
+
failures return DNSError.
|
|
206
|
+
|
|
207
|
+
Example:
|
|
208
|
+
results = await client.resolve_multi_full("example.com", ["A", "AAAA", "MX"])
|
|
209
|
+
a_result = results["A"]
|
|
210
|
+
if isinstance(a_result, DNSResult):
|
|
211
|
+
print(f"A records: {a_result.response.answers}")
|
|
212
|
+
else:
|
|
213
|
+
print(f"Error: {a_result.error}")
|
|
214
|
+
"""
|
|
215
|
+
raw_dict = await self._inner.resolve_multi_full(host, record_types)
|
|
216
|
+
result = {}
|
|
217
|
+
for key, value in raw_dict.items():
|
|
218
|
+
data = orjson.loads(value)
|
|
219
|
+
if "error" in data:
|
|
220
|
+
result[key] = DNSError.model_validate(data)
|
|
221
|
+
else:
|
|
222
|
+
result[key] = DNSResult.model_validate({"host": host, "response": data})
|
|
223
|
+
return result
|
|
224
|
+
|
|
225
|
+
async def resolve_batch(self, hosts, record_type=None):
|
|
226
|
+
"""Resolve multiple hostnames concurrently, yielding simplified tuples.
|
|
227
|
+
|
|
228
|
+
Args:
|
|
229
|
+
hosts: Iterable of hostname strings
|
|
230
|
+
record_type: Record type string ("A", "AAAA", "MX", etc.). Defaults to "A"
|
|
231
|
+
|
|
232
|
+
Yields:
|
|
233
|
+
tuple[str, str, list[str]]: (hostname, record_type, rdata) tuples.
|
|
234
|
+
Only successful, non-empty results are returned.
|
|
235
|
+
Results are unordered (faster hosts first).
|
|
236
|
+
|
|
237
|
+
Example:
|
|
238
|
+
async for host, rdtype, answers in client.resolve_batch(["example.com", "google.com"], "A"):
|
|
239
|
+
print(f"{host} ({rdtype}): {', '.join(answers)}")
|
|
240
|
+
"""
|
|
241
|
+
async for batch in self._inner.resolve_batch(hosts, record_type):
|
|
242
|
+
for host, rdtype, answers in batch:
|
|
243
|
+
yield (host, rdtype, answers)
|
|
244
|
+
|
|
245
|
+
async def resolve_batch_full(self, hosts, record_type=None, skip_empty=False, skip_errors=False):
|
|
246
|
+
"""Resolve multiple hostnames concurrently, yielding full results as they complete.
|
|
247
|
+
|
|
248
|
+
Args:
|
|
249
|
+
hosts: Iterable of hostname strings
|
|
250
|
+
record_type: Record type string ("A", "AAAA", "MX", etc.). Defaults to "A"
|
|
251
|
+
skip_empty: Skip empty responses (default: False)
|
|
252
|
+
skip_errors: Skip error responses (default: False)
|
|
253
|
+
|
|
254
|
+
Yields:
|
|
255
|
+
tuple[str, DNSResultOrError]: (hostname, result) pairs. Successful resolutions
|
|
256
|
+
return DNSResult, failures return DNSError.
|
|
257
|
+
Results are unordered (faster hosts first).
|
|
258
|
+
|
|
259
|
+
Example:
|
|
260
|
+
async for host, result in client.resolve_batch_full(["example.com", "google.com"], "A"):
|
|
261
|
+
if isinstance(result, DNSError):
|
|
262
|
+
print(f"{host} failed: {result.error}")
|
|
263
|
+
else:
|
|
264
|
+
print(f"{host}: {len(result.response.answers)} answers")
|
|
265
|
+
"""
|
|
266
|
+
async for batch in self._inner.resolve_batch_full(hosts, record_type, skip_empty, skip_errors):
|
|
267
|
+
for host, raw in batch:
|
|
268
|
+
data = orjson.loads(raw)
|
|
269
|
+
if "error" in data:
|
|
270
|
+
yield (host, DNSError.model_validate(data))
|
|
271
|
+
else:
|
|
272
|
+
yield (host, DNSResult.model_validate({"host": host, "response": data}))
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class MockClient(Client):
|
|
276
|
+
"""Mock DNS client for testing purposes.
|
|
277
|
+
|
|
278
|
+
This client inherits from Client but uses a mocked Rust backend that returns
|
|
279
|
+
fabricated responses based on pre-configured mock data. Use `mock_dns()` to
|
|
280
|
+
configure the responses.
|
|
281
|
+
"""
|
|
282
|
+
|
|
283
|
+
def __init__(self, resolvers=None, config=None):
|
|
284
|
+
"""Initialize mock client (resolvers and config are ignored)."""
|
|
285
|
+
if _native is None:
|
|
286
|
+
raise RuntimeError(
|
|
287
|
+
"blastdns native module is unavailable. "
|
|
288
|
+
"Build it via `maturin develop --features python` "
|
|
289
|
+
"or `cargo build --features python` before using MockClient."
|
|
290
|
+
)
|
|
291
|
+
# Skip parent __init__, directly set _inner to mock client
|
|
292
|
+
self._inner = _native.MockClient()
|
|
293
|
+
|
|
294
|
+
@property
|
|
295
|
+
def resolvers(self) -> list[str]:
|
|
296
|
+
"""Mock client has no real resolvers."""
|
|
297
|
+
return ["mock:53"]
|
|
298
|
+
|
|
299
|
+
def stats(self) -> list[ResolverStats]:
|
|
300
|
+
"""Mock client dispatches to no real resolvers, so there are no counters."""
|
|
301
|
+
return []
|
|
302
|
+
|
|
303
|
+
def mock_dns(self, data):
|
|
304
|
+
"""Configure mock DNS responses.
|
|
305
|
+
|
|
306
|
+
Args:
|
|
307
|
+
data: Dictionary mapping hosts to their DNS records, with optional
|
|
308
|
+
"_NXDOMAIN" key for hosts that should return NXDOMAIN.
|
|
309
|
+
|
|
310
|
+
Example:
|
|
311
|
+
mock_client.mock_dns({
|
|
312
|
+
"example.com": {"A": ["93.184.216.34"], "AAAA": ["2606:2800:220:1:248:1893:25c8:1946"]},
|
|
313
|
+
"bad.dns": {"CNAME": ["baddns.azurewebsites.net."]},
|
|
314
|
+
"_NXDOMAIN": ["notfound.example.com", "baddns.azurewebsites.net"]
|
|
315
|
+
})
|
|
316
|
+
"""
|
|
317
|
+
self._inner.mock_dns(data)
|
blastdns/exceptions.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""BlastDNS exception hierarchy.
|
|
2
|
+
|
|
3
|
+
All DNS-related errors raised by blastdns are subclasses of BlastDNSError,
|
|
4
|
+
so consumers can catch broadly or narrowly as needed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class BlastDNSError(Exception):
|
|
9
|
+
"""Base exception for all blastdns errors."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ConfigurationError(BlastDNSError):
|
|
13
|
+
"""Invalid configuration (bad resolver address, invalid hostname, etc.)."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class NoResolversError(ConfigurationError):
|
|
17
|
+
"""No DNS resolvers were provided or detected."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ResolverError(BlastDNSError):
|
|
21
|
+
"""A resolver failed to process a query (timeout, connection failure, etc.)."""
|
blastdns/models.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
from typing import Any, Dict, List, Literal, Optional, Tuple, Union
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel, Field
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Header(BaseModel):
|
|
7
|
+
"""DNS message header."""
|
|
8
|
+
|
|
9
|
+
id: int
|
|
10
|
+
message_type: Literal["Query", "Response"]
|
|
11
|
+
op_code: str
|
|
12
|
+
authoritative: bool
|
|
13
|
+
truncation: bool
|
|
14
|
+
recursion_desired: bool
|
|
15
|
+
recursion_available: bool
|
|
16
|
+
authentic_data: bool
|
|
17
|
+
checking_disabled: bool
|
|
18
|
+
response_code: str
|
|
19
|
+
query_count: int
|
|
20
|
+
answer_count: int
|
|
21
|
+
name_server_count: int
|
|
22
|
+
additional_count: int
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class EdnsFlags(BaseModel):
|
|
26
|
+
"""EDNS flags."""
|
|
27
|
+
|
|
28
|
+
dnssec_ok: bool
|
|
29
|
+
z: int
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class EdnsOptions(BaseModel):
|
|
33
|
+
"""EDNS options container."""
|
|
34
|
+
|
|
35
|
+
options: List[Any] = Field(default_factory=list)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Edns(BaseModel):
|
|
39
|
+
"""EDNS (Extension mechanisms for DNS) metadata."""
|
|
40
|
+
|
|
41
|
+
version: int
|
|
42
|
+
rcode_high: int
|
|
43
|
+
max_payload: int
|
|
44
|
+
flags: EdnsFlags
|
|
45
|
+
options: EdnsOptions
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Query(BaseModel):
|
|
49
|
+
"""DNS query record."""
|
|
50
|
+
|
|
51
|
+
name: str
|
|
52
|
+
query_type: str
|
|
53
|
+
query_class: str
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Record(BaseModel):
|
|
57
|
+
"""DNS resource record (answer, name server, or additional).
|
|
58
|
+
|
|
59
|
+
``text`` and ``targets`` are computed on the Rust side from the underlying
|
|
60
|
+
hickory ``RData`` so callers don't have to re-derive presentation format
|
|
61
|
+
or pull host names out of nested rdata dicts in Python.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
name_labels: str
|
|
65
|
+
ttl: int
|
|
66
|
+
dns_class: str
|
|
67
|
+
rdata: Dict[str, Any]
|
|
68
|
+
text: str = ""
|
|
69
|
+
targets: List[Tuple[str, str]] = Field(default_factory=list)
|
|
70
|
+
|
|
71
|
+
def to_text(self) -> str:
|
|
72
|
+
"""Presentation (zone-file) format of the rdata. Equivalent to
|
|
73
|
+
dnspython's ``answer.to_text()``."""
|
|
74
|
+
return self.text
|
|
75
|
+
|
|
76
|
+
def extract_targets(self) -> List[Tuple[str, str]]:
|
|
77
|
+
"""Hostnames embedded in the rdata that BBOT-style consumers want to
|
|
78
|
+
follow (A literal IPs, CNAME chain target, MX exchange, etc).
|
|
79
|
+
|
|
80
|
+
TXT records return ``[]`` -- pulling hostnames out of free-form TXT
|
|
81
|
+
content (SPF/DKIM/etc) is consumer-specific and is up to the caller.
|
|
82
|
+
"""
|
|
83
|
+
return list(self.targets)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class Response(BaseModel):
|
|
87
|
+
"""DNS response message."""
|
|
88
|
+
|
|
89
|
+
header: Header
|
|
90
|
+
queries: List[Query]
|
|
91
|
+
answers: List[Record]
|
|
92
|
+
name_servers: List[Record]
|
|
93
|
+
additionals: List[Record]
|
|
94
|
+
signature: List[Any] = Field(default_factory=list)
|
|
95
|
+
edns: Optional[Edns] = None
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class DNSResult(BaseModel):
|
|
99
|
+
"""Complete DNS resolution result with host and response."""
|
|
100
|
+
|
|
101
|
+
host: str
|
|
102
|
+
response: Response
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class DNSError(BaseModel):
|
|
106
|
+
"""DNS resolution error."""
|
|
107
|
+
|
|
108
|
+
error: str
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class ResolverStats(BaseModel):
|
|
112
|
+
"""Cumulative counters for a single resolver.
|
|
113
|
+
|
|
114
|
+
``attempted`` equals ``answered + empty + timeout + error``, so a caller can
|
|
115
|
+
account for every dispatched query. Diff two snapshots to measure one batch.
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
resolver: str
|
|
119
|
+
attempted: int
|
|
120
|
+
answered: int
|
|
121
|
+
empty: int
|
|
122
|
+
timeout: int
|
|
123
|
+
error: int
|
|
124
|
+
rtt_mean_us: int
|
|
125
|
+
rtt_min_us: int
|
|
126
|
+
purgatory_entries: int
|
|
127
|
+
truncated: int = 0
|
|
128
|
+
rate_qps: Optional[float] = None
|
|
129
|
+
"""Current pacing rate, or ``None`` when unthrottled. A value here means the
|
|
130
|
+
adaptive controller is holding this resolver below the rate at which it began
|
|
131
|
+
losing queries."""
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
DNSResultOrError = Union[DNSResult, DNSError]
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Tests for batching functionality in resolve_batch and resolve_batch_full."""
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from blastdns import MockClient
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@pytest.mark.asyncio
|
|
9
|
+
async def test_batch_timeout_triggers():
|
|
10
|
+
"""Test that 200ms timeout triggers batch send with slow iterator."""
|
|
11
|
+
client = MockClient()
|
|
12
|
+
|
|
13
|
+
# Mock hosts
|
|
14
|
+
mock_data = {}
|
|
15
|
+
for i in range(60):
|
|
16
|
+
mock_data[f"host{i}.example.com"] = {"A": [f"192.0.2.{i % 255}"]}
|
|
17
|
+
|
|
18
|
+
client.mock_dns(mock_data)
|
|
19
|
+
|
|
20
|
+
# Generator: 20 fast, delay 250ms, 20 fast, delay 250ms, 20 fast
|
|
21
|
+
# Expected batches:
|
|
22
|
+
# Batch 1: 21 items (first 20 + 1 after delay, then timeout)
|
|
23
|
+
# Batch 2: 20 items (next 19 + 1 after delay, then timeout)
|
|
24
|
+
# Batch 3: 19 items (remaining items, stream end)
|
|
25
|
+
def slow_hosts():
|
|
26
|
+
import time
|
|
27
|
+
|
|
28
|
+
for i in range(60):
|
|
29
|
+
yield f"host{i}.example.com"
|
|
30
|
+
if i == 19 or i == 39:
|
|
31
|
+
time.sleep(0.25)
|
|
32
|
+
|
|
33
|
+
batch_sizes = []
|
|
34
|
+
total_results = 0
|
|
35
|
+
|
|
36
|
+
async for batch in client._inner.resolve_batch(slow_hosts(), "A"):
|
|
37
|
+
batch_sizes.append(len(batch))
|
|
38
|
+
total_results += len(batch)
|
|
39
|
+
|
|
40
|
+
assert total_results == 60, f"Expected 60 total results, got {total_results}"
|
|
41
|
+
assert len(batch_sizes) == 3, f"Expected 3 batches, got {len(batch_sizes)}: {batch_sizes}"
|
|
42
|
+
assert batch_sizes[0] == 21, f"Batch 1 should have 21 items, got {batch_sizes[0]}"
|
|
43
|
+
assert batch_sizes[1] == 20, f"Batch 2 should have 20 items, got {batch_sizes[1]}"
|
|
44
|
+
assert batch_sizes[2] == 19, f"Batch 3 should have 19 items, got {batch_sizes[2]}"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@pytest.mark.asyncio
|
|
48
|
+
async def test_batch_size_1000():
|
|
49
|
+
"""Test that batches are sent at 1000 items."""
|
|
50
|
+
client = MockClient()
|
|
51
|
+
|
|
52
|
+
# Mock 2500 hosts - should create 3 batches: 1000, 1000, 500
|
|
53
|
+
mock_data = {}
|
|
54
|
+
for i in range(2500):
|
|
55
|
+
mock_data[f"host{i}.example.com"] = {"A": [f"192.0.2.{i % 255}"]}
|
|
56
|
+
|
|
57
|
+
client.mock_dns(mock_data)
|
|
58
|
+
hosts = [f"host{i}.example.com" for i in range(2500)]
|
|
59
|
+
|
|
60
|
+
# Call _inner directly to count batches
|
|
61
|
+
batch_count = 0
|
|
62
|
+
total_results = 0
|
|
63
|
+
batch_sizes = []
|
|
64
|
+
|
|
65
|
+
async for batch in client._inner.resolve_batch(hosts, "A"):
|
|
66
|
+
batch_count += 1
|
|
67
|
+
batch_size = len(batch)
|
|
68
|
+
batch_sizes.append(batch_size)
|
|
69
|
+
total_results += batch_size
|
|
70
|
+
|
|
71
|
+
assert batch_count == 3, f"Expected 3 batches, got {batch_count}"
|
|
72
|
+
assert total_results == 2500, f"Expected 2500 total results, got {total_results}"
|
|
73
|
+
assert batch_sizes[0] == 1000, f"First batch should be 1000, got {batch_sizes[0]}"
|
|
74
|
+
assert batch_sizes[1] == 1000, f"Second batch should be 1000, got {batch_sizes[1]}"
|
|
75
|
+
assert batch_sizes[2] == 500, f"Third batch should be 500, got {batch_sizes[2]}"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@pytest.mark.asyncio
|
|
79
|
+
async def test_batch_full_with_size_limit():
|
|
80
|
+
"""Test resolve_batch_full respects batch size limit."""
|
|
81
|
+
client = MockClient()
|
|
82
|
+
|
|
83
|
+
# Mock 2200 hosts - should create 3 batches: 1000, 1000, 200
|
|
84
|
+
mock_data = {}
|
|
85
|
+
for i in range(2200):
|
|
86
|
+
mock_data[f"host{i}.example.com"] = {"A": [f"192.0.2.{i % 255}"]}
|
|
87
|
+
|
|
88
|
+
client.mock_dns(mock_data)
|
|
89
|
+
hosts = [f"host{i}.example.com" for i in range(2200)]
|
|
90
|
+
|
|
91
|
+
batch_count = 0
|
|
92
|
+
total_results = 0
|
|
93
|
+
batch_sizes = []
|
|
94
|
+
|
|
95
|
+
async for batch in client._inner.resolve_batch_full(hosts, "A", False, False):
|
|
96
|
+
batch_count += 1
|
|
97
|
+
batch_size = len(batch)
|
|
98
|
+
batch_sizes.append(batch_size)
|
|
99
|
+
total_results += batch_size
|
|
100
|
+
|
|
101
|
+
assert batch_count == 3, f"Expected 3 batches, got {batch_count}"
|
|
102
|
+
assert total_results == 2200, f"Expected 2200 total results, got {total_results}"
|
|
103
|
+
assert batch_sizes[0] == 1000, f"First batch should be 1000, got {batch_sizes[0]}"
|
|
104
|
+
assert batch_sizes[1] == 1000, f"Second batch should be 1000, got {batch_sizes[1]}"
|
|
105
|
+
assert batch_sizes[2] == 200, f"Third batch should be 200, got {batch_sizes[2]}"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@pytest.mark.asyncio
|
|
109
|
+
async def test_empty_stream():
|
|
110
|
+
"""Test that empty stream returns StopAsyncIteration."""
|
|
111
|
+
client = MockClient()
|
|
112
|
+
client.mock_dns({}) # No hosts
|
|
113
|
+
|
|
114
|
+
batch_count = 0
|
|
115
|
+
async for batch in client._inner.resolve_batch([], "A"):
|
|
116
|
+
batch_count += 1
|
|
117
|
+
|
|
118
|
+
assert batch_count == 0, f"Expected 0 batches, got {batch_count}"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@pytest.mark.asyncio
|
|
122
|
+
async def test_python_wrapper_unwraps_batches():
|
|
123
|
+
"""Test that the Python wrapper properly unwraps batches."""
|
|
124
|
+
client = MockClient()
|
|
125
|
+
|
|
126
|
+
# Mock 2500 hosts
|
|
127
|
+
mock_data = {}
|
|
128
|
+
for i in range(2500):
|
|
129
|
+
mock_data[f"host{i}.example.com"] = {"A": [f"192.0.2.{i % 255}"]}
|
|
130
|
+
|
|
131
|
+
client.mock_dns(mock_data)
|
|
132
|
+
hosts = [f"host{i}.example.com" for i in range(2500)]
|
|
133
|
+
|
|
134
|
+
# Use the high-level API that should unwrap batches
|
|
135
|
+
results = []
|
|
136
|
+
async for host, record_type, answers in client.resolve_batch(hosts, "A"):
|
|
137
|
+
results.append((host, record_type, answers))
|
|
138
|
+
|
|
139
|
+
assert len(results) == 2500, f"Expected 2500 results, got {len(results)}"
|