Skip to content

Commit

Permalink
feat(middleware): code cleanning.
Browse files Browse the repository at this point in the history
  • Loading branch information
andysim3d committed Oct 7, 2024
1 parent adbc345 commit b762d96
Show file tree
Hide file tree
Showing 8 changed files with 28 additions and 34 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ anyhow = "1.0.89"
async-trait = "0.1.83"
auto_impl = "1.2.0"
aws-config = { version = "1.5.6", default-features = false }
cargo-husky = { version = "1", default-features = false, features = ["user-hooks"] }
futures = "0.3.30"
futures-util = "0.3.30"
itertools = "0.13.0"
Expand All @@ -66,15 +65,13 @@ serde = "1.0.210"
serde_json = "1.0.128"
rand = "0.8.5"
reqwest = { version = "0.12.8", default-features = false, features = ["rustls-tls"] }
rustls = "0.23.13"
thiserror = "1.0.64"
tokio = { version = "1.39.3", default-features = false, features = ["rt", "sync", "time"]}
tokio-util = "0.7.12"
tonic = "0.12.3"
tonic-build = "0.12.3"
tonic-health = "0.12.3"
tonic-reflection = "0.12.3"
tonic-types = "0.12.3"
tower = { version = "0.4.13", features = ["timeout"] }
tracing = "0.1.40"
strum = { version = "0.26.3", features = ["derive"] }
Expand Down
1 change: 0 additions & 1 deletion crates/provider/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ futures-util.workspace = true
tower.workspace = true
tracing.workspace = true
url.workspace = true
pin-project.workspace = true

mockall = {workspace = true, optional = true }

Expand Down
12 changes: 8 additions & 4 deletions crates/provider/src/alloy/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ impl<S> Layer<S> for AlloyMetricLayer
where
S: Service<RequestPacket, Response = ResponsePacket, Error = TransportError> + Sync,
{
// type Service = S;
type Service = AlloyMetricMiddleware<S>;

fn layer(&self, service: S) -> Self::Service {
Expand Down Expand Up @@ -81,14 +80,14 @@ where
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx)
}

fn call(&mut self, request: RequestPacket) -> Self::Future {
let method_name = get_method_name(&request);
let mut method_logger = MethodSessionLogger::new(
let method_logger = MethodSessionLogger::start(
"alloy_provider_client".to_string(),
method_name,
"rpc".to_string(),
);
method_logger.start();
let mut svc = self.service.clone();
async move {
let response = svc.call(request).await;
Expand Down Expand Up @@ -155,7 +154,12 @@ fn get_http_status_from_code(code: u16) -> HttpCode {

fn get_rpc_status_code(response_packet: &ResponsePacket) -> RpcCode {
let response: &alloy_json_rpc::Response = match response_packet {
ResponsePacket::Batch(resps) => &resps[0],
ResponsePacket::Batch(resps) => {
if resps.is_empty() {
return RpcCode::Success;
}
&resps[0]
}
ResponsePacket::Single(resp) => resp,
};
let response_code: i64 = match &response.payload {
Expand Down
4 changes: 2 additions & 2 deletions crates/provider/src/alloy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,14 @@ pub fn new_alloy_evm_provider(rpc_url: &str) -> anyhow::Result<impl EvmProvider
pub fn new_alloy_provider(
rpc_url: &str,
) -> anyhow::Result<
impl AlloyProvider<AlloyMetricMiddleware<RetryBackoffService<Http<Client>>>> + Clone,
impl AlloyProvider<RetryBackoffService<AlloyMetricMiddleware<Http<Client>>>> + Clone,
> {
let url = Url::parse(rpc_url).context("invalid rpc url")?;
let metric_layer = AlloyMetricLayer::default();
let retry_layer = alloy_transport::layers::RetryBackoffLayer::new(10, 500, 0);
let client = ClientBuilder::default()
.layer(metric_layer)
.layer(retry_layer)
.layer(metric_layer)
.http(url);
let provider = ProviderBuilder::new().on_client(client);
Ok(provider)
Expand Down
3 changes: 1 addition & 2 deletions crates/rpc/src/rpc_metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,12 @@ where
type Future = BoxFuture<'a, MethodResponse>;

fn call(&self, req: Request<'a>) -> Self::Future {
let mut method_logger = MethodSessionLogger::new(
let method_logger = MethodSessionLogger::start(
self.service_name.clone(),
req.method_name().to_string(),
"rpc".to_string(),
);

method_logger.start();
let svc = self.service.clone();

async move {
Expand Down
22 changes: 13 additions & 9 deletions crates/task/src/grpc/grpc_metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ use std::{

use pin_project::pin_project;
use rundler_types::task::{
metric_recorder::MethodSessionLogger, status_code::get_http_status_from_code,
metric_recorder::MethodSessionLogger,
status_code::{get_http_status_from_code, HttpCode},
};
use tonic::codegen::http;
use tower::{Layer, Service};
Expand Down Expand Up @@ -78,12 +79,11 @@ where
fn call(&mut self, request: http::Request<Body>) -> Self::Future {
let uri = request.uri().clone();
let method_name = uri.path().split('/').last().unwrap_or("unknown");
let mut method_logger = MethodSessionLogger::new(
let method_logger = MethodSessionLogger::start(
self.scope.clone(),
method_name.to_string(),
"grpc".to_string(),
);
method_logger.start();
ResponseFuture {
response_future: self.inner.call(request),
method_logger,
Expand Down Expand Up @@ -112,13 +112,17 @@ where
let this = self.project();
let res = this.response_future.poll(cx);
match &res {
Poll::Ready(response) => {
Poll::Ready(result) => {
this.method_logger.done();

let http_status = response.as_ref().ok().map(|response| response.status());
if let Some(status_code) = http_status {
this.method_logger
.record_http(get_http_status_from_code(status_code.as_u16()));
match result {
Ok(response) => {
let http_status = response.status();
this.method_logger
.record_http(get_http_status_from_code(http_status.as_u16()));
}
_ => {
this.method_logger.record_http(HttpCode::FiveHundreds);
}
}
}
Poll::Pending => {}
Expand Down
16 changes: 4 additions & 12 deletions crates/types/src/task/metric_recorder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,10 @@ impl MethodSessionLogger {
}

/// start the session. time will be initialized.
pub fn start(&mut self) {
self.start_time = Instant::now();
MethodMetrics::increment_num_requests(
&self.method_name,
&self.service_name,
&self.protocol,
);
MethodMetrics::increment_open_requests(
&self.method_name,
&self.service_name,
&self.protocol,
);
pub fn start(service_name: String, method_name: String, protocol: String) -> Self {
MethodMetrics::increment_num_requests(&method_name, &service_name, &protocol);
MethodMetrics::increment_open_requests(&method_name, &service_name, &protocol);
Self::new(service_name, method_name, protocol)
}

/// record a rpc status code.
Expand Down

0 comments on commit b762d96

Please sign in to comment.