From ba1a5ae85f6622541b7e2192affa1b684f1999b3 Mon Sep 17 00:00:00 2001 From: Johan Peltenburg Date: Fri, 24 Jul 2026 09:03:18 +0200 Subject: [PATCH 01/12] feat(schema): add paths for schema types Signed-off-by: Johan Peltenburg --- crates/schema/Cargo.toml | 2 +- crates/schema/src/builder/entity.rs | 23 ++- crates/schema/src/builder/mod.rs | 39 ++++- crates/schema/src/builder/record.rs | 23 ++- crates/schema/src/lib.rs | 16 +- crates/schema/src/schema/data_type.rs | 5 +- crates/schema/src/schema/entity.rs | 15 +- crates/schema/src/schema/mod.rs | 25 ++-- crates/schema/src/schema/path.rs | 206 ++++++++++++++++++++++++++ crates/schema/src/schema/record.rs | 15 +- crates/schema/src/test_utils.rs | 32 +++- crates/schema/src/visitor.rs | 16 +- 12 files changed, 346 insertions(+), 71 deletions(-) create mode 100644 crates/schema/src/schema/path.rs diff --git a/crates/schema/Cargo.toml b/crates/schema/Cargo.toml index 7fb914962..79dc74138 100644 --- a/crates/schema/Cargo.toml +++ b/crates/schema/Cargo.toml @@ -17,7 +17,7 @@ rustc-hash = { workspace = true } serde = { workspace = true, optional = true } smallvec = { workspace = true, optional = true } thiserror = { workspace = true } -ts-rs = { workspace = true, optional = true, features = ["indexmap-impl"] } +ts-rs = { workspace = true, optional = true, features = ["format", "indexmap-impl"] } [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/schema/src/builder/entity.rs b/crates/schema/src/builder/entity.rs index b2405084c..a815a0507 100644 --- a/crates/schema/src/builder/entity.rs +++ b/crates/schema/src/builder/entity.rs @@ -2,35 +2,32 @@ // SPDX-License-Identifier: Apache-2.0 use crate::builder::{AnnotationsBuilder, BuilderError, collect_unique}; -use crate::schema::identifier::IdentifierError; -use crate::{Annotations, Entity, Event, Identifier}; +use crate::{Annotations, Entity, Event, Path, PathError}; /// Builder for an [`Entity`]. pub struct EntityBuilder { - name: Identifier, + path: Path, events: Vec, annotations: AnnotationsBuilder, } impl EntityBuilder { /// Start an entity named `name`. - pub fn new(name: Identifier) -> Self { + pub fn new(path: impl Into) -> Self { Self { - name, + path: path.into(), events: Vec::new(), annotations: AnnotationsBuilder::new(), } } - /// Start an entity named `name`, validating `name` as an [`Identifier`]. + /// Start an entity at `path`, validating its segments. /// /// # Errors /// - /// Errors if `name` is not a valid identifier. - pub fn try_new( - name: impl TryInto, - ) -> Result { - Ok(Self::new(name.try_into()?)) + /// Errors if `path` is not a valid path. + pub fn try_new(path: impl AsRef) -> Result { + Ok(Self::new(path.as_ref().parse::()?)) } /// Add an event, returning the builder for chaining. @@ -60,7 +57,7 @@ impl EntityBuilder { /// the annotations are invalid. pub fn build(self) -> Result { let Self { - name, + path, events, annotations, } = self; @@ -69,7 +66,7 @@ impl EntityBuilder { } let events = collect_unique(events, |event| event.name().clone())?; let annotations = annotations.build()?; - Ok(Entity::from_parts(name, events, annotations)) + Ok(Entity::from_parts(path, events, annotations)) } } diff --git a/crates/schema/src/builder/mod.rs b/crates/schema/src/builder/mod.rs index 91e9faa6e..aa42ecbb8 100644 --- a/crates/schema/src/builder/mod.rs +++ b/crates/schema/src/builder/mod.rs @@ -127,9 +127,44 @@ impl SchemaBuilder { records, annotations, } = self; - let entities = collect_unique(entities, |entity| entity.name().clone())?; - let records = collect_unique(records, |record| record.name().clone())?; + let entities = collect_unique(entities, |entity| entity.path().clone())?; + let records = collect_unique(records, |record| record.path().clone())?; + if let Some(path) = entities.keys().find(|path| records.contains_key(*path)) { + return Err(BuilderError::DuplicateName(path.to_string())); + } let annotations = annotations.build()?; Ok(Schema::from_parts(name, entities, records, annotations)) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::{entity, event, path, record}; + + #[test] + fn qualified_type_paths_coexist() { + let schema = SchemaBuilder::try_new("Schema") + .unwrap() + .with_entity(entity("Foo::Q", [event("event", [])])) + .with_entity(entity("Bar::Q", [event("event", [])])) + .build() + .unwrap(); + + assert!(schema.entity(&path("Foo::Q")).is_some()); + assert!(schema.entity(&path("Bar::Q")).is_some()); + } + + #[test] + fn record_and_entity_cannot_share_a_path() { + let result = SchemaBuilder::try_new("Schema") + .unwrap() + .with_entity(entity("Foo::Q", [event("event", [])])) + .with_record(record("Foo::Q", [])) + .build(); + let Err(error) = result else { + panic!("expected a duplicate path error"); + }; + assert_eq!(error, BuilderError::DuplicateName("Foo::Q".to_string())); + } +} diff --git a/crates/schema/src/builder/record.rs b/crates/schema/src/builder/record.rs index 8e1570e3f..81f113f43 100644 --- a/crates/schema/src/builder/record.rs +++ b/crates/schema/src/builder/record.rs @@ -2,35 +2,32 @@ // SPDX-License-Identifier: Apache-2.0 use crate::builder::{AnnotationsBuilder, BuilderError, collect_unique}; -use crate::schema::identifier::IdentifierError; -use crate::{Annotations, Field, Identifier, Record}; +use crate::{Annotations, Field, Path, PathError, Record}; /// Builder for a [`Record`]. pub struct RecordBuilder { - name: Identifier, + path: Path, fields: Vec, annotations: AnnotationsBuilder, } impl RecordBuilder { /// Start a record named `name`. - pub fn new(name: Identifier) -> Self { + pub fn new(path: impl Into) -> Self { Self { - name, + path: path.into(), fields: Vec::new(), annotations: AnnotationsBuilder::new(), } } - /// Start a record named `name`, validating `name` as an [`Identifier`]. + /// Start a record at `path`, validating its segments. /// /// # Errors /// - /// Errors if `name` is not a valid identifier. - pub fn try_new( - name: impl TryInto, - ) -> Result { - Ok(Self::new(name.try_into()?)) + /// Errors if `path` is not a valid path. + pub fn try_new(path: impl AsRef) -> Result { + Ok(Self::new(path.as_ref().parse::()?)) } /// Add a field, returning the builder for chaining. @@ -59,12 +56,12 @@ impl RecordBuilder { /// Errors if a field name is repeated or the annotations are invalid. pub fn build(self) -> Result { let Self { - name, + path, fields, annotations, } = self; let fields = collect_unique(fields, |field| field.name().clone())?; let annotations = annotations.build()?; - Ok(Record::from_parts(name, fields, annotations)) + Ok(Record::from_parts(path, fields, annotations)) } } diff --git a/crates/schema/src/lib.rs b/crates/schema/src/lib.rs index 5b9f84247..8dcda6c2b 100644 --- a/crates/schema/src/lib.rs +++ b/crates/schema/src/lib.rs @@ -11,7 +11,8 @@ //! //! The schema core concepts are: //! -//! - [`Identifier`]: defines the name of things +//! - [`Identifier`]: defines the name of schema-local elements +//! - [`Path`]: identifies record and entity types //! - [`DataType`]: defines common data types (bool, integer, string, etc.) //! plus Quent-specific types, such as: //! - [`DataType::EntityRef`] @@ -89,8 +90,17 @@ //! serializing schemas, this crate has a `serde` feature. pub use schema::{ - Schema, annotations::Annotations, constraint::Constraint, data_type::DataType, entity::Entity, - event::Cardinality, event::Event, field::Field, identifier::Identifier, metadata::Metadata, + Schema, + annotations::Annotations, + constraint::Constraint, + data_type::DataType, + entity::Entity, + event::Cardinality, + event::Event, + field::Field, + identifier::Identifier, + metadata::Metadata, + path::{Path, PathError}, record::Record, }; diff --git a/crates/schema/src/schema/data_type.rs b/crates/schema/src/schema/data_type.rs index e0f41b5d3..a357088f3 100644 --- a/crates/schema/src/schema/data_type.rs +++ b/crates/schema/src/schema/data_type.rs @@ -1,7 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use crate::schema::{annotations::Annotations, identifier::Identifier}; +use crate::Path; +use crate::schema::annotations::Annotations; /// Types of data values in [`crate::event::Event`]s and [`crate::record::Record`]s. #[derive(Clone, Debug, PartialEq, Eq)] @@ -28,7 +29,7 @@ pub enum DataType { /// The top-level [`crate::Schema::records`] field must contain a /// [`crate::record::Record`] with this name, otherwise the /// [`crate::Schema`] is ill-formed. - Record(Identifier), + Record(Path), /// A record whose fields are determined by the instrumentation client at /// run-time. DynamicRecord, diff --git a/crates/schema/src/schema/entity.rs b/crates/schema/src/schema/entity.rs index f5b49c802..ca171734b 100644 --- a/crates/schema/src/schema/entity.rs +++ b/crates/schema/src/schema/entity.rs @@ -1,14 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +use crate::Path; use crate::schema::{Map, annotations::Annotations, event::Event, identifier::Identifier}; #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct Entity { - /// The name of the entity. - name: Identifier, + /// The path of the entity. + path: Path, /// The events that this entity can emit. #[cfg_attr(feature = "ts", ts(as = "indexmap::IndexMap"))] events: Map, @@ -18,20 +19,20 @@ pub struct Entity { impl Entity { pub(crate) fn from_parts( - name: Identifier, + path: Path, events: Map, annotations: Annotations, ) -> Self { Self { - name, + path, events, annotations, } } - /// The name of the entity. - pub fn name(&self) -> &Identifier { - &self.name + /// The path of the entity. + pub fn path(&self) -> &Path { + &self.path } /// The annotations of this entity. diff --git a/crates/schema/src/schema/mod.rs b/crates/schema/src/schema/mod.rs index 0d2611863..2da1c7876 100644 --- a/crates/schema/src/schema/mod.rs +++ b/crates/schema/src/schema/mod.rs @@ -3,6 +3,7 @@ //! Plain schema data types +use crate::Path; use crate::schema::{ annotations::Annotations, entity::Entity, identifier::Identifier, record::Record, }; @@ -15,6 +16,7 @@ pub mod event; pub mod field; pub mod identifier; pub mod metadata; +pub mod path; pub mod record; /// Container type for named elements. @@ -27,12 +29,13 @@ pub struct Schema { /// The name of the model. name: Identifier, /// The [`Entity`]s of the model. - // The FxBuildHasher has no ts_rs::TS impl, hence these attributes: - #[cfg_attr(feature = "ts", ts(as = "indexmap::IndexMap"))] - entities: Map, + #[cfg_attr(feature = "serde", serde(with = "indexmap::map::serde_seq"))] + #[cfg_attr(feature = "ts", ts(as = "Vec<(Path, Entity)>"))] + entities: Map, /// The [`Record`]s of the model. - #[cfg_attr(feature = "ts", ts(as = "indexmap::IndexMap"))] - records: Map, + #[cfg_attr(feature = "serde", serde(with = "indexmap::map::serde_seq"))] + #[cfg_attr(feature = "ts", ts(as = "Vec<(Path, Record)>"))] + records: Map, /// Annotations of this schema. annotations: Annotations, } @@ -40,8 +43,8 @@ pub struct Schema { impl Schema { pub(crate) fn from_parts( name: Identifier, - entities: Map, - records: Map, + entities: Map, + records: Map, annotations: Annotations, ) -> Self { Self { @@ -63,8 +66,8 @@ impl Schema { } /// The entity declared under `name`, if any. - pub fn entity(&self, name: &Identifier) -> Option<&Entity> { - self.entities.get(name) + pub fn entity(&self, path: &Path) -> Option<&Entity> { + self.entities.get(path) } /// The declared entities, in declaration order. @@ -73,8 +76,8 @@ impl Schema { } /// The record declared under `name`, if any. - pub fn record(&self, name: &Identifier) -> Option<&Record> { - self.records.get(name) + pub fn record(&self, path: &Path) -> Option<&Record> { + self.records.get(path) } /// The declared records, in declaration order. diff --git a/crates/schema/src/schema/path.rs b/crates/schema/src/schema/path.rs new file mode 100644 index 000000000..29c722e6a --- /dev/null +++ b/crates/schema/src/schema/path.rs @@ -0,0 +1,206 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::fmt::{Display, Formatter}; +use std::str::FromStr; + +use thiserror::Error; + +use crate::Identifier; + +/// A nonempty absolute path of identifier segments. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(try_from = "Vec"))] +pub struct Path(Vec); + +#[cfg(feature = "ts")] +impl ts_rs::TS for Path { + type WithoutGenerics = Self; + type OptionInnerType = Self; + + fn name(_: &ts_rs::Config) -> String { + "Path".to_owned() + } + + fn inline(config: &ts_rs::Config) -> String { + format!("Array<{}>", Identifier::inline(config)) + } + + fn decl(config: &ts_rs::Config) -> String { + format!("type Path = {};", Self::inline(config)) + } + + fn output_path() -> Option { + Some("Path.ts".into()) + } +} + +/// Reason a path failed validation. +#[derive(Debug, Clone, PartialEq, Eq, Error)] +pub enum PathError { + /// No segments were provided. + #[error("path must contain at least one segment")] + Empty, + /// A string contained an invalid segment. + #[error("invalid path segment {index}: {source}")] + InvalidSegment { + index: usize, + #[source] + source: crate::schema::identifier::IdentifierError, + }, +} + +impl Path { + /// Returns all path segments. + pub fn segments(&self) -> &[Identifier] { + &self.0 + } + + /// Returns the segments preceding the path name. + pub fn namespace(&self) -> &[Identifier] { + &self.0[..self.0.len() - 1] + } + + /// Returns the final path segment. + pub fn name(&self) -> &Identifier { + self.0.last().expect("Path guarantees at least one segment") + } + + /// Returns this path with its final segment replaced. + pub fn with_name(&self, name: Identifier) -> Self { + let mut segments = self.0.clone(); + *segments + .last_mut() + .expect("Path guarantees at least one segment") = name; + Self(segments) + } +} + +impl From for Path { + fn from(identifier: Identifier) -> Self { + Self(vec![identifier]) + } +} + +impl TryFrom> for Path { + type Error = PathError; + + fn try_from(segments: Vec) -> Result { + if segments.is_empty() { + return Err(PathError::Empty); + } + Ok(Self(segments)) + } +} + +impl FromStr for Path { + type Err = PathError; + + fn from_str(value: &str) -> Result { + if value.is_empty() { + return Err(PathError::Empty); + } + value + .split("::") + .enumerate() + .map(|(index, segment)| { + Identifier::try_new(segment) + .map_err(|source| PathError::InvalidSegment { index, source }) + }) + .collect::, _>>()? + .try_into() + } +} + +impl Display for Path { + fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result { + let mut segments = self.0.iter(); + formatter.write_str( + segments + .next() + .expect("Path guarantees at least one segment"), + )?; + for segment in segments { + write!(formatter, "::{segment}")?; + } + Ok(()) + } +} + +impl PartialEq for Path { + fn eq(&self, other: &str) -> bool { + let mut other_segments = other.split("::"); + self.0 + .iter() + .all(|segment| other_segments.next().is_some_and(|other| segment == other)) + && other_segments.next().is_none() + } +} + +impl PartialEq<&str> for Path { + fn eq(&self, other: &&str) -> bool { + self == *other + } +} + +impl<'a> IntoIterator for &'a Path { + type Item = &'a Identifier; + type IntoIter = std::slice::Iter<'a, Identifier>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + +impl IntoIterator for Path { + type Item = Identifier; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::ident; + + #[test] + fn constructs_and_inspects_paths() { + let path = Path::try_from(vec![ident("Foo"), ident("Query")]).unwrap(); + + assert_eq!(path.segments(), &[ident("Foo"), ident("Query")]); + assert_eq!(path.namespace(), &[ident("Foo")]); + assert_eq!(path.name(), "Query"); + assert_eq!(path.with_name(ident("Result")).to_string(), "Foo::Result"); + assert_eq!( + path.into_iter() + .map(|segment| segment.to_string()) + .collect::>(), + ["Foo", "Query"] + ); + } + + #[test] + fn parses_and_formats_paths() { + let path: Path = "Foo::Query".parse().unwrap(); + assert_eq!(path.to_string(), "Foo::Query"); + assert_eq!(Path::from(ident("Query")).to_string(), "Query"); + } + + #[test] + fn rejects_empty_and_invalid_paths() { + assert_eq!(Path::try_from(Vec::new()), Err(PathError::Empty)); + assert_eq!("".parse::(), Err(PathError::Empty)); + assert!(matches!( + "Foo::".parse::(), + Err(PathError::InvalidSegment { index: 1, .. }) + )); + assert!(matches!( + "Foo::bad-name".parse::(), + Err(PathError::InvalidSegment { index: 1, .. }) + )); + } +} diff --git a/crates/schema/src/schema/record.rs b/crates/schema/src/schema/record.rs index 7d35eb72b..fb6d97a4d 100644 --- a/crates/schema/src/schema/record.rs +++ b/crates/schema/src/schema/record.rs @@ -1,14 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +use crate::Path; use crate::schema::{Map, annotations::Annotations, field::Field, identifier::Identifier}; #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct Record { - /// The name of the record. - name: Identifier, + /// The path of the record. + path: Path, /// The fields of the record. #[cfg_attr(feature = "ts", ts(as = "indexmap::IndexMap"))] fields: Map, @@ -18,20 +19,20 @@ pub struct Record { impl Record { pub(crate) fn from_parts( - name: Identifier, + path: Path, fields: Map, annotations: Annotations, ) -> Self { Self { - name, + path, fields, annotations, } } - /// The name of the record. - pub fn name(&self) -> &Identifier { - &self.name + /// The path of the record. + pub fn path(&self) -> &Path { + &self.path } /// The annotations of this record. diff --git a/crates/schema/src/test_utils.rs b/crates/schema/src/test_utils.rs index ecac61ae9..4dd63e89f 100644 --- a/crates/schema/src/test_utils.rs +++ b/crates/schema/src/test_utils.rs @@ -10,11 +10,19 @@ //! The functions in this module can panic and should only be used in tests. use crate::builder::{EntityBuilder, EventBuilder, RecordBuilder, SchemaBuilder}; -use crate::{Annotations, Cardinality, DataType, Entity, Event, Field, Identifier, Record, Schema}; +use crate::{ + Annotations, Cardinality, DataType, Entity, Event, Field, Identifier, Path, Record, Schema, +}; pub fn ident(s: &str) -> Identifier { Identifier::try_new(s).unwrap() } +pub fn path(s: &str) -> Path { + s.parse().unwrap() +} +pub fn record_type(name: &str) -> DataType { + DataType::Record(path(name)) +} pub fn field(name: &str, ty: DataType) -> Field { Field::new(ident(name), ty, Annotations::default()) } @@ -32,16 +40,16 @@ pub fn event_with( .unwrap() } pub fn entity(name: &str, events: impl IntoIterator) -> Entity { - EntityBuilder::new(ident(name)) + EntityBuilder::new(path(name)) .with_events(events) .build() .unwrap() } pub fn eventless_entity(name: &str) -> Entity { - Entity::from_parts(ident(name), Default::default(), Annotations::default()) + Entity::from_parts(path(name), Default::default(), Annotations::default()) } pub fn record(name: &str, fields: impl IntoIterator) -> Record { - RecordBuilder::new(ident(name)) + RecordBuilder::new(path(name)) .with_fields(fields) .build() .unwrap() @@ -57,3 +65,19 @@ pub fn schema( .build() .unwrap() } + +pub fn unchecked_schema( + name: &str, + entities: impl IntoIterator, + records: impl IntoIterator, +) -> Schema { + let entities = entities + .into_iter() + .map(|entity| (entity.path().clone(), entity)) + .collect(); + let records = records + .into_iter() + .map(|record| (record.path().clone(), record)) + .collect(); + Schema::from_parts(ident(name), entities, records, Annotations::default()) +} diff --git a/crates/schema/src/visitor.rs b/crates/schema/src/visitor.rs index 52455a2f6..7dd1b71e7 100644 --- a/crates/schema/src/visitor.rs +++ b/crates/schema/src/visitor.rs @@ -107,9 +107,9 @@ impl Display for Element<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Schema(s) => Display::fmt(s.name(), f), - Self::Entity(e) => Display::fmt(e.name(), f), + Self::Entity(e) => Display::fmt(e.path(), f), Self::Event(e) => Display::fmt(e.name(), f), - Self::Record(r) => Display::fmt(r.name(), f), + Self::Record(r) => Display::fmt(r.path(), f), Self::Field(fi) => Display::fmt(fi.name(), f), Self::Annotations(_) => f.write_str("Annotations"), Self::DataType(ty) => match ty { @@ -255,7 +255,7 @@ tuple_impls!(A => 0, B => 1, C => 2, D => 3, E => 4, F => 5, G => 6, H => 7, I = mod test { use super::*; use crate::builder::AnnotationsBuilder; - use crate::test_utils::{entity, event, field, ident, record, schema}; + use crate::test_utils::{entity, event, field, ident, path, record, record_type, schema}; // Stateless no-op visitor #[derive(Default)] @@ -399,9 +399,9 @@ mod test { } // Declared names resolve through the root mid-walk. if let Element::Schema(_) = cursor.current() { - assert!(cursor.root().entity(&ident("E")).is_some()); - assert!(cursor.root().record(&ident("R")).is_some()); - assert!(cursor.root().entity(&ident("nope")).is_none()); + assert!(cursor.root().entity(&path("E")).is_some()); + assert!(cursor.root().record(&path("R")).is_some()); + assert!(cursor.root().entity(&path("nope")).is_none()); } } fn finish(self) {} @@ -416,7 +416,7 @@ mod test { "S", vec![entity( "E", - vec![event("Ev", vec![field("f", DataType::Record(ident("R")))])], + vec![event("Ev", vec![field("f", record_type("R"))])], )], vec![record("R", vec![field("rf", DataType::U64)])], ); @@ -476,7 +476,7 @@ mod test { field("f64_f", DataType::F64), field("opt_f", DataType::Option(Box::new(DataType::U64))), field("list_f", DataType::List(Box::new(DataType::Bool))), - field("rec_f", DataType::Record(ident("R"))), + field("rec_f", record_type("R")), field("dyn_f", DataType::DynamicRecord), field( "ref_f", From 08b60add13e7863df6198af9608ae287cabab114 Mon Sep 17 00:00:00 2001 From: Johan Peltenburg Date: Fri, 24 Jul 2026 09:03:26 +0200 Subject: [PATCH 02/12] feat(constraints): validate schema type paths Signed-off-by: Johan Peltenburg --- .../constraints/src/duplicate_type_paths.rs | 60 +++++++++++++++++++ .../src/entities_without_events.rs | 2 +- crates/constraints/src/lib.rs | 10 +++- crates/constraints/src/recursive_record.rs | 47 +++++++++------ crates/constraints/src/unresolved_refs.rs | 29 +++++---- crates/constraints/tests/validator.rs | 9 ++- 6 files changed, 121 insertions(+), 36 deletions(-) create mode 100644 crates/constraints/src/duplicate_type_paths.rs diff --git a/crates/constraints/src/duplicate_type_paths.rs b/crates/constraints/src/duplicate_type_paths.rs new file mode 100644 index 000000000..997838fda --- /dev/null +++ b/crates/constraints/src/duplicate_type_paths.rs @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use quent_schema::visitor::{Cursor, Element, Visitor}; +use std::collections::HashSet; + +/// Reports paths declared by both a record and an entity. +#[derive(Default)] +pub(crate) struct DuplicateTypePaths { + found: Vec, +} + +impl Visitor for DuplicateTypePaths { + type Output = Vec; + + fn visit(&mut self, cursor: &Cursor) { + let Element::Schema(schema) = cursor.current() else { + return; + }; + let records: HashSet<_> = schema.records().map(|record| record.path()).collect(); + self.found.extend( + schema + .entities() + .filter(|entity| records.contains(entity.path())) + .map(|entity| entity.path().to_string()), + ); + } + + fn finish(self) -> Self::Output { + self.found + } +} + +#[cfg(test)] +mod tests { + use super::*; + use quent_schema::test_utils::{entity, event, record, unchecked_schema}; + + #[test] + fn reports_a_path_used_by_both_type_kinds() { + let schema = unchecked_schema( + "Schema", + [ + entity("Shared", [event("event", [])]), + entity("Foo::Q", [event("event", [])]), + entity("Bar::Q", [event("event", [])]), + ], + [ + record("Shared", []), + record("Foo::R", []), + record("Bar::R", []), + ], + ); + + assert_eq!( + schema.walk(DuplicateTypePaths::default()), + ["Shared".to_string()] + ); + } +} diff --git a/crates/constraints/src/entities_without_events.rs b/crates/constraints/src/entities_without_events.rs index 3e528d650..2987df6c1 100644 --- a/crates/constraints/src/entities_without_events.rs +++ b/crates/constraints/src/entities_without_events.rs @@ -16,7 +16,7 @@ impl Visitor for EntitiesWithoutEvents { if let Element::Entity(entity) = cursor.current() && entity.events().len() == 0 { - self.entities.push(entity.name().to_string()); + self.entities.push(entity.path().to_string()); } } diff --git a/crates/constraints/src/lib.rs b/crates/constraints/src/lib.rs index 8ff8d6cfb..ad2e63a1d 100644 --- a/crates/constraints/src/lib.rs +++ b/crates/constraints/src/lib.rs @@ -5,6 +5,7 @@ pub mod utils; +mod duplicate_type_paths; mod entities_without_events; mod recursive_record; mod unregistered_constraints; @@ -53,6 +54,8 @@ pub struct BaseConstraintsError { pub recursive_records: Vec, /// Entities that declare no events. pub entities_without_events: Vec, + /// Paths declared by both a record and an entity. + pub duplicate_type_paths: Vec, } impl Display for BaseConstraintsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -63,6 +66,7 @@ impl Display for BaseConstraintsError { utils::bullet_list(&self.invalid_references), utils::bullet_list(&self.recursive_records), utils::bullet_list(&self.entities_without_events), + utils::bullet_list(&self.duplicate_type_paths), ] .join("\n") ) @@ -129,12 +133,14 @@ pub fn validate(schema: &Schema) -> Report { unregistered_constraints, recursive_records, entities_without_events, + duplicate_type_paths, results, ) = schema.walk(( unresolved_refs::UnresolvedReferences::default(), unregistered_constraints::UnregisteredConstraints::new(C::NAMES), recursive_record::RecursiveRecords::default(), entities_without_events::EntitiesWithoutEvents::default(), + duplicate_type_paths::DuplicateTypePaths::default(), C::default(), )); Report { @@ -143,12 +149,14 @@ pub fn validate(schema: &Schema) -> Report { invalid_references.len(), recursive_records.len(), entities_without_events.len(), + duplicate_type_paths.len(), ) { - (0, 0, 0) => Ok(()), + (0, 0, 0, 0) => Ok(()), _ => Err(BaseConstraintsError { invalid_references, recursive_records, entities_without_events, + duplicate_type_paths, }), }, results, diff --git a/crates/constraints/src/recursive_record.rs b/crates/constraints/src/recursive_record.rs index 4d0201f32..403b5426f 100644 --- a/crates/constraints/src/recursive_record.rs +++ b/crates/constraints/src/recursive_record.rs @@ -5,7 +5,7 @@ use std::collections::BTreeSet; use petgraph::{algo::tarjan_scc, graphmap::DiGraphMap}; use quent_schema::{ - DataType, Identifier, + DataType, Path, visitor::{Cursor, Element, Visitor}, }; use rustc_hash::FxHashMap; @@ -15,7 +15,7 @@ use rustc_hash::FxHashMap; #[derive(Default)] pub(crate) struct RecursiveRecords { // Record name -> the records its fields reference. - edges: FxHashMap>, + edges: FxHashMap>, } impl Visitor for RecursiveRecords { @@ -29,7 +29,7 @@ impl Visitor for RecursiveRecords { && let [_, Element::Record(source), ..] = cursor.elements() { self.edges - .entry(source.name().clone()) + .entry(source.path().clone()) .or_default() .push(target.clone()); } @@ -37,13 +37,13 @@ impl Visitor for RecursiveRecords { fn finish(self) -> Self::Output { // Construct a graph of all records referencing all other records. - let graph: DiGraphMap<&Identifier, ()> = self + let graph: DiGraphMap<&Path, ()> = self .edges .iter() .flat_map(|(source, targets)| targets.iter().map(move |target| (source, target))) .collect(); - let mut recursive: BTreeSet<&Identifier> = BTreeSet::new(); + let mut recursive: BTreeSet<&Path> = BTreeSet::new(); // Records in a strongly connected component of more than one node are // mutually recursive. for scc in tarjan_scc(&graph) { @@ -66,7 +66,7 @@ impl Visitor for RecursiveRecords { mod tests { use super::*; use quent_schema::Schema; - use quent_schema::test_utils::{entity, event, field, ident, record, schema}; + use quent_schema::test_utils::{entity, event, field, record, record_type, schema}; fn walk(schema: &Schema) -> Vec { schema.walk(RecursiveRecords::default()) @@ -79,7 +79,7 @@ mod tests { "S", vec![], vec![ - record("S", vec![field("f", DataType::Record(ident("R")))]), + record("S", vec![field("f", record_type("R"))]), record("R", vec![field("g", DataType::U64)]), ], ); @@ -91,7 +91,7 @@ mod tests { let s = schema( "S", vec![], - vec![record("R", vec![field("f", DataType::Record(ident("R")))])], + vec![record("R", vec![field("f", record_type("R"))])], ); assert_eq!(walk(&s), vec!["R".to_string()]); } @@ -102,8 +102,8 @@ mod tests { "S", vec![], vec![ - record("A", vec![field("f", DataType::Record(ident("B")))]), - record("B", vec![field("g", DataType::Record(ident("A")))]), + record("A", vec![field("f", record_type("B"))]), + record("B", vec![field("g", record_type("A"))]), ], ); assert_eq!(walk(&s), vec!["A".to_string(), "B".to_string()]); @@ -112,16 +112,11 @@ mod tests { #[test] fn recursion_through_option_and_list_wrappers_is_reported() { let cases = [ - ( - "A", - DataType::Option(Box::new(DataType::Record(ident("A")))), - ), - ("B", DataType::List(Box::new(DataType::Record(ident("B"))))), + ("A", DataType::Option(Box::new(record_type("A")))), + ("B", DataType::List(Box::new(record_type("B")))), ( "C", - DataType::List(Box::new(DataType::Option(Box::new(DataType::Record( - ident("C"), - ))))), + DataType::List(Box::new(DataType::Option(Box::new(record_type("C"))))), ), ]; for (name, ty) in cases { @@ -136,10 +131,24 @@ mod tests { "S", vec![entity( "E", - vec![event("Ev", vec![field("f", DataType::Record(ident("R")))])], + vec![event("Ev", vec![field("f", record_type("R"))])], )], vec![record("R", vec![field("g", DataType::U64)])], ); assert!(walk(&s).is_empty()); } + + #[test] + fn recursion_across_namespaces_is_reported() { + let s = schema( + "S", + [], + [ + record("Foo::A", [field("b", record_type("Bar::B"))]), + record("Bar::B", [field("a", record_type("Foo::A"))]), + ], + ); + + assert_eq!(walk(&s), ["Bar::B".to_string(), "Foo::A".to_string()]); + } } diff --git a/crates/constraints/src/unresolved_refs.rs b/crates/constraints/src/unresolved_refs.rs index ebf866656..7fac751f4 100644 --- a/crates/constraints/src/unresolved_refs.rs +++ b/crates/constraints/src/unresolved_refs.rs @@ -33,7 +33,7 @@ impl Visitor for UnresolvedReferences { mod tests { use super::*; use quent_schema::Schema; - use quent_schema::test_utils::{entity, event, field, ident, record, schema}; + use quent_schema::test_utils::{entity, event, field, record, record_type, schema}; fn unresolved(schema: &Schema) -> Vec { schema.walk(UnresolvedReferences::default()) @@ -47,7 +47,7 @@ mod tests { "E", vec![event("Ev", vec![field("f", DataType::U64)])], )], - vec![record("R", vec![field("rf", DataType::Record(ident("R")))])], + vec![record("R", vec![field("rf", record_type("R"))])], ); assert!(unresolved(&s).is_empty()); } @@ -58,10 +58,7 @@ mod tests { "S", vec![entity( "E", - vec![event( - "Ev", - vec![field("f", DataType::Record(ident("ghost")))], - )], + vec![event("Ev", vec![field("f", record_type("ghost"))])], )], vec![], ); @@ -77,7 +74,7 @@ mod tests { "S", vec![entity( "E", - vec![event("Ev", vec![field("f", DataType::Record(ident("R")))])], + vec![event("Ev", vec![field("f", record_type("R"))])], )], vec![record("R", vec![])], ); @@ -86,9 +83,7 @@ mod tests { #[test] fn references_into_nested_data_types_are_checked() { - let ty = DataType::Option(Box::new(DataType::List(Box::new(DataType::Record(ident( - "ghost", - )))))); + let ty = DataType::Option(Box::new(DataType::List(Box::new(record_type("ghost"))))); let s = schema( "S", vec![entity("E", vec![event("Ev", vec![field("f", ty)])])], @@ -96,4 +91,18 @@ mod tests { ); assert!(unresolved(&s).iter().any(|r| r.contains("ghost"))); } + + #[test] + fn qualified_record_reference_resolves() { + let s = schema( + "S", + [entity( + "Bar::E", + [event("Ev", [field("f", record_type("Foo::R"))])], + )], + [record("Foo::R", [])], + ); + + assert!(unresolved(&s).is_empty()); + } } diff --git a/crates/constraints/tests/validator.rs b/crates/constraints/tests/validator.rs index d437d0204..36265f15a 100644 --- a/crates/constraints/tests/validator.rs +++ b/crates/constraints/tests/validator.rs @@ -5,7 +5,9 @@ use quent_constraints::{Constraint, validate}; use quent_schema::{ Annotations, Cardinality, DataType, Field, Schema, builder::{AnnotationsBuilder, EntityBuilder, EventBuilder, RecordBuilder, SchemaBuilder}, - test_utils::{self, entity, event, eventless_entity, field, ident, record, schema}, + test_utils::{ + self, entity, event, eventless_entity, field, ident, record, record_type, schema, + }, visitor::{Cursor, Visitor}, }; @@ -26,10 +28,7 @@ fn ghost_ref_schema() -> Schema { "S", vec![entity( "E", - vec![event( - "Ev", - vec![field("f", DataType::Record(ident("ghost")))], - )], + vec![event("Ev", vec![field("f", record_type("ghost"))])], )], vec![], ) From 405995d048993d8dab19edeb2873307e61e3e825 Mon Sep 17 00:00:00 2001 From: Johan Peltenburg Date: Fri, 24 Jul 2026 09:03:35 +0200 Subject: [PATCH 03/12] feat(fsm): support entity paths Signed-off-by: Johan Peltenburg --- crates/fsm/src/builder.rs | 14 ++++----- crates/fsm/src/lib.rs | 47 ++++++++++-------------------- crates/fsm/tests/fsm-constraint.rs | 14 ++++++++- 3 files changed, 36 insertions(+), 39 deletions(-) diff --git a/crates/fsm/src/builder.rs b/crates/fsm/src/builder.rs index 9a43769a2..49f3e021c 100644 --- a/crates/fsm/src/builder.rs +++ b/crates/fsm/src/builder.rs @@ -5,7 +5,7 @@ use std::collections::HashSet; use quent_constraints::Constraint; use quent_schema::builder::{AnnotationsBuilder, BuilderError, EntityBuilder, EventBuilder}; -use quent_schema::{Annotations, Cardinality, Entity, Field, Identifier}; +use quent_schema::{Annotations, Cardinality, Entity, Field, Identifier, Path}; use thiserror::Error; use crate::{ExitStates, Fsm, FsmConstraint, FsmError, Transition, check_entity}; @@ -30,7 +30,7 @@ pub struct StateDecl { /// [`Self::build`] validates the topology with the same checks as /// [`crate::FsmConstraint`], so a built entity is always valid. pub struct FsmEntityBuilder { - id: Identifier, + path: Path, annotations: AnnotationsBuilder, states: Vec, } @@ -58,10 +58,10 @@ pub enum FsmEntityBuilderError { } impl FsmEntityBuilder { - /// Begin an FSM entity named `id`. - pub fn new(id: Identifier) -> Self { + /// Begin an FSM entity at `path`. + pub fn new(path: impl Into) -> Self { Self { - id, + path: path.into(), annotations: AnnotationsBuilder::new(), states: Vec::new(), } @@ -99,7 +99,7 @@ impl FsmEntityBuilder { /// topology is invalid. pub fn build(self) -> Result { let Self { - id, + path, mut annotations, states, } = self; @@ -148,7 +148,7 @@ impl FsmEntityBuilder { ExitStates::new(first_exit.clone(), other_exits.to_vec()), ); - let mut entity = EntityBuilder::new(id); + let mut entity = EntityBuilder::new(path); for state in states { // An isolated state has no place on the topology; the FSM constraint // reports it, so `Once` here is only a stand-in. diff --git a/crates/fsm/src/lib.rs b/crates/fsm/src/lib.rs index 43f6b4271..5bb3f2554 100644 --- a/crates/fsm/src/lib.rs +++ b/crates/fsm/src/lib.rs @@ -12,7 +12,7 @@ use petgraph::{ }; use quent_constraints::{Constraint, utils::bullet_list}; use quent_schema::{ - Cardinality, Entity, Identifier, + Cardinality, Entity, Identifier, Path, visitor::{Cursor, Element, Visitor}, }; use serde::{Deserialize, Serialize}; @@ -209,7 +209,7 @@ impl Visitor for FsmConstraint { Some(s) => s, None => { self.errors.push(FsmError::InvalidData { - entity: entity.name().clone(), + entity: entity.path().clone(), message: "constraint data is missing".to_string(), }); return; @@ -219,7 +219,7 @@ impl Visitor for FsmConstraint { Ok(f) => f, Err(e) => { self.errors.push(FsmError::InvalidData { - entity: entity.name().clone(), + entity: entity.path().clone(), message: format!("failed to decode fsm: {e}"), }); return; @@ -246,7 +246,7 @@ pub(crate) fn check_entity(entity: &Entity, fsm: &Fsm, errors: &mut Vec { #[derive(Debug, Error)] pub enum FsmError { #[error("entity \"{entity}\" fsm: {message}")] - InvalidData { entity: Identifier, message: String }, + InvalidData { entity: Path, message: String }, #[error("entity \"{entity}\" fsm: \"{name}\" is a reserved state name")] - ReservedStateName { - entity: Identifier, - name: &'static str, - }, + ReservedStateName { entity: Path, name: &'static str }, #[error("entity \"{entity}\" fsm: state \"{state}\" is unreachable from the initial state")] - UnreachableFromInit { - entity: Identifier, - state: Identifier, - }, + UnreachableFromInit { entity: Path, state: Identifier }, #[error("entity \"{entity}\" fsm: state \"{state}\" cannot reach any exit transition")] - CannotReachExit { - entity: Identifier, - state: Identifier, - }, + CannotReachExit { entity: Path, state: Identifier }, #[error("entity \"{entity}\" fsm: state \"{state}\" does not match any event")] - UnknownState { - entity: Identifier, - state: Identifier, - }, + UnknownState { entity: Path, state: Identifier }, #[error("entity \"{entity}\" fsm: event \"{event}\" does not appear as a state")] - UncoveredEvent { - entity: Identifier, - event: Identifier, - }, + UncoveredEvent { entity: Path, event: Identifier }, #[error( "entity \"{entity}\" fsm: state \"{state}\" expects cardinality {expected:?}, but event has {found:?}" )] CardinalityMismatch { - entity: Identifier, + entity: Path, state: Identifier, expected: Cardinality, found: Cardinality, diff --git a/crates/fsm/tests/fsm-constraint.rs b/crates/fsm/tests/fsm-constraint.rs index 051057426..192369bbf 100644 --- a/crates/fsm/tests/fsm-constraint.rs +++ b/crates/fsm/tests/fsm-constraint.rs @@ -47,7 +47,7 @@ fn fsm_annotations(data: Option) -> Annotations { } fn entity_with(name: &str, events: Vec, data: &str) -> Entity { - EntityBuilder::new(ident(name)) + EntityBuilder::new(name.parse::().unwrap()) .with_events(events) .with_annotations(fsm_annotations(Some(data.to_string()))) .build() @@ -78,6 +78,18 @@ fn well_formed_linear_fsm_passes() { assert!(validate(&schema_with(entity)).is_empty()); } +#[test] +fn diagnostics_include_the_qualified_entity_path() { + let fsm = fsm("a", &[("a", "missing")], &["a"]); + let entity = entity_with("Foo::E", vec![event("a", Cardinality::Once)], &fsm); + + assert!( + validate(&schema_with(entity)).iter().any( + |error| matches!(error, FsmError::UnknownState { entity, .. } if entity == "Foo::E") + ) + ); +} + #[test] fn well_formed_self_loop_fsm_passes() { let fsm = fsm("a", &[("a", "a")], &["a"]); From ce2dbf5e9094d598f8b85c82f58563bc308e9cc9 Mon Sep 17 00:00:00 2001 From: Johan Peltenburg Date: Fri, 24 Jul 2026 09:03:35 +0200 Subject: [PATCH 04/12] feat(ref-target): support entity paths Signed-off-by: Johan Peltenburg --- crates/ref-target/src/lib.rs | 19 ++++++++----------- .../ref-target/tests/ref-target-constraint.rs | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/crates/ref-target/src/lib.rs b/crates/ref-target/src/lib.rs index 97dde2d12..87a000101 100644 --- a/crates/ref-target/src/lib.rs +++ b/crates/ref-target/src/lib.rs @@ -5,23 +5,23 @@ use quent_constraints::{Constraint, utils::bullet_list}; use quent_schema::{ - Annotations, DataType, Identifier, + Annotations, DataType, Path, visitor::{Cursor, Element, Visitor}, }; use thiserror::Error; /// The entity type an entity reference is restricted to point at. #[derive(Debug, Clone, PartialEq, Eq)] -pub struct RefTarget(Identifier); +pub struct RefTarget(Path); -impl From for Identifier { +impl From for Path { fn from(ref_target: RefTarget) -> Self { ref_target.0 } } -impl AsRef for RefTarget { - fn as_ref(&self) -> &Identifier { +impl AsRef for RefTarget { + fn as_ref(&self) -> &Path { &self.0 } } @@ -30,7 +30,7 @@ impl RefTarget { /// Return the reference target entity type declared on `annotations`, if any. pub fn from_annotations(annotations: &Annotations) -> Option { let raw = annotations.constraint(RefTargetConstraint::NAME)?.data()?; - Identifier::try_from(raw).ok().map(RefTarget) + raw.parse().ok().map(RefTarget) } } @@ -61,7 +61,7 @@ impl Visitor for RefTargetConstraint { location, message: "constraint data is missing".to_string(), }), - Some(raw) => match Identifier::try_from(raw) { + Some(raw) => match raw.parse::() { Ok(target) => { if cursor.root().entity(&target).is_none() { self.errors @@ -94,10 +94,7 @@ pub enum RefTargetError { #[error("{location}: invalid ref-target data: {message}")] InvalidData { location: String, message: String }, #[error("{location}: ref-target points at unknown entity \"{target}\"")] - UnknownTarget { - location: String, - target: Identifier, - }, + UnknownTarget { location: String, target: Path }, #[error("multiple ref-target violations:\n{}", bullet_list(.0))] Multiple(Vec), } diff --git a/crates/ref-target/tests/ref-target-constraint.rs b/crates/ref-target/tests/ref-target-constraint.rs index db52f3940..39e05d5c9 100644 --- a/crates/ref-target/tests/ref-target-constraint.rs +++ b/crates/ref-target/tests/ref-target-constraint.rs @@ -85,3 +85,17 @@ fn invalid_target_identifier_is_rejected() { .any(|e| matches!(e, RefTargetError::InvalidData { .. })), ); } + +#[test] +fn qualified_target_resolves() { + let worker = entity("Foo::Worker", [event("created", [])]); + let task = entity( + "Bar::Task", + [event( + "created", + [field("on", entity_ref(Some("Foo::Worker")))], + )], + ); + + assert!(validate(&schema_with(vec![worker, task])).is_empty()); +} From 1fd5a8f381e2cc5ecd8fae0044906001d5c159dd Mon Sep 17 00:00:00 2001 From: Johan Peltenburg Date: Fri, 24 Jul 2026 09:03:36 +0200 Subject: [PATCH 05/12] feat(ref-tree): support entity paths Signed-off-by: Johan Peltenburg --- crates/ref-tree/src/lib.rs | 67 ++++++++++---------- crates/ref-tree/tests/ref-tree-constraint.rs | 29 +++++---- 2 files changed, 50 insertions(+), 46 deletions(-) diff --git a/crates/ref-tree/src/lib.rs b/crates/ref-tree/src/lib.rs index 92e679cc1..9640077e3 100644 --- a/crates/ref-tree/src/lib.rs +++ b/crates/ref-tree/src/lib.rs @@ -15,7 +15,7 @@ use thiserror::Error; use quent_constraints::{Constraint, utils::bullet_list}; use quent_ref_target::RefTarget; use quent_schema::{ - DataType, Identifier, + DataType, Identifier, Path, visitor::{Cursor, Element, Visitor}, }; @@ -101,9 +101,9 @@ pub struct RefTreeConstraint { // Map of a node to its petgraph index. index: FxHashMap, // Name of every entity, in schema order, to figure out which one is root. - entities: Vec, + entities: Vec, // Quick lookup for records that have already declared a parent. - records_seen: FxHashSet, + records_seen: FxHashSet, // Set once a tree-forming reference declares a parent. The tree shape is // only validated when at least one reference uses the constraint. used: bool, @@ -114,9 +114,9 @@ pub struct RefTreeConstraint { /// A vertex in the entity/event/record graph. #[derive(Clone, PartialEq, Eq, Hash)] enum Node { - Entity(Identifier), - Event(Identifier, Identifier), - Record(Identifier), + Entity(Path), + Event(Path, Identifier), + Record(Path), } impl Visitor for RefTreeConstraint { @@ -127,17 +127,17 @@ impl Visitor for RefTreeConstraint { // Add every entity as a node. Element::Schema(schema) => { for entity in schema.entities() { - self.entities.push(entity.name().clone()); - self.node_or_insert(Node::Entity(entity.name().clone())); + self.entities.push(entity.path().clone()); + self.node_or_insert(Node::Entity(entity.path().clone())); } } // If we encounter an event, add it as a node and connect it to its // entity. Element::Event(event) => { if let [_, Element::Entity(entity), ..] = cursor.elements() { - let from = self.node_or_insert(Node::Entity(entity.name().clone())); + let from = self.node_or_insert(Node::Entity(entity.path().clone())); let to = self - .node_or_insert(Node::Event(entity.name().clone(), event.name().clone())); + .node_or_insert(Node::Event(entity.path().clone(), event.name().clone())); self.graph.add_edge(from, to, ()); } } @@ -254,16 +254,16 @@ impl RefTreeConstraint { fn check_tree( graph: &Graph, index: &FxHashMap, - entities: &[Identifier], + entities: &[Path], errors: &mut Vec, ) { - let mut roots: Vec<&Identifier> = Vec::new(); - let mut non_roots: Vec<&Identifier> = Vec::new(); + let mut roots: Vec<&Path> = Vec::new(); + let mut non_roots: Vec<&Path> = Vec::new(); // For each entity, we figure out whether we can collapse its parent edges // (through multiple events) into one edge. If not, this violates the // requirements. - let mut entity_edges: Vec<(&Identifier, &Identifier)> = Vec::new(); + let mut entity_edges: Vec<(&Path, &Path)> = Vec::new(); for entity in entities { // Unwrap should be safe here since we added entities to the set and @@ -310,12 +310,12 @@ fn check_tree( // Now check: // - every entity reaches root (req 5) // If there are no errors afterwards the whole constraint is validated. - let mut maybe_tree: DiGraphMap<&Identifier, ()> = DiGraphMap::new(); + let mut maybe_tree: DiGraphMap<&Path, ()> = DiGraphMap::new(); maybe_tree.add_node(root); for (parent, child) in entity_edges { maybe_tree.add_edge(parent, child, ()); } - let reachable: FxHashSet<&Identifier> = Bfs::new(&maybe_tree, root).iter(&maybe_tree).collect(); + let reachable: FxHashSet<&Path> = Bfs::new(&maybe_tree, root).iter(&maybe_tree).collect(); for entity in non_roots { if !reachable.contains(entity) { errors.push(RefTreeError::Unreachable { @@ -368,7 +368,7 @@ fn event_ref_count(graph: &Graph, event: NodeIndex) -> usize { } // List all unique parent entities reachable from the supplied entity -fn entity_unique_parents(graph: &Graph, entity: NodeIndex) -> Vec<&Identifier> { +fn entity_unique_parents(graph: &Graph, entity: NodeIndex) -> Vec<&Path> { let mut parents = Vec::new(); let mut seen: FxHashSet = FxHashSet::default(); let mut stack: Vec = graph.neighbors(entity).collect(); @@ -384,17 +384,17 @@ fn entity_unique_parents(graph: &Graph, entity: NodeIndex) -> Vec<&Ide parents } -fn event_at_cursor<'s>(cursor: &'s Cursor) -> Option<(&'s Identifier, &'s Identifier)> { +fn event_at_cursor<'s>(cursor: &'s Cursor) -> Option<(&'s Path, &'s Identifier)> { match cursor.elements() { [_schema, Element::Entity(entity), Element::Event(event), ..] => { - Some((entity.name(), event.name())) + Some((entity.path(), event.name())) } _ => None, } } -fn record_at_cursor<'s>(cursor: &'s Cursor) -> Option<&'s Identifier> { +fn record_at_cursor<'s>(cursor: &'s Cursor) -> Option<&'s Path> { match cursor.elements() { - [_schema, Element::Record(record), ..] => Some(record.name()), + [_schema, Element::Record(record), ..] => Some(record.path()), _ => None, } } @@ -404,29 +404,26 @@ pub enum RefTreeError { #[error("{location}: a tree-forming reference must be target-constrained")] NotTargetConstrained { location: String }, #[error("{location}: tree-forming reference targets unknown entity \"{target}\"")] - UnknownTarget { - location: String, - target: Identifier, - }, + UnknownTarget { location: String, target: Path }, #[error("{location}: an event carries more than one tree-forming reference")] MultiplePerEvent { location: String }, #[error("{location}: a record carries more than one tree-forming reference")] MultipleRefsInRecord { location: String }, #[error("tree-forming references are used, but there is no root entity")] NoRoot, - #[error("more than one root entity: {}", join_idents(.roots))] - MultipleRoots { roots: Vec }, - #[error("entity \"{entity}\" declares more than one parent type: {}", join_idents(.parents))] - ConflictingParents { - entity: Identifier, - parents: Vec, - }, + #[error("more than one root entity: {}", join_paths(.roots))] + MultipleRoots { roots: Vec }, + #[error("entity \"{entity}\" declares more than one parent type: {}", join_paths(.parents))] + ConflictingParents { entity: Path, parents: Vec }, #[error("entity \"{entity}\" has no path to the root through tree-forming references")] - Unreachable { entity: Identifier }, + Unreachable { entity: Path }, #[error("multiple ref-tree violations:\n{}", bullet_list(.0))] Multiple(Vec), } -fn join_idents(ids: &[Identifier]) -> String { - ids.iter().map(AsRef::as_ref).collect::>().join(", ") +fn join_paths(ids: &[Path]) -> String { + ids.iter() + .map(ToString::to_string) + .collect::>() + .join(", ") } diff --git a/crates/ref-tree/tests/ref-tree-constraint.rs b/crates/ref-tree/tests/ref-tree-constraint.rs index 94478dd78..9927f096c 100644 --- a/crates/ref-tree/tests/ref-tree-constraint.rs +++ b/crates/ref-tree/tests/ref-tree-constraint.rs @@ -7,7 +7,7 @@ use quent_ref_tree::{RefTreeConstraint, RefTreeError}; use quent_schema::{ Annotations, DataType, Entity, Record, Schema, builder::AnnotationsBuilder, - test_utils::{entity, event, field, ident, record, schema}, + test_utils::{entity, event, field, record, record_type, schema}, }; /// A type-erased tree-forming reference (no target). @@ -27,7 +27,7 @@ fn tree_ref_to(target: &str) -> DataType { data: None, annotations: AnnotationsBuilder::new() .with_constraint(RefTreeConstraint::NAME, None) - .with_constraint(RefTargetConstraint::NAME, Some(ident(target).to_string())) + .with_constraint(RefTargetConstraint::NAME, Some(target.to_string())) .build() .unwrap(), } @@ -93,6 +93,16 @@ fn target_chain_to_root_passes() { assert_valid(&schema); } +#[test] +fn qualified_target_chain_to_root_passes() { + let schema = schema_with(vec![ + root("Domain::Cluster"), + child("Worker::Node", tree_ref_to("Domain::Cluster")), + child("Task::Job", tree_ref_to("Worker::Node")), + ]); + assert_valid(&schema); +} + #[test] fn single_child_under_root_passes() { let schema = schema_with(vec![ @@ -134,7 +144,7 @@ fn tree_ref_in_reference_payload_is_found() { fn tree_ref_via_record_field_resolves_parent() { // A parent reference reached through a record-typed event field counts. let meta = record("Meta", vec![field("owner", tree_ref_to("Cluster"))]); - let worker = child("Worker", DataType::Record(ident("Meta"))); + let worker = child("Worker", record_type("Meta")); let schema = schema_with_records(vec![root("Cluster"), worker], vec![meta]); assert_valid(&schema); } @@ -149,7 +159,7 @@ fn multiple_refs_in_record_is_rejected() { field("b", tree_ref_to("Cluster")), ], ); - let worker = child("Worker", DataType::Record(ident("Meta"))); + let worker = child("Worker", record_type("Meta")); let schema = schema_with_records(vec![root("Cluster"), worker], vec![meta]); assert!(matches!( single_error(&schema), @@ -165,13 +175,10 @@ fn recursive_record_does_not_loop() { "Meta", vec![ field("owner", tree_ref_to("Cluster")), - field( - "nested", - DataType::Option(Box::new(DataType::Record(ident("Meta")))), - ), + field("nested", DataType::Option(Box::new(record_type("Meta")))), ], ); - let worker = child("Worker", DataType::Record(ident("Meta"))); + let worker = child("Worker", record_type("Meta")); let schema = schema_with_records(vec![root("Cluster"), worker], vec![meta]); assert_valid(&schema); } @@ -204,7 +211,7 @@ fn type_erased_tree_ref_is_rejected() { fn type_erased_tree_ref_via_record_is_rejected() { // Req. 3 also reaches references hidden behind a record-typed field. let meta = record("Meta", vec![field("owner", tree_ref())]); - let worker = child("Worker", DataType::Record(ident("Meta"))); + let worker = child("Worker", record_type("Meta")); let schema = schema_with_records(vec![root("Cluster"), worker], vec![meta]); assert!(matches!( single_error(&schema), @@ -261,7 +268,7 @@ fn direct_and_record_refs_in_one_event_is_rejected() { "created", vec![ field("direct", tree_ref_to("Cluster")), - field("meta", DataType::Record(ident("Meta"))), + field("meta", record_type("Meta")), ], )], ); From 39f6a3fc91ac5ae646dc3a81c28124ba3bb4c958 Mon Sep 17 00:00:00 2001 From: Johan Peltenburg Date: Fri, 24 Jul 2026 09:03:36 +0200 Subject: [PATCH 06/12] feat(resource): support resource paths Signed-off-by: Johan Peltenburg --- crates/resource/src/builder.rs | 113 +++++++++++-------- crates/resource/src/lib.rs | 56 ++++----- crates/resource/tests/resource-constraint.rs | 44 +++++--- 3 files changed, 117 insertions(+), 96 deletions(-) diff --git a/crates/resource/src/builder.rs b/crates/resource/src/builder.rs index 3c3b6f417..da875f75f 100644 --- a/crates/resource/src/builder.rs +++ b/crates/resource/src/builder.rs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 use quent_schema::{ - Annotations, DataType, Field, Identifier, Record, + Annotations, DataType, Field, Identifier, Path, Record, builder::{AnnotationsBuilder, BuilderError, RecordBuilder}, }; use thiserror::Error; @@ -23,46 +23,56 @@ pub struct ResourceParts { /// Builds a resource definition and its usage and bounds record types. pub struct ResourceBuilder { - name: Identifier, - usage_record_name: Identifier, - bounds_record_name: Identifier, + path: Path, + usage_record_path: Path, + bounds_record_path: Path, capacities: Vec<(Identifier, Capacity)>, } impl ResourceBuilder { - /// Start a resource using `{name}Usage` and `{name}Bounds` record names. - pub fn new(name: Identifier) -> Self { - let usage_record_name = Self::default_usage_record_name(&name); - let bounds_record_name = Self::default_bounds_record_name(&name); - Self::with_record_names(name, usage_record_name, bounds_record_name) + /// Start a resource using sibling `{name}Usage` and `{name}Bounds` record paths. + pub fn new(path: impl Into) -> Self { + let path = path.into(); + let usage_record_path = Self::default_usage_record_path(&path); + let bounds_record_path = Self::default_bounds_record_path(&path); + Self::with_record_paths(path, usage_record_path, bounds_record_path) } - /// Return the default usage record name for `resource`. - pub fn default_usage_record_name(resource: &Identifier) -> Identifier { - suffixed_identifier(resource, "Usage") + /// Return the default usage record path for `resource`. + pub fn default_usage_record_path(resource: &Path) -> Path { + resource.with_name(suffixed_identifier(resource.name(), "Usage")) } - /// Return the default bounds record name for `resource`. - pub fn default_bounds_record_name(resource: &Identifier) -> Identifier { - suffixed_identifier(resource, "Bounds") + /// Return the default bounds record path for `resource`. + pub fn default_bounds_record_path(resource: &Path) -> Path { + resource.with_name(suffixed_identifier(resource.name(), "Bounds")) } - /// Start a resource with explicit generated record names. + /// Start a resource with explicit generated record paths. /// - /// `bounds_record_name` is used only when a capacity is bounded. - pub fn with_record_names( - name: Identifier, - usage_record_name: Identifier, - bounds_record_name: Identifier, + /// `bounds_record_path` is used only when a capacity is bounded. + pub fn with_record_paths( + path: impl Into, + usage_record_path: impl Into, + bounds_record_path: impl Into, ) -> Self { Self { - name, - usage_record_name, - bounds_record_name, + path: path.into(), + usage_record_path: usage_record_path.into(), + bounds_record_path: bounds_record_path.into(), capacities: Vec::new(), } } + /// Start a resource with explicit generated record paths. + pub fn with_record_names( + path: impl Into, + usage_record_path: impl Into, + bounds_record_path: impl Into, + ) -> Self { + Self::with_record_paths(path, usage_record_path, bounds_record_path) + } + /// Add a capacity, returning the builder for chaining. pub fn with_capacity(mut self, name: Identifier, capacity: Capacity) -> Self { self.capacities.push((name, capacity)); @@ -89,9 +99,9 @@ impl ResourceBuilder { /// bounds are generated, or generation fails. pub fn build(self) -> Result { let ResourceBuilder { - name, - usage_record_name, - bounds_record_name, + path, + usage_record_path, + bounds_record_path, capacities, } = self; let mut unique_capacities = Capacities::default(); @@ -107,25 +117,25 @@ impl ResourceBuilder { } let capacities = unique_capacities; let has_bounds = capacities.values().any(Capacity::is_bounded); - if has_bounds && usage_record_name == bounds_record_name { - return Err(BuildError::DuplicateRecordName(usage_record_name)); + if has_bounds && usage_record_path == bounds_record_path { + return Err(BuildError::DuplicateRecordName(usage_record_path)); } // Usages include every capacity. Bounds omit unbounded capacities // because those have no bound value to carry. let usage = build_resource_record( - usage_record_name, + usage_record_path, Resource::Usage { - resource: name.clone(), + resource: path.clone(), }, capacities.keys(), )?; let bounds = if has_bounds { Some(build_resource_record( - bounds_record_name, + bounds_record_path, Resource::Bounds { - resource: name.clone(), + resource: path.clone(), }, capacities .iter() @@ -148,14 +158,14 @@ impl ResourceBuilder { /// /// Each supplied identifier becomes a `U64` field. fn build_resource_record<'a>( - name: Identifier, + path: Path, resource: Resource, fields: impl Iterator, ) -> Result { let annotations = AnnotationsBuilder::new() .with_constraint(Resource::NAME, Some(resource.constraint_data()?)) .build()?; - let mut builder = RecordBuilder::new(name).with_annotations(annotations); + let mut builder = RecordBuilder::new(path).with_annotations(annotations); for field in fields { builder = builder.with_field(Field::new( field.clone(), @@ -175,8 +185,8 @@ fn suffixed_identifier(resource: &Identifier, suffix: &str) -> Identifier { pub enum BuildError { #[error("duplicate capacity \"{0}\"")] DuplicateCapacity(Identifier), - #[error("usage and bounds records have the same name \"{0}\"")] - DuplicateRecordName(Identifier), + #[error("usage and bounds records have the same path \"{0}\"")] + DuplicateRecordName(Path), #[error(transparent)] Schema(#[from] BuilderError), #[error("serializing resource data: {0}")] @@ -187,14 +197,11 @@ pub enum BuildError { mod tests { use super::*; use crate::CapacityKind; - use quent_schema::test_utils::ident; + use quent_schema::test_utils::{ident, path}; #[test] fn builds_definition_and_records() { let bytes = ident("bytes"); - let usage_name = ident("MemoryUsage"); - let bounds_name = ident("MemoryBounds"); - let parts = ResourceBuilder::new(ident("Memory")) .with_capacity(bytes.clone(), Capacity::new(CapacityKind::Occupancy, true)) .build() @@ -206,12 +213,12 @@ mod tests { assert_eq!(capacity.kind(), CapacityKind::Occupancy); assert!(capacity.is_bounded()); assert!(capacities.next().is_none()); - assert_eq!(parts.usage.name(), &usage_name); + assert_eq!(parts.usage.path(), &path("MemoryUsage")); assert!(parts.usage.field(&bytes).is_some()); assert!( parts .bounds - .is_some_and(|bounds| bounds.name() == &bounds_name) + .is_some_and(|bounds| bounds.path() == &path("MemoryBounds")) ); } @@ -221,7 +228,7 @@ mod tests { fn builds_unit_resource() { let parts = ResourceBuilder::new(ident("Thread")).build().unwrap(); assert!(parts.definition.capacities().unwrap().next().is_none()); - assert_eq!(parts.usage.name(), &ident("ThreadUsage")); + assert_eq!(parts.usage.path(), &path("ThreadUsage")); assert_eq!(parts.usage.fields().count(), 0); assert!(parts.bounds.is_none()); } @@ -237,8 +244,8 @@ mod tests { .build() .unwrap(); - assert_eq!(parts.usage.name(), &ident("MemoryClaim")); - assert_eq!(parts.bounds.unwrap().name(), &ident("MemoryLimits")); + assert_eq!(parts.usage.path(), &path("MemoryClaim")); + assert_eq!(parts.bounds.unwrap().path(), &path("MemoryLimits")); } #[test] @@ -266,4 +273,18 @@ mod tests { Err(BuildError::DuplicateCapacity(name)) if name == bytes )); } + + #[test] + fn generated_records_are_siblings_of_the_resource() { + let parts = ResourceBuilder::new(path("Foo::Memory")) + .with_capacity(ident("bytes"), Capacity::new(CapacityKind::Occupancy, true)) + .build() + .unwrap(); + + assert_eq!(parts.usage.path().to_string(), "Foo::MemoryUsage"); + assert_eq!( + parts.bounds.unwrap().path().to_string(), + "Foo::MemoryBounds" + ); + } } diff --git a/crates/resource/src/lib.rs b/crates/resource/src/lib.rs index 750fd13ab..43ae9a2dc 100644 --- a/crates/resource/src/lib.rs +++ b/crates/resource/src/lib.rs @@ -6,7 +6,7 @@ use quent_constraints::{Constraint, utils::bullet_list}; use quent_fsm::FsmConstraint; use quent_schema::{ - Annotations, DataType, Entity, Identifier, + Annotations, DataType, Entity, Identifier, Path, visitor::{Cursor, Element, Visitor}, }; use rustc_hash::{FxHashMap as Map, FxHashSet}; @@ -52,9 +52,9 @@ pub use builder::{BuildError, ResourceBuilder, ResourceParts}; #[derive(Default)] pub struct ResourceConstraint { errors: Vec, - resources: Map>, - usage_records: Map, - bounds_records: Map, + resources: Map>, + usage_records: Map, + bounds_records: Map, record_refs: Vec, } @@ -104,9 +104,9 @@ pub enum Resource { /// Declares the capacities provided by the annotated entity. Definition(Capacities), /// Declares the annotated record as bounds for `resource`. - Bounds { resource: Identifier }, + Bounds { resource: Path }, /// Declares the annotated record as a usage of `resource`. - Usage { resource: Identifier }, + Usage { resource: Path }, } impl Resource { @@ -142,23 +142,23 @@ impl Resource { } struct UsageRecord { - resource: Identifier, + resource: Path, claims: Vec, location: String, } struct BoundsRecord { - resource: Identifier, + resource: Path, fields: Vec, location: String, } struct RecordRef { - record: Identifier, + record: Path, on_entity_ref: bool, in_list: bool, in_reference_list: bool, - entity: Option<(Identifier, bool)>, + entity: Option<(Path, bool)>, location: String, } @@ -171,7 +171,7 @@ impl Visitor for ResourceConstraint { match self.decode_resource_annotation(cursor, entity.annotations()) { Some(Resource::Definition(capacities)) => { self.resources.insert( - entity.name().clone(), + entity.path().clone(), capacities .iter() .map(|(name, capacity)| (name.clone(), capacity.is_bounded())) @@ -192,7 +192,7 @@ impl Visitor for ResourceConstraint { match self.decode_resource_annotation(cursor, record.annotations()) { Some(Resource::Usage { resource }) => { self.usage_records.insert( - record.name().clone(), + record.path().clone(), UsageRecord { resource, claims: record.fields().map(|field| field.name().clone()).collect(), @@ -202,7 +202,7 @@ impl Visitor for ResourceConstraint { } Some(Resource::Bounds { resource }) => { self.bounds_records.insert( - record.name().clone(), + record.path().clone(), BoundsRecord { resource, fields: record.fields().map(|field| field.name().clone()).collect(), @@ -254,7 +254,7 @@ impl Visitor for ResourceConstraint { }), entity: enclosing_entity(cursor).map(|entity| { ( - entity.name().clone(), + entity.path().clone(), entity.annotations().has_constraint(FsmConstraint::NAME), ) }), @@ -501,14 +501,11 @@ pub enum ResourceError { element: &'static str, }, #[error("{location}: names undeclared resource \"{resource}\"")] - UnknownResource { - location: String, - resource: Identifier, - }, + UnknownResource { location: String, resource: Path }, #[error("{location}: claims undeclared capacity \"{capacity}\" of resource \"{resource}\"")] UndeclaredCapacity { location: String, - resource: Identifier, + resource: Path, capacity: Identifier, }, #[error("{location}: a usage record is used outside an entity reference")] @@ -516,15 +513,9 @@ pub enum ResourceError { #[error("{location}: a usage record cannot be nested in list-valued reference data")] UsageInList { location: String }, #[error("entity \"{entity}\" uses resource \"{resource}\" but is not an FSM")] - NonFsmUser { - entity: Identifier, - resource: Identifier, - }, + NonFsmUser { entity: Path, resource: Path }, #[error("{location}: bounds of resource \"{resource}\" used outside that resource's events")] - ForeignBounds { - location: String, - resource: Identifier, - }, + ForeignBounds { location: String, resource: Path }, #[error("{location}: a bounds record cannot be used in a list")] BoundsInList { location: String }, #[error( @@ -532,22 +523,19 @@ pub enum ResourceError { )] UnboundedCapacity { location: String, - resource: Identifier, + resource: Path, capacity: Identifier, }, #[error("{location}: bounds of resource \"{resource}\" omit bounded capacity \"{capacity}\"")] UncoveredCapacity { location: String, - resource: Identifier, + resource: Path, capacity: Identifier, }, #[error("{location}: unbounded resource \"{resource}\" declares a bounds record")] - UnexpectedBounds { - location: String, - resource: Identifier, - }, + UnexpectedBounds { location: String, resource: Path }, #[error("resource \"{resource}\" has a bounded capacity but no bounds event")] - MissingBounds { resource: Identifier }, + MissingBounds { resource: Path }, #[error("multiple resource violations:\n{}", bullet_list(.0))] Multiple(Vec), } diff --git a/crates/resource/tests/resource-constraint.rs b/crates/resource/tests/resource-constraint.rs index 73345952a..5c595ef3a 100644 --- a/crates/resource/tests/resource-constraint.rs +++ b/crates/resource/tests/resource-constraint.rs @@ -7,7 +7,7 @@ use quent_resource::{ResourceConstraint, ResourceError}; use quent_schema::{ Annotations, DataType, Entity, Record, Schema, builder::{AnnotationsBuilder, EntityBuilder, RecordBuilder, SchemaBuilder}, - test_utils::{event, field, ident, schema}, + test_utils::{event, field, ident, path, record_type, schema}, }; /// Create resource definition data from `(name, kind, bounded)` tuples. @@ -25,10 +25,12 @@ fn definition_data(capacities: &[(&str, &str, bool)]) -> String { } fn usage_data(resource: &str) -> String { + let resource: Vec<_> = resource.split("::").collect(); serde_json::json!({ "usage": { "resource": resource } }).to_string() } fn bounds_data(resource: &str) -> String { + let resource: Vec<_> = resource.split("::").collect(); serde_json::json!({ "bounds": { "resource": resource } }).to_string() } @@ -49,7 +51,7 @@ fn fsm_annotations() -> Annotations { /// Create a record carrying resource `data` with a `U64` field for each name. fn resource_record(name: &str, data: String, fields: &[&str]) -> Record { - let mut builder = RecordBuilder::new(ident(name)).with_annotations(resource_annotations(data)); + let mut builder = RecordBuilder::new(path(name)).with_annotations(resource_annotations(data)); for &f in fields { builder = builder.with_field(field(f, DataType::U64)); } @@ -66,7 +68,7 @@ fn bounds_record(name: &str, resource: &str, fields: &[&str]) -> Record { /// Create a resource entity with a bounds event referencing `bounds` when given. fn resource_entity(name: &str, capacities: &[(&str, &str, bool)], bounds: Option<&str>) -> Entity { - let bounds = bounds.map(|bounds| DataType::Record(ident(bounds))); + let bounds = bounds.map(record_type); resource_entity_with_bounds_type(name, capacities, bounds) } @@ -75,7 +77,7 @@ fn resource_entity_with_bounds_type( capacities: &[(&str, &str, bool)], bounds: Option, ) -> Entity { - let mut builder = EntityBuilder::new(ident(name)) + let mut builder = EntityBuilder::new(path(name)) .with_annotations(resource_annotations(definition_data(capacities))); let fields = bounds.map(|bounds| field("bounds", bounds)).into_iter(); builder = builder.with_event(event("operating", fields)); @@ -87,7 +89,7 @@ fn resource_entity_with_bounds_type( /// It is an FSM iff `fsm`, and the record rides on an entity reference iff /// `on_ref`. fn user_entity(name: &str, fsm: bool, record: &str, on_ref: bool) -> Entity { - let record = DataType::Record(ident(record)); + let record = record_type(record); user_entity_with_data_type(name, fsm, record, on_ref) } @@ -101,7 +103,7 @@ fn user_entity_with_data_type(name: &str, fsm: bool, data: DataType, on_ref: boo data }; let mut builder = - EntityBuilder::new(ident(name)).with_event(event("using", [field("claim", ty)])); + EntityBuilder::new(path(name)).with_event(event("using", [field("claim", ty)])); if fsm { builder = builder.with_annotations(fsm_annotations()); } @@ -133,6 +135,20 @@ fn valid_resource_passes() { assert!(resource_errors(&schema("App", vec![memory, worker], vec![bounds, usage])).is_empty()); } +#[test] +fn qualified_resource_paths_pass() { + let memory = resource_entity( + "Foo::Memory", + &[("bytes", "occupancy", true)], + Some("Foo::MemoryBounds"), + ); + let bounds = bounds_record("Foo::MemoryBounds", "Foo::Memory", &["bytes"]); + let usage = usage_record("Foo::MemoryUsage", "Foo::Memory", &["bytes"]); + let worker = user_entity("Bar::Worker", true, "Foo::MemoryUsage", true); + + assert!(resource_errors(&schema("App", [memory, worker], [bounds, usage])).is_empty()); +} + /// A resource with no capacities is accepted as a unit resource. #[test] fn unit_resource_is_accepted() { @@ -257,14 +273,12 @@ fn optional_resource_records_are_accepted() { let memory = resource_entity_with_bounds_type( "Memory", &[("bytes", "occupancy", true)], - Some(DataType::Option(Box::new(DataType::Record(ident( - "MemoryBounds", - ))))), + Some(DataType::Option(Box::new(record_type("MemoryBounds")))), ); let worker = user_entity_with_data_type( "Worker", true, - DataType::Option(Box::new(DataType::Record(ident("MemoryUsage")))), + DataType::Option(Box::new(record_type("MemoryUsage"))), true, ); let bounds = bounds_record("MemoryBounds", "Memory", &["bytes"]); @@ -277,7 +291,7 @@ fn optional_resource_records_are_accepted() { fn listed_resource_references_with_usage_are_accepted() { let memory = resource_entity("Memory", &[("bytes", "occupancy", false)], None); let reference = DataType::EntityRef { - data: Some(Box::new(DataType::Record(ident("MemoryUsage")))), + data: Some(Box::new(record_type("MemoryUsage"))), annotations: Annotations::default(), }; let worker = @@ -293,7 +307,7 @@ fn usage_records_in_list_valued_reference_data_are_rejected() { let worker = user_entity_with_data_type( "Worker", true, - DataType::List(Box::new(DataType::Record(ident("MemoryUsage")))), + DataType::List(Box::new(record_type("MemoryUsage"))), true, ); let usage = usage_record("MemoryUsage", "Memory", &["bytes"]); @@ -311,9 +325,7 @@ fn listed_bounds_records_are_rejected() { let memory = resource_entity_with_bounds_type( "Memory", &[("bytes", "occupancy", true)], - Some(DataType::List(Box::new(DataType::Record(ident( - "MemoryBounds", - ))))), + Some(DataType::List(Box::new(record_type("MemoryBounds")))), ); let bounds = bounds_record("MemoryBounds", "Memory", &["bytes"]); let errors = resource_errors(&schema("App", [memory], [bounds])); @@ -359,7 +371,7 @@ fn misplaced_resources_are_rejected() { let memory = resource_entity("Memory", &[("bytes", "occupancy", false)], None); let usage = usage_record("MemoryUsage", "Memory", &["bytes"]); let carrier = DataType::EntityRef { - data: Some(Box::new(DataType::Record(ident("MemoryUsage")))), + data: Some(Box::new(record_type("MemoryUsage"))), annotations: Annotations::default(), }; let wrapper = RecordBuilder::new(ident("Wrapper")) From bd22bbc4fb98c911943b24c291a98df029400a04 Mon Sep 17 00:00:00 2001 From: Johan Peltenburg Date: Fri, 24 Jul 2026 09:03:36 +0200 Subject: [PATCH 07/12] refactor(yaml): lower type names to paths Signed-off-by: Johan Peltenburg --- crates/yaml/src/lower.rs | 40 ++++++++++++++------------ crates/yaml/tests/fsm.rs | 4 +-- crates/yaml/tests/references.rs | 10 +++---- crates/yaml/tests/resource.rs | 51 ++++++++++++++++----------------- 4 files changed, 53 insertions(+), 52 deletions(-) diff --git a/crates/yaml/src/lower.rs b/crates/yaml/src/lower.rs index ab1a50b96..94f4cfab4 100644 --- a/crates/yaml/src/lower.rs +++ b/crates/yaml/src/lower.rs @@ -22,7 +22,9 @@ use quent_resource::{Capacity, Resource, ResourceBuilder}; use quent_schema::builder::{ AnnotationsBuilder, BuilderError, EntityBuilder, EventBuilder, RecordBuilder, SchemaBuilder, }; -use quent_schema::{Annotations, Cardinality, DataType, Entity, Field, Identifier, Record, Schema}; +use quent_schema::{ + Annotations, Cardinality, DataType, Entity, Field, Identifier, Path, Record, Schema, +}; use serde::Deserialize; use crate::ast::{self, AnnotationMap, Model, TypeExpr}; @@ -110,11 +112,9 @@ pub(crate) fn lower(model: &Model, sink: &mut Diagnostics) -> Option { fn schema_builder_diagnostics(error: &BuilderError, sink: &mut Diagnostics) { match error { - BuilderError::DuplicateName(name) => sink.error( - &format!("records.{name}"), - format!("record `{name}` conflicts with a generated resource record: {error}"), - None, - ), + BuilderError::DuplicateName(name) => { + sink.error("", format!("duplicate type path `{name}`"), None) + } error => sink.error("", error.to_string(), None), } } @@ -309,7 +309,7 @@ fn event_of( name: &str, event: &ast::Event, entity_path: &str, - bounds_record: Option<&Identifier>, + bounds_record: Option<&Path>, resources: &ResourceLowerer, sink: &mut Diagnostics, ) -> Option { @@ -340,7 +340,7 @@ fn event_of( fn event_fields( fields: &IndexMap, path: &str, - bounds_record: Option<&Identifier>, + bounds_record: Option<&Path>, resources: &ResourceLowerer, sink: &mut Diagnostics, ) -> Vec { @@ -473,7 +473,7 @@ fn entity_ref_type( /// A bare name that is not a [`BuiltinType`], lowered as a record reference. fn record_ref(name: &str, path: &str, sink: &mut Diagnostics) -> Option { match Identifier::try_new(name) { - Ok(id) => Some(DataType::Record(id)), + Ok(id) => Some(DataType::Record(id.into())), Err(e) => { sink.error(path, format!("invalid type `{name}`: {e}"), None); None @@ -611,7 +611,7 @@ fn ident(name: &str, path: &str, sink: &mut Diagnostics) -> Option { #[derive(Default)] struct ResourceLowerer { - usage_records: IndexMap, + usage_records: IndexMap, } impl ResourceLowerer { @@ -643,9 +643,9 @@ impl ResourceLowerer { sink: &mut Diagnostics, ) { let record = match resource.usage_record() { - Some(name) => ident(name, &format!("{path}.usage-record"), sink), + Some(name) => ident(name, &format!("{path}.usage-record"), sink).map(Path::from), None => ident(owner, path, sink) - .map(|owner| ResourceBuilder::default_usage_record_name(&owner)), + .map(|owner| ResourceBuilder::default_usage_record_path(&owner.into())), }; if let Some(record) = record { self.usage_records @@ -661,14 +661,18 @@ impl ResourceLowerer { resource: &ast::ResourceDecl, path: &str, sink: &mut Diagnostics, - ) -> (Vec, Option, Option) { + ) -> (Vec, Option, Option) { let resource_path = format!("{path}.resource"); let Some(usage_record_name) = self.usage_records.get(owner).cloned() else { return (Vec::new(), None, None); }; let bounds_record_name = match resource.bounds_record() { - Some(name) => ident(name, &format!("{resource_path}.bounds-record"), sink), - None => Some(ResourceBuilder::default_bounds_record_name(&id)), + Some(name) => { + ident(name, &format!("{resource_path}.bounds-record"), sink).map(Path::from) + } + None => Some(ResourceBuilder::default_bounds_record_path( + &id.clone().into(), + )), }; let Some(bounds_record_name) = bounds_record_name else { return (Vec::new(), None, None); @@ -707,7 +711,7 @@ impl ResourceLowerer { None } }; - let bounds = parts.bounds.as_ref().map(|record| record.name().clone()); + let bounds = parts.bounds.as_ref().map(|record| record.path().clone()); let mut records = vec![parts.usage]; records.extend(parts.bounds); (records, bounds, constraint) @@ -719,7 +723,7 @@ impl ResourceLowerer { } } - fn usage_record(&self, target: &str, path: &str, sink: &mut Diagnostics) -> Option { + fn usage_record(&self, target: &str, path: &str, sink: &mut Diagnostics) -> Option { if let Some(record) = self.usage_records.get(target) { return Some(record.clone()); } @@ -738,7 +742,7 @@ impl ResourceLowerer { /// Reports an error when no bounds record is available. fn bounds_field( name: Option, - bounds_record: Option<&Identifier>, + bounds_record: Option<&Path>, path: &str, sink: &mut Diagnostics, ) -> Option { diff --git a/crates/yaml/tests/fsm.rs b/crates/yaml/tests/fsm.rs index 6672b9803..36e389dfa 100644 --- a/crates/yaml/tests/fsm.rs +++ b/crates/yaml/tests/fsm.rs @@ -4,7 +4,7 @@ //! FSM tests: an `fsms:` block declares an entity whose events are its states, //! deriving their cardinality from the topology and validating it. -use quent_schema::test_utils::ident; +use quent_schema::test_utils::{ident, path}; use quent_schema::{Cardinality, Schema}; use quent_yaml::{Error, parse_from_str}; @@ -43,7 +43,7 @@ fsms: #[test] fn fsm_builds_events_and_derives_cardinality() { let schema = schema_of(QUERY); - let query = schema.entity(&ident("Query")).unwrap(); + let query = schema.entity(&path("Query")).unwrap(); assert!(query.annotations().has_constraint(FSM)); assert_eq!(query.events().count(), 3); // `progress` self-loops, so it is Multi; the others are Once. diff --git a/crates/yaml/tests/references.rs b/crates/yaml/tests/references.rs index e60efde38..7c410c7eb 100644 --- a/crates/yaml/tests/references.rs +++ b/crates/yaml/tests/references.rs @@ -4,7 +4,7 @@ //! Reference tests: `ref:` and `scope-ref:` emit the right constraints and are //! validated against the schema. -use quent_schema::test_utils::ident; +use quent_schema::test_utils::{ident, path}; use quent_schema::{Annotations, Cardinality, DataType, Schema}; use quent_yaml::parse_from_str; @@ -17,7 +17,7 @@ fn schema_of(src: &str) -> Schema { fn cardinality(schema: &Schema, entity: &str, event: &str) -> Cardinality { schema - .entity(&ident(entity)) + .entity(&path(entity)) .unwrap() .event(&ident(event)) .unwrap() @@ -32,7 +32,7 @@ fn ref_annotations<'s>( field: &str, ) -> &'s Annotations { let field = schema - .entity(&ident(entity)) + .entity(&path(entity)) .unwrap() .event(&ident(event)) .unwrap() @@ -92,7 +92,7 @@ entities: Cardinality::Multi ); let field = schema - .entity(&ident("Engine")) + .entity(&path("Engine")) .unwrap() .event(&ident("started")) .unwrap() @@ -129,7 +129,7 @@ entities: ", ); let field = schema - .entity(&ident("Engine")) + .entity(&path("Engine")) .unwrap() .event(&ident("started")) .unwrap() diff --git a/crates/yaml/tests/resource.rs b/crates/yaml/tests/resource.rs index 46026b4e3..a4235a0bf 100644 --- a/crates/yaml/tests/resource.rs +++ b/crates/yaml/tests/resource.rs @@ -5,7 +5,7 @@ //! unit resource), `uses:` claims a resource, and `sets-resource-bounds: true` //! marks an attribute carrying the generated bounds record. -use quent_schema::test_utils::ident; +use quent_schema::test_utils::{ident, path, record_type}; use quent_schema::{DataType, Schema}; use quent_yaml::parse_from_str; @@ -53,7 +53,7 @@ fn resource_declaration_generates_records_and_carries_bounds() { let schema = schema_of(MEMORY_AND_TASK); // The definition rides on the resource entity. - let memory = schema.entity(&ident("Memory")).unwrap(); + let memory = schema.entity(&path("Memory")).unwrap(); assert!(memory.annotations().has_constraint(RESOURCE)); let definition = memory .annotations() @@ -64,9 +64,9 @@ fn resource_declaration_generates_records_and_carries_bounds() { assert!(definition.contains(r#""kind":"rate""#), "{definition}"); // The builder generates the usage and bounds records. - let usage = schema.record(&ident("MemoryUsage")).unwrap(); + let usage = schema.record(&path("MemoryUsage")).unwrap(); assert!(usage.field(&ident("bandwidth")).is_some()); - let bounds = schema.record(&ident("MemoryBounds")).unwrap(); + let bounds = schema.record(&path("MemoryBounds")).unwrap(); assert!(bounds.field(&ident("bandwidth")).is_some()); let field = memory @@ -74,7 +74,7 @@ fn resource_declaration_generates_records_and_carries_bounds() { .unwrap() .field(&ident("limits")) .unwrap(); - assert_eq!(field.ty(), &DataType::Record(ident("MemoryBounds"))); + assert_eq!(field.ty(), &record_type("MemoryBounds")); } #[test] @@ -92,14 +92,14 @@ entities: ); assert!( schema - .entity(&ident("Thread")) + .entity(&path("Thread")) .unwrap() .annotations() .has_constraint(RESOURCE) ); - let usage = schema.record(&ident("ThreadUsage")).unwrap(); + let usage = schema.record(&path("ThreadUsage")).unwrap(); assert_eq!(usage.fields().count(), 0); - assert!(schema.record(&ident("ThreadBounds")).is_none()); + assert!(schema.record(&path("ThreadBounds")).is_none()); } #[test] @@ -117,7 +117,7 @@ fsms: to: [exit] ", ); - let worker = schema.entity(&ident("Worker")).unwrap(); + let worker = schema.entity(&path("Worker")).unwrap(); assert!(worker.annotations().has_constraint(FSM)); assert!(worker.annotations().has_constraint(RESOURCE)); } @@ -140,7 +140,7 @@ fsms: to: [resizing, exit] ", ); - let pool = schema.entity(&ident("Pool")).unwrap(); + let pool = schema.entity(&path("Pool")).unwrap(); assert!(pool.annotations().has_constraint(FSM)); assert!(pool.annotations().has_constraint(RESOURCE)); let field = pool @@ -148,14 +148,14 @@ fsms: .unwrap() .field(&ident("limits")) .unwrap(); - assert_eq!(field.ty(), &DataType::Record(ident("PoolBounds"))); + assert_eq!(field.ty(), &record_type("PoolBounds")); } #[test] fn uses_carries_the_usage_record_on_a_targeted_reference() { let schema = schema_of(MEMORY_AND_TASK); let field = schema - .entity(&ident("Task")) + .entity(&path("Task")) .unwrap() .event(&ident("running")) .unwrap() @@ -164,10 +164,7 @@ fn uses_carries_the_usage_record_on_a_targeted_reference() { let DataType::EntityRef { data, annotations } = field.ty() else { panic!("expected an entity ref, got {:?}", field.ty()); }; - assert_eq!( - data.as_deref(), - Some(&DataType::Record(ident("MemoryUsage"))) - ); + assert_eq!(data.as_deref(), Some(&record_type("MemoryUsage"))); assert_eq!( annotations.constraint(REF_TARGET).unwrap().data(), Some("Memory") @@ -236,24 +233,24 @@ fsms: ", ); - assert!(schema.record(&ident("MemoryUsage")).is_some()); + assert!(schema.record(&path("MemoryUsage")).is_some()); assert!( schema - .record(&ident("MemoryClaim")) + .record(&path("MemoryClaim")) .unwrap() .field(&ident("bytes")) .is_some() ); assert!( schema - .record(&ident("MemoryLimits")) + .record(&path("MemoryLimits")) .unwrap() .field(&ident("bytes")) .is_some() ); let usage = schema - .entity(&ident("Task")) + .entity(&path("Task")) .unwrap() .event(&ident("running")) .unwrap() @@ -262,19 +259,16 @@ fsms: let DataType::EntityRef { data, .. } = usage.ty() else { panic!("expected an entity ref"); }; - assert_eq!( - data.as_deref(), - Some(&DataType::Record(ident("MemoryClaim"))) - ); + assert_eq!(data.as_deref(), Some(&record_type("MemoryClaim"))); let bounds = schema - .entity(&ident("Memory")) + .entity(&path("Memory")) .unwrap() .event(&ident("resized")) .unwrap() .field(&ident("limits")) .unwrap(); - assert_eq!(bounds.ty(), &DataType::Record(ident("MemoryLimits"))); + assert_eq!(bounds.ty(), &record_type("MemoryLimits")); } #[test] @@ -313,7 +307,10 @@ entities: registered: {} ", ); - assert!(errors.contains("generated resource record"), "{errors}"); + assert!( + errors.contains("duplicate type path `MemoryUsage`"), + "{errors}" + ); } #[test] From 0a3716a893baf62a87cb791781a7f90f0a6717a5 Mon Sep 17 00:00:00 2001 From: Johan Peltenburg Date: Fri, 24 Jul 2026 13:12:42 +0200 Subject: [PATCH 08/12] refactor(instrumentation-build): reject qualified type paths Signed-off-by: Johan Peltenburg --- crates/instrumentation-build/src/any_event.rs | 2 +- crates/instrumentation-build/src/data_type.rs | 16 +++--- crates/instrumentation-build/src/events.rs | 4 +- crates/instrumentation-build/src/lib.rs | 57 +++++++++++++++++-- crates/instrumentation-build/src/records.rs | 4 +- .../src/runtime/context.rs | 11 +++- .../src/runtime/handle.rs | 4 +- .../instrumentation-build/src/runtime/mod.rs | 21 +++++-- .../src/runtime/observer.rs | 2 +- 9 files changed, 91 insertions(+), 30 deletions(-) diff --git a/crates/instrumentation-build/src/any_event.rs b/crates/instrumentation-build/src/any_event.rs index 559f64e0d..eaccbb826 100644 --- a/crates/instrumentation-build/src/any_event.rs +++ b/crates/instrumentation-build/src/any_event.rs @@ -28,7 +28,7 @@ pub(crate) fn generate_any_event( let variants: Vec<(Ident, Ident)> = schema .entities() .map(|entity| { - let pascal = to_case(entity.name(), Case::Pascal); + let pascal = to_case(entity.path().name(), Case::Pascal); ( raw_ident(pascal.clone()), raw_ident(format!("{pascal}Event")), diff --git a/crates/instrumentation-build/src/data_type.rs b/crates/instrumentation-build/src/data_type.rs index 235286e23..3250278b7 100644 --- a/crates/instrumentation-build/src/data_type.rs +++ b/crates/instrumentation-build/src/data_type.rs @@ -3,10 +3,9 @@ //! Mapping from schema [`DataType`]s to Rust type tokens. -use convert_case::{Case, Casing}; +use convert_case::Case; use proc_macro2::TokenStream; -use quent_constraints::Constraint; -use quent_ref_target::RefTargetConstraint; +use quent_ref_target::RefTarget; use quent_schema::{Annotations, DataType}; use quote::quote; @@ -52,7 +51,7 @@ pub(crate) fn map_data_type(ty: &DataType, depth: usize) -> TokenStream { quote! { Vec<#inner> } } DataType::Record(name) => { - let ident = raw_ident(to_case(name, Case::Pascal)); + let ident = raw_ident(to_case(name.name(), Case::Pascal)); quote! { #ident } } DataType::DynamicRecord => quote! { ::quent_instrumentation::DynamicAttributes }, @@ -73,12 +72,9 @@ pub(crate) fn map_data_type(ty: &DataType, depth: usize) -> TokenStream { /// ref-target constraint, or the `AnyEntity` marker when it is not restricted /// to a target entity. fn ref_target_marker(annotations: &Annotations) -> TokenStream { - match annotations - .constraint(RefTargetConstraint::NAME) - .and_then(|c| c.data()) - { + match RefTarget::from_annotations(annotations) { Some(entity) => { - let marker = raw_ident(entity.to_case(Case::Pascal)); + let marker = raw_ident(to_case(entity.as_ref().name(), Case::Pascal)); quote! { #marker } } None => quote! { AnyEntity }, @@ -88,6 +84,8 @@ fn ref_target_marker(annotations: &Annotations) -> TokenStream { #[cfg(test)] mod tests { use super::*; + use quent_constraints::Constraint; + use quent_ref_target::RefTargetConstraint; use quent_schema::DataType; #[test] diff --git a/crates/instrumentation-build/src/events.rs b/crates/instrumentation-build/src/events.rs index 4ff56fffa..cdd53c525 100644 --- a/crates/instrumentation-build/src/events.rs +++ b/crates/instrumentation-build/src/events.rs @@ -24,7 +24,7 @@ pub(crate) fn generate_event_types( } fn entity_event_enum(entity: &Entity, opts: &Options) -> Result { - let entity_pascal = to_case(entity.name(), Case::Pascal); + let entity_pascal = to_case(entity.path().name(), Case::Pascal); let enum_ident = raw_ident(format!("{entity_pascal}Event")); let docs = doc_attr_or( entity.annotations().docs(), @@ -91,7 +91,7 @@ mod tests { field("n", DataType::U32), field("opt", DataType::Option(Box::new(DataType::I32))), field("list", DataType::List(Box::new(DataType::String))), - field("rec", DataType::Record(ident("SomeRecord"))), + field("rec", DataType::Record(ident("SomeRecord").into())), field("dynrec", DataType::DynamicRecord), field( "eref", diff --git a/crates/instrumentation-build/src/lib.rs b/crates/instrumentation-build/src/lib.rs index 2f33d0891..435a0d430 100644 --- a/crates/instrumentation-build/src/lib.rs +++ b/crates/instrumentation-build/src/lib.rs @@ -40,6 +40,9 @@ //! //! # Restrictions //! +//! Qualified record and entity paths are not supported; generation fails with +//! [`GenerateError::UnsupportedTypePath`]. +//! //! The schema does not limit how many events an entity declares, but this //! generator caps once-cardinality //! ([`Cardinality::Once`](quent_schema::Cardinality::Once)) events at 64 per @@ -61,7 +64,7 @@ mod runtime; use std::path::PathBuf; use quent_constraints::{BaseConstraintsError, Report, validate}; -use quent_schema::{Identifier, Schema}; +use quent_schema::{Path, Schema}; use quote::quote; use events::generate_event_types; @@ -123,13 +126,18 @@ pub enum GenerateError { }, #[error("generated code did not form a valid Rust file")] InvalidGeneratedCode(#[source] syn::Error), + #[error("qualified type path `{path}` is not supported")] + UnsupportedTypePath { + /// The unsupported record or entity path. + path: Path, + }, #[error( "entity `{entity}` declares {count} once-events, exceeding the maximum of {max}", max = crate::runtime::MAX_ONCE_EVENTS )] TooManyOnceEvents { /// The offending entity. - entity: Identifier, + entity: Path, /// The number of once-cardinality events the entity declares. count: usize, }, @@ -169,9 +177,12 @@ pub fn generate(schema: &Schema, opts: &Options) -> Result Result { + ensure_unqualified_type_paths(schema)?; + // record structs, event enums, then the live instrumentation surface let reexports = runtime::reexports(); let records = generate_record_types(schema, opts)?; @@ -186,3 +197,41 @@ pub fn generate_str(schema: &Schema, opts: &Options) -> Result Result<(), GenerateError> { + let qualified = schema + .records() + .map(|record| record.path()) + .chain(schema.entities().map(|entity| entity.path())) + .find(|path| !path.namespace().is_empty()); + + match qualified { + Some(path) => Err(GenerateError::UnsupportedTypePath { path: path.clone() }), + None => Ok(()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use quent_schema::test_utils::{entity, event, record, schema}; + + #[test] + fn rejects_qualified_type_paths() { + let schemas = [ + ( + schema("M", [entity("Foo::E", [event("ev", [])])], []), + "Foo::E", + ), + (schema("M", [], [record("Foo::R", [])]), "Foo::R"), + ]; + + for (schema, expected) in schemas { + let error = generate_str(&schema, &Options::default()).unwrap_err(); + let GenerateError::UnsupportedTypePath { path } = error else { + panic!("unexpected error: {error}"); + }; + assert_eq!(path, expected); + } + } +} diff --git a/crates/instrumentation-build/src/records.rs b/crates/instrumentation-build/src/records.rs index 6727777a2..103000c61 100644 --- a/crates/instrumentation-build/src/records.rs +++ b/crates/instrumentation-build/src/records.rs @@ -29,7 +29,7 @@ pub(crate) fn generate_record_types( } fn record_struct(record: &Record, opts: &Options) -> Result { - let record_pascal = to_case(record.name(), Case::Pascal); + let record_pascal = to_case(record.path().name(), Case::Pascal); let ident = raw_ident(record_pascal.clone()); let docs = doc_attr_or( record.annotations().docs(), @@ -75,7 +75,7 @@ mod tests { record( "Nested", [ - field("inner", DataType::Record(ident("OnePrim"))), + field("inner", DataType::Record(ident("OnePrim").into())), field("list", DataType::List(Box::new(DataType::String))), ], ), diff --git a/crates/instrumentation-build/src/runtime/context.rs b/crates/instrumentation-build/src/runtime/context.rs index 00188fcc1..a7c444ac4 100644 --- a/crates/instrumentation-build/src/runtime/context.rs +++ b/crates/instrumentation-build/src/runtime/context.rs @@ -20,20 +20,25 @@ pub(super) fn schema_context(schema: &Schema) -> TokenStream { let fields: Vec<_> = schema .entities() - .map(|e| raw_ident(to_case(e.name(), Case::Snake))) + .map(|e| raw_ident(to_case(e.path().name(), Case::Snake))) .collect(); let observer_tys: Vec<_> = schema.entities().map(observer_ident).collect(); let event_tys: Vec<_> = schema.entities().map(event_ident).collect(); let accessors: Vec<_> = schema .entities() - .map(|e| raw_ident(format!("{}_observer", to_case(e.name(), Case::Snake)))) + .map(|e| { + raw_ident(format!( + "{}_observer", + to_case(e.path().name(), Case::Snake) + )) + }) .collect(); let accessor_docs: Vec = schema .entities() .map(|e| { format!( "Observer for `{}` entities.", - to_case(e.name(), Case::Pascal) + to_case(e.path().name(), Case::Pascal) ) }) .collect(); diff --git a/crates/instrumentation-build/src/runtime/handle.rs b/crates/instrumentation-build/src/runtime/handle.rs index 0c8a9898c..9f5ff4b02 100644 --- a/crates/instrumentation-build/src/runtime/handle.rs +++ b/crates/instrumentation-build/src/runtime/handle.rs @@ -24,7 +24,7 @@ pub(crate) const MAX_ONCE_EVENTS: usize = u64::BITS as usize; /// Returns [`GenerateError::TooManyOnceEvents`] if the entity declares more /// once-cardinality events than fit the once-flag word. pub(super) fn entity_handle(entity: &Entity) -> Result { - let entity_pascal = to_case(entity.name(), Case::Pascal); + let entity_pascal = to_case(entity.path().name(), Case::Pascal); let event_ty = event_ident(entity); let handle_ty = handle_ident(entity); let marker_ty = marker_ident(entity); @@ -35,7 +35,7 @@ pub(super) fn entity_handle(entity: &Entity) -> Result MAX_ONCE_EVENTS { return Err(GenerateError::TooManyOnceEvents { - entity: entity.name().clone(), + entity: entity.path().clone(), count: once_count, }); } diff --git a/crates/instrumentation-build/src/runtime/mod.rs b/crates/instrumentation-build/src/runtime/mod.rs index c0055a2f7..380ff6751 100644 --- a/crates/instrumentation-build/src/runtime/mod.rs +++ b/crates/instrumentation-build/src/runtime/mod.rs @@ -68,7 +68,7 @@ fn entity_marker(entity: &Entity) -> TokenStream { let marker = marker_ident(entity); let doc = format!( "Marker type for the `{}` entity.", - to_case(entity.name(), Case::Pascal) + to_case(entity.path().name(), Case::Pascal) ); quote! { #[doc = #doc] @@ -80,7 +80,7 @@ fn entity_marker(entity: &Entity) -> TokenStream { /// Tie an entity's event enum to its stream name (the entity's snake-case name). fn entity_event_impl(entity: &Entity) -> TokenStream { let event_ty = event_ident(entity); - let stream_name = to_case(entity.name(), Case::Snake); + let stream_name = to_case(entity.path().name(), Case::Snake); quote! { impl ::quent_instrumentation::EntityEvent for #event_ty { const NAME: &'static str = #stream_name; @@ -90,22 +90,31 @@ fn entity_event_impl(entity: &Entity) -> TokenStream { /// `{Entity}Event` — the entity's event enum. fn event_ident(entity: &Entity) -> Ident { - raw_ident(format!("{}Event", to_case(entity.name(), Case::Pascal))) + raw_ident(format!( + "{}Event", + to_case(entity.path().name(), Case::Pascal) + )) } /// `{Entity}` — the entity's ref-target marker type. fn marker_ident(entity: &Entity) -> Ident { - raw_ident(to_case(entity.name(), Case::Pascal)) + raw_ident(to_case(entity.path().name(), Case::Pascal)) } /// `{Entity}Observer`. fn observer_ident(entity: &Entity) -> Ident { - raw_ident(format!("{}Observer", to_case(entity.name(), Case::Pascal))) + raw_ident(format!( + "{}Observer", + to_case(entity.path().name(), Case::Pascal) + )) } /// `{Entity}Handle`. fn handle_ident(entity: &Entity) -> Ident { - raw_ident(format!("{}Handle", to_case(entity.name(), Case::Pascal))) + raw_ident(format!( + "{}Handle", + to_case(entity.path().name(), Case::Pascal) + )) } #[cfg(test)] diff --git a/crates/instrumentation-build/src/runtime/observer.rs b/crates/instrumentation-build/src/runtime/observer.rs index 3b510706a..ab9f8d680 100644 --- a/crates/instrumentation-build/src/runtime/observer.rs +++ b/crates/instrumentation-build/src/runtime/observer.rs @@ -13,7 +13,7 @@ use crate::common::to_case; /// Generate the declaration of an {Entity}Observer and its impls. pub(super) fn entity_observer(entity: &Entity) -> TokenStream { - let entity_pascal = to_case(entity.name(), Case::Pascal); + let entity_pascal = to_case(entity.path().name(), Case::Pascal); let event_ty = event_ident(entity); let observer_ty = observer_ident(entity); let handle_ty = handle_ident(entity); From 1a4f09639e29b44ea8d0d7cc1884e6a06d5a075b Mon Sep 17 00:00:00 2001 From: Johan Peltenburg Date: Fri, 24 Jul 2026 13:28:42 +0200 Subject: [PATCH 09/12] test(instrumentation-build): remove temporary path rejection test Signed-off-by: Johan Peltenburg --- crates/instrumentation-build/src/lib.rs | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/crates/instrumentation-build/src/lib.rs b/crates/instrumentation-build/src/lib.rs index 435a0d430..00b67533e 100644 --- a/crates/instrumentation-build/src/lib.rs +++ b/crates/instrumentation-build/src/lib.rs @@ -210,28 +210,3 @@ fn ensure_unqualified_type_paths(schema: &Schema) -> Result<(), GenerateError> { None => Ok(()), } } - -#[cfg(test)] -mod tests { - use super::*; - use quent_schema::test_utils::{entity, event, record, schema}; - - #[test] - fn rejects_qualified_type_paths() { - let schemas = [ - ( - schema("M", [entity("Foo::E", [event("ev", [])])], []), - "Foo::E", - ), - (schema("M", [], [record("Foo::R", [])]), "Foo::R"), - ]; - - for (schema, expected) in schemas { - let error = generate_str(&schema, &Options::default()).unwrap_err(); - let GenerateError::UnsupportedTypePath { path } = error else { - panic!("unexpected error: {error}"); - }; - assert_eq!(path, expected); - } - } -} From 325d1f58719f9af54dd2662e8349ec2df3e2b16e Mon Sep 17 00:00:00 2001 From: Johan Peltenburg Date: Fri, 24 Jul 2026 13:33:18 +0200 Subject: [PATCH 10/12] refactor(schema): derive TypeScript path binding Signed-off-by: Johan Peltenburg --- crates/schema/Cargo.toml | 6 +++++- crates/schema/src/schema/path.rs | 24 ++---------------------- 2 files changed, 7 insertions(+), 23 deletions(-) diff --git a/crates/schema/Cargo.toml b/crates/schema/Cargo.toml index 79dc74138..a69cd2ac5 100644 --- a/crates/schema/Cargo.toml +++ b/crates/schema/Cargo.toml @@ -17,7 +17,11 @@ rustc-hash = { workspace = true } serde = { workspace = true, optional = true } smallvec = { workspace = true, optional = true } thiserror = { workspace = true } -ts-rs = { workspace = true, optional = true, features = ["format", "indexmap-impl"] } +ts-rs = { workspace = true, optional = true, features = [ + "format", + "indexmap-impl", + "no-serde-warnings", +] } [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/schema/src/schema/path.rs b/crates/schema/src/schema/path.rs index 29c722e6a..ac206774e 100644 --- a/crates/schema/src/schema/path.rs +++ b/crates/schema/src/schema/path.rs @@ -12,30 +12,10 @@ use crate::Identifier; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(try_from = "Vec"))] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[cfg_attr(feature = "ts", ts(as = "Vec"))] pub struct Path(Vec); -#[cfg(feature = "ts")] -impl ts_rs::TS for Path { - type WithoutGenerics = Self; - type OptionInnerType = Self; - - fn name(_: &ts_rs::Config) -> String { - "Path".to_owned() - } - - fn inline(config: &ts_rs::Config) -> String { - format!("Array<{}>", Identifier::inline(config)) - } - - fn decl(config: &ts_rs::Config) -> String { - format!("type Path = {};", Self::inline(config)) - } - - fn output_path() -> Option { - Some("Path.ts".into()) - } -} - /// Reason a path failed validation. #[derive(Debug, Clone, PartialEq, Eq, Error)] pub enum PathError { From 41aaff1f5f96ea875f2b4031892eb63208bdba00 Mon Sep 17 00:00:00 2001 From: Johan Peltenburg Date: Fri, 24 Jul 2026 13:56:51 +0200 Subject: [PATCH 11/12] docs(schema): clarify path-based APIs Signed-off-by: Johan Peltenburg --- crates/schema/src/builder/entity.rs | 2 +- crates/schema/src/builder/record.rs | 2 +- crates/schema/src/schema/data_type.rs | 6 ++---- crates/schema/src/schema/mod.rs | 4 ++-- crates/schema/src/test_utils.rs | 7 +++++-- 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/schema/src/builder/entity.rs b/crates/schema/src/builder/entity.rs index a815a0507..281d2bea3 100644 --- a/crates/schema/src/builder/entity.rs +++ b/crates/schema/src/builder/entity.rs @@ -12,7 +12,7 @@ pub struct EntityBuilder { } impl EntityBuilder { - /// Start an entity named `name`. + /// Starts an entity whose identity is the supplied qualified path. pub fn new(path: impl Into) -> Self { Self { path: path.into(), diff --git a/crates/schema/src/builder/record.rs b/crates/schema/src/builder/record.rs index 81f113f43..612f79bc9 100644 --- a/crates/schema/src/builder/record.rs +++ b/crates/schema/src/builder/record.rs @@ -12,7 +12,7 @@ pub struct RecordBuilder { } impl RecordBuilder { - /// Start a record named `name`. + /// Starts a record at the supplied qualified path. pub fn new(path: impl Into) -> Self { Self { path: path.into(), diff --git a/crates/schema/src/schema/data_type.rs b/crates/schema/src/schema/data_type.rs index a357088f3..833a5ee77 100644 --- a/crates/schema/src/schema/data_type.rs +++ b/crates/schema/src/schema/data_type.rs @@ -24,11 +24,9 @@ pub enum DataType { F64, Option(Box), List(Box), - /// A reference to a named [`crate::record::Record`]. + /// A reference to the [`crate::Record`] declared at the exact path. /// - /// The top-level [`crate::Schema::records`] field must contain a - /// [`crate::record::Record`] with this name, otherwise the - /// [`crate::Schema`] is ill-formed. + /// The [`crate::Schema`] is ill-formed if no record is declared at this path. Record(Path), /// A record whose fields are determined by the instrumentation client at /// run-time. diff --git a/crates/schema/src/schema/mod.rs b/crates/schema/src/schema/mod.rs index 2da1c7876..d54dfac03 100644 --- a/crates/schema/src/schema/mod.rs +++ b/crates/schema/src/schema/mod.rs @@ -65,7 +65,7 @@ impl Schema { &self.annotations } - /// The entity declared under `name`, if any. + /// Returns the entity declared at `path`, if any. pub fn entity(&self, path: &Path) -> Option<&Entity> { self.entities.get(path) } @@ -75,7 +75,7 @@ impl Schema { self.entities.values() } - /// The record declared under `name`, if any. + /// Returns the record declared at `path`, if any. pub fn record(&self, path: &Path) -> Option<&Record> { self.records.get(path) } diff --git a/crates/schema/src/test_utils.rs b/crates/schema/src/test_utils.rs index 4dd63e89f..d9bfdf607 100644 --- a/crates/schema/src/test_utils.rs +++ b/crates/schema/src/test_utils.rs @@ -17,11 +17,13 @@ use crate::{ pub fn ident(s: &str) -> Identifier { Identifier::try_new(s).unwrap() } +/// Parses a schema path, panicking if it is invalid. pub fn path(s: &str) -> Path { s.parse().unwrap() } -pub fn record_type(name: &str) -> DataType { - DataType::Record(path(name)) +/// Constructs a record-reference data type, panicking if the path is invalid. +pub fn record_type(s: &str) -> DataType { + DataType::Record(path(s)) } pub fn field(name: &str, ty: DataType) -> Field { Field::new(ident(name), ty, Annotations::default()) @@ -66,6 +68,7 @@ pub fn schema( .unwrap() } +/// Constructs a schema without applying [`SchemaBuilder`] validation. pub fn unchecked_schema( name: &str, entities: impl IntoIterator, From b30c84138afcf62d0d679fad8e2b9b5ce8c738be Mon Sep 17 00:00:00 2001 From: Johan Peltenburg Date: Fri, 24 Jul 2026 15:10:10 +0200 Subject: [PATCH 12/12] refactor(schema): store path name separately Signed-off-by: Johan Peltenburg --- crates/resource/tests/resource-constraint.rs | 16 ++-- crates/schema/Cargo.toml | 6 +- crates/schema/src/schema/path.rs | 88 ++++++++------------ 3 files changed, 48 insertions(+), 62 deletions(-) diff --git a/crates/resource/tests/resource-constraint.rs b/crates/resource/tests/resource-constraint.rs index 5c595ef3a..533ed6588 100644 --- a/crates/resource/tests/resource-constraint.rs +++ b/crates/resource/tests/resource-constraint.rs @@ -3,7 +3,7 @@ use quent_constraints::Constraint as _; use quent_fsm::FsmConstraint; -use quent_resource::{ResourceConstraint, ResourceError}; +use quent_resource::{Resource, ResourceConstraint, ResourceError}; use quent_schema::{ Annotations, DataType, Entity, Record, Schema, builder::{AnnotationsBuilder, EntityBuilder, RecordBuilder, SchemaBuilder}, @@ -25,13 +25,19 @@ fn definition_data(capacities: &[(&str, &str, bool)]) -> String { } fn usage_data(resource: &str) -> String { - let resource: Vec<_> = resource.split("::").collect(); - serde_json::json!({ "usage": { "resource": resource } }).to_string() + Resource::Usage { + resource: path(resource), + } + .constraint_data() + .unwrap() } fn bounds_data(resource: &str) -> String { - let resource: Vec<_> = resource.split("::").collect(); - serde_json::json!({ "bounds": { "resource": resource } }).to_string() + Resource::Bounds { + resource: path(resource), + } + .constraint_data() + .unwrap() } /// Create resource constraint annotations carrying `data`. diff --git a/crates/schema/Cargo.toml b/crates/schema/Cargo.toml index a69cd2ac5..79dc74138 100644 --- a/crates/schema/Cargo.toml +++ b/crates/schema/Cargo.toml @@ -17,11 +17,7 @@ rustc-hash = { workspace = true } serde = { workspace = true, optional = true } smallvec = { workspace = true, optional = true } thiserror = { workspace = true } -ts-rs = { workspace = true, optional = true, features = [ - "format", - "indexmap-impl", - "no-serde-warnings", -] } +ts-rs = { workspace = true, optional = true, features = ["format", "indexmap-impl"] } [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/schema/src/schema/path.rs b/crates/schema/src/schema/path.rs index ac206774e..e20265606 100644 --- a/crates/schema/src/schema/path.rs +++ b/crates/schema/src/schema/path.rs @@ -9,12 +9,13 @@ use thiserror::Error; use crate::Identifier; /// A nonempty absolute path of identifier segments. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "serde", serde(try_from = "Vec"))] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] -#[cfg_attr(feature = "ts", ts(as = "Vec"))] -pub struct Path(Vec); +pub struct Path { + namespace: Vec, + name: Identifier, +} /// Reason a path failed validation. #[derive(Debug, Clone, PartialEq, Eq, Error)] @@ -32,45 +33,43 @@ pub enum PathError { } impl Path { - /// Returns all path segments. - pub fn segments(&self) -> &[Identifier] { - &self.0 - } - /// Returns the segments preceding the path name. pub fn namespace(&self) -> &[Identifier] { - &self.0[..self.0.len() - 1] + &self.namespace } /// Returns the final path segment. pub fn name(&self) -> &Identifier { - self.0.last().expect("Path guarantees at least one segment") + &self.name } /// Returns this path with its final segment replaced. pub fn with_name(&self, name: Identifier) -> Self { - let mut segments = self.0.clone(); - *segments - .last_mut() - .expect("Path guarantees at least one segment") = name; - Self(segments) + Self { + namespace: self.namespace.clone(), + name, + } } } impl From for Path { - fn from(identifier: Identifier) -> Self { - Self(vec![identifier]) + fn from(name: Identifier) -> Self { + Self { + namespace: Vec::new(), + name, + } } } impl TryFrom> for Path { type Error = PathError; - fn try_from(segments: Vec) -> Result { - if segments.is_empty() { - return Err(PathError::Empty); - } - Ok(Self(segments)) + fn try_from(mut segments: Vec) -> Result { + let name = segments.pop().ok_or(PathError::Empty)?; + Ok(Self { + namespace: segments, + name, + }) } } @@ -95,24 +94,19 @@ impl FromStr for Path { impl Display for Path { fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result { - let mut segments = self.0.iter(); - formatter.write_str( - segments - .next() - .expect("Path guarantees at least one segment"), - )?; - for segment in segments { - write!(formatter, "::{segment}")?; + for segment in &self.namespace { + write!(formatter, "{segment}::")?; } - Ok(()) + formatter.write_str(&self.name) } } impl PartialEq for Path { fn eq(&self, other: &str) -> bool { let mut other_segments = other.split("::"); - self.0 + self.namespace .iter() + .chain(std::iter::once(&self.name)) .all(|segment| other_segments.next().is_some_and(|other| segment == other)) && other_segments.next().is_none() } @@ -124,21 +118,18 @@ impl PartialEq<&str> for Path { } } -impl<'a> IntoIterator for &'a Path { - type Item = &'a Identifier; - type IntoIter = std::slice::Iter<'a, Identifier>; - - fn into_iter(self) -> Self::IntoIter { - self.0.iter() +impl PartialOrd for Path { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) } } -impl IntoIterator for Path { - type Item = Identifier; - type IntoIter = std::vec::IntoIter; - - fn into_iter(self) -> Self::IntoIter { - self.0.into_iter() +impl Ord for Path { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.namespace + .iter() + .chain(std::iter::once(&self.name)) + .cmp(other.namespace.iter().chain(std::iter::once(&other.name))) } } @@ -151,16 +142,9 @@ mod tests { fn constructs_and_inspects_paths() { let path = Path::try_from(vec![ident("Foo"), ident("Query")]).unwrap(); - assert_eq!(path.segments(), &[ident("Foo"), ident("Query")]); assert_eq!(path.namespace(), &[ident("Foo")]); assert_eq!(path.name(), "Query"); assert_eq!(path.with_name(ident("Result")).to_string(), "Foo::Result"); - assert_eq!( - path.into_iter() - .map(|segment| segment.to_string()) - .collect::>(), - ["Foo", "Query"] - ); } #[test]