diff --git a/aimdb-core/CHANGELOG.md b/aimdb-core/CHANGELOG.md index 9ef078d9..4dfcb6fe 100644 --- a/aimdb-core/CHANGELOG.md +++ b/aimdb-core/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking — typed record keys (design 063) - Add TypedName, TypedKey and Name. Record registration, handles, direct reads/writes, transforms and joins infer payloads from declarations. Remove bare-string typed access and public schema setters. +- Add a schema type-state: `TypedKey::Schema` (`Declared` / `Undeclared`), `SchemaState`, `ContractDeclared`, and a third parameter on `RecordRegistrar<'a, T, S = Undeclared>`. `configure` hands out the key's state. `Input` / `Output` take the state as a parameter (`impl Input for MyInput`). `ContractOutboundLink` / `ContractInboundLink` (from `into_contract()`) wire only into `ContractDeclared` records. `Name` gains `Debug`. ### Added — value envelopes (design 062) diff --git a/aimdb-core/src/builder.rs b/aimdb-core/src/builder.rs index c0935eae..6b3a1e64 100644 --- a/aimdb-core/src/builder.rs +++ b/aimdb-core/src/builder.rs @@ -510,7 +510,8 @@ impl AimDbBuilder { /// ```rust,ignore /// let mut b = AimDbBuilder::new().runtime(rt); /// let mqtt = b.connect(MqttConnector::new("mqtt://broker.local:1883")); - /// let record_3 = aimdb_core::Name::::new("temp.indoor"); + /// // A contract record is declared with `Key`, which carries its schema. + /// let record_3 = aimdb_data_contracts::Key::::new("temp.indoor"); /// b.configure(record_3, |r| { /// // A contract (`Linkable`) brings its own wire format: /// r.output(aimdb_data_contracts::publish(mqtt, "sensors/temp/indoor")); @@ -557,7 +558,7 @@ impl AimDbBuilder { pub fn configure( &mut self, key: K, - f: impl FnOnce(&mut RecordRegistrar<'_, K::Contract>), + f: impl FnOnce(&mut RecordRegistrar<'_, K::Contract, K::Schema>), ) -> &mut Self { type Payload = ::Contract; // Convert any RecordKey to StringKey for internal storage @@ -632,6 +633,7 @@ impl AimDbBuilder { key_link_address: key.link_address().map(ToString::to_string), extensions: &self.extensions, last_stage: None, + _schema: core::marker::PhantomData, }; if let Some((name, version)) = K::SCHEMA { reg.rec.set_schema(name, version); diff --git a/aimdb-core/src/lib.rs b/aimdb-core/src/lib.rs index 0b4dffb1..273549a3 100644 --- a/aimdb-core/src/lib.rs +++ b/aimdb-core/src/lib.rs @@ -214,7 +214,10 @@ pub use topic_pattern::{ pub use inbound_key::KeyId; // Record identification exports -pub use record_id::{Name, RecordId, RecordKey, StringKey, TypedKey, TypedName}; +pub use record_id::{ + ContractDeclared, Declared, Name, RecordId, RecordKey, SchemaState, StringKey, TypedKey, + TypedName, Undeclared, +}; // Graph exports (dependency graph for record topology) pub use graph::{DependencyGraph, EdgeType, GraphEdge, GraphNode, RecordOrigin}; diff --git a/aimdb-core/src/record_id.rs b/aimdb-core/src/record_id.rs index ff75e9d4..51799713 100644 --- a/aimdb-core/src/record_id.rs +++ b/aimdb-core/src/record_id.rs @@ -638,8 +638,8 @@ mod tests { } #[test] - fn test_static_str_record_key() { - // &'static str implements RecordKey + fn test_name_record_key() { + // A `Name` with a static name implements RecordKey let key = Name::::new("sensors.temp"); assert_eq!(key.as_str(), "sensors.temp"); } @@ -725,7 +725,45 @@ pub trait TypedKey: TypedName + RecordKey + Copy { /// Contract name and version reported as the record's schema; `None` for /// a record without a data contract. const SCHEMA: Option<(&'static str, u32)>; + /// [`Declared`] when [`SCHEMA`](Self::SCHEMA) is `Some`, [`Undeclared`] + /// otherwise. `configure` hands out a registrar in this state, so + /// contract-only verbs (`linked_to`, `publish`, `observe`, …) exist only + /// on records whose key declares their contract. + type Schema: SchemaState; } + +mod sealed { + pub trait Sealed {} +} + +/// Whether a record's key declares a data contract: [`Declared`] or +/// [`Undeclared`]. The third type parameter of +/// [`RecordRegistrar`](crate::typed_api::RecordRegistrar). +pub trait SchemaState: sealed::Sealed + Send + Sync + 'static {} + +/// The record's key declares its contract (`Key`, +/// `#[record_key(contract = T)]`): contract-only verbs are available. +#[derive(Debug)] +pub enum Declared {} + +/// The record's key declares no contract (`Name`, +/// `#[record_key(payload = T)]`): contract-only verbs do not compile. +#[derive(Debug)] +pub enum Undeclared {} + +impl sealed::Sealed for Declared {} +impl sealed::Sealed for Undeclared {} +impl SchemaState for Declared {} +impl SchemaState for Undeclared {} + +/// Implemented only by [`Declared`]: the bound contract-only verbs put on a +/// registrar's schema state. +#[diagnostic::on_unimplemented( + message = "this record's key declares no data contract", + note = "contract verbs (`linked_to`, `linked_from`, `publish`, `subscribe`, `observe`) need the record declared with `Key` or `#[record_key(contract = T)]`, not `Name` or `payload = T`" +)] +pub trait ContractDeclared: SchemaState {} +impl ContractDeclared for Declared {} /// A record name with its payload type and no data contract. /// /// `Name<'static, T>` is a key: a `const` for a record without a contract, or @@ -775,6 +813,11 @@ impl core::hash::Hash for Name<'_, T> { self.name.hash(state) } } +impl core::fmt::Debug for Name<'_, T> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(self.name) + } +} impl core::borrow::Borrow for Name<'_, T> { fn borrow(&self) -> &str { self.name @@ -796,6 +839,7 @@ impl RecordKey for Name<'static, T> { } impl TypedKey for Name<'static, T> { const SCHEMA: Option<(&'static str, u32)> = None; + type Schema = Undeclared; } impl AsRef for Name<'_, T> { fn as_ref(&self) -> &str { diff --git a/aimdb-core/src/typed_api.rs b/aimdb-core/src/typed_api.rs index 48094697..3315d56d 100644 --- a/aimdb-core/src/typed_api.rs +++ b/aimdb-core/src/typed_api.rs @@ -466,7 +466,20 @@ pub enum StageKind { /// Registrar for configuring a typed record /// /// Provides a fluent API for registering producer and consumer functions. -pub struct RecordRegistrar<'a, T: Send + Sync + 'static + Debug + Clone> { +/// +/// `S` is the record's [`SchemaState`](crate::SchemaState): `configure` +/// hands out [`Declared`](crate::Declared) for a key that declares a data +/// contract (`Key`, `#[record_key(contract = T)]`) and +/// [`Undeclared`](crate::Undeclared) otherwise. Contract-only verbs +/// (`linked_to`, `publish`, `observe`, …) are implemented only for +/// `Declared`, so using one on a `Name` record does not compile. +/// Everything else works in both states; extension traits implement for any +/// `S: SchemaState`. +pub struct RecordRegistrar< + 'a, + T: Send + Sync + 'static + Debug + Clone, + S: crate::SchemaState = crate::Undeclared, +> { /// The typed record being configured pub(crate) rec: &'a mut TypedRecord, /// Connector builders indexed by scheme @@ -484,9 +497,10 @@ pub struct RecordRegistrar<'a, T: Send + Sync + 'static + Debug + Clone> { /// Tracked even when the `observability` feature is off (then it's just unused). #[cfg_attr(not(feature = "observability"), allow(dead_code))] pub(crate) last_stage: Option<(StageKind, usize)>, + pub(crate) _schema: core::marker::PhantomData S>, } -impl<'a, T> RecordRegistrar<'a, T> +impl<'a, T, S: crate::SchemaState> RecordRegistrar<'a, T, S> where T: Send + Sync + 'static + Debug + Clone, { @@ -552,9 +566,10 @@ where /// Sets the data-contract schema this record carries, reported in the /// dependency graph (`graph.nodes`) and in `record.list`. /// - /// `aimdb-data-contracts` calls this from `SchemaType` (`linked_to`, - /// `linked_from`, `observe`, `contract_schema`). Setting the same schema - /// again does nothing; a different one fails `build()`. + /// Only `configure` calls this, from the key's [`TypedKey::SCHEMA`](crate::TypedKey::SCHEMA): + /// the key is the one source of a record's schema (063). Setting the same + /// schema again does nothing; a different one fails `build()`. + #[cfg(test)] pub(crate) fn schema(&mut self, name: &str, version: u32) -> &mut Self { self.rec.set_schema(name, version); self @@ -721,13 +736,13 @@ where } /// Builds a link using the address declared on this record's typed key. /// A missing address is reported by `build()`. - pub fn link_to_key(&mut self) -> OutboundConnectorBuilder<'_, 'a, T> { + pub fn link_to_key(&mut self) -> OutboundConnectorBuilder<'_, 'a, T, S> { let address = self.key_link_address.clone().unwrap_or_default(); self.link_to(&address) } /// Builds a link using the address declared on this record's typed key. /// A missing address is reported by `build()`. - pub fn link_from_key(&mut self) -> InboundConnectorBuilder<'_, 'a, T> { + pub fn link_from_key(&mut self) -> InboundConnectorBuilder<'_, 'a, T, S> { let address = self.key_link_address.clone().unwrap_or_default(); self.link_from(&address) } @@ -735,14 +750,14 @@ where /// Link TO external system (outbound: AimDB → External) /// /// Subscribes to buffer updates and publishes them to an external system. - pub fn link_to(&mut self, url: &str) -> OutboundConnectorBuilder<'_, 'a, T> { + pub fn link_to(&mut self, url: &str) -> OutboundConnectorBuilder<'_, 'a, T, S> { OutboundLink::new(url).attach(self) } /// Link FROM external system (inbound: External → AimDB) /// /// Subscribes to an external data source and produces values into this record's buffer. - pub fn link_from(&mut self, url: &str) -> InboundConnectorBuilder<'_, 'a, T> { + pub fn link_from(&mut self, url: &str) -> InboundConnectorBuilder<'_, 'a, T, S> { InboundLink::new(url).attach(self) } @@ -752,7 +767,7 @@ where /// Conflicting writers are reported by `build()`, exactly as for /// `.source()` and `.link_from()`; several inbound links on one record /// are allowed (fan-in). - pub fn input(&mut self, input: impl Input) -> &mut Self { + pub fn input(&mut self, input: impl Input) -> &mut Self { input.wire(self); self } @@ -762,7 +777,7 @@ where /// Takes anything implementing [`Output`], such as an /// [`OutboundLink`]. A following [`with_name`](Self::with_name) names the /// stage the output registered, as after `.link_to(..).finish()`. - pub fn output(&mut self, output: impl Output) -> &mut Self { + pub fn output(&mut self, output: impl Output) -> &mut Self { output.wire(self); self } @@ -795,11 +810,11 @@ where /// /// Produces 0, 1, 2 into any record built from an `i32`. /// struct Counter; /// -/// impl Input for Counter +/// impl Input for Counter /// where /// T: From + Send + Sync + 'static + Debug + Clone, /// { -/// fn wire(self, reg: &mut RecordRegistrar<'_, T>) { +/// fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { /// reg.source(|_ctx, producer| async move { /// for i in 0..3 { /// producer.produce(T::from(i)); @@ -820,11 +835,11 @@ where /// /// An input on one channel. /// struct Sensor(Channel); /// -/// impl Input for Sensor +/// impl Input for Sensor /// where /// T: From + Send + Sync + 'static + Debug + Clone, /// { -/// fn wire(self, reg: &mut RecordRegistrar<'_, T>) { +/// fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { /// reg.source(|_ctx, producer| async move { producer.produce(T::from(0)) }); /// } /// } @@ -852,9 +867,9 @@ where label = "not an input for `{T}`", note = "an input implements `Input<{T}>`; device inputs usually do so for every `T: From`" )] -pub trait Input { +pub trait Input { /// Registers this input's writer on the record. - fn wire(self, reg: &mut RecordRegistrar<'_, T>); + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>); } /// Something that can read from a `T` record, passed to @@ -866,29 +881,51 @@ pub trait Input { message = "`{Self}` cannot be an output of a `{T}` record", label = "not an output for `{T}`" )] -pub trait Output { +pub trait Output { /// Registers this output's reader on the record. - fn wire(self, reg: &mut RecordRegistrar<'_, T>); + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>); } -impl Input for InboundLink +impl Input for InboundLink where T: Send + Sync + 'static + Debug + Clone, { - fn wire(self, reg: &mut RecordRegistrar<'_, T>) { + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { reg.push_inbound(self); } } -impl Output for OutboundLink +impl Output for OutboundLink where T: Send + Sync + 'static + Debug + Clone, { - fn wire(self, reg: &mut RecordRegistrar<'_, T>) { + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { reg.push_outbound(self); } } +/// A contract link is an input only of a record whose key declares the +/// contract: `subscribe(..)` on a `Name` record does not compile. +impl Input for ContractInboundLink +where + T: Send + Sync + 'static + Debug + Clone, +{ + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { + reg.push_inbound(self.attach(Detached)); + } +} + +/// A contract link is an output only of a record whose key declares the +/// contract: `publish(..)` on a `Name` record does not compile. +impl Output for ContractOutboundLink +where + T: Send + Sync + 'static + Debug + Clone, +{ + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { + reg.push_outbound(self.attach(Detached)); + } +} + // ============================================================================ // Link builders - Fluent connector link configuration // ============================================================================ @@ -899,18 +936,32 @@ where #[derive(Debug, Clone, Copy, Default)] pub struct Detached; +/// Marks a detached link that carries a data contract: what +/// `aimdb-data-contracts`' `publish` / `subscribe` return. +/// +/// It takes every option a [`Detached`] link takes, but is an +/// [`Input`] / [`Output`] only of a record whose key declares the contract +/// ([`ContractDeclared`](crate::ContractDeclared)). +#[derive(Debug, Clone, Copy, Default)] +pub struct DetachedContract; + /// Outbound link builder attached to a record: what /// [`RecordRegistrar::link_to`] returns. /// /// `'r` is the borrow of the registrar taken by `link_to()`; `'a` is the /// registrar's own borrow of the record being configured. -pub type OutboundConnectorBuilder<'r, 'a, T> = - OutboundLinkBuilder>; +pub type OutboundConnectorBuilder<'r, 'a, T, S = crate::Undeclared> = + OutboundLinkBuilder>; /// Outbound link not attached to a record yet, built with /// [`OutboundLink::new`] and registered by [`RecordRegistrar::output`]. pub type OutboundLink = OutboundLinkBuilder; +/// Outbound link carrying a data contract, built by +/// [`OutboundLink::into_contract`]: an [`Output`] only of a record whose key +/// declares the contract. +pub type ContractOutboundLink = OutboundLinkBuilder; + type OutboundWireFinalizer = Arc) -> Result, String> + Send + Sync>; @@ -938,7 +989,6 @@ pub struct OutboundLinkBuilder { at: R, url: String, connector: Option, - schema: Option<(String, u32)>, config: Vec<(String, String)>, context_serializer: Option>, context_serializer_into: Option<(usize, TypedContextSerializerIntoFn)>, @@ -973,7 +1023,6 @@ where wire_finalizer: None, url: url.to_string(), connector: None, - schema: None, config: Vec::new(), context_serializer: None, context_serializer_into: None, @@ -981,6 +1030,18 @@ where } } + /// Marks this link as carrying a data contract, so it wires only into a + /// record whose key declares the contract. `aimdb-data-contracts`' + /// `publish` calls this; the link's options are unchanged. + pub fn into_contract(self) -> ContractOutboundLink { + self.attach(DetachedContract) + } +} + +impl OutboundLinkBuilder +where + T: Send + Sync + 'static + Debug + Clone, +{ fn attach(self, at: R) -> OutboundLinkBuilder { OutboundLinkBuilder { at, @@ -989,7 +1050,6 @@ where wire_finalizer: self.wire_finalizer, url: self.url, connector: self.connector, - schema: self.schema, config: self.config, context_serializer: self.context_serializer, context_serializer_into: self.context_serializer_into, @@ -1039,7 +1099,6 @@ where wire_finalizer: self.wire_finalizer, url: self.url, connector: self.connector, - schema: self.schema, config: self.config, context_serializer: self.context_serializer, context_serializer_into: self.context_serializer_into, @@ -1048,19 +1107,6 @@ where (self.at, link) } - /// Reports `name` / `version` as the record's data-contract schema when - /// the link is registered, as [`RecordRegistrar::schema`] would. - /// - /// Reported even if the link itself is rejected, like a `schema()` call - /// before it. A different schema on the same record fails `build()`. - /// `aimdb-data-contracts`' `publish` / `subscribe` set it from the - /// contract type. - #[cfg(test)] - pub(crate) fn with_schema(mut self, name: &str, version: u32) -> Self { - self.schema = Some((name.to_string(), version)); - self - } - /// Adds a configuration option to the connector pub fn with_config(mut self, key: &str, value: &str) -> Self { self.config.push((key.to_string(), value.to_string())); @@ -1183,7 +1229,7 @@ where } } -impl<'r, 'a, T> OutboundLinkBuilder> +impl<'r, 'a, T, S: crate::SchemaState> OutboundLinkBuilder> where T: Send + Sync + 'static + Debug + Clone, { @@ -1198,7 +1244,7 @@ where /// /// The buffer requirement is validated by `build()` (calling `.buffer()` /// after `.link_to()` is fine). - pub fn finish(self) -> &'r mut RecordRegistrar<'a, T> { + pub fn finish(self) -> &'r mut RecordRegistrar<'a, T, S> { let (registrar, link) = self.detach(); registrar.push_outbound(link); registrar @@ -1287,12 +1333,18 @@ type InboundWireFinalizer = /// /// `'r` is the borrow of the registrar taken by `link_from()`; `'a` is the /// registrar's own borrow of the record being configured. -pub type InboundConnectorBuilder<'r, 'a, T> = InboundLinkBuilder>; +pub type InboundConnectorBuilder<'r, 'a, T, S = crate::Undeclared> = + InboundLinkBuilder>; /// Inbound link not attached to a record yet, built with /// [`InboundLink::new`] and registered by [`RecordRegistrar::input`]. pub type InboundLink = InboundLinkBuilder; +/// Inbound link carrying a data contract, built by +/// [`InboundLink::into_contract`]: an [`Input`] only of a record whose key +/// declares the contract. +pub type ContractInboundLink = InboundLinkBuilder; + /// Builder for configuring inbound connector links (External → AimDB) /// /// `R` is what the builder is attached to. [`RecordRegistrar::link_from`] @@ -1317,7 +1369,6 @@ pub struct InboundLinkBuilder { at: R, url: String, connector: Option, - schema: Option<(String, u32)>, config: Vec<(String, String)>, context_deserializer: Option>, match_deserializer: Option>, @@ -1354,7 +1405,6 @@ where wire_finalizer: None, url: url.to_string(), connector: None, - schema: None, config: Vec::new(), context_deserializer: None, match_deserializer: None, @@ -1364,6 +1414,18 @@ where } } + /// Marks this link as carrying a data contract, so it wires only into a + /// record whose key declares the contract. `aimdb-data-contracts`' + /// `subscribe` calls this; the link's options are unchanged. + pub fn into_contract(self) -> ContractInboundLink { + self.attach(DetachedContract) + } +} + +impl InboundLinkBuilder +where + T: Send + Sync + 'static + Debug + Clone, +{ fn attach(self, at: R) -> InboundLinkBuilder { InboundLinkBuilder { at, @@ -1372,7 +1434,6 @@ where wire_finalizer: self.wire_finalizer, url: self.url, connector: self.connector, - schema: self.schema, config: self.config, context_deserializer: self.context_deserializer, match_deserializer: self.match_deserializer, @@ -1424,7 +1485,6 @@ where wire_finalizer: self.wire_finalizer, url: self.url, connector: self.connector, - schema: self.schema, config: self.config, context_deserializer: self.context_deserializer, match_deserializer: self.match_deserializer, @@ -1435,19 +1495,6 @@ where (self.at, link) } - /// Reports `name` / `version` as the record's data-contract schema when - /// the link is registered, as [`RecordRegistrar::schema`] would. - /// - /// Reported even if the link itself is rejected, like a `schema()` call - /// before it. A different schema on the same record fails `build()`. - /// `aimdb-data-contracts`' `publish` / `subscribe` set it from the - /// contract type. - #[cfg(test)] - pub(crate) fn with_schema(mut self, name: &str, version: u32) -> Self { - self.schema = Some((name.to_string(), version)); - self - } - /// Adds a configuration option to the connector pub fn with_config(mut self, key: &str, value: &str) -> Self { self.config.push((key.to_string(), value.to_string())); @@ -1577,7 +1624,7 @@ where } } -impl<'r, 'a, T> InboundLinkBuilder> +impl<'r, 'a, T, S: crate::SchemaState> InboundLinkBuilder> where T: Send + Sync + 'static + Debug + Clone, { @@ -1593,7 +1640,7 @@ where /// /// The buffer requirement is validated by `build()` (calling `.buffer()` /// after `.link_from()` is fine). - pub fn finish(self) -> &'r mut RecordRegistrar<'a, T> { + pub fn finish(self) -> &'r mut RecordRegistrar<'a, T, S> { let (registrar, link) = self.detach(); registrar.push_inbound(link); registrar @@ -1645,7 +1692,7 @@ macro_rules! wire_link { wire_link!(OutboundLink); wire_link!(InboundLink); -impl<'a, T> RecordRegistrar<'a, T> +impl<'a, T, S: crate::SchemaState> RecordRegistrar<'a, T, S> where T: Send + Sync + 'static + Debug + Clone, { @@ -1690,10 +1737,6 @@ where use crate::connector::{ConnectorLink, LinkAddress}; use crate::error::ConfigError; - if let Some((name, version)) = link.schema.take() { - self.schema(&name, version); - } - let record_key = self.record_key.clone(); if let Some(handle) = link.connector { @@ -1922,9 +1965,6 @@ where return; }; - if let Some((name, version)) = link.schema.take() { - self.schema(&name, version); - } match self.inbound_link(&mut link) { Ok(inbound) => self.rec.add_inbound_connector(inbound), Err(message) => { @@ -2121,6 +2161,7 @@ mod tests { key_link_address: None, extensions, last_stage: None, + _schema: core::marker::PhantomData, } } @@ -2629,11 +2670,11 @@ mod tests { /// A custom input, generic over every record type it can produce. struct Counter; - impl Input for Counter + impl Input for Counter where T: From + Send + Sync + 'static + Debug + Clone, { - fn wire(self, reg: &mut RecordRegistrar<'_, T>) { + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { reg.source(|_ctx, producer| async move { for i in 0..3 { producer.produce(T::from(i)); @@ -2774,61 +2815,6 @@ mod tests { } } - /// `with_schema` reports the record's schema on registration, in both - /// directions and on both forms, even when the link is rejected; a second - /// schema conflicts as with `reg.schema(..)`. - #[test] - fn with_schema_reports_the_record_schema() { - let schema_of = |rec: &crate::typed_record::TypedRecord| { - rec.schema().map(|s| (s.name.clone(), s.version)) - }; - let expected = Some(("contract".to_string(), 2)); - - let mut detached = registered(|reg| { - reg.output( - OutboundLink::new("mqtt://out") - .with_serializer(ser) - .with_schema("contract", 2), - ) - .input( - InboundLink::new("mqtt://in") - .with_deserializer(de) - .with_schema("contract", 2), - ); - }); - assert_eq!(schema_of(&detached), expected); - assert_eq!(detached.outbound_connectors().len(), 1); - assert!(drain_errors(&mut detached).is_empty()); - - let mut attached = registered(|reg| { - reg.link_from("mqtt://in") - .with_deserializer(de) - .with_schema("contract", 2) - .finish(); - }); - assert_eq!(schema_of(&attached), expected); - assert!(drain_errors(&mut attached).is_empty()); - - // Rejected (no serializer), yet the schema is reported. - let mut rejected = registered(|reg| { - reg.output(OutboundLink::new("mqtt://out").with_schema("contract", 2)); - }); - assert_eq!(schema_of(&rejected), expected); - assert!(rejected.outbound_connectors().is_empty()); - assert_eq!(drain_errors(&mut rejected).len(), 1); - - let mut conflicting = registered(|reg| { - reg.schema("contract", 1).output( - OutboundLink::new("mqtt://out") - .with_serializer(ser) - .with_schema("contract", 2), - ); - }); - let errors = drain_errors(&mut conflicting); - assert_eq!(errors.len(), 1, "{errors:?}"); - assert!(errors[0].message.contains("already carries contract v1")); - } - /// A connector registered with `connect` serves links exactly like one /// registered with `with_connector`. #[tokio::test] diff --git a/aimdb-data-contracts/CHANGELOG.md b/aimdb-data-contracts/CHANGELOG.md index d8705fe9..3254a4ec 100644 --- a/aimdb-data-contracts/CHANGELOG.md +++ b/aimdb-data-contracts/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking — typed record keys (design 063) -- Add Key; contract identity comes from SchemaType. Link and observation helpers preserve the schema declared by the key. +- Add Key; contract identity comes from SchemaType. Link and observation helpers require the schema declared by the key: `publish`, `subscribe`, `linked_to`, `linked_from`, their `_with` forms and `observe` do not compile on a record declared with `Name` or `payload = T`. `publish` / `subscribe` return `ContractOutboundLink` / `ContractInboundLink`. `LinkableRegistrarExt`, `LinkCodecRegistrarExt` and `ObservableRegistrarExt` take the registrar's schema state as a third parameter and return `&mut Self`. ### Changed — value envelopes (design 062) diff --git a/aimdb-data-contracts/src/key.rs b/aimdb-data-contracts/src/key.rs index e503c316..c8de140b 100644 --- a/aimdb-data-contracts/src/key.rs +++ b/aimdb-data-contracts/src/key.rs @@ -88,6 +88,7 @@ where T: SchemaType + Send + Sync + Clone + core::fmt::Debug + 'static, { const SCHEMA: Option<(&'static str, u32)> = Some((T::NAME, T::VERSION)); + type Schema = aimdb_core::Declared; } impl AsRef for Key { diff --git a/aimdb-data-contracts/src/lib.rs b/aimdb-data-contracts/src/lib.rs index fd06c4f9..b7bd49ac 100644 --- a/aimdb-data-contracts/src/lib.rs +++ b/aimdb-data-contracts/src/lib.rs @@ -306,11 +306,11 @@ pub trait Observable: SchemaType { /// Not compiled: the snippet needs `aimdb-core`'s builder types in scope. /// /// ```rust,ignore -/// use aimdb_data_contracts::subscribe; +/// use aimdb_data_contracts::{subscribe, Key}; /// use my_app::Temperature; // user-defined type implementing Linkable /// /// let mqtt = builder.connect(MqttConnector::new(broker_url)); -/// builder.configure(aimdb_core::Name::::interned(NODE_ID), |reg| { +/// builder.configure(Key::::interned(NODE_ID), |reg| { /// reg.buffer(BufferCfg::SingleLatest) /// .input(subscribe(mqtt, "sensors/temperature")); /// }); diff --git a/aimdb-data-contracts/src/linkable.rs b/aimdb-data-contracts/src/linkable.rs index ca8c7559..743cb681 100644 --- a/aimdb-data-contracts/src/linkable.rs +++ b/aimdb-data-contracts/src/linkable.rs @@ -5,46 +5,51 @@ //! `reg.input(..)`. The registrar verbs [`LinkableRegistrarExt::linked_from`] / //! [`linked_to`](LinkableRegistrarExt::linked_to) do the same from a full URL, //! and [`LinkCodecRegistrarExt`] selects a different codec per link. Every -//! path reports `T::NAME` / `T::VERSION` as the record's schema. The raw +//! path needs a record whose key declares `T` as its contract (`Key` or +//! `#[record_key(contract = T)]`); on a `Name` record it does not compile. The raw //! `.link_to()` / `.link_from()` builders remain the escape hatch. use aimdb_core::typed_api::RecordRegistrar; -use aimdb_core::{ConnectorHandle, InboundLink, OutboundLink}; +use aimdb_core::typed_api::{ContractInboundLink, ContractOutboundLink}; +use aimdb_core::{ConnectorHandle, ContractDeclared, InboundLink, OutboundLink, SchemaState}; use crate::{link_codecs, LinkCodec, LinkCodecBuilderExt, Linkable}; -/// An outbound link carrying contract `T`: its codec and its schema. -fn contract_out(link: OutboundLink, codec: C) -> OutboundLink +/// An outbound link carrying contract `T`: its codec, and a link type that +/// wires only into a record whose key declares `T`. +fn contract_out(link: OutboundLink, codec: C) -> ContractOutboundLink where T: Linkable + Send + Sync + Clone + core::fmt::Debug + 'static, C: LinkCodec, { - link.with_link_codec(codec) + link.with_link_codec(codec).into_contract() } -/// An inbound link carrying contract `T`: its codec and its schema. -fn contract_in(link: InboundLink, codec: C) -> InboundLink +/// An inbound link carrying contract `T`: its codec, and a link type that +/// wires only into a record whose key declares `T`. +fn contract_in(link: InboundLink, codec: C) -> ContractInboundLink where T: Linkable + Send + Sync + Clone + core::fmt::Debug + 'static, C: LinkCodec, { - link.with_link_codec(codec) + link.with_link_codec(codec).into_contract() } /// Publishes a `T` record to `address` on `connector`, encoded with `T`'s own /// [`Linkable`] codec; pass it to `reg.output(..)`. /// /// `address` needs no scheme (`"sensors/temp"`); a full URL whose scheme is -/// the connector's, as a `#[link_address]` key gives, works too. The record -/// reports `T::NAME` / `T::VERSION` as its schema. The result is an ordinary -/// [`OutboundLink`], so connector options (`with_qos`, …) and +/// the connector's, as a `#[link_address]` key gives, works too. The result +/// is a [`ContractOutboundLink`]: connector options (`with_qos`, …) and /// [`with_link_codec`](LinkCodecBuilderExt::with_link_codec), which replaces -/// the codec, apply to it. +/// the codec, apply to it as to any [`OutboundLink`]. It is an output only of +/// a record whose key declares `T` (`Key` or +/// `#[record_key(contract = T)]`). /// /// ```rust,ignore /// let mqtt = builder.connect(MqttConnector::new(broker_url)); -/// let record_1 = aimdb_core::Name::::new("temp.indoor"); -/// builder.configure(record_1, |reg| { +/// const TEMP_INDOOR: Key = Key::new("temp.indoor"); +/// builder.configure(TEMP_INDOOR, |reg| { /// reg.buffer(BufferCfg::SingleLatest) /// .output(publish(mqtt, "sensors/temp/indoor").with_qos(1)); /// }); @@ -61,7 +66,24 @@ where /// reg.output(aimdb_data_contracts::publish(mqtt, "sensors/x")); /// } /// ``` -pub fn publish(connector: ConnectorHandle, address: &str) -> OutboundLink +/// +/// Neither does a contract record declared without its contract (a +/// `Name`, whose registrar is [`Undeclared`](aimdb_core::Undeclared)): +/// +/// ```compile_fail,E0277 +/// # use aimdb_core::{ConnectorHandle, RecordRegistrar, Undeclared}; +/// # #[derive(Clone, Debug)] +/// # struct Temp; +/// # impl aimdb_data_contracts::SchemaType for Temp { const NAME: &'static str = "temp"; } +/// # impl aimdb_data_contracts::Linkable for Temp { +/// # fn to_bytes(&self) -> Result, String> { Ok(Vec::new()) } +/// # fn from_bytes(_: &[u8]) -> Result { Ok(Temp) } +/// # } +/// fn wire(reg: &mut RecordRegistrar<'_, Temp, Undeclared>, mqtt: ConnectorHandle) { +/// reg.output(aimdb_data_contracts::publish(mqtt, "sensors/temp")); +/// } +/// ``` +pub fn publish(connector: ConnectorHandle, address: &str) -> ContractOutboundLink where T: Linkable + Send + Sync + Clone + core::fmt::Debug + 'static, { @@ -72,7 +94,7 @@ where /// own [`Linkable`] codec; pass it to `reg.input(..)`. /// /// The counterpart of [`publish`]; the same address rules and options apply. -pub fn subscribe(connector: ConnectorHandle, address: &str) -> InboundLink +pub fn subscribe(connector: ConnectorHandle, address: &str) -> ContractInboundLink where T: Linkable + Send + Sync + Clone + core::fmt::Debug + 'static, { @@ -82,14 +104,18 @@ where /// Adds `.linked_from(url)` and `.linked_to(url)` to [`RecordRegistrar`] for /// [`Linkable`] types. /// -/// Both also report `T::NAME`/`T::VERSION` as the record's schema -/// ([`RecordRegistrar::schema`]). -pub trait LinkableRegistrarExt<'a, T> +/// Both exist only on a record whose key declares `T` as its contract +/// (`Key` or `#[record_key(contract = T)]`); on a `Name` record they do +/// not compile. +pub trait LinkableRegistrarExt<'a, T, S> where T: Linkable + Send + Sync + Clone + core::fmt::Debug + 'static, + S: SchemaState, { /// `.link_from(url)` with the codec defaulted to `T::from_bytes`. - fn linked_from(&mut self, url: &str) -> &mut RecordRegistrar<'a, T>; + fn linked_from(&mut self, url: &str) -> &mut Self + where + S: ContractDeclared; /// `.link_to(url)` with the codec defaulted to `T::to_bytes` and an /// optional bounded [`Linkable::encode_into`] fast path. @@ -97,18 +123,27 @@ where /// `Linkable::to_bytes`'s `String` error is mapped to /// `SerializeError::InvalidData` — the connector layer's serializer error /// type carries no string detail. - fn linked_to(&mut self, url: &str) -> &mut RecordRegistrar<'a, T>; + fn linked_to(&mut self, url: &str) -> &mut Self + where + S: ContractDeclared; } -impl<'a, T> LinkableRegistrarExt<'a, T> for RecordRegistrar<'a, T> +impl<'a, T, S> LinkableRegistrarExt<'a, T, S> for RecordRegistrar<'a, T, S> where T: Linkable + Send + Sync + Clone + core::fmt::Debug + 'static, + S: SchemaState, { - fn linked_from(&mut self, url: &str) -> &mut RecordRegistrar<'a, T> { + fn linked_from(&mut self, url: &str) -> &mut Self + where + S: ContractDeclared, + { self.input(contract_in(InboundLink::new(url), link_codecs::Default)) } - fn linked_to(&mut self, url: &str) -> &mut RecordRegistrar<'a, T> { + fn linked_to(&mut self, url: &str) -> &mut Self + where + S: ContractDeclared, + { self.output(contract_out(OutboundLink::new(url), link_codecs::Default)) } } @@ -118,35 +153,41 @@ where /// This is a sibling trait rather than new required methods on /// `LinkableRegistrarExt`, preserving source compatibility for downstream /// implementations of the existing public extension trait. -pub trait LinkCodecRegistrarExt<'a, T> +pub trait LinkCodecRegistrarExt<'a, T, S> where T: Linkable + Send + Sync + Clone + core::fmt::Debug + 'static, + S: SchemaState, { /// `.link_from(url).with_link_codec(codec).finish()`. - fn linked_from_with(&mut self, url: &str, codec: C) -> &mut RecordRegistrar<'a, T> + fn linked_from_with(&mut self, url: &str, codec: C) -> &mut Self where - C: LinkCodec; + C: LinkCodec, + S: ContractDeclared; /// `.link_to(url).with_link_codec(codec).finish()`. - fn linked_to_with(&mut self, url: &str, codec: C) -> &mut RecordRegistrar<'a, T> + fn linked_to_with(&mut self, url: &str, codec: C) -> &mut Self where - C: LinkCodec; + C: LinkCodec, + S: ContractDeclared; } -impl<'a, T> LinkCodecRegistrarExt<'a, T> for RecordRegistrar<'a, T> +impl<'a, T, S> LinkCodecRegistrarExt<'a, T, S> for RecordRegistrar<'a, T, S> where T: Linkable + Send + Sync + Clone + core::fmt::Debug + 'static, + S: SchemaState, { - fn linked_from_with(&mut self, url: &str, codec: C) -> &mut RecordRegistrar<'a, T> + fn linked_from_with(&mut self, url: &str, codec: C) -> &mut Self where C: LinkCodec, + S: ContractDeclared, { self.input(contract_in(InboundLink::new(url), codec)) } - fn linked_to_with(&mut self, url: &str, codec: C) -> &mut RecordRegistrar<'a, T> + fn linked_to_with(&mut self, url: &str, codec: C) -> &mut Self where C: LinkCodec, + S: ContractDeclared, { self.output(contract_out(OutboundLink::new(url), codec)) } diff --git a/aimdb-data-contracts/src/observable.rs b/aimdb-data-contracts/src/observable.rs index 62827ef9..dff6b68e 100644 --- a/aimdb-data-contracts/src/observable.rs +++ b/aimdb-data-contracts/src/observable.rs @@ -8,6 +8,7 @@ extern crate alloc; use aimdb_core::typed_api::RecordRegistrar; +use aimdb_core::{ContractDeclared, SchemaState}; use crate::Observable; @@ -49,13 +50,19 @@ pub async fn log_tap( /// Adds `.observe()` and `.log(node_id)` to [`RecordRegistrar`] for /// [`Observable`] types. -pub trait ObservableRegistrarExt<'a, T> +/// +/// `S` is the registrar's [`SchemaState`]: `.observe()` exists only on a +/// record whose key declares `T` as its contract; `.log()` on any record. +pub trait ObservableRegistrarExt<'a, T, S> where T: Observable + Send + Sync + Clone + core::fmt::Debug + 'static, + S: SchemaState, { /// Feed `T::signal()` into the record's signal gauge (last/min/max/mean), /// visible via `record.list` / `record.get` / stage profiling. - /// Also reports `T::NAME`/`T::VERSION` as the record's schema. + /// Only on a record whose key declares `T` as its contract (`Key` or + /// `#[record_key(contract = T)]`); on a `Name` record it does not + /// compile. /// /// Recording requires `aimdb-core`'s `observability` feature: without it /// [`RecordRegistrar::signal_gauge`] hands back an inert gauge and this @@ -65,23 +72,26 @@ where /// Bounded `T::Signal: Into` here (not on the trait), so `f32`/`i32`/ /// `u32` signals qualify while a type with an exotic signal can still /// implement `Observable` and write its own tap. - fn observe(&mut self) -> &mut RecordRegistrar<'a, T> + fn observe(&mut self) -> &mut Self where - T::Signal: Into; + T::Signal: Into, + S: ContractDeclared; /// Log each value to the runtime log, formatted from `Debug` + /// `SIGNAL`/`UNIT`. For humans watching a console; `.observe()` is the /// metrics path. - fn log(&mut self, node_id: &'static str) -> &mut RecordRegistrar<'a, T>; + fn log(&mut self, node_id: &'static str) -> &mut Self; } -impl<'a, T> ObservableRegistrarExt<'a, T> for RecordRegistrar<'a, T> +impl<'a, T, S> ObservableRegistrarExt<'a, T, S> for RecordRegistrar<'a, T, S> where T: Observable + Send + Sync + Clone + core::fmt::Debug + 'static, + S: SchemaState, { - fn observe(&mut self) -> &mut RecordRegistrar<'a, T> + fn observe(&mut self) -> &mut Self where T::Signal: Into, + S: ContractDeclared, { let gauge = self.signal_gauge(T::SIGNAL, T::UNIT); self.tap(move |_ctx, consumer| async move { @@ -93,7 +103,7 @@ where .with_name("observe") } - fn log(&mut self, node_id: &'static str) -> &mut RecordRegistrar<'a, T> { + fn log(&mut self, node_id: &'static str) -> &mut Self { self.tap(move |ctx, consumer| log_tap(ctx, consumer, node_id)) .with_name("log") } diff --git a/aimdb-data-contracts/src/simulatable.rs b/aimdb-data-contracts/src/simulatable.rs index eaba29d7..f85f0b45 100644 --- a/aimdb-data-contracts/src/simulatable.rs +++ b/aimdb-data-contracts/src/simulatable.rs @@ -98,24 +98,16 @@ where /// Installs a **source**, so single-writer-per-key is enforced by `build()` /// exactly as for a hardware `.source()` — the two are mutually exclusive by /// the app's `#[cfg]`, never both present in one binary. - fn simulate( - &mut self, - profile: SimProfile, - rng: R, - ) -> &mut RecordRegistrar<'a, T> + fn simulate(&mut self, profile: SimProfile, rng: R) -> &mut Self where R: rand::Rng + Send + 'static; } -impl<'a, T> SimulatableRegistrarExt<'a, T> for RecordRegistrar<'a, T> +impl<'a, T, S: aimdb_core::SchemaState> SimulatableRegistrarExt<'a, T> for RecordRegistrar<'a, T, S> where T: Simulatable + Send + Sync + Clone + core::fmt::Debug + 'static, { - fn simulate( - &mut self, - profile: SimProfile, - mut rng: R, - ) -> &mut RecordRegistrar<'a, T> + fn simulate(&mut self, profile: SimProfile, mut rng: R) -> &mut Self where R: rand::Rng + Send + 'static, { diff --git a/aimdb-data-contracts/tests/compile-fail-links/input_wrong_direction.stderr b/aimdb-data-contracts/tests/compile-fail-links/input_wrong_direction.stderr index 0b0f6dd5..bc6c63e1 100644 --- a/aimdb-data-contracts/tests/compile-fail-links/input_wrong_direction.stderr +++ b/aimdb-data-contracts/tests/compile-fail-links/input_wrong_direction.stderr @@ -6,17 +6,22 @@ error[E0277]: `OutboundLinkBuilder` cannot be the input of a `Te | | | required by a bound introduced by this call | - = help: the trait `aimdb_core::Input` is not implemented for `OutboundLinkBuilder` + = help: the trait `aimdb_core::Input` is not implemented for `OutboundLinkBuilder` = note: an input implements `Input`; device inputs usually do so for every `T: From` -help: the trait `aimdb_core::Input` is implemented for `InboundLinkBuilder` +help: the following other types implement trait `aimdb_core::Input` --> $WORKSPACE/aimdb-core/src/typed_api.rs | - | / impl Input for InboundLink + | / impl Input for InboundLink | | where | | T: Send + Sync + 'static + Debug + Clone, - | |_____________________________________________^ -note: required by a bound in `RecordRegistrar::<'a, T>::input` + | |_____________________________________________^ `InboundLinkBuilder` +... + | / impl Input for ContractInboundLink + | | where + | | T: Send + Sync + 'static + Debug + Clone, + | |_____________________________________________^ `InboundLinkBuilder` +note: required by a bound in `RecordRegistrar::<'a, T, S>::input` --> $WORKSPACE/aimdb-core/src/typed_api.rs | - | pub fn input(&mut self, input: impl Input) -> &mut Self { - | ^^^^^^^^ required by this bound in `RecordRegistrar::<'a, T>::input` + | pub fn input(&mut self, input: impl Input) -> &mut Self { + | ^^^^^^^^^^^ required by this bound in `RecordRegistrar::<'a, T, S>::input` diff --git a/aimdb-data-contracts/tests/compile-fail-links/output_wrong_record.stderr b/aimdb-data-contracts/tests/compile-fail-links/output_wrong_record.stderr index f85416b7..ff78993d 100644 --- a/aimdb-data-contracts/tests/compile-fail-links/output_wrong_record.stderr +++ b/aimdb-data-contracts/tests/compile-fail-links/output_wrong_record.stderr @@ -6,17 +6,21 @@ error[E0277]: `OutboundLinkBuilder` cannot be an output of a `Ot | | | required by a bound introduced by this call | -help: the trait `Output` is not implemented for `OutboundLinkBuilder` - but trait `Output` is implemented for it + = help: the trait `aimdb_core::Output` is not implemented for `OutboundLinkBuilder` +help: the following other types implement trait `aimdb_core::Output` --> $WORKSPACE/aimdb-core/src/typed_api.rs | - | / impl Output for OutboundLink + | / impl Output for OutboundLink | | where | | T: Send + Sync + 'static + Debug + Clone, - | |_____________________________________________^ - = help: for that trait implementation, expected `Temp`, found `Other` -note: required by a bound in `RecordRegistrar::<'a, T>::output` + | |_____________________________________________^ `OutboundLinkBuilder` +... + | / impl Output for ContractOutboundLink + | | where + | | T: Send + Sync + 'static + Debug + Clone, + | |_____________________________________________^ `OutboundLinkBuilder` +note: required by a bound in `RecordRegistrar::<'a, T, S>::output` --> $WORKSPACE/aimdb-core/src/typed_api.rs | - | pub fn output(&mut self, output: impl Output) -> &mut Self { - | ^^^^^^^^^ required by this bound in `RecordRegistrar::<'a, T>::output` + | pub fn output(&mut self, output: impl Output) -> &mut Self { + | ^^^^^^^^^^^^ required by this bound in `RecordRegistrar::<'a, T, S>::output` diff --git a/aimdb-data-contracts/tests/compile-fail/typed_key_bare_string.stderr b/aimdb-data-contracts/tests/compile-fail/typed_key_bare_string.stderr index 755dd9db..8fcea5ea 100644 --- a/aimdb-data-contracts/tests/compile-fail/typed_key_bare_string.stderr +++ b/aimdb-data-contracts/tests/compile-fail/typed_key_bare_string.stderr @@ -18,15 +18,15 @@ note: required by a bound in `AimDbBuilder::configure` | pub fn configure( | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AimDbBuilder::configure` -error[E0277]: `&str` does not name a record and its payload type +error[E0277]: `&str` is not a typed record key --> tests/compile-fail/typed_key_bare_string.rs:3:5 | 3 | b.configure("reading", |_| {}); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TypedName` is not implemented for `&str` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TypedKey` is not implemented for `&str` | - = note: pass a `Key`, or a `Name` for a record without a data contract or a name known only at run time -help: the trait `TypedName` is implemented for `aimdb_core::Name<'_, T>` + = note: declare the record once as a `Key` (or a `Name` without a data contract) and pass that +help: the trait `TypedKey` is implemented for `aimdb_core::Name<'static, T>` --> $WORKSPACE/aimdb-core/src/record_id.rs | - | impl TypedName for Name<'_, T> { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | impl TypedKey for Name<'static, T> { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/aimdb-data-contracts/tests/compile-fail/typed_key_contract_verbs_on_name.rs b/aimdb-data-contracts/tests/compile-fail/typed_key_contract_verbs_on_name.rs new file mode 100644 index 00000000..8749dc27 --- /dev/null +++ b/aimdb-data-contracts/tests/compile-fail/typed_key_contract_verbs_on_name.rs @@ -0,0 +1,43 @@ +//! Contract verbs need a record whose key declares the contract: on a +//! `Name` record (schema-free), they do not compile. +use aimdb_core::{AimDbBuilder, ConnectorHandle, Name}; +use aimdb_data_contracts::{ + publish, subscribe, LinkCodecRegistrarExt, Linkable, LinkableRegistrarExt, Observable, + ObservableRegistrarExt, SchemaType, +}; + +#[derive(Clone, Debug)] +struct Temp(f32); +impl SchemaType for Temp { + const NAME: &'static str = "temp"; +} +impl Linkable for Temp { + fn to_bytes(&self) -> Result, String> { + Ok(Vec::new()) + } + fn from_bytes(_: &[u8]) -> Result { + Ok(Temp(0.0)) + } +} +impl Observable for Temp { + type Signal = f32; + const UNIT: &'static str = "C"; + fn signal(&self) -> f32 { + self.0 + } +} + +const TEMP: Name = Name::new("temp"); + +fn wire(b: &mut AimDbBuilder, mqtt: ConnectorHandle) { + b.configure(TEMP, |r| { + r.linked_to("mqtt://out"); + r.linked_from("mqtt://in"); + r.linked_to_with("mqtt://out2", aimdb_data_contracts::link_codecs::Default); + r.observe(); + r.output(publish(mqtt, "out")); + r.input(subscribe(mqtt, "in")); + }); +} + +fn main() {} diff --git a/aimdb-data-contracts/tests/compile-fail/typed_key_contract_verbs_on_name.stderr b/aimdb-data-contracts/tests/compile-fail/typed_key_contract_verbs_on_name.stderr new file mode 100644 index 00000000..6d74587a --- /dev/null +++ b/aimdb-data-contracts/tests/compile-fail/typed_key_contract_verbs_on_name.stderr @@ -0,0 +1,125 @@ +error[E0277]: this record's key declares no data contract + --> tests/compile-fail/typed_key_contract_verbs_on_name.rs:34:11 + | +34 | r.linked_to("mqtt://out"); + | ^^^^^^^^^ the trait `ContractDeclared` is not implemented for `Undeclared` + | + = note: contract verbs (`linked_to`, `linked_from`, `publish`, `subscribe`, `observe`) need the record declared with `Key` or `#[record_key(contract = T)]`, not `Name` or `payload = T` +help: the trait `ContractDeclared` is implemented for `Declared` + --> $WORKSPACE/aimdb-core/src/record_id.rs + | + | impl ContractDeclared for Declared {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `linked_to` + --> src/linkable.rs + | + | fn linked_to(&mut self, url: &str) -> &mut Self + | --------- required by a bound in this associated function + | where + | S: ContractDeclared; + | ^^^^^^^^^^^^^^^^ required by this bound in `LinkableRegistrarExt::linked_to` + +error[E0277]: this record's key declares no data contract + --> tests/compile-fail/typed_key_contract_verbs_on_name.rs:35:11 + | +35 | r.linked_from("mqtt://in"); + | ^^^^^^^^^^^ the trait `ContractDeclared` is not implemented for `Undeclared` + | + = note: contract verbs (`linked_to`, `linked_from`, `publish`, `subscribe`, `observe`) need the record declared with `Key` or `#[record_key(contract = T)]`, not `Name` or `payload = T` +help: the trait `ContractDeclared` is implemented for `Declared` + --> $WORKSPACE/aimdb-core/src/record_id.rs + | + | impl ContractDeclared for Declared {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `linked_from` + --> src/linkable.rs + | + | fn linked_from(&mut self, url: &str) -> &mut Self + | ----------- required by a bound in this associated function + | where + | S: ContractDeclared; + | ^^^^^^^^^^^^^^^^ required by this bound in `LinkableRegistrarExt::linked_from` + +error[E0277]: this record's key declares no data contract + --> tests/compile-fail/typed_key_contract_verbs_on_name.rs:36:11 + | +36 | r.linked_to_with("mqtt://out2", aimdb_data_contracts::link_codecs::Default); + | ^^^^^^^^^^^^^^ the trait `ContractDeclared` is not implemented for `Undeclared` + | + = note: contract verbs (`linked_to`, `linked_from`, `publish`, `subscribe`, `observe`) need the record declared with `Key` or `#[record_key(contract = T)]`, not `Name` or `payload = T` +help: the trait `ContractDeclared` is implemented for `Declared` + --> $WORKSPACE/aimdb-core/src/record_id.rs + | + | impl ContractDeclared for Declared {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `linked_to_with` + --> src/linkable.rs + | + | fn linked_to_with(&mut self, url: &str, codec: C) -> &mut Self + | -------------- required by a bound in this associated function +... + | S: ContractDeclared; + | ^^^^^^^^^^^^^^^^ required by this bound in `LinkCodecRegistrarExt::linked_to_with` + +error[E0277]: this record's key declares no data contract + --> tests/compile-fail/typed_key_contract_verbs_on_name.rs:37:11 + | +37 | r.observe(); + | ^^^^^^^ the trait `ContractDeclared` is not implemented for `Undeclared` + | + = note: contract verbs (`linked_to`, `linked_from`, `publish`, `subscribe`, `observe`) need the record declared with `Key` or `#[record_key(contract = T)]`, not `Name` or `payload = T` +help: the trait `ContractDeclared` is implemented for `Declared` + --> $WORKSPACE/aimdb-core/src/record_id.rs + | + | impl ContractDeclared for Declared {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `observe` + --> src/observable.rs + | + | fn observe(&mut self) -> &mut Self + | ------- required by a bound in this associated function +... + | S: ContractDeclared; + | ^^^^^^^^^^^^^^^^ required by this bound in `ObservableRegistrarExt::observe` + +error[E0277]: this record's key declares no data contract + --> tests/compile-fail/typed_key_contract_verbs_on_name.rs:38:18 + | +38 | r.output(publish(mqtt, "out")); + | ------ ^^^^^^^^^^^^^^^^^^^^ the trait `ContractDeclared` is not implemented for `Undeclared` + | | + | required by a bound introduced by this call + | + = note: contract verbs (`linked_to`, `linked_from`, `publish`, `subscribe`, `observe`) need the record declared with `Key` or `#[record_key(contract = T)]`, not `Name` or `payload = T` +help: the trait `ContractDeclared` is implemented for `Declared` + --> $WORKSPACE/aimdb-core/src/record_id.rs + | + | impl ContractDeclared for Declared {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `OutboundLinkBuilder` to implement `aimdb_core::Output` +note: required by a bound in `RecordRegistrar::<'a, T, S>::output` + --> $WORKSPACE/aimdb-core/src/typed_api.rs + | + | pub fn output(&mut self, output: impl Output) -> &mut Self { + | ^^^^^^^^^^^^ required by this bound in `RecordRegistrar::<'a, T, S>::output` + +error[E0277]: this record's key declares no data contract + --> tests/compile-fail/typed_key_contract_verbs_on_name.rs:39:17 + | +39 | r.input(subscribe(mqtt, "in")); + | ----- ^^^^^^^^^^^^^^^^^^^^^ the trait `ContractDeclared` is not implemented for `Undeclared` + | | + | required by a bound introduced by this call + | + = note: contract verbs (`linked_to`, `linked_from`, `publish`, `subscribe`, `observe`) need the record declared with `Key` or `#[record_key(contract = T)]`, not `Name` or `payload = T` +help: the trait `ContractDeclared` is implemented for `Declared` + --> $WORKSPACE/aimdb-core/src/record_id.rs + | + | impl ContractDeclared for Declared {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `InboundLinkBuilder` to implement `aimdb_core::Input` +note: required by a bound in `RecordRegistrar::<'a, T, S>::input` + --> $WORKSPACE/aimdb-core/src/typed_api.rs + | + | pub fn input(&mut self, input: impl Input) -> &mut Self { + | ^^^^^^^^^^^ required by this bound in `RecordRegistrar::<'a, T, S>::input` diff --git a/aimdb-data-contracts/tests/compile-fail/typed_key_payload_access.stderr b/aimdb-data-contracts/tests/compile-fail/typed_key_payload_access.stderr index 71954099..063d8874 100644 --- a/aimdb-data-contracts/tests/compile-fail/typed_key_payload_access.stderr +++ b/aimdb-data-contracts/tests/compile-fail/typed_key_payload_access.stderr @@ -6,16 +6,16 @@ error[E0631]: type mismatch in closure arguments | | | expected due to this | - = note: expected closure signature `for<'a, 'b> fn(&'a mut RecordRegistrar<'b, V2>) -> _` - found closure signature `fn(&mut RecordRegistrar<'_, V1>) -> _` + = note: expected closure signature `for<'a, 'b> fn(&'a mut RecordRegistrar<'b, V2, Declared>) -> _` + found closure signature `fn(&mut RecordRegistrar<'_, V1, Undeclared>) -> _` note: required by a bound in `AimDbBuilder::configure` --> $WORKSPACE/aimdb-core/src/builder.rs | | pub fn configure( | --------- required by a bound in this associated function ... - | f: impl FnOnce(&mut RecordRegistrar<'_, K::Contract>), - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AimDbBuilder::configure` + | f: impl FnOnce(&mut RecordRegistrar<'_, K::Contract, K::Schema>), + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AimDbBuilder::configure` error[E0308]: mismatched types --> tests/compile-fail/typed_key_payload_access.rs:6:50 diff --git a/aimdb-data-contracts/tests/versioned_links.rs b/aimdb-data-contracts/tests/versioned_links.rs index 128660a9..6913d232 100644 --- a/aimdb-data-contracts/tests/versioned_links.rs +++ b/aimdb-data-contracts/tests/versioned_links.rs @@ -80,7 +80,9 @@ fn value() -> V2 { quality: 300, } } -async fn db(configure: impl FnOnce(&mut RecordRegistrar<'_, V2>)) -> (AimDb, Capture) { +async fn db( + configure: impl FnOnce(&mut RecordRegistrar<'_, V2, aimdb_core::Declared>), +) -> (AimDb, Capture) { let key_reading_1 = aimdb_data_contracts::Key::::new("reading"); let captured: Capture = Default::default(); let mut b = builder(); @@ -235,7 +237,7 @@ fn outbound_headers_downgrades_shapes_and_owned_fallback() { }); } -fn invalid(configure: impl FnOnce(&mut RecordRegistrar<'_, V2>)) -> String { +fn invalid(configure: impl FnOnce(&mut RecordRegistrar<'_, V2, aimdb_core::Declared>)) -> String { futures::executor::block_on(async { let key_reading_2 = aimdb_data_contracts::Key::::new("reading"); let mut b = builder(); diff --git a/aimdb-derive/src/lib.rs b/aimdb-derive/src/lib.rs index 82294d61..c1843557 100644 --- a/aimdb-derive/src/lib.rs +++ b/aimdb-derive/src/lib.rs @@ -353,6 +353,7 @@ fn derive_record_key_impl(input: DeriveInput) -> Result::NAME, <#ty as ::aimdb_data_contracts::SchemaType>::VERSION, )); + type Schema = aimdb_core::Declared; } }, (None, Some(ty)) => quote! { @@ -364,6 +365,7 @@ fn derive_record_key_impl(input: DeriveInput) -> Result = None; + type Schema = aimdb_core::Undeclared; } }, (None, None) => { diff --git a/aimdb-embassy-adapter/src/lib.rs b/aimdb-embassy-adapter/src/lib.rs index 460cfd30..61988422 100644 --- a/aimdb-embassy-adapter/src/lib.rs +++ b/aimdb-embassy-adapter/src/lib.rs @@ -182,7 +182,8 @@ where } #[cfg(all(feature = "embassy-runtime", feature = "embassy-sync"))] -impl EmbassyRecordRegistrarExt for aimdb_core::RecordRegistrar<'_, T> +impl EmbassyRecordRegistrarExt + for aimdb_core::RecordRegistrar<'_, T, S> where T: Send + Sync + Clone + core::fmt::Debug + 'static, { @@ -272,7 +273,7 @@ where fn buffer_sized( &mut self, buffer_type: EmbassyBufferType, - ) -> &mut aimdb_core::RecordRegistrar<'a, T>; + ) -> &mut Self; /// Registers a producer with additional context (e.g., hardware peripherals) /// @@ -309,11 +310,7 @@ where /// // Produce data... /// } /// ``` - fn source_with_context( - &mut self, - context: Ctx, - f: F, - ) -> &mut aimdb_core::RecordRegistrar<'a, T> + fn source_with_context(&mut self, context: Ctx, f: F) -> &mut Self where Ctx: Send + 'static, F: FnOnce(aimdb_core::RuntimeContext, aimdb_core::Producer, Ctx) -> Fut + Send + 'static, @@ -321,14 +318,15 @@ where } #[cfg(all(feature = "embassy-runtime", feature = "embassy-sync"))] -impl<'a, T> EmbassyRecordRegistrarExtCustom<'a, T> for aimdb_core::RecordRegistrar<'a, T> +impl<'a, T, S: aimdb_core::SchemaState> EmbassyRecordRegistrarExtCustom<'a, T> + for aimdb_core::RecordRegistrar<'a, T, S> where T: Send + Sync + Clone + core::fmt::Debug + 'static, { fn buffer_sized( &mut self, buffer_type: EmbassyBufferType, - ) -> &mut aimdb_core::RecordRegistrar<'a, T> { + ) -> &mut Self { use aimdb_core::buffer::{Buffer, BufferCfg}; use alloc::boxed::Box; @@ -360,11 +358,7 @@ where self.buffer_with_cfg(buffer, cfg) } - fn source_with_context( - &mut self, - context: Ctx, - f: F, - ) -> &mut aimdb_core::RecordRegistrar<'a, T> + fn source_with_context(&mut self, context: Ctx, f: F) -> &mut Self where Ctx: Send + 'static, F: FnOnce(aimdb_core::RuntimeContext, aimdb_core::Producer, Ctx) -> Fut + Send + 'static, diff --git a/aimdb-mqtt-connector/tests/link_ext_tests.rs b/aimdb-mqtt-connector/tests/link_ext_tests.rs index bdb6e0fc..99e22077 100644 --- a/aimdb-mqtt-connector/tests/link_ext_tests.rs +++ b/aimdb-mqtt-connector/tests/link_ext_tests.rs @@ -225,7 +225,8 @@ async fn detached_links_take_the_same_knobs() { /// `publish` / `subscribe` take the MQTT knobs like any other link. #[tokio::test] async fn publish_and_subscribe_take_the_knobs() { - let key_test_reading_contract_6 = aimdb_core::Name::::new("test.reading.contract"); + let key_test_reading_contract_6 = + aimdb_data_contracts::Key::::new("test.reading.contract"); let runtime = Arc::new(TokioAdapter::new().unwrap()); let mut builder = AimDbBuilder::new().runtime(runtime); let mqtt = builder diff --git a/aimdb-persistence/src/ext.rs b/aimdb-persistence/src/ext.rs index bea71d8d..6ed543f7 100644 --- a/aimdb-persistence/src/ext.rs +++ b/aimdb-persistence/src/ext.rs @@ -27,14 +27,15 @@ where /// Rows are stored under the record key. That key is also the `topic` a /// history query returns, so history is authorized against the same name /// as live reads. - fn persist(&mut self) -> &mut RecordRegistrar<'a, T>; + fn persist(&mut self) -> &mut Self; } -impl<'a, T> RecordRegistrarPersistExt<'a, T> for RecordRegistrar<'a, T> +impl<'a, T, S: aimdb_core::SchemaState> RecordRegistrarPersistExt<'a, T> + for RecordRegistrar<'a, T, S> where T: serde::Serialize + Send + Sync + Clone + core::fmt::Debug + 'static, { - fn persist(&mut self) -> &mut RecordRegistrar<'a, T> { + fn persist(&mut self) -> &mut Self { let record_name = self.record_key().to_owned(); // Retrieve the backend from the builder's Extensions TypeMap, if configured. let backend: Option> = self diff --git a/aimdb-tokio-adapter/src/lib.rs b/aimdb-tokio-adapter/src/lib.rs index f717edb3..9e9b4201 100644 --- a/aimdb-tokio-adapter/src/lib.rs +++ b/aimdb-tokio-adapter/src/lib.rs @@ -46,7 +46,8 @@ where fn buffer(&mut self, cfg: aimdb_core::buffer::BufferCfg) -> &mut Self; } -impl TokioRecordRegistrarExt for aimdb_core::RecordRegistrar<'_, T> +impl TokioRecordRegistrarExt + for aimdb_core::RecordRegistrar<'_, T, S> where T: Send + Sync + Clone + core::fmt::Debug + 'static, { diff --git a/aimdb-wasm-adapter/src/lib.rs b/aimdb-wasm-adapter/src/lib.rs index a7bf30ee..f4be2651 100644 --- a/aimdb-wasm-adapter/src/lib.rs +++ b/aimdb-wasm-adapter/src/lib.rs @@ -84,7 +84,8 @@ where fn buffer(&mut self, cfg: aimdb_core::buffer::BufferCfg) -> &mut Self; } -impl WasmRecordRegistrarExt for aimdb_core::RecordRegistrar<'_, T> +impl WasmRecordRegistrarExt + for aimdb_core::RecordRegistrar<'_, T, S> where T: Send + Sync + Clone + core::fmt::Debug + 'static, { diff --git a/aimdb-zenoh-connector/README.md b/aimdb-zenoh-connector/README.md index bf763c1a..aa4bacb8 100644 --- a/aimdb-zenoh-connector/README.md +++ b/aimdb-zenoh-connector/README.md @@ -48,12 +48,12 @@ let ros2 = Ros2Connector::new("tcp/192.168.10.5:7447", .register::(); let mut builder = AimDbBuilder::new().runtime(runtime).with_connector(ros2); -let record_1 = aimdb_core::Name::::new("cell4.temperature"); +let record_1 = aimdb_data_contracts::Key::::new("cell4.temperature"); builder.configure(record_1, |reg| { reg.buffer(BufferCfg::SpmcRing { capacity: 16 }) .linked_to("ros2://cell4/temperature"); // a ROS publisher }); -let record_2 = aimdb_core::Name::::new("cell4.spindle.cmd"); +let record_2 = aimdb_data_contracts::Key::::new("cell4.spindle.cmd"); builder.configure(record_2, |reg| { reg.buffer(BufferCfg::Mailbox) .linked_from("ros2://cell4/spindle_cmd"); // a ROS subscription @@ -88,7 +88,7 @@ use aimdb_zenoh_connector::ZenohConnector; let zenoh = ZenohConnector::new("tcp/192.168.10.5:7447"); builder.with_connector(zenoh); -let record_3 = aimdb_core::Name::::new("cell4.state"); +let record_3 = aimdb_data_contracts::Key::::new("cell4.state"); builder.configure(record_3, |reg| { reg.buffer(BufferCfg::SingleLatest) .linked_to_with("zenoh://aimdb/cell4/state", Postcard::<128>); @@ -124,7 +124,7 @@ let mut builder = AimDbBuilder::new().runtime(runtime) .with_connector(zenoh) .with_connector(ros2); -let record_5 = aimdb_core::Name::::new("cell4.temperature"); +let record_5 = aimdb_data_contracts::Key::::new("cell4.temperature"); builder.configure(record_5, |reg| { reg.buffer(BufferCfg::SpmcRing { capacity: 16 }) .linked_from("zenoh://cell4/probe/temperature") diff --git a/aimdb-zenoh-connector/examples/ros2_gateway.rs b/aimdb-zenoh-connector/examples/ros2_gateway.rs index a0cedb8b..22400ff7 100644 --- a/aimdb-zenoh-connector/examples/ros2_gateway.rs +++ b/aimdb-zenoh-connector/examples/ros2_gateway.rs @@ -54,9 +54,10 @@ struct Twist { angular: Vector3, } +const CMD_VEL: aimdb_data_contracts::Key = aimdb_data_contracts::Key::new("robot.cmd_vel"); + #[tokio::main] async fn main() { - let key_robot_cmd_vel_1 = aimdb_core::Name::::new("robot.cmd_vel"); let endpoint = std::env::var("ZENOH_ENDPOINT").unwrap_or_else(|_| "tcp/127.0.0.1:7447".into()); let socket = std::env::var("AIMX_SOCKET").unwrap_or_else(|_| "/tmp/aimdb-ros2-gateway.sock".into()); @@ -83,15 +84,14 @@ async fn main() { .with_connector(aimx); // SingleLatest: the record is the robot's current command, which // `aimdb record get` reads and a late `aimdb watch` receives first. - builder.configure(key_robot_cmd_vel_1, |reg| { + builder.configure(CMD_VEL, |reg| { reg.buffer(BufferCfg::SingleLatest) .with_remote_access() .linked_from("ros2://cmd_vel") // CDR, as a ROS subscription .linked_to_with("zenoh://telemetry/cmd_vel", Json); // JSON, plain Zenoh }); let (db, runner) = builder.build().await.expect("build"); - let record_key_1 = aimdb_core::Name::::new("robot.cmd_vel"); - let mut reader = db.subscribe(record_key_1).expect("reader"); + let mut reader = db.subscribe(CMD_VEL).expect("reader"); tokio::spawn(runner.run()); println!("ros2_gateway: /cmd_vel -> robot.cmd_vel -> telemetry/cmd_vel"); diff --git a/aimdb-zenoh-connector/examples/ros2_listener.rs b/aimdb-zenoh-connector/examples/ros2_listener.rs index 9e982061..6a40c35f 100644 --- a/aimdb-zenoh-connector/examples/ros2_listener.rs +++ b/aimdb-zenoh-connector/examples/ros2_listener.rs @@ -26,9 +26,10 @@ struct StringMsg { data: String, } +const COMMAND: aimdb_data_contracts::Key = aimdb_data_contracts::Key::new("command"); + #[tokio::main] async fn main() { - let key_command_1 = aimdb_core::Name::::new("command"); let endpoint = std::env::var("ZENOH_ENDPOINT").unwrap_or_else(|_| "tcp/127.0.0.1:7447".into()); let ros2 = Ros2Connector::new(endpoint, Ros2Node::new("listener").namespace("/aimdb")) .register::(); @@ -36,13 +37,12 @@ async fn main() { let mut builder = AimDbBuilder::new() .runtime(Arc::new(TokioAdapter::new().unwrap())) .with_connector(ros2); - builder.configure(key_command_1, |reg| { + builder.configure(COMMAND, |reg| { reg.buffer(BufferCfg::SpmcRing { capacity: 16 }); reg.linked_from("ros2://aimdb_cmd"); }); let (db, runner) = builder.build().await.expect("build"); - let record_key_1 = aimdb_core::Name::::new("command"); - let mut reader = db.subscribe(record_key_1).expect("reader"); + let mut reader = db.subscribe(COMMAND).expect("reader"); tokio::spawn(runner.run()); while let Ok(msg) = reader.recv().await { diff --git a/aimdb-zenoh-connector/examples/turtlesim_mcp.rs b/aimdb-zenoh-connector/examples/turtlesim_mcp.rs index fff1861d..a40c37aa 100644 --- a/aimdb-zenoh-connector/examples/turtlesim_mcp.rs +++ b/aimdb-zenoh-connector/examples/turtlesim_mcp.rs @@ -184,8 +184,10 @@ async fn main() { async fn run() { let key_turtle_goal_1 = aimdb_core::Name::::new("turtle.goal"); - let key_turtle_pose_2 = aimdb_core::Name::

::new("turtle.pose"); - let key_turtle_cmd_vel_3 = aimdb_core::Name::::new("turtle.cmd_vel"); + // Pose and Twist are ROS contracts: `Key` declares their schema, which + // `linked_from` / `linked_to` require. Goal is plain app state: `Name`. + let pose_key = aimdb_data_contracts::Key::

::new("turtle.pose"); + let cmd_vel_key = aimdb_data_contracts::Key::::new("turtle.cmd_vel"); let endpoint = std::env::var("ZENOH_ENDPOINT").unwrap_or_else(|_| "tcp/127.0.0.1:7447".into()); let socket = std::env::var("AIMX_SOCKET").unwrap_or_else(|_| "/tmp/aimdb-turtlesim.sock".into()); @@ -212,21 +214,18 @@ async fn run() { builder.configure(key_turtle_goal_1, |reg| { reg.buffer(BufferCfg::SingleLatest).with_remote_access(); }); - builder.configure(key_turtle_pose_2, |reg| { + builder.configure(pose_key, |reg| { reg.buffer(BufferCfg::SingleLatest) .with_remote_access() .linked_from("ros2://turtle1/pose"); }); // Only the newest velocity command matters. - builder.configure(key_turtle_cmd_vel_3, |reg| { + builder.configure(cmd_vel_key, |reg| { reg.buffer(BufferCfg::SingleLatest) .with_remote_access() .transform_join(|join| { - let key_turtle_goal_4 = aimdb_core::Name::::new("turtle.goal"); - let key_turtle_pose_5 = aimdb_core::Name::

::new("turtle.pose"); - join.input(key_turtle_goal_4) - .input(key_turtle_pose_5) - .on_triggers(|mut rx, producer| async move { + join.input(key_turtle_goal_1).input(pose_key).on_triggers( + |mut rx, producer| async move { let mut goal = Goal::Stop; let mut pose = None; let mut moving = false; @@ -253,7 +252,8 @@ async fn run() { None => {} } } - }) + }, + ) }) .linked_to("ros2://turtle1/cmd_vel"); }); diff --git a/aimdb-zenoh-connector/tests/ros2_inbound.rs b/aimdb-zenoh-connector/tests/ros2_inbound.rs index 9eb96912..d17f76ce 100644 --- a/aimdb-zenoh-connector/tests/ros2_inbound.rs +++ b/aimdb-zenoh-connector/tests/ros2_inbound.rs @@ -93,16 +93,16 @@ async fn a_ros_publisher_reaches_every_record_linked_to_its_topic() { .runtime(Arc::new(TokioAdapter::new().unwrap())) .with_connector(ros2(&endpoint)); for record in ["spindle.a", "spindle.b"] { - let record_key_1 = aimdb_core::Name::::interned(record); + let record_key_1 = aimdb_data_contracts::Key::::interned(record); builder.configure(record_key_1, |reg| { reg.buffer(BufferCfg::SpmcRing { capacity: 16 }); reg.linked_from("ros2://cell4/spindle_cmd"); }); } let (db, runner) = builder.build().await.expect("build"); - let record_key_2 = aimdb_core::Name::::new("spindle.a"); + let record_key_2 = aimdb_data_contracts::Key::::new("spindle.a"); let mut a = db.subscribe(record_key_2).unwrap(); - let record_key_3 = aimdb_core::Name::::new("spindle.b"); + let record_key_3 = aimdb_data_contracts::Key::::new("spindle.b"); let mut b = db.subscribe(record_key_3).unwrap(); tokio::spawn(runner.run()); @@ -155,10 +155,10 @@ async fn a_ros_publisher_reaches_every_record_linked_to_its_topic() { /// Builds a database with one inbound `ros2://` link set up by `link`, and /// returns the build error, if any. async fn build_with( - link: impl FnOnce(&mut RecordRegistrar<'_, Command>) + Send + 'static, + link: impl FnOnce(&mut RecordRegistrar<'_, Command, aimdb_core::Declared>) + Send + 'static, other: bool, ) -> Result<(), String> { - let key_command_1 = aimdb_core::Name::::new("command"); + let key_command_1 = aimdb_data_contracts::Key::::new("command"); let mut builder = AimDbBuilder::new() .runtime(Arc::new(TokioAdapter::new().unwrap())) .with_connector(ros2("")); @@ -167,7 +167,7 @@ async fn build_with( link(reg); }); if other { - let key_other_2 = aimdb_core::Name::::new("other"); + let key_other_2 = aimdb_data_contracts::Key::::new("other"); builder.configure(key_other_2, |reg| { reg.buffer(BufferCfg::SingleLatest); reg.linked_from("ros2://cell4/spindle_cmd"); @@ -178,7 +178,7 @@ async fn build_with( #[tokio::test] async fn build_refuses_inbound_links_ros_could_not_serve() { - let key_command_3 = aimdb_core::Name::::new("command"); + let key_command_3 = aimdb_data_contracts::Key::::new("command"); let e = build_with( |reg| { reg.linked_from("ros2://cell4/{cell}/cmd"); @@ -262,7 +262,7 @@ struct CommandMirror { #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn one_ros_type_per_topic_across_both_directions() { let build = |mirror: bool| async move { - let key_out_4 = aimdb_core::Name::::new("out"); + let key_out_4 = aimdb_data_contracts::Key::::new("out"); let mut builder = AimDbBuilder::new() .runtime(Arc::new(TokioAdapter::new().unwrap())) .with_connector(ros2("").register::()); @@ -271,13 +271,13 @@ async fn one_ros_type_per_topic_across_both_directions() { reg.linked_to("ros2://cell4/spindle_cmd"); }); if mirror { - let key_in_5 = aimdb_core::Name::::new("in"); + let key_in_5 = aimdb_data_contracts::Key::::new("in"); builder.configure(key_in_5, |reg| { reg.buffer(BufferCfg::SingleLatest); reg.linked_from("ros2://cell4/spindle_cmd"); }); } else { - let key_in_6 = aimdb_core::Name::::new("in"); + let key_in_6 = aimdb_data_contracts::Key::::new("in"); builder.configure(key_in_6, |reg| { reg.buffer(BufferCfg::SingleLatest); reg.linked_from("ros2://cell4/spindle_cmd"); diff --git a/aimdb-zenoh-connector/tests/ros2_outbound.rs b/aimdb-zenoh-connector/tests/ros2_outbound.rs index 2735a592..ad8d3e1a 100644 --- a/aimdb-zenoh-connector/tests/ros2_outbound.rs +++ b/aimdb-zenoh-connector/tests/ros2_outbound.rs @@ -83,7 +83,8 @@ fn gid(token: &str) -> [u8; 16] { out } -const RECORD_READING: aimdb_core::Name = aimdb_core::Name::new("reading"); +const RECORD_READING: aimdb_data_contracts::Key = + aimdb_data_contracts::Key::new("reading"); #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_record_appears_as_a_ros_publisher() { @@ -188,7 +189,9 @@ async fn a_record_appears_as_a_ros_publisher() { /// returns the build error. async fn refused( connector: Ros2Connector, - link: impl FnOnce(&mut aimdb_core::RecordRegistrar<'_, Reading>) + Send + 'static, + link: impl FnOnce(&mut aimdb_core::RecordRegistrar<'_, Reading, aimdb_core::Declared>) + + Send + + 'static, ) -> String { let mut builder = AimDbBuilder::new() .runtime(Arc::new(TokioAdapter::new().unwrap())) diff --git a/aimdb-zenoh-connector/tests/shared_session.rs b/aimdb-zenoh-connector/tests/shared_session.rs index fb70f69f..cd57276d 100644 --- a/aimdb-zenoh-connector/tests/shared_session.rs +++ b/aimdb-zenoh-connector/tests/shared_session.rs @@ -78,7 +78,8 @@ async fn counting_proxy(router_port: u16) -> (u16, Arc) { /// The gateway (053 §4.8): `zenoh://` in, `ros2://` out, on one session. async fn gateway(zenoh_first: bool) { - let key_cell4_temperature_1 = aimdb_core::Name::::new("cell4.temperature"); + let key_cell4_temperature_1 = + aimdb_data_contracts::Key::::new("cell4.temperature"); let router_port = free_port(); let router = format!("tcp/127.0.0.1:{router_port}"); let _router = zenoh::open(config("router", &router, true)).await.unwrap(); @@ -146,7 +147,8 @@ async fn gateway(zenoh_first: bool) { ); } -const RECORD_STATE: aimdb_core::Name = aimdb_core::Name::new("state"); +const RECORD_STATE: aimdb_data_contracts::Key = + aimdb_data_contracts::Key::new("state"); #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn the_gateway_opens_one_connection_with_zenoh_registered_first() { @@ -214,7 +216,7 @@ async fn two_ros2_views_on_one_session_are_refused() { /// connections through the same proxy. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn separate_connectors_open_two_connections() { - let key_t_3 = aimdb_core::Name::::new("t"); + let key_t_3 = aimdb_data_contracts::Key::::new("t"); let router_port = free_port(); let router = format!("tcp/127.0.0.1:{router_port}"); let _router = zenoh::open(config("router", &router, true)).await.unwrap(); diff --git a/docs/aimdb-and-ros2.md b/docs/aimdb-and-ros2.md index 7c665fec..575ad151 100644 --- a/docs/aimdb-and-ros2.md +++ b/docs/aimdb-and-ros2.md @@ -99,7 +99,7 @@ let zenoh = ZenohConnector::new("tcp/192.168.10.5:7447"); let ros2 = zenoh.ros2(Ros2Node::new("cell4_gateway")).register::(); builder.with_connector(zenoh).with_connector(ros2); -let record_1 = aimdb_core::Name::::new("cell4.temperature"); +let record_1 = aimdb_data_contracts::Key::::new("cell4.temperature"); builder.configure(record_1, |reg| { reg.buffer(BufferCfg::SpmcRing { capacity: 16 }) .linked_from("zenoh://cell4/probe/temperature") diff --git a/docs/aimdb-usage-guide.md b/docs/aimdb-usage-guide.md index 646f92ac..d046f843 100644 --- a/docs/aimdb-usage-guide.md +++ b/docs/aimdb-usage-guide.md @@ -35,8 +35,20 @@ lookups declare a borrowed `Name::::new(&name)`; lookups do not intern names. A `Name` declaration reports no contract schema, including when its payload happens to implement `SchemaType`. -Link helpers and `.observe()` no longer assign schemas. `contract_schema()` -and public schema setters are removed. Existing envelope and version options +The key is the only source of a record's schema: link helpers and +`.observe()` no longer assign one. Instead, `configure` hands the closure a +registrar typed by whether the key declares a contract +(`RecordRegistrar<'_, T, Declared>` for `Key` / `contract = T`, +`RecordRegistrar<'_, T, Undeclared>` for `Name` / `payload = T`). The +contract verbs — `publish`, `subscribe`, `linked_to`, `linked_from`, their +`_with` forms and `.observe()` — exist only on `Declared` registrars, so using +one on a `Name` record is a compile error ("this record's key declares no +data contract") rather than a record silently reported without a schema. The +raw `.link_to()` / `.link_from()` builders work in both states. Helper +functions that take a registrar name the state they need +(`&mut RecordRegistrar<'_, T, Declared>`) or are generic over +`S: SchemaState`; custom `Input` / `Output` implementations are generic over +`S` too. `contract_schema()` and public schema setters are removed. Existing envelope and version options are unchanged: select inline explicitly before `accepts_from`, and use a static `with_contract` binding for a bare legacy sender. A historical wire version does not change the record's current schema. @@ -258,11 +270,11 @@ impl From for ButtonPress { /// type built `From`. It owns its pin. struct PushButton(Pin<'static>); -impl Input for PushButton +impl Input for PushButton where T: From + Send + Sync + 'static + Debug + Clone, { - fn wire(self, reg: &mut RecordRegistrar<'_, T>) { + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { let PushButton(mut pin) = self; reg.source(move |ctx, producer| async move { let mut press = 0; @@ -444,7 +456,7 @@ async fn main() -> DbResult<()> { // `connect` registers the connector and returns a handle to link through. let mqtt = builder.connect(MqttConnector::new("mqtt://broker.example.com:1883")); - let record_4 = aimdb_core::Name::::new("sensor.reading"); + let record_4 = aimdb_data_contracts::Key::::new("sensor.reading"); builder.configure(record_4, |reg| { reg.buffer(BufferCfg::SingleLatest) .input(subscribe(mqtt, "sensor/room1").with_qos(1)) @@ -494,12 +506,12 @@ let mut builder = AimDbBuilder::new() .with_connector(zenoh) .with_connector(ros2); -let record_5 = aimdb_core::Name::::new("cell4.state"); +let record_5 = aimdb_data_contracts::Key::::new("cell4.state"); builder.configure(record_5, |reg| { reg.buffer(BufferCfg::SingleLatest) .linked_to_with("zenoh://aimdb/cell4/state", Postcard::<128>); }); -let record_6 = aimdb_core::Name::::new("cell4.temperature"); +let record_6 = aimdb_data_contracts::Key::::new("cell4.temperature"); builder.configure(record_6, |reg| { reg.buffer(BufferCfg::SpmcRing { capacity: 16 }) .linked_to("ros2://cell4/temperature"); @@ -729,11 +741,11 @@ there; the MQTT demos generic over its record and bounded by `T: From`: ```rust -impl Input for PushButton +impl Input for PushButton where T: From + Send + Sync + 'static + Debug + Clone, { - fn wire(self, reg: &mut RecordRegistrar<'_, T>) { + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { reg.source(move |ctx, producer| async move { /* wait for an edge, debounce */ producer.produce(T::from(ButtonEvent { /* … */ })); @@ -757,7 +769,7 @@ inputs once, as struct fields, and an input takes one by value: let board = board::init(spawner).await; let NucleoInputs { b1 } = board.inputs; -builder.configure::(ButtonKey::B1, |reg| { +builder.configure(ButtonKey::B1, |reg| { reg.buffer_sized::<8, 3>(EmbassyBufferType::SpmcRing) .input(PushButton::on(b1)) .output(publish(mqtt, ButtonKey::B1.link_address().unwrap())); diff --git a/docs/ros2-walkthrough.md b/docs/ros2-walkthrough.md index 3358371a..57bfc271 100644 --- a/docs/ros2-walkthrough.md +++ b/docs/ros2-walkthrough.md @@ -94,7 +94,7 @@ let ros2 = zenoh .ros2(Ros2Node::new("telemetry_gateway").namespace("/aimdb")) .register::(); -let record_1 = aimdb_core::Name::::new("robot.cmd_vel"); +let record_1 = aimdb_data_contracts::Key::::new("robot.cmd_vel"); builder.configure(record_1, |reg| { reg.buffer(BufferCfg::SingleLatest) .with_remote_access() diff --git a/examples/embassy-knx-connector-demo/src/board.rs b/examples/embassy-knx-connector-demo/src/board.rs index 9b885439..b006610d 100644 --- a/examples/embassy-knx-connector-demo/src/board.rs +++ b/examples/embassy-knx-connector-demo/src/board.rs @@ -226,11 +226,11 @@ impl PushButton { } } -impl Input for PushButton +impl Input for PushButton where T: From + Send + Sync + 'static + Debug + Clone, { - fn wire(self, reg: &mut RecordRegistrar<'_, T>) { + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { let PushButton { button: UserButton(mut pin), } = self; diff --git a/examples/embassy-mqtt-connector-demo/README.md b/examples/embassy-mqtt-connector-demo/README.md index 8bbd97a0..dc9cff13 100644 --- a/examples/embassy-mqtt-connector-demo/README.md +++ b/examples/embassy-mqtt-connector-demo/README.md @@ -39,7 +39,7 @@ let mut builder = AimDbBuilder::new() .with_client_id("my-client-id"), ); -let record_1 = aimdb_core::Name::::new("temperature"); +let record_1 = aimdb_data_contracts::Key::::new("temperature"); builder.configure(record_1, |reg| { reg.buffer(BufferCfg::SingleLatest) .source(sensor_producer) diff --git a/examples/embassy-mqtt-connector-demo/src/board.rs b/examples/embassy-mqtt-connector-demo/src/board.rs index 055aa46c..45206a9d 100644 --- a/examples/embassy-mqtt-connector-demo/src/board.rs +++ b/examples/embassy-mqtt-connector-demo/src/board.rs @@ -244,11 +244,11 @@ impl PushButton { } } -impl Input for PushButton +impl Input for PushButton where T: From + Send + Sync + 'static + Debug + Clone, { - fn wire(self, reg: &mut RecordRegistrar<'_, T>) { + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { let PushButton { button: UserButton(mut pin), name, diff --git a/examples/mqtt-connector-demo-common/src/sim.rs b/examples/mqtt-connector-demo-common/src/sim.rs index e9dc6100..5efc149c 100644 --- a/examples/mqtt-connector-demo-common/src/sim.rs +++ b/examples/mqtt-connector-demo-common/src/sim.rs @@ -114,11 +114,11 @@ impl Thermometer { } } -impl Input for Thermometer +impl Input for Thermometer where T: From + Send + Sync + 'static + Debug + Clone, { - fn wire(self, reg: &mut RecordRegistrar<'_, T>) { + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { let Thermometer { channel, period_secs, diff --git a/examples/remote-access-demo/src/server.rs b/examples/remote-access-demo/src/server.rs index 915cd6dd..3a52c056 100644 --- a/examples/remote-access-demo/src/server.rs +++ b/examples/remote-access-demo/src/server.rs @@ -84,9 +84,13 @@ struct AppSettings { feature_flag_alpha: bool, } +/// `Temperature` is a contract (`SchemaType` + `Observable`): its key carries +/// the schema reported in `record.list`, and `.observe()` requires it. +const TEMPERATURE: aimdb_data_contracts::Key = + aimdb_data_contracts::Key::new("server::Temperature"); + #[tokio::main] async fn main() -> Result<(), Box> { - let key_server_temperature_1 = aimdb_core::Name::::new("server::Temperature"); let key_server_temperaturefahrenheit_2 = aimdb_core::Name::::new("server::TemperatureFahrenheit"); let key_server_systemstatus_4 = aimdb_core::Name::::new("server::SystemStatus"); @@ -146,7 +150,7 @@ async fn main() -> Result<(), Box> { // `.observe()` feeds the reading's signal (`Observable::signal()`, here // `celsius`) into a live gauge — last/min/max/mean surface in // `record.list`/`record.get` as `signal_stats`. - builder.configure(key_server_temperature_1, |reg| { + builder.configure(TEMPERATURE, |reg| { reg.buffer(BufferCfg::SpmcRing { capacity: 100 }) .with_remote_access() .source(temperature_simulator) @@ -161,10 +165,9 @@ async fn main() -> Result<(), Box> { // transform closure itself), unlike `.source()`/`.tap()` which time the // interval between calls — see `get_stage_profiling`. builder.configure(key_server_temperaturefahrenheit_2, |reg| { - let key_server_temperature_3 = aimdb_core::Name::::new("server::Temperature"); reg.buffer(BufferCfg::SpmcRing { capacity: 100 }) .with_remote_access() - .transform(key_server_temperature_3, |b| { + .transform(TEMPERATURE, |b| { b.map(|t: &Temperature| { Some(TemperatureFahrenheit { sensor_id: t.sensor_id.clone(), diff --git a/examples/tokio-knx-connector-demo/src/main.rs b/examples/tokio-knx-connector-demo/src/main.rs index acd81e37..e9945244 100644 --- a/examples/tokio-knx-connector-demo/src/main.rs +++ b/examples/tokio-knx-connector-demo/src/main.rs @@ -57,11 +57,11 @@ use knx_connector_demo_common::{ /// every record type built `From`. struct EnterKey; -impl Input for EnterKey +impl Input for EnterKey where T: From + Send + Sync + 'static + Debug + Clone, { - fn wire(self, reg: &mut RecordRegistrar<'_, T>) { + fn wire(self, reg: &mut RecordRegistrar<'_, T, S>) { reg.source(|ctx, producer| async move { let log = ctx.log(); log.info("\n⌨️ Press ENTER to toggle light on 1/0/6"); diff --git a/tools/rolling-upgrade-fixture/contracts_n/src/lib.rs b/tools/rolling-upgrade-fixture/contracts_n/src/lib.rs index 07718f27..d1ddd7ec 100644 --- a/tools/rolling-upgrade-fixture/contracts_n/src/lib.rs +++ b/tools/rolling-upgrade-fixture/contracts_n/src/lib.rs @@ -25,8 +25,11 @@ aimdb_data_contracts::catalog! { contracts: [TemperatureV1], helpers: [], } migration_chain! { type Current = TemperatureV1; steps {} } /// Firmware's actual link declaration, also compiled for Cortex-M. -pub fn publish + 'static>( - r: &mut aimdb_core::RecordRegistrar<'_, Temperature>, +pub fn publish< + C: aimdb_data_contracts::LinkCodec + 'static, + S: aimdb_core::SchemaState, +>( + r: &mut aimdb_core::RecordRegistrar<'_, Temperature, S>, codec: C, ) { use aimdb_data_contracts::{EnvelopeCarrier, EnvelopeLinkExt, LinkCodecBuilderExt}; @@ -36,8 +39,11 @@ pub fn publish + 'static>( .finish(); } -pub fn receive + 'static>( - r: &mut aimdb_core::RecordRegistrar<'_, Temperature>, +pub fn receive< + C: aimdb_data_contracts::LinkCodec + 'static, + S: aimdb_core::SchemaState, +>( + r: &mut aimdb_core::RecordRegistrar<'_, Temperature, S>, codec: C, ) { use aimdb_data_contracts::{EnvelopeCarrier, EnvelopeLinkExt, LinkCodecBuilderExt}; diff --git a/tools/rolling-upgrade-fixture/contracts_n1/src/lib.rs b/tools/rolling-upgrade-fixture/contracts_n1/src/lib.rs index 94c2fce1..a868922a 100644 --- a/tools/rolling-upgrade-fixture/contracts_n1/src/lib.rs +++ b/tools/rolling-upgrade-fixture/contracts_n1/src/lib.rs @@ -62,8 +62,11 @@ impl MigrationStep for V1ToV2 { aimdb_data_contracts::catalog! { contracts: [TemperatureV1, TemperatureV2, Humidity], helpers: [], } migration_chain! { type Current = TemperatureV2; steps { V1ToV2: TemperatureV1 => TemperatureV2 } } -pub fn receive + 'static>( - r: &mut aimdb_core::RecordRegistrar<'_, Temperature>, +pub fn receive< + C: aimdb_data_contracts::LinkCodec + 'static, + S: aimdb_core::SchemaState, +>( + r: &mut aimdb_core::RecordRegistrar<'_, Temperature, S>, codec: C, ) { use aimdb_data_contracts::{ @@ -76,8 +79,11 @@ pub fn receive + 'static>( .finish(); } -pub fn send_to_firmware + 'static>( - r: &mut aimdb_core::RecordRegistrar<'_, Temperature>, +pub fn send_to_firmware< + C: aimdb_data_contracts::LinkCodec + 'static, + S: aimdb_core::SchemaState, +>( + r: &mut aimdb_core::RecordRegistrar<'_, Temperature, S>, codec: C, ) { use aimdb_data_contracts::{