Skip to content

Commit 75a5146

Browse files
refactor(db): move relay membership store ownership
Signed-off-by: tornquist <[email protected]>
1 parent 723b40d commit 75a5146

3 files changed

Lines changed: 425 additions & 364 deletions

File tree

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

Lines changed: 1 addition & 362 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ pub use reminder::DueReminder;
9797
use buzz_datastore_tracing::datastore_span;
9898
use chrono::{DateTime, Utc};
9999
use sqlx::postgres::{PgConnection, PgPoolOptions};
100-
use sqlx::{Connection, PgPool, QueryBuilder, Row};
100+
use sqlx::{Connection, PgPool, QueryBuilder};
101101
use std::time::Duration;
102102
use uuid::Uuid;
103103

@@ -1335,174 +1335,6 @@ impl Db {
13351335
Ok(result.rows_affected())
13361336
}
13371337

1338-
/// Returns `true` if `pubkey` (64-char hex) is a member of `community`.
1339-
///
1340-
/// Replica-routed on the bounded arm — the one PERMISSION read routed by
1341-
/// explicit product decision (bounded-stale membership beats the 10s
1342-
/// cache it replaced). Admits and revokes may lag by at most the budget
1343-
/// `B`; everything else fails closed to the writer, exactly like
1344-
/// [`Db::query_events_routed_bounded`]. Not precedent for routing other
1345-
/// permission reads.
1346-
#[datastore_span(name = "is_relay_member", system = "postgresql")]
1347-
pub async fn is_relay_member(&self, community: CommunityId, pubkey: &str) -> Result<bool> {
1348-
let path = "relay_membership";
1349-
match self.route_read(path, RoutePredicate::Bounded).await {
1350-
RouteDecision::Replica(mut tx, _entry, reason) => {
1351-
match relay_members::is_relay_member_on(&mut tx, community, pubkey).await {
1352-
Ok(is_member) => {
1353-
Self::record_route(path, "replica", reason);
1354-
Ok(is_member)
1355-
}
1356-
Err(e) => {
1357-
tracing::warn!(path, "replica read failed; re-running on writer: {e}");
1358-
Self::record_route(path, "writer", "replica_error");
1359-
relay_members::is_relay_member(&self.pool, community, pubkey).await
1360-
}
1361-
}
1362-
}
1363-
RouteDecision::Writer => {
1364-
relay_members::is_relay_member(&self.pool, community, pubkey).await
1365-
}
1366-
}
1367-
}
1368-
1369-
/// Returns the relay member record for `pubkey` in `community`, or `None` if not found.
1370-
#[datastore_span(name = "get_relay_member", system = "postgresql")]
1371-
pub async fn get_relay_member(
1372-
&self,
1373-
community: CommunityId,
1374-
pubkey: &str,
1375-
) -> Result<Option<relay_members::RelayMember>> {
1376-
relay_members::get_relay_member(&self.pool, community, pubkey).await
1377-
}
1378-
1379-
/// Returns all relay members of `community` ordered by `created_at` ascending.
1380-
#[datastore_span(name = "list_relay_members", system = "postgresql")]
1381-
pub async fn list_relay_members(
1382-
&self,
1383-
community: CommunityId,
1384-
) -> Result<Vec<relay_members::RelayMember>> {
1385-
relay_members::list_relay_members(&self.pool, community).await
1386-
}
1387-
1388-
/// Adds a new relay member to `community`.
1389-
///
1390-
/// Returns `true` if the row was actually inserted, `false` if the pubkey
1391-
/// already existed in `community` (idempotent — `ON CONFLICT DO NOTHING`).
1392-
#[datastore_span(name = "add_relay_member", system = "postgresql")]
1393-
pub async fn add_relay_member(
1394-
&self,
1395-
community: CommunityId,
1396-
pubkey: &str,
1397-
role: &str,
1398-
added_by: Option<&str>,
1399-
) -> Result<bool> {
1400-
relay_members::add_relay_member(&self.pool, community, pubkey, role, added_by).await
1401-
}
1402-
1403-
/// Claims relay membership via an invite and atomically persists the
1404-
/// accepted policy version when a policy is configured.
1405-
#[datastore_span(name = "claim_relay_membership", system = "postgresql")]
1406-
pub async fn claim_relay_membership(
1407-
&self,
1408-
community: CommunityId,
1409-
pubkey: &str,
1410-
role: &str,
1411-
policy_version: Option<&str>,
1412-
) -> Result<bool> {
1413-
relay_members::claim_relay_membership(&self.pool, community, pubkey, role, policy_version)
1414-
.await
1415-
}
1416-
1417-
/// Returns whether a member has persisted acceptance evidence for a policy version.
1418-
#[datastore_span(name = "has_join_policy_acceptance", system = "postgresql")]
1419-
pub async fn has_join_policy_acceptance(
1420-
&self,
1421-
community: CommunityId,
1422-
pubkey: &str,
1423-
policy_version: &str,
1424-
) -> Result<bool> {
1425-
relay_members::has_join_policy_acceptance(&self.pool, community, pubkey, policy_version)
1426-
.await
1427-
}
1428-
1429-
/// Removes a relay member from `community` atomically, refusing to delete the owner.
1430-
#[datastore_span(name = "remove_relay_member", system = "postgresql")]
1431-
pub async fn remove_relay_member(
1432-
&self,
1433-
community: CommunityId,
1434-
pubkey: &str,
1435-
) -> Result<relay_members::RemoveResult> {
1436-
relay_members::remove_relay_member(&self.pool, community, pubkey).await
1437-
}
1438-
1439-
/// Removes a relay member from `community` only if their current role matches `expected_role`.
1440-
///
1441-
/// Atomic conditional delete — eliminates the TOCTOU race between a
1442-
/// prior role read and the delete. See [`relay_members::remove_relay_member_if_role`].
1443-
#[datastore_span(name = "remove_relay_member_if_role", system = "postgresql")]
1444-
pub async fn remove_relay_member_if_role(
1445-
&self,
1446-
community: CommunityId,
1447-
pubkey: &str,
1448-
expected_role: &str,
1449-
) -> Result<relay_members::RemoveResult> {
1450-
relay_members::remove_relay_member_if_role(&self.pool, community, pubkey, expected_role)
1451-
.await
1452-
}
1453-
1454-
/// Updates the role of an existing relay member in `community`. Returns `true` if updated.
1455-
#[datastore_span(name = "update_relay_member_role", system = "postgresql")]
1456-
pub async fn update_relay_member_role(
1457-
&self,
1458-
community: CommunityId,
1459-
pubkey: &str,
1460-
new_role: &str,
1461-
) -> Result<bool> {
1462-
relay_members::update_relay_member_role(&self.pool, community, pubkey, new_role).await
1463-
}
1464-
1465-
/// Ensures the owner pubkey exists with role `"owner"` in `community`. Called at startup.
1466-
#[datastore_span(name = "bootstrap_owner", system = "postgresql")]
1467-
pub async fn bootstrap_owner(&self, community: CommunityId, owner_pubkey: &str) -> Result<()> {
1468-
relay_members::bootstrap_owner(&self.pool, community, owner_pubkey).await
1469-
}
1470-
1471-
/// Returns `true` if any member of `community` holds the `admin` or
1472-
/// `owner` role.
1473-
pub async fn has_admin_or_owner(&self, community: CommunityId) -> Result<bool> {
1474-
relay_members::has_admin_or_owner(&self.pool, community).await
1475-
}
1476-
1477-
/// Atomically transfers ownership of `community` to `new_owner_pubkey`,
1478-
/// demoting the previous owner(s) to `member`. Verifies
1479-
/// `expected_owner_pubkey` matches the current owner inside the same
1480-
/// transaction to prevent stale-owner races.
1481-
#[datastore_span(name = "transfer_ownership", system = "postgresql")]
1482-
pub async fn transfer_ownership(
1483-
&self,
1484-
community: CommunityId,
1485-
new_owner_pubkey: &str,
1486-
expected_owner_pubkey: &str,
1487-
) -> Result<relay_members::TransferResult> {
1488-
relay_members::transfer_ownership(
1489-
&self.pool,
1490-
community,
1491-
new_owner_pubkey,
1492-
expected_owner_pubkey,
1493-
)
1494-
.await
1495-
}
1496-
1497-
/// Migrates existing `pubkey_allowlist` entries into `relay_members` for `community`.
1498-
///
1499-
/// Idempotent — uses `ON CONFLICT DO NOTHING`. Returns the number of rows
1500-
/// inserted, or 0 if the `pubkey_allowlist` table doesn't exist.
1501-
#[datastore_span(name = "backfill_from_allowlist", system = "postgresql")]
1502-
pub async fn backfill_from_allowlist(&self, community: CommunityId) -> Result<u64> {
1503-
relay_members::backfill_from_allowlist(&self.pool, community).await
1504-
}
1505-
15061338
/// Mints a v2 use-limited relay invite. The plaintext code is returned
15071339
/// exactly once; only its SHA-256 hash is persisted.
15081340
///
@@ -1823,199 +1655,6 @@ impl Db {
18231655
) -> Result<Vec<archived_identities::ArchivedIdentity>> {
18241656
archived_identities::list_archived(&self.pool, community_id).await
18251657
}
1826-
1827-
/// Returns whether the relay-authored NIP-43 snapshot is absent or differs
1828-
/// from the canonical membership rows for `community_id`.
1829-
///
1830-
/// Snapshot and canonical rows are compared directly rather than by
1831-
/// timestamp: relay membership events use whole-second Nostr timestamps,
1832-
/// and multiple mutations within one second must still be repaired.
1833-
#[datastore_span(
1834-
name = "nip43_membership_snapshot_needs_reconciliation",
1835-
system = "postgresql"
1836-
)]
1837-
pub async fn nip43_membership_snapshot_needs_reconciliation(
1838-
&self,
1839-
community_id: CommunityId,
1840-
relay_pubkey: &nostr::PublicKey,
1841-
) -> Result<bool> {
1842-
let snapshot = self
1843-
.query_events(&crate::event::EventQuery {
1844-
kinds: Some(vec![buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST as i32]),
1845-
pubkey: Some(relay_pubkey.to_bytes().to_vec()),
1846-
global_only: true,
1847-
limit: Some(1),
1848-
..crate::event::EventQuery::for_community(community_id)
1849-
})
1850-
.await?
1851-
.into_iter()
1852-
.next();
1853-
let members = self.list_relay_members(community_id).await?;
1854-
1855-
let Some(snapshot) = snapshot else {
1856-
return Ok(true);
1857-
};
1858-
let mut snapshot_members = snapshot
1859-
.event
1860-
.tags
1861-
.iter()
1862-
.filter_map(|tag| {
1863-
let parts = tag.as_slice();
1864-
(parts.first().map(String::as_str) == Some("member") && parts.len() >= 3)
1865-
.then(|| (parts[1].to_ascii_lowercase(), parts[2].clone()))
1866-
})
1867-
.collect::<Vec<_>>();
1868-
let mut canonical_members = members
1869-
.into_iter()
1870-
.map(|member| (member.pubkey.to_ascii_lowercase(), member.role))
1871-
.collect::<Vec<_>>();
1872-
snapshot_members.sort_unstable();
1873-
canonical_members.sort_unstable();
1874-
1875-
Ok(snapshot_members != canonical_members)
1876-
}
1877-
1878-
/// Atomically publish a NIP-43 membership snapshot under a single
1879-
/// transaction-scoped advisory lock.
1880-
///
1881-
/// This method acquires the per-community snapshot lock, reads the
1882-
/// current membership, builds the event, and replaces the prior snapshot
1883-
/// — all inside one transaction on one database connection. This
1884-
/// prevents the stale-snapshot race where a concurrent publication reads
1885-
/// older state and overwrites a newer snapshot by arrival order.
1886-
///
1887-
#[datastore_span(name = "publish_nip43_membership_locked", system = "postgresql")]
1888-
pub async fn publish_nip43_membership_locked(
1889-
&self,
1890-
community_id: CommunityId,
1891-
relay_keypair: &nostr::Keys,
1892-
) -> Result<(StoredEvent, bool, usize)> {
1893-
use nostr::{EventBuilder, Kind, Tag};
1894-
1895-
let kind_i32 = buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST as i32;
1896-
let pubkey_bytes = relay_keypair.public_key().to_bytes();
1897-
1898-
let lock_key = replaceable::event_replacement_lock_key(
1899-
community_id,
1900-
kind_i32,
1901-
pubkey_bytes.as_slice(),
1902-
None,
1903-
);
1904-
1905-
let (mut tx, transaction_timer) = observability::begin_transaction(
1906-
&self.pool,
1907-
observability::TransactionOperation::PublishNip43MembershipLocked,
1908-
)
1909-
.await?;
1910-
let (event, received_at, was_inserted, member_count) = transaction_timer
1911-
.observe(async {
1912-
1913-
// Acquire the per-community snapshot lock BEFORE reading members.
1914-
// This serializes the entire read-build-write cycle: a concurrent
1915-
// publication will block here until our transaction commits, then
1916-
// read the updated membership state.
1917-
observability::observe_advisory_lock(
1918-
observability::LockType::Membership,
1919-
sqlx::query("SELECT pg_advisory_xact_lock($1)")
1920-
.bind(lock_key)
1921-
.execute(&mut *tx),
1922-
)
1923-
.await?;
1924-
1925-
// Read current members inside the locked transaction.
1926-
let rows = sqlx::query(
1927-
"SELECT pubkey, role FROM relay_members \
1928-
WHERE community_id = $1 ORDER BY created_at ASC",
1929-
)
1930-
.bind(community_id.as_uuid())
1931-
.fetch_all(&mut *tx)
1932-
.await?;
1933-
1934-
let member_count = rows.len();
1935-
1936-
// Build the NIP-43 event from the locked member rows.
1937-
let mut tags: Vec<Tag> = Vec::with_capacity(member_count + 1);
1938-
// NIP-70 protected-event marker.
1939-
tags.push(Tag::parse(["-"]).map_err(|e| {
1940-
crate::error::DbError::InvalidData(format!("failed to build '-' tag: {e}"))
1941-
})?);
1942-
for row in &rows {
1943-
let pubkey: String = row.try_get("pubkey")?;
1944-
let role: String = row.try_get("role")?;
1945-
tags.push(Tag::parse(["member", &pubkey, &role]).map_err(|e| {
1946-
crate::error::DbError::InvalidData(format!("failed to build member tag: {e}"))
1947-
})?);
1948-
}
1949-
1950-
let event = EventBuilder::new(Kind::Custom(kind_i32 as u16), "")
1951-
.tags(tags)
1952-
.sign_with_keys(relay_keypair)
1953-
.map_err(|e| {
1954-
crate::error::DbError::InvalidData(format!("failed to sign kind:13534: {e}"))
1955-
})?;
1956-
1957-
let created_at_secs = event.created_at.as_secs() as i64;
1958-
let created_at = chrono::DateTime::from_timestamp(created_at_secs, 0)
1959-
.ok_or(DbError::InvalidTimestamp(created_at_secs))?;
1960-
let sig_bytes = event.sig.serialize();
1961-
let tags_json = serde_json::to_value(&event.tags)?;
1962-
let received_at = chrono::Utc::now();
1963-
let d_tag = crate::event::extract_d_tag(&event);
1964-
1965-
// Soft-delete prior snapshots — unconditional, the relay is authoritative.
1966-
sqlx::query(
1967-
"UPDATE events SET deleted_at = NOW() \
1968-
WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \
1969-
AND channel_id IS NULL \
1970-
AND deleted_at IS NULL",
1971-
)
1972-
.bind(community_id.as_uuid())
1973-
.bind(kind_i32)
1974-
.bind(pubkey_bytes.as_slice())
1975-
.execute(&mut *tx)
1976-
.await?;
1977-
1978-
let insert_result = sqlx::query(
1979-
"INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag) \
1980-
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) \
1981-
ON CONFLICT DO NOTHING",
1982-
)
1983-
.bind(community_id.as_uuid())
1984-
.bind(event.id.as_bytes().as_slice())
1985-
.bind(pubkey_bytes.as_slice())
1986-
.bind(created_at)
1987-
.bind(kind_i32)
1988-
.bind(&tags_json)
1989-
.bind(&event.content)
1990-
.bind(sig_bytes.as_slice())
1991-
.bind(received_at)
1992-
.bind::<Option<Uuid>>(None)
1993-
.bind(d_tag.as_deref())
1994-
.execute(&mut *tx)
1995-
.await?;
1996-
1997-
let was_inserted = insert_result.rows_affected() > 0;
1998-
if was_inserted {
1999-
tx.commit().await?;
2000-
} else {
2001-
tx.rollback().await?;
2002-
}
2003-
Ok::<_, DbError>((event, received_at, was_inserted, member_count))
2004-
})
2005-
.await?;
2006-
2007-
if was_inserted {
2008-
if let Err(e) = crate::insert_mentions(&self.pool, community_id, &event, None).await {
2009-
tracing::warn!(event_id = %event.id, "Failed to insert mentions: {e}");
2010-
}
2011-
}
2012-
2013-
Ok((
2014-
StoredEvent::with_received_at(event, received_at, None, was_inserted),
2015-
was_inserted,
2016-
member_count,
2017-
))
2018-
}
20191658
}
20201659

20211660
#[cfg(test)]

0 commit comments

Comments
 (0)