13/28
Part 4 of 6 · A pool and a coordinatorLearn and do
One coordinator thread makes every decision
A pool fetches a fixed list of URLs. A crawl doesn't have a fixed list.
Each finished page can bring more work
wait = wait(pending, return_when=FIRST_COMPLETED). Block until any one fetch finishes.
The hard part isn't fetching in parallel. It's that work makes more work: every finished page can bring new URLs. So you can't submit everything up front and wait. You need a loop that keeps feeding the pool, and a rule for when to stop.
The cleanest version keeps every decision in one thread, the coordinator. Workers only fetch.
The coordinator loop
import logging
import sys
from collections.abc import Callable
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from urllib.parse import urldefrag, urljoin, urlparse
logging.basicConfig(stream=sys.stdout, format="%(message)s")
log = logging.getLogger("crawler")
def normalize(base: str, href: str) -> str:
"""href resolved against its page, base, with no fragment."""
return urldefrag(urljoin(base, href)).url
def crawl(
start_url: str, fetch: Callable[[str], list[str]], max_workers: int = 8
) -> set[str]:
"""Every reachable page on the start's host, max_workers fetches at a time."""
start = urldefrag(start_url).url
host = urlparse(start).hostname
# every URL ever submitted
seen = {start}
with ThreadPoolExecutor(max_workers=max_workers) as pool:
# future -> its URL
pending = {pool.submit(fetch, start): start}
while pending:
done, _ = wait(pending, return_when=FIRST_COMPLETED)
for future in done:
url = pending.pop(future)
try:
links = future.result()
except Exception as exc:
log.warning("fetch failed for %s: %r", url, exc)
continue
for link in links:
link = normalize(url, link)
if urlparse(link).hostname == host and link not in seen:
seen.add(link)
pending[pool.submit(fetch, link)] = link
return seen
calls.clear()
for url in sorted(crawl(f"{E}/", fetch, max_workers=4)):
print(url)
print(len(calls), "fetches")
The coordinator crawls the small site on 4 workers. How many fetches, and what happens at /broken?
Pick one to see what it prints.
Pick an answer above to see the rest