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 ActionContext {
148 pub fn new(request: Request, tools: Arc<Tools>) -> Self {
150 Self {
151 request,
152 request_meta: RequestMeta::default(),
153 user: None,
154 tools,
155 registry: None,
156 table_definition: None,
157 request_id: RequestId::generate(),
158 module: None,
159 action: None,
160 cached_roles: Arc::from(Vec::new()),
161 request_context: RequestContext::default(),
162 tenant_access: TenantAccess::Missing,
163 }
164 }
165
166 pub fn tools(&self) -> &Tools {
168 &self.tools
169 }
170
171 #[cfg(feature = "http")]
176 pub fn http(&self) -> Result<&crate::http::HttpClient, BaseError> {
177 self.tools.http()
178 }
179
180 fn slow_query_threshold(&self) -> Option<std::time::Duration> {
185 self.tools
186 .config::<crate::observability::ObservabilityConfig>()
187 .ok()
188 .and_then(|config| config.slow_query_threshold)
189 }
190
191 pub fn request_context(&mut self) -> &mut RequestContext {
193 &mut self.request_context
194 }
195
196 pub fn with_tenant(mut self, tenant: TenantContext) -> Self {
198 self.tenant_access = TenantAccess::Tenant(tenant);
199 self
200 }
201
202 pub(crate) fn with_system_tenant(mut self, capability: SystemTenantCapability) -> Self {
203 self.tenant_access = TenantAccess::System(capability);
204 self
205 }
206
207 pub fn tenant(&self) -> Result<TenantContext, BaseError> {
209 match self.tenant_access {
210 TenantAccess::Tenant(tenant) => Ok(tenant),
211 TenantAccess::Missing | TenantAccess::System(_) => Err(BaseError::Unauthorized(
212 "请求缺少普通租户 capability".to_string(),
213 )),
214 }
215 }
216
217 pub fn system_tenant(&self) -> Result<SystemTenantCapability, BaseError> {
219 match self.tenant_access {
220 TenantAccess::System(capability) => Ok(capability),
221 TenantAccess::Missing | TenantAccess::Tenant(_) => Err(BaseError::PermissionDenied(
222 "请求缺少系统租户 capability".to_string(),
223 )),
224 }
225 }
226
227 pub fn actor(&self) -> Result<ActorContext, BaseError> {
229 self.user
230 .as_ref()
231 .map(|user| ActorContext::new(user.id))
232 .ok_or_else(|| BaseError::Unauthorized("请求缺少已认证操作者".to_string()))
233 }
234
235 pub fn request_id(&self) -> RequestId {
237 self.request_id
238 }
239
240 pub(crate) fn with_registry(mut self, registry: Arc<Registry>) -> Self {
241 self.registry = Some(registry);
242 self
243 }
244
245 pub fn plugins(self) -> Result<Plugins, BaseError> {
247 let registry = self.registry.as_ref().cloned().ok_or_else(|| {
248 BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
249 })?;
250 Ok(Plugins::new(registry, self))
251 }
252
253 #[allow(dead_code)]
258 pub(crate) fn with_user(mut self, user: User) -> Self {
259 let mut roles = user.roles.iter().cloned().collect::<Vec<_>>();
260 roles.sort_unstable();
261 self.cached_roles = Arc::from(roles);
262 self.user = Some(user);
263 self
264 }
265
266 pub fn authenticated_user(&self) -> Option<&User> {
271 self.user.as_ref()
272 }
273
274 pub fn ui_catalog(&self) -> Result<crate::definition::UiCatalog, BaseError> {
278 let registry = self.registry.as_ref().ok_or_else(|| {
279 BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
280 })?;
281 registry.ui_catalog(self)
282 }
283
284 pub fn with_request_id(mut self, request_id: RequestId) -> Self {
289 self.request_id = request_id;
290 self
291 }
292
293 pub fn with_request_meta(mut self, request_meta: RequestMeta) -> Self {
295 self.request_meta = request_meta;
296 self
297 }
298
299 pub fn with_module(mut self, module: impl Into<String>) -> Self {
303 self.module = Some(module.into());
304 self
305 }
306
307 pub fn dispatch_target(&self) -> Option<(&str, &str)> {
312 Some((self.module.as_deref()?, self.action.as_deref()?))
313 }
314
315 pub(crate) fn with_dispatch_target(
317 mut self,
318 module: impl Into<String>,
319 action: impl Into<String>,
320 ) -> Self {
321 self.module = Some(module.into());
322 self.action = Some(action.into());
323 self
324 }
325
326 pub fn with_table_definition(mut self, definition: TableDefinition) -> Self {
328 self.table_definition = Some(definition);
329 self
330 }
331
332 pub fn table_definition(&self) -> Result<&TableDefinition, BaseError> {
334 self.table_definition
335 .as_ref()
336 .ok_or(BaseError::TableDefinitionNotSet)
337 }
338
339 pub(crate) fn extract_input_owned<I: DeserializeOwned>(&mut self) -> Result<I, BaseError> {
344 let body = std::mem::take(&mut self.request.body);
345 serde_json::from_value(body)
346 .map_err(|e| BaseError::ParamInvalid("body".to_string(), e.to_string()))
347 }
348
349 fn base_table_query(&self, definition: &TableDefinition) -> Result<TableQuery, BaseError> {
361 #[cfg(feature = "mysql")]
363 let pool = self
364 .tools
365 .optional_mysql()?
366 .map(|database| Arc::new(database.pool().clone()));
367 #[cfg(not(feature = "mysql"))]
368 let pool = None;
369
370 let slow_threshold = self.slow_query_threshold();
373 Ok(TableQuery::new(
374 definition.shared_config(),
375 Arc::clone(&self.cached_roles),
376 pool,
377 )
378 .with_slow_threshold(slow_threshold)
379 .with_request_id(self.request_id))
380 }
381
382 pub fn table_query(&self) -> Result<TableQuery, BaseError> {
388 let definition = self.table_definition()?;
389 let mut query = self.base_table_query(definition)?;
390 if let Some(field) = definition.tenant_key_field() {
391 query = query.scope_tenant(field, serde_json::json!(self.tenant()?.id().get()))?;
392 }
393 Ok(query)
394 }
395
396 pub fn system_table_query(
402 &self,
403 capability: SystemTenantCapability,
404 ) -> Result<TableQuery, BaseError> {
405 if self.system_tenant()? != capability {
406 return Err(BaseError::PermissionDenied(
407 "系统租户 capability 与当前请求不匹配".to_string(),
408 ));
409 }
410 let definition = self.table_definition()?;
411 self.base_table_query(definition)
412 }
413
414 pub fn tables(&self) -> Result<Tables, BaseError> {
416 self.table_query().map(Tables::new)
417 }
418
419 pub fn system_tables(&self, capability: SystemTenantCapability) -> Result<Tables, BaseError> {
421 self.system_table_query(capability).map(Tables::new)
422 }
423
424 #[cfg(feature = "mysql")]
448 pub async fn begin_transaction(&self) -> Result<yang_db::Transaction, BaseError> {
449 self.tools
450 .mysql()?
451 .transaction()
452 .await
453 .map_err(BaseError::DatabaseTransactionFailed)
454 }
455
456 pub fn user_roles(&self) -> Vec<String> {
462 self.user
463 .as_ref()
464 .map(|u| u.roles.iter().cloned().collect())
465 .unwrap_or_default()
466 }
467
468 pub fn user_roles_set(&self) -> Option<&HashSet<String>> {
478 self.user.as_ref().map(|u| &u.roles)
479 }
480}
481
482#[cfg(test)]
483mod tests {
484 use super::*;
485 use crate::observability::ObservabilityConfig;
486 use crate::tools::ToolsBuilder;
487 use std::time::Duration;
488
489 fn empty_context() -> ActionContext {
490 let tools = Arc::new(ToolsBuilder::new().build().expect("空 Tools 应构建成功"));
491 ActionContext::new(Request::new(serde_json::json!({})), tools)
492 }
493
494 #[cfg(feature = "http")]
495 #[test]
496 fn http_shortcut_returns_client_when_configured() {
497 let tools = Arc::new(
498 ToolsBuilder::new()
499 .http(crate::http::HttpClient::new(30).expect("测试 HTTP 客户端应创建成功"))
500 .build()
501 .expect("配置 HTTP 客户端后应构建成功"),
502 );
503 let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
504
505 let client = context.http().expect("已配置时 ctx.http() 应可用");
506 let _builder = client.get("https://api.example.com/test");
507 }
508
509 #[cfg(feature = "http")]
510 #[test]
511 fn http_shortcut_errors_when_not_configured() {
512 let context = empty_context();
513
514 assert!(matches!(
515 context.http(),
516 Err(BaseError::HttpClientNotInitialized)
517 ));
518 }
519
520 #[test]
521 fn slow_query_threshold_is_none_without_registered_config() {
522 let context = empty_context();
523
524 assert_eq!(context.slow_query_threshold(), None);
525 }
526
527 #[test]
528 fn slow_query_threshold_reads_from_tools_config_slot() {
529 let threshold = Duration::from_millis(200);
530 let tools = Arc::new(
531 ToolsBuilder::new()
532 .config(ObservabilityConfig::new().with_slow_query_threshold(threshold))
533 .build()
534 .expect("注册可观测性配置后应构建成功"),
535 );
536 let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
537
538 assert_eq!(context.slow_query_threshold(), Some(threshold));
539 }
540
541 #[test]
542 fn authenticated_roles_are_cached_once_in_stable_order() {
543 let context = empty_context()
544 .with_user(User::new(1, "alice").with_roles(["operator", "admin", "operator"]));
545
546 assert_eq!(
547 context.cached_roles.as_ref(),
548 ["admin".to_string(), "operator".to_string()]
549 );
550 assert_eq!(
551 context.user_roles_set(),
552 Some(&HashSet::from([
553 "admin".to_string(),
554 "operator".to_string()
555 ]))
556 );
557 }
558
559 #[test]
560 fn ui_catalog_rejects_context_without_bound_registry() {
561 let context = empty_context();
562
563 assert!(matches!(
564 context.ui_catalog(),
565 Err(BaseError::ConfigError(message))
566 if message == "ActionContext 未绑定应用 Registry"
567 ));
568 }
569}