Skip to content

Commit ae8e1f3

Browse files
committed
refactor: use metrics middleware in request handler
Signed-off-by: Gustavo Inacio <[email protected]>
1 parent 2d5eb7b commit ae8e1f3

File tree

4 files changed

+59
-55
lines changed

4 files changed

+59
-55
lines changed

crates/service/src/error.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,6 @@ pub enum IndexerServiceError {
3030
#[error("Failed to sign attestation")]
3131
FailedToSignAttestation,
3232

33-
#[error("Could not decode signer: {0}")]
34-
CouldNotDecodeSigner(tap_core::Error),
35-
3633
#[error("There was an error while accessing escrow account: {0}")]
3734
EscrowAccount(#[from] EscrowAccountsError),
3835
}
@@ -54,7 +51,6 @@ impl IntoResponse for IndexerServiceError {
5451
ReceiptError(_)
5552
| InvalidRequest(_)
5653
| InvalidFreeQueryAuthToken
57-
| CouldNotDecodeSigner(_)
5854
| EscrowAccount(_)
5955
| ProcessingError(_) => StatusCode::BAD_REQUEST,
6056
};

crates/service/src/middleware.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,10 @@ mod inject_labels;
77
mod inject_receipt;
88
mod inject_sender;
99
mod metrics;
10+
11+
pub use inject_allocation::{allocation_middleware, AllocationState};
12+
pub use inject_deployment::deployment_middleware;
13+
pub use inject_labels::labels_middleware;
14+
pub use inject_receipt::receipt_middleware;
15+
pub use inject_sender::{sender_middleware, SenderState, Sender};
16+
pub use metrics::MetricsMiddlewareLayer;

crates/service/src/routes/request_handler.rs

Lines changed: 6 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,14 @@
33

44
use std::sync::Arc;
55

6-
use crate::{error::IndexerServiceError, metrics::{FAILED_RECEIPT, HANDLER_FAILURE, HANDLER_HISTOGRAM}, tap::AgoraQuery};
6+
use crate::{
7+
error::IndexerServiceError, metrics::FAILED_RECEIPT, middleware::Sender, tap::AgoraQuery,
8+
};
79
use axum::{
810
extract::{Path, State},
911
http::HeaderMap,
1012
response::IntoResponse,
13+
Extension,
1114
};
1215
use axum_extra::TypedHeader;
1316
use reqwest::StatusCode;
@@ -20,23 +23,8 @@ use crate::service::{AttestationOutput, IndexerServiceResponse, IndexerServiceSt
2023

2124
pub async fn request_handler(
2225
Path(manifest_id): Path<DeploymentId>,
23-
typed_header: TypedHeader<TapReceipt>,
24-
state: State<Arc<IndexerServiceState>>,
25-
headers: HeaderMap,
26-
body: String,
27-
) -> Result<impl IntoResponse, IndexerServiceError> {
28-
_request_handler(manifest_id, typed_header, state, headers, body)
29-
.await
30-
.inspect_err(|_| {
31-
HANDLER_FAILURE
32-
.with_label_values(&[&manifest_id.to_string()])
33-
.inc()
34-
})
35-
}
36-
37-
async fn _request_handler(
38-
manifest_id: DeploymentId,
3926
TypedHeader(receipt): TypedHeader<TapReceipt>,
27+
Extension(sender): Extension<Sender>,
4028
State(state): State<Arc<IndexerServiceState>>,
4129
headers: HeaderMap,
4230
req: String,
@@ -87,30 +75,6 @@ async fn _request_handler(
8775
variables,
8876
});
8977

90-
// recover the signer address
91-
// get escrow accounts from channel
92-
// return sender from signer
93-
//
94-
// TODO: We are currently doing this process twice.
95-
// One here and other on common/src/tap/checks/sender_balance_check.rs
96-
// We'll get back to normal once we have attachable context to `verify_and_store_receipt`
97-
let signer = receipt
98-
.recover_signer(&state.domain_separator)
99-
.map_err(IndexerServiceError::CouldNotDecodeSigner)?;
100-
let sender = state
101-
.escrow_accounts
102-
.borrow()
103-
.get_sender_for_signer(&signer)
104-
.map_err(IndexerServiceError::EscrowAccount)?;
105-
106-
let _metric = HANDLER_HISTOGRAM
107-
.with_label_values(&[
108-
&manifest_id.to_string(),
109-
&allocation_id.to_string(),
110-
&sender.to_string(),
111-
])
112-
.start_timer();
113-
11478
// Verify the receipt and store it in the database
11579
state
11680
.tap_manager
@@ -121,7 +85,7 @@ async fn _request_handler(
12185
.with_label_values(&[
12286
&manifest_id.to_string(),
12387
&allocation_id.to_string(),
124-
&sender.to_string(),
88+
&sender.0.to_string(),
12589
])
12690
.inc()
12791
})

crates/service/src/service/indexer_service.rs

Lines changed: 46 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,18 @@ use alloy::dyn_abi::Eip712Domain;
55
use anyhow;
66
use axum::extract::MatchedPath;
77
use axum::extract::Request as ExtractRequest;
8-
use axum::http::{Method, Request};
98
use axum::{
9+
http::{Method, Request},
10+
middleware::{from_fn, from_fn_with_state},
1011
response::IntoResponse,
1112
routing::{get, post},
12-
Json, Router,
13+
serve, Json, Router, ServiceExt,
1314
};
14-
use axum::{serve, ServiceExt};
1515
use build_info::BuildInfo;
1616
use indexer_attestation::AttestationSigner;
1717
use indexer_monitor::{
18-
attestation_signers, dispute_manager, escrow_accounts, indexer_allocations, DeploymentDetails,
19-
EscrowAccounts, SubgraphClient,
18+
attestation_signers, deployment_to_allocation, dispute_manager, escrow_accounts,
19+
indexer_allocations, DeploymentDetails, EscrowAccounts, SubgraphClient,
2020
};
2121
use prometheus::TextEncoder;
2222
use reqwest::StatusCode;
@@ -30,12 +30,23 @@ use thegraph_core::{Address, Attestation};
3030
use tokio::net::TcpListener;
3131
use tokio::signal;
3232
use tokio::sync::watch::Receiver;
33+
use tower::ServiceBuilder;
3334
use tower_governor::{governor::GovernorConfigBuilder, GovernorLayer};
3435
use tower_http::validate_request::ValidateRequestHeaderLayer;
3536
use tower_http::{cors, cors::CorsLayer, normalize_path::NormalizePath, trace::TraceLayer};
3637
use tracing::warn;
3738
use tracing::{error, info, info_span};
3839

40+
use crate::metrics::HANDLER_FAILURE;
41+
use crate::metrics::HANDLER_HISTOGRAM;
42+
use crate::middleware::allocation_middleware;
43+
use crate::middleware::deployment_middleware;
44+
use crate::middleware::labels_middleware;
45+
use crate::middleware::receipt_middleware;
46+
use crate::middleware::sender_middleware;
47+
use crate::middleware::AllocationState;
48+
use crate::middleware::MetricsMiddlewareLayer;
49+
use crate::middleware::SenderState;
3950
use crate::routes::health;
4051
use crate::routes::request_handler;
4152
use crate::routes::static_subgraph_request_handler;
@@ -257,7 +268,7 @@ pub async fn run(options: IndexerServiceOptions) -> Result<(), anyhow::Error> {
257268

258269
let checks = IndexerTapContext::get_checks(
259270
database,
260-
allocations,
271+
allocations.clone(),
261272
escrow_accounts.clone(),
262273
domain_separator.clone(),
263274
timestamp_error_tolerance,
@@ -276,8 +287,8 @@ pub async fn run(options: IndexerServiceOptions) -> Result<(), anyhow::Error> {
276287
attestation_signers,
277288
tap_manager,
278289
service_impl: options.service_impl,
279-
escrow_accounts,
280-
domain_separator,
290+
escrow_accounts: escrow_accounts.clone(),
291+
domain_separator: domain_separator.clone(),
281292
});
282293

283294
// Rate limits by allowing bursts of 10 requests and requiring 100ms of
@@ -362,13 +373,39 @@ pub async fn run(options: IndexerServiceOptions) -> Result<(), anyhow::Error> {
362373

363374
misc_routes = misc_routes.with_state(state.clone());
364375

376+
let deployment_to_allocation = deployment_to_allocation(allocations);
377+
let allocation_state = AllocationState {
378+
deployment_to_allocation,
379+
};
380+
let sender_state = SenderState {
381+
escrow_accounts,
382+
domain_separator,
383+
};
384+
385+
let service_builder = ServiceBuilder::new()
386+
// inject deployment id
387+
.layer(from_fn(deployment_middleware))
388+
// inject receipt
389+
.layer(from_fn(receipt_middleware))
390+
// inject deployment id
391+
.layer(from_fn_with_state(allocation_state, allocation_middleware))
392+
// inject sender
393+
.layer(from_fn_with_state(sender_state, sender_middleware))
394+
// inject metrics labels
395+
.layer(from_fn(labels_middleware))
396+
// metrics for histogram and failure
397+
.layer(MetricsMiddlewareLayer::new(
398+
HANDLER_HISTOGRAM.clone(),
399+
HANDLER_FAILURE.clone(),
400+
));
401+
365402
let data_routes = Router::new()
366403
.route(
367404
PathBuf::from(&options.config.service.url_prefix)
368405
.join(format!("{}/id/:id", options.url_namespace))
369406
.to_str()
370407
.expect("Failed to set up `/{url_namespace}/id/:id` route"),
371-
post(request_handler),
408+
post(request_handler).route_layer(service_builder),
372409
)
373410
.with_state(state.clone());
374411

0 commit comments

Comments
 (0)