MonitorCosmosDB.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 TEAMModelFunction.model;
  12. using TEAMModelOS.SDK.DI;
  13. using TEAMModelOS.SDK.Extension;
  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. public MonitorCosmosDB(IHttpClientFactory clientFactory, AzureCosmosFactory azureCosmos,AzureServiceBusFactory azureServiceBus, AzureStorageFactory azureStorage)
  23. {
  24. _clientFactory = clientFactory;
  25. _azureCosmos = azureCosmos;
  26. _serviceBus = azureServiceBus;
  27. _azureStorage = azureStorage;
  28. }
  29. [FunctionName("ActiveChange")]
  30. public async Task School([CosmosDBTrigger(
  31. databaseName: "TEAMModelOS",
  32. collectionName: "Common",
  33. ConnectionStringSetting = "AzureServiceCosmosConnectionString",
  34. LeaseCollectionName = "leases")]IReadOnlyList<Document> input, ILogger log)
  35. {
  36. if (input != null && input.Count > 0)
  37. {
  38. log.LogInformation("Documents modified " + input.Count);
  39. log.LogInformation("First document Id " + input[0].Id);
  40. }
  41. string pk = input[0].GetPropertyValue<string>("pk");
  42. if (!string.IsNullOrEmpty(pk))
  43. {
  44. var client = _azureCosmos.GetCosmosClient();
  45. long stime = input[0].GetPropertyValue<long>("startTime");
  46. long etime = input[0].GetPropertyValue<long>("endTime");
  47. string school = input[0].GetPropertyValue<string>("school");
  48. string code = input[0].GetPropertyValue<string>("code");
  49. switch (pk) {
  50. case "Exam":
  51. ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(input[0].Id,new Azure.Cosmos.PartitionKey($"{code}"));
  52. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  53. 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}") }))
  54. {
  55. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  56. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  57. {
  58. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  59. {
  60. examClassResults.Add(obj.ToObject<ExamClassResult>());
  61. }
  62. }
  63. }
  64. var message = new ServiceBusMessage(new { id = input[0].Id, name = "Exam", code = code }.ToJsonString());
  65. message.Properties.Add("name", "Exam");
  66. List<ChangeRecord> records = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input[0].Id }, { "PartitionKey", info.progress } });
  67. //ChangeRecord record = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input[0].Id, new Azure.Cosmos.PartitionKey($"{info.progress}"));
  68. switch (info.progress) {
  69. case "pending":
  70. if (records.Count> 0)
  71. {
  72. await _serviceBus.GetServiceBusClient().cancelMessage("active - task", records[0].sequenceNumber);
  73. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", message, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  74. records[0].sequenceNumber = start;
  75. await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
  76. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  77. }
  78. else {
  79. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", message, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  80. ChangeRecord changeRecord = new ChangeRecord
  81. {
  82. RowKey = input[0].Id,
  83. PartitionKey = "pending",
  84. sequenceNumber = start
  85. };
  86. await _azureStorage.Save<ChangeRecord>(changeRecord);
  87. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  88. }
  89. break;
  90. case "going":
  91. if (examClassResults.Count < 0) {
  92. for (int j = 0; j < info.subjects.Count; j++)
  93. {
  94. for (int k = 0; k < info.targetClassIds.Count; k++)
  95. {
  96. ExamClassResult result = new ExamClassResult();
  97. result.code = "ExamClassResult-" + info.school;
  98. result.examId = info.id;
  99. result.id = Guid.NewGuid().ToString();
  100. result.subjectId = info.subjects[j].id;
  101. result.year = info.year;
  102. result.ttl = -1;
  103. result.scope = info.scope;
  104. result.pk = typeof(ExamClassResult).Name;
  105. result.info.id = info.targetClassIds[k];
  106. var sresponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(info.targetClassIds[k], new Azure.Cosmos.PartitionKey($"Class-{info.school}"));
  107. if (sresponse.Status == 200)
  108. {
  109. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  110. Classroom classroom = json.ToObject<Classroom>();
  111. result.info.name = classroom.name;
  112. List<List<string>> ans = new List<List<string>>();
  113. List<double> ansPoint = new List<double>();
  114. foreach (double p in info.papers[j].point)
  115. {
  116. ans.Add(new List<string>());
  117. ansPoint.Add(-1);
  118. }
  119. foreach (StudentSimple stu in classroom.students)
  120. {
  121. result.studentIds.Add(stu.id);
  122. result.studentAnswers.Add(ans);
  123. result.studentScores.Add(ansPoint);
  124. }
  125. }
  126. result.progress = info.progress;
  127. result.school = info.school;
  128. await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(result, new Azure.Cosmos.PartitionKey($"{result.code}"));
  129. }
  130. }
  131. if (records.Count > 0)
  132. {
  133. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", message, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  134. await _serviceBus.GetServiceBusClient().cancelMessage("active - task", records[0].sequenceNumber);
  135. records[0].sequenceNumber = end;
  136. await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
  137. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  138. }
  139. else
  140. {
  141. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", message, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  142. ChangeRecord changeRecord = new ChangeRecord
  143. {
  144. RowKey = input[0].Id,
  145. PartitionKey = "going",
  146. sequenceNumber = end
  147. };
  148. await _azureStorage.Save<ChangeRecord>(changeRecord);
  149. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  150. }
  151. }
  152. break;
  153. case "finish":
  154. for (int j = 0; j < info.subjects.Count; j++)
  155. {
  156. ExamResult result = new ExamResult();
  157. result.ttl = -1;
  158. result.pk = typeof(ExamResult).Name;
  159. result.code = "ExamResult-" + info.school;
  160. result.school = info.school;
  161. result.id = Guid.NewGuid().ToString();
  162. result.examId = info.id;
  163. result.subjectId = info.subjects[j].id;
  164. result.year = info.year;
  165. result.paper = info.papers[j];
  166. result.point = info.papers[j].point;
  167. result.scope = info.scope;
  168. result.name = info.name;
  169. //result.time
  170. //人数总和
  171. int Count = 0;
  172. int m = 0;
  173. List<ClassRange> classRanges = new List<ClassRange>();
  174. foreach (ExamClassResult classResult in examClassResults)
  175. {
  176. if (classResult.subjectId.Equals(info.subjects[j].id)) {
  177. //处理班级信息
  178. ClassRange range = new ClassRange();
  179. range.id = classResult.info.id;
  180. range.name = classResult.info.name;
  181. List<int> ran = new List<int>();
  182. int stuCount = classResult.studentIds.Count;
  183. Count += stuCount;
  184. if (m == 0)
  185. {
  186. ran.Add(0);
  187. ran.Add(stuCount - 1);
  188. }
  189. else
  190. {
  191. ran.Add(Count - stuCount);
  192. ran.Add(Count - 1);
  193. }
  194. m++;
  195. range.range = ran;
  196. classRanges.Add(range);
  197. //处理学生ID
  198. foreach (string id in classResult.studentIds)
  199. {
  200. result.studentIds.Add(id);
  201. }
  202. foreach (List<double> scores in classResult.studentScores)
  203. {
  204. result.studentScores.Add(scores);
  205. }
  206. }
  207. }
  208. result.classes = classRanges;
  209. await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common").CreateItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{result.school}"));
  210. }
  211. break;
  212. }
  213. break;
  214. case "Vote":
  215. Vote vote = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Vote>(input[0].Id, new Azure.Cosmos.PartitionKey($"{code}"));
  216. var messageVote = new ServiceBusMessage(new { id = input[0].Id, name = "Vote", code = code }.ToJsonString());
  217. messageVote.Properties.Add("name", "Vote");
  218. List<ChangeRecord> voteRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input[0].Id }, { "PartitionKey", vote.progress } });
  219. //ChangeRecord voteRecord = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input[0].Id, new Azure.Cosmos.PartitionKey($"{vote.progress}"));
  220. switch (vote.progress) {
  221. case "pending":
  222. if (voteRecords.Count > 0)
  223. {
  224. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  225. await _serviceBus.GetServiceBusClient().cancelMessage("active - task", voteRecords[0].sequenceNumber);
  226. voteRecords[0].sequenceNumber = start;
  227. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  228. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(voteRecord, voteRecord.id, new Azure.Cosmos.PartitionKey($"{voteRecord.code}"));
  229. }
  230. else
  231. {
  232. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  233. ChangeRecord changeRecord = new ChangeRecord
  234. {
  235. RowKey = input[0].Id,
  236. PartitionKey = "pending",
  237. sequenceNumber = start
  238. };
  239. await _azureStorage.Save<ChangeRecord>(changeRecord);
  240. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  241. }
  242. break;
  243. case "going":
  244. if (voteRecords.Count > 0)
  245. {
  246. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  247. await _serviceBus.GetServiceBusClient().cancelMessage("active - task", voteRecords[0].sequenceNumber);
  248. voteRecords[0].sequenceNumber = end;
  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 end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  255. ChangeRecord changeRecord = new ChangeRecord
  256. {
  257. RowKey = input[0].Id,
  258. PartitionKey = "going",
  259. sequenceNumber = end
  260. };
  261. await _azureStorage.Save<ChangeRecord>(changeRecord);
  262. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  263. }
  264. break;
  265. }
  266. break;
  267. case "Survey":
  268. Survey survey = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(input[0].Id, new Azure.Cosmos.PartitionKey($"{code}"));
  269. var messageSurvey = new ServiceBusMessage(new { id = input[0].Id, name = "Survey", code = code }.ToJsonString());
  270. messageSurvey.Properties.Add("name", "Survey");
  271. List<ChangeRecord> changeRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input[0].Id },{"PartitionKey", survey.progress} });
  272. //ChangeRecord surveyRecord = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input[0].Id, new Azure.Cosmos.PartitionKey($"{survey.progress}"));
  273. switch (survey.progress)
  274. {
  275. case "pending":
  276. if (changeRecords.Count > 0)
  277. {
  278. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  279. await _serviceBus.GetServiceBusClient().cancelMessage("active - task", changeRecords[0].sequenceNumber);
  280. changeRecords[0].sequenceNumber = start;
  281. await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  282. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(surveyRecord, surveyRecord.id, new Azure.Cosmos.PartitionKey($"{surveyRecord.code}"));
  283. }
  284. else
  285. {
  286. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  287. ChangeRecord changeRecord = new ChangeRecord
  288. {
  289. RowKey = input[0].Id,
  290. PartitionKey = "pending",
  291. sequenceNumber = start
  292. };
  293. await _azureStorage.Save<ChangeRecord>(changeRecord);
  294. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  295. }
  296. break;
  297. case "going":
  298. if (changeRecords.Count > 0)
  299. {
  300. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  301. await _serviceBus.GetServiceBusClient().cancelMessage("active - task", changeRecords[0].sequenceNumber);
  302. changeRecords[0].sequenceNumber = end;
  303. await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  304. }
  305. else
  306. {
  307. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  308. ChangeRecord changeRecord = new ChangeRecord
  309. {
  310. RowKey = input[0].Id,
  311. PartitionKey = "going",
  312. sequenceNumber = end
  313. };
  314. await _azureStorage.Save<ChangeRecord>(changeRecord);
  315. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  316. }
  317. break;
  318. }
  319. break;
  320. }
  321. }
  322. }
  323. }
  324. }