WebWorker.js 17 KB

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