use std::any::{Any, TypeId};
use std::collections::BTreeMap;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use serde_json::{Map, Value};
use crate::model::names::{FeatureName, Name, StageName, WorkflowName};
use crate::model::digest::{Fnv1a64, digest_of};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[derive(serde::Serialize, schemars::JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Bind {
Registry,
Document,
Render,
Either,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BindSite {
Document,
Render,
}
impl Bind {
pub fn admits(self, site: BindSite) -> bool {
matches!(
(self, site),
(Bind::Either, _)
| (Bind::Document, BindSite::Document)
| (Bind::Render, BindSite::Render)
)
}
pub fn label(self) -> &'static str {
match self {
Bind::Registry => "registry",
Bind::Document => "document",
Bind::Render => "render",
Bind::Either => "either",
}
}
}
impl fmt::Display for Bind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.label())
}
}
impl fmt::Display for BindSite {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
BindSite::Document => "document",
BindSite::Render => "render request",
})
}
}
pub trait Options: Any + Send + Sync + Default + Hash + fmt::Debug {}
impl<T: Any + Send + Sync + Default + Hash + fmt::Debug> Options for T {}
pub fn short_type_name(name: &'static str) -> &'static str {
let head_end = name.find('<').unwrap_or(name.len());
match name[..head_end].rfind("::") {
Some(pos) => &name[pos + 2..],
None => name,
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TypeKey {
type_name: &'static str,
type_id: TypeId,
}
impl TypeKey {
pub fn of<T: ?Sized + Any>() -> TypeKey {
TypeKey { type_name: std::any::type_name::<T>(), type_id: TypeId::of::<T>() }
}
pub fn type_name(&self) -> &'static str {
self.type_name
}
pub fn short_name(&self) -> &'static str {
short_type_name(self.type_name)
}
pub fn type_id(&self) -> TypeId {
self.type_id
}
pub fn is<T: ?Sized + Any>(&self) -> bool {
self.type_id == TypeId::of::<T>()
}
}
impl fmt::Debug for TypeKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "TypeKey({})", self.short_name())
}
}
impl fmt::Display for TypeKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.short_name())
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum OptionKey {
Type(TypeKey),
Data(Name),
}
impl OptionKey {
pub fn of<T: ?Sized + Any>() -> OptionKey {
OptionKey::Type(TypeKey::of::<T>())
}
pub fn named(name: impl Into<Name>) -> OptionKey {
OptionKey::Data(name.into())
}
pub fn short_name(&self) -> &str {
match self {
OptionKey::Type(key) => key.short_name(),
OptionKey::Data(name) => name.as_str(),
}
}
pub fn type_key(&self) -> Option<&TypeKey> {
match self {
OptionKey::Type(key) => Some(key),
OptionKey::Data(_) => None,
}
}
pub fn is<T: ?Sized + Any>(&self) -> bool {
self.type_key().is_some_and(TypeKey::is::<T>)
}
pub(crate) fn write_digest(&self, hasher: &mut Fnv1a64) {
match self {
OptionKey::Type(key) => hasher.write_str(key.type_name()),
OptionKey::Data(name) => {
hasher.write_str("data:");
hasher.write_str(name.as_str());
}
}
}
}
impl fmt::Debug for OptionKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "OptionKey({})", self.short_name())
}
}
impl fmt::Display for OptionKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.short_name())
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct DataValue(pub Value);
impl Default for DataValue {
fn default() -> DataValue {
DataValue(Value::Object(Map::new()))
}
}
impl Hash for DataValue {
fn hash<H: Hasher>(&self, state: &mut H) {
hash_value(&self.0, state);
}
}
pub fn hash_value<H: Hasher>(value: &Value, state: &mut H) {
match value {
Value::Null => 0u8.hash(state),
Value::Bool(flag) => (1u8, flag).hash(state),
Value::Number(number) if number.is_f64() && number.as_f64() == Some(0.0) => (2u8, "0.0").hash(state),
Value::Number(number) => (2u8, number.to_string()).hash(state),
Value::String(text) => (3u8, text).hash(state),
Value::Array(items) => {
(4u8, items.len()).hash(state);
for item in items {
hash_value(item, state);
}
}
Value::Object(map) => {
5u8.hash(state);
let mut entries: Vec<(&String, &Value)> = map.iter().collect();
entries.sort_by(|a, b| a.0.cmp(b.0));
entries.len().hash(state);
for (key, value) in entries {
key.hash(state);
hash_value(value, state);
}
}
}
}
type ErasedValue = Arc<dyn Any + Send + Sync>;
fn default_erased<T: Options>() -> ErasedValue {
Arc::new(T::default())
}
fn digest_erased<T: Options>(value: &(dyn Any + Send + Sync)) -> u64 {
digest_of(value.downcast_ref::<T>().expect("an option value is digested through its own type"))
}
#[derive(Clone)]
pub struct OptionRef {
key: OptionKey,
make_default: fn() -> ErasedValue,
digest: fn(&(dyn Any + Send + Sync)) -> u64,
}
impl OptionRef {
pub fn of<T: Options>() -> OptionRef {
OptionRef {
key: OptionKey::of::<T>(),
make_default: default_erased::<T>,
digest: digest_erased::<T>,
}
}
pub fn named(name: impl Into<Name>) -> OptionRef {
OptionRef {
key: OptionKey::named(name),
make_default: default_erased::<DataValue>,
digest: digest_erased::<DataValue>,
}
}
pub fn key(&self) -> &OptionKey {
&self.key
}
pub fn make_default(&self) -> ErasedValue {
(self.make_default)()
}
pub fn digest(&self, value: &(dyn Any + Send + Sync)) -> u64 {
(self.digest)(value)
}
}
impl PartialEq for OptionRef {
fn eq(&self, other: &OptionRef) -> bool {
self.key == other.key
}
}
impl Eq for OptionRef {}
impl PartialOrd for OptionRef {
fn partial_cmp(&self, other: &OptionRef) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for OptionRef {
fn cmp(&self, other: &OptionRef) -> std::cmp::Ordering {
self.key.cmp(&other.key)
}
}
impl serde::Serialize for OptionRef {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.key.short_name())
}
}
impl schemars::JsonSchema for OptionRef {
fn schema_name() -> std::borrow::Cow<'static, str> {
"String".into()
}
fn inline_schema() -> bool {
true
}
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
String::json_schema(generator)
}
}
fn serialize_key_name<S: serde::Serializer>(key: &OptionKey, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(key.short_name())
}
impl fmt::Debug for OptionRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "OptionRef({})", self.key.short_name())
}
}
#[derive(Debug, Clone)]
#[derive(serde::Serialize, schemars::JsonSchema)]
pub struct OptionDecl {
#[serde(serialize_with = "serialize_key_name")]
#[schemars(with = "String")]
pub key: OptionKey,
pub bind: Bind,
pub owner: FeatureName,
pub docs: String,
}
impl OptionDecl {
pub fn of<T: Options>(owner: impl Into<FeatureName>, bind: Bind) -> OptionDecl {
OptionDecl { key: OptionKey::of::<T>(), bind, owner: owner.into(), docs: String::new() }
}
pub fn named(name: impl Into<Name>, owner: impl Into<FeatureName>, bind: Bind) -> OptionDecl {
OptionDecl { key: OptionKey::named(name), bind, owner: owner.into(), docs: String::new() }
}
pub fn docs(mut self, docs: impl Into<String>) -> OptionDecl {
self.docs = crate::kept_docs(docs);
self
}
}
#[derive(Clone)]
struct OptionValue {
value: ErasedValue,
digest: u64,
}
#[derive(Clone, Default)]
pub struct OptionValues {
entries: BTreeMap<OptionKey, OptionValue>,
}
impl OptionValues {
pub fn new() -> OptionValues {
OptionValues::default()
}
pub fn set<T: Options>(&mut self, value: T) {
let digest = digest_of(&value);
self.entries.insert(OptionKey::of::<T>(), OptionValue { value: Arc::new(value), digest });
}
pub fn with<T: Options>(mut self, value: T) -> OptionValues {
self.set(value);
self
}
pub fn get<T: Options>(&self) -> Option<&T> {
self.entries.get(&OptionKey::of::<T>()).and_then(|entry| entry.value.downcast_ref::<T>())
}
pub fn set_named(&mut self, name: impl Into<Name>, value: Value) {
let value = DataValue(value);
let digest = digest_of(&value);
self.entries.insert(OptionKey::named(name), OptionValue { value: Arc::new(value), digest });
}
pub fn get_named(&self, name: &str) -> Option<&Value> {
self.entries
.get(&OptionKey::named(name))
.and_then(|entry| entry.value.downcast_ref::<DataValue>())
.map(|value| &value.0)
}
pub fn get_erased(&self, key: &OptionKey) -> Option<&ErasedValue> {
self.entries.get(key).map(|entry| &entry.value)
}
pub fn merge_from(&mut self, other: &OptionValues) {
for (key, entry) in &other.entries {
self.entries.insert(key.clone(), entry.clone());
}
}
pub fn keys(&self) -> impl Iterator<Item = OptionKey> + '_ {
self.entries.keys().cloned()
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn digest(&self) -> u64 {
let mut hasher = Fnv1a64::new();
for (key, entry) in &self.entries {
key.write_digest(&mut hasher);
hasher.write_u64(entry.digest);
}
hasher.value()
}
}
impl fmt::Debug for OptionValues {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.entries.keys()).finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OptionError {
UndeclaredRead {
stage: StageName,
option: String,
declared: Vec<String>,
},
UnknownOption {
site: BindSite,
option: String,
roster: Vec<String>,
workflow: Option<WorkflowName>,
},
BindingRefused {
site: BindSite,
option: String,
declared: Bind,
owner: FeatureName,
workflow: Option<WorkflowName>,
},
RegistryBoundRead {
stage: StageName,
option: String,
owner: FeatureName,
},
}
impl fmt::Display for OptionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
OptionError::UndeclaredRead { stage, option, declared } => write!(
f,
"stage `{stage}` must declare each option type it reads, but it reads \
`{option}` without declaring it; it declares: [{}]",
declared.join(", ")
),
OptionError::UnknownOption { site, option, roster, workflow } => write!(
f,
"{} for the option type `{option}`, but no feature declares that option type; \
declared option types: [{}]",
value_set(*site, workflow),
roster.join(", ")
),
OptionError::BindingRefused { site, option, declared, owner, workflow } => write!(
f,
"{} for the option type `{option}` of feature `{owner}`, but feature `{owner}` \
declares that values of this option type may be set only {}",
value_set(*site, workflow),
match declared {
Bind::Registry => {
format!("in the configuration of feature `{owner}`, when the registry is built")
}
Bind::Document => "on the document".to_string(),
Bind::Render => "on the render request".to_string(),
Bind::Either => "on the document or on the render request".to_string(),
}
),
OptionError::RegistryBoundRead { stage, option, owner } => write!(
f,
"stage `{stage}` declares a read of the option type `{option}` of feature \
`{owner}`, but feature `{owner}` fixes the value of that option type when the \
registry is built, so no stage can read it"
),
}
}
}
impl std::error::Error for OptionError {}
fn value_set(site: BindSite, workflow: &Option<WorkflowName>) -> String {
match workflow {
Some(workflow) => format!("a value is set on the {site} of workflow `{workflow}`"),
None => format!("a value is set on the {site}"),
}
}
pub fn validate_values<'d>(
values: &OptionValues,
site: BindSite,
lookup: impl Fn(&OptionKey) -> Option<&'d OptionDecl>,
roster: &[OptionKey],
workflow: Option<&WorkflowName>,
) -> Vec<OptionError> {
let mut errors = Vec::new();
for key in values.keys() {
match lookup(&key) {
None => errors.push(OptionError::UnknownOption {
site,
option: key.short_name().to_string(),
roster: roster.iter().map(|key| key.short_name().to_string()).collect(),
workflow: workflow.cloned(),
}),
Some(decl) if !decl.bind.admits(site) => errors.push(OptionError::BindingRefused {
site,
option: key.short_name().to_string(),
declared: decl.bind,
owner: decl.owner.clone(),
workflow: workflow.cloned(),
}),
Some(_) => {}
}
}
errors
}
#[derive(Clone)]
pub struct ResolvedOptions {
stage: StageName,
entries: BTreeMap<OptionKey, (ErasedValue, u64)>,
}
impl ResolvedOptions {
pub fn resolve(
stage: StageName,
reads: &[OptionRef],
render: &OptionValues,
document: &OptionValues,
) -> ResolvedOptions {
let mut entries = BTreeMap::new();
for read in reads {
let key = read.key().clone();
let (value, digest) =
match render.entries.get(&key).or_else(|| document.entries.get(&key)) {
Some(entry) => (Arc::clone(&entry.value), entry.digest),
None => {
let value = read.make_default();
let digest = read.digest(value.as_ref());
(value, digest)
}
};
entries.insert(key, (value, digest));
}
ResolvedOptions { stage, entries }
}
pub fn get<T: Options>(&self) -> Result<&T, OptionError> {
let key = OptionKey::of::<T>();
match self.entries.get(&key) {
Some((value, _)) => Ok(value
.downcast_ref::<T>()
.expect("a resolved option is stored under its own type")),
None => Err(self.undeclared(key.short_name())),
}
}
pub fn get_named(&self, name: &str) -> Result<&Value, OptionError> {
match self.entries.get(&OptionKey::named(name)) {
Some((value, _)) => Ok(&value
.downcast_ref::<DataValue>()
.expect("an option declared from data is stored as a `DataValue`")
.0),
None => Err(self.undeclared(name)),
}
}
fn undeclared(&self, option: &str) -> OptionError {
OptionError::UndeclaredRead {
stage: self.stage.clone(),
option: option.to_string(),
declared: self.entries.keys().map(|key| key.short_name().to_string()).collect(),
}
}
pub fn keys(&self) -> impl Iterator<Item = OptionKey> + '_ {
self.entries.keys().cloned()
}
pub fn get_erased(&self, key: &OptionKey) -> Option<&(dyn Any + Send + Sync)> {
self.entries.get(key).map(|(value, _)| &**value)
}
pub fn digest(&self) -> u64 {
let mut hasher = Fnv1a64::new();
for (key, (_, digest)) in &self.entries {
key.write_digest(&mut hasher);
hasher.write_u64(*digest);
}
hasher.value()
}
}
impl fmt::Debug for ResolvedOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ResolvedOptions")
.field("stage", &self.stage)
.field("options", &self.entries.keys().collect::<Vec<_>>())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, Default, Hash, PartialEq, Eq)]
struct Width(u32);
#[derive(Debug, Default, Hash)]
struct Depth(u32);
#[test]
fn a_binding_admits_its_own_site_and_either_admits_both() {
assert!(Bind::Document.admits(BindSite::Document));
assert!(!Bind::Document.admits(BindSite::Render));
assert!(Bind::Render.admits(BindSite::Render));
assert!(!Bind::Render.admits(BindSite::Document));
assert!(Bind::Either.admits(BindSite::Document));
assert!(Bind::Either.admits(BindSite::Render));
assert!(!Bind::Registry.admits(BindSite::Document));
}
#[test]
fn resolution_takes_render_over_document_over_default() {
let reads = [OptionRef::of::<Width>(), OptionRef::of::<Depth>()];
let render = OptionValues::new().with(Width(120));
let document = OptionValues::new().with(Width(100)).with(Depth(5));
let resolved = ResolvedOptions::resolve("s".into(), &reads, &render, &document);
assert_eq!(resolved.get::<Width>().unwrap(), &Width(120));
assert_eq!(resolved.get::<Depth>().unwrap().0, 5);
let none = ResolvedOptions::resolve(
"s".into(),
&reads,
&OptionValues::new(),
&OptionValues::new(),
);
assert_eq!(none.get::<Width>().unwrap(), &Width(0));
}
#[test]
fn an_undeclared_read_is_a_typed_error() {
let resolved =
ResolvedOptions::resolve("s".into(), &[], &OptionValues::new(), &OptionValues::new());
let error = resolved.get::<Width>().unwrap_err();
assert!(matches!(error, OptionError::UndeclaredRead { ref option, .. } if option == "Width"));
}
#[test]
fn values_at_a_refused_site_are_reported() {
let decl = OptionDecl::of::<Width>("f", Bind::Render);
let values = OptionValues::new().with(Width(1)).with(Depth(2));
let errors = validate_values(
&values,
BindSite::Document,
|key| if key.is::<Width>() { Some(&decl) } else { None },
&[OptionKey::of::<Width>()],
None,
);
assert_eq!(errors.len(), 2);
assert!(matches!(errors[0], OptionError::UnknownOption { ref option, .. } if option == "Depth"));
assert!(matches!(errors[1], OptionError::BindingRefused { ref option, .. } if option == "Width"));
}
#[test]
fn the_values_digest_depends_on_the_values() {
let a = OptionValues::new().with(Width(1));
let b = OptionValues::new().with(Width(2));
assert_ne!(a.digest(), b.digest());
assert_eq!(a.digest(), OptionValues::new().with(Width(1)).digest());
}
fn hash_of(value: &DataValue) -> u64 {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
value.hash(&mut hasher);
hasher.finish()
}
#[test]
fn equal_data_values_hash_equal_whatever_the_order_of_their_entries() {
let one = DataValue(serde_json::json!({ "a": 1, "b": { "x": [1, 2], "y": "t" } }));
let two = DataValue(serde_json::json!({ "b": { "y": "t", "x": [1, 2] }, "a": 1 }));
assert_eq!(one, two);
assert_eq!(hash_of(&one), hash_of(&two));
assert_eq!(digest_of(&one), digest_of(&two));
let other = DataValue(serde_json::json!({ "a": 2, "b": { "x": [1, 2], "y": "t" } }));
assert_ne!(hash_of(&one), hash_of(&other));
assert_eq!(DataValue::default(), DataValue(serde_json::json!({})));
let (negative, zero) = (DataValue(serde_json::json!(-0.0)), DataValue(serde_json::json!(0.0)));
assert_eq!(negative, zero);
assert_eq!(hash_of(&negative), hash_of(&zero));
}
#[test]
fn a_type_key_and_a_data_key_never_compare_equal() {
let full = std::any::type_name::<Width>();
assert_ne!(OptionKey::of::<Width>(), OptionKey::named(full));
assert_ne!(OptionKey::of::<Width>(), OptionKey::named("Width"));
assert_eq!(OptionKey::named("w.display"), OptionKey::named("w.display"));
assert!(OptionKey::of::<Width>() < OptionKey::named("a"));
assert!(OptionKey::of::<Width>().is::<Width>());
assert!(!OptionKey::named("Width").is::<Width>());
assert_eq!(OptionKey::named("w.display").short_name(), "w.display");
let values = OptionValues::new().with(Width(1));
let mut named = values.clone();
named.set_named("Width", serde_json::json!({ "w": 1 }));
assert_eq!(named.len(), 2);
assert_eq!(named.get::<Width>(), Some(&Width(1)));
assert_eq!(named.get_named("Width"), Some(&serde_json::json!({ "w": 1 })));
assert_ne!(values.digest(), named.digest());
}
#[test]
fn a_data_read_resolves_to_the_value_set_or_the_empty_map() {
let reads = [OptionRef::named("w.display"), OptionRef::named("w.other")];
let mut document = OptionValues::new();
document.set_named("w.display", serde_json::json!({ "size": 3 }));
let resolved = ResolvedOptions::resolve("s".into(), &reads, &OptionValues::new(), &document);
assert_eq!(resolved.get_named("w.display").unwrap(), &serde_json::json!({ "size": 3 }));
assert_eq!(resolved.get_named("w.other").unwrap(), &serde_json::json!({}));
let error = resolved.get_named("w.none").unwrap_err();
assert_eq!(
error.to_string(),
"stage `s` must declare each option type it reads, but it reads `w.none` without \
declaring it; it declares: [w.display, w.other]"
);
}
}