public async establishConnection()

in common/lib/plugins/limitless/limitless_router_service.ts [75:128]


  public async establishConnection(context: LimitlessConnectionContext): Promise<void> {
    context.setRouters(this.getLimitlessRouters(context.getProperties()));

    if (!context.getRouters() || context.getRouters().length === 0) {
      logger.debug(Messages.get("LimitlessRouterServiceImpl.limitlessRouterCacheEmpty"));
      const waitForRouterInfo = WrapperProperties.WAIT_F0R_ROUTER_INFO.get(context.getProperties());
      if (waitForRouterInfo) {
        await this.synchronouslyGetLimitlessRoutersWithRetry(context);
      } else {
        logger.debug(Messages.get("LimitlessRouterServiceImpl.usingProvidedConnectUrl"));
        if (!context.getConnection()) {
          context.setConnection(await context.getConnectFunc()());
        }
        return;
      }
    }

    if (context.getRouters() && context.getRouters().some((h: HostInfo) => h.equals(context.getHostInfo()))) {
      logger.debug(Messages.get("LimitlessRouterServiceImpl.connectWithHost", context.getHostInfo().host));
      if (!context.getConnection()) {
        try {
          context.setConnection(await context.getConnectFunc()());
        } catch (e) {
          await this.retryConnectWithLeastLoadedRouters(context);
        }
      }
      return;
    }

    RoundRobinHostSelector.setRoundRobinHostWeightPairsProperty(context.getRouters(), context.getProperties());
    let selectedHostSpec: HostInfo | undefined;
    try {
      selectedHostSpec = this.pluginService.getHostInfoByStrategy(HostRole.WRITER, RoundRobinHostSelector.STRATEGY_NAME, context.getRouters());
      logger.debug(Messages.get("LimitlessRouterServiceImpl.selectedHost", selectedHostSpec ? selectedHostSpec.host : "undefined"));
    } catch (error: any) {
      await this.retryConnectWithLeastLoadedRouters(context);
      return;
    }

    if (!selectedHostSpec) {
      await this.retryConnectWithLeastLoadedRouters(context);
      return;
    }

    try {
      context.setConnection(await this.pluginService.connect(selectedHostSpec, context.getProperties()));
    } catch (e) {
      logger.debug(Messages.get("LimitlessRouterServiceImpl.failedToConnectToHost", selectedHostSpec.host));
      selectedHostSpec.setAvailability(HostAvailability.NOT_AVAILABLE);

      // Retry connect prioritising the healthiest router for best chance of connection over load-balancing with round-robin
      await this.retryConnectWithLeastLoadedRouters(context);
    }
  }