1use std::future::Future;
2use std::sync::Arc;
3
4use parking_lot::RwLock;
5use tokio::sync::Mutex;
6
7use crate::client_hub::{ClientHub, ClientScope};
8use crate::gts::PluginV1;
9
10pub struct GtsPluginSelector {
16 cached: RwLock<Option<Arc<str>>>,
18 resolve_lock: Mutex<()>,
20}
21
22impl Default for GtsPluginSelector {
23 fn default() -> Self {
24 Self::new()
25 }
26}
27
28impl GtsPluginSelector {
29 #[must_use]
30 pub fn new() -> Self {
31 Self {
32 cached: RwLock::new(None),
33 resolve_lock: Mutex::new(()),
34 }
35 }
36
37 #[must_use]
42 pub fn pre_cached(value: String) -> Self {
43 Self {
44 cached: RwLock::new(Some(Arc::from(value))),
45 resolve_lock: Mutex::new(()),
46 }
47 }
48
49 pub async fn get_or_init<F, Fut, E>(&self, resolve: F) -> Result<Arc<str>, E>
58 where
59 F: FnOnce() -> Fut,
60 Fut: Future<Output = Result<String, E>>,
61 {
62 {
64 let guard = self.cached.read();
65 if let Some(ref id) = *guard {
66 return Ok(Arc::clone(id));
67 }
68 }
69
70 let _resolve_guard = self.resolve_lock.lock().await;
72
73 {
75 let guard = self.cached.read();
76 if let Some(ref id) = *guard {
77 return Ok(Arc::clone(id));
78 }
79 }
80
81 let id_string = resolve().await?;
83 let id: Arc<str> = id_string.into();
84
85 {
86 let mut guard = self.cached.write();
87 *guard = Some(Arc::clone(&id));
88 }
89
90 Ok(id)
91 }
92
93 pub async fn reset(&self) -> bool {
97 let _resolve_guard = self.resolve_lock.lock().await;
98 let mut guard = self.cached.write();
99 guard.take().is_some()
100 }
101}
102
103#[derive(Debug, thiserror::Error)]
105pub enum ChoosePluginError {
106 #[error("invalid plugin instance content for '{gts_id}': {reason}")]
108 InvalidPluginInstance {
109 gts_id: String,
111 reason: String,
113 },
114
115 #[error("no plugin instances found for type '{type_id}', vendor '{vendor}'")]
117 PluginNotFound {
118 type_id: String,
120 vendor: String,
122 },
123}
124
125pub fn choose_plugin_instance<'a, P>(
152 vendor: &str,
153 instances: impl IntoIterator<Item = (&'a str, &'a serde_json::Value)>,
154) -> Result<String, ChoosePluginError>
155where
156 P: for<'de> gts::GtsDeserialize<'de> + gts::GtsSchema,
157{
158 let mut best: Option<(&str, i16)> = None;
159 let mut count: usize = 0;
160
161 for (gts_id, content_val) in instances {
162 count += 1;
163 let content: PluginV1<P> = serde_json::from_value(content_val.clone()).map_err(|e| {
164 tracing::error!(
165 gts_id = %gts_id,
166 error = %e,
167 "Failed to deserialize plugin instance content"
168 );
169 ChoosePluginError::InvalidPluginInstance {
170 gts_id: gts_id.to_owned(),
171 reason: e.to_string(),
172 }
173 })?;
174
175 if content.id != gts_id {
176 return Err(ChoosePluginError::InvalidPluginInstance {
177 gts_id: gts_id.to_owned(),
178 reason: format!(
179 "content.id mismatch: expected {:?}, got {:?}",
180 gts_id, content.id
181 ),
182 });
183 }
184
185 if content.vendor != vendor {
186 continue;
187 }
188
189 match &best {
190 None => best = Some((gts_id, content.priority)),
191 Some((_, cur_priority)) => {
192 if content.priority < *cur_priority {
193 best = Some((gts_id, content.priority));
194 }
195 }
196 }
197 }
198
199 tracing::debug!(vendor, instance_count = count, "choose_plugin_instance");
200
201 best.map(|(gts_id, _)| gts_id.to_owned())
202 .ok_or_else(|| ChoosePluginError::PluginNotFound {
203 type_id: P::TYPE_ID.to_owned(),
204 vendor: vendor.to_owned(),
205 })
206}
207
208fn is_instance_of<P: gts::GtsSchema>(gts_id: &str) -> bool {
212 P::TYPE_ID.ends_with('~')
213 && !gts_id.ends_with('~')
214 && gts_id
215 .strip_prefix(P::TYPE_ID)
216 .is_some_and(|rest| !rest.is_empty())
217}
218
219pub fn bind_plugin_instances<'a, P, C>(
231 hub: &ClientHub,
232 documents: impl IntoIterator<Item = &'a (impl AsRef<str> + 'a, serde_json::Value)>,
233 client: &Arc<C>,
234) -> anyhow::Result<()>
235where
236 P: gts::GtsSchema,
237 C: ?Sized + Send + Sync + 'static,
238{
239 let mut bound = 0usize;
240 for (id, _) in documents {
241 let id = id.as_ref();
242 if is_instance_of::<P>(id) {
243 hub.register_scoped::<C>(ClientScope::gts_id(id), Arc::clone(client));
244 tracing::info!(gts_id = %id, "plugin instance admitted and bound");
245 bound += 1;
246 }
247 }
248 anyhow::ensure!(bound > 0, "no instance of {} to bind", P::TYPE_ID);
249 Ok(())
250}
251
252pub fn choose_registered_plugin_instance<'a, P, C>(
268 hub: &ClientHub,
269 vendor: &str,
270 instances: impl IntoIterator<Item = (&'a str, Option<&'a serde_json::Value>)>,
271) -> Result<String, ChoosePluginError>
272where
273 P: for<'de> gts::GtsDeserialize<'de> + gts::GtsSchema,
274 C: ?Sized + Send + Sync + 'static,
275{
276 let registered = instances
277 .into_iter()
278 .filter(|(gts_id, _)| {
279 hub.try_get_scoped::<C>(&ClientScope::gts_id(gts_id))
280 .is_some()
281 })
282 .map(|(gts_id, content)| {
283 content.map(|content| (gts_id, content)).ok_or_else(|| {
284 ChoosePluginError::InvalidPluginInstance {
285 gts_id: gts_id.to_owned(),
286 reason: "listed without content".to_owned(),
287 }
288 })
289 })
290 .collect::<Result<Vec<_>, _>>()?;
291 choose_plugin_instance::<P>(vendor, registered)
292}
293
294#[cfg(test)]
295#[cfg_attr(coverage_nightly, coverage(off))]
296mod tests {
297 use super::*;
298 use std::sync::Arc;
299 use std::sync::atomic::{AtomicUsize, Ordering};
300 use toolkit_gts::gts_id;
301
302 const PLUGIN_A: &str =
303 gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~vendor.a.test.plugin.v1");
304 const PLUGIN_B: &str =
305 gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~vendor.b.test.plugin.v1");
306 const CONCURRENT_PLUGIN: &str = gts_id!(
307 "cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~vendor.concurrent.test.plugin.v1"
308 );
309
310 #[tokio::test]
311 async fn resolve_called_once_returns_same_str() {
312 let selector = GtsPluginSelector::new();
313 let calls = Arc::new(AtomicUsize::new(0));
314
315 let calls_a = calls.clone();
316 let id_a = selector
317 .get_or_init(|| async move {
318 calls_a.fetch_add(1, Ordering::SeqCst);
319 Ok::<_, std::convert::Infallible>(PLUGIN_A.to_owned())
320 })
321 .await
322 .unwrap();
323
324 let calls_b = calls.clone();
325 let id_b = selector
326 .get_or_init(|| async move {
327 calls_b.fetch_add(1, Ordering::SeqCst);
328 Ok::<_, std::convert::Infallible>(PLUGIN_B.to_owned())
329 })
330 .await
331 .unwrap();
332
333 assert_eq!(id_a, id_b);
334 assert_eq!(calls.load(Ordering::SeqCst), 1);
335 }
336
337 #[tokio::test]
338 async fn reset_triggers_reselection() {
339 let selector = GtsPluginSelector::new();
340 let calls = Arc::new(AtomicUsize::new(0));
341
342 let calls_a = calls.clone();
343 let id_a = selector
344 .get_or_init(|| async move {
345 calls_a.fetch_add(1, Ordering::SeqCst);
346 Ok::<_, std::convert::Infallible>(PLUGIN_A.to_owned())
347 })
348 .await;
349 assert_eq!(&*id_a.unwrap(), PLUGIN_A);
350 assert_eq!(calls.load(Ordering::SeqCst), 1);
351 assert!(selector.reset().await);
352
353 let calls_b = calls.clone();
354 let id_b = selector
355 .get_or_init(|| async move {
356 calls_b.fetch_add(1, Ordering::SeqCst);
357 Ok::<_, std::convert::Infallible>(PLUGIN_B.to_owned())
358 })
359 .await;
360 assert_eq!(&*id_b.unwrap(), PLUGIN_B);
361 assert_eq!(calls.load(Ordering::SeqCst), 2);
362 }
363
364 #[tokio::test]
365 async fn concurrent_get_or_init_resolves_once() {
366 let selector = Arc::new(GtsPluginSelector::new());
367 let calls = Arc::new(AtomicUsize::new(0));
368
369 let mut handles = Vec::new();
370 for _ in 0..10 {
371 let selector = Arc::clone(&selector);
372 let calls = Arc::clone(&calls);
373 handles.push(tokio::spawn(async move {
374 selector
375 .get_or_init(|| async {
376 tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
378 calls.fetch_add(1, Ordering::SeqCst);
379 Ok::<_, std::convert::Infallible>(CONCURRENT_PLUGIN.to_owned())
380 })
381 .await
382 }));
383 }
384
385 let mut results = Vec::new();
387 for handle in handles {
388 results.push(handle.await.unwrap().unwrap());
389 }
390
391 for id in &results {
393 assert_eq!(&**id, CONCURRENT_PLUGIN);
394 }
395
396 assert_eq!(calls.load(Ordering::SeqCst), 1);
398 }
399
400 mod choose_registered {
401 use super::*;
402 use serde_json::{Value, json};
403 use toolkit_gts::gts_type_schema;
404
405 #[derive(Default)]
406 #[gts_type_schema(
407 dir_path = "schemas",
408 base = PluginV1,
409 type_id = gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~"),
410 description = "Test plugin specification",
411 properties = "",
412 )]
413 struct TestPluginSpecV1;
414
415 #[derive(Default)]
417 #[gts_type_schema(
418 dir_path = "schemas",
419 base = PluginV1,
420 type_id = gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.other_test.plugin.v1~"),
421 description = "Other test plugin specification",
422 properties = "",
423 )]
424 struct OtherPluginSpecV1;
425
426 trait TestClient: Send + Sync {}
427 trait OtherClient: Send + Sync {}
428 struct Client;
429 impl TestClient for Client {}
430 impl OtherClient for Client {}
431
432 fn instance(name: &str, vendor: &str, priority: i16) -> (String, Value) {
434 let (id, content) = PluginV1::<TestPluginSpecV1>::build_registration(
435 &format!("vendor.x.{name}.plugin.v1"),
436 vendor,
437 priority,
438 )
439 .expect("serializes");
440 (id.to_string(), content)
441 }
442
443 fn register(hub: &ClientHub, gts_id: &str) {
444 hub.register_scoped::<dyn TestClient>(ClientScope::gts_id(gts_id), Arc::new(Client));
445 }
446
447 fn choose(
448 hub: &ClientHub,
449 listed: &[(String, Option<Value>)],
450 ) -> Result<String, ChoosePluginError> {
451 choose_registered_plugin_instance::<TestPluginSpecV1, dyn TestClient>(
452 hub,
453 "acme",
454 listed
455 .iter()
456 .map(|(id, content)| (id.as_str(), content.as_ref())),
457 )
458 }
459
460 #[test]
461 fn unregistered_entries_are_skipped_unexamined() {
462 let hub = ClientHub::new();
463 let (missing, _) = instance("missing", "acme", 0);
464 let (malformed, _) = instance("malformed", "acme", 0);
465 let (preferred, preferred_content) = instance("preferred", "acme", -10);
466 let (running, running_content) = instance("running", "acme", 5);
467 let (elsewhere, elsewhere_content) = instance("elsewhere", "acme", -20);
468 register(&hub, &running);
469 hub.register_scoped::<dyn OtherClient>(
471 ClientScope::gts_id(&elsewhere),
472 Arc::new(Client),
473 );
474
475 let chosen = choose(
476 &hub,
477 &[
478 (missing, None),
479 (malformed, Some(json!({ "bogus": true }))),
480 (preferred, Some(preferred_content)),
481 (running.clone(), Some(running_content)),
482 (elsewhere, Some(elsewhere_content)),
483 ],
484 )
485 .expect("chooses");
486 assert_eq!(chosen, running);
487 }
488
489 #[test]
490 fn the_lowest_registered_priority_of_the_vendor_wins_and_the_first_on_a_tie() {
491 let hub = ClientHub::new();
492 let listed: Vec<_> = [
493 instance("low", "acme", 5),
494 instance("other_vendor", "other", -5),
495 instance("tie_first", "acme", 1),
496 instance("tie_second", "acme", 1),
497 ]
498 .into_iter()
499 .map(|(id, content)| {
500 register(&hub, &id);
501 (id, Some(content))
502 })
503 .collect();
504
505 assert_eq!(choose(&hub, &listed).expect("chooses"), listed[2].0);
506 }
507
508 #[test]
509 fn a_registered_entry_without_content_is_invalid_before_any_is_read() {
510 let hub = ClientHub::new();
511 let (malformed, _) = instance("malformed", "acme", 0);
512 let (missing, _) = instance("missing", "acme", 0);
513 register(&hub, &malformed);
514 register(&hub, &missing);
515
516 let error = choose(
517 &hub,
518 &[
519 (malformed, Some(json!({ "bogus": true }))),
520 (missing.clone(), None),
521 ],
522 )
523 .expect_err("refused");
524 assert!(
525 matches!(&error, ChoosePluginError::InvalidPluginInstance { gts_id, reason }
526 if *gts_id == missing && reason == "listed without content"),
527 "{error:?}"
528 );
529 }
530
531 #[test]
532 fn a_malformed_or_misnamed_registered_entry_is_invalid() {
533 let hub = ClientHub::new();
534 let (malformed, _) = instance("malformed", "other", 0);
535 let (good, good_content) = instance("good", "acme", 0);
536 let (misnamed, _) = instance("misnamed", "acme", 0);
537 for id in [&malformed, &good, &misnamed] {
538 register(&hub, id);
539 }
540
541 let error = choose(
542 &hub,
543 &[
544 (good, Some(good_content.clone())),
545 (malformed.clone(), Some(json!({ "bogus": true }))),
546 ],
547 )
548 .expect_err("refused");
549 assert!(
550 matches!(&error, ChoosePluginError::InvalidPluginInstance { gts_id, .. } if *gts_id == malformed),
551 "{error:?}"
552 );
553
554 let error =
555 choose(&hub, &[(misnamed.clone(), Some(good_content))]).expect_err("refused");
556 assert!(
557 matches!(&error, ChoosePluginError::InvalidPluginInstance { gts_id, .. } if *gts_id == misnamed),
558 "{error:?}"
559 );
560 }
561
562 #[tokio::test]
566 async fn the_first_selection_after_every_binding_chooses_the_best_bound_plugin() {
567 let hub = ClientHub::new();
568 let (fast, fast_content) = instance("fast", "acme", 5);
569 let (best, best_content) = instance("best", "acme", 1);
570 register(&hub, &fast);
571 register(&hub, &best);
572 let selector = GtsPluginSelector::new();
573 let listing = vec![
574 (fast, Some(fast_content)),
575 (best.clone(), Some(best_content)),
576 ];
577
578 let chosen = selector
579 .get_or_init(|| async { choose(&hub, &listing) })
580 .await
581 .expect("chooses");
582
583 assert_eq!(&*chosen, best);
584 }
585
586 #[test]
589 fn a_stale_unbound_instance_is_never_chosen() {
590 let hub = ClientHub::new();
591 let (stale, stale_content) = instance("stale", "acme", -100);
592 let (bound, bound_content) = instance("bound", "acme", 10);
593 register(&hub, &bound);
594
595 let chosen = choose(
596 &hub,
597 &[
598 (stale, Some(stale_content)),
599 (bound.clone(), Some(bound_content)),
600 ],
601 )
602 .expect("chooses");
603
604 assert_eq!(chosen, bound);
605 }
606
607 #[test]
610 fn binding_admitted_instances_binds_only_the_specs_instances() {
611 let hub = ClientHub::new();
612 let spec = <TestPluginSpecV1 as gts::GtsSchema>::TYPE_ID;
613 let (mine, mine_content) = instance("mine", "acme", 1);
614 let derived = format!("{spec}vendor.x.derived.plugin.v1~vendor.x.mine.plugin.v1");
615 let derived_schema = format!("{spec}vendor.x.derived.plugin.v1~");
616 let other = PluginV1::<OtherPluginSpecV1>::build_registration(
617 "vendor.x.o.plugin.v1",
618 "acme",
619 1,
620 )
621 .expect("serializes");
622 let manifest = [
623 (mine.clone(), mine_content),
624 (derived.clone(), json!({})),
625 (derived_schema.clone(), json!({})),
626 (spec.to_owned(), json!({})),
627 (other.0.as_ref().to_owned(), other.1),
628 ];
629 let client: Arc<dyn TestClient> = Arc::new(Client);
630 let bound = |id: &str| {
631 hub.try_get_scoped::<dyn TestClient>(&ClientScope::gts_id(id))
632 .is_some()
633 };
634
635 bind_plugin_instances::<TestPluginSpecV1, dyn TestClient>(&hub, &manifest, &client)
636 .expect("binds");
637
638 assert!(
639 bound(&mine) && bound(&derived),
640 "the spec's instances, derived included"
641 );
642 assert!(
643 !bound(&derived_schema) && !bound(spec),
644 "type schemas are not bound"
645 );
646 assert!(
647 !bound(other.0.as_ref()),
648 "another spec's instance is not bound"
649 );
650 assert!(
651 bind_plugin_instances::<TestPluginSpecV1, dyn TestClient>(
652 &hub,
653 &manifest[2..],
654 &client
655 )
656 .is_err(),
657 "a manifest without an instance of the spec"
658 );
659
660 let typed_hub = ClientHub::new();
662 let typed: Vec<(gts::GtsId, serde_json::Value)> = manifest
663 .iter()
664 .map(|(id, content)| (gts::GtsId::try_new(id).expect("valid"), content.clone()))
665 .collect();
666 bind_plugin_instances::<TestPluginSpecV1, _>(&typed_hub, &typed, &client)
667 .expect("binds");
668 let bound = |id: &str| {
669 typed_hub
670 .try_get_scoped::<dyn TestClient>(&ClientScope::gts_id(id))
671 .is_some()
672 };
673 assert!(bound(&mine) && bound(&derived));
674 assert!(!bound(&derived_schema) && !bound(spec) && !bound(other.0.as_ref()));
675 }
676
677 #[test]
678 fn nothing_registered_is_not_found() {
679 let (id, content) = instance("listed", "acme", 0);
680 let error = choose(&ClientHub::new(), &[(id, Some(content))]).expect_err("refused");
681 assert!(
682 matches!(error, ChoosePluginError::PluginNotFound { .. }),
683 "{error:?}"
684 );
685 }
686 }
687}