Checkpoint: Migration to axum

This commit is contained in:
Lennart
2025-06-08 14:10:12 +02:00
parent 790c657b08
commit 95889e3df1
60 changed files with 1476 additions and 2205 deletions

View File

@@ -2,10 +2,10 @@ use axum::body::Body;
use futures_util::future::BoxFuture;
use headers::Allow;
use http::{Method, Request, Response};
use std::{convert::Infallible, str::FromStr, sync::Arc};
use std::{convert::Infallible, str::FromStr};
pub type MethodFunction<Service> =
fn(Arc<Service>, Request<Body>) -> BoxFuture<'static, Result<Response<Body>, Infallible>>;
fn(Service, Request<Body>) -> BoxFuture<'static, Result<Response<Body>, Infallible>>;
pub trait AxumMethods: Sized + Send + Sync + 'static {
#[inline]

View File

@@ -2,6 +2,7 @@ use super::methods::{axum_route_propfind, axum_route_proppatch};
use crate::resource::{ResourceService, axum_methods::AxumMethods};
use axum::{
body::Body,
extract::FromRequestParts,
handler::Handler,
http::{Request, Response},
response::IntoResponse,
@@ -9,16 +10,16 @@ use axum::{
use futures_util::future::BoxFuture;
use headers::HeaderMapExt;
use http::{HeaderValue, StatusCode};
use std::{convert::Infallible, sync::Arc};
use std::convert::Infallible;
use tower::Service;
#[derive(Clone)]
pub struct AxumService<RS: ResourceService + AxumMethods> {
resource_service: Arc<RS>,
resource_service: RS,
}
impl<RS: ResourceService + AxumMethods> AxumService<RS> {
pub fn new(resource_service: Arc<RS>) -> Self {
pub fn new(resource_service: RS) -> Self {
Self { resource_service }
}
}
@@ -27,6 +28,7 @@ impl<RS: ResourceService + AxumMethods + Clone + Send + Sync> Service<Request<Bo
for AxumService<RS>
where
RS::Error: IntoResponse + Send + Sync + 'static,
RS::Principal: FromRequestParts<RS>,
{
type Error = Infallible;
type Response = Response<Body>;

View File

@@ -2,77 +2,15 @@ use crate::Error;
use crate::privileges::UserPrivilege;
use crate::resource::Resource;
use crate::resource::ResourceService;
#[cfg(feature = "axum")]
use axum::extract::{Extension, Path, State};
#[cfg(feature = "axum")]
use axum::extract::{Path, State};
use axum_extra::TypedHeader;
use headers::Header;
use headers::{HeaderValue, IfMatch, IfNoneMatch};
#[cfg(feature = "axum")]
use headers::{IfMatch, IfNoneMatch};
use http::HeaderMap;
use itertools::Itertools;
#[cfg(feature = "axum")]
use std::sync::Arc;
use tracing::instrument;
#[cfg(feature = "actix")]
#[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service))]
pub async fn actix_route_delete<R: ResourceService>(
path: actix_web::web::Path<R::PathComponents>,
req: actix_web::HttpRequest,
principal: R::Principal,
resource_service: actix_web::web::Data<R>,
root_span: tracing_actix_web::RootSpan,
) -> Result<actix_web::HttpResponse, R::Error> {
let no_trash = req
.headers()
.get("X-No-Trashbin")
.map(|val| matches!(val.to_str(), Ok("1")))
.unwrap_or(false);
// This weird conversion stuff is because we want to use the headers library (to be
// framework-agnostic in the future) which uses http==1.0,
// while actix-web still uses http==0.2
let if_match = req
.headers()
.get_all(http_02::header::IF_MATCH)
.map(|val_02| HeaderValue::from_bytes(val_02.as_bytes()).unwrap())
.collect_vec();
let if_none_match = req
.headers()
.get_all(http_02::header::IF_NONE_MATCH)
.map(|val_02| HeaderValue::from_bytes(val_02.as_bytes()).unwrap())
.collect_vec();
let if_match = if if_match.is_empty() {
None
} else {
Some(IfMatch::decode(&mut if_match.iter()).unwrap())
};
let if_none_match = if if_none_match.is_empty() {
None
} else {
Some(IfNoneMatch::decode(&mut if_none_match.iter()).unwrap())
};
route_delete(
&path.into_inner(),
&principal,
resource_service.as_ref(),
no_trash,
if_match,
if_none_match,
)
.await?;
Ok(actix_web::HttpResponse::Ok().body(""))
}
#[cfg(feature = "axum")]
pub(crate) async fn axum_route_delete<R: ResourceService>(
Path(path): Path<R::PathComponents>,
State(resource_service): State<Arc<R>>,
Extension(principal): Extension<R::Principal>,
State(resource_service): State<R>,
principal: R::Principal,
if_match: Option<TypedHeader<IfMatch>>,
if_none_match: Option<TypedHeader<IfNoneMatch>>,
header_map: HeaderMap,
@@ -84,7 +22,7 @@ pub(crate) async fn axum_route_delete<R: ResourceService>(
route_delete(
&path,
&principal,
resource_service.as_ref(),
&resource_service,
no_trash,
if_match.map(|hdr| hdr.0),
if_none_match.map(|hdr| hdr.0),

View File

@@ -2,17 +2,6 @@ mod delete;
mod propfind;
mod proppatch;
#[cfg(feature = "actix")]
pub(crate) use delete::actix_route_delete;
#[cfg(feature = "axum")]
pub(crate) use delete::axum_route_delete;
#[cfg(feature = "actix")]
pub(crate) use propfind::actix_route_propfind;
#[cfg(feature = "axum")]
pub(crate) use propfind::axum_route_propfind;
#[cfg(feature = "actix")]
pub(crate) use proppatch::actix_route_proppatch;
#[cfg(feature = "axum")]
pub(crate) use proppatch::axum_route_proppatch;

View File

@@ -7,47 +7,15 @@ use crate::resource::ResourceService;
use crate::xml::MultistatusElement;
use crate::xml::PropfindElement;
use crate::xml::PropfindType;
#[cfg(feature = "axum")]
use axum::extract::{Extension, OriginalUri, Path, State};
use rustical_xml::PropName;
use rustical_xml::XmlDocument;
use std::sync::Arc;
use tracing::instrument;
#[cfg(feature = "actix")]
#[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service, puri))]
#[allow(clippy::type_complexity)]
pub(crate) async fn actix_route_propfind<R: ResourceService>(
path: ::actix_web::web::Path<R::PathComponents>,
body: String,
req: ::actix_web::HttpRequest,
user: R::Principal,
depth: Depth,
root_span: tracing_actix_web::RootSpan,
resource_service: ::actix_web::web::Data<R>,
puri: ::actix_web::web::Data<R::PrincipalUri>,
) -> Result<
MultistatusElement<<R::Resource as Resource>::Prop, <R::MemberType as Resource>::Prop>,
R::Error,
> {
route_propfind(
&path.into_inner(),
req.path(),
&body,
&user,
&depth,
resource_service.as_ref(),
puri.as_ref(),
)
.await
}
#[cfg(feature = "axum")]
pub(crate) async fn axum_route_propfind<R: ResourceService>(
Path(path): Path<R::PathComponents>,
State(resource_service): State<Arc<R>>,
State(resource_service): State<R>,
depth: Depth,
Extension(principal): Extension<R::Principal>,
principal: R::Principal,
uri: OriginalUri,
Extension(puri): Extension<R::PrincipalUri>,
body: String,
@@ -61,7 +29,7 @@ pub(crate) async fn axum_route_propfind<R: ResourceService>(
&body,
&principal,
&depth,
resource_service.as_ref(),
&resource_service,
&puri,
)
.await
@@ -115,7 +83,7 @@ pub(crate) async fn route_propfind<R: ResourceService>(
}
}
let response = resource.propfind_typed(path, &propfind_self.prop, puri, &principal)?;
let response = resource.propfind_typed(path, &propfind_self.prop, puri, principal)?;
Ok(MultistatusElement {
responses: vec![response],

View File

@@ -1,13 +1,11 @@
use crate::Error;
use crate::privileges::UserPrivilege;
use std::sync::Arc;
use crate::resource::Resource;
use crate::resource::ResourceService;
#[cfg(feature = "axum")]
use axum::extract::{Extension, OriginalUri, Path, State};
use crate::xml::MultistatusElement;
use crate::xml::TagList;
use crate::xml::multistatus::{PropstatElement, PropstatWrapper, ResponseElement};
use axum::extract::{OriginalUri, Path, State};
use http::StatusCode;
use quick_xml::name::Namespace;
use rustical_xml::NamespaceOwned;
@@ -17,7 +15,6 @@ use rustical_xml::XmlDeserialize;
use rustical_xml::XmlDocument;
use rustical_xml::XmlRootTag;
use std::str::FromStr;
use tracing::instrument;
#[derive(XmlDeserialize, Clone, Debug)]
#[xml(untagged)]
@@ -64,46 +61,14 @@ enum Operation<T: XmlDeserialize> {
#[xml(ns = "crate::namespace::NS_DAV")]
struct PropertyupdateElement<T: XmlDeserialize>(#[xml(ty = "untagged", flatten)] Vec<Operation<T>>);
#[cfg(feature = "actix")]
#[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service))]
pub(crate) async fn actix_route_proppatch<R: ResourceService>(
path: actix_web::web::Path<R::PathComponents>,
body: String,
req: actix_web::HttpRequest,
principal: R::Principal,
root_span: tracing_actix_web::RootSpan,
resource_service: actix_web::web::Data<R>,
) -> Result<MultistatusElement<String, String>, R::Error> {
route_proppatch(
&path.into_inner(),
req.path(),
&body,
&principal,
resource_service.as_ref(),
)
.await
}
#[cfg(feature = "axum")]
pub(crate) async fn axum_route_proppatch<R: ResourceService>(
Path(path): Path<R::PathComponents>,
State(resource_service): State<Arc<R>>,
Extension(principal): Extension<R::Principal>,
State(resource_service): State<R>,
principal: R::Principal,
uri: OriginalUri,
body: String,
) -> Result<
MultistatusElement<String, String>,
R::Error,
> {
route_proppatch(
&path,
uri.path(),
&body,
&principal,
resource_service.as_ref(),
)
.await
) -> Result<MultistatusElement<String, String>, R::Error> {
route_proppatch(&path, uri.path(), &body, &principal, &resource_service).await
}
pub(crate) async fn route_proppatch<R: ResourceService>(
@@ -118,10 +83,10 @@ pub(crate) async fn route_proppatch<R: ResourceService>(
// Extract operations
let PropertyupdateElement::<SetPropertyPropWrapperWrapper<<R::Resource as Resource>::Prop>>(
operations,
) = XmlDocument::parse_str(&body).map_err(Error::XmlError)?;
) = XmlDocument::parse_str(body).map_err(Error::XmlError)?;
let mut resource = resource_service.get_resource(path_components).await?;
let privileges = resource.get_user_privileges(&principal)?;
let privileges = resource.get_user_privileges(principal)?;
if !privileges.has(&UserPrivilege::Write) {
return Err(Error::Unauthorized.into());
}

View File

@@ -12,17 +12,13 @@ use rustical_xml::{EnumVariants, NamespaceOwned, PropName, XmlDeserialize, XmlSe
use std::collections::HashSet;
use std::str::FromStr;
#[cfg(feature = "axum")]
mod axum_methods;
#[cfg(feature = "axum")]
mod axum_service;
mod methods;
mod principal_uri;
mod resource_service;
#[cfg(feature = "axum")]
pub use axum_methods::AxumMethods;
#[cfg(feature = "axum")]
pub use axum_service::AxumService;
pub use principal_uri::PrincipalUri;

View File

@@ -1,14 +1,8 @@
#[cfg(feature = "actix")]
use super::methods::{actix_route_delete, actix_route_propfind, actix_route_proppatch};
use super::{PrincipalUri, Resource};
use crate::Principal;
#[cfg(feature = "axum")]
use crate::resource::{AxumMethods, AxumService};
#[cfg(feature = "actix")]
use actix_web::{http::Method, web, web::Data};
use async_trait::async_trait;
use serde::Deserialize;
use std::{str::FromStr, sync::Arc};
#[async_trait]
pub trait ResourceService: Sized + Send + Sync + 'static {
@@ -28,11 +22,6 @@ pub trait ResourceService: Sized + Send + Sync + 'static {
Ok(vec![])
}
async fn test_get_members(&self, _path: &Self::PathComponents) -> Result<String, Self::Error> {
// ) -> Result<Vec<Self::MemberType>, Self::Error> {
Ok("asd".to_string())
}
async fn get_resource(
&self,
_path: &Self::PathComponents,
@@ -54,36 +43,10 @@ pub trait ResourceService: Sized + Send + Sync + 'static {
Err(crate::Error::Unauthorized.into())
}
#[cfg(feature = "actix")]
#[inline]
fn actix_resource(self) -> actix_web::Resource
where
Self::Error: actix_web::ResponseError,
Self::Principal: actix_web::FromRequest,
{
web::resource("")
.app_data(Data::new(self))
.route(
web::method(Method::from_str("PROPFIND").unwrap()).to(actix_route_propfind::<Self>),
)
.route(
web::method(Method::from_str("PROPPATCH").unwrap())
.to(actix_route_proppatch::<Self>),
)
.delete(actix_route_delete::<Self>)
}
#[cfg(feature = "actix")]
fn actix_scope(self) -> actix_web::Scope
where
Self::Error: actix_web::ResponseError,
Self::Principal: actix_web::FromRequest;
#[cfg(feature = "axum")]
fn axum_service(self) -> AxumService<Self>
where
Self: Clone + Send + Sync + AxumMethods,
{
AxumService::new(Arc::new(self))
AxumService::new(self)
}
}