DbSearcher.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. //const _ = require('lodash');
  2. const utils = require('./utils');
  3. const maxUtf8Char = String.fromCodePoint(0xFFFFF);
  4. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  5. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  6. const enruArr = (ruAlphabet + enAlphabet).split('');
  7. class DbSearcher {
  8. constructor(config, db) {
  9. this.config = config;
  10. this.db = db;
  11. this.searchFlag = 0;
  12. this.timer = null;
  13. this.closed = false;
  14. this.periodicCleanCache();//no await
  15. }
  16. getWhere(a) {
  17. const db = this.db;
  18. a = a.toLowerCase();
  19. let where;
  20. //особая обработка префиксов
  21. if (a[0] == '=') {
  22. a = a.substring(1);
  23. where = `@@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a)})`;
  24. } else if (a[0] == '*') {
  25. a = a.substring(1);
  26. where = `@@indexIter('value', (v) => (v.indexOf(${db.esc(a)}) >= 0) )`;
  27. } else if (a[0] == '#') {
  28. a = a.substring(1);
  29. where = `@@indexIter('value', (v) => {
  30. const enru = new Set(${db.esc(enruArr)});
  31. return !v || (!enru.has(v[0].toLowerCase()) && v.indexOf(${db.esc(a)}) >= 0);
  32. });`;
  33. } else {
  34. where = `@@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  35. }
  36. return where;
  37. }
  38. async selectAuthorIds(query) {
  39. const db = this.db;
  40. let authorIds = new Set();
  41. //сначала выберем все id авторов по фильтру
  42. //порядок id соответсвует ASC-сортировке по author
  43. if (query.author && query.author !== '*') {
  44. const where = this.getWhere(query.author);
  45. const authorRows = await db.select({
  46. table: 'author',
  47. dirtyIdsOnly: true,
  48. where
  49. });
  50. for (const row of authorRows)
  51. authorIds.add(row.id);
  52. } else {//все авторы
  53. if (!db.searchCache.authorIdsAll) {
  54. const authorRows = await db.select({
  55. table: 'author',
  56. dirtyIdsOnly: true,
  57. });
  58. db.searchCache.authorIdsAll = [];
  59. for (const row of authorRows) {
  60. authorIds.add(row.id);
  61. db.searchCache.authorIdsAll.push(row.id);
  62. }
  63. } else {//оптимизация
  64. for (const id of db.searchCache.authorIdsAll) {
  65. authorIds.add(id);
  66. }
  67. }
  68. }
  69. const idsArr = [];
  70. idsArr.push(authorIds);
  71. //серии
  72. if (query.series && query.series !== '*') {
  73. const where = this.getWhere(query.series);
  74. const seriesRows = await db.select({
  75. table: 'series',
  76. map: `(r) => ({authorId: r.authorId})`,
  77. where
  78. });
  79. const ids = new Set();
  80. for (const row of seriesRows) {
  81. for (const id of row.authorId)
  82. ids.add(id);
  83. }
  84. idsArr.push(ids);
  85. }
  86. //названия
  87. if (query.title && query.title !== '*') {
  88. const where = this.getWhere(query.title);
  89. let titleRows = await db.select({
  90. table: 'title',
  91. map: `(r) => ({authorId: r.authorId})`,
  92. where
  93. });
  94. const ids = new Set();
  95. for (const row of titleRows) {
  96. for (const id of row.authorId)
  97. ids.add(id);
  98. }
  99. idsArr.push(ids);
  100. //чистки памяти при тяжелых запросах
  101. if (query.title[0] == '*') {
  102. titleRows = null;
  103. utils.freeMemory();
  104. await db.freeMemory();
  105. }
  106. }
  107. //жанры
  108. if (query.genre) {
  109. const genres = query.genre.split(',');
  110. const ids = new Set();
  111. for (const g of genres) {
  112. const genreRows = await db.select({
  113. table: 'genre',
  114. map: `(r) => ({authorId: r.authorId})`,
  115. where: `@@indexLR('value', ${db.esc(g)}, ${db.esc(g)})`,
  116. });
  117. for (const row of genreRows) {
  118. for (const id of row.authorId)
  119. ids.add(id);
  120. }
  121. }
  122. idsArr.push(ids);
  123. }
  124. //языки
  125. if (query.lang) {
  126. const langs = query.lang.split(',');
  127. const ids = new Set();
  128. for (const l of langs) {
  129. const langRows = await db.select({
  130. table: 'lang',
  131. map: `(r) => ({authorId: r.authorId})`,
  132. where: `@@indexLR('value', ${db.esc(l)}, ${db.esc(l)})`,
  133. });
  134. for (const row of langRows) {
  135. for (const id of row.authorId)
  136. ids.add(id);
  137. }
  138. }
  139. idsArr.push(ids);
  140. }
  141. if (idsArr.length > 1)
  142. authorIds = utils.intersectSet(idsArr);
  143. //сортировка
  144. authorIds = Array.from(authorIds);
  145. authorIds.sort((a, b) => a - b);
  146. return authorIds;
  147. }
  148. async getAuthorIds(query) {
  149. const db = this.db;
  150. if (!db.searchCache)
  151. db.searchCache = {};
  152. let result;
  153. //сначала попробуем найти в кеше
  154. const q = query;
  155. const keyArr = [q.author, q.series, q.title, q.genre, q.lang];
  156. const keyStr = `query-${keyArr.join('')}`;
  157. if (!keyStr) {//пустой запрос
  158. if (db.searchCache.authorIdsAll)
  159. result = db.searchCache.authorIdsAll;
  160. else
  161. result = await this.selectAuthorIds(query);
  162. } else {//непустой запрос
  163. const key = JSON.stringify(keyArr);
  164. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  165. if (rows.length) {//нашли в кеше
  166. await db.insert({
  167. table: 'query_time',
  168. replace: true,
  169. rows: [{id: key, time: Date.now()}],
  170. });
  171. result = rows[0].value;
  172. } else {//не нашли в кеше, ищем в поисковых таблицах
  173. result = await this.selectAuthorIds(query);
  174. await db.insert({
  175. table: 'query_cache',
  176. replace: true,
  177. rows: [{id: key, value: result}],
  178. });
  179. await db.insert({
  180. table: 'query_time',
  181. replace: true,
  182. rows: [{id: key, time: Date.now()}],
  183. });
  184. }
  185. }
  186. return result;
  187. }
  188. async search(query) {
  189. if (this.closed)
  190. throw new Error('DbSearcher closed');
  191. this.searchFlag++;
  192. try {
  193. const db = this.db;
  194. const authorIds = await this.getAuthorIds(query);
  195. const totalFound = authorIds.length;
  196. let limit = (query.limit ? query.limit : 100);
  197. limit = (limit > 1000 ? 1000 : limit);
  198. const offset = (query.offset ? query.offset : 0);
  199. //выборка найденных авторов
  200. let result = await db.select({
  201. table: 'author',
  202. map: `(r) => ({id: r.id, author: r.author})`,
  203. where: `@@id(${db.esc(authorIds.slice(offset, offset + limit))})`
  204. });
  205. return {result, totalFound};
  206. } finally {
  207. this.searchFlag--;
  208. }
  209. }
  210. async getBookList(authorId) {
  211. if (this.closed)
  212. throw new Error('DbSearcher closed');
  213. this.searchFlag++;
  214. try {
  215. const db = this.db;
  216. let result;
  217. const key = `author_books-${authorId}`;
  218. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  219. if (rows.length) {//нашли в кеше
  220. await db.insert({
  221. table: 'query_time',
  222. replace: true,
  223. rows: [{id: key, time: Date.now()}],
  224. });
  225. result = rows[0].value;
  226. } else {//не нашли в кеше
  227. //выборка автора по authorId
  228. const rows = await db.select({
  229. table: 'author_book',
  230. where: `@@id(${db.esc(authorId)})`
  231. });
  232. let author = '';
  233. let books = [];
  234. if (rows.length) {
  235. author = rows[0].author;
  236. books = rows[0].books;
  237. }
  238. result = {author, books};
  239. //кладем в кеш
  240. await db.insert({
  241. table: 'query_cache',
  242. replace: true,
  243. rows: [{id: key, value: result}],
  244. });
  245. await db.insert({
  246. table: 'query_time',
  247. replace: true,
  248. rows: [{id: key, time: Date.now()}],
  249. });
  250. }
  251. return result;
  252. } finally {
  253. this.searchFlag--;
  254. }
  255. }
  256. async periodicCleanCache() {
  257. this.timer = null;
  258. const cleanInterval = 5*1000;//this.config.cacheCleanInterval*60*1000;
  259. try {
  260. const db = this.db;
  261. const oldThres = Date.now() - cleanInterval;
  262. //выберем всех кандидатов на удаление
  263. const rows = await db.select({
  264. table: 'query_time',
  265. where: `
  266. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  267. `
  268. });
  269. const ids = [];
  270. for (const row of rows)
  271. ids.push(row.id);
  272. //удаляем
  273. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  274. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  275. //console.log('Cache clean', ids);
  276. } catch(e) {
  277. console.error(e.message);
  278. } finally {
  279. if (!this.closed) {
  280. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  281. }
  282. }
  283. }
  284. async close() {
  285. while (this.searchFlag > 0) {
  286. await utils.sleep(50);
  287. }
  288. if (this.timer) {
  289. clearTimeout(this.timer);
  290. this.timer = null;
  291. }
  292. this.closed = true;
  293. }
  294. }
  295. module.exports = DbSearcher;