From e4de3e3770e9bde81dce42ebcf844b841737e43c Mon Sep 17 00:00:00 2001 From: itvi-1234 Date: Wed, 2 Dec 2026 12:13:34 +0530 Subject: [PATCH] Make publishing safe to repeat, publish only missing versions, and look up registries in parallel Publishing is about to run after every generation on main, so two runs close together and many packages have to work. Repeated publishing: a run started soon after another can build a version that the registry has just received but does not list yet. PyPI now skips a file it already has (skip-existing). When npm refuses a publish or a first-release stage, the script asks npm again and skips the package if the version is there. When the Central Portal refuses an upload, the script asks Maven Central again and skips it if the version is there; otherwise it says the upload may still be publishing from another run and points to the Portal's deployments, since the Portal has no documented lookup by coordinates. Only missing versions: preflight now passes each registry's workflow only the versions that registry does not have, instead of all, so a release of one package no longer builds every package. An empty or malformed targets list is never sent, because an empty input means every package to those workflows. Parallel lookups: registries are asked side by side, 16 lookups at a time per registry. Lookups a registry throttles (429, 5xx) or that fail on the network are tried again 8 at a time, then one by one, with a pause before each round. Go versions come from one tag listing instead of one git ls-remote per package. The pull request card uses the same lookups. A preflight of every package in every language took 5 seconds against the live registries. --- .github/workflows/binding-publish-all.yml | 6 +- .github/workflows/binding-publish-pypi.yml | 4 + .../extension-bindings/ci/publish-maven.py | 14 +++- tooling/extension-bindings/ci/publish-npm.py | 20 +++-- tooling/extension-bindings/ci/publish_all.py | 78 ++++++++++++------- .../extension-bindings/ci/publish_setup.py | 64 +++++++++++++-- .../extension-bindings/ci/test_publish_all.py | 40 +++++++++- .../ci/test_publish_maven.py | 14 ++++ .../extension-bindings/ci/test_publish_npm.py | 35 +++++++++ .../ci/test_publish_setup.py | 56 +++++++++++++ 10 files changed, 288 insertions(+), 43 deletions(-) diff --git a/.github/workflows/binding-publish-all.yml b/.github/workflows/binding-publish-all.yml index 35f557c..8125f74 100644 --- a/.github/workflows/binding-publish-all.yml +++ b/.github/workflows/binding-publish-all.yml @@ -57,6 +57,7 @@ jobs: timeout-minutes: 10 outputs: languages: ${{ steps.plan.outputs.languages }} + targets: ${{ steps.plan.outputs.targets }} env: PACKAGES: ${{ inputs.packages }} EXECUTE: ${{ !inputs.dry_run }} @@ -122,10 +123,11 @@ jobs: # Starting another workflow with workflow_dispatch. actions: write env: - PACKAGES: ${{ inputs.packages }} EXECUTE: ${{ !inputs.dry_run }} MAVEN_AUTO_PUBLISH: ${{ inputs.maven_auto_publish }} LANGUAGE: ${{ matrix.language }} + # Only the versions preflight found missing from this registry, not every selected package. + TARGETS: ${{ fromJSON(needs.preflight.outputs.targets)[matrix.language] }} steps: - name: Check out repository @@ -147,7 +149,7 @@ jobs: GH_TOKEN: ${{ github.token }} run: | set -euo pipefail - args=(--language "$LANGUAGE" --packages "$PACKAGES" --ref main) + args=(--language "$LANGUAGE" --targets "$TARGETS" --ref main) if [[ "$EXECUTE" == true ]]; then args+=(--execute) fi diff --git a/.github/workflows/binding-publish-pypi.yml b/.github/workflows/binding-publish-pypi.yml index 37af081..374ceb4 100644 --- a/.github/workflows/binding-publish-pypi.yml +++ b/.github/workflows/binding-publish-pypi.yml @@ -83,3 +83,7 @@ jobs: uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 with: packages-dir: dist/ + # The build skips versions PyPI lists, but a run started right after another one + # can still rebuild a file PyPI just received. PyPI never takes a filename twice, + # so that file is skipped instead of failing the run. + skip-existing: true diff --git a/tooling/extension-bindings/ci/publish-maven.py b/tooling/extension-bindings/ci/publish-maven.py index 8ce1eb1..537da6f 100644 --- a/tooling/extension-bindings/ci/publish-maven.py +++ b/tooling/extension-bindings/ci/publish-maven.py @@ -250,7 +250,19 @@ def publish(root: Path, targets: list[Target], execute: bool, auto: bool = False pom_file.write_text( auto_publish_settings(pom_file.read_text(encoding="utf-8")), encoding="utf-8" ) - run(["mvn", "-B", "-Prelease", "deploy"], copy) + try: + run(["mvn", "-B", "-Prelease", "deploy"], copy) + except subprocess.CalledProcessError as error: + # Central never takes a version twice. The Portal has no documented lookup by + # coordinates, so an upload another run made that is still publishing cannot be seen. + if already_published(coordinate): + summarize(f"{label} reached Maven Central from another run meanwhile; skipped.") + continue + raise ValueError( + f"the Central Portal refused {label}. If another publish run uploaded this version " + f"within the last hour, it may still be publishing: check {DEPLOYMENTS}, and when it " + "is there, nothing needs doing. Otherwise the Maven output above has the reason." + ) from error if auto: uploaded.append(coordinate) summarize(f"Uploaded {label}; it passed validation and the Portal is publishing it.") diff --git a/tooling/extension-bindings/ci/publish-npm.py b/tooling/extension-bindings/ci/publish-npm.py index 4474833..2e2dba4 100644 --- a/tooling/extension-bindings/ci/publish-npm.py +++ b/tooling/extension-bindings/ci/publish-npm.py @@ -233,17 +233,27 @@ def publish(root: Path, targets: list[Target], execute: bool) -> None: "(Staged Packages); skipped." ) elif status == "missing": - run( - ["npm", "stage", "publish", "--access", "public", "--ignore-scripts"], - destination, - env={**os.environ, "NODE_AUTH_TOKEN": os.environ[STAGE_TOKEN]}, - ) + try: + run( + ["npm", "stage", "publish", "--access", "public", "--ignore-scripts"], + destination, + env={**os.environ, "NODE_AUTH_TOKEN": os.environ[STAGE_TOKEN]}, + ) + except subprocess.CalledProcessError: + if npm_status(package_name) == "missing": + raise + summarize(f"{package_name} was staged or published by another run meanwhile; skipped.") + continue staged.append(f"{package_name}@{version}") summarize(f"Staged {package_name}@{version} as its first release.") else: try: run(["npm", "publish", "--access", "public", "--ignore-scripts"], destination) except subprocess.CalledProcessError as error: + # npm never takes a version twice; another run may have published it moments ago. + if already_published(package_name, version): + summarize(f"{package_name}@{version} was published by another run meanwhile; skipped.") + continue if package_name in untrusted: raise ValueError( f"npm refused {package_name}: it has no trusted publisher for this workflow. " diff --git a/tooling/extension-bindings/ci/publish_all.py b/tooling/extension-bindings/ci/publish_all.py index 4aa4ed7..16cadbf 100644 --- a/tooling/extension-bindings/ci/publish_all.py +++ b/tooling/extension-bindings/ci/publish_all.py @@ -29,12 +29,13 @@ import argparse import json import os +import re import subprocess import sys import time -import urllib.error import urllib.request import xml.etree.ElementTree as ET +from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from datetime import datetime, timedelta, timezone from pathlib import Path @@ -104,23 +105,20 @@ def packages(catalog: dict, keys: list[str], languages: list[str]) -> list[Packa return result -def child_targets(keys: list[str], every: bool, language: str, chosen: list[Package]) -> str: - """The targets input of one language's publish workflow.""" - if every: - return "all" - return ",".join(f"{item.key}:{language}" for item in chosen if item.language == language) +def child_targets(findings: list[Finding], language: str) -> str: + """The targets input of one language's publish workflow: only the versions its registry does not have yet, + so a release of one package does not build every package.""" + return ",".join( + f"{item.package.key}:{language}" + for item in findings + if item.package.language == language and item.status != PUBLISHED + ) # Registry lookups. Each returns the versions a registry lists for a package, or # None when the package does not exist there yet. def _get(url: str) -> bytes | None: - try: - with urllib.request.urlopen(url, timeout=30) as response: - return response.read() - except urllib.error.HTTPError as error: - if error.code == 404: - return None - raise + return publish_setup.fetch(url) def npm_versions(package: Package) -> set[str] | None: @@ -141,16 +139,38 @@ def maven_versions(package: Package) -> set[str] | None: return {(item.text or "").strip() for item in ET.fromstring(body).findall("./versioning/versions/version")} -def go_versions(package: Package, root: Path) -> set[str] | None: - prefix = f"refs/tags/bindings/{package.key}/go/v" +def go_tags(root: Path) -> list[str]: + """Every binding tag on the remote, read once for all Go packages.""" output = subprocess.run( - ["git", "ls-remote", "--tags", "origin", prefix + "*"], + ["git", "ls-remote", "--tags", "origin", "refs/tags/bindings/*"], cwd=root, check=True, capture_output=True, text=True, ).stdout - versions = {line.split()[1][len(prefix):].removesuffix("^{}") for line in output.splitlines() if line.strip()} + return [line.split()[1] for line in output.splitlines() if line.strip()] + + +def go_versions(package: Package, tags: list[str]) -> set[str] | None: + prefix = f"refs/tags/bindings/{package.key}/go/v" + versions = {tag[len(prefix):].removesuffix("^{}") for tag in tags if tag.startswith(prefix)} return versions or None +def look_up(chosen: list[Package], lookup: Callable[[Package], set[str] | None]) -> list[set[str] | None]: + """Every package's registry versions, in the order given. Registries are asked side by side, each 16 at a + time, then 8, then one by one for what a registry throttled (publish_setup.gather).""" + by_language: dict[str, list[Package]] = {} + for item in chosen: + by_language.setdefault(item.language, []).append(item) + + def one_registry(items: list[Package]) -> dict[Package, set[str] | None]: + return dict(zip(items, publish_setup.gather(items, lookup))) + + answers: dict[Package, set[str] | None] = {} + with ThreadPoolExecutor(max(len(by_language), 1)) as pool: + for part in pool.map(one_registry, by_language.values()): + answers.update(part) + return [answers[item] for item in chosen] + + def inspect(package: Package, versions: set[str] | None, execute: bool) -> Finding: """What publishing a package's version would do, and whether it needs setup first.""" if versions is not None and package.version.removeprefix("v") in {item.removeprefix("v") for item in versions}: @@ -186,10 +206,11 @@ def preflight( languages = selected_languages(languages_text) chosen = packages(catalog, keys, languages) if lookup is None: - lookups = {"go": lambda item: go_versions(item, root), "python": pypi_versions, + tags = go_tags(root) if "go" in languages else [] + lookups = {"go": lambda item: go_versions(item, tags), "python": pypi_versions, "typescript": npm_versions, "java": maven_versions} lookup = lambda item: lookups[item.language](item) # noqa: E731 - findings = [inspect(item, lookup(item), execute) for item in chosen] + findings = [inspect(item, versions, execute) for item, versions in zip(chosen, look_up(chosen, lookup))] pending = [language for language in languages if any(item.package.language == language and item.status != PUBLISHED for item in findings)] return findings, pending, any(item.blocking for item in findings) @@ -219,6 +240,14 @@ def setup_stop(card: str | None, execute: bool, setup_done: bool) -> str | None: ) +def checked_targets(targets: str, language: str) -> str: + """The targets preflight gave one language. An empty input means every package to the child workflows, so an + empty or malformed one stops the run instead of being sent.""" + if not re.fullmatch(rf"[a-z0-9-]+:{language}(,[a-z0-9-]+:{language})*", targets): + raise ValueError(f"no {language} targets from preflight: {targets!r}") + return targets + + def report(findings: list[Finding], execute: bool) -> str: lines = [ f"## Binding publication plan ({'real run' if execute else 'dry run'})", @@ -299,7 +328,7 @@ def main() -> None: start = commands.add_parser("dispatch", help="run one language's publish workflow and wait for it") start.add_argument("--root", type=Path, default=Path.cwd()) start.add_argument("--language", required=True, choices=list(WORKFLOWS)) - start.add_argument("--packages", default="all") + start.add_argument("--targets", required=True, help="this language's targets, from the preflight output") start.add_argument("--ref", default="main") start.add_argument("--execute", action="store_true") start.add_argument("--maven-auto-publish", action="store_true") @@ -323,15 +352,12 @@ def main() -> None: summarize(report(findings, args.execute)) if blocked: summarize("⛔ A real run cannot publish these first releases. Nothing was published.") - write_outputs(languages=json.dumps(pending), blocked=str(blocked).lower()) + targets = {language: child_targets(findings, language) for language in pending} + write_outputs(languages=json.dumps(pending), targets=json.dumps(targets), blocked=str(blocked).lower()) if blocked: sys.exit(1) return - catalog = yaml.safe_load((root / TOOLING / "packages.yaml").read_text(encoding="utf-8")) - keys = selected_keys(catalog, args.packages) - every = args.packages.strip() in ("", "all") - targets = child_targets(keys, every, args.language, packages(catalog, keys, [args.language])) - inputs = {"targets": targets, "dry_run": "false" if args.execute else "true"} + inputs = {"targets": checked_targets(args.targets, args.language), "dry_run": "false" if args.execute else "true"} if args.language == "java": inputs["auto_publish"] = "true" if args.maven_auto_publish else "false" token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN", "") diff --git a/tooling/extension-bindings/ci/publish_setup.py b/tooling/extension-bindings/ci/publish_setup.py index c9f4f2a..6ba5d43 100644 --- a/tooling/extension-bindings/ci/publish_setup.py +++ b/tooling/extension-bindings/ci/publish_setup.py @@ -27,11 +27,13 @@ import argparse import json +import time import urllib.error import urllib.request +from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from pathlib import Path -from typing import Callable +from typing import Callable, TypeVar import yaml @@ -69,6 +71,21 @@ class Finding: state: str +# Registries answered 48 lookups at a time without throttling in a test, so +# lookups start 16 at a time per registry. The ones a registry throttles, or +# that fail on the network, are tried again 8 at a time, then one by one. +WORKER_STEPS = (16, 8, 1) +STEP_PAUSE_SECONDS = 5 +RETRY_CODES = {429, 500, 502, 503, 504} + +T = TypeVar("T") +R = TypeVar("R") + + +class Throttled(OSError): + """A registry answered too many requests or failed for a moment; asking again later can work.""" + + def fetch(url: str) -> bytes | None: """The body of a public URL, or None when it does not exist.""" try: @@ -77,7 +94,44 @@ def fetch(url: str) -> bytes | None: except urllib.error.HTTPError as error: if error.code == 404: return None + if error.code in RETRY_CODES: + raise Throttled(f"{url}: HTTP {error.code}") from error raise + except (urllib.error.URLError, TimeoutError) as error: + raise Throttled(f"{url}: {error}") from error + + +def gather(items: list[T], work: Callable[[T], R]) -> list[R]: + """work(item) for every item, in order. Each round runs fewer at a time than the one before (WORKER_STEPS), + and only for the items the last round could not finish because a registry throttled or failed for a moment.""" + results: dict[int, R] = {} + pending = list(range(len(items))) + error: Throttled | None = None + for step, workers in enumerate(WORKER_STEPS): + if not pending: + break + if step: + time.sleep(STEP_PAUSE_SECONDS) + + def attempt(index: int) -> tuple[int, R | None, Throttled | None]: + try: + return index, work(items[index]), None + except Throttled as failure: + return index, None, failure + + with ThreadPoolExecutor(workers) as pool: + outcomes = list(pool.map(attempt, pending)) + pending = [] + for index, value, failure in outcomes: + if failure is None: + results[index] = value # type: ignore[assignment] + else: + pending.append(index) + error = failure + if pending: + assert error is not None + raise error + return [results[index] for index in range(len(items))] def packages(root: Path, base: str, head: str) -> list[Package]: @@ -117,10 +171,10 @@ def pypi_state(package: Package, get: Fetch) -> str: def inspect(found: list[Package], get: Fetch = fetch) -> list[Finding]: - return [ - Finding(package, npm_state(package, get) if package.language == "typescript" else pypi_state(package, get)) - for package in found - ] + def state(package: Package) -> Finding: + return Finding(package, npm_state(package, get) if package.language == "typescript" else pypi_state(package, get)) + + return gather(found, state) def trust_command(names: list[str]) -> str: diff --git a/tooling/extension-bindings/ci/test_publish_all.py b/tooling/extension-bindings/ci/test_publish_all.py index aafd0ca..72f01b7 100644 --- a/tooling/extension-bindings/ci/test_publish_all.py +++ b/tooling/extension-bindings/ci/test_publish_all.py @@ -54,10 +54,42 @@ def test_languages_and_packages_are_parsed_and_unknown_ones_refused(self) -> Non with self.assertRaisesRegex(ValueError, "unknown package nope"): script.selected_keys(CATALOG, "nope") - def test_each_child_workflow_gets_its_own_language_targets(self) -> None: - chosen = script.packages(CATALOG, ["common", "env"], ["python"]) - self.assertEqual(script.child_targets(["common", "env"], False, "python", chosen), "common:python,env:python") - self.assertEqual(script.child_targets(["common", "env"], True, "python", chosen), "all") + def test_each_child_workflow_gets_only_the_versions_its_registry_lacks(self) -> None: + chosen = script.packages(CATALOG, ["common", "env"], ["python", "typescript"]) + status = {"common": script.PUBLISHED, "env": script.NEW_VERSION} + findings = [script.Finding(item, status[item.key]) for item in chosen] + self.assertEqual(script.child_targets(findings, "python"), "env:python") + self.assertEqual(script.child_targets(findings, "typescript"), "env:typescript") + self.assertEqual(script.child_targets(findings, "java"), "") + + def test_a_child_workflow_never_gets_an_empty_targets_input(self) -> None: + self.assertEqual(script.checked_targets("common:java,env:java", "java"), "common:java,env:java") + for bad in ("", "all", "common:go", "common:java,"): + with self.subTest(bad=bad), self.assertRaisesRegex(ValueError, "no java targets"): + script.checked_targets(bad, "java") + + def test_lookups_run_in_parallel_and_keep_their_order(self) -> None: + chosen = script.packages(CATALOG, ["common", "env"], ["go", "python", "typescript", "java"]) + seen = [] + + def lookup(item): + seen.append(item) + return {item.version} if item.key == "common" else None + + answers = script.look_up(chosen, lookup) + self.assertEqual(sorted(seen, key=chosen.index), chosen) + self.assertEqual(answers, [{item.version} if item.key == "common" else None for item in chosen]) + + def test_go_versions_come_from_one_tag_listing(self) -> None: + tags = [ + "refs/tags/bindings/common/go/v0.4.0", + "refs/tags/bindings/common/go/v0.4.0^{}", + "refs/tags/bindings/common-extra/go/v9.0.0", + "refs/tags/bindings/env/python/v1.0.0", + ] + common = script.Package("common", "go", "example.com/x/common", "0.4.0") + self.assertEqual(script.go_versions(common, tags), {"0.4.0"}) + self.assertIsNone(script.go_versions(script.Package("env", "go", "example.com/x/env", "0.1.0"), tags)) def test_published_new_and_first_release_versions_are_told_apart(self) -> None: go, python, typescript, java = script.packages(CATALOG, ["common"], list(script.LANGUAGES)) diff --git a/tooling/extension-bindings/ci/test_publish_maven.py b/tooling/extension-bindings/ci/test_publish_maven.py index 4f394b0..83912be 100644 --- a/tooling/extension-bindings/ci/test_publish_maven.py +++ b/tooling/extension-bindings/ci/test_publish_maven.py @@ -180,6 +180,20 @@ def test_a_real_run_uploads_with_a_signing_release_build(self) -> None: self.assertEqual(count, 1) self.assertEqual(run.call_args.args[0], ["mvn", "-B", "-Prelease", "deploy"]) + def test_a_refused_upload_that_another_run_already_published_is_skipped(self) -> None: + answers = iter([False, True]) # not on Central before the upload, on Central after the refusal + with patch.object(script, "run", side_effect=script.subprocess.CalledProcessError(1, ["mvn"])), patch.object( + script, "already_published", side_effect=lambda coordinate: next(answers) + ): + count = script.publish(self.root, select_targets(self.catalog, "addon:java"), True) + self.assertEqual(count, 0) + + def test_a_refused_upload_points_to_the_portal_deployments(self) -> None: + with patch.object(script, "run", side_effect=script.subprocess.CalledProcessError(1, ["mvn"])), patch.object( + script, "already_published", return_value=False + ), self.assertRaisesRegex(ValueError, "refused .*addon.*may still be publishing"): + script.publish(self.root, select_targets(self.catalog, "addon:java"), True) + def test_a_package_is_not_uploaded_before_what_it_depends_on_is_on_central(self) -> None: # The upload is released by hand, so in one run the dependency is uploaded but not yet on Central. with patch.object(script, "run") as run, patch.object( diff --git a/tooling/extension-bindings/ci/test_publish_npm.py b/tooling/extension-bindings/ci/test_publish_npm.py index bbafb53..14eaacb 100644 --- a/tooling/extension-bindings/ci/test_publish_npm.py +++ b/tooling/extension-bindings/ci/test_publish_npm.py @@ -219,6 +219,41 @@ def run(command, cwd, **options): ): script.publish(self.root, self.targets, True) + def test_a_version_another_run_published_meanwhile_is_skipped(self) -> None: + def run(command, cwd, **options): + if command[:2] == ["npm", "publish"] and str(cwd).endswith("@example/addon"): + raise script.subprocess.CalledProcessError(1, command) + return SimpleNamespace(stdout="11.15.0\n") + + # Not on npm when the run looked, there when npm refused the upload. + answers = {"@example/addon": iter([False, True]), "@example/owner": iter([False])} + summaries = [] + with patch.object(script, "run", side_effect=run) as runner, patch.object( + script, "already_published", side_effect=lambda name, version: next(answers[name]) + ), patch.object(script, "npm_status", return_value="published"), patch.object( + script, "summarize", side_effect=summaries.append + ): + script.publish(self.root, self.targets, True) + self.assertIn("@example/addon@0.1.0 was published by another run meanwhile; skipped.", summaries) + publishes = [call for call in runner.call_args_list if call.args[0][:2] == ["npm", "publish"]] + self.assertEqual(len(publishes), 2, "the next package is still published") + + def test_a_first_release_staged_by_another_run_meanwhile_is_skipped(self) -> None: + def run(command, cwd, **options): + if command[:3] == ["npm", "stage", "publish"]: + raise script.subprocess.CalledProcessError(1, command) + return SimpleNamespace(stdout="11.15.0\n") + + statuses = {"@example/addon": iter(["missing", "staged"]), "@example/owner": iter(["published"])} + summaries = [] + with patch.object(script, "run", side_effect=run), patch.object( + script, "already_published", return_value=False + ), patch.object(script, "npm_status", side_effect=lambda name: next(statuses[name])), patch.object( + script, "summarize", side_effect=summaries.append + ), patch.dict("os.environ", {"NPM_STAGE_TOKEN": "stage-token"}): + script.publish(self.root, self.targets, True) + self.assertIn("@example/addon was staged or published by another run meanwhile; skipped.", summaries) + def test_npm_status_reads_the_registry(self) -> None: def view(stdout="", stderr="", code=0): return SimpleNamespace(returncode=code, stdout=stdout, stderr=stderr) diff --git a/tooling/extension-bindings/ci/test_publish_setup.py b/tooling/extension-bindings/ci/test_publish_setup.py index 6ed9e52..1e265d5 100644 --- a/tooling/extension-bindings/ci/test_publish_setup.py +++ b/tooling/extension-bindings/ci/test_publish_setup.py @@ -4,6 +4,7 @@ import json import unittest +import unittest.mock import publish_setup as script from publish_setup import Package @@ -72,6 +73,61 @@ def test_an_existing_project_already_has_its_publisher(self) -> None: self.assertEqual(self.state(["0.1.0", "0.2.0"]), script.PUBLISHED) +class FetchTests(unittest.TestCase): + def test_throttling_and_network_failures_can_be_retried_and_missing_is_none(self) -> None: + def http(code: int): + return script.urllib.error.HTTPError("https://example.invalid", code, "", None, None) + + for failure in (http(429), http(503), script.urllib.error.URLError("timed out")): + with self.subTest(failure=failure), unittest.mock.patch.object( + script.urllib.request, "urlopen", side_effect=failure + ), self.assertRaises(script.Throttled): + script.fetch("https://example.invalid") + with unittest.mock.patch.object(script.urllib.request, "urlopen", side_effect=http(404)): + self.assertIsNone(script.fetch("https://example.invalid")) + with unittest.mock.patch.object(script.urllib.request, "urlopen", side_effect=http(403)), \ + self.assertRaises(script.urllib.error.HTTPError) as raised: + script.fetch("https://example.invalid") + self.assertNotIsInstance(raised.exception, script.Throttled) + + +class GatherTests(unittest.TestCase): + def run_rounds(self, fails: dict[int, int]) -> tuple[list[int], list[int]]: + """fails maps an item to how many times it is throttled before it works.""" + left = dict(fails) + workers_seen = [] + real_pool = script.ThreadPoolExecutor + + def pool(workers): + workers_seen.append(workers) + return real_pool(workers) + + def work(item: int) -> int: + if left.get(item, 0) > 0: + left[item] -= 1 + raise script.Throttled(f"item {item}") + return item * 10 + + with unittest.mock.patch.object(script, "ThreadPoolExecutor", side_effect=pool), \ + unittest.mock.patch.object(script.time, "sleep"): + results = script.gather(list(range(20)), work) + return results, workers_seen + + def test_all_at_16_when_nothing_is_throttled(self) -> None: + results, rounds = self.run_rounds({}) + self.assertEqual(results, [item * 10 for item in range(20)]) + self.assertEqual(rounds, [16]) + + def test_throttled_items_go_again_8_at_a_time_then_one_by_one(self) -> None: + results, rounds = self.run_rounds({3: 1, 7: 2}) + self.assertEqual(results, [item * 10 for item in range(20)]) + self.assertEqual(rounds, [16, 8, 1]) + + def test_it_gives_up_after_the_one_by_one_round(self) -> None: + with self.assertRaisesRegex(script.Throttled, "item 5"): + self.run_rounds({5: 3}) + + class CardTests(unittest.TestCase): def test_one_package_gets_one_trust_command_and_several_get_a_loop(self) -> None: one = script.trust_command(["@example/a"])