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, 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)]
96#[non_exhaustive]
97pub struct ActionContext {
98 pub request: Request,
100 pub request_meta: RequestMeta,
102 pub(crate) user: Option<User>,
106 tools: Arc<Tools>,
108 registry: Option<Arc<Registry>>,
110 table_definition: Option<TableDefinition>,
112 pub request_id: RequestId,
117 pub module: Option<String>,
122 action: Option<String>,
126 #[allow(dead_code)]
129 cached_roles: Arc<[String]>,
130 request_context: RequestContext,
132 tenant: Option<TenantContext>,
134}
135
136impl ActionContext {
137 pub fn new(request: Request, tools: Arc<Tools>) -> Self {
139 Self {
140 request,
141 request_meta: RequestMeta::default(),
142 user: None,
143 tools,
144 registry: None,
145 table_definition: None,
146 request_id: RequestId::generate(),
147 module: None,
148 action: None,
149 cached_roles: Arc::from(Vec::new()),
150 request_context: RequestContext::default(),
151 tenant: None,
152 }
153 }
154
155 pub fn tools(&self) -> &Tools {
157 &self.tools
158 }
159
160 #[cfg(feature = "http")]
165 pub fn http(&self) -> Result<&crate::http::HttpClient, BaseError> {
166 self.tools.http()
167 }
168
169 fn slow_query_threshold(&self) -> Option<std::time::Duration> {
174 self.tools
175 .config::<crate::observability::ObservabilityConfig>()
176 .ok()
177 .and_then(|config| config.slow_query_threshold)
178 }
179
180 pub fn request_context(&mut self) -> &mut RequestContext {
182 &mut self.request_context
183 }
184
185 pub fn with_tenant(mut self, tenant: TenantContext) -> Self {
187 self.tenant = Some(tenant);
188 self
189 }
190
191 pub fn tenant(&self) -> Result<TenantContext, BaseError> {
193 self.tenant
194 .ok_or_else(|| BaseError::Unauthorized("请求缺少租户上下文".to_string()))
195 }
196
197 pub fn actor(&self) -> Result<ActorContext, BaseError> {
199 self.user
200 .as_ref()
201 .map(|user| ActorContext::new(user.id))
202 .ok_or_else(|| BaseError::Unauthorized("请求缺少已认证操作者".to_string()))
203 }
204
205 pub fn request_id(&self) -> RequestId {
207 self.request_id
208 }
209
210 pub(crate) fn with_registry(mut self, registry: Arc<Registry>) -> Self {
211 self.registry = Some(registry);
212 self
213 }
214
215 pub fn plugins(self) -> Result<Plugins, BaseError> {
217 let registry = self.registry.as_ref().cloned().ok_or_else(|| {
218 BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
219 })?;
220 Ok(Plugins::new(registry, self))
221 }
222
223 #[allow(dead_code)]
228 pub(crate) fn with_user(mut self, user: User) -> Self {
229 self.user = Some(user);
230 self
231 }
232
233 pub fn authenticated_user(&self) -> Option<&User> {
238 self.user.as_ref()
239 }
240
241 pub fn ui_catalog(&self) -> Result<crate::definition::UiCatalog, BaseError> {
245 let registry = self.registry.as_ref().ok_or_else(|| {
246 BaseError::ConfigError("ActionContext 未绑定应用 Registry".to_string())
247 })?;
248 registry.ui_catalog(self)
249 }
250
251 pub fn with_request_id(mut self, request_id: RequestId) -> Self {
256 self.request_id = request_id;
257 self
258 }
259
260 pub fn with_request_meta(mut self, request_meta: RequestMeta) -> Self {
262 self.request_meta = request_meta;
263 self
264 }
265
266 pub fn with_module(mut self, module: impl Into<String>) -> Self {
270 self.module = Some(module.into());
271 self
272 }
273
274 pub fn dispatch_target(&self) -> Option<(&str, &str)> {
279 Some((self.module.as_deref()?, self.action.as_deref()?))
280 }
281
282 pub(crate) fn with_dispatch_target(
284 mut self,
285 module: impl Into<String>,
286 action: impl Into<String>,
287 ) -> Self {
288 self.module = Some(module.into());
289 self.action = Some(action.into());
290 self
291 }
292
293 pub fn with_table_definition(mut self, definition: TableDefinition) -> Self {
295 self.table_definition = Some(definition);
296 self
297 }
298
299 pub fn table_definition(&self) -> Result<&TableDefinition, BaseError> {
301 self.table_definition
302 .as_ref()
303 .ok_or(BaseError::TableDefinitionNotSet)
304 }
305
306 pub(crate) fn extract_input_owned<I: DeserializeOwned>(&mut self) -> Result<I, BaseError> {
311 let body = std::mem::take(&mut self.request.body);
312 serde_json::from_value(body)
313 .map_err(|e| BaseError::ParamInvalid("body".to_string(), e.to_string()))
314 }
315
316 pub fn table_query(&self) -> Result<TableQuery, BaseError> {
328 let definition = self
329 .table_definition
330 .as_ref()
331 .ok_or(BaseError::TableDefinitionNotSet)?;
332
333 let roles_set = self.user_roles_set();
335 let user_roles: Arc<[String]> = Arc::from(
336 roles_set
337 .map(|s| s.iter().cloned().collect::<Vec<_>>())
338 .unwrap_or_default(),
339 );
340
341 #[cfg(feature = "mysql")]
343 let pool = self
344 .tools
345 .optional_mysql()?
346 .map(|database| Arc::new(database.pool().clone()));
347 #[cfg(not(feature = "mysql"))]
348 let pool = None;
349
350 let slow_threshold = self.slow_query_threshold();
353 let mut query = TableQuery::new(definition.shared_config(), user_roles, pool)
354 .with_slow_threshold(slow_threshold)
355 .with_request_id(self.request_id);
356 if let Some(field) = definition.tenant_key_field() {
357 let tenant = self.tenant()?;
358 if !tenant.is_system() {
359 let tenant_id = tenant.id().ok_or_else(|| {
360 BaseError::Unauthorized("普通租户上下文缺少 tenant id".to_string())
361 })?;
362 query = query.scope_tenant(field, serde_json::json!(tenant_id.get()))?;
363 }
364 }
365 Ok(query)
366 }
367
368 pub fn tables(&self) -> Result<Tables, BaseError> {
370 self.table_query().map(Tables::new)
371 }
372
373 #[cfg(feature = "mysql")]
397 pub async fn begin_transaction(&self) -> Result<yang_db::Transaction, BaseError> {
398 self.tools
399 .mysql()?
400 .transaction()
401 .await
402 .map_err(BaseError::DatabaseTransactionFailed)
403 }
404
405 pub fn user_roles(&self) -> Vec<String> {
411 self.user
412 .as_ref()
413 .map(|u| u.roles.iter().cloned().collect())
414 .unwrap_or_default()
415 }
416
417 pub fn user_roles_set(&self) -> Option<&HashSet<String>> {
427 self.user.as_ref().map(|u| &u.roles)
428 }
429}
430
431#[cfg(test)]
432mod tests {
433 use super::*;
434 use crate::observability::ObservabilityConfig;
435 use crate::tools::ToolsBuilder;
436 use std::time::Duration;
437
438 fn empty_context() -> ActionContext {
439 let tools = Arc::new(ToolsBuilder::new().build().expect("空 Tools 应构建成功"));
440 ActionContext::new(Request::new(serde_json::json!({})), tools)
441 }
442
443 #[cfg(feature = "http")]
444 #[test]
445 fn http_shortcut_returns_client_when_configured() {
446 let tools = Arc::new(
447 ToolsBuilder::new()
448 .http(crate::http::HttpClient::new(30).expect("测试 HTTP 客户端应创建成功"))
449 .build()
450 .expect("配置 HTTP 客户端后应构建成功"),
451 );
452 let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
453
454 let client = context.http().expect("已配置时 ctx.http() 应可用");
455 let _builder = client.get("https://api.example.com/test");
456 }
457
458 #[cfg(feature = "http")]
459 #[test]
460 fn http_shortcut_errors_when_not_configured() {
461 let context = empty_context();
462
463 assert!(matches!(
464 context.http(),
465 Err(BaseError::HttpClientNotInitialized)
466 ));
467 }
468
469 #[test]
470 fn slow_query_threshold_is_none_without_registered_config() {
471 let context = empty_context();
472
473 assert_eq!(context.slow_query_threshold(), None);
474 }
475
476 #[test]
477 fn slow_query_threshold_reads_from_tools_config_slot() {
478 let threshold = Duration::from_millis(200);
479 let tools = Arc::new(
480 ToolsBuilder::new()
481 .config(ObservabilityConfig::new().with_slow_query_threshold(threshold))
482 .build()
483 .expect("注册可观测性配置后应构建成功"),
484 );
485 let context = ActionContext::new(Request::new(serde_json::json!({})), tools);
486
487 assert_eq!(context.slow_query_threshold(), Some(threshold));
488 }
489
490 #[test]
491 fn ui_catalog_rejects_context_without_bound_registry() {
492 let context = empty_context();
493
494 assert!(matches!(
495 context.ui_catalog(),
496 Err(BaseError::ConfigError(message))
497 if message == "ActionContext 未绑定应用 Registry"
498 ));
499 }
500}