Pool.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. using BO.ProcessServer.Options;
  2. using Quadarax.Foundation.Core.Object;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.IO.Abstractions;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. using Quadarax.Foundation.Core.IO.Extensions;
  10. using Quadarax.Foundation.Core.Logging;
  11. // ReSharper disable once InconsistentNaming
  12. namespace BO.ProcessServer.Business
  13. {
  14. internal class Pool : DisposableObject
  15. {
  16. #region *** Enums ***
  17. public enum PoolTypeEnum
  18. {
  19. Pending,
  20. Working,
  21. Done,
  22. Fail
  23. }
  24. #endregion
  25. #region *** Constants ***
  26. private const string CS_ALL_FILES = "*.*";
  27. #endregion
  28. #region *** Private fields ***
  29. private readonly IFileSystem _fileSystem;
  30. private IDirectoryInfo _dirPending;
  31. private IDirectoryInfo _dirWorking;
  32. private IDirectoryInfo _dirDone;
  33. private IDirectoryInfo _dirFail;
  34. private ILog _log;
  35. #endregion
  36. #region *** Constructors ***
  37. public Pool(Configuration configuration, IFileSystem fileSystem, ILogger logger)
  38. {
  39. _log = logger.GetLogger(GetType());
  40. if (configuration==null) throw new ArgumentNullException(nameof(configuration));
  41. _fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
  42. var basePath = TranslatePath(configuration.System.PoolPathBase);
  43. if (!_fileSystem.Directory.Exists(TranslatePath(configuration.System.PoolPathBase)))
  44. throw new FileNotFoundException($"BasePool directory '{basePath}' not found!");
  45. _dirPending = _fileSystem.DirectoryInfo.FromDirectoryName(_fileSystem.Path.Combine(basePath, configuration.System.PoolPathPending));
  46. _dirWorking = _fileSystem.DirectoryInfo.FromDirectoryName(_fileSystem.Path.Combine(basePath, configuration.System.PoolPathWorking));
  47. _dirDone = _fileSystem.DirectoryInfo.FromDirectoryName(_fileSystem.Path.Combine(basePath, configuration.System.PoolPathDone));
  48. _dirFail = _fileSystem.DirectoryInfo.FromDirectoryName(_fileSystem.Path.Combine(basePath, configuration.System.PoolPathFail));
  49. _log.Log(LogSeverityEnum.Info, $"Open pool in '{basePath}'. Initial status (files): Pending={_dirPending.GetFiles().Length};Working={_dirWorking.GetFiles().Length};Done={_dirDone.GetFiles().Length};Fail={_dirFail.GetFiles().Length}");
  50. }
  51. #endregion
  52. #region *** Public Operations ***
  53. public async Task<string> PutDocumentAsync(long documentId, string fileName, Stream streamToWrite)
  54. {
  55. var poolFileName = TranslateFileName(documentId, fileName);
  56. if (_dirPending.ExistsFile(poolFileName))
  57. {
  58. _log.Log(LogSeverityEnum.Warn, $"Pool [Pending]: File '{poolFileName}' already exists. Overwrite.");
  59. _dirPending.DeleteFile(poolFileName);
  60. }
  61. var fullFileName = _dirPending.GetFullFileName(poolFileName);
  62. await using (var sw = _fileSystem.File.OpenWrite(fullFileName))
  63. {
  64. streamToWrite.Seek(0, SeekOrigin.Begin);
  65. await streamToWrite.CopyToAsync(sw);
  66. await sw.FlushAsync();
  67. _log.Log(LogSeverityEnum.Debug, $"Pool [Pending]: File '{poolFileName}' created.");
  68. }
  69. return fullFileName;
  70. }
  71. public async Task<IEnumerable<string>> GetSinglePendingDocumentFilesAsync()
  72. {
  73. var first = GetPoolBranch(PoolTypeEnum.Pending).EnumerateFiles(CS_ALL_FILES, SearchOption.TopDirectoryOnly).FirstOrDefault();
  74. if (first == null) return new List<string>();
  75. var documentId = GetDocumentIdFromFileName(first.Name);
  76. return GetDocumentFiles(PoolTypeEnum.Pending, documentId);
  77. }
  78. public long GetDocumentIdFromFileName(string fileName)
  79. {
  80. var fileNameOnly = _fileSystem.Path.GetFileName(fileName);
  81. var pos = fileNameOnly.IndexOf("_", StringComparison.InvariantCulture);
  82. if (pos < 0)
  83. throw new ArgumentOutOfRangeException(nameof(fileName),
  84. $"FileName '{fileName}' format is unexpected (00000000_name.ext expects).");
  85. return long.Parse(fileNameOnly.Substring(0, pos));
  86. }
  87. public IEnumerable<string> GetDocumentsCount(PoolTypeEnum poolBranchFrom)
  88. {
  89. return GetPoolBranch(poolBranchFrom).GetFiles(CS_ALL_FILES, SearchOption.TopDirectoryOnly).Select(x=>x.FullName);
  90. }
  91. public IEnumerable<string> GetDocumentFiles(PoolTypeEnum poolBranchFrom, long documentId)
  92. {
  93. return GetPoolBranch(poolBranchFrom).GetFiles(TranslateSearchPattern(documentId), SearchOption.TopDirectoryOnly).Select(x=>x.FullName);
  94. }
  95. public IEnumerable<string> MoveDocumentFiles(PoolTypeEnum poolBranchFrom, PoolTypeEnum poolBranchTo, long documentId)
  96. {
  97. var files = GetDocumentFiles(poolBranchFrom, documentId).ToArray();
  98. var tasks = new List<Task>();
  99. foreach (var file in files)
  100. {
  101. tasks.Add(Task.Factory.StartNew(() =>
  102. {
  103. _fileSystem.File.Move(file, GetPoolBranch(poolBranchTo).GetFullFileName(_fileSystem.Path.GetFileName(file)));
  104. _log.Log(LogSeverityEnum.Debug, $"Pool [{poolBranchFrom}]: File '{_fileSystem.Path.GetFileName(file)}' moved to [{poolBranchTo}].");
  105. }
  106. ));
  107. }
  108. Task.WaitAll(tasks.ToArray());
  109. return files;
  110. }
  111. public IEnumerable<string> DeleteDocumentFiles(PoolTypeEnum poolBranchFrom, long documentId)
  112. {
  113. var files = GetPoolBranch(poolBranchFrom).GetFiles(TranslateSearchPattern(documentId), SearchOption.TopDirectoryOnly);
  114. foreach (var file in files)
  115. {
  116. file.Delete();
  117. _log.Log(LogSeverityEnum.Debug, $"Pool [{poolBranchFrom}]: File '{file.Name}' deleted.");
  118. }
  119. return files.Select(x => x.FullName);
  120. }
  121. #endregion
  122. #region *** Private operations & overrides ***
  123. protected override void OnDisposing()
  124. {
  125. _dirPending = null;
  126. _dirWorking = null;
  127. _dirDone = null;
  128. _dirFail = null;
  129. }
  130. private string TranslatePath(string path)
  131. {
  132. if (string.IsNullOrEmpty(path))
  133. return path;
  134. return path.Replace("{CD}", _fileSystem.Directory.GetCurrentDirectory());
  135. }
  136. private string TranslateFileName(long documentId, string originalFileName)
  137. {
  138. return $"{documentId:D8}_{originalFileName}";
  139. }
  140. private string TranslateSearchPattern(long documentId)
  141. {
  142. return $"{documentId:D8}_{CS_ALL_FILES}";
  143. }
  144. private IDirectoryInfo GetPoolBranch(PoolTypeEnum poolBranch)
  145. {
  146. switch (poolBranch)
  147. {
  148. case PoolTypeEnum.Done:
  149. return _dirDone;
  150. case PoolTypeEnum.Fail:
  151. return _dirFail;
  152. case PoolTypeEnum.Pending:
  153. return _dirPending;
  154. case PoolTypeEnum.Working:
  155. return _dirWorking;
  156. default:
  157. throw new NotSupportedException();
  158. }
  159. }
  160. #endregion
  161. }
  162. }