Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 40 additions & 9 deletions tooling/extension-bindings/ci/publish_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import subprocess
import sys
import time
import urllib.error
import urllib.request
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
Expand Down Expand Up @@ -266,6 +267,11 @@ def report(findings: list[Finding], execute: bool) -> str:
return "\n".join(lines)


# GitHub's API sometimes answers 502 or 503 for a moment.
GITHUB_ATTEMPTS = 4
GITHUB_RETRY_SECONDS = 10


class GitHub:
"""The few Actions REST calls dispatch needs, authenticated with the job's token."""

Expand All @@ -279,9 +285,19 @@ def request(self, method: str, path: str, body: dict | None = None) -> dict:
headers={"Authorization": f"Bearer {self.token}", "Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28", "Content-Type": "application/json"},
)
with urllib.request.urlopen(request, timeout=60) as response:
payload = response.read()
return json.loads(payload) if payload else {}
# A read is asked again when GitHub fails for a moment. A dispatch is not, because asking twice could start
# two runs; dispatch() checks for its run before it asks again.
attempts = GITHUB_ATTEMPTS if method == "GET" else 1
for attempt in range(1, attempts + 1):
try:
with urllib.request.urlopen(request, timeout=60) as response:
payload = response.read()
return json.loads(payload) if payload else {}
except urllib.error.HTTPError as error:
if error.code not in publish_setup.RETRY_CODES or attempt == attempts:
raise
time.sleep(GITHUB_RETRY_SECONDS * attempt)
raise AssertionError("unreachable")


def dispatch(
Expand All @@ -291,18 +307,33 @@ def dispatch(
) -> dict:
"""Start a workflow_dispatch run and wait for it to finish. Returns the finished run."""
started = now() - timedelta(seconds=5)
github.request("POST", f"actions/workflows/{workflow}/dispatches", {"ref": ref, "inputs": inputs})
deadline = now() + timedelta(seconds=timeout)
run = None
while run is None:

def started_run() -> dict | None:
listing = github.request("GET", f"actions/workflows/{workflow}/runs?event=workflow_dispatch&branch={ref}&per_page=20")
mine = [
item for item in listing.get("workflow_runs", [])
if datetime.fromisoformat(item["created_at"].replace("Z", "+00:00")) >= started
and item.get("triggering_actor", {}).get("login") == "github-actions[bot]"
]
if mine:
run = min(mine, key=lambda item: item["created_at"])
return min(mine, key=lambda item: item["created_at"]) if mine else None

run = None
for attempt in range(1, GITHUB_ATTEMPTS + 1):
try:
github.request("POST", f"actions/workflows/{workflow}/dispatches", {"ref": ref, "inputs": inputs})
break
except urllib.error.HTTPError as error:
if error.code not in publish_setup.RETRY_CODES or attempt == GITHUB_ATTEMPTS:
raise
# A failed answer can still have started the run; only ask again when it did not.
sleep(GITHUB_RETRY_SECONDS * attempt)
if run := started_run():
break
print(f"{workflow}: GitHub answered HTTP {error.code}; asking again.", flush=True)
deadline = now() + timedelta(seconds=timeout)
while run is None:
run = started_run()
if run:
break
if now() > deadline:
raise TimeoutError(f"{workflow} did not start a run")
Expand Down
72 changes: 72 additions & 0 deletions tooling/extension-bindings/ci/test_publish_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
import unittest.mock

import yaml

Expand Down Expand Up @@ -180,6 +181,77 @@ def test_a_run_that_never_starts_times_out(self) -> None:
now=lambda: next(clock), sleep=lambda _: None)


def bad_gateway(self) -> Exception:
return script.urllib.error.HTTPError("https://api.github.invalid", 502, "Bad Gateway", None, None)

def test_a_dispatch_that_github_failed_is_asked_again(self) -> None:
start = datetime(2026, 12, 2, 15, 0, tzinfo=timezone.utc)
clock = iter(start + timedelta(seconds=step) for step in range(100))
bot = {"login": "github-actions[bot]"}
mine = {"id": 7, "created_at": "2026-12-02T15:00:30Z", "triggering_actor": bot, "status": "completed",
"conclusion": "success", "html_url": "mine"}
posts = []

class Flaky(FakeGitHub):
def request(inner, method, path, body=None):
if method == "POST":
posts.append(path)
if len(posts) == 1:
raise self.bad_gateway()
inner.runs = [mine]
return super().request(method, path, body)

run = script.dispatch(Flaky([], []), "binding-promote.yml", "main", {}, timeout=3600,
now=lambda: next(clock), sleep=lambda _: None)
self.assertEqual(run["id"], 7)
self.assertEqual(len(posts), 2)

def test_a_dispatch_that_started_despite_the_error_is_not_sent_twice(self) -> None:
start = datetime(2026, 12, 2, 15, 0, tzinfo=timezone.utc)
clock = iter(start + timedelta(seconds=step) for step in range(100))
mine = {"id": 8, "created_at": "2026-12-02T15:00:02Z", "triggering_actor": {"login": "github-actions[bot]"},
"status": "completed", "conclusion": "success", "html_url": "mine"}
posts = []

class StartedAnyway(FakeGitHub):
def request(inner, method, path, body=None):
if method == "POST":
posts.append(path)
inner.runs = [mine] # GitHub started the run, then answered 502
raise self.bad_gateway()
return super().request(method, path, body)

run = script.dispatch(StartedAnyway([], []), "binding-publish-pypi.yml", "main", {}, timeout=3600,
now=lambda: next(clock), sleep=lambda _: None)
self.assertEqual(run["id"], 8)
self.assertEqual(len(posts), 1)

def test_reads_are_asked_again_and_dispatches_are_not(self) -> None:
answer = unittest.mock.MagicMock()
answer.__enter__.return_value.read.return_value = b'{"ok": true}'
github = script.GitHub("example/repo", "token")
with unittest.mock.patch.object(script.urllib.request, "urlopen",
side_effect=[self.bad_gateway(), answer]), \
unittest.mock.patch.object(script.time, "sleep"):
self.assertEqual(github.request("GET", "actions/runs/1"), {"ok": True})
with unittest.mock.patch.object(script.urllib.request, "urlopen", side_effect=[self.bad_gateway()]), \
self.assertRaises(script.urllib.error.HTTPError):
github.request("POST", "actions/workflows/x.yml/dispatches", {})

def test_other_dispatch_errors_stop_at_once(self) -> None:
refused = script.urllib.error.HTTPError("https://api.github.invalid", 422, "Unprocessable", None, None)

class Refusing(FakeGitHub):
def request(inner, method, path, body=None):
if method == "POST":
raise refused
return super().request(method, path, body)

with self.assertRaises(script.urllib.error.HTTPError):
script.dispatch(Refusing([], []), "binding-promote.yml", "main", {}, timeout=60,
now=lambda: datetime(2026, 12, 2, tzinfo=timezone.utc), sleep=lambda _: None)


class SetupCardTests(unittest.TestCase):
def finding(self, key: str, language: str, coordinate: str, status: str) -> script.Finding:
return script.Finding(script.Package(key, language, coordinate, "0.2.0"), status)
Expand Down