1
use super::registry::{PoolRegistry, TENANT_MAX_CONNECTIONS, TenantPool};
2
use crate::config::system_config;
3
use crate::db::DBError;
4
use crate::telemetry::pools::{PoolKind, PoolUsage, record_acquire_error};
5
use crate::user::connection::TenantConnection;
6
use sqlx::postgres::PgPoolOptions;
7
use sqlx::types::Uuid;
8
use std::sync::Arc;
9
use std::time::Duration;
10
use tokio::sync::OnceCell;
11

            
12
/// Default idle life of a tenant pool, overridable via the
13
/// `userregistrytimeout` config key.
14
const DEFAULT_IDLE_SECS: u64 = 300;
15

            
16
/// How stale a tenant's quarantine status may be before it is re-read.
17
///
18
/// The status lives in the global directory and is written by the fleet
19
/// migrator in *another process*, so a warm pool here would otherwise keep
20
/// serving a database that has just been declared unusable — the registry is
21
/// per-process and nothing can invalidate it from outside. Re-reading on every
22
/// acquire would double the load on the admin pool (whose whole budget is 5);
23
/// re-reading on a short clock bounds the staleness instead, at one query per
24
/// tenant per interval.
25
const QUARANTINE_RECHECK: Duration = Duration::from_secs(30);
26

            
27
892440
async fn acquire_connection(
28
892440
    registry: &PoolRegistry,
29
892440
    user_id: Uuid,
30
892440
) -> Result<TenantConnection, DBError> {
31
892440
    let slot = match registry.touch(user_id)? {
32
837720
        Some(slot) => slot,
33
54720
        None => registry.install(user_id)?,
34
    };
35

            
36
892440
    if registry.claim_recheck(user_id, QUARANTINE_RECHECK)? {
37
        match routing(user_id).await {
38
            // A tenant quarantined mid-flight must stop being served, so this
39
            // drops the pool as well as refusing the request.
40
            Ok(route) if route.quarantined || route.disabled => {
41
                registry.forget(user_id, &slot)?;
42
                return Err(refusal(&route));
43
            }
44
            Ok(_) => {}
45
            Err(e) => {
46
                // The claim already advanced the clock; give it back so the
47
                // next caller retries rather than trusting a stale answer for
48
                // the rest of the interval.
49
                registry.release_recheck(user_id, QUARANTINE_RECHECK)?;
50
                return Err(e);
51
            }
52
        }
53
892440
    }
54

            
55
    // Cloning the handle pins the pool for the length of this request: an
56
    // eviction between here and `acquire` only un-registers it, so the caller
57
    // never races a close.
58
892440
    let tenant = match slot.get_or_try_init(|| build(registry, user_id)).await {
59
885600
        Ok(tenant) => Arc::clone(tenant),
60
        Err(e) => {
61
6840
            registry.forget(user_id, &slot)?;
62
6840
            return Err(e);
63
        }
64
    };
65

            
66
885600
    let conn = tenant.pool().acquire().await.map_err(|error| {
67
180
        record_acquire_error(PoolKind::Tenant, &error);
68
180
        DBError::Sqlx(error)
69
180
    })?;
70

            
71
    // The pool travels with the connection: releasing its permit here, while
72
    // the connection is still open, is what let the resident bound be exceeded.
73
885420
    Ok(TenantConnection::tenant(conn, tenant))
74
892440
}
75

            
76
/// The directory stores a database name; the DSN is composed here.
77
///
78
/// The residency permit is taken before connecting and moved into the
79
/// [`TenantPool`], so a build that fails or is cancelled returns it by dropping
80
/// it rather than leaving the slot to be reclaimed later.
81
54720
async fn build(registry: &PoolRegistry, user_id: Uuid) -> Result<Arc<TenantPool>, DBError> {
82
54720
    let permit = registry.reserve().await?;
83
54720
    let route = routing(user_id).await?;
84

            
85
    // Also here, not only on recheck: a *fresh* pool would otherwise be built
86
    // for a disabled user and served until the first recheck.
87
47880
    if route.quarantined || route.disabled {
88
        return Err(refusal(&route));
89
47880
    }
90

            
91
47880
    let url = crate::provision::dsn_for(&route.database_name)?;
92

            
93
47880
    let pool = PgPoolOptions::new()
94
47880
        .max_connections(TENANT_MAX_CONNECTIONS)
95
47880
        .idle_timeout(registry.idle_timeout())
96
47880
        .acquire_timeout(Duration::from_secs(10))
97
47880
        .connect(&url)
98
47880
        .await
99
47880
        .map_err(DBError::Sqlx)?;
100

            
101
47880
    Ok(Arc::new(TenantPool::new(pool, permit)))
102
54720
}
103

            
104
/// Where a tenant lives and whether it may currently be served.
105
struct Route {
106
    database_name: String,
107
    quarantined: bool,
108
    disabled: bool,
109
}
110

            
111
/// Not the same event, so not the same user-facing text.
112
fn refusal(route: &Route) -> DBError {
113
    if route.quarantined {
114
        DBError::TenantQuarantined
115
    } else {
116
        DBError::TenantDisabled
117
    }
118
}
119

            
120
54720
async fn routing(user_id: Uuid) -> Result<Route, DBError> {
121
54720
    let mut conn = crate::db::get_connection().await?;
122

            
123
54720
    let row = sqlx::query_file!("../server/sql/select/system/tenant_routing.sql", &user_id)
124
54720
        .fetch_optional(&mut *conn)
125
54720
        .await
126
54720
        .map_err(DBError::Sqlx)?
127
54720
        .ok_or(DBError::UnknownTenant)?;
128

            
129
47880
    Ok(Route {
130
47880
        database_name: row.database_name,
131
47880
        quarantined: row.quarantined_at.is_some(),
132
47880
        disabled: !row.verified,
133
47880
    })
134
54720
}
135

            
136
static POOL_REGISTRY: OnceCell<PoolRegistry> = OnceCell::const_new();
137

            
138
892620
async fn pool_registry() -> &'static PoolRegistry {
139
892620
    POOL_REGISTRY
140
51660
        .get_or_init(|| async move {
141
51660
            let timeout = match system_config("userregistrytimeout").await {
142
                Ok(Some(value)) => value.to_string().parse().unwrap_or(DEFAULT_IDLE_SECS),
143
                Ok(None) => DEFAULT_IDLE_SECS,
144
                Err(error) => {
145
51480
                    tracing::warn!("userregistrytimeout unreadable, using the default: {error:?}");
146
51480
                    DEFAULT_IDLE_SECS
147
                }
148
            };
149
51480
            PoolRegistry::new(Duration::from_secs(timeout))
150
103140
        })
151
892620
        .await
152
892440
}
153

            
154
892620
pub(in crate::user) async fn get_connection(user_id: Uuid) -> Result<TenantConnection, DBError> {
155
892620
    acquire_connection(pool_registry().await, user_id).await
156
892440
}
157

            
158
/// Connections of the registered tenant pools; none before the first request.
159
pub(in crate::user) fn usage() -> PoolUsage {
160
    let Some(registry) = POOL_REGISTRY.get() else {
161
        return PoolUsage::default();
162
    };
163
    registry.usage().unwrap_or_else(|error| {
164
        tracing::warn!("tenant pool usage unavailable: {error}");
165
        PoolUsage::default()
166
    })
167
}