manager.js 12 KB

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