Skip to main content

yang_base/definition/builder/
registry.rs

1//! Registry:ActionRef 到稳定运行时 slot 的不可变映射、dispatch 与请求级 UI 目录投影。
2
3use crate::action::{ActionContext, ApiResponse, DynAction, ResponseAttachment};
4use crate::definition::ActionRef;
5use crate::error::BaseError;
6use crate::router::middleware::{authorize, AuthorizationPolicy, Next};
7use crate::table::TableDefinition;
8use std::any::TypeId;
9use std::collections::{BTreeMap, HashSet};
10use std::fmt;
11use std::marker::PhantomData;
12use std::sync::Arc;
13
14use super::handle::{ActionHandle, TypedActionHandle};
15use super::project::{
16    column_readable, form_field, project_table_query, project_tree, table_column_schema,
17};
18
19/// ActionRef 到稳定运行时 slot 的不可变映射。
20#[derive(Clone, Default)]
21pub struct Registry {
22    pub(super) actions: BTreeMap<ActionRef, ActionHandle>,
23    pub(super) handlers: Vec<RuntimeAction>,
24    pub(super) table_views: Vec<RuntimeTableView>,
25    pub(super) modules: Vec<RuntimeModule>,
26    /// `module_id` → `table_views` 下标(升序)。构建期一次性预索引,
27    /// 使 Module→View 投影从请求期 O(M×V) 全扫降为 O(M + 命中数) 查表。
28    pub(super) views_by_module: BTreeMap<String, Vec<usize>>,
29}
30
31#[derive(Clone)]
32pub(super) struct RuntimeAction {
33    pub(super) handler: Arc<dyn DynAction>,
34    pub(super) middlewares: Arc<[Arc<dyn crate::router::Middleware>]>,
35    pub(super) policy: AuthorizationPolicy,
36    pub(super) module: String,
37    pub(super) action: String,
38    /// 与同表其它 Action 共享的表定义;`TableDefinition::clone` 只是 `Arc<TableConfig>` bump。
39    pub(super) table_definition: Option<Arc<TableDefinition>>,
40    /// 本次 Action 所属模块的默认逻辑数据源。
41    pub(super) datasource: Option<crate::datasource::DatasourceId>,
42    pub(super) ui_schema: crate::definition::ActionDemoSchema,
43}
44
45#[derive(Clone)]
46pub(super) struct RuntimeTableView {
47    pub(super) module: String,
48    pub(super) view_id: String,
49    pub(super) title: String,
50    /// 逻辑数据源;同名表可能同时存在于多个源,UI 必须能区分。
51    pub(super) datasource: crate::datasource::DatasourceId,
52    pub(super) table: String,
53    pub(super) columns: Arc<[RuntimeTableColumn]>,
54    pub(super) data_action: Option<ActionHandle>,
55    pub(super) actions: Arc<[RuntimeViewAction]>,
56    pub(super) tree: Option<RuntimeTreeView>,
57    pub(super) default_sort: Arc<[RuntimeTableSort]>,
58    pub(super) policy: AuthorizationPolicy,
59}
60
61#[derive(Clone)]
62pub(super) struct RuntimeTreeView {
63    pub(super) schema: crate::definition::TreeViewSchema,
64    pub(super) fields: [RuntimeTableColumn; 3],
65}
66
67#[derive(Clone)]
68pub(super) struct RuntimeTableSort {
69    pub(super) schema: crate::definition::TableSortSchema,
70    pub(super) column: RuntimeTableColumn,
71}
72
73#[derive(Clone)]
74pub(super) struct RuntimeViewAction {
75    pub(super) handle: ActionHandle,
76    pub(super) presentation: crate::definition::ActionPresentationSpec,
77}
78
79#[derive(Clone)]
80pub(super) struct RuntimeTableColumn {
81    pub(super) schema: crate::definition::TableColumnSchema,
82    pub(super) relation: Option<RuntimeRelationOptions>,
83    pub(super) validation: Option<crate::definition::FormFieldValidationSchema>,
84    pub(super) readable: crate::definition::AccessRule,
85    pub(super) writable: crate::definition::AccessRule,
86    pub(super) secret: bool,
87    pub(super) server_managed: bool,
88}
89
90#[derive(Clone)]
91pub(super) struct RuntimeRelationOptions {
92    pub(super) schema: crate::definition::RelationOptionsSchema,
93    pub(super) policy: AuthorizationPolicy,
94}
95
96impl fmt::Debug for Registry {
97    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
98        formatter
99            .debug_struct("Registry")
100            .field("actions", &self.actions)
101            .field("handler_count", &self.handlers.len())
102            .finish()
103    }
104}
105
106impl Registry {
107    /// 解析构建期已验证的 Action 引用。
108    pub fn resolve(&self, action: &ActionRef) -> Option<ActionHandle> {
109        self.actions.get(action).copied()
110    }
111
112    /// 解析并校验强类型内部调用句柄。
113    pub fn resolve_typed<I, O>(
114        &self,
115        action: &ActionRef,
116    ) -> Result<TypedActionHandle<I, O>, BaseError>
117    where
118        I: Send + 'static,
119        O: Send + 'static,
120    {
121        let raw = self
122            .resolve(action)
123            .ok_or_else(|| BaseError::ActionNotFound(action.to_string()))?;
124        let runtime = self
125            .handlers
126            .get(raw.slot())
127            .ok_or_else(|| BaseError::ActionNotFound(action.to_string()))?;
128        if runtime.handler.input_type_id() != TypeId::of::<I>()
129            || runtime.handler.output_type_id() != TypeId::of::<O>()
130        {
131            return Err(BaseError::ConfigError(format!(
132                "Action {action} 的内部调用类型不匹配"
133            )));
134        }
135        Ok(TypedActionHandle {
136            raw,
137            marker: PhantomData,
138        })
139    }
140
141    /// 返回 Action 总数。
142    pub fn len(&self) -> usize {
143        self.actions.len()
144    }
145
146    /// Registry 是否为空。
147    pub fn is_empty(&self) -> bool {
148        self.actions.is_empty()
149    }
150
151    /// 返回预绑定 Handler;无效 handle 稳定返回 ActionNotFound。
152    pub fn handler(&self, handle: ActionHandle) -> Result<&dyn DynAction, BaseError> {
153        self.handlers
154            .get(handle.slot())
155            .map(|runtime| runtime.handler.as_ref())
156            .ok_or_else(|| BaseError::ActionNotFound(format!("slot {}", handle.slot())))
157    }
158
159    /// 为 Module→View 投影预建立 `module_id` 索引(HashSet 的可见性过滤仍留在请求期)。
160    ///
161    /// 必须在 `table_views` 冻结之后调用;按下标升序 push,保证每模块内 view
162    /// 顺序与旧的请求期全扫实现逐位一致。
163    pub(super) fn reindex_views_by_module(&mut self) {
164        let mut index: BTreeMap<String, Vec<usize>> = BTreeMap::new();
165        for (position, view) in self.table_views.iter().enumerate() {
166            index.entry(view.module.clone()).or_default().push(position);
167        }
168        self.views_by_module = index;
169    }
170
171    pub(crate) fn ui_catalog(
172        &self,
173        context: &ActionContext,
174    ) -> Result<crate::definition::UiCatalog, BaseError> {
175        let actions = self
176            .handlers
177            .iter()
178            .filter(|runtime| runtime.policy.allows(context))
179            .map(|runtime| runtime.ui_schema.clone());
180        let table_views = self
181            .table_views
182            .iter()
183            .filter(|view| view.policy.allows(context))
184            .filter_map(|view| {
185                let data_runtime = view
186                    .data_action
187                    .and_then(|handle| self.handlers.get(handle.slot()))
188                    .filter(|runtime| runtime.policy.allows(context))?;
189                let allowed_actions = view
190                    .actions
191                    .iter()
192                    .filter_map(|action| {
193                        self.handlers
194                            .get(action.handle.slot())
195                            .filter(|runtime| runtime.policy.allows(context))
196                            .map(|runtime| (runtime, &action.presentation))
197                    })
198                    .collect::<Vec<_>>();
199                Some(crate::definition::TableViewSchema {
200                    view_id: view.view_id.clone(),
201                    title: view.title.clone(),
202                    datasource: view.datasource.to_string(),
203                    table: view.table.clone(),
204                    data_action: data_runtime.ui_schema.operation_id.clone(),
205                    columns: view
206                        .columns
207                        .iter()
208                        .filter(|column| column_readable(column, context))
209                        .map(|column| table_column_schema(column, context))
210                        .collect(),
211                    form: crate::definition::FormSchema {
212                        fields: view
213                            .columns
214                            .iter()
215                            .filter_map(|column| form_field(column, context))
216                            .collect(),
217                    },
218                    tree: project_tree(view, context),
219                    query: project_table_query(view, context),
220                    actions: allowed_actions
221                        .iter()
222                        .map(|(runtime, _)| runtime.ui_schema.operation_id.clone())
223                        .collect(),
224                    action_presentations: allowed_actions
225                        .into_iter()
226                        .map(|(runtime, presentation)| {
227                            crate::definition::ActionPresentationSchema {
228                                operation_id: runtime.ui_schema.operation_id.clone(),
229                                title: runtime.ui_schema.title.clone(),
230                                placement: presentation.placement,
231                                interaction: presentation.interaction,
232                                confirmation: presentation.confirmation.clone(),
233                                availability: presentation.availability.clone(),
234                                view_id: presentation.view_id.clone(),
235                                record_parameter: presentation.record_parameter.clone(),
236                            }
237                        })
238                        .collect(),
239                })
240            });
241        let table_views = table_views.collect::<Vec<_>>();
242        let visible_views = table_views
243            .iter()
244            .map(|view| view.view_id.clone())
245            .collect::<HashSet<_>>();
246        let modules = self.modules.iter().filter_map(|module| {
247            let primary_action = module
248                .primary_action
249                .and_then(|handle| self.handlers.get(handle.slot()))
250                .filter(|runtime| runtime.policy.allows(context))
251                .map(|runtime| runtime.ui_schema.operation_id.clone());
252            if module.primary_action.is_some() && primary_action.is_none() {
253                return None;
254            }
255            let allowed_actions = module
256                .actions
257                .iter()
258                .filter_map(|action| {
259                    self.handlers
260                        .get(action.handle.slot())
261                        .filter(|runtime| runtime.policy.allows(context))
262                        .map(|runtime| (runtime, &action.presentation))
263                })
264                .collect::<Vec<_>>();
265            let views = self
266                .views_by_module
267                .get(&module.module_id)
268                .into_iter()
269                .flatten()
270                .map(|position| &self.table_views[*position])
271                .filter(|view| visible_views.contains(&view.view_id))
272                .map(|view| view.view_id.clone())
273                .collect::<Vec<_>>();
274            if primary_action.is_none() && allowed_actions.is_empty() && views.is_empty() {
275                return None;
276            }
277            Some(crate::definition::ModulePresentationSchema {
278                module_id: module.module_id.clone(),
279                identity: module.identity.clone(),
280                title: module.title.clone(),
281                description: module.description.clone(),
282                icon: module.icon.clone(),
283                order: module.order,
284                app_route: module.app_route.clone(),
285                primary_action,
286                actions: allowed_actions
287                    .iter()
288                    .map(|(runtime, _)| runtime.ui_schema.operation_id.clone())
289                    .collect(),
290                action_presentations: allowed_actions
291                    .into_iter()
292                    .map(
293                        |(runtime, presentation)| crate::definition::ActionPresentationSchema {
294                            operation_id: runtime.ui_schema.operation_id.clone(),
295                            title: runtime.ui_schema.title.clone(),
296                            placement: presentation.placement,
297                            interaction: presentation.interaction,
298                            confirmation: presentation.confirmation.clone(),
299                            availability: presentation.availability.clone(),
300                            view_id: presentation.view_id.clone(),
301                            record_parameter: presentation.record_parameter.clone(),
302                        },
303                    )
304                    .collect(),
305                views,
306            })
307        });
308        crate::definition::UiCatalog::from_parts(actions, table_views, modules)
309    }
310
311    /// 通过构建期 handle 执行唯一预绑定 Handler。
312    pub async fn dispatch(
313        &self,
314        handle: ActionHandle,
315        mut context: ActionContext,
316    ) -> Result<ApiResponse, BaseError> {
317        use tracing::Instrument;
318
319        let runtime = self
320            .handlers
321            .get(handle.slot())
322            .ok_or_else(|| BaseError::ActionNotFound(format!("slot {}", handle.slot())))?;
323        context = context.with_dispatch_target(runtime.module.clone(), runtime.action.clone());
324        context = context.with_datasource(runtime.datasource.clone());
325        if let Some(table) = &runtime.table_definition {
326            context = context.with_table_definition((**table).clone());
327        }
328        let next = Next {
329            remaining: &runtime.middlewares,
330            action: Arc::clone(&runtime.handler),
331            policy: &runtime.policy,
332        };
333        let span = tracing::info_span!(
334            "dispatch",
335            operation = %runtime.ui_schema.operation_id,
336            module = %runtime.module,
337            action = %runtime.action,
338            request_id = tracing::field::Empty,
339            actor_id = tracing::field::Empty,
340            tenant_scope = tracing::field::Empty,
341            tenant_id = tracing::field::Empty,
342            result = tracing::field::Empty,
343            error_code = tracing::field::Empty,
344            duration_ms = tracing::field::Empty,
345        );
346        span.record("request_id", tracing::field::display(context.request_id));
347        let result = next.run(context).instrument(span).await;
348        if let Ok(response) = &result {
349            warn_response_kind_mismatch(runtime, response);
350        }
351        result
352    }
353
354    /// 使用强类型输入直接调用预解析 Action;不发生 JSON 序列化或名称查找。
355    ///
356    /// # 约束范围(重要)
357    ///
358    /// 内部调用**不经过中间件链**:`StepUpMiddleware`、租户解析等中间件仅在
359    /// [`Registry::dispatch`] 路径执行,本方法(以及 `Plugins::api_run`)只做
360    /// 权限校验后直接调用 Handler。敏感 Action 的 step-up 因此不约束内部调用;
361    /// 调用方是受信代码,如需重认证必须自行编排 `StepUpManager`。该语义由
362    /// `internal_call_bypasses_step_up_middleware_by_design` 测试锁定。
363    pub async fn call<I, O>(
364        &self,
365        handle: TypedActionHandle<I, O>,
366        mut context: ActionContext,
367        input: I,
368    ) -> Result<O, BaseError>
369    where
370        I: Send + 'static,
371        O: Send + 'static,
372    {
373        let runtime = self
374            .handlers
375            .get(handle.raw.slot())
376            .ok_or_else(|| BaseError::ActionNotFound(format!("slot {}", handle.raw.slot())))?;
377        authorize(&runtime.policy, &context)?;
378        context = context.with_dispatch_target(runtime.module.clone(), runtime.action.clone());
379        context = context.with_datasource(runtime.datasource.clone());
380        if let Some(table) = &runtime.table_definition {
381            context = context.with_table_definition((**table).clone());
382        }
383        let output = runtime.handler.call_boxed(context, Box::new(input)).await?;
384        output.downcast::<O>().map(|value| *value).map_err(|_| {
385            BaseError::ConfigError(format!(
386                "Action {}.{} 的内部调用输出类型不匹配",
387                runtime.module, runtime.action
388            ))
389        })
390    }
391}
392
393#[derive(Clone)]
394pub(super) struct RuntimeModule {
395    pub(super) app_route: Option<String>,
396    pub(super) module_id: String,
397    pub(super) identity: crate::definition::AccountIdentitySchema,
398    pub(super) title: String,
399    pub(super) description: String,
400    pub(super) icon: String,
401    pub(super) order: i32,
402    pub(super) primary_action: Option<ActionHandle>,
403    pub(super) actions: Arc<[RuntimeViewAction]>,
404}
405
406/// 比对运行时响应与 Action 声明的 `response_kind`,不一致时仅告警。
407///
408/// `response_kind` 是前端契约(UI 目录/OpenAPI 的投影来源),运行时附件才是真实响应;
409/// 两者脱节属于 Action 实现与声明不符的契约缺陷,但不应升级为可用性故障,
410/// 因此只 `warn`、不阻断、不改变响应。错误响应没有成功响应契约可比,跳过检查。
411fn warn_response_kind_mismatch(runtime: &RuntimeAction, response: &ApiResponse) {
412    let actual = match &response.attachment {
413        Some(ResponseAttachment::Download { .. }) => {
414            crate::definition::ActionResponseKind::Download
415        }
416        Some(ResponseAttachment::Preview { .. }) => crate::definition::ActionResponseKind::Preview,
417        Some(ResponseAttachment::Redirect { .. }) => {
418            crate::definition::ActionResponseKind::Redirect
419        }
420        // Raw 的 body 就是 JSON 文本,与声明 Json 的 Action 一致,不触发告警
421        Some(ResponseAttachment::Raw { .. }) => crate::definition::ActionResponseKind::Json,
422        None => crate::definition::ActionResponseKind::Json,
423    };
424    let declared = runtime.ui_schema.response_kind;
425    if declared != actual {
426        tracing::warn!(
427            module = %runtime.module,
428            action = %runtime.action,
429            declared = ?declared,
430            actual = ?actual,
431            "Action 声明的 response_kind 与运行时实际响应类别不一致"
432        );
433    }
434}