DbSearcher.js 12 KB

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