Skip to main content

robonix_atlas/
client.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// Author: wheatfox <wheatfox17@icloud.com>
3//
4// Atlas client-side helpers shared by every Robonix component that talks
5// to Atlas (pilot, executor, cli, system services, …).
6//
7// All helpers return `anyhow::Error` wrapping the underlying
8// `tonic::Status` so callers can attach context with `.with_context(...)`.
9
10use crate::pb;
11use anyhow::{Context, Result};
12use robonix_scribe::{debug, warn};
13use std::time::Duration;
14use tonic::transport::{Channel, Endpoint};
15
16pub mod channel;
17
18/// Wrapped `pb::atlas_client::AtlasClient` with helpers.
19///
20/// Cheap to clone — the inner generated client wraps a `Channel`, which
21/// is itself just a handle to a connection pool. Share clones across
22/// tasks rather than wrapping in a `Mutex`.
23#[derive(Clone)]
24pub struct AtlasClient {
25    /// Generated control-plane client shared with execution handles.
26    inner: pb::atlas_client::AtlasClient<Channel>,
27    /// Live executions shared across clones, including work whose caller timed out.
28    channels: std::sync::Arc<channel::Channels>,
29}
30
31impl AtlasClient {
32    /// Connect once. Accepts bare `host:port` or full `http://host:port`.
33    pub async fn connect(endpoint: impl AsRef<str>) -> Result<Self> {
34        let normalized = normalize_grpc_endpoint(endpoint.as_ref());
35        let channel = Endpoint::new(normalized.clone())
36            .with_context(|| format!("invalid Atlas endpoint '{}'", normalized))?
37            .connect()
38            .await
39            .with_context(|| format!("connect to Atlas at '{}'", normalized))?;
40        Ok(Self {
41            inner: pb::atlas_client::AtlasClient::new(channel),
42            channels: Default::default(),
43        })
44    }
45
46    /// `connect`, retrying up to `attempts` times with `delay` between tries.
47    pub async fn connect_with_retry(
48        endpoint: impl AsRef<str>,
49        attempts: u32,
50        delay: Duration,
51    ) -> Result<Self> {
52        let endpoint = endpoint.as_ref();
53        let mut last_err: Option<anyhow::Error> = None;
54        for i in 0..attempts.max(1) {
55            match Self::connect(endpoint).await {
56                Ok(c) => return Ok(c),
57                Err(e) => {
58                    debug!(
59                        "[atlas-client] connect attempt {}/{} failed: {e:#}",
60                        i + 1,
61                        attempts
62                    );
63                    last_err = Some(e);
64                    if i + 1 < attempts {
65                        tokio::time::sleep(delay).await;
66                    }
67                }
68            }
69        }
70        Err(last_err.unwrap_or_else(|| anyhow::anyhow!("connect_with_retry: 0 attempts")))
71    }
72
73    pub fn inner(&self) -> pb::atlas_client::AtlasClient<Channel> {
74        self.inner.clone()
75    }
76
77    // ── Registration (one RPC per kind, shared request/response type) ──────
78
79    fn build_register_req(
80        id: &str,
81        namespace: &str,
82        capability_md_path: &str,
83    ) -> pb::RegisterRequest {
84        pb::RegisterRequest {
85            id: id.to_string(),
86            namespace: namespace.to_string(),
87            capability_md_path: capability_md_path.to_string(),
88            // Rust system components (atlas / executor / pilot / liaison)
89            // ship no CAPABILITY.md; only Python packages register content
90            // (via the robonix_api client). Leave empty here.
91            capability_md: String::new(),
92        }
93    }
94
95    /// Register a Primitive. Returns the (possibly Atlas-assigned) id.
96    pub async fn register_primitive(
97        &mut self,
98        id: &str,
99        namespace: &str,
100        capability_md_path: &str,
101    ) -> Result<String> {
102        let resp = self
103            .inner
104            .register_primitive(Self::build_register_req(id, namespace, capability_md_path))
105            .await
106            .with_context(|| format!("RegisterPrimitive '{id}'"))?;
107        Ok(resp.into_inner().id)
108    }
109
110    /// Register a Service.
111    pub async fn register_service(
112        &mut self,
113        id: &str,
114        namespace: &str,
115        capability_md_path: &str,
116    ) -> Result<String> {
117        let resp = self
118            .inner
119            .register_service(Self::build_register_req(id, namespace, capability_md_path))
120            .await
121            .with_context(|| format!("RegisterService '{id}'"))?;
122        Ok(resp.into_inner().id)
123    }
124
125    /// Register a Skill.
126    pub async fn register_skill(
127        &mut self,
128        id: &str,
129        namespace: &str,
130        capability_md_path: &str,
131    ) -> Result<String> {
132        let resp = self
133            .inner
134            .register_skill(Self::build_register_req(id, namespace, capability_md_path))
135            .await
136            .with_context(|| format!("RegisterSkill '{id}'"))?;
137        Ok(resp.into_inner().id)
138    }
139
140    /// Unregister any registered entity. Returns `true` if a record was
141    /// removed, `false` if the id was unknown (idempotent).
142    pub async fn unregister(&mut self, id: &str) -> Result<bool> {
143        let resp = self
144            .inner
145            .unregister(pb::UnregisterRequest { id: id.to_string() })
146            .await
147            .with_context(|| format!("Unregister '{id}'"))?;
148        Ok(resp.into_inner().was_present)
149    }
150
151    // ── Liveness + lifecycle ───────────────────────────────────────────────
152
153    pub async fn heartbeat(&mut self, id: &str) -> Result<()> {
154        self.inner
155            .heartbeat(pb::HeartbeatRequest { id: id.to_string() })
156            .await
157            .with_context(|| format!("Heartbeat '{id}'"))?;
158        Ok(())
159    }
160
161    /// Push a lifecycle state transition. `detail` is a free-form
162    /// human-readable note (e.g. "missing /opt/models/...") that
163    /// `rbnx caps` surfaces verbatim; pass empty when there's nothing.
164    pub async fn set_lifecycle_state(
165        &mut self,
166        id: &str,
167        new_state: pb::LifecycleState,
168        detail: &str,
169    ) -> Result<()> {
170        self.inner
171            .set_lifecycle_state(pb::SetLifecycleStateRequest {
172                id: id.to_string(),
173                state: new_state as i32,
174                detail: detail.to_string(),
175            })
176            .await
177            .with_context(|| format!("SetLifecycleState '{id}' -> {new_state:?}"))?;
178        Ok(())
179    }
180
181    // ── Capability binding ─────────────────────────────────────────────────
182
183    /// Declare one Capability (transport-bound endpoint) on an entity.
184    /// Returns the *authoritative* endpoint (may differ from the request
185    /// when Atlas rewrote to disambiguate). `description` is the optional
186    /// natural-language description for this Capability.
187    pub async fn declare_capability(
188        &mut self,
189        provider_id: &str,
190        contract_id: &str,
191        transport: pb::Transport,
192        endpoint: &str,
193        params: pb::TransportParams,
194    ) -> Result<String> {
195        self.declare_capability_with_description(
196            provider_id,
197            contract_id,
198            transport,
199            endpoint,
200            params,
201            "",
202        )
203        .await
204    }
205
206    /// Same as `declare_capability` but with the instance-specific
207    /// description string (see DeclareCapabilityRequest.description).
208    pub async fn declare_capability_with_description(
209        &mut self,
210        provider_id: &str,
211        contract_id: &str,
212        transport: pb::Transport,
213        endpoint: &str,
214        params: pb::TransportParams,
215        description: &str,
216    ) -> Result<String> {
217        self.declare_capability_with_description_and_time(
218            provider_id,
219            contract_id,
220            transport,
221            endpoint,
222            params,
223            description,
224            None,
225        )
226        .await
227    }
228
229    /// Declare one Capability with optional structured sensor timing while
230    /// preserving the metadata-free APIs used by existing providers.
231    #[allow(clippy::too_many_arguments)] // Mirrors the existing declaration wire fields.
232    pub async fn declare_capability_with_description_and_time(
233        &mut self,
234        provider_id: &str,
235        contract_id: &str,
236        transport: pb::Transport,
237        endpoint: &str,
238        params: pb::TransportParams,
239        description: &str,
240        time_descriptor: Option<pb::CapabilityTimeDescriptor>,
241    ) -> Result<String> {
242        let resp = self
243            .inner
244            .declare_capability(pb::DeclareCapabilityRequest {
245                provider_id: provider_id.to_string(),
246                contract_id: contract_id.to_string(),
247                transport: transport as i32,
248                endpoint: endpoint.to_string(),
249                params: Some(params),
250                description: description.to_string(),
251                time_descriptor,
252            })
253            .await
254            .with_context(|| {
255                format!(
256                    "DeclareCapability provider='{provider_id}' contract='{contract_id}' \
257                     transport={transport:?}"
258                )
259            })?;
260        Ok(resp.into_inner().endpoint)
261    }
262
263    // ── Discovery ──────────────────────────────────────────────────────────
264
265    /// Generic Query. `kind == Kind::Unspecified` = no kind filter (all
266    /// kinds returned; each `CapabilityProvider.kind` carries its kind).
267    /// Empty strings / `Transport::Unspecified` = no filter on that field.
268    pub async fn query(
269        &mut self,
270        kind: pb::Kind,
271        id: &str,
272        contract_id: &str,
273        namespace_prefix: &str,
274        transport: pb::Transport,
275    ) -> Result<Vec<pb::CapabilityProvider>> {
276        let resp = self
277            .inner
278            .query(pb::QueryRequest {
279                kind: kind as i32,
280                id: id.to_string(),
281                contract_id: contract_id.to_string(),
282                namespace_prefix: namespace_prefix.to_string(),
283                transport: transport as i32,
284            })
285            .await
286            .with_context(|| format!("Query kind={kind:?}"))?;
287        Ok(resp.into_inner().providers)
288    }
289
290    /// Convenience — find Primitives (kind filter applied).
291    pub async fn query_primitives(
292        &mut self,
293        id: &str,
294        contract_id: &str,
295        namespace_prefix: &str,
296        transport: pb::Transport,
297    ) -> Result<Vec<pb::CapabilityProvider>> {
298        self.query(
299            pb::Kind::Primitive,
300            id,
301            contract_id,
302            namespace_prefix,
303            transport,
304        )
305        .await
306    }
307
308    /// Convenience — find Services.
309    pub async fn query_services(
310        &mut self,
311        id: &str,
312        contract_id: &str,
313        namespace_prefix: &str,
314        transport: pb::Transport,
315    ) -> Result<Vec<pb::CapabilityProvider>> {
316        self.query(
317            pb::Kind::Service,
318            id,
319            contract_id,
320            namespace_prefix,
321            transport,
322        )
323        .await
324    }
325
326    /// Convenience — find Skills.
327    pub async fn query_skills(
328        &mut self,
329        id: &str,
330        contract_id: &str,
331        namespace_prefix: &str,
332        transport: pb::Transport,
333    ) -> Result<Vec<pb::CapabilityProvider>> {
334        self.query(
335            pb::Kind::Skill,
336            id,
337            contract_id,
338            namespace_prefix,
339            transport,
340        )
341        .await
342    }
343
344    /// Consumer-facing discovery: flat list of Capabilities across all
345    /// kinds. Walks `Query(kind=Unspecified)` and flattens each
346    /// CapabilityProvider's nested capabilities. Each returned
347    /// `Capability` already carries `provider_id` + `provider_kind`.
348    pub async fn flatten_capabilities(
349        &mut self,
350        contract_id: &str,
351        namespace_prefix: &str,
352        transport: pb::Transport,
353    ) -> Result<Vec<pb::Capability>> {
354        let providers = self
355            .query(
356                pb::Kind::Unspecified,
357                "",
358                contract_id,
359                namespace_prefix,
360                transport,
361            )
362            .await?;
363        Ok(providers
364            .into_iter()
365            .flat_map(|p| p.capabilities.into_iter())
366            .collect())
367    }
368
369    /// Back-compat alias for the legacy 3-arg signature returning a list
370    /// of CapabilityProviders. Equivalent to
371    /// `query(Kind::Unspecified, id, contract_id, "", transport)`.
372    pub async fn query_capabilities(
373        &mut self,
374        id: &str,
375        contract_id: &str,
376        transport: pb::Transport,
377    ) -> Result<Vec<pb::CapabilityProvider>> {
378        self.query(pb::Kind::Unspecified, id, contract_id, "", transport)
379            .await
380    }
381
382    // ── Channels ───────────────────────────────────────────────────────────
383
384    /// Open a channel to one (provider, contract, transport). Atlas only
385    /// providers the edge — the consumer dials the returned endpoint
386    /// itself using whatever transport-appropriate mechanism (tonic for
387    /// grpc, rclrs for ros2, fastmcp for mcp, …).
388    /// Returns `(channel_id, endpoint, params)`.
389    pub async fn connect_capability(
390        &mut self,
391        consumer_id: &str,
392        provider_id: &str,
393        contract_id: &str,
394        transport: pb::Transport,
395    ) -> Result<(String, String, pb::TransportParams)> {
396        self.allocate_channel(consumer_id, provider_id, contract_id, transport)
397            .await
398    }
399
400    async fn allocate_channel(
401        &mut self,
402        consumer_id: &str,
403        provider_id: &str,
404        contract_id: &str,
405        transport: pb::Transport,
406    ) -> Result<(String, String, pb::TransportParams)> {
407        let (channel_id, endpoint, params, _) = self
408            .connect_capability_with_time(consumer_id, provider_id, contract_id, transport)
409            .await?;
410        Ok((channel_id, endpoint, params))
411    }
412
413    /// Open a channel and return the timing descriptor from the same Atlas
414    /// declaration record as the endpoint and transport parameters.
415    pub async fn connect_capability_with_time(
416        &mut self,
417        consumer_id: &str,
418        provider_id: &str,
419        contract_id: &str,
420        transport: pb::Transport,
421    ) -> Result<(
422        String,
423        String,
424        pb::TransportParams,
425        Option<pb::CapabilityTimeDescriptor>,
426    )> {
427        let resp = self
428            .inner
429            .connect_capability(pb::ConnectCapabilityRequest {
430                consumer_id: consumer_id.to_string(),
431                provider_id: provider_id.to_string(),
432                contract_id: contract_id.to_string(),
433                transport: transport as i32,
434            })
435            .await
436            .with_context(|| {
437                format!(
438                    "ConnectCapability consumer='{consumer_id}' provider='{provider_id}' \
439                     contract='{contract_id}' transport={transport:?}"
440                )
441            })?;
442        let r = resp.into_inner();
443        Ok((
444            r.channel_id,
445            r.endpoint,
446            r.params.unwrap_or_default(),
447            r.time_descriptor,
448        ))
449    }
450
451    /// Release a previously-opened channel. Idempotent: returns `false`
452    /// when the channel_id was unknown.
453    pub async fn disconnect_capability(&mut self, channel_id: &str) -> Result<bool> {
454        let resp = self
455            .inner
456            .disconnect_capability(pb::DisconnectCapabilityRequest {
457                channel_id: channel_id.to_string(),
458            })
459            .await
460            .with_context(|| format!("DisconnectCapability '{channel_id}'"))?;
461        Ok(resp.into_inner().was_open)
462    }
463
464    // ── Contract registry ──────────────────────────────────────────────────
465
466    /// Look up one contract by id.
467    pub async fn query_contract(
468        &mut self,
469        contract_id: &str,
470    ) -> Result<Option<pb::ContractDescriptor>> {
471        let resp = self
472            .inner
473            .query_contract(pb::QueryContractRequest {
474                contract_id: contract_id.to_string(),
475            })
476            .await
477            .with_context(|| format!("QueryContract '{contract_id}'"))?;
478        let inner = resp.into_inner();
479        Ok(if inner.found { inner.contract } else { None })
480    }
481
482    pub async fn list_contracts(
483        &mut self,
484        namespace_prefix: &str,
485    ) -> Result<Vec<pb::ContractDescriptor>> {
486        let resp = self
487            .inner
488            .list_contracts(pb::ListContractsRequest {
489                namespace_prefix: namespace_prefix.to_string(),
490            })
491            .await
492            .with_context(|| format!("ListContracts prefix='{namespace_prefix}'"))?;
493        Ok(resp.into_inner().contracts)
494    }
495}
496
497/// gRPC-only convenience: pick the first Capability matching `contract_id`
498/// over gRPC, call `ConnectCapability` to register the edge, dial the
499/// returned host:port, and hand back a tonic Channel + the channel_id
500/// (so the caller can DisconnectCapability on shutdown).
501///
502/// Returns `(channel_id, provider_id, Channel)`.
503pub async fn connect_to_capability(
504    atlas: &mut AtlasClient,
505    consumer_id: &str,
506    contract_id: &str,
507) -> Result<(String, String, Channel)> {
508    let rows = atlas
509        .flatten_capabilities(contract_id, "", pb::Transport::Grpc)
510        .await?;
511    if rows.is_empty() {
512        anyhow::bail!(
513            "no Capability offering contract_id='{contract_id}' over gRPC; \
514             registered entities may not have declared this Capability yet"
515        );
516    }
517    if rows.len() > 1 {
518        warn!(
519            "[atlas-client] {} entities offer '{contract_id}' over gRPC; \
520             picking first ('{}'). Use query_capabilities + connect_capability \
521             for deterministic selection.",
522            rows.len(),
523            rows[0].provider_id,
524        );
525    }
526    let provider_id = rows
527        .into_iter()
528        .next()
529        .expect("non-empty checked above")
530        .provider_id;
531    let (channel_id, endpoint_str, _params) = atlas
532        .connect_capability(consumer_id, &provider_id, contract_id, pb::Transport::Grpc)
533        .await?;
534    let normalized = normalize_grpc_endpoint(&endpoint_str);
535    let channel = Endpoint::new(normalized.clone())
536        .with_context(|| {
537            format!(
538                "invalid endpoint '{}' for provider '{}'",
539                normalized, provider_id
540            )
541        })?
542        .connect()
543        .await
544        .with_context(|| {
545            format!(
546                "connect to provider '{provider_id}' at '{normalized}' for contract '{contract_id}'"
547            )
548        })?;
549    Ok((channel_id, provider_id, channel))
550}
551
552// ── TransportParams constructors ───────────────────────────────────────────
553
554pub fn grpc_params(
555    proto_file: impl Into<String>,
556    service_name: impl Into<String>,
557    method: impl Into<String>,
558) -> pb::TransportParams {
559    pb::TransportParams {
560        kind: Some(pb::transport_params::Kind::Grpc(pb::GrpcParams {
561            proto_file: proto_file.into(),
562            service_name: service_name.into(),
563            method: method.into(),
564        })),
565    }
566}
567
568pub fn ros2_params(qos_profile: impl Into<String>) -> pb::TransportParams {
569    pb::TransportParams {
570        kind: Some(pb::transport_params::Kind::Ros2(pb::Ros2Params {
571            qos_profile: qos_profile.into(),
572        })),
573    }
574}
575
576/// Build `TransportParams` for an MCP tool Capability. The natural-
577/// language description now lives on `DeclareCapabilityRequest.description`,
578/// not inside `McpParams`.
579pub fn mcp_params(input_schema_json: impl Into<String>) -> pb::TransportParams {
580    pb::TransportParams {
581        kind: Some(pb::transport_params::Kind::Mcp(pb::McpParams {
582            input_schema_json: input_schema_json.into(),
583        })),
584    }
585}
586
587// ── Helpers ────────────────────────────────────────────────────────────────
588
589fn normalize_grpc_endpoint(s: &str) -> String {
590    let s = s.trim();
591    if s.starts_with("http://") || s.starts_with("https://") {
592        s.to_string()
593    } else {
594        format!("http://{s}")
595    }
596}
浙ICP备2023005800号-2 浙公网安备33010902005384号