manager.js 12 KB

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