WebSocketController.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. const WebSocket = require ('ws');
  2. const _ = require('lodash');
  3. const ReaderWorker = require('../core/Reader/ReaderWorker');//singleton
  4. const JembaReaderStorage = require('../core/Reader/JembaReaderStorage');//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 JembaReaderStorage();
  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.toString());
  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. req = JSON.parse(message);
  44. ws.lastActivity = Date.now();
  45. //pong for WebSocketConnection
  46. this.send({_rok: 1}, req, ws);
  47. switch (req.action) {
  48. case 'test':
  49. await this.test(req, ws); break;
  50. case 'get-config':
  51. await this.getConfig(req, ws); break;
  52. case 'worker-get-state':
  53. await this.workerGetState(req, ws); break;
  54. case 'worker-get-state-finish':
  55. await this.workerGetStateFinish(req, ws); break;
  56. case 'reader-restore-cached-file':
  57. await this.readerRestoreCachedFile(req, ws); break;
  58. case 'reader-storage':
  59. await this.readerStorageDo(req, ws); break;
  60. default:
  61. throw new Error(`Action not found: ${req.action}`);
  62. }
  63. } catch (e) {
  64. this.send({error: e.message}, req, ws);
  65. }
  66. }
  67. send(res, req, ws) {
  68. if (ws.readyState == WebSocket.OPEN) {
  69. ws.lastActivity = Date.now();
  70. let r = res;
  71. if (req.requestId)
  72. r = Object.assign({requestId: req.requestId}, r);
  73. const message = JSON.stringify(r);
  74. ws.send(message);
  75. if (this.isDevelopment) {
  76. log(`WebSocket-OUT: ${message.substr(0, 4000)}`);
  77. }
  78. }
  79. }
  80. //Actions ------------------------------------------------------------------
  81. async test(req, ws) {
  82. this.send({message: 'Liberama project is awesome'}, req, ws);
  83. }
  84. async getConfig(req, ws) {
  85. if (Array.isArray(req.params)) {
  86. const paramsSet = new Set(req.params);
  87. this.send(_.pick(this.config, this.config.webConfigParams.filter(x => paramsSet.has(x))), req, ws);
  88. } else {
  89. throw new Error('params is not an array');
  90. }
  91. }
  92. async workerGetState(req, ws) {
  93. if (!req.workerId)
  94. throw new Error(`key 'workerId' is wrong`);
  95. const state = this.workerState.getState(req.workerId);
  96. this.send((state ? state : {}), req, ws);
  97. }
  98. async workerGetStateFinish(req, ws) {
  99. if (!req.workerId)
  100. throw new Error(`key 'workerId' is wrong`);
  101. const refreshPause = 200;
  102. let i = 0;
  103. let state = {};
  104. while (1) {// eslint-disable-line no-constant-condition
  105. const prevProgress = state.progress || -1;
  106. const prevState = state.state || '';
  107. const lastModified = state.lastModified || 0;
  108. state = this.workerState.getState(req.workerId);
  109. this.send((state && lastModified != state.lastModified ? state : {}), req, ws);
  110. if (!state) break;
  111. if (state.state != 'finish' && state.state != 'error')
  112. await utils.sleep(refreshPause);
  113. else
  114. break;
  115. i++;
  116. if (i > 3*60*1000/refreshPause) {//3 мин ждем телодвижений воркера
  117. this.send({state: 'error', error: 'Время ожидания процесса истекло'}, req, ws);
  118. break;
  119. }
  120. i = (prevProgress != state.progress || prevState != state.state ? 1 : i);
  121. }
  122. }
  123. async readerRestoreCachedFile(req, ws) {
  124. if (!req.path)
  125. throw new Error(`key 'path' is empty`);
  126. const workerId = this.readerWorker.restoreCachedFile(req.path);
  127. const state = this.workerState.getState(workerId);
  128. this.send((state ? state : {}), req, ws);
  129. }
  130. async readerStorageDo(req, ws) {
  131. if (!req.body)
  132. throw new Error(`key 'body' is empty`);
  133. if (!req.body.action)
  134. throw new Error(`key 'action' is empty`);
  135. if (!req.body.items || Array.isArray(req.body.data))
  136. throw new Error(`key 'items' is empty`);
  137. this.send(await this.readerStorage.doAction(req.body), req, ws);
  138. }
  139. }
  140. module.exports = WebSocketController;