use std::fmt;
use std::time::Duration;
pub const ENV_SESSION_BACKEND: &str = "GREENTIC_RUNNER_SESSION_BACKEND";
pub const ENV_STATE_BACKEND: &str = "GREENTIC_RUNNER_STATE_BACKEND";
pub const ENV_REDIS_URL: &str = "GREENTIC_RUNNER_REDIS_URL";
pub const ENV_SESSION_NAMESPACE: &str = "GREENTIC_RUNNER_SESSION_NAMESPACE";
pub const ENV_GREENTIC_ENV: &str = "GREENTIC_ENV";
pub const ENV_SESSION_WAIT_TTL_SECS: &str = "GREENTIC_RUNNER_SESSION_WAIT_TTL_SECS";
pub const DEFAULT_WAIT_TTL: Duration = Duration::from_secs(24 * 60 * 60);
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StorageConfigError {
MissingRedisUrl { store: &'static str },
MissingSessionNamespace,
UnknownBackend { store: &'static str, value: String },
}
impl fmt::Display for StorageConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingRedisUrl { store } => write!(
f,
"{store} backend 'redis' was requested but no Redis URL was supplied \
(set {ENV_REDIS_URL}); refusing rather than falling back to in-memory, \
which would silently lose every parked conversation"
),
Self::MissingSessionNamespace => write!(
f,
"session backend 'redis' was requested but no keyspace could be resolved: \
set {ENV_SESSION_NAMESPACE} explicitly, or {ENV_GREENTIC_ENV} to derive one. \
A session entry key carries no environment, so sharing the crate default \
keyspace lets two environments evict each other's parked flows"
),
Self::UnknownBackend { store, value } => write!(
f,
"unknown {store} backend '{value}' (expected 'memory' or 'redis')"
),
}
}
}
impl std::error::Error for StorageConfigError {}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum SessionBackend {
#[default]
InMemory,
Redis {
url: String,
namespace: String,
wait_ttl: Option<Duration>,
},
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum StateBackend {
#[default]
InMemory,
Redis {
url: String,
},
}
impl SessionBackend {
pub fn redis(
url: impl Into<String>,
namespace: impl Into<String>,
) -> Result<Self, StorageConfigError> {
Self::redis_with_ttl(url, namespace, Some(DEFAULT_WAIT_TTL))
}
pub fn redis_with_ttl(
url: impl Into<String>,
namespace: impl Into<String>,
wait_ttl: Option<Duration>,
) -> Result<Self, StorageConfigError> {
let url = url.into();
let namespace = namespace.into();
if url.trim().is_empty() {
return Err(StorageConfigError::MissingRedisUrl { store: "session" });
}
if namespace.trim().is_empty() {
return Err(StorageConfigError::MissingSessionNamespace);
}
let wait_ttl = wait_ttl.filter(|ttl| !ttl.is_zero());
Ok(Self::Redis {
url,
namespace,
wait_ttl,
})
}
pub fn namespace_for_env(env: &str) -> Result<String, StorageConfigError> {
let env = env.trim();
if env.is_empty() {
return Err(StorageConfigError::MissingSessionNamespace);
}
Ok(format!("greentic:session:{env}"))
}
pub fn is_durable(&self) -> bool {
matches!(self, Self::Redis { .. })
}
pub fn wait_ttl(&self) -> Option<Duration> {
match self {
Self::InMemory => None,
Self::Redis { wait_ttl, .. } => *wait_ttl,
}
}
pub fn describe(&self) -> String {
match self {
Self::InMemory => "in-memory".to_string(),
Self::Redis {
namespace,
wait_ttl,
..
} => {
let ttl = match wait_ttl {
Some(ttl) => format!("{}s", ttl.as_secs()),
None => "none".to_string(),
};
format!("redis (namespace '{namespace}', wait ttl {ttl})")
}
}
}
}
impl StateBackend {
pub fn redis(url: impl Into<String>) -> Result<Self, StorageConfigError> {
let url = url.into();
if url.trim().is_empty() {
return Err(StorageConfigError::MissingRedisUrl { store: "state" });
}
Ok(Self::Redis { url })
}
pub fn is_durable(&self) -> bool {
matches!(self, Self::Redis { .. })
}
pub fn describe(&self) -> &'static str {
match self {
Self::InMemory => "in-memory",
Self::Redis { .. } => "redis",
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct StorageConfig {
pub session: SessionBackend,
pub state: StateBackend,
}
impl StorageConfig {
pub fn in_memory() -> Self {
Self::default()
}
pub fn redis(
url: impl Into<String>,
namespace: impl Into<String>,
) -> Result<Self, StorageConfigError> {
Self::redis_with_ttl(url, namespace, Some(DEFAULT_WAIT_TTL))
}
pub fn redis_with_ttl(
url: impl Into<String>,
namespace: impl Into<String>,
wait_ttl: Option<Duration>,
) -> Result<Self, StorageConfigError> {
let url = url.into();
Ok(Self {
session: SessionBackend::redis_with_ttl(url.clone(), namespace, wait_ttl)?,
state: StateBackend::redis(url)?,
})
}
pub fn from_env() -> Result<Self, StorageConfigError> {
Self::from_vars(
std::env::var(ENV_SESSION_BACKEND).ok().as_deref(),
std::env::var(ENV_STATE_BACKEND).ok().as_deref(),
std::env::var(ENV_REDIS_URL).ok().as_deref(),
std::env::var(ENV_SESSION_NAMESPACE).ok().as_deref(),
std::env::var(ENV_GREENTIC_ENV).ok().as_deref(),
std::env::var(ENV_SESSION_WAIT_TTL_SECS).ok().as_deref(),
)
}
pub fn from_vars(
session_backend: Option<&str>,
state_backend: Option<&str>,
redis_url: Option<&str>,
session_namespace: Option<&str>,
greentic_env: Option<&str>,
wait_ttl_secs: Option<&str>,
) -> Result<Self, StorageConfigError> {
let url = redis_url.map(str::trim).filter(|value| !value.is_empty());
let wait_ttl = match named(wait_ttl_secs).and_then(|raw| raw.parse::<u64>().ok()) {
Some(0) => None,
Some(secs) => Some(Duration::from_secs(secs)),
None => Some(DEFAULT_WAIT_TTL),
};
let session = match named(session_backend) {
None | Some("memory") => SessionBackend::InMemory,
Some("redis") => {
let url = url.ok_or(StorageConfigError::MissingRedisUrl { store: "session" })?;
let namespace = match named(session_namespace) {
Some(explicit) => explicit.to_string(),
None => SessionBackend::namespace_for_env(
named(greentic_env).ok_or(StorageConfigError::MissingSessionNamespace)?,
)?,
};
SessionBackend::redis_with_ttl(url, namespace, wait_ttl)?
}
Some(other) => {
return Err(StorageConfigError::UnknownBackend {
store: "session",
value: other.to_string(),
});
}
};
let state = match named(state_backend) {
None | Some("memory") => StateBackend::InMemory,
Some("redis") => {
let url = url.ok_or(StorageConfigError::MissingRedisUrl { store: "state" })?;
StateBackend::redis(url)?
}
Some(other) => {
return Err(StorageConfigError::UnknownBackend {
store: "state",
value: other.to_string(),
});
}
};
Ok(Self { session, state })
}
pub fn is_durable(&self) -> bool {
self.session.is_durable() || self.state.is_durable()
}
}
fn named(value: Option<&str>) -> Option<&str> {
value.map(str::trim).filter(|value| !value.is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_default_is_both_stores_in_memory() {
let config = StorageConfig::default();
assert_eq!(config.session, SessionBackend::InMemory);
assert_eq!(config.state, StateBackend::InMemory);
assert!(!config.is_durable());
}
#[test]
fn an_unnamed_backend_stays_in_memory_even_when_a_url_is_present() {
let config =
StorageConfig::from_vars(None, None, Some("redis://x"), None, Some("prod"), None)
.expect("resolve");
assert_eq!(config, StorageConfig::in_memory());
}
#[test]
fn explicit_redis_without_a_url_is_refused_not_disabled() {
let err = StorageConfig::from_vars(Some("redis"), None, None, Some("ns"), None, None)
.expect_err("must refuse");
assert_eq!(
err,
StorageConfigError::MissingRedisUrl { store: "session" }
);
let err = StorageConfig::from_vars(None, Some("redis"), None, None, None, None)
.expect_err("must refuse");
assert_eq!(err, StorageConfigError::MissingRedisUrl { store: "state" });
}
#[test]
fn an_empty_url_reads_as_absent_rather_than_as_a_host_named_nothing() {
let err =
StorageConfig::from_vars(Some("redis"), None, Some(" "), Some("ns"), None, None)
.expect_err("must refuse");
assert_eq!(
err,
StorageConfigError::MissingRedisUrl { store: "session" }
);
}
#[test]
fn a_session_redis_backend_without_a_resolvable_namespace_is_refused() {
let err =
StorageConfig::from_vars(Some("redis"), None, Some("redis://x"), None, None, None)
.expect_err("must refuse");
assert_eq!(err, StorageConfigError::MissingSessionNamespace);
}
#[test]
fn the_namespace_falls_back_to_the_environment_name() {
let config = StorageConfig::from_vars(
Some("redis"),
None,
Some("redis://x"),
None,
Some("prod"),
None,
)
.expect("resolve");
assert_eq!(
config.session,
SessionBackend::Redis {
url: "redis://x".into(),
namespace: "greentic:session:prod".into(),
wait_ttl: Some(DEFAULT_WAIT_TTL),
}
);
}
#[test]
fn an_explicit_namespace_beats_the_derived_one() {
let config = StorageConfig::from_vars(
Some("redis"),
None,
Some("redis://x"),
Some("acme:sessions"),
Some("prod"),
None,
)
.expect("resolve");
assert_eq!(
config.session,
SessionBackend::Redis {
url: "redis://x".into(),
namespace: "acme:sessions".into(),
wait_ttl: Some(DEFAULT_WAIT_TTL),
}
);
}
#[test]
fn two_environments_derive_different_namespaces() {
let prod = SessionBackend::namespace_for_env("prod").expect("prod");
let staging = SessionBackend::namespace_for_env("staging").expect("staging");
assert_ne!(prod, staging);
}
#[test]
fn an_unknown_backend_name_is_refused_rather_than_guessed() {
let err = StorageConfig::from_vars(Some("cassandra"), None, None, None, None, None)
.expect_err("must refuse");
assert_eq!(
err,
StorageConfigError::UnknownBackend {
store: "session",
value: "cassandra".into(),
}
);
}
#[test]
fn a_description_never_carries_the_connection_url() {
let backend = SessionBackend::redis("redis://user:hunter2@redis:6379", "ns").expect("cfg");
let described = backend.describe();
assert!(
!described.contains("hunter2"),
"credential leaked: {described}"
);
assert!(!described.contains("redis://"), "url leaked: {described}");
assert!(described.contains("ns"));
let state = StateBackend::redis("redis://user:hunter2@redis:6379").expect("cfg");
assert!(!state.describe().contains("hunter2"));
}
#[test]
fn a_redis_session_backend_is_bounded_unless_an_operator_says_otherwise() {
let backend = SessionBackend::redis("redis://x", "ns").expect("cfg");
assert_eq!(backend.wait_ttl(), Some(DEFAULT_WAIT_TTL));
assert!(
DEFAULT_WAIT_TTL >= Duration::from_secs(60 * 60),
"a default under an hour would drop conversations a human parked"
);
let config = StorageConfig::from_vars(
Some("redis"),
None,
Some("redis://x"),
Some("ns"),
None,
None,
)
.expect("resolve");
assert_eq!(config.session.wait_ttl(), Some(DEFAULT_WAIT_TTL));
}
#[test]
fn the_wait_ttl_is_overridable_and_zero_disables_it() {
let config = StorageConfig::from_vars(
Some("redis"),
None,
Some("redis://x"),
Some("ns"),
None,
Some("90"),
)
.expect("resolve");
assert_eq!(config.session.wait_ttl(), Some(Duration::from_secs(90)));
let disabled = StorageConfig::from_vars(
Some("redis"),
None,
Some("redis://x"),
Some("ns"),
None,
Some("0"),
)
.expect("resolve");
assert_eq!(disabled.session.wait_ttl(), None);
}
#[test]
fn an_unparseable_ttl_falls_back_to_the_bounded_default() {
let config = StorageConfig::from_vars(
Some("redis"),
None,
Some("redis://x"),
Some("ns"),
None,
Some("ten minutes"),
)
.expect("resolve");
assert_eq!(config.session.wait_ttl(), Some(DEFAULT_WAIT_TTL));
}
#[test]
fn a_zero_duration_reads_as_disabled_rather_than_as_instant_expiry() {
let backend =
SessionBackend::redis_with_ttl("redis://x", "ns", Some(Duration::ZERO)).expect("cfg");
assert_eq!(backend.wait_ttl(), None);
}
#[test]
fn the_description_reports_the_ttl_so_an_operator_can_see_it() {
let bounded = SessionBackend::redis("redis://x", "ns").expect("cfg");
assert!(bounded.describe().contains("86400s"));
let unbounded = SessionBackend::redis_with_ttl("redis://x", "ns", None).expect("cfg");
assert!(unbounded.describe().contains("none"));
}
#[test]
fn every_refusal_names_the_variable_that_fixes_it() {
assert!(
StorageConfigError::MissingRedisUrl { store: "state" }
.to_string()
.contains(ENV_REDIS_URL)
);
let namespace = StorageConfigError::MissingSessionNamespace.to_string();
assert!(namespace.contains(ENV_SESSION_NAMESPACE));
assert!(namespace.contains(ENV_GREENTIC_ENV));
}
}