1use std::future::Future;
2use std::sync::Arc;
3use std::time::Duration;
4
5use parking_lot::RwLock;
6use tokio::sync::Mutex;
7use toolkit_canonical_errors::CanonicalError;
8
9use crate::client_hub::{ClientHub, ClientScope};
10use crate::gts::PluginV1;
11
12pub struct GtsPluginSelector {
18 cached: RwLock<Option<Arc<str>>>,
20 resolve_lock: Mutex<()>,
22}
23
24impl Default for GtsPluginSelector {
25 fn default() -> Self {
26 Self::new()
27 }
28}
29
30impl GtsPluginSelector {
31 #[must_use]
32 pub fn new() -> Self {
33 Self {
34 cached: RwLock::new(None),
35 resolve_lock: Mutex::new(()),
36 }
37 }
38
39 #[must_use]
44 pub fn pre_cached(value: String) -> Self {
45 Self {
46 cached: RwLock::new(Some(Arc::from(value))),
47 resolve_lock: Mutex::new(()),
48 }
49 }
50
51 pub async fn get_or_init<F, Fut, E>(&self, resolve: F) -> Result<Arc<str>, E>
60 where
61 F: FnOnce() -> Fut,
62 Fut: Future<Output = Result<String, E>>,
63 {
64 {
66 let guard = self.cached.read();
67 if let Some(ref id) = *guard {
68 return Ok(Arc::clone(id));
69 }
70 }
71
72 let _resolve_guard = self.resolve_lock.lock().await;
74
75 {
77 let guard = self.cached.read();
78 if let Some(ref id) = *guard {
79 return Ok(Arc::clone(id));
80 }
81 }
82
83 let id_string = resolve().await?;
85 let id: Arc<str> = id_string.into();
86
87 {
88 let mut guard = self.cached.write();
89 *guard = Some(Arc::clone(&id));
90 }
91
92 Ok(id)
93 }
94
95 pub async fn get_or_init_with_timeout<F, Fut, E>(
107 &self,
108 timeout: Duration,
109 resolve: F,
110 on_timeout: impl FnOnce(String) -> E,
111 ) -> Result<Arc<str>, E>
112 where
113 F: FnOnce() -> Fut,
114 Fut: Future<Output = Result<String, E>>,
115 {
116 tokio::time::timeout(timeout, self.get_or_init(resolve))
117 .await
118 .unwrap_or_else(|_| {
119 Err(on_timeout(format!(
120 "plugin discovery did not finish within {timeout:?}"
121 )))
122 })
123 }
124
125 pub async fn reset(&self) -> bool {
129 let _resolve_guard = self.resolve_lock.lock().await;
130 let mut guard = self.cached.write();
131 guard.take().is_some()
132 }
133}
134
135#[must_use]
145pub fn is_discovery_outage(error: &CanonicalError) -> bool {
146 match error {
147 CanonicalError::ServiceUnavailable { .. }
148 | CanonicalError::DeadlineExceeded { .. }
149 | CanonicalError::Aborted { .. } => true,
150 CanonicalError::ResourceExhausted { ctx, .. } => ctx
151 .violations
152 .iter()
153 .any(|violation| violation.retry_after_seconds.is_some()),
154 _ => false,
155 }
156}
157
158#[derive(Debug, thiserror::Error)]
160pub enum ChoosePluginError {
161 #[error("invalid plugin instance content for '{gts_id}': {reason}")]
163 InvalidPluginInstance {
164 gts_id: String,
166 reason: String,
168 },
169
170 #[error("no plugin instances found for type '{type_id}', vendor '{vendor}'")]
172 PluginNotFound {
173 type_id: String,
175 vendor: String,
177 },
178}
179
180pub fn choose_plugin_instance<'a, P>(
207 vendor: &str,
208 instances: impl IntoIterator<Item = (&'a str, &'a serde_json::Value)>,
209) -> Result<String, ChoosePluginError>
210where
211 P: for<'de> gts::GtsDeserialize<'de> + gts::GtsSchema,
212{
213 let mut best: Option<(&str, i16)> = None;
214 let mut count: usize = 0;
215
216 for (gts_id, content_val) in instances {
217 count += 1;
218 let content: PluginV1<P> = serde_json::from_value(content_val.clone()).map_err(|e| {
219 tracing::error!(
220 gts_id = %gts_id,
221 error = %e,
222 "Failed to deserialize plugin instance content"
223 );
224 ChoosePluginError::InvalidPluginInstance {
225 gts_id: gts_id.to_owned(),
226 reason: e.to_string(),
227 }
228 })?;
229
230 if content.id != gts_id {
231 return Err(ChoosePluginError::InvalidPluginInstance {
232 gts_id: gts_id.to_owned(),
233 reason: format!(
234 "content.id mismatch: expected {:?}, got {:?}",
235 gts_id, content.id
236 ),
237 });
238 }
239
240 if content.vendor != vendor {
241 continue;
242 }
243
244 match &best {
245 None => best = Some((gts_id, content.priority)),
246 Some((_, cur_priority)) => {
247 if content.priority < *cur_priority {
248 best = Some((gts_id, content.priority));
249 }
250 }
251 }
252 }
253
254 tracing::debug!(vendor, instance_count = count, "choose_plugin_instance");
255
256 best.map(|(gts_id, _)| gts_id.to_owned())
257 .ok_or_else(|| ChoosePluginError::PluginNotFound {
258 type_id: P::TYPE_ID.to_owned(),
259 vendor: vendor.to_owned(),
260 })
261}
262
263fn is_instance_of<P: gts::GtsSchema>(gts_id: &str) -> bool {
267 P::TYPE_ID.ends_with('~')
268 && !gts_id.ends_with('~')
269 && gts_id
270 .strip_prefix(P::TYPE_ID)
271 .is_some_and(|rest| !rest.is_empty())
272}
273
274pub fn bind_plugin_instances<'a, P, C>(
286 hub: &ClientHub,
287 documents: impl IntoIterator<Item = &'a (impl AsRef<str> + 'a, serde_json::Value)>,
288 client: &Arc<C>,
289) -> anyhow::Result<()>
290where
291 P: gts::GtsSchema,
292 C: ?Sized + Send + Sync + 'static,
293{
294 let mut bound = 0usize;
295 for (id, _) in documents {
296 let id = id.as_ref();
297 if is_instance_of::<P>(id) {
298 hub.register_scoped::<C>(ClientScope::gts_id(id), Arc::clone(client));
299 tracing::info!(gts_id = %id, "plugin instance admitted and bound");
300 bound += 1;
301 }
302 }
303 anyhow::ensure!(bound > 0, "no instance of {} to bind", P::TYPE_ID);
304 Ok(())
305}
306
307pub fn choose_registered_plugin_instance<'a, P, C>(
323 hub: &ClientHub,
324 vendor: &str,
325 instances: impl IntoIterator<Item = (&'a str, Option<&'a serde_json::Value>)>,
326) -> Result<String, ChoosePluginError>
327where
328 P: for<'de> gts::GtsDeserialize<'de> + gts::GtsSchema,
329 C: ?Sized + Send + Sync + 'static,
330{
331 let registered = instances
332 .into_iter()
333 .filter(|(gts_id, _)| {
334 hub.try_get_scoped::<C>(&ClientScope::gts_id(gts_id))
335 .is_some()
336 })
337 .map(|(gts_id, content)| {
338 content.map(|content| (gts_id, content)).ok_or_else(|| {
339 ChoosePluginError::InvalidPluginInstance {
340 gts_id: gts_id.to_owned(),
341 reason: "listed without content".to_owned(),
342 }
343 })
344 })
345 .collect::<Result<Vec<_>, _>>()?;
346 choose_plugin_instance::<P>(vendor, registered)
347}
348
349#[cfg(test)]
350#[cfg_attr(coverage_nightly, coverage(off))]
351mod tests {
352 use super::*;
353 use std::sync::Arc;
354 use std::sync::atomic::{AtomicUsize, Ordering};
355 use toolkit_gts::gts_id;
356
357 const PLUGIN_A: &str =
358 gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~vendor.a.test.plugin.v1");
359 const PLUGIN_B: &str =
360 gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~vendor.b.test.plugin.v1");
361 const CONCURRENT_PLUGIN: &str = gts_id!(
362 "cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~vendor.concurrent.test.plugin.v1"
363 );
364
365 #[tokio::test]
366 async fn resolve_called_once_returns_same_str() {
367 let selector = GtsPluginSelector::new();
368 let calls = Arc::new(AtomicUsize::new(0));
369
370 let calls_a = calls.clone();
371 let id_a = selector
372 .get_or_init(|| async move {
373 calls_a.fetch_add(1, Ordering::SeqCst);
374 Ok::<_, std::convert::Infallible>(PLUGIN_A.to_owned())
375 })
376 .await
377 .unwrap();
378
379 let calls_b = calls.clone();
380 let id_b = selector
381 .get_or_init(|| async move {
382 calls_b.fetch_add(1, Ordering::SeqCst);
383 Ok::<_, std::convert::Infallible>(PLUGIN_B.to_owned())
384 })
385 .await
386 .unwrap();
387
388 assert_eq!(id_a, id_b);
389 assert_eq!(calls.load(Ordering::SeqCst), 1);
390 }
391
392 #[tokio::test]
393 async fn reset_triggers_reselection() {
394 let selector = GtsPluginSelector::new();
395 let calls = Arc::new(AtomicUsize::new(0));
396
397 let calls_a = calls.clone();
398 let id_a = selector
399 .get_or_init(|| async move {
400 calls_a.fetch_add(1, Ordering::SeqCst);
401 Ok::<_, std::convert::Infallible>(PLUGIN_A.to_owned())
402 })
403 .await;
404 assert_eq!(&*id_a.unwrap(), PLUGIN_A);
405 assert_eq!(calls.load(Ordering::SeqCst), 1);
406 assert!(selector.reset().await);
407
408 let calls_b = calls.clone();
409 let id_b = selector
410 .get_or_init(|| async move {
411 calls_b.fetch_add(1, Ordering::SeqCst);
412 Ok::<_, std::convert::Infallible>(PLUGIN_B.to_owned())
413 })
414 .await;
415 assert_eq!(&*id_b.unwrap(), PLUGIN_B);
416 assert_eq!(calls.load(Ordering::SeqCst), 2);
417 }
418
419 #[tokio::test]
420 async fn concurrent_get_or_init_resolves_once() {
421 let selector = Arc::new(GtsPluginSelector::new());
422 let calls = Arc::new(AtomicUsize::new(0));
423
424 let mut handles = Vec::new();
425 for _ in 0..10 {
426 let selector = Arc::clone(&selector);
427 let calls = Arc::clone(&calls);
428 handles.push(tokio::spawn(async move {
429 selector
430 .get_or_init(|| async {
431 tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
433 calls.fetch_add(1, Ordering::SeqCst);
434 Ok::<_, std::convert::Infallible>(CONCURRENT_PLUGIN.to_owned())
435 })
436 .await
437 }));
438 }
439
440 let mut results = Vec::new();
442 for handle in handles {
443 results.push(handle.await.unwrap().unwrap());
444 }
445
446 for id in &results {
448 assert_eq!(&**id, CONCURRENT_PLUGIN);
449 }
450
451 assert_eq!(calls.load(Ordering::SeqCst), 1);
453 }
454
455 mod choose_registered {
456 use super::*;
457 use serde_json::{Value, json};
458 use toolkit_gts::gts_type_schema;
459
460 #[derive(Default)]
461 #[gts_type_schema(
462 dir_path = "schemas",
463 base = PluginV1,
464 type_id = gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~"),
465 description = "Test plugin specification",
466 properties = "",
467 )]
468 struct TestPluginSpecV1;
469
470 #[derive(Default)]
472 #[gts_type_schema(
473 dir_path = "schemas",
474 base = PluginV1,
475 type_id = gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.other_test.plugin.v1~"),
476 description = "Other test plugin specification",
477 properties = "",
478 )]
479 struct OtherPluginSpecV1;
480
481 trait TestClient: Send + Sync {}
482 trait OtherClient: Send + Sync {}
483 struct Client;
484 impl TestClient for Client {}
485 impl OtherClient for Client {}
486
487 fn instance(name: &str, vendor: &str, priority: i16) -> (String, Value) {
489 let (id, content) = PluginV1::<TestPluginSpecV1>::build_registration(
490 &format!("vendor.x.{name}.plugin.v1"),
491 vendor,
492 priority,
493 )
494 .expect("serializes");
495 (id.to_string(), content)
496 }
497
498 fn register(hub: &ClientHub, gts_id: &str) {
499 hub.register_scoped::<dyn TestClient>(ClientScope::gts_id(gts_id), Arc::new(Client));
500 }
501
502 fn choose(
503 hub: &ClientHub,
504 listed: &[(String, Option<Value>)],
505 ) -> Result<String, ChoosePluginError> {
506 choose_registered_plugin_instance::<TestPluginSpecV1, dyn TestClient>(
507 hub,
508 "acme",
509 listed
510 .iter()
511 .map(|(id, content)| (id.as_str(), content.as_ref())),
512 )
513 }
514
515 #[test]
516 fn unregistered_entries_are_skipped_unexamined() {
517 let hub = ClientHub::new();
518 let (missing, _) = instance("missing", "acme", 0);
519 let (malformed, _) = instance("malformed", "acme", 0);
520 let (preferred, preferred_content) = instance("preferred", "acme", -10);
521 let (running, running_content) = instance("running", "acme", 5);
522 let (elsewhere, elsewhere_content) = instance("elsewhere", "acme", -20);
523 register(&hub, &running);
524 hub.register_scoped::<dyn OtherClient>(
526 ClientScope::gts_id(&elsewhere),
527 Arc::new(Client),
528 );
529
530 let chosen = choose(
531 &hub,
532 &[
533 (missing, None),
534 (malformed, Some(json!({ "bogus": true }))),
535 (preferred, Some(preferred_content)),
536 (running.clone(), Some(running_content)),
537 (elsewhere, Some(elsewhere_content)),
538 ],
539 )
540 .expect("chooses");
541 assert_eq!(chosen, running);
542 }
543
544 #[test]
545 fn the_lowest_registered_priority_of_the_vendor_wins_and_the_first_on_a_tie() {
546 let hub = ClientHub::new();
547 let listed: Vec<_> = [
548 instance("low", "acme", 5),
549 instance("other_vendor", "other", -5),
550 instance("tie_first", "acme", 1),
551 instance("tie_second", "acme", 1),
552 ]
553 .into_iter()
554 .map(|(id, content)| {
555 register(&hub, &id);
556 (id, Some(content))
557 })
558 .collect();
559
560 assert_eq!(choose(&hub, &listed).expect("chooses"), listed[2].0);
561 }
562
563 #[test]
564 fn a_registered_entry_without_content_is_invalid_before_any_is_read() {
565 let hub = ClientHub::new();
566 let (malformed, _) = instance("malformed", "acme", 0);
567 let (missing, _) = instance("missing", "acme", 0);
568 register(&hub, &malformed);
569 register(&hub, &missing);
570
571 let error = choose(
572 &hub,
573 &[
574 (malformed, Some(json!({ "bogus": true }))),
575 (missing.clone(), None),
576 ],
577 )
578 .expect_err("refused");
579 assert!(
580 matches!(&error, ChoosePluginError::InvalidPluginInstance { gts_id, reason }
581 if *gts_id == missing && reason == "listed without content"),
582 "{error:?}"
583 );
584 }
585
586 #[test]
587 fn a_malformed_or_misnamed_registered_entry_is_invalid() {
588 let hub = ClientHub::new();
589 let (malformed, _) = instance("malformed", "other", 0);
590 let (good, good_content) = instance("good", "acme", 0);
591 let (misnamed, _) = instance("misnamed", "acme", 0);
592 for id in [&malformed, &good, &misnamed] {
593 register(&hub, id);
594 }
595
596 let error = choose(
597 &hub,
598 &[
599 (good, Some(good_content.clone())),
600 (malformed.clone(), Some(json!({ "bogus": true }))),
601 ],
602 )
603 .expect_err("refused");
604 assert!(
605 matches!(&error, ChoosePluginError::InvalidPluginInstance { gts_id, .. } if *gts_id == malformed),
606 "{error:?}"
607 );
608
609 let error =
610 choose(&hub, &[(misnamed.clone(), Some(good_content))]).expect_err("refused");
611 assert!(
612 matches!(&error, ChoosePluginError::InvalidPluginInstance { gts_id, .. } if *gts_id == misnamed),
613 "{error:?}"
614 );
615 }
616
617 #[tokio::test]
621 async fn the_first_selection_after_every_binding_chooses_the_best_bound_plugin() {
622 let hub = ClientHub::new();
623 let (fast, fast_content) = instance("fast", "acme", 5);
624 let (best, best_content) = instance("best", "acme", 1);
625 register(&hub, &fast);
626 register(&hub, &best);
627 let selector = GtsPluginSelector::new();
628 let listing = vec![
629 (fast, Some(fast_content)),
630 (best.clone(), Some(best_content)),
631 ];
632
633 let chosen = selector
634 .get_or_init(|| async { choose(&hub, &listing) })
635 .await
636 .expect("chooses");
637
638 assert_eq!(&*chosen, best);
639 }
640
641 #[test]
644 fn a_stale_unbound_instance_is_never_chosen() {
645 let hub = ClientHub::new();
646 let (stale, stale_content) = instance("stale", "acme", -100);
647 let (bound, bound_content) = instance("bound", "acme", 10);
648 register(&hub, &bound);
649
650 let chosen = choose(
651 &hub,
652 &[
653 (stale, Some(stale_content)),
654 (bound.clone(), Some(bound_content)),
655 ],
656 )
657 .expect("chooses");
658
659 assert_eq!(chosen, bound);
660 }
661
662 #[test]
665 fn binding_admitted_instances_binds_only_the_specs_instances() {
666 let hub = ClientHub::new();
667 let spec = <TestPluginSpecV1 as gts::GtsSchema>::TYPE_ID;
668 let (mine, mine_content) = instance("mine", "acme", 1);
669 let derived = format!("{spec}vendor.x.derived.plugin.v1~vendor.x.mine.plugin.v1");
670 let derived_schema = format!("{spec}vendor.x.derived.plugin.v1~");
671 let other = PluginV1::<OtherPluginSpecV1>::build_registration(
672 "vendor.x.o.plugin.v1",
673 "acme",
674 1,
675 )
676 .expect("serializes");
677 let manifest = [
678 (mine.clone(), mine_content),
679 (derived.clone(), json!({})),
680 (derived_schema.clone(), json!({})),
681 (spec.to_owned(), json!({})),
682 (other.0.as_ref().to_owned(), other.1),
683 ];
684 let client: Arc<dyn TestClient> = Arc::new(Client);
685 let bound = |id: &str| {
686 hub.try_get_scoped::<dyn TestClient>(&ClientScope::gts_id(id))
687 .is_some()
688 };
689
690 bind_plugin_instances::<TestPluginSpecV1, dyn TestClient>(&hub, &manifest, &client)
691 .expect("binds");
692
693 assert!(
694 bound(&mine) && bound(&derived),
695 "the spec's instances, derived included"
696 );
697 assert!(
698 !bound(&derived_schema) && !bound(spec),
699 "type schemas are not bound"
700 );
701 assert!(
702 !bound(other.0.as_ref()),
703 "another spec's instance is not bound"
704 );
705 assert!(
706 bind_plugin_instances::<TestPluginSpecV1, dyn TestClient>(
707 &hub,
708 &manifest[2..],
709 &client
710 )
711 .is_err(),
712 "a manifest without an instance of the spec"
713 );
714
715 let typed_hub = ClientHub::new();
717 let typed: Vec<(gts::GtsId, serde_json::Value)> = manifest
718 .iter()
719 .map(|(id, content)| (gts::GtsId::try_new(id).expect("valid"), content.clone()))
720 .collect();
721 bind_plugin_instances::<TestPluginSpecV1, _>(&typed_hub, &typed, &client)
722 .expect("binds");
723 let bound = |id: &str| {
724 typed_hub
725 .try_get_scoped::<dyn TestClient>(&ClientScope::gts_id(id))
726 .is_some()
727 };
728 assert!(bound(&mine) && bound(&derived));
729 assert!(!bound(&derived_schema) && !bound(spec) && !bound(other.0.as_ref()));
730 }
731
732 #[test]
733 fn nothing_registered_is_not_found() {
734 let (id, content) = instance("listed", "acme", 0);
735 let error = choose(&ClientHub::new(), &[(id, Some(content))]).expect_err("refused");
736 assert!(
737 matches!(error, ChoosePluginError::PluginNotFound { .. }),
738 "{error:?}"
739 );
740 }
741 }
742}
743
744#[cfg(test)]
745#[path = "selection_tests.rs"]
746mod selection_tests;