refactor: split core.upstream by subject

HTTP to the forges moves to core.forgehttp, comparisons, trees and
clone history to core.upstreamtree. core.upstream keeps repositories,
the cache and revisions.
This commit is contained in:
Abdessamad Derraz committed 2026-11-24 06:20:52 +01:00
1 parent ce92eff0aa
commit 263a64c0e0
65 files changed
+1417 -1337

No files matched your search

+2 -2
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import json
from core import upstream
from core import forgehttp
from sitegen.agents import INDEXNOW_FILE, INDEXNOW_KEY, PUBLISHER, SITE
HOST = PUBLISHER
@@ -16,7 +16,7 @@ USER_AGENT = "retrobios-indexnow"
def live_digests(url: str = f"{SITE}digests.json") -> dict[str, str]:
"""The digests the live site serves. None yet (the first deploy that
writes them) is an empty map: every page is new."""
body = upstream.fetch_body(url, timeout=60, user_agent=USER_AGENT)
body = forgehttp.fetch_body(url, timeout=60, user_agent=USER_AGENT)
return {} if body is None else json.loads(body.decode("utf-8"))
+7 -7
View File
@@ -19,7 +19,7 @@ from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from core import upstream
from core import forgehttp
from core.artifacts import write_text_atomic
from core.cli import SourceUnreadable
from core.github import github_token
@@ -37,7 +37,7 @@ USER_AGENT = "retrobios-site-insights"
EXPORT_POLL = 5
EXPORT_TRIES = 60
# GoatCounter answers four requests a second and 500 per window, and says
# when to come back in X-Rate-Limit-Reset. core.upstream.open_retrying waits
# when to come back in X-Rate-Limit-Reset. core.forgehttp.open_retrying waits
# a short wait and gives up on a long one, which ends the run.
# Expected click-through rate: the site's own rate at each rounded
@@ -83,15 +83,15 @@ class SourceUnavailable(Exception):
def _open(request: urllib.request.Request) -> tuple[int, bytes]:
"""Status and body of a request, retried by core.upstream.open_retrying:
"""Status and body of a request, retried by core.forgehttp.open_retrying:
a dropped connection or a 5xx is asked again, a rate limit waited out."""
try:
return upstream.open_retrying(request, lambda response: (response.status, response.read()), 60)
except (urllib.error.HTTPError, upstream.RateLimitError) as error:
return forgehttp.open_retrying(request, lambda response: (response.status, response.read()), 60)
except (urllib.error.HTTPError, forgehttp.RateLimitError) as error:
if isinstance(error, urllib.error.HTTPError) and error.code != 429:
raise
headers = error.headers if isinstance(error, urllib.error.HTTPError) else None
wait = upstream.requested_wait(headers)
wait = forgehttp.requested_wait(headers)
delay = f" for {wait:.0f} s" if wait is not None else ""
raise SourceUnavailable(f"{urllib.parse.urlsplit(request.full_url).hostname} refuses requests"
f"{delay} (rate limit); run again then", wait) from error
@@ -220,7 +220,7 @@ def fetch_github() -> dict:
if not github_token():
raise SourceUnavailable("GitHub traffic needs a token: GITHUB_TOKEN, or gh auth login")
api = f"https://api.github.com/repos/{REPOSITORY}"
auth = upstream.forge_headers(api, "application/vnd.github+json", USER_AGENT)
auth = forgehttp.forge_headers(api, "application/vnd.github+json", USER_AGENT)
releases = _get_json(f"{api}/releases?per_page=10", auth)
return {
"views": _get_json(f"{api}/traffic/views", auth),
+3 -2
View File
@@ -18,6 +18,7 @@ from core.artifacts import write_if_changed
from core.paths import DB_FILE, REPO_ROOT
from core.sizes import size_text
from core import upstream
from core import forgehttp
from installer_build.module import installer_module
from model.guides import PACKAGE_COMMAND
from sitegen.guidedata import install_command
@@ -161,9 +162,9 @@ def fetch_contributors() -> list[dict]:
return []
url = f"https://api.github.com/repos/{REPO}/contributors"
try:
body = upstream.fetch_body(url, accept_json=True, timeout=10, user_agent="retrobios-readme/1.0")
body = forgehttp.fetch_body(url, accept_json=True, timeout=10, user_agent="retrobios-readme/1.0")
data = json.loads(body) if body is not None else []
except (upstream.UpstreamError, ValueError) as exc:
except (forgehttp.UpstreamError, ValueError) as exc:
print(f"contributors: {exc}", file=sys.stderr)
return []
owner = REPO.split("/")[0]
+6 -4
View File
@@ -12,6 +12,8 @@ from pathlib import Path
from core.text import series
from core import upstream
from core import forgehttp
from core import upstreamtree
from core.artifacts import repository_output_lock, write_if_changed
from core.paths import REPO_ROOT
from model.citations import document_citations, known_repositories
@@ -217,8 +219,8 @@ def _cached_tree(
for index, cache_dir in enumerate(cache_dirs):
online = fetch and index == len(cache_dirs) - 1
try:
paths, truncated = upstream.list_tree(repo, pin, str(cache_dir), offline=not online)
except upstream.UpstreamError as exc:
paths, truncated = upstreamtree.list_tree(repo, pin, str(cache_dir), offline=not online)
except forgehttp.UpstreamError as exc:
print(f" {tree_key(repo, pin)}: {exc}", file=sys.stderr)
return None
if paths and not truncated:
@@ -277,8 +279,8 @@ def _listed_directories(
for index, cache_dir in enumerate(cache_dirs):
online = fetch and index == len(cache_dirs) - 1
try:
names = upstream.list_directory(repo, pin, folder, str(cache_dir), offline=not online)
except upstream.UpstreamError:
names = upstreamtree.list_directory(repo, pin, folder, str(cache_dir), offline=not online)
except forgehttp.UpstreamError:
names = None
if names is not None:
break