DbSearcher.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. }
  89. idsArr.push(seriesIds);
  90. }
  91. //названия
  92. if (query.title && query.title !== '*') {
  93. const titleKey = `select-ids-title-${query.title}`;
  94. let titleIds = await this.getCached(titleKey);
  95. if (titleIds === null) {
  96. const where = this.getWhere(query.title);
  97. let titleRows = await db.select({
  98. table: 'title',
  99. rawResult: true,
  100. where: `
  101. const ids = ${where};
  102. const result = new Set();
  103. for (const id of ids) {
  104. const row = @unsafeRow(id);
  105. for (const authorId of row.authorId)
  106. result.add(authorId);
  107. }
  108. return Array.from(result);
  109. `
  110. });
  111. titleIds = titleRows[0].rawResult;
  112. }
  113. idsArr.push(titleIds);
  114. //чистки памяти при тяжелых запросах
  115. if (this.config.lowMemoryMode && query.title[0] == '*') {
  116. utils.freeMemory();
  117. await db.freeMemory();
  118. }
  119. }
  120. //жанры
  121. if (query.genre) {
  122. const genreKey = `select-ids-genre-${query.genre}`;
  123. let genreIds = await this.getCached(genreKey);
  124. if (genreIds === null) {
  125. const genreRows = await db.select({
  126. table: 'genre',
  127. rawResult: true,
  128. where: `
  129. const genres = ${db.esc(query.genre.split(','))};
  130. const ids = new Set();
  131. for (const g of genres) {
  132. for (const id of @indexLR('value', g, g))
  133. ids.add(id);
  134. }
  135. const result = new Set();
  136. for (const id of ids) {
  137. const row = @unsafeRow(id);
  138. for (const authorId of row.authorId)
  139. result.add(authorId);
  140. }
  141. return Array.from(result);
  142. `
  143. });
  144. genreIds = genreRows[0].rawResult;
  145. }
  146. idsArr.push(genreIds);
  147. }
  148. //языки
  149. if (query.lang) {
  150. const langKey = `select-ids-lang-${query.lang}`;
  151. let langIds = await this.getCached(langKey);
  152. if (langIds === null) {
  153. const langRows = await db.select({
  154. table: 'lang',
  155. rawResult: true,
  156. where: `
  157. const langs = ${db.esc(query.lang.split(','))};
  158. const ids = new Set();
  159. for (const l of langs) {
  160. for (const id of @indexLR('value', l, l))
  161. ids.add(id);
  162. }
  163. const result = new Set();
  164. for (const id of ids) {
  165. const row = @unsafeRow(id);
  166. for (const authorId of row.authorId)
  167. result.add(authorId);
  168. }
  169. return Array.from(result);
  170. `
  171. });
  172. langIds = langRows[0].rawResult;
  173. }
  174. idsArr.push(langIds);
  175. }
  176. /*
  177. //ищем пересечение множеств
  178. idsArr.push(authorIds);
  179. if (idsArr.length > 1) {
  180. const idsSetArr = idsArr.map(ids => new Set(ids));
  181. authorIds = Array.from(utils.intersectSet(idsSetArr));
  182. }
  183. //сортировка
  184. authorIds.sort((a, b) => a - b);
  185. */
  186. //ищем пересечение множеств, работает быстрее предыдущего
  187. if (idsArr.length) {
  188. idsArr.push(authorIds);
  189. let proc = 0;
  190. let nextProc = 0;
  191. let inter = new Set(idsArr[0]);
  192. for (let i = 1; i < idsArr.length; i++) {
  193. const newInter = new Set();
  194. for (const id of idsArr[i]) {
  195. if (inter.has(id))
  196. newInter.add(id);
  197. //прерываемся иногда, чтобы не блокировать Event Loop
  198. proc++;
  199. if (proc >= nextProc) {
  200. nextProc += 10000;
  201. await utils.processLoop();
  202. }
  203. }
  204. inter = newInter;
  205. }
  206. authorIds = Array.from(inter);
  207. }
  208. //сортировка
  209. authorIds.sort((a, b) => a - b);
  210. return authorIds;
  211. }
  212. queryKey(q) {
  213. return JSON.stringify([q.author, q.series, q.title, q.genre, q.lang]);
  214. }
  215. async getCached(key) {
  216. if (!this.config.queryCacheEnabled)
  217. return null;
  218. let result = null;
  219. const db = this.db;
  220. const memCache = this.memCache;
  221. if (memCache.has(key)) {//есть в недавних
  222. result = memCache.get(key);
  223. //изменим порядок ключей, для последующей правильной чистки старых
  224. memCache.delete(key);
  225. memCache.set(key, result);
  226. } else {//смотрим в таблице
  227. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  228. if (rows.length) {//нашли в кеше
  229. await db.insert({
  230. table: 'query_time',
  231. replace: true,
  232. rows: [{id: key, time: Date.now()}],
  233. });
  234. result = rows[0].value;
  235. memCache.set(key, result);
  236. if (memCache.size > maxMemCacheSize) {
  237. //удаляем самый старый ключ-значение
  238. for (const k of memCache.keys()) {
  239. memCache.delete(k);
  240. break;
  241. }
  242. }
  243. }
  244. }
  245. return result;
  246. }
  247. async putCached(key, value) {
  248. if (!this.config.queryCacheEnabled)
  249. return;
  250. const db = this.db;
  251. const memCache = this.memCache;
  252. memCache.set(key, value);
  253. if (memCache.size > maxMemCacheSize) {
  254. //удаляем самый старый ключ-значение
  255. for (const k of memCache.keys()) {
  256. memCache.delete(k);
  257. break;
  258. }
  259. }
  260. //кладем в таблицу
  261. await db.insert({
  262. table: 'query_cache',
  263. replace: true,
  264. rows: [{id: key, value}],
  265. });
  266. await db.insert({
  267. table: 'query_time',
  268. replace: true,
  269. rows: [{id: key, time: Date.now()}],
  270. });
  271. }
  272. async search(query) {
  273. if (this.closed)
  274. throw new Error('DbSearcher closed');
  275. this.searchFlag++;
  276. try {
  277. const db = this.db;
  278. const key = `author-ids-${this.queryKey(query)}`;
  279. //сначала попробуем найти в кеше
  280. let authorIds = await this.getCached(key);
  281. if (authorIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  282. authorIds = await this.selectAuthorIds(query);
  283. await this.putCached(key, authorIds);
  284. }
  285. const totalFound = authorIds.length;
  286. let limit = (query.limit ? query.limit : 100);
  287. limit = (limit > 1000 ? 1000 : limit);
  288. const offset = (query.offset ? query.offset : 0);
  289. //выборка найденных авторов
  290. const result = await db.select({
  291. table: 'author',
  292. map: `(r) => ({id: r.id, author: r.author, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  293. where: `@@id(${db.esc(authorIds.slice(offset, offset + limit))})`
  294. });
  295. return {result, totalFound};
  296. } finally {
  297. this.searchFlag--;
  298. }
  299. }
  300. async getBookList(authorId) {
  301. if (this.closed)
  302. throw new Error('DbSearcher closed');
  303. this.searchFlag++;
  304. try {
  305. const db = this.db;
  306. //выборка книг автора по authorId
  307. const rows = await db.select({
  308. table: 'author_book',
  309. where: `@@id(${db.esc(authorId)})`
  310. });
  311. let author = '';
  312. let books = '';
  313. if (rows.length) {
  314. author = rows[0].author;
  315. books = rows[0].books;
  316. }
  317. return {author, books};
  318. } finally {
  319. this.searchFlag--;
  320. }
  321. }
  322. async getSeriesBookList(series) {
  323. if (this.closed)
  324. throw new Error('DbSearcher closed');
  325. this.searchFlag++;
  326. try {
  327. const db = this.db;
  328. series = series.toLowerCase();
  329. //выборка серии по названию серии
  330. let rows = await db.select({
  331. table: 'series',
  332. where: `@@dirtyIndexLR('value', ${db.esc(series)}, ${db.esc(series)})`
  333. });
  334. let books;
  335. if (rows.length) {
  336. //выборка книг серии
  337. rows = await db.select({
  338. table: 'series_book',
  339. where: `@@id(${rows[0].id})`
  340. });
  341. if (rows.length)
  342. books = rows[0].books;
  343. }
  344. return {books: (books && books.length ? JSON.stringify(books) : '')};
  345. } finally {
  346. this.searchFlag--;
  347. }
  348. }
  349. async periodicCleanCache() {
  350. this.timer = null;
  351. const cleanInterval = this.config.cacheCleanInterval*60*1000;
  352. if (!cleanInterval)
  353. return;
  354. try {
  355. const db = this.db;
  356. const oldThres = Date.now() - cleanInterval;
  357. //выберем всех кандидатов на удаление
  358. const rows = await db.select({
  359. table: 'query_time',
  360. where: `
  361. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  362. `
  363. });
  364. const ids = [];
  365. for (const row of rows)
  366. ids.push(row.id);
  367. //удаляем
  368. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  369. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  370. //console.log('Cache clean', ids);
  371. } catch(e) {
  372. console.error(e.message);
  373. } finally {
  374. if (!this.closed) {
  375. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  376. }
  377. }
  378. }
  379. async close() {
  380. while (this.searchFlag > 0) {
  381. await utils.sleep(50);
  382. }
  383. this.searchCache = null;
  384. if (this.timer) {
  385. clearTimeout(this.timer);
  386. this.timer = null;
  387. }
  388. this.closed = true;
  389. }
  390. }
  391. module.exports = DbSearcher;