BUCServer.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. const fs = require('fs-extra');
  2. const FileDownloader = require('../FileDownloader');
  3. const JembaConnManager = require('../../db/JembaConnManager');//singleton
  4. const ayncExit = new (require('../AsyncExit'))();
  5. const utils = require('../utils');
  6. const log = new (require('../AppLogger'))().log;//singleton
  7. const minuteMs = 60*1000;
  8. const hourMs = 60*minuteMs;
  9. const dayMs = 24*hourMs;
  10. let instance = null;
  11. //singleton
  12. class BUCServer {
  13. constructor(config) {
  14. if (!instance) {
  15. this.config = config;
  16. //константы
  17. if (this.config.branch !== 'development') {
  18. this.maxCheckQueueLength = 10000;//максимальная длина checkQueue
  19. this.fillCheckQueuePeriod = 1*minuteMs;//период пополнения очереди
  20. this.periodicCheckWait = 500;//пауза, если нечего делать
  21. this.cleanQueryInterval = 300*dayMs;//интервал очистки устаревших
  22. this.oldQueryInterval = 30*dayMs;//интервал устаревания запроса на обновление
  23. this.checkingInterval = 3*hourMs;//интервал проверки обновления одного и того же файла
  24. this.sameHostCheckInterval = 1000;//интервал проверки файла на том же сайте, не менее
  25. } else {
  26. this.maxCheckQueueLength = 10;//максимальная длина checkQueue
  27. this.fillCheckQueuePeriod = 10*1000;//период пополнения очереди
  28. this.periodicCheckWait = 500;//пауза, если нечего делать
  29. this.cleanQueryInterval = 300*dayMs;//интервал очистки устаревших
  30. this.oldQueryInterval = 30*dayMs;//интервал устаревания запроса на обновление
  31. this.checkingInterval = 30*1000;//интервал проверки обновления одного и того же файла
  32. this.sameHostCheckInterval = 1000;//интервал проверки файла на том же сайте, не менее
  33. }
  34. this.config.tempDownloadDir = `${config.tempDir}/download`;
  35. fs.ensureDirSync(this.config.tempDownloadDir);
  36. this.down = new FileDownloader(config.maxUploadFileSize);
  37. this.connManager = new JembaConnManager();
  38. this.db = this.connManager.db['book-update-server'];
  39. this.checkQueue = [];
  40. this.hostChecking = {};
  41. this.main(); //no await
  42. instance = this;
  43. }
  44. return instance;
  45. }
  46. async getBuc(fromCheckTime, callback) {
  47. const db = this.db;
  48. const iterName = utils.randomHexString(30);
  49. while (1) {//eslint-disable-line
  50. const rows = await db.select({
  51. table: 'buc',
  52. where: `
  53. let iter = @getItem(${db.esc(iterName)});
  54. if (!iter) {
  55. iter = @dirtyIndexLR('checkTime', ${db.esc(fromCheckTime)});
  56. iter = iter.values();
  57. @setItem(${db.esc(iterName)}, iter);
  58. }
  59. const ids = new Set();
  60. let id = iter.next();
  61. while (!id.done && ids.size < 100) {
  62. ids.add(id.value);
  63. id = iter.next();
  64. }
  65. return ids;
  66. `
  67. });
  68. if (rows.length)
  69. callback(rows);
  70. else
  71. break;
  72. }
  73. await db.select({
  74. table: 'buc',
  75. where: `
  76. @delItem(${db.esc(iterName)});
  77. return new Set();
  78. `
  79. });
  80. }
  81. async updateBuc(bookUrls) {
  82. const db = this.db;
  83. const now = Date.now();
  84. const rows = await db.select({
  85. table: 'buc',
  86. map: `(r) => ({id: r.id})`,
  87. where: `@@id(${db.esc(bookUrls)})`
  88. });
  89. const exists = new Set();
  90. for (const row of rows) {
  91. exists.add(row.id);
  92. }
  93. const toUpdateIds = [];
  94. const toInsertRows = [];
  95. for (let id of bookUrls) {
  96. if (!id)
  97. continue;
  98. if (id.length > 1000) {
  99. id = id.substring(0, 1000);
  100. }
  101. if (exists.has(id)) {
  102. toUpdateIds.push(id);
  103. } else {
  104. toInsertRows.push({
  105. id,
  106. queryTime: now,
  107. checkTime: 0, // 0 - never checked
  108. modTime: '',
  109. size: 0,
  110. checkSum: '', //sha256
  111. state: 0, // 0 - not processing, 1 - processing
  112. error: '',
  113. });
  114. }
  115. }
  116. if (toUpdateIds.length) {
  117. await db.update({
  118. table: 'buc',
  119. mod: `(r) => r.queryTime = ${db.esc(now)}`,
  120. where: `@@id(${db.esc(toUpdateIds)})`
  121. });
  122. }
  123. if (toInsertRows.length) {
  124. await db.insert({
  125. table: 'buc',
  126. ignore: true,
  127. rows: toInsertRows,
  128. });
  129. }
  130. }
  131. async fillCheckQueue() {
  132. const db = this.db;
  133. while (1) {//eslint-disable-line
  134. try {
  135. let now = Date.now();
  136. //чистка совсем устаревших
  137. let rows = await db.select({
  138. table: 'buc',
  139. where: `@@dirtyIndexLR('queryTime', undefined, ${db.esc(now - this.cleanQueryInterval)})`
  140. });
  141. if (rows.length) {
  142. const ids = rows.map((r) => r.id);
  143. const res = await db.delete({
  144. table: 'buc',
  145. where: `@@id(${db.esc(ids)})`,
  146. });
  147. log(LM_WARN, `clean 'buc' table: deleted ${res.deleted}`);
  148. }
  149. rows = await db.select({table: 'buc', count: true});
  150. log(LM_WARN, `'buc' table length: ${rows[0].count}`);
  151. now = Date.now();
  152. //выборка кандидатов
  153. rows = await db.select({
  154. table: 'buc',
  155. where: `
  156. @@and(
  157. @dirtyIndexLR('queryTime', ${db.esc(now - this.oldQueryInterval)}),
  158. @dirtyIndexLR('checkTime', undefined, ${db.esc(now - this.checkingInterval)}),
  159. @flag('notProcessing')
  160. );
  161. `
  162. });
  163. //console.log(rows);
  164. if (rows.length) {
  165. const ids = [];
  166. for (const row of rows) {
  167. if (this.checkQueue.length >= this.maxCheckQueueLength)
  168. break;
  169. ids.push(row.id);
  170. this.checkQueue.push(row);
  171. }
  172. await db.update({
  173. table: 'buc',
  174. mod: `(r) => r.state = 1`,
  175. where: `@@id(${db.esc(ids)})`
  176. });
  177. log(LM_WARN, `checkQueue: added ${ids.length} recs, total ${this.checkQueue.length}`);
  178. }
  179. } catch(e) {
  180. log(LM_ERR, e.stack);
  181. }
  182. await utils.sleep(this.fillCheckQueuePeriod);
  183. }
  184. }
  185. async periodicCheck() {
  186. const db = this.db;
  187. while (1) {//eslint-disable-line
  188. try {
  189. if (!this.checkQueue.length)
  190. await utils.sleep(this.periodicCheckWait);
  191. if (!this.checkQueue.length)
  192. continue;
  193. const row = this.checkQueue.shift();
  194. const url = new URL(row.id);
  195. //только если обращались к тому же хосту не ранее sameHostCheckInterval миллисекунд назад
  196. if (!this.hostChecking[url.hostname]) {
  197. this.hostChecking[url.hostname] = true;
  198. try {
  199. let unchanged = true;
  200. let size = 0;
  201. let hash = '';
  202. const headers = await this.down.head(row.id);
  203. const modTime = headers['last-modified'] || '';
  204. if (!modTime || !row.modTime || (modTime !== row.modTime)) {
  205. const downdata = await this.down.load(row.id);
  206. size = downdata.length;
  207. hash = await utils.getBufHash(downdata, 'sha256', 'hex');
  208. unchanged = false;
  209. }
  210. await db.update({
  211. table: 'buc',
  212. mod: `(r) => {
  213. r.checkTime = ${db.esc(Date.now())};
  214. r.modTime = ${(unchanged ? 'r.modTime' : db.esc(modTime))};
  215. r.size = ${(unchanged ? 'r.size' : db.esc(size))};
  216. r.checkSum = ${(unchanged ? 'r.checkSum' : db.esc(hash))};
  217. r.state = 0;
  218. r.error = '';
  219. }`,
  220. where: `@@id(${db.esc(row.id)})`
  221. });
  222. if (unchanged) {
  223. log(`checked ${row.id} > unchanged`);
  224. } else {
  225. log(`checked ${row.id} > size ${size}`);
  226. }
  227. } catch (e) {
  228. await db.update({
  229. table: 'buc',
  230. mod: `(r) => {
  231. r.checkTime = ${db.esc(Date.now())};
  232. r.state = 0;
  233. r.error = ${db.esc(e.message)};
  234. }`,
  235. where: `@@id(${db.esc(row.id)})`
  236. });
  237. log(LM_ERR, `error ${row.id} > ${e.stack}`);
  238. } finally {
  239. (async() => {
  240. await utils.sleep(this.sameHostCheckInterval);
  241. this.hostChecking[url.hostname] = false;
  242. })();
  243. }
  244. } else {
  245. this.checkQueue.push(row);
  246. }
  247. } catch(e) {
  248. log(LM_ERR, e.stack);
  249. }
  250. await utils.sleep(10);
  251. }
  252. }
  253. async main() {
  254. try {
  255. //обнуляем все статусы
  256. await this.db.update({table: 'buc', mod: `(r) => r.state = 0`});
  257. this.fillCheckQueue();//no await
  258. //10 потоков
  259. for (let i = 0; i < 10; i++)
  260. this.periodicCheck();//no await
  261. log(`------------------`);
  262. log(`BUC Server started`);
  263. log(`------------------`);
  264. } catch (e) {
  265. log(LM_FATAL, e.stack);
  266. ayncExit.exit(1);
  267. }
  268. }
  269. }
  270. module.exports = BUCServer;