multiclient.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. module.exports = function (dependencies) {
  2. const { Client } = dependencies;
  3. /**
  4. * This is a simple round-robin pool of http/2 clients.
  5. * Most use cases would not need this.
  6. *
  7. * While http/2 itself supports multiplexing,
  8. * there are limits on the number of active simultaneous requests
  9. * that may be hit.
  10. *
  11. * This approach was chosen because it's easy to reason about compared to
  12. * switching to an http2 pool implementation.
  13. */
  14. function MultiClient(options) {
  15. const count = parseInt(options.clientCount || 2, 10);
  16. if (count < 1 || !Number.isFinite(count)) {
  17. throw new Error(`Expected positive client count but got ${options.clientCount}`);
  18. }
  19. const clients = [];
  20. for (let i = 0; i < count; i++) {
  21. clients.push(new Client(options));
  22. }
  23. this.clients = clients;
  24. this.clientIndex = 0;
  25. }
  26. MultiClient.prototype.chooseSingleClient = function () {
  27. const client = this.clients[this.clientIndex];
  28. this.clientIndex = (this.clientIndex + 1) % this.clients.length;
  29. return client;
  30. };
  31. MultiClient.prototype.write = function write(notification, device, count) {
  32. return this.chooseSingleClient().write(notification, device, count);
  33. };
  34. MultiClient.prototype.shutdown = function shutdown(callback) {
  35. let callCount = 0;
  36. const multiCallback = () => {
  37. callCount++;
  38. if (callCount === this.clients.length) {
  39. callback();
  40. }
  41. };
  42. this.clients.forEach(client => client.shutdown(multiCallback));
  43. };
  44. MultiClient.prototype.setLogger = function (newLogger, newErrorLogger = null) {
  45. this.clients.forEach(client => client.setLogger(newLogger, newErrorLogger));
  46. };
  47. return MultiClient;
  48. };