WebWorker.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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, iteration = 0) {
  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. await this.createDb(dbPath);
  136. utils.freeMemory();
  137. }
  138. //загружаем БД
  139. this.setMyState(ssDbLoading);
  140. log('Searcher DB loading');
  141. const db = new JembaDbThread();//в отдельном потоке
  142. await db.lock({
  143. dbPath,
  144. softLock: true,
  145. tableDefaults: {
  146. cacheSize: config.dbCacheSize,
  147. },
  148. });
  149. try {
  150. //открываем таблицы
  151. await db.openAll({exclude: ['author_id', 'series_id', 'title_id', 'book']});
  152. const bookCacheSize = 500;
  153. await db.open({
  154. table: 'book',
  155. cacheSize: (config.lowMemoryMode || config.dbCacheSize > bookCacheSize ? config.dbCacheSize : bookCacheSize)
  156. });
  157. } catch(e) {
  158. log(LM_ERR, `Database error: ${e.message}`);
  159. if (iteration < 1) {
  160. log('Recreating DB');
  161. await this.loadOrCreateDb(true, iteration + 1);
  162. } else
  163. throw e;
  164. return;
  165. }
  166. //поисковый движок
  167. this.dbSearcher = new DbSearcher(config, db);
  168. //stuff
  169. db.wwCache = {};
  170. this.db = db;
  171. this.setMyState(ssNormal);
  172. log('Searcher DB ready');
  173. this.logServerStats();
  174. } catch (e) {
  175. log(LM_FATAL, e.message);
  176. ayncExit.exit(1);
  177. }
  178. }
  179. async recreateDb() {
  180. this.setMyState(ssDbCreating);
  181. if (this.dbSearcher) {
  182. await this.dbSearcher.close();
  183. this.dbSearcher = null;
  184. }
  185. await this.closeDb();
  186. await this.loadOrCreateDb(true);
  187. }
  188. async dbConfig() {
  189. this.checkMyState();
  190. const db = this.db;
  191. if (!db.wwCache.config) {
  192. const rows = await db.select({table: 'config'});
  193. const config = {};
  194. for (const row of rows) {
  195. config[row.id] = row.value;
  196. }
  197. db.wwCache.config = config;
  198. }
  199. return db.wwCache.config;
  200. }
  201. async search(from, query) {
  202. this.checkMyState();
  203. const result = await this.dbSearcher.search(from, query);
  204. const config = await this.dbConfig();
  205. result.inpxHash = (config.inpxHash ? config.inpxHash : '');
  206. return result;
  207. }
  208. async getAuthorBookList(authorId) {
  209. this.checkMyState();
  210. return await this.dbSearcher.getAuthorBookList(authorId);
  211. }
  212. async getSeriesBookList(series) {
  213. this.checkMyState();
  214. return await this.dbSearcher.getSeriesBookList(series);
  215. }
  216. async getGenreTree() {
  217. this.checkMyState();
  218. const config = await this.dbConfig();
  219. let result;
  220. const db = this.db;
  221. if (!db.wwCache.genres) {
  222. const genres = _.cloneDeep(genreTree);
  223. const last = genres[genres.length - 1];
  224. const genreValues = new Set();
  225. for (const section of genres) {
  226. for (const g of section.value)
  227. genreValues.add(g.value);
  228. }
  229. //добавим к жанрам те, что нашлись при парсинге
  230. const genreParsed = new Set();
  231. let rows = await db.select({table: 'genre', map: `(r) => ({value: r.value})`});
  232. for (const row of rows) {
  233. genreParsed.add(row.value);
  234. if (!genreValues.has(row.value))
  235. last.value.push({name: row.value, value: row.value});
  236. }
  237. //уберем те, которые не нашлись при парсинге
  238. for (let j = 0; j < genres.length; j++) {
  239. const section = genres[j];
  240. for (let i = 0; i < section.value.length; i++) {
  241. const g = section.value[i];
  242. if (!genreParsed.has(g.value))
  243. section.value.splice(i--, 1);
  244. }
  245. if (!section.value.length)
  246. genres.splice(j--, 1);
  247. }
  248. // langs
  249. rows = await db.select({table: 'lang', map: `(r) => ({value: r.value})`});
  250. const langs = rows.map(r => r.value);
  251. result = {
  252. genreTree: genres,
  253. langList: langs,
  254. inpxHash: (config.inpxHash ? config.inpxHash : ''),
  255. };
  256. db.wwCache.genres = result;
  257. } else {
  258. result = db.wwCache.genres;
  259. }
  260. return result;
  261. }
  262. async extractBook(bookPath) {
  263. const outFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
  264. const folder = `${this.config.libDir}/${path.dirname(bookPath)}`;
  265. const file = path.basename(bookPath);
  266. const zipReader = new ZipReader();
  267. await zipReader.open(folder);
  268. try {
  269. await zipReader.extractToFile(file, outFile);
  270. return outFile;
  271. } finally {
  272. await zipReader.close();
  273. }
  274. }
  275. async restoreBook(bookPath, downFileName) {
  276. const db = this.db;
  277. let extractedFile = '';
  278. let hash = '';
  279. if (!this.remoteLib) {
  280. extractedFile = await this.extractBook(bookPath);
  281. hash = await utils.getFileHash(extractedFile, 'sha256', 'hex');
  282. } else {
  283. hash = await this.remoteLib.downloadBook(bookPath, downFileName);
  284. }
  285. const link = `${this.config.filesPathStatic}/${hash}`;
  286. const bookFile = `${this.config.filesDir}/${hash}`;
  287. const bookFileDesc = `${bookFile}.json`;
  288. if (!await fs.pathExists(bookFile) || !await fs.pathExists(bookFileDesc)) {
  289. await fs.ensureDir(path.dirname(bookFile));
  290. const tmpFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
  291. await utils.gzipFile(extractedFile, tmpFile, 4);
  292. await fs.remove(extractedFile);
  293. await fs.move(tmpFile, bookFile, {overwrite: true});
  294. await fs.writeFile(bookFileDesc, JSON.stringify({bookPath, downFileName}));
  295. } else {
  296. if (extractedFile)
  297. await fs.remove(extractedFile);
  298. await utils.touchFile(bookFile);
  299. await utils.touchFile(bookFileDesc);
  300. }
  301. await db.insert({
  302. table: 'file_hash',
  303. replace: true,
  304. rows: [
  305. {id: bookPath, hash},
  306. {id: hash, bookPath, downFileName}
  307. ]
  308. });
  309. return link;
  310. }
  311. async getBookLink(params) {
  312. this.checkMyState();
  313. const {bookPath, downFileName} = params;
  314. try {
  315. const db = this.db;
  316. let link = '';
  317. //найдем хеш
  318. const rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(bookPath)})`});
  319. if (rows.length) {//хеш найден по bookPath
  320. const hash = rows[0].hash;
  321. const bookFileDesc = `${this.config.filesDir}/${hash}.json`;
  322. if (await fs.pathExists(bookFileDesc)) {
  323. link = `${this.config.filesPathStatic}/${hash}`;
  324. }
  325. }
  326. if (!link) {
  327. link = await this.restoreBook(bookPath, downFileName)
  328. }
  329. if (!link)
  330. throw new Error('404 Файл не найден');
  331. return {link};
  332. } catch(e) {
  333. log(LM_ERR, `getBookLink error: ${e.message}`);
  334. if (e.message.indexOf('ENOENT') >= 0)
  335. throw new Error('404 Файл не найден');
  336. throw e;
  337. }
  338. }
  339. /*
  340. async restoreBookFile(publicPath) {
  341. this.checkMyState();
  342. try {
  343. const db = this.db;
  344. const hash = path.basename(publicPath);
  345. //найдем bookPath и downFileName
  346. const rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(hash)})`});
  347. if (rows.length) {//нашли по хешу
  348. const rec = rows[0];
  349. await this.restoreBook(rec.bookPath, rec.downFileName);
  350. return rec.downFileName;
  351. } else {//bookPath не найден
  352. throw new Error('404 Файл не найден');
  353. }
  354. } catch(e) {
  355. log(LM_ERR, `restoreBookFile error: ${e.message}`);
  356. if (e.message.indexOf('ENOENT') >= 0)
  357. throw new Error('404 Файл не найден');
  358. throw e;
  359. }
  360. }
  361. async getDownFileName(publicPath) {
  362. this.checkMyState();
  363. const db = this.db;
  364. const hash = path.basename(publicPath);
  365. //найдем downFileName
  366. const rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(hash)})`});
  367. if (rows.length) {//downFileName найден по хешу
  368. return rows[0].downFileName;
  369. } else {//bookPath не найден
  370. throw new Error('404 Файл не найден');
  371. }
  372. }
  373. */
  374. async getInpxFile(params) {
  375. let data = null;
  376. if (params.inpxFileHash && this.inpxFileHash && params.inpxFileHash === this.inpxFileHash) {
  377. data = false;
  378. }
  379. if (data === null)
  380. data = await fs.readFile(this.config.inpxFile, 'base64');
  381. return {data};
  382. }
  383. logServerStats() {
  384. try {
  385. const memUsage = process.memoryUsage().rss/(1024*1024);//Mb
  386. let loadAvg = os.loadavg();
  387. loadAvg = loadAvg.map(v => v.toFixed(2));
  388. log(`Server info [ memUsage: ${memUsage.toFixed(2)}MB, loadAvg: (${loadAvg.join(', ')}) ]`);
  389. if (this.config.server.ready)
  390. log(`Server accessible at http://127.0.0.1:${this.config.server.port} (listening on ${this.config.server.host}:${this.config.server.port})`);
  391. } catch (e) {
  392. log(LM_ERR, e.message);
  393. }
  394. }
  395. async periodicLogServerStats() {
  396. while (1) {// eslint-disable-line
  397. this.logServerStats();
  398. await utils.sleep(60*1000);
  399. }
  400. }
  401. async cleanDir(config) {
  402. const {dir, maxSize} = config;
  403. const list = await fs.readdir(dir);
  404. let size = 0;
  405. let files = [];
  406. //формируем список
  407. for (const filename of list) {
  408. const filePath = `${dir}/${filename}`;
  409. const stat = await fs.stat(filePath);
  410. if (!stat.isDirectory()) {
  411. size += stat.size;
  412. files.push({name: filePath, stat});
  413. }
  414. }
  415. log(LM_WARN, `clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files, total size=${size}`);
  416. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  417. let i = 0;
  418. //удаляем
  419. while (i < files.length && size > maxSize) {
  420. const file = files[i];
  421. const oldFile = file.name;
  422. await fs.remove(oldFile);
  423. size -= file.stat.size;
  424. i++;
  425. }
  426. log(LM_WARN, `removed ${i} files`);
  427. }
  428. async periodicCleanDir(dirConfig) {
  429. try {
  430. for (const config of dirConfig)
  431. await fs.ensureDir(config.dir);
  432. let lastCleanDirTime = 0;
  433. while (1) {// eslint-disable-line no-constant-condition
  434. //чистка папок
  435. if (Date.now() - lastCleanDirTime >= cleanDirPeriod) {
  436. for (const config of dirConfig) {
  437. try {
  438. await this.cleanDir(config);
  439. } catch(e) {
  440. log(LM_ERR, e.stack);
  441. }
  442. }
  443. lastCleanDirTime = Date.now();
  444. }
  445. await utils.sleep(60*1000);//интервал проверки 1 минута
  446. }
  447. } catch (e) {
  448. log(LM_FATAL, e.message);
  449. ayncExit.exit(1);
  450. }
  451. }
  452. async periodicCheckInpx() {
  453. const inpxCheckInterval = this.config.inpxCheckInterval;
  454. if (!inpxCheckInterval)
  455. return;
  456. while (1) {// eslint-disable-line no-constant-condition
  457. try {
  458. while (this.myState != ssNormal)
  459. await utils.sleep(1000);
  460. if (this.remoteLib) {
  461. await this.remoteLib.downloadInpxFile();
  462. }
  463. const newInpxHash = await this.inpxHashCreator.getHash();
  464. const dbConfig = await this.dbConfig();
  465. const currentInpxHash = (dbConfig.inpxHash ? dbConfig.inpxHash : '');
  466. if (newInpxHash !== currentInpxHash) {
  467. log('inpx file: changes found, recreating DB');
  468. await this.recreateDb();
  469. } else {
  470. log('inpx file: no changes');
  471. }
  472. } catch(e) {
  473. log(LM_ERR, `periodicCheckInpx: ${e.message}`);
  474. }
  475. await utils.sleep(inpxCheckInterval*60*1000);
  476. }
  477. }
  478. }
  479. module.exports = WebWorker;