ci(gitea): split builds and retry artifact publication
This commit is contained in:
1 parent
d83f94afd5
commit
b225008476
18 files changed
+1790
-286
No files matched your search
@@ -0,0 +1,109 @@
|
||||
"""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):
|
||||
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))
|
||||
Reference in new issue
Block a user