Skip to main content

yang_base/definition/
interface.rs

1//! BR 业务术语对应的唯一原生 Addon/Module 注册接口。
2
3use super::{
4    ActionName, ActionRef, ActionSpec, AddonName, AddonSpec, Fields, HttpMethod, ModuleName,
5    ModuleSpec, ParamInput, RouteSpec, TableName, TableSpec, ViewSpec,
6};
7use crate::action::functional::FnAction;
8use crate::action::DynAction;
9use crate::action::{Action as BusinessAction, ActionContext, PermissionMode, TypedAction};
10use crate::error::BaseError;
11use schemars::JsonSchema;
12use serde::de::DeserializeOwned;
13use serde::Serialize;
14use std::future::Future;
15use std::marker::PhantomData;
16use std::sync::Arc;
17
18/// 已原子绑定定义和 Handler 的 Action 集合。
19#[derive(Default)]
20pub struct Actions(Vec<(ActionSpec, Arc<dyn DynAction>)>);
21
22impl Actions {
23    /// 创建空集合。
24    pub const fn new() -> Self {
25        Self(Vec::new())
26    }
27
28    /// 原子增加 Action 定义及 Handler。
29    pub fn action<A>(mut self, spec: ActionSpec, handler: A) -> Self
30    where
31        A: DynAction,
32    {
33        self.0.push((spec, Arc::new(handler)));
34        self
35    }
36
37    /// 从同一个原生 Action 类型原子生成 route/params/权限定义并绑定 Handler。
38    pub fn native<A>(mut self, handler: A) -> Self
39    where
40        A: BusinessAction + TypedAction,
41    {
42        let name = handler.name();
43        let path = if handler.path().is_empty() {
44            format!("/{name}")
45        } else {
46            handler.path().to_string()
47        };
48        let permissions = handler
49            .permissions()
50            .iter()
51            .map(|permission| permission.name().to_string())
52            .collect::<Vec<_>>();
53        let mut spec = ActionSpec::new(
54            super::ActionName::__from_validated_literal(name),
55            super::RouteSpec::new(handler.http_method(), path, name),
56        )
57        .display_name(handler.display_name())
58        .description(handler.description())
59        .permissions(permissions, handler.permission_mode())
60        .public(handler.is_public())
61        .response_kind(handler.response_kind())
62        .success_status(handler.success_status())
63        .params(<A as BusinessAction>::params());
64        if let Some(multipart) = handler.multipart_spec() {
65            spec = spec.multipart(multipart);
66        }
67        for call in handler.calls() {
68            spec = spec.calls(call);
69        }
70        self.0.push((spec, Arc::new(handler)));
71        self
72    }
73
74    pub(crate) fn into_vec(self) -> Vec<(ActionSpec, Arc<dyn DynAction>)> {
75        self.0
76    }
77}
78
79impl std::fmt::Debug for Actions {
80    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        formatter
82            .debug_struct("Actions")
83            .field("len", &self.0.len())
84            .finish()
85    }
86}
87
88impl ModuleSpec {
89    /// 在手写 ModuleSpec 路径中原子注册一个原生 Action。
90    pub fn native_action<A>(self, handler: A) -> Self
91    where
92        A: BusinessAction + TypedAction,
93    {
94        let mut values = Actions::new().native(handler).into_vec();
95        let (mut spec, handler) = values.remove(0);
96        if spec.route.operation_id == spec.name.as_str() {
97            spec.route.operation_id = format!("{}.{}", self.name, spec.name);
98        }
99        self.dyn_action(spec, handler)
100    }
101
102    /// 以一个普通 async fn / 闭包为 Handler 原子注册函数式 Action。
103    ///
104    /// `I`/`O` 由 Handler 签名推断:Handler 形如
105    /// `async fn(ActionContext, I) -> Result<O, BaseError>`;闭包写法必须标注
106    /// 参数类型以便推断 `I`。`I` 通常由 `params!` 生成,从而同时提供强类型输入
107    /// 与唯一原生参数定义。
108    ///
109    /// 默认契约与 [`ModuleSpec::native_action`] 一致:`POST /{name}`,
110    /// `operation_id` 补全为 `<module>.<name>`;其余定义经返回的
111    /// [`ActionFnBuilder`] 声明后由 [`ActionFnBuilder::register`] 终结注册,
112    /// route/params/权限与 Handler 在同一次调用链中原子完成,不存在
113    /// "先注册 spec 再绑 handler" 的两步形态。
114    ///
115    /// # 示例
116    ///
117    /// ```rust,ignore
118    /// ModuleSpec::new(module!("account.user"))
119    ///     .action_fn(ActionName::new("disable")?, disable_user)
120    ///     .route(HttpMethod::Post, "/users/disable")
121    ///     .display_name("停用用户")
122    ///     .permissions(["account.user:write"])
123    ///     .register()
124    /// ```
125    pub fn action_fn<F, I, O, Fut>(self, name: ActionName, handler: F) -> ActionFnBuilder<F, I, O>
126    where
127        F: Fn(ActionContext, I) -> Fut + Send + Sync + 'static,
128        Fut: Future<Output = Result<O, BaseError>> + Send,
129        I: ParamInput + DeserializeOwned + JsonSchema + Send + 'static,
130        O: Serialize + JsonSchema + Send + 'static,
131    {
132        let spec = ActionSpec::new(
133            name.clone(),
134            RouteSpec::new(HttpMethod::Post, format!("/{name}"), name.as_str()),
135        );
136        ActionFnBuilder {
137            module: self,
138            spec,
139            handler,
140            marker: PhantomData,
141        }
142    }
143}
144
145/// 函数式 Action 的终结式注册 Builder。
146///
147/// 由 [`ModuleSpec::action_fn`] 创建,持有半成品 [`ActionSpec`] 与业务函数;
148/// 每个声明方法对应一个 ActionSpec 契约面,终结方法 [`Self::register`]
149/// 一次性完成 params/JSON Schema 填充、operation_id 补全与 Handler 绑定。
150pub struct ActionFnBuilder<F, I, O> {
151    module: ModuleSpec,
152    spec: ActionSpec,
153    handler: F,
154    marker: PhantomData<fn(I) -> O>,
155}
156
157impl<F, I, O> ActionFnBuilder<F, I, O> {
158    /// 覆盖默认路由(`POST /{name}`)。
159    #[must_use]
160    pub fn route(mut self, method: HttpMethod, path: impl Into<String>) -> Self {
161        self.spec.route.method = method;
162        self.spec.route.path = path.into();
163        self
164    }
165
166    /// 设置用户可见名称(默认同 Action 名)。
167    #[must_use]
168    pub fn display_name(mut self, display_name: impl Into<String>) -> Self {
169        self.spec.display_name = display_name.into();
170        self
171    }
172
173    /// 设置业务说明。
174    #[must_use]
175    pub fn description(mut self, description: impl Into<String>) -> Self {
176        self.spec.description = description.into();
177        self
178    }
179
180    /// 设置所需权限列表(默认为空)。
181    #[must_use]
182    pub fn permissions<P, S>(mut self, permissions: P) -> Self
183    where
184        P: IntoIterator<Item = S>,
185        S: Into<String>,
186    {
187        self.spec.permissions = permissions.into_iter().map(Into::into).collect();
188        self
189    }
190
191    /// 设置权限匹配模式(默认 All,即 AND 语义)。
192    #[must_use]
193    pub fn permission_mode(mut self, mode: PermissionMode) -> Self {
194        self.spec.permission_mode = mode;
195        self
196    }
197
198    /// 标记为公开 Action(跳过登录/权限检查);默认非公开。
199    #[must_use]
200    pub fn public(mut self) -> Self {
201        self.spec.is_public = true;
202        self
203    }
204
205    /// 设置成功响应 HTTP 状态码(默认 200)。
206    #[must_use]
207    pub fn success_status(mut self, status: u16) -> Self {
208        self.spec.success_status = status;
209        self
210    }
211
212    /// 声明成功响应的静态类别(默认普通 JSON)。
213    #[must_use]
214    pub fn response_kind(mut self, kind: super::ActionResponseKind) -> Self {
215        self.spec.response_kind = kind;
216        self
217    }
218
219    /// 声明 Action 接受受限的 `multipart/form-data` 请求。
220    #[must_use]
221    pub fn multipart(mut self, multipart: super::MultipartSpec) -> Self {
222        self.spec = self.spec.multipart(multipart);
223        self
224    }
225
226    /// 声明一个内部 Action 调用引用;AppBuilder 在构建期交叉校验。
227    #[must_use]
228    pub fn calls(mut self, action: ActionRef) -> Self {
229        self.spec.calls.push(action);
230        self
231    }
232
233    /// 终结注册:填充 params 与 Input/Output JSON Schema,补全 operation_id,
234    /// 并经 `dyn_action` 把定义与 Handler 原子压入所属 Module。
235    ///
236    /// Schema 在注册期直接由 `schemars::schema_for!` 序列化填充,使
237    /// `bind_handler_contract` 跳过 `DynAction::meta()` 的占位实现;
238    /// 序列化失败会写入 `contract_error`,由 AppBuilder 构建期拒绝。
239    pub fn register<Fut>(mut self) -> ModuleSpec
240    where
241        F: Fn(ActionContext, I) -> Fut + Send + Sync + 'static,
242        Fut: Future<Output = Result<O, BaseError>> + Send,
243        I: ParamInput + DeserializeOwned + JsonSchema + Send + 'static,
244        O: Serialize + JsonSchema + Send + 'static,
245    {
246        self.spec.params = I::params().into_vec();
247        match (
248            serde_json::to_value(schemars::schema_for!(I)),
249            serde_json::to_value(schemars::schema_for!(O)),
250        ) {
251            (Ok(input_schema), Ok(output_schema)) => {
252                self.spec.input_schema = input_schema;
253                self.spec.output_schema = output_schema;
254            }
255            (Err(error), _) | (_, Err(error)) => {
256                self.spec.contract_error = Some(error.to_string());
257            }
258        }
259        let mut spec = self.spec;
260        if spec.route.operation_id == spec.name.as_str() {
261            spec.route.operation_id = format!("{}.{}", self.module.name, spec.name);
262        }
263        self.module
264            .dyn_action(spec, Arc::new(FnAction::<F, I, O>::new(self.handler)))
265    }
266}
267
268/// 原生 Module 集合。
269#[derive(Debug, Clone, Default)]
270pub struct Modules(Vec<ModuleSpec>);
271
272impl Modules {
273    /// 创建空集合。
274    pub const fn new() -> Self {
275        Self(Vec::new())
276    }
277
278    /// 增加已经完成聚合的 Module。
279    pub fn module<M>(mut self, module: M) -> Self
280    where
281        M: Module,
282    {
283        self.0.push(module.into_spec());
284        self
285    }
286
287    pub(crate) fn into_vec(self) -> Vec<ModuleSpec> {
288        self.0
289    }
290}
291
292/// 业务 Module:fields/actions/views 仍集中在同一个实现中。
293pub trait Module: Sized {
294    /// 返回全限定 Module 名。
295    fn name(&self) -> ModuleName;
296
297    /// 返回可选数据库表名。
298    fn table(&self) -> Option<TableName> {
299        None
300    }
301
302    /// 返回主表字段。
303    fn fields(&self) -> Fields {
304        Fields::new()
305    }
306
307    /// 在统一字段投影后补充表标题、复合索引等表级约束。
308    fn configure_table(&self, table: TableSpec) -> TableSpec {
309        table
310    }
311
312    /// 返回 Module Actions。
313    fn actions(&self) -> Actions {
314        Actions::new()
315    }
316
317    /// 返回显式 Views;空集合由构建器生成默认 View。
318    fn views(&self) -> Vec<ViewSpec> {
319        Vec::new()
320    }
321
322    /// 直接聚合为唯一 ModuleSpec,不经过兼容投影。
323    fn into_spec(self) -> ModuleSpec {
324        let module_name = self.name();
325        let mut spec = ModuleSpec::new(module_name.clone());
326        if let Some(table) = self.table() {
327            let table = TableSpec::new(table).fields(self.fields());
328            spec = spec.table(self.configure_table(table));
329        }
330        for (mut action, handler) in self.actions().into_vec() {
331            if action.route.operation_id == action.name.as_str() {
332                action.route.operation_id = format!("{}.{}", module_name, action.name);
333            }
334            spec = spec.dyn_action(action, handler);
335        }
336        for view in self.views() {
337            spec = spec.view(view);
338        }
339        spec
340    }
341}
342
343/// 产品能力 Addon。
344pub trait Addon: Sized {
345    /// 返回 Addon 名。
346    fn name(&self) -> AddonName;
347
348    /// 返回所属 Modules。
349    fn modules(&self) -> Modules;
350
351    /// 返回依赖 Addon 名。
352    fn dependencies(&self) -> Vec<AddonName> {
353        Vec::new()
354    }
355
356    /// 直接聚合为唯一 AddonSpec。
357    fn into_spec(self) -> AddonSpec {
358        let mut spec = AddonSpec::new(self.name());
359        for dependency in self.dependencies() {
360            spec = spec.depends_on(dependency);
361        }
362        for module in self.modules().into_vec() {
363            spec = spec.module(module);
364        }
365        spec
366    }
367}
368
369impl<T> From<T> for AddonSpec
370where
371    T: Addon,
372{
373    fn from(value: T) -> Self {
374        value.into_spec()
375    }
376}