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