Resolve DNS with CNAME chains
Resolve a name against a table of A and CNAME records: follow the chain, return the addresses and the effective TTL, and tell apart a loop, a chain that is too long, a missing name and a name with no address.
Statement
Write resolve(records, name, max_hops=8), the lookup a resolver performs against data it already holds. records is a list of (owner, type, ttl, value). The value of an A record is an IPv4 address; the value of a CNAME record is another name to look up instead. Any other type (AAAA, TXT, MX) is not an address but still means its owner exists.
Starting at name, follow CNAMEs until you reach a name that is not an alias, and return a dict with four keys. status is "OK" when that name has A records; addresses then lists their values in table order, and ttl is the smallest TTL among every CNAME followed and every A record returned, because an answer may only be cached for as long as its shortest-lived part. chain is every name visited, starting with name, in lower case and without a trailing dot.
Otherwise addresses is [] and ttl is None, and status says why: "NXDOMAIN" when the last name in the chain has no records at all, "NODATA" when it exists but has no A record, "LOOP" when a CNAME points at a name already in the chain, and "TOO_LONG" when following the next CNAME would make more than max_hops hops. Check for the loop first. For LOOP and TOO_LONG, chain ends at the name whose CNAME was not followed.
Names match without regard to case, and one trailing dot is ignored. A CNAME may not share its owner with any other record, a second CNAME included: if the table breaks that rule anywhere, raise ValueError whatever name was asked for.
Examples
records = [
("www.example.com", "CNAME", 3600, "app.example.net"),
("app.example.net", "CNAME", 45, "edge-lb.example.net"),
("edge-lb.example.net", "A", 300, "192.0.2.10"),
("edge-lb.example.net", "A", 300, "192.0.2.11"),
("v6only.example.com", "AAAA", 300, "2001:db8::10"),
("api.example.com", "A", 120, "198.51.100.7"),
("a.example.com", "CNAME", 60, "b.example.com"),
("b.example.com", "CNAME", 60, "a.example.com"),
]
resolve(records, "www.example.com")
→ {"status": "OK", "addresses": ["192.0.2.10", "192.0.2.11"], "ttl": 45,
"chain": ["www.example.com", "app.example.net", "edge-lb.example.net"]}
resolve(records, "missing.example.com") → "NXDOMAIN", chain ["missing.example.com"]
resolve(records, "v6only.example.com") → "NODATA", chain ["v6only.example.com"]
resolve(records, "a.example.com") → "LOOP", chain ["a.example.com", "b.example.com"]Constraints
Up to 10⁵ records in any order. TTLs are non-negative integers. max_hops is 0 or more: a chain of exactly max_hops CNAMEs resolves, and with max_hops = 0 only a name with its own A records does.
Index the table once per call instead of scanning it at every hop. One test resolves a chain of 2,000 CNAMEs inside a table of 20,000 records.