#!/usr/bin/env python3 """Vendor which request members a Route 53 condition key composes into tools/aws/sources/route53-condition-keys.json, a source of the request condition key table. AWS's Service Reference gives AssociateVPCWithHostedZone, DisassociateVPCFromHostedZone, ListHostedZonesByVPC, CreateHostedZone, CreateVPCAssociationAuthorization and DeleteVPCAssociationAuthorization the key `route53:VPCs` without saying where a request carries it, or in what form, and botocore does not say it either. Route 53's developer guide does, in its table of the condition keys Route 53 defines: route53:VPCs AssociateVPCWithHostedZone DisassociateVPCFromHostedZone ListHostedZonesByVPC CreateHostedZone CreateVPCAssociationAuthorization DeleteVPCAssociationAuthorization Multi-valued Represents a list of VPCs in the request of AssociateVPCWithHostedZone, ..., in the format of "VPCId=,VPCRegion= https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/specifying-conditions-route53.html This script copies the row of each key the table gives in a format of request members, `=` pairs, as it stands, with the operations it names and the members of its format, in order. A row giving no such format is not read here. Nothing in the output is written by hand; regen_request_condition_keys.py reads it to give the table each key as its format composes those members of each operation's request. Run from anywhere in the repo: python3 tools/aws/fetch_route53_conditions.py # rewrite the vendored file from the page python3 tools/aws/fetch_route53_conditions.py --verify # online: the file still says what the page does """ from __future__ import annotations import argparse import html import json import re import sys import urllib.request from datetime import datetime, timezone from pathlib import Path PAGE = "https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/specifying-conditions-route53.html" REPO_ROOT = Path(__file__).resolve().parents[2] OUTPUT = REPO_ROOT / "tools/aws/sources/route53-condition-keys.json" # The header of the page's table of condition keys. HEADER = ["Route 53 Condition Key", "API operations", "Value type", "Description"] # A description giving the key's value in a format of request members. FORMAT_RE = re.compile(r'\bin the format of "?(?P[A-Za-z]+=<[a-z-]+>(?:,[A-Za-z]+=<[a-z-]+>)+)') MEMBER_RE = re.compile(r"(?P[A-Za-z]+)=<[a-z-]+>") KEY_RE = re.compile(r"^route53:[A-Za-z]+$") OPERATION_RE = re.compile(r"^[A-Z][A-Za-z]+$") def text(fragment: str) -> str: """A fragment of a page as text, spaces collapsed.""" return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip() def body(page: str) -> str: """The page's own content, its navigation left out.""" match = re.search(r'
(?P.*?)(?:
list[list[str]]: """The rows of the page's table of condition keys, each its key, operations, value type and description.""" for table in re.findall(r"]*>(.*?)", body(page), re.S): rows = [[text(cell) for cell in re.findall(r"]*>(.*?)", row, re.S)] for row in re.findall(r"(.*?)", table, re.S)] if rows and rows[0] == HEADER: return [row for row in rows[1:] if len(row) == len(HEADER) and KEY_RE.match(row[0])] raise ValueError(f"{PAGE} has no table of Route 53 condition keys: its layout changed") def build(fetch) -> dict: keys = [] for key, operations, value_type, description in key_rows(fetch(PAGE)): found = FORMAT_RE.search(description) if found is None: continue named = operations.split() if not named or not all(OPERATION_RE.match(name) for name in named): raise ValueError(f"{PAGE} names {key}'s operations as '{operations}': its layout changed") keys.append({"key": key, "operations": named, "format": found.group("format"), "members": MEMBER_RE.findall(found.group("format")), "valueType": value_type, "row": description}) if not keys: raise ValueError(f"{PAGE} gives no key in a format of request members: its layout changed") return { "_source": { "page": PAGE, "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), "note": "Each Route 53 key whose row of the page's table of condition keys gives its value in a format of " "request members, with the operations the row names, the format and its members in order, and " "the row's description, copied as it stands.", }, "keys": sorted(keys, key=lambda entry: entry["key"]), } def fetch_url(url: str) -> str: request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"}) with urllib.request.urlopen(request, timeout=60) as response: return response.read().decode("utf-8") def stale(vendored: dict, page: str) -> bool: """Whether the page now gives something other than the vendored file, its date aside.""" return vendored.get("keys") != build(lambda url: page)["keys"] def main(argv: list[str] | None = None, fetch=fetch_url) -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the page") args = parser.parse_args(argv) try: page = fetch(PAGE) except OSError as e: print(f"error: could not read the Route 53 developer guide ({e})", file=sys.stderr) return 2 if args.verify: vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) if stale(vendored, page): print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the Route 53 developer guide does: run " f"tools/aws/fetch_route53_conditions.py and then make request-condition-keys-sync", file=sys.stderr) return 1 print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the Route 53 developer guide") return 0 built = build(lambda url: page) OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['keys'])} keys)") return 0 if __name__ == "__main__": sys.exit(main())