BUCClient.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. const WebSocketConnection = require('../WebSocketConnection');
  2. const JembaConnManager = require('../../db/JembaConnManager');//singleton
  3. const ayncExit = new (require('../AsyncExit'))();
  4. const utils = require('../utils');
  5. const log = new (require('../AppLogger'))().log;//singleton
  6. const minuteMs = 60*1000;
  7. const hourMs = 60*minuteMs;
  8. const dayMs = 24*hourMs;
  9. let instance = null;
  10. //singleton
  11. class BUCClient {
  12. constructor(config) {
  13. if (!instance) {
  14. this.config = config;
  15. this.connManager = new JembaConnManager();
  16. this.appDb = this.connManager.db['app'];
  17. this.wsc = new WebSocketConnection(config.bucServer.url, 10, 30, {rejectUnauthorized: false});
  18. this.accessToken = config.bucServer.accessToken;
  19. //константы
  20. if (this.config.branch !== 'development') {
  21. this.cleanQueryInterval = 300*dayMs;//интервал очистки устаревших
  22. this.syncPeriod = 1*hourMs;//период синхронизации с сервером BUC
  23. } else {
  24. this.cleanQueryInterval = 300*dayMs;//интервал очистки устаревших
  25. this.syncPeriod = 1*minuteMs;//период синхронизации с сервером BUC
  26. }
  27. this.fromCheckTime = 1;
  28. this.bookUrls = new Set();
  29. this.main();//no await
  30. instance = this;
  31. }
  32. return instance;
  33. }
  34. async wsRequest(query) {
  35. const response = await this.wsc.message(
  36. await this.wsc.send(Object.assign({accessToken: this.accessToken}, query), 60),
  37. 60
  38. );
  39. if (response.error)
  40. throw new Error(response.error);
  41. return response;
  42. }
  43. async wsGetBuc(fromCheckTime, callback) {
  44. const requestId = await this.wsc.send({accessToken: this.accessToken, action: 'get-buc', fromCheckTime}, 60);
  45. while (1) {//eslint-disable-line
  46. const res = await this.wsc.message(requestId, 60);
  47. if (res.state == 'get') {
  48. await callback(res.rows);
  49. } else {
  50. break;
  51. }
  52. }
  53. }
  54. async wsUpdateBuc(bookUrls) {
  55. return await this.wsRequest({action: 'update-buc', bookUrls});
  56. }
  57. async checkBuc(bookUrls) {
  58. const db = this.appDb;
  59. for (const url of bookUrls)
  60. this.bookUrls.add(url);
  61. const rows = await db.select({
  62. table: 'buc',
  63. where: `@@id(${db.esc(bookUrls)})`
  64. });
  65. return rows;
  66. }
  67. async findMaxCheckTime() {
  68. const db = this.appDb;
  69. let result = 1;
  70. //одним куском, возможно будет жрать память
  71. const rows = await db.select({
  72. table: 'buc',
  73. where: `
  74. const result = new Set();
  75. let max = 0;
  76. let maxId = null;
  77. @iter(@all(), (row) => {
  78. if (row.checkTime > max) {
  79. max = row.checkTime;
  80. maxId = row.id;
  81. }
  82. });
  83. if (maxId)
  84. result.add(maxId);
  85. return result;
  86. `
  87. });
  88. if (rows.length)
  89. result = rows[0].checkTime;
  90. return result;
  91. }
  92. async periodicSync() {
  93. const db = this.appDb;
  94. while (1) {//eslint-disable-line
  95. try {
  96. //сначала отправим this.bookUrls
  97. log(`client: remote update buc begin`);
  98. const arr = Array.from(this.bookUrls);
  99. this.bookUrls = new Set();
  100. const chunkSize = 100;
  101. let updated = 0;
  102. for (let i = 0; i < arr.length; i += chunkSize) {
  103. const chunk = arr.slice(i, i + chunkSize);
  104. const res = await this.wsUpdateBuc(chunk);
  105. if (!res.error && res.state == 'success') {
  106. //update success
  107. updated += chunk.length;
  108. } else {
  109. for (const url of chunk) {
  110. this.bookUrls.add(url);
  111. }
  112. log(LM_ERR, `update-buc error: ${(res.error ? res.error : `wrong state "${res.state}"`)}`);
  113. }
  114. }
  115. log(`client: remote update buc end, updated ${updated} urls`);
  116. //почистим нашу таблицу 'buc'
  117. log(`client: clean 'buc' table begin`);
  118. const cleanTime = Date.now() - this.cleanQueryInterval;
  119. while (1) {//eslint-disable-line
  120. //выборка всех по кусочкам
  121. const rows = await db.select({
  122. table: 'buc',
  123. where: `
  124. let iter = @getItem('clean');
  125. if (!iter) {
  126. iter = @all();
  127. @setItem('clean', iter);
  128. }
  129. const ids = new Set();
  130. let id = iter.next();
  131. while (!id.done && ids.size < 1000) {
  132. ids.add(id.value);
  133. id = iter.next();
  134. }
  135. return ids;
  136. `
  137. });
  138. if (rows.length) {
  139. const toDelIds = [];
  140. for (const row of rows)
  141. if (row.queryTime <= cleanTime)
  142. toDelIds.push(row.id);
  143. //удаление
  144. const res = await db.delete({
  145. table: 'buc',
  146. where: `@@id(${db.esc(toDelIds)})`,
  147. });
  148. log(`client: clean 'buc' deleted ${res.deleted}`);
  149. } else {
  150. break;
  151. }
  152. }
  153. await db.select({
  154. table: 'buc',
  155. where: `
  156. @delItem('clean');
  157. return new Set();
  158. `
  159. });
  160. log(`client: clean 'buc' table end`);
  161. //синхронизация с сервером BUC
  162. log(`client: sync 'buc' table begin`);
  163. this.fromCheckTime -= 30*minuteMs;//минус полчаса на всякий случай
  164. await this.wsGetBuc(this.fromCheckTime, async(rows) => {
  165. for (const row of rows) {
  166. if (row.checkTime > this.fromCheckTime)
  167. this.fromCheckTime = row.checkTime;
  168. }
  169. const res = await db.insert({
  170. table: 'buc',
  171. replace: true,
  172. rows
  173. });
  174. log(`client: sync 'buc' table, inserted ${res.inserted} rows, replaced ${res.replaced}`);
  175. });
  176. log(`client: sync 'buc' table end`);
  177. } catch (e) {
  178. log(LM_ERR, e.stack);
  179. }
  180. await utils.sleep(this.syncPeriod);
  181. }
  182. }
  183. async main() {
  184. try {
  185. if (!this.config.bucEnabled)
  186. throw new Error('BookUpdateChecker disabled');
  187. this.fromCheckTime = await this.findMaxCheckTime();
  188. this.periodicSync();//no await
  189. log(`BUC Client started`);
  190. } catch (e) {
  191. log(LM_FATAL, e.stack);
  192. ayncExit.exit(1);
  193. }
  194. }
  195. }
  196. module.exports = BUCClient;