manager.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import { Socket as Engine, installTimerFunctions, } from "engine.io-client";
  2. import { Socket } from "./socket.js";
  3. import * as parser from "socket.io-parser";
  4. import { on } from "./on.js";
  5. import Backoff from "backo2";
  6. import { Emitter, } from "@socket.io/component-emitter";
  7. export class Manager extends Emitter {
  8. constructor(uri, opts) {
  9. var _a;
  10. super();
  11. this.nsps = {};
  12. this.subs = [];
  13. if (uri && "object" === typeof uri) {
  14. opts = uri;
  15. uri = undefined;
  16. }
  17. opts = opts || {};
  18. opts.path = opts.path || "/socket.io";
  19. this.opts = opts;
  20. installTimerFunctions(this, opts);
  21. this.reconnection(opts.reconnection !== false);
  22. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  23. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  24. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  25. this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
  26. this.backoff = new Backoff({
  27. min: this.reconnectionDelay(),
  28. max: this.reconnectionDelayMax(),
  29. jitter: this.randomizationFactor(),
  30. });
  31. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  32. this._readyState = "closed";
  33. this.uri = uri;
  34. const _parser = opts.parser || parser;
  35. this.encoder = new _parser.Encoder();
  36. this.decoder = new _parser.Decoder();
  37. this._autoConnect = opts.autoConnect !== false;
  38. if (this._autoConnect)
  39. this.open();
  40. }
  41. reconnection(v) {
  42. if (!arguments.length)
  43. return this._reconnection;
  44. this._reconnection = !!v;
  45. return this;
  46. }
  47. reconnectionAttempts(v) {
  48. if (v === undefined)
  49. return this._reconnectionAttempts;
  50. this._reconnectionAttempts = v;
  51. return this;
  52. }
  53. reconnectionDelay(v) {
  54. var _a;
  55. if (v === undefined)
  56. return this._reconnectionDelay;
  57. this._reconnectionDelay = v;
  58. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
  59. return this;
  60. }
  61. randomizationFactor(v) {
  62. var _a;
  63. if (v === undefined)
  64. return this._randomizationFactor;
  65. this._randomizationFactor = v;
  66. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
  67. return this;
  68. }
  69. reconnectionDelayMax(v) {
  70. var _a;
  71. if (v === undefined)
  72. return this._reconnectionDelayMax;
  73. this._reconnectionDelayMax = v;
  74. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
  75. return this;
  76. }
  77. timeout(v) {
  78. if (!arguments.length)
  79. return this._timeout;
  80. this._timeout = v;
  81. return this;
  82. }
  83. /**
  84. * Starts trying to reconnect if reconnection is enabled and we have not
  85. * started reconnecting yet
  86. *
  87. * @private
  88. */
  89. maybeReconnectOnOpen() {
  90. // Only try to reconnect if it's the first time we're connecting
  91. if (!this._reconnecting &&
  92. this._reconnection &&
  93. this.backoff.attempts === 0) {
  94. // keeps reconnection from firing twice for the same reconnection loop
  95. this.reconnect();
  96. }
  97. }
  98. /**
  99. * Sets the current transport `socket`.
  100. *
  101. * @param {Function} fn - optional, callback
  102. * @return self
  103. * @public
  104. */
  105. open(fn) {
  106. if (~this._readyState.indexOf("open"))
  107. return this;
  108. this.engine = new Engine(this.uri, this.opts);
  109. const socket = this.engine;
  110. const self = this;
  111. this._readyState = "opening";
  112. this.skipReconnect = false;
  113. // emit `open`
  114. const openSubDestroy = on(socket, "open", function () {
  115. self.onopen();
  116. fn && fn();
  117. });
  118. // emit `error`
  119. const errorSub = on(socket, "error", (err) => {
  120. self.cleanup();
  121. self._readyState = "closed";
  122. this.emitReserved("error", err);
  123. if (fn) {
  124. fn(err);
  125. }
  126. else {
  127. // Only do this if there is no fn to handle the error
  128. self.maybeReconnectOnOpen();
  129. }
  130. });
  131. if (false !== this._timeout) {
  132. const timeout = this._timeout;
  133. if (timeout === 0) {
  134. openSubDestroy(); // prevents a race condition with the 'open' event
  135. }
  136. // set timer
  137. const timer = this.setTimeoutFn(() => {
  138. openSubDestroy();
  139. socket.close();
  140. // @ts-ignore
  141. socket.emit("error", new Error("timeout"));
  142. }, timeout);
  143. if (this.opts.autoUnref) {
  144. timer.unref();
  145. }
  146. this.subs.push(function subDestroy() {
  147. clearTimeout(timer);
  148. });
  149. }
  150. this.subs.push(openSubDestroy);
  151. this.subs.push(errorSub);
  152. return this;
  153. }
  154. /**
  155. * Alias for open()
  156. *
  157. * @return self
  158. * @public
  159. */
  160. connect(fn) {
  161. return this.open(fn);
  162. }
  163. /**
  164. * Called upon transport open.
  165. *
  166. * @private
  167. */
  168. onopen() {
  169. // clear old subs
  170. this.cleanup();
  171. // mark as open
  172. this._readyState = "open";
  173. this.emitReserved("open");
  174. // add new subs
  175. const socket = this.engine;
  176. this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)), on(this.decoder, "decoded", this.ondecoded.bind(this)));
  177. }
  178. /**
  179. * Called upon a ping.
  180. *
  181. * @private
  182. */
  183. onping() {
  184. this.emitReserved("ping");
  185. }
  186. /**
  187. * Called with data.
  188. *
  189. * @private
  190. */
  191. ondata(data) {
  192. this.decoder.add(data);
  193. }
  194. /**
  195. * Called when parser fully decodes a packet.
  196. *
  197. * @private
  198. */
  199. ondecoded(packet) {
  200. this.emitReserved("packet", packet);
  201. }
  202. /**
  203. * Called upon socket error.
  204. *
  205. * @private
  206. */
  207. onerror(err) {
  208. this.emitReserved("error", err);
  209. }
  210. /**
  211. * Creates a new socket for the given `nsp`.
  212. *
  213. * @return {Socket}
  214. * @public
  215. */
  216. socket(nsp, opts) {
  217. let socket = this.nsps[nsp];
  218. if (!socket) {
  219. socket = new Socket(this, nsp, opts);
  220. this.nsps[nsp] = socket;
  221. }
  222. return socket;
  223. }
  224. /**
  225. * Called upon a socket close.
  226. *
  227. * @param socket
  228. * @private
  229. */
  230. _destroy(socket) {
  231. const nsps = Object.keys(this.nsps);
  232. for (const nsp of nsps) {
  233. const socket = this.nsps[nsp];
  234. if (socket.active) {
  235. return;
  236. }
  237. }
  238. this._close();
  239. }
  240. /**
  241. * Writes a packet.
  242. *
  243. * @param packet
  244. * @private
  245. */
  246. _packet(packet) {
  247. const encodedPackets = this.encoder.encode(packet);
  248. for (let i = 0; i < encodedPackets.length; i++) {
  249. this.engine.write(encodedPackets[i], packet.options);
  250. }
  251. }
  252. /**
  253. * Clean up transport subscriptions and packet buffer.
  254. *
  255. * @private
  256. */
  257. cleanup() {
  258. this.subs.forEach((subDestroy) => subDestroy());
  259. this.subs.length = 0;
  260. this.decoder.destroy();
  261. }
  262. /**
  263. * Close the current socket.
  264. *
  265. * @private
  266. */
  267. _close() {
  268. this.skipReconnect = true;
  269. this._reconnecting = false;
  270. this.onclose("forced close");
  271. if (this.engine)
  272. this.engine.close();
  273. }
  274. /**
  275. * Alias for close()
  276. *
  277. * @private
  278. */
  279. disconnect() {
  280. return this._close();
  281. }
  282. /**
  283. * Called upon engine close.
  284. *
  285. * @private
  286. */
  287. onclose(reason) {
  288. this.cleanup();
  289. this.backoff.reset();
  290. this._readyState = "closed";
  291. this.emitReserved("close", reason);
  292. if (this._reconnection && !this.skipReconnect) {
  293. this.reconnect();
  294. }
  295. }
  296. /**
  297. * Attempt a reconnection.
  298. *
  299. * @private
  300. */
  301. reconnect() {
  302. if (this._reconnecting || this.skipReconnect)
  303. return this;
  304. const self = this;
  305. if (this.backoff.attempts >= this._reconnectionAttempts) {
  306. this.backoff.reset();
  307. this.emitReserved("reconnect_failed");
  308. this._reconnecting = false;
  309. }
  310. else {
  311. const delay = this.backoff.duration();
  312. this._reconnecting = true;
  313. const timer = this.setTimeoutFn(() => {
  314. if (self.skipReconnect)
  315. return;
  316. this.emitReserved("reconnect_attempt", self.backoff.attempts);
  317. // check again for the case socket closed in above events
  318. if (self.skipReconnect)
  319. return;
  320. self.open((err) => {
  321. if (err) {
  322. self._reconnecting = false;
  323. self.reconnect();
  324. this.emitReserved("reconnect_error", err);
  325. }
  326. else {
  327. self.onreconnect();
  328. }
  329. });
  330. }, delay);
  331. if (this.opts.autoUnref) {
  332. timer.unref();
  333. }
  334. this.subs.push(function subDestroy() {
  335. clearTimeout(timer);
  336. });
  337. }
  338. }
  339. /**
  340. * Called upon successful reconnect.
  341. *
  342. * @private
  343. */
  344. onreconnect() {
  345. const attempt = this.backoff.attempts;
  346. this._reconnecting = false;
  347. this.backoff.reset();
  348. this.emitReserved("reconnect", attempt);
  349. }
  350. }