fix: a short R2 failure no longer fails a customer's upload (DTF-API-D, DTF-WEB-27)

R2 answered ListParts with a 500 twice, 10 s apart, while closing an upload.
The storage calls an upload waits on (list parts, complete, head) try again on
a 5xx three more times over about 6 s; a 4xx and a timeout go back at once.
A complete R2 had in fact done answers NoSuchUpload on the retry: the object
is there, so it counts as done. The browser asks to close the upload again
after 3 s and 6 s on a server failure; only the last one is reported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-12-01 13:24:30 -03:00
parent 741db76fa9
commit 5d70a6f912
2 changed files with 62 additions and 9 deletions

View File

@@ -3,6 +3,7 @@ import hashlib
import hmac
import json
import os
import time
from typing import Mapping, NamedTuple, Protocol
from urllib.parse import urlparse
import boto3
@@ -240,6 +241,30 @@ class ObjectStorage(Protocol):
def discard_prefix(self, prefix: str): ...
def view(self, key: str, content_type: str, expires: int = 3600) -> str: ...
# R2 answers a 500 now and then for a few seconds (Sentry DTF-API-D,
# 2026-12-01: ListParts "InternalError" twice, 10 s apart, while closing a
# customer's upload). The calls an upload waits on try again on such an
# answer, three more times over about 6 s. A 4xx is an answer and goes back
# at once, and a timeout is not retried here, so the request stays inside the
# gateway's 30 s.
STEADY_WAITS = (1, 2, 3)
def server_error(exc):
return (exc.response.get('ResponseMetadata', {}).get('HTTPStatusCode') or 0) >= 500
def steady(call, sleep=time.sleep):
"""`call()`, again after each wait in STEADY_WAITS while storage answers 5xx."""
for wait in STEADY_WAITS + (None,):
try:
return call()
except ClientError as exc:
if wait is None or not server_error(exc):
raise
sleep(wait)
class LocalS3Storage:
def __init__(self):
config = Config(signature_version='s3v4', s3={'addressing_style': 'path'},
@@ -273,11 +298,13 @@ class LocalS3Storage:
ContentType='application/octet-stream')['UploadId']
def parts(self, key, upload_id):
def listed():
result = []
for page in self.client.get_paginator('list_parts').paginate(
Bucket=self.bucket, Key=key, UploadId=upload_id):
result.extend(page.get('Parts', []))
return result
return steady(listed)
def part_url(self, key, upload_id, part, size):
return self.public.generate_presigned_url('upload_part', Params={
@@ -285,11 +312,22 @@ class LocalS3Storage:
'ContentLength': size}, ExpiresIn=900)
def complete(self, key, upload_id, parts):
self.client.complete_multipart_upload(Bucket=self.bucket, Key=key, UploadId=upload_id,
MultipartUpload={'Parts': [{'PartNumber': p['PartNumber'], 'ETag': p['ETag']} for p in parts]})
try:
steady(lambda: self.client.complete_multipart_upload(Bucket=self.bucket, Key=key, UploadId=upload_id,
MultipartUpload={'Parts': [{'PartNumber': p['PartNumber'], 'ETag': p['ETag']} for p in parts]}))
except ClientError as exc:
# A try after a 500 that R2 had in fact completed finds no upload
# left: the object is there, so the upload is complete.
if exc.response.get('Error', {}).get('Code') != 'NoSuchUpload':
raise
try:
self.size(key)
except ClientError:
raise exc
return
def size(self, key):
return self.client.head_object(Bucket=self.bucket, Key=key)['ContentLength']
return steady(lambda: self.client.head_object(Bucket=self.bucket, Key=key))['ContentLength']
def fetch(self, key, path):
"""Copy a stored object to a local file (the worker's scratch space)."""

View File

@@ -107,7 +107,22 @@ async function sendUpload(file, {api, prefix='/uploads', startPath=prefix, progr
done.add(part);sent+=length(part);
onBytes(sent);
}
await api(prefix+'/'+id+'/complete',{});
// Closing the upload reads the parts back from storage, which can fail for
// a few seconds (an R2 500, Sentry DTF-API-D, 01/12). Asked again after 3 s
// and 6 s, quietly: closing twice is safe, the server answers an upload that
// is already closed. A refusal (4xx) is shown at once; only the last
// failure reaches the customer and Sentry. No status is a reply that was
// not JSON (the gateway's 500 page) or no reply at all.
const SERVER_ERRORS=[500,502,503,504];
for(let attempt=0;;attempt++){
const last=attempt>=2;
try{await api(prefix+'/'+id+'/complete',{},last?{}:{expected:SERVER_ERRORS});break;}
catch(error){
if(last||error?.name==='AbortError'||(error?.status!==undefined&&!SERVER_ERRORS.includes(error.status)))throw error;
await new Promise(resolve=>setTimeout(resolve,(attempt+1)*3000));
if(signal?.aborted){giveBack();throw cancelled();}
}
}
return waitForScan();
}
window.dtfUpload = async (file, options) => {