Skip to content

Commit

Permalink
issue-25: Add Cacheable
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreyErmilov committed Sep 17, 2021
1 parent b8ef10e commit 32311b9
Show file tree
Hide file tree
Showing 12 changed files with 254 additions and 4 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
members = [
"hitbox",
"hitbox-actix",
"hitbox-axum",
"hitbox-backend",
"hitbox-derive",
"hitbox-redis",
Expand Down
6 changes: 5 additions & 1 deletion examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ default = []

[dev-dependencies]
hitbox = { path = "../hitbox", features = ["derive"] }
hitbox-actix = { path = "../hitbox-actix", features = ["redis"]}
hitbox-actix = { path = "../hitbox-actix", features = ["redis"] }
hitbox-axum = { path = "../hitbox-axum" }
actix = "0.12"
log = "0.4"
actix-rt = "2"
Expand All @@ -24,3 +25,6 @@ actix_derive = "0.6"
actix-web = "3"
tracing = "0.1"
tracing-subscriber = "0.2"
axum = "0.2.4"
tokio = { version = "1.0", features = ["full"] }
tower = { version = "0.4.8", features = ["full"] }
27 changes: 27 additions & 0 deletions examples/examples/axum.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use std::net::SocketAddr;

use axum::{
handler::{get, Handler},
Router,
};
use axum::response::Html;

use hitbox_axum::CacheLayer;

#[tokio::main]
async fn main() {
let app = Router::new().route(
"/:user_id/index.html",
get(handler.layer(CacheLayer::new())),
);

let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}

async fn handler() -> Html<&'static str> {
Html::from("<h1>Header</h1>")
}
11 changes: 11 additions & 0 deletions hitbox-axum/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

## [0.1.0] - 2021-09-12
### Added
- Initial release
23 changes: 23 additions & 0 deletions hitbox-axum/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[package]
name = "hitbox-axum"
version = "0.1.0"
authors = ["Belousow Makc <[email protected]>", "Andrey Ermilov <[email protected]>"]
license = "MIT"
edition = "2018"
description = "Asynchronous caching framework for Axum."
readme = "README.md"
repository = "https://github.com/hit-box/hitbox/"
categories = ["caching", "asynchronous"]
keywords = ["cache", "axum", "tokio", "async", "cache-backend", "hitbox"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
hitbox = { path = "../hitbox", version = "0.1.0" }
tower-layer = "0.3.1"
tower-service = "0.3.1"
serde = "1"
serde_json = "1"
axum = "0.2"
sha2 = "0.9"
futures = "0.3"
21 changes: 21 additions & 0 deletions hitbox-axum/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Makc

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
34 changes: 34 additions & 0 deletions hitbox-axum/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# hitbox-axum

*Work In Progress!*

Hitbox-Axum is an asynchronous caching framework for [Axum] framework.
It's designed for distributed and for single-machine applications.

## Features
- [x] Automatic cache key generation.
- [x] Multiple cache backend implementations.
- [x] Stale cache mechanics.
- [ ] Cache locks for [dogpile effect] preventions.
- [ ] Distributed cache locks.
- [ ] Detailed metrics out of the box.

## Backend implementations
- [x] [Redis](https://github.com/hit-box/hitbox/tree/master/hitbox-redis)
- [ ] In-memory backend

## Feature flags
* derive - Support for [Cacheable] trait derive macros.
* redis - Support for default redis backend.

## Restrictions
Default cache key implementation based on serde_qs crate
and have some [restrictions](https://docs.rs/serde_qs/latest/serde_qs/#supported-types).

[Cacheable]: https://docs.rs/hitbox/latest/hitbox/cache/trait.Cacheable.html
[CacheableResponse]: https://docs.rs/hitbox/latest/hitbox/response/trait.CacheableResponse.html
[Backend]: https://docs.rs/hitbox-backend/latest/hitbox_backend/trait.Backend.html
[RedisBackend]: https://docs.rs/hitbox-redis/latest/hitbox_redis/struct.RedisBackend.html
[dogpile effect]: https://www.sobstel.org/blog/preventing-dogpile-effect/

[Axum]: https://github.com/tokio-rs/axum
52 changes: 52 additions & 0 deletions hitbox-axum/src/cacheable.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use axum::http::Request;
use hitbox::cache::Cacheable;
use hitbox::CacheError;

pub struct Wrapper<T> {
pub request: Request<T>,
}

impl<T> Wrapper<T> {
pub fn into_inner(self) -> Request<T> {
self.request
}
}

impl<T> Cacheable for Wrapper<T> {
fn cache_key(&self) -> Result<String, CacheError> {
let path = self.request.uri().path();
let method = self.request.method();
let query = self.request.uri().query().unwrap_or_default();
Ok(format!("{}:{}:{}", path, method, query))
}

fn cache_key_prefix(&self) -> String {
todo!()
}

fn cache_ttl(&self) -> u32 {
todo!()
}

fn cache_stale_ttl(&self) -> u32 {
todo!()
}

fn cache_version(&self) -> u32 {
todo!()
}
}

#[cfg(test)]
mod tests {
use crate::Wrapper;
use axum::http::Request;
use hitbox::cache::Cacheable;

#[test]
fn test_cache_key() {
let request = Request::new(String::from("Hello world"));
let wrapper = Wrapper { request };
assert_eq!(wrapper.cache_key().unwrap(), String::from("/:GET:"))
}
}
25 changes: 25 additions & 0 deletions hitbox-axum/src/layer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use crate::service::CacheService;
use tower_layer::Layer;

#[derive(Debug, Clone)]
pub struct CacheLayer {}

impl CacheLayer {
pub fn new() -> Self {
CacheLayer {}
}
}

impl Default for CacheLayer {
fn default() -> Self {
CacheLayer::new()
}
}

impl<S> Layer<S> for CacheLayer {
type Service = CacheService<S>;

fn layer(&self, service: S) -> Self::Service {
CacheService::new(service)
}
}
6 changes: 6 additions & 0 deletions hitbox-axum/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
mod cacheable;
mod layer;
mod service;

pub use cacheable::Wrapper;
pub use layer::CacheLayer;
46 changes: 46 additions & 0 deletions hitbox-axum/src/service.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use std::task::{Context, Poll};

use axum::http::{Request, Response};
use futures::future::BoxFuture;
use tower_service::Service;

use crate::Wrapper;

#[derive(Clone)]
pub struct CacheService<S> {
service: S,
}

impl<S> CacheService<S> {
pub fn new(service: S) -> CacheService<S> {
CacheService { service }
}
}

impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for CacheService<S>
where
S: Service<Request<ReqBody>, Response=Response<ResBody>> + Clone + Send + 'static,
S::Future: Send + 'static,
ReqBody: Send + 'static,
ResBody: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx)
}

fn call(&mut self, request: Request<ReqBody>) -> Self::Future {
// self.service.call(wrapper.into_inner())
let clone = self.service.clone();
let mut service = std::mem::replace(&mut self.service, clone);

Box::pin(async move {
let wrapper = Wrapper { request };
let res: Response<ResBody> = service.call(wrapper.into_inner()).await?;
Ok(res)
})
}
}
6 changes: 3 additions & 3 deletions hitbox-derive/src/cacheable_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub fn impl_macro(ast: &syn::DeriveInput) -> TokenStream {
}
};

let cache_ttl_implement = match find_attribute(&ast, "cache_ttl") {
let cache_ttl_implement = match find_attribute(ast, "cache_ttl") {
Some(cache_ttl) => quote! {
fn cache_ttl(&self) -> u32 {
#cache_ttl
Expand All @@ -36,7 +36,7 @@ pub fn impl_macro(ast: &syn::DeriveInput) -> TokenStream {
None => proc_macro2::TokenStream::new(),
};

let cache_stale_ttl_implement = match find_attribute(&ast, "cache_stale_ttl") {
let cache_stale_ttl_implement = match find_attribute(ast, "cache_stale_ttl") {
Some(cache_stale_ttl) => quote! {
fn cache_stale_ttl(&self) -> u32 {
#cache_stale_ttl
Expand All @@ -45,7 +45,7 @@ pub fn impl_macro(ast: &syn::DeriveInput) -> TokenStream {
None => proc_macro2::TokenStream::new(),
};

let cache_version_implement = match find_attribute(&ast, "cache_version") {
let cache_version_implement = match find_attribute(ast, "cache_version") {
Some(cache_version) => quote! {
fn cache_version(&self) -> u32 {
#cache_version
Expand Down

0 comments on commit 32311b9

Please sign in to comment.