Skip to content

Commit 5752d1e

Browse files
authored
mostly docs, some code tweaks as well (#31)
Db background tasks never shutdown o_O
1 parent 757de67 commit 5752d1e

File tree

8 files changed

+339
-58
lines changed

8 files changed

+339
-58
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,11 @@ the server to update the active subscriptions.
112112
[broadcast]: https://docs.rs/tokio/*/tokio/sync/broadcast/index.html
113113
[`StreamMap`]: https://docs.rs/tokio/*/tokio/stream/struct.StreamMap.html
114114

115+
### Using a `std::sync::Mutex` in an async application
116+
117+
The server uses a `std::sync::Mutex` and **not** a Tokio mutex to synchronize
118+
access to shared state. See [`db.rs`](src/db.rs) for more details.
119+
115120
## Contributing
116121

117122
Contributions to `mini-redis` are welcome. Keep in mind, the goal of the project

src/client.rs

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,7 @@ impl Client {
4747
/// Set the value of a key to `value`.
4848
#[instrument(skip(self))]
4949
pub async fn set(&mut self, key: &str, value: Bytes) -> crate::Result<()> {
50-
self.set_cmd(Set {
51-
key: key.to_string(),
52-
value: value,
53-
expire: None,
54-
})
55-
.await
50+
self.set_cmd(Set::new(key, value, None)).await
5651
}
5752

5853
/// publish `message` on the `channel`
@@ -88,12 +83,7 @@ impl Client {
8883
value: Bytes,
8984
expiration: Duration,
9085
) -> crate::Result<()> {
91-
self.set_cmd(Set {
92-
key: key.to_string(),
93-
value: value.into(),
94-
expire: Some(expiration),
95-
})
96-
.await
86+
self.set_cmd(Set::new(key, value, Some(expiration))).await
9787
}
9888

9989
async fn set_cmd(&mut self, cmd: Set) -> crate::Result<()> {

src/cmd/get.rs

Lines changed: 45 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
1-
use crate::{Connection, Db, Frame, Parse, ParseError};
1+
use crate::{Connection, Db, Frame, Parse};
22

33
use bytes::Bytes;
44
use tracing::{debug, instrument};
55

6+
/// Get the value of key.
7+
///
8+
/// If the key does not exist the special value nil is returned. An error is
9+
/// returned if the value stored at key is not a string, because GET only
10+
/// handles string values.
611
#[derive(Debug)]
712
pub struct Get {
13+
/// Name of the key to get
814
key: String,
915
}
1016

@@ -14,36 +20,63 @@ impl Get {
1420
Get { key: key.to_string() }
1521
}
1622

17-
// instrumenting functions will log all of the arguments passed to the function
18-
// with their debug implementations
19-
// see https://docs.rs/tracing/0.1.13/tracing/attr.instrument.html
20-
pub(crate) fn parse_frames(parse: &mut Parse) -> Result<Get, ParseError> {
23+
/// Parse a `Get` instance from received data.
24+
///
25+
/// The `Parse` argument provides a cursor like API to read fields from a
26+
/// received `Frame`. At this point, the data has already been received from
27+
/// the socket.
28+
///
29+
/// The `GET` string has already been consumed.
30+
///
31+
/// # Returns
32+
///
33+
/// Returns the `Get` value on success. If the frame is malformed, `Err` is
34+
/// returned.
35+
///
36+
/// # Format
37+
///
38+
/// Expects an array frame containing two entries.
39+
///
40+
/// ```text
41+
/// GET key
42+
/// ```
43+
pub(crate) fn parse_frames(parse: &mut Parse) -> crate::Result<Get> {
44+
// The `GET` string has already been consumed. The next value is the
45+
// name of the key to get. If the next value is not a string or the
46+
// input is fully consumed, then an error is returned.
2147
let key = parse.next_string()?;
2248

23-
// adding this debug event allows us to see what key is parsed
24-
// the ? sigil tells `tracing` to use the `Debug` implementation
25-
// get parse events can be filtered by running
26-
// RUST_LOG=mini_redis::cmd::get[parse_frames]=debug cargo run --bin server
27-
// see https://docs.rs/tracing/0.1.13/tracing/#recording-fields
28-
debug!(?key);
29-
3049
Ok(Get { key })
3150
}
3251

52+
/// Apply the `Get` command to the specified `Db` instance.
53+
///
54+
/// The response is written to `dst`. This is called by the server in order
55+
/// to execute a received command.
3356
#[instrument(skip(self, db, dst))]
3457
pub(crate) async fn apply(self, db: &Db, dst: &mut Connection) -> crate::Result<()> {
58+
// Get the value from the shared database state
3559
let response = if let Some(value) = db.get(&self.key) {
60+
// If a value is present, it is written to the client in "bulk"
61+
// format.
3662
Frame::Bulk(value)
3763
} else {
64+
// If there is no value, `Null` is written.
3865
Frame::Null
3966
};
4067

4168
debug!(?response);
4269

70+
// Write the response back to the client
4371
dst.write_frame(&response).await?;
72+
4473
Ok(())
4574
}
4675

76+
/// Converts the command into an equivalent `Frame`.
77+
///
78+
/// This is called by the client when encoding a `Get` command to send to
79+
/// the server.
4780
pub(crate) fn into_frame(self) -> Frame {
4881
let mut frame = Frame::array();
4982
frame.push_bulk(Bytes::from("get".as_bytes()));

src/cmd/mod.rs

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ pub use unknown::Unknown;
1515

1616
use crate::{Connection, Db, Frame, Parse, ParseError, Shutdown};
1717

18+
/// Enumeration of supported Redis commands.
19+
///
20+
/// Methods called on `Command` are delegated to the command implementation.
1821
#[derive(Debug)]
1922
pub(crate) enum Command {
2023
Get(Get),
@@ -26,27 +29,59 @@ pub(crate) enum Command {
2629
}
2730

2831
impl Command {
32+
/// Parse a command from a received frame.
33+
///
34+
/// The `Frame` must represent a Redis command supported by `mini-redis` and
35+
/// be the array variant.
36+
///
37+
/// # Returns
38+
///
39+
/// On success, the command value is returned, otherwise, `Err` is returned.
2940
pub(crate) fn from_frame(frame: Frame) -> crate::Result<Command> {
41+
// The frame value is decorated with `Parse`. `Parse` provides a
42+
// "cursor" like API which makes parsing the command easier.
43+
//
44+
// The frame value must be an array variant. Any other frame variants
45+
// result in an error being returned.
3046
let mut parse = Parse::new(frame)?;
3147

48+
// All redis commands begin with the command name as a string. The name
49+
// is read and converted to lower casae in order to do case sensitive
50+
// matching.
3251
let command_name = parse.next_string()?.to_lowercase();
3352

53+
// Match the command name, delegating the rest of the parsing to the
54+
// specific command.
3455
let command = match &command_name[..] {
3556
"get" => Command::Get(Get::parse_frames(&mut parse)?),
3657
"publish" => Command::Publish(Publish::parse_frames(&mut parse)?),
3758
"set" => Command::Set(Set::parse_frames(&mut parse)?),
3859
"subscribe" => Command::Subscribe(Subscribe::parse_frames(&mut parse)?),
3960
"unsubscribe" => Command::Unsubscribe(Unsubscribe::parse_frames(&mut parse)?),
4061
_ => {
41-
parse.next_string()?;
42-
Command::Unknown(Unknown::new(command_name))
62+
// The command is not recognized and an Unknown command is
63+
// returned.
64+
//
65+
// `return` is called here to skip the `finish()` call below. As
66+
// the command is not recognized, there is most likely
67+
// unconsumed fields remaining in the `Parse` instance.
68+
return Ok(Command::Unknown(Unknown::new(command_name)));
4369
},
4470
};
4571

72+
// Check if there is any remaining unconsumed fields in the `Parse`
73+
// value. If fields remain, this indicates an unexpected frame format
74+
// and an error is returned.
4675
parse.finish()?;
76+
77+
// The command has been successfully parsed
4778
Ok(command)
4879
}
4980

81+
/// Apply the command to the specified `Db` instance.
82+
///
83+
/// The response is written to `dst`. This is called by the server in order
84+
/// to execute a received command.
5085
pub(crate) async fn apply(
5186
self,
5287
db: &Db,
@@ -63,10 +98,11 @@ impl Command {
6398
Unknown(cmd) => cmd.apply(dst).await,
6499
// `Unsubscribe` cannot be applied. It may only be received from the
65100
// context of a `Subscribe` command.
66-
Unsubscribe(_) => unimplemented!(),
101+
Unsubscribe(_) => Err("`Unsubscribe` is unsupported in this context".into()),
67102
}
68103
}
69104

105+
/// Returns the command name
70106
pub(crate) fn get_name(&self) -> &str {
71107
match self {
72108
Command::Get(_) => "get",

src/cmd/publish.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::{Connection, Db, Frame, Parse, ParseError};
1+
use crate::{Connection, Db, Frame, Parse};
22

33
use bytes::Bytes;
44

@@ -9,13 +9,17 @@ pub struct Publish {
99
}
1010

1111
impl Publish {
12-
pub(crate) fn parse_frames(parse: &mut Parse) -> Result<Publish, ParseError> {
12+
pub(crate) fn parse_frames(parse: &mut Parse) -> crate::Result<Publish> {
1313
let channel = parse.next_string()?;
1414
let message = parse.next_bytes()?;
1515

1616
Ok(Publish { channel, message })
1717
}
1818

19+
/// Apply the `Publish` command to the specified `Db` instance.
20+
///
21+
/// The response is written to `dst`. This is called by the server in order
22+
/// to execute a received command.
1923
pub(crate) async fn apply(self, db: &Db, dst: &mut Connection) -> crate::Result<()> {
2024
// Set the value
2125
let num_subscribers = db.publish(&self.channel, self.message);

src/cmd/set.rs

Lines changed: 81 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,57 +5,127 @@ use bytes::Bytes;
55
use std::time::Duration;
66
use tracing::{debug, instrument};
77

8+
/// Set `key` to hold the string `value`.
9+
///
10+
/// If `key` already holds a value, it is overwritten, regardless of its type.
11+
/// Any previous time to live associated with the key is discarded on successful
12+
/// SET operation.
13+
///
14+
/// # Options
15+
///
16+
/// Currently, the following options are supported:
17+
///
18+
/// * EX `seconds` -- Set the specified expire time, in seconds.
19+
/// * PX `milliseconds` -- Set the specified expire time, in milliseconds.
820
#[derive(Debug)]
921
pub struct Set {
1022
/// the lookup key
11-
pub(crate) key: String,
23+
key: String,
1224

1325
/// the value to be stored
14-
pub(crate) value: Bytes,
26+
value: Bytes,
1527

1628
/// When to expire the key
17-
pub(crate) expire: Option<Duration>,
29+
expire: Option<Duration>,
1830
}
1931

2032
impl Set {
21-
#[instrument]
22-
pub(crate) fn parse_frames(parse: &mut Parse) -> Result<Set, ParseError> {
33+
/// Create a new `Set` command which sets `key` to `value`.
34+
///
35+
/// If `expire` is `Some`, the value should expire after the specified
36+
/// duration.
37+
pub(crate) fn new(key: impl ToString, value: Bytes, expire: Option<Duration>) -> Set {
38+
Set {
39+
key: key.to_string(),
40+
value,
41+
expire,
42+
}
43+
}
44+
45+
/// Parse a `Set` instance from received data.
46+
///
47+
/// The `Parse` argument provides a cursor like API to read fields from a
48+
/// received `Frame`. At this point, the data has already been received from
49+
/// the socket.
50+
///
51+
/// The `SET` string has already been consumed.
52+
///
53+
/// # Returns
54+
///
55+
/// Returns the `Set` value on success. If the frame is malformed, `Err` is
56+
/// returned.
57+
///
58+
/// # Format
59+
///
60+
/// Expects an array frame containing at least 3 entries.
61+
///
62+
/// ```text
63+
/// SET key value [EX seconds|PX milliseconds]
64+
/// ```
65+
pub(crate) fn parse_frames(parse: &mut Parse) -> crate::Result<Set> {
2366
use ParseError::EndOfStream;
2467

68+
// Read the key to set. This is a required field
2569
let key = parse.next_string()?;
70+
71+
// Read the value to set. This is a required field.
2672
let value = parse.next_bytes()?;
73+
74+
// The expiration is optional. If nothing else follows, then it is
75+
// `None`.
2776
let mut expire = None;
2877

78+
// Attempt to parse another string.
2979
match parse.next_string() {
3080
Ok(s) if s == "EX" => {
81+
// An expiration is specified in seconds. The next value is an
82+
// integer.
3183
let secs = parse.next_int()?;
3284
expire = Some(Duration::from_secs(secs));
3385
}
3486
Ok(s) if s == "PX" => {
87+
// An expiration is specified in milliseconds. The next value is
88+
// an integer.
3589
let ms = parse.next_int()?;
3690
expire = Some(Duration::from_millis(ms));
3791
}
38-
Ok(_) => unimplemented!(),
92+
// Currently, mini-redis does not support any of the other SET
93+
// options. An error here results in the connection being
94+
// terminated. Other connections will continue to operate normally.
95+
Ok(_) => return Err("currently `SET` only supports the expiration option".into()),
96+
// The `EndOfStream` error indicates there is no further data to
97+
// parse. In this case, it is a normal run time situation and
98+
// indicates there are no specified `SET` options.
3999
Err(EndOfStream) => {}
40-
Err(err) => return Err(err),
100+
// All other errors are bubbled up, resulting in the connection
101+
// being terminated.
102+
Err(err) => return Err(err.into()),
41103
}
42104

43-
debug!(?key, ?value, ?expire);
44-
45105
Ok(Set { key, value, expire })
46106
}
47107

48-
#[instrument(skip(db))]
108+
/// Apply the `Get` command to the specified `Db` instace.
109+
///
110+
/// The response is written to `dst`. This is called by the server in order
111+
/// to execute a received command.
112+
#[instrument(skip(self, db, dst))]
49113
pub(crate) async fn apply(self, db: &Db, dst: &mut Connection) -> crate::Result<()> {
50-
// Set the value
114+
// Set the value in the shared database state.
51115
db.set(self.key, self.value, self.expire);
52116

117+
// Create a success response and write it to `dst`.
53118
let response = Frame::Simple("OK".to_string());
54119
debug!(?response);
55120
dst.write_frame(&response).await?;
121+
56122
Ok(())
57123
}
58124

125+
/// Converts the command into an equivalent `Frame`.
126+
///
127+
/// This is called by the client when encoding a `Set` command to send to
128+
/// the server.
59129
pub(crate) fn into_frame(self) -> Frame {
60130
let mut frame = Frame::array();
61131
frame.push_bulk(Bytes::from("set".as_bytes()));

0 commit comments

Comments
 (0)