protected async retryConnectWithLeastLoadedRouters()

in common/lib/plugins/limitless/limitless_router_service.ts [136:192]


  protected async retryConnectWithLeastLoadedRouters(context: LimitlessConnectionContext): Promise<void> {
    let remainingAttempts: number = WrapperProperties.MAX_RETRIES.get(context.getProperties());
    while (remainingAttempts-- > 0) {
      if (
        !context.getRouters() ||
        context.getRouters().length === 0 ||
        !context.getRouters().some((h) => h.getAvailability() === HostAvailability.AVAILABLE)
      ) {
        await this.synchronouslyGetLimitlessRoutersWithRetry(context);
        if (
          !context.getRouters() ||
          context.getRouters().length === 0 ||
          !context.getRouters().some((h) => h.getAvailability() === HostAvailability.AVAILABLE)
        ) {
          logger.warn(Messages.get("LimitlessRouterServiceImpl.noRoutersAvailableForRetry"));
          if (context.getConnection()) {
            return;
          } else {
            try {
              context.setConnection(await context.getConnectFunc()());
              return;
            } catch (e) {
              throw new AwsWrapperError(Messages.get("LimitlessRouterServiceImpl.noRoutersAvailable"));
            }
          }
        }
      }

      let selectedHostSpec: HostInfo | undefined = undefined;
      try {
        // Select healthiest router for best chance of connection over load-balancing with round-robin
        selectedHostSpec = this.pluginService.getHostInfoByStrategy(HostRole.WRITER, HighestWeightHostSelector.STRATEGY_NAME, context.getRouters());
        logger.debug(Messages.get("LimitlessRouterServiceImpl.selectedHostForRetry", selectedHostSpec ? selectedHostSpec.host : "undefined"));
        if (!selectedHostSpec) {
          continue;
        }
      } catch (e) {
        if (e instanceof UnsupportedStrategyError) {
          logger.error(Messages.get("LimitlessRouterServiceImpl.incorrectConfiguration"));
          throw e;
        }
        // error from host selector
        continue;
      }

      try {
        context.setConnection(await this.pluginService.connect(selectedHostSpec, context.getProperties()));
        if (context.getConnection()) {
          return;
        }
      } catch (error) {
        selectedHostSpec.setAvailability(HostAvailability.NOT_AVAILABLE);
        logger.debug(Messages.get("LimitlessRouterServiceImpl.failedToConnectToHost", selectedHostSpec.host));
      }
    }
    throw new AwsWrapperError(Messages.get("LimitlessRouterServiceImpl.maxRetriesExceeded"));
  }