From 911a53e7ac1396915edaeb79e818964a43d09ee3 Mon Sep 17 00:00:00 2001 From: ZzIsGod1019 <1498852723@qq.com> Date: Tue, 17 Oct 2023 22:00:22 +0800 Subject: [PATCH] flow: finish front action (#485) * flow: update dto * flow:update * flow: front condition finish * flow:finish --- basic/src/rbum/dto/rbum_safe_dto.rs | 6 +- clients/hwsms/src/ext/mod.rs | 2 +- clients/hwsms/src/ext/reach.rs | 14 +++- clients/hwsms/src/lib.rs | 7 +- gateway/spacegate/src/plugin/auth.rs | 50 +++++++------ .../flow/src/api/cc/flow_cc_inst_api.rs | 11 +++ middleware/flow/src/dto/flow_external_dto.rs | 13 +++- middleware/flow/src/flow_initializer.rs | 9 ++- .../flow/src/serv/flow_external_serv.rs | 47 +++++++++++- middleware/flow/src/serv/flow_inst_serv.rs | 73 ++++++++++++++++++- middleware/flow/src/serv/flow_model_serv.rs | 21 ++++-- middleware/flow/tests/mock_api.rs | 5 +- middleware/flow/tests/test_flow_scenes_fsm.rs | 8 ++ sdk/invoke/src/clients/base_spi_client.rs | 2 +- sdk/invoke/src/clients/iam_client.rs | 7 +- sdk/invoke/src/clients/spi_log_client.rs | 2 +- sdk/invoke/src/invoke_enumeration.rs | 4 +- sdk/invoke/src/lib.rs | 2 +- sdk/simple-invoke-client-macro/src/lib.rs | 2 +- spi/spi-conf/src/api/nacos/grpc/mod.rs | 4 +- spi/spi-conf/src/conf_initializer.rs | 6 +- .../console_system/api/iam_cs_tenant_api.rs | 2 +- support/reach/src/api/cc/message.rs | 3 +- support/reach/src/config/sms.rs | 2 +- support/reach/src/dto/enums.rs | 2 +- support/reach/src/init.rs | 37 +++++----- support/reach/src/serv/message.rs | 4 +- support/reach/src/task/event_listener.rs | 20 ++--- support/reach/tests/test_reach_common.rs | 4 +- support/reach/tests/test_send_client.rs | 2 +- 30 files changed, 262 insertions(+), 109 deletions(-) diff --git a/basic/src/rbum/dto/rbum_safe_dto.rs b/basic/src/rbum/dto/rbum_safe_dto.rs index 8f5de05ad..dfbea8ddd 100644 --- a/basic/src/rbum/dto/rbum_safe_dto.rs +++ b/basic/src/rbum/dto/rbum_safe_dto.rs @@ -1,10 +1,10 @@ -use serde::{Serialize, Deserialize}; +use serde::{Deserialize, Serialize}; +#[cfg(feature = "default")] +use tardis::db::sea_orm; use tardis::{ chrono::{DateTime, Utc}, web::poem_openapi, }; -#[cfg(feature = "default")] -use tardis::db::sea_orm; #[derive(Debug, Clone, Default, Serialize)] #[cfg_attr(feature = "default", derive(poem_openapi::Object, sea_orm::FromQueryResult))] pub struct RbumSafeSummaryResp { diff --git a/clients/hwsms/src/ext/mod.rs b/clients/hwsms/src/ext/mod.rs index 147866678..17f769a44 100644 --- a/clients/hwsms/src/ext/mod.rs +++ b/clients/hwsms/src/ext/mod.rs @@ -1,4 +1,4 @@ //! Extented features #[cfg(feature = "reach")] -mod reach; \ No newline at end of file +mod reach; diff --git a/clients/hwsms/src/ext/reach.rs b/clients/hwsms/src/ext/reach.rs index bbb8aa989..5dad34430 100644 --- a/clients/hwsms/src/ext/reach.rs +++ b/clients/hwsms/src/ext/reach.rs @@ -1,15 +1,21 @@ -use std::{collections::HashSet, sync::{Arc, OnceLock}}; +use std::{ + collections::HashSet, + sync::{Arc, OnceLock}, +}; use bios_reach::{ client::{GenericTemplate, SendChannel}, - dto::{ContentReplace, ReachChannelKind}, config::ReachConfig, consts::MODULE_CODE, + config::ReachConfig, + consts::MODULE_CODE, + dto::{ContentReplace, ReachChannelKind}, }; use tardis::{ async_trait::async_trait, - basic::{error::TardisError, result::TardisResult}, TardisFuns, + basic::{error::TardisError, result::TardisResult}, + TardisFuns, }; -use crate::{SendSmsRequest, SmsContent, SmsClient}; +use crate::{SendSmsRequest, SmsClient, SmsContent}; #[async_trait] impl SendChannel for crate::SmsClient { diff --git a/clients/hwsms/src/lib.rs b/clients/hwsms/src/lib.rs index 712698926..de7dcb305 100644 --- a/clients/hwsms/src/lib.rs +++ b/clients/hwsms/src/lib.rs @@ -3,16 +3,17 @@ use tardis::{ basic::result::TardisResult, - chrono::{Utc, SecondsFormat}, + chrono::{SecondsFormat, Utc}, + crypto::rust_crypto::sha2::Sha256, rand::random, url::Url, web::reqwest::{ header::{HeaderMap, HeaderValue, AUTHORIZATION}, Client, - }, crypto::rust_crypto::sha2::Sha256, + }, }; -mod ext; mod api; +mod ext; pub use api::*; mod model; pub use model::*; diff --git a/gateway/spacegate/src/plugin/auth.rs b/gateway/spacegate/src/plugin/auth.rs index fd904f326..292c128b6 100644 --- a/gateway/spacegate/src/plugin/auth.rs +++ b/gateway/spacegate/src/plugin/auth.rs @@ -80,7 +80,7 @@ pub struct SgFilterAuth { /// |---------------|-----------|---------------------| /// | `/apis` | `apis` | `/{true_url}` | /// |`/prefix/apis` | `apis` |`/prefix/{true_url}` | - mix_replace_url:String, + mix_replace_url: String, } impl Default for SgFilterAuth { @@ -201,9 +201,9 @@ impl SgPluginFilter for SgFilterAuth { return Ok((true, ctx)); } - log::trace!("[Plugin.Auth] request filter info: request path is {}",ctx.request.get_uri().path()); + log::trace!("[Plugin.Auth] request filter info: request path is {}", ctx.request.get_uri().path()); if ctx.request.get_method().eq(&Method::GET) && ctx.request.get_uri().path() == self.fetch_server_config_path.as_str() { - log::debug!("[Plugin.Auth] request path hit fetch server config path: {}",self.fetch_server_config_path); + log::debug!("[Plugin.Auth] request path hit fetch server config path: {}", self.fetch_server_config_path); ctx.set_action(SgRouteFilterRequestAction::Response); let mut headers = HeaderMap::new(); headers.insert(http::header::CONTENT_TYPE, HeaderValue::from_static("application/json")); @@ -223,7 +223,7 @@ impl SgPluginFilter for SgFilterAuth { if self.auth_config.strict_security_mode && !is_true_mix_req { log::debug!("[Plugin.Auth] handle mix request"); - let mut ctx = mix_req_to_ctx(&self.auth_config,&self.mix_replace_url, ctx).await?; + let mut ctx = mix_req_to_ctx(&self.auth_config, &self.mix_replace_url, ctx).await?; ctx.request.set_header_str(&self.header_is_mix_req, "true")?; return Ok((false, ctx)); } @@ -294,7 +294,7 @@ impl SgPluginFilter for SgFilterAuth { } } -async fn mix_req_to_ctx(auth_config: &AuthConfig,mix_replace_url:&str, mut ctx: SgRoutePluginContext) -> TardisResult { +async fn mix_req_to_ctx(auth_config: &AuthConfig, mix_replace_url: &str, mut ctx: SgRoutePluginContext) -> TardisResult { let body = ctx.request.take_body_into_bytes().await?; let string_body = String::from_utf8_lossy(&body).trim_matches('"').to_string(); if string_body.is_empty() { @@ -355,7 +355,7 @@ async fn mix_req_to_ctx(auth_config: &AuthConfig,mix_replace_url:&str, mut ctx: None => real_ip, }; ctx.request.set_header_str("X-Forwarded-For", &forwarded_for)?; - ctx.request.set_header_str(hyper::header::CONTENT_LENGTH.as_str(),mix_body.body.as_bytes().len().to_string().as_str())?; + ctx.request.set_header_str(hyper::header::CONTENT_LENGTH.as_str(), mix_body.body.as_bytes().len().to_string().as_str())?; ctx.request.set_body(mix_body.body); Ok(ctx) } @@ -471,7 +471,7 @@ mod tests { use super::*; #[tokio::test] - async fn test(){ + async fn test() { env::set_var("RUST_LOG", "info,bios_spacegate=trace,bios_auth=trace,tardis=trace"); tracing_subscriber::fmt::init(); @@ -733,7 +733,7 @@ mod tests { cache_url: env::var("TARDIS_FW.CACHE.URL").unwrap(), ..Default::default() }; - filter_auth.auth_config.strict_security_mode=true; + filter_auth.auth_config.strict_security_mode = true; filter_auth .init(&SgPluginFilterInitDto { @@ -765,7 +765,7 @@ mod tests { let data: Value = serde_json::from_str(&String::from_utf8_lossy( &hyper::body::to_bytes(server_config_resp.body_mut()).await.unwrap().iter().cloned().collect::>(), )) - .unwrap(); + .unwrap(); let pub_key = data["data"]["pub_key"].as_str().unwrap(); let server_sm2 = TardisCryptoSm2 {}; @@ -774,24 +774,28 @@ mod tests { let front_pri_key = TardisFuns::crypto.sm2.new_private_key().unwrap(); let front_pub_key = TardisFuns::crypto.sm2.new_public_key(&front_pri_key).unwrap(); - //=========request GET by apis============ - let true_path="get_path"; - let body=MixRequestBody{ + let true_path = "get_path"; + let body = MixRequestBody { method: "GET".to_string(), uri: true_path.to_string(), body: "".to_string(), headers: Default::default(), ts: 0.0, }; - let mix_body=TardisFuns::json.obj_to_string(&body).unwrap(); + let mix_body = TardisFuns::json.obj_to_string(&body).unwrap(); let mut header = HeaderMap::new(); - let (crypto_body, bios_crypto_value) = crypto_req(&mix_body, server_public_key.serialize().unwrap().as_ref(), front_pub_key.serialize().unwrap().as_ref(), true); + let (crypto_body, bios_crypto_value) = crypto_req( + &mix_body, + server_public_key.serialize().unwrap().as_ref(), + front_pub_key.serialize().unwrap().as_ref(), + true, + ); header.insert("Bios-Crypto", bios_crypto_value.parse().unwrap()); - header.insert(hyper::header::CONTENT_LENGTH,crypto_body.as_bytes().len().to_string().parse().unwrap()); + header.insert(hyper::header::CONTENT_LENGTH, crypto_body.as_bytes().len().to_string().parse().unwrap()); let ctx = SgRoutePluginContext::new_http( Method::POST, - Uri::from_str(&format!("http://sg.idealworld.group/{}",filter_auth.mix_replace_url)).unwrap(), + Uri::from_str(&format!("http://sg.idealworld.group/{}", filter_auth.mix_replace_url)).unwrap(), Version::HTTP_11, header, Body::from(crypto_body), @@ -801,17 +805,19 @@ mod tests { ); let (is_ok, mut before_filter_ctx) = filter_auth.req_filter("", ctx).await.unwrap(); assert!(!is_ok); - assert_eq!(before_filter_ctx.get_action(),&SgRouteFilterRequestAction::Redirect); - assert_eq!(before_filter_ctx.request.get_uri().path(),&format!("/{}",true_path)); - assert_eq!(before_filter_ctx.request.get_method(),&Method::GET); - assert_eq!(before_filter_ctx.request.get_headers().get(hyper::header::CONTENT_LENGTH),Some(&HeaderValue::from_static("0"))); + assert_eq!(before_filter_ctx.get_action(), &SgRouteFilterRequestAction::Redirect); + assert_eq!(before_filter_ctx.request.get_uri().path(), &format!("/{}", true_path)); + assert_eq!(before_filter_ctx.request.get_method(), &Method::GET); + assert_eq!( + before_filter_ctx.request.get_headers().get(hyper::header::CONTENT_LENGTH), + Some(&HeaderValue::from_static("0")) + ); let (is_ok, mut before_filter_ctx) = filter_auth.req_filter("", before_filter_ctx).await.unwrap(); assert!(is_ok); - println!("before_filter_ctx=={:?}",before_filter_ctx); + println!("before_filter_ctx=={:?}", before_filter_ctx); let req_body = before_filter_ctx.request.dump_body().await.unwrap(); assert!(req_body.is_empty()); - filter_auth.destroy().await.unwrap(); } diff --git a/middleware/flow/src/api/cc/flow_cc_inst_api.rs b/middleware/flow/src/api/cc/flow_cc_inst_api.rs index ec0e05937..c3fe9081a 100644 --- a/middleware/flow/src/api/cc/flow_cc_inst_api.rs +++ b/middleware/flow/src/api/cc/flow_cc_inst_api.rs @@ -116,4 +116,15 @@ impl FlowCcInstApi { funs.commit().await?; TardisResp::ok(Void {}) } + + /// trigger instance front action / 触发前置动作 + #[oai(path = "/trigger_front_action", method = "get")] + async fn trigger_front_action(&self) -> TardisApiResult { + let mut funs = flow_constants::get_tardis_inst(); + funs.begin().await?; + FlowInstServ::trigger_front_action(&funs).await?; + funs.commit().await?; + + TardisResp::ok(Void {}) + } } diff --git a/middleware/flow/src/dto/flow_external_dto.rs b/middleware/flow/src/dto/flow_external_dto.rs index b9733c2e3..16ecd6760 100644 --- a/middleware/flow/src/dto/flow_external_dto.rs +++ b/middleware/flow/src/dto/flow_external_dto.rs @@ -5,7 +5,7 @@ use tardis::web::poem_openapi::{ types::{ParseFromJSON, ToJSON}, }; -#[derive(Serialize, Deserialize, Debug, poem_openapi::Object)] +#[derive(Serialize, Deserialize, Debug, Default, poem_openapi::Object)] pub struct FlowExternalReq { pub kind: FlowExternalKind, pub curr_tag: String, @@ -13,14 +13,18 @@ pub struct FlowExternalReq { pub inst_id: String, pub target_state: Option, pub original_state: Option, + pub owner_paths: String, + pub obj_ids: Vec, pub params: Vec, } -#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, poem_openapi::Enum)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize, poem_openapi::Enum)] pub enum FlowExternalKind { + #[default] FetchRelObj, ModifyField, NotifyChanges, + QueryField, } #[derive(Debug, Deserialize, Serialize, poem_openapi::Object, Clone)] @@ -59,3 +63,8 @@ pub struct FlowExternalModifyFieldResp {} #[derive(Serialize, Deserialize, Debug, poem_openapi::Object)] pub struct FlowExternalNotifyChangesResp {} + +#[derive(Serialize, Deserialize, Debug, Default, poem_openapi::Object)] +pub struct FlowExternalQueryFieldResp { + pub objs: Vec, +} diff --git a/middleware/flow/src/flow_initializer.rs b/middleware/flow/src/flow_initializer.rs index 61735b4ab..5d39a2450 100644 --- a/middleware/flow/src/flow_initializer.rs +++ b/middleware/flow/src/flow_initializer.rs @@ -32,7 +32,9 @@ use crate::{ dto::{ flow_model_dto::FlowModelFilterReq, flow_state_dto::FlowSysStateKind, - flow_transition_dto::{FlowTransitionActionChangeInfo, FlowTransitionDoubleCheckInfo, FlowTransitionInitInfo, FlowTransitionActionChangeKind, FlowTransitionActionByVarChangeInfoChangedKind}, + flow_transition_dto::{ + FlowTransitionActionByVarChangeInfoChangedKind, FlowTransitionActionChangeInfo, FlowTransitionActionChangeKind, FlowTransitionDoubleCheckInfo, FlowTransitionInitInfo, + }, }, flow_config::{BasicInfo, FlowBasicInfoManager, FlowConfig}, flow_constants, @@ -76,6 +78,7 @@ pub async fn init_db(mut funs: TardisFunsInst) -> TardisResult<()> { funs.begin().await?; if check_initialized(&funs, &ctx).await? { init_basic_info(&funs).await?; + self::modify_post_actions(&funs, &ctx).await?; } else { let db_kind = TardisFuns::reldb().backend(); let compatible_type = TardisFuns::reldb().compatible_type(); @@ -85,7 +88,6 @@ pub async fn init_db(mut funs: TardisFunsInst) -> TardisResult<()> { funs.db().init(flow_inst::ActiveModel::init(db_kind, None, compatible_type.clone())).await?; funs.db().init(flow_config::ActiveModel::init(db_kind, None, compatible_type.clone())).await?; init_rbum_data(&funs, &ctx).await?; - self::modify_post_actions(&funs, &ctx).await?; }; funs.commit().await?; Ok(()) @@ -130,7 +132,8 @@ pub async fn modify_post_actions(funs: &TardisFunsInst, ctx: &TardisContext) -> id: String, action_by_post_changes: Value, } - let transactions = funs.db() + let transactions = funs + .db() .find_dtos::( Query::select() .columns([ diff --git a/middleware/flow/src/serv/flow_external_serv.rs b/middleware/flow/src/serv/flow_external_serv.rs index 556633738..8c3aa6984 100644 --- a/middleware/flow/src/serv/flow_external_serv.rs +++ b/middleware/flow/src/serv/flow_external_serv.rs @@ -9,7 +9,8 @@ use tardis::{ use crate::{ dto::flow_external_dto::{ - FlowExternalFetchRelObjResp, FlowExternalKind, FlowExternalModifyFieldResp, FlowExternalNotifyChangesResp, FlowExternalParams, FlowExternalReq, FlowExternalResp, + FlowExternalFetchRelObjResp, FlowExternalKind, FlowExternalModifyFieldResp, FlowExternalNotifyChangesResp, FlowExternalParams, FlowExternalQueryFieldResp, FlowExternalReq, + FlowExternalResp, }, flow_config::FlowConfig, flow_constants, @@ -33,8 +34,6 @@ impl FlowExternalServ { inst_id: inst_id.to_string(), curr_tag: tag.to_string(), curr_bus_obj_id: rel_business_obj_id.to_string(), - target_state: None, - original_state: None, params: rel_tags .into_iter() .map(|tag| FlowExternalParams { @@ -44,6 +43,7 @@ impl FlowExternalServ { value: None, }) .collect_vec(), + ..Default::default() }; debug!("do_fetch_rel_obj body: {:?}", body); let resp: FlowExternalResp = funs @@ -83,6 +83,7 @@ impl FlowExternalServ { target_state, original_state, params, + ..Default::default() }; debug!("do_modify_field body: {:?}", body); let resp: FlowExternalResp = funs @@ -120,7 +121,7 @@ impl FlowExternalServ { curr_bus_obj_id: rel_business_obj_id.to_string(), target_state: Some(target_state), original_state: Some(original_state), - params: vec![], + ..Default::default() }; debug!("do_notify_changes body: {:?}", body); let resp: FlowExternalResp = funs @@ -153,6 +154,44 @@ impl FlowExternalServ { } } + pub async fn do_query_field( + tag: &str, + rel_business_obj_ids: Vec, + own_paths: &str, + ctx: &TardisContext, + funs: &TardisFunsInst, + ) -> TardisResult { + let external_url = Self::get_external_url(tag, ctx, funs).await?; + if external_url.is_empty() { + return Ok(FlowExternalQueryFieldResp::default()); + } + + let header = Self::headers(None, funs, ctx).await?; + let body = FlowExternalReq { + kind: FlowExternalKind::QueryField, + inst_id: "".to_string(), + curr_tag: tag.to_string(), + curr_bus_obj_id: "".to_string(), + owner_paths: own_paths.to_string(), + obj_ids: rel_business_obj_ids, + target_state: None, + original_state: None, + params: vec![], + }; + debug!("do_query_field body: {:?}", body); + let resp: FlowExternalResp = funs + .web_client() + .post(&external_url, &body, header) + .await? + .body + .ok_or_else(|| funs.err().internal_error("flow_external", "do_query_field", "illegal response", "500-external-illegal-response"))?; + if let Some(data) = resp.body { + Ok(data) + } else { + Err(funs.err().internal_error("flow_external", "do_query_field", "illegal response", "500-external-illegal-response")) + } + } + async fn get_external_url(tag: &str, ctx: &TardisContext, funs: &TardisFunsInst) -> TardisResult { let external_url = SpiKvClient::get_item(format!("{}:config:{}", flow_constants::DOMAIN_CODE, tag), None, funs, ctx) .await? diff --git a/middleware/flow/src/serv/flow_inst_serv.rs b/middleware/flow/src/serv/flow_inst_serv.rs index 0a34a526f..449b7447a 100644 --- a/middleware/flow/src/serv/flow_inst_serv.rs +++ b/middleware/flow/src/serv/flow_inst_serv.rs @@ -30,7 +30,7 @@ use tardis::{ }; use crate::{ - domain::flow_inst, + domain::{flow_inst, flow_transition}, dto::{ flow_external_dto::FlowExternalParams, flow_inst_dto::{ @@ -1299,4 +1299,75 @@ impl FlowInstServ { } } } + + pub async fn trigger_front_action(funs: &TardisFunsInst) -> TardisResult<()> { + #[derive(sea_orm::FromQueryResult)] + pub struct FloTransitionsResult { + rel_flow_model_id: String, + action_by_front_changes: Value, + } + #[derive(sea_orm::FromQueryResult)] + pub struct FlowInstanceResult { + id: String, + } + // find models + let global_ctx = TardisContext::default(); + // let model_id = funs + // .db() + // .find_dtos::( + // Query::select() + // .columns([flow_transition::Column::RelFlowModelId]) + // .from(flow_transition::Entity) + // .and_where(Expr::cust_with_expr("JSON_ARRAY_LENGTH($1) > 1", Expr::col(flow_transition::Column::ActionByFrontChanges))), + // ) + // .await? + // .iter() + // .map(|res| res.rel_flow_model_id.clone()) + // .collect_vec(); + let rel_flow_model_ids = funs + .db() + .find_dtos::( + Query::select().columns([flow_transition::Column::RelFlowModelId, flow_transition::Column::ActionByFrontChanges]).from(flow_transition::Entity), + ) + .await? + .iter() + .filter(|res| !TardisFuns::json.json_to_obj::>(res.action_by_front_changes.clone()).unwrap_or_default().is_empty()) + .map(|res| res.rel_flow_model_id.clone()) + .collect_vec(); + // find models + let model_ids = FlowModelServ::find_detail_items( + &FlowModelFilterReq { + basic: RbumBasicFilterReq { + ids: Some(rel_flow_model_ids), + ..Default::default() + }, + ..Default::default() + }, + None, + None, + funs, + &global_ctx, + ) + .await? + .into_iter() + .filter(|model| { + model + .transitions() + .into_iter() + .any(|trans| trans.action_by_front_changes().into_iter().any(|action| action.right_value == FlowTransitionFrontActionRightValue::RealTime)) + }) + .map(|model| model.id) + .collect_vec(); + let flow_insts = funs + .db() + .find_dtos::( + Query::select().columns([flow_inst::Column::Id]).from(flow_inst::Entity).and_where(Expr::col(flow_inst::Column::RelFlowModelId).is_in(&model_ids)), + ) + .await?; + for flow_inst in flow_insts { + Self::do_front_change(&flow_inst.id, &global_ctx, funs).await?; + } + + Ok(()) + } } diff --git a/middleware/flow/src/serv/flow_model_serv.rs b/middleware/flow/src/serv/flow_model_serv.rs index c7df7a476..d9f3b740a 100644 --- a/middleware/flow/src/serv/flow_model_serv.rs +++ b/middleware/flow/src/serv/flow_model_serv.rs @@ -708,6 +708,10 @@ impl FlowModelServ { // Find model by tag and template id pub async fn get_models(tags: Vec<&str>, template_id: Option, funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult> { + let global_ctx = TardisContext { + own_paths: "".to_string(), + ..ctx.clone() + }; let mut result = HashMap::new(); let models = if let Some(template_id) = &template_id { @@ -717,6 +721,7 @@ impl FlowModelServ { &FlowModelFilterReq { basic: RbumBasicFilterReq { ignore_scope: true, + with_sub_own_paths: true, ..Default::default() }, rel_template_id: Some(template_id.clone()), @@ -727,7 +732,7 @@ impl FlowModelServ { None, None, funs, - ctx, + &global_ctx, ) .await? } else { @@ -797,8 +802,8 @@ impl FlowModelServ { // add custom model by template model // rel_template_id: Associated parent template id - // current_template_id: Current tempalte id - pub async fn add_custom_model(tag: &str, rel_template_id: &str, current_template_id: Option, funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult { + // current_template_id: Current template id + pub async fn add_custom_model(tag: &str, parent_template_id: &str, rel_template_id: Option, funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult { let current_model = Self::find_one_detail_item( &FlowModelFilterReq { basic: RbumBasicFilterReq { @@ -806,7 +811,7 @@ impl FlowModelServ { ..Default::default() }, tags: Some(vec![tag.to_string()]), - rel_template_id: current_template_id.clone(), + rel_template_id: rel_template_id.clone(), ..Default::default() }, funs, @@ -822,7 +827,7 @@ impl FlowModelServ { ..ctx.clone() }; - let basic = if !rel_template_id.is_empty() { + let basic = if !parent_template_id.is_empty() { RbumBasicFilterReq { with_sub_own_paths: true, ignore_scope: true, @@ -835,7 +840,7 @@ impl FlowModelServ { &FlowModelFilterReq { basic, tags: Some(vec![tag.to_string()]), - rel_template_id: Some(rel_template_id.to_string()), + rel_template_id: Some(parent_template_id.to_string()), ..Default::default() }, funs, @@ -869,8 +874,8 @@ impl FlowModelServ { icon: Some(parent_model.icon), info: Some(parent_model.info), init_state_id: parent_model.init_state_id, - template: current_template_id.is_some(), - rel_template_id: current_template_id, + template: rel_template_id.is_some(), + rel_template_id, transitions: None, rel_model_id: Some(parent_model.id.clone()), tag: Some(parent_model.tag), diff --git a/middleware/flow/tests/mock_api.rs b/middleware/flow/tests/mock_api.rs index de98513d5..ebdb802a7 100644 --- a/middleware/flow/tests/mock_api.rs +++ b/middleware/flow/tests/mock_api.rs @@ -1,5 +1,5 @@ use bios_mw_flow::dto::flow_external_dto::{ - FlowExternalFetchRelObjResp, FlowExternalKind, FlowExternalModifyFieldResp, FlowExternalNotifyChangesResp, FlowExternalReq, RelBusObjResp, + FlowExternalFetchRelObjResp, FlowExternalKind, FlowExternalModifyFieldResp, FlowExternalNotifyChangesResp, FlowExternalQueryFieldResp, FlowExternalReq, RelBusObjResp, }; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -56,6 +56,9 @@ impl MockApi { FlowExternalKind::NotifyChanges => { json!(FlowExternalNotifyChangesResp {}) } + FlowExternalKind::QueryField => { + json!(FlowExternalQueryFieldResp { objs: vec![] }) + } }; MockResp::ok(result) } diff --git a/middleware/flow/tests/test_flow_scenes_fsm.rs b/middleware/flow/tests/test_flow_scenes_fsm.rs index 4a70f47a5..764fa206b 100644 --- a/middleware/flow/tests/test_flow_scenes_fsm.rs +++ b/middleware/flow/tests/test_flow_scenes_fsm.rs @@ -471,6 +471,12 @@ pub async fn test(flow_client: &mut TestHttpClient, _kv_client: &mut TestHttpCli }, ) .await; + + ctx.own_paths = "t2".to_string(); + flow_client.set_auth(&ctx)?; + let other_models: HashMap = flow_client.get(&format!("/cc/model/get_models?tag_ids=REQ&temp_id={}", share_template_id)).await; + assert_eq!(req_share_model_id, other_models.get("REQ").unwrap().id.clone()); + ctx.own_paths = "t3/app03".to_string(); flow_client.set_auth(&ctx)?; let mut result: Vec = flow_client @@ -773,6 +779,8 @@ pub async fn test(flow_client: &mut TestHttpClient, _kv_client: &mut TestHttpCli ) .await; assert_eq!(state_and_next_transitions[0].current_flow_state_name, "已完成"); + // + let _: Void = flow_client.get("/cc/inst/trigger_front_action").await; Ok(()) } diff --git a/sdk/invoke/src/clients/base_spi_client.rs b/sdk/invoke/src/clients/base_spi_client.rs index 5f261aaa3..37f20e364 100644 --- a/sdk/invoke/src/clients/base_spi_client.rs +++ b/sdk/invoke/src/clients/base_spi_client.rs @@ -50,4 +50,4 @@ impl BaseSpiClient { } Err(TardisError::bad_request("The requested schema does not exist", "")) } -} \ No newline at end of file +} diff --git a/sdk/invoke/src/clients/iam_client.rs b/sdk/invoke/src/clients/iam_client.rs index 4ee3a33cd..916b2e58d 100644 --- a/sdk/invoke/src/clients/iam_client.rs +++ b/sdk/invoke/src/clients/iam_client.rs @@ -1,10 +1,7 @@ use std::collections::HashMap; use serde::{Deserialize, Serialize}; -use tardis::{ - basic::dto::TardisContext, - TardisFunsInst, web::poem_openapi, -}; +use tardis::{basic::dto::TardisContext, web::poem_openapi, TardisFunsInst}; use crate::impl_tardis_api_client; @@ -53,4 +50,4 @@ pub struct IamAccountDetailAggResp { impl_tardis_api_client! { IamClient<'_>: {get_account, get ["/ct/account", id] {tenant_id} IamAccountDetailAggResp} -} \ No newline at end of file +} diff --git a/sdk/invoke/src/clients/spi_log_client.rs b/sdk/invoke/src/clients/spi_log_client.rs index 223f5f73c..9b76b3383 100644 --- a/sdk/invoke/src/clients/spi_log_client.rs +++ b/sdk/invoke/src/clients/spi_log_client.rs @@ -119,4 +119,4 @@ impl SpiLogClient { let resp = funs.web_client().put::>>(&format!("{log_url}/ci/item/find"), &find_req, headers.clone()).await?; BaseSpiClient::package_resp(resp) } -} \ No newline at end of file +} diff --git a/sdk/invoke/src/invoke_enumeration.rs b/sdk/invoke/src/invoke_enumeration.rs index 4324c26b3..d736a8be2 100644 --- a/sdk/invoke/src/invoke_enumeration.rs +++ b/sdk/invoke/src/invoke_enumeration.rs @@ -40,5 +40,5 @@ pub enum InvokeModuleKind { Graph, Stats, Schedule, - Iam -} \ No newline at end of file + Iam, +} diff --git a/sdk/invoke/src/lib.rs b/sdk/invoke/src/lib.rs index 5a8240684..6df47c804 100644 --- a/sdk/invoke/src/lib.rs +++ b/sdk/invoke/src/lib.rs @@ -6,4 +6,4 @@ pub mod invoke_enumeration; pub mod invoke_initializer; #[cfg(feature = "macro")] -pub use simple_invoke_client_macro::simple_invoke_client; \ No newline at end of file +pub use simple_invoke_client_macro::simple_invoke_client; diff --git a/sdk/simple-invoke-client-macro/src/lib.rs b/sdk/simple-invoke-client-macro/src/lib.rs index a85ad50fd..3bf88265e 100644 --- a/sdk/simple-invoke-client-macro/src/lib.rs +++ b/sdk/simple-invoke-client-macro/src/lib.rs @@ -172,7 +172,7 @@ impl ApiInfoBuilder { /// # Usage /// This Attribute Macro is used to generate corresponding client methods for you api. /// Simplely add it **upon** `OpenApi` attribute. -/// +/// /// The `Client` is your custom client struct witch implemented `SimpleInvokeClient` trait. /// ```no_run, ignore /// #[simple_invoke_client(Client)] diff --git a/spi/spi-conf/src/api/nacos/grpc/mod.rs b/spi/spi-conf/src/api/nacos/grpc/mod.rs index e644bfe12..5c2ec1b29 100644 --- a/spi/spi-conf/src/api/nacos/grpc/mod.rs +++ b/spi/spi-conf/src/api/nacos/grpc/mod.rs @@ -232,9 +232,7 @@ pub async fn dispatch_request(type_info: &str, value: &str, access_token: Option let Some(token) = access_token else { return Err(TardisError::unauthorized("missing access token", "")); }; - jwt_validate(token, &funs).await.map_err(|e| { - TardisError::unauthorized(&format!("invalid access token, error: {e}, token: {token}"), "") - }) + jwt_validate(token, &funs).await.map_err(|e| TardisError::unauthorized(&format!("invalid access token, error: {e}, token: {token}"), "")) }; let response = match type_info { "ServerCheckRequest" => ServerCheckResponse::success(None).as_payload(), diff --git a/spi/spi-conf/src/conf_initializer.rs b/spi/spi-conf/src/conf_initializer.rs index 6052c1039..28a4d6cfe 100644 --- a/spi/spi-conf/src/conf_initializer.rs +++ b/spi/spi-conf/src/conf_initializer.rs @@ -64,7 +64,5 @@ pub(crate) fn get_tardis_inst() -> TardisFunsInst { pub(crate) fn get_tardis_inst_ref() -> &'static TardisFunsInst { use std::sync::OnceLock; static INST: OnceLock = OnceLock::new(); - INST.get_or_init(|| { - TardisFuns::inst_with_db_conn(DOMAIN_CODE.to_string(), None) - }) -} \ No newline at end of file + INST.get_or_init(|| TardisFuns::inst_with_db_conn(DOMAIN_CODE.to_string(), None)) +} diff --git a/support/iam/src/console_system/api/iam_cs_tenant_api.rs b/support/iam/src/console_system/api/iam_cs_tenant_api.rs index b9d819595..9b890ea8e 100644 --- a/support/iam/src/console_system/api/iam_cs_tenant_api.rs +++ b/support/iam/src/console_system/api/iam_cs_tenant_api.rs @@ -25,7 +25,7 @@ impl IamCsTenantApi { add_remote_ip(request, &ctx.0).await?; let mut funs = iam_constants::get_tardis_inst(); funs.begin().await?; - let result = IamTenantServ::add_tenant_agg(&add_req.0, &funs,&ctx.0).await?.0; + let result = IamTenantServ::add_tenant_agg(&add_req.0, &funs, &ctx.0).await?.0; funs.commit().await?; ctx.0.execute_task().await?; TardisResp::ok(result) diff --git a/support/reach/src/api/cc/message.rs b/support/reach/src/api/cc/message.rs index 06f01fc06..c09f0f2c1 100644 --- a/support/reach/src/api/cc/message.rs +++ b/support/reach/src/api/cc/message.rs @@ -1,6 +1,6 @@ +use bios_basic::rbum::serv::rbum_crud_serv::RbumCrudOperation; use std::collections::{HashMap, HashSet}; use tardis::log as tracing; -use bios_basic::rbum::serv::rbum_crud_serv::RbumCrudOperation; use tardis::web::context_extractor::TardisContextExtractor; use tardis::web::poem_openapi::param::{Path, Query}; @@ -9,7 +9,6 @@ use tardis::web::poem_openapi; use tardis::web::poem_openapi::payload::Json; use tardis::web::web_resp::{TardisApiResult, TardisResp, Void}; - use crate::client::{GenericTemplate, SendChannelMap}; use crate::config::ReachConfig; use crate::consts::*; diff --git a/support/reach/src/config/sms.rs b/support/reach/src/config/sms.rs index 1c7f8e6e5..73c8617d2 100644 --- a/support/reach/src/config/sms.rs +++ b/support/reach/src/config/sms.rs @@ -7,7 +7,7 @@ pub struct SmsConfig { pub app_key: String, pub app_secret: String, pub status_call_back: Option, - + pub sms_pwd_template_id: String, pub sms_general_from: String, pub sms_general_signature: Option, diff --git a/support/reach/src/dto/enums.rs b/support/reach/src/dto/enums.rs index 91cccbb87..39c09e5a2 100644 --- a/support/reach/src/dto/enums.rs +++ b/support/reach/src/dto/enums.rs @@ -1,4 +1,4 @@ -use std::{str::FromStr, fmt::Display}; +use std::{fmt::Display, str::FromStr}; use serde::{Deserialize, Serialize}; use tardis::{ diff --git a/support/reach/src/init.rs b/support/reach/src/init.rs index bab7277e5..2cb357e6c 100644 --- a/support/reach/src/init.rs +++ b/support/reach/src/init.rs @@ -14,10 +14,11 @@ use tardis::{ use crate::{ api, + client::SendChannelMap, config::ReachConfig, consts::{get_tardis_inst, DOMAIN_CODE, DOMAIN_REACH_ID, RBUM_EXT_TABLE_REACH_MESSAGE, RBUM_KIND_CODE_REACH_MESSAGE, REACH_INIT_OWNER}, serv::ReachTriggerSceneService, - task, client::SendChannelMap, + task, }; pub async fn db_init() -> TardisResult<()> { @@ -49,25 +50,27 @@ pub async fn db_init() -> TardisResult<()> { .await? } }; - + // add domain let domain_id = match RbumDomainServ::get_rbum_domain_id_by_code(DOMAIN_CODE, &funs).await? { Some(id) => id, - None => RbumDomainServ::add_rbum( - &mut RbumDomainAddReq { - code: DOMAIN_CODE.into(), - name: DOMAIN_CODE.into(), - note: None, - icon: None, - sort: None, - scope_level: Some(RbumScopeLevelKind::Root), - }, - &funs, - &ctx, - ) - .await? + None => { + RbumDomainServ::add_rbum( + &mut RbumDomainAddReq { + code: DOMAIN_CODE.into(), + name: DOMAIN_CODE.into(), + note: None, + icon: None, + sort: None, + scope_level: Some(RbumScopeLevelKind::Root), + }, + &funs, + &ctx, + ) + .await? + } }; - + DOMAIN_REACH_ID.set(domain_id).expect("fail to set DOMAIN_REACH_ID"); let db_kind = TardisFuns::reldb().backend(); let compatible_type = TardisFuns::reldb().compatible_type(); @@ -89,7 +92,7 @@ pub fn get_reach_send_channel_map() -> &'static SendChannelMap { REACH_SEND_CHANNEL_MAP.get().expect("missing send channel map") } pub async fn init(web_server: &TardisWebServer, send_channels: SendChannelMap) -> TardisResult<()> { - REACH_SEND_CHANNEL_MAP.get_or_init(||send_channels); + REACH_SEND_CHANNEL_MAP.get_or_init(|| send_channels); db_init().await?; api::init(web_server).await?; task::init().await?; diff --git a/support/reach/src/serv/message.rs b/support/reach/src/serv/message.rs index 42820f225..2a1564807 100644 --- a/support/reach/src/serv/message.rs +++ b/support/reach/src/serv/message.rs @@ -8,9 +8,9 @@ use tardis::basic::dto::TardisContext; use tardis::basic::result::TardisResult; use tardis::db::reldb_client::TardisActiveModel; -use tardis::db::sea_orm::sea_query::{Expr, Query, SelectStatement, Alias}; +use tardis::db::sea_orm::sea_query::{Alias, Expr, Query, SelectStatement}; use tardis::db::sea_orm::*; -use tardis::{TardisFunsInst, TardisFuns}; +use tardis::{TardisFuns, TardisFunsInst}; pub struct ReachMessageServ; #[async_trait] diff --git a/support/reach/src/task/event_listener.rs b/support/reach/src/task/event_listener.rs index 97f58d5d4..f57ff90e8 100644 --- a/support/reach/src/task/event_listener.rs +++ b/support/reach/src/task/event_listener.rs @@ -12,7 +12,6 @@ use crate::{consts::*, domain::*, dto::*, serv::*}; #[derive(Debug, Default, Clone)] pub struct EventListener {} - // logic of this part could be modified. impl EventListener { @@ -21,7 +20,7 @@ impl EventListener { funs.mq() .subscribe(MQ_REACH_TOPIC_MESSAGE, |(_, msg)| { log::debug!("Receive message : {msg}"); - async move { + async move { let funs = get_tardis_inst(); let err = |msg: &str| funs.err().not_found("reach", "event_listener", msg, ""); let send_req: ReachMsgSendReq = TardisFuns::json.str_to_obj(&msg)?; @@ -33,10 +32,7 @@ impl EventListener { let scene = funs .db() .get_dto::( - Query::select() - .columns(trigger_scene::Column::iter()) - .from(trigger_scene::Entity) - .and_where(trigger_scene::Column::Code.eq(&send_req.scene_code)), + Query::select().columns(trigger_scene::Column::iter()).from(trigger_scene::Entity).and_where(trigger_scene::Column::Code.eq(&send_req.scene_code)), ) .await? .ok_or_else(|| funs.err().not_found("reach", "event_listener", "cannot find scene", ""))?; @@ -44,7 +40,7 @@ impl EventListener { rel_reach_trigger_scene_id: Some(scene.id.clone()), ..Default::default() }; - + // retrive all related global configs, group by channel let global_configs = ReachTriggerGlobalConfigService::find_detail_rbums(filter, None, None, &funs, &ctx).await?.into_iter().fold(HashMap::new(), |mut map, item| { @@ -54,7 +50,7 @@ impl EventListener { if global_configs.is_empty() { return Err(err("global_configs is empty")); } - + // retrive all instance configs, group by group_code let filter = &ReachTriggerInstanceConfigFilterReq { rel_reach_trigger_scene_id: Some(scene.id), @@ -69,17 +65,17 @@ impl EventListener { map.entry(item.receive_group_code.clone()).or_insert(Vec::new()).push(item); map }); - + let mut instance_group_code = instances.into_iter().filter(|inst| receive_group_code.contains_key(&inst.receive_group_code.clone())).fold(HashMap::new(), |mut map, item| { map.entry(item.receive_group_code.clone()).or_insert(Vec::new()).push(item); map }); - + if instance_group_code.is_empty() { return Ok(()); } - + let (other_receive_collect, other_group_code) = receive_group_code.into_iter().fold( (HashMap::new(), HashSet::new()), |(mut other_receive_collect, mut other_group_code), (group_code, receives)| { @@ -96,7 +92,7 @@ impl EventListener { (other_receive_collect, other_group_code) }, ); - + for (_kind, gc) in global_configs { for (receive_kind, to_res_ids) in &other_receive_collect { if other_group_code.contains(&gc.rel_reach_channel) { diff --git a/support/reach/tests/test_reach_common.rs b/support/reach/tests/test_reach_common.rs index a07613312..bebcc3b3b 100644 --- a/support/reach/tests/test_reach_common.rs +++ b/support/reach/tests/test_reach_common.rs @@ -6,9 +6,9 @@ use bios_basic::rbum::serv::rbum_domain_serv::RbumDomainServ; use bios_basic::rbum::serv::rbum_item_serv::RbumItemServ; use bios_basic::rbum::serv::rbum_kind_serv::RbumKindServ; use bios_basic::{rbum::rbum_config::RbumConfig, test::test_http_client::TestHttpClient}; -use bios_client_hwsms::{SmsResponse, SmsId}; +use bios_client_hwsms::{SmsId, SmsResponse}; use bios_reach::client::SendChannelMap; -use bios_reach::consts::{DOMAIN_CODE, IAM_KEY_PHONE_V_CODE, RBUM_KIND_CODE_REACH_MESSAGE, REACH_INIT_OWNER, get_tardis_inst}; +use bios_reach::consts::{get_tardis_inst, DOMAIN_CODE, IAM_KEY_PHONE_V_CODE, RBUM_KIND_CODE_REACH_MESSAGE, REACH_INIT_OWNER}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::{Arc, OnceLock}; diff --git a/support/reach/tests/test_send_client.rs b/support/reach/tests/test_send_client.rs index 1cb029840..cb4de974d 100644 --- a/support/reach/tests/test_send_client.rs +++ b/support/reach/tests/test_send_client.rs @@ -1,7 +1,7 @@ // std::env::set_var("PROFILE", "prod"); use serde::Deserialize; use std::time::Duration; -use tardis::{basic::result::TardisResult, tokio, testcontainers}; +use tardis::{basic::result::TardisResult, testcontainers, tokio}; mod test_reach_common; use bios_reach::{consts::*, invoke};