1use crate::definition::{Plugins, Registry};
12use crate::error::BaseError;
13use crate::table::{TableDefinition, TableQuery, Tables};
14use crate::tools::Tools;
15use serde::de::DeserializeOwned;
16use std::collections::HashSet;
17use std::sync::Arc;
18
19use super::Request;
20use super::RequestId;
21use super::RequestMeta;
22use super::{ActorContext, RequestContext, SystemTenantCapability, TenantContext};
23
24#[derive(Debug, Clone)]
29#[non_exhaustive]
30pub struct User {
31 pub id: i64,
33 pub username: String,
35 pub nickname: String,
37 pub email: String,
39 pub roles: HashSet<String>,
41 pub permissions: HashSet<String>,
43}
44
45impl User {
46 pub fn new(id: i64, username: impl Into<String>) -> Self {
48 Self {
49 id,
50 username: username.into(),
51 nickname: String::new(),
52 email: String::new(),
53 roles: HashSet::new(),
54 permissions: HashSet::new(),
55 }
56 }
57
58 pub fn with_roles(mut self, roles: impl IntoIterator<Item = impl Into<String>>) -> Self {
60 self.roles = roles.into_iter().map(Into::into).collect();
61 self
62 }
63
64 pub fn with_permissions(
66 mut self,
67 permissions: impl IntoIterator<Item = impl Into<String>>,
68 ) -> Self {
69 self.permissions = permissions.into_iter().map(Into::into).collect();
70 self
71 }
72
73 pub fn has_permission(&self, permission: &str) -> bool {
75 self.permissions.contains(permission)
76 }
77
78 pub fn has_role(&self, role: &str) -> bool {
80 self.roles.contains(role)
81 }
82
83 pub fn has_any_role(&self, roles: &[String]) -> bool {
85 roles.iter().any(|r| self.has_role(r))
86 }
87}
88
89#[derive(Debug, Clone, Copy, Default)]
94enum TenantAccess {
95 #[default]
96 Missing,
97 Tenant(TenantContext),
98 System(SystemTenantCapability),
99}
100
101#[derive(Debug)]
108#[non_exhaustive]
109pub struct ActionContext {
110 pub request: Request,
112 pub request_meta: RequestMeta,
114 pub(crate) user: Option<User>,
118 tools: Arc<Tools>,
120 registry: Option<Arc<Registry>>,
122 table_definition: Option<TableDefinition>,
124 datasource: Option<crate::datasource::DatasourceId>,
126 pub request_id: RequestId,
131 pub module: Option<String>,
136 action: Option<String>,
140 cached_roles: Arc<[String]>,
143 request_context: RequestContext,
145 tenant_access: TenantAccess,
147}
148
149impl Clone for ActionContext {
150 fn clone(&self) -> Self {
151 Self {
154 request: self.request.clone(),
155 request_meta: self.request_meta.clone(),
156 user: self.user.clone(),
157 tools: Arc::clone(&self.tools),
158 registry: self.registry.clone(),
159 table_definition: self.table_definition.clone(),
160 datasource: self.datasource.clone(),
161 request_id: self.request_id,
162 module: self.module.clone(),
163 action: self.action.clone(),
164 cached_roles: Arc::clone(&self.cached_roles),
165 request_context: RequestContext::default(),
166 tenant_access: self.tenant_access,
167 }
168 }
169}
170
171impl ActionContext {
172 pub fn new(request: Request, tools: Arc<Tools>) -> Self {
174 Self {
175 request,
176 request_meta: RequestMeta::default(),
177 user: None,
178 tools,
179 registry: None,
180 table_definition: None,
181 datasource: None,
182 request_id: RequestId::generate(),
183 module: None,
184 action: None,
185 cached_roles: Arc::from(Vec::new()),
186 request_context: RequestContext::default(),
187 tenant_access: TenantAccess::Missing,
188 }
189 }
190
191 pub fn tools(&self) -> &Tools {
193 &self.tools
194 }
195
196 #[cfg(feature = "http")]
201 pub fn http(&self) -> Result<&crate::http::HttpClient, BaseError> {
202 self.tools.http()
203 }
204
205 fn slow_query_threshold(&self) -> Option<std::time::Duration> {
210 self.tools
211 .config::<crate::observability::ObservabilityConfig>()
212 .ok()
213 .and_then(|config| config.slow_query_threshold)
214 }
215
216 pub fn request_context(&mut self) -> &mut RequestContext {
218 &mut self.request_context
219 }
220
221 pub fn with_tenant(mut self, tenant: TenantContext) -> Self {
223 self.tenant_access = TenantAccess::Tenant(tenant);
224 self
225 }
226
227 pub(crate) fn with_system_tenant(mut self, capability: SystemTenantCapability) -> Self {
228 self.tenant_access = TenantAccess::System(capability);
229 self
230 }
231
232 pub fn tenant(&self) -> Result<TenantContext, BaseError> {
234 match self.tenant_access {
235 TenantAccess::Tenant(tenant) => Ok(tenant),
236 TenantAccess::Missing | TenantAccess::System(_) => Err(BaseError::Unauthorized(
237 "请求缺少普通租户 capability".to_string(),
238 )),
239 }
240 }
241
242 pub fn system_tenant(&self) -> Result<SystemTenantCapability, BaseError> {
244 match self.tenant_access {
245 TenantAccess::System(capability) => Ok(capability),
246 TenantAccess::Missing | TenantAccess::Tenant(_) => Err(BaseError::PermissionDenied(
247 "请求缺少系统租户 capability".to_string(),
248 )),
249 }
250 }
251
252 pub fn actor(&self) -> Result<ActorContext, BaseError> {
254 self.user
255 .as_ref()
256 .map(|user| ActorContext::new(user.id))
257 .ok_or_else(|| BaseError::Unauthorized("请求缺少已认证操作者".to_string()))
258 }
259
260 pub fn request_id(&self) -> RequestId {
262 self.request_id
263 }
264
265 pub(crate) fn with_registry(mut self, registry: Arc<Registry>) -> Self {
266 self.registry = Some(registry);
267 self
268 }
269
270 pub fn plugins(self) -> Result<Plugins, BaseError> {
272 let registry = self.registry.as_ref().cloned().ok_or_else(|| {
273 BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
274 })?;
275 Ok(Plugins::new(registry, self))
276 }
277
278 #[allow(dead_code)]
283 pub(crate) fn with_user(mut self, user: User) -> Self {
284 let mut roles = user.roles.iter().cloned().collect::<Vec<_>>();
285 roles.sort_unstable();
286 self.cached_roles = Arc::from(roles);
287 self.user = Some(user);
288 self
289 }
290
291 pub fn authenticated_user(&self) -> Option<&User> {
296 self.user.as_ref()
297 }
298
299 pub fn ui_catalog(&self) -> Result<crate::definition::UiCatalog, BaseError> {
303 let registry = self.registry.as_ref().ok_or_else(|| {
304 BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
305 })?;
306 registry.ui_catalog(self)
307 }
308
309 pub fn with_request_id(mut self, request_id: RequestId) -> Self {
314 self.request_id = request_id;
315 self
316 }
317
318 pub fn with_request_meta(mut self, request_meta: RequestMeta) -> Self {
320 self.request_meta = request_meta;
321 self
322 }
323
324 pub fn with_module(mut self, module: impl Into<String>) -> Self {
328 self.module = Some(module.into());
329 self
330 }
331
332 pub fn dispatch_target(&self) -> Option<(&str, &str)> {
337 Some((self.module.as_deref()?, self.action.as_deref()?))
338 }
339
340 pub(crate) fn with_dispatch_target(
342 mut self,
343 module: impl Into<String>,
344 action: impl Into<String>,
345 ) -> Self {
346 self.module = Some(module.into());
347 self.action = Some(action.into());
348 self
349 }
350
351 pub fn with_table_definition(mut self, definition: TableDefinition) -> Self {
353 self.table_definition = Some(definition);
354 self
355 }
356
357 pub fn table_definition(&self) -> Result<&TableDefinition, BaseError> {
359 self.table_definition
360 .as_ref()
361 .ok_or(BaseError::TableDefinitionNotSet)
362 }
363
364 pub(crate) fn with_datasource(
366 mut self,
367 datasource: Option<crate::datasource::DatasourceId>,
368 ) -> Self {
369 self.datasource = datasource;
370 self
371 }
372
373 pub fn datasource(&self) -> Option<&crate::datasource::DatasourceId> {
375 self.datasource.as_ref()
376 }
377
378 #[cfg(any(feature = "mysql", feature = "postgres"))]
380 fn resolved_datasource(&self) -> crate::datasource::DatasourceId {
381 self.datasource
382 .clone()
383 .or_else(|| {
384 self.table_definition
385 .as_ref()
386 .map(|definition| definition.datasource().clone())
387 })
388 .unwrap_or_default()
389 }
390
391 pub(crate) fn extract_input_owned<I: DeserializeOwned>(&mut self) -> Result<I, BaseError> {
396 let body = std::mem::take(&mut self.request.body);
397 serde_json::from_value(body)
398 .map_err(|e| BaseError::ParamInvalid("body".to_string(), e.to_string()))
399 }
400
401 fn base_table_query(&self, definition: &TableDefinition) -> Result<TableQuery, BaseError> {
413 #[cfg(any(feature = "mysql", feature = "postgres"))]
414 let (pool, pool_source) = {
415 let source = definition.datasource().clone();
416 match self.tools.database_named(&source) {
417 Ok(database) => (Some(database.pool()), database.id().clone()),
418 Err(BaseError::DatabaseNotInitialized) => (None, source),
419 Err(error) => return Err(error),
420 }
421 };
422 #[cfg(not(any(feature = "mysql", feature = "postgres")))]
423 let (pool, pool_source) = (None, crate::datasource::DatasourceId::default_source());
424
425 let slow_threshold = self.slow_query_threshold();
428 #[cfg(any(feature = "mysql", feature = "postgres"))]
429 let query = TableQuery::new_sourced(
430 definition.shared_config(),
431 Arc::clone(&self.cached_roles),
432 pool,
433 pool_source,
434 )
435 .require_sourced_tx(
436 self.tools
437 .datasources()
438 .map(|datasources| {
439 let backends: Vec<_> = datasources
440 .iter()
441 .map(|datasource| datasource.database().backend())
442 .collect();
443 backends
444 .iter()
445 .enumerate()
446 .any(|(index, backend)| backends[..index].contains(backend))
447 })
448 .unwrap_or(false),
449 );
450 #[cfg(not(any(feature = "mysql", feature = "postgres")))]
451 let query = {
452 let _ = pool_source;
453 TableQuery::new(
454 definition.shared_config(),
455 Arc::clone(&self.cached_roles),
456 pool,
457 )
458 };
459 Ok(query
460 .with_slow_threshold(slow_threshold)
461 .with_request_id(self.request_id)
462 .with_regex_cache(self.tools.regex_cache().clone()))
463 }
464
465 pub fn table_query(&self) -> Result<TableQuery, BaseError> {
471 let definition = self.table_definition()?;
472 let mut query = self.base_table_query(definition)?;
473 if let Some(field) = definition.tenant_key_field() {
474 query = query.scope_tenant(field, serde_json::json!(self.tenant()?.id().get()))?;
475 }
476 Ok(query)
477 }
478
479 pub fn system_table_query(
485 &self,
486 capability: SystemTenantCapability,
487 ) -> Result<TableQuery, BaseError> {
488 if self.system_tenant()? != capability {
489 return Err(BaseError::PermissionDenied(
490 "系统租户 capability 与当前请求不匹配".to_string(),
491 ));
492 }
493 let definition = self.table_definition()?;
494 self.base_table_query(definition)
495 }
496
497 pub fn tables(&self) -> Result<Tables, BaseError> {
499 self.table_query().map(Tables::new)
500 }
501
502 pub fn system_tables(&self, capability: SystemTenantCapability) -> Result<Tables, BaseError> {
504 self.system_table_query(capability).map(Tables::new)
505 }
506
507 #[cfg(any(feature = "mysql", feature = "postgres"))]
532 pub async fn begin_transaction(&self) -> Result<crate::database::AnyTransaction, BaseError> {
533 let source = self.resolved_datasource();
534 self.begin_transaction_on(&source).await
535 }
536
537 #[cfg(any(feature = "mysql", feature = "postgres"))]
539 pub async fn begin_transaction_on(
540 &self,
541 source: &crate::datasource::DatasourceId,
542 ) -> Result<crate::database::AnyTransaction, BaseError> {
543 self.tools
544 .database_named(source)?
545 .begin()
546 .await
547 .map_err(BaseError::DatabaseTransactionFailed)
548 }
549
550 #[cfg(any(feature = "mysql", feature = "postgres"))]
552 pub fn database(&self) -> Result<&crate::database::AnyDatabase, BaseError> {
553 let source = self.resolved_datasource();
554 self.database_on(&source)
555 }
556
557 #[cfg(any(feature = "mysql", feature = "postgres"))]
559 pub fn database_on(
560 &self,
561 source: &crate::datasource::DatasourceId,
562 ) -> Result<&crate::database::AnyDatabase, BaseError> {
563 self.tools.database_named(source)
564 }
565
566 #[cfg(any(feature = "mysql", feature = "postgres"))]
571 pub const TENANT_LOCAL_KEY: &'static str = "app.tenant_id";
572
573 #[cfg(any(feature = "mysql", feature = "postgres"))]
592 pub async fn set_local(
593 &self,
594 tx: &mut crate::database::AnyTransaction,
595 key: &str,
596 value: &str,
597 ) -> Result<(), BaseError> {
598 #[cfg(not(feature = "postgres"))]
600 let _ = (key, value);
601 match tx.kind_mut() {
602 #[cfg(feature = "postgres")]
603 crate::database::AnyTransactionKind::Postgres(tx) => tx
604 .set_local(key, value)
605 .await
606 .map_err(BaseError::DatabaseExecuteFailed),
607 #[cfg(feature = "mysql")]
608 crate::database::AnyTransactionKind::MySql(_) => Err(BaseError::ConfigError(
609 "MySQL 不支持事务级 SET LOCAL;该能力仅在 PostgreSQL 下可用".to_string(),
610 )),
611 }
612 }
613
614 #[cfg(any(feature = "mysql", feature = "postgres"))]
620 pub async fn set_tenant_local(
621 &self,
622 tx: &mut crate::database::AnyTransaction,
623 ) -> Result<(), BaseError> {
624 let tenant_id = self.tenant()?.id().get();
625 self.set_local(tx, Self::TENANT_LOCAL_KEY, &tenant_id.to_string())
626 .await
627 }
628
629 pub fn user_roles(&self) -> Vec<String> {
635 self.user
636 .as_ref()
637 .map(|u| u.roles.iter().cloned().collect())
638 .unwrap_or_default()
639 }
640
641 pub fn user_roles_set(&self) -> Option<&HashSet<String>> {
651 self.user.as_ref().map(|u| &u.roles)
652 }
653}
654
655#[cfg(test)]
656mod tests {
657 use super::*;
658 use crate::observability::ObservabilityConfig;
659 use crate::tools::ToolsBuilder;
660 use std::time::Duration;
661
662 fn empty_context() -> ActionContext {
663 let tools = Arc::new(ToolsBuilder::new().build().expect("空 Tools 应构建成功"));
664 ActionContext::new(Request::new(serde_json::json!({})), tools)
665 }
666
667 #[cfg(feature = "http")]
668 #[test]
669 fn http_shortcut_returns_client_when_configured() {
670 let tools = Arc::new(
671 ToolsBuilder::new()
672 .http(crate::http::HttpClient::new(30).expect("测试 HTTP 客户端应创建成功"))
673 .build()
674 .expect("配置 HTTP 客户端后应构建成功"),
675 );
676 let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
677
678 let client = context.http().expect("已配置时 ctx.http() 应可用");
679 let _builder = client.get("https://api.example.com/test");
680 }
681
682 #[cfg(feature = "http")]
683 #[test]
684 fn http_shortcut_errors_when_not_configured() {
685 let context = empty_context();
686
687 assert!(matches!(
688 context.http(),
689 Err(BaseError::HttpClientNotInitialized)
690 ));
691 }
692
693 #[test]
694 fn slow_query_threshold_is_none_without_registered_config() {
695 let context = empty_context();
696
697 assert_eq!(context.slow_query_threshold(), None);
698 }
699
700 #[test]
701 fn slow_query_threshold_reads_from_tools_config_slot() {
702 let threshold = Duration::from_millis(200);
703 let tools = Arc::new(
704 ToolsBuilder::new()
705 .config(ObservabilityConfig::new().with_slow_query_threshold(threshold))
706 .build()
707 .expect("注册可观测性配置后应构建成功"),
708 );
709 let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
710
711 assert_eq!(context.slow_query_threshold(), Some(threshold));
712 }
713
714 #[test]
715 fn authenticated_roles_are_cached_once_in_stable_order() {
716 let context = empty_context()
717 .with_user(User::new(1, "alice").with_roles(["operator", "admin", "operator"]));
718
719 assert_eq!(
720 context.cached_roles.as_ref(),
721 ["admin".to_string(), "operator".to_string()]
722 );
723 assert_eq!(
724 context.user_roles_set(),
725 Some(&HashSet::from([
726 "admin".to_string(),
727 "operator".to_string()
728 ]))
729 );
730 }
731
732 #[test]
733 fn ui_catalog_rejects_context_without_bound_registry() {
734 let context = empty_context();
735
736 assert!(matches!(
737 context.ui_catalog(),
738 Err(BaseError::ConfigError(message))
739 if message == "ActionContext 未绑定应用 Registry"
740 ));
741 }
742}