181 lines
8.6 KiB
Python
181 lines
8.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Coordinate candidate preparation and record independently authored QA evidence."""
|
|
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import sys
|
|
from urllib.error import HTTPError
|
|
|
|
import candidate_release as candidate
|
|
import candidate_runtime as runtime
|
|
import hifox_release_trigger as hfx
|
|
import production_cd as cd
|
|
|
|
STATE = Path.home() / '.local/state/kg-candidate-release'
|
|
CLI = str(Path.home() / '.local/bin/hifox')
|
|
WORKFLOW = candidate.API + '/actions/workflows/prepare-candidate.yml/dispatches?return_run_details=true'
|
|
QA_AUTHORS = {cd.RELEASE_OWNER, '62a66d1e-4311-4b54-8004-bbb03c69c08c', 'bdf4f412-8c3f-45ab-84f4-638c60a43806'}
|
|
WAIT_TEST = 'b59c34ee-94f4-41a8-8577-dea73b2c6414'
|
|
TESTING = 'f8906482-bad7-4af8-9a3b-d52630eff3f7'
|
|
QA_FENCE = re.compile(r'^```kg-qa-v1\s*\n(\{.*?\})\s*\n```\s*$', re.MULTILINE | re.DOTALL)
|
|
|
|
|
|
def task(task_id):
|
|
cd.require(cd.matches(cd.UUID, task_id), 'provide the task UUID')
|
|
obj = hfx.hifox(CLI, 'task', 'view', task_id)
|
|
if not isinstance(obj, dict) or obj.get('id') != task_id or obj.get('spaceId') != cd.SPACE:
|
|
raise cd.CDError('task is outside the release space')
|
|
return obj
|
|
|
|
|
|
def timeline(task_id):
|
|
rows = hfx.hifox(CLI, 'api', 'get', f'/rest/v1/tasks/{task_id}/timeline')
|
|
cd.require(isinstance(rows, list), 'task timeline unavailable')
|
|
return [row for row in rows if row.get('event') == 'commented']
|
|
|
|
|
|
def owner_plan(task_id):
|
|
task(task_id)
|
|
matches = [candidate.FENCE.search(row.get('content') or '') for row in reversed(sorted(
|
|
timeline(task_id), key=lambda row: row.get('createdAt', ''))) if (row.get('actor') or {}).get('id') == cd.RELEASE_OWNER]
|
|
match = next((row for row in matches if row), None)
|
|
if match is None:
|
|
raise cd.CDError('release owner must post a kg-release-v1 plan on the release task')
|
|
plan = json.loads(match[1])
|
|
candidate.check_plan(plan)
|
|
cd.require(plan['task'] == task_id, 'release plan belongs to another task')
|
|
for item in plan['items']:
|
|
requirement = task(item['task'])
|
|
identifier = requirement.get('identifier')
|
|
pr = candidate.read_forge(candidate.API + f'/pulls/{item["pr"]}')
|
|
fields = ' '.join(str(v or '') for v in (pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')))
|
|
cd.require(isinstance(identifier, str) and re.search(rf'(?<![\w-]){re.escape(identifier)}(?!\w)', fields, re.IGNORECASE),
|
|
f"PR #{item['pr']} does not identify its HiFox requirement")
|
|
return plan
|
|
|
|
|
|
def queue(task_id):
|
|
plan = owner_plan(task_id)
|
|
STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
key = cd.acceptance_digest(plan)
|
|
path = STATE / (key + '.dispatch.json')
|
|
with cd.deploy_lock(STATE / 'dispatch.lock'):
|
|
if path.exists():
|
|
result = cd.read_json(cd.immutable_file(path))
|
|
cd.require(result['state'] == 'queued', 'candidate dispatch outcome unknown; reconcile Gitea before retry')
|
|
return result
|
|
conf = Path.home() / '.config/knowledge-governance/qa.json'
|
|
runtime.qa_database(conf)
|
|
cd.record(path, {'state': 'submitting', 'plan': plan})
|
|
result = hfx.forge('POST', WORKFLOW, {'ref': 'main', 'inputs': {'plan': json.dumps(plan), 'mode': 'prepare'}})
|
|
run = str(result.get('workflow_run_id', ''))
|
|
cd.require(cd.matches(hfx.RUN_ID, run), 'missing candidate run ID; reconcile Gitea before retry')
|
|
receipt = {'state': 'queued', 'plan': plan, 'run': run, 'url': f'{cd.FORGE}/{cd.REPO}/actions/runs/{run}'}
|
|
cd.record(path, receipt)
|
|
return receipt
|
|
|
|
|
|
def add_comment(task_id, key, body):
|
|
marker = f'[KG candidate {key}]'
|
|
|
|
def existing():
|
|
return [row for row in timeline(task_id) if marker in (row.get('content') or '')]
|
|
|
|
if not existing():
|
|
hfx.hifox(CLI, 'task', 'comment', task_id, '--body', f'{marker}\n\n{body}')
|
|
rows = existing()
|
|
cd.require(len(rows) == 1 and cd.matches(cd.UUID, rows[0].get('id')) and body in rows[0].get('content', ''),
|
|
'candidate comment not uniquely verified')
|
|
return rows[0]['id']
|
|
|
|
|
|
def publish_candidate(plan, receipt, run):
|
|
body = (f'候选验收地址 {receipt["url"]}\n\n提交 `{receipt["sha"]}`\n\n'
|
|
f'归档 `{receipt["bundle"]}`\n\n'
|
|
f'构建记录 {cd.FORGE}/{cd.REPO}/actions/runs/{run}\n\n'
|
|
f'发布任务 {task(plan["task"])["url"]}')
|
|
key = 'ready ' + receipt['bundle']
|
|
add_comment(plan['task'], key, body)
|
|
for item in plan['items']:
|
|
item_id = item['task']
|
|
status = (task(item_id).get('status') or {}).get('id')
|
|
if status == TESTING:
|
|
cd.require(any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)),
|
|
f'{item_id}: another QA round is already in progress')
|
|
continue
|
|
cd.require(status == WAIT_TEST, f'{item_id}: requirement must be in 待测试')
|
|
add_comment(item_id, key, body)
|
|
cd.require((task(item_id).get('status') or {}).get('id') == WAIT_TEST,
|
|
f'{item_id}: task status changed during candidate handoff')
|
|
hfx.hifox(CLI, 'task', 'edit', item_id, '--status', TESTING)
|
|
cd.require((task(item_id).get('status') or {}).get('id') == TESTING, f'{item_id}: testing status not verified')
|
|
|
|
|
|
def register(task_id):
|
|
plan = owner_plan(task_id)
|
|
directory = STATE / cd.acceptance_digest(plan)
|
|
with cd.deploy_lock(directory / 'registration.lock'):
|
|
receipt = cd.read_json(cd.immutable_file(directory / 'ready.json'))
|
|
cd.require(receipt.get('mode') == 'acceptance', 'isolated smoke results are ineligible for publication')
|
|
runtime.attest(directory / 'bundle', receipt)
|
|
reports = {}
|
|
tasks = [item['task'] for item in plan['items']] + [task_id]
|
|
for item_id in tasks:
|
|
obj = task(item_id)
|
|
rows = sorted(timeline(item_id), key=lambda row: row.get('createdAt', ''), reverse=True)
|
|
for row in rows:
|
|
match = QA_FENCE.search(row.get('content') or '')
|
|
if not match or (row.get('actor') or {}).get('id') not in QA_AUTHORS:
|
|
continue
|
|
result = json.loads(match[1])
|
|
if result.get('bundle') == receipt['bundle']:
|
|
reports[item_id] = (row, result)
|
|
break
|
|
if item_id in reports:
|
|
row = reports[item_id][0]
|
|
cd.require(cd.matches(cd.UUID, row.get('id')) and obj.get('url', '').startswith('https://app.hifox.com/'),
|
|
'invalid QA evidence link')
|
|
candidate.check_qa(plan, receipt, reports, QA_AUTHORS)
|
|
fresh = owner_plan(task_id)
|
|
cd.require(fresh == plan, 'release plan changed during registration')
|
|
rel = task(task_id)
|
|
cd.require((rel.get('status') or {}).get('id') not in (cd.READY, cd.PUBLISHED),
|
|
'register QA before the owner moves the release task to 待发布')
|
|
sha, bundle = receipt['sha'], receipt['bundle']
|
|
links = '\n'.join(f'- {task(item)["url"]}#comment-{reports[item][0]["id"]}' for item in tasks)
|
|
body = f'批次验收通过\n\n提交 `{sha}`\n\n归档 `{bundle}`\n\n需求验收与批次回归报告\n{links}'
|
|
comment = add_comment(task_id, 'acceptance ' + bundle, body)
|
|
acceptance = {'verdict': 'passed', 'sha': sha, 'bundle': bundle, 'evidence': rel['url'] + '#comment-' + comment}
|
|
if cd.metadata(task(task_id), 'cd_acceptance') != acceptance:
|
|
hfx.hifox(CLI, 'task', 'metadata', 'set', task_id, 'cd_acceptance', json.dumps(json.dumps(acceptance)))
|
|
cd.require(cd.metadata(task(task_id), 'cd_acceptance') == acceptance, 'acceptance writeback not verified')
|
|
return acceptance
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('action', choices=('prepare', 'register', 'status'))
|
|
parser.add_argument('task')
|
|
args = parser.parse_args()
|
|
if args.action == 'prepare':
|
|
result = queue(args.task)
|
|
elif args.action == 'register':
|
|
result = register(args.task)
|
|
else:
|
|
plan = owner_plan(args.task)
|
|
key = cd.acceptance_digest(plan)
|
|
results = [STATE / key / 'ready.json', STATE / (key + '.dispatch.json')]
|
|
result = next((cd.read_json(cd.immutable_file(p)) for p in results if p.exists()), {'state': 'unprepared'})
|
|
print(json.dumps(result, ensure_ascii=False))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except HTTPError as exc:
|
|
sys.exit(f'Candidate coordinator: HTTP {exc.code}; reconcile Gitea before retry')
|
|
except (cd.CDError, runtime.qa_env.QAError, OSError, ValueError) as exc:
|
|
sys.exit(f'Candidate coordinator: {exc}')
|