build-flow.api/src/modules/file/Application/Common/FileSizeBackfillHelper.cs
ljw559 4ec64c773a feat: 文件大小回填与文件夹递归总大小计算
- IS3StorageService 新增 GetObjectSizeAsync(HeadObject 取 ContentLength)
- 新增 FileSizeBackfillHelper:读路径惰性回填历史 Size=0 的文件
- 新增 FolderSizeCalculator:后序 DFS 计算文件夹递归总大小
- GetRootFiles/GetFolder 加载时回填;GetFolderTree 计算并返回 FolderDto.Size
- FolderDto 增加 Size 字段,FolderMapper.ToDto 适配

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-06 00:45:46 +08:00

53 lines
1.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using File.Domain.Entities;
using File.Infrastructure.Persistence;
using File.Infrastructure.Storage;
namespace File.Application.Common;
/// <summary>
/// 文件大小回填助手:对 Size==0 的 FileMeta,从 S3 HeadObject 取真实 ContentLength 写回。
/// 用于读路径(列表加载)惰性修复早期未记录大小的旧数据——首次加载即回填并持久化,
/// 后续加载直接命中 DB 不再访问 S3。对象缺失或空文件保留 Size=0;单个失败不中断整体。
/// </summary>
public static class FileSizeBackfillHelper
{
public static async Task BackfillAsync(
FileDbContext db,
IS3StorageService s3,
IReadOnlyList<FileMeta> files,
CancellationToken ct)
{
var stale = files.Where(f => f.Size == 0).ToList();
if (stale.Count == 0)
{
return;
}
var updated = 0;
foreach (var file in stale)
{
try
{
var size = await s3.GetObjectSizeAsync(file.S3Bucket, file.S3Key, ct);
if (size is null || size <= 0)
{
// 对象缺失(已被外部清理)或空文件:保留 Size=0
continue;
}
file.Size = size.Value;
updated++;
}
catch
{
// 单个对象查询失败不中断整体回填,保留 Size=0 下次可重试
}
}
if (updated > 0)
{
await db.SaveChangesAsync(ct);
}
}
}