SocketIoShim.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. /* global io */
  2. import { debugConsole } from '@/utils/debugging'
  3. import EventEmitter from '@/utils/EventEmitter'
  4. class SocketShimBase {
  5. static connect(url, options) {
  6. return new SocketShimBase()
  7. }
  8. constructor(socket) {
  9. this._socket = socket
  10. }
  11. }
  12. const transparentMethods = [
  13. 'connect',
  14. 'disconnect',
  15. 'emit',
  16. 'on',
  17. 'removeListener',
  18. ]
  19. for (const method of transparentMethods) {
  20. SocketShimBase.prototype[method] = function () {
  21. this._socket[method].apply(this._socket, arguments)
  22. }
  23. }
  24. class SocketShimNoop extends SocketShimBase {
  25. static connect() {
  26. return new SocketShimNoop()
  27. }
  28. constructor(socket) {
  29. super(socket)
  30. this.socket = {
  31. get connected() {
  32. return false
  33. },
  34. get sessionid() {
  35. return undefined
  36. },
  37. get transport() {
  38. return {}
  39. },
  40. connect() {},
  41. disconnect(reason) {},
  42. }
  43. }
  44. connect() {}
  45. disconnect(reason) {}
  46. emit() {}
  47. on() {}
  48. removeListener() {}
  49. }
  50. class SocketShimV0 extends SocketShimBase {
  51. static connect(url, options) {
  52. return new SocketShimV0(io.connect(url, options))
  53. }
  54. constructor(socket) {
  55. super(socket)
  56. this.socket = this._socket.socket
  57. }
  58. }
  59. class SocketShimV2 extends SocketShimBase {
  60. static connect(url, options) {
  61. options.forceNew = options['force new connection']
  62. // .resource has no leading slash, path wants to see one.
  63. options.path = '/' + options.resource
  64. options.reconnection = options.reconnect
  65. options.timeout = options['connect timeout']
  66. return new SocketShimV2(url, options)
  67. }
  68. static get EVENT_MAP() {
  69. // Use the v2 event names transparently to the frontend.
  70. const connectionFailureEvents = [
  71. 'connect_error',
  72. 'connect_timeout',
  73. 'error',
  74. ]
  75. return new Map([
  76. ['connect_failed', connectionFailureEvents],
  77. ['error', connectionFailureEvents],
  78. ])
  79. }
  80. _on(event, handler) {
  81. // Keep track of our event listeners.
  82. // We move them to a new socket in ._replaceSocketWithNewInstance()
  83. if (!this._events.has(event)) {
  84. this._events.set(event, [handler])
  85. } else {
  86. this._events.get(event).push(handler)
  87. }
  88. this._socket.on(event, handler)
  89. }
  90. on(event, handler) {
  91. if (SocketShimV2.EVENT_MAP.has(event)) {
  92. for (const v2Event of SocketShimV2.EVENT_MAP.get(event)) {
  93. this._on(v2Event, handler)
  94. }
  95. } else {
  96. this._on(event, handler)
  97. }
  98. }
  99. _removeListener(event, handler) {
  100. // Keep track of our event listeners.
  101. // We move them to a new socket in ._replaceSocketWithNewInstance()
  102. if (this._events.has(event)) {
  103. const listeners = this._events.get(event)
  104. const pos = listeners.indexOf(handler)
  105. if (pos !== -1) {
  106. listeners.splice(pos, 1)
  107. }
  108. }
  109. this._socket.removeListener(event, handler)
  110. }
  111. removeListener(event, handler) {
  112. if (SocketShimV2.EVENT_MAP.has(event)) {
  113. for (const v2Event of SocketShimV2.EVENT_MAP.get(event)) {
  114. this._removeListener(v2Event, handler)
  115. }
  116. } else {
  117. this._removeListener(event, handler)
  118. }
  119. }
  120. static createNewSocket(url, options) {
  121. // open a brand new connection for the default namespace '/'
  122. // The old socket can still leak 'disconnect' events from the teardown
  123. // of the old transport. The leaking 'disconnect' events interfere with
  124. // the _new_ connection and cancel the new connect attempt.
  125. // Also skip the caching in these locations:
  126. // - `io.connect()` caches `io.Manager`s in `io.managers`
  127. // - `io.Manager().socket()` caches `io.Socket`s in its `this.nsps`
  128. return io.Manager(url, options).socket('/', options)
  129. }
  130. _replaceSocketWithNewInstance() {
  131. const oldSocket = this._socket
  132. const newSocket = SocketShimV2.createNewSocket(this._url, this._options)
  133. // move our existing event handlers to the new socket
  134. this._events.forEach((listeners, event) => {
  135. for (const listener of listeners) {
  136. oldSocket.removeListener(event, listener)
  137. newSocket.on(event, listener)
  138. }
  139. })
  140. if (oldSocket.connected) {
  141. // We overwrite the reference to oldSocket soon.
  142. // Make sure we are disconnected.
  143. oldSocket.disconnect()
  144. }
  145. this._socket = newSocket
  146. }
  147. connect() {
  148. // have the same logic behind socket.connect and socket.socket.connect
  149. this._replaceSocketWithNewInstance()
  150. }
  151. constructor(url, options) {
  152. super(SocketShimV2.createNewSocket(url, options))
  153. this._url = url
  154. this._options = options
  155. this._events = new Map()
  156. const self = this
  157. function _getEngine() {
  158. return (self._socket.io && self._socket.io.engine) || {}
  159. }
  160. this.socket = {
  161. get connected() {
  162. return self._socket.connected
  163. },
  164. get sessionid() {
  165. if (self._socket.id) {
  166. return self._socket.id
  167. }
  168. // socket.id is discarded upon disconnect
  169. // the id is still available in the internal state
  170. return _getEngine().id
  171. },
  172. get transport() {
  173. return _getEngine().transport
  174. },
  175. connect() {
  176. self._replaceSocketWithNewInstance()
  177. },
  178. disconnect(reason) {
  179. return self._socket.disconnect(reason)
  180. },
  181. }
  182. }
  183. }
  184. let current
  185. if (typeof io === 'undefined' || !io) {
  186. debugConsole.log('[socket.io] Shim: socket.io is not loaded, returning noop')
  187. current = SocketShimNoop
  188. } else if (typeof io.version === 'string' && io.version.slice(0, 1) === '0') {
  189. debugConsole.log('[socket.io] Shim: detected v0')
  190. current = SocketShimV0
  191. } else {
  192. // socket.io v2 does not have a global io.version attribute.
  193. debugConsole.log('[socket.io] Shim: detected v2')
  194. current = SocketShimV2
  195. }
  196. export class SocketIOMock extends EventEmitter {
  197. addListener(event, listener) {
  198. this.on(event, listener)
  199. }
  200. removeListener(event, listener) {
  201. this.off(event, listener)
  202. }
  203. disconnect() {
  204. this.emitToClient('disconnect')
  205. }
  206. emitToClient(...args) {
  207. // Round-trip through JSON.parse/stringify to simulate (de-)serializing on network layer.
  208. this.emit(...JSON.parse(JSON.stringify(args)))
  209. }
  210. }
  211. export default {
  212. SocketShimNoop,
  213. SocketShimV0,
  214. SocketShimV2,
  215. current,
  216. connect: current.connect,
  217. stub: () => new SocketShimNoop(),
  218. }