|
| 1 | +use crate::{Connection, Frame, Parse, ParseError}; |
| 2 | +use bytes::Bytes; |
| 3 | +use tracing::{debug, instrument}; |
| 4 | + |
| 5 | +/// Returns PONG if no argument is provided, otherwise |
| 6 | +/// return a copy of the argument as a bulk. |
| 7 | +/// |
| 8 | +/// This command is often used to test if a connection |
| 9 | +/// is still alive, or to measure latency. |
| 10 | +#[derive(Debug, Default)] |
| 11 | +pub struct Ping { |
| 12 | + /// optional message to be returned |
| 13 | + msg: Option<String>, |
| 14 | +} |
| 15 | + |
| 16 | +impl Ping { |
| 17 | + /// Create a new `Ping` command with optional `msg`. |
| 18 | + pub fn new(msg: Option<String>) -> Ping { |
| 19 | + Ping { msg } |
| 20 | + } |
| 21 | + |
| 22 | + /// Parse a `Ping` instance from a received frame. |
| 23 | + /// |
| 24 | + /// The `Parse` argument provides a cursor-like API to read fields from the |
| 25 | + /// `Frame`. At this point, the entire frame has already been received from |
| 26 | + /// the socket. |
| 27 | + /// |
| 28 | + /// The `PING` string has already been consumed. |
| 29 | + /// |
| 30 | + /// # Returns |
| 31 | + /// |
| 32 | + /// Returns the `Ping` value on success. If the frame is malformed, `Err` is |
| 33 | + /// returned. |
| 34 | + /// |
| 35 | + /// # Format |
| 36 | + /// |
| 37 | + /// Expects an array frame containing `PING` and an optional message. |
| 38 | + /// |
| 39 | + /// ```text |
| 40 | + /// PING [message] |
| 41 | + /// ``` |
| 42 | + pub(crate) fn parse_frames(parse: &mut Parse) -> crate::Result<Ping> { |
| 43 | + match parse.next_string() { |
| 44 | + Ok(msg) => Ok(Ping::new(Some(msg))), |
| 45 | + Err(ParseError::EndOfStream) => Ok(Ping::default()), |
| 46 | + Err(e) => Err(e.into()), |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + /// Apply the `Ping` command and return the message. |
| 51 | + /// |
| 52 | + /// The response is written to `dst`. This is called by the server in order |
| 53 | + /// to execute a received command. |
| 54 | + #[instrument(skip(self, dst))] |
| 55 | + pub(crate) async fn apply(self, dst: &mut Connection) -> crate::Result<()> { |
| 56 | + let response = match self.msg { |
| 57 | + None => Frame::Simple("PONG".to_string()), |
| 58 | + Some(msg) => Frame::Bulk(Bytes::from(msg)), |
| 59 | + }; |
| 60 | + |
| 61 | + // Write the response back to the client |
| 62 | + dst.write_frame(&response).await?; |
| 63 | + |
| 64 | + Ok(()) |
| 65 | + } |
| 66 | +} |
0 commit comments