Skip to main content

qualia_core_db/sensing/
discovery.rs

1//! Host supplied, bounded discovery for sensing endpoints.
2//!
3//! Discovery returns opaque endpoint references and relationship-scoped context
4//! labels. It does not establish identity, guardianship, consent, permission,
5//! calibration, connectivity, or sensor capability. A caller must separately
6//! authorize use of any discovered endpoint.
7
8use core::num::NonZeroU64;
9
10/// Maximum discovery candidates accepted and returned in one call.
11pub const MAX_DISCOVERY_RESULTS: usize = 32;
12
13/// A nonzero opaque identifier in a provider-defined namespace.
14///
15/// These values are handles only. In particular, they are not assumed to be
16/// DIDs, cryptographic identities, or globally comparable identifiers.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub struct DiscoveryId(NonZeroU64);
19
20impl DiscoveryId {
21    pub const fn new(value: u64) -> Result<Self, DiscoveryError> {
22        match NonZeroU64::new(value) {
23            Some(value) => Ok(Self(value)),
24            None => Err(DiscoveryError::InvalidIdentifier),
25        }
26    }
27
28    pub const fn value(self) -> u64 {
29        self.0.get()
30    }
31}
32
33/// Monotonic time in one explicit provider clock domain and restart epoch.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub struct DiscoveryClock {
36    clock_id: DiscoveryId,
37    restart_epoch: u32,
38    ticks_ns: u64,
39    uncertainty_ns: u64,
40}
41
42impl DiscoveryClock {
43    pub const fn new(
44        clock_id: u64,
45        restart_epoch: u32,
46        ticks_ns: u64,
47        uncertainty_ns: u64,
48    ) -> Result<Self, DiscoveryError> {
49        let clock_id = match DiscoveryId::new(clock_id) {
50            Ok(id) => id,
51            Err(error) => return Err(error),
52        };
53        if ticks_ns.checked_add(uncertainty_ns).is_none() {
54            return Err(DiscoveryError::InvalidTime);
55        }
56        Ok(Self {
57            clock_id,
58            restart_epoch,
59            ticks_ns,
60            uncertainty_ns,
61        })
62    }
63
64    pub const fn clock_id(self) -> DiscoveryId {
65        self.clock_id
66    }
67
68    pub const fn restart_epoch(self) -> u32 {
69        self.restart_epoch
70    }
71
72    pub const fn ticks_ns(self) -> u64 {
73        self.ticks_ns
74    }
75
76    pub const fn uncertainty_ns(self) -> u64 {
77        self.uncertainty_ns
78    }
79
80    const fn lower_ns(self) -> u64 {
81        self.ticks_ns.saturating_sub(self.uncertainty_ns)
82    }
83
84    const fn upper_ns(self) -> u64 {
85        // Constructor has already checked this addition.
86        self.ticks_ns + self.uncertainty_ns
87    }
88}
89
90/// Provider-declared endpoint lease. Expiry and observation use the same
91/// monotonic clock and restart epoch; they are not UTC timestamps.
92#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93pub struct DiscoveryLease {
94    observed: DiscoveryClock,
95    expires_at_ns: u64,
96}
97
98impl DiscoveryLease {
99    pub const fn new(observed: DiscoveryClock, expires_at_ns: u64) -> Result<Self, DiscoveryError> {
100        // The observation must be definitely before expiry, including its
101        // entire declared uncertainty interval.
102        if observed.upper_ns() >= expires_at_ns {
103            return Err(DiscoveryError::InvalidTime);
104        }
105        Ok(Self {
106            observed,
107            expires_at_ns,
108        })
109    }
110
111    pub const fn observed(self) -> DiscoveryClock {
112        self.observed
113    }
114
115    pub const fn expires_at_ns(self) -> u64 {
116        self.expires_at_ns
117    }
118
119    /// Conservative validity check: `now` must be definitely after the
120    /// observation and its latest possible time must remain before expiry.
121    pub fn is_fresh_at(self, now: DiscoveryClock) -> Result<bool, DiscoveryError> {
122        if self.observed.clock_id != now.clock_id
123            || self.observed.restart_epoch != now.restart_epoch
124        {
125            return Err(DiscoveryError::ClockDomainMismatch);
126        }
127        Ok(now.lower_ns() >= self.observed.upper_ns() && now.upper_ns() < self.expires_at_ns)
128    }
129}
130
131/// Optional social or physical query filters. Relationship and context
132/// identifiers are opaque labels supplied by the host; their presence is not
133/// proof of a relationship or authorization. All filters may be absent for
134/// environmental, nonhuman, or not-yet-classified observations.
135#[derive(Clone, Copy, Debug, PartialEq, Eq)]
136pub struct DiscoveryQuery {
137    relationship_id: Option<DiscoveryId>,
138    context_id: Option<DiscoveryId>,
139    subject_id: Option<DiscoveryId>,
140    sensor_id: Option<DiscoveryId>,
141    protocol_id: Option<DiscoveryId>,
142}
143
144impl DiscoveryQuery {
145    pub const fn new(
146        relationship_id: Option<u64>,
147        context_id: Option<u64>,
148        subject_id: Option<u64>,
149        sensor_id: Option<u64>,
150        protocol_id: Option<u64>,
151    ) -> Result<Self, DiscoveryError> {
152        let relationship_id = match optional_id(relationship_id) {
153            Ok(id) => id,
154            Err(error) => return Err(error),
155        };
156        let context_id = match optional_id(context_id) {
157            Ok(id) => id,
158            Err(error) => return Err(error),
159        };
160        let subject_id = match optional_id(subject_id) {
161            Ok(id) => id,
162            Err(error) => return Err(error),
163        };
164        let sensor_id = match optional_id(sensor_id) {
165            Ok(id) => id,
166            Err(error) => return Err(error),
167        };
168        let protocol_id = match optional_id(protocol_id) {
169            Ok(id) => id,
170            Err(error) => return Err(error),
171        };
172        Ok(Self {
173            relationship_id,
174            context_id,
175            subject_id,
176            sensor_id,
177            protocol_id,
178        })
179    }
180
181    pub const fn relationship_id(self) -> Option<DiscoveryId> {
182        self.relationship_id
183    }
184
185    pub const fn context_id(self) -> Option<DiscoveryId> {
186        self.context_id
187    }
188
189    pub const fn subject_id(self) -> Option<DiscoveryId> {
190        self.subject_id
191    }
192
193    pub const fn sensor_id(self) -> Option<DiscoveryId> {
194        self.sensor_id
195    }
196
197    pub const fn protocol_id(self) -> Option<DiscoveryId> {
198        self.protocol_id
199    }
200}
201
202/// Opaque host locator/reference plus the optional scope the host says it serves.
203/// The value is intentionally not a network address and is meaningful only
204/// to the provider that returned it.
205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
206pub struct DiscoveredEndpoint {
207    provider_id: DiscoveryId,
208    endpoint_ref: DiscoveryId,
209    relationship_id: Option<DiscoveryId>,
210    context_id: Option<DiscoveryId>,
211    subject_id: Option<DiscoveryId>,
212    sensor_id: Option<DiscoveryId>,
213    protocol_id: DiscoveryId,
214    lease: DiscoveryLease,
215}
216
217impl DiscoveredEndpoint {
218    #[allow(clippy::too_many_arguments)]
219    pub const fn new(
220        provider_id: u64,
221        endpoint_ref: u64,
222        relationship_id: Option<u64>,
223        context_id: Option<u64>,
224        subject_id: Option<u64>,
225        sensor_id: Option<u64>,
226        protocol_id: u64,
227        lease: DiscoveryLease,
228    ) -> Result<Self, DiscoveryError> {
229        let provider_id = match DiscoveryId::new(provider_id) {
230            Ok(id) => id,
231            Err(error) => return Err(error),
232        };
233        let endpoint_ref = match DiscoveryId::new(endpoint_ref) {
234            Ok(id) => id,
235            Err(error) => return Err(error),
236        };
237        let relationship_id = match optional_id(relationship_id) {
238            Ok(id) => id,
239            Err(error) => return Err(error),
240        };
241        let context_id = match optional_id(context_id) {
242            Ok(id) => id,
243            Err(error) => return Err(error),
244        };
245        let subject_id = match optional_id(subject_id) {
246            Ok(id) => id,
247            Err(error) => return Err(error),
248        };
249        let sensor_id = match optional_id(sensor_id) {
250            Ok(id) => id,
251            Err(error) => return Err(error),
252        };
253        let protocol_id = match DiscoveryId::new(protocol_id) {
254            Ok(id) => id,
255            Err(error) => return Err(error),
256        };
257        Ok(Self {
258            provider_id,
259            endpoint_ref,
260            relationship_id,
261            context_id,
262            subject_id,
263            sensor_id,
264            protocol_id,
265            lease,
266        })
267    }
268
269    pub const fn provider_id(self) -> DiscoveryId {
270        self.provider_id
271    }
272    pub const fn endpoint_ref(self) -> DiscoveryId {
273        self.endpoint_ref
274    }
275    pub const fn relationship_id(self) -> Option<DiscoveryId> {
276        self.relationship_id
277    }
278    pub const fn context_id(self) -> Option<DiscoveryId> {
279        self.context_id
280    }
281    pub const fn subject_id(self) -> Option<DiscoveryId> {
282        self.subject_id
283    }
284    pub const fn sensor_id(self) -> Option<DiscoveryId> {
285        self.sensor_id
286    }
287    pub const fn protocol_id(self) -> DiscoveryId {
288        self.protocol_id
289    }
290    pub const fn lease(self) -> DiscoveryLease {
291        self.lease
292    }
293}
294
295/// Host-supplied resolver. Implementations may bridge QDNF, SPARQL-MM,
296/// social directories, or another service; this contract itself performs no
297/// network I/O and assigns no trust to provider output.
298pub trait DiscoveryProvider {
299    fn resolve_into(
300        &self,
301        query: DiscoveryQuery,
302        out: &mut [Option<DiscoveredEndpoint>],
303    ) -> Result<usize, DiscoveryError>;
304}
305
306/// Errors from bounded, caller-buffered resolution.
307#[derive(Clone, Copy, Debug, PartialEq, Eq)]
308pub enum DiscoveryError {
309    InvalidIdentifier,
310    InvalidTime,
311    ClockDomainMismatch,
312    Capacity,
313    InvalidProviderResult,
314    DuplicateEndpoint,
315    ProviderFailure,
316}
317
318/// Resolve a scoped query into caller-owned output.
319///
320/// A fixed stack scratch buffer validates the complete result set before the
321/// caller's output is modified. The provider result is still an assertion and
322/// does not authorize use of a sensor or establish the endpoint's identity.
323/// On success, only `out[..count]` is replaced; the caller-owned tail remains
324/// untouched and has no validity guarantee from this call.
325pub fn discover_into<P: DiscoveryProvider>(
326    provider: &P,
327    query: DiscoveryQuery,
328    now: DiscoveryClock,
329    out: &mut [Option<DiscoveredEndpoint>],
330) -> Result<usize, DiscoveryError> {
331    if out.len() > MAX_DISCOVERY_RESULTS {
332        return Err(DiscoveryError::Capacity);
333    }
334    let mut scratch = [None; MAX_DISCOVERY_RESULTS];
335    let count = provider.resolve_into(query, &mut scratch)?;
336    if count > scratch.len() || count > out.len() {
337        return Err(DiscoveryError::Capacity);
338    }
339    let mut i = 0;
340    while i < count {
341        let endpoint = scratch[i].ok_or(DiscoveryError::InvalidProviderResult)?;
342        if query
343            .relationship_id
344            .is_some_and(|id| Some(id) != endpoint.relationship_id)
345            || query
346                .context_id
347                .is_some_and(|id| Some(id) != endpoint.context_id)
348            || query
349                .subject_id
350                .is_some_and(|id| Some(id) != endpoint.subject_id)
351            || query
352                .sensor_id
353                .is_some_and(|id| Some(id) != endpoint.sensor_id)
354            || query
355                .protocol_id
356                .is_some_and(|id| id != endpoint.protocol_id)
357            || !endpoint.lease.is_fresh_at(now)?
358        {
359            return Err(DiscoveryError::InvalidProviderResult);
360        }
361        let mut prior = 0;
362        while prior < i {
363            let earlier = scratch[prior].ok_or(DiscoveryError::InvalidProviderResult)?;
364            if endpoint.provider_id == earlier.provider_id
365                && endpoint.endpoint_ref == earlier.endpoint_ref
366            {
367                return Err(DiscoveryError::DuplicateEndpoint);
368            }
369            prior += 1;
370        }
371        i += 1;
372    }
373    i = 0;
374    while i < count {
375        out[i] = scratch[i];
376        i += 1;
377    }
378    Ok(count)
379}
380
381const fn optional_id(value: Option<u64>) -> Result<Option<DiscoveryId>, DiscoveryError> {
382    match value {
383        Some(value) => match DiscoveryId::new(value) {
384            Ok(id) => Ok(Some(id)),
385            Err(error) => Err(error),
386        },
387        None => Ok(None),
388    }
389}
390
391#[cfg(test)]
392#[path = "discovery_tests.rs"]
393mod tests;