in-memory-adapter.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. "use strict";
  2. var _a;
  3. Object.defineProperty(exports, "__esModule", { value: true });
  4. exports.SessionAwareAdapter = exports.Adapter = void 0;
  5. const events_1 = require("events");
  6. const yeast_1 = require("./contrib/yeast");
  7. const WebSocket = require("ws");
  8. const canPreComputeFrame = typeof ((_a = WebSocket === null || WebSocket === void 0 ? void 0 : WebSocket.Sender) === null || _a === void 0 ? void 0 : _a.frame) === "function";
  9. class Adapter extends events_1.EventEmitter {
  10. /**
  11. * In-memory adapter constructor.
  12. *
  13. * @param {Namespace} nsp
  14. */
  15. constructor(nsp) {
  16. super();
  17. this.nsp = nsp;
  18. this.rooms = new Map();
  19. this.sids = new Map();
  20. this.encoder = nsp.server.encoder;
  21. }
  22. /**
  23. * To be overridden
  24. */
  25. init() { }
  26. /**
  27. * To be overridden
  28. */
  29. close() { }
  30. /**
  31. * Returns the number of Socket.IO servers in the cluster
  32. *
  33. * @public
  34. */
  35. serverCount() {
  36. return Promise.resolve(1);
  37. }
  38. /**
  39. * Adds a socket to a list of room.
  40. *
  41. * @param {SocketId} id the socket id
  42. * @param {Set<Room>} rooms a set of rooms
  43. * @public
  44. */
  45. addAll(id, rooms) {
  46. if (!this.sids.has(id)) {
  47. this.sids.set(id, new Set());
  48. }
  49. for (const room of rooms) {
  50. this.sids.get(id).add(room);
  51. if (!this.rooms.has(room)) {
  52. this.rooms.set(room, new Set());
  53. this.emit("create-room", room);
  54. }
  55. if (!this.rooms.get(room).has(id)) {
  56. this.rooms.get(room).add(id);
  57. this.emit("join-room", room, id);
  58. }
  59. }
  60. }
  61. /**
  62. * Removes a socket from a room.
  63. *
  64. * @param {SocketId} id the socket id
  65. * @param {Room} room the room name
  66. */
  67. del(id, room) {
  68. if (this.sids.has(id)) {
  69. this.sids.get(id).delete(room);
  70. }
  71. this._del(room, id);
  72. }
  73. _del(room, id) {
  74. const _room = this.rooms.get(room);
  75. if (_room != null) {
  76. const deleted = _room.delete(id);
  77. if (deleted) {
  78. this.emit("leave-room", room, id);
  79. }
  80. if (_room.size === 0 && this.rooms.delete(room)) {
  81. this.emit("delete-room", room);
  82. }
  83. }
  84. }
  85. /**
  86. * Removes a socket from all rooms it's joined.
  87. *
  88. * @param {SocketId} id the socket id
  89. */
  90. delAll(id) {
  91. if (!this.sids.has(id)) {
  92. return;
  93. }
  94. for (const room of this.sids.get(id)) {
  95. this._del(room, id);
  96. }
  97. this.sids.delete(id);
  98. }
  99. /**
  100. * Broadcasts a packet.
  101. *
  102. * Options:
  103. * - `flags` {Object} flags for this packet
  104. * - `except` {Array} sids that should be excluded
  105. * - `rooms` {Array} list of rooms to broadcast to
  106. *
  107. * @param {Object} packet the packet object
  108. * @param {Object} opts the options
  109. * @public
  110. */
  111. broadcast(packet, opts) {
  112. const flags = opts.flags || {};
  113. const packetOpts = {
  114. preEncoded: true,
  115. volatile: flags.volatile,
  116. compress: flags.compress,
  117. };
  118. packet.nsp = this.nsp.name;
  119. const encodedPackets = this._encode(packet, packetOpts);
  120. this.apply(opts, (socket) => {
  121. if (typeof socket.notifyOutgoingListeners === "function") {
  122. socket.notifyOutgoingListeners(packet);
  123. }
  124. socket.client.writeToEngine(encodedPackets, packetOpts);
  125. });
  126. }
  127. /**
  128. * Broadcasts a packet and expects multiple acknowledgements.
  129. *
  130. * Options:
  131. * - `flags` {Object} flags for this packet
  132. * - `except` {Array} sids that should be excluded
  133. * - `rooms` {Array} list of rooms to broadcast to
  134. *
  135. * @param {Object} packet the packet object
  136. * @param {Object} opts the options
  137. * @param clientCountCallback - the number of clients that received the packet
  138. * @param ack - the callback that will be called for each client response
  139. *
  140. * @public
  141. */
  142. broadcastWithAck(packet, opts, clientCountCallback, ack) {
  143. const flags = opts.flags || {};
  144. const packetOpts = {
  145. preEncoded: true,
  146. volatile: flags.volatile,
  147. compress: flags.compress,
  148. };
  149. packet.nsp = this.nsp.name;
  150. // we can use the same id for each packet, since the _ids counter is common (no duplicate)
  151. packet.id = this.nsp._ids++;
  152. const encodedPackets = this._encode(packet, packetOpts);
  153. let clientCount = 0;
  154. this.apply(opts, (socket) => {
  155. // track the total number of acknowledgements that are expected
  156. clientCount++;
  157. // call the ack callback for each client response
  158. socket.acks.set(packet.id, ack);
  159. if (typeof socket.notifyOutgoingListeners === "function") {
  160. socket.notifyOutgoingListeners(packet);
  161. }
  162. socket.client.writeToEngine(encodedPackets, packetOpts);
  163. });
  164. clientCountCallback(clientCount);
  165. }
  166. _encode(packet, packetOpts) {
  167. const encodedPackets = this.encoder.encode(packet);
  168. if (canPreComputeFrame &&
  169. encodedPackets.length === 1 &&
  170. typeof encodedPackets[0] === "string") {
  171. // "4" being the "message" packet type in the Engine.IO protocol
  172. const data = Buffer.from("4" + encodedPackets[0]);
  173. // see https://github.com/websockets/ws/issues/617#issuecomment-283002469
  174. packetOpts.wsPreEncodedFrame = WebSocket.Sender.frame(data, {
  175. readOnly: false,
  176. mask: false,
  177. rsv1: false,
  178. opcode: 1,
  179. fin: true,
  180. });
  181. }
  182. return encodedPackets;
  183. }
  184. /**
  185. * Gets a list of sockets by sid.
  186. *
  187. * @param {Set<Room>} rooms the explicit set of rooms to check.
  188. */
  189. sockets(rooms) {
  190. const sids = new Set();
  191. this.apply({ rooms }, (socket) => {
  192. sids.add(socket.id);
  193. });
  194. return Promise.resolve(sids);
  195. }
  196. /**
  197. * Gets the list of rooms a given socket has joined.
  198. *
  199. * @param {SocketId} id the socket id
  200. */
  201. socketRooms(id) {
  202. return this.sids.get(id);
  203. }
  204. /**
  205. * Returns the matching socket instances
  206. *
  207. * @param opts - the filters to apply
  208. */
  209. fetchSockets(opts) {
  210. const sockets = [];
  211. this.apply(opts, (socket) => {
  212. sockets.push(socket);
  213. });
  214. return Promise.resolve(sockets);
  215. }
  216. /**
  217. * Makes the matching socket instances join the specified rooms
  218. *
  219. * @param opts - the filters to apply
  220. * @param rooms - the rooms to join
  221. */
  222. addSockets(opts, rooms) {
  223. this.apply(opts, (socket) => {
  224. socket.join(rooms);
  225. });
  226. }
  227. /**
  228. * Makes the matching socket instances leave the specified rooms
  229. *
  230. * @param opts - the filters to apply
  231. * @param rooms - the rooms to leave
  232. */
  233. delSockets(opts, rooms) {
  234. this.apply(opts, (socket) => {
  235. rooms.forEach((room) => socket.leave(room));
  236. });
  237. }
  238. /**
  239. * Makes the matching socket instances disconnect
  240. *
  241. * @param opts - the filters to apply
  242. * @param close - whether to close the underlying connection
  243. */
  244. disconnectSockets(opts, close) {
  245. this.apply(opts, (socket) => {
  246. socket.disconnect(close);
  247. });
  248. }
  249. apply(opts, callback) {
  250. const rooms = opts.rooms;
  251. const except = this.computeExceptSids(opts.except);
  252. if (rooms.size) {
  253. const ids = new Set();
  254. for (const room of rooms) {
  255. if (!this.rooms.has(room))
  256. continue;
  257. for (const id of this.rooms.get(room)) {
  258. if (ids.has(id) || except.has(id))
  259. continue;
  260. const socket = this.nsp.sockets.get(id);
  261. if (socket) {
  262. callback(socket);
  263. ids.add(id);
  264. }
  265. }
  266. }
  267. }
  268. else {
  269. for (const [id] of this.sids) {
  270. if (except.has(id))
  271. continue;
  272. const socket = this.nsp.sockets.get(id);
  273. if (socket)
  274. callback(socket);
  275. }
  276. }
  277. }
  278. computeExceptSids(exceptRooms) {
  279. const exceptSids = new Set();
  280. if (exceptRooms && exceptRooms.size > 0) {
  281. for (const room of exceptRooms) {
  282. if (this.rooms.has(room)) {
  283. this.rooms.get(room).forEach((sid) => exceptSids.add(sid));
  284. }
  285. }
  286. }
  287. return exceptSids;
  288. }
  289. /**
  290. * Send a packet to the other Socket.IO servers in the cluster
  291. * @param packet - an array of arguments, which may include an acknowledgement callback at the end
  292. */
  293. serverSideEmit(packet) {
  294. console.warn("this adapter does not support the serverSideEmit() functionality");
  295. }
  296. /**
  297. * Save the client session in order to restore it upon reconnection.
  298. */
  299. persistSession(session) { }
  300. /**
  301. * Restore the session and find the packets that were missed by the client.
  302. * @param pid
  303. * @param offset
  304. */
  305. restoreSession(pid, offset) {
  306. return null;
  307. }
  308. }
  309. exports.Adapter = Adapter;
  310. class SessionAwareAdapter extends Adapter {
  311. constructor(nsp) {
  312. super(nsp);
  313. this.nsp = nsp;
  314. this.sessions = new Map();
  315. this.packets = [];
  316. this.maxDisconnectionDuration =
  317. nsp.server.opts.connectionStateRecovery.maxDisconnectionDuration;
  318. const timer = setInterval(() => {
  319. const threshold = Date.now() - this.maxDisconnectionDuration;
  320. this.sessions.forEach((session, sessionId) => {
  321. const hasExpired = session.disconnectedAt < threshold;
  322. if (hasExpired) {
  323. this.sessions.delete(sessionId);
  324. }
  325. });
  326. for (let i = this.packets.length - 1; i >= 0; i--) {
  327. const hasExpired = this.packets[i].emittedAt < threshold;
  328. if (hasExpired) {
  329. this.packets.splice(0, i + 1);
  330. break;
  331. }
  332. }
  333. }, 60 * 1000);
  334. // prevents the timer from keeping the process alive
  335. timer.unref();
  336. }
  337. persistSession(session) {
  338. session.disconnectedAt = Date.now();
  339. this.sessions.set(session.pid, session);
  340. }
  341. restoreSession(pid, offset) {
  342. const session = this.sessions.get(pid);
  343. if (!session) {
  344. // the session may have expired
  345. return null;
  346. }
  347. const hasExpired = session.disconnectedAt + this.maxDisconnectionDuration < Date.now();
  348. if (hasExpired) {
  349. // the session has expired
  350. this.sessions.delete(pid);
  351. return null;
  352. }
  353. const index = this.packets.findIndex((packet) => packet.id === offset);
  354. if (index === -1) {
  355. // the offset may be too old
  356. return null;
  357. }
  358. const missedPackets = [];
  359. for (let i = index + 1; i < this.packets.length; i++) {
  360. const packet = this.packets[i];
  361. if (shouldIncludePacket(session.rooms, packet.opts)) {
  362. missedPackets.push(packet.data);
  363. }
  364. }
  365. return Promise.resolve(Object.assign(Object.assign({}, session), { missedPackets }));
  366. }
  367. broadcast(packet, opts) {
  368. var _a;
  369. const isEventPacket = packet.type === 2;
  370. // packets with acknowledgement are not stored because the acknowledgement function cannot be serialized and
  371. // restored on another server upon reconnection
  372. const withoutAcknowledgement = packet.id === undefined;
  373. const notVolatile = ((_a = opts.flags) === null || _a === void 0 ? void 0 : _a.volatile) === undefined;
  374. if (isEventPacket && withoutAcknowledgement && notVolatile) {
  375. const id = (0, yeast_1.yeast)();
  376. // the offset is stored at the end of the data array, so the client knows the ID of the last packet it has
  377. // processed (and the format is backward-compatible)
  378. packet.data.push(id);
  379. this.packets.push({
  380. id,
  381. opts,
  382. data: packet.data,
  383. emittedAt: Date.now(),
  384. });
  385. }
  386. super.broadcast(packet, opts);
  387. }
  388. }
  389. exports.SessionAwareAdapter = SessionAwareAdapter;
  390. function shouldIncludePacket(sessionRooms, opts) {
  391. const included = opts.rooms.size === 0 || sessionRooms.some((room) => opts.rooms.has(room));
  392. const notExcluded = sessionRooms.every((room) => !opts.except.has(room));
  393. return included && notExcluded;
  394. }