DbSearcher.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. const fs = require('fs-extra');
  2. //const _ = require('lodash');
  3. const LockQueue = require('./LockQueue');
  4. const utils = require('./utils');
  5. const maxMemCacheSize = 100;
  6. const maxLimit = 1000;
  7. const emptyFieldValue = '?';
  8. const maxUtf8Char = String.fromCodePoint(0xFFFFF);
  9. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  10. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  11. const enruArr = (ruAlphabet + enAlphabet).split('');
  12. class DbSearcher {
  13. constructor(config, db) {
  14. this.config = config;
  15. this.db = db;
  16. this.lock = new LockQueue();
  17. this.searchFlag = 0;
  18. this.timer = null;
  19. this.closed = false;
  20. this.memCache = new Map();
  21. this.bookIdMap = {};
  22. this.periodicCleanCache();//no await
  23. this.fillBookIdMapAll();//no await
  24. }
  25. queryKey(q) {
  26. return JSON.stringify([q.author, q.series, q.title, q.genre, q.lang, q.del, q.date, q.librate]);
  27. }
  28. getWhere(a) {
  29. const db = this.db;
  30. a = a.toLowerCase();
  31. let where;
  32. //особая обработка префиксов
  33. if (a[0] == '=') {
  34. a = a.substring(1);
  35. where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a)})`;
  36. } else if (a[0] == '*') {
  37. a = a.substring(1);
  38. where = `@indexIter('value', (v) => (v !== ${db.esc(emptyFieldValue)} && v.indexOf(${db.esc(a)}) >= 0) )`;
  39. } else if (a[0] == '#') {
  40. a = a.substring(1);
  41. where = `@indexIter('value', (v) => {
  42. const enru = new Set(${db.esc(enruArr)});
  43. return !v || (v !== ${db.esc(emptyFieldValue)} && !enru.has(v[0]) && v.indexOf(${db.esc(a)}) >= 0);
  44. })`;
  45. } else {
  46. where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  47. }
  48. return where;
  49. }
  50. async selectBookIds(query) {
  51. const db = this.db;
  52. const idsArr = [];
  53. const tableBookIds = async(table, where) => {
  54. const rows = await db.select({
  55. table,
  56. rawResult: true,
  57. where: `
  58. const ids = ${where};
  59. const result = new Set();
  60. for (const id of ids) {
  61. const row = @unsafeRow(id);
  62. for (const bookId of row.bookIds)
  63. result.add(bookId);
  64. }
  65. return Array.from(result);
  66. `
  67. });
  68. return rows[0].rawResult;
  69. };
  70. //авторы
  71. if (query.author && query.author !== '*') {
  72. const key = `book-ids-author-${query.author}`;
  73. let ids = await this.getCached(key);
  74. if (ids === null) {
  75. ids = await tableBookIds('author', this.getWhere(query.author));
  76. await this.putCached(key, ids);
  77. }
  78. idsArr.push(ids);
  79. }
  80. //серии
  81. if (query.series && query.series !== '*') {
  82. const key = `book-ids-series-${query.series}`;
  83. let ids = await this.getCached(key);
  84. if (ids === null) {
  85. ids = await tableBookIds('series', this.getWhere(query.series));
  86. await this.putCached(key, ids);
  87. }
  88. idsArr.push(ids);
  89. }
  90. //названия
  91. if (query.title && query.title !== '*') {
  92. const key = `book-ids-title-${query.title}`;
  93. let ids = await this.getCached(key);
  94. if (ids === null) {
  95. ids = await tableBookIds('title', this.getWhere(query.title));
  96. await this.putCached(key, ids);
  97. }
  98. idsArr.push(ids);
  99. }
  100. //жанры
  101. if (query.genre) {
  102. const key = `book-ids-genre-${query.genre}`;
  103. let ids = await this.getCached(key);
  104. if (ids === null) {
  105. const genreRows = await db.select({
  106. table: 'genre',
  107. rawResult: true,
  108. where: `
  109. const genres = ${db.esc(query.genre.split(','))};
  110. const ids = new Set();
  111. for (const g of genres) {
  112. for (const id of @indexLR('value', g, g))
  113. ids.add(id);
  114. }
  115. const result = new Set();
  116. for (const id of ids) {
  117. const row = @unsafeRow(id);
  118. for (const bookId of row.bookIds)
  119. result.add(bookId);
  120. }
  121. return Array.from(result);
  122. `
  123. });
  124. ids = genreRows[0].rawResult;
  125. await this.putCached(key, ids);
  126. }
  127. idsArr.push(ids);
  128. }
  129. //языки
  130. if (query.lang) {
  131. const key = `book-ids-lang-${query.lang}`;
  132. let ids = await this.getCached(key);
  133. if (ids === null) {
  134. const langRows = await db.select({
  135. table: 'lang',
  136. rawResult: true,
  137. where: `
  138. const langs = ${db.esc(query.lang.split(','))};
  139. const ids = new Set();
  140. for (const l of langs) {
  141. for (const id of @indexLR('value', l, l))
  142. ids.add(id);
  143. }
  144. const result = new Set();
  145. for (const id of ids) {
  146. const row = @unsafeRow(id);
  147. for (const bookId of row.bookIds)
  148. result.add(bookId);
  149. }
  150. return Array.from(result);
  151. `
  152. });
  153. ids = langRows[0].rawResult;
  154. await this.putCached(key, ids);
  155. }
  156. idsArr.push(ids);
  157. }
  158. //удаленные
  159. if (query.del !== undefined) {
  160. const key = `book-ids-del-${query.del}`;
  161. let ids = await this.getCached(key);
  162. if (ids === null) {
  163. ids = await tableBookIds('del', `@indexLR('value', ${db.esc(query.del)}, ${db.esc(query.del)})`);
  164. await this.putCached(key, ids);
  165. }
  166. idsArr.push(ids);
  167. }
  168. //дата поступления
  169. if (query.date) {
  170. const key = `book-ids-date-${query.date}`;
  171. let ids = await this.getCached(key);
  172. if (ids === null) {
  173. let [from = '', to = ''] = query.date.split(',');
  174. ids = await tableBookIds('date', `@indexLR('value', ${db.esc(from)} || undefined, ${db.esc(to)} || undefined)`);
  175. await this.putCached(key, ids);
  176. }
  177. idsArr.push(ids);
  178. }
  179. //оценка
  180. if (query.librate) {
  181. const key = `book-ids-librate-${query.librate}`;
  182. let ids = await this.getCached(key);
  183. if (ids === null) {
  184. const dateRows = await db.select({
  185. table: 'librate',
  186. rawResult: true,
  187. where: `
  188. const rates = ${db.esc(query.librate.split(',').map(n => parseInt(n, 10)).filter(n => !isNaN(n)))};
  189. const ids = new Set();
  190. for (const rate of rates) {
  191. for (const id of @indexLR('value', rate, rate))
  192. ids.add(id);
  193. }
  194. const result = new Set();
  195. for (const id of ids) {
  196. const row = @unsafeRow(id);
  197. for (const bookId of row.bookIds)
  198. result.add(bookId);
  199. }
  200. return Array.from(result);
  201. `
  202. });
  203. ids = dateRows[0].rawResult;
  204. await this.putCached(key, ids);
  205. }
  206. idsArr.push(ids);
  207. }
  208. if (idsArr.length > 1) {
  209. //ищем пересечение множеств
  210. let proc = 0;
  211. let nextProc = 0;
  212. let inter = new Set(idsArr[0]);
  213. for (let i = 1; i < idsArr.length; i++) {
  214. const newInter = new Set();
  215. for (const id of idsArr[i]) {
  216. if (inter.has(id))
  217. newInter.add(id);
  218. //прерываемся иногда, чтобы не блокировать Event Loop
  219. proc++;
  220. if (proc >= nextProc) {
  221. nextProc += 10000;
  222. await utils.processLoop();
  223. }
  224. }
  225. inter = newInter;
  226. }
  227. return Array.from(inter);
  228. } else if (idsArr.length == 1) {
  229. return idsArr[0];
  230. } else {
  231. return false;
  232. }
  233. }
  234. async fillBookIdMap(from) {
  235. if (this.bookIdMap[from])
  236. return this.bookIdMap[from];
  237. await this.lock.get();
  238. try {
  239. const data = await fs.readFile(`${this.config.dataDir}/db/${from}_id.map`, 'utf-8');
  240. const idMap = JSON.parse(data);
  241. idMap.arr = new Uint32Array(idMap.arr);
  242. idMap.map = new Map(idMap.map);
  243. this.bookIdMap[from] = idMap;
  244. return this.bookIdMap[from];
  245. } finally {
  246. this.lock.ret();
  247. }
  248. }
  249. async fillBookIdMapAll() {
  250. try {
  251. await this.fillBookIdMap('author');
  252. await this.fillBookIdMap('series');
  253. await this.fillBookIdMap('title');
  254. } catch (e) {
  255. throw new Error(`DbSearcher.fillBookIdMapAll error: ${e.message}`)
  256. }
  257. }
  258. async filterTableIds(tableIds, from, query) {
  259. let result = tableIds;
  260. //т.к. авторы у книги идут списком (т.е. одна книга относиться сразу к нескольким авторам),
  261. //то в выборку по bookId могут попасть авторы, которые отсутствуют в критерии query.author,
  262. //поэтому дополнительно фильтруем
  263. if (from == 'author' && query.author && query.author !== '*') {
  264. const key = `filter-ids-author-${query.author}`;
  265. let authorIds = await this.getCached(key);
  266. if (authorIds === null) {
  267. const rows = await this.db.select({
  268. table: 'author',
  269. rawResult: true,
  270. where: `return Array.from(${this.getWhere(query.author)})`
  271. });
  272. authorIds = rows[0].rawResult;
  273. await this.putCached(key, authorIds);
  274. }
  275. //пересечение tableIds и authorIds
  276. result = [];
  277. const authorIdsSet = new Set(authorIds);
  278. for (const id of tableIds)
  279. if (authorIdsSet.has(id))
  280. result.push(id);
  281. }
  282. return result;
  283. }
  284. async selectTableIds(from, query) {
  285. const db = this.db;
  286. const queryKey = this.queryKey(query);
  287. const tableKey = `${from}-table-ids-${queryKey}`;
  288. let tableIds = await this.getCached(tableKey);
  289. if (tableIds === null) {
  290. const bookKey = `book-ids-${queryKey}`;
  291. let bookIds = await this.getCached(bookKey);
  292. if (bookIds === null) {
  293. bookIds = await this.selectBookIds(query);
  294. await this.putCached(bookKey, bookIds);
  295. }
  296. //id книг (bookIds) нашли, теперь надо их смаппировать в id таблицы from (авторов, серий, названий)
  297. if (bookIds) {
  298. const tableIdsSet = new Set();
  299. const idMap = await this.fillBookIdMap(from);
  300. let proc = 0;
  301. let nextProc = 0;
  302. for (const bookId of bookIds) {
  303. const tableId = idMap.arr[bookId];
  304. if (tableId) {
  305. tableIdsSet.add(tableId);
  306. proc++;
  307. } else {
  308. const tableIdArr = idMap.map.get(bookId);
  309. if (tableIdArr) {
  310. for (const tableId of tableIdArr) {
  311. tableIdsSet.add(tableId);
  312. proc++;
  313. }
  314. }
  315. }
  316. //прерываемся иногда, чтобы не блокировать Event Loop
  317. if (proc >= nextProc) {
  318. nextProc += 10000;
  319. await utils.processLoop();
  320. }
  321. }
  322. tableIds = Array.from(tableIdsSet);
  323. } else {//bookIds пустой - критерии не заданы, значит берем все id из from
  324. const rows = await db.select({
  325. table: from,
  326. rawResult: true,
  327. where: `return Array.from(@all())`
  328. });
  329. tableIds = rows[0].rawResult;
  330. }
  331. //т.к. авторы у книги идут списком, то дополнительно фильтруем
  332. tableIds = await this.filterTableIds(tableIds, from, query);
  333. //сортируем по id
  334. //порядок id соответствует ASC-сортировке по строковому значению из from (имя автора, назание серии, название книги)
  335. tableIds.sort((a, b) => a - b);
  336. await this.putCached(tableKey, tableIds);
  337. }
  338. return tableIds;
  339. }
  340. async restoreBooks(from, ids) {
  341. const db = this.db;
  342. const bookTable = `${from}_book`;
  343. const rows = await db.select({
  344. table: bookTable,
  345. where: `@@id(${db.esc(ids)})`
  346. });
  347. if (rows.length == ids.length)
  348. return rows;
  349. //далее восстановим книги из book в <from>_book
  350. const idsSet = new Set(rows.map(r => r.id));
  351. //недостающие
  352. const tableIds = [];
  353. for (const id of ids) {
  354. if (!idsSet.has(id))
  355. tableIds.push(id);
  356. }
  357. const tableRows = await db.select({
  358. table: from,
  359. where: `@@id(${db.esc(tableIds)})`
  360. });
  361. //список недостающих bookId
  362. const bookIds = [];
  363. for (const row of tableRows) {
  364. for (const bookId of row.bookIds)
  365. bookIds.push(bookId);
  366. }
  367. //выбираем книги
  368. const books = await db.select({
  369. table: 'book',
  370. where: `@@id(${db.esc(bookIds)})`
  371. });
  372. const booksMap = new Map();
  373. for (const book of books)
  374. booksMap.set(book.id, book);
  375. //распределяем
  376. for (const row of tableRows) {
  377. const books = [];
  378. for (const bookId of row.bookIds) {
  379. const book = booksMap.get(bookId);
  380. if (book)
  381. books.push(book);
  382. }
  383. rows.push({id: row.id, name: row.name, books});
  384. }
  385. await db.insert({table: bookTable, ignore: true, rows});
  386. return rows;
  387. }
  388. async search(from, query) {
  389. if (this.closed)
  390. throw new Error('DbSearcher closed');
  391. if (!['author', 'series', 'title'].includes(from))
  392. throw new Error(`Unknown value for param 'from'`);
  393. this.searchFlag++;
  394. try {
  395. const db = this.db;
  396. const ids = await this.selectTableIds(from, query);
  397. const totalFound = ids.length;
  398. let limit = (query.limit ? query.limit : 100);
  399. limit = (limit > maxLimit ? maxLimit : limit);
  400. const offset = (query.offset ? query.offset : 0);
  401. //выборка найденных значений
  402. const found = await db.select({
  403. table: from,
  404. map: `(r) => ({id: r.id, ${from}: r.name, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  405. where: `@@id(${db.esc(ids.slice(offset, offset + limit))})`
  406. });
  407. //для title восстановим books
  408. if (from == 'title') {
  409. const bookIds = found.map(r => r.id);
  410. const rows = await this.restoreBooks(from, bookIds);
  411. const rowsMap = new Map();
  412. for (const row of rows)
  413. rowsMap.set(row.id, row);
  414. for (const f of found) {
  415. const b = rowsMap.get(f.id);
  416. if (b)
  417. f.books = b.books;
  418. }
  419. }
  420. return {found, totalFound};
  421. } finally {
  422. this.searchFlag--;
  423. }
  424. }
  425. async getAuthorBookList(authorId) {
  426. if (this.closed)
  427. throw new Error('DbSearcher closed');
  428. if (!authorId)
  429. return {author: '', books: ''};
  430. this.searchFlag++;
  431. try {
  432. //выборка книг автора по authorId
  433. const rows = await this.restoreBooks('author', [authorId])
  434. let author = '';
  435. let books = '';
  436. if (rows.length) {
  437. author = rows[0].name;
  438. books = rows[0].books;
  439. }
  440. return {author, books: (books && books.length ? JSON.stringify(books) : '')};
  441. } finally {
  442. this.searchFlag--;
  443. }
  444. }
  445. async getSeriesBookList(series) {
  446. if (this.closed)
  447. throw new Error('DbSearcher closed');
  448. if (!series)
  449. return {books: ''};
  450. this.searchFlag++;
  451. try {
  452. const db = this.db;
  453. series = series.toLowerCase();
  454. //выборка серии по названию серии
  455. let rows = await db.select({
  456. table: 'series',
  457. rawResult: true,
  458. where: `return Array.from(@dirtyIndexLR('value', ${db.esc(series)}, ${db.esc(series)}))`
  459. });
  460. let books;
  461. if (rows.length && rows[0].rawResult.length) {
  462. //выборка книг серии
  463. const bookRows = await this.restoreBooks('series', [rows[0].rawResult[0]])
  464. if (bookRows.length)
  465. books = bookRows[0].books;
  466. }
  467. return {books: (books && books.length ? JSON.stringify(books) : '')};
  468. } finally {
  469. this.searchFlag--;
  470. }
  471. }
  472. async getCached(key) {
  473. if (!this.config.queryCacheEnabled)
  474. return null;
  475. let result = null;
  476. const db = this.db;
  477. const memCache = this.memCache;
  478. if (memCache.has(key)) {//есть в недавних
  479. result = memCache.get(key);
  480. //изменим порядок ключей, для последующей правильной чистки старых
  481. memCache.delete(key);
  482. memCache.set(key, result);
  483. } else {//смотрим в таблице
  484. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  485. if (rows.length) {//нашли в кеше
  486. await db.insert({
  487. table: 'query_time',
  488. replace: true,
  489. rows: [{id: key, time: Date.now()}],
  490. });
  491. result = rows[0].value;
  492. memCache.set(key, result);
  493. if (memCache.size > maxMemCacheSize) {
  494. //удаляем самый старый ключ-значение
  495. for (const k of memCache.keys()) {
  496. memCache.delete(k);
  497. break;
  498. }
  499. }
  500. }
  501. }
  502. return result;
  503. }
  504. async putCached(key, value) {
  505. if (!this.config.queryCacheEnabled)
  506. return;
  507. const db = this.db;
  508. const memCache = this.memCache;
  509. memCache.set(key, value);
  510. if (memCache.size > maxMemCacheSize) {
  511. //удаляем самый старый ключ-значение
  512. for (const k of memCache.keys()) {
  513. memCache.delete(k);
  514. break;
  515. }
  516. }
  517. //кладем в таблицу асинхронно
  518. (async() => {
  519. try {
  520. await db.insert({
  521. table: 'query_cache',
  522. replace: true,
  523. rows: [{id: key, value}],
  524. });
  525. await db.insert({
  526. table: 'query_time',
  527. replace: true,
  528. rows: [{id: key, time: Date.now()}],
  529. });
  530. } catch(e) {
  531. console.error(`putCached: ${e.message}`);
  532. }
  533. })();
  534. }
  535. async periodicCleanCache() {
  536. this.timer = null;
  537. const cleanInterval = this.config.cacheCleanInterval*60*1000;
  538. if (!cleanInterval)
  539. return;
  540. try {
  541. const db = this.db;
  542. const oldThres = Date.now() - cleanInterval;
  543. //выберем всех кандидатов на удаление
  544. const rows = await db.select({
  545. table: 'query_time',
  546. where: `
  547. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  548. `
  549. });
  550. const ids = [];
  551. for (const row of rows)
  552. ids.push(row.id);
  553. //удаляем
  554. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  555. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  556. //console.log('Cache clean', ids);
  557. } catch(e) {
  558. console.error(e.message);
  559. } finally {
  560. if (!this.closed) {
  561. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  562. }
  563. }
  564. }
  565. async close() {
  566. while (this.searchFlag > 0) {
  567. await utils.sleep(50);
  568. }
  569. this.searchCache = null;
  570. if (this.timer) {
  571. clearTimeout(this.timer);
  572. this.timer = null;
  573. }
  574. this.closed = true;
  575. }
  576. }
  577. module.exports = DbSearcher;