DbSearcher.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. queryKey(q) {
  217. return JSON.stringify([q.author, q.series, q.title, q.genre, q.lang]);
  218. }
  219. async getCached(key) {
  220. if (!this.config.queryCacheEnabled)
  221. return null;
  222. let result = null;
  223. const db = this.db;
  224. const memCache = this.memCache;
  225. if (memCache.has(key)) {//есть в недавних
  226. result = memCache.get(key);
  227. //изменим порядок ключей, для последующей правильной чистки старых
  228. memCache.delete(key);
  229. memCache.set(key, result);
  230. } else {//смотрим в таблице
  231. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  232. if (rows.length) {//нашли в кеше
  233. await db.insert({
  234. table: 'query_time',
  235. replace: true,
  236. rows: [{id: key, time: Date.now()}],
  237. });
  238. result = rows[0].value;
  239. memCache.set(key, result);
  240. if (memCache.size > maxMemCacheSize) {
  241. //удаляем самый старый ключ-значение
  242. for (const k of memCache.keys()) {
  243. memCache.delete(k);
  244. break;
  245. }
  246. }
  247. }
  248. }
  249. return result;
  250. }
  251. async putCached(key, value) {
  252. if (!this.config.queryCacheEnabled)
  253. return;
  254. const db = this.db;
  255. const memCache = this.memCache;
  256. memCache.set(key, value);
  257. if (memCache.size > maxMemCacheSize) {
  258. //удаляем самый старый ключ-значение
  259. for (const k of memCache.keys()) {
  260. memCache.delete(k);
  261. break;
  262. }
  263. }
  264. //кладем в таблицу
  265. await db.insert({
  266. table: 'query_cache',
  267. replace: true,
  268. rows: [{id: key, value}],
  269. });
  270. await db.insert({
  271. table: 'query_time',
  272. replace: true,
  273. rows: [{id: key, time: Date.now()}],
  274. });
  275. }
  276. async search(query) {
  277. if (this.closed)
  278. throw new Error('DbSearcher closed');
  279. this.searchFlag++;
  280. try {
  281. const db = this.db;
  282. const key = `author-ids-${this.queryKey(query)}`;
  283. //сначала попробуем найти в кеше
  284. let authorIds = await this.getCached(key);
  285. if (authorIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  286. authorIds = await this.selectAuthorIds(query);
  287. await this.putCached(key, authorIds);
  288. }
  289. const totalFound = authorIds.length;
  290. let limit = (query.limit ? query.limit : 100);
  291. limit = (limit > 1000 ? 1000 : limit);
  292. const offset = (query.offset ? query.offset : 0);
  293. //выборка найденных авторов
  294. const result = await db.select({
  295. table: 'author',
  296. map: `(r) => ({id: r.id, author: r.author, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  297. where: `@@id(${db.esc(authorIds.slice(offset, offset + limit))})`
  298. });
  299. return {result, totalFound};
  300. } finally {
  301. this.searchFlag--;
  302. }
  303. }
  304. async getBookList(authorId) {
  305. if (this.closed)
  306. throw new Error('DbSearcher closed');
  307. this.searchFlag++;
  308. try {
  309. const db = this.db;
  310. //выборка книг автора по authorId
  311. const rows = await db.select({
  312. table: 'author_book',
  313. where: `@@id(${db.esc(authorId)})`
  314. });
  315. let author = '';
  316. let books = '';
  317. if (rows.length) {
  318. author = rows[0].author;
  319. books = rows[0].books;
  320. }
  321. return {author, books};
  322. } finally {
  323. this.searchFlag--;
  324. }
  325. }
  326. async getSeriesBookList(series) {
  327. if (this.closed)
  328. throw new Error('DbSearcher closed');
  329. this.searchFlag++;
  330. try {
  331. const db = this.db;
  332. series = series.toLowerCase();
  333. //выборка серии по названию серии
  334. let rows = await db.select({
  335. table: 'series',
  336. where: `@@dirtyIndexLR('value', ${db.esc(series)}, ${db.esc(series)})`
  337. });
  338. let books;
  339. if (rows.length) {
  340. //выборка книг серии
  341. rows = await db.select({
  342. table: 'series_book',
  343. where: `@@id(${rows[0].id})`
  344. });
  345. if (rows.length)
  346. books = rows[0].books;
  347. }
  348. return {books: (books && books.length ? JSON.stringify(books) : '')};
  349. } finally {
  350. this.searchFlag--;
  351. }
  352. }
  353. async periodicCleanCache() {
  354. this.timer = null;
  355. const cleanInterval = this.config.cacheCleanInterval*60*1000;
  356. if (!cleanInterval)
  357. return;
  358. try {
  359. const db = this.db;
  360. const oldThres = Date.now() - cleanInterval;
  361. //выберем всех кандидатов на удаление
  362. const rows = await db.select({
  363. table: 'query_time',
  364. where: `
  365. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  366. `
  367. });
  368. const ids = [];
  369. for (const row of rows)
  370. ids.push(row.id);
  371. //удаляем
  372. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  373. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  374. //console.log('Cache clean', ids);
  375. } catch(e) {
  376. console.error(e.message);
  377. } finally {
  378. if (!this.closed) {
  379. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  380. }
  381. }
  382. }
  383. async close() {
  384. while (this.searchFlag > 0) {
  385. await utils.sleep(50);
  386. }
  387. this.searchCache = null;
  388. if (this.timer) {
  389. clearTimeout(this.timer);
  390. this.timer = null;
  391. }
  392. this.closed = true;
  393. }
  394. }
  395. module.exports = DbSearcher;