MonitorCosmosDB.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. List<ExamSubject> examSubjects = new List<ExamSubject>();
  62. 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}") }))
  63. {
  64. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  65. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  66. {
  67. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  68. {
  69. examClassResults.Add(obj.ToObject<ExamClassResult>());
  70. }
  71. }
  72. }
  73. List<ChangeRecord> records = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", info.progress } });
  74. //ChangeRecord record = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{info.progress}"));
  75. switch (info.progress)
  76. {
  77. case "pending":
  78. var message = new ServiceBusMessage(new { id = input.Id, progress = "going", code = code }.ToJsonString());
  79. message.ApplicationProperties.Add("name", "Exam");
  80. if (records.Count > 0)
  81. {
  82. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", records[0].sequenceNumber);
  83. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", message, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  84. records[0].sequenceNumber = start;
  85. await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
  86. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  87. }
  88. else
  89. {
  90. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", message, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  91. ChangeRecord changeRecord = new ChangeRecord
  92. {
  93. RowKey = input.Id,
  94. PartitionKey = "pending",
  95. sequenceNumber = start,
  96. msgId = message.MessageId
  97. };
  98. await _azureStorage.Save<ChangeRecord>(changeRecord);
  99. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  100. }
  101. break;
  102. case "going":
  103. if (examClassResults.Count == 0)
  104. {
  105. foreach (string cla in info.targetClassIds) {
  106. int m = 0;
  107. foreach (ExamSubject subject in info.subjects) {
  108. ExamClassResult result = new ExamClassResult
  109. {
  110. code = "ExamClassResult-" + info.school,
  111. examId = info.id,
  112. id = Guid.NewGuid().ToString(),
  113. subjectId = subject.id,
  114. year = info.year,
  115. scope = info.scope
  116. };
  117. result.info.id = cla;
  118. var sresponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"Class-{info.school}"));
  119. if (sresponse.Status == 200)
  120. {
  121. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  122. Class classroom = json.ToObject<Class>();
  123. result.info.name = classroom.name;
  124. List<List<string>> ans = new List<List<string>>();
  125. List<double> ansPoint = new List<double>();
  126. foreach (double p in info.papers[m].point)
  127. {
  128. ans.Add(new List<string>());
  129. ansPoint.Add(-1);
  130. }
  131. foreach (StudentSimple stu in classroom.students)
  132. {
  133. result.studentIds.Add(stu.id);
  134. result.studentAnswers.Add(ans);
  135. result.studentScores.Add(ansPoint);
  136. result.sum.Add(0);
  137. }
  138. }
  139. //result.progress = info.progress;
  140. result.school = info.school;
  141. m++;
  142. await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(result, new Azure.Cosmos.PartitionKey($"{result.code}"));
  143. }
  144. }
  145. // 发送信息通知
  146. var messageEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = code }.ToJsonString());
  147. messageEnd.ApplicationProperties.Add("name", "Exam");
  148. if (records.Count > 0)
  149. {
  150. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  151. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", records[0].sequenceNumber);
  152. records[0].sequenceNumber = end;
  153. await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
  154. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  155. }
  156. else
  157. {
  158. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  159. ChangeRecord changeRecord = new ChangeRecord
  160. {
  161. RowKey = input.Id,
  162. PartitionKey = "going",
  163. sequenceNumber = end,
  164. msgId = messageEnd.MessageId
  165. };
  166. await _azureStorage.Save<ChangeRecord>(changeRecord);
  167. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  168. }
  169. }
  170. else
  171. {
  172. //处理单科结算时科目与试卷信息匹配的问题
  173. int gno = 0;
  174. foreach (ExamSubject subject in info.subjects) {
  175. if (subject.classCount == info.targetClassIds.Count) {
  176. await createClassResultAsync(info, examClassResults, subject, gno);
  177. }
  178. gno++;
  179. }
  180. }
  181. break;
  182. case "finish":
  183. int fno = 0;
  184. foreach (ExamSubject subject in info.subjects) {
  185. await createClassResultAsync(info, examClassResults, subject, fno);
  186. fno++;
  187. }
  188. break;
  189. }
  190. break;
  191. case "Vote":
  192. Vote vote = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Vote>(input.Id, new Azure.Cosmos.PartitionKey($"{code}"));
  193. List<ChangeRecord> voteRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", vote.progress } });
  194. //ChangeRecord voteRecord = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{vote.progress}"));
  195. switch (vote.progress)
  196. {
  197. case "pending":
  198. var messageVote = new ServiceBusMessage(new { id = input.Id, progress = "going", code = code }.ToJsonString());
  199. messageVote.ApplicationProperties.Add("name", "Vote");
  200. if (voteRecords.Count > 0)
  201. {
  202. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  203. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", voteRecords[0].sequenceNumber);
  204. voteRecords[0].sequenceNumber = start;
  205. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  206. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(voteRecord, voteRecord.id, new Azure.Cosmos.PartitionKey($"{voteRecord.code}"));
  207. }
  208. else
  209. {
  210. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  211. ChangeRecord changeRecord = new ChangeRecord
  212. {
  213. RowKey = input.Id,
  214. PartitionKey = "pending",
  215. sequenceNumber = start,
  216. msgId = messageVote.MessageId
  217. };
  218. await _azureStorage.Save<ChangeRecord>(changeRecord);
  219. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  220. }
  221. break;
  222. case "going":
  223. var messageVoteEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = code }.ToJsonString());
  224. messageVoteEnd.ApplicationProperties.Add("name", "Vote");
  225. if (voteRecords.Count > 0)
  226. {
  227. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  228. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", voteRecords[0].sequenceNumber);
  229. voteRecords[0].sequenceNumber = end;
  230. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  231. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(voteRecord, voteRecord.id, new Azure.Cosmos.PartitionKey($"{voteRecord.code}"));
  232. }
  233. else
  234. {
  235. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  236. ChangeRecord changeRecord = new ChangeRecord
  237. {
  238. RowKey = input.Id,
  239. PartitionKey = "going",
  240. sequenceNumber = end,
  241. msgId = messageVoteEnd.MessageId
  242. };
  243. await _azureStorage.Save<ChangeRecord>(changeRecord);
  244. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  245. }
  246. break;
  247. }
  248. break;
  249. case "Survey":
  250. Survey survey = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(input.Id, new Azure.Cosmos.PartitionKey($"{code}"));
  251. //messageSurvey.ScheduledEnqueueTime = DateTimeOffset.FromUnixTimeMilliseconds(stime);
  252. //string msgid = messageSurvey.MessageId;
  253. List<ChangeRecord> changeRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", survey.progress } });
  254. //ChangeRecord surveyRecord = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{survey.progress}"));
  255. switch (survey.progress)
  256. {
  257. case "pending":
  258. var messageSurvey = new ServiceBusMessage(new { id = input.Id, progress = "going", code = code }.ToJsonString());
  259. messageSurvey.ApplicationProperties.Add("name", "Survey");
  260. if (changeRecords.Count > 0)
  261. {
  262. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", changeRecords[0].sequenceNumber);
  263. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  264. changeRecords[0].sequenceNumber = start;
  265. await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  266. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(surveyRecord, surveyRecord.id, new Azure.Cosmos.PartitionKey($"{surveyRecord.code}"));
  267. }
  268. else
  269. {
  270. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  271. ChangeRecord changeRecord = new ChangeRecord
  272. {
  273. RowKey = input.Id,
  274. PartitionKey = "pending",
  275. sequenceNumber = start,
  276. msgId = messageSurvey.MessageId
  277. };
  278. await _azureStorage.Save<ChangeRecord>(changeRecord);
  279. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  280. }
  281. break;
  282. case "going":
  283. var messageSurveyEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = code }.ToJsonString());
  284. messageSurveyEnd.ApplicationProperties.Add("name", "Survey");
  285. if (changeRecords.Count > 0)
  286. {
  287. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  288. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", changeRecords[0].sequenceNumber);
  289. changeRecords[0].sequenceNumber = end;
  290. await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  291. }
  292. else
  293. {
  294. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  295. ChangeRecord changeRecord = new ChangeRecord
  296. {
  297. RowKey = input.Id,
  298. PartitionKey = "going",
  299. sequenceNumber = end,
  300. msgId = messageSurveyEnd.MessageId
  301. };
  302. await _azureStorage.Save<ChangeRecord>(changeRecord);
  303. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  304. }
  305. break;
  306. }
  307. break;
  308. }
  309. }
  310. }
  311. }
  312. }
  313. public async Task createClassResultAsync(ExamInfo info,List<ExamClassResult> examClassResults,ExamSubject subject,int no) {
  314. //保证试卷信息与科目信息同步
  315. ExamResult result = new ExamResult();
  316. //人数总和
  317. int Count = 0;
  318. int m = 0;
  319. List<ClassRange> classRanges = new List<ClassRange>();
  320. foreach (ExamClassResult classResult in examClassResults)
  321. {
  322. if (classResult.subjectId.Equals(subject.id))
  323. {
  324. foreach (List<double> scores in classResult.studentScores)
  325. {
  326. result.studentScores.Add(scores);
  327. }
  328. //处理班级信息
  329. ClassRange range = new ClassRange();
  330. range.id = classResult.info.id;
  331. range.name = classResult.info.name;
  332. List<int> ran = new List<int>();
  333. int stuCount = classResult.studentIds.Count;
  334. Count += stuCount;
  335. if (m == 0)
  336. {
  337. ran.Add(0);
  338. ran.Add(stuCount - 1);
  339. }
  340. else
  341. {
  342. ran.Add(Count - stuCount);
  343. ran.Add(Count - 1);
  344. }
  345. m++;
  346. range.range = ran;
  347. classRanges.Add(range);
  348. //处理学生ID
  349. foreach (string id in classResult.studentIds)
  350. {
  351. result.studentIds.Add(id);
  352. }
  353. }
  354. }
  355. result.classes = classRanges;
  356. result.code = "ExamResult-" + info.id;
  357. result.school = info.school;
  358. result.id = subject.id;
  359. result.examId = info.id;
  360. result.subjectId = subject.id;
  361. result.year = info.year;
  362. result.paper = info.papers[no];
  363. //result.point = info.papers[j].point;
  364. result.scope = info.scope;
  365. result.name = info.name;
  366. result.time = info.startTime;
  367. await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
  368. }
  369. }
  370. }