WebWorker.js 17 KB

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