ngdb 2.2.2

A high-performance, thread-safe RocksDB wrapper
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
//! Comprehensive replication example demonstrating advanced patterns
//!
//! This example covers:
//! - Multi-node replication setup
//! - Conflict resolution strategies (LastWriteWins, FirstWriteWins, Custom)
//! - Custom replication hooks
//! - Batch operations across nodes
//! - Checksum verification
//! - Proper production replication patterns

use borsh::{BorshDeserialize, BorshSerialize};
use ngdb::{
    ConflictResolution, DatabaseConfig, ReplicationConfig, ReplicationHook, ReplicationLog,
    ReplicationManager, ReplicationOperation, Result, Storable,
};
use std::sync::Arc;

#[derive(Debug, Clone, PartialEq, BorshSerialize, BorshDeserialize)]
struct Record {
    id: u64,
    value: String,
    version: u64,
    timestamp: u64,
}

impl Storable for Record {
    type Key = u64;

    fn key(&self) -> Self::Key {
        self.id
    }

    fn validate(&self) -> Result<()> {
        if self.value.is_empty() {
            return Err(ngdb::Error::InvalidData(
                "Value cannot be empty".to_string(),
            ));
        }
        Ok(())
    }
}

struct AuditHook {
    node_id: String,
}

impl ReplicationHook for AuditHook {
    fn before_apply(&self, log: &ReplicationLog) -> Result<()> {
        println!(
            "[{}] Receiving operation {} from {}",
            self.node_id, log.operation_id, log.source_node_id
        );
        Ok(())
    }

    fn after_apply(&self, log: &ReplicationLog) -> Result<()> {
        println!("[{}] Applied operation {}", self.node_id, log.operation_id);
        Ok(())
    }

    fn on_replication_error(&self, log: &ReplicationLog, error: &ngdb::Error) {
        eprintln!(
            "[{}] Error applying operation {}: {:?}",
            self.node_id, log.operation_id, error
        );
    }

    fn resolve_conflict(&self, existing: &[u8], new: &[u8]) -> Result<Vec<u8>> {
        let existing_record: Record = borsh::from_slice(existing)
            .map_err(|e| ngdb::Error::SerializationError(e.to_string()))?;
        let new_record: Record =
            borsh::from_slice(new).map_err(|e| ngdb::Error::SerializationError(e.to_string()))?;

        let winner = if new_record.version > existing_record.version {
            println!(
                "[{}] Conflict: New v{} > Existing v{}, accepting new",
                self.node_id, new_record.version, existing_record.version
            );
            new_record
        } else if new_record.version == existing_record.version {
            if new_record.timestamp > existing_record.timestamp {
                println!(
                    "[{}] Conflict: Same version, newer timestamp, accepting new",
                    self.node_id
                );
                new_record
            } else {
                println!(
                    "[{}] Conflict: Same version, older timestamp, keeping existing",
                    self.node_id
                );
                existing_record
            }
        } else {
            println!(
                "[{}] Conflict: New v{} < Existing v{}, keeping existing",
                self.node_id, new_record.version, existing_record.version
            );
            existing_record
        };

        borsh::to_vec(&winner).map_err(|e| ngdb::Error::SerializationError(e.to_string()))
    }
}

fn main() -> Result<()> {
    let temp_dir = std::env::temp_dir();
    let node1_path = temp_dir.join("ngdb_full_repl_node1");
    let node2_path = temp_dir.join("ngdb_full_repl_node2");
    let node3_path = temp_dir.join("ngdb_full_repl_node3");

    let _ = std::fs::remove_dir_all(&node1_path);
    let _ = std::fs::remove_dir_all(&node2_path);
    let _ = std::fs::remove_dir_all(&node3_path);

    // Setup three-node replication cluster
    {
        let node1_db = DatabaseConfig::new(node1_path.to_str().unwrap())
            .create_if_missing(true)
            .add_column_family("records")
            .open()?;

        let node2_db = DatabaseConfig::new(node2_path.to_str().unwrap())
            .create_if_missing(true)
            .add_column_family("records")
            .open()?;

        let node3_db = DatabaseConfig::new(node3_path.to_str().unwrap())
            .create_if_missing(true)
            .add_column_family("records")
            .open()?;

        let config1 = ReplicationConfig::new("node-1")
            .enable()
            .with_peers(vec!["node-2".to_string(), "node-3".to_string()])
            .conflict_resolution(ConflictResolution::LastWriteWins);

        let config2 = ReplicationConfig::new("node-2")
            .enable()
            .with_peers(vec!["node-1".to_string(), "node-3".to_string()])
            .conflict_resolution(ConflictResolution::LastWriteWins);

        let config3 = ReplicationConfig::new("node-3")
            .enable()
            .with_peers(vec!["node-1".to_string(), "node-2".to_string()])
            .conflict_resolution(ConflictResolution::Custom);

        let mut manager1 = ReplicationManager::new(node1_db.clone(), config1)?;
        let mut manager2 = ReplicationManager::new(node2_db.clone(), config2)?;
        let mut manager3 = ReplicationManager::new(node3_db.clone(), config3)?;

        manager1.register_hook(Arc::new(AuditHook {
            node_id: "node-1".to_string(),
        }));
        manager2.register_hook(Arc::new(AuditHook {
            node_id: "node-2".to_string(),
        }));
        manager3.register_hook(Arc::new(AuditHook {
            node_id: "node-3".to_string(),
        }));

        println!("Initialized 3-node cluster\n");

        // Primary write with full replication
        {
            let record = Record {
                id: 1,
                value: "Initial record from Node 1".to_string(),
                version: 1,
                timestamp: current_timestamp_micros(),
            };

            let node1_records = node1_db.collection::<Record>("records")?;
            node1_records.put(&record)?;
            println!("Node 1: Written record {}", record.id);

            let log = ReplicationLog::new(
                "node-1".to_string(),
                ReplicationOperation::Put {
                    collection: "records".to_string(),
                    key: borsh::to_vec(&record.id)?,
                    value: borsh::to_vec(&record)?,
                },
            )
            .with_checksum();

            manager2.apply_replication(log.clone())?;
            manager3.apply_replication(log)?;
            println!("Replicated to all nodes\n");
        }

        // Conflict resolution - LastWriteWins
        {
            let record_v2 = Record {
                id: 1,
                value: "Updated by Node 2".to_string(),
                version: 2,
                timestamp: current_timestamp_micros(),
            };

            let node2_records = node2_db.collection::<Record>("records")?;
            node2_records.put(&record_v2)?;
            println!("Node 2: Updated to v{}", record_v2.version);

            let log2 = ReplicationLog::new(
                "node-2".to_string(),
                ReplicationOperation::Put {
                    collection: "records".to_string(),
                    key: borsh::to_vec(&record_v2.id)?,
                    value: borsh::to_vec(&record_v2)?,
                },
            )
            .with_checksum();

            std::thread::sleep(std::time::Duration::from_millis(10));

            let record_v2_conflict = Record {
                id: 1,
                value: "Updated by Node 3".to_string(),
                version: 2,
                timestamp: current_timestamp_micros(),
            };

            let node3_records = node3_db.collection::<Record>("records")?;
            node3_records.put(&record_v2_conflict)?;
            println!(
                "Node 3: Updated to v{} (conflicting)",
                record_v2_conflict.version
            );

            let log3 = ReplicationLog::new(
                "node-3".to_string(),
                ReplicationOperation::Put {
                    collection: "records".to_string(),
                    key: borsh::to_vec(&record_v2_conflict.id)?,
                    value: borsh::to_vec(&record_v2_conflict)?,
                },
            )
            .with_checksum();

            manager1.apply_replication(log2)?;
            manager1.apply_replication(log3)?;

            let node1_records = node1_db.collection::<Record>("records")?;
            let final_record = node1_records.get(&1)?.expect("Record should exist");
            println!(
                "Node 1 final state: v{}, value: {}\n",
                final_record.version, final_record.value
            );
        }

        // Batch replication
        {
            let node1_records = node1_db.collection::<Record>("records")?;
            let mut batch = node1_records.batch();
            let mut batch_ops = Vec::new();

            let timestamp = current_timestamp_micros();

            for i in 10..15 {
                let record = Record {
                    id: i,
                    value: format!("Batch record {}", i),
                    version: 1,
                    timestamp,
                };
                batch.put(&record)?;

                batch_ops.push(ngdb::BatchOp::Put {
                    key: borsh::to_vec(&record.id)?,
                    value: borsh::to_vec(&record)?,
                });
            }

            batch.commit()?;
            println!("Node 1: Committed batch of 5 records");

            let batch_log = ReplicationLog::new(
                "node-1".to_string(),
                ReplicationOperation::Batch {
                    collection: "records".to_string(),
                    operations: batch_ops,
                },
            )
            .with_checksum();

            manager2.apply_replication(batch_log.clone())?;
            manager3.apply_replication(batch_log)?;
            println!("Batch replicated to all nodes\n");
        }

        // Delete operation replication
        {
            let delete_id = 14u64;

            let node1_records = node1_db.collection::<Record>("records")?;
            node1_records.delete(&delete_id)?;
            println!("Node 1: Deleted record {}", delete_id);

            let delete_log = ReplicationLog::new(
                "node-1".to_string(),
                ReplicationOperation::Delete {
                    collection: "records".to_string(),
                    key: borsh::to_vec(&delete_id)?,
                },
            )
            .with_checksum();

            manager2.apply_replication(delete_log.clone())?;
            manager3.apply_replication(delete_log)?;
            println!("Delete replicated to all nodes\n");
        }

        // FirstWriteWins strategy
        {
            let config2_fww = ReplicationConfig::new("node-2")
                .enable()
                .with_peers(vec!["node-1".to_string(), "node-3".to_string()])
                .conflict_resolution(ConflictResolution::FirstWriteWins);

            let manager2_fww = ReplicationManager::new(node2_db.clone(), config2_fww)?;

            let initial_record = Record {
                id: 100,
                value: "First write".to_string(),
                version: 1,
                timestamp: current_timestamp_micros(),
            };

            let node2_records = node2_db.collection::<Record>("records")?;
            node2_records.put(&initial_record)?;
            println!("Node 2: Written initial record {}", initial_record.id);

            let update_record = Record {
                id: 100,
                value: "Second write (should be rejected)".to_string(),
                version: 2,
                timestamp: current_timestamp_micros(),
            };

            let update_log = ReplicationLog::new(
                "node-1".to_string(),
                ReplicationOperation::Put {
                    collection: "records".to_string(),
                    key: borsh::to_vec(&update_record.id)?,
                    value: borsh::to_vec(&update_record)?,
                },
            )
            .with_checksum();

            manager2_fww.apply_replication(update_log)?;

            let final_record = node2_records.get(&100)?.expect("Record should exist");
            println!("Node 2 kept: '{}'\n", final_record.value);
        }

        // Custom conflict resolution with version checking
        {
            let record_v1 = Record {
                id: 200,
                value: "Version 1".to_string(),
                version: 1,
                timestamp: current_timestamp_micros(),
            };

            let node3_records = node3_db.collection::<Record>("records")?;
            node3_records.put(&record_v1)?;
            println!("Node 3: Written v{}", record_v1.version);

            let record_v2 = Record {
                id: 200,
                value: "Version 2".to_string(),
                version: 2,
                timestamp: current_timestamp_micros(),
            };

            let log_v2 = ReplicationLog::new(
                "node-1".to_string(),
                ReplicationOperation::Put {
                    collection: "records".to_string(),
                    key: borsh::to_vec(&record_v2.id)?,
                    value: borsh::to_vec(&record_v2)?,
                },
            )
            .with_checksum();

            manager3.apply_replication(log_v2)?;

            let final_record = node3_records.get(&200)?.expect("Record should exist");
            println!("Node 3 accepted: v{}\n", final_record.version);
        }

        // Consistency verification across all nodes
        {
            let node1_records = node1_db.collection::<Record>("records")?;
            let node2_records = node2_db.collection::<Record>("records")?;
            let node3_records = node3_db.collection::<Record>("records")?;

            let count1 = node1_records.iter()?.count()?;
            let count2 = node2_records.iter()?.count()?;
            let count3 = node3_records.iter()?.count()?;

            println!("Node 1: {} records", count1);
            println!("Node 2: {} records", count2);
            println!("Node 3: {} records\n", count3);
        }

        // Replication statistics
        {
            let stats1 = manager1.stats().unwrap();
            let stats2 = manager2.stats().unwrap();
            let stats3 = manager3.stats().unwrap();

            println!("Node 1: {} operations applied", stats1.total_operations);
            println!("Node 2: {} operations applied", stats2.total_operations);
            println!("Node 3: {} operations applied\n", stats3.total_operations);
        }

        // Checksum verification
        {
            let record = Record {
                id: 300,
                value: "Checksum test".to_string(),
                version: 1,
                timestamp: current_timestamp_micros(),
            };

            let log_with_checksum = ReplicationLog::new(
                "node-1".to_string(),
                ReplicationOperation::Put {
                    collection: "records".to_string(),
                    key: borsh::to_vec(&record.id)?,
                    value: borsh::to_vec(&record)?,
                },
            )
            .with_checksum();

            println!(
                "Created log with checksum: {:?}",
                log_with_checksum.checksum
            );
            manager2.apply_replication(log_with_checksum)?;
        }

        node1_db.shutdown()?;
        node2_db.shutdown()?;
        node3_db.shutdown()?;
    }

    let _ = std::fs::remove_dir_all(&node1_path);
    let _ = std::fs::remove_dir_all(&node2_path);
    let _ = std::fs::remove_dir_all(&node3_path);

    Ok(())
}

fn current_timestamp_micros() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("System time before Unix epoch")
        .as_micros() as u64
}