MonitorCosmosDB.cs 29 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. for (int j = 0; j < info.subjects.Count; j++)
  105. {
  106. for (int k = 0; k < info.targetClassIds.Count; k++)
  107. {
  108. ExamClassResult result = new ExamClassResult
  109. {
  110. code = "ExamClassResult-" + info.school,
  111. examId = info.id,
  112. id = Guid.NewGuid().ToString(),
  113. subjectId = info.subjects[j].id,
  114. year = info.year,
  115. scope = info.scope,
  116. ttl = -1,
  117. pk = typeof(ExamClassResult).Name
  118. };
  119. result.info.id = info.targetClassIds[k];
  120. var sresponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(info.targetClassIds[k], new Azure.Cosmos.PartitionKey($"Class-{info.school}"));
  121. if (sresponse.Status == 200)
  122. {
  123. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  124. Class classroom = json.ToObject<Class>();
  125. result.info.name = classroom.name;
  126. List<List<string>> ans = new List<List<string>>();
  127. List<double> ansPoint = new List<double>();
  128. foreach (double p in info.papers[j].point)
  129. {
  130. ans.Add(new List<string>());
  131. ansPoint.Add(-1);
  132. }
  133. foreach (StudentSimple stu in classroom.students)
  134. {
  135. result.studentIds.Add(stu.id);
  136. result.studentAnswers.Add(ans);
  137. result.studentScores.Add(ansPoint);
  138. }
  139. }
  140. //result.progress = info.progress;
  141. result.school = info.school;
  142. await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(result, new Azure.Cosmos.PartitionKey($"{result.code}"));
  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. for (int j = 0; j < info.subjects.Count; j++)
  171. {
  172. if (info.subjects[j].classCount == info.targetClassIds.Count)
  173. {
  174. info.progress = "finish";
  175. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new Azure.Cosmos.PartitionKey($"{code}"));
  176. }
  177. }
  178. }
  179. break;
  180. case "finish":
  181. for (int j = 0; j < info.subjects.Count; j++)
  182. {
  183. ExamResult result = new ExamResult();
  184. //人数总和
  185. int Count = 0;
  186. int m = 0;
  187. List<ClassRange> classRanges = new List<ClassRange>();
  188. foreach (ExamClassResult classResult in examClassResults)
  189. {
  190. if (classResult.subjectId.Equals(info.subjects[j].id))
  191. {
  192. foreach (List<double> scores in classResult.studentScores)
  193. {
  194. result.studentScores.Add(scores);
  195. }
  196. //处理班级信息
  197. ClassRange range = new ClassRange();
  198. range.id = classResult.info.id;
  199. range.name = classResult.info.name;
  200. List<int> ran = new List<int>();
  201. int stuCount = classResult.studentIds.Count;
  202. Count += stuCount;
  203. if (m == 0)
  204. {
  205. ran.Add(0);
  206. ran.Add(stuCount - 1);
  207. }
  208. else
  209. {
  210. ran.Add(Count - stuCount);
  211. ran.Add(Count - 1);
  212. }
  213. m++;
  214. range.range = ran;
  215. classRanges.Add(range);
  216. //处理学生ID
  217. foreach (string id in classResult.studentIds)
  218. {
  219. result.studentIds.Add(id);
  220. }
  221. }
  222. }
  223. result.classes = classRanges;
  224. result.pk = typeof(ExamResult).Name;
  225. result.code = "ExamResult-" + info.id;
  226. result.school = info.school;
  227. result.id = info.subjects[j].id;
  228. result.examId = info.id;
  229. result.subjectId = info.subjects[j].id;
  230. result.year = info.year;
  231. result.paper = info.papers[j];
  232. //result.point = info.papers[j].point;
  233. result.scope = info.scope;
  234. result.name = info.name;
  235. result.time = info.startTime;
  236. result.ttl = -1;
  237. await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
  238. }
  239. break;
  240. }
  241. break;
  242. case "Vote":
  243. Vote vote = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Vote>(input.Id, new Azure.Cosmos.PartitionKey($"{code}"));
  244. List<ChangeRecord> voteRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", vote.progress } });
  245. //ChangeRecord voteRecord = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{vote.progress}"));
  246. switch (vote.progress)
  247. {
  248. case "pending":
  249. var messageVote = new ServiceBusMessage(new { id = input.Id, progress = "going", code = code }.ToJsonString());
  250. messageVote.ApplicationProperties.Add("name", "Vote");
  251. if (voteRecords.Count > 0)
  252. {
  253. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  254. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", voteRecords[0].sequenceNumber);
  255. voteRecords[0].sequenceNumber = start;
  256. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  257. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(voteRecord, voteRecord.id, new Azure.Cosmos.PartitionKey($"{voteRecord.code}"));
  258. }
  259. else
  260. {
  261. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  262. ChangeRecord changeRecord = new ChangeRecord
  263. {
  264. RowKey = input.Id,
  265. PartitionKey = "pending",
  266. sequenceNumber = start,
  267. msgId = messageVote.MessageId
  268. };
  269. await _azureStorage.Save<ChangeRecord>(changeRecord);
  270. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  271. }
  272. break;
  273. case "going":
  274. var messageVoteEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = code }.ToJsonString());
  275. messageVoteEnd.ApplicationProperties.Add("name", "Vote");
  276. if (voteRecords.Count > 0)
  277. {
  278. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  279. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", voteRecords[0].sequenceNumber);
  280. voteRecords[0].sequenceNumber = end;
  281. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  282. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(voteRecord, voteRecord.id, new Azure.Cosmos.PartitionKey($"{voteRecord.code}"));
  283. }
  284. else
  285. {
  286. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  287. ChangeRecord changeRecord = new ChangeRecord
  288. {
  289. RowKey = input.Id,
  290. PartitionKey = "going",
  291. sequenceNumber = end,
  292. msgId = messageVoteEnd.MessageId
  293. };
  294. await _azureStorage.Save<ChangeRecord>(changeRecord);
  295. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  296. }
  297. break;
  298. }
  299. break;
  300. case "Survey":
  301. Survey survey = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(input.Id, new Azure.Cosmos.PartitionKey($"{code}"));
  302. //messageSurvey.ScheduledEnqueueTime = DateTimeOffset.FromUnixTimeMilliseconds(stime);
  303. //string msgid = messageSurvey.MessageId;
  304. List<ChangeRecord> changeRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", survey.progress } });
  305. //ChangeRecord surveyRecord = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{survey.progress}"));
  306. switch (survey.progress)
  307. {
  308. case "pending":
  309. var messageSurvey = new ServiceBusMessage(new { id = input.Id, progress = "going", code = code }.ToJsonString());
  310. messageSurvey.ApplicationProperties.Add("name", "Survey");
  311. if (changeRecords.Count > 0)
  312. {
  313. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", changeRecords[0].sequenceNumber);
  314. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  315. changeRecords[0].sequenceNumber = start;
  316. await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  317. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(surveyRecord, surveyRecord.id, new Azure.Cosmos.PartitionKey($"{surveyRecord.code}"));
  318. }
  319. else
  320. {
  321. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  322. ChangeRecord changeRecord = new ChangeRecord
  323. {
  324. RowKey = input.Id,
  325. PartitionKey = "pending",
  326. sequenceNumber = start,
  327. msgId = messageSurvey.MessageId
  328. };
  329. await _azureStorage.Save<ChangeRecord>(changeRecord);
  330. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  331. }
  332. break;
  333. case "going":
  334. var messageSurveyEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = code }.ToJsonString());
  335. messageSurveyEnd.ApplicationProperties.Add("name", "Survey");
  336. if (changeRecords.Count > 0)
  337. {
  338. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  339. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", changeRecords[0].sequenceNumber);
  340. changeRecords[0].sequenceNumber = end;
  341. await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  342. }
  343. else
  344. {
  345. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  346. ChangeRecord changeRecord = new ChangeRecord
  347. {
  348. RowKey = input.Id,
  349. PartitionKey = "going",
  350. sequenceNumber = end,
  351. msgId = messageSurveyEnd.MessageId
  352. };
  353. await _azureStorage.Save<ChangeRecord>(changeRecord);
  354. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  355. }
  356. break;
  357. }
  358. break;
  359. }
  360. }
  361. }
  362. }
  363. }
  364. }
  365. }