using FreeSql.DataAnnotations; using System.Text.Json; namespace Store.Modules.CloudProduct.Entities; /// 跨用户复用的图片识别数据,仅存储成功识别结果。 [Table(Name = "image_analysis_cache")] public sealed class ImageAnalysisCache { /// 客户端指定的 MD5 缓存键,统一保存为 32 位小写十六进制。 [Column(IsPrimary = true, StringLength = 32)] public string CacheKey { get; set; } = ""; /// 模型识别结果的 JSON 字符串数组,空数组表示未识别到文字或品牌。 [Column(DbType = "longtext")] public string RecognitionResult { get; set; } = ""; /// 缓存最近更新时间,UTC。 public DateTime UpdatedAt { get; set; } /// 从 UpdatedAt 起算的缓存有效小时数,命中时不续期。 public int ExpiresAt { get; set; } /// 每轮成功识别后更新有效期:空结果逐级延长,有内容则重置级别。 public void RecordExpiration(bool isEmpty, DateTime utcNow) { // 新记录和上次有内容的记录,首次为空时均从 24 小时起算。 ExpiresAt = isEmpty ? ExpiresAt switch { 24 => 48, 48 => 96, 96 => 192, 192 or 384 => 384, _ => 24 } : 720; UpdatedAt = utcNow; } /// 仅复用有效期内的数组,旧对象格式需要重新识别。 public string[]? ReadFreshResult(DateTime utcNow) { if (utcNow >= UpdatedAt.AddHours(ExpiresAt) || !RecognitionResult.TrimStart().StartsWith('[')) return null; return JsonSerializer.Deserialize(RecognitionResult); } }