use larust_core::AppError;
use larust_orm::Backend;
use sqlx::AnyPool;
fn normalize_scope(scope: Option<&str>) -> &str {
scope.unwrap_or("")
}
async fn ensure_table(pool: &AnyPool) -> Result<(), AppError> {
let create_table = match larust_orm::backend() {
Backend::Sqlite => {
"CREATE TABLE IF NOT EXISTS feature_flags (\
name TEXT NOT NULL, \
scope TEXT NOT NULL, \
active INTEGER NOT NULL, \
PRIMARY KEY (name, scope)\
)"
}
Backend::MySql => {
"CREATE TABLE IF NOT EXISTS feature_flags (\
name VARCHAR(255) NOT NULL, \
scope VARCHAR(255) NOT NULL, \
active INTEGER NOT NULL, \
PRIMARY KEY (name, scope)\
)"
}
Backend::Postgres => {
"CREATE TABLE IF NOT EXISTS feature_flags (\
name TEXT NOT NULL, \
scope TEXT NOT NULL, \
active INTEGER NOT NULL, \
PRIMARY KEY (name, scope)\
)"
}
};
sqlx::query(create_table)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
pub async fn active(name: &str, scope: Option<&str>, default: bool) -> Result<bool, AppError> {
let pool = larust_orm::pool()?;
ensure_table(pool).await?;
let backend = larust_orm::backend();
let select_sql = format!(
"SELECT active FROM feature_flags WHERE name = {} AND scope = {}",
larust_orm::placeholder(backend, 1),
larust_orm::placeholder(backend, 2),
);
let row: Option<(i64,)> = sqlx::query_as(&select_sql)
.bind(name)
.bind(normalize_scope(scope))
.fetch_optional(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(row.map(|(active,)| active != 0).unwrap_or(default))
}
async fn set_active(name: &str, scope: Option<&str>, value: bool) -> Result<(), AppError> {
let pool = larust_orm::pool()?;
ensure_table(pool).await?;
let upsert_sql = match larust_orm::backend() {
Backend::Sqlite => {
"INSERT INTO feature_flags (name, scope, active) VALUES (?, ?, ?) \
ON CONFLICT(name, scope) DO UPDATE SET active = excluded.active"
}
Backend::MySql => {
"INSERT INTO feature_flags (name, scope, active) VALUES (?, ?, ?) \
ON DUPLICATE KEY UPDATE active = VALUES(active)"
}
Backend::Postgres => {
"INSERT INTO feature_flags (name, scope, active) VALUES ($1, $2, $3) \
ON CONFLICT(name, scope) DO UPDATE SET active = excluded.active"
}
};
sqlx::query(upsert_sql)
.bind(name)
.bind(normalize_scope(scope))
.bind(i64::from(value))
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
pub async fn activate(name: &str, scope: Option<&str>) -> Result<(), AppError> {
set_active(name, scope, true).await
}
pub async fn deactivate(name: &str, scope: Option<&str>) -> Result<(), AppError> {
set_active(name, scope, false).await
}
pub async fn forget(name: &str, scope: Option<&str>) -> Result<(), AppError> {
let pool = larust_orm::pool()?;
ensure_table(pool).await?;
let backend = larust_orm::backend();
let sql = format!(
"DELETE FROM feature_flags WHERE name = {} AND scope = {}",
larust_orm::placeholder(backend, 1),
larust_orm::placeholder(backend, 2),
);
sqlx::query(&sql)
.bind(name)
.bind(normalize_scope(scope))
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
pub async fn purge(name: &str) -> Result<(), AppError> {
let pool = larust_orm::pool()?;
ensure_table(pool).await?;
let backend = larust_orm::backend();
let sql = format!(
"DELETE FROM feature_flags WHERE name = {}",
larust_orm::placeholder(backend, 1)
);
sqlx::query(&sql)
.bind(name)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
async fn connect_test_db() {
let dir = tempfile::tempdir().unwrap().keep();
let database_url = format!("sqlite://{}/test.sqlite", dir.display());
larust_orm::connect(&database_url).await.unwrap();
}
#[tokio::test]
async fn pennant_crate_behaves_correctly_across_every_scenario() {
connect_test_db().await;
assert!(active("new-api", None, true).await.unwrap());
assert!(!active("new-api", None, false).await.unwrap());
assert!(!active("new-api", Some("user:1"), false).await.unwrap());
activate("new-api", Some("user:1")).await.unwrap();
assert!(active("new-api", Some("user:1"), false).await.unwrap());
assert!(!active("new-api", None, false).await.unwrap());
assert!(!active("new-api", Some("user:2"), false).await.unwrap());
deactivate("new-api", Some("user:1")).await.unwrap();
assert!(!active("new-api", Some("user:1"), true).await.unwrap());
activate("new-api", Some("user:1")).await.unwrap();
assert!(active("new-api", Some("user:1"), false).await.unwrap());
activate("new-api", None).await.unwrap();
assert!(active("new-api", None, false).await.unwrap());
assert!(active("new-api", Some("user:1"), false).await.unwrap());
deactivate("new-api", None).await.unwrap();
assert!(!active("new-api", None, true).await.unwrap());
assert!(active("new-api", Some("user:1"), false).await.unwrap());
forget("new-api", Some("user:1")).await.unwrap();
assert!(active("new-api", Some("user:1"), true).await.unwrap());
assert!(!active("new-api", Some("user:1"), false).await.unwrap());
activate("new-api", Some("user:2")).await.unwrap();
activate("other-flag", Some("user:2")).await.unwrap();
purge("new-api").await.unwrap();
assert!(!active("new-api", Some("user:2"), false).await.unwrap());
assert!(!active("new-api", None, false).await.unwrap());
assert!(active("other-flag", Some("user:2"), false).await.unwrap());
}
}