Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ buzz-admin (operator CLI: relay membership + key generation)
buzz-test-client (integration test harness + manual CLI)
```

**Key architectural principle:** The relay is the single source of truth. `buzz-relay` orchestrates all subsystems by calling them directly — it imports `buzz-db`, `buzz-auth`, `buzz-pubsub`, `buzz-search`, `buzz-audit`, and `buzz-workflow`. However, those subsystems are isolated from each other: `buzz-workflow` never calls `buzz-pubsub`, `buzz-search` never calls `buzz-db`, etc. The one sanctioned exception is `buzz-audit`, which stores its chain through `buzz_db::AuditLog`. `buzz-audit` computes and checks the hashes; `AuditLog` owns the audit pool and the chain's appends and reads. Cross-subsystem coordination happens only through the relay. In multi-community mode, the relay also owns propagation of `TenantContext`; service crates should receive community-scoped inputs rather than independently deriving tenancy from client-controlled event tags.
**Key architectural principle:** The relay is the single source of truth. `buzz-relay` orchestrates all subsystems by calling them directly — it imports `buzz-db`, `buzz-auth`, `buzz-pubsub`, `buzz-search`, `buzz-audit`, and `buzz-workflow`. However, those subsystems are isolated from each other: `buzz-workflow` never calls `buzz-pubsub`, etc. The one sanctioned exception is `buzz-audit`, which stores its chain through `buzz_db::AuditLog`. `buzz-audit` computes and checks the hashes; `AuditLog` owns the audit pool and the chain's appends and reads. Every crate reaches Postgres only through `buzz-db`, except `buzz-push-gateway`, a separate service that builds its own pool. Cross-subsystem coordination happens only through the relay. In multi-community mode, the relay also owns propagation of `TenantContext`; service crates should receive community-scoped inputs rather than independently deriving tenancy from client-controlled event tags.

---

Expand Down Expand Up @@ -585,7 +585,8 @@ kind 30180 (custom emoji entries) until an operator runs the updated maintenance
script, which must happen before the emoji migration rollout.

**Key behaviors:**
- `SearchService::new(pool)` wraps a `PgPool`; `search(&SearchQuery)` runs a
- `SearchService::new(store)` wraps a `buzz_db::SearchStore`, which owns the
search pool and the FTS SQL (`buzz_db::search`); `search(&SearchQuery)` runs a
parameterized FTS query against the `events.search_tsv` GIN index and returns
`SearchResult` (candidate `SearchHit`s). Prefix-mode relevance (outside
profile search) ranks only the newest 1000 matches, which Postgres may read
Expand Down
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion crates/buzz-db/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ pub use store::{
event, feed, git_repo, group_discovery, leader_lock, media, membership_snapshot, moderation,
nip_fi_binding, operator_listener, partition, personal_read, pins, product_feedback, push,
reaction, read_state, relay_admin_actions, relay_invite, relay_members, relay_operators,
reminder, replaceable, search_backfill, search_outbox, storage_accounting, thread,
reminder, replaceable, search, search_backfill, search_outbox, storage_accounting, thread,
thread_window, user, user_deletion, user_deletion_fences, workflow,
};

Expand All @@ -124,6 +124,7 @@ pub use leader_lock::SessionLeader;
pub use nip_fi_binding::{NipFiBindingRecord, NipFiUnbind, RowCapExceeded};
pub use reaction::ReactionEventInsertOutcome;
pub use reminder::DueReminder;
pub use search::SearchStore;
pub use store::{ArtifactSnapshot, SnapshotDenied};

/// A value read from the database, with when its reading connection was
Expand Down
2 changes: 2 additions & 0 deletions crates/buzz-db/src/store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ pub mod relay_operators;
pub mod reminder;
/// Replaceable-event persistence and coordinate locking.
pub mod replaceable;
/// Postgres full-text message and profile search.
pub mod search;
/// Queuing events stored before the search index existed.
pub mod search_backfill;
/// The durable queue between event admission and the search index.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,81 @@
//!
//! See conformance row 50.

use sqlx::postgres::PgPoolOptions;
use sqlx::{PgPool, QueryBuilder, Row};
use uuid::Uuid;

use buzz_core::CommunityId;
use buzz_datastore_tracing::datastore_span;

use crate::error::SearchError;
use crate::{DbConfig, DbPoolStats, Result};

pub mod cancel;

/// Options for the search pool: every new connection's session
/// `statement_timeout` is lowered to the event-read deadline
/// ([`crate::event::READ_STATEMENT_TIMEOUT`]) unless it is already tighter.
/// Searches cancel their statement when abandoned (see [`cancel`]); this
/// bounds the ones a cancel cannot reach.
pub fn pool_options() -> PgPoolOptions {
PgPoolOptions::new().after_connect(|conn, _meta| {
Box::pin(crate::event::tighten_session_read_statement_timeout(conn))
})
}

/// Handle to Postgres full-text message and profile search, over its own
/// pool. Clone is cheap.
///
/// The search pool is separate from the serving pools, so slow searches
/// cannot take connections that event reads and writes need.
#[derive(Debug, Clone)]
pub struct SearchStore {
pool: PgPool,
}

impl SearchStore {
/// Build the search pool from [`pool_options`]: on the reader when
/// `config` has one, else the writer, with the writer's acquire timeout,
/// so a dead reader fails a search within the same bound. The pool
/// connects lazily: this never dials.
pub fn connect(config: &DbConfig) -> Result<Self> {
let url = config
.read_database_url
.as_deref()
.unwrap_or(&config.database_url);
let pool = pool_options()
.acquire_timeout(std::time::Duration::from_secs(config.acquire_timeout_secs))
.connect_lazy(url)?;
Ok(Self { pool })
}

/// Create a handle over an existing pool. For tests.
pub fn from_pool(pool: PgPool) -> Self {
Self { pool }
}

/// Pool utilisation, for the relay's pool metrics.
pub fn pool_stats(&self) -> DbPoolStats {
DbPoolStats::from_pool(&self.pool)
}

/// See [`search`].
pub async fn search(&self, query: &SearchQuery) -> Result<SearchResult> {
search(&self.pool, query).await
}

/// See [`search_profile_names`].
pub async fn search_profile_names(
&self,
community: CommunityId,
q: &str,
verified_by: Option<[u8; 32]>,
page: u32,
per_page: u32,
) -> Result<SearchResult> {
search_profile_names(&self.pool, community, q, verified_by, page, per_page).await
}
}

/// Channel-scope filter for a community-scoped FTS query.
///
Expand Down Expand Up @@ -188,7 +256,7 @@ pub struct ScoreParts {
/// A hit with the parts of its score.
#[derive(Debug, Clone)]
pub struct ScoredHit {
/// The hit, as [`SearchService::search`](crate::SearchService::search)
/// The hit, as `buzz_search::SearchService::search`
/// returns it.
pub hit: SearchHit,
/// How its rank was made.
Expand Down Expand Up @@ -316,17 +384,18 @@ fn push_tsquery(
}
/// The page a [`SearchQuery`] asks for, clamped the same way by every
/// backend.
pub(crate) struct PageBounds {
pub struct PageBounds {
/// 1-indexed page, at most [`PAGE_MAX`].
pub(crate) page: u32,
pub page: u32,
/// Hits per page: `per_page` clamped to `1..=PER_PAGE_MAX`, or the
/// default when it is 0.
pub(crate) per_page: u32,
pub per_page: u32,
/// Hits before this page.
pub(crate) offset: i64,
pub offset: i64,
}

pub(crate) fn page_bounds(query: &SearchQuery) -> PageBounds {
/// The page `query` asks for, clamped; see [`PageBounds`].
pub fn page_bounds(query: &SearchQuery) -> PageBounds {
let per_page = if query.per_page == 0 {
PER_PAGE_DEFAULT
} else {
Expand All @@ -340,7 +409,9 @@ pub(crate) fn page_bounds(query: &SearchQuery) -> PageBounds {
}
}

pub(crate) fn normalized_search_text(q: &str) -> Option<String> {
/// The search text every backend matches: trimmed, NUL bytes replaced, and
/// capped in length; `None` when nothing is left to search.
pub fn normalized_search_text(q: &str) -> Option<String> {
let trimmed = q.trim();
if trimmed.is_empty() {
return None;
Expand Down Expand Up @@ -381,7 +452,7 @@ pub(crate) fn normalized_search_text(q: &str) -> Option<String> {
/// `community_id = $ctx` is the first predicate and is non-negotiable. There
/// is no code path through this function that omits it.
#[datastore_span(name = "search", system = "postgresql", pool = "search")]
pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result<SearchResult, SearchError> {
pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result<SearchResult> {
let profile_only = query.kinds.as_deref() == Some(&[0][..]);
let Some(search_text) = normalized_search_text(&query.q) else {
return Ok(SearchResult {
Expand Down Expand Up @@ -538,7 +609,7 @@ pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result<SearchResult,

// Not a cached prepared statement: after five runs Postgres may switch a
// cached statement to a generic plan, which cannot see the tsquery.
let rows = crate::cancel::fetch_all(pool, conn, qb.build().persistent(false)).await?;
let rows = cancel::fetch_all(pool, conn, qb.build().persistent(false)).await?;

let mut hits = Vec::with_capacity(rows.len());
for row in rows {
Expand Down Expand Up @@ -605,7 +676,7 @@ pub async fn search_profile_names(
verified_by: Option<[u8; 32]>,
page: u32,
per_page: u32,
) -> Result<SearchResult, SearchError> {
) -> Result<SearchResult> {
let page = page.clamp(1, PAGE_MAX);
let Some(search_text) = normalized_search_text(q) else {
return Ok(SearchResult {
Expand Down Expand Up @@ -712,7 +783,7 @@ pub async fn search_profile_names(
people.person, ev.kind",
);

let rows = crate::cancel::fetch_all(pool, pool.acquire().await?, qb.build()).await?;
let rows = cancel::fetch_all(pool, pool.acquire().await?, qb.build()).await?;
let mut hits = Vec::with_capacity(rows.len());
for row in rows {
let id_bytes: Vec<u8> = row.try_get("id")?;
Expand Down Expand Up @@ -830,6 +901,22 @@ fn push_name_columns(qb: &mut QueryBuilder<sqlx::Postgres>, fields: &[&str]) {
mod tests {
use super::*;

#[tokio::test]
async fn search_pool_is_lazy_prefers_the_reader_and_bounds_acquire() {
// Unroutable per RFC 5737 TEST-NET-1: construction must not dial it.
let config = DbConfig {
read_database_url: Some("postgres://u:p@192.0.2.1:5432/none".to_owned()), // sadscan:disable np.postgres.1
..DbConfig::default()
};
let store = SearchStore::connect(&config).expect("lazy construction must not dial");
assert_eq!(store.pool.connect_options().get_host(), "192.0.2.1");
assert_eq!(
store.pool.options().get_acquire_timeout(),
std::time::Duration::from_secs(config.acquire_timeout_secs),
"a dead reader must fail a search within the writer's acquire bound"
);
}

#[test]
fn normalized_search_text_trims_and_rejects_empty() {
assert_eq!(
Expand All @@ -854,3 +941,36 @@ mod tests {
assert_eq!(cleaned.chars().count(), SEARCH_TEXT_MAX_CHARS);
}
}

#[cfg(test)]
mod postgres_tests {
use super::*;

/// Every connection the production constructor opens gets the read
/// statement timeout, which bounds a search that a cancel cannot reach.
#[tokio::test]
#[ignore = "requires Postgres"]
async fn search_store_bounds_every_statement() {
let store = SearchStore::connect(&DbConfig {
database_url: crate::test_support::database_url(),
..DbConfig::default()
})
.expect("build search store");
let mut conns = Vec::new();
for _ in 0..2 {
let mut conn = store.pool.acquire().await.expect("search connection");
let timeout: String = sqlx::query_scalar("SHOW statement_timeout")
.fetch_one(&mut *conn)
.await
.expect("read statement_timeout");
assert_eq!(
timeout,
crate::event::READ_STATEMENT_TIMEOUT,
"every search connection is bounded"
);
conns.push(conn);
}
drop(conns);
store.pool.close().await;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
//! connection instead. The abandoned connection stays checked out until the
//! task is done, so its backend cannot start another caller's statement
//! before the signal lands. A cancel that cannot reach the backend leaves the
//! statement to the pool's statement timeout ([`crate::pool_options`]).
//! statement to the pool's statement timeout ([`super::pool_options`]).

use std::time::Duration;

Expand Down Expand Up @@ -121,7 +121,7 @@ async fn cancel(pool: &PgPool, (pid, started_us): (i32, i64)) -> &'static str {
let mut conn = match tokio::time::timeout(CANCEL_ACQUIRE_TIMEOUT, pool.acquire()).await {
Ok(Ok(conn)) => conn,
Ok(Err(e)) => {
tracing::warn!(error_kind = %buzz_db::error::sqlx_error_kind(&e), pid, "search cancel could not get a connection");
tracing::warn!(error_kind = %crate::error::sqlx_error_kind(&e), pid, "search cancel could not get a connection");
return "error";
}
Err(_) => return "pool_busy",
Expand All @@ -135,7 +135,7 @@ async fn cancel(pool: &PgPool, (pid, started_us): (i32, i64)) -> &'static str {
Ok(None) => elsewhere.push(conn),
Ok(Some(signalled)) => return signal_outcome(signalled),
Err(e) => {
tracing::warn!(error_kind = %buzz_db::error::sqlx_error_kind(&e), pid, "search cancel failed");
tracing::warn!(error_kind = %crate::error::sqlx_error_kind(&e), pid, "search cancel failed");
return "error";
}
}
Expand Down
Loading
Loading