Skip to main content

aimdb_core/
connector.rs

1//! Connector infrastructure for external protocol integration
2//!
3//! Provides the `.link_to()` / `.link_from()` builder API for ergonomic
4//! connector setup with automatic client lifecycle management. Connectors
5//! bridge AimDB records to external systems (MQTT, KNX, WebSocket, …).
6//!
7//! # Design Philosophy
8//!
9//! - **User Extensions**: Connector implementations are provided by users
10//! - **Shared Clients**: Single client instance shared across tasks (Arc or static)
11//! - **No Buffering**: Direct access to protocol clients, no intermediate queues
12//! - **Type Safety**: Compile-time guarantees via typed handlers
13//!
14//! # Example
15//!
16//! ```no_run
17//! # use aimdb_core::AimDbBuilder;
18//! # #[derive(Clone, Debug)] struct WeatherAlert { level: u8 }
19//! # fn wire(builder: &mut AimDbBuilder) {
20//! builder.configure::<WeatherAlert>("weather.alert", |reg| {
21//!     // .buffer(BufferCfg::SingleLatest) — via your runtime adapter's ext trait
22//!     reg.link_to("mqtt://alerts/weather")
23//!         .with_serializer(|_ctx, alert: &WeatherAlert| Ok(vec![alert.level]))
24//!         .finish();
25//! });
26//! # }
27//! ```
28
29use core::fmt::{self, Debug};
30use core::future::Future;
31use core::pin::Pin;
32
33use alloc::{
34    boxed::Box,
35    string::{String, ToString},
36    sync::Arc,
37    vec::Vec,
38};
39
40use alloc::format;
41
42use crate::{builder::AimDb, DbResult};
43
44/// Error shared by outbound record serialization operations.
45///
46/// Deliberately separate from the session `CodecError`, which describes
47/// failures in an envelope codec (AimX, WebSocket, and similar framed
48/// protocols). A link codec sits one layer higher: it turns a typed record into
49/// the opaque payload passed to a connector.
50///
51/// Uses an enum instead of `String` for predictable `no_std` behavior and
52/// `defmt` logging support on Embassy targets.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum SerializeError {
55    /// Output buffer is too small for the serialized data
56    BufferTooSmall,
57
58    /// Invalid data that cannot be serialized
59    InvalidData,
60}
61
62#[cfg(feature = "defmt")]
63impl defmt::Format for SerializeError {
64    fn format(&self, f: defmt::Formatter) {
65        match self {
66            Self::BufferTooSmall => defmt::write!(f, "BufferTooSmall"),
67            Self::InvalidData => defmt::write!(f, "InvalidData"),
68        }
69    }
70}
71
72#[cfg(feature = "std")]
73impl std::fmt::Display for SerializeError {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        match self {
76            Self::BufferTooSmall => write!(f, "Output buffer too small"),
77            Self::InvalidData => write!(f, "Invalid data for serialization"),
78        }
79    }
80}
81
82#[cfg(feature = "std")]
83impl std::error::Error for SerializeError {}
84
85// ============================================================================
86// TopicWriter - Destinations written into bounded storage
87// ============================================================================
88
89/// Writes an outbound link's destination for each value (outbound only).
90///
91/// Closures implement it, and [`with_topic_fn`](crate::typed_api::OutboundLinkBuilder::with_topic_fn)
92/// takes one directly. A writer type goes to
93/// [`with_topic_writer`](crate::typed_api::OutboundLinkBuilder::with_topic_writer).
94///
95/// # Example
96///
97/// ```rust
98/// use aimdb_core::connector::{TopicBuf, TopicOverflow, TopicWriter};
99/// use core::fmt::Write;
100/// # #[derive(Clone, Debug)] struct Temperature { sensor_id: u32 }
101///
102/// struct SensorTopic;
103///
104/// impl TopicWriter<Temperature> for SensorTopic {
105///     fn write_topic(&self, value: &Temperature, out: &mut TopicBuf<'_>) -> Result<bool, TopicOverflow> {
106///         write!(out, "sensors/temp/{}", value.sensor_id)?;
107///         Ok(true)
108///     }
109/// }
110/// ```
111pub trait TopicWriter<T>: Send + Sync {
112    /// Write the destination for `value` into `out`.
113    ///
114    /// `Ok(true)` publishes to what was written, `Ok(false)` to the static
115    /// topic from the `link_to()` URL. A value whose topic does not fit is
116    /// skipped, whatever this returns; the topic is never truncated.
117    fn write_topic(&self, value: &T, out: &mut TopicBuf<'_>) -> Result<bool, TopicOverflow>;
118}
119
120impl<T, F> TopicWriter<T> for F
121where
122    F: Fn(&T, &mut TopicBuf<'_>) -> Result<bool, TopicOverflow> + Send + Sync,
123{
124    fn write_topic(&self, value: &T, out: &mut TopicBuf<'_>) -> Result<bool, TopicOverflow> {
125        self(value, out)
126    }
127}
128
129/// A topic did not fit in its link's topic capacity.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub struct TopicOverflow;
132
133impl From<core::fmt::Error> for TopicOverflow {
134    fn from(_: core::fmt::Error) -> Self {
135        TopicOverflow
136    }
137}
138
139/// Bounded topic storage handed to a [`TopicWriter`].
140///
141/// A write that does not fit is refused whole, so the contents are always
142/// valid UTF-8. After the first refused write every later write is refused
143/// too.
144pub struct TopicBuf<'a> {
145    buf: &'a mut [u8],
146    len: usize,
147    overflowed: bool,
148}
149
150impl<'a> TopicBuf<'a> {
151    /// An empty topic over `buf`; its capacity is `buf.len()`.
152    pub fn new(buf: &'a mut [u8]) -> Self {
153        Self {
154            buf,
155            len: 0,
156            overflowed: false,
157        }
158    }
159
160    /// Append `s`, or refuse it whole if it does not fit.
161    pub fn push_str(&mut self, s: &str) -> Result<(), TopicOverflow> {
162        let end = self.len + s.len();
163        match self.buf.get_mut(self.len..end) {
164            Some(dst) if !self.overflowed => {
165                dst.copy_from_slice(s.as_bytes());
166                self.len = end;
167                Ok(())
168            }
169            _ => {
170                self.overflowed = true;
171                Err(TopicOverflow)
172            }
173        }
174    }
175
176    /// Bytes written so far.
177    pub fn len(&self) -> usize {
178        self.len
179    }
180
181    /// Whether nothing has been written.
182    pub fn is_empty(&self) -> bool {
183        self.len == 0
184    }
185
186    /// The most bytes this topic can hold.
187    pub fn capacity(&self) -> usize {
188        self.buf.len()
189    }
190
191    /// The topic written so far.
192    pub fn as_str(&self) -> &str {
193        // Only whole `&str`s are ever copied in, so this cannot fail.
194        self.buf
195            .get(..self.len)
196            .and_then(|b| core::str::from_utf8(b).ok())
197            .unwrap_or_default()
198    }
199
200    /// Whether a write was refused.
201    pub(crate) fn overflowed(&self) -> bool {
202        self.overflowed
203    }
204}
205
206impl core::fmt::Write for TopicBuf<'_> {
207    fn write_str(&mut self, s: &str) -> core::fmt::Result {
208        self.push_str(s).map_err(|_| core::fmt::Error)
209    }
210}
211
212/// A connector registered with [`AimDbBuilder::connect`](crate::AimDbBuilder::connect).
213///
214/// Links started from a handle ([`OutboundLink::on`](crate::OutboundLink::on),
215/// [`InboundLink::on`](crate::InboundLink::on)) take the connector's scheme,
216/// so they cannot name a connector that was never registered.
217///
218/// The handle is `Copy` and names its connector by position, not by scheme,
219/// so it holds no string. It is only valid in the builder that returned it;
220/// a link on another builder's handle fails `build()`.
221#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
222pub struct ConnectorHandle {
223    /// The [`AimDbBuilder`](crate::AimDbBuilder) that returned the handle.
224    pub(crate) builder: u32,
225    /// Position in that builder's connector list.
226    pub(crate) index: u16,
227}
228
229/// A fresh id per [`AimDbBuilder`](crate::AimDbBuilder), so a
230/// [`ConnectorHandle`] from one builder is told apart from another's. Starts
231/// at 1; tests use 0 as a fixed id.
232pub(crate) fn next_builder_id() -> u32 {
233    use core::sync::atomic::{AtomicU32, Ordering};
234    static NEXT: AtomicU32 = AtomicU32::new(1);
235    NEXT.fetch_add(1, Ordering::Relaxed)
236}
237
238/// The full `scheme://address` URL of a link started from `handle`, or why
239/// it cannot have one.
240///
241/// An address without a scheme takes the connector's. An address with one
242/// (as a `#[link_address]` key gives) must name the connector's scheme.
243pub(crate) fn resolve_link_url(
244    builder_id: u32,
245    connectors: &[Box<dyn ConnectorBuilder>],
246    handle: ConnectorHandle,
247    address: &str,
248) -> Result<String, String> {
249    // An out-of-range index can only come from another builder's handle.
250    let Some(connector) = connectors
251        .get(usize::from(handle.index))
252        .filter(|_| handle.builder == builder_id)
253    else {
254        return Err("Connector handle belongs to a different AimDbBuilder".into());
255    };
256    let scheme = connector.scheme();
257    match address.split_once("://") {
258        None => Ok(alloc::format!("{scheme}://{address}")),
259        Some((given, _)) if given == scheme => Ok(address.into()),
260        Some((given, _)) => Err(alloc::format!(
261            "Address scheme '{given}' does not match the connector's scheme '{scheme}'"
262        )),
263    }
264}
265
266/// Address of a record link: `scheme://resource` (e.g. `mqtt://sensors/temp`).
267///
268/// A link address names a topic/resource on a connector's already-configured
269/// endpoint — it is *not* a URL: there is no host, port, or credential
270/// component (the connector constructor takes the endpoint
271/// [`ConnectorUrl`]). The scheme selects which registered connector serves
272/// the link; the resource is passed to it verbatim (e.g. an MQTT topic, a
273/// KNX group address).
274///
275/// A trailing `?key=value` query is accepted and ignored; per-link options
276/// are passed via `.with_config()` / `.with_timeout_ms()`.
277#[derive(Clone, Debug, PartialEq)]
278pub struct LinkAddress {
279    scheme: String,
280    resource: String,
281}
282
283impl LinkAddress {
284    /// Parses a `scheme://resource` link address.
285    ///
286    /// # Example
287    ///
288    /// ```rust
289    /// use aimdb_core::connector::LinkAddress;
290    ///
291    /// let addr = LinkAddress::parse("mqtt://sensors/temp").unwrap();
292    /// assert_eq!(addr.scheme(), "mqtt");
293    /// assert_eq!(addr.resource_id(), "sensors/temp");
294    /// ```
295    pub fn parse(s: &str) -> DbResult<Self> {
296        use crate::DbError;
297
298        let (scheme, rest) = s
299            .split_once("://")
300            .ok_or_else(|| DbError::InvalidOperation {
301                operation: "LinkAddress::parse".into(),
302                reason: alloc::format!("link address '{s}' missing '://' separator"),
303            })?;
304
305        // Per-link options travel via .with_config(); a query here is legal
306        // input but carries no meaning — strip it.
307        let resource = rest.split_once('?').map(|(r, _)| r).unwrap_or(rest);
308        let resource = resource.trim_start_matches('/');
309
310        if scheme.is_empty() || resource.is_empty() {
311            return Err(DbError::InvalidOperation {
312                operation: "LinkAddress::parse".into(),
313                reason: alloc::format!("link address '{s}' needs both a scheme and a resource"),
314            });
315        }
316
317        Ok(Self {
318            scheme: scheme.to_string(),
319            resource: resource.to_string(),
320        })
321    }
322
323    /// Returns the scheme (selects the registered connector, e.g. `"mqtt"`).
324    pub fn scheme(&self) -> &str {
325        &self.scheme
326    }
327
328    /// Returns the resource identifier the connector addresses (topic, group
329    /// address, path — passed to the connector verbatim).
330    pub fn resource_id(&self) -> &str {
331        &self.resource
332    }
333}
334
335impl fmt::Display for LinkAddress {
336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337        write!(f, "{}://{}", self.scheme, self.resource)
338    }
339}
340
341/// Parsed connector *endpoint* URL with protocol, host, port, and credentials
342///
343/// This is the URL a connector is constructed with (broker/gateway/server
344/// endpoint) — record links use the far simpler [`LinkAddress`] instead.
345/// The parser is scheme-agnostic: any `scheme://…` URL parses. Connectors in
346/// this workspace use e.g.:
347/// - MQTT: `mqtt://host:port`, `mqtts://host:port`
348/// - KNX: `knx://gateway:3671`
349/// - WebSocket: `ws://host:port/path`, `wss://host:port/path`
350#[derive(Clone, Debug, PartialEq)]
351pub struct ConnectorUrl {
352    /// Protocol scheme (e.g. mqtt, mqtts, knx, ws, wss, uds, serial)
353    pub scheme: String,
354
355    /// Host, or a comma-separated host list (preserved verbatim)
356    pub host: String,
357
358    /// Port number (optional, protocol-specific defaults)
359    pub port: Option<u16>,
360
361    /// Path component (optional)
362    pub path: Option<String>,
363
364    /// Username for authentication (optional)
365    pub username: Option<String>,
366
367    /// Password for authentication (optional)
368    pub password: Option<String>,
369
370    /// Query parameters (optional, parsed from URL)
371    pub query_params: Vec<(String, String)>,
372}
373
374impl ConnectorUrl {
375    /// Parses a connector URL string
376    ///
377    /// # Supported Formats
378    ///
379    /// - `mqtt://host:port`
380    /// - `mqtt://user:pass@host:port`
381    /// - `mqtts://host:port` (TLS)
382    /// - `knx://gateway:3671`
383    /// - `ws://host:port/path?key=value` (WebSocket)
384    /// - `wss://host:port/path` (WebSocket Secure)
385    ///
386    /// Any other `scheme://…` parses the same way; comma-separated host
387    /// lists are preserved verbatim in [`host`](ConnectorUrl::host).
388    ///
389    /// # Example
390    ///
391    /// ```rust
392    /// use aimdb_core::connector::ConnectorUrl;
393    ///
394    /// let url = ConnectorUrl::parse("mqtt://user:pass@broker.example.com:1883").unwrap();
395    /// assert_eq!(url.scheme, "mqtt");
396    /// assert_eq!(url.host, "broker.example.com");
397    /// assert_eq!(url.port, Some(1883));
398    /// assert_eq!(url.username, Some("user".to_string()));
399    /// ```
400    pub fn parse(url: &str) -> DbResult<Self> {
401        parse_connector_url(url)
402    }
403
404    /// Returns the default port for this protocol scheme
405    pub fn default_port(&self) -> Option<u16> {
406        match self.scheme.as_str() {
407            "mqtt" | "ws" => Some(1883),
408            "mqtts" | "wss" => Some(8883),
409            _ => None,
410        }
411    }
412
413    /// Returns the effective port (explicit or default)
414    pub fn effective_port(&self) -> Option<u16> {
415        self.port.or_else(|| self.default_port())
416    }
417
418    /// Returns true if this is a secure connection (TLS)
419    pub fn is_secure(&self) -> bool {
420        matches!(self.scheme.as_str(), "mqtts" | "https" | "wss")
421    }
422
423    /// Returns the URL scheme (protocol)
424    pub fn scheme(&self) -> &str {
425        &self.scheme
426    }
427
428    /// Returns the path component, or "/" if not specified
429    pub fn path(&self) -> &str {
430        self.path.as_deref().unwrap_or("/")
431    }
432}
433
434impl fmt::Display for ConnectorUrl {
435    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
436        write!(f, "{}://", self.scheme)?;
437
438        if let Some(ref username) = self.username {
439            write!(f, "{}", username)?;
440            if self.password.is_some() {
441                write!(f, ":****")?; // Don't expose password in Display
442            }
443            write!(f, "@")?;
444        }
445
446        write!(f, "{}", self.host)?;
447
448        if let Some(port) = self.port {
449            write!(f, ":{}", port)?;
450        }
451
452        if let Some(ref path) = self.path {
453            if !path.starts_with('/') {
454                write!(f, "/")?;
455            }
456            write!(f, "{}", path)?;
457        }
458
459        Ok(())
460    }
461}
462
463/// Link config key naming the wire format of the link's codec (e.g. `"cdr"`).
464///
465/// Recorded by codec verbs and removed by the serializer/deserializer setters,
466/// so it is present only when a known codec installed the current serializer.
467/// Keys prefixed `aimdb.` are reserved; connectors must not use them.
468pub const WIRE_FORMAT_KEY: &str = "aimdb.wire_format";
469
470/// Configuration for an outbound connector link
471///
472/// Stores the parsed URL, configuration, and the route factory until the
473/// database is built. `OutboundRoutes` runs the factory once per link.
474#[derive(Clone)]
475pub struct ConnectorLink {
476    /// Parsed link address (`scheme://resource`)
477    pub url: LinkAddress,
478
479    /// Additional configuration options (protocol-specific)
480    pub config: Vec<(String, String)>,
481
482    /// Builds the link's route for `OutboundRoutes`.
483    pub(crate) route_factory: crate::outbound::RouteFactoryFn,
484}
485
486impl Debug for ConnectorLink {
487    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
488        f.debug_struct("ConnectorLink")
489            .field("url", &self.url)
490            .field("config", &self.config)
491            .finish_non_exhaustive()
492    }
493}
494
495impl ConnectorLink {
496    /// Creates a new connector link from a link address and route factory
497    pub(crate) fn new(url: LinkAddress, route_factory: crate::outbound::RouteFactoryFn) -> Self {
498        Self {
499            url,
500            config: Vec::new(),
501            route_factory,
502        }
503    }
504}
505
506/// Fused inbound ingest callback: deserialize + produce in one typed closure
507///
508/// Built where the record type `T` is known (`RecordRegistrar::push_inbound`),
509/// so no `Box<dyn Any>` crosses the connector boundary per message. The closure
510/// captures the typed producer and deserializer; callers only see bytes.
511///
512/// Synchronous by design: `Producer<T>::produce` is sync and infallible
513///, so the only failure is the user
514/// deserializer's — reported as the same `String` the deserializer API uses.
515///
516/// The [`RuntimeContext`](crate::RuntimeContext) and the
517/// [`TopicMatch`](crate::TopicMatch) the message arrived on are threaded per
518/// call (not captured).
519pub type IngestFn = Arc<
520    dyn Fn(&crate::RuntimeContext, &crate::TopicMatch<'_>, &[u8]) -> Result<(), String>
521        + Send
522        + Sync,
523>;
524
525/// Type alias for ingest factory callback (alloc feature)
526///
527/// Takes the live [`AimDb`] and returns the fused [`IngestFn`]. This allows
528/// capturing the record type T at link_from() time while storing the factory
529/// in a type-erased InboundConnectorLink. The factory runs once at
530/// route-collection time, not per message.
531///
532/// Available in both `std` and `no_std + alloc` environments.
533pub type IngestFactoryFn = Arc<dyn Fn(&AimDb) -> IngestFn + Send + Sync>;
534
535/// Topic resolver function for inbound connections (late-binding)
536///
537/// Called once at connector startup to resolve the subscription topic.
538/// Returns `Some(topic)` to use a dynamic topic, or `None` to fall back
539/// to the static topic from the `link_from()` URL.
540///
541/// # Use Cases
542///
543/// - Topics determined from smart contracts at runtime
544/// - Service discovery integration
545/// - Environment-specific topic configuration
546/// - Topics read from configuration files or databases
547///
548/// # no_std Compatibility
549///
550/// Works in both `std` and `no_std + alloc` environments.
551pub type TopicResolverFn = Arc<dyn Fn() -> Option<String> + Send + Sync>;
552
553/// Configuration for an inbound connector link (External → AimDB)
554///
555/// Stores the parsed URL, configuration, and the fused ingest factory. The
556/// factory captures the type T at creation time, allowing type-safe
557/// deserialize+produce later without needing PhantomData or type parameters.
558#[derive(Clone)]
559#[non_exhaustive]
560pub struct InboundConnectorLink {
561    /// Parsed link address (`scheme://resource`)
562    pub url: LinkAddress,
563
564    /// Additional configuration options (protocol-specific)
565    pub config: Vec<(String, String)>,
566
567    /// Fused ingest factory (alloc feature)
568    ///
569    /// Takes the live [`AimDb`] and returns the [`IngestFn`] that
570    /// deserializes bytes and produces into the record's buffer in one typed
571    /// closure. Captures the record type T at link_from() call time —
572    /// `finish()` validates the deserializer is present before registering
573    /// the link, so the factory is always set.
574    ///
575    /// Available in both `std` and `no_std + alloc` environments.
576    pub ingest_factory: IngestFactoryFn,
577
578    /// Set by `.key(..)`: the keyed capture and the key table's capacity.
579    pub key: Option<(String, core::num::NonZeroU16)>,
580
581    /// Optional dynamic topic resolver (late-binding)
582    ///
583    /// Called once at connector startup to determine the subscription topic.
584    /// If the resolver returns `None`, the static topic from the URL is used.
585    ///
586    /// Available in both `std` and `no_std + alloc` environments.
587    pub topic_resolver: Option<TopicResolverFn>,
588}
589
590impl Debug for InboundConnectorLink {
591    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
592        f.debug_struct("InboundConnectorLink")
593            .field("url", &self.url)
594            .field("config", &self.config)
595            .field("ingest_factory", &"<factory>")
596            .field("key", &self.key)
597            .field(
598                "topic_resolver",
599                &self.topic_resolver.as_ref().map(|_| "<function>"),
600            )
601            .finish()
602    }
603}
604
605impl InboundConnectorLink {
606    /// Creates a new inbound connector link from a link address and ingest factory
607    pub fn new(url: LinkAddress, ingest_factory: IngestFactoryFn) -> Self {
608        Self {
609            url,
610            config: Vec::new(),
611            ingest_factory,
612            key: None,
613            topic_resolver: None,
614        }
615    }
616
617    /// Creates the fused ingest callback using the stored factory.
618    ///
619    /// Runs once at route-collection time; the returned [`IngestFn`] is the
620    /// per-message path (deserialize + produce, no erasure crossing).
621    ///
622    /// Available in both `std` and `no_std + alloc` environments.
623    pub fn create_ingest(&self, db: &AimDb) -> IngestFn {
624        (self.ingest_factory)(db)
625    }
626
627    /// Resolves the subscription topic for this link
628    ///
629    /// If a topic resolver is configured, calls it to determine the topic.
630    /// Otherwise, returns the static topic from the URL.
631    ///
632    /// This is called once at connector startup.
633    pub fn resolve_topic(&self) -> String {
634        self.topic_resolver
635            .as_ref()
636            .and_then(|resolver| resolver())
637            .unwrap_or_else(|| self.url.resource_id().to_string())
638    }
639}
640
641/// Parses a connector URL string into structured components
642///
643/// This is a simple parser that handles the most common URL formats.
644/// For production use, consider using the `url` crate with feature flags.
645fn parse_connector_url(url: &str) -> DbResult<ConnectorUrl> {
646    use crate::DbError;
647
648    // Split scheme from rest
649    let (scheme, rest) = url
650        .split_once("://")
651        .ok_or_else(|| DbError::InvalidOperation {
652            operation: "parse_connector_url".into(),
653            reason: format!("Missing scheme in URL: {}", url),
654        })?;
655
656    // Extract credentials if present (user:pass@host)
657    let (credentials, host_part) = if let Some(at_idx) = rest.find('@') {
658        let creds = &rest[..at_idx];
659        let host = &rest[at_idx + 1..];
660        (Some(creds), host)
661    } else {
662        (None, rest)
663    };
664
665    let (username, password) = if let Some(creds) = credentials {
666        if let Some((user, pass)) = creds.split_once(':') {
667            (Some(user.to_string()), Some(pass.to_string()))
668        } else {
669            (Some(creds.to_string()), None)
670        }
671    } else {
672        (None, None)
673    };
674
675    // Split path and query from host:port
676    let (host_port, path, query_params) = if let Some(slash_idx) = host_part.find('/') {
677        let hp = &host_part[..slash_idx];
678        let path_query = &host_part[slash_idx..];
679
680        // Split query parameters
681        let (path_part, query_part) = if let Some(q_idx) = path_query.find('?') {
682            (&path_query[..q_idx], Some(&path_query[q_idx + 1..]))
683        } else {
684            (path_query, None)
685        };
686
687        // Parse query parameters
688        let params = if let Some(query) = query_part {
689            query
690                .split('&')
691                .filter_map(|pair| {
692                    let (k, v) = pair.split_once('=')?;
693                    Some((k.to_string(), v.to_string()))
694                })
695                .collect()
696        } else {
697            Vec::new()
698        };
699
700        (hp, Some(path_part.to_string()), params)
701    } else {
702        (host_part, None, Vec::new())
703    };
704
705    // Split host and port
706    let (host, port) = if let Some(colon_idx) = host_port.rfind(':') {
707        let h = &host_port[..colon_idx];
708        let p = &host_port[colon_idx + 1..];
709        let port_num = p.parse::<u16>().ok();
710        (h.to_string(), port_num)
711    } else {
712        (host_port.to_string(), None)
713    };
714
715    Ok(ConnectorUrl {
716        scheme: scheme.to_string(),
717        host,
718        port,
719        path,
720        username,
721        password,
722        query_params,
723    })
724}
725
726/// Trait for building connectors after the database is constructed
727///
728/// Connectors that need to collect routes from the database (for inbound routing)
729/// implement this trait. The builder pattern allows connectors to be constructed
730/// in two phases:
731///
732/// 1. Configuration phase: User provides broker URLs and settings
733/// 2. Build phase: Connector collects routes from the database and initializes
734///
735/// # Example
736///
737/// Illustrative sketch of a connector author's `build()` (not compiled: the
738/// client types and `MqttGrammar`, the connector's
739/// [`TopicGrammar`](crate::TopicGrammar), are the connector's own — see
740/// `aimdb-mqtt-connector` for a real one):
741///
742/// ```rust,ignore
743/// pub struct MqttConnectorBuilder {
744///     broker_url: String,
745/// }
746///
747/// impl ConnectorBuilder for MqttConnectorBuilder {
748///     fn build<'a>(
749///         &'a self,
750///         db: &'a AimDb,
751///     ) -> Pin<Box<dyn Future<Output = DbResult<Vec<BoxFuture>>> + Send + 'a>> {
752///         Box::pin(async move {
753///             // Wildcard rules are the connector's; `&ExactGrammar` if it has none.
754///             let inbound = InboundDispatch::new(db, self.scheme(), &MqttGrammar)?;
755///             let outbound = OutboundRoutes::new(db, self.scheme())?;
756///             let connector = MqttConnector::new(&self.broker_url, inbound, outbound).await?;
757///             Ok(connector.futures())
758///         })
759///     }
760///
761///     fn scheme(&self) -> &str {
762///         "mqtt"
763///     }
764/// }
765/// ```
766pub trait ConnectorBuilder: Send + Sync {
767    /// Build the connector and return its driving futures.
768    ///
769    /// Called during `AimDbBuilder::build()` after the database has been
770    /// constructed. The returned futures (typically the transport task)
771    /// are appended to the builder's accumulator and driven by
772    /// `AimDbRunner::run()`.
773    ///
774    /// # Arguments
775    /// * `db` - The constructed database instance
776    ///
777    /// # Returns
778    /// All `BoxFuture`s the connector needs to operate. Empty if the connector
779    /// has no work to drive.
780    #[allow(clippy::type_complexity)]
781    fn build<'a>(
782        &'a self,
783        db: &'a AimDb,
784    ) -> Pin<
785        Box<
786            dyn Future<Output = DbResult<Vec<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>>>
787                + Send
788                + 'a,
789        >,
790    >;
791
792    /// The URL scheme this connector handles
793    ///
794    /// Returns the scheme (e.g., "mqtt", "knx", "uds") that this connector
795    /// will be registered under. Used for routing `.link_from()` and `.link_to()`
796    /// declarations to the appropriate connector.
797    fn scheme(&self) -> &str;
798
799    /// Whether registering a second connector under this scheme is an error.
800    ///
801    /// Say `true` when [`build`](Self::build) claims every route for its
802    /// scheme — [`InboundDispatch`](crate::InboundDispatch),
803    /// [`OutboundRoutes`](crate::OutboundRoutes) and `crate::session`'s
804    /// `pump_client` (left unlinked: that module is behind
805    /// `connector-session`, and this trait is not) all filter by scheme
806    /// alone, so two such connectors each collect *all* of it: every
807    /// `link_to` gets two publishers, and the routes
808    /// cannot be divided between the two endpoints because nothing in a route
809    /// names which connector it belongs to. That misconfiguration is otherwise
810    /// silent, and it fails as duplicated or misdirected traffic at runtime
811    /// rather than at build.
812    ///
813    /// Leave it `false` — the default — for a connector that only serves what
814    /// it is given, such as a session *server*: it binds its own listener and
815    /// collects no routes, so two of them under one scheme are two endpoints
816    /// onto the same dispatch, which is useful rather than broken.
817    fn owns_scheme(&self) -> bool {
818        false
819    }
820}
821
822#[cfg(test)]
823mod tests {
824    use super::*;
825    use alloc::format;
826
827    #[test]
828    fn test_parse_simple_mqtt() {
829        let url = ConnectorUrl::parse("mqtt://broker.example.com:1883").unwrap();
830        assert_eq!(url.scheme, "mqtt");
831        assert_eq!(url.host, "broker.example.com");
832        assert_eq!(url.port, Some(1883));
833        assert_eq!(url.username, None);
834        assert_eq!(url.password, None);
835    }
836
837    #[test]
838    fn test_parse_mqtt_with_credentials() {
839        let url = ConnectorUrl::parse("mqtt://user:pass@broker.example.com:1883").unwrap();
840        assert_eq!(url.scheme, "mqtt");
841        assert_eq!(url.host, "broker.example.com");
842        assert_eq!(url.port, Some(1883));
843        assert_eq!(url.username, Some("user".to_string()));
844        assert_eq!(url.password, Some("pass".to_string()));
845    }
846
847    #[test]
848    fn test_parse_https_with_path() {
849        let url = ConnectorUrl::parse("https://api.example.com:8443/events").unwrap();
850        assert_eq!(url.scheme, "https");
851        assert_eq!(url.host, "api.example.com");
852        assert_eq!(url.port, Some(8443));
853        assert_eq!(url.path, Some("/events".to_string()));
854    }
855
856    #[test]
857    fn test_parse_with_query_params() {
858        let url = ConnectorUrl::parse("http://api.example.com/data?key=value&foo=bar").unwrap();
859        assert_eq!(url.scheme, "http");
860        assert_eq!(url.host, "api.example.com");
861        assert_eq!(url.path, Some("/data".to_string()));
862        assert_eq!(url.query_params.len(), 2);
863        assert_eq!(
864            url.query_params[0],
865            ("key".to_string(), "value".to_string())
866        );
867        assert_eq!(url.query_params[1], ("foo".to_string(), "bar".to_string()));
868    }
869
870    #[test]
871    fn test_default_ports() {
872        let mqtt = ConnectorUrl::parse("mqtt://broker.local").unwrap();
873        assert_eq!(mqtt.default_port(), Some(1883));
874        assert_eq!(mqtt.effective_port(), Some(1883));
875
876        let mqtts = ConnectorUrl::parse("mqtts://broker.local").unwrap();
877        assert_eq!(mqtts.default_port(), Some(8883));
878
879        // No connector, no default: unknown schemes carry no port opinion.
880        let knx = ConnectorUrl::parse("knx://gateway.local").unwrap();
881        assert_eq!(knx.default_port(), None);
882    }
883
884    #[test]
885    fn test_is_secure() {
886        assert!(ConnectorUrl::parse("mqtts://broker.local")
887            .unwrap()
888            .is_secure());
889        assert!(ConnectorUrl::parse("https://api.example.com")
890            .unwrap()
891            .is_secure());
892        assert!(ConnectorUrl::parse("wss://ws.example.com")
893            .unwrap()
894            .is_secure());
895
896        assert!(!ConnectorUrl::parse("mqtt://broker.local")
897            .unwrap()
898            .is_secure());
899        assert!(!ConnectorUrl::parse("http://api.example.com")
900            .unwrap()
901            .is_secure());
902        assert!(!ConnectorUrl::parse("ws://ws.example.com")
903            .unwrap()
904            .is_secure());
905    }
906
907    #[test]
908    fn test_display_hides_password() {
909        let url = ConnectorUrl::parse("mqtt://user:secret@broker.local:1883").unwrap();
910        let display = format!("{}", url);
911        assert!(display.contains("user:****"));
912        assert!(!display.contains("secret"));
913    }
914
915    #[test]
916    fn test_parse_kafka_style() {
917        let url =
918            ConnectorUrl::parse("kafka://broker1.local:9092,broker2.local:9092/my-topic").unwrap();
919        assert_eq!(url.scheme, "kafka");
920        // Note: Our simple parser doesn't handle the second port in comma-separated hosts perfectly
921        // It parses "broker1.local:9092,broker2.local" as the host and "9092" as the port
922        // This is acceptable for now - production connectors can handle this in their client factories
923        assert!(url.host.contains("broker1.local"));
924        assert!(url.host.contains("broker2.local"));
925        assert_eq!(url.path, Some("/my-topic".to_string()));
926    }
927
928    #[test]
929    fn test_parse_missing_scheme() {
930        let result = ConnectorUrl::parse("broker.example.com:1883");
931        assert!(result.is_err());
932    }
933
934    // ========================================================================
935    // TopicBuf Tests
936    // ========================================================================
937
938    #[test]
939    fn topic_buf_accepts_an_exact_fit() {
940        let mut storage = [0u8; 6];
941        let mut out = super::TopicBuf::new(&mut storage);
942        assert!(out.is_empty());
943        out.push_str("ab/").unwrap();
944        out.push_str("cde").unwrap();
945        assert_eq!((out.as_str(), out.len(), out.capacity()), ("ab/cde", 6, 6));
946        assert!(!out.overflowed());
947    }
948
949    #[test]
950    fn topic_buf_refuses_an_overflowing_write_whole() {
951        let mut storage = [0u8; 6];
952        let mut out = super::TopicBuf::new(&mut storage);
953        out.push_str("ab/").unwrap();
954        // "cdé" is 4 bytes: one over, and it ends in a two-byte character.
955        assert_eq!(out.push_str("cdé"), Err(super::TopicOverflow));
956        assert_eq!(out.as_str(), "ab/");
957        assert!(out.overflowed());
958        // Latched: a write that would fit is refused too.
959        assert!(out.push_str("x").is_err());
960        assert_eq!(out.as_str(), "ab/");
961    }
962
963    #[test]
964    fn topic_buf_overflow_propagates_through_write() {
965        use core::fmt::Write as _;
966        fn writer(v: u32, out: &mut super::TopicBuf<'_>) -> Result<bool, super::TopicOverflow> {
967            write!(out, "t/{v}")?;
968            Ok(true)
969        }
970        let mut storage = [0u8; 4];
971        assert_eq!(
972            writer(12, &mut super::TopicBuf::new(&mut storage)),
973            Ok(true)
974        );
975        assert_eq!(
976            writer(123, &mut super::TopicBuf::new(&mut storage)),
977            Err(super::TopicOverflow)
978        );
979    }
980
981    // ========================================================================
982    // TopicResolverFn Tests
983    // ========================================================================
984
985    #[test]
986    fn test_topic_resolver_returns_some() {
987        let resolver: super::TopicResolverFn = Arc::new(|| Some("resolved/topic".into()));
988
989        assert_eq!(resolver(), Some("resolved/topic".into()));
990    }
991
992    #[test]
993    fn test_topic_resolver_returns_none() {
994        let resolver: super::TopicResolverFn = Arc::new(|| None);
995
996        // Returns None, should fall back to default topic
997        assert_eq!(resolver(), None);
998    }
999
1000    #[cfg(feature = "std")]
1001    #[test]
1002    fn test_topic_resolver_with_captured_state() {
1003        use std::sync::Mutex;
1004
1005        let config = Arc::new(Mutex::new(Some("dynamic/topic".to_string())));
1006        let config_clone = config.clone();
1007
1008        let resolver: super::TopicResolverFn =
1009            Arc::new(move || config_clone.lock().unwrap().clone());
1010
1011        assert_eq!(resolver(), Some("dynamic/topic".into()));
1012
1013        // Clear config
1014        *config.lock().unwrap() = None;
1015        assert_eq!(resolver(), None);
1016    }
1017
1018    /// Dummy ingest factory for link-construction tests (never invoked).
1019    fn dummy_ingest_factory() -> super::IngestFactoryFn {
1020        Arc::new(|_db| Arc::new(|_ctx, _m, _bytes| Ok(())))
1021    }
1022
1023    #[test]
1024    fn test_inbound_connector_link_resolve_topic_default() {
1025        use super::{InboundConnectorLink, LinkAddress};
1026
1027        let url = LinkAddress::parse("mqtt://sensors/temperature").unwrap();
1028        let link = InboundConnectorLink::new(url, dummy_ingest_factory());
1029
1030        // No resolver configured, should return static topic from URL
1031        assert_eq!(link.resolve_topic(), "sensors/temperature");
1032    }
1033
1034    #[test]
1035    fn test_inbound_connector_link_resolve_topic_dynamic() {
1036        use super::{InboundConnectorLink, LinkAddress};
1037
1038        let url = LinkAddress::parse("mqtt://sensors/default").unwrap();
1039        let mut link = InboundConnectorLink::new(url, dummy_ingest_factory());
1040
1041        // Configure dynamic resolver
1042        link.topic_resolver = Some(Arc::new(|| Some("sensors/dynamic/kitchen".into())));
1043
1044        // Should return resolved topic, not URL topic
1045        assert_eq!(link.resolve_topic(), "sensors/dynamic/kitchen");
1046    }
1047
1048    #[test]
1049    fn test_inbound_connector_link_resolve_topic_fallback() {
1050        use super::{InboundConnectorLink, LinkAddress};
1051
1052        let url = LinkAddress::parse("mqtt://sensors/fallback").unwrap();
1053        let mut link = InboundConnectorLink::new(url, dummy_ingest_factory());
1054
1055        // Configure resolver that returns None
1056        link.topic_resolver = Some(Arc::new(|| None));
1057
1058        // Should fall back to static topic from URL
1059        assert_eq!(link.resolve_topic(), "sensors/fallback");
1060    }
1061}