Skip to content

Commit

Permalink
feat: 更新库依赖
Browse files Browse the repository at this point in the history
  • Loading branch information
yangjing committed Sep 23, 2024
1 parent 137e38d commit fbd5f18
Show file tree
Hide file tree
Showing 20 changed files with 105 additions and 52 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ hmac = "0.12"
sha2 = "0.10"
argon2 = "0.5"
# -- JWT & JWE
josekit = "0.8"
josekit = "0.10"
aliri = "0.6"
# -- Async
futures = "0.3"
Expand Down Expand Up @@ -171,7 +171,7 @@ prost-build = "0.13"
prost-types = "0.13"

# -- opendal
opendal = { version = "0.49", features = ["services-obs"] }
opendal = { version = "0.50", features = ["services-obs"] }

strum = { version = "0.26", features = ["derive"] }
strum_macros = "0.26"
Expand Down
19 changes: 15 additions & 4 deletions crates/ultimate-api/src/v1/page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,23 @@ impl<T> PagePayload<T> {
pub struct Pagination {
#[prost(int64, tag = "1")]
pub page: i64,

#[prost(int64, tag = "2")]
pub page_size: i64,

#[serde(default = "default_sort_bys")]
#[prost(message, repeated, tag = "3")]
pub sort_bys: ::prost::alloc::vec::Vec<SortBy>,

#[serde(skip_serializing_if = "Option::is_none")]
#[prost(int64, optional, tag = "4")]
pub offset: ::core::option::Option<i64>,
}

fn default_sort_bys() -> Vec<SortBy> {
vec![]
}

impl Pagination {
pub fn page(&self) -> i64 {
self.page
Expand Down Expand Up @@ -101,7 +110,7 @@ pub struct SortBy {
impl From<SortBy> for modql::filter::OrderBy {
fn from(value: SortBy) -> Self {
match value.d.try_into().unwrap_or_default() {
SortDirection::ASC => modql::filter::OrderBy::Asc(value.f),
SortDirection::ASC | SortDirection::UNSPECIFIED => modql::filter::OrderBy::Asc(value.f),
SortDirection::DESC => modql::filter::OrderBy::Desc(value.f),
}
}
Expand All @@ -111,7 +120,7 @@ impl From<SortBy> for modql::filter::OrderBy {
impl From<&SortBy> for modql::filter::OrderBy {
fn from(value: &SortBy) -> Self {
match value.d.try_into().unwrap_or_default() {
SortDirection::ASC => modql::filter::OrderBy::Asc(value.f.clone()),
SortDirection::ASC | SortDirection::UNSPECIFIED => modql::filter::OrderBy::Asc(value.f.clone()),
SortDirection::DESC => modql::filter::OrderBy::Desc(value.f.clone()),
}
}
Expand All @@ -123,8 +132,9 @@ impl From<&SortBy> for modql::filter::OrderBy {
#[repr(i32)]
#[allow(non_camel_case_types)]
pub enum SortDirection {
ASC = 0,
DESC = 1,
UNSPECIFIED = 0,
ASC = 1,
DESC = 2,
}

impl SortDirection {
Expand All @@ -136,6 +146,7 @@ impl SortDirection {
match self {
SortDirection::ASC => "ASC",
SortDirection::DESC => "DESC",
SortDirection::UNSPECIFIED => "UNSPECIFIED",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
Expand Down
3 changes: 2 additions & 1 deletion crates/ultimate-db/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ workspace = true
default = ["modql"]
utoipa = ["dep:utoipa", "ultimate-api/utoipa"]
modql = ["dep:modql", "ultimate-api/modql"]
uuid = ["dep:uuid"]

[dependencies]
ultimate-api = { workspace = true }
Expand All @@ -27,7 +28,7 @@ log.workspace = true
thiserror.workspace = true
tokio.workspace = true
tracing.workspace = true
uuid.workspace = true
uuid = { workspace = true, optional = true }
sqlx.workspace = true
sea-query-binder.workspace = true
sea-query.workspace = true
Expand Down
8 changes: 6 additions & 2 deletions crates/ultimate-db/src/base/crud_fns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ where
let sqlx_query = sqlx::query_with(&sql, values);

let count = mm.dbx().execute(sqlx_query).await?;
if count == 0 {
if count == 1 {
Ok(())
} else {
// TODO 需要更有效的插入失败错误
Expand Down Expand Up @@ -137,7 +137,11 @@ where
E: for<'r> FromRow<'r, PgRow> + Unpin + Send,
E: HasSeaFields,
{
let filter: FilterGroups = id.to_filter_node("id").into();
let filter: FilterGroups = match id {
#[cfg(feature = "uuid")]
Id::Uuid(id) => crate::IdUuidFilter { id: Some(modql::filter::OpValString::Eq(id.to_string()).into()) }.into(),
_ => id.to_filter_node("id").into(),
};
find_unique::<MC, E, _>(mm, filter).await?.ok_or_else(|| Error::EntityNotFound {
schema: MC::SCHEMA,
entity: MC::TABLE,
Expand Down
45 changes: 42 additions & 3 deletions crates/ultimate-db/src/id.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use derive_more::derive::Display;
use modql::{field::HasSeaFields, filter::FilterNode};
use modql::{
field::HasSeaFields,
filter::{FilterNode, FilterNodes, OpValsString},
};
use sea_query::SimpleExpr;
use serde::{Deserialize, Serialize};
use sqlx::{postgres::PgRow, FromRow};
use uuid::Uuid;

pub trait DbRowType: HasSeaFields + for<'r> FromRow<'r, PgRow> + Unpin + Send {}

Expand All @@ -13,7 +15,8 @@ pub enum Id {
I32(i32),
I64(i64),
String(String),
Uuid(Uuid),
#[cfg(feature = "uuid")]
Uuid(uuid::Uuid),
}

impl Id {
Expand All @@ -22,11 +25,18 @@ impl Id {
Id::I32(id) => (col, *id).into(),
Id::I64(id) => (col, *id).into(),
Id::String(id) => (col, id).into(),
#[cfg(feature = "uuid")]
Id::Uuid(id) => (col, id.to_string()).into(),
}
}
}

#[derive(Debug, Default, Deserialize, FilterNodes)]
pub struct IdUuidFilter {
#[modql(cast_as = "uuid")]
pub id: Option<OpValsString>,
}

impl From<Id> for FilterNode {
fn from(id: Id) -> Self {
id.to_filter_node("id")
Expand All @@ -39,6 +49,7 @@ impl From<Id> for SimpleExpr {
Id::I32(id) => SimpleExpr::Value(id.into()),
Id::I64(id) => SimpleExpr::Value(id.into()),
Id::String(id) => SimpleExpr::Value(id.into()),
#[cfg(feature = "uuid")]
Id::Uuid(id) => SimpleExpr::Value(id.into()),
}
}
Expand Down Expand Up @@ -68,6 +79,20 @@ impl From<&str> for Id {
}
}

#[cfg(feature = "uuid")]
impl From<uuid::Uuid> for Id {
fn from(value: uuid::Uuid) -> Self {
Id::Uuid(value)
}
}

#[cfg(feature = "uuid")]
impl From<&uuid::Uuid> for Id {
fn from(value: &uuid::Uuid) -> Self {
Id::Uuid(*value)
}
}

pub fn to_vec_id<V, I>(ids: I) -> Vec<Id>
where
V: Into<Id>,
Expand All @@ -84,23 +109,37 @@ mod tests {
struct TestModel {
pub role_id: i32,
pub user_id: i64,
#[cfg(feature = "uuid")]
pub order_id: Uuid,
#[cfg(not(feature = "uuid"))]
pub order_id: String,
pub dict_id: String,
}

#[test]
fn test_id() -> anyhow::Result<()> {
let id = Id::I32(32);
println!("id is {id}");

#[cfg(feature = "uuid")]
let order_id = Id::Uuid(Uuid::now_v7());
#[cfg(not(feature = "uuid"))]
let order_id = Id::String("123".to_string());

println!("order id is {order_id}");
assert_eq!("32", serde_json::to_string(&id)?);
assert_eq!(serde_json::to_string(&Id::String("abcdefg".into()))?, r#""abcdefg""#);

let tm = TestModel {
role_id: 53,
user_id: 2309457238947,

#[cfg(feature = "uuid")]
order_id: Uuid::now_v7(),

#[cfg(not(feature = "uuid"))]
order_id: "123".to_string(),

dict_id: "system.run.mode".to_string(),
};

Expand Down
5 changes: 3 additions & 2 deletions crates/ultimate-grpc/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use futures::{Future, TryFutureExt};
use prost_types::FieldMask;
use tonic::{metadata::MetadataMap, service::RoutesBuilder, transport::Server, Status};
use tower_http::{compression::CompressionLayer, trace::TraceLayer};
use tower_http::trace::TraceLayer;
use ultimate::{
configuration::model::{GrpcConf, SecurityConf},
security::{jose::JwtPayload, SecurityUtils},
Expand All @@ -18,7 +18,8 @@ where
{
let grpc_addr = conf.server_addr.parse()?;

let mut b = Server::builder().layer(CompressionLayer::new()).layer(TraceLayer::new_for_grpc());
#[allow(unused_mut)]
let mut b = Server::builder().layer(TraceLayer::new_for_grpc());

#[cfg(feature = "tonic-web")]
let mut b = b.accept_http1(true).layer(tonic_web::GrpcWebLayer::new());
Expand Down
7 changes: 3 additions & 4 deletions crates/ultimate-web/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use axum::response::IntoResponse;
use axum::Json;
use serde::Serialize;
use serde_json::Value;
use ulid::Ulid;
use ultimate::security;
use ultimate::DataError;

Expand All @@ -14,7 +13,7 @@ pub type AppResult<T> = core::result::Result<Json<T>, AppError>;
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct AppError {
/// A unique error ID.
pub err_id: Ulid,
pub err_id: ulid::Ulid,

pub err_code: i32,

Expand All @@ -28,11 +27,11 @@ pub struct AppError {

impl AppError {
pub fn new(error: impl Into<String>) -> Self {
Self { err_id: Ulid::new(), err_code: 500, err_msg: error.into(), err_msg_detail: None }
Self { err_id: ulid::Ulid::new(), err_code: 500, err_msg: error.into(), err_msg_detail: None }
}

pub fn new_with_code(err_code: i32, err_msg: impl Into<String>) -> Self {
Self { err_id: Ulid::new(), err_code, err_msg: err_msg.into(), err_msg_detail: None }
Self { err_id: ulid::Ulid::new(), err_code, err_msg: err_msg.into(), err_msg_detail: None }
}

pub fn with_err_code(mut self, err_code: i32) -> Self {
Expand Down
4 changes: 2 additions & 2 deletions crates/ultimate-web/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ use tower_http::{
};
use tracing::info;

use ultimate::configuration::UltimateConfig;
use ultimate::configuration::Configuration;

pub async fn init_server(conf: Arc<UltimateConfig>, app: Router) -> ultimate::Result<()> {
pub async fn init_server(conf: Arc<Configuration>, app: Router) -> ultimate::Result<()> {
let make_service = app
.layer(CompressionLayer::new())
.layer(CorsLayer::new().allow_methods(cors::Any).allow_origin(cors::Any))
Expand Down
4 changes: 2 additions & 2 deletions crates/ultimate/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ tokio.workspace = true
async-trait.workspace = true
toml.workspace = true
config.workspace = true
strum_macros.workspace = true
strum.workspace = true
uuid = { workspace = true, optional = true }
ulid = { workspace = true, optional = true }
ulid = { workspace = true }
log.workspace = true
tracing.workspace = true
# tracing-log.workspace = true
Expand Down
2 changes: 1 addition & 1 deletion crates/ultimate/examples/example-config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ fn main() {

let config_state = starter::load_and_init();

println!("Config content is:\n{}", toml::to_string(config_state.ultimate_config()).unwrap());
println!("Config content is:\n{}", toml::to_string(config_state.configuration()).unwrap());
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use serde::{Deserialize, Deserializer, Serialize};
use super::model::{AppConf, DbConf, GrpcConf, SecurityConf, TraceConfig, WebConfig};

#[derive(Clone, Serialize, Deserialize)]
pub struct UltimateConfig {
pub struct Configuration {
app: AppConf,

security: SecurityConf,
Expand All @@ -19,7 +19,7 @@ pub struct UltimateConfig {
grpc: GrpcConf,
}

impl UltimateConfig {
impl Configuration {
pub fn app(&self) -> &AppConf {
&self.app
}
Expand All @@ -45,11 +45,11 @@ impl UltimateConfig {
}
}

impl TryFrom<&Config> for UltimateConfig {
impl TryFrom<&Config> for Configuration {
type Error = super::Error;

fn try_from(c: &Config) -> std::result::Result<Self, Self::Error> {
let qc = c.get::<UltimateConfig>("ultimate")?;
let qc = c.get::<Configuration>("ultimate")?;
Ok(qc)
}
}
Expand Down Expand Up @@ -124,7 +124,7 @@ mod tests {
std::env::set_var("ULTIMATE__SECURITY__PWD__PWD_KEY", "80c9a35c0f231219ca14c44fe10c728d");
std::env::set_var("ULTIMATE__APP__NAME", "ultimate");
let c = load_config().unwrap();
let qc = UltimateConfig::try_from(&c).unwrap();
let qc = Configuration::try_from(&c).unwrap();

assert_eq!(qc.security().pwd().pwd_key(), b"80c9a35c0f231219ca14c44fe10c728d");
assert_eq!(qc.security().token().secret_key(), b"8462b1ec9af827ebed13926f8f1e5409774fa1a21a1c8f726a4a34cf7dcabaf2");
Expand Down
Loading

0 comments on commit fbd5f18

Please sign in to comment.