From 43fa9008a948e0d8d3b1496195e1d470f5946017 Mon Sep 17 00:00:00 2001 From: cflmy Date: Fri, 27 Nov 2026 23:27:19 +0800 Subject: [PATCH] Dispatch verified consumer tasks through native Woodpecker --- .woodpecker/reconcile.yml | 2 + docs/DEVELOPMENT.md | 2 + scripts/reconcile-releases.py | 145 ++++++++++++++++--- tests/integration/test_reconcile_releases.py | 46 ++++++ 4 files changed, 174 insertions(+), 21 deletions(-) diff --git a/.woodpecker/reconcile.yml b/.woodpecker/reconcile.yml index 5b96ce3..0f1d65c 100644 --- a/.woodpecker/reconcile.yml +++ b/.woodpecker/reconcile.yml @@ -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 diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 5e16479..af2a943 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -84,6 +84,8 @@ bash scripts/integration.sh # 生态候选:真实 CLI 制品 + 正式发布对账使用 `python3 scripts/reconcile-releases.py --plan --published-after `。从固定根及领域 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 及批准后的晋升基于各自的真实结果。 ## 发行与回滚 diff --git a/scripts/reconcile-releases.py b/scripts/reconcile-releases.py index 965aac7..3bd9dc3 100755 --- a/scripts/reconcile-releases.py +++ b/scripts/reconcile-releases.py @@ -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"