WebWorker.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. const os = require('os');
  2. const path = require('path');
  3. const fs = require('fs-extra');
  4. const _ = require('lodash');
  5. const ZipReader = require('./ZipReader');
  6. const WorkerState = require('./WorkerState');//singleton
  7. const { JembaDb, JembaDbThread } = require('jembadb');
  8. const DbCreator = require('./DbCreator');
  9. const DbSearcher = require('./DbSearcher');
  10. const InpxHashCreator = require('./InpxHashCreator');
  11. const RemoteLib = require('./RemoteLib');//singleton
  12. const ayncExit = new (require('./AsyncExit'))();
  13. const log = new (require('./AppLogger'))().log;//singleton
  14. const utils = require('./utils');
  15. const genreTree = require('./genres');
  16. const Fb2Parser = require('./xml/Fb2Parser');
  17. //server states
  18. const ssNormal = 'normal';
  19. const ssDbLoading = 'db_loading';
  20. const ssDbCreating = 'db_creating';
  21. const stateToText = {
  22. [ssNormal]: '',
  23. [ssDbLoading]: 'Загрузка поисковой базы',
  24. [ssDbCreating]: 'Создание поисковой базы',
  25. };
  26. const cleanDirPeriod = 60*60*1000;//каждый час
  27. //singleton
  28. let instance = null;
  29. class WebWorker {
  30. constructor(config) {
  31. if (!instance) {
  32. this.config = config;
  33. this.workerState = new WorkerState();
  34. this.remoteLib = null;
  35. if (config.remoteLib) {
  36. this.remoteLib = new RemoteLib(config);
  37. }
  38. this.inpxHashCreator = new InpxHashCreator(config);
  39. this.fb2Parser = new Fb2Parser();
  40. this.inpxFileHash = '';
  41. this.wState = this.workerState.getControl('server_state');
  42. this.myState = '';
  43. this.db = null;
  44. this.dbSearcher = null;
  45. ayncExit.add(this.closeDb.bind(this));
  46. this.loadOrCreateDb();//no await
  47. this.periodicLogServerStats();//no await
  48. const dirConfig = [
  49. {
  50. dir: config.filesDir,
  51. maxSize: config.maxFilesDirSize,
  52. },
  53. ];
  54. this.periodicCleanDir(dirConfig);//no await
  55. this.periodicCheckInpx();//no await
  56. instance = this;
  57. }
  58. return instance;
  59. }
  60. checkMyState() {
  61. if (this.myState != ssNormal)
  62. throw new Error('server_busy');
  63. }
  64. setMyState(newState, workerState = {}) {
  65. this.myState = newState;
  66. this.wState.set(Object.assign({}, workerState, {
  67. state: newState,
  68. serverMessage: stateToText[newState]
  69. }));
  70. }
  71. async closeDb() {
  72. if (this.db) {
  73. await this.db.unlock();
  74. this.db = null;
  75. }
  76. }
  77. async createDb(dbPath) {
  78. this.setMyState(ssDbCreating);
  79. log('Searcher DB create start');
  80. const config = this.config;
  81. if (await fs.pathExists(dbPath))
  82. throw new Error(`createDb.pathExists: ${dbPath}`);
  83. const db = new JembaDbThread();
  84. await db.lock({
  85. dbPath,
  86. create: true,
  87. softLock: true,
  88. tableDefaults: {
  89. cacheSize: config.dbCacheSize,
  90. },
  91. });
  92. try {
  93. const dbCreator = new DbCreator(config);
  94. await dbCreator.run(db, (state) => {
  95. this.setMyState(ssDbCreating, state);
  96. if (state.fileName)
  97. log(` load ${state.fileName}`);
  98. if (state.recsLoaded)
  99. log(` processed ${state.recsLoaded} records`);
  100. if (state.job)
  101. log(` ${state.job}`);
  102. });
  103. log('Searcher DB successfully created');
  104. } finally {
  105. await db.unlock();
  106. }
  107. }
  108. async loadOrCreateDb(recreate = false, iteration = 0) {
  109. this.setMyState(ssDbLoading);
  110. try {
  111. const config = this.config;
  112. const dbPath = `${config.dataDir}/db`;
  113. this.inpxFileHash = await this.inpxHashCreator.getInpxFileHash();
  114. //проверим полный InxpHash (включая фильтр и версию БД)
  115. //для этого заглянем в конфиг внутри БД, если он есть
  116. if (!(config.recreateDb || recreate) && await fs.pathExists(dbPath)) {
  117. const newInpxHash = await this.inpxHashCreator.getHash();
  118. const tmpDb = new JembaDb();
  119. await tmpDb.lock({dbPath, softLock: true});
  120. try {
  121. await tmpDb.open({table: 'config'});
  122. const rows = await tmpDb.select({table: 'config', where: `@@id('inpxHash')`});
  123. if (!rows.length || newInpxHash !== rows[0].value)
  124. throw new Error('inpx file: changes found on start, recreating DB');
  125. } catch (e) {
  126. log(LM_WARN, e.message);
  127. recreate = true;
  128. } finally {
  129. await tmpDb.unlock();
  130. }
  131. }
  132. //удалим БД если нужно
  133. if (config.recreateDb || recreate)
  134. await fs.remove(dbPath);
  135. //пересоздаем БД из INPX если нужно
  136. if (!await fs.pathExists(dbPath)) {
  137. await this.createDb(dbPath);
  138. utils.freeMemory();
  139. }
  140. //загружаем БД
  141. this.setMyState(ssDbLoading);
  142. log('Searcher DB loading');
  143. const db = new JembaDbThread();//в отдельном потоке
  144. await db.lock({
  145. dbPath,
  146. softLock: true,
  147. tableDefaults: {
  148. cacheSize: config.dbCacheSize,
  149. },
  150. });
  151. try {
  152. //открываем таблицы
  153. await db.openAll({exclude: ['author_id', 'series_id', 'title_id', 'book']});
  154. const bookCacheSize = 500;
  155. await db.open({
  156. table: 'book',
  157. cacheSize: (config.lowMemoryMode || config.dbCacheSize > bookCacheSize ? config.dbCacheSize : bookCacheSize)
  158. });
  159. } catch(e) {
  160. log(LM_ERR, `Database error: ${e.message}`);
  161. if (iteration < 1) {
  162. log('Recreating DB');
  163. await this.loadOrCreateDb(true, iteration + 1);
  164. } else
  165. throw e;
  166. return;
  167. }
  168. //поисковый движок
  169. this.dbSearcher = new DbSearcher(config, db);
  170. //stuff
  171. db.wwCache = {};
  172. this.db = db;
  173. this.setMyState(ssNormal);
  174. log('Searcher DB ready');
  175. this.logServerStats();
  176. } catch (e) {
  177. log(LM_FATAL, e.message);
  178. ayncExit.exit(1);
  179. }
  180. }
  181. async recreateDb() {
  182. this.setMyState(ssDbCreating);
  183. if (this.dbSearcher) {
  184. await this.dbSearcher.close();
  185. this.dbSearcher = null;
  186. }
  187. await this.closeDb();
  188. await this.loadOrCreateDb(true);
  189. }
  190. async dbConfig() {
  191. this.checkMyState();
  192. const db = this.db;
  193. if (!db.wwCache.config) {
  194. const rows = await db.select({table: 'config'});
  195. const config = {};
  196. for (const row of rows) {
  197. config[row.id] = row.value;
  198. }
  199. db.wwCache.config = config;
  200. }
  201. return db.wwCache.config;
  202. }
  203. async search(from, query) {
  204. this.checkMyState();
  205. const result = await this.dbSearcher.search(from, query);
  206. const config = await this.dbConfig();
  207. result.inpxHash = (config.inpxHash ? config.inpxHash : '');
  208. return result;
  209. }
  210. async getAuthorBookList(authorId) {
  211. this.checkMyState();
  212. return await this.dbSearcher.getAuthorBookList(authorId);
  213. }
  214. async getSeriesBookList(series) {
  215. this.checkMyState();
  216. return await this.dbSearcher.getSeriesBookList(series);
  217. }
  218. async getGenreTree() {
  219. this.checkMyState();
  220. const config = await this.dbConfig();
  221. let result;
  222. const db = this.db;
  223. if (!db.wwCache.genres) {
  224. const genres = _.cloneDeep(genreTree);
  225. const last = genres[genres.length - 1];
  226. const genreValues = new Set();
  227. for (const section of genres) {
  228. for (const g of section.value)
  229. genreValues.add(g.value);
  230. }
  231. //добавим к жанрам те, что нашлись при парсинге
  232. const genreParsed = new Set();
  233. let rows = await db.select({table: 'genre', map: `(r) => ({value: r.value})`});
  234. for (const row of rows) {
  235. genreParsed.add(row.value);
  236. if (!genreValues.has(row.value))
  237. last.value.push({name: row.value, value: row.value});
  238. }
  239. //уберем те, которые не нашлись при парсинге
  240. for (let j = 0; j < genres.length; j++) {
  241. const section = genres[j];
  242. for (let i = 0; i < section.value.length; i++) {
  243. const g = section.value[i];
  244. if (!genreParsed.has(g.value))
  245. section.value.splice(i--, 1);
  246. }
  247. if (!section.value.length)
  248. genres.splice(j--, 1);
  249. }
  250. // langs
  251. rows = await db.select({table: 'lang', map: `(r) => ({value: r.value})`});
  252. const langs = rows.map(r => r.value);
  253. result = {
  254. genreTree: genres,
  255. langList: langs,
  256. inpxHash: (config.inpxHash ? config.inpxHash : ''),
  257. };
  258. db.wwCache.genres = result;
  259. } else {
  260. result = db.wwCache.genres;
  261. }
  262. return result;
  263. }
  264. async extractBook(bookPath) {
  265. const outFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
  266. const folder = `${this.config.libDir}/${path.dirname(bookPath)}`;
  267. const file = path.basename(bookPath);
  268. const zipReader = new ZipReader();
  269. await zipReader.open(folder);
  270. try {
  271. await zipReader.extractToFile(file, outFile);
  272. return outFile;
  273. } finally {
  274. await zipReader.close();
  275. }
  276. }
  277. async restoreBook(bookPath, downFileName) {
  278. const db = this.db;
  279. let extractedFile = '';
  280. let hash = '';
  281. if (!this.remoteLib) {
  282. extractedFile = await this.extractBook(bookPath);
  283. hash = await utils.getFileHash(extractedFile, 'sha256', 'hex');
  284. } else {
  285. hash = await this.remoteLib.downloadBook(bookPath, downFileName);
  286. }
  287. const link = `${this.config.filesPathStatic}/${hash}`;
  288. const bookFile = `${this.config.filesDir}/${hash}`;
  289. const bookFileDesc = `${bookFile}.json`;
  290. if (!await fs.pathExists(bookFile) || !await fs.pathExists(bookFileDesc)) {
  291. if (!await fs.pathExists(bookFile) && extractedFile) {
  292. const tmpFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
  293. await utils.gzipFile(extractedFile, tmpFile, 4);
  294. await fs.remove(extractedFile);
  295. await fs.move(tmpFile, bookFile, {overwrite: true});
  296. } else {
  297. await utils.touchFile(bookFile);
  298. }
  299. await fs.writeFile(bookFileDesc, JSON.stringify({bookPath, downFileName}));
  300. } else {
  301. if (extractedFile)
  302. await fs.remove(extractedFile);
  303. await utils.touchFile(bookFile);
  304. await utils.touchFile(bookFileDesc);
  305. }
  306. await db.insert({
  307. table: 'file_hash',
  308. replace: true,
  309. rows: [
  310. {id: bookPath, hash},
  311. {id: hash, bookPath, downFileName}
  312. ]
  313. });
  314. return link;
  315. }
  316. async getBookLink(bookId) {
  317. this.checkMyState();
  318. try {
  319. const db = this.db;
  320. let link = '';
  321. //найдем bookPath и downFileName
  322. let rows = await db.select({table: 'book', where: `@@id(${db.esc(bookId)})`});
  323. if (!rows.length)
  324. throw new Error('404 Файл не найден');
  325. const book = rows[0];
  326. let downFileName = book.file;
  327. const author = book.author.split(',');
  328. const at = [author[0], book.title];
  329. downFileName = utils.makeValidFileNameOrEmpty(at.filter(r => r).join(' - '))
  330. || utils.makeValidFileNameOrEmpty(at[0])
  331. || utils.makeValidFileNameOrEmpty(at[1])
  332. || downFileName;
  333. downFileName = downFileName.substring(0, 100);
  334. const ext = `.${book.ext}`;
  335. if (downFileName.substring(downFileName.length - ext.length) != ext)
  336. downFileName += ext;
  337. const bookPath = `${book.folder}/${book.file}${ext}`;
  338. //найдем хеш
  339. rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(bookPath)})`});
  340. if (rows.length) {//хеш найден по bookPath
  341. const hash = rows[0].hash;
  342. const bookFile = `${this.config.filesDir}/${hash}`;
  343. const bookFileDesc = `${bookFile}.json`;
  344. if (await fs.pathExists(bookFile) && await fs.pathExists(bookFileDesc)) {
  345. link = `${this.config.filesPathStatic}/${hash}`;
  346. }
  347. }
  348. if (!link) {
  349. link = await this.restoreBook(bookPath, downFileName)
  350. }
  351. if (!link)
  352. throw new Error('404 Файл не найден');
  353. return {link, bookPath, downFileName};
  354. } catch(e) {
  355. log(LM_ERR, `getBookLink error: ${e.message}`);
  356. if (e.message.indexOf('ENOENT') >= 0)
  357. throw new Error('404 Файл не найден');
  358. throw e;
  359. }
  360. }
  361. async getBookInfo(bookId) {
  362. this.checkMyState();
  363. try {
  364. const db = this.db;
  365. let bookInfo = await this.getBookLink(bookId);
  366. const hash = path.basename(bookInfo.link);
  367. const bookFile = `${this.config.filesDir}/${hash}`;
  368. const bookFileInfo = `${bookFile}.info`;
  369. if (!await fs.pathExists(bookFileInfo)) {
  370. const rows = await db.select({table: 'book', where: `@@id(${db.esc(bookId)})`});
  371. const book = rows[0];
  372. let fb2 = false;
  373. if (book.ext == 'fb2') {
  374. const parsedFb2 = await this.fb2Parser.getDescAndCover(bookFile);
  375. fb2 = parsedFb2;
  376. }
  377. bookInfo.book = book;
  378. bookInfo.fb2 = fb2;
  379. bookInfo.cover = '';
  380. await fs.writeFile(bookFileInfo, JSON.stringify(bookInfo, null, 2));
  381. } else {
  382. await utils.touchFile(bookFileInfo);
  383. const info = fs.readFile(bookFileInfo, 'utf-8');
  384. bookInfo = JSON.parse(info);
  385. }
  386. return {bookInfo};
  387. } catch(e) {
  388. log(LM_ERR, `getBookInfo error: ${e.message}`);
  389. if (e.message.indexOf('ENOENT') >= 0)
  390. throw new Error('404 Файл не найден');
  391. throw e;
  392. }
  393. }
  394. async getInpxFile(params) {
  395. let data = null;
  396. if (params.inpxFileHash && this.inpxFileHash && params.inpxFileHash === this.inpxFileHash) {
  397. data = false;
  398. }
  399. if (data === null)
  400. data = await fs.readFile(this.config.inpxFile, 'base64');
  401. return {data};
  402. }
  403. logServerStats() {
  404. try {
  405. const memUsage = process.memoryUsage().rss/(1024*1024);//Mb
  406. let loadAvg = os.loadavg();
  407. loadAvg = loadAvg.map(v => v.toFixed(2));
  408. log(`Server info [ memUsage: ${memUsage.toFixed(2)}MB, loadAvg: (${loadAvg.join(', ')}) ]`);
  409. if (this.config.server.ready)
  410. log(`Server accessible at http://127.0.0.1:${this.config.server.port} (listening on ${this.config.server.host}:${this.config.server.port})`);
  411. } catch (e) {
  412. log(LM_ERR, e.message);
  413. }
  414. }
  415. async periodicLogServerStats() {
  416. while (1) {// eslint-disable-line
  417. this.logServerStats();
  418. await utils.sleep(60*1000);
  419. }
  420. }
  421. async cleanDir(config) {
  422. const {dir, maxSize} = config;
  423. const list = await fs.readdir(dir);
  424. let size = 0;
  425. let files = [];
  426. //формируем список
  427. for (const filename of list) {
  428. const filePath = `${dir}/${filename}`;
  429. const stat = await fs.stat(filePath);
  430. if (!stat.isDirectory()) {
  431. size += stat.size;
  432. files.push({name: filePath, stat});
  433. }
  434. }
  435. log(LM_WARN, `clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files, total size=${size}`);
  436. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  437. let i = 0;
  438. //удаляем
  439. while (i < files.length && size > maxSize) {
  440. const file = files[i];
  441. const oldFile = file.name;
  442. await fs.remove(oldFile);
  443. size -= file.stat.size;
  444. i++;
  445. }
  446. log(LM_WARN, `removed ${i} files`);
  447. }
  448. async periodicCleanDir(dirConfig) {
  449. try {
  450. for (const config of dirConfig)
  451. await fs.ensureDir(config.dir);
  452. let lastCleanDirTime = 0;
  453. while (1) {// eslint-disable-line no-constant-condition
  454. //чистка папок
  455. if (Date.now() - lastCleanDirTime >= cleanDirPeriod) {
  456. for (const config of dirConfig) {
  457. try {
  458. await this.cleanDir(config);
  459. } catch(e) {
  460. log(LM_ERR, e.stack);
  461. }
  462. }
  463. lastCleanDirTime = Date.now();
  464. }
  465. await utils.sleep(60*1000);//интервал проверки 1 минута
  466. }
  467. } catch (e) {
  468. log(LM_FATAL, e.message);
  469. ayncExit.exit(1);
  470. }
  471. }
  472. async periodicCheckInpx() {
  473. const inpxCheckInterval = this.config.inpxCheckInterval;
  474. if (!inpxCheckInterval)
  475. return;
  476. while (1) {// eslint-disable-line no-constant-condition
  477. try {
  478. while (this.myState != ssNormal)
  479. await utils.sleep(1000);
  480. if (this.remoteLib) {
  481. await this.remoteLib.downloadInpxFile();
  482. }
  483. const newInpxHash = await this.inpxHashCreator.getHash();
  484. const dbConfig = await this.dbConfig();
  485. const currentInpxHash = (dbConfig.inpxHash ? dbConfig.inpxHash : '');
  486. if (newInpxHash !== currentInpxHash) {
  487. log('inpx file: changes found, recreating DB');
  488. await this.recreateDb();
  489. } else {
  490. log('inpx file: no changes');
  491. }
  492. } catch(e) {
  493. log(LM_ERR, `periodicCheckInpx: ${e.message}`);
  494. }
  495. await utils.sleep(inpxCheckInterval*60*1000);
  496. }
  497. }
  498. }
  499. module.exports = WebWorker;