Skip to main content

zenkey_fleet/bus/
query.rs

1//! The fan-in query discipline (RFC 05 §2.1) — moved verbatim from
2//! zenctl's `bus.rs`; this stays the single chokepoint for fleet GETs.
3
4use std::time::Duration;
5
6use crate::{Error, Result};
7use zenkey::{RegistrySlice, parse_slice};
8use zenoh::Session;
9use zenoh::qos::Priority;
10use zenoh::query::{ConsolidationMode, QueryTarget};
11
12use crate::bus::session::Fleet;
13use crate::report::ValueSource;
14
15/// How a producer answered a procedure call.
16///
17/// `Clone` is a refcount bump on the payload, not a copy — which is what lets
18/// a GUI hold an answer in widget state without paying for it.
19#[derive(Debug, Clone)]
20pub enum Answer {
21    /// A value reply — RFC 05 §3: "a reply always indicates success".
22    /// Carried as zenoh's refcounted buffer: cloning is a refcount bump,
23    /// and consumers decode via `reader()`/`to_bytes()` (a `Cow` — it
24    /// copies only when the payload arrived fragmented). Report §14's
25    /// zero-copy discipline: the old `to_bytes().to_vec()` double copy per
26    /// reply is retired.
27    Value(zenoh::bytes::ZBytes),
28    /// An error reply (`reply_err`), carrying the `{error, message}` envelope
29    /// when it parses. RFC 05 §3: "an error always indicates failure".
30    Error { name: String, message: String },
31}
32
33/// One host's answer, attributed to the origin that actually replied.
34#[derive(Debug, Clone)]
35pub struct FleetAnswer {
36    pub origin: String,
37    /// The reply's **own** key expression — what `origin` was derived from, and
38    /// the concrete key a follow-up must be addressed to.
39    ///
40    /// Empty for an error reply, which zenoh gives no sample and therefore no
41    /// key. Carried because `origin` is lossy by design: the attribution helper goes
42    /// through the grammar and yields `"?"` for any key that does not parse
43    /// under `base`, and a caller that must still *name* the responder (RFC 09
44    /// §5.1 O1 — a non-conforming key is a fact) has nowhere else to look.
45    pub key: String,
46    /// The reply's declared encoding, when it carried one.
47    ///
48    /// A caller that speaks a specific wire (`@blob`'s postcard replies, say)
49    /// needs to tell "answered in a dialect we do not speak" from "did not
50    /// answer": the first is an observation, the second is silence, and RFC 09
51    /// §5.1 O4 forbids rendering them alike.
52    pub encoding: Option<String>,
53    /// The reply's attachment, when it carried one (refcounted, like the
54    /// payload). `None` on an error reply is the only truth available:
55    /// zenoh's `ReplyError` carries no attachment — a fact about the wire,
56    /// not an unobserved field.
57    pub attachment: Option<zenoh::bytes::ZBytes>,
58    pub answer: Answer,
59}
60
61/// What one GET may vary — everything RFC 05 §2.1 does **not** fix.
62///
63/// The §2.1 triple is not a knob and deliberately has no field here: it is
64/// applied by `disciplined_get` to every GET this crate issues. What a
65/// caller does choose is the timeout, the request body, an attachment riding
66/// beside it (#126), the query's priority (RFC 04 §3, RFC 07 §2.6) and
67/// whether replies from *outside* the selector are accepted.
68///
69/// A spec struct rather than named sibling functions: `fleet_get_at`
70/// (priority) and `fleet_get_call` (attachment) used to be those siblings, and
71/// `_at` had come to mean two things — this axis, and the injected-clock
72/// convention (`ingest_at`, `ZrecWriter::new_at`). The greps the siblings
73/// bought survive as setter greps: "who issues bulk GETs?" is
74/// `grep '\.priority('`, "who sends attachments on queries?" is
75/// `grep '\.attachment('`.
76#[derive(Debug, Clone)]
77pub struct GetOpts {
78    timeout: Duration,
79    payload: Option<Vec<u8>>,
80    attachment: Option<Vec<u8>>,
81    priority: Priority,
82    accept_any: bool,
83    max_replies: usize,
84    /// What the bound cost, filled in by the GET (#339). Shared rather than
85    /// returned — see [`GetOpts::elided`].
86    elided: std::sync::Arc<std::sync::atomic::AtomicU64>,
87}
88
89/// How many replies a GET keeps unless the caller says otherwise (#339).
90///
91/// Every fan-out here was unbounded: `collect_answers`, `fetch_timed` and
92/// `admin_get` pushed every reply into a `Vec`, each holding a refcounted
93/// payload, so a `**` sweep against a router with a large storage was
94/// unbounded memory in a tool that bounds everything else it accumulates.
95///
96/// 4096 is chosen against what the fan-out *means*: a fleet GET is one reply
97/// per producer per key, and a fleet with four thousand replying entities on
98/// one selector is past what any of these renderers show anyway. A caller
99/// that genuinely wants more says so, and hears what the last bound cost.
100pub const DEFAULT_MAX_REPLIES: usize = 4096;
101
102impl GetOpts {
103    /// A plain GET, bounded by `timeout`.
104    ///
105    /// [`Priority::DEFAULT`] is `Priority::Data` — byte-identical to setting
106    /// no priority at all, which is what every un-annotated GET did before
107    /// this type existed.
108    pub fn new(timeout: Duration) -> Self {
109        GetOpts {
110            timeout,
111            payload: None,
112            attachment: None,
113            priority: Priority::DEFAULT,
114            accept_any: false,
115            max_replies: DEFAULT_MAX_REPLIES,
116            elided: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
117        }
118    }
119
120    /// The request body, when there is one. `None` is the common case and
121    /// costs nothing to say.
122    pub fn payload(mut self, payload: Option<Vec<u8>>) -> Self {
123        self.payload = payload;
124        self
125    }
126
127    /// A query attachment (#126), verbatim — never schema-encoded. The encode
128    /// ladder is for bodies; an attachment is outside the registry's
129    /// vocabulary (#117), on a query exactly as on a publish.
130    pub fn attachment(mut self, attachment: Option<Vec<u8>>) -> Self {
131        self.attachment = attachment;
132        self
133    }
134
135    /// State the query's priority (RFC 04 §3, RFC 07 §2.6).
136    ///
137    /// Replies inherit the *query's* QoS — a server-side setter is a no-op —
138    /// so a bulk plane's priority can only be decided here. RFC 07 §2.6 makes
139    /// that a caller obligation rather than a suggestion: `@blob` GETs MUST
140    /// ride at [`Priority::DataLow`], or one operator fetching a debug bundle
141    /// starves the telemetry and alerts sharing the link.
142    pub fn priority(mut self, priority: Priority) -> Self {
143        self.priority = priority;
144        self
145    }
146
147    /// Accept replies on keys **outside** the selector
148    /// ([`zenoh::query::ReplyKeyExpr::Any`]) — the querying-subscriber
149    /// pattern.
150    ///
151    /// The `@adv` cache replies with the cached sample on the *sample's* own
152    /// key, outside a `<key>/@adv/**` selector, and zenoh drops such replies
153    /// unless the caller opts in. Harmless on a rung whose replies sit inside
154    /// the selector anyway.
155    pub fn accept_any(mut self) -> Self {
156        self.accept_any = true;
157        self
158    }
159
160    /// The bound this GET runs under.
161    pub fn timeout(&self) -> Duration {
162        self.timeout
163    }
164
165    /// Keep at most `max` replies (#339). Zero is clamped to one: a GET that
166    /// kept nothing would report silence, and silence is never a verdict
167    /// (RFC 05 §3.1).
168    pub fn max_replies(mut self, max: usize) -> Self {
169        self.max_replies = max.max(1);
170        self
171    }
172
173    /// The reply bound in force.
174    pub fn reply_bound(&self) -> usize {
175        self.max_replies
176    }
177
178    /// **What the bound cost**: replies that arrived and were not kept,
179    /// across every GET run under these options (RFC 13 §3 O6 — a bound that
180    /// hides data must say so).
181    ///
182    /// It rides here, on the object that *states* the bound, rather than in
183    /// the return type, for the reason every other bounded structure in this
184    /// crate keeps its own ledger (`StatsTable::evicted`,
185    /// `Retention::evicted`, `BoundedLru::admit`): the thing that owns the
186    /// ceiling owns the count of what the ceiling refused. A caller reads it
187    /// beside the answers it just got:
188    ///
189    /// ```ignore
190    /// let opts = GetOpts::new(timeout);
191    /// let answers = fleet_get(&fleet, key, &opts).await?;
192    /// if opts.elided() > 0 { /* say so — never render this as "all of them" */ }
193    /// ```
194    ///
195    /// The count is exact: past the bound the replies are still drained, they
196    /// are simply not kept. Draining is what makes the number honest; *keeping*
197    /// is what was unbounded.
198    pub fn elided(&self) -> u64 {
199        self.elided.load(std::sync::atomic::Ordering::Relaxed)
200    }
201
202    /// Forget what earlier GETs under these options cost — for a caller that
203    /// reuses one `GetOpts` and reports per GET rather than per run.
204    pub fn reset_elided(&self) {
205        self.elided.store(0, std::sync::atomic::Ordering::Relaxed);
206    }
207
208    /// Add to the ledger — for the drains that live in another module
209    /// ([`crate::admin_get_within`]) and keep their own reply shape.
210    pub(crate) fn note_elided(&self, n: u64) {
211        if n > 0 {
212            self.elided
213                .fetch_add(n, std::sync::atomic::Ordering::Relaxed);
214        }
215    }
216}
217
218/// **The** `session.get` of this crate (RFC 05 §2.1) — no other module issues
219/// one, which is what makes the discipline checkable by grep rather than by
220/// review.
221///
222/// Two of the three things §2.1 requires are set here, once:
223///
224/// 1. **target = All.** The default `BestMatching` short-circuits to a single
225///    queryable the moment any matching one is declared `complete` — "one
226///    storage config away from silently collapsing the fleet to one reply".
227/// 2. **consolidation = None.** Default consolidation keeps one reply *per
228///    reply key*; belt-and-braces against a producer that wrongly echoes the
229///    wildcard selector instead of replying on its own concrete key.
230///
231/// The third — **attribution by the reply's own key**, never by the key we
232/// asked on — belongs to whoever drains the channel, and lives in
233/// `answer_of` for the [`FleetAnswer`] path.
234///
235/// The error is the middleware's own, unwrapped: every caller has a better
236/// sentence to wrap it in than this function does.
237pub(crate) async fn disciplined_get(
238    session: &Session,
239    selector: &str,
240    opts: &GetOpts,
241) -> Result<zenoh::handlers::FifoChannelHandler<zenoh::query::Reply>> {
242    let mut builder = session
243        .get(selector)
244        .target(QueryTarget::All)
245        .consolidation(ConsolidationMode::None)
246        .priority(opts.priority)
247        .timeout(opts.timeout);
248    if let Some(body) = opts.payload.clone() {
249        builder = builder.payload(body);
250    }
251    if let Some(att) = opts.attachment.clone() {
252        builder = builder.attachment(att);
253    }
254    if opts.accept_any {
255        builder = builder.accept_replies(zenoh::query::ReplyKeyExpr::Any);
256    }
257    builder.await.map_err(|e| Error::bus("get", "", e))
258}
259
260/// Call a procedure and collect **every** reply, attributed by origin.
261///
262/// The RFC 05 §2.1 fan-in, end to end: `disciplined_get` sets target `All`
263/// and consolidation `None`, and `answer_of` attributes each reply by the
264/// reply's *own* key — which is what makes `*`-origin fan-out legible.
265///
266/// Silence is deliberately *not* interpreted here (RFC 05 §3.1: "no reply" is
267/// not one condition). Callers that need a verdict join this against the
268/// liveliness roster; see `cmd::doctor`.
269/// Bounded at [`GetOpts::reply_bound`], and what the bound cost is on
270/// [`GetOpts::elided`] (#339).
271pub async fn fleet_get(fleet: &Fleet<'_>, key: &str, opts: &GetOpts) -> Result<Vec<FleetAnswer>> {
272    let replies = disciplined_get(fleet.session(), key, opts)
273        .await
274        .map_err(|e| Error::bus("query", key.to_string(), e))?;
275    let (answers, elided) = collect_answers(fleet.base(), replies, opts.max_replies).await;
276    opts.note_elided(elided);
277    Ok(answers)
278}
279
280/// Drain a reply channel into attributed answers — the shared back half of
281/// [`fleet_get`] and [`RepeatingQuery`]: one implementation of reply-key
282/// attribution and the RFC 05 §3 error envelope, however the query was issued.
283///
284/// Returns what it kept and **how many it did not** (#339). Past `max` the
285/// replies are still drained — the channel is being emptied either way — they
286/// are simply not retained, so the count is exact and the memory is bounded.
287/// The two are different facts: draining is the fan-in finishing, keeping is
288/// what used to be unbounded.
289async fn collect_answers(
290    base: &str,
291    replies: zenoh::handlers::FifoChannelHandler<zenoh::query::Reply>,
292    max: usize,
293) -> (Vec<FleetAnswer>, u64) {
294    let mut out = Vec::new();
295    let mut elided = 0u64;
296
297    while let Ok(reply) = replies.recv_async().await {
298        if out.len() >= max {
299            elided += 1;
300            continue;
301        }
302        out.push(answer_of(base, reply));
303    }
304    (out, elided)
305}
306
307/// One reply, attributed — the per-reply half of [`collect_answers`], shared
308/// with the timed drain in [`RepeatingQuery::fetch_timed`] so attribution and
309/// the RFC 05 §3 error envelope have exactly one implementation.
310fn answer_of(base: &str, reply: zenoh::query::Reply) -> FleetAnswer {
311    match reply.result() {
312        Ok(sample) => FleetAnswer {
313            origin: origin_of(base, sample.key_expr().as_str()),
314            key: sample.key_expr().as_str().to_string(),
315            encoding: Some(sample.encoding().to_string()),
316            attachment: sample.attachment().cloned(),
317            answer: Answer::Value(sample.payload().clone()),
318        },
319        Err(err) => {
320            // The error envelope is `{ "error": "<name>", "message": "…" }`
321            // (RFC 05 §3), with reserved names like `error/not-found`. If it
322            // does not parse we still surface the bytes — an unreadable
323            // refusal is still a refusal.
324            let bytes = err.payload().to_bytes();
325            let (name, message) = match serde_json::from_slice::<serde_json::Value>(&bytes) {
326                Ok(v) => (
327                    v.get("error")
328                        .and_then(|e| e.as_str())
329                        .unwrap_or("error/unparsed")
330                        .to_string(),
331                    v.get("message")
332                        .and_then(|m| m.as_str())
333                        .unwrap_or_default()
334                        .to_string(),
335                ),
336                Err(_) => (
337                    "error/unparsed".to_string(),
338                    String::from_utf8_lossy(&bytes).to_string(),
339                ),
340            };
341            // An error reply has no sample, so no concrete key to attribute
342            // by; zenoh does not surface the responder here.
343            FleetAnswer {
344                origin: "?".to_string(),
345                key: String::new(),
346                encoding: None,
347                attachment: None,
348                answer: Answer::Error { name, message },
349            }
350        }
351    }
352}
353
354/// A **declared** querier carrying the same RFC 05 §2.1 discipline as
355/// [`fleet_get`] (target `All`, consolidation `None`, attribution by reply
356/// key), for fetches that re-ask the **same key expression** — watch loops,
357/// the schema cache's re-asks, registry sweeps, doctor. Declaring once lets
358/// the network keep routing state warm instead of rebuilding it per GET
359/// (report §12's zenoh-1.9 adoption row).
360///
361/// When to use which:
362/// - recurring, same keyexpr → declare a `RepeatingQuery` and `fetch` many
363///   times (parameters and payload ride **per get**, never in the declared
364///   keyexpr — a `?params` suffix in `key` is a bug here);
365/// - genuinely one-shot, or an ad-hoc key → [`fleet_get`].
366///
367/// Liveliness sweeps ([`crate::bus::roster::roster()`]) are a different API
368/// (`session.liveliness().get()`) with no querier equivalent and stay
369/// undeclared.
370pub struct RepeatingQuery {
371    querier: zenoh::query::Querier<'static>,
372    base: String,
373    /// Replies kept per fetch, and what the bound has cost across all of them
374    /// (#339) — the same ledger [`GetOpts`] carries, for the declared path.
375    max_replies: usize,
376    elided: std::sync::atomic::AtomicU64,
377}
378
379/// Declare a repeating query on `key` (a full wire keyexpr, no `?params`).
380///
381/// The §2.1 discipline is fixed at declaration: target `All`, consolidation
382/// `None`, `timeout` for every subsequent fetch.
383pub async fn declare_repeating(
384    fleet: &Fleet<'_>,
385    key: &str,
386    timeout: Duration,
387) -> Result<RepeatingQuery> {
388    declare(fleet, key, timeout, false).await
389}
390
391/// As [`declare_repeating`], additionally accepting replies **outside** the
392/// declared keyexpr (`ReplyKeyExpr::Any`) — the querying-subscriber pattern
393/// the `@adv` cache rung needs. A separate constructor because this axis is
394/// part of the querier's identity: never reuse one querier across both modes.
395pub async fn declare_repeating_any(
396    fleet: &Fleet<'_>,
397    key: &str,
398    timeout: Duration,
399) -> Result<RepeatingQuery> {
400    declare(fleet, key, timeout, true).await
401}
402
403async fn declare(
404    fleet: &Fleet<'_>,
405    key: &str,
406    timeout: Duration,
407    accept_any: bool,
408) -> Result<RepeatingQuery> {
409    let mut builder = fleet
410        .session()
411        .declare_querier(key.to_string())
412        .target(QueryTarget::All)
413        .consolidation(ConsolidationMode::None)
414        .timeout(timeout);
415    if accept_any {
416        builder = builder.accept_replies(zenoh::query::ReplyKeyExpr::Any);
417    }
418    let querier = crate::bus::teardown::declared("declare querier", &key, builder).await?;
419    Ok(RepeatingQuery {
420        querier,
421        base: fleet.base().to_string(),
422        max_replies: DEFAULT_MAX_REPLIES,
423        elided: std::sync::atomic::AtomicU64::new(0),
424    })
425}
426
427impl RepeatingQuery {
428    /// The declared key expression.
429    pub fn key(&self) -> &str {
430        self.querier.key_expr().as_str()
431    }
432
433    /// One fetch on the declared keyexpr, every reply attributed by its own
434    /// key — [`fleet_get`]'s contract, minus the per-call declaration.
435    pub async fn fetch(&self) -> Result<Vec<FleetAnswer>> {
436        self.fetch_with("", None).await
437    }
438
439    /// As [`fetch`](Self::fetch), with selector parameters and/or a request
440    /// payload riding this one get.
441    pub async fn fetch_with(
442        &self,
443        params: &str,
444        payload: Option<Vec<u8>>,
445    ) -> Result<Vec<FleetAnswer>> {
446        let mut builder = self.querier.get();
447        if !params.is_empty() {
448            builder = builder.parameters(params);
449        }
450        if let Some(body) = payload {
451            builder = builder.payload(body);
452        }
453        let replies = builder
454            .await
455            .map_err(|e| Error::bus("query", self.key(), e))?;
456        let (answers, elided) = collect_answers(&self.base, replies, self.max_replies).await;
457        self.note_elided(elided);
458        Ok(answers)
459    }
460
461    /// Keep at most `max` replies per fetch (#339). Zero is clamped to one.
462    pub fn max_replies(mut self, max: usize) -> Self {
463        self.max_replies = max.max(1);
464        self
465    }
466
467    /// The reply bound in force.
468    pub fn reply_bound(&self) -> usize {
469        self.max_replies
470    }
471
472    /// Replies this querier's bound refused, across every fetch (RFC 13 §3
473    /// O6). See [`GetOpts::elided`] for why the count lives with the bound.
474    pub fn elided(&self) -> u64 {
475        self.elided.load(std::sync::atomic::Ordering::Relaxed)
476    }
477
478    fn note_elided(&self, n: u64) {
479        if n > 0 {
480            self.elided
481                .fetch_add(n, std::sync::atomic::Ordering::Relaxed);
482        }
483    }
484
485    /// As [`fetch`](Self::fetch), stamping each reply with how long after the
486    /// GET it arrived (issue #52).
487    ///
488    /// This exists because a fan-out call's *call* duration is the time until
489    /// the slowest answer, so attributing it to every origin would report a
490    /// fast responder's latency as the fleet's worst. Timing each reply where
491    /// it is drained is the only place the distinction is available — and it
492    /// keeps the RFC 05 §2.1 chokepoint intact rather than forking a second
493    /// GET path to measure with.
494    pub async fn fetch_timed(&self) -> Result<Vec<(FleetAnswer, Duration)>> {
495        let started = std::time::Instant::now();
496        let replies = self
497            .querier
498            .get()
499            .await
500            .map_err(|e| Error::bus("query", self.key(), e))?;
501        let mut out = Vec::new();
502        let mut elided = 0u64;
503        while let Ok(reply) = replies.recv_async().await {
504            let at = started.elapsed();
505            if out.len() >= self.max_replies {
506                elided += 1;
507                continue;
508            }
509            out.push((answer_of(&self.base, reply), at));
510        }
511        self.note_elided(elided);
512        Ok(out)
513    }
514
515    /// Undeclare, telling the network to drop the routing state. The crate's
516    /// idiom: teardown is explicit and awaited, never left to `Drop`.
517    pub async fn undeclare(self) -> Result<()> {
518        self.querier
519            .undeclare()
520            .await
521            .map_err(|e| Error::bus("undeclare querier", "", e))
522    }
523
524    /// Whether any queryable currently matches **this querier** — "someone
525    /// serves what *we* ask", a routing fact about the querier this process
526    /// declared (RFC 12 §9's allowed half). `false` is not a fleet verdict:
527    /// it never means "nobody serves this key" (RFC 05 §3.1).
528    pub async fn matching_status(&self) -> Result<bool> {
529        self.querier
530            .matching_status()
531            .await
532            .map(|s| s.matching())
533            .map_err(|e| Error::bus("matching status", "", e))
534    }
535
536    /// Event-driven matching changes for this querier — same honesty bounds
537    /// as [`matching_status`](Self::matching_status).
538    pub async fn matching_events(&self) -> Result<crate::bus::write::MatchingEvents> {
539        crate::bus::write::MatchingEvents::for_querier(&self.querier).await
540    }
541}
542
543/// The origin chunk of a wire key, via the grammar (never by index — RFC 03
544/// §1.1: positions are relative to the configured base).
545fn origin_of(base: &str, key: &str) -> String {
546    zenkey::grammar::parse_full(base, key)
547        .map(|k| k.origin.chunk().to_string())
548        .unwrap_or_else(|| "?".to_string())
549}
550
551/// Discover every live producer's registry slice **from the bus**, with nothing
552/// compiled in (RFC 08 §6: "generic explorer tooling … needs no compiled-in
553/// registry").
554///
555/// Every producer MUST serve its registry slice as TOML on
556/// `@rpc/<producer>/introspect`. This fans one wildcard-producer `introspect`
557/// GET across the fleet — `<base>/v1/*/@rpc/*/introspect` — and parses each
558/// reply. It is the same introspect+`parse_slice` path `doctor` walks, minus
559/// the compiled-in diff: here the served slice *is* the answer.
560///
561/// A reply that does not parse is reported to stderr and skipped, never fatal:
562/// one malformed producer must not blind the tool to every other producer's
563/// slice. The tuple's first element is the producer (or service) base name the
564/// slice declares (`slice.name`), matching the compiled path's producer column.
565///
566/// A verbatim service origin is unmatchable by the `*` of a fleet selector
567/// (grammar property D4), so the wildcard sweep cannot enumerate services.
568/// The well-known `@catalog` identity service (RFC 06 §5) is therefore asked
569/// by name, exactly as [`crate::bus::roster::roster()`] does for its alive token; other
570/// service origins remain reachable only via local registry files
571/// (`doctor --registry` asks each declared `service_origin` by name).
572pub async fn fleet_registry(
573    fleet: &Fleet<'_>,
574    timeout: Duration,
575) -> Result<Vec<(String, RegistrySlice)>> {
576    Ok(fleet_registry_raw(fleet, timeout)
577        .await?
578        .into_iter()
579        .map(|(slice, _)| (slice.name.clone(), slice))
580        .collect())
581}
582
583/// As [`fleet_registry`], additionally yielding each reply's raw TOML text
584/// (the artifact the slice cache persists).
585pub async fn fleet_registry_raw(
586    fleet: &Fleet<'_>,
587    timeout: Duration,
588) -> Result<Vec<(RegistrySlice, String)>> {
589    let repeating = RepeatingRegistry::declare(fleet, timeout).await?;
590
591    let slices = repeating.fetch().await?;
592
593    repeating.undeclare().await?;
594
595    Ok(slices)
596}
597
598/// The registry sweep as a **declared** pair of queriers (#37) — for callers
599/// that re-run the sweep (`--watch topic list`, doctor's second pass, a GUI
600/// refresh). One-shot callers keep [`fleet_registry`].
601///
602/// Two queriers, not one: the wildcard-producer fan-out plus `@catalog` by
603/// name (a `*` never matches a verbatim origin, D4 — the two cannot
604/// double-count; same reasoning as [`fleet_registry`]).
605pub struct RepeatingRegistry {
606    wildcard: RepeatingQuery,
607    catalog: RepeatingQuery,
608}
609
610impl RepeatingRegistry {
611    pub async fn declare(fleet: &Fleet<'_>, timeout: Duration) -> Result<Self> {
612        // This session is un-namespaced on purpose (RFC 09 §5), so it must
613        // spell the base itself — exactly as `service call` composes its key.
614        let wildcard = fleet.wire(zenkey::selector::rpc(
615            zenkey::selector::Scope::fleet(),
616            zenkey::selector::Producers::all(),
617            &["introspect"],
618        ));
619        let catalog = fleet.wire(zenkey::selector::service_rpc(
620            &zenkey::ServiceOrigin::catalog(),
621            &["introspect"],
622        ));
623        Ok(RepeatingRegistry {
624            wildcard: declare_repeating(fleet, &wildcard, timeout).await?,
625            catalog: declare_repeating(fleet, &catalog, timeout).await?,
626        })
627    }
628
629    /// One sweep: every parsed slice with its raw TOML. A reply that does not
630    /// parse is logged and skipped, never fatal — one malformed producer must
631    /// not blind the tool to every other producer's slice.
632    pub async fn fetch(&self) -> Result<Vec<(RegistrySlice, String)>> {
633        let mut slices = Vec::new();
634        for q in [&self.wildcard, &self.catalog] {
635            for answer in q.fetch().await? {
636                let Answer::Value(bytes) = answer.answer else {
637                    continue;
638                };
639                let served_toml = String::from_utf8_lossy(&bytes.to_bytes()).to_string();
640                match parse_slice(&served_toml) {
641                    Ok(slice) => slices.push((slice, served_toml)),
642                    Err(e) => tracing::warn!(
643                        origin = %answer.origin,
644                        "introspect reply did not parse, skipping: {e}"
645                    ),
646                }
647            }
648        }
649        Ok(slices)
650    }
651
652    /// Undeclare both queriers, acknowledged.
653    ///
654    /// Both, even when the first refuses (#346): the wildcard sweep and the
655    /// `@catalog` ask are one teardown, and leaving the second declared
656    /// because the first would not go is the half-torn-down state
657    /// [`crate::Monitor::shutdown`] refuses. Failures are reported together.
658    pub async fn undeclare(self) -> Result<()> {
659        crate::bus::teardown::drain_undeclare(
660            vec![
661                ("wildcard introspect".to_string(), self.wildcard),
662                ("@catalog introspect".to_string(), self.catalog),
663            ],
664            RepeatingQuery::undeclare,
665        )
666        .await
667    }
668}
669
670/// One state sample from a snapshot GET.
671#[derive(Debug, Clone)]
672pub struct StateSample {
673    /// Full wire key.
674    pub key: String,
675    /// HLC timestamp, when the deployment stamps samples (RFC 04 §4
676    /// requires it for LWW to be meaningful — its absence is itself a
677    /// doctor-grade observation).
678    pub timestamp: Option<zenoh::time::Timestamp>,
679    pub payload_len: usize,
680}
681
682/// GET the current state under a selector with the fan-in discipline
683/// (target All, consolidation None) — the doctor's freshness check
684/// (RFC 04 §1.2) consumes the timestamps. Same chokepoint posture as
685/// [`fleet_get`]: no subcommand issues a raw `session.get`.
686///
687/// `max` bounds the samples **drained** (`doctor --sample N`): the loop
688/// stops reading at the cap, so a bounded sweep is cheaper, not merely
689/// quieter. `None` drains every reply.
690pub async fn state_snapshot(
691    session: &Session,
692    selector: &str,
693    timeout: Duration,
694    max: Option<usize>,
695) -> Result<Vec<StateSample>> {
696    let replies = disciplined_get(session, selector, &GetOpts::new(timeout))
697        .await
698        .map_err(|e| Error::bus("state snapshot", selector, e))?;
699    let mut out = Vec::new();
700    while let Ok(reply) = replies.recv_async().await {
701        if max.is_some_and(|m| out.len() >= m) {
702            break;
703        }
704        let Ok(sample) = reply.result() else { continue };
705        out.push(StateSample {
706            key: sample.key_expr().as_str().to_string(),
707            timestamp: sample.timestamp().copied(),
708            payload_len: sample.payload().len(),
709        });
710    }
711    Ok(out)
712}
713
714/// One fetched value with its provenance.
715#[derive(Debug, Clone)]
716pub struct FetchedValue {
717    /// The concrete key the value arrived on.
718    pub key: String,
719    pub payload: zenoh::bytes::ZBytes,
720    pub encoding: String,
721    pub timestamp: Option<zenoh::time::Timestamp>,
722    /// The value's attachment, when the sample carried one (#117).
723    pub attachment: Option<zenoh::bytes::ZBytes>,
724    pub source: ValueSource,
725}
726
727/// The outcome: a value, or an attributed nothing.
728#[derive(Debug, Clone)]
729pub enum FetchOutcome {
730    Value(FetchedValue),
731    /// Every rung was tried and none answered — a non-verdict, stated with
732    /// exactly what was asked (RFC 05 §3.1: silence never becomes a claim
733    /// that no value exists).
734    None {
735        attempted: [&'static str; 3],
736    },
737}
738
739/// Fetch ladder bounds.
740#[derive(Debug, Clone, Copy)]
741pub struct FetchSpec {
742    /// Per-GET timeout (two GETs happen: concrete key, then `@adv` cache).
743    pub get_timeout: Duration,
744    /// The final subscribe-window rung's duration.
745    pub window: Duration,
746}
747
748impl Default for FetchSpec {
749    fn default() -> Self {
750        FetchSpec {
751            get_timeout: Duration::from_secs(2),
752            window: Duration::from_millis(1500),
753        }
754    }
755}
756
757/// Fetch one concrete key's current value **on demand** — the value half of
758/// the lazy-observation contract (issue #84): a selection retrieves one
759/// value; nothing is prefetched, nothing stays subscribed.
760///
761/// The ladder, each rung bounded:
762/// 1. GET the concrete key (storages answer; RFC 04 §3.2's "a plain GET does
763///    not reach publisher caches" is exactly why rung 2 exists);
764/// 2. GET `<key>/@adv/**?_max=1` — zenoh-ext's AdvancedPublisher cache
765///    declares its queryable there and replies with the cached sample on its
766///    own concrete key (`@adv` is verbatim, so no data selector ever collides
767///    with it — RFC 03 §4 D2 working in our favor);
768/// 3. a brief callback subscription on the key, first sample wins.
769///
770/// Several answers on a rung (multiple storages) resolve by latest HLC
771/// timestamp; unstamped answers lose to stamped ones (RFC 04 §1.2's LWW).
772pub async fn fetch_value(session: &Session, key: &str, spec: FetchSpec) -> Result<FetchOutcome> {
773    // Rung 1 + 2: bounded GETs.
774    if let Some(v) = fetch_stored(session, key, spec.get_timeout).await? {
775        return Ok(FetchOutcome::Value(v));
776    }
777
778    // Rung 3: a window. The subscriber is explicitly undeclared afterwards —
779    // the window closes, provably.
780    let (tx, rx) = tokio::sync::oneshot::channel::<FetchedValue>();
781    let tx = std::sync::Mutex::new(Some(tx));
782    let subscriber = crate::bus::teardown::declared(
783        "window subscribe",
784        key,
785        session.declare_subscriber(key).callback(move |sample| {
786            if let Some(tx) = tx.lock().expect("fetch window lock").take() {
787                let _ = tx.send(FetchedValue {
788                    key: sample.key_expr().as_str().to_string(),
789                    payload: sample.payload().clone(),
790                    encoding: sample.encoding().to_string(),
791                    timestamp: sample.timestamp().copied(),
792                    attachment: sample.attachment().cloned(),
793                    source: ValueSource::Window,
794                });
795            }
796        }),
797    )
798    .await?;
799    let caught = tokio::time::timeout(spec.window, rx).await;
800    subscriber
801        .undeclare()
802        .await
803        .map_err(|e| Error::bus("window undeclare", key, e))?;
804    if let Ok(Ok(v)) = caught {
805        return Ok(FetchOutcome::Value(v));
806    }
807
808    Ok(FetchOutcome::None {
809        attempted: ["get", "@adv cache", "subscribe window"],
810    })
811}
812
813/// The **stored** half of the [`fetch_value`] ladder, on its own: GET the
814/// concrete key (rung 1 — storages answer), then GET the `@adv` cache
815/// (rung 2). No subscriber is ever declared, so this is two bounded GETs
816/// and nothing on the data plane — the shape `zenctl why`'s default run
817/// needs (issue #214), where the subscribe window is an explicit opt-in.
818///
819/// `Ok(None)` is silence, and silence is never a verdict (RFC 05 §3.1): it
820/// means neither a storage nor a publisher cache *answered*, not that no
821/// value exists.
822pub async fn fetch_stored(
823    session: &Session,
824    key: &str,
825    get_timeout: Duration,
826) -> Result<Option<FetchedValue>> {
827    for (selector, source) in [
828        (key.to_string(), ValueSource::Storage),
829        (format!("{key}/@adv/**?_max=1"), ValueSource::Cache),
830    ] {
831        if let Some(v) = get_latest(session, &selector, source, get_timeout).await? {
832            return Ok(Some(v));
833        }
834    }
835    Ok(None)
836}
837
838async fn get_latest(
839    session: &Session,
840    selector: &str,
841    source: ValueSource,
842    timeout: Duration,
843) -> Result<Option<FetchedValue>> {
844    // `accept_any`: the @adv cache replies with the cached sample on the
845    // sample's OWN key — outside the `<key>/@adv/**` selector.
846    let replies = disciplined_get(session, selector, &GetOpts::new(timeout).accept_any())
847        .await
848        .map_err(|e| Error::bus("get", selector, e))?;
849    let mut candidates = Vec::new();
850    while let Ok(reply) = replies.recv_async().await {
851        let Ok(sample) = reply.result() else { continue };
852        candidates.push(FetchedValue {
853            key: sample.key_expr().as_str().to_string(),
854            payload: sample.payload().clone(),
855            encoding: sample.encoding().to_string(),
856            timestamp: sample.timestamp().copied(),
857            attachment: sample.attachment().cloned(),
858            source,
859        });
860    }
861    Ok(pick_latest(candidates))
862}
863
864/// The winner among several answers on one rung — RFC 04 §1.2's LWW, as a
865/// pure function.
866///
867/// Latest HLC wins; a **stamped** answer beats an unstamped one whatever the
868/// order they arrived in (a storage that does not stamp cannot outrank one
869/// that does, and RFC 04 §4 is why an unstamped deployment is a doctor-grade
870/// observation rather than a tie-break rule here). Ties keep the first
871/// answer, which is the arrival order the channel gave us — arbitrary, but
872/// stated.
873///
874/// Extracted from [`get_latest`] because a rule this quiet is exactly the
875/// kind that stops being true: as a loop over a live reply channel it was
876/// unreachable from a test.
877fn pick_latest(candidates: impl IntoIterator<Item = FetchedValue>) -> Option<FetchedValue> {
878    let mut best: Option<FetchedValue> = None;
879    for candidate in candidates {
880        best = Some(match best.take() {
881            None => candidate,
882            Some(cur) => match (cur.timestamp, candidate.timestamp) {
883                (Some(a), Some(b)) if b > a => candidate,
884                (None, Some(_)) => candidate,
885                _ => cur,
886            },
887        });
888    }
889    best
890}
891
892#[cfg(test)]
893mod tests {
894    use super::*;
895
896    fn stamp(secs: u64) -> zenoh::time::Timestamp {
897        zenoh::time::Timestamp::new(
898            zenoh::time::NTP64::from(Duration::from_secs(secs)),
899            zenoh::time::TimestampId::rand(),
900        )
901    }
902
903    fn value(key: &str, timestamp: Option<zenoh::time::Timestamp>) -> FetchedValue {
904        FetchedValue {
905            key: key.to_string(),
906            payload: zenoh::bytes::ZBytes::from(vec![0u8]),
907            encoding: "application/json".to_string(),
908            timestamp,
909            attachment: None,
910            source: ValueSource::Storage,
911        }
912    }
913
914    #[test]
915    fn the_latest_hlc_wins_whatever_order_the_replies_arrived_in() {
916        let pick = |order: [u64; 3]| {
917            pick_latest(order.map(|s| value(&format!("k/{s}"), Some(stamp(s)))))
918                .expect("three candidates")
919                .key
920        };
921        assert_eq!(pick([1, 2, 3]), "k/3");
922        assert_eq!(pick([3, 2, 1]), "k/3", "arrival order is not the rule");
923        assert_eq!(pick([2, 3, 1]), "k/3");
924    }
925
926    /// RFC 04 §1.2: a storage that does not stamp cannot outrank one that
927    /// does — in either arrival order. That asymmetry is the whole reason
928    /// this is not a `max_by_key` on the timestamp.
929    #[test]
930    fn a_stamped_answer_beats_an_unstamped_one_both_ways_round() {
931        let stamped = || value("stamped", Some(stamp(7)));
932        let bare = || value("bare", None);
933        assert_eq!(pick_latest([bare(), stamped()]).unwrap().key, "stamped");
934        assert_eq!(pick_latest([stamped(), bare()]).unwrap().key, "stamped");
935    }
936
937    #[test]
938    fn nothing_answered_is_nothing_picked_and_a_tie_keeps_the_first() {
939        assert!(
940            pick_latest(Vec::new()).is_none(),
941            "silence is not a value (RFC 05 §3.1)"
942        );
943        let ts = stamp(4);
944        assert_eq!(
945            pick_latest([value("first", Some(ts)), value("second", Some(ts))])
946                .unwrap()
947                .key,
948            "first",
949            "equal stamps keep arrival order — arbitrary, but stated"
950        );
951        assert_eq!(
952            pick_latest([value("first", None), value("second", None)])
953                .unwrap()
954                .key,
955            "first",
956            "two unstamped answers cannot be ordered; the first stands"
957        );
958    }
959}