1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-30 18:34:36 +01:00

chore: remove actix-redis crate (#408)

This commit is contained in:
Rob Ede 2024-03-12 23:30:06 +00:00 committed by GitHub
parent e6f99e915d
commit f250348e57
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
21 changed files with 54 additions and 527 deletions

View File

@ -92,7 +92,7 @@ jobs:
- name: tests - name: tests
timeout-minutes: 40 timeout-minutes: 40
run: cargo ci-test --exclude=actix-redis --exclude=actix-session --exclude=actix-limitation -- --nocapture run: cargo ci-test --exclude=actix-session --exclude=actix-limitation -- --nocapture
- name: CI cache clean - name: CI cache clean
run: cargo-ci-cache-clean run: cargo-ci-cache-clean

View File

@ -118,7 +118,7 @@ jobs:
- name: tests - name: tests
timeout-minutes: 40 timeout-minutes: 40
run: cargo ci-test --exclude=actix-redis --exclude=actix-session --exclude=actix-limitation run: cargo ci-test --exclude=actix-session --exclude=actix-limitation
- name: CI cache clean - name: CI cache clean
run: cargo-ci-cache-clean run: cargo-ci-cache-clean

View File

@ -5,7 +5,6 @@ members = [
"actix-identity", "actix-identity",
"actix-limitation", "actix-limitation",
"actix-protobuf", "actix-protobuf",
"actix-redis",
"actix-session", "actix-session",
"actix-settings", "actix-settings",
"actix-web-httpauth", "actix-web-httpauth",
@ -23,7 +22,6 @@ actix-cors = { path = "./actix-cors" }
actix-identity = { path = "./actix-identity" } actix-identity = { path = "./actix-identity" }
actix-limitation = { path = "./actix-limitation" } actix-limitation = { path = "./actix-limitation" }
actix-protobuf = { path = "./actix-protobuf" } actix-protobuf = { path = "./actix-protobuf" }
actix-redis = { path = "./actix-redis" }
actix-session = { path = "./actix-session" } actix-session = { path = "./actix-session" }
actix-settings = { path = "./actix-settings" } actix-settings = { path = "./actix-settings" }
actix-web-httpauth = { path = "./actix-web-httpauth" } actix-web-httpauth = { path = "./actix-web-httpauth" }

View File

@ -19,7 +19,6 @@
| [actix-identity] | [![crates.io](https://img.shields.io/crates/v/actix-identity?label=latest)](https://crates.io/crates/actix-identity) [![dependency status](https://deps.rs/crate/actix-identity/latest/status.svg)](https://deps.rs/crate/actix-identity) | Identity management. | | [actix-identity] | [![crates.io](https://img.shields.io/crates/v/actix-identity?label=latest)](https://crates.io/crates/actix-identity) [![dependency status](https://deps.rs/crate/actix-identity/latest/status.svg)](https://deps.rs/crate/actix-identity) | Identity management. |
| [actix-limitation] | [![crates.io](https://img.shields.io/crates/v/actix-limitation?label=latest)](https://crates.io/crates/actix-limitation) [![dependency status](https://deps.rs/crate/actix-limitation/latest/status.svg)](https://deps.rs/crate/actix-limitation) | Rate-limiting using a fixed window counter for arbitrary keys, backed by Redis. | | [actix-limitation] | [![crates.io](https://img.shields.io/crates/v/actix-limitation?label=latest)](https://crates.io/crates/actix-limitation) [![dependency status](https://deps.rs/crate/actix-limitation/latest/status.svg)](https://deps.rs/crate/actix-limitation) | Rate-limiting using a fixed window counter for arbitrary keys, backed by Redis. |
| [actix-protobuf] | [![crates.io](https://img.shields.io/crates/v/actix-protobuf?label=latest)](https://crates.io/crates/actix-protobuf) [![dependency status](https://deps.rs/crate/actix-protobuf/latest/status.svg)](https://deps.rs/crate/actix-protobuf) | Protobuf payload extractor. | | [actix-protobuf] | [![crates.io](https://img.shields.io/crates/v/actix-protobuf?label=latest)](https://crates.io/crates/actix-protobuf) [![dependency status](https://deps.rs/crate/actix-protobuf/latest/status.svg)](https://deps.rs/crate/actix-protobuf) | Protobuf payload extractor. |
| [actix-redis] | [![crates.io](https://img.shields.io/crates/v/actix-redis?label=latest)](https://crates.io/crates/actix-redis) [![dependency status](https://deps.rs/crate/actix-redis/latest/status.svg)](https://deps.rs/crate/actix-redis) | Actor-based Redis client. |
| [actix-session] | [![crates.io](https://img.shields.io/crates/v/actix-session?label=latest)](https://crates.io/crates/actix-session) [![dependency status](https://deps.rs/crate/actix-session/latest/status.svg)](https://deps.rs/crate/actix-session) | Session management. | | [actix-session] | [![crates.io](https://img.shields.io/crates/v/actix-session?label=latest)](https://crates.io/crates/actix-session) [![dependency status](https://deps.rs/crate/actix-session/latest/status.svg)](https://deps.rs/crate/actix-session) | Session management. |
| [actix-settings] | [![crates.io](https://img.shields.io/crates/v/actix-settings?label=latest)](https://crates.io/crates/actix-settings) [![dependency status](https://deps.rs/crate/actix-settings/latest/status.svg)](https://deps.rs/crate/actix-settings) | Easily manage Actix Web's settings from a TOML file and environment variables. | | [actix-settings] | [![crates.io](https://img.shields.io/crates/v/actix-settings?label=latest)](https://crates.io/crates/actix-settings) [![dependency status](https://deps.rs/crate/actix-settings/latest/status.svg)](https://deps.rs/crate/actix-settings) | Easily manage Actix Web's settings from a TOML file and environment variables. |
| [actix-web-httpauth] | [![crates.io](https://img.shields.io/crates/v/actix-web-httpauth?label=latest)](https://crates.io/crates/actix-web-httpauth) [![dependency status](https://deps.rs/crate/actix-web-httpauth/latest/status.svg)](https://deps.rs/crate/actix-web-httpauth) | HTTP authentication schemes. | | [actix-web-httpauth] | [![crates.io](https://img.shields.io/crates/v/actix-web-httpauth?label=latest)](https://crates.io/crates/actix-web-httpauth) [![dependency status](https://deps.rs/crate/actix-web-httpauth/latest/status.svg)](https://deps.rs/crate/actix-web-httpauth) | HTTP authentication schemes. |
@ -62,7 +61,6 @@ To add a crate to this list, submit a pull request.
[actix-identity]: ./actix-identity [actix-identity]: ./actix-identity
[actix-limitation]: ./actix-limitation [actix-limitation]: ./actix-limitation
[actix-protobuf]: ./actix-protobuf [actix-protobuf]: ./actix-protobuf
[actix-redis]: ./actix-redis
[actix-session]: ./actix-session [actix-session]: ./actix-session
[actix-settings]: ./actix-settings [actix-settings]: ./actix-settings
[actix-web-httpauth]: ./actix-web-httpauth [actix-web-httpauth]: ./actix-web-httpauth

View File

@ -1,154 +0,0 @@
# Changes
## Unreleased
- Minimum supported Rust version (MSRV) is now 1.75.
## 0.13.0
- Update `redis-async` dependency to `0.16`.
- Minimum supported Rust version (MSRV) is now 1.68.
## 0.12.0
- Update `actix` dependency to `0.13`.
- Update `redis-async` dependency to `0.13`.
- Update `tokio-util` dependency to `0.7`.
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
## 0.11.0
### Removed
- `RedisSession` has been removed. Check out `RedisActorSessionStore` in `actix-session` for a session store backed by Redis using `actix-redis`. [#212]
### Changed
- Update `redis-async` dependency to `0.12`. [#212]
[#212]: https://github.com/actix/actix-extras/pull/212
## 0.10.0
- Update `actix-web` dependency to `4`.
## 0.10.0-beta.6
- Update `actix-web` dependency to `4.0.0-rc.1`.
## 0.10.0-beta.5
- Update `actix-web` dependency to `4.0.0.beta-18`. [#218]
- Minimum supported Rust version (MSRV) is now 1.54.
[#218]: https://github.com/actix/actix-extras/pull/218
## 0.10.0-beta.4
- A session will be created in Redis if and only if there is some data inside the session state. This reduces the performance impact of `RedisSession` on routes that do not leverage sessions. [#207]
- Update `actix-web` dependency to `4.0.0.beta-14`. [#209]
[#207]: https://github.com/actix/actix-extras/pull/207
[#209]: https://github.com/actix/actix-extras/pull/209
## 0.10.0-beta.3
- Update `actix-web` dependency to v4.0.0-beta.10. [#203]
- Minimum supported Rust version (MSRV) is now 1.52.
[#203]: https://github.com/actix/actix-extras/pull/203
## 0.10.0-beta.2
- No notable changes.
## 0.10.0-beta.1
- Update `actix-web` dependency to 4.0.0 beta.
- Minimum supported Rust version (MSRV) is now 1.46.0.
## 0.9.2
- Implement `std::error::Error` for `Error` [#135]
- Allow the removal of `Max-Age` for session-only cookies. [#161]
[#135]: https://github.com/actix/actix-extras/pull/135
[#161]: https://github.com/actix/actix-extras/pull/161
## 0.9.1
- Enforce minimum redis-async version of 0.6.3 to workaround breaking patch change.
## 0.9.0
- Update `actix-web` dependency to 3.0.0.
- Minimize `futures` dependency.
## 0.9.0-alpha.2
- Add `cookie_http_only` functionality to RedisSession builder, setting this to false allows JavaScript to access cookies. Defaults to true.
- Change type of parameter of ttl method to u32.
- Update `actix` to 0.10.0-alpha.3
- Update `tokio-util` to 0.3
- Minimum supported Rust version(MSRV) is now 1.40.0.
## 0.9.0-alpha.1
- Update `actix` to 0.10.0-alpha.2
- Update `actix-session` to 0.4.0-alpha.1
- Update `actix-web` to 3.0.0-alpha.1
- Update `time` to 0.2.9
## 0.8.1
- Move `env_logger` dependency to dev-dependencies and update to 0.7
- Update `actix_web` to 2.0.0 from 2.0.0-rc
- Move repository to actix-extras
## 0.8.0 - 2019-12-20
- Release
## 0.8.0-alpha.1 - 2019-12-16
- Migrate to actix 0.9
## 0.7.0 - 2019-09-25
- added cache_keygen functionality to RedisSession builder, enabling support for customizable cache key creation
## 0.6.1 - 2019-07-19
- remove ClonableService usage
- added comprehensive tests for session workflow
## 0.6.0 - 2019-07-08
- actix-web 1.0.0 compatibility
- Upgraded logic that evaluates session state, including new SessionStatus field, and introduced `session.renew()` and `session.purge()` functionality. Use `renew()` to cycle the session key at successful login. `renew()` keeps a session's state while replacing the old cookie and session key with new ones. Use `purge()` at logout to invalidate the session cookie and remove the session's redis cache entry.
## 0.5.1 - 2018-08-02
- Use cookie 0.11
## 0.5.0 - 2018-07-21
- Session cookie configuration
- Actix/Actix-web 0.7 compatibility
## 0.4.0 - 2018-05-08
- Actix web 0.6 compatibility
## 0.3.0 - 2018-04-10
- Actix web 0.5 compatibility
## 0.2.0 - 2018-02-28
- Use resolver actor from actix
- Use actix web 0.5
## 0.1.0 - 2018-01-23
- First release

View File

@ -1,48 +0,0 @@
[package]
name = "actix-redis"
version = "0.13.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actor-based Redis client"
keywords = ["actix", "redis", "async"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-extras.git"
categories = ["network-programming", "asynchronous"]
license.workspace = true
edition.workspace = true
rust-version.workspace = true
[package.metadata.docs.rs]
rustdoc-args = ["--cfg", "docsrs"]
all-features = true
[lib]
name = "actix_redis"
path = "src/lib.rs"
[features]
default = ["web"]
# actix-web integration
web = ["actix-web"]
[dependencies]
actix = { version = "0.13", default-features = false }
actix-rt = { version = "2.1", default-features = false }
actix-service = "2"
actix-tls = { version = "3", default-features = false, features = ["connect"] }
log = "0.4.6"
backoff = "0.4.0"
derive_more = "0.99.7"
futures-core = "0.3.17"
redis-async = "0.16"
time = "0.3"
tokio = { version = "1.18.4", features = ["sync"] }
tokio-util = "0.7"
actix-web = { version = "4", default-features = false, optional = true }
[dev-dependencies]
actix-test = "0.1.0-beta.12"
actix-web = { version = "4", default-features = false, features = ["macros"] }
env_logger = "0.11"
serde = { version = "1.0.101", features = ["derive"] }

View File

@ -1 +0,0 @@
../LICENSE-APACHE

View File

@ -1 +0,0 @@
../LICENSE-MIT

View File

@ -1,18 +0,0 @@
# actix-redis
> Actor-based Redis client.
<!-- prettier-ignore-start -->
[![crates.io](https://img.shields.io/crates/v/actix-redis?label=latest)](https://crates.io/crates/actix-redis)
[![Documentation](https://docs.rs/actix-redis/badge.svg?version=0.13.0)](https://docs.rs/actix-redis/0.13.0)
![Apache 2.0 or MIT licensed](https://img.shields.io/crates/l/actix-redis)
[![Dependency Status](https://deps.rs/crate/actix-redis/0.13.0/status.svg)](https://deps.rs/crate/actix-redis/0.13.0)
<!-- prettier-ignore-end -->
## Documentation & Resources
- [API Documentation](https://docs.rs/actix-redis)
- [Example Project](https://github.com/actix/examples/tree/master/auth/redis-session)
- Minimum Supported Rust Version (MSRV): 1.57

View File

@ -1,32 +0,0 @@
//! Redis integration for `actix`.
#![forbid(unsafe_code)]
#![deny(rust_2018_idioms, nonstandard_style)]
#![warn(future_incompatible)]
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
use derive_more::{Display, Error, From};
pub use redis_async::{error::Error as RespError, resp::RespValue, resp_array};
mod redis;
pub use self::redis::{Command, RedisActor};
/// General purpose `actix-redis` error.
#[derive(Debug, Display, Error, From)]
pub enum Error {
#[display(fmt = "Redis error: {_0}")]
Redis(redis_async::error::Error),
/// Receiving message during reconnecting.
#[display(fmt = "Redis: Not connected")]
NotConnected,
/// Cancel all waiters when connection is dropped.
#[display(fmt = "Redis: Disconnected")]
Disconnected,
}
#[cfg(feature = "web")]
impl actix_web::ResponseError for Error {}

View File

@ -1,143 +0,0 @@
use std::{collections::VecDeque, io};
use actix::prelude::*;
use actix_rt::net::TcpStream;
use actix_service::boxed::{self, BoxService};
use actix_tls::connect::{ConnectError, ConnectInfo, Connection, ConnectorService};
use backoff::{backoff::Backoff, ExponentialBackoff};
use log::{error, info, warn};
use redis_async::{
error::Error as RespError,
resp::{RespCodec, RespValue},
};
use tokio::{
io::{split, WriteHalf},
sync::oneshot,
};
use tokio_util::codec::FramedRead;
use crate::Error;
/// Command for sending data to Redis.
#[derive(Debug)]
pub struct Command(pub RespValue);
impl Message for Command {
type Result = Result<RespValue, Error>;
}
/// Redis communication actor.
pub struct RedisActor {
addr: String,
connector: BoxService<ConnectInfo<String>, Connection<String, TcpStream>, ConnectError>,
backoff: ExponentialBackoff,
cell: Option<actix::io::FramedWrite<RespValue, WriteHalf<TcpStream>, RespCodec>>,
queue: VecDeque<oneshot::Sender<Result<RespValue, Error>>>,
}
impl RedisActor {
/// Start new `Supervisor` with `RedisActor`.
pub fn start<S: Into<String>>(addr: S) -> Addr<RedisActor> {
let addr = addr.into();
let backoff = ExponentialBackoff {
max_elapsed_time: None,
..Default::default()
};
Supervisor::start(|_| RedisActor {
addr,
connector: boxed::service(ConnectorService::default()),
cell: None,
backoff,
queue: VecDeque::new(),
})
}
}
impl Actor for RedisActor {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Context<Self>) {
let req = ConnectInfo::new(self.addr.to_owned());
self.connector
.call(req)
.into_actor(self)
.map(|res, act, ctx| match res {
Ok(conn) => {
let stream = conn.into_parts().0;
info!("Connected to redis server: {}", act.addr);
let (r, w) = split(stream);
// configure write side of the connection
let framed = actix::io::FramedWrite::new(w, RespCodec, ctx);
act.cell = Some(framed);
// read side of the connection
ctx.add_stream(FramedRead::new(r, RespCodec));
act.backoff.reset();
}
Err(err) => {
error!("Can not connect to redis server: {}", err);
// re-connect with backoff time.
// we stop current context, supervisor will restart it.
if let Some(timeout) = act.backoff.next_backoff() {
ctx.run_later(timeout, |_, ctx| ctx.stop());
}
}
})
.wait(ctx);
}
}
impl Supervised for RedisActor {
fn restarting(&mut self, _: &mut Self::Context) {
self.cell.take();
for tx in self.queue.drain(..) {
let _ = tx.send(Err(Error::Disconnected));
}
}
}
impl actix::io::WriteHandler<io::Error> for RedisActor {
fn error(&mut self, err: io::Error, _: &mut Self::Context) -> Running {
warn!("Redis connection dropped: {} error: {}", self.addr, err);
Running::Stop
}
}
impl StreamHandler<Result<RespValue, RespError>> for RedisActor {
fn handle(&mut self, msg: Result<RespValue, RespError>, ctx: &mut Self::Context) {
match msg {
Err(e) => {
if let Some(tx) = self.queue.pop_front() {
let _ = tx.send(Err(e.into()));
}
ctx.stop();
}
Ok(val) => {
if let Some(tx) = self.queue.pop_front() {
let _ = tx.send(Ok(val));
}
}
}
}
}
impl Handler<Command> for RedisActor {
type Result = ResponseFuture<Result<RespValue, Error>>;
fn handle(&mut self, msg: Command, _: &mut Self::Context) -> Self::Result {
let (tx, rx) = oneshot::channel();
if let Some(ref mut cell) = self.cell {
self.queue.push_back(tx);
cell.write(msg.0);
} else {
let _ = tx.send(Err(Error::NotConnected));
}
Box::pin(async move { rx.await.map_err(|_| Error::Disconnected)? })
}
}

View File

@ -1,42 +0,0 @@
#[macro_use]
extern crate redis_async;
use actix_redis::{Command, Error, RedisActor, RespValue};
#[actix_web::test]
async fn test_error_connect() {
let addr = RedisActor::start("localhost:54000");
let _addr2 = addr.clone();
let res = addr.send(Command(resp_array!["GET", "test"])).await;
match res {
Ok(Err(Error::NotConnected)) => (),
_ => panic!("Should not happen {:?}", res),
}
}
#[actix_web::test]
async fn test_redis() {
env_logger::init();
let addr = RedisActor::start("127.0.0.1:6379");
let res = addr
.send(Command(resp_array!["SET", "test", "value"]))
.await;
match res {
Ok(Ok(resp)) => {
assert_eq!(resp, RespValue::SimpleString("OK".to_owned()));
let res = addr.send(Command(resp_array!["GET", "test"])).await;
match res {
Ok(Ok(resp)) => {
println!("RESP: {resp:?}");
assert_eq!(resp, RespValue::BulkString((&b"value"[..]).into()));
}
_ => panic!("Should not happen {:?}", res),
}
}
_ => panic!("Should not happen {:?}", res),
}
}

View File

@ -2,6 +2,8 @@
## Unreleased ## Unreleased
- Remove `redis-actor-session` crate feature (and, therefore, the `actix-redis` based storage backend).
## 0.9.0 ## 0.9.0
- Remove use of `async-trait` on `SessionStore` trait. - Remove use of `async-trait` on `SessionStore` trait.

View File

@ -20,7 +20,6 @@ all-features = true
[features] [features]
default = [] default = []
cookie-session = [] cookie-session = []
redis-actor-session = ["actix-redis", "actix", "futures-core", "rand"]
redis-rs-session = ["redis", "rand"] redis-rs-session = ["redis", "rand"]
redis-rs-tls-session = ["redis-rs-session", "redis/tokio-native-tls-comp"] redis-rs-tls-session = ["redis-rs-session", "redis/tokio-native-tls-comp"]
@ -36,16 +35,11 @@ serde = { version = "1" }
serde_json = { version = "1" } serde_json = { version = "1" }
tracing = { version = "0.1.30", default-features = false, features = ["log"] } tracing = { version = "0.1.30", default-features = false, features = ["log"] }
# redis-actor-session
actix = { version = "0.13", default-features = false, optional = true }
actix-redis = { version = "0.12", optional = true }
futures-core = { version = "0.3.17", optional = true }
# redis-rs-session # redis-rs-session
redis = { version = "0.24", default-features = false, features = ["tokio-comp", "connection-manager"], optional = true } redis = { version = "0.24", default-features = false, features = ["tokio-comp", "connection-manager"], optional = true }
[dev-dependencies] [dev-dependencies]
actix-session = { path = ".", features = ["cookie-session", "redis-actor-session", "redis-rs-session"] } actix-session = { path = ".", features = ["cookie-session", "redis-rs-session"] }
actix-test = "0.1.0-beta.10" actix-test = "0.1.0-beta.10"
actix-web = { version = "4", default-features = false, features = ["cookies", "secure-cookies", "macros"] } actix-web = { version = "4", default-features = false, features = ["cookies", "secure-cookies", "macros"] }
env_logger = "0.11" env_logger = "0.11"
@ -53,8 +47,8 @@ log = "0.4"
[[example]] [[example]]
name = "basic" name = "basic"
required-features = ["redis-actor-session"] required-features = ["redis-rs-session"]
[[example]] [[example]]
name = "authentication" name = "authentication"
required-features = ["redis-actor-session"] required-features = ["redis-rs-session"]

View File

@ -100,14 +100,6 @@ By default, `actix-session` does not provide any storage backend to retrieve and
actix-session = { version = "...", features = ["cookie-session"] } actix-session = { version = "...", features = ["cookie-session"] }
``` ```
- a Redis-based backend via [`actix-redis`](https://docs.rs/actix-redis), [`RedisActorSessionStore`], using the `redis-actor-session` feature flag.
```toml
[dependencies]
# ...
actix-session = { version = "...", features = ["redis-actor-session"] }
```
- a Redis-based backend via [`redis-rs`](https://docs.rs/redis-rs), [`RedisSessionStore`], using the `redis-rs-session` feature flag. - a Redis-based backend via [`redis-rs`](https://docs.rs/redis-rs), [`RedisSessionStore`], using the `redis-rs-session` feature flag.
```toml ```toml

View File

@ -1,4 +1,4 @@
use actix_session::{storage::RedisActorSessionStore, Session, SessionMiddleware}; use actix_session::{storage::RedisSessionStore, Session, SessionMiddleware};
use actix_web::{ use actix_web::{
cookie::{Key, SameSite}, cookie::{Key, SameSite},
error::InternalError, error::InternalError,
@ -76,6 +76,9 @@ async fn main() -> std::io::Result<()> {
// The signing key would usually be read from a configuration file/environment variables. // The signing key would usually be read from a configuration file/environment variables.
let signing_key = Key::generate(); let signing_key = Key::generate();
log::info!("setting up Redis session storage");
let storage = RedisSessionStore::new("127.0.0.1:6379").await.unwrap();
log::info!("starting HTTP server at http://localhost:8080"); log::info!("starting HTTP server at http://localhost:8080");
HttpServer::new(move || { HttpServer::new(move || {
@ -84,10 +87,7 @@ async fn main() -> std::io::Result<()> {
.wrap(middleware::Logger::default()) .wrap(middleware::Logger::default())
// cookie session middleware // cookie session middleware
.wrap( .wrap(
SessionMiddleware::builder( SessionMiddleware::builder(storage.clone(), signing_key.clone())
RedisActorSessionStore::new("127.0.0.1:6379"),
signing_key.clone(),
)
// allow the cookie to be accessed from javascript // allow the cookie to be accessed from javascript
.cookie_http_only(false) .cookie_http_only(false)
// allow the cookie only from the current domain // allow the cookie only from the current domain

View File

@ -1,4 +1,4 @@
use actix_session::{storage::RedisActorSessionStore, Session, SessionMiddleware}; use actix_session::{storage::RedisSessionStore, Session, SessionMiddleware};
use actix_web::{cookie::Key, middleware, web, App, Error, HttpRequest, HttpServer, Responder}; use actix_web::{cookie::Key, middleware, web, App, Error, HttpRequest, HttpServer, Responder};
/// simple handler /// simple handler
@ -23,6 +23,9 @@ async fn main() -> std::io::Result<()> {
// The signing key would usually be read from a configuration file/environment variables. // The signing key would usually be read from a configuration file/environment variables.
let signing_key = Key::generate(); let signing_key = Key::generate();
log::info!("setting up Redis session storage");
let storage = RedisSessionStore::new("127.0.0.1:6379").await.unwrap();
log::info!("starting HTTP server at http://localhost:8080"); log::info!("starting HTTP server at http://localhost:8080");
HttpServer::new(move || { HttpServer::new(move || {
@ -30,10 +33,7 @@ async fn main() -> std::io::Result<()> {
// enable logger // enable logger
.wrap(middleware::Logger::default()) .wrap(middleware::Logger::default())
// cookie session middleware // cookie session middleware
.wrap(SessionMiddleware::new( .wrap(SessionMiddleware::new(storage.clone(), signing_key.clone()))
RedisActorSessionStore::new("127.0.0.1:6379"),
signing_key.clone(),
))
// register simple route, handle all methods // register simple route, handle all methods
.service(web::resource("/").to(index)) .service(web::resource("/").to(index))
}) })

View File

@ -106,15 +106,6 @@ attached to your sessions. You can enable:
actix-session = { version = "...", features = ["cookie-session"] } actix-session = { version = "...", features = ["cookie-session"] }
``` ```
- a Redis-based backend via [`actix-redis`](https://docs.rs/actix-redis),
[`RedisActorSessionStore`], using the `redis-actor-session` feature flag.
```toml
[dependencies]
# ...
actix-session = { version = "...", features = ["redis-actor-session"] }
```
- a Redis-based backend via [`redis-rs`](https://docs.rs/redis-rs), [`RedisSessionStore`], using - a Redis-based backend via [`redis-rs`](https://docs.rs/redis-rs), [`RedisSessionStore`], using
the `redis-rs-session` feature flag. the `redis-rs-session` feature flag.

View File

@ -47,7 +47,7 @@ use crate::{
/// # Examples /// # Examples
/// ```no_run /// ```no_run
/// use actix_web::{web, App, HttpServer, HttpResponse, Error}; /// use actix_web::{web, App, HttpServer, HttpResponse, Error};
/// use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore}; /// use actix_session::{Session, SessionMiddleware, storage::RedisSessionStore};
/// use actix_web::cookie::Key; /// use actix_web::cookie::Key;
/// ///
/// // The secret key would usually be read from a configuration file/environment variables. /// // The secret key would usually be read from a configuration file/environment variables.
@ -59,17 +59,17 @@ use crate::{
/// #[actix_web::main] /// #[actix_web::main]
/// async fn main() -> std::io::Result<()> { /// async fn main() -> std::io::Result<()> {
/// let secret_key = get_secret_key(); /// let secret_key = get_secret_key();
/// let redis_connection_string = "127.0.0.1:6379"; /// let storage = RedisSessionStore::new("127.0.0.1:6379").await.unwrap();
/// HttpServer::new(move || ///
/// HttpServer::new(move || {
/// App::new() /// App::new()
/// // Add session management to your application using Redis for session state storage /// // Add session management to your application using Redis as storage
/// .wrap( /// .wrap(SessionMiddleware::new(
/// SessionMiddleware::new( /// storage.clone(),
/// RedisActorSessionStore::new(redis_connection_string), /// secret_key.clone(),
/// secret_key.clone() /// ))
/// ) /// .default_service(web::to(|| HttpResponse::Ok()))
/// ) /// })
/// .default_service(web::to(|| HttpResponse::Ok())))
/// .bind(("127.0.0.1", 8080))? /// .bind(("127.0.0.1", 8080))?
/// .run() /// .run()
/// .await /// .await
@ -80,7 +80,7 @@ use crate::{
/// ///
/// ```no_run /// ```no_run
/// use actix_web::{App, cookie::{Key, time}, Error, HttpResponse, HttpServer, web}; /// use actix_web::{App, cookie::{Key, time}, Error, HttpResponse, HttpServer, web};
/// use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore}; /// use actix_session::{Session, SessionMiddleware, storage::RedisSessionStore};
/// use actix_session::config::PersistentSession; /// use actix_session::config::PersistentSession;
/// ///
/// // The secret key would usually be read from a configuration file/environment variables. /// // The secret key would usually be read from a configuration file/environment variables.
@ -92,22 +92,20 @@ use crate::{
/// #[actix_web::main] /// #[actix_web::main]
/// async fn main() -> std::io::Result<()> { /// async fn main() -> std::io::Result<()> {
/// let secret_key = get_secret_key(); /// let secret_key = get_secret_key();
/// let redis_connection_string = "127.0.0.1:6379"; /// let storage = RedisSessionStore::new("127.0.0.1:6379").await.unwrap();
/// HttpServer::new(move || ///
/// HttpServer::new(move || {
/// App::new() /// App::new()
/// // Customise session length! /// // Customise session length!
/// .wrap( /// .wrap(
/// SessionMiddleware::builder( /// SessionMiddleware::builder(storage.clone(), secret_key.clone())
/// RedisActorSessionStore::new(redis_connection_string),
/// secret_key.clone()
/// )
/// .session_lifecycle( /// .session_lifecycle(
/// PersistentSession::default() /// PersistentSession::default().session_ttl(time::Duration::days(5)),
/// .session_ttl(time::Duration::days(5))
/// ) /// )
/// .build(), /// .build(),
/// ) /// )
/// .default_service(web::to(|| HttpResponse::Ok()))) /// .default_service(web::to(|| HttpResponse::Ok()))
/// })
/// .bind(("127.0.0.1", 8080))? /// .bind(("127.0.0.1", 8080))?
/// .run() /// .run()
/// .await /// .await

View File

@ -11,18 +11,13 @@ pub use self::{
#[cfg(feature = "cookie-session")] #[cfg(feature = "cookie-session")]
mod cookie; mod cookie;
#[cfg(feature = "redis-actor-session")]
mod redis_actor;
#[cfg(feature = "redis-rs-session")] #[cfg(feature = "redis-rs-session")]
mod redis_rs; mod redis_rs;
#[cfg(any(feature = "redis-actor-session", feature = "redis-rs-session"))] #[cfg(feature = "redis-rs-session")]
mod utils; mod utils;
#[cfg(feature = "cookie-session")] #[cfg(feature = "cookie-session")]
pub use cookie::CookieSessionStore; pub use cookie::CookieSessionStore;
#[cfg(feature = "redis-actor-session")]
pub use redis_actor::{RedisActorSessionStore, RedisActorSessionStoreBuilder};
#[cfg(feature = "redis-rs-session")] #[cfg(feature = "redis-rs-session")]
pub use redis_rs::{RedisSessionStore, RedisSessionStoreBuilder}; pub use redis_rs::{RedisSessionStore, RedisSessionStoreBuilder};

View File

@ -120,9 +120,7 @@ impl RedisSessionStoreBuilder {
self self
} }
/// Finalise the builder and return a [`RedisActorSessionStore`] instance. /// Finalise the builder and return a [`RedisSessionStore`] instance.
///
/// [`RedisActorSessionStore`]: crate::storage::RedisActorSessionStore
pub async fn build(self) -> Result<RedisSessionStore, anyhow::Error> { pub async fn build(self) -> Result<RedisSessionStore, anyhow::Error> {
let client = ConnectionManager::new(redis::Client::open(self.connection_string)?).await?; let client = ConnectionManager::new(redis::Client::open(self.connection_string)?).await?;
Ok(RedisSessionStore { Ok(RedisSessionStore {