Skip to content

Commit 87d7a4e

Browse files
committed
refactor: update router to use split config
Signed-off-by: Gustavo Inacio <[email protected]>
1 parent b72fe1b commit 87d7a4e

File tree

3 files changed

+119
-77
lines changed

3 files changed

+119
-77
lines changed

crates/service/src/routes/health.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,13 @@ use axum::{
77
Json,
88
};
99
use graphql_client::GraphQLQuery;
10-
use indexer_config::GraphNodeConfig;
1110
use indexer_query::{health_query, HealthQuery};
1211
use reqwest::StatusCode;
1312
use serde_json::json;
1413
use thiserror::Error;
1514

15+
use crate::service::GraphNodeState;
16+
1617
#[derive(Debug, Error)]
1718
pub enum CheckHealthError {
1819
#[error("Failed to send request")]
@@ -43,15 +44,15 @@ impl IntoResponse for CheckHealthError {
4344

4445
pub async fn health(
4546
Path(deployment_id): Path<String>,
46-
State(graph_node): State<GraphNodeConfig>,
47+
State(graph_node): State<GraphNodeState>,
4748
) -> Result<impl IntoResponse, CheckHealthError> {
4849
let req_body = HealthQuery::build_query(health_query::Variables {
4950
ids: vec![deployment_id],
5051
});
5152

52-
let client = reqwest::Client::new();
53-
let response = client
54-
.post(graph_node.status_url)
53+
let response = graph_node
54+
.graph_node_client
55+
.post(graph_node.graph_node_status_url.clone())
5556
.json(&req_body)
5657
.send()
5758
.await

crates/service/src/service.rs

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -61,13 +61,6 @@ pub async fn run() -> anyhow::Result<()> {
6161
.build()
6262
.expect("Failed to init HTTP client");
6363

64-
// Graphnode state
65-
let graphnode_state = GraphNodeState {
66-
graph_node_client: http_client.clone(),
67-
graph_node_status_url: &config.graph_node.status_url,
68-
graph_node_query_base_url: &config.graph_node.query_url,
69-
};
70-
7164
let network_subgraph = create_subgraph_client(
7265
http_client.clone(),
7366
&config.graph_node,
@@ -100,11 +93,16 @@ pub async fn run() -> anyhow::Result<()> {
10093
let router = ServiceRouter::builder()
10194
.database(database)
10295
.domain_separator(domain_separator)
103-
.graphnode_state(graphnode_state)
96+
.graph_node(&config.graph_node)
97+
.http_client(http_client)
10498
.release(release)
105-
.config(config)
106-
.network_subgraph(network_subgraph)
107-
.escrow_subgraph(escrow_subgraph)
99+
.indexer(&config.indexer)
100+
.service(&config.service)
101+
.dips(config.dips.as_ref())
102+
.blockchain(&config.blockchain)
103+
.timestamp_buffer_secs(config.tap.rav_request.timestamp_buffer_secs)
104+
.network_subgraph(network_subgraph, &config.subgraphs.network)
105+
.escrow_subgraph(escrow_subgraph, &config.subgraphs.escrow)
108106
.build();
109107

110108
serve_metrics(config.metrics.get_socket_addr());

crates/service/src/service/router.rs

Lines changed: 104 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ use axum::{
1313
Json, Router,
1414
};
1515
use governor::{clock::QuantaInstant, middleware::NoOpMiddleware};
16+
use indexer_config::{
17+
BlockchainConfig, DipsConfig, EscrowSubgraphConfig, GraphNodeConfig, IndexerConfig,
18+
NetworkSubgraphConfig, ServiceConfig, ServiceTapConfig,
19+
};
1620
use indexer_monitor::{
1721
attestation_signers, deployment_to_allocation, dispute_manager, escrow_accounts,
1822
indexer_allocations, AllocationWatcher, DisputeManagerWatcher, EscrowAccountsWatcher,
@@ -58,29 +62,42 @@ use super::{release::IndexerServiceRelease, GraphNodeState};
5862
pub struct ServiceRouter {
5963
// database
6064
database: sqlx::PgPool,
61-
6265
// tap domain
6366
domain_separator: Eip712Domain,
64-
65-
// watchers
67+
// graphnode client
68+
http_client: reqwest::Client,
69+
// release info
6670
#[builder(default, setter(strip_option))]
67-
allocations: Option<AllocationWatcher>,
71+
release: Option<IndexerServiceRelease>,
72+
73+
// configuration
74+
graph_node: &'static GraphNodeConfig,
75+
indexer: &'static IndexerConfig,
76+
service: &'static ServiceConfig,
77+
blockchain: &'static BlockchainConfig,
78+
timestamp_buffer_secs: Duration,
79+
#[builder(default)]
80+
dips: Option<&'static DipsConfig>,
81+
82+
// either provice subgraph or watcher
83+
#[builder(default, setter(transform =
84+
|subgraph: &'static SubgraphClient,
85+
config: &'static EscrowSubgraphConfig|
86+
Some((subgraph, config))))]
87+
escrow_subgraph: Option<(&'static SubgraphClient, &'static EscrowSubgraphConfig)>,
6888
#[builder(default, setter(strip_option))]
6989
escrow_accounts: Option<EscrowAccountsWatcher>,
7090

91+
// provide network subgraph or allocations + dispute manager
92+
#[builder(default, setter(transform =
93+
|subgraph: &'static SubgraphClient,
94+
config: &'static NetworkSubgraphConfig|
95+
Some((subgraph, config))))]
96+
network_subgraph: Option<(&'static SubgraphClient, &'static NetworkSubgraphConfig)>,
7197
#[builder(default, setter(strip_option))]
72-
dispute_manager: Option<DisputeManagerWatcher>,
73-
74-
// state, maybe create inside
75-
graphnode_state: GraphNodeState,
76-
98+
allocations: Option<AllocationWatcher>,
7799
#[builder(default, setter(strip_option))]
78-
release: Option<IndexerServiceRelease>,
79-
config: &'static indexer_config::Config,
80-
81-
// optional serve
82-
escrow_subgraph: &'static SubgraphClient,
83-
network_subgraph: &'static SubgraphClient,
100+
dispute_manager: Option<DisputeManagerWatcher>,
84101
}
85102

86103
const MISC_BURST_SIZE: u32 = 10;
@@ -95,6 +112,22 @@ const DEFAULT_ROUTE: &str = "/";
95112

96113
impl ServiceRouter {
97114
pub async fn create_router(self) -> anyhow::Result<Router> {
115+
let IndexerConfig {
116+
indexer_address,
117+
operator_mnemonic,
118+
} = self.indexer;
119+
let ServiceConfig {
120+
serve_network_subgraph,
121+
serve_escrow_subgraph,
122+
serve_auth_token,
123+
url_prefix,
124+
tap: ServiceTapConfig {
125+
max_receipt_value_grt,
126+
},
127+
free_query_auth_token,
128+
..
129+
} = self.service;
130+
98131
// COST
99132
let cost_schema = routes::cost::build_schema(self.database.clone()).await;
100133
let post_cost = post_service(GraphQL::new(cost_schema));
@@ -106,12 +139,12 @@ impl ServiceRouter {
106139
let agreement_store: Arc<dyn AgreementStore> = Arc::new(InMemoryAgreementStore::default());
107140
let prices: Vec<Price> = vec![];
108141

109-
let dips = match self.config.dips.as_ref() {
142+
let dips = match self.dips.as_ref() {
110143
Some(dips_config) => {
111144
let schema = dips::build_schema(
112-
self.config.indexer.indexer_address,
145+
*indexer_address,
113146
dips_config,
114-
&self.config.blockchain,
147+
self.blockchain,
115148
agreement_store,
116149
prices,
117150
);
@@ -122,50 +155,52 @@ impl ServiceRouter {
122155

123156
// Monitor the indexer's own allocations
124157
// if not provided, create monitor from subgraph
125-
let allocations = match self.allocations {
126-
Some(allocations) => allocations,
127-
None => indexer_allocations(
128-
self.network_subgraph,
129-
self.config.indexer.indexer_address,
130-
self.config.subgraphs.network.config.syncing_interval_secs,
131-
self.config
132-
.subgraphs
133-
.network
134-
.recently_closed_allocation_buffer_secs,
158+
let allocations = match (self.allocations, self.network_subgraph.as_ref()) {
159+
(Some(allocations), _) => allocations,
160+
(_, Some((network_subgraph, network))) => indexer_allocations(
161+
network_subgraph,
162+
*indexer_address,
163+
network.config.syncing_interval_secs,
164+
network.recently_closed_allocation_buffer_secs,
135165
)
136166
.await
137167
.expect("Failed to initialize indexer_allocations watcher"),
168+
(None, None) => panic!("No allocations or network subgraph was provided"),
138169
};
139170

140171
// Monitor escrow accounts
141172
// if not provided, create monitor from subgraph
142-
let escrow_accounts = match self.escrow_accounts {
143-
Some(escrow_account) => escrow_account,
144-
None => escrow_accounts(
145-
self.escrow_subgraph,
146-
self.config.indexer.indexer_address,
147-
self.config.subgraphs.escrow.config.syncing_interval_secs,
173+
let escrow_accounts = match (self.escrow_accounts, self.escrow_subgraph.as_ref()) {
174+
(Some(escrow_account), _) => escrow_account,
175+
(_, Some((escrow_subgraph, escrow))) => escrow_accounts(
176+
escrow_subgraph,
177+
*indexer_address,
178+
escrow.config.syncing_interval_secs,
148179
true, // Reject thawing signers eagerly
149180
)
150181
.await
151182
.expect("Error creating escrow_accounts channel"),
183+
(None, None) => panic!("No allocations or network subgraph was provided"),
152184
};
153185

154186
// Monitor dispute manager address
155187
// if not provided, create monitor from subgraph
156-
let dispute_manager = match self.dispute_manager {
157-
Some(dispute_manager) => dispute_manager,
158-
None => dispute_manager(self.network_subgraph, DISPUTE_MANAGER_INTERVAL)
159-
.await
160-
.expect("Failed to initialize dispute manager"),
188+
let dispute_manager = match (self.dispute_manager, self.network_subgraph.as_ref()) {
189+
(Some(dispute_manager), _) => dispute_manager,
190+
(_, Some((network_subgraph, _))) => {
191+
dispute_manager(network_subgraph, DISPUTE_MANAGER_INTERVAL)
192+
.await
193+
.expect("Failed to initialize dispute manager")
194+
}
195+
(None, None) => panic!("No allocations or network subgraph was provided"),
161196
};
162197

163198
// Maintain an up-to-date set of attestation signers, one for each
164199
// allocation
165200
let attestation_signers = attestation_signers(
166201
allocations.clone(),
167-
self.config.indexer.operator_mnemonic.clone(),
168-
self.config.blockchain.chain_id as u64,
202+
operator_mnemonic.clone(),
203+
self.blockchain.chain_id as u64,
169204
dispute_manager,
170205
);
171206

@@ -182,10 +217,11 @@ impl ServiceRouter {
182217

183218
// load serve_network_subgraph route
184219
let serve_network_subgraph = match (
185-
self.config.service.serve_auth_token.as_ref(),
186-
self.config.service.serve_network_subgraph,
220+
serve_auth_token.as_ref(),
221+
serve_network_subgraph,
222+
self.network_subgraph.as_ref(),
187223
) {
188-
(Some(free_auth_token), true) => {
224+
(Some(free_auth_token), true, Some((network_subgraph, _))) => {
189225
info!("Serving network subgraph at /network");
190226

191227
let auth_layer = ValidateRequestHeaderLayer::bearer(free_auth_token);
@@ -195,10 +231,10 @@ impl ServiceRouter {
195231
post(static_subgraph_request_handler)
196232
.route_layer(auth_layer)
197233
.route_layer(static_subgraph_rate_limiter.clone())
198-
.with_state(self.network_subgraph),
234+
.with_state(network_subgraph),
199235
)
200236
}
201-
(None, true) => {
237+
(_, true, _) => {
202238
warn!("`serve_network_subgraph` is enabled but no `serve_auth_token` provided. Disabling it.");
203239
Router::new()
204240
}
@@ -207,10 +243,11 @@ impl ServiceRouter {
207243

208244
// load serve_escrow_subgraph route
209245
let serve_escrow_subgraph = match (
210-
self.config.service.serve_auth_token.as_ref(),
211-
self.config.service.serve_escrow_subgraph,
246+
serve_auth_token.as_ref(),
247+
serve_escrow_subgraph,
248+
self.escrow_subgraph,
212249
) {
213-
(Some(free_auth_token), true) => {
250+
(Some(free_auth_token), true, Some((escrow_subgraph, _))) => {
214251
info!("Serving escrow subgraph at /escrow");
215252

216253
let auth_layer = ValidateRequestHeaderLayer::bearer(free_auth_token);
@@ -220,10 +257,10 @@ impl ServiceRouter {
220257
post(static_subgraph_request_handler)
221258
.route_layer(auth_layer)
222259
.route_layer(static_subgraph_rate_limiter)
223-
.with_state(self.escrow_subgraph),
260+
.with_state(escrow_subgraph),
224261
)
225262
}
226-
(None, true) => {
263+
(_, true, _) => {
227264
warn!("`serve_escrow_subgraph` is enabled but no `serve_auth_token` provided. Disabling it.");
228265
Router::new()
229266
}
@@ -238,8 +275,8 @@ impl ServiceRouter {
238275
IndexerTapContext::new(self.database.clone(), self.domain_separator.clone())
239276
.await;
240277

241-
let timestamp_error_tolerance = self.config.tap.rav_request.timestamp_buffer_secs;
242-
let receipt_max_value = self.config.service.tap.max_receipt_value_grt.get_value();
278+
let timestamp_error_tolerance = self.timestamp_buffer_secs;
279+
let receipt_max_value = max_receipt_value_grt.get_value();
243280

244281
// Create checks
245282
let checks = IndexerTapContext::get_checks(
@@ -265,7 +302,7 @@ impl ServiceRouter {
265302
let failed_receipt_metric = Box::leak(Box::new(FAILED_RECEIPT.clone()));
266303
let tap_auth = auth::tap_receipt_authorize(tap_manager, failed_receipt_metric);
267304

268-
if let Some(free_auth_token) = &self.config.service.serve_auth_token {
305+
if let Some(free_auth_token) = &free_query_auth_token {
269306
let free_query = Bearer::new(free_auth_token);
270307
let result = free_query.or(tap_auth);
271308
let auth_layer = AsyncRequireAuthorizationLayer::new(result);
@@ -348,16 +385,22 @@ impl ServiceRouter {
348385
None => Router::new(),
349386
};
350387

351-
let operator_address = Json(
352-
serde_json::json!({ "publicKey": public_key(&self.config.indexer.operator_mnemonic)?}),
353-
);
388+
let operator_address =
389+
Json(serde_json::json!({ "publicKey": public_key(operator_mnemonic)?}));
390+
391+
// Graphnode state
392+
let graphnode_state = GraphNodeState {
393+
graph_node_client: self.http_client,
394+
graph_node_status_url: &self.graph_node.status_url,
395+
graph_node_query_base_url: &self.graph_node.query_url,
396+
};
354397

355398
// data layer
356399
let data_routes = Router::new()
357400
.route("/subgraphs/id/:id", post_request_handler)
358-
.with_state(self.graphnode_state.clone());
401+
.with_state(graphnode_state.clone());
359402

360-
let subgraphs_route = Router::new().nest(&self.config.service.url_prefix, data_routes);
403+
let subgraphs_route = Router::new().nest(url_prefix, data_routes);
361404

362405
let misc_routes = Router::new()
363406
.route("/", get("Service is up and running"))
@@ -368,13 +411,13 @@ impl ServiceRouter {
368411
.nest("/dips", dips)
369412
.route(
370413
"/subgraph/health/:deployment_id",
371-
get(health).with_state(self.config.graph_node.clone()),
414+
get(health).with_state(graphnode_state.clone()),
372415
)
373416
.layer(misc_rate_limiter);
374417

375418
let extra_routes = Router::new()
376419
.route("/cost", post_cost)
377-
.route("/status", post_status.with_state(self.graphnode_state));
420+
.route("/status", post_status.with_state(graphnode_state));
378421

379422
let router = Router::new()
380423
.merge(misc_routes)

0 commit comments

Comments
 (0)