PsProcessProviderBase.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. using qdr.fnd.core.pqueue.Enums;
  2. using qdr.fnd.core.pqueue.Exceptions;
  3. using Quadarax.Foundation.Core.Data;
  4. using Quadarax.Foundation.Core.Logging;
  5. using Quadarax.Foundation.Core.Object;
  6. using Quadarax.Foundation.Core.Thread.Extensions;
  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), _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. #endregion
  90. #region *** Protected Operations ***
  91. protected TValue? GetArgumentValue<TValue>(string name)
  92. {
  93. if (string.IsNullOrEmpty(name))
  94. throw new ArgumentNullException(nameof(name));
  95. if (Arguments.TryGetValue(name, out var arg))
  96. return arg.GetTypedValue<TValue>();
  97. return default;
  98. }
  99. protected bool ContainsArgument(string name)
  100. {
  101. if (string.IsNullOrEmpty(name))
  102. throw new ArgumentNullException(nameof(name));
  103. return Arguments.ContainsKey(name);
  104. }
  105. protected virtual void OnValidate()
  106. {
  107. if (!ContainsArgument(CS_ARG_RESULT_CODE) || !Arguments[CS_ARG_RESULT_CODE].IsOutput)
  108. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_CODE);
  109. if (!ContainsArgument(CS_ARG_RESULT_TEXT) || !Arguments[CS_ARG_RESULT_TEXT].IsOutput)
  110. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_TEXT);
  111. if (!ContainsArgument(CS_ARG_PROCESS_TIMEOUT) || Arguments[CS_ARG_PROCESS_TIMEOUT].IsOutput)
  112. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_PROCESS_TIMEOUT);
  113. }
  114. protected virtual async Task OnProcessError(Exception exception)
  115. {
  116. if (exception == null)
  117. throw new ArgumentNullException(nameof(exception));
  118. if (ProcessStdOutputCallback != null)
  119. ProcessStdOutputCallback(ItemId, exception.Message);
  120. if (ContainsArgument(CS_ARG_RESULT_TEXT))
  121. Arguments[CS_ARG_RESULT_TEXT].Value = exception.Message;
  122. }
  123. protected virtual async Task OnProcess()
  124. {
  125. //nothing to do
  126. }
  127. /// <inheritdoc />
  128. protected override void OnDisposing()
  129. {
  130. ProcessDoneCallback = null!;
  131. ProcessStdOutputCallback = null!;
  132. }
  133. private async Task StartInternal(TimeSpan timeout)
  134. {
  135. var dtStart = DateTime.Now;
  136. try
  137. {
  138. await OnProcess().TimeoutAfter(timeout).ContinueWith(task =>
  139. {
  140. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' done. Duration {(DateTime.Now - dtStart).ToReadableString()}.");
  141. if (ProcessDoneCallback != null)
  142. ProcessDoneCallback(ItemId, PsStatusEnum.DoneOk, "Succesfuly done.");
  143. IsRunning = false;
  144. });
  145. }
  146. catch (Exception e)
  147. {
  148. await OnProcessError(e).ContinueWith(task =>
  149. {
  150. Log.Log(LogSeverityEnum.Error, $"Provider running failed. Duration {(DateTime.Now - dtStart).ToReadableString()}.", e);
  151. if (ProcessDoneCallback != null)
  152. ProcessDoneCallback(ItemId, PsStatusEnum.DoneFailed, e.Message);
  153. IsRunning = false;
  154. });
  155. }
  156. }
  157. #endregion
  158. }
  159. }