ProcessQueue.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. #endregion
  20. #region *** Private fields ***
  21. private readonly CallbackDelegates _delegates;
  22. private readonly ILog _log;
  23. private readonly ProcessQueueConfiguration _configuration;
  24. private readonly IProcessorStorageProvider _storageProvider;
  25. private bool _isTransient;
  26. private Timer _timerWatchDog;
  27. private bool _isFirstCycle;
  28. #endregion
  29. #region *** Constructors ***
  30. public ProcessQueue(string processQueueIdentifierToken, IProcessorStorageProvider storage, ProcessQueueConfiguration configuration, CallbackDelegates? delegates = null)
  31. {
  32. if (string.IsNullOrEmpty(processQueueIdentifierToken)) throw new ArgumentNullException(nameof(processQueueIdentifierToken));
  33. QueueIdentifier = processQueueIdentifierToken;
  34. _delegates = delegates ?? new CallbackDelegates();
  35. _log = new ConsoleLogger().GetLogger(GetType());
  36. _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
  37. _storageProvider = storage ?? throw new ArgumentNullException(nameof(storage));
  38. _configuration.Validate();
  39. }
  40. #endregion
  41. #region *** Public Operations ***
  42. public void Start()
  43. {
  44. if (IsRunning || _isTransient)
  45. {
  46. Log(LogSeverityEnum.Warn, $"ProcessQueue [{QueueIdentifier}] already running! Skip start.");
  47. return;
  48. }
  49. _isTransient = true;
  50. var now = DateTime.Now;
  51. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] starting...");
  52. //TODO: start mechanism here
  53. _isFirstCycle = true;
  54. _timerWatchDog = new
  55. Timer(OnWatchdog, this, (int) _configuration.WatchdogInterval.TotalMilliseconds, (int) _configuration.WatchdogInterval.TotalMilliseconds);
  56. Log(LogSeverityEnum.Info, $"ProcessQueue [{QueueIdentifier}] started @{DateTime.Now.Subtract(now).ToReadableString()}");
  57. _isTransient = false;
  58. IsRunning = true;
  59. }
  60. public void Stop()
  61. {
  62. if (!IsRunning || _isTransient)
  63. {
  64. Log(LogSeverityEnum.Warn, $"ProcessQueue [{QueueIdentifier}] already stopped! Skip stop.");
  65. return;
  66. }
  67. _isTransient = true;
  68. var now = DateTime.Now;
  69. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] stopping...");
  70. //TODO: start mechanism here
  71. Log(LogSeverityEnum.Info, $"ProcessQueue [{QueueIdentifier}] stopped @{DateTime.Now.Subtract(now).ToReadableString()}");
  72. _isTransient = false;
  73. IsRunning = false;
  74. }
  75. public ITaskIdentifier CreateTask(string reference, string providerClass, TypedArgument[] initialArguments, byte priority, int initialAttempts, TimeSpan attemptTimeout, DateTime validFrom, DateTime? validTo)
  76. {
  77. try
  78. {
  79. var task = new TaskItem(this,reference, providerClass,initialArguments,priority,initialAttempts,attemptTimeout,validFrom,validTo, null);
  80. var newId = _storageProvider.Create(task);
  81. task.Id = newId.Id;
  82. return task;
  83. }
  84. catch (Exception e)
  85. {
  86. var message = $"Error creating task [Ref:{reference}, Provider:{providerClass}] for queue [{QueueIdentifier}]";
  87. Log(LogSeverityEnum.Error, message, e);
  88. throw new Exception(message, e);
  89. }
  90. }
  91. public ITaskItem GetTask(ITaskIdentifier id)
  92. {
  93. if (id == null) throw new ArgumentNullException(nameof(id));
  94. var result = _storageProvider.Get(id).FirstOrDefault();
  95. return result == null ? throw new Exception($"Task [{id.Id}] not found!") : (ITaskItem)result;
  96. }
  97. public ITaskItem[] GetTask(ITaskIdentifier[] ids)
  98. {
  99. var result = _storageProvider.Get(ids);
  100. var diff = result.Select(x => x.Id).CompareDiff(ids.Select(x => x.Id));
  101. if (diff.Any())
  102. throw new Exception($"Tasks [{string.Join(",", diff)}] not found!");
  103. return (ITaskItem[])result;
  104. }
  105. public ITaskIdentifier[] QueryTasks(ProcessStatusEnum[] states,int maxItems, bool affinityQueue = true, bool onlyTimeValid = true, bool includeDeleted = false)
  106. {
  107. if (states == null || !states.Any()) throw new ArgumentNullException(nameof(states));
  108. var now = DateTime.Now;
  109. if (!states.Contains(ProcessStatusEnum.Deleted) && includeDeleted)
  110. states = states.Concat(new[] { ProcessStatusEnum.Deleted }).ToArray();
  111. var items = _storageProvider.Query(states);
  112. if (onlyTimeValid)
  113. items = items.Where(x=> x.ProcessingValidFrom <= now && x.ProcessingValidTo.GetValueOrDefault(DateTime.MaxValue) >= now);
  114. items = affinityQueue ? items.Where(x => x.AffinityToken != null && x.AffinityToken.QueueIdentifier == QueueIdentifier)
  115. : items.Where(x => x.AffinityToken == null);
  116. var result = items.OrderBy(x => x.ProcessingValidFrom)
  117. .ThenBy(x => x.Priority)
  118. .Take(maxItems)
  119. .Select(x=>(ITaskIdentifier)x)
  120. .ToArray();
  121. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] Query tasks {result.Length} of {maxItems}@{DateTime.Now.Subtract(now).ToReadableString()}");
  122. return result;
  123. }
  124. #endregion
  125. #region *** Private Operations ***
  126. private void OnWatchdog(object? state)
  127. {
  128. try
  129. {
  130. if (_isFirstCycle)
  131. {
  132. // first cycle scenario
  133. // reset previous left tasks
  134. var forceLeftTasks = QueryTasks(new[] { ProcessStatusEnum.Started}, _configuration.WorkersCount, true,true, false);
  135. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] Watchdog first cycle. Force reset on {forceLeftTasks.Count()} tasks.");
  136. foreach (var task in forceLeftTasks)
  137. {
  138. ((ITaskItem)task).Stop("(System) Force stop of interrupted task.", true, false);
  139. ((ITaskItem)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. // calculate free slots and assigned slots
  145. // start assigned slots
  146. }
  147. catch (Exception e)
  148. {
  149. Log(LogSeverityEnum.Error, e.Message, e);
  150. }
  151. }
  152. protected void Log(LogSeverityEnum type, string message, Exception? e = null)
  153. {
  154. if (type == LogSeverityEnum.Error || type == LogSeverityEnum.Fatal)
  155. {
  156. _delegates.OnProcessorError?.Invoke(message, e);
  157. }
  158. _log.Log(type, message,e);
  159. }
  160. protected override void OnDisposing()
  161. {
  162. if (IsRunning)
  163. Stop();
  164. _delegates?.Reset();
  165. Log(LogSeverityEnum.Debug, $"ProcessQueue [{QueueIdentifier}] disposed.");
  166. }
  167. #endregion
  168. }
  169. }