From 6ccf747235d15285600c65c2f3fda0274107aa12 Mon Sep 17 00:00:00 2001 From: RWDai <27391645+RWDai@users.noreply.github.com> Date: Mon, 6 May 2024 17:30:03 +0800 Subject: [PATCH 1/3] solve build failure caused by dependency api changes (#719) --- backend/basic/src/rbum/rbum_config.rs | 2 +- backend/services/bios-all/Cargo.toml | 14 ++++++++++++-- backend/supports/reach/src/domain/message.rs | 3 --- .../supports/reach/src/domain/message_signature.rs | 3 --- .../supports/reach/src/domain/message_template.rs | 3 --- .../reach/src/domain/reach_vcode_strategy.rs | 3 --- .../reach/src/domain/trigger_global_config.rs | 3 --- .../reach/src/domain/trigger_instance_config.rs | 3 --- backend/supports/reach/src/domain/trigger_scene.rs | 3 --- 9 files changed, 13 insertions(+), 24 deletions(-) diff --git a/backend/basic/src/rbum/rbum_config.rs b/backend/basic/src/rbum/rbum_config.rs index 02b417f2c..b9599ba49 100644 --- a/backend/basic/src/rbum/rbum_config.rs +++ b/backend/basic/src/rbum/rbum_config.rs @@ -3,7 +3,7 @@ use std::fmt::Debug; use std::sync::Mutex; use lazy_static::lazy_static; -use serde::{de, Deserialize, Serialize}; +use serde::{Deserialize, Serialize}; use tardis::basic::error::TardisError; use tardis::basic::result::TardisResult; use tardis::TardisFunsInst; diff --git a/backend/services/bios-all/Cargo.toml b/backend/services/bios-all/Cargo.toml index bd84b33e4..8e4755f3b 100644 --- a/backend/services/bios-all/Cargo.toml +++ b/backend/services/bios-all/Cargo.toml @@ -12,7 +12,12 @@ publish.workspace = true [dependencies] serde.workspace = true -tardis = { workspace = true, features = ["web-server", "conf-remote", "cluster", "k8s"] } +tardis = { workspace = true, features = [ + "web-server", + "conf-remote", + "cluster", + "k8s", +] } bios-iam = { path = "../../supports/iam", features = ["spi_search", "spi_kv"] } bios-auth = { path = "../../supports/auth", features = ["web-server"] } bios-reach = { path = "../../supports/reach" } @@ -33,4 +38,9 @@ bios-mw-flow = { path = "../../middlewares/flow" } bios-mw-event = { path = "../../middlewares/event" } # clients -bios-client-hwsms = { path = "../../../frontend/clients/hwsms", features = ["reach"] } +bios-client-hwsms = { path = "../../../frontend/clients/hwsms", features = [ + "reach", +] } + +# see [issue](https://github.com/kube-rs/kube/issues/1486) +json-patch = { version = "=1.2.0" } diff --git a/backend/supports/reach/src/domain/message.rs b/backend/supports/reach/src/domain/message.rs index 7bcdbe0d3..361490e01 100644 --- a/backend/supports/reach/src/domain/message.rs +++ b/backend/supports/reach/src/domain/message.rs @@ -1,9 +1,6 @@ -use tardis::basic::dto::TardisContext; use tardis::chrono::{DateTime, Utc}; -use tardis::db::reldb_client::TardisActiveModel; use tardis::db::sea_orm; -use tardis::db::sea_orm::sea_query::{ColumnDef, IndexCreateStatement, Table, TableCreateStatement}; use tardis::db::sea_orm::*; use crate::dto::*; diff --git a/backend/supports/reach/src/domain/message_signature.rs b/backend/supports/reach/src/domain/message_signature.rs index 466f22e74..5dcc531d1 100644 --- a/backend/supports/reach/src/domain/message_signature.rs +++ b/backend/supports/reach/src/domain/message_signature.rs @@ -1,10 +1,7 @@ use crate::dto::*; -use tardis::basic::dto::TardisContext; use tardis::chrono::{self, DateTime, Utc}; -use tardis::db::reldb_client::TardisActiveModel; use tardis::db::sea_orm; -use tardis::db::sea_orm::sea_query::{ColumnDef, Table, TableCreateStatement}; use tardis::db::sea_orm::*; use crate::fill_by_mod_req; diff --git a/backend/supports/reach/src/domain/message_template.rs b/backend/supports/reach/src/domain/message_template.rs index c19f3c15c..be5f570d4 100644 --- a/backend/supports/reach/src/domain/message_template.rs +++ b/backend/supports/reach/src/domain/message_template.rs @@ -1,11 +1,8 @@ -use tardis::basic::dto::TardisContext; use tardis::chrono::{DateTime, Utc}; -use tardis::db::reldb_client::TardisActiveModel; use tardis::db::sea_orm; use crate::fill_by_mod_req; use crate::{dto::*, fill_by_add_req}; -use tardis::db::sea_orm::sea_query::{ColumnDef, Table, TableCreateStatement}; use tardis::db::sea_orm::*; use tardis::{TardisCreateEntity, TardisEmptyBehavior, TardisEmptyRelation}; #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, TardisCreateEntity, TardisEmptyBehavior, TardisEmptyRelation)] diff --git a/backend/supports/reach/src/domain/reach_vcode_strategy.rs b/backend/supports/reach/src/domain/reach_vcode_strategy.rs index 2791d32c7..4851bcea7 100644 --- a/backend/supports/reach/src/domain/reach_vcode_strategy.rs +++ b/backend/supports/reach/src/domain/reach_vcode_strategy.rs @@ -1,11 +1,8 @@ use crate::dto::*; use crate::fill_by_add_req; -use tardis::basic::dto::TardisContext; use tardis::chrono::{self, DateTime, Utc}; -use tardis::db::reldb_client::TardisActiveModel; use tardis::db::sea_orm; -use tardis::db::sea_orm::sea_query::{ColumnDef, IndexCreateStatement, Table, TableCreateStatement}; use tardis::db::sea_orm::*; use tardis::{TardisCreateEntity, TardisEmptyBehavior, TardisEmptyRelation}; #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, TardisCreateEntity, TardisEmptyBehavior, TardisEmptyRelation)] diff --git a/backend/supports/reach/src/domain/trigger_global_config.rs b/backend/supports/reach/src/domain/trigger_global_config.rs index 910e5ad33..e372b2ef3 100644 --- a/backend/supports/reach/src/domain/trigger_global_config.rs +++ b/backend/supports/reach/src/domain/trigger_global_config.rs @@ -1,12 +1,9 @@ use crate::dto::*; use crate::fill_by_add_req; use crate::fill_by_mod_req; -use tardis::basic::dto::TardisContext; use tardis::chrono::{self, DateTime, Utc}; -use tardis::db::reldb_client::TardisActiveModel; use tardis::db::sea_orm; -use tardis::db::sea_orm::sea_query::{ColumnDef, IndexCreateStatement, Table, TableCreateStatement}; use tardis::db::sea_orm::*; use tardis::{TardisCreateEntity, TardisEmptyBehavior, TardisEmptyRelation}; #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, TardisCreateEntity, TardisEmptyBehavior, TardisEmptyRelation)] diff --git a/backend/supports/reach/src/domain/trigger_instance_config.rs b/backend/supports/reach/src/domain/trigger_instance_config.rs index 0d8af1f73..06ffc878c 100644 --- a/backend/supports/reach/src/domain/trigger_instance_config.rs +++ b/backend/supports/reach/src/domain/trigger_instance_config.rs @@ -1,11 +1,8 @@ use crate::dto::*; use crate::fill_by_add_req; use crate::fill_by_mod_req; -use tardis::basic::dto::TardisContext; use tardis::chrono::{self, DateTime, Utc}; -use tardis::db::reldb_client::TardisActiveModel; use tardis::db::sea_orm; -use tardis::db::sea_orm::sea_query::{ColumnDef, IndexCreateStatement, Table, TableCreateStatement}; use tardis::db::sea_orm::*; use tardis::{TardisCreateEntity, TardisEmptyBehavior, TardisEmptyRelation}; diff --git a/backend/supports/reach/src/domain/trigger_scene.rs b/backend/supports/reach/src/domain/trigger_scene.rs index 125e8022d..2d7b09b0c 100644 --- a/backend/supports/reach/src/domain/trigger_scene.rs +++ b/backend/supports/reach/src/domain/trigger_scene.rs @@ -1,11 +1,8 @@ use crate::dto::*; use crate::fill_by_add_req; -use tardis::basic::dto::TardisContext; use tardis::chrono::{self, DateTime, Utc}; -use tardis::db::reldb_client::TardisActiveModel; use tardis::db::sea_orm; -use tardis::db::sea_orm::sea_query::{ColumnDef, IndexCreateStatement, Table, TableCreateStatement}; use tardis::db::sea_orm::*; use tardis::{TardisCreateEntity, TardisEmptyBehavior, TardisEmptyRelation}; From 03611737ac240d6c93fcec753d030025420fe53d Mon Sep 17 00:00:00 2001 From: ZzIsGod1019 <1498852723@qq.com> Date: Tue, 7 May 2024 09:27:23 +0800 Subject: [PATCH 2/3] flow: add type addorsub (#718) --- backend/basic/src/helper/request_helper.rs | 14 ++-- backend/basic/src/rbum/dto/rbum_kind_dto.rs | 4 +- .../flow/src/api/cc/flow_cc_inst_api.rs | 34 ++++++--- .../flow/src/api/ci/flow_ci_inst_api.rs | 4 +- .../middlewares/flow/src/domain/flow_inst.rs | 3 - .../middlewares/flow/src/dto/flow_inst_dto.rs | 4 +- .../flow/src/dto/flow_transition_dto.rs | 2 + backend/middlewares/flow/src/event.rs | 14 +--- .../middlewares/flow/src/flow_constants.rs | 1 - .../flow/src/serv/clients/event_client.rs | 16 +--- .../flow/src/serv/flow_event_serv.rs | 73 +++++++------------ .../flow/src/serv/flow_external_serv.rs | 22 ------ .../flow/src/serv/flow_inst_serv.rs | 51 +++++++------ .../flow/src/serv/flow_model_serv.rs | 20 ++--- .../flow/tests/test_flow_scenes_fsm.rs | 35 ++++----- 15 files changed, 111 insertions(+), 186 deletions(-) diff --git a/backend/basic/src/helper/request_helper.rs b/backend/basic/src/helper/request_helper.rs index 7902e8752..cc8136579 100644 --- a/backend/basic/src/helper/request_helper.rs +++ b/backend/basic/src/helper/request_helper.rs @@ -38,14 +38,12 @@ pub async fn try_set_real_ip_from_req_to_ctx(request: &Request, ctx: &TardisCont /// assert_eq!(parse_forwarded_ip("Forwarded: proto=http; for=192.168.0"), None); /// ``` pub fn parse_forwarded_ip(forwarded_value: &str) -> Option { - forwarded_value - .strip_prefix("Forwarded: ") - .and_then(|forwarded_value| { - forwarded_value - .split(';') - .find(|part| part.trim().starts_with("for=")) - .and_then(|part| part.trim()[4..].split(',').next().and_then(|ip_str| IpAddr::from_str(ip_str).ok())) - }) + forwarded_value.strip_prefix("Forwarded: ").and_then(|forwarded_value| { + forwarded_value + .split(';') + .find(|part| part.trim().starts_with("for=")) + .and_then(|part| part.trim()[4..].split(',').next().and_then(|ip_str| IpAddr::from_str(ip_str).ok())) + }) } /// Try to get real ip from request diff --git a/backend/basic/src/rbum/dto/rbum_kind_dto.rs b/backend/basic/src/rbum/dto/rbum_kind_dto.rs index 5e63d7717..ac75f7c2c 100644 --- a/backend/basic/src/rbum/dto/rbum_kind_dto.rs +++ b/backend/basic/src/rbum/dto/rbum_kind_dto.rs @@ -17,9 +17,9 @@ pub struct RbumKindAddReq { /// Resource kind module /// /// 资源类型模块 - /// + /// /// Default is ``empty`` - /// + /// /// 默认为 ``空`` /// /// Used to further divide the resource kind. For example, there are multiple resource kinds under the ``cmdb compute`` module, such as ``ecs, ec2, k8s``. diff --git a/backend/middlewares/flow/src/api/cc/flow_cc_inst_api.rs b/backend/middlewares/flow/src/api/cc/flow_cc_inst_api.rs index f1e66e677..51cd54ca9 100644 --- a/backend/middlewares/flow/src/api/cc/flow_cc_inst_api.rs +++ b/backend/middlewares/flow/src/api/cc/flow_cc_inst_api.rs @@ -1,5 +1,6 @@ use std::collections::HashMap; +use serde_json::Value; use tardis::web::context_extractor::TardisContextExtractor; use tardis::web::poem::Request; use tardis::web::poem_openapi; @@ -20,7 +21,8 @@ pub struct FlowCcInstApi; /// Flow instance process API #[poem_openapi::OpenApi(prefix_path = "/cc/inst")] impl FlowCcInstApi { - /// Start Instance / 启动实例 + /// Start Instance(Return Instance ID) + /// 启动实例(返回实例ID) #[oai(path = "/", method = "post")] async fn start(&self, add_req: Json, ctx: TardisContextExtractor, _request: &Request) -> TardisApiResult { let mut funs = flow_constants::get_tardis_inst(); @@ -30,7 +32,8 @@ impl FlowCcInstApi { TardisResp::ok(result) } - /// Abort Instance / 中止实例 + /// Abort Instance + /// 终止实例 #[oai(path = "/:flow_inst_id", method = "put")] async fn abort(&self, flow_inst_id: Path, abort_req: Json, ctx: TardisContextExtractor, _request: &Request) -> TardisApiResult { let mut funs = flow_constants::get_tardis_inst(); @@ -40,7 +43,8 @@ impl FlowCcInstApi { TardisResp::ok(Void {}) } - /// Get Instance By Instance Id / 获取实例信息 + /// Get Instance By Instance Id + /// 获取实例信息 #[oai(path = "/:flow_inst_id", method = "get")] async fn get(&self, flow_inst_id: Path, ctx: TardisContextExtractor, _request: &Request) -> TardisApiResult { let funs = flow_constants::get_tardis_inst(); @@ -48,7 +52,8 @@ impl FlowCcInstApi { TardisResp::ok(result) } - /// Find Instances / 获取实例列表 + /// Find Instances + /// 获取实例列表 #[oai(path = "/", method = "get")] async fn paginate( &self, @@ -66,7 +71,8 @@ impl FlowCcInstApi { TardisResp::ok(result) } - /// Find Next Transitions / 获取下一个流转状态列表 + /// Find Next Transitions + /// 获取下一个流转状态列表 #[oai(path = "/:flow_inst_id/transition/next", method = "put")] async fn find_next_transitions( &self, @@ -80,7 +86,8 @@ impl FlowCcInstApi { TardisResp::ok(result) } - /// Find the state and transfer information of the specified model in batch / 批量获取指定模型的状态及流转信息 + /// Find the state and transfer information of the specified model in batch + /// 批量获取指定模型的状态及流转信息 #[oai(path = "/batch/state_transitions", method = "put")] async fn find_state_and_next_transitions( &self, @@ -93,7 +100,8 @@ impl FlowCcInstApi { TardisResp::ok(result) } - /// Transfer State By State Id / 流转 + /// Transfer State By Transaction Id + /// 通过动作ID流转状态 #[oai(path = "/:flow_inst_id/transition/transfer", method = "put")] async fn transfer( &self, @@ -111,7 +119,8 @@ impl FlowCcInstApi { TardisResp::ok(result) } - /// Batch transfer State By State Id / 批量流转 + /// Batch transfer State By Transaction Id + /// 批量流转 #[oai(path = "/batch/:flow_inst_ids/transition/transfer", method = "put")] async fn batch_transfer( &self, @@ -138,7 +147,8 @@ impl FlowCcInstApi { TardisResp::ok(result) } - /// Modify Assigned / 同步执行人信息 + /// Modify Assigned[Deprecated] + /// 同步执行人信息[已废弃] #[oai(path = "/:flow_inst_id/transition/modify_assigned", method = "post")] async fn modify_assigned( &self, @@ -149,12 +159,14 @@ impl FlowCcInstApi { ) -> TardisApiResult { let mut funs = flow_constants::get_tardis_inst(); funs.begin().await?; - FlowInstServ::modify_assigned(&flow_inst_id.0, &modify_req.0.current_assigned, &funs, &ctx.0).await?; + let vars = HashMap::from([("current_assigned".to_string(), Value::String(modify_req.0.current_assigned))]); + FlowInstServ::modify_current_vars(&flow_inst_id.0, &vars, &funs, &ctx.0).await?; funs.commit().await?; TardisResp::ok(Void {}) } - /// Modify list of variables / 同步当前变量列表 + /// Modify list of variables + /// 同步当前变量列表 #[oai(path = "/:flow_inst_id/modify_current_vars", method = "patch")] async fn modify_current_vars( &self, diff --git a/backend/middlewares/flow/src/api/ci/flow_ci_inst_api.rs b/backend/middlewares/flow/src/api/ci/flow_ci_inst_api.rs index 10e703509..0365a037b 100644 --- a/backend/middlewares/flow/src/api/ci/flow_ci_inst_api.rs +++ b/backend/middlewares/flow/src/api/ci/flow_ci_inst_api.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use bios_basic::rbum::helper::rbum_scope_helper::check_without_owner_and_unsafe_fill_ctx; use tardis::log::debug; +use tardis::serde_json::Value; use tardis::web::context_extractor::TardisContextExtractor; use tardis::web::poem::web::Path; use tardis::web::poem::Request; @@ -128,7 +129,8 @@ impl FlowCiInstApi { let mut funs = flow_constants::get_tardis_inst(); check_without_owner_and_unsafe_fill_ctx(request, &funs, &mut ctx.0)?; funs.begin().await?; - FlowInstServ::modify_assigned(&flow_inst_id.0, &modify_req.0.current_assigned, &funs, &ctx.0).await?; + let vars = HashMap::from([("assigned_to".to_string(), Value::String(modify_req.0.current_assigned))]); + FlowInstServ::modify_current_vars(&flow_inst_id.0, &vars, &funs, &ctx.0).await?; funs.commit().await?; TardisResp::ok(Void {}) } diff --git a/backend/middlewares/flow/src/domain/flow_inst.rs b/backend/middlewares/flow/src/domain/flow_inst.rs index 8f29f8618..fde060526 100644 --- a/backend/middlewares/flow/src/domain/flow_inst.rs +++ b/backend/middlewares/flow/src/domain/flow_inst.rs @@ -59,7 +59,4 @@ pub struct Model { pub transitions: Option>, pub own_paths: String, - - /// Current Assigned / 指定执行人 - pub current_assigned: Option, } diff --git a/backend/middlewares/flow/src/dto/flow_inst_dto.rs b/backend/middlewares/flow/src/dto/flow_inst_dto.rs index a932c8f79..7e15b3048 100644 --- a/backend/middlewares/flow/src/dto/flow_inst_dto.rs +++ b/backend/middlewares/flow/src/dto/flow_inst_dto.rs @@ -64,7 +64,6 @@ pub struct FlowInstSummaryResp { pub rel_business_obj_id: String, pub current_state_id: String, - pub current_assigned: Option, pub create_ctx: FlowOperationContext, pub create_time: DateTime, @@ -90,7 +89,6 @@ pub struct FlowInstDetailResp { pub current_state_kind: Option, pub current_state_ext: Option, - pub current_assigned: Option, pub current_vars: Option>, pub create_vars: Option>, @@ -141,7 +139,7 @@ pub struct FlowInstFindNextTransitionsReq { pub vars: Option>, } -#[derive(Serialize, Deserialize, Debug, poem_openapi::Object)] +#[derive(Serialize, Deserialize, Debug, poem_openapi::Object, Clone)] pub struct FlowInstFindNextTransitionResp { pub next_flow_transition_id: String, pub next_flow_transition_name: String, diff --git a/backend/middlewares/flow/src/dto/flow_transition_dto.rs b/backend/middlewares/flow/src/dto/flow_transition_dto.rs index daec783d4..13ac0c6a2 100644 --- a/backend/middlewares/flow/src/dto/flow_transition_dto.rs +++ b/backend/middlewares/flow/src/dto/flow_transition_dto.rs @@ -294,6 +294,8 @@ pub enum FlowTransitionActionByVarChangeInfoChangedKind { AutoGetOperator, #[sea_orm(string_value = "select_field")] SelectField, + #[sea_orm(string_value = "and_or_subs")] + AddOrSub, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, poem_openapi::Object, sea_orm::FromJsonQueryResult)] diff --git a/backend/middlewares/flow/src/event.rs b/backend/middlewares/flow/src/event.rs index 15cd301d7..dd2ab07af 100644 --- a/backend/middlewares/flow/src/event.rs +++ b/backend/middlewares/flow/src/event.rs @@ -10,7 +10,7 @@ use tardis::{ }; use crate::{ - flow_constants::{self, get_tardis_inst, EVENT_FRONT_CHANGE, EVENT_MODIFY_ASSIGNED, EVENT_POST_CHANGE}, + flow_constants::{self, get_tardis_inst, EVENT_FRONT_CHANGE, EVENT_POST_CHANGE}, serv::flow_event_serv::FlowEventServ, }; pub const RECONNECT_INTERVAL: Duration = Duration::from_secs(10); @@ -44,18 +44,6 @@ pub async fn start_flow_event_service(config: &EventTopicConfig) -> TardisResult }); } Some(EVENT_POST_CHANGE) => {} - Some(EVENT_MODIFY_ASSIGNED) => { - let Ok((inst_id, assigned_id, ctx)) = TardisFuns::json.json_to_obj::<(String, String, _)>(msg) else { - return None; - }; - tokio::spawn(async move { - let funs = get_tardis_inst(); - let result = FlowEventServ::do_modify_assigned(&inst_id, &assigned_id, &ctx, &funs).await; - if let Err(err) = result { - error!("[BIOS.Log] failed to do front change: {}, inst_id: {}", err, inst_id); - } - }); - } Some(unknown_event) => { warn!("[BIOS.Flow] event receive unknown event {unknown_event}") } diff --git a/backend/middlewares/flow/src/flow_constants.rs b/backend/middlewares/flow/src/flow_constants.rs index a083e5eb2..cc1c2ada8 100644 --- a/backend/middlewares/flow/src/flow_constants.rs +++ b/backend/middlewares/flow/src/flow_constants.rs @@ -10,7 +10,6 @@ pub const EVENT_FRONT_CHANGE: &str = "event_front_change"; pub const EVENT_POST_CHANGE: &str = "event_post_change"; pub const EVENT_UPDATE_STATE: &str = "event_update_state"; pub const EVENT_MODIFY_FIELD: &str = "event_modify_field"; -pub const EVENT_MODIFY_ASSIGNED: &str = "event_modify_assigned"; pub fn get_tardis_inst() -> TardisFunsInst { TardisFuns::inst_with_db_conn(DOMAIN_CODE.to_string(), None) diff --git a/backend/middlewares/flow/src/serv/clients/event_client.rs b/backend/middlewares/flow/src/serv/clients/event_client.rs index d77048949..bd03803e7 100644 --- a/backend/middlewares/flow/src/serv/clients/event_client.rs +++ b/backend/middlewares/flow/src/serv/clients/event_client.rs @@ -6,30 +6,16 @@ use tardis::{ TardisFuns, }; -use crate::flow_constants::{EVENT_FRONT_CHANGE, EVENT_MODIFY_ASSIGNED, EVENT_POST_CHANGE}; +use crate::flow_constants::{EVENT_FRONT_CHANGE, EVENT_POST_CHANGE}; #[async_trait] pub trait FlowEventExt { - async fn publish_modify_assigned(&self, inst_id: String, assigned_id: String, from: String, spi_app_id: String, ctx: &TardisContext) -> TardisResult<()>; async fn publish_front_change(&self, inst_id: String, from: String, spi_app_id: String, ctx: &TardisContext) -> TardisResult<()>; async fn publish_post_change(&self, inst_id: String, next_transition_id: String, from: String, spi_app_id: String, ctx: &TardisContext) -> TardisResult<()>; } #[async_trait] impl FlowEventExt for TardisWSClient { - async fn publish_modify_assigned(&self, inst_id: String, assigned_id: String, from: String, spi_app_id: String, ctx: &TardisContext) -> TardisResult<()> { - let spi_ctx = TardisContext { owner: spi_app_id, ..ctx.clone() }; - let req = TardisWebsocketReq { - msg: TardisFuns::json.obj_to_json(&(inst_id, assigned_id, spi_ctx)).expect("invalid json"), - to_avatars: Some(vec!["flow/service".into()]), - from_avatar: from, - event: Some(EVENT_MODIFY_ASSIGNED.into()), - ..Default::default() - }; - info!("event add log {}", TardisFuns::json.obj_to_string(&req).expect("invalid json")); - self.send_obj(&req).await?; - return Ok(()); - } async fn publish_front_change(&self, inst_id: String, from: String, spi_app_id: String, ctx: &TardisContext) -> TardisResult<()> { let spi_ctx = TardisContext { owner: spi_app_id, ..ctx.clone() }; let req = TardisWebsocketReq { diff --git a/backend/middlewares/flow/src/serv/flow_event_serv.rs b/backend/middlewares/flow/src/serv/flow_event_serv.rs index ad7f48f01..90f4b47d5 100644 --- a/backend/middlewares/flow/src/serv/flow_event_serv.rs +++ b/backend/middlewares/flow/src/serv/flow_event_serv.rs @@ -9,7 +9,6 @@ use tardis::{ db::sea_orm::{ self, sea_query::{Expr, Query}, - Set, }, TardisFunsInst, }; @@ -166,17 +165,6 @@ impl FlowEventServ { ctx, ) .await?; - // let flow_transitions = flow_model - // .transitions() - // .into_iter() - // .filter(|trans| trans.from_flow_state_id == flow_inst_detail.current_state_id && !trans.action_by_post_changes().is_empty()) - // .sorted_by_key(|trans| trans.sort) - // .collect_vec(); - // if flow_transitions.is_empty() { - // return Ok(()); - // } - // let next_flow_transition = - // FlowInstServ::do_find_next_transitions(&flow_inst_detail, &flow_model, Some(flow_transition_id.to_string()), &None, true, funs, ctx).await?.next_flow_transitions.pop(); let next_flow_transition = flow_model.transitions().into_iter().find(|trans| trans.id == flow_transition_id); if next_flow_transition.is_none() { return Err(funs.err().not_found("flow_inst", "transfer", "no transferable state", "404-flow-inst-transfer-state-not-found")); @@ -228,9 +216,34 @@ impl FlowEventServ { match post_change.kind { FlowTransitionActionChangeKind::Var => { if let Some(mut change_info) = post_change.var_change_info { - if change_info.changed_kind.is_some() && change_info.changed_kind.clone().unwrap() == FlowTransitionActionByVarChangeInfoChangedKind::AutoGetOperateTime { - change_info.changed_val = Some(json!(Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true))); - change_info.changed_kind = Some(FlowTransitionActionByVarChangeInfoChangedKind::ChangeContent); + if change_info.changed_kind.is_some() { + match change_info.changed_kind.clone().unwrap() { + FlowTransitionActionByVarChangeInfoChangedKind::AutoGetOperateTime => { + change_info.changed_val = Some(json!(Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true))); + change_info.changed_kind = Some(FlowTransitionActionByVarChangeInfoChangedKind::ChangeContent); + } + FlowTransitionActionByVarChangeInfoChangedKind::AddOrSub => { + if change_info.changed_val.is_some() + && change_info.changed_val.clone().unwrap().is_object() + && flow_inst_detail.current_vars.clone().unwrap_or_default().get(&change_info.var_name).is_some() + && change_info.changed_val.clone().unwrap().as_object().unwrap().get("value").is_some() + && change_info.changed_val.clone().unwrap().as_object().unwrap().get("op").is_some() + { + let original_map = flow_inst_detail.current_vars.clone().unwrap_or_default(); + let target_value = change_info.changed_val.clone().unwrap().as_object().unwrap().get("value").unwrap().as_i64().unwrap_or_default(); + let changed_op = change_info.changed_val.clone().unwrap().as_object().unwrap().get("op").unwrap().as_str().unwrap_or_default().to_string(); + if let Some(original_value) = original_map.get(&change_info.var_name) { + change_info.changed_kind = Some(FlowTransitionActionByVarChangeInfoChangedKind::ChangeContent); + match changed_op.as_str() { + "add" => change_info.changed_val = Some(json!(original_value.as_i64().unwrap_or_default() + target_value)), + "sub" => change_info.changed_val = Some(json!(original_value.as_i64().unwrap_or_default() - target_value)), + _ => {} + } + } + } + } + _ => {} + }; } let rel_tag = change_info.obj_tag.unwrap_or_default(); if !rel_tag.is_empty() { @@ -489,34 +502,4 @@ impl FlowEventServ { } Ok(()) } - - pub async fn do_modify_assigned(flow_inst_id: &str, assigned_id: &str, ctx: &TardisContext, funs: &TardisFunsInst) -> TardisResult<()> { - if funs - .db() - .count( - Query::select() - .column((flow_inst::Entity, flow_inst::Column::Id)) - .from(flow_inst::Entity) - .and_where(Expr::col((flow_inst::Entity, flow_inst::Column::Id)).eq(flow_inst_id.to_string())) - .and_where(Expr::col((flow_inst::Entity, flow_inst::Column::OwnPaths)).like(format!("{}%", ctx.own_paths))), - ) - .await? - == 0 - { - return Err(funs.err().not_found( - "flow_inst", - "modify_assigned", - &format!("flow instance {} not found", flow_inst_id), - "404-flow-inst-not-found", - )); - } - let flow_inst = flow_inst::ActiveModel { - id: Set(flow_inst_id.to_string()), - current_assigned: Set(Some(assigned_id.to_string())), - ..Default::default() - }; - funs.db().update_one(flow_inst, ctx).await?; - - Ok(()) - } } diff --git a/backend/middlewares/flow/src/serv/flow_external_serv.rs b/backend/middlewares/flow/src/serv/flow_external_serv.rs index e9f16a2e1..1bc9c0360 100644 --- a/backend/middlewares/flow/src/serv/flow_external_serv.rs +++ b/backend/middlewares/flow/src/serv/flow_external_serv.rs @@ -3,7 +3,6 @@ use itertools::Itertools; use tardis::{ basic::{dto::TardisContext, result::TardisResult}, log::debug, - web::web_resp::TardisResp, TardisFuns, TardisFunsInst, }; @@ -16,7 +15,6 @@ use crate::{ flow_state_dto::FlowSysStateKind, flow_transition_dto::{FlowTransitionActionByVarChangeInfoChangedKind, FlowTransitionDetailResp, TagRelKind}, }, - flow_config::FlowConfig, flow_constants, }; @@ -186,26 +184,6 @@ impl FlowExternalServ { } } - pub async fn do_find_embed_subrole_id(role_id: &str, ctx: &TardisContext, funs: &TardisFunsInst) -> TardisResult { - let iam_url = &funs.conf::().iam_url; - - let header = Self::headers(None, funs, ctx).await?; - let resp = funs - .web_client() - .get::>(&format!("{iam_url}/cc/role/get_embed_subrole_id?id={role_id}"), header) - .await? - .body - .ok_or_else(|| funs.err().internal_error("flow_external", "do_find_embed_subrole_id", "illegal response", "500-external-illegal-response"))?; - if resp.code != *"200" { - return Err(funs.err().internal_error("flow_external", "do_find_embed_subrole_id", "illegal response", "500-external-illegal-response")); - } - if let Some(data) = resp.data { - Ok(data) - } else { - Err(funs.err().internal_error("flow_external", "do_find_embed_subrole_id", "illegal response", "500-external-illegal-response")) - } - } - pub async fn do_query_field( tag: &str, rel_business_obj_ids: Vec, diff --git a/backend/middlewares/flow/src/serv/flow_inst_serv.rs b/backend/middlewares/flow/src/serv/flow_inst_serv.rs index 397769570..bce710fe2 100644 --- a/backend/middlewares/flow/src/serv/flow_inst_serv.rs +++ b/backend/middlewares/flow/src/serv/flow_inst_serv.rs @@ -261,22 +261,6 @@ impl FlowInstServ { Ok(()) } - pub async fn modify_assigned(flow_inst_id: &str, assigned_id: &str, funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult<()> { - if let Some(ws_client) = ws_flow_client().await { - ws_client - .publish_modify_assigned( - flow_inst_id.to_string(), - assigned_id.to_string(), - default_flow_avatar().await.clone(), - funs.conf::().invoke.spi_app_id.clone(), - ctx, - ) - .await - } else { - FlowEventServ::do_modify_assigned(flow_inst_id, assigned_id, ctx, funs).await - } - } - pub async fn get(flow_inst_id: &str, funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult { let mut flow_insts = Self::find_detail(vec![flow_inst_id.to_string()], funs, ctx).await?; if flow_insts.len() == 1 { @@ -299,7 +283,6 @@ impl FlowInstServ { pub current_state_kind: Option, pub current_state_ext: Option, - pub current_assigned: Option, pub current_vars: Option, pub create_vars: Option, @@ -338,7 +321,6 @@ impl FlowInstServ { (flow_inst::Entity, flow_inst::Column::OutputMessage), (flow_inst::Entity, flow_inst::Column::Transitions), (flow_inst::Entity, flow_inst::Column::OwnPaths), - (flow_inst::Entity, flow_inst::Column::CurrentAssigned), ]) .expr_as(Expr::col((rel_state_table.clone(), NAME_FIELD.clone())).if_null(""), Alias::new("current_state_name")) .expr_as(Expr::col((flow_state_table.clone(), Alias::new("color"))).if_null(""), Alias::new("current_state_color")) @@ -403,7 +385,6 @@ impl FlowInstServ { current_state_color: inst.current_state_color, current_state_kind: inst.current_state_kind, current_state_ext: inst.current_state_ext, - current_assigned: inst.current_assigned, current_vars: inst.current_vars.map(|current_vars| TardisFuns::json.json_to_obj(current_vars).unwrap()), rel_business_obj_id: inst.rel_business_obj_id, }) @@ -426,6 +407,7 @@ impl FlowInstServ { pub rel_flow_model_id: String, pub rel_flow_model_name: String, + pub current_vars: Option, pub current_state_id: String, pub rel_business_obj_id: String, @@ -438,7 +420,6 @@ impl FlowInstServ { pub output_message: Option, pub own_paths: String, - pub current_assigned: Option, } let mut query = Query::select(); query @@ -446,6 +427,7 @@ impl FlowInstServ { (flow_inst::Entity, flow_inst::Column::Id), (flow_inst::Entity, flow_inst::Column::RelFlowModelId), (flow_inst::Entity, flow_inst::Column::RelBusinessObjId), + (flow_inst::Entity, flow_inst::Column::CreateVars), (flow_inst::Entity, flow_inst::Column::CurrentStateId), (flow_inst::Entity, flow_inst::Column::CreateCtx), (flow_inst::Entity, flow_inst::Column::CreateTime), @@ -454,7 +436,6 @@ impl FlowInstServ { (flow_inst::Entity, flow_inst::Column::FinishAbort), (flow_inst::Entity, flow_inst::Column::OutputMessage), (flow_inst::Entity, flow_inst::Column::OwnPaths), - (flow_inst::Entity, flow_inst::Column::CurrentAssigned), ]) .expr_as(Expr::col((RBUM_ITEM_TABLE.clone(), NAME_FIELD.clone())).if_null(""), Alias::new("rel_flow_model_name")) .from(flow_inst::Entity) @@ -504,7 +485,6 @@ impl FlowInstServ { own_paths: inst.own_paths, current_state_id: inst.current_state_id, rel_business_obj_id: inst.rel_business_obj_id, - current_assigned: inst.current_assigned, }) .collect_vec(), }) @@ -978,15 +958,34 @@ impl FlowInstServ { if !model_transition.guard_by_spec_account_ids.is_empty() && model_transition.guard_by_spec_account_ids.contains(&ctx.owner) { return true; } - if !model_transition.guard_by_spec_role_ids.is_empty() && model_transition.guard_by_spec_role_ids.iter().any(|role_ids| ctx.roles.contains(role_ids)) { + if !model_transition.guard_by_spec_role_ids.is_empty() + && model_transition.guard_by_spec_role_ids.iter().any(|role_id| { + ctx.roles + .clone() + .into_iter() + .map(|ctx_role_id| ctx_role_id.split(':').last().unwrap_or(&ctx_role_id).to_string()) + .collect_vec() + .contains(&role_id.split(':').last().unwrap_or(role_id).to_string()) + }) + { return true; } - if !model_transition.guard_by_spec_org_ids.is_empty() && model_transition.guard_by_spec_org_ids.iter().any(|role_ids| ctx.groups.contains(role_ids)) { + if !model_transition.guard_by_spec_org_ids.is_empty() && model_transition.guard_by_spec_org_ids.iter().any(|org_id| ctx.groups.contains(org_id)) { return true; } if model_transition.guard_by_assigned - && flow_inst.current_assigned.is_some() - && flow_inst.current_assigned.clone().unwrap().split(',').collect_vec().contains(&ctx.owner.as_str()) + && flow_inst.current_vars.clone().unwrap_or_default().get("assigned_to").is_some() + && flow_inst + .current_vars + .clone() + .unwrap_or_default() + .get("assigned_to") + .unwrap() + .as_str() + .unwrap_or_default() + .split(',') + .collect_vec() + .contains(&ctx.owner.as_str()) { return true; } diff --git a/backend/middlewares/flow/src/serv/flow_model_serv.rs b/backend/middlewares/flow/src/serv/flow_model_serv.rs index 51e051f90..1eef7811f 100644 --- a/backend/middlewares/flow/src/serv/flow_model_serv.rs +++ b/backend/middlewares/flow/src/serv/flow_model_serv.rs @@ -45,7 +45,6 @@ use crate::{ use async_trait::async_trait; use super::{ - flow_external_serv::FlowExternalServ, flow_inst_serv::FlowInstServ, flow_rel_serv::{FlowRelKind, FlowRelServ}, }; @@ -881,19 +880,18 @@ impl FlowModelServ { .ok_or_else(|| funs.err().internal_error("flow_model_serv", "add_custom_model", "default model is not exist", "404-flow-model-not-found"))? }; - let mut transitions = parent_model.transitions(); // add model let model_id = Self::add_item( &mut FlowModelAddReq { - name: parent_model.name.into(), - icon: Some(parent_model.icon), - info: Some(parent_model.info), - init_state_id: parent_model.init_state_id, + name: parent_model.name.clone().into(), + icon: Some(parent_model.icon.clone()), + info: Some(parent_model.info.clone()), + init_state_id: parent_model.init_state_id.clone(), template: rel_template_id.is_some(), rel_template_id, transitions: None, rel_model_id: Some(parent_model.id.clone()), - tag: Some(parent_model.tag), + tag: Some(parent_model.tag.clone()), scope_level: None, disabled: Some(parent_model.disabled), }, @@ -924,13 +922,7 @@ impl FlowModelServ { .await?; } // add transition - // sub role_id instead of role_id - for transition in &mut transitions { - for role_id in &mut transition.guard_by_spec_role_ids { - *role_id = FlowExternalServ::do_find_embed_subrole_id(role_id, ctx, funs).await.unwrap_or(role_id.to_string()); - } - } - Self::add_transitions(&model_id, &transitions.into_iter().map(|trans| trans.into()).collect_vec(), funs, ctx).await?; + Self::add_transitions(&model_id, &parent_model.transitions().into_iter().map(|trans| trans.into()).collect_vec(), funs, ctx).await?; Ok(model_id) } diff --git a/backend/middlewares/flow/tests/test_flow_scenes_fsm.rs b/backend/middlewares/flow/tests/test_flow_scenes_fsm.rs index 9033957a6..a2f5976b8 100644 --- a/backend/middlewares/flow/tests/test_flow_scenes_fsm.rs +++ b/backend/middlewares/flow/tests/test_flow_scenes_fsm.rs @@ -6,8 +6,7 @@ use bios_basic::test::test_http_client::TestHttpClient; use bios_mw_flow::dto::flow_config_dto::FlowConfigModifyReq; use bios_mw_flow::dto::flow_inst_dto::{ FlowInstBatchBindReq, FlowInstBatchBindResp, FlowInstBindRelObjReq, FlowInstBindReq, FlowInstDetailResp, FlowInstFindNextTransitionResp, FlowInstFindNextTransitionsReq, - FlowInstFindStateAndTransitionsReq, FlowInstFindStateAndTransitionsResp, FlowInstModifyAssignedReq, FlowInstModifyCurrentVarsReq, FlowInstStartReq, FlowInstTransferReq, - FlowInstTransferResp, + FlowInstFindStateAndTransitionsReq, FlowInstFindStateAndTransitionsResp, FlowInstModifyCurrentVarsReq, FlowInstStartReq, FlowInstTransferReq, FlowInstTransferResp, }; use bios_mw_flow::dto::flow_model_dto::{ FlowModelAddCustomModelItemReq, FlowModelAddCustomModelReq, FlowModelAddCustomModelResp, FlowModelAggResp, FlowModelBindStateReq, FlowModelFindRelStateResp, @@ -25,7 +24,7 @@ use tardis::basic::dto::TardisContext; use tardis::basic::result::TardisResult; use tardis::log::info; -use tardis::serde_json::json; +use tardis::serde_json::{json, Value}; use tardis::tokio; use tardis::web::poem_openapi::types::Type; use tardis::web::web_resp::{TardisPage, Void}; @@ -264,7 +263,7 @@ pub async fn test(flow_client: &mut TestHttpClient) -> TardisResult<()> { guard_by_his_operators: None, guard_by_assigned: None, guard_by_spec_account_ids: None, - guard_by_spec_role_ids: None, + guard_by_spec_role_ids: Some(vec!["admin".to_string()]), guard_by_spec_org_ids: None, guard_by_other_conds: None, vars_collect: None, @@ -663,14 +662,9 @@ pub async fn test(flow_client: &mut TestHttpClient) -> TardisResult<()> { let next_transitions: Vec = flow_client.put(&format!("/cc/inst/{}/transition/next", req_inst_id1), &FlowInstFindNextTransitionsReq { vars: None }).await; assert_eq!(next_transitions.len(), 2); - flow_client.set_auth(&TardisContext { - own_paths: "t1/app01".to_string(), - ak: "".to_string(), - roles: vec!["admin".to_string()], - groups: vec![], - owner: "a001".to_string(), - ..Default::default() - })?; + ctx.owner = "a001".to_string(); + ctx.roles = vec!["t:admin".to_string()]; + flow_client.set_auth(&ctx)?; let next_transitions: Vec = flow_client.put(&format!("/cc/inst/{}/transition/next", req_inst_id1), &FlowInstFindNextTransitionsReq { vars: None }).await; assert_eq!(next_transitions.len(), 2); @@ -769,7 +763,11 @@ pub async fn test(flow_client: &mut TestHttpClient) -> TardisResult<()> { .await; assert_eq!(state_and_next_transitions[0].next_flow_transitions.len(), 1); // handle front change - let current_vars = HashMap::from([("status".to_string(), json!(true)), ("handle_time".to_string(), json!("2023-10-10"))]); + let current_vars = HashMap::from([ + ("status".to_string(), json!(true)), + ("handle_time".to_string(), json!("2023-10-10")), + ("assigned_to".to_string(), Value::String(ctx.owner.clone())), + ]); let _: Void = flow_client .patch( &format!("/cc/inst/{}/modify_current_vars", req_inst_id2), @@ -785,6 +783,7 @@ pub async fn test(flow_client: &mut TestHttpClient) -> TardisResult<()> { }], ) .await; + assert_eq!(state_and_next_transitions[0].next_flow_transitions.len(), 2); // let _: Void = flow_client .patch( @@ -792,7 +791,7 @@ pub async fn test(flow_client: &mut TestHttpClient) -> TardisResult<()> { &json!({ "modify_transitions": [ { - "id": state_and_next_transitions[0].next_flow_transitions[0].next_flow_transition_id.clone(), + "id": state_and_next_transitions[0].next_flow_transitions.clone().into_iter().find(|trans| trans.next_flow_state_name == *"已完成").unwrap().next_flow_transition_id, "action_by_front_changes": [ { "relevance_relation": "in", @@ -826,14 +825,6 @@ pub async fn test(flow_client: &mut TestHttpClient) -> TardisResult<()> { assert_eq!(state_and_next_transitions[0].current_flow_state_name, "已完成"); let flow_inst_list: Vec = flow_client.get(&format!("/ci/inst/find_detail_by_obj_ids?obj_ids={}", req_inst_rel_id2)).await; assert_eq!(flow_inst_list[0].id, req_inst_id2); - let _: Void = flow_client - .post( - &format!("/cc/inst/{}/transition/modify_assigned", req_inst_id2), - &FlowInstModifyAssignedReq { - current_assigned: "xxx".to_string(), - }, - ) - .await; Ok(()) } From 1aa04754ea66dff4468f6d78b69b9d5341230578 Mon Sep 17 00:00:00 2001 From: RWDai <27391645+RWDai@users.noreply.github.com> Date: Tue, 7 May 2024 10:06:11 +0800 Subject: [PATCH 3/3] fix: fix schedule init invoke (#720) --- backend/middlewares/schedule/src/schedule_initializer.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backend/middlewares/schedule/src/schedule_initializer.rs b/backend/middlewares/schedule/src/schedule_initializer.rs index 9ab4ffeeb..cea5f4dcf 100644 --- a/backend/middlewares/schedule/src/schedule_initializer.rs +++ b/backend/middlewares/schedule/src/schedule_initializer.rs @@ -1,5 +1,6 @@ use crate::{api::ci::schedule_ci_job_api, schedule_config::ScheduleConfig, schedule_constants::DOMAIN_CODE, serv::schedule_job_serv}; use bios_basic::spi::{dto::spi_bs_dto::SpiBsCertResp, spi_constants, spi_funs::SpiBsInst, spi_initializer}; +use bios_sdk_invoke::invoke_initializer; use tardis::{ basic::{dto::TardisContext, result::TardisResult}, log::error, @@ -9,6 +10,7 @@ use tardis::{ pub async fn init(web_server: &TardisWebServer) -> TardisResult<()> { let mut funs = TardisFuns::inst_with_db_conn(DOMAIN_CODE.to_string(), None); + invoke_initializer::init(funs.module_code(), funs.conf::().invoke.clone())?; funs.begin().await?; let ctx = spi_initializer::init(DOMAIN_CODE, &funs).await?; schedule_job_serv::init(&funs, &ctx).await?;