Skip to content

Commit 618be8a

Browse files
committed
refactor: move extra routes to routes mod
Signed-off-by: Gustavo Inacio <[email protected]>
1 parent 959b2c2 commit 618be8a

File tree

7 files changed

+101
-76
lines changed

7 files changed

+101
-76
lines changed

crates/service/src/service/health.rs renamed to crates/service/src/routes/health.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
// SPDX-License-Identifier: Apache-2.0
33

44
use axum::{
5-
extract::Path,
5+
extract::{Path, State},
66
response::{IntoResponse, Response as AxumResponse},
7-
Extension, Json,
7+
Json,
88
};
99
use graphql_client::GraphQLQuery;
1010
use indexer_config::GraphNodeConfig;
@@ -43,7 +43,7 @@ impl IntoResponse for CheckHealthError {
4343

4444
pub async fn health(
4545
Path(deployment_id): Path<String>,
46-
Extension(graph_node): Extension<GraphNodeConfig>,
46+
State(graph_node): State<GraphNodeConfig>,
4747
) -> Result<impl IntoResponse, CheckHealthError> {
4848
let req_body = HealthQuery::build_query(health_query::Variables {
4949
ids: vec![deployment_id],

crates/service/src/routes/mod.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,12 @@
33

44
pub mod cost;
55
pub mod dips;
6+
mod health;
7+
mod request_handler;
8+
mod static_subgraph;
69
mod status;
710

11+
pub use health::health;
12+
pub use request_handler::request_handler;
13+
pub use static_subgraph::static_subgraph_request_handler;
814
pub use status::status;

crates/service/src/service/request_handler.rs renamed to crates/service/src/routes/request_handler.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,9 @@ use tap_core::receipt::Context;
1818
use thegraph_core::DeploymentId;
1919
use tracing::trace;
2020

21-
use super::{
22-
indexer_service::{AttestationOutput, IndexerServiceError, IndexerServiceState},
23-
tap_receipt_header::TapReceipt,
24-
IndexerServiceImpl, IndexerServiceResponse,
21+
use crate::service::{
22+
AttestationOutput, IndexerServiceError, IndexerServiceImpl, IndexerServiceResponse,
23+
IndexerServiceState, TapReceipt,
2524
};
2625

2726
lazy_static! {
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// Copyright 2023-, Edge & Node, GraphOps, and Semiotic Labs.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
use axum::{body::Bytes, http::HeaderMap, response::IntoResponse, Extension, Json};
5+
use reqwest::StatusCode;
6+
use serde_json::json;
7+
use tracing::warn;
8+
9+
use indexer_common::SubgraphClient;
10+
11+
#[autometrics::autometrics]
12+
pub async fn static_subgraph_request_handler(
13+
Extension(subgraph_client): Extension<&'static SubgraphClient>,
14+
Extension(required_auth_token): Extension<Option<String>>,
15+
headers: HeaderMap,
16+
body: Bytes,
17+
) -> Result<impl IntoResponse, StaticSubgraphError> {
18+
if let Some(required_auth_token) = required_auth_token {
19+
let authorization = headers
20+
.get("authorization")
21+
.map(|value| value.to_str())
22+
.transpose()
23+
.map_err(|_| StaticSubgraphError::Unauthorized)?
24+
.ok_or_else(|| StaticSubgraphError::Unauthorized)?
25+
.trim_start_matches("Bearer ");
26+
27+
if authorization != required_auth_token {
28+
return Err(StaticSubgraphError::Unauthorized);
29+
}
30+
}
31+
32+
let response = subgraph_client.query_raw(body).await?;
33+
34+
Ok((
35+
response.status(),
36+
response.headers().to_owned(),
37+
response.text().await.inspect_err(|e| {
38+
warn!("Failed to read response body: {}", e);
39+
})?,
40+
))
41+
}
42+
43+
#[derive(Debug, thiserror::Error)]
44+
pub enum StaticSubgraphError {
45+
#[error("No valid receipt or free query auth token provided")]
46+
Unauthorized,
47+
48+
#[error("Failed to query subgraph: {0}")]
49+
FailedToQuery(#[from] anyhow::Error),
50+
51+
#[error("Failed to parse subgraph response: {0}")]
52+
FailedToParse(#[from] reqwest::Error),
53+
}
54+
55+
impl IntoResponse for StaticSubgraphError {
56+
fn into_response(self) -> axum::response::Response {
57+
let status = match self {
58+
StaticSubgraphError::Unauthorized => StatusCode::UNAUTHORIZED,
59+
StaticSubgraphError::FailedToQuery(_) | StaticSubgraphError::FailedToParse(_) => {
60+
StatusCode::INTERNAL_SERVER_ERROR
61+
}
62+
};
63+
64+
tracing::error!(%self, "An IndexerServiceError occoured.");
65+
(
66+
status,
67+
Json(json! {{
68+
"message": self.to_string(),
69+
}}),
70+
)
71+
.into_response()
72+
}
73+
}

crates/service/src/service.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,20 +28,20 @@ use crate::{
2828
dips::{AgreementStore, InMemoryAgreementStore},
2929
},
3030
routes::dips::Price,
31-
service::indexer_service::{
32-
AttestationOutput, IndexerService, IndexerServiceImpl, IndexerServiceOptions,
33-
IndexerServiceRelease, IndexerServiceResponse,
34-
},
31+
service::indexer_service::{IndexerService, IndexerServiceOptions, IndexerServiceRelease},
3532
};
3633
use clap::Parser;
3734
use tracing::error;
3835

39-
mod health;
4036
mod indexer_service;
41-
mod request_handler;
42-
mod static_subgraph;
4337
mod tap_receipt_header;
4438

39+
pub use indexer_service::{
40+
AttestationOutput, IndexerServiceError, IndexerServiceImpl, IndexerServiceResponse,
41+
IndexerServiceState,
42+
};
43+
pub use tap_receipt_header::TapReceipt;
44+
4545
#[derive(Debug)]
4646
struct SubgraphServiceResponse {
4747
inner: String,

crates/service/src/service/indexer_service.rs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,9 @@ use tower_governor::{governor::GovernorConfigBuilder, GovernorLayer};
3939
use tower_http::{cors, cors::CorsLayer, normalize_path::NormalizePath, trace::TraceLayer};
4040
use tracing::{error, info, info_span};
4141

42-
use super::request_handler::request_handler;
43-
use super::{health::health, static_subgraph::static_subgraph_request_handler};
42+
use crate::routes::health;
43+
use crate::routes::request_handler;
44+
use crate::routes::static_subgraph_request_handler;
4445
use crate::tap::IndexerTapContext;
4546
use indexer_config::Config;
4647

@@ -90,8 +91,6 @@ where
9091
InvalidFreeQueryAuthToken,
9192
#[error("Failed to sign attestation")]
9293
FailedToSignAttestation,
93-
#[error("Failed to query subgraph: {0}")]
94-
FailedToQueryStaticSubgraph(anyhow::Error),
9594

9695
#[error("Could not decode signer: {0}")]
9796
CouldNotDecodeSigner(tap_core::Error),
@@ -123,8 +122,6 @@ where
123122
| CouldNotDecodeSigner(_)
124123
| EscrowAccount(_)
125124
| ProcessingError(_) => StatusCode::BAD_REQUEST,
126-
127-
FailedToQueryStaticSubgraph(_) => StatusCode::INTERNAL_SERVER_ERROR,
128125
};
129126
tracing::error!(%self, "An IndexerServiceError occoured.");
130127
(
@@ -399,16 +396,18 @@ impl IndexerService {
399396

400397
// Check subgraph Health
401398
misc_routes = misc_routes
402-
.route("/subgraph/health/:deployment_id", get(health))
403-
.route_layer(Extension(options.config.graph_node.clone()))
399+
.route(
400+
"/subgraph/health/:deployment_id",
401+
get(health).with_state(options.config.graph_node.clone()),
402+
)
404403
.layer(misc_rate_limiter);
405404

406405
if options.config.service.serve_network_subgraph {
407406
info!("Serving network subgraph at /network");
408407

409408
misc_routes = misc_routes.route(
410409
"/network",
411-
post(static_subgraph_request_handler::<I>)
410+
post(static_subgraph_request_handler)
412411
.route_layer(Extension(network_subgraph))
413412
.route_layer(Extension(options.config.service.serve_auth_token.clone()))
414413
.route_layer(static_subgraph_rate_limiter.clone()),
@@ -419,7 +418,7 @@ impl IndexerService {
419418
info!("Serving escrow subgraph at /escrow");
420419

421420
misc_routes = misc_routes
422-
.route("/escrow", post(static_subgraph_request_handler::<I>))
421+
.route("/escrow", post(static_subgraph_request_handler))
423422
.route_layer(Extension(escrow_subgraph))
424423
.route_layer(Extension(options.config.service.serve_auth_token.clone()))
425424
.route_layer(static_subgraph_rate_limiter);

crates/service/src/service/static_subgraph.rs

Lines changed: 0 additions & 52 deletions
This file was deleted.

0 commit comments

Comments
 (0)