Skip to content

Commit

Permalink
add tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
4t145 committed Jul 28, 2023
1 parent 4b3765e commit a1b4126
Show file tree
Hide file tree
Showing 53 changed files with 874 additions and 302 deletions.
12 changes: 8 additions & 4 deletions sdk/invoke/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,19 @@ name = "bios_sdk_invoke"
path = "src/lib.rs"

[features]
default = ["spi-kv", "spi-log", "spi-search"]
spi-kv = []
spi-log = []
spi-search = []
default = ["spi-kv", "spi-log", "spi-search", "iam"]
spi-base = []
spi-kv = ["spi-base"]
spi-log = ["spi-base"]
spi-search = ["spi-base"]
iam = ["dep:bios-iam"]

[dependencies]
serde.workspace = true
lazy_static.workspace = true
itertools.workspace = true
tardis = { workspace = true, features = ["web-server"] }
bios-iam = { path = "../../support/iam", optional = true }

[dev-dependencies]
tardis = { workspace = true, features = ["test"] }
20 changes: 20 additions & 0 deletions sdk/invoke/src/clients.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,23 @@
use tardis::{
basic::{dto::TardisContext, result::TardisResult},
TardisFuns,
};

use crate::invoke_constants::TARDIS_CONTEXT;

#[cfg(feature = "spi-base")]
mod base_spi_client;
#[cfg(feature = "iam")]
pub mod iam_client;
#[cfg(feature = "spi-kv")]
pub mod spi_kv_client;
#[cfg(feature = "spi-log")]
pub mod spi_log_client;

pub trait TardisCtxTrait {
fn get_ctx(&self) -> &TardisContext;
fn get_tardis_context(&self) -> TardisResult<(String, String)> {
let ctx = self.get_ctx();
Ok((TARDIS_CONTEXT.to_string(), TardisFuns::crypto.base64.encode(&TardisFuns::json.obj_to_string(ctx)?)))
}
}
8 changes: 4 additions & 4 deletions sdk/invoke/src/clients/base_spi_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@ use tardis::web::web_client::TardisHttpResponse;
use tardis::web::web_resp::TardisResp;
use tardis::{TardisFuns, TardisFunsInst};

use crate::invoke_config::InvokeConfig;
use crate::invoke_config::{InvokeConfig, InvokeConfigTrait};
use crate::invoke_constants::TARDIS_CONTEXT;
use crate::invoke_enumeration::InvokeModuleKind;

pub struct BaseSpiClient;

impl BaseSpiClient {
pub async fn module_url(module: InvokeModuleKind, funs: &TardisFunsInst) -> TardisResult<String> {
if let Some(uri) = funs.conf::<InvokeConfig>().module_urls.get(&module.to_string()) {
return Ok(uri.as_str().to_string());
pub async fn module_url<C: InvokeConfigTrait + 'static>(module: InvokeModuleKind, funs: &TardisFunsInst) -> TardisResult<String> {
if let Some(uri) = funs.conf::<C>().get_module_opt_url(module) {
return Ok(uri.to_string());
}
Err(funs.err().conflict("spi-module", "spi_module", "spi module uri Not configured yet.", "400-spi-module-not-exist"))
}
Expand Down
47 changes: 47 additions & 0 deletions sdk/invoke/src/clients/iam_client.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
pub use bios_iam::basic::dto::iam_account_dto::*;
use tardis::{
basic::{dto::TardisContext, result::TardisResult},
TardisFunsInst,
};

use super::TardisCtxTrait;

#[derive(Clone)]
pub struct IamClient<'a> {
pub funs: &'a TardisFunsInst,
pub ctx: &'a TardisContext,
pub account: &'a str,
pub base_url: &'a str,
}

impl<'a> IamClient<'a> {
pub fn new(account: &'a str, funs: &'a TardisFunsInst, ctx: &'a TardisContext, url: &'a str) -> Self {
Self {
funs,
ctx,
account,
base_url: url,
}
}
}
impl<'a> TardisCtxTrait for IamClient<'a> {
fn get_ctx(&self) -> &'a TardisContext {
self.ctx
}
}

impl IamClient<'_> {
pub async fn get_account(&self, id: &str, tenant_id: &str) -> TardisResult<IamAccountSummaryAggResp> {
let ctx = self.get_tardis_context()?;
let url = format!(
"{base_url}/{account}/{id}?tenant_id={tenant_id}",
base_url = self.base_url,
account = self.account,
id = id,
tenant_id = tenant_id
);
let resp = self.funs.web_client().get::<IamAccountSummaryAggResp>(&url, Some(vec![ctx])).await?;
let resp_body = resp.body.ok_or_else(|| self.funs.err().internal_error("iam-client", "get_account", "response", "500-iam_client-request_fail"))?;
Ok(resp_body)
}
}
16 changes: 12 additions & 4 deletions sdk/invoke/src/clients/spi_kv_client.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
use std::marker::PhantomData;

use serde::Serialize;
use tardis::basic::dto::TardisContext;
use tardis::basic::result::TardisResult;
use tardis::serde_json::json;
use tardis::TardisFunsInst;

use crate::invoke_config::InvokeConfigTrait;
use crate::invoke_enumeration::InvokeModuleKind;

use super::base_spi_client::BaseSpiClient;

pub struct SpiKvClient;
#[derive(Debug, Default)]
pub struct SpiKvClient<C> {
marker: PhantomData<C>
}

impl SpiKvClient {
impl<C> SpiKvClient<C>
where C: InvokeConfigTrait + 'static
{
pub async fn add_or_modify_item<T: ?Sized + Serialize>(key: &str, value: &T, info: Option<String>, funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult<()> {
let kv_url: String = BaseSpiClient::module_url(InvokeModuleKind::Kv, funs).await?;
let kv_url: String = BaseSpiClient::module_url::<C>(InvokeModuleKind::Kv, funs).await?;
let headers = BaseSpiClient::headers(None, funs, ctx).await?;
let json = json!({
"key":key.to_string(),
Expand All @@ -24,7 +32,7 @@ impl SpiKvClient {
}

pub async fn add_or_modify_key_name(key: &str, name: &str, funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult<()> {
let kv_url = BaseSpiClient::module_url(InvokeModuleKind::Kv, funs).await?;
let kv_url = BaseSpiClient::module_url::<C>(InvokeModuleKind::Kv, funs).await?;
let headers = BaseSpiClient::headers(None, funs, ctx).await?;
funs.web_client()
.put_obj_to_str(
Expand Down
18 changes: 12 additions & 6 deletions sdk/invoke/src/clients/spi_log_client.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::marker::PhantomData;

use serde::{Deserialize, Serialize};

use tardis::{
Expand All @@ -11,9 +13,11 @@ use tardis::{
TardisFunsInst,
};

use crate::{clients::base_spi_client::BaseSpiClient, invoke_enumeration::InvokeModuleKind};

pub struct SpiLogClient;
use crate::{clients::base_spi_client::BaseSpiClient, invoke_enumeration::InvokeModuleKind, invoke_config::InvokeConfigTrait};
#[derive(Debug, Default)]
pub struct SpiLogClient<C> {
marker: PhantomData<C>
}

#[derive(poem_openapi::Object, Serialize, Deserialize, Debug)]
pub struct LogItemFindReq {
Expand Down Expand Up @@ -43,7 +47,9 @@ pub struct LogItemFindResp {
pub ts: DateTime<Utc>,
}

impl SpiLogClient {
impl<C> SpiLogClient<C>
where C: InvokeConfigTrait + 'static
{
pub async fn add(
tag: &str,
content: &str,
Expand All @@ -58,7 +64,7 @@ impl SpiLogClient {
funs: &TardisFunsInst,
ctx: &TardisContext,
) -> TardisResult<()> {
let log_url: String = BaseSpiClient::module_url(InvokeModuleKind::Log, funs).await?;
let log_url: String = BaseSpiClient::module_url::<C>(InvokeModuleKind::Log, funs).await?;
let headers = BaseSpiClient::headers(None, funs, ctx).await?;
let body = json!({
"tag": tag,
Expand All @@ -77,7 +83,7 @@ impl SpiLogClient {
}

pub async fn find(find_req: LogItemFindReq, funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult<Option<TardisPage<LogItemFindResp>>> {
let log_url: String = BaseSpiClient::module_url(InvokeModuleKind::Log, funs).await?;
let log_url: String = BaseSpiClient::module_url::<C>(InvokeModuleKind::Log, funs).await?;
let headers = BaseSpiClient::headers(None, funs, ctx).await?;
let resp = funs.web_client().put::<LogItemFindReq, TardisResp<TardisPage<LogItemFindResp>>>(&format!("{log_url}/ci/item"), &find_req, headers.clone()).await?;
BaseSpiClient::package_resp(resp)
Expand Down
28 changes: 23 additions & 5 deletions sdk/invoke/src/invoke_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,36 @@ use crate::invoke_enumeration::InvokeModuleKind;
#[serde(default)]
pub struct InvokeConfig {
pub spi_app_id: String,
pub module_urls: HashMap<String, String>,
pub module_urls: HashMap<InvokeModuleKind, String>,
}
pub trait InvokeConfigTrait:
for <'a> Deserialize<'a> {
fn get_spi_app_id(&self) -> &str;
fn get_module_url(&self, module: InvokeModuleKind) -> &str {
self.get_module_opt_url(module).unwrap_or_else(|| panic!("invoke config missing invoke url for module [{module}]"))
}
fn get_module_opt_url(&self, module: InvokeModuleKind) -> Option<&str>;
}

impl InvokeConfigTrait for InvokeConfig {
fn get_spi_app_id(&self) -> &str {
&self.spi_app_id
}

fn get_module_opt_url(&self, module: InvokeModuleKind) -> Option<&str> {
self.module_urls.get(&module).map(|x|x.as_str())
}
}
impl Default for InvokeConfig {
fn default() -> Self {
InvokeConfig {
spi_app_id: Default::default(),
module_urls: HashMap::from([
(InvokeModuleKind::Kv.to_string(), "http://127.0.0.1:8080/spi-kv".to_string()),
(InvokeModuleKind::Log.to_string(), "http://127.0.0.1:8080/spi-log".to_string()),
(InvokeModuleKind::Search.to_string(), "http://127.0.0.1:8080/spi-search".to_string()),
(InvokeModuleKind::Schedule.to_string(), "http://127.0.0.1:8080/schedule".to_string()),
(InvokeModuleKind::Kv, "http://127.0.0.1:8080/spi-kv".to_string()),
(InvokeModuleKind::Log, "http://127.0.0.1:8080/spi-log".to_string()),
(InvokeModuleKind::Search, "http://127.0.0.1:8080/spi-search".to_string()),
(InvokeModuleKind::Schedule, "http://127.0.0.1:8080/schedule".to_string()),
(InvokeModuleKind::Iam, "http://127.0.0.1:8080/iam".to_string()),
]),
}
}
Expand Down
4 changes: 3 additions & 1 deletion sdk/invoke/src/invoke_enumeration.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize};
use tardis::{db::sea_orm, derive_more::Display, web::poem_openapi};

#[derive(Display, Clone, Debug, PartialEq, Eq, Deserialize, Serialize, poem_openapi::Enum, sea_orm::strum::EnumString)]
#[derive(Display, Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize, poem_openapi::Enum, sea_orm::strum::EnumString, Hash)]
pub enum InvokeModuleKind {
#[oai(rename = "search")]
Search,
Expand All @@ -21,4 +21,6 @@ pub enum InvokeModuleKind {
Stats,
#[oai(rename = "schedule")]
Schedule,
#[oai(rename = "iam")]
Iam,
}
2 changes: 1 addition & 1 deletion sdk/invoke/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
mod clients;
pub mod clients;
pub mod invoke_config;
pub mod invoke_constants;
pub mod invoke_enumeration;
9 changes: 8 additions & 1 deletion support/reach/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,15 @@ path = "src/lib.rs"
[dependencies]
serde.workspace = true
lazy_static.workspace = true
tardis = { workspace = true, features = ["reldb-postgres", "web-server", "mail"] }
tardis = { workspace = true, features = [
"reldb-postgres",
"web-server",
"mail",
] }
bios-basic = { path = "../../basic", features = ["default"] }
bios-sdk-invoke = { path = "../../sdk/invoke", features = [
"iam",
], default-features = false }
[dev-dependencies]
tardis = { workspace = true, features = ["test"] }

Expand Down
44 changes: 9 additions & 35 deletions support/reach/src/api/cc/message.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};

use bios_basic::rbum::serv::rbum_crud_serv::RbumCrudOperation;

Expand All @@ -7,46 +7,19 @@ use tardis::web::poem::web::{Json, Path};

use tardis::web::poem_openapi;
use tardis::web::web_resp::{TardisApiResult, TardisResp, Void};
use tardis::TardisFuns;

use crate::client::email::MailClient;
use crate::client::sms::SmsClient;
use crate::client::{email, sms, SendChannel, UnimplementedChannel};
use crate::client::{sms, SendChannelAll};
use crate::config::ReachConfig;
use crate::consts::get_tardis_inst;
use crate::consts::DOMAIN_CODE;
use crate::consts::*;
use crate::dto::*;
use crate::serv::*;

#[derive(Clone)]
#[derive(Clone, Default)]
/// 用户触达消息-公共控制台
pub struct ReachMessageCcApi {
sms_client: sms::SmsClient,
email_client: email::MailClient,
channel: SendChannelAll,
}

impl Default for ReachMessageCcApi {
fn default() -> Self {
let config = TardisFuns::cs_config::<ReachConfig>(DOMAIN_CODE);
let sms_config = &config.sms;
let base_url = sms_config.base_url.parse().expect("invalid sms base url");
let callback_url = sms_config.status_call_back.as_ref().map(|x| x.parse().expect("invalid sms status_call_back url"));
Self {
sms_client: SmsClient::new(base_url, &sms_config.app_key, &sms_config.app_secret, callback_url),
email_client: MailClient::new(),
}
}
}

impl ReachMessageCcApi {
pub fn get_channel(&self, kind: ReachChannelKind) -> &(dyn SendChannel + Send + Sync) {
match kind {
ReachChannelKind::Sms => &self.sms_client,
ReachChannelKind::Email => &self.email_client,
_ => UnimplementedChannel::get_const_ref(kind),
}
}
}
#[poem_openapi::OpenApi(prefix_path = "/cc/msg")]
impl ReachMessageCcApi {
/// 根据模板id发送信息
Expand All @@ -60,7 +33,7 @@ impl ReachMessageCcApi {
) -> TardisApiResult<Void> {
let funs = get_tardis_inst();
let msg_template = ReachMessageTemplateServ::get_by_id(&msg_template_id, &funs, &ctx).await?;
self.get_channel(msg_template.rel_reach_channel).send((&msg_template).into(), &replacement.0.into(), &to).await?;
self.channel.send(msg_template.rel_reach_channel, &msg_template, &replacement.0.into(), &HashSet::from([to.0])).await?;
TardisResp::ok(VOID)
}

Expand All @@ -85,7 +58,7 @@ impl ReachMessageCcApi {
.ok_or_else(|| funs.err().internal_error("reach_message", "vcode_send", "msg", "500-reach-missing-message-template"))?
};
let content_replace = ([("code", code.0)]).into();
self.get_channel(msg_template.rel_reach_channel).send((&msg_template).into(), &content_replace, &to).await?;
self.channel.send(msg_template.rel_reach_channel, &msg_template, &content_replace, &HashSet::from([to.0])).await?;
TardisResp::ok(VOID)
}

Expand All @@ -95,7 +68,8 @@ impl ReachMessageCcApi {
let funs = get_tardis_inst();
let config = funs.conf::<ReachConfig>();
let sms_cfg = &config.sms;
self.sms_client
self.channel
.sms_client
.send_sms(sms::SendSmsRequest {
from: &sms_cfg.sms_general_from,
status_callback: sms_cfg.status_call_back.as_deref(),
Expand Down
7 changes: 4 additions & 3 deletions support/reach/src/client/email.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use tardis::TardisFuns;
use crate::consts::get_tardis_inst;

#[derive(Clone)]
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct MailClient {
pub(super) inner: &'static tardis::mail::mail_client::TardisMailClient,
}

impl MailClient {
pub fn new() -> Self {
Self { inner: TardisFuns::mail() }
Self { inner: get_tardis_inst().mail() }
}
}

Expand Down
Loading

0 comments on commit a1b4126

Please sign in to comment.