socketManager.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const _ = require('./utils/underscore.js');
  2. const Q = require('bluebird');
  3. const log = require('./utils/logger').create('Sockets');
  4. const Web3IpcSocket = require('./sockets/web3Ipc');
  5. const Web3HttpSocket = require('./sockets/web3Http');
  6. /**
  7. * `Socket` manager.
  8. */
  9. class SocketManager {
  10. constructor() {
  11. this._sockets = {};
  12. }
  13. /**
  14. * Get socket with given id, creating it if it does not exist.
  15. *
  16. * @return {Socket}
  17. */
  18. create(id, type) {
  19. log.debug(`Create socket, id=${id}, type=${type}`);
  20. switch (type) {
  21. case 'ipc':
  22. this._sockets[id] = new Web3IpcSocket(this, id);
  23. break;
  24. case 'http':
  25. this._sockets[id] = new Web3HttpSocket(this, id);
  26. break;
  27. default:
  28. throw new Error(`Unrecognized socket type: ${type}`);
  29. }
  30. return this._sockets[id];
  31. }
  32. /**
  33. * Get socket with given id, creating it if it does not exist.
  34. *
  35. * @return {Socket}
  36. */
  37. get(id, type) {
  38. if (!this._sockets[id]) {
  39. this.create(id, type);
  40. }
  41. return this._sockets[id];
  42. }
  43. /**
  44. * @return {Promise}
  45. */
  46. destroyAll() {
  47. log.info('Destroy all sockets');
  48. return Q.all(
  49. _.map(this._sockets, (s, id) => {
  50. this.remove(id);
  51. return s.destroy();
  52. })
  53. );
  54. }
  55. /**
  56. * Remove socket with given id from this manager.
  57. *
  58. * Usually called by `Socket` instances when they're destroyed.
  59. */
  60. remove(id) {
  61. log.debug(`Remove socket, id=${id}`);
  62. delete this._sockets[id];
  63. }
  64. }
  65. module.exports = new SocketManager();