Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
6bae406
feat(resp): implement full RESP3 support with unified architecture
Dayuxiaoshui Oct 12, 2025
717bbb4
style(resp): fix code formatting in resp3_scaffold.rs
Dayuxiaoshui Oct 12, 2025
24062a1
fix(resp): add Apache 2.0 license headers to all new files
Dayuxiaoshui Oct 12, 2025
448006f
docs(resp): add comprehensive docstrings to improve coverage
Dayuxiaoshui Oct 12, 2025
807e52f
style(resp): fix code formatting and linting issues
Dayuxiaoshui Oct 12, 2025
65962bf
test(resp): improve test assertions and error messages
Dayuxiaoshui Oct 12, 2025
7435bfc
fix(resp): prevent integer overflow in double casting
Dayuxiaoshui Oct 12, 2025
6dc13eb
feat(resp): complete RESP3 implementation with full RESP type support
Dayuxiaoshui Oct 12, 2025
b890744
feat(resp): optimize encode_many performance with buffer pre-allocation
Dayuxiaoshui Oct 12, 2025
431f94b
fix(resp): replace write! macro with extend_from_slice in RESP3 encoder
Dayuxiaoshui Oct 12, 2025
ec0c26c
fix(resp): refactor RESP3 decoder to support all RESP types in Map/Se…
Dayuxiaoshui Oct 12, 2025
c68e6c5
fix(resp): fix clippy warnings in RESP3 decoder
Dayuxiaoshui Oct 12, 2025
4b40ed7
fix(resp): fix critical buffer corruption in RESP3 decoder
Dayuxiaoshui Oct 12, 2025
8a6c004
fix(resp): implement stateful parsing to prevent data loss in collect…
Dayuxiaoshui Oct 12, 2025
404ee40
fix(resp): remove unused import in incremental_parsing test
Dayuxiaoshui Oct 12, 2025
e2c8196
fix(resp): address CodeRabbit security and code quality issues
Dayuxiaoshui Oct 12, 2025
2f81a4f
fix(resp): implement stack-based nested collection parsing
Dayuxiaoshui Oct 12, 2025
9d54ad3
feat(resp): enhance DoS protection and fix CodeRabbit issues
Dayuxiaoshui Oct 12, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion src/resp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ workspace = true
[dependencies]
bytes.workspace = true
thiserror.workspace = true
nom.workspace = true
nom.workspace = true
memchr = "2"
73 changes: 73 additions & 0 deletions src/resp/src/compat.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Copyright (c) 2024-present, arana-db Community. All rights reserved.
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// Defines how Boolean values should be converted when encoding to older RESP versions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BooleanMode {
/// Convert Boolean to Integer: true → :1, false → :0
Integer,
/// Convert Boolean to Simple String: true → +OK, false → +ERR
SimpleString,
}

/// Defines how Double values should be converted when encoding to older RESP versions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DoubleMode {
/// Convert Double to Bulk String: 3.14 → $4\r\n3.14\r\n
BulkString,
/// Convert Double to Integer if whole number: 2.0 → :2, 2.5 → BulkString
IntegerIfWhole,
}

/// Defines how Map values should be converted when encoding to older RESP versions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MapMode {
/// Convert Map to flat Array: Map{k1:v1,k2:v2} → *4\r\nk1\r\nv1\r\nk2\r\nv2\r\n
FlatArray,
/// Convert Map to Array of pairs: Map{k1:v1,k2:v2} → *2\r\n*2\r\nk1\r\nv1\r\n*2\r\nk2\r\nv2\r\n
ArrayOfPairs,
}

/// Configuration for converting RESP3 types to older RESP versions.
///
/// This policy defines how RESP3-specific types (Boolean, Double, Map, etc.)
/// should be represented when encoding to RESP1 or RESP2 protocols.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DownlevelPolicy {
/// How to convert Boolean values
pub boolean_mode: BooleanMode,
/// How to convert Double values
pub double_mode: DoubleMode,
/// How to convert Map values
pub map_mode: MapMode,
}

impl Default for DownlevelPolicy {
/// Creates a default downlevel policy with conservative conversion settings.
///
/// Default settings:
/// - Boolean → Integer (true → :1, false → :0)
/// - Double → BulkString (3.14 → $4\r\n3.14\r\n)
/// - Map → FlatArray (Map{k:v} → *2\r\nk\r\nv\r\n)
fn default() -> Self {
Self {
boolean_mode: BooleanMode::Integer,
double_mode: DoubleMode::BulkString,
map_mode: MapMode::FlatArray,
}
}
}
6 changes: 6 additions & 0 deletions src/resp/src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,12 @@ impl RespEncode for RespEncoder {
}
self.append_crlf()
}
// RESP3-only variants (Null, Boolean, Double, BulkError, VerbatimString,
// BigNumber, Map, Set, Push) are not encoded in the legacy RESP2 encoder
// and are silently skipped. These should be handled by version-specific
// encoders (Resp1Encoder, Resp2Encoder, Resp3Encoder) with appropriate
// downlevel conversion policies.
_ => self,
}
}
}
103 changes: 103 additions & 0 deletions src/resp/src/factory.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// Copyright (c) 2024-present, arana-db Community. All rights reserved.
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Factory functions for creating RESP protocol encoders and decoders.
//!
//! This module provides convenient factory functions to create version-specific
//! encoder and decoder instances based on the desired RESP protocol version.

use crate::{
compat::DownlevelPolicy,
traits::{Decoder, Encoder},
types::RespVersion,
};

/// Create a new decoder for the specified RESP version.
///
/// # Arguments
/// * `version` - The RESP protocol version to create a decoder for
///
/// # Returns
/// A boxed decoder instance that implements the `Decoder` trait
///
/// # Examples
/// ```
/// use resp::{RespVersion, new_decoder};
///
/// let mut decoder = new_decoder(RespVersion::RESP3);
/// decoder.push("+OK\r\n".into());
/// ```
pub fn new_decoder(version: RespVersion) -> Box<dyn Decoder> {
match version {
RespVersion::RESP1 => Box::new(crate::resp1::decoder::Resp1Decoder::default()),
RespVersion::RESP2 => Box::new(crate::resp2::decoder::Resp2Decoder::default()),
RespVersion::RESP3 => Box::new(crate::resp3::decoder::Resp3Decoder::default()),
}
}

/// Create a new encoder for the specified RESP version.
///
/// # Arguments
/// * `version` - The RESP protocol version to create an encoder for
///
/// # Returns
/// A boxed encoder instance that implements the `Encoder` trait
///
/// # Examples
/// ```
/// use resp::{RespData, RespVersion, new_encoder};
///
/// let mut encoder = new_encoder(RespVersion::RESP3);
/// let bytes = encoder.encode_one(&RespData::Boolean(true)).unwrap();
/// assert_eq!(bytes.as_ref(), b"#t\r\n");
/// ```
pub fn new_encoder(version: RespVersion) -> Box<dyn Encoder> {
match version {
RespVersion::RESP1 => Box::new(crate::resp1::encoder::Resp1Encoder::default()),
RespVersion::RESP2 => Box::new(crate::resp2::encoder::Resp2Encoder::default()),
RespVersion::RESP3 => Box::new(crate::resp3::encoder::Resp3Encoder::default()),
}
}

/// Create a new encoder for the specified RESP version with custom downlevel policy.
///
/// # Arguments
/// * `version` - The RESP protocol version to create an encoder for
/// * `policy` - The downlevel compatibility policy for RESP3 types
///
/// # Returns
/// A boxed encoder instance that implements the `Encoder` trait
///
/// # Examples
/// ```
/// use resp::{BooleanMode, DownlevelPolicy, RespData, RespVersion, new_encoder_with_policy};
///
/// let policy = DownlevelPolicy {
/// boolean_mode: BooleanMode::SimpleString,
/// ..Default::default()
/// };
/// let mut encoder = new_encoder_with_policy(RespVersion::RESP2, policy);
/// let bytes = encoder.encode_one(&RespData::Boolean(true)).unwrap(); // "+OK\r\n"
/// assert_eq!(bytes.as_ref(), b"+OK\r\n");
/// ```
pub fn new_encoder_with_policy(version: RespVersion, policy: DownlevelPolicy) -> Box<dyn Encoder> {
match version {
RespVersion::RESP1 => Box::new(crate::resp1::encoder::Resp1Encoder::with_policy(policy)),
RespVersion::RESP2 => Box::new(crate::resp2::encoder::Resp2Encoder::with_policy(policy)),
RespVersion::RESP3 => Box::new(crate::resp3::encoder::Resp3Encoder::default()),
}
}
15 changes: 15 additions & 0 deletions src/resp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,30 @@
// limitations under the License.

pub mod command;
pub mod compat;
pub mod encode;
pub mod error;
pub mod parse;
pub mod types;

// Versioned modules
pub mod resp1;
pub mod resp2;
pub mod resp3;

// Unified traits and helpers
pub mod factory;
pub mod multi;
pub mod traits;

pub use command::{Command, CommandType, RespCommand};
pub use compat::{BooleanMode, DoubleMode, DownlevelPolicy, MapMode};
pub use encode::{CmdRes, RespEncode};
pub use error::{RespError, RespResult};
pub use factory::{new_decoder, new_encoder, new_encoder_with_policy};
pub use multi::{decode_many, encode_many};
pub use parse::{Parse, RespParse, RespParseResult};
pub use traits::{Decoder, Encoder};
pub use types::{RespData, RespType, RespVersion};

pub const CRLF: &str = "\r\n";
89 changes: 89 additions & 0 deletions src/resp/src/multi.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Copyright (c) 2024-present, arana-db Community. All rights reserved.
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Utilities for batch processing of RESP messages.
//!
//! This module provides functions for encoding and decoding multiple RESP messages
//! in a single operation, which is useful for pipelining and batch operations.

use bytes::{Bytes, BytesMut};

use crate::{
error::RespResult,
traits::{Decoder, Encoder},
types::RespData,
};

/// Decode multiple RESP messages from a single byte chunk.
///
/// This function pushes the entire chunk into the decoder and attempts to parse
/// all complete messages available. Useful for processing pipelined commands.
///
/// # Arguments
/// * `decoder` - The decoder instance to use for parsing
/// * `chunk` - The byte chunk containing one or more RESP messages
///
/// # Returns
/// A vector of parsing results. Each element is either `Ok(RespData)` for a
/// successfully parsed message, or `Err(RespError)` for parsing errors.
///
/// # Examples
/// ```
/// use resp::{RespVersion, decode_many, new_decoder};
///
/// let mut decoder = new_decoder(RespVersion::RESP2);
/// let results = decode_many(&mut *decoder, "+OK\r\n:42\r\n".into());
/// assert_eq!(results.len(), 2);
/// ```
pub fn decode_many(decoder: &mut dyn Decoder, chunk: Bytes) -> Vec<RespResult<RespData>> {
decoder.push(chunk);
let mut out = Vec::new();
while let Some(frame) = decoder.next() {
out.push(frame);
}
out
}

/// Encode multiple RESP messages into a single byte buffer.
///
/// This function encodes each `RespData` value in sequence and concatenates
/// the results into a single `Bytes` buffer. Useful for building pipelined commands.
///
/// # Arguments
/// * `encoder` - The encoder instance to use for encoding
/// * `values` - A slice of `RespData` values to encode
///
/// # Returns
/// A `Result` containing the concatenated encoded bytes, or an error if encoding fails.
///
/// # Examples
/// ```
/// use resp::{RespData, RespVersion, encode_many, new_encoder};
///
/// let mut encoder = new_encoder(RespVersion::RESP2);
/// let values = vec![RespData::SimpleString("OK".into()), RespData::Integer(42)];
/// let bytes = encode_many(&mut *encoder, &values).unwrap();
/// // bytes contains "+OK\r\n:42\r\n"
/// assert_eq!(bytes.as_ref(), b"+OK\r\n:42\r\n");
/// ```
pub fn encode_many(encoder: &mut dyn Encoder, values: &[RespData]) -> RespResult<Bytes> {
let mut buf = BytesMut::with_capacity(values.len() * 32); // Rough estimate
for v in values {
encoder.encode_into(v, &mut buf)?;
}
Ok(buf.freeze())
}
2 changes: 1 addition & 1 deletion src/resp/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use crate::{
types::{RespData, RespVersion},
};

#[derive(Debug, PartialEq, Eq)]
#[derive(Debug, PartialEq)]
pub enum RespParseResult {
Complete(RespData),
Incomplete,
Expand Down
Loading
Loading