Skip to content

Commit

Permalink
Merge pull request #70 from Marsyew/main
Browse files Browse the repository at this point in the history
fix:change the http error code
  • Loading branch information
hongcha98 authored Nov 21, 2023
2 parents 3771087 + 4cbd262 commit 98c1fd6
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 17 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ mime_guess = "2.0.4"
rust-embed = { version = "8.0.0", features = ["axum-ex"] }
prometheus = "0.13.3"
lazy_static = "1.4.0"
thiserror = "1"
3 changes: 2 additions & 1 deletion src/forward/forward_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ use webrtc::track::track_remote::TrackRemote;

use crate::forward::track_match::{track_match_codec, track_sort};
use crate::media;
use crate::AppError;

use super::rtcp::RtcpMessage;
use super::track_match;
Expand Down Expand Up @@ -156,7 +157,7 @@ impl PeerForwardInternal {
pub(crate) async fn set_anchor(&self, peer: Arc<RTCPeerConnection>) -> Result<()> {
let mut anchor = self.anchor.write().await;
if anchor.is_some() {
return Err(anyhow::anyhow!("anchor is set"));
return Err(AppError::ResourceAlreadyExists("A connection has already been established".to_string()).into());
}
info!("[{}] [anchor] set {}", self.id, peer.get_stats_id());
*anchor = Some(peer);
Expand Down
5 changes: 3 additions & 2 deletions src/forward/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use webrtc::sdp::{MediaDescription, SessionDescription};

use crate::forward::forward_internal::{get_peer_key, PeerForwardInternal};
use crate::{media, metrics};
use crate::AppError;

mod forward_internal;
mod rtcp;
Expand All @@ -38,11 +39,11 @@ impl PeerForward {
offer: RTCSessionDescription,
) -> Result<(RTCSessionDescription, String)> {
if self.internal.anchor_is_some().await {
return Err(anyhow::anyhow!("anchor is set"));
return Err(AppError::ResourceAlreadyExists("A connection has already been established".to_string()).into());
}
let _ = self.anchor_lock.lock().await;
if self.internal.anchor_is_some().await {
return Err(anyhow::anyhow!("anchor is set"));
return Err(AppError::ResourceAlreadyExists("A connection has already been established".to_string()).into());
}
let peer = self
.internal
Expand Down
54 changes: 41 additions & 13 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ use log::info;
use tower_http::services::{ServeDir, ServeFile};
use tower_http::validate_request::ValidateRequestHeaderLayer;
use webrtc::peer_connection::sdp::session_description::RTCSessionDescription;
use thiserror::Error;
use http::header::ToStrError;

use config::IceServer;
use path::manager::Manager;
Expand Down Expand Up @@ -152,7 +154,7 @@ async fn whip(
header: HeaderMap,
uri: Uri,
body: String,
) -> Result<Response<String>, AppError> {
) -> AppResult<Response<String>> {
let content_type = header
.get("Content-Type")
.ok_or(anyhow::anyhow!("Content-Type is required"))?;
Expand All @@ -176,7 +178,7 @@ async fn whep(
header: HeaderMap,
uri: Uri,
body: String,
) -> Result<Response<String>, AppError> {
) -> AppResult<Response<String>> {
let content_type = header
.get("Content-Type")
.ok_or(anyhow::anyhow!("Content-Type is required"))?;
Expand All @@ -199,7 +201,7 @@ async fn add_ice_candidate(
Path(id): Path<String>,
header: HeaderMap,
body: String,
) -> Result<Response<String>, AppError> {
) -> AppResult<Response<String>> {
let content_type = header
.get("Content-Type")
.ok_or(AppError::from(anyhow::anyhow!("Content-Type is required")))?;
Expand All @@ -221,7 +223,7 @@ async fn remove_path_key(
State(state): State<AppState>,
Path(id): Path<String>,
header: HeaderMap,
) -> Result<Response<String>, AppError> {
) -> AppResult<Response<String>> {
let key = header
.get("If-Match")
.ok_or(AppError::from(anyhow::anyhow!("If-Match is required")))?
Expand All @@ -233,7 +235,7 @@ async fn remove_path_key(
.body("".to_string())?)
}

async fn ice_server_config(State(state): State<AppState>) -> Result<Response<String>, AppError> {
async fn ice_server_config(State(state): State<AppState>) -> AppResult<Response<String>> {
let mut builder = Response::builder()
.status(StatusCode::NO_CONTENT)
.header("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PATCH")
Expand Down Expand Up @@ -276,19 +278,45 @@ fn string_encoder(s: &impl ToString) -> String {
s[1..s.len() - 1].to_string()
}

struct AppError(anyhow::Error);
pub type AppResult<T> = Result<T, AppError>;
#[derive(Debug, Error)]
pub enum AppError {
#[error("resource not found:{0}")]
ResourceNotFound(String),
#[error("resource already exists:{0}")]
ResourceAlreadyExists(String),
#[error("internal server error")]
InternalServerError(anyhow::Error),
}

impl IntoResponse for AppError {
fn into_response(self) -> Response {
(StatusCode::INTERNAL_SERVER_ERROR, self.0.to_string()).into_response()
match self {
AppError::ResourceNotFound(err) => (StatusCode::NOT_FOUND, err.to_string()).into_response(),
AppError::InternalServerError(err) => (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()).into_response(),
AppError::ResourceAlreadyExists(err) => (StatusCode::CONFLICT, err.to_string()).into_response(),
}
}
}
impl From<http::Error> for AppError {
fn from(err: http::Error) -> Self {
AppError::InternalServerError(err.into())
}
}
impl From<ToStrError> for AppError {
fn from(err: ToStrError) -> Self {
AppError::InternalServerError(err.into())
}
}

impl From<webrtc::Error> for AppError {
fn from(err: webrtc::Error) -> Self {
AppError::InternalServerError(err.into())
}
}

impl<E> From<E> for AppError
where
E: Into<anyhow::Error>,
{
fn from(err: E) -> Self {
Self(err.into())
impl From<anyhow::Error> for AppError {
fn from(err: anyhow::Error) -> Self {
AppError::InternalServerError(err)
}
}
3 changes: 2 additions & 1 deletion src/path/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use webrtc::{
};

use crate::forward::PeerForward;
use crate::AppError;

#[derive(Clone)]
pub struct Manager {
Expand Down Expand Up @@ -52,7 +53,7 @@ impl Manager {
if let Some(forward) = forward {
forward.add_subscribe(offer).await
} else {
Err(anyhow::anyhow!("resource not exists"))
Err(AppError::ResourceNotFound(("The requested resource not exist,please check the path and try again.").to_string()).into())
}
}

Expand Down

0 comments on commit 98c1fd6

Please sign in to comment.