Pool.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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 long GetDocumentIdFromFileName(string fileName)
  72. {
  73. var fileNameOnly = _fileSystem.Path.GetFileName(fileName);
  74. var pos = fileNameOnly.IndexOf("_", StringComparison.InvariantCulture);
  75. if (pos < 0)
  76. throw new ArgumentOutOfRangeException(nameof(fileName),
  77. $"FileName '{fileName}' format is unexpected (00000000_name.ext expects).");
  78. return long.Parse(fileNameOnly.Substring(0, pos));
  79. }
  80. public IEnumerable<string> GetDocumentsCount(PoolTypeEnum poolBranchFrom)
  81. {
  82. return GetPoolBranch(poolBranchFrom).GetFiles(CS_ALL_FILES, SearchOption.TopDirectoryOnly).Select(x=>x.FullName);
  83. }
  84. public IEnumerable<string> GetDocumentFiles(PoolTypeEnum poolBranchFrom, long documentId)
  85. {
  86. return GetPoolBranch(poolBranchFrom).GetFiles(TranslateSearchPattern(documentId), SearchOption.TopDirectoryOnly).Select(x=>x.FullName);
  87. }
  88. public IEnumerable<string> MoveDocumentFiles(PoolTypeEnum poolBranchFrom, PoolTypeEnum poolBranchTo, long documentId)
  89. {
  90. var files = GetDocumentFiles(poolBranchFrom, documentId).ToArray();
  91. var tasks = new List<Task>();
  92. foreach (var file in files)
  93. {
  94. tasks.Add(Task.Factory.StartNew(() =>
  95. {
  96. _fileSystem.File.Move(file, GetPoolBranch(poolBranchTo).GetFullFileName(_fileSystem.Path.GetFileName(file)));
  97. _log.Log(LogSeverityEnum.Debug, $"Pool [{poolBranchFrom}]: File '{_fileSystem.Path.GetFileName(file)}' moved to [{poolBranchTo}].");
  98. }
  99. ));
  100. }
  101. Task.WaitAll(tasks.ToArray());
  102. return files;
  103. }
  104. public IEnumerable<string> DeleteDocumentFiles(PoolTypeEnum poolBranchFrom, long documentId)
  105. {
  106. var files = GetPoolBranch(poolBranchFrom).GetFiles(TranslateSearchPattern(documentId), SearchOption.TopDirectoryOnly);
  107. foreach (var file in files)
  108. {
  109. file.Delete();
  110. _log.Log(LogSeverityEnum.Debug, $"Pool [{poolBranchFrom}]: File '{file.Name}' deleted.");
  111. }
  112. return files.Select(x => x.FullName);
  113. }
  114. #endregion
  115. #region *** Private operations & overrides ***
  116. protected override void OnDisposing()
  117. {
  118. _dirPending = null;
  119. _dirWorking = null;
  120. _dirDone = null;
  121. _dirFail = null;
  122. }
  123. private string TranslatePath(string path)
  124. {
  125. if (string.IsNullOrEmpty(path))
  126. return path;
  127. return path.Replace("{CD}", _fileSystem.Directory.GetCurrentDirectory());
  128. }
  129. private string TranslateFileName(long documentId, string originalFileName)
  130. {
  131. return $"{documentId:D8}_{originalFileName}";
  132. }
  133. private string TranslateSearchPattern(long documentId)
  134. {
  135. return $"{documentId:D8}_{CS_ALL_FILES}";
  136. }
  137. private IDirectoryInfo GetPoolBranch(PoolTypeEnum poolBranch)
  138. {
  139. switch (poolBranch)
  140. {
  141. case PoolTypeEnum.Done:
  142. return _dirDone;
  143. case PoolTypeEnum.Fail:
  144. return _dirFail;
  145. case PoolTypeEnum.Pending:
  146. return _dirPending;
  147. case PoolTypeEnum.Working:
  148. return _dirWorking;
  149. default:
  150. throw new NotSupportedException();
  151. }
  152. }
  153. #endregion
  154. }
  155. }