manager.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import { Socket as Engine, installTimerFunctions, nextTick, } 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 "./contrib/backo2.js";
  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. const onError = (err) => {
  123. debug("error");
  124. this.cleanup();
  125. this._readyState = "closed";
  126. this.emitReserved("error", err);
  127. if (fn) {
  128. fn(err);
  129. }
  130. else {
  131. // Only do this if there is no fn to handle the error
  132. this.maybeReconnectOnOpen();
  133. }
  134. };
  135. // emit `error`
  136. const errorSub = on(socket, "error", onError);
  137. if (false !== this._timeout) {
  138. const timeout = this._timeout;
  139. debug("connect attempt will timeout after %d", timeout);
  140. // set timer
  141. const timer = this.setTimeoutFn(() => {
  142. debug("connect attempt timed out after %d", timeout);
  143. openSubDestroy();
  144. onError(new Error("timeout"));
  145. socket.close();
  146. }, timeout);
  147. if (this.opts.autoUnref) {
  148. timer.unref();
  149. }
  150. this.subs.push(() => {
  151. this.clearTimeoutFn(timer);
  152. });
  153. }
  154. this.subs.push(openSubDestroy);
  155. this.subs.push(errorSub);
  156. return this;
  157. }
  158. /**
  159. * Alias for open()
  160. *
  161. * @return self
  162. * @public
  163. */
  164. connect(fn) {
  165. return this.open(fn);
  166. }
  167. /**
  168. * Called upon transport open.
  169. *
  170. * @private
  171. */
  172. onopen() {
  173. debug("open");
  174. // clear old subs
  175. this.cleanup();
  176. // mark as open
  177. this._readyState = "open";
  178. this.emitReserved("open");
  179. // add new subs
  180. const socket = this.engine;
  181. 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)));
  182. }
  183. /**
  184. * Called upon a ping.
  185. *
  186. * @private
  187. */
  188. onping() {
  189. this.emitReserved("ping");
  190. }
  191. /**
  192. * Called with data.
  193. *
  194. * @private
  195. */
  196. ondata(data) {
  197. try {
  198. this.decoder.add(data);
  199. }
  200. catch (e) {
  201. this.onclose("parse error", e);
  202. }
  203. }
  204. /**
  205. * Called when parser fully decodes a packet.
  206. *
  207. * @private
  208. */
  209. ondecoded(packet) {
  210. // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
  211. nextTick(() => {
  212. this.emitReserved("packet", packet);
  213. }, this.setTimeoutFn);
  214. }
  215. /**
  216. * Called upon socket error.
  217. *
  218. * @private
  219. */
  220. onerror(err) {
  221. debug("error", err);
  222. this.emitReserved("error", err);
  223. }
  224. /**
  225. * Creates a new socket for the given `nsp`.
  226. *
  227. * @return {Socket}
  228. * @public
  229. */
  230. socket(nsp, opts) {
  231. let socket = this.nsps[nsp];
  232. if (!socket) {
  233. socket = new Socket(this, nsp, opts);
  234. this.nsps[nsp] = socket;
  235. }
  236. else if (this._autoConnect && !socket.active) {
  237. socket.connect();
  238. }
  239. return socket;
  240. }
  241. /**
  242. * Called upon a socket close.
  243. *
  244. * @param socket
  245. * @private
  246. */
  247. _destroy(socket) {
  248. const nsps = Object.keys(this.nsps);
  249. for (const nsp of nsps) {
  250. const socket = this.nsps[nsp];
  251. if (socket.active) {
  252. debug("socket %s is still active, skipping close", nsp);
  253. return;
  254. }
  255. }
  256. this._close();
  257. }
  258. /**
  259. * Writes a packet.
  260. *
  261. * @param packet
  262. * @private
  263. */
  264. _packet(packet) {
  265. debug("writing packet %j", packet);
  266. const encodedPackets = this.encoder.encode(packet);
  267. for (let i = 0; i < encodedPackets.length; i++) {
  268. this.engine.write(encodedPackets[i], packet.options);
  269. }
  270. }
  271. /**
  272. * Clean up transport subscriptions and packet buffer.
  273. *
  274. * @private
  275. */
  276. cleanup() {
  277. debug("cleanup");
  278. this.subs.forEach((subDestroy) => subDestroy());
  279. this.subs.length = 0;
  280. this.decoder.destroy();
  281. }
  282. /**
  283. * Close the current socket.
  284. *
  285. * @private
  286. */
  287. _close() {
  288. debug("disconnect");
  289. this.skipReconnect = true;
  290. this._reconnecting = false;
  291. this.onclose("forced close");
  292. if (this.engine)
  293. this.engine.close();
  294. }
  295. /**
  296. * Alias for close()
  297. *
  298. * @private
  299. */
  300. disconnect() {
  301. return this._close();
  302. }
  303. /**
  304. * Called upon engine close.
  305. *
  306. * @private
  307. */
  308. onclose(reason, description) {
  309. debug("closed due to %s", reason);
  310. this.cleanup();
  311. this.backoff.reset();
  312. this._readyState = "closed";
  313. this.emitReserved("close", reason, description);
  314. if (this._reconnection && !this.skipReconnect) {
  315. this.reconnect();
  316. }
  317. }
  318. /**
  319. * Attempt a reconnection.
  320. *
  321. * @private
  322. */
  323. reconnect() {
  324. if (this._reconnecting || this.skipReconnect)
  325. return this;
  326. const self = this;
  327. if (this.backoff.attempts >= this._reconnectionAttempts) {
  328. debug("reconnect failed");
  329. this.backoff.reset();
  330. this.emitReserved("reconnect_failed");
  331. this._reconnecting = false;
  332. }
  333. else {
  334. const delay = this.backoff.duration();
  335. debug("will wait %dms before reconnect attempt", delay);
  336. this._reconnecting = true;
  337. const timer = this.setTimeoutFn(() => {
  338. if (self.skipReconnect)
  339. return;
  340. debug("attempting reconnect");
  341. this.emitReserved("reconnect_attempt", self.backoff.attempts);
  342. // check again for the case socket closed in above events
  343. if (self.skipReconnect)
  344. return;
  345. self.open((err) => {
  346. if (err) {
  347. debug("reconnect attempt error");
  348. self._reconnecting = false;
  349. self.reconnect();
  350. this.emitReserved("reconnect_error", err);
  351. }
  352. else {
  353. debug("reconnect success");
  354. self.onreconnect();
  355. }
  356. });
  357. }, delay);
  358. if (this.opts.autoUnref) {
  359. timer.unref();
  360. }
  361. this.subs.push(() => {
  362. this.clearTimeoutFn(timer);
  363. });
  364. }
  365. }
  366. /**
  367. * Called upon successful reconnect.
  368. *
  369. * @private
  370. */
  371. onreconnect() {
  372. const attempt = this.backoff.attempts;
  373. this._reconnecting = false;
  374. this.backoff.reset();
  375. this.emitReserved("reconnect", attempt);
  376. }
  377. }