fix(background): ensure partial results are saved on failure

This commit is contained in:
ShiYu
2025-05-24 10:29:22 +08:00
parent b76d462b12
commit 056b685eaa
+21 -2
View File
@@ -198,6 +198,8 @@ public sealed class BackgroundTaskQueue : IBackgroundTaskQueue, IDisposable
string localFilePath = ""; string localFilePath = "";
bool isTempFile = false; bool isTempFile = false;
var dbContext = await _contextFactory.CreateDbContextAsync();
var picture = await dbContext.Pictures.FindAsync(task.PictureId);
try try
{ {
@@ -207,8 +209,6 @@ public sealed class BackgroundTaskQueue : IBackgroundTaskQueue, IDisposable
// 1. 获取图片信息 // 1. 获取图片信息
await UpdatePictureStatus(task.PictureId, ProcessingStatus.Processing, 10); await UpdatePictureStatus(task.PictureId, ProcessingStatus.Processing, 10);
var dbContext = await _contextFactory.CreateDbContextAsync();
var picture = await dbContext.Pictures.FindAsync(task.PictureId);
if (picture == null) if (picture == null)
{ {
@@ -277,6 +277,9 @@ public sealed class BackgroundTaskQueue : IBackgroundTaskQueue, IDisposable
// 4. 从EXIF中提取拍摄时间并确保是UTC格式 // 4. 从EXIF中提取拍摄时间并确保是UTC格式
picture.TakenAt = ImageHelper.ParseExifDateTime(exifInfo.DateTimeOriginal); picture.TakenAt = ImageHelper.ParseExifDateTime(exifInfo.DateTimeOriginal);
// 保存缩略图和EXIF信息的更改,确保这些基本信息即使在后续步骤失败时也能保存
await dbContext.SaveChangesAsync();
// 5. 将缩略图转换为Base64并调用AI分析 // 5. 将缩略图转换为Base64并调用AI分析
await UpdatePictureStatus(task.PictureId, ProcessingStatus.Processing, 50); await UpdatePictureStatus(task.PictureId, ProcessingStatus.Processing, 50);
string base64Image = await ImageHelper.ConvertImageToBase64(thumbnailPath); string base64Image = await ImageHelper.ConvertImageToBase64(thumbnailPath);
@@ -360,6 +363,22 @@ public sealed class BackgroundTaskQueue : IBackgroundTaskQueue, IDisposable
// 更新状态为失败 // 更新状态为失败
await UpdatePictureStatus(task.PictureId, ProcessingStatus.Failed, 0, ex.Message); await UpdatePictureStatus(task.PictureId, ProcessingStatus.Failed, 0, ex.Message);
// 确保图片对象存在且已有的处理结果被保存
if (picture != null)
{
picture.ProcessingStatus = ProcessingStatus.Failed;
picture.ProcessingError = ex.Message;
try
{
await dbContext.SaveChangesAsync();
}
catch (Exception saveEx)
{
Console.WriteLine($"保存失败状态时出错: {saveEx.Message}");
}
}
// 记录错误日志 // 记录错误日志
Console.WriteLine($"图片处理失败: 图片ID={task.PictureId}, 错误: {ex.Message}"); Console.WriteLine($"图片处理失败: 图片ID={task.PictureId}, 错误: {ex.Message}");
} }