| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196 |
- using molilian.core;
- using dodohold.core;
- using Dapper;
- using Microsoft.AspNetCore.Mvc;
- using Org.BouncyCastle.Ocsp;
- using System.Collections.Concurrent;
- using System.Diagnostics;
- using System.Text.Json;
- using System.Runtime.InteropServices;
- using System.Net;
- using System.Threading;
- using System.Data;
- using Microsoft.AspNetCore.Mvc.RazorPages;
- using TencentCloud.Soe.V20180724.Models;
- using static dodohold.core.ZTOExpress.CreateOrderArgs;
- using static Spire.Xls.Core.Spreadsheet.HTMLOptions;
- using System.Net.Http.Json;
- using System.Text.RegularExpressions;
- using System.Text;
- using TencentCloud.Oceanus.V20190422.Models;
- using YunhuiKit;
- using TencentCloud.Cdn.V20180606.Models;
- namespace molilian.api.Controllers
- {
- [ApiController]
- [Route("[controller]/[action]")]
- public class TestController : ControllerBase
- {
- private const string JdStressDeeplinkContent = "openapp.jdmobile://virtual?params=%7B%22category%22%3A%22jump%22%2C%22des%22%3A%22productDetail%22%2C%22skuId%22%3A%2210139003162781%22%2C%22sourceType%22%3A%22Item%22%2C%22sourceValue%22%3A%22view-ware%22%7D";
- private const int DeeplinkReportStatsExpireSeconds = 90 * 86400;
- private const int DeeplinkReportRepairMaxDays = 366;
- protected IHttpContextAccessor _accessor;
- public TestController(IHttpContextAccessor accessor)
- {
- _accessor = accessor;
- }
- [HttpGet]
- public async Task<ActionResult> jd_unsafe_parse_stress([FromQuery] int t = 5, [FromQuery] int time = 60, [FromQuery] string ip = "127.0.0.1", [FromQuery] string oaid = "", [FromQuery] bool wait = false)
- {
- t = t <= 0 ? 5 : t;
- time = time <= 0 ? 60 : time;
- string runId = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff");
- string logName = $"run_{runId}_t{t}_time{time}";
- string startLogStatus = await SaveJdStressStartLogAsync(runId, logName, t, time, ip, oaid, wait);
- if (wait)
- {
- var result = await RunJdStressAsync(runId, logName, t, time, ip, oaid, startLogStatus, CancellationToken.None);
- return new APIResult(result);
- }
- _ = Task.Run(async () =>
- {
- try
- {
- await RunJdStressAsync(runId, logName, t, time, ip, oaid, startLogStatus, CancellationToken.None);
- }
- catch (Exception ex)
- {
- _ = new LoggerLibrary("jd_api_stress", $"{logName}_runner_error")
- .Info(ex.Message, ex.StackTrace)
- .SaveAsync();
- }
- });
- return new APIResult(new
- {
- success = true,
- message = "后台压测已启动",
- runId,
- requestPerSecond = t,
- timeSeconds = time,
- expectedRequests = (long)t * time,
- wait,
- log = new
- {
- type = "LoggerLibrary",
- dir = "jd_api_stress",
- name = logName,
- status = startLogStatus
- }
- });
- }
- [HttpGet]
- public async Task<ActionResult> ecs_list_test()
- {
- var list = AliyunPoolCore.EcsList();
- return new APIResult(new
- {
- success = true,
- msg = "ok",
- list
- });
- }
-
- [HttpGet]
- public async Task<ActionResult> testReconnectionRedis()
- {
- string cacheKey = "test";
- RedisKit.SetAsync(cacheKey, 1, 3600);
- string val = await RedisKit.GetAsync<string>(cacheKey);
- return new APIResult(new { success = "ok", val });
- }
- [HttpGet]
- public async Task<ActionResult> backfill_track_parse_metrics([FromQuery] string reportDate = "")
- {
- DateTime targetDate = DateTime.Now.Date;
- if (!string.IsNullOrWhiteSpace(reportDate) && !DateTime.TryParse(reportDate, out targetDate))
- {
- return new APIResult(new
- {
- success = false,
- message = "reportDate格式错误,请使用 yyyy-MM-dd"
- });
- }
- var result = await TracksCore.BackfillParseMetricCountersAsync(targetDate);
- return new APIResult(new
- {
- success = true,
- message = "ok",
- data = result
- });
- }
- [HttpGet]
- public async Task<ActionResult> ChangePublicIpByName(string nodeName)
- {
- var proxy_node = new DBContext.Table("proxy_nodes").Get<dynamic>("nodeName=@nodeName", new { nodeName });
- if (proxy_node == null) return new APIResult(new { success = false, msg = "没有匹配的 proxy_nodes 记录" });
- int aliyun_id = proxy_node.aliyun_id;
- string proxy_server = proxy_node.server;
- var account = new DBContext.Table("aliyun_pool").Get<AliyunPoolDTO>(aliyun_id);
- if (account == null) return new APIResult(new { success = false, msg = "没有匹配的 aliyun_pool 记录" });
- var uri = new Uri(proxy_server);
- string privateIp = uri.Host;
- AliyunCore core = new AliyunCore(account);
- var success = await core.ChangePublicIpAsync(privateIp);
- return new APIResult(new { success = "ok" });
- }
- [HttpGet]
- public async Task<ActionResult> ChangePublicIp(int id)
- {
- id = id >= 20000 ? id - 20000 : id;
- var proxy_node = new DBContext.Table("proxy_nodes").Get<dynamic>(id);
- if (proxy_node == null) return new APIResult(new { success = false, msg = "没有匹配的 proxy_nodes 记录" });
- int aliyun_id = proxy_node.aliyun_id;
- string proxy_server = proxy_node.server;
- var account = new DBContext.Table("aliyun_pool").Get<AliyunPoolDTO>(aliyun_id);
- if (account == null) return new APIResult(new { success = false, msg = "没有匹配的 aliyun_pool 记录" });
- var uri = new Uri(proxy_server);
- string privateIp = uri.Host;
- AliyunCore core = new AliyunCore(account);
- var success = await core.ChangePublicIpAsync(privateIp);
- return new APIResult(new { success = "ok" });
- }
- [HttpGet]
- //第一部 先加一个网卡,
- public async Task<ActionResult> CreateNetworkInterface(int id, string ecsid)
- {
- AliyunCore core = new AliyunCore(id);
- //创建弹性网卡并绑定公网IP
- var success = core.EcsCreateNetworkInterface("cn-beijing", ecsid);
- return new APIResult(new { success });
- }
- [HttpGet]
- //第二部 给网卡绑定很多个辅助ip
- public async Task<ActionResult> EcsAssignPrivateIpAddresses(int id, string ecsid, int count, bool isSecondary = true)
- {
- AliyunCore core = new AliyunCore(id);
- //创建弹性网卡并绑定公网IP
- var success = core.EcsAssignPrivateIpAddresses("cn-beijing", ecsid, count, !isSecondary);
- return new APIResult(new { success });
- }
- [HttpGet]
- public async Task<ActionResult> QueryAccountBalance()
- {
- AliyunPlus plus = new AliyunPlus("LTAI5tQbkTjtULQcrWGaw2VJ", "UIkkolVVEddooOKOIUByCqymZkK6ZA");
- var response = plus.QueryAccountBalance();
- var balance = response.Body.Data.AvailableAmount;
- return new APIResult(new { response });
- }
- //[HttpGet]
- //public async Task<ActionResult> test(string table = "tk_parse_logs_shop", int count = 100)
- //{
- // //table = "tk_parse_logs_shop";
- // //table = "tk_parse_logs_live";
- // //table = "tk_parse_logs_video";
- // string filter = "success=0 AND message='放弃转链' AND reason='非标准链接'";
- // for (int i = 0; i < 100; i++)
- // {
- // try
- // {
- // var list = new DBContext.Table(table)
- // .Where(filter, new { })
- // .Limit(count).Select<TkDataDTO>();
- // if (!list.Any())
- // {
- // return new APIResult(new
- // {
- // success = false,
- // message = "所有任务完成"
- // });
- // }
- // foreach (var item in list)
- // {
- // TkPoolDTO? account = TkPoolCore.GetOne(TkPoolCore.TkAction.parse);
- // if (account == null)
- // {
- // return new APIResult(new
- // {
- // success = false,
- // message = "没有工作账号"
- // });
- // }
- // var result = item.Convert2Json().Convert2Object<TkDataDTO>();
- // result.accountId = account.id;
- // result.accountName = account.company;
- // var alimama = new AlimamaPlus(account);
- // int timeout = alimama._config.rt_max;
- // using var cts = new CancellationTokenSource();
- // cts.CancelAfter(timeout);
- // result = await alimama.UnionParseAsync(item.content, result);
- // string reason = "非标准链接".Equals(result.reason) ? "非标准链接ok" : result.reason;
- // new DBContext.Table(table)
- // .Add("linkType", (int)result.link_type)
- // .Add("rawContent", result.rawContent)
- // .Add("success", result.success)
- // .Add("message", result.message)
- // .Add("reason", reason)
- // .Add("content", result.content)
- // .Add("itemId", result.itemId)
- // .Add("itemName", result.itemName)
- // .Add("pic", result.pic)
- // .Add("couponAmount", result.couponAmount)
- // .Add("promotionPrice", result.promotionPrice)
- // .Add("taoToken", result.taoToken)
- // .Add("shortLinkurl", result.shortLinkurl)
- // .Add("deeplink_url", result.deeplink_url)
- // .Add("num_iid", result.num_iid)
- // .Add("elapsedTime", result.elapsedTime)
- // .Add("elapsedTime2", result.elapsedTime2)
- // .Add("elapsedTime3", result.elapsedTime3)
- // .Add("subCode", result.subCode)
- // .Where("id=@id", new { item.id })
- // .Update();
- // }
- // }
- // catch
- // {
- // }
- // }
- // return new APIResult(new
- // {
- // success = true,
- // message = "ok"
- // });
- //}
- [HttpGet]
- public async Task<ActionResult> redu_douyin(string command)
- {
- ReduPlus plus = new ReduPlus("", "", "");
- var result = await plus.DouyinParse(command);
- return Content(result.Convert2Json());
- }
- [HttpGet]
- public async Task<ActionResult> redu_kuaishou(string command)
- {
- ReduPlus plus = new ReduPlus("", "", "");
- var result = await plus.KuaishouParse(command);
- return Content(result.Convert2Json());
- }
- [HttpPost]
- public async Task<ActionResult> test2([FromForm] string jsonContent, [FromForm] string testText)
- {
- // 用于存储输出结果的StringBuilder
- StringBuilder outputBuilder = new StringBuilder();
- // 解析JSON数据
- JsonDocument jsonDoc = JsonDocument.Parse(jsonContent);
- // 获取根元素
- JsonElement root = jsonDoc.RootElement;
- // 遍历规则
- foreach (JsonElement ruleSet in root.EnumerateArray())
- {
- string platformType = ruleSet.Read("platformType", string.Empty);
- string supplier = ruleSet.Read("supplier", string.Empty);
- outputBuilder.AppendLine($"平台类型: {platformType}, 供应商: {supplier}");
- JsonElement pwdRules = ruleSet.GetProperty("pwdRules");
- int idx = 0;
- foreach (JsonElement patternElement in pwdRules.EnumerateArray())
- {
- string pattern = patternElement.GetString();
- try
- {
- // 使用Regex类来编译正则表达式
- Regex compiledPattern = new Regex(pattern);
- if (compiledPattern.IsMatch(testText))
- {
- outputBuilder.AppendLine($"规则 {idx + 1}: 匹配\t{pattern}");
- }
- else
- {
- outputBuilder.AppendLine($"规则 {idx + 1}: 不匹配");
- }
- }
- catch (Exception e)
- {
- outputBuilder.AppendLine($"规则 {idx + 1}: 正则表达式错误 - {e.Message}\t{pattern}");
- }
- idx++;
- }
- }
- outputBuilder.AppendLine("测试完成");
- return Content(outputBuilder.ToString());
- }
- [HttpGet]
- public async Task<ActionResult> ip(string ip)
- {
- string result = IP2RegionPlus.Search(ip);
- return new APIResult(new
- {
- success = true,
- message = result
- });
- }
- [HttpPost]
- public async Task<ActionResult> testreg([FromBody] JsonElement form)
- {
- var content = form.Read("s", string.Empty);
- string shortLinkurl = AlimamaPlus.GetTaobaoLink(content);
- bool is_tao_token = AlimamaPlus.MatchRegexes(content, []);
- bool is_other = AlimamaPlus.MatchOtherInfo(content, []);
- return new APIResult(new
- {
- shortLinkurl,
- is_tao_token,
- is_other
- });
- }
- //[HttpGet]
- //public async Task<ActionResult> comparison_tk([FromQuery] int count = 100)
- //{
- // string cacheKey = ":lock_key:comparison_tk_logs";
- // int last_id = RedisHelper.Get<int>(cacheKey);
- // string filter = "id>@last_id";
- // var result = new DBContext.Table("comparison_tk_logs")
- // .Where(filter, new { last_id })
- // .Page(count, 1)
- // .Order("ID")
- // .PageList<TkDataDTO>(false);
- // var ip = "127.0.0.1";
- // var oaid = "test-comparison_tk_logs";
- // foreach (var item in result.List)
- // {
- // await UnionParseCore.TaobaoParseAsync(item.rawContent, ip, oaid);
- // RedisHelper.Set(cacheKey, item.id, 10 * 86400);
- // }
- // if (result.Count < count)
- // {
- // cacheKey = ":lock_key:start_comparison_tk";
- // RedisHelper.Set(cacheKey, 1, 600);
- // }
- // return new APIResult(new
- // {
- // success = true,
- // message = "ok"
- // });
- //}
- //[HttpGet]
- //public async Task<ActionResult> comparison_tk_raw([FromQuery] int count = 100)
- //{
- // string cacheKey = ":lock_key:comparison_tk_logs_raw";
- // int last_id = RedisHelper.Get<int>(cacheKey);
- // string filter = "id>@last_id";
- // var result = new DBContext.Table("comparison_tk_logs")
- // .Where(filter, new { last_id })
- // .Page(count, 1)
- // .Order("ID")
- // .PageList<TkDataDTO>(false);
- // var ip = "127.0.0.1";
- // var oaid = "test-comparison_tk_logs_raw";
- // foreach (var item in result.List)
- // {
- // await UnionParseCore.TaobaoParseAsync(item.rawContent, ip, oaid);
- // RedisHelper.Set(cacheKey, item.id, 10 * 86400);
- // }
- // if (result.Count < count)
- // {
- // cacheKey = ":lock_key:start_comparison_tk";
- // RedisHelper.Set(cacheKey, 1, 600);
- // }
- // return new APIResult(new
- // {
- // success = true,
- // message = "ok"
- // });
- //}
- [HttpGet]
- public async Task<ActionResult> testTask()
- {
- string url = "https://www.taobao.com";
- TkDataDTO result = new TkDataDTO();
- result.message = "init";
- result.success = true;
- int timeout = 1000;
- using var cts = new CancellationTokenSource();
- cts.CancelAfter(timeout);
- var requestTask = Task.Run(() => AlimamaPlus.testTaskAsync(result, cts.Token), cts.Token);
- var delayTask = Task.Delay(timeout, cts.Token);
- var completedTask = await Task.WhenAny(requestTask, delayTask);
- if (completedTask == requestTask)
- {
- result = await requestTask;
- }
- else
- {
- cts.Cancel();
- result.success = false;
- result.message = "放弃转链";
- result.reason = "请求超时";
- result.itemName = "点击打开淘宝APP";
- }
- return new APIResult(new
- {
- success = true,
- message = "ok",
- result,
- });
- }
- [HttpGet]
- public async Task<ActionResult> testThread()
- {
- // 查看默认的最小和最大线程数
- ThreadPool.GetMinThreads(out int defaultMinWorker, out int defaultMinIOC);
- ThreadPool.GetMaxThreads(out int defaultMaxWorker, out int defaultMaxIOC);
- string tmp = $"Default Min worker threads: {defaultMinWorker}, Min I/O completion threads: {defaultMinIOC}";
- string tmp2 = $"Default Max worker threads: {defaultMaxWorker}, Max I/O completion threads: {defaultMaxIOC}";
- // 获取当前线程池中可用的工作线程数和 I/O 完成端口线程数
- ThreadPool.GetAvailableThreads(out int availableWorkerThreads, out int availableIOCompletionThreads);
- string tmp3 = $"Current available worker threads: {availableWorkerThreads}, available I/O completion threads: {availableIOCompletionThreads}";
- return new APIResult(new
- {
- tmp,
- tmp2,
- tmp3,
- });
- }
- [HttpPost]
- public async Task<ActionResult> test1([FromBody] JsonElement form)
- {
- NotifyCore.Notify(new NifyMessage
- {
- message = $"【淘宝联盟:test】cookie 掉线",
- priority = NifyMessagePriority.high,
- tags = ["red_circle"]
- });
- return new APIResult(new
- {
- success = true,
- message = "ok"
- });
- }
- [HttpGet]
- public async Task<ActionResult> RepairDeeplinkReportStats(
- DateTime startDate = default,
- DateTime endDate = default,
- bool dryRun = true,
- bool useLegacyRedis = false,
- bool allowPartialSources = false,
- bool allowCurrentDate = false,
- string fallbackEndpoint = "",
- int commandTimeoutSeconds = 600)
- {
- var yesterday = DateTime.Now.Date.AddDays(-1);
- if (startDate == default) startDate = yesterday;
- if (endDate == default) endDate = startDate;
- startDate = startDate.Date;
- endDate = endDate.Date;
- commandTimeoutSeconds = Math.Clamp(commandTimeoutSeconds, 30, 3600);
- if (endDate < startDate)
- {
- return new APIResult(new { success = false, message = "endDate 不能早于 startDate" });
- }
- int requestedDays = (endDate - startDate).Days + 1;
- if (requestedDays > DeeplinkReportRepairMaxDays)
- {
- return new APIResult(new
- {
- success = false,
- message = $"单次最多重建 {DeeplinkReportRepairMaxDays} 天数据"
- });
- }
- if (!allowCurrentDate && endDate >= DateTime.Now.Date)
- {
- return new APIResult(new
- {
- success = false,
- message = "默认禁止重建当天数据,避免覆盖实时计数;如确需执行请传 allowCurrentDate=true"
- });
- }
- var endpoints = (EndPointCore.List(true) ?? Enumerable.Empty<EndPointDTO>())
- .Where(node => node.status && node.is_public_api)
- .Where(node => !string.IsNullOrWhiteSpace(EndPointCore.GetRedisServer(node)))
- .GroupBy(node => node.name, StringComparer.OrdinalIgnoreCase)
- .Select(group => group.First())
- .OrderBy(node => node.name, StringComparer.OrdinalIgnoreCase)
- .ToList();
- if (endpoints.Count == 0)
- {
- return new APIResult(new { success = false, message = "没有可用的公共 API Redis 节点" });
- }
- EndPointDTO fallbackNode;
- if (!string.IsNullOrWhiteSpace(fallbackEndpoint))
- {
- fallbackNode = endpoints.FirstOrDefault(node => node.name.Equals(
- fallbackEndpoint.Trim(),
- StringComparison.OrdinalIgnoreCase
- ))!;
- if (fallbackNode == null)
- {
- return new APIResult(new
- {
- success = false,
- message = $"fallbackEndpoint={fallbackEndpoint} 不在可用公共节点中",
- availableEndpoints = endpoints.Select(node => node.name).ToList()
- });
- }
- }
- else
- {
- fallbackNode = endpoints.FirstOrDefault(node => node.name.Equals(
- EndPointCore.CurrentEndPoint,
- StringComparison.OrdinalIgnoreCase
- )) ?? endpoints[0];
- }
- var endpointNames = endpoints.ToDictionary(
- node => node.name,
- node => node.name,
- StringComparer.OrdinalIgnoreCase
- );
- var knownChannelNames = GetKnownDeeplinkReportChannelNames();
- var repairDates = new List<DeeplinkReportRepairDate>();
- var warnings = new List<object>();
- var errors = new List<object>();
- if (useLegacyRedis)
- {
- return await RepairDeeplinkReportStatsFromLegacyRedisAsync(
- endpoints,
- knownChannelNames,
- startDate,
- endDate,
- dryRun
- );
- }
- var parseAdminEndpoint = EndPointCore.GetParseAdmin();
- bool usesConfiguredParseDatabase = parseAdminEndpoint != null &&
- !string.IsNullOrWhiteSpace(parseAdminEndpoint.db_server);
- using var connection = usesConfiguredParseDatabase
- ? EndPointCore.GetDbConnection(parseAdminEndpoint!.db_server)
- : DBContext.GetOpenConnection();
- if (connection.State != ConnectionState.Open) connection.Open();
- foreach (var reportDate in EachDay(startDate, endDate))
- {
- string dateKey = reportDate.ToString("yyyyMMdd");
- string toolTableName = $"tool_parse_logs_{dateKey}";
- string deeplinkTableName = $"deeplink_parse_logs_{dateKey}";
- bool toolTableExists = TableExists(connection, toolTableName, commandTimeoutSeconds);
- bool deeplinkTableExists = TableExists(connection, deeplinkTableName, commandTimeoutSeconds);
- if (!toolTableExists && !deeplinkTableExists)
- {
- warnings.Add(new
- {
- date = reportDate.ToString("yyyy-MM-dd"),
- message = "两个来源日表都不存在,已跳过",
- toolTableName,
- deeplinkTableName
- });
- continue;
- }
- if (!allowPartialSources && (!toolTableExists || !deeplinkTableExists))
- {
- warnings.Add(new
- {
- date = reportDate.ToString("yyyy-MM-dd"),
- message = "来源日表不完整,已跳过;确认缺失表确实无数据后可传 allowPartialSources=true",
- toolTableName,
- toolTableExists,
- deeplinkTableName,
- deeplinkTableExists
- });
- continue;
- }
- try
- {
- var sourceCounts = new List<DeeplinkReportRepairSourceCount>();
- if (toolTableExists)
- {
- var toolCounts = SqlMapper.Query<DeeplinkReportToolSourceRow>(
- connection,
- $@"
- SELECT
- COALESCE(end_point, '') end_point,
- channel,
- COUNT(*) total_count,
- CAST(COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) AS SIGNED) success_count
- FROM {toolTableName}
- GROUP BY COALESCE(end_point, ''), channel",
- commandTimeout: commandTimeoutSeconds
- );
- sourceCounts.AddRange(toolCounts.Select(item => new DeeplinkReportRepairSourceCount
- {
- source = toolTableName,
- source_endpoint = item.end_point?.Trim() ?? string.Empty,
- channel_name = GetDeeplinkReportChannelName(item.channel),
- total_count = item.total_count,
- success_count = item.success_count,
- fail_count = Math.Max(0, item.total_count - item.success_count)
- }));
- }
- if (deeplinkTableExists)
- {
- var deeplinkCounts = SqlMapper.Query<DeeplinkReportNamedSourceRow>(
- connection,
- $@"
- SELECT
- COALESCE(end_point, '') end_point,
- COALESCE(NULLIF(TRIM(channel_name), ''), 'unknown') channel_name,
- COUNT(*) total_count,
- CAST(COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) AS SIGNED) success_count
- FROM {deeplinkTableName}
- GROUP BY COALESCE(end_point, ''), COALESCE(NULLIF(TRIM(channel_name), ''), 'unknown')",
- commandTimeout: commandTimeoutSeconds
- );
- sourceCounts.AddRange(deeplinkCounts.Select(item => new DeeplinkReportRepairSourceCount
- {
- source = deeplinkTableName,
- source_endpoint = item.end_point?.Trim() ?? string.Empty,
- channel_name = NormalizeDeeplinkReportChannelName(item.channel_name),
- total_count = item.total_count,
- success_count = item.success_count,
- fail_count = Math.Max(0, item.total_count - item.success_count)
- }));
- }
- var mergedCounts = new Dictionary<string, DeeplinkReportRepairCount>(StringComparer.OrdinalIgnoreCase);
- var remappedSources = new List<object>();
- foreach (var sourceCount in sourceCounts)
- {
- bool endpointMatched = endpointNames.TryGetValue(sourceCount.source_endpoint, out var endpointName);
- endpointName ??= fallbackNode.name;
- if (!endpointMatched)
- {
- remappedSources.Add(new
- {
- sourceCount.source,
- sourceEndpoint = sourceCount.source_endpoint,
- mappedEndpoint = endpointName,
- sourceCount.channel_name,
- sourceCount.total_count
- });
- }
- string mergedKey = $"{endpointName}\u001f{sourceCount.channel_name}";
- if (!mergedCounts.TryGetValue(mergedKey, out var mergedCount))
- {
- mergedCount = new DeeplinkReportRepairCount
- {
- endpoint_name = endpointName,
- channel_name = sourceCount.channel_name
- };
- mergedCounts[mergedKey] = mergedCount;
- }
- mergedCount.total_count += sourceCount.total_count;
- mergedCount.success_count += sourceCount.success_count;
- mergedCount.fail_count += sourceCount.fail_count;
- knownChannelNames.Add(sourceCount.channel_name);
- }
- var dateCounts = mergedCounts.Values
- .OrderBy(item => item.endpoint_name, StringComparer.OrdinalIgnoreCase)
- .ThenByDescending(item => item.total_count)
- .ThenBy(item => item.channel_name, StringComparer.OrdinalIgnoreCase)
- .ToList();
- var repairDate = new DeeplinkReportRepairDate
- {
- report_date = reportDate,
- tool_table_exists = toolTableExists,
- deeplink_table_exists = deeplinkTableExists,
- counts = dateCounts,
- remapped_sources = remappedSources
- };
- repairDates.Add(repairDate);
- }
- catch (Exception ex)
- {
- errors.Add(new
- {
- scope = "mysql_aggregate",
- date = reportDate.ToString("yyyy-MM-dd"),
- error = FormatRepairError(ex)
- });
- }
- }
- var redisReports = new List<object>();
- foreach (var endpoint in endpoints)
- {
- var endpointReports = new List<object>();
- string redisServer = EndPointCore.GetRedisServer(endpoint);
- try
- {
- await using var scope = await RedisClientFactory.CreateScopeAsync(redisServer);
- var redis = scope.Client;
- foreach (var repairDate in repairDates)
- {
- string dateKey = repairDate.report_date.ToString("yyyyMMdd");
- var endpointCounts = repairDate.counts
- .Where(item => item.endpoint_name.Equals(endpoint.name, StringComparison.OrdinalIgnoreCase))
- .ToList();
- var expectedParentCount = SumDeeplinkReportRepairCounts(endpointCounts);
- var beforeParentCount = await ReadDeeplinkReportBucketAsync(redis, "tool", dateKey);
- string channelIndexKey = $":parse_total:tool:channels:{dateKey}";
- var indexedChannelNames = await redis.SMembersAsync<string>(channelIndexKey) ?? [];
- var channelsToClear = new HashSet<string>(knownChannelNames, StringComparer.OrdinalIgnoreCase);
- channelsToClear.UnionWith(indexedChannelNames);
- channelsToClear.UnionWith(repairDate.counts
- .Select(item => item.channel_name)
- .Where(item => !string.IsNullOrWhiteSpace(item)));
- if (!dryRun)
- {
- await redis.DelAsync(channelIndexKey);
- foreach (var channelToClear in channelsToClear)
- {
- await DeleteDeeplinkReportBucketAsync(
- redis,
- $"tool:channel:{channelToClear}",
- dateKey
- );
- }
- await WriteDeeplinkReportBucketAsync(redis, "tool", dateKey, expectedParentCount);
- foreach (var endpointCount in endpointCounts)
- {
- await WriteDeeplinkReportBucketAsync(
- redis,
- $"tool:channel:{endpointCount.channel_name}",
- dateKey,
- endpointCount
- );
- }
- var endpointChannelNames = endpointCounts
- .Where(item => item.total_count > 0)
- .Select(item => item.channel_name)
- .Distinct(StringComparer.OrdinalIgnoreCase)
- .ToArray();
- if (endpointChannelNames.Length > 0)
- {
- await redis.SAddAsync(channelIndexKey, endpointChannelNames);
- await redis.ExpireAsync(channelIndexKey, DeeplinkReportStatsExpireSeconds);
- }
- }
- var afterParentCount = dryRun
- ? null
- : await ReadDeeplinkReportBucketAsync(redis, "tool", dateKey);
- endpointReports.Add(new
- {
- date = repairDate.report_date.ToString("yyyy-MM-dd"),
- before = beforeParentCount,
- expected = expectedParentCount,
- after = afterParentCount,
- channels = endpointCounts,
- clearedChannelCount = channelsToClear.Count
- });
- }
- }
- catch (Exception ex)
- {
- errors.Add(new
- {
- scope = "redis_write",
- endpoint = endpoint.name,
- error = FormatRepairError(ex)
- });
- }
- redisReports.Add(new
- {
- endpoint = endpoint.name,
- endpoint.description,
- reports = endpointReports
- });
- }
- var dailyReports = repairDates.Select(item => new
- {
- date = item.report_date.ToString("yyyy-MM-dd"),
- item.tool_table_exists,
- item.deeplink_table_exists,
- source = new
- {
- total_count = item.counts.Sum(count => count.total_count),
- success_count = item.counts.Sum(count => count.success_count),
- fail_count = item.counts.Sum(count => count.fail_count)
- },
- channels = item.counts
- .GroupBy(count => count.channel_name, StringComparer.OrdinalIgnoreCase)
- .Select(group => new
- {
- channel_name = group.Key,
- total_count = group.Sum(count => count.total_count),
- success_count = group.Sum(count => count.success_count),
- fail_count = group.Sum(count => count.fail_count)
- })
- .OrderByDescending(count => count.total_count)
- .ThenBy(count => count.channel_name, StringComparer.OrdinalIgnoreCase)
- .ToList(),
- endpoint_channels = item.counts,
- item.remapped_sources
- }).ToList();
- return new APIResult(new
- {
- success = errors.Count == 0,
- dryRun,
- allowPartialSources,
- allowCurrentDate,
- startDate = startDate.ToString("yyyy-MM-dd"),
- endDate = endDate.ToString("yyyy-MM-dd"),
- fallbackEndpoint = fallbackNode.name,
- sourceDatabase = new
- {
- endpoint = usesConfiguredParseDatabase ? parseAdminEndpoint!.name : EndPointCore.CurrentEndPoint,
- configured = usesConfiguredParseDatabase
- },
- processedDays = repairDates.Count,
- skippedDays = requestedDays - repairDates.Count,
- dailyReports,
- redis = redisReports,
- warnings,
- errors
- });
- }
- [HttpGet]
- public async Task<ActionResult> RepairTkDailyAccountStats(
- DateTime startDate = default,
- DateTime endDate = default,
- string accountIds = "129,140",
- string extraNames = "搜同款_楚颜_128众杰科技,搜同款_广哲2",
- bool dryRun = false,
- bool repairDailyLogs = true,
- bool repairRedis = true,
- bool repairRedisNameKeys = true,
- int commandTimeoutSeconds = 600)
- {
- if (startDate == default) startDate = new DateTime(2026, 6, 16);
- if (endDate == default) endDate = DateTime.Now.Date;
- commandTimeoutSeconds = Math.Clamp(commandTimeoutSeconds, 30, 3600);
- startDate = startDate.Date;
- endDate = endDate.Date;
- if (endDate < startDate)
- {
- return new APIResult(new { success = false, message = "endDate 不能早于 startDate" });
- }
- var ids = (accountIds ?? string.Empty)
- .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
- .Select(item => int.TryParse(item, out int id) ? id : 0)
- .Where(id => id > 0)
- .Distinct()
- .ToArray();
- if (ids.Length == 0)
- {
- return new APIResult(new { success = false, message = "accountIds 不能为空" });
- }
- using var conn = CenterHub.GetOpenConnection();
- if (conn.State != ConnectionState.Open) conn.Open();
- var errors = new List<object>();
- var affectedNames = new HashSet<string>(StringComparer.Ordinal);
- var accounts = SqlMapper.Query<TkDailyRepairCountRow>(
- conn,
- "SELECT id accountId, company accountName FROM tk_pool WHERE id IN @ids",
- new { ids },
- commandTimeout: commandTimeoutSeconds).ToList();
- foreach (string name in accounts.Select(item => item.accountName).Where(item => !string.IsNullOrWhiteSpace(item)))
- {
- affectedNames.Add(name);
- }
- extraNames ??= string.Empty;
- foreach (string name in extraNames
- .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
- .Where(item => !string.IsNullOrWhiteSpace(item)))
- {
- affectedNames.Add(name);
- }
- foreach (string name in SqlMapper.Query<string>(
- conn,
- @"
- SELECT DISTINCT accountName
- FROM center_daily_logs
- WHERE channel = 0
- AND accountId IN @ids
- AND log_date BETWEEN @startDate AND @endDate
- AND COALESCE(accountName,'')<>''",
- new { ids, startDate, endDate },
- commandTimeout: commandTimeoutSeconds))
- {
- affectedNames.Add(name);
- }
- var days = EachDay(startDate, endDate).ToList();
- var dailyReports = new List<object>();
- var endpointCountsByDate = new Dictionary<string, List<TkDailyRepairEndpointCountRow>>();
- foreach (var date in days)
- {
- try
- {
- string tableName = $"tk_parse_logs_{date:yyyyMMdd}";
- if (!TableExists(conn, tableName, commandTimeoutSeconds))
- {
- dailyReports.Add(new { date = date.ToString("yyyy-MM-dd"), tableName, skipped = true, reason = "table not exists" });
- continue;
- }
- var endpointCounts = SqlMapper.Query<TkDailyRepairEndpointCountRow>(
- conn,
- $@"
- SELECT
- l.accountId,
- COALESCE(p.company, MAX(l.accountName), '') accountName,
- COALESCE(l.end_point, '') end_point,
- COUNT(*) total_count,
- CAST(COALESCE(SUM(l.success = 1), 0) AS SIGNED) success_count,
- CAST(COALESCE(SUM(l.success = 0), 0) AS SIGNED) fail_count,
- CAST(COALESCE(SUM(l.message = '放弃转链' OR l.reason = '放弃转链'), 0) AS SIGNED) abandon_count
- FROM {tableName} l
- LEFT JOIN tk_pool p ON p.id = l.accountId
- WHERE l.accountId IN @ids
- GROUP BY l.accountId, p.company, l.end_point
- ORDER BY l.accountId, l.end_point",
- new { ids },
- commandTimeout: commandTimeoutSeconds).ToList();
- endpointCountsByDate[date.ToString("yyyyMMdd")] = endpointCounts;
- var accountCounts = endpointCounts
- .GroupBy(item => item.accountId)
- .Select(group => new TkDailyRepairCountRow
- {
- accountId = group.Key,
- accountName = accounts.FirstOrDefault(item => item.accountId == group.Key)?.accountName
- ?? group.FirstOrDefault()?.accountName
- ?? string.Empty,
- total_count = group.Sum(item => item.total_count),
- success_count = group.Sum(item => item.success_count),
- fail_count = group.Sum(item => item.fail_count),
- abandon_count = group.Sum(item => item.abandon_count)
- })
- .ToList();
- int dailyLogRows = 0;
- var allAccountCounts = ids
- .Select(accountId => accountCounts.FirstOrDefault(item => item.accountId == accountId)
- ?? new TkDailyRepairCountRow
- {
- accountId = accountId,
- accountName = accounts.FirstOrDefault(item => item.accountId == accountId)?.accountName ?? string.Empty
- })
- .ToList();
- foreach (var counts in allAccountCounts)
- {
- if (!dryRun && repairDailyLogs)
- {
- dailyLogRows += UpsertCenterDailyLog(conn, date, counts, commandTimeoutSeconds);
- }
- }
- dailyReports.Add(new
- {
- date = date.ToString("yyyy-MM-dd"),
- tableName,
- skipped = false,
- dailyLogRows,
- source = "mysql:tk_parse_logs_yyyyMMdd",
- counts = allAccountCounts,
- endpointCounts
- });
- }
- catch (Exception ex)
- {
- var error = new { scope = "daily_log", date = date.ToString("yyyy-MM-dd"), error = FormatRepairError(ex) };
- errors.Add(error);
- dailyReports.Add(new { date = date.ToString("yyyy-MM-dd"), skipped = true, reason = "error", error });
- }
- }
- var endpointReports = new List<object>();
- if (repairRedis || repairRedisNameKeys)
- {
- var endpoints = EndPointCore.List(true)
- .Where(node => node.status && node.is_public_api && !string.IsNullOrEmpty(EndPointCore.GetRedisServer(node)))
- .ToList();
- foreach (var endpoint in endpoints)
- {
- var redisServer = EndPointCore.GetRedisServer(endpoint);
- var endpointReport = new List<object>();
- try
- {
- await using var scope = await RedisClientFactory.CreateScopeAsync(redisServer);
- var redis = scope.Client;
- foreach (var date in days)
- {
- string dateKey = date.ToString("yyyyMMdd");
- if (!endpointCountsByDate.TryGetValue(dateKey, out var endpointCounts))
- {
- continue;
- }
- foreach (int accountId in ids)
- {
- var counts = endpointCounts.FirstOrDefault(item =>
- item.accountId == accountId &&
- string.Equals(item.end_point, endpoint.name, StringComparison.Ordinal))
- ?? new TkDailyRepairEndpointCountRow
- {
- accountId = accountId,
- accountName = accounts.FirstOrDefault(item => item.accountId == accountId)?.accountName ?? string.Empty,
- end_point = endpoint.name
- };
- if (!dryRun && repairRedis)
- {
- await WriteParseCountKeysAsync(redis, $"tb_{accountId}", dateKey, counts);
- }
- endpointReport.Add(new
- {
- date = date.ToString("yyyy-MM-dd"),
- bucket = $"tb_{accountId}",
- counts
- });
- }
- if (repairRedisNameKeys)
- {
- foreach (string name in affectedNames)
- {
- var before = await ReadParseCountKeysAsync(redis, name, dateKey);
- if (!dryRun)
- {
- await DeleteParseBucketKeysAsync(redis, name, dateKey);
- }
- endpointReport.Add(new
- {
- date = date.ToString("yyyy-MM-dd"),
- deletedBucket = name,
- before
- });
- }
- }
- }
- }
- catch (Exception ex)
- {
- errors.Add(new { scope = "redis_endpoint", endpoint = endpoint.name, error = FormatRepairError(ex) });
- }
- endpointReports.Add(new
- {
- endpoint = endpoint.name,
- endpoint.description,
- dryRun,
- deletedBuckets = endpointReport
- });
- }
- }
- return new APIResult(new
- {
- success = errors.Count == 0,
- dryRun,
- accountIds = ids,
- extraNames,
- repairDailyLogs,
- repairRedis,
- repairRedisNameKeys,
- commandTimeoutSeconds,
- startDate = startDate.ToString("yyyy-MM-dd"),
- endDate = endDate.ToString("yyyy-MM-dd"),
- affectedNames = affectedNames.OrderBy(item => item).ToList(),
- mysql = dailyReports,
- redis = endpointReports,
- errors
- });
- }
- private static HashSet<string> GetKnownDeeplinkReportChannelNames()
- {
- var channelNames = Enum.GetNames(typeof(TkChannelEnum))
- .ToHashSet(StringComparer.OrdinalIgnoreCase);
- try
- {
- var rules = new DBContext.Table("deeplink_parse_rule")
- .Select<DeeplinkParseRuleDTO>() ?? Enumerable.Empty<DeeplinkParseRuleDTO>();
- foreach (var rule in rules)
- {
- if (!string.IsNullOrWhiteSpace(rule.channel_name))
- {
- channelNames.Add(rule.channel_name.Trim());
- }
- }
- }
- catch
- {
- // The source log rows and Redis channel index still provide enough information.
- }
- return channelNames;
- }
- private static async Task<ActionResult> RepairDeeplinkReportStatsFromLegacyRedisAsync(
- List<EndPointDTO> endpoints,
- HashSet<string> knownChannelNames,
- DateTime startDate,
- DateTime endDate,
- bool dryRun)
- {
- var sourceChannelNames = knownChannelNames
- .Where(IsLegacyDeeplinkReportSourceChannel)
- .OrderBy(channelName => channelName, StringComparer.OrdinalIgnoreCase)
- .ToList();
- var requestedDates = EachDay(startDate, endDate).ToList();
- var countsByDate = requestedDates.ToDictionary(
- reportDate => reportDate,
- _ => new List<DeeplinkReportRepairCount>()
- );
- var endpointReports = new List<object>();
- var warnings = new List<object>();
- var errors = new List<object>();
- foreach (var endpoint in endpoints)
- {
- var dateReports = new List<object>();
- string redisServer = EndPointCore.GetRedisServer(endpoint);
- try
- {
- await using var scope = await RedisClientFactory.CreateScopeAsync(redisServer);
- var redis = scope.Client;
- foreach (var reportDate in requestedDates)
- {
- string dateKey = reportDate.ToString("yyyyMMdd");
- var readTasks = sourceChannelNames.Select(async channelName =>
- {
- var legacyCount = await ReadDeeplinkReportBucketAsync(redis, channelName, dateKey);
- legacyCount.endpoint_name = endpoint.name;
- legacyCount.channel_name = channelName;
- return legacyCount;
- });
- var legacyCounts = (await Task.WhenAll(readTasks))
- .Where(count => count.total_count > 0 || count.success_count > 0 || count.fail_count > 0)
- .OrderByDescending(count => count.total_count)
- .ThenBy(count => count.channel_name, StringComparer.OrdinalIgnoreCase)
- .ToList();
- var expectedParentCount = SumDeeplinkReportRepairCounts(legacyCounts);
- var beforeParentCount = await ReadDeeplinkReportBucketAsync(redis, "tool", dateKey);
- if (expectedParentCount.total_count <= 0)
- {
- dateReports.Add(new
- {
- date = reportDate.ToString("yyyy-MM-dd"),
- sourceFound = false,
- before = beforeParentCount,
- message = "未找到旧渠道统计键,未执行清理或覆盖"
- });
- continue;
- }
- countsByDate[reportDate].AddRange(legacyCounts);
- string channelIndexKey = $":parse_total:tool:channels:{dateKey}";
- var indexedChannelNames = await redis.SMembersAsync<string>(channelIndexKey) ?? [];
- var channelsToClear = new HashSet<string>(sourceChannelNames, StringComparer.OrdinalIgnoreCase);
- channelsToClear.UnionWith(indexedChannelNames);
- if (!dryRun)
- {
- await redis.DelAsync(channelIndexKey);
- foreach (var channelToClear in channelsToClear)
- {
- await DeleteDeeplinkReportBucketAsync(
- redis,
- $"tool:channel:{channelToClear}",
- dateKey
- );
- }
- await WriteDeeplinkReportBucketAsync(redis, "tool", dateKey, expectedParentCount);
- foreach (var legacyCount in legacyCounts)
- {
- await WriteDeeplinkReportBucketAsync(
- redis,
- $"tool:channel:{legacyCount.channel_name}",
- dateKey,
- legacyCount
- );
- }
- string[] populatedChannelNames = legacyCounts
- .Where(count => count.total_count > 0)
- .Select(count => count.channel_name)
- .Distinct(StringComparer.OrdinalIgnoreCase)
- .ToArray();
- if (populatedChannelNames.Length > 0)
- {
- await redis.SAddAsync(channelIndexKey, populatedChannelNames);
- await redis.ExpireAsync(channelIndexKey, DeeplinkReportStatsExpireSeconds);
- }
- }
- var afterParentCount = dryRun
- ? null
- : await ReadDeeplinkReportBucketAsync(redis, "tool", dateKey);
- dateReports.Add(new
- {
- date = reportDate.ToString("yyyy-MM-dd"),
- sourceFound = true,
- before = beforeParentCount,
- expected = expectedParentCount,
- after = afterParentCount,
- channels = legacyCounts,
- sourceKeysPreserved = true
- });
- }
- }
- catch (Exception ex)
- {
- errors.Add(new
- {
- scope = "legacy_redis",
- endpoint = endpoint.name,
- error = FormatRepairError(ex)
- });
- }
- endpointReports.Add(new
- {
- endpoint = endpoint.name,
- endpoint.description,
- reports = dateReports
- });
- }
- foreach (var reportDate in requestedDates.Where(date => countsByDate[date].Count == 0))
- {
- warnings.Add(new
- {
- date = reportDate.ToString("yyyy-MM-dd"),
- message = "所有节点均未找到旧渠道统计,不会修改该日数据"
- });
- }
- var processedDates = requestedDates
- .Where(date => countsByDate[date].Count > 0)
- .ToList();
- var dailyReports = processedDates.Select(reportDate =>
- {
- var endpointChannelCounts = countsByDate[reportDate];
- var channelCounts = endpointChannelCounts
- .GroupBy(count => count.channel_name, StringComparer.OrdinalIgnoreCase)
- .Select(group => new
- {
- channel_name = group.Key,
- total_count = group.Sum(count => count.total_count),
- success_count = group.Sum(count => count.success_count),
- fail_count = group.Sum(count => count.fail_count)
- })
- .OrderByDescending(count => count.total_count)
- .ThenBy(count => count.channel_name, StringComparer.OrdinalIgnoreCase)
- .ToList();
- return new
- {
- date = reportDate.ToString("yyyy-MM-dd"),
- total_count = channelCounts.Sum(count => count.total_count),
- success_count = channelCounts.Sum(count => count.success_count),
- fail_count = channelCounts.Sum(count => count.fail_count),
- channels = channelCounts,
- endpoint_channels = endpointChannelCounts
- };
- }).ToList();
- return new APIResult(new
- {
- success = errors.Count == 0,
- dryRun,
- useLegacyRedis = true,
- sourceMode = "legacyRedis",
- sourceKeysPreserved = true,
- parentTotalRule = "sum(channel totals)",
- startDate = startDate.ToString("yyyy-MM-dd"),
- endDate = endDate.ToString("yyyy-MM-dd"),
- processedDays = processedDates.Count,
- skippedDays = requestedDates.Count - processedDates.Count,
- sourceChannels = sourceChannelNames,
- dailyReports,
- redis = endpointReports,
- warnings,
- errors
- });
- }
- private static bool IsLegacyDeeplinkReportSourceChannel(string channelName)
- {
- if (string.IsNullOrWhiteSpace(channelName)) return false;
- return !channelName.Equals("all", StringComparison.OrdinalIgnoreCase) &&
- !channelName.Equals("tool", StringComparison.OrdinalIgnoreCase) &&
- !channelName.Equals("unknown", StringComparison.OrdinalIgnoreCase) &&
- !channelName.Equals("legacy_unclassified", StringComparison.OrdinalIgnoreCase);
- }
- private static string GetDeeplinkReportChannelName(int channelValue)
- {
- if (Enum.IsDefined(typeof(TkChannelEnum), channelValue))
- {
- return ((TkChannelEnum)channelValue).ToString();
- }
- return $"channel_{channelValue}";
- }
- private static string NormalizeDeeplinkReportChannelName(string channelName)
- {
- return string.IsNullOrWhiteSpace(channelName) ? "unknown" : channelName.Trim();
- }
- private static DeeplinkReportRepairCount SumDeeplinkReportRepairCounts(
- IEnumerable<DeeplinkReportRepairCount> counts)
- {
- return new DeeplinkReportRepairCount
- {
- total_count = counts.Sum(item => item.total_count),
- success_count = counts.Sum(item => item.success_count),
- fail_count = counts.Sum(item => item.fail_count)
- };
- }
- private static async Task<DeeplinkReportRepairCount> ReadDeeplinkReportBucketAsync(
- YunhuiKit.RedisClient redis,
- string bucket,
- string dateKey)
- {
- return new DeeplinkReportRepairCount
- {
- total_count = await redis.GetAsync<long>($":parse_total:{bucket}:{dateKey}"),
- success_count = await redis.GetAsync<long>($":parse_total:{bucket}:success:{dateKey}"),
- fail_count = await redis.GetAsync<long>($":parse_total:{bucket}:fail:{dateKey}")
- };
- }
- private static Task<long> DeleteDeeplinkReportBucketAsync(
- YunhuiKit.RedisClient redis,
- string bucket,
- string dateKey)
- {
- return redis.DelAsync(
- $":parse_total:{bucket}:{dateKey}",
- $":parse_total:{bucket}:success:{dateKey}",
- $":parse_total:{bucket}:fail:{dateKey}"
- );
- }
- private static async Task WriteDeeplinkReportBucketAsync(
- YunhuiKit.RedisClient redis,
- string bucket,
- string dateKey,
- DeeplinkReportRepairCount counts)
- {
- if (counts.total_count <= 0)
- {
- await DeleteDeeplinkReportBucketAsync(redis, bucket, dateKey);
- return;
- }
- bool totalWritten = await redis.SetAsync(
- $":parse_total:{bucket}:{dateKey}",
- counts.total_count,
- DeeplinkReportStatsExpireSeconds
- );
- bool successWritten = await redis.SetAsync(
- $":parse_total:{bucket}:success:{dateKey}",
- counts.success_count,
- DeeplinkReportStatsExpireSeconds
- );
- bool failWritten = await redis.SetAsync(
- $":parse_total:{bucket}:fail:{dateKey}",
- counts.fail_count,
- DeeplinkReportStatsExpireSeconds
- );
- if (!totalWritten || !successWritten || !failWritten)
- {
- throw new InvalidOperationException($"Redis 写入失败:bucket={bucket}, date={dateKey}");
- }
- }
- private sealed class DeeplinkReportToolSourceRow
- {
- public string end_point { get; set; } = string.Empty;
- public int channel { get; set; }
- public long total_count { get; set; }
- public long success_count { get; set; }
- }
- private sealed class DeeplinkReportNamedSourceRow
- {
- public string end_point { get; set; } = string.Empty;
- public string channel_name { get; set; } = string.Empty;
- public long total_count { get; set; }
- public long success_count { get; set; }
- }
- private sealed class DeeplinkReportRepairSourceCount
- {
- public string source { get; set; } = string.Empty;
- public string source_endpoint { get; set; } = string.Empty;
- public string channel_name { get; set; } = string.Empty;
- public long total_count { get; set; }
- public long success_count { get; set; }
- public long fail_count { get; set; }
- }
- private sealed class DeeplinkReportRepairCount
- {
- public string endpoint_name { get; set; } = string.Empty;
- public string channel_name { get; set; } = string.Empty;
- public long total_count { get; set; }
- public long success_count { get; set; }
- public long fail_count { get; set; }
- }
- private sealed class DeeplinkReportRepairDate
- {
- public DateTime report_date { get; set; }
- public bool tool_table_exists { get; set; }
- public bool deeplink_table_exists { get; set; }
- public List<DeeplinkReportRepairCount> counts { get; set; } = [];
- public List<object> remapped_sources { get; set; } = [];
- }
- private static IEnumerable<DateTime> EachDay(DateTime startDate, DateTime endDate)
- {
- for (var date = startDate.Date; date <= endDate.Date; date = date.AddDays(1))
- {
- yield return date;
- }
- }
- private static bool TableExists(IDbConnection conn, string tableName, int commandTimeoutSeconds)
- {
- const string sql = @"
- SELECT COUNT(*)
- FROM information_schema.tables
- WHERE table_schema = DATABASE()
- AND table_name = @tableName";
- return SqlMapper.ExecuteScalar<int>(
- conn,
- sql,
- new { tableName },
- commandTimeout: commandTimeoutSeconds) > 0;
- }
- private static int UpsertCenterDailyLog(IDbConnection conn, DateTime date, TkDailyRepairCountRow counts, int commandTimeoutSeconds)
- {
- if (string.IsNullOrWhiteSpace(counts.accountName)) return 0;
- string successPercentage = counts.total_count > 0 ? $"{counts.success_count / (double)counts.total_count * 100:f2}%" : string.Empty;
- string abandonPercentage = counts.total_count > 0 ? $"{counts.abandon_count / (double)counts.total_count * 100:f2}%" : string.Empty;
- var existingIds = SqlMapper.Query<int>(
- conn,
- @"
- SELECT id
- FROM center_daily_logs
- WHERE channel = 0
- AND log_date = @date
- AND accountId = @accountId
- ORDER BY id",
- new { date, counts.accountId },
- commandTimeout: commandTimeoutSeconds).ToList();
- if (existingIds.Count > 0)
- {
- int affectedRows = SqlMapper.Execute(
- conn,
- @"
- UPDATE center_daily_logs
- SET accountName = @accountName,
- parse_total_count = @totalCount,
- parse_success_count = @successCount,
- parse_abandon_count = @abandonCount,
- parse_success_percentage = @successPercentage,
- parse_abandon_percentage = @abandonPercentage,
- last_time = NOW()
- WHERE id = @id",
- new
- {
- id = existingIds[0],
- counts.accountName,
- totalCount = counts.total_count,
- successCount = counts.success_count,
- abandonCount = counts.abandon_count,
- successPercentage,
- abandonPercentage
- },
- commandTimeout: commandTimeoutSeconds);
- if (existingIds.Count > 1)
- {
- affectedRows += SqlMapper.Execute(
- conn,
- "DELETE FROM center_daily_logs WHERE id IN @ids",
- new { ids = existingIds.Skip(1).ToArray() },
- commandTimeout: commandTimeoutSeconds);
- }
- return affectedRows;
- }
- if (counts.total_count <= 0) return 0;
- return SqlMapper.Execute(
- conn,
- @"
- INSERT INTO center_daily_logs
- (channel, accountId, accountName, log_date, create_time, last_time,
- parse_total_count, parse_success_count, parse_abandon_count,
- parse_success_percentage, parse_abandon_percentage)
- VALUES
- (0, @accountId, @accountName, @date, NOW(), NOW(),
- @totalCount, @successCount, @abandonCount,
- @successPercentage, @abandonPercentage)",
- new
- {
- date,
- counts.accountId,
- counts.accountName,
- totalCount = counts.total_count,
- successCount = counts.success_count,
- abandonCount = counts.abandon_count,
- successPercentage,
- abandonPercentage
- },
- commandTimeout: commandTimeoutSeconds);
- }
- private static async Task<TkDailyRepairCountRow> ReadParseCountKeysAsync(YunhuiKit.RedisClient redis, string bucket, string dateKey)
- {
- return new TkDailyRepairCountRow
- {
- accountName = bucket,
- total_count = await redis.GetAsync<int>($":parse_total:{bucket}:{dateKey}"),
- success_count = await redis.GetAsync<int>($":parse_total:{bucket}:success:{dateKey}"),
- fail_count = await redis.GetAsync<int>($":parse_total:{bucket}:fail:{dateKey}"),
- abandon_count = await redis.GetAsync<int>($":parse_total:{bucket}:放弃转链:{dateKey}")
- };
- }
- private static async Task DeleteParseBucketKeysAsync(YunhuiKit.RedisClient redis, string bucket, string dateKey)
- {
- var keys = new List<string>
- {
- $":parse_total:{bucket}:{dateKey}",
- $":parse_total:{bucket}:success:{dateKey}",
- $":parse_total:{bucket}:fail:{dateKey}",
- $":parse_total:{bucket}:放弃转链:{dateKey}",
- $":parse_total:{bucket}:message:{dateKey}",
- $":parse_total:{bucket}:reason:{dateKey}"
- };
- foreach (string dpBucket in new[] { "dp_none", "dp_home", "dp_success", "dp_fail" })
- {
- keys.Add($":parse_total:{dpBucket}:{bucket}:{dateKey}");
- keys.Add($":parse_total:{dpBucket}:{bucket}:success:{dateKey}");
- keys.Add($":parse_total:{dpBucket}:{bucket}:fail:{dateKey}");
- keys.Add($":parse_total:{dpBucket}:{bucket}:放弃转链:{dateKey}");
- keys.Add($":parse_total:{dpBucket}:{bucket}:message:{dateKey}");
- keys.Add($":parse_total:{dpBucket}:{bucket}:reason:{dateKey}");
- }
- await redis.DelAsync(keys.ToArray());
- }
- private static string FormatRepairError(Exception ex)
- {
- return ex.InnerException == null ? ex.Message : $"{ex.Message} | {ex.InnerException.Message}";
- }
- private static async Task WriteParseCountKeysAsync(YunhuiKit.RedisClient redis, string bucket, string dateKey, TkDailyRepairCountRow counts)
- {
- var keys = new[]
- {
- $":parse_total:{bucket}:{dateKey}",
- $":parse_total:{bucket}:success:{dateKey}",
- $":parse_total:{bucket}:fail:{dateKey}",
- $":parse_total:{bucket}:放弃转链:{dateKey}"
- };
- if (counts.total_count <= 0)
- {
- await redis.DelAsync(keys);
- return;
- }
- await redis.SetAsync(keys[0], counts.total_count, 90 * 86400);
- await redis.SetAsync(keys[1], counts.success_count, 90 * 86400);
- await redis.SetAsync(keys[2], counts.fail_count, 90 * 86400);
- await redis.SetAsync(keys[3], counts.abandon_count, 90 * 86400);
- }
- private class TkDailyRepairCountRow
- {
- public int accountId { get; set; }
- public string accountName { get; set; } = string.Empty;
- public long total_count { get; set; }
- public long success_count { get; set; }
- public long fail_count { get; set; }
- public long abandon_count { get; set; }
- }
- private sealed class TkDailyRepairEndpointCountRow : TkDailyRepairCountRow
- {
- public string end_point { get; set; } = string.Empty;
- }
- private static async Task<string> SaveJdStressStartLogAsync(string runId, string logName, int t, int time, string ip, string oaid, bool wait)
- {
- try
- {
- await new LoggerLibrary("jd_api_stress", logName)
- .AppendLine($"status=started")
- .AppendLine($"runId={runId}")
- .AppendLine($"startedAt={DateTime.Now:O}")
- .AppendLine($"t={t}")
- .AppendLine($"timeSeconds={time}")
- .AppendLine($"ip={ip}")
- .AppendLine($"oaid={oaid}")
- .AppendLine($"wait={wait}")
- .AppendLine($"content={JdStressDeeplinkContent}")
- .SaveAsync();
- return "started";
- }
- catch (Exception ex)
- {
- return ex.Message;
- }
- }
- private static async Task<JdStressRunResult> RunJdStressAsync(string runId, string logName, int t, int time, string ip, string oaid, string startLogStatus, CancellationToken cancellationToken)
- {
- var startedAt = DateTime.Now;
- var stopwatch = Stopwatch.StartNew();
- long scheduledCount = 0;
- long completedCount = 0;
- long successCount = 0;
- long failCount = 0;
- long exceptionCount = 0;
- long riskControlCount = 0;
- long totalElapsedMs = 0;
- int activeCount = 0;
- int peakActiveCount = 0;
- var responseLines = new ConcurrentQueue<string>();
- var messageCounts = new ConcurrentDictionary<string, int>(StringComparer.Ordinal);
- var codeCounts = new ConcurrentDictionary<string, int>(StringComparer.Ordinal);
- int initialTaskCapacity = (int)Math.Min((long)t * Math.Min(time, 60), 4096L);
- var runningTasks = new List<Task>(initialTaskCapacity);
- string message = "ok";
- try
- {
- for (int second = 0; second < time && !cancellationToken.IsCancellationRequested; second++)
- {
- for (int i = 0; i < t; i++)
- {
- long sequence = Interlocked.Increment(ref scheduledCount);
- runningTasks.Add(Task.Run(async () =>
- {
- int currentActive = Interlocked.Increment(ref activeCount);
- UpdateMax(ref peakActiveCount, currentActive);
- try
- {
- var item = await ExecuteJdStressRequestAsync(sequence, ip, oaid, cancellationToken);
- Interlocked.Increment(ref completedCount);
- Interlocked.Add(ref totalElapsedMs, item.ElapsedMs);
- if (item.Success)
- {
- Interlocked.Increment(ref successCount);
- }
- else
- {
- Interlocked.Increment(ref failCount);
- }
- if (item.IsException)
- {
- Interlocked.Increment(ref exceptionCount);
- }
- if (IsRiskControlResult(item))
- {
- Interlocked.Increment(ref riskControlCount);
- }
- string messageKey = string.IsNullOrWhiteSpace(item.SubMessage)
- ? item.Message
- : $"{item.Message}:{item.SubMessage}";
- if (string.IsNullOrWhiteSpace(messageKey)) messageKey = "empty";
- messageCounts.AddOrUpdate(messageKey, 1, (_, value) => value + 1);
- codeCounts.AddOrUpdate(item.Code.ToString(), 1, (_, value) => value + 1);
- responseLines.Enqueue(
- $"{item.FinishedAt:O}\tseq={item.Sequence}\telapsedMs={item.ElapsedMs}\tcode={item.Code}\tsuccess={item.Success}\tmessage={NormalizeLogValue(item.Message)}\tsub_message={NormalizeLogValue(item.SubMessage)}\tresponse={NormalizeLogValue(item.Response)}");
- }
- finally
- {
- Interlocked.Decrement(ref activeCount);
- }
- }));
- }
- await ObserveCompletedTasksAsync(runningTasks);
- var nextTick = TimeSpan.FromSeconds(second + 1);
- var delay = nextTick - stopwatch.Elapsed;
- if (delay > TimeSpan.Zero)
- {
- await Task.Delay(delay, cancellationToken);
- }
- }
- }
- catch (OperationCanceledException ex)
- {
- message = $"canceled:{ex.Message}";
- responseLines.Enqueue($"{DateTime.Now:O}\tmessage={NormalizeLogValue(message)}");
- }
- catch (Exception ex)
- {
- message = $"runner error:{ex.Message}";
- responseLines.Enqueue($"{DateTime.Now:O}\tmessage={NormalizeLogValue(message)}\tstack={NormalizeLogValue(ex.StackTrace ?? string.Empty)}");
- }
- try
- {
- await Task.WhenAll(runningTasks);
- }
- catch (Exception ex)
- {
- message = $"task wait error:{ex.Message}";
- responseLines.Enqueue($"{DateTime.Now:O}\tmessage={NormalizeLogValue(message)}\tstack={NormalizeLogValue(ex.StackTrace ?? string.Empty)}");
- }
- stopwatch.Stop();
- string logStatus = "saved";
- try
- {
- var log = new LoggerLibrary("jd_api_stress", logName);
- log.AppendLine($"status=finished");
- log.AppendLine($"startLogStatus={startLogStatus}");
- log.AppendLine($"runId={runId}");
- log.AppendLine($"startedAt={startedAt:O}");
- log.AppendLine($"finishedAt={DateTime.Now:O}");
- log.AppendLine($"t={t}");
- log.AppendLine($"timeSeconds={time}");
- log.AppendLine($"ip={ip}");
- log.AppendLine($"oaid={oaid}");
- log.AppendLine($"content={JdStressDeeplinkContent}");
- log.AppendLine($"scheduled={scheduledCount}");
- log.AppendLine($"completed={completedCount}");
- log.AppendLine($"success={successCount}");
- log.AppendLine($"fail={failCount}");
- log.AppendLine($"exception={exceptionCount}");
- log.AppendLine($"riskControl={riskControlCount}");
- log.AppendLine($"peakActive={peakActiveCount}");
- log.AppendLine("messageCounts=");
- foreach (var item in messageCounts.OrderByDescending(item => item.Value))
- {
- log.AppendLine($"{item.Key}\t{item.Value}");
- }
- log.AppendLine("codeCounts=");
- foreach (var item in codeCounts.OrderByDescending(item => item.Value))
- {
- log.AppendLine($"{item.Key}\t{item.Value}");
- }
- log.AppendLine("responses=");
- while (responseLines.TryDequeue(out string? line))
- {
- log.AppendLine(line);
- }
- await log.SaveAsync();
- }
- catch (Exception ex)
- {
- logStatus = ex.Message;
- }
- return new JdStressRunResult
- {
- success = true,
- message = message,
- runId = runId,
- requestPerSecond = t,
- timeSeconds = time,
- expectedRequests = (long)t * time,
- scheduledCount = scheduledCount,
- completedCount = completedCount,
- successCount = successCount,
- failCount = failCount,
- exceptionCount = exceptionCount,
- riskControlCount = riskControlCount,
- peakActiveCount = peakActiveCount,
- averageElapsedMs = completedCount == 0 ? 0 : Math.Round(totalElapsedMs / (double)completedCount, 2),
- elapsedSeconds = Math.Round(stopwatch.Elapsed.TotalSeconds, 2),
- messageCounts = messageCounts.OrderByDescending(item => item.Value).ToDictionary(item => item.Key, item => item.Value),
- codeCounts = codeCounts.OrderByDescending(item => item.Value).ToDictionary(item => item.Key, item => item.Value),
- log = new JdStressLogInfo
- {
- type = "LoggerLibrary",
- dir = "jd_api_stress",
- name = logName,
- status = logStatus
- }
- };
- }
- private static async Task ObserveCompletedTasksAsync(List<Task> runningTasks)
- {
- for (int i = runningTasks.Count - 1; i >= 0; i--)
- {
- if (!runningTasks[i].IsCompleted) continue;
- await runningTasks[i];
- runningTasks.RemoveAt(i);
- }
- }
- private static async Task<JdStressRequestResult> ExecuteJdStressRequestAsync(long sequence, string ip, string oaid, CancellationToken cancellationToken)
- {
- var sw = Stopwatch.StartNew();
- try
- {
- var request = new UnionParseRequest
- {
- Content = JdStressDeeplinkContent,
- Channel = "jd",
- CommerceType = 0,
- Ip = ip,
- Oaid = oaid,
- RiskStrategy = string.Empty,
- LaunchScene = 0,
- AccountId = 0,
- SpecialText = 0,
- QueryText = string.Empty,
- ClickId = string.Empty,
- Type = "dp",
- Pic = string.Empty
- };
- var result = await UnionParseCore.DeeplinkJdParseAsync(request, cancellationToken);
- sw.Stop();
- string response = result.Content ?? string.Empty;
- var parsed = ParseJdStressResponse(response);
- parsed.Sequence = sequence;
- parsed.ElapsedMs = sw.ElapsedMilliseconds;
- parsed.Response = response;
- parsed.FinishedAt = DateTime.Now;
- return parsed;
- }
- catch (Exception ex)
- {
- sw.Stop();
- return new JdStressRequestResult
- {
- Sequence = sequence,
- ElapsedMs = sw.ElapsedMilliseconds,
- Success = false,
- Message = "exception",
- SubMessage = ex.Message,
- Code = 0,
- Response = ex.ToString(),
- FinishedAt = DateTime.Now,
- IsException = true
- };
- }
- }
- private static JdStressRequestResult ParseJdStressResponse(string response)
- {
- var result = new JdStressRequestResult();
- if (string.IsNullOrWhiteSpace(response))
- {
- result.Message = "empty response";
- return result;
- }
- try
- {
- using var doc = JsonDocument.Parse(response);
- var root = doc.RootElement;
- result.Success = ReadBool(root, "success");
- result.Message = ReadString(root, "message");
- result.SubMessage = ReadString(root, "sub_message");
- result.Code = ReadInt(root, "code");
- }
- catch (Exception ex)
- {
- result.Success = false;
- result.Message = "parse response error";
- result.SubMessage = ex.Message;
- result.Code = 0;
- }
- return result;
- }
- private static bool ReadBool(JsonElement root, string propertyName)
- {
- if (!root.TryGetProperty(propertyName, out var property)) return false;
- return property.ValueKind switch
- {
- JsonValueKind.True => true,
- JsonValueKind.False => false,
- JsonValueKind.Number => property.TryGetInt32(out int value) && value != 0,
- JsonValueKind.String => bool.TryParse(property.GetString(), out bool value) && value,
- _ => false
- };
- }
- private static int ReadInt(JsonElement root, string propertyName)
- {
- if (!root.TryGetProperty(propertyName, out var property)) return 0;
- return property.ValueKind switch
- {
- JsonValueKind.Number => property.TryGetInt32(out int value) ? value : 0,
- JsonValueKind.String => int.TryParse(property.GetString(), out int value) ? value : 0,
- _ => 0
- };
- }
- private static string ReadString(JsonElement root, string propertyName)
- {
- if (!root.TryGetProperty(propertyName, out var property)) return string.Empty;
- if (property.ValueKind == JsonValueKind.Null || property.ValueKind == JsonValueKind.Undefined) return string.Empty;
- return property.ValueKind == JsonValueKind.String ? property.GetString() ?? string.Empty : property.ToString();
- }
- private static bool IsRiskControlResult(JdStressRequestResult result)
- {
- if (!"放弃转链".Equals(result.Message, StringComparison.Ordinal)) return false;
- return result.SubMessage.Contains("控制", StringComparison.Ordinal)
- || result.SubMessage.Contains("风控", StringComparison.Ordinal)
- || result.SubMessage.Contains("限流", StringComparison.Ordinal)
- || result.SubMessage.Contains("频", StringComparison.Ordinal)
- || result.SubMessage.Contains("系统繁忙", StringComparison.Ordinal);
- }
- private static string NormalizeLogValue(string value)
- {
- return (value ?? string.Empty)
- .Replace("\r", "\\r")
- .Replace("\n", "\\n")
- .Replace("\t", " ");
- }
- private static void UpdateMax(ref int target, int value)
- {
- int snapshot;
- while (value > (snapshot = Volatile.Read(ref target))
- && Interlocked.CompareExchange(ref target, value, snapshot) != snapshot)
- {
- }
- }
- private sealed class JdStressRequestResult
- {
- public long Sequence { get; set; }
- public bool Success { get; set; }
- public string Message { get; set; } = string.Empty;
- public string SubMessage { get; set; } = string.Empty;
- public int Code { get; set; }
- public long ElapsedMs { get; set; }
- public string Response { get; set; } = string.Empty;
- public DateTime FinishedAt { get; set; }
- public bool IsException { get; set; }
- }
- private sealed class JdStressRunResult
- {
- public bool success { get; set; }
- public string message { get; set; } = string.Empty;
- public string runId { get; set; } = string.Empty;
- public int requestPerSecond { get; set; }
- public int timeSeconds { get; set; }
- public long expectedRequests { get; set; }
- public long scheduledCount { get; set; }
- public long completedCount { get; set; }
- public long successCount { get; set; }
- public long failCount { get; set; }
- public long exceptionCount { get; set; }
- public long riskControlCount { get; set; }
- public int peakActiveCount { get; set; }
- public double averageElapsedMs { get; set; }
- public double elapsedSeconds { get; set; }
- public Dictionary<string, int> messageCounts { get; set; } = [];
- public Dictionary<string, int> codeCounts { get; set; } = [];
- public JdStressLogInfo log { get; set; } = new();
- }
- private sealed class JdStressLogInfo
- {
- public string type { get; set; } = string.Empty;
- public string dir { get; set; } = string.Empty;
- public string name { get; set; } = string.Empty;
- public string status { get; set; } = string.Empty;
- }
- [HttpGet]
- public async Task<ActionResult> xxx()
- {
- var list = await TkPoolCore.ListAsync();
- if (list == null) return new APIResult(new { success = false, message = "没有有效账号", });
- string message = string.Empty;
- foreach (var account in list)
- {
- try
- {
- var alimama = new AlimamaPlus(account);
- alimama.RenewCookie();
- }
- catch (Exception ex)
- {
- message = $"【cookie续期】xxxx\n{ex.Message}\n{ex.StackTrace}";
- NotifyCore.Notify(new NifyMessage
- {
- message = message,
- priority = NifyMessagePriority.high,
- tags = ["red_circle"]
- });
- continue;
- }
- }
- return new APIResult(new { success = true, message = "ok" });
- }
- }
- }
|