async failoverWriter()

in common/lib/plugins/failover/failover_plugin.ts [390:450]


  async failoverWriter() {
    logger.debug(Messages.get("Failover.startWriterFailover"));

    const telemetryFactory = this.pluginService.getTelemetryFactory();
    const telemetryContext = telemetryFactory.openTelemetryContext(FailoverPlugin.TELEMETRY_WRITER_FAILOVER, TelemetryTraceLevel.NESTED);
    this.failoverWriterTriggeredCounter.inc();

    try {
      await telemetryContext.start(async () => {
        try {
          const result = await this._writerFailoverHandler.failover(this.pluginService.getAllHosts());

          if (result) {
            const error = result.error;
            if (error) {
              throw error;
            }
          }

          if (!result || !result.isConnected || !result.client) {
            // "Unable to establish SQL connection to writer host"
            throw new FailoverFailedError(Messages.get("Failover.unableToConnectToWriter"));
          }

          // successfully re-connected to a writer host
          const writerHostInfo = getWriter(result.topology);
          if (!writerHostInfo) {
            throw new AwsWrapperError(Messages.get("Failover.unableToDetermineWriter"));
          }

          await this.pluginService.refreshHostList();
          const allowedHosts = this.pluginService.getHosts();
          if (!allowedHosts.some((hostInfo: HostInfo) => hostInfo.host === writerHostInfo?.host)) {
            const failoverErrorMessage = Messages.get(
              "Failover.newWriterNotAllowed",
              writerHostInfo ? writerHostInfo.host : "<null>",
              logTopology(allowedHosts, "[Failover.newWriterNotAllowed] ")
            );
            logger.error(failoverErrorMessage);
            await this.pluginService.abortTargetClient(result.client);
            throw new FailoverFailedError(failoverErrorMessage);
          }

          await this.pluginService.abortCurrentClient();
          await this.pluginService.setCurrentClient(result.client, writerHostInfo);
          logger.debug(Messages.get("Failover.establishedConnection", this.pluginService.getCurrentHostInfo()?.host ?? ""));
          this.throwFailoverSuccessError();
        } catch (error: any) {
          if (error instanceof FailoverSuccessError) {
            this.failoverWriterSuccessCounter.inc();
          }
          this.failoverWriterFailedCounter.inc();
          throw error;
        }
      });
    } finally {
      if (this.telemetryFailoverAdditionalTopTraceSetting) {
        await telemetryFactory.postCopy(telemetryContext, TelemetryTraceLevel.FORCE_TOP_LEVEL);
      }
    }
  }