MonitorCosmosDB.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.Http;
  4. using System.Text.Json;
  5. using System.Threading.Tasks;
  6. using Azure.Cosmos;
  7. using Azure.Messaging.ServiceBus;
  8. using Microsoft.Azure.Documents;
  9. using Microsoft.Azure.WebJobs;
  10. using Microsoft.Extensions.Logging;
  11. using TEAMModelOS.SDK.DI;
  12. using TEAMModelOS.SDK.Extension;
  13. using TEAMModelOS.SDK.Models;
  14. namespace TEAMModelFunction
  15. {
  16. public class MonitorCosmosDB
  17. {
  18. private readonly IHttpClientFactory _clientFactory;
  19. private readonly AzureCosmosFactory _azureCosmos;
  20. private readonly AzureServiceBusFactory _serviceBus;
  21. private readonly AzureStorageFactory _azureStorage;
  22. private readonly DingDing _dingDing;
  23. public MonitorCosmosDB(IHttpClientFactory clientFactory, AzureCosmosFactory azureCosmos, AzureServiceBusFactory azureServiceBus, AzureStorageFactory azureStorage, DingDing dingDing)
  24. {
  25. _clientFactory = clientFactory;
  26. _azureCosmos = azureCosmos;
  27. _serviceBus = azureServiceBus;
  28. _azureStorage = azureStorage;
  29. _dingDing = dingDing;
  30. }
  31. [FunctionName("Common")]
  32. public async Task Common([CosmosDBTrigger(
  33. databaseName: "TEAMModelOS",
  34. collectionName: "Common",
  35. ConnectionStringSetting = "Azure:Cosmos:ConnectionString",
  36. LeaseCollectionName = "leases")]IReadOnlyList<Document> inputs, ILogger log)
  37. {
  38. if (inputs != null && inputs.Count > 0)
  39. {
  40. log.LogInformation("Documents modified " + inputs.Count);
  41. log.LogInformation("First document Id " + inputs[0].Id);
  42. var client = _azureCosmos.GetCosmosClient();
  43. foreach (var input in inputs)
  44. {
  45. string pk = input.GetPropertyValue<string>("pk");
  46. if (!string.IsNullOrWhiteSpace(pk))
  47. {
  48. long stime = input.GetPropertyValue<long>("startTime");
  49. long etime = input.GetPropertyValue<long>("endTime");
  50. string school = input.GetPropertyValue<string>("school");
  51. string code = input.GetPropertyValue<string>("code");
  52. await _dingDing.SendBotMsg($"CosmosDBTrigger,{pk}\n" +
  53. $"Start Time:{DateTimeOffset.FromUnixTimeMilliseconds(stime).AddHours(8)}\n" +
  54. $"End Time:{DateTimeOffset.FromUnixTimeMilliseconds(etime).AddHours(8)}",
  55. GroupNames.醍摩豆服務運維群組);
  56. switch (pk)
  57. {
  58. case "Exam":
  59. ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(input.Id, new Azure.Cosmos.PartitionKey($"{code}"));
  60. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  61. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{school}") }))
  62. {
  63. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  64. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  65. {
  66. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  67. {
  68. examClassResults.Add(obj.ToObject<ExamClassResult>());
  69. }
  70. }
  71. }
  72. List<ChangeRecord> records = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", info.progress } });
  73. //ChangeRecord record = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{info.progress}"));
  74. switch (info.progress)
  75. {
  76. case "pending":
  77. var message = new ServiceBusMessage(new { id = input.Id, progress = "going", code = code }.ToJsonString());
  78. message.ApplicationProperties.Add("name", "Exam");
  79. if (records.Count > 0)
  80. {
  81. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", records[0].sequenceNumber);
  82. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", message, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  83. records[0].sequenceNumber = start;
  84. await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
  85. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  86. }
  87. else
  88. {
  89. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", message, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  90. ChangeRecord changeRecord = new ChangeRecord
  91. {
  92. RowKey = input.Id,
  93. PartitionKey = "pending",
  94. sequenceNumber = start,
  95. msgId = message.MessageId
  96. };
  97. await _azureStorage.Save<ChangeRecord>(changeRecord);
  98. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  99. }
  100. break;
  101. case "going":
  102. if (examClassResults.Count == 0)
  103. {
  104. // 初始化ExamClassResult
  105. for (int j = 0; j < info.subjects.Count; j++)
  106. {
  107. for (int k = 0; k < info.targetClassIds.Count; k++)
  108. {
  109. ExamClassResult result = new ExamClassResult
  110. {
  111. code = "ExamClassResult-" + info.school,
  112. examId = info.id,
  113. id = Guid.NewGuid().ToString(),
  114. subjectId = info.subjects[j].id,
  115. year = info.year,
  116. scope = info.scope
  117. };
  118. result.info.id = info.targetClassIds[k];
  119. var sresponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(info.targetClassIds[k], new Azure.Cosmos.PartitionKey($"Class-{info.school}"));
  120. if (sresponse.Status == 200)
  121. {
  122. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  123. Class classroom = json.ToObject<Class>();
  124. result.info.name = classroom.name;
  125. List<List<string>> ans = new List<List<string>>();
  126. List<double> ansPoint = new List<double>();
  127. foreach (double p in info.papers[j].point)
  128. {
  129. ans.Add(new List<string>());
  130. ansPoint.Add(-1);
  131. }
  132. foreach (StudentSimple stu in classroom.students)
  133. {
  134. result.studentIds.Add(stu.id);
  135. result.studentAnswers.Add(ans);
  136. result.studentScores.Add(ansPoint);
  137. }
  138. }
  139. //result.progress = info.progress;
  140. result.school = info.school;
  141. await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(result, new Azure.Cosmos.PartitionKey($"{result.code}"));
  142. }
  143. }
  144. // 发送信息通知
  145. var messageEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = code }.ToJsonString());
  146. messageEnd.ApplicationProperties.Add("name", "Exam");
  147. if (records.Count > 0)
  148. {
  149. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  150. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", records[0].sequenceNumber);
  151. records[0].sequenceNumber = end;
  152. await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
  153. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  154. }
  155. else
  156. {
  157. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  158. ChangeRecord changeRecord = new ChangeRecord
  159. {
  160. RowKey = input.Id,
  161. PartitionKey = "going",
  162. sequenceNumber = end,
  163. msgId = messageEnd.MessageId
  164. };
  165. await _azureStorage.Save<ChangeRecord>(changeRecord);
  166. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  167. }
  168. }
  169. else
  170. {
  171. for (int j = 0; j < info.subjects.Count; j++)
  172. {
  173. if (info.subjects[j].classCount == info.targetClassIds.Count)
  174. {
  175. info.progress = "finish";
  176. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new Azure.Cosmos.PartitionKey($"{code}"));
  177. }
  178. }
  179. }
  180. break;
  181. case "finish":
  182. for (int j = 0; j < info.subjects.Count; j++)
  183. {
  184. ExamResult result = new ExamResult();
  185. //人数总和
  186. int Count = 0;
  187. int m = 0;
  188. List<ClassRange> classRanges = new List<ClassRange>();
  189. foreach (ExamClassResult classResult in examClassResults)
  190. {
  191. if (classResult.subjectId.Equals(info.subjects[j].id))
  192. {
  193. foreach (List<double> scores in classResult.studentScores)
  194. {
  195. result.studentScores.Add(scores);
  196. }
  197. //处理班级信息
  198. ClassRange range = new ClassRange();
  199. range.id = classResult.info.id;
  200. range.name = classResult.info.name;
  201. List<int> ran = new List<int>();
  202. int stuCount = classResult.studentIds.Count;
  203. Count += stuCount;
  204. if (m == 0)
  205. {
  206. ran.Add(0);
  207. ran.Add(stuCount - 1);
  208. }
  209. else
  210. {
  211. ran.Add(Count - stuCount);
  212. ran.Add(Count - 1);
  213. }
  214. m++;
  215. range.range = ran;
  216. classRanges.Add(range);
  217. //处理学生ID
  218. foreach (string id in classResult.studentIds)
  219. {
  220. result.studentIds.Add(id);
  221. }
  222. }
  223. }
  224. result.classes = classRanges;
  225. result.pk = typeof(ExamResult).Name;
  226. result.code = "ExamResult-" + info.id;
  227. result.school = info.school;
  228. result.id = info.subjects[j].id;
  229. result.examId = info.id;
  230. result.subjectId = info.subjects[j].id;
  231. result.year = info.year;
  232. result.paper = info.papers[j];
  233. //result.point = info.papers[j].point;
  234. result.scope = info.scope;
  235. result.name = info.name;
  236. result.time = info.startTime;
  237. result.ttl = -1;
  238. await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
  239. }
  240. break;
  241. }
  242. break;
  243. case "Vote":
  244. Vote vote = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Vote>(input.Id, new Azure.Cosmos.PartitionKey($"{code}"));
  245. List<ChangeRecord> voteRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", vote.progress } });
  246. //ChangeRecord voteRecord = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{vote.progress}"));
  247. switch (vote.progress)
  248. {
  249. case "pending":
  250. var messageVote = new ServiceBusMessage(new { id = input.Id, progress = "going", code = code }.ToJsonString());
  251. messageVote.ApplicationProperties.Add("name", "Vote");
  252. if (voteRecords.Count > 0)
  253. {
  254. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  255. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", voteRecords[0].sequenceNumber);
  256. voteRecords[0].sequenceNumber = start;
  257. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  258. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(voteRecord, voteRecord.id, new Azure.Cosmos.PartitionKey($"{voteRecord.code}"));
  259. }
  260. else
  261. {
  262. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  263. ChangeRecord changeRecord = new ChangeRecord
  264. {
  265. RowKey = input.Id,
  266. PartitionKey = "pending",
  267. sequenceNumber = start,
  268. msgId = messageVote.MessageId
  269. };
  270. await _azureStorage.Save<ChangeRecord>(changeRecord);
  271. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  272. }
  273. break;
  274. case "going":
  275. var messageVoteEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = code }.ToJsonString());
  276. messageVoteEnd.ApplicationProperties.Add("name", "Vote");
  277. if (voteRecords.Count > 0)
  278. {
  279. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  280. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", voteRecords[0].sequenceNumber);
  281. voteRecords[0].sequenceNumber = end;
  282. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  283. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(voteRecord, voteRecord.id, new Azure.Cosmos.PartitionKey($"{voteRecord.code}"));
  284. }
  285. else
  286. {
  287. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  288. ChangeRecord changeRecord = new ChangeRecord
  289. {
  290. RowKey = input.Id,
  291. PartitionKey = "going",
  292. sequenceNumber = end,
  293. msgId = messageVoteEnd.MessageId
  294. };
  295. await _azureStorage.Save<ChangeRecord>(changeRecord);
  296. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  297. }
  298. break;
  299. }
  300. break;
  301. case "Survey":
  302. Survey survey = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(input.Id, new Azure.Cosmos.PartitionKey($"{code}"));
  303. //messageSurvey.ScheduledEnqueueTime = DateTimeOffset.FromUnixTimeMilliseconds(stime);
  304. //string msgid = messageSurvey.MessageId;
  305. List<ChangeRecord> changeRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", survey.progress } });
  306. //ChangeRecord surveyRecord = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{survey.progress}"));
  307. switch (survey.progress)
  308. {
  309. case "pending":
  310. var messageSurvey = new ServiceBusMessage(new { id = input.Id, progress = "going", code = code }.ToJsonString());
  311. messageSurvey.ApplicationProperties.Add("name", "Survey");
  312. if (changeRecords.Count > 0)
  313. {
  314. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", changeRecords[0].sequenceNumber);
  315. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  316. changeRecords[0].sequenceNumber = start;
  317. await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  318. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(surveyRecord, surveyRecord.id, new Azure.Cosmos.PartitionKey($"{surveyRecord.code}"));
  319. }
  320. else
  321. {
  322. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  323. ChangeRecord changeRecord = new ChangeRecord
  324. {
  325. RowKey = input.Id,
  326. PartitionKey = "pending",
  327. sequenceNumber = start,
  328. msgId = messageSurvey.MessageId
  329. };
  330. await _azureStorage.Save<ChangeRecord>(changeRecord);
  331. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  332. }
  333. break;
  334. case "going":
  335. var messageSurveyEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = code }.ToJsonString());
  336. messageSurveyEnd.ApplicationProperties.Add("name", "Survey");
  337. if (changeRecords.Count > 0)
  338. {
  339. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  340. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", changeRecords[0].sequenceNumber);
  341. changeRecords[0].sequenceNumber = end;
  342. await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  343. }
  344. else
  345. {
  346. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  347. ChangeRecord changeRecord = new ChangeRecord
  348. {
  349. RowKey = input.Id,
  350. PartitionKey = "going",
  351. sequenceNumber = end,
  352. msgId = messageSurveyEnd.MessageId
  353. };
  354. await _azureStorage.Save<ChangeRecord>(changeRecord);
  355. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  356. }
  357. break;
  358. }
  359. break;
  360. }
  361. }
  362. }
  363. }
  364. }
  365. }
  366. }