diff --git a/.env.example b/.env.example index b4e7827944..be1c6308ce 100644 --- a/.env.example +++ b/.env.example @@ -183,6 +183,12 @@ BUZZ_PUSH_GATEWAY_DELIVERY_URL=https://push.buzz.xyz/v1/deliveries/apns # measured_at as already recorded. # BUZZ_STORAGE_USAGE_URL=https://kgoose.example/cash-app/goose/v1/buzz/storage-usage/record +# Optional OpenSearch message index; see docs/opensearch-search-deployment.md. +# BUZZ_OPENSEARCH_URL=http://localhost:9200 +# BUZZ_OPENSEARCH_USERNAME= +# BUZZ_OPENSEARCH_PASSWORD= +# BUZZ_OPENSEARCH_PREVIEW=true + # Optional relay-owned KLIPY key. When set, NIP-11 advertises GIF search and # authenticated desktop clients use this relay as the metadata/search proxy. # Keep the real value in your deployment's secret manager; never commit it. diff --git a/.github/workflows/_ci-relay.yml b/.github/workflows/_ci-relay.yml index 7d62a2044b..8954ebbe85 100644 --- a/.github/workflows/_ci-relay.yml +++ b/.github/workflows/_ci-relay.yml @@ -206,7 +206,18 @@ jobs: PGSCHEMA_PLAN_PORT: "5432" PGSCHEMA_PLAN_USER: buzz PGSCHEMA_PLAN_PASSWORD: buzz_dev + BUZZ_TEST_OPENSEARCH_URL: http://localhost:9200 steps: + # Started without waiting, so its boot overlaps the setup steps below. + # Not a service container: those block the job until they are healthy. + - name: Start OpenSearch + run: | + docker run --detach --name opensearch --publish 9200:9200 \ + --env discovery.type=single-node \ + --env DISABLE_SECURITY_PLUGIN=true \ + --env DISABLE_INSTALL_DEMO_CONFIG=true \ + --env OPENSEARCH_JAVA_OPTS="-Xms512m -Xmx512m" \ + opensearchproject/opensearch:2.19.3@sha256:e96cc6ae1500a073d973c0906f30f7cf4d9c461f32f855f9242a2da933660cdd - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 # pgschema has no --version; --help exits 0 once Hermit has fetched it. @@ -239,6 +250,16 @@ jobs: path: target/ci - name: Restore relay executable permission run: chmod +x ./target/ci/buzz-relay + - name: Wait for OpenSearch + run: | + for _ in $(seq 1 60); do + if curl -fsS "$BUZZ_TEST_OPENSEARCH_URL/_cluster/health?wait_for_status=yellow&timeout=1s" >/dev/null; then + exit 0 + fi + sleep 2 + done + docker logs opensearch | tail -50 + exit 1 - name: PostgreSQL-backed tests env: BUZZ_POSTGRES_ADMIN_URL: postgres://buzz:${{ env.BUZZ_TEST_POSTGRES_PASSWORD }}@localhost:5432/postgres diff --git a/Cargo.lock b/Cargo.lock index 45a79b7fba..418d921e88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1554,7 +1554,13 @@ dependencies = [ "buzz-core", "buzz-datastore-tracing", "buzz-db", + "chrono", + "hex", "metrics", + "nostr 0.44.7", + "opensearch", + "rand 0.10.1", + "serde_json", "sqlx", "thiserror 2.0.18", "tokio", @@ -2618,7 +2624,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccc2776f0c61eca1ca32528f85548abd1a4be8fb53d1b21c013e4f18da1e7090" dependencies = [ "data-encoding", - "syn 1.0.109", + "syn 2.0.117", ] [[package]] @@ -3501,8 +3507,8 @@ dependencies = [ "libc", "log", "rustversion", - "windows-link 0.1.3", - "windows-result 0.3.4", + "windows-link 0.2.1", + "windows-result 0.4.1", ] [[package]] @@ -4159,7 +4165,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core 0.61.2", + "windows-core 0.62.2", ] [[package]] @@ -6959,6 +6965,26 @@ dependencies = [ "uuid", ] +[[package]] +name = "opensearch" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af6815a23449a0860c8fe049a828c3589d3ad56d3b5875d0d1f340d1291871e" +dependencies = [ + "base64 0.22.1", + "bytes", + "dyn-clone", + "lazy_static", + "percent-encoding", + "reqwest 0.13.4", + "rustc_version", + "serde", + "serde_json", + "serde_with", + "url", + "void", +] + [[package]] name = "openssl" version = "0.10.80" @@ -11476,6 +11502,12 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" + [[package]] name = "vtparse" version = "0.6.2" @@ -12242,8 +12274,8 @@ dependencies = [ "log", "serde", "thiserror 2.0.18", - "windows 0.61.3", - "windows-core 0.61.2", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 912e33c495..72313f1864 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -109,6 +109,7 @@ jsonwebtoken = { version = "10.4.0", default-features = false, features = ["aws_ # HTTP client (webhook delivery) reqwest = { version = "0.13", features = ["json", "rustls", "stream"], default-features = false } +opensearch = { version = "2.4", default-features = false, features = ["rustls-tls"] } # Cryptography sha2 = "0.11" diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index 07e2b8f387..61f3efa6c4 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -99,7 +99,7 @@ pub use store::{ git_repo, 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, storage_accounting, thread, thread_window, user, user_deletion, + replaceable, search_outbox, storage_accounting, thread, thread_window, user, user_deletion, user_deletion_fences, workflow, }; diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 560a1f031e..10efbae978 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -47,6 +47,26 @@ pub(crate) async fn run_migrations_through(pool: &PgPool, target: i64) -> Result .await } +/// Migrations that only add a tenant table, applied after the fence +/// retirement (0090). Append each new one here. +#[cfg(test)] +const TENANT_TABLE_MIGRATIONS_AFTER_FENCE_RETIREMENT: [i64; 1] = [106]; + +/// Create the tenant tables added since the fence retirement, without +/// recording their migrations. For tests that stop before the retirement but +/// exercise the whole deletion catalog, and never migrate further. +#[cfg(test)] +pub(crate) async fn create_tenant_tables_added_after_fence_retirement(pool: &PgPool) -> Result<()> { + for version in TENANT_TABLE_MIGRATIONS_AFTER_FENCE_RETIREMENT { + let migration = MIGRATOR + .iter() + .find(|migration| migration.version == version) + .ok_or_else(|| crate::DbError::InvalidData(format!("no migration {version}")))?; + sqlx::raw_sql(migration.sql.as_str()).execute(pool).await?; + } + Ok(()) +} + async fn run_migrations_locked(conn: &mut PgConnection) -> Result<()> { reject_legacy_nip_rs_cardinality_ambiguity(conn).await?; for (version, doc, indexes) in INLINE_INDEX_BUILDS { @@ -1036,7 +1056,11 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 105); + assert_eq!(migrations.len(), 106); + assert_eq!(migrations[105].version, 106); + assert!( + strip_sql_comments(migrations[105].sql.as_str()).contains("CREATE TABLE search_outbox") + ); assert_eq!(migrations[104].version, 105); assert!(strip_sql_comments(migrations[104].sql.as_str()) .contains("ADD COLUMN finished BOOLEAN NOT NULL DEFAULT true;")); @@ -1709,6 +1733,7 @@ mod postgres_tests { "nip_fi_profile_heads", "media_uploaders", "media_publications", + "search_outbox", ]; for table in crate::deletion::EXPECTED_SCOPED_TABLES .iter() @@ -3501,6 +3526,7 @@ mod postgres_tests { "user_deletion_fences", "workflow_runs", "push_gateway_installations", + "search_outbox", ] { assert_eq!( columns(&desired, table).await, @@ -4469,11 +4495,22 @@ mod postgres_tests { .validate_serving_catalog() .await .expect("new runtime must accept pre-retirement catalog"); + // Deletion needs every tenant table this binary purges, and tables + // added after the retirement are not there yet. + let drift = store + .validate_catalog() + .await + .expect_err("deletion refuses a catalog missing later tenant tables") + .to_string(); + assert!( + drift.contains("(missing=search_outbox, unknown=)"), + "deletion must accept the pre-retirement fences: {drift}" + ); + run_migrations(&pool).await.expect("apply all migrations"); store .validate_catalog() .await - .expect("deletion must accept pre-retirement catalog"); - run_migrations(&pool).await.expect("apply all migrations"); + .expect("deletion accepts the migrated catalog"); let fence_triggers: i64 = sqlx::query_scalar( "SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal AND tgname LIKE 'community_write_fence_%'", ) @@ -4545,10 +4582,17 @@ mod postgres_tests { .validate_serving_catalog() .await .expect("new code must boot before the drop"); - store + // Deletion needs every tenant table this binary purges, and tables + // added after the retirement are not there yet. + let drift = store .validate_catalog() .await - .expect("deletion must accept the catalog before the drop"); + .expect_err("deletion refuses a catalog missing later tenant tables") + .to_string(); + assert!( + drift.contains("(missing=search_outbox, unknown=)"), + "deletion must accept the catalog before the drop: {drift}" + ); run_migrations(&pool).await.expect("apply all migrations"); assert_eq!(present(&pool).await, (false, false)); store diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index c36fa754d1..04d5b723f3 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -120,6 +120,7 @@ pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ "relay_invites", "relay_members", "scheduled_workflow_fires", + "search_outbox", "thread_metadata", "users", "workflow_approvals", @@ -161,7 +162,6 @@ pub const PENDING_SCOPED_TABLES: &[&str] = &[ "identity_retirement_holds", "identity_retirement_workflows", "search_backfill", - "search_outbox", ]; /// Tenant tables an expand migration may add between a deletion's approval @@ -205,6 +205,7 @@ pub const PURGE_SCOPED_TABLES: &[&str] = &[ "scheduled_workflow_fires", "workflow_runs", "push_wake_outbox", + "search_outbox", "join_policy_acceptances", "media_uploaders", "media_publications", @@ -4867,6 +4868,9 @@ pub(crate) mod postgres_tests { crate::migration::run_migrations_through(&db.pool, 89) .await .expect("migrate with fence objects present"); + crate::migration::create_tenant_tables_added_after_fence_retirement(&db.pool) + .await + .expect("tenant tables added since"); let store = db.deletion_store(); let community = db .ensure_configured_community("optional-fences.example") @@ -5012,6 +5016,9 @@ DROP FUNCTION community_deletion_lock_key(UUID); crate::migration::run_migrations_through(&db.pool, 86) .await .expect("phase-one schema"); + crate::migration::create_tenant_tables_added_after_fence_retirement(&db.pool) + .await + .expect("tenant tables added since"); let community = db .ensure_configured_community("optional-guards.example") .await @@ -9708,6 +9715,69 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); (db, store, scratch) } + /// Once a community is fenced for deletion, admission refuses its writes + /// (and so its outbox rows) and claims skip it; the purge removes its + /// outbox rows and keeps another community's. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn search_outbox_is_fenced_and_purged() { + let (db, store) = store().await; + crate::search_outbox::enable(&db.pool) + .await + .expect("enable outbox"); + let (request, inventory) = inventoried_request(&db, &store).await; + let community = request.community_id; + let bystander = db + .ensure_configured_community(&format!("bystander-{}.example", Uuid::new_v4().simple())) + .await + .expect("bystander community") + .id; + let keys = nostr::Keys::generate(); + let message = |content: &str| { + nostr::EventBuilder::new(nostr::Kind::Custom(9), content) + .sign_with_keys(&keys) + .expect("sign") + }; + for owner in [community, bystander] { + db.insert_event(owner, &message("queued"), None) + .await + .expect("insert"); + } + let queued = |owner: CommunityId| { + let pool = db.pool.clone(); + async move { + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM search_outbox WHERE community_id = $1", + ) + .bind(owner.as_uuid()) + .fetch_one(&pool) + .await + .expect("count outbox rows") + } + }; + + let token = fence_and_drain(&store, &request, &inventory).await; + db.insert_event(community, &message("after fence"), None) + .await + .expect_err("a fenced community admits no writes"); + assert_eq!(queued(community).await, 1); + let batch = crate::search_outbox::claim_batch(&db.pool, 10, &[]) + .await + .expect("claim") + .expect("the bystander's batch"); + assert_eq!( + batch.community(), + bystander, + "claims skip a fenced community" + ); + drop(batch); + + let deleted = store.purge_postgres(&token).await.expect("purge postgres"); + assert_eq!(deleted.get("search_outbox"), Some(&1)); + assert_eq!(queued(community).await, 0); + assert_eq!(queued(bystander).await, 1); + } + /// Approve, claim, fence, drain and remove bindings, leaving the request /// ready for `purge_postgres`. async fn fence_and_drain( diff --git a/crates/buzz-db/src/store/event_follow_up.rs b/crates/buzz-db/src/store/event_follow_up.rs index b649d80b11..175ae99ec5 100644 --- a/crates/buzz-db/src/store/event_follow_up.rs +++ b/crates/buzz-db/src/store/event_follow_up.rs @@ -1,11 +1,14 @@ //! App-owned follow-up work for a newly inserted `events` row. //! -//! Two pieces of work follow every durable event insert: +//! Three pieces of work follow every durable event insert: //! //! - **Push match enqueue.** Eligible event IDs and signed timestamps are staged //! in memory. Commit submits them to a bounded best-effort worker using a //! dedicated connection. //! Push errors, delays, overload, and shutdown can drop wakes, never messages. +//! - **Search outbox.** A searchable event queues a durable `search_outbox` +//! row in the same transaction when search indexing is enabled (see +//! [`crate::search_outbox`]). //! - **Channel TTL refresh.** A channel-scoped event pushes its ephemeral //! channel's `ttl_deadline` forward. [`AdmittedTx`] records the channel and //! runs the refresh as the last statement before COMMIT (see @@ -40,8 +43,8 @@ const SQLSTATE_LOCK_NOT_AVAILABLE: &str = "55P03"; /// /// Call only when the INSERT affected a row, after releasing any savepoint /// that may roll it back. `created_at` must be the signed timestamp bound by -/// the INSERT, not receipt time. Stages push work for after commit and records -/// TTL work. +/// the INSERT, not receipt time. Stages push work for after commit, queues the +/// search outbox row, and records TTL work. pub(crate) async fn after_admitted_insert( tx: &mut AdmittedTx, event_id: &[u8], @@ -50,6 +53,7 @@ pub(crate) async fn after_admitted_insert( channel_id: Option, ) -> Result<()> { tx.record_push_event(event_id, created_at, kind); + crate::search_outbox::enqueue_in_transaction(tx, event_id, created_at, kind).await?; tx.record_channel_event(channel_id, kind); Ok(()) } diff --git a/crates/buzz-db/src/store/mod.rs b/crates/buzz-db/src/store/mod.rs index f2f94dce93..4345416f4c 100644 --- a/crates/buzz-db/src/store/mod.rs +++ b/crates/buzz-db/src/store/mod.rs @@ -84,6 +84,10 @@ pub mod relay_operators; pub mod reminder; /// Replaceable-event persistence and coordinate locking. pub mod replaceable; +/// The durable queue between event admission and the search index. +pub mod search_outbox; +#[cfg(test)] +mod search_outbox_postgres_tests; /// Durable completed snapshots from the isolated media-storage worker. pub mod storage_accounting; /// Thread metadata persistence. diff --git a/crates/buzz-db/src/store/search_outbox.rs b/crates/buzz-db/src/store/search_outbox.rs new file mode 100644 index 0000000000..ef2efb6d03 --- /dev/null +++ b/crates/buzz-db/src/store/search_outbox.rs @@ -0,0 +1,286 @@ +//! The search outbox: the durable queue between event admission and the +//! search index. +//! +//! When [`enable`] has been called (the relay does so when it is configured +//! with an OpenSearch address), every admitted insert of a +//! [`SEARCHABLE_KINDS`] event writes a `search_outbox` row in the same +//! transaction, so a stored message always has its index change queued and a +//! rolled-back write never does. The write makes no call to the search +//! engine. +//! +//! The indexer re-reads `events` for every row it claims, so duplicate or +//! out-of-order rows for one event are harmless. + +use std::sync::atomic::{AtomicBool, Ordering}; + +use buzz_core::{media::EDIT_GOVERNED_KINDS, CommunityId}; +use chrono::{DateTime, Utc}; +use sqlx::{PgPool, Row}; +use uuid::Uuid; + +use crate::{AdmittedTx, Result}; + +/// Event kinds the search index holds; no other kind is ever queued. They +/// are the message kinds an edit can replace, so the list has one owner. +pub const SEARCHABLE_KINDS: [i32; EDIT_GOVERNED_KINDS.len()] = { + let mut kinds = [0; EDIT_GOVERNED_KINDS.len()]; + let mut i = 0; + while i < kinds.len() { + kinds[i] = EDIT_GOVERNED_KINDS[i] as i32; + i += 1; + } + kinds +}; + +/// Communities a claim may pass over because their deletion fenced them +/// between candidate selection and admission, or another worker holds all +/// their rows. +const CLAIM_COMMUNITY_CANDIDATES: usize = 8; + +static ENABLED: AtomicBool = AtomicBool::new(false); + +/// Start writing outbox rows on admission, for the life of the process. +/// +/// Process-wide because the outbox follows every event insert path. Call it +/// once at startup, before serving writes, when a search index is configured. +/// Fails, leaving the outbox off, if migrations have not created the table: +/// enabled without it, every searchable insert would fail. +pub async fn enable(pool: &PgPool) -> Result<()> { + let exists: bool = sqlx::query_scalar("SELECT to_regclass('public.search_outbox') IS NOT NULL") + .fetch_one(pool) + .await?; + if !exists { + return Err(crate::DbError::InvalidData( + "the search_outbox table is missing; run migrations before enabling search indexing" + .into(), + )); + } + ENABLED.store(true, Ordering::Relaxed); + Ok(()) +} + +/// Queue `event_id` for indexing in the admitted transaction that inserted it. +pub(crate) async fn enqueue_in_transaction( + tx: &mut AdmittedTx, + event_id: &[u8], + created_at: DateTime, + kind: i32, +) -> Result<()> { + if !ENABLED.load(Ordering::Relaxed) || !SEARCHABLE_KINDS.contains(&kind) { + return Ok(()); + } + let community = tx.community(); + sqlx::query( + "INSERT INTO search_outbox (community_id, event_id, event_created_at) VALUES ($1, $2, $3)", + ) + .bind(community.as_uuid()) + .bind(event_id) + .bind(created_at) + .execute(tx.conn()) + .await?; + Ok(()) +} + +/// The current state of a queued event, as the index should hold it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SearchDocument { + /// Event id. + pub event_id: [u8; 32], + /// Event kind. + pub kind: i32, + /// Author public key. + pub pubkey: [u8; 32], + /// Channel, for channel-scoped events. + pub channel_id: Option, + /// Signed creation time. + pub created_at: DateTime, + /// Message text. + pub content: String, + /// The channel's type (`stream`, `forum`, `dm`, ...), when it has one. + pub channel_type: Option, + /// Whether the author is an agent with an owner. + pub author_is_agent: bool, + /// Root of the thread the event replies in, if it is a reply. + pub thread_root: Option<[u8; 32]>, + /// Hex public keys the event mentions. + pub mentions: Vec, +} + +/// Rows claimed for one community, with the current state of their events. +/// +/// Holds an admitted transaction, so the community cannot be fenced for +/// deletion while the batch is being indexed. Dropping the batch without +/// [`SearchOutboxBatch::complete`] rolls back and leaves the rows queued. +#[must_use = "dropping a batch leaves its rows queued; call complete()"] +pub struct SearchOutboxBatch { + tx: AdmittedTx, + row_ids: Vec, + /// Events to write to the index. + pub documents: Vec, + /// Queued events that are gone, deleted or not searchable: their + /// documents must be removed from the index. + pub removed: Vec<[u8; 32]>, +} + +impl SearchOutboxBatch { + /// The community every row in the batch belongs to. + pub fn community(&self) -> CommunityId { + self.tx.community() + } + + /// Delete the claimed rows and commit. Call once the index holds the + /// batch. + pub async fn complete(mut self) -> Result<()> { + let community = self.tx.community(); + sqlx::query("DELETE FROM search_outbox WHERE community_id = $1 AND id = ANY($2)") + .bind(community.as_uuid()) + .bind(&self.row_ids) + .execute(self.tx.conn()) + .await?; + self.tx.commit().await + } +} + +/// Claim up to `limit` of the oldest queued rows of one community not in +/// `skip`, skipping rows another worker holds, and read their events' current +/// state. +/// +/// Returns `None` when no other active community has unclaimed rows. +pub async fn claim_batch( + pool: &PgPool, + limit: i64, + skip: &[CommunityId], +) -> Result> { + let mut refused: Vec = skip.iter().map(|community| *community.as_uuid()).collect(); + for _ in 0..CLAIM_COMMUNITY_CANDIDATES { + // Exclude fenced communities so they cannot occupy the queue head. + let candidate: Option = sqlx::query_scalar( + "SELECT o.community_id FROM search_outbox o \ + JOIN communities c ON c.id = o.community_id \ + WHERE c.deletion_state = 'active' AND c.deleted_at IS NULL \ + AND o.community_id <> ALL($1) \ + ORDER BY o.created_at LIMIT 1", + ) + .bind(&refused) + .fetch_optional(pool) + .await?; + let Some(id) = candidate else { + return Ok(None); + }; + let community = CommunityId::from_uuid(id); + let Some(mut tx) = crate::begin_community_sweep_transaction( + pool, + community, + crate::observability::WriterOperation::Maintenance, + ) + .await? + else { + refused.push(id); + continue; + }; + let rows = sqlx::query( + "SELECT id, event_id, event_created_at FROM search_outbox \ + WHERE community_id = $1 \ + ORDER BY created_at \ + FOR UPDATE SKIP LOCKED \ + LIMIT $2", + ) + .bind(community.as_uuid()) + .bind(limit) + .fetch_all(tx.conn()) + .await?; + if rows.is_empty() { + // Another worker holds every row of this community. + refused.push(id); + continue; + } + let mut row_ids = Vec::with_capacity(rows.len()); + let mut queued = std::collections::BTreeMap::<[u8; 32], DateTime>::new(); + for row in &rows { + row_ids.push(row.try_get("id")?); + queued.insert( + bytes32(row.try_get("event_id")?)?, + row.try_get("event_created_at")?, + ); + } + let documents = read_documents(&mut tx, &queued).await?; + for document in &documents { + queued.remove(&document.event_id); + } + let removed = queued.into_keys().collect(); + return Ok(Some(SearchOutboxBatch { + tx, + row_ids, + documents, + removed, + })); + } + Ok(None) +} + +/// Read the current state of each live, searchable queued event. +async fn read_documents( + tx: &mut AdmittedTx, + queued: &std::collections::BTreeMap<[u8; 32], DateTime>, +) -> Result> { + let community = tx.community(); + let ids: Vec<&[u8]> = queued.keys().map(|id| id.as_slice()).collect(); + let created: Vec> = queued.values().copied().collect(); + // The (created_at, id) pair is the events key, so each lookup prunes to + // one partition. + let rows = sqlx::query( + "SELECT e.id, e.kind, e.pubkey, e.channel_id, e.created_at, e.content, \ + c.channel_type::text AS channel_type, \ + (u.agent_owner_pubkey IS NOT NULL) AS author_is_agent, \ + t.root_event_id, \ + ARRAY(SELECT m.pubkey_hex::text FROM event_mentions m \ + WHERE m.community_id = e.community_id AND m.event_id = e.id \ + ORDER BY m.pubkey_hex) AS mentions \ + FROM unnest($2::bytea[], $3::timestamptz[]) AS k(id, created_at) \ + JOIN events e \ + ON e.community_id = $1 AND e.created_at = k.created_at AND e.id = k.id \ + LEFT JOIN channels c ON c.community_id = e.community_id AND c.id = e.channel_id \ + LEFT JOIN users u ON u.community_id = e.community_id AND u.pubkey = e.pubkey \ + LEFT JOIN thread_metadata t \ + ON t.community_id = e.community_id \ + AND t.event_created_at = e.created_at AND t.event_id = e.id \ + WHERE e.deleted_at IS NULL AND e.kind = ANY($4)", + ) + .bind(community.as_uuid()) + .bind(&ids) + .bind(&created) + .bind(SEARCHABLE_KINDS.as_slice()) + .fetch_all(tx.conn()) + .await?; + let mut documents = Vec::with_capacity(rows.len()); + for row in rows { + documents.push(SearchDocument { + event_id: bytes32(row.try_get("id")?)?, + kind: row.try_get("kind")?, + pubkey: bytes32(row.try_get("pubkey")?)?, + channel_id: row.try_get("channel_id")?, + created_at: row.try_get("created_at")?, + content: row.try_get("content")?, + channel_type: row.try_get("channel_type")?, + author_is_agent: row.try_get("author_is_agent")?, + thread_root: row + .try_get::>, _>("root_event_id")? + .map(bytes32) + .transpose()?, + mentions: row.try_get("mentions")?, + }); + } + Ok(documents) +} + +/// Queued rows, for lag checks and tests. +pub async fn depth(pool: &PgPool) -> Result { + Ok(sqlx::query_scalar("SELECT count(*) FROM search_outbox") + .fetch_one(pool) + .await?) +} + +fn bytes32(bytes: Vec) -> Result<[u8; 32]> { + <[u8; 32]>::try_from(bytes.as_slice()) + .map_err(|_| crate::DbError::InvalidData(format!("expected 32 bytes, got {}", bytes.len()))) +} diff --git a/crates/buzz-db/src/store/search_outbox_postgres_tests.rs b/crates/buzz-db/src/store/search_outbox_postgres_tests.rs new file mode 100644 index 0000000000..49360d4f3c --- /dev/null +++ b/crates/buzz-db/src/store/search_outbox_postgres_tests.rs @@ -0,0 +1,301 @@ +//! PostgreSQL contract for the search outbox: what admission queues and what +//! a claim reads back. The community-deletion fence and purge are covered in +//! `deletion::postgres_tests::search_outbox_is_fenced_and_purged`. +//! +//! nextest runs each test in its own process, so [`search_outbox::enable`] +//! does not leak between tests. +use crate::{event, search_outbox, Db, DbConfig}; +use buzz_core::CommunityId; +use chrono::DateTime; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use sqlx::PgPool; +use uuid::Uuid; + +async fn connect() -> Db { + let database_url = std::env::var("BUZZ_TEST_DATABASE_URL") + .expect("Postgres wrapper must provide an isolated database URL"); + Db::new(&DbConfig { + database_url, + ..DbConfig::default() + }) + .await + .expect("connect to isolated database") +} + +async fn create_community(pool: &PgPool) -> CommunityId { + let id = Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(id) + .bind(format!("search-outbox-{}.example", id.simple())) + .execute(pool) + .await + .expect("create community"); + CommunityId::from_uuid(id) +} + +async fn create_dm(pool: &PgPool, community: CommunityId, author: &Keys) -> Uuid { + let id = Uuid::new_v4(); + sqlx::query( + "INSERT INTO channels (id, community_id, name, channel_type, created_by) \ + VALUES ($1, $2, $3, 'dm', $4)", + ) + .bind(id) + .bind(community.as_uuid()) + .bind(format!("dm-{}", id.simple())) + .bind(author.public_key().to_bytes().as_slice()) + .execute(pool) + .await + .expect("create channel"); + id +} + +fn signed(keys: &Keys, kind: u16, content: &str, tags: Vec) -> Event { + EventBuilder::new(Kind::Custom(kind), content) + .tags(tags) + .sign_with_keys(keys) + .expect("sign event") +} + +async fn queued(pool: &PgPool, community: CommunityId) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM search_outbox WHERE community_id = $1") + .bind(community.as_uuid()) + .fetch_one(pool) + .await + .expect("count outbox rows") +} + +/// An admitted message queues one row; a claim reads back its current state, +/// including fields from other tables, and completing it empties the queue. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn claim_reads_the_current_state_of_queued_events() { + let db = connect().await; + let pool = db.pool(); + search_outbox::enable(pool).await.expect("enable outbox"); + let community = create_community(pool).await; + let agent = Keys::generate(); + let owner = Keys::generate(); + let mentioned = Keys::generate(); + let channel = create_dm(pool, community, &agent).await; + sqlx::query("INSERT INTO users (community_id, pubkey, agent_owner_pubkey) VALUES ($1, $2, $3)") + .bind(community.as_uuid()) + .bind(agent.public_key().to_bytes().as_slice()) + .bind(owner.public_key().to_bytes().as_slice()) + .execute(pool) + .await + .expect("register agent"); + + let root = signed(&agent, 9, "root message", vec![]); + db.insert_event(community, &root, Some(channel)) + .await + .expect("insert root"); + let reply = signed( + &agent, + 9, + "reply mentioning someone", + vec![Tag::public_key(mentioned.public_key())], + ); + let root_created = DateTime::from_timestamp(root.created_at.as_secs() as i64, 0).unwrap(); + let reply_created = DateTime::from_timestamp(reply.created_at.as_secs() as i64, 0).unwrap(); + db.insert_event_with_thread_metadata( + community, + &reply, + Some(channel), + Some(event::ThreadMetadataParams { + event_id: reply.id.as_bytes(), + event_created_at: reply_created, + channel_id: channel, + parent_event_id: Some(root.id.as_bytes()), + parent_event_created_at: Some(root_created), + root_event_id: Some(root.id.as_bytes()), + root_event_created_at: Some(root_created), + depth: 1, + broadcast: false, + }), + ) + .await + .expect("insert reply"); + assert_eq!(queued(pool, community).await, 2); + + let batch = search_outbox::claim_batch(pool, 10, &[]) + .await + .expect("claim") + .expect("a batch"); + assert_eq!(batch.community(), community); + assert!(batch.removed.is_empty()); + let doc = batch + .documents + .iter() + .find(|doc| doc.event_id == *reply.id.as_bytes()) + .expect("reply document"); + assert_eq!(doc.kind, 9); + assert_eq!(doc.pubkey, agent.public_key().to_bytes()); + assert_eq!(doc.channel_id, Some(channel)); + assert_eq!(doc.created_at, reply_created); + assert_eq!(doc.content, "reply mentioning someone"); + assert_eq!(doc.channel_type.as_deref(), Some("dm")); + assert!(doc.author_is_agent); + assert_eq!(doc.thread_root, Some(*root.id.as_bytes())); + assert_eq!(doc.mentions, vec![mentioned.public_key().to_hex()]); + batch.complete().await.expect("complete"); + assert_eq!(queued(pool, community).await, 0); + assert!(search_outbox::claim_batch(pool, 10, &[]) + .await + .expect("claim") + .is_none()); +} + +/// A claimed event that was deleted after it was queued comes back as +/// removed, not as a document. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn claim_reports_deleted_events_as_removed() { + let db = connect().await; + let pool = db.pool(); + search_outbox::enable(pool).await.expect("enable outbox"); + let community = create_community(pool).await; + let message = signed(&Keys::generate(), 9, "soon deleted", vec![]); + db.insert_event(community, &message, None) + .await + .expect("insert"); + sqlx::query("UPDATE events SET deleted_at = now() WHERE community_id = $1 AND id = $2") + .bind(community.as_uuid()) + .bind(message.id.as_bytes().as_slice()) + .execute(pool) + .await + .expect("delete"); + + let batch = search_outbox::claim_batch(pool, 10, &[]) + .await + .expect("claim") + .expect("a batch"); + assert!(batch.documents.is_empty()); + assert_eq!(batch.removed, vec![*message.id.as_bytes()]); + batch.complete().await.expect("complete"); +} + +/// Only searchable kinds queue, a rolled-back insert queues nothing, and a +/// batch dropped without completing leaves its rows queued. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn only_committed_searchable_events_queue() { + let db = connect().await; + let pool = db.pool(); + search_outbox::enable(pool).await.expect("enable outbox"); + let community = create_community(pool).await; + let keys = Keys::generate(); + db.insert_event(community, &signed(&keys, 7, "+", vec![]), None) + .await + .expect("insert reaction"); + assert_eq!(queued(pool, community).await, 0, "kind 7 is not searchable"); + + let mut tx = db + .begin_event_write_transaction(community) + .await + .expect("begin"); + event::insert_event_in_transaction(&mut tx, &signed(&keys, 9, "rolled back", vec![]), None) + .await + .expect("insert"); + tx.rollback().await.expect("rollback"); + assert_eq!( + queued(pool, community).await, + 0, + "a rollback queues nothing" + ); + + db.insert_event(community, &signed(&keys, 9, "kept", vec![]), None) + .await + .expect("insert message"); + let batch = search_outbox::claim_batch(pool, 10, &[]) + .await + .expect("claim") + .expect("a batch"); + drop(batch); + assert_eq!( + queued(pool, community).await, + 1, + "an abandoned batch keeps its row" + ); +} + +/// Without [`search_outbox::enable`], admission writes no outbox rows. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn disabled_outbox_queues_nothing() { + let db = connect().await; + let pool = db.pool(); + let community = create_community(pool).await; + db.insert_event( + community, + &signed(&Keys::generate(), 9, "hello", vec![]), + None, + ) + .await + .expect("insert"); + assert_eq!(queued(pool, community).await, 0); +} + +/// Enabling fails, and leaves admission unchanged, while the table is missing. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn enable_requires_the_table() { + let db = connect().await; + let pool = db.pool(); + sqlx::query("DROP TABLE search_outbox") + .execute(pool) + .await + .expect("drop table"); + search_outbox::enable(pool) + .await + .expect_err("enable refuses a database without the table"); + let community = create_community(pool).await; + db.insert_event( + community, + &signed(&Keys::generate(), 9, "still stored", vec![]), + None, + ) + .await + .expect("admission works with the outbox off"); +} + +/// A claim passes over communities it is told to skip and communities whose +/// rows another worker holds. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn claim_passes_over_skipped_and_held_communities() { + let db = connect().await; + let pool = db.pool(); + search_outbox::enable(pool).await.expect("enable outbox"); + let first = create_community(pool).await; + let second = create_community(pool).await; + let keys = Keys::generate(); + for community in [first, second] { + db.insert_event(community, &signed(&keys, 9, "queued", vec![]), None) + .await + .expect("insert"); + } + + let held = search_outbox::claim_batch(pool, 10, &[]) + .await + .expect("claim") + .expect("a batch"); + assert_eq!(held.community(), first, "the oldest row's community"); + let other = search_outbox::claim_batch(pool, 10, &[]) + .await + .expect("claim") + .expect("another worker's batch"); + assert_eq!(other.community(), second); + drop(other); + drop(held); + + let skipping = search_outbox::claim_batch(pool, 10, &[first]) + .await + .expect("claim") + .expect("a batch"); + assert_eq!(skipping.community(), second); + drop(skipping); + assert!(search_outbox::claim_batch(pool, 10, &[first, second]) + .await + .expect("claim") + .is_none()); +} diff --git a/crates/buzz-db/tests/observability_source.rs b/crates/buzz-db/tests/observability_source.rs index 88920c2a7d..99df6ee01c 100644 --- a/crates/buzz-db/tests/observability_source.rs +++ b/crates/buzz-db/tests/observability_source.rs @@ -1706,15 +1706,16 @@ fn events_insert_tails(source: &str) -> Vec { tails } -/// An events insert must run both follow-ups: the push enqueue and the -/// pre-commit TTL refresh. `after_admitted_insert` does both; a writer that -/// inserts inside a savepoint calls the two halves separately. +/// An events insert must run every follow-up: the push enqueue, the search +/// outbox row and the pre-commit TTL refresh. `after_admitted_insert` does +/// all three; a writer that inserts inside a savepoint calls them separately. /// /// Only real calls count: a hook in a comment or a string literal does not. fn runs_event_follow_ups(function_source: &str) -> bool { let code = mask_comments_and_literals(function_source); code.contains("event_follow_up::after_admitted_insert(") || (code.contains("event_follow_up::enqueue_push_match(") + && code.contains("search_outbox::enqueue_in_transaction(") && code.contains(".record_channel_event(")) } @@ -1759,6 +1760,16 @@ pub(crate) async fn hooked_writer(tx: &mut AdmittedTx) { .await .expect("follow up"); } +pub(crate) async fn unsearched_writer(tx: &mut AdmittedTx) { + sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") + .execute(tx.conn()) + .await + .expect("write"); + crate::store::event_follow_up::enqueue_push_match(tx.conn(), community, id, kind) + .await + .expect("enqueue"); + tx.record_channel_event(channel, kind); +} pub(crate) async fn savepoint_writer(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) @@ -1767,6 +1778,9 @@ pub(crate) async fn savepoint_writer(tx: &mut AdmittedTx) { crate::store::event_follow_up::enqueue_push_match(tx.conn(), community, id, kind) .await .expect("enqueue"); + crate::search_outbox::enqueue_in_transaction(tx, id, created_at, kind) + .await + .expect("search"); tx.record_channel_event(channel, kind); } pub(crate) async fn mention_writer(tx: &mut AdmittedTx) { @@ -1900,6 +1914,7 @@ mod tests { "pub(crate) async fn unhooked_writer(tx: &mut AdmittedTx) {", "pub(crate) async fn quoted_writer(tx: &mut AdmittedTx) {", "pub(crate) async fn push_only_writer(tx: &mut AdmittedTx) {", + "pub(crate) async fn unsearched_writer(tx: &mut AdmittedTx) {", "pub(crate) async fn lowercase_writer(tx: &mut AdmittedTx) {", "pub(crate) async fn continued_writer(tx: &mut AdmittedTx) {", "pub(crate) async fn writer_under_doc_mention(tx: &mut AdmittedTx) {", @@ -1915,7 +1930,7 @@ mod tests { "pub(crate) async fn writer_after_raw_string_example(tx: &mut AdmittedTx) {", "pub(crate) async fn writer_after_test_helper(tx: &mut AdmittedTx) {", ], - "an events insert must run the push enqueue and record the TTL refresh" + "an events insert must run the push enqueue, queue the search row and record the TTL refresh" ); } diff --git a/crates/buzz-relay/src/config.rs b/crates/buzz-relay/src/config.rs index 4f91dfa75b..fd02bea605 100644 --- a/crates/buzz-relay/src/config.rs +++ b/crates/buzz-relay/src/config.rs @@ -305,6 +305,12 @@ pub struct Config { /// (`BUZZ_STORAGE_USAGE_URL`). Unset disables storage-usage delivery. pub storage_usage_delivery_url: Option, + /// OpenSearch cluster for message search (`BUZZ_OPENSEARCH_URL`, with + /// optional `BUZZ_OPENSEARCH_USERNAME` and `BUZZ_OPENSEARCH_PASSWORD`). + /// When set, admitted messages are queued in the search outbox and the + /// indexer keeps the index up to date; searches still use Postgres. + pub opensearch: Option, + /// Allow NIP-OA owner attestation for relay membership. /// /// When `true` and `require_relay_membership` is also `true`, agents @@ -1023,6 +1029,13 @@ impl Config { ))); } }; + let opensearch = parse_opensearch_config( + optional_utf8_env("BUZZ_OPENSEARCH_URL")?, + optional_utf8_env("BUZZ_OPENSEARCH_USERNAME")?, + optional_utf8_env("BUZZ_OPENSEARCH_PASSWORD")?, + parse_bool("BUZZ_OPENSEARCH_PREVIEW", false)?, + ) + .map_err(ConfigError::InvalidValue)?; if !operator_listener_delivery_urls.is_empty() && relay_operator_api_origin.is_none() { error!( "BUZZ_OPERATOR_LISTENERS is set but RELAY_OPERATOR_API_ORIGIN is not — operator-listener registration requests will reject every request until RELAY_OPERATOR_API_ORIGIN is set" @@ -1572,6 +1585,7 @@ impl Config { multi_community_relay, operator_listener_delivery_urls, storage_usage_delivery_url, + opensearch, allow_nip_oa_auth, klipy, media, @@ -1636,10 +1650,129 @@ impl Config { } } +/// An environment variable that must be UTF-8 if set. +fn optional_utf8_env(name: &str) -> Result, ConfigError> { + match std::env::var(name) { + Ok(value) => Ok(Some(value)), + Err(std::env::VarError::NotPresent) => Ok(None), + Err(error) => Err(ConfigError::InvalidValue(format!( + "{name} must be valid UTF-8: {error}" + ))), + } +} + +/// Parse the OpenSearch settings: an HTTP(S) URL without credentials, query, +/// or fragment, and basic credentials given both or neither. Empty values +/// count as unset. +/// +/// Deletes and edits don't reach the index yet, so a URL also needs the +/// `BUZZ_OPENSEARCH_PREVIEW` opt-in. +fn parse_opensearch_config( + url: Option, + username: Option, + password: Option, + preview: bool, +) -> Result, String> { + let set = |value: Option| value.filter(|value| !value.trim().is_empty()); + let (username, password) = (set(username), set(password)); + let Some(raw) = set(url) else { + if username.is_some() || password.is_some() { + return Err( + "BUZZ_OPENSEARCH_USERNAME and BUZZ_OPENSEARCH_PASSWORD need BUZZ_OPENSEARCH_URL" + .into(), + ); + } + return Ok(None); + }; + if !preview { + return Err("BUZZ_OPENSEARCH_URL needs BUZZ_OPENSEARCH_PREVIEW=true: deleted messages stay in the index, so use it only on a relay without real data".into()); + } + let parsed = url::Url::parse(raw.trim()) + .map_err(|e| format!("BUZZ_OPENSEARCH_URL is not a valid URL: {e}"))?; + if !matches!(parsed.scheme(), "http" | "https") + || parsed.host().is_none() + || !parsed.username().is_empty() + || parsed.password().is_some() + || parsed.query().is_some() + || parsed.fragment().is_some() + { + return Err("BUZZ_OPENSEARCH_URL must be an HTTP(S) URL without credentials, query, or fragment; set BUZZ_OPENSEARCH_USERNAME and BUZZ_OPENSEARCH_PASSWORD for basic auth".into()); + } + let basic_auth = match (username, password) { + (Some(username), Some(password)) => Some((username, password)), + (None, None) => None, + _ => { + return Err( + "set both BUZZ_OPENSEARCH_USERNAME and BUZZ_OPENSEARCH_PASSWORD, or neither".into(), + ) + } + }; + Ok(Some(buzz_search::opensearch::OpenSearchConfig { + url: parsed.to_string(), + basic_auth, + index_prefix: buzz_search::opensearch::DEFAULT_INDEX_PREFIX.to_string(), + })) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn opensearch_config_is_optional_and_validated() { + let some = |value: &str| Some(value.to_string()); + assert!(parse_opensearch_config(None, None, None, false) + .unwrap() + .is_none()); + assert!(parse_opensearch_config(some(" "), None, None, false) + .unwrap() + .is_none()); + assert!(parse_opensearch_config(None, some(""), some(""), false) + .unwrap() + .is_none()); + let config = + parse_opensearch_config(some("http://localhost:9200"), some(""), some(" "), true) + .unwrap() + .unwrap(); + assert!(config.basic_auth.is_none()); + + assert!( + parse_opensearch_config(some("http://localhost:9200"), None, None, false).is_err(), + "a URL without the preview opt-in" + ); + let config = parse_opensearch_config(some("http://localhost:9200"), None, None, true) + .unwrap() + .unwrap(); + assert_eq!(config.url, "http://localhost:9200/"); + assert!(config.basic_auth.is_none()); + assert_eq!(config.index_prefix, "buzz-"); + + let config = parse_opensearch_config( + some("https://search.example.org"), + some("relay"), + some("secret"), + true, + ) + .unwrap() + .unwrap(); + assert_eq!(config.basic_auth, Some(("relay".into(), "secret".into()))); + assert!(!format!("{config:?}").contains("secret")); + + for (url, username, password) in [ + (some("ftp://search.example.org"), None, None), + (some("https://user:pw@search.example.org"), None, None), + (some("https://search.example.org?x=1"), None, None), + (some("not a url"), None, None), + (some("https://search.example.org"), some("relay"), None), + (None, some("relay"), some("secret")), + ] { + assert!( + parse_opensearch_config(url.clone(), username, password, true).is_err(), + "{url:?}" + ); + } + } + #[test] fn klipy_config_debug_redacts_the_api_key() { let config = KlipyConfig { diff --git a/crates/buzz-relay/src/main.rs b/crates/buzz-relay/src/main.rs index d0caf91773..2a7d508efe 100644 --- a/crates/buzz-relay/src/main.rs +++ b/crates/buzz-relay/src/main.rs @@ -651,6 +651,22 @@ async fn run_relay_main(boot: BootTracker) -> anyhow::Result<()> { "Search service ready (Postgres FTS)" ); + // With an OpenSearch address, admission queues searchable events in the + // search outbox and the indexer (spawned below) drains it. Searches stay + // on Postgres for now. + let search_indexer = match &config.opensearch { + Some(opensearch) => { + let index = buzz_search::opensearch::SearchIndex::new(opensearch) + .map_err(|e| anyhow::anyhow!("OpenSearch client: {}", e.kind()))?; + buzz_db::search_outbox::enable(db.pool()) + .await + .map_err(|e| anyhow::anyhow!("search outbox: {e}"))?; + info!(url = %opensearch.url, "search outbox enabled"); + Some(buzz_search::indexer::Indexer::new(db.clone(), index)) + } + None => None, + }; + let workflow_config = buzz_workflow::WorkflowConfig { agent_mentions: config.workflow_agent_mentions, ..Default::default() @@ -1136,6 +1152,11 @@ async fn run_relay_main(boot: BootTracker) -> anyhow::Result<()> { info!("storage-usage delivery worker started"); } + if let Some(indexer) = search_indexer { + tokio::spawn(indexer.run()); + info!("search indexer started"); + } + // Admin outbox delivery worker — drives `relay_admin_outbox` rows. // Uses DB-level leases (held_by / lease_expires_at) so multiple pods can // run the worker concurrently without double-delivery. diff --git a/crates/buzz-search/Cargo.toml b/crates/buzz-search/Cargo.toml index 73a324791a..5cc2e50a28 100644 --- a/crates/buzz-search/Cargo.toml +++ b/crates/buzz-search/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true rust-version.workspace = true license.workspace = true repository.workspace = true -description = "Postgres full-text search for Buzz, scoped by community" +description = "Community-scoped message search for Buzz: Postgres full-text search and OpenSearch" [dependencies] buzz-core = { workspace = true } @@ -17,3 +17,11 @@ thiserror = { workspace = true } tracing = { workspace = true } metrics = { workspace = true } tokio = { workspace = true } +opensearch = { workspace = true } +serde_json = { workspace = true } +hex = { workspace = true } +chrono = { workspace = true } +rand = { workspace = true } + +[dev-dependencies] +nostr = { workspace = true } diff --git a/crates/buzz-search/src/error.rs b/crates/buzz-search/src/error.rs index bde59fc4cd..ea0178488b 100644 --- a/crates/buzz-search/src/error.rs +++ b/crates/buzz-search/src/error.rs @@ -1,11 +1,19 @@ use thiserror::Error; -/// Errors produced by the FTS service. +/// Errors produced by the search service. #[derive(Debug, Error)] pub enum SearchError { /// A database error from sqlx. #[error("database error: {0}")] Db(#[from] sqlx::Error), + /// OpenSearch failed, rejected the request, or returned a partial + /// result. The text is a fixed description, never the search text. + #[error("search engine error: {0}")] + Engine(String), + /// OpenSearch refused this request itself (HTTP 400 or 413), so sending + /// it again fails the same way. The text is a fixed description. + #[error("search engine rejected the request: {0}")] + Rejected(String), } impl SearchError { @@ -25,7 +33,10 @@ impl SearchError { /// A fixed description of this error for log lines: never the message, /// which can repeat the search text. pub fn kind(&self) -> String { - let SearchError::Db(e) = self; - buzz_db::error::sqlx_error_kind(e) + match self { + SearchError::Db(e) => buzz_db::error::sqlx_error_kind(e), + SearchError::Engine(description) => format!("opensearch: {description}"), + SearchError::Rejected(description) => format!("opensearch rejected: {description}"), + } } } diff --git a/crates/buzz-search/src/indexer.rs b/crates/buzz-search/src/indexer.rs new file mode 100644 index 0000000000..e615531065 --- /dev/null +++ b/crates/buzz-search/src/indexer.rs @@ -0,0 +1,158 @@ +//! The indexer: drains `search_outbox` into the OpenSearch index. +//! +//! One relay at a time holds the indexer lease (a session advisory lock); +//! when it stops, its lock connection closes and another relay takes over. +//! Rows are deleted only once the index holds their events, so a failed +//! request leaves them queued. +//! +//! A batch holds its community's admission open for up to one request +//! timeout. Community deletion's quiesce step waits for that batch, and once +//! the community is quiescing no new batch for it can start. + +use std::time::Duration; + +use buzz_db::{search_outbox, Db, DbError}; +use tracing::{info, warn}; + +use crate::opensearch::SearchIndex; +use crate::SearchError; +use buzz_core::CommunityId; + +/// Deployment-global advisory lock electing the indexing instance. +const INDEXER_LOCK_KEY: i64 = 0x4255_5A5A_5345_4152; + +/// Outbox rows per batch, and so documents per bulk request. +const BATCH_SIZE: i64 = 500; + +/// How often an idle leader checks the queue, and a follower the lease. +const POLL_INTERVAL: Duration = Duration::from_secs(5); + +/// Longest wait after repeated failures. +const MAX_BACKOFF: Duration = Duration::from_secs(60); + +/// Why a batch was not indexed. Its rows stay queued. +#[derive(Debug, thiserror::Error)] +pub enum IndexerError { + /// Claiming, reading or completing the batch failed. + #[error("outbox: {0}")] + Outbox(#[from] DbError), + /// The index write failed. + #[error("index write: {}", .0.kind())] + Index(#[from] SearchError), +} + +/// Moves queued events from `search_outbox` into a [`SearchIndex`]. +#[derive(Debug, Clone)] +pub struct Indexer { + db: Db, + index: SearchIndex, +} + +impl Indexer { + /// An indexer reading the outbox from `db` and writing `index`. + pub fn new(db: Db, index: SearchIndex) -> Self { + Self { db, index } + } + + /// Index batches until none is left to claim. A community whose batch + /// the cluster rejects is skipped for the rest of the pass and reported + /// once the others are done; any other failure ends the pass. + pub async fn drain(&self) -> Result<(), IndexerError> { + let mut skipped: Vec = Vec::new(); + let mut rejection = None; + while let Some(batch) = + search_outbox::claim_batch(self.db.pool(), BATCH_SIZE, &skipped).await? + { + let community = batch.community(); + match self + .index + .write(community, &batch.documents, &batch.removed) + .await + { + Ok(()) => batch.complete().await?, + Err(error @ SearchError::Rejected(_)) => { + warn!(%community, error = %error.kind(), "search index rejected a batch; its rows stay queued"); + skipped.push(community); + rejection.get_or_insert(error); + } + Err(error) => return Err(error.into()), + } + } + rejection.map_or(Ok(()), |error| Err(error.into())) + } + + /// One leader pass: make sure the index exists, then drain. Checking + /// every pass (one request when the alias exists) recreates an index + /// that went away, and creating it here rather than at startup means an + /// unreachable cluster never delays serving. + async fn pass(&self) -> Result<(), IndexerError> { + self.index.ensure().await?; + self.drain().await + } + + /// Hold the indexer lease and keep the index up to date, forever. Abort + /// the task to stop; that closes the lease connection and lets another + /// instance take over. + pub async fn run(self) { + // Spread lease attempts of instances that start together. + tokio::time::sleep(POLL_INTERVAL.mul_f64(rand::random::())).await; + let mut leader: Option = None; + let mut failures = 0u32; + loop { + if let Some(guard) = leader.as_mut() { + if !guard.is_live().await { + warn!("search indexer lease session lost; re-electing"); + leader = None; + } + } + if leader.is_none() { + match self.db.try_lock_session_leader(INDEXER_LOCK_KEY).await { + Ok(Some(acquired)) => { + info!("acquired the search indexer lease"); + leader = Some(acquired); + } + Ok(None) => {} + Err(error) => warn!(%error, "search indexer lease attempt failed"), + } + } + if leader.is_some() { + match self.pass().await { + Ok(()) => failures = 0, + Err(error) => { + failures = failures.saturating_add(1); + warn!(%error, failures, "search indexing failed; rows stay queued"); + } + } + } + tokio::time::sleep(backoff(failures)).await; + } + } +} + +/// The wait before the next attempt: the poll interval, doubled per +/// consecutive failure up to [`MAX_BACKOFF`], with jitter after a failure. +fn backoff(failures: u32) -> Duration { + if failures == 0 { + return POLL_INTERVAL; + } + let ceiling = POLL_INTERVAL + .saturating_mul(1 << failures.min(4)) + .min(MAX_BACKOFF); + ceiling.mul_f64(0.5 + rand::random::() / 2.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backoff_grows_to_a_cap() { + assert_eq!(backoff(0), POLL_INTERVAL); + for failures in 1..10 { + let wait = backoff(failures); + assert!(wait <= MAX_BACKOFF, "{failures}: {wait:?}"); + assert!(wait >= POLL_INTERVAL, "{failures}: {wait:?}"); + } + assert!(backoff(8) >= MAX_BACKOFF / 2); + } +} diff --git a/crates/buzz-search/src/lib.rs b/crates/buzz-search/src/lib.rs index bdf66340ca..4e7ded874e 100644 --- a/crates/buzz-search/src/lib.rs +++ b/crates/buzz-search/src/lib.rs @@ -1,6 +1,13 @@ #![deny(unsafe_code)] #![warn(missing_docs)] -//! Buzz search — community-scoped Postgres full-text search over Buzz events. +//! Buzz search — community-scoped message search over Buzz events. +//! +//! [`SearchService`] answers from one of two backends: Postgres full-text +//! search, described below and still the one the relay uses, or the +//! [`opensearch`] index, which [`indexer::Indexer`] keeps in sync from the +//! `search_outbox` queue. +//! +//! ## Postgres full-text search //! //! The index lives in the `events` table: `search_tsv TSVECTOR GENERATED //! ALWAYS AS (to_tsvector('simple', content)) STORED`, with `GIN @@ -18,13 +25,18 @@ //! //! Every [`SearchQuery`] carries a [`CommunityId`]. There is no construction //! path through this crate that omits it, and every SQL execution binds -//! `community_id = $ctx` as the first predicate. A query bound to community +//! `community_id = $ctx` as the first predicate; every OpenSearch query +//! filters on the community first. A query bound to community //! A cannot return events stored under community B, by construction. #[doc(hidden)] pub mod cancel; /// Search error types. pub mod error; +/// The OpenSearch indexer worker. +pub mod indexer; +/// The OpenSearch message index. +pub mod opensearch; /// Search query execution. pub mod query; @@ -49,24 +61,55 @@ pub fn pool_options() -> PgPoolOptions { }) } -/// Thin handle around a `PgPool` for community-scoped FTS. +/// The single entry point for community-scoped message search: a +/// [`SearchQuery`] in, a [`SearchResult`] of hit keys out. /// -/// Holds nothing the pool itself doesn't already own. The whole purpose of -/// this type is a stable injection point for the relay's `AppState`. +/// Which engine answers [`SearchService::search`] is internal to this type, +/// so callers and their tests don't depend on it. Profile name search always +/// runs on Postgres. #[derive(Debug, Clone)] pub struct SearchService { pool: PgPool, + backend: Backend, +} + +/// The engine behind [`SearchService::search`]. +#[derive(Debug, Clone)] +enum Backend { + /// Postgres full-text search over `events.search_tsv`. + Postgres, + /// The OpenSearch message index, kept in sync by [`indexer::Indexer`]. + OpenSearch(Box), } impl SearchService { - /// Build a search service over an existing Postgres pool. + /// Build a search service over an existing Postgres pool, searching with + /// Postgres full-text search. pub fn new(pool: PgPool) -> Self { - Self { pool } + Self { + pool, + backend: Backend::Postgres, + } } - /// Execute a community-scoped FTS query. + /// Build a search service that answers message searches from the + /// OpenSearch `index`. Profile name search stays on `pool`. + /// + /// Only tests select this backend for now; the relay still searches + /// Postgres. + pub fn with_opensearch(pool: PgPool, index: opensearch::SearchIndex) -> Self { + Self { + pool, + backend: Backend::OpenSearch(Box::new(index)), + } + } + + /// Execute a community-scoped message search. pub async fn search(&self, query: &SearchQuery) -> Result { - query::search(&self.pool, query).await + match &self.backend { + Backend::Postgres => query::search(&self.pool, query).await, + Backend::OpenSearch(index) => index.search(query).await, + } } /// Find people by profile name, and by verified profile names signed by diff --git a/crates/buzz-search/src/opensearch.rs b/crates/buzz-search/src/opensearch.rs new file mode 100644 index 0000000000..8a35d89b4c --- /dev/null +++ b/crates/buzz-search/src/opensearch.rs @@ -0,0 +1,443 @@ +//! The OpenSearch message index: layout, writes and searches. +//! +//! One alias, `{prefix}messages`, points at the index of the mapping version +//! this code writes, `{prefix}messages-v1`. A document is one message, with +//! id `community:event_id`. Documents are routed by id, so messages spread +//! evenly over shards, and every search filters on the community first: that +//! filter, not routing, is the multi-tenant fence. +//! +//! Message text is indexed but not kept in the stored document source. The +//! relay re-reads every hit from Postgres, so the index holds only what search +//! needs. + +use std::time::Duration; + +use buzz_core::CommunityId; +use buzz_db::search_outbox::SearchDocument; +use opensearch::auth::Credentials; +use opensearch::http::response::Response; +use opensearch::http::transport::{SingleNodeConnectionPool, TransportBuilder}; +use opensearch::http::Url; +use opensearch::indices::IndicesRefreshParts; +use opensearch::indices::{IndicesCreateParts, IndicesDeleteParts, IndicesExistsParts}; +use opensearch::{BulkOperation, BulkParts, OpenSearch, SearchParts}; +use serde_json::{json, Value}; + +use crate::query::{normalized_search_text, page_bounds, PageBounds}; +use crate::{ + ChannelScope, SearchError, SearchHit, SearchMode, SearchQuery, SearchResult, SearchSort, +}; + +/// Mapping version this code writes and searches. Bump it, with a reindex, +/// whenever the mapping or analysis changes. +const MAPPING_VERSION: u32 = 1; + +/// Index names used when the configuration sets no prefix. +pub const DEFAULT_INDEX_PREFIX: &str = "buzz-"; + +/// Bound on every request, so a stalled cluster cannot hold an indexer batch +/// (and its admitted transaction) or a search open. +const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); + +/// OpenSearch's default `index.max_result_window`: `from + size` beyond it is +/// rejected, so pages past it are empty. +const MAX_RESULT_WINDOW: i64 = 10_000; + +/// How to reach an OpenSearch cluster. +#[derive(Clone)] +pub struct OpenSearchConfig { + /// Cluster address, for example `http://localhost:9200`. + pub url: String, + /// HTTP basic credentials, if the cluster needs them. + pub basic_auth: Option<(String, String)>, + /// Prefix of the alias and index names. The relay always uses + /// [`DEFAULT_INDEX_PREFIX`]; tests set their own to share a cluster. + pub index_prefix: String, +} + +impl std::fmt::Debug for OpenSearchConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("OpenSearchConfig") + .field("url", &self.url) + .field( + "basic_auth", + &self.basic_auth.as_ref().map(|(user, _)| user), + ) + .field("index_prefix", &self.index_prefix) + .finish() + } +} + +/// The message index on one OpenSearch cluster. +#[derive(Clone)] +pub struct SearchIndex { + client: OpenSearch, + alias: String, + index: String, +} + +impl std::fmt::Debug for SearchIndex { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SearchIndex") + .field("alias", &self.alias) + .field("index", &self.index) + .finish_non_exhaustive() + } +} + +impl SearchIndex { + /// A client for the index described by `config`. Makes no request. + pub fn new(config: &OpenSearchConfig) -> Result { + let url = Url::parse(&config.url) + .map_err(|_| SearchError::Engine("invalid OpenSearch URL".into()))?; + let mut transport = + TransportBuilder::new(SingleNodeConnectionPool::new(url)).timeout(REQUEST_TIMEOUT); + if let Some((user, password)) = &config.basic_auth { + transport = transport.auth(Credentials::Basic(user.clone(), password.clone())); + } + let transport = transport + .build() + .map_err(|_| SearchError::Engine("OpenSearch client setup failed".into()))?; + Ok(Self { + client: OpenSearch::new(transport), + alias: format!("{}messages", config.index_prefix), + index: format!("{}messages-v{MAPPING_VERSION}", config.index_prefix), + }) + } + + /// Create the versioned index behind the alias unless the alias exists. + pub async fn ensure(&self) -> Result<(), SearchError> { + if self.alias_exists().await? { + return Ok(()); + } + let response = self + .client + .indices() + .create(IndicesCreateParts::Index(&self.index)) + .body(index_definition(&self.alias)) + .send() + .await + .map_err(transport_error)?; + // Another relay may have created it, with its alias, first. + if response.status_code().as_u16() == 400 { + let body: Value = response.json().await.map_err(transport_error)?; + if body["error"]["type"] == "resource_already_exists_exception" { + if self.alias_exists().await? { + return Ok(()); + } + return Err(SearchError::Engine("index exists without its alias".into())); + } + return Err(SearchError::Engine("index creation rejected".into())); + } + checked(response).await.map(drop) + } + + async fn alias_exists(&self) -> Result { + let response = self + .client + .indices() + .exists(IndicesExistsParts::Index(&[&self.alias])) + .send() + .await + .map_err(transport_error)?; + Ok(response.status_code().is_success()) + } + + /// Delete the versioned index. For tests and tools. + pub async fn delete(&self) -> Result<(), SearchError> { + let response = self + .client + .indices() + .delete(IndicesDeleteParts::Index(&[&self.index])) + .send() + .await + .map_err(transport_error)?; + if response.status_code().as_u16() == 404 { + return Ok(()); + } + checked(response).await.map(drop) + } + + /// Make every write so far visible to search, instead of waiting for the + /// refresh interval. For tests and tools. + pub async fn refresh(&self) -> Result<(), SearchError> { + let response = self + .client + .indices() + .refresh(IndicesRefreshParts::Index(&[&self.alias])) + .send() + .await + .map_err(transport_error)?; + checked(response).await.map(drop) + } + + /// Upsert `documents` and delete `removed` for one community, in one + /// bulk request through the alias. Fails unless every item succeeded; + /// deleting a document that is not there succeeds. The request requires + /// the alias, so a missing index fails the write instead of being created + /// with a dynamic mapping. + pub async fn write( + &self, + community: CommunityId, + documents: &[SearchDocument], + removed: &[[u8; 32]], + ) -> Result<(), SearchError> { + if documents.is_empty() && removed.is_empty() { + return Ok(()); + } + let index = &self.alias; + let mut operations: Vec> = + Vec::with_capacity(documents.len() + removed.len()); + for document in documents { + operations.push( + BulkOperation::index(document_source(community, document)) + .id(document_id(community, &document.event_id)) + .index(index) + .into(), + ); + } + for event_id in removed { + operations.push( + BulkOperation::delete(document_id(community, event_id)) + .index(index) + .into(), + ); + } + let response = self + .client + .bulk(BulkParts::None) + .require_alias(true) + .body(operations) + .send() + .await + .map_err(transport_error)?; + let body = checked(response).await?; + if body["errors"] != true { + return Ok(()); + } + let failed = body["items"] + .as_array() + .into_iter() + .flatten() + .filter_map(|item| item.as_object()?.values().next()) + .filter(|result| result.get("error").is_some()) + .collect::>(); + let reason = failed + .first() + .and_then(|result| result["error"]["type"].as_str()) + .unwrap_or("unknown"); + let description = format!("{} bulk items failed ({reason})", failed.len()); + // Only a batch whose every failure is the documents' own fault is + // rejected; anything else may succeed on a retry. + let rejected = !failed.is_empty() + && failed + .iter() + .all(|result| result["status"].as_u64().is_some_and(rejects)); + Err(if rejected { + SearchError::Rejected(description) + } else { + SearchError::Engine(description) + }) + } + + /// Run a message search against the alias. + pub(crate) async fn search(&self, query: &SearchQuery) -> Result { + let PageBounds { + page, + per_page, + offset, + } = page_bounds(query); + let Some(text) = normalized_search_text(&query.q) else { + return Ok(SearchResult { + hits: Vec::new(), + page, + }); + }; + if offset + i64::from(per_page) > MAX_RESULT_WINDOW { + return Ok(SearchResult { + hits: Vec::new(), + page, + }); + } + let response = self + .client + .search(SearchParts::Index(&[&self.alias])) + .body(search_body(query, &text, offset, per_page)) + .send() + .await + .map_err(transport_error)?; + let body = checked(response).await?; + // A partly failed search is an error, not fewer hits. + if body["timed_out"] == true { + return Err(SearchError::Engine("search timed out".into())); + } + if body["_shards"]["failed"].as_u64().unwrap_or(0) > 0 { + return Err(SearchError::Engine("search shards failed".into())); + } + let hits = body["hits"]["hits"] + .as_array() + .into_iter() + .flatten() + .map(parse_hit) + .collect::>()?; + Ok(SearchResult { hits, page }) + } +} + +/// Settings, mapping and alias of a new index. +fn index_definition(alias: &str) -> Value { + json!({ + "settings": { "index": { "refresh_interval": "30s" } }, + "mappings": { + "dynamic": "strict", + "_source": { "excludes": ["content"] }, + "properties": { + "community": { "type": "keyword" }, + "event_id": { "type": "keyword" }, + "kind": { "type": "integer" }, + "author": { "type": "keyword" }, + "channel": { "type": "keyword" }, + "channel_type": { "type": "keyword" }, + "author_is_agent": { "type": "boolean" }, + "thread_root": { "type": "keyword" }, + "mentions": { "type": "keyword" }, + "created_at": { "type": "date", "format": "epoch_second" }, + "content": { "type": "text" } + } + }, + "aliases": { alias: {} } + }) +} + +fn document_id(community: CommunityId, event_id: &[u8; 32]) -> String { + format!("{}:{}", community.as_uuid(), hex::encode(event_id)) +} + +fn document_source(community: CommunityId, document: &SearchDocument) -> Value { + json!({ + "community": community.as_uuid().to_string(), + "event_id": hex::encode(document.event_id), + "kind": document.kind, + "author": hex::encode(document.pubkey), + "channel": document.channel_id.map(|id| id.to_string()), + "channel_type": document.channel_type, + "author_is_agent": document.author_is_agent, + "thread_root": document.thread_root.map(hex::encode), + "mentions": document.mentions, + "created_at": document.created_at.timestamp(), + "content": document.content, + }) +} + +/// The request body of a search: filters on the community first, then on +/// scope, kinds, authors and time; the text must match every word. +fn search_body(query: &SearchQuery, text: &str, offset: i64, per_page: u32) -> Value { + let mut filter = + vec![json!({ "term": { "community": query.community.as_uuid().to_string() } })]; + let channels = |ids: &[uuid::Uuid]| json!({ "terms": { "channel": ids.iter().map(|id| id.to_string()).collect::>() } }); + let channel_less = json!({ "bool": { "must_not": { "exists": { "field": "channel" } } } }); + match &query.channel_scope { + ChannelScope::Any => {} + ChannelScope::ChannelLessOnly => filter.push(channel_less), + ChannelScope::Channels(ids) => filter.push(channels(ids)), + ChannelScope::ChannelsOrChannelLess(ids) => filter.push(json!({ + "bool": { "should": [channels(ids), channel_less], "minimum_should_match": 1 } + })), + } + if let Some(kinds) = query.kinds.as_ref().filter(|kinds| !kinds.is_empty()) { + filter.push(json!({ "terms": { "kind": kinds } })); + } + if let Some(authors) = query.authors.as_ref().filter(|authors| !authors.is_empty()) { + let authors: Vec = authors.iter().map(hex::encode).collect(); + filter.push(json!({ "terms": { "author": authors } })); + } + let mut range = serde_json::Map::new(); + if let Some(since) = query.since { + range.insert("gte".into(), since.into()); + } + if let Some(until) = query.until { + range.insert("lte".into(), until.into()); + } + if !range.is_empty() { + filter.push(json!({ "range": { "created_at": range } })); + } + let text_match = match query.mode { + SearchMode::FullText => { + json!({ "match": { "content": { "query": text, "operator": "and" } } }) + } + SearchMode::Prefix => { + json!({ "match_bool_prefix": { "content": { "query": text, "operator": "and" } } }) + } + }; + let tiebreak = [ + json!({ "created_at": "desc" }), + json!({ "event_id": "asc" }), + ]; + let sort: Vec = match query.sort { + SearchSort::Relevance => std::iter::once(json!("_score")).chain(tiebreak).collect(), + SearchSort::Newest => tiebreak.into(), + }; + json!({ + "from": offset, + "size": per_page, + "track_total_hits": false, + "track_scores": true, + "_source": ["event_id", "kind", "author", "channel", "created_at"], + "query": { "bool": { "filter": filter, "must": [text_match] } }, + "sort": sort + }) +} + +fn parse_hit(hit: &Value) -> Result { + let invalid = || SearchError::Engine("unexpected search hit shape".into()); + let source = &hit["_source"]; + let bytes32 = |value: &Value| -> Result<[u8; 32], SearchError> { + let bytes = hex::decode(value.as_str().ok_or_else(invalid)?).map_err(|_| invalid())?; + bytes.try_into().map_err(|_| invalid()) + }; + let channel_id = match source["channel"].as_str() { + Some(id) => Some(id.parse().map_err(|_| invalid())?), + None => None, + }; + Ok(SearchHit { + event_id: bytes32(&source["event_id"])?, + kind: source["kind"] + .as_i64() + .and_then(|kind| i32::try_from(kind).ok()) + .ok_or_else(invalid)?, + pubkey: bytes32(&source["author"])?, + channel_id, + created_at: source["created_at"].as_i64().ok_or_else(invalid)?, + rank: hit["_score"].as_f64().unwrap_or(0.0) as f32, + }) +} + +/// Whether an HTTP status means OpenSearch refused the request itself: a +/// malformed or too large request. Auth failures, a missing index (404), +/// throttling (429) and server errors are the cluster's state, not the +/// request's. +fn rejects(status: u64) -> bool { + matches!(status, 400 | 413) +} + +/// The response body, or an error naming the status. +async fn checked(response: Response) -> Result { + let status = response.status_code(); + if !status.is_success() { + let description = format!("HTTP {}", status.as_u16()); + return Err(if rejects(u64::from(status.as_u16())) { + SearchError::Rejected(description) + } else { + SearchError::Engine(description) + }); + } + response.json().await.map_err(transport_error) +} + +fn transport_error(error: opensearch::Error) -> SearchError { + if error.is_timeout() { + SearchError::Engine("request timed out".into()) + } else { + SearchError::Engine("request failed".into()) + } +} diff --git a/crates/buzz-search/src/query.rs b/crates/buzz-search/src/query.rs index 170d600ecc..ef8fb2fd2a 100644 --- a/crates/buzz-search/src/query.rs +++ b/crates/buzz-search/src/query.rs @@ -225,7 +225,33 @@ fn push_tsquery( } } } -fn normalized_search_text(q: &str) -> Option { +/// The page a [`SearchQuery`] asks for, clamped the same way by every +/// backend. +pub(crate) struct PageBounds { + /// 1-indexed page, at most [`PAGE_MAX`]. + pub(crate) 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, + /// Hits before this page. + pub(crate) offset: i64, +} + +pub(crate) fn page_bounds(query: &SearchQuery) -> PageBounds { + let per_page = if query.per_page == 0 { + PER_PAGE_DEFAULT + } else { + query.per_page.clamp(1, PER_PAGE_MAX) + }; + let page = query.page.clamp(1, PAGE_MAX); + PageBounds { + page, + per_page, + offset: i64::from(page - 1) * i64::from(per_page), + } +} + +pub(crate) fn normalized_search_text(q: &str) -> Option { let trimmed = q.trim(); if trimmed.is_empty() { return None; @@ -275,14 +301,11 @@ pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result (PgPool, String) { - let url = std::env::var("BUZZ_TEST_DATABASE_URL").unwrap_or_else(|_| TEST_DB_URL.to_string()); - // The PostgreSQL lane supplies an isolated desired-state database. Outside - // that lane use a dedicated database with the production migrations. - let pool = PgPoolOptions::new() - .max_connections(5) - .connect(&url) - .await - .expect("connect test database"); - if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { - buzz_db::migration::run_migrations(&pool) - .await - .expect("apply production migrations"); - } - (pool, String::new()) -} - -async fn teardown(pool: PgPool, _schema: &str) { - pool.close().await; - // The test runner owns database cleanup. -} - -/// Insert a community row, return its id. -async fn mk_community(pool: &PgPool, host: &str) -> CommunityId { - let id = Uuid::new_v4(); - sqlx::query("INSERT INTO communities (id, host, signing_key) VALUES ($1, $2, $3)") - .bind(id) - .bind(host) - .bind(b"signingkey".as_slice()) - .execute(pool) - .await - .expect("insert community"); - CommunityId::from_uuid(id) -} - -/// Insert a minimal event. `created_at_secs` is unix seconds. -#[allow(clippy::too_many_arguments)] -async fn insert_event( - pool: &PgPool, - community: CommunityId, - id: [u8; 32], - pubkey: [u8; 32], - kind: i32, - content: &str, - channel_id: Option, - created_at_secs: i64, -) { - sqlx::query( - "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, channel_id) \ - VALUES ($1, $2, $3, to_timestamp($4), $5, '[]'::jsonb, $6, $7, $8)", - ) - .bind(community.as_uuid()) - .bind(&id[..]) - .bind(&pubkey[..]) - .bind(created_at_secs) - .bind(kind) - .bind(content) - .bind(b"signature".as_slice()) - .bind(channel_id) - .execute(pool) - .await - .expect("insert event"); -} - -fn rand_bytes32() -> [u8; 32] { - let mut out = [0u8; 32]; - let u = Uuid::new_v4(); - let bytes = u.as_bytes(); - out[..16].copy_from_slice(bytes); - out[16..].copy_from_slice(bytes); - out -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn search_finds_event_in_same_community() { - let (pool, schema) = setup().await; - - let c_a = mk_community(&pool, "a.example").await; - let evt_id = rand_bytes32(); - let pk = rand_bytes32(); - insert_event( - &pool, - c_a, - evt_id, - pk, - 9, - "hello wonderland — buzz everyone", - None, - 1700000000, - ) - .await; - - let svc = SearchService::new(pool.clone()); - let result = svc - .search(&SearchQuery { - community: c_a, - q: "wonderland".into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("search ok"); - - assert_eq!(result.hits.len(), 1); - assert_eq!(result.hits[0].event_id, evt_id); - assert_eq!(result.hits[0].kind, 9); - assert_eq!(result.hits[0].created_at, 1700000000); - assert!(result.hits[0].rank > 0.0); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn search_does_not_return_other_community_events() { - // The load-bearing test: event indexed under community A, query bound to - // community B → zero hits. - let (pool, schema) = setup().await; - - let c_a = mk_community(&pool, "a.example").await; - let c_b = mk_community(&pool, "b.example").await; - let pk = rand_bytes32(); - insert_event( - &pool, - c_a, - rand_bytes32(), - pk, - 9, - "only-in-a unique-token-xyz", - None, - 1700000000, - ) - .await; - - let svc = SearchService::new(pool.clone()); - let result_a = svc - .search(&SearchQuery { - community: c_a, - q: "unique-token-xyz".into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .unwrap(); - assert_eq!(result_a.hits.len(), 1, "A should see its own event"); - - let result_b = svc - .search(&SearchQuery { - community: c_b, - q: "unique-token-xyz".into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .unwrap(); - assert_eq!(result_b.hits.len(), 0, "B must not see A's event"); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn kind0_search_by_display_name_works_without_flattening() { - // The case I worried might regress without the kind:0 content-flattening - // hack. Postgres FTS over raw JSON content tokenizes through the - // punctuation and finds display_name/nip05 values. - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "a.example").await; - let pk = rand_bytes32(); - insert_event( - &pool, - c, - rand_bytes32(), - pk, - 0, - r#"{"display_name":"Alice Wonderland","name":"alice","nip05":"alice@buzz.app","about":"hello"}"#, - None, - 1700000000, - ) - .await; - - let svc = SearchService::new(pool.clone()); - for q in ["wonderland", "alice", "alice@buzz.app"] { - let r = svc - .search(&SearchQuery { - community: c, - q: q.to_string(), - channel_scope: ChannelScope::Any, - kinds: Some(vec![0]), - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .unwrap(); - assert_eq!(r.hits.len(), 1, "kind:0 query {q:?} should find Alice"); - } - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn short_kind0_prefix_prioritizes_exact_lexeme_on_a_noisy_page() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "short-profile-prefix.example").await; - let exact_id = rand_bytes32(); - insert_event( - &pool, - c, - exact_id, - rand_bytes32(), - 0, - r#"{"display_name":"jm"}"#, - None, - 1_700_000_000, - ) - .await; - - // These profiles all match jm:* and are newer than the exact name. Without - // exact-lexeme priority they consume the entire bounded first page. - for (i, display_name) in ["jma", "jmbravo", "jmcharlie", "jmdelta"] - .iter() - .enumerate() - { - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - 0, - &format!(r#"{{"display_name":"{display_name}"}}"#), - None, - 1_700_000_100 + i as i64, - ) - .await; - } - - let svc = SearchService::new(pool.clone()); - let first_page = svc - .search(&SearchQuery { - community: c, - q: "jm".into(), - channel_scope: ChannelScope::Any, - kinds: Some(vec![0]), - authors: None, - since: None, - until: None, - page: 1, - per_page: 3, - mode: buzz_search::SearchMode::Prefix, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("short profile prefix search ok"); - - assert_eq!(first_page.hits.len(), 3); - assert_eq!(first_page.hits[0].event_id, exact_id); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn prefix_mode_matches_final_token_prefix_without_changing_full_text() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "prefix.example").await; - let project_plan = rand_bytes32(); - let project_archive = rand_bytes32(); - let projectile_plan = rand_bytes32(); - insert_event( - &pool, - c, - project_plan, - rand_bytes32(), - 9, - "project planning milestone", - None, - 1_700_000_000, - ) - .await; - insert_event( - &pool, - c, - project_archive, - rand_bytes32(), - 9, - "project archive", - None, - 1_700_000_001, - ) - .await; - insert_event( - &pool, - c, - projectile_plan, - rand_bytes32(), - 9, - "projectile planning distractor", - None, - 1_700_000_002, - ) - .await; - // Rows whose own parser output contains a short lexeme, so a short - // trailing `:*` from punctuation in the query would match them. - let contraction = rand_bytes32(); - let hyphenated = rand_bytes32(); - let profile = rand_bytes32(); - insert_event( - &pool, - c, - contraction, - rand_bytes32(), - 9, - "don't panic", - None, - 1_700_000_003, - ) - .await; - insert_event( - &pool, - c, - hyphenated, - rand_bytes32(), - 9, - "pre-processing done", - None, - 1_700_000_004, - ) - .await; - insert_event( - &pool, - c, - profile, - rand_bytes32(), - 0, - r#"{"display_name":"prof"}"#, - None, - 1_700_000_005, - ) - .await; - - let svc = SearchService::new(pool.clone()); - let full_text = svc - .search(&SearchQuery { - community: c, - q: "pro".into(), - channel_scope: ChannelScope::Any, - kinds: Some(vec![9]), - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("full text search ok"); - assert!( - full_text.hits.is_empty(), - "plain full-text search must stay word/lexeme-based, got {:?}", - full_text - .hits - .iter() - .map(|h| h.event_id) - .collect::>() - ); - - let prefix = svc - .search(&SearchQuery { - community: c, - q: "pro".into(), - channel_scope: ChannelScope::Any, - kinds: Some(vec![9]), - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::Prefix, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("prefix search ok"); - let prefix_ids: Vec<[u8; 32]> = prefix.hits.iter().map(|h| h.event_id).collect(); - assert!(prefix_ids.contains(&project_plan)); - assert!(prefix_ids.contains(&project_archive)); - - // Non-profile prefix search returns no hits, in either sort, whatever the - // kinds and whatever completed words precede it, when the trailing token's - // `simple` parser output has a lexeme below three characters. Punctuation - // must not pad the count: `pr.`, `@pr` and `#pr` still yield `pr`, `don't` - // yields `t` and `pre-p` yields `p`. Each row would match without the - // minimum. kind:0-only stays one-character typeahead. - for (q, kinds, sort, expected) in [ - ( - "pr", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![], - ), - ( - " p ", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![], - ), - ( - "project pr", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![], - ), - ( - "project p ", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![], - ), - ("pr", None, buzz_search::SearchSort::Relevance, vec![]), - ( - "pr", - Some(vec![0, 9]), - buzz_search::SearchSort::Relevance, - vec![], - ), - ("pr", Some(vec![9]), buzz_search::SearchSort::Newest, vec![]), - ( - "pr.", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![], - ), - ( - "@pr", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![], - ), - ( - "#pr", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![], - ), - ( - "...p", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![], - ), - ( - "don't", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![], - ), - ( - "pre-p", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![], - ), - // Controls: padded but long enough, punctuation-only trailing token - // (no `:*` lexeme, so the completed word matches exactly), long - // hyphenated parts, a short completed word (exact, so not limited), - // and a one-character profile query. - ( - "pro.", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![project_plan, project_archive, projectile_plan, hyphenated], - ), - ( - "project ?", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![project_plan, project_archive], - ), - ( - "pre-pro", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![hyphenated], - ), - ( - "t pan", - Some(vec![9]), - buzz_search::SearchSort::Relevance, - vec![contraction], - ), - ( - "p", - Some(vec![0]), - buzz_search::SearchSort::Relevance, - vec![profile], - ), - ] { - let result = svc - .search(&SearchQuery { - community: c, - q: q.into(), - channel_scope: ChannelScope::Any, - kinds: kinds.clone(), - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::Prefix, - sort, - }) - .await - .expect("prefix search ok"); - let mut got: Vec<[u8; 32]> = result.hits.iter().map(|h| h.event_id).collect(); - let mut want = expected.clone(); - got.sort(); - want.sort(); - assert_eq!(got, want, "{q:?} {kinds:?} {sort:?}"); - } - // A short trailing lexeme is a prefix-mode rule only; full text still - // matches the contraction exactly. - let full_text_contraction = svc - .search(&SearchQuery { - community: c, - q: "don't".into(), - channel_scope: ChannelScope::Any, - kinds: Some(vec![9]), - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("full text search ok"); - assert_eq!( - full_text_contraction - .hits - .iter() - .map(|h| h.event_id) - .collect::>(), - vec![contraction] - ); - - let multi_token_prefix = svc - .search(&SearchQuery { - community: c, - q: "project pla".into(), - channel_scope: ChannelScope::Any, - kinds: Some(vec![9]), - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::Prefix, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("multi-token prefix search ok"); - assert_eq!(multi_token_prefix.hits.len(), 1); - assert_eq!(multi_token_prefix.hits[0].event_id, project_plan); - - let completed_token_is_exact = svc - .search(&SearchQuery { - community: c, - q: "project plan".into(), - channel_scope: ChannelScope::Any, - kinds: Some(vec![9]), - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::Prefix, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("completed-token exact + trailing-prefix search ok"); - let completed_ids: Vec<[u8; 32]> = completed_token_is_exact - .hits - .iter() - .map(|h| h.event_id) - .collect(); - assert!(completed_ids.contains(&project_plan)); - assert!( - !completed_ids.contains(&projectile_plan), - "completed tokens must stay exact; only the trailing token gets :*" - ); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn prefix_mode_handles_tsquery_boundary_punctuation() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "prefix-punctuation.example").await; - let hit_id = rand_bytes32(); - insert_event( - &pool, - c, - hit_id, - rand_bytes32(), - 9, - "operators ' : & | ( ) ! alpha beta marker", - None, - 1_700_000_000, - ) - .await; - - let svc = SearchService::new(pool.clone()); - let result = svc - .search(&SearchQuery { - community: c, - q: "operators ' : & | ( ) ! alpha bet".into(), - channel_scope: ChannelScope::Any, - kinds: Some(vec![9]), - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::Prefix, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("prefix punctuation search ok"); - - assert_eq!(result.hits.len(), 1); - assert_eq!(result.hits[0].event_id, hit_id); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn prefix_mode_preserves_storage_level_privacy_exclusions() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "prefix-privacy.example").await; - let token = "prefixprivacy_unique_marker"; - let control_id = rand_bytes32(); - - insert_event( - &pool, - c, - control_id, - rand_bytes32(), - 9, - &format!("public control {token}"), - None, - 1_700_000_000, - ) - .await; - - for (i, &kind) in [1059_u32, 30300, 30622, 44100, 44101].iter().enumerate() { - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - kind as i32, - &format!("private kind {kind} {token}"), - None, - 1_700_000_100 + i as i64, - ) - .await; - } - - let svc = SearchService::new(pool.clone()); - let result = svc - .search(&SearchQuery { - community: c, - q: "prefixpriv".into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::Prefix, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("prefix privacy search ok"); - - assert_eq!(result.hits.len(), 1); - assert_eq!(result.hits[0].event_id, control_id); - - teardown(pool, &schema).await; -} - -/// Prefix relevance (typeahead) ranks only the newest 1000 matches, so an -/// older, better-ranked message drops out, and its pages end with that -/// window; full-text and profile relevance still rank every match. -/// Mutation: rank every prefix match → the old message tops the first page; -/// window profiles too → the old profile drops off the first page. -#[tokio::test] -#[ignore = "requires Postgres"] -async fn prefix_relevance_ranks_only_the_newest_matches() { - let (pool, schema) = setup().await; - let c = mk_community(&pool, "rank-window.example").await; - let (old, old_profile) = (rand_bytes32(), rand_bytes32()); - for (id, kind) in [(old, 9), (old_profile, 0)] { - insert_event( - &pool, - c, - id, - rand_bytes32(), - kind, - "planning planning planning planning", - None, - 1_700_000_000, - ) - .await; - // 1000 newer, weaker matches fill the window. - sqlx::query( - "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig) \ - SELECT $1, sha256((g || '/' || $2)::bytea), sha256((g || '/' || $2)::bytea), \ - to_timestamp(1700000001 + g), $2, '[]'::jsonb, 'planning notes ' || g, 'signature' \ - FROM generate_series(1, 1000) g", - ) - .bind(c.as_uuid()) - .bind(kind) - .execute(&pool) - .await - .expect("insert newer matches"); - } - - let svc = SearchService::new(pool.clone()); - let query = |q: &str, mode, page| SearchQuery { - community: c, - q: q.into(), - channel_scope: ChannelScope::Any, - kinds: Some(vec![9]), - authors: None, - since: None, - until: None, - page, - per_page: 20, - mode, - sort: buzz_search::SearchSort::Relevance, - }; - let ids = |r: buzz_search::SearchResult| r.hits.iter().map(|h| h.event_id).collect::>(); - - let typeahead = ids(svc - .search(&query("plan", buzz_search::SearchMode::Prefix, 1)) - .await - .expect("prefix")); - assert_eq!(typeahead.len(), 20); - assert!(!typeahead.contains(&old), "outside the newest-1000 window"); - - let full_text = ids(svc - .search(&query("planning", buzz_search::SearchMode::FullText, 1)) - .await - .expect("full text")); - assert_eq!(full_text.first(), Some(&old), "full text ranks every match"); - - // Every page ranks the same window, so prefix pages end with it. - let last = ids(svc - .search(&query("plan", buzz_search::SearchMode::Prefix, 50)) - .await - .expect("page 50")); - assert_eq!(last.len(), 20); - assert!(!last.contains(&old)); - let past = svc - .search(&query("plan", buzz_search::SearchMode::Prefix, 51)) - .await - .expect("page 51"); - assert!(past.hits.is_empty(), "no page past the window"); - - let profiles = ids(svc - .search(&SearchQuery { - kinds: Some(vec![0]), - ..query("plan", buzz_search::SearchMode::Prefix, 1) - }) - .await - .expect("profile prefix")); - assert_eq!( - profiles.first(), - Some(&old_profile), - "profile typeahead ranks every match" - ); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn channel_scope_restricts_results() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "a.example").await; - // Channels need community_id since channels PK is (community_id, id). - let ch_a = Uuid::new_v4(); - let ch_b = Uuid::new_v4(); - sqlx::query("INSERT INTO channels (community_id, id, name, channel_type, created_by) VALUES ($1, $2, $3, 'stream'::channel_type, $4), ($1, $5, $6, 'stream'::channel_type, $4)") - .bind(c.as_uuid()) - .bind(ch_a) - .bind("ch-a") - .bind(b"\x01".repeat(32)) - .bind(ch_b) - .bind("ch-b") - .execute(&pool) - .await - .expect("insert channels"); - - let pk = rand_bytes32(); - insert_event( - &pool, - c, - rand_bytes32(), - pk, - 9, - "shared-token in ch-a", - Some(ch_a), - 1700000000, - ) - .await; - insert_event( - &pool, - c, - rand_bytes32(), - pk, - 9, - "shared-token in ch-b", - Some(ch_b), - 1700000001, - ) - .await; - insert_event( - &pool, - c, - rand_bytes32(), - pk, - 9, - "shared-token global", - None, - 1700000002, - ) - .await; - - let svc = SearchService::new(pool.clone()); - - // restrict to ch_a, exclude global - let r = svc - .search(&SearchQuery { - community: c, - q: "shared-token".into(), - channel_scope: ChannelScope::Channels(vec![ch_a]), - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .unwrap(); - assert_eq!(r.hits.len(), 1); - assert_eq!(r.hits[0].channel_id, Some(ch_a)); - - // restrict to ch_a + include global - let r = svc - .search(&SearchQuery { - community: c, - q: "shared-token".into(), - channel_scope: ChannelScope::ChannelsOrChannelLess(vec![ch_a]), - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .unwrap(); - assert_eq!(r.hits.len(), 2); - - // no channel constraint - let r = svc - .search(&SearchQuery { - community: c, - q: "shared-token".into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .unwrap(); - assert_eq!(r.hits.len(), 3); - - // empty accessible channels + exclude global = zero - let r = svc - .search(&SearchQuery { - community: c, - q: "shared-token".into(), - channel_scope: ChannelScope::Channels(vec![]), - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .unwrap(); - assert_eq!(r.hits.len(), 0); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn deleted_events_are_excluded() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "a.example").await; - let evt_id = rand_bytes32(); - let pk = rand_bytes32(); - insert_event(&pool, c, evt_id, pk, 9, "deleted-token-q", None, 1700000000).await; - - // Soft-delete - sqlx::query("UPDATE events SET deleted_at = NOW() WHERE community_id = $1 AND id = $2") - .bind(c.as_uuid()) - .bind(&evt_id[..]) - .execute(&pool) - .await - .expect("delete"); - - let svc = SearchService::new(pool.clone()); - let r = svc - .search(&SearchQuery { - community: c, - q: "deleted-token-q".into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .unwrap(); - assert!( - r.hits.is_empty(), - "soft-deleted events must not appear in FTS" - ); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn empty_query_returns_empty_result_no_roundtrip() { - let (pool, schema) = setup().await; - let c = mk_community(&pool, "a.example").await; - let svc = SearchService::new(pool.clone()); - - for q in ["", " "] { - let r = svc - .search(&SearchQuery { - community: c, - q: q.into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .unwrap(); - assert!( - r.hits.is_empty(), - "empty/whitespace query must return no hits" - ); - } - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn since_until_filters() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "a.example").await; - let pk = rand_bytes32(); - insert_event( - &pool, - c, - rand_bytes32(), - pk, - 9, - "time-token-zz at A", - None, - 1_700_000_000, - ) - .await; - insert_event( - &pool, - c, - rand_bytes32(), - pk, - 9, - "time-token-zz at B", - None, - 1_700_010_000, - ) - .await; - insert_event( - &pool, - c, - rand_bytes32(), - pk, - 9, - "time-token-zz at C", - None, - 1_700_020_000, - ) - .await; - - let svc = SearchService::new(pool.clone()); - - let r = svc - .search(&SearchQuery { - community: c, - q: "time-token-zz".into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: Some(1_700_005_000), - until: Some(1_700_015_000), - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .unwrap(); - assert_eq!(r.hits.len(), 1); - assert_eq!(r.hits[0].created_at, 1_700_010_000); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn pagination_works() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "a.example").await; - let pk = rand_bytes32(); - for i in 0..7 { - insert_event( - &pool, - c, - rand_bytes32(), - pk, - 9, - "page-token-qq", - None, - 1_700_000_000 + i, - ) - .await; - } - - let svc = SearchService::new(pool.clone()); - - let r = svc - .search(&SearchQuery { - community: c, - q: "page-token-qq".into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 3, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .unwrap(); - assert_eq!(r.hits.len(), 3); - - let r2 = svc - .search(&SearchQuery { - community: c, - q: "page-token-qq".into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 3, - per_page: 3, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .unwrap(); - assert_eq!( - r2.hits.len(), - 1, - "page 3 of 7 with per_page=3 should have 1 hit" - ); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn newest_sort_pages_by_time_then_id_within_scope() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "a.example").await; - let channel = Uuid::new_v4(); - let pk = rand_bytes32(); - let most_relevant = [9u8; 32]; - let tie_low = [1u8; 32]; - let tie_high = [2u8; 32]; - let newest = [3u8; 32]; - let rows = [ - ( - most_relevant, - "sortword sortword sortword sortword", - 1_700_000_000, - ), - (tie_high, "sortword once", 1_700_000_100), - (tie_low, "sortword once", 1_700_000_100), - (newest, "sortword once", 1_700_000_200), - ]; - for (id, content, created_at) in rows { - insert_event(&pool, c, id, pk, 9, content, Some(channel), created_at).await; - } - // Newer than every scoped row, but outside the requested channel scope. - insert_event( - &pool, - c, - rand_bytes32(), - pk, - 9, - "sortword once", - Some(Uuid::new_v4()), - 1_700_000_300, - ) - .await; - - let svc = SearchService::new(pool.clone()); - let page = |page, sort| { - let svc = svc.clone(); - async move { - svc.search(&SearchQuery { - community: c, - q: "sortword".into(), - channel_scope: ChannelScope::Channels(vec![channel]), - kinds: None, - authors: None, - since: None, - until: None, - page, - per_page: 2, - mode: buzz_search::SearchMode::FullText, - sort, - }) - .await - .unwrap() - .hits - .into_iter() - .map(|hit| hit.event_id) - .collect::>() - } - }; - - let newest_order = [ - page(1, buzz_search::SearchSort::Newest).await, - page(2, buzz_search::SearchSort::Newest).await, - page(3, buzz_search::SearchSort::Newest).await, - ] - .concat(); - assert_eq!(newest_order, vec![newest, tie_low, tie_high, most_relevant]); - assert_eq!( - page(1, buzz_search::SearchSort::Relevance).await[0], - most_relevant - ); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn channel_less_only_excludes_per_channel_events() { - // Closes the row-3 fence hole: in the legacy 2x2 shape, both - // `Some(vec![]) + true` and `None + true` silently broadened to all - // community channels rather than restricting to channel-less events. - // `ChannelScope::ChannelLessOnly` is the variant that the old type - // could not express. - // - // Adversarial check: mutate this test's expectation to `>= 2` and the - // assertion goes red against the new SQL `AND channel_id IS NULL`, - // proving the predicate bites. Mutate `query.rs` `ChannelLessOnly` arm - // to a no-op (the `Any` semantic the old code emitted) and this test - // also goes red — three hits instead of one — proving the fix is the - // emitted predicate, not the variant name. - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "a.example").await; - let ch_a = Uuid::new_v4(); - let ch_b = Uuid::new_v4(); - sqlx::query("INSERT INTO channels (community_id, id, name, channel_type, created_by) VALUES ($1, $2, $3, 'stream'::channel_type, $4), ($1, $5, $6, 'stream'::channel_type, $4)") - .bind(c.as_uuid()) - .bind(ch_a) - .bind("ch-a") - .bind(b"\x01".repeat(32)) - .bind(ch_b) - .bind("ch-b") - .execute(&pool) - .await - .expect("insert channels"); - - let pk = rand_bytes32(); - insert_event( - &pool, - c, - rand_bytes32(), - pk, - 9, - "fence-token in ch-a", - Some(ch_a), - 1_700_000_000, - ) - .await; - insert_event( - &pool, - c, - rand_bytes32(), - pk, - 9, - "fence-token in ch-b", - Some(ch_b), - 1_700_000_001, - ) - .await; - insert_event( - &pool, - c, - rand_bytes32(), - pk, - 9, - "fence-token channel-less", - None, - 1_700_000_002, - ) - .await; - - let svc = SearchService::new(pool.clone()); - - let r = svc - .search(&SearchQuery { - community: c, - q: "fence-token".into(), - channel_scope: ChannelScope::ChannelLessOnly, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .unwrap(); - assert_eq!( - r.hits.len(), - 1, - "ChannelLessOnly must return only the channel_id IS NULL row" - ); - assert_eq!(r.hits[0].channel_id, None); - - teardown(pool, &schema).await; -} - -/// Search-input hardening: NUL bytes are not valid Postgres text-search input. -/// Sanitize before calling `websearch_to_tsquery` so the bridge does not turn -/// adversarial search text into HTTP 500s. -#[tokio::test] -#[ignore = "requires Postgres"] -async fn nul_bytes_in_query_are_sanitized() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "nul.example").await; - let evt_id = rand_bytes32(); - insert_event( - &pool, - c, - evt_id, - rand_bytes32(), - 9, - "foo bar search text", - None, - 1_700_000_000, - ) - .await; - - let svc = SearchService::new(pool.clone()); - let result = svc - .search(&SearchQuery { - community: c, - q: "foo\0bar".into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("NUL-containing search query should not bubble a Postgres error"); - - assert_eq!(result.hits.len(), 1); - assert_eq!(result.hits[0].event_id, evt_id); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn enormous_page_number_is_clamped() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "page-clamp.example").await; - for i in 0..5 { - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - 9, - "clamp-token", - None, - 1_700_000_000 + i, - ) - .await; - } - - let svc = SearchService::new(pool.clone()); - let result = svc - .search(&SearchQuery { - community: c, - q: "clamp-token".into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: u32::MAX, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("huge page number should be bounded, not error"); - - assert_eq!(result.page, 1000); - assert!(result.hits.is_empty()); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn very_long_query_is_bounded_before_pg_parse() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "long-query.example").await; - let svc = SearchService::new(pool.clone()); - let result = svc - .search(&SearchQuery { - community: c, - q: "x".repeat(10_000), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("long search query should be capped before Postgres parses it"); - - assert!(result.hits.is_empty()); - - teardown(pool, &schema).await; -} - -/// Privacy regression gate: the storage layer MUST NOT make these kinds -/// searchable. The migration's `search_tsv` generated column emits NULL -/// for excluded kinds, so a `search_tsv @@ query` probe never matches. -/// -/// Set kept in sync with the pre-rewrite skip in `handlers/event.rs:287-290` -/// on `main`: -/// - 1059 = `KIND_GIFT_WRAP` (NIP-17 ciphertext) -/// - 30300 = `KIND_EVENT_REMINDER` (in `AUTHOR_ONLY_KINDS`) -/// - 30622 = `KIND_DM_VISIBILITY` (per-viewer private hide state) -/// - 44100 = `KIND_MEMBER_ADDED_NOTIFICATION` (p-gated membership notice) -/// - 44101 = `KIND_MEMBER_REMOVED_NOTIFICATION` (p-gated membership notice) -/// - 44200 = `KIND_AGENT_TURN_METRIC` (NIP-AM: p-gated encrypted turn metrics) -/// -/// All seven events are inserted with the same unique token in their content -/// so a single search query exercises every kind in one round-trip. Only -/// the kind:9 control must surface — the excluded kinds must not. -/// -/// Mutate-bite: drop the `CASE WHEN kind IN (…)` from the generated column -/// (revert to `to_tsvector('simple', content)`) → excluded events surface → -/// restore. -#[tokio::test] -#[ignore = "requires Postgres"] -async fn excluded_kinds_are_storage_level_unsearchable() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "privacy.example").await; - let token = "privacykinds_unique_marker_xyzzy"; - - // kind:9 control — MUST be searchable. - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - 9, - &format!("public chat — {token}"), - None, - 1_700_000_000, - ) - .await; - - // kind:1059 gift wrap (NIP-17 ciphertext) — MUST NOT be searchable. - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - 1059, - &format!("gift wrap — {token}"), - None, - 1_700_000_001, - ) - .await; - - // kind:30300 event reminder (AUTHOR_ONLY_KINDS) — MUST NOT be searchable. - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - 30300, - &format!("reminder — {token}"), - None, - 1_700_000_002, - ) - .await; - - // kind:30622 DM visibility snapshot — MUST NOT be searchable. - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - 30622, - &format!("dm visibility — {token}"), - None, - 1_700_000_003, - ) - .await; - - // kind:44100 member-added notification — p-gated and MUST NOT be searchable. - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - KIND_MEMBER_ADDED_NOTIFICATION as i32, - &format!("member added — {token}"), - None, - 1_700_000_004, - ) - .await; - - // kind:44101 member-removed notification — p-gated and MUST NOT be searchable. - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - KIND_MEMBER_REMOVED_NOTIFICATION as i32, - &format!("member removed — {token}"), - None, - 1_700_000_005, - ) - .await; - - // kind:44200 agent turn metric — p-gated NIP-44 ciphertext and MUST NOT be searchable. - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - KIND_AGENT_TURN_METRIC as i32, - &format!("agent turn metric — {token}"), - None, - 1_700_000_006, - ) - .await; - - let svc = SearchService::new(pool.clone()); - let result = svc - .search(&SearchQuery { - community: c, - q: token.into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("search ok"); - - let kinds: Vec = result.hits.iter().map(|h| h.kind).collect(); - - // Positive: kind:9 surfaces (control — proves the search index works at all). - assert!( - kinds.contains(&9), - "kind:9 control row MUST be searchable, got kinds={kinds:?}", - ); - - // Negative (load-bearing): each excluded kind MUST NOT surface. - for forbidden in [ - 1059, - 30300, - 30622, - KIND_MEMBER_ADDED_NOTIFICATION as i32, - KIND_MEMBER_REMOVED_NOTIFICATION as i32, - KIND_AGENT_TURN_METRIC as i32, - ] { - assert!( - !kinds.contains(&forbidden), - "kind:{forbidden} MUST NOT be searchable — \ - privacy regression in `search_tsv` generated column. kinds={kinds:?}", - ); - } - - // Tight bound: exactly one hit (the control). Catches any future - // weakening where some-but-not-all excluded kinds surface. - assert_eq!( - result.hits.len(), - 1, - "expected exactly 1 hit (the kind:9 control), got {} (kinds={kinds:?})", - result.hits.len(), - ); - - teardown(pool, &schema).await; -} - -/// Tripwire: every Rust-side author-only kind MUST be excluded from -/// `search_tsv` at the storage layer. -/// -/// The schema generated column hard-codes the privacy skip-set, while -/// `AUTHOR_ONLY_KINDS` is a Rust const. If a future author-only kind is added -/// without the matching schema migration, search would still spend FTS budget on -/// those private hits before the relay post-filter rejects them. Catch that -/// drift here by inserting one row per author-only kind and proving only the -/// public kind:9 control is searchable. -#[tokio::test] -#[ignore = "requires Postgres"] -async fn author_only_kinds_are_storage_level_unsearchable() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "author-only-tripwire.example").await; - let token = "authoronly_tripwire_marker_qwerty"; - - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - 9, - &format!("public control — {token}"), - None, - 1_700_000_000, - ) - .await; - - for (i, &kind) in AUTHOR_ONLY_KINDS.iter().enumerate() { - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - kind as i32, - &format!("author-only kind:{kind} — {token}"), - None, - 1_700_000_100 + i as i64, - ) - .await; - } - - let svc = SearchService::new(pool.clone()); - let result = svc - .search(&SearchQuery { - community: c, - q: token.into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 100, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("search ok"); - - let kinds: Vec = result.hits.iter().map(|h| h.kind).collect(); - assert!( - kinds.contains(&9), - "kind:9 control row MUST be searchable, got kinds={kinds:?}", - ); - - for &kind in AUTHOR_ONLY_KINDS { - assert!( - !kinds.contains(&(kind as i32)), - "AUTHOR_ONLY kind:{kind} MUST NOT be searchable — \ - schema skip-set is missing this kind. AUTHOR_ONLY_KINDS={AUTHOR_ONLY_KINDS:?}, \ - hits={kinds:?}", - ); - } - - assert_eq!( - result.hits.len(), - 1, - "expected exactly 1 hit (the kind:9 control), got {} (kinds={kinds:?})", - result.hits.len(), - ); - - teardown(pool, &schema).await; -} - -/// Tripwire: every Rust-side `P_GATED_KINDS` entry that is *persistent* (not -/// in the ephemeral 20000–29999 range) MUST be excluded from `search_tsv` at -/// the storage layer. -/// -/// L2 (the filter-level `#p` gate in `p_gated_filters_authorized`) prevents -/// reachable leaks today, but it is Rust logic — a future bug or new exempt -/// search entry point could surface tokenized content from these kinds. The -/// L1 NULL tsvector is the unbreakable backstop: `@@` mathematically cannot -/// match NULL. This test catches the drift where someone adds a persistent -/// kind to `P_GATED_KINDS` without the matching `schema/schema.sql` + -/// `migrations/0001_initial_schema.sql` skip-set update. -/// -/// Ephemeral kinds (20000–29999) are skipped: they are never stored, so the -/// storage-layer defense does not apply to them regardless of the schema -/// CASE. `p_gated_filters_authorized` remains their sole defense by design. -/// -/// Companion to `author_only_kinds_are_storage_level_unsearchable`: that test -/// covers `AUTHOR_ONLY_KINDS` drift; this one covers `P_GATED_KINDS` -/// persistent-subset drift. Together they tripwire both Rust-side privacy -/// constants against the schema literal. -#[tokio::test] -#[ignore = "requires Postgres"] -async fn p_gated_persistent_kinds_have_storage_null_tsvector() { - let (pool, schema) = setup().await; - - let c = mk_community(&pool, "p-gated-tripwire.example").await; - let token = "pgated_tripwire_marker_qwerty"; - - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - 9, - &format!("public control — {token}"), - None, - 1_700_000_000, - ) - .await; - - let persistent: Vec = P_GATED_KINDS - .iter() - .copied() - .filter(|&k| !buzz_core::kind::is_ephemeral(k)) - .collect(); - assert!( - !persistent.is_empty(), - "P_GATED_KINDS must include at least one persistent kind for this \ - test to be meaningful; got {P_GATED_KINDS:?}", - ); - - for (i, &kind) in persistent.iter().enumerate() { - insert_event( - &pool, - c, - rand_bytes32(), - rand_bytes32(), - kind as i32, - &format!("p-gated kind:{kind} — {token}"), - None, - 1_700_000_100 + i as i64, - ) - .await; - } - - let svc = SearchService::new(pool.clone()); - let result = svc - .search(&SearchQuery { - community: c, - q: token.into(), - channel_scope: ChannelScope::Any, - kinds: None, - authors: None, - since: None, - until: None, - page: 1, - per_page: 100, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }) - .await - .expect("search ok"); - - let kinds: Vec = result.hits.iter().map(|h| h.kind).collect(); - assert!( - kinds.contains(&9), - "kind:9 control row MUST be searchable, got kinds={kinds:?}", - ); - - for &kind in &persistent { - assert!( - !kinds.contains(&(kind as i32)), - "P_GATED persistent kind:{kind} MUST NOT be searchable — \ - schema NULL tsvector skip-set is missing this kind. Defense \ - reduces to L2 (filter-level `#p` gate) alone. \ - P_GATED_KINDS={P_GATED_KINDS:?}, hits={kinds:?}", - ); - } - - assert_eq!( - result.hits.len(), - 1, - "expected exactly 1 hit (the kind:9 control), got {} (kinds={kinds:?})", - result.hits.len(), - ); - - teardown(pool, &schema).await; -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn artifact_search_uses_only_live_current_head() { - let (pool, schema) = setup().await; - let community = mk_community(&pool, "artifact-search.example").await; - let pk = rand_bytes32(); - let old = rand_bytes32(); - let head = rand_bytes32(); - let artifact = Uuid::new_v4(); - insert_event( - &pool, - community, - old, - pk, - 45010, - "artifactneedle old", - None, - 1700000000, - ) - .await; - insert_event( - &pool, - community, - head, - pk, - 45010, - "artifactneedle current", - None, - 1700000001, - ) - .await; - sqlx::query("INSERT INTO artifact_heads(community_id,artifact_id,event_id,channel_id,artifact_type) VALUES($1,$2,$3,$4,'buzz.task')") - .bind(community.as_uuid()).bind(artifact).bind(head.as_slice()).bind(Uuid::new_v4()).execute(&pool).await.unwrap(); - let svc = SearchService::new(pool.clone()); - let query = SearchQuery { - community, - q: "artifactneedle".into(), - channel_scope: ChannelScope::Any, - kinds: Some(vec![45010]), - authors: None, - since: None, - until: None, - page: 1, - per_page: 10, - mode: buzz_search::SearchMode::FullText, - sort: buzz_search::SearchSort::Relevance, - }; - let result = svc.search(&query).await.unwrap(); - assert_eq!(result.hits.len(), 1); - assert_eq!(result.hits[0].event_id, head); - sqlx::query("UPDATE artifact_heads SET deleted=true WHERE community_id=$1 AND artifact_id=$2") - .bind(community.as_uuid()) - .bind(artifact) - .execute(&pool) - .await - .unwrap(); - let result = svc.search(&query).await.unwrap(); - assert!(result.hits.is_empty()); - teardown(pool, &schema).await; +search_suite_tests! { + Backend::Postgres; + #[ignore = "requires Postgres"] + fn search_finds_event_in_same_community, + fn search_does_not_return_other_community_events, + fn kind0_search_by_display_name_works_without_flattening, + fn short_kind0_prefix_prioritizes_exact_lexeme_on_a_noisy_page, + fn prefix_mode_matches_final_token_prefix_without_changing_full_text, + fn prefix_mode_handles_tsquery_boundary_punctuation, + fn prefix_mode_preserves_storage_level_privacy_exclusions, + fn prefix_relevance_ranks_only_the_newest_matches, + fn authors_filter_restricts_results, + fn channel_scope_restricts_results, + fn channel_scope_of_thousands_of_channels, + fn deleted_events_are_excluded, + fn empty_query_returns_empty_result_no_roundtrip, + fn since_until_filters, + fn pagination_works, + fn newest_sort_pages_by_time_then_id_within_scope, + fn channel_less_only_excludes_per_channel_events, + fn nul_bytes_in_query_are_sanitized, + fn enormous_page_number_is_clamped, + fn very_long_query_is_bounded_before_pg_parse, + fn excluded_kinds_are_storage_level_unsearchable, + fn author_only_kinds_are_storage_level_unsearchable, + fn p_gated_persistent_kinds_have_storage_null_tsvector, + fn artifact_search_uses_only_live_current_head, } /// Insert a current kind:0 profile; returns its event id. diff --git a/crates/buzz-search/tests/postgres_opensearch_search.rs b/crates/buzz-search/tests/postgres_opensearch_search.rs new file mode 100644 index 0000000000..8ae2196404 --- /dev/null +++ b/crates/buzz-search/tests/postgres_opensearch_search.rs @@ -0,0 +1,346 @@ +//! Message search through the OpenSearch backend. +//! +//! The shared [`search_suite`] cases run against OpenSearch, then sync tests +//! write through the database layer's normal paths and wait for the indexer. +//! Needs Postgres (run through `scripts/postgres-test-run.sh -p buzz-search +//! --tests`) and an OpenSearch cluster at `BUZZ_TEST_OPENSEARCH_URL` +//! (default `http://localhost:9200`; `docker compose up -d opensearch`). + +mod search_suite; + +use search_suite::{search_suite_tests, Backend}; + +// Not run here, with the reason: +// - kind0_* and artifact_*: kinds 0 and 45010 are not searchable kinds; +// - prefix_*: prefix mode is reworked with prefix analysis (issue 06); +// - deleted_events_are_excluded: deletes reach the index in issue 04. +search_suite_tests! { + Backend::OpenSearch; + #[ignore = "requires Postgres and OpenSearch"] + fn search_finds_event_in_same_community, + fn search_does_not_return_other_community_events, + fn authors_filter_restricts_results, + fn channel_scope_restricts_results, + fn channel_scope_of_thousands_of_channels, + fn empty_query_returns_empty_result_no_roundtrip, + fn since_until_filters, + fn pagination_works, + fn newest_sort_pages_by_time_then_id_within_scope, + fn channel_less_only_excludes_per_channel_events, + fn nul_bytes_in_query_are_sanitized, + fn enormous_page_number_is_clamped, + fn very_long_query_is_bounded_before_pg_parse, + fn excluded_kinds_are_storage_level_unsearchable, + fn author_only_kinds_are_storage_level_unsearchable, + fn p_gated_persistent_kinds_have_storage_null_tsvector, +} + +use std::time::Duration; + +use buzz_core::CommunityId; +use buzz_db::{search_outbox, Db, DbConfig}; +use buzz_search::indexer::Indexer; +use buzz_search::opensearch::{OpenSearchConfig, SearchIndex}; +use buzz_search::{ChannelScope, SearchMode, SearchQuery, SearchService, SearchSort}; +use nostr::{Event, EventBuilder, Keys, Kind}; +use opensearch::http::transport::Transport; +use opensearch::indices::{IndicesCreateParts, IndicesExistsParts}; +use opensearch::{GetParts, OpenSearch}; +use uuid::Uuid; + +const TEST_OPENSEARCH_URL: &str = "http://localhost:9200"; + +fn opensearch_url() -> String { + std::env::var("BUZZ_TEST_OPENSEARCH_URL").unwrap_or_else(|_| TEST_OPENSEARCH_URL.into()) +} + +/// A database layer with the search outbox on, as the relay runs it when +/// OpenSearch is configured. +async fn sync_db() -> Db { + let (pool, _) = search_suite::setup().await; + search_outbox::enable(&pool).await.expect("enable outbox"); + pool.close().await; + Db::new(&DbConfig { + database_url: std::env::var("BUZZ_TEST_DATABASE_URL") + .unwrap_or_else(|_| search_suite::TEST_DB_URL.into()), + ..DbConfig::default() + }) + .await + .expect("connect database layer") +} + +/// A new index of the test's own, and its index-name prefix. +async fn sync_index() -> (SearchIndex, String) { + let prefix = format!("test-{}-", Uuid::new_v4().simple()); + let index = SearchIndex::new(&OpenSearchConfig { + url: opensearch_url(), + basic_auth: None, + index_prefix: prefix.clone(), + }) + .expect("OpenSearch client"); + index.ensure().await.expect("create index"); + (index, prefix) +} + +fn message(keys: &Keys, content: &str) -> Event { + EventBuilder::new(Kind::Custom(9), content) + .sign_with_keys(keys) + .expect("sign") +} + +/// Wait until the indexer has drained the outbox, then make its writes +/// visible to search. +async fn wait_until_indexed(db: &Db, index: &SearchIndex) { + tokio::time::timeout(Duration::from_secs(30), async { + while search_outbox::depth(db.pool()).await.expect("outbox depth") > 0 { + tokio::time::sleep(Duration::from_millis(50)).await; + } + }) + .await + .expect("the indexer drains the outbox"); + index.refresh().await.expect("refresh"); +} + +async fn find(service: &SearchService, community: CommunityId, q: &str) -> Vec<[u8; 32]> { + service + .search(&SearchQuery { + community, + q: q.into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: SearchMode::FullText, + sort: SearchSort::Newest, + }) + .await + .expect("search") + .hits + .into_iter() + .map(|hit| hit.event_id) + .collect() +} + +/// An admitted message becomes searchable once the lease-holding indexer +/// catches up; a rolled-back one never does, and its text is not stored in +/// the document source. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn admitted_messages_become_searchable() { + let db = sync_db().await; + let (index, prefix) = sync_index().await; + let community = search_suite::mk_community(db.pool(), "sync.example").await; + let keys = Keys::generate(); + let indexer = tokio::spawn(Indexer::new(db.clone(), index.clone()).run()); + + let kept = message(&keys, "syncword kept"); + db.insert_event(community, &kept, None) + .await + .expect("insert"); + let mut tx = db + .begin_event_write_transaction(community) + .await + .expect("begin"); + buzz_db::event::insert_event_in_transaction( + &mut tx, + &message(&keys, "syncword rolled back"), + None, + ) + .await + .expect("insert"); + tx.rollback().await.expect("rollback"); + + wait_until_indexed(&db, &index).await; + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + assert_eq!( + find(&service, community, "syncword").await, + vec![*kept.id.as_bytes()] + ); + + let client = OpenSearch::new(Transport::single_node(&opensearch_url()).expect("transport")); + let document: serde_json::Value = client + .get(GetParts::IndexId( + &format!("{prefix}messages"), + &format!("{}:{}", community.as_uuid(), kept.id.to_hex()), + )) + .send() + .await + .expect("get document") + .json() + .await + .expect("document body"); + assert_eq!(document["found"], true); + assert_eq!(document["_source"]["kind"], 9); + assert!( + document["_source"].get("content").is_none(), + "message text must not be stored: {document}" + ); + + indexer.abort(); + index.delete().await.expect("delete index"); +} + +/// Stopping the instance holding the indexer lease lets another take over, +/// and rows queued meanwhile are indexed. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn the_indexer_lease_hands_over() { + let db = sync_db().await; + let (index, _) = sync_index().await; + let community = search_suite::mk_community(db.pool(), "lease.example").await; + let keys = Keys::generate(); + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + + let first = tokio::spawn(Indexer::new(db.clone(), index.clone()).run()); + let before = message(&keys, "leaseword before"); + db.insert_event(community, &before, None) + .await + .expect("insert"); + wait_until_indexed(&db, &index).await; + + // The first instance holds the lease, so the second only waits. + let second = tokio::spawn(Indexer::new(db.clone(), index.clone()).run()); + first.abort(); + let _ = first.await; + let after = message(&keys, "leaseword after"); + db.insert_event(community, &after, None) + .await + .expect("insert"); + wait_until_indexed(&db, &index).await; + assert_eq!( + find(&service, community, "leaseword").await, + vec![*after.id.as_bytes(), *before.id.as_bytes()] + ); + + second.abort(); + index.delete().await.expect("delete index"); +} + +/// Admission never calls OpenSearch: with it unreachable, messages are +/// stored and their rows stay queued until indexing succeeds. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn admission_queues_while_opensearch_is_unreachable() { + let db = sync_db().await; + let community = search_suite::mk_community(db.pool(), "down.example").await; + let unreachable = SearchIndex::new(&OpenSearchConfig { + url: "http://127.0.0.1:9".into(), + basic_auth: None, + index_prefix: "unreachable-".into(), + }) + .expect("client"); + db.insert_event(community, &message(&Keys::generate(), "downword"), None) + .await + .expect("a message is stored while OpenSearch is down"); + + Indexer::new(db.clone(), unreachable) + .drain() + .await + .expect_err("indexing fails while OpenSearch is down"); + assert_eq!(search_outbox::depth(db.pool()).await.expect("depth"), 1); + + let (index, _) = sync_index().await; + Indexer::new(db.clone(), index.clone()) + .drain() + .await + .expect("indexing succeeds once OpenSearch is back"); + index.refresh().await.expect("refresh"); + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + assert_eq!(find(&service, community, "downword").await.len(), 1); + index.delete().await.expect("delete index"); +} + +fn raw_client() -> OpenSearch { + OpenSearch::new(Transport::single_node(&opensearch_url()).expect("transport")) +} + +/// A batch the cluster rejects leaves its rows queued and its community +/// skipped, while other communities are still indexed in the same pass. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn a_rejected_community_does_not_hold_back_others() { + let db = sync_db().await; + // An index whose `content` is a keyword: a term longer than 32766 bytes + // is rejected per document with HTTP 400. + let prefix = format!("test-{}-", Uuid::new_v4().simple()); + let response = raw_client() + .indices() + .create(IndicesCreateParts::Index(&format!("{prefix}messages-v1"))) + .body(serde_json::json!({ + "mappings": { "properties": { "content": { "type": "keyword" } } }, + "aliases": { format!("{prefix}messages"): {} } + })) + .send() + .await + .expect("create index"); + assert!(response.status_code().is_success()); + let index = SearchIndex::new(&OpenSearchConfig { + url: opensearch_url(), + basic_auth: None, + index_prefix: prefix, + }) + .expect("client"); + + let poisoned = search_suite::mk_community(db.pool(), "poisoned.example").await; + let healthy = search_suite::mk_community(db.pool(), "healthy.example").await; + let keys = Keys::generate(); + db.insert_event(poisoned, &message(&keys, &"x".repeat(40_000)), None) + .await + .expect("insert oversized term"); + db.insert_event(healthy, &message(&keys, "fine"), None) + .await + .expect("insert"); + + let error = Indexer::new(db.clone(), index.clone()) + .drain() + .await + .expect_err("the pass reports the rejected batch"); + assert!(error.to_string().contains("rejected"), "{error}"); + let queued: Vec = sqlx::query_scalar("SELECT community_id FROM search_outbox") + .fetch_all(db.pool()) + .await + .expect("queued rows"); + assert_eq!(queued, vec![*poisoned.as_uuid()]); + index.delete().await.expect("delete index"); +} + +/// Writes go through the alias and never create an index themselves, so a +/// deleted index cannot come back with a dynamic mapping; `ensure` restores +/// it with its alias. +#[tokio::test] +#[ignore = "requires Postgres and OpenSearch"] +async fn writes_never_create_an_index() { + let db = sync_db().await; + let (index, prefix) = sync_index().await; + index.delete().await.expect("delete index"); + let community = search_suite::mk_community(db.pool(), "gone.example").await; + db.insert_event(community, &message(&Keys::generate(), "orphan"), None) + .await + .expect("insert"); + + let indexer = Indexer::new(db.clone(), index.clone()); + indexer + .drain() + .await + .expect_err("a write without the index fails"); + let exists = raw_client() + .indices() + .exists(IndicesExistsParts::Index(&[&format!( + "{prefix}messages-v1" + )])) + .send() + .await + .expect("exists"); + assert_eq!(exists.status_code().as_u16(), 404, "no index was created"); + assert_eq!(search_outbox::depth(db.pool()).await.expect("depth"), 1); + + index.ensure().await.expect("recreate index"); + indexer.drain().await.expect("indexing resumes"); + index.refresh().await.expect("refresh"); + let service = SearchService::with_opensearch(db.pool().clone(), index.clone()); + assert_eq!(find(&service, community, "orphan").await.len(), 1); + index.delete().await.expect("delete index"); +} diff --git a/crates/buzz-search/tests/search_suite/mod.rs b/crates/buzz-search/tests/search_suite/mod.rs new file mode 100644 index 0000000000..0dc8f00fb1 --- /dev/null +++ b/crates/buzz-search/tests/search_suite/mod.rs @@ -0,0 +1,2118 @@ +//! Search behavior every [`SearchService`] backend must share. +//! +//! Each case is a function taking a [`Backend`]; a test binary turns the +//! cases it runs into tests with [`search_suite_tests!`]. The cases write +//! fixture rows straight into Postgres (queuing each event in the search +//! outbox), then search through [`SearchService::search`], so they check +//! search behavior, not the write path. On OpenSearch every search first +//! drains the outbox and refreshes the index. +//! +//! Run through `scripts/postgres-test-run.sh -p buzz-search --tests` for a +//! fresh desired-state database per test. Outside that lane, point +//! BUZZ_TEST_DATABASE_URL at a disposable dedicated database; fixtures use +//! the production migrator and unique community IDs. + +// Each test binary uses its own subset of the cases and helpers. +#![allow(dead_code)] + +use buzz_core::{ + kind::{ + AUTHOR_ONLY_KINDS, KIND_AGENT_TURN_METRIC, KIND_MEMBER_ADDED_NOTIFICATION, + KIND_MEMBER_REMOVED_NOTIFICATION, P_GATED_KINDS, + }, + CommunityId, +}; +use buzz_search::indexer::Indexer; +use buzz_search::opensearch::{OpenSearchConfig, SearchIndex}; +use buzz_search::{ChannelScope, SearchError, SearchQuery, SearchResult, SearchService}; +use sqlx::{postgres::PgPoolOptions, PgPool}; +use uuid::Uuid; + +/// Turns each `fn case` into a test against `$backend`. The attribute after +/// the backend goes on every test, so each binary states what its tests need. +macro_rules! search_suite_tests { + ($backend:expr; #[$meta:meta] $(fn $case:ident),+ $(,)?) => { + $( + #[tokio::test] + #[$meta] + async fn $case() { + search_suite::$case($backend).await; + } + )+ + }; +} +pub(crate) use search_suite_tests; + +/// The engine a case searches with. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Backend { + /// Postgres full-text search. + Postgres, + /// The OpenSearch index at `BUZZ_TEST_OPENSEARCH_URL`, kept in sync by + /// the indexer. + OpenSearch, +} + +/// A test's search service, for the backend under test. +pub struct Fixture { + service: SearchService, + opensearch: Option<(Indexer, SearchIndex)>, +} + +impl Fixture { + /// Connect to the test database and build the backend's search service. + /// For OpenSearch, that includes a new index of the test's own. + pub async fn setup(backend: Backend) -> (PgPool, Fixture) { + let (pool, _schema) = setup().await; + let fixture = match backend { + Backend::Postgres => Fixture { + service: SearchService::new(pool.clone()), + opensearch: None, + }, + Backend::OpenSearch => { + let index = test_index().await; + Fixture { + service: SearchService::with_opensearch(pool.clone(), index.clone()), + opensearch: Some(( + Indexer::new(buzz_db::Db::from_pool(pool.clone()), index.clone()), + index, + )), + } + } + }; + (pool, fixture) + } + + /// The search service under test. + pub fn service(&self) -> Searcher<'_> { + Searcher { fixture: self } + } + + /// Release the fixture's resources. + pub async fn teardown(self, pool: PgPool) { + if let Some((_, index)) = self.opensearch { + index.delete().await.expect("delete test index"); + } + teardown(pool, "").await; + } +} + +/// [`SearchService`] for a case: each search first lets the backend catch up +/// with the rows the case wrote. +#[derive(Clone, Copy)] +pub struct Searcher<'a> { + fixture: &'a Fixture, +} + +impl Searcher<'_> { + /// [`SearchService::search`], once the backend has caught up. + pub async fn search(&self, query: &SearchQuery) -> Result { + if let Some((indexer, index)) = &self.fixture.opensearch { + indexer.drain().await.expect("drain the search outbox"); + index.refresh().await.expect("refresh the test index"); + } + self.fixture.service.search(query).await + } +} + +/// A new, empty message index of the calling test's own on the test cluster. +pub async fn test_index() -> SearchIndex { + let index = SearchIndex::new(&OpenSearchConfig { + url: std::env::var("BUZZ_TEST_OPENSEARCH_URL") + .unwrap_or_else(|_| "http://localhost:9200".to_string()), + basic_auth: None, + index_prefix: format!("test-{}-", Uuid::new_v4().simple()), + }) + .expect("OpenSearch client"); + index.ensure().await.expect("create test index"); + index +} + +pub const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1 -- local test-only credentials +pub async fn setup() -> (PgPool, String) { + let url = std::env::var("BUZZ_TEST_DATABASE_URL").unwrap_or_else(|_| TEST_DB_URL.to_string()); + // The PostgreSQL lane supplies an isolated desired-state database. Outside + // that lane use a dedicated database with the production migrations. + let pool = PgPoolOptions::new() + .max_connections(5) + .connect(&url) + .await + .expect("connect test database"); + if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { + buzz_db::migration::run_migrations(&pool) + .await + .expect("apply production migrations"); + } + (pool, String::new()) +} + +pub async fn teardown(pool: PgPool, _schema: &str) { + pool.close().await; + // The test runner owns database cleanup. +} + +/// Insert a community row, return its id. +pub async fn mk_community(pool: &PgPool, host: &str) -> CommunityId { + let id = Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host, signing_key) VALUES ($1, $2, $3)") + .bind(id) + .bind(host) + .bind(b"signingkey".as_slice()) + .execute(pool) + .await + .expect("insert community"); + CommunityId::from_uuid(id) +} + +/// Insert a minimal event, and queue it in the search outbox as admission +/// would. `created_at_secs` is unix seconds. +#[allow(clippy::too_many_arguments)] +pub async fn insert_event( + pool: &PgPool, + community: CommunityId, + id: [u8; 32], + pubkey: [u8; 32], + kind: i32, + content: &str, + channel_id: Option, + created_at_secs: i64, +) { + sqlx::query( + "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, channel_id) \ + VALUES ($1, $2, $3, to_timestamp($4), $5, '[]'::jsonb, $6, $7, $8)", + ) + .bind(community.as_uuid()) + .bind(&id[..]) + .bind(&pubkey[..]) + .bind(created_at_secs) + .bind(kind) + .bind(content) + .bind(b"signature".as_slice()) + .bind(channel_id) + .execute(pool) + .await + .expect("insert event"); + // Postgres search ignores the outbox; the indexer skips kinds that are + // not searchable. + sqlx::query( + "INSERT INTO search_outbox (community_id, event_id, event_created_at) \ + VALUES ($1, $2, to_timestamp($3))", + ) + .bind(community.as_uuid()) + .bind(&id[..]) + .bind(created_at_secs) + .execute(pool) + .await + .expect("queue event for indexing"); +} + +pub fn rand_bytes32() -> [u8; 32] { + let mut out = [0u8; 32]; + let u = Uuid::new_v4(); + let bytes = u.as_bytes(); + out[..16].copy_from_slice(bytes); + out[16..].copy_from_slice(bytes); + out +} + +pub async fn search_finds_event_in_same_community(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c_a = mk_community(&pool, "a.example").await; + let evt_id = rand_bytes32(); + let pk = rand_bytes32(); + insert_event( + &pool, + c_a, + evt_id, + pk, + 9, + "hello wonderland — buzz everyone", + None, + 1700000000, + ) + .await; + + let svc = fx.service(); + let result = svc + .search(&SearchQuery { + community: c_a, + q: "wonderland".into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("search ok"); + + assert_eq!(result.hits.len(), 1); + assert_eq!(result.hits[0].event_id, evt_id); + assert_eq!(result.hits[0].kind, 9); + assert_eq!(result.hits[0].created_at, 1700000000); + assert!(result.hits[0].rank > 0.0); + + fx.teardown(pool).await; +} + +pub async fn search_does_not_return_other_community_events(backend: Backend) { + // The load-bearing test: event indexed under community A, query bound to + // community B → zero hits. + let (pool, fx) = Fixture::setup(backend).await; + + let c_a = mk_community(&pool, "a.example").await; + let c_b = mk_community(&pool, "b.example").await; + let pk = rand_bytes32(); + insert_event( + &pool, + c_a, + rand_bytes32(), + pk, + 9, + "only-in-a unique-token-xyz", + None, + 1700000000, + ) + .await; + + let svc = fx.service(); + let result_a = svc + .search(&SearchQuery { + community: c_a, + q: "unique-token-xyz".into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .unwrap(); + assert_eq!(result_a.hits.len(), 1, "A should see its own event"); + + let result_b = svc + .search(&SearchQuery { + community: c_b, + q: "unique-token-xyz".into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .unwrap(); + assert_eq!(result_b.hits.len(), 0, "B must not see A's event"); + + fx.teardown(pool).await; +} + +pub async fn kind0_search_by_display_name_works_without_flattening(backend: Backend) { + // The case I worried might regress without the kind:0 content-flattening + // hack. Postgres FTS over raw JSON content tokenizes through the + // punctuation and finds display_name/nip05 values. + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "a.example").await; + let pk = rand_bytes32(); + insert_event( + &pool, + c, + rand_bytes32(), + pk, + 0, + r#"{"display_name":"Alice Wonderland","name":"alice","nip05":"alice@buzz.app","about":"hello"}"#, + None, + 1700000000, + ) + .await; + + let svc = fx.service(); + for q in ["wonderland", "alice", "alice@buzz.app"] { + let r = svc + .search(&SearchQuery { + community: c, + q: q.to_string(), + channel_scope: ChannelScope::Any, + kinds: Some(vec![0]), + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .unwrap(); + assert_eq!(r.hits.len(), 1, "kind:0 query {q:?} should find Alice"); + } + + fx.teardown(pool).await; +} + +pub async fn short_kind0_prefix_prioritizes_exact_lexeme_on_a_noisy_page(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "short-profile-prefix.example").await; + let exact_id = rand_bytes32(); + insert_event( + &pool, + c, + exact_id, + rand_bytes32(), + 0, + r#"{"display_name":"jm"}"#, + None, + 1_700_000_000, + ) + .await; + + // These profiles all match jm:* and are newer than the exact name. Without + // exact-lexeme priority they consume the entire bounded first page. + for (i, display_name) in ["jma", "jmbravo", "jmcharlie", "jmdelta"] + .iter() + .enumerate() + { + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + 0, + &format!(r#"{{"display_name":"{display_name}"}}"#), + None, + 1_700_000_100 + i as i64, + ) + .await; + } + + let svc = fx.service(); + let first_page = svc + .search(&SearchQuery { + community: c, + q: "jm".into(), + channel_scope: ChannelScope::Any, + kinds: Some(vec![0]), + authors: None, + since: None, + until: None, + page: 1, + per_page: 3, + mode: buzz_search::SearchMode::Prefix, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("short profile prefix search ok"); + + assert_eq!(first_page.hits.len(), 3); + assert_eq!(first_page.hits[0].event_id, exact_id); + + fx.teardown(pool).await; +} + +pub async fn prefix_mode_matches_final_token_prefix_without_changing_full_text(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "prefix.example").await; + let project_plan = rand_bytes32(); + let project_archive = rand_bytes32(); + let projectile_plan = rand_bytes32(); + insert_event( + &pool, + c, + project_plan, + rand_bytes32(), + 9, + "project planning milestone", + None, + 1_700_000_000, + ) + .await; + insert_event( + &pool, + c, + project_archive, + rand_bytes32(), + 9, + "project archive", + None, + 1_700_000_001, + ) + .await; + insert_event( + &pool, + c, + projectile_plan, + rand_bytes32(), + 9, + "projectile planning distractor", + None, + 1_700_000_002, + ) + .await; + // Rows whose own parser output contains a short lexeme, so a short + // trailing `:*` from punctuation in the query would match them. + let contraction = rand_bytes32(); + let hyphenated = rand_bytes32(); + let profile = rand_bytes32(); + insert_event( + &pool, + c, + contraction, + rand_bytes32(), + 9, + "don't panic", + None, + 1_700_000_003, + ) + .await; + insert_event( + &pool, + c, + hyphenated, + rand_bytes32(), + 9, + "pre-processing done", + None, + 1_700_000_004, + ) + .await; + insert_event( + &pool, + c, + profile, + rand_bytes32(), + 0, + r#"{"display_name":"prof"}"#, + None, + 1_700_000_005, + ) + .await; + + let svc = fx.service(); + let full_text = svc + .search(&SearchQuery { + community: c, + q: "pro".into(), + channel_scope: ChannelScope::Any, + kinds: Some(vec![9]), + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("full text search ok"); + assert!( + full_text.hits.is_empty(), + "plain full-text search must stay word/lexeme-based, got {:?}", + full_text + .hits + .iter() + .map(|h| h.event_id) + .collect::>() + ); + + let prefix = svc + .search(&SearchQuery { + community: c, + q: "pro".into(), + channel_scope: ChannelScope::Any, + kinds: Some(vec![9]), + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::Prefix, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("prefix search ok"); + let prefix_ids: Vec<[u8; 32]> = prefix.hits.iter().map(|h| h.event_id).collect(); + assert!(prefix_ids.contains(&project_plan)); + assert!(prefix_ids.contains(&project_archive)); + + // Non-profile prefix search returns no hits, in either sort, whatever the + // kinds and whatever completed words precede it, when the trailing token's + // `simple` parser output has a lexeme below three characters. Punctuation + // must not pad the count: `pr.`, `@pr` and `#pr` still yield `pr`, `don't` + // yields `t` and `pre-p` yields `p`. Each row would match without the + // minimum. kind:0-only stays one-character typeahead. + for (q, kinds, sort, expected) in [ + ( + "pr", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![], + ), + ( + " p ", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![], + ), + ( + "project pr", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![], + ), + ( + "project p ", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![], + ), + ("pr", None, buzz_search::SearchSort::Relevance, vec![]), + ( + "pr", + Some(vec![0, 9]), + buzz_search::SearchSort::Relevance, + vec![], + ), + ("pr", Some(vec![9]), buzz_search::SearchSort::Newest, vec![]), + ( + "pr.", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![], + ), + ( + "@pr", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![], + ), + ( + "#pr", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![], + ), + ( + "...p", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![], + ), + ( + "don't", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![], + ), + ( + "pre-p", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![], + ), + // Controls: padded but long enough, punctuation-only trailing token + // (no `:*` lexeme, so the completed word matches exactly), long + // hyphenated parts, a short completed word (exact, so not limited), + // and a one-character profile query. + ( + "pro.", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![project_plan, project_archive, projectile_plan, hyphenated], + ), + ( + "project ?", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![project_plan, project_archive], + ), + ( + "pre-pro", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![hyphenated], + ), + ( + "t pan", + Some(vec![9]), + buzz_search::SearchSort::Relevance, + vec![contraction], + ), + ( + "p", + Some(vec![0]), + buzz_search::SearchSort::Relevance, + vec![profile], + ), + ] { + let result = svc + .search(&SearchQuery { + community: c, + q: q.into(), + channel_scope: ChannelScope::Any, + kinds: kinds.clone(), + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::Prefix, + sort, + }) + .await + .expect("prefix search ok"); + let mut got: Vec<[u8; 32]> = result.hits.iter().map(|h| h.event_id).collect(); + let mut want = expected.clone(); + got.sort(); + want.sort(); + assert_eq!(got, want, "{q:?} {kinds:?} {sort:?}"); + } + // A short trailing lexeme is a prefix-mode rule only; full text still + // matches the contraction exactly. + let full_text_contraction = svc + .search(&SearchQuery { + community: c, + q: "don't".into(), + channel_scope: ChannelScope::Any, + kinds: Some(vec![9]), + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("full text search ok"); + assert_eq!( + full_text_contraction + .hits + .iter() + .map(|h| h.event_id) + .collect::>(), + vec![contraction] + ); + + let multi_token_prefix = svc + .search(&SearchQuery { + community: c, + q: "project pla".into(), + channel_scope: ChannelScope::Any, + kinds: Some(vec![9]), + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::Prefix, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("multi-token prefix search ok"); + assert_eq!(multi_token_prefix.hits.len(), 1); + assert_eq!(multi_token_prefix.hits[0].event_id, project_plan); + + let completed_token_is_exact = svc + .search(&SearchQuery { + community: c, + q: "project plan".into(), + channel_scope: ChannelScope::Any, + kinds: Some(vec![9]), + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::Prefix, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("completed-token exact + trailing-prefix search ok"); + let completed_ids: Vec<[u8; 32]> = completed_token_is_exact + .hits + .iter() + .map(|h| h.event_id) + .collect(); + assert!(completed_ids.contains(&project_plan)); + assert!( + !completed_ids.contains(&projectile_plan), + "completed tokens must stay exact; only the trailing token gets :*" + ); + + fx.teardown(pool).await; +} + +pub async fn prefix_mode_handles_tsquery_boundary_punctuation(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "prefix-punctuation.example").await; + let hit_id = rand_bytes32(); + insert_event( + &pool, + c, + hit_id, + rand_bytes32(), + 9, + "operators ' : & | ( ) ! alpha beta marker", + None, + 1_700_000_000, + ) + .await; + + let svc = fx.service(); + let result = svc + .search(&SearchQuery { + community: c, + q: "operators ' : & | ( ) ! alpha bet".into(), + channel_scope: ChannelScope::Any, + kinds: Some(vec![9]), + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::Prefix, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("prefix punctuation search ok"); + + assert_eq!(result.hits.len(), 1); + assert_eq!(result.hits[0].event_id, hit_id); + + fx.teardown(pool).await; +} + +pub async fn prefix_mode_preserves_storage_level_privacy_exclusions(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "prefix-privacy.example").await; + let token = "prefixprivacy_unique_marker"; + let control_id = rand_bytes32(); + + insert_event( + &pool, + c, + control_id, + rand_bytes32(), + 9, + &format!("public control {token}"), + None, + 1_700_000_000, + ) + .await; + + for (i, &kind) in [1059_u32, 30300, 30622, 44100, 44101].iter().enumerate() { + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + kind as i32, + &format!("private kind {kind} {token}"), + None, + 1_700_000_100 + i as i64, + ) + .await; + } + + let svc = fx.service(); + let result = svc + .search(&SearchQuery { + community: c, + q: "prefixpriv".into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::Prefix, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("prefix privacy search ok"); + + assert_eq!(result.hits.len(), 1); + assert_eq!(result.hits[0].event_id, control_id); + + fx.teardown(pool).await; +} + +/// Prefix relevance (typeahead) ranks only the newest 1000 matches, so an +/// older, better-ranked message drops out, and its pages end with that +/// window; full-text and profile relevance still rank every match. +/// Mutation: rank every prefix match → the old message tops the first page; +/// window profiles too → the old profile drops off the first page. +pub async fn prefix_relevance_ranks_only_the_newest_matches(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + let c = mk_community(&pool, "rank-window.example").await; + let (old, old_profile) = (rand_bytes32(), rand_bytes32()); + for (id, kind) in [(old, 9), (old_profile, 0)] { + insert_event( + &pool, + c, + id, + rand_bytes32(), + kind, + "planning planning planning planning", + None, + 1_700_000_000, + ) + .await; + // 1000 newer, weaker matches fill the window. + sqlx::query( + "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig) \ + SELECT $1, sha256((g || '/' || $2)::bytea), sha256((g || '/' || $2)::bytea), \ + to_timestamp(1700000001 + g), $2, '[]'::jsonb, 'planning notes ' || g, 'signature' \ + FROM generate_series(1, 1000) g", + ) + .bind(c.as_uuid()) + .bind(kind) + .execute(&pool) + .await + .expect("insert newer matches"); + } + + let svc = fx.service(); + let query = |q: &str, mode, page| SearchQuery { + community: c, + q: q.into(), + channel_scope: ChannelScope::Any, + kinds: Some(vec![9]), + authors: None, + since: None, + until: None, + page, + per_page: 20, + mode, + sort: buzz_search::SearchSort::Relevance, + }; + let ids = |r: buzz_search::SearchResult| r.hits.iter().map(|h| h.event_id).collect::>(); + + let typeahead = ids(svc + .search(&query("plan", buzz_search::SearchMode::Prefix, 1)) + .await + .expect("prefix")); + assert_eq!(typeahead.len(), 20); + assert!(!typeahead.contains(&old), "outside the newest-1000 window"); + + let full_text = ids(svc + .search(&query("planning", buzz_search::SearchMode::FullText, 1)) + .await + .expect("full text")); + assert_eq!(full_text.first(), Some(&old), "full text ranks every match"); + + // Every page ranks the same window, so prefix pages end with it. + let last = ids(svc + .search(&query("plan", buzz_search::SearchMode::Prefix, 50)) + .await + .expect("page 50")); + assert_eq!(last.len(), 20); + assert!(!last.contains(&old)); + let past = svc + .search(&query("plan", buzz_search::SearchMode::Prefix, 51)) + .await + .expect("page 51"); + assert!(past.hits.is_empty(), "no page past the window"); + + let profiles = ids(svc + .search(&SearchQuery { + kinds: Some(vec![0]), + ..query("plan", buzz_search::SearchMode::Prefix, 1) + }) + .await + .expect("profile prefix")); + assert_eq!( + profiles.first(), + Some(&old_profile), + "profile typeahead ranks every match" + ); + + fx.teardown(pool).await; +} + +pub async fn authors_filter_restricts_results(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + let c = mk_community(&pool, "a.example").await; + let alice = rand_bytes32(); + let bob = rand_bytes32(); + let carol = rand_bytes32(); + let alice_id = rand_bytes32(); + let bob_id = rand_bytes32(); + insert_event( + &pool, + c, + alice_id, + alice, + 9, + "authorword from alice", + None, + 1_700_000_000, + ) + .await; + insert_event( + &pool, + c, + bob_id, + bob, + 9, + "authorword from bob", + None, + 1_700_000_001, + ) + .await; + insert_event( + &pool, + c, + rand_bytes32(), + carol, + 9, + "authorword from carol", + None, + 1_700_000_002, + ) + .await; + + let svc = fx.service(); + let search = |authors: Option>>| { + let query = SearchQuery { + community: c, + q: "authorword".into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Newest, + }; + async move { + svc.search(&query) + .await + .expect("search") + .hits + .into_iter() + .map(|hit| hit.event_id) + .collect::>() + } + }; + + assert_eq!( + search(Some(vec![alice.to_vec(), bob.to_vec()])).await, + vec![bob_id, alice_id] + ); + assert_eq!(search(None).await.len(), 3); + + fx.teardown(pool).await; +} + +pub async fn channel_scope_restricts_results(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "a.example").await; + // Channels need community_id since channels PK is (community_id, id). + let ch_a = Uuid::new_v4(); + let ch_b = Uuid::new_v4(); + sqlx::query("INSERT INTO channels (community_id, id, name, channel_type, created_by) VALUES ($1, $2, $3, 'stream'::channel_type, $4), ($1, $5, $6, 'stream'::channel_type, $4)") + .bind(c.as_uuid()) + .bind(ch_a) + .bind("ch-a") + .bind(b"\x01".repeat(32)) + .bind(ch_b) + .bind("ch-b") + .execute(&pool) + .await + .expect("insert channels"); + + let pk = rand_bytes32(); + insert_event( + &pool, + c, + rand_bytes32(), + pk, + 9, + "shared-token in ch-a", + Some(ch_a), + 1700000000, + ) + .await; + insert_event( + &pool, + c, + rand_bytes32(), + pk, + 9, + "shared-token in ch-b", + Some(ch_b), + 1700000001, + ) + .await; + insert_event( + &pool, + c, + rand_bytes32(), + pk, + 9, + "shared-token global", + None, + 1700000002, + ) + .await; + + let svc = fx.service(); + + // restrict to ch_a, exclude global + let r = svc + .search(&SearchQuery { + community: c, + q: "shared-token".into(), + channel_scope: ChannelScope::Channels(vec![ch_a]), + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .unwrap(); + assert_eq!(r.hits.len(), 1); + assert_eq!(r.hits[0].channel_id, Some(ch_a)); + + // restrict to ch_a + include global + let r = svc + .search(&SearchQuery { + community: c, + q: "shared-token".into(), + channel_scope: ChannelScope::ChannelsOrChannelLess(vec![ch_a]), + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .unwrap(); + assert_eq!(r.hits.len(), 2); + + // no channel constraint + let r = svc + .search(&SearchQuery { + community: c, + q: "shared-token".into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .unwrap(); + assert_eq!(r.hits.len(), 3); + + // empty accessible channels + exclude global = zero + let r = svc + .search(&SearchQuery { + community: c, + q: "shared-token".into(), + channel_scope: ChannelScope::Channels(vec![]), + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .unwrap(); + assert_eq!(r.hits.len(), 0); + + fx.teardown(pool).await; +} + +pub async fn deleted_events_are_excluded(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "a.example").await; + let evt_id = rand_bytes32(); + let pk = rand_bytes32(); + insert_event(&pool, c, evt_id, pk, 9, "deleted-token-q", None, 1700000000).await; + + // Soft-delete + sqlx::query("UPDATE events SET deleted_at = NOW() WHERE community_id = $1 AND id = $2") + .bind(c.as_uuid()) + .bind(&evt_id[..]) + .execute(&pool) + .await + .expect("delete"); + + let svc = fx.service(); + let r = svc + .search(&SearchQuery { + community: c, + q: "deleted-token-q".into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .unwrap(); + assert!( + r.hits.is_empty(), + "soft-deleted events must not appear in FTS" + ); + + fx.teardown(pool).await; +} + +pub async fn empty_query_returns_empty_result_no_roundtrip(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + let c = mk_community(&pool, "a.example").await; + let svc = fx.service(); + + for q in ["", " "] { + let r = svc + .search(&SearchQuery { + community: c, + q: q.into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .unwrap(); + assert!( + r.hits.is_empty(), + "empty/whitespace query must return no hits" + ); + } + + fx.teardown(pool).await; +} + +pub async fn since_until_filters(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "a.example").await; + let pk = rand_bytes32(); + insert_event( + &pool, + c, + rand_bytes32(), + pk, + 9, + "time-token-zz at A", + None, + 1_700_000_000, + ) + .await; + insert_event( + &pool, + c, + rand_bytes32(), + pk, + 9, + "time-token-zz at B", + None, + 1_700_010_000, + ) + .await; + insert_event( + &pool, + c, + rand_bytes32(), + pk, + 9, + "time-token-zz at C", + None, + 1_700_020_000, + ) + .await; + + let svc = fx.service(); + + let r = svc + .search(&SearchQuery { + community: c, + q: "time-token-zz".into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: Some(1_700_005_000), + until: Some(1_700_015_000), + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .unwrap(); + assert_eq!(r.hits.len(), 1); + assert_eq!(r.hits[0].created_at, 1_700_010_000); + + fx.teardown(pool).await; +} + +pub async fn pagination_works(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "a.example").await; + let pk = rand_bytes32(); + for i in 0..7 { + insert_event( + &pool, + c, + rand_bytes32(), + pk, + 9, + "page-token-qq", + None, + 1_700_000_000 + i, + ) + .await; + } + + let svc = fx.service(); + + let r = svc + .search(&SearchQuery { + community: c, + q: "page-token-qq".into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 3, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .unwrap(); + assert_eq!(r.hits.len(), 3); + + let r2 = svc + .search(&SearchQuery { + community: c, + q: "page-token-qq".into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 3, + per_page: 3, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .unwrap(); + assert_eq!( + r2.hits.len(), + 1, + "page 3 of 7 with per_page=3 should have 1 hit" + ); + + fx.teardown(pool).await; +} + +pub async fn newest_sort_pages_by_time_then_id_within_scope(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "a.example").await; + let channel = Uuid::new_v4(); + let pk = rand_bytes32(); + let most_relevant = [9u8; 32]; + let tie_low = [1u8; 32]; + let tie_high = [2u8; 32]; + let newest = [3u8; 32]; + let rows = [ + ( + most_relevant, + "sortword sortword sortword sortword", + 1_700_000_000, + ), + (tie_high, "sortword once", 1_700_000_100), + (tie_low, "sortword once", 1_700_000_100), + (newest, "sortword once", 1_700_000_200), + ]; + for (id, content, created_at) in rows { + insert_event(&pool, c, id, pk, 9, content, Some(channel), created_at).await; + } + // Newer than every scoped row, but outside the requested channel scope. + insert_event( + &pool, + c, + rand_bytes32(), + pk, + 9, + "sortword once", + Some(Uuid::new_v4()), + 1_700_000_300, + ) + .await; + + let svc = fx.service(); + let page = |page, sort| async move { + svc.search(&SearchQuery { + community: c, + q: "sortword".into(), + channel_scope: ChannelScope::Channels(vec![channel]), + kinds: None, + authors: None, + since: None, + until: None, + page, + per_page: 2, + mode: buzz_search::SearchMode::FullText, + sort, + }) + .await + .unwrap() + .hits + .into_iter() + .map(|hit| hit.event_id) + .collect::>() + }; + + let newest_order = [ + page(1, buzz_search::SearchSort::Newest).await, + page(2, buzz_search::SearchSort::Newest).await, + page(3, buzz_search::SearchSort::Newest).await, + ] + .concat(); + assert_eq!(newest_order, vec![newest, tie_low, tie_high, most_relevant]); + assert_eq!( + page(1, buzz_search::SearchSort::Relevance).await[0], + most_relevant + ); + + fx.teardown(pool).await; +} + +/// A heavy DM user's scope holds thousands of channel ids; the whole scope +/// must reach the backend. +pub async fn channel_scope_of_thousands_of_channels(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + let c = mk_community(&pool, "a.example").await; + let inside = Uuid::new_v4(); + let outside = Uuid::new_v4(); + let hit = rand_bytes32(); + let pk = rand_bytes32(); + insert_event( + &pool, + c, + hit, + pk, + 9, + "scopeword inside", + Some(inside), + 1_700_000_000, + ) + .await; + insert_event( + &pool, + c, + rand_bytes32(), + pk, + 9, + "scopeword outside", + Some(outside), + 1_700_000_001, + ) + .await; + let mut scope: Vec = (0..4_999).map(|_| Uuid::new_v4()).collect(); + scope.push(inside); + + let result = fx + .service() + .search(&SearchQuery { + community: c, + q: "scopeword".into(), + channel_scope: ChannelScope::Channels(scope), + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("search"); + let ids: Vec<_> = result.hits.iter().map(|hit| hit.event_id).collect(); + assert_eq!(ids, vec![hit]); + + fx.teardown(pool).await; +} + +pub async fn channel_less_only_excludes_per_channel_events(backend: Backend) { + // Closes the row-3 fence hole: in the legacy 2x2 shape, both + // `Some(vec![]) + true` and `None + true` silently broadened to all + // community channels rather than restricting to channel-less events. + // `ChannelScope::ChannelLessOnly` is the variant that the old type + // could not express. + // + // Adversarial check: mutate this test's expectation to `>= 2` and the + // assertion goes red against the new SQL `AND channel_id IS NULL`, + // proving the predicate bites. Mutate `query.rs` `ChannelLessOnly` arm + // to a no-op (the `Any` semantic the old code emitted) and this test + // also goes red — three hits instead of one — proving the fix is the + // emitted predicate, not the variant name. + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "a.example").await; + let ch_a = Uuid::new_v4(); + let ch_b = Uuid::new_v4(); + sqlx::query("INSERT INTO channels (community_id, id, name, channel_type, created_by) VALUES ($1, $2, $3, 'stream'::channel_type, $4), ($1, $5, $6, 'stream'::channel_type, $4)") + .bind(c.as_uuid()) + .bind(ch_a) + .bind("ch-a") + .bind(b"\x01".repeat(32)) + .bind(ch_b) + .bind("ch-b") + .execute(&pool) + .await + .expect("insert channels"); + + let pk = rand_bytes32(); + insert_event( + &pool, + c, + rand_bytes32(), + pk, + 9, + "fence-token in ch-a", + Some(ch_a), + 1_700_000_000, + ) + .await; + insert_event( + &pool, + c, + rand_bytes32(), + pk, + 9, + "fence-token in ch-b", + Some(ch_b), + 1_700_000_001, + ) + .await; + insert_event( + &pool, + c, + rand_bytes32(), + pk, + 9, + "fence-token channel-less", + None, + 1_700_000_002, + ) + .await; + + let svc = fx.service(); + + let r = svc + .search(&SearchQuery { + community: c, + q: "fence-token".into(), + channel_scope: ChannelScope::ChannelLessOnly, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .unwrap(); + assert_eq!( + r.hits.len(), + 1, + "ChannelLessOnly must return only the channel_id IS NULL row" + ); + assert_eq!(r.hits[0].channel_id, None); + + fx.teardown(pool).await; +} + +/// Search-input hardening: NUL bytes are not valid Postgres text-search input. +/// Sanitize before calling `websearch_to_tsquery` so the bridge does not turn +/// adversarial search text into HTTP 500s. +pub async fn nul_bytes_in_query_are_sanitized(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "nul.example").await; + let evt_id = rand_bytes32(); + insert_event( + &pool, + c, + evt_id, + rand_bytes32(), + 9, + "foo bar search text", + None, + 1_700_000_000, + ) + .await; + + let svc = fx.service(); + let result = svc + .search(&SearchQuery { + community: c, + q: "foo\0bar".into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("NUL-containing search query should not bubble a Postgres error"); + + assert_eq!(result.hits.len(), 1); + assert_eq!(result.hits[0].event_id, evt_id); + + fx.teardown(pool).await; +} + +pub async fn enormous_page_number_is_clamped(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "page-clamp.example").await; + for i in 0..5 { + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + 9, + "clamp-token", + None, + 1_700_000_000 + i, + ) + .await; + } + + let svc = fx.service(); + let result = svc + .search(&SearchQuery { + community: c, + q: "clamp-token".into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: u32::MAX, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("huge page number should be bounded, not error"); + + assert_eq!(result.page, 1000); + assert!(result.hits.is_empty()); + + fx.teardown(pool).await; +} + +pub async fn very_long_query_is_bounded_before_pg_parse(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "long-query.example").await; + let svc = fx.service(); + let result = svc + .search(&SearchQuery { + community: c, + q: "x".repeat(10_000), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("long search query should be capped before Postgres parses it"); + + assert!(result.hits.is_empty()); + + fx.teardown(pool).await; +} + +/// Privacy regression gate: the storage layer MUST NOT make these kinds +/// searchable. The migration's `search_tsv` generated column emits NULL +/// for excluded kinds, so a `search_tsv @@ query` probe never matches. +/// +/// Set kept in sync with the pre-rewrite skip in `handlers/event.rs:287-290` +/// on `main`: +/// - 1059 = `KIND_GIFT_WRAP` (NIP-17 ciphertext) +/// - 30300 = `KIND_EVENT_REMINDER` (in `AUTHOR_ONLY_KINDS`) +/// - 30622 = `KIND_DM_VISIBILITY` (per-viewer private hide state) +/// - 44100 = `KIND_MEMBER_ADDED_NOTIFICATION` (p-gated membership notice) +/// - 44101 = `KIND_MEMBER_REMOVED_NOTIFICATION` (p-gated membership notice) +/// - 44200 = `KIND_AGENT_TURN_METRIC` (NIP-AM: p-gated encrypted turn metrics) +/// +/// All seven events are inserted with the same unique token in their content +/// so a single search query exercises every kind in one round-trip. Only +/// the kind:9 control must surface — the excluded kinds must not. +/// +/// Mutate-bite: drop the `CASE WHEN kind IN (…)` from the generated column +/// (revert to `to_tsvector('simple', content)`) → excluded events surface → +/// restore. +pub async fn excluded_kinds_are_storage_level_unsearchable(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "privacy.example").await; + let token = "privacykinds_unique_marker_xyzzy"; + + // kind:9 control — MUST be searchable. + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + 9, + &format!("public chat — {token}"), + None, + 1_700_000_000, + ) + .await; + + // kind:1059 gift wrap (NIP-17 ciphertext) — MUST NOT be searchable. + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + 1059, + &format!("gift wrap — {token}"), + None, + 1_700_000_001, + ) + .await; + + // kind:30300 event reminder (AUTHOR_ONLY_KINDS) — MUST NOT be searchable. + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + 30300, + &format!("reminder — {token}"), + None, + 1_700_000_002, + ) + .await; + + // kind:30622 DM visibility snapshot — MUST NOT be searchable. + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + 30622, + &format!("dm visibility — {token}"), + None, + 1_700_000_003, + ) + .await; + + // kind:44100 member-added notification — p-gated and MUST NOT be searchable. + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + KIND_MEMBER_ADDED_NOTIFICATION as i32, + &format!("member added — {token}"), + None, + 1_700_000_004, + ) + .await; + + // kind:44101 member-removed notification — p-gated and MUST NOT be searchable. + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + KIND_MEMBER_REMOVED_NOTIFICATION as i32, + &format!("member removed — {token}"), + None, + 1_700_000_005, + ) + .await; + + // kind:44200 agent turn metric — p-gated NIP-44 ciphertext and MUST NOT be searchable. + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + KIND_AGENT_TURN_METRIC as i32, + &format!("agent turn metric — {token}"), + None, + 1_700_000_006, + ) + .await; + + let svc = fx.service(); + let result = svc + .search(&SearchQuery { + community: c, + q: token.into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("search ok"); + + let kinds: Vec = result.hits.iter().map(|h| h.kind).collect(); + + // Positive: kind:9 surfaces (control — proves the search index works at all). + assert!( + kinds.contains(&9), + "kind:9 control row MUST be searchable, got kinds={kinds:?}", + ); + + // Negative (load-bearing): each excluded kind MUST NOT surface. + for forbidden in [ + 1059, + 30300, + 30622, + KIND_MEMBER_ADDED_NOTIFICATION as i32, + KIND_MEMBER_REMOVED_NOTIFICATION as i32, + KIND_AGENT_TURN_METRIC as i32, + ] { + assert!( + !kinds.contains(&forbidden), + "kind:{forbidden} MUST NOT be searchable — \ + privacy regression in `search_tsv` generated column. kinds={kinds:?}", + ); + } + + // Tight bound: exactly one hit (the control). Catches any future + // weakening where some-but-not-all excluded kinds surface. + assert_eq!( + result.hits.len(), + 1, + "expected exactly 1 hit (the kind:9 control), got {} (kinds={kinds:?})", + result.hits.len(), + ); + + fx.teardown(pool).await; +} + +/// Tripwire: every Rust-side author-only kind MUST be excluded from +/// `search_tsv` at the storage layer. +/// +/// The schema generated column hard-codes the privacy skip-set, while +/// `AUTHOR_ONLY_KINDS` is a Rust const. If a future author-only kind is added +/// without the matching schema migration, search would still spend FTS budget on +/// those private hits before the relay post-filter rejects them. Catch that +/// drift here by inserting one row per author-only kind and proving only the +/// public kind:9 control is searchable. +pub async fn author_only_kinds_are_storage_level_unsearchable(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "author-only-tripwire.example").await; + let token = "authoronly_tripwire_marker_qwerty"; + + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + 9, + &format!("public control — {token}"), + None, + 1_700_000_000, + ) + .await; + + for (i, &kind) in AUTHOR_ONLY_KINDS.iter().enumerate() { + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + kind as i32, + &format!("author-only kind:{kind} — {token}"), + None, + 1_700_000_100 + i as i64, + ) + .await; + } + + let svc = fx.service(); + let result = svc + .search(&SearchQuery { + community: c, + q: token.into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 100, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("search ok"); + + let kinds: Vec = result.hits.iter().map(|h| h.kind).collect(); + assert!( + kinds.contains(&9), + "kind:9 control row MUST be searchable, got kinds={kinds:?}", + ); + + for &kind in AUTHOR_ONLY_KINDS { + assert!( + !kinds.contains(&(kind as i32)), + "AUTHOR_ONLY kind:{kind} MUST NOT be searchable — \ + schema skip-set is missing this kind. AUTHOR_ONLY_KINDS={AUTHOR_ONLY_KINDS:?}, \ + hits={kinds:?}", + ); + } + + assert_eq!( + result.hits.len(), + 1, + "expected exactly 1 hit (the kind:9 control), got {} (kinds={kinds:?})", + result.hits.len(), + ); + + fx.teardown(pool).await; +} + +/// Tripwire: every Rust-side `P_GATED_KINDS` entry that is *persistent* (not +/// in the ephemeral 20000–29999 range) MUST be excluded from `search_tsv` at +/// the storage layer. +/// +/// L2 (the filter-level `#p` gate in `p_gated_filters_authorized`) prevents +/// reachable leaks today, but it is Rust logic — a future bug or new exempt +/// search entry point could surface tokenized content from these kinds. The +/// L1 NULL tsvector is the unbreakable backstop: `@@` mathematically cannot +/// match NULL. This test catches the drift where someone adds a persistent +/// kind to `P_GATED_KINDS` without the matching `schema/schema.sql` + +/// `migrations/0001_initial_schema.sql` skip-set update. +/// +/// Ephemeral kinds (20000–29999) are skipped: they are never stored, so the +/// storage-layer defense does not apply to them regardless of the schema +/// CASE. `p_gated_filters_authorized` remains their sole defense by design. +/// +/// Companion to `author_only_kinds_are_storage_level_unsearchable`: that test +/// covers `AUTHOR_ONLY_KINDS` drift; this one covers `P_GATED_KINDS` +/// persistent-subset drift. Together they tripwire both Rust-side privacy +/// constants against the schema literal. +pub async fn p_gated_persistent_kinds_have_storage_null_tsvector(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + + let c = mk_community(&pool, "p-gated-tripwire.example").await; + let token = "pgated_tripwire_marker_qwerty"; + + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + 9, + &format!("public control — {token}"), + None, + 1_700_000_000, + ) + .await; + + let persistent: Vec = P_GATED_KINDS + .iter() + .copied() + .filter(|&k| !buzz_core::kind::is_ephemeral(k)) + .collect(); + assert!( + !persistent.is_empty(), + "P_GATED_KINDS must include at least one persistent kind for this \ + test to be meaningful; got {P_GATED_KINDS:?}", + ); + + for (i, &kind) in persistent.iter().enumerate() { + insert_event( + &pool, + c, + rand_bytes32(), + rand_bytes32(), + kind as i32, + &format!("p-gated kind:{kind} — {token}"), + None, + 1_700_000_100 + i as i64, + ) + .await; + } + + let svc = fx.service(); + let result = svc + .search(&SearchQuery { + community: c, + q: token.into(), + channel_scope: ChannelScope::Any, + kinds: None, + authors: None, + since: None, + until: None, + page: 1, + per_page: 100, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }) + .await + .expect("search ok"); + + let kinds: Vec = result.hits.iter().map(|h| h.kind).collect(); + assert!( + kinds.contains(&9), + "kind:9 control row MUST be searchable, got kinds={kinds:?}", + ); + + for &kind in &persistent { + assert!( + !kinds.contains(&(kind as i32)), + "P_GATED persistent kind:{kind} MUST NOT be searchable — \ + schema NULL tsvector skip-set is missing this kind. Defense \ + reduces to L2 (filter-level `#p` gate) alone. \ + P_GATED_KINDS={P_GATED_KINDS:?}, hits={kinds:?}", + ); + } + + assert_eq!( + result.hits.len(), + 1, + "expected exactly 1 hit (the kind:9 control), got {} (kinds={kinds:?})", + result.hits.len(), + ); + + fx.teardown(pool).await; +} + +pub async fn artifact_search_uses_only_live_current_head(backend: Backend) { + let (pool, fx) = Fixture::setup(backend).await; + let community = mk_community(&pool, "artifact-search.example").await; + let pk = rand_bytes32(); + let old = rand_bytes32(); + let head = rand_bytes32(); + let artifact = Uuid::new_v4(); + insert_event( + &pool, + community, + old, + pk, + 45010, + "artifactneedle old", + None, + 1700000000, + ) + .await; + insert_event( + &pool, + community, + head, + pk, + 45010, + "artifactneedle current", + None, + 1700000001, + ) + .await; + sqlx::query("INSERT INTO artifact_heads(community_id,artifact_id,event_id,channel_id,artifact_type) VALUES($1,$2,$3,$4,'buzz.task')") + .bind(community.as_uuid()).bind(artifact).bind(head.as_slice()).bind(Uuid::new_v4()).execute(&pool).await.unwrap(); + let svc = fx.service(); + let query = SearchQuery { + community, + q: "artifactneedle".into(), + channel_scope: ChannelScope::Any, + kinds: Some(vec![45010]), + authors: None, + since: None, + until: None, + page: 1, + per_page: 10, + mode: buzz_search::SearchMode::FullText, + sort: buzz_search::SearchSort::Relevance, + }; + let result = svc.search(&query).await.unwrap(); + assert_eq!(result.hits.len(), 1); + assert_eq!(result.hits[0].event_id, head); + sqlx::query("UPDATE artifact_heads SET deleted=true WHERE community_id=$1 AND artifact_id=$2") + .bind(community.as_uuid()) + .bind(artifact) + .execute(&pool) + .await + .unwrap(); + let result = svc.search(&query).await.unwrap(); + assert!(result.hits.is_empty()); + fx.teardown(pool).await; +} diff --git a/docker-compose.yml b/docker-compose.yml index ad4ac2fd53..e64d865909 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -149,6 +149,37 @@ services: com.buzz.env: "dev" restart: "no" + # Opt-in message index; see docs/opensearch-search-deployment.md. + opensearch: + image: opensearchproject/opensearch:2.19.3@sha256:e96cc6ae1500a073d973c0906f30f7cf4d9c461f32f855f9242a2da933660cdd + container_name: buzz-opensearch + profiles: ["search"] + environment: + discovery.type: single-node + DISABLE_SECURITY_PLUGIN: "true" + DISABLE_INSTALL_DEMO_CONFIG: "true" + OPENSEARCH_JAVA_OPTS: "-Xms512m -Xmx512m" + ports: + - "127.0.0.1:9200:9200" + volumes: + - opensearch-data:/usr/share/opensearch/data + networks: + - buzz-net + healthcheck: + test: ["CMD-SHELL", "curl -fsS http://localhost:9200/_cluster/health?wait_for_status=yellow&timeout=1s"] + interval: 5s + timeout: 5s + retries: 24 + start_period: 20s + deploy: + resources: + limits: + memory: 1g + labels: + com.buzz.service: "opensearch" + com.buzz.env: "dev" + restart: unless-stopped + prometheus: image: prom/prometheus:latest container_name: buzz-prometheus @@ -183,6 +214,10 @@ volumes: name: buzz-prometheus-data labels: com.buzz.volume: "prometheus" + opensearch-data: + name: buzz-opensearch-data + labels: + com.buzz.volume: "opensearch" networks: buzz-net: diff --git a/docs/opensearch-search-deployment.md b/docs/opensearch-search-deployment.md new file mode 100644 index 0000000000..187df2dee4 --- /dev/null +++ b/docs/opensearch-search-deployment.md @@ -0,0 +1,54 @@ +# OpenSearch message index deployment + +With `BUZZ_OPENSEARCH_URL` set, the relay keeps an OpenSearch index of +messages up to date through the `search_outbox` table. Searches still run on +Postgres. + +| Variable | Meaning | +| --- | --- | +| `BUZZ_OPENSEARCH_URL` | HTTP(S) cluster URL without credentials, query or fragment. Unset turns indexing off. | +| `BUZZ_OPENSEARCH_USERNAME`, `BUZZ_OPENSEARCH_PASSWORD` | Optional basic auth. Set both or neither. | +| `BUZZ_OPENSEARCH_PREVIEW` | Required with the URL until [block/buzz#9862](https://github.com/block/buzz/pull/9862), because deleted messages stay in the index. Use it only on relays without real data. | + +## Rollout order + +1. Deploy a release that lists `search_outbox` as a pending deletion-scoped + table ([block/buzz#9871](https://github.com/block/buzz/pull/9871)). + Deletion code that predates it rejects the catalog once migration `0106` + runs, which stops community deletion. +2. Deploy the release with migration `0106`. Nothing is queued until the + setting is on. +3. Set `BUZZ_OPENSEARCH_URL` and `BUZZ_OPENSEARCH_PREVIEW=true` on every + relay. Each relay queues only the messages it stores, so one without the + settings leaves gaps. A relay with them refuses to start before `0106` has + run. Until [block/buzz#9862](https://github.com/block/buzz/pull/9862) + caps bulk requests, a cluster with a 10 MiB request limit can reject a + full batch. + +Messages stored before step 3 are not indexed; there is no backfill yet. + +To turn indexing off, unset the URL and restart the relays. Queued rows stay +until it is back on. + +## Operating + +While OpenSearch is down the queue grows without bound. Check it with: + +```sh +psql -c 'SELECT count(*), min(created_at) FROM search_outbox' +``` + +The index holds the words of every indexed message, DMs included, so anyone +who can query the cluster can search them. Limit cluster access to the relays. + +If you stream Postgres changes through logical replication, leave +`search_outbox` out of the publication. Its rows are short-lived queue +entries. + +## Local run + +```sh +docker compose --profile search up -d opensearch +BUZZ_OPENSEARCH_URL=http://localhost:9200 BUZZ_OPENSEARCH_PREVIEW=true just relay +curl -s 'localhost:9200/buzz-messages/_search?pretty' +``` diff --git a/migrations/0106_search_outbox.sql b/migrations/0106_search_outbox.sql new file mode 100644 index 0000000000..204090e774 --- /dev/null +++ b/migrations/0106_search_outbox.sql @@ -0,0 +1,13 @@ +-- The search indexer's queue; see schema/tables/public/search_outbox.sql. +-- Its writers use community admission (docs/database.md). A new, empty table. +SET LOCAL lock_timeout = '5s'; +CREATE TABLE search_outbox ( + community_id UUID NOT NULL, + id UUID NOT NULL DEFAULT gen_random_uuid(), + event_id BYTEA NOT NULL CHECK (length(event_id) = 32), + event_created_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (community_id, id) +); +CREATE INDEX search_outbox_queue ON search_outbox (created_at); +CREATE INDEX search_outbox_community_queue ON search_outbox (community_id, created_at); diff --git a/schema/schema.sql b/schema/schema.sql index 051590a0cc..f7800133a9 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -97,6 +97,7 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; \i tables/public/push_leases.sql \i tables/public/push_wake_outbox.sql \i tables/public/push_match_queue.sql +\i tables/public/search_outbox.sql \i tables/public/push_gateway_challenges.sql \i tables/public/push_gateway_installations.sql \i tables/public/push_gateway_delegations.sql diff --git a/schema/tables/public/search_outbox.sql b/schema/tables/public/search_outbox.sql new file mode 100644 index 0000000000..5f6000c328 --- /dev/null +++ b/schema/tables/public/search_outbox.sql @@ -0,0 +1,19 @@ +-- ── Search outbox ───────────────────────────────────────────────────────────── +-- Keys of events whose search index entry must be brought up to date. Written +-- in the transaction that admits the event, only when the relay is configured +-- with an OpenSearch address; the indexer claims rows with SKIP LOCKED, +-- re-reads each event from `events`, writes the index and deletes the rows. +-- Not deduplicated: a change made while an older row is claimed keeps its own +-- row. Keep this table out of logical-replication publications; its rows are +-- insert-then-delete churn that change-data-capture consumers never need. + +CREATE TABLE search_outbox ( + community_id UUID NOT NULL, + id UUID NOT NULL DEFAULT gen_random_uuid(), + event_id BYTEA NOT NULL CHECK (length(event_id) = 32), + event_created_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (community_id, id) +); +CREATE INDEX search_outbox_queue ON search_outbox (created_at); +CREATE INDEX search_outbox_community_queue ON search_outbox (community_id, created_at);