WebWorker.js 10 KB

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