ipfrs-storage 0.1.0

Storage backends and block management for IPFRS content-addressed system
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! GraphQL Query Interface for Block Metadata
//!
//! This module provides a GraphQL API for querying blocks by properties,
//! with support for filtering, sorting, and pagination.
//!
//! # Features
//!
//! - Query blocks by CID, size, or age
//! - Filter by size range, date range, or CID pattern
//! - Sort by size, creation time, or CID
//! - Cursor-based pagination for large result sets
//! - Aggregate statistics (total count, total size, etc.)
//!
//! # Example
//!
//! ```ignore
//! use ipfrs_storage::graphql::{BlockQuerySchema, QueryRoot};
//! use ipfrs_storage::MemoryBlockStore;
//! use async_graphql::Schema;
//!
//! #[tokio::main]
//! async fn main() {
//!     let store = MemoryBlockStore::new();
//!     let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription)
//!         .data(store)
//!         .finish();
//!
//!     let query = r#"
//!         query {
//!             blocks(filter: { minSize: 1000 }, limit: 10) {
//!                 nodes {
//!                     cid
//!                     size
//!                 }
//!                 totalCount
//!             }
//!         }
//!     "#;
//!
//!     let result = schema.execute(query).await;
//!     println!("{}", result.data);
//! }
//! ```

use crate::traits::BlockStore;
use async_graphql::{
    Context, EmptyMutation, EmptySubscription, Object, Result, Schema, SimpleObject,
};
use chrono::{DateTime, Utc};
use ipfrs_core::{Block, Cid};
use std::sync::Arc;

/// GraphQL schema for block queries
pub type BlockQuerySchema = Schema<QueryRoot, EmptyMutation, EmptySubscription>;

/// Block metadata exposed via GraphQL
#[derive(Debug, Clone, SimpleObject)]
pub struct BlockMetadata {
    /// Content identifier (CID) as string
    pub cid: String,
    /// Block size in bytes
    pub size: u64,
    /// Creation/insertion timestamp (simulated for now)
    pub created_at: DateTime<Utc>,
    /// Block data (optional, can be large)
    #[graphql(skip)]
    pub data: Option<Vec<u8>>,
}

impl BlockMetadata {
    /// Create metadata from a Block
    pub fn from_block(block: &Block) -> Self {
        Self {
            cid: block.cid().to_string(),
            size: block.data().len() as u64,
            created_at: Utc::now(), // In production, this would be tracked
            data: Some(block.data().to_vec()),
        }
    }

    /// Get the actual CID
    pub fn parse_cid(&self) -> Result<Cid> {
        self.cid
            .parse()
            .map_err(|e| format!("Invalid CID: {e}").into())
    }
}

/// Filter criteria for block queries
#[derive(Debug, Clone, Default)]
pub struct BlockFilter {
    /// Minimum block size in bytes
    pub min_size: Option<u64>,
    /// Maximum block size in bytes
    pub max_size: Option<u64>,
    /// Filter by CID prefix
    pub cid_prefix: Option<String>,
    /// Filter blocks created after this time
    pub created_after: Option<DateTime<Utc>>,
    /// Filter blocks created before this time
    pub created_before: Option<DateTime<Utc>>,
}

#[Object]
impl BlockFilter {
    async fn min_size(&self) -> Option<u64> {
        self.min_size
    }

    async fn max_size(&self) -> Option<u64> {
        self.max_size
    }

    async fn cid_prefix(&self) -> Option<&str> {
        self.cid_prefix.as_deref()
    }
}

/// Sort order for block queries
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortOrder {
    Ascending,
    Descending,
}

/// Field to sort blocks by
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortField {
    /// Sort by CID (lexicographically)
    Cid,
    /// Sort by block size
    Size,
    /// Sort by creation time
    CreatedAt,
}

/// Paginated result for block queries
#[derive(Debug, Clone, SimpleObject)]
pub struct BlockConnection {
    /// List of blocks in this page
    pub nodes: Vec<BlockMetadata>,
    /// Total count of blocks matching the query
    pub total_count: u64,
    /// Cursor for the next page (if available)
    pub next_cursor: Option<String>,
    /// Whether there are more results
    pub has_next_page: bool,
}

/// Aggregate statistics for blocks
#[derive(Debug, Clone, SimpleObject)]
pub struct BlockStats {
    /// Total number of blocks
    pub count: u64,
    /// Total size of all blocks in bytes
    pub total_size: u64,
    /// Average block size in bytes
    pub average_size: f64,
    /// Minimum block size
    pub min_size: u64,
    /// Maximum block size
    pub max_size: u64,
}

/// GraphQL query root
pub struct QueryRoot;

#[Object]
impl QueryRoot {
    /// Query blocks with optional filtering, sorting, and pagination
    async fn blocks(
        &self,
        ctx: &Context<'_>,
        #[graphql(desc = "Minimum size filter")] min_size: Option<u64>,
        #[graphql(desc = "Maximum size filter")] max_size: Option<u64>,
        #[graphql(desc = "CID prefix filter")] cid_prefix: Option<String>,
        #[graphql(desc = "Maximum number of results", default = 100)] limit: usize,
        #[graphql(desc = "Cursor for pagination")] cursor: Option<String>,
    ) -> Result<BlockConnection> {
        let store = ctx.data::<Arc<dyn BlockStore + Send + Sync>>()?;

        // Get all CIDs from the store
        let cids = store
            .list_cids()
            .map_err(|e| format!("Failed to list CIDs: {e}"))?;

        // Fetch all blocks and convert to metadata
        let mut blocks = Vec::new();
        for cid in cids {
            if let Some(block) = store
                .get(&cid)
                .await
                .map_err(|e| format!("Failed to get block: {e}"))?
            {
                let metadata = BlockMetadata::from_block(&block);

                // Apply filters
                if let Some(min) = min_size {
                    if metadata.size < min {
                        continue;
                    }
                }
                if let Some(max) = max_size {
                    if metadata.size > max {
                        continue;
                    }
                }
                if let Some(prefix) = &cid_prefix {
                    if !metadata.cid.starts_with(prefix) {
                        continue;
                    }
                }

                blocks.push(metadata);
            }
        }

        // Sort by size (default)
        blocks.sort_by_key(|b| b.size);

        // Apply cursor-based pagination
        let start_idx = if let Some(cursor) = cursor {
            cursor.parse::<usize>().unwrap_or(0)
        } else {
            0
        };

        let total_count = blocks.len() as u64;
        let end_idx = (start_idx + limit).min(blocks.len());
        let paginated_blocks: Vec<_> = blocks[start_idx..end_idx].to_vec();
        let has_next_page = end_idx < blocks.len();
        let next_cursor = if has_next_page {
            Some(end_idx.to_string())
        } else {
            None
        };

        Ok(BlockConnection {
            nodes: paginated_blocks,
            total_count,
            next_cursor,
            has_next_page,
        })
    }

    /// Get a single block by CID
    async fn block(
        &self,
        ctx: &Context<'_>,
        #[graphql(desc = "Content identifier")] cid: String,
    ) -> Result<Option<BlockMetadata>> {
        let store = ctx.data::<Arc<dyn BlockStore + Send + Sync>>()?;

        let cid: Cid = cid.parse().map_err(|e| format!("Invalid CID: {e}"))?;

        let block = store
            .get(&cid)
            .await
            .map_err(|e| format!("Failed to get block: {e}"))?;

        Ok(block.as_ref().map(BlockMetadata::from_block))
    }

    /// Get aggregate statistics for all blocks
    async fn stats(&self, ctx: &Context<'_>) -> Result<BlockStats> {
        let store = ctx.data::<Arc<dyn BlockStore + Send + Sync>>()?;

        let cids = store
            .list_cids()
            .map_err(|e| format!("Failed to list CIDs: {e}"))?;

        let mut count = 0u64;
        let mut total_size = 0u64;
        let mut min_size = u64::MAX;
        let mut max_size = 0u64;

        for cid in cids {
            if let Some(block) = store
                .get(&cid)
                .await
                .map_err(|e| format!("Failed to get block: {e}"))?
            {
                let size = block.data().len() as u64;
                count += 1;
                total_size += size;
                min_size = min_size.min(size);
                max_size = max_size.max(size);
            }
        }

        let average_size = if count > 0 {
            total_size as f64 / count as f64
        } else {
            0.0
        };

        Ok(BlockStats {
            count,
            total_size,
            average_size,
            min_size: if min_size == u64::MAX { 0 } else { min_size },
            max_size,
        })
    }

    /// Search blocks by CID pattern
    async fn search(
        &self,
        ctx: &Context<'_>,
        #[graphql(desc = "Search pattern (CID prefix)")] pattern: String,
        #[graphql(desc = "Maximum number of results", default = 10)] limit: usize,
    ) -> Result<Vec<BlockMetadata>> {
        let store = ctx.data::<Arc<dyn BlockStore + Send + Sync>>()?;

        let cids = store
            .list_cids()
            .map_err(|e| format!("Failed to list CIDs: {e}"))?;

        let mut results = Vec::new();
        for cid in cids {
            let cid_str = cid.to_string();
            if cid_str.contains(&pattern) {
                if let Some(block) = store
                    .get(&cid)
                    .await
                    .map_err(|e| format!("Failed to get block: {e}"))?
                {
                    results.push(BlockMetadata::from_block(&block));
                    if results.len() >= limit {
                        break;
                    }
                }
            }
        }

        Ok(results)
    }
}

/// Create a new GraphQL schema with a block store
pub fn create_schema<S: BlockStore + Send + Sync + 'static>(store: S) -> BlockQuerySchema {
    let store: Arc<dyn BlockStore + Send + Sync> = Arc::new(store);
    Schema::build(QueryRoot, EmptyMutation, EmptySubscription)
        .data(store)
        .finish()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::memory::MemoryBlockStore;
    use bytes::Bytes;

    #[tokio::test]
    async fn test_query_all_blocks() {
        let store = MemoryBlockStore::new();

        // Add some test blocks
        let block1 = Block::new(Bytes::from("hello")).unwrap();
        let block2 = Block::new(Bytes::from("world")).unwrap();
        store.put(&block1).await.unwrap();
        store.put(&block2).await.unwrap();

        let schema = create_schema(store);

        let query = r#"
            query {
                blocks(limit: 10) {
                    nodes {
                        cid
                        size
                    }
                    totalCount
                }
            }
        "#;

        let result = schema.execute(query).await;
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn test_query_single_block() {
        let store = MemoryBlockStore::new();
        let block = Block::new(Bytes::from("test")).unwrap();
        let cid = block.cid().to_string();
        store.put(&block).await.unwrap();

        let schema = create_schema(store);

        let query = format!(
            r#"
            query {{
                block(cid: "{}") {{
                    cid
                    size
                }}
            }}
        "#,
            cid
        );

        let result = schema.execute(&query).await;
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn test_stats_query() {
        let store = MemoryBlockStore::new();

        let block1 = Block::new(Bytes::from("hello")).unwrap();
        let block2 = Block::new(Bytes::from("world")).unwrap();
        store.put(&block1).await.unwrap();
        store.put(&block2).await.unwrap();

        let schema = create_schema(store);

        let query = r#"
            query {
                stats {
                    count
                    totalSize
                    averageSize
                    minSize
                    maxSize
                }
            }
        "#;

        let result = schema.execute(query).await;
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn test_search_blocks() {
        let store = MemoryBlockStore::new();
        let block = Block::new(Bytes::from("searchable")).unwrap();
        store.put(&block).await.unwrap();

        let schema = create_schema(store);

        let query = r#"
            query {
                search(pattern: "ba", limit: 5) {
                    cid
                    size
                }
            }
        "#;

        let result = schema.execute(query).await;
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn test_filter_by_size() {
        let store = MemoryBlockStore::new();

        let small = Block::new(Bytes::from("hi")).unwrap();
        let large = Block::new(Bytes::from("this is a much larger block")).unwrap();
        store.put(&small).await.unwrap();
        store.put(&large).await.unwrap();

        let schema = create_schema(store);

        let query = r#"
            query {
                blocks(minSize: 10, limit: 10) {
                    nodes {
                        size
                    }
                    totalCount
                }
            }
        "#;

        let result = schema.execute(query).await;
        assert!(result.errors.is_empty());
    }
}