1 //! inf3r-catalog — every served name on this host.2 //!3 //! The core learns a peer only from the catalogue that the peer prints with4 //! `--describe` (spec section 16.3). This crate turns those catalogues into one5 //! map from a serve name to its capabilities, and answers every request from6 //! that map. The plugin's own `target.toml` and `models/*.toml` are never read.7 //!8 //! The map is built at discovery and then read-only. There is no I/O, no clock,9 //! and no thread here: a name is ambiguous or it is not, and that fact is the10 //! same on every call.11 12 use std::collections::BTreeMap;13 use std::fmt;14 15 use inf3r_proto::body::{Cancel, Capability, Catalogue, Model, Queue, Runtime, Stops};16 17 /// One served name and the capabilities that a request may ask for.18 #[derive(Clone, PartialEq, Eq, Debug)]19 pub struct Entry {20 /// The name from the user. It is the only name that a request carries.21 pub serve: String,22 /// The peer that printed this name. Two peers with one name are an error.23 pub plugin: String,24 /// The capabilities that the name declares, inherited from the source when25 /// the name is an alias.26 pub capabilities: BTreeMap<String, Capability>,27 }28 29 /// The reason a catalogue could not be added to the catalog.30 #[derive(Clone, PartialEq, Eq, Debug)]31 pub enum CatalogError {32 /// Two peers print one serve name, so a request could reach either one.33 AmbiguousModel {34 /// The name that both peers print.35 serve: String,36 /// The peer that printed the name first.37 first: String,38 /// The peer that printed the name again.39 second: String,40 },41 /// An alias names a source that no peer served by the end of discovery.42 UnknownAlias {43 /// The alias that has no source.44 serve: String,45 /// The name that the alias points at.46 source: String,47 },48 /// An alias points at an alias, so the capabilities never reach a model.49 AliasCycle {50 /// The alias whose source is not a model.51 serve: String,52 },53 /// A capability has no vocabulary version, so its output has no contract.54 MissingVocab {55 /// The model that declares the capability.56 serve: String,57 /// The capability without a vocabulary.58 capability: String,59 },60 /// A model serves nothing, so no request can ever be admitted for it.61 EmptyCapabilities {62 /// The model without capabilities.63 serve: String,64 },65 /// One model names one capability twice, so the last one would silently66 /// win. The wire is a map, which keeps the first; a catalogue that repeats a67 /// key is a peer bug.68 DuplicateCapability {69 /// The model that repeats the capability.70 serve: String,71 /// The capability that appears twice.72 capability: String,73 },74 /// A runtime field is empty, so the peer cannot be matched to a version.75 EmptyRuntimeField {76 /// The peer whose catalogue declares the runtime.77 plugin: String,78 /// The field that is empty, `name` or `version`.79 field: &'static str,80 },81 /// A lifecycle fact is a word that the engine does not know, so the core82 /// cannot predict how a cancel, a stop, or a queue behaves on that engine.83 UnknownWord {84 /// The model that declares the capability.85 serve: String,86 /// The capability with the unknown word.87 capability: String,88 /// The fact, such as `cancel`.89 field: &'static str,90 /// The word that the capability declares.91 word: String,92 /// The words that the fact allows.93 allowed: &'static str,94 },95 }96 97 impl fmt::Display for CatalogError {98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {99 match self {100 CatalogError::AmbiguousModel {101 serve,102 first,103 second,104 } => write!(f, "{serve} is served by {first} and {second}"),105 CatalogError::UnknownAlias { serve, source } => {106 write!(f, "alias {serve} names {source}, which no peer serves")107 }108 CatalogError::AliasCycle { serve } => {109 write!(f, "alias {serve} names an alias, not a model")110 }111 CatalogError::MissingVocab { serve, capability } => {112 write!(f, "{serve} has no vocab for {capability}")113 }114 CatalogError::EmptyCapabilities { serve } => {115 write!(f, "{serve} declares no capability")116 }117 CatalogError::DuplicateCapability { serve, capability } => {118 write!(f, "{serve} declares {capability} twice")119 }120 CatalogError::EmptyRuntimeField { plugin, field } => {121 write!(f, "{plugin} declares an empty runtime {field}")122 }123 CatalogError::UnknownWord {124 serve,125 capability,126 field,127 word,128 allowed,129 } => write!(130 f,131 "{serve} declares {field} {word} for {capability}; allowed: {allowed}"132 ),133 }134 }135 }136 137 impl std::error::Error for CatalogError {}138 139 /// Every serve name on this host, keyed by the name from the user.140 #[derive(Clone, PartialEq, Eq, Debug, Default)]141 pub struct Catalog {142 entries: BTreeMap<String, Entry>,143 /// Alias name to the name it renames. An alias is pending while its entry144 /// has no capabilities; `finish` turns a leftover into an error.145 sources: BTreeMap<String, String>,146 }147 148 impl Catalog {149 /// An empty catalog, before discovery adds any peer.150 pub fn new() -> Catalog {151 Catalog::default()152 }153 154 /// Adds every model of one peer's catalogue.155 pub fn add(&mut self, plugin: &str, catalogue: &Catalogue) -> Result<(), CatalogError> {156 check_runtime(plugin, &catalogue.runtime)?;157 for model in &catalogue.models {158 self.insert(plugin, model)?;159 }160 Ok(())161 }162 163 /// Ends discovery. A pending alias that never found its source is an error.164 pub fn finish(&mut self) -> Result<(), CatalogError> {165 let aliases: Vec<(String, String)> = self166 .sources167 .iter()168 .map(|(serve, source)| (serve.clone(), source.clone()))169 .collect();170 for (serve, source) in aliases {171 if self.sources.contains_key(&source) {172 return Err(CatalogError::AliasCycle { serve });173 }174 let Some(capabilities) = self175 .entries176 .get(&source)177 .map(|entry| entry.capabilities.clone())178 else {179 return Err(CatalogError::UnknownAlias { serve, source });180 };181 if let Some(entry) = self.entries.get_mut(&serve) {182 entry.capabilities = capabilities;183 }184 }185 Ok(())186 }187 188 /// Removes every entry of one plugin and returns the names that went.189 ///190 /// A reload keeps its catalog entries; a switch removes them, because the191 /// new child may serve a different set of names. An alias on another plugin192 /// that pointed at one of these names becomes an error at `finish`.193 pub fn remove_plugin(&mut self, plugin: &str) -> Vec<String> {194 let names: Vec<String> = self195 .entries196 .iter()197 .filter(|(_, entry)| entry.plugin == plugin)198 .map(|(name, _)| name.clone())199 .collect();200 for name in &names {201 self.entries.remove(name);202 self.sources.remove(name);203 }204 names205 }206 207 /// Every alias resolves here; an alias is not a second model.208 pub fn get(&self, serve: &str) -> Option<&Entry> {209 self.entries.get(serve)210 }211 212 /// The capability that a request names, when this model declares it.213 /// `None` is what the core turns into `unknown_capability`.214 pub fn capability(&self, serve: &str, capability: &str) -> Option<&Capability> {215 self.entries.get(serve)?.capabilities.get(capability)216 }217 218 /// Every serve name, in sorted order. Two peers cannot print one name, so219 /// the order is stable across restarts.220 pub fn names(&self) -> impl Iterator<Item = &str> {221 self.entries.keys().map(String::as_str)222 }223 224 fn insert(&mut self, plugin: &str, model: &Model) -> Result<(), CatalogError> {225 let serve = model.serve.as_str();226 if let Some(existing) = self.entries.get(serve)227 && existing.plugin != plugin228 {229 return Err(CatalogError::AmbiguousModel {230 serve: serve.to_string(),231 first: existing.plugin.clone(),232 second: plugin.to_string(),233 });234 }235 match &model.alias_of {236 Some(source) => {237 let capabilities = self.alias_capabilities(serve, source)?;238 self.sources.insert(serve.to_string(), source.clone());239 self.entries.insert(240 serve.to_string(),241 Entry {242 serve: serve.to_string(),243 plugin: plugin.to_string(),244 capabilities,245 },246 );247 }248 None => {249 check_capabilities(serve, &model.capabilities)?;250 self.sources.remove(serve);251 self.entries.insert(252 serve.to_string(),253 Entry {254 serve: serve.to_string(),255 plugin: plugin.to_string(),256 capabilities: model.capabilities.clone(),257 },258 );259 self.resolve_pending(serve);260 }261 }262 Ok(())263 }264 265 /// The capabilities that an alias inherits. Empty means pending: the source266 /// has not arrived yet.267 fn alias_capabilities(268 &self,269 serve: &str,270 source: &str,271 ) -> Result<BTreeMap<String, Capability>, CatalogError> {272 if self.sources.contains_key(source) {273 return Err(CatalogError::AliasCycle {274 serve: serve.to_string(),275 });276 }277 match self.entries.get(source) {278 Some(entry) => Ok(entry.capabilities.clone()),279 None => Ok(BTreeMap::new()),280 }281 }282 283 /// Gives every alias that named `source` the capabilities of the model that284 /// just arrived.285 fn resolve_pending(&mut self, source: &str) {286 let Some(capabilities) = self.entries.get(source).map(|e| e.capabilities.clone()) else {287 return;288 };289 for (serve, target) in &self.sources {290 if target == source291 && let Some(entry) = self.entries.get_mut(serve)292 {293 entry.capabilities = capabilities.clone();294 }295 }296 }297 }298 299 /// A runtime that is present must name itself and its version, because an300 /// empty field cannot be compared with the runtime's own report.301 fn check_runtime(plugin: &str, runtime: &Option<Runtime>) -> Result<(), CatalogError> {302 let Some(runtime) = runtime else {303 return Ok(());304 };305 for (field, value) in [("name", &runtime.name), ("version", &runtime.version)] {306 if value.is_empty() {307 return Err(CatalogError::EmptyRuntimeField {308 plugin: plugin.to_string(),309 field,310 });311 }312 }313 Ok(())314 }315 316 /// A real model must declare something and every capability must have a317 /// vocabulary. An alias passes its own empty map and is checked as an alias.318 fn check_capabilities(319 serve: &str,320 capabilities: &BTreeMap<String, Capability>,321 ) -> Result<(), CatalogError> {322 if capabilities.is_empty() {323 return Err(CatalogError::EmptyCapabilities {324 serve: serve.to_string(),325 });326 }327 for (name, capability) in capabilities {328 if capability.vocab.is_empty() {329 return Err(CatalogError::MissingVocab {330 serve: serve.to_string(),331 capability: name.clone(),332 });333 }334 check_word(serve, name, "cancel", &capability.cancel, CANCELS)?;335 check_word(serve, name, "stops", &capability.stops, STOPS)?;336 check_word(serve, name, "queue", &capability.queue, QUEUES)?;337 }338 Ok(())339 }340 341 /// The words that the `cancel` fact allows.342 const CANCELS: &str = "token, frame, request";343 /// The words that the `stops` fact allows.344 const STOPS: &str = "plugin, native, none";345 /// The words that the `queue` fact allows.346 const QUEUES: &str = "none, internal";347 348 /// A lifecycle fact must be a word of its vocabulary. The decoder keeps an349 /// unknown word instead of guessing, so the catalog is the one place that350 /// refuses it and it can name the peer that declared it.351 fn check_word<T>(352 serve: &str,353 capability: &str,354 field: &'static str,355 value: &T,356 allowed: &'static str,357 ) -> Result<(), CatalogError>358 where359 T: Word,360 {361 match value.word() {362 Some(word) => Err(CatalogError::UnknownWord {363 serve: serve.to_string(),364 capability: capability.to_string(),365 field,366 word: word.to_string(),367 allowed,368 }),369 None => Ok(()),370 }371 }372 373 /// The unknown word of a lifecycle fact, when it has one.374 trait Word {375 fn word(&self) -> Option<&str>;376 }377 378 impl Word for Cancel {379 fn word(&self) -> Option<&str> {380 match self {381 Cancel::Unknown(word) => Some(word.as_str()),382 _ => None,383 }384 }385 }386 387 impl Word for Stops {388 fn word(&self) -> Option<&str> {389 match self {390 Stops::Unknown(word) => Some(word.as_str()),391 _ => None,392 }393 }394 }395 396 impl Word for Queue {397 fn word(&self) -> Option<&str> {398 match self {399 Queue::Unknown(word) => Some(word.as_str()),400 _ => None,401 }402 }403 }