TkPoolCore.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. using dodohold.core;
  2. using Org.BouncyCastle.Bcpg.OpenPgp;
  3. using YunhuiKit;
  4. namespace molilian.core
  5. {
  6. public partial class TkPoolCore
  7. {
  8. public enum TkAction
  9. {
  10. all,
  11. parse,
  12. coupon,
  13. promotionQuery,
  14. activity
  15. }
  16. private static string _end_point;
  17. static TkPoolCore()
  18. {
  19. _end_point = Environment.GetEnvironmentVariable("EndPoint");
  20. }
  21. private static SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
  22. private static IEnumerable<TkPoolDTO> _cached;
  23. private static IEnumerable<TkPoolDTO> _all_cached;
  24. public static IEnumerable<TkPoolDTO> GetCachedAccounts()
  25. {
  26. return _all_cached ?? _cached ?? Enumerable.Empty<TkPoolDTO>();
  27. }
  28. public static async Task<TkPoolDTO> GetOneAsync(int id)
  29. {
  30. var list = await ListAsync();
  31. if (!list.Any()) return null;
  32. return list.Where(e => e.id == id).FirstOrDefault();
  33. }
  34. public static async Task<TkPoolDTO> ALLGetOneAsync(int id)
  35. {
  36. var list = await AllListAsync();
  37. if (!list.Any()) return null;
  38. return list.Where(e => e.id == id).FirstOrDefault();
  39. }
  40. public static async Task<TkPoolDTO> GetOneAsync2(TkAction action)
  41. {
  42. var list = await ListAsync().ConfigureAwait(false);
  43. if (!list.Any()) return null;
  44. // 线程安全的随机排序
  45. var random = new Random(Guid.NewGuid().GetHashCode());
  46. var shuffled = list.OrderBy(_ => random.Next()).ToList();
  47. foreach (var item in shuffled)
  48. {
  49. if (await FilterNodesAsync(item, action).ConfigureAwait(false))
  50. return item;
  51. }
  52. return null;
  53. }
  54. public static async Task<TkPoolDTO> GetOneAsync(TkAction action, bool isTaobaoUrl, string riskStrategy, int launchScene, string parse_type = "", string strategy_id = "")
  55. {
  56. var list = await ListAsync().ConfigureAwait(false);
  57. if (!list.Any())
  58. return null;
  59. // 获取所有账号(包括离线账号)
  60. var allAccounts = await AllListAsync().ConfigureAwait(false);
  61. if (allAccounts == null)
  62. return null;
  63. if (!string.IsNullOrEmpty(strategy_id))
  64. {
  65. list = list.Where(item => strategy_id.Equals(item.strategy_id)).ToList();
  66. }
  67. else
  68. {
  69. list = list.Where(item => string.IsNullOrEmpty(item.strategy_id)).ToList();
  70. }
  71. if (!list.Any()) return null;
  72. if ("dp".Equals(parse_type))
  73. {
  74. list = list.Where(item => "dp".Equals(item.parse_type)).ToList();
  75. if (!list.Any()) return null;
  76. }
  77. else if ("ym".Equals(parse_type))
  78. {
  79. list = list.Where(item => "ym".Equals(item.parse_type)).ToList();
  80. if (!list.Any()) return null;
  81. }
  82. else
  83. {
  84. list = list.Where(item => string.IsNullOrEmpty(item.parse_type)).ToList();
  85. }
  86. if (!list.Any()) return null;
  87. if (!string.IsNullOrEmpty(riskStrategy) && !"os".Equals(riskStrategy) && launchScene != -1)
  88. {
  89. list = list.Where(item => riskStrategy.Equals(item.riskStrategy) && item.launchScene == launchScene).ToList();
  90. }
  91. else
  92. {
  93. list = list.Where(item => string.IsNullOrEmpty(item.riskStrategy)).ToList();
  94. }
  95. if (!list.Any()) return null;
  96. list = FilterByAction(list, action).ToList();
  97. if (!list.Any()) return null;
  98. list = list.Where(item => PassesFastAccountChecks(item, action)).ToList();
  99. if (!list.Any()) return null;
  100. var ownerByRelatedId = BuildOwnerByRelatedAccountId(allAccounts);
  101. var onlineAccountIds = list.Select(a => a.id).ToHashSet();
  102. var filteredList = list
  103. .Where(item =>
  104. !ownerByRelatedId.TryGetValue(item.id, out var ownerAccount) ||
  105. onlineAccountIds.Contains(ownerAccount.id) ||
  106. !ownerAccount.enable_fake_click)
  107. .ToList();
  108. if (filteredList.Count == 0) return null;
  109. // 1. 筛选出有可用端点的账号池,并计算权重
  110. var weightedAccounts = new List<(TkPoolDTO account, int weight)>();
  111. var random = new Random(Guid.NewGuid().GetHashCode()); // 避免重复种子问题
  112. foreach (var item in filteredList)
  113. {
  114. // 获取账号关联的所有端点配置
  115. var endpoints = await TkEndpointCore.GetEndpointsByAccountReadonlyAsync(item.id, isTaobaoUrl, item.parseEndpoint).ConfigureAwait(false);
  116. if (endpoints == null || endpoints.Count == 0)
  117. continue;
  118. // 过滤可用端点(状态正常且未达限制)
  119. var availableEndpoints = endpoints
  120. .Where(e => e.status)
  121. .Where(e => e.hourly_calls_limit <= 0 || e.current_hourly_calls < e.hourly_calls_limit)
  122. .Where(e => e.daily_calls_limit <= 0 || e.current_daily_calls < e.daily_calls_limit)
  123. .Where(e => !TkEndpointManager.IsEndpointSuspended(item.id, e.endpoint)) // 直接检查端点对象
  124. .ToList();
  125. if (availableEndpoints.Count == 0) continue;
  126. // 计算账号权重(基于剩余调用量)
  127. int weight = availableEndpoints.Sum(e =>
  128. e.hourly_calls_limit <= 0 ? 3600 : e.hourly_calls_limit - e.current_hourly_calls);
  129. weightedAccounts.Add((item, weight));
  130. }
  131. if (weightedAccounts.Count == 0) return null;
  132. // 2. 保留原有加权随机选择,选中账号超出 QPS 时继续尝试其他账号
  133. int totalWeight = weightedAccounts.Sum(x => x.weight);
  134. int randomNumber = random.Next(0, totalWeight);
  135. foreach (var (account, weight) in weightedAccounts)
  136. {
  137. if (randomNumber < weight)
  138. {
  139. if (await FilterNodesAsync(account, action).ConfigureAwait(false) && TryAcquireQps(account))
  140. return account;
  141. break;
  142. }
  143. randomNumber -= weight;
  144. }
  145. // 3. 选中账号不可用或超过 QPS 时,回退尝试其他候选账号
  146. var fallbackCandidates = weightedAccounts
  147. .OrderBy(_ => random.Next())
  148. .Select(x => x.account);
  149. foreach (var account in fallbackCandidates)
  150. {
  151. if (await FilterNodesAsync(account, action).ConfigureAwait(false) && TryAcquireQps(account))
  152. return account;
  153. }
  154. return null;
  155. }
  156. private static readonly TimeSpan QpsWindow = TimeSpan.FromSeconds(1);
  157. private static bool TryAcquireQps(TkPoolDTO account)
  158. {
  159. if (account == null) return false;
  160. long acquiredSinceTicks = DateTime.UtcNow.Ticks;
  161. if (!SpecialBusinessRateLimiter.TryAcquire($"tk_pool_qps:{account.id}", account.qps_limit, QpsWindow))
  162. return false;
  163. // cis_limit:N 毫秒内只允许 1 次;未满足间隔时归还刚占用的 QPS 名额
  164. if (account.cis_limit > 0 &&
  165. !SpecialBusinessRateLimiter.TryAcquire($"tk_pool_cis:{account.id}", 1, TimeSpan.FromMilliseconds(account.cis_limit)))
  166. {
  167. if (account.qps_limit > 0)
  168. SpecialBusinessRateLimiter.Release($"tk_pool_qps:{account.id}", QpsWindow, acquiredSinceTicks);
  169. return false;
  170. }
  171. return true;
  172. }
  173. /// <summary>
  174. /// 归还分配账号时占用的 QPS / 请求间隔名额(转链未提交到 endpoint 时调用)
  175. /// </summary>
  176. public static void ReleaseQps(TkPoolDTO account, long acquiredSinceTicks)
  177. {
  178. if (account == null) return;
  179. if (account.qps_limit > 0)
  180. SpecialBusinessRateLimiter.Release($"tk_pool_qps:{account.id}", QpsWindow, acquiredSinceTicks);
  181. if (account.cis_limit > 0)
  182. SpecialBusinessRateLimiter.Release($"tk_pool_cis:{account.id}", TimeSpan.FromMilliseconds(account.cis_limit), acquiredSinceTicks);
  183. }
  184. private static async Task<bool> FilterNodesAsync(TkPoolDTO item, TkAction action)
  185. {
  186. if (!PassesFastAccountChecks(item, action)) return false;
  187. if (item.daily_calls_limit > 0)
  188. {
  189. int daily_num = RiskControlCore.GetCalls(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMdd"));
  190. if (daily_num >= item.daily_calls_limit) return false;
  191. }
  192. if (item.hourly_calls_limit > 0)
  193. {
  194. int hourly_num = RiskControlCore.GetCalls(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMddHH"));
  195. if (hourly_num >= item.hourly_calls_limit) return false;
  196. }
  197. var endpointCheck = await TkEndpointManager.HasAvailableEndpointAsync(item.id).ConfigureAwait(false);
  198. if (!endpointCheck) return false;
  199. switch (action)
  200. {
  201. case TkAction.parse:
  202. if (!item.enable_parse) return false;
  203. break;
  204. case TkAction.promotionQuery:
  205. if (!item.enable_promotionQuery) return false;
  206. break;
  207. case TkAction.coupon:
  208. case TkAction.activity:
  209. if (!item.enable_coupon) return false;
  210. break;
  211. }
  212. if (item.daily_income_limit == 0) return true;
  213. decimal income_amt = RiskControlCore.GetIncomeAmt(TkChannelEnum.tb, $"{item.id}");
  214. return income_amt < item.daily_income_limit;
  215. }
  216. private static IEnumerable<TkPoolDTO> FilterByAction(IEnumerable<TkPoolDTO> accounts, TkAction action)
  217. {
  218. return action switch
  219. {
  220. TkAction.parse => accounts.Where(item => item.enable_parse),
  221. TkAction.promotionQuery => accounts.Where(item => item.enable_promotionQuery),
  222. TkAction.coupon => accounts.Where(item => item.enable_coupon),
  223. TkAction.activity => accounts.Where(item => item.enable_coupon),
  224. _ => accounts
  225. };
  226. }
  227. private static bool PassesFastAccountChecks(TkPoolDTO item, TkAction action)
  228. {
  229. if (!string.IsNullOrEmpty(item.suspended_endpoint) && item.suspended_endpoint.Contains($"{_end_point}|")) return false;
  230. if (!string.IsNullOrEmpty(_end_point) && !string.IsNullOrEmpty(item.end_point) && item.end_point != _end_point)
  231. return false;
  232. if (!new WorkSchedule(item.time_range).IsWorkHour()) return false;
  233. return action switch
  234. {
  235. TkAction.parse => item.enable_parse,
  236. TkAction.promotionQuery => item.enable_promotionQuery,
  237. TkAction.coupon => item.enable_coupon,
  238. TkAction.activity => item.enable_coupon,
  239. _ => true
  240. };
  241. }
  242. private static Dictionary<int, TkPoolDTO> BuildOwnerByRelatedAccountId(IEnumerable<TkPoolDTO> allAccounts)
  243. {
  244. var result = new Dictionary<int, TkPoolDTO>();
  245. foreach (var account in allAccounts)
  246. {
  247. if (string.IsNullOrWhiteSpace(account.related_account_ids)) continue;
  248. foreach (var idStr in account.related_account_ids.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
  249. {
  250. if (!int.TryParse(idStr, out var relatedId)) continue;
  251. result.TryAdd(relatedId, account);
  252. }
  253. }
  254. return result;
  255. }
  256. public static async Task<IEnumerable<TkPoolDTO>> AllListAsync(bool force = false)
  257. {
  258. if (!force && _all_cached != default) return _all_cached;
  259. try
  260. {
  261. await _semaphore.WaitAsync();
  262. string cache_key = $"cache:all_tk_pool";
  263. var list = await RedisKit.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  264. if (force || list == default)
  265. {
  266. list = new DBContext.Table("tk_pool").Select<TkPoolDTO>();
  267. if (list == null) return default;
  268. // 等待 Redis 写入完成
  269. await RedisKit.SetAsync(cache_key, list, 30 * 86400);
  270. }
  271. _all_cached = list;
  272. return list;
  273. }
  274. catch (Exception)
  275. {
  276. // 发生异常时返回上一次的缓存,如果没有则返回默认值
  277. return _all_cached ?? default;
  278. }
  279. finally
  280. {
  281. _semaphore.Release();
  282. }
  283. }
  284. public static async Task<IEnumerable<TkPoolDTO>> ListAsync(bool force = false)
  285. {
  286. // 内存缓存检查
  287. if (!force && _cached != null) return _cached;
  288. string cache_key = "cache:tk_pool";
  289. if (!force)
  290. {
  291. var cachedList = await RedisHelper.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  292. if (cachedList != null)
  293. {
  294. _cached = cachedList;
  295. return cachedList;
  296. }
  297. }
  298. // 获取新数据
  299. await _semaphore.WaitAsync();
  300. try
  301. {
  302. // 双重检查,防止并发情况下重复加载
  303. if (!force)
  304. {
  305. var cachedList = await RedisHelper.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  306. if (cachedList != null)
  307. {
  308. _cached = cachedList;
  309. return cachedList;
  310. }
  311. }
  312. // 从数据库加载数据
  313. var list = new DBContext.Table("tk_pool")
  314. .Where("status=@status", new { status = 1 })
  315. .Select<TkPoolDTO>();
  316. if (list == null) return default;
  317. // 更新调用次数
  318. foreach (var item in list)
  319. {
  320. _ = RiskControlCore.SetCallsAsync(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMddHH"), item.current_hourly_calls);
  321. _ = RiskControlCore.SetCallsAsync(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMdd"), item.current_daily_calls);
  322. }
  323. // 更新缓存
  324. await RedisHelper.SetAsync(cache_key, list, 30 * 86400);
  325. _cached = list;
  326. return list;
  327. }
  328. finally
  329. {
  330. _semaphore.Release();
  331. }
  332. }
  333. public static void Refresh()
  334. {
  335. _ = ListAsync(true);
  336. _ = AllListAsync(true);
  337. TkEndpointCore.Refresh();
  338. TkEndpointManager.Refresh();
  339. }
  340. public static void UpdateDrawBalance(string name, decimal amout)
  341. {
  342. new DBContext.Table("tk_pool")
  343. .Add("draw_balance", amout)
  344. .Where("name=@name", new { name })
  345. .Update();
  346. _ = ListAsync(true);
  347. }
  348. public static void Suspend(string endpoint, int accountId, string name, string content)
  349. {
  350. string cache_key = $"cache:tk_pool:{accountId}:suspend";
  351. long count = RedisHelper.IncrBy(cache_key);
  352. RedisHelper.Expire(cache_key, 10);
  353. if (count > 1) return;
  354. var update = new DBContext.Table("tk_pool").Add("suspended_endpoint:", $"CONCAT(suspended_endpoint, '{endpoint},')");
  355. if (accountId > 0)
  356. {
  357. update.Where("id=@accountId", new { accountId }).Update();
  358. }
  359. else
  360. {
  361. update.Where("name=@name", new { name }).Update();
  362. }
  363. _ = ListAsync(true);
  364. NotifyCore.Notify(new NifyMessage
  365. {
  366. message = $"【淘客{accountId}:{name}】{endpoint} 暂停",
  367. priority = NifyMessagePriority.high,
  368. tags = ["red_circle"]
  369. });
  370. _ = EndPointCore.NotifyReload(true);
  371. }
  372. public static void Disabled(int accountId, string name, string content, bool is_hide)
  373. {
  374. #if DEBUG
  375. #else
  376. #endif
  377. string cache_key = $"cache:tk_pool:{accountId}:disabled";
  378. long count = RedisHelper.IncrBy(cache_key);
  379. RedisHelper.Expire(cache_key, 10);
  380. if (count > 1) return;
  381. var update = new DBContext.Table("tk_pool").Add("status", 0);
  382. if (accountId > 0)
  383. {
  384. update.Where("id=@accountId", new { accountId }).Update();
  385. }
  386. else
  387. {
  388. update.Where("name=@name", new { name }).Update();
  389. }
  390. _ = ListAsync(true);
  391. _ = AllListAsync(true);
  392. NotifyCore.Notify(new NifyMessage
  393. {
  394. message = $"【淘客{accountId}:{name}】cookie 掉线\n\n{content}",
  395. priority = NifyMessagePriority.high,
  396. tags = ["red_circle"]
  397. });
  398. if (!is_hide)
  399. {
  400. _ = NotifyCore.QYWeixinPushNotifyAsync("掉线", $"【淘客{accountId}:{name}】cookie 掉线");
  401. }
  402. _ = EndPointCore.NotifyReload(true);
  403. }
  404. public static async Task<int> UpdateCookies(string cookies, string user_agent)
  405. {
  406. if (string.IsNullOrEmpty(cookies)) return 0;
  407. cookies += ";";
  408. string dnk = cookies.GetContentPart("dnk=", ";");
  409. string company = dnk;
  410. int accountId = 0;
  411. string tb_token = cookies.GetContentPart("_tb_token_=", ";");
  412. if (string.IsNullOrEmpty(dnk) || string.IsNullOrEmpty(tb_token)) return 0;
  413. var exist = new DBContext.Table("tk_pool").Fields("id, name, company, refpid, status").Get<dynamic>("name=@dnk", new { dnk });
  414. if (exist != null)
  415. {
  416. int status = exist.status;
  417. string refpid = exist.refpid;
  418. company = exist.company;
  419. accountId = exist.id;
  420. if (!string.IsNullOrEmpty(refpid)) status = 1;
  421. new DBContext.Table("tk_pool")
  422. .Add("name", dnk)
  423. .Add("tb_token", tb_token)
  424. .Add("cookies", cookies)
  425. .Add("user_agent", user_agent)
  426. .Add("status", status)
  427. .Add("suspended_endpoint", string.Empty)
  428. .Add("last_time", DateTime.Now)
  429. .Add("login_time", DateTime.Now)
  430. .Where("id=@id", new { exist.id })
  431. .Update();
  432. RiskControlCore.SetRiskCookie($"tb:{exist.id}", "");
  433. if (status == 1) _ = ListAsync(true);
  434. }
  435. else
  436. {
  437. accountId = new DBContext.Table("tk_pool")
  438. .Add("name", dnk)
  439. .Add("description", "由cookies上报创建此记录")
  440. .Add("tb_token", tb_token)
  441. .Add("refpid", string.Empty)
  442. .Add("cookies", cookies)
  443. .Add("user_agent", user_agent)
  444. .Add("create_time", DateTime.Now)
  445. .Add("last_time", DateTime.Now)
  446. .Add("login_time", DateTime.Now)
  447. .Add("status", 0)
  448. .Create();
  449. RiskControlCore.SetRiskCookie($"tb:{accountId}", "");
  450. }
  451. NotifyCore.Notify(new NifyMessage
  452. {
  453. message = $"【淘客{accountId}:{company}】cookie 上线",
  454. tags = ["green_circle"]
  455. });
  456. _ = EndPointCore.NotifyReload(true);
  457. //NotifyCore.QYWeixinPushNotifyAsync("上线", $"【淘宝联盟:{dnk}】cookie 上报更新");
  458. return accountId;
  459. }
  460. internal static void AccountExhausted()
  461. {
  462. string cache_key = $"cache:tk_pool:account:exhausted";
  463. long count = RedisHelper.IncrBy(cache_key);
  464. if (count > 1) return;
  465. RedisHelper.Expire(cache_key, 3600);
  466. NotifyCore.Notify(new NifyMessage
  467. {
  468. message = $"【淘客】没有匹配账号",
  469. priority = NifyMessagePriority.high,
  470. tags = ["red_circle"]
  471. });
  472. _ = NotifyCore.QYWeixinPushNotifyAsync("没账号", $"【淘客】没有匹配账号");
  473. }
  474. }
  475. }