Merge pull request 'CI-08: dispatch verified consumer tasks using native Woodpecker' (#44) from codex/issue-10-native-dispatch into main
Merge PR #44: dispatch verified consumer tasks through native Woodpecker
This commit was merged in pull request #44.
This commit is contained in:
commit
d28ed9d00d
4 files changed
+174
-21
No files matched your search
@@ -15,6 +15,8 @@ steps:
|
||||
environment:
|
||||
MARQDO_GIT_TOKEN:
|
||||
from_secret: gitea_reconcile_token
|
||||
MARQDO_WOODPECKER_DISPATCH_TOKEN:
|
||||
from_secret: woodpecker_reconcile_token
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
|
||||
@@ -84,6 +84,8 @@ bash scripts/integration.sh # 生态候选:真实 CLI 制品 +
|
||||
|
||||
正式发布对账使用 `python3 scripts/reconcile-releases.py --plan --published-after <ISO-8601 时间>`。从固定根及领域 tree 解析受管仓库,核对 Gitea tag、`release-evidence.json`、同 SHA Woodpecker 组件 CI 和资产字节摘要。根 `reconcile` 工作流从当前受保护的 `main` 串行运行,只检出领域聚合仓,使用 `gitea_reconcile_token` 以专用非管理员账号写追踪工单。`historical-baseline` 表示已登记历史输入,`blocked` 表示发布验证未通过,`tracked` 表示已记录经验证的发布。扫描完整且追踪写入成功时,已报告的发布阻塞保留为 `blocked`,工作流仍成功结束。消费者验收和父级接受均需各自的 CI 与 PR 证据。
|
||||
|
||||
消费者通过已接受 Git 树里的 `.woodpecker/upstream.yml` 接入派发。根只在该消费者的受保护默认分支精确匹配 gitlink 时触发,发送本仓任务编号和幂等键。Woodpecker 原生触发要求项目级 push 权限,该角色同时可以管理该项目的 CI secret。仅把这一角色授予专用非管理员 `marqdo-reconcile` 在已接入的消费者仓,并通过 Woodpecker 登录为该账号生成 token。根仓 `woodpecker_reconcile_token` 限于受保护 `main` 的 manual/cron 配置,部署时核对账号和具体仓权限。触发凭据只在根协调步骤使用,消费者测试无需该凭据。根报告通过已存在的同任务 Woodpecker 流水线识别重复或失联的触发结果。
|
||||
|
||||
对已验证的发布,`--plan` 计算直接 active 消费者的输入摘要。受保护 `--apply` 按发布和消费者登记一条任务,基线变化时在原任务中记录新输入。输入附精确资产、依赖、消费者基线和根追踪编号。下游独立 CI 及批准后的晋升基于各自的真实结果。
|
||||
|
||||
## 发行与回滚
|
||||
|
||||
+124
-21
@@ -59,22 +59,23 @@ class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
|
||||
|
||||
class Gitea:
|
||||
def __init__(self, token: str):
|
||||
def __init__(self, token: str, dispatch_token: str = ""):
|
||||
self.token = token
|
||||
self.dispatch_token = dispatch_token
|
||||
self.opener = urllib.request.build_opener(NoRedirect())
|
||||
|
||||
def open(self, method, url, data=None, authenticated=False):
|
||||
def open(self, method, url, data=None, authorization=None):
|
||||
headers = {}
|
||||
if authenticated and self.token:
|
||||
headers["Authorization"] = f"token {self.token}"
|
||||
if authorization:
|
||||
headers["Authorization"] = authorization
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
request = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
return self.opener.open(request, timeout=30)
|
||||
|
||||
def request(self, method, base, path, data=None, authenticated=False):
|
||||
def request(self, method, base, path, data=None, authorization=None):
|
||||
try:
|
||||
with self.open(method, base + path, data, authenticated) as response:
|
||||
with self.open(method, base + path, data, authorization) as response:
|
||||
payload = response.read(8 * MAX_INDEX_BYTES + 1)
|
||||
require(len(payload) <= 8 * MAX_INDEX_BYTES, "API response exceeds size limit")
|
||||
return json.loads(payload)
|
||||
@@ -84,15 +85,21 @@ class Gitea:
|
||||
raise ApiUnavailable(f"{method} {path}: {error}") from error
|
||||
|
||||
def get(self, path):
|
||||
return self.request("GET", FORGE + "/api/v1", path, authenticated=True)
|
||||
return self.request("GET", FORGE + "/api/v1", path,
|
||||
authorization=f"token {self.token}" if self.token else None)
|
||||
|
||||
def post(self, path, data):
|
||||
return self.request("POST", FORGE + "/api/v1", path,
|
||||
json.dumps(data).encode(), authenticated=True)
|
||||
json.dumps(data).encode(), f"token {self.token}")
|
||||
|
||||
def ci(self, path):
|
||||
return self.request("GET", CI + "/api", path)
|
||||
|
||||
def dispatch_ci(self, path, data=None):
|
||||
return self.request("GET" if data is None else "POST", CI + "/api", path,
|
||||
None if data is None else json.dumps(data).encode(),
|
||||
f"Bearer {self.dispatch_token}")
|
||||
|
||||
def asset(self, path, size, *, index=False):
|
||||
limit = MAX_INDEX_BYTES if index else MAX_ASSET_BYTES
|
||||
require(type(size) is int and 0 < size <= limit, "invalid asset size")
|
||||
@@ -180,12 +187,7 @@ def managed_repositories(root):
|
||||
return revision, graph, managed
|
||||
|
||||
|
||||
def verify_pipeline(client, repository, source_sha, evidence):
|
||||
require(exact_fields(evidence, {"pipeline_number", "url", "source_sha"}),
|
||||
"invalid component CI evidence")
|
||||
number = evidence["pipeline_number"]
|
||||
require(type(number) is int and number > 0 and evidence["source_sha"] == source_sha,
|
||||
"release has no component CI evidence for its exact SHA")
|
||||
def ci_repository(client, repository):
|
||||
repo = client.ci(f"/repos/lookup/{repository}")
|
||||
forge_repo = client.get(f"/repos/{repository}")
|
||||
require(isinstance(repo, dict) and repo.get("full_name") == repository
|
||||
@@ -193,9 +195,19 @@ def verify_pipeline(client, repository, source_sha, evidence):
|
||||
and isinstance(forge_repo, dict) and type(forge_repo.get("id")) is int
|
||||
and repo.get("forge_remote_id") == str(forge_repo["id"]),
|
||||
"CI repository identity mismatch")
|
||||
expected_url = f"{CI}/repos/{repo['id']}/pipeline/{number}"
|
||||
return repo["id"], forge_repo
|
||||
|
||||
|
||||
def verify_pipeline(client, repository, source_sha, evidence):
|
||||
require(exact_fields(evidence, {"pipeline_number", "url", "source_sha"}),
|
||||
"invalid component CI evidence")
|
||||
number = evidence["pipeline_number"]
|
||||
require(type(number) is int and number > 0 and evidence["source_sha"] == source_sha,
|
||||
"release has no component CI evidence for its exact SHA")
|
||||
repo_id, _ = ci_repository(client, repository)
|
||||
expected_url = f"{CI}/repos/{repo_id}/pipeline/{number}"
|
||||
require(evidence["url"] == expected_url, "component CI URL mismatch")
|
||||
pipeline = client.ci(f"/repos/{repo['id']}/pipelines/{number}")
|
||||
pipeline = client.ci(f"/repos/{repo_id}/pipelines/{number}")
|
||||
workflow = "main" if repository == "cflmy/marqdo-cli" else "ci"
|
||||
require(isinstance(pipeline, dict) and pipeline.get("number") == number
|
||||
and pipeline.get("commit") == source_sha and pipeline.get("status") == "success"
|
||||
@@ -425,13 +437,90 @@ def register_consumer_tasks(client, root_sha, entry, issue_cache):
|
||||
task.update(registration="blocked", error=str(error))
|
||||
|
||||
|
||||
def reconcile(client, root=PROJECT_ROOT, apply=False, report_out=None, cutoff=None):
|
||||
def verify_dispatch_identity(client):
|
||||
actor = client.dispatch_ci("/user")
|
||||
require(isinstance(actor, dict) and actor.get("login") == RECONCILE_ACCOUNT
|
||||
and not actor.get("admin") and not actor.get("admin_env"),
|
||||
"dispatch requires the non-admin reconcile account in Woodpecker")
|
||||
|
||||
|
||||
def dispatch_consumer(client, root_sha, task, published_at, can_start):
|
||||
repo_id, forge_repo = ci_repository(client, task["repository"])
|
||||
branch = forge_repo.get("default_branch")
|
||||
require(match(BASENAME, branch), "consumer has an unsupported default branch name")
|
||||
protected = client.get(f"/repos/{task['repository']}/branches/{branch}")
|
||||
require(protected.get("protected") is True
|
||||
and (protected.get("commit") or {}).get("id") == task["baseline_sha"],
|
||||
"consumer default branch is unprotected or differs from the accepted gitlink")
|
||||
ref = urllib.parse.urlencode({"ref": task["baseline_sha"]})
|
||||
try:
|
||||
config = client.get(f"/repos/{task['repository']}/contents/.woodpecker/upstream.yml?{ref}")
|
||||
except ReconcileError as error:
|
||||
if str(error).endswith(": HTTP 404"):
|
||||
task["dispatch_status"] = "no-upstream-workflow"
|
||||
return False
|
||||
raise
|
||||
require(config.get("type") == "file", "consumer upstream workflow is not a repository file")
|
||||
|
||||
api = f"/repos/{repo_id}"
|
||||
permissions = client.dispatch_ci(f"{api}/permissions")
|
||||
require(permissions.get("push") is True and permissions.get("admin") is False,
|
||||
"dispatch needs project-level push permission without project admin")
|
||||
require(type(task["issue"]) is int and task["issue"] > 0, "invalid consumer issue number")
|
||||
key = hashlib.sha256(f"{root_sha}\n{task['key']}".encode()).hexdigest()
|
||||
variables = {"MARQDO_UPSTREAM_ISSUE": str(task["issue"]), "MARQDO_UPSTREAM_TASK": key}
|
||||
|
||||
def corresponds(pipeline):
|
||||
return (type(pipeline.get("number")) is int and pipeline["number"] > 0
|
||||
and pipeline.get("event") == "manual" and pipeline.get("branch") == branch
|
||||
and pipeline.get("selected_workflow") == "upstream"
|
||||
and pipeline.get("author") == RECONCILE_ACCOUNT
|
||||
and pipeline.get("commit") == task["baseline_sha"]
|
||||
and pipeline.get("variables") == variables)
|
||||
|
||||
# Check Woodpecker's actual runs, including an accepted POST whose response
|
||||
# was lost. A failed run remains evidence until the task inputs change.
|
||||
pipelines = f"{api}/pipelines"
|
||||
for page in range(1, MAX_PAGES + 1):
|
||||
query = urllib.parse.urlencode(dict(event="manual", branch=branch, after=published_at,
|
||||
page=page, perPage=PAGE_SIZE))
|
||||
records = client.dispatch_ci(f"{pipelines}?{query}")
|
||||
require(isinstance(records, list) and len(records) <= PAGE_SIZE, "invalid CI pipeline page")
|
||||
existing = next((pipeline for pipeline in records if corresponds(pipeline)), None)
|
||||
if existing or len(records) < PAGE_SIZE:
|
||||
break
|
||||
else:
|
||||
raise ReconcileError("CI pipeline pagination limit reached")
|
||||
started = False
|
||||
if existing is None:
|
||||
if not can_start:
|
||||
task["dispatch_status"] = "queued-for-dispatch"
|
||||
return False
|
||||
verify_root_base(client, root_sha)
|
||||
existing = client.dispatch_ci(pipelines, {"branch": branch, "workflow": "upstream",
|
||||
"variables": variables})
|
||||
require(isinstance(existing, dict) and corresponds(existing),
|
||||
"dispatched pipeline differs from the intended consumer task")
|
||||
started = True
|
||||
task["dispatch_status"] = existing["status"]
|
||||
task["pipeline"] = f"{CI}/repos/{repo_id}/pipeline/{existing['number']}"
|
||||
return started
|
||||
|
||||
|
||||
def reconcile(client, root=PROJECT_ROOT, apply=False, report_out=None, cutoff=None, dispatch=False):
|
||||
root_sha, graph, managed = managed_repositories(root)
|
||||
cutoff_time = timestamp(cutoff) if cutoff else None
|
||||
issues_url = f"/repos/{ROOT_REPOSITORY}/issues"
|
||||
issues = list(pages(client, issues_url, state="all", type="issues", labels=LABEL))
|
||||
if apply:
|
||||
verify_apply_context(client, root_sha)
|
||||
dispatch_status, dispatch_error, starts = "disabled", None, 0
|
||||
if apply and dispatch:
|
||||
try:
|
||||
verify_dispatch_identity(client)
|
||||
dispatch_status = "enabled"
|
||||
except ReconcileError as error:
|
||||
dispatch_status, dispatch_error = "unavailable", str(error)
|
||||
labels = f"/repos/{ROOT_REPOSITORY}/labels"
|
||||
label_id = next((x["id"] for x in pages(client, labels) if x.get("name") == LABEL), None) if apply else None
|
||||
results, errors, consumer_issues = [], {}, {}
|
||||
@@ -506,6 +595,15 @@ def reconcile(client, root=PROJECT_ROOT, apply=False, report_out=None, cutoff=No
|
||||
and entry["status"] in {"created", "pending", "tracked"}
|
||||
and (not trackers or trackers[0]["state"] == "open")):
|
||||
register_consumer_tasks(client, root_sha, entry, consumer_issues)
|
||||
if dispatch_status == "enabled":
|
||||
for task in entry["consumer_tasks"]:
|
||||
if task["status"] != "pending" or task["registration"] != "recorded":
|
||||
continue
|
||||
try:
|
||||
starts += dispatch_consumer(client, root_sha, task, entry["published_at"],
|
||||
can_start=starts < 4)
|
||||
except ReconcileError as error:
|
||||
task.update(dispatch_status="blocked", dispatch_error=str(error))
|
||||
results.append(entry)
|
||||
prefix = f"<!-- marqdo:release-reconcile repository={repository} tag="
|
||||
for issue in issues:
|
||||
@@ -529,10 +627,13 @@ def reconcile(client, root=PROJECT_ROOT, apply=False, report_out=None, cutoff=No
|
||||
"root_repository": ROOT_REPOSITORY, "root_sha": root_sha,
|
||||
"apply": apply, "repositories": len(managed), "releases": len(results),
|
||||
"scan_complete": not errors, "scan_errors": errors, "results": results,
|
||||
"dispatch_status": dispatch_status,
|
||||
"counts": {status: sum(item["status"] == status for item in results)
|
||||
for status in sorted({item["status"] for item in results})},
|
||||
"generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
}
|
||||
if dispatch_error:
|
||||
report["dispatch_error"] = dispatch_error
|
||||
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")
|
||||
@@ -549,6 +650,7 @@ def main(argv):
|
||||
parser.add_argument("--published-after", default=os.environ.get("MARQDO_RECONCILE_PUBLISHED_AFTER"))
|
||||
args = parser.parse_args(argv)
|
||||
token = os.environ.get("MARQDO_GIT_TOKEN", "")
|
||||
dispatch_token = os.environ.get("MARQDO_WOODPECKER_DISPATCH_TOKEN", "")
|
||||
if args.apply and not token:
|
||||
parser.error("--apply requires MARQDO_GIT_TOKEN")
|
||||
try:
|
||||
@@ -557,15 +659,16 @@ def main(argv):
|
||||
except ReconcileError as error:
|
||||
parser.error(str(error))
|
||||
try:
|
||||
report = reconcile(Gitea(token), args.root.resolve(), args.apply,
|
||||
args.report_out, args.published_after)
|
||||
report = reconcile(Gitea(token, dispatch_token), args.root.resolve(), args.apply,
|
||||
args.report_out, args.published_after, dispatch=bool(dispatch_token))
|
||||
except (OSError, ReconcileError) as error:
|
||||
print(f"reconcile: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
return int(not report["scan_complete"] or any(
|
||||
return int(not report["scan_complete"] or report["dispatch_status"] == "unavailable" or any(
|
||||
"tracking_update" in item
|
||||
or any(task.get("registration") == "blocked" for task in item.get("consumer_tasks", []))
|
||||
or any(task.get("registration") == "blocked" or task.get("dispatch_status") == "blocked"
|
||||
for task in item.get("consumer_tasks", []))
|
||||
for item in report["results"]))
|
||||
|
||||
|
||||
|
||||
@@ -140,6 +140,52 @@ class ReconcileTest(unittest.TestCase):
|
||||
def run_scan(self, **kwargs):
|
||||
return reconcile.reconcile(self.forge, **kwargs)
|
||||
|
||||
def test_native_dispatch_reuses_a_run_for_the_same_task_and_root(self):
|
||||
task = {"repository": REPO, "baseline_sha": BASE, "issue": 42, "key": "c" * 64}
|
||||
routes = {
|
||||
f"/repos/{REPO}/branches/master": {"protected": True, "commit": {"id": BASE}},
|
||||
f"/repos/{REPO}/contents/.woodpecker/upstream.yml?ref={BASE}": {"type": "file"},
|
||||
"/repos/cflmy/marqdo/branches/main": {"protected": True, "commit": {"id": BASE}},
|
||||
}
|
||||
runs = []
|
||||
posts = []
|
||||
|
||||
def dispatch(path, data=None):
|
||||
if path == "/repos/8/permissions":
|
||||
return {"push": True, "admin": False}
|
||||
if data is None:
|
||||
self.assertTrue(path.startswith("/repos/8/pipelines?"))
|
||||
return runs
|
||||
self.assertEqual(path, "/repos/8/pipelines")
|
||||
self.assertEqual(data["branch"], "master")
|
||||
self.assertEqual(data["workflow"], "upstream")
|
||||
self.assertEqual(data["variables"]["MARQDO_UPSTREAM_ISSUE"], "42")
|
||||
posts.append(data)
|
||||
runs.append({"number": 15, "status": "pending", "author": ACTOR["login"],
|
||||
"event": "manual", "branch": data["branch"], "commit": BASE,
|
||||
"selected_workflow": data["workflow"], "variables": data["variables"]})
|
||||
return runs[-1]
|
||||
|
||||
with (patch.object(reconcile, "ci_repository", return_value=(8, {"default_branch": "master"})),
|
||||
patch.object(self.forge, "get", side_effect=routes.__getitem__),
|
||||
patch.object(self.forge, "dispatch_ci", side_effect=dispatch, create=True)):
|
||||
self.assertTrue(reconcile.dispatch_consumer(self.forge, BASE, task, PUBLISHED, True))
|
||||
self.assertFalse(reconcile.dispatch_consumer(self.forge, BASE, task, PUBLISHED, True))
|
||||
self.assertEqual(task["pipeline"], f"{reconcile.CI}/repos/8/pipeline/15")
|
||||
self.assertEqual(len(posts), 1)
|
||||
routes[f"/repos/{REPO}/branches/master"]["protected"] = False
|
||||
with self.assertRaisesRegex(reconcile.ReconcileError, "unprotected"):
|
||||
reconcile.dispatch_consumer(self.forge, BASE, task, PUBLISHED, True)
|
||||
self.assertEqual(len(posts), 1)
|
||||
|
||||
def test_dispatch_rejects_owner_or_admin_identity_before_writing_to_ci(self):
|
||||
for identity in ({"login": "cflmy"}, {**ACTOR, "admin": True}):
|
||||
with patch.object(self.forge, "dispatch_ci", return_value=identity, create=True) as ci:
|
||||
report = self.run_scan(apply=True, dispatch=True)
|
||||
ci.assert_called_once_with("/user")
|
||||
self.assertTrue(report["scan_complete"])
|
||||
self.assertEqual(report["dispatch_status"], "unavailable")
|
||||
|
||||
def test_dry_run_fully_verifies_without_writing(self):
|
||||
report = self.run_scan()
|
||||
self.assertEqual(self.forge.writes, [])
|
||||
|
||||
Reference in new issue
Block a user