Skip to content
Open
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
33 changes: 27 additions & 6 deletions common/lib/plugins/aurora_initial_connection_strategy_plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu
}

if (type === RdsUrlType.RDS_WRITER_CLUSTER) {
const writerCandidateClient = await this.getVerifiedWriterClient(props, isInitialConnection, connectFunc);
const writerCandidateClient = await this.getVerifiedWriterClient(props, isInitialConnection, connectFunc, hostInfo.host);
if (writerCandidateClient === null) {
// Can't get writer connection. Continue with a normal workflow.
logger.debug("Writer cluster endpoint does not resolve to a valid reader instance, skipping the initial connection strategy logic.");
Expand All @@ -94,11 +94,17 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu
return connectFunc();
}

async getVerifiedWriterClient<T>(props: Map<string, any>, isInitialConnection: boolean, connectFunc: () => Promise<T>): Promise<any> {
async getVerifiedWriterClient<T>(
props: Map<string, any>,
isInitialConnection: boolean,
connectFunc: () => Promise<T>,
originalHost?: string
): Promise<any> {
if (!this.hostListProviderService) {
throw new AwsWrapperError(Messages.get("HostListProviderService.notFound")); // should not be reached
}
const retryDelayMs = WrapperProperties.OPEN_CONNECTION_RETRY_INTERVAL_MS.get(props);
const verifyRole = this.shouldVerifyWriterRole(props, originalHost);

const endTimeMillis = Date.now() + WrapperProperties.OPEN_CONNECTION_RETRY_TIMEOUT_MS.get(props);
let writerCandidateClient: any;
Expand All @@ -118,7 +124,7 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu
writerCandidate = await this.pluginService.identifyConnection(writerCandidateClient);

if (writerCandidate) {
if (this.shouldVerifyRole(props) && writerCandidate.role !== HostRole.WRITER) {
if (verifyRole && 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 +137,7 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu
}
writerCandidateClient = await this.pluginService.connect(writerCandidate, props, this);

if (this.shouldVerifyRole(props) && (await this.pluginService.getHostRole(writerCandidateClient)) !== HostRole.WRITER) {
if (verifyRole && (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 @@ -160,6 +166,7 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu
}

const retryDelayMs = WrapperProperties.OPEN_CONNECTION_RETRY_INTERVAL_MS.get(props);
const verifyRole = this.shouldVerifyRole(props);
const endTimeMs = Date.now() + WrapperProperties.OPEN_CONNECTION_RETRY_TIMEOUT_MS.get(props);

let readerCandidateClient: any;
Expand All @@ -181,7 +188,7 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu
readerCandidate = await this.pluginService.identifyConnection(readerCandidateClient);

if (readerCandidate) {
if (this.shouldVerifyRole(props) && readerCandidate.role !== HostRole.READER) {
if (verifyRole && 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 +209,7 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu
}
readerCandidateClient = await this.pluginService.connect(readerCandidate, props, this);

if (this.shouldVerifyRole(props) && (await this.pluginService.getHostRole(readerCandidateClient)) !== HostRole.READER) {
if (verifyRole && (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 @@ -235,6 +242,20 @@ export class AuroraInitialConnectionStrategyPlugin extends AbstractConnectionPlu
return WrapperProperties.VERIFY_OPENED_CONNECTION_ROLE.get(props) !== "none";
}

private shouldVerifyWriterRole(props: Map<string, any>, originalHost?: string): boolean {
const setting = WrapperProperties.VERIFY_OPENED_CONNECTION_ROLE.get(props);
if (setting != null) {
return setting !== "none";
}

const writer = this.getWriter();
if (writer !== null && originalHost && this.rdsUtils.isRdsInstance(writer.host) && this.rdsUtils.isSameRegion(writer.host, originalHost)) {
return true;
}

return WrapperProperties.VERIFY_INACTIVE_CLUSTER_WRITER_CONNECTION_ROLE.get(props) !== "none";
}

private getWriter(): HostInfo | null {
return this.getAccessibleHosts().find((x) => x.role === HostRole.WRITER) ?? null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,38 @@ Since version 2.1.1, the Aurora Initial Connection Strategy Plugin will be enabl

The following properties can be used to configure the Aurora Initial Connection Strategy Plugin.

| Parameter | Value | Required | Description | Example | Default Value |
| ------------------------------- | :----: | :------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------ | ------------- |
| `readerHostSelectorStrategy` | string | No | The strategy that will be used to select a new reader host when opening a new connection. <br><br> For more information on the available reader selection strategies, see this [table](../ReaderSelectionStrategies.md). | `leastConnections` | `random` |
| `openConnectionRetryTimeoutMs` | number | No | The maximum allowed time for retries when opening a connection in milliseconds. | `40000` | `30000` |
| `openConnectionRetryIntervalMs` | number | No | The time between retries when opening a connection in milliseconds. | `2000` | `1000` |
| Parameter | Value | Required | Description | Example | Default Value |
| --------------------------------------------------- | :----: | :------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ------------- |
| `readerHostSelectorStrategy` | string | No | The strategy that will be used to select a new reader host when opening a new connection. <br><br> For more information on the available reader selection strategies, see this [table](../ReaderSelectionStrategies.md). | `leastConnections` | `random` |
| `openConnectionRetryTimeoutMs` | number | No | The maximum allowed time for retries when opening a connection in milliseconds. | `40000` | `30000` |
| `openConnectionRetryIntervalMs` | number | No | The time between retries when opening a connection in milliseconds. | `2000` | `1000` |
| `verifyOpenedConnectionType` | string | No | Controls whether the role of an opened connection is verified. Allowed values are `writer`, `reader` and `none`. Set to `none` to disable role verification. See [Disabling role verification](#disabling-role-verification). | `none` | `null` |
| `verifyInactiveClusterWriterEndpointConnectionType` | string | No | Controls whether a connection opened through a writer cluster endpoint that may be inactive is verified to be a writer. Allowed values are `writer` and `none`. Applies only when `verifyOpenedConnectionType` is not set. See [Inactive writer cluster endpoints](#inactive-writer-cluster-endpoints). | `none` | `writer` |

## Disabling role verification

By default, the plugin checks that a newly opened connection has the expected role (writer or reader). If it does not, the plugin refreshes the topology, closes the connection and retries until `openConnectionRetryTimeoutMs` elapses. Each check requires a query on the new connection.

Setting `verifyOpenedConnectionType` to `none` turns off these role checks. With `none`:

- The plugin does not query the role of the opened connection, and it does not retry because of a role mismatch. This includes mismatches reported by the topology when connecting through a cluster endpoint.
- The plugin still uses the topology to choose an instance, applies the reader selection strategy and any accessible-region filtering, and retries if a connection attempt fails.
- The wrapper does not confirm the role of the connection after it is opened, so the role it records for the host may be out of date.
- A reader cluster endpoint can return a writer connection, for example while DNS is updating. Without role verification the plugin does not retry to obtain a reader.

Use `none` only if you want to avoid the role queries and can tolerate a connection whose role has not been confirmed.

> [!NOTE]
> `verifyOpenedConnectionType` applies only to role verification of newly opened connections. It does not change the role checks that failover plugins perform when selecting a new host.

### Inactive writer cluster endpoints

With an Aurora Global Database, the writer cluster endpoint in a secondary region is inactive and does not point to the current writer. The same is true when the topology is not yet available. When `verifyOpenedConnectionType` is not set, the plugin verifies the role of connections opened through a writer cluster endpoint as follows:

- If the topology writer is in the same region as the endpoint, the endpoint is active and the connection is always verified to be a writer.
- Otherwise, `verifyInactiveClusterWriterEndpointConnectionType` decides. `writer` (the default) verifies that the connection is a writer. `none` skips role verification.

An explicit `verifyOpenedConnectionType` always takes precedence over `verifyInactiveClusterWriterEndpointConnectionType`.

## Examples

Expand Down
53 changes: 53 additions & 0 deletions tests/unit/aurora_initial_connection_strategy_plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,59 @@ describe("Aurora initial connection strategy plugin", () => {
verify(mockPluginService.setRoutedHostInfo(identified)).once();
});

describe("writer cluster endpoint role verification", () => {
const writerInstance = hostInfoBuilder.withHost("writer-instance").withRole(HostRole.WRITER).build();

function setup(sameRegion: boolean) {
const client = instance(mock(PgClientWrapper));
when(mockRdsUtils.identifyRdsType(anything())).thenReturn(RdsUrlType.RDS_WRITER_CLUSTER);
when(mockRdsUtils.isRdsClusterDns(anything())).thenReturn(false);
when(mockRdsUtils.isRdsInstance(anything())).thenReturn(true);
when(mockRdsUtils.isSameRegion(anything(), anything())).thenReturn(sameRegion);
when(mockPluginService.getAllHosts()).thenReturn([writerInstance]);
when(mockPluginService.connect(anything(), anything(), anything())).thenResolve(client);
// The connection reports a reader, which would normally trigger a retry.
when(mockPluginService.getHostRole(client)).thenResolve(HostRole.READER);
return client;
}

it("skips verification for an inactive writer endpoint when verifyInactiveClusterWriterEndpointConnectionType is none", async () => {
WrapperProperties.VERIFY_INACTIVE_CLUSTER_WRITER_CONNECTION_ROLE.set(props, "none");
const client = setup(false);

expect(await plugin.connect(hostInfo, props, true, mockFunc)).toBe(client);
verify(mockPluginService.getHostRole(anything())).never();
verify(mockPluginService.setRoutedHostInfo(writerInstance)).once();
});

it("still verifies an active writer endpoint when verifyInactiveClusterWriterEndpointConnectionType is none", async () => {
WrapperProperties.VERIFY_INACTIVE_CLUSTER_WRITER_CONNECTION_ROLE.set(props, "none");
WrapperProperties.OPEN_CONNECTION_RETRY_TIMEOUT_MS.set(props, 1);
setup(true);

await plugin.connect(hostInfo, props, true, mockFunc);
verify(mockPluginService.getHostRole(anything())).atLeast(1);
});

it("verifies an inactive writer endpoint by default", async () => {
WrapperProperties.OPEN_CONNECTION_RETRY_TIMEOUT_MS.set(props, 1);
setup(false);

await plugin.connect(hostInfo, props, true, mockFunc);
verify(mockPluginService.getHostRole(anything())).atLeast(1);
});

it("lets an explicit verifyOpenedConnectionType override verifyInactiveClusterWriterEndpointConnectionType", async () => {
WrapperProperties.VERIFY_OPENED_CONNECTION_ROLE.set(props, "writer");
WrapperProperties.VERIFY_INACTIVE_CLUSTER_WRITER_CONNECTION_ROLE.set(props, "none");
WrapperProperties.OPEN_CONNECTION_RETRY_TIMEOUT_MS.set(props, 1);
setup(false);

await plugin.connect(hostInfo, props, true, mockFunc);
verify(mockPluginService.getHostRole(anything())).atLeast(1);
});
});

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