oxiland 0.13.0

Embedded RDF datasets, SPARQL, persistence, and streaming I/O for Rust
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
use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex, RwLock};

use crate::Result;
use crate::factory;

/// A Redland-style feature value.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum FeatureValue {
    /// Textual feature value.
    String(String),
    /// Integer feature value.
    Integer(i64),
    /// Boolean feature value.
    Boolean(bool),
}

/// Shared IRI-keyed feature registry used by [`World`], models, parsers, and
/// serializers.
#[derive(Clone, Default)]
pub struct FeatureMap {
    inner: Arc<RwLock<HashMap<String, FeatureValue>>>,
}

impl fmt::Debug for FeatureMap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let map = self
            .inner
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        f.debug_map().entries(map.iter()).finish()
    }
}

impl FeatureMap {
    /// Creates an empty feature map.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Assigns a feature identified by an IRI.
    pub fn set(&self, iri: impl Into<String>, value: FeatureValue) {
        self.inner
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(iri.into(), value);
    }

    /// Returns a cloned feature value, if configured.
    #[must_use]
    pub fn get(&self, iri: &str) -> Option<FeatureValue> {
        self.inner
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(iri)
            .cloned()
    }
}

/// Feature registry used for Redland `librdf_storage_get/set_feature` mapping.
pub type StorageFeatures = FeatureMap;

/// Log severity for [`World`] logging (ADR-014).
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub enum LogLevel {
    /// Debug diagnostics.
    Debug,
    /// Informational messages.
    Info,
    /// Recoverable problems.
    #[default]
    Warn,
    /// Failures.
    Error,
}

impl LogLevel {
    /// Canonical lowercase name.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Debug => "debug",
            Self::Info => "info",
            Self::Warn => "warn",
            Self::Error => "error",
        }
    }
}

/// Logical log facility (ADR-014).
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum LogFacility {
    /// General / uncategorized.
    General,
    /// Model and storage operations.
    Model,
    /// Parser / serializer.
    Io,
    /// SPARQL query and update.
    Query,
    /// Utility helpers.
    Utility,
}

impl LogFacility {
    /// Canonical lowercase name.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::General => "general",
            Self::Model => "model",
            Self::Io => "io",
            Self::Query => "query",
            Self::Utility => "utility",
        }
    }
}

/// One log record delivered to handlers.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LogRecord {
    /// Severity.
    pub level: LogLevel,
    /// Facility.
    pub facility: LogFacility,
    /// Message text.
    pub message: String,
}

impl fmt::Display for LogRecord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "[{} {}] {}",
            self.level.name(),
            self.facility.name(),
            self.message
        )
    }
}

type LogHandler = Arc<dyn Fn(&LogRecord) + Send + Sync>;

/// Opaque embedding bridge token (ADR-026).
///
/// Safe Rust stores the value without dereferencing it. C ABI maps these to
/// `void *` handles for Raptor/Rasqal embedding parity.
pub type BridgeToken = usize;

/// Process-level configuration, feature registry, and logging (ADR-014).
///
/// Redland requires explicit world initialization. Oxiland resources are RAII
/// managed, so construction is sufficient and shutdown happens on drop.
///
/// `World` is cheap to clone: clones share the same feature registry, minimum
/// log level, log handler, and opaque bridge tokens. It is `Send` and `Sync`.
///
/// When the `tracing` Cargo feature is enabled, [`World::log`] also emits
/// `tracing` events, gated by the same minimum log level as the handler.
///
/// # Examples
///
/// ```
/// use oxiland::{FeatureValue, World};
///
/// let world = World::new();
/// world.set_feature("http://example.com/feature", FeatureValue::Boolean(true));
/// assert_eq!(
///     world.feature("http://example.com/feature"),
///     Some(FeatureValue::Boolean(true))
/// );
/// ```
#[derive(Clone, Default)]
pub struct World {
    features: FeatureMap,
    min_level: Arc<RwLock<LogLevel>>,
    handler: Arc<Mutex<Option<LogHandler>>>,
    raptor: Arc<RwLock<Option<BridgeToken>>>,
    raptor_init: Arc<RwLock<Option<BridgeToken>>>,
    rasqal: Arc<RwLock<Option<BridgeToken>>>,
    rasqal_init: Arc<RwLock<Option<BridgeToken>>>,
}

impl fmt::Debug for World {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("World")
            .field(
                "min_level",
                &*self
                    .min_level
                    .read()
                    .unwrap_or_else(std::sync::PoisonError::into_inner),
            )
            .field(
                "handler_set",
                &self
                    .handler
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .is_some(),
            )
            .field("raptor_set", &self.raptor().is_some())
            .field("rasqal_set", &self.rasqal().is_some())
            .finish_non_exhaustive()
    }
}

impl World {
    /// Creates an initialized world.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Assigns a feature identified by an IRI.
    pub fn set_feature(&self, iri: impl Into<String>, value: FeatureValue) {
        self.features.set(iri, value);
    }

    /// Returns a cloned feature value, if configured.
    #[must_use]
    pub fn feature(&self, iri: &str) -> Option<FeatureValue> {
        self.features.get(iri)
    }

    /// Sets the minimum level that will be delivered to the handler.
    pub fn set_log_level(&self, level: LogLevel) {
        *self
            .min_level
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = level;
    }

    /// Returns the configured minimum log level.
    #[must_use]
    pub fn log_level(&self) -> LogLevel {
        *self
            .min_level
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Registers a log handler. Replaces any previous handler.
    ///
    /// Handlers are invoked synchronously in call order of [`World::log`]. When
    /// multiple logical callbacks are needed, compose them in a single handler.
    pub fn set_log_handler<F>(&self, handler: F)
    where
        F: Fn(&LogRecord) + Send + Sync + 'static,
    {
        *self
            .handler
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::new(handler));
    }

    /// Clears the log handler.
    pub fn clear_log_handler(&self) {
        *self
            .handler
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
    }

    /// Emits a log record when `level` is at least the configured minimum.
    pub fn log(&self, level: LogLevel, facility: LogFacility, message: impl Into<String>) {
        if level < self.log_level() {
            return;
        }
        let record = LogRecord {
            level,
            facility,
            message: message.into(),
        };
        #[cfg(feature = "tracing")]
        {
            match level {
                LogLevel::Debug => {
                    tracing::debug!(facility = record.facility.name(), "{}", record.message)
                }
                LogLevel::Info => {
                    tracing::info!(facility = record.facility.name(), "{}", record.message)
                }
                LogLevel::Warn => {
                    tracing::warn!(facility = record.facility.name(), "{}", record.message)
                }
                LogLevel::Error => {
                    tracing::error!(facility = record.facility.name(), "{}", record.message)
                }
            }
        }
        if let Some(handler) = self
            .handler
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .as_ref()
            .cloned()
        {
            handler(&record);
        }
    }

    /// Stores an opaque Raptor world bridge token (ADR-026).
    ///
    /// Prefer this over raw pointers: the safe crate never dereferences the
    /// token. C ABI maps it to `void *`.
    pub fn set_raptor(&self, token: Option<BridgeToken>) {
        *self
            .raptor
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = token;
    }

    /// Returns the opaque Raptor bridge token, if set.
    #[must_use]
    pub fn raptor(&self) -> Option<BridgeToken> {
        *self
            .raptor
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Alias for [`World::set_raptor`].
    pub fn set_raptor_bridge(&self, token: Option<BridgeToken>) {
        self.set_raptor(token);
    }

    /// Alias for [`World::raptor`].
    #[must_use]
    pub fn raptor_bridge(&self) -> Option<BridgeToken> {
        self.raptor()
    }

    /// Stores an opaque Raptor init-handler token (ADR-026).
    pub fn set_raptor_init_handler(&self, token: Option<BridgeToken>) {
        *self
            .raptor_init
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = token;
    }

    /// Returns the opaque Raptor init-handler token, if set.
    #[must_use]
    pub fn raptor_init_handler(&self) -> Option<BridgeToken> {
        *self
            .raptor_init
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Stores an opaque Rasqal world bridge token (ADR-026).
    pub fn set_rasqal(&self, token: Option<BridgeToken>) {
        *self
            .rasqal
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = token;
    }

    /// Returns the opaque Rasqal bridge token, if set.
    #[must_use]
    pub fn rasqal(&self) -> Option<BridgeToken> {
        *self
            .rasqal
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Stores an opaque Rasqal init-handler token (ADR-026).
    pub fn set_rasqal_init_handler(&self, token: Option<BridgeToken>) {
        *self
            .rasqal_init
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = token;
    }

    /// Returns the opaque Rasqal init-handler token, if set.
    #[must_use]
    pub fn rasqal_init_handler(&self) -> Option<BridgeToken> {
        *self
            .rasqal_init
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Registers a baseline parser factory (ADR-025).
    pub fn register_parser_factory(&self, name: &str) -> Result<()> {
        factory::register_parser_factory(name)
    }

    /// Registers a baseline serializer factory (ADR-025).
    pub fn register_serializer_factory(&self, name: &str) -> Result<()> {
        factory::register_serializer_factory(name)
    }

    /// Registers a baseline storage factory (ADR-025).
    pub fn register_storage_factory(&self, name: &str) -> Result<()> {
        factory::register_storage_factory(name)
    }

    /// Registers a baseline query factory (ADR-025).
    pub fn register_query_factory(&self, name: &str) -> Result<()> {
        factory::register_query_factory(name)
    }
}