spicedb_embedded/lib.rs
1//! Embedded `SpiceDB` using CGO FFI with native gRPC.
2//!
3//! This crate provides an in-process `SpiceDB` instance for authorization checks.
4//! It uses a C-shared library to start `SpiceDB` servers, then connects via Unix
5//! socket. All API access is through tonic clients generated from
6//! [buf.build/authzed/api](https://buf.build/authzed/api) (see the `spicedb-grpc-tonic` crate).
7//!
8//! # Example
9//!
10//! ```ignore
11//! use spicedb_embedded::{v1, EmbeddedSpiceDB};
12//!
13//! #[tokio::main]
14//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
15//! let schema = r#"
16//! definition user {}
17//! definition document {
18//! relation reader: user
19//! permission read = reader
20//! }
21//! "#;
22//!
23//! let relationships = vec![v1::Relationship {
24//! resource: Some(v1::ObjectReference { object_type: "document".into(), object_id: "readme".into() }),
25//! relation: "reader".into(),
26//! subject: Some(v1::SubjectReference {
27//! object: Some(v1::ObjectReference { object_type: "user".into(), object_id: "alice".into() }),
28//! optional_relation: String::new(),
29//! }),
30//! optional_caveat: None,
31//! }];
32//!
33//! let spicedb = EmbeddedSpiceDB::new(schema, &relationships, None)?;
34//! let mut permissions = spicedb.permissions();
35//! // Use the full SpiceDB API via the generated client
36//! let response = permissions.check_permission(&v1::CheckPermissionRequest {
37//! consistency: None,
38//! resource: Some(v1::ObjectReference { object_type: "document".into(), object_id: "readme".into() }),
39//! permission: "read".into(),
40//! subject: Some(v1::SubjectReference {
41//! object: Some(v1::ObjectReference { object_type: "user".into(), object_id: "alice".into() }),
42//! optional_relation: String::new(),
43//! }),
44//! context: None,
45//! with_tracing: false,
46//! })?;
47//! Ok(())
48//! }
49//! ```
50
51mod spicedb;
52
53pub use spicedb::{EmbeddedSpiceDB, MemoryPermissionsClient, MemorySchemaClient, StartOptions};
54// Re-export spicedb-grpc so users have direct access to all generated types
55pub use spicedb_grpc_tonic::v1;
56
57/// Errors from embedded `SpiceDB` operations
58#[derive(Debug, thiserror::Error)]
59pub enum SpiceDBError {
60 /// Failed to load the module (WASM or shared library)
61 #[error("failed to load module: {0}")]
62 ModuleLoad(String),
63
64 /// Runtime error during execution
65 #[error("runtime error: {0}")]
66 Runtime(String),
67
68 /// Protocol error in communication
69 #[error("protocol error: {0}")]
70 Protocol(String),
71
72 /// Error from `SpiceDB` itself
73 #[error("SpiceDB error: {0}")]
74 SpiceDB(String),
75}