|
| 1 | +use anyhow::Result; |
| 2 | +use futures::SinkExt; |
| 3 | +use tokio::net::TcpStream; |
| 4 | +use tokio_stream::StreamExt; |
| 5 | +use tokio_util::codec::{Decoder, Encoder, Framed}; |
| 6 | +use tracing::info; |
| 7 | + |
| 8 | +use crate::{ |
| 9 | + cmd::{Command, CommandExecutor}, |
| 10 | + Backend, RespDecode, RespEncode, RespError, RespFrame, |
| 11 | +}; |
| 12 | + |
| 13 | +#[derive(Debug)] |
| 14 | +struct RedisRequest { |
| 15 | + frame: RespFrame, |
| 16 | + backend: Backend, |
| 17 | +} |
| 18 | + |
| 19 | +#[derive(Debug)] |
| 20 | +struct RedisResponse { |
| 21 | + frame: RespFrame, |
| 22 | +} |
| 23 | + |
| 24 | +#[derive(Debug)] |
| 25 | +struct RespFrameCodec; |
| 26 | + |
| 27 | +pub async fn stream_handler(stream: TcpStream, backend: Backend) -> Result<()> { |
| 28 | + // how to get a frame from the stream? |
| 29 | + let mut framed = Framed::new(stream, RespFrameCodec); |
| 30 | + loop { |
| 31 | + match framed.next().await { |
| 32 | + Some(Ok(frame)) => { |
| 33 | + info!("Received frame: {:?}", frame); |
| 34 | + let request = RedisRequest { |
| 35 | + frame, |
| 36 | + backend: backend.clone(), |
| 37 | + }; |
| 38 | + let response = request_handler(request).await?; |
| 39 | + info!("Sending response: {:?}", response.frame); |
| 40 | + framed.send(response.frame).await?; |
| 41 | + } |
| 42 | + Some(Err(e)) => return Err(e), |
| 43 | + None => return Ok(()), |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +// NOTE: need a backend to process the frame |
| 49 | +// async fn request_handler(request: RespFrame) -> Result<RespFrame> { |
| 50 | +// todo!() |
| 51 | +// } |
| 52 | +async fn request_handler(request: RedisRequest) -> Result<RedisResponse> { |
| 53 | + let (frame, backend) = (request.frame, request.backend); |
| 54 | + let cmd = Command::try_from(frame)?; |
| 55 | + info!("Executing command: {:?}", cmd); |
| 56 | + let frame = cmd.execute(&backend); |
| 57 | + Ok(RedisResponse { frame }) |
| 58 | +} |
| 59 | + |
| 60 | +impl Encoder<RespFrame> for RespFrameCodec { |
| 61 | + type Error = anyhow::Error; |
| 62 | + |
| 63 | + fn encode(&mut self, item: RespFrame, dst: &mut bytes::BytesMut) -> Result<()> { |
| 64 | + let encoded = item.encode(); |
| 65 | + dst.extend_from_slice(&encoded); |
| 66 | + Ok(()) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +impl Decoder for RespFrameCodec { |
| 71 | + type Item = RespFrame; |
| 72 | + type Error = anyhow::Error; |
| 73 | + |
| 74 | + fn decode(&mut self, src: &mut bytes::BytesMut) -> Result<Option<RespFrame>> { |
| 75 | + match RespFrame::decode(src) { |
| 76 | + Ok(frame) => Ok(Some(frame)), |
| 77 | + Err(RespError::NotComplete) => Ok(None), |
| 78 | + Err(e) => Err(e.into()), |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments