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 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
use std::convert::AsRef; use std::sync::Arc; use std::time::Duration; use crate::dev::{Expiry, ExpiryStore, Store}; use crate::error::Result; #[cfg(feature = "with-serde")] use crate::format::{deserialize, serialize, Format}; /// Takes the underlying backend and provides common methods for it /// /// It can be stored in actix_web's Data and be used from handlers /// without specifying the backend itself and provides all the common methods from underlying /// store and expiry. /// The backend this struct holds should implement [`ExpiryStore`](dev/trait.ExpiryStore.html) /// either directly, or by depending on the default polyfill. /// Look [`StorageBuilder`](dev/struct.StorageBuilder.html) for more details. /// /// ## Example /// /// ```rust /// use actix_storage::Storage; /// use actix_web::*; /// /// async fn index(storage: web::Data<Storage>) -> Result<String, Error>{ /// storage.set_bytes("key", "value").await; /// let val = storage.get_bytes("key").await?.unwrap_or_default(); /// Ok(std::str::from_utf8(&val) /// .map_err(|err| error::ErrorInternalServerError("Storage error"))?.to_string()) /// } /// ``` /// /// It is also possible to set and get values directly using serde by enabling /// `with-serde` feature flag. /// #[derive(Clone)] pub struct Storage { store: Arc<dyn ExpiryStore>, #[cfg(feature = "with-serde")] format: Format, } impl Storage { /// Returns the storage builder struct pub fn build() -> StorageBuilder { StorageBuilder::default() } /// Stores a generic serializable value on storage using serde /// /// Calling set operations twice on the same key, overwrites it's value and /// clear the expiry on that key(if it exist). /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # /// # async fn index<'a>(storage: web::Data<Storage>) -> &'a str { /// storage.set("age", &60_u8).await; /// # "set" /// # } /// ``` /// /// ## Errors /// Beside the normal errors caused by the storage itself, it will result in error if /// serialization fails. /// /// Note: it required the value to be `Sized` as some of the serde extensions currently /// has the same requirement, this restriction may be lifted in future. /// /// requires `"with-serde"` feature and one of the format features to work ex. `"serde-json"` #[cfg(feature = "with-serde")] pub async fn set<V>(&self, key: impl AsRef<[u8]>, value: &V) -> Result<()> where V: serde::Serialize, { self.store .set(key.as_ref().into(), serialize(value, &self.format)?.into()) .await } /// Stores a generic serializable value on storage using serde and sets expiry on the key /// It should be prefered over explicity setting a value and putting an expiry on it as /// providers may provide a more optimized way to do both operations at once. /// /// Calling set operations twice on the same key, overwrites it's value and /// clear the expiry on that key(if it exist). /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # use std::time::Duration; /// # /// # async fn index<'a>(storage: web::Data<Storage>) -> &'a str { /// storage.set_expiring("age", &60_u8, Duration::from_secs(10)).await; /// # "set" /// # } /// ``` /// /// ## Errors /// Beside the normal errors caused by the storage itself, it will result in error if /// expiry provider is not set or serialization fails. /// /// Note: it required the value to be `Sized` as some of the serde extensions currently /// has the same requirement, this restriction may be lifted in future. /// /// requires `"with-serde"` feature and one of the format features to work ex. `"serde-json"` #[cfg(feature = "with-serde")] pub async fn set_expiring<V>( &self, key: impl AsRef<[u8]>, value: &V, expires_in: Duration, ) -> Result<()> where V: serde::Serialize, { self.store .set_expiring( key.as_ref().into(), serialize(value, &self.format)?.into(), expires_in, ) .await } /// Stores a sequence of bytes on storage /// /// Calling set operations twice on the same key, overwrites it's value and /// clear the expiry on that key(if it exist). /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # /// # async fn index<'a>(storage: web::Data<Storage>) -> &'a str { /// storage.set_bytes("age", vec![10]).await; /// storage.set_bytes("name", "Violet".as_bytes()).await; /// # "set" /// # } /// ``` pub async fn set_bytes(&self, key: impl AsRef<[u8]>, value: impl AsRef<[u8]>) -> Result<()> { self.store .set(key.as_ref().into(), value.as_ref().into()) .await } /// Stores a sequence of bytes on storage and sets expiry on the key /// It should be prefered over calling set and expire as providers may define /// a more optimized way to do both operations at once. /// /// Calling set operations twice on the same key, overwrites it's value and /// clear the expiry on that key(if it exist). /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # use std::time::Duration; /// # /// # async fn index<'a>(storage: web::Data<Storage>) -> &'a str { /// storage.set_expiring_bytes("name", "Violet".as_bytes(), Duration::from_secs(10)).await; /// # "set" /// # } /// ``` /// /// ## Errors /// Beside the normal errors caused by the storage itself, it will result in error if /// expiry provider is not set. pub async fn set_expiring_bytes( &self, key: impl AsRef<[u8]>, value: impl AsRef<[u8]>, expires_in: Duration, ) -> Result<()> { self.store .set_expiring(key.as_ref().into(), value.as_ref().into(), expires_in) .await } /// Gets a generic deserializable value from backend using serde /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # /// # async fn index(storage: web::Data<Storage>) -> Result<String, Error> { /// let val: Option<String> = storage.get("key").await?; /// # Ok(val.unwrap()) /// # } /// ``` /// /// ## Errors /// Beside the normal errors caused by the storage itself, it will result in error if /// deserialization fails. /// /// requires `"with-serde"` feature and one of the format features to work ex. `"serde-json"` #[cfg(feature = "with-serde")] pub async fn get<K, V>(&self, key: K) -> Result<Option<V>> where K: AsRef<[u8]>, V: serde::de::DeserializeOwned, { let val = self.store.get(key.as_ref().into()).await?; val.map(|val| deserialize(val.as_ref(), &self.format)) .transpose() } /// Gets a generic deserializable value from backend using serde together with its expiry /// It should be prefered over calling get and expiry as providers may define /// a more optimized way to do the both operations at once. /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # /// # async fn index(storage: web::Data<Storage>) -> Result<String> { /// let val: Option<(String, _)> = storage.get_expiring("key").await?; /// # Ok(val.unwrap().0) /// # } /// ``` /// /// ## Errors /// Beside the normal errors caused by the storage itself, it will result in error if /// expiry provider is not set or deserialization fails. /// /// requires `"with-serde"` and one of the format features to work ex. `"serde-json"` #[cfg(feature = "with-serde")] pub async fn get_expiring<K, V>(&self, key: K) -> Result<Option<(V, Option<Duration>)>> where K: AsRef<[u8]>, V: serde::de::DeserializeOwned, { if let Some((val, expiry)) = self.store.get_expiring(key.as_ref().into()).await? { let val = deserialize(val.as_ref(), &self.format)?; Ok(Some((val, expiry))) } else { Ok(None) } } /// Gets a sequence of bytes from backend, resulting in an owned vector /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # /// # async fn index(storage: web::Data<Storage>) -> Result<String, Error> { /// let val = storage.get_bytes("key").await?; /// # Ok(std::str::from_utf8(&val.unwrap()).unwrap_or_default().to_owned()) /// # } /// ``` pub async fn get_bytes(&self, key: impl AsRef<[u8]>) -> Result<Option<Vec<u8>>> { Ok(self.store.get(key.as_ref().into()).await?.map(|val| { let mut new_value = vec![]; new_value.extend_from_slice(val.as_ref()); new_value })) } /// Same as `get_bytes` but it also gets expiry. /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # /// # async fn index(storage: web::Data<Storage>) -> Result<String, Error> { /// let val = storage.get_expiring_bytes("key").await?; /// # Ok(std::str::from_utf8(&val.unwrap().0).unwrap_or_default().to_owned()) /// # } /// ``` pub async fn get_expiring_bytes( &self, key: impl AsRef<[u8]>, ) -> Result<Option<(Vec<u8>, Option<Duration>)>> { if let Some((val, expiry)) = self.store.get_expiring(key.as_ref().into()).await? { Ok(Some((val.as_ref().into(), expiry))) } else { Ok(None) } } /// Gets a sequence of bytes from backend, resulting in an arc /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # /// # async fn index(storage: web::Data<Storage>) -> Result<String, Error> { /// let val = storage.get_bytes_ref("key").await?; /// # Ok(std::str::from_utf8(&val.unwrap()).unwrap_or_default().to_owned()) /// # } /// ``` pub async fn get_bytes_ref(&self, key: impl AsRef<[u8]>) -> Result<Option<Arc<[u8]>>> { self.store.get(key.as_ref().into()).await } /// Same as `get_bytes_ref` but it also gets expiry. /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # /// # async fn index(storage: web::Data<Storage>) -> Result<String, Error> { /// let val = storage.get_expiring_bytes_ref("key").await?; /// # Ok(std::str::from_utf8(&val.unwrap().0).unwrap_or_default().to_owned()) /// # } /// ``` pub async fn get_expiring_bytes_ref( &self, key: impl AsRef<[u8]>, ) -> Result<Option<(Arc<[u8]>, Option<Duration>)>> { if let Some((val, expiry)) = self.store.get_expiring(key.as_ref().into()).await? { Ok(Some((val, expiry))) } else { Ok(None) } } /// Deletes/Removes a key value pair from storage. /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # /// # async fn index(storage: web::Data<Storage>) -> Result<String, Error> { /// storage.delete("key").await?; /// # Ok("deleted".to_string()) /// # } /// ``` pub async fn delete(&self, key: impl AsRef<[u8]>) -> Result<()> { self.store.delete(key.as_ref().into()).await } /// Checks if storage contains a key. /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # /// # async fn index(storage: web::Data<Storage>) -> Result<String, Error> { /// let exist = storage.contains_key("key").await?; /// # Ok("deleted".to_string()) /// # } /// ``` pub async fn contains_key(&self, key: impl AsRef<[u8]>) -> Result<bool> { self.store.contains_key(key.as_ref().into()).await } /// Sets expiry on a key, it won't result in error if the key doesn't exist. /// /// Calling set methods twice or calling persist will result in expiry being erased /// from the key, calling expire itself twice will overwrite the expiry for key. /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # use std::time::Duration; /// # /// # async fn index(storage: web::Data<Storage>) -> Result<String, Error> { /// storage.expire("key", Duration::from_secs(10)).await?; /// # Ok("deleted".to_string()) /// # } /// ``` pub async fn expire(&self, key: impl AsRef<[u8]>, expire_in: Duration) -> Result<()> { self.store.expire(key.as_ref().into(), expire_in).await } /// Gets expiry for the provided key, it will give none if there is no expiry set. /// /// The result of this method is not guaranteed to be exact and may be inaccurate /// depending on sotrage implementation. /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # use std::time::Duration; /// # /// # async fn index(storage: web::Data<Storage>) -> Result<String, Error> { /// let exp = storage.expiry("key").await?; /// if let Some(exp) = exp{ /// println!("Key will expire in {} seconds", exp.as_secs()); /// } else { /// println!("Long live the key"); /// } /// # Ok("deleted".to_string()) /// # } /// ``` pub async fn expiry(&self, key: impl AsRef<[u8]>) -> Result<Option<Duration>> { self.store.expiry(key.as_ref().into()).await } /// Extends expiry for a key, it won't result in error if the key doesn't exist. /// /// If the provided key doesn't have an expiry set, it will set the expiry on that key. /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # use std::time::Duration; /// # /// # async fn index(storage: web::Data<Storage>) -> Result<String, Error> { /// storage.expire("key", Duration::from_secs(5)).await?; /// storage.extend("key", Duration::from_secs(5)).await?; // ket will expire in ~10 seconds /// # Ok("deleted".to_string()) /// # } /// ``` pub async fn extend(&self, key: impl AsRef<[u8]>, expire_in: Duration) -> Result<()> { self.store.extend(key.as_ref().into(), expire_in).await } /// Clears expiry from the provided key, making it persistant. /// /// Calling expire will overwrite persist. /// /// ## Example /// ```rust /// # use actix_storage::Storage; /// # use actix_web::*; /// # use std::time::Duration; /// # /// # async fn index(storage: web::Data<Storage>) -> Result<String, Error> { /// storage.persist("key").await?; /// # Ok("deleted".to_string()) /// # } /// ``` pub async fn persist(&self, key: impl AsRef<[u8]>) -> Result<()> { self.store.persist(key.as_ref().into()).await } } /// Builder struct for [`Storage`](../struct.Storage.html) /// /// A provider can either implement [`ExpiryStore`](trait.ExpiryStore.html) directly, /// or implement [`Store`](trait.Store.html) and rely on another provider to provide /// expiration capablities. The builder will polyfill a [`ExpiryStore`](trait.ExpiryStore.html) /// by combining an [`Expiry`](trait.Expiry.html) and a [`Store`](trait.Store.html) itself. /// /// If there is no [`Expiry`](trait.Expiry.html) set in either of the ways, it will result in runtime /// errors when calling methods which require that functionality. #[derive(Default)] pub struct StorageBuilder { store: Option<Arc<dyn Store>>, expiry: Option<Arc<dyn Expiry>>, expiry_store: Option<Arc<dyn ExpiryStore>>, #[cfg(feature = "with-serde")] format: Format, } impl StorageBuilder { #[must_use = "Builder must be used by calling finish"] /// This method can be used to set a [`Store`](trait.Store.html), the second call to this /// method will overwrite the store. pub fn store(mut self, store: impl Store + 'static) -> Self { self.store = Some(Arc::new(store)); self } #[must_use = "Builder must be used by calling finish"] /// This method can be used to set a [`Expiry`](trait.Expiry.html), the second call to this /// method will overwrite the expiry. /// /// The expiry should work on the same storage as the provided store. pub fn expiry(mut self, expiry: impl Expiry + 'static) -> Self { self.expiry = Some(Arc::new(expiry)); self } #[must_use = "Builder must be used by calling finish"] /// This method can be used to set an [`ExpiryStore`](trait.ExpiryStore.html) directly, /// Its error to call [`expiry`](#method.expiry) or [`store`](#method.store) after calling this method. pub fn expiry_store<T>(mut self, expiry_store: T) -> Self where T: 'static + Store + Expiry + ExpiryStore, { self.expiry_store = Some(Arc::new(expiry_store)); self } #[cfg(feature = "with-serde")] #[must_use = "Builder must be used by calling finish"] /// This method can be used to set the format storage will use for serialization/deserialization, /// we will use default format if it is not called which can be None if there is no serde feature /// enabled. pub fn format(mut self, format: Format) -> Self { self.format = format; self } /// This method should be used after configuring the storage. /// /// ## Panics /// If there is no store provided either by calling [`expiry_store`](#method.expiry_store) /// or [`store`](#method.store) it will panic. pub fn finish(self) -> Storage { let expiry_store = if let Some(expiry_store) = self.expiry_store { expiry_store } else if let Some(store) = self.store { Arc::new(self::private::ExpiryStoreGlue(store, self.expiry)) } else { // It is a configuration error, so we just panic. panic!("Storage builder needs at least a store"); }; Storage { store: expiry_store, #[cfg(feature = "with-serde")] format: self.format, } } } mod private { use std::sync::Arc; use std::time::Duration; use crate::{ error::{Result, StorageError}, provider::{Expiry, ExpiryStore, Store}, }; pub(crate) struct ExpiryStoreGlue(pub Arc<dyn Store>, pub Option<Arc<dyn Expiry>>); #[async_trait::async_trait] impl Expiry for ExpiryStoreGlue { async fn expire(&self, key: Arc<[u8]>, expire_in: Duration) -> Result<()> { if let Some(expiry) = self.1.clone() { expiry.expire(key, expire_in).await } else { Err(StorageError::MethodNotSupported) } } async fn expiry(&self, key: Arc<[u8]>) -> Result<Option<Duration>> { if let Some(ref expiry) = self.1 { expiry.expiry(key).await } else { Err(StorageError::MethodNotSupported) } } async fn extend(&self, key: Arc<[u8]>, expire_in: Duration) -> Result<()> { if let Some(ref expiry) = self.1 { expiry.extend(key, expire_in).await } else { Err(StorageError::MethodNotSupported) } } async fn persist(&self, key: Arc<[u8]>) -> Result<()> { if let Some(ref expiry) = self.1 { expiry.persist(key).await } else { Err(StorageError::MethodNotSupported) } } } #[async_trait::async_trait] impl Store for ExpiryStoreGlue { async fn set(&self, key: Arc<[u8]>, value: Arc<[u8]>) -> Result<()> { self.0.set(key.clone(), value).await?; if let Some(ref expiry) = self.1 { expiry.set_called(key).await; }; Ok(()) } async fn get(&self, key: Arc<[u8]>) -> Result<Option<Arc<[u8]>>> { self.0.get(key).await } async fn delete(&self, key: Arc<[u8]>) -> Result<()> { self.0.delete(key).await } async fn contains_key(&self, key: Arc<[u8]>) -> Result<bool> { self.0.contains_key(key).await } } #[async_trait::async_trait] impl ExpiryStore for ExpiryStoreGlue { async fn set_expiring( &self, key: Arc<[u8]>, value: Arc<[u8]>, expire_in: Duration, ) -> Result<()> { if let Some(expiry) = self.1.clone() { self.0.set(key.clone(), value).await?; expiry.expire(key, expire_in).await } else { Err(StorageError::MethodNotSupported) } } async fn get_expiring( &self, key: Arc<[u8]>, ) -> Result<Option<(Arc<[u8]>, Option<Duration>)>> { if let Some(expiry) = self.1.clone() { let val = self.0.get(key.clone()).await?; if let Some(val) = val { let expiry = expiry.expiry(key).await?; Ok(Some((val, expiry))) } else { Ok(None) } } else { Err(StorageError::MethodNotSupported) } } } } #[cfg(test)] mod test { use std::time::Duration; use super::*; #[actix_rt::test] async fn test_no_expiry() { struct OnlyStore; #[async_trait::async_trait] impl Store for OnlyStore { async fn set(&self, _: Arc<[u8]>, _: Arc<[u8]>) -> Result<()> { Ok(()) } async fn get(&self, _: Arc<[u8]>) -> Result<Option<Arc<[u8]>>> { Ok(None) } async fn contains_key(&self, _: Arc<[u8]>) -> Result<bool> { Ok(false) } async fn delete(&self, _: Arc<[u8]>) -> Result<()> { Ok(()) } } let storage = Storage::build().store(OnlyStore).finish(); let k = "key"; let v = "value".as_bytes(); let d = Duration::from_secs(1); // These checks should all result in error as we didn't set any expiry assert!(storage.expire(k, d).await.is_err()); assert!(storage.expiry(k).await.is_err()); assert!(storage.extend(k, d).await.is_err()); assert!(storage.persist(k).await.is_err()); assert!(storage.set_expiring_bytes(k, v, d).await.is_err()); assert!(storage.get_expiring_bytes(k).await.is_err()); // These tests should all succeed assert!(storage.set_bytes(k, v).await.is_ok()); assert!(storage.get_bytes(k).await.is_ok()); assert!(storage.delete(k).await.is_ok()); assert!(storage.contains_key(k).await.is_ok()); } #[actix_rt::test] async fn test_expiry_store_polyfill() { #[derive(Clone)] struct SampleStore; #[async_trait::async_trait] impl Store for SampleStore { async fn set(&self, _: Arc<[u8]>, _: Arc<[u8]>) -> Result<()> { Ok(()) } async fn get(&self, _: Arc<[u8]>) -> Result<Option<Arc<[u8]>>> { Ok(Some("v".as_bytes().into())) } async fn contains_key(&self, _: Arc<[u8]>) -> Result<bool> { Ok(false) } async fn delete(&self, _: Arc<[u8]>) -> Result<()> { Ok(()) } } #[async_trait::async_trait] impl Expiry for SampleStore { async fn expire(&self, _: Arc<[u8]>, _: Duration) -> Result<()> { Ok(()) } async fn expiry(&self, _: Arc<[u8]>) -> Result<Option<Duration>> { Ok(Some(Duration::from_secs(1))) } async fn extend(&self, _: Arc<[u8]>, _: Duration) -> Result<()> { Ok(()) } async fn persist(&self, _: Arc<[u8]>) -> Result<()> { Ok(()) } } let k = "key"; let v = "value".as_bytes(); let d = Duration::from_secs(1); let store = SampleStore; let storage = Storage::build().store(store.clone()).expiry(store).finish(); assert!(storage .set_expiring_bytes("key", "value", Duration::from_secs(1)) .await .is_ok()); // These tests should all succeed assert!(storage.expire(k, d).await.is_ok()); assert!(storage.expiry(k).await.is_ok()); assert!(storage.extend(k, d).await.is_ok()); assert!(storage.persist(k).await.is_ok()); assert!(storage.set_expiring_bytes(k, v, d).await.is_ok()); assert!(storage.get_expiring_bytes(k).await.is_ok()); assert!(storage.set_bytes(k, v).await.is_ok()); assert!(storage.get_bytes(k).await.is_ok()); assert!(storage.delete(k).await.is_ok()); assert!(storage.contains_key(k).await.is_ok()); // values should match let res = storage.get_expiring_bytes("key").await; assert!(res.is_ok()); assert!(res.unwrap() == Some(("v".as_bytes().into(), Some(Duration::from_secs(1))))); } #[test] #[should_panic(expected = "Storage builder needs at least a store")] fn test_no_sotre() { Storage::build().finish(); } }