Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Calendar: no ghost events, and deleting one that is gone just works

Yashwanth Kamireddie28deadfbb2e
diff --git a/crates/quince-core/src/calendar.rs b/crates/quince-core/src/calendar.rs
index dfe9f28..a8253a0 100644
--- a/crates/quince-core/src/calendar.rs
+++ b/crates/quince-core/src/calendar.rs
@@ -7,7 +7,7 @@ use crate::{Library, Result};
use rusqlite::params;
use serde::{Deserialize, Serialize};
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Calendar {
pub guid: String,
@@ -30,7 +30,7 @@ const fn yes() -> bool {
true
}
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Event {
pub guid: String,
@@ -225,6 +225,16 @@ impl Library {
rows.next().transpose().map_err(Into::into)
}
+ /// Every stored event starting in `[from, to)`, as (guid, calendar), whatever its
+ /// calendar's switch — what a pass over that window has to account for.
+ pub fn events_starting_between(&self, from: i64, to: i64) -> Result<Vec<(String, String)>> {
+ let mut stmt = self.conn.prepare(
+ "SELECT guid, calendar_guid FROM events WHERE starts_at >= ?1 AND starts_at < ?2",
+ )?;
+ let rows = stmt.query_map(params![from, to], |row| Ok((row.get(0)?, row.get(1)?)))?;
+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
+ }
+
/// Drop events Apple no longer has.
pub fn forget_events(&mut self, guids: &[String]) -> Result<()> {
let tx = self.conn.transaction()?;
diff --git a/crates/quince-icloud/src/calendar.rs b/crates/quince-icloud/src/calendar.rs
index 8253fcb..c354e2f 100644
--- a/crates/quince-icloud/src/calendar.rs
+++ b/crates/quince-icloud/src/calendar.rs
@@ -162,7 +162,7 @@ fn event_from(v: &Value) -> Result<Option<Event>> {
}
/// `YYYY-MM-DD` for the day an instant falls on, in the event's own timezone.
-fn day_of(seconds: i64, timezone: Option<&str>) -> String {
+pub(crate) fn day_of(seconds: i64, timezone: Option<&str>) -> String {
let zone = timezone
.and_then(|name| TimeZone::get(name).ok())
.unwrap_or(TimeZone::UTC);
@@ -192,6 +192,10 @@ fn client_state(calendar_guid: &str, ctag: Option<&str>) -> Value {
pub struct Snapshot {
pub calendars: Vec<Calendar>,
pub events: Vec<Event>,
+ /// The span, in unix seconds `[from, to)`, Apple was asked about in full. Every event
+ /// starting inside it that Apple did not return is gone from iCloud. `None` for a reply
+ /// that covers only what was written.
+ pub covers: Option<(i64, i64)>,
}
/// Read a `/ca/startup` or `/ca/events` body.
@@ -215,7 +219,11 @@ pub fn parse_snapshot(body: &Value) -> Snapshot {
})
.unwrap_or_default();
- Snapshot { calendars, events }
+ Snapshot {
+ calendars,
+ events,
+ covers: None,
+ }
}
/// Apple's calendar service.
@@ -312,16 +320,23 @@ impl<'a> CalendarClient<'a> {
"ClientState": client_state(&event.calendar_guid, ctag),
});
let path = format!("/ca/events/{}/{}", event.calendar_guid, event.guid);
- self.post(
- &path,
- &body,
- &day,
- &day,
- event.timezone.as_deref(),
- Some("DELETE"),
- )
- .await?;
- Ok(())
+ match self
+ .post(
+ &path,
+ &body,
+ &day,
+ &day,
+ event.timezone.as_deref(),
+ Some("DELETE"),
+ )
+ .await
+ {
+ // Deleting what is already gone has done what was asked — but only once Apple's
+ // own record confirms it is gone, not on the word of a status code alone.
+ // Measured: an event Apple no longer has answers 404 with an empty ChangeSet.
+ Err(Error::NotFound) if self.event_detail(event, &day).await.is_none() => Ok(()),
+ other => other.map(|_| ()),
+ }
}
/// Apple's own full record of an event, or `None` for one it has never heard of.
@@ -456,6 +471,9 @@ impl<'a> CalendarClient<'a> {
if status.as_u16() == 450 {
return Err(Error::ReauthRequired);
}
+ if status.as_u16() == 404 {
+ return Err(Error::NotFound);
+ }
if !status.is_success() {
return Err(Error::Protocol(format!(
"{path} returned {status}: {}",
@@ -489,6 +507,9 @@ impl<'a> CalendarClient<'a> {
if status.as_u16() == 450 {
return Err(Error::ReauthRequired);
}
+ if status.as_u16() == 404 {
+ return Err(Error::NotFound);
+ }
if !status.is_success() {
return Err(Error::Protocol(format!(
"{path} returned {status}: {}",
@@ -925,6 +946,49 @@ mod write_tests {
assert_eq!(body["Event"]["alarms"], serde_json::json!([]));
}
+ /// Deleting an event Apple no longer has: it answers 404, and its own record confirms
+ /// there is nothing there, so the delete has done what was asked.
+ #[tokio::test]
+ async fn deleting_what_apple_no_longer_has_succeeds() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/ca/events/.*"))
+ .respond_with(ResponseTemplate::new(404).set_body_json(
+ serde_json::json!({ "ChangeSet": { "fullState": false, "UpcomingAlarm": [] } }),
+ ))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path_regex(r".*/ca/eventdetail/.*"))
+ .respond_with(ResponseTemplate::new(404))
+ .mount(&server)
+ .await;
+ let http = reqwest::Client::new();
+ let client = CalendarClient::new(&http, &server.uri(), vec![]);
+ client.delete_event(&event(), None).await.unwrap();
+ }
+
+ /// But a 404 for an event Apple can still show is not passed off as a delete.
+ #[tokio::test]
+ async fn a_404_for_an_event_still_there_is_an_error() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/ca/events/.*"))
+ .respond_with(ResponseTemplate::new(404))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path_regex(r".*/ca/eventdetail/.*"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(
+ serde_json::json!({ "Event": [{ "guid": "E-1", "title": "Dentist" }] }),
+ ))
+ .mount(&server)
+ .await;
+ let http = reqwest::Client::new();
+ let client = CalendarClient::new(&http, &server.uri(), vec![]);
+ assert!(client.delete_event(&event(), None).await.is_err());
+ }
+
#[tokio::test]
async fn a_rejection_reads_as_a_sentence() {
let server = MockServer::start().await;
diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rs
index 2ae6df9..6428b0c 100644
--- a/crates/quince-icloud/src/lib.rs
+++ b/crates/quince-icloud/src/lib.rs
@@ -24,6 +24,9 @@ pub enum Error {
ReauthRequired,
#[error("this changed on another device first — refresh and try again")]
Conflict,
+ /// Apple has no such record — it was deleted elsewhere, or never kept.
+ #[error("that is no longer in iCloud")]
+ NotFound,
/// CloudKit would not read the cursor we held. Handled where the walk happens by starting
/// over, so this should never reach a person.
#[error("iCloud no longer recognises where we had got to")]
diff --git a/crates/quince-icloud/src/sync.rs b/crates/quince-icloud/src/sync.rs
index 7bd9034..e53042f 100644
--- a/crates/quince-icloud/src/sync.rs
+++ b/crates/quince-icloud/src/sync.rs
@@ -98,7 +98,23 @@ pub async fn fetch_calendar(
}
}
- Ok(Snapshot { calendars, events })
+ // The whole window was asked about, day by day in the viewer's zone, so anything stored
+ // as starting inside it that did not come back is no longer in iCloud.
+ let zone = jiff::tz::TimeZone::get(timezone).unwrap_or_else(|_| jiff::tz::TimeZone::system());
+ let edge = |d: Date| {
+ d.to_zoned(zone.clone())
+ .map(|z| z.timestamp().as_second())
+ .map_err(|e| Error::Protocol(format!("{d} has no start in {timezone}: {e}")))
+ };
+ let first = parse_date(from)?;
+ let after_last = parse_date(to)?
+ .checked_add(jiff::Span::new().days(1))
+ .map_err(|e| Error::Protocol(format!("{to} has no next day: {e}")))?;
+ Ok(Snapshot {
+ calendars,
+ events,
+ covers: Some((edge(first)?, edge(after_last)?)),
+ })
}
/// Create an event, or save changes to one, and store what Apple answers with.
@@ -121,12 +137,29 @@ pub async fn put_event(
.and_then(|c| c.ctag);
let answer = client.put_event(event, ctag.as_deref()).await?;
- // Apple echoes the stored event back. If it did not, the local copy is what we sent,
- // which is still better than showing nothing until the next refresh.
- let stored: Vec<_> = if answer.events.is_empty() {
- vec![event.clone()]
- } else {
+ // What goes into the library is what Apple holds, never what was sent. Measured: a save
+ // to the account answers with an empty list, and storing the sent copy instead kept an
+ // event with no etag — so the next edit or delete went without one — and, where Apple
+ // had not kept it, a ghost that could never be deleted. So an empty answer is followed
+ // by asking for the event's day and taking Apple's own copy.
+ let stored: Vec<_> = if answer.events.iter().any(|e| e.guid == event.guid) {
answer.events
+ } else {
+ let day = crate::calendar::day_of(event.starts_at, event.timezone.as_deref());
+ let tz = event.timezone.as_deref().unwrap_or("UTC");
+ let kept: Vec<_> = client
+ .events(&day, &day, tz)
+ .await?
+ .events
+ .into_iter()
+ .filter(|e| e.guid == event.guid)
+ .collect();
+ if kept.is_empty() {
+ return Err(Error::Protocol(
+ "iCloud took the event but did not keep it — nothing was saved".into(),
+ ));
+ }
+ kept
};
let known: std::collections::HashSet<String> =
library.calendars()?.into_iter().map(|c| c.guid).collect();
@@ -173,6 +206,23 @@ pub fn apply_calendar(library: &mut Library, snapshot: Snapshot) -> Result<SyncS
.collect();
library.put_events(&events)?;
+ // An event deleted on the phone stayed here for good — a pass only ever added — and
+ // deleting that ghost here then failed, because Apple had nothing to delete. Within the
+ // window Apple was asked about, what it did not return is gone; outside it, nothing is
+ // assumed. Only calendars Apple reported are judged.
+ if let Some((from, to)) = snapshot.covers {
+ let returned: std::collections::HashSet<&str> =
+ events.iter().map(|e| e.guid.as_str()).collect();
+ let gone: Vec<String> = library
+ .events_starting_between(from, to)?
+ .into_iter()
+ .filter(|(guid, calendar)| {
+ known.contains(calendar.as_str()) && !returned.contains(guid.as_str())
+ })
+ .map(|(guid, _)| guid)
+ .collect();
+ library.forget_events(&gone)?;
+ }
library.mark_synced("calendar", None)?;
Ok(SyncSummary {
@@ -202,6 +252,151 @@ mod tests {
})
}
+ fn saved_library() -> Library {
+ let mut library = Library::in_memory().unwrap();
+ library
+ .put_calendars(&[quince_core::calendar::Calendar {
+ guid: "work".into(),
+ title: "Work".into(),
+ ..Default::default()
+ }])
+ .unwrap();
+ library
+ }
+
+ fn new_event() -> quince_core::calendar::Event {
+ let start = "2026-10-03T04:30:00Z"
+ .parse::<jiff::Timestamp>()
+ .unwrap()
+ .as_second();
+ quince_core::calendar::Event {
+ guid: "NEW-1".into(),
+ calendar_guid: "work".into(),
+ title: "Dentist".into(),
+ starts_at: start,
+ ends_at: start + 3600,
+ timezone: Some("Asia/Kolkata".into()),
+ ..Default::default()
+ }
+ }
+
+ /// A save answers with nothing (measured on the account); what is stored is Apple's own
+ /// copy, read back, with the etag the next edit or delete needs.
+ #[tokio::test]
+ async fn a_saved_event_is_stored_as_apple_keeps_it() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/ca/events"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "Event": [{ "guid": "NEW-1", "pGuid": "work", "title": "Dentist", "etag": "apple-1",
+ "tz": "Asia/Kolkata",
+ "startDate": [20261003, 2026, 10, 3, 10, 0, 600], "duration": 60 }]
+ })))
+ .mount(&server)
+ .await;
+ let mut library = saved_library();
+ let http = reqwest::Client::new();
+ put_event(&http, &server.uri(), vec![], &mut library, &new_event())
+ .await
+ .unwrap();
+ assert_eq!(
+ library.event("NEW-1").unwrap().unwrap().etag.as_deref(),
+ Some("apple-1")
+ );
+ }
+
+ /// And where Apple did not keep it, nothing is stored — no ghost that cannot be deleted
+ /// — and the person is told.
+ #[tokio::test]
+ async fn an_event_apple_did_not_keep_is_not_stored() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/ca/events"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "Event": [] })))
+ .mount(&server)
+ .await;
+ let mut library = saved_library();
+ let http = reqwest::Client::new();
+ assert!(
+ put_event(&http, &server.uri(), vec![], &mut library, &new_event())
+ .await
+ .is_err()
+ );
+ assert!(library.event("NEW-1").unwrap().is_none());
+ }
+
+ /// An event deleted on the phone leaves this library at the next pass over its window —
+ /// the ghost of one is what a delete here then failed on — while an event outside the
+ /// window, which Apple was not asked about, is left alone.
+ #[tokio::test]
+ async fn an_event_deleted_elsewhere_leaves_but_one_outside_the_window_stays() {
+ let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/ca/startup"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "Collection": [{ "guid": "cal-1", "title": "Work" }]
+ })))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/ca/events"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "Event": [] })))
+ .mount(&server)
+ .await;
+ let mut library = Library::in_memory().unwrap();
+ library
+ .put_calendars(&[quince_core::calendar::Calendar {
+ guid: "cal-1".into(),
+ title: "Work".into(),
+ ..Default::default()
+ }])
+ .unwrap();
+ let at = |s: &str| s.parse::<jiff::Timestamp>().unwrap().as_second();
+ let ev = |guid: &str, start: i64| quince_core::calendar::Event {
+ guid: guid.into(),
+ calendar_guid: "cal-1".into(),
+ title: guid.into(),
+ starts_at: start,
+ ends_at: start + 3600,
+ ..Default::default()
+ };
+ library
+ .put_events(&[
+ ev("deleted", at("2026-09-12T09:00:00Z")),
+ ev("later", at("2026-11-02T09:00:00Z")),
+ ])
+ .unwrap();
+
+ let http = reqwest::Client::new();
+ calendar(
+ &http,
+ &server.uri(),
+ vec![],
+ &mut library,
+ "2026-09-01",
+ "2026-09-30",
+ "UTC",
+ )
+ .await
+ .unwrap();
+ assert!(
+ library.event("deleted").unwrap().is_none(),
+ "deleted on the phone, gone here"
+ );
+ assert!(
+ library.event("later").unwrap().is_some(),
+ "outside the window, untouched"
+ );
+ }
+
/// Some accounts get collections from /ca/startup and nothing else; the events arrive
/// only from /ca/events. A sync that trusts startup alone silently shows an empty
/// calendar.