loom_rpc_handler/handler/
ws.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
use axum::extract::{ConnectInfo, State};
use axum::{
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    response::IntoResponse,
};

use crate::dto::block::{BlockHeader, WebSocketMessage};
use eyre::ErrReport;
use loom_rpc_state::AppState;
use loom_types_blockchain::ChainParameters;
use revm::DatabaseRef;
use std::net::SocketAddr;
use tracing::{error, warn};

/// Handle websocket upgrade
pub async fn ws_handler<DB: DatabaseRef<Error = ErrReport> + Send + Sync + Clone + 'static>(
    ws: WebSocketUpgrade,
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    State(app_state): State<AppState<DB>>,
) -> impl IntoResponse {
    ws.on_failed_upgrade(move |e| {
        warn!("ws upgrade error: {} with {}", e, addr);
    })
    .on_upgrade(move |socket| on_upgrade(socket, addr, app_state))
}

/// Actual websocket statemachine (one will be spawned per connection)
async fn on_upgrade<DB: DatabaseRef + Send + Sync + Clone + 'static>(mut socket: WebSocket, _who: SocketAddr, app_state: AppState<DB>) {
    let mut receiver = app_state.bc.new_block_headers_channel().subscribe().await;

    while let Ok(header) = receiver.recv().await {
        let ws_msg = WebSocketMessage::BlockHeader(BlockHeader {
            number: header.inner.header.number,
            timestamp: header.inner.header.timestamp,
            base_fee_per_gas: header.inner.header.base_fee_per_gas,
            next_block_base_fee: ChainParameters::ethereum().calc_next_block_base_fee_from_header(&header.inner.header),
        });
        match serde_json::to_string(&ws_msg) {
            Ok(json) => {
                let _ = socket.send(Message::Text(json)).await;
            }
            Err(e) => {
                error!("Failed to serialize block header: {}", e);
            }
        }
    }
}