TracksCore.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Net;
  5. using System.Threading.Tasks;
  6. using Dapper;
  7. using CSRedis;
  8. using dodohold.core;
  9. using System.Text.Json;
  10. using YunhuiKit;
  11. namespace molilian.core
  12. {
  13. public enum TrackType
  14. {
  15. Expose,
  16. Click
  17. }
  18. public partial class TracksCore
  19. {
  20. private const string RedisPrefix = ":tracks_v123";
  21. private const int DailyExpireSeconds = 40 * 86400;
  22. private const int HourlyExpireSeconds = 7 * 86400; // keep a week of hourly buckets
  23. private const string DefaultDimensionValue = "";
  24. private const int LinkCacheExpireSeconds = 30 * 86400;
  25. private const string TrackRequestLogKey = ":tracks:request:logs";
  26. private static readonly HashSet<string> SupportEventTypes = new(StringComparer.OrdinalIgnoreCase) { "expose", "click" };
  27. /// <summary>
  28. /// 生成一个监测链接(仅返回 path,不包含域名),同时落地到 track_links
  29. /// </summary>
  30. public static Task<TrackLinkDTO> CreateLinkAsync(string eventType, string typename, string scene, string uniqueId, string description = "", bool forceNew = false)
  31. {
  32. return CreateLinkAsync(eventType, string.Empty, typename, scene, uniqueId, description, forceNew);
  33. }
  34. /// <summary>
  35. /// 生成一个监测链接(仅返回 path,不包含域名),同时落地到 track_links
  36. /// </summary>
  37. public static Task<TrackLinkDTO> CreateLinkAsync(string eventType, string platform, string typename, string scene, string uniqueId, string description = "", bool forceNew = false)
  38. {
  39. eventType = NormalizeEventType(eventType);
  40. platform = Normalize(platform);
  41. typename = Normalize(typename);
  42. scene = NormalizeOrAll(scene);
  43. uniqueId = NormalizeOrAll(uniqueId);
  44. description = Normalize(description);
  45. if (!SupportEventTypes.Contains(eventType))
  46. {
  47. return Task.FromResult<TrackLinkDTO>(null);
  48. }
  49. string cacheKey = GetLinkCacheKey(eventType, platform, typename, scene, uniqueId);
  50. if (!forceNew)
  51. {
  52. try
  53. {
  54. int cachedId = RedisHelper.Get<int>(cacheKey);
  55. if (cachedId > 0)
  56. {
  57. var cachedLink = RedisHelper.Get<TrackLinkDTO>(GetLinkIdCacheKey(cachedId));
  58. if (cachedLink != null) return Task.FromResult(cachedLink);
  59. }
  60. }
  61. catch
  62. {
  63. // ignore cache errors
  64. }
  65. }
  66. try
  67. {
  68. using var conn = DBContext.GetOpenConnection();
  69. TrackLinkDTO exist = null;
  70. if (!forceNew)
  71. {
  72. exist = new DBContext.Table(conn, "track_links")
  73. .Get<TrackLinkDTO>("event_type=@event_type AND platform=@platform AND typename=@typename AND scene=@scene AND unique_id=@unique_id",
  74. new { event_type = eventType, platform, typename, scene, unique_id = uniqueId });
  75. }
  76. if (exist != null)
  77. {
  78. exist.description = description;
  79. string path = BuildPath(exist.id, uniqueId);
  80. if (string.IsNullOrEmpty(exist.path) || !exist.path.Contains("track_id"))
  81. {
  82. exist.path = path;
  83. new DBContext.Table(conn, "track_links")
  84. .Add("path", path)
  85. .Add("platform", platform)
  86. .Add("typename", typename)
  87. .Add("description", description)
  88. .Add("update_time", DateTime.Now)
  89. .Where("id=@id", new { exist.id })
  90. .Update();
  91. }
  92. _ = RedisHelper.Set(cacheKey, exist.id, LinkCacheExpireSeconds);
  93. _ = RedisHelper.Set(GetLinkIdCacheKey(exist.id), exist, LinkCacheExpireSeconds);
  94. return Task.FromResult(exist);
  95. }
  96. var item = new TrackLinkDTO
  97. {
  98. event_type = eventType,
  99. platform = platform,
  100. typename = typename,
  101. scene = scene,
  102. unique_id = uniqueId,
  103. path = string.Empty,
  104. description = description,
  105. create_time = DateTime.Now,
  106. update_time = DateTime.Now
  107. };
  108. var id = conn.Insert(item);
  109. if (id != null && int.TryParse(id.ToString(), out var linkId))
  110. {
  111. item.id = linkId;
  112. item.path = BuildPath(linkId, uniqueId);
  113. new DBContext.Table(conn, "track_links")
  114. .Add("path", item.path)
  115. .Add("description", description)
  116. .Add("update_time", DateTime.Now)
  117. .Where("id=@id", new { item.id })
  118. .Update();
  119. }
  120. _ = RedisHelper.Set(cacheKey, item.id, LinkCacheExpireSeconds);
  121. _ = RedisHelper.Set(GetLinkIdCacheKey(item.id), item, LinkCacheExpireSeconds);
  122. return Task.FromResult(item);
  123. }
  124. catch (Exception ex)
  125. {
  126. _ = new LoggerLibrary("TracksCore", "CreateLink")
  127. .Info(ex.Message, ex.StackTrace)
  128. .SaveAsync();
  129. return Task.FromResult<TrackLinkDTO>(null);
  130. }
  131. }
  132. /// <summary>
  133. /// 曝光/点击触发:计入 Redis,失败不影响返回
  134. /// </summary>
  135. public static Task<bool> TrackAsync(TrackLinkDTO link)
  136. {
  137. string dateStr = DateTime.Now.ToString("yyyyMMdd");
  138. string hourStr = DateTime.Now.ToString("yyyyMMddHH");
  139. var metrics = new List<(string key, string indexKey, string indexValue, int expire)>
  140. {
  141. ($"{RedisPrefix}:daily:{link.event_type}:{link.id}:{dateStr}", $"{RedisPrefix}:daily:index:{dateStr}:track", $"{link.event_type}|{link.id}", DailyExpireSeconds),
  142. ($"{RedisPrefix}:hour:{link.event_type}:{link.id}:{hourStr}", $"{RedisPrefix}:hour:index:{hourStr}:track", $"{link.event_type}|{link.id}", HourlyExpireSeconds),
  143. };
  144. try
  145. {
  146. foreach (var metric in metrics)
  147. {
  148. RedisHelper.IncrBy(metric.key);
  149. RedisHelper.Expire(metric.key, metric.expire);
  150. RedisHelper.SAdd(metric.indexKey, metric.indexValue);
  151. RedisHelper.Expire(metric.indexKey, metric.expire);
  152. }
  153. return Task.FromResult(true);
  154. }
  155. catch (Exception ex)
  156. {
  157. _ = new LoggerLibrary("TracksCore", "TrackAsync")
  158. .Info(ex.Message, ex.StackTrace)
  159. .SaveAsync();
  160. return Task.FromResult(false);
  161. }
  162. }
  163. /// <summary>
  164. /// 日报:拉取指定日期 Redis 计数并落地到 track_daily_report,可高频重复执行。
  165. /// </summary>
  166. public static async Task<int> FlushDailyAsync(DateTime targetDate)
  167. {
  168. string dateStr = targetDate.ToString("yyyyMMdd");
  169. string indexKey = $"{RedisPrefix}:daily:index:{dateStr}:track";
  170. var indexMembers = await RedisHelper.SMembersAsync<string>(indexKey) ?? [];
  171. if (indexMembers == null || indexMembers.Length == 0) return 0;
  172. int rows = 0;
  173. using var conn = DBContext.GetOpenConnection();
  174. var linkCache = new Dictionary<int, TrackLinkDTO>();
  175. foreach (var member in indexMembers)
  176. {
  177. var parts = member.Split('|');
  178. if (parts.Length != 2) continue;
  179. string eventType = NormalizeEventType(parts[0]);
  180. if (!SupportEventTypes.Contains(eventType)) continue;
  181. if (!int.TryParse(parts[1], out var trackId) || trackId <= 0) continue;
  182. string countKey = $"{RedisPrefix}:daily:{eventType}:{trackId}:{dateStr}";
  183. int total = await RedisHelper.GetAsync<int>(countKey);
  184. if (total <= 0) continue;
  185. if (!linkCache.TryGetValue(trackId, out var link))
  186. {
  187. link = new DBContext.Table(conn, "track_links")
  188. .Get<TrackLinkDTO>("id=@id", new { id = trackId });
  189. if (link != null) linkCache[trackId] = link;
  190. }
  191. await UpsertDailyReportAsync(conn, targetDate.Date, eventType, trackId, link, total);
  192. rows++;
  193. }
  194. return rows;
  195. }
  196. private static Task<int> UpsertDailyReportAsync(IDbConnection conn, DateTime reportDate, string eventType, int trackId, TrackLinkDTO link, int total)
  197. {
  198. const string sql = @"
  199. INSERT INTO track_daily_report
  200. (report_date, event_type, track_link_id, platform, typename, scene, unique_id, event_count, create_time, update_time)
  201. VALUES
  202. (@reportDate, @eventType, @trackId, @platform, @typename, @scene, @uniqueId, @eventCount, @now, @now)
  203. ON DUPLICATE KEY UPDATE
  204. event_count = VALUES(event_count),
  205. platform = VALUES(platform),
  206. typename = VALUES(typename),
  207. scene = VALUES(scene),
  208. unique_id = VALUES(unique_id),
  209. update_time = VALUES(update_time);";
  210. return conn.ExecuteAsync(sql, new
  211. {
  212. reportDate,
  213. eventType,
  214. trackId,
  215. platform = link?.platform ?? string.Empty,
  216. typename = link?.typename ?? string.Empty,
  217. scene = link?.scene ?? string.Empty,
  218. uniqueId = link?.unique_id ?? string.Empty,
  219. eventCount = total,
  220. now = DateTime.Now
  221. });
  222. }
  223. public static async Task<List<TrackHourlyReportDTO>> GetHourlyReportAsync(int trackId, DateTime targetDate)
  224. {
  225. var result = new List<TrackHourlyReportDTO>();
  226. if (trackId <= 0) return result;
  227. var link = await GetLinkByIdAsync(trackId);
  228. if (link == null) return result;
  229. string eventType = NormalizeEventType(link.event_type);
  230. if (!SupportEventTypes.Contains(eventType)) return result;
  231. string dateStr = targetDate.ToString("yyyyMMdd");
  232. for (int hour = 0; hour < 24; hour++)
  233. {
  234. string hourStr = $"{dateStr}{hour:00}";
  235. string countKey = $"{RedisPrefix}:hour:{eventType}:{trackId}:{hourStr}";
  236. int total = await RedisHelper.GetAsync<int>(countKey);
  237. result.Add(new TrackHourlyReportDTO
  238. {
  239. track_link_id = trackId,
  240. event_type = eventType,
  241. platform = link.platform ?? string.Empty,
  242. typename = link.typename ?? string.Empty,
  243. scene = link.scene ?? string.Empty,
  244. unique_id = link.unique_id ?? string.Empty,
  245. report_date = targetDate.Date,
  246. hour = hour,
  247. event_count = total
  248. });
  249. }
  250. return result;
  251. }
  252. public static string BuildPath(TrackType type, TkDataDTO result)
  253. {
  254. int trackId = type == TrackType.Click ? 1 : 2;
  255. if (result == null) return string.Empty;
  256. string unique_id = $"1|{result.itemId}_{result.mktId}";
  257. return BuildPath(trackId, unique_id);
  258. }
  259. public static string BuildPath(TrackType type, JdDataDTO result)
  260. {
  261. int trackId = type == TrackType.Click ? 19 : 20;
  262. if (result == null) return string.Empty;
  263. string unique_id = $"13|{result.shortLinkurl.UrlEncode()}";
  264. return BuildPath(trackId, unique_id);
  265. }
  266. public static string BuildPath(TrackType type, PddDataDTO result)
  267. {
  268. int trackId = type == TrackType.Click ? 21 : 22;
  269. if (result == null) return string.Empty;
  270. string unique_id = $"9|{result.shortLinkurl.UrlEncode()}";
  271. return BuildPath(trackId, unique_id);
  272. }
  273. public static string BuildPath(int trackId, string unique_id = "")
  274. {
  275. return $"https://api.molilian.com/tracks/track?track_id={trackId}&unique_id={unique_id}";
  276. }
  277. public static string GetLinkCacheKey(string eventType, string typename, string scene, string uniqueId)
  278. {
  279. return GetLinkCacheKey(eventType, string.Empty, typename, scene, uniqueId);
  280. }
  281. public static string GetLinkCacheKey(string eventType, string platform, string typename, string scene, string uniqueId)
  282. {
  283. eventType = NormalizeEventType(eventType);
  284. platform = Normalize(platform);
  285. typename = Normalize(typename);
  286. scene = NormalizeOrAll(scene);
  287. uniqueId = NormalizeOrAll(uniqueId);
  288. return $"{RedisPrefix}:link:{eventType}:{platform}:{typename}:{scene}:{uniqueId}";
  289. }
  290. public static string GetLinkIdCacheKey(int trackId)
  291. {
  292. return $"{RedisPrefix}:linkid:{trackId}";
  293. }
  294. public static async Task<TrackLinkDTO> GetLinkByIdAsync(int trackId)
  295. {
  296. if (trackId <= 0) return null;
  297. string cacheKey = GetLinkIdCacheKey(trackId);
  298. try
  299. {
  300. var cached = RedisHelper.Get<TrackLinkDTO>(cacheKey);
  301. if (cached != null) return cached;
  302. }
  303. catch { }
  304. try
  305. {
  306. var item = new DBContext.Table("track_links").Get<TrackLinkDTO>("id=@id", new { id = trackId });
  307. if (item != null)
  308. {
  309. _ = RedisHelper.Set(cacheKey, item, LinkCacheExpireSeconds);
  310. }
  311. return item;
  312. }
  313. catch
  314. {
  315. return null;
  316. }
  317. }
  318. public static Task<bool> LogTrackRequestAsync(TrackRequestLogDTO dto)
  319. {
  320. try
  321. {
  322. dto.event_type = NormalizeEventType(dto.event_type);
  323. dto.platform = Normalize(dto.platform);
  324. dto.typename = Normalize(dto.typename);
  325. dto.scene = NormalizeOrAll(dto.scene);
  326. dto.unique_id = NormalizeOrAll(dto.unique_id);
  327. dto.ip = Normalize(dto.ip);
  328. dto.user_agent = Normalize(dto.user_agent);
  329. dto.referer = Normalize(dto.referer);
  330. dto.create_time = DateTime.Now;
  331. RedisHelper.RPush(TrackRequestLogKey, dto);
  332. return Task.FromResult(true);
  333. }
  334. catch
  335. {
  336. return Task.FromResult(false);
  337. }
  338. }
  339. public static async Task<int> InsertTrackRequestLogAsync(int limit, YunhuiKit.RedisClient redis)
  340. {
  341. int count = 0;
  342. try
  343. {
  344. using var conn = DBContext.GetOpenConnection();
  345. for (int i = 0; i < limit; i++)
  346. {
  347. var entity = await redis.LPopAsync<TrackRequestLogDTO>(TrackRequestLogKey);
  348. if (entity == null) break;
  349. try
  350. {
  351. if (entity.create_time == default) entity.create_time = DateTime.Now;
  352. conn.Insert(entity);
  353. count++;
  354. }
  355. catch
  356. {
  357. // ignore malformed item
  358. }
  359. }
  360. }
  361. catch
  362. {
  363. return count;
  364. }
  365. return count;
  366. }
  367. private static string Normalize(string value)
  368. {
  369. return (value ?? string.Empty).Trim();
  370. }
  371. private static string NormalizeOrAll(string value)
  372. {
  373. var result = Normalize(value);
  374. return string.IsNullOrEmpty(result) ? DefaultDimensionValue : result;
  375. }
  376. private static string NormalizeEventType(string value)
  377. {
  378. return Normalize(value).ToLowerInvariant();
  379. }
  380. private static int GetTrackLinkId(IDbConnection conn, string eventType, string platform, string scene, string uniqueId)
  381. {
  382. try
  383. {
  384. var record = new DBContext.Table(conn, "track_links")
  385. .Fields("id")
  386. .Get<TrackLinkDTO>("event_type=@event_type AND platform=@platform AND scene=@scene AND unique_id=@unique_id",
  387. new { event_type = eventType, platform, scene, unique_id = uniqueId });
  388. if (record == null) return 0;
  389. return record.id;
  390. }
  391. catch
  392. {
  393. return 0;
  394. }
  395. }
  396. }
  397. }