PsProcessProviderBase.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. using qdr.fnd.core.pqueue.Enums;
  2. using qdr.fnd.core.pqueue.Exceptions;
  3. using qdr.fnd.core.pqueue.fnd.candidates;
  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 qdr.fnd.core.pqueue.Process
  9. {
  10. public delegate void ProcessDoneCallback(string itemId, PsStatusEnum newStatus, string message);
  11. public delegate void ProcessStdOutputCallback(string itemId, string message);
  12. public abstract class PsProcessProviderBase : DisposableObject, IPsProcessProvider
  13. {
  14. #region *** Constants ***
  15. /// <summary>
  16. /// (Output) Argument name for the result code. Type is <see cref="long"/>
  17. /// </summary>
  18. public const string CS_ARG_RESULT_CODE = "result-code";
  19. /// <summary>
  20. /// (Output) Argument name for the result test. Type is <see cref="string"/>
  21. /// </summary>
  22. public const string CS_ARG_RESULT_TEXT = "result-text";
  23. /// <summary>
  24. /// (Input) Argument name for process timeout. Type is <see cref="TimeSpan"/>
  25. /// </summary>
  26. public const string CS_ARG_PROCESS_TIMEOUT = "process-timeout";
  27. #endregion
  28. #region *** Properties ***
  29. protected ILog Log { get; private set; }
  30. protected ProcessDoneCallback ProcessDoneCallback { get; private set; }
  31. protected ProcessStdOutputCallback ProcessStdOutputCallback { get; private set; }
  32. /// <inheritdoc />
  33. public IDictionary<string, TypedArgument> Arguments { get; private set; }
  34. public bool IsRunning { get; private set; }
  35. /// <inheritdoc />
  36. public string ItemId { get; private set; }
  37. /// <inheritdoc />
  38. public DateTime? StartedTimestamp { get; private set; }
  39. /// <inheritdoc />
  40. public DateTime? FinishedTimestamp { get; private set; }
  41. #endregion
  42. #region *** Private fields ***
  43. private CancellationTokenSource? _cancelationToken;
  44. #endregion
  45. #region *** Constructors ***
  46. public PsProcessProviderBase(ProcessDoneCallback processDoneCallback, ProcessStdOutputCallback processStdOutputCallback, string itemId, TypedArgument[] arguments, ILogger logger)
  47. {
  48. if (string.IsNullOrEmpty(itemId)) throw new ArgumentNullException(nameof(itemId));
  49. ProcessDoneCallback = processDoneCallback ?? throw new ArgumentNullException(nameof(processDoneCallback));
  50. ProcessStdOutputCallback = processStdOutputCallback ?? throw new ArgumentNullException(nameof(processStdOutputCallback));
  51. ItemId = itemId;
  52. Log = logger.GetLogger(GetType());
  53. Arguments = arguments.ToDictionary(x => x.Name, x => x);
  54. _cancelationToken = new CancellationTokenSource();
  55. }
  56. #endregion
  57. #region *** Public Operations ***
  58. /// <inheritdoc />
  59. public void Validate()
  60. {
  61. OnValidate();
  62. }
  63. /// <inheritdoc />
  64. public void Start()
  65. {
  66. if (IsRunning)
  67. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderIsRunning, GetType().Name, ItemId);
  68. Validate();
  69. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' starting.");
  70. IsRunning = true;
  71. StartedTimestamp = DateTime.Now;
  72. var timeout = GetArgumentValue<TimeSpan>(CS_ARG_PROCESS_TIMEOUT);
  73. Task.Run(async () =>
  74. {
  75. try
  76. {
  77. await TimeoutUtils.ExecuteWithTimeoutAsync(async () =>
  78. {
  79. await OnProcess().ContinueWith(task =>
  80. {
  81. if (task.IsFaulted)
  82. {
  83. var e = task.Exception!;
  84. OnProcessError(e).ContinueWith(taskInner =>
  85. {
  86. if (taskInner.IsFaulted)
  87. throw taskInner.Exception!;
  88. ProcessDoneFailed(e.Message, e);
  89. });
  90. }
  91. else
  92. {
  93. ProcessDoneOk("Succesfuly done.");
  94. }
  95. });
  96. }, timeout);
  97. }
  98. catch (Exception e)
  99. {
  100. await OnProcessError(e).ContinueWith(task =>
  101. {
  102. if (task.IsFaulted)
  103. throw task.Exception!;
  104. ProcessDoneFailed(e.Message, e);
  105. });
  106. }
  107. });
  108. }
  109. /// <inheritdoc />
  110. public void Stop()
  111. {
  112. if (!IsRunning)
  113. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotRunning, GetType().Name, ItemId);
  114. _cancelationToken?.Cancel();
  115. ProcessDoneFailed("Process was forced stopped.");
  116. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' was forced stopped.");
  117. }
  118. /// <summary>
  119. /// Generates all arguments collection
  120. /// </summary>
  121. /// <returns>Full scoped arguments collection</returns>
  122. public static IEnumerable<TypedArgument> CreateArguments()
  123. {
  124. var list = new List<TypedArgument>
  125. {
  126. new TypedArgument(CS_ARG_RESULT_CODE, typeof(long), true),
  127. new TypedArgument(CS_ARG_RESULT_TEXT, typeof(string), true),
  128. new TypedArgument(CS_ARG_PROCESS_TIMEOUT, typeof(TimeSpan), false)
  129. };
  130. return list;
  131. }
  132. /// <inheritdoc />
  133. public void WaitToDone()
  134. {
  135. while (IsRunning)
  136. {
  137. Task.Delay(100).Wait();
  138. };
  139. Log.Log(LogSeverityEnum.Debug, $"Provider for ItemId='{ItemId}' detect that process finished.");
  140. }
  141. #endregion
  142. #region *** Protected Operations ***
  143. protected TValue? GetArgumentValue<TValue>(string name)
  144. {
  145. if (string.IsNullOrEmpty(name))
  146. throw new ArgumentNullException(nameof(name));
  147. if (Arguments.TryGetValue(name, out var arg))
  148. return arg.GetTypedValue<TValue>();
  149. return default;
  150. }
  151. protected bool ContainsArgument(string name)
  152. {
  153. if (string.IsNullOrEmpty(name))
  154. throw new ArgumentNullException(nameof(name));
  155. return Arguments.ContainsKey(name);
  156. }
  157. protected virtual void OnValidate()
  158. {
  159. if (!ContainsArgument(CS_ARG_RESULT_CODE) || !Arguments[CS_ARG_RESULT_CODE].IsOutput)
  160. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_CODE);
  161. if (!ContainsArgument(CS_ARG_RESULT_TEXT) || !Arguments[CS_ARG_RESULT_TEXT].IsOutput)
  162. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_TEXT);
  163. if (!ContainsArgument(CS_ARG_PROCESS_TIMEOUT) || Arguments[CS_ARG_PROCESS_TIMEOUT].IsOutput)
  164. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_PROCESS_TIMEOUT);
  165. }
  166. #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
  167. protected virtual async Task OnProcessError(Exception exception)
  168. #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
  169. {
  170. if (exception == null)
  171. throw new ArgumentNullException(nameof(exception));
  172. if (ProcessStdOutputCallback != null)
  173. ProcessStdOutputCallback(ItemId, exception.Message);
  174. if (ContainsArgument(CS_ARG_RESULT_TEXT))
  175. Arguments[CS_ARG_RESULT_TEXT].Value = exception.Message;
  176. }
  177. #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
  178. protected virtual async Task OnProcess()
  179. #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
  180. {
  181. //nothing to do
  182. }
  183. /// <inheritdoc />
  184. protected override void OnDisposing()
  185. {
  186. _cancelationToken?.Dispose();
  187. ProcessDoneCallback = null!;
  188. ProcessStdOutputCallback = null!;
  189. _cancelationToken = null;
  190. }
  191. private void ProcessDoneFailed(string message, Exception? e = null)
  192. {
  193. Log.Log(LogSeverityEnum.Error, $"Provider running failed. Duration {(DateTime.Now - StartedTimestamp.GetValueOrDefault()).ToReadableString()}.", e);
  194. if (ProcessDoneCallback != null)
  195. ProcessDoneCallback(ItemId, PsStatusEnum.DoneFailed, message);
  196. IsRunning = false;
  197. FinishedTimestamp = DateTime.Now;
  198. }
  199. private void ProcessDoneOk(string message)
  200. {
  201. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' done. Duration {(DateTime.Now - StartedTimestamp.GetValueOrDefault()).ToReadableString()}.");
  202. if (ProcessDoneCallback != null)
  203. ProcessDoneCallback(ItemId, PsStatusEnum.DoneOk, message);
  204. IsRunning = false;
  205. FinishedTimestamp = DateTime.Now;
  206. }
  207. #endregion
  208. }
  209. }