ProcessQueue.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Quadarax.Foundation.Core.Business.Processor.Enums;
  7. using Quadarax.Foundation.Core.Business.Processor.Providers;
  8. using Quadarax.Foundation.Core.Business.Processor.Task;
  9. using Quadarax.Foundation.Core.Logging;
  10. using Quadarax.Foundation.Core.Object;
  11. using Quadarax.Foundation.Core.Value.Extensions;
  12. namespace Quadarax.Foundation.Core.Business.Processor.Queue
  13. {
  14. public class ProcessQueue : DisposableObject
  15. {
  16. #region *** Properties ***
  17. public bool IsRunning { get; private set; }
  18. public string QueueIdentifier { get; private set; }
  19. internal IProcessorStorageProvider Provider => _storageProvider;
  20. #endregion
  21. #region *** Private fields ***
  22. private readonly CallbackDelegates _delegates;
  23. private readonly ILog _log;
  24. private readonly ProcessQueueConfiguration _configuration;
  25. private readonly IProcessorStorageProvider _storageProvider;
  26. private bool _isTransient;
  27. private Timer _timerWatchDog;
  28. private bool _isFirstCycle;
  29. private TaskSlots _taskSlots;
  30. #endregion
  31. #region *** Constructors ***
  32. public ProcessQueue(string processQueueIdentifierToken, IProcessorStorageProvider storage, ProcessQueueConfiguration configuration, CallbackDelegates? delegates = null)
  33. {
  34. if (string.IsNullOrEmpty(processQueueIdentifierToken)) throw new ArgumentNullException(nameof(processQueueIdentifierToken));
  35. QueueIdentifier = processQueueIdentifierToken;
  36. _taskSlots = new TaskSlots(configuration.WorkersCount);
  37. _delegates = delegates ?? new CallbackDelegates();
  38. _log = new ConsoleLogger().GetLogger(GetType());
  39. _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
  40. _storageProvider = storage ?? throw new ArgumentNullException(nameof(storage));
  41. _configuration.Validate();
  42. }
  43. #endregion
  44. #region *** Public Operations ***
  45. public void Start()
  46. {
  47. if (IsRunning || _isTransient)
  48. {
  49. Log(LogSeverityEnum.Warn, $"ProcessQueue [{QueueIdentifier}] already running! Skip start.");
  50. return;
  51. }
  52. _isTransient = true;
  53. var now = DateTime.Now;
  54. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] starting...");
  55. //TODO: start mechanism here
  56. _isFirstCycle = true;
  57. _timerWatchDog = new
  58. Timer(OnWatchdog, this, (int) _configuration.WatchdogInterval.TotalMilliseconds, (int) _configuration.WatchdogInterval.TotalMilliseconds);
  59. Log(LogSeverityEnum.Info, $"ProcessQueue [{QueueIdentifier}] started @{DateTime.Now.Subtract(now).ToReadableString()}");
  60. _isTransient = false;
  61. IsRunning = true;
  62. }
  63. public void Stop()
  64. {
  65. if (!IsRunning || _isTransient)
  66. {
  67. Log(LogSeverityEnum.Warn, $"ProcessQueue [{QueueIdentifier}] already stopped! Skip stop.");
  68. return;
  69. }
  70. _isTransient = true;
  71. var now = DateTime.Now;
  72. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] stopping...");
  73. //TODO: start mechanism here
  74. Log(LogSeverityEnum.Info, $"ProcessQueue [{QueueIdentifier}] stopped @{DateTime.Now.Subtract(now).ToReadableString()}");
  75. _isTransient = false;
  76. IsRunning = false;
  77. }
  78. public ITaskIdentifier CreateTask(string reference, string providerClass, TypedArgument[] initialArguments, byte priority, int initialAttempts, TimeSpan attemptTimeout, DateTime validFrom, DateTime? validTo)
  79. {
  80. try
  81. {
  82. var task = new TaskItem(this,reference, providerClass,initialArguments,priority,initialAttempts,attemptTimeout,validFrom,validTo, null);
  83. var newId = _storageProvider.Create(task);
  84. task.Id = newId.Id;
  85. return task;
  86. }
  87. catch (Exception e)
  88. {
  89. var message = $"Error creating task [Ref:{reference}, Provider:{providerClass}] for queue [{QueueIdentifier}]";
  90. Log(LogSeverityEnum.Error, message, e);
  91. throw new Exception(message, e);
  92. }
  93. }
  94. public ITaskItem GetTask(ITaskIdentifier id)
  95. {
  96. if (id == null) throw new ArgumentNullException(nameof(id));
  97. var result = _storageProvider.Get(id).FirstOrDefault();
  98. return result == null ? throw new Exception($"Task [{id.Id}] not found!") : (ITaskItem)result;
  99. }
  100. public ITaskItem[] GetTask(ITaskIdentifier[] ids)
  101. {
  102. var result = _storageProvider.Get(ids);
  103. var diff = result.Select(x => x.Id).CompareDiff(ids.Select(x => x.Id));
  104. if (diff.Any())
  105. throw new Exception($"Tasks [{string.Join(",", diff)}] not found!");
  106. return (ITaskItem[])result;
  107. }
  108. public ITaskIdentifier[] QueryTasks(ProcessStatusEnum[] states,int maxItems, bool affinityQueue = true, bool onlyTimeValid = true, bool includeDeleted = false)
  109. {
  110. if (states == null || !states.Any()) throw new ArgumentNullException(nameof(states));
  111. var now = DateTime.Now;
  112. if (!states.Contains(ProcessStatusEnum.Deleted) && includeDeleted)
  113. states = states.Concat(new[] { ProcessStatusEnum.Deleted }).ToArray();
  114. var items = _storageProvider.Query(states);
  115. if (onlyTimeValid)
  116. items = items.Where(x=> x.ProcessingValidFrom <= now && x.ProcessingValidTo.GetValueOrDefault(DateTime.MaxValue) >= now);
  117. items = affinityQueue ? items.Where(x => x.AffinityToken != null && x.AffinityToken.QueueIdentifier == QueueIdentifier)
  118. : items.Where(x => x.AffinityToken == null);
  119. var result = items.OrderBy(x => x.ProcessingValidFrom)
  120. .ThenBy(x => x.Priority)
  121. .Take(maxItems)
  122. .Select(x=>(ITaskIdentifier)x)
  123. .ToArray();
  124. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] Query tasks {result.Length} of {maxItems}@{DateTime.Now.Subtract(now).ToReadableString()}");
  125. return result;
  126. }
  127. #endregion
  128. #region *** Private Operations ***
  129. private void OnWatchdog(object? state)
  130. {
  131. try
  132. {
  133. if (_isFirstCycle)
  134. {
  135. // first cycle scenario
  136. // reset previous left tasks
  137. var forceLeftTaskIds = QueryTasks(new[] { ProcessStatusEnum.Started}, _configuration.WorkersCount, true,true, false);
  138. var forceLeftTasks = GetTask(forceLeftTaskIds);
  139. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] Watchdog first cycle. Force reset on {forceLeftTaskIds.Count()} tasks.");
  140. foreach (var task in forceLeftTasks)
  141. {
  142. task.Stop("(System) Force stop of interrupted task.", true, false);
  143. task.Reset("(System) Reset after force stop.", TimeSpan.FromSeconds(10));
  144. }
  145. _isFirstCycle = false;
  146. }
  147. // gets processing tasks to know thread assigned slots
  148. var assigningTaskIds = QueryTasks(new[] { ProcessStatusEnum.Pending }, _taskSlots.FreeSlotsCount, false, true, false);
  149. var assigningTasks = GetTask(assigningTaskIds);
  150. var startedCnt = 0;
  151. foreach (var assign in assigningTasks)
  152. {
  153. if (_taskSlots.AssignSlot(assign) >= 0)
  154. {
  155. ((TaskItem)assign).Start();
  156. startedCnt++;
  157. }
  158. }
  159. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] Watchdog cycle. Assigned and started {startedCnt} of {assigningTaskIds.Length} tasks.");
  160. }
  161. catch (Exception e)
  162. {
  163. Log(LogSeverityEnum.Error, e.Message, e);
  164. }
  165. }
  166. protected void Log(LogSeverityEnum type, string message, Exception? e = null)
  167. {
  168. if (type == LogSeverityEnum.Error || type == LogSeverityEnum.Fatal)
  169. {
  170. _delegates.OnProcessorError?.Invoke(message, e);
  171. }
  172. _log.Log(type, message,e);
  173. }
  174. protected override void OnDisposing()
  175. {
  176. if (IsRunning)
  177. Stop();
  178. _delegates?.Reset();
  179. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] disposed.");
  180. }
  181. #endregion
  182. }
  183. }