Skip to content

Commit

Permalink
处理异味
Browse files Browse the repository at this point in the history
  • Loading branch information
shenghui0779 committed May 18, 2024
1 parent 8af002e commit 284ea66
Show file tree
Hide file tree
Showing 10 changed files with 176 additions and 162 deletions.
276 changes: 150 additions & 126 deletions Cargo.lock

Large diffs are not rendered by default.

17 changes: 2 additions & 15 deletions api/src/middleware/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,23 +73,15 @@ async fn drain_body(request: Request, next: Next) -> Result<(Response, Option<St
.and_then(|value| value.to_str().ok())
{
Some(v) => {
if v.starts_with("application/json")
|| v.starts_with("application/x-www-form-urlencoded")
{
true
} else {
false
}
v.starts_with("application/json") || v.starts_with("application/x-www-form-urlencoded")
}
None => false,
};

if !ok {
return Ok((next.run(request).await, None));
}

let (parts, body) = request.into_parts();

// this wont work if the body is an long running stream
let bytes = match body.collect().await {
Ok(v) => v.to_bytes(),
Expand All @@ -98,14 +90,9 @@ async fn drain_body(request: Request, next: Next) -> Result<(Response, Option<St
return Err(ApiErr::ErrSystem(None));
}
};

let body = std::str::from_utf8(&bytes)
.and_then(|s| Ok(s.to_string()))
.ok();

let body = std::str::from_utf8(&bytes).map(|s| s.to_string()).ok();
let response = next
.run(Request::from_parts(parts, Body::from(bytes)))
.await;

Ok((response, body))
}
2 changes: 1 addition & 1 deletion api/src/service/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ pub struct RespList {
pub async fn list(query: HashMap<String, String>) -> Result<ApiOK<RespList>> {
let mut builder = Account::find();
if let Some(username) = query.get("username") {
if username.len() > 0 {
if !username.is_empty() {
builder = builder.filter(account::Column::Username.eq(username.to_owned()));
}
}
Expand Down
16 changes: 10 additions & 6 deletions api/src/service/identity.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt::Display;

use anyhow::{anyhow, Result};
use base64::{prelude::BASE64_STANDARD, Engine};
use sea_orm::EntityTrait;
Expand Down Expand Up @@ -65,7 +67,7 @@ impl Identity {
match serde_json::from_slice::<Identity>(&plain) {
Err(e) => {
tracing::error!(error = ?e, "error invalid auth_token");
return Identity::empty();
Identity::empty()
}
Ok(identity) => identity,
}
Expand Down Expand Up @@ -110,22 +112,24 @@ impl Identity {
match Account::find_by_id(self.id()).one(db::conn()).await? {
None => return Err(anyhow!("授权账号不存在")),
Some(v) => {
if v.login_token.len() == 0 || self.t != v.login_token {
if v.login_token.is_empty() || self.t != v.login_token {
return Err(anyhow!("授权已失效"));
}
}
}

Ok(())
}
}

pub fn to_string(&self) -> String {
impl Display for Identity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.i == 0 {
return String::from("<none>");
return write!(f, "<none>");
}
if self.r == 0 {
return format!("id:{}|token:{}", self.i, self.t);
return write!(f, "id:{}|token:{}", self.i, self.t);
}
format!("id:{}|role:{}|token:{}", self.i, self.r, self.t)
write!(f, "id:{}|role:{}|token:{}", self.i, self.r, self.t)
}
}
4 changes: 2 additions & 2 deletions api/src/service/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,12 @@ pub async fn list(identity: Identity, query: HashMap<String, String>) -> Result<
builder = builder.filter(project::Column::AccountId.eq(identity.id()));
}
if let Some(code) = query.get("code") {
if code.len() > 0 {
if !code.is_empty() {
builder = builder.filter(project::Column::Code.eq(code.to_owned()));
}
}
if let Some(name) = query.get("name") {
if name.len() > 0 {
if !name.is_empty() {
builder = builder.filter(project::Column::Name.contains(name));
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ thiserror = "1.0"
anyhow = "1.0"
rand = "0.8"
const-hex = "1.10"
openssl = "0.10"
openssl = { version = "0.10", features = ["vendored"] }
digest = "0.10"
md-5 = "0.10"
sha1 = "0.10"
Expand Down
8 changes: 4 additions & 4 deletions pkg/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,10 @@ impl mobc::Manager for RedisAsyncConnManager {
}

async fn check(&self, mut conn: Self::Connection) -> Result<Self::Connection, Self::Error> {
if !redis::cmd("PING")
if redis::cmd("PING")
.query_async::<Self::Connection, String>(&mut conn)
.await
.is_ok()
.is_err()
{
return Err(redis::RedisError::from(io::Error::from(
io::ErrorKind::BrokenPipe,
Expand Down Expand Up @@ -195,10 +195,10 @@ impl mobc::Manager for RedisClusterAsyncConnManager {
}

async fn check(&self, mut conn: Self::Connection) -> Result<Self::Connection, Self::Error> {
if !redis::cmd("PING")
if redis::cmd("PING")
.query_async::<Self::Connection, String>(&mut conn)
.await
.is_ok()
.is_err()
{
return Err(redis::RedisError::from(io::Error::from(
io::ErrorKind::BrokenPipe,
Expand Down
6 changes: 3 additions & 3 deletions pkg/src/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ impl RedisLock {
self.token = token;
return Ok(true);
}
return Ok(false);
Ok(false)
}
Err(e) => {
// 尝试GET一次:避免因redis网络错误导致误加锁
Expand All @@ -65,7 +65,7 @@ impl RedisLock {
self.token = token;
return Ok(true);
}
return Ok(false);
Ok(false)
}
}
}
Expand All @@ -74,7 +74,7 @@ impl RedisLock {
// 释放锁
impl Drop for RedisLock {
fn drop(&mut self) {
if self.token.len() == 0 {
if self.token.is_empty() {
return;
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/src/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl<'a> Format<'a> {

// 日期转Unix时间戳
pub fn to_timestamp(self, datetime: &str) -> i64 {
if datetime.len() == 0 {
if datetime.is_empty() {
return 0;
}

Expand Down
5 changes: 2 additions & 3 deletions pkg/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ pub fn query_page(args: &HashMap<String, String>) -> (u64, u64) {
limit = size
}
}

if limit > 100 {
limit = 100
}
Expand All @@ -33,9 +32,9 @@ pub fn query_page(args: &HashMap<String, String>) -> (u64, u64) {
}

pub fn new_validation_err(s: String) -> ValidationError {
return ValidationError {
ValidationError {
code: Cow::from(""),
message: Some(Cow::from(s)),
params: HashMap::new(),
};
}
}

0 comments on commit 284ea66

Please sign in to comment.