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 pub request_id: RequestId,
129 pub module: Option<String>,
134 action: Option<String>,
138 cached_roles: Arc<[String]>,
141 request_context: RequestContext,
143 tenant_access: TenantAccess,
145}
146
147impl Clone for ActionContext {
148 fn clone(&self) -> Self {
149 Self {
152 request: self.request.clone(),
153 request_meta: self.request_meta.clone(),
154 user: self.user.clone(),
155 tools: Arc::clone(&self.tools),
156 registry: self.registry.clone(),
157 table_definition: self.table_definition.clone(),
158 request_id: self.request_id,
159 module: self.module.clone(),
160 action: self.action.clone(),
161 cached_roles: Arc::clone(&self.cached_roles),
162 request_context: RequestContext::default(),
163 tenant_access: self.tenant_access,
164 }
165 }
166}
167
168impl ActionContext {
169 pub fn new(request: Request, tools: Arc<Tools>) -> Self {
171 Self {
172 request,
173 request_meta: RequestMeta::default(),
174 user: None,
175 tools,
176 registry: None,
177 table_definition: None,
178 request_id: RequestId::generate(),
179 module: None,
180 action: None,
181 cached_roles: Arc::from(Vec::new()),
182 request_context: RequestContext::default(),
183 tenant_access: TenantAccess::Missing,
184 }
185 }
186
187 pub fn tools(&self) -> &Tools {
189 &self.tools
190 }
191
192 #[cfg(feature = "http")]
197 pub fn http(&self) -> Result<&crate::http::HttpClient, BaseError> {
198 self.tools.http()
199 }
200
201 fn slow_query_threshold(&self) -> Option<std::time::Duration> {
206 self.tools
207 .config::<crate::observability::ObservabilityConfig>()
208 .ok()
209 .and_then(|config| config.slow_query_threshold)
210 }
211
212 pub fn request_context(&mut self) -> &mut RequestContext {
214 &mut self.request_context
215 }
216
217 pub fn with_tenant(mut self, tenant: TenantContext) -> Self {
219 self.tenant_access = TenantAccess::Tenant(tenant);
220 self
221 }
222
223 pub(crate) fn with_system_tenant(mut self, capability: SystemTenantCapability) -> Self {
224 self.tenant_access = TenantAccess::System(capability);
225 self
226 }
227
228 pub fn tenant(&self) -> Result<TenantContext, BaseError> {
230 match self.tenant_access {
231 TenantAccess::Tenant(tenant) => Ok(tenant),
232 TenantAccess::Missing | TenantAccess::System(_) => Err(BaseError::Unauthorized(
233 "请求缺少普通租户 capability".to_string(),
234 )),
235 }
236 }
237
238 pub fn system_tenant(&self) -> Result<SystemTenantCapability, BaseError> {
240 match self.tenant_access {
241 TenantAccess::System(capability) => Ok(capability),
242 TenantAccess::Missing | TenantAccess::Tenant(_) => Err(BaseError::PermissionDenied(
243 "请求缺少系统租户 capability".to_string(),
244 )),
245 }
246 }
247
248 pub fn actor(&self) -> Result<ActorContext, BaseError> {
250 self.user
251 .as_ref()
252 .map(|user| ActorContext::new(user.id))
253 .ok_or_else(|| BaseError::Unauthorized("请求缺少已认证操作者".to_string()))
254 }
255
256 pub fn request_id(&self) -> RequestId {
258 self.request_id
259 }
260
261 pub(crate) fn with_registry(mut self, registry: Arc<Registry>) -> Self {
262 self.registry = Some(registry);
263 self
264 }
265
266 pub fn plugins(self) -> Result<Plugins, BaseError> {
268 let registry = self.registry.as_ref().cloned().ok_or_else(|| {
269 BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
270 })?;
271 Ok(Plugins::new(registry, self))
272 }
273
274 #[allow(dead_code)]
279 pub(crate) fn with_user(mut self, user: User) -> Self {
280 let mut roles = user.roles.iter().cloned().collect::<Vec<_>>();
281 roles.sort_unstable();
282 self.cached_roles = Arc::from(roles);
283 self.user = Some(user);
284 self
285 }
286
287 pub fn authenticated_user(&self) -> Option<&User> {
292 self.user.as_ref()
293 }
294
295 pub fn ui_catalog(&self) -> Result<crate::definition::UiCatalog, BaseError> {
299 let registry = self.registry.as_ref().ok_or_else(|| {
300 BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
301 })?;
302 registry.ui_catalog(self)
303 }
304
305 pub fn with_request_id(mut self, request_id: RequestId) -> Self {
310 self.request_id = request_id;
311 self
312 }
313
314 pub fn with_request_meta(mut self, request_meta: RequestMeta) -> Self {
316 self.request_meta = request_meta;
317 self
318 }
319
320 pub fn with_module(mut self, module: impl Into<String>) -> Self {
324 self.module = Some(module.into());
325 self
326 }
327
328 pub fn dispatch_target(&self) -> Option<(&str, &str)> {
333 Some((self.module.as_deref()?, self.action.as_deref()?))
334 }
335
336 pub(crate) fn with_dispatch_target(
338 mut self,
339 module: impl Into<String>,
340 action: impl Into<String>,
341 ) -> Self {
342 self.module = Some(module.into());
343 self.action = Some(action.into());
344 self
345 }
346
347 pub fn with_table_definition(mut self, definition: TableDefinition) -> Self {
349 self.table_definition = Some(definition);
350 self
351 }
352
353 pub fn table_definition(&self) -> Result<&TableDefinition, BaseError> {
355 self.table_definition
356 .as_ref()
357 .ok_or(BaseError::TableDefinitionNotSet)
358 }
359
360 pub(crate) fn extract_input_owned<I: DeserializeOwned>(&mut self) -> Result<I, BaseError> {
365 let body = std::mem::take(&mut self.request.body);
366 serde_json::from_value(body)
367 .map_err(|e| BaseError::ParamInvalid("body".to_string(), e.to_string()))
368 }
369
370 fn base_table_query(&self, definition: &TableDefinition) -> Result<TableQuery, BaseError> {
382 #[cfg(feature = "mysql")]
384 let pool = self
385 .tools
386 .optional_mysql()?
387 .map(|database| Arc::new(database.pool().clone()));
388 #[cfg(not(feature = "mysql"))]
389 let pool = None;
390
391 let slow_threshold = self.slow_query_threshold();
394 Ok(TableQuery::new(
395 definition.shared_config(),
396 Arc::clone(&self.cached_roles),
397 pool,
398 )
399 .with_slow_threshold(slow_threshold)
400 .with_request_id(self.request_id)
401 .with_regex_cache(self.tools.regex_cache().clone()))
402 }
403
404 pub fn table_query(&self) -> Result<TableQuery, BaseError> {
410 let definition = self.table_definition()?;
411 let mut query = self.base_table_query(definition)?;
412 if let Some(field) = definition.tenant_key_field() {
413 query = query.scope_tenant(field, serde_json::json!(self.tenant()?.id().get()))?;
414 }
415 Ok(query)
416 }
417
418 pub fn system_table_query(
424 &self,
425 capability: SystemTenantCapability,
426 ) -> Result<TableQuery, BaseError> {
427 if self.system_tenant()? != capability {
428 return Err(BaseError::PermissionDenied(
429 "系统租户 capability 与当前请求不匹配".to_string(),
430 ));
431 }
432 let definition = self.table_definition()?;
433 self.base_table_query(definition)
434 }
435
436 pub fn tables(&self) -> Result<Tables, BaseError> {
438 self.table_query().map(Tables::new)
439 }
440
441 pub fn system_tables(&self, capability: SystemTenantCapability) -> Result<Tables, BaseError> {
443 self.system_table_query(capability).map(Tables::new)
444 }
445
446 #[cfg(feature = "mysql")]
470 pub async fn begin_transaction(&self) -> Result<yang_db::Transaction, BaseError> {
471 self.tools
472 .mysql()?
473 .transaction()
474 .await
475 .map_err(BaseError::DatabaseTransactionFailed)
476 }
477
478 pub fn user_roles(&self) -> Vec<String> {
484 self.user
485 .as_ref()
486 .map(|u| u.roles.iter().cloned().collect())
487 .unwrap_or_default()
488 }
489
490 pub fn user_roles_set(&self) -> Option<&HashSet<String>> {
500 self.user.as_ref().map(|u| &u.roles)
501 }
502}
503
504#[cfg(test)]
505mod tests {
506 use super::*;
507 use crate::observability::ObservabilityConfig;
508 use crate::tools::ToolsBuilder;
509 use std::time::Duration;
510
511 fn empty_context() -> ActionContext {
512 let tools = Arc::new(ToolsBuilder::new().build().expect("空 Tools 应构建成功"));
513 ActionContext::new(Request::new(serde_json::json!({})), tools)
514 }
515
516 #[cfg(feature = "http")]
517 #[test]
518 fn http_shortcut_returns_client_when_configured() {
519 let tools = Arc::new(
520 ToolsBuilder::new()
521 .http(crate::http::HttpClient::new(30).expect("测试 HTTP 客户端应创建成功"))
522 .build()
523 .expect("配置 HTTP 客户端后应构建成功"),
524 );
525 let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
526
527 let client = context.http().expect("已配置时 ctx.http() 应可用");
528 let _builder = client.get("https://api.example.com/test");
529 }
530
531 #[cfg(feature = "http")]
532 #[test]
533 fn http_shortcut_errors_when_not_configured() {
534 let context = empty_context();
535
536 assert!(matches!(
537 context.http(),
538 Err(BaseError::HttpClientNotInitialized)
539 ));
540 }
541
542 #[test]
543 fn slow_query_threshold_is_none_without_registered_config() {
544 let context = empty_context();
545
546 assert_eq!(context.slow_query_threshold(), None);
547 }
548
549 #[test]
550 fn slow_query_threshold_reads_from_tools_config_slot() {
551 let threshold = Duration::from_millis(200);
552 let tools = Arc::new(
553 ToolsBuilder::new()
554 .config(ObservabilityConfig::new().with_slow_query_threshold(threshold))
555 .build()
556 .expect("注册可观测性配置后应构建成功"),
557 );
558 let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
559
560 assert_eq!(context.slow_query_threshold(), Some(threshold));
561 }
562
563 #[test]
564 fn authenticated_roles_are_cached_once_in_stable_order() {
565 let context = empty_context()
566 .with_user(User::new(1, "alice").with_roles(["operator", "admin", "operator"]));
567
568 assert_eq!(
569 context.cached_roles.as_ref(),
570 ["admin".to_string(), "operator".to_string()]
571 );
572 assert_eq!(
573 context.user_roles_set(),
574 Some(&HashSet::from([
575 "admin".to_string(),
576 "operator".to_string()
577 ]))
578 );
579 }
580
581 #[test]
582 fn ui_catalog_rejects_context_without_bound_registry() {
583 let context = empty_context();
584
585 assert!(matches!(
586 context.ui_catalog(),
587 Err(BaseError::ConfigError(message))
588 if message == "ActionContext 未绑定应用 Registry"
589 ));
590 }
591}