aether-protocol 0.9.3

The official network protocol crate for AetherDB. Defines all request/response data structures for communicating with the high-performance CORD engine.
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
// File: src/lib.rs
// =============================================================================
// This is the main library file. Its primary job is to declare the modules
// and re-export their contents so they are easily accessible to any crate
// that uses `aether-protocol`.

//! # AetherDB Network Protocol
//!
//! This crate defines the official, stable network protocol for communicating
//! with an AetherDB instance. It contains all request and response data
//! structures, serialized using `bincode` for maximum performance.

// Declare the modules that make up our library.
pub mod request;
pub mod response;
pub mod types;

// Re-export the most important structs and enums for convenience.
pub use request::Request;
pub use response::Response;
pub use types::{BatchRequest, BatchResponse, DbStats, Direction, Filter, QueryOptions, Record, RecordSet};
pub use response::QueryMetrics;

#[cfg(test)]
mod tests {
    use crate::types::{BatchRequest, BatchResponse, DbStats, Direction, Filter, QueryOptions, Record, RecordSet};
    use crate::{Request, Response};
    use serde_json::json;
    use std::collections::HashMap;

    // Helper functions to test serialization/deserialization roundtrip
    
    // Use serde_json for testing since it handles serde_json::Value better than bincode
    fn test_serialization_json<T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug>(
        value: T,
    ) -> T {
        let serialized = serde_json::to_string(&value).expect("Failed to serialize to JSON");
        let deserialized = serde_json::from_str(&serialized).expect("Failed to deserialize from JSON");
        assert_eq!(value, deserialized, "Data loss during JSON serialization roundtrip");
        deserialized
    }
    
    // For non-JSON-Value types, we can still use bincode to ensure it works
    fn test_serialization_bincode<T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug>(
        value: T,
    ) -> T {
        let serialized = bincode::serialize(&value).expect("Failed to serialize");
        let deserialized = bincode::deserialize(&serialized).expect("Failed to deserialize");
        assert_eq!(value, deserialized, "Data loss during bincode serialization roundtrip");
        deserialized
    }

    #[test]
    fn test_record_serialization() {
        let mut record = Record::new();
        record.insert("name".to_string(), json!("John Doe"));
        record.insert("age".to_string(), json!(30));
        record.insert("active".to_string(), json!(true));
        record.insert("scores".to_string(), json!([85, 90, 78]));
        
        let deserialized = test_serialization_json(record);
        assert_eq!(deserialized["name"], json!("John Doe"));
    }

    #[test]
    fn test_recordset_serialization() {
        let mut record1 = Record::new();
        record1.insert("id".to_string(), json!(1));
        record1.insert("name".to_string(), json!("Record 1"));
        
        let mut record2 = Record::new();
        record2.insert("id".to_string(), json!(2));
        record2.insert("name".to_string(), json!("Record 2"));
        
        let recordset = RecordSet {
            records: vec![record1, record2],
        };
        
        test_serialization_json(recordset);
    }

    #[test]
    fn test_filter_serialization() {
        // Test each Filter variant
        let filters = vec![
            Filter::Equals {
                field: "status".to_string(),
                value: json!("active"),
            },
            Filter::NotEquals {
                field: "deleted".to_string(),
                value: json!(true),
            },
            Filter::GreaterThan {
                field: "age".to_string(),
                value: 18.0,
            },
            Filter::LessThan {
                field: "price".to_string(),
                value: 100.0,
            },
            Filter::In {
                field: "category".to_string(),
                values: vec![json!("electronics"), json!("books")],
            },
            Filter::And(vec![
                Filter::Equals {
                    field: "active".to_string(),
                    value: json!(true),
                },
                Filter::GreaterThan {
                    field: "score".to_string(),
                    value: 70.0,
                },
            ]),
            Filter::Or(vec![
                Filter::Equals {
                    field: "type".to_string(),
                    value: json!("premium"),
                },
                Filter::Equals {
                    field: "special".to_string(),
                    value: json!(true),
                },
            ]),
        ];
        
        for filter in filters {
            test_serialization_json(filter);
        }
    }

    #[test]
    fn test_query_options_serialization() {
        let options = QueryOptions {
            sort_by: Some(("created_at".to_string(), Direction::Desc)),
            limit: Some(100),
            offset: Some(20),
        };
        
        // Can use bincode for this since it doesn't have serde_json::Value
        test_serialization_bincode(options);
    }

    #[test]
    fn test_db_stats_serialization() {
        let stats = DbStats {
            collection_count: 5,
            record_count: 1000,
        };
        
        // Can use bincode for this since it doesn't have serde_json::Value
        test_serialization_bincode(stats);
    }

    #[test]
    fn test_batch_request_serialization() {
        let mut requests = HashMap::new();
        requests.insert("key1".to_string(), ("testdb".to_string(), "users".to_string(), "user_1".to_string()));
        requests.insert("key2".to_string(), ("testdb".to_string(), "products".to_string(), "product_1".to_string()));
        
        let batch_request = BatchRequest { requests };
        // Can use bincode for this since it doesn't have serde_json::Value
        test_serialization_bincode(batch_request);
    }

    #[test]
    fn test_batch_response_serialization() {
        let mut record1 = Record::new();
        record1.insert("id".to_string(), json!("user_1"));
        record1.insert("name".to_string(), json!("John Doe"));
        
        let mut record2 = Record::new();
        record2.insert("id".to_string(), json!("product_1"));
        record2.insert("name".to_string(), json!("Widget"));
        
        let mut results = HashMap::new();
        results.insert("key1".to_string(), Some(record1));
        results.insert("key2".to_string(), Some(record2));
        results.insert("key3".to_string(), None); // Test None case
        
        let batch_response = BatchResponse { results };
        test_serialization_json(batch_response);
    }

    #[test]
    fn test_request_serialization() {
        // Test all Request variants
        let requests = vec![
            // Database Management
            Request::CreateDatabase { db_name: "testdb".to_string() },
            Request::DropDatabase { db_name: "testdb".to_string() },
            Request::ListDatabases,
            
            // Collection Management
            Request::ListCollections,
            Request::CreateCollection { db_name: "users".to_string(), collection_name: "users".to_string() },
            Request::DropCollection { db_name: "users".to_string(), collection_name: "users".to_string() },
            Request::GetStats,
            Request::Flush,
            
            // Index Management
            Request::CreateIndex {
                db_name: "users".to_string(),
                collection: "users".to_string(),
                field_name: "email".to_string(),
            },
            Request::DropIndex {
                db_name: "users".to_string(),
                collection: "users".to_string(),
                field_name: "email".to_string(),
            },
            Request::ListIndexes {
                db_name: "users".to_string(),
                collection: "users".to_string(),
            },
            
            // CRUD Operations
            Request::CreateRecord {
                db_name: "users".to_string(),
                collection: "users".to_string(),
                record_id: "user123".to_string(),
                data: {
                    let mut record = Record::new();
                    record.insert("name".to_string(), json!("Alice"));
                    record.insert("email".to_string(), json!("alice@example.com"));
                    record
                },
            },
            Request::UpdateRecord {
                db_name: "users".to_string(),
                collection: "users".to_string(),
                record_id: "user123".to_string(),
                data: {
                    let mut record = Record::new();
                    record.insert("active".to_string(), json!(false));
                    record
                },
            },
            Request::UpsertRecord {
                db_name: "users".to_string(),
                collection: "users".to_string(),
                record_id: "user123".to_string(),
                data: {
                    let mut record = Record::new();
                    record.insert("name".to_string(), json!("Alice"));
                    record.insert("email".to_string(), json!("updated@example.com"));
                    record
                },
            },
            Request::GetRecord {
                db_name: "users".to_string(),
                collection: "users".to_string(),
                record_id: "user123".to_string(),
            },
            Request::DeleteRecord {
                db_name: "users".to_string(),
                collection: "users".to_string(),
                record_id: "user123".to_string(),
                cascade: true,
            },
            Request::GetLastInsertId,
            
            // Querying & Relational
            Request::FindRecords {
                db_name: "users".to_string(),
                collection: "users".to_string(),
                filter: crate::types::Filter::And(vec![
                    crate::types::Filter::Equals {
                        field: "active".to_string(),
                        value: json!(true),
                    },
                    crate::types::Filter::GreaterThan {
                        field: "age".to_string(),
                        value: 21.0,
                    },
                ]),
                options: Some(crate::types::QueryOptions {
                    sort_by: Some(("created_at".to_string(), crate::types::Direction::Desc)),
                    limit: Some(50),
                    offset: Some(0),
                }),
            },
            Request::CountRecords {
                db_name: "users".to_string(),
                collection: "users".to_string(),
                filter: crate::types::Filter::Equals {
                    field: "active".to_string(),
                    value: json!(true),
                },
            },
            Request::GetRecordWithRelated {
                db_name: "users".to_string(),
                primary_collection: "orders".to_string(),
                primary_record_id: "order123".to_string(),
                relation_key_field: "user_id".to_string(),
                related_collection: "users".to_string(),
            },
            Request::ExecuteBatchGet({
                let mut requests = HashMap::new();
                requests.insert("key1".to_string(), ("testdb".to_string(), "users".to_string(), "user123".to_string()));
                requests.insert("key2".to_string(), ("testdb".to_string(), "products".to_string(), "product456".to_string()));
                crate::types::BatchRequest { requests }
            }),
            Request::Search {
                db_name: "users".to_string(),
                collection: "users".to_string(),
                query: "John Doe".to_string(),
                field: Some("name".to_string()),
            },
            Request::Search {
                db_name: "users".to_string(),
                collection: "users".to_string(),
                query: "John Doe".to_string(),
                field: None, // The field is absent
            },
        ];
        
        for request in requests {
            test_serialization_json(request);
        }
    }

    #[test]
    fn test_response_serialization() {
        // Test all Response variants
        let responses = vec![
            // General Responses
            Response::Success,
            Response::Error("Invalid request format".to_string()),
            
            // Database Management Responses
            Response::DatabaseList(vec![
                "testdb".to_string(),
                "userdb".to_string(),
                "analytics".to_string(),
            ]),
            Response::DatabaseCreated(true),
            Response::DatabaseDropped(true),
            
            // Collection Management Responses
            Response::CollectionList(vec![
                "users".to_string(),
                "products".to_string(),
                "orders".to_string(),
            ]),
            Response::Stats(crate::types::DbStats {
                collection_count: 3,
                record_count: 1500,
            }),
            Response::IndexList(vec![
                "email".to_string(),
                "username".to_string(),
            ]),
            
            // Record & Query Responses
            Response::Record(Some({
                let mut record = Record::new();
                record.insert("id".to_string(), json!("user123"));
                record.insert("name".to_string(), json!("Bob"));
                record.insert("email".to_string(), json!("bob@example.com"));
                record
            })),
            Response::Record(None), // Test None case
            Response::RecordSet(crate::types::RecordSet {
                records: vec![
                    {
                        let mut record = Record::new();
                        record.insert("id".to_string(), json!("1"));
                        record.insert("name".to_string(), json!("Item 1"));
                        record
                    },
                    {
                        let mut record = Record::new();
                        record.insert("id".to_string(), json!("2"));
                        record.insert("name".to_string(), json!("Item 2"));
                        record
                    },
                ],
            }),
            Response::RecordCount(42),
            Response::RecordDeleted(true),
            Response::LastInsertId(123),
            Response::RecordWithRelated(Some(({
                let mut order = Record::new();
                order.insert("id".to_string(), json!("order123"));
                order.insert("amount".to_string(), json!(99.99));
                order
            }, {
                let mut user = Record::new();
                user.insert("id".to_string(), json!("user456"));
                user.insert("name".to_string(), json!("Charlie"));
                user
            }))),
            Response::RecordWithRelated(None), // Test None case
            Response::BatchResponse({
                let mut results = HashMap::new();
                let mut user_record = Record::new();
                user_record.insert("id".to_string(), json!("user123"));
                user_record.insert("name".to_string(), json!("Dave"));
                
                let mut product_record = Record::new();
                product_record.insert("id".to_string(), json!("product456"));
                product_record.insert("name".to_string(), json!("Gadget"));
                
                results.insert("key1".to_string(), Some(user_record));
                results.insert("key2".to_string(), Some(product_record));
                results.insert("key3".to_string(), None); // Test None case
                
                crate::types::BatchResponse { results }
            }),
        ];
        
        for response in responses {
            test_serialization_json(response);
        }
    }
}
#[test]
fn test_result_metrics_serialization() {
    // 1. Create the inner data (the actual result of a query).
    let record_set = RecordSet { records: vec![] };
    let inner_response = Response::RecordSet(record_set);

    // 2. Create the metrics data.
    let metrics = QueryMetrics {
        execution_time_micros: 12345,
    };

    // 3. Wrap them in the new ResultMetrics response.
    let original_response = Response::ResultMetrics {
        data: Box::new(inner_response),
        metrics,
    };

    // 4. Serialize and deserialize the response.
    let bytes = bincode::serialize(&original_response).unwrap();
    let deserialized_response: Response = bincode::deserialize(&bytes).unwrap();

    // 5. Assert that the data survived the round trip perfectly.
    assert_eq!(original_response, deserialized_response);
}