using dodohold.core; using System.Security.Cryptography; using System.Text; namespace molilian.core { public static class TaobaoGeneralLinkParseCacheCore { // 成功结果缓存 1 天;确定无法解析的链接缓存 1 小时;网络异常等临时错误不缓存 public const int SuccessExpireSeconds = 86400; public const int FailureExpireSeconds = 3600; // 统计跨天保留,每次通知领取上次通知后的全部次数;同一天只允许领取一次。 private const string ClaimNotificationScript = @" local count = redis.call('HINCRBY', KEYS[1], 'pending', 1) local lastDate = redis.call('HGET', KEYS[1], 'last_notify_date') if lastDate and lastDate >= ARGV[1] then return 0 end redis.call('HSET', KEYS[1], 'last_notify_date', ARGV[1]) redis.call('HSET', KEYS[1], 'pending', 0) return count"; public static async Task GetAsync(string content) { try { return await CenterHub.Redis.GetAsync(GetCacheKey(content)); } catch (Exception ex) { LogFailure("cache_read_error", ex); return null; } } public static async Task SaveAsync(string content, TaobaoGeneralLinkParseCacheDTO record, int expireSeconds) { if (expireSeconds <= 0) return; try { await CenterHub.Redis.SetAsync(GetCacheKey(content), record, expireSeconds); } catch (Exception ex) { LogFailure("cache_write_error", ex); } } public static async Task NotifyFailureOnceAsync(string reason, int parseAccountId, int consumerAccountId) { reason = string.IsNullOrWhiteSpace(reason) ? "未知错误" : reason.Trim(); string key = $"notify:taobao:general_link_parse:v1:{Hash(reason)}"; long count = 0; try { count = Convert.ToInt64(await CenterHub.Redis.EvalAsync(ClaimNotificationScript, key, DateTime.Now.ToString("yyyyMMdd"))); if (count <= 0) return; await NotifyCore.NotifyAsync( $"【淘宝万能解析失败】\n错误信息:{reason}\n" + $"自上次相同错误通知以来发生:{count} 次(含本次)\n" + $"使用账号:{consumerAccountId},解析账号:{parseAccountId}\n已回退原短链解析逻辑。"); } catch (Exception ex) { if (count > 0) { try { // 发送失败的次数留给下一次通知,同一天不重复尝试发送。 await CenterHub.Redis.HIncrByAsync(key, "pending", count); } catch (Exception restoreException) { LogFailure("notify_count_restore_error", restoreException); } } LogFailure("notify_error", ex); } } private static string GetCacheKey(string content) { // v2:精简缓存结构,不与 v1 旧数据混用 // 取 SHA256 前 8 字节(16 位十六进制),压缩 key 占用 string hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(content.Trim())), 0, 8); return $"cache:taobao:general_link_parse:v2:{hash}"; } private static string Hash(string value) { return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value))); } private static void LogFailure(string operation, Exception ex) { _ = new LoggerLibrary("tbk_dg_general_link_parse", operation) .Info(ex.Message, ex.StackTrace) .SaveAsync(); } } }