Files
telemt/src/transport/middle_proxy/registry.rs
T

61 lines
1.8 KiB
Rust
Raw Normal View History

2026-02-14 01:36:14 +03:00
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use tokio::sync::{RwLock, mpsc};
use super::MeResponse;
2026-02-15 14:02:00 +03:00
use super::codec::RpcWriter;
use std::sync::Arc;
use tokio::sync::Mutex;
2026-02-14 01:36:14 +03:00
pub struct ConnRegistry {
2026-02-16 12:49:16 +07:00
map: RwLock<HashMap<u64, mpsc::UnboundedSender<MeResponse>>>,
2026-02-15 14:02:00 +03:00
writers: RwLock<HashMap<u64, Arc<Mutex<RpcWriter>>>>,
2026-02-14 01:36:14 +03:00
next_id: AtomicU64,
}
impl ConnRegistry {
pub fn new() -> Self {
2026-02-14 01:51:10 +03:00
// Avoid fully predictable conn_id sequence from 1.
let start = rand::random::<u64>() | 1;
2026-02-14 01:36:14 +03:00
Self {
map: RwLock::new(HashMap::new()),
2026-02-15 14:02:00 +03:00
writers: RwLock::new(HashMap::new()),
2026-02-14 01:51:10 +03:00
next_id: AtomicU64::new(start),
2026-02-14 01:36:14 +03:00
}
}
2026-02-16 12:49:16 +07:00
pub async fn register(&self) -> (u64, mpsc::UnboundedReceiver<MeResponse>) {
2026-02-14 01:36:14 +03:00
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
2026-02-16 12:49:16 +07:00
// Unbounded per-connection queue prevents reader-loop HOL blocking on
// slow clients: routing stays non-blocking and preserves message order.
let (tx, rx) = mpsc::unbounded_channel();
2026-02-14 01:36:14 +03:00
self.map.write().await.insert(id, tx);
(id, rx)
}
pub async fn unregister(&self, id: u64) {
self.map.write().await.remove(&id);
2026-02-15 14:02:00 +03:00
self.writers.write().await.remove(&id);
2026-02-14 01:36:14 +03:00
}
pub async fn route(&self, id: u64, resp: MeResponse) -> bool {
let m = self.map.read().await;
if let Some(tx) = m.get(&id) {
2026-02-16 12:49:16 +07:00
tx.send(resp).is_ok()
2026-02-14 01:36:14 +03:00
} else {
false
}
}
2026-02-15 14:02:00 +03:00
pub async fn set_writer(&self, id: u64, w: Arc<Mutex<RpcWriter>>) {
let mut guard = self.writers.write().await;
guard.entry(id).or_insert_with(|| w);
}
pub async fn get_writer(&self, id: u64) -> Option<Arc<Mutex<RpcWriter>>> {
let guard = self.writers.read().await;
guard.get(&id).cloned()
}
2026-02-14 01:36:14 +03:00
}