ProcessQueue.cs 9.1 KB

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