PsProcessProviderBase.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 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. _ = Task.Factory.StartNew(() => StartInternal(timeout).TimeoutAfter(_cancelationToken!, timeout), _cancelationToken!.Token);
  66. }
  67. /// <inheritdoc />
  68. public void Stop()
  69. {
  70. if (!IsRunning)
  71. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotRunning, GetType().Name, ItemId);
  72. _cancelationToken?.Cancel();
  73. IsRunning = false;
  74. }
  75. /// <summary>
  76. /// Generates all arguments collection
  77. /// </summary>
  78. /// <returns>Full scoped arguments collection</returns>
  79. public static IEnumerable<TypedArgument> CreateArguments()
  80. {
  81. var list = new List<TypedArgument>
  82. {
  83. new TypedArgument(CS_ARG_RESULT_CODE, typeof(long), true),
  84. new TypedArgument(CS_ARG_RESULT_TEXT, typeof(string), true),
  85. new TypedArgument(CS_ARG_PROCESS_TIMEOUT, typeof(TimeSpan), false)
  86. };
  87. return list;
  88. }
  89. /// <inheritdoc />
  90. public void WaitToDone()
  91. {
  92. while(IsRunning)
  93. {
  94. Task.Delay(100).Wait();
  95. };
  96. Log.Log(LogSeverityEnum.Debug, $"Provider for ItemId='{ItemId}' detect that process finished.");
  97. }
  98. #endregion
  99. #region *** Protected Operations ***
  100. protected TValue? GetArgumentValue<TValue>(string name)
  101. {
  102. if (string.IsNullOrEmpty(name))
  103. throw new ArgumentNullException(nameof(name));
  104. if (Arguments.TryGetValue(name, out var arg))
  105. return arg.GetTypedValue<TValue>();
  106. return default;
  107. }
  108. protected bool ContainsArgument(string name)
  109. {
  110. if (string.IsNullOrEmpty(name))
  111. throw new ArgumentNullException(nameof(name));
  112. return Arguments.ContainsKey(name);
  113. }
  114. protected virtual void OnValidate()
  115. {
  116. if (!ContainsArgument(CS_ARG_RESULT_CODE) || !Arguments[CS_ARG_RESULT_CODE].IsOutput)
  117. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_CODE);
  118. if (!ContainsArgument(CS_ARG_RESULT_TEXT) || !Arguments[CS_ARG_RESULT_TEXT].IsOutput)
  119. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_TEXT);
  120. if (!ContainsArgument(CS_ARG_PROCESS_TIMEOUT) || Arguments[CS_ARG_PROCESS_TIMEOUT].IsOutput)
  121. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_PROCESS_TIMEOUT);
  122. }
  123. protected virtual async Task OnProcessError(Exception exception)
  124. {
  125. if (exception == null)
  126. throw new ArgumentNullException(nameof(exception));
  127. if (ProcessStdOutputCallback != null)
  128. ProcessStdOutputCallback(ItemId, exception.Message);
  129. if (ContainsArgument(CS_ARG_RESULT_TEXT))
  130. Arguments[CS_ARG_RESULT_TEXT].Value = exception.Message;
  131. }
  132. protected virtual async Task OnProcess()
  133. {
  134. //nothing to do
  135. }
  136. /// <inheritdoc />
  137. protected override void OnDisposing()
  138. {
  139. ProcessDoneCallback = null!;
  140. ProcessStdOutputCallback = null!;
  141. }
  142. private async Task StartInternal(TimeSpan timeout)
  143. {
  144. var dtStart = DateTime.Now;
  145. try
  146. {
  147. Log.Log(LogSeverityEnum.Debug, $"Provider for ItemId='{ItemId}' has general timeout for execution {timeout.ToReadableString()}.");
  148. await OnProcess().ContinueWith(task =>
  149. {
  150. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' done. Duration {(DateTime.Now - dtStart).ToReadableString()}.");
  151. if (ProcessDoneCallback != null)
  152. ProcessDoneCallback(ItemId, PsStatusEnum.DoneOk, "Succesfuly done.");
  153. IsRunning = false;
  154. });
  155. }
  156. catch (Exception e)
  157. {
  158. await OnProcessError(e).ContinueWith(task =>
  159. {
  160. Log.Log(LogSeverityEnum.Error, $"Provider running failed. Duration {(DateTime.Now - dtStart).ToReadableString()}.", e);
  161. if (ProcessDoneCallback != null)
  162. ProcessDoneCallback(ItemId, PsStatusEnum.DoneFailed, e.Message);
  163. IsRunning = false;
  164. });
  165. }
  166. }
  167. #endregion
  168. }
  169. }