Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
A folder of five thousand notes stops sending all five thousand bodies
Yashwanth Kamireddi52ac32796f88
diff --git a/crates/quince-core/src/notes.rs b/crates/quince-core/src/notes.rsindex 8b5dc96..c59c39e 100644--- a/crates/quince-core/src/notes.rs+++ b/crates/quince-core/src/notes.rs@@ -163,6 +163,23 @@ impl Library {Ok(())}+ /// One note's text, whole.+ ///+ /// Fetched for the note being read rather than for every note in the list, which is what+ /// keeps opening a folder of five thousand cheap.+ pub fn note_body(&self, guid: &str) -> Result<Option<String>> {+ let mut stmt = self+ .conn+ .prepare("SELECT body FROM notes WHERE guid = ?1")?;+ let mut rows = stmt.query(params![guid])?;+ match rows.next()? {+ // The note exists but has nothing in it — which is not the same as no such note,+ // and the difference decides whether an editor may open.+ Some(row) => Ok(Some(row.get::<_, Option<String>>(0)?.unwrap_or_default())),+ None => Ok(None),+ }+ }+pub fn note_folders(&self) -> Result<Vec<NoteFolder>> {let mut stmt = self.conn.prepare("SELECT guid, title, sort_order, parent_guid@@ -183,9 +200,20 @@ impl Library {////// Passing `None` is the "All Notes" view, which in Apple's app means every note that/// has not been deleted. Including the deleted ones put them in both places at once.+ /// The notes in a folder, without their bodies.+ ///+ /// A list of notes shows a title, a line of preview and a date. Carrying every body along+ /// with that is what the plan calls an unbounded payload: five thousand ordinary notes+ /// come to nearly ten megabytes, and all of it crosses into the window on every refresh to+ /// draw text nobody reads. The body of the one note being read is fetched on its own.+ ///+ /// The preview is a truncation, so it is put in `snippet` — which is only ever displayed —+ /// and never in `body`, which is what an editor would save back. A body that came back+ /// short and got written would take the rest of the note with it.pub fn notes_in(&self, folder_guid: Option<&str>) -> Result<Vec<Note>> {let mut stmt = self.conn.prepare(- "SELECT guid, folder_guid, title, snippet, body, locked, pinned,+ "SELECT guid, folder_guid, title,+ coalesce(snippet, substr(body, 1, 200)), locked, pinned,created_at, modified_at, editable, etagFROM notesWHERE (?1 IS NULL AND (folder_guid IS NULL OR folder_guid != ?2))@@ -198,13 +226,14 @@ impl Library {folder_guid: row.get(1)?,title: row.get(2)?,snippet: row.get(3)?,- body: row.get(4)?,- locked: row.get::<_, i64>(5)? != 0,- pinned: row.get::<_, i64>(6)? != 0,- created_at: row.get(7)?,- modified_at: row.get(8)?,- editable: row.get::<_, i64>(9)? != 0,- etag: row.get(10)?,+ // Never a truncation. Absent, so nothing can save a short one back.+ body: None,+ locked: row.get::<_, i64>(4)? != 0,+ pinned: row.get::<_, i64>(5)? != 0,+ created_at: row.get(6)?,+ modified_at: row.get(7)?,+ editable: row.get::<_, i64>(8)? != 0,+ etag: row.get(9)?,})})?;Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)@@ -359,3 +388,88 @@ mod tests {assert!(lib.notes_in(None).unwrap()[0].locked);}}++/// Reading a lot of notes without carrying every word of them.+#[cfg(test)]+mod body_tests {+ use super::*;++ fn stored() -> Library {+ let mut lib = Library::in_memory().unwrap();+ lib.put_note_folders(&[NoteFolder {+ guid: "F1".into(),+ title: "Notes".into(),+ sort_order: 0,+ parent_guid: None,+ }])+ .unwrap();+ lib.put_notes(&[+ Note {+ guid: "N1".into(),+ folder_guid: Some("F1".into()),+ title: "Long one".into(),+ snippet: None,+ body: Some("x".repeat(5_000)),+ locked: false,+ editable: true,+ pinned: false,+ created_at: Some(1),+ modified_at: Some(2),+ etag: None,+ },+ Note {+ guid: "N2".into(),+ folder_guid: Some("F1".into()),+ title: "Empty one".into(),+ snippet: None,+ body: None,+ locked: false,+ editable: true,+ pinned: false,+ created_at: Some(1),+ modified_at: Some(1),+ etag: None,+ },+ ])+ .unwrap();+ lib+ }++ /// The danger this guards: a body that came back short and got saved would take the rest+ /// of the note with it. The list carries no body at all, so nothing can.+ #[test]+ fn a_listed_note_carries_no_body_to_save_back() {+ for note in stored().notes_in(None).unwrap() {+ assert_eq!(+ note.body, None,+ "{} must not carry a body into a list",+ note.title+ );+ }+ }++ /// A preview still has to appear, and it is a truncation — so it goes where only display+ /// reads it.+ #[test]+ fn a_note_with_no_snippet_still_previews() {+ let listed = stored().notes_in(None).unwrap();+ let long = listed.iter().find(|n| n.guid == "N1").unwrap();+ assert_eq!(long.snippet.as_deref().map(str::len), Some(200));+ }++ /// The note being read gets its text whole.+ #[test]+ fn the_body_is_fetched_in_full_for_one_note() {+ let lib = stored();+ assert_eq!(lib.note_body("N1").unwrap().map(|b| b.len()), Some(5_000));+ }++ /// A note with nothing in it is not the same as no such note, and the difference decides+ /// whether an editor may open at all.+ #[test]+ fn an_empty_note_and_a_missing_one_are_told_apart() {+ let lib = stored();+ assert_eq!(lib.note_body("N2").unwrap(), Some(String::new()));+ assert_eq!(lib.note_body("nothing-like-this").unwrap(), None);+ }+}diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rsindex 4356259..d9093a2 100644--- a/crates/quince-icloud/src/notes.rs+++ b/crates/quince-icloud/src/notes.rs@@ -487,7 +487,15 @@ mod tests {let stored = library.notes_in(None).unwrap();assert_eq!(stored[0].title, "UNIT 1: Testing");- assert_eq!(stored[0].body.as_deref(), Some("the body"));+ // A listed note carries no body — the text is stored, and asked for on its own when+ // the note is opened. Carrying it here is what made a folder of thousands slow, and+ // a body that came back short and got saved would take the rest of the note with it.+ assert_eq!(stored[0].body, None);+ assert_eq!(+ library.note_body(&stored[0].guid).unwrap().as_deref(),+ Some("the body"),+ "the text arrived and was stored"+ );assert_eq!(library.note_folders().unwrap()[0].title, "Notes");}diff --git a/probe/examples/at_scale.rs b/probe/examples/at_scale.rsnew file mode 100644index 0000000..4563301--- /dev/null+++ b/probe/examples/at_scale.rs@@ -0,0 +1,160 @@+//! Throwaway: what a big account costs. Local only — no network, no real data.+use quince_core::contacts::{Contact, ContactMethod};+use quince_core::notes::{Note, NoteFolder};+use quince_core::reminders::{Reminder, ReminderList};+use std::time::Instant;++fn main() -> Result<(), Box<dyn std::error::Error>> {+ let dir = std::env::temp_dir().join(format!("quince-scale-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir)?;+ let mut lib = quince_core::Library::open(&dir)?;++ // A heavy but entirely ordinary account.+ let lists: Vec<ReminderList> = (0..50)+ .map(|i| ReminderList {+ guid: format!("List/{i}"),+ title: format!("List {i}"),+ colour: None,+ ctag: None,+ sort_order: i,+ enabled: true,+ })+ .collect();+ lib.put_reminder_lists(&lists)?;++ let reminders: Vec<Reminder> = (0..20_000)+ .map(|i| Reminder {+ guid: format!("Reminder/{i}"),+ list_guid: format!("List/{}", i % 50),+ title: format!("Something to do number {i}"),+ notes: Some("with a note on it".into()),+ due_at: Some(1_789_000_000 + i * 60),+ completed_at: if i % 3 == 0 {+ Some(1_789_000_000)+ } else {+ None+ },+ priority: i % 4,+ flagged: i % 7 == 0,+ parent_guid: None,+ recur_frequency: None,+ recur_interval: None,+ etag: Some(format!("e{i}")),+ raw: None,+ })+ .collect();+ let t = Instant::now();+ lib.put_reminders(&reminders)?;+ println!(+ "storing 20,000 reminders {:>7} ms",+ t.elapsed().as_millis()+ );++ let contacts: Vec<Contact> = (0..5_000)+ .map(|i| Contact {+ guid: format!("C{i}"),+ first_name: Some(format!("Person{i}")),+ middle_name: None,+ photo_url: None,+ photo_signature: None,+ photo_crop: None,+ last_name: Some(format!("Surname{}", i % 900)),+ company: None,+ is_company: false,+ birthday: None,+ notes: None,+ etag: None,+ methods: vec![+ ContactMethod {+ kind: "phone".into(),+ label: Some("mobile".into()),+ value: format!("+9199{i:08}"),+ },+ ContactMethod {+ kind: "email".into(),+ label: None,+ value: format!("p{i}@example.invalid"),+ },+ ],+ })+ .collect();+ let t = Instant::now();+ lib.put_contacts(&contacts)?;+ println!(+ "storing 5,000 contacts {:>7} ms",+ t.elapsed().as_millis()+ );++ lib.put_note_folders(&[NoteFolder {+ guid: "F1".into(),+ title: "Notes".into(),+ sort_order: 0,+ parent_guid: None,+ }])?;+ let notes: Vec<Note> = (0..5_000)+ .map(|i| Note {+ guid: format!("N{i}"),+ folder_guid: Some("F1".into()),+ title: format!("Note {i}"),+ snippet: Some("a snippet".into()),+ body: Some("x".repeat(2_000)),+ locked: false,+ editable: true,+ pinned: i % 50 == 0,+ created_at: Some(1_789_000_000),+ modified_at: Some(1_789_000_000 + i),+ etag: None,+ })+ .collect();+ let t = Instant::now();+ lib.put_notes(¬es)?;+ println!(+ "storing 5,000 notes {:>7} ms",+ t.elapsed().as_millis()+ );++ println!("\n--- what the window asks for on every screen ---");+ let t = Instant::now();+ let n = lib.contacts(None)?.len();+ println!(+ "contacts(None) {n:>6} rows {:>7} ms",+ t.elapsed().as_millis()+ );++ let t = Instant::now();+ let n = lib.contacts(Some("Surname7"))?.len();+ println!(+ "contacts(search) {n:>6} rows {:>7} ms",+ t.elapsed().as_millis()+ );++ let t = Instant::now();+ let n = lib.notes_in(None)?.len();+ let bytes: usize = lib+ .notes_in(None)?+ .iter()+ .map(|x| x.body.as_deref().unwrap_or("").len())+ .sum();+ println!(+ "notes_in(None) {n:>6} rows {:>7} ms {} KB of bodies",+ t.elapsed().as_millis(),+ bytes / 1024+ );++ let t = Instant::now();+ let n = lib.reminders_in("List/3", true)?.len();+ println!(+ "reminders_in(one list) {n:>6} rows {:>7} ms",+ t.elapsed().as_millis()+ );++ let t = Instant::now();+ let n = lib.reminders_due_between(0, i64::MAX)?.len();+ println!(+ "reminders_due_between {n:>6} rows {:>7} ms",+ t.elapsed().as_millis()+ );++ std::fs::remove_dir_all(&dir).ok();+ Ok(())+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 2288028..0f73372 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -677,6 +677,17 @@ async fn note_by_guid(data: &State<'_, Data>, guid: &str) -> Result<Note, String/// Writes to Apple first and re-reads after, so the editor never shows a version Apple has/// not accepted. A note whose document cannot be rewritten safely is refused with the/// reason rather than flattened.+/// One note's text, whole.+///+/// A list of notes carries no bodies — five thousand ordinary ones come to nearly ten+/// megabytes, and sending that into the window on every refresh to draw text nobody reads is+/// the unbounded payload the plan rules out. The note being read asks for its own.+#[tauri::command]+async fn note_body(guid: String, data: State<'_, Data>) -> UiResult<Option<String>> {+ let library = data.0.lock().await;+ library.note_body(&guid).map_err(|e| e.to_string())+}+#[tauri::command]async fn note_save(guid: String,@@ -1397,6 +1408,7 @@ fn main() {reminder_list_rename,reminder_list_delete,note_folders,+ note_body,note_save,note_create,note_delete,diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex dbbd5df..f380ae3 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -86,6 +86,14 @@ export const api = {noteFolders: () => invoke<NoteFolder[]>("note_folders"),notesIn: (folderGuid: string | null) => invoke<Note[]>("notes_in", { folderGuid }),+ /**+ * One note's text, whole. Null when there is no such note any more.+ *+ * A listed note carries no body — the list only draws a title and a line of preview, and+ * carrying every word of every note into the window on each refresh is what makes a folder+ * of thousands slow.+ */+ noteBody: (guid: string) => invoke<string | null>("note_body", { guid }),noteSave: (guid: string, body: string) => invoke<void>("note_save", { guid, body }),noteCreate: (folderGuid: string | null, body: string) =>invoke<string>("note_create", { folderGuid, body }),diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsxindex 7e38220..7def71c 100644--- a/src/screens/NotesView.tsx+++ b/src/screens/NotesView.tsx@@ -19,11 +19,11 @@ const when = (seconds: number | null) => {};/** True when the body already opens with the title, which is Apple's usual case. */-function bodyRepeatsTitle(note: Note): boolean {- const body = note.body?.trimStart();- if (!body) return false;+function bodyRepeatsTitle(note: Note, body: string | null): boolean {+ const text = body?.trimStart();+ if (!text) return false;const title = note.title.trim();- return title.length > 0 && body.startsWith(title);+ return title.length > 0 && text.startsWith(title);}export function NotesView() {@@ -107,7 +107,40 @@ export function NotesView() {setSaved(false);}, [openGuid]);- const dirty = draft !== null && open !== null && draft !== (open.body ?? "");+ /**+ * The open note's text, fetched on its own.+ *+ * A listed note carries no body, so this is the only thing that knows what the note says —+ * and until it arrives nothing may be edited or saved. An editor showing an empty box over+ * a note whose text had not loaded yet would write that emptiness back the moment anyone+ * touched it, which is the worst thing this app could do.+ *+ * Kept beside the guid it belongs to, so a slow fetch for one note can never be mistaken+ * for the body of the next one opened.+ */+ const [loadedBody, setLoadedBody] = useState<{ guid: string; text: string } | null>(null);++ useEffect(() => {+ if (!openGuid) return setLoadedBody(null);+ let cancelled = false;+ setLoadedBody((current) => (current?.guid === openGuid ? current : null));+ api+ .noteBody(openGuid)+ .then((text) => {+ if (!cancelled && text !== null) setLoadedBody({ guid: openGuid, text });+ })+ .catch((e) => {+ if (!cancelled) setError(messageOf(e));+ });+ return () => {+ cancelled = true;+ };+ }, [openGuid, revision]);++ /** What the open note says, or null while that is still unknown. */+ const body = open && loadedBody?.guid === open.guid ? loadedBody.text : null;++ const dirty = draft !== null && body !== null && draft !== body;/*** Saving is not something anyone should have to remember.@@ -131,13 +164,14 @@ export function NotesView() {}, [write]);const type = useCallback(- (body: string) => {- if (!open) return;- setDraft(body);+ (typed: string) => {+ // Nothing may be typed into a note whose text has not arrived.+ if (!open || body === null) return;+ setDraft(typed);setSaved(false);- pending.current = body === (open.body ?? "") ? null : { guid: open.guid, body };+ pending.current = typed === body ? null : { guid: open.guid, body: typed };},- [open]+ [open, body]);// A pause in typing is the signal. Long enough not to write on every keystroke, short@@ -301,7 +335,7 @@ export function NotesView() {<span className="note-row-meta"><span className="note-row-when">{when(note.modifiedAt)}</span><span className="note-row-snippet">- {note.locked ? "Locked" : note.snippet || note.body?.slice(0, 60) || "No text"}+ {note.locked ? "Locked" : note.snippet?.slice(0, 60) || "No text"}</span></span></button>@@ -337,7 +371,7 @@ export function NotesView() {<>{/* Apple derives a note's title from its first line, so the body alreadycontains it. Rendering both shows the same sentence twice. */}- {!bodyRepeatsTitle(open) && <h2>{open.title}</h2>}+ {!bodyRepeatsTitle(open, body) && <h2>{open.title}</h2>}<div className="note-bar"><p className="note-when">@@ -360,11 +394,20 @@ export function NotesView() {</div></div>- {open.editable ? (+ {/*+ * Nothing is shown to type into until the note's own text has arrived. An+ * empty box over a note whose body had not loaded would write that emptiness+ * back the moment anyone touched it.+ */}+ {body === null ? (+ <p className="note-loading" aria-live="polite">+ Opening…+ </p>+ ) : open.editable ? (<textareaclassName="note-text"aria-label={`Body of ${open.title}`}- value={draft ?? open.body ?? ""}+ value={draft ?? body}onChange={(e) => type(e.target.value)}onKeyDown={(e) => {// Nothing needs saving by hand, but the reflex deserves an answer.@@ -378,7 +421,7 @@ export function NotesView() {/>) : (<>- <pre className="note-text">{open.body ?? ""}</pre>+ <pre className="note-text">{body}</pre><p className="note-readonly">This note holds formatting Quince can't rewrite without losing it, so itstays read-only here. Editing it on an Apple device is safe.diff --git a/src/styles/app.css b/src/styles/app.cssindex b8ab8b0..92d2cde 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -2285,3 +2285,11 @@ button.cal-day-item:hover { background: color-mix(in srgb, var(--sheet) 92%, varcolor: var(--text-2);font-size: var(--t-13);}++/* Shown while a note's own text is being fetched, in place of anything typeable. */+.note-loading {+ margin: 0;+ padding: 10px 2px;+ color: var(--text-3);+ font-size: var(--t-13);+}