DbSearcher.js 15 KB

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