ProcessQueue.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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, ITypedArgument[] 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. if (ids == null) throw new ArgumentNullException(nameof(ids));
  99. if (!ids.Any()) return Array.Empty<ITaskItem>();
  100. var result = _storageProvider.Get(ids);
  101. var diff = result.Select(x => x.Id).CompareDiff(ids.Select(x => x.Id));
  102. if (diff.Any())
  103. throw new Exception($"Tasks [{string.Join(",", diff)}] not found!");
  104. return result.Select(x=>x as ITaskItem).ToArray()!;
  105. }
  106. public ITaskIdentifier[] QueryTasks(IPaging paging,ProcessStatusEnum[] states,int maxItems, bool affinityQueue = true, bool onlyTimeValid = true, bool includeDeleted = false)
  107. {
  108. if (states == null || !states.Any()) throw new ArgumentNullException(nameof(states));
  109. var now = DateTime.Now;
  110. if (!states.Contains(ProcessStatusEnum.Deleted) && includeDeleted)
  111. states = states.Concat(new[] { ProcessStatusEnum.Deleted }).ToArray();
  112. var items = _storageProvider.Query(paging, states);
  113. if (onlyTimeValid)
  114. items = items.Where(x=> x.ProcessingValidFrom <= now && x.ProcessingValidTo.GetValueOrDefault(DateTime.MaxValue) >= now);
  115. items = affinityQueue ? items.Where(x => x.AffinityToken != null && x.AffinityToken.QueueIdentifier == QueueIdentifier)
  116. : items.Where(x => x.AffinityToken == null);
  117. var result = items.OrderBy(x => x.ProcessingValidFrom)
  118. .ThenBy(x => x.Priority)
  119. .Take(maxItems)
  120. .Select(x=>(ITaskIdentifier)x)
  121. .ToArray();
  122. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] Query tasks {result.Length} of {maxItems}@{DateTime.Now.Subtract(now).ToReadableString()}");
  123. return result;
  124. }
  125. #endregion
  126. #region *** Private Operations ***
  127. private void OnWatchdog(object? state)
  128. {
  129. try
  130. {
  131. if (_isFirstCycle)
  132. {
  133. // first cycle scenario
  134. // reset previous left tasks
  135. var forceLeftTaskIds = QueryTasks(Paging.NoPaging, new[] { ProcessStatusEnum.Started}, _configuration.WorkersCount, true,true, false);
  136. var forceLeftTasks = GetTask(forceLeftTaskIds);
  137. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] Watchdog first cycle. Force reset on {forceLeftTaskIds.Count()} tasks.");
  138. foreach (var task in forceLeftTasks)
  139. {
  140. task.Stop("(System) Force stop of interrupted task.", true, false);
  141. task.Reset("(System) Reset after force stop.", TimeSpan.FromSeconds(10));
  142. }
  143. _isFirstCycle = false;
  144. }
  145. // gets processing tasks to know thread assigned slots
  146. var assigningTaskIds = QueryTasks(Paging.NoPaging, new[] { ProcessStatusEnum.Pending }, _taskSlots.FreeSlotsCount, false, true, false);
  147. var assigningTasks = GetTask(assigningTaskIds);
  148. var startedCnt = 0;
  149. foreach (var assign in assigningTasks)
  150. {
  151. var ordinal = _taskSlots.AssignSlot(assign);
  152. if (ordinal >= 0)
  153. {
  154. ((TaskItem)assign).Start(new AffinityToken(QueueIdentifier, ordinal));
  155. startedCnt++;
  156. }
  157. }
  158. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] Watchdog cycle. Assigned and started {startedCnt} of {assigningTaskIds.Length} tasks.");
  159. }
  160. catch (Exception e)
  161. {
  162. Log(LogSeverityEnum.Error, e.Message, e);
  163. }
  164. }
  165. protected void Log(LogSeverityEnum type, string message, Exception? e = null)
  166. {
  167. if (type == LogSeverityEnum.Error || type == LogSeverityEnum.Fatal)
  168. {
  169. _delegates.OnProcessorError?.Invoke(message, e);
  170. }
  171. _log.Log(type, message,e);
  172. }
  173. protected override void OnDisposing()
  174. {
  175. if (IsRunning)
  176. Stop();
  177. _delegates?.Reset();
  178. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] disposed.");
  179. }
  180. #endregion
  181. }
  182. }