DbSearcher.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. //const _ = require('lodash');
  2. const utils = require('./utils');
  3. const maxMemCacheSize = 100;
  4. const emptyFieldValue = '?';
  5. const maxUtf8Char = String.fromCodePoint(0xFFFFF);
  6. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  7. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  8. const enruArr = (ruAlphabet + enAlphabet).split('');
  9. class DbSearcher {
  10. constructor(config, db) {
  11. this.config = config;
  12. this.db = db;
  13. this.searchFlag = 0;
  14. this.timer = null;
  15. this.closed = false;
  16. this.memCache = new Map();
  17. this.periodicCleanCache();//no await
  18. }
  19. getWhere(a) {
  20. const db = this.db;
  21. a = a.toLowerCase();
  22. let where;
  23. //особая обработка префиксов
  24. if (a[0] == '=') {
  25. a = a.substring(1);
  26. where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a)})`;
  27. } else if (a[0] == '*') {
  28. a = a.substring(1);
  29. where = `@indexIter('value', (v) => (v !== ${db.esc(emptyFieldValue)} && v.indexOf(${db.esc(a)}) >= 0) )`;
  30. } else if (a[0] == '#') {
  31. a = a.substring(1);
  32. where = `@indexIter('value', (v) => {
  33. const enru = new Set(${db.esc(enruArr)});
  34. return !v || (v !== ${db.esc(emptyFieldValue)} && !enru.has(v[0]) && v.indexOf(${db.esc(a)}) >= 0);
  35. })`;
  36. } else {
  37. where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  38. }
  39. return where;
  40. }
  41. async selectAuthorIds(query) {
  42. const db = this.db;
  43. const authorKеy = `select-ids-author-${query.author}`;
  44. let authorIds = await this.getCached(authorKеy);
  45. //сначала выберем все id авторов по фильтру
  46. //порядок id соответствует ASC-сортировке по author
  47. if (authorIds === null) {
  48. if (query.author && query.author !== '*') {
  49. const where = this.getWhere(query.author);
  50. const authorRows = await db.select({
  51. table: 'author',
  52. rawResult: true,
  53. where: `return Array.from(${where})`,
  54. });
  55. authorIds = authorRows[0].rawResult;
  56. } else {//все авторы
  57. const authorRows = await db.select({
  58. table: 'author',
  59. rawResult: true,
  60. where: `return Array.from(@all())`,
  61. });
  62. authorIds = authorRows[0].rawResult;
  63. }
  64. await this.putCached(authorKеy, authorIds);
  65. }
  66. const idsArr = [];
  67. //серии
  68. if (query.series && query.series !== '*') {
  69. const seriesKеy = `select-ids-series-${query.series}`;
  70. let seriesIds = await this.getCached(seriesKеy);
  71. if (seriesIds === null) {
  72. const where = this.getWhere(query.series);
  73. const seriesRows = await db.select({
  74. table: 'series',
  75. rawResult: true,
  76. where: `
  77. const ids = ${where};
  78. const result = new Set();
  79. for (const id of ids) {
  80. const row = @unsafeRow(id);
  81. for (const authorId of row.authorId)
  82. result.add(authorId);
  83. }
  84. return Array.from(result);
  85. `
  86. });
  87. seriesIds = seriesRows[0].rawResult;
  88. await this.putCached(seriesKеy, seriesIds);
  89. }
  90. idsArr.push(seriesIds);
  91. }
  92. //названия
  93. if (query.title && query.title !== '*') {
  94. const titleKey = `select-ids-title-${query.title}`;
  95. let titleIds = await this.getCached(titleKey);
  96. if (titleIds === null) {
  97. const where = this.getWhere(query.title);
  98. let titleRows = await db.select({
  99. table: 'title',
  100. rawResult: true,
  101. where: `
  102. const ids = ${where};
  103. const result = new Set();
  104. for (const id of ids) {
  105. const row = @unsafeRow(id);
  106. for (const authorId of row.authorId)
  107. result.add(authorId);
  108. }
  109. return Array.from(result);
  110. `
  111. });
  112. titleIds = titleRows[0].rawResult;
  113. await this.putCached(titleKey, titleIds);
  114. }
  115. idsArr.push(titleIds);
  116. //чистки памяти при тяжелых запросах
  117. if (this.config.lowMemoryMode && query.title[0] == '*') {
  118. utils.freeMemory();
  119. await db.freeMemory();
  120. }
  121. }
  122. //жанры
  123. if (query.genre) {
  124. const genreKey = `select-ids-genre-${query.genre}`;
  125. let genreIds = await this.getCached(genreKey);
  126. if (genreIds === null) {
  127. const genreRows = await db.select({
  128. table: 'genre',
  129. rawResult: true,
  130. where: `
  131. const genres = ${db.esc(query.genre.split(','))};
  132. const ids = new Set();
  133. for (const g of genres) {
  134. for (const id of @indexLR('value', g, g))
  135. ids.add(id);
  136. }
  137. const result = new Set();
  138. for (const id of ids) {
  139. const row = @unsafeRow(id);
  140. for (const authorId of row.authorId)
  141. result.add(authorId);
  142. }
  143. return Array.from(result);
  144. `
  145. });
  146. genreIds = genreRows[0].rawResult;
  147. await this.putCached(genreKey, genreIds);
  148. }
  149. idsArr.push(genreIds);
  150. }
  151. //языки
  152. if (query.lang) {
  153. const langKey = `select-ids-lang-${query.lang}`;
  154. let langIds = await this.getCached(langKey);
  155. if (langIds === null) {
  156. const langRows = await db.select({
  157. table: 'lang',
  158. rawResult: true,
  159. where: `
  160. const langs = ${db.esc(query.lang.split(','))};
  161. const ids = new Set();
  162. for (const l of langs) {
  163. for (const id of @indexLR('value', l, l))
  164. ids.add(id);
  165. }
  166. const result = new Set();
  167. for (const id of ids) {
  168. const row = @unsafeRow(id);
  169. for (const authorId of row.authorId)
  170. result.add(authorId);
  171. }
  172. return Array.from(result);
  173. `
  174. });
  175. langIds = langRows[0].rawResult;
  176. await this.putCached(langKey, langIds);
  177. }
  178. idsArr.push(langIds);
  179. }
  180. /*
  181. //ищем пересечение множеств
  182. idsArr.push(authorIds);
  183. if (idsArr.length > 1) {
  184. const idsSetArr = idsArr.map(ids => new Set(ids));
  185. authorIds = Array.from(utils.intersectSet(idsSetArr));
  186. }
  187. //сортировка
  188. authorIds.sort((a, b) => a - b);
  189. */
  190. //ищем пересечение множеств, работает быстрее предыдущего
  191. if (idsArr.length) {
  192. idsArr.push(authorIds);
  193. let proc = 0;
  194. let nextProc = 0;
  195. let inter = new Set(idsArr[0]);
  196. for (let i = 1; i < idsArr.length; i++) {
  197. const newInter = new Set();
  198. for (const id of idsArr[i]) {
  199. if (inter.has(id))
  200. newInter.add(id);
  201. //прерываемся иногда, чтобы не блокировать Event Loop
  202. proc++;
  203. if (proc >= nextProc) {
  204. nextProc += 10000;
  205. await utils.processLoop();
  206. }
  207. }
  208. inter = newInter;
  209. }
  210. authorIds = Array.from(inter);
  211. }
  212. //сортировка
  213. authorIds.sort((a, b) => a - b);
  214. return authorIds;
  215. }
  216. async selectSeriesIds(query) {
  217. const db = this.db;
  218. let seriesIds = [];
  219. //серии
  220. if (query.series && query.series !== '*') {
  221. const where = this.getWhere(query.series);
  222. const seriesRows = await db.select({
  223. table: 'series',
  224. rawResult: true,
  225. where: `
  226. const ids = ${where};
  227. const result = new Set();
  228. for (const id of ids) {
  229. const row = @unsafeRow(id);
  230. for (const authorId of row.authorId)
  231. result.add(authorId);
  232. }
  233. return Array.from(result);
  234. `
  235. });
  236. seriesIds = seriesRows[0].rawResult;
  237. } else {
  238. const authorRows = await db.select({
  239. table: 'series',
  240. rawResult: true,
  241. where: `return Array.from(@all())`,
  242. });
  243. seriesIds = authorRows[0].rawResult;
  244. }
  245. seriesIds.sort((a, b) => a - b);
  246. return seriesIds;
  247. }
  248. queryKey(q) {
  249. return JSON.stringify([q.author, q.series, q.title, q.genre, q.lang]);
  250. }
  251. async getCached(key) {
  252. if (!this.config.queryCacheEnabled)
  253. return null;
  254. let result = null;
  255. const db = this.db;
  256. const memCache = this.memCache;
  257. if (memCache.has(key)) {//есть в недавних
  258. result = memCache.get(key);
  259. //изменим порядок ключей, для последующей правильной чистки старых
  260. memCache.delete(key);
  261. memCache.set(key, result);
  262. } else {//смотрим в таблице
  263. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  264. if (rows.length) {//нашли в кеше
  265. await db.insert({
  266. table: 'query_time',
  267. replace: true,
  268. rows: [{id: key, time: Date.now()}],
  269. });
  270. result = rows[0].value;
  271. memCache.set(key, result);
  272. if (memCache.size > maxMemCacheSize) {
  273. //удаляем самый старый ключ-значение
  274. for (const k of memCache.keys()) {
  275. memCache.delete(k);
  276. break;
  277. }
  278. }
  279. }
  280. }
  281. return result;
  282. }
  283. async putCached(key, value) {
  284. if (!this.config.queryCacheEnabled)
  285. return;
  286. const db = this.db;
  287. const memCache = this.memCache;
  288. memCache.set(key, value);
  289. if (memCache.size > maxMemCacheSize) {
  290. //удаляем самый старый ключ-значение
  291. for (const k of memCache.keys()) {
  292. memCache.delete(k);
  293. break;
  294. }
  295. }
  296. //кладем в таблицу
  297. await db.insert({
  298. table: 'query_cache',
  299. replace: true,
  300. rows: [{id: key, value}],
  301. });
  302. await db.insert({
  303. table: 'query_time',
  304. replace: true,
  305. rows: [{id: key, time: Date.now()}],
  306. });
  307. }
  308. async authorSearch(query) {
  309. if (this.closed)
  310. throw new Error('DbSearcher closed');
  311. this.searchFlag++;
  312. try {
  313. const db = this.db;
  314. const key = `author-ids-${this.queryKey(query)}`;
  315. //сначала попробуем найти в кеше
  316. let authorIds = await this.getCached(key);
  317. if (authorIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  318. authorIds = await this.selectAuthorIds(query);
  319. await this.putCached(key, authorIds);
  320. }
  321. const totalFound = authorIds.length;
  322. let limit = (query.limit ? query.limit : 100);
  323. limit = (limit > 1000 ? 1000 : limit);
  324. const offset = (query.offset ? query.offset : 0);
  325. //выборка найденных авторов
  326. const result = await db.select({
  327. table: 'author',
  328. map: `(r) => ({id: r.id, author: r.author, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  329. where: `@@id(${db.esc(authorIds.slice(offset, offset + limit))})`
  330. });
  331. return {result, totalFound};
  332. } finally {
  333. this.searchFlag--;
  334. }
  335. }
  336. async seriesSearch(query) {
  337. if (this.closed)
  338. throw new Error('DbSearcher closed');
  339. this.searchFlag++;
  340. try {
  341. const db = this.db;
  342. const key = `series-ids-${this.queryKey(query)}`;
  343. //сначала попробуем найти в кеше
  344. let seriesIds = await this.getCached(key);
  345. if (seriesIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  346. seriesIds = await this.selectSeriesIds(query);
  347. await this.putCached(key, seriesIds);
  348. }
  349. const totalFound = seriesIds.length;
  350. let limit = (query.limit ? query.limit : 100);
  351. limit = (limit > 1000 ? 1000 : limit);
  352. const offset = (query.offset ? query.offset : 0);
  353. //выборка найденных авторов
  354. const result = await db.select({
  355. table: 'series_book',
  356. map: `(r) => ({id: r.id, series: r.series, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  357. where: `@@id(${db.esc(seriesIds.slice(offset, offset + limit))})`
  358. });
  359. return {result, totalFound};
  360. } finally {
  361. this.searchFlag--;
  362. }
  363. }
  364. async getAuthorBookList(authorId) {
  365. if (this.closed)
  366. throw new Error('DbSearcher closed');
  367. if (!authorId)
  368. return {author: '', books: ''};
  369. this.searchFlag++;
  370. try {
  371. const db = this.db;
  372. //выборка книг автора по authorId
  373. const rows = await db.select({
  374. table: 'author_book',
  375. where: `@@id(${db.esc(authorId)})`
  376. });
  377. let author = '';
  378. let books = '';
  379. if (rows.length) {
  380. author = rows[0].author;
  381. books = rows[0].books;
  382. }
  383. return {author, books};
  384. } finally {
  385. this.searchFlag--;
  386. }
  387. }
  388. async getSeriesBookList(series, seriesId) {
  389. if (this.closed)
  390. throw new Error('DbSearcher closed');
  391. if (!series && !seriesId)
  392. return {books: ''};
  393. this.searchFlag++;
  394. try {
  395. const db = this.db;
  396. series = series.toLowerCase();
  397. //выборка серии по названию серии
  398. let rows = await db.select({
  399. table: 'series',
  400. where: `@@dirtyIndexLR('value', ${db.esc(series)}, ${db.esc(series)})`
  401. });
  402. let books;
  403. if (rows.length) {
  404. //выборка книг серии
  405. rows = await db.select({
  406. table: 'series_book',
  407. where: `@@id(${rows[0].id})`
  408. });
  409. if (rows.length)
  410. books = rows[0].books;
  411. }
  412. return {books: (books && books.length ? JSON.stringify(books) : '')};
  413. } finally {
  414. this.searchFlag--;
  415. }
  416. }
  417. async periodicCleanCache() {
  418. this.timer = null;
  419. const cleanInterval = this.config.cacheCleanInterval*60*1000;
  420. if (!cleanInterval)
  421. return;
  422. try {
  423. const db = this.db;
  424. const oldThres = Date.now() - cleanInterval;
  425. //выберем всех кандидатов на удаление
  426. const rows = await db.select({
  427. table: 'query_time',
  428. where: `
  429. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  430. `
  431. });
  432. const ids = [];
  433. for (const row of rows)
  434. ids.push(row.id);
  435. //удаляем
  436. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  437. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  438. //console.log('Cache clean', ids);
  439. } catch(e) {
  440. console.error(e.message);
  441. } finally {
  442. if (!this.closed) {
  443. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  444. }
  445. }
  446. }
  447. async close() {
  448. while (this.searchFlag > 0) {
  449. await utils.sleep(50);
  450. }
  451. this.searchCache = null;
  452. if (this.timer) {
  453. clearTimeout(this.timer);
  454. this.timer = null;
  455. }
  456. this.closed = true;
  457. }
  458. }
  459. module.exports = DbSearcher;