ReaderWorker.js 16 KB

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