1
use crate::db::DBError;
2
use crate::telemetry::pools::{AcquireFailure, PoolKind, PoolUsage, record_acquire_failure};
3
use sqlx::types::Uuid;
4
use sqlx::{Pool, Postgres};
5
use std::collections::HashMap;
6
use std::sync::{Arc, Mutex, MutexGuard};
7
use std::time::{Duration, Instant};
8
use tokio::sync::{OnceCell, OwnedSemaphorePermit, Semaphore};
9

            
10
#[cfg(test)]
11
mod tests;
12
#[cfg(test)]
13
mod usage_tests;
14

            
15
/// Connections a single tenant pool may open.
16
pub(super) const TENANT_MAX_CONNECTIONS: u32 = 2;
17

            
18
/// Tenant pools resident in one process.
19
pub(super) const MAX_RESIDENT_POOLS: usize = 8;
20

            
21
/// How long a newcomer waits for a residency permit before giving up. Matches
22
/// the pool's own `acquire_timeout`, so a caller cannot wait appreciably longer
23
/// for a slot than for a connection once it has one.
24
const RESERVE_DEADLINE: Duration = Duration::from_secs(10);
25

            
26
/// How long each wait attempt runs before looking for a victim again.
27
const RESERVE_RETRY: Duration = Duration::from_millis(250);
28

            
29
/// A tenant pool and the residency permit that pays for it.
30
///
31
/// The permit lives *here*, not in the registry entry, and that placement is
32
/// what makes the budget hold under failure. The pool and its permit are
33
/// created and dropped as one value, so every path that discards a pool —
34
/// eviction, expiry, a failed build, a cancelled request — returns the permit
35
/// automatically. Nothing has to remember to.
36
///
37
/// It also decouples eviction from use: a caller holds an `Arc` of this while
38
/// working, so evicting the entry merely un-registers the pool. It stays alive,
39
/// and its permit stays spent, until the last user lets go.
40
pub(crate) struct TenantPool {
41
    pool: Pool<Postgres>,
42
    _permit: OwnedSemaphorePermit,
43
}
44

            
45
impl TenantPool {
46
47916
    pub(crate) const fn new(pool: Pool<Postgres>, permit: OwnedSemaphorePermit) -> Self {
47
47916
        Self {
48
47916
            pool,
49
47916
            _permit: permit,
50
47916
        }
51
47916
    }
52

            
53
885604
    pub(crate) const fn pool(&self) -> &Pool<Postgres> {
54
885604
        &self.pool
55
885604
    }
56
}
57

            
58
/// One user's slot. The cell is empty while a build is in flight; `OnceCell`
59
/// serializes creation per user, so concurrent first requests await one
60
/// initialization instead of each building a pool and overwriting the rest.
61
pub(super) type Slot = Arc<OnceCell<Arc<TenantPool>>>;
62

            
63
struct Entry {
64
    cell: Slot,
65
    last_used: Instant,
66
    /// When this tenant's quarantine status was last read from the directory.
67
    checked_at: Instant,
68
}
69

            
70
pub(super) struct PoolRegistry {
71
    pools: Arc<Mutex<HashMap<Uuid, Entry>>>,
72
    residency: Arc<Semaphore>,
73
    expiration: Duration,
74
    reserve_deadline: Duration,
75
}
76

            
77
/// Removes pools idle for longer than `expiration`. Dropping the entry drops
78
/// the pool and returns its permit; nothing else is required.
79
892445
fn sweep_expired(pools: &mut HashMap<Uuid, Entry>, expiration: Duration) {
80
    // `last_used` is stamped on acquire, so a connection held longer than the
81
    // idle timeout looks idle to the clock while it is very much in use: only
82
    // drop what nobody holds. An ABANDONED slot — never built, nobody
83
    // building — is exactly such a thing, and requiring an initialised pool to
84
    // sweep left one behind for every request cancelled mid-build, forever.
85
892445
    pools.retain(|_, e| e.last_used.elapsed() < expiration || !unheld(e));
86
892445
}
87

            
88
/// Whether nobody holds this entry: no caller has the slot, and no connection
89
/// is out on the pool if one was ever built.
90
42
fn unheld(entry: &Entry) -> bool {
91
42
    Arc::strong_count(&entry.cell) == 1
92
41
        && entry
93
41
            .cell
94
41
            .get()
95
40
            .is_none_or(|pool| Arc::strong_count(pool) == 1)
96
42
}
97

            
98
/// Removes the least-recently-used slot so a newcomer can take its permit.
99
/// Returns whether anything was actually evicted — a registry holding only
100
/// in-flight builds has no permit to give back yet.
101
14
fn evict_lru(pools: &mut HashMap<Uuid, Entry>) -> bool {
102
14
    let Some(victim) = pools
103
14
        .iter()
104
57
        .filter(|(_, e)| is_idle(e))
105
22
        .min_by_key(|(_, e)| e.last_used)
106
6
        .map(|(id, _)| *id)
107
    else {
108
8
        return false;
109
    };
110

            
111
6
    pools.remove(&victim).is_some()
112
14
}
113

            
114
/// Whether a pool can be dropped right now: nobody is using it, and nobody is
115
/// on their way to using it.
116
///
117
/// The permit travels with the pool and comes back only when its last
118
/// [`TenantConnection`] drops, so dropping a BUSY pool frees nothing — the
119
/// newcomer waits out the whole reserve deadline and fails, while the victim
120
/// rebuilds a second pool beside its still-live one and takes the tenant over
121
/// its own connection cap.
122
///
123
/// A slot still building is never idle: its permit is
124
/// taken inside the build, so dropping the slot frees nothing and only strands
125
/// the builder.
126
///
127
/// BOTH counts matter. A connection anchors the pool itself, but a caller that
128
/// has taken the slot and not yet reached the pool — it may be in `routing()`,
129
/// an admin-database round trip — holds only the slot, and evicting under it
130
/// puts that caller on an unregistered pool while its replacement is built.
131
57
fn is_idle(entry: &Entry) -> bool {
132
57
    entry.cell.get().is_some() && unheld(entry)
133
57
}
134

            
135
impl PoolRegistry {
136
51503
    pub(super) fn new(expiration: Duration) -> Self {
137
51503
        Self {
138
51503
            pools: Arc::new(Mutex::new(HashMap::new())),
139
51503
            residency: Arc::new(Semaphore::new(MAX_RESIDENT_POOLS)),
140
51503
            expiration,
141
51503
            reserve_deadline: RESERVE_DEADLINE,
142
51503
        }
143
51503
    }
144

            
145
47881
    pub(super) const fn idle_timeout(&self) -> Duration {
146
47881
        self.expiration
147
47881
    }
148

            
149
1846521
    fn lock(&self) -> Result<MutexGuard<'_, HashMap<Uuid, Entry>>, DBError> {
150
1846521
        self.pools.lock().map_err(|_| DBError::RegistryPoisoned)
151
1846521
    }
152

            
153
    /// Connections of the resident, built pools, summed over tenants.
154
2
    pub(super) fn usage(&self) -> Result<PoolUsage, DBError> {
155
2
        Ok(self
156
2
            .lock()?
157
            .values()
158
3
            .filter_map(|entry| entry.cell.get())
159
3
            .map(|tenant| PoolUsage::of(tenant.pool()))
160
3
            .fold(PoolUsage::default(), |total, one| total + one))
161
2
    }
162

            
163
    /// Marks the user's slot as used now and hands it back, if resident.
164
892445
    pub(super) fn touch(&self, user_id: Uuid) -> Result<Option<Slot>, DBError> {
165
892445
        let mut pools = self.lock()?;
166
892445
        sweep_expired(&mut pools, self.expiration);
167

            
168
892445
        Ok(pools.get_mut(&user_id).map(|entry| {
169
837721
            entry.last_used = Instant::now();
170
837721
            Arc::clone(&entry.cell)
171
837721
        }))
172
892445
    }
173

            
174
    /// Takes a permit now, evicting one idle pool if none is free. The permit an
175
    /// eviction frees is claimed here, before any deadline can discard it.
176
54780
    fn try_reserve(&self) -> Result<Option<OwnedSemaphorePermit>, DBError> {
177
54788
        let acquire = || Arc::clone(&self.residency).try_acquire_owned().ok();
178
54780
        if let Some(permit) = acquire() {
179
54772
            return Ok(Some(permit));
180
8
        }
181

            
182
8
        evict_lru(&mut *self.lock()?);
183
8
        Ok(acquire())
184
54780
    }
185

            
186
    /// Reserves a residency permit, evicting the least-recently-used pool when
187
    /// the process is already at its ceiling.
188
    ///
189
    /// Retried on every pass, which is safe only because `is_idle` refuses to
190
    /// take a pool anybody holds: a newcomer can therefore reclaim a resident
191
    /// that fell idle while it waited, instead of giving up on the one victim
192
    /// it found at the start and timing out beside an idle pool.
193
54777
    pub(super) async fn reserve(&self) -> Result<OwnedSemaphorePermit, DBError> {
194
54777
        let deadline = Instant::now() + self.reserve_deadline;
195

            
196
        loop {
197
54780
            if let Some(permit) = self.try_reserve()? {
198
54774
                return Ok(permit);
199
6
            }
200

            
201
6
            let remaining = deadline.saturating_duration_since(Instant::now());
202
6
            if remaining.is_zero() {
203
3
                record_acquire_failure(PoolKind::Tenant, AcquireFailure::Residency);
204
3
                return Err(DBError::PoolBudgetExhausted);
205
3
            }
206

            
207
3
            let wait = Arc::clone(&self.residency).acquire_owned();
208
3
            if let Ok(Ok(permit)) = tokio::time::timeout(remaining.min(RESERVE_RETRY), wait).await {
209
                return Ok(permit);
210
3
            }
211
        }
212
54777
    }
213

            
214
    /// Inserts an empty slot for `user_id`, or yields the existing one if
215
    /// another task won the race.
216
54772
    pub(super) fn install(&self, user_id: Uuid) -> Result<Slot, DBError> {
217
54772
        let mut pools = self.lock()?;
218

            
219
54772
        if let Some(existing) = pools.get_mut(&user_id) {
220
1
            existing.last_used = Instant::now();
221
1
            return Ok(Arc::clone(&existing.cell));
222
54771
        }
223

            
224
54771
        let cell = Slot::default();
225
54771
        pools.insert(
226
54771
            user_id,
227
54771
            Entry {
228
54771
                cell: Arc::clone(&cell),
229
54771
                last_used: Instant::now(),
230
54771
                checked_at: Instant::now(),
231
54771
            },
232
54771
        );
233

            
234
54771
        Ok(cell)
235
54772
    }
236

            
237
    /// Claims the right to re-read this tenant's quarantine status.
238
    ///
239
    /// Returns true to exactly one caller per interval. A plain "is it stale?"
240
    /// check would let every concurrent request for a tenant observe the same
241
    /// stale timestamp and each issue its own directory query — a stampede
242
    /// against an admin pool whose entire budget is 5. Claiming advances the
243
    /// clock under the lock, so the losers proceed on the previous answer.
244
    ///
245
    /// An absent entry answers true: that tenant is about to be built, and the
246
    /// build reads the directory anyway.
247
892450
    pub(super) fn claim_recheck(&self, user_id: Uuid, interval: Duration) -> Result<bool, DBError> {
248
892450
        let mut pools = self.lock()?;
249

            
250
892450
        let Some(entry) = pools.get_mut(&user_id) else {
251
1
            return Ok(true);
252
        };
253

            
254
892449
        if entry.checked_at.elapsed() < interval {
255
892446
            return Ok(false);
256
3
        }
257

            
258
3
        entry.checked_at = Instant::now();
259
3
        Ok(true)
260
892450
    }
261

            
262
    /// Rolls back a claimed recheck whose read failed, so the next caller
263
    /// retries instead of waiting out the interval on an unknown status.
264
2
    pub(super) fn release_recheck(&self, user_id: Uuid, interval: Duration) -> Result<(), DBError> {
265
2
        if let Some(entry) = self.lock()?.get_mut(&user_id) {
266
1
            entry.checked_at = Instant::now()
267
1
                .checked_sub(interval)
268
1
                .unwrap_or_else(Instant::now);
269
1
        }
270

            
271
2
        Ok(())
272
2
    }
273

            
274
    /// Drops a slot whose build failed — but only if it is still *this* slot.
275
    ///
276
    /// Without the identity check a caller whose build failed would evict
277
    /// whatever entry happens to sit under that user id, including a fresh one
278
    /// another task installed and populated in the meantime.
279
6842
    pub(super) fn forget(&self, user_id: Uuid, slot: &Slot) -> Result<(), DBError> {
280
6842
        let mut pools = self.lock()?;
281

            
282
6842
        if pools
283
6842
            .get(&user_id)
284
6842
            .is_some_and(|entry| Arc::ptr_eq(&entry.cell, slot))
285
        {
286
6841
            pools.remove(&user_id);
287
1
        }
288

            
289
6842
        Ok(())
290
6842
    }
291
}