concept-store 0.1.65

The disk-backed columnar concept and description store
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Read-only access to a built artifact.
//!
//! Every method is a point read: one key, one record, decoded with a typed
//! error. Scans belong to the offline build, never to a request path.

use std::path::{Path, PathBuf};

use concept_graph::ordinal::Ordinal;
use redb::{ReadOnlyDatabase, ReadableDatabase, ReadableTable, TableHandle};

use crate::column::{Column, ColumnError};
use crate::record::{self, Concept, Designation, PropertyValue, RecordError};
use crate::tables;

/// A failure while opening or reading an artifact.
#[derive(Debug, thiserror::Error)]
pub enum StoreError {
    /// The database could not be opened or read.
    #[error("cannot open the artifact at {path}")]
    Open {
        /// The artifact.
        path: PathBuf,
        /// The underlying error.
        #[source]
        source: redb::DatabaseError,
    },
    /// A transaction failed.
    #[error("cannot begin a read transaction")]
    Transaction(#[from] redb::TransactionError),
    /// A table is missing or has another type.
    #[error("cannot open table {table}")]
    Table {
        /// The table name.
        table: String,
        /// The underlying error.
        #[source]
        source: redb::TableError,
    },
    /// A read failed inside the database.
    #[error("storage read failed")]
    Storage(#[from] redb::StorageError),
    /// The artifact was written by another layout version.
    #[error("artifact layout {found:?}, expected {expected:?}")]
    Layout {
        /// The layout found, if any.
        found: Option<String>,
        /// The layout this build reads.
        expected: &'static str,
    },
    /// A packed column is not the layout this build reads.
    #[error("the {column} column does not read")]
    Column {
        /// The column name.
        column: String,
        /// The underlying error.
        #[source]
        source: ColumnError,
    },
    /// A stored record is damaged.
    #[error("damaged record in table {table} at key {key}")]
    Record {
        /// The table name.
        table: String,
        /// The key, rendered.
        key: String,
        /// The underlying error.
        #[source]
        source: RecordError,
    },
}

/// An opened artifact.
pub struct Store {
    path: PathBuf,
    db: ReadOnlyDatabase,
    /// The concepts, read once at open. An ordinal is a position, so this
    /// column answers by slicing where a b-tree would search.
    concepts: Column,
    /// The preferred designations the build chose, per concept, so choosing a
    /// display reads no table at all.
    displays: Column,
}

impl std::fmt::Debug for Store {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Store")
            .field("path", &self.path)
            .finish_non_exhaustive()
    }
}

macro_rules! open_table {
    ($txn:expr, $def:expr) => {
        $txn.open_table($def).map_err(|source| StoreError::Table {
            table: $def.name().to_owned(),
            source,
        })
    };
}

impl Store {
    /// Opens the artifact at `path` read-only and checks its layout version.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the file cannot be opened, is not an
    /// artifact of this layout, or a table is missing.
    pub fn open(path: &Path) -> Result<Self, StoreError> {
        let db = ReadOnlyDatabase::open(path).map_err(|source| StoreError::Open {
            path: path.to_path_buf(),
            source,
        })?;
        let mut store = Self {
            path: path.to_path_buf(),
            db,
            concepts: Column::default(),
            displays: Column::default(),
        };
        let layout = store.meta(tables::META_LAYOUT)?;
        if layout.as_deref() != Some(tables::LAYOUT_VERSION) {
            return Err(StoreError::Layout {
                found: layout,
                expected: tables::LAYOUT_VERSION,
            });
        }
        store.concepts = store.column(tables::COLUMN_CONCEPTS)?;
        store.displays = store.column(tables::COLUMN_DISPLAYS)?;
        Ok(store)
    }

    /// The packed column named `name`, read and checked once.
    fn column(&self, name: &str) -> Result<Column, StoreError> {
        let txn = self.db.begin_read()?;
        let table = open_table!(txn, tables::COLUMNS)?;
        let Some(bytes) = table.get(name)? else {
            return Ok(Column::default());
        };
        Column::read(bytes.value()).map_err(|source| StoreError::Column {
            column: name.to_owned(),
            source,
        })
    }

    /// The artifact's path.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// An artifact-level fact by key.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the database cannot be read.
    pub fn meta(&self, key: &str) -> Result<Option<String>, StoreError> {
        let txn = self.db.begin_read()?;
        let table = open_table!(txn, tables::META)?;
        Ok(table.get(key)?.map(|v| v.value().to_owned()))
    }

    /// The ordinal of a native code, if the version has it.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the database cannot be read.
    pub fn ordinal(&self, code: &str) -> Result<Option<Ordinal>, StoreError> {
        let txn = self.db.begin_read()?;
        let table = open_table!(txn, tables::CODES)?;
        Ok(table.get(code)?.map(|v| Ordinal::new(v.value())))
    }

    /// The concept at `ordinal`, if any.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the database cannot be read or the record is damaged.
    pub fn concept(&self, ordinal: Ordinal) -> Result<Option<Concept>, StoreError> {
        self.concepts
            .get(ordinal)
            .map(|bytes| Self::decode_concept(ordinal, bytes))
            .transpose()
    }

    /// The native code at `ordinal`, borrowed from the column.
    ///
    /// The code is the first field of the record, so this reads one length
    /// and one string and copies nothing.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the code is damaged.
    pub fn code(&self, ordinal: Ordinal) -> Result<Option<&str>, StoreError> {
        self.concepts
            .get(ordinal)
            .map(|bytes| {
                record::code(bytes).map_err(|source| StoreError::Record {
                    table: tables::COLUMN_CONCEPTS.to_owned(),
                    key: ordinal.to_string(),
                    source,
                })
            })
            .transpose()
    }

    /// Decodes one concept record, naming the ordinal it came from.
    fn decode_concept(ordinal: Ordinal, bytes: &[u8]) -> Result<Concept, StoreError> {
        Concept::decode(bytes).map_err(|source| StoreError::Record {
            table: tables::COLUMN_CONCEPTS.to_owned(),
            key: ordinal.to_string(),
            source,
        })
    }

    /// The concepts at `ordinals`, in the order given, `None` where the store
    /// has no such concept.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when a record is damaged.
    pub fn concepts(
        &self,
        ordinals: impl IntoIterator<Item = Ordinal>,
    ) -> Result<Vec<Option<Concept>>, StoreError> {
        ordinals
            .into_iter()
            .map(|ordinal| self.concept(ordinal))
            .collect()
    }

    /// The native codes at `ordinals`, in the order given, `None` where the
    /// store has no such concept.
    ///
    /// One read transaction answers the whole batch, and each record is
    /// decoded only as far as its code. A caller that names concepts by code
    /// (the children of one concept, the members of a page) pays neither the
    /// transaction per concept nor the rest of the record.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the database cannot be read or a code is
    /// damaged.
    pub fn codes(
        &self,
        ordinals: impl IntoIterator<Item = Ordinal>,
    ) -> Result<Vec<Option<String>>, StoreError> {
        ordinals
            .into_iter()
            .map(|ordinal| Ok(self.code(ordinal)?.map(ToOwned::to_owned)))
            .collect()
    }

    /// Every designation of `ordinal`, in index order.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the database cannot be read or a record is damaged.
    pub fn designations(&self, ordinal: Ordinal) -> Result<Vec<Designation>, StoreError> {
        let txn = self.db.begin_read()?;
        let table = open_table!(txn, tables::DESIGNATIONS)?;
        let mut out = Vec::new();
        for entry in table.range((ordinal.index(), 0)..(ordinal.index(), u32::MAX))? {
            let (key, value) = entry?;
            out.push(
                Designation::decode(value.value()).map_err(|source| StoreError::Record {
                    table: tables::DESIGNATIONS.name().to_owned(),
                    key: format!("{:?}", key.value()),
                    source,
                })?,
            );
        }
        Ok(out)
    }

    /// The acceptability ordinal of a designation in a language reference set.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the database cannot be read.
    pub fn acceptability(
        &self,
        ordinal: Ordinal,
        designation: u32,
        language_refset: u32,
    ) -> Result<Option<u32>, StoreError> {
        let txn = self.db.begin_read()?;
        let table = open_table!(txn, tables::ACCEPTABILITY)?;
        Ok(table
            .get((ordinal.index(), designation, language_refset))?
            .map(|v| v.value()))
    }

    /// The preferred designation of `ordinal` for a language reference set and
    /// designation use, as the build precomputed it.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the database cannot be read or the record is damaged.
    pub fn preferred(
        &self,
        ordinal: Ordinal,
        language_refset: u32,
        use_ordinal: u32,
    ) -> Result<Option<Designation>, StoreError> {
        let txn = self.db.begin_read()?;
        let preferred = open_table!(txn, tables::PREFERRED)?;
        let Some(index) = preferred.get((ordinal.index(), language_refset, use_ordinal))? else {
            return Ok(None);
        };
        let designations = open_table!(txn, tables::DESIGNATIONS)?;
        designations
            .get((ordinal.index(), index.value()))?
            .map(|v| {
                Designation::decode(v.value()).map_err(|source| StoreError::Record {
                    table: tables::DESIGNATIONS.name().to_owned(),
                    key: format!("({ordinal}, {})", index.value()),
                    source,
                })
            })
            .transpose()
    }

    /// The display of `ordinal` from the first of `language_refsets` whose
    /// language `accept` admits.
    ///
    /// The build chose one display per reference set, so this reads the column
    /// and stops at the first language the caller wants; no table is touched.
    /// The reference sets are asked in the order given, which is what decides
    /// the answer when several carry the same language.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the column is damaged.
    pub fn display(
        &self,
        ordinal: Ordinal,
        language_refsets: impl IntoIterator<Item = u32>,
        accept: impl Fn(&str) -> bool,
    ) -> Result<Option<String>, StoreError> {
        let Some(bytes) = self.displays.get(ordinal) else {
            return Ok(None);
        };
        let damaged = |source| StoreError::Record {
            table: tables::COLUMN_DISPLAYS.to_owned(),
            key: ordinal.to_string(),
            source,
        };
        for refset in language_refsets {
            let Some((language, term)) = record::Displays::find(bytes, refset).map_err(damaged)?
            else {
                continue;
            };
            if accept(&language) {
                return Ok(Some(term));
            }
        }
        Ok(None)
    }

    /// Every property of `ordinal`, as `(property key ordinal, values)`, in key order.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the database cannot be read or a record is damaged.
    pub fn properties(
        &self,
        ordinal: Ordinal,
    ) -> Result<Vec<(u32, Vec<PropertyValue>)>, StoreError> {
        let txn = self.db.begin_read()?;
        let table = open_table!(txn, tables::PROPERTIES)?;
        let mut out = Vec::new();
        for entry in table.range((ordinal.index(), 0)..(ordinal.index(), u32::MAX))? {
            let (key, value) = entry?;
            let values =
                PropertyValue::decode_list(value.value()).map_err(|source| StoreError::Record {
                    table: tables::PROPERTIES.name().to_owned(),
                    key: format!("{:?}", key.value()),
                    source,
                })?;
            out.push((key.value().1, values));
        }
        Ok(out)
    }

    /// A vocabulary entry: the name of a property key, designation use,
    /// language reference set, or acceptability ordinal.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the database cannot be read.
    pub fn vocabulary(&self, kind: Vocabulary, ordinal: u32) -> Result<Option<String>, StoreError> {
        let txn = self.db.begin_read()?;
        let table = open_table!(txn, kind.table())?;
        Ok(table.get(ordinal)?.map(|v| v.value().to_owned()))
    }

    /// The ordinal of a vocabulary name, by scanning the (small) vocabulary table.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the database cannot be read.
    pub fn vocabulary_ordinal(
        &self,
        kind: Vocabulary,
        name: &str,
    ) -> Result<Option<u32>, StoreError> {
        let txn = self.db.begin_read()?;
        let table = open_table!(txn, kind.table())?;
        for entry in table.iter()? {
            let (key, value) = entry?;
            if value.value() == name {
                return Ok(Some(key.value()));
            }
        }
        Ok(None)
    }
}

/// The small name tables of an artifact.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Vocabulary {
    /// Property key names.
    PropertyKeys,
    /// Designation use codes.
    DesignationUses,
    /// Language reference set codes.
    LanguageRefsets,
    /// Acceptability codes.
    Acceptabilities,
}

impl Vocabulary {
    fn table(self) -> redb::TableDefinition<'static, u32, &'static str> {
        match self {
            Self::PropertyKeys => tables::PROPERTY_KEYS,
            Self::DesignationUses => tables::DESIGNATION_USES,
            Self::LanguageRefsets => tables::LANGUAGE_REFSETS,
            Self::Acceptabilities => tables::ACCEPTABILITIES,
        }
    }
}