From cdc2559d15001400f810dce03c32aec7bb2a1619 Mon Sep 17 00:00:00 2001 From: Daniel Polito Date: Sun, 15 Nov 2026 17:54:43 -0300 Subject: [PATCH 1/5] Reduce registry reads and recover publication from tested artifacts --- .github/workflows/ci-cd.yml | 4 +- .github/workflows/resume-publication.yml | 70 +++++++++++++++ README.md | 10 ++- tasks/recover.py | 76 ++++++++++++++++ tasks/release.py | 25 ++---- tasks/test_recover.py | 105 +++++++++++++++++++++++ tasks/test_release.py | 58 +++++++++---- tasks/test_release_registry.py | 26 +++++- 8 files changed, 331 insertions(+), 43 deletions(-) create mode 100644 .github/workflows/resume-publication.yml create mode 100644 tasks/recover.py create mode 100644 tasks/test_recover.py diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index 933dc59..01f4aee 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -27,7 +27,7 @@ jobs: - uses: actions/checkout@v4 - uses: docker/setup-buildx-action@v3 - name: Test release metadata and publication guards - run: python3 -m unittest discover -s tasks -p 'test_release.py' -v + run: python3 -m unittest discover -s tasks -p 'test_*.py' -v - name: Test manifest promotion against a local registry run: python3 tasks/test_release_registry.py - name: Install actionlint @@ -141,6 +141,8 @@ jobs: steps: - uses: actions/checkout@v4 - uses: docker/setup-buildx-action@v3 + with: + driver: docker - uses: actions/download-artifact@v8.0.2 with: pattern: swoole-${{ github.run_id }}-${{ github.run_attempt }}-* diff --git a/.github/workflows/resume-publication.yml b/.github/workflows/resume-publication.yml new file mode 100644 index 0000000..614511b --- /dev/null +++ b/.github/workflows/resume-publication.yml @@ -0,0 +1,70 @@ +name: Resume publication + +on: + workflow_dispatch: + inputs: + source_run: + description: Latest CI/CD run with every native build/test/staging job successful + required: true + type: string + source_attempt: + description: Completed attempt containing the complete release metadata + required: true + type: string + +permissions: + contents: read + actions: read + +concurrency: + group: CI/CD-${{ github.ref }} + cancel-in-progress: false + +jobs: + publish: + if: github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - name: Authorize the complete source attempt + env: + GH_TOKEN: ${{ github.token }} + SOURCE_RUN: ${{ inputs.source_run }} + SOURCE_ATTEMPT: ${{ inputs.source_attempt }} + run: python3 tasks/recover.py "$SOURCE_RUN" "$SOURCE_ATTEMPT" + - uses: actions/download-artifact@v8.0.2 + with: + github-token: ${{ github.token }} + run-id: ${{ env.SOURCE_RUN_ID }} + pattern: swoole-${{ env.SOURCE_RUN_ID }}-${{ env.SOURCE_RUN_ATTEMPT }}-* + path: release-metadata + - uses: docker/setup-buildx-action@v3 + with: + driver: docker + - uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + - name: Republish all manifests from tested digests (no builds or staging) + run: | + GITHUB_RUN_ID="$SOURCE_RUN_ID" GITHUB_RUN_ATTEMPT="$SOURCE_RUN_ATTEMPT" python3 tasks/release.py promote release-metadata + + dispatch: + needs: publish + if: github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Check downstream credentials + env: + DISPATCH_TOKEN: ${{ secrets.DISPATCH_TOKEN || secrets.WORKFLOW_TOKEN }} + run: | + if [ -z "$DISPATCH_TOKEN" ]; then + echo "::error::Configure DISPATCH_TOKEN or WORKFLOW_TOKEN for OCI8 dispatch." + exit 1 + fi + - uses: peter-evans/repository-dispatch@v4 + with: + token: ${{ secrets.DISPATCH_TOKEN || secrets.WORKFLOW_TOKEN }} + repository: kool-dev/docker-php-oci8 + event-type: docker-php-swoole-updated diff --git a/README.md b/README.md index 1283d2b..b142c62 100644 --- a/README.md +++ b/README.md @@ -56,13 +56,17 @@ PHP's scheduled rebuild sends `docker-php-updated` after publication to start a The 24 native jobs use `ubuntu-24.04` for amd64 and `ubuntu-24.04-arm` for arm64. Each builds and tests a base/NGINX pair through a job-local registry; NGINX consumes that same job's fresh base. After all tests in a job pass, trusted main-branch runs retag those exact tested daemon images (without rebuilding) to `kooldev/php:ci-swoole-RUN_ID-RUN_ATTEMPT-VARIANT-ARCH`. PRs, forks, and manual feature-branch runs never log in, stage, publish, or notify OCI8. -A single manifest-only job requires every native job and the workflow checks to succeed. It validates all 24 stable tags × both architectures, run/attempt scope, repository, unique tag/platform entries, digest format, and every remote digest's platform before updating any stable tag. Stable manifests reference the recorded immutable Docker Hub digests, never staging tag lookups or rebuilt images. Metadata artifacts are retained for seven days. There is no cross-tag transaction: a registry failure during promotion can still leave a partially updated release. +A single manifest-only job requires every native job and the workflow checks to succeed. It validates all 24 stable tags × both architectures, run/attempt scope, repository, unique tag/platform entries, digest format, tested image ID and Linux OS before updating any stable tag. Staging verifies each local tested image's platform and records Docker's push digest directly. Publication trusts those artifacts rather than re-reading 48 remote manifests/configs; staging also avoids 48 post-push inspections. Stable manifests reference the recorded immutable Docker Hub digests, never staging tag lookups or rebuilt images. Metadata artifacts are retained for seven days. There is no cross-tag transaction: a registry failure during promotion can still leave a partially updated release. -Recovery requires **Re-run all jobs**, not just failed jobs: artifacts and staging tags are scoped to the current run ID **and attempt**, and incomplete attempts fail closed. A new manual main-branch workflow run also rebuilds/tests the complete release. Do not combine artifacts from previous attempts. +If all native build/test/staging jobs succeeded and only publication or dispatch needs retrying, use **Resume publication** on `main`, supplying the CI/CD `source_run` ID and completed `source_attempt`. It downloads only that attempt's complete metadata and republishes all 24 manifests without rebuilding or staging again. The source must be the latest trusted CI/CD run and latest completed attempt at the current default-branch commit. Failed/missing native jobs, expired metadata, or stale commits require a fresh complete CI/CD run. Older metadata without the tested-platform fields is not accepted. + +Recovery shares CI/CD's release lock; OCI8 is notified only after all manifests succeed. Repeating recovery can repeat that notification. For normal CI/CD reruns, still choose **Re-run all jobs**, not just failed jobs: incomplete current attempts fail closed. Never combine metadata from different attempts. + +Manifest assembly still reads Docker Hub and consumes pull allowance. Resume only once quota is available; these changes reduce requests, not eliminate limits. Publication uses the existing Docker driver rather than booting another BuildKit container. Staging tags accumulate until separately cleaned up. Receiver push and PHP dispatch triggers are preserved; avoid scheduling a standalone receiver release immediately before a PHP parent release when possible. Only after all 24 stable manifests succeed, one bounded notification sends `docker-php-swoole-updated` to `kool-dev/docker-php-oci8`, allowing its Swoole-derived variants to rebuild after their parents. OCI8 must listen for this event and serialize its own releases; this chain does not trigger PHP again. -The notification uses `DISPATCH_TOKEN`, falling back to `WORKFLOW_TOKEN`. The selected credential must permit repository dispatch to OCI8; secret presence alone does not verify access. Missing credentials or failed dispatches fail the notification job visibly, without undoing published images. The job summary distinguishes publication from notification; an accepted dispatch does not prove OCI8 completed. Investigate and retry a failed notification with a manual workflow run; there is no independent downstream schedule to mask a broken chain. This is not an atomic release or digest-pinned parent chain. +The notification uses `DISPATCH_TOKEN`, falling back to `WORKFLOW_TOKEN`. The selected credential must permit repository dispatch to OCI8; secret presence alone does not verify access. Missing credentials or failed dispatches fail the notification job visibly, without undoing published images. The CI/CD job summary distinguishes publication from notification; an accepted dispatch does not prove OCI8 completed. Investigate and use Resume publication for an eligible source, or a fresh full run otherwise; there is no independent downstream schedule to mask a broken chain. This is not an atomic release or digest-pinned parent chain. Release logic has offline coverage via `python3 -m unittest discover -s tasks -p 'test_release.py' -v`; CI also runs actionlint and `python3 tasks/test_release_registry.py` against a disposable local registry. The latter stages tiny scratch fixtures and verifies all 24 two-platform manifests without touching Docker Hub (set `RELEASE_TEST_REGISTRY=localhost:PORT` to use another local port). It does not execute ARM code. Native amd64/arm64 image tests remain required to validate the actual runtime images. diff --git a/tasks/recover.py b/tasks/recover.py new file mode 100644 index 0000000..41b6726 --- /dev/null +++ b/tasks/recover.py @@ -0,0 +1,76 @@ +"""Authorize reusing one complete, latest trusted CI attempt without rebuilding.""" + +import json +import os +import re +import subprocess +import sys + +REPOSITORY = "kool-dev/docker-php-swoole" +BRANCH = "main" +BUILD_PREFIX = "build (" +BUILD_COUNT = 24 +CHECK_JOB = "workflow-tests" +EVENTS = {"push", "workflow_dispatch", "repository_dispatch"} + + +def api(path): + return json.loads(subprocess.check_output(["gh", "api", path], text=True)) + + +def validate(run_id, attempt): + if (os.environ.get("GITHUB_REPOSITORY") != REPOSITORY + or os.environ.get("GITHUB_REF") != f"refs/heads/{BRANCH}" + or os.environ.get("GITHUB_EVENT_NAME") != "workflow_dispatch" + or not all(re.fullmatch(r"[1-9][0-9]*", s) for s in (run_id, attempt))): + raise ValueError("Recovery requires a trusted default-branch manual run and numeric scope") + root = f"repos/{REPOSITORY}" + workflow = api(f"{root}/actions/workflows/ci-cd.yml") + source = api(f"{root}/actions/runs/{run_id}") + head = api(f"{root}/branches/{BRANCH}")["commit"]["sha"] + if (source["workflow_id"] != workflow["id"] + or source["event"] not in EVENTS + or source["head_branch"] != BRANCH + or source["head_repository"]["full_name"] != REPOSITORY + or source["head_sha"] != head or head != os.environ["GITHUB_SHA"] + or source["run_attempt"] != int(attempt) + or source["status"] != "completed"): + raise ValueError("Source must be the completed latest attempt at the current default-branch HEAD") + # A rerun keeps its ID/creation time. Compare attempt start times, not IDs. + trusted = [] + page = 1 + while True: + batch = api(f"{root}/actions/workflows/ci-cd.yml/runs?branch={BRANCH}&per_page=100&page={page}")["workflow_runs"] + trusted.extend(r for r in batch if r["event"] in EVENTS and r["head_branch"] == BRANCH) + if len(batch) < 100: + break + page += 1 + latest = max(trusted, key=lambda r: (r["run_started_at"], r["id"]), default=None) + if (not latest or latest["id"] != int(run_id) + or latest["run_attempt"] != int(attempt) or latest["status"] != "completed"): + raise ValueError("A newer CI release exists; do not resume this source") + jobs = [] + page = 1 + while True: + batch = api(f"{root}/actions/runs/{run_id}/attempts/{attempt}/jobs?per_page=100&page={page}")["jobs"] + jobs.extend(batch) + if len(batch) < 100: + break + page += 1 + builds = [j for j in jobs if j["name"].startswith(BUILD_PREFIX)] + checks = [j for j in jobs if j["name"] == CHECK_JOB] + if (len(builds) != BUILD_COUNT or len({j["name"] for j in builds}) != BUILD_COUNT + or len(checks) != 1 + or any(j["conclusion"] != "success" for j in builds + checks)): + raise ValueError("Every native build/test/staging job and the checks must have succeeded") + return run_id, attempt + + +def main(): + run_id, attempt = validate(*sys.argv[1:]) + with open(os.environ["GITHUB_ENV"], "a") as env: + env.write(f"SOURCE_RUN_ID={run_id}\nSOURCE_RUN_ATTEMPT={attempt}\n") + + +if __name__ == "__main__": + main() diff --git a/tasks/release.py b/tasks/release.py index 135f720..5070409 100644 --- a/tasks/release.py +++ b/tasks/release.py @@ -55,15 +55,13 @@ def stage(version, kind, arch, directory): command("docker", "tag", image_id, target) if command("docker", "image", "inspect", "--format", "{{.Id}}", target) != image_id: raise ValueError("Staging tag is not the tested image") - command("docker", "push", "--quiet", target) - descriptor = json.loads(command("docker", "buildx", "imagetools", "inspect", - target, "--format", "{{json .Manifest}}")) - digest = descriptor["digest"] - if not isinstance(digest, str) or not DIGEST.fullmatch(digest): - raise ValueError(f"Invalid pushed digest: {digest}") + output = command("docker", "push", target) + digests = re.findall(r"\bdigest: (sha256:[0-9a-f]{64})\b", output) + if len(digests) != 1: + raise ValueError("Push did not report exactly one registry digest") records.append(dict(repository=REPOSITORY, run_id=run, run_attempt=attempt, tag=tag, arch=arch, staging_tag=staging, - digest=digest, image_id=image_id)) + digest=digests[0], image_id=image_id, os=image["Os"])) path = Path(directory) path.mkdir(parents=True, exist_ok=True) (path / f"{version}{kind}-{arch}.json").write_text(json.dumps(records) + "\n") @@ -78,11 +76,11 @@ def load_records(directory, run, attempt): for record in batch: if not isinstance(record, dict) or set(record) != { "repository", "run_id", "run_attempt", "tag", "arch", - "staging_tag", "digest", "image_id" + "staging_tag", "digest", "image_id", "os" }: raise ValueError("Malformed metadata") tag, arch = record["tag"], record["arch"] - if (record["repository"] != REPOSITORY + if (record["repository"] != REPOSITORY or record["os"] != "linux" or record["run_id"] != run or record["run_attempt"] != attempt or tag not in TAGS or arch not in ARCHES or record["staging_tag"] != staging_tag(run, attempt, tag, arch) @@ -103,13 +101,8 @@ def load_records(directory, run, attempt): def promote(directory): run, attempt = release_scope() records = load_records(directory, run, attempt) - # Resolve every immutable reference and platform before changing ANY stable tag. - for (tag, arch), record in records.items(): - reference = f"{REPOSITORY}@{record['digest']}" - image = json.loads(command("docker", "buildx", "imagetools", "inspect", - reference, "--format", "{{json .Image}}")) - if image["architecture"] != arch or image["os"] != "linux": - raise ValueError(f"Wrong platform for {tag}/{arch}") + # Staging already checked the tested local ID/OS/architecture and recorded + # Docker's push digest. Trust this run's artifacts, not another registry GET. for tag in TAGS: command("docker", "buildx", "imagetools", "create", "--tag", f"{REPOSITORY}:{tag}", diff --git a/tasks/test_recover.py b/tasks/test_recover.py new file mode 100644 index 0000000..93a34f1 --- /dev/null +++ b/tasks/test_recover.py @@ -0,0 +1,105 @@ +import copy +import os +from pathlib import Path +import unittest +from unittest.mock import patch + +import recover + + +class RecoveryTests(unittest.TestCase): + def setUp(self): + self.source = dict(id=123, workflow_id=7, event="push", + head_branch=recover.BRANCH, head_sha="abc", + head_repository=dict(full_name=recover.REPOSITORY), + run_attempt=2, status="completed", run_started_at="2026-11-15T11:00:00Z") + self.recent = [copy.deepcopy(self.source)] + self.jobs = [dict(name=f"{recover.BUILD_PREFIX}{i})", conclusion="success") + for i in range(recover.BUILD_COUNT)] + self.jobs.append(dict(name=recover.CHECK_JOB, conclusion="success")) + env = dict(GITHUB_REPOSITORY=recover.REPOSITORY, + GITHUB_REF=f"refs/heads/{recover.BRANCH}", + GITHUB_EVENT_NAME="workflow_dispatch", GITHUB_SHA="abc") + self.env = patch.dict(os.environ, env, clear=True) + self.env.start() + self.addCleanup(self.env.stop) + + def api(self, path): + if path.endswith("/actions/workflows/ci-cd.yml"): + return dict(id=7) + if "/branches/" in path: + return dict(commit=dict(sha="abc")) + if "/runs?" in path: + return dict(workflow_runs=self.recent) + if "/jobs?" in path: + return dict(jobs=self.jobs) + return self.source + + def test_latest_complete_source_accepted_even_if_publication_failed(self): + self.source["conclusion"] = "failure" + with patch.object(recover, "api", side_effect=self.api): + self.assertEqual(recover.validate("123", "2"), ("123", "2")) + + def test_untrusted_or_malformed_request_never_calls_api(self): + for env, run, attempt in [ + (dict(GITHUB_EVENT_NAME="pull_request"), "123", "2"), + (dict(GITHUB_REF="refs/heads/feature"), "123", "2"), + (dict(GITHUB_REPOSITORY="fork/repo"), "123", "2"), + ({}, "123\nOTHER=bad", "2"), ({}, "123", "0"), + ]: + with patch.dict(os.environ, env), patch.object(recover, "api") as api: + with self.assertRaises(ValueError): + recover.validate(run, attempt) + api.assert_not_called() + + def test_rejects_wrong_workflow_fork_branch_commit_event_attempt_and_active_run(self): + for field, value in [ + ("workflow_id", 8), ("head_branch", "feature"), ("head_sha", "old"), + ("head_repository", dict(full_name="fork/repo")), + ("event", "pull_request"), ("run_attempt", 3), ("status", "in_progress"), + ]: + with patch.dict(self.source, {field: value}), patch.object(recover, "api", side_effect=self.api): + with self.assertRaises(ValueError): + recover.validate("123", "2") + + def test_rejects_newer_release_even_at_same_commit(self): + self.recent.append(dict(self.source, id=124)) + with patch.object(recover, "api", side_effect=self.api): + with self.assertRaises(ValueError): + recover.validate("123", "2") + + def test_old_run_id_with_newer_attempt_is_newer_than_source(self): + self.recent.append(dict(self.source, id=122, run_started_at="2026-11-15T12:00:00Z")) + with patch.object(recover, "api", side_effect=self.api): + with self.assertRaises(ValueError): + recover.validate("123", "2") + + def test_rejects_incomplete_failed_or_duplicate_builds_and_missing_checks(self): + original = copy.deepcopy(self.jobs) + for jobs in [ + original[:-1], original[1:], original + [original[0]], + [dict(j, conclusion="failure") if i == 0 else j for i, j in enumerate(original)], + [dict(j, name=original[0]["name"]) if i == 1 else j for i, j in enumerate(original)], + ]: + self.jobs = jobs + with patch.object(recover, "api", side_effect=self.api): + with self.assertRaises(ValueError): + recover.validate("123", "2") + + def test_recovery_workflow_shares_release_lock_and_blocks_dispatch_on_failure(self): + text = (Path(__file__).resolve().parents[1] / + ".github/workflows/resume-publication.yml").read_text() + self.assertIn("group: CI/CD-${{ github.ref }}", text) + self.assertIn(f"github.ref == 'refs/heads/{recover.BRANCH}'", text) + self.assertIn(f"github.repository == '{recover.REPOSITORY}'", text) + self.assertIn("actions: read", text) + self.assertIn("run-id: ${{ env.SOURCE_RUN_ID }}", text) + self.assertLess(text.index("recover.py"), text.index("download-artifact@")) + self.assertLess(text.index("download-artifact@"), text.index("docker/login-action@")) + self.assertNotIn("build-push-action@", text) + self.assertNotIn("always()", text) + self.assertIn("needs: publish", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/tasks/test_release.py b/tasks/test_release.py index 0d3994e..4d1cef1 100644 --- a/tasks/test_release.py +++ b/tasks/test_release.py @@ -26,7 +26,7 @@ def setUp(self): self.addCleanup(env.stop) self.records = [ dict(repository=release.REPOSITORY, run_id="12345", run_attempt="2", - tag=tag, arch=arch, digest=f"sha256:{index:064x}", + tag=tag, arch=arch, os="linux", digest=f"sha256:{index:064x}", image_id=f"sha256:{index + 100:064x}", staging_tag=release.staging_tag("12345", "2", tag, arch)) for index, (tag, arch) in enumerate( @@ -48,7 +48,7 @@ def test_invalid_metadata_never_touches_registry(self): ("tag", "latest"), ("arch", "s390x"), ("staging_tag", "old-attempt"), ("digest", "sha256:bad"), ("digest", "sha256:" + "g" * 64), ("digest", "sha256:" + "a" * 64 + ";echo bad"), - ("digest", None), ("image_id", "bad"), + ("digest", None), ("image_id", "bad"), ("os", "windows"), ): records = copy.deepcopy(self.records) records[0][field] = value @@ -64,7 +64,7 @@ def test_invalid_metadata_never_touches_registry(self): release.promote(self.directory) command.assert_not_called() - def test_all_remote_platforms_preflight_before_manifest_updates(self): + def test_promotion_uses_validated_artifacts_without_remote_inspections(self): self.write() commands = [] platforms = {record["digest"]: record["arch"] for record in self.records} @@ -78,9 +78,8 @@ def docker(*args): with patch.object(release, "command", side_effect=docker): release.promote(self.directory) - self.assertEqual(len(commands), 72) - self.assertTrue(all(cmd[3] == "inspect" for cmd in commands[:48])) - for tag, cmd in zip(release.TAGS, commands[48:]): + self.assertEqual(len(commands), 24) + for tag, cmd in zip(release.TAGS, commands): self.assertEqual(cmd[:6], ("docker", "buildx", "imagetools", "create", "--tag", f"kooldev/php:{tag}")) self.assertEqual(cmd[6:], tuple( @@ -88,16 +87,14 @@ def docker(*args): if record["tag"] == tag)) self.assertFalse(any("build" in cmd or "pull" in cmd for cmd in commands)) - def test_last_bad_remote_platform_prevents_all_stable_updates(self): - self.write() - responses = [json.dumps(dict(os="linux", architecture=r["arch"])) - for r in self.records] - responses[-1] = '{"os":"linux","architecture":"amd64"}' - with patch.object(release, "command", side_effect=responses) as command: + def test_last_bad_record_prevents_all_stable_updates(self): + records = copy.deepcopy(self.records) + records[-1]["os"] = "windows" + self.write(records) + with patch.object(release, "command") as command: with self.assertRaises(ValueError): release.promote(self.directory) - self.assertEqual(command.call_count, 48) - self.assertTrue(all(call.args[3] == "inspect" for call in command.call_args_list)) + command.assert_not_called() def test_registry_failure_prevents_all_stable_updates(self): self.write() @@ -111,19 +108,19 @@ def test_stage_retags_tested_image_ids_without_pull_or_build(self): def docker(*args): commands.append(args) - image_id = image_ids[0 if len(commands) <= 5 else 1] + image_id = image_ids[0 if len(commands) <= 4 else 1] if args[:3] == ("docker", "image", "inspect"): if "--format" in args: return image_id return json.dumps([dict(Id=image_id, Architecture="amd64", Os="linux")]) - if "imagetools" in args: - return json.dumps(dict(digest="sha256:" + "c" * 64)) + if args[:2] == ("docker", "push"): + return "tag: digest: sha256:" + "c" * 64 + " size: 123" return "" with patch.object(release, "command", side_effect=docker): release.stage("8.5-swoole", "-prod", "amd64", self.directory) - self.assertEqual(len(commands), 10) - for offset, image_id in ((0, image_ids[0]), (5, image_ids[1])): + self.assertEqual(len(commands), 8) + for offset, image_id in ((0, image_ids[0]), (4, image_ids[1])): self.assertEqual(commands[offset + 1][:3], ("docker", "tag", image_id)) self.assertEqual(commands[offset + 2][-1], commands[offset + 1][-1]) self.assertEqual(commands[offset + 3][-1], commands[offset + 1][-1]) @@ -132,6 +129,17 @@ def docker(*args): self.assertTrue(all(record["staging_tag"].startswith("ci-swoole-12345-2-") for record in records)) self.assertFalse(any("build" in cmd or "pull" in cmd for cmd in commands)) + self.assertFalse(any("imagetools" in cmd for cmd in commands)) + + def test_ambiguous_or_missing_push_digest_never_writes_metadata(self): + image = dict(Id="sha256:" + "a" * 64, Architecture="amd64", Os="linux") + for output in ("no digest", "digest: sha256:" + "c" * 64 + "\ndigest: sha256:" + "d" * 64): + with patch.object(release, "command", side_effect=[ + json.dumps([image]), "", image["Id"], output + ]): + with self.assertRaises(ValueError): + release.stage("8.5-swoole", "", "amd64", self.directory) + self.assertEqual(list(self.directory.iterdir()), []) def test_retag_mismatch_prevents_push(self): image = dict(Id="sha256:" + "a" * 64, Architecture="amd64", Os="linux") @@ -142,6 +150,18 @@ def test_retag_mismatch_prevents_push(self): self.assertFalse(any(call.args[1] == "push" for call in command.call_args_list)) self.assertEqual(list(self.directory.iterdir()), []) + def test_wrong_local_platform_or_id_prevents_push(self): + for image in ( + dict(Id="bad", Architecture="amd64", Os="linux"), + dict(Id="sha256:" + "a" * 64, Architecture="arm64", Os="linux"), + dict(Id="sha256:" + "a" * 64, Architecture="amd64", Os="windows"), + ): + with patch.object(release, "command", return_value=json.dumps([image])) as command: + with self.assertRaises(ValueError): + release.stage("8.5-swoole", "", "amd64", self.directory) + self.assertEqual(command.call_count, 1) + self.assertEqual(list(self.directory.iterdir()), []) + def test_untrusted_events_cannot_stage_or_promote(self): for override in ( dict(GITHUB_EVENT_NAME="pull_request"), diff --git a/tasks/test_release_registry.py b/tasks/test_release_registry.py index 52036a7..3ebf8e8 100644 --- a/tasks/test_release_registry.py +++ b/tasks/test_release_registry.py @@ -60,20 +60,38 @@ def local_command(*args): assert all(record["image_id"] == ids["amd64"] for record in staged) assert all(record["digest"] == digests["amd64"] for record in staged) # Expand the two tiny native-config fixtures over the complete release - # shape. This tests real remote preflight and all stable manifest writes. + # shape. This tests all stable writes without redundant remote preflight. records = [ dict(repository=release.REPOSITORY, run_id="12345", run_attempt="2", - tag=tag, arch=arch, digest=digests[arch], image_id=ids[arch], + tag=tag, arch=arch, os="linux", digest=digests[arch], image_id=ids[arch], staging_tag=release.staging_tag("12345", "2", tag, arch)) for tag in release.TAGS for arch in release.ARCHES ] metadata = root / "metadata" metadata.mkdir() (metadata / "records.json").write_text(json.dumps(records)) + writes = [] + + def interrupted(*args): + if args[1:4] == ("buildx", "imagetools", "create"): + if writes: + raise RuntimeError("simulated registry outage") + writes.append(args) + return local_command(*args) + + with patch.object(release, "command", side_effect=interrupted): + try: + release.promote(metadata) + except RuntimeError as error: + assert str(error) == "simulated registry outage" + else: + raise AssertionError("Expected interrupted publication") + assert len(writes) == 1 + # Recovery retries the full immutable set without builds or staging. commands.clear() release.promote(metadata) - assert len(commands) == 72 - assert all(cmd[3] == "inspect" for cmd in commands[:48]) + assert len(commands) == 24 + assert all(cmd[3] == "create" for cmd in commands) for tag in release.TAGS: manifest = json.loads(original( "docker", "buildx", "imagetools", "inspect", From b9816d00858be8ad2c6cad10a0c7f222f38c511b Mon Sep 17 00:00:00 2001 From: Daniel Polito Date: Sun, 15 Nov 2026 18:09:17 -0300 Subject: [PATCH 2/5] Remove publication recovery and retain request reductions only --- .github/workflows/ci-cd.yml | 2 +- .github/workflows/resume-publication.yml | 70 --------------- README.md | 8 +- tasks/recover.py | 76 ---------------- tasks/test_recover.py | 105 ----------------------- tasks/test_release.py | 4 - tasks/test_release_registry.py | 18 ---- 7 files changed, 4 insertions(+), 279 deletions(-) delete mode 100644 .github/workflows/resume-publication.yml delete mode 100644 tasks/recover.py delete mode 100644 tasks/test_recover.py diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index 01f4aee..da436a0 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -27,7 +27,7 @@ jobs: - uses: actions/checkout@v4 - uses: docker/setup-buildx-action@v3 - name: Test release metadata and publication guards - run: python3 -m unittest discover -s tasks -p 'test_*.py' -v + run: python3 -m unittest discover -s tasks -p 'test_release.py' -v - name: Test manifest promotion against a local registry run: python3 tasks/test_release_registry.py - name: Install actionlint diff --git a/.github/workflows/resume-publication.yml b/.github/workflows/resume-publication.yml deleted file mode 100644 index 614511b..0000000 --- a/.github/workflows/resume-publication.yml +++ /dev/null @@ -1,70 +0,0 @@ -name: Resume publication - -on: - workflow_dispatch: - inputs: - source_run: - description: Latest CI/CD run with every native build/test/staging job successful - required: true - type: string - source_attempt: - description: Completed attempt containing the complete release metadata - required: true - type: string - -permissions: - contents: read - actions: read - -concurrency: - group: CI/CD-${{ github.ref }} - cancel-in-progress: false - -jobs: - publish: - if: github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' - runs-on: ubuntu-24.04 - steps: - - uses: actions/checkout@v4 - - name: Authorize the complete source attempt - env: - GH_TOKEN: ${{ github.token }} - SOURCE_RUN: ${{ inputs.source_run }} - SOURCE_ATTEMPT: ${{ inputs.source_attempt }} - run: python3 tasks/recover.py "$SOURCE_RUN" "$SOURCE_ATTEMPT" - - uses: actions/download-artifact@v8.0.2 - with: - github-token: ${{ github.token }} - run-id: ${{ env.SOURCE_RUN_ID }} - pattern: swoole-${{ env.SOURCE_RUN_ID }}-${{ env.SOURCE_RUN_ATTEMPT }}-* - path: release-metadata - - uses: docker/setup-buildx-action@v3 - with: - driver: docker - - uses: docker/login-action@v3 - with: - username: ${{ secrets.DOCKER_USERNAME }} - password: ${{ secrets.DOCKER_PASSWORD }} - - name: Republish all manifests from tested digests (no builds or staging) - run: | - GITHUB_RUN_ID="$SOURCE_RUN_ID" GITHUB_RUN_ATTEMPT="$SOURCE_RUN_ATTEMPT" python3 tasks/release.py promote release-metadata - - dispatch: - needs: publish - if: github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' - runs-on: ubuntu-24.04 - timeout-minutes: 5 - steps: - - name: Check downstream credentials - env: - DISPATCH_TOKEN: ${{ secrets.DISPATCH_TOKEN || secrets.WORKFLOW_TOKEN }} - run: | - if [ -z "$DISPATCH_TOKEN" ]; then - echo "::error::Configure DISPATCH_TOKEN or WORKFLOW_TOKEN for OCI8 dispatch." - exit 1 - fi - - uses: peter-evans/repository-dispatch@v4 - with: - token: ${{ secrets.DISPATCH_TOKEN || secrets.WORKFLOW_TOKEN }} - repository: kool-dev/docker-php-oci8 - event-type: docker-php-swoole-updated diff --git a/README.md b/README.md index b142c62..9c9a8da 100644 --- a/README.md +++ b/README.md @@ -58,15 +58,13 @@ The 24 native jobs use `ubuntu-24.04` for amd64 and `ubuntu-24.04-arm` for arm64 A single manifest-only job requires every native job and the workflow checks to succeed. It validates all 24 stable tags × both architectures, run/attempt scope, repository, unique tag/platform entries, digest format, tested image ID and Linux OS before updating any stable tag. Staging verifies each local tested image's platform and records Docker's push digest directly. Publication trusts those artifacts rather than re-reading 48 remote manifests/configs; staging also avoids 48 post-push inspections. Stable manifests reference the recorded immutable Docker Hub digests, never staging tag lookups or rebuilt images. Metadata artifacts are retained for seven days. There is no cross-tag transaction: a registry failure during promotion can still leave a partially updated release. -If all native build/test/staging jobs succeeded and only publication or dispatch needs retrying, use **Resume publication** on `main`, supplying the CI/CD `source_run` ID and completed `source_attempt`. It downloads only that attempt's complete metadata and republishes all 24 manifests without rebuilding or staging again. The source must be the latest trusted CI/CD run and latest completed attempt at the current default-branch commit. Failed/missing native jobs, expired metadata, or stale commits require a fresh complete CI/CD run. Older metadata without the tested-platform fields is not accepted. +Recovery requires **Re-run all jobs**, not just failed jobs: artifacts and staging tags are scoped to the current run ID **and attempt**, and incomplete attempts fail closed. A new manual main-branch workflow run also rebuilds/tests the complete release. Do not combine artifacts from previous attempts. -Recovery shares CI/CD's release lock; OCI8 is notified only after all manifests succeed. Repeating recovery can repeat that notification. For normal CI/CD reruns, still choose **Re-run all jobs**, not just failed jobs: incomplete current attempts fail closed. Never combine metadata from different attempts. - -Manifest assembly still reads Docker Hub and consumes pull allowance. Resume only once quota is available; these changes reduce requests, not eliminate limits. Publication uses the existing Docker driver rather than booting another BuildKit container. Staging tags accumulate until separately cleaned up. Receiver push and PHP dispatch triggers are preserved; avoid scheduling a standalone receiver release immediately before a PHP parent release when possible. +Manifest assembly still reads Docker Hub and consumes pull allowance; these changes reduce requests, not eliminate limits. Publication uses the existing Docker driver rather than booting another BuildKit container. Only after all 24 stable manifests succeed, one bounded notification sends `docker-php-swoole-updated` to `kool-dev/docker-php-oci8`, allowing its Swoole-derived variants to rebuild after their parents. OCI8 must listen for this event and serialize its own releases; this chain does not trigger PHP again. -The notification uses `DISPATCH_TOKEN`, falling back to `WORKFLOW_TOKEN`. The selected credential must permit repository dispatch to OCI8; secret presence alone does not verify access. Missing credentials or failed dispatches fail the notification job visibly, without undoing published images. The CI/CD job summary distinguishes publication from notification; an accepted dispatch does not prove OCI8 completed. Investigate and use Resume publication for an eligible source, or a fresh full run otherwise; there is no independent downstream schedule to mask a broken chain. This is not an atomic release or digest-pinned parent chain. +The notification uses `DISPATCH_TOKEN`, falling back to `WORKFLOW_TOKEN`. The selected credential must permit repository dispatch to OCI8; secret presence alone does not verify access. Missing credentials or failed dispatches fail the notification job visibly, without undoing published images. The job summary distinguishes publication from notification; an accepted dispatch does not prove OCI8 completed. Investigate and retry a failed notification with a manual workflow run; there is no independent downstream schedule to mask a broken chain. This is not an atomic release or digest-pinned parent chain. Release logic has offline coverage via `python3 -m unittest discover -s tasks -p 'test_release.py' -v`; CI also runs actionlint and `python3 tasks/test_release_registry.py` against a disposable local registry. The latter stages tiny scratch fixtures and verifies all 24 two-platform manifests without touching Docker Hub (set `RELEASE_TEST_REGISTRY=localhost:PORT` to use another local port). It does not execute ARM code. Native amd64/arm64 image tests remain required to validate the actual runtime images. diff --git a/tasks/recover.py b/tasks/recover.py deleted file mode 100644 index 41b6726..0000000 --- a/tasks/recover.py +++ /dev/null @@ -1,76 +0,0 @@ -"""Authorize reusing one complete, latest trusted CI attempt without rebuilding.""" - -import json -import os -import re -import subprocess -import sys - -REPOSITORY = "kool-dev/docker-php-swoole" -BRANCH = "main" -BUILD_PREFIX = "build (" -BUILD_COUNT = 24 -CHECK_JOB = "workflow-tests" -EVENTS = {"push", "workflow_dispatch", "repository_dispatch"} - - -def api(path): - return json.loads(subprocess.check_output(["gh", "api", path], text=True)) - - -def validate(run_id, attempt): - if (os.environ.get("GITHUB_REPOSITORY") != REPOSITORY - or os.environ.get("GITHUB_REF") != f"refs/heads/{BRANCH}" - or os.environ.get("GITHUB_EVENT_NAME") != "workflow_dispatch" - or not all(re.fullmatch(r"[1-9][0-9]*", s) for s in (run_id, attempt))): - raise ValueError("Recovery requires a trusted default-branch manual run and numeric scope") - root = f"repos/{REPOSITORY}" - workflow = api(f"{root}/actions/workflows/ci-cd.yml") - source = api(f"{root}/actions/runs/{run_id}") - head = api(f"{root}/branches/{BRANCH}")["commit"]["sha"] - if (source["workflow_id"] != workflow["id"] - or source["event"] not in EVENTS - or source["head_branch"] != BRANCH - or source["head_repository"]["full_name"] != REPOSITORY - or source["head_sha"] != head or head != os.environ["GITHUB_SHA"] - or source["run_attempt"] != int(attempt) - or source["status"] != "completed"): - raise ValueError("Source must be the completed latest attempt at the current default-branch HEAD") - # A rerun keeps its ID/creation time. Compare attempt start times, not IDs. - trusted = [] - page = 1 - while True: - batch = api(f"{root}/actions/workflows/ci-cd.yml/runs?branch={BRANCH}&per_page=100&page={page}")["workflow_runs"] - trusted.extend(r for r in batch if r["event"] in EVENTS and r["head_branch"] == BRANCH) - if len(batch) < 100: - break - page += 1 - latest = max(trusted, key=lambda r: (r["run_started_at"], r["id"]), default=None) - if (not latest or latest["id"] != int(run_id) - or latest["run_attempt"] != int(attempt) or latest["status"] != "completed"): - raise ValueError("A newer CI release exists; do not resume this source") - jobs = [] - page = 1 - while True: - batch = api(f"{root}/actions/runs/{run_id}/attempts/{attempt}/jobs?per_page=100&page={page}")["jobs"] - jobs.extend(batch) - if len(batch) < 100: - break - page += 1 - builds = [j for j in jobs if j["name"].startswith(BUILD_PREFIX)] - checks = [j for j in jobs if j["name"] == CHECK_JOB] - if (len(builds) != BUILD_COUNT or len({j["name"] for j in builds}) != BUILD_COUNT - or len(checks) != 1 - or any(j["conclusion"] != "success" for j in builds + checks)): - raise ValueError("Every native build/test/staging job and the checks must have succeeded") - return run_id, attempt - - -def main(): - run_id, attempt = validate(*sys.argv[1:]) - with open(os.environ["GITHUB_ENV"], "a") as env: - env.write(f"SOURCE_RUN_ID={run_id}\nSOURCE_RUN_ATTEMPT={attempt}\n") - - -if __name__ == "__main__": - main() diff --git a/tasks/test_recover.py b/tasks/test_recover.py deleted file mode 100644 index 93a34f1..0000000 --- a/tasks/test_recover.py +++ /dev/null @@ -1,105 +0,0 @@ -import copy -import os -from pathlib import Path -import unittest -from unittest.mock import patch - -import recover - - -class RecoveryTests(unittest.TestCase): - def setUp(self): - self.source = dict(id=123, workflow_id=7, event="push", - head_branch=recover.BRANCH, head_sha="abc", - head_repository=dict(full_name=recover.REPOSITORY), - run_attempt=2, status="completed", run_started_at="2026-11-15T11:00:00Z") - self.recent = [copy.deepcopy(self.source)] - self.jobs = [dict(name=f"{recover.BUILD_PREFIX}{i})", conclusion="success") - for i in range(recover.BUILD_COUNT)] - self.jobs.append(dict(name=recover.CHECK_JOB, conclusion="success")) - env = dict(GITHUB_REPOSITORY=recover.REPOSITORY, - GITHUB_REF=f"refs/heads/{recover.BRANCH}", - GITHUB_EVENT_NAME="workflow_dispatch", GITHUB_SHA="abc") - self.env = patch.dict(os.environ, env, clear=True) - self.env.start() - self.addCleanup(self.env.stop) - - def api(self, path): - if path.endswith("/actions/workflows/ci-cd.yml"): - return dict(id=7) - if "/branches/" in path: - return dict(commit=dict(sha="abc")) - if "/runs?" in path: - return dict(workflow_runs=self.recent) - if "/jobs?" in path: - return dict(jobs=self.jobs) - return self.source - - def test_latest_complete_source_accepted_even_if_publication_failed(self): - self.source["conclusion"] = "failure" - with patch.object(recover, "api", side_effect=self.api): - self.assertEqual(recover.validate("123", "2"), ("123", "2")) - - def test_untrusted_or_malformed_request_never_calls_api(self): - for env, run, attempt in [ - (dict(GITHUB_EVENT_NAME="pull_request"), "123", "2"), - (dict(GITHUB_REF="refs/heads/feature"), "123", "2"), - (dict(GITHUB_REPOSITORY="fork/repo"), "123", "2"), - ({}, "123\nOTHER=bad", "2"), ({}, "123", "0"), - ]: - with patch.dict(os.environ, env), patch.object(recover, "api") as api: - with self.assertRaises(ValueError): - recover.validate(run, attempt) - api.assert_not_called() - - def test_rejects_wrong_workflow_fork_branch_commit_event_attempt_and_active_run(self): - for field, value in [ - ("workflow_id", 8), ("head_branch", "feature"), ("head_sha", "old"), - ("head_repository", dict(full_name="fork/repo")), - ("event", "pull_request"), ("run_attempt", 3), ("status", "in_progress"), - ]: - with patch.dict(self.source, {field: value}), patch.object(recover, "api", side_effect=self.api): - with self.assertRaises(ValueError): - recover.validate("123", "2") - - def test_rejects_newer_release_even_at_same_commit(self): - self.recent.append(dict(self.source, id=124)) - with patch.object(recover, "api", side_effect=self.api): - with self.assertRaises(ValueError): - recover.validate("123", "2") - - def test_old_run_id_with_newer_attempt_is_newer_than_source(self): - self.recent.append(dict(self.source, id=122, run_started_at="2026-11-15T12:00:00Z")) - with patch.object(recover, "api", side_effect=self.api): - with self.assertRaises(ValueError): - recover.validate("123", "2") - - def test_rejects_incomplete_failed_or_duplicate_builds_and_missing_checks(self): - original = copy.deepcopy(self.jobs) - for jobs in [ - original[:-1], original[1:], original + [original[0]], - [dict(j, conclusion="failure") if i == 0 else j for i, j in enumerate(original)], - [dict(j, name=original[0]["name"]) if i == 1 else j for i, j in enumerate(original)], - ]: - self.jobs = jobs - with patch.object(recover, "api", side_effect=self.api): - with self.assertRaises(ValueError): - recover.validate("123", "2") - - def test_recovery_workflow_shares_release_lock_and_blocks_dispatch_on_failure(self): - text = (Path(__file__).resolve().parents[1] / - ".github/workflows/resume-publication.yml").read_text() - self.assertIn("group: CI/CD-${{ github.ref }}", text) - self.assertIn(f"github.ref == 'refs/heads/{recover.BRANCH}'", text) - self.assertIn(f"github.repository == '{recover.REPOSITORY}'", text) - self.assertIn("actions: read", text) - self.assertIn("run-id: ${{ env.SOURCE_RUN_ID }}", text) - self.assertLess(text.index("recover.py"), text.index("download-artifact@")) - self.assertLess(text.index("download-artifact@"), text.index("docker/login-action@")) - self.assertNotIn("build-push-action@", text) - self.assertNotIn("always()", text) - self.assertIn("needs: publish", text) - - -if __name__ == "__main__": - unittest.main() diff --git a/tasks/test_release.py b/tasks/test_release.py index 4d1cef1..45a5576 100644 --- a/tasks/test_release.py +++ b/tasks/test_release.py @@ -67,13 +67,9 @@ def test_invalid_metadata_never_touches_registry(self): def test_promotion_uses_validated_artifacts_without_remote_inspections(self): self.write() commands = [] - platforms = {record["digest"]: record["arch"] for record in self.records} def docker(*args): commands.append(args) - if "inspect" in args: - digest = args[4].split("@")[1] - return json.dumps(dict(os="linux", architecture=platforms[digest])) return "" with patch.object(release, "command", side_effect=docker): diff --git a/tasks/test_release_registry.py b/tasks/test_release_registry.py index 3ebf8e8..b31758b 100644 --- a/tasks/test_release_registry.py +++ b/tasks/test_release_registry.py @@ -70,24 +70,6 @@ def local_command(*args): metadata = root / "metadata" metadata.mkdir() (metadata / "records.json").write_text(json.dumps(records)) - writes = [] - - def interrupted(*args): - if args[1:4] == ("buildx", "imagetools", "create"): - if writes: - raise RuntimeError("simulated registry outage") - writes.append(args) - return local_command(*args) - - with patch.object(release, "command", side_effect=interrupted): - try: - release.promote(metadata) - except RuntimeError as error: - assert str(error) == "simulated registry outage" - else: - raise AssertionError("Expected interrupted publication") - assert len(writes) == 1 - # Recovery retries the full immutable set without builds or staging. commands.clear() release.promote(metadata) assert len(commands) == 24 From 490228c2f29bbb9692af347bc0703ed9669bde69 Mon Sep 17 00:00:00 2001 From: Daniel Polito Date: Sun, 15 Nov 2026 18:55:55 -0300 Subject: [PATCH 3/5] Use shared Bash native-image CI from kool --- .github/workflows/ci-cd.yml | 244 +++++++++++++-------------------- README.md | 6 +- tasks/release.py | 118 ---------------- tasks/test_release.py | 211 ---------------------------- tasks/test_release_registry.py | 88 ------------ 5 files changed, 97 insertions(+), 570 deletions(-) delete mode 100644 tasks/release.py delete mode 100644 tasks/test_release.py delete mode 100644 tasks/test_release_registry.py diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index da436a0..d06cfd9 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -1,5 +1,4 @@ name: CI/CD - on: push: branches: [main] @@ -7,186 +6,131 @@ on: pull_request: repository_dispatch: types: [docker-php-updated] - permissions: contents: read - concurrency: - group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.ref }} + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} - jobs: - workflow-tests: + checks: runs-on: ubuntu-24.04 - services: - registry: - image: registry:2 - ports: - - 5000:5000 + outputs: + tags: ${{ steps.tags.outputs.tags }} steps: - - uses: actions/checkout@v4 - - uses: docker/setup-buildx-action@v3 - - name: Test release metadata and publication guards - run: python3 -m unittest discover -s tasks -p 'test_release.py' -v - - name: Test manifest promotion against a local registry - run: python3 tasks/test_release_registry.py - - name: Install actionlint - env: - GOBIN: ${{ runner.temp }}/actionlint - run: go install github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 - - name: Lint workflow - run: ${{ runner.temp }}/actionlint/actionlint - + - uses: actions/checkout@v7 + - name: Check generated contexts + run: | + docker run --rm -v "$PWD:/app" fireworkweb/fwd:v1.0 fwd template + git diff --exit-code + - id: tags + run: echo "tags=$(jq -c '[.builds[].name]' fwd-template.json)" >> "$GITHUB_OUTPUT" build: - runs-on: ${{ matrix.runner }} - - services: - registry: - image: registry:2 - ports: - - 5000:5000 - + needs: checks + runs-on: ${{ matrix.platform.runner }} strategy: + fail-fast: false matrix: version: ['8.2-swoole', '8.3-swoole', '8.4-swoole', '8.5-swoole', '8.4-debian-swoole', '8.5-debian-swoole'] type: ['', '-prod'] - arch: [amd64, arm64] - include: - - arch: amd64 - runner: ubuntu-24.04 - - arch: arm64 - runner: ubuntu-24.04-arm - + platform: + - {arch: amd64, runner: ubuntu-24.04} + - {arch: arm64, runner: ubuntu-24.04-arm} + env: + BASE: ${{ matrix.version }}${{ matrix.type }} + NGINX: ${{ matrix.version }}-nginx${{ matrix.type }} + ARCH: ${{ matrix.platform.arch }} steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup Docker Buildx - uses: docker/setup-buildx-action@v3 + - uses: actions/checkout@v7 + - uses: kool-dev/kool/.github/actions/image-build@e06584d9fc7de69f4e3a9811d64a9f691f592b6b with: - driver-opts: network=host # needed to push to local registry - - - name: Build and export to Docker - uses: docker/build-push-action@v6 + arch: ${{ env.ARCH }} + - name: Build fresh base + id: base + uses: docker/build-push-action@v7 with: - context: ${{ matrix.version }}${{ matrix.type }} - platforms: linux/${{ matrix.arch }} - provenance: false + context: ${{ env.BASE }} + platforms: linux/${{ env.ARCH }} pull: true - push: true - tags: localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} - - - name: Build and export to Docker (nginx) - uses: docker/build-push-action@v6 + provenance: false + load: true + tags: kooldev/php:${{ env.BASE }} + - name: Build nginx from same-job base (never force-pull) + id: nginx + uses: docker/build-push-action@v7 with: - context: ${{ matrix.version }}-nginx${{ matrix.type }} - platforms: linux/${{ matrix.arch }} + context: ${{ env.NGINX }} + platforms: linux/${{ env.ARCH }} provenance: false - pull: true - push: true - tags: localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} - build-contexts: | - kooldev/php:${{ matrix.version }}${{ matrix.type }}=docker-image://localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} - + load: true + tags: kooldev/php:${{ env.NGINX }} + - uses: kool-dev/kool/.github/actions/image-parent@e06584d9fc7de69f4e3a9811d64a9f691f592b6b + with: + base-ref: kooldev/php:${{ env.BASE }} + base-id: ${{ steps.base.outputs.imageid }} + image-id: ${{ steps.nginx.outputs.imageid }} - name: Tests + env: + BASE_ID: ${{ steps.base.outputs.imageid }} + NGINX_ID: ${{ steps.nginx.outputs.imageid }} run: | - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} php -r "exit(extension_loaded('swoole') ? 0 : 1);" - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} nginx -v - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} nginx -t - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} supervisord --version - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} dockerize --version - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} dockerize --version - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} sh -c 'echo "{{ .Env.TEST_VAR }}" > /tmp/test.tmpl && TEST_VAR=hello dockerize -template /tmp/test.tmpl:/tmp/test.out && test "$(cat /tmp/test.out)" = hello' - docker run --rm -e ASUSER=1000 localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} php -r "exit(posix_getuid() === 1000 ? 0 : 1);" - - - name: Test Supervisor lifecycle - run: bash tasks/test-supervisor.sh localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} - + docker run --rm "$BASE_ID" php -r "exit(extension_loaded('swoole') ? 0 : 1);" + docker run --rm "$NGINX_ID" nginx -v + docker run --rm "$NGINX_ID" nginx -t + docker run --rm "$NGINX_ID" supervisord --version + docker run --rm "$BASE_ID" dockerize --version + docker run --rm "$NGINX_ID" dockerize --version + docker run --rm "$BASE_ID" sh -c 'echo "{{ .Env.TEST_VAR }}" > /tmp/test.tmpl && TEST_VAR=hello dockerize -template /tmp/test.tmpl:/tmp/test.out && test "$(cat /tmp/test.out)" = hello' + docker run --rm -e ASUSER=1000 "$NGINX_ID" php -r "exit(posix_getuid() === 1000 ? 0 : 1);" + bash tasks/test-supervisor.sh "$NGINX_ID" - name: Tests (dev) if: matrix.type == '' + env: + BASE_ID: ${{ steps.base.outputs.imageid }} + NGINX_ID: ${{ steps.nginx.outputs.imageid }} run: | - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} node -v - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}${{ matrix.type }} yarn -v - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} node -v - docker run --rm localhost:5000/kooldev/php:${{ matrix.version }}-nginx${{ matrix.type }} yarn -v - - - name: Login to DockerHub - if: contains(fromJSON('["push", "workflow_dispatch", "repository_dispatch"]'), github.event_name) && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' - uses: docker/login-action@v3 + docker run --rm "$BASE_ID" node -v + docker run --rm "$BASE_ID" yarn -v + docker run --rm "$NGINX_ID" node -v + docker run --rm "$NGINX_ID" yarn -v + - uses: kool-dev/kool/.github/actions/image-stage@e06584d9fc7de69f4e3a9811d64a9f691f592b6b + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' with: + canonical-repository: kool-dev/docker-php-swoole + default-branch: main + repository: kooldev/php + arch: ${{ env.ARCH }} + group: ${{ env.BASE }} + images: >- + [{"tag":"${{ env.BASE }}","id":"${{ steps.base.outputs.imageid }}"}, + {"tag":"${{ env.NGINX }}","id":"${{ steps.nginx.outputs.imageid }}"}] username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - - - name: Stage exact tested images - if: contains(fromJSON('["push", "workflow_dispatch", "repository_dispatch"]'), github.event_name) && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' - env: - VERSION: ${{ matrix.version }} - TYPE: ${{ matrix.type }} - ARCH: ${{ matrix.arch }} - run: python3 tasks/release.py stage "$VERSION" "$TYPE" "$ARCH" release-metadata - - - name: Upload immutable release metadata - if: contains(fromJSON('["push", "workflow_dispatch", "repository_dispatch"]'), github.event_name) && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' - uses: actions/upload-artifact@v7.0.2 - with: - name: swoole-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.version }}${{ matrix.type }}-${{ matrix.arch }} - path: release-metadata/*.json - if-no-files-found: error - retention-days: 7 - publish: - needs: [build, workflow-tests] - if: contains(fromJSON('["push", "workflow_dispatch", "repository_dispatch"]'), github.event_name) && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' - runs-on: ubuntu-24.04 - steps: - - uses: actions/checkout@v4 - - uses: docker/setup-buildx-action@v3 - with: - driver: docker - - uses: actions/download-artifact@v8.0.2 - with: - pattern: swoole-${{ github.run_id }}-${{ github.run_attempt }}-* - path: release-metadata - - name: Login to DockerHub - uses: docker/login-action@v3 - with: - username: ${{ secrets.DOCKER_USERNAME }} - password: ${{ secrets.DOCKER_PASSWORD }} - - name: Preflight all digests and promote manifests only - run: python3 tasks/release.py promote release-metadata - + needs: [checks, build] + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' + uses: kool-dev/kool/.github/workflows/image-publish.yml@e06584d9fc7de69f4e3a9811d64a9f691f592b6b + with: + canonical-repository: kool-dev/docker-php-swoole + default-branch: main + repository: kooldev/php + tags: ${{ needs.checks.outputs.tags }} + tooling-ref: e06584d9fc7de69f4e3a9811d64a9f691f592b6b + secrets: + DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} + DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} dispatch: needs: publish - if: contains(fromJSON('["push", "workflow_dispatch", "repository_dispatch"]'), github.event_name) && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' - runs-on: ubuntu-latest + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' + runs-on: ubuntu-24.04 timeout-minutes: 5 - env: - GH_TOKEN: ${{ secrets.DISPATCH_TOKEN || secrets.WORKFLOW_TOKEN }} steps: - - name: Check dispatch credential - id: credential + - name: Notify OCI8 after complete publication + env: + GH_TOKEN: ${{ secrets.DISPATCH_TOKEN || secrets.WORKFLOW_TOKEN }} run: | - if [ -z "$GH_TOKEN" ]; then - echo "::error::Set DISPATCH_TOKEN or WORKFLOW_TOKEN with dispatch access to kool-dev/docker-php-oci8." + if [[ -z "$GH_TOKEN" ]]; then + echo "::error::Configure DISPATCH_TOKEN or WORKFLOW_TOKEN for OCI8 dispatch." exit 1 fi - - - name: Notify OCI8 after all Swoole tags are published - id: notify - run: | - gh api --method POST repos/kool-dev/docker-php-oci8/dispatches \ - -f event_type=docker-php-swoole-updated - - - name: Summarize publication and downstream notification - if: always() - env: - CREDENTIAL_OUTCOME: ${{ steps.credential.outcome }} - DISPATCH_OUTCOME: ${{ steps.notify.outcome }} - run: | - { - echo "### Swoole release propagation" - echo "- All 24 Swoole stable manifests: published successfully." - echo "- Dispatch credential check: $CREDENTIAL_OUTCOME." - echo "- OCI8 docker-php-swoole-updated dispatch: $DISPATCH_OUTCOME." - echo "- Dispatch acceptance does not confirm OCI8 build or publication completion." - } >> "$GITHUB_STEP_SUMMARY" + gh api --method POST repos/kool-dev/docker-php-oci8/dispatches -f event_type=docker-php-swoole-updated + echo "- OCI8: dispatch accepted (not downstream completion)." >> "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index 9c9a8da..6c612e4 100644 --- a/README.md +++ b/README.md @@ -54,9 +54,9 @@ Please refer to [kooldev/php](https://github.com/kool-dev/docker-php). PHP's scheduled rebuild sends `docker-php-updated` after publication to start a Swoole rebuild. Swoole has no separate cron schedule; manual workflow runs remain available for recovery. Builds explicitly pull parents. Main-branch releases share a concurrency group and are not canceled in progress; only superseded PR runs are canceled. GitHub may replace pending runs and does not promise FIFO ordering. -The 24 native jobs use `ubuntu-24.04` for amd64 and `ubuntu-24.04-arm` for arm64. Each builds and tests a base/NGINX pair through a job-local registry; NGINX consumes that same job's fresh base. After all tests in a job pass, trusted main-branch runs retag those exact tested daemon images (without rebuilding) to `kooldev/php:ci-swoole-RUN_ID-RUN_ATTEMPT-VARIANT-ARCH`. PRs, forks, and manual feature-branch runs never log in, stage, publish, or notify OCI8. +The 24 native jobs use `ubuntu-24.04` for amd64 and `ubuntu-24.04-arm` for arm64. Each builds and tests a base/NGINX pair using Docker's same-job local image store; NGINX never force-pulls a stale public base. A shared check verifies the tested base ID and full layer ancestry. After all runtime/Supervisor/dev tests pass, trusted main-branch runs stage those exact immutable IDs without rebuilding. PRs, forks, and manual feature-branch runs never log in, stage, publish, or notify OCI8. -A single manifest-only job requires every native job and the workflow checks to succeed. It validates all 24 stable tags × both architectures, run/attempt scope, repository, unique tag/platform entries, digest format, tested image ID and Linux OS before updating any stable tag. Staging verifies each local tested image's platform and records Docker's push digest directly. Publication trusts those artifacts rather than re-reading 48 remote manifests/configs; staging also avoids 48 post-push inspections. Stable manifests reference the recorded immutable Docker Hub digests, never staging tag lookups or rebuilt images. Metadata artifacts are retained for seven days. There is no cross-tag transaction: a registry failure during promotion can still leave a partially updated release. +All image repos share Bash/`jq` actions and a reusable publisher in [kool-dev/kool](https://github.com/kool-dev/kool/tree/main/.github/actions), pinned to one immutable commit. Image-specific builds/tests stay here; no Python release tooling is required. The publisher requires every native job and generation checks to succeed, then validates all 24 tags × both architectures, run/attempt scope, repository, unique entries, tested IDs/platforms and digests before any stable update. It trusts staging's local ID/platform checks and Docker push digests, avoiding redundant remote inspections. Artifacts are retained for seven days; stable updates remain sequential, not atomic. Recovery requires **Re-run all jobs**, not just failed jobs: artifacts and staging tags are scoped to the current run ID **and attempt**, and incomplete attempts fail closed. A new manual main-branch workflow run also rebuilds/tests the complete release. Do not combine artifacts from previous attempts. @@ -66,7 +66,7 @@ Only after all 24 stable manifests succeed, one bounded notification sends `dock The notification uses `DISPATCH_TOKEN`, falling back to `WORKFLOW_TOKEN`. The selected credential must permit repository dispatch to OCI8; secret presence alone does not verify access. Missing credentials or failed dispatches fail the notification job visibly, without undoing published images. The job summary distinguishes publication from notification; an accepted dispatch does not prove OCI8 completed. Investigate and retry a failed notification with a manual workflow run; there is no independent downstream schedule to mask a broken chain. This is not an atomic release or digest-pinned parent chain. -Release logic has offline coverage via `python3 -m unittest discover -s tasks -p 'test_release.py' -v`; CI also runs actionlint and `python3 tasks/test_release_registry.py` against a disposable local registry. The latter stages tiny scratch fixtures and verifies all 24 two-platform manifests without touching Docker Hub (set `RELEASE_TEST_REGISTRY=localhost:PORT` to use another local port). It does not execute ARM code. Native amd64/arm64 image tests remain required to validate the actual runtime images. +Shared Bash contract and real loopback-registry tests live in the tooling repository. Here CI runs the real template generator and native image/Supervisor tests. Synthetic registry fixtures do not execute ARM application code. ### Update images with templates diff --git a/tasks/release.py b/tasks/release.py deleted file mode 100644 index 5070409..0000000 --- a/tasks/release.py +++ /dev/null @@ -1,118 +0,0 @@ -#!/usr/bin/env python3 -"""Stage tested daemon images, then promote only a complete run's digests.""" - -import json -import os -from pathlib import Path -import re -import subprocess -import sys - -REPOSITORY = "kooldev/php" -VERSIONS = ("8.2-swoole", "8.3-swoole", "8.4-swoole", "8.5-swoole", - "8.4-debian-swoole", "8.5-debian-swoole") -TAGS = tuple(f"{version}{nginx}{kind}" for version in VERSIONS - for nginx in ("", "-nginx") for kind in ("", "-prod")) -ARCHES = ("amd64", "arm64") -DIGEST = re.compile(r"sha256:[0-9a-f]{64}") - - -def command(*args): - return subprocess.check_output(args, text=True).strip() - - -def release_scope(): - if (os.environ.get("GITHUB_REPOSITORY") != "kool-dev/docker-php-swoole" - or os.environ.get("GITHUB_REF") != "refs/heads/main" - or os.environ.get("GITHUB_EVENT_NAME") not in - ("push", "workflow_dispatch", "repository_dispatch")): - raise ValueError("Publication requires a trusted main-branch event") - scope = (os.environ["GITHUB_RUN_ID"], os.environ["GITHUB_RUN_ATTEMPT"]) - if not all(re.fullmatch(r"[1-9][0-9]*", value) for value in scope): - raise ValueError("Invalid run ID/attempt") - return scope - - -def staging_tag(run, attempt, tag, arch): - return f"ci-swoole-{run}-{attempt}-{tag}-{arch}" - - -def stage(version, kind, arch, directory): - run, attempt = release_scope() - if version not in VERSIONS or kind not in ("", "-prod") or arch not in ARCHES: - raise ValueError("Invalid build variant/platform") - records = [] - for tag in (f"{version}{kind}", f"{version}-nginx{kind}"): - source = f"localhost:5000/{REPOSITORY}:{tag}" - # No pull or rebuild: these are the daemon images used by docker run tests. - image = json.loads(command("docker", "image", "inspect", source))[0] - image_id = image["Id"] - if (not DIGEST.fullmatch(image_id) or image["Architecture"] != arch - or image["Os"] != "linux"): - raise ValueError(f"Unexpected tested image: {source}") - staging = staging_tag(run, attempt, tag, arch) - target = f"{REPOSITORY}:{staging}" - command("docker", "tag", image_id, target) - if command("docker", "image", "inspect", "--format", "{{.Id}}", target) != image_id: - raise ValueError("Staging tag is not the tested image") - output = command("docker", "push", target) - digests = re.findall(r"\bdigest: (sha256:[0-9a-f]{64})\b", output) - if len(digests) != 1: - raise ValueError("Push did not report exactly one registry digest") - records.append(dict(repository=REPOSITORY, run_id=run, run_attempt=attempt, - tag=tag, arch=arch, staging_tag=staging, - digest=digests[0], image_id=image_id, os=image["Os"])) - path = Path(directory) - path.mkdir(parents=True, exist_ok=True) - (path / f"{version}{kind}-{arch}.json").write_text(json.dumps(records) + "\n") - - -def load_records(directory, run, attempt): - records = {} - for path in sorted(Path(directory).rglob("*.json")): - batch = json.loads(path.read_text()) - if not isinstance(batch, list): - raise ValueError(f"Invalid artifact: {path}") - for record in batch: - if not isinstance(record, dict) or set(record) != { - "repository", "run_id", "run_attempt", "tag", "arch", - "staging_tag", "digest", "image_id", "os" - }: - raise ValueError("Malformed metadata") - tag, arch = record["tag"], record["arch"] - if (record["repository"] != REPOSITORY or record["os"] != "linux" - or record["run_id"] != run or record["run_attempt"] != attempt - or tag not in TAGS or arch not in ARCHES - or record["staging_tag"] != staging_tag(run, attempt, tag, arch) - or not isinstance(record["digest"], str) - or not DIGEST.fullmatch(record["digest"]) - or not isinstance(record["image_id"], str) - or not DIGEST.fullmatch(record["image_id"])): - raise ValueError("Invalid repository, scope, tag, architecture or digest") - key = (tag, arch) - if key in records: - raise ValueError(f"Duplicate metadata: {key}") - records[key] = record - if set(records) != {(tag, arch) for tag in TAGS for arch in ARCHES}: - raise ValueError("Incomplete release: require all 24 tags on both architectures") - return records - - -def promote(directory): - run, attempt = release_scope() - records = load_records(directory, run, attempt) - # Staging already checked the tested local ID/OS/architecture and recorded - # Docker's push digest. Trust this run's artifacts, not another registry GET. - for tag in TAGS: - command("docker", "buildx", "imagetools", "create", "--tag", - f"{REPOSITORY}:{tag}", - *(f"{REPOSITORY}@{records[tag, arch]['digest']}" for arch in ARCHES)) - - -if __name__ == "__main__": - if len(sys.argv) == 6 and sys.argv[1] == "stage": - stage(*sys.argv[2:]) - elif len(sys.argv) == 3 and sys.argv[1] == "promote": - promote(sys.argv[2]) - else: - sys.exit("Usage: release.py stage VERSION TYPE ARCH DIRECTORY | promote DIRECTORY") diff --git a/tasks/test_release.py b/tasks/test_release.py deleted file mode 100644 index 45a5576..0000000 --- a/tasks/test_release.py +++ /dev/null @@ -1,211 +0,0 @@ -"""Offline tests for the release boundary.""" - -import copy -import json -import os -from pathlib import Path -import tempfile -import unittest -from unittest.mock import patch - -import release - - -TRUSTED = dict(GITHUB_REPOSITORY="kool-dev/docker-php-swoole", - GITHUB_REF="refs/heads/main", GITHUB_EVENT_NAME="push", - GITHUB_RUN_ID="12345", GITHUB_RUN_ATTEMPT="2") - - -class ReleaseTests(unittest.TestCase): - def setUp(self): - self.temp = tempfile.TemporaryDirectory() - self.addCleanup(self.temp.cleanup) - self.directory = Path(self.temp.name) - env = patch.dict(os.environ, TRUSTED, clear=True) - env.start() - self.addCleanup(env.stop) - self.records = [ - dict(repository=release.REPOSITORY, run_id="12345", run_attempt="2", - tag=tag, arch=arch, os="linux", digest=f"sha256:{index:064x}", - image_id=f"sha256:{index + 100:064x}", - staging_tag=release.staging_tag("12345", "2", tag, arch)) - for index, (tag, arch) in enumerate( - (tag, arch) for tag in release.TAGS for arch in release.ARCHES) - ] - - def write(self, records=None): - (self.directory / "records.json").write_text( - json.dumps(self.records if records is None else records)) - - def test_complete_metadata(self): - self.write() - self.assertEqual(len(release.load_records(self.directory, "12345", "2")), 48) - - def test_invalid_metadata_never_touches_registry(self): - cases = [self.records[:-1], self.records + [self.records[0]], [], {}] - for field, value in ( - ("repository", "attacker/php"), ("run_attempt", "1"), ("run_id", "999"), - ("tag", "latest"), ("arch", "s390x"), ("staging_tag", "old-attempt"), - ("digest", "sha256:bad"), ("digest", "sha256:" + "g" * 64), - ("digest", "sha256:" + "a" * 64 + ";echo bad"), - ("digest", None), ("image_id", "bad"), ("os", "windows"), - ): - records = copy.deepcopy(self.records) - records[0][field] = value - cases.append(records) - records = copy.deepcopy(self.records) - del records[0]["digest"] - cases.append(records) - for records in cases: - with self.subTest(records=str(records)[:150]): - self.write(records) - with patch.object(release, "command") as command: - with self.assertRaises(ValueError): - release.promote(self.directory) - command.assert_not_called() - - def test_promotion_uses_validated_artifacts_without_remote_inspections(self): - self.write() - commands = [] - - def docker(*args): - commands.append(args) - return "" - - with patch.object(release, "command", side_effect=docker): - release.promote(self.directory) - self.assertEqual(len(commands), 24) - for tag, cmd in zip(release.TAGS, commands): - self.assertEqual(cmd[:6], ("docker", "buildx", "imagetools", "create", - "--tag", f"kooldev/php:{tag}")) - self.assertEqual(cmd[6:], tuple( - f"kooldev/php@{record['digest']}" for record in self.records - if record["tag"] == tag)) - self.assertFalse(any("build" in cmd or "pull" in cmd for cmd in commands)) - - def test_last_bad_record_prevents_all_stable_updates(self): - records = copy.deepcopy(self.records) - records[-1]["os"] = "windows" - self.write(records) - with patch.object(release, "command") as command: - with self.assertRaises(ValueError): - release.promote(self.directory) - command.assert_not_called() - - def test_registry_failure_prevents_all_stable_updates(self): - self.write() - with patch.object(release, "command", side_effect=RuntimeError("registry unavailable")): - with self.assertRaises(RuntimeError): - release.promote(self.directory) - - def test_stage_retags_tested_image_ids_without_pull_or_build(self): - image_ids = ["sha256:" + "a" * 64, "sha256:" + "b" * 64] - commands = [] - - def docker(*args): - commands.append(args) - image_id = image_ids[0 if len(commands) <= 4 else 1] - if args[:3] == ("docker", "image", "inspect"): - if "--format" in args: - return image_id - return json.dumps([dict(Id=image_id, Architecture="amd64", Os="linux")]) - if args[:2] == ("docker", "push"): - return "tag: digest: sha256:" + "c" * 64 + " size: 123" - return "" - - with patch.object(release, "command", side_effect=docker): - release.stage("8.5-swoole", "-prod", "amd64", self.directory) - self.assertEqual(len(commands), 8) - for offset, image_id in ((0, image_ids[0]), (4, image_ids[1])): - self.assertEqual(commands[offset + 1][:3], ("docker", "tag", image_id)) - self.assertEqual(commands[offset + 2][-1], commands[offset + 1][-1]) - self.assertEqual(commands[offset + 3][-1], commands[offset + 1][-1]) - records = json.loads(next(self.directory.glob("*.json")).read_text()) - self.assertEqual([record["image_id"] for record in records], image_ids) - self.assertTrue(all(record["staging_tag"].startswith("ci-swoole-12345-2-") - for record in records)) - self.assertFalse(any("build" in cmd or "pull" in cmd for cmd in commands)) - self.assertFalse(any("imagetools" in cmd for cmd in commands)) - - def test_ambiguous_or_missing_push_digest_never_writes_metadata(self): - image = dict(Id="sha256:" + "a" * 64, Architecture="amd64", Os="linux") - for output in ("no digest", "digest: sha256:" + "c" * 64 + "\ndigest: sha256:" + "d" * 64): - with patch.object(release, "command", side_effect=[ - json.dumps([image]), "", image["Id"], output - ]): - with self.assertRaises(ValueError): - release.stage("8.5-swoole", "", "amd64", self.directory) - self.assertEqual(list(self.directory.iterdir()), []) - - def test_retag_mismatch_prevents_push(self): - image = dict(Id="sha256:" + "a" * 64, Architecture="amd64", Os="linux") - with patch.object(release, "command", - side_effect=[json.dumps([image]), "", "sha256:" + "b" * 64]) as command: - with self.assertRaises(ValueError): - release.stage("8.5-swoole", "", "amd64", self.directory) - self.assertFalse(any(call.args[1] == "push" for call in command.call_args_list)) - self.assertEqual(list(self.directory.iterdir()), []) - - def test_wrong_local_platform_or_id_prevents_push(self): - for image in ( - dict(Id="bad", Architecture="amd64", Os="linux"), - dict(Id="sha256:" + "a" * 64, Architecture="arm64", Os="linux"), - dict(Id="sha256:" + "a" * 64, Architecture="amd64", Os="windows"), - ): - with patch.object(release, "command", return_value=json.dumps([image])) as command: - with self.assertRaises(ValueError): - release.stage("8.5-swoole", "", "amd64", self.directory) - self.assertEqual(command.call_count, 1) - self.assertEqual(list(self.directory.iterdir()), []) - - def test_untrusted_events_cannot_stage_or_promote(self): - for override in ( - dict(GITHUB_EVENT_NAME="pull_request"), - dict(GITHUB_EVENT_NAME="pull_request_target"), - dict(GITHUB_EVENT_NAME="workflow_dispatch", GITHUB_REF="refs/heads/feature"), - dict(GITHUB_REPOSITORY="fork/docker-php-swoole"), - dict(GITHUB_RUN_ATTEMPT="0"), - ): - with self.subTest(override=override), patch.dict(os.environ, override): - with patch.object(release, "command") as command: - for action in (lambda: release.promote(self.directory), - lambda: release.stage("8.5-swoole", "", "amd64", self.directory)): - with self.assertRaises(ValueError): - action() - command.assert_not_called() - - def test_workflow_publication_boundary(self): - workflow = (Path(__file__).resolve().parents[1] / - ".github/workflows/ci-cd.yml").read_text() - build = workflow.split(" build:\n")[1].split(" publish:\n")[0] - publish = workflow.split(" publish:\n")[1].split(" dispatch:\n")[0] - dispatch = workflow.split(" dispatch:\n")[1] - guard = ("contains(fromJSON('[\"push\", \"workflow_dispatch\", \"repository_dispatch\"]'), " - "github.event_name) && github.ref == 'refs/heads/main' && " - "github.repository == 'kool-dev/docker-php-swoole'") - self.assertEqual(build.count("if: " + guard), 3) - self.assertIn("if: " + guard, publish) - self.assertIn("if: " + guard, dispatch) - self.assertIn("needs: [build, workflow-tests]", publish) - self.assertIn("needs: publish", dispatch) - self.assertLess(build.index("Test Supervisor lifecycle"), build.index("Login to DockerHub")) - self.assertLess(build.index("Tests (dev)"), build.index("Login to DockerHub")) - self.assertEqual(workflow.count("uses: docker/build-push-action@"), 2) - self.assertNotIn("setup-qemu", workflow) - self.assertNotIn("build-push-action", publish) - self.assertIn("kooldev/php:${{ matrix.version }}${{ matrix.type }}=" - "docker-image://localhost:5000/", build) - self.assertIn("runner: ubuntu-24.04\n", build) - self.assertIn("runner: ubuntu-24.04-arm\n", build) - self.assertIn("name: swoole-${{ github.run_id }}-${{ github.run_attempt }}-", build) - self.assertIn("pattern: swoole-${{ github.run_id }}-${{ github.run_attempt }}-*", publish) - self.assertIn("actions/upload-artifact@v7.0.2", build) - self.assertIn("actions/download-artifact@v8.0.2", publish) - self.assertNotIn("schedule:", workflow) - self.assertIn("cancel-in-progress: ${{ github.event_name == 'pull_request' }}", workflow) - self.assertIn("secrets.DISPATCH_TOKEN || secrets.WORKFLOW_TOKEN", dispatch) - self.assertIn("timeout-minutes: 5", dispatch) - - -if __name__ == "__main__": - unittest.main() diff --git a/tasks/test_release_registry.py b/tasks/test_release_registry.py deleted file mode 100644 index b31758b..0000000 --- a/tasks/test_release_registry.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Opt-in real registry boundary test; only writes to the specified loopback registry.""" - -import json -import os -from pathlib import Path -import re -import subprocess -import tempfile -from unittest.mock import patch - -import release - - -def main(): - registry = os.environ.get("RELEASE_TEST_REGISTRY", "localhost:5000") - if not re.fullmatch(r"localhost:[0-9]+", registry): - raise ValueError("Integration test requires a loopback registry") - repository = f"{registry}/swoole-release-test/php" - original = release.command - commands = [] - - def local_command(*args): - # Production code stays hard-coded to Docker Hub. Only this test rewrites - # references; no credentials, production writes, or production reads. - mapped = [] - for arg in args: - for prefix in ("localhost:5000/kooldev/php", "kooldev/php"): - if arg.startswith(prefix + ":") or arg.startswith(prefix + "@"): - arg = repository + arg[len(prefix):] - break - mapped.append(arg) - commands.append(mapped) - return original(*mapped) - - with tempfile.TemporaryDirectory() as temporary: - root = Path(temporary) - (root / "Dockerfile").write_text("FROM scratch\nLABEL purpose=swoole-release-test\n") - digests, ids = {}, {} - for arch in release.ARCHES: - target = f"{repository}:fixture-{arch}" - subprocess.run(["docker", "buildx", "build", "--platform", f"linux/{arch}", - "--provenance=false", "--load", "--tag", target, - str(root)], check=True) - ids[arch] = original("docker", "image", "inspect", "--format", "{{.Id}}", target) - original("docker", "push", "--quiet", target) - digests[arch] = json.loads(original( - "docker", "buildx", "imagetools", "inspect", target, - "--format", "{{json .Manifest}}"))["digest"] - - # The inspected daemon IDs are our tested fixture images. Stage them by - # ID through the unmodified production code, with registry-only routing. - for tag in ("8.5-swoole-prod", "8.5-swoole-nginx-prod"): - original("docker", "tag", ids["amd64"], f"{repository}:{tag}") - env = dict(GITHUB_REPOSITORY="kool-dev/docker-php-swoole", - GITHUB_REF="refs/heads/main", GITHUB_EVENT_NAME="push", - GITHUB_RUN_ID="12345", GITHUB_RUN_ATTEMPT="2") - with patch.dict(os.environ, env), patch.object(release, "command", local_command): - release.stage("8.5-swoole", "-prod", "amd64", root / "staged") - staged = json.loads(next((root / "staged").glob("*.json")).read_text()) - assert all(record["image_id"] == ids["amd64"] for record in staged) - assert all(record["digest"] == digests["amd64"] for record in staged) - # Expand the two tiny native-config fixtures over the complete release - # shape. This tests all stable writes without redundant remote preflight. - records = [ - dict(repository=release.REPOSITORY, run_id="12345", run_attempt="2", - tag=tag, arch=arch, os="linux", digest=digests[arch], image_id=ids[arch], - staging_tag=release.staging_tag("12345", "2", tag, arch)) - for tag in release.TAGS for arch in release.ARCHES - ] - metadata = root / "metadata" - metadata.mkdir() - (metadata / "records.json").write_text(json.dumps(records)) - commands.clear() - release.promote(metadata) - assert len(commands) == 24 - assert all(cmd[3] == "create" for cmd in commands) - for tag in release.TAGS: - manifest = json.loads(original( - "docker", "buildx", "imagetools", "inspect", - f"{repository}:{tag}", "--raw")) - assert {entry["platform"]["architecture"] for entry in manifest["manifests"]} == { - "amd64", "arm64"} - assert {entry["digest"] for entry in manifest["manifests"]} == set(digests.values()) - print("PASS: exact daemon-ID staging and 24 two-platform manifest-only promotions, loopback only") - - -if __name__ == "__main__": - main() From c303a28ce98b6a93ea4ba453226850b8d363cb0e Mon Sep 17 00:00:00 2001 From: Daniel Polito Date: Mon, 16 Nov 2026 09:26:57 -0300 Subject: [PATCH 4/5] Pin shared image tooling from kool-dev/action --- .github/workflows/ci-cd.yml | 10 +++++----- README.md | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index d06cfd9..c892fd0 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -41,7 +41,7 @@ jobs: ARCH: ${{ matrix.platform.arch }} steps: - uses: actions/checkout@v7 - - uses: kool-dev/kool/.github/actions/image-build@e06584d9fc7de69f4e3a9811d64a9f691f592b6b + - uses: kool-dev/action/image-build@c1a0de73a81d63b9b1da74001afd60aa5573470a with: arch: ${{ env.ARCH }} - name: Build fresh base @@ -63,7 +63,7 @@ jobs: provenance: false load: true tags: kooldev/php:${{ env.NGINX }} - - uses: kool-dev/kool/.github/actions/image-parent@e06584d9fc7de69f4e3a9811d64a9f691f592b6b + - uses: kool-dev/action/image-parent@c1a0de73a81d63b9b1da74001afd60aa5573470a with: base-ref: kooldev/php:${{ env.BASE }} base-id: ${{ steps.base.outputs.imageid }} @@ -92,7 +92,7 @@ jobs: docker run --rm "$BASE_ID" yarn -v docker run --rm "$NGINX_ID" node -v docker run --rm "$NGINX_ID" yarn -v - - uses: kool-dev/kool/.github/actions/image-stage@e06584d9fc7de69f4e3a9811d64a9f691f592b6b + - uses: kool-dev/action/image-stage@c1a0de73a81d63b9b1da74001afd60aa5573470a if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' with: canonical-repository: kool-dev/docker-php-swoole @@ -108,13 +108,13 @@ jobs: publish: needs: [checks, build] if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' - uses: kool-dev/kool/.github/workflows/image-publish.yml@e06584d9fc7de69f4e3a9811d64a9f691f592b6b + uses: kool-dev/action/.github/workflows/image-publish.yml@c1a0de73a81d63b9b1da74001afd60aa5573470a with: canonical-repository: kool-dev/docker-php-swoole default-branch: main repository: kooldev/php tags: ${{ needs.checks.outputs.tags }} - tooling-ref: e06584d9fc7de69f4e3a9811d64a9f691f592b6b + tooling-ref: c1a0de73a81d63b9b1da74001afd60aa5573470a secrets: DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} diff --git a/README.md b/README.md index 6c612e4..5eb0325 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ PHP's scheduled rebuild sends `docker-php-updated` after publication to start a The 24 native jobs use `ubuntu-24.04` for amd64 and `ubuntu-24.04-arm` for arm64. Each builds and tests a base/NGINX pair using Docker's same-job local image store; NGINX never force-pulls a stale public base. A shared check verifies the tested base ID and full layer ancestry. After all runtime/Supervisor/dev tests pass, trusted main-branch runs stage those exact immutable IDs without rebuilding. PRs, forks, and manual feature-branch runs never log in, stage, publish, or notify OCI8. -All image repos share Bash/`jq` actions and a reusable publisher in [kool-dev/kool](https://github.com/kool-dev/kool/tree/main/.github/actions), pinned to one immutable commit. Image-specific builds/tests stay here; no Python release tooling is required. The publisher requires every native job and generation checks to succeed, then validates all 24 tags × both architectures, run/attempt scope, repository, unique entries, tested IDs/platforms and digests before any stable update. It trusts staging's local ID/platform checks and Docker push digests, avoiding redundant remote inspections. Artifacts are retained for seven days; stable updates remain sequential, not atomic. +All image repos share Bash/`jq` actions and a reusable publisher in [kool-dev/action](https://github.com/kool-dev/action/blob/master/image-ci.md), pinned to one immutable commit. Image-specific builds/tests stay here; no Python release tooling is required. The publisher requires every native job and generation checks to succeed, then validates all 24 tags × both architectures, run/attempt scope, repository, unique entries, tested IDs/platforms and digests before any stable update. It trusts staging's local ID/platform checks and Docker push digests, avoiding redundant remote inspections. Artifacts are retained for seven days; stable updates remain sequential, not atomic. Recovery requires **Re-run all jobs**, not just failed jobs: artifacts and staging tags are scoped to the current run ID **and attempt**, and incomplete attempts fail closed. A new manual main-branch workflow run also rebuilds/tests the complete release. Do not combine artifacts from previous attempts. From 0c975abb3636fc60d30f4b3473de31f97f02ab6e Mon Sep 17 00:00:00 2001 From: Daniel Polito Date: Mon, 16 Nov 2026 09:51:52 -0300 Subject: [PATCH 5/5] Call the publisher action directly and trim repeated documentation --- .github/workflows/ci-cd.yml | 26 +++++++++++++------------- README.md | 4 +--- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index c892fd0..cd61237 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -41,7 +41,7 @@ jobs: ARCH: ${{ matrix.platform.arch }} steps: - uses: actions/checkout@v7 - - uses: kool-dev/action/image-build@c1a0de73a81d63b9b1da74001afd60aa5573470a + - uses: kool-dev/action/image-build@6a6d04e8d1e1c66afc178e32c7d77d76169c7717 with: arch: ${{ env.ARCH }} - name: Build fresh base @@ -63,7 +63,7 @@ jobs: provenance: false load: true tags: kooldev/php:${{ env.NGINX }} - - uses: kool-dev/action/image-parent@c1a0de73a81d63b9b1da74001afd60aa5573470a + - uses: kool-dev/action/image-parent@6a6d04e8d1e1c66afc178e32c7d77d76169c7717 with: base-ref: kooldev/php:${{ env.BASE }} base-id: ${{ steps.base.outputs.imageid }} @@ -92,7 +92,7 @@ jobs: docker run --rm "$BASE_ID" yarn -v docker run --rm "$NGINX_ID" node -v docker run --rm "$NGINX_ID" yarn -v - - uses: kool-dev/action/image-stage@c1a0de73a81d63b9b1da74001afd60aa5573470a + - uses: kool-dev/action/image-stage@6a6d04e8d1e1c66afc178e32c7d77d76169c7717 if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' with: canonical-repository: kool-dev/docker-php-swoole @@ -108,16 +108,16 @@ jobs: publish: needs: [checks, build] if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' - uses: kool-dev/action/.github/workflows/image-publish.yml@c1a0de73a81d63b9b1da74001afd60aa5573470a - with: - canonical-repository: kool-dev/docker-php-swoole - default-branch: main - repository: kooldev/php - tags: ${{ needs.checks.outputs.tags }} - tooling-ref: c1a0de73a81d63b9b1da74001afd60aa5573470a - secrets: - DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} - DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} + runs-on: ubuntu-24.04 + steps: + - uses: kool-dev/action/image-publish@6a6d04e8d1e1c66afc178e32c7d77d76169c7717 + with: + canonical-repository: kool-dev/docker-php-swoole + default-branch: main + repository: kooldev/php + tags: ${{ needs.checks.outputs.tags }} + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} dispatch: needs: publish if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'kool-dev/docker-php-swoole' diff --git a/README.md b/README.md index 5eb0325..d1eba06 100644 --- a/README.md +++ b/README.md @@ -56,12 +56,10 @@ PHP's scheduled rebuild sends `docker-php-updated` after publication to start a The 24 native jobs use `ubuntu-24.04` for amd64 and `ubuntu-24.04-arm` for arm64. Each builds and tests a base/NGINX pair using Docker's same-job local image store; NGINX never force-pulls a stale public base. A shared check verifies the tested base ID and full layer ancestry. After all runtime/Supervisor/dev tests pass, trusted main-branch runs stage those exact immutable IDs without rebuilding. PRs, forks, and manual feature-branch runs never log in, stage, publish, or notify OCI8. -All image repos share Bash/`jq` actions and a reusable publisher in [kool-dev/action](https://github.com/kool-dev/action/blob/master/image-ci.md), pinned to one immutable commit. Image-specific builds/tests stay here; no Python release tooling is required. The publisher requires every native job and generation checks to succeed, then validates all 24 tags × both architectures, run/attempt scope, repository, unique entries, tested IDs/platforms and digests before any stable update. It trusts staging's local ID/platform checks and Docker push digests, avoiding redundant remote inspections. Artifacts are retained for seven days; stable updates remain sequential, not atomic. +CI uses [shared Bash/`jq` actions](https://github.com/kool-dev/action/blob/master/image-ci.md), pinned in the workflow. One publisher validates the complete 24-tag × two-architecture release before stable updates. Swoole builds, generation checks and runtime tests stay here. Recovery requires **Re-run all jobs**, not just failed jobs: artifacts and staging tags are scoped to the current run ID **and attempt**, and incomplete attempts fail closed. A new manual main-branch workflow run also rebuilds/tests the complete release. Do not combine artifacts from previous attempts. -Manifest assembly still reads Docker Hub and consumes pull allowance; these changes reduce requests, not eliminate limits. Publication uses the existing Docker driver rather than booting another BuildKit container. - Only after all 24 stable manifests succeed, one bounded notification sends `docker-php-swoole-updated` to `kool-dev/docker-php-oci8`, allowing its Swoole-derived variants to rebuild after their parents. OCI8 must listen for this event and serialize its own releases; this chain does not trigger PHP again. The notification uses `DISPATCH_TOKEN`, falling back to `WORKFLOW_TOKEN`. The selected credential must permit repository dispatch to OCI8; secret presence alone does not verify access. Missing credentials or failed dispatches fail the notification job visibly, without undoing published images. The job summary distinguishes publication from notification; an accepted dispatch does not prove OCI8 completed. Investigate and retry a failed notification with a manual workflow run; there is no independent downstream schedule to mask a broken chain. This is not an atomic release or digest-pinned parent chain.