Skip to main content

aurora_db/network/
protocol.rs

1use crate::query::SimpleQueryBuilder;
2use crate::types::{Document, FieldType, Value};
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6/// A module to handle Base64 encoding for Vec<u8> in JSON.
7mod base64_serde {
8    use base64::{Engine as _, engine::general_purpose};
9    use serde::{self, Deserialize, Deserializer, Serializer};
10
11    pub fn serialize<S>(bytes: &Vec<u8>, serializer: S) -> Result<S::Ok, S::Error>
12    where
13        S: Serializer,
14    {
15        if serializer.is_human_readable() {
16            let base64 = general_purpose::STANDARD.encode(bytes);
17            serializer.serialize_str(&base64)
18        } else {
19            serializer.serialize_bytes(bytes)
20        }
21    }
22
23    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
24    where
25        D: Deserializer<'de>,
26    {
27        if deserializer.is_human_readable() {
28            let base64 = <String>::deserialize(deserializer)?;
29            general_purpose::STANDARD
30                .decode(&base64)
31                .map_err(serde::de::Error::custom)
32        } else {
33            <Vec<u8>>::deserialize(deserializer)
34        }
35    }
36}
37
38/// Represents a request sent from a client to the server.
39#[derive(Serialize, Deserialize, Debug)]
40pub enum Request {
41    /// Get a value by key.
42    Get(String),
43    /// Put a value by key.
44    Put(String, #[serde(with = "base64_serde")] Vec<u8>),
45    /// Delete a key.
46    Delete(String),
47    /// Create a new collection.
48    NewCollection {
49        name: String,
50        fields: Vec<(String, FieldType, bool)>,
51    },
52    /// Insert a document into a collection.
53    Insert {
54        collection: String,
55        data: HashMap<String, Value>,
56    },
57    /// Get a document from a collection by ID.
58    GetDocument { collection: String, id: String },
59    /// Query a collection.
60    Query(SimpleQueryBuilder),
61    /// Begin a transaction.
62    BeginTransaction,
63    /// Commit a transaction.
64    CommitTransaction(u64),
65    /// Roll back a transaction.
66    RollbackTransaction(u64),
67}
68
69/// Represents a response sent from the server to a client.
70#[derive(Serialize, Deserialize, Debug)]
71pub enum Response {
72    /// A successful operation with an optional value.
73    Success(#[serde(with = "base64_serde_option")] Option<Vec<u8>>),
74    /// A successful operation with a Document.
75    Document(Option<Document>),
76    /// A successful operation with a list of Documents.
77    Documents(Vec<Document>),
78    /// A successful operation with a string response (e.g., a document ID).
79    Message(String),
80    /// Transaction ID returned from BeginTransaction.
81    TransactionId(u64),
82    /// A successful operation with no return value.
83    Done,
84    /// An error occurred.
85    Error(String),
86}
87
88/// A module for optional Base64 encoding.
89mod base64_serde_option {
90    use base64::{Engine as _, engine::general_purpose};
91    use serde::{self, Deserialize, Deserializer, Serializer};
92
93    pub fn serialize<S>(bytes: &Option<Vec<u8>>, serializer: S) -> Result<S::Ok, S::Error>
94    where
95        S: Serializer,
96    {
97        match bytes {
98            Some(b) => super::base64_serde::serialize(b, serializer),
99            None => serializer.serialize_none(),
100        }
101    }
102
103    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Vec<u8>>, D::Error>
104    where
105        D: Deserializer<'de>,
106    {
107        let opt: Option<Vec<u8>> = if deserializer.is_human_readable() {
108            let base64: Option<String> = Option::deserialize(deserializer)?;
109            match base64 {
110                Some(s) => Some(
111                    general_purpose::STANDARD
112                        .decode(&s)
113                        .map_err(serde::de::Error::custom)?,
114                ),
115                None => None,
116            }
117        } else {
118            Option::deserialize(deserializer)?
119        };
120        Ok(opt)
121    }
122}