Skip to content

Commit ecb115e

Browse files
committed
refactor: use attestation middleware
Signed-off-by: Gustavo Inacio <[email protected]>
1 parent 5e683d3 commit ecb115e

File tree

5 files changed

+37
-87
lines changed

5 files changed

+37
-87
lines changed

crates/service/src/error.rs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
// Copyright 2023-, Edge & Node, GraphOps, and Semiotic Labs.
22
// SPDX-License-Identifier: Apache-2.0
33

4-
use alloy::primitives::Address;
54
use anyhow::Error;
65
use axum::{
76
response::{IntoResponse, Response},
@@ -27,12 +26,8 @@ pub enum IndexerServiceError {
2726

2827
#[error("Issues with provided receipt: {0}")]
2928
ReceiptError(#[from] tap_core::Error),
30-
#[error("No attestation signer found for allocation `{0}`")]
31-
NoSignerForAllocation(Address),
3229
#[error("Error while processing the request: {0}")]
3330
ProcessingError(SubgraphServiceError),
34-
#[error("Failed to sign attestation")]
35-
FailedToSignAttestation,
3631

3732
#[error("There was an error while accessing escrow account: {0}")]
3833
EscrowAccount(#[from] EscrowAccountsError),
@@ -48,8 +43,6 @@ impl IntoResponse for IndexerServiceError {
4843
}
4944

5045
let status = match self {
51-
NoSignerForAllocation(_) | FailedToSignAttestation => StatusCode::INTERNAL_SERVER_ERROR,
52-
5346
ReceiptError(_) | EscrowAccount(_) | ProcessingError(_) => StatusCode::BAD_REQUEST,
5447
ReceiptNotFound => StatusCode::PAYMENT_REQUIRED,
5548
DeploymentIdNotFound => StatusCode::INTERNAL_SERVER_ERROR,

crates/service/src/middleware.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,6 @@ pub use inject_deployment::deployment_middleware;
1818
pub use inject_labels::labels_middleware;
1919
pub use inject_receipt::receipt_middleware;
2020
pub use inject_sender::{sender_middleware, SenderState};
21+
pub use inject_attestation_signer::{signer_middleware, AttestationState};
22+
pub use attestation::{attestation_middleware, AttestationInput};
2123
pub use prometheus_metrics::PrometheusMetricsMiddlewareLayer;

crates/service/src/routes/request_handler.rs

Lines changed: 4 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,51 +3,28 @@
33

44
use std::sync::Arc;
55

6-
use crate::{error::IndexerServiceError, middleware::Allocation};
6+
use crate::error::IndexerServiceError;
77
use axum::{
88
extract::{Path, State},
99
response::IntoResponse,
10-
Extension,
1110
};
12-
use reqwest::StatusCode;
1311
use thegraph_core::DeploymentId;
1412
use tracing::trace;
1513

16-
use crate::service::{AttestationOutput, IndexerServiceResponse, IndexerServiceState};
14+
use crate::service::IndexerServiceState;
1715

1816
pub async fn request_handler(
1917
Path(manifest_id): Path<DeploymentId>,
20-
Extension(Allocation(allocation_id)): Extension<Allocation>,
2118
State(state): State<Arc<IndexerServiceState>>,
2219
req: String,
2320
) -> Result<impl IntoResponse, IndexerServiceError> {
2421
trace!("Handling request for deployment `{manifest_id}`");
2522

26-
// Check if we have an attestation signer for the allocation the receipt was created for
27-
let signer = state
28-
.attestation_signers
29-
.borrow()
30-
.get(&allocation_id)
31-
.cloned()
32-
.ok_or_else(|| (IndexerServiceError::NoSignerForAllocation(allocation_id)))?;
33-
3423
let response = state
3524
.service_impl
36-
.process_request(manifest_id, &req)
25+
.process_request(manifest_id, req)
3726
.await
3827
.map_err(IndexerServiceError::ProcessingError)?;
3928

40-
let res = response
41-
.as_str()
42-
.map_err(|_| IndexerServiceError::FailedToSignAttestation)?;
43-
44-
let attestation = AttestationOutput::Attestation(
45-
response
46-
.is_attestable()
47-
.then(|| signer.create_attestation(&req, res)),
48-
);
49-
50-
let response = response.finalize(attestation);
51-
52-
Ok((StatusCode::OK, response))
29+
Ok(response)
5330
}

crates/service/src/service.rs

Lines changed: 18 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,12 @@ use anyhow::anyhow;
99
use async_graphql::{EmptySubscription, Schema};
1010
use async_graphql_axum::GraphQL;
1111
use axum::{
12+
http::{HeaderValue, Response},
1213
routing::{post, post_service},
13-
Json, Router,
14+
Router,
1415
};
1516
use indexer_config::{Config, DipsConfig};
16-
use reqwest::Url;
17-
use serde::{de::DeserializeOwned, Serialize};
18-
use serde_json::{json, Value};
17+
use reqwest::{header::CONTENT_TYPE, Url};
1918
use sqlx::PgPool;
2019
use thegraph_core::attestation::eip712_domain;
2120
use thegraph_core::DeploymentId;
@@ -26,6 +25,7 @@ use crate::{
2625
self,
2726
dips::{AgreementStore, InMemoryAgreementStore},
2827
},
28+
middleware::AttestationInput,
2929
routes::dips::Price,
3030
service::indexer_service::{IndexerServiceOptions, IndexerServiceRelease},
3131
};
@@ -38,42 +38,6 @@ mod tap_receipt_header;
3838
pub use indexer_service::{AttestationOutput, IndexerServiceResponse, IndexerServiceState};
3939
pub use tap_receipt_header::TapReceipt;
4040

41-
#[derive(Debug)]
42-
pub struct SubgraphServiceResponse {
43-
inner: String,
44-
attestable: bool,
45-
}
46-
47-
impl SubgraphServiceResponse {
48-
pub fn new(inner: String, attestable: bool) -> Self {
49-
Self { inner, attestable }
50-
}
51-
}
52-
53-
impl IndexerServiceResponse for SubgraphServiceResponse {
54-
type Data = Json<Value>;
55-
type Error = SubgraphServiceError; // not used
56-
57-
fn is_attestable(&self) -> bool {
58-
self.attestable
59-
}
60-
61-
fn as_str(&self) -> Result<&str, Self::Error> {
62-
Ok(self.inner.as_str())
63-
}
64-
65-
fn finalize(self, attestation: AttestationOutput) -> Self::Data {
66-
let (attestation_key, attestation_value) = match attestation {
67-
AttestationOutput::Attestation(attestation) => ("attestation", json!(attestation)),
68-
AttestationOutput::Attestable => ("attestable", json!(self.is_attestable())),
69-
};
70-
Json(json!({
71-
"graphQLResponse": self.inner,
72-
attestation_key: attestation_value,
73-
}))
74-
}
75-
}
76-
7741
#[derive(Clone)]
7842
pub struct SubgraphServiceState {
7943
pub config: &'static Config,
@@ -95,11 +59,11 @@ impl SubgraphService {
9559
}
9660

9761
impl SubgraphService {
98-
pub async fn process_request<Request: DeserializeOwned + Send + std::fmt::Debug + Serialize>(
62+
pub async fn process_request(
9963
&self,
10064
deployment: DeploymentId,
101-
request: &Request,
102-
) -> Result<SubgraphServiceResponse, SubgraphServiceError> {
65+
req: String,
66+
) -> Result<Response<String>, SubgraphServiceError> {
10367
let deployment_url = self
10468
.state
10569
.graph_node_query_base_url
@@ -110,7 +74,8 @@ impl SubgraphService {
11074
.state
11175
.graph_node_client
11276
.post(deployment_url)
113-
.json(request)
77+
.body(req.clone())
78+
.header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
11479
.send()
11580
.await
11681
.map_err(SubgraphServiceError::QueryForwardingError)?;
@@ -126,8 +91,16 @@ impl SubgraphService {
12691
.text()
12792
.await
12893
.map_err(SubgraphServiceError::QueryForwardingError)?;
94+
let attestation_input = if attestable {
95+
AttestationInput::Attestable { req }
96+
} else {
97+
AttestationInput::NotAttestable
98+
};
99+
100+
let mut response = Response::new(body);
101+
response.extensions_mut().insert(attestation_input);
129102

130-
Ok(SubgraphServiceResponse::new(body, attestable))
103+
Ok(response)
131104
}
132105
}
133106

crates/service/src/service/indexer_service.rs

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ use axum::{
1111
serve, Json, Router, ServiceExt,
1212
};
1313
use build_info::BuildInfo;
14-
use indexer_attestation::AttestationSigner;
1514
use indexer_monitor::{
1615
attestation_signers, deployment_to_allocation, dispute_manager, escrow_accounts,
1716
indexer_allocations, DeploymentDetails, SubgraphClient,
@@ -24,8 +23,8 @@ use std::{
2423
collections::HashMap, error::Error, net::SocketAddr, path::PathBuf, sync::Arc, time::Duration,
2524
};
2625
use tap_core::{manager::Manager, receipt::checks::CheckList, tap_eip712_domain};
27-
use thegraph_core::{Address, Attestation};
28-
use tokio::{net::TcpListener, signal, sync::watch::Receiver};
26+
use thegraph_core::Attestation;
27+
use tokio::{net::TcpListener, signal};
2928
use tower::ServiceBuilder;
3029
use tower_governor::{governor::GovernorConfigBuilder, GovernorLayer};
3130
use tower_http::{
@@ -40,10 +39,11 @@ use tracing::{error, info, info_span, warn};
4039
use crate::{
4140
metrics::{FAILED_RECEIPT, HANDLER_FAILURE, HANDLER_HISTOGRAM},
4241
middleware::{
43-
allocation_middleware,
42+
allocation_middleware, attestation_middleware,
4443
auth::{self, Bearer, OrExt},
4544
context_middleware, deployment_middleware, labels_middleware, receipt_middleware,
46-
sender_middleware, AllocationState, PrometheusMetricsMiddlewareLayer, SenderState,
45+
sender_middleware, signer_middleware, AllocationState, AttestationState,
46+
PrometheusMetricsMiddlewareLayer, SenderState,
4747
},
4848
routes::{health, request_handler, static_subgraph_request_handler},
4949
tap::IndexerTapContext,
@@ -98,7 +98,6 @@ pub struct IndexerServiceOptions {
9898

9999
pub struct IndexerServiceState {
100100
pub config: Config,
101-
pub attestation_signers: Receiver<HashMap<Address, AttestationSigner>>,
102101
pub service_impl: SubgraphService,
103102
}
104103

@@ -276,7 +275,6 @@ pub async fn run(options: IndexerServiceOptions) -> Result<(), anyhow::Error> {
276275

277276
let state = Arc::new(IndexerServiceState {
278277
config: options.config.clone(),
279-
attestation_signers,
280278
service_impl: options.service_impl,
281279
});
282280

@@ -386,6 +384,9 @@ pub async fn run(options: IndexerServiceOptions) -> Result<(), anyhow::Error> {
386384
escrow_accounts,
387385
domain_separator,
388386
};
387+
let attestation_state = AttestationState {
388+
attestation_signers,
389+
};
389390

390391
let service_builder = ServiceBuilder::new()
391392
// inject deployment id
@@ -404,7 +405,11 @@ pub async fn run(options: IndexerServiceOptions) -> Result<(), anyhow::Error> {
404405
HANDLER_FAILURE.clone(),
405406
))
406407
// tap context
407-
.layer(from_fn(context_middleware));
408+
.layer(from_fn(context_middleware))
409+
// inject signer
410+
.layer(from_fn_with_state(attestation_state, signer_middleware))
411+
// create attestation
412+
.layer(from_fn(attestation_middleware));
408413

409414
request_handler_route = request_handler_route.layer(service_builder);
410415

0 commit comments

Comments
 (0)