Files
cutdex/tool/gitea/release_transport.py
lingjhf 4346d9330a
Gitea CI / Build Windows x64 app (pull_request) Successful in 5m56s
Gitea CI / Assemble and validate CI artifacts (pull_request) Successful in 53s
Gitea CI / Gitea CI passed (pull_request) Successful in 2s
Gitea CI / Check code and tests (pull_request) Successful in 5m49s
Gitea CI / Build Android APK (pull_request) Successful in 3m30s
Gitea CI / Audit and package Windows x64 (pull_request) Successful in 1m4s
fix(release): keep signed CI archive redirects on loopback
2026-10-06 16:41:45 +08:00

142 lines
6.2 KiB
Python

"""Gitea HTTP and bounded transfer helpers for staged release publication."""
import hashlib
from concurrent.futures import ThreadPoolExecutor
import http.client
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
SERVER = 'https://git.orangraph.com'
RETRY_DELAYS = (5, 15)
def transport_url(url):
"""Route this host's Gitea traffic locally when the runner opts in."""
internal = os.environ.get('CUTDEX_GITEA_INTERNAL_URL', '').rstrip('/')
if not internal:
return url
if internal != 'http://127.0.0.1:3000':
raise ValueError('Unexpected internal Gitea endpoint')
parsed = urllib.parse.urlparse(url)
if parsed.scheme != 'https' or parsed.netloc != 'git.orangraph.com':
raise ValueError('Unexpected Gitea transport origin')
return urllib.parse.urlunparse(parsed._replace(scheme='http', netloc='127.0.0.1:3000'))
def transient(error):
if isinstance(error, urllib.error.HTTPError):
if error.code == 404 and error.headers.get('Content-Type', '').split(';')[0].lower() == 'text/html':
body = error.read(64 * 1024).lower()
# FRP returns this page while the vhost tunnel is unavailable.
# A normal Gitea API 404 remains a permanent error.
return b'github.com/fatedier/frp' in body and b'not found' in body
return error.code in {408, 429, 500, 502, 503, 504}
return isinstance(error, (urllib.error.URLError, TimeoutError, ConnectionError,
http.client.IncompleteRead))
def retry_read(operation):
"""Retry safe attachment-list reads, without retrying permanent HTTP errors."""
for attempt in range(len(RETRY_DELAYS) + 1):
try:
return operation()
except Exception as error:
if not transient(error) or attempt == len(RETRY_DELAYS):
raise
print(f'Attachment list temporarily unavailable; retrying in {RETRY_DELAYS[attempt]}s.', file=sys.stderr)
time.sleep(RETRY_DELAYS[attempt])
def request(url, data=None, method=None, content_type='application/json'):
endpoint = transport_url(url)
headers = {'Authorization': 'token ' + os.environ['GITEA_TOKEN']}
local_archive = (data is None and method in (None, 'GET')
and re.fullmatch(r'/api/v1/repos/[^/]+/[^/]+/actions/artifacts/\d+/zip',
urllib.parse.urlparse(url).path))
if endpoint != url and not local_archive:
# Gitea constructs response links from Host, even when reached locally.
# CI ZIP downloads redirect to a signed raw URL. Keep their local Host
# so urllib follows that redirect locally instead of returning to FRP.
headers['Host'] = 'git.orangraph.com'
if data is not None:
headers['Content-Type'] = content_type
if isinstance(data, dict):
data = json.dumps(data).encode()
req = urllib.request.Request(endpoint, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=300) as response:
body = response.read()
return json.loads(body) if body and 'application/json' in response.headers.get('Content-Type', '') else body
def attachment_url(asset):
url = urllib.parse.urlparse(asset['browser_download_url'])
if url.hostname != 'git.orangraph.com':
raise ValueError('Unexpected attachment host')
return urllib.parse.urlunparse(url._replace(scheme='https', netloc='git.orangraph.com'))
def fingerprint(asset):
"""Hash one remote attachment in chunks, keeping memory usage bounded."""
sha256, sha1, size = hashlib.sha256(), hashlib.sha1(), 0
url = attachment_url(asset)
endpoint = transport_url(url)
headers = {'Authorization': 'token ' + os.environ['GITEA_TOKEN']}
if endpoint != url:
headers['Host'] = 'git.orangraph.com'
req = urllib.request.Request(endpoint, headers=headers)
with urllib.request.urlopen(req, timeout=300) as response:
while chunk := response.read(1024 * 1024):
sha256.update(chunk)
sha1.update(chunk)
size += len(chunk)
return {'sha256': sha256.hexdigest(), 'sha1': sha1.hexdigest(), 'size': size}
def upload_contents(base, release_id, contents, *, transport=None):
send = transport or request
def attachment_names():
assets = retry_read(lambda: send(f"{base}/releases/{release_id}/assets"))
names = [asset['name'] for asset in assets]
if len(set(names)) != len(names):
raise ValueError('Duplicate Release attachments')
return set(names)
names = attachment_names()
for name in contents:
if '/' in name or '\\' in name:
raise ValueError('Unexpected artifact path')
def upload(item):
name, body = item
boundary = uuid.uuid4().hex
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode() + body + f'\r\n--{boundary}--\r\n'.encode())
for attempt in range(len(RETRY_DELAYS) + 1):
# A timeout can occur after Gitea has committed the upload. Reconcile
# before another POST; publication will still verify the file bytes.
if attempt and name in attachment_names():
return
try:
send(f"{base}/releases/{release_id}/assets?name={urllib.parse.quote(name)}", payload, 'POST', f'multipart/form-data; boundary={boundary}')
return
except Exception as error:
if not transient(error):
raise
if attempt == len(RETRY_DELAYS):
if name in attachment_names():
return
raise
print(f'Upload temporarily failed for {name}; retrying in {RETRY_DELAYS[attempt]}s.', file=sys.stderr)
time.sleep(RETRY_DELAYS[attempt])
pending = [(name, body) for name, body in contents.items() if name not in names]
with ThreadPoolExecutor(max_workers=2) as executor:
# Consume every result so failures prevent the publication step.
list(executor.map(upload, pending))