PsProcessProviderBase.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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(Callbacks callbacks, string itemId, TypedArgument[] arguments, ILogger logger)
  47. {
  48. if (string.IsNullOrEmpty(itemId)) throw new ArgumentNullException(nameof(itemId));
  49. if (callbacks==null) throw new ArgumentNullException(nameof(callbacks));
  50. ProcessDoneCallback = callbacks.ProcessDoneCallback ?? throw new ArgumentNullException("callbacks.ProcessDoneCallback");
  51. ProcessStdOutputCallback = callbacks.ProcessStdOutputCallback ?? throw new ArgumentNullException("callbacks.ProcessStdOutputCallback");
  52. ItemId = itemId;
  53. Log = logger.GetLogger(GetType());
  54. Arguments = arguments.ToDictionary(x => x.Name, x => x);
  55. _cancelationToken = new CancellationTokenSource();
  56. }
  57. public PsProcessProviderBase(ConstructorArguments constructorArguments)
  58. : this(constructorArguments.Callbacks, constructorArguments.ItemId, constructorArguments.Arguments, constructorArguments.Logger)
  59. {
  60. }
  61. #endregion
  62. #region *** Public Operations ***
  63. /// <inheritdoc />
  64. public void Validate()
  65. {
  66. OnValidate();
  67. }
  68. /// <inheritdoc />
  69. public void Start()
  70. {
  71. if (IsRunning)
  72. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderIsRunning, GetType().Name, ItemId);
  73. Validate();
  74. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' starting.");
  75. IsRunning = true;
  76. StartedTimestamp = DateTime.Now;
  77. var timeout = GetArgumentValue<TimeSpan>(CS_ARG_PROCESS_TIMEOUT);
  78. Task.Run(async () =>
  79. {
  80. try
  81. {
  82. await TimeoutUtils.ExecuteWithTimeoutAsync(async () =>
  83. {
  84. await OnProcess().ContinueWith(task =>
  85. {
  86. if (task.IsFaulted)
  87. {
  88. var e = task.Exception!;
  89. OnProcessError(e).ContinueWith(taskInner =>
  90. {
  91. if (taskInner.IsFaulted)
  92. throw taskInner.Exception!;
  93. ProcessDoneFailed(e.Message, e);
  94. });
  95. }
  96. else
  97. {
  98. ProcessDoneOk("Succesfuly done.");
  99. }
  100. });
  101. }, timeout);
  102. }
  103. catch (Exception e)
  104. {
  105. await OnProcessError(e).ContinueWith(task =>
  106. {
  107. if (task.IsFaulted)
  108. throw task.Exception!;
  109. ProcessDoneFailed(e.Message, e);
  110. });
  111. }
  112. });
  113. }
  114. /// <inheritdoc />
  115. public void Stop()
  116. {
  117. if (!IsRunning)
  118. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotRunning, GetType().Name, ItemId);
  119. _cancelationToken?.Cancel();
  120. ProcessDoneFailed("Process was forced stopped.");
  121. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' was forced stopped.");
  122. }
  123. /// <summary>
  124. /// Generates all arguments collection
  125. /// </summary>
  126. /// <returns>Full scoped arguments collection</returns>
  127. public static IEnumerable<TypedArgument> CreateArguments()
  128. {
  129. var list = new List<TypedArgument>
  130. {
  131. new TypedArgument(CS_ARG_RESULT_CODE, typeof(long), true),
  132. new TypedArgument(CS_ARG_RESULT_TEXT, typeof(string), true),
  133. new TypedArgument(CS_ARG_PROCESS_TIMEOUT, typeof(TimeSpan), false)
  134. };
  135. return list;
  136. }
  137. /// <inheritdoc />
  138. public void WaitToDone()
  139. {
  140. while (IsRunning)
  141. {
  142. Task.Delay(100).Wait();
  143. };
  144. Log.Log(LogSeverityEnum.Debug, $"Provider for ItemId='{ItemId}' detect that process finished.");
  145. }
  146. #endregion
  147. #region *** Protected Operations ***
  148. protected TValue? GetArgumentValue<TValue>(string name)
  149. {
  150. if (string.IsNullOrEmpty(name))
  151. throw new ArgumentNullException(nameof(name));
  152. if (Arguments.TryGetValue(name, out var arg))
  153. return arg.GetTypedValue<TValue>();
  154. return default;
  155. }
  156. protected bool ContainsArgument(string name)
  157. {
  158. if (string.IsNullOrEmpty(name))
  159. throw new ArgumentNullException(nameof(name));
  160. return Arguments.ContainsKey(name);
  161. }
  162. protected virtual void OnValidate()
  163. {
  164. if (!ContainsArgument(CS_ARG_RESULT_CODE) || !Arguments[CS_ARG_RESULT_CODE].IsOutput)
  165. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_CODE);
  166. if (!ContainsArgument(CS_ARG_RESULT_TEXT) || !Arguments[CS_ARG_RESULT_TEXT].IsOutput)
  167. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_TEXT);
  168. if (!ContainsArgument(CS_ARG_PROCESS_TIMEOUT) || Arguments[CS_ARG_PROCESS_TIMEOUT].IsOutput)
  169. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_PROCESS_TIMEOUT);
  170. }
  171. #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
  172. protected virtual async Task OnProcessError(Exception exception)
  173. #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
  174. {
  175. if (exception == null)
  176. throw new ArgumentNullException(nameof(exception));
  177. if (ProcessStdOutputCallback != null)
  178. ProcessStdOutputCallback(ItemId, exception.Message);
  179. if (ContainsArgument(CS_ARG_RESULT_TEXT))
  180. Arguments[CS_ARG_RESULT_TEXT].Value = exception.Message;
  181. }
  182. #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
  183. protected virtual async Task OnProcess()
  184. #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
  185. {
  186. //nothing to do
  187. }
  188. /// <inheritdoc />
  189. protected override void OnDisposing()
  190. {
  191. _cancelationToken?.Dispose();
  192. ProcessDoneCallback = null!;
  193. ProcessStdOutputCallback = null!;
  194. _cancelationToken = null;
  195. }
  196. private void ProcessDoneFailed(string message, Exception? e = null)
  197. {
  198. Log.Log(LogSeverityEnum.Error, $"Provider running failed. Duration {(DateTime.Now - StartedTimestamp.GetValueOrDefault()).ToReadableString()}.", e);
  199. if (ProcessDoneCallback != null)
  200. ProcessDoneCallback(ItemId, PsStatusEnum.DoneFailed, message);
  201. IsRunning = false;
  202. FinishedTimestamp = DateTime.Now;
  203. }
  204. private void ProcessDoneOk(string message)
  205. {
  206. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' done. Duration {(DateTime.Now - StartedTimestamp.GetValueOrDefault()).ToReadableString()}.");
  207. if (ProcessDoneCallback != null)
  208. ProcessDoneCallback(ItemId, PsStatusEnum.DoneOk, message);
  209. IsRunning = false;
  210. FinishedTimestamp = DateTime.Now;
  211. }
  212. #endregion
  213. #region *** Nested Classes ***
  214. public class Callbacks
  215. {
  216. public ProcessDoneCallback ProcessDoneCallback { get; private set; }
  217. public ProcessStdOutputCallback ProcessStdOutputCallback { get; private set; }
  218. public Callbacks(ProcessDoneCallback processDoneCallback, ProcessStdOutputCallback processStdOutputCallback)
  219. {
  220. ProcessDoneCallback = processDoneCallback;
  221. ProcessStdOutputCallback = processStdOutputCallback;
  222. }
  223. }
  224. public class ConstructorArguments
  225. {
  226. public Callbacks Callbacks { get; private set; }
  227. public string ItemId { get; private set; }
  228. public TypedArgument[] Arguments { get; private set; }
  229. public ILogger Logger { get; private set; }
  230. public ConstructorArguments(Callbacks callbacks, string itemId, TypedArgument[] arguments, ILogger logger)
  231. {
  232. Callbacks = callbacks;
  233. ItemId = itemId;
  234. Arguments = arguments;
  235. Logger = logger;
  236. }
  237. }
  238. #endregion
  239. }
  240. }