DbSearcher.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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 new Uint32Array(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 new Uint32Array(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 new Uint32Array(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 new Uint32Array(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 new Uint32Array(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 tableIdsFilter(from, query) {
  259. //т.к. авторы у книги идут списком (т.е. одна книга относиться сразу к нескольким авторам),
  260. //то в выборку по bookId могут попасть авторы, которые отсутствуют в критерии query.author,
  261. //поэтому дополнительно фильтруем
  262. let result = null;
  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 new Uint32Array(${this.getWhere(query.author)})`
  271. });
  272. authorIds = rows[0].rawResult;
  273. await this.putCached(key, authorIds);
  274. }
  275. result = new Set(authorIds);
  276. }
  277. return result;
  278. }
  279. async selectTableIds(from, query) {
  280. const db = this.db;
  281. const queryKey = this.queryKey(query);
  282. const tableKey = `${from}-table-ids-${queryKey}`;
  283. let tableIds = await this.getCached(tableKey);
  284. if (tableIds === null) {
  285. const bookKey = `book-ids-${queryKey}`;
  286. let bookIds = await this.getCached(bookKey);
  287. if (bookIds === null) {
  288. bookIds = await this.selectBookIds(query);
  289. await this.putCached(bookKey, bookIds);
  290. }
  291. //id книг (bookIds) нашли, теперь надо их смаппировать в id таблицы from (авторов, серий, названий)
  292. if (bookIds) {
  293. //т.к. авторы у книги идут списком, то дополнительно фильтруем
  294. const filter = await this.tableIdsFilter(from, query);
  295. const tableIdsSet = new Set();
  296. const idMap = await this.fillBookIdMap(from);
  297. let proc = 0;
  298. let nextProc = 0;
  299. for (const bookId of bookIds) {
  300. const tableId = idMap.arr[bookId];
  301. if (tableId) {
  302. if (!filter || filter.has(tableId))
  303. tableIdsSet.add(tableId);
  304. proc++;
  305. } else {
  306. const tableIdArr = idMap.map.get(bookId);
  307. if (tableIdArr) {
  308. for (const tableId of tableIdArr) {
  309. if (!filter || filter.has(tableId))
  310. tableIdsSet.add(tableId);
  311. proc++;
  312. }
  313. }
  314. }
  315. //прерываемся иногда, чтобы не блокировать Event Loop
  316. if (proc >= nextProc) {
  317. nextProc += 10000;
  318. await utils.processLoop();
  319. }
  320. }
  321. tableIds = Array.from(tableIdsSet);
  322. } else {//bookIds пустой - критерии не заданы, значит берем все id из from
  323. const rows = await db.select({
  324. table: from,
  325. rawResult: true,
  326. where: `return Array.from(@all())`
  327. });
  328. tableIds = rows[0].rawResult;
  329. }
  330. //сортируем по id
  331. //порядок id соответствует ASC-сортировке по строковому значению из from (имя автора, назание серии, название книги)
  332. tableIds.sort((a, b) => a - b);
  333. await this.putCached(tableKey, tableIds);
  334. }
  335. return tableIds;
  336. }
  337. async restoreBooks(from, ids) {
  338. const db = this.db;
  339. const bookTable = `${from}_book`;
  340. const rows = await db.select({
  341. table: bookTable,
  342. where: `@@id(${db.esc(ids)})`
  343. });
  344. if (rows.length == ids.length)
  345. return rows;
  346. //далее восстановим книги из book в <from>_book
  347. const idsSet = new Set(rows.map(r => r.id));
  348. //недостающие
  349. const tableIds = [];
  350. for (const id of ids) {
  351. if (!idsSet.has(id))
  352. tableIds.push(id);
  353. }
  354. const tableRows = await db.select({
  355. table: from,
  356. where: `@@id(${db.esc(tableIds)})`
  357. });
  358. //список недостающих bookId
  359. const bookIds = [];
  360. for (const row of tableRows) {
  361. for (const bookId of row.bookIds)
  362. bookIds.push(bookId);
  363. }
  364. //выбираем книги
  365. const books = await db.select({
  366. table: 'book',
  367. where: `@@id(${db.esc(bookIds)})`
  368. });
  369. const booksMap = new Map();
  370. for (const book of books)
  371. booksMap.set(book.id, book);
  372. //распределяем
  373. for (const row of tableRows) {
  374. const books = [];
  375. for (const bookId of row.bookIds) {
  376. const book = booksMap.get(bookId);
  377. if (book)
  378. books.push(book);
  379. }
  380. rows.push({id: row.id, name: row.name, books});
  381. }
  382. await db.insert({table: bookTable, ignore: true, rows});
  383. return rows;
  384. }
  385. async search(from, query) {
  386. if (this.closed)
  387. throw new Error('DbSearcher closed');
  388. if (!['author', 'series', 'title'].includes(from))
  389. throw new Error(`Unknown value for param 'from'`);
  390. this.searchFlag++;
  391. try {
  392. const db = this.db;
  393. const ids = await this.selectTableIds(from, query);
  394. const totalFound = ids.length;
  395. let limit = (query.limit ? query.limit : 100);
  396. limit = (limit > maxLimit ? maxLimit : limit);
  397. const offset = (query.offset ? query.offset : 0);
  398. //выборка найденных значений
  399. const found = await db.select({
  400. table: from,
  401. map: `(r) => ({id: r.id, ${from}: r.name, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  402. where: `@@id(${db.esc(ids.slice(offset, offset + limit))})`
  403. });
  404. //для title восстановим books
  405. if (from == 'title') {
  406. const bookIds = found.map(r => r.id);
  407. const rows = await this.restoreBooks(from, bookIds);
  408. const rowsMap = new Map();
  409. for (const row of rows)
  410. rowsMap.set(row.id, row);
  411. for (const f of found) {
  412. const b = rowsMap.get(f.id);
  413. if (b)
  414. f.books = b.books;
  415. }
  416. }
  417. return {found, totalFound};
  418. } finally {
  419. this.searchFlag--;
  420. }
  421. }
  422. async getAuthorBookList(authorId) {
  423. if (this.closed)
  424. throw new Error('DbSearcher closed');
  425. if (!authorId)
  426. return {author: '', books: ''};
  427. this.searchFlag++;
  428. try {
  429. //выборка книг автора по authorId
  430. const rows = await this.restoreBooks('author', [authorId])
  431. let author = '';
  432. let books = '';
  433. if (rows.length) {
  434. author = rows[0].name;
  435. books = rows[0].books;
  436. }
  437. return {author, books: (books && books.length ? JSON.stringify(books) : '')};
  438. } finally {
  439. this.searchFlag--;
  440. }
  441. }
  442. async getSeriesBookList(series) {
  443. if (this.closed)
  444. throw new Error('DbSearcher closed');
  445. if (!series)
  446. return {books: ''};
  447. this.searchFlag++;
  448. try {
  449. const db = this.db;
  450. series = series.toLowerCase();
  451. //выборка серии по названию серии
  452. let rows = await db.select({
  453. table: 'series',
  454. rawResult: true,
  455. where: `return Array.from(@dirtyIndexLR('value', ${db.esc(series)}, ${db.esc(series)}))`
  456. });
  457. let books;
  458. if (rows.length && rows[0].rawResult.length) {
  459. //выборка книг серии
  460. const bookRows = await this.restoreBooks('series', [rows[0].rawResult[0]])
  461. if (bookRows.length)
  462. books = bookRows[0].books;
  463. }
  464. return {books: (books && books.length ? JSON.stringify(books) : '')};
  465. } finally {
  466. this.searchFlag--;
  467. }
  468. }
  469. async getCached(key) {
  470. if (!this.config.queryCacheEnabled)
  471. return null;
  472. let result = null;
  473. const db = this.db;
  474. const memCache = this.memCache;
  475. if (memCache.has(key)) {//есть в недавних
  476. result = memCache.get(key);
  477. //изменим порядок ключей, для последующей правильной чистки старых
  478. memCache.delete(key);
  479. memCache.set(key, result);
  480. } else {//смотрим в таблице
  481. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  482. if (rows.length) {//нашли в кеше
  483. await db.insert({
  484. table: 'query_time',
  485. replace: true,
  486. rows: [{id: key, time: Date.now()}],
  487. });
  488. result = rows[0].value;
  489. memCache.set(key, result);
  490. if (memCache.size > maxMemCacheSize) {
  491. //удаляем самый старый ключ-значение
  492. for (const k of memCache.keys()) {
  493. memCache.delete(k);
  494. break;
  495. }
  496. }
  497. }
  498. }
  499. return result;
  500. }
  501. async putCached(key, value) {
  502. if (!this.config.queryCacheEnabled)
  503. return;
  504. const db = this.db;
  505. const memCache = this.memCache;
  506. memCache.set(key, value);
  507. if (memCache.size > maxMemCacheSize) {
  508. //удаляем самый старый ключ-значение
  509. for (const k of memCache.keys()) {
  510. memCache.delete(k);
  511. break;
  512. }
  513. }
  514. //кладем в таблицу асинхронно
  515. (async() => {
  516. try {
  517. await db.insert({
  518. table: 'query_cache',
  519. replace: true,
  520. rows: [{id: key, value}],
  521. });
  522. await db.insert({
  523. table: 'query_time',
  524. replace: true,
  525. rows: [{id: key, time: Date.now()}],
  526. });
  527. } catch(e) {
  528. console.error(`putCached: ${e.message}`);
  529. }
  530. })();
  531. }
  532. async periodicCleanCache() {
  533. this.timer = null;
  534. const cleanInterval = this.config.cacheCleanInterval*60*1000;
  535. if (!cleanInterval)
  536. return;
  537. try {
  538. const db = this.db;
  539. const oldThres = Date.now() - cleanInterval;
  540. //выберем всех кандидатов на удаление
  541. const rows = await db.select({
  542. table: 'query_time',
  543. where: `
  544. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  545. `
  546. });
  547. const ids = [];
  548. for (const row of rows)
  549. ids.push(row.id);
  550. //удаляем
  551. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  552. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  553. //console.log('Cache clean', ids);
  554. } catch(e) {
  555. console.error(e.message);
  556. } finally {
  557. if (!this.closed) {
  558. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  559. }
  560. }
  561. }
  562. async close() {
  563. while (this.searchFlag > 0) {
  564. await utils.sleep(50);
  565. }
  566. this.searchCache = null;
  567. if (this.timer) {
  568. clearTimeout(this.timer);
  569. this.timer = null;
  570. }
  571. this.closed = true;
  572. }
  573. }
  574. module.exports = DbSearcher;