WebWorker.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. //singleton
  25. let instance = null;
  26. class WebWorker {
  27. constructor(config) {
  28. if (!instance) {
  29. this.config = config;
  30. this.workerState = new WorkerState();
  31. this.wState = this.workerState.getControl('server_state');
  32. this.myState = '';
  33. this.db = null;
  34. this.dbSearcher = null;
  35. ayncExit.add(this.closeDb.bind(this));
  36. this.loadOrCreateDb();//no await
  37. this.logServerStats();//no await
  38. instance = this;
  39. }
  40. return instance;
  41. }
  42. checkMyState() {
  43. if (this.myState != ssNormal)
  44. throw new Error('server_busy');
  45. }
  46. setMyState(newState, workerState = {}) {
  47. this.myState = newState;
  48. this.wState.set(Object.assign({}, workerState, {
  49. state: newState,
  50. serverMessage: stateToText[newState]
  51. }));
  52. }
  53. async closeDb() {
  54. if (this.db) {
  55. await this.db.unlock();
  56. this.db = null;
  57. }
  58. }
  59. async createDb(dbPath) {
  60. this.setMyState(ssDbCreating);
  61. log('Searcher DB create start');
  62. const config = this.config;
  63. if (await fs.pathExists(dbPath))
  64. throw new Error(`createDb.pathExists: ${dbPath}`);
  65. const db = new JembaDbThread();//создаем не в потоке, чтобы лучше работал GC
  66. await db.lock({
  67. dbPath,
  68. create: true,
  69. softLock: true,
  70. tableDefaults: {
  71. cacheSize: 5,
  72. },
  73. });
  74. try {
  75. const dbCreator = new DbCreator(config);
  76. await dbCreator.run(db, (state) => {
  77. this.setMyState(ssDbCreating, state);
  78. if (state.fileName)
  79. log(` load ${state.fileName}`);
  80. if (state.recsLoaded)
  81. log(` processed ${state.recsLoaded} records`);
  82. if (state.job)
  83. log(` ${state.job}`);
  84. });
  85. log('Searcher DB successfully created');
  86. } finally {
  87. await db.unlock();
  88. }
  89. }
  90. async loadOrCreateDb(recreate = false) {
  91. this.setMyState(ssDbLoading);
  92. try {
  93. const config = this.config;
  94. const dbPath = `${config.dataDir}/db`;
  95. //пересоздаем БД из INPX если нужно
  96. if (config.recreateDb || recreate)
  97. await fs.remove(dbPath);
  98. if (!await fs.pathExists(dbPath)) {
  99. await this.createDb(dbPath);
  100. utils.freeMemory();
  101. }
  102. //загружаем БД
  103. this.setMyState(ssDbLoading);
  104. log('Searcher DB loading');
  105. const db = new JembaDbThread();
  106. await db.lock({
  107. dbPath,
  108. softLock: true,
  109. tableDefaults: {
  110. cacheSize: 5,
  111. },
  112. });
  113. //открываем все таблицы
  114. await db.openAll();
  115. this.dbSearcher = new DbSearcher(config, db);
  116. db.wwCache = {};
  117. this.db = db;
  118. log('Searcher DB ready');
  119. } catch (e) {
  120. log(LM_FATAL, e.message);
  121. ayncExit.exit(1);
  122. } finally {
  123. this.setMyState(ssNormal);
  124. }
  125. }
  126. async recreateDb() {
  127. this.setMyState(ssDbCreating);
  128. if (this.dbSearcher) {
  129. await this.dbSearcher.close();
  130. this.dbSearcher = null;
  131. }
  132. await this.closeDb();
  133. await this.loadOrCreateDb(true);
  134. }
  135. async dbConfig() {
  136. this.checkMyState();
  137. const db = this.db;
  138. if (!db.wwCache.config) {
  139. const rows = await db.select({table: 'config'});
  140. const config = {};
  141. for (const row of rows) {
  142. config[row.id] = row.value;
  143. }
  144. db.wwCache.config = config;
  145. }
  146. return db.wwCache.config;
  147. }
  148. async search(query) {
  149. this.checkMyState();
  150. const config = await this.dbConfig();
  151. const result = await this.dbSearcher.search(query);
  152. return {
  153. author: result.result,
  154. totalFound: result.totalFound,
  155. inpxHash: (config.inpxHash ? config.inpxHash : ''),
  156. };
  157. }
  158. async getBookList(authorId) {
  159. this.checkMyState();
  160. return await this.dbSearcher.getBookList(authorId);
  161. }
  162. async getGenreTree() {
  163. this.checkMyState();
  164. const config = await this.dbConfig();
  165. let result;
  166. const db = this.db;
  167. if (!db.wwCache.genres) {
  168. const genres = _.cloneDeep(genreTree);
  169. const last = genres[genres.length - 1];
  170. const genreValues = new Set();
  171. for (const section of genres) {
  172. for (const g of section.value)
  173. genreValues.add(g.value);
  174. }
  175. //добавим к жанрам те, что нашлись при парсинге
  176. const genreParsed = new Set();
  177. let rows = await db.select({table: 'genre', map: `(r) => ({value: r.value})`});
  178. for (const row of rows) {
  179. genreParsed.add(row.value);
  180. if (!genreValues.has(row.value))
  181. last.value.push({name: row.value, value: row.value});
  182. }
  183. //уберем те, которые не нашлись при парсинге
  184. for (let j = 0; j < genres.length; j++) {
  185. const section = genres[j];
  186. for (let i = 0; i < section.value.length; i++) {
  187. const g = section.value[i];
  188. if (!genreParsed.has(g.value))
  189. section.value.splice(i--, 1);
  190. }
  191. if (!section.value.length)
  192. genres.splice(j--, 1);
  193. }
  194. // langs
  195. rows = await db.select({table: 'lang', map: `(r) => ({value: r.value})`});
  196. const langs = rows.map(r => r.value);
  197. result = {
  198. genreTree: genres,
  199. langList: langs,
  200. inpxHash: (config.inpxHash ? config.inpxHash : ''),
  201. };
  202. db.wwCache.genres = result;
  203. } else {
  204. result = db.wwCache.genres;
  205. }
  206. return result;
  207. }
  208. async extractBook(bookPath) {
  209. const tempDir = this.config.tempDir;
  210. const outFile = `${tempDir}/${utils.randomHexString(30)}`;
  211. const folder = `${this.config.libDir}/${path.dirname(bookPath)}`;
  212. const file = path.basename(bookPath);
  213. const zipReader = new ZipReader();
  214. await zipReader.open(folder);
  215. try {
  216. await zipReader.extractToFile(file, outFile);
  217. return outFile;
  218. } finally {
  219. await zipReader.close();
  220. }
  221. }
  222. async gzipFile(inputFile, outputFile, level = 1) {
  223. return new Promise((resolve, reject) => {
  224. const gzip = zlib.createGzip({level});
  225. const input = fs.createReadStream(inputFile);
  226. const output = fs.createWriteStream(outputFile);
  227. input.pipe(gzip).pipe(output).on('finish', (err) => {
  228. if (err) reject(err);
  229. else resolve();
  230. });
  231. });
  232. }
  233. async restoreBook(bookPath) {
  234. const db = this.db;
  235. const extractedFile = await this.extractBook(bookPath);
  236. const hash = await utils.getFileHash(extractedFile, 'sha256', 'hex');
  237. const link = `/files/${hash}`;
  238. const publicPath = `${this.config.publicDir}${link}`;
  239. if (!await fs.pathExists(publicPath)) {
  240. await fs.ensureDir(path.dirname(publicPath));
  241. await this.gzipFile(extractedFile, publicPath, 4);
  242. } else {
  243. await fs.remove(extractedFile);
  244. }
  245. await db.insert({
  246. table: 'file_hash',
  247. replace: true,
  248. rows: [
  249. {id: bookPath, hash},
  250. {id: hash, bookPath}
  251. ]
  252. });
  253. return link;
  254. }
  255. async getBookLink(bookPath) {
  256. this.checkMyState();
  257. try {
  258. const db = this.db;
  259. let link = '';
  260. //найдем хеш
  261. const rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(bookPath)})`});
  262. if (rows.length) {//хеш найден по bookPath
  263. const hash = rows[0].hash;
  264. link = `/files/${hash}`;
  265. const publicPath = `${this.config.publicDir}${link}`;
  266. if (!await fs.pathExists(publicPath)) {
  267. link = '';
  268. }
  269. }
  270. if (!link) {
  271. link = await this.restoreBook(bookPath)
  272. }
  273. if (!link)
  274. throw new Error('404 Файл не найден');
  275. return {link};
  276. } catch(e) {
  277. log(LM_ERR, `getBookLink error: ${e.message}`);
  278. if (e.message.indexOf('ENOENT') >= 0)
  279. throw new Error('404 Файл не найден');
  280. throw e;
  281. }
  282. }
  283. async restoreBookFile(publicPath) {
  284. try {
  285. const db = this.db;
  286. const hash = path.basename(publicPath);
  287. //найдем bookPath
  288. const rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(hash)})`});
  289. if (rows.length) {//bookPath найден по хешу
  290. const bookPath = rows[0].bookPath;
  291. await this.restoreBook(bookPath);
  292. } else {//bookPath не найден
  293. throw new Error('404 Файл не найден');
  294. }
  295. } catch(e) {
  296. log(LM_ERR, `restoreBookFile error: ${e.message}`);
  297. if (e.message.indexOf('ENOENT') >= 0)
  298. throw new Error('404 Файл не найден');
  299. throw e;
  300. }
  301. }
  302. async logServerStats() {
  303. while (1) {// eslint-disable-line
  304. try {
  305. const memUsage = process.memoryUsage().rss/(1024*1024);//Mb
  306. let loadAvg = os.loadavg();
  307. loadAvg = loadAvg.map(v => v.toFixed(2));
  308. log(`Server info [ memUsage: ${memUsage.toFixed(2)}MB, loadAvg: (${loadAvg.join(', ')}) ]`);
  309. } catch (e) {
  310. log(LM_ERR, e.message);
  311. }
  312. await utils.sleep(5*1000);
  313. }
  314. }
  315. }
  316. module.exports = WebWorker;