Skip to main content

aurora_db/network/
protocol.rs

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