Skip to main content

laravel_tenanted/
lib.rs

1//! Storage-agnostic **database-per-tenant** support for `laravel-rust` — the idiomatic Rust
2//! equivalent of Rails' `activerecord-tenanted`, with **zero dependency on LiteVault**.
3//!
4//! Built natively on `laravel::db::DatabaseManager`, `DatabaseManager::using_connection`,
5//! `laravel::context`, `laravel::queue::Middleware`, `laravel::cache::Store`, `laravel::storage`,
6//! `laravel::event`, `laravel::errors::Status`, and Artisan commands so **completely ordinary
7//! `laravel-rust` code** (`#[model]`, `create!(...)`, `db::table(...)`, `db::query!(...)`,
8//! `db::transaction(...)`, Route Model Binding, DB validation, queues, cache, file storage, and
9//! logs) is **automatically tenant-scoped** across:
10//! - **Plain local SQLite** (`sqlite://storage/tenants/{tenant}/main.sqlite3?mode=rwc`, default),
11//! - **PostgreSQL / MySQL** (`postgres://user:pass@host/tenant_{tenant}`), or
12//! - **LiteVault S3/R2 SQLite VFS** (`laravel_rust_litevault::tenanted_database_url("tenants/{tenant}/main")`).
13//!
14//! # Quick Start
15//!
16//! Enable multi-tenancy in **1 line** on `Application::configure()`:
17//!
18//! ```rust,ignore
19//! use laravel_tenanted::WithTenancy;
20//!
21//! laravel::Application::configure()
22//!     .with_tenancy()
23//!     .with_routing(|routing, _| {
24//!         routing.routes(|route| {
25//!             route.get("/invoices", list_invoices);
26//!         });
27//!     })
28//!     .run()
29//! ```
30//!
31//! Or customize your subdomain / session resolver and tenant tables inline with
32//! `.with_tenancy_using(|t| ...)` (no `Box::pin`, no manual provider/cache wiring):
33//!
34//! ```rust,ignore
35//! use laravel_tenanted::WithTenancy;
36//!
37//! laravel::Application::configure()
38//!     .with_tenancy_using(|t| {
39//!         t.subdomain("myapp.com") // or t.session("active_org") for Inertia apps
40//!             .create_table("invoices", |table| {
41//!                 table.id();
42//!                 table.string("label").unique();
43//!                 table.big_integer("cents");
44//!             });
45//!     })
46//!     .with_routing(|routing, _| {
47//!         routing.routes(|route| {
48//!             route.get("/invoices", list_invoices);
49//!         });
50//!     })
51//!     .run()
52//! ```
53//!
54//! Inside any route, job, or [`using_tenant`] scope, write completely normal `laravel-rust` code:
55//!
56//! ```rust,ignore
57//! use laravel::http::Json;
58//! use laravel::model::model;
59//! use laravel_tenanted::Tenant;
60//!
61//! #[model]
62//! pub struct Invoice { pub id: i64, pub label: String, pub cents: i64 }
63//!
64//! async fn list_invoices(_tenant: Tenant) -> laravel::Result<Json<Vec<Invoice>>> {
65//!     Ok(Json(Invoice::query().get().await?))
66//! }
67//! ```
68
69pub mod builder;
70pub mod cache;
71pub mod commands;
72pub mod config;
73pub mod error;
74pub mod events;
75pub mod extract;
76pub mod manager;
77pub mod middleware;
78pub mod provider;
79pub mod queue;
80pub mod storage;
81pub mod testing;
82
83use std::future::Future;
84use std::sync::Arc;
85
86use laravel::db::{AnyConnection, Builder};
87
88pub use builder::{TenancyBuilder, WithTenancy};
89pub use cache::{TenantedCache, TenantedCacheSettings, TenantedCacheStore};
90pub use commands::{
91    TenantCreateCommand, TenantDeleteCommand, TenantEvictCommand, TenantListCommand,
92    TenantMigrateCommand,
93};
94pub use config::{
95    IntoTenantMigration, MigrationFn, MigrationFuture, TenantConfig, TenantDeleteFn,
96    TenantExistsFn, TenantListerFn, TenantMigration, TenantPoolStats,
97};
98pub use error::{NO_TENANT_CONNECTION, TenantedError, sanitize_tenant_id};
99pub use events::{
100    TenantCreated, TenantDeleted, TenantEntered, TenantEvicted, TenantExited, TenantMigrated,
101};
102pub use extract::Tenant;
103pub use manager::{TenantManager, global_manager, set_global_manager};
104pub use middleware::{RequestTenantResolver, ResolveTenantMiddleware};
105pub use provider::TenantedServiceProvider;
106pub use queue::TenantQueueMiddleware;
107pub use storage::TenantedStorage;
108
109/// Resolve the active [`TenantManager`] from the current `laravel::Application` container (or
110/// fallback global manager).
111pub async fn manager() -> laravel::Result<Arc<TenantManager>> {
112    Ok(manager::resolve_manager().await?)
113}
114
115/// Return the validated tenant ID active in the current scope (or `None` when outside a tenant
116/// scope or inside [`without_tenant`]).
117pub fn current() -> Option<String> {
118    let key = global_manager()
119        .map(|m| m.config.context_key.clone())
120        .unwrap_or_else(|| "tenant".into());
121    manager::active_tenant(&key)
122}
123
124/// Backwards-compatible alias for [`current`].
125pub fn current_tenant() -> Option<String> {
126    current()
127}
128
129/// Return `true` when code is executing inside an active tenant scope.
130pub fn is_active() -> bool {
131    current().is_some()
132}
133
134/// Return the currently active tenant ID, or fail with [`TenantedError::NoTenant`].
135pub fn require() -> laravel::Result<String> {
136    current().ok_or_else(|| TenantedError::NoTenant.into())
137}
138
139/// Return the currently active tenant ID as a typed `Result<String, TenantedError>`.
140pub fn id() -> Result<String, TenantedError> {
141    current().ok_or(TenantedError::NoTenant)
142}
143
144/// Return the `DatabaseManager` connection name for the active tenant (e.g. `"tenant_acme"`).
145pub fn connection_name() -> Option<String> {
146    let tid = current()?;
147    let prefix = global_manager()
148        .map(|m| m.config.connection_prefix.clone())
149        .unwrap_or_else(|| "tenant_".into());
150    Some(format!("{prefix}{tid}"))
151}
152
153/// Backwards-compatible alias for [`connection_name`].
154pub fn current_connection_name() -> Option<String> {
155    connection_name()
156}
157
158/// Run an async block strictly scoped to one validated tenant — exact Rust equivalent of
159/// Rails' `ApplicationRecord.with_tenant("acme") { ... }`.
160///
161/// Inside `fut`, `laravel::db::using_connection`, `laravel::context`, and lifecycle events are
162/// all automatically configured so vanilla `Model::query()`, `create!(...)`, `db::table(...)`,
163/// `db::query!(...)`, `db::transaction(...)`, `laravel::cache`, and `laravel::queue` all target
164/// `tenant_id`.
165pub async fn run<F, T>(tenant_id: &str, fut: F) -> laravel::Result<T>
166where
167    F: Future<Output = laravel::Result<T>>,
168{
169    let mgr = manager::resolve_manager().await?;
170    mgr.run(tenant_id, fut).await
171}
172
173/// Alias for [`run`] matching Rails' `with_tenant`.
174pub async fn with_tenant<F, T>(tenant_id: &str, fut: F) -> laravel::Result<T>
175where
176    F: Future<Output = laravel::Result<T>>,
177{
178    run(tenant_id, fut).await
179}
180
181/// Alias for [`run`] matching `laravel::db::using_connection`.
182pub async fn using_tenant<F, T>(tenant_id: &str, fut: F) -> laravel::Result<T>
183where
184    F: Future<Output = laravel::Result<T>>,
185{
186    run(tenant_id, fut).await
187}
188
189/// Temporarily execute `fut` outside any tenant scope on the central (shared) database —
190/// exact sibling of `laravel::model::without_events` and Rails' `without_tenant`.
191/// Restores the surrounding tenant scope cleanly on exit.
192pub async fn without_tenant<F, T>(fut: F) -> laravel::Result<T>
193where
194    F: Future<Output = laravel::Result<T>>,
195{
196    let mgr = manager::resolve_manager().await?;
197    mgr.without_tenant(fut).await
198}
199
200/// Alias for [`without_tenant`] familiar to `stancl/tenancy` users.
201pub async fn central<F, T>(fut: F) -> laravel::Result<T>
202where
203    F: Future<Output = laravel::Result<T>>,
204{
205    without_tenant(fut).await
206}
207
208/// Alias for [`without_tenant`] familiar to `spatie/laravel-multitenancy` users.
209pub async fn landlord<F, T>(fut: F) -> laravel::Result<T>
210where
211    F: Future<Output = laravel::Result<T>>,
212{
213    without_tenant(fut).await
214}
215
216/// Obtain the native `laravel::db::AnyConnection` for the currently active tenant (or fail with
217/// [`TenantedError::NoTenant`]).
218pub async fn connection() -> laravel::Result<AnyConnection> {
219    let mgr = manager::resolve_manager().await?;
220    let tid = manager::active_tenant(&mgr.config.context_key).ok_or(TenantedError::NoTenant)?;
221    mgr.connection(&tid).await
222}
223
224/// Start a native `laravel::db::Builder` scoped to the currently active tenant's database.
225pub async fn table(name: impl Into<String>) -> laravel::Result<Builder> {
226    let conn = connection().await?;
227    Ok(conn.table(name.into()))
228}
229
230/// Return a tenant-scoped cache wrapper around the application's default cache store.
231/// Fails closed with [`TenantedError::NoTenant`] if no tenant is active.
232pub fn cache() -> laravel::Result<TenantedCache> {
233    let repo = laravel::cache::manager().default_store()?;
234    let key = global_manager()
235        .map(|m| m.config.context_key.clone())
236        .unwrap_or_else(|| "tenant".into());
237    TenantedCache::for_current(repo, &key)
238}
239
240/// Return a tenant-scoped cache wrapper around a named `laravel::cache` store (e.g. `"redis"`).
241pub fn cache_store(store_name: &str) -> laravel::Result<TenantedCache> {
242    let repo = laravel::cache::store(store_name)?;
243    let key = global_manager()
244        .map(|m| m.config.context_key.clone())
245        .unwrap_or_else(|| "tenant".into());
246    TenantedCache::for_current(repo, &key)
247}
248
249/// Return a tenant-scoped storage wrapper around the application's default `laravel::storage::Disk`
250/// (automatically prefixing all paths with `{storage_prefix}/{id}/` and rejecting path traversal).
251/// Fails closed with [`TenantedError::NoTenant`] if no tenant is active.
252pub fn storage() -> laravel::Result<TenantedStorage> {
253    let disk = laravel::storage::default_disk()?;
254    let (key, prefix) = global_manager()
255        .map(|m| (m.config.context_key.clone(), m.config.storage_prefix.clone()))
256        .unwrap_or_else(|| ("tenant".into(), "tenants".into()));
257    TenantedStorage::for_current(disk, &key, &prefix)
258}
259
260/// Return a tenant-scoped storage wrapper around a named `laravel::storage::Disk` (e.g. `"s3"`,
261/// `"public"`, `"local"`, or `"laravel_cloud"`), automatically prefixing all paths with
262/// `{storage_prefix}/{id}/` and rejecting path traversal.
263pub fn storage_disk(disk_name: &str) -> laravel::Result<TenantedStorage> {
264    let disk = laravel::storage::disk(disk_name)?;
265    let (key, prefix) = global_manager()
266        .map(|m| (m.config.context_key.clone(), m.config.storage_prefix.clone()))
267        .unwrap_or_else(|| ("tenant".into(), "tenants".into()));
268    TenantedStorage::for_current(disk, &key, &prefix)
269}
270
271/// Explicitly provision and migrate a new tenant database.
272pub async fn create(tenant_id: &str) -> laravel::Result<AnyConnection> {
273    let mgr = manager::resolve_manager().await?;
274    mgr.create(tenant_id).await
275}
276
277/// Check whether `tenant_id` already exists.
278pub async fn exists(tenant_id: &str) -> laravel::Result<bool> {
279    let mgr = manager::resolve_manager().await?;
280    mgr.exists(tenant_id)
281}
282
283/// Run pending migrations on `tenant_id`.
284pub async fn migrate(tenant_id: &str) -> laravel::Result<Vec<String>> {
285    let mgr = manager::resolve_manager().await?;
286    mgr.migrate(tenant_id).await
287}
288
289/// List all discovered and currently open tenants.
290pub async fn list() -> laravel::Result<Vec<String>> {
291    let mgr = manager::resolve_manager().await?;
292    mgr.list_tenants()
293}
294
295/// Evict one tenant's connection pool from the LRU cache.
296pub async fn evict(tenant_id: &str) -> laravel::Result<()> {
297    let mgr = manager::resolve_manager().await?;
298    mgr.evict(tenant_id)
299}
300
301/// Evict and permanently delete a tenant database.
302pub async fn delete(tenant_id: &str) -> laravel::Result<()> {
303    let mgr = manager::resolve_manager().await?;
304    mgr.delete(tenant_id).await
305}
306
307/// Iterate across all discovered tenants (or an explicit list via `for_each_in`), executing `f`
308/// inside [`run`] for each tenant.
309pub async fn for_each<F, Fut>(mut f: F) -> laravel::Result<()>
310where
311    F: FnMut(String) -> Fut,
312    Fut: Future<Output = laravel::Result<()>>,
313{
314    let mgr = manager::resolve_manager().await?;
315    let tenants = mgr.list_tenants()?;
316    for tid in tenants {
317        let tid_for_cb = tid.clone();
318        mgr.run(&tid, f(tid_for_cb)).await?;
319    }
320    Ok(())
321}
322
323/// Iterate across an explicit list of tenant IDs, executing `f` inside [`run`] for each.
324pub async fn for_each_in<I, S, F, Fut>(tenants: I, mut f: F) -> laravel::Result<()>
325where
326    I: IntoIterator<Item = S>,
327    S: AsRef<str>,
328    F: FnMut(String) -> Fut,
329    Fut: Future<Output = laravel::Result<()>>,
330{
331    let mgr = manager::resolve_manager().await?;
332    for raw in tenants {
333        let clean = sanitize_tenant_id(raw.as_ref())?;
334        let tid_for_cb = clean.clone();
335        mgr.run(&clean, f(tid_for_cb)).await?;
336    }
337    Ok(())
338}