Skip to main content

toolkit/
discovery.rs

1//! Consumer-side discovery wiring for eventual readiness.
2//!
3//! Bridges the service [`DirectoryClient`](crate::DirectoryClient) into the
4//! contract layer's [`EndpointResolver`], and carries the
5//! [`ConsumerRegistration`]s emitted by `#[toolkit::consumes]` that the
6//! runtime's proxy-wiring phase replays at startup.
7//!
8//! Unconditional: consuming another gear over a discovered REST transport is
9//! the normal case, and `#[toolkit::consumes]` emits its registration
10//! unconditionally too. Putting this behind a feature only created a way to
11//! build a gear whose declared dependencies were silently never wired.
12
13use std::sync::Arc;
14
15use async_trait::async_trait;
16
17use cf_system_sdks::directory::{DirectoryInvalidArgument, DirectoryNotFound};
18
19use crate::DirectoryClient;
20use crate::client_hub::ClientHub;
21
22/// Re-export so the `#[toolkit::consumes]`-generated wire fn can name the
23/// resolver type as `toolkit::discovery::EndpointResolver` without the consuming
24/// gear crate needing a direct `toolkit-contract` dependency.
25pub use toolkit_contract::runtime::resolving::{EndpointResolver, ResolveError, ResolveTarget};
26
27/// Adapts the service [`DirectoryClient`] into the contract-layer
28/// [`EndpointResolver`] consumed by `DirectoryResolvingClient`.
29///
30/// Keeps `toolkit-contract` free of a dependency on the directory SDK: the
31/// adapter lives here in `toolkit`, which already owns `DirectoryClient`.
32///
33/// Successful resolutions are memoized for a short TTL ([`Self::TTL`]) so a
34/// per-call resolving client does not incur a directory round-trip on every
35/// business call (the `OoP` directory is a network hop). Only `Ok(Some(uri))` is
36/// cached; `Ok(None)` / `Err` always re-resolve. The TTL is deliberately short
37/// so endpoint churn self-heals within ~TTL, and an endpoint failure seen by a
38/// client drops the entry at once ([`EndpointResolver::invalidate`]).
39///
40/// REST endpoints are looked up by gear name, gRPC endpoints by service name
41/// (`resolve_grpc_service`); the two are cached apart.
42pub struct DirectoryEndpointResolver {
43    client: Arc<dyn DirectoryClient>,
44    cache: parking_lot::Mutex<std::collections::HashMap<String, (String, std::time::Instant)>>,
45}
46
47impl DirectoryEndpointResolver {
48    /// Memoization window for successful resolutions.
49    ///
50    /// Public because it bounds observable behaviour: a provider that moves is
51    /// followed within roughly this window, or at the next call after a client
52    /// saw the old endpoint fail.
53    pub const TTL: std::time::Duration = std::time::Duration::from_millis(1500);
54
55    /// Wrap a [`DirectoryClient`] with a short-TTL resolution cache.
56    #[must_use]
57    pub fn new(client: Arc<dyn DirectoryClient>) -> Self {
58        Self {
59            client,
60            cache: parking_lot::Mutex::new(std::collections::HashMap::new()),
61        }
62    }
63
64    fn cached(&self, key: &str) -> Option<String> {
65        self.cache
66            .lock()
67            .get(key)
68            .filter(|(_, at)| at.elapsed() < Self::TTL)
69            .map(|(uri, _)| uri.clone())
70    }
71
72    fn store(&self, key: &str, uri: &str) {
73        self.cache
74            .lock()
75            .insert(key.to_owned(), (uri.to_owned(), std::time::Instant::now()));
76    }
77
78    fn cache_key(target: &ResolveTarget) -> String {
79        match target {
80            ResolveTarget::Grpc { service, .. } => format!("grpc:{service}"),
81            // `ResolveTarget` is non-exhaustive; anything else is keyed by gear.
82            other => format!("rest:{}", other.gear()),
83        }
84    }
85
86    /// Look `name` up through `lookup`, memoizing a hit under `key`. `name`
87    /// is the gear or service name, for errors and logs.
88    async fn resolve_cached<F, Fut>(
89        &self,
90        key: &str,
91        name: &str,
92        lookup: F,
93    ) -> Result<Option<String>, ResolveError>
94    where
95        F: FnOnce() -> Fut,
96        Fut: std::future::Future<Output = anyhow::Result<crate::ServiceEndpoint>>,
97    {
98        // Fresh cache hit avoids the directory round-trip.
99        if let Some(uri) = self.cached(key) {
100            return Ok(Some(uri));
101        }
102        // Preserve the trait's `Ok(None)` (no live instance / not ready) vs
103        // `Err` (directory backend unreachable) distinction so a real directory
104        // outage surfaces at `warn` rather than being silently treated as
105        // "provider not ready". The directory returns the typed
106        // `DirectoryNotFound` sentinel for the not-found case; anything else is
107        // a genuine backend/transport failure (relevant for the OoP gRPC
108        // directory client).
109        match lookup().await {
110            Ok(ep) => {
111                self.store(key, &ep.uri);
112                Ok(Some(ep.uri))
113            }
114            Err(e) if e.downcast_ref::<DirectoryNotFound>().is_some() => Ok(None),
115            Err(e) if e.downcast_ref::<DirectoryInvalidArgument>().is_some() => {
116                // A malformed provider name is a permanent configuration error,
117                // not a transient outage: re-resolving can never succeed. Log
118                // it distinctly from the generic backend-failure path (at
119                // `error`, not the caller's transient `warn`) so the actionable
120                // "fix your config" message is not mistaken for a directory
121                // outage, and still return `Err` so the call fails.
122                tracing::error!(
123                    name,
124                    error = %e,
125                    "provider name permanently rejected by the directory (invalid \
126                     argument); this is a static configuration error, not a directory \
127                     outage, and will never resolve. Check the consumed gear or service name"
128                );
129                Err(ResolveError::new(name, e))
130            }
131            Err(e) => Err(ResolveError::new(name, e)),
132        }
133    }
134}
135
136#[async_trait]
137impl EndpointResolver for DirectoryEndpointResolver {
138    async fn resolve_endpoint(&self, gear: &str) -> Result<Option<String>, ResolveError> {
139        let key = Self::cache_key(&ResolveTarget::rest(gear));
140        self.resolve_cached(&key, gear, || self.client.resolve_rest_service(gear))
141            .await
142    }
143
144    async fn resolve_grpc_endpoint(&self, service: &str) -> Result<Option<String>, ResolveError> {
145        let key = Self::cache_key(&ResolveTarget::grpc("", service));
146        self.resolve_cached(&key, service, || self.client.resolve_grpc_service(service))
147            .await
148    }
149
150    fn invalidate(&self, target: &ResolveTarget) {
151        self.cache.lock().remove(&Self::cache_key(target));
152    }
153}
154
155/// An [`EndpointResolver`] that never resolves any gear (`Ok(None)` for every
156/// lookup). Used by the proxy-wiring phase when no [`DirectoryClient`] is present
157/// in the [`ClientHub`]: co-located (local) consumers still short-circuit and
158/// wire successfully, while remote consumers register as *unresolved* readiness
159/// gates (so `/readyz` correctly stays 503) rather than being silently skipped.
160pub struct NullEndpointResolver;
161
162#[async_trait]
163impl EndpointResolver for NullEndpointResolver {
164    async fn resolve_endpoint(&self, _gear: &str) -> Result<Option<String>, ResolveError> {
165        Ok(None)
166    }
167}
168
169/// An [`EndpointResolver`] that always resolves to a fixed endpoint — the
170/// ADR-0004 static-endpoint override. It bypasses the service directory: a
171/// consumer configured with `gears.<owner>.clients.consumes.<dep>.endpoint`
172/// wires a resolving client whose endpoint is this constant. gRPC lookups get
173/// `grpc_endpoint` when one is set, else the same endpoint.
174pub struct StaticEndpointResolver {
175    endpoint: String,
176    grpc_endpoint: Option<String>,
177}
178
179impl StaticEndpointResolver {
180    /// Wrap a fixed base endpoint URI.
181    #[must_use]
182    pub fn new(endpoint: impl Into<String>) -> Self {
183        Self {
184            endpoint: endpoint.into(),
185            grpc_endpoint: None,
186        }
187    }
188
189    /// Resolve gRPC services to `endpoint` instead.
190    #[must_use]
191    pub fn with_grpc_endpoint(mut self, endpoint: impl Into<String>) -> Self {
192        self.grpc_endpoint = Some(endpoint.into());
193        self
194    }
195}
196
197#[async_trait]
198impl EndpointResolver for StaticEndpointResolver {
199    async fn resolve_endpoint(&self, _gear: &str) -> Result<Option<String>, ResolveError> {
200        Ok(Some(self.endpoint.clone()))
201    }
202
203    async fn resolve_grpc_endpoint(&self, _service: &str) -> Result<Option<String>, ResolveError> {
204        Ok(Some(
205            self.grpc_endpoint
206                .clone()
207                .unwrap_or_else(|| self.endpoint.clone()),
208        ))
209    }
210}
211
212/// Static overrides for some transports, the directory for the rest. Built by
213/// the proxy-wiring phase from `clients.consumes.<dep>.endpoint` /
214/// `grpc_endpoint`.
215pub(crate) struct OverrideResolver {
216    /// Fixed REST endpoint, from `endpoint`.
217    pub(crate) rest: Option<String>,
218    /// Fixed gRPC endpoint, from `grpc_endpoint`, else `endpoint`.
219    pub(crate) grpc: Option<String>,
220    /// Resolves a transport that has no override.
221    pub(crate) fallback: Arc<dyn EndpointResolver>,
222}
223
224#[async_trait]
225impl EndpointResolver for OverrideResolver {
226    async fn resolve_endpoint(&self, gear: &str) -> Result<Option<String>, ResolveError> {
227        match &self.rest {
228            Some(uri) => Ok(Some(uri.clone())),
229            None => self.fallback.resolve_endpoint(gear).await,
230        }
231    }
232
233    async fn resolve_grpc_endpoint(&self, service: &str) -> Result<Option<String>, ResolveError> {
234        match &self.grpc {
235            Some(uri) => Ok(Some(uri.clone())),
236            None => self.fallback.resolve_grpc_endpoint(service).await,
237        }
238    }
239
240    fn invalidate(&self, target: &ResolveTarget) {
241        self.fallback.invalidate(target);
242    }
243}
244
245/// Outcome of a [`ConsumerRegistration::wire`] call: whether the dependency was
246/// satisfied by a co-located compile-time impl (no directory dependency) or by
247/// a directory-resolving client that still needs endpoint resolution.
248///
249/// The runtime uses this to gate readiness: `Local` deps are readiness-resolved
250/// immediately (no `/readyz` gating, no probe loop), while remote deps gate
251/// readiness until the directory resolves what the client will call (ADR-0007).
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253#[non_exhaustive]
254pub enum WireOutcome {
255    /// A compile-time (in-process) impl was already registered — it won the
256    /// `hub.try_get_local` short-circuit; no remote binding was created.
257    Local,
258    /// A directory-resolving REST client was registered; readiness waits for
259    /// the provider gear's REST endpoint.
260    Remote,
261    /// A directory-resolving gRPC client was registered; readiness waits for
262    /// the directory to resolve `service`.
263    RemoteGrpc {
264        /// Fully qualified gRPC service name (`package.Service`).
265        service: &'static str,
266    },
267}
268
269/// A consumer→provider contract wiring, registered by `#[toolkit::consumes]`
270/// via `inventory::submit!` and replayed by the runtime's proxy-wiring phase.
271///
272/// `wire` is a non-capturing `fn` (the provider gear name is inlined into the
273/// generated body). It must:
274///   1. short-circuit returning [`WireOutcome::Local`] if a compile-time (local)
275///      impl is already registered (`hub.try_get_local::<dyn Trait>().is_some()`),
276///      so in-process providers win;
277///   2. otherwise register a directory-resolving client under the contract
278///      trait via [`ClientHub::register_remote_proxy`] (using the supplied
279///      [`EndpointResolver`]) and return [`WireOutcome::Remote`] for REST or
280///      [`WireOutcome::RemoteGrpc`] for gRPC.
281///
282/// The runtime passes the owner gear's view ([`ClientHub::for_gear`]) when
283/// `owner_gear` is a gear in this process, so each consumer gets its own proxy
284/// built from its own `clients.consumes.<dep>` settings; otherwise it passes the
285/// process-wide hub.
286///
287/// Step 1 must use `try_get_local`, not `try_get`: `try_get` also returns a
288/// process-wide proxy, and reporting that as `Local` would mark the dependency
289/// readiness-resolved — flipping `/readyz` to 200 while the provider is still
290/// absent.
291pub struct ConsumerRegistration {
292    /// Gear that declares the dependency (diagnostics).
293    pub owner_gear: &'static str,
294    /// Provider gear name the contract resolves against (diagnostics).
295    pub dep_gear: &'static str,
296    /// Wiring action: register the client into the hub; reports whether the
297    /// dependency was satisfied locally or bound to a remote client. See
298    /// [`WireFn`] for the argument roles.
299    pub wire: WireFn,
300}
301
302/// The wiring function pointer emitted by `#[toolkit::consumes]`: registers the
303/// client into the `ClientHub` from an endpoint resolver and a prepared
304/// [`ClientTuning`](toolkit_contract::wiring::ClientTuning) (the `clients.consumes`
305/// knobs plus the process's platform-plane credential source). Aliased to keep
306/// the fn-pointer type readable.
307pub type WireFn = fn(
308    &ClientHub,
309    Arc<dyn EndpointResolver>,
310    toolkit_contract::wiring::ClientTuning,
311) -> anyhow::Result<WireOutcome>;
312
313inventory::collect!(ConsumerRegistration);
314
315#[cfg(test)]
316#[cfg_attr(coverage_nightly, coverage(off))]
317mod tests {
318    use super::*;
319    use cf_system_sdks::directory::{RegisterInstanceInfo, ServiceEndpoint, ServiceInstanceInfo};
320    use std::sync::atomic::{AtomicUsize, Ordering};
321
322    /// Counts `resolve_rest_service` / `resolve_grpc_service` calls; all other
323    /// methods are unused here.
324    struct CountingDirectory {
325        calls: AtomicUsize,
326    }
327
328    #[async_trait]
329    impl DirectoryClient for CountingDirectory {
330        async fn resolve_grpc_service(&self, service: &str) -> anyhow::Result<ServiceEndpoint> {
331            self.calls.fetch_add(1, Ordering::SeqCst);
332            Ok(ServiceEndpoint::new(format!("http://grpc.local/{service}")))
333        }
334        async fn resolve_rest_service(&self, gear: &str) -> anyhow::Result<ServiceEndpoint> {
335            self.calls.fetch_add(1, Ordering::SeqCst);
336            Ok(ServiceEndpoint::new(format!("http://{gear}.local")))
337        }
338        async fn list_instances(&self, _: &str) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
339            unimplemented!()
340        }
341        async fn list_all_instances(&self) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
342            unimplemented!()
343        }
344        async fn register_instance(&self, _: RegisterInstanceInfo) -> anyhow::Result<()> {
345            unimplemented!()
346        }
347        async fn deregister_instance(&self, _: &str, _: &str) -> anyhow::Result<()> {
348            unimplemented!()
349        }
350        async fn send_heartbeat(&self, _: &str, _: &str) -> anyhow::Result<()> {
351            unimplemented!()
352        }
353    }
354
355    #[tokio::test]
356    async fn memoizes_successful_resolution_within_ttl() {
357        let dir = Arc::new(CountingDirectory {
358            calls: AtomicUsize::new(0),
359        });
360        let resolver = DirectoryEndpointResolver::new(dir.clone());
361
362        for _ in 0..3 {
363            let ep = resolver.resolve_endpoint("billing").await.unwrap();
364            assert_eq!(ep.as_deref(), Some("http://billing.local"));
365        }
366
367        assert_eq!(
368            dir.calls.load(Ordering::SeqCst),
369            1,
370            "successful resolution must be memoized within the TTL (one directory lookup)"
371        );
372    }
373
374    #[tokio::test]
375    async fn grpc_lookups_go_by_service_name_and_are_cached_apart() {
376        let dir = Arc::new(CountingDirectory {
377            calls: AtomicUsize::new(0),
378        });
379        let resolver = DirectoryEndpointResolver::new(dir.clone());
380
381        let grpc = resolver
382            .resolve_grpc_endpoint("billing.v1.BillingApi")
383            .await
384            .unwrap();
385        assert_eq!(
386            grpc.as_deref(),
387            Some("http://grpc.local/billing.v1.BillingApi")
388        );
389        let rest = resolver.resolve_endpoint("billing").await.unwrap();
390        assert_eq!(rest.as_deref(), Some("http://billing.local"));
391        resolver
392            .resolve_grpc_endpoint("billing.v1.BillingApi")
393            .await
394            .unwrap();
395
396        assert_eq!(dir.calls.load(Ordering::SeqCst), 2, "one lookup per target");
397    }
398
399    #[tokio::test]
400    async fn invalidate_drops_only_that_targets_answer() {
401        let dir = Arc::new(CountingDirectory {
402            calls: AtomicUsize::new(0),
403        });
404        let resolver = DirectoryEndpointResolver::new(dir.clone());
405        resolver.resolve_endpoint("billing").await.unwrap();
406        resolver
407            .resolve_grpc_endpoint("billing.v1.BillingApi")
408            .await
409            .unwrap();
410
411        resolver.invalidate(&ResolveTarget::grpc("billing", "billing.v1.BillingApi"));
412        resolver.resolve_endpoint("billing").await.unwrap();
413        resolver
414            .resolve_grpc_endpoint("billing.v1.BillingApi")
415            .await
416            .unwrap();
417
418        assert_eq!(
419            dir.calls.load(Ordering::SeqCst),
420            3,
421            "only the gRPC answer was looked up again"
422        );
423    }
424
425    #[tokio::test]
426    async fn the_static_resolver_can_pin_grpc_apart() {
427        let both = StaticEndpointResolver::new("http://svc:8080");
428        let split =
429            StaticEndpointResolver::new("http://svc:8080").with_grpc_endpoint("http://svc:50051");
430
431        assert_eq!(
432            both.resolve_grpc_endpoint("x.v1.X")
433                .await
434                .unwrap()
435                .as_deref(),
436            Some("http://svc:8080")
437        );
438        assert_eq!(
439            split
440                .resolve_grpc_endpoint("x.v1.X")
441                .await
442                .unwrap()
443                .as_deref(),
444            Some("http://svc:50051")
445        );
446        assert_eq!(
447            split.resolve_endpoint("svc").await.unwrap().as_deref(),
448            Some("http://svc:8080")
449        );
450    }
451
452    #[tokio::test]
453    async fn static_resolver_always_returns_fixed_endpoint() {
454        let resolver = StaticEndpointResolver::new("http://localhost:8081");
455        assert_eq!(
456            resolver
457                .resolve_endpoint("anything")
458                .await
459                .unwrap()
460                .as_deref(),
461            Some("http://localhost:8081")
462        );
463        assert_eq!(
464            resolver.resolve_endpoint("other").await.unwrap().as_deref(),
465            Some("http://localhost:8081")
466        );
467    }
468
469    #[tokio::test]
470    async fn null_resolver_never_resolves() {
471        assert_eq!(
472            NullEndpointResolver
473                .resolve_endpoint("billing")
474                .await
475                .unwrap(),
476            None
477        );
478    }
479
480    /// Answers every lookup with a caller-chosen failure, so the resolver's
481    /// two error branches can be told apart.
482    struct FailingDirectory {
483        make_error: fn(&str) -> anyhow::Error,
484    }
485
486    #[async_trait]
487    impl DirectoryClient for FailingDirectory {
488        async fn resolve_grpc_service(&self, _: &str) -> anyhow::Result<ServiceEndpoint> {
489            unimplemented!()
490        }
491        async fn resolve_rest_service(&self, gear: &str) -> anyhow::Result<ServiceEndpoint> {
492            Err((self.make_error)(gear))
493        }
494        async fn list_instances(&self, _: &str) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
495            unimplemented!()
496        }
497        async fn list_all_instances(&self) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
498            unimplemented!()
499        }
500        async fn register_instance(&self, _: RegisterInstanceInfo) -> anyhow::Result<()> {
501            unimplemented!()
502        }
503        async fn deregister_instance(&self, _: &str, _: &str) -> anyhow::Result<()> {
504            unimplemented!()
505        }
506        async fn send_heartbeat(&self, _: &str, _: &str) -> anyhow::Result<()> {
507            unimplemented!()
508        }
509    }
510
511    #[tokio::test]
512    async fn not_found_sentinel_resolves_to_ok_none() {
513        // "The provider has not registered yet" is a routine startup condition,
514        // not a failure: it must come back as `Ok(None)` so the readiness probe
515        // logs it at `debug` and the resolving client reports `Unresolved`
516        // rather than warning on every call.
517        let dir = Arc::new(FailingDirectory {
518            make_error: |gear| DirectoryNotFound::new(format!("gear {gear}")).into(),
519        });
520        let resolver = DirectoryEndpointResolver::new(dir);
521
522        assert_eq!(resolver.resolve_endpoint("billing").await.unwrap(), None);
523    }
524
525    #[tokio::test]
526    async fn backend_failure_resolves_to_err() {
527        // Anything that is not the sentinel is a genuine directory outage and
528        // must stay an error, so a stuck 503 has a diagnostic trail.
529        let dir = Arc::new(FailingDirectory {
530            make_error: |_| anyhow::anyhow!("connection refused"),
531        });
532        let resolver = DirectoryEndpointResolver::new(dir);
533
534        assert!(resolver.resolve_endpoint("billing").await.is_err());
535    }
536
537    #[tokio::test]
538    #[tracing_test::traced_test]
539    async fn invalid_argument_resolves_to_err_and_logs_config_error() {
540        // A malformed provider name is a permanent configuration error, handled
541        // by the dedicated arm. Unlike the not-found sentinel (`Ok(None)`), it
542        // must stay an `Err` so the call fails rather than being treated as a
543        // provider that is merely not ready yet. It must also be logged
544        // distinctly at `error` (a static configuration error) so it is not
545        // folded into the generic backend-failure path, which emits no log of
546        // its own at the resolver.
547        let dir = Arc::new(FailingDirectory {
548            make_error: |gear| DirectoryInvalidArgument::new(format!("bad name {gear}")).into(),
549        });
550        let resolver = DirectoryEndpointResolver::new(dir);
551
552        assert!(resolver.resolve_endpoint("Bad Name").await.is_err());
553
554        logs_assert(|lines: &[&str]| {
555            match lines
556                .iter()
557                .find(|line| line.contains("permanently rejected by the directory"))
558            {
559                Some(line) if line.contains("ERROR") => Ok(()),
560                Some(_) => Err("invalid-argument arm logged at the wrong level".to_owned()),
561                None => {
562                    Err("invalid-argument arm must emit a distinct config-error log".to_owned())
563                }
564            }
565        });
566    }
567
568    /// Mirrors the body `#[toolkit::consumes]` generates, so the wiring
569    /// contract is exercised without going through `inventory` (which is
570    /// link-time global and cannot hold two registrations built by a test).
571    fn generated_wire_body<C>(hub: &ClientHub, proxy: Arc<C>) -> anyhow::Result<WireOutcome>
572    where
573        C: ?Sized + Send + Sync + 'static,
574    {
575        if hub.try_get_local::<C>().is_some() {
576            return Ok(WireOutcome::Local);
577        }
578        if hub.has_remote_proxy::<C>() {
579            if let Some(owner) = hub.owner() {
580                anyhow::bail!("gear `{owner}` declares #[toolkit::consumes] more than once");
581            }
582            return Ok(WireOutcome::Remote);
583        }
584        hub.register_remote_proxy::<C>(proxy);
585        Ok(WireOutcome::Remote)
586    }
587
588    trait Payments: Send + Sync {}
589    struct PaymentsProxy;
590    impl Payments for PaymentsProxy {}
591    struct PaymentsLocal;
592    impl Payments for PaymentsLocal {}
593
594    #[test]
595    fn two_consumers_of_one_contract_get_their_own_proxies() {
596        // Two gears in one process consuming the same contract from the same
597        // provider. Each must get its own proxy (built from its own wiring
598        // settings), and neither may short-circuit to `Local`, which would mark
599        // the dependency readiness-resolved with no provider up.
600        let hub = ClientHub::new();
601        let a = hub.for_gear("a");
602        let b = hub.for_gear("b");
603
604        let first = generated_wire_body::<dyn Payments>(&a, Arc::new(PaymentsProxy)).unwrap();
605        let second = generated_wire_body::<dyn Payments>(&b, Arc::new(PaymentsProxy)).unwrap();
606
607        assert_eq!(first, WireOutcome::Remote);
608        assert_eq!(
609            second,
610            WireOutcome::Remote,
611            "the second consumer must still gate readiness, not short-circuit to Local"
612        );
613        assert!(!Arc::ptr_eq(
614            &a.get::<dyn Payments>().unwrap(),
615            &b.get::<dyn Payments>().unwrap()
616        ));
617    }
618
619    #[test]
620    fn a_gear_consuming_one_contract_twice_is_an_error() {
621        let hub = ClientHub::new();
622        let a = hub.for_gear("a");
623
624        generated_wire_body::<dyn Payments>(&a, Arc::new(PaymentsProxy)).unwrap();
625        let err = generated_wire_body::<dyn Payments>(&a, Arc::new(PaymentsProxy)).unwrap_err();
626
627        assert!(err.to_string().contains("more than once"), "{err}");
628    }
629
630    #[test]
631    fn the_process_wide_hub_reuses_its_proxy() {
632        // Registrations whose owner is not a gear here (cluster-sdk's) wire into
633        // the plain hub and share one proxy.
634        let hub = ClientHub::new();
635
636        let first = generated_wire_body::<dyn Payments>(&hub, Arc::new(PaymentsProxy)).unwrap();
637        let second = generated_wire_body::<dyn Payments>(&hub, Arc::new(PaymentsProxy)).unwrap();
638
639        assert_eq!((first, second), (WireOutcome::Remote, WireOutcome::Remote));
640    }
641
642    #[test]
643    fn a_genuine_local_impl_still_wins() {
644        // The short-circuit must keep working for its actual purpose: a
645        // co-located provider registered during init means no HTTP hop and no
646        // readiness gate.
647        let hub = ClientHub::new();
648        hub.register::<dyn Payments>(Arc::new(PaymentsLocal));
649
650        let outcome = generated_wire_body::<dyn Payments>(&hub, Arc::new(PaymentsProxy)).unwrap();
651
652        assert_eq!(outcome, WireOutcome::Local);
653    }
654
655    #[tokio::test]
656    async fn typed_not_found_reaches_the_resolver_as_ok_none() {
657        let dir = Arc::new(crate::directory::test_support::ManagerDirectoryClient::new(
658            Arc::new(crate::runtime::GearManager::new()),
659        ));
660        let resolver = DirectoryEndpointResolver::new(dir);
661
662        assert_eq!(
663            resolver.resolve_endpoint("never-registered").await.unwrap(),
664            None
665        );
666    }
667}