Learning question: In a server, what do you gain when a request becomes a value of its own before any work is done on its behalf?
A server reads bytes and eventually changes some state. The Command pattern is about the moment in between. This article looks at where that moment is in mini-redis, which code creates the request value, which code runs it, and which code does the work.
Scope. We read three files of mini-redis at commit 3d93b42 [S5]. We do not cover undo, command queues or the wire protocol. You need enums and match. async appears in two signatures; read it as "this function can pause", which is all this article needs. The pattern's parts are named as in Design Patterns [S1, ch. 5, "Command"].
A handler that does it all in one arm
The first plan for a request loop is one match on the command name, with the work written inside each arm. It reads the name, and in the same breath it reaches into the store, like a waiter who cooks. It considers the name and the doing to be one act. Then someone asks for a log line that shows each request before it runs, with its arguments, and there is no line of the loop at which the request exists.
Predict
mini-redis accepts GET colour. Before reading on: if you send GET with no key, would you expect the server to find out before or after it has touched the store? What would have to be true of the code for the answer to be "before, always"?
Name the parts
| Role in the pattern [S1] | In mini-redis | Where |
|---|---|---|
| Command | enum Command |
src/cmd/mod.rs line 25 |
| ConcreteCommand | Get, Set, Publish, and four more structs |
src/cmd/get.rs line 12 |
| Client (creates the command) | Command::from_frame |
src/cmd/mod.rs line 44 |
| Invoker | Handler::run |
src/server.rs lines 344 and 364 |
| Receiver | Db |
used at src/cmd/get.rs line 66 |
How does a frame become a command?
Sometimes you need to log a request, reject it, or count it before running it, and there is nothing to hold. Thankfully, there's a simpler way: build a value first. Take a look at Example 1.
Example 1. The command and the code that creates it (src/cmd/mod.rs, lines 25 to 33 and 44 to 84, abridged, comments removed [S5])
pub enum Command {
Get(Get),
Publish(Publish),
Set(Set),
Subscribe(Subscribe),
Unsubscribe(Unsubscribe),
Ping(Ping),
Unknown(Unknown),
}
pub fn from_frame(frame: Frame) -> crate::Result<Command> {
let mut parse = Parse::new(frame)?;
let command_name = parse.next_string()?.to_lowercase();
let command = match &command_name[..] {
"get" => Command::Get(Get::parse_frames(&mut parse)?),
// five more names
_ => return Ok(Command::Unknown(Unknown::new(command_name))),
};
parse.finish()?;
Ok(command)
}
There are three new pieces. enum Command lists every kind of request the server understands; each variant carries a struct with that request's arguments, so a Get holds its key. from_frame takes the Frame by value and returns either a Command or an error. And Unknown is a variant too: a name the server does not know still becomes a value, so the decision about what to answer is made later, by the same code path as everything else.
Now Example 2, where the value is run.
Example 2. The invoker (src/server.rs, lines 344, 355 and 364 to 365, comments removed [S5])
let cmd = Command::from_frame(frame)?;
debug!(?cmd);
cmd.apply(&self.db, &mut self.connection, &mut self.shutdown)
.await?;
Three statements, and the middle one is the answer to the scene. Between creating the command and applying it, cmd is an ordinary value, and the server logs it. apply takes self, so the command is moved into the call and cannot be applied a second time.¹ The store is only lent: &self.db is a borrow, and the handler keeps its database.
What transfers, and what does not
The book describes Command as an interface with an Execute operation and one class per request [S1]. The roles transfer. The shape does not: mini-redis has one enum and a match in Command::apply (line 98) where the book has a class hierarchy. The Rust patterns book makes the same observation in general terms, that the pattern stays useful although Rust has no objects in the book's sense [S2, ch. 7, "Command pattern"]. If you have ever put a job object on a queue in PHP, the idea of a request as a value will be familiar; the difference to hold on to is that this value is consumed by being run.
What does the enum close?
An enum means the list of commands is closed: adding one edits Command, from_frame, apply and get_name, and the compiler will stop at each match on the enum that has not been updated, which is either a welcome checklist or, in a library whose users want to add commands of their own without forking it, the reason to choose something other than an enum, and mini-redis is a server with a fixed protocol, so nobody outside it needs to. In your own code, who needs to add a command: you, or someone who cannot edit your enum?
Practice tier: judgment, with compiler help. Choosing to make the request a value is yours. Once it is an enum, the compiler enforces that every match covers every variant.
Testing
The claim is that a request is checked and named before it can run. Example 3 would fail if from_frame deferred that work.
Example 3. Three frames, no server (tests/p05_command_mini_redis.rs)
#[test]
fn a_get_with_a_missing_key_is_refused_before_a_command_exists() {
assert!(Command::from_frame(frame(&["GET"])).is_err());
}
No Db exists in this test, and no connection. The file has two more tests: GET colour becomes Command::Get holding "colour", and FLUSHALL becomes Command::Unknown. All three passed against the pinned commit on rustc 1.100.0.
Retrieve
- Which function plays the Client, and what does it return when the name is not recognised?
- Why can
cmdnot be applied twice?
The Actors article returns to this value: there, a request travels through a channel, which is only possible because it is one.
TL;DR
mini-redis turns each frame into a Command value with Command::from_frame, and only then calls apply on it from Handler::run. Between the two calls the request can be logged, and a malformed request is refused before the store is involved. The command is an enum with a struct per variant, and applying it consumes it.
¹ apply(self, ..) with no & means the method takes ownership of the value it is called on.