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 get_openapi_spec(&self, _: &str) -> anyhow::Result<String> {
339            unimplemented!()
340        }
341        async fn list_instances(&self, _: &str) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
342            unimplemented!()
343        }
344        async fn list_all_instances(&self) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
345            unimplemented!()
346        }
347        async fn register_instance(&self, _: RegisterInstanceInfo) -> anyhow::Result<()> {
348            unimplemented!()
349        }
350        async fn deregister_instance(&self, _: &str, _: &str) -> anyhow::Result<()> {
351            unimplemented!()
352        }
353        async fn send_heartbeat(&self, _: &str, _: &str) -> anyhow::Result<()> {
354            unimplemented!()
355        }
356    }
357
358    #[tokio::test]
359    async fn memoizes_successful_resolution_within_ttl() {
360        let dir = Arc::new(CountingDirectory {
361            calls: AtomicUsize::new(0),
362        });
363        let resolver = DirectoryEndpointResolver::new(dir.clone());
364
365        for _ in 0..3 {
366            let ep = resolver.resolve_endpoint("billing").await.unwrap();
367            assert_eq!(ep.as_deref(), Some("http://billing.local"));
368        }
369
370        assert_eq!(
371            dir.calls.load(Ordering::SeqCst),
372            1,
373            "successful resolution must be memoized within the TTL (one directory lookup)"
374        );
375    }
376
377    #[tokio::test]
378    async fn grpc_lookups_go_by_service_name_and_are_cached_apart() {
379        let dir = Arc::new(CountingDirectory {
380            calls: AtomicUsize::new(0),
381        });
382        let resolver = DirectoryEndpointResolver::new(dir.clone());
383
384        let grpc = resolver
385            .resolve_grpc_endpoint("billing.v1.BillingApi")
386            .await
387            .unwrap();
388        assert_eq!(
389            grpc.as_deref(),
390            Some("http://grpc.local/billing.v1.BillingApi")
391        );
392        let rest = resolver.resolve_endpoint("billing").await.unwrap();
393        assert_eq!(rest.as_deref(), Some("http://billing.local"));
394        resolver
395            .resolve_grpc_endpoint("billing.v1.BillingApi")
396            .await
397            .unwrap();
398
399        assert_eq!(dir.calls.load(Ordering::SeqCst), 2, "one lookup per target");
400    }
401
402    #[tokio::test]
403    async fn invalidate_drops_only_that_targets_answer() {
404        let dir = Arc::new(CountingDirectory {
405            calls: AtomicUsize::new(0),
406        });
407        let resolver = DirectoryEndpointResolver::new(dir.clone());
408        resolver.resolve_endpoint("billing").await.unwrap();
409        resolver
410            .resolve_grpc_endpoint("billing.v1.BillingApi")
411            .await
412            .unwrap();
413
414        resolver.invalidate(&ResolveTarget::grpc("billing", "billing.v1.BillingApi"));
415        resolver.resolve_endpoint("billing").await.unwrap();
416        resolver
417            .resolve_grpc_endpoint("billing.v1.BillingApi")
418            .await
419            .unwrap();
420
421        assert_eq!(
422            dir.calls.load(Ordering::SeqCst),
423            3,
424            "only the gRPC answer was looked up again"
425        );
426    }
427
428    #[tokio::test]
429    async fn the_static_resolver_can_pin_grpc_apart() {
430        let both = StaticEndpointResolver::new("http://svc:8080");
431        let split =
432            StaticEndpointResolver::new("http://svc:8080").with_grpc_endpoint("http://svc:50051");
433
434        assert_eq!(
435            both.resolve_grpc_endpoint("x.v1.X")
436                .await
437                .unwrap()
438                .as_deref(),
439            Some("http://svc:8080")
440        );
441        assert_eq!(
442            split
443                .resolve_grpc_endpoint("x.v1.X")
444                .await
445                .unwrap()
446                .as_deref(),
447            Some("http://svc:50051")
448        );
449        assert_eq!(
450            split.resolve_endpoint("svc").await.unwrap().as_deref(),
451            Some("http://svc:8080")
452        );
453    }
454
455    #[tokio::test]
456    async fn static_resolver_always_returns_fixed_endpoint() {
457        let resolver = StaticEndpointResolver::new("http://localhost:8081");
458        assert_eq!(
459            resolver
460                .resolve_endpoint("anything")
461                .await
462                .unwrap()
463                .as_deref(),
464            Some("http://localhost:8081")
465        );
466        assert_eq!(
467            resolver.resolve_endpoint("other").await.unwrap().as_deref(),
468            Some("http://localhost:8081")
469        );
470    }
471
472    #[tokio::test]
473    async fn null_resolver_never_resolves() {
474        assert_eq!(
475            NullEndpointResolver
476                .resolve_endpoint("billing")
477                .await
478                .unwrap(),
479            None
480        );
481    }
482
483    /// Answers every lookup with a caller-chosen failure, so the resolver's
484    /// two error branches can be told apart.
485    struct FailingDirectory {
486        make_error: fn(&str) -> anyhow::Error,
487    }
488
489    #[async_trait]
490    impl DirectoryClient for FailingDirectory {
491        async fn resolve_grpc_service(&self, _: &str) -> anyhow::Result<ServiceEndpoint> {
492            unimplemented!()
493        }
494        async fn resolve_rest_service(&self, gear: &str) -> anyhow::Result<ServiceEndpoint> {
495            Err((self.make_error)(gear))
496        }
497        async fn get_openapi_spec(&self, _: &str) -> anyhow::Result<String> {
498            unimplemented!()
499        }
500        async fn list_instances(&self, _: &str) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
501            unimplemented!()
502        }
503        async fn list_all_instances(&self) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
504            unimplemented!()
505        }
506        async fn register_instance(&self, _: RegisterInstanceInfo) -> anyhow::Result<()> {
507            unimplemented!()
508        }
509        async fn deregister_instance(&self, _: &str, _: &str) -> anyhow::Result<()> {
510            unimplemented!()
511        }
512        async fn send_heartbeat(&self, _: &str, _: &str) -> anyhow::Result<()> {
513            unimplemented!()
514        }
515    }
516
517    #[tokio::test]
518    async fn not_found_sentinel_resolves_to_ok_none() {
519        // "The provider has not registered yet" is a routine startup condition,
520        // not a failure: it must come back as `Ok(None)` so the readiness probe
521        // logs it at `debug` and the resolving client reports `Unresolved`
522        // rather than warning on every call.
523        let dir = Arc::new(FailingDirectory {
524            make_error: |gear| DirectoryNotFound::new(format!("gear {gear}")).into(),
525        });
526        let resolver = DirectoryEndpointResolver::new(dir);
527
528        assert_eq!(resolver.resolve_endpoint("billing").await.unwrap(), None);
529    }
530
531    #[tokio::test]
532    async fn backend_failure_resolves_to_err() {
533        // Anything that is not the sentinel is a genuine directory outage and
534        // must stay an error, so a stuck 503 has a diagnostic trail.
535        let dir = Arc::new(FailingDirectory {
536            make_error: |_| anyhow::anyhow!("connection refused"),
537        });
538        let resolver = DirectoryEndpointResolver::new(dir);
539
540        assert!(resolver.resolve_endpoint("billing").await.is_err());
541    }
542
543    #[tokio::test]
544    #[tracing_test::traced_test]
545    async fn invalid_argument_resolves_to_err_and_logs_config_error() {
546        // A malformed provider name is a permanent configuration error, handled
547        // by the dedicated arm. Unlike the not-found sentinel (`Ok(None)`), it
548        // must stay an `Err` so the call fails rather than being treated as a
549        // provider that is merely not ready yet. It must also be logged
550        // distinctly at `error` (a static configuration error) so it is not
551        // folded into the generic backend-failure path, which emits no log of
552        // its own at the resolver.
553        let dir = Arc::new(FailingDirectory {
554            make_error: |gear| DirectoryInvalidArgument::new(format!("bad name {gear}")).into(),
555        });
556        let resolver = DirectoryEndpointResolver::new(dir);
557
558        assert!(resolver.resolve_endpoint("Bad Name").await.is_err());
559
560        logs_assert(|lines: &[&str]| {
561            match lines
562                .iter()
563                .find(|line| line.contains("permanently rejected by the directory"))
564            {
565                Some(line) if line.contains("ERROR") => Ok(()),
566                Some(_) => Err("invalid-argument arm logged at the wrong level".to_owned()),
567                None => {
568                    Err("invalid-argument arm must emit a distinct config-error log".to_owned())
569                }
570            }
571        });
572    }
573
574    /// Mirrors the body `#[toolkit::consumes]` generates, so the wiring
575    /// contract is exercised without going through `inventory` (which is
576    /// link-time global and cannot hold two registrations built by a test).
577    fn generated_wire_body<C>(hub: &ClientHub, proxy: Arc<C>) -> anyhow::Result<WireOutcome>
578    where
579        C: ?Sized + Send + Sync + 'static,
580    {
581        if hub.try_get_local::<C>().is_some() {
582            return Ok(WireOutcome::Local);
583        }
584        if hub.has_remote_proxy::<C>() {
585            if let Some(owner) = hub.owner() {
586                anyhow::bail!("gear `{owner}` declares #[toolkit::consumes] more than once");
587            }
588            return Ok(WireOutcome::Remote);
589        }
590        hub.register_remote_proxy::<C>(proxy);
591        Ok(WireOutcome::Remote)
592    }
593
594    trait Payments: Send + Sync {}
595    struct PaymentsProxy;
596    impl Payments for PaymentsProxy {}
597    struct PaymentsLocal;
598    impl Payments for PaymentsLocal {}
599
600    #[test]
601    fn two_consumers_of_one_contract_get_their_own_proxies() {
602        // Two gears in one process consuming the same contract from the same
603        // provider. Each must get its own proxy (built from its own wiring
604        // settings), and neither may short-circuit to `Local`, which would mark
605        // the dependency readiness-resolved with no provider up.
606        let hub = ClientHub::new();
607        let a = hub.for_gear("a");
608        let b = hub.for_gear("b");
609
610        let first = generated_wire_body::<dyn Payments>(&a, Arc::new(PaymentsProxy)).unwrap();
611        let second = generated_wire_body::<dyn Payments>(&b, Arc::new(PaymentsProxy)).unwrap();
612
613        assert_eq!(first, WireOutcome::Remote);
614        assert_eq!(
615            second,
616            WireOutcome::Remote,
617            "the second consumer must still gate readiness, not short-circuit to Local"
618        );
619        assert!(!Arc::ptr_eq(
620            &a.get::<dyn Payments>().unwrap(),
621            &b.get::<dyn Payments>().unwrap()
622        ));
623    }
624
625    #[test]
626    fn a_gear_consuming_one_contract_twice_is_an_error() {
627        let hub = ClientHub::new();
628        let a = hub.for_gear("a");
629
630        generated_wire_body::<dyn Payments>(&a, Arc::new(PaymentsProxy)).unwrap();
631        let err = generated_wire_body::<dyn Payments>(&a, Arc::new(PaymentsProxy)).unwrap_err();
632
633        assert!(err.to_string().contains("more than once"), "{err}");
634    }
635
636    #[test]
637    fn the_process_wide_hub_reuses_its_proxy() {
638        // Registrations whose owner is not a gear here (cluster-sdk's) wire into
639        // the plain hub and share one proxy.
640        let hub = ClientHub::new();
641
642        let first = generated_wire_body::<dyn Payments>(&hub, Arc::new(PaymentsProxy)).unwrap();
643        let second = generated_wire_body::<dyn Payments>(&hub, Arc::new(PaymentsProxy)).unwrap();
644
645        assert_eq!((first, second), (WireOutcome::Remote, WireOutcome::Remote));
646    }
647
648    #[test]
649    fn a_genuine_local_impl_still_wins() {
650        // The short-circuit must keep working for its actual purpose: a
651        // co-located provider registered during init means no HTTP hop and no
652        // readiness gate.
653        let hub = ClientHub::new();
654        hub.register::<dyn Payments>(Arc::new(PaymentsLocal));
655
656        let outcome = generated_wire_body::<dyn Payments>(&hub, Arc::new(PaymentsProxy)).unwrap();
657
658        assert_eq!(outcome, WireOutcome::Local);
659    }
660
661    #[tokio::test]
662    async fn local_directory_client_not_found_reaches_the_resolver_as_ok_none() {
663        // End-to-end over the real in-process client rather than a stub: this
664        // is the pairing that was broken (the client returned a bare `anyhow`,
665        // so the resolver could never produce `Ok(None)`).
666        let dir = Arc::new(crate::directory::LocalDirectoryClient::new(Arc::new(
667            crate::runtime::GearManager::new(),
668        )));
669        let resolver = DirectoryEndpointResolver::new(dir);
670
671        assert_eq!(
672            resolver.resolve_endpoint("never-registered").await.unwrap(),
673            None
674        );
675    }
676}