var ClientEngine = function()

in src/worker.js [122:292]


  var ClientEngine = function () {
    var self = this;

    this.multiplexer = new connect.StreamMultiplexer();
    this.conduit = new connect.Conduit("AmazonConnectSharedWorker", null, this.multiplexer);
    this.client = new WorkerClient(this.conduit);
    this.timeout = null;
    this.agent = null;
    this.nextToken = null;
    this.initData = {};
    this.portConduitMap = {};
    this.masterCoord = new MasterTopicCoordinator();
    this.logsBuffer = [];
    this.suppress = false;
    this.forceOffline = false;

    var webSocketManager = null;

    connect.rootLogger = new connect.DownstreamConduitLogger(this.conduit);

    this.conduit.onDownstream(connect.EventType.SEND_LOGS, function (logsToUpload) {
      // Add softphone logs downstream
      connect.getLog().pushLogsDownstream(logsToUpload);

      self.logsBuffer = self.logsBuffer.concat(logsToUpload);
      //only call API to send logs if buffer reached cap
      if (self.logsBuffer.length > LOG_BUFFER_CAP_SIZE) {
        self.handleSendLogsRequest(self.logsBuffer);
      }
    });

    this.conduit.onDownstream(connect.EventType.CONFIGURE, function (data) {
      if (data.authToken && data.authToken !== self.initData.authToken) {
        self.initData = data;
        connect.core.init(data);
        // init only once.
        if (!webSocketManager) {

          connect.getLog().info("Creating a new Websocket connection for CCP")
            .sendInternalLogToServer();

          connect.WebSocketManager.setGlobalConfig({
            loggerConfig: { logger: connect.getLog() }
          });

          webSocketManager = connect.WebSocketManager.create();

          webSocketManager.onInitFailure(function () {
            self.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE);
          });

          webSocketManager.onConnectionOpen(function (response) {
            self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_OPEN, response);
          });

          webSocketManager.onConnectionClose(function (response) {
            self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_CLOSE, response);
          });

          webSocketManager.onConnectionGain(function () {
            self.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED);
            self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_GAIN);
          });

          webSocketManager.onConnectionLost(function (response) {
            self.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST, response);
            self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_LOST, response);
          });

          webSocketManager.onSubscriptionUpdate(function (response) {
            self.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE, response);
          });

          webSocketManager.onSubscriptionFailure(function (response) {
            self.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE, response);
          });

          webSocketManager.onAllMessage(function (response) {
            self.conduit.sendDownstream(connect.WebSocketEvents.ALL_MESSAGE, response);
          });

          self.conduit.onDownstream(connect.WebSocketEvents.SEND, function (message) {
            webSocketManager.sendMessage(message);
          });

          self.conduit.onDownstream(connect.WebSocketEvents.SUBSCRIBE, function (topics) {
            webSocketManager.subscribeTopics(topics);
          });

          webSocketManager.init(connect.hitch(self, self.getWebSocketUrl)).then(function(response) {
            try {
              if (response && !response.webSocketConnectionFailed) {
                // Start polling for agent data.
                connect.getLog().info("Kicking off agent polling")
                  .sendInternalLogToServer();
                self.pollForAgent();
  
                connect.getLog().info("Kicking off config polling")
                  .sendInternalLogToServer();
                self.pollForAgentConfiguration({ repeatForever: true });
  
                connect.getLog().info("Kicking off auth token polling")
                  .sendInternalLogToServer();
                global.setInterval(connect.hitch(self, self.checkAuthToken), CHECK_AUTH_TOKEN_INTERVAL_MS);
              } else {
                if (!connect.webSocketInitFailed) {
                  const event = connect.WebSocketEvents.INIT_FAILURE;
                  self.conduit.sendDownstream(event);
                  connect.webSocketInitFailed = true;
                  throw new Error(event);
                }
              }
            } catch (e) {
              connect.getLog().error("WebSocket failed to initialize")
                .withException(e)
                .sendInternalLogToServer();
            }
          });
        } else {
          connect.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists")
            .sendInternalLogToServer();
        }
      }
    });
    this.conduit.onDownstream(connect.EventType.TERMINATE, function () {
      //upload pending logs before terminating.
      self.handleSendLogsRequest(self.logsBuffer);
      connect.core.terminate();
      self.conduit.sendDownstream(connect.EventType.TERMINATED);
    });
    this.conduit.onDownstream(connect.EventType.SYNCHRONIZE, function () {
      self.conduit.sendDownstream(connect.EventType.ACKNOWLEDGE);
    });
    this.conduit.onDownstream(connect.EventType.BROADCAST, function (data) {
      self.conduit.sendDownstream(data.event, data.data);
    });

    /**
     * Called when a consumer port connects to this SharedWorker.
     * Let's add them to our multiplexer.
     */
    global.onconnect = function (event) {
      var port = event.ports[0];
      var stream = new connect.PortStream(port);
      self.multiplexer.addStream(stream);
      port.start();

      var portConduit = new connect.Conduit(stream.getId(), null, stream);
      portConduit.sendDownstream(connect.EventType.ACKNOWLEDGE, { id: stream.getId() });

      self.portConduitMap[stream.getId()] = portConduit;
      self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { length: Object.keys(self.portConduitMap).length });

      if (self.agent !== null) {
        self.updateAgent();
      }

      portConduit.onDownstream(connect.EventType.API_REQUEST,
        connect.hitch(self, self.handleAPIRequest, portConduit));
      portConduit.onDownstream(connect.EventType.MASTER_REQUEST,
        connect.hitch(self, self.handleMasterRequest, portConduit, stream.getId()));
      portConduit.onDownstream(connect.EventType.RELOAD_AGENT_CONFIGURATION,
        connect.hitch(self, self.pollForAgentConfiguration));
      portConduit.onDownstream(connect.EventType.CLOSE, function () {
        self.multiplexer.removeStream(stream);
        delete self.portConduitMap[stream.getId()];
        self.masterCoord.removeMaster(stream.getId());
        self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { length: Object.keys(self.portConduitMap).length });
      });
    };
  };