|
| 1 | +//! API server for Prometheus metrics and health checks |
| 2 | +
|
1 | 3 | use { |
2 | | - crate::chain::reader::BlockStatus, |
3 | | - axum::{ |
4 | | - body::Body, |
5 | | - http::StatusCode, |
6 | | - response::{IntoResponse, Response}, |
7 | | - routing::get, |
8 | | - Router, |
9 | | - }, |
10 | | - prometheus_client::{ |
11 | | - encoding::EncodeLabelSet, |
12 | | - metrics::{counter::Counter, family::Family}, |
13 | | - registry::Registry, |
14 | | - }, |
15 | | - std::sync::Arc, |
16 | | - tokio::sync::RwLock, |
| 4 | + anyhow::{anyhow, Result}, |
| 5 | + axum::{body::Body, routing::get, Router}, |
| 6 | + index::index, |
| 7 | + live::live, |
| 8 | + metrics::metrics, |
| 9 | + prometheus_client::registry::Registry, |
| 10 | + ready::ready, |
| 11 | + std::{net::SocketAddr, sync::Arc}, |
| 12 | + tokio::sync::{watch, RwLock}, |
| 13 | + tower_http::cors::CorsLayer, |
17 | 14 | }; |
18 | | -pub use {index::*, live::*, metrics::*, ready::*}; |
19 | | - |
20 | 15 | mod index; |
21 | 16 | mod live; |
22 | 17 | mod metrics; |
23 | 18 | mod ready; |
24 | | - |
25 | | -pub type ChainId = String; |
26 | | - |
27 | | -#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)] |
28 | | -pub struct RequestLabel { |
29 | | - pub value: String, |
30 | | -} |
31 | | - |
32 | | -pub struct ApiMetrics { |
33 | | - pub http_requests: Family<RequestLabel, Counter>, |
34 | | -} |
35 | | - |
36 | 19 | #[derive(Clone)] |
37 | 20 | pub struct ApiState { |
38 | 21 | pub metrics_registry: Arc<RwLock<Registry>>, |
39 | | - |
40 | | - /// Prometheus metrics |
41 | | - pub metrics: Arc<ApiMetrics>, |
42 | | -} |
43 | | - |
44 | | -impl ApiState { |
45 | | - pub async fn new(metrics_registry: Arc<RwLock<Registry>>) -> ApiState { |
46 | | - let metrics = ApiMetrics { |
47 | | - http_requests: Family::default(), |
48 | | - }; |
49 | | - |
50 | | - let http_requests = metrics.http_requests.clone(); |
51 | | - metrics_registry.write().await.register( |
52 | | - "http_requests", |
53 | | - "Number of HTTP requests received", |
54 | | - http_requests, |
55 | | - ); |
56 | | - |
57 | | - ApiState { |
58 | | - metrics: Arc::new(metrics), |
59 | | - metrics_registry, |
60 | | - } |
61 | | - } |
62 | | -} |
63 | | - |
64 | | -/// The state of the service for a single blockchain. |
65 | | -#[derive(Clone)] |
66 | | -pub struct BlockchainState { |
67 | | - /// The chain id for this blockchain, useful for logging |
68 | | - pub id: ChainId, |
69 | | - /// The BlockStatus of the block that is considered to be confirmed on the blockchain. |
70 | | - /// For eg., Finalized, Safe |
71 | | - pub confirmed_block_status: BlockStatus, |
72 | 22 | } |
73 | 23 |
|
74 | | -pub enum RestError { |
75 | | - /// The server cannot currently communicate with the blockchain, so is not able to verify |
76 | | - /// which random values have been requested. |
77 | | - TemporarilyUnavailable, |
78 | | - /// A catch-all error for all other types of errors that could occur during processing. |
79 | | - Unknown, |
80 | | -} |
81 | | - |
82 | | -impl IntoResponse for RestError { |
83 | | - fn into_response(self) -> Response { |
84 | | - match self { |
85 | | - RestError::TemporarilyUnavailable => ( |
86 | | - StatusCode::SERVICE_UNAVAILABLE, |
87 | | - "This service is temporarily unavailable", |
88 | | - ) |
89 | | - .into_response(), |
90 | | - RestError::Unknown => ( |
91 | | - StatusCode::INTERNAL_SERVER_ERROR, |
92 | | - "An unknown error occurred processing the request", |
93 | | - ) |
94 | | - .into_response(), |
95 | | - } |
96 | | - } |
97 | | -} |
98 | | - |
99 | | -pub fn routes(state: ApiState) -> Router<(), Body> { |
| 24 | +pub fn routes(api_state: ApiState) -> Router<(), Body> { |
100 | 25 | Router::new() |
101 | 26 | .route("/", get(index)) |
102 | 27 | .route("/live", get(live)) |
103 | | - .route("/metrics", get(metrics)) |
104 | 28 | .route("/ready", get(ready)) |
105 | | - .with_state(state) |
| 29 | + .route("/metrics", get(metrics)) |
| 30 | + .with_state(api_state) |
| 31 | +} |
| 32 | + |
| 33 | +pub async fn run_api_server( |
| 34 | + socket_addr: SocketAddr, |
| 35 | + metrics_registry: Arc<RwLock<Registry>>, |
| 36 | + mut exit_rx: watch::Receiver<bool>, |
| 37 | +) -> Result<()> { |
| 38 | + let api_state = ApiState { |
| 39 | + metrics_registry: metrics_registry.clone(), |
| 40 | + }; |
| 41 | + |
| 42 | + let app = Router::new(); |
| 43 | + let app = app |
| 44 | + .merge(routes(api_state)) |
| 45 | + // Permissive CORS layer to allow all origins |
| 46 | + .layer(CorsLayer::permissive()); |
| 47 | + |
| 48 | + tracing::info!("Starting API server on: {:?}", &socket_addr); |
| 49 | + axum::Server::try_bind(&socket_addr) |
| 50 | + .map_err(|e| anyhow!("Failed to bind to address {}: {}", &socket_addr, e))? |
| 51 | + .serve(app.into_make_service()) |
| 52 | + .with_graceful_shutdown(async { |
| 53 | + // Ctrl+c signal received |
| 54 | + let _ = exit_rx.changed().await; |
| 55 | + |
| 56 | + tracing::info!("Shutting down API server..."); |
| 57 | + }) |
| 58 | + .await?; |
| 59 | + |
| 60 | + Ok(()) |
106 | 61 | } |
0 commit comments