1use khive_storage::note::{Note, NoteFilter, NoteStatusSelector};
4use khive_storage::{PageRequest, SeekCursor};
5use uuid::Uuid;
6
7use crate::{KhiveRuntime, MailboxView, NamespaceToken, RuntimeError, RuntimeResult};
8
9impl KhiveRuntime {
10 pub async fn list_notes_filtered(
11 &self,
12 token: &NamespaceToken,
13 mut filter: NoteFilter,
14 limit: u32,
15 offset: u32,
16 ) -> RuntimeResult<Vec<Note>> {
17 filter = filter.with_default_note_status(NoteStatusSelector::Active);
18 filter.namespaces = token
19 .visible_namespace_strs()
20 .into_iter()
21 .map(str::to_owned)
22 .collect();
23 Ok(self
24 .notes(token)?
25 .query_notes_filtered_count_free(
26 token.namespace().as_str(),
27 &filter,
28 PageRequest {
29 limit,
30 offset: offset.into(),
31 },
32 )
33 .await?
34 .items)
35 }
36
37 pub async fn list_notes_filtered_after(
38 &self,
39 token: &NamespaceToken,
40 mut filter: NoteFilter,
41 after: Option<Uuid>,
42 limit: u32,
43 ) -> RuntimeResult<(Vec<Note>, Option<Uuid>)> {
44 filter = filter.with_default_note_status(NoteStatusSelector::Active);
45 let store = self.notes(token)?;
46 let after = match after {
47 None => None,
48 Some(id) => {
49 let note = self
50 .get_note_including_deleted(token, id)
51 .await?
52 .ok_or_else(|| RuntimeError::NotFound(format!("note cursor {id}")))?;
53 Self::ensure_namespace_visible(¬e.namespace, token)?;
54 if filter
58 .mailbox
59 .as_ref()
60 .is_some_and(|scope| !MailboxView::scope_permits_message_note(scope, ¬e))
61 {
62 return Err(RuntimeError::NotFound(format!("note cursor {id}")));
63 }
64 let sequence = store.note_sequence(id).await?.ok_or_else(|| {
65 RuntimeError::Internal(format!(
66 "note cursor {id} has no insertion-sequence ledger row"
67 ))
68 })?;
69 Some(SeekCursor { sequence, id })
70 }
71 };
72 filter.namespaces = token
73 .visible_namespace_strs()
74 .into_iter()
75 .map(str::to_owned)
76 .collect();
77 let page = store
78 .query_notes_filtered_after(token.namespace().as_str(), &filter, after, limit)
79 .await?;
80 Ok((page.items, page.next_after.map(|cursor| cursor.id)))
81 }
82}
83
84#[cfg(test)]
85mod archive_visibility_tests {
86 use super::*;
87 use crate::Namespace;
88 use std::time::Duration;
89
90 async fn fixture() -> (KhiveRuntime, NamespaceToken, [Uuid; 4]) {
91 let runtime = KhiveRuntime::memory().unwrap();
92 let token = runtime.authorize(Namespace::local()).unwrap();
93 let mut ids = Vec::new();
94 for (index, status) in ["archived", "active", "archived", "active"]
95 .into_iter()
96 .enumerate()
97 {
98 let mut note = Note::new("local", "observation", format!("archive probe {index}"));
99 note.status = status.into();
100 note.created_at = 40 - index as i64 * 10;
101 note.updated_at = note.created_at;
102 note.properties = Some(
104 serde_json::json!({"status": if status == "active" { "archived" } else { "active" }}),
105 );
106 ids.push(note.id);
107 runtime
108 .notes(&token)
109 .unwrap()
110 .upsert_note(note)
111 .await
112 .unwrap();
113 }
114 (runtime, token, ids.try_into().unwrap())
115 }
116
117 fn ids(notes: &[Note]) -> Vec<Uuid> {
118 notes.iter().map(|note| note.id).collect()
119 }
120
121 #[tokio::test]
122 async fn ordinary_runtime_lists_default_active_before_offset_and_seek() {
123 tokio::time::timeout(Duration::from_secs(10), async {
124 let (runtime, token, note_ids) = fixture().await;
125 for offset in [0, 1] {
126 let expected = vec![note_ids[if offset == 0 { 1 } else { 3 }]];
127 assert_eq!(
128 ids(&runtime.list_notes(&token, None, 1, offset).await.unwrap()),
129 expected,
130 "ordinary Runtime list must default to the active column before pagination"
131 );
132 assert_eq!(
133 ids(&runtime
134 .list_notes_filtered(&token, NoteFilter::default(), 1, offset)
135 .await
136 .unwrap()),
137 expected
138 );
139 }
140 let (first, next) = runtime
141 .list_notes_after(&token, None, None, 1)
142 .await
143 .unwrap();
144 assert_eq!(ids(&first), vec![note_ids[1]]);
145 assert_eq!(next, Some(note_ids[1]));
146 let (filtered, filtered_next) = runtime
147 .list_notes_filtered_after(&token, NoteFilter::default(), None, 1)
148 .await
149 .unwrap();
150 assert_eq!(ids(&filtered), vec![note_ids[1]]);
151 assert_eq!(filtered_next, Some(note_ids[1]));
152 let (after, _) = runtime
154 .list_notes_after(&token, None, Some(note_ids[0]), 10)
155 .await
156 .unwrap();
157 assert_eq!(ids(&after), vec![note_ids[1], note_ids[3]]);
158 let (after, _) = runtime
159 .list_notes_filtered_after(&token, NoteFilter::default(), Some(note_ids[0]), 10)
160 .await
161 .unwrap();
162 assert_eq!(ids(&after), vec![note_ids[1], note_ids[3]]);
163 assert_eq!(
164 runtime
165 .get_note_including_deleted(&token, note_ids[0])
166 .await
167 .unwrap()
168 .unwrap()
169 .status,
170 "archived"
171 );
172 })
173 .await
174 .expect("bounded actual runtime list regression");
175 }
176
177 #[tokio::test]
178 async fn runtime_explicit_archived_and_any_preserve_raw_population_and_column_status() {
179 tokio::time::timeout(Duration::from_secs(10), async {
180 let (runtime, token, note_ids) = fixture().await;
181 for (selector, expected) in [
182 (NoteStatusSelector::Archived, vec![note_ids[0], note_ids[2]]),
183 (NoteStatusSelector::Any, note_ids.to_vec()),
184 ] {
185 let filter = NoteFilter {
186 note_status: Some(selector),
187 ..Default::default()
188 };
189 assert_eq!(
190 ids(&runtime
191 .list_notes_filtered(&token, filter.clone(), 10, 0)
192 .await
193 .unwrap()),
194 expected
195 );
196 let (notes, _) = runtime
197 .list_notes_filtered_after(&token, filter, None, 10)
198 .await
199 .unwrap();
200 assert_eq!(ids(¬es), expected);
201 }
202 let raw = runtime
203 .notes(&token)
204 .unwrap()
205 .query_notes_count_free(
206 "local",
207 None,
208 PageRequest {
209 limit: 10,
210 offset: 0,
211 },
212 )
213 .await
214 .unwrap();
215 assert_eq!(
216 raw.items.len(),
217 4,
218 "raw operational read remains status-neutral"
219 );
220 assert_eq!(raw.total, None, "count-free contract is unchanged");
221 let active = runtime.list_notes(&token, None, 10, 0).await.unwrap();
222 assert!(active.iter().all(|note| note.status == "active"
223 && note.properties.as_ref().unwrap()["status"] == "archived"));
224 })
225 .await
226 .expect("bounded explicit-selector regression");
227 }
228
229 #[tokio::test]
230 async fn active_list_defaults_preserve_the_visible_namespace_set() {
231 tokio::time::timeout(Duration::from_secs(10), async {
232 let runtime = KhiveRuntime::memory().unwrap();
233 for namespace in ["archive-a", "archive-b", "archive-c"] {
234 let token = runtime
235 .authorize(Namespace::parse(namespace).unwrap())
236 .unwrap();
237 for status in ["active", "archived"] {
238 let mut note = Note::new(namespace, "observation", status);
239 note.status = status.into();
240 runtime
241 .notes(&token)
242 .unwrap()
243 .upsert_note(note)
244 .await
245 .unwrap();
246 }
247 }
248 let token = runtime
249 .authorize_with_visibility(
250 Namespace::parse("archive-a").unwrap(),
251 vec![Namespace::parse("archive-b").unwrap()],
252 )
253 .unwrap();
254 let filter = NoteFilter {
255 namespaces: vec!["archive-c".into()],
256 ..Default::default()
257 };
258 let lists = [
259 runtime.list_notes(&token, None, 10, 0).await.unwrap(),
260 runtime
261 .list_notes_filtered(&token, filter.clone(), 10, 0)
262 .await
263 .unwrap(),
264 runtime
265 .list_notes_after(&token, None, None, 10)
266 .await
267 .unwrap()
268 .0,
269 runtime
270 .list_notes_filtered_after(&token, filter, None, 10)
271 .await
272 .unwrap()
273 .0,
274 ];
275 for notes in lists {
276 assert_eq!(notes.len(), 2);
277 assert!(notes.iter().all(|note| note.status == "active"
278 && matches!(note.namespace.as_str(), "archive-a" | "archive-b")));
279 }
280 let all = runtime
281 .list_notes_filtered(
282 &token,
283 NoteFilter {
284 note_status: Some(NoteStatusSelector::Any),
285 ..Default::default()
286 },
287 10,
288 0,
289 )
290 .await
291 .unwrap();
292 assert_eq!(all.len(), 4);
293 assert!(all.iter().all(|note| note.namespace != "archive-c"));
294 })
295 .await
296 .expect("bounded visible-namespace regression");
297 }
298}