WebWorker.js 16 KB

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