use super::{Registry, TypedActionHandle};
use crate::action::ActionContext;
use crate::error::BaseError;
use std::sync::Arc;
use std::sync::OnceLock;
pub struct ActionLink<I, O> {
reference: super::ActionRef,
handle: Arc<OnceLock<TypedActionHandle<I, O>>>,
}
impl<I, O> Clone for ActionLink<I, O> {
fn clone(&self) -> Self {
Self {
reference: self.reference.clone(),
handle: Arc::clone(&self.handle),
}
}
}
impl<I, O> ActionLink<I, O>
where
I: Send + 'static,
O: Send + 'static,
{
pub fn new(reference: super::ActionRef) -> Self {
Self {
reference,
handle: Arc::new(OnceLock::new()),
}
}
pub fn reference(&self) -> &super::ActionRef {
&self.reference
}
pub fn bind(&self, registry: &Registry) -> Result<(), BaseError> {
let handle = registry.resolve_typed(&self.reference)?;
self.handle.set(handle).map_err(|_| {
BaseError::ConfigError(format!("ActionLink {} 被重复绑定", self.reference))
})
}
pub fn handle(&self) -> Result<TypedActionHandle<I, O>, BaseError> {
self.handle.get().copied().ok_or_else(|| {
BaseError::ConfigError(format!("ActionLink {} 尚未绑定", self.reference))
})
}
}
pub struct Plugins {
registry: Arc<Registry>,
context: ActionContext,
}
impl Plugins {
pub(crate) fn new(registry: Arc<Registry>, context: ActionContext) -> Self {
Self { registry, context }
}
pub async fn api_run<I, O>(
self,
handle: TypedActionHandle<I, O>,
input: I,
) -> Result<O, BaseError>
where
I: Send + 'static,
O: Send + 'static,
{
self.registry.call(handle, self.context, input).await
}
}