Skip to content

Commit

Permalink
Merge pull request #184 from Enraged-Dun-Cookie-Development-Team/fix-…
Browse files Browse the repository at this point in the history
…官网跨域支持

修复一堆之前合并误删的代码
  • Loading branch information
phidiaLam authored May 17, 2024
2 parents bbfbfa3 + 8648f88 commit bbb2a6e
Show file tree
Hide file tree
Showing 16 changed files with 105 additions and 148 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/checker.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
- name: Rust toolchain Stable
uses: actions-rs/toolchain@v1
with:
toolchain: 1.77.0
toolchain: 1.78.0
components: clippy
default: true
- name: Rust toolchain Nightly
Expand Down
37 changes: 4 additions & 33 deletions libs/range-limit/src/range_limit/serde.rs
Original file line number Diff line number Diff line change
@@ -1,37 +1,8 @@
use std::ops::Deref;

use serde::{de, Serialize};
use serde::{de, Deserialize, Serialize};

use crate::{measurable::Measurable, RangeBound, RangeBoundLimit};

trait SerdeProc {
type ToSerde: Measurable + serde::Serialize;
fn to_serde(&self) -> &Self::ToSerde;
}

struct Normal<T>(T);

impl<T: Measurable + Serialize> SerdeProc for Normal<T> {
type ToSerde = T;

fn to_serde(&self) -> &Self::ToSerde { &self.0 }
}

struct SmartPtr<P, T>(P)
where
P: Deref<Target = T>;

impl<P, T> SerdeProc for SmartPtr<P, T>
where
P: Deref<Target = T>,
T: Measurable + Serialize,
{
type ToSerde = T;

fn to_serde(&self) -> &Self::ToSerde { self.0.deref() }
}

impl<T: serde::Serialize, Rb> serde::Serialize for RangeBoundLimit<T, Rb> {
impl<T: serde::Serialize, Rb> Serialize for RangeBoundLimit<T, Rb> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
Expand All @@ -40,9 +11,9 @@ impl<T: serde::Serialize, Rb> serde::Serialize for RangeBoundLimit<T, Rb> {
}
}

impl<'de, T, Rb> serde::Deserialize<'de> for RangeBoundLimit<T, Rb>
impl<'de, T, Rb> Deserialize<'de> for RangeBoundLimit<T, Rb>
where
T: serde::Deserialize<'de> + Measurable,
T: Deserialize<'de> + Measurable,
Rb: RangeBound,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
Expand Down
2 changes: 1 addition & 1 deletion libs/status-err/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub trait StatusErr: std::error::Error {
fn prefix(&self) -> ErrPrefix;

fn code(&self) -> u16;
///

fn status(&self) -> status_code::StatusCode {
status_code::StatusCode::new(self.prefix(), self.code())
}
Expand Down
5 changes: 1 addition & 4 deletions logic/ceobe_cookie_logic/src/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,7 @@ pub struct CookieContentReq {

fn empty_change_to_none<'de, D: Deserializer<'de>>(
d: D,
) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
{
) -> Result<Option<String>, D::Error> {
let value = Option::<String>::deserialize(d)?;
Ok(match value.as_deref() {
Some("") | None => None,
Expand Down
5 changes: 5 additions & 0 deletions logic/fetcher_logic/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,18 @@ use std::{
};

pub(super) trait GetOrCreate<K, V> {
#[allow(dead_code)]
fn get_mut_or_create(&mut self, key: K, value: V) -> &mut V;

fn get_mut_or_default(&mut self, key: K) -> &mut V
where
V: Default;

#[allow(dead_code)]
fn get_mut_or_create_with<F: FnOnce() -> V>(
&mut self, key: K, default: F,
) -> &mut V;

fn get_mut_or_try_create_with<F: FnOnce() -> Result<V, E>, E>(
&mut self, key: K, default: F,
) -> Result<&mut V, E>;
Expand Down
5 changes: 1 addition & 4 deletions logic/fetcher_logic/src/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,10 +183,7 @@ impl From<DataSourceForFetcherConfig> for DatasourceWithNameResp {

fn empty_change_to_none<'de, D: Deserializer<'de>>(
d: D,
) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
{
) -> Result<Option<String>, D::Error> {
let value = Option::<String>::deserialize(d)?;
Ok(match value.as_deref() {
Some("") | None => None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use super::{AnnouncementOperate, Column, Entity, Model, OperateResult};
impl AnnouncementOperate<'_, NoConnect> {
pub async fn find_by_filter_raw<'s, 'db: 's>(
filter: impl IntoCondition,
db: &'db (impl ConnectionTrait + StreamTrait + Send + 's),
db: &'db (impl ConnectionTrait + StreamTrait + 's),
) -> OperateResult<impl Stream<Item = Result<Model, DbErr>> + Send + 's>
{
Ok(Entity::find()
Expand All @@ -30,7 +30,7 @@ impl AnnouncementOperate<'_, NoConnect> {

pub async fn find_by_filter_not_delete_raw<'s, 'db: 's>(
filter: impl IntoCondition,
db: &'db (impl ConnectionTrait + StreamTrait + Send + 's),
db: &'db (impl ConnectionTrait + StreamTrait + 's),
) -> OperateResult<impl Stream<Item = Result<Model, DbErr>> + Send + 's>
{
Self::find_by_filter_raw(
Expand Down
28 changes: 28 additions & 0 deletions src/bootstrap/middleware/cors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use axum_starter::{prepare, PrepareMiddlewareEffect};
use http::{HeaderValue, Method};
use tower_http::cors::CorsLayer;

pub trait CorsConfigTrait {
fn allow_origins(&self) -> Vec<HeaderValue>;

fn allow_methods(&self) -> Vec<Method>;
}

#[prepare(PrepareCors)]
pub fn prepare_cors<T: CorsConfigTrait>(cfg: &T) -> CorsMiddleware {
CorsMiddleware(
CorsLayer::new()
.allow_origin(cfg.allow_origins())
.allow_methods(cfg.allow_methods()),
)
}

pub struct CorsMiddleware(CorsLayer);

impl<S> PrepareMiddlewareEffect<S> for CorsMiddleware {
type Middleware = CorsLayer;

fn take(self, _: &mut axum_starter::StateCollector) -> Self::Middleware {
self.0
}
}
1 change: 1 addition & 0 deletions src/bootstrap/middleware/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod cors;
pub mod panic_report;
pub mod tracing_request;
43 changes: 43 additions & 0 deletions src/configs/cors_config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use http::{HeaderValue, Method};
use serde::{Deserialize, Deserializer};

use crate::bootstrap::middleware::cors::CorsConfigTrait;

#[derive(Deserialize, Debug, Clone, Default)]
pub struct CorsConfigImpl {
#[serde(alias = "origins", deserialize_with = "de_origins")]
allow_origins: Vec<HeaderValue>,
#[serde(alias = "methods", deserialize_with = "de_methods")]
allow_methods: Vec<Method>,
}

impl CorsConfigTrait for CorsConfigImpl {
fn allow_origins(&self) -> Vec<HeaderValue> { self.allow_origins.clone() }

fn allow_methods(&self) -> Vec<Method> { self.allow_methods.clone() }
}

fn de_origins<'de, D: Deserializer<'de>>(
de: D,
) -> Result<Vec<HeaderValue>, D::Error> {
let vec = Vec::<String>::deserialize(de)?;
vec.iter().map(|path| path.parse()).try_fold(
Vec::with_capacity(vec.len()),
|mut vec, value| {
vec.push(value.map_err(serde::de::Error::custom)?);
Ok(vec)
},
)
}

fn de_methods<'de, D: Deserializer<'de>>(
de: D,
) -> Result<Vec<Method>, D::Error> {
let vec = Vec::<String>::deserialize(de)?;
vec.iter()
.map(|method| Method::try_from(method.as_str()))
.try_fold(Vec::with_capacity(vec.len()), |mut vec, value| {
vec.push(value.map_err(serde::de::Error::custom)?);
Ok(vec)
})
}
3 changes: 3 additions & 0 deletions src/configs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use self::{
};

pub mod auth_config;
pub mod cors_config;
pub mod first_user;
pub mod http_listen_config;
pub mod logger;
Expand Down Expand Up @@ -66,4 +67,6 @@ pub struct GlobalConfig {
pub mob_push: mob_config::MobPushConfig,
#[serde(alias = "qq")]
pub qq_channel: qq_channel::QqChannelConfig,
#[serde(default)]
pub cors: cors_config::CorsConfigImpl,
}
13 changes: 9 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ use bootstrap::{
service_init::{graceful_shutdown, RouteV1, RouterFallback},
},
middleware::{
panic_report::PrepareCatchPanic,
cors::PrepareCors, panic_report::PrepareCatchPanic,
tracing_request::PrepareRequestTracker,
},
};
use ceobe_qiniu_upload::QiniuUpload;
use configs::{
auth_config::AuthConfig, mob_config::MobPushConfig,
qiniu_secret::QiniuUploadConfig, qq_channel::QqChannelConfig,
resp_result_config::RespResultConfig,
auth_config::AuthConfig, cors_config::CorsConfigImpl,
mob_config::MobPushConfig, qiniu_secret::QiniuUploadConfig,
qq_channel::QqChannelConfig, resp_result_config::RespResultConfig,
schedule_notifier_config::ScheduleNotifierConfig, GlobalConfig,
CONFIG_FILE_JSON, CONFIG_FILE_TOML, CONFIG_FILE_YAML,
};
Expand All @@ -46,6 +46,10 @@ mod router;
mod serves;
mod utils;

#[cfg(not(target_env = "msvc"))]
#[global_allocator]
static GLOBAL: jemallocator::Jemalloc = jemallocator::Jemalloc;

fn main() {
let rt = tokio::runtime::Runtime::new().expect("Init Rt failure");
#[cfg(debug_assertions)]
Expand Down Expand Up @@ -88,6 +92,7 @@ async fn main_task() {
// router
.prepare_route(RouteV1)
.prepare_route(RouterFallback)
.prepare_middleware::<Route, _>(PrepareCors::<_, CorsConfigImpl>)
.prepare_middleware::<Route, _>(
PrepareCatchPanic::<_, QqChannelConfig>,
)
Expand Down
89 changes: 0 additions & 89 deletions src/utils/field_with_struct_trait.rs

This file was deleted.

7 changes: 3 additions & 4 deletions src/utils/mob_verify/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ use http::Request;
use once_cell::sync::OnceCell;
use tracing::warn;

crate::quick_trait! {
pub MobIdConfig{
crate::trait_field!{*mob_header:String=String::from("mob-id")}
}
pub trait MobIdConfig {
fn mob_header(&self) -> String { String::from("mob-id") }
}

static LOCAL_CONFIG: OnceCell<LocalMobIdConfig> = OnceCell::new();

struct LocalMobIdConfig {
Expand Down
1 change: 0 additions & 1 deletion src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
pub mod data_struct;
pub mod field_with_struct_trait;
pub mod mob_verify;
pub mod quick_struct;
pub mod time_format;
Expand Down
8 changes: 3 additions & 5 deletions src/utils/user_authorize/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@ use once_cell::sync::OnceCell;
use sha2::Sha256;
use tracing::warn;

crate::quick_trait! {
pub AuthConfig{
crate::trait_field!{*jwt_key:&[u8]}
crate::trait_field!{*token_header:String=String::from("Token")}
}
pub trait AuthConfig {
fn jwt_key(&self) -> &[u8];
fn token_header(&self) -> String { String::from("Token") }
}
static LOCAL_CONFIG: OnceCell<LocalAuthConfig> = OnceCell::new();

Expand Down

0 comments on commit bbb2a6e

Please sign in to comment.