anya-core 1.2.0

Enterprise-grade Bitcoin Infrastructure Platform
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
use std::error::Error;
use std::sync::{Arc, Mutex};
use log::{info, warn, error};
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};

/// Metrics for tracking Read First Always principle compliance
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadFirstMetrics {
    /// Number of read operations performed
    pub read_count: u64,
    /// Number of write operations performed
    pub write_count: u64,
    /// Number of write operations performed without a preceding read
    pub violation_count: u64,
    /// Timestamp of the last reset
    pub last_reset: DateTime<Utc>,
}

impl ReadFirstMetrics {
    /// Create a new ReadFirstMetrics instance
    pub fn new() -> Self {
        Self {
            read_count: 0,
            write_count: 0,
            violation_count: 0,
            last_reset: Utc::now(),
        }
    }

    /// Reset all metrics to zero
    pub fn reset(&mut self) {
        self.read_count = 0;
        self.write_count = 0;
        self.violation_count = 0;
        self.last_reset = Utc::now();
    }

    /// Calculate the compliance rate (percentage of writes preceded by reads)
    pub fn compliance_rate(&self) -> f64 {
        if self.write_count == 0 {
            return 100.0;
        }
        let compliant_writes = self.write_count.saturating_sub(self.violation_count);
        (compliant_writes as f64 / self.write_count as f64) * 100.0
    }

    /// Log the current metrics to the info log
    pub fn log_metrics(&self) {
        info!(
            "Read First Metrics: reads={}, writes={}, violations={}, compliance_rate={:.2}%",
            self.read_count,
            self.write_count,
            self.violation_count,
            self.compliance_rate()
        );
    }
}

/// ReadFirstDwnManager ensures the Read First Always principle is followed
/// in all DWN (Decentralized Web Node) operations.
#[derive(Debug)]
pub struct ReadFirstDwnManager {
    /// The Web5 client for performing DWN operations
    web5_client: Arc<dyn Web5Client>,
    /// Metrics for tracking Read First compliance
    metrics: Arc<Mutex<ReadFirstMetrics>>,
    /// Whether a read operation has been performed in the current operation context
    read_performed: Arc<Mutex<bool>>,
}

/// Trait for abstracting Web5 client operations
pub trait Web5Client: Send + Sync {
    fn create_record(&self, options: &CreateRecordOptions) -> Result<Record, Web5Error>;
    fn read_record(&self, record_id: &str) -> Result<Option<Record>, Web5Error>;
    fn update_record(&self, record_id: &str, options: &UpdateRecordOptions) -> Result<Record, Web5Error>;
    fn delete_record(&self, record_id: &str) -> Result<bool, Web5Error>;
    fn query_records(&self, query: &QueryOptions) -> Result<Vec<Record>, Web5Error>;
    // v2.0.0-beta9: Add support for async and new API signatures
    fn create_record_async<'a>(&'a self, options: &'a CreateRecordOptions) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Record, Web5Error>> + Send + 'a>> {
        Box::pin(async move { self.create_record(options) })
    }
    fn read_record_async<'a>(&'a self, record_id: &'a str) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Option<Record>, Web5Error>> + Send + 'a>> {
        Box::pin(async move { self.read_record(record_id) })
    }
    fn update_record_async<'a>(&'a self, record_id: &'a str, options: &'a UpdateRecordOptions) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Record, Web5Error>> + Send + 'a>> {
        Box::pin(async move { self.update_record(record_id, options) })
    }
    fn delete_record_async<'a>(&'a self, record_id: &'a str) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<bool, Web5Error>> + Send + 'a>> {
        Box::pin(async move { self.delete_record(record_id) })
    }
    fn query_records_async<'a>(&'a self, query: &'a QueryOptions) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<Record>, Web5Error>> + Send + 'a>> {
        Box::pin(async move { self.query_records(query) })
    }
}

/// Options for creating a record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateRecordOptions {
    pub data: String,
    pub schema: String,
    pub data_format: String,
}

/// Options for updating a record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateRecordOptions {
    pub data: String,
    pub data_format: String,
}

/// Options for querying records
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryOptions {
    pub schema: Option<String>,
    pub filter: Option<String>,
}

/// Record representation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Record {
    pub id: String,
    pub data: String,
    pub schema: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: Option<DateTime<Utc>>,
}

/// Custom error type for Web5 operations
#[derive(Debug, thiserror::Error)]
pub enum Web5Error {
    #[error("Record not found: {0}")]
    RecordNotFound(String),
    
    #[error("Read First violation: attempted to {0} without reading first")]
    ReadFirstViolation(String),
    
    #[error("Web5 client error: {0}")]
    ClientError(String),
    
    #[error("Serialization error: {0}")]
    SerializationError(String),
    
    #[error("Invalid operation: {0}")]
    InvalidOperation(String),
}

impl ReadFirstDwnManager {
    /// Create a new ReadFirstDwnManager
    pub fn new(web5_client: Arc<dyn Web5Client>) -> Self {
        Self {
            web5_client,
            metrics: Arc::new(Mutex::new(ReadFirstMetrics::new())),
            read_performed: Arc::new(Mutex::new(false)),
        }
    }
    
    /// Reset the read_performed flag for a new operation context
    fn reset_read_status(&self) {
        if let Ok(mut status) = self.read_performed.lock() {
            *status = false;
        }
    }
    
    /// Mark that a read has been performed in the current operation context
    fn mark_read_performed(&self) {
        if let Ok(mut status) = self.read_performed.lock() {
            *status = true;
        }
        
        if let Ok(mut metrics) = self.metrics.lock() {
            metrics.read_count += 1;
        }
    }
    
    /// Check if a read has been performed and update metrics for a write operation
    fn check_read_before_write(&self, operation: &str) -> Result<(), Web5Error> {
        let read_performed = if let Ok(status) = self.read_performed.lock() {
            *status
        } else {
            false
        };
        
        if let Ok(mut metrics) = self.metrics.lock() {
            metrics.write_count += 1;
            
            if !read_performed {
                metrics.violation_count += 1;
                warn!("Read First violation: {} operation performed without a preceding read", operation);
                return Err(Web5Error::ReadFirstViolation(operation.to_string()));
            }
        }
        
        Ok(())
    }
    
    /// Get a copy of the current metrics
    pub fn get_metrics(&self) -> ReadFirstMetrics {
        if let Ok(metrics) = self.metrics.lock() {
            metrics.clone()
        } else {
            ReadFirstMetrics::new()
        }
    }
    
    /// Log the current metrics
    pub fn log_metrics(&self) {
        if let Ok(metrics) = self.metrics.lock() {
            metrics.log_metrics();
        }
    }
    
    /// Reset all metrics
    pub fn reset_metrics(&self) {
        if let Ok(mut metrics) = self.metrics.lock() {
            metrics.reset();
        }
    }
    
    /// Create a record with Read First enforcement
    pub fn create_record(&self, options: &CreateRecordOptions) -> Result<Record, Web5Error> {
        // Reset read status for new operation
        self.reset_read_status();
        
        // READ FIRST: Query for similar records based on schema
        let query_options = QueryOptions {
            schema: Some(options.schema.clone()),
            filter: None,
        };
        
        // Perform the query (read operation)
        let _ = self.query_records(&query_options)?;
        
        // Check if read was performed before write
        self.check_read_before_write("create")?;
        
        // Perform the actual create operation
        self.web5_client.create_record(options)
    }
    
    /// Read a record and track metrics
    pub fn read_record(&self, record_id: &str) -> Result<Option<Record>, Web5Error> {
        // Mark that a read has been performed
        self.mark_read_performed();
        
        // Perform the actual read operation
        self.web5_client.read_record(record_id)
    }
    
    /// Query records and track metrics
    pub fn query_records(&self, query: &QueryOptions) -> Result<Vec<Record>, Web5Error> {
        // Mark that a read has been performed
        self.mark_read_performed();
        
        // Perform the actual query operation
        self.web5_client.query_records(query)
    }
    
    /// Update a record with Read First enforcement
    pub fn update_record(&self, record_id: &str, options: &UpdateRecordOptions) -> Result<Record, Web5Error> {
        // Reset read status for new operation
        self.reset_read_status();
        
        // READ FIRST: Read the record before updating
        let record = self.read_record(record_id)?;
        
        // Ensure the record exists
        let record = record.ok_or_else(|| Web5Error::RecordNotFound(record_id.to_string()))?;
        
        // Check if read was performed before write
        self.check_read_before_write("update")?;
        
        // Perform the actual update operation
        self.web5_client.update_record(record_id, options)
    }
    
    /// Delete a record with Read First enforcement
    pub fn delete_record(&self, record_id: &str) -> Result<bool, Web5Error> {
        // Reset read status for new operation
        self.reset_read_status();
        
        // READ FIRST: Read the record before deleting
        let record = self.read_record(record_id)?;
        
        // Ensure the record exists
        let _ = record.ok_or_else(|| Web5Error::RecordNotFound(record_id.to_string()))?;
        
        // Check if read was performed before write
        self.check_read_before_write("delete")?;
        
        // Perform the actual delete operation
        self.web5_client.delete_record(record_id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mockall::predicate::*;
    use mockall::*;
    
    mock! {
        TestWeb5Client {}
        impl Web5Client for TestWeb5Client {
            fn create_record(&self, options: &CreateRecordOptions) -> Result<Record, Web5Error>;
            fn read_record(&self, record_id: &str) -> Result<Option<Record>, Web5Error>;
            fn update_record(&self, record_id: &str, options: &UpdateRecordOptions) -> Result<Record, Web5Error>;
            fn delete_record(&self, record_id: &str) -> Result<bool, Web5Error>;
            fn query_records(&self, query: &QueryOptions) -> Result<Vec<Record>, Web5Error>;
        }
    }
    
    #[test]
    fn test_create_record_enforces_read_first() {
        let mut mock = MockTestWeb5Client::new();
        
        // Setup expectations
        mock.expect_query_records()
            .times(1)
            .returning(|_| Ok(vec![]));
            
        mock.expect_create_record()
            .times(1)
            .returning(|_| {
                Ok(Record {
                    id: "test-id".to_string(),
                    data: "test-data".to_string(),
                    schema: Some("test-schema".to_string()),
                    created_at: Utc::now(),
                    updated_at: None,
                })
            });
            
        // Create the manager with the mock
        let manager = ReadFirstDwnManager::new(Arc::new(mock));
        
        // Test creating a record
        let result = manager.create_record(&CreateRecordOptions {
            data: "test-data".to_string(),
            schema: "test-schema".to_string(),
            data_format: "application/json".to_string(),
        });
        
        // Verify success
        assert!(result.is_ok());
        
        // Verify metrics
        let metrics = manager.get_metrics();
        assert_eq!(metrics.read_count, 1);
        assert_eq!(metrics.write_count, 1);
        assert_eq!(metrics.violation_count, 0);
        assert_eq!(metrics.compliance_rate(), 100.0);
    }
    
    #[test]
    fn test_update_record_enforces_read_first() {
        let mut mock = MockTestWeb5Client::new();
        
        // Setup expectations
        mock.expect_read_record()
            .times(1)
            .returning(|_| {
                Ok(Some(Record {
                    id: "test-id".to_string(),
                    data: "original-data".to_string(),
                    schema: Some("test-schema".to_string()),
                    created_at: Utc::now(),
                    updated_at: None,
                }))
            });
            
        mock.expect_update_record()
            .times(1)
            .returning(|_, _| {
                Ok(Record {
                    id: "test-id".to_string(),
                    data: "updated-data".to_string(),
                    schema: Some("test-schema".to_string()),
                    created_at: Utc::now(),
                    updated_at: Some(Utc::now()),
                })
            });
            
        // Create the manager with the mock
        let manager = ReadFirstDwnManager::new(Arc::new(mock));
        
        // Test updating a record
        let result = manager.update_record("test-id", &UpdateRecordOptions {
            data: "updated-data".to_string(),
            data_format: "application/json".to_string(),
        });
        
        // Verify success
        assert!(result.is_ok());
        
        // Verify metrics
        let metrics = manager.get_metrics();
        assert_eq!(metrics.read_count, 1);
        assert_eq!(metrics.write_count, 1);
        assert_eq!(metrics.violation_count, 0);
        assert_eq!(metrics.compliance_rate(), 100.0);
    }
    
    #[test]
    fn test_update_nonexistent_record_fails() {
        let mut mock = MockTestWeb5Client::new();
        
        // Setup expectations
        mock.expect_read_record()
            .times(1)
            .returning(|_| Ok(None));
            
        // Create the manager with the mock
        let manager = ReadFirstDwnManager::new(Arc::new(mock));
        
        // Test updating a record
        let result = manager.update_record("nonexistent-id", &UpdateRecordOptions {
            data: "updated-data".to_string(),
            data_format: "application/json".to_string(),
        });
        
        // Verify error
        assert!(result.is_err());
        match result {
            Err(Web5Error::RecordNotFound(_)) => (),
            _ => panic!("Expected RecordNotFound error"),
        }
    }
    
    #[test]
    fn test_delete_record_enforces_read_first() {
        let mut mock = MockTestWeb5Client::new();
        
        // Setup expectations
        mock.expect_read_record()
            .times(1)
            .returning(|_| {
                Ok(Some(Record {
                    id: "test-id".to_string(),
                    data: "test-data".to_string(),
                    schema: Some("test-schema".to_string()),
                    created_at: Utc::now(),
                    updated_at: None,
                }))
            });
            
        mock.expect_delete_record()
            .times(1)
            .returning(|_| Ok(true));
            
        // Create the manager with the mock
        let manager = ReadFirstDwnManager::new(Arc::new(mock));
        
        // Test deleting a record
        let result = manager.delete_record("test-id");
        
        // Verify success
        assert!(result.is_ok());
        assert!(result?);
        
        // Verify metrics
        let metrics = manager.get_metrics();
        assert_eq!(metrics.read_count, 1);
        assert_eq!(metrics.write_count, 1);
        assert_eq!(metrics.violation_count, 0);
        assert_eq!(metrics.compliance_rate(), 100.0);
    }
}