-
Notifications
You must be signed in to change notification settings - Fork 39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(middleware): create a generic middleware to collect method metrics. #804
Draft
andysim3d
wants to merge
3
commits into
feat/v0.4
Choose a base branch
from
andy/metric-middle-ware
base: feat/v0.4
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
use std::{ | ||
future::Future, | ||
pin::Pin, | ||
task::{Context, Poll}, | ||
time::{Duration, Instant}, | ||
}; | ||
|
||
use futures::{future::BoxFuture, FutureExt}; | ||
use jsonrpsee::server::HttpBody; | ||
use pin_project::pin_project; | ||
use tower::{Layer, Service}; | ||
use tonic::codegen::http; | ||
|
||
#![allow(dead_code)] | ||
|
||
pub trait RequestInfo { | ||
pub fn get_method_name(&self) -> String; | ||
} | ||
|
||
pub struct MethodExtractor<Request> | ||
{} | ||
|
||
impl<Request> MethodExtractor<Request> where Request: RequestInfo | ||
{ | ||
pub fn new () -> Self { | ||
Self { } | ||
} | ||
pub fn extract_method_name(&self, request: Request) -> String{ | ||
request.get_method_name() | ||
} | ||
} | ||
|
||
impl<Body> RequestInfo for http::Request<Body>{ | ||
fn get_method_name(&self) -> String { | ||
let method_name = self.uri().path().split('/').last().unwrap_or("unknown"); | ||
method_name.to_string() | ||
} | ||
} | ||
|
||
impl<'a> RequestInfo for jsonrpsee::types::Request<'a>{ | ||
fn get_method_name<'a>(&self) -> String { | ||
self. | ||
request.method_name().to_string() | ||
} | ||
} | ||
|
||
#[derive(Debug, Clone)] | ||
pub struct MetricsLayer { | ||
service_name: String, | ||
} | ||
|
||
impl MetricsLayer { | ||
pub fn new(service_name: String, protocal: String) -> Self { | ||
MetricsLayer { | ||
service_name, | ||
} | ||
} | ||
} | ||
|
||
impl<S> Layer<S> for MetricsLayer { | ||
type Service = MetricsMiddleware<S>; | ||
fn layer(&self, service: S) -> Self::Service { | ||
MetricsMiddleware::new(service, self.service_name.clone()) | ||
} | ||
} | ||
|
||
|
||
#[derive(Clone, Debug)] | ||
pub struct MetricsMiddleware<S, Request> { | ||
inner: S, | ||
service_name: String, | ||
service_metrics: ServiceMetrics, | ||
method_extractor: MethodExtractor<Request> | ||
} | ||
|
||
impl<S, Request> MetricsMiddleware<S, Request> | ||
where Request: RequestInfo | ||
{ | ||
pub fn new(inner: S, service_name: String) -> Self { | ||
Self { | ||
inner: inner, | ||
service_name: service_name, | ||
service_metrics: ServiceMetrics::new(service_name.as_str()), | ||
method_extractor: MethodExtractor<Request>::new(), | ||
} | ||
} | ||
} | ||
|
||
impl<S, Request> Service<Request> for MetricsMiddleware<S> | ||
where | ||
S: Service<Request>, | ||
Request: RequestInfo, | ||
{ | ||
type Response = S::Response; | ||
type Error = S::Error; | ||
type Future = BoxFuture<Response>; | ||
|
||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { | ||
self.inner.poll_ready(cx) | ||
} | ||
|
||
fn call(&mut self, request: Request) -> Self::Future { | ||
let method_name = self.method_extractor.extract_method_name(request); | ||
MethodMetrics::increment_num_requests(self.service_name.clone(), method_name.to_string()); | ||
MethodMetrics::increment_open_requests(self.service_name.clone(), method_name); | ||
|
||
let start = Instant::now(); | ||
let svc = self.inner.clone(); | ||
let service_name = self.service_name.clone(); | ||
async move{ | ||
let rsp: Result<Response, Error> = svc.call(request).await; | ||
MethodMetrics::record_request_latency(method_name, service_name, start.elapsed()); | ||
MethodMetrics::decrement_open_requests(method_name, service_name); | ||
if rsp.is_err(){ | ||
MethodMetrics::increment_error_count(method_name, service_name); | ||
} | ||
rsp | ||
} | ||
.boxed() | ||
} | ||
} | ||
|
||
|
||
#[derive(Clone)] | ||
// service metrics tracks all method metrics of specific service. | ||
struct ServiceMetrics { | ||
service_name: &str, | ||
} | ||
|
||
impl ServiceMetrics { | ||
fn new(service_name: &str) -> Self { | ||
Self { | ||
service_name: service_name | ||
} | ||
} | ||
} | ||
|
||
#[derive(Clone)] | ||
struct MethodMetrics {} | ||
|
||
impl MethodMetrics { | ||
fn increment_num_requests(method_name: String, service_name: String) { | ||
metrics::counter!("num_requests", "method_name" => method_name.to_string(), "service_name" => service_name.to_string()).increment(1) | ||
} | ||
|
||
fn increment_open_requests(method_name: String, service_name: String) { | ||
metrics::gauge!("open_requests", "method_name" => method_name.to_string(), "service_name" => service_name.to_string()).increment(1_f64) | ||
} | ||
|
||
fn decrement_open_requests( method_name: String, service_name: String) { | ||
metrics::gauge!("open_requests", "method_name" => method_name.to_string(), "service_name" => service_name.to_string()).decrement(1_f64) | ||
} | ||
|
||
fn increment_error_count( method_name: String, service_name: String) { | ||
metrics::counter!("open_requests", "method_name" => method_name.to_string(), "service_name" => service_name.to_string()).increment(1) | ||
} | ||
|
||
fn record_request_latency( method_name: String, service_name: String, latency: Duration) { | ||
metrics::histogram!("request_latency", "method_name" => method_name.to_string(), "service_name" => service_name.to_string()).record(latency) | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
add a method_extractor here, and make that generic.