DbSearcher.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. const fs = require('fs-extra');
  2. //const _ = require('lodash');
  3. const LockQueue = require('./LockQueue');
  4. const utils = require('./utils');
  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.queryCacheMemSize = this.config.queryCacheMemSize;
  15. this.queryCacheDiskSize = this.config.queryCacheDiskSize;
  16. this.queryCacheEnabled = this.config.queryCacheEnabled
  17. && (this.queryCacheMemSize > 0 || this.queryCacheDiskSize > 0);
  18. this.db = db;
  19. this.lock = new LockQueue();
  20. this.searchFlag = 0;
  21. this.timer = null;
  22. this.closed = false;
  23. this.memCache = new Map();
  24. this.bookIdMap = {};
  25. this.periodicCleanCache();//no await
  26. this.fillBookIdMapAll();//no await
  27. }
  28. queryKey(q) {
  29. return JSON.stringify([q.author, q.series, q.title, q.genre, q.lang, q.del, q.date, q.librate]);
  30. }
  31. getWhere(a) {
  32. const db = this.db;
  33. a = a.toLowerCase();
  34. let where;
  35. //особая обработка префиксов
  36. if (a[0] == '=') {
  37. a = a.substring(1);
  38. where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a)})`;
  39. } else if (a[0] == '*') {
  40. a = a.substring(1);
  41. where = `@indexIter('value', (v) => (v !== ${db.esc(emptyFieldValue)} && v.indexOf(${db.esc(a)}) >= 0) )`;
  42. } else if (a[0] == '#') {
  43. a = a.substring(1);
  44. where = `@indexIter('value', (v) => {
  45. const enru = new Set(${db.esc(enruArr)});
  46. return !v || (v !== ${db.esc(emptyFieldValue)} && !enru.has(v[0]) && v.indexOf(${db.esc(a)}) >= 0);
  47. })`;
  48. } else {
  49. where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  50. }
  51. return where;
  52. }
  53. async selectBookIds(query) {
  54. const db = this.db;
  55. const idsArr = [];
  56. const tableBookIds = async(table, where) => {
  57. const rows = await db.select({
  58. table,
  59. rawResult: true,
  60. where: `
  61. const ids = ${where};
  62. const result = new Set();
  63. for (const id of ids) {
  64. const row = @unsafeRow(id);
  65. for (const bookId of row.bookIds)
  66. result.add(bookId);
  67. }
  68. return new Uint32Array(result);
  69. `
  70. });
  71. return rows[0].rawResult;
  72. };
  73. //авторы
  74. if (query.author && query.author !== '*') {
  75. const key = `book-ids-author-${query.author}`;
  76. let ids = await this.getCached(key);
  77. if (ids === null) {
  78. ids = await tableBookIds('author', this.getWhere(query.author));
  79. await this.putCached(key, ids);
  80. }
  81. idsArr.push(ids);
  82. }
  83. //серии
  84. if (query.series && query.series !== '*') {
  85. const key = `book-ids-series-${query.series}`;
  86. let ids = await this.getCached(key);
  87. if (ids === null) {
  88. ids = await tableBookIds('series', this.getWhere(query.series));
  89. await this.putCached(key, ids);
  90. }
  91. idsArr.push(ids);
  92. }
  93. //названия
  94. if (query.title && query.title !== '*') {
  95. const key = `book-ids-title-${query.title}`;
  96. let ids = await this.getCached(key);
  97. if (ids === null) {
  98. ids = await tableBookIds('title', this.getWhere(query.title));
  99. await this.putCached(key, ids);
  100. }
  101. idsArr.push(ids);
  102. }
  103. //жанры
  104. if (query.genre) {
  105. const key = `book-ids-genre-${query.genre}`;
  106. let ids = await this.getCached(key);
  107. if (ids === null) {
  108. const genreRows = await db.select({
  109. table: 'genre',
  110. rawResult: true,
  111. where: `
  112. const genres = ${db.esc(query.genre.split(','))};
  113. const ids = new Set();
  114. for (const g of genres) {
  115. for (const id of @indexLR('value', g, g))
  116. ids.add(id);
  117. }
  118. const result = new Set();
  119. for (const id of ids) {
  120. const row = @unsafeRow(id);
  121. for (const bookId of row.bookIds)
  122. result.add(bookId);
  123. }
  124. return new Uint32Array(result);
  125. `
  126. });
  127. ids = genreRows[0].rawResult;
  128. await this.putCached(key, ids);
  129. }
  130. idsArr.push(ids);
  131. }
  132. //языки
  133. if (query.lang) {
  134. const key = `book-ids-lang-${query.lang}`;
  135. let ids = await this.getCached(key);
  136. if (ids === null) {
  137. const langRows = await db.select({
  138. table: 'lang',
  139. rawResult: true,
  140. where: `
  141. const langs = ${db.esc(query.lang.split(','))};
  142. const ids = new Set();
  143. for (const l of langs) {
  144. for (const id of @indexLR('value', l, l))
  145. ids.add(id);
  146. }
  147. const result = new Set();
  148. for (const id of ids) {
  149. const row = @unsafeRow(id);
  150. for (const bookId of row.bookIds)
  151. result.add(bookId);
  152. }
  153. return new Uint32Array(result);
  154. `
  155. });
  156. ids = langRows[0].rawResult;
  157. await this.putCached(key, ids);
  158. }
  159. idsArr.push(ids);
  160. }
  161. //удаленные
  162. if (query.del !== undefined) {
  163. const key = `book-ids-del-${query.del}`;
  164. let ids = await this.getCached(key);
  165. if (ids === null) {
  166. ids = await tableBookIds('del', `@indexLR('value', ${db.esc(query.del)}, ${db.esc(query.del)})`);
  167. await this.putCached(key, ids);
  168. }
  169. idsArr.push(ids);
  170. }
  171. //дата поступления
  172. if (query.date) {
  173. const key = `book-ids-date-${query.date}`;
  174. let ids = await this.getCached(key);
  175. if (ids === null) {
  176. let [from = '', to = ''] = query.date.split(',');
  177. ids = await tableBookIds('date', `@indexLR('value', ${db.esc(from)} || undefined, ${db.esc(to)} || undefined)`);
  178. await this.putCached(key, ids);
  179. }
  180. idsArr.push(ids);
  181. }
  182. //оценка
  183. if (query.librate) {
  184. const key = `book-ids-librate-${query.librate}`;
  185. let ids = await this.getCached(key);
  186. if (ids === null) {
  187. const dateRows = await db.select({
  188. table: 'librate',
  189. rawResult: true,
  190. where: `
  191. const rates = ${db.esc(query.librate.split(',').map(n => parseInt(n, 10)).filter(n => !isNaN(n)))};
  192. const ids = new Set();
  193. for (const rate of rates) {
  194. for (const id of @indexLR('value', rate, rate))
  195. ids.add(id);
  196. }
  197. const result = new Set();
  198. for (const id of ids) {
  199. const row = @unsafeRow(id);
  200. for (const bookId of row.bookIds)
  201. result.add(bookId);
  202. }
  203. return new Uint32Array(result);
  204. `
  205. });
  206. ids = dateRows[0].rawResult;
  207. await this.putCached(key, ids);
  208. }
  209. idsArr.push(ids);
  210. }
  211. if (idsArr.length > 1) {
  212. //ищем пересечение множеств
  213. let proc = 0;
  214. let nextProc = 0;
  215. let inter = new Set(idsArr[0]);
  216. for (let i = 1; i < idsArr.length; i++) {
  217. const newInter = new Set();
  218. for (const id of idsArr[i]) {
  219. if (inter.has(id))
  220. newInter.add(id);
  221. //прерываемся иногда, чтобы не блокировать Event Loop
  222. proc++;
  223. if (proc >= nextProc) {
  224. nextProc += 10000;
  225. await utils.processLoop();
  226. }
  227. }
  228. inter = newInter;
  229. }
  230. return new Uint32Array(inter);
  231. } else if (idsArr.length == 1) {
  232. return idsArr[0];
  233. } else {
  234. return false;
  235. }
  236. }
  237. async fillBookIdMap(from) {
  238. if (this.bookIdMap[from])
  239. return this.bookIdMap[from];
  240. await this.lock.get();
  241. try {
  242. const data = await fs.readFile(`${this.config.dataDir}/db/${from}_id.map`, 'utf-8');
  243. const idMap = JSON.parse(data);
  244. idMap.arr = new Uint32Array(idMap.arr);
  245. idMap.map = new Map(idMap.map);
  246. this.bookIdMap[from] = idMap;
  247. return this.bookIdMap[from];
  248. } finally {
  249. this.lock.ret();
  250. }
  251. }
  252. async fillBookIdMapAll() {
  253. try {
  254. await this.fillBookIdMap('author');
  255. await this.fillBookIdMap('series');
  256. await this.fillBookIdMap('title');
  257. } catch (e) {
  258. throw new Error(`DbSearcher.fillBookIdMapAll error: ${e.message}`)
  259. }
  260. }
  261. async tableIdsFilter(from, query) {
  262. //т.к. авторы у книги идут списком (т.е. одна книга относиться сразу к нескольким авторам),
  263. //то в выборку по bookId могут попасть авторы, которые отсутствуют в критерии query.author,
  264. //поэтому дополнительно фильтруем
  265. let result = null;
  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 new Uint32Array(${this.getWhere(query.author)})`
  274. });
  275. authorIds = rows[0].rawResult;
  276. await this.putCached(key, authorIds);
  277. }
  278. result = new Set(authorIds);
  279. }
  280. return result;
  281. }
  282. async selectTableIds(from, query) {
  283. const db = this.db;
  284. const queryKey = this.queryKey(query);
  285. const tableKey = `${from}-table-ids-${queryKey}`;
  286. let tableIds = await this.getCached(tableKey);
  287. if (tableIds === null) {
  288. const bookKey = `book-ids-${queryKey}`;
  289. let bookIds = await this.getCached(bookKey);
  290. if (bookIds === null) {
  291. bookIds = await this.selectBookIds(query);
  292. await this.putCached(bookKey, bookIds);
  293. }
  294. //id книг (bookIds) нашли, теперь надо их смаппировать в id таблицы from (авторов, серий, названий)
  295. if (bookIds) {
  296. //т.к. авторы у книги идут списком, то дополнительно фильтруем
  297. const filter = await this.tableIdsFilter(from, query);
  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. if (!filter || filter.has(tableId))
  306. tableIdsSet.add(tableId);
  307. proc++;
  308. } else {
  309. const tableIdArr = idMap.map.get(bookId);
  310. if (tableIdArr) {
  311. for (const tableId of tableIdArr) {
  312. if (!filter || filter.has(tableId))
  313. tableIdsSet.add(tableId);
  314. proc++;
  315. }
  316. }
  317. }
  318. //прерываемся иногда, чтобы не блокировать Event Loop
  319. if (proc >= nextProc) {
  320. nextProc += 10000;
  321. await utils.processLoop();
  322. }
  323. }
  324. tableIds = new Uint32Array(tableIdsSet);
  325. } else {//bookIds пустой - критерии не заданы, значит берем все id из from
  326. const rows = await db.select({
  327. table: from,
  328. rawResult: true,
  329. where: `return new Uint32Array(@all())`
  330. });
  331. tableIds = rows[0].rawResult;
  332. }
  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. const slice = ids.slice(offset, offset + limit);
  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(Array.from(slice))})`
  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.queryCacheEnabled)
  475. return null;
  476. let result = null;
  477. const db = this.db;
  478. const memCache = this.memCache;
  479. if (this.queryCacheMemSize > 0 && memCache.has(key)) {//есть в недавних
  480. result = memCache.get(key);
  481. //изменим порядок ключей, для последующей правильной чистки старых
  482. memCache.delete(key);
  483. memCache.set(key, result);
  484. } else if (this.queryCacheDiskSize > 0) {//смотрим в таблице
  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. //заполняем кеш в памяти
  494. if (this.queryCacheMemSize > 0) {
  495. memCache.set(key, result);
  496. if (memCache.size > this.queryCacheMemSize) {
  497. //удаляем самый старый ключ-значение
  498. for (const k of memCache.keys()) {
  499. memCache.delete(k);
  500. break;
  501. }
  502. }
  503. }
  504. }
  505. }
  506. return result;
  507. }
  508. async putCached(key, value) {
  509. if (!this.queryCacheEnabled)
  510. return;
  511. const db = this.db;
  512. if (this.queryCacheMemSize > 0) {
  513. const memCache = this.memCache;
  514. memCache.set(key, value);
  515. if (memCache.size > this.queryCacheMemSize) {
  516. //удаляем самый старый ключ-значение
  517. for (const k of memCache.keys()) {
  518. memCache.delete(k);
  519. break;
  520. }
  521. }
  522. }
  523. if (this.queryCacheDiskSize > 0) {
  524. //кладем в таблицу асинхронно
  525. (async() => {
  526. try {
  527. await db.insert({
  528. table: 'query_cache',
  529. replace: true,
  530. rows: [{id: key, value}],
  531. });
  532. await db.insert({
  533. table: 'query_time',
  534. replace: true,
  535. rows: [{id: key, time: Date.now()}],
  536. });
  537. } catch(e) {
  538. console.error(`putCached: ${e.message}`);
  539. }
  540. })();
  541. }
  542. }
  543. async periodicCleanCache() {
  544. this.timer = null;
  545. const cleanInterval = this.config.cacheCleanInterval*60*1000;
  546. if (!cleanInterval)
  547. return;
  548. try {
  549. if (!this.queryCacheEnabled || this.queryCacheDiskSize <= 0)
  550. return;
  551. const db = this.db;
  552. let rows = await db.select({table: 'query_time', count: true});
  553. const delCount = rows[0].count - this.queryCacheDiskSize;
  554. if (delCount < 1)
  555. return;
  556. //выберем всех кандидатов на удаление
  557. //находим delCount минимальных по time
  558. rows = await db.select({
  559. table: 'query_time',
  560. rawResult: true,
  561. where: `
  562. const res = Array(${db.esc(delCount)}).fill({time: Date.now()});
  563. @unsafeIter(@all(), (r) => {
  564. if (r.time >= res[${db.esc(delCount - 1)}].time)
  565. return false;
  566. let ins = {id: r.id, time: r.time};
  567. for (let i = 0; i < res.length; i++) {
  568. if (!res[i].id || ins.time < res[i].time) {
  569. const t = res[i];
  570. res[i] = ins;
  571. ins = t;
  572. }
  573. if (!ins.id)
  574. break;
  575. }
  576. return false;
  577. });
  578. return res.filter(r => r.id).map(r => r.id);
  579. `
  580. });
  581. const ids = rows[0].rawResult;
  582. //удаляем
  583. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  584. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  585. //console.log('Cache clean', ids);
  586. } catch(e) {
  587. console.error(e.message);
  588. } finally {
  589. if (!this.closed) {
  590. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  591. }
  592. }
  593. }
  594. async close() {
  595. while (this.searchFlag > 0) {
  596. await utils.sleep(50);
  597. }
  598. this.searchCache = null;
  599. if (this.timer) {
  600. clearTimeout(this.timer);
  601. this.timer = null;
  602. }
  603. this.closed = true;
  604. }
  605. }
  606. module.exports = DbSearcher;