Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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();
Expand Down Expand Up @@ -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.
Expand All @@ -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();
Expand Down Expand Up @@ -231,6 +231,10 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu
}
}

private shouldVerifyRole(props: Map<string, any>): boolean {
return WrapperProperties.VERIFY_OPENED_CONNECTION_ROLE.get(props) !== "none";
}

private getWriter(): HostInfo | null {
return this.getAccessibleHosts().find((x) => x.role === HostRole.WRITER) ?? null;
}
Expand Down
7 changes: 5 additions & 2 deletions mysql/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}

Expand Down Expand Up @@ -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.
Expand Down
7 changes: 5 additions & 2 deletions pg/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}

Expand Down Expand Up @@ -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.
Expand Down
47 changes: 47 additions & 0 deletions tests/unit/aurora_initial_connection_strategy_plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()]);
Expand Down
59 changes: 59 additions & 0 deletions tests/unit/client_connection_role.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>) => 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);
});
});