Skip to content

Commit

Permalink
Use BTreeMap for deterministic drop order
Browse files Browse the repository at this point in the history
Because of the use of the static ROUTE_ID counter, the internal
ordering of the HashMap depends on when the routes are added to the
Router. Routes can cause arbitrary code to run when they are dropped,
so this is an unwanted source of non determinism. (Even controlling
the HashMap's RandomState will not help in this case).

A BTreeMap guarantees routes are dropped in the order they were created,
and. I also suspect it will be no slower (and maybe faster) for small
numbers of routes (the common case). This is not performance critical
code in any case.
  • Loading branch information
mystenmark committed Feb 1, 2024
1 parent 1169850 commit 939e6de
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions crates/anemo/src/routing/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
use crate::{Request, Response};
use bytes::Bytes;
use std::{collections::HashMap, convert::Infallible, fmt, sync::Arc};
use std::{
collections::{BTreeMap, HashMap},
convert::Infallible,
fmt,
sync::Arc,
};
use tower::{
util::{BoxCloneService, Oneshot},
Service,
Expand Down Expand Up @@ -30,7 +35,7 @@ impl RouteId {
/// The router type for composing handlers and services.
#[derive(Clone)]
pub struct Router {
routes: HashMap<RouteId, Route>,
routes: BTreeMap<RouteId, Route>,
matcher: RouteMatcher,
fallback: Route,
}
Expand Down

0 comments on commit 939e6de

Please sign in to comment.