WebWorker.js 19 KB

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