Pool.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. private const string CS_ALL_FILES_WOEXT = "*";
  28. #endregion
  29. #region *** Private fields ***
  30. private readonly IFileSystem _fileSystem;
  31. private IDirectoryInfo _dirPending;
  32. private IDirectoryInfo _dirWorking;
  33. private IDirectoryInfo _dirDone;
  34. private IDirectoryInfo _dirFail;
  35. private ILog _log;
  36. #endregion
  37. #region *** Constructors ***
  38. public Pool(Configuration configuration, IFileSystem fileSystem, ILogger logger)
  39. {
  40. _log = logger.GetLogger(GetType());
  41. if (configuration==null) throw new ArgumentNullException(nameof(configuration));
  42. _fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
  43. var basePath = TranslatePath(configuration.System.PoolPathBase);
  44. if (!_fileSystem.Directory.Exists(TranslatePath(configuration.System.PoolPathBase)))
  45. throw new FileNotFoundException($"BasePool directory '{basePath}' not found!");
  46. _dirPending = _fileSystem.DirectoryInfo.FromDirectoryName(_fileSystem.Path.Combine(basePath, configuration.System.PoolPathPending));
  47. _dirWorking = _fileSystem.DirectoryInfo.FromDirectoryName(_fileSystem.Path.Combine(basePath, configuration.System.PoolPathWorking));
  48. _dirDone = _fileSystem.DirectoryInfo.FromDirectoryName(_fileSystem.Path.Combine(basePath, configuration.System.PoolPathDone));
  49. _dirFail = _fileSystem.DirectoryInfo.FromDirectoryName(_fileSystem.Path.Combine(basePath, configuration.System.PoolPathFail));
  50. _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}");
  51. }
  52. #endregion
  53. #region *** Public Operations ***
  54. public async Task<string> PutDocumentAsync(long documentId, string fileName, Stream streamToWrite)
  55. {
  56. var poolFileName = TranslateFileName(documentId, fileName);
  57. if (_dirPending.ExistsFile(poolFileName))
  58. {
  59. _log.Log(LogSeverityEnum.Warn, $"Pool [Pending]: File '{poolFileName}' already exists. Overwrite.");
  60. _dirPending.DeleteFile(poolFileName);
  61. }
  62. var fullFileName = _dirPending.GetFullFileName(poolFileName);
  63. await using (var sw = _fileSystem.File.OpenWrite(fullFileName))
  64. {
  65. streamToWrite.Seek(0, SeekOrigin.Begin);
  66. await streamToWrite.CopyToAsync(sw);
  67. await sw.FlushAsync();
  68. _log.Log(LogSeverityEnum.Debug, $"Pool [Pending]: File '{poolFileName}' created.");
  69. }
  70. return fullFileName;
  71. }
  72. public async Task<Stream> PopDocumentAsync(string fullFileName)
  73. {
  74. var memory = new MemoryStream();
  75. await using (var sw = _fileSystem.File.OpenRead(fullFileName))
  76. {
  77. await sw.CopyToAsync(memory);
  78. await memory.FlushAsync();
  79. _log.Log(LogSeverityEnum.Debug, $"Pool: File '{fullFileName}' pop.");
  80. }
  81. memory.Seek(0, SeekOrigin.Begin);
  82. return memory;
  83. }
  84. public async Task<Tuple<long, IEnumerable<string>>> GetSinglePendingDocumentFilesAsync()
  85. {
  86. var first = GetPoolBranch(PoolTypeEnum.Pending).EnumerateFiles(CS_ALL_FILES, SearchOption.TopDirectoryOnly).FirstOrDefault();
  87. if (first == null) return new Tuple<long, IEnumerable<string>>(-1, new List<string>());
  88. var documentId = GetDocumentIdFromFileName(first.Name);
  89. return new Tuple<long, IEnumerable<string>>(documentId, GetDocumentFiles(PoolTypeEnum.Pending, documentId));
  90. }
  91. public long GetDocumentIdFromFileName(string fileName)
  92. {
  93. var fileNameOnly = _fileSystem.Path.GetFileName(fileName);
  94. var pos = fileNameOnly.IndexOf("_", StringComparison.InvariantCulture);
  95. if (pos < 0)
  96. throw new ArgumentOutOfRangeException(nameof(fileName),
  97. $"FileName '{fileName}' format is unexpected (00000000_name.ext expects).");
  98. return long.Parse(fileNameOnly.Substring(0, pos));
  99. }
  100. public int GetDocumentsCount(PoolTypeEnum poolBranchFrom)
  101. {
  102. return GetPoolBranch(poolBranchFrom).GetFiles(CS_ALL_FILES, SearchOption.TopDirectoryOnly).Select(x=>x.FullName).Count();
  103. }
  104. public long GetDocumentsSize(PoolTypeEnum poolBranchFrom)
  105. {
  106. var files = GetPoolBranch(poolBranchFrom).GetFiles(CS_ALL_FILES, SearchOption.TopDirectoryOnly);
  107. return files.Aggregate<IFileInfo, long>(0, (current, file) => current + file.Length);
  108. }
  109. public IEnumerable<long> GetDocumentIdsFromOldest(PoolTypeEnum poolBranchFrom)
  110. {
  111. var result = new List<long>();
  112. var files = GetPoolBranch(poolBranchFrom).GetFiles(CS_ALL_FILES, SearchOption.TopDirectoryOnly).OrderByDescending(x=>x.LastWriteTime);
  113. foreach (var file in files)
  114. {
  115. var docId = GetDocumentIdFromFileName(file.FullName);
  116. if (!result.Contains(docId))
  117. result.Add(docId);
  118. }
  119. return result;
  120. }
  121. public IEnumerable<string> GetDocumentFiles(PoolTypeEnum poolBranchFrom, long documentId, string alternativeExt = null)
  122. {
  123. return GetPoolBranch(poolBranchFrom).GetFiles(TranslateSearchPattern(documentId,alternativeExt), SearchOption.TopDirectoryOnly).Select(x=>x.FullName);
  124. }
  125. public IEnumerable<string> MoveDocumentFiles(PoolTypeEnum poolBranchFrom, PoolTypeEnum poolBranchTo, long documentId, string alternativeExt = null)
  126. {
  127. var files = GetDocumentFiles(poolBranchFrom, documentId, alternativeExt).ToArray();
  128. var tasks = new List<Task>();
  129. foreach (var file in files)
  130. {
  131. tasks.Add(Task.Factory.StartNew(() =>
  132. {
  133. _fileSystem.File.Move(file, GetPoolBranch(poolBranchTo).GetFullFileName(_fileSystem.Path.GetFileName(file)));
  134. _log.Log(LogSeverityEnum.Debug, $"Pool [{poolBranchFrom}]: File '{_fileSystem.Path.GetFileName(file)}' moved to [{poolBranchTo}].");
  135. }
  136. ));
  137. }
  138. Task.WaitAll(tasks.ToArray());
  139. return files;
  140. }
  141. public IEnumerable<string> DeleteDocumentFiles(PoolTypeEnum poolBranchFrom, long documentId)
  142. {
  143. var files = GetPoolBranch(poolBranchFrom).GetFiles(TranslateSearchPattern(documentId), SearchOption.TopDirectoryOnly);
  144. foreach (var file in files)
  145. {
  146. file.Delete();
  147. _log.Log(LogSeverityEnum.Debug, $"Pool [{poolBranchFrom}]: File '{file.Name}' deleted.");
  148. }
  149. return files.Select(x => x.FullName);
  150. }
  151. #endregion
  152. #region *** Private operations & overrides ***
  153. protected override void OnDisposing()
  154. {
  155. _dirPending = null;
  156. _dirWorking = null;
  157. _dirDone = null;
  158. _dirFail = null;
  159. }
  160. private string TranslatePath(string path)
  161. {
  162. if (string.IsNullOrEmpty(path))
  163. return path;
  164. return path.Replace(Constants.CS_TAG_CURRENT_DIR, _fileSystem.Directory.GetCurrentDirectory());
  165. }
  166. private string TranslateFileName(long documentId, string originalFileName)
  167. {
  168. return $"{documentId:D8}_{originalFileName}";
  169. }
  170. private string TranslateSearchPattern(long documentId,string alternativeExt = null)
  171. {
  172. var search = CS_ALL_FILES;
  173. if (!string.IsNullOrEmpty(alternativeExt))
  174. search = CS_ALL_FILES_WOEXT + alternativeExt;
  175. return $"{documentId:D8}_{CS_ALL_FILES}";
  176. }
  177. private IDirectoryInfo GetPoolBranch(PoolTypeEnum poolBranch)
  178. {
  179. switch (poolBranch)
  180. {
  181. case PoolTypeEnum.Done:
  182. return _dirDone;
  183. case PoolTypeEnum.Fail:
  184. return _dirFail;
  185. case PoolTypeEnum.Pending:
  186. return _dirPending;
  187. case PoolTypeEnum.Working:
  188. return _dirWorking;
  189. default:
  190. throw new NotSupportedException();
  191. }
  192. }
  193. #endregion
  194. }
  195. }