WebSocketController.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. const WebSocket = require ('ws');
  2. const _ = require('lodash');
  3. const ReaderWorker = require('../core/Reader/ReaderWorker');//singleton
  4. const ReaderStorage = require('../core/Reader/ReaderStorage');//singleton
  5. const WorkerState = require('../core/WorkerState');//singleton
  6. const log = new (require('../core/AppLogger'))().log;//singleton
  7. const utils = require('../core/utils');
  8. const cleanPeriod = 1*60*1000;//1 минута
  9. const closeSocketOnIdle = 5*60*1000;//5 минут
  10. class WebSocketController {
  11. constructor(wss, config) {
  12. this.config = config;
  13. this.isDevelopment = (config.branch == 'development');
  14. this.readerStorage = new ReaderStorage();
  15. this.readerWorker = new ReaderWorker(config);
  16. this.workerState = new WorkerState();
  17. this.wss = wss;
  18. wss.on('connection', (ws) => {
  19. ws.on('message', (message) => {
  20. this.onMessage(ws, message);
  21. });
  22. });
  23. setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  24. }
  25. periodicClean() {
  26. try {
  27. const now = Date.now();
  28. this.wss.clients.forEach((ws) => {
  29. if (!ws.lastActivity || now - ws.lastActivity > closeSocketOnIdle - 50) {
  30. ws.terminate();
  31. }
  32. });
  33. } finally {
  34. setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  35. }
  36. }
  37. async onMessage(ws, message) {
  38. let req = {};
  39. try {
  40. if (this.isDevelopment) {
  41. log(`WebSocket-IN: ${message.substr(0, 4000)}`);
  42. }
  43. ws.lastActivity = Date.now();
  44. req = JSON.parse(message);
  45. switch (req.action) {
  46. case 'test':
  47. await this.test(req, ws); break;
  48. case 'get-config':
  49. await this.getConfig(req, ws); break;
  50. case 'worker-get-state':
  51. await this.workerGetState(req, ws); break;
  52. case 'worker-get-state-finish':
  53. await this.workerGetStateFinish(req, ws); break;
  54. case 'reader-restore-cached-file':
  55. await this.readerRestoreCachedFile(req, ws); break;
  56. case 'reader-storage':
  57. await this.readerStorageDo(req, ws); break;
  58. default:
  59. throw new Error(`Action not found: ${req.action}`);
  60. }
  61. } catch (e) {
  62. this.send({error: e.message}, req, ws);
  63. }
  64. }
  65. send(res, req, ws) {
  66. if (ws.readyState == WebSocket.OPEN) {
  67. ws.lastActivity = Date.now();
  68. let r = res;
  69. if (req.requestId)
  70. r = Object.assign({requestId: req.requestId}, r);
  71. const message = JSON.stringify(r);
  72. ws.send(message);
  73. if (this.isDevelopment) {
  74. log(`WebSocket-OUT: ${message.substr(0, 4000)}`);
  75. }
  76. }
  77. }
  78. //Actions ------------------------------------------------------------------
  79. async test(req, ws) {
  80. this.send({message: 'Liberama project is awesome'}, req, ws);
  81. }
  82. async getConfig(req, ws) {
  83. if (Array.isArray(req.params)) {
  84. const paramsSet = new Set(req.params);
  85. this.send(_.pick(this.config, this.config.webConfigParams.filter(x => paramsSet.has(x))), req, ws);
  86. } else {
  87. throw new Error('params is not an array');
  88. }
  89. }
  90. async workerGetState(req, ws) {
  91. if (!req.workerId)
  92. throw new Error(`key 'workerId' is wrong`);
  93. const state = this.workerState.getState(req.workerId);
  94. this.send((state ? state : {}), req, ws);
  95. }
  96. async workerGetStateFinish(req, ws) {
  97. if (!req.workerId)
  98. throw new Error(`key 'workerId' is wrong`);
  99. const refreshPause = 200;
  100. let i = 0;
  101. let state = {};
  102. while (1) {// eslint-disable-line no-constant-condition
  103. const prevProgress = state.progress || -1;
  104. const prevState = state.state || '';
  105. const lastModified = state.lastModified || 0;
  106. state = this.workerState.getState(req.workerId);
  107. this.send((state && lastModified != state.lastModified ? state : {}), req, ws);
  108. if (!state) break;
  109. if (state.state != 'finish' && state.state != 'error')
  110. await utils.sleep(refreshPause);
  111. else
  112. break;
  113. i++;
  114. if (i > 3*60*1000/refreshPause) {//3 мин ждем телодвижений воркера
  115. this.send({state: 'error', error: 'Время ожидания процесса истекло'}, req, ws);
  116. break;
  117. }
  118. i = (prevProgress != state.progress || prevState != state.state ? 1 : i);
  119. }
  120. }
  121. async readerRestoreCachedFile(req, ws) {
  122. if (!req.path)
  123. throw new Error(`key 'path' is empty`);
  124. const workerId = this.readerWorker.restoreCachedFile(req.path);
  125. const state = this.workerState.getState(workerId);
  126. this.send((state ? state : {}), req, ws);
  127. }
  128. async readerStorageDo(req, ws) {
  129. if (!req.body)
  130. throw new Error(`key 'body' is empty`);
  131. if (!req.body.action)
  132. throw new Error(`key 'action' is empty`);
  133. if (!req.body.items || Array.isArray(req.body.data))
  134. throw new Error(`key 'items' is empty`);
  135. this.send(await this.readerStorage.doAction(req.body), req, ws);
  136. }
  137. }
  138. module.exports = WebSocketController;