WebWorker.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. const os = require('os');
  2. const path = require('path');
  3. const fs = require('fs-extra');
  4. const zlib = require('zlib');
  5. const _ = require('lodash');
  6. const ZipReader = require('./ZipReader');
  7. const WorkerState = require('./WorkerState');//singleton
  8. const { JembaDbThread } = require('jembadb');
  9. const DbCreator = require('./DbCreator');
  10. const DbSearcher = require('./DbSearcher');
  11. const InpxHashCreator = require('./InpxHashCreator');
  12. const RemoteLib = require('./RemoteLib');//singleton
  13. const ayncExit = new (require('./AsyncExit'))();
  14. const log = new (require('./AppLogger'))().log;//singleton
  15. const utils = require('./utils');
  16. const genreTree = require('./genres');
  17. //server states
  18. const ssNormal = 'normal';
  19. const ssDbLoading = 'db_loading';
  20. const ssDbCreating = 'db_creating';
  21. const stateToText = {
  22. [ssNormal]: '',
  23. [ssDbLoading]: 'Загрузка поисковой базы',
  24. [ssDbCreating]: 'Создание поисковой базы',
  25. };
  26. const cleanDirPeriod = 60*60*1000;//каждый час
  27. //singleton
  28. let instance = null;
  29. class WebWorker {
  30. constructor(config) {
  31. if (!instance) {
  32. this.config = config;
  33. this.workerState = new WorkerState();
  34. this.remoteLib = null;
  35. if (config.remoteLib) {
  36. this.remoteLib = new RemoteLib(config);
  37. }
  38. this.wState = this.workerState.getControl('server_state');
  39. this.myState = '';
  40. this.db = null;
  41. this.dbSearcher = null;
  42. ayncExit.add(this.closeDb.bind(this));
  43. this.loadOrCreateDb();//no await
  44. this.logServerStats();//no await
  45. const dirConfig = [
  46. {
  47. dir: `${this.config.publicDir}/files`,
  48. maxSize: this.config.maxFilesDirSize,
  49. },
  50. ];
  51. this.periodicCleanDir(dirConfig);//no await
  52. this.periodicCheckInpx();//no await
  53. instance = this;
  54. }
  55. return instance;
  56. }
  57. checkMyState() {
  58. if (this.myState != ssNormal)
  59. throw new Error('server_busy');
  60. }
  61. setMyState(newState, workerState = {}) {
  62. this.myState = newState;
  63. this.wState.set(Object.assign({}, workerState, {
  64. state: newState,
  65. serverMessage: stateToText[newState]
  66. }));
  67. }
  68. async closeDb() {
  69. if (this.db) {
  70. await this.db.unlock();
  71. this.db = null;
  72. }
  73. }
  74. async createDb(dbPath) {
  75. this.setMyState(ssDbCreating);
  76. log('Searcher DB create start');
  77. const config = this.config;
  78. if (await fs.pathExists(dbPath))
  79. throw new Error(`createDb.pathExists: ${dbPath}`);
  80. const db = new JembaDbThread();
  81. await db.lock({
  82. dbPath,
  83. create: true,
  84. softLock: true,
  85. tableDefaults: {
  86. cacheSize: 5,
  87. },
  88. });
  89. try {
  90. const dbCreator = new DbCreator(config);
  91. await dbCreator.run(db, (state) => {
  92. this.setMyState(ssDbCreating, state);
  93. if (state.fileName)
  94. log(` load ${state.fileName}`);
  95. if (state.recsLoaded)
  96. log(` processed ${state.recsLoaded} records`);
  97. if (state.job)
  98. log(` ${state.job}`);
  99. });
  100. log('Searcher DB successfully created');
  101. } finally {
  102. await db.unlock();
  103. }
  104. }
  105. async loadOrCreateDb(recreate = false) {
  106. this.setMyState(ssDbLoading);
  107. try {
  108. const config = this.config;
  109. const dbPath = `${config.dataDir}/db`;
  110. //пересоздаем БД из INPX если нужно
  111. if (config.recreateDb || recreate)
  112. await fs.remove(dbPath);
  113. if (!await fs.pathExists(dbPath)) {
  114. await this.createDb(dbPath);
  115. utils.freeMemory();
  116. }
  117. //загружаем БД
  118. this.setMyState(ssDbLoading);
  119. log('Searcher DB loading');
  120. const db = new JembaDbThread();
  121. await db.lock({
  122. dbPath,
  123. softLock: true,
  124. tableDefaults: {
  125. cacheSize: 5,
  126. },
  127. });
  128. //открываем все таблицы
  129. await db.openAll();
  130. this.dbSearcher = new DbSearcher(config, db);
  131. db.wwCache = {};
  132. this.db = db;
  133. log('Searcher DB ready');
  134. } catch (e) {
  135. log(LM_FATAL, e.message);
  136. ayncExit.exit(1);
  137. } finally {
  138. this.setMyState(ssNormal);
  139. }
  140. }
  141. async recreateDb() {
  142. this.setMyState(ssDbCreating);
  143. if (this.dbSearcher) {
  144. await this.dbSearcher.close();
  145. this.dbSearcher = null;
  146. }
  147. await this.closeDb();
  148. await this.loadOrCreateDb(true);
  149. }
  150. async dbConfig() {
  151. this.checkMyState();
  152. const db = this.db;
  153. if (!db.wwCache.config) {
  154. const rows = await db.select({table: 'config'});
  155. const config = {};
  156. for (const row of rows) {
  157. config[row.id] = row.value;
  158. }
  159. db.wwCache.config = config;
  160. }
  161. return db.wwCache.config;
  162. }
  163. async search(query) {
  164. this.checkMyState();
  165. const config = await this.dbConfig();
  166. const result = await this.dbSearcher.search(query);
  167. return {
  168. author: result.result,
  169. totalFound: result.totalFound,
  170. inpxHash: (config.inpxHash ? config.inpxHash : ''),
  171. };
  172. }
  173. async getBookList(authorId) {
  174. this.checkMyState();
  175. return await this.dbSearcher.getBookList(authorId);
  176. }
  177. async getSeriesBookList(seriesId) {
  178. this.checkMyState();
  179. return await this.dbSearcher.getSeriesBookList(seriesId);
  180. }
  181. async getGenreTree() {
  182. this.checkMyState();
  183. const config = await this.dbConfig();
  184. let result;
  185. const db = this.db;
  186. if (!db.wwCache.genres) {
  187. const genres = _.cloneDeep(genreTree);
  188. const last = genres[genres.length - 1];
  189. const genreValues = new Set();
  190. for (const section of genres) {
  191. for (const g of section.value)
  192. genreValues.add(g.value);
  193. }
  194. //добавим к жанрам те, что нашлись при парсинге
  195. const genreParsed = new Set();
  196. let rows = await db.select({table: 'genre', map: `(r) => ({value: r.value})`});
  197. for (const row of rows) {
  198. genreParsed.add(row.value);
  199. if (!genreValues.has(row.value))
  200. last.value.push({name: row.value, value: row.value});
  201. }
  202. //уберем те, которые не нашлись при парсинге
  203. for (let j = 0; j < genres.length; j++) {
  204. const section = genres[j];
  205. for (let i = 0; i < section.value.length; i++) {
  206. const g = section.value[i];
  207. if (!genreParsed.has(g.value))
  208. section.value.splice(i--, 1);
  209. }
  210. if (!section.value.length)
  211. genres.splice(j--, 1);
  212. }
  213. // langs
  214. rows = await db.select({table: 'lang', map: `(r) => ({value: r.value})`});
  215. const langs = rows.map(r => r.value);
  216. result = {
  217. genreTree: genres,
  218. langList: langs,
  219. inpxHash: (config.inpxHash ? config.inpxHash : ''),
  220. };
  221. db.wwCache.genres = result;
  222. } else {
  223. result = db.wwCache.genres;
  224. }
  225. return result;
  226. }
  227. async extractBook(bookPath) {
  228. const outFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
  229. const folder = `${this.config.libDir}/${path.dirname(bookPath)}`;
  230. const file = path.basename(bookPath);
  231. const zipReader = new ZipReader();
  232. await zipReader.open(folder);
  233. try {
  234. await zipReader.extractToFile(file, outFile);
  235. return outFile;
  236. } finally {
  237. await zipReader.close();
  238. }
  239. }
  240. //async
  241. gzipFile(inputFile, outputFile, level = 1) {
  242. return new Promise((resolve, reject) => {
  243. const gzip = zlib.createGzip({level});
  244. const input = fs.createReadStream(inputFile);
  245. const output = fs.createWriteStream(outputFile);
  246. input.pipe(gzip).pipe(output).on('finish', (err) => {
  247. if (err) reject(err);
  248. else resolve();
  249. });
  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 this.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 logServerStats() {
  348. while (1) {// eslint-disable-line
  349. try {
  350. const memUsage = process.memoryUsage().rss/(1024*1024);//Mb
  351. let loadAvg = os.loadavg();
  352. loadAvg = loadAvg.map(v => v.toFixed(2));
  353. log(`Server info [ memUsage: ${memUsage.toFixed(2)}MB, loadAvg: (${loadAvg.join(', ')}) ]`);
  354. } catch (e) {
  355. log(LM_ERR, e.message);
  356. }
  357. await utils.sleep(60*1000);
  358. }
  359. }
  360. async cleanDir(config) {
  361. const {dir, maxSize} = config;
  362. const list = await fs.readdir(dir);
  363. let size = 0;
  364. let files = [];
  365. //формируем список
  366. for (const filename of list) {
  367. const filePath = `${dir}/${filename}`;
  368. const stat = await fs.stat(filePath);
  369. if (!stat.isDirectory()) {
  370. size += stat.size;
  371. files.push({name: filePath, stat});
  372. }
  373. }
  374. log(LM_WARN, `clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files, total size=${size}`);
  375. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  376. let i = 0;
  377. //удаляем
  378. while (i < files.length && size > maxSize) {
  379. const file = files[i];
  380. const oldFile = file.name;
  381. await fs.remove(oldFile);
  382. size -= file.stat.size;
  383. i++;
  384. }
  385. log(LM_WARN, `removed ${i} files`);
  386. }
  387. async periodicCleanDir(dirConfig) {
  388. try {
  389. for (const config of dirConfig)
  390. await fs.ensureDir(config.dir);
  391. let lastCleanDirTime = 0;
  392. while (1) {// eslint-disable-line no-constant-condition
  393. //чистка папок
  394. if (Date.now() - lastCleanDirTime >= cleanDirPeriod) {
  395. for (const config of dirConfig) {
  396. try {
  397. await this.cleanDir(config);
  398. } catch(e) {
  399. log(LM_ERR, e.stack);
  400. }
  401. }
  402. lastCleanDirTime = Date.now();
  403. }
  404. await utils.sleep(60*1000);//интервал проверки 1 минута
  405. }
  406. } catch (e) {
  407. log(LM_FATAL, e.message);
  408. ayncExit.exit(1);
  409. }
  410. }
  411. async periodicCheckInpx() {
  412. const inpxCheckInterval = this.config.inpxCheckInterval;
  413. if (!inpxCheckInterval)
  414. return;
  415. const inpxHashCreator = new InpxHashCreator(this.config);
  416. while (1) {// eslint-disable-line no-constant-condition
  417. try {
  418. while (this.myState != ssNormal)
  419. await utils.sleep(1000);
  420. if (this.remoteLib) {
  421. await this.remoteLib.downloadInpxFile(60*1000);
  422. }
  423. const newInpxHash = await inpxHashCreator.getHash();
  424. const dbConfig = await this.dbConfig();
  425. const currentInpxHash = (dbConfig.inpxHash ? dbConfig.inpxHash : '');
  426. if (newInpxHash !== currentInpxHash) {
  427. log('inpx file: changes found, recreating DB');
  428. await this.recreateDb();
  429. } else {
  430. log('inpx file: no changes');
  431. }
  432. } catch(e) {
  433. log(LM_ERR, `periodicCheckInpx: ${e.message}`);
  434. }
  435. await utils.sleep(inpxCheckInterval*60*1000);
  436. }
  437. }
  438. }
  439. module.exports = WebWorker;