Skip to main content

toolkit/
client_hub.rs

1//! Minimalistic, type-safe `ClientHub`.
2//!
3//! Design goals:
4//! - Providers register an implementation once (local or remote).
5//! - Consumers fetch by *interface type* (trait object): `get::<dyn my::Api>()`.
6//! - For plugin-like scenarios, multiple implementations of the same interface can coexist
7//!   under different scopes (e.g. selected by GTS instance ID).
8//! - Remote proxies wired by `#[toolkit::consumes]` belong to the consuming gear: each gear
9//!   reads the hub through its own view ([`ClientHub::for_gear`]) and gets its own proxy.
10//!
11//! Implementation details:
12//! - Key = type name. We use `type_name::<T>()`, which works for `T = dyn Trait`.
13//! - Value = `Arc<T>` stored as `Box<dyn Any + Send + Sync>` (downcast on read).
14//! - Sync hot path: `get()` is non-async; no hidden per-entry cells or lazy slots.
15//!
16//! Notes:
17//! - Re-registering overwrites the previous value atomically; existing Arcs held by consumers remain valid.
18//! - For testing, just register a mock under the same trait type.
19
20use parking_lot::RwLock;
21use std::{any::Any, collections::HashMap, fmt, sync::Arc};
22
23/// Stable type key for trait objects — uses fully-qualified `type_name::<T>()`.
24#[derive(Clone, Eq, PartialEq, Hash)]
25pub struct TypeKey(&'static str);
26
27impl TypeKey {
28    #[inline]
29    fn of<T: ?Sized + 'static>() -> Self {
30        TypeKey(std::any::type_name::<T>())
31    }
32}
33
34impl fmt::Debug for TypeKey {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        f.write_str(self.0)
37    }
38}
39
40/// A scope for resolving multiple implementations of the same interface type.
41///
42/// This is intentionally opaque: the scope semantics are defined by the caller.
43/// One common scope is a full GTS entity/instance ID.
44#[derive(Clone, Eq, PartialEq, Hash)]
45pub struct ClientScope(Arc<str>);
46
47impl ClientScope {
48    /// Create a new scope from an arbitrary string.
49    #[inline]
50    #[must_use]
51    pub fn new(scope: impl Into<Arc<str>>) -> Self {
52        Self(scope.into())
53    }
54
55    /// Create a scope derived from a GTS identifier.
56    ///
57    /// Internally we prefix the scope to avoid accidental collisions with other scope kinds.
58    #[must_use]
59    pub fn gts_id(gts_id: &str) -> Self {
60        let mut s = String::with_capacity("gts:".len() + gts_id.len());
61        s.push_str("gts:");
62        s.push_str(gts_id);
63        Self(Arc::<str>::from(s))
64    }
65
66    #[inline]
67    #[must_use]
68    pub fn as_str(&self) -> &str {
69        &self.0
70    }
71}
72
73impl fmt::Debug for ClientScope {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.write_str(self.as_str())
76    }
77}
78
79#[derive(Clone, Eq, PartialEq, Hash)]
80struct ScopedKey {
81    type_key: TypeKey,
82    scope: ClientScope,
83}
84
85impl fmt::Debug for ScopedKey {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        f.debug_struct("ScopedKey")
88            .field("type_key", &self.type_key)
89            .field("scope", &self.scope)
90            .finish()
91    }
92}
93
94#[derive(Debug, thiserror::Error)]
95pub enum ClientHubError {
96    #[error("client not found: type={type_key:?}")]
97    NotFound { type_key: TypeKey },
98
99    #[error("type mismatch in hub for type={type_key:?}")]
100    TypeMismatch { type_key: TypeKey },
101
102    #[error("scoped client not found: type={type_key:?} scope={scope:?}")]
103    ScopedNotFound {
104        type_key: TypeKey,
105        scope: ClientScope,
106    },
107
108    #[error("type mismatch in hub for type={type_key:?} scope={scope:?}")]
109    ScopedTypeMismatch {
110        type_key: TypeKey,
111        scope: ClientScope,
112    },
113}
114
115type Boxed = Box<dyn Any + Send + Sync>;
116
117/// Internal map type for the client hub.
118type ClientMap = HashMap<TypeKey, Boxed>;
119
120/// Internal map type for the scoped client hub.
121type ScopedClientMap = HashMap<ScopedKey, Boxed>;
122
123/// Key of a consumer-wiring proxy: the contract type and the gear that owns
124/// the proxy. `owner = None` is a process-wide proxy.
125#[derive(Clone, Eq, PartialEq, Hash, Debug)]
126struct ProxyKey {
127    type_key: TypeKey,
128    owner: Option<Arc<str>>,
129}
130
131/// Registrations shared by every view of one hub.
132#[derive(Default)]
133struct Storage {
134    map: RwLock<ClientMap>,
135    scoped_map: RwLock<ScopedClientMap>,
136    /// Discovery-resolving proxies registered by consumer wiring, kept apart
137    /// from `map` so a proxy is never mistaken for an in-process impl.
138    ///
139    /// Keyed by owner because each consumer wires the contract with its own
140    /// `clients.consumes.<dep>` settings (endpoint, timeout, retry, TLS). One
141    /// proxy per contract would hand every consumer the settings of whichever
142    /// wired first.
143    proxies: RwLock<HashMap<ProxyKey, Boxed>>,
144}
145
146/// Type-safe registry of clients keyed by interface type.
147///
148/// A hub is shared storage plus an optional owner gear. [`Self::for_gear`]
149/// returns a view of the same storage owned by a gear; `GearCtx::client_hub`
150/// hands each gear its own view. Plain and scoped registrations are shared by
151/// all views. Remote proxies registered through a view belong to its owner.
152#[derive(Default)]
153pub struct ClientHub {
154    storage: Arc<Storage>,
155    owner: Option<Arc<str>>,
156}
157
158impl ClientHub {
159    #[inline]
160    #[must_use]
161    pub fn new() -> Self {
162        Self::default()
163    }
164
165    /// A view of this hub's storage owned by `gear`.
166    ///
167    /// Local and scoped registrations are shared with every other view. A
168    /// remote proxy registered through the view is seen only by this view and
169    /// does not replace another gear's proxy for the same contract.
170    #[must_use]
171    pub fn for_gear(&self, gear: impl Into<Arc<str>>) -> Arc<Self> {
172        Arc::new(Self {
173            storage: Arc::clone(&self.storage),
174            owner: Some(gear.into()),
175        })
176    }
177
178    /// The gear that owns this view, or `None` for the process-wide hub.
179    #[must_use]
180    pub fn owner(&self) -> Option<&str> {
181        self.owner.as_deref()
182    }
183
184    fn proxy_key<T: ?Sized + 'static>(&self) -> ProxyKey {
185        ProxyKey {
186            type_key: TypeKey::of::<T>(),
187            owner: self.owner.clone(),
188        }
189    }
190
191    /// Local impl first, then this owner's proxy, then the process-wide proxy.
192    fn lookup<T>(&self) -> Result<Arc<T>, ClientHubError>
193    where
194        T: ?Sized + Send + Sync + 'static,
195    {
196        let type_key = TypeKey::of::<T>();
197        let downcast = |boxed: &Boxed| {
198            boxed
199                .downcast_ref::<Arc<T>>()
200                .cloned()
201                .ok_or_else(|| ClientHubError::TypeMismatch {
202                    type_key: type_key.clone(),
203                })
204        };
205        if let Some(boxed) = self.storage.map.read().get(&type_key) {
206            return downcast(boxed);
207        }
208        let proxies = self.storage.proxies.read();
209        let mut key = ProxyKey {
210            type_key: type_key.clone(),
211            owner: self.owner.clone(),
212        };
213        if key.owner.is_some()
214            && let Some(boxed) = proxies.get(&key)
215        {
216            return downcast(boxed);
217        }
218        key.owner = None;
219        match proxies.get(&key) {
220            Some(boxed) => downcast(boxed),
221            None => Err(ClientHubError::NotFound { type_key }),
222        }
223    }
224}
225
226impl ClientHub {
227    /// Register a client under the interface type `T`.
228    /// `T` can be a trait object like `dyn my_gear::api::MyClient`.
229    ///
230    /// The registration is shared by every view and wins over any remote
231    /// proxy for `T` in [`Self::get`], also when it is registered after one.
232    pub fn register<T>(&self, client: Arc<T>)
233    where
234        T: ?Sized + Send + Sync + 'static,
235    {
236        let mut w = self.storage.map.write();
237        w.insert(TypeKey::of::<T>(), Box::new(client));
238    }
239
240    /// Register a scoped client under the interface type `T`.
241    ///
242    /// This enables multiple implementations of the same interface to coexist,
243    /// distinguished by a caller-defined `ClientScope` (e.g., a GTS instance ID).
244    pub fn register_scoped<T>(&self, scope: ClientScope, client: Arc<T>)
245    where
246        T: ?Sized + Send + Sync + 'static,
247    {
248        let key = ScopedKey {
249            type_key: TypeKey::of::<T>(),
250            scope,
251        };
252        let mut w = self.storage.scoped_map.write();
253        w.insert(key, Box::new(client));
254    }
255
256    /// Fetch a client by interface type `T`.
257    ///
258    /// Returns, in order: a local registration, this view's remote proxy, a
259    /// process-wide remote proxy.
260    ///
261    /// # Errors
262    /// Returns `ClientHubError::NotFound` if no client is registered for the type.
263    /// Returns `ClientHubError::TypeMismatch` if the stored type doesn't match.
264    pub fn get<T>(&self) -> Result<Arc<T>, ClientHubError>
265    where
266        T: ?Sized + Send + Sync + 'static,
267    {
268        self.lookup::<T>()
269    }
270
271    /// Try to fetch a client by interface type `T`.
272    ///
273    /// Same lookup order as [`Self::get`]; returns `None` if nothing is
274    /// registered or the stored type doesn't match. Use [`Self::try_get_local`]
275    /// when the answer needs to mean "satisfied in-process".
276    #[must_use]
277    pub fn try_get<T>(&self) -> Option<Arc<T>>
278    where
279        T: ?Sized + Send + Sync + 'static,
280    {
281        self.lookup::<T>().ok()
282    }
283
284    /// Register a client that is a discovery-resolving proxy to a *remote*
285    /// provider, not an in-process implementation.
286    ///
287    /// The proxy belongs to this view's owner, or is process-wide when the hub
288    /// has no owner. It never hides a local registration of `T`.
289    pub fn register_remote_proxy<T>(&self, client: Arc<T>)
290    where
291        T: ?Sized + Send + Sync + 'static,
292    {
293        let key = self.proxy_key::<T>();
294        self.storage.proxies.write().insert(key, Box::new(client));
295    }
296
297    /// Try to fetch a client by interface type `T`, ignoring remote proxies.
298    ///
299    /// This is the short-circuit probe for consumer wiring: a compile-time
300    /// (local) registration takes priority over a discovery-based proxy, so the
301    /// wiring closure asks whether a *local* implementation exists before
302    /// registering one of its own. Seeing a proxy here would let a consumer
303    /// report its dependency as local and turn `/readyz` green before the
304    /// provider exists.
305    #[must_use]
306    pub fn try_get_local<T>(&self) -> Option<Arc<T>>
307    where
308        T: ?Sized + Send + Sync + 'static,
309    {
310        let r = self.storage.map.read();
311        let boxed = r.get(&TypeKey::of::<T>())?;
312        boxed.downcast_ref::<Arc<T>>().cloned()
313    }
314
315    /// Whether this view already holds a remote proxy for interface type `T`:
316    /// its owner's proxy, or the process-wide one for a hub without an owner.
317    ///
318    /// Another gear's proxy does not count, so each consumer builds a proxy
319    /// from its own wiring settings.
320    #[must_use]
321    pub fn has_remote_proxy<T>(&self) -> bool
322    where
323        T: ?Sized + Send + Sync + 'static,
324    {
325        self.storage
326            .proxies
327            .read()
328            .contains_key(&self.proxy_key::<T>())
329    }
330    /// Fetch a scoped client by interface type `T` and scope.
331    ///
332    /// # Errors
333    /// Returns `ClientHubError::ScopedNotFound` if no client is registered for the `(type, scope)` pair.
334    /// Returns `ClientHubError::ScopedTypeMismatch` if the stored type doesn't match.
335    pub fn get_scoped<T>(&self, scope: &ClientScope) -> Result<Arc<T>, ClientHubError>
336    where
337        T: ?Sized + Send + Sync + 'static,
338    {
339        let key = ScopedKey {
340            type_key: TypeKey::of::<T>(),
341            scope: scope.clone(),
342        };
343        let r = self.storage.scoped_map.read();
344
345        let boxed = r.get(&key).ok_or_else(|| ClientHubError::ScopedNotFound {
346            type_key: key.type_key.clone(),
347            scope: key.scope.clone(),
348        })?;
349
350        if let Some(arc_t) = boxed.downcast_ref::<Arc<T>>() {
351            return Ok(arc_t.clone());
352        }
353        Err(ClientHubError::ScopedTypeMismatch {
354            type_key: key.type_key,
355            scope: key.scope,
356        })
357    }
358
359    /// Try to fetch a scoped client by interface type `T` and scope.
360    ///
361    /// Returns `None` if not found or if the stored type doesn't match.
362    #[must_use]
363    pub fn try_get_scoped<T>(&self, scope: &ClientScope) -> Option<Arc<T>>
364    where
365        T: ?Sized + Send + Sync + 'static,
366    {
367        let key = ScopedKey {
368            type_key: TypeKey::of::<T>(),
369            scope: scope.clone(),
370        };
371        let r = self.storage.scoped_map.read();
372        let boxed = r.get(&key)?;
373
374        boxed.downcast_ref::<Arc<T>>().cloned()
375    }
376
377    /// Remove a local client by interface type; returns the removed client if
378    /// it was present. Remote proxies are not touched.
379    #[expect(
380        clippy::must_use_candidate,
381        reason = "callers remove for the side effect and may drop the client"
382    )]
383    pub fn remove<T>(&self) -> Option<Arc<T>>
384    where
385        T: ?Sized + Send + Sync + 'static,
386    {
387        let type_key = TypeKey::of::<T>();
388        let mut w = self.storage.map.write();
389        let boxed = w.remove(&type_key)?;
390        boxed.downcast::<Arc<T>>().ok().map(|b| *b)
391    }
392
393    /// Remove a scoped client by interface type + scope; returns the removed client if it was present.
394    #[expect(
395        clippy::must_use_candidate,
396        reason = "callers remove for the side effect and may drop the client"
397    )]
398    pub fn remove_scoped<T>(&self, scope: &ClientScope) -> Option<Arc<T>>
399    where
400        T: ?Sized + Send + Sync + 'static,
401    {
402        let key = ScopedKey {
403            type_key: TypeKey::of::<T>(),
404            scope: scope.clone(),
405        };
406        let mut w = self.storage.scoped_map.write();
407        let boxed = w.remove(&key)?;
408        boxed.downcast::<Arc<T>>().ok().map(|b| *b)
409    }
410
411    /// Clear everything (useful in tests).
412    pub fn clear(&self) {
413        self.storage.map.write().clear();
414        self.storage.scoped_map.write().clear();
415        self.storage.proxies.write().clear();
416    }
417
418    /// Introspection: (total entries).
419    #[must_use]
420    pub fn len(&self) -> usize {
421        self.storage.map.read().len()
422            + self.storage.scoped_map.read().len()
423            + self.storage.proxies.read().len()
424    }
425
426    /// Check if the hub is empty.
427    #[must_use]
428    pub fn is_empty(&self) -> bool {
429        self.storage.map.read().is_empty()
430            && self.storage.scoped_map.read().is_empty()
431            && self.storage.proxies.read().is_empty()
432    }
433}
434
435#[cfg(test)]
436#[cfg_attr(coverage_nightly, coverage(off))]
437mod tests {
438    use super::*;
439    use toolkit_gts::gts_id;
440
441    #[async_trait::async_trait]
442    trait TestApi: Send + Sync {
443        async fn id(&self) -> usize;
444    }
445
446    struct ImplA(usize);
447    #[async_trait::async_trait]
448    impl TestApi for ImplA {
449        async fn id(&self) -> usize {
450            self.0
451        }
452    }
453
454    #[tokio::test]
455    async fn register_and_get_dyn_trait() {
456        let hub = ClientHub::new();
457        let api: Arc<dyn TestApi> = Arc::new(ImplA(7));
458        hub.register::<dyn TestApi>(api.clone());
459
460        let got = hub.get::<dyn TestApi>().unwrap();
461        assert_eq!(got.id().await, 7);
462        assert_eq!(Arc::as_ptr(&api), Arc::as_ptr(&got));
463    }
464
465    #[tokio::test]
466    async fn remove_works() {
467        let hub = ClientHub::new();
468        let api: Arc<dyn TestApi> = Arc::new(ImplA(42));
469        hub.register::<dyn TestApi>(api);
470
471        assert!(hub.get::<dyn TestApi>().is_ok());
472
473        let removed = hub.remove::<dyn TestApi>();
474        assert!(removed.is_some());
475        assert!(hub.get::<dyn TestApi>().is_err());
476    }
477
478    #[tokio::test]
479    async fn try_get_local_ignores_a_remote_proxy() {
480        let hub = ClientHub::new();
481        let proxy: Arc<dyn TestApi> = Arc::new(ImplA(1));
482        hub.register_remote_proxy::<dyn TestApi>(proxy);
483
484        // Reachable for business calls...
485        assert!(hub.try_get::<dyn TestApi>().is_some());
486        assert!(hub.get::<dyn TestApi>().is_ok());
487        // ...but not a local implementation. This is what stops a second
488        // consumer of the same contract from reporting `WireOutcome::Local`
489        // and marking the dependency readiness-resolved while the provider is
490        // still absent.
491        assert!(hub.try_get_local::<dyn TestApi>().is_none());
492        assert!(hub.has_remote_proxy::<dyn TestApi>());
493    }
494
495    #[tokio::test]
496    async fn try_get_local_sees_a_plain_registration() {
497        let hub = ClientHub::new();
498        let local: Arc<dyn TestApi> = Arc::new(ImplA(2));
499        hub.register::<dyn TestApi>(local);
500
501        assert!(hub.try_get_local::<dyn TestApi>().is_some());
502        assert!(!hub.has_remote_proxy::<dyn TestApi>());
503    }
504
505    #[tokio::test]
506    async fn a_late_local_registration_wins_over_the_proxy() {
507        // A consumer wires a directory proxy under the contract first...
508        let hub = ClientHub::new();
509        let view = hub.for_gear("orders");
510        view.register_remote_proxy::<dyn TestApi>(Arc::new(ImplA(1)));
511        assert!(view.try_get_local::<dyn TestApi>().is_none());
512
513        // ...then the real in-process provider registers its local impl. It must
514        // win in every view, the proxy owner's included.
515        hub.register::<dyn TestApi>(Arc::new(ImplA(2)));
516        let local = view
517            .try_get_local::<dyn TestApi>()
518            .expect("the late local registration must be visible as local");
519        assert_eq!(local.id().await, 2);
520        assert_eq!(view.get::<dyn TestApi>().unwrap().id().await, 2);
521    }
522
523    #[tokio::test]
524    async fn each_gear_gets_its_own_proxy() {
525        let hub = ClientHub::new();
526        let a = hub.for_gear("a");
527        let b = hub.for_gear("b");
528        a.register_remote_proxy::<dyn TestApi>(Arc::new(ImplA(1)));
529
530        assert!(a.has_remote_proxy::<dyn TestApi>());
531        assert!(!b.has_remote_proxy::<dyn TestApi>());
532        assert!(b.try_get::<dyn TestApi>().is_none());
533        assert!(hub.try_get::<dyn TestApi>().is_none());
534
535        b.register_remote_proxy::<dyn TestApi>(Arc::new(ImplA(2)));
536        assert_eq!(a.get::<dyn TestApi>().unwrap().id().await, 1);
537        assert_eq!(b.get::<dyn TestApi>().unwrap().id().await, 2);
538    }
539
540    #[tokio::test]
541    async fn a_view_falls_back_to_the_process_wide_proxy() {
542        let hub = ClientHub::new();
543        hub.register_remote_proxy::<dyn TestApi>(Arc::new(ImplA(1)));
544        let view = hub.for_gear("orders");
545
546        assert_eq!(view.get::<dyn TestApi>().unwrap().id().await, 1);
547        // It is not this gear's proxy, so wiring builds one of its own.
548        assert!(!view.has_remote_proxy::<dyn TestApi>());
549
550        view.register_remote_proxy::<dyn TestApi>(Arc::new(ImplA(2)));
551        assert_eq!(view.get::<dyn TestApi>().unwrap().id().await, 2);
552        assert_eq!(hub.get::<dyn TestApi>().unwrap().id().await, 1);
553    }
554
555    #[tokio::test]
556    async fn removing_the_local_impl_leaves_the_proxy() {
557        let hub = ClientHub::new();
558        hub.register_remote_proxy::<dyn TestApi>(Arc::new(ImplA(1)));
559        hub.register::<dyn TestApi>(Arc::new(ImplA(2)));
560
561        assert!(hub.remove::<dyn TestApi>().is_some());
562        assert!(hub.try_get_local::<dyn TestApi>().is_none());
563        assert!(hub.has_remote_proxy::<dyn TestApi>());
564        assert_eq!(hub.get::<dyn TestApi>().unwrap().id().await, 1);
565    }
566
567    #[test]
568    fn views_share_local_and_scoped_registrations() {
569        let hub = ClientHub::new();
570        let view = hub.for_gear("orders");
571        let scope = ClientScope::new("pricing");
572        view.register::<str>(Arc::from("local"));
573        view.register_scoped::<str>(scope.clone(), Arc::from("scoped"));
574
575        assert_eq!(view.owner(), Some("orders"));
576        assert_eq!(hub.owner(), None);
577        assert_eq!(&*hub.get::<str>().unwrap(), "local");
578        assert_eq!(&*hub.get_scoped::<str>(&scope).unwrap(), "scoped");
579        assert_eq!(&*hub.for_gear("billing").get::<str>().unwrap(), "local");
580    }
581
582    #[tokio::test]
583    async fn overwrite_replaces_atomically() {
584        let hub = ClientHub::new();
585        hub.register::<dyn TestApi>(Arc::new(ImplA(1)));
586
587        let old = hub.get::<dyn TestApi>().unwrap();
588        assert_eq!(old.id().await, 1);
589
590        hub.register::<dyn TestApi>(Arc::new(ImplA(2)));
591
592        let new = hub.get::<dyn TestApi>().unwrap();
593        assert_eq!(new.id().await, 2);
594
595        // Old Arc is still valid
596        assert_eq!(old.id().await, 1);
597    }
598
599    #[tokio::test]
600    async fn scoped_register_and_get_dyn_trait() {
601        let hub = ClientHub::new();
602        let scope_a = ClientScope::gts_id(gts_id!(
603            "cf.core.toolkit.plugins.v1~cf.core.tenant_resolver.plugin.v1~contoso.app._.plugin.v1.0"
604        ));
605        let scope_b = ClientScope::gts_id(gts_id!(
606            "cf.core.toolkit.plugins.v1~cf.core.tenant_resolver.plugin.v1~fabrikam.app._.plugin.v1.0"
607        ));
608
609        let api_a: Arc<dyn TestApi> = Arc::new(ImplA(1));
610        let api_b: Arc<dyn TestApi> = Arc::new(ImplA(2));
611
612        hub.register_scoped::<dyn TestApi>(scope_a.clone(), api_a.clone());
613        hub.register_scoped::<dyn TestApi>(scope_b.clone(), api_b.clone());
614
615        assert_eq!(
616            hub.get_scoped::<dyn TestApi>(&scope_a).unwrap().id().await,
617            1
618        );
619        assert_eq!(
620            hub.get_scoped::<dyn TestApi>(&scope_b).unwrap().id().await,
621            2
622        );
623    }
624
625    #[test]
626    fn scoped_get_is_independent_from_global_get() {
627        let hub = ClientHub::new();
628        let scope = ClientScope::gts_id(gts_id!(
629            "cf.core.toolkit.plugins.v1~cf.core.tenant_resolver.plugin.v1~fabrikam.app._.plugin.v1.0"
630        ));
631        hub.register::<str>(Arc::from("global"));
632        hub.register_scoped::<str>(scope.clone(), Arc::from("scoped"));
633
634        assert_eq!(&*hub.get::<str>().unwrap(), "global");
635        assert_eq!(&*hub.get_scoped::<str>(&scope).unwrap(), "scoped");
636    }
637
638    #[test]
639    fn try_get_scoped_returns_some_on_hit() {
640        let hub = ClientHub::new();
641        let scope = ClientScope::gts_id(gts_id!(
642            "cf.core.toolkit.plugins.v1~cf.core.tenant_resolver.plugin.v1~contoso.app._.plugin.v1.0"
643        ));
644        hub.register_scoped::<str>(scope.clone(), Arc::from("scoped"));
645
646        let got = hub.try_get_scoped::<str>(&scope);
647        assert_eq!(got.as_deref(), Some("scoped"));
648    }
649
650    #[test]
651    fn try_get_scoped_returns_none_on_miss() {
652        let hub = ClientHub::new();
653        let scope = ClientScope::gts_id(gts_id!(
654            "cf.core.toolkit.plugins.v1~cf.core.tenant_resolver.plugin.v1~fabrikam.app._.plugin.v1.0"
655        ));
656
657        let got = hub.try_get_scoped::<str>(&scope);
658        assert!(got.is_none());
659    }
660}