♻️ refactor: use BoundedVec for unregistered_servers

main
_ 2021-04-02 22:30:22 -05:00
parent 2c4d3cf534
commit 6927707501
3 changed files with 17 additions and 14 deletions

View File

@ -316,10 +316,7 @@ async fn handle_unregistered_servers_internal (state: &Arc <RelayState>)
let now = Utc::now (); let now = Utc::now ();
let server_list = { let server_list = state.unregistered_servers.to_vec ().await;
let guard = state.unregistered_servers.read ().await;
(*guard).clone ()
};
let unregistered_servers = server_list.into_iter () let unregistered_servers = server_list.into_iter ()
.map (|x| { .map (|x| {

View File

@ -84,7 +84,7 @@ pub struct RelayState {
pub shutdown_watch_rx: watch::Receiver <bool>, pub shutdown_watch_rx: watch::Receiver <bool>,
// List of recently rejected server names (Used to approve servers) // List of recently rejected server names (Used to approve servers)
pub unregistered_servers: RwLock <Vec <RejectedServer>>, pub unregistered_servers: BoundedVec <RejectedServer>,
} }
pub struct BoundedVec <T: Clone> { pub struct BoundedVec <T: Clone> {
@ -93,12 +93,23 @@ pub struct BoundedVec <T: Clone> {
} }
impl <T: Clone> BoundedVec <T> { impl <T: Clone> BoundedVec <T> {
pub fn new (bound: usize) -> Self {
Self {
bound,
v: Default::default (),
}
}
pub async fn to_vec (&self) -> Vec <T> { pub async fn to_vec (&self) -> Vec <T> {
let guard = self.v.read ().await; let guard = self.v.read ().await;
(*guard).clone () (*guard).clone ()
} }
pub async fn push (&mut self, x: T) { // Not mut because we have a RwLock
// One of the only problems with Rust is that
// 'mut' doesn't _really_ -mean 'mutable' once you're
// multi-threading or using async
pub async fn push (&self, x: T) {
let mut guard = self.v.write ().await; let mut guard = self.v.write ().await;
guard.push (x); guard.push (x);
@ -128,7 +139,7 @@ impl TryFrom <Config> for RelayState {
response_rendezvous: Default::default (), response_rendezvous: Default::default (),
shutdown_watch_tx, shutdown_watch_tx,
shutdown_watch_rx, shutdown_watch_rx,
unregistered_servers: Default::default (), unregistered_servers: BoundedVec::new (20),
}) })
} }
} }

View File

@ -63,16 +63,11 @@ pub async fn handle_listen (
match config.servers.get (&watcher_code) { match config.servers.get (&watcher_code) {
None => { None => {
error! ("Denied http_listen for non-existent server name {}", watcher_code); error! ("Denied http_listen for non-existent server name {}", watcher_code);
let mut guard = state.unregistered_servers.write ().await; state.unregistered_servers.push (crate::RejectedServer {
guard.push (crate::RejectedServer {
name: watcher_code, name: watcher_code,
tripcode: actual_tripcode, tripcode: actual_tripcode,
seen: now, seen: now,
}); }).await;
while guard.len () > 20 {
guard.remove (0);
}
return trip_error (); return trip_error ();
}, },