DbSearcher.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. //const _ = require('lodash');
  2. const utils = require('./utils');
  3. const maxMemCacheSize = 100;
  4. const maxUtf8Char = String.fromCodePoint(0xFFFFF);
  5. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  6. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  7. const enruArr = (ruAlphabet + enAlphabet).split('');
  8. class DbSearcher {
  9. constructor(config, db) {
  10. this.config = config;
  11. this.db = db;
  12. this.searchFlag = 0;
  13. this.timer = null;
  14. this.closed = false;
  15. this.searchCache = {
  16. memCache: new Map(),
  17. authorIdsAll: false,
  18. };
  19. this.periodicCleanCache();//no await
  20. }
  21. getWhere(a) {
  22. const db = this.db;
  23. a = a.toLowerCase();
  24. let where;
  25. //особая обработка префиксов
  26. if (a[0] == '=') {
  27. a = a.substring(1);
  28. where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a)})`;
  29. } else if (a[0] == '*') {
  30. a = a.substring(1);
  31. where = `@indexIter('value', (v) => (v.indexOf(${db.esc(a)}) >= 0) )`;
  32. } else if (a[0] == '#') {
  33. a = a.substring(1);
  34. where = `@indexIter('value', (v) => {
  35. const enru = new Set(${db.esc(enruArr)});
  36. return !v || (!enru.has(v[0].toLowerCase()) && v.indexOf(${db.esc(a)}) >= 0);
  37. })`;
  38. } else {
  39. where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  40. }
  41. return where;
  42. }
  43. async selectAuthorIds(query) {
  44. const db = this.db;
  45. let authorIds = [];
  46. //сначала выберем все id авторов по фильтру
  47. //порядок id соответсвует ASC-сортировке по author
  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. if (!this.searchCache.authorIdsAll) {
  58. const authorRows = await db.select({
  59. table: 'author',
  60. rawResult: true,
  61. where: `return Array.from(@all())`,
  62. });
  63. authorIds = authorRows[0].rawResult;
  64. this.searchCache.authorIdsAll = authorIds;
  65. } else {//оптимизация
  66. authorIds = this.searchCache.authorIdsAll;
  67. }
  68. }
  69. const idsArr = [];
  70. //серии
  71. if (query.series && query.series !== '*') {
  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. idsArr.push(new Set(seriesRows[0].rawResult));
  88. }
  89. //названия
  90. if (query.title && query.title !== '*') {
  91. const where = this.getWhere(query.title);
  92. let titleRows = await db.select({
  93. table: 'title',
  94. rawResult: true,
  95. where: `
  96. const ids = ${where};
  97. const result = new Set();
  98. for (const id of ids) {
  99. const row = @unsafeRow(id);
  100. for (const authorId of row.authorId)
  101. result.add(authorId);
  102. }
  103. return Array.from(result);
  104. `
  105. });
  106. idsArr.push(new Set(titleRows[0].rawResult));
  107. //чистки памяти при тяжелых запросах
  108. if (this.config.lowMemoryMode && query.title[0] == '*') {
  109. titleRows = null;
  110. utils.freeMemory();
  111. await db.freeMemory();
  112. }
  113. }
  114. //жанры
  115. if (query.genre) {
  116. const genreRows = await db.select({
  117. table: 'genre',
  118. rawResult: true,
  119. where: `
  120. const genres = ${db.esc(query.genre.split(','))};
  121. const ids = new Set();
  122. for (const g of genres) {
  123. for (const id of @indexLR('value', g, g))
  124. ids.add(id);
  125. }
  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(new Set(genreRows[0].rawResult));
  136. }
  137. //языки
  138. if (query.lang) {
  139. const langRows = await db.select({
  140. table: 'lang',
  141. rawResult: true,
  142. where: `
  143. const langs = ${db.esc(query.lang.split(','))};
  144. const ids = new Set();
  145. for (const l of langs) {
  146. for (const id of @indexLR('value', l, l))
  147. ids.add(id);
  148. }
  149. const result = new Set();
  150. for (const id of ids) {
  151. const row = @unsafeRow(id);
  152. for (const authorId of row.authorId)
  153. result.add(authorId);
  154. }
  155. return Array.from(result);
  156. `
  157. });
  158. idsArr.push(new Set(langRows[0].rawResult));
  159. }
  160. if (idsArr.length) {
  161. //ищем пересечение множеств
  162. idsArr.push(new Set(authorIds));
  163. authorIds = Array.from(utils.intersectSet(idsArr));
  164. }
  165. //сортировка
  166. authorIds.sort((a, b) => a - b);
  167. return authorIds;
  168. }
  169. queryKey(q) {
  170. return JSON.stringify([q.author, q.series, q.title, q.genre, q.lang]);
  171. }
  172. async getCached(key) {
  173. if (!this.config.queryCacheEnabled)
  174. return null;
  175. let result = null;
  176. const db = this.db;
  177. const memCache = this.searchCache.memCache;
  178. if (memCache.has(key)) {//есть в недавних
  179. result = memCache.get(key);
  180. //изменим порядок ключей, для последующей правильной чистки старых
  181. memCache.delete(key);
  182. memCache.set(key, result);
  183. } else {//смотрим в таблице
  184. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  185. if (rows.length) {//нашли в кеше
  186. await db.insert({
  187. table: 'query_time',
  188. replace: true,
  189. rows: [{id: key, time: Date.now()}],
  190. });
  191. result = rows[0].value;
  192. memCache.set(key, result);
  193. if (memCache.size > maxMemCacheSize) {
  194. //удаляем самый старый ключ-значение
  195. for (const k of memCache.keys()) {
  196. memCache.delete(k);
  197. break;
  198. }
  199. }
  200. }
  201. }
  202. return result;
  203. }
  204. async putCached(key, value) {
  205. if (!this.config.queryCacheEnabled)
  206. return;
  207. const db = this.db;
  208. const memCache = this.searchCache.memCache;
  209. memCache.set(key, value);
  210. if (memCache.size > maxMemCacheSize) {
  211. //удаляем самый старый ключ-значение
  212. for (const k of memCache.keys()) {
  213. memCache.delete(k);
  214. break;
  215. }
  216. }
  217. //кладем в таблицу
  218. await db.insert({
  219. table: 'query_cache',
  220. replace: true,
  221. rows: [{id: key, value}],
  222. });
  223. await db.insert({
  224. table: 'query_time',
  225. replace: true,
  226. rows: [{id: key, time: Date.now()}],
  227. });
  228. }
  229. async search(query) {
  230. if (this.closed)
  231. throw new Error('DbSearcher closed');
  232. this.searchFlag++;
  233. try {
  234. const db = this.db;
  235. const key = `author-ids-${this.queryKey(query)}`;
  236. //сначала попробуем найти в кеше
  237. let authorIds = await this.getCached(key);
  238. if (authorIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  239. authorIds = await this.selectAuthorIds(query);
  240. await this.putCached(key, authorIds);
  241. }
  242. const totalFound = authorIds.length;
  243. let limit = (query.limit ? query.limit : 100);
  244. limit = (limit > 1000 ? 1000 : limit);
  245. const offset = (query.offset ? query.offset : 0);
  246. //выборка найденных авторов
  247. const result = await db.select({
  248. table: 'author',
  249. map: `(r) => ({id: r.id, author: r.author, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  250. where: `@@id(${db.esc(authorIds.slice(offset, offset + limit))})`
  251. });
  252. return {result, totalFound};
  253. } finally {
  254. this.searchFlag--;
  255. }
  256. }
  257. async getBookList(authorId) {
  258. if (this.closed)
  259. throw new Error('DbSearcher closed');
  260. this.searchFlag++;
  261. try {
  262. const db = this.db;
  263. //выборка книг автора по authorId
  264. const rows = await db.select({
  265. table: 'author_book',
  266. where: `@@id(${db.esc(authorId)})`
  267. });
  268. let author = '';
  269. let books = '';
  270. if (rows.length) {
  271. author = rows[0].author;
  272. books = rows[0].books;
  273. }
  274. return {author, books};
  275. } finally {
  276. this.searchFlag--;
  277. }
  278. }
  279. async getSeriesBookList(series) {
  280. if (this.closed)
  281. throw new Error('DbSearcher closed');
  282. this.searchFlag++;
  283. try {
  284. const db = this.db;
  285. series = series.toLowerCase();
  286. //выборка серии по названию серии
  287. let rows = await db.select({
  288. table: 'series',
  289. where: `@@dirtyIndexLR('value', ${db.esc(series)}, ${db.esc(series)})`
  290. });
  291. let books;
  292. if (rows.length) {
  293. //выборка книг серии
  294. rows = await db.select({
  295. table: 'series_book',
  296. where: `@@id(${rows[0].id})`
  297. });
  298. if (rows.length)
  299. books = rows[0].books;
  300. }
  301. return {books: (books && books.length ? JSON.stringify(books) : '')};
  302. } finally {
  303. this.searchFlag--;
  304. }
  305. }
  306. async periodicCleanCache() {
  307. this.timer = null;
  308. const cleanInterval = this.config.cacheCleanInterval*60*1000;
  309. if (!cleanInterval)
  310. return;
  311. try {
  312. const db = this.db;
  313. const oldThres = Date.now() - cleanInterval;
  314. //выберем всех кандидатов на удаление
  315. const rows = await db.select({
  316. table: 'query_time',
  317. where: `
  318. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  319. `
  320. });
  321. const ids = [];
  322. for (const row of rows)
  323. ids.push(row.id);
  324. //удаляем
  325. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  326. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  327. //console.log('Cache clean', ids);
  328. } catch(e) {
  329. console.error(e.message);
  330. } finally {
  331. if (!this.closed) {
  332. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  333. }
  334. }
  335. }
  336. async close() {
  337. while (this.searchFlag > 0) {
  338. await utils.sleep(50);
  339. }
  340. this.searchCache = null;
  341. if (this.timer) {
  342. clearTimeout(this.timer);
  343. this.timer = null;
  344. }
  345. this.closed = true;
  346. }
  347. }
  348. module.exports = DbSearcher;