1use std::sync::Arc;
18
19use waratah_exec::{TermDict, TermId};
20use waratah_storage::{EncodedTerm, TextSubjectRow};
21
22use crate::error::ComputeError;
23
24const DECODE_CHUNK: usize = 8_192;
27
28#[derive(Debug)]
30pub struct TextSubjectWindow {
31 dict: Arc<TermDict>,
32 with_graph: bool,
35 subjects: Vec<TermId>,
37 graphs: Vec<TermId>,
39}
40
41impl TextSubjectWindow {
42 pub fn len(&self) -> usize {
44 self.subjects.len()
45 }
46
47 pub fn is_empty(&self) -> bool {
49 self.subjects.is_empty()
50 }
51
52 pub fn has_graph(&self) -> bool {
54 self.with_graph
55 }
56
57 pub fn stored_ids(&self) -> usize {
59 self.subjects.len() + self.graphs.len()
60 }
61
62 pub fn contains_subject(&self, subject: &EncodedTerm) -> bool {
68 self.dict
69 .peek(subject)
70 .is_some_and(|id| self.subjects.binary_search(&id).is_ok())
71 }
72
73 pub fn graphs_for(&self, subject: &EncodedTerm) -> Result<Vec<EncodedTerm>, ComputeError> {
78 if !self.with_graph {
79 return Ok(Vec::new());
80 }
81 let Some(id) = self.dict.peek(subject) else {
82 return Ok(Vec::new());
83 };
84 let start = self.subjects.partition_point(|candidate| *candidate < id);
85 let mut raw = Vec::new();
86 for index in start..self.subjects.len() {
87 if self.subjects[index] != id {
88 break;
89 }
90 raw.push(self.graphs[index].0);
91 }
92 let mut decoded = vec![None; raw.len()];
93 self.dict.get_many(&raw, &mut decoded);
94 let mut graphs = Vec::with_capacity(decoded.len());
95 for graph in decoded {
96 let Some(graph) = graph else {
97 return Err(ComputeError::Internal(
98 "text subject window holds a graph id that does not resolve in the \
99 query dictionary"
100 .into(),
101 ));
102 };
103 graphs.push(graph);
104 }
105 Ok(graphs)
106 }
107
108 pub fn rows(&self) -> TextSubjectRows<'_> {
116 TextSubjectRows {
117 window: self,
118 offset: 0,
119 buffer: Vec::new().into_iter(),
120 }
121 }
122}
123
124pub struct TextSubjectRows<'a> {
126 window: &'a TextSubjectWindow,
127 offset: usize,
128 buffer: std::vec::IntoIter<Result<TextSubjectRow, ComputeError>>,
129}
130
131impl Iterator for TextSubjectRows<'_> {
132 type Item = Result<TextSubjectRow, ComputeError>;
133
134 fn next(&mut self) -> Option<Self::Item> {
135 loop {
136 if let Some(row) = self.buffer.next() {
137 return Some(row);
138 }
139 if self.offset >= self.window.len() {
140 return None;
141 }
142 let end = (self.offset + DECODE_CHUNK).min(self.window.len());
143 let ids: Vec<u32> = self.window.subjects[self.offset..end]
144 .iter()
145 .map(|id| id.0)
146 .collect();
147 let mut subjects = vec![None; ids.len()];
148 self.window.dict.get_many(&ids, &mut subjects);
149 let graphs = if self.window.with_graph {
150 let ids: Vec<u32> = self.window.graphs[self.offset..end]
151 .iter()
152 .map(|id| id.0)
153 .collect();
154 let mut graphs = vec![None; ids.len()];
155 self.window.dict.get_many(&ids, &mut graphs);
156 graphs
157 } else {
158 Vec::new()
159 };
160 let mut chunk = Vec::with_capacity(subjects.len());
161 for (index, subject) in subjects.into_iter().enumerate() {
162 let Some(subject) = subject else {
163 chunk.push(Err(ComputeError::Internal(
168 "text subject window holds a subject id that does not resolve in the \
169 query dictionary"
170 .into(),
171 )));
172 continue;
173 };
174 let graph = if self.window.with_graph {
175 let Some(graph) = graphs.get(index).and_then(|graph| graph.clone()) else {
176 chunk.push(Err(ComputeError::Internal(
177 "text subject window holds a graph id that does not resolve in the \
178 query dictionary"
179 .into(),
180 )));
181 continue;
182 };
183 Some(graph)
184 } else {
185 None
186 };
187 chunk.push(Ok(TextSubjectRow { subject, graph }));
188 }
189 self.offset = end;
190 self.buffer = chunk.into_iter();
191 }
192 }
193}
194
195#[derive(Debug)]
206pub struct TextSubjectWindowBuilder {
207 dict: Arc<TermDict>,
208 with_graph: bool,
209 rows: Vec<(TermId, TermId)>,
210}
211
212impl TextSubjectWindowBuilder {
213 pub fn new(dict: Arc<TermDict>, with_graph: bool) -> Self {
215 Self {
216 dict,
217 with_graph,
218 rows: Vec::new(),
219 }
220 }
221
222 pub fn len(&self) -> usize {
224 self.rows.len()
225 }
226
227 pub fn is_empty(&self) -> bool {
229 self.rows.is_empty()
230 }
231
232 pub fn push(&mut self, row: TextSubjectRow) -> Result<(), ComputeError> {
234 let subject = self.dict.intern(row.subject)?;
235 let graph = if self.with_graph {
239 let Some(graph) = row.graph else {
240 return Err(ComputeError::Internal(
241 "text subject resolve returned a row without its requested graph column".into(),
242 ));
243 };
244 self.dict.intern(graph)?
245 } else {
246 TermId::UNBOUND
247 };
248 self.rows.push((subject, graph));
249 Ok(())
250 }
251
252 pub fn finish(mut self) -> TextSubjectWindow {
254 self.rows
255 .sort_unstable_by_key(|(subject, graph)| (*subject, *graph));
256 let mut subjects = Vec::with_capacity(self.rows.len());
257 let mut graphs = if self.with_graph {
258 Vec::with_capacity(self.rows.len())
259 } else {
260 Vec::new()
261 };
262 for (subject, graph) in self.rows {
263 subjects.push(subject);
264 if self.with_graph {
265 graphs.push(graph);
266 }
267 }
268 TextSubjectWindow {
269 dict: self.dict,
270 with_graph: self.with_graph,
271 subjects,
272 graphs,
273 }
274 }
275}
276
277#[cfg(test)]
278mod tests {
279 use super::*;
280 use waratah_storage::NamedNode;
281
282 fn subject(n: usize) -> EncodedTerm {
283 EncodedTerm::from(&NamedNode::new(format!("http://ex/s{n}")).unwrap())
284 }
285
286 fn graph(n: usize) -> EncodedTerm {
287 EncodedTerm::from(&NamedNode::new(format!("http://ex/g{n}")).unwrap())
288 }
289
290 fn row(s: usize, g: Option<usize>) -> TextSubjectRow {
291 TextSubjectRow {
292 subject: subject(s),
293 graph: g.map(graph),
294 }
295 }
296
297 fn build(with_graph: bool, rows: Vec<TextSubjectRow>) -> TextSubjectWindow {
298 let mut builder =
299 TextSubjectWindowBuilder::new(std::sync::Arc::new(TermDict::new()), with_graph);
300 for row in rows {
301 builder.push(row).expect("row interns");
302 }
303 builder.finish()
304 }
305
306 #[test]
307 fn interned_window_answers_membership_and_graphs() {
308 let window = build(
312 true,
313 vec![row(1, Some(1)), row(1, Some(2)), row(2, Some(1))],
314 );
315 assert_eq!(window.len(), 3);
316 assert!(window.has_graph());
317 assert_eq!(
318 window.stored_ids(),
319 6,
320 "one subject id + one graph id per row"
321 );
322 assert!(window.contains_subject(&subject(1)));
323 assert!(window.contains_subject(&subject(2)));
324 assert!(
325 !window.contains_subject(&subject(3)),
326 "a foreign term is absent"
327 );
328 assert_eq!(
329 window.graphs_for(&subject(1)).unwrap(),
330 vec![graph(1), graph(2)]
331 );
332 assert_eq!(window.graphs_for(&subject(2)).unwrap(), vec![graph(1)]);
333 assert!(window.graphs_for(&subject(3)).unwrap().is_empty());
334 let rows: Vec<TextSubjectRow> = window
335 .rows()
336 .collect::<Result<Vec<_>, _>>()
337 .expect("every id resolves");
338 assert_eq!(rows.len(), 3);
339 assert_eq!(rows[0], row(1, Some(1)));
340 assert_eq!(rows[1], row(1, Some(2)));
341 assert_eq!(rows[2], row(2, Some(1)));
342 }
343
344 #[test]
345 fn subject_only_window_drops_a_stray_graph() {
346 let window = build(false, vec![row(1, Some(7))]);
349 assert_eq!(window.len(), 1);
350 assert!(!window.has_graph());
351 assert_eq!(window.stored_ids(), 1);
352 assert!(window.graphs_for(&subject(1)).unwrap().is_empty());
353 assert_eq!(window.rows().next().unwrap().unwrap().graph, None);
354 }
355
356 #[test]
357 fn a_missing_graph_column_is_an_error() {
358 let mut builder = TextSubjectWindowBuilder::new(std::sync::Arc::new(TermDict::new()), true);
359 let err = builder
360 .push(row(1, None))
361 .expect_err("graph column required");
362 assert!(
363 err.to_string()
364 .contains("without its requested graph column"),
365 "{err}"
366 );
367 }
368
369 #[test]
370 fn rows_decode_across_the_chunk_boundary() {
371 let count = DECODE_CHUNK + 1;
374 let window = build(false, (0..count).map(|n| row(n, None)).collect());
375 let rows: Vec<TextSubjectRow> = window
376 .rows()
377 .collect::<Result<Vec<_>, _>>()
378 .expect("every id resolves");
379 assert_eq!(rows.len(), count, "the chunk seam drops nothing");
380 assert_eq!(rows.first().unwrap().subject, subject(0));
381 assert_eq!(rows[DECODE_CHUNK].subject, subject(DECODE_CHUNK));
382 assert_eq!(rows.last().unwrap().subject, subject(count - 1));
383 }
384
385 #[test]
391 fn a_dangling_subject_id_is_an_error_not_a_dropped_row() {
392 let window = TextSubjectWindow {
393 dict: std::sync::Arc::new(TermDict::new()),
394 with_graph: false,
395 subjects: vec![TermId(9_999)],
396 graphs: Vec::new(),
397 };
398 let row = window.rows().next().expect("one row");
399 assert!(
400 matches!(
401 &row,
402 Err(ComputeError::Internal(message)) if message.contains("subject id")
403 ),
404 "{row:?}"
405 );
406 }
407
408 #[test]
409 fn a_dangling_graph_id_is_an_error_not_a_dropped_graph() {
410 let dict = std::sync::Arc::new(TermDict::new());
411 let subject_id = dict.intern(subject(1)).expect("subject interns");
412 let window = TextSubjectWindow {
413 dict,
414 with_graph: true,
415 subjects: vec![subject_id],
416 graphs: vec![TermId(9_999)],
417 };
418 let error = window
420 .graphs_for(&subject(1))
421 .expect_err("the graph id must resolve");
422 assert!(
423 matches!(&error, ComputeError::Internal(message) if message.contains("graph id")),
424 "{error}"
425 );
426 let row = window.rows().next().expect("one row");
427 assert!(
428 matches!(
429 &row,
430 Err(ComputeError::Internal(message)) if message.contains("graph id")
431 ),
432 "{row:?}"
433 );
434 }
435}