WebSocketController.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. const WebSocket = require ('ws');
  2. const _ = require('lodash');
  3. const WorkerState = require('../core/WorkerState');//singleton
  4. const WebWorker = require('../core/WebWorker');//singleton
  5. const log = new (require('../core/AppLogger'))().log;//singleton
  6. const utils = require('../core/utils');
  7. const cleanPeriod = 1*60*1000;//1 минута
  8. const closeSocketOnIdle = 5*60*1000;//5 минут
  9. class WebSocketController {
  10. constructor(wss, config) {
  11. this.config = config;
  12. this.isDevelopment = (config.branch == 'development');
  13. this.workerState = new WorkerState();
  14. this.webWorker = new WebWorker(config);
  15. this.wss = wss;
  16. wss.on('connection', (ws) => {
  17. ws.on('message', (message) => {
  18. this.onMessage(ws, message.toString());
  19. });
  20. ws.on('error', (err) => {
  21. log(LM_ERR, err);
  22. });
  23. });
  24. setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  25. }
  26. periodicClean() {
  27. try {
  28. const now = Date.now();
  29. this.wss.clients.forEach((ws) => {
  30. if (!ws.lastActivity || now - ws.lastActivity > closeSocketOnIdle - 50) {
  31. ws.terminate();
  32. }
  33. });
  34. } finally {
  35. setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  36. }
  37. }
  38. async onMessage(ws, message) {
  39. let req = {};
  40. try {
  41. if (this.isDevelopment) {
  42. log(`WebSocket-IN: ${message.substr(0, 4000)}`);
  43. }
  44. req = JSON.parse(message);
  45. ws.lastActivity = Date.now();
  46. //pong for WebSocketConnection
  47. this.send({_rok: 1}, req, ws);
  48. switch (req.action) {
  49. case 'test':
  50. await this.test(req, ws); break;
  51. case 'get-config':
  52. await this.getConfig(req, ws); break;
  53. case 'get-worker-state':
  54. await this.getWorkerState(req, ws); break;
  55. case 'search':
  56. await this.search(req, ws); break;
  57. case 'get-book-list':
  58. await this.getBookList(req, ws); break;
  59. case 'get-genre-tree':
  60. await this.getGenreTree(req, ws); break;
  61. case 'get-book-link':
  62. await this.getBookLink(req, ws); break;
  63. default:
  64. throw new Error(`Action not found: ${req.action}`);
  65. }
  66. } catch (e) {
  67. this.send({error: e.message}, req, ws);
  68. }
  69. }
  70. send(res, req, ws) {
  71. if (ws.readyState == WebSocket.OPEN) {
  72. ws.lastActivity = Date.now();
  73. let r = res;
  74. if (req.requestId)
  75. r = Object.assign({requestId: req.requestId}, r);
  76. const message = JSON.stringify(r);
  77. ws.send(message);
  78. if (this.isDevelopment) {
  79. log(`WebSocket-OUT: ${message.substr(0, 4000)}`);
  80. }
  81. }
  82. }
  83. //Actions ------------------------------------------------------------------
  84. async test(req, ws) {
  85. this.send({message: `${this.config.name} project is awesome`}, req, ws);
  86. }
  87. async getConfig(req, ws) {
  88. const config = _.pick(this.config, this.config.webConfigParams);
  89. config.dbConfig = await this.webWorker.dbConfig();
  90. this.send(config, req, ws);
  91. }
  92. async getWorkerState(req, ws) {
  93. if (!req.workerId)
  94. throw new Error(`key 'workerId' is empty`);
  95. const state = this.workerState.getState(req.workerId);
  96. this.send((state ? state : {}), req, ws);
  97. }
  98. async search(req, ws) {
  99. if (!req.query)
  100. throw new Error(`query is empty`);
  101. const result = await this.webWorker.search(req.query);
  102. this.send(result, req, ws);
  103. }
  104. async getBookList(req, ws) {
  105. if (!utils.hasProp(req, 'authorId'))
  106. throw new Error(`authorId is empty`);
  107. const result = await this.webWorker.getBookList(req.authorId);
  108. this.send(result, req, ws);
  109. }
  110. async getGenreTree(req, ws) {
  111. const result = await this.webWorker.getGenreTree();
  112. this.send(result, req, ws);
  113. }
  114. async getBookLink(req, ws) {
  115. if (!utils.hasProp(req, 'bookPath'))
  116. throw new Error(`bookPath is empty`);
  117. const result = await this.webWorker.getBookLink(req.bookPath);
  118. this.send(result, req, ws);
  119. }
  120. }
  121. module.exports = WebSocketController;