WebWorker.js 16 KB

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