MonitorCosmosDB.cs 28 KB

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