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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
//! Library containing the structs that manage the client to connect to `smol_db`

use crate::client_error::ClientError;
use crate::ClientError::{
    BadPacket, PacketDeserializationError, PacketSerializationError, SocketReadError,
    SocketWriteError, UnableToConnect,
};
use serde::{Deserialize, Serialize};
use smol_db_common::prelude::*;
#[cfg(feature = "statistics")]
use smol_db_common::statistics::DBStatistics;
use std::collections::HashMap;
#[cfg(not(feature = "async"))]
use std::io::{Read, Write};

use std::io::Error;
#[cfg(not(feature = "async"))]
use std::net::Shutdown;

use std::net::SocketAddr;

#[cfg(not(feature = "async"))]
use std::net::TcpStream;

#[cfg(feature = "async")]
use tokio::{io::AsyncReadExt, io::AsyncWriteExt, net::TcpStream};

pub mod client_error;
use crate::client_error::ClientError::{
    DBResponseError, EncryptionSetupError, KeyGenerationError, PacketEncryptionError,
};
use smol_db_common::encryption::client_encrypt::ClientKey;
pub use smol_db_common::{
    db::Role, db_packets::db_packet_response::DBPacketResponseError,
    db_packets::db_packet_response::DBSuccessResponse, db_packets::db_settings,
};

/// Easy usable module containing everything needed to use the client library normally
pub mod prelude {
    pub use crate::client_error;
    pub use crate::client_error::ClientError::DBResponseError;
    pub use crate::SmolDbClient;
    pub use smol_db_common::db::Role;
    pub use smol_db_common::db::Role::*;
    pub use smol_db_common::db_packets::db_packet_info::DBPacketInfo;
    pub use smol_db_common::db_packets::db_packet_response::DBPacketResponseError::*;
    pub use smol_db_common::db_packets::db_packet_response::DBSuccessResponse;
    pub use smol_db_common::db_packets::db_packet_response::DBSuccessResponse::SuccessNoData;
    pub use smol_db_common::db_packets::db_packet_response::DBSuccessResponse::SuccessReply;
    pub use smol_db_common::db_packets::db_settings::DBSettings;
    #[cfg(feature = "statistics")]
    pub use smol_db_common::statistics::DBStatistics;
}

/// `SmolDbClient` struct used for communicating to the database.
/// This struct has implementations that allow for end to end communication with the database server.
pub struct SmolDbClient {
    socket: TcpStream,
    encryption: Option<ClientKey>,
}

impl SmolDbClient {
    /// Creates a new `SmolDBClient` struct connected to the ip address given.
    /// ```
    /// use smol_db_client::SmolDbClient;
    ///
    /// // create the new client
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    /// // client should be functional provided a database server was able to be connected to at the given location
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn new(ip: &str) -> Result<Self, ClientError> {
        let socket = TcpStream::connect(ip);
        match socket {
            Ok(s) => Ok(Self {
                socket: s,
                encryption: None,
            }),
            Err(err) => Err(UnableToConnect(err)),
        }
    }

    #[cfg(feature = "async")]
    pub async fn new(ip: &str) -> Result<Self, ClientError> {
        let socket = TcpStream::connect(ip).await;
        match socket {
            Ok(s) => Ok(Self {
                socket: s,
                encryption: None,
            }),
            Err(err) => Err(UnableToConnect(err)),
        }
    }

    /// Requests the server to use encryption for communication. Encryption is done both ways, and is done using RSA with a 2048 bit key
    /// This function is slow due to large rsa key size ~1-4 seconds to generate the key
    /// Encryption is done invisibly.
    /// ```
    /// use smol_db_client::SmolDbClient;
    /// use smol_db_common::prelude::DBSettings;
    ///
    /// let key = "test_key_123";
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    /// client.set_access_key(key.to_string()).unwrap();
    /// client.setup_encryption().unwrap(); // encryption is done invisibly after it is setup, nothing else is needed :)
    /// client.create_db("docsetup_encryption_test",DBSettings::default()).unwrap();
    /// let _ = client.delete_db("docsetup_encryption_test").unwrap();
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn setup_encryption(&mut self) -> Result<DBSuccessResponse<String>, ClientError> {
        let server_pub_key_ser = self
            .send_packet(&DBPacket::SetupEncryption)?
            .as_option()
            .ok_or(EncryptionSetupError)?
            .to_string();
        let server_pub_key = serde_json::from_str::<RsaPublicKey>(&server_pub_key_ser)
            .map_err(|err| PacketDeserializationError(Error::from(err)))?;
        // this function is really slow due to long key length generation, this can be modified if needed, but at the moment, this is ok.
        let pri_key = ClientKey::new(server_pub_key).map_err(KeyGenerationError)?;
        let pub_client_key = pri_key.get_pub_key().clone();
        self.encryption = Some(pri_key);
        let resp = self.send_packet(&DBPacket::PubKey(pub_client_key));
        if resp.is_err() {
            self.encryption = None;
        }
        resp
    }

    #[cfg(feature = "async")]
    pub async fn setup_encryption(&mut self) -> Result<DBSuccessResponse<String>, ClientError> {
        let server_pub_key_ser = self
            .send_packet(&DBPacket::SetupEncryption)
            .await?
            .as_option()
            .ok_or(EncryptionSetupError)?
            .to_string();
        let server_pub_key = serde_json::from_str::<RsaPublicKey>(&server_pub_key_ser)
            .map_err(|err| PacketDeserializationError(Error::from(err)))?;
        // this function is really slow due to long key length generation, this can be modified if needed, but at the moment, this is ok.
        let pri_key = ClientKey::new(server_pub_key).map_err(KeyGenerationError)?;
        let pub_client_key = pri_key.get_pub_key().clone();
        self.encryption = Some(pri_key);
        let resp = self.send_packet(&DBPacket::PubKey(pub_client_key)).await;
        if resp.is_err() {
            self.encryption = None;
        }
        resp
    }

    /// Returns true if end to end encryption is enabled
    pub fn is_encryption_enabled(&self) -> bool {
        self.encryption.is_some()
    }

    /// Reconnects the client, this will reset the session, which can be used to remove any key that was used.
    /// Or to reconnect in the event of a loss of connection
    /// ```
    /// use smol_db_client::SmolDbClient;
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    ///
    /// // disconnecting is optional between reconnects
    /// client.disconnect().unwrap();
    /// client.reconnect().unwrap();
    ///
    /// // as shown here
    ///
    /// client.reconnect().unwrap();
    ///
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn reconnect(&mut self) -> Result<(), ClientError> {
        let ip = self.socket.peer_addr().map_err(UnableToConnect)?;
        let new_socket = TcpStream::connect(ip).map_err(UnableToConnect)?;
        self.socket = new_socket;
        Ok(())
    }

    /// Reconnects the client, this will reset the session, which can be used to remove any key that was used.
    /// Or to reconnect in the event of a loss of connection
    #[cfg(feature = "async")]
    pub async fn reconnect(&mut self) -> Result<(), ClientError> {
        let ip = self.socket.peer_addr().map_err(UnableToConnect)?;
        let new_socket = TcpStream::connect(ip).await.map_err(UnableToConnect)?;
        self.socket = new_socket;
        Ok(())
    }

    /// Returns a result containing the peer address of this client
    pub fn get_connected_ip(&self) -> std::io::Result<SocketAddr> {
        self.socket.peer_addr()
    }

    /// Disconnects the socket from the database.
    /// ```
    /// use smol_db_client::SmolDbClient;
    ///
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    ///
    /// // disconnect the client
    /// let _ = client.disconnect().expect("Failed to disconnect socket");
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn disconnect(&self) -> std::io::Result<()> {
        self.socket.shutdown(Shutdown::Both)
    }

    /// Disconnects the socket from the database.
    #[cfg(feature = "async")]
    pub async fn disconnect(&mut self) -> std::io::Result<()> {
        self.socket.shutdown().await
    }

    /// Deletes the data at the given db location, requires permissions to do so.
    /// ```
    /// use smol_db_client::client_error::ClientError;
    /// use smol_db_client::SmolDbClient;
    /// use smol_db_common::db_packets::db_packet_response::DBPacketResponseError;
    /// use smol_db_common::db_packets::db_settings::DBSettings;
    ///
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    ///
    /// let _ = client.set_access_key("test_key_123".to_string()).unwrap();
    /// let _ = client.create_db("doctest_delete_data",DBSettings::default()).unwrap();
    /// let _ = client.write_db("doctest_delete_data","cool_data_location","cool_data");
    /// let read_data1 = client.read_db("doctest_delete_data","cool_data_location").unwrap().as_option().unwrap().to_string();
    /// assert_eq!(read_data1.as_str(),"cool_data");
    ///
    /// // delete the data at the given location
    /// let _ = client.delete_data("doctest_delete_data","cool_data_location").unwrap();
    /// let read_data2 = client.read_db("doctest_delete_data","cool_data_location");
    /// assert_eq!(read_data2.unwrap_err(),ClientError::DBResponseError(DBPacketResponseError::ValueNotFound)); // is err here means DBResponseError(ValueNotFound)
    ///
    /// let _ = client.delete_db("doctest_delete_data").unwrap();
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn delete_data(
        &mut self,
        db_name: &str,
        db_location: &str,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_delete_data(db_name, db_location);
        self.send_packet(&packet)
    }

    /// Deletes the data at the given db location, requires permissions to do so.
    #[cfg(feature = "async")]
    pub async fn delete_data(
        &mut self,
        db_name: &str,
        db_location: &str,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_delete_data(db_name, db_location);
        self.send_packet(&packet).await
    }

    /// Returns the `DBStatistics` struct if permissions allow it on a given db
    #[cfg(feature = "statistics")]
    #[cfg(not(feature = "async"))]
    pub fn get_stats(&mut self, db_name: &str) -> Result<DBStatistics, ClientError> {
        let packet = DBPacket::new_get_stats(db_name);
        let resp = self.send_packet(&packet)?;

        match resp {
            SuccessNoData => Err(BadPacket),
            SuccessReply(data) => match serde_json::from_str::<DBStatistics>(&data) {
                Ok(statistics) => Ok(statistics),
                Err(err) => Err(PacketDeserializationError(Error::from(err))),
            },
        }
    }

    /// Returns the `DBStatistics` struct if permissions allow it on a given db
    #[cfg(feature = "statistics")]
    #[cfg(feature = "async")]
    pub async fn get_stats(&mut self, db_name: &str) -> Result<DBStatistics, ClientError> {
        let packet = DBPacket::new_get_stats(db_name);
        let resp = self.send_packet(&packet).await?;

        match resp {
            SuccessNoData => Err(BadPacket),
            SuccessReply(data) => match serde_json::from_str::<DBStatistics>(&data) {
                Ok(statistics) => Ok(statistics),
                Err(err) => Err(PacketDeserializationError(Error::from(err))),
            },
        }
    }

    /// Returns the role of the given client in the given db.
    /// ```
    /// use smol_db_client::SmolDbClient;
    /// use smol_db_common::db::Role;
    /// use smol_db_common::db_packets::db_settings::DBSettings;
    ///
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    ///
    /// let _ = client.set_access_key("test_key_123".to_string()).unwrap();
    /// let _ = client.create_db("doctest_get_role",DBSettings::default()).unwrap();
    ///
    /// // get the given clients role from a db
    /// let role = client.get_role("doctest_get_role").unwrap();
    /// assert_eq!(role,Role::SuperAdmin);
    ///
    /// let _ = client.delete_db("doctest_get_role").unwrap();
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn get_role(&mut self, db_name: &str) -> Result<Role, ClientError> {
        let packet = DBPacket::new_get_role(db_name);

        let resp = self.send_packet(&packet)?;

        match resp {
            SuccessNoData => Err(BadPacket),
            SuccessReply(data) => match serde_json::from_str::<Role>(&data) {
                Ok(role) => Ok(role),
                Err(err) => Err(PacketDeserializationError(Error::from(err))),
            },
        }
    }

    /// Returns the role of the given client in the given db.
    #[cfg(feature = "async")]
    pub async fn get_role(&mut self, db_name: &str) -> Result<Role, ClientError> {
        let packet = DBPacket::new_get_role(db_name);

        let resp = self.send_packet(&packet).await?;

        match resp {
            SuccessNoData => Err(BadPacket),
            SuccessReply(data) => match serde_json::from_str::<Role>(&data) {
                Ok(role) => Ok(role),
                Err(err) => Err(PacketDeserializationError(Error::from(err))),
            },
        }
    }

    /// Gets the `DBSettings` of the given DB.
    /// Error on IO error, or when database name does not exist, or when the user lacks permissions to view `DBSettings`.
    /// ```
    /// use smol_db_client::SmolDbClient;
    /// use smol_db_common::db_packets::db_settings::DBSettings;
    ///
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    ///
    /// let _ = client.set_access_key("test_key_123".to_string()).unwrap();
    /// let _ = client.create_db("doctest_get_db_settings",DBSettings::default()).unwrap();
    ///
    /// // get the db settings
    /// let settings = client.get_db_settings("doctest_get_db_settings").unwrap();
    /// assert_eq!(settings,DBSettings::default());
    ///
    /// let _ = client.delete_db("doctest_get_db_settings").unwrap();
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn get_db_settings(&mut self, db_name: &str) -> Result<DBSettings, ClientError> {
        let packet = DBPacket::new_get_db_settings(db_name);

        let resp = self.send_packet(&packet)?;
        match resp {
            SuccessNoData => Err(BadPacket),
            SuccessReply(data) => match serde_json::from_str::<DBSettings>(&data) {
                Ok(db_settings) => Ok(db_settings),
                Err(err) => Err(PacketDeserializationError(Error::from(err))),
            },
        }
    }

    /// Gets the `DBSettings` of the given DB.
    /// Error on IO error, or when database name does not exist, or when the user lacks permissions to view `DBSettings`.
    #[cfg(feature = "async")]
    pub async fn get_db_settings(&mut self, db_name: &str) -> Result<DBSettings, ClientError> {
        let packet = DBPacket::new_get_db_settings(db_name);

        let resp = self.send_packet(&packet).await?;
        match resp {
            SuccessNoData => Err(BadPacket),
            SuccessReply(data) => match serde_json::from_str::<DBSettings>(&data) {
                Ok(db_settings) => Ok(db_settings),
                Err(err) => Err(PacketDeserializationError(Error::from(err))),
            },
        }
    }

    /// Sets the `DBSettings` of a given DB
    /// Error on IO Error, or when database does not exist, or when the user lacks permissions to set `DBSettings`
    /// ```
    /// use std::time::Duration;
    /// use smol_db_client::SmolDbClient;
    /// use smol_db_common::db_packets::db_settings::DBSettings;
    ///
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    ///
    /// let _ = client.set_access_key("test_key_123".to_string()).unwrap();
    /// let _ = client.create_db("doctest_set_db_settings",DBSettings::default()).unwrap();
    ///
    /// // set the new db settings
    /// let new_settings = DBSettings::new(Duration::from_secs(10),(true,false,true),(false,false,false),vec![],vec![]);
    /// let _ = client.set_db_settings("doctest_set_db_settings",new_settings.clone()).unwrap();
    ///
    /// let settings = client.get_db_settings("doctest_set_db_settings").unwrap();
    /// assert_eq!(settings,new_settings);
    ///
    /// let _ = client.delete_db("doctest_set_db_settings").unwrap();
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn set_db_settings(
        &mut self,
        db_name: &str,
        db_settings: DBSettings,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_set_db_settings(db_name, db_settings);
        self.send_packet(&packet)
    }

    /// Sets the `DBSettings` of a given DB
    /// Error on IO Error, or when database does not exist, or when the user lacks permissions to set `DBSettings`
    #[cfg(feature = "async")]
    pub async fn set_db_settings(
        &mut self,
        db_name: &str,
        db_settings: DBSettings,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_set_db_settings(db_name, db_settings);
        self.send_packet(&packet).await
    }

    /// Sets this clients access key within the DB Server. The server will persist the key until the session is disconnected, or connection is lost.
    /// ```
    /// use smol_db_client::SmolDbClient;
    /// use smol_db_common::db_packets::db_settings::DBSettings;
    ///
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    ///
    /// // sets the access key of the given client
    /// let _ = client.set_access_key("test_key_123".to_string()).unwrap();
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn set_access_key(
        &mut self,
        key: String,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_set_key(key);
        self.send_packet(&packet)
    }

    /// Sets this clients access key within the DB Server. The server will persist the key until the session is disconnected, or connection is lost.
    #[cfg(feature = "async")]
    pub async fn set_access_key(
        &mut self,
        key: String,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_set_key(key);
        self.send_packet(&packet).await
    }

    /// Sends a packet to the clients currently connected database and returns the result
    #[cfg(not(feature = "async"))]

    fn send_packet(
        &mut self,
        sent_packet: &DBPacket,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let mut buf: [u8; 1024] = [0; 1024];

        // branch depending on if we are using encryption with communication
        let ser_packet = match &mut self.encryption {
            None => sent_packet
                .serialize_packet()
                .map_err(|err| PacketSerializationError(Error::from(err)))?,
            Some(client_encrypt) => {
                // if we are sending a public key packet, we dont encrypt it, since the server needs this to send data back properly
                if !matches!(sent_packet, DBPacket::PubKey(_)) {
                    client_encrypt
                        .encrypt_packet(sent_packet)
                        .map_err(PacketEncryptionError)?
                        .serialize_packet()
                        .map_err(|err| PacketSerializationError(Error::from(err)))?
                } else {
                    sent_packet
                        .serialize_packet()
                        .map_err(|err| PacketSerializationError(Error::from(err)))?
                }
            }
        };

        self.socket
            .write(ser_packet.as_bytes())
            .map_err(SocketWriteError)?;
        let read_len = self.socket.read(&mut buf).map_err(SocketReadError)?;
        match serde_json::from_slice::<Result<DBSuccessResponse<String>, DBPacketResponseError>>(
            &buf[0..read_len],
        ) {
            Ok(thing) => thing.map_err(DBResponseError),
            Err(err) => {
                // if we fail to read a packet, check if it is an encrypted packet
                if let Some(client_private_key) = &self.encryption {
                    client_private_key
                        .decrypt_server_packet(&buf[0..read_len])
                        .unwrap()
                        .map_err(DBResponseError)
                } else {
                    Err(PacketDeserializationError(Error::from(err)))
                }
            }
        }
    }

    /// Sends a packet to the clients currently connected database and returns the result
    #[cfg(feature = "async")]
    async fn send_packet(
        &mut self,
        sent_packet: &DBPacket,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let mut buf: [u8; 1024] = [0; 1024];

        // branch depending on if we are using encryption with communication
        let ser_packet = match &mut self.encryption {
            None => sent_packet
                .serialize_packet()
                .map_err(|err| PacketSerializationError(Error::from(err)))?,
            Some(client_encrypt) => {
                // if we are sending a public key packet, we dont encrypt it, since the server needs this to send data back properly
                if !matches!(sent_packet, DBPacket::PubKey(_)) {
                    client_encrypt
                        .encrypt_packet(sent_packet)
                        .map_err(PacketEncryptionError)?
                        .serialize_packet()
                        .map_err(|err| PacketSerializationError(Error::from(err)))?
                } else {
                    sent_packet
                        .serialize_packet()
                        .map_err(|err| PacketSerializationError(Error::from(err)))?
                }
            }
        };

        self.socket
            .write(ser_packet.as_bytes())
            .await
            .map_err(SocketWriteError)?;
        let read_len = self.socket.read(&mut buf).await.map_err(SocketReadError)?;
        match serde_json::from_slice::<Result<DBSuccessResponse<String>, DBPacketResponseError>>(
            &buf[0..read_len],
        ) {
            Ok(thing) => thing.map_err(DBResponseError),
            Err(err) => {
                // if we fail to read a packet, check if it is an encrypted packet
                if let Some(client_private_key) = &self.encryption {
                    client_private_key
                        .decrypt_server_packet(&buf[0..read_len])
                        .unwrap()
                        .map_err(DBResponseError)
                } else {
                    Err(PacketDeserializationError(Error::from(err)))
                }
            }
        }
    }

    /// Creates a db through the client with the given name.
    /// Error on IO Error, or when the user lacks permissions to create a DB
    /// ```
    /// use std::time::Duration;
    /// use smol_db_client::SmolDbClient;
    /// use smol_db_common::db_packets::db_settings::DBSettings;
    ///
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    ///
    /// let _ = client.set_access_key("test_key_123".to_string()).unwrap();
    /// let _ = client.create_db("doctest_create_db",DBSettings::default()).unwrap();
    ///
    /// let _ = client.delete_db("doctest_create_db").unwrap();
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn create_db(
        &mut self,
        db_name: &str,
        db_settings: DBSettings,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_create_db(db_name, db_settings);
        let resp = self.send_packet(&packet)?;

        Ok(resp)
    }

    /// Creates a db through the client with the given name.
    /// Error on IO Error, or when the user lacks permissions to create a DB
    #[cfg(feature = "async")]
    pub async fn create_db(
        &mut self,
        db_name: &str,
        db_settings: DBSettings,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_create_db(db_name, db_settings);
        let resp = self.send_packet(&packet).await?;

        Ok(resp)
    }

    /// Writes to a db at the location specified, with the data given as a string.
    /// Returns the data in the location that was over written if there was any.
    /// Requires permissions to write to the given DB
    /// ```
    /// use smol_db_client::SmolDbClient;
    /// use smol_db_common::db_packets::db_settings::DBSettings;
    ///
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    ///
    /// let _ = client.set_access_key("test_key_123".to_string()).unwrap();
    /// let _ = client.create_db("doctest_write_data",DBSettings::default()).unwrap();
    ///
    /// // write the given data to the given location within the specified db
    /// let _ = client.write_db("doctest_write_data","cool_data_location","cool_data");
    ///
    /// let read_data1 = client.read_db("doctest_write_data","cool_data_location").unwrap().as_option().unwrap().to_string();
    /// assert_eq!(read_data1.as_str(),"cool_data");
    ///
    /// let _ = client.delete_db("doctest_write_data").unwrap();
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn write_db(
        &mut self,
        db_name: &str,
        db_location: &str,
        data: &str,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_write(db_name, db_location, data);

        self.send_packet(&packet)
    }

    /// Writes to a db at the location specified, with the data given as a string.
    /// Returns the data in the location that was over written if there was any.
    /// Requires permissions to write to the given DB
    #[cfg(feature = "async")]
    pub async fn write_db(
        &mut self,
        db_name: &str,
        db_location: &str,
        data: &str,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_write(db_name, db_location, data);

        self.send_packet(&packet).await
    }

    /// Reads from a db at the location specific.
    /// Returns an error if there is no data in the location.
    /// Requires permissions to read from the given DB
    /// ```
    /// use smol_db_client::SmolDbClient;
    /// use smol_db_common::db_packets::db_settings::DBSettings;
    ///
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    ///
    /// let _ = client.set_access_key("test_key_123".to_string()).unwrap();
    /// let _ = client.create_db("doctest_read_db",DBSettings::default()).unwrap();
    ///
    ///let _ = client.write_db("doctest_read_db","cool_data_location","cool_data");
    ///
    /// // read the given database at the given location
    /// let read_data1 = client.read_db("doctest_read_db","cool_data_location").unwrap().as_option().unwrap().to_string();
    /// assert_eq!(read_data1.as_str(),"cool_data");
    ///
    /// let _ = client.delete_db("doctest_read_db").unwrap();
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn read_db(
        &mut self,
        db_name: &str,
        db_location: &str,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_read(db_name, db_location);

        self.send_packet(&packet)
    }

    /// Reads from a db at the location specific.
    /// Returns an error if there is no data in the location.
    /// Requires permissions to read from the given DB
    #[cfg(feature = "async")]
    pub async fn read_db(
        &mut self,
        db_name: &str,
        db_location: &str,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_read(db_name, db_location);

        self.send_packet(&packet).await
    }

    /// Deletes the given db by name.
    /// Requires super admin privileges on the given DB Server
    /// ```
    /// use smol_db_client::SmolDbClient;
    /// use smol_db_common::db_packets::db_settings::DBSettings;
    ///
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    ///
    /// let _ = client.set_access_key("test_key_123".to_string()).unwrap();
    /// let _ = client.create_db("doctest_delete_db",DBSettings::default()).unwrap();
    ///
    /// // delete the db with the given name
    /// let _ = client.delete_db("doctest_delete_db").unwrap();
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn delete_db(&mut self, db_name: &str) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_delete_db(db_name);

        self.send_packet(&packet)
    }

    /// Deletes the given db by name.
    /// Requires super admin privileges on the given DB Server
    #[cfg(feature = "async")]
    pub async fn delete_db(
        &mut self,
        db_name: &str,
    ) -> Result<DBSuccessResponse<String>, ClientError> {
        let packet = DBPacket::new_delete_db(db_name);

        self.send_packet(&packet).await
    }

    /// Lists all the current databases available by name from the server
    /// Only error on IO Error
    /// ```
    /// use smol_db_client::SmolDbClient;
    /// use smol_db_common::db_packets::db_packet_info::DBPacketInfo;
    /// use smol_db_common::db_packets::db_settings::DBSettings;
    ///
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    ///
    /// let _ = client.set_access_key("test_key_123".to_string()).unwrap();
    /// let _ = client.create_db("doctest_list_db1",DBSettings::default()).unwrap();
    ///
    /// // get list of databases currently on the server
    /// let list_of_dbs1 = client.list_db().unwrap();
    /// assert!(list_of_dbs1.contains(&DBPacketInfo::new("doctest_list_db1")));
    /// assert!(!list_of_dbs1.contains(&DBPacketInfo::new("doctest_list_db2")));
    ///
    /// let _ = client.create_db("doctest_list_db2",DBSettings::default()).unwrap();
    ///
    /// // newly created databases show up after getting another copy of the list
    /// let list_of_dbs2 = client.list_db().unwrap();
    /// assert!(list_of_dbs2.contains(&DBPacketInfo::new("doctest_list_db2")));
    /// assert!(list_of_dbs2.contains(&DBPacketInfo::new("doctest_list_db1")));
    ///
    /// let _ = client.delete_db("doctest_list_db1").unwrap();
    /// let _ = client.delete_db("doctest_list_db2").unwrap();
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn list_db(&mut self) -> Result<Vec<DBPacketInfo>, ClientError> {
        let packet = DBPacket::new_list_db();

        let response = self.send_packet(&packet)?;

        match response {
            SuccessNoData => Err(BadPacket),
            SuccessReply(data) => match serde_json::from_str::<Vec<DBPacketInfo>>(&data) {
                Ok(thing) => Ok(thing),
                Err(err) => Err(PacketDeserializationError(Error::from(err))),
            },
        }
    }

    /// Lists all the current databases available by name from the server
    /// Only error on IO Error
    #[cfg(feature = "async")]
    pub async fn list_db(&mut self) -> Result<Vec<DBPacketInfo>, ClientError> {
        let packet = DBPacket::new_list_db();

        let response = self.send_packet(&packet).await?;

        match response {
            SuccessNoData => Err(BadPacket),
            SuccessReply(data) => match serde_json::from_str::<Vec<DBPacketInfo>>(&data) {
                Ok(thing) => Ok(thing),
                Err(err) => Err(PacketDeserializationError(Error::from(err))),
            },
        }
    }

    /// Get the hashmap of the contents of a database. Contents are always String:String for the hashmap.
    /// Requires list permissions on the given DB
    /// ```
    /// use smol_db_client::SmolDbClient;
    /// use smol_db_common::db_packets::db_settings::DBSettings;
    ///
    /// let mut client = SmolDbClient::new("localhost:8222").unwrap();
    ///
    /// let _ = client.set_access_key("test_key_123".to_string()).unwrap();
    /// let _ = client.create_db("doctest_list_cont_db",DBSettings::default()).unwrap();
    ///
    ///let _ = client.write_db("doctest_list_cont_db","cool_data_location","cool_data");
    ///
    /// let contents = client.list_db_contents("doctest_list_cont_db").unwrap();
    /// assert_eq!(contents.len(),1);
    /// assert_eq!(contents.get("cool_data_location").unwrap().as_str(),"cool_data");
    ///
    /// let _ = client.delete_db("doctest_list_cont_db").unwrap();
    /// ```
    #[cfg(not(feature = "async"))]
    pub fn list_db_contents(
        &mut self,
        db_name: &str,
    ) -> Result<HashMap<String, String>, ClientError> {
        let packet = DBPacket::new_list_db_contents(db_name);

        let response = self.send_packet(&packet)?;

        match response {
            SuccessNoData => Err(BadPacket),
            SuccessReply(data) => match serde_json::from_str::<HashMap<String, String>>(&data) {
                Ok(thing) => Ok(thing),
                Err(err) => Err(PacketDeserializationError(Error::from(err))),
            },
        }
    }

    /// Get the hashmap of the contents of a database. Contents are always String:String for the hashmap.
    /// Requires list permissions on the given DB
    #[cfg(feature = "async")]
    pub async fn list_db_contents(
        &mut self,
        db_name: &str,
    ) -> Result<HashMap<String, String>, ClientError> {
        let packet = DBPacket::new_list_db_contents(db_name);

        let response = self.send_packet(&packet).await?;

        match response {
            SuccessNoData => Err(BadPacket),
            SuccessReply(data) => match serde_json::from_str::<HashMap<String, String>>(&data) {
                Ok(thing) => Ok(thing),
                Err(err) => Err(PacketDeserializationError(Error::from(err))),
            },
        }
    }

    /// Lists the given db's contents, deserializing the contents into a hash map.
    #[cfg(not(feature = "async"))]
    pub fn list_db_contents_generic<T>(
        &mut self,
        db_name: &str,
    ) -> Result<HashMap<String, T>, ClientError>
    where
        for<'a> T: Serialize + Deserialize<'a>,
    {
        let contents = self.list_db_contents(db_name)?;
        let mut converted_contents: HashMap<String, T> = HashMap::new();
        for (key, value) in contents {
            match serde_json::from_str::<T>(&value) {
                Ok(thing) => {
                    converted_contents.insert(key, thing);
                }
                Err(err) => {
                    return Err(PacketDeserializationError(Error::from(err)));
                }
            }
        }
        Ok(converted_contents)
    }

    /// Lists the given db's contents, deserializing the contents into a hash map.
    #[cfg(feature = "async")]
    pub async fn list_db_contents_generic<T>(
        &mut self,
        db_name: &str,
    ) -> Result<HashMap<String, T>, ClientError>
    where
        for<'a> T: Serialize + Deserialize<'a>,
    {
        let contents = self.list_db_contents(db_name).await?;
        let mut converted_contents: HashMap<String, T> = HashMap::new();
        for (key, value) in contents {
            match serde_json::from_str::<T>(&value) {
                Ok(thing) => {
                    converted_contents.insert(key, thing);
                }
                Err(err) => {
                    return Err(PacketDeserializationError(Error::from(err)));
                }
            }
        }
        Ok(converted_contents)
    }

    /// Writes to the db while serializing the given data, returning the data at the location given and deserialized to the same type.
    #[cfg(not(feature = "async"))]
    pub fn write_db_generic<T>(
        &mut self,
        db_name: &str,
        db_location: &str,
        data: T,
    ) -> Result<DBSuccessResponse<T>, ClientError>
    where
        for<'a> T: Serialize + Deserialize<'a>,
    {
        match serde_json::to_string(&data) {
            Ok(ser_data) => match self.write_db(db_name, db_location, &ser_data) {
                Ok(response) => match response {
                    SuccessNoData => Ok(SuccessNoData),
                    SuccessReply(data_string) => match serde_json::from_str::<T>(&data_string) {
                        Ok(thing) => Ok(SuccessReply(thing)),
                        Err(err) => Err(PacketDeserializationError(Error::from(err))),
                    },
                },
                Err(err) => Err(err),
            },
            Err(err) => Err(PacketSerializationError(Error::from(err))),
        }
    }

    /// Writes to the db while serializing the given data, returning the data at the location given and deserialized to the same type.
    #[cfg(feature = "async")]
    pub async fn write_db_generic<T>(
        &mut self,
        db_name: &str,
        db_location: &str,
        data: T,
    ) -> Result<DBSuccessResponse<T>, ClientError>
    where
        for<'a> T: Serialize + Deserialize<'a>,
    {
        match serde_json::to_string(&data) {
            Ok(ser_data) => match self.write_db(db_name, db_location, &ser_data).await {
                Ok(response) => match response {
                    SuccessNoData => Ok(SuccessNoData),
                    SuccessReply(data_string) => match serde_json::from_str::<T>(&data_string) {
                        Ok(thing) => Ok(SuccessReply(thing)),
                        Err(err) => Err(PacketDeserializationError(Error::from(err))),
                    },
                },
                Err(err) => Err(err),
            },
            Err(err) => Err(PacketSerializationError(Error::from(err))),
        }
    }

    /// Reads from db and tries to deserialize the content at the location to the given generic
    #[cfg(not(feature = "async"))]
    pub fn read_db_generic<T>(
        &mut self,
        db_name: &str,
        db_location: &str,
    ) -> Result<DBSuccessResponse<T>, ClientError>
    where
        for<'a> T: Serialize + Deserialize<'a>,
    {
        match self.read_db(db_name, db_location) {
            Ok(data) => match data {
                SuccessNoData => Ok(SuccessNoData),
                SuccessReply(read_data) => match serde_json::from_str::<T>(&read_data) {
                    Ok(data) => Ok(SuccessReply(data)),
                    Err(err) => Err(PacketDeserializationError(Error::from(err))),
                },
            },
            Err(err) => Err(err),
        }
    }

    /// Reads from db and tries to deserialize the content at the location to the given generic
    #[cfg(feature = "async")]
    pub async fn read_db_generic<T>(
        &mut self,
        db_name: &str,
        db_location: &str,
    ) -> Result<DBSuccessResponse<T>, ClientError>
    where
        for<'a> T: Serialize + Deserialize<'a>,
    {
        match self.read_db(db_name, db_location).await {
            Ok(data) => match data {
                SuccessNoData => Ok(SuccessNoData),
                SuccessReply(read_data) => match serde_json::from_str::<T>(&read_data) {
                    Ok(data) => Ok(SuccessReply(data)),
                    Err(err) => Err(PacketDeserializationError(Error::from(err))),
                },
            },
            Err(err) => Err(err),
        }
    }
}