WebWorker.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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');
  8. const { JembaDbThread } = require('jembadb');
  9. const DbCreator = require('./DbCreator');
  10. const DbSearcher = require('./DbSearcher');
  11. const ayncExit = new (require('./AsyncExit'))();
  12. const log = new (require('./AppLogger'))().log;//singleton
  13. const utils = require('./utils');
  14. const genreTree = require('./genres');
  15. //server states
  16. const ssNormal = 'normal';
  17. const ssDbLoading = 'db_loading';
  18. const ssDbCreating = 'db_creating';
  19. const stateToText = {
  20. [ssNormal]: '',
  21. [ssDbLoading]: 'Загрузка поисковой базы',
  22. [ssDbCreating]: 'Создание поисковой базы',
  23. };
  24. const cleanDirPeriod = 60*60*1000;//каждый час
  25. //singleton
  26. let instance = null;
  27. class WebWorker {
  28. constructor(config) {
  29. if (!instance) {
  30. this.config = config;
  31. this.workerState = new WorkerState();
  32. this.wState = this.workerState.getControl('server_state');
  33. this.myState = '';
  34. this.db = null;
  35. this.dbSearcher = null;
  36. ayncExit.add(this.closeDb.bind(this));
  37. this.loadOrCreateDb();//no await
  38. this.logServerStats();//no await
  39. const dirConfig = [
  40. {
  41. dir: `${this.config.publicDir}/files`,
  42. maxSize: this.config.maxFilesDirSize,
  43. },
  44. ];
  45. this.periodicCleanDir(dirConfig);//no await
  46. instance = this;
  47. }
  48. return instance;
  49. }
  50. checkMyState() {
  51. if (this.myState != ssNormal)
  52. throw new Error('server_busy');
  53. }
  54. setMyState(newState, workerState = {}) {
  55. this.myState = newState;
  56. this.wState.set(Object.assign({}, workerState, {
  57. state: newState,
  58. serverMessage: stateToText[newState]
  59. }));
  60. }
  61. async closeDb() {
  62. if (this.db) {
  63. await this.db.unlock();
  64. this.db = null;
  65. }
  66. }
  67. async createDb(dbPath) {
  68. this.setMyState(ssDbCreating);
  69. log('Searcher DB create start');
  70. const config = this.config;
  71. if (await fs.pathExists(dbPath))
  72. throw new Error(`createDb.pathExists: ${dbPath}`);
  73. const db = new JembaDbThread();//создаем не в потоке, чтобы лучше работал GC
  74. await db.lock({
  75. dbPath,
  76. create: true,
  77. softLock: true,
  78. tableDefaults: {
  79. cacheSize: 5,
  80. },
  81. });
  82. try {
  83. const dbCreator = new DbCreator(config);
  84. await dbCreator.run(db, (state) => {
  85. this.setMyState(ssDbCreating, state);
  86. if (state.fileName)
  87. log(` load ${state.fileName}`);
  88. if (state.recsLoaded)
  89. log(` processed ${state.recsLoaded} records`);
  90. if (state.job)
  91. log(` ${state.job}`);
  92. });
  93. log('Searcher DB successfully created');
  94. } finally {
  95. await db.unlock();
  96. }
  97. }
  98. async loadOrCreateDb(recreate = false) {
  99. this.setMyState(ssDbLoading);
  100. try {
  101. const config = this.config;
  102. const dbPath = `${config.dataDir}/db`;
  103. //пересоздаем БД из INPX если нужно
  104. if (config.recreateDb || recreate)
  105. await fs.remove(dbPath);
  106. if (!await fs.pathExists(dbPath)) {
  107. await this.createDb(dbPath);
  108. utils.freeMemory();
  109. }
  110. //загружаем БД
  111. this.setMyState(ssDbLoading);
  112. log('Searcher DB loading');
  113. const db = new JembaDbThread();
  114. await db.lock({
  115. dbPath,
  116. softLock: true,
  117. tableDefaults: {
  118. cacheSize: 5,
  119. },
  120. });
  121. //открываем все таблицы
  122. await db.openAll();
  123. this.dbSearcher = new DbSearcher(config, db);
  124. db.wwCache = {};
  125. this.db = db;
  126. log('Searcher DB ready');
  127. } catch (e) {
  128. log(LM_FATAL, e.message);
  129. ayncExit.exit(1);
  130. } finally {
  131. this.setMyState(ssNormal);
  132. }
  133. }
  134. async recreateDb() {
  135. this.setMyState(ssDbCreating);
  136. if (this.dbSearcher) {
  137. await this.dbSearcher.close();
  138. this.dbSearcher = null;
  139. }
  140. await this.closeDb();
  141. await this.loadOrCreateDb(true);
  142. }
  143. async dbConfig() {
  144. this.checkMyState();
  145. const db = this.db;
  146. if (!db.wwCache.config) {
  147. const rows = await db.select({table: 'config'});
  148. const config = {};
  149. for (const row of rows) {
  150. config[row.id] = row.value;
  151. }
  152. db.wwCache.config = config;
  153. }
  154. return db.wwCache.config;
  155. }
  156. async search(query) {
  157. this.checkMyState();
  158. const config = await this.dbConfig();
  159. const result = await this.dbSearcher.search(query);
  160. return {
  161. author: result.result,
  162. totalFound: result.totalFound,
  163. inpxHash: (config.inpxHash ? config.inpxHash : ''),
  164. };
  165. }
  166. async getBookList(authorId) {
  167. this.checkMyState();
  168. return await this.dbSearcher.getBookList(authorId);
  169. }
  170. async getGenreTree() {
  171. this.checkMyState();
  172. const config = await this.dbConfig();
  173. let result;
  174. const db = this.db;
  175. if (!db.wwCache.genres) {
  176. const genres = _.cloneDeep(genreTree);
  177. const last = genres[genres.length - 1];
  178. const genreValues = new Set();
  179. for (const section of genres) {
  180. for (const g of section.value)
  181. genreValues.add(g.value);
  182. }
  183. //добавим к жанрам те, что нашлись при парсинге
  184. const genreParsed = new Set();
  185. let rows = await db.select({table: 'genre', map: `(r) => ({value: r.value})`});
  186. for (const row of rows) {
  187. genreParsed.add(row.value);
  188. if (!genreValues.has(row.value))
  189. last.value.push({name: row.value, value: row.value});
  190. }
  191. //уберем те, которые не нашлись при парсинге
  192. for (let j = 0; j < genres.length; j++) {
  193. const section = genres[j];
  194. for (let i = 0; i < section.value.length; i++) {
  195. const g = section.value[i];
  196. if (!genreParsed.has(g.value))
  197. section.value.splice(i--, 1);
  198. }
  199. if (!section.value.length)
  200. genres.splice(j--, 1);
  201. }
  202. // langs
  203. rows = await db.select({table: 'lang', map: `(r) => ({value: r.value})`});
  204. const langs = rows.map(r => r.value);
  205. result = {
  206. genreTree: genres,
  207. langList: langs,
  208. inpxHash: (config.inpxHash ? config.inpxHash : ''),
  209. };
  210. db.wwCache.genres = result;
  211. } else {
  212. result = db.wwCache.genres;
  213. }
  214. return result;
  215. }
  216. async extractBook(bookPath) {
  217. const outFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
  218. const folder = `${this.config.libDir}/${path.dirname(bookPath)}`;
  219. const file = path.basename(bookPath);
  220. const zipReader = new ZipReader();
  221. await zipReader.open(folder);
  222. try {
  223. await zipReader.extractToFile(file, outFile);
  224. return outFile;
  225. } finally {
  226. await zipReader.close();
  227. }
  228. }
  229. //async
  230. gzipFile(inputFile, outputFile, level = 1) {
  231. return new Promise((resolve, reject) => {
  232. const gzip = zlib.createGzip({level});
  233. const input = fs.createReadStream(inputFile);
  234. const output = fs.createWriteStream(outputFile);
  235. input.pipe(gzip).pipe(output).on('finish', (err) => {
  236. if (err) reject(err);
  237. else resolve();
  238. });
  239. });
  240. }
  241. async restoreBook(bookPath, downFileName) {
  242. const db = this.db;
  243. const extractedFile = await this.extractBook(bookPath);
  244. const hash = await utils.getFileHash(extractedFile, 'sha256', 'hex');
  245. const link = `/files/${hash}`;
  246. const publicPath = `${this.config.publicDir}${link}`;
  247. if (!await fs.pathExists(publicPath)) {
  248. await fs.ensureDir(path.dirname(publicPath));
  249. const tmpFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
  250. await this.gzipFile(extractedFile, tmpFile, 4);
  251. await fs.remove(extractedFile);
  252. await fs.move(tmpFile, publicPath, {overwrite: true});
  253. } else {
  254. await fs.remove(extractedFile);
  255. await utils.touchFile(publicPath);
  256. }
  257. await db.insert({
  258. table: 'file_hash',
  259. replace: true,
  260. rows: [
  261. {id: bookPath, hash},
  262. {id: hash, bookPath, downFileName}
  263. ]
  264. });
  265. return link;
  266. }
  267. async getBookLink(params) {
  268. this.checkMyState();
  269. const {bookPath, downFileName} = params;
  270. try {
  271. const db = this.db;
  272. let link = '';
  273. //найдем хеш
  274. const rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(bookPath)})`});
  275. if (rows.length) {//хеш найден по bookPath
  276. const hash = rows[0].hash;
  277. link = `/files/${hash}`;
  278. const publicPath = `${this.config.publicDir}${link}`;
  279. if (!await fs.pathExists(publicPath)) {
  280. link = '';
  281. }
  282. }
  283. if (!link) {
  284. link = await this.restoreBook(bookPath, downFileName)
  285. }
  286. if (!link)
  287. throw new Error('404 Файл не найден');
  288. return {link};
  289. } catch(e) {
  290. log(LM_ERR, `getBookLink error: ${e.message}`);
  291. if (e.message.indexOf('ENOENT') >= 0)
  292. throw new Error('404 Файл не найден');
  293. throw e;
  294. }
  295. }
  296. async restoreBookFile(publicPath) {
  297. try {
  298. const db = this.db;
  299. const hash = path.basename(publicPath);
  300. //найдем bookPath и downFileName
  301. const rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(hash)})`});
  302. if (rows.length) {//нашли по хешу
  303. const rec = rows[0];
  304. await this.restoreBook(rec.bookPath, rec.downFileName);
  305. return rec.downFileName;
  306. } else {//bookPath не найден
  307. throw new Error('404 Файл не найден');
  308. }
  309. } catch(e) {
  310. log(LM_ERR, `restoreBookFile error: ${e.message}`);
  311. if (e.message.indexOf('ENOENT') >= 0)
  312. throw new Error('404 Файл не найден');
  313. throw e;
  314. }
  315. }
  316. async getDownFileName(publicPath) {
  317. const db = this.db;
  318. const hash = path.basename(publicPath);
  319. //найдем downFileName
  320. const rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(hash)})`});
  321. if (rows.length) {//downFileName найден по хешу
  322. return rows[0].downFileName;
  323. } else {//bookPath не найден
  324. throw new Error('404 Файл не найден');
  325. }
  326. }
  327. async logServerStats() {
  328. while (1) {// eslint-disable-line
  329. try {
  330. const memUsage = process.memoryUsage().rss/(1024*1024);//Mb
  331. let loadAvg = os.loadavg();
  332. loadAvg = loadAvg.map(v => v.toFixed(2));
  333. log(`Server info [ memUsage: ${memUsage.toFixed(2)}MB, loadAvg: (${loadAvg.join(', ')}) ]`);
  334. } catch (e) {
  335. log(LM_ERR, e.message);
  336. }
  337. await utils.sleep(5*1000);
  338. }
  339. }
  340. async cleanDir(config) {
  341. const {dir, maxSize} = config;
  342. const list = await fs.readdir(dir);
  343. let size = 0;
  344. let files = [];
  345. //формируем список
  346. for (const filename of list) {
  347. const filePath = `${dir}/${filename}`;
  348. const stat = await fs.stat(filePath);
  349. if (!stat.isDirectory()) {
  350. size += stat.size;
  351. files.push({name: filePath, stat});
  352. }
  353. }
  354. log(LM_WARN, `clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files, total size=${size}`);
  355. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  356. let i = 0;
  357. //удаляем
  358. while (i < files.length && size > maxSize) {
  359. const file = files[i];
  360. const oldFile = file.name;
  361. await fs.remove(oldFile);
  362. size -= file.stat.size;
  363. i++;
  364. }
  365. log(LM_WARN, `removed ${i} files`);
  366. }
  367. async periodicCleanDir(dirConfig) {
  368. try {
  369. let lastCleanDirTime = 0;
  370. while (1) {// eslint-disable-line no-constant-condition
  371. //чистка папок
  372. if (Date.now() - lastCleanDirTime >= cleanDirPeriod) {
  373. for (const config of Object.values(dirConfig)) {
  374. try {
  375. await this.cleanDir(config);
  376. } catch(e) {
  377. log(LM_ERR, e.stack);
  378. }
  379. }
  380. lastCleanDirTime = Date.now();
  381. }
  382. await utils.sleep(60*1000);//интервал проверки 1 минута
  383. }
  384. } catch (e) {
  385. log(LM_FATAL, e.message);
  386. ayncExit.exit(1);
  387. }
  388. }
  389. }
  390. module.exports = WebWorker;