DbSearcher.js 18 KB

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