use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use parking_lot::RwLock;
use tokio::sync::Mutex;
use toolkit_canonical_errors::CanonicalError;
use crate::client_hub::{ClientHub, ClientScope};
use crate::gts::PluginV1;
pub struct GtsPluginSelector {
cached: RwLock<Option<Arc<str>>>,
resolve_lock: Mutex<()>,
}
impl Default for GtsPluginSelector {
fn default() -> Self {
Self::new()
}
}
impl GtsPluginSelector {
#[must_use]
pub fn new() -> Self {
Self {
cached: RwLock::new(None),
resolve_lock: Mutex::new(()),
}
}
#[must_use]
pub fn pre_cached(value: String) -> Self {
Self {
cached: RwLock::new(Some(Arc::from(value))),
resolve_lock: Mutex::new(()),
}
}
pub async fn get_or_init<F, Fut, E>(&self, resolve: F) -> Result<Arc<str>, E>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<String, E>>,
{
{
let guard = self.cached.read();
if let Some(ref id) = *guard {
return Ok(Arc::clone(id));
}
}
let _resolve_guard = self.resolve_lock.lock().await;
{
let guard = self.cached.read();
if let Some(ref id) = *guard {
return Ok(Arc::clone(id));
}
}
let id_string = resolve().await?;
let id: Arc<str> = id_string.into();
{
let mut guard = self.cached.write();
*guard = Some(Arc::clone(&id));
}
Ok(id)
}
pub async fn get_or_init_with_timeout<F, Fut, E>(
&self,
timeout: Duration,
resolve: F,
on_timeout: impl FnOnce(String) -> E,
) -> Result<Arc<str>, E>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<String, E>>,
{
tokio::time::timeout(timeout, self.get_or_init(resolve))
.await
.unwrap_or_else(|_| {
Err(on_timeout(format!(
"plugin discovery did not finish within {timeout:?}"
)))
})
}
pub async fn reset(&self) -> bool {
let _resolve_guard = self.resolve_lock.lock().await;
let mut guard = self.cached.write();
guard.take().is_some()
}
}
#[must_use]
pub fn is_discovery_outage(error: &CanonicalError) -> bool {
match error {
CanonicalError::ServiceUnavailable { .. }
| CanonicalError::DeadlineExceeded { .. }
| CanonicalError::Aborted { .. } => true,
CanonicalError::ResourceExhausted { ctx, .. } => ctx
.violations
.iter()
.any(|violation| violation.retry_after_seconds.is_some()),
_ => false,
}
}
#[derive(Debug, thiserror::Error)]
pub enum ChoosePluginError {
#[error("invalid plugin instance content for '{gts_id}': {reason}")]
InvalidPluginInstance {
gts_id: String,
reason: String,
},
#[error("no plugin instances found for type '{type_id}', vendor '{vendor}'")]
PluginNotFound {
type_id: String,
vendor: String,
},
}
pub fn choose_plugin_instance<'a, P>(
vendor: &str,
instances: impl IntoIterator<Item = (&'a str, &'a serde_json::Value)>,
) -> Result<String, ChoosePluginError>
where
P: for<'de> gts::GtsDeserialize<'de> + gts::GtsSchema,
{
let mut best: Option<(&str, i16)> = None;
let mut count: usize = 0;
for (gts_id, content_val) in instances {
count += 1;
let content: PluginV1<P> = serde_json::from_value(content_val.clone()).map_err(|e| {
tracing::error!(
gts_id = %gts_id,
error = %e,
"Failed to deserialize plugin instance content"
);
ChoosePluginError::InvalidPluginInstance {
gts_id: gts_id.to_owned(),
reason: e.to_string(),
}
})?;
if content.id != gts_id {
return Err(ChoosePluginError::InvalidPluginInstance {
gts_id: gts_id.to_owned(),
reason: format!(
"content.id mismatch: expected {:?}, got {:?}",
gts_id, content.id
),
});
}
if content.vendor != vendor {
continue;
}
match &best {
None => best = Some((gts_id, content.priority)),
Some((_, cur_priority)) => {
if content.priority < *cur_priority {
best = Some((gts_id, content.priority));
}
}
}
}
tracing::debug!(vendor, instance_count = count, "choose_plugin_instance");
best.map(|(gts_id, _)| gts_id.to_owned())
.ok_or_else(|| ChoosePluginError::PluginNotFound {
type_id: P::TYPE_ID.to_owned(),
vendor: vendor.to_owned(),
})
}
fn is_instance_of<P: gts::GtsSchema>(gts_id: &str) -> bool {
P::TYPE_ID.ends_with('~')
&& !gts_id.ends_with('~')
&& gts_id
.strip_prefix(P::TYPE_ID)
.is_some_and(|rest| !rest.is_empty())
}
pub fn bind_plugin_instances<'a, P, C>(
hub: &ClientHub,
documents: impl IntoIterator<Item = &'a (impl AsRef<str> + 'a, serde_json::Value)>,
client: &Arc<C>,
) -> anyhow::Result<()>
where
P: gts::GtsSchema,
C: ?Sized + Send + Sync + 'static,
{
let mut bound = 0usize;
for (id, _) in documents {
let id = id.as_ref();
if is_instance_of::<P>(id) {
hub.register_scoped::<C>(ClientScope::gts_id(id), Arc::clone(client));
tracing::info!(gts_id = %id, "plugin instance admitted and bound");
bound += 1;
}
}
anyhow::ensure!(bound > 0, "no instance of {} to bind", P::TYPE_ID);
Ok(())
}
pub fn choose_registered_plugin_instance<'a, P, C>(
hub: &ClientHub,
vendor: &str,
instances: impl IntoIterator<Item = (&'a str, Option<&'a serde_json::Value>)>,
) -> Result<String, ChoosePluginError>
where
P: for<'de> gts::GtsDeserialize<'de> + gts::GtsSchema,
C: ?Sized + Send + Sync + 'static,
{
let registered = instances
.into_iter()
.filter(|(gts_id, _)| {
hub.try_get_scoped::<C>(&ClientScope::gts_id(gts_id))
.is_some()
})
.map(|(gts_id, content)| {
content.map(|content| (gts_id, content)).ok_or_else(|| {
ChoosePluginError::InvalidPluginInstance {
gts_id: gts_id.to_owned(),
reason: "listed without content".to_owned(),
}
})
})
.collect::<Result<Vec<_>, _>>()?;
choose_plugin_instance::<P>(vendor, registered)
}
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use toolkit_gts::gts_id;
const PLUGIN_A: &str =
gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~vendor.a.test.plugin.v1");
const PLUGIN_B: &str =
gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~vendor.b.test.plugin.v1");
const CONCURRENT_PLUGIN: &str = gts_id!(
"cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~vendor.concurrent.test.plugin.v1"
);
#[tokio::test]
async fn resolve_called_once_returns_same_str() {
let selector = GtsPluginSelector::new();
let calls = Arc::new(AtomicUsize::new(0));
let calls_a = calls.clone();
let id_a = selector
.get_or_init(|| async move {
calls_a.fetch_add(1, Ordering::SeqCst);
Ok::<_, std::convert::Infallible>(PLUGIN_A.to_owned())
})
.await
.unwrap();
let calls_b = calls.clone();
let id_b = selector
.get_or_init(|| async move {
calls_b.fetch_add(1, Ordering::SeqCst);
Ok::<_, std::convert::Infallible>(PLUGIN_B.to_owned())
})
.await
.unwrap();
assert_eq!(id_a, id_b);
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn reset_triggers_reselection() {
let selector = GtsPluginSelector::new();
let calls = Arc::new(AtomicUsize::new(0));
let calls_a = calls.clone();
let id_a = selector
.get_or_init(|| async move {
calls_a.fetch_add(1, Ordering::SeqCst);
Ok::<_, std::convert::Infallible>(PLUGIN_A.to_owned())
})
.await;
assert_eq!(&*id_a.unwrap(), PLUGIN_A);
assert_eq!(calls.load(Ordering::SeqCst), 1);
assert!(selector.reset().await);
let calls_b = calls.clone();
let id_b = selector
.get_or_init(|| async move {
calls_b.fetch_add(1, Ordering::SeqCst);
Ok::<_, std::convert::Infallible>(PLUGIN_B.to_owned())
})
.await;
assert_eq!(&*id_b.unwrap(), PLUGIN_B);
assert_eq!(calls.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn concurrent_get_or_init_resolves_once() {
let selector = Arc::new(GtsPluginSelector::new());
let calls = Arc::new(AtomicUsize::new(0));
let mut handles = Vec::new();
for _ in 0..10 {
let selector = Arc::clone(&selector);
let calls = Arc::clone(&calls);
handles.push(tokio::spawn(async move {
selector
.get_or_init(|| async {
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
calls.fetch_add(1, Ordering::SeqCst);
Ok::<_, std::convert::Infallible>(CONCURRENT_PLUGIN.to_owned())
})
.await
}));
}
let mut results = Vec::new();
for handle in handles {
results.push(handle.await.unwrap().unwrap());
}
for id in &results {
assert_eq!(&**id, CONCURRENT_PLUGIN);
}
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
mod choose_registered {
use super::*;
use serde_json::{Value, json};
use toolkit_gts::gts_type_schema;
#[derive(Default)]
#[gts_type_schema(
dir_path = "schemas",
base = PluginV1,
type_id = gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~"),
description = "Test plugin specification",
properties = "",
)]
struct TestPluginSpecV1;
#[derive(Default)]
#[gts_type_schema(
dir_path = "schemas",
base = PluginV1,
type_id = gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.other_test.plugin.v1~"),
description = "Other test plugin specification",
properties = "",
)]
struct OtherPluginSpecV1;
trait TestClient: Send + Sync {}
trait OtherClient: Send + Sync {}
struct Client;
impl TestClient for Client {}
impl OtherClient for Client {}
fn instance(name: &str, vendor: &str, priority: i16) -> (String, Value) {
let (id, content) = PluginV1::<TestPluginSpecV1>::build_registration(
&format!("vendor.x.{name}.plugin.v1"),
vendor,
priority,
)
.expect("serializes");
(id.to_string(), content)
}
fn register(hub: &ClientHub, gts_id: &str) {
hub.register_scoped::<dyn TestClient>(ClientScope::gts_id(gts_id), Arc::new(Client));
}
fn choose(
hub: &ClientHub,
listed: &[(String, Option<Value>)],
) -> Result<String, ChoosePluginError> {
choose_registered_plugin_instance::<TestPluginSpecV1, dyn TestClient>(
hub,
"acme",
listed
.iter()
.map(|(id, content)| (id.as_str(), content.as_ref())),
)
}
#[test]
fn unregistered_entries_are_skipped_unexamined() {
let hub = ClientHub::new();
let (missing, _) = instance("missing", "acme", 0);
let (malformed, _) = instance("malformed", "acme", 0);
let (preferred, preferred_content) = instance("preferred", "acme", -10);
let (running, running_content) = instance("running", "acme", 5);
let (elsewhere, elsewhere_content) = instance("elsewhere", "acme", -20);
register(&hub, &running);
hub.register_scoped::<dyn OtherClient>(
ClientScope::gts_id(&elsewhere),
Arc::new(Client),
);
let chosen = choose(
&hub,
&[
(missing, None),
(malformed, Some(json!({ "bogus": true }))),
(preferred, Some(preferred_content)),
(running.clone(), Some(running_content)),
(elsewhere, Some(elsewhere_content)),
],
)
.expect("chooses");
assert_eq!(chosen, running);
}
#[test]
fn the_lowest_registered_priority_of_the_vendor_wins_and_the_first_on_a_tie() {
let hub = ClientHub::new();
let listed: Vec<_> = [
instance("low", "acme", 5),
instance("other_vendor", "other", -5),
instance("tie_first", "acme", 1),
instance("tie_second", "acme", 1),
]
.into_iter()
.map(|(id, content)| {
register(&hub, &id);
(id, Some(content))
})
.collect();
assert_eq!(choose(&hub, &listed).expect("chooses"), listed[2].0);
}
#[test]
fn a_registered_entry_without_content_is_invalid_before_any_is_read() {
let hub = ClientHub::new();
let (malformed, _) = instance("malformed", "acme", 0);
let (missing, _) = instance("missing", "acme", 0);
register(&hub, &malformed);
register(&hub, &missing);
let error = choose(
&hub,
&[
(malformed, Some(json!({ "bogus": true }))),
(missing.clone(), None),
],
)
.expect_err("refused");
assert!(
matches!(&error, ChoosePluginError::InvalidPluginInstance { gts_id, reason }
if *gts_id == missing && reason == "listed without content"),
"{error:?}"
);
}
#[test]
fn a_malformed_or_misnamed_registered_entry_is_invalid() {
let hub = ClientHub::new();
let (malformed, _) = instance("malformed", "other", 0);
let (good, good_content) = instance("good", "acme", 0);
let (misnamed, _) = instance("misnamed", "acme", 0);
for id in [&malformed, &good, &misnamed] {
register(&hub, id);
}
let error = choose(
&hub,
&[
(good, Some(good_content.clone())),
(malformed.clone(), Some(json!({ "bogus": true }))),
],
)
.expect_err("refused");
assert!(
matches!(&error, ChoosePluginError::InvalidPluginInstance { gts_id, .. } if *gts_id == malformed),
"{error:?}"
);
let error =
choose(&hub, &[(misnamed.clone(), Some(good_content))]).expect_err("refused");
assert!(
matches!(&error, ChoosePluginError::InvalidPluginInstance { gts_id, .. } if *gts_id == misnamed),
"{error:?}"
);
}
#[tokio::test]
async fn the_first_selection_after_every_binding_chooses_the_best_bound_plugin() {
let hub = ClientHub::new();
let (fast, fast_content) = instance("fast", "acme", 5);
let (best, best_content) = instance("best", "acme", 1);
register(&hub, &fast);
register(&hub, &best);
let selector = GtsPluginSelector::new();
let listing = vec![
(fast, Some(fast_content)),
(best.clone(), Some(best_content)),
];
let chosen = selector
.get_or_init(|| async { choose(&hub, &listing) })
.await
.expect("chooses");
assert_eq!(&*chosen, best);
}
#[test]
fn a_stale_unbound_instance_is_never_chosen() {
let hub = ClientHub::new();
let (stale, stale_content) = instance("stale", "acme", -100);
let (bound, bound_content) = instance("bound", "acme", 10);
register(&hub, &bound);
let chosen = choose(
&hub,
&[
(stale, Some(stale_content)),
(bound.clone(), Some(bound_content)),
],
)
.expect("chooses");
assert_eq!(chosen, bound);
}
#[test]
fn binding_admitted_instances_binds_only_the_specs_instances() {
let hub = ClientHub::new();
let spec = <TestPluginSpecV1 as gts::GtsSchema>::TYPE_ID;
let (mine, mine_content) = instance("mine", "acme", 1);
let derived = format!("{spec}vendor.x.derived.plugin.v1~vendor.x.mine.plugin.v1");
let derived_schema = format!("{spec}vendor.x.derived.plugin.v1~");
let other = PluginV1::<OtherPluginSpecV1>::build_registration(
"vendor.x.o.plugin.v1",
"acme",
1,
)
.expect("serializes");
let manifest = [
(mine.clone(), mine_content),
(derived.clone(), json!({})),
(derived_schema.clone(), json!({})),
(spec.to_owned(), json!({})),
(other.0.as_ref().to_owned(), other.1),
];
let client: Arc<dyn TestClient> = Arc::new(Client);
let bound = |id: &str| {
hub.try_get_scoped::<dyn TestClient>(&ClientScope::gts_id(id))
.is_some()
};
bind_plugin_instances::<TestPluginSpecV1, dyn TestClient>(&hub, &manifest, &client)
.expect("binds");
assert!(
bound(&mine) && bound(&derived),
"the spec's instances, derived included"
);
assert!(
!bound(&derived_schema) && !bound(spec),
"type schemas are not bound"
);
assert!(
!bound(other.0.as_ref()),
"another spec's instance is not bound"
);
assert!(
bind_plugin_instances::<TestPluginSpecV1, dyn TestClient>(
&hub,
&manifest[2..],
&client
)
.is_err(),
"a manifest without an instance of the spec"
);
let typed_hub = ClientHub::new();
let typed: Vec<(gts::GtsId, serde_json::Value)> = manifest
.iter()
.map(|(id, content)| (gts::GtsId::try_new(id).expect("valid"), content.clone()))
.collect();
bind_plugin_instances::<TestPluginSpecV1, _>(&typed_hub, &typed, &client)
.expect("binds");
let bound = |id: &str| {
typed_hub
.try_get_scoped::<dyn TestClient>(&ClientScope::gts_id(id))
.is_some()
};
assert!(bound(&mine) && bound(&derived));
assert!(!bound(&derived_schema) && !bound(spec) && !bound(other.0.as_ref()));
}
#[test]
fn nothing_registered_is_not_found() {
let (id, content) = instance("listed", "acme", 0);
let error = choose(&ClientHub::new(), &[(id, Some(content))]).expect_err("refused");
assert!(
matches!(error, ChoosePluginError::PluginNotFound { .. }),
"{error:?}"
);
}
}
}
#[cfg(test)]
#[path = "selection_tests.rs"]
mod selection_tests;