-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: fastest response strategy plugin (#345)
- Loading branch information
Showing
13 changed files
with
442 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
137 changes: 137 additions & 0 deletions
137
common/lib/plugins/strategy/fastest_response/fastest_response_strategy_plugin.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
38 changes: 38 additions & 0 deletions
38
common/lib/plugins/strategy/fastest_response/fastest_respose_strategy_plugin_factory.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | ||
); | ||
} | ||
} | ||
} |
144 changes: 144 additions & 0 deletions
144
common/lib/plugins/strategy/fastest_response/host_response_time_monitor.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} |
Oops, something went wrong.