manager.js 11 KB

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