ecat_data_sqlx/
routing.rs1use std::sync::Arc;
6use std::time::Duration;
7
8use ecat_data::{RdbmsClient, RdbmsRouting};
9use serde::Deserialize;
10
11use crate::{SqlxClient, SqlxConfig};
12
13fn default_true() -> bool {
15 true
16}
17
18#[derive(Debug, Clone, Deserialize)]
20#[serde(deny_unknown_fields)]
21pub struct SqlxRoutingConfig {
22 pub primary: SqlxConfig,
23 #[serde(default)]
24 pub replicas: Vec<SqlxConfig>,
25 #[serde(default)]
27 pub max_replica_lag_secs: Option<u64>,
28 #[serde(default = "default_true")]
30 pub fallback_to_primary: bool,
31}
32
33pub async fn build_routing(cfg: &SqlxRoutingConfig) -> Result<RdbmsRouting, sqlx::Error> {
35 let primary = Arc::new(SqlxClient::from_config(cfg.primary.clone()).await?);
36 let mut replicas: Vec<Arc<dyn RdbmsClient>> = Vec::with_capacity(cfg.replicas.len());
37 for replica in &cfg.replicas {
38 replicas.push(Arc::new(SqlxClient::from_config(replica.clone()).await?));
39 }
40 let mut routing =
41 RdbmsRouting::new(primary, replicas).fallback_to_primary(cfg.fallback_to_primary);
42 if let Some(secs) = cfg.max_replica_lag_secs {
43 routing = routing.max_replica_lag(Duration::from_secs(secs));
44 }
45 Ok(routing)
46}
47
48#[cfg(test)]
49mod tests;