Skip to content

Commit

Permalink
Order server use uuid for user_id,and get uuid from jwt.
Browse files Browse the repository at this point in the history
  • Loading branch information
whitestarlau committed Jul 23, 2023
1 parent 33530bb commit 82e36a6
Show file tree
Hide file tree
Showing 10 changed files with 92 additions and 44 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions order_server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ default-run = "order-service"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
jwt_lib = { path = "../jwt_lib" }
common_lib = { path = "../common_lib" }

axum = "0.6.10"
Expand All @@ -19,6 +20,7 @@ sqlx = { version = "0.6.2", features = [
"runtime-tokio-rustls",
"macros",
"chrono",
"uuid",
] }
serde = { version = "1.0.134", features = ["derive"] }
serde_json = "1.0"
Expand Down Expand Up @@ -50,6 +52,9 @@ tracing = "0.1"
tracing-subscriber = "0.3"
tracing-appender = "0.2.2"

# uuid生成
uuid = { version = "1.4.0", features = ["serde", "v4"] }

[build-dependencies]
tonic-build = "0.8"

Expand Down
2 changes: 1 addition & 1 deletion order_server/db_local_new.sql
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ drop table if exists orders_de_inventory_msg;
create table orders_de_inventory_msg (
id serial primary key,

user_id BIGINT not null,
user_id UUID not null,

order_id INT not null,

Expand Down
2 changes: 1 addition & 1 deletion order_server/db_new.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ drop table if exists orders;
create table orders (
id serial primary key,

user_id BIGINT not null,
user_id UUID not null,

item_id INT not null,
price INT not null,
Expand Down
13 changes: 9 additions & 4 deletions order_server/src/bin/test-grpc.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use uuid::Uuid;

use crate::order_proto::{order_service_client::OrderServiceClient, GetOrderRequest};

mod order_proto {
Expand All @@ -7,11 +9,14 @@ mod order_proto {
#[tokio::main]
async fn main() {
println!("test grpc");
let get_order_result = grpc_get_order(810975).await;
eprintln!("grpc_get_order result: {:?}", get_order_result);
let uuid_parse = Uuid::parse_str(&"ddeee".to_string());
if let Ok(uuid) = uuid_parse {
let get_order_result = grpc_get_order(uuid).await;
eprintln!("grpc_get_order result: {:?}", get_order_result);
}
}

async fn grpc_get_order(user_id: i64) -> Result<String, String> {
async fn grpc_get_order(user_id: Uuid) -> Result<String, String> {
let addr = "http://127.0.0.1:3000";
eprintln!("grpc_get_order on : {}", addr);

Expand All @@ -22,7 +27,7 @@ async fn grpc_get_order(user_id: i64) -> Result<String, String> {
eprintln!("grpc_get_order client success.");

let req = tonic::Request::new(GetOrderRequest {
user_id: user_id,
user_id: user_id.to_string(),
page: 0,
page_size: 5,
});
Expand Down
10 changes: 6 additions & 4 deletions order_server/src/db_access/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use chrono::NaiveDateTime;
use common_lib::internal_error;
use sqlx::postgres::PgPool;
use tracing::info;
use uuid::Uuid;

use crate::{
db_access::repo::deduction_inventory_call,
Expand All @@ -20,7 +21,7 @@ mod inventory_proto {

pub async fn get_all_orders_from_db(
pool: &PgPool,
user_id: i64,
user_id: Uuid,
page: i64,
page_size: i64,
) -> Result<Vec<Order>, (StatusCode, String)> {
Expand Down Expand Up @@ -59,6 +60,7 @@ pub async fn add_new_order_from_db(
local_pool: &PgPool,
inventory_addr: String,
data: AddOrder,
uuid: Uuid,
) -> Result<AddOrderResult, (StatusCode, String)> {
let des = data.description.unwrap_or_default();
let price = data.price;
Expand All @@ -71,7 +73,7 @@ pub async fn add_new_order_from_db(
let ts_1970 = NaiveDateTime::from_timestamp_opt(0, 0).unwrap_or_default();

let insert_result :Result<i32, (StatusCode, String)> = sqlx::query!("INSERT INTO orders (user_id, item_id, price, count, currency, pay_time, description,inventory_state) VALUES ($1, $2, $3, $4, $5, $6, $7,$8) RETURNING id",
data.user_id,
uuid,
data.items_id,
data.price,data.count, data.currency,
ts_1970, des,
Expand All @@ -83,10 +85,10 @@ pub async fn add_new_order_from_db(
.map_err(internal_error);

match insert_result {
Ok(order_id ) => {
Ok(order_id) => {
let insert_msg = sqlx::query!(
"INSERT INTO orders_de_inventory_msg (user_id, order_id) VALUES ($1, $2) RETURNING id",
data.user_id,
uuid,
order_id,
)
.map(|row| row.id)
Expand Down
38 changes: 29 additions & 9 deletions order_server/src/handlers/grpc.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::f32::consts::E;

use sqlx::PgPool;
use uuid::Uuid;

use crate::{
db_access::db::{add_new_order_from_db, get_all_orders_from_db},
Expand Down Expand Up @@ -32,21 +35,29 @@ impl OrderService for GrpcServiceImpl {
request: tonic::Request<order_proto::GetOrderRequest>,
) -> Result<tonic::Response<order_proto::GetOrderRespone>, tonic::Status> {
let request_data = request.into_inner();
let db = get_all_orders_from_db(
&self.pool,
request_data.user_id,
request_data.page,
request_data.page_size,
)
.await;

let uuid_result = Uuid::parse_str(&request_data.user_id);
let uuid: Uuid;
if let Ok(uid) = uuid_result {
uuid = uid;
} else {
let response = order_proto::GetOrderRespone { orders: vec![] };
return Ok(tonic::Response::new(response));
}

let db =
get_all_orders_from_db(&self.pool, uuid, request_data.page, request_data.page_size)
.await;

let mut response_datas: Vec<order_proto::Order> = Vec::new();
if let Ok(datas) = db {
for order in datas {
// let item_id_str = serde_json::to_string(&order.items_id).unwrap_or_default();
let des = order.description.unwrap_or_default();

let uuid_str = order.user_id.to_string();
let proto_order = order_proto::Order {
user_id: order.user_id,
user_id: uuid_str,
items_id: order.item_id,
price: order.price,
count: order.count,
Expand All @@ -71,8 +82,16 @@ impl OrderService for GrpcServiceImpl {
) -> Result<tonic::Response<order_proto::AddOrderRespone>, tonic::Status> {
let request_data = request.into_inner();

let uuid_result = Uuid::parse_str(&request_data.user_id);
let uuid: Uuid;
if let Ok(uid) = uuid_result {
uuid = uid;
} else {
let response = order_proto::AddOrderRespone { result: 1 };
return Ok(tonic::Response::new(response));
}

let add = AddOrder {
user_id: request_data.user_id,
items_id: request_data.items_id,
price: request_data.price,
count: request_data.count,
Expand All @@ -85,6 +104,7 @@ impl OrderService for GrpcServiceImpl {
&self.local_pool,
"https://127.0.0.1:3001".to_string(),
add,
uuid,
)
.await;

Expand Down
49 changes: 32 additions & 17 deletions order_server/src/handlers/rest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ use axum::{
use futures::TryFutureExt;
use idgenerator::IdInstance;

use jwt_lib::jwt::Claims;
use tracing::{info, instrument};
use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt};


use crate::{
consul_api,
db_access::db::{add_new_order_from_db, get_all_orders_from_db},
Expand All @@ -29,7 +29,6 @@ pub async fn health_handler() -> Html<&'static str> {
Html("<h1>Order server health ok.</h1>")
}


#[instrument]
pub async fn get_all_orders(
State(state): State<AppState>,
Expand All @@ -52,33 +51,49 @@ pub async fn get_all_orders(
* 生成一个新的token,存入数据库,然后在addOrder的时候我们会校验这个token是否使用过
*/
pub async fn request_new_order_token(
claims_op: Option<Claims>,
State(_pool): State<AppState>,
) -> Result<axum::Json<NewOrderToken>, (StatusCode, String)> {
let id = IdInstance::next_id();
println!("request_new_order_token: {}", id);
Ok(axum::Json(NewOrderToken { token: id }))
if let Some(claims) = claims_op {
let id = IdInstance::next_id();
println!("request_new_order_token: {}", id);
Ok(axum::Json(NewOrderToken { token: id }))
} else {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
"Cannot found legal jwt from header.".to_string(),
));
}
}

pub async fn add_new_order(
claims_op: Option<Claims>,
State(state): State<AppState>,
Json(data): Json<AddOrder>,
) -> Result<axum::Json<AddOrderResult>, (StatusCode, String)> {
//TODO 此处插入数据合法性校验

//从consul获取库存微服务的地址
let cs = consul_api::consul::Consul::newDefault().map_err(map_consult_error)?;
let filter = consul_api::model::Filter::ID(state.inventory_srv_id);
let srv_option = cs.get_service(&filter).await.map_err(map_consult_error)?;
//TODO 此处插入token数据合法性校验
if let Some(claims) = claims_op {
let uuid = claims.sub;
//从consul获取库存微服务的地址
let cs = consul_api::consul::Consul::newDefault().map_err(map_consult_error)?;
let filter = consul_api::model::Filter::ID(state.inventory_srv_id);
let srv_option = cs.get_service(&filter).await.map_err(map_consult_error)?;

if let Some(srv) = srv_option {
let inventory_addr = srv.address;
add_new_order_from_db(&state.pool, &state.local_pool, inventory_addr, data)
.await
.map(map_ok_result)
if let Some(srv) = srv_option {
let inventory_addr = srv.address;
add_new_order_from_db(&state.pool, &state.local_pool, inventory_addr, data, uuid)
.await
.map(map_ok_result)
} else {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
"cannot found inventory_srv from consul.".to_string(),
));
}
} else {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
"cannot found inventory_srv from consul.".to_string(),
"Cannot found legal jwt from header.".to_string(),
));
}
}
Expand Down
9 changes: 4 additions & 5 deletions order_server/src/models/order.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct GetOrderParams {
pub user_id: i64,
pub user_id: Uuid,
pub page: i64,
pub page_size: i64,
}
Expand All @@ -15,7 +16,7 @@ pub struct GetOrderParams {
pub struct Order {
pub id: i32,

pub user_id: i64,
pub user_id: Uuid,

pub item_id: i32,
pub price: i32,
Expand All @@ -32,8 +33,6 @@ pub struct Order {

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct AddOrder {
pub user_id: i64,

pub items_id: i32,
pub price: i32,
pub count : i32,
Expand All @@ -59,7 +58,7 @@ pub struct NewOrderToken {
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct OrderDeInventoryMsg {
pub id: i32,
pub user_id: i64,
pub user_id: Uuid,

pub order_id: i32,
}
6 changes: 3 additions & 3 deletions proto/order.proto
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ syntax = "proto3";
package order;

message GetOrderRequest {
int64 user_id = 1;
string user_id = 1;
int64 page = 2;
int64 page_size = 3;
}

message Order {
int64 user_id = 1;
string user_id = 1;
int32 items_id = 2;
int32 price = 3;
int32 count = 4;
Expand All @@ -21,7 +21,7 @@ message GetOrderRespone {
}

message AddOrderRequest {
int64 user_id = 1;
string user_id = 1;
int32 items_id = 2;
int32 price = 3;
int32 count = 4;
Expand Down

0 comments on commit 82e36a6

Please sign in to comment.