Skip to main content

oxirs_core/
lib.rs

1//! # OxiRS Core - RDF and SPARQL Foundation
2//!
3//! [![Version](https://img.shields.io/badge/version-0.3.2-blue)](https://github.com/cool-japan/oxirs/releases)
4//! [![docs.rs](https://docs.rs/oxirs-core/badge.svg)](https://docs.rs/oxirs-core)
5//!
6//! **Status**: Production Release (v0.3.2)
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 encoding; // RFC 3986 percent-encoding utilities (pure-std replacement for the urlencoding crate)
293pub mod federation;
294pub mod format;
295pub mod graph;
296pub mod indexing;
297pub mod interning;
298pub mod io;
299pub mod jsonld; // Re-enabled after fixing StringInterner method calls
300pub mod model;
301pub mod molecular;
302pub mod optimization;
303pub mod oxigraph_compat;
304pub mod parser;
305pub mod perf_sla; // Performance SLA harness: SloTarget, BenchmarkResult, assert_meets_slo
306pub mod production;
307pub mod quantum;
308pub mod query;
309pub mod rdf_store;
310pub mod rdfxml;
311pub mod serializer;
312pub mod sparql; // SPARQL query processing modules
313pub mod storage;
314pub mod store;
315pub mod transaction;
316pub mod vocab; // Oxigraph compatibility layer
317
318// Core abstractions for OxiRS ecosystem
319pub mod error;
320#[cfg(feature = "parallel")]
321pub mod parallel;
322pub mod platform;
323#[cfg(feature = "simd")]
324pub mod simd;
325pub mod simd_triple_matching; // SIMD-optimized triple pattern matching using SciRS2
326pub mod zero_copy_rdf; // Zero-copy RDF operations using SciRS2-core memory management
327
328// Query optimization enhancements
329pub mod cache; // Core-level query result cache with LRU and delta invalidation
330pub mod data_factory;
331pub mod named_graph; // Named Graph Management API (Jena Dataset-compatible)
332pub mod optimizer; // Runtime feedback-based adaptive query optimization
333pub mod provenance; // W3C PROV-O ontology support for RDF data provenance tracking
334pub mod rdf;
335pub mod sla; // Shared per-tenant SLA primitives (admission control, priority dispatcher)
336pub mod stability; // API stability markers and LTS compatibility matrix
337pub mod statistics; // Equi-depth histogram statistics for cardinality estimation
338pub mod view; // Incremental view maintenance with delta propagation // W3C DataFactory API for programmatic RDF term construction
339pub mod views; // Incremental view maintenance (new: DeltaChange-based API with IncrementalViewMaintainer) // RDF dataset utilities (diff, patch)
340
341// Re-export core types for convenience
342pub use model::*;
343pub use rdf_store::{ConcreteStore, RdfStore, Store};
344
345// Re-export URDNA2015 canonicalization API
346pub use canon::{canonicalize, Canonicalizer, QuadTerm as CanonQuadTerm, RdfQuad as CanonRdfQuad};
347
348// Re-export the Pure Rust crypto provider installer for ergonomic access.
349pub use crypto_provider::ensure_crypto_provider;
350pub use transaction::{
351    AcidTransaction, IsolationLevel, TransactionId, TransactionManager, TransactionState,
352};
353
354// Re-export Jena Assembler types at crate root for ergonomic access
355pub use assembler::{
356    from_turtle, AssemblerBuilder, AssemblerConfig, AssemblerError, DatasetConfig, GraphConfig,
357    StoreBackend,
358};
359
360/// Core error type for OxiRS operations
361#[derive(Debug, Clone, thiserror::Error)]
362pub enum OxirsError {
363    #[error("Store error: {0}")]
364    Store(String),
365    #[error("Query error: {0}")]
366    Query(String),
367    #[error("Parse error: {0}")]
368    Parse(String),
369    #[error("Serialization error: {0}")]
370    Serialize(String),
371    #[error("IO error: {0}")]
372    Io(String),
373    #[error("Concurrency error: {0}")]
374    ConcurrencyError(String),
375    #[error("Quantum computing error: {0}")]
376    QuantumError(String),
377    #[error("Molecular optimization error: {0}")]
378    MolecularError(String),
379    #[error("Neural-symbolic fusion error: {0}")]
380    NeuralSymbolicError(String),
381    #[error("Operation not supported: {0}")]
382    NotSupported(String),
383    #[error("Update error: {0}")]
384    Update(String),
385    #[error("Federation error: {0}")]
386    Federation(String),
387}
388
389impl From<std::io::Error> for OxirsError {
390    fn from(err: std::io::Error) -> Self {
391        OxirsError::Io(err.to_string())
392    }
393}
394
395// Additional error conversions
396impl From<oxicode::Error> for OxirsError {
397    fn from(err: oxicode::Error) -> Self {
398        OxirsError::Serialize(err.to_string())
399    }
400}
401
402impl From<serde_json::Error> for OxirsError {
403    fn from(err: serde_json::Error) -> Self {
404        OxirsError::Serialize(err.to_string())
405    }
406}
407
408// Note: DataFusion, Arrow, and Parquet error conversions removed
409// Add these features to Cargo.toml if these integrations are needed
410
411impl From<std::time::SystemTimeError> for OxirsError {
412    fn from(err: std::time::SystemTimeError) -> Self {
413        OxirsError::Io(format!("System time error: {err}"))
414    }
415}
416
417/// Result type alias for OxiRS operations
418pub type Result<T> = std::result::Result<T, OxirsError>;
419
420/// Version information for OxiRS Core
421pub const VERSION: &str = env!("CARGO_PKG_VERSION");
422
423/// Initialize OxiRS Core with default configuration
424pub fn init() -> Result<()> {
425    tracing::info!("Initializing OxiRS Core v{}", VERSION);
426    Ok(())
427}