oxirs_core/lib.rs
1//! # OxiRS Core - RDF and SPARQL Foundation
2//!
3//! [](https://github.com/cool-japan/oxirs/releases)
4//! [](https://docs.rs/oxirs-core)
5//!
6//! **Status**: Production Release (v0.3.1)
7//! **Stability**: Public APIs are stabilizing. Production-ready for RDF/SPARQL core operations.
8//!
9//! ## Overview
10//!
11//! `oxirs-core` is a high-performance, zero-dependency Rust-native RDF data model and SPARQL foundation
12//! for the OxiRS semantic web platform. It provides the fundamental types, traits, and operations that
13//! all other OxiRS crates build upon.
14//!
15//! This crate is designed for:
16//! - Building semantic web applications in Rust
17//! - Processing large-scale knowledge graphs with minimal memory overhead
18//! - Developing SPARQL query engines and triple stores
19//! - Creating RDF-based data pipelines and transformations
20//!
21//! ## Key Features
22//!
23//! ### Core RDF Support
24//! - **RDF 1.2 Compliance** - Full implementation of the RDF 1.2 data model
25//! - **Multiple Serialization Formats** - Support for Turtle, N-Triples, TriG, N-Quads, RDF/XML, JSON-LD
26//! - **Named Graphs** - Full quad support with named graph management
27//! - **RDF-star** - Support for quoted triples (statement reification)
28//!
29//! ### Performance & Scalability
30//! - **Memory Efficiency** - Arena-based allocators and optimized data structures
31//! - **Concurrent Operations** - Lock-free data structures for high-throughput workloads
32//! - **Parallel Processing** - SIMD and multi-threaded query execution
33//! - **Zero-Copy Parsing** - Streaming parsers with minimal allocations
34//!
35//! ### SPARQL Foundation
36//! - **SPARQL 1.1 Query** - SELECT, CONSTRUCT, ASK, DESCRIBE queries
37//! - **SPARQL 1.1 Update** - INSERT, DELETE, LOAD, CLEAR operations
38//! - **SPARQL 1.2 Features** - Enhanced property paths, aggregations, and functions
39//! - **Federation** - SERVICE clause support for distributed queries
40//!
41//! ### Storage & Persistence
42//! - **Pluggable Backends** - In-memory and disk-based storage options
43//! - **Persistent Storage** - Automatic N-Quads serialization for durability
44//! - **Indexed Access** - Multi-index support (SPO, POS, OSP) for fast pattern matching
45//! - **Transaction Support** - ACID-compliant transactions for data integrity
46//!
47//! ### Production Features
48//! - **Monitoring & Metrics** - Built-in performance instrumentation via SciRS2
49//! - **Error Handling** - Rich error types with context and suggestions
50//! - **Health Checks** - Circuit breakers and resource quotas
51//! - **Benchmarking** - Comprehensive benchmark suite for performance validation
52//!
53//! ## Quick Start
54//!
55//! ### Creating a Store and Adding Data
56//!
57//! ```rust,no_run
58//! use oxirs_core::RdfStore;
59//! use oxirs_core::model::{NamedNode, Triple, Literal};
60//!
61//! # fn example() -> Result<(), oxirs_core::OxirsError> {
62//! // Create an in-memory RDF store
63//! let mut store = RdfStore::new()?;
64//!
65//! // Create RDF terms
66//! let alice = NamedNode::new("http://example.org/alice")?;
67//! let knows = NamedNode::new("http://xmlns.com/foaf/0.1/knows")?;
68//! let bob = NamedNode::new("http://example.org/bob")?;
69//! let name = NamedNode::new("http://xmlns.com/foaf/0.1/name")?;
70//!
71//! // Insert triples
72//! store.insert_triple(Triple::new(alice.clone(), knows, bob))?;
73//! store.insert_triple(Triple::new(alice, name, Literal::new("Alice")))?;
74//!
75//! println!("Store contains {} triples", store.len()?);
76//! # Ok(())
77//! # }
78//! ```
79//!
80//! ### Querying with Pattern Matching
81//!
82//! ```rust,no_run
83//! use oxirs_core::RdfStore;
84//! use oxirs_core::model::{NamedNode, Subject, Predicate};
85//!
86//! # fn query_example() -> Result<(), oxirs_core::OxirsError> {
87//! # let mut store = RdfStore::new()?;
88//! // Query all triples with a specific predicate
89//! let knows = NamedNode::new("http://xmlns.com/foaf/0.1/knows")?;
90//! let predicate = Predicate::NamedNode(knows);
91//!
92//! let triples = store.query_triples(None, Some(&predicate), None)?;
93//! for triple in triples {
94//! println!("{:?} knows {:?}", triple.subject(), triple.object());
95//! }
96//! # Ok(())
97//! # }
98//! ```
99//!
100//! ### Executing SPARQL Queries
101//!
102//! ```rust,no_run
103//! use oxirs_core::RdfStore;
104//!
105//! # fn sparql_example() -> Result<(), oxirs_core::OxirsError> {
106//! # let store = RdfStore::new()?;
107//! // Execute a SPARQL SELECT query
108//! let query = r#"
109//! PREFIX foaf: <http://xmlns.com/foaf/0.1/>
110//! SELECT ?name WHERE {
111//! ?person foaf:name ?name .
112//! }
113//! "#;
114//!
115//! let results = store.query(query)?;
116//! println!("Query returned {} results", results.len());
117//! # Ok(())
118//! # }
119//! ```
120//!
121//! ### Loading Data from Files
122//!
123//! ```rust,no_run
124//! use oxirs_core::RdfStore;
125//! use oxirs_core::parser::{Parser, RdfFormat};
126//! use std::fs;
127//!
128//! # fn load_example() -> Result<(), oxirs_core::OxirsError> {
129//! # let mut store = RdfStore::new()?;
130//! // Load RDF data from a Turtle file
131//! let content = fs::read_to_string("data.ttl")
132//! .map_err(|e| oxirs_core::OxirsError::Io(e.to_string()))?;
133//!
134//! let parser = Parser::new(RdfFormat::Turtle);
135//! let quads = parser.parse_str_to_quads(&content)?;
136//!
137//! for quad in quads {
138//! store.insert_quad(quad)?;
139//! }
140//!
141//! println!("Loaded {} quads from file", store.len()?);
142//! # Ok(())
143//! # }
144//! ```
145//!
146//! ### Persistent Storage
147//!
148//! ```rust,no_run
149//! use oxirs_core::RdfStore;
150//! use oxirs_core::model::{NamedNode, Triple, Literal};
151//!
152//! # fn persistent_example() -> Result<(), oxirs_core::OxirsError> {
153//! // Create a persistent store (data saved to disk)
154//! let mut store = RdfStore::open("./my_rdf_store")?;
155//!
156//! // Add data - automatically persisted
157//! let subject = NamedNode::new("http://example.org/resource")?;
158//! let predicate = NamedNode::new("http://purl.org/dc/terms/title")?;
159//! let object = Literal::new("My Resource");
160//!
161//! store.insert_triple(Triple::new(subject, predicate, object))?;
162//!
163//! // Data is automatically saved to disk on modifications
164//! println!("Data persisted to disk");
165//! # Ok(())
166//! # }
167//! ```
168//!
169//! ## Advanced Features
170//!
171//! ### Named Graphs (Quads)
172//!
173//! ```rust,no_run
174//! use oxirs_core::RdfStore;
175//! use oxirs_core::model::{NamedNode, Quad, GraphName, Literal};
176//!
177//! # fn quads_example() -> Result<(), oxirs_core::OxirsError> {
178//! # let mut store = RdfStore::new()?;
179//! // Create a quad with a named graph
180//! let graph = GraphName::NamedNode(NamedNode::new("http://example.org/graph1")?);
181//! let subject = NamedNode::new("http://example.org/subject")?;
182//! let predicate = NamedNode::new("http://example.org/predicate")?;
183//! let object = Literal::new("value");
184//!
185//! let quad = Quad::new(subject, predicate, object, graph);
186//! store.insert_quad(quad)?;
187//!
188//! // Query specific graph
189//! let graph_node = NamedNode::new("http://example.org/graph1")?;
190//! let quads = store.graph_quads(Some(&graph_node))?;
191//! println!("Graph contains {} quads", quads.len());
192//! # Ok(())
193//! # }
194//! ```
195//!
196//! ### Bulk Operations for Performance
197//!
198//! ```rust,ignore
199//! use oxirs_core::RdfStore;
200//! use oxirs_core::model::{NamedNode, Quad, Literal};
201//!
202//! # fn bulk_example() -> Result<(), oxirs_core::OxirsError> {
203//! # let mut store = RdfStore::new()?;
204//! // Prepare many quads for bulk insert
205//! let mut quads = Vec::new();
206//! for i in 0..1000 {
207//! let subject = NamedNode::new(&format!("http://example.org/item{}", i))?;
208//! let predicate = NamedNode::new("http://example.org/value")?;
209//! let object = Literal::new(&i.to_string());
210//! quads.push(Quad::from_triple(Triple::new(subject, predicate, object)));
211//! }
212//!
213//! // Bulk insert for better performance
214//! let ids = store.bulk_insert_quads(quads)?;
215//! println!("Inserted {} quads with IDs: {:?}", ids.len(), &ids[..5]);
216//! # Ok(())
217//! # }
218//! ```
219//!
220//! ## Module Organization
221//!
222//! - [`model`] - Core RDF data model types (IRI, Literal, Blank Node, Triple, Quad)
223//! - [`rdf_store`] - RDF store implementations with pluggable storage backends
224//! - [`parser`] - RDF parsers for multiple serialization formats
225//! - [`serializer`] - RDF serializers for exporting data
226//! - [`query`] - SPARQL query algebra and execution engine
227//! - [`sparql`] - SPARQL query processing and federation
228//! - [`storage`] - Storage backends (memory, disk, columnar)
229//! - [`indexing`] - Multi-index structures for fast pattern matching
230//! - [`concurrent`] - Lock-free data structures for concurrent access
231//! - [`optimization`] - Query optimization and execution planning
232//! - [`federation`] - SPARQL federation for distributed queries
233//! - [`production`] - Production features (monitoring, health checks, circuit breakers)
234//!
235//! ## Feature Flags
236//!
237//! - `serde` - Enable serialization support (default)
238//! - `parallel` - Enable parallel processing with rayon (default)
239//! - `simd` - Enable SIMD optimizations for x86_64
240//! - `async` - Enable async I/O support
241//! - `rdf-star` - Enable RDF-star (quoted triples) support
242//! - `sparql-12` - Enable SPARQL 1.2 features
243//!
244//! ## Performance Tips
245//!
246//! 1. **Use bulk operations** - `bulk_insert_quads()` is faster than individual inserts
247//! 2. **Choose the right backend** - UltraMemory backend for maximum performance
248//! 3. **Enable parallel feature** - Leverage multi-core CPUs for query execution
249//! 4. **Use indexed queries** - Pattern matching benefits from multi-index structures
250//! 5. **Profile with built-in metrics** - Use SciRS2 metrics for bottleneck identification
251//!
252//! ## API Stability
253//!
254//! As of Beta 1 (v0.3.0):
255//! - **Stable APIs**: Core RDF model types (`NamedNode`, `Literal`, `Triple`, `Quad`)
256//! - **Stable APIs**: Store operations (`RdfStore`, `insert`, `query`, `remove`)
257//! - **Stable APIs**: Parser and serializer interfaces
258//! - **Unstable APIs**: Advanced optimization features (may change)
259//! - **Experimental**: Consciousness, molecular, and quantum modules
260//!
261//! See [MIGRATION_GUIDE.md](../MIGRATION_GUIDE.md) for migration from alpha versions.
262//!
263//! ## Architecture
264//!
265//! For detailed architecture documentation, see [ARCHITECTURE.md](../ARCHITECTURE.md).
266//!
267//! ## Examples
268//!
269//! More examples are available in the `examples/` directory:
270//! - `basic_store.rs` - Basic store operations
271//! - `sparql_query.rs` - SPARQL query examples
272//! - `persistent_store.rs` - Persistent storage usage
273//! - `bulk_loading.rs` - High-performance bulk data loading
274//! - `federation.rs` - Federated SPARQL queries
275
276pub mod ai;
277pub mod api_surface; // Programmatic public-API surface tracking and stability enforcement
278pub mod assembler; // Jena Assembler vocabulary — RDF-based dataset/model configuration using ja:
279pub mod audit; // SOC2/GDPR-compliant structured audit trail (enterprise compliance)
280pub mod canon; // W3C RDF Dataset Normalization (URDNA2015) — canonical blank node naming
281pub mod concurrent;
282pub mod config;
283pub mod config_parser;
284pub mod config_types;
285pub mod config_types_core;
286pub mod config_types_network;
287pub mod config_types_storage;
288pub mod config_validation;
289pub mod consciousness; // Consciousness-inspired computing for intuitive query optimization
290pub mod crypto_provider; // Installs the Pure Rust rustls CryptoProvider as the process default (binaries + tests)
291pub mod distributed;
292pub mod federation;
293pub mod format;
294pub mod graph;
295pub mod indexing;
296pub mod interning;
297pub mod io;
298pub mod jsonld; // Re-enabled after fixing StringInterner method calls
299pub mod model;
300pub mod molecular;
301pub mod optimization;
302pub mod oxigraph_compat;
303pub mod parser;
304pub mod perf_sla; // Performance SLA harness: SloTarget, BenchmarkResult, assert_meets_slo
305pub mod production;
306pub mod quantum;
307pub mod query;
308pub mod rdf_store;
309pub mod rdfxml;
310pub mod serializer;
311pub mod sparql; // SPARQL query processing modules
312pub mod storage;
313pub mod store;
314pub mod transaction;
315pub mod vocab; // Oxigraph compatibility layer
316
317// Core abstractions for OxiRS ecosystem
318pub mod error;
319#[cfg(feature = "parallel")]
320pub mod parallel;
321pub mod platform;
322#[cfg(feature = "simd")]
323pub mod simd;
324pub mod simd_triple_matching; // SIMD-optimized triple pattern matching using SciRS2
325pub mod zero_copy_rdf; // Zero-copy RDF operations using SciRS2-core memory management
326
327// Query optimization enhancements
328pub mod cache; // Core-level query result cache with LRU and delta invalidation
329pub mod data_factory;
330pub mod named_graph; // Named Graph Management API (Jena Dataset-compatible)
331pub mod optimizer; // Runtime feedback-based adaptive query optimization
332pub mod provenance; // W3C PROV-O ontology support for RDF data provenance tracking
333pub mod rdf;
334pub mod sla; // Shared per-tenant SLA primitives (admission control, priority dispatcher)
335pub mod stability; // API stability markers and LTS compatibility matrix
336pub mod statistics; // Equi-depth histogram statistics for cardinality estimation
337pub mod view; // Incremental view maintenance with delta propagation // W3C DataFactory API for programmatic RDF term construction
338pub mod views; // Incremental view maintenance (new: DeltaChange-based API with IncrementalViewMaintainer) // RDF dataset utilities (diff, patch)
339
340// Re-export core types for convenience
341pub use model::*;
342pub use rdf_store::{ConcreteStore, RdfStore, Store};
343
344// Re-export URDNA2015 canonicalization API
345pub use canon::{canonicalize, Canonicalizer, QuadTerm as CanonQuadTerm, RdfQuad as CanonRdfQuad};
346
347// Re-export the Pure Rust crypto provider installer for ergonomic access.
348pub use crypto_provider::ensure_crypto_provider;
349pub use transaction::{
350 AcidTransaction, IsolationLevel, TransactionId, TransactionManager, TransactionState,
351};
352
353// Re-export Jena Assembler types at crate root for ergonomic access
354pub use assembler::{
355 from_turtle, AssemblerBuilder, AssemblerConfig, AssemblerError, DatasetConfig, GraphConfig,
356 StoreBackend,
357};
358
359/// Core error type for OxiRS operations
360#[derive(Debug, Clone, thiserror::Error)]
361pub enum OxirsError {
362 #[error("Store error: {0}")]
363 Store(String),
364 #[error("Query error: {0}")]
365 Query(String),
366 #[error("Parse error: {0}")]
367 Parse(String),
368 #[error("Serialization error: {0}")]
369 Serialize(String),
370 #[error("IO error: {0}")]
371 Io(String),
372 #[error("Concurrency error: {0}")]
373 ConcurrencyError(String),
374 #[error("Quantum computing error: {0}")]
375 QuantumError(String),
376 #[error("Molecular optimization error: {0}")]
377 MolecularError(String),
378 #[error("Neural-symbolic fusion error: {0}")]
379 NeuralSymbolicError(String),
380 #[error("Operation not supported: {0}")]
381 NotSupported(String),
382 #[error("Update error: {0}")]
383 Update(String),
384 #[error("Federation error: {0}")]
385 Federation(String),
386}
387
388impl From<std::io::Error> for OxirsError {
389 fn from(err: std::io::Error) -> Self {
390 OxirsError::Io(err.to_string())
391 }
392}
393
394// Additional error conversions
395impl From<oxicode::Error> for OxirsError {
396 fn from(err: oxicode::Error) -> Self {
397 OxirsError::Serialize(err.to_string())
398 }
399}
400
401impl From<serde_json::Error> for OxirsError {
402 fn from(err: serde_json::Error) -> Self {
403 OxirsError::Serialize(err.to_string())
404 }
405}
406
407// Note: DataFusion, Arrow, and Parquet error conversions removed
408// Add these features to Cargo.toml if these integrations are needed
409
410impl From<std::time::SystemTimeError> for OxirsError {
411 fn from(err: std::time::SystemTimeError) -> Self {
412 OxirsError::Io(format!("System time error: {err}"))
413 }
414}
415
416/// Result type alias for OxiRS operations
417pub type Result<T> = std::result::Result<T, OxirsError>;
418
419/// Version information for OxiRS Core
420pub const VERSION: &str = env!("CARGO_PKG_VERSION");
421
422/// Initialize OxiRS Core with default configuration
423pub fn init() -> Result<()> {
424 tracing::info!("Initializing OxiRS Core v{}", VERSION);
425 Ok(())
426}