larust_pennant/lib.rs
1//! Laravel's `laravel/pennant` - feature flags, narrowed to its core:
2//! persisted, scope-aware boolean flags, with no process-wide resolver
3//! registry.
4//!
5//! **No `Feature::define(...)` registry, deliberately.** Real Pennant lets
6//! an app register a default-value *closure* once (typically in a service
7//! provider), and `Feature::active(...)` calls it lazily on first check per
8//! scope, persisting the result. A process-wide `OnceLock<HashMap<String,
9//! BoxedResolver>>` could reproduce that here, but this framework has
10//! already rejected that exact shape once - `larust_queue::JobRegistry`'s
11//! own doc comment is explicit that its handler map is "not a process-wide
12//! static... built fresh by whatever calls `work()`", specifically because
13//! only one thing in one process ever needs it. A feature flag's default
14//! has the same shape: decided by the one call site that cares, not a
15//! registry every part of the app must agree to populate before anything
16//! can check a flag. [`active`] takes its `default` as a plain argument
17//! instead - the caller supplies "what if nothing's been decided yet" right
18//! where it's checked, same as any other `Option`-shaped default would be.
19//!
20//! Boolean-only, not Pennant's richer non-boolean "value" flags
21//! (`Feature::value('purchase-button', fn () => ...)` returning a string/
22//! array) - deliberately out of scope for this version: the vast majority
23//! of real Pennant usage is the boolean on/off case this crate covers, and
24//! a typed, non-boolean value store is a genuinely different, larger
25//! feature (what type? how is it validated? how does a caller declare the
26//! type it expects back?) worth its own design, not bolted on speculatively
27//! here.
28//!
29//! Storage is unconditionally SQL (`feature_flags`, this crate's own
30//! table - the same "owns a small table" shape `larust-sanctum`/
31//! `larust-permissions`/`larust-notifications`/`larust-cache` each
32//! already have), not Pennant's own pluggable `array`/`database` driver
33//! split: an in-memory driver would silently lose every flag on restart,
34//! which defeats the entire point of a *persisted* rollout decision - not
35//! a real choice worth offering.
36//!
37//! Re-exported through `larust_support::pennant` (see `crates/
38//! larust-support/src/lib.rs`) so generated apps depend only on
39//! `larust-support`, never on this crate directly - the same wiring every
40//! other optional Tier-1 shim crate already uses.
41//!
42//! ## Deliberately out of scope for this version
43//!
44//! - **No `@feature`/`@endfeature` Blade directive.** Unlike `@can`/
45//! `@role` (gated by `larust-permissions`), `larust-view`'s own
46//! directive set is a fixed list hardcoded in its parser, not a
47//! pluggable registry an optional crate can extend - adding one is a
48//! real, separate change to a core crate, not something this crate can
49//! do on its own. [`active`] is still callable directly from any
50//! controller/view-context-building code in the meantime, same as
51//! Laravel's own `Feature::active(...)` is usable outside Blade too.
52//! - **No `pennant:purge`-equivalent "purge everything" operation.**
53//! [`purge`] removes one named flag across every scope (the safe,
54//! common "retire this flag" case); clearing the entire table in one
55//! call is a sharper footgun with no real use case this crate has seen
56//! requested yet.
57//! - **No rich/non-boolean values** - see this doc comment's own opening
58//! for why.
59
60use larust_core::AppError;
61use larust_orm::Backend;
62use sqlx::AnyPool;
63
64/// `None` (an unscoped, "global" flag) is stored as an empty string, not
65/// SQL `NULL` - `(name, scope)` is this table's composite primary key, and
66/// standard SQL `NULL` never equals itself for uniqueness purposes (two
67/// `NULL` scopes for the same `name` wouldn't collide), which would let
68/// `activate("x", None)` silently insert a second, un-deduplicated row
69/// every time instead of updating the one already there. An empty string
70/// is a value no real scope (a user id, an email, a tenant slug) will ever
71/// collide with, and keeps the primary key simple and `NOT NULL` like
72/// every other string-keyed table in this codebase already is.
73fn normalize_scope(scope: Option<&str>) -> &str {
74 scope.unwrap_or("")
75}
76
77/// Same lazy self-bootstrap idiom `larust-sanctum`/`larust-notifications`'s
78/// own `ensure_table` establishes - plain `CREATE TABLE IF NOT EXISTS`, no
79/// migration file and no explicit startup call needed anywhere.
80/// Deliberately **not** memoized behind a `OnceCell`: `larust_testing::
81/// test_transaction`/a fresh per-test database means a process-wide
82/// completion flag could point at a since-discarded database - the exact
83/// regression `larust-notifications`'s own doc comment documents hitting
84/// once already. `IF NOT EXISTS` makes re-running this on every call cheap
85/// enough that giving up the memoization is the better trade.
86async fn ensure_table(pool: &AnyPool) -> Result<(), AppError> {
87 let create_table = match larust_orm::backend() {
88 Backend::Sqlite => {
89 "CREATE TABLE IF NOT EXISTS feature_flags (\
90 name TEXT NOT NULL, \
91 scope TEXT NOT NULL, \
92 active INTEGER NOT NULL, \
93 PRIMARY KEY (name, scope)\
94 )"
95 }
96 // `VARCHAR`, not MySQL's own `TEXT` - a `TEXT`/`BLOB` column used
97 // in a key specification (this table's composite primary key)
98 // needs an explicit length ("BLOB/TEXT column used in key
99 // specification without a key length"), the same lesson
100 // `larust-cache`'s own `cache_items` table and `larust-sanctum`'s
101 // own `token_hash` column already document. `VARCHAR(255)` is a
102 // reasonable cap for a flag name or a scope string (a user id, an
103 // email, a short slug).
104 Backend::MySql => {
105 "CREATE TABLE IF NOT EXISTS feature_flags (\
106 name VARCHAR(255) NOT NULL, \
107 scope VARCHAR(255) NOT NULL, \
108 active INTEGER NOT NULL, \
109 PRIMARY KEY (name, scope)\
110 )"
111 }
112 // Postgres has native, unbounded `TEXT` and no MySQL-style
113 // key-length requirement - same shape as SQLite's own arm.
114 Backend::Postgres => {
115 "CREATE TABLE IF NOT EXISTS feature_flags (\
116 name TEXT NOT NULL, \
117 scope TEXT NOT NULL, \
118 active INTEGER NOT NULL, \
119 PRIMARY KEY (name, scope)\
120 )"
121 }
122 };
123 sqlx::query(create_table)
124 .execute(pool)
125 .await
126 .map_err(|source| AppError::Internal(Box::new(source)))?;
127 Ok(())
128}
129
130/// Whether `name` is active for `scope` (`None` for the unscoped, global
131/// case - see [`normalize_scope`]'s own doc comment). Returns `default`
132/// when nothing has been decided yet for this exact `(name, scope)` pair -
133/// the caller's own fallback, not a registered resolver (see this crate's
134/// own doc comment for why). Laravel's `Feature::for($user)->active('x')`/
135/// plain `Feature::active('x')`.
136pub async fn active(name: &str, scope: Option<&str>, default: bool) -> Result<bool, AppError> {
137 let pool = larust_orm::pool()?;
138 ensure_table(pool).await?;
139
140 let backend = larust_orm::backend();
141 let select_sql = format!(
142 "SELECT active FROM feature_flags WHERE name = {} AND scope = {}",
143 larust_orm::placeholder(backend, 1),
144 larust_orm::placeholder(backend, 2),
145 );
146 let row: Option<(i64,)> = sqlx::query_as(&select_sql)
147 .bind(name)
148 .bind(normalize_scope(scope))
149 .fetch_optional(pool)
150 .await
151 .map_err(|source| AppError::Internal(Box::new(source)))?;
152
153 Ok(row.map(|(active,)| active != 0).unwrap_or(default))
154}
155
156/// Shared upsert behind [`activate`]/[`deactivate`] - same "one named row
157/// per `(name, scope)`, overwrite on conflict" shape `larust-cache`'s own
158/// `put` already establishes for `cache_items`, just keyed by a composite
159/// `(name, scope)` pair instead of a single `key` column.
160async fn set_active(name: &str, scope: Option<&str>, value: bool) -> Result<(), AppError> {
161 let pool = larust_orm::pool()?;
162 ensure_table(pool).await?;
163
164 let upsert_sql = match larust_orm::backend() {
165 Backend::Sqlite => {
166 "INSERT INTO feature_flags (name, scope, active) VALUES (?, ?, ?) \
167 ON CONFLICT(name, scope) DO UPDATE SET active = excluded.active"
168 }
169 Backend::MySql => {
170 "INSERT INTO feature_flags (name, scope, active) VALUES (?, ?, ?) \
171 ON DUPLICATE KEY UPDATE active = VALUES(active)"
172 }
173 Backend::Postgres => {
174 "INSERT INTO feature_flags (name, scope, active) VALUES ($1, $2, $3) \
175 ON CONFLICT(name, scope) DO UPDATE SET active = excluded.active"
176 }
177 };
178 sqlx::query(upsert_sql)
179 .bind(name)
180 .bind(normalize_scope(scope))
181 .bind(i64::from(value))
182 .execute(pool)
183 .await
184 .map_err(|source| AppError::Internal(Box::new(source)))?;
185
186 Ok(())
187}
188
189/// Persists `name` as active for `scope` - every later [`active`] call for
190/// this exact pair returns `true` until [`deactivate`]/[`forget`].
191/// Laravel's `Feature::activate('x')`.
192pub async fn activate(name: &str, scope: Option<&str>) -> Result<(), AppError> {
193 set_active(name, scope, true).await
194}
195
196/// Persists `name` as inactive for `scope` - every later [`active`] call
197/// for this exact pair returns `false` until [`activate`]/[`forget`].
198/// Laravel's `Feature::deactivate('x')`.
199pub async fn deactivate(name: &str, scope: Option<&str>) -> Result<(), AppError> {
200 set_active(name, scope, false).await
201}
202
203/// Removes any stored decision for `(name, scope)` - a later [`active`]
204/// call for this exact pair falls back to its own `default` argument
205/// again, as if nothing had ever been decided. Laravel's
206/// `Feature::forget('x')`.
207pub async fn forget(name: &str, scope: Option<&str>) -> Result<(), AppError> {
208 let pool = larust_orm::pool()?;
209 ensure_table(pool).await?;
210
211 let backend = larust_orm::backend();
212 let sql = format!(
213 "DELETE FROM feature_flags WHERE name = {} AND scope = {}",
214 larust_orm::placeholder(backend, 1),
215 larust_orm::placeholder(backend, 2),
216 );
217 sqlx::query(&sql)
218 .bind(name)
219 .bind(normalize_scope(scope))
220 .execute(pool)
221 .await
222 .map_err(|source| AppError::Internal(Box::new(source)))?;
223
224 Ok(())
225}
226
227/// Removes every stored decision for `name`, across every scope - for
228/// retiring a flag entirely once a rollout is finished, rather than
229/// forgetting one scope at a time. Laravel's `Feature::purge('x')` (this
230/// crate has no equivalent of purging *every* flag in one call - see this
231/// module's own doc comment for why).
232pub async fn purge(name: &str) -> Result<(), AppError> {
233 let pool = larust_orm::pool()?;
234 ensure_table(pool).await?;
235
236 let backend = larust_orm::backend();
237 let sql = format!(
238 "DELETE FROM feature_flags WHERE name = {}",
239 larust_orm::placeholder(backend, 1)
240 );
241 sqlx::query(&sql)
242 .bind(name)
243 .execute(pool)
244 .await
245 .map_err(|source| AppError::Internal(Box::new(source)))?;
246
247 Ok(())
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253
254 async fn connect_test_db() {
255 let dir = tempfile::tempdir().unwrap().keep();
256 let database_url = format!("sqlite://{}/test.sqlite", dir.display());
257 larust_orm::connect(&database_url).await.unwrap();
258 }
259
260 /// All scenarios share one test function, not several - `larust_orm::
261 /// connect()` sets a process-wide pool exactly once, the same
262 /// constraint `larust-sanctum`/`larust-permissions`/
263 /// `larust-notifications`'s own test suites document and work around.
264 #[tokio::test]
265 async fn pennant_crate_behaves_correctly_across_every_scenario() {
266 connect_test_db().await;
267
268 // A flag nobody has ever decided on falls back to the caller's
269 // own `default`, whichever way it's asked.
270 assert!(active("new-api", None, true).await.unwrap());
271 assert!(!active("new-api", None, false).await.unwrap());
272 assert!(!active("new-api", Some("user:1"), false).await.unwrap());
273
274 // Activating it for one scope persists `true` there, regardless
275 // of what `default` the caller supplies on the next check - and
276 // leaves every other scope (including the unscoped/global one)
277 // completely untouched.
278 activate("new-api", Some("user:1")).await.unwrap();
279 assert!(active("new-api", Some("user:1"), false).await.unwrap());
280 assert!(!active("new-api", None, false).await.unwrap());
281 assert!(!active("new-api", Some("user:2"), false).await.unwrap());
282
283 // Deactivating persists `false` the same way - not merely "forget
284 // the previous value", a real, explicit decision of its own.
285 deactivate("new-api", Some("user:1")).await.unwrap();
286 assert!(!active("new-api", Some("user:1"), true).await.unwrap());
287
288 // Re-activating the same `(name, scope)` pair overwrites in
289 // place - no duplicate-row/uniqueness error on the second write.
290 activate("new-api", Some("user:1")).await.unwrap();
291 assert!(active("new-api", Some("user:1"), false).await.unwrap());
292
293 // The unscoped/global flag is entirely independent of any scoped
294 // decision under the same name.
295 activate("new-api", None).await.unwrap();
296 assert!(active("new-api", None, false).await.unwrap());
297 assert!(active("new-api", Some("user:1"), false).await.unwrap());
298 deactivate("new-api", None).await.unwrap();
299 assert!(!active("new-api", None, true).await.unwrap());
300 assert!(active("new-api", Some("user:1"), false).await.unwrap());
301
302 // Forgetting one scope reverts only that scope to the caller's
303 // own default, leaving every other scope's own stored decision
304 // alone.
305 forget("new-api", Some("user:1")).await.unwrap();
306 assert!(active("new-api", Some("user:1"), true).await.unwrap());
307 assert!(!active("new-api", Some("user:1"), false).await.unwrap());
308
309 // Purging a flag clears every scope it was ever set under -
310 // including ones `forget` above never touched - but leaves a
311 // different, unrelated flag name completely alone.
312 activate("new-api", Some("user:2")).await.unwrap();
313 activate("other-flag", Some("user:2")).await.unwrap();
314 purge("new-api").await.unwrap();
315 assert!(!active("new-api", Some("user:2"), false).await.unwrap());
316 assert!(!active("new-api", None, false).await.unwrap());
317 assert!(active("other-flag", Some("user:2"), false).await.unwrap());
318 }
319}