Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/ideal-world/tardis into main
Browse files Browse the repository at this point in the history
  • Loading branch information
gudaoxuri committed May 12, 2023
2 parents 183cf43 + 9d88fa3 commit 8f4b51f
Show file tree
Hide file tree
Showing 22 changed files with 986 additions and 21 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/cicd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ jobs:
toolchain: stable
components: rustfmt, clippy

- name: Install Protoc
uses: arduino/setup-protoc@v1

- name: Cache rust
uses: Swatinem/rust-cache@v2

Expand Down
2 changes: 1 addition & 1 deletion examples/multi-apps/doc/src/initializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ use crate::domain::doc;

pub async fn init(web_server: &TardisWebServer) -> TardisResult<()> {
TardisFuns::reldb().conn().create_table_from_entity(doc::Entity).await?;
web_server.add_module("doc", doc_api::DocApi).await;
web_server.add_module("doc", doc_api::DocApi, None).await;
Ok(())
}
4 changes: 2 additions & 2 deletions examples/multi-apps/tag/src/initializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ use tardis::basic::result::TardisResult;
use tardis::web::web_server::TardisWebServer;
use tardis::TardisFuns;

use crate::api::tag_api;
use crate::api::tag_api::{self};
use crate::domain::tag;

pub async fn init(web_server: &TardisWebServer) -> TardisResult<()> {
TardisFuns::reldb().conn().create_table_from_entity(tag::Entity).await?;
web_server.add_module("tag", tag_api::TagApi).await;
web_server.add_module("tag", tag_api::TagApi, None).await;
Ok(())
}
9 changes: 9 additions & 0 deletions examples/tracing-otlp/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "tracing-otlp"
version = "0.1.0"
edition = "2021"

[dependencies]
tardis = { path = "../../tardis", features = ["future", "web-server", "reldb-postgres", "tracing"] }
tracing = { version = "0.1" }
random-string = { version = "1.0.0" }
5 changes: 5 additions & 0 deletions examples/tracing-otlp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## Setup Jaeger Agent

```sh
docker run -d --name jaeger -e COLLECTOR_OTLP_ENABLED=true -p 16686:16686 -p 4317:4317 -p 4318:4318 jaegertracing/all-in-one:latest
```
18 changes: 18 additions & 0 deletions examples/tracing-otlp/config/conf-default.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[fw.app]
id = "tracing-otlp"
name = "tracing示例"
desc = "tracing示例"
version = "1.0.0"

[fw.web_server]
port = 8089
doc_urls = [["test env", "http://localhost:8089/"]]

[fw.db]
url = "postgres://postgres:ENC(5892ae51dbeedacdf10ba4c0d7af42a7)@localhost:5432/test"

[fw.tracing]
level = "info"
endpoint = "http://localhost:4317"
protocol = "grpc"
server_name = "tracing示例"
23 changes: 23 additions & 0 deletions examples/tracing-otlp/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use std::env;
use tardis::basic::result::TardisResult;
use tardis::tokio;
use tardis::TardisFuns;

use crate::route::Api;

mod processor;
mod route;

///
/// Visit: http://127.0.0.1:8089/ui
///
#[tokio::main]
async fn main() -> TardisResult<()> {
env::set_var("RUST_LOG", "debug");
env::set_var("PROFILE", "default");

// Initial configuration
TardisFuns::init(Some("config")).await?;
// Register the processor and start the web service
TardisFuns::web_server().add_route(Api).await.start().await
}
129 changes: 129 additions & 0 deletions examples/tracing-otlp/src/processor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
use std::collections::HashMap;
use tardis::async_trait::async_trait;
use tardis::basic::{error::TardisError, result::TardisResult};
use tardis::tokio;
use tardis::tokio::time::{sleep, Duration};
use tardis::tracing::{debug_span, info_span, instrument, Instrument};

#[derive(Debug)]
pub enum TaskKind {
SendEmail,
SendSms,
SendPush,
ExportExcel,
GenerateImage,
}

impl TryFrom<u32> for TaskKind {
type Error = TardisError;
fn try_from(value: u32) -> TardisResult<Self> {
match value {
1 => Ok(TaskKind::SendEmail),
2 => Ok(TaskKind::SendSms),
3 => Ok(TaskKind::SendPush),
4 => Ok(TaskKind::ExportExcel),
5 => Ok(TaskKind::GenerateImage),
_ => Err(TardisError::not_implemented("[Tardis.Task] Unsupported Task kind", "501-tardis-os-kind-error")),
}
}
}

#[async_trait]
trait Task {
async fn handle(&self, params: HashMap<String, String>) -> TardisResult<()>;
}

#[derive(Debug)]
struct SendEmailTask;

#[async_trait]
impl Task for SendEmailTask {
#[instrument]
async fn handle(&self, _params: HashMap<String, String>) -> TardisResult<()> {
sleep(Duration::from_millis(300)).await;
tokio::spawn(
async move {
let span = debug_span!("into spawn");
let _enter = span.enter();

log_user().await.unwrap();
}
.instrument(tracing::info_span!("task")),
);
Ok(())
}
}

#[derive(Debug)]
struct SendSmsTask;

#[async_trait]
impl Task for SendSmsTask {
#[instrument]
async fn handle(&self, _params: HashMap<String, String>) -> TardisResult<()> {
sleep(Duration::from_millis(300)).await;
log_user().await.unwrap();
Ok(())
}
}

#[derive(Debug)]
struct SendPushTask;

#[async_trait]
impl Task for SendPushTask {
#[instrument]
async fn handle(&self, _params: HashMap<String, String>) -> TardisResult<()> {
sleep(Duration::from_millis(300)).await;
notify_admin().await.unwrap();
Ok(())
}
}

#[derive(Debug)]
struct ExportExcelTask;

#[async_trait]
impl Task for ExportExcelTask {
#[instrument]
async fn handle(&self, _params: HashMap<String, String>) -> TardisResult<()> {
sleep(Duration::from_millis(300)).await;
notify_admin().await.unwrap();
Ok(())
}
}

#[derive(Debug)]
struct GenerateImageTask;

#[async_trait]
impl Task for GenerateImageTask {
#[instrument]
async fn handle(&self, _params: HashMap<String, String>) -> TardisResult<()> {
sleep(Duration::from_millis(500)).await;
notify_admin().await.unwrap();
Ok(())
}
}

pub async fn dispatch(task_kind: TaskKind, params: HashMap<String, String>) -> TardisResult<()> {
match task_kind {
TaskKind::SendEmail => SendEmailTask.handle(params).await,
TaskKind::SendSms => SendSmsTask.handle(params).await,
TaskKind::SendPush => SendPushTask.handle(params).await,
TaskKind::ExportExcel => ExportExcelTask.handle(params).await,
TaskKind::GenerateImage => GenerateImageTask.handle(params).await,
}
}

#[instrument]
async fn notify_admin() -> TardisResult<()> {
sleep(Duration::from_millis(100)).await;
Ok(())
}

#[instrument]
async fn log_user() -> TardisResult<()> {
sleep(Duration::from_millis(100)).await;
Ok(())
}
116 changes: 116 additions & 0 deletions examples/tracing-otlp/src/route.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
use std::collections::HashMap;

use tardis::tracing::instrument;
use tardis::web::poem_openapi;
use tardis::web::web_resp::{TardisApiResult, TardisResp};

use crate::processor::{self, TaskKind};

#[derive(Debug)]
pub struct Api;

#[poem_openapi::OpenApi]
impl Api {
#[instrument]
#[oai(path = "/send_email", method = "get")]
async fn send_email(&self) -> TardisApiResult<String> {
let params = gen_params(&TaskKind::SendEmail);
processor::dispatch(TaskKind::SendEmail, params).await.unwrap();
TardisResp::ok("send email".to_string())
}

#[instrument(level = "debug")]
#[oai(path = "/send_sms", method = "get")]
async fn send_sms(&self) -> TardisApiResult<String> {
let params = gen_params(&TaskKind::SendEmail);
processor::dispatch(TaskKind::SendEmail, params).await.unwrap();
TardisResp::ok("send sms".to_string())
}

#[instrument(level = "debug")]
#[oai(path = "/send_push", method = "get")]
async fn send_push(&self) -> TardisApiResult<String> {
let params = gen_params(&TaskKind::SendEmail);
processor::dispatch(TaskKind::SendEmail, params).await.unwrap();
TardisResp::ok("send push".to_string())
}

#[instrument(level = "debug")]
#[oai(path = "/export_excel", method = "get")]
async fn export_excel(&self) -> TardisApiResult<String> {
let params = gen_params(&TaskKind::ExportExcel);
processor::dispatch(TaskKind::ExportExcel, params).await.unwrap();
TardisResp::ok("send push".to_string())
}

#[instrument(level = "debug")]
#[oai(path = "/generate_image", method = "get")]
async fn generate_image(&self) -> TardisApiResult<String> {
let params = gen_params(&TaskKind::GenerateImage);
processor::dispatch(TaskKind::GenerateImage, params).await.unwrap();
TardisResp::ok("send push".to_string())
}
}

fn gen_params(kind: &TaskKind) -> HashMap<String, String> {
let mut params = HashMap::new();
match kind {
TaskKind::SendEmail => {
params.insert("user_id".to_string(), mock_user_id());
params.insert("email".to_string(), mock_email());
params.insert("content".to_string(), mock_content());
}
TaskKind::SendSms => {
params.insert("user_id".to_string(), mock_user_id());
params.insert("phone".to_string(), mock_phone_num());
params.insert("content".to_string(), mock_content());
}
TaskKind::SendPush => {
params.insert("user_id".to_string(), mock_user_id());
params.insert("token".to_string(), mock_token());
params.insert("content".to_string(), mock_content());
}
TaskKind::ExportExcel => {
params.insert("import_path".to_string(), mock_data_path());
}
TaskKind::GenerateImage => {
params.insert("export_url".to_string(), mock_img_url());
}
}
params
}

fn mock_phone_num() -> String {
let head_charset = "3456789";
let tail_charset = "0123456789";
format!("1{}{}", random_string::generate(2, head_charset), random_string::generate(8, tail_charset))
}

fn mock_email() -> String {
let charset = "0123456789qwertyyuiopasdfghjklzxcvbnm";
format!("{}@gmail.com", random_string::generate(8, charset))
}

fn mock_user_id() -> String {
let charset = "123456789";
random_string::generate(6, charset)
}

fn mock_token() -> String {
let charset = "0123456789qwertyyuiopasdfghjklzxcvbnm";
random_string::generate(16, charset)
}

fn mock_content() -> String {
"test".to_string()
}

fn mock_data_path() -> String {
let charset = "0123456789qwertyyuiopasdfghjklzxcvbnm";
format!("./data/export/tmp/{}.csv", random_string::generate(12, charset))
}

fn mock_img_url() -> String {
let charset = "0123456789qwertyyuiopasdfghjklzxcvbnm";
format!("www.xxx.com/oss/{}.jpg", random_string::generate(13, charset))
}
13 changes: 13 additions & 0 deletions examples/tracing/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "tardis-example-tracing"
version = "0.1.0"
authors.workspace = true
edition.workspace = true
publish = false

[dependencies]
log = { version = "0.4" }
tracing = { version = "0.1" }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tardis = { path = "../../tardis", features = ["future"] }
random-string = { version = "1.0.0" }
Loading

0 comments on commit 8f4b51f

Please sign in to comment.