use std::any::Any;
use std::cmp::Reverse;
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use crate::model::names::{FeatureName, Name};
use crate::model::options::TypeKey;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Arity {
Single,
OrderedMany,
}
#[derive(Debug, Clone)]
pub struct SlotDecl {
pub name: Name,
pub ty: TypeKey,
pub arity: Arity,
pub owner: FeatureName,
pub docs: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SlotTarget {
ByType(TypeKey),
ByName(Name),
}
impl fmt::Display for SlotTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SlotTarget::ByType(ty) => write!(f, "the service slot of type `{ty}`"),
SlotTarget::ByName(name) => write!(f, "the service slot `{name}`"),
}
}
}
type ErasedService = Arc<dyn Any + Send + Sync>;
type Ranked = (bool, Reverse<Option<usize>>, usize, ErasedService);
pub struct Contribution {
pub owner: FeatureName,
pub target: SlotTarget,
pub value: ErasedService,
pub ty: TypeKey,
pub prepend: bool,
pub peer: bool,
}
impl Contribution {
pub fn new<S: ?Sized + Any + Send + Sync>(
owner: impl Into<FeatureName>,
target: SlotTarget,
imp: Arc<S>,
prepend: bool,
) -> Contribution {
Contribution {
owner: owner.into(),
target,
value: Arc::new(imp),
ty: TypeKey::of::<S>(),
prepend,
peer: false,
}
}
pub fn as_peer(mut self) -> Contribution {
self.peer = true;
self
}
}
impl fmt::Debug for Contribution {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Contribution")
.field("owner", &self.owner)
.field("target", &self.target)
.field("ty", &self.ty)
.field("prepend", &self.prepend)
.field("peer", &self.peer)
.finish()
}
}
#[derive(Debug, Clone)]
pub struct ServiceRequirement {
pub owner: FeatureName,
pub target: SlotTarget,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PeerContribution {
pub owner: FeatureName,
pub slot: Name,
pub ty: TypeKey,
pub resolved: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServiceError {
DuplicateSlot {
slot: Name,
first: FeatureName,
second: FeatureName,
},
UndeclaredSlot {
feature: FeatureName,
target: SlotTarget,
roster: Vec<Name>,
},
AmbiguousSlot {
feature: FeatureName,
ty: TypeKey,
slots: Vec<Name>,
},
TypeMismatch {
feature: FeatureName,
slot: Name,
declared: TypeKey,
contributed: TypeKey,
},
SingleSlotRefilled {
slot: Name,
first: FeatureName,
second: FeatureName,
},
RequiredSlotUnfilled {
slot: Name,
required_by: FeatureName,
},
}
impl fmt::Display for ServiceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ServiceError::DuplicateSlot { slot, first, second } => {
write!(
f,
"service slot `{slot}` must be declared only once, but feature `{first}` \
declares it and feature `{second}` declares it again"
)
}
ServiceError::UndeclaredSlot { feature, target, roster } => write!(
f,
"feature `{feature}` refers to {target}, but no feature declares a service slot \
of that {}; declared service slots: [{}]",
match target {
SlotTarget::ByName(_) => "name",
SlotTarget::ByType(_) => "type",
},
roster.iter().map(|name| name.as_str()).collect::<Vec<_>>().join(", ")
),
ServiceError::AmbiguousSlot { feature, ty, slots } => write!(
f,
"feature `{feature}` must refer to a service slot by name when several slots \
have the type `{ty}` ([{}])",
slots.iter().map(|name| name.as_str()).collect::<Vec<_>>().join(", ")
),
ServiceError::TypeMismatch { feature, slot, declared, contributed } => write!(
f,
"a value contributed to service slot `{slot}` must have the slot's type \
`{declared}`, but feature `{feature}` contributes a `{contributed}`"
),
ServiceError::SingleSlotRefilled { slot, first, second } => write!(
f,
"service slot `{slot}` takes at most one value, but feature `{first}` \
contributes one and feature `{second}` contributes another"
),
ServiceError::RequiredSlotUnfilled { slot, required_by } => {
write!(
f,
"service slot `{slot}` must receive a value, because feature \
`{required_by}` requires it"
)
}
}
}
}
impl std::error::Error for ServiceError {}
#[derive(Default)]
pub struct Services {
slots: BTreeMap<Name, SlotDecl>,
contents: BTreeMap<Name, Vec<ErasedService>>,
ranked: BTreeMap<Name, Vec<ErasedService>>,
by_type: BTreeMap<TypeKey, Vec<Name>>,
peers: Vec<PeerContribution>,
}
impl Services {
pub fn new() -> Services {
Services::default()
}
pub fn slot(&self, name: &str) -> Option<&SlotDecl> {
self.slots.get(name)
}
pub fn slots(&self) -> impl Iterator<Item = &SlotDecl> + '_ {
self.slots.values()
}
pub fn slots_of<S: ?Sized + Any>(&self) -> &[Name] {
self.by_type.get(&TypeKey::of::<S>()).map(Vec::as_slice).unwrap_or(&[])
}
fn contents_of<S: ?Sized + Any + Send + Sync>(
&self,
name: &str,
) -> impl Iterator<Item = &S> + '_ {
self.shared_named::<S>(name).map(|arc| &**arc)
}
pub fn service<S: ?Sized + Any + Send + Sync>(&self) -> Option<&S> {
self.slots_of::<S>().iter().find_map(|name| self.service_named::<S>(name))
}
pub fn services<S: ?Sized + Any + Send + Sync>(&self) -> impl Iterator<Item = &S> + '_ {
self.slots_of::<S>().iter().flat_map(|name| self.contents_of::<S>(name))
}
pub fn service_named<S: ?Sized + Any + Send + Sync>(&self, name: &str) -> Option<&S> {
self.services_by_precedence_named::<S>(name).next()
}
pub fn shared_service_named<S: ?Sized + Any + Send + Sync>(&self, name: &str) -> Option<&Arc<S>> {
self.ranked.get(name).into_iter().flatten().find_map(|value| value.downcast_ref::<Arc<S>>())
}
pub fn services_named<S: ?Sized + Any + Send + Sync>(
&self,
name: &str,
) -> impl Iterator<Item = &S> + '_ {
self.contents_of::<S>(name)
}
pub fn services_by_precedence_named<S: ?Sized + Any + Send + Sync>(
&self,
name: &str,
) -> impl Iterator<Item = &S> + '_ {
self.ranked
.get(name)
.into_iter()
.flatten()
.filter_map(|value| value.downcast_ref::<Arc<S>>())
.map(|arc| &**arc)
}
pub fn shared_named<S: ?Sized + Any + Send + Sync>(
&self,
name: &str,
) -> impl Iterator<Item = &Arc<S>> + '_ {
self.contents
.get(name)
.into_iter()
.flatten()
.filter_map(|value| value.downcast_ref::<Arc<S>>())
}
pub fn count(&self, name: &str) -> usize {
self.contents.get(name).map(Vec::len).unwrap_or(0)
}
pub fn peer_contributions(&self) -> &[PeerContribution] {
&self.peers
}
}
impl fmt::Debug for Services {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.slots.keys().map(|name| (name, self.count(name)))).finish()
}
}
fn resolve_target(
feature: &FeatureName,
target: &SlotTarget,
slots: &BTreeMap<Name, SlotDecl>,
by_type: &BTreeMap<TypeKey, Vec<Name>>,
) -> Result<Name, ServiceError> {
match target {
SlotTarget::ByName(name) => {
if slots.contains_key(name) {
Ok(name.clone())
} else {
Err(ServiceError::UndeclaredSlot {
feature: feature.clone(),
target: target.clone(),
roster: slots.keys().cloned().collect(),
})
}
}
SlotTarget::ByType(ty) => match by_type.get(ty).map(Vec::as_slice) {
Some([name]) => Ok(name.clone()),
Some(names) if names.len() > 1 => Err(ServiceError::AmbiguousSlot {
feature: feature.clone(),
ty: *ty,
slots: names.to_vec(),
}),
_ => Err(ServiceError::UndeclaredSlot {
feature: feature.clone(),
target: target.clone(),
roster: slots.keys().cloned().collect(),
}),
},
}
}
pub fn assemble(
decls: Vec<SlotDecl>,
contributions: Vec<Contribution>,
requirements: Vec<ServiceRequirement>,
features: &[FeatureName],
) -> Result<Services, Vec<ServiceError>> {
let mut errors = Vec::new();
let mut slots: BTreeMap<Name, SlotDecl> = BTreeMap::new();
let mut by_type: BTreeMap<TypeKey, Vec<Name>> = BTreeMap::new();
for decl in decls {
if let Some(existing) = slots.get(&decl.name) {
errors.push(ServiceError::DuplicateSlot {
slot: decl.name.clone(),
first: existing.owner.clone(),
second: decl.owner.clone(),
});
continue;
}
by_type.entry(decl.ty).or_default().push(decl.name.clone());
slots.insert(decl.name.clone(), decl);
}
for names in by_type.values_mut() {
names.sort();
}
let mut prepends: BTreeMap<Name, Vec<ErasedService>> = BTreeMap::new();
let mut appends: BTreeMap<Name, Vec<ErasedService>> = BTreeMap::new();
let mut ranking: BTreeMap<Name, Vec<Ranked>> = BTreeMap::new();
let mut single_filled: BTreeMap<Name, FeatureName> = BTreeMap::new();
let mut peers: Vec<PeerContribution> = Vec::new();
for contribution in contributions {
let name = match resolve_target(&contribution.owner, &contribution.target, &slots, &by_type)
{
Ok(name) => name,
Err(error) => {
match (contribution.peer, &contribution.target, &error) {
(true, SlotTarget::ByName(slot), ServiceError::UndeclaredSlot { .. }) => {
peers.push(PeerContribution {
owner: contribution.owner.clone(),
slot: slot.clone(),
ty: contribution.ty,
resolved: false,
});
}
_ => errors.push(error),
}
continue;
}
};
if contribution.peer {
peers.push(PeerContribution {
owner: contribution.owner.clone(),
slot: name.clone(),
ty: contribution.ty,
resolved: true,
});
}
let decl = &slots[&name];
if decl.ty != contribution.ty {
errors.push(ServiceError::TypeMismatch {
feature: contribution.owner,
slot: name,
declared: decl.ty,
contributed: contribution.ty,
});
continue;
}
if decl.arity == Arity::Single {
if let Some(first) = single_filled.get(&name) {
errors.push(ServiceError::SingleSlotRefilled {
slot: name,
first: first.clone(),
second: contribution.owner,
});
continue;
}
single_filled.insert(name.clone(), contribution.owner.clone());
}
let position = features.iter().position(|feature| *feature == contribution.owner);
let entry = ranking.entry(name.clone()).or_default();
let seq = entry.len();
entry.push((!contribution.prepend, Reverse(position), seq, Arc::clone(&contribution.value)));
let bucket = if contribution.prepend { &mut prepends } else { &mut appends };
bucket.entry(name).or_default().push(contribution.value);
}
let ranked: BTreeMap<Name, Vec<ErasedService>> = ranking
.into_iter()
.map(|(name, mut values)| {
values.sort_by_key(|(group, position, seq, _)| (*group, *position, *seq));
(name, values.into_iter().map(|(_, _, _, value)| value).collect())
})
.collect();
let mut contents: BTreeMap<Name, Vec<ErasedService>> = BTreeMap::new();
for (name, mut values) in prepends {
values.extend(appends.remove(&name).unwrap_or_default());
contents.insert(name, values);
}
contents.extend(appends);
for requirement in requirements {
match resolve_target(&requirement.owner, &requirement.target, &slots, &by_type) {
Ok(name) => {
if contents.get(&name).map(Vec::is_empty).unwrap_or(true) {
errors.push(ServiceError::RequiredSlotUnfilled {
slot: name,
required_by: requirement.owner,
});
}
}
Err(error) => errors.push(error),
}
}
if errors.is_empty() {
Ok(Services { slots, contents, ranked, by_type, peers })
} else {
Err(errors)
}
}
#[cfg(test)]
mod tests {
use super::*;
trait Greeter: Send + Sync {
fn greet(&self) -> &'static str;
}
struct Hello;
impl Greeter for Hello {
fn greet(&self) -> &'static str {
"hello"
}
}
fn slot(name: &str, arity: Arity) -> SlotDecl {
SlotDecl {
name: name.into(),
ty: TypeKey::of::<dyn Greeter>(),
arity,
owner: "a".into(),
docs: String::new(),
}
}
#[test]
fn a_contribution_by_type_lands_in_the_one_slot_of_that_type() {
let services = assemble(
vec![slot("x.greeter", Arity::Single)],
vec![Contribution::new::<dyn Greeter>(
"b",
SlotTarget::ByType(TypeKey::of::<dyn Greeter>()),
Arc::new(Hello),
false,
)],
Vec::new(),
&[],
)
.unwrap();
assert_eq!(services.service::<dyn Greeter>().map(Greeter::greet), Some("hello"));
assert_eq!(
services.service_named::<dyn Greeter>("x.greeter").map(Greeter::greet),
Some("hello")
);
assert!(services.service::<String>().is_none());
}
#[test]
fn a_contribution_by_type_is_ambiguous_when_two_slots_carry_it() {
let errors = assemble(
vec![slot("x.a", Arity::Single), slot("x.b", Arity::Single)],
vec![Contribution::new::<dyn Greeter>(
"b",
SlotTarget::ByType(TypeKey::of::<dyn Greeter>()),
Arc::new(Hello),
false,
)],
Vec::new(),
&[],
)
.unwrap_err();
assert!(
matches!(&errors[0], ServiceError::AmbiguousSlot { slots, .. } if slots.len() == 2)
);
}
#[test]
fn a_required_unfilled_slot_is_an_error() {
let errors = assemble(
vec![slot("x.greeter", Arity::Single)],
Vec::new(),
vec![ServiceRequirement {
owner: "a".into(),
target: SlotTarget::ByName("x.greeter".into()),
}],
&[],
)
.unwrap_err();
assert!(
matches!(
&errors[0],
ServiceError::RequiredSlotUnfilled { slot, .. } if slot == "x.greeter"
)
);
}
#[test]
fn a_read_for_precedence_takes_the_feature_placed_last_first_in_each_group() {
let value = |owner: &str, text: &'static str, prepend: bool| {
Contribution::new::<String>(
owner,
SlotTarget::ByName("x.list".into()),
Arc::new(text.to_string()),
prepend,
)
};
let decl = SlotDecl {
name: "x.list".into(),
ty: TypeKey::of::<String>(),
arity: Arity::OrderedMany,
owner: "a".into(),
docs: String::new(),
};
let services = assemble(
vec![decl],
vec![
value("a", "a1", false),
value("a", "a-first", true),
value("a", "a2", false),
value("b", "b1", false),
value("b", "b-first", true),
value("b", "b2", false),
value("host", "host1", false),
],
Vec::new(),
&["a".into(), "b".into()],
)
.unwrap();
let assembled: Vec<&str> = services.services_named::<String>("x.list").map(String::as_str).collect();
assert_eq!(assembled, ["a-first", "b-first", "a1", "a2", "b1", "b2", "host1"]);
let ranked: Vec<&str> =
services.services_by_precedence_named::<String>("x.list").map(String::as_str).collect();
assert_eq!(ranked, ["b-first", "a-first", "b1", "b2", "a1", "a2", "host1"]);
assert_eq!(services.service_named::<String>("x.list").map(String::as_str), Some("b-first"));
assert_eq!(services.service::<String>().map(String::as_str), Some("b-first"));
}
}