DbSearcher.js 22 KB

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