DbSearcher.js 15 KB

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