Skip to main content

notes_tools/store/
notes_store.rs

1use std::{path::Path, str::FromStr, sync::Arc};
2
3use agent_storage::{FamilyId, FamilyStore, UserId};
4use chrono::{DateTime, Utc};
5use rusqlite::{Connection, OptionalExtension, params};
6use tokio::sync::Mutex;
7use uuid::Uuid;
8
9use crate::{NewNote, Note, NoteSummary, NotesError, UpdateNote};
10
11#[derive(Clone)]
12pub struct NotesStore {
13    connection: Arc<Mutex<Connection>>,
14    families: Arc<dyn FamilyStore>,
15}
16
17impl NotesStore {
18    pub fn open(
19        path: impl AsRef<Path>,
20        families: Arc<dyn FamilyStore>,
21    ) -> Result<Self, NotesError> {
22        let connection = Connection::open(path).map_err(storage)?;
23        connection
24            .busy_timeout(std::time::Duration::from_secs(5))
25            .map_err(storage)?;
26        connection
27            .execute_batch(include_str!("../../migrations/0001_notes.sql"))
28            .map_err(storage)?;
29        Ok(Self {
30            connection: Arc::new(Mutex::new(connection)),
31            families,
32        })
33    }
34
35    pub async fn create(&self, note: NewNote) -> Result<Note, NotesError> {
36        let owner = parse_user(&note.owner_id)?;
37        if note.title.trim().is_empty() {
38            return Err(NotesError::Invalid("title must not be empty".into()));
39        }
40        if let Some(id) = &note.family_id {
41            self.require_family_member(owner, id).await?;
42        }
43        let id = Uuid::new_v4().to_string();
44        let now = Utc::now().to_rfc3339();
45        let connection = self.connection.lock().await;
46        connection.execute(
47            "INSERT INTO notes(id, owner_id, family_id, title, content, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)",
48            params![id, note.owner_id, note.family_id, note.title.trim(), note.content, now],
49        ).map_err(storage)?;
50        load_note(&connection, &id)?.ok_or(NotesError::NotFound)
51    }
52
53    pub async fn list_accessible(
54        &self,
55        user_id: &str,
56        selected_family: Option<&str>,
57    ) -> Result<Vec<NoteSummary>, NotesError> {
58        let user = parse_user(user_id)?;
59        let family_ids = self.accessible_families(user, selected_family).await?;
60        let connection = self.connection.lock().await;
61        let mut result = Vec::new();
62        let mut statement = connection.prepare("SELECT id, owner_id, family_id, title, created_at, updated_at FROM notes WHERE owner_id = ?1 ORDER BY updated_at DESC, id").map_err(storage)?;
63        let rows = statement
64            .query_map([user_id], summary_row)
65            .map_err(storage)?;
66        for row in rows {
67            result.push(row.map_err(storage)?);
68        }
69        drop(statement);
70        for family_id in family_ids {
71            let mut statement = connection.prepare("SELECT id, owner_id, family_id, title, created_at, updated_at FROM notes WHERE family_id = ?1 ORDER BY updated_at DESC, id").map_err(storage)?;
72            let rows = statement
73                .query_map([family_id.to_string()], summary_row)
74                .map_err(storage)?;
75            for row in rows {
76                result.push(row.map_err(storage)?);
77            }
78        }
79        result.sort_by(|a, b| {
80            b.updated_at
81                .cmp(&a.updated_at)
82                .then_with(|| a.id.cmp(&b.id))
83        });
84        result.dedup_by(|a, b| a.id == b.id);
85        Ok(result)
86    }
87
88    pub async fn get_accessible(
89        &self,
90        user_id: &str,
91        selected_family: Option<&str>,
92        note_id: &str,
93    ) -> Result<Note, NotesError> {
94        let user = parse_user(user_id)?;
95        let family_ids = self.accessible_families(user, selected_family).await?;
96        let connection = self.connection.lock().await;
97        let note = load_note(&connection, note_id)?.ok_or(NotesError::NotFound)?;
98        if note.owner_id != user_id
99            && !note
100                .family_id
101                .as_ref()
102                .is_some_and(|id| family_ids.iter().any(|family| family.to_string() == *id))
103        {
104            return Err(NotesError::NotFound);
105        }
106        Ok(note)
107    }
108
109    pub async fn update_owned(
110        &self,
111        user_id: &str,
112        note_id: &str,
113        update: UpdateNote,
114    ) -> Result<Note, NotesError> {
115        let user = parse_user(user_id)?;
116        if let Some(Some(family_id)) = &update.family_id {
117            self.require_family_member(user, family_id).await?;
118        }
119        let connection = self.connection.lock().await;
120        let mut note = load_note(&connection, note_id)?
121            .filter(|note| note.owner_id == user_id)
122            .ok_or(NotesError::NotFound)?;
123        if let Some(title) = update.title {
124            if title.trim().is_empty() {
125                return Err(NotesError::Invalid("title must not be empty".into()));
126            }
127            note.title = title.trim().to_owned();
128        }
129        if let Some(content) = update.content {
130            note.content = content;
131        }
132        if let Some(family_id) = update.family_id {
133            note.family_id = family_id;
134        }
135        note.updated_at = Utc::now();
136        connection.execute("UPDATE notes SET family_id=?1, title=?2, content=?3, updated_at=?4 WHERE id=?5 AND owner_id=?6",
137            params![note.family_id, note.title, note.content, note.updated_at.to_rfc3339(), note_id, user_id]).map_err(storage)?;
138        Ok(note)
139    }
140
141    pub async fn delete_owned(&self, user_id: &str, note_id: &str) -> Result<(), NotesError> {
142        parse_user(user_id)?;
143        let connection = self.connection.lock().await;
144        let changed = connection
145            .execute(
146                "DELETE FROM notes WHERE id=?1 AND owner_id=?2",
147                params![note_id, user_id],
148            )
149            .map_err(storage)?;
150        if changed == 0 {
151            return Err(NotesError::NotFound);
152        }
153        Ok(())
154    }
155
156    async fn require_family_member(&self, user: UserId, value: &str) -> Result<(), NotesError> {
157        let id = FamilyId::from_str(value)
158            .map_err(|_| NotesError::Invalid("invalid family id".into()))?;
159        let families = self
160            .families
161            .list_families(user)
162            .await
163            .map_err(|e| NotesError::Family(e.to_string()))?;
164        if families.iter().any(|family| family.id == id) {
165            Ok(())
166        } else {
167            Err(NotesError::NotFound)
168        }
169    }
170
171    async fn accessible_families(
172        &self,
173        user: UserId,
174        selected: Option<&str>,
175    ) -> Result<Vec<FamilyId>, NotesError> {
176        let families = self
177            .families
178            .list_families(user)
179            .await
180            .map_err(|e| NotesError::Family(e.to_string()))?;
181        if let Some(selected) = selected {
182            let id = FamilyId::from_str(selected)
183                .map_err(|_| NotesError::Invalid("invalid family id in trusted context".into()))?;
184            if !families.iter().any(|family| family.id == id) {
185                return Err(NotesError::NotFound);
186            }
187            Ok(vec![id])
188        } else {
189            Ok(families.into_iter().map(|family| family.id).collect())
190        }
191    }
192}
193
194fn summary_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<NoteSummary> {
195    Ok(NoteSummary {
196        id: row.get(0)?,
197        owner_id: row.get(1)?,
198        family_id: row.get(2)?,
199        title: row.get(3)?,
200        created_at: DateTime::parse_from_rfc3339(&row.get::<_, String>(4)?)
201            .map(|v| v.with_timezone(&Utc))
202            .map_err(|e| {
203                rusqlite::Error::FromSqlConversionFailure(
204                    4,
205                    rusqlite::types::Type::Text,
206                    Box::new(e),
207                )
208            })?,
209        updated_at: DateTime::parse_from_rfc3339(&row.get::<_, String>(5)?)
210            .map(|v| v.with_timezone(&Utc))
211            .map_err(|e| {
212                rusqlite::Error::FromSqlConversionFailure(
213                    5,
214                    rusqlite::types::Type::Text,
215                    Box::new(e),
216                )
217            })?,
218    })
219}
220fn parse_user(value: &str) -> Result<UserId, NotesError> {
221    UserId::from_str(value).map_err(|_| NotesError::Invalid("invalid user id".into()))
222}
223fn storage(error: rusqlite::Error) -> NotesError {
224    NotesError::Storage(error.to_string())
225}
226fn parse_time(value: &str) -> Result<DateTime<Utc>, NotesError> {
227    DateTime::parse_from_rfc3339(value)
228        .map(|v| v.with_timezone(&Utc))
229        .map_err(|e| NotesError::Storage(e.to_string()))
230}
231fn load_note(connection: &Connection, id: &str) -> Result<Option<Note>, NotesError> {
232    connection.query_row("SELECT id, owner_id, family_id, title, content, created_at, updated_at FROM notes WHERE id=?1", [id], |row| {
233        Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, Option<String>>(2)?, row.get::<_, String>(3)?, row.get::<_, String>(4)?, row.get::<_, String>(5)?, row.get::<_, String>(6)?))
234    }).optional().map_err(storage)?.map(|(id, owner_id, family_id, title, content, created_at, updated_at)| Ok(Note {
235        id, owner_id, family_id, title, content, created_at: parse_time(&created_at)?, updated_at: parse_time(&updated_at)?
236    })).transpose()
237}