ReaderWorker.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. const fs = require('fs-extra');
  2. const path = require('path');
  3. const LimitedQueue = require('../LimitedQueue');
  4. const WorkerState = require('../WorkerState');//singleton
  5. const FileDownloader = require('../FileDownloader');
  6. const FileDecompressor = require('../FileDecompressor');
  7. const BookConverter = require('./BookConverter');
  8. const RemoteStorage = require('../RemoteStorage');
  9. const JembaConnManager = require('../../db/JembaConnManager');//singleton
  10. const ayncExit = new (require('../AsyncExit'))();
  11. const utils = require('../utils');
  12. const log = new (require('../AppLogger'))().log;//singleton
  13. const cleanDirPeriod = 60*60*1000;//каждый час
  14. const remoteSendPeriod = 119*1000;//примерно раз 2 минуты
  15. const queue = new LimitedQueue(5, 100, 2*60*1000 + 15000);//2 минуты ожидание подвижек
  16. let instance = null;
  17. //singleton
  18. class ReaderWorker {
  19. constructor(config) {
  20. if (!instance) {
  21. this.config = Object.assign({}, config);
  22. this.config.tempDownloadDir = `${config.tempDir}/download`;
  23. fs.ensureDirSync(this.config.tempDownloadDir);
  24. this.workerState = new WorkerState();
  25. this.down = new FileDownloader(config.maxUploadFileSize);
  26. this.decomp = new FileDecompressor(3*config.maxUploadFileSize);
  27. this.bookConverter = new BookConverter(this.config);
  28. this.connManager = new JembaConnManager();
  29. this.appDb = this.connManager.db['app'];
  30. this.remoteStorage = false;
  31. if (config.remoteStorage) {
  32. this.remoteStorage = new RemoteStorage(
  33. Object.assign({maxContentLength: 3*config.maxUploadFileSize}, config.remoteStorage)
  34. );
  35. }
  36. this.dirConfigArr = [
  37. {
  38. dir: this.config.tempPublicDir,
  39. remoteDir: '/tmp',
  40. maxSize: this.config.maxTempPublicDirSize,
  41. moveToRemote: true,
  42. },
  43. {
  44. dir: this.config.uploadPublicDir,
  45. remoteDir: '/upload',
  46. maxSize: this.config.maxUploadPublicDirSize,
  47. moveToRemote: true,
  48. }
  49. ];
  50. //преобразуем в объект для большего удобства
  51. this.dirConfig = {};
  52. for (const configRec of this.dirConfigArr)
  53. this.dirConfig[configRec.remoteDir] = configRec;
  54. this.remoteFilesToSend = [];
  55. this.periodicCleanDir();//no await
  56. instance = this;
  57. }
  58. return instance;
  59. }
  60. async loadBook(opts, wState) {
  61. const url = opts.url;
  62. let decompDir = '';
  63. let downloadedFilename = '';
  64. let isUploaded = false;
  65. let convertFilename = '';
  66. const overLoadMes = 'Слишком большая очередь загрузки. Пожалуйста, попробуйте позже.';
  67. const fileNotFoundMes = 'Файл не найден';
  68. const overLoadErr = new Error(overLoadMes);
  69. let q = null;
  70. try {
  71. wState.set({state: 'queue', step: 1, totalSteps: 1});
  72. try {
  73. let qSize = 0;
  74. q = await queue.get((place) => {
  75. wState.set({place, progress: (qSize ? Math.round((qSize - place)/qSize*100) : 0)});
  76. if (!qSize)
  77. qSize = place;
  78. });
  79. } catch (e) {
  80. throw overLoadErr;
  81. }
  82. wState.set({state: 'download', step: 1, totalSteps: 3, url});
  83. const tempFilename = utils.randomHexString(30);
  84. const tempFilename2 = utils.randomHexString(30);
  85. const decompDirname = utils.randomHexString(30);
  86. let downloadSize = -1;
  87. //download or use uploaded
  88. if (url.indexOf('disk://') != 0) {//download
  89. const downdata = await this.down.load(url, {}, (progress) => {
  90. wState.set({progress});
  91. }, q.abort);
  92. downloadedFilename = `${this.config.tempDownloadDir}/${tempFilename}`;
  93. downloadSize = downdata.length;
  94. await fs.writeFile(downloadedFilename, downdata);
  95. } else {//uploaded file
  96. const fileHash = url.substr(7);
  97. downloadedFilename = `${this.config.uploadPublicDir}/${fileHash}`;
  98. if (!await fs.pathExists(downloadedFilename)) {
  99. //если удалено из upload, попробуем восстановить из удаленного хранилища
  100. try {
  101. await this.restoreRemoteFile(fileHash, '/upload');
  102. } catch(e) {
  103. throw new Error('Файл не найден на сервере (возможно был удален как устаревший). Пожалуйста, загрузите файл с диска на сервер заново.');
  104. }
  105. }
  106. await utils.touchFile(downloadedFilename);
  107. isUploaded = true;
  108. }
  109. wState.set({progress: 100});
  110. if (q.abort())
  111. throw overLoadErr;
  112. q.resetTimeout();
  113. //decompress
  114. wState.set({state: 'decompress', step: 2, progress: 0});
  115. decompDir = `${this.config.tempDownloadDir}/${decompDirname}`;
  116. let decompFiles = {};
  117. try {
  118. decompFiles = await this.decomp.decompressNested(downloadedFilename, decompDir);
  119. } catch (e) {
  120. log(LM_ERR, e.stack);
  121. throw new Error('Ошибка распаковки');
  122. }
  123. wState.set({progress: 100});
  124. if (q.abort())
  125. throw overLoadErr;
  126. q.resetTimeout();
  127. //конвертирование в fb2
  128. wState.set({state: 'convert', step: 3, progress: 0});
  129. convertFilename = `${this.config.tempDownloadDir}/${tempFilename2}`;
  130. await this.bookConverter.convertToFb2(decompFiles, convertFilename, opts, progress => {
  131. wState.set({progress});
  132. if (queue.freed > 0)
  133. q.resetTimeout();
  134. }, q.abort);
  135. //сжимаем файл в tmp, если там уже нет с тем же именем-sha256
  136. const compFilename = await this.decomp.gzipFileIfNotExists(convertFilename, this.config.tempPublicDir);
  137. const stat = await fs.stat(compFilename);
  138. wState.set({progress: 100});
  139. //finish
  140. const finishFilename = path.basename(compFilename);
  141. const result = {path: `/tmp/${finishFilename}`, size: stat.size};
  142. if (downloadSize >= 0)
  143. result.downloadSize = downloadSize;
  144. wState.finish(result);
  145. //асинхронно через 30 сек добавим в очередь на отправку
  146. //т.к. gzipFileIfNotExists может переупаковать файл
  147. (async() => {
  148. await utils.sleep(30*1000);
  149. this.pushRemoteSend(compFilename, '/tmp');
  150. })();
  151. } catch (e) {
  152. log(LM_ERR, `url: ${url}, downloadedFilename: ${downloadedFilename}`);
  153. log(LM_ERR, e.stack);
  154. let mes = e.message.split('|FORLOG|');
  155. if (mes[1])
  156. log(LM_ERR, mes[0] + mes[1]);
  157. mes = mes[0];
  158. if (mes == 'abort')
  159. mes = overLoadMes;
  160. if (mes.indexOf('ENOTDIR') >= 0)
  161. mes = fileNotFoundMes;
  162. wState.set({state: 'error', error: mes});
  163. } finally {
  164. //clean
  165. try {
  166. if (q)
  167. q.ret();
  168. if (decompDir)
  169. await fs.remove(decompDir);
  170. if (downloadedFilename && !isUploaded)
  171. await fs.remove(downloadedFilename);
  172. if (convertFilename)
  173. await fs.remove(convertFilename);
  174. } catch (e) {
  175. log(LM_ERR, `Remove error: ${e.stack}`);
  176. }
  177. }
  178. }
  179. loadBookUrl(opts) {
  180. const workerId = this.workerState.generateWorkerId();
  181. const wState = this.workerState.getControl(workerId);
  182. wState.set({state: 'start'});
  183. this.loadBook(opts, wState);
  184. return workerId;
  185. }
  186. async saveFile(file) {
  187. const hash = await utils.getFileHash(file.path, 'sha256', 'hex');
  188. const outFilename = `${this.config.uploadPublicDir}/${hash}`;
  189. if (!await fs.pathExists(outFilename)) {
  190. await fs.move(file.path, outFilename);
  191. this.pushRemoteSend(outFilename, '/upload');
  192. } else {
  193. await utils.touchFile(outFilename);
  194. await fs.remove(file.path);
  195. }
  196. return `disk://${hash}`;
  197. }
  198. async saveFileBuf(buf) {
  199. const hash = await utils.getBufHash(buf, 'sha256', 'hex');
  200. const outFilename = `${this.config.uploadPublicDir}/${hash}`;
  201. if (!await fs.pathExists(outFilename)) {
  202. await fs.writeFile(outFilename, buf);
  203. this.pushRemoteSend(outFilename, '/upload');
  204. } else {
  205. await utils.touchFile(outFilename);
  206. }
  207. return `disk://${hash}`;
  208. }
  209. async uploadFileTouch(url) {
  210. const outFilename = `${this.config.uploadPublicDir}/${url.replace('disk://', '')}`;
  211. await utils.touchFile(outFilename);
  212. return url;
  213. }
  214. async restoreRemoteFile(filename, remoteDir) {
  215. let targetDir = '';
  216. if (this.dirConfig[remoteDir])
  217. targetDir = this.dirConfig[remoteDir].dir;
  218. else
  219. throw new Error(`restoreRemoteFile: unknown remoteDir value (${remoteDir})`);
  220. const basename = path.basename(filename);
  221. const targetName = `${targetDir}/${basename}`;
  222. if (!await fs.pathExists(targetName)) {
  223. let found = false;
  224. if (this.remoteStorage) {
  225. found = await this.remoteStorage.getFileSuccess(targetName, remoteDir);
  226. }
  227. if (!found) {
  228. throw new Error('404 Файл не найден');
  229. }
  230. }
  231. return targetName;
  232. }
  233. pushRemoteSend(fileName, remoteDir) {
  234. if (this.remoteStorage
  235. && this.dirConfig[remoteDir]
  236. && this.dirConfig[remoteDir].moveToRemote) {
  237. this.remoteFilesToSend.push({fileName, remoteDir});
  238. }
  239. }
  240. async remoteSendFile(sendFileRec) {
  241. const {fileName, remoteDir} = sendFileRec;
  242. const sent = this.remoteSent;
  243. if (!fileName || sent[fileName])
  244. return;
  245. log(`remoteSendFile ${remoteDir}/${path.basename(fileName)}`);
  246. //отправляем в remoteStorage
  247. await this.remoteStorage.putFile(fileName, remoteDir);
  248. sent[fileName] = true;
  249. await this.appDb.insert({table: 'remote_sent', ignore: true, rows: [{id: fileName, remoteDir}]});
  250. }
  251. async remoteSendAll() {
  252. if (!this.remoteStorage)
  253. return;
  254. const newSendQueue = [];
  255. while (this.remoteFilesToSend.length) {
  256. const sendFileRec = this.remoteFilesToSend.shift();
  257. if (sendFileRec.remoteDir
  258. && this.dirConfig[sendFileRec.remoteDir]
  259. && this.dirConfig[sendFileRec.remoteDir].moveToRemote) {
  260. try {
  261. await this.remoteSendFile(sendFileRec);
  262. } catch (e) {
  263. newSendQueue.push(sendFileRec)
  264. log(LM_ERR, e.stack);
  265. }
  266. }
  267. }
  268. this.remoteFilesToSend = newSendQueue;
  269. }
  270. async cleanDir(config) {
  271. const {dir, remoteDir, maxSize, moveToRemote} = config;
  272. const sent = this.remoteSent;
  273. const list = await fs.readdir(dir);
  274. let size = 0;
  275. let files = [];
  276. for (const filename of list) {
  277. const filePath = `${dir}/${filename}`;
  278. const stat = await fs.stat(filePath);
  279. if (!stat.isDirectory()) {
  280. size += stat.size;
  281. files.push({name: filePath, stat});
  282. }
  283. }
  284. log(LM_WARN, `clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files, total size=${size}`);
  285. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  286. //удаленное хранилище
  287. if (moveToRemote && this.remoteStorage) {
  288. const foundFiles = new Set();
  289. for (const file of files) {
  290. foundFiles.add(file.name);
  291. //отсылаем на всякий случай перед удалением, если вдруг remoteSendAll не справился
  292. try {
  293. await this.remoteSendFile({fileName: file.name, remoteDir});
  294. } catch (e) {
  295. log(LM_ERR, e.stack);
  296. }
  297. }
  298. //почистим remoteSent и БД
  299. //несколько неоптимально, таскает все записи из таблицы
  300. const rows = await this.appDb.select({table: 'remote_sent'});
  301. for (const row of rows) {
  302. if ((row.remoteDir === remoteDir && !foundFiles.has(row.id))
  303. || !this.dirConfig[row.remoteDir]) {
  304. delete sent[row.id];
  305. await this.appDb.delete({table: 'remote_sent', where: `@@id(${this.appDb.esc(row.id)})`});
  306. }
  307. }
  308. }
  309. let i = 0;
  310. let j = 0;
  311. while (i < files.length && size > maxSize) {
  312. const file = files[i];
  313. const oldFile = file.name;
  314. //реально удаляем только если сохранили в хранилище или размер dir увеличен в 1.5 раза
  315. if (!(moveToRemote && this.remoteStorage)
  316. || (moveToRemote && this.remoteStorage && sent[oldFile])
  317. || size > maxSize*1.5) {
  318. await fs.remove(oldFile);
  319. j++;
  320. }
  321. size -= file.stat.size;
  322. i++;
  323. }
  324. log(LM_WARN, `removed ${j} files`);
  325. }
  326. async periodicCleanDir() {
  327. try {
  328. if (!this.remoteSent)
  329. this.remoteSent = {};
  330. //инициализация this.remoteSent
  331. if (this.remoteStorage) {
  332. const rows = await this.appDb.select({table: 'remote_sent'});
  333. for (const row of rows) {
  334. this.remoteSent[row.id] = true;
  335. }
  336. }
  337. let lastCleanDirTime = 0;
  338. let lastRemoteSendTime = 0;
  339. while (1) {// eslint-disable-line no-constant-condition
  340. //отсылка в удаленное хранилище
  341. if (Date.now() - lastRemoteSendTime >= remoteSendPeriod) {
  342. try {
  343. await this.remoteSendAll();
  344. } catch(e) {
  345. log(LM_ERR, e.stack);
  346. }
  347. lastRemoteSendTime = Date.now();
  348. }
  349. //чистка папок
  350. if (Date.now() - lastCleanDirTime >= cleanDirPeriod) {
  351. for (const config of Object.values(this.dirConfig)) {
  352. try {
  353. await this.cleanDir(config);
  354. } catch(e) {
  355. log(LM_ERR, e.stack);
  356. }
  357. }
  358. lastCleanDirTime = Date.now();
  359. }
  360. await utils.sleep(60*1000);//интервал проверки 1 минута
  361. }
  362. } catch (e) {
  363. log(LM_FATAL, e.message);
  364. ayncExit.exit(1);
  365. }
  366. }
  367. }
  368. module.exports = ReaderWorker;