DbSearcher.js 22 KB

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