Skip to content

Commit

Permalink
review: Move backend construction
Browse files Browse the repository at this point in the history
we use this function in one place, to construct a `Distribute<K>`. we
can move this, defining it as an associated function of `Distribute<K>`,
to reduce non-local reasoning.

Signed-off-by: katelyn martin <[email protected]>
  • Loading branch information
cratelyn committed Nov 4, 2024
1 parent dcd488e commit b64583e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 20 deletions.
21 changes: 2 additions & 19 deletions linkerd/distribute/src/params.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use ahash::AHashSet;
use rand::distributions::WeightedError;
use std::{collections::HashMap, fmt::Debug, hash::Hash, sync::Arc};
use std::{fmt::Debug, hash::Hash, sync::Arc};

use crate::{
keys::{KeyId, UnweightedKeys, WeightedKey},
keys::{UnweightedKeys, WeightedKey},
WeightedKeys,
};

Expand Down Expand Up @@ -88,21 +88,4 @@ impl<K> Distribution<K> {
weighted_keys.validate_weights()?;
Ok(Self::RandomAvailable(Arc::new(weighted_keys)))
}

pub(crate) fn make_svc_from_keys<T>(
&self,
mut make_svc: impl FnMut(&K) -> T,
) -> HashMap<KeyId, T> {
match self {
Distribution::Empty => HashMap::new(),
Distribution::FirstAvailable(keys) => keys
.iter()
.map(|&id| (id, make_svc(keys.get(id))))
.collect(),
Distribution::RandomAvailable(keys) => keys
.iter()
.map(|&id| (id, make_svc(&keys.get(id).key)))
.collect(),
}
}
}
19 changes: 18 additions & 1 deletion linkerd/distribute/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,30 @@ enum Selection<K> {

impl<K: Hash + Eq, S> Distribute<K, S> {
pub(crate) fn new(dist: Distribution<K>, make_svc: impl FnMut(&K) -> S) -> Self {
let backends = dist.make_svc_from_keys(make_svc);
let backends = Self::make_backends(&dist, make_svc);
Self {
backends,
selection: dist.into(),
ready_idx: None,
}
}

fn make_backends(
dist: &Distribution<K>,
mut make_svc: impl FnMut(&K) -> S,
) -> HashMap<KeyId, S> {
match dist {
Distribution::Empty => HashMap::new(),
Distribution::FirstAvailable(keys) => keys
.iter()
.map(|&id| (id, make_svc(keys.get(id))))
.collect(),
Distribution::RandomAvailable(keys) => keys
.iter()
.map(|&id| (id, make_svc(&keys.get(id).key)))
.collect(),
}
}
}

impl<Req, K, S> Service<Req> for Distribute<K, S>
Expand Down

0 comments on commit b64583e

Please sign in to comment.