Remove RwLock around stores, locking shall be the responsibility of the store implementation

This commit is contained in:
Lennart
2024-10-27 15:36:49 +01:00
parent df8790f46d
commit 858f43de67
31 changed files with 119 additions and 236 deletions

View File

@@ -5,7 +5,6 @@ use rustical_store::auth::User;
use rustical_store::model::Calendar; use rustical_store::model::Calendar;
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
#[derive(Deserialize, Serialize, Clone, Debug)] #[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
@@ -57,7 +56,7 @@ pub async fn route_mkcalendar<C: CalendarStore + ?Sized>(
path: Path<(String, String)>, path: Path<(String, String)>,
body: String, body: String,
user: User, user: User,
store: Data<RwLock<C>>, store: Data<C>,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
let (principal, cal_id) = path.into_inner(); let (principal, cal_id) = path.into_inner();
if principal != user.id { if principal != user.id {
@@ -79,7 +78,7 @@ pub async fn route_mkcalendar<C: CalendarStore + ?Sized>(
synctoken: 0, synctoken: 0,
}; };
match store.read().await.get_calendar(&principal, &cal_id).await { match store.get_calendar(&principal, &cal_id).await {
Err(rustical_store::Error::NotFound) => { Err(rustical_store::Error::NotFound) => {
// No conflict, no worries // No conflict, no worries
} }
@@ -93,7 +92,7 @@ pub async fn route_mkcalendar<C: CalendarStore + ?Sized>(
} }
} }
match store.write().await.insert_calendar(calendar).await { match store.insert_calendar(calendar).await {
// The spec says we should return a mkcalendar-response but I don't know what goes into it. // The spec says we should return a mkcalendar-response but I don't know what goes into it.
// However, it works without one but breaks on iPadOS when using an empty one :) // However, it works without one but breaks on iPadOS when using an empty one :)
Ok(()) => Ok(HttpResponse::Created() Ok(()) => Ok(HttpResponse::Created()

View File

@@ -18,7 +18,6 @@ use rustical_dav::{
}; };
use rustical_store::{model::object::CalendarObject, CalendarStore}; use rustical_store::{model::object::CalendarObject, CalendarStore};
use serde::Deserialize; use serde::Deserialize;
use tokio::sync::RwLock;
#[derive(Deserialize, Clone, Debug)] #[derive(Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
@@ -35,7 +34,7 @@ pub async fn get_objects_calendar_multiget<C: CalendarStore + ?Sized>(
principal_url: &str, principal_url: &str,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
store: &RwLock<C>, store: &C,
) -> Result<(Vec<CalendarObject>, Vec<String>), Error> { ) -> Result<(Vec<CalendarObject>, Vec<String>), Error> {
let resource_def = let resource_def =
ResourceDef::prefix(principal_url).join(&ResourceDef::new("/{cal_id}/{object_id}")); ResourceDef::prefix(principal_url).join(&ResourceDef::new("/{cal_id}/{object_id}"));
@@ -43,7 +42,6 @@ pub async fn get_objects_calendar_multiget<C: CalendarStore + ?Sized>(
let mut result = vec![]; let mut result = vec![];
let mut not_found = vec![]; let mut not_found = vec![];
let store = store.read().await;
for href in &cal_query.href { for href in &cal_query.href {
let mut path = Path::new(href.as_str()); let mut path = Path::new(href.as_str());
if !resource_def.capture_match_info(&mut path) { if !resource_def.capture_match_info(&mut path) {
@@ -69,7 +67,7 @@ pub async fn handle_calendar_multiget<C: CalendarStore + ?Sized>(
req: HttpRequest, req: HttpRequest,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
cal_store: &RwLock<C>, cal_store: &C,
) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> { ) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> {
let principal_url = PrincipalResource::get_url(req.resource_map(), vec![principal]).unwrap(); let principal_url = PrincipalResource::get_url(req.resource_map(), vec![principal]).unwrap();
let (objects, not_found) = let (objects, not_found) =

View File

@@ -7,7 +7,6 @@ use rustical_dav::{
}; };
use rustical_store::{model::object::CalendarObject, CalendarStore}; use rustical_store::{model::object::CalendarObject, CalendarStore};
use serde::Deserialize; use serde::Deserialize;
use tokio::sync::RwLock;
use crate::{ use crate::{
calendar_object::resource::{CalendarObjectProp, CalendarObjectResource}, calendar_object::resource::{CalendarObjectProp, CalendarObjectResource},
@@ -195,9 +194,9 @@ pub async fn get_objects_calendar_query<C: CalendarStore + ?Sized>(
cal_query: &CalendarQueryRequest, cal_query: &CalendarQueryRequest,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
store: &RwLock<C>, store: &C,
) -> Result<Vec<CalendarObject>, Error> { ) -> Result<Vec<CalendarObject>, Error> {
let mut objects = store.read().await.get_objects(principal, cal_id).await?; let mut objects = store.get_objects(principal, cal_id).await?;
if let Some(filter) = &cal_query.filter { if let Some(filter) = &cal_query.filter {
objects.retain(|object| filter.matches(object)); objects.retain(|object| filter.matches(object));
} }
@@ -209,7 +208,7 @@ pub async fn handle_calendar_query<C: CalendarStore + ?Sized>(
req: HttpRequest, req: HttpRequest,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
cal_store: &RwLock<C>, cal_store: &C,
) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> { ) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> {
let objects = get_objects_calendar_query(&cal_query, principal, cal_id, cal_store).await?; let objects = get_objects_calendar_query(&cal_query, principal, cal_id, cal_store).await?;

View File

@@ -8,7 +8,6 @@ use calendar_query::{handle_calendar_query, CalendarQueryRequest};
use rustical_store::{auth::User, CalendarStore}; use rustical_store::{auth::User, CalendarStore};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sync_collection::{handle_sync_collection, SyncCollectionRequest}; use sync_collection::{handle_sync_collection, SyncCollectionRequest};
use tokio::sync::RwLock;
use tracing::instrument; use tracing::instrument;
mod calendar_multiget; mod calendar_multiget;
@@ -37,7 +36,7 @@ pub async fn route_report_calendar<C: CalendarStore + ?Sized>(
body: String, body: String,
user: User, user: User,
req: HttpRequest, req: HttpRequest,
cal_store: Data<RwLock<C>>, cal_store: Data<C>,
) -> Result<impl Responder, Error> { ) -> Result<impl Responder, Error> {
let (principal, cal_id) = path.into_inner(); let (principal, cal_id) = path.into_inner();
if principal != user.id { if principal != user.id {
@@ -48,13 +47,21 @@ pub async fn route_report_calendar<C: CalendarStore + ?Sized>(
Ok(match request.clone() { Ok(match request.clone() {
ReportRequest::CalendarQuery(cal_query) => { ReportRequest::CalendarQuery(cal_query) => {
handle_calendar_query(cal_query, req, &principal, &cal_id, &cal_store).await? handle_calendar_query(cal_query, req, &principal, &cal_id, cal_store.as_ref()).await?
} }
ReportRequest::CalendarMultiget(cal_multiget) => { ReportRequest::CalendarMultiget(cal_multiget) => {
handle_calendar_multiget(cal_multiget, req, &principal, &cal_id, &cal_store).await? handle_calendar_multiget(cal_multiget, req, &principal, &cal_id, cal_store.as_ref())
.await?
} }
ReportRequest::SyncCollection(sync_collection) => { ReportRequest::SyncCollection(sync_collection) => {
handle_sync_collection(sync_collection, req, &principal, &cal_id, &cal_store).await? handle_sync_collection(
sync_collection,
req,
&principal,
&cal_id,
cal_store.as_ref(),
)
.await?
} }
}) })
} }

View File

@@ -12,7 +12,6 @@ use rustical_store::{
CalendarStore, CalendarStore,
}; };
use serde::Deserialize; use serde::Deserialize;
use tokio::sync::RwLock;
use crate::{ use crate::{
calendar_object::resource::{CalendarObjectProp, CalendarObjectResource}, calendar_object::resource::{CalendarObjectProp, CalendarObjectResource},
@@ -47,7 +46,7 @@ pub async fn handle_sync_collection<C: CalendarStore + ?Sized>(
req: HttpRequest, req: HttpRequest,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
cal_store: &RwLock<C>, cal_store: &C,
) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> { ) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> {
let props = match sync_collection.prop { let props = match sync_collection.prop {
PropfindType::Allprop => { PropfindType::Allprop => {
@@ -62,8 +61,6 @@ pub async fn handle_sync_collection<C: CalendarStore + ?Sized>(
let old_synctoken = parse_synctoken(&sync_collection.sync_token).unwrap_or(0); let old_synctoken = parse_synctoken(&sync_collection.sync_token).unwrap_or(0);
let (new_objects, deleted_objects, new_synctoken) = cal_store let (new_objects, deleted_objects, new_synctoken) = cal_store
.read()
.await
.sync_changes(principal, cal_id, old_synctoken) .sync_changes(principal, cal_id, old_synctoken)
.await?; .await?;

View File

@@ -21,10 +21,9 @@ use serde::{Deserialize, Serialize};
use std::str::FromStr; use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
use strum::{EnumString, VariantNames}; use strum::{EnumString, VariantNames};
use tokio::sync::RwLock;
pub struct CalendarResourceService<C: CalendarStore + ?Sized> { pub struct CalendarResourceService<C: CalendarStore + ?Sized> {
pub cal_store: Arc<RwLock<C>>, pub cal_store: Arc<C>,
pub path: String, pub path: String,
pub principal: String, pub principal: String,
pub calendar_id: String, pub calendar_id: String,
@@ -261,8 +260,6 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResourceService<C> {
} }
let calendar = self let calendar = self
.cal_store .cal_store
.read()
.await
.get_calendar(&self.principal, &self.calendar_id) .get_calendar(&self.principal, &self.calendar_id)
.await .await
.map_err(|_e| Error::NotFound)?; .map_err(|_e| Error::NotFound)?;
@@ -275,8 +272,6 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResourceService<C> {
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> { ) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
Ok(self Ok(self
.cal_store .cal_store
.read()
.await
.get_objects(&self.principal, &self.calendar_id) .get_objects(&self.principal, &self.calendar_id)
.await? .await?
.into_iter() .into_iter()
@@ -298,7 +293,7 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResourceService<C> {
path_components: Self::PathComponents, path_components: Self::PathComponents,
) -> Result<Self, Self::Error> { ) -> Result<Self, Self::Error> {
let cal_store = req let cal_store = req
.app_data::<Data<RwLock<C>>>() .app_data::<Data<C>>()
.expect("no calendar store in app_data!") .expect("no calendar store in app_data!")
.clone() .clone()
.into_inner(); .into_inner();
@@ -313,8 +308,6 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResourceService<C> {
async fn save_resource(&self, file: Self::Resource) -> Result<(), Self::Error> { async fn save_resource(&self, file: Self::Resource) -> Result<(), Self::Error> {
self.cal_store self.cal_store
.write()
.await
.update_calendar( .update_calendar(
self.principal.to_owned(), self.principal.to_owned(),
self.calendar_id.to_owned(), self.calendar_id.to_owned(),
@@ -326,8 +319,6 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResourceService<C> {
async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> { async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> {
self.cal_store self.cal_store
.write()
.await
.delete_calendar(&self.principal, &self.calendar_id, use_trashbin) .delete_calendar(&self.principal, &self.calendar_id, use_trashbin)
.await?; .await?;
Ok(()) Ok(())

View File

@@ -7,7 +7,6 @@ use actix_web::HttpResponse;
use rustical_store::auth::User; use rustical_store::auth::User;
use rustical_store::model::CalendarObject; use rustical_store::model::CalendarObject;
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
use tokio::sync::RwLock;
use tracing::instrument; use tracing::instrument;
use tracing_actix_web::RootSpan; use tracing_actix_web::RootSpan;
@@ -16,7 +15,7 @@ use super::resource::CalendarObjectPathComponents;
#[instrument(parent = root_span.id(), skip(store, root_span))] #[instrument(parent = root_span.id(), skip(store, root_span))]
pub async fn get_event<C: CalendarStore + ?Sized>( pub async fn get_event<C: CalendarStore + ?Sized>(
path: Path<CalendarObjectPathComponents>, path: Path<CalendarObjectPathComponents>,
store: Data<RwLock<C>>, store: Data<C>,
user: User, user: User,
root_span: RootSpan, root_span: RootSpan,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
@@ -30,16 +29,12 @@ pub async fn get_event<C: CalendarStore + ?Sized>(
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
} }
let calendar = store.read().await.get_calendar(&principal, &cal_id).await?; let calendar = store.get_calendar(&principal, &cal_id).await?;
if user.id != calendar.principal { if user.id != calendar.principal {
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
} }
let event = store let event = store.get_object(&principal, &cal_id, &object_id).await?;
.read()
.await
.get_object(&principal, &cal_id, &object_id)
.await?;
Ok(HttpResponse::Ok() Ok(HttpResponse::Ok()
.insert_header(("ETag", event.get_etag())) .insert_header(("ETag", event.get_etag()))
@@ -50,7 +45,7 @@ pub async fn get_event<C: CalendarStore + ?Sized>(
#[instrument(parent = root_span.id(), skip(store, req, root_span))] #[instrument(parent = root_span.id(), skip(store, req, root_span))]
pub async fn put_event<C: CalendarStore + ?Sized>( pub async fn put_event<C: CalendarStore + ?Sized>(
path: Path<CalendarObjectPathComponents>, path: Path<CalendarObjectPathComponents>,
store: Data<RwLock<C>>, store: Data<C>,
body: String, body: String,
user: User, user: User,
req: HttpRequest, req: HttpRequest,
@@ -66,37 +61,16 @@ pub async fn put_event<C: CalendarStore + ?Sized>(
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
} }
let calendar = store.read().await.get_calendar(&principal, &cal_id).await?;
if user.id != calendar.principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
// TODO: implement If-Match // TODO: implement If-Match
// //
let mut store_write = store.write().await;
if Some(&HeaderValue::from_static("*")) == req.headers().get(header::IF_NONE_MATCH) { let overwrite =
// Only write if not existing Some(&HeaderValue::from_static("*")) != req.headers().get(header::IF_NONE_MATCH);
match store_write
.get_object(&principal, &cal_id, &object_id)
.await
{
Ok(_) => {
// Conflict
return Ok(HttpResponse::Conflict().body("Resource with this URI already exists"));
}
Err(rustical_store::Error::NotFound) => {
// Path unused, we can proceed
}
Err(err) => {
// Some unknown error :(
return Err(err.into());
}
}
}
let object = CalendarObject::from_ics(object_id, body)?; let object = CalendarObject::from_ics(object_id, body)?;
store_write.put_object(principal, cal_id, object).await?; store
.put_object(principal, cal_id, object, overwrite)
.await?;
Ok(HttpResponse::Created().body("")) Ok(HttpResponse::Created().body(""))
} }

View File

@@ -1,3 +1,4 @@
use super::methods::{get_event, put_event};
use crate::Error; use crate::Error;
use actix_web::{dev::ResourceMap, web::Data, HttpRequest}; use actix_web::{dev::ResourceMap, web::Data, HttpRequest};
use async_trait::async_trait; use async_trait::async_trait;
@@ -8,12 +9,9 @@ use rustical_store::CalendarStore;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use strum::{EnumString, VariantNames}; use strum::{EnumString, VariantNames};
use tokio::sync::RwLock;
use super::methods::{get_event, put_event};
pub struct CalendarObjectResourceService<C: CalendarStore + ?Sized> { pub struct CalendarObjectResourceService<C: CalendarStore + ?Sized> {
pub cal_store: Arc<RwLock<C>>, pub cal_store: Arc<C>,
pub path: String, pub path: String,
pub principal: String, pub principal: String,
pub cal_id: String, pub cal_id: String,
@@ -121,7 +119,7 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarObjectResourceServic
} = path_components; } = path_components;
let cal_store = req let cal_store = req
.app_data::<Data<RwLock<C>>>() .app_data::<Data<C>>()
.expect("no calendar store in app_data!") .expect("no calendar store in app_data!")
.clone() .clone()
.into_inner(); .into_inner();
@@ -141,8 +139,6 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarObjectResourceServic
} }
let event = self let event = self
.cal_store .cal_store
.read()
.await
.get_object(&self.principal, &self.cal_id, &self.object_id) .get_object(&self.principal, &self.cal_id, &self.object_id)
.await?; .await?;
Ok(event.into()) Ok(event.into())
@@ -154,8 +150,6 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarObjectResourceServic
async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> { async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> {
self.cal_store self.cal_store
.write()
.await
.delete_object(&self.principal, &self.cal_id, &self.object_id, use_trashbin) .delete_object(&self.principal, &self.cal_id, &self.object_id, use_trashbin)
.await?; .await?;
Ok(()) Ok(())

View File

@@ -29,7 +29,7 @@ impl actix_web::ResponseError for Error {
match self { match self {
Error::StoreError(err) => match err { Error::StoreError(err) => match err {
rustical_store::Error::NotFound => StatusCode::NOT_FOUND, rustical_store::Error::NotFound => StatusCode::NOT_FOUND,
rustical_store::Error::InvalidIcs(_) => StatusCode::BAD_REQUEST, rustical_store::Error::InvalidData(_) => StatusCode::BAD_REQUEST,
_ => StatusCode::INTERNAL_SERVER_ERROR, _ => StatusCode::INTERNAL_SERVER_ERROR,
}, },
Error::DavError(err) => err.status_code(), Error::DavError(err) => err.status_code(),

View File

@@ -11,7 +11,6 @@ use rustical_dav::resource::ResourceService;
use rustical_store::auth::{AuthenticationMiddleware, AuthenticationProvider}; use rustical_store::auth::{AuthenticationMiddleware, AuthenticationProvider};
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::RwLock;
pub mod calendar; pub mod calendar;
pub mod calendar_object; pub mod calendar_object;
@@ -28,7 +27,7 @@ pub fn configure_well_known(cfg: &mut web::ServiceConfig, caldav_root: String) {
pub fn configure_dav<AP: AuthenticationProvider, C: CalendarStore + ?Sized>( pub fn configure_dav<AP: AuthenticationProvider, C: CalendarStore + ?Sized>(
cfg: &mut web::ServiceConfig, cfg: &mut web::ServiceConfig,
auth_provider: Arc<AP>, auth_provider: Arc<AP>,
store: Arc<RwLock<C>>, store: Arc<C>,
) { ) {
cfg.service( cfg.service(
web::scope("") web::scope("")

View File

@@ -1,3 +1,4 @@
use crate::calendar::resource::CalendarResource;
use crate::Error; use crate::Error;
use actix_web::dev::ResourceMap; use actix_web::dev::ResourceMap;
use actix_web::web::Data; use actix_web::web::Data;
@@ -9,13 +10,10 @@ use rustical_store::CalendarStore;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use strum::{EnumString, VariantNames}; use strum::{EnumString, VariantNames};
use tokio::sync::RwLock;
use crate::calendar::resource::CalendarResource;
pub struct PrincipalResourceService<C: CalendarStore + ?Sized> { pub struct PrincipalResourceService<C: CalendarStore + ?Sized> {
principal: String, principal: String,
cal_store: Arc<RwLock<C>>, cal_store: Arc<C>,
} }
#[derive(Clone)] #[derive(Clone)]
@@ -113,7 +111,7 @@ impl<C: CalendarStore + ?Sized> ResourceService for PrincipalResourceService<C>
(principal,): Self::PathComponents, (principal,): Self::PathComponents,
) -> Result<Self, Self::Error> { ) -> Result<Self, Self::Error> {
let cal_store = req let cal_store = req
.app_data::<Data<RwLock<C>>>() .app_data::<Data<C>>()
.expect("no calendar store in app_data!") .expect("no calendar store in app_data!")
.clone() .clone()
.into_inner(); .into_inner();
@@ -137,12 +135,7 @@ impl<C: CalendarStore + ?Sized> ResourceService for PrincipalResourceService<C>
&self, &self,
rmap: &ResourceMap, rmap: &ResourceMap,
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> { ) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
let calendars = self let calendars = self.cal_store.get_calendars(&self.principal).await?;
.cal_store
.read()
.await
.get_calendars(&self.principal)
.await?;
Ok(calendars Ok(calendars
.into_iter() .into_iter()
.map(|cal| { .map(|cal| {

View File

@@ -8,14 +8,13 @@ use actix_web::HttpResponse;
use rustical_store::auth::User; use rustical_store::auth::User;
use rustical_store::model::AddressObject; use rustical_store::model::AddressObject;
use rustical_store::AddressbookStore; use rustical_store::AddressbookStore;
use tokio::sync::RwLock;
use tracing::instrument; use tracing::instrument;
use tracing_actix_web::RootSpan; use tracing_actix_web::RootSpan;
#[instrument(parent = root_span.id(), skip(store, root_span))] #[instrument(parent = root_span.id(), skip(store, root_span))]
pub async fn get_object<AS: AddressbookStore + ?Sized>( pub async fn get_object<AS: AddressbookStore + ?Sized>(
path: Path<AddressObjectPathComponents>, path: Path<AddressObjectPathComponents>,
store: Data<RwLock<AS>>, store: Data<AS>,
user: User, user: User,
root_span: RootSpan, root_span: RootSpan,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
@@ -29,20 +28,12 @@ pub async fn get_object<AS: AddressbookStore + ?Sized>(
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
} }
let addressbook = store let addressbook = store.get_addressbook(&principal, &cal_id).await?;
.read()
.await
.get_addressbook(&principal, &cal_id)
.await?;
if user.id != addressbook.principal { if user.id != addressbook.principal {
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
} }
let object = store let object = store.get_object(&principal, &cal_id, &object_id).await?;
.read()
.await
.get_object(&principal, &cal_id, &object_id)
.await?;
Ok(HttpResponse::Ok() Ok(HttpResponse::Ok()
.insert_header(("ETag", object.get_etag())) .insert_header(("ETag", object.get_etag()))
@@ -53,7 +44,7 @@ pub async fn get_object<AS: AddressbookStore + ?Sized>(
#[instrument(parent = root_span.id(), skip(store, req, root_span))] #[instrument(parent = root_span.id(), skip(store, req, root_span))]
pub async fn put_object<AS: AddressbookStore + ?Sized>( pub async fn put_object<AS: AddressbookStore + ?Sized>(
path: Path<AddressObjectPathComponents>, path: Path<AddressObjectPathComponents>,
store: Data<RwLock<AS>>, store: Data<AS>,
body: String, body: String,
user: User, user: User,
req: HttpRequest, req: HttpRequest,
@@ -69,42 +60,15 @@ pub async fn put_object<AS: AddressbookStore + ?Sized>(
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
} }
let addressbook = store
.read()
.await
.get_addressbook(&principal, &addressbook_id)
.await?;
if user.id != addressbook.principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
// TODO: implement If-Match // TODO: implement If-Match
// //
let mut store_write = store.write().await;
if Some(&HeaderValue::from_static("*")) == req.headers().get(header::IF_NONE_MATCH) { let overwrite =
// Only write if not existing Some(&HeaderValue::from_static("*")) != req.headers().get(header::IF_NONE_MATCH);
match store_write
.get_object(&principal, &addressbook_id, &object_id)
.await
{
Ok(_) => {
// Conflict
return Ok(HttpResponse::Conflict().body("Resource with this URI already exists"));
}
Err(rustical_store::Error::NotFound) => {
// Path unused, we can proceed
}
Err(err) => {
// Some unknown error :(
return Err(err.into());
}
}
}
let object = AddressObject::from_vcf(object_id, body)?; let object = AddressObject::from_vcf(object_id, body)?;
store_write store
.put_object(principal, addressbook_id, object) .put_object(principal, addressbook_id, object, overwrite)
.await?; .await?;
Ok(HttpResponse::Created().body("")) Ok(HttpResponse::Created().body(""))

View File

@@ -7,12 +7,11 @@ use rustical_store::{model::AddressObject, AddressbookStore};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use strum::{EnumString, VariantNames}; use strum::{EnumString, VariantNames};
use tokio::sync::RwLock;
use super::methods::{get_object, put_object}; use super::methods::{get_object, put_object};
pub struct AddressObjectResourceService<AS: AddressbookStore + ?Sized> { pub struct AddressObjectResourceService<AS: AddressbookStore + ?Sized> {
pub addr_store: Arc<RwLock<AS>>, pub addr_store: Arc<AS>,
pub path: String, pub path: String,
pub principal: String, pub principal: String,
pub cal_id: String, pub cal_id: String,
@@ -120,7 +119,7 @@ impl<AS: AddressbookStore + ?Sized> ResourceService for AddressObjectResourceSer
} = path_components; } = path_components;
let addr_store = req let addr_store = req
.app_data::<Data<RwLock<AS>>>() .app_data::<Data<AS>>()
.expect("no addressbook store in app_data!") .expect("no addressbook store in app_data!")
.clone() .clone()
.into_inner(); .into_inner();
@@ -140,8 +139,6 @@ impl<AS: AddressbookStore + ?Sized> ResourceService for AddressObjectResourceSer
} }
let event = self let event = self
.addr_store .addr_store
.read()
.await
.get_object(&self.principal, &self.cal_id, &self.object_id) .get_object(&self.principal, &self.cal_id, &self.object_id)
.await?; .await?;
Ok(event.into()) Ok(event.into())
@@ -153,8 +150,6 @@ impl<AS: AddressbookStore + ?Sized> ResourceService for AddressObjectResourceSer
async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> { async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> {
self.addr_store self.addr_store
.write()
.await
.delete_object(&self.principal, &self.cal_id, &self.object_id, use_trashbin) .delete_object(&self.principal, &self.cal_id, &self.object_id, use_trashbin)
.await?; .await?;
Ok(()) Ok(())

View File

@@ -4,7 +4,6 @@ use actix_web::{web::Data, HttpResponse};
use rustical_store::model::Addressbook; use rustical_store::model::Addressbook;
use rustical_store::{auth::User, AddressbookStore}; use rustical_store::{auth::User, AddressbookStore};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
#[derive(Deserialize, Serialize, Clone, Debug)] #[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
@@ -38,7 +37,7 @@ pub async fn route_mkcol<AS: AddressbookStore + ?Sized>(
path: Path<(String, String)>, path: Path<(String, String)>,
body: String, body: String,
user: User, user: User,
store: Data<RwLock<AS>>, store: Data<AS>,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
let (principal, addressbook_id) = path.into_inner(); let (principal, addressbook_id) = path.into_inner();
if principal != user.id { if principal != user.id {
@@ -57,12 +56,7 @@ pub async fn route_mkcol<AS: AddressbookStore + ?Sized>(
synctoken: 0, synctoken: 0,
}; };
match store match store.get_addressbook(&principal, &addressbook_id).await {
.read()
.await
.get_addressbook(&principal, &addressbook_id)
.await
{
Err(rustical_store::Error::NotFound) => { Err(rustical_store::Error::NotFound) => {
// No conflict, no worries // No conflict, no worries
} }
@@ -76,7 +70,7 @@ pub async fn route_mkcol<AS: AddressbookStore + ?Sized>(
} }
} }
match store.write().await.insert_addressbook(addressbook).await { match store.insert_addressbook(addressbook).await {
// TODO: The spec says we should return a mkcol-response. // TODO: The spec says we should return a mkcol-response.
// However, it works without one but breaks on iPadOS when using an empty one :) // However, it works without one but breaks on iPadOS when using an empty one :)
Ok(()) => Ok(HttpResponse::Created() Ok(()) => Ok(HttpResponse::Created()

View File

@@ -18,7 +18,6 @@ use rustical_dav::{
}; };
use rustical_store::{model::AddressObject, AddressbookStore}; use rustical_store::{model::AddressObject, AddressbookStore};
use serde::Deserialize; use serde::Deserialize;
use tokio::sync::RwLock;
#[derive(Deserialize, Clone, Debug)] #[derive(Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
@@ -34,7 +33,7 @@ pub async fn get_objects_addressbook_multiget<AS: AddressbookStore + ?Sized>(
principal_url: &str, principal_url: &str,
principal: &str, principal: &str,
addressbook_id: &str, addressbook_id: &str,
store: &RwLock<AS>, store: &AS,
) -> Result<(Vec<AddressObject>, Vec<String>), Error> { ) -> Result<(Vec<AddressObject>, Vec<String>), Error> {
let resource_def = let resource_def =
ResourceDef::prefix(principal_url).join(&ResourceDef::new("/{addressbook_id}/{object_id}")); ResourceDef::prefix(principal_url).join(&ResourceDef::new("/{addressbook_id}/{object_id}"));
@@ -42,7 +41,6 @@ pub async fn get_objects_addressbook_multiget<AS: AddressbookStore + ?Sized>(
let mut result = vec![]; let mut result = vec![];
let mut not_found = vec![]; let mut not_found = vec![];
let store = store.read().await;
for href in &addressbook_multiget.href { for href in &addressbook_multiget.href {
let mut path = Path::new(href.as_str()); let mut path = Path::new(href.as_str());
if !resource_def.capture_match_info(&mut path) { if !resource_def.capture_match_info(&mut path) {
@@ -68,7 +66,7 @@ pub async fn handle_addressbook_multiget<AS: AddressbookStore + ?Sized>(
req: HttpRequest, req: HttpRequest,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
addr_store: &RwLock<AS>, addr_store: &AS,
) -> Result<MultistatusElement<PropstatWrapper<AddressObjectProp>, String>, Error> { ) -> Result<MultistatusElement<PropstatWrapper<AddressObjectProp>, String>, Error> {
let principal_url = PrincipalResource::get_url(req.resource_map(), vec![principal]).unwrap(); let principal_url = PrincipalResource::get_url(req.resource_map(), vec![principal]).unwrap();
let (objects, not_found) = get_objects_addressbook_multiget( let (objects, not_found) = get_objects_addressbook_multiget(

View File

@@ -7,7 +7,6 @@ use addressbook_multiget::{handle_addressbook_multiget, AddressbookMultigetReque
use rustical_store::{auth::User, AddressbookStore}; use rustical_store::{auth::User, AddressbookStore};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sync_collection::{handle_sync_collection, SyncCollectionRequest}; use sync_collection::{handle_sync_collection, SyncCollectionRequest};
use tokio::sync::RwLock;
use tracing::instrument; use tracing::instrument;
mod addressbook_multiget; mod addressbook_multiget;
@@ -34,7 +33,7 @@ pub async fn route_report_addressbook<AS: AddressbookStore + ?Sized>(
body: String, body: String,
user: User, user: User,
req: HttpRequest, req: HttpRequest,
addr_store: Data<RwLock<AS>>, addr_store: Data<AS>,
) -> Result<impl Responder, Error> { ) -> Result<impl Responder, Error> {
let (principal, addressbook_id) = path.into_inner(); let (principal, addressbook_id) = path.into_inner();
if principal != user.id { if principal != user.id {
@@ -50,7 +49,7 @@ pub async fn route_report_addressbook<AS: AddressbookStore + ?Sized>(
req, req,
&principal, &principal,
&addressbook_id, &addressbook_id,
&addr_store, addr_store.as_ref(),
) )
.await? .await?
} }
@@ -60,7 +59,7 @@ pub async fn route_report_addressbook<AS: AddressbookStore + ?Sized>(
req, req,
&principal, &principal,
&addressbook_id, &addressbook_id,
&addr_store, addr_store.as_ref(),
) )
.await? .await?
} }

View File

@@ -16,7 +16,6 @@ use rustical_store::{
AddressbookStore, AddressbookStore,
}; };
use serde::Deserialize; use serde::Deserialize;
use tokio::sync::RwLock;
#[derive(Deserialize, Clone, Debug)] #[derive(Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
@@ -45,7 +44,7 @@ pub async fn handle_sync_collection<AS: AddressbookStore + ?Sized>(
req: HttpRequest, req: HttpRequest,
principal: &str, principal: &str,
addressbook_id: &str, addressbook_id: &str,
addr_store: &RwLock<AS>, addr_store: &AS,
) -> Result<MultistatusElement<PropstatWrapper<AddressObjectProp>, String>, Error> { ) -> Result<MultistatusElement<PropstatWrapper<AddressObjectProp>, String>, Error> {
let props = match sync_collection.prop { let props = match sync_collection.prop {
PropfindType::Allprop => { PropfindType::Allprop => {
@@ -60,8 +59,6 @@ pub async fn handle_sync_collection<AS: AddressbookStore + ?Sized>(
let old_synctoken = parse_synctoken(&sync_collection.sync_token).unwrap_or(0); let old_synctoken = parse_synctoken(&sync_collection.sync_token).unwrap_or(0);
let (new_objects, deleted_objects, new_synctoken) = addr_store let (new_objects, deleted_objects, new_synctoken) = addr_store
.read()
.await
.sync_changes(principal, addressbook_id, old_synctoken) .sync_changes(principal, addressbook_id, old_synctoken)
.await?; .await?;

View File

@@ -18,10 +18,9 @@ use serde::{Deserialize, Serialize};
use std::str::FromStr; use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
use strum::{EnumString, VariantNames}; use strum::{EnumString, VariantNames};
use tokio::sync::RwLock;
pub struct AddressbookResourceService<AS: AddressbookStore + ?Sized> { pub struct AddressbookResourceService<AS: AddressbookStore + ?Sized> {
pub addr_store: Arc<RwLock<AS>>, pub addr_store: Arc<AS>,
pub path: String, pub path: String,
pub principal: String, pub principal: String,
pub addressbook_id: String, pub addressbook_id: String,
@@ -204,8 +203,6 @@ impl<AS: AddressbookStore + ?Sized> ResourceService for AddressbookResourceServi
} }
let addressbook = self let addressbook = self
.addr_store .addr_store
.read()
.await
.get_addressbook(&self.principal, &self.addressbook_id) .get_addressbook(&self.principal, &self.addressbook_id)
.await .await
.map_err(|_e| Error::NotFound)?; .map_err(|_e| Error::NotFound)?;
@@ -218,8 +215,6 @@ impl<AS: AddressbookStore + ?Sized> ResourceService for AddressbookResourceServi
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> { ) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
Ok(self Ok(self
.addr_store .addr_store
.read()
.await
.get_objects(&self.principal, &self.addressbook_id) .get_objects(&self.principal, &self.addressbook_id)
.await? .await?
.into_iter() .into_iter()
@@ -241,7 +236,7 @@ impl<AS: AddressbookStore + ?Sized> ResourceService for AddressbookResourceServi
path_components: Self::PathComponents, path_components: Self::PathComponents,
) -> Result<Self, Self::Error> { ) -> Result<Self, Self::Error> {
let addr_store = req let addr_store = req
.app_data::<Data<RwLock<AS>>>() .app_data::<Data<AS>>()
.expect("no addressbook store in app_data!") .expect("no addressbook store in app_data!")
.clone() .clone()
.into_inner(); .into_inner();
@@ -256,8 +251,6 @@ impl<AS: AddressbookStore + ?Sized> ResourceService for AddressbookResourceServi
async fn save_resource(&self, file: Self::Resource) -> Result<(), Self::Error> { async fn save_resource(&self, file: Self::Resource) -> Result<(), Self::Error> {
self.addr_store self.addr_store
.write()
.await
.update_addressbook( .update_addressbook(
self.principal.to_owned(), self.principal.to_owned(),
self.addressbook_id.to_owned(), self.addressbook_id.to_owned(),
@@ -269,8 +262,6 @@ impl<AS: AddressbookStore + ?Sized> ResourceService for AddressbookResourceServi
async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> { async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> {
self.addr_store self.addr_store
.write()
.await
.delete_addressbook(&self.principal, &self.addressbook_id, use_trashbin) .delete_addressbook(&self.principal, &self.addressbook_id, use_trashbin)
.await?; .await?;
Ok(()) Ok(())

View File

@@ -29,7 +29,7 @@ impl actix_web::ResponseError for Error {
match self { match self {
Error::StoreError(err) => match err { Error::StoreError(err) => match err {
rustical_store::Error::NotFound => StatusCode::NOT_FOUND, rustical_store::Error::NotFound => StatusCode::NOT_FOUND,
rustical_store::Error::InvalidIcs(_) => StatusCode::BAD_REQUEST, rustical_store::Error::InvalidData(_) => StatusCode::BAD_REQUEST,
_ => StatusCode::INTERNAL_SERVER_ERROR, _ => StatusCode::INTERNAL_SERVER_ERROR,
}, },
Error::DavError(err) => err.status_code(), Error::DavError(err) => err.status_code(),

View File

@@ -18,7 +18,6 @@ use rustical_store::{
AddressbookStore, AddressbookStore,
}; };
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::RwLock;
pub mod address_object; pub mod address_object;
pub mod addressbook; pub mod addressbook;
@@ -33,7 +32,7 @@ pub fn configure_well_known(cfg: &mut web::ServiceConfig, carddav_root: String)
pub fn configure_dav<AP: AuthenticationProvider, A: AddressbookStore + ?Sized>( pub fn configure_dav<AP: AuthenticationProvider, A: AddressbookStore + ?Sized>(
cfg: &mut web::ServiceConfig, cfg: &mut web::ServiceConfig,
auth_provider: Arc<AP>, auth_provider: Arc<AP>,
store: Arc<RwLock<A>>, store: Arc<A>,
) { ) {
cfg.service( cfg.service(
web::scope("") web::scope("")

View File

@@ -10,11 +10,10 @@ use rustical_store::AddressbookStore;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use strum::{EnumString, VariantNames}; use strum::{EnumString, VariantNames};
use tokio::sync::RwLock;
pub struct PrincipalResourceService<A: AddressbookStore + ?Sized> { pub struct PrincipalResourceService<A: AddressbookStore + ?Sized> {
principal: String, principal: String,
addr_store: Arc<RwLock<A>>, addr_store: Arc<A>,
} }
#[derive(Clone)] #[derive(Clone)]
@@ -111,7 +110,7 @@ impl<A: AddressbookStore + ?Sized> ResourceService for PrincipalResourceService<
(principal,): Self::PathComponents, (principal,): Self::PathComponents,
) -> Result<Self, Self::Error> { ) -> Result<Self, Self::Error> {
let addr_store = req let addr_store = req
.app_data::<Data<RwLock<A>>>() .app_data::<Data<A>>()
.expect("no addressbook store in app_data!") .expect("no addressbook store in app_data!")
.clone() .clone()
.into_inner(); .into_inner();
@@ -135,12 +134,7 @@ impl<A: AddressbookStore + ?Sized> ResourceService for PrincipalResourceService<
&self, &self,
rmap: &ResourceMap, rmap: &ResourceMap,
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> { ) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
let addressbooks = self let addressbooks = self.addr_store.get_addressbooks(&self.principal).await?;
.addr_store
.read()
.await
.get_addressbooks(&self.principal)
.await?;
Ok(addressbooks Ok(addressbooks
.into_iter() .into_iter()
.map(|addressbook| { .map(|addressbook| {

View File

@@ -13,7 +13,6 @@ use rustical_store::{
CalendarStore, CalendarStore,
}; };
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::RwLock;
mod config; mod config;
mod routes; mod routes;
@@ -29,10 +28,9 @@ struct UserPage {
async fn route_user<C: CalendarStore + ?Sized>( async fn route_user<C: CalendarStore + ?Sized>(
path: Path<String>, path: Path<String>,
store: Data<RwLock<C>>, store: Data<C>,
user: User, user: User,
) -> impl Responder { ) -> impl Responder {
let store = store.read().await;
let user_id = path.into_inner(); let user_id = path.into_inner();
UserPage { UserPage {
calendars: store.get_calendars(&user.id).await.unwrap(), calendars: store.get_calendars(&user.id).await.unwrap(),
@@ -49,10 +47,9 @@ struct CalendarPage {
async fn route_calendar<C: CalendarStore + ?Sized>( async fn route_calendar<C: CalendarStore + ?Sized>(
path: Path<(String, String)>, path: Path<(String, String)>,
store: Data<RwLock<C>>, store: Data<C>,
user: User, user: User,
) -> impl Responder { ) -> impl Responder {
let store = store.read().await;
let (owner, cal_id) = path.into_inner(); let (owner, cal_id) = path.into_inner();
CalendarPage { CalendarPage {
owner: owner.to_owned(), owner: owner.to_owned(),
@@ -63,7 +60,7 @@ async fn route_calendar<C: CalendarStore + ?Sized>(
pub fn configure_frontend<AP: AuthenticationProvider, C: CalendarStore + ?Sized>( pub fn configure_frontend<AP: AuthenticationProvider, C: CalendarStore + ?Sized>(
cfg: &mut web::ServiceConfig, cfg: &mut web::ServiceConfig,
auth_provider: Arc<AP>, auth_provider: Arc<AP>,
store: Arc<RwLock<C>>, store: Arc<C>,
) { ) {
cfg.service( cfg.service(
web::scope("") web::scope("")

View File

@@ -10,19 +10,19 @@ pub trait AddressbookStore: Send + Sync + 'static {
async fn get_addressbooks(&self, principal: &str) -> Result<Vec<Addressbook>, Error>; async fn get_addressbooks(&self, principal: &str) -> Result<Vec<Addressbook>, Error>;
async fn update_addressbook( async fn update_addressbook(
&mut self, &self,
principal: String, principal: String,
id: String, id: String,
addressbook: Addressbook, addressbook: Addressbook,
) -> Result<(), Error>; ) -> Result<(), Error>;
async fn insert_addressbook(&mut self, addressbook: Addressbook) -> Result<(), Error>; async fn insert_addressbook(&self, addressbook: Addressbook) -> Result<(), Error>;
async fn delete_addressbook( async fn delete_addressbook(
&mut self, &self,
principal: &str, principal: &str,
name: &str, name: &str,
use_trashbin: bool, use_trashbin: bool,
) -> Result<(), Error>; ) -> Result<(), Error>;
async fn restore_addressbook(&mut self, principal: &str, name: &str) -> Result<(), Error>; async fn restore_addressbook(&self, principal: &str, name: &str) -> Result<(), Error>;
async fn sync_changes( async fn sync_changes(
&self, &self,
@@ -43,20 +43,21 @@ pub trait AddressbookStore: Send + Sync + 'static {
object_id: &str, object_id: &str,
) -> Result<AddressObject, Error>; ) -> Result<AddressObject, Error>;
async fn put_object( async fn put_object(
&mut self, &self,
principal: String, principal: String,
addressbook_id: String, addressbook_id: String,
object: AddressObject, object: AddressObject,
overwrite: bool,
) -> Result<(), Error>; ) -> Result<(), Error>;
async fn delete_object( async fn delete_object(
&mut self, &self,
principal: &str, principal: &str,
addressbook_id: &str, addressbook_id: &str,
object_id: &str, object_id: &str,
use_trashbin: bool, use_trashbin: bool,
) -> Result<(), Error>; ) -> Result<(), Error>;
async fn restore_object( async fn restore_object(
&mut self, &self,
principal: &str, principal: &str,
addressbook_id: &str, addressbook_id: &str,
object_id: &str, object_id: &str,

View File

@@ -9,19 +9,19 @@ pub trait CalendarStore: Send + Sync + 'static {
async fn get_calendars(&self, principal: &str) -> Result<Vec<Calendar>, Error>; async fn get_calendars(&self, principal: &str) -> Result<Vec<Calendar>, Error>;
async fn update_calendar( async fn update_calendar(
&mut self, &self,
principal: String, principal: String,
id: String, id: String,
calendar: Calendar, calendar: Calendar,
) -> Result<(), Error>; ) -> Result<(), Error>;
async fn insert_calendar(&mut self, calendar: Calendar) -> Result<(), Error>; async fn insert_calendar(&self, calendar: Calendar) -> Result<(), Error>;
async fn delete_calendar( async fn delete_calendar(
&mut self, &self,
principal: &str, principal: &str,
name: &str, name: &str,
use_trashbin: bool, use_trashbin: bool,
) -> Result<(), Error>; ) -> Result<(), Error>;
async fn restore_calendar(&mut self, principal: &str, name: &str) -> Result<(), Error>; async fn restore_calendar(&self, principal: &str, name: &str) -> Result<(), Error>;
async fn sync_changes( async fn sync_changes(
&self, &self,
@@ -42,20 +42,21 @@ pub trait CalendarStore: Send + Sync + 'static {
object_id: &str, object_id: &str,
) -> Result<CalendarObject, Error>; ) -> Result<CalendarObject, Error>;
async fn put_object( async fn put_object(
&mut self, &self,
principal: String, principal: String,
cal_id: String, cal_id: String,
object: CalendarObject, object: CalendarObject,
overwrite: bool,
) -> Result<(), Error>; ) -> Result<(), Error>;
async fn delete_object( async fn delete_object(
&mut self, &self,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
object_id: &str, object_id: &str,
use_trashbin: bool, use_trashbin: bool,
) -> Result<(), Error>; ) -> Result<(), Error>;
async fn restore_object( async fn restore_object(
&mut self, &self,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
object_id: &str, object_id: &str,

View File

@@ -3,8 +3,11 @@ pub enum Error {
#[error("Not found")] #[error("Not found")]
NotFound, NotFound,
#[error("Invalid ics input: {0}")] #[error("Resource already exists and overwrite=false")]
InvalidIcs(String), AlreadyExists,
#[error("Invalid ics/vcf input: {0}")]
InvalidData(String),
#[error(transparent)] #[error(transparent)]
SqlxError(sqlx::Error), SqlxError(sqlx::Error),

View File

@@ -68,7 +68,7 @@ impl CalendarObject {
let mut parser = ical::IcalParser::new(BufReader::new(ics.as_bytes())); let mut parser = ical::IcalParser::new(BufReader::new(ics.as_bytes()));
let cal = parser.next().ok_or(Error::NotFound)??; let cal = parser.next().ok_or(Error::NotFound)??;
if parser.next().is_some() { if parser.next().is_some() {
return Err(Error::InvalidIcs( return Err(Error::InvalidData(
"multiple calendars, only one allowed".to_owned(), "multiple calendars, only one allowed".to_owned(),
)); ));
} }
@@ -80,7 +80,7 @@ impl CalendarObject {
!= 1 != 1
{ {
// https://datatracker.ietf.org/doc/html/rfc4791#section-4.1 // https://datatracker.ietf.org/doc/html/rfc4791#section-4.1
return Err(Error::InvalidIcs( return Err(Error::InvalidData(
"iCalendar object is only allowed to have exactly one component".to_owned(), "iCalendar object is only allowed to have exactly one component".to_owned(),
)); ));
} }
@@ -114,7 +114,7 @@ impl CalendarObject {
}); });
} }
Err(Error::InvalidIcs( Err(Error::InvalidData(
"iCalendar component type not supported :(".to_owned(), "iCalendar component type not supported :(".to_owned(),
)) ))
} }

View File

@@ -99,7 +99,7 @@ impl AddressbookStore for SqliteStore {
#[instrument] #[instrument]
async fn update_addressbook( async fn update_addressbook(
&mut self, &self,
principal: String, principal: String,
id: String, id: String,
addressbook: Addressbook, addressbook: Addressbook,
@@ -123,7 +123,7 @@ impl AddressbookStore for SqliteStore {
} }
#[instrument] #[instrument]
async fn insert_addressbook(&mut self, addressbook: Addressbook) -> Result<(), Error> { async fn insert_addressbook(&self, addressbook: Addressbook) -> Result<(), Error> {
sqlx::query!( sqlx::query!(
r#"INSERT INTO addressbooks (principal, id, displayname, description) r#"INSERT INTO addressbooks (principal, id, displayname, description)
VALUES (?, ?, ?, ?)"#, VALUES (?, ?, ?, ?)"#,
@@ -139,7 +139,7 @@ impl AddressbookStore for SqliteStore {
#[instrument] #[instrument]
async fn delete_addressbook( async fn delete_addressbook(
&mut self, &self,
principal: &str, principal: &str,
addressbook_id: &str, addressbook_id: &str,
use_trashbin: bool, use_trashbin: bool,
@@ -168,7 +168,7 @@ impl AddressbookStore for SqliteStore {
#[instrument] #[instrument]
async fn restore_addressbook( async fn restore_addressbook(
&mut self, &self,
principal: &str, principal: &str,
addressbook_id: &str, addressbook_id: &str,
) -> Result<(), Error> { ) -> Result<(), Error> {
@@ -264,10 +264,12 @@ impl AddressbookStore for SqliteStore {
#[instrument] #[instrument]
async fn put_object( async fn put_object(
&mut self, &self,
principal: String, principal: String,
addressbook_id: String, addressbook_id: String,
object: AddressObject, object: AddressObject,
// TODO: implement
overwrite: bool,
) -> Result<(), Error> { ) -> Result<(), Error> {
let mut tx = self.db.begin().await?; let mut tx = self.db.begin().await?;
@@ -298,7 +300,7 @@ impl AddressbookStore for SqliteStore {
#[instrument] #[instrument]
async fn delete_object( async fn delete_object(
&mut self, &self,
principal: &str, principal: &str,
addressbook_id: &str, addressbook_id: &str,
object_id: &str, object_id: &str,
@@ -341,7 +343,7 @@ impl AddressbookStore for SqliteStore {
#[instrument] #[instrument]
async fn restore_object( async fn restore_object(
&mut self, &self,
principal: &str, principal: &str,
addressbook_id: &str, addressbook_id: &str,
object_id: &str, object_id: &str,

View File

@@ -98,7 +98,7 @@ impl CalendarStore for SqliteStore {
} }
#[instrument] #[instrument]
async fn insert_calendar(&mut self, calendar: Calendar) -> Result<(), Error> { async fn insert_calendar(&self, calendar: Calendar) -> Result<(), Error> {
sqlx::query!( sqlx::query!(
r#"INSERT INTO calendars (principal, id, displayname, description, "order", color, timezone) r#"INSERT INTO calendars (principal, id, displayname, description, "order", color, timezone)
VALUES (?, ?, ?, ?, ?, ?, ?)"#, VALUES (?, ?, ?, ?, ?, ?, ?)"#,
@@ -117,7 +117,7 @@ impl CalendarStore for SqliteStore {
#[instrument] #[instrument]
async fn update_calendar( async fn update_calendar(
&mut self, &self,
principal: String, principal: String,
id: String, id: String,
calendar: Calendar, calendar: Calendar,
@@ -144,7 +144,7 @@ impl CalendarStore for SqliteStore {
// Does not actually delete the calendar but just disables it // Does not actually delete the calendar but just disables it
#[instrument] #[instrument]
async fn delete_calendar( async fn delete_calendar(
&mut self, &self,
principal: &str, principal: &str,
id: &str, id: &str,
use_trashbin: bool, use_trashbin: bool,
@@ -172,7 +172,7 @@ impl CalendarStore for SqliteStore {
} }
#[instrument] #[instrument]
async fn restore_calendar(&mut self, principal: &str, id: &str) -> Result<(), Error> { async fn restore_calendar(&self, principal: &str, id: &str) -> Result<(), Error> {
sqlx::query!( sqlx::query!(
r"UPDATE calendars SET deleted_at = NULL WHERE (principal, id) = (?, ?)", r"UPDATE calendars SET deleted_at = NULL WHERE (principal, id) = (?, ?)",
principal, principal,
@@ -223,10 +223,12 @@ impl CalendarStore for SqliteStore {
#[instrument] #[instrument]
async fn put_object( async fn put_object(
&mut self, &self,
principal: String, principal: String,
cal_id: String, cal_id: String,
object: CalendarObject, object: CalendarObject,
// TODO: implement
overwrite: bool,
) -> Result<(), Error> { ) -> Result<(), Error> {
let mut tx = self.db.begin().await?; let mut tx = self.db.begin().await?;
@@ -257,7 +259,7 @@ impl CalendarStore for SqliteStore {
#[instrument] #[instrument]
async fn delete_object( async fn delete_object(
&mut self, &self,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
id: &str, id: &str,
@@ -300,7 +302,7 @@ impl CalendarStore for SqliteStore {
#[instrument] #[instrument]
async fn restore_object( async fn restore_object(
&mut self, &self,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
object_id: &str, object_id: &str,

View File

@@ -92,7 +92,7 @@ impl CalDateTime {
if let Ok(tz) = olson_name.parse::<Tz>() { if let Ok(tz) = olson_name.parse::<Tz>() {
Some(tz) Some(tz)
} else { } else {
return Err(Error::InvalidIcs(format!( return Err(Error::InvalidData(format!(
"Timezone has X-LIC-LOCATION property to specify a timezone from the Olson database, however it's value {olson_name} is invalid" "Timezone has X-LIC-LOCATION property to specify a timezone from the Olson database, however it's value {olson_name} is invalid"
))); )));
} }
@@ -109,7 +109,7 @@ impl CalDateTime {
} }
} else { } else {
// TZID refers to timezone that does not exist // TZID refers to timezone that does not exist
return Err(Error::InvalidIcs(format!( return Err(Error::InvalidData(format!(
"No timezone specified with TZID={tzid}" "No timezone specified with TZID={tzid}"
))); )));
} }
@@ -167,7 +167,7 @@ impl From<CalDateTime> for DateTime<Utc> {
pub fn parse_duration(string: &str) -> Result<Duration, Error> { pub fn parse_duration(string: &str) -> Result<Duration, Error> {
let captures = RE_DURATION let captures = RE_DURATION
.captures(string) .captures(string)
.ok_or(Error::InvalidIcs("Invalid duration format".to_owned()))?; .ok_or(Error::InvalidData("Invalid duration format".to_owned()))?;
let mut duration = Duration::zero(); let mut duration = Duration::zero();
if let Some(weeks) = captures.name("W") { if let Some(weeks) = captures.name("W") {

View File

@@ -6,12 +6,11 @@ use rustical_frontend::configure_frontend;
use rustical_store::auth::AuthenticationProvider; use rustical_store::auth::AuthenticationProvider;
use rustical_store::{AddressbookStore, CalendarStore}; use rustical_store::{AddressbookStore, CalendarStore};
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::RwLock;
use tracing_actix_web::TracingLogger; use tracing_actix_web::TracingLogger;
pub fn make_app<AS: AddressbookStore + ?Sized, CS: CalendarStore + ?Sized>( pub fn make_app<AS: AddressbookStore + ?Sized, CS: CalendarStore + ?Sized>(
addr_store: Arc<RwLock<AS>>, addr_store: Arc<AS>,
cal_store: Arc<RwLock<CS>>, cal_store: Arc<CS>,
auth_provider: Arc<impl AuthenticationProvider>, auth_provider: Arc<impl AuthenticationProvider>,
) -> App< ) -> App<
impl ServiceFactory< impl ServiceFactory<

View File

@@ -19,7 +19,6 @@ use rustical_store::{AddressbookStore, CalendarStore};
use std::fs; use std::fs;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use tokio::sync::RwLock;
use tracing::level_filters::LevelFilter; use tracing::level_filters::LevelFilter;
use tracing_opentelemetry::OpenTelemetryLayer; use tracing_opentelemetry::OpenTelemetryLayer;
use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::layer::SubscriberExt;
@@ -41,14 +40,11 @@ struct Args {
async fn get_data_stores( async fn get_data_stores(
migrate: bool, migrate: bool,
config: &DataStoreConfig, config: &DataStoreConfig,
) -> Result<( ) -> Result<(Arc<dyn AddressbookStore>, Arc<dyn CalendarStore>)> {
Arc<RwLock<dyn AddressbookStore>>,
Arc<RwLock<dyn CalendarStore>>,
)> {
Ok(match &config { Ok(match &config {
DataStoreConfig::Sqlite(SqliteDataStoreConfig { db_url }) => { DataStoreConfig::Sqlite(SqliteDataStoreConfig { db_url }) => {
let db = create_db_pool(db_url, migrate).await?; let db = create_db_pool(db_url, migrate).await?;
let sqlite_store = Arc::new(RwLock::new(SqliteStore::new(db))); let sqlite_store = Arc::new(SqliteStore::new(db));
(sqlite_store.clone(), sqlite_store.clone()) (sqlite_store.clone(), sqlite_store.clone())
} }
}) })