Skip to main content

zenkey_fleet/bus/
producer.rs

1//! Producer-side bring-up discipline (RFC 04 §5, RFC 05 §2.1/§3, RFC 08
2//! §6.1) — the MUSTs every producer owes the bus, as an API that makes the
3//! wrong shapes unrepresentable rather than a checklist that trusts review.
4//!
5//! The conformance review found these uniformly unenforced, with the
6//! in-repo dev tools modeling the violations; this module is the
7//! enforcement seam, and [`crate::bus::serve`]/[`crate::tape::generate`] now ride it
8//! or its rules. It lives beside — not inside — `serve.rs`, deliberately:
9//! `serve` is the *explorer's* mock (answer anything, wildcards welcome),
10//! while this is the *producer's* posture (concrete keys, ordered
11//! presence), and folding the strict API into the permissive one would
12//! give every mock a way to claim it is a producer.
13//!
14//! Three rules, three shapes:
15//!
16//! - **Order** ([`BringUp`]): a producer declares its queryables
17//!   (`introspect`, `describe`, its procedures) **first**, and its `alive`
18//!   liveliness token **last** — "alive ⇒ callable" (RFC 04 §5): callers
19//!   attribute RPC silence against the roster, so a token that precedes
20//!   the queryables manufactures false negatives. RFC 08 §6.1's bounded
21//!   grace exists to tolerate declarations spawned concurrently at
22//!   startup; this API sequences them instead, so there is no race for a
23//!   checker to be graceful about. The token is only mintable by
24//!   consuming the bring-up: alive-before-queryable does not typecheck.
25//! - **Vocabulary** ([`ReservedError`]): the RFC 05 §3 reserved error
26//!   names as an enum, so a responder cannot misspell `error/unsupported`
27//!   — and RFC 08 §6.1's conditional-procedure rule (declare always,
28//!   answer `error/unsupported`/`error/gated` when gated) is writable
29//!   without a string literal.
30//! - **Reply key** ([`Responder::reply`]): a procedure replies on its
31//!   **own concrete key**, never by echoing `query.key_expr()` (RFC 05
32//!   §2.1: consolidation keeps one reply *per reply key*, so a fleet
33//!   echoing a shared wildcard selector consolidates down to one
34//!   survivor). The responder holds its declared key and replies on it;
35//!   the query's key is never consulted.
36
37use crate::{Error, Result};
38use zenoh::Session;
39use zenoh::handlers::FifoChannelHandler;
40use zenoh::liveliness::LivelinessToken;
41use zenoh::query::{Query, Queryable};
42
43/// The RFC 05 §3 reserved error vocabulary — the names every conforming
44/// caller understands, as a closed enum. Producer-specific names live under
45/// `error/<producer>/…` and are registered like subjects; these six are the
46/// convention's own.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub enum ReservedError {
49    /// `error/invalid-args` — the request payload does not parse or fails
50    /// validation.
51    InvalidArgs,
52    /// `error/unauthorized` — the caller may not invoke this procedure.
53    Unauthorized,
54    /// `error/not-found` — the named entity does not exist here.
55    NotFound,
56    /// `error/unsupported` — the capability is absent from this build
57    /// (RFC 08 §6.1: a conditional procedure still declares, and answers
58    /// with this — "producer present, capability not in this build →
59    /// rebuild").
60    Unsupported,
61    /// `error/busy` — present and capable, but not now.
62    Busy,
63    /// `error/gated` — the capability is built in but disabled here by
64    /// policy or configuration (RFC 05 §3: gated writes keep their gate at
65    /// the server; RFC 08 §6.1: "capability built in, disabled here →
66    /// reconfigure").
67    Gated,
68}
69
70impl ReservedError {
71    /// Every reserved name, for iteration (renderers, doctors).
72    pub const ALL: [ReservedError; 6] = [
73        ReservedError::InvalidArgs,
74        ReservedError::Unauthorized,
75        ReservedError::NotFound,
76        ReservedError::Unsupported,
77        ReservedError::Busy,
78        ReservedError::Gated,
79    ];
80
81    /// The wire name, namespaced like a key (RFC 05 §3).
82    pub fn name(self) -> &'static str {
83        match self {
84            ReservedError::InvalidArgs => "error/invalid-args",
85            ReservedError::Unauthorized => "error/unauthorized",
86            ReservedError::NotFound => "error/not-found",
87            ReservedError::Unsupported => "error/unsupported",
88            ReservedError::Busy => "error/busy",
89            ReservedError::Gated => "error/gated",
90        }
91    }
92
93    /// The RFC 05 §3 error envelope, `{ "error": <name>, "message": … }`,
94    /// serialized as JSON (the RFC shows the envelope as JSON for
95    /// readability; a deployment whose payload default differs encodes the
96    /// same two fields itself).
97    pub fn envelope(self, message: &str) -> Vec<u8> {
98        serde_json::to_vec(&serde_json::json!({
99            "error": self.name(),
100            "message": message,
101        }))
102        .expect("two string fields serialize")
103    }
104}
105
106/// One declared `@rpc` queryable, bound to its own concrete key — the only
107/// key it will ever reply on.
108pub struct Responder {
109    key: String,
110    queryable: Queryable<FifoChannelHandler<Query>>,
111}
112
113impl std::fmt::Debug for Responder {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        f.debug_struct("Responder")
116            .field("key", &self.key)
117            .finish_non_exhaustive()
118    }
119}
120
121impl Responder {
122    /// The concrete key this responder was declared on — and replies on.
123    pub fn key(&self) -> &str {
124        &self.key
125    }
126
127    /// The next query, or `None` once the queryable is gone.
128    pub async fn next(&self) -> Option<Query> {
129        self.queryable.recv_async().await.ok()
130    }
131
132    /// Reply a value on this responder's **own concrete key** (RFC 05
133    /// §2.1). `query.key_expr()` is deliberately never consulted: echoing
134    /// the query's selector puts a fleet's replies on one shared wildcard
135    /// key, and default consolidation keeps one survivor per reply key.
136    pub async fn reply(
137        &self,
138        query: &Query,
139        payload: Vec<u8>,
140        encoding: Option<&str>,
141    ) -> Result<()> {
142        let reply = query.reply(self.key.clone(), payload);
143        let reply = match encoding {
144            Some(e) => reply.encoding(e),
145            None => reply,
146        };
147        reply.await.map_err(|e| Error::bus("reply", &self.key, e))
148    }
149
150    /// Refuse on Zenoh's reply-error channel with a [`ReservedError`]
151    /// envelope (RFC 05 §3: a value reply always means success; a failure
152    /// always rides `reply_err` — never a success payload carrying
153    /// `ok: false`).
154    pub async fn reply_err(
155        &self,
156        query: &Query,
157        error: ReservedError,
158        message: &str,
159    ) -> Result<()> {
160        query
161            .reply_err(error.envelope(message))
162            .encoding("application/json")
163            .await
164            .map_err(|e| Error::bus("reply_err", &self.key, e))
165    }
166
167    /// Undeclare, acknowledged.
168    pub async fn undeclare(self) -> Result<()> {
169        self.queryable
170            .undeclare()
171            .await
172            .map_err(|e| Error::bus("undeclare", &self.key, e))
173    }
174}
175
176/// The ordered bring-up (RFC 04 §5): queryables first, `alive` last — as
177/// one API in which the wrong order is unrepresentable.
178///
179/// ```no_run
180/// # async fn demo(session: zenoh::Session) -> zenkey_fleet::Result<()> {
181/// let mut up = zenkey_fleet::bus::producer::BringUp::new(&session);
182/// up.serve("v1/h-3fa9c2d41b7e/@rpc/sysinfo/introspect").await?;
183/// up.serve("v1/h-3fa9c2d41b7e/@rpc/sysinfo/describe").await?;
184/// // The token is mintable only by consuming the bring-up: every
185/// // queryable above is declared (awaited, not spawned) before it.
186/// let live = up.alive("v1/h-3fa9c2d41b7e/state/sysinfo/alive").await?;
187/// # let _ = live; Ok(()) }
188/// ```
189///
190/// Keys are written base-relative here because a *producer's* session is
191/// namespaced (the deployment base is session config, RFC 03 §1.1); an
192/// un-namespaced explorer passes full wire keys, which is equally fine —
193/// the API is a string seam either way, concreteness enforced.
194#[derive(Debug)]
195pub struct BringUp<'a> {
196    session: &'a Session,
197    responders: Vec<Responder>,
198}
199
200impl<'a> BringUp<'a> {
201    /// Start a bring-up: nothing is declared yet, and no `alive` token can
202    /// exist before [`alive`](Self::alive) consumes this value.
203    pub fn new(session: &'a Session) -> Self {
204        BringUp {
205            session,
206            responders: Vec::new(),
207        }
208    }
209
210    /// Declare one `@rpc` queryable on the producer's **own concrete key**,
211    /// awaited before return (no spawn race, so RFC 08 §6.1's bounded
212    /// grace has nothing to tolerate). Refused:
213    ///
214    /// - a wildcard key — a producer serves its own concrete keys, and a
215    ///   concrete declared key is what makes [`Responder::reply`]'s
216    ///   reply-key discipline meaningful (RFC 05 §2.1);
217    /// - `complete` is not a parameter at all: `@rpc` queryables are
218    ///   **never** declared complete (RFC 05 §2.1 — one complete queryable
219    ///   short-circuits `BestMatching` callers to a single reply).
220    pub async fn serve(&mut self, key: &str) -> Result<&Responder> {
221        let parsed = zenoh::key_expr::KeyExpr::try_from(key.to_string())
222            .map_err(|e| Error::bus("declare queryable", key, e))?;
223        if parsed.is_wild() {
224            // The caller handed us the key; nothing was declared.
225            return Err(Error::unaskable(
226                key.to_string(),
227                "a producer serves its own concrete key, never a wildcard \
228                 (RFC 05 §2.1 — replies are attributed by their concrete reply \
229                 key)",
230            ));
231        }
232        let queryable = crate::bus::teardown::declared(
233            "declare queryable",
234            key,
235            self.session.declare_queryable(parsed).complete(false),
236        )
237        .await?;
238        self.responders.push(Responder {
239            key: key.to_string(),
240            queryable,
241        });
242        Ok(self.responders.last().expect("just pushed"))
243    }
244
245    /// Declare the `alive` liveliness token — consuming the bring-up, so
246    /// the token structurally cannot precede the queryables ("alive ⇒
247    /// callable", RFC 04 §5).
248    pub async fn alive(self, alive_key: &str) -> Result<LiveProducer> {
249        let token = crate::bus::teardown::declared(
250            "declare alive token",
251            alive_key,
252            self.session
253                .liveliness()
254                .declare_token(alive_key.to_string()),
255        )
256        .await?;
257        Ok(LiveProducer {
258            token: Some(token),
259            responders: self.responders,
260        })
261    }
262
263    /// Finish **without** presence: hand back the declared responders and
264    /// never mint a token. This is the mock/synthetic path ([`crate::
265    /// generate`]'s impersonated producers, RFC 13 §5) — a tool that
266    /// answers for a producer must not also claim its presence. A real
267    /// producer wants [`alive`](Self::alive).
268    pub fn without_alive(self) -> Vec<Responder> {
269        self.responders
270    }
271}
272
273/// A producer that is up: queryables declared, then `alive` — held while
274/// serving.
275#[derive(Debug)]
276pub struct LiveProducer {
277    token: Option<LivelinessToken>,
278    /// The declared responders, in bring-up order — drive them
279    /// ([`Responder::next`]) to serve.
280    pub responders: Vec<Responder>,
281}
282
283impl LiveProducer {
284    /// Retire in the reverse of bring-up: retract `alive` **first** (the
285    /// roster must stop attributing silence to a producer that is going
286    /// away), then undeclare the queryables, acknowledged.
287    ///
288    /// A token that will not retract still bails before the queryables, and
289    /// deliberately: "alive ⇒ callable" (RFC 04 §5) is a claim that outlives
290    /// this call, and stripping callability while presence stands would
291    /// manufacture exactly the false negative the ordering exists to prevent.
292    /// The queryables themselves drain (#346): one that will not undeclare
293    /// must not leave the rest declared, and the failures are reported
294    /// together — the `bus::teardown` shape, shared with the monitor and the
295    /// replayer.
296    pub async fn retire(mut self) -> Result<()> {
297        if let Some(token) = self.token.take() {
298            token
299                .undeclare()
300                .await
301                .map_err(|e| Error::bus("retract alive token", "", e))?;
302        }
303        let declared: Vec<(String, Responder)> = self
304            .responders
305            .drain(..)
306            .map(|r| (r.key.clone(), r))
307            .collect();
308        crate::bus::teardown::drain_undeclare(declared, Responder::undeclare).await
309    }
310}