diff --git a/common/lib/plugins/aurora_initial_connection_strategy_plugin.ts b/common/lib/plugins/aurora_initial_connection_strategy_plugin.ts index 88e88880..46d3ff39 100644 --- a/common/lib/plugins/aurora_initial_connection_strategy_plugin.ts +++ b/common/lib/plugins/aurora_initial_connection_strategy_plugin.ts @@ -118,7 +118,7 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu writerCandidate = await this.pluginService.identifyConnection(writerCandidateClient); if (writerCandidate) { - if (writerCandidate.role !== HostRole.WRITER) { + if (this.shouldVerifyRole(props) && writerCandidate.role !== HostRole.WRITER) { // Shouldn't be here. But let's try again. await this.pluginService.abortTargetClient(writerCandidateClient); await sleep(retryDelayMs); @@ -131,7 +131,7 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu } writerCandidateClient = await this.pluginService.connect(writerCandidate, props, this); - if ((await this.pluginService.getHostRole(writerCandidateClient)) !== HostRole.WRITER) { + if (this.shouldVerifyRole(props) && (await this.pluginService.getHostRole(writerCandidateClient)) !== HostRole.WRITER) { // If the new connection resolves to a reader instance, this means the topology is outdated. // Force refresh to update the topology. await this.pluginService.forceRefreshHostList(); @@ -181,7 +181,7 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu readerCandidate = await this.pluginService.identifyConnection(readerCandidateClient); if (readerCandidate) { - if (readerCandidate.role !== HostRole.READER) { + if (this.shouldVerifyRole(props) && readerCandidate.role !== HostRole.READER) { if (this.hasNoReaders()) { // It seems that cluster has no readers. Simulate Aurora reader cluster endpoint logic // and return the current (writer) client. @@ -202,7 +202,7 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu } readerCandidateClient = await this.pluginService.connect(readerCandidate, props, this); - if ((await this.pluginService.getHostRole(readerCandidateClient)) !== HostRole.READER) { + if (this.shouldVerifyRole(props) && (await this.pluginService.getHostRole(readerCandidateClient)) !== HostRole.READER) { // If the new connection resolves to a writer instance, this means the topology is outdated. // Force refresh to update the topology. await this.pluginService.forceRefreshHostList(); @@ -231,6 +231,10 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu } } + private shouldVerifyRole(props: Map): boolean { + return WrapperProperties.VERIFY_OPENED_CONNECTION_ROLE.get(props) !== "none"; + } + private getWriter(): HostInfo | null { return this.getAccessibleHosts().find((x) => x.role === HostRole.WRITER) ?? null; } diff --git a/mysql/lib/client.ts b/mysql/lib/client.ts index 04d685cf..f1117818 100644 --- a/mysql/lib/client.ts +++ b/mysql/lib/client.ts @@ -44,7 +44,7 @@ import { isDialectTopologyAware } from "../../common/lib/database_dialect/topolo import { MySQLClient, MySQLPoolClient } from "./mysql_client"; import { DriverConnectionProvider } from "../../common/lib/driver_connection_provider"; import { GlobalAuroraMySQLDatabaseDialect } from "./dialect/global_aurora_mysql_database_dialect"; -import { AwsClientConfig } from "../../common/lib/wrapper_property"; +import { AwsClientConfig, WrapperProperties } from "../../common/lib/wrapper_property"; export interface AwsMySQLClientConfig extends ConnectionOptions, AwsClientConfig {} @@ -77,7 +77,10 @@ class BaseAwsMySQLClient extends AwsClient implements MySQLClient { throw new AwsWrapperError(Messages.get("HostInfo.noHostParameter")); } const result: ClientWrapper = await this.pluginManager.connect(hostInfo, this.properties, true, null); - if (isDialectTopologyAware(this.pluginService.getDialect())) { + if ( + WrapperProperties.VERIFY_OPENED_CONNECTION_ROLE.get(this.properties) !== "none" && + isDialectTopologyAware(this.pluginService.getDialect()) + ) { try { const role = await this.pluginService.getHostRole(result); // The current host role may be incorrect, use the created client to confirm the host role. diff --git a/pg/lib/client.ts b/pg/lib/client.ts index 0037d849..e32385ca 100644 --- a/pg/lib/client.ts +++ b/pg/lib/client.ts @@ -42,7 +42,7 @@ import { isDialectTopologyAware } from "../../common/lib/database_dialect/topolo import { PgClient, PgPoolClient } from "./pg_client"; import { DriverConnectionProvider } from "../../common/lib/driver_connection_provider"; import { GlobalAuroraPgDatabaseDialect } from "./dialect/global_aurora_pg_database_dialect"; -import { AwsClientConfig } from "../../common/lib/wrapper_property"; +import { AwsClientConfig, WrapperProperties } from "../../common/lib/wrapper_property"; export interface AwsPgClientConfig extends ClientConfig, AwsClientConfig {} @@ -205,7 +205,10 @@ class BaseAwsPgClient extends AwsClient implements PgClient { throw new AwsWrapperError(Messages.get("HostInfo.noHostParameter")); } const result: ClientWrapper = await this.pluginManager.connect(hostInfo, this.properties, true, null); - if (isDialectTopologyAware(this.pluginService.getDialect())) { + if ( + WrapperProperties.VERIFY_OPENED_CONNECTION_ROLE.get(this.properties) !== "none" && + isDialectTopologyAware(this.pluginService.getDialect()) + ) { try { const role = await this.pluginService.getHostRole(result); // The current host role may be incorrect, use the created client to confirm the host role. diff --git a/tests/unit/aurora_initial_connection_strategy_plugin.test.ts b/tests/unit/aurora_initial_connection_strategy_plugin.test.ts index 4bf0886c..a23d1632 100644 --- a/tests/unit/aurora_initial_connection_strategy_plugin.test.ts +++ b/tests/unit/aurora_initial_connection_strategy_plugin.test.ts @@ -131,6 +131,53 @@ describe("Aurora initial connection strategy plugin", () => { verify(mockPluginService.forceRefreshHostList()).never(); }); + it.each(["writer", "reader"])("skips %s role verification when verifyOpenedConnectionType is none", async (role) => { + WrapperProperties.VERIFY_OPENED_CONNECTION_ROLE.set(props, "none"); + const isReader = role === "reader"; + const candidate = hostInfoBuilder + .withHost("instance") + .withRole(isReader ? HostRole.READER : HostRole.WRITER) + .build(); + const client = isReader ? readerClient : writerClient; + when(mockRdsUtils.identifyRdsType(anything())).thenReturn(isReader ? RdsUrlType.RDS_READER_CLUSTER : RdsUrlType.RDS_WRITER_CLUSTER); + when(mockPluginService.getAllHosts()).thenReturn([candidate]); + when(mockPluginService.getHosts()).thenReturn([candidate]); + when(mockPluginService.acceptsStrategy(anything(), anything())).thenReturn(true); + when(mockPluginService.getHostInfoByStrategy(anything(), anything(), anything())).thenReturn(candidate); + when(mockPluginService.connect(anything(), anything(), anything())).thenResolve(client); + // A contradictory role must be ignored when verification is disabled. + when(mockPluginService.getHostRole(client)).thenResolve(isReader ? HostRole.WRITER : HostRole.READER); + + expect(await plugin.connect(hostInfo, props, true, mockFunc)).toBe(client); + verify(mockPluginService.getHostRole(anything())).never(); + verify(mockPluginService.forceRefreshHostList()).never(); + verify(mockPluginService.setRoutedHostInfo(candidate)).once(); + }); + + it.each(["writer", "reader"])("does not retry on a topology role mismatch for %s when verifyOpenedConnectionType is none", async (role) => { + WrapperProperties.VERIFY_OPENED_CONNECTION_ROLE.set(props, "none"); + const isReader = role === "reader"; + // No candidate is found up front, and the identified host reports the opposite role. + const identified = hostInfoBuilder + .withHost("instance") + .withRole(isReader ? HostRole.WRITER : HostRole.READER) + .build(); + const client = isReader ? writerClient : readerClient; + const connectFunc = jest.fn(() => Promise.resolve(client)); + when(mockRdsUtils.identifyRdsType(anything())).thenReturn(isReader ? RdsUrlType.RDS_READER_CLUSTER : RdsUrlType.RDS_WRITER_CLUSTER); + // For the reader case the cluster has a reader, so the "no readers" fallback does not apply. + when(mockPluginService.getAllHosts()).thenReturn(isReader ? [hostInfoBuilder.withHost("reader").withRole(HostRole.READER).build()] : []); + when(mockPluginService.getHosts()).thenReturn([]); + when(mockPluginService.acceptsStrategy(anything(), anything())).thenReturn(true); + when(mockPluginService.getHostInfoByStrategy(anything(), anything(), anything())).thenReturn(undefined); + when(mockPluginService.identifyConnection(anything())).thenResolve(identified); + + expect(await plugin.connect(hostInfo, props, true, connectFunc)).toBe(client); + expect(connectFunc).toHaveBeenCalledTimes(1); + verify(mockPluginService.abortTargetClient(anything())).never(); + verify(mockPluginService.setRoutedHostInfo(identified)).once(); + }); + it("test reader - resolves to writer", async () => { when(mockRdsUtils.identifyRdsType(anything())).thenReturn(RdsUrlType.RDS_READER_CLUSTER); when(mockPluginService.getHosts()).thenReturn([hostInfoBuilder.withRole(HostRole.READER).build()]); diff --git a/tests/unit/client_connection_role.test.ts b/tests/unit/client_connection_role.test.ts new file mode 100644 index 00000000..1900e82a --- /dev/null +++ b/tests/unit/client_connection_role.test.ts @@ -0,0 +1,59 @@ +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"). + You may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +import { jest } from "@jest/globals"; +import { AwsMySQLClient } from "../../mysql/lib/client"; +import { AwsPgClient } from "../../pg/lib/client"; +import { HostInfoBuilder } from "../../common/lib/host_info_builder"; +import { SimpleHostAvailabilityStrategy } from "../../common/lib/host_availability/simple_host_availability_strategy"; +import { HostRole } from "../../common/lib/host_role"; + +describe.each([AwsMySQLClient, AwsPgClient])("connection role verification: %p", (Client) => { + it.each([undefined, "none"])("honors verifyOpenedConnectionType=%s", async (verification) => { + const client = new Client({ plugins: "", verifyOpenedConnectionType: verification }); + const host = new HostInfoBuilder({ hostAvailabilityStrategy: new SimpleHostAvailabilityStrategy() }) + .withHost("instance") + .withRole(HostRole.WRITER) + .build(); + const connection = { hostInfo: host }; + const getHostRole = jest.fn(async () => HostRole.READER); + const setCurrentClient = jest.fn(async () => {}); + // Isolate the final role check from connection setup and physical I/O. + Object.assign(client, { + internalConnect: async () => {}, + internalPostConnect: async () => {}, + telemetryFactory: { openTelemetryContext: () => ({ start: async (fn: () => Promise) => fn() }) }, + pluginManager: { connect: async () => connection }, + pluginService: { + getCurrentHostInfo: () => host, + getDialect: () => ({}), + getHostRole, + setCurrentHostInfo: () => {}, + setInitialConnectionHostInfo: () => {}, + getRoutedHostInfo: () => null, + getInitialConnectionHostInfo: () => null, + setRoutedHostInfo: () => {}, + setCurrentClient + } + }); + + await client.connect(); + + expect(getHostRole).toHaveBeenCalledTimes(verification === "none" ? 0 : 1); + expect(host.role).toBe(verification === "none" ? HostRole.WRITER : HostRole.READER); + expect(setCurrentClient).toHaveBeenCalledWith(connection, host); + }); +});