Skip to content

Commit

Permalink
feat: fastest response strategy plugin (#345)
Browse files Browse the repository at this point in the history
  • Loading branch information
joyc-bq authored Dec 10, 2024
1 parent 979f54e commit 95f1b6f
Show file tree
Hide file tree
Showing 13 changed files with 442 additions and 13 deletions.
2 changes: 2 additions & 0 deletions common/lib/connection_plugin_chain_builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import { ConnectionProviderManager } from "./connection_provider_manager";
import { DeveloperConnectionPluginFactory } from "./plugins/dev/developer_connection_plugin_factory";
import { ConnectionPluginFactory } from "./plugin_factory";
import { LimitlessConnectionPluginFactory } from "./plugins/limitless/limitless_connection_plugin_factory";
import { FastestResponseStrategyPluginFactory } from "./plugins/strategy/fastest_response/fastest_respose_strategy_plugin_factory";

/*
Type alias used for plugin factory sorting. It holds a reference to a plugin
Expand All @@ -57,6 +58,7 @@ export class ConnectionPluginChainBuilder {
["readWriteSplitting", { factory: ReadWriteSplittingPluginFactory, weight: 600 }],
["failover", { factory: FailoverPluginFactory, weight: 700 }],
["efm", { factory: HostMonitoringPluginFactory, weight: 800 }],
["fastestResponseStrategy", { factory: FastestResponseStrategyPluginFactory, weight: 900 }],
["limitless", { factory: LimitlessConnectionPluginFactory, weight: 950 }],
["iam", { factory: IamAuthenticationPluginFactory, weight: 1000 }],
["secretsManager", { factory: AwsSecretsManagerPluginFactory, weight: 1100 }],
Expand Down
6 changes: 3 additions & 3 deletions common/lib/database_dialect/limitless_database_dialect.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/*
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.
Expand Down
6 changes: 3 additions & 3 deletions common/lib/highest_weight_host_selector.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/*
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.
Expand Down
1 change: 0 additions & 1 deletion common/lib/plugins/efm/host_monitoring_plugin_factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import { ConnectionPluginFactory } from "../../plugin_factory";
import { PluginService } from "../../plugin_service";
import { ConnectionPlugin } from "../../connection_plugin";
import { RdsUtils } from "../../utils/rds_utils";
import { logger } from "../../../logutils";
import { AwsWrapperError } from "../../utils/errors";
import { Messages } from "../../utils/messages";

Expand Down
4 changes: 2 additions & 2 deletions common/lib/plugins/limitless/limitless_router_monitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export class LimitlessRouterMonitor {
logger.debug(Messages.get("LimitlessRouterMonitor.running", this.hostInfo.host));

while (!this.stopped) {
const telemetryContext = this.telemetryFactory.openTelemetryContext("limitless router monitor thread", TelemetryTraceLevel.TOP_LEVEL);
const telemetryContext = this.telemetryFactory.openTelemetryContext("limitless router monitor task", TelemetryTraceLevel.TOP_LEVEL);
telemetryContext.setAttribute("url", this.hostInfo.host);
await telemetryContext.start(async () => {
try {
Expand Down Expand Up @@ -108,7 +108,7 @@ export class LimitlessRouterMonitor {
}
await sleep(this.intervalMillis);
} catch (e: any) {
logger.debug(Messages.get("LimitlessRouterMonitor.exceptionDuringMonitoringStop", this.hostInfo.host, e.message));
logger.debug(Messages.get("LimitlessRouterMonitor.errorDuringMonitoringStop", this.hostInfo.host, e.message));
}
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/*
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 { CacheMap } from "../../../utils/cache_map";
import { ClientWrapper } from "../../../client_wrapper";
import { HostRole } from "../../../host_role";
import { AbstractConnectionPlugin } from "../../../abstract_connection_plugin";
import { HostResponseTimeService, HostResponseTimeServiceImpl } from "./host_response_time_service";
import { PluginService } from "../../../plugin_service";
import { WrapperProperties } from "../../../wrapper_property";
import { HostInfo } from "../../../host_info";
import { HostChangeOptions } from "../../../host_change_options";
import { RandomHostSelector } from "../../../random_host_selector";
import { Messages } from "../../../utils/messages";
import { equalsIgnoreCase, logAndThrowError } from "../../../utils/utils";

export class FastestResponseStrategyPlugin extends AbstractConnectionPlugin {
static readonly FASTEST_RESPONSE_STRATEGY_NAME: string = "fastestResponse";
private static readonly subscribedMethods = new Set<string>([
"connect",
"forceConnect",
"notifyHostListChanged",
"acceptsStrategy",
"getHostInfoByStrategy"
]);
protected static readonly cachedFastestResponseHostByRole: CacheMap<string, HostInfo> = new CacheMap<string, HostInfo>();
protected cacheExpirationNanos: bigint;
protected hostResponseTimeService: HostResponseTimeService;
protected readonly properties: Map<string, any>;
private pluginService: PluginService;
private randomHostSelector: RandomHostSelector = new RandomHostSelector();

constructor(pluginService: PluginService, properties: Map<string, any>, hostResponseTimeService?: HostResponseTimeService) {
super();
this.pluginService = pluginService;
this.properties = properties;
this.hostResponseTimeService =
hostResponseTimeService ??
new HostResponseTimeServiceImpl(pluginService, properties, WrapperProperties.RESPONSE_MEASUREMENT_INTERVAL_MILLIS.get(this.properties));
this.cacheExpirationNanos = BigInt(WrapperProperties.RESPONSE_MEASUREMENT_INTERVAL_MILLIS.get(this.properties) * 1_000_000);
}

public getSubscribedMethods(): Set<string> {
return FastestResponseStrategyPlugin.subscribedMethods;
}

async connect(
hostInfo: HostInfo,
props: Map<string, any>,
isInitialConnection: boolean,
connectFunc: () => Promise<ClientWrapper>
): Promise<ClientWrapper> {
const result = await connectFunc();
if (isInitialConnection) {
this.hostResponseTimeService.setHosts(this.pluginService.getHosts());
}
return result;
}

async forceConnect(
hostInfo: HostInfo,
props: Map<string, any>,
isInitialConnection: boolean,
forceConnectFunc: () => Promise<ClientWrapper>
): Promise<ClientWrapper> {
const result = await forceConnectFunc();
if (isInitialConnection) {
this.hostResponseTimeService.setHosts(this.pluginService.getHosts());
}
return result;
}

acceptsStrategy(role: HostRole, strategy: string) {
return equalsIgnoreCase(FastestResponseStrategyPlugin.FASTEST_RESPONSE_STRATEGY_NAME, strategy.toLowerCase());
}

getHostInfoByStrategy(role: HostRole, strategy: string, hosts?: HostInfo[]): HostInfo | undefined {
if (!this.acceptsStrategy(role, strategy)) {
logAndThrowError(Messages.get("FastestResponseStrategyPlugin.unsupportedHostSelectorStrategy", strategy));
}
// The cache holds a host with the fastest response time.
// If the cache doesn't have a host for a role, it's necessary to find the fastest host in the topology.
const fastestResponseHost: HostInfo = FastestResponseStrategyPlugin.cachedFastestResponseHostByRole.get(role);
if (fastestResponseHost) {
// Found the fastest host. Find the host in the latest topology.
const foundHost = this.pluginService.getHosts().find((host) => host === fastestResponseHost);
if (foundHost) {
// Found a host in the topology.
return foundHost;
}
}
// Cached result isn't available. Need to find the fastest response time host.
const calculatedFastestResponseHost: ResponseTimeTuple[] = this.pluginService
.getHosts()
.filter((host) => role === host.role)
.map((host) => new ResponseTimeTuple(host, this.hostResponseTimeService.getResponseTime(host)))
.sort((a, b) => {
return a.responseTime - b.responseTime;
});
const calculatedHost = calculatedFastestResponseHost.length === 0 ? null : calculatedFastestResponseHost[0];

if (!calculatedHost) {
// Unable to identify the fastest response host.
// As a last resort, let's use a random host selector.
return this.randomHostSelector.getHost(hosts, role, this.properties);
}
FastestResponseStrategyPlugin.cachedFastestResponseHostByRole.put(role, calculatedHost.hostInfo, Number(this.cacheExpirationNanos));
return calculatedHost.hostInfo;
}

async notifyHostListChanged(changes: Map<string, Set<HostChangeOptions>>): Promise<void> {
this.hostResponseTimeService.setHosts(this.pluginService.getHosts());
}
}

class ResponseTimeTuple {
readonly hostInfo: HostInfo;
readonly responseTime: number;

constructor(hostInfo: HostInfo, responseTime: number) {
this.hostInfo = hostInfo;
this.responseTime = responseTime;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
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 { ConnectionPluginFactory } from "../../../plugin_factory";
import { PluginService } from "../../../plugin_service";
import { ConnectionPlugin } from "../../../connection_plugin";
import { AwsWrapperError } from "../../../utils/errors";
import { Messages } from "../../../utils/messages";

export class FastestResponseStrategyPluginFactory extends ConnectionPluginFactory {
private static fastestResponseStrategyPlugin: any;

async getInstance(pluginService: PluginService, properties: Map<string, any>): Promise<ConnectionPlugin> {
try {
if (!FastestResponseStrategyPluginFactory.fastestResponseStrategyPlugin) {
FastestResponseStrategyPluginFactory.fastestResponseStrategyPlugin = await import("./fastest_response_strategy_plugin");
}
return new FastestResponseStrategyPluginFactory.fastestResponseStrategyPlugin.FastestResponseStrategyPlugin(pluginService, properties);
} catch (error: any) {
throw new AwsWrapperError(
Messages.get("ConnectionPluginChainBuilder.errorImportingPlugin", error.message, "FastestResponseStrategyPluginFactory")
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/*
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 { HostInfo } from "../../../host_info";
import { PluginService } from "../../../plugin_service";
import { TelemetryFactory } from "../../../utils/telemetry/telemetry_factory";
import { sleep } from "../../../utils/utils";
import { logger } from "../../../../logutils";
import { Messages } from "../../../utils/messages";
import { TelemetryTraceLevel } from "../../../utils/telemetry/telemetry_trace_level";
import { ClientWrapper } from "../../../client_wrapper";
import { TelemetryContext } from "../../../utils/telemetry/telemetry_context";

export class HostResponseTimeMonitor {
static readonly MONITORING_PROPERTY_PREFIX = "frt_";
static readonly NUM_OF_MEASURES = 5;
private readonly intervalMs: number;
private readonly hostInfo: HostInfo;
private stopped = false;
private responseTimeMs = Number.MAX_SAFE_INTEGER;
private checkTimestamp = Date.now();

private readonly properties: Map<string, any>;
private pluginService: PluginService;
private telemetryFactory: TelemetryFactory;
protected monitoringClient: ClientWrapper | null = null;

constructor(pluginService: PluginService, hostInfo: HostInfo, properties: Map<string, any>, intervalMs: number) {
this.pluginService = pluginService;
this.hostInfo = hostInfo;
this.properties = properties;
this.intervalMs = intervalMs;
this.telemetryFactory = this.pluginService.getTelemetryFactory();

const hostId: string = this.hostInfo.hostId ?? this.getHostInfo().host;
/**
* Report current response time (in milliseconds) to telemetry engine.
* Report -1 if response time couldn't be measured.
*/
this.telemetryFactory.createGauge(`frt.response.time.${hostId}`, () => this.getResponseTime() == Number.MAX_SAFE_INTEGER);
this.run();
}

getResponseTime() {
return this.responseTimeMs;
}

getCheckTimeStamp() {
return this.checkTimestamp;
}

getHostInfo() {
return this.hostInfo;
}

async close(): Promise<void> {
this.stopped = true;
await sleep(500);
logger.debug(Messages.get("HostResponseTimeMonitor.stopped", this.hostInfo.host));
}

async run(): Promise<void> {
const telemetryContext: TelemetryContext = this.telemetryFactory.openTelemetryContext("host response time task", TelemetryTraceLevel.TOP_LEVEL);
telemetryContext.setAttribute("url", this.hostInfo.host);
while (!this.stopped) {
await telemetryContext.start(async () => {
try {
await this.openConnection();
if (this.monitoringClient) {
let responseTimeSum = 0;
let count = 0;
for (let i = 0; i < HostResponseTimeMonitor.NUM_OF_MEASURES; i++) {
if (this.stopped) {
break;
}
const startTime = Date.now();
if (await this.pluginService.isClientValid(this.monitoringClient)) {
const responseTime = Date.now() - startTime;
responseTimeSum += responseTime;
count++;
}
}
if (count > 0) {
this.responseTimeMs = responseTimeSum / count;
} else {
this.responseTimeMs = Number.MAX_SAFE_INTEGER;
}
this.checkTimestamp = Date.now();
logger.debug(Messages.get("HostResponseTimeMonitor.responseTime", this.hostInfo.host, this.responseTimeMs.toString()));
}
await sleep(this.intervalMs);
} catch (error) {
logger.debug(Messages.get("HostResponseTimeMonitor.interruptedErrorDuringMonitoring", this.hostInfo.host, error.message));
} finally {
this.stopped = true;
if (this.monitoringClient) {
await this.monitoringClient.abort();
}
this.monitoringClient = null;
}
});
}
}

async openConnection(): Promise<void> {
try {
if (this.monitoringClient) {
const clientIsValid = await this.pluginService.isClientValid(this.monitoringClient);
if (clientIsValid) {
return;
}
}
const monitoringConnProperties: Map<string, any> = new Map(this.properties);
for (const key of monitoringConnProperties.keys()) {
if (!key.startsWith(HostResponseTimeMonitor.MONITORING_PROPERTY_PREFIX)) {
continue;
}
monitoringConnProperties.set(key.substring(HostResponseTimeMonitor.MONITORING_PROPERTY_PREFIX.length), this.properties.get(key));
monitoringConnProperties.delete(key);
}
logger.debug(Messages.get("HostResponseTimeMonitor.openingConnection", this.hostInfo.url));
this.monitoringClient = await this.pluginService.forceConnect(this.hostInfo, monitoringConnProperties);
logger.debug(Messages.get("HostResponseTimeMonitor.openedConnection", this.hostInfo.url));
} catch (e) {
if (this.monitoringClient) {
await this.monitoringClient.abort();
}
this.monitoringClient = null;
}
}
}
Loading

0 comments on commit 95f1b6f

Please sign in to comment.