TracksCore.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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, string scene = "")
  136. {
  137. string dateStr = DateTime.Now.ToString("yyyyMMdd");
  138. string hourStr = DateTime.Now.ToString("yyyyMMddHH");
  139. string metricScene = ResolveMetricScene(link, scene);
  140. string indexValue = BuildMetricIndexValue(link.event_type, link.id, metricScene);
  141. var metrics = new List<(string key, string indexKey, string indexValue, int expire)>
  142. {
  143. (BuildDailyCountKey(link.event_type, link.id, dateStr, metricScene), $"{RedisPrefix}:daily:index:{dateStr}:track", indexValue, DailyExpireSeconds),
  144. (BuildHourlyCountKey(link.event_type, link.id, hourStr, metricScene), $"{RedisPrefix}:hour:index:{hourStr}:track", indexValue, HourlyExpireSeconds),
  145. };
  146. try
  147. {
  148. foreach (var metric in metrics)
  149. {
  150. RedisHelper.IncrBy(metric.key);
  151. RedisHelper.Expire(metric.key, metric.expire);
  152. RedisHelper.SAdd(metric.indexKey, metric.indexValue);
  153. RedisHelper.Expire(metric.indexKey, metric.expire);
  154. }
  155. return Task.FromResult(true);
  156. }
  157. catch (Exception ex)
  158. {
  159. _ = new LoggerLibrary("TracksCore", "TrackAsync")
  160. .Info(ex.Message, ex.StackTrace)
  161. .SaveAsync();
  162. return Task.FromResult(false);
  163. }
  164. }
  165. /// <summary>
  166. /// 日报:拉取指定日期 Redis 计数并落地到 track_daily_report,可高频重复执行。
  167. /// </summary>
  168. public static async Task<int> FlushDailyAsync(DateTime targetDate)
  169. {
  170. string dateStr = targetDate.ToString("yyyyMMdd");
  171. string indexKey = $"{RedisPrefix}:daily:index:{dateStr}:track";
  172. var indexMembers = await RedisHelper.SMembersAsync<string>(indexKey) ?? [];
  173. if (indexMembers == null || indexMembers.Length == 0) return 0;
  174. var buckets = new Dictionary<string, DailyReportBucket>();
  175. using var conn = DBContext.GetOpenConnection();
  176. var linkCache = new Dictionary<int, TrackLinkDTO>();
  177. foreach (var member in indexMembers)
  178. {
  179. var parts = member.Split('|');
  180. if (parts.Length != 2 && parts.Length != 3) continue;
  181. string eventType = NormalizeEventType(parts[0]);
  182. if (!SupportEventTypes.Contains(eventType)) continue;
  183. if (!int.TryParse(parts[1], out var trackId) || trackId <= 0) continue;
  184. bool hasScenePart = parts.Length == 3;
  185. string memberScene = hasScenePart ? DecodeIndexPart(parts[2]) : string.Empty;
  186. string countKey = BuildDailyCountKey(eventType, trackId, dateStr, hasScenePart ? memberScene : string.Empty);
  187. int total = await RedisHelper.GetAsync<int>(countKey);
  188. if (total <= 0) continue;
  189. if (!linkCache.TryGetValue(trackId, out var link))
  190. {
  191. link = new DBContext.Table(conn, "track_links")
  192. .Get<TrackLinkDTO>("id=@id", new { id = trackId });
  193. if (link != null) linkCache[trackId] = link;
  194. }
  195. string reportScene = ResolveMetricScene(link, memberScene);
  196. string bucketKey = BuildMetricIndexValue(eventType, trackId, reportScene);
  197. if (!buckets.TryGetValue(bucketKey, out var bucket))
  198. {
  199. bucket = new DailyReportBucket
  200. {
  201. EventType = eventType,
  202. TrackId = trackId,
  203. Scene = reportScene,
  204. Link = link
  205. };
  206. buckets[bucketKey] = bucket;
  207. }
  208. bucket.Total += total;
  209. }
  210. int rows = 0;
  211. foreach (var bucket in buckets.Values)
  212. {
  213. await UpsertDailyReportAsync(conn, targetDate.Date, bucket.EventType, bucket.TrackId, bucket.Scene, bucket.Link, bucket.Total);
  214. rows++;
  215. }
  216. return rows;
  217. }
  218. private static Task<int> UpsertDailyReportAsync(IDbConnection conn, DateTime reportDate, string eventType, int trackId, string scene, TrackLinkDTO? link, int total)
  219. {
  220. const string sql = @"
  221. INSERT INTO track_daily_report
  222. (report_date, event_type, track_link_id, platform, typename, scene, unique_id, event_count, create_time, update_time)
  223. VALUES
  224. (@reportDate, @eventType, @trackId, @platform, @typename, @scene, @uniqueId, @eventCount, @now, @now)
  225. ON DUPLICATE KEY UPDATE
  226. event_count = VALUES(event_count),
  227. platform = VALUES(platform),
  228. typename = VALUES(typename),
  229. scene = VALUES(scene),
  230. unique_id = VALUES(unique_id),
  231. update_time = VALUES(update_time);";
  232. return conn.ExecuteAsync(sql, new
  233. {
  234. reportDate,
  235. eventType,
  236. trackId,
  237. platform = link?.platform ?? string.Empty,
  238. typename = link?.typename ?? string.Empty,
  239. scene,
  240. uniqueId = link?.unique_id ?? string.Empty,
  241. eventCount = total,
  242. now = DateTime.Now
  243. });
  244. }
  245. public static async Task<List<TrackHourlyReportDTO>> GetHourlyReportAsync(int trackId, DateTime targetDate, string scene = "")
  246. {
  247. var result = new List<TrackHourlyReportDTO>();
  248. if (trackId <= 0) return result;
  249. var link = await GetLinkByIdAsync(trackId);
  250. if (link == null) return result;
  251. string eventType = NormalizeEventType(link.event_type);
  252. if (!SupportEventTypes.Contains(eventType)) return result;
  253. string metricScene = ResolveMetricScene(link, scene);
  254. string linkScene = ResolveMetricScene(link, string.Empty);
  255. string dateStr = targetDate.ToString("yyyyMMdd");
  256. for (int hour = 0; hour < 24; hour++)
  257. {
  258. string hourStr = $"{dateStr}{hour:00}";
  259. int total = await RedisHelper.GetAsync<int>(BuildHourlyCountKey(eventType, trackId, hourStr, metricScene));
  260. if (!string.IsNullOrEmpty(metricScene) && metricScene == linkScene)
  261. {
  262. total += await RedisHelper.GetAsync<int>(BuildHourlyCountKey(eventType, trackId, hourStr, string.Empty));
  263. }
  264. result.Add(new TrackHourlyReportDTO
  265. {
  266. track_link_id = trackId,
  267. event_type = eventType,
  268. platform = link.platform ?? string.Empty,
  269. typename = link.typename ?? string.Empty,
  270. scene = metricScene,
  271. unique_id = link.unique_id ?? string.Empty,
  272. report_date = targetDate.Date,
  273. hour = hour,
  274. event_count = total
  275. });
  276. }
  277. return result;
  278. }
  279. public static string BuildPath(TrackType type, TkDataDTO result)
  280. {
  281. int trackId = type == TrackType.Click ? 1 : 2;
  282. if (result == null) return string.Empty;
  283. string unique_id = $"1|{result.itemId}_{result.mktId}";
  284. return BuildPath(trackId, unique_id, GetTrackScene(result.parse_type, result.riskStrategy));
  285. }
  286. public static string BuildPath(TrackType type, JdDataDTO result)
  287. {
  288. int trackId = type == TrackType.Click ? 19 : 20;
  289. if (result == null) return string.Empty;
  290. string unique_id = $"13|{result.shortLinkurl.UrlEncode()}";
  291. return BuildPath(trackId, unique_id, GetTrackScene(result.parse_type, result.riskStrategy));
  292. }
  293. public static string BuildPath(TrackType type, PddDataDTO result)
  294. {
  295. int trackId = type == TrackType.Click ? 21 : 22;
  296. if (result == null) return string.Empty;
  297. string unique_id = $"9|{result.shortLinkurl.UrlEncode()}";
  298. return BuildPath(trackId, unique_id, GetTrackScene(result.parse_type, result.riskStrategy));
  299. }
  300. public static string BuildPath(int trackId, string unique_id = "", string scene = "")
  301. {
  302. scene = NormalizeReportScene(scene);
  303. string url = $"https://api.molilian.com/tracks/track?track_id={trackId}&unique_id={unique_id}";
  304. if (!string.IsNullOrEmpty(scene)) url += $"&scene={scene.UrlEncode()}";
  305. return url;
  306. }
  307. public static string ResolveMetricScene(TrackLinkDTO? link, string scene = "")
  308. {
  309. scene = NormalizeReportScene(scene);
  310. if (!string.IsNullOrEmpty(scene)) return scene;
  311. return NormalizeOrAll(link?.scene ?? string.Empty);
  312. }
  313. public static string GetLinkCacheKey(string eventType, string typename, string scene, string uniqueId)
  314. {
  315. return GetLinkCacheKey(eventType, string.Empty, typename, scene, uniqueId);
  316. }
  317. public static string GetLinkCacheKey(string eventType, string platform, string typename, string scene, string uniqueId)
  318. {
  319. eventType = NormalizeEventType(eventType);
  320. platform = Normalize(platform);
  321. typename = Normalize(typename);
  322. scene = NormalizeOrAll(scene);
  323. uniqueId = NormalizeOrAll(uniqueId);
  324. return $"{RedisPrefix}:link:{eventType}:{platform}:{typename}:{scene}:{uniqueId}";
  325. }
  326. public static string GetLinkIdCacheKey(int trackId)
  327. {
  328. return $"{RedisPrefix}:linkid:{trackId}";
  329. }
  330. public static async Task<TrackLinkDTO> GetLinkByIdAsync(int trackId)
  331. {
  332. if (trackId <= 0) return null;
  333. string cacheKey = GetLinkIdCacheKey(trackId);
  334. try
  335. {
  336. var cached = RedisHelper.Get<TrackLinkDTO>(cacheKey);
  337. if (cached != null) return cached;
  338. }
  339. catch { }
  340. try
  341. {
  342. var item = new DBContext.Table("track_links").Get<TrackLinkDTO>("id=@id", new { id = trackId });
  343. if (item != null)
  344. {
  345. _ = RedisHelper.Set(cacheKey, item, LinkCacheExpireSeconds);
  346. }
  347. return item;
  348. }
  349. catch
  350. {
  351. return null;
  352. }
  353. }
  354. public static Task<bool> LogTrackRequestAsync(TrackRequestLogDTO dto)
  355. {
  356. try
  357. {
  358. dto.event_type = NormalizeEventType(dto.event_type);
  359. dto.platform = Normalize(dto.platform);
  360. dto.typename = Normalize(dto.typename);
  361. dto.scene = NormalizeOrAll(dto.scene);
  362. dto.unique_id = NormalizeOrAll(dto.unique_id);
  363. dto.ip = Normalize(dto.ip);
  364. dto.user_agent = Normalize(dto.user_agent);
  365. dto.referer = Normalize(dto.referer);
  366. dto.create_time = DateTime.Now;
  367. RedisHelper.RPush(TrackRequestLogKey, dto);
  368. return Task.FromResult(true);
  369. }
  370. catch
  371. {
  372. return Task.FromResult(false);
  373. }
  374. }
  375. public static async Task<int> InsertTrackRequestLogAsync(int limit, YunhuiKit.RedisClient redis)
  376. {
  377. int count = 0;
  378. try
  379. {
  380. using var conn = DBContext.GetOpenConnection();
  381. for (int i = 0; i < limit; i++)
  382. {
  383. var entity = await redis.LPopAsync<TrackRequestLogDTO>(TrackRequestLogKey);
  384. if (entity == null) break;
  385. try
  386. {
  387. if (entity.create_time == default) entity.create_time = DateTime.Now;
  388. conn.Insert(entity);
  389. count++;
  390. }
  391. catch
  392. {
  393. // ignore malformed item
  394. }
  395. }
  396. }
  397. catch
  398. {
  399. return count;
  400. }
  401. return count;
  402. }
  403. private static string Normalize(string value)
  404. {
  405. return (value ?? string.Empty).Trim();
  406. }
  407. private static string NormalizeReportScene(string value)
  408. {
  409. var scene = Normalize(value);
  410. return scene == "默认场景" ? string.Empty : scene;
  411. }
  412. private static string NormalizeOrAll(string value)
  413. {
  414. var result = Normalize(value);
  415. return string.IsNullOrEmpty(result) ? DefaultDimensionValue : result;
  416. }
  417. private static string NormalizeEventType(string value)
  418. {
  419. return Normalize(value).ToLowerInvariant();
  420. }
  421. private static string GetTrackScene(string parseType, string riskStrategy)
  422. {
  423. parseType = NormalizeReportScene(parseType);
  424. if (!string.IsNullOrEmpty(parseType)) return parseType;
  425. riskStrategy = NormalizeReportScene(riskStrategy);
  426. if (!string.IsNullOrEmpty(riskStrategy)) return riskStrategy;
  427. return DefaultDimensionValue;
  428. }
  429. private static string BuildDailyCountKey(string eventType, int trackId, string dateStr, string scene)
  430. {
  431. eventType = NormalizeEventType(eventType);
  432. scene = NormalizeReportScene(scene);
  433. string key = $"{RedisPrefix}:daily:{eventType}:{trackId}:{dateStr}";
  434. if (!string.IsNullOrEmpty(scene)) key += $":{EncodeIndexPart(scene)}";
  435. return key;
  436. }
  437. private static string BuildHourlyCountKey(string eventType, int trackId, string hourStr, string scene)
  438. {
  439. eventType = NormalizeEventType(eventType);
  440. scene = NormalizeReportScene(scene);
  441. string key = $"{RedisPrefix}:hour:{eventType}:{trackId}:{hourStr}";
  442. if (!string.IsNullOrEmpty(scene)) key += $":{EncodeIndexPart(scene)}";
  443. return key;
  444. }
  445. private static string BuildMetricIndexValue(string eventType, int trackId, string scene)
  446. {
  447. eventType = NormalizeEventType(eventType);
  448. scene = NormalizeReportScene(scene);
  449. if (string.IsNullOrEmpty(scene)) return $"{eventType}|{trackId}";
  450. return $"{eventType}|{trackId}|{EncodeIndexPart(scene)}";
  451. }
  452. private static string EncodeIndexPart(string value)
  453. {
  454. return Normalize(value).UrlEncode();
  455. }
  456. private static string DecodeIndexPart(string value)
  457. {
  458. try
  459. {
  460. return Normalize(value).UrlDecode();
  461. }
  462. catch
  463. {
  464. return Normalize(value);
  465. }
  466. }
  467. private sealed class DailyReportBucket
  468. {
  469. public string EventType { get; set; } = string.Empty;
  470. public int TrackId { get; set; }
  471. public string Scene { get; set; } = string.Empty;
  472. public TrackLinkDTO? Link { get; set; }
  473. public int Total { get; set; }
  474. }
  475. private static int GetTrackLinkId(IDbConnection conn, string eventType, string platform, string scene, string uniqueId)
  476. {
  477. try
  478. {
  479. var record = new DBContext.Table(conn, "track_links")
  480. .Fields("id")
  481. .Get<TrackLinkDTO>("event_type=@event_type AND platform=@platform AND scene=@scene AND unique_id=@unique_id",
  482. new { event_type = eventType, platform, scene, unique_id = uniqueId });
  483. if (record == null) return 0;
  484. return record.id;
  485. }
  486. catch
  487. {
  488. return 0;
  489. }
  490. }
  491. }
  492. }