Skip to content

Commit 27378c8

Browse files
refactor(db): move usage store ownership
Signed-off-by: tornquist <[email protected]>
1 parent 8d3042d commit 27378c8

3 files changed

Lines changed: 258 additions & 175 deletions

File tree

‎crates/buzz-db/src/lib.rs‎

Lines changed: 3 additions & 169 deletions
Original file line numberDiff line numberDiff line change
@@ -93,11 +93,12 @@ pub use error::{DbError, Result};
9393
pub use event::{EventQuery, DEFAULT_MAX_PAGE_LIMIT};
9494
pub use reaction::ReactionEventInsertOutcome;
9595
pub use reminder::DueReminder;
96+
pub use usage::UsageMetricsLeader;
9697

9798
use buzz_datastore_tracing::datastore_span;
9899
use chrono::{DateTime, Utc};
99-
use sqlx::postgres::{PgConnection, PgPoolOptions};
100-
use sqlx::{Connection, PgPool, QueryBuilder};
100+
use sqlx::postgres::PgPoolOptions;
101+
use sqlx::{PgPool, QueryBuilder};
101102
use std::time::Duration;
102103
use uuid::Uuid;
103104

@@ -513,27 +514,6 @@ pub struct DbPoolStats {
513514
pub max: u32,
514515
}
515516

516-
/// Owns the detached Postgres session holding the relay usage-metrics advisory lock.
517-
///
518-
/// The connection deliberately does not return to the main pool: session advisory
519-
/// locks must remain bound to this exact physical connection, and the poller
520-
/// pings it before each leader-only collection tick.
521-
pub struct UsageMetricsLeader {
522-
connection: PgConnection,
523-
}
524-
525-
impl UsageMetricsLeader {
526-
/// Returns whether the lock-owning session is still reachable.
527-
///
528-
/// Bounded to 5 seconds — a blackholed connection (no RST) would otherwise
529-
/// stall the entire poller tick until the OS TCP timeout.
530-
pub async fn is_live(&mut self) -> bool {
531-
tokio::time::timeout(std::time::Duration::from_secs(5), self.connection.ping())
532-
.await
533-
.is_ok_and(|r| r.is_ok())
534-
}
535-
}
536-
537517
/// Configuration for the Postgres connection pool.
538518
#[derive(Debug, Clone)]
539519
pub struct DbConfig {
@@ -1013,32 +993,6 @@ impl Db {
1013993
})
1014994
}
1015995

1016-
/// Try to acquire the detached session advisory lock for relay usage metrics.
1017-
///
1018-
/// The returned guard owns the exact connection that acquired the lock. It is
1019-
/// detached from the shared pool so a stable leader neither returns a locked
1020-
/// session to other callers nor permanently consumes a pool slot. Dropping the
1021-
/// guard closes the connection and releases the session-scoped lock.
1022-
#[datastore_span(name = "try_lock_usage_metrics", system = "postgresql")]
1023-
pub async fn try_lock_usage_metrics(
1024-
&self,
1025-
lock_key: i64,
1026-
) -> Result<Option<UsageMetricsLeader>> {
1027-
let mut connection =
1028-
observability::acquire(&self.pool, observability::PoolRole::Writer).await?;
1029-
let acquired = sqlx::query_scalar::<_, bool>("SELECT pg_try_advisory_lock($1)")
1030-
.bind(lock_key)
1031-
.fetch_one(&mut *connection)
1032-
.await?;
1033-
if acquired {
1034-
Ok(Some(UsageMetricsLeader {
1035-
connection: connection.detach(),
1036-
}))
1037-
} else {
1038-
Ok(None)
1039-
}
1040-
}
1041-
1042996
/// List reports for the deployment-global read-only admin plane.
1043997
#[allow(clippy::too_many_arguments)]
1044998
#[datastore_span(name = "admin_list_reports", system = "postgresql")]
@@ -1094,74 +1048,6 @@ impl Db {
10941048
admin_moderation::get_feedback(&self.pool, id).await
10951049
}
10961050

1097-
/// Return total number of communities on this relay.
1098-
#[datastore_span(name = "usage_community_count", system = "postgresql")]
1099-
pub async fn usage_community_count(&self) -> Result<i64> {
1100-
usage::community_count(&self.pool).await
1101-
}
1102-
1103-
/// Return per-community user counts split by human/agent.
1104-
#[datastore_span(name = "usage_user_counts", system = "postgresql")]
1105-
pub async fn usage_user_counts(&self) -> Result<Vec<usage::CommunityUserCounts>> {
1106-
usage::user_counts(&self.pool).await
1107-
}
1108-
1109-
/// Return per-community channel counts by type.
1110-
#[datastore_span(name = "usage_channel_counts", system = "postgresql")]
1111-
pub async fn usage_channel_counts(&self) -> Result<Vec<usage::CommunityChannelCount>> {
1112-
usage::channel_counts(&self.pool).await
1113-
}
1114-
1115-
/// Return per-community kind=9 message counts.
1116-
#[datastore_span(name = "usage_message_counts", system = "postgresql")]
1117-
pub async fn usage_message_counts(&self) -> Result<Vec<usage::CommunityMessageCount>> {
1118-
usage::message_counts(&self.pool).await
1119-
}
1120-
1121-
/// Return per-community relay-member counts by role.
1122-
#[datastore_span(name = "usage_relay_member_counts", system = "postgresql")]
1123-
pub async fn usage_relay_member_counts(&self) -> Result<Vec<usage::CommunityMemberCount>> {
1124-
usage::relay_member_counts(&self.pool).await
1125-
}
1126-
1127-
/// Return per-community workflow counts by status.
1128-
#[datastore_span(name = "usage_workflow_counts", system = "postgresql")]
1129-
pub async fn usage_workflow_counts(&self) -> Result<Vec<usage::CommunityWorkflowCount>> {
1130-
usage::workflow_counts(&self.pool).await
1131-
}
1132-
1133-
/// Return per-community git-repo counts.
1134-
#[datastore_span(name = "usage_git_repo_counts", system = "postgresql")]
1135-
pub async fn usage_git_repo_counts(&self) -> Result<Vec<usage::CommunityGitRepoCount>> {
1136-
usage::git_repo_counts(&self.pool).await
1137-
}
1138-
1139-
/// Return per-community distinct active-user counts for a given SQL interval.
1140-
///
1141-
/// `interval_sql` must be a trusted literal such as `"1 day"` or `"7 days"`.
1142-
#[datastore_span(name = "usage_active_user_counts", system = "postgresql")]
1143-
pub async fn usage_active_user_counts(
1144-
&self,
1145-
interval_sql: &'static str,
1146-
) -> Result<Vec<usage::CommunityActiveUsers>> {
1147-
usage::active_user_counts(&self.pool, interval_sql).await
1148-
}
1149-
1150-
/// Return per-community active-channel counts for a given SQL interval.
1151-
#[datastore_span(name = "usage_active_channel_counts", system = "postgresql")]
1152-
pub async fn usage_active_channel_counts(
1153-
&self,
1154-
interval_sql: &'static str,
1155-
) -> Result<Vec<usage::CommunityActiveChannels>> {
1156-
usage::active_channel_counts(&self.pool, interval_sql).await
1157-
}
1158-
1159-
/// Return all community id → host mappings.
1160-
#[datastore_span(name = "usage_community_hosts", system = "postgresql")]
1161-
pub async fn usage_community_hosts(&self) -> Result<Vec<usage::CommunityHost>> {
1162-
usage::community_hosts(&self.pool).await
1163-
}
1164-
11651051
/// Return the shared durable whole-community deletion adapter.
11661052
pub fn deletion_store(&self) -> deletion::DeletionStore {
11671053
deletion::DeletionStore::new(self.pool.clone())
@@ -1340,7 +1226,6 @@ impl Db {
13401226
mod tests {
13411227
use super::*;
13421228
use buzz_core::CommunityId;
1343-
use sqlx::postgres::PgPoolOptions;
13441229
use sqlx::PgPool;
13451230
use uuid::Uuid;
13461231

@@ -1677,57 +1562,6 @@ mod tests {
16771562
assert_eq!(watermark.1, c.id.as_bytes().as_slice());
16781563
}
16791564

1680-
#[tokio::test]
1681-
#[ignore = "requires Postgres"]
1682-
async fn test_usage_metrics_lock_has_single_owner_and_releases_on_drop() {
1683-
// Use a private scratch database — not the shared TEST_DATABASE_URL.
1684-
// Postgres advisory locks are per-database; hardcoding the production
1685-
// USAGE_METRICS_LOCK_KEY (0x4255_5A5A_4D45_5452) on the shared test DB
1686-
// races any live buzz-relay on the same database (see #3619).
1687-
let admin_url = std::env::var("TEST_DATABASE_URL").unwrap_or_else(|_| TEST_DB_URL.into());
1688-
let admin = PgPoolOptions::new()
1689-
.max_connections(1)
1690-
.connect(&admin_url)
1691-
.await
1692-
.expect("connect admin to create scratch db");
1693-
let (pool, scratch_name) = create_scratch_db(&admin, "usage_metrics_lock").await;
1694-
let first = Db::from_pool(pool.clone());
1695-
let second = Db::from_pool(pool.clone());
1696-
// Same key as production (`buzz-relay` USAGE_METRICS_LOCK_KEY) — safe here
1697-
// because the scratch DB is empty of other holders.
1698-
let key = 0x4255_5A5A_4D45_5452;
1699-
1700-
let mut leader = first
1701-
.try_lock_usage_metrics(key)
1702-
.await
1703-
.expect("first lock attempt")
1704-
.expect("first database handle becomes leader");
1705-
assert!(leader.is_live().await, "lock owner remains reachable");
1706-
assert!(
1707-
second
1708-
.try_lock_usage_metrics(key)
1709-
.await
1710-
.expect("second lock attempt")
1711-
.is_none(),
1712-
"another session cannot become leader while the guard exists"
1713-
);
1714-
1715-
drop(leader);
1716-
assert!(
1717-
second
1718-
.try_lock_usage_metrics(key)
1719-
.await
1720-
.expect("lock attempt after leader drop")
1721-
.is_some(),
1722-
"dropping the detached session releases its advisory lock"
1723-
);
1724-
1725-
// Release any remaining session state before DROP DATABASE.
1726-
drop(first);
1727-
drop(second);
1728-
drop_scratch_db(&admin, pool, &scratch_name).await;
1729-
}
1730-
17311565
// ---- Read-replica routing ------------------------------------------------
17321566
//
17331567
// These tests pin the routing contract of `Db::read()` and the two routed

0 commit comments

Comments
 (0)