Skip to main content

yang_base/definition/
plugins.rs

1//! 构建期预解析的强类型 Action 调用入口。
2
3use super::{Registry, TypedActionHandle};
4use crate::action::ActionContext;
5use crate::error::BaseError;
6use std::sync::Arc;
7use std::sync::OnceLock;
8
9/// 构建期绑定、请求期仅复制 slot 的强类型内部 Action 引用。
10pub struct ActionLink<I, O> {
11    reference: super::ActionRef,
12    handle: Arc<OnceLock<TypedActionHandle<I, O>>>,
13}
14
15impl<I, O> Clone for ActionLink<I, O> {
16    fn clone(&self) -> Self {
17        Self {
18            reference: self.reference.clone(),
19            handle: Arc::clone(&self.handle),
20        }
21    }
22}
23
24impl<I, O> ActionLink<I, O>
25where
26    I: Send + 'static,
27    O: Send + 'static,
28{
29    /// 声明一个待 AppBuilder 解析的 ActionRef。
30    pub fn new(reference: super::ActionRef) -> Self {
31        Self {
32            reference,
33            handle: Arc::new(OnceLock::new()),
34        }
35    }
36
37    /// 返回定义期引用,供 Action::calls 声明依赖。
38    pub fn reference(&self) -> &super::ActionRef {
39        &self.reference
40    }
41
42    /// 在 AppBuilder 构建期解析并冻结 slot。
43    pub fn bind(&self, registry: &Registry) -> Result<(), BaseError> {
44        let handle = registry.resolve_typed(&self.reference)?;
45        self.handle.set(handle).map_err(|_| {
46            BaseError::ConfigError(format!("ActionLink {} 被重复绑定", self.reference))
47        })
48    }
49
50    /// 请求期取得已绑定 handle;仅执行 OnceLock 读取,不做名称查找。
51    pub fn handle(&self) -> Result<TypedActionHandle<I, O>, BaseError> {
52        self.handle.get().copied().ok_or_else(|| {
53            BaseError::ConfigError(format!("ActionLink {} 尚未绑定", self.reference))
54        })
55    }
56}
57
58/// 请求内的强类型 Action 调用器。
59///
60/// `Plugins` 拥有当前 `ActionContext`,因此用户、租户、request id 与 Tools 会原样
61/// 传给目标 Action。调用使用预解析 slot 和 Rust 值,不经过字符串分派或 JSON。
62pub struct Plugins {
63    registry: Arc<Registry>,
64    context: ActionContext,
65}
66
67impl Plugins {
68    pub(crate) fn new(registry: Arc<Registry>, context: ActionContext) -> Self {
69        Self { registry, context }
70    }
71
72    /// 直接调用预解析 Action。
73    pub async fn api_run<I, O>(
74        self,
75        handle: TypedActionHandle<I, O>,
76        input: I,
77    ) -> Result<O, BaseError>
78    where
79        I: Send + 'static,
80        O: Send + 'static,
81    {
82        self.registry.call(handle, self.context, input).await
83    }
84}