dnskit 0.1.0__py3-none-any.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.
dnskit/core/batch.py ADDED
@@ -0,0 +1,211 @@
1
+ """Run `lookup`, `doctor` or `email` on every domain in a list, a few at a time.
2
+
3
+ `read_domains` turns a text file into `BatchLine`s (one domain per line; blank lines and
4
+ `#` comments skipped; a URL counts as its domain), `run_batch` checks each valid one and
5
+ returns a `BatchReport` whose items each say OK or not, with a one-line summary.
6
+ """
7
+
8
+ import time
9
+ from collections.abc import Callable, Sequence
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from dataclasses import dataclass
12
+ from enum import StrEnum
13
+ from typing import Any
14
+
15
+ from dnskit.core.diagnosis import explain
16
+ from dnskit.core.doctor import DOCTOR_TIMEOUT_S, DoctorReport, doctor
17
+ from dnskit.core.local import LocalReport, local_check
18
+ from dnskit.core.lookup import DEFAULT_RTYPES, LookupReport, LookupStatus, lookup
19
+ from dnskit.core.mail import CheckStatus, EmailReport, email_check
20
+ from dnskit.core.reach import parse_target
21
+
22
+ DEFAULT_PARALLEL = 4
23
+ MAX_PARALLEL = 16
24
+
25
+
26
+ class BatchCheck(StrEnum):
27
+ LOOKUP = "lookup"
28
+ DOCTOR = "doctor"
29
+ EMAIL = "email"
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class BatchLine:
34
+ line: int # 1-based, in the file
35
+ text: str # as written, without the comment
36
+ name: str | None # the domain, or None when the line isn't one
37
+ error: str | None = None # why it isn't
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class BatchItem:
42
+ line: int
43
+ name: str
44
+ ok: bool
45
+ summary: str # one line: what was found
46
+ elapsed_ms: float
47
+ report: LookupReport | DoctorReport | EmailReport | None = None
48
+ error: str | None = None # the check itself failed (crashed); report is None
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class BatchReport:
53
+ check: BatchCheck
54
+ items: tuple[BatchItem, ...] # in file order
55
+ invalid: tuple[BatchLine, ...] # lines that aren't domains
56
+ duplicates: tuple[BatchLine, ...] # domains listed again (checked once)
57
+ elapsed_ms: float
58
+ local: LocalReport | None = None # doctor: this computer, checked once for all domains
59
+
60
+ @property
61
+ def passed(self) -> tuple[BatchItem, ...]:
62
+ return tuple(i for i in self.items if i.ok)
63
+
64
+ @property
65
+ def failed(self) -> tuple[BatchItem, ...]:
66
+ return tuple(i for i in self.items if not i.ok)
67
+
68
+ @property
69
+ def all_ok(self) -> bool:
70
+ return not self.failed and not self.invalid
71
+
72
+
73
+ def read_domains(text: str) -> list[BatchLine]:
74
+ """One `BatchLine` per non-blank, non-comment line. Invalid domains get an `error`."""
75
+ lines = []
76
+ for number, raw in enumerate(text.splitlines(), start=1):
77
+ content = raw.split("#", 1)[0].strip()
78
+ if not content:
79
+ continue
80
+ try:
81
+ lines.append(BatchLine(number, content, parse_target(content)))
82
+ except ValueError as exc:
83
+ lines.append(BatchLine(number, content, None, str(exc)))
84
+ return lines
85
+
86
+
87
+ def run_batch(
88
+ lines: Sequence[BatchLine],
89
+ check: BatchCheck,
90
+ *,
91
+ timeout: float | None = None,
92
+ parallel: int = DEFAULT_PARALLEL,
93
+ quick: bool = False,
94
+ server: str | None = None,
95
+ selectors: Sequence[str] = (),
96
+ resolvers: Sequence[tuple[str, str]] | None = None,
97
+ on_done: Callable[[BatchItem], None] | None = None,
98
+ ) -> BatchReport:
99
+ """Check every valid line's domain with `check`, up to `parallel` at a time.
100
+
101
+ A domain listed twice is checked once. `on_done` is called from worker threads as each
102
+ finishes. For `doctor`, this computer is checked once and shared by every domain.
103
+ `server`/`selectors` apply to lookup and email; `quick`/`resolvers` to doctor.
104
+ """
105
+ start = time.perf_counter()
106
+ seen: set[str] = set()
107
+ todo: list[BatchLine] = []
108
+ duplicates: list[BatchLine] = []
109
+ for line in lines:
110
+ if line.name is None:
111
+ continue
112
+ (duplicates if line.name in seen else todo).append(line)
113
+ seen.add(line.name)
114
+
115
+ local = local_check(probe_ghosts=False) if check is BatchCheck.DOCTOR and todo else None
116
+
117
+ def run(line: BatchLine) -> BatchItem:
118
+ assert line.name is not None
119
+ begun = time.perf_counter()
120
+ try:
121
+ report, ok, summary = _check(
122
+ line.name, check, timeout, quick, server, selectors, resolvers, local
123
+ )
124
+ error = None
125
+ except Exception as exc: # one domain mustn't stop the rest
126
+ report, ok, summary, error = (
127
+ None,
128
+ False,
129
+ "couldn't be checked",
130
+ str(exc) or type(exc).__name__,
131
+ )
132
+ item = BatchItem(
133
+ line.line, line.name, ok, summary, (time.perf_counter() - begun) * 1000, report, error
134
+ )
135
+ if on_done:
136
+ on_done(item)
137
+ return item
138
+
139
+ workers = max(1, min(parallel, MAX_PARALLEL, len(todo) or 1))
140
+ with ThreadPoolExecutor(max_workers=workers) as pool:
141
+ items = tuple(pool.map(run, todo))
142
+ return BatchReport(
143
+ check=check,
144
+ items=items,
145
+ invalid=tuple(line for line in lines if line.name is None),
146
+ duplicates=tuple(duplicates),
147
+ elapsed_ms=(time.perf_counter() - start) * 1000,
148
+ local=local,
149
+ )
150
+
151
+
152
+ def _check(
153
+ name: str,
154
+ check: BatchCheck,
155
+ timeout: float | None,
156
+ quick: bool,
157
+ server: str | None,
158
+ selectors: Sequence[str],
159
+ resolvers: Sequence[tuple[str, str]] | None,
160
+ local: LocalReport | None,
161
+ ) -> tuple[Any, bool, str]:
162
+ match check:
163
+ case BatchCheck.LOOKUP:
164
+ found = lookup(name, DEFAULT_RTYPES, nameserver=server, timeout=timeout or 5.0)
165
+ return found, *summarize_lookup(found)
166
+ case BatchCheck.DOCTOR:
167
+ health = doctor(
168
+ name,
169
+ quick=quick,
170
+ timeout=timeout or DOCTOR_TIMEOUT_S,
171
+ resolvers=resolvers,
172
+ local=local,
173
+ )
174
+ return health, *summarize_doctor(health)
175
+ case BatchCheck.EMAIL:
176
+ mail = email_check(name, selectors, nameserver=server, timeout=timeout or 5.0)
177
+ return mail, *summarize_email(mail)
178
+
179
+
180
+ def summarize_lookup(report: LookupReport) -> tuple[bool, str]:
181
+ """OK when the name exists; the summary lists how many records of each type it has."""
182
+ found = [r for r in report.results if r.records]
183
+ if found:
184
+ return True, ", ".join(f"{r.rtype} {len(r.records)}" for r in found)
185
+ statuses = [r.status for r in report.results]
186
+ if LookupStatus.NO_ANSWER in statuses:
187
+ return True, "exists, but has none of these records"
188
+ diagnosis = explain(statuses[0], report.name, "A")
189
+ return False, diagnosis.title if diagnosis else statuses[0].value
190
+
191
+
192
+ def summarize_doctor(report: DoctorReport) -> tuple[bool, str]:
193
+ """OK when healthy (no critical or major issue). The summary is the score and the most
194
+ important issue (notes aside), or "no issues"."""
195
+ top = report.problems[0].title if report.problems else "no issues"
196
+ return report.healthy, f"{report.score}/100 · {top}"
197
+
198
+
199
+ def summarize_email(report: EmailReport) -> tuple[bool, str]:
200
+ """OK unless a check fails; the summary is the most important finding."""
201
+ if report.domain_status is not LookupStatus.OK:
202
+ diagnosis = explain(report.domain_status, report.domain, "MX")
203
+ return False, diagnosis.title if diagnosis else report.domain_status.value
204
+ worst = report.status
205
+ headline = next(
206
+ (s.headline for _, s in report.checks if s.status is worst and s.headline), None
207
+ )
208
+ if worst is CheckStatus.PASS or headline is None:
209
+ return True, "all checks pass"
210
+ label = next(label for label, s in report.checks if s.headline is headline)
211
+ return worst is not CheckStatus.FAIL, f"{worst.value}: {label}: {headline.title}"
dnskit/core/compare.py ADDED
@@ -0,0 +1,168 @@
1
+ """Compare one record's answer across several resolvers."""
2
+
3
+ import time
4
+ from collections import Counter
5
+ from collections.abc import Sequence
6
+ from concurrent.futures import ThreadPoolExecutor
7
+ from dataclasses import dataclass
8
+ from enum import StrEnum
9
+
10
+ from dnskit.core.lookup import LookupResult, LookupStatus, _query_one, _validate_rtype
11
+ from dnskit.core.nameservers import system_nameservers
12
+
13
+ # Public resolvers always included in a comparison, as (label, IP).
14
+ PUBLIC_RESOLVERS: tuple[tuple[str, str], ...] = (
15
+ ("Google", "8.8.8.8"),
16
+ ("Cloudflare", "1.1.1.1"),
17
+ ("Quad9", "9.9.9.9"),
18
+ )
19
+
20
+ # Shorter than lookup's default: every resolver is queried at once, so the slowest one sets
21
+ # the total time, and a healthy resolver answers in well under a second.
22
+ COMPARE_TIMEOUT_S = 2.0
23
+
24
+ # Statuses that are a real answer from DNS (comparable between resolvers). Anything else
25
+ # means the resolver failed to give one.
26
+ _ANSWERED = {LookupStatus.OK, LookupStatus.NXDOMAIN, LookupStatus.NO_ANSWER}
27
+
28
+ # Record types whose values are case-sensitive text; other values are DNS names or numbers.
29
+ _CASE_SENSITIVE_RTYPES = {"TXT", "SPF", "CAA"}
30
+
31
+
32
+ class Agreement(StrEnum):
33
+ MAJORITY = "majority" # gave the most common answer
34
+ DIFFERS = "differs" # answered, but not with the most common answer (or there is none)
35
+ FAILED = "failed" # gave no usable answer: timeout, SERVFAIL, refused, no network
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class ResolverAnswer:
40
+ label: str # e.g. "Google", "System #2", or "Cloudflare / system #3"
41
+ nameserver: str
42
+ result: LookupResult
43
+ agreement: Agreement
44
+
45
+ @property
46
+ def ttl(self) -> int | None:
47
+ return self.result.records[0].ttl if self.result.records else None
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class CompareReport:
52
+ name: str
53
+ rtype: str
54
+ answers: tuple[ResolverAnswer, ...] # public resolvers first, then system order
55
+ has_majority: bool # False when no resolver answered, or the top answers are tied
56
+ distinct_answers: int # how many different answers the responding resolvers gave
57
+ elapsed_ms: float
58
+
59
+ @property
60
+ def responded(self) -> tuple[ResolverAnswer, ...]:
61
+ return tuple(a for a in self.answers if a.agreement is not Agreement.FAILED)
62
+
63
+ @property
64
+ def failed(self) -> tuple[ResolverAnswer, ...]:
65
+ return tuple(a for a in self.answers if a.agreement is Agreement.FAILED)
66
+
67
+ @property
68
+ def majority(self) -> tuple[ResolverAnswer, ...]:
69
+ return tuple(a for a in self.answers if a.agreement is Agreement.MAJORITY)
70
+
71
+ @property
72
+ def differing(self) -> tuple[ResolverAnswer, ...]:
73
+ return tuple(a for a in self.answers if a.agreement is Agreement.DIFFERS)
74
+
75
+ @property
76
+ def all_agree(self) -> bool:
77
+ """Every resolver that answered gave the same answer. Failures don't count."""
78
+ return bool(self.responded) and not self.differing
79
+
80
+
81
+ def compare(
82
+ name: str,
83
+ rtype: str = "A",
84
+ timeout: float = COMPARE_TIMEOUT_S,
85
+ resolvers: Sequence[tuple[str, str]] | None = None,
86
+ ) -> CompareReport:
87
+ """Query `name`/`rtype` through the public resolvers and each system nameserver.
88
+
89
+ `resolvers` replaces PUBLIC_RESOLVERS as (label, IP) pairs, e.g. from the config file.
90
+
91
+ Every resolver is queried on its own (no fallback to another server), all in parallel.
92
+ Answers are compared by status and record values, ignoring order, TTL and the case of
93
+ DNS names; resolvers that failed are left out of the comparison. An unknown record type
94
+ raises ValueError.
95
+ """
96
+ rtype = _validate_rtype(rtype)
97
+ asked = _resolvers_to_compare(PUBLIC_RESOLVERS if resolvers is None else resolvers)
98
+
99
+ start = time.perf_counter()
100
+ with ThreadPoolExecutor(max_workers=len(asked)) as pool:
101
+ results = list(pool.map(lambda r: _query_one(name, rtype, [r[1]], timeout), asked))
102
+
103
+ ranking = rank_answers(results)
104
+ answers = tuple(
105
+ ResolverAnswer(label, nameserver, result, agreement)
106
+ for (label, nameserver), result, agreement in zip(
107
+ asked, results, ranking.agreements, strict=True
108
+ )
109
+ )
110
+ return CompareReport(
111
+ name=name,
112
+ rtype=rtype,
113
+ answers=answers,
114
+ has_majority=ranking.has_majority,
115
+ distinct_answers=ranking.distinct_answers,
116
+ elapsed_ms=(time.perf_counter() - start) * 1000,
117
+ )
118
+
119
+
120
+ @dataclass(frozen=True)
121
+ class Ranking:
122
+ agreements: tuple[Agreement, ...] # one per result, in the same order
123
+ has_majority: bool
124
+ distinct_answers: int
125
+
126
+
127
+ def rank_answers(results: Sequence[LookupResult]) -> Ranking:
128
+ """Which results gave the most common answer. A tie for most common means no majority."""
129
+ keys = [answer_key(result) for result in results]
130
+ counts = Counter(key for key in keys if key is not None)
131
+ ranked = counts.most_common(2)
132
+ has_majority = bool(ranked) and (len(ranked) == 1 or ranked[0][1] > ranked[1][1])
133
+ majority = ranked[0][0] if has_majority else None
134
+
135
+ agreements = []
136
+ for key in keys:
137
+ if key is None:
138
+ agreements.append(Agreement.FAILED)
139
+ elif key == majority:
140
+ agreements.append(Agreement.MAJORITY)
141
+ else:
142
+ agreements.append(Agreement.DIFFERS)
143
+ return Ranking(tuple(agreements), has_majority, len(counts))
144
+
145
+
146
+ def _resolvers_to_compare(public: Sequence[tuple[str, str]]) -> list[tuple[str, str]]:
147
+ """Public resolvers, then system nameservers, as (label, IP), each IP only once.
148
+
149
+ System nameservers are numbered in system order, matching `dnskit resolvers`. One that is
150
+ also a public resolver keeps the public resolver's row, labelled with both.
151
+ """
152
+ labels = {ip: label for label, ip in public}
153
+ for i, ip in enumerate(system_nameservers(), start=1):
154
+ if ip not in labels:
155
+ labels[ip] = f"System #{i}"
156
+ elif "system" not in labels[ip].lower():
157
+ labels[ip] += f" / system #{i}"
158
+ return [(label, ip) for ip, label in labels.items()]
159
+
160
+
161
+ def answer_key(result: LookupResult) -> tuple[LookupStatus, frozenset[str]] | None:
162
+ """What a resolver answered, in a form that compares equal for equivalent answers."""
163
+ if result.status not in _ANSWERED:
164
+ return None
165
+ values = (record.value for record in result.records)
166
+ if result.rtype not in _CASE_SENSITIVE_RTYPES:
167
+ values = (value.lower() for value in values)
168
+ return result.status, frozenset(values)
dnskit/core/config.py ADDED
@@ -0,0 +1,248 @@
1
+ """User settings: a TOML file with each command's default options and custom resolver lists.
2
+
3
+ The file is optional. `[defaults]` applies to every command that has the setting, a
4
+ command's own section (`[lookup]`, `[doctor]`, …) overrides it, and options on the command
5
+ line override both. `[compare]` and `[propagation]` can also replace the public resolvers
6
+ they ask. A broken file raises ConfigError (a ValueError) naming the file and the setting.
7
+ """
8
+
9
+ import os
10
+ import sys
11
+ import tomllib
12
+ from collections.abc import Iterable
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from dnskit.core.propagation import GLOBAL_REGION, PublicResolver
18
+ from dnskit.core.reverse import parse_ip
19
+
20
+ CONFIG_ENV = "DNSKIT_CONFIG"
21
+
22
+ _STR, _FLOAT, _INT, _BOOL, _STRS = "text", "number", "whole number", "true or false", "list of text"
23
+
24
+ # The settings each command accepts, by name, with the kind of value. Names are the long
25
+ # option names without the dashes (`--type` is `type`, `--selector` is `selectors`).
26
+ _TIMEOUT = {"timeout": _FLOAT, "json": _BOOL}
27
+ COMMAND_SETTINGS: dict[str, dict[str, str]] = {
28
+ "lookup": {"type": _STR, "server": _STR, **_TIMEOUT},
29
+ "reverse": {"server": _STR, **_TIMEOUT},
30
+ "compare": {"type": _STR, **_TIMEOUT},
31
+ "email": {"selectors": _STRS, "server": _STR, **_TIMEOUT},
32
+ "resolvers": {**_TIMEOUT},
33
+ "local": {**_TIMEOUT},
34
+ "reach": {"port": _INT, "server": _STR, **_TIMEOUT},
35
+ "trace": {"type": _STR, **_TIMEOUT},
36
+ "dnssec": {"server": _STR, **_TIMEOUT},
37
+ "propagation": {"type": _STR, **_TIMEOUT},
38
+ "doctor": {"quick": _BOOL, **_TIMEOUT},
39
+ "batch": {"check": _STR, "parallel": _INT, "quick": _BOOL, **_TIMEOUT},
40
+ "watch": {"type": _STR, "server": _STR, "interval": _FLOAT, "strict": _BOOL, **_TIMEOUT},
41
+ }
42
+ # Sections that also hold a resolver list, and the fields each entry has (name: required).
43
+ _RESOLVER_FIELDS: dict[str, dict[str, bool]] = {
44
+ "compare": {"name": True, "address": True},
45
+ "propagation": {"name": True, "address": True, "location": False, "region": False},
46
+ }
47
+
48
+ CONFIG_TEMPLATE = """\
49
+ # dnskit settings. Every setting is optional: delete or comment out what you don't need.
50
+ # Options given on the command line always win over this file.
51
+
52
+ [defaults]
53
+ # Applies to every command that has the setting.
54
+ # server = "1.1.1.1" # ask this DNS server instead of choosing the fastest system one
55
+ # json = true # always print JSON
56
+
57
+ # [lookup]
58
+ # type = "A" # one record type instead of A, AAAA, MX, CNAME, NS and TXT
59
+ # timeout = 5.0
60
+
61
+ # [email]
62
+ # selectors = ["s2024", "mailjet"] # your own DKIM selectors, checked every time
63
+
64
+ # [doctor]
65
+ # quick = true
66
+
67
+ # [watch]
68
+ # interval = 60.0 # seconds between checks
69
+
70
+ # [batch]
71
+ # check = "doctor" # lookup, doctor or email
72
+ # parallel = 4
73
+
74
+ # [compare]
75
+ # Replaces Google, Cloudflare and Quad9. This computer's DNS servers are always added.
76
+ # resolvers = [
77
+ # { name = "Google", address = "8.8.8.8" },
78
+ # { name = "Office DNS", address = "10.0.0.53" },
79
+ # ]
80
+
81
+ # [propagation]
82
+ # Replaces the 14 built-in resolvers. region = "global" marks an anycast resolver.
83
+ # resolvers = [
84
+ # { name = "Google", address = "8.8.8.8", region = "global" },
85
+ # { name = "Telkom", address = "196.43.1.14", location = "South Africa", region = "Africa" },
86
+ # ]
87
+ """
88
+
89
+
90
+ class ConfigError(ValueError):
91
+ """The config file can't be read, or a setting in it is wrong."""
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class Config:
96
+ path: Path
97
+ exists: bool
98
+ # Command name -> setting name -> value, with [defaults] already merged in.
99
+ settings: dict[str, dict[str, Any]] = field(default_factory=dict)
100
+ compare_resolvers: tuple[tuple[str, str], ...] | None = None # (label, IP)
101
+ propagation_resolvers: tuple[PublicResolver, ...] | None = None
102
+
103
+ def for_command(self, command: str) -> dict[str, Any]:
104
+ return dict(self.settings.get(command, {}))
105
+
106
+
107
+ def config_path() -> Path:
108
+ """Where the config file is. Override with DNSKIT_CONFIG."""
109
+ if override := os.environ.get(CONFIG_ENV):
110
+ return Path(override)
111
+ if sys.platform == "win32" and (appdata := os.environ.get("APPDATA")):
112
+ return Path(appdata) / "dnskit" / "config.toml"
113
+ xdg = os.environ.get("XDG_CONFIG_HOME")
114
+ return (Path(xdg) if xdg else Path.home() / ".config") / "dnskit" / "config.toml"
115
+
116
+
117
+ def load_config(path: Path | None = None) -> Config:
118
+ """Read and check the config file. A missing file is an empty config."""
119
+ path = path or config_path()
120
+ try:
121
+ text = path.read_text(encoding="utf-8")
122
+ except FileNotFoundError:
123
+ return Config(path, exists=False)
124
+ except OSError as exc:
125
+ raise ConfigError(f"Can't read {path}: {exc.strerror or exc}.") from exc
126
+ return parse_config(text, path)
127
+
128
+
129
+ def parse_config(text: str, path: Path) -> Config:
130
+ """Check a config file's text; every problem raises ConfigError naming the setting."""
131
+ try:
132
+ data = tomllib.loads(text)
133
+ except tomllib.TOMLDecodeError as exc:
134
+ raise ConfigError(f"{path} isn't valid TOML: {exc}.") from exc
135
+
136
+ def fail(where: str, problem: str) -> ConfigError:
137
+ return ConfigError(f"{path}: {where} {problem}.")
138
+
139
+ known = {"defaults", *COMMAND_SETTINGS}
140
+ for section, values in data.items():
141
+ if section not in known:
142
+ raise fail(f"[{section}]", f"isn't a dnskit section (use {_listed(sorted(known))})")
143
+ if not isinstance(values, dict):
144
+ raise fail(section, "must be a section, like [" + section + "]")
145
+
146
+ defaults = data.get("defaults", {})
147
+ every = {
148
+ name: kind for settings in COMMAND_SETTINGS.values() for name, kind in settings.items()
149
+ }
150
+ for name, value in defaults.items():
151
+ if name not in every:
152
+ raise fail(f"[defaults] {name}", "isn't a setting any command has")
153
+ _check(value, every[name], f"[defaults] {name}", fail)
154
+
155
+ settings: dict[str, dict[str, Any]] = {}
156
+ for command, allowed in COMMAND_SETTINGS.items():
157
+ own = dict(data.get(command, {}))
158
+ own.pop("resolvers", None) if command in _RESOLVER_FIELDS else None
159
+ for name, value in own.items():
160
+ if name not in allowed:
161
+ raise fail(f"[{command}] {name}", f"isn't a setting (use {_listed(allowed)})")
162
+ _check(value, allowed[name], f"[{command}] {name}", fail)
163
+ merged = {k: v for k, v in defaults.items() if k in allowed} | own
164
+ if merged:
165
+ settings[command] = merged
166
+
167
+ compare = _resolver_list(data, "compare", fail)
168
+ propagation = _resolver_list(data, "propagation", fail)
169
+ return Config(
170
+ path,
171
+ exists=True,
172
+ settings=settings,
173
+ compare_resolvers=tuple((r["name"], r["address"]) for r in compare) if compare else None,
174
+ propagation_resolvers=tuple(_public_resolver(r) for r in propagation)
175
+ if propagation
176
+ else None,
177
+ )
178
+
179
+
180
+ def _check(value: Any, kind: str, where: str, fail: Any) -> None:
181
+ ok = {
182
+ _STR: isinstance(value, str),
183
+ _FLOAT: isinstance(value, int | float) and not isinstance(value, bool) and value > 0,
184
+ _INT: isinstance(value, int) and not isinstance(value, bool) and value > 0,
185
+ _BOOL: isinstance(value, bool),
186
+ _STRS: isinstance(value, list) and all(isinstance(v, str) for v in value),
187
+ }[kind]
188
+ if not ok:
189
+ positive = " above 0" if kind in (_FLOAT, _INT) else ""
190
+ raise fail(where, f"must be a {kind}{positive}, not {value!r}")
191
+
192
+
193
+ def _resolver_list(data: dict[str, Any], section: str, fail: Any) -> list[dict[str, str]]:
194
+ entries = data.get(section, {}).get("resolvers")
195
+ if entries is None:
196
+ return []
197
+ where = f"[{section}] resolvers"
198
+ if not isinstance(entries, list) or not entries:
199
+ raise fail(where, "must be a list of resolvers, like [{ name = ..., address = ... }]")
200
+ fields = _RESOLVER_FIELDS[section]
201
+ checked = []
202
+ for n, entry in enumerate(entries, start=1):
203
+ if not isinstance(entry, dict):
204
+ raise fail(f"{where} entry {n}", "must be a table like { name = ..., address = ... }")
205
+ for key, value in entry.items():
206
+ if key not in fields:
207
+ raise fail(f"{where} entry {n}", f"has an unknown field {key!r}")
208
+ if not isinstance(value, str) or not value.strip():
209
+ raise fail(f"{where} entry {n} {key}", "must be text")
210
+ for key, required in fields.items():
211
+ if required and key not in entry:
212
+ raise fail(f"{where} entry {n}", f"needs a {key}")
213
+ try:
214
+ parse_ip(entry["address"])
215
+ except ValueError:
216
+ raise fail(
217
+ f"{where} entry {n}", f"has an address that isn't an IP: {entry['address']!r}"
218
+ ) from None
219
+ checked.append(entry)
220
+ addresses = [e["address"] for e in checked]
221
+ if len(set(addresses)) < len(addresses):
222
+ raise fail(where, "lists the same address twice")
223
+ return checked
224
+
225
+
226
+ def _public_resolver(entry: dict[str, str]) -> PublicResolver:
227
+ region = entry.get("region", "Other")
228
+ if region.lower() in ("global", GLOBAL_REGION.lower()):
229
+ return PublicResolver(entry["name"], entry["address"], "nearest site", GLOBAL_REGION)
230
+ return PublicResolver(entry["name"], entry["address"], entry.get("location", "unknown"), region)
231
+
232
+
233
+ def write_template(path: Path | None = None) -> Path:
234
+ """Create a commented starter config file. An existing file raises ConfigError."""
235
+ path = path or config_path()
236
+ if path.exists():
237
+ raise ConfigError(f"{path} already exists; edit it instead.")
238
+ try:
239
+ path.parent.mkdir(parents=True, exist_ok=True)
240
+ path.write_text(CONFIG_TEMPLATE, encoding="utf-8")
241
+ except OSError as exc:
242
+ raise ConfigError(f"Can't write {path}: {exc.strerror or exc}.") from exc
243
+ return path
244
+
245
+
246
+ def _listed(names: Iterable[str]) -> str:
247
+ items = list(names)
248
+ return ", ".join(items[:-1]) + " or " + items[-1] if len(items) > 1 else items[0]