1use 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#[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 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 pub(super) table_definition: Option<Arc<TableDefinition>>,
40 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 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 pub fn resolve(&self, action: &ActionRef) -> Option<ActionHandle> {
109 self.actions.get(action).copied()
110 }
111
112 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 pub fn len(&self) -> usize {
143 self.actions.len()
144 }
145
146 pub fn is_empty(&self) -> bool {
148 self.actions.is_empty()
149 }
150
151 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 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 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 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
406fn 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 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}