PsProcessProviderBase.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. public IDictionary<string, TypedArgument> Arguments { get; private set; }
  33. public bool IsRunning { get; private set; }
  34. public string ItemId { get; private set; }
  35. #endregion
  36. #region *** Private fields ***
  37. private CancellationTokenSource? _cancelationToken;
  38. #endregion
  39. #region *** Constructors ***
  40. public PsProcessProviderBase(ProcessDoneCallback processDoneCallback, ProcessStdOutputCallback processStdOutputCallback, string itemId, TypedArgument[] arguments, ILogger logger)
  41. {
  42. if (string.IsNullOrEmpty(itemId)) throw new ArgumentNullException(nameof(itemId));
  43. ProcessDoneCallback = processDoneCallback ?? throw new ArgumentNullException(nameof(processDoneCallback));
  44. ProcessStdOutputCallback = processStdOutputCallback ?? throw new ArgumentNullException(nameof(processStdOutputCallback));
  45. ItemId = itemId;
  46. Log = logger.GetLogger(GetType());
  47. Arguments = arguments.ToDictionary(x => x.Name, x => x);
  48. _cancelationToken = new CancellationTokenSource();
  49. }
  50. #endregion
  51. #region *** Public Operations ***
  52. /// <inheritdoc />
  53. public void Validate()
  54. {
  55. OnValidate();
  56. }
  57. /// <inheritdoc />
  58. public async void Start()
  59. {
  60. if (IsRunning)
  61. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderIsRunning, GetType().Name, ItemId);
  62. Validate();
  63. IsRunning = true;
  64. var timeout = GetArgumentValue<TimeSpan>(CS_ARG_PROCESS_TIMEOUT);
  65. var dtStart = DateTime.Now;
  66. try
  67. {
  68. await TimeoutUtils.ExecuteWithTimeoutAsync(async () =>
  69. {
  70. await OnProcess().ContinueWith(task =>
  71. {
  72. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' done. Duration {(DateTime.Now - dtStart).ToReadableString()}.");
  73. if (ProcessDoneCallback != null)
  74. ProcessDoneCallback(ItemId, PsStatusEnum.DoneOk, "Succesfuly done.");
  75. IsRunning = false;
  76. });
  77. }, timeout);
  78. }
  79. catch (Exception e)
  80. {
  81. await OnProcessError(e).ContinueWith(task =>
  82. {
  83. Log.Log(LogSeverityEnum.Error, $"Provider running failed. Duration {(DateTime.Now - dtStart).ToReadableString()}.", e);
  84. if (ProcessDoneCallback != null)
  85. ProcessDoneCallback(ItemId, PsStatusEnum.DoneFailed, e.Message);
  86. IsRunning = false;
  87. });
  88. }
  89. }
  90. /// <inheritdoc />
  91. public void Stop()
  92. {
  93. if (!IsRunning)
  94. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotRunning, GetType().Name, ItemId);
  95. _cancelationToken?.Cancel();
  96. IsRunning = false;
  97. }
  98. /// <summary>
  99. /// Generates all arguments collection
  100. /// </summary>
  101. /// <returns>Full scoped arguments collection</returns>
  102. public static IEnumerable<TypedArgument> CreateArguments()
  103. {
  104. var list = new List<TypedArgument>
  105. {
  106. new TypedArgument(CS_ARG_RESULT_CODE, typeof(long), true),
  107. new TypedArgument(CS_ARG_RESULT_TEXT, typeof(string), true),
  108. new TypedArgument(CS_ARG_PROCESS_TIMEOUT, typeof(TimeSpan), false)
  109. };
  110. return list;
  111. }
  112. /// <inheritdoc />
  113. public void WaitToDone()
  114. {
  115. while (IsRunning)
  116. {
  117. Task.Delay(100).Wait();
  118. };
  119. Log.Log(LogSeverityEnum.Debug, $"Provider for ItemId='{ItemId}' detect that process finished.");
  120. }
  121. #endregion
  122. #region *** Protected Operations ***
  123. protected TValue? GetArgumentValue<TValue>(string name)
  124. {
  125. if (string.IsNullOrEmpty(name))
  126. throw new ArgumentNullException(nameof(name));
  127. if (Arguments.TryGetValue(name, out var arg))
  128. return arg.GetTypedValue<TValue>();
  129. return default;
  130. }
  131. protected bool ContainsArgument(string name)
  132. {
  133. if (string.IsNullOrEmpty(name))
  134. throw new ArgumentNullException(nameof(name));
  135. return Arguments.ContainsKey(name);
  136. }
  137. protected virtual void OnValidate()
  138. {
  139. if (!ContainsArgument(CS_ARG_RESULT_CODE) || !Arguments[CS_ARG_RESULT_CODE].IsOutput)
  140. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_CODE);
  141. if (!ContainsArgument(CS_ARG_RESULT_TEXT) || !Arguments[CS_ARG_RESULT_TEXT].IsOutput)
  142. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_TEXT);
  143. if (!ContainsArgument(CS_ARG_PROCESS_TIMEOUT) || Arguments[CS_ARG_PROCESS_TIMEOUT].IsOutput)
  144. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_PROCESS_TIMEOUT);
  145. }
  146. protected virtual async Task OnProcessError(Exception exception)
  147. {
  148. if (exception == null)
  149. throw new ArgumentNullException(nameof(exception));
  150. if (ProcessStdOutputCallback != null)
  151. ProcessStdOutputCallback(ItemId, exception.Message);
  152. if (ContainsArgument(CS_ARG_RESULT_TEXT))
  153. Arguments[CS_ARG_RESULT_TEXT].Value = exception.Message;
  154. }
  155. protected virtual async Task OnProcess()
  156. {
  157. //nothing to do
  158. }
  159. /// <inheritdoc />
  160. protected override void OnDisposing()
  161. {
  162. ProcessDoneCallback = null!;
  163. ProcessStdOutputCallback = null!;
  164. }
  165. private async Task StartInternal()
  166. {
  167. var dtStart = DateTime.Now;
  168. try
  169. {
  170. await OnProcess().ContinueWith(task =>
  171. {
  172. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' done. Duration {(DateTime.Now - dtStart).ToReadableString()}.");
  173. if (ProcessDoneCallback != null)
  174. ProcessDoneCallback(ItemId, PsStatusEnum.DoneOk, "Succesfuly done.");
  175. IsRunning = false;
  176. });
  177. }
  178. catch (Exception e)
  179. {
  180. await OnProcessError(e).ContinueWith(task =>
  181. {
  182. Log.Log(LogSeverityEnum.Error, $"Provider running failed. Duration {(DateTime.Now - dtStart).ToReadableString()}.", e);
  183. if (ProcessDoneCallback != null)
  184. ProcessDoneCallback(ItemId, PsStatusEnum.DoneFailed, e.Message);
  185. IsRunning = false;
  186. });
  187. }
  188. }
  189. #endregion
  190. }
  191. }