Fix CalDAV/CardDAV multiget loading entire collections into memory

A REPORT multiget for a handful of resources previously listed the
whole calendar/address book (every row incl. ical_data/vcard) and
filtered by href in Rust with an O(N×M) substring scan. Large
collections paid full-table latency, RAM and DB CPU on every sync.

- Add find_events_by_ical_uids / get_contacts_by_uids through every
  layer (domain repo trait → PG repo → storage port/adapter → use case
  → handler) using one indexed `= ANY($2)` query, mirroring the
  existing single-UID lookups.
- Extract UIDs from multiget hrefs with a shared, tested
  uid_from_multiget_href helper (percent-decoding, case-insensitive
  extension strip, collection hrefs rejected). Exact UID matching also
  removes the false positives the old substring filter allowed.
- CalDAV PROPFIND single-event path now uses the existing indexed
  get_event_by_ical_uid instead of listing all events.
- Honour the already-documented limit/offset query params on
  GET /api/address-books/{id}/contacts: optional ListQuery fields
  thread through ContactUseCase::list_contacts to a paginated repo
  query. Omitted params keep returning the full book (frontend and
  DAV listing/sync paths unchanged).

https://claude.ai/code/session_0193Hff42gaA962wThxMGSd1
This commit is contained in:
Claude
2026-06-11 09:21:35 +00:00
parent f678ff414e
commit 6a27c742d4
14 changed files with 431 additions and 49 deletions
@@ -422,6 +422,26 @@ impl CalendarStoragePort for CalendarStorageAdapter {
Ok(event.map(CalendarEventDto::from))
}
async fn find_events_by_ical_uids(
&self,
calendar_id: &str,
ical_uids: &[String],
) -> Result<Vec<CalendarEventDto>, DomainError> {
let uuid = Uuid::parse_str(calendar_id).map_err(|_| {
DomainError::new(
ErrorKind::InvalidInput,
"Calendar",
"Invalid calendar ID format",
)
})?;
let events = self
.event_repository
.find_events_by_ical_uids(&uuid, ical_uids)
.await?;
Ok(events.into_iter().map(CalendarEventDto::from).collect())
}
async fn list_events_by_calendar(
&self,
calendar_id: &str,
@@ -730,9 +730,10 @@ impl ContactUseCase for ContactStorageAdapter {
Ok(contact.map(ContactDto::from))
}
async fn list_contacts(
async fn get_contacts_by_uids(
&self,
address_book_id: &str,
uids: &[String],
user_id: Uuid,
) -> Result<Vec<ContactDto>, DomainError> {
let uuid = Self::parse_uuid(address_book_id, "AddressBook")?;
@@ -740,13 +741,43 @@ impl ContactUseCase for ContactStorageAdapter {
// Check read access
self.check_address_book_access(&uuid, user_id).await?;
if uids.is_empty() {
return Ok(Vec::new());
}
let contacts = self
.contact_repository
.get_contacts_by_address_book(&uuid)
.get_contacts_by_uids(&uuid, uids)
.await?;
Ok(contacts.into_iter().map(ContactDto::from).collect())
}
async fn list_contacts(
&self,
address_book_id: &str,
limit: Option<i64>,
offset: Option<i64>,
user_id: Uuid,
) -> Result<Vec<ContactDto>, DomainError> {
let uuid = Self::parse_uuid(address_book_id, "AddressBook")?;
// Check read access
self.check_address_book_access(&uuid, user_id).await?;
let contacts = if limit.is_some() || offset.is_some() {
let limit = limit.unwrap_or(100);
let offset = offset.unwrap_or(0);
self.contact_repository
.get_contacts_by_address_book_paginated(&uuid, limit, offset)
.await?
} else {
self.contact_repository
.get_contacts_by_address_book(&uuid)
.await?
};
Ok(contacts.into_iter().map(ContactDto::from).collect())
}
async fn search_contacts(
&self,
address_book_id: &str,
@@ -370,6 +370,56 @@ impl CalendarEventRepository for CalendarEventPgRepository {
}
}
async fn find_events_by_ical_uids(
&self,
calendar_id: &Uuid,
ical_uids: &[String],
) -> CalendarEventRepositoryResult<Vec<CalendarEvent>> {
let rows = sqlx::query(
r#"
SELECT
id, calendar_id, summary, description, location,
start_time, end_time, all_day, rrule,
created_at, updated_at, ical_uid, ical_data
FROM caldav.calendar_events
WHERE calendar_id = $1 AND ical_uid = ANY($2)
ORDER BY start_time
"#,
)
.bind(calendar_id)
.bind(ical_uids)
.fetch_all(&*self.pool)
.await
.map_err(|e| {
DomainError::database_error(format!("Failed to get calendar events by UIDs: {}", e))
})?;
let mut events = Vec::new();
for row in rows {
let event = CalendarEvent::with_id(
row.get("id"),
row.get("calendar_id"),
row.get("summary"),
row.get::<Option<String>, _>("description"),
row.get::<Option<String>, _>("location"),
row.get("start_time"),
row.get("end_time"),
row.get("all_day"),
row.get::<Option<String>, _>("rrule"),
row.get("ical_uid"),
row.get("ical_data"),
row.get("created_at"),
row.get("updated_at"),
)
.map_err(|e| {
DomainError::database_error(format!("Error creating calendar event: {}", e))
})?;
events.push(event);
}
Ok(events)
}
async fn count_events_in_calendar(
&self,
calendar_id: &Uuid,
@@ -247,13 +247,44 @@ impl ContactRepository for ContactPgRepository {
}
}
async fn get_contacts_by_uids(
&self,
address_book_id: &Uuid,
uids: &[String],
) -> ContactRepositoryResult<Vec<Contact>> {
let rows = sqlx::query(
r#"
SELECT
id, address_book_id, uid, full_name, first_name, last_name, nickname,
email, phone, address, organization, title, notes, photo_url,
birthday, anniversary, vcard, etag, created_at, updated_at
FROM carddav.contacts
WHERE address_book_id = $1 AND uid = ANY($2)
ORDER BY full_name, first_name, last_name
"#,
)
.bind(address_book_id)
.bind(uids)
.fetch_all(&*self.pool)
.await
.map_err(|e| {
DomainError::database_error(format!("Failed to get contacts by uids: {}", e))
})?;
let mut contacts = Vec::new();
for row in &rows {
contacts.push(Self::row_to_contact(row)?);
}
Ok(contacts)
}
async fn get_contacts_by_address_book(
&self,
address_book_id: &Uuid,
) -> ContactRepositoryResult<Vec<Contact>> {
let rows = sqlx::query(
r#"
SELECT
SELECT
id, address_book_id, uid, full_name, first_name, last_name, nickname,
email, phone, address, organization, title, notes, photo_url,
birthday, anniversary, vcard, etag, created_at, updated_at
@@ -276,6 +307,43 @@ impl ContactRepository for ContactPgRepository {
Ok(contacts)
}
async fn get_contacts_by_address_book_paginated(
&self,
address_book_id: &Uuid,
limit: i64,
offset: i64,
) -> ContactRepositoryResult<Vec<Contact>> {
let rows = sqlx::query(
r#"
SELECT
id, address_book_id, uid, full_name, first_name, last_name, nickname,
email, phone, address, organization, title, notes, photo_url,
birthday, anniversary, vcard, etag, created_at, updated_at
FROM carddav.contacts
WHERE address_book_id = $1
ORDER BY full_name, first_name, last_name
LIMIT $2 OFFSET $3
"#,
)
.bind(address_book_id)
.bind(limit)
.bind(offset)
.fetch_all(&*self.pool)
.await
.map_err(|e| {
DomainError::database_error(format!(
"Failed to get contacts by address book (paginated): {}",
e
))
})?;
let mut contacts = Vec::new();
for row in &rows {
contacts.push(Self::row_to_contact(row)?);
}
Ok(contacts)
}
async fn get_contacts_by_email(&self, email: &str) -> ContactRepositoryResult<Vec<Contact>> {
let search_pattern = super::like_escape(email);