Skip to main content

yang_base/definition/
builder.rs

1//! App 定义构建、交叉校验与运行时 slot 预解析。
2
3use super::{
4    ActionRef, AddonSpec, BuildError, FieldKind, FieldRef, ModuleName, ParamSource, TableName,
5};
6use crate::action::{ActionContext, ApiResponse, DynAction, Request, ResponseAttachment};
7use crate::error::BaseError;
8use crate::router::middleware::{
9    authorize, AuthorizationPolicy, MiddlewareRole, Next, PermissionGroup,
10};
11use crate::table::{RelationOptionsRequest, RelationOptionsResponse, TableDefinition};
12use crate::tools::Tools;
13use std::any::TypeId;
14use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
15use std::fmt;
16use std::marker::PhantomData;
17use std::sync::Arc;
18
19/// 已预解析的 Action Registry slot。
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub struct ActionHandle(usize);
22
23impl ActionHandle {
24    /// 返回稳定 slot 索引。
25    pub const fn slot(self) -> usize {
26        self.0
27    }
28}
29
30/// 带 Input/Output 类型信息的预解析内部调用句柄。
31#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
32pub struct TypedActionHandle<I, O> {
33    raw: ActionHandle,
34    marker: PhantomData<fn(I) -> O>,
35}
36
37impl<I, O> Copy for TypedActionHandle<I, O> {}
38
39impl<I, O> Clone for TypedActionHandle<I, O> {
40    fn clone(&self) -> Self {
41        *self
42    }
43}
44
45impl<I, O> TypedActionHandle<I, O> {
46    /// 返回底层稳定 slot。
47    pub const fn raw(self) -> ActionHandle {
48        self.raw
49    }
50}
51
52/// 构建期产生的确定性只读定义快照。
53#[derive(Debug, Clone, PartialEq, Eq, Default)]
54pub struct DefinitionCatalog {
55    addons: Vec<AddonSpec>,
56}
57
58impl DefinitionCatalog {
59    /// 按名称稳定排序的 Addon 定义。
60    pub fn addons(&self) -> &[AddonSpec] {
61        &self.addons
62    }
63
64    /// 返回按稳定注册顺序排列的原生表定义。
65    pub fn tables(&self) -> impl Iterator<Item = &super::TableSpec> {
66        self.addons
67            .iter()
68            .flat_map(|addon| &addon.modules)
69            .filter_map(|module| module.table.as_ref())
70    }
71}
72
73/// ActionRef 到稳定运行时 slot 的不可变映射。
74#[derive(Clone, Default)]
75pub struct Registry {
76    actions: BTreeMap<ActionRef, ActionHandle>,
77    handlers: Vec<RuntimeAction>,
78    table_views: Vec<RuntimeTableView>,
79}
80
81#[derive(Clone)]
82struct RuntimeAction {
83    handler: Arc<dyn DynAction>,
84    middlewares: Arc<[Arc<dyn crate::router::Middleware>]>,
85    policy: AuthorizationPolicy,
86    module: String,
87    action: String,
88    table_definition: Option<TableDefinition>,
89    ui_schema: super::ActionDemoSchema,
90}
91
92#[derive(Clone)]
93struct RuntimeTableView {
94    view_id: String,
95    title: String,
96    table: String,
97    columns: Arc<[RuntimeTableColumn]>,
98    data_action: Option<ActionHandle>,
99    actions: Arc<[RuntimeViewAction]>,
100    tree: Option<RuntimeTreeView>,
101    default_sort: Arc<[RuntimeTableSort]>,
102    policy: AuthorizationPolicy,
103}
104
105#[derive(Clone)]
106struct RuntimeTreeView {
107    schema: super::TreeViewSchema,
108    fields: [RuntimeTableColumn; 3],
109}
110
111#[derive(Clone)]
112struct RuntimeTableSort {
113    schema: super::TableSortSchema,
114    column: RuntimeTableColumn,
115}
116
117#[derive(Clone)]
118struct RuntimeViewAction {
119    handle: ActionHandle,
120    presentation: super::ActionPresentationSpec,
121}
122
123#[derive(Clone)]
124struct RuntimeTableColumn {
125    schema: super::TableColumnSchema,
126    relation: Option<RuntimeRelationOptions>,
127    validation: Option<super::FormFieldValidationSchema>,
128    readable: super::AccessRule,
129    writable: super::AccessRule,
130    secret: bool,
131    server_managed: bool,
132}
133
134#[derive(Clone)]
135struct RuntimeRelationOptions {
136    schema: super::RelationOptionsSchema,
137    policy: AuthorizationPolicy,
138}
139
140impl fmt::Debug for Registry {
141    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
142        formatter
143            .debug_struct("Registry")
144            .field("actions", &self.actions)
145            .field("handler_count", &self.handlers.len())
146            .finish()
147    }
148}
149
150impl Registry {
151    /// 解析构建期已验证的 Action 引用。
152    pub fn resolve(&self, action: &ActionRef) -> Option<ActionHandle> {
153        self.actions.get(action).copied()
154    }
155
156    /// 解析并校验强类型内部调用句柄。
157    pub fn resolve_typed<I, O>(
158        &self,
159        action: &ActionRef,
160    ) -> Result<TypedActionHandle<I, O>, BaseError>
161    where
162        I: Send + 'static,
163        O: Send + 'static,
164    {
165        let raw = self
166            .resolve(action)
167            .ok_or_else(|| BaseError::ActionNotFound(action.to_string()))?;
168        let runtime = self
169            .handlers
170            .get(raw.slot())
171            .ok_or_else(|| BaseError::ActionNotFound(action.to_string()))?;
172        if runtime.handler.input_type_id() != TypeId::of::<I>()
173            || runtime.handler.output_type_id() != TypeId::of::<O>()
174        {
175            return Err(BaseError::ConfigError(format!(
176                "Action {action} 的内部调用类型不匹配"
177            )));
178        }
179        Ok(TypedActionHandle {
180            raw,
181            marker: PhantomData,
182        })
183    }
184
185    /// 返回 Action 总数。
186    pub fn len(&self) -> usize {
187        self.actions.len()
188    }
189
190    /// Registry 是否为空。
191    pub fn is_empty(&self) -> bool {
192        self.actions.is_empty()
193    }
194
195    /// 返回预绑定 Handler;无效 handle 稳定返回 ActionNotFound。
196    pub fn handler(&self, handle: ActionHandle) -> Result<&dyn DynAction, BaseError> {
197        self.handlers
198            .get(handle.slot())
199            .map(|runtime| runtime.handler.as_ref())
200            .ok_or_else(|| BaseError::ActionNotFound(format!("slot {}", handle.slot())))
201    }
202
203    pub(crate) fn ui_catalog(
204        &self,
205        context: &ActionContext,
206    ) -> Result<super::UiCatalog, BaseError> {
207        let actions = self
208            .handlers
209            .iter()
210            .filter(|runtime| runtime.policy.allows(context))
211            .map(|runtime| runtime.ui_schema.clone());
212        let table_views = self
213            .table_views
214            .iter()
215            .filter(|view| view.policy.allows(context))
216            .filter_map(|view| {
217                let data_runtime = view
218                    .data_action
219                    .and_then(|handle| self.handlers.get(handle.slot()))
220                    .filter(|runtime| runtime.policy.allows(context))?;
221                let allowed_actions = view
222                    .actions
223                    .iter()
224                    .filter_map(|action| {
225                        self.handlers
226                            .get(action.handle.slot())
227                            .filter(|runtime| runtime.policy.allows(context))
228                            .map(|runtime| (runtime, &action.presentation))
229                    })
230                    .collect::<Vec<_>>();
231                Some(super::TableViewSchema {
232                    view_id: view.view_id.clone(),
233                    title: view.title.clone(),
234                    table: view.table.clone(),
235                    data_action: data_runtime.ui_schema.operation_id.clone(),
236                    columns: view
237                        .columns
238                        .iter()
239                        .filter(|column| column_readable(column, context))
240                        .map(|column| table_column_schema(column, context))
241                        .collect(),
242                    form: super::FormSchema {
243                        fields: view
244                            .columns
245                            .iter()
246                            .filter_map(|column| form_field(column, context))
247                            .collect(),
248                    },
249                    tree: project_tree(view, context),
250                    query: project_table_query(view, context),
251                    actions: allowed_actions
252                        .iter()
253                        .map(|(runtime, _)| runtime.ui_schema.operation_id.clone())
254                        .collect(),
255                    action_presentations: allowed_actions
256                        .into_iter()
257                        .map(|(runtime, presentation)| super::ActionPresentationSchema {
258                            operation_id: runtime.ui_schema.operation_id.clone(),
259                            title: runtime.ui_schema.title.clone(),
260                            placement: presentation.placement,
261                            interaction: presentation.interaction,
262                            confirmation: presentation.confirmation.clone(),
263                            availability: presentation.availability.clone(),
264                            view_id: presentation.view_id.clone(),
265                        })
266                        .collect(),
267                })
268            });
269        super::UiCatalog::new(actions)?.with_table_views(table_views)
270    }
271
272    /// 通过构建期 handle 执行唯一预绑定 Handler。
273    pub async fn dispatch(
274        &self,
275        handle: ActionHandle,
276        mut context: ActionContext,
277    ) -> Result<ApiResponse, BaseError> {
278        use tracing::Instrument;
279
280        let runtime = self
281            .handlers
282            .get(handle.slot())
283            .ok_or_else(|| BaseError::ActionNotFound(format!("slot {}", handle.slot())))?;
284        context = context.with_dispatch_target(runtime.module.clone(), runtime.action.clone());
285        if let Some(table) = &runtime.table_definition {
286            context = context.with_table_definition(table.clone());
287        }
288        let next = Next {
289            remaining: &runtime.middlewares,
290            action: Arc::clone(&runtime.handler),
291            policy: &runtime.policy,
292        };
293        let span = tracing::info_span!(
294            "dispatch",
295            module = %runtime.module,
296            action = %runtime.action,
297            request_id = tracing::field::Empty,
298        );
299        span.record("request_id", tracing::field::display(context.request_id));
300        let result = next.run(context).instrument(span).await;
301        if let Ok(response) = &result {
302            warn_response_kind_mismatch(runtime, response);
303        }
304        result
305    }
306
307    /// 使用强类型输入直接调用预解析 Action;不发生 JSON 序列化或名称查找。
308    ///
309    /// # 约束范围(重要)
310    ///
311    /// 内部调用**不经过中间件链**:`StepUpMiddleware`、租户解析等中间件仅在
312    /// [`Registry::dispatch`] 路径执行,本方法(以及 `Plugins::api_run`)只做
313    /// 权限校验后直接调用 Handler。敏感 Action 的 step-up 因此不约束内部调用;
314    /// 调用方是受信代码,如需重认证必须自行编排 `StepUpManager`。该语义由
315    /// `internal_call_bypasses_step_up_middleware_by_design` 测试锁定。
316    pub async fn call<I, O>(
317        &self,
318        handle: TypedActionHandle<I, O>,
319        mut context: ActionContext,
320        input: I,
321    ) -> Result<O, BaseError>
322    where
323        I: Send + 'static,
324        O: Send + 'static,
325    {
326        let runtime = self
327            .handlers
328            .get(handle.raw.slot())
329            .ok_or_else(|| BaseError::ActionNotFound(format!("slot {}", handle.raw.slot())))?;
330        authorize(&runtime.policy, &context)?;
331        context = context.with_dispatch_target(runtime.module.clone(), runtime.action.clone());
332        if let Some(table) = &runtime.table_definition {
333            context = context.with_table_definition(table.clone());
334        }
335        let output = runtime.handler.call_boxed(context, Box::new(input)).await?;
336        output.downcast::<O>().map(|value| *value).map_err(|_| {
337            BaseError::ConfigError(format!(
338                "Action {}.{} 的内部调用输出类型不匹配",
339                runtime.module, runtime.action
340            ))
341        })
342    }
343}
344
345/// 比对运行时响应与 Action 声明的 `response_kind`,不一致时仅告警。
346///
347/// `response_kind` 是前端契约(UI 目录/OpenAPI 的投影来源),运行时附件才是真实响应;
348/// 两者脱节属于 Action 实现与声明不符的契约缺陷,但不应升级为可用性故障,
349/// 因此只 `warn`、不阻断、不改变响应。错误响应没有成功响应契约可比,跳过检查。
350fn warn_response_kind_mismatch(runtime: &RuntimeAction, response: &ApiResponse) {
351    let actual = match &response.attachment {
352        Some(ResponseAttachment::Download { .. }) => super::ActionResponseKind::Download,
353        Some(ResponseAttachment::Preview { .. }) => super::ActionResponseKind::Preview,
354        Some(ResponseAttachment::Redirect { .. }) => super::ActionResponseKind::Redirect,
355        None => super::ActionResponseKind::Json,
356    };
357    let declared = runtime.ui_schema.response_kind;
358    if declared != actual {
359        tracing::warn!(
360            module = %runtime.module,
361            action = %runtime.action,
362            declared = ?declared,
363            actual = ?actual,
364            "Action 声明的 response_kind 与运行时实际响应类别不一致"
365        );
366    }
367}
368
369/// 构建完成且运行期不可变的 App 定义。
370#[derive(Clone)]
371pub struct BuiltApp {
372    catalog: DefinitionCatalog,
373    registry: Arc<Registry>,
374    tools: Arc<Tools>,
375    table_definitions: Vec<TableDefinition>,
376    compiled_views: Vec<super::CompiledTableView>,
377}
378
379impl fmt::Debug for BuiltApp {
380    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
381        formatter
382            .debug_struct("BuiltApp")
383            .field("catalog", &self.catalog)
384            .field("registry", &self.registry)
385            .field("tools", &self.tools)
386            .field("table_definition_count", &self.table_definitions.len())
387            .field("compiled_view_count", &self.compiled_views.len())
388            .finish()
389    }
390}
391
392impl BuiltApp {
393    /// 返回只读定义 Catalog。
394    pub fn catalog(&self) -> &DefinitionCatalog {
395        &self.catalog
396    }
397
398    /// 返回预解析 Registry。
399    pub fn registry(&self) -> &Registry {
400        &self.registry
401    }
402
403    /// 返回当前应用实例显式拥有的冻结资源。
404    pub fn tools(&self) -> &Tools {
405        &self.tools
406    }
407
408    /// 返回从 Catalog 唯一字段事实预编译的数据库 schema 定义。
409    pub fn table_definitions(&self) -> &[TableDefinition] {
410        &self.table_definitions
411    }
412
413    /// 返回启动期解析完成的默认/显式 Table Views。
414    pub fn compiled_views(&self) -> &[super::CompiledTableView] {
415        &self.compiled_views
416    }
417
418    /// 按当前请求的认证身份投影有权访问的版本化 UI 目录。
419    ///
420    /// Action 和 View 均复用 dispatch 的构建期冻结授权策略;TableView 列同时按
421    /// 字段读取角色过滤,secret 字段始终 fail-closed。租户数据范围仍由实际
422    /// TableQuery 独立强制执行,前端目录不能替代服务端数据隔离。
423    pub fn ui_catalog(&self, context: &ActionContext) -> Result<super::UiCatalog, BaseError> {
424        self.registry.ui_catalog(context)
425    }
426
427    /// 为一次请求创建绑定当前应用资源的 ActionContext。
428    pub fn context(&self, request: Request) -> ActionContext {
429        ActionContext::new(request, Arc::clone(&self.tools))
430            .with_registry(Arc::clone(&self.registry))
431    }
432
433    /// 通过启动期解析的 handle 执行请求。
434    pub async fn dispatch(
435        &self,
436        handle: ActionHandle,
437        request: Request,
438    ) -> Result<ApiResponse, BaseError> {
439        self.registry.dispatch(handle, self.context(request)).await
440    }
441
442    /// 执行已由传输层补全元数据的上下文。
443    pub async fn dispatch_context(
444        &self,
445        handle: ActionHandle,
446        context: ActionContext,
447    ) -> Result<ApiResponse, BaseError> {
448        self.registry.dispatch(handle, context).await
449    }
450}
451
452/// 仅在启动期可变的 App 定义构建器。
453#[derive(Debug, Clone, Default)]
454#[must_use = "AppBuilder 必须调用 build() 才会执行交叉校验并冻结定义"]
455pub struct AppBuilder {
456    addons: Vec<AddonSpec>,
457}
458
459impl AppBuilder {
460    /// 创建空构建器。
461    pub fn new() -> Self {
462        Self::default()
463    }
464
465    /// 注册一个原生 Addon 定义。
466    pub fn addon(mut self, addon: impl Into<AddonSpec>) -> Self {
467        self.addons.push(addon.into());
468        self
469    }
470
471    /// 校验全部定义、解析引用并冻结 Catalog/Registry。
472    pub fn build(mut self, tools: impl Into<Arc<Tools>>) -> Result<BuiltApp, BuildError> {
473        validate_unique_addons(&self.addons)?;
474        validate_dependencies(&self.addons)?;
475        validate_module_ownership(&self.addons)?;
476        validate_unique_modules(&self.addons)?;
477        validate_module_contents(&self.addons)?;
478        validate_middleware_order(&self.addons)?;
479        resolve_param_fields(&mut self.addons)?;
480
481        let fields = collect_fields(&self.addons)?;
482        let actions = collect_actions(&self.addons)?;
483        let views = collect_views(&self.addons)?;
484        validate_references(&self.addons, &fields, &actions, &views)?;
485        validate_routes(&self.addons)?;
486
487        sort_definitions(&mut self.addons);
488        let mut registry = build_registry(&self.addons)?;
489        let compiled_views = compile_views(&self.addons, &registry)?;
490        registry.table_views = compile_runtime_table_views(&self.addons, &registry)?;
491        for runtime in &registry.handlers {
492            runtime.handler.bind_registry(&registry).map_err(|error| {
493                BuildError::InvalidReference {
494                    kind: "ActionLink",
495                    reference: error.to_string(),
496                }
497            })?;
498        }
499        let registry = Arc::new(registry);
500        let table_definitions = compile_table_definitions(&self.addons)?;
501        for module in self.addons.iter_mut().flat_map(|addon| &mut addon.modules) {
502            module.clear_handlers();
503        }
504        Ok(BuiltApp {
505            catalog: DefinitionCatalog {
506                addons: self.addons,
507            },
508            registry,
509            tools: tools.into(),
510            table_definitions,
511            compiled_views,
512        })
513    }
514}
515
516fn resolve_param_fields(addons: &mut [AddonSpec]) -> Result<(), BuildError> {
517    let definitions = addons
518        .iter()
519        .flat_map(|addon| &addon.modules)
520        .filter_map(|module| module.table.as_ref())
521        .flat_map(|table| {
522            table.fields.iter().map(move |field| {
523                (
524                    super::FieldRef::new(table.name.clone(), field.name.clone()),
525                    field.clone(),
526                )
527            })
528        })
529        .collect::<BTreeMap<_, _>>();
530
531    for action in addons
532        .iter_mut()
533        .flat_map(|addon| &mut addon.modules)
534        .flat_map(super::ModuleSpec::actions_mut)
535    {
536        for param in &mut action.params {
537            let Some(reference) = &param.field else {
538                continue;
539            };
540            let field = definitions
541                .get(reference)
542                .ok_or_else(|| BuildError::InvalidReference {
543                    kind: "Field",
544                    reference: reference.to_string(),
545                })?;
546            param.kind.get_or_insert(field.kind);
547            param.required |= field.is_required();
548            if param.validation.min_length.is_none() {
549                param.validation.min_length = field.validation.min_length;
550            }
551            if param.validation.max_length.is_none() {
552                param.validation.max_length = field.validation.max_length;
553            }
554            if param.validation.minimum.is_none() {
555                param.validation.minimum = field.validation.minimum.clone();
556            }
557            if param.validation.maximum.is_none() {
558                param.validation.maximum = field.validation.maximum.clone();
559            }
560            if param.validation.pattern.is_none() {
561                param.validation.pattern = field.validation.pattern.clone();
562            }
563            if param.presentation.title.is_empty() {
564                param.presentation.title = field.presentation.title.clone();
565            }
566            if param.presentation.description.is_empty() {
567                param.presentation.description = field.presentation.description.clone();
568            }
569            if param.presentation.widget.is_none() {
570                param.presentation.widget = field.presentation.widget;
571            }
572        }
573    }
574    Ok(())
575}
576
577fn compile_table_definitions(addons: &[AddonSpec]) -> Result<Vec<TableDefinition>, BuildError> {
578    addons
579        .iter()
580        .flat_map(|addon| &addon.modules)
581        .filter_map(|module| module.table.as_ref())
582        .map(|table| {
583            table
584                .table_definition()
585                .map_err(|error| BuildError::InvalidFieldDefinition {
586                    table: table.name.to_string(),
587                    field: "<table>".to_string(),
588                    reason: error.to_string(),
589                })
590        })
591        .collect()
592}
593
594fn compile_views(
595    addons: &[AddonSpec],
596    registry: &Registry,
597) -> Result<Vec<super::CompiledTableView>, BuildError> {
598    let mut compiled = Vec::new();
599    for module in addons.iter().flat_map(|addon| &addon.modules) {
600        let Some(table) = &module.table else {
601            continue;
602        };
603        let table_ref = yang_db::TableRef::new(table.name.to_string()).map_err(|error| {
604            BuildError::InvalidReference {
605                kind: "Table",
606                reference: error.to_string(),
607            }
608        })?;
609        if module.views.is_empty() {
610            let name =
611                super::ViewName::new("default").map_err(|error| BuildError::InvalidReference {
612                    kind: "View",
613                    reference: error.to_string(),
614                })?;
615            let fields = table
616                .fields
617                .iter()
618                .filter(|field| {
619                    !field.access.secret
620                        && !matches!(field.access.readable, super::AccessRule::Nobody)
621                })
622                .map(|field| checked_runtime_field(&table.name, &field.name))
623                .collect::<Result<Vec<_>, _>>()?;
624            compiled.push(super::CompiledTableView::new(
625                module.name.clone(),
626                name,
627                table_ref,
628                fields,
629                None,
630                Vec::new(),
631                None,
632            ));
633            continue;
634        }
635
636        for view in &module.views {
637            let fields = view
638                .fields
639                .iter()
640                .map(|field| checked_runtime_field(field.table(), field.field()))
641                .collect::<Result<Vec<_>, _>>()?;
642            let actions = view
643                .actions
644                .iter()
645                .map(|action| {
646                    registry
647                        .resolve(action)
648                        .ok_or_else(|| BuildError::InvalidReference {
649                            kind: "View Action",
650                            reference: action.to_string(),
651                        })
652                })
653                .collect::<Result<Vec<_>, _>>()?;
654            let data_action = view
655                .data_action
656                .as_ref()
657                .map(|action| {
658                    registry
659                        .resolve(action)
660                        .ok_or_else(|| BuildError::InvalidReference {
661                            kind: "View Data Action",
662                            reference: action.to_string(),
663                        })
664                })
665                .transpose()?;
666            let tree = view
667                .tree
668                .as_ref()
669                .map(|tree| {
670                    Ok(super::CompiledTreeView::new(
671                        checked_runtime_field(tree.id_field.table(), tree.id_field.field())?,
672                        checked_runtime_field(
673                            tree.parent_field.table(),
674                            tree.parent_field.field(),
675                        )?,
676                        checked_runtime_field(tree.label_field.table(), tree.label_field.field())?,
677                        tree.max_nodes
678                            .unwrap_or(crate::table::DEFAULT_TREE_MAX_NODES),
679                    ))
680                })
681                .transpose()?;
682            compiled.push(super::CompiledTableView::new(
683                module.name.clone(),
684                view.name.clone(),
685                table_ref.clone(),
686                fields,
687                data_action,
688                actions,
689                tree,
690            ));
691        }
692    }
693    Ok(compiled)
694}
695
696fn compile_runtime_table_views(
697    addons: &[AddonSpec],
698    registry: &Registry,
699) -> Result<Vec<RuntimeTableView>, BuildError> {
700    let fields = addons
701        .iter()
702        .flat_map(|addon| &addon.modules)
703        .filter_map(|module| module.table.as_ref())
704        .flat_map(|table| {
705            table
706                .fields
707                .iter()
708                .map(move |field| (FieldRef::new(table.name.clone(), field.name.clone()), field))
709        })
710        .collect::<BTreeMap<_, _>>();
711    let mut compiled = Vec::new();
712
713    for module in addons.iter().flat_map(|addon| &addon.modules) {
714        let Some(table) = &module.table else {
715            continue;
716        };
717        let policy = module_view_policy(module);
718        if module.views.is_empty() {
719            let columns = table
720                .fields
721                .iter()
722                .map(|field| runtime_table_column(field, registry))
723                .collect::<Result<Vec<_>, _>>()?;
724            compiled.push(RuntimeTableView {
725                view_id: format!("{}.default", module.name),
726                title: if table.title.is_empty() {
727                    module.name.to_string()
728                } else {
729                    table.title.clone()
730                },
731                table: table.name.to_string(),
732                columns: columns.into(),
733                data_action: None,
734                actions: Arc::from(Vec::new()),
735                tree: None,
736                default_sort: Arc::from(Vec::new()),
737                policy,
738            });
739            continue;
740        }
741
742        for view in &module.views {
743            let columns = view
744                .fields
745                .iter()
746                .map(|reference| {
747                    let field = fields.get(reference).copied().ok_or_else(|| {
748                        BuildError::InvalidReference {
749                            kind: "View Field",
750                            reference: reference.to_string(),
751                        }
752                    })?;
753                    runtime_table_column(field, registry)
754                })
755                .collect::<Result<Vec<_>, _>>()?;
756            let actions = view
757                .actions
758                .iter()
759                .map(|reference| {
760                    let handle = registry.resolve(reference).ok_or_else(|| {
761                        BuildError::InvalidReference {
762                            kind: "View Action",
763                            reference: reference.to_string(),
764                        }
765                    })?;
766                    let runtime = registry.handlers.get(handle.slot()).ok_or_else(|| {
767                        BuildError::InvalidReference {
768                            kind: "View Action",
769                            reference: reference.to_string(),
770                        }
771                    })?;
772                    let presentation = view
773                        .action_presentations
774                        .get(reference)
775                        .cloned()
776                        .unwrap_or_else(|| infer_action_presentation(runtime));
777                    validate_action_presentation(reference, &presentation, runtime)?;
778                    Ok(RuntimeViewAction {
779                        handle,
780                        presentation,
781                    })
782                })
783                .collect::<Result<Vec<_>, _>>()?;
784            let data_action = view
785                .data_action
786                .as_ref()
787                .map(|reference| {
788                    let handle = registry.resolve(reference).ok_or_else(|| {
789                        BuildError::InvalidReference {
790                            kind: "View Data Action",
791                            reference: reference.to_string(),
792                        }
793                    })?;
794                    let runtime = registry.handlers.get(handle.slot()).ok_or_else(|| {
795                        BuildError::InvalidReference {
796                            kind: "View Data Action",
797                            reference: reference.to_string(),
798                        }
799                    })?;
800                    if runtime.ui_schema.response_kind != super::ActionResponseKind::Json {
801                        return Err(BuildError::InvalidReference {
802                            kind: "View Data Action",
803                            reference: format!("{reference}: 数据 Action 必须返回 JSON"),
804                        });
805                    }
806                    Ok(handle)
807                })
808                .transpose()?;
809            let tree = view
810                .tree
811                .as_ref()
812                .map(|tree| {
813                    let column = |reference: &FieldRef| {
814                        let field = fields.get(reference).copied().ok_or_else(|| {
815                            BuildError::InvalidReference {
816                                kind: "Tree View Field",
817                                reference: reference.to_string(),
818                            }
819                        })?;
820                        runtime_table_column(field, registry)
821                    };
822                    Ok(RuntimeTreeView {
823                        schema: super::TreeViewSchema {
824                            id_field: tree.id_field.field().to_string(),
825                            parent_field: tree.parent_field.field().to_string(),
826                            label_field: tree.label_field.field().to_string(),
827                            max_nodes: tree
828                                .max_nodes
829                                .unwrap_or(crate::table::DEFAULT_TREE_MAX_NODES),
830                        },
831                        fields: [
832                            column(&tree.id_field)?,
833                            column(&tree.parent_field)?,
834                            column(&tree.label_field)?,
835                        ],
836                    })
837                })
838                .transpose()?;
839            let mut seen_sort_fields = BTreeSet::new();
840            let default_sort = view
841                .default_sort
842                .iter()
843                .map(|sort| {
844                    if !view.fields.contains(&sort.field) || !seen_sort_fields.insert(&sort.field) {
845                        return Err(BuildError::InvalidReference {
846                            kind: "View Default Sort",
847                            reference: sort.field.to_string(),
848                        });
849                    }
850                    let field = fields.get(&sort.field).copied().ok_or_else(|| {
851                        BuildError::InvalidReference {
852                            kind: "View Default Sort",
853                            reference: sort.field.to_string(),
854                        }
855                    })?;
856                    if !field.access.sortable {
857                        return Err(BuildError::InvalidReference {
858                            kind: "View Default Sort",
859                            reference: format!("{}: 字段未允许排序", sort.field),
860                        });
861                    }
862                    Ok(RuntimeTableSort {
863                        schema: super::TableSortSchema {
864                            field: sort.field.field().to_string(),
865                            direction: sort.direction,
866                        },
867                        column: runtime_table_column(field, registry)?,
868                    })
869                })
870                .collect::<Result<Vec<_>, _>>()?;
871            compiled.push(RuntimeTableView {
872                view_id: format!("{}.{}", module.name, view.name),
873                title: view.title.clone(),
874                table: table.name.to_string(),
875                columns: columns.into(),
876                data_action,
877                actions: actions.into(),
878                tree,
879                default_sort: default_sort.into(),
880                policy: policy.clone(),
881            });
882        }
883    }
884    Ok(compiled)
885}
886
887fn project_tree(view: &RuntimeTableView, context: &ActionContext) -> Option<super::TreeViewSchema> {
888    let tree = view.tree.as_ref()?;
889    tree.fields
890        .iter()
891        .all(|column| column_readable(column, context))
892        .then(|| tree.schema.clone())
893}
894
895fn project_table_query(
896    view: &RuntimeTableView,
897    context: &ActionContext,
898) -> super::TableQuerySchema {
899    let readable_columns = view
900        .columns
901        .iter()
902        .filter(|column| column_readable(column, context));
903    let search_fields = readable_columns
904        .clone()
905        .filter(|column| column.schema.searchable)
906        .map(|column| column.schema.field.clone())
907        .collect();
908    let filter_fields = readable_columns
909        .filter(|column| column.schema.filterable)
910        .map(|column| column.schema.field.clone())
911        .collect();
912    let default_sort = view
913        .default_sort
914        .iter()
915        .filter(|sort| column_readable(&sort.column, context))
916        .map(|sort| sort.schema.clone())
917        .collect();
918    super::TableQuerySchema {
919        search_fields,
920        filter_fields,
921        default_sort,
922        default_page_size: crate::table::DEFAULT_QUERY_PAGE_SIZE,
923        max_page_size: crate::table::MAX_TABLE_QUERY_PAGE_SIZE,
924    }
925}
926
927fn infer_action_presentation(runtime: &RuntimeAction) -> super::ActionPresentationSpec {
928    let interaction = match runtime.ui_schema.response_kind {
929        super::ActionResponseKind::Download => super::ActionInteraction::Download,
930        super::ActionResponseKind::Preview => super::ActionInteraction::Preview,
931        super::ActionResponseKind::Redirect => super::ActionInteraction::Navigate,
932        super::ActionResponseKind::Json => match runtime.ui_schema.method.as_str() {
933            "POST" | "PUT" | "PATCH" => super::ActionInteraction::Form,
934            _ => super::ActionInteraction::Invoke,
935        },
936    };
937    super::ActionPresentationSpec::new(super::ActionPlacement::Toolbar, interaction)
938}
939
940fn validate_action_presentation(
941    action: &ActionRef,
942    presentation: &super::ActionPresentationSpec,
943    runtime: &RuntimeAction,
944) -> Result<(), BuildError> {
945    let invalid = |reason: &str| BuildError::InvalidReference {
946        kind: "Action Presentation",
947        reference: format!("{action}: {reason}"),
948    };
949
950    match (presentation.interaction, presentation.view_id.as_deref()) {
951        (super::ActionInteraction::Custom, Some(view_id)) => {
952            ModuleName::new(view_id).map_err(|_| invalid("custom view_id 必须是稳定限定标识"))?;
953        }
954        (super::ActionInteraction::Custom, None) => {
955            return Err(invalid("custom 交互缺少 view_id"));
956        }
957        (_, Some(_)) => {
958            return Err(invalid("只有 custom 交互可以声明 view_id"));
959        }
960        (_, None) => {}
961    }
962
963    if let Some(confirmation) = &presentation.confirmation {
964        for text in [&confirmation.title, &confirmation.message] {
965            let trimmed = text.trim();
966            if trimmed.is_empty() || trimmed.chars().count() > 500 {
967                return Err(invalid("confirmation title/message 必须在 1..=500 字符"));
968            }
969        }
970    }
971
972    if let Some(availability) = &presentation.availability {
973        let reason = availability.reason.trim();
974        if reason.is_empty() || reason.chars().count() > 500 {
975            return Err(invalid("availability reason 必须在 1..=500 字符"));
976        }
977    }
978
979    let expected_response = match presentation.interaction {
980        super::ActionInteraction::Download => Some(super::ActionResponseKind::Download),
981        super::ActionInteraction::Preview => Some(super::ActionResponseKind::Preview),
982        super::ActionInteraction::Navigate => Some(super::ActionResponseKind::Redirect),
983        super::ActionInteraction::Form | super::ActionInteraction::Invoke => {
984            Some(super::ActionResponseKind::Json)
985        }
986        super::ActionInteraction::Custom => None,
987    };
988    if let Some(expected) = expected_response {
989        if runtime.ui_schema.response_kind != expected {
990            return Err(invalid("交互方式与 Action 响应类型不一致"));
991        }
992    }
993    Ok(())
994}
995
996fn module_view_policy(module: &super::ModuleSpec) -> AuthorizationPolicy {
997    let has_module_permissions = !module.default_permissions.is_empty();
998    let groups = if !has_module_permissions {
999        Vec::new()
1000    } else {
1001        vec![PermissionGroup::new(
1002            "模块",
1003            Arc::<[String]>::from(module.default_permissions.clone()),
1004            module.default_permission_mode,
1005        )]
1006    };
1007    // 模块未声明额外权限时,View 是否可见由其 data_action 的策略决定;否则
1008    // 这里若仍强制登录,会错误隐藏显式 public 的数据页。
1009    AuthorizationPolicy::new(!has_module_permissions, groups)
1010}
1011
1012fn runtime_table_column(
1013    field: &super::FieldSpec,
1014    registry: &Registry,
1015) -> Result<RuntimeTableColumn, BuildError> {
1016    let name = field.name.to_string();
1017    let relation = match (&field.select, &field.relation) {
1018        (Some(select), Some(target)) => {
1019            let handle = registry
1020                .resolve(select)
1021                .ok_or_else(|| BuildError::InvalidReference {
1022                    kind: "Relation Options Action",
1023                    reference: select.to_string(),
1024                })?;
1025            let runtime = registry.handlers.get(handle.slot()).ok_or_else(|| {
1026                BuildError::InvalidReference {
1027                    kind: "Relation Options Action",
1028                    reference: select.to_string(),
1029                }
1030            })?;
1031            // I-4:UI 目录向前端承诺 select Action 讲
1032            // RelationOptionsRequest/RelationOptionsResponse;构建期按 TypeId 强制
1033            // 输入/输出签名,签名不符的 Action 不得接入关系选择器。
1034            if runtime.handler.input_type_id() != TypeId::of::<RelationOptionsRequest>()
1035                || runtime.handler.output_type_id() != TypeId::of::<RelationOptionsResponse>()
1036            {
1037                return Err(BuildError::InvalidReference {
1038                    kind: "Relation Options Action",
1039                    reference: format!(
1040                        "{select}: 输入/输出必须是 RelationOptionsRequest/RelationOptionsResponse"
1041                    ),
1042                });
1043            }
1044            Some(RuntimeRelationOptions {
1045                schema: super::RelationOptionsSchema {
1046                    operation_id: runtime.ui_schema.operation_id.clone(),
1047                    value_field: target.to_string(),
1048                    label_fields: field
1049                        .presentation
1050                        .display
1051                        .iter()
1052                        .map(ToString::to_string)
1053                        .collect(),
1054                },
1055                policy: runtime.policy.clone(),
1056            })
1057        }
1058        (Some(select), None) => {
1059            return Err(BuildError::InvalidReference {
1060                kind: "Relation Options Field",
1061                reference: format!("{}: {select}", field.name),
1062            });
1063        }
1064        (None, _) => None,
1065    };
1066    Ok(RuntimeTableColumn {
1067        schema: super::TableColumnSchema {
1068            title: if field.presentation.title.is_empty() {
1069                name.clone()
1070            } else {
1071                field.presentation.title.clone()
1072            },
1073            field: name,
1074            description: field.presentation.description.clone(),
1075            widget: field.widget_hint(),
1076            required: field.is_required(),
1077            searchable: field.access.searchable,
1078            filterable: field.access.filterable,
1079            sortable: field.access.sortable,
1080            relation: None,
1081        },
1082        relation,
1083        validation: super::FormFieldValidationSchema::from_spec(&field.validation),
1084        readable: field.access.readable.clone(),
1085        writable: field.access.writable.clone(),
1086        secret: field.access.secret,
1087        server_managed: field.kind == FieldKind::Key
1088            || (field.kind == FieldKind::Timestamp
1089                && field.timestamp_mode != super::TimestampMode::Value),
1090    })
1091}
1092
1093fn table_column_schema(
1094    column: &RuntimeTableColumn,
1095    context: &ActionContext,
1096) -> super::TableColumnSchema {
1097    let mut schema = column.schema.clone();
1098    schema.relation = column
1099        .relation
1100        .as_ref()
1101        .filter(|relation| relation.policy.allows(context))
1102        .map(|relation| relation.schema.clone());
1103    schema
1104}
1105
1106fn column_readable(column: &RuntimeTableColumn, context: &ActionContext) -> bool {
1107    !column.secret && access_rule_allows(&column.readable, context)
1108}
1109
1110fn form_field(
1111    column: &RuntimeTableColumn,
1112    context: &ActionContext,
1113) -> Option<super::FormFieldSchema> {
1114    let readable = column_readable(column, context);
1115    let writable = !column.server_managed && access_rule_allows(&column.writable, context);
1116    if !readable && !writable {
1117        return None;
1118    }
1119    Some(super::FormFieldSchema {
1120        field: column.schema.field.clone(),
1121        title: column.schema.title.clone(),
1122        description: column.schema.description.clone(),
1123        widget: column.schema.widget,
1124        required: column.schema.required && writable,
1125        read_only: !writable,
1126        write_only: column.secret || !readable,
1127        relation: column
1128            .relation
1129            .as_ref()
1130            .filter(|relation| relation.policy.allows(context))
1131            .map(|relation| relation.schema.clone()),
1132        validation: column.validation.clone(),
1133    })
1134}
1135
1136fn access_rule_allows(rule: &super::AccessRule, context: &ActionContext) -> bool {
1137    match rule {
1138        super::AccessRule::Everyone => true,
1139        super::AccessRule::Nobody => false,
1140        super::AccessRule::Roles(roles) => context
1141            .user_roles_set()
1142            .is_some_and(|user_roles| roles.iter().any(|role| user_roles.contains(role))),
1143    }
1144}
1145
1146fn checked_runtime_field(
1147    table: &super::TableName,
1148    field: &super::FieldName,
1149) -> Result<yang_db::FieldRef, BuildError> {
1150    yang_db::FieldRef::new(format!("{table}.{field}")).map_err(|error| {
1151        BuildError::InvalidReference {
1152            kind: "Field",
1153            reference: error.to_string(),
1154        }
1155    })
1156}
1157
1158fn duplicate(kind: &'static str, name: impl ToString) -> BuildError {
1159    BuildError::DuplicateName {
1160        kind,
1161        name: name.to_string(),
1162    }
1163}
1164
1165fn insert_unique<T: Ord + Clone + ToString>(
1166    set: &mut BTreeSet<T>,
1167    value: &T,
1168    kind: &'static str,
1169) -> Result<(), BuildError> {
1170    if set.insert(value.clone()) {
1171        Ok(())
1172    } else {
1173        Err(duplicate(kind, value.to_string()))
1174    }
1175}
1176
1177fn validate_unique_addons(addons: &[AddonSpec]) -> Result<(), BuildError> {
1178    let mut names = BTreeSet::new();
1179    for addon in addons {
1180        insert_unique(&mut names, &addon.name, "Addon")?;
1181    }
1182    Ok(())
1183}
1184
1185fn validate_dependencies(addons: &[AddonSpec]) -> Result<(), BuildError> {
1186    let names: BTreeSet<_> = addons.iter().map(|addon| addon.name.clone()).collect();
1187    for addon in addons {
1188        let mut dependencies = BTreeSet::new();
1189        for dependency in &addon.dependencies {
1190            insert_unique(&mut dependencies, dependency, "Addon dependency")?;
1191            if !names.contains(dependency) {
1192                return Err(BuildError::DependencyMissing {
1193                    addon: addon.name.to_string(),
1194                    dependency: dependency.to_string(),
1195                });
1196            }
1197        }
1198    }
1199    Ok(())
1200}
1201
1202fn validate_module_ownership(addons: &[AddonSpec]) -> Result<(), BuildError> {
1203    for addon in addons {
1204        for module in &addon.modules {
1205            let owner = module.name.as_str().split('.').next().unwrap_or_default();
1206            if owner != addon.name.as_str() {
1207                return Err(BuildError::InvalidReference {
1208                    kind: "Module owner",
1209                    reference: format!("{} -> {}", addon.name, module.name),
1210                });
1211            }
1212        }
1213    }
1214    Ok(())
1215}
1216
1217fn validate_unique_modules(addons: &[AddonSpec]) -> Result<(), BuildError> {
1218    let mut names = BTreeSet::new();
1219    for module in addons.iter().flat_map(|addon| &addon.modules) {
1220        insert_unique(&mut names, &module.name, "Module")?;
1221    }
1222    Ok(())
1223}
1224
1225fn validate_module_contents(addons: &[AddonSpec]) -> Result<(), BuildError> {
1226    let mut tables = BTreeSet::new();
1227    let mut operations = BTreeSet::new();
1228    for module in addons.iter().flat_map(|addon| &addon.modules) {
1229        if let Some(table) = &module.table {
1230            insert_unique(&mut tables, &table.name, "Table")?;
1231            let mut fields = BTreeSet::new();
1232            let mut tenant_key = None;
1233            for field in &table.fields {
1234                insert_unique(&mut fields, &field.name, "Field")?;
1235                if field.tenant_key && tenant_key.replace(&field.name).is_some() {
1236                    return Err(BuildError::InvalidFieldDefinition {
1237                        table: table.name.to_string(),
1238                        field: field.name.to_string(),
1239                        reason: "同一表只能声明一个 tenant_key".to_string(),
1240                    });
1241                }
1242                if matches!(field.kind, FieldKind::Table | FieldKind::Tree)
1243                    && field.relation.is_none()
1244                {
1245                    return Err(BuildError::InvalidFieldDefinition {
1246                        table: table.name.to_string(),
1247                        field: field.name.to_string(),
1248                        reason: "Table/Tree 字段必须声明 relation".to_string(),
1249                    });
1250                }
1251                if !matches!(field.kind, FieldKind::Table | FieldKind::Tree)
1252                    && field.relation.is_some()
1253                {
1254                    return Err(BuildError::InvalidFieldDefinition {
1255                        table: table.name.to_string(),
1256                        field: field.name.to_string(),
1257                        reason: "只有 Table/Tree 字段可以声明 relation".to_string(),
1258                    });
1259                }
1260                // I-5:服务端关键词搜索只会命中文本列;允许非文本字段声明
1261                // searchable 等于让 UI 投影的 search_fields 说谎,构建期拒绝。
1262                if field.access.searchable
1263                    && !matches!(field.kind, FieldKind::Str | FieldKind::Text)
1264                {
1265                    return Err(BuildError::InvalidFieldDefinition {
1266                        table: table.name.to_string(),
1267                        field: field.name.to_string(),
1268                        reason: "只有文本字段(Str/Text)可以声明 searchable".to_string(),
1269                    });
1270                }
1271            }
1272        }
1273
1274        let mut actions = BTreeSet::new();
1275        let mut module_permissions = BTreeSet::new();
1276        for permission in &module.default_permissions {
1277            if permission.trim().is_empty() {
1278                return Err(BuildError::InvalidReference {
1279                    kind: "Module permission",
1280                    reference: format!("{} -> 空权限", module.name),
1281                });
1282            }
1283            insert_unique(&mut module_permissions, permission, "Module permission")?;
1284        }
1285        for action in module.actions() {
1286            insert_unique(&mut actions, &action.name, "Action")?;
1287            if let Some(error) = &action.contract_error {
1288                return Err(BuildError::InvalidReference {
1289                    kind: "Action schema",
1290                    reference: format!("{}.{} -> {error}", module.name, action.name),
1291                });
1292            }
1293            if action.display_name.trim().is_empty() {
1294                return Err(BuildError::InvalidReference {
1295                    kind: "Action display_name",
1296                    reference: format!("{}.{}", module.name, action.name),
1297                });
1298            }
1299            if !(100..=599).contains(&action.success_status) {
1300                return Err(BuildError::InvalidReference {
1301                    kind: "Action success_status",
1302                    reference: format!(
1303                        "{}.{} -> {}",
1304                        module.name, action.name, action.success_status
1305                    ),
1306                });
1307            }
1308            validate_action_media(module, action)?;
1309            let mut permissions = BTreeSet::new();
1310            for permission in &action.permissions {
1311                if permission.trim().is_empty() {
1312                    return Err(BuildError::InvalidReference {
1313                        kind: "Action permission",
1314                        reference: format!("{}.{} -> 空权限", module.name, action.name),
1315                    });
1316                }
1317                insert_unique(&mut permissions, permission, "Action permission")?;
1318            }
1319            if action.route.operation_id.trim().is_empty() {
1320                return Err(BuildError::InvalidRoute {
1321                    method: action.route.method.as_str().to_string(),
1322                    path: action.route.path.clone(),
1323                    reason: "operation_id 不能为空".to_string(),
1324                });
1325            }
1326            if !operations.insert(action.route.operation_id.clone()) {
1327                return Err(duplicate("operation_id", &action.route.operation_id));
1328            }
1329            let mut params = BTreeSet::new();
1330            for param in &action.params {
1331                let identity = (param.source, param.name.clone());
1332                if !params.insert(identity) {
1333                    return Err(duplicate("Param", &param.name));
1334                }
1335                if param.source == ParamSource::Path
1336                    && !action
1337                        .route
1338                        .path
1339                        .contains(&format!("{{{}}}", param.name.as_str()))
1340                {
1341                    return Err(BuildError::InvalidReference {
1342                        kind: "Path param",
1343                        reference: format!("{} -> {}", param.name, action.route.path),
1344                    });
1345                }
1346            }
1347        }
1348
1349        let mut views = BTreeSet::new();
1350        for view in &module.views {
1351            insert_unique(&mut views, &view.name, "View")?;
1352        }
1353    }
1354    Ok(())
1355}
1356
1357fn validate_middleware_order(addons: &[AddonSpec]) -> Result<(), BuildError> {
1358    for module in addons.iter().flat_map(|addon| &addon.modules) {
1359        let mut authentication_dependent_seen = None;
1360        for middleware in module.middlewares() {
1361            match middleware.role() {
1362                MiddlewareRole::TenantResolution => {
1363                    authentication_dependent_seen = Some("TenantResolverMiddleware")
1364                }
1365                MiddlewareRole::StepUpProtection => {
1366                    authentication_dependent_seen = Some("StepUpMiddleware")
1367                }
1368                MiddlewareRole::Authentication if authentication_dependent_seen.is_some() => {
1369                    return Err(BuildError::InvalidReference {
1370                        kind: "Middleware order",
1371                        reference: format!(
1372                            "{}: TokenAuthMiddleware 必须先于 {} 注册",
1373                            module.name,
1374                            authentication_dependent_seen.unwrap_or("身份依赖中间件")
1375                        ),
1376                    });
1377                }
1378                MiddlewareRole::Unspecified | MiddlewareRole::Authentication => {}
1379            }
1380        }
1381    }
1382    Ok(())
1383}
1384
1385fn validate_action_media(
1386    module: &super::ModuleSpec,
1387    action: &super::ActionSpec,
1388) -> Result<(), BuildError> {
1389    let invalid = |reason: &str| BuildError::InvalidReference {
1390        kind: "Action request media",
1391        reference: format!("{}.{} -> {reason}", module.name, action.name),
1392    };
1393    // C-1 双向强制:二进制文件字段(UploadedFile,schema 形态为 format: binary)
1394    // 只能出现在 multipart Action 中,multipart Action 也必须至少声明一个文件字段。
1395    let has_binary_input = schema_contains_binary_field(&action.input_schema);
1396    match (action.request_media_type, action.multipart.as_ref()) {
1397        (super::ActionMediaType::Json, None) => {
1398            if has_binary_input {
1399                return Err(invalid(
1400                    "JSON Action 的输入不得包含二进制文件字段(应声明 multipart 请求)",
1401                ));
1402            }
1403            return Ok(());
1404        }
1405        (super::ActionMediaType::Json, Some(_)) => {
1406            return Err(invalid("JSON Action 不得携带 multipart 配置"));
1407        }
1408        (super::ActionMediaType::Multipart, None) => {
1409            return Err(invalid("multipart Action 缺少资源限制"));
1410        }
1411        (super::ActionMediaType::Multipart, Some(_)) => {}
1412    }
1413    if !matches!(
1414        action.route.method,
1415        super::HttpMethod::Post | super::HttpMethod::Put | super::HttpMethod::Patch
1416    ) {
1417        return Err(invalid("multipart 只允许 POST/PUT/PATCH"));
1418    }
1419
1420    let multipart = action
1421        .multipart
1422        .as_ref()
1423        .ok_or_else(|| invalid("multipart Action 缺少资源限制"))?;
1424    if multipart.max_files == 0 {
1425        return Err(invalid("max_files 必须大于 0"));
1426    }
1427    if multipart.max_file_bytes == 0 || multipart.max_total_bytes == 0 {
1428        return Err(invalid("文件与请求字节上限必须大于 0"));
1429    }
1430    if multipart.max_file_bytes > multipart.max_total_bytes {
1431        return Err(invalid("max_file_bytes 不能大于 max_total_bytes"));
1432    }
1433    if multipart.max_text_field_bytes == 0 {
1434        return Err(invalid("文本字段字节上限必须大于 0"));
1435    }
1436    if multipart.max_text_field_bytes > multipart.max_total_bytes {
1437        return Err(invalid("max_text_field_bytes 不能大于 max_total_bytes"));
1438    }
1439    if multipart.allowed_content_types.is_empty() {
1440        return Err(invalid("allowed_content_types 不能为空"));
1441    }
1442    let mut content_types = BTreeSet::new();
1443    for content_type in &multipart.allowed_content_types {
1444        if !is_exact_mime_type(content_type) {
1445            return Err(invalid("allowed_content_types 必须是小写精确 MIME 类型"));
1446        }
1447        if !content_types.insert(content_type) {
1448            return Err(invalid("allowed_content_types 不能重复"));
1449        }
1450    }
1451    if !has_binary_input {
1452        return Err(invalid("multipart Action 的输入必须至少声明一个文件字段"));
1453    }
1454    Ok(())
1455}
1456
1457/// 递归检测 JSON Schema 是否声明二进制文件字段(`format: "binary"`,
1458/// 即 `UploadedFile` 经 schemars 生成的形态;`$ref`/`anyOf`/`items` 递归覆盖)。
1459pub(crate) fn schema_contains_binary_field(schema: &serde_json::Value) -> bool {
1460    schema_subtree_contains_binary(schema, schema)
1461}
1462
1463/// 递归检测 schema 子树是否声明二进制文件字段;本地 `$ref`(`#/definitions/...`)
1464/// 按 document 解析后继续深入,带循环保护(自引用类型不会死循环)。
1465pub(crate) fn schema_subtree_contains_binary(
1466    document: &serde_json::Value,
1467    subtree: &serde_json::Value,
1468) -> bool {
1469    fn inner(
1470        document: &serde_json::Value,
1471        subtree: &serde_json::Value,
1472        visited: &mut BTreeSet<String>,
1473    ) -> bool {
1474        match subtree {
1475            serde_json::Value::Object(map) => {
1476                if map.get("format").and_then(serde_json::Value::as_str) == Some("binary") {
1477                    return true;
1478                }
1479                if let Some(name) = map
1480                    .get("$ref")
1481                    .and_then(serde_json::Value::as_str)
1482                    .and_then(|reference| reference.strip_prefix("#/definitions/"))
1483                {
1484                    if visited.insert(name.to_string()) {
1485                        if let Some(target) = document
1486                            .get("definitions")
1487                            .and_then(|definitions| definitions.get(name))
1488                        {
1489                            if inner(document, target, visited) {
1490                                return true;
1491                            }
1492                        }
1493                    }
1494                }
1495                map.values().any(|value| inner(document, value, visited))
1496            }
1497            serde_json::Value::Array(items) => {
1498                items.iter().any(|item| inner(document, item, visited))
1499            }
1500            _ => false,
1501        }
1502    }
1503    inner(document, subtree, &mut BTreeSet::new())
1504}
1505
1506fn is_exact_mime_type(value: &str) -> bool {
1507    let Some((top, subtype)) = value.split_once('/') else {
1508        return false;
1509    };
1510    !top.is_empty()
1511        && !subtype.is_empty()
1512        && !subtype.contains('/')
1513        && top.bytes().all(is_mime_token_byte)
1514        && subtype.bytes().all(is_mime_token_byte)
1515}
1516
1517fn is_mime_token_byte(value: u8) -> bool {
1518    value.is_ascii_lowercase()
1519        || value.is_ascii_digit()
1520        || matches!(
1521            value,
1522            b'!' | b'#'
1523                | b'$'
1524                | b'%'
1525                | b'&'
1526                | b'\''
1527                | b'+'
1528                | b'-'
1529                | b'.'
1530                | b'^'
1531                | b'_'
1532                | b'`'
1533                | b'|'
1534                | b'~'
1535        )
1536}
1537
1538fn collect_fields(
1539    addons: &[AddonSpec],
1540) -> Result<BTreeMap<TableName, BTreeSet<super::FieldName>>, BuildError> {
1541    let mut result = BTreeMap::new();
1542    for table in addons
1543        .iter()
1544        .flat_map(|addon| &addon.modules)
1545        .filter_map(|module| module.table.as_ref())
1546    {
1547        let fields = table
1548            .fields
1549            .iter()
1550            .map(|field| field.name.clone())
1551            .collect();
1552        if result.insert(table.name.clone(), fields).is_some() {
1553            return Err(duplicate("Table", &table.name));
1554        }
1555    }
1556    Ok(result)
1557}
1558
1559fn collect_actions(addons: &[AddonSpec]) -> Result<BTreeSet<ActionRef>, BuildError> {
1560    let mut result = BTreeSet::new();
1561    for module in addons.iter().flat_map(|addon| &addon.modules) {
1562        for action in module.actions() {
1563            let reference = ActionRef::new(module.name.clone(), action.name.clone());
1564            insert_unique(&mut result, &reference, "Action")?;
1565        }
1566    }
1567    Ok(result)
1568}
1569
1570fn collect_views(addons: &[AddonSpec]) -> Result<BTreeSet<super::ViewRef>, BuildError> {
1571    let mut result = BTreeSet::new();
1572    for module in addons.iter().flat_map(|addon| &addon.modules) {
1573        for view in &module.views {
1574            let reference = super::ViewRef::new(module.name.clone(), view.name.clone());
1575            insert_unique(&mut result, &reference, "View")?;
1576        }
1577    }
1578    Ok(result)
1579}
1580
1581fn validate_field_ref(
1582    reference: &FieldRef,
1583    fields: &BTreeMap<TableName, BTreeSet<super::FieldName>>,
1584) -> Result<(), BuildError> {
1585    if fields
1586        .get(reference.table())
1587        .is_some_and(|table| table.contains(reference.field()))
1588    {
1589        Ok(())
1590    } else {
1591        Err(BuildError::InvalidReference {
1592            kind: "Field",
1593            reference: reference.to_string(),
1594        })
1595    }
1596}
1597
1598fn validate_action_ref(
1599    reference: &ActionRef,
1600    actions: &BTreeSet<ActionRef>,
1601) -> Result<(), BuildError> {
1602    if actions.contains(reference) {
1603        Ok(())
1604    } else {
1605        Err(BuildError::InvalidReference {
1606            kind: "Action",
1607            reference: reference.to_string(),
1608        })
1609    }
1610}
1611
1612fn validate_references(
1613    addons: &[AddonSpec],
1614    fields: &BTreeMap<TableName, BTreeSet<super::FieldName>>,
1615    actions: &BTreeSet<ActionRef>,
1616    views: &BTreeSet<super::ViewRef>,
1617) -> Result<(), BuildError> {
1618    for module in addons.iter().flat_map(|addon| &addon.modules) {
1619        for middleware in module.middlewares() {
1620            if let Some(target) = middleware.target_action() {
1621                if target.module() != &module.name {
1622                    return Err(BuildError::InvalidReference {
1623                        kind: "Middleware Action",
1624                        reference: target.to_string(),
1625                    });
1626                }
1627                validate_action_ref(target, actions).map_err(|_| BuildError::InvalidReference {
1628                    kind: "Middleware Action",
1629                    reference: target.to_string(),
1630                })?;
1631            }
1632        }
1633        if let Some(table) = &module.table {
1634            for field in &table.fields {
1635                if let Some(relation) = &field.relation {
1636                    validate_field_ref(relation, fields)?;
1637                }
1638                if let Some(select) = &field.select {
1639                    if field.relation.is_none() {
1640                        return Err(BuildError::InvalidReference {
1641                            kind: "Relation Options Field",
1642                            reference: format!("{}.{}: {select}", table.name, field.name),
1643                        });
1644                    }
1645                    validate_action_ref(select, actions)?;
1646                }
1647                for display in &field.presentation.display {
1648                    validate_field_ref(display, fields)?;
1649                    let same_target_table = field
1650                        .relation
1651                        .as_ref()
1652                        .is_some_and(|relation| display.table() == relation.table());
1653                    if !same_target_table {
1654                        return Err(BuildError::InvalidReference {
1655                            kind: "Relation Display Field",
1656                            reference: format!("{}.{}: {display}", table.name, field.name),
1657                        });
1658                    }
1659                }
1660            }
1661        }
1662        for action in module.actions() {
1663            for param in &action.params {
1664                if let Some(field) = &param.field {
1665                    validate_field_ref(field, fields)?;
1666                }
1667            }
1668            for call in &action.calls {
1669                validate_action_ref(call, actions)?;
1670            }
1671        }
1672        for view in &module.views {
1673            let view_ref = super::ViewRef::new(module.name.clone(), view.name.clone());
1674            if !views.contains(&view_ref) {
1675                return Err(BuildError::InvalidReference {
1676                    kind: "View",
1677                    reference: view_ref.to_string(),
1678                });
1679            }
1680            for field in &view.fields {
1681                validate_field_ref(field, fields)?;
1682            }
1683            if let Some(tree) = &view.tree {
1684                let table = module
1685                    .table
1686                    .as_ref()
1687                    .ok_or_else(|| BuildError::InvalidReference {
1688                        kind: "Tree View",
1689                        reference: format!("{view_ref}: 缺少主表"),
1690                    })?;
1691                let tree_fields = [&tree.id_field, &tree.parent_field, &tree.label_field];
1692                if tree.id_field == tree.parent_field {
1693                    return Err(BuildError::InvalidReference {
1694                        kind: "Tree View",
1695                        reference: format!("{view_ref}: id/parent 字段必须不同"),
1696                    });
1697                }
1698                if tree.max_nodes == Some(0) {
1699                    return Err(BuildError::InvalidReference {
1700                        kind: "Tree View",
1701                        reference: format!("{view_ref}: max_nodes 必须大于 0"),
1702                    });
1703                }
1704                for field in tree_fields {
1705                    validate_field_ref(field, fields)?;
1706                    if field.table() != &table.name || !view.fields.contains(field) {
1707                        return Err(BuildError::InvalidReference {
1708                            kind: "Tree View Field",
1709                            reference: format!("{view_ref}: {field}"),
1710                        });
1711                    }
1712                }
1713            }
1714            for action in &view.actions {
1715                validate_action_ref(action, actions)?;
1716            }
1717        }
1718    }
1719    Ok(())
1720}
1721
1722#[derive(Default)]
1723struct RouteRegistry {
1724    matcher: matchit::Router<()>,
1725    methods_by_path: HashMap<String, HashSet<&'static str>>,
1726}
1727
1728impl RouteRegistry {
1729    fn insert(&mut self, method: &'static str, path: &str) -> Result<(), BuildError> {
1730        validate_route(method, path)?;
1731        if let Some(methods) = self.methods_by_path.get_mut(path) {
1732            if methods.insert(method) {
1733                return Ok(());
1734            }
1735            return Err(route_conflict(method, path, String::new()));
1736        }
1737        self.matcher
1738            .insert(path.to_string(), ())
1739            .map_err(|error| route_conflict(method, path, format!(" ({error})")))?;
1740        self.methods_by_path
1741            .insert(path.to_string(), HashSet::from([method]));
1742        Ok(())
1743    }
1744}
1745
1746fn validate_route(method: &str, path: &str) -> Result<(), BuildError> {
1747    if !path.starts_with('/') || path.contains(['?', '#']) || path.chars().any(char::is_whitespace)
1748    {
1749        return Err(BuildError::InvalidRoute {
1750            method: method.to_string(),
1751            path: path.to_string(),
1752            reason: "path 必须是无 query/fragment/空白的绝对路径".to_string(),
1753        });
1754    }
1755    if path
1756        .split('/')
1757        .any(|segment| segment.starts_with([':', '*']))
1758    {
1759        return Err(BuildError::InvalidRoute {
1760            method: method.to_string(),
1761            path: path.to_string(),
1762            reason: "path 必须使用 Axum 0.8 的 {name}/{*name} 参数语法".to_string(),
1763        });
1764    }
1765    let mut matcher = matchit::Router::new();
1766    matcher
1767        .insert(path.to_string(), ())
1768        .map_err(|error| BuildError::InvalidRoute {
1769            method: method.to_string(),
1770            path: path.to_string(),
1771            reason: error.to_string(),
1772        })?;
1773    Ok(())
1774}
1775
1776fn route_conflict(method: &str, path: &str, detail: String) -> BuildError {
1777    BuildError::RouteConflict {
1778        method: method.to_string(),
1779        path: path.to_string(),
1780        detail,
1781    }
1782}
1783
1784fn validate_routes(addons: &[AddonSpec]) -> Result<(), BuildError> {
1785    let mut routes = RouteRegistry::default();
1786    for action in addons
1787        .iter()
1788        .flat_map(|addon| &addon.modules)
1789        .flat_map(|module| module.actions())
1790    {
1791        routes.insert(action.route.method.as_str(), &action.route.path)?;
1792    }
1793    Ok(())
1794}
1795
1796fn sort_definitions(addons: &mut [AddonSpec]) {
1797    for addon in addons.iter_mut() {
1798        addon.dependencies.sort();
1799        addon
1800            .modules
1801            .sort_by(|left, right| left.name.cmp(&right.name));
1802        for module in &mut addon.modules {
1803            module.default_permissions.sort();
1804            if let Some(table) = &mut module.table {
1805                table
1806                    .fields
1807                    .sort_by(|left, right| left.name.cmp(&right.name));
1808            }
1809            module.sort_actions();
1810            for action in module.actions_mut() {
1811                action.params.sort_by(|left, right| {
1812                    (left.source, &left.name).cmp(&(right.source, &right.name))
1813                });
1814                action.calls.sort();
1815                action.permissions.sort();
1816                action.tags.sort();
1817            }
1818            module
1819                .views
1820                .sort_by(|left, right| left.name.cmp(&right.name));
1821        }
1822    }
1823    addons.sort_by(|left, right| left.name.cmp(&right.name));
1824}
1825
1826fn build_registry(addons: &[AddonSpec]) -> Result<Registry, BuildError> {
1827    let mut actions = BTreeMap::new();
1828    let mut handlers = Vec::new();
1829    for (slot, (module, table, action, handler, middlewares)) in addons
1830        .iter()
1831        .flat_map(|addon| &addon.modules)
1832        .flat_map(|module| {
1833            module.action_pairs().map(move |(action, handler)| {
1834                (
1835                    &module.name,
1836                    module.table.as_ref(),
1837                    action,
1838                    handler,
1839                    module.middlewares(),
1840                )
1841            })
1842        })
1843        .enumerate()
1844    {
1845        actions.insert(
1846            ActionRef::new(module.clone(), action.name.clone()),
1847            ActionHandle(slot),
1848        );
1849        let mut permission_groups = Vec::new();
1850        let module_spec = addons
1851            .iter()
1852            .flat_map(|addon| &addon.modules)
1853            .find(|candidate| &candidate.name == module);
1854        if let Some(module_spec) = module_spec {
1855            if !module_spec.default_permissions.is_empty() {
1856                permission_groups.push(PermissionGroup::new(
1857                    "模块",
1858                    Arc::<[String]>::from(module_spec.default_permissions.clone()),
1859                    module_spec.default_permission_mode,
1860                ));
1861            }
1862        }
1863        if !action.permissions.is_empty() {
1864            permission_groups.push(PermissionGroup::new(
1865                "Action",
1866                Arc::<[String]>::from(action.permissions.clone()),
1867                action.permission_mode,
1868            ));
1869        }
1870        handlers.push(RuntimeAction {
1871            handler: Arc::clone(handler),
1872            middlewares: Arc::from(middlewares.to_vec()),
1873            policy: AuthorizationPolicy::new(action.is_public, permission_groups),
1874            module: module.to_string(),
1875            action: action.name.to_string(),
1876            ui_schema: super::ActionDemoSchema::from(action),
1877            table_definition: table
1878                .map(super::TableSpec::table_definition)
1879                .transpose()
1880                .map_err(|error| BuildError::InvalidFieldDefinition {
1881                    table: table
1882                        .map_or_else(|| "<none>".to_string(), |value| value.name.to_string()),
1883                    field: "<table>".to_string(),
1884                    reason: error.to_string(),
1885                })?,
1886        });
1887    }
1888    Ok(Registry {
1889        actions,
1890        handlers,
1891        table_views: Vec::new(),
1892    })
1893}
1894
1895#[allow(dead_code)]
1896fn _module_name_type_is_used(_: &ModuleName) {}