TaobaoGeneralLinkParseNotificationCore.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using dodohold.core;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. namespace molilian.core
  5. {
  6. public static class TaobaoGeneralLinkParseNotificationCore
  7. {
  8. // 统计跨天保留,每次通知领取上次通知后的全部次数;同一天只允许领取一次。
  9. private const string ClaimNotificationScript = @"
  10. local count = redis.call('HINCRBY', KEYS[1], 'pending', 1)
  11. local lastDate = redis.call('HGET', KEYS[1], 'last_notify_date')
  12. if lastDate and lastDate >= ARGV[1] then
  13. return 0
  14. end
  15. redis.call('HSET', KEYS[1], 'last_notify_date', ARGV[1])
  16. redis.call('HSET', KEYS[1], 'pending', 0)
  17. return count";
  18. public static async Task NotifyFailureOnceAsync(string reason, int parseAccountId, int consumerAccountId)
  19. {
  20. reason = string.IsNullOrWhiteSpace(reason) ? "未知错误" : reason.Trim();
  21. string key = $"notify:taobao:general_link_parse:v1:{Hash(reason)}";
  22. long count = 0;
  23. try
  24. {
  25. count = Convert.ToInt64(await CenterHub.Redis.EvalAsync(ClaimNotificationScript, key, DateTime.Now.ToString("yyyyMMdd")));
  26. if (count <= 0) return;
  27. await NotifyCore.NotifyAsync(
  28. $"【淘宝万能解析失败】\n错误信息:{reason}\n" +
  29. $"自上次相同错误通知以来发生:{count} 次(含本次)\n" +
  30. $"使用账号:{consumerAccountId},解析账号:{parseAccountId}\n已回退原短链解析逻辑。");
  31. }
  32. catch (Exception ex)
  33. {
  34. if (count > 0)
  35. {
  36. try
  37. {
  38. // 发送失败的次数留给下一次通知,同一天不重复尝试发送。
  39. await CenterHub.Redis.HIncrByAsync(key, "pending", count);
  40. }
  41. catch (Exception restoreException)
  42. {
  43. LogFailure("notify_count_restore_error", restoreException);
  44. }
  45. }
  46. LogFailure("notify_error", ex);
  47. }
  48. }
  49. private static string Hash(string value)
  50. {
  51. return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)));
  52. }
  53. private static void LogFailure(string operation, Exception ex)
  54. {
  55. _ = new LoggerLibrary("tbk_dg_general_link_parse", operation)
  56. .Info(ex.Message, ex.StackTrace)
  57. .SaveAsync();
  58. }
  59. }
  60. }