Skip to content

Commit ad30b6b

Browse files
committed
pre-commit fix
1 parent 94320d8 commit ad30b6b

File tree

4 files changed

+116
-81
lines changed

4 files changed

+116
-81
lines changed

apps/fortuna/src/api.rs

Lines changed: 74 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
use std::collections::{BTreeMap, VecDeque};
21
use chrono::DateTime;
32
use ethers::types::TxHash;
4-
use serde::{Deserialize, Serialize};
3+
use serde::Serialize;
4+
use std::collections::BTreeMap;
55
use utoipa::ToSchema;
66
use {
77
crate::{
@@ -27,14 +27,15 @@ use {
2727
url::Url,
2828
};
2929
pub use {chain_ids::*, index::*, live::*, metrics::*, ready::*, revelation::*};
30+
use crate::api::explorer::get_requests;
3031

3132
mod chain_ids;
33+
mod explorer;
3234
mod index;
3335
mod live;
3436
mod metrics;
3537
mod ready;
3638
mod revelation;
37-
mod explorer;
3839

3940
pub type ChainId = String;
4041

@@ -47,22 +48,12 @@ pub struct ApiMetrics {
4748
pub http_requests: Family<RequestLabel, Counter>,
4849
}
4950

50-
51-
5251
#[derive(Clone, Debug, Serialize)]
53-
enum JournalLog {
54-
Observed {
55-
tx_hash: TxHash
56-
},
57-
FailedToReveal {
58-
reason: String,
59-
},
60-
Revealed {
61-
tx_hash: TxHash
62-
},
63-
Landed {
64-
block_number: BlockNumber,
65-
}
52+
pub enum JournalLog {
53+
Observed { tx_hash: TxHash },
54+
FailedToReveal { reason: String },
55+
Revealed { tx_hash: TxHash },
56+
Landed { block_number: BlockNumber },
6657
}
6758

6859
impl JournalLog {
@@ -77,13 +68,13 @@ impl JournalLog {
7768
}
7869

7970
#[derive(Clone, Debug, Serialize)]
80-
struct TimedJournalLog {
71+
pub struct TimedJournalLog {
8172
pub timestamp: DateTime<chrono::Utc>,
82-
pub log:JournalLog,
73+
pub log: JournalLog,
8374
}
8475

8576
#[derive(Clone, Debug, Serialize, ToSchema)]
86-
struct RequestJournal {
77+
pub struct RequestJournal {
8778
pub chain_id: ChainId,
8879
pub sequence: u64,
8980
pub journal: Vec<TimedJournalLog>,
@@ -105,27 +96,32 @@ impl History {
10596
Self::default()
10697
}
10798

108-
pub fn add(&mut self, (chain_id, sequence): RequestKey, request_journal_log: TimedJournalLog){
99+
pub fn add(&mut self, (chain_id, sequence): RequestKey, request_journal_log: TimedJournalLog) {
109100
let mut new_entry = false;
110-
let entry = self.by_request_key.entry((chain_id.clone(), sequence)).or_insert_with(|| {
111-
new_entry = true;
112-
RequestJournal {
113-
chain_id: chain_id.clone(),
114-
sequence,
115-
journal: vec![],
116-
}
117-
});
118-
request_journal_log.log.get_tx_hash().map(|tx_hash| {
101+
let entry = self
102+
.by_request_key
103+
.entry((chain_id.clone(), sequence))
104+
.or_insert_with(|| {
105+
new_entry = true;
106+
RequestJournal {
107+
chain_id: chain_id.clone(),
108+
sequence,
109+
journal: vec![],
110+
}
111+
});
112+
if let Some(tx_hash) = request_journal_log.log.get_tx_hash() {
119113
self.by_hash
120114
.entry(tx_hash)
121-
.or_insert_with(Vec::new)
115+
.or_default()
122116
.push((chain_id.clone(), sequence));
123-
});
117+
}
124118
entry.journal.push(request_journal_log);
125119
if new_entry {
126120
let current_time = chrono::Utc::now();
127-
self.by_chain_and_time
128-
.insert((chain_id.clone(), current_time), (chain_id.clone(), sequence));
121+
self.by_chain_and_time.insert(
122+
(chain_id.clone(), current_time),
123+
(chain_id.clone(), sequence),
124+
);
129125
self.by_time
130126
.insert(current_time, (chain_id.clone(), sequence));
131127

@@ -140,42 +136,56 @@ impl History {
140136
}
141137

142138
pub fn get_request_logs_by_tx_hash(&self, tx_hash: TxHash) -> Vec<RequestJournal> {
143-
self.by_hash.get(&tx_hash).map(|request_keys| {
144-
request_keys.iter()
145-
.map(|request_key| self.by_request_key.get(request_key).unwrap().clone())
146-
.collect()
147-
}).unwrap_or_default()
139+
self.by_hash
140+
.get(&tx_hash)
141+
.map(|request_keys| {
142+
request_keys
143+
.iter()
144+
.map(|request_key| self.by_request_key.get(request_key).unwrap().clone())
145+
.collect()
146+
})
147+
.unwrap_or_default()
148148
}
149149

150-
pub fn get_latest_requests(&self, chain_id: Option<&ChainId>, limit: u64,
151-
min_timestamp: Option<DateTime<chrono::Utc>>,
152-
max_timestamp: Option<DateTime<chrono::Utc>>) -> Vec<RequestJournal> {
150+
pub fn get_latest_requests(
151+
&self,
152+
chain_id: Option<&ChainId>,
153+
limit: u64,
154+
min_timestamp: Option<DateTime<chrono::Utc>>,
155+
max_timestamp: Option<DateTime<chrono::Utc>>,
156+
) -> Vec<RequestJournal> {
153157
match chain_id {
154158
Some(chain_id) => {
155-
let range = self.by_chain_and_time.range((chain_id.clone(), min_timestamp.unwrap_or(DateTime::<chrono::Utc>::MIN_UTC))..(chain_id.clone(), max_timestamp.unwrap_or(DateTime::<chrono::Utc>::MAX_UTC)));
156-
range.rev()
157-
.take(limit as usize)
158-
.map(|(_, request_key)| {
159-
self.by_request_key.get(request_key).unwrap().clone()
160-
})
161-
.collect()
162-
163-
},
164-
None => {
165-
self.by_time
166-
.range(min_timestamp.unwrap_or(DateTime::<chrono::Utc>::MIN_UTC)..max_timestamp.unwrap_or(DateTime::<chrono::Utc>::MAX_UTC))
159+
let range = self.by_chain_and_time.range(
160+
(
161+
chain_id.clone(),
162+
min_timestamp.unwrap_or(DateTime::<chrono::Utc>::MIN_UTC),
163+
)
164+
..(
165+
chain_id.clone(),
166+
max_timestamp.unwrap_or(DateTime::<chrono::Utc>::MAX_UTC),
167+
),
168+
);
169+
range
167170
.rev()
168171
.take(limit as usize)
169-
.map(|(_time, request_key)| {
170-
self.by_request_key.get(request_key).unwrap().clone()
171-
})
172-
.collect::<Vec<_>>()
173-
},
172+
.map(|(_, request_key)| self.by_request_key.get(request_key).unwrap().clone())
173+
.collect()
174+
}
175+
None => self
176+
.by_time
177+
.range(
178+
min_timestamp.unwrap_or(DateTime::<chrono::Utc>::MIN_UTC)
179+
..max_timestamp.unwrap_or(DateTime::<chrono::Utc>::MAX_UTC),
180+
)
181+
.rev()
182+
.take(limit as usize)
183+
.map(|(_time, request_key)| self.by_request_key.get(request_key).unwrap().clone())
184+
.collect::<Vec<_>>(),
174185
}
175186
}
176187
}
177188

178-
179189
#[derive(Clone)]
180190
pub struct ApiState {
181191
pub chains: Arc<RwLock<HashMap<ChainId, ApiBlockChainState>>>,
@@ -192,7 +202,7 @@ impl ApiState {
192202
pub async fn new(
193203
chains: Arc<RwLock<HashMap<ChainId, ApiBlockChainState>>>,
194204
metrics_registry: Arc<RwLock<Registry>>,
195-
history: Arc<RwLock<History>>
205+
history: Arc<RwLock<History>>,
196206
) -> ApiState {
197207
let metrics = ApiMetrics {
198208
http_requests: Family::default(),
@@ -312,6 +322,7 @@ pub fn routes(state: ApiState) -> Router<(), Body> {
312322
.route("/metrics", get(metrics))
313323
.route("/ready", get(ready))
314324
.route("/v1/chains", get(chain_ids))
325+
.route("/v1/explorer", get(get_requests))
315326
.route(
316327
"/v1/chains/:chain_id/revelations/:sequence",
317328
get(revelation),
@@ -397,7 +408,7 @@ mod test {
397408
ApiBlockChainState::Initialized(avax_state),
398409
);
399410

400-
let api_state = ApiState::new(Arc::new(RwLock::new(chains)), metrics_registry).await;
411+
let api_state = ApiState::new(Arc::new(RwLock::new(chains)), metrics_registry, Default::default()).await;
401412

402413
let app = api::routes(api_state);
403414
(TestServer::new(app).unwrap(), eth_read, avax_read)

apps/fortuna/src/api/explorer.rs

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
use axum::extract::{Path, Query, State};
1+
use crate::api::{
2+
ChainId, RequestJournal, RestError
3+
,
4+
};
5+
use axum::extract::{Query, State};
26
use axum::Json;
37
use ethers::types::TxHash;
48
use utoipa::IntoParams;
5-
use crate::api::{BinaryEncoding, ChainId, GetRandomValueResponse, RequestJournal, RestError, RevelationPathParams, RevelationQueryParams};
6-
use crate::chain::reader::BlockNumber;
7-
89

910
#[derive(Debug, serde::Serialize, serde::Deserialize, IntoParams)]
1011
#[into_params(parameter_in=Query)]
@@ -43,13 +44,31 @@ pub async fn get_requests(
4344
) -> anyhow::Result<Json<Vec<RequestJournal>>, RestError> {
4445
let result = match query_params.mode {
4546
ExplorerQueryParamsMode::TxHash => {
46-
let tx_hash = query_params.tx_hash.ok_or(RestError::BadFilterParameters("tx_hash is required when mode=tx-hash".to_string()))?;
47-
state.history.read().await.get_request_logs_by_tx_hash(tx_hash)
47+
let tx_hash = query_params.tx_hash.ok_or(RestError::BadFilterParameters(
48+
"tx_hash is required when mode=tx-hash".to_string(),
49+
))?;
50+
state
51+
.history
52+
.read()
53+
.await
54+
.get_request_logs_by_tx_hash(tx_hash)
4855
}
4956
ExplorerQueryParamsMode::ChainAndSequence => {
50-
let chain_id = query_params.chain_id.ok_or(RestError::BadFilterParameters("chain_id is required when mode=chain-and-sequence".to_string()))?;
51-
let sequence_id = query_params.sequence_id.ok_or(RestError::BadFilterParameters("sequence_id is required when mode=chain-and-sequence".to_string()))?;
52-
state.history.read().await.get_request_logs(&(chain_id, sequence_id)).into_iter().collect()
57+
let chain_id = query_params.chain_id.ok_or(RestError::BadFilterParameters(
58+
"chain_id is required when mode=chain-and-sequence".to_string(),
59+
))?;
60+
let sequence_id = query_params
61+
.sequence_id
62+
.ok_or(RestError::BadFilterParameters(
63+
"sequence_id is required when mode=chain-and-sequence".to_string(),
64+
))?;
65+
state
66+
.history
67+
.read()
68+
.await
69+
.get_request_logs(&(chain_id, sequence_id))
70+
.into_iter()
71+
.collect()
5372
}
5473
ExplorerQueryParamsMode::ChainAndTimestamp => {
5574
vec![]
@@ -58,7 +77,5 @@ pub async fn get_requests(
5877
vec![]
5978
}
6079
};
61-
Ok(
62-
Json(result),
63-
)
64-
}
80+
Ok(Json(result))
81+
}

apps/fortuna/src/command/run.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use crate::api::History;
12
use {
23
crate::{
34
api::{self, ApiBlockChainState, BlockchainState, ChainId},
@@ -21,7 +22,6 @@ use {
2122
utoipa::OpenApi,
2223
utoipa_swagger_ui::SwaggerUi,
2324
};
24-
use crate::api::History;
2525

2626
pub async fn run_api(
2727
socket_addr: SocketAddr,
@@ -148,8 +148,15 @@ pub async fn run(opts: &RunOptions) -> Result<()> {
148148

149149
Ok::<(), Error>(())
150150
});
151-
152-
run_api(opts.addr, chains.clone(), metrics_registry.clone(),history, rx_exit).await?;
151+
152+
run_api(
153+
opts.addr,
154+
chains.clone(),
155+
metrics_registry.clone(),
156+
history,
157+
rx_exit,
158+
)
159+
.await?;
153160
Ok(())
154161
}
155162

apps/fortuna/src/keeper.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use crate::api::History;
12
use crate::keeper::track::track_block_timestamp_lag;
23
use {
34
crate::{
@@ -26,7 +27,6 @@ use {
2627
},
2728
tracing::{self, Instrument},
2829
};
29-
use crate::api::History;
3030

3131
pub(crate) mod block;
3232
pub(crate) mod commitment;
@@ -60,7 +60,7 @@ pub async fn run_keeper_threads(
6060
chain_eth_config: EthereumConfig,
6161
chain_state: BlockchainState,
6262
metrics: Arc<KeeperMetrics>,
63-
history: Arc<RwLock<History>>,
63+
_history: Arc<RwLock<History>>,
6464
rpc_metrics: Arc<RpcMetrics>,
6565
) -> anyhow::Result<()> {
6666
tracing::info!("Starting keeper");

0 commit comments

Comments
 (0)