feat(caldav): CalDAV client, VEVENT/VTODO mapping and two-way sync

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-10-21 03:37:48 +02:00
1 parent fbcfcf678f
commit b5e0d0f325
14 files changed
+4611 -5

No files matched your search

+398
View File
@@ -0,0 +1,398 @@
//! A tiny in-process CalDAV server (just enough of RFC 4791/6578 for the client).
#![allow(dead_code)]
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
pub const HOME: &str = "/dav/calendars/user/";
pub const PERSONAL: &str = "/dav/calendars/user/personal/";
pub const TASKS: &str = "/dav/calendars/user/tasks/";
#[derive(Default)]
pub struct State {
pub objects: BTreeMap<String, (String, String)>, // path -> (etag, body)
pub rev: u64,
log: Vec<(u64, String, bool)>, // rev, path, deleted
pub support_sync: bool,
pub requests: Vec<String>,
pub puts: Vec<(String, Option<String>)>, // path, if-match
}
#[derive(Clone)]
pub struct Mock {
pub state: Arc<Mutex<State>>,
pub base: String,
}
impl Mock {
pub async fn start() -> Mock {
let l = TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", l.local_addr().unwrap());
let state = Arc::new(Mutex::new(State {
support_sync: true,
..Default::default()
}));
let st = state.clone();
tokio::spawn(async move {
loop {
let Ok((mut sock, _)) = l.accept().await else {
break;
};
let st = st.clone();
tokio::spawn(async move {
if let Some(req) = read_request(&mut sock).await {
let resp = handle(&st, req);
let _ = sock.write_all(resp.as_bytes()).await;
let _ = sock.shutdown().await;
}
});
}
});
Mock { state, base }
}
/// Server-side write (as another client would do). Returns the new etag.
pub fn set(&self, path: &str, body: &str) -> String {
let mut s = self.state.lock().unwrap();
put(&mut s, path, body)
}
pub fn remove(&self, path: &str) {
let mut s = self.state.lock().unwrap();
s.objects.remove(path);
s.rev += 1;
let r = s.rev;
s.log.push((r, path.to_string(), true));
}
pub fn body(&self, path: &str) -> Option<String> {
self.state
.lock()
.unwrap()
.objects
.get(path)
.map(|o| o.1.clone())
}
pub fn paths(&self, dir: &str) -> Vec<String> {
self.state
.lock()
.unwrap()
.objects
.keys()
.filter(|p| p.starts_with(dir))
.cloned()
.collect()
}
pub fn disable_sync_collection(&self) {
self.state.lock().unwrap().support_sync = false;
}
pub fn count_requests(&self, needle: &str) -> usize {
self.state
.lock()
.unwrap()
.requests
.iter()
.filter(|r| r.contains(needle))
.count()
}
}
fn put(s: &mut State, path: &str, body: &str) -> String {
s.rev += 1;
let etag = format!("\"e{}\"", s.rev);
s.objects
.insert(path.to_string(), (etag.clone(), body.to_string()));
let r = s.rev;
s.log.push((r, path.to_string(), false));
etag
}
struct Req {
method: String,
path: String,
headers: BTreeMap<String, String>,
body: String,
}
async fn read_request(sock: &mut tokio::net::TcpStream) -> Option<Req> {
let mut buf = Vec::new();
let mut tmp = [0u8; 4096];
let head_end = loop {
let n = sock.read(&mut tmp).await.ok()?;
if n == 0 {
return None;
}
buf.extend_from_slice(&tmp[..n]);
if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
break i + 4;
}
};
let head = String::from_utf8_lossy(&buf[..head_end]).to_string();
let mut lines = head.lines();
let first = lines.next()?;
let mut parts = first.split_whitespace();
let (method, path) = (parts.next()?.to_string(), parts.next()?.to_string());
let headers: BTreeMap<String, String> = lines
.filter_map(|l| {
l.split_once(':')
.map(|(k, v)| (k.trim().to_lowercase(), v.trim().to_string()))
})
.collect();
let len: usize = headers
.get("content-length")
.and_then(|v| v.parse().ok())
.unwrap_or(0);
while buf.len() < head_end + len {
let n = sock.read(&mut tmp).await.ok()?;
if n == 0 {
break;
}
buf.extend_from_slice(&tmp[..n]);
}
let body = String::from_utf8_lossy(&buf[head_end..]).to_string();
Some(Req {
method,
path,
headers,
body,
})
}
fn http(status: &str, headers: &[(&str, String)], body: &str) -> String {
let mut s = format!(
"HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n",
body.len()
);
for (k, v) in headers {
s.push_str(&format!("{k}: {v}\r\n"));
}
s.push_str("\r\n");
s.push_str(body);
s
}
fn xml_escape(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
}
fn multistatus(inner: &str) -> String {
let body = format!(
r#"<?xml version="1.0" encoding="utf-8"?><d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:cs="http://calendarserver.org/ns/">{inner}</d:multistatus>"#
);
http(
"207 Multi-Status",
&[("Content-Type", "application/xml".into())],
&body,
)
}
fn prop_response(href: &str, props: &str) -> String {
format!(
"<d:response><d:href>{href}</d:href><d:propstat><d:prop>{props}</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>"
)
}
fn ctag(s: &State, dir: &str) -> String {
// Per-collection ctag: highest revision touching the collection.
let r = s
.log
.iter()
.filter(|(_, p, _)| p.starts_with(dir))
.map(|(r, _, _)| *r)
.max()
.unwrap_or(0);
format!("ctag-{r}")
}
fn calendar_props(s: &State, dir: &str, name: &str, comps: &[&str]) -> String {
let comps: String = comps
.iter()
.map(|c| format!(r#"<c:comp name="{c}"/>"#))
.collect();
format!(
"<d:displayname>{name}</d:displayname><d:resourcetype><d:collection/><c:calendar/></d:resourcetype><c:supported-calendar-component-set>{comps}</c:supported-calendar-component-set><cs:getctag>{}</cs:getctag>",
ctag(s, dir)
)
}
fn hrefs_in(body: &str) -> Vec<String> {
let mut out = Vec::new();
let mut rest = body;
while let Some(i) = rest.find("<d:href>") {
let after = &rest[i + 8..];
let Some(j) = after.find("</d:href>") else {
break;
};
out.push(after[..j].replace("&amp;", "&"));
rest = &after[j..];
}
out
}
fn handle(st: &Arc<Mutex<State>>, req: Req) -> String {
let mut s = st.lock().unwrap();
s.requests.push(format!("{} {}", req.method, req.path));
if !req
.headers
.get("authorization")
.is_some_and(|a| a.starts_with("Basic "))
{
return http(
"401 Unauthorized",
&[("WWW-Authenticate", "Basic realm=\"mock\"".into())],
"",
);
}
let (m, p, b) = (req.method.as_str(), req.path.as_str(), req.body.as_str());
match (m, p) {
("PROPFIND", "/.well-known/caldav") => {
http("301 Moved Permanently", &[("Location", "/dav/".into())], "")
}
("PROPFIND", "/dav/") => multistatus(&prop_response(
"/dav/",
"<d:current-user-principal><d:href>/dav/principals/user/</d:href></d:current-user-principal>",
)),
("PROPFIND", "/dav/principals/user/") => multistatus(&prop_response(
p,
&format!("<c:calendar-home-set><d:href>{HOME}</d:href></c:calendar-home-set>"),
)),
("PROPFIND", HOME) => {
let mut inner = prop_response(HOME, "<d:resourcetype><d:collection/></d:resourcetype>");
inner += &prop_response(
PERSONAL,
&calendar_props(&s, PERSONAL, "Personal", &["VEVENT", "VTODO"]),
);
inner += &prop_response(TASKS, &calendar_props(&s, TASKS, "Tasks", &["VTODO"]));
multistatus(&inner)
}
("PROPFIND", cal) if cal == PERSONAL || cal == TASKS => {
if b.contains("getctag") {
multistatus(&prop_response(
cal,
&format!("<cs:getctag>{}</cs:getctag>", ctag(&s, cal)),
))
} else {
let mut inner =
prop_response(cal, "<d:resourcetype><d:collection/></d:resourcetype>");
for (path, (etag, _)) in s.objects.iter().filter(|(k, _)| k.starts_with(cal)) {
inner += &prop_response(
path,
&format!("<d:getetag>{}</d:getetag>", xml_escape(etag)),
);
}
multistatus(&inner)
}
}
("REPORT", cal) if b.contains("sync-collection") => {
if !s.support_sync {
return http("501 Not Implemented", &[], "");
}
let since: u64 = b
.split("<d:sync-token>")
.nth(1)
.and_then(|t| t.split("</d:sync-token>").next())
.and_then(|t| t.strip_prefix("tok-"))
.and_then(|t| t.parse().ok())
.unwrap_or(0);
let mut latest: BTreeMap<&String, bool> = BTreeMap::new();
for (r, path, deleted) in &s.log {
if *r > since && path.starts_with(cal) {
latest.insert(path, *deleted);
}
}
let mut inner = String::new();
for (path, deleted) in latest {
if deleted {
inner += &format!(
"<d:response><d:href>{path}</d:href><d:status>HTTP/1.1 404 Not Found</d:status></d:response>"
);
} else if let Some((etag, _)) = s.objects.get(path) {
inner += &prop_response(
path,
&format!("<d:getetag>{}</d:getetag>", xml_escape(etag)),
);
}
}
inner += &format!("<d:sync-token>tok-{}</d:sync-token>", s.rev);
multistatus(&inner)
}
("REPORT", _) if b.contains("calendar-multiget") => {
let mut inner = String::new();
for h in hrefs_in(b) {
if let Some((etag, body)) = s.objects.get(&h) {
inner += &prop_response(
&h,
&format!(
"<d:getetag>{}</d:getetag><c:calendar-data>{}</c:calendar-data>",
xml_escape(etag),
xml_escape(body)
),
);
}
}
multistatus(&inner)
}
("GET", path) => match s.objects.get(path) {
Some((etag, body)) => http(
"200 OK",
&[
("ETag", etag.clone()),
("Content-Type", "text/calendar".into()),
],
body,
),
None => http("404 Not Found", &[], ""),
},
("PUT", path) => {
let if_match = req.headers.get("if-match").cloned();
s.puts.push((path.to_string(), if_match.clone()));
let current = s.objects.get(path).map(|o| o.0.clone());
let ok = match (
&if_match,
req.headers.get("if-none-match").map(String::as_str),
&current,
) {
(Some(m), _, Some(c)) => m == c,
(Some(_), _, None) => false,
(None, Some("*"), Some(_)) => false,
_ => true,
};
if !ok {
return http("412 Precondition Failed", &[], "");
}
let etag = put(&mut s, path, b);
http(
if current.is_some() {
"204 No Content"
} else {
"201 Created"
},
&[("ETag", etag)],
"",
)
}
("DELETE", path) => {
if let (Some(m), Some((c, _))) = (req.headers.get("if-match"), s.objects.get(path))
&& m != c
{
return http("412 Precondition Failed", &[], "");
}
if s.objects.remove(path).is_some() {
s.rev += 1;
let r = s.rev;
s.log.push((r, path.to_string(), true));
http("204 No Content", &[], "")
} else {
http("404 Not Found", &[], "")
}
}
_ => http("404 Not Found", &[], ""),
}
}
+367
View File
@@ -0,0 +1,367 @@
mod mock;
use chrono::NaiveDate;
use chrono_tz::Europe::Madrid;
use mock::{HOME, Mock, PERSONAL, TASKS};
use synapse_caldav::{
Config, Credentials, DavClient, events_for_day, materialize_day, refresh_calendars, sync,
};
use synapse_core::{Graph, Placement};
fn day(y: i32, m: u32, d: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(y, m, d).unwrap()
}
fn ms(y: i32, m: u32, d: u32, h: u32) -> i64 {
day(y, m, d)
.and_hms_opt(h, 0, 0)
.unwrap()
.and_utc()
.timestamp_millis()
}
fn client(m: &Mock) -> DavClient {
DavClient::new(
&m.base,
Credentials {
username: "u".into(),
password: "app-pw".into(),
},
)
.unwrap()
}
fn graph() -> (tempfile::TempDir, Graph) {
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path()).unwrap();
g.set_now(Some(ms(2026, 10, 21, 9)));
(dir, g)
}
fn vtodo(uid: &str, body: &str) -> String {
format!(
"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Other//EN\r\nBEGIN:VTODO\r\nUID:{uid}\r\n{body}END:VTODO\r\nEND:VCALENDAR\r\n"
)
}
fn page_blocks(g: &Graph, title: &str) -> Vec<(usize, synapse_core::Block)> {
let p = g.page_by_title(title).unwrap().unwrap();
g.page_tree(p.id).unwrap()
}
const STANDUP: &str = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:standup\r\nSUMMARY:Standup\r\nDTSTART;TZID=Europe/Madrid:20261007T100000\r\nDTEND;TZID=Europe/Madrid:20261007T103000\r\nRRULE:FREQ=WEEKLY;BYDAY=WE\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:dentist\r\nSUMMARY:Dentist\r\nDTSTART;TZID=Europe/Madrid:20261021T170000\r\nDURATION:PT45M\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
#[tokio::test]
async fn discovery_and_calendar_listing() {
let m = Mock::start().await;
let (_d, g) = graph();
let c = client(&m);
let cals = refresh_calendars(&g, &c).await.unwrap();
assert_eq!(cals.len(), 2);
let tasks = cals.iter().find(|c| c.href == TASKS).unwrap();
assert!(tasks.supports_tasks && !tasks.supports_events);
let personal = cals.iter().find(|c| c.href == PERSONAL).unwrap();
assert!(personal.supports_events && personal.supports_tasks);
assert!(m.count_requests("PROPFIND /.well-known/caldav") >= 1);
assert_eq!(c.discover().await.unwrap(), HOME);
}
#[tokio::test]
async fn events_recurrence_and_journal_materialisation() {
let m = Mock::start().await;
m.set(&format!("{PERSONAL}standup.ics"), STANDUP);
let (_d, g) = graph();
let cfg = Config::new(Madrid);
let rep = sync(&g, &client(&m), &cfg).await.unwrap();
assert_eq!(rep.events_changed, 1);
// 2026-10-21 is a Wednesday: the weekly standup and the dentist.
let evs = events_for_day(&g, day(2026, 10, 21), Madrid).unwrap();
let names: Vec<_> = evs.iter().map(|e| e.summary.as_str()).collect();
assert_eq!(names, ["Standup", "Dentist"]);
assert!(evs[0].recurring && !evs[1].recurring);
assert_eq!(evs[1].end - evs[1].start, chrono::Duration::minutes(45));
assert!(
events_for_day(&g, day(2026, 10, 22), Madrid)
.unwrap()
.is_empty()
);
assert_eq!(
events_for_day(&g, day(2026, 10, 28), Madrid).unwrap().len(),
1
);
let ids = materialize_day(&g, day(2026, 10, 21), Madrid).unwrap();
assert_eq!(ids.len(), 2);
let j = g.journal(day(2026, 10, 21)).unwrap();
let tree = g.page_tree(j.id).unwrap();
assert_eq!(tree[0].1.content, "10:00-10:30 [[Standup]]");
assert_eq!(tree[1].1.content, "17:00-17:45 Dentist");
// The recurring meeting got its own page (via the [[link]]), the one-off did not.
assert!(g.page_by_title("Standup").unwrap().is_some());
assert!(g.page_by_title("Dentist").unwrap().is_none());
// Idempotent.
assert_eq!(materialize_day(&g, day(2026, 10, 21), Madrid).unwrap(), ids);
assert_eq!(g.page_tree(j.id).unwrap().len(), 2);
// Dentist cancelled remotely: the next sync + materialise removes its block only.
m.remove(&format!("{PERSONAL}standup.ics"));
m.set(
&format!("{PERSONAL}standup.ics"),
&STANDUP.replace("UID:dentist", "UID:dentist\r\nSTATUS:CANCELLED"),
);
sync(&g, &client(&m), &cfg).await.unwrap();
materialize_day(&g, day(2026, 10, 21), Madrid).unwrap();
let tree = g.page_tree(j.id).unwrap();
assert_eq!(tree.len(), 1);
assert_eq!(tree[0].1.content, "10:00-10:30 [[Standup]]");
}
#[tokio::test]
async fn task_round_trip_both_directions() {
let m = Mock::start().await;
let path = format!("{TASKS}milk.ics");
m.set(&path, &vtodo("milk", "SUMMARY:Buy milk\r\nPRIORITY:1\r\nDUE;VALUE=DATE:20261025\r\nX-KEEP:me\r\nLAST-MODIFIED:20261020T080000Z\r\n"));
let (_d, g) = graph();
let cfg = Config::new(Madrid);
let c = client(&m);
// Remote -> local.
let rep = sync(&g, &c, &cfg).await.unwrap();
assert_eq!(rep.tasks_pulled, 1);
let blocks = page_blocks(&g, "Tasks");
assert_eq!(blocks.len(), 1);
let b = &blocks[0].1;
assert_eq!(b.content, "TODO [#A] Buy milk\nDEADLINE: <2026-10-25 Sun>");
assert_eq!(b.properties["caldav-uid"], "milk");
assert_eq!(b.properties["caldav-calendar"], TASKS);
// Local completion -> remote.
g.set_now(Some(ms(2026, 10, 21, 10)));
g.update_block(b.id, "DONE [#A] Buy milk\nDEADLINE: <2026-10-25 Sun>")
.unwrap();
let rep = sync(&g, &c, &cfg).await.unwrap();
assert_eq!(rep.tasks_updated_remote, 1);
let remote = m.body(&path).unwrap();
assert!(
remote.contains("STATUS:COMPLETED") && remote.contains("PERCENT-COMPLETE:100"),
"{remote}"
);
assert!(remote.contains("COMPLETED:20261021T100000Z"), "{remote}");
assert!(
remote.contains("X-KEEP:me"),
"unknown properties survive: {remote}"
);
// The PUT was conditional on the etag we had.
assert!(
m.state
.lock()
.unwrap()
.puts
.iter()
.any(|(p, im)| p == &path && im.is_some())
);
// No echo: another sync changes nothing.
let rep = sync(&g, &c, &cfg).await.unwrap();
assert_eq!((rep.tasks_updated_remote, rep.conflicts), (0, 0));
// Remote reopens it as in-process -> local DOING.
let reopened = remote
.replace("STATUS:COMPLETED", "STATUS:IN-PROCESS")
.replace("PERCENT-COMPLETE:100", "PERCENT-COMPLETE:30")
.replace("COMPLETED:20261021T100000Z\r\n", "");
m.set(&path, &reopened);
sync(&g, &c, &cfg).await.unwrap();
let b = g.get_block(b.id).unwrap().unwrap();
assert_eq!(b.content, "DOING [#A] Buy milk\nDEADLINE: <2026-10-25 Sun>");
}
#[tokio::test]
async fn new_journal_task_goes_to_default_list_and_completes_remotely() {
let m = Mock::start().await;
m.set(&format!("{PERSONAL}standup.ics"), STANDUP); // gives the account an events-only-ish calendar
let (_d, g) = graph();
let mut cfg = Config::new(Madrid);
cfg.default_task_calendar = Some(TASKS.into());
let c = client(&m);
sync(&g, &c, &cfg).await.unwrap(); // establishes "enabled_at"
let j = g.today_journal().unwrap();
let plain = g
.insert_block(j.id, Placement::LastChildOf(None), "just a note")
.unwrap();
let t = g
.insert_block(
j.id,
Placement::LastChildOf(None),
"LATER [#B] Call the bank\nSCHEDULED: <2026-10-22 Thu 09:30>",
)
.unwrap();
let rep = sync(&g, &c, &cfg).await.unwrap();
assert_eq!(rep.tasks_created_remote, 1);
let paths = m.paths(TASKS);
assert_eq!(paths.len(), 1);
let body = m.body(&paths[0]).unwrap();
assert!(
body.contains("SUMMARY:Call the bank") && body.contains("PRIORITY:5"),
"{body}"
);
assert!(
body.contains("DTSTART;TZID=Europe/Madrid:20261022T093000"),
"{body}"
);
assert!(
g.get_block(plain.id)
.unwrap()
.unwrap()
.properties
.is_empty()
);
let t = g.get_block(t.id).unwrap().unwrap();
assert!(t.properties.contains_key("caldav-uid"));
assert_eq!(
t.content, "LATER [#B] Call the bank\nSCHEDULED: <2026-10-22 Thu 09:30>",
"content untouched"
);
// Completed in another app -> DONE here; LATER spelling kept only for open states.
m.set(
&paths[0],
&body.replace("STATUS:NEEDS-ACTION", "STATUS:COMPLETED"),
);
sync(&g, &c, &cfg).await.unwrap();
let t = g.get_block(t.id).unwrap().unwrap();
assert!(
t.content.starts_with("DONE [#B] Call the bank"),
"{}",
t.content
);
}
#[tokio::test]
async fn conflict_last_modified_wins_and_loser_kept_as_child() {
let m = Mock::start().await;
let path = format!("{TASKS}t.ics");
m.set(
&path,
&vtodo(
"t",
"SUMMARY:Plan trip\r\nLAST-MODIFIED:20261021T080000Z\r\n",
),
);
let (_d, g) = graph();
let cfg = Config::new(Madrid);
let c = client(&m);
sync(&g, &c, &cfg).await.unwrap();
let b = page_blocks(&g, "Tasks")[0].1.clone();
// Case 1: remote edited later (11:00) than the local edit (10:00): remote wins.
g.set_now(Some(ms(2026, 10, 21, 10)));
g.update_block(b.id, "TODO Plan trip to Rome").unwrap();
m.set(
&path,
&vtodo(
"t",
"SUMMARY:Plan trip to Paris\r\nLAST-MODIFIED:20261021T110000Z\r\n",
),
);
g.set_now(Some(ms(2026, 10, 21, 12)));
let rep = sync(&g, &c, &cfg).await.unwrap();
assert_eq!(rep.conflicts, 1);
let tree = page_blocks(&g, "Tasks");
assert_eq!(tree[0].1.content, "TODO Plan trip to Paris");
assert_eq!(tree[1].0, 1);
assert!(tree[1].1.content.contains("local") && tree[1].1.content.contains("Plan trip to Rome"));
// Case 2: local edited later (14:00) than the remote (13:00): local wins and is pushed.
m.set(
&path,
&vtodo(
"t",
"SUMMARY:Plan trip to Oslo\r\nLAST-MODIFIED:20261021T130000Z\r\n",
),
);
g.set_now(Some(ms(2026, 10, 21, 14)));
g.update_block(b.id, "TODO Plan trip to Lima").unwrap();
g.set_now(Some(ms(2026, 10, 21, 15)));
let rep = sync(&g, &c, &cfg).await.unwrap();
assert_eq!(rep.conflicts, 1);
assert_eq!(
g.get_block(b.id).unwrap().unwrap().content,
"TODO Plan trip to Lima"
);
assert!(m.body(&path).unwrap().contains("SUMMARY:Plan trip to Lima"));
let tree = page_blocks(&g, "Tasks");
assert!(
tree.iter()
.any(|(d, x)| *d == 1 && x.content.contains("remote") && x.content.contains("Oslo"))
);
}
#[tokio::test]
async fn stale_etag_on_push_refetches_and_retries() {
let m = Mock::start().await;
let path = format!("{TASKS}r.ics");
m.set(
&path,
&vtodo("r", "SUMMARY:Race\r\nLAST-MODIFIED:20261021T080000Z\r\n"),
);
let (_d, g) = graph();
let cfg = Config::new(Madrid);
let c = client(&m);
sync(&g, &c, &cfg).await.unwrap();
let b = page_blocks(&g, "Tasks")[0].1.clone();
g.set_now(Some(ms(2026, 10, 21, 10)));
g.update_block(b.id, "TODO Race local").unwrap();
// Our cached etag is out of date although the pull sees no change since its token.
g.conn()
.execute("UPDATE caldav_object SET etag='\"stale\"'", [])
.unwrap();
let rep = sync(&g, &c, &cfg).await.unwrap();
assert_eq!(rep.conflicts, 1);
assert_eq!(rep.tasks_updated_remote, 1);
assert!(m.body(&path).unwrap().contains("SUMMARY:Race local"));
let puts = m.state.lock().unwrap().puts.clone();
assert_eq!(
puts.len(),
2,
"first PUT rejected with 412, second accepted: {puts:?}"
);
}
#[tokio::test]
async fn deletions_both_ways_and_ctag_fallback() {
let m = Mock::start().await;
m.disable_sync_collection();
m.set(&format!("{TASKS}a.ics"), &vtodo("a", "SUMMARY:Alpha\r\n"));
m.set(&format!("{TASKS}b.ics"), &vtodo("b", "SUMMARY:Beta\r\n"));
let (_d, g) = graph();
let cfg = Config::new(Madrid);
let c = client(&m);
sync(&g, &c, &cfg).await.unwrap();
assert_eq!(page_blocks(&g, "Tasks").len(), 2);
assert_eq!(
m.count_requests("REPORT"),
3,
"two refused sync-collections + one multiget"
);
// Unchanged ctag: the second sync lists nothing.
let before = m.count_requests("depth");
sync(&g, &c, &cfg).await.unwrap();
assert_eq!(m.count_requests("depth"), before);
// Remote delete of Alpha -> block gone; local delete of Beta -> remote gone.
m.remove(&format!("{TASKS}a.ics"));
let beta = page_blocks(&g, "Tasks")
.into_iter()
.find(|(_, b)| b.content.contains("Beta"))
.unwrap()
.1;
g.delete_block(beta.id).unwrap();
let rep = sync(&g, &c, &cfg).await.unwrap();
assert_eq!(rep.removed_remote, 1);
assert_eq!(rep.tasks_deleted_remote, 1);
assert!(page_blocks(&g, "Tasks").is_empty());
assert!(m.paths(TASKS).is_empty());
}