QueueItem.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text;
  5. using Quadarax.Foundation.Core.Business.Exceptions;
  6. using Quadarax.Foundation.Core.Object;
  7. using Quadarax.Foundation.Core.Value.Extensions;
  8. namespace Quadarax.Foundation.Core.Business.ProcessQueue
  9. {
  10. public class QueueItem : DisposableObject, IQueueItem
  11. {
  12. public QueueItemStateEnum State { get; protected set;}
  13. public DateTime Created { get; }
  14. public DateTime? Modified { get; }
  15. public DateTime? Started { get; }
  16. public DateTime? Finished { get; }
  17. public DateTime StartFrom { get; }
  18. public DateTime? StartTo { get; }
  19. public string Affinity { get; protected set; }
  20. public int Priority { get; }
  21. public void Assign(string assignTo)
  22. {
  23. if (!string.IsNullOrEmpty(Affinity) && !string.IsNullOrEmpty(assignTo))
  24. throw new InvalidStateException(
  25. $"Query item '{GetIdentifier()}' has already set Affinity to '{Affinity}'");
  26. ValidateState("set Affinity", QueueItemStateEnum.New, QueueItemStateEnum.Paused);
  27. ends here
  28. Affinity = assignTo;
  29. }
  30. public void Start()
  31. {
  32. throw new NotImplementedException();
  33. }
  34. public void Stop()
  35. {
  36. throw new NotImplementedException();
  37. }
  38. public void Pause()
  39. {
  40. throw new NotImplementedException();
  41. }
  42. public string GetIdentifier()
  43. {
  44. return OnGetIdentifer();
  45. }
  46. protected void ValidateState(string operationName, params QueueItemStateEnum[] allowedStates)
  47. {
  48. if (string.IsNullOrEmpty(operationName)) throw new ArgumentNullException(nameof(operationName));
  49. if (allowedStates.Length==0)
  50. return;
  51. if (!State.In(allowedStates))
  52. throw new InvalidStateException(
  53. $"Query item '{GetIdentifier()}' has invalid state to {operationName} (expecting. {string.Join(",", allowedStates.Select(x=>x.ToString()))}");
  54. }
  55. protected virtual string OnGetIdentifer()
  56. {
  57. var sb = new StringBuilder();
  58. sb.Append("QI").Append(Created.ToFileTimeUtc()).Append("_").Append(StartFrom.ToFileTimeUtc()).Append("_")
  59. .Append(string.IsNullOrEmpty(Affinity) ? 0 : Affinity.GetHashCode());
  60. return sb.ToString();
  61. }
  62. protected override void OnDisposing()
  63. {
  64. }
  65. }
  66. }