"""Loading the Open Food Facts Canada + US products into `off_products` (the weekly import). Everything here runs as the table owner from the import script, never inside a web request. The file is streamed; only the kept columns are stored. A new set replaces the old one in a single transaction, and only when the whole file was read cleanly and looks sane. """ import csv import gzip import http.client import time import urllib.error import urllib.parse import urllib.request import zlib from collections.abc import Callable, Iterable, Iterator from dataclasses import dataclass from pathlib import Path from typing import Any import psycopg from app.adapters.off import VERSION from engine import offrows URL = "https://static.openfoodfacts.org/data/en.openfoodfacts.org.products.csv.gz" ALLOWED_HOST = "static.openfoodfacts.org" MIN_KEEP_RATIO = 0.5 # a new set under half the size of the last good one is refused MIN_ROWS = ( 50_000 # Canada + US is far larger; a tiny file is never accepted as the baseline ) REQUIRED = { "code", "countries_tags", "product_name", "energy-kcal_100g", "proteins_100g", "carbohydrates_100g", "fat_100g", "fiber_100g", } # fmt: skip LOCK_KEY = 90210 # advisory lock: one import at a time CHUNK = 1 << 20 COLUMNS = [ "code", "name", "brand", "quantity_text", "pack_g", "kcal", "protein_g", "carbs_g", "fat_g", "fibre_g", "serving_g", "per_text", "countries", ] Opener = Any # a urllib opener; tests pass a fake @dataclass(frozen=True) class Source: last_modified: str | None size: int | None def agent(contact: str) -> str: return f"MealSite/{VERSION} ({contact})" class NoRedirects(urllib.request.HTTPRedirectHandler): """The contact address goes only to Open Food Facts, so no redirect is ever followed.""" def redirect_request(self, *args: Any, **kwargs: Any) -> None: return None def make_opener() -> Any: return urllib.request.build_opener(NoRedirects) class HeaderError(ValueError): pass def check_url(url: str) -> None: parts = urllib.parse.urlsplit(url) if parts.scheme != "https" or parts.hostname != ALLOWED_HOST: raise ValueError("refusing to talk to an unexpected address") REDIRECT_HOSTS = { "openfoodfacts-ds.s3.eu-west-3.amazonaws.com" } # where their file really lives REDIRECTS = (301, 302, 303, 307, 308) def fetch( opener: Opener, url: str, contact: str, method: str, extra: dict[str, str], timeout: float, ) -> Any: """Open `url` (Open Food Facts' own address, with the contact in the User-Agent). If it answers with a redirect, follow exactly one, and only to their known file host over https; that second request carries no contact address. Anything else is refused.""" check_url(url) first = urllib.request.Request( url, method=method, headers={"User-Agent": agent(contact), **extra} ) try: return opener.open(first, timeout=timeout) except urllib.error.HTTPError as e: if e.code not in REDIRECTS: raise target = urllib.parse.urljoin( url, e.headers.get("Location", "") if e.headers else "" ) parts = urllib.parse.urlsplit(target) if parts.scheme != "https" or parts.hostname not in REDIRECT_HOSTS: raise ValueError("refusing to follow a redirect to an unexpected address") second = urllib.request.Request( target, method=method, headers={"User-Agent": f"MealSite/{VERSION}", **extra} ) return opener.open(second, timeout=timeout) def head(opener: Opener, contact: str, url: str = URL) -> Source: with fetch(opener, url, contact, "HEAD", {}, 30) as r: size = r.headers.get("Content-Length") return Source( r.headers.get("Last-Modified"), int(size) if size and size.isdigit() else None, ) RETRIES = 60 # stalled attempts in a row before giving up for this run PAUSE_S = 5.0 def download( opener: Opener, contact: str, dest: Path, expected: int | None, url: str = URL, progress: Callable[[int], None] | None = None, sleep: Callable[[float], None] = time.sleep, ) -> None: """Fetch the file to `dest`, continuing a partial file from where it stopped (Range). A stall or a dropped connection part-way (the file host is slow and sometimes goes quiet) is retried from the same place after a short pause, so a two-hour download survives hiccups.""" stalls = 0 while True: have = dest.stat().st_size if dest.exists() else 0 if expected is not None and have > expected: dest.unlink() have = 0 if expected is not None and have == expected: return extra = {"Range": f"bytes={have}-"} if have else {} try: with fetch(opener, url, contact, "GET", extra, 60) as r: status = getattr(r, "status", 200) mode = ( "ab" if have and status == 206 else "wb" ) # no Range support: restart with open(dest, mode) as out: while chunk := r.read(CHUNK): out.write(chunk) if progress: progress(len(chunk)) except ( TimeoutError, ConnectionError, urllib.error.URLError, http.client.HTTPException, ) as e: if isinstance(e, urllib.error.HTTPError) and e.code not in ( 500, 502, 503, 504, ): raise moved = (dest.stat().st_size if dest.exists() else 0) > have stalls = 0 if moved else stalls + 1 if stalls >= RETRIES: raise OSError( "the download keeps stalling; it continues next time" ) from e sleep(PAUSE_S) continue size = dest.stat().st_size if expected is None or size == expected: return if size <= have: # a clean end with nothing new: no point asking again now raise OSError("the download is incomplete; it continues next time") def read_rows(path: Path) -> Iterator[dict[str, str]]: """Rows of the gzipped tab-separated file, one at a time (nothing is held in memory).""" csv.field_size_limit(2**31 - 1) # sys.maxsize overflows a 32-bit C long on Windows with gzip.open(path, "rt", encoding="utf-8", errors="replace", newline="") as f: reader = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE) missing = REQUIRED - set(reader.fieldnames or []) if ( missing ): # a renamed column must stop the import, not quietly empty the table raise HeaderError( "the file's header has changed: " + ", ".join(sorted(missing)) ) yield from reader def kept_rows( rows: Iterable[dict[str, str]], counter: dict[str, int] ) -> Iterator[offrows.Row]: seen: set[str] = set() for raw in rows: counter["read"] += 1 row = offrows.parse_row(raw) if row is None or row.code in seen: continue seen.add(row.code) counter["kept"] += 1 yield row def load_staging(conn: psycopg.Connection[Any], rows: Iterable[offrows.Row]) -> None: conn.execute("delete from off_products_staging") cols = ", ".join(COLUMNS) with conn.cursor().copy(f"copy off_products_staging ({cols}) from stdin") as cp: for r in rows: cp.write_row([getattr(r, c) for c in COLUMNS]) def last_good( conn: psycopg.Connection[Any], ) -> tuple[int, str | None, int | None] | None: row = conn.execute( """select rows_kept, source_last_modified, source_bytes from off_imports where status = 'ok' order by id desc limit 1""" ).fetchone() return None if row is None else (int(row[0]), row[1], row[2]) def start_log(conn: psycopg.Connection[Any]) -> int: row = conn.execute( "insert into off_imports (status) values ('running') returning id" ).fetchone() assert row is not None return int(row[0]) def finish_log( conn: psycopg.Connection[Any], log_id: int, status: str, note: str, read: int, kept: int, src: Source, ) -> None: conn.execute( """update off_imports set status = %s, note = %s, rows_read = %s, rows_kept = %s, source_last_modified = %s, source_bytes = %s, finished_at = clock_timestamp() where id = %s""", (status, note[:300], read, kept, src.last_modified, src.size, log_id), ) def import_file( admin_url: str, path: Path, src: Source, rows: Iterable[dict[str, str]] | None = None, min_rows: int | None = None, ) -> tuple[str, str]: """Load, check and swap. Returns (status, note). Old data stays unless status is 'ok'.""" with psycopg.connect(admin_url, autocommit=True) as logconn: got = logconn.execute("select pg_try_advisory_lock(%s)", (LOCK_KEY,)).fetchone() if got is None or not got[0]: return "failed", "another import is already running" logconn.execute( # a run that died leaves 'running' behind: mark it """update off_imports set status = 'failed', note = 'interrupted', finished_at = clock_timestamp() where status = 'running'""" ) log_id = start_log(logconn) counter = {"read": 0, "kept": 0} try: with psycopg.connect( admin_url ) as conn: # one transaction: stage, check, swap load_staging( conn, kept_rows(rows if rows is not None else read_rows(path), counter), ) prev = last_good(logconn) least = MIN_ROWS if min_rows is None else min_rows floor = max(least, int(prev[0] * MIN_KEEP_RATIO)) if prev else least if counter["kept"] < floor: conn.rollback() note = f"kept {counter['kept']} rows, under the floor of {floor}; nothing replaced" finish_log( logconn, log_id, "refused", note, counter["read"], counter["kept"], src, ) return "refused", note conn.execute("delete from off_products") conn.execute( f"insert into off_products ({', '.join(COLUMNS)}) " f"select {', '.join(COLUMNS)} from off_products_staging" ) conn.execute("delete from off_products_staging") note = f"replaced with {counter['kept']} products" finish_log( logconn, log_id, "ok", note, counter["read"], counter["kept"], src ) return "ok", note except ( OSError, EOFError, UnicodeError, csv.Error, zlib.error, HeaderError, psycopg.Error, ) as e: why = ( str(e) if isinstance(e, HeaderError) else "the file could not be read cleanly" ) rule = getattr(getattr(e, "diag", None), "constraint_name", None) if rule: # the name of the table rule, never any product data why += f" (rule: {rule})" note = f"{type(e).__name__}: {why}; nothing replaced" finish_log( logconn, log_id, "failed", note, counter["read"], counter["kept"], src ) return "failed", note def unchanged(conn: psycopg.Connection[Any], src: Source) -> bool: prev = last_good(conn) return ( prev is not None and src.last_modified is not None and prev[1] == src.last_modified and (prev[2] is None or src.size is None or prev[2] == src.size) )