Add upload cleanup functionality and improve error handling for media uploads
ci / build-backend (push) Successful in 2m3s
ci / build-frontend (push) Successful in 44s
ci / tests (push) Successful in 2m39s
ci / sonar (push) Successful in 5m50s

Implemented a new background service, UploadsCleanupBackgroundService, to manage stale uploads in the uploads directory. Enhanced error handling in the media upload process to ensure incomplete uploads are deleted immediately upon failure, preventing unnecessary storage usage. Updated the .env.example and StorageOptions to include configuration for stale upload retention time. Improved documentation to reflect these changes and clarify the upload process.
This commit is contained in:
Leonid Pershin
2026-07-27 02:56:15 +03:00
parent 986f7ff52d
commit a8b5a8f693
11 changed files with 301 additions and 17 deletions
@@ -88,13 +88,27 @@ public static class MediaEndpoints
var extension = Path.GetExtension(fileName);
var token = await storage.SaveUploadAsync(request.Body, extension, cancellationToken);
var result = await sender.Send(
new RegisterMediaAssetCommand(token, MediaSource.Upload, fileName),
cancellationToken
);
// Файл уже на диске в uploads/, но в БД его ещё нет и ссылок на токен нигде не остаётся:
// любой исход, кроме успешной регистрации, обязан за собой убрать. Удаляем и при исключении
// (оборванный запрос, сбой БД) — иначе гигабайты остаются в uploads/ до уборщика.
// Токен отмены для уборки не пробрасываем: при обрыве запроса он уже сработал.
Result<Guid> result;
try
{
result = await sender.Send(
new RegisterMediaAssetCommand(token, MediaSource.Upload, fileName),
cancellationToken
);
}
catch
{
await storage.DeleteUploadAsync(token, CancellationToken.None);
throw;
}
if (!result.IsSuccess)
{
await storage.DeleteUploadAsync(token, cancellationToken);
await storage.DeleteUploadAsync(token, CancellationToken.None);
return result.ToHttpResult();
}