DbSearcher.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. db.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 = new Set();
  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.add(row.id);
  57. } else {//все авторы
  58. if (!db.searchCache.authorIdsAll) {
  59. const authorRows = await db.select({
  60. table: 'author',
  61. dirtyIdsOnly: true,
  62. });
  63. db.searchCache.authorIdsAll = [];
  64. for (const row of authorRows) {
  65. authorIds.add(row.id);
  66. db.searchCache.authorIdsAll.push(row.id);
  67. }
  68. } else {//оптимизация
  69. authorIds = new Set(db.searchCache.authorIdsAll);
  70. }
  71. }
  72. const idsArr = [];
  73. idsArr.push(authorIds);
  74. //серии
  75. if (query.series && query.series !== '*') {
  76. const where = this.getWhere(query.series);
  77. const seriesRows = await db.select({
  78. table: 'series',
  79. map: `(r) => ({authorId: r.authorId})`,
  80. where
  81. });
  82. const ids = new Set();
  83. for (const row of seriesRows) {
  84. for (const id of row.authorId)
  85. ids.add(id);
  86. }
  87. idsArr.push(ids);
  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. map: `(r) => ({authorId: r.authorId})`,
  95. where
  96. });
  97. const ids = new Set();
  98. for (const row of titleRows) {
  99. for (const id of row.authorId)
  100. ids.add(id);
  101. }
  102. idsArr.push(ids);
  103. //чистки памяти при тяжелых запросах
  104. if (query.title[0] == '*') {
  105. titleRows = null;
  106. utils.freeMemory();
  107. await db.freeMemory();
  108. }
  109. }
  110. //жанры
  111. if (query.genre) {
  112. const genres = query.genre.split(',');
  113. const ids = new Set();
  114. for (const g of genres) {
  115. const genreRows = await db.select({
  116. table: 'genre',
  117. map: `(r) => ({authorId: r.authorId})`,
  118. where: `@@indexLR('value', ${db.esc(g)}, ${db.esc(g)})`,
  119. });
  120. for (const row of genreRows) {
  121. for (const id of row.authorId)
  122. ids.add(id);
  123. }
  124. }
  125. idsArr.push(ids);
  126. }
  127. //языки
  128. if (query.lang) {
  129. const langs = query.lang.split(',');
  130. const ids = new Set();
  131. for (const l of langs) {
  132. const langRows = await db.select({
  133. table: 'lang',
  134. map: `(r) => ({authorId: r.authorId})`,
  135. where: `@@indexLR('value', ${db.esc(l)}, ${db.esc(l)})`,
  136. });
  137. for (const row of langRows) {
  138. for (const id of row.authorId)
  139. ids.add(id);
  140. }
  141. }
  142. idsArr.push(ids);
  143. }
  144. if (idsArr.length > 1)
  145. authorIds = utils.intersectSet(idsArr);
  146. //сортировка
  147. authorIds = Array.from(authorIds);
  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 = db.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 = db.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. if (this.timer) {
  323. clearTimeout(this.timer);
  324. this.timer = null;
  325. }
  326. this.closed = true;
  327. }
  328. }
  329. module.exports = DbSearcher;