BUCClient.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. map: `(r) => ({id: r.id, size: r.size})`,
  64. where: `@@id(${db.esc(bookUrls)})`,
  65. });
  66. return rows;
  67. }
  68. async findMaxCheckTime() {
  69. const db = this.appDb;
  70. let result = 1;
  71. //одним куском, возможно будет жрать память
  72. const rows = await db.select({
  73. table: 'buc',
  74. where: `
  75. const result = new Set();
  76. let max = 0;
  77. let maxId = null;
  78. @iter(@all(), (row) => {
  79. if (row.checkTime > max) {
  80. max = row.checkTime;
  81. maxId = row.id;
  82. }
  83. });
  84. if (maxId)
  85. result.add(maxId);
  86. return result;
  87. `
  88. });
  89. if (rows.length)
  90. result = rows[0].checkTime;
  91. return result;
  92. }
  93. async periodicSync() {
  94. const db = this.appDb;
  95. while (1) {//eslint-disable-line
  96. try {
  97. //сначала отправим this.bookUrls
  98. log(`client: remote update buc begin`);
  99. const arr = Array.from(this.bookUrls);
  100. this.bookUrls = new Set();
  101. const chunkSize = 100;
  102. let updated = 0;
  103. for (let i = 0; i < arr.length; i += chunkSize) {
  104. const chunk = arr.slice(i, i + chunkSize);
  105. const res = await this.wsUpdateBuc(chunk);
  106. if (!res.error && res.state == 'success') {
  107. //update success
  108. updated += chunk.length;
  109. } else {
  110. for (const url of chunk) {
  111. this.bookUrls.add(url);
  112. }
  113. log(LM_ERR, `update-buc error: ${(res.error ? res.error : `wrong state "${res.state}"`)}`);
  114. }
  115. }
  116. log(`client: remote update buc end, updated ${updated} urls`);
  117. //почистим нашу таблицу 'buc'
  118. log(`client: clean 'buc' table begin`);
  119. const cleanTime = Date.now() - this.cleanQueryInterval;
  120. while (1) {//eslint-disable-line
  121. //выборка всех по кусочкам
  122. const rows = await db.select({
  123. table: 'buc',
  124. where: `
  125. let iter = @getItem('clean');
  126. if (!iter) {
  127. iter = @all();
  128. @setItem('clean', iter);
  129. }
  130. const ids = new Set();
  131. let id = iter.next();
  132. while (!id.done && ids.size < 1000) {
  133. ids.add(id.value);
  134. id = iter.next();
  135. }
  136. return ids;
  137. `
  138. });
  139. if (rows.length) {
  140. const toDelIds = [];
  141. for (const row of rows)
  142. if (row.queryTime <= cleanTime)
  143. toDelIds.push(row.id);
  144. //удаление
  145. const res = await db.delete({
  146. table: 'buc',
  147. where: `@@id(${db.esc(toDelIds)})`,
  148. });
  149. log(`client: clean 'buc' deleted ${res.deleted}`);
  150. } else {
  151. break;
  152. }
  153. }
  154. await db.select({
  155. table: 'buc',
  156. where: `
  157. @delItem('clean');
  158. return new Set();
  159. `
  160. });
  161. log(`client: clean 'buc' table end`);
  162. //синхронизация с сервером BUC
  163. log(`client: sync 'buc' table begin`);
  164. this.fromCheckTime -= 30*minuteMs;//минус полчаса на всякий случай
  165. await this.wsGetBuc(this.fromCheckTime, async(rows) => {
  166. for (const row of rows) {
  167. if (row.checkTime > this.fromCheckTime)
  168. this.fromCheckTime = row.checkTime;
  169. }
  170. const res = await db.insert({
  171. table: 'buc',
  172. replace: true,
  173. rows
  174. });
  175. log(`client: sync 'buc' table, inserted ${res.inserted} rows, replaced ${res.replaced}`);
  176. });
  177. log(`client: sync 'buc' table end`);
  178. } catch (e) {
  179. log(LM_ERR, e.stack);
  180. }
  181. await utils.sleep(this.syncPeriod);
  182. }
  183. }
  184. async main() {
  185. try {
  186. if (!this.config.bucEnabled)
  187. throw new Error('BookUpdateChecker disabled');
  188. this.fromCheckTime = await this.findMaxCheckTime();
  189. this.periodicSync();//no await
  190. log(`BUC Client started`);
  191. } catch (e) {
  192. log(LM_FATAL, e.stack);
  193. ayncExit.exit(1);
  194. }
  195. }
  196. }
  197. module.exports = BUCClient;