fix: #478 make s3 upload confirmation resilient

This commit is contained in:
Lan committed 2026-06-05 11:33:21 +08:00
1 parent 3fe136536e
commit 8d6eaacb70
2 files changed
+70 -11

No files matched your search

+24 -11
View File
@@ -536,18 +536,31 @@ class S3FileStorage(FileStorageInterface):
:param save_path: 文件路径
:return: 文件是否存在
"""
async with self.session.client(
"s3",
endpoint_url=self.endpoint_url,
aws_session_token=self.aws_session_token,
region_name=self.region_name,
config=Config(signature_version=self.signature_version),
) as s3:
async with self._client() as s3:
last_error = None
for attempt in range(3):
try:
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
return True
except Exception as e:
last_error = e
if attempt < 2:
await asyncio.sleep(0.2 * (attempt + 1))
try:
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
return True
except Exception:
return False
result = await s3.list_objects_v2(
Bucket=self.bucket_name,
Prefix=save_path,
MaxKeys=1,
)
for item in result.get("Contents", []):
if item.get("Key") == save_path:
return True
except Exception as e:
last_error = e
logger.warning(f"S3文件确认失败 key={save_path}: {last_error}")
return False
class OneDriveFileStorage(FileStorageInterface):
+46
View File
@@ -0,0 +1,46 @@
import asyncio
import unittest
from core.storage import S3FileStorage
class FakeS3Client:
def __init__(self, list_response):
self.list_response = list_response
self.head_calls = 0
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, traceback):
return False
async def head_object(self, **kwargs):
self.head_calls += 1
raise RuntimeError("head not supported")
async def list_objects_v2(self, **kwargs):
return self.list_response
class S3FileExistsTests(unittest.TestCase):
def test_file_exists_falls_back_to_list_objects(self):
client = FakeS3Client({"Contents": [{"Key": "share/data/file.txt"}]})
storage = S3FileStorage.__new__(S3FileStorage)
storage.bucket_name = "bucket"
storage._client = lambda: client
exists = asyncio.run(storage.file_exists("share/data/file.txt"))
self.assertTrue(exists)
self.assertEqual(client.head_calls, 3)
def test_file_exists_returns_false_when_missing(self):
client = FakeS3Client({"Contents": [{"Key": "share/data/other.txt"}]})
storage = S3FileStorage.__new__(S3FileStorage)
storage.bucket_name = "bucket"
storage._client = lambda: client
exists = asyncio.run(storage.file_exists("share/data/file.txt"))
self.assertFalse(exists)