Files
cutdex/tool/gitea/release_transport.py
T
lingjhf 933ace4e51
Gitea CI / Check code and tests (pull_request) Successful in 5m11s
Gitea CI / Build Android APK (pull_request) Failing after 4m12s
Gitea CI / Audit and package Windows x64 (pull_request) Canceled after 0s
Gitea CI / Assemble and validate CI artifacts (pull_request) Canceled after 0s
Gitea CI / Gitea CI passed (pull_request) Canceled after 0s
Gitea CI / Build Windows x64 app (pull_request) Canceled after 5m11s
fix(release): retry FRP tunnel reconnection responses
2026-10-06 14:16:32 +08:00

115 lines
4.9 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 sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
SERVER = 'https://git.orangraph.com'
RETRY_DELAYS = (5, 15)
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'):
headers = {'Authorization': 'token ' + os.environ['GITEA_TOKEN']}
if data is not None:
headers['Content-Type'] = content_type
if isinstance(data, dict):
data = json.dumps(data).encode()
req = urllib.request.Request(url, 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
req = urllib.request.Request(attachment_url(asset),
headers={'Authorization': 'token ' + os.environ['GITEA_TOKEN']})
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))