Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reach: fix hw sms client to compat old template #493

Merged
merged 10 commits into from
Oct 20, 2023
13 changes: 13 additions & 0 deletions basic/src/rbum/dto/rbum_item_dto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ pub struct RbumItemAddReq {
pub disabled: Option<bool>,
}

impl Default for RbumItemAddReq {
fn default() -> Self {
Self {
id: Default::default(),
code: Default::default(),
name: TrimString::from(""),
rel_rbum_kind_id: Default::default(),
rel_rbum_domain_id: Default::default(),
scope_level: Default::default(),
disabled: Default::default(),
}
}
}
/// For security reasons, this object cannot be used as an input to the API
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
Expand Down
12 changes: 8 additions & 4 deletions clients/hwsms/src/ext/reach.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ use std::{
};

use bios_reach::{
reach_send_channel::{GenericTemplate, SendChannel},
dto::{ContentReplace, ReachChannelKind},
reach_config::ReachConfig,
reach_consts::MODULE_CODE,
dto::{ContentReplace, ReachChannelKind},
reach_send_channel::{GenericTemplate, SendChannel},
};
use tardis::{
async_trait::async_trait,
basic::{error::TardisError, result::TardisResult},
TardisFuns,
serde_json, TardisFuns,
};

use crate::{SendSmsRequest, SmsClient, SmsContent};
Expand All @@ -24,6 +24,10 @@ impl SendChannel for crate::SmsClient {
}
async fn send(&self, template: GenericTemplate<'_>, content: &ContentReplace, to: &HashSet<&str>) -> TardisResult<()> {
let content = content.render_final_content::<20>(template.content);
// content should be a json string array
let content_as_json_string_array: Vec<String> =
serde_json::from_str(&content).map_err(|e| TardisError::conflict(&format!("hwsms content should be a json string array: {e}"), "409-reach-bad-template"))?;
let template_paras = content_as_json_string_array.iter().map(|s| s.as_str()).collect();
tardis::log::trace!("send sms {content}");
let sms_content = SmsContent {
to: &to.iter().fold(
Expand All @@ -38,7 +42,7 @@ impl SendChannel for crate::SmsClient {
},
),
template_id: template.sms_template_id.ok_or_else(|| TardisError::conflict("template missing field template_id", "409-reach-bad-template"))?,
template_paras: vec![&content],
template_paras,
signature: template.sms_signature,
};
let from = template.sms_from.ok_or_else(|| TardisError::conflict("template missing field sms_from", "409-reach-bad-template"))?;
Expand Down
2 changes: 1 addition & 1 deletion services/bios-all/src/initializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub async fn init(web_server: &TardisWebServer) -> TardisResult<()> {
web_server,
SendChannelMap::new()
.with_arc_channel(bios_client_hwsms::SmsClient::from_reach_config())
.with_arc_channel(Arc::new(tardis::TardisFuns::mail_by_module(bios_reach::reach_consts::MODULE_CODE))),
.with_arc_channel(Arc::new(tardis::TardisFuns::mail_by_module_or_default(bios_reach::reach_consts::MODULE_CODE))),
)
.await?;

Expand Down
4 changes: 2 additions & 2 deletions support/reach/src/reach_send_channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use tardis::{
mail::mail_client::TardisMailSendReq,
};

use crate::{reach_config::ReachConfig, domain::message_template, dto::*};
use crate::{domain::message_template, dto::*, reach_config::ReachConfig};

#[derive(Default, Debug)]
pub struct GenericTemplate<'t> {
Expand All @@ -24,7 +24,7 @@ impl<'t> GenericTemplate<'t> {
pub fn pwd_template(config: &'t ReachConfig) -> Self {
Self {
name: None,
content: "{pwd}",
content: r#"["{pwd}"]"#,
sms_from: Some(&config.sms.sms_general_from),
sms_template_id: Some(&config.sms.sms_pwd_template_id),
sms_signature: config.sms.sms_general_signature.as_deref(),
Expand Down
14 changes: 7 additions & 7 deletions support/reach/src/serv/message_send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ use std::collections::{HashMap, HashSet};

use bios_basic::rbum::{dto::rbum_item_dto::RbumItemAddReq, serv::rbum_crud_serv::RbumCrudOperation};
use tardis::{
basic::{result::TardisResult, dto::TardisContext},
basic::{dto::TardisContext, result::TardisResult},
db::sea_orm::{sea_query::Query, ColumnTrait, Iterable},
TardisFunsInst,
};

use crate::{reach_consts::*, domain, dto::*, serv::*};
use crate::{domain, dto::*, reach_consts::*, serv::*};

pub async fn message_send(send_req: ReachMsgSendReq, funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult<()> {
let err = |msg: &str| funs.err().not_found("reach", "event_listener", msg, "");
Expand Down Expand Up @@ -54,11 +54,11 @@ pub async fn message_send(send_req: ReachMsgSendReq, funs: &TardisFunsInst, ctx:
map.entry(item.receive_group_code.clone()).or_default().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::<String, Vec<_>>::new(), |mut map, item| {
map.entry(item.receive_group_code.clone()).or_default().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::<String, Vec<_>>::new(), |mut map, item| {
map.entry(item.receive_group_code.clone()).or_default().push(item);
map
});

if instance_group_code.is_empty() {
return Ok(());
Expand Down
48 changes: 44 additions & 4 deletions support/reach/src/task/message_send_listener.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::{collections::HashSet, sync::Arc};

use crate::{reach_send_channel::*, reach_config::ReachConfig, reach_consts::*, domain::*, dto::*, reach_init::get_reach_send_channel_map, serv::*};
use bios_basic::rbum::helper::rbum_scope_helper;
use crate::{domain::*, dto::*, reach_config::ReachConfig, reach_consts::*, reach_init::get_reach_send_channel_map, reach_send_channel::*, serv::*};
use bios_basic::rbum::{helper::rbum_scope_helper, serv::rbum_crud_serv::RbumCrudOperation};
use bios_sdk_invoke::clients::iam_client::IamClient;
use tardis::{
basic::{dto::TardisContext, result::TardisResult},
chrono::Utc,
db::sea_orm::{sea_query::Query, *},
log, tokio, TardisFunsInst,
};
Expand All @@ -28,6 +29,7 @@ impl Default for MessageSendListener {

impl MessageSendListener {
async fn execute_send_account(&self, message: message::Model, template: message_template::Model) -> TardisResult<()> {
let content_replace: ContentReplace = message.content_replace.parse()?;
let cfg = self.funs.conf::<ReachConfig>();
let _lock = self.sync.lock().await;
let ctx = TardisContext {
Expand All @@ -40,11 +42,12 @@ impl MessageSendListener {
&ctx,
cfg.invoke.module_urls.get("iam").expect("missing iam base url"),
));
// if not pending status, this task may be excuted by other nodes, just return
if !ReachMessageServ::update_status(&message.id, ReachStatusKind::Pending, ReachStatusKind::Sending, &self.funs, &ctx).await? {
return Ok(());
}
let mut to = HashSet::new();

let start_time = Utc::now();
let owner_path = rbum_scope_helper::get_pre_paths(RBUM_SCOPE_LEVEL_TENANT as i16, &message.own_paths).unwrap_or_default();
for account_id in message.to_res_ids.split(ACCOUNT_SPLIT) {
if let Ok(mut resp) = iam_client.get_account(account_id, &owner_path).await {
Expand All @@ -53,14 +56,51 @@ impl MessageSendListener {
continue;
};
to.insert(phone);
} else {
log::warn!("[Reach] iam get account info error, account_id: {account_id}")
}
}
match self.channel.send(message.rel_reach_channel, &template, &message.content_replace.parse()?, &to).await {
match self.channel.send(message.rel_reach_channel, &template, &content_replace, &to).await {
Ok(_) => {
ReachMessageServ::update_status(&message.id, ReachStatusKind::Sending, ReachStatusKind::SendSuccess, &self.funs, &ctx).await?;
for rel_account_id in to {
ReachMessageLogServ::add_rbum(
&mut ReachMsgLogAddReq {
rbum_add_req: Default::default(),
dnd_time: Default::default(),
rel_account_id,
dnd_strategy: ReachDndStrategyKind::Ignore,
start_time,
end_time: Utc::now(),
failure: false,
fail_message: Default::default(),
rel_reach_message_id: message.id.clone(),
},
&self.funs,
&ctx,
).await?;
}
}
Err(e) => {
ReachMessageServ::update_status(&message.id, ReachStatusKind::Sending, ReachStatusKind::Fail, &self.funs, &ctx).await?;
for rel_account_id in to {
ReachMessageLogServ::add_rbum(
&mut ReachMsgLogAddReq {
rbum_add_req: Default::default(),
dnd_time: Default::default(),
rel_account_id,
dnd_strategy: ReachDndStrategyKind::Ignore,
start_time,
end_time: Utc::now(),
failure: true,
fail_message: e.to_string(),
rel_reach_message_id: message.id.clone(),
},
&self.funs,
&ctx,
).await?;
}

return Err(e);
}
}
Expand Down
4 changes: 2 additions & 2 deletions support/reach/tests/test_send_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ pub async fn test_hw_sms() -> TardisResult<()> {
let ctx = get_test_ctx();
let funs = get_tardis_inst();
let client = reach_invoke::Client::new("http://localhost:8080/reach", ctx, &funs);
// client.pwd_send(&phone, &code, &()).await?;
client.pwd_send(&phone, &code, &()).await?;

client.vcode_send(&phone, &code, &()).await?;
// client.vcode_send(&phone, &code, &()).await?;
// wait for send
tokio::time::sleep(Duration::from_secs(10)).await;
drop(holder);
Expand Down