ReaderWorker.js 16 KB

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