DbSearcher.js 15 KB

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