|
| 1 | +use crate::location_service::LocationService; |
| 2 | +use crate::store::node_store::NodeStore; |
| 3 | +use anyhow::Result; |
| 4 | +use log::{error, info, warn}; |
| 5 | +use redis::AsyncCommands; |
| 6 | +use std::sync::Arc; |
| 7 | +use std::time::Duration; |
| 8 | +use tokio::time::interval; |
| 9 | + |
| 10 | +const LOCATION_RETRY_KEY: &str = "location:retries:"; |
| 11 | +const MAX_RETRIES: u32 = 3; |
| 12 | +const BATCH_SIZE: usize = 10; |
| 13 | + |
| 14 | +pub struct LocationEnrichmentService { |
| 15 | + node_store: Arc<NodeStore>, |
| 16 | + location_service: Arc<LocationService>, |
| 17 | + redis_client: redis::Client, |
| 18 | +} |
| 19 | + |
| 20 | +impl LocationEnrichmentService { |
| 21 | + pub fn new( |
| 22 | + node_store: Arc<NodeStore>, |
| 23 | + location_service: Arc<LocationService>, |
| 24 | + redis_url: &str, |
| 25 | + ) -> Result<Self> { |
| 26 | + let redis_client = redis::Client::open(redis_url)?; |
| 27 | + Ok(Self { |
| 28 | + node_store, |
| 29 | + location_service, |
| 30 | + redis_client, |
| 31 | + }) |
| 32 | + } |
| 33 | + |
| 34 | + pub async fn run(&self, interval_seconds: u64) -> Result<()> { |
| 35 | + let mut interval = interval(Duration::from_secs(interval_seconds)); |
| 36 | + |
| 37 | + loop { |
| 38 | + interval.tick().await; |
| 39 | + |
| 40 | + if let Err(e) = self.enrich_nodes_without_location().await { |
| 41 | + error!("Location enrichment cycle failed: {}", e); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + async fn enrich_nodes_without_location(&self) -> Result<()> { |
| 47 | + let nodes = self.node_store.get_nodes().await?; |
| 48 | + let mut conn = self.redis_client.get_multiplexed_async_connection().await?; |
| 49 | + |
| 50 | + let nodes_without_location: Vec<_> = nodes |
| 51 | + .into_iter() |
| 52 | + .filter(|node| node.location.is_none()) |
| 53 | + .collect(); |
| 54 | + |
| 55 | + if nodes_without_location.is_empty() { |
| 56 | + return Ok(()); |
| 57 | + } |
| 58 | + |
| 59 | + info!( |
| 60 | + "Found {} nodes without location data", |
| 61 | + nodes_without_location.len() |
| 62 | + ); |
| 63 | + |
| 64 | + // Process in batches to respect rate limits |
| 65 | + for chunk in nodes_without_location.chunks(BATCH_SIZE) { |
| 66 | + for node in chunk { |
| 67 | + let retry_key = format!("{}{}", LOCATION_RETRY_KEY, node.id); |
| 68 | + let retries: u32 = conn.get(&retry_key).await.unwrap_or(0); |
| 69 | + |
| 70 | + if retries >= MAX_RETRIES { |
| 71 | + continue; // Skip nodes that have exceeded retry limit |
| 72 | + } |
| 73 | + |
| 74 | + match self.location_service.get_location(&node.ip_address).await { |
| 75 | + Ok(Some(location)) => { |
| 76 | + info!( |
| 77 | + "Successfully fetched location for node {}: {:?}", |
| 78 | + node.id, location |
| 79 | + ); |
| 80 | + |
| 81 | + let mut updated_node = node.clone(); |
| 82 | + updated_node.location = Some(location); |
| 83 | + |
| 84 | + if let Err(e) = self.node_store.update_node(updated_node).await { |
| 85 | + error!("Failed to update node {} with location: {}", node.id, e); |
| 86 | + } else { |
| 87 | + let _: () = conn.del(&retry_key).await?; |
| 88 | + } |
| 89 | + } |
| 90 | + Ok(None) => { |
| 91 | + // Location service is disabled |
| 92 | + break; |
| 93 | + } |
| 94 | + Err(e) => { |
| 95 | + warn!( |
| 96 | + "Failed to fetch location for node {} (attempt {}/{}): {}", |
| 97 | + node.id, |
| 98 | + retries + 1, |
| 99 | + MAX_RETRIES, |
| 100 | + e |
| 101 | + ); |
| 102 | + |
| 103 | + // Increment retry counter |
| 104 | + let _: () = conn.set_ex(&retry_key, retries + 1, 86400).await?; |
| 105 | + // Expire after 24h |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + // Rate limiting - wait between requests |
| 110 | + tokio::time::sleep(Duration::from_millis(100)).await; |
| 111 | + } |
| 112 | + |
| 113 | + // Longer wait between batches |
| 114 | + tokio::time::sleep(Duration::from_secs(1)).await; |
| 115 | + } |
| 116 | + |
| 117 | + Ok(()) |
| 118 | + } |
| 119 | +} |
0 commit comments