socket-io.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import { GlobalSocketEventName } from '@growi/core/dist/interfaces';
  2. import { Server } from 'socket.io';
  3. import loggerFactory from '~/utils/logger';
  4. import { RoomPrefix, getRoomNameWithId } from '../util/socket-io-helpers';
  5. import YjsConnectionManager from './yjs-connection-manager';
  6. const expressSession = require('express-session');
  7. const passport = require('passport');
  8. const logger = loggerFactory('growi:service:socket-io');
  9. /**
  10. * Serve socket.io for server-to-client messaging
  11. */
  12. class SocketIoService {
  13. constructor(crowi) {
  14. this.crowi = crowi;
  15. this.configManager = crowi.configManager;
  16. this.guestClients = new Set();
  17. }
  18. get isInitialized() {
  19. return (this.io != null);
  20. }
  21. // Since the Order is important, attachServer() should be async
  22. async attachServer(server) {
  23. this.io = new Server({
  24. transports: ['websocket'],
  25. serveClient: false,
  26. });
  27. this.io.attach(server);
  28. // create the YjsConnectionManager instance
  29. this.yjsConnectionManager = new YjsConnectionManager(this.io);
  30. // create namespace for admin
  31. this.adminNamespace = this.io.of('/admin');
  32. // setup middlewares
  33. // !!CAUTION!! -- ORDER IS IMPORTANT
  34. await this.setupSessionMiddleware();
  35. await this.setupLoginRequiredMiddleware();
  36. await this.setupAdminRequiredMiddleware();
  37. await this.setupCheckConnectionLimitsMiddleware();
  38. await this.setupStoreGuestIdEventHandler();
  39. await this.setupLoginedUserRoomsJoinOnConnection();
  40. await this.setupDefaultSocketJoinRoomsEventHandler();
  41. await this.setupYjsConnection();
  42. }
  43. getDefaultSocket() {
  44. if (this.io == null) {
  45. throw new Error('Http server has not attached yet.');
  46. }
  47. return this.io.sockets;
  48. }
  49. getAdminSocket() {
  50. if (this.io == null) {
  51. throw new Error('Http server has not attached yet.');
  52. }
  53. return this.adminNamespace;
  54. }
  55. /**
  56. * use passport session
  57. * @see https://socket.io/docs/v4/middlewares/#Compatibility-with-Express-middleware
  58. */
  59. setupSessionMiddleware() {
  60. const wrap = middleware => (socket, next) => middleware(socket.request, {}, next);
  61. this.io.use(wrap(expressSession(this.crowi.sessionConfig)));
  62. this.io.use(wrap(passport.initialize()));
  63. this.io.use(wrap(passport.session()));
  64. // express and passport session on main socket doesn't shared to child namespace socket
  65. // need to define the session for specific namespace
  66. this.getAdminSocket().use(wrap(expressSession(this.crowi.sessionConfig)));
  67. this.getAdminSocket().use(wrap(passport.initialize()));
  68. this.getAdminSocket().use(wrap(passport.session()));
  69. }
  70. /**
  71. * use loginRequired middleware
  72. */
  73. setupLoginRequiredMiddleware() {
  74. const loginRequired = require('../middlewares/login-required')(this.crowi, true, (req, res, next) => {
  75. next(new Error('Login is required to connect.'));
  76. });
  77. // convert Connect/Express middleware to Socket.io middleware
  78. this.io.use((socket, next) => {
  79. loginRequired(socket.request, {}, next);
  80. });
  81. }
  82. /**
  83. * use adminRequired middleware
  84. */
  85. setupAdminRequiredMiddleware() {
  86. const adminRequired = require('../middlewares/admin-required')(this.crowi, (req, res, next) => {
  87. next(new Error('Admin priviledge is required to connect.'));
  88. });
  89. // convert Connect/Express middleware to Socket.io middleware
  90. this.getAdminSocket().use((socket, next) => {
  91. adminRequired(socket.request, {}, next);
  92. });
  93. }
  94. /**
  95. * use checkConnectionLimits middleware
  96. */
  97. setupCheckConnectionLimitsMiddleware() {
  98. this.getAdminSocket().use(this.checkConnectionLimitsForAdmin.bind(this));
  99. this.getDefaultSocket().use(this.checkConnectionLimitsForGuest.bind(this));
  100. this.getDefaultSocket().use(this.checkConnectionLimits.bind(this));
  101. }
  102. setupStoreGuestIdEventHandler() {
  103. this.io.on('connection', (socket) => {
  104. if (socket.request.user == null) {
  105. this.guestClients.add(socket.id);
  106. socket.on('disconnect', () => {
  107. this.guestClients.delete(socket.id);
  108. });
  109. }
  110. });
  111. }
  112. setupLoginedUserRoomsJoinOnConnection() {
  113. this.io.on('connection', (socket) => {
  114. const user = socket.request.user;
  115. if (user == null) {
  116. logger.debug('Socket io: An anonymous user has connected');
  117. return;
  118. }
  119. socket.join(getRoomNameWithId(RoomPrefix.USER, user._id));
  120. });
  121. }
  122. setupDefaultSocketJoinRoomsEventHandler() {
  123. this.io.on('connection', (socket) => {
  124. // set event handlers for joining rooms
  125. socket.on('join:page', ({ pageId }) => {
  126. socket.join(getRoomNameWithId(RoomPrefix.PAGE, pageId));
  127. });
  128. });
  129. }
  130. setupYjsConnection() {
  131. this.io.on('connection', (socket) => {
  132. socket.on(GlobalSocketEventName.YDocSync, async({ pageId, initialValue }) => {
  133. try {
  134. await this.yjsConnectionManager.handleYDocSync(pageId, initialValue);
  135. }
  136. catch (error) {
  137. logger.warn(error.message);
  138. socket.emit(GlobalSocketEventName.YDocSyncError, 'An error occurred during YDoc synchronization.');
  139. }
  140. });
  141. });
  142. }
  143. async checkConnectionLimitsForAdmin(socket, next) {
  144. const namespaceName = socket.nsp.name;
  145. if (namespaceName === '/admin') {
  146. const clients = await this.getAdminSocket().allSockets();
  147. const clientsCount = clients.length;
  148. logger.debug('Current count of clients for \'/admin\':', clientsCount);
  149. const limit = this.configManager.getConfig('crowi', 's2cMessagingPubsub:connectionsLimitForAdmin');
  150. if (limit <= clientsCount) {
  151. const msg = `The connection was refused because the current count of clients for '/admin' is ${clientsCount} and exceeds the limit`;
  152. logger.warn(msg);
  153. next(new Error(msg));
  154. return;
  155. }
  156. }
  157. next();
  158. }
  159. async checkConnectionLimitsForGuest(socket, next) {
  160. if (socket.request.user == null) {
  161. const clientsCount = this.guestClients.size;
  162. logger.debug('Current count of clients for guests:', clientsCount);
  163. const limit = this.configManager.getConfig('crowi', 's2cMessagingPubsub:connectionsLimitForGuest');
  164. if (limit <= clientsCount) {
  165. const msg = `The connection was refused because the current count of clients for guests is ${clientsCount} and exceeds the limit`;
  166. logger.warn(msg);
  167. next(new Error(msg));
  168. return;
  169. }
  170. }
  171. next();
  172. }
  173. /**
  174. * @see https://socket.io/docs/server-api/#socket-client
  175. */
  176. async checkConnectionLimits(socket, next) {
  177. // exclude admin
  178. const namespaceName = socket.nsp.name;
  179. if (namespaceName === '/admin') {
  180. next();
  181. }
  182. const clients = await this.getDefaultSocket().allSockets();
  183. const clientsCount = clients.length;
  184. logger.debug('Current count of clients for \'/\':', clientsCount);
  185. const limit = this.configManager.getConfig('crowi', 's2cMessagingPubsub:connectionsLimit');
  186. if (limit <= clientsCount) {
  187. const msg = `The connection was refused because the current count of clients for '/' is ${clientsCount} and exceeds the limit`;
  188. logger.warn(msg);
  189. next(new Error(msg));
  190. return;
  191. }
  192. next();
  193. }
  194. }
  195. module.exports = SocketIoService;