Skip to main content

helia_json/
lib.rs

1//! # Helia JSON
2//!
3//! Simple JSON serialization for Helia, providing straightforward JSON storage
4//! with content addressing for structured data in IPFS.
5//!
6//! ## Overview
7//!
8//! This module provides a simplified JSON interface for Helia, focusing on ease of use
9//! for basic JSON operations. It's ideal when you need:
10//!
11//! - **Simple JSON storage**: Direct JSON-to-CID mapping
12//! - **Quick prototyping**: Minimal setup for JSON operations
13//! - **Familiar API**: Standard JSON serialization patterns
14//! - **IPFS compatibility**: Works with IPFS ecosystem
15//!
16//! ## When to Use JSON vs DAG-JSON
17//!
18//! ### Use `helia-json` when:
19//! - You need simple, straightforward JSON storage
20//! - Working with standard JSON objects without IPLD features
21//! - Building quick prototypes or simple applications
22//! - Prefer minimal API surface
23//!
24//! ### Use `helia-dag-json` when:
25//! - You need full IPLD (InterPlanetary Linked Data) support
26//! - Working with linked data structures (CID links)
27//! - Building complex DAG (Directed Acyclic Graph) applications
28//! - Need compatibility with go-ipfs/js-ipfs DAG-JSON implementations
29//! - Require advanced IPLD features
30//!
31//! ## Core Concepts
32//!
33//! ### Content Addressing
34//! Each JSON object is stored with a unique Content Identifier (CID):
35//! - CID is deterministic based on content
36//! - CID includes codec identifier (0x0200 for JSON)
37//! - CID provides integrity verification
38//!
39//! ### JSON Codec
40//! This module uses the JSON codec (0x0200) from the multicodec table, providing
41//! a simple JSON serialization format for IPFS storage.
42//!
43//! ## Usage Examples
44//!
45//! ### Example 1: Basic Object Storage
46//! ```no_run
47//! use rust_helia::create_helia_default;
48//! use helia_json::{Json, JsonInterface};
49//! use serde::{Deserialize, Serialize};
50//! use std::sync::Arc;
51//!
52//! #[derive(Serialize, Deserialize, PartialEq, Debug)]
53//! struct User {
54//!     name: String,
55//!     age: u32,
56//! }
57//!
58//! #[tokio::main]
59//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
60//!     let helia = create_helia_default().await?;
61//!     let json = Json::new(Arc::new(helia));
62//!     
63//!     let user = User {
64//!         name: "Alice".to_string(),
65//!         age: 30,
66//!     };
67//!     
68//!     // Store JSON object
69//!     let cid = json.add(&user, None).await?;
70//!     println!("Stored at: {}", cid);
71//!     
72//!     // Retrieve JSON object
73//!     let retrieved: User = json.get(&cid, None).await?;
74//!     assert_eq!(user.name, retrieved.name);
75//!     
76//!     Ok(())
77//! }
78//! ```
79//!
80//! ### Example 2: Collections and HashMaps
81//! ```no_run
82//! use rust_helia::create_helia_default;
83//! use helia_json::{Json, JsonInterface};
84//! use std::collections::HashMap;
85//! use std::sync::Arc;
86//!
87//! #[tokio::main]
88//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
89//!     let helia = create_helia_default().await?;
90//!     let json = Json::new(Arc::new(helia));
91//!     
92//!     let mut config = HashMap::new();
93//!     config.insert("api_key".to_string(), "secret123".to_string());
94//!     config.insert("endpoint".to_string(), "https://api.example.com".to_string());
95//!     
96//!     let cid = json.add(&config, None).await?;
97//!     
98//!     let loaded: HashMap<String, String> = json.get(&cid, None).await?;
99//!     println!("API Key: {}", loaded.get("api_key").unwrap());
100//!     
101//!     Ok(())
102//! }
103//! ```
104//!
105//! ### Example 3: Pinning for Persistence
106//! ```no_run
107//! use rust_helia::create_helia_default;
108//! use helia_json::{Json, JsonInterface, AddOptions};
109//! use serde::{Deserialize, Serialize};
110//! use std::sync::Arc;
111//!
112//! #[derive(Serialize, Deserialize)]
113//! struct Document {
114//!     title: String,
115//!     content: String,
116//! }
117//!
118//! #[tokio::main]
119//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
120//!     let helia = create_helia_default().await?;
121//!     let json = Json::new(Arc::new(helia));
122//!     
123//!     let doc = Document {
124//!         title: "Important Note".to_string(),
125//!         content: "Remember to pin!".to_string(),
126//!     };
127//!     
128//!     // Pin to prevent garbage collection
129//!     let options = AddOptions {
130//!         pin: true,
131//!         ..Default::default()
132//!     };
133//!     
134//!     let cid = json.add(&doc, Some(options)).await?;
135//!     println!("Pinned document at: {}", cid);
136//!     
137//!     Ok(())
138//! }
139//! ```
140//!
141//! ### Example 4: Thread-Safe Operations
142//! ```no_run
143//! use rust_helia::create_helia_default;
144//! use helia_json::{Json, JsonInterface};
145//! use serde::{Deserialize, Serialize};
146//! use std::sync::Arc;
147//!
148//! #[derive(Serialize, Deserialize, Clone)]
149//! struct Message {
150//!     id: u32,
151//!     text: String,
152//! }
153//!
154//! #[tokio::main]
155//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
156//!     let helia = create_helia_default().await?;
157//!     let json = Arc::new(Json::new(Arc::new(helia)));
158//!     
159//!     let mut handles = vec![];
160//!     
161//!     for i in 0..5 {
162//!         let json_clone = json.clone();
163//!         let handle = tokio::spawn(async move {
164//!             let msg = Message {
165//!                 id: i,
166//!                 text: format!("Message {}", i),
167//!             };
168//!             json_clone.add(&msg, None).await
169//!         });
170//!         handles.push(handle);
171//!     }
172//!     
173//!     for handle in handles {
174//!         let cid = handle.await??;
175//!         println!("Stored message at: {}", cid);
176//!     }
177//!     
178//!     Ok(())
179//! }
180//! ```
181//!
182//! ## Performance Characteristics
183//!
184//! ### Serialization
185//! - **Small objects (<1KB)**: ~15-60µs
186//! - **Medium objects (1-10KB)**: ~60-250µs
187//! - **Large objects (>10KB)**: 250µs+
188//!
189//! ### Storage
190//! - **JSON overhead**: Similar to DAG-JSON (~30-50% larger than CBOR)
191//! - **Recommended size**: <10MB per object
192//! - **Format**: Human-readable text
193//!
194//! ## Error Handling
195//!
196//! ```no_run
197//! use rust_helia::create_helia_default;
198//! use helia_json::{Json, JsonInterface, JsonError};
199//! use serde::{Deserialize, Serialize};
200//! use std::sync::Arc;
201//!
202//! #[derive(Serialize, Deserialize)]
203//! struct Data { value: String }
204//!
205//! #[tokio::main]
206//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
207//!     let helia = create_helia_default().await?;
208//!     let json = Json::new(Arc::new(helia));
209//!     
210//!     let data = Data { value: "test".to_string() };
211//!     let cid = json.add(&data, None).await?;
212//!     
213//!     match json.get::<Data>(&cid, None).await {
214//!         Ok(retrieved) => println!("Success: {}", retrieved.value),
215//!         Err(JsonError::InvalidCodec { expected, actual }) => {
216//!             eprintln!("Wrong codec: expected {}, got {}", expected, actual);
217//!         }
218//!         Err(JsonError::Serialization(e)) => {
219//!             eprintln!("Serialization error: {}", e);
220//!         }
221//!         Err(e) => eprintln!("Error: {}", e),
222//!     }
223//!     
224//!     Ok(())
225//! }
226//! ```
227//!
228//! ## Comparison: JSON vs DAG-JSON vs DAG-CBOR
229//!
230//! | Feature | JSON | DAG-JSON | DAG-CBOR |
231//! |---------|------|----------|----------|
232//! | Simplicity | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
233//! | IPLD Support | ❌ | ✅ | ✅ |
234//! | CID Links | ❌ | ✅ | ✅ |
235//! | Format | Text | Text | Binary |
236//! | Size | Medium | Medium | Small |
237//! | Speed | Medium | Medium | Fast |
238//! | Use Case | Simple | IPLD/DAG | Performance |
239//!
240//! ## Limitations
241//!
242//! ### Current Constraints
243//! 1. **No IPLD features**: No support for CID links within objects
244//! 2. **Object size**: Recommended <10MB per object
245//! 3. **No DAG operations**: Not suitable for complex graph structures
246//!
247//! ### When to Use Alternatives
248//! - **Need IPLD/CID links**: Use `helia-dag-json`
249//! - **Need performance**: Use `helia-dag-cbor`
250//! - **Need files**: Use `helia-unixfs`
251//!
252//! ## Compatibility
253//!
254//! - **JSON codec**: 0x0200 (multicodec table)
255//! - **Serialization**: Standard serde_json
256//! - **IPFS compatible**: Works with IPFS ecosystem
257
258pub mod errors;
259pub mod json;
260
261#[cfg(test)]
262mod tests;
263
264use std::sync::Arc;
265
266use helia_interface::{AbortOptions, Helia};
267
268pub use errors::*;
269pub use json::*;
270
271/// Options for adding JSON data
272#[derive(Debug, Clone, Default)]
273pub struct AddOptions {
274    /// Optional abort signal
275    pub abort_signal: Option<AbortOptions>,
276    /// Whether to pin the added data
277    pub pin: bool,
278}
279
280/// Options for getting JSON data
281#[derive(Debug, Clone, Default)]
282pub struct GetOptions {
283    /// Optional abort signal
284    pub abort_signal: Option<AbortOptions>,
285}
286
287/// Create a JSON instance for use with Helia
288pub fn json(helia: Arc<dyn Helia>) -> Json {
289    Json::new(helia)
290}