1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
//! Abstraction of SET command.
//!
//! For general information about this command, see the [Redis documentation](<https://redis.io/commands/set/>).
//!
//! # Basic usage
//! ```
//!# use core::str::FromStr;
//!# use embedded_nal::SocketAddr;
//!# use std_embedded_nal::Stack;
//!# use std_embedded_time::StandardClock;
//!# use embedded_redis::commands::set::SetCommand;
//!# use embedded_redis::network::ConnectionHandler;
//!#
//! let mut stack = Stack::default();
//! let clock = StandardClock::default();
//!
//! let mut connection_handler = ConnectionHandler::resp2(SocketAddr::from_str("127.0.0.1:6379").unwrap());
//! let client = connection_handler.connect(&mut stack, Some(&clock)).unwrap();
//!
//! let command = SetCommand::new("key", "value");
//! let _ = client.send(command);
//! ```
//!
//! # Expiration (EX, PX, EXAT, PXAT)
//! Setting TTL can be achieved in the following way. Fore more details s. [ExpirationPolicy] enum.
//! ```
//!# use core::str::FromStr;
//!# use embedded_nal::SocketAddr;
//!# use std_embedded_nal::Stack;
//!# use std_embedded_time::StandardClock;
//!# use embedded_redis::commands::set::{SetCommand, ExpirationPolicy};
//!# use embedded_redis::network::ConnectionHandler;
//!#
//!# let mut stack = Stack::default();
//!# let clock = StandardClock::default();
//!#
//!# let mut connection_handler = ConnectionHandler::resp2(SocketAddr::from_str("127.0.0.1:6379").unwrap());
//!# let client = connection_handler.connect(&mut stack, Some(&clock)).unwrap();
//!#
//! // Expires in 120 seconds
//! let command = SetCommand::new("key", "value")
//! .expires(ExpirationPolicy::Seconds(120));
//!# let _ = client.send(command);
//! ```
//! # Exclusive condition (NX/XX)
//! Manage set condition. Fore more details s. [Exclusivity] enum.
//!
//! Using this options affects the return type. s. [ExclusiveSetResponse]
//! ```
//!# use core::str::FromStr;
//!# use embedded_nal::SocketAddr;
//!# use std_embedded_nal::Stack;
//!# use std_embedded_time::StandardClock;
//!# use embedded_redis::commands::set::{SetCommand, Exclusivity};
//!# use embedded_redis::network::ConnectionHandler;
//!#
//!# let mut stack = Stack::default();
//!# let clock = StandardClock::default();
//!#
//!# let mut connection_handler = ConnectionHandler::resp2(SocketAddr::from_str("127.0.0.1:6379").unwrap());
//!# let client = connection_handler.connect(&mut stack, Some(&clock)).unwrap();
//!#
//! // Just set the key if its not existing yet
//! let command = SetCommand::new("key", "value")
//! .set_exclusive(Exclusivity::SetIfMissing);
//!# let _ = client.send(command);
//! ```
//! # Return previous value (!GET)
//! Returns the previous value stored at the given key.
//!
//! Using this options affects the return type. s. [ReturnPreviousResponse]
//! ```
//!# use core::str::FromStr;
//!# use embedded_nal::SocketAddr;
//!# use std_embedded_nal::Stack;
//!# use std_embedded_time::StandardClock;
//!# use embedded_redis::commands::set::{SetCommand};
//!# use embedded_redis::network::ConnectionHandler;
//!#
//!# let mut stack = Stack::default();
//!# let clock = StandardClock::default();
//!#
//!# let mut connection_handler = ConnectionHandler::resp2(SocketAddr::from_str("127.0.0.1:6379").unwrap());
//!# let client = connection_handler.connect(&mut stack, Some(&clock)).unwrap();
//!#
//! // Just set the key if its not existing yet
//! let command = SetCommand::new("key", "value")
//! .return_previous();
//!# let _ = client.send(command);
//! ```
//! # Shorthand
//! [Client](Client#method.set) provides a shorthand method for this command.
//! ```
//!# use core::str::FromStr;
//!# use bytes::Bytes;
//!# use embedded_nal::SocketAddr;
//!# use std_embedded_nal::Stack;
//!# use std_embedded_time::StandardClock;
//!# use embedded_redis::commands::set::SetCommand;
//!# use embedded_redis::network::ConnectionHandler;
//!#
//!# let mut stack = Stack::default();
//!# let clock = StandardClock::default();
//!#
//!# let mut connection_handler = ConnectionHandler::resp2(SocketAddr::from_str("127.0.0.1:6379").unwrap());
//!# let client = connection_handler.connect(&mut stack, Some(&clock)).unwrap();
//!#
//!# let _ = client.send(SetCommand::new("test_key", "test_value")).unwrap().wait();
//!#
//! // Using &str arguments
//! let _ = client.set("key", "value");
//!
//! // Using String arguments
//! let _ = client.set("key".to_string(), "value".to_string());
//!
//! // Using Bytes arguments
//! let _ = client.set(Bytes::from_static(b"key"), Bytes::from_static(b"value"));
//! ```
use crate::commands::auth::AuthCommand;
use crate::commands::builder::{CommandBuilder, IsNullFrame, ToStringBytes, ToStringOption};
use crate::commands::hello::HelloCommand;
use crate::commands::{Command, ResponseTypeError};
use crate::network::client::{Client, CommandErrors};
use crate::network::future::Future;
use crate::network::protocol::Protocol;
use alloc::string::ToString;
use bytes::Bytes;
use core::marker::PhantomData;
use embedded_nal::TcpClientStack;
use embedded_time::Clock;
pub enum ExpirationPolicy {
/// Does not set and expiration option
Never,
/// EX option
Seconds(usize),
/// PX option
Milliseconds(usize),
/// EXAT option
TimestampSeconds(usize),
/// PXAT option
TimestampMilliseconds(usize),
/// KEEPTTL option
Keep,
}
pub enum Exclusivity {
None,
/// NX option
SetIfExists,
/// XX option
SetIfMissing,
}
pub struct SetCommand<R> {
key: Bytes,
value: Bytes,
expiration: ExpirationPolicy,
exclusivity: Exclusivity,
/// GET option
return_old_value: bool,
response_type: PhantomData<R>,
}
impl SetCommand<ConfirmationResponse> {
pub fn new<K, V>(key: K, value: V) -> Self
where
Bytes: From<K>,
Bytes: From<V>,
{
SetCommand {
key: key.into(),
value: value.into(),
expiration: ExpirationPolicy::Never,
exclusivity: Exclusivity::None,
return_old_value: false,
response_type: PhantomData,
}
}
/// Set expiration (TTL)
pub fn expires(mut self, policy: ExpirationPolicy) -> SetCommand<ConfirmationResponse> {
self.expiration = policy;
self
}
/// Only set key if Exclusivity condition is met
pub fn set_exclusive(self, option: Exclusivity) -> SetCommand<ExclusiveSetResponse> {
SetCommand {
key: self.key,
value: self.value,
expiration: self.expiration,
exclusivity: option,
return_old_value: self.return_old_value,
response_type: PhantomData,
}
}
}
impl<R> SetCommand<R> {
/// Returns the previous key by setting the GET option
pub fn return_previous(self) -> SetCommand<ReturnPreviousResponse> {
SetCommand {
key: self.key,
value: self.value,
expiration: self.expiration,
exclusivity: self.exclusivity,
return_old_value: true,
response_type: PhantomData,
}
}
}
/// Regular response if neither !GET or NX/XX option is set.
/// Indicates that SET operation was successful
pub type ConfirmationResponse = ();
/// Response if NX/XX option was set.
///
/// Some => SET was executed successfully.
/// None => Operation was not performed, as NX/XX condition was not met.
pub type ExclusiveSetResponse = Option<()>;
/// Response if !GET option is used.
///
/// Some => The old string value stored at key.
/// None => The key did not exist.
pub type ReturnPreviousResponse = Option<Bytes>;
impl<F> Command<F> for SetCommand<ConfirmationResponse>
where
F: From<CommandBuilder> + ToStringOption,
{
type Response = ConfirmationResponse;
fn encode(&self) -> F {
self.get_builder().into()
}
fn eval_response(&self, frame: F) -> Result<Self::Response, ResponseTypeError> {
if frame.to_string_option().ok_or(ResponseTypeError {})? != "OK" {
return Err(ResponseTypeError {});
}
Ok(())
}
}
impl<F> Command<F> for SetCommand<ExclusiveSetResponse>
where
F: From<CommandBuilder> + ToStringOption + IsNullFrame,
{
type Response = ExclusiveSetResponse;
fn encode(&self) -> F {
self.get_builder().into()
}
fn eval_response(&self, frame: F) -> Result<Self::Response, ResponseTypeError> {
if frame.is_null_frame() {
return Ok(None);
}
if frame.to_string_option().ok_or(ResponseTypeError {})? == "OK" {
return Ok(Some(()));
}
Err(ResponseTypeError {})
}
}
impl<F> Command<F> for SetCommand<ReturnPreviousResponse>
where
F: From<CommandBuilder> + IsNullFrame + ToStringBytes,
{
type Response = ReturnPreviousResponse;
fn encode(&self) -> F {
self.get_builder().into()
}
fn eval_response(&self, frame: F) -> Result<Self::Response, ResponseTypeError> {
if frame.is_null_frame() {
return Ok(None);
}
Ok(Some(frame.to_string_bytes().ok_or(ResponseTypeError {})?))
}
}
impl<R> SetCommand<R> {
/// General logic for building the command
fn get_builder(&self) -> CommandBuilder {
CommandBuilder::new("SET")
.arg(&self.key)
.arg(&self.value)
.arg_static_option(self.expiration_unit())
.arg_option(self.expiration_time().as_ref())
.arg_static_option(self.exclusive_option())
.arg_static_option(self.get_option())
}
/// Returns the expiration time unit argument
fn expiration_unit(&self) -> Option<&'static str> {
match self.expiration {
ExpirationPolicy::Never => None,
ExpirationPolicy::Seconds(_) => Some("EX"),
ExpirationPolicy::Milliseconds(_) => Some("PX"),
ExpirationPolicy::TimestampSeconds(_) => Some("EXAT"),
ExpirationPolicy::TimestampMilliseconds(_) => Some("PXAT"),
ExpirationPolicy::Keep => Some("KEEPTTL"),
}
}
/// Returns the expiration time
fn expiration_time(&self) -> Option<Bytes> {
match self.expiration {
ExpirationPolicy::Never => None,
ExpirationPolicy::Seconds(seconds)
| ExpirationPolicy::Milliseconds(seconds)
| ExpirationPolicy::TimestampSeconds(seconds)
| ExpirationPolicy::TimestampMilliseconds(seconds) => Some(seconds.to_string().into()),
ExpirationPolicy::Keep => None,
}
}
/// Returns the exclusivity argument
fn exclusive_option(&self) -> Option<&'static str> {
match self.exclusivity {
Exclusivity::None => None,
Exclusivity::SetIfExists => Some("XX"),
Exclusivity::SetIfMissing => Some("NX"),
}
}
fn get_option(&self) -> Option<&'static str> {
if self.return_old_value {
return Some("GET");
}
None
}
}
impl<'a, N: TcpClientStack, C: Clock, P: Protocol> Client<'a, N, C, P>
where
AuthCommand: Command<<P as Protocol>::FrameType>,
HelloCommand: Command<<P as Protocol>::FrameType>,
{
/// Shorthand for [SetCommand]
/// For using options of SET command, use [SetCommand] directly instead
pub fn set<K, V>(
&'a self,
key: K,
value: V,
) -> Result<Future<'a, N, C, P, SetCommand<ConfirmationResponse>>, CommandErrors>
where
<P as Protocol>::FrameType: ToStringBytes,
<P as Protocol>::FrameType: ToStringOption,
<P as Protocol>::FrameType: IsNullFrame,
<P as Protocol>::FrameType: From<CommandBuilder>,
Bytes: From<K>,
Bytes: From<V>,
{
self.send(SetCommand::new(key, value))
}
}