ci: complete component release propagation for issue #10
Add authoritative component-release helpers, evidence-aware reconcile with freshness and root upstream dispatch, least-privilege secrets, image scan and multi-arch build gates, and pin active component publish workflows. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
068f91cd31
commit
a61f3442bc
39 files changed
+2130
-111
No files matched your search
@@ -0,0 +1,21 @@
|
||||
# Component release helpers (authoritative copy)
|
||||
|
||||
This directory is the **single authoritative implementation** of the thin
|
||||
component release helpers required by [marqdo#10](https://git.cflmy.cn/cflmy/marqdo/issues/10)
|
||||
§4 (immutable release identity) and §6 (notify after publish).
|
||||
|
||||
Active component repositories vendor an identical copy under `scripts/release/`
|
||||
and run only that local copy. CI must never download these scripts from the
|
||||
parent repository at runtime. When the helpers change, update this directory
|
||||
first, re-run the root unit tests, then copy the same bytes into each consumer
|
||||
and record the content hashes in that consumer's `scripts/release/README.md`.
|
||||
|
||||
| Module | Role |
|
||||
| --- | --- |
|
||||
| `package_source.py` | Deterministic source archive + `.sha256` from an allowlist |
|
||||
| `write_evidence.py` | Emit `release-evidence.json` (external index; no self-hash) |
|
||||
| `publish_gitea.py` | Draft → upload assets (index last) → undraft; never overwrite public assets |
|
||||
| `notify_root.py` | Bounded retry trigger of the root `reconcile` Woodpecker workflow |
|
||||
|
||||
Secrets stay out of package/evidence scripts. Publish workflows hold
|
||||
`gitea_publish_token`; notify workflows hold `woodpecker_notify_token`.
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
# Copy the authoritative component-release helpers into a consumer repository.
|
||||
# Usage: scripts/component-release/install-vendor.sh <component-repo-root>
|
||||
set -euo pipefail
|
||||
src="$(cd "$(dirname "$0")" && pwd)"
|
||||
dst_root="${1:?component repository root required}"
|
||||
dst="$dst_root/scripts/release"
|
||||
mkdir -p "$dst"
|
||||
for name in package_source.py write_evidence.py publish_gitea.py notify_root.py; do
|
||||
cp "$src/$name" "$dst/$name"
|
||||
chmod +x "$dst/$name"
|
||||
done
|
||||
{
|
||||
echo "# Vendored from marqdo scripts/component-release"
|
||||
echo "#"
|
||||
echo "# Do not edit in place across repositories. Change the root copy, re-test,"
|
||||
echo "# then re-run install-vendor.sh and record the hashes below."
|
||||
echo "#"
|
||||
for name in package_source.py write_evidence.py publish_gitea.py notify_root.py; do
|
||||
hash="$(sha256sum "$dst/$name" | awk '{print $1}')"
|
||||
echo "# $name sha256=$hash"
|
||||
done
|
||||
} >"$dst/README.md"
|
||||
echo "vendored into $dst"
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Ask the root Marqdo reconcile workflow to scan after a release.
|
||||
|
||||
The payload is only a hint. Correctness comes from the root
|
||||
`scripts/reconcile-releases.py` reading authoritative Gitea releases.
|
||||
Lost notifications are recovered by the root `release-reconcile` cron.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
DEFAULT_URL = "https://ci.cflmy.cn/api/repos/6/pipelines"
|
||||
DEFAULT_BODY = {"branch": "main", "workflow": "reconcile"}
|
||||
|
||||
|
||||
class NotifyError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def token() -> str:
|
||||
value = (
|
||||
os.environ.get("WOODPECKER_NOTIFY_TOKEN")
|
||||
or os.environ.get("WOODPECKER_TOKEN")
|
||||
or os.environ.get("woodpecker_token")
|
||||
)
|
||||
if not value:
|
||||
raise NotifyError("WOODPECKER_NOTIFY_TOKEN (or WOODPECKER_TOKEN) is not set")
|
||||
return value
|
||||
|
||||
|
||||
def trigger(url: str, token_value: str, body: dict, attempts: int = 3) -> dict:
|
||||
payload = json.dumps(body).encode()
|
||||
last_error: Exception | None = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
data=payload,
|
||||
method="POST",
|
||||
headers={
|
||||
"Authorization": f"Bearer {token_value}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
raw = response.read()
|
||||
decoded = json.loads(raw) if raw else {}
|
||||
return {
|
||||
"status": "triggered",
|
||||
"http_status": response.status,
|
||||
"pipeline_id": decoded.get("id"),
|
||||
"pipeline_number": decoded.get("number"),
|
||||
"attempt": attempt,
|
||||
}
|
||||
except urllib.error.HTTPError as error:
|
||||
# Auth/permission failures must not retry forever.
|
||||
if error.code in (401, 403, 404):
|
||||
raise NotifyError(f"trigger rejected with HTTP {error.code}") from error
|
||||
last_error = error
|
||||
except urllib.error.URLError as error:
|
||||
last_error = error
|
||||
if attempt < attempts:
|
||||
delay = (2 ** (attempt - 1)) + random.uniform(0, 0.5)
|
||||
time.sleep(delay)
|
||||
raise NotifyError(f"trigger failed after {attempts} attempts: {last_error}")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--url", default=os.environ.get("MARQDO_RECONCILE_TRIGGER_URL", DEFAULT_URL))
|
||||
parser.add_argument("--branch", default="main")
|
||||
parser.add_argument("--workflow", default="reconcile")
|
||||
parser.add_argument("--hint-component", default="")
|
||||
parser.add_argument("--hint-tag", default="")
|
||||
parser.add_argument("--attempts", type=int, default=3)
|
||||
args = parser.parse_args(argv)
|
||||
body = {"branch": args.branch, "workflow": args.workflow}
|
||||
# Hints are informational only; the root reconcile never trusts them as commands.
|
||||
if args.hint_component or args.hint_tag:
|
||||
body["variables"] = {
|
||||
"MARQDO_RELEASE_HINT_COMPONENT": args.hint_component,
|
||||
"MARQDO_RELEASE_HINT_TAG": args.hint_tag,
|
||||
}
|
||||
try:
|
||||
result = trigger(args.url, token(), body, attempts=max(1, args.attempts))
|
||||
except NotifyError as error:
|
||||
print(f"notify_root: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print(json.dumps(result, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build a deterministic source archive for a Marqdo component release.
|
||||
|
||||
Only allowlisted relative paths are included. The archive uses fixed mtime,
|
||||
uid/gid, and sorted member names so the same tree always yields the same
|
||||
sha256. Output is written under an isolated directory (default: dist/).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_ALLOWLIST = (
|
||||
"modules",
|
||||
"index.mq.md",
|
||||
"marqdo.yaml",
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
)
|
||||
FIXED_MTIME = 0
|
||||
EVIDENCE_NAME = "release-evidence.json"
|
||||
|
||||
|
||||
class PackageError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
raise PackageError(message)
|
||||
|
||||
|
||||
def is_safe_relative(path: str) -> bool:
|
||||
if not path or path.startswith("/") or path.startswith("\\"):
|
||||
return False
|
||||
parts = Path(path).parts
|
||||
return not any(part in (".", "..") for part in parts)
|
||||
|
||||
|
||||
def collect_files(root: Path, allowlist: list[str]) -> list[tuple[str, Path]]:
|
||||
selected: dict[str, Path] = {}
|
||||
for entry in allowlist:
|
||||
if not is_safe_relative(entry):
|
||||
fail(f"unsafe allowlist entry: {entry!r}")
|
||||
target = root / entry
|
||||
if not target.exists():
|
||||
continue
|
||||
if target.is_file():
|
||||
selected[entry.replace("\\", "/")] = target
|
||||
continue
|
||||
if not target.is_dir():
|
||||
fail(f"allowlist entry is not a regular file or directory: {entry}")
|
||||
for path in sorted(target.rglob("*")):
|
||||
if not path.is_file():
|
||||
continue
|
||||
if path.is_symlink():
|
||||
fail(f"symlinks are not publishable: {path.relative_to(root)}")
|
||||
relative = path.relative_to(root).as_posix()
|
||||
if not is_safe_relative(relative):
|
||||
fail(f"unsafe relative path: {relative}")
|
||||
selected[relative] = path
|
||||
if not selected:
|
||||
fail("allowlist matched no files")
|
||||
return sorted(selected.items(), key=lambda item: item[0])
|
||||
|
||||
|
||||
def archive_bytes(files: list[tuple[str, Path]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=buffer, mode="w:gz", format=tarfile.PAX_FORMAT, compresslevel=9) as archive:
|
||||
for relative, path in files:
|
||||
data = path.read_bytes()
|
||||
info = tarfile.TarInfo(name=relative)
|
||||
info.size = len(data)
|
||||
info.mtime = FIXED_MTIME
|
||||
info.uid = 0
|
||||
info.gid = 0
|
||||
info.uname = ""
|
||||
info.gname = ""
|
||||
info.mode = 0o644
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def write_outputs(
|
||||
root: Path,
|
||||
out_dir: Path,
|
||||
component_id: str,
|
||||
version: str,
|
||||
allowlist: list[str],
|
||||
) -> dict:
|
||||
files = collect_files(root, allowlist)
|
||||
payload = archive_bytes(files)
|
||||
digest = hashlib.sha256(payload).hexdigest()
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
archive_name = f"marqdo-{component_id}-{version}-source.tar.gz"
|
||||
archive_path = out_dir / archive_name
|
||||
sha_path = out_dir / f"{archive_name}.sha256"
|
||||
archive_path.write_bytes(payload)
|
||||
sha_path.write_text(f"{digest} {archive_name}\n", encoding="utf-8")
|
||||
return {
|
||||
"archive": str(archive_path),
|
||||
"sha256_file": str(sha_path),
|
||||
"name": archive_name,
|
||||
"size": len(payload),
|
||||
"sha256": digest,
|
||||
"files": [relative for relative, _ in files],
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", default=".", help="component repository root")
|
||||
parser.add_argument("--component-id", required=True)
|
||||
parser.add_argument("--version", required=True, help="version without leading v")
|
||||
parser.add_argument("--out-dir", default="dist")
|
||||
parser.add_argument(
|
||||
"--allow",
|
||||
action="append",
|
||||
default=[],
|
||||
help="relative allowlist entry (repeatable); defaults applied when omitted",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
allowlist = args.allow or list(DEFAULT_ALLOWLIST)
|
||||
root = Path(args.root).resolve()
|
||||
out_dir = Path(args.out_dir)
|
||||
if not out_dir.is_absolute():
|
||||
out_dir = root / out_dir
|
||||
try:
|
||||
result = write_outputs(root, out_dir, args.component_id, args.version, allowlist)
|
||||
except PackageError as error:
|
||||
print(f"package_source: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print(result["archive"])
|
||||
print(result["sha256_file"])
|
||||
print(f"sha256={result['sha256']} size={result['size']} files={len(result['files'])}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,352 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish a Gitea release with a draft transaction and immutable public assets.
|
||||
|
||||
Order (issue #10 §4.2):
|
||||
create/reuse draft → upload non-index assets → upload release-evidence.json last
|
||||
→ re-read and verify → mark non-draft → re-confirm.
|
||||
|
||||
Never deletes or replaces assets on an already-published (non-draft) release.
|
||||
Identical published identity is treated as idempotent success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_API = "https://git.cflmy.cn/api/v1"
|
||||
INDEX_NAME = "release-evidence.json"
|
||||
|
||||
|
||||
class PublishError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def token() -> str:
|
||||
value = (
|
||||
os.environ.get("GITEA_PUBLISH_TOKEN")
|
||||
or os.environ.get("GITEA_TOKEN")
|
||||
or os.environ.get("gitea_token")
|
||||
)
|
||||
if not value:
|
||||
raise PublishError("GITEA_PUBLISH_TOKEN (or GITEA_TOKEN) is not set")
|
||||
return value
|
||||
|
||||
|
||||
def request(
|
||||
api: str,
|
||||
method: str,
|
||||
path: str,
|
||||
token_value: str,
|
||||
payload: dict | None = None,
|
||||
raw: bytes | None = None,
|
||||
content_type: str = "application/json",
|
||||
) -> tuple[int, bytes]:
|
||||
url = f"{api}{path}"
|
||||
headers = {"Authorization": f"token {token_value}", "Accept": "application/json"}
|
||||
data = None
|
||||
if payload is not None:
|
||||
data = json.dumps(payload).encode()
|
||||
headers["Content-Type"] = content_type
|
||||
elif raw is not None:
|
||||
data = raw
|
||||
headers["Content-Type"] = content_type
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=120) as response:
|
||||
return response.status, response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.read()
|
||||
|
||||
|
||||
def decode(body: bytes) -> object:
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def get_release_by_tag(api: str, repo: str, tag: str, token_value: str) -> dict | None:
|
||||
status, body = request(
|
||||
api,
|
||||
"GET",
|
||||
f"/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe='')}",
|
||||
token_value,
|
||||
)
|
||||
if status == 404:
|
||||
return None
|
||||
if status != 200:
|
||||
raise PublishError(f"lookup release {tag} failed with HTTP {status}")
|
||||
release = decode(body)
|
||||
if not isinstance(release, dict) or "id" not in release:
|
||||
raise PublishError("release lookup response malformed")
|
||||
return release
|
||||
|
||||
|
||||
def create_draft(
|
||||
api: str,
|
||||
repo: str,
|
||||
tag: str,
|
||||
body: str,
|
||||
token_value: str,
|
||||
*,
|
||||
prerelease: bool,
|
||||
target: str,
|
||||
) -> dict:
|
||||
payload = {
|
||||
"tag_name": tag,
|
||||
"name": tag,
|
||||
"body": body,
|
||||
"draft": True,
|
||||
"prerelease": prerelease,
|
||||
"target_commitish": target,
|
||||
}
|
||||
status, response = request(api, "POST", f"/repos/{repo}/releases", token_value, payload)
|
||||
if status not in (200, 201):
|
||||
raise PublishError(f"creating draft release failed with HTTP {status}: {response[:200]!r}")
|
||||
release = decode(response)
|
||||
if not isinstance(release, dict) or "id" not in release:
|
||||
raise PublishError("draft create response malformed")
|
||||
return release
|
||||
|
||||
|
||||
def patch_release(api: str, repo: str, release_id: int, token_value: str, payload: dict) -> dict:
|
||||
status, response = request(
|
||||
api, "PATCH", f"/repos/{repo}/releases/{release_id}", token_value, payload
|
||||
)
|
||||
if status != 200:
|
||||
raise PublishError(f"updating release {release_id} failed with HTTP {status}")
|
||||
release = decode(response)
|
||||
if not isinstance(release, dict):
|
||||
raise PublishError("release patch response malformed")
|
||||
return release
|
||||
|
||||
|
||||
def list_assets(api: str, repo: str, release_id: int, token_value: str) -> list[dict]:
|
||||
status, response = request(
|
||||
api, "GET", f"/repos/{repo}/releases/{release_id}/assets", token_value
|
||||
)
|
||||
if status != 200:
|
||||
raise PublishError(f"listing assets failed with HTTP {status}")
|
||||
assets = decode(response)
|
||||
if not isinstance(assets, list):
|
||||
raise PublishError("asset list malformed")
|
||||
return assets
|
||||
|
||||
|
||||
def upload_asset(
|
||||
api: str, repo: str, release_id: int, path: Path, token_value: str
|
||||
) -> dict:
|
||||
name = path.name
|
||||
if not name or "/" in name or name in (".", ".."):
|
||||
raise PublishError(f"unsafe asset name: {name!r}")
|
||||
existing = list_assets(api, repo, release_id, token_value)
|
||||
for asset in existing:
|
||||
if asset.get("name") == name:
|
||||
raise PublishError(
|
||||
f"asset {name} already exists on draft/release {release_id}; "
|
||||
"refusing to overwrite"
|
||||
)
|
||||
boundary = f"----marqdo{uuid.uuid4().hex}"
|
||||
content_type = mimetypes.guess_type(name)[0] or "application/octet-stream"
|
||||
body = bytearray()
|
||||
body.extend(f"--{boundary}\r\n".encode())
|
||||
body.extend(
|
||||
f'Content-Disposition: form-data; name="attachment"; filename="{name}"\r\n'.encode()
|
||||
)
|
||||
body.extend(f"Content-Type: {content_type}\r\n\r\n".encode())
|
||||
body.extend(path.read_bytes())
|
||||
body.extend(f"\r\n--{boundary}--\r\n".encode())
|
||||
status, response = request(
|
||||
api,
|
||||
"POST",
|
||||
f"/repos/{repo}/releases/{release_id}/assets?name={urllib.parse.quote(name)}",
|
||||
token_value,
|
||||
raw=bytes(body),
|
||||
content_type=f"multipart/form-data; boundary={boundary}",
|
||||
)
|
||||
if status not in (200, 201):
|
||||
raise PublishError(f"uploading {name} failed with HTTP {status}: {response[:200]!r}")
|
||||
result = decode(response)
|
||||
if not isinstance(result, dict):
|
||||
raise PublishError(f"upload response for {name} malformed")
|
||||
return result
|
||||
|
||||
|
||||
def asset_identity(path: Path) -> dict:
|
||||
return {
|
||||
"name": path.name,
|
||||
"size": path.stat().st_size,
|
||||
"sha256": sha256_file(path),
|
||||
}
|
||||
|
||||
|
||||
def published_matches(release: dict, expected: list[dict]) -> bool:
|
||||
remote = {
|
||||
asset.get("name"): int(asset.get("size") or -1)
|
||||
for asset in (release.get("assets") or [])
|
||||
}
|
||||
if set(remote) != {item["name"] for item in expected}:
|
||||
return False
|
||||
for item in expected:
|
||||
if remote.get(item["name"]) != item["size"]:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def publish(
|
||||
*,
|
||||
api: str,
|
||||
repo: str,
|
||||
tag: str,
|
||||
body: str,
|
||||
target: str,
|
||||
assets: list[Path],
|
||||
prerelease: bool,
|
||||
token_value: str,
|
||||
) -> dict:
|
||||
if not assets:
|
||||
raise PublishError("no assets to publish")
|
||||
index_assets = [path for path in assets if path.name == INDEX_NAME]
|
||||
other_assets = [path for path in assets if path.name != INDEX_NAME]
|
||||
if len(index_assets) != 1:
|
||||
raise PublishError("exactly one release-evidence.json is required")
|
||||
ordered = other_assets + index_assets
|
||||
expected = [asset_identity(path) for path in ordered]
|
||||
|
||||
existing = get_release_by_tag(api, repo, tag, token_value)
|
||||
if existing and not existing.get("draft"):
|
||||
if published_matches(existing, expected):
|
||||
return {
|
||||
"status": "idempotent",
|
||||
"release_id": existing["id"],
|
||||
"html_url": existing.get("html_url"),
|
||||
"tag": tag,
|
||||
"assets": expected,
|
||||
}
|
||||
raise PublishError(
|
||||
f"published release {tag} already exists with different assets; "
|
||||
"refusing to overwrite"
|
||||
)
|
||||
|
||||
if existing and existing.get("draft"):
|
||||
release = existing
|
||||
# Keep draft body/target aligned when continuing an interrupted publish.
|
||||
release = patch_release(
|
||||
api,
|
||||
repo,
|
||||
int(release["id"]),
|
||||
token_value,
|
||||
{
|
||||
"name": tag,
|
||||
"body": body,
|
||||
"draft": True,
|
||||
"prerelease": prerelease,
|
||||
"target_commitish": target,
|
||||
},
|
||||
)
|
||||
else:
|
||||
release = create_draft(
|
||||
api, repo, tag, body, token_value, prerelease=prerelease, target=target
|
||||
)
|
||||
|
||||
release_id = int(release["id"])
|
||||
remote_names = {asset.get("name") for asset in list_assets(api, repo, release_id, token_value)}
|
||||
for path in ordered:
|
||||
if path.name in remote_names:
|
||||
# Same-name asset already on this draft: require identical size, else fail.
|
||||
match = next(
|
||||
asset
|
||||
for asset in list_assets(api, repo, release_id, token_value)
|
||||
if asset.get("name") == path.name
|
||||
)
|
||||
if int(match.get("size") or -1) != path.stat().st_size:
|
||||
raise PublishError(
|
||||
f"draft asset {path.name} size mismatch; refusing to overwrite"
|
||||
)
|
||||
continue
|
||||
upload_asset(api, repo, release_id, path, token_value)
|
||||
|
||||
refreshed = get_release_by_tag(api, repo, tag, token_value)
|
||||
if not refreshed or not published_matches(refreshed, expected):
|
||||
raise PublishError("post-upload release asset list does not match local files")
|
||||
|
||||
published = patch_release(
|
||||
api,
|
||||
repo,
|
||||
release_id,
|
||||
token_value,
|
||||
{"draft": False, "prerelease": prerelease, "name": tag, "body": body},
|
||||
)
|
||||
if published.get("draft"):
|
||||
raise PublishError("release remained draft after publish")
|
||||
final = get_release_by_tag(api, repo, tag, token_value)
|
||||
if not final or final.get("draft") or not published_matches(final, expected):
|
||||
raise PublishError("final release confirmation failed")
|
||||
return {
|
||||
"status": "published",
|
||||
"release_id": final["id"],
|
||||
"html_url": final.get("html_url"),
|
||||
"tag": tag,
|
||||
"assets": expected,
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL", DEFAULT_API))
|
||||
parser.add_argument("--repo", required=True, help="owner/name")
|
||||
parser.add_argument("--tag", required=True)
|
||||
parser.add_argument("--target", required=True, help="full commit SHA for the tag")
|
||||
parser.add_argument("--body-file", default=None)
|
||||
parser.add_argument("--body", default="")
|
||||
parser.add_argument("--asset", action="append", default=[], required=True)
|
||||
parser.add_argument("--prerelease", action="store_true", default=False)
|
||||
parser.add_argument("--evidence-out", default="dist/gitea-publish-result.json")
|
||||
args = parser.parse_args(argv)
|
||||
body = args.body
|
||||
if args.body_file:
|
||||
body = Path(args.body_file).read_text(encoding="utf-8")
|
||||
assets = [Path(item) for item in args.asset]
|
||||
for path in assets:
|
||||
if not path.is_file():
|
||||
print(f"publish_gitea: FAIL: missing asset {path}", file=sys.stderr)
|
||||
return 1
|
||||
try:
|
||||
result = publish(
|
||||
api=args.api_url.rstrip("/"),
|
||||
repo=args.repo,
|
||||
tag=args.tag,
|
||||
body=body,
|
||||
target=args.target,
|
||||
assets=assets,
|
||||
prerelease=args.prerelease,
|
||||
token_value=token(),
|
||||
)
|
||||
except PublishError as error:
|
||||
print(f"publish_gitea: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
out = Path(args.evidence_out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
print(json.dumps(result, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/bin/sh
|
||||
# Deterministic source archive + release-evidence.json for this component.
|
||||
#
|
||||
# Required env:
|
||||
# COMPONENT_ID catalog id (e.g. std-text)
|
||||
# REPOSITORY owner/name (e.g. cflmy/marqdo-std-text)
|
||||
# Optional:
|
||||
# VERSION without leading v (default: derived from CI_COMMIT_TAG)
|
||||
# SOURCE_SHA full commit (default: HEAD)
|
||||
# OUT_DIR default dist
|
||||
# DEPENDENCY repeatable write_evidence dependency specs via env DEP_ARGS
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
COMPONENT_ID=${COMPONENT_ID:?COMPONENT_ID is required}
|
||||
REPOSITORY=${REPOSITORY:?REPOSITORY is required}
|
||||
SOURCE_SHA=${SOURCE_SHA:-$(git -C "$ROOT" rev-parse HEAD)}
|
||||
OUT_DIR=${OUT_DIR:-dist}
|
||||
TAG=${CI_COMMIT_TAG:-${TAG:-}}
|
||||
if [ -n "${VERSION:-}" ]; then
|
||||
:
|
||||
elif [ -n "$TAG" ]; then
|
||||
VERSION=${TAG#v}
|
||||
else
|
||||
echo "package.sh: set VERSION or CI_COMMIT_TAG" >&2
|
||||
exit 1
|
||||
fi
|
||||
TAG=${TAG:-v$VERSION}
|
||||
|
||||
python3 "$ROOT/scripts/release/package_source.py" \
|
||||
--root "$ROOT" \
|
||||
--component-id "$COMPONENT_ID" \
|
||||
--version "$VERSION" \
|
||||
--out-dir "$OUT_DIR"
|
||||
|
||||
ARCHIVE=$(ls "$ROOT/$OUT_DIR"/marqdo-"$COMPONENT_ID"-"$VERSION"-source.tar.gz)
|
||||
SHAFILE="$ARCHIVE.sha256"
|
||||
|
||||
EVIDENCE_ARGS="--component-id $COMPONENT_ID --repository $REPOSITORY --tag $TAG --source-sha $SOURCE_SHA --asset $ARCHIVE --asset $SHAFILE --out $ROOT/$OUT_DIR/release-evidence.json"
|
||||
if [ -n "${CI_PIPELINE_NUMBER:-}" ]; then
|
||||
EVIDENCE_ARGS="$EVIDENCE_ARGS --pipeline-number $CI_PIPELINE_NUMBER"
|
||||
fi
|
||||
if [ -n "${CI_PIPELINE_URL:-}" ]; then
|
||||
EVIDENCE_ARGS="$EVIDENCE_ARGS --pipeline-url $CI_PIPELINE_URL"
|
||||
fi
|
||||
# shellcheck disable=SC2086
|
||||
eval "python3 \"$ROOT/scripts/release/write_evidence.py\" $EVIDENCE_ARGS ${DEP_ARGS:-}"
|
||||
echo "$ARCHIVE"
|
||||
echo "$SHAFILE"
|
||||
echo "$ROOT/$OUT_DIR/release-evidence.json"
|
||||
@@ -0,0 +1,33 @@
|
||||
# Protected publish workflow: tag or manual only.
|
||||
# Holds the publish token. Push/PR lanes must never mount this secret.
|
||||
when:
|
||||
- event: [tag, manual]
|
||||
|
||||
steps:
|
||||
publish:
|
||||
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
|
||||
environment:
|
||||
GITEA_PUBLISH_TOKEN:
|
||||
from_secret: gitea_publish_token
|
||||
COMPONENT_ID: "${COMPONENT_ID}"
|
||||
REPOSITORY: "${REPOSITORY}"
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
test -n "${GITEA_PUBLISH_TOKEN:?gitea_publish_token secret missing}"
|
||||
test -n "${CI_COMMIT_TAG:?publish requires a tag}"
|
||||
export SOURCE_SHA="${CI_COMMIT_SHA}"
|
||||
export VERSION="${CI_COMMIT_TAG#v}"
|
||||
export TAG="${CI_COMMIT_TAG}"
|
||||
sh scripts/package.sh
|
||||
ARCHIVE="dist/marqdo-${COMPONENT_ID}-${VERSION}-source.tar.gz"
|
||||
python3 scripts/release/publish_gitea.py \
|
||||
--repo "$REPOSITORY" \
|
||||
--tag "$TAG" \
|
||||
--target "$SOURCE_SHA" \
|
||||
--prerelease \
|
||||
--body "Automated source release for ${COMPONENT_ID} ${TAG}." \
|
||||
--asset "$ARCHIVE" \
|
||||
--asset "${ARCHIVE}.sha256" \
|
||||
--asset dist/release-evidence.json \
|
||||
--evidence-out dist/gitea-publish-result.json
|
||||
@@ -0,0 +1,20 @@
|
||||
# Fast-path notification after a completed Gitea release.
|
||||
# Hint only; root reconcile verifies authoritative releases. Lost calls are
|
||||
# recovered by the root release-reconcile cron.
|
||||
when:
|
||||
event: [release]
|
||||
|
||||
steps:
|
||||
notify:
|
||||
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
|
||||
environment:
|
||||
WOODPECKER_NOTIFY_TOKEN:
|
||||
from_secret: woodpecker_notify_token
|
||||
COMPONENT_ID: "${COMPONENT_ID}"
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
test -n "${WOODPECKER_NOTIFY_TOKEN:?woodpecker_notify_token secret missing}"
|
||||
python3 scripts/release/notify_root.py \
|
||||
--hint-component "${COMPONENT_ID}" \
|
||||
--hint-tag "${CI_COMMIT_TAG:-}"
|
||||
@@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Write the external release-evidence.json index for a component release.
|
||||
|
||||
The index references already-built assets. It never includes itself in
|
||||
`assets[]` (no self-referential digest). Downstream discoverers hash the index
|
||||
bytes separately when they download it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
SHA_RE = re.compile(r"^[0-9a-f]{40}$")
|
||||
DIGEST_RE = re.compile(r"^[0-9a-f]{64}$")
|
||||
MAX_ASSETS = 128
|
||||
MAX_DEPENDENCIES = 256
|
||||
INDEX_NAME = "release-evidence.json"
|
||||
|
||||
|
||||
class EvidenceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
while True:
|
||||
chunk = handle.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def parse_dependency(raw: str) -> dict:
|
||||
# id=cli,source_sha=<40hex>[,asset_sha256=<64hex>]
|
||||
fields = {}
|
||||
for part in raw.split(","):
|
||||
if "=" not in part:
|
||||
raise EvidenceError(f"invalid dependency field: {raw!r}")
|
||||
key, value = part.split("=", 1)
|
||||
fields[key.strip()] = value.strip()
|
||||
component_id = fields.get("id")
|
||||
source_sha = fields.get("source_sha")
|
||||
if not component_id or not source_sha or not SHA_RE.match(source_sha):
|
||||
raise EvidenceError(f"dependency requires id and 40-hex source_sha: {raw!r}")
|
||||
entry = {"id": component_id, "source_sha": source_sha}
|
||||
asset = fields.get("asset_sha256")
|
||||
if asset:
|
||||
if not DIGEST_RE.match(asset):
|
||||
raise EvidenceError(f"invalid asset_sha256 in dependency: {raw!r}")
|
||||
entry["asset_sha256"] = asset
|
||||
return entry
|
||||
|
||||
|
||||
def build_evidence(
|
||||
*,
|
||||
component_id: str,
|
||||
repository: str,
|
||||
tag: str,
|
||||
source_sha: str,
|
||||
assets: list[Path],
|
||||
dependencies: list[dict],
|
||||
pipeline_number: int | None,
|
||||
pipeline_url: str | None,
|
||||
) -> dict:
|
||||
if not component_id:
|
||||
raise EvidenceError("component_id is required")
|
||||
if "/" not in repository:
|
||||
raise EvidenceError("repository must be owner/name")
|
||||
if not tag:
|
||||
raise EvidenceError("tag is required")
|
||||
if not SHA_RE.match(source_sha):
|
||||
raise EvidenceError("source_sha must be a 40-hex commit")
|
||||
if not assets:
|
||||
raise EvidenceError("at least one non-index asset is required")
|
||||
if len(assets) > MAX_ASSETS:
|
||||
raise EvidenceError(f"more than {MAX_ASSETS} assets")
|
||||
if len(dependencies) > MAX_DEPENDENCIES:
|
||||
raise EvidenceError(f"more than {MAX_DEPENDENCIES} dependencies")
|
||||
|
||||
asset_entries = []
|
||||
seen_names: set[str] = set()
|
||||
for path in assets:
|
||||
if not path.is_file():
|
||||
raise EvidenceError(f"asset missing: {path}")
|
||||
name = path.name
|
||||
if name == INDEX_NAME:
|
||||
raise EvidenceError("assets must not include release-evidence.json itself")
|
||||
if name in seen_names or "/" in name or name in (".", ".."):
|
||||
raise EvidenceError(f"unsafe or duplicate asset name: {name!r}")
|
||||
seen_names.add(name)
|
||||
target = "source"
|
||||
if name.endswith(".tar.gz") and "linux" in name:
|
||||
target = "x86_64-unknown-linux-gnu"
|
||||
asset_entries.append(
|
||||
{
|
||||
"name": name,
|
||||
"target": target,
|
||||
"size": path.stat().st_size,
|
||||
"sha256": sha256_file(path),
|
||||
}
|
||||
)
|
||||
|
||||
evidence = {
|
||||
"component_id": component_id,
|
||||
"repository": repository,
|
||||
"tag": tag,
|
||||
"source_sha": source_sha,
|
||||
"ci": {
|
||||
"pipeline_number": pipeline_number,
|
||||
"url": pipeline_url,
|
||||
"source_sha": source_sha,
|
||||
},
|
||||
"assets": asset_entries,
|
||||
"dependencies": dependencies,
|
||||
}
|
||||
return evidence
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--component-id", required=True)
|
||||
parser.add_argument("--repository", required=True)
|
||||
parser.add_argument("--tag", required=True)
|
||||
parser.add_argument("--source-sha", required=True)
|
||||
parser.add_argument("--asset", action="append", default=[], required=True)
|
||||
parser.add_argument("--dependency", action="append", default=[])
|
||||
parser.add_argument("--pipeline-number", type=int, default=None)
|
||||
parser.add_argument("--pipeline-url", default=None)
|
||||
parser.add_argument("--out", default=f"dist/{INDEX_NAME}")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
dependencies = [parse_dependency(item) for item in args.dependency]
|
||||
evidence = build_evidence(
|
||||
component_id=args.component_id,
|
||||
repository=args.repository,
|
||||
tag=args.tag,
|
||||
source_sha=args.source_sha,
|
||||
assets=[Path(item) for item in args.asset],
|
||||
dependencies=dependencies,
|
||||
pipeline_number=args.pipeline_number,
|
||||
pipeline_url=args.pipeline_url,
|
||||
)
|
||||
except EvidenceError as error:
|
||||
print(f"write_evidence: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
out = Path(args.out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
|
||||
if len(payload.encode()) > 1024 * 1024:
|
||||
print("write_evidence: FAIL: index exceeds 1 MiB", file=sys.stderr)
|
||||
return 1
|
||||
out.write_text(payload, encoding="utf-8")
|
||||
print(out)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+493
-66
@@ -1,23 +1,28 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Release discovery and idempotent tracking for the Marqdo ecosystem.
|
||||
"""Release discovery, evidence verification, tracking and consumer dispatch.
|
||||
|
||||
Reads the authoritative catalog/gitlinks to derive managed repositories, scans
|
||||
Gitea releases (including prereleases), verifies tag/source identity and asset
|
||||
size/SHA-256, and creates one tracking Issue per release in the root repository.
|
||||
Gitea releases (including prereleases), verifies asset size/SHA-256 and optional
|
||||
`release-evidence.json`, creates one tracking Issue per release in the root
|
||||
repository, records direct consumers via `scripts/impact.py`, and can open
|
||||
idempotent `[Upstream]` Issues in consumer repositories.
|
||||
|
||||
It never updates gitlinks, never publishes, and never trusts a release body as a
|
||||
command. The same implementation backs the Woodpecker manual/cron reconcile
|
||||
workflow, so a lost notification is recovered by the next successful scan.
|
||||
|
||||
State/idempotency is the root Issue itself: the body carries a stable marker
|
||||
`<!-- marqdo:release-reconcile repository=<full> tag=<tag> -->` and the fixed
|
||||
`release-tracking` label. A concurrent run can create a duplicate only if both
|
||||
scan before either issue is visible; the workflow serializes runs.
|
||||
`release-tracking` label. Consumer tasks use
|
||||
`<!-- marqdo:upstream-task key=<hex> -->`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -31,18 +36,33 @@ PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
API_BASE = os.environ.get("MARQDO_GITEA_API", "https://git.cflmy.cn/api/v1")
|
||||
ROOT_REPOSITORY = os.environ.get("MARQDO_ROOT_REPOSITORY", "cflmy/marqdo")
|
||||
LABEL = "release-tracking"
|
||||
UPSTREAM_LABEL = "upstream-validation"
|
||||
MAX_ASSET_BYTES = 256 * 1024 * 1024
|
||||
MAX_ASSETS = 128
|
||||
MAX_EVIDENCE_BYTES = 1024 * 1024
|
||||
INDEX_NAME = "release-evidence.json"
|
||||
SHA_RE = re.compile(r"^[0-9a-f]{40}$")
|
||||
DIGEST_RE = re.compile(r"^[0-9a-f]{64}$")
|
||||
|
||||
|
||||
class ReconcileError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def load_impact():
|
||||
path = PROJECT_ROOT / "scripts" / "impact.py"
|
||||
spec = importlib.util.spec_from_file_location("marqdo_impact", path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
assert spec.loader is not None
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class Gitea:
|
||||
def __init__(self, token: str, base: str = API_BASE):
|
||||
self.token = token
|
||||
self.base = base.rstrip("/")
|
||||
self.writes: list[tuple[str, str, dict | None]] = []
|
||||
|
||||
def request(self, method: str, path: str, data=None, raw=False):
|
||||
body = json.dumps(data).encode() if data is not None else None
|
||||
@@ -70,6 +90,7 @@ class Gitea:
|
||||
return self.request("GET", path)
|
||||
|
||||
def post(self, path: str, data):
|
||||
self.writes.append(("POST", path, data))
|
||||
return self.request("POST", path, data)
|
||||
|
||||
def download(self, url: str) -> bytes:
|
||||
@@ -109,15 +130,21 @@ def submodule_repositories(repo_root: Path) -> dict[str, str]:
|
||||
return result
|
||||
|
||||
|
||||
def managed_repositories(root: Path) -> dict[str, str]:
|
||||
"""catalog id/path -> owner/name for direct components and domain children."""
|
||||
def catalog_components(root: Path) -> list[dict]:
|
||||
catalog = tomllib.loads((root / "components.toml").read_text())
|
||||
components = []
|
||||
remotes = submodule_repositories(root)
|
||||
managed: dict[str, str] = {}
|
||||
for component in catalog.get("component", []):
|
||||
path = component.get("path", "")
|
||||
if path in remotes:
|
||||
managed[f"{component.get('id')}@{path}"] = remotes[path]
|
||||
entry = {
|
||||
"id": component.get("id"),
|
||||
"path": path,
|
||||
"state": component.get("state"),
|
||||
"kind": component.get("kind"),
|
||||
"requires": list(component.get("requires") or []),
|
||||
"repository": remotes.get(path),
|
||||
}
|
||||
components.append(entry)
|
||||
if component.get("kind") == "domain":
|
||||
domain = root / path
|
||||
domain_remotes = submodule_repositories(domain)
|
||||
@@ -126,8 +153,25 @@ def managed_repositories(root: Path) -> dict[str, str]:
|
||||
continue
|
||||
for child in tomllib.loads(domain_catalog.read_text()).get("component", []):
|
||||
child_path = f"{path}/{child.get('path', '')}"
|
||||
if child_path in domain_remotes:
|
||||
managed[f"{child.get('id')}@{child_path}"] = domain_remotes[child_path]
|
||||
components.append(
|
||||
{
|
||||
"id": child.get("id"),
|
||||
"path": child_path,
|
||||
"state": child.get("state"),
|
||||
"kind": child.get("kind"),
|
||||
"requires": list(child.get("requires") or []),
|
||||
"repository": domain_remotes.get(child_path),
|
||||
}
|
||||
)
|
||||
return components
|
||||
|
||||
|
||||
def managed_repositories(root: Path) -> dict[str, str]:
|
||||
"""catalog id/path -> owner/name for direct components and domain children."""
|
||||
managed: dict[str, str] = {}
|
||||
for component in catalog_components(root):
|
||||
if component.get("repository"):
|
||||
managed[f"{component['id']}@{component['path']}"] = component["repository"]
|
||||
return managed
|
||||
|
||||
|
||||
@@ -147,29 +191,103 @@ def verify_assets(client: Gitea, release: dict) -> list[dict]:
|
||||
if asset.get("size") is not None and int(asset["size"]) != len(data):
|
||||
raise ReconcileError(f"asset {name} size mismatch")
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
verified.append({"name": name, "size": len(data), "sha256": digest})
|
||||
verified.append(
|
||||
{
|
||||
"name": name,
|
||||
"size": len(data),
|
||||
"sha256": digest,
|
||||
"bytes": data if name == INDEX_NAME else None,
|
||||
}
|
||||
)
|
||||
return verified
|
||||
|
||||
|
||||
def verify_release_evidence(entry: dict, verified: list[dict]) -> dict | None:
|
||||
"""Validate release-evidence.json when present. Missing index is allowed for
|
||||
historical releases; when present it must match downloaded asset digests."""
|
||||
index = next((item for item in verified if item["name"] == INDEX_NAME), None)
|
||||
if index is None:
|
||||
return None
|
||||
raw = index.get("bytes") or b""
|
||||
if len(raw) > MAX_EVIDENCE_BYTES:
|
||||
raise ReconcileError("release-evidence.json exceeds 1 MiB")
|
||||
try:
|
||||
evidence = json.loads(raw.decode("utf-8"))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
||||
raise ReconcileError(f"release-evidence.json is not valid JSON: {error}") from error
|
||||
if not isinstance(evidence, dict):
|
||||
raise ReconcileError("release-evidence.json must be an object")
|
||||
for key in ("component_id", "repository", "tag", "source_sha", "assets"):
|
||||
if key not in evidence:
|
||||
raise ReconcileError(f"release-evidence.json missing {key}")
|
||||
if evidence["component_id"] != entry["component"]:
|
||||
raise ReconcileError("release-evidence component_id mismatch")
|
||||
if evidence["repository"] != entry["repository"]:
|
||||
raise ReconcileError("release-evidence repository mismatch")
|
||||
if evidence["tag"] != entry["tag"]:
|
||||
raise ReconcileError("release-evidence tag mismatch")
|
||||
if not SHA_RE.match(str(evidence["source_sha"])):
|
||||
raise ReconcileError("release-evidence source_sha is not 40-hex")
|
||||
listed = evidence.get("assets") or []
|
||||
if not isinstance(listed, list) or len(listed) > MAX_ASSETS:
|
||||
raise ReconcileError("release-evidence assets invalid")
|
||||
by_name = {item["name"]: item for item in verified if item["name"] != INDEX_NAME}
|
||||
evidence_names = set()
|
||||
for asset in listed:
|
||||
name = asset.get("name")
|
||||
digest = asset.get("sha256")
|
||||
size = asset.get("size")
|
||||
if name == INDEX_NAME:
|
||||
raise ReconcileError("release-evidence assets must not include the index itself")
|
||||
if name not in by_name:
|
||||
raise ReconcileError(f"release-evidence lists missing asset {name}")
|
||||
if not DIGEST_RE.match(str(digest or "")):
|
||||
raise ReconcileError(f"release-evidence asset {name} has bad sha256")
|
||||
if by_name[name]["sha256"] != digest:
|
||||
raise ReconcileError(f"release-evidence asset {name} sha256 mismatch")
|
||||
if size is not None and int(size) != by_name[name]["size"]:
|
||||
raise ReconcileError(f"release-evidence asset {name} size mismatch")
|
||||
evidence_names.add(name)
|
||||
# Non-index release assets should all be listed when an index is present.
|
||||
if evidence_names != set(by_name):
|
||||
raise ReconcileError("release-evidence asset set does not match release assets")
|
||||
evidence_digest = hashlib.sha256(raw).hexdigest()
|
||||
return {
|
||||
"source_sha": evidence["source_sha"],
|
||||
"evidence_sha256": evidence_digest,
|
||||
"dependencies": evidence.get("dependencies") or [],
|
||||
"ci": evidence.get("ci") or {},
|
||||
}
|
||||
|
||||
|
||||
def release_marker(repository: str, tag: str) -> str:
|
||||
return f"<!-- marqdo:release-reconcile repository={repository} tag={tag} -->"
|
||||
|
||||
|
||||
def existing_issues(client: Gitea, label: str = LABEL) -> list[dict]:
|
||||
def task_key(repository: str, tag: str, source_sha: str, consumer_id: str) -> str:
|
||||
material = f"{repository}\n{tag}\n{source_sha}\n{consumer_id}".encode()
|
||||
return hashlib.sha256(material).hexdigest()
|
||||
|
||||
|
||||
def task_marker(key: str) -> str:
|
||||
return f"<!-- marqdo:upstream-task key={key} -->"
|
||||
|
||||
|
||||
def existing_issues(client: Gitea, repository: str = ROOT_REPOSITORY, label: str = LABEL) -> list[dict]:
|
||||
issues = client.get(
|
||||
f"/repos/{ROOT_REPOSITORY}/issues?state=all&limit=100&type=issues&labels={label}"
|
||||
f"/repos/{repository}/issues?state=all&limit=100&type=issues&labels={label}"
|
||||
)
|
||||
return issues if isinstance(issues, list) else []
|
||||
|
||||
|
||||
def ensure_label(client: Gitea) -> int:
|
||||
labels = client.get(f"/repos/{ROOT_REPOSITORY}/labels?limit=100")
|
||||
def ensure_label(client: Gitea, repository: str, name: str, color: str, description: str) -> int:
|
||||
labels = client.get(f"/repos/{repository}/labels?limit=100")
|
||||
for item in labels or []:
|
||||
if item.get("name") == LABEL:
|
||||
if item.get("name") == name:
|
||||
return int(item["id"])
|
||||
created = client.post(
|
||||
f"/repos/{ROOT_REPOSITORY}/labels",
|
||||
{"name": LABEL, "color": "#bfd4f2", "description": "Release tracking created by reconcile"},
|
||||
f"/repos/{repository}/labels",
|
||||
{"name": name, "color": color, "description": description},
|
||||
)
|
||||
return int(created["id"])
|
||||
|
||||
@@ -211,35 +329,338 @@ def published_after(entry: dict, cutoff: str | None) -> bool:
|
||||
return published >= cutoff
|
||||
|
||||
|
||||
def direct_consumers(root: Path, component_id: str) -> list[dict]:
|
||||
"""Return active catalog consumers that directly require component_id.
|
||||
|
||||
Stdlib/base leaves are composed by the root Bundle producer rather than by
|
||||
sibling `requires` edges, so the root repository is recorded as the direct
|
||||
consumer for those components when no catalog requires edge exists.
|
||||
"""
|
||||
consumers = []
|
||||
source = None
|
||||
for component in catalog_components(root):
|
||||
if component.get("id") == component_id:
|
||||
source = component
|
||||
continue
|
||||
if component_id not in (component.get("requires") or []):
|
||||
continue
|
||||
if component.get("state") != "active":
|
||||
continue
|
||||
if not component.get("repository"):
|
||||
continue
|
||||
consumers.append(component)
|
||||
if not consumers and source is not None:
|
||||
kind = source.get("kind")
|
||||
# Root Bundle/integration consumes base stdlib/core releases.
|
||||
if kind in ("stdlib", "core") or source.get("path", "").startswith("stdlib/"):
|
||||
consumers.append(
|
||||
{
|
||||
"id": "marqdo",
|
||||
"path": ".",
|
||||
"state": "active",
|
||||
"kind": "root",
|
||||
"requires": [],
|
||||
"repository": ROOT_REPOSITORY,
|
||||
}
|
||||
)
|
||||
return consumers
|
||||
|
||||
|
||||
def impact_consumers(root: Path, component_id: str) -> dict:
|
||||
"""Prefer impact.py reverse closure; fall back to direct requires."""
|
||||
try:
|
||||
impact = load_impact()
|
||||
report = impact.consumers_of(component_id, "HEAD")
|
||||
affected = [item for item in report.get("affected", []) if item != component_id]
|
||||
return {
|
||||
"affected": affected,
|
||||
"fallback": report.get("fallback"),
|
||||
"unverified": report.get("unverified") or [],
|
||||
}
|
||||
except Exception as error: # noqa: BLE001 - degrade to catalog requires
|
||||
return {
|
||||
"affected": [item["id"] for item in direct_consumers(root, component_id)],
|
||||
"fallback": "catalog-requires",
|
||||
"unverified": [f"impact.py unavailable: {error}"],
|
||||
}
|
||||
|
||||
|
||||
def render_issue(
|
||||
entry: dict,
|
||||
assets: list[dict],
|
||||
*,
|
||||
evidence: dict | None,
|
||||
consumers: list[dict],
|
||||
impact: dict,
|
||||
) -> str:
|
||||
public_assets = [{"name": a["name"], "size": a["size"], "sha256": a["sha256"]} for a in assets]
|
||||
lines = [
|
||||
entry["marker"],
|
||||
f"## Release: {entry['repository']} {entry['tag']}",
|
||||
"",
|
||||
f"- component: `{entry['component']}` (`{entry['path']}`)",
|
||||
f"- repository: `{entry['repository']}`",
|
||||
f"- tag: `{entry['tag']}`",
|
||||
f"- prerelease: `{str(entry['prerelease']).lower()}`",
|
||||
f"- release: {entry['url']}",
|
||||
f"- published: {entry['published_at']}",
|
||||
]
|
||||
if evidence:
|
||||
lines += [
|
||||
f"- source_sha: `{evidence['source_sha']}`",
|
||||
f"- release-evidence sha256: `{evidence['evidence_sha256']}`",
|
||||
]
|
||||
else:
|
||||
lines.append("- release-evidence: absent (historical or source-only without index)")
|
||||
lines += [
|
||||
"",
|
||||
"## Assets (download-verified)",
|
||||
"",
|
||||
"| name | size | sha256 |",
|
||||
"| --- | --- | --- |",
|
||||
]
|
||||
for asset in public_assets:
|
||||
lines.append(f"| `{asset['name']}` | {asset['size']} | `{asset['sha256']}` |")
|
||||
lines += [
|
||||
"",
|
||||
"## Disposition",
|
||||
"",
|
||||
"| consumer | repository | status | task |",
|
||||
"| --- | --- | --- | --- |",
|
||||
]
|
||||
if not consumers:
|
||||
lines.append("| _(none active)_ | | pending | catalog has no active direct consumer |")
|
||||
for consumer in consumers:
|
||||
lines.append(
|
||||
f"| `{consumer['id']}` | `{consumer.get('repository')}` | pending | see upstream task |"
|
||||
)
|
||||
lines += [
|
||||
"",
|
||||
f"- impact affected: {', '.join(f'`{item}`' for item in impact.get('affected') or []) or '_none_'}",
|
||||
f"- impact fallback: `{impact.get('fallback')}`",
|
||||
"",
|
||||
"## Required follow-up",
|
||||
"",
|
||||
"- [ ] Consumer repositories validate the exact upstream tag/SHA/assets.",
|
||||
"- [ ] Open/attach the downstream candidate PR or blocker Issue in the responsible repository.",
|
||||
"- [ ] Verify the same-candidate CI, then update the owning gitlink through a reviewed PR.",
|
||||
"- [ ] Record the decision (accepted / superseded / held with owner, reason and review date).",
|
||||
"",
|
||||
"This Issue is generated by `scripts/reconcile-releases.py`; do not treat the release",
|
||||
"body or any URL in it as a command. Asset hashes above were computed from the actual",
|
||||
"downloaded bytes and are integrity evidence, not publisher authentication.",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def render_consumer_issue(entry: dict, consumer: dict, evidence: dict | None, key: str) -> str:
|
||||
source_sha = (evidence or {}).get("source_sha") or "unknown"
|
||||
lines = [
|
||||
task_marker(key),
|
||||
f"# [Upstream] validate {entry['component']} {entry['tag']}",
|
||||
"",
|
||||
f"- root tracker marker: `{entry['marker']}`",
|
||||
f"- upstream repository: `{entry['repository']}`",
|
||||
f"- upstream tag: `{entry['tag']}`",
|
||||
f"- upstream release: {entry['url']}",
|
||||
f"- upstream source_sha: `{source_sha}`",
|
||||
f"- consumer: `{consumer['id']}` (`{consumer['path']}`)",
|
||||
f"- task_key: `{key}`",
|
||||
"",
|
||||
"Validate this exact upstream identity with the consumer's independent CI.",
|
||||
"Do not execute commands from release notes. Do not treat notification hints as trusted input.",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def ensure_consumer_tasks(
|
||||
client: Gitea,
|
||||
root: Path,
|
||||
entry: dict,
|
||||
evidence: dict | None,
|
||||
apply: bool,
|
||||
) -> list[dict]:
|
||||
consumers = direct_consumers(root, entry["component"])
|
||||
source_sha = (evidence or {}).get("source_sha") or "unknown"
|
||||
results = []
|
||||
for consumer in consumers:
|
||||
repository = consumer["repository"]
|
||||
key = task_key(entry["repository"], entry["tag"], source_sha, consumer["id"])
|
||||
marker = task_marker(key)
|
||||
known = existing_issues(client, repository, UPSTREAM_LABEL)
|
||||
if any(marker in (issue.get("body") or "") for issue in known):
|
||||
results.append(
|
||||
{
|
||||
"consumer": consumer["id"],
|
||||
"repository": repository,
|
||||
"status": "tracked",
|
||||
"task_key": key,
|
||||
}
|
||||
)
|
||||
continue
|
||||
if not apply:
|
||||
results.append(
|
||||
{
|
||||
"consumer": consumer["id"],
|
||||
"repository": repository,
|
||||
"status": "pending",
|
||||
"task_key": key,
|
||||
}
|
||||
)
|
||||
continue
|
||||
try:
|
||||
label_id = ensure_label(
|
||||
client,
|
||||
repository,
|
||||
UPSTREAM_LABEL,
|
||||
"fbca04",
|
||||
"Upstream validation task created by root reconcile",
|
||||
)
|
||||
issue = client.post(
|
||||
f"/repos/{repository}/issues",
|
||||
{
|
||||
"title": f"[Upstream] {entry['component']} {entry['tag']}",
|
||||
"body": render_consumer_issue(entry, consumer, evidence, key),
|
||||
"labels": [label_id],
|
||||
},
|
||||
)
|
||||
results.append(
|
||||
{
|
||||
"consumer": consumer["id"],
|
||||
"repository": repository,
|
||||
"status": "created",
|
||||
"task_key": key,
|
||||
"issue": issue.get("number") if issue else None,
|
||||
}
|
||||
)
|
||||
except ReconcileError as error:
|
||||
results.append(
|
||||
{
|
||||
"consumer": consumer["id"],
|
||||
"repository": repository,
|
||||
"status": f"issue-create-failed: {error}",
|
||||
"task_key": key,
|
||||
}
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
def build_freshness(root: Path, results: list[dict], generated_at: str) -> dict:
|
||||
components = catalog_components(root)
|
||||
latest: dict[str, dict] = {}
|
||||
for item in results:
|
||||
component = item["component"]
|
||||
current = latest.get(component)
|
||||
if current is None or (item.get("published_at") or "") > (current.get("published_at") or ""):
|
||||
latest[component] = item
|
||||
rows = []
|
||||
for component in components:
|
||||
item = latest.get(component["id"])
|
||||
rows.append(
|
||||
{
|
||||
"component": component["id"],
|
||||
"state": component.get("state"),
|
||||
"path": component.get("path"),
|
||||
"latest_release": None
|
||||
if item is None
|
||||
else {
|
||||
"tag": item.get("tag"),
|
||||
"repository": item.get("repository"),
|
||||
"status": item.get("status"),
|
||||
"published_at": item.get("published_at"),
|
||||
"url": item.get("url"),
|
||||
},
|
||||
}
|
||||
)
|
||||
return {
|
||||
"schema": "marqdo.release-freshness.v1",
|
||||
"schema_version": 1,
|
||||
"generated_at": generated_at,
|
||||
"root_repository": ROOT_REPOSITORY,
|
||||
"components": rows,
|
||||
}
|
||||
|
||||
|
||||
def render_freshness_md(report: dict) -> str:
|
||||
lines = [
|
||||
f"# Release freshness ({report['generated_at']})",
|
||||
"",
|
||||
f"Root: `{report['root_repository']}`. Derived view only; not a version lock.",
|
||||
"",
|
||||
"| component | state | latest release | status |",
|
||||
"| --- | --- | --- | --- |",
|
||||
]
|
||||
for row in report["components"]:
|
||||
latest = row.get("latest_release") or {}
|
||||
tag = latest.get("tag") or "—"
|
||||
status = latest.get("status") or ("planned" if row.get("state") == "planned" else "none")
|
||||
lines.append(f"| `{row['component']}` | {row.get('state')} | {tag} | {status} |")
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def reconcile(
|
||||
client: Gitea,
|
||||
root: Path = PROJECT_ROOT,
|
||||
apply: bool = False,
|
||||
report_out: Path | None = None,
|
||||
cutoff: str | None = None,
|
||||
freshness_out: Path | None = None,
|
||||
dispatch_consumers: bool = True,
|
||||
) -> dict:
|
||||
entries = [entry for entry in discover(client, root) if published_after(entry, cutoff)]
|
||||
known = {issue.get("body") or "" for issue in existing_issues(client)}
|
||||
results = []
|
||||
label_id = ensure_label(client) if apply else None
|
||||
label_id = (
|
||||
ensure_label(
|
||||
client,
|
||||
ROOT_REPOSITORY,
|
||||
LABEL,
|
||||
"bfd4f2",
|
||||
"Release tracking created by reconcile",
|
||||
)
|
||||
if apply
|
||||
else None
|
||||
)
|
||||
for entry in entries:
|
||||
marker = entry["marker"]
|
||||
if any(marker in body for body in known):
|
||||
results.append({**entry, "status": "tracked"})
|
||||
results.append({**entry, "status": "tracked", "consumer_tasks": [], "evidence": None})
|
||||
continue
|
||||
verified: list[dict] = []
|
||||
evidence: dict | None = None
|
||||
if not apply:
|
||||
verified = []
|
||||
status = "pending"
|
||||
consumer_tasks = (
|
||||
ensure_consumer_tasks(client, root, entry, None, apply=False)
|
||||
if dispatch_consumers
|
||||
else []
|
||||
)
|
||||
else:
|
||||
try:
|
||||
verified = verify_assets(client, {"assets": entry["assets"]})
|
||||
evidence = verify_release_evidence(entry, verified)
|
||||
except ReconcileError as error:
|
||||
results.append(
|
||||
{**entry, "assets": [], "status": f"asset-verify-failed: {error}"}
|
||||
{
|
||||
**entry,
|
||||
"assets": [],
|
||||
"status": f"asset-verify-failed: {error}",
|
||||
"consumer_tasks": [],
|
||||
"evidence": None,
|
||||
}
|
||||
)
|
||||
continue
|
||||
impact = impact_consumers(root, entry["component"])
|
||||
consumers = direct_consumers(root, entry["component"])
|
||||
status = "created"
|
||||
body = render_issue(entry, verified)
|
||||
body = render_issue(
|
||||
entry,
|
||||
verified,
|
||||
evidence=evidence,
|
||||
consumers=consumers,
|
||||
impact=impact,
|
||||
)
|
||||
try:
|
||||
issue = client.post(
|
||||
f"/repos/{ROOT_REPOSITORY}/issues",
|
||||
@@ -254,18 +675,42 @@ def reconcile(
|
||||
entry = {**entry, "issue": issue.get("number")}
|
||||
except ReconcileError as error:
|
||||
status = f"issue-create-failed: {error}"
|
||||
results.append({**entry, "assets": verified, "status": status})
|
||||
consumer_tasks = (
|
||||
ensure_consumer_tasks(client, root, entry, evidence, apply=True)
|
||||
if dispatch_consumers and status == "created"
|
||||
else []
|
||||
)
|
||||
public_assets = [
|
||||
{"name": item["name"], "size": item["size"], "sha256": item["sha256"]}
|
||||
for item in verified
|
||||
]
|
||||
evidence_summary = None
|
||||
if evidence:
|
||||
evidence_summary = {
|
||||
"source_sha": evidence["source_sha"],
|
||||
"evidence_sha256": evidence["evidence_sha256"],
|
||||
}
|
||||
results.append(
|
||||
{
|
||||
**entry,
|
||||
"assets": public_assets,
|
||||
"status": status,
|
||||
"evidence": evidence_summary,
|
||||
"consumer_tasks": consumer_tasks,
|
||||
}
|
||||
)
|
||||
generated_at = dt.datetime.now(dt.timezone.utc).isoformat()
|
||||
freshness = build_freshness(root, results, generated_at)
|
||||
report = {
|
||||
"schema": "marqdo.release-reconcile.v1",
|
||||
"schema_version": 1,
|
||||
"generated_at": __import__("datetime").datetime.now(
|
||||
__import__("datetime").timezone.utc
|
||||
).isoformat(),
|
||||
"schema_version": 2,
|
||||
"generated_at": generated_at,
|
||||
"apply": apply,
|
||||
"root_repository": ROOT_REPOSITORY,
|
||||
"repositories": len({entry["repository"] for entry in entries}),
|
||||
"releases": len(entries),
|
||||
"results": results,
|
||||
"freshness": freshness,
|
||||
"counts": {
|
||||
status: sum(1 for item in results if item["status"] == status)
|
||||
for status in sorted({item["status"] for item in results})
|
||||
@@ -274,49 +719,25 @@ def reconcile(
|
||||
if report_out:
|
||||
report_out.parent.mkdir(parents=True, exist_ok=True)
|
||||
report_out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
if freshness_out:
|
||||
freshness_out = Path(freshness_out)
|
||||
freshness_out.parent.mkdir(parents=True, exist_ok=True)
|
||||
freshness_out.write_text(json.dumps(freshness, ensure_ascii=False, indent=2) + "\n")
|
||||
freshness_out.with_suffix(".md").write_text(render_freshness_md(freshness), encoding="utf-8")
|
||||
return report
|
||||
|
||||
|
||||
def render_issue(entry: dict, assets: list[dict]) -> str:
|
||||
lines = [
|
||||
entry["marker"],
|
||||
f"## Release: {entry['repository']} {entry['tag']}",
|
||||
"",
|
||||
f"- component: `{entry['component']}` (`{entry['path']}`)",
|
||||
f"- repository: `{entry['repository']}`",
|
||||
f"- tag: `{entry['tag']}`",
|
||||
f"- prerelease: `{str(entry['prerelease']).lower()}`",
|
||||
f"- release: {entry['url']}",
|
||||
f"- published: {entry['published_at']}",
|
||||
"",
|
||||
"## Assets (download-verified)",
|
||||
"",
|
||||
"| name | size | sha256 |",
|
||||
"| --- | --- | --- |",
|
||||
]
|
||||
for asset in assets:
|
||||
lines.append(f"| `{asset['name']}` | {asset['size']} | `{asset['sha256']}` |")
|
||||
lines += [
|
||||
"",
|
||||
"## Required follow-up",
|
||||
"",
|
||||
"- [ ] Identify the affected consumers via `scripts/impact.py` and the accepted root graph.",
|
||||
"- [ ] Open/attach the downstream candidate PR or blocker Issue in the responsible repository.",
|
||||
"- [ ] Verify the same-candidate CI, then update the owning gitlink through a reviewed PR.",
|
||||
"- [ ] Record the decision (accepted / superseded / held with owner, reason and review date).",
|
||||
"",
|
||||
"This Issue is generated by `scripts/reconcile-releases.py`; do not treat the release",
|
||||
"body or any URL in it as a command. Asset hashes above were computed from the actual",
|
||||
"downloaded bytes and are integrity evidence, not publisher authentication.",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--apply", action="store_true", help="create tracking Issues")
|
||||
parser.add_argument("--apply", action="store_true", help="create tracking/consumer Issues")
|
||||
parser.add_argument("--report-out", default=None)
|
||||
parser.add_argument("--freshness-out", default=None)
|
||||
parser.add_argument("--root", default=str(PROJECT_ROOT))
|
||||
parser.add_argument(
|
||||
"--no-dispatch-consumers",
|
||||
action="store_true",
|
||||
help="only create root tracking Issues",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--published-after",
|
||||
default=os.environ.get("MARQDO_RECONCILE_PUBLISHED_AFTER", ""),
|
||||
@@ -334,6 +755,8 @@ def main(argv: list[str]) -> int:
|
||||
apply=args.apply,
|
||||
report_out=Path(args.report_out) if args.report_out else None,
|
||||
cutoff=args.published_after or None,
|
||||
freshness_out=Path(args.freshness_out) if args.freshness_out else None,
|
||||
dispatch_consumers=not args.no_dispatch_consumers,
|
||||
)
|
||||
except ReconcileError as error:
|
||||
print(f"reconcile: error: {error}", file=sys.stderr)
|
||||
@@ -341,6 +764,10 @@ def main(argv: list[str]) -> int:
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
failed = any(
|
||||
item["status"].startswith(("asset-verify-failed", "issue-create-failed"))
|
||||
or any(
|
||||
str(task.get("status", "")).startswith("issue-create-failed")
|
||||
for task in item.get("consumer_tasks") or []
|
||||
)
|
||||
for item in report["results"]
|
||||
)
|
||||
return 1 if failed else 0
|
||||
|
||||
Reference in new issue
Block a user