Skip to content

Commit 7a12d58

Browse files
authored
refactor: trim some dead code, simplify auth (#73)
* refactor: trim some dead code, simplify auth * chore: clean up tracing a bit * chore: clean up an integration test * fix: imports * nit: merge import
1 parent 177f538 commit 7a12d58

File tree

10 files changed

+115
-171
lines changed

10 files changed

+115
-171
lines changed

Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
[package]
2-
name = "zenith-builder-example"
2+
name = "builder"
33
version = "0.1.1"
4-
description = "Zenith Builder Example"
4+
description = "signet builder example"
55

66
edition = "2024"
77
rust-version = "1.85"

bin/builder.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
11
use builder::{
22
config::BuilderConfig,
3-
service::serve_builder_with_span,
3+
service::serve_builder,
44
tasks::{
55
block::Simulator, bundler, metrics::MetricsTask, oauth::Authenticator, submit::SubmitTask,
66
tx_poller,
77
},
88
};
9+
use init4_bin_base::{deps::tracing, utils::calc::SlotCalculator};
910
use signet_sim::SimCache;
10-
use signet_types::SlotCalculator;
1111
use std::sync::Arc;
1212
use tokio::select;
13+
use tracing::info_span;
1314

1415
// Note: Must be set to `multi_thread` to support async tasks.
1516
// See: https://docs.rs/tokio/latest/tokio/attr.main.html
1617
#[tokio::main(flavor = "multi_thread")]
1718
async fn main() -> eyre::Result<()> {
1819
let _guard = init4_bin_base::init4();
19-
20-
let span = tracing::info_span!("zenith-builder");
20+
let init_span_guard = info_span!("builder initialization");
2121

2222
let config = BuilderConfig::load_from_env()?.clone();
2323
let constants = config.load_pecorino_constants();
24-
let authenticator = Authenticator::new(&config);
24+
let authenticator = Authenticator::new(&config)?;
2525

2626
let (host_provider, ru_provider, sequencer_signer) = tokio::try_join!(
2727
config.connect_host_provider(),
@@ -35,7 +35,7 @@ async fn main() -> eyre::Result<()> {
3535
let (tx_channel, metrics_jh) = metrics.spawn();
3636

3737
let submit = SubmitTask {
38-
authenticator: authenticator.clone(),
38+
token: authenticator.token(),
3939
host_provider,
4040
zenith,
4141
client: reqwest::Client::new(),
@@ -47,7 +47,7 @@ async fn main() -> eyre::Result<()> {
4747
let tx_poller = tx_poller::TxPoller::new(&config);
4848
let (tx_receiver, tx_poller_jh) = tx_poller.spawn();
4949

50-
let bundle_poller = bundler::BundlePoller::new(&config, authenticator.clone());
50+
let bundle_poller = bundler::BundlePoller::new(&config, authenticator.token());
5151
let (bundle_receiver, bundle_poller_jh) = bundle_poller.spawn();
5252

5353
let authenticator_jh = authenticator.spawn();
@@ -65,8 +65,11 @@ async fn main() -> eyre::Result<()> {
6565

6666
let build_jh = sim.clone().spawn_simulator_task(constants, sim_items.clone(), submit_channel);
6767

68-
let port = config.builder_port;
69-
let server = serve_builder_with_span(([0, 0, 0, 0], port), span);
68+
let server = serve_builder(([0, 0, 0, 0], config.builder_port));
69+
70+
// We have finished initializing the builder, so we can drop the init span
71+
// guard.
72+
drop(init_span_guard);
7073

7174
select! {
7275
_ = tx_poller_jh => {

src/service.rs

Lines changed: 13 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,10 @@
1-
use std::{fmt::Debug, net::SocketAddr};
2-
31
use axum::{
42
Router,
53
http::StatusCode,
64
response::{IntoResponse, Response},
75
routing::get,
86
};
9-
use tracing::{Instrument, Span};
10-
11-
/// App result
12-
pub type AppResult<T, E = AppError> = Result<T, E>;
13-
14-
/// App error. This is a wrapper around eyre::Report that also includes an HTTP
15-
/// status code. It implements [`IntoResponse`] so that it can be returned as an
16-
/// error type from [`axum::handler::Handler`]s.
17-
#[derive(Debug)]
18-
pub struct AppError {
19-
code: StatusCode,
20-
eyre: eyre::Report,
21-
}
22-
23-
impl AppError {
24-
/// Instantiate a new error with the bad request status code.
25-
pub fn bad_req<E: std::error::Error + Send + Sync + 'static>(e: E) -> Self {
26-
Self { code: StatusCode::BAD_REQUEST, eyre: e.into() }
27-
}
28-
29-
/// Instantiate a new error with the bad request status code and an error
30-
/// string.
31-
pub fn bad_req_str(e: &str) -> Self {
32-
Self { code: StatusCode::BAD_REQUEST, eyre: eyre::eyre!(e.to_owned()) }
33-
}
34-
35-
/// Instantiate a new error with the internal server error status code.
36-
pub fn server_err<E: std::error::Error + Send + Sync + 'static>(e: E) -> Self {
37-
Self { code: StatusCode::INTERNAL_SERVER_ERROR, eyre: e.into() }
38-
}
39-
}
40-
41-
impl IntoResponse for AppError {
42-
fn into_response(self) -> Response {
43-
(self.code, format!("{}", self.eyre)).into_response()
44-
}
45-
}
7+
use std::net::SocketAddr;
468

479
/// Return a 404 Not Found response
4810
pub async fn return_404() -> Response {
@@ -55,26 +17,20 @@ pub async fn return_200() -> Response {
5517
}
5618

5719
/// Serve a builder service on the given socket address.
58-
pub fn serve_builder_with_span(
59-
socket: impl Into<SocketAddr>,
60-
span: Span,
61-
) -> tokio::task::JoinHandle<()> {
20+
pub fn serve_builder(socket: impl Into<SocketAddr>) -> tokio::task::JoinHandle<()> {
6221
let router = Router::new().route("/healthcheck", get(return_200)).fallback(return_404);
6322

6423
let addr = socket.into();
65-
tokio::spawn(
66-
async move {
67-
match tokio::net::TcpListener::bind(&addr).await {
68-
Ok(listener) => {
69-
if let Err(err) = axum::serve(listener, router).await {
70-
tracing::error!(%err, "serve failed");
71-
}
72-
}
73-
Err(err) => {
74-
tracing::error!(%err, "failed to bind to the address");
24+
tokio::spawn(async move {
25+
match tokio::net::TcpListener::bind(&addr).await {
26+
Ok(listener) => {
27+
if let Err(err) = axum::serve(listener, router).await {
28+
tracing::error!(%err, "serve failed");
7529
}
76-
};
77-
}
78-
.instrument(span),
79-
)
30+
}
31+
Err(err) => {
32+
tracing::error!(%err, "failed to bind to the address");
33+
}
34+
};
35+
})
8036
}

src/tasks/block.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@ use alloy::{
1515
};
1616
use chrono::{DateTime, Utc};
1717
use eyre::Report;
18+
use init4_bin_base::utils::calc::SlotCalculator;
1819
use signet_sim::{BlockBuild, BuiltBlock, SimCache};
19-
use signet_types::{SlotCalculator, config::SignetSystemConstants};
20+
use signet_types::config::SignetSystemConstants;
2021
use std::{
2122
sync::{
2223
Arc,
@@ -210,7 +211,7 @@ impl Simulator {
210211
}
211212
}
212213

213-
/// Spawns the simulator task, which handles the setup and sets the deadline
214+
/// Spawns the simulator task, which handles the setup and sets the deadline
214215
/// for the each round of simulation.
215216
///
216217
/// # Arguments

src/tasks/bundler.rs

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
//! Bundler service responsible for fetching bundles and sending them to the simulator.
2-
pub use crate::config::BuilderConfig;
3-
use crate::tasks::oauth::Authenticator;
2+
use crate::tasks::oauth::SharedToken;
43
use oauth2::TokenResponse;
54
use reqwest::{Client, Url};
65
use serde::{Deserialize, Serialize};
76
use signet_bundle::SignetEthBundle;
87
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
98
use tokio::task::JoinHandle;
109
use tokio::time;
11-
use tracing::{Instrument, debug, trace};
10+
use tracing::{Instrument, debug, trace, warn};
11+
12+
pub use crate::config::BuilderConfig;
13+
1214
/// Holds a bundle from the cache with a unique ID and a Zenith bundle.
1315
#[derive(Debug, Clone, Serialize, Deserialize)]
1416
pub struct Bundle {
@@ -26,12 +28,12 @@ pub struct TxPoolBundleResponse {
2628
}
2729

2830
/// The BundlePoller polls the tx-pool for bundles.
29-
#[derive(Debug, Clone)]
31+
#[derive(Debug)]
3032
pub struct BundlePoller {
3133
/// The builder configuration values.
3234
pub config: BuilderConfig,
3335
/// Authentication module that periodically fetches and stores auth tokens.
34-
pub authenticator: Authenticator,
36+
pub token: SharedToken,
3537
/// Holds a Reqwest client
3638
pub client: Client,
3739
/// Defines the interval at which the bundler polls the tx-pool for bundles.
@@ -41,28 +43,26 @@ pub struct BundlePoller {
4143
/// Implements a poller for the block builder to pull bundles from the tx-pool.
4244
impl BundlePoller {
4345
/// Creates a new BundlePoller from the provided builder config.
44-
pub fn new(config: &BuilderConfig, authenticator: Authenticator) -> Self {
45-
Self {
46-
config: config.clone(),
47-
authenticator,
48-
client: Client::new(),
49-
poll_interval_ms: 1000,
50-
}
46+
pub fn new(config: &BuilderConfig, token: SharedToken) -> Self {
47+
Self { config: config.clone(), token, client: Client::new(), poll_interval_ms: 1000 }
5148
}
5249

5350
/// Creates a new BundlePoller from the provided builder config and with the specified poll interval in ms.
5451
pub fn new_with_poll_interval_ms(
5552
config: &BuilderConfig,
56-
authenticator: Authenticator,
53+
token: SharedToken,
5754
poll_interval_ms: u64,
5855
) -> Self {
59-
Self { config: config.clone(), authenticator, client: Client::new(), poll_interval_ms }
56+
Self { config: config.clone(), token, client: Client::new(), poll_interval_ms }
6057
}
6158

6259
/// Fetches bundles from the transaction cache and returns them.
6360
pub async fn check_bundle_cache(&mut self) -> eyre::Result<Vec<Bundle>> {
6461
let bundle_url: Url = Url::parse(&self.config.tx_pool_url)?.join("bundles")?;
65-
let token = self.authenticator.fetch_oauth_token().await?;
62+
let Some(token) = self.token.read() else {
63+
warn!("No token available, skipping bundle fetch");
64+
return Ok(vec![]);
65+
};
6666

6767
let result = self
6868
.client

0 commit comments

Comments
 (0)