-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckpoint_service.rs
323 lines (305 loc) · 11.5 KB
/
checkpoint_service.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
use model::{checkpoint::{ActiveModel, Entity as Checkpoint, RpcCheckpointInfo, RpcCheckpointInfoBatchExp}, block:: Entity as Block};
use sea_orm::{
prelude::*, ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter, QueryOrder, Order,
QuerySelect
};
use tracing::{error, info};
use model::pgu64::PgU64;
use crate::services::pagination::PaginatedData;
use super::utils::resolve_order;
pub struct CheckpointService<'a> {
pub db: &'a DatabaseConnection,
}
impl<'a> CheckpointService<'a> {
pub fn new(db: &'a DatabaseConnection) -> Self {
Self { db }
}
pub async fn checkpoint_exists(&self, idx: i64) -> bool {
Checkpoint::find()
.filter(model::checkpoint::Column::Idx.eq(idx))
.one(self.db)
.await
.map(|result| result.is_some())
.unwrap_or(false)
}
/// Insert a new checkpoint into the database
pub async fn insert_checkpoint(&self, checkpoint: RpcCheckpointInfo) {
let idx: i64 = PgU64(checkpoint.idx).to_i64();
// for the first checkpoint, no need to check the previous checkpoint
if idx > i64::MIN {
if let Some(previous_idx) = idx.checked_sub(1) {
let previous_checkpoint_exists = self.checkpoint_exists(previous_idx).await;
// checkpoints must be continuous, better to restart to re-sync from a valid checkpoint
if !previous_checkpoint_exists {
error!(
"Cannot insert checkpoint with idx {}: previous checkpoint with idx {} does not exist",
checkpoint.idx, previous_idx
);
return;
}
}
}
// Insert the checkpoint
let active_model: ActiveModel = checkpoint.into();
match Checkpoint::insert(active_model).exec(self.db).await {
Ok(_) => info!("Checkpoint with idx {} inserted successfully", idx),
Err(err) => error!("Error inserting checkpoint with idx {}: {:?}", idx, err),
}
}
/// Fetch a checkpoint by its index
pub async fn get_checkpoint_by_idx(&self, idx: i64) -> Option<RpcCheckpointInfoBatchExp> {
match Checkpoint::find()
.filter(model::checkpoint::Column::Idx.eq(idx))
.one(self.db)
.await
{
Ok(Some(checkpoint)) => {
Some(checkpoint.into())
}
Ok(None) => None,
Err(err) => {
error!("Error fetching checkpoint by idx: {:?}", err);
None
}
}
}
/// Fetch a checkpoint by its L2 block ID
pub async fn get_checkpoint_idx_by_block_hash(
&self,
block_hash: &str,
) -> Result<Option<i64>, DbErr> {
match Block::find()
.filter(model::block::Column::BlockHash.eq(block_hash))
.one(self.db)
.await
{
Ok(Some(block))=>{
tracing::info!("Block found: {:?}", block);
Ok(Some(block.checkpoint_idx))
}
Ok(None) => {
tracing::info!("No block found for hash: {}", block_hash);
Ok(None)
}
Err(err) => {
tracing::error!("Query failed: {:?}", err);
Err(err)
}
}
}
/// Fetch a checkpoint by its L2 block height
pub async fn get_checkpoint_idx_by_block_height(
&self,
block_height: i64,
) -> Result<Option<i64>, DbErr> {
tracing::debug!("Searching for block with height: {}", block_height);
match Block::find()
.filter(model::block::Column::Height.eq(block_height))
.one(self.db)
.await
{
Ok(Some(block)) => {
tracing::info!("Block found: {:?}", block);
Ok(Some(block.checkpoint_idx))
}
Ok(None) => {
tracing::info!("No block found for height: {}", block_height);
Ok(None)
}
Err(err) => {
tracing::error!("Query failed: {:?}", err);
Err(err)
}
}
}
// TODO: move this out of db and have a separate pagination wrapper module
pub async fn get_paginated_checkpoints(
&self,
current_page: u64,
page_size: u64,
absolute_first_page: u64,
order: Option<&str>
) -> PaginatedData<RpcCheckpointInfoBatchExp> {
let total_checkpoints = self.get_total_checkpoint_count().await;
let total_pages = (total_checkpoints as f64 / page_size as f64).ceil() as u64;
let offset = (current_page - absolute_first_page) * page_size; // Adjust based on the first page
let order = resolve_order(order);
// Convert `u64` to `i64` for compatibility with PostgreSQL
let offset = offset.try_into().ok();
let limit = page_size.try_into().ok();
let items = match Checkpoint::find()
.filter(Expr::col(model::checkpoint::Column::Idx).is_not_null()) // Ensure idx is not NULL
.order_by(model::checkpoint::Column::Idx, order) // Sort numerically
.offset(offset)
.limit(limit)
.all(self.db)
.await
{
Ok(checkpoints) => checkpoints.into_iter().map(Into::into).collect(),
Err(err) => {
error!("Error fetching paginated checkpoints: {:?}", err);
vec![]
}
};
PaginatedData {
current_page,
total_pages,
absolute_first_page,
items,
}
}
/// Get the total count of checkpoints in the database
pub async fn get_total_checkpoint_count(&self) -> u64 {
use sea_orm::entity::prelude::*;
match Checkpoint::find().count(self.db).await {
Ok(count) => count,
Err(err) => {
error!("Failed to count checkpoints: {:?}", err);
0
}
}
}
/// Get the latest checkpoint index stored in the database
pub async fn get_latest_checkpoint_index(&self) -> Option<i64> {
use sea_orm::entity::prelude::*;
match Checkpoint::find()
.select_only()
.column_as(model::checkpoint::Column::Idx.max(), "max_idx")
.into_tuple::<Option<i64>>() // Fetch the max value as a tuple
.one(self.db)
.await
{
Ok(Some(max_idx)) => max_idx,
Ok(_) => None, // If no checkpoints exist, return None
Err(err) => {
error!("Failed to fetch the latest checkpoint index: {:?}", err);
None
}
}
}
/// Get the earliest checkpoint index whose status is either `Pending` or `Confirmed` or `-`
pub async fn get_earliest_unfinalized_checkpoint_idx(&self) -> Option<i64> {
// add the condition to check no checkpoint at all
self.get_latest_checkpoint_index().await?;
match Checkpoint::find()
.filter(
model::checkpoint::Column::Status.eq("Pending")
.or(model::checkpoint::Column::Status.eq("Confirmed"))
.or(model::checkpoint::Column::Status.eq("-")),
)
.order_by(model::checkpoint::Column::Idx, Order::Asc)
.one(self.db)
.await
{
Ok(Some(checkpoint)) => Some(checkpoint.idx),
Ok(None) => None,
Err(err) => {
error!("Error fetching earliest unfinalized checkpoint: {:?}", err);
None
}
}
}
/// Get the earliest checkpoint index whose status is `Pending`
pub async fn get_earliest_pending_checkpoint_idx(&self) -> Option<i64> {
// add the condition to check no checkpoint at all
self.get_latest_checkpoint_index().await?;
match Checkpoint::find()
.filter(
model::checkpoint::Column::Status.eq("Pending"),
)
.order_by(model::checkpoint::Column::Idx, Order::Asc)
.one(self.db)
.await
{
Ok(Some(checkpoint)) => Some(checkpoint.idx),
Ok(None) => None,
Err(err) => {
error!("Error fetching earliest pending checkpoint: {:?}", err);
None
}
}
}
/// Get the earliest checkpoint index whose status is `Pending`
pub async fn get_earliest_confirmed_checkpoint_idx(&self) -> Option<i64> {
// add the condition to check no checkpoint at all
self.get_latest_checkpoint_index().await?;
match Checkpoint::find()
.filter(
model::checkpoint::Column::Status.eq("Confirmed"),
)
.order_by(model::checkpoint::Column::Idx, Order::Asc)
.one(self.db)
.await
{
Ok(Some(checkpoint)) => Some(checkpoint.idx),
Ok(None) => None,
Err(err) => {
error!("Error fetching earliest confirmed checkpoint: {:?}", err);
None
}
}
}
/// Get the earliest checkpoint index whose status is `Pending`
pub async fn get_last_finalized_checkpoint_idx(&self) -> Option<i64> {
// add the condition to check no checkpoint at all
self.get_latest_checkpoint_index().await?;
match Checkpoint::find()
.filter(
model::checkpoint::Column::Status.eq("Finalized"),
)
.order_by(model::checkpoint::Column::Idx, Order::Desc)
.one(self.db)
.await
{
Ok(Some(checkpoint)) => Some(checkpoint.idx),
Ok(None) => None,
Err(err) => {
error!("Error fetching last finalized checkpoint: {:?}", err);
None
}
}
}
/// Update the status of a checkpoint
pub async fn update_checkpoint(&self, checkpoint_idx: i64, updated_checkpoint: RpcCheckpointInfo) -> Result<(), DbErr> {
match Checkpoint::find()
.filter(model::checkpoint::Column::Idx.eq(checkpoint_idx))
.one(self.db)
.await
{
Ok(Some(checkpoint)) => {
let mut active_model: ActiveModel = checkpoint.into();
let updated_checkpoint: ActiveModel = updated_checkpoint.into();
let status = updated_checkpoint.status.clone();
active_model.status = status;
active_model.batch_txid = updated_checkpoint.batch_txid;
match active_model.update(self.db).await {
Ok(_) => {
info!(
"Checkpoint with idx {} updated successfully",
checkpoint_idx
);
Ok(())
},
Err(err) => {
error!(
"Failed to update checkpoint with idx {}: {:?}",
checkpoint_idx, err
);
Err(err)
},
}
}
Ok(None) => {
error!("Checkpoint with idx {} not found", checkpoint_idx);
Err(DbErr::RecordNotFound(format!("Checkpoint with idx {} not found", checkpoint_idx)))
}
Err(err) => {
error!(
"Error querying checkpoint with idx {}: {:?}",
checkpoint_idx, err
);
Err(err)
}
}
}
}