1use parking_lot::RwLock;
21use std::{any::Any, collections::HashMap, fmt, sync::Arc};
22
23#[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#[derive(Clone, Eq, PartialEq, Hash)]
45pub struct ClientScope(Arc<str>);
46
47impl ClientScope {
48 #[inline]
50 #[must_use]
51 pub fn new(scope: impl Into<Arc<str>>) -> Self {
52 Self(scope.into())
53 }
54
55 #[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
117type ClientMap = HashMap<TypeKey, Boxed>;
119
120type ScopedClientMap = HashMap<ScopedKey, Boxed>;
122
123#[derive(Clone, Eq, PartialEq, Hash, Debug)]
126struct ProxyKey {
127 type_key: TypeKey,
128 owner: Option<Arc<str>>,
129}
130
131#[derive(Default)]
133struct Storage {
134 map: RwLock<ClientMap>,
135 scoped_map: RwLock<ScopedClientMap>,
136 proxies: RwLock<HashMap<ProxyKey, Boxed>>,
144}
145
146#[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 #[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 #[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 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 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 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 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 #[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 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 #[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 #[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 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 #[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 #[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 #[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 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 #[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 #[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 assert!(hub.try_get::<dyn TestApi>().is_some());
486 assert!(hub.get::<dyn TestApi>().is_ok());
487 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 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 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 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 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}