Files
buzz/crates/buzz-db/src/lib.rs
Kalvin C e95d7a9509 feat(relay): add pinned messages (nip-pm) (#9729)
## Summary
Implements NIP-PM on the relay. A member signs one command to pin or
unpin a message, and the relay publishes the channel's pins as one
relay-signed list. The NIP is `docs/nips/NIP-PM.md`, added in #9712.

- **Kinds.** `40010` pin and `40011` unpin commands (one `h`, one `e`,
empty content) and the relay-signed `30623` pin list, one addressable
event per channel, newest pin first. The list carries the channel in `d`
and in `h`.
- **Ordering.** Every writer of a channel's list takes that list's
replacement lock, so pins, unpins and deletes of pinned messages apply
one at a time. A command, the new list and the notice are stored in one
transaction.
- **Idempotency.** A command sent again answers `duplicate:` and is not
applied again. Pinning a pinned message or unpinning an unpinned one is
accepted and changes nothing.
- **Validation.** The author must be able to post in the channel, and
the channel must not be archived. A pin target must be a live message of
that channel. A channel holds at most 250 pins.
- **Deletes.** A delete by the author, the owner of the agent that wrote
the message, a channel admin or a relay admin removes the message from
the list in the deleting transaction and publishes the new list. A
delete removes its messages first and then takes the list locks in
channel order, rewriting each list once. Each list write records its
timestamp, and a delete reads that first: a delete of a message that is
not pinned locks only its own month of `events`, plus the list month
when the channel has a list (#9743). The pin list itself cannot be
deleted.
- **Notice.** A pin that changes the list posts a `message_pinned`
system message naming the member, the message and the command.
- **Reads.** The list is readable by those who can read the channel.
Clients read it with `#h`, which names the channel under NIP-CL, and
each new list is delivered to `#h` subscribers.
- **Configuration.** None. A relay running this build accepts the
commands; it does not advertise pins in NIP-11.
- **Threads.** A pin or unpin command cannot be the parent of a reply or
the target of an edit or a vote.
- **Account erasure.** Content cleanup removes a member's pin and unpin
commands. One under an hour old keeps its ID, timestamp, kind and
channel so that a resend stays a duplicate. The leader's periodic
maintenance tick removes those records once the command is an hour old.
`docs/operator-user-account-retention.md` describes this.

### Related issue
N/A. #8809 is an earlier draft of message pins with a different event
model.

### Testing
- Postgres-backed store tests for the list writes: ordering, concurrent
pins, resends, the limit, deletes, the lock order of a delete of several
messages, the partitions a delete locks, the refusal to delete the list,
erasure records and their expiry across communities.
- Postgres-backed handler tests through ingest and REQ: the pin and
unpin journey with notices and live delivery, who can read the list
(private channel, DM and an unlisted channel read by a non-member),
every refusal, a reply to a command, and deletes that rewrite the list.
- `e2e_channel_pins` runs over WebSocket against a relay and is added to
the relay integration job.
- Run against a local relay started with no pins configuration: the
end-to-end test. On an earlier revision, the periodic tick removed
expired erasure records from an archived channel while leaving younger
records, live commands and other kinds.
- `cargo fmt --check`, clippy with warnings denied on the touched
crates, and the file-size check.
- `just test-unit`, which includes the buzz-db source-policy tests.

---------

Signed-off-by: Kalvin Chau <kalvin@block.xyz>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 10:50:47 -08:00

142 lines
6.1 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#![deny(unsafe_code)]
#![warn(missing_docs)]
//! buzz-db — Postgres event store for Buzz.
//!
//! ## Design invariants
//! - AUTH events (kind 22242) are never stored — they carry bearer tokens.
//! - Ephemeral events (20000–29999) are never stored — Redis pub/sub only.
//! - Events table is partitioned by month on `created_at`.
//! - No FK references to partitioned tables.
//! - Uses `sqlx::query()` (runtime) not `sqlx::query!()` (compile-time).
//!
//! ## Runtime and store ownership
//! Database runtime infrastructure and domain persistence are physically
//! separated behind this crate-root compatibility facade:
//!
//! - Runtime concerns own pool construction, writer/replica routing,
//! transactions, sessions, metrics, health support, and migrations.
//! - Store concerns own domain-specific SQL, row mapping, locking, mutation
//! rules, indexes, and focused persistence tests.
//!
//! Existing crate-root modules, records, and [`Db`] methods remain the public
//! API. The internal `runtime` and `store` namespaces are not public APIs.
/// Wrap `$retire`, an `UPDATE`/`DELETE` on `events` that retires a
/// coordinate's previous head, so the same statement drops those rows' mention
/// index entries. Mention-index reads (`#p` filters and feeds) never return a
/// retired row, so its mention rows are dead weight they must walk and
/// discard: one per member for every kind:39002 roster republish. `$1` must
/// bind the community.
///
/// The addressable path, the relay's member snapshot, and the kind:13534
/// list writer (whose `member` tags index no mentions) supersede through
/// this, so a head and its mention rows leave together when a newer head
/// replaces it. NIP-33 parameterized replacement drops its superseded rows'
/// mentions itself (`remove_coordinate_versions_in_tx`). Channel deletion
/// (`soft_delete_discovery_events`) retires live heads without a
/// replacement and does not go through this.
macro_rules! superseded_with_mentions_sql {
($retire:expr) => {
concat!(
"WITH superseded AS (",
$retire,
" RETURNING id) \
DELETE FROM event_mentions mention USING superseded \
WHERE mention.community_id = $1 AND mention.event_id = superseded.id"
)
};
}
mod runtime;
mod store;
/// Concurrency caps whose limit can change at runtime.
pub mod concurrency_gate;
/// Database error types.
pub mod error;
#[cfg(test)]
mod test_support;
pub use runtime::{
insert_mentions, migration, replica_fence, AdmittedTx, ColdStartError, Db, DbConfig,
DbConnectionOutcome, DbConnectionStep, DbPoolRole, DbPoolStats, DbReadinessOutcome,
ReadSession,
};
/// Valid low-cardinality `(pool_role, operation)` pairs for pool-acquisition telemetry.
pub const DB_POOL_ACQUIRE_VALID_PAIRS: [(&str, &str); 11] =
runtime::observability::POOL_ACQUIRE_VALID_PAIRS;
/// Raw Prometheus series ceiling per relay pod for the operation-aware contract.
pub const DB_POOL_ACQUIRE_RAW_SERIES_PER_POD: usize =
runtime::observability::POOL_ACQUIRE_RAW_SERIES_PER_POD;
/// Valid database connection role/step pairs with a start counter.
pub const DB_CONNECTION_STARTED_STEPS: [(DbPoolRole, DbConnectionStep); 3] =
runtime::CONNECTION_STARTED_STEPS;
/// Valid database connection role/step pairs with a duration histogram.
pub const DB_CONNECTION_DURATION_STEPS: [(DbPoolRole, DbConnectionStep); 3] =
runtime::CONNECTION_DURATION_STEPS;
/// Valid database connection role/step/outcome terminal combinations.
pub const DB_CONNECTION_TERMINALS: [(DbPoolRole, DbConnectionStep, DbConnectionOutcome); 12] =
runtime::CONNECTION_TERMINALS;
/// Raw Prometheus series ceiling per pod for connection-step telemetry.
pub const DB_CONNECTION_RAW_SERIES_PER_POD: usize = runtime::CONNECTION_RAW_SERIES_PER_POD;
pub(crate) use runtime::{
begin_community_event_write_transaction,
begin_community_event_write_transaction_with_legacy_metrics, begin_community_sweep_transaction,
begin_community_write_transaction, insert_mentions_in_transaction, observability, route_proof,
sweep_admitted_communities, ReadSessionInner, RouteDecision, RoutePredicate,
};
pub use store::{
admin_moderation, allowlist, api_token, archived_identities, artifact, artifact_sync, channel,
channel_members, community, community_auth, deletion, dm, entity_deletion, event, feed,
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,
user_deletion_fences, workflow,
};
pub use allowlist::AllowlistEntry;
pub use api_token::{ApiTokenRecord, TokenSummary};
pub use community::{
ArchivedCommunityRecord, CommunityRecord, CreateCommunityWithOwnerResult,
CreatedCommunityRecord, EnsuredCommunityRecord, OwnedCommunityRecord, UnarchiveCommunityResult,
UnarchivedCommunityRecord,
};
pub use concurrency_gate::{ConcurrencyGate, GatePermit};
pub use error::{DbError, Result};
pub use event::{ChannelHeadPrecondition, ChannelHeadWriteStatus, DeletionTarget};
pub use event::{EventQuery, DEFAULT_MAX_PAGE_LIMIT};
pub use leader_lock::SessionLeader;
pub use nip_fi_binding::{NipFiBindingRecord, NipFiUnbind, RowCapExceeded};
pub use reaction::ReactionEventInsertOutcome;
pub use reminder::DueReminder;
pub use store::{ArtifactSnapshot, SnapshotDenied};
/// A value read from the database, with when its reading connection was
/// checked out of the pool.
///
/// The statement that produced `value` started after `read_at`, so its
/// snapshot is no older than `read_at`. A cache that serves `value` for a
/// bound after `read_at` is never staler than that bound, however long the
/// read waited for a connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReadAt<T> {
/// The value as read.
pub value: T,
/// When the connection that read `value` was checked out.
pub read_at: std::time::Instant,
}
use buzz_core::CommunityId;
/// Durable NIP-FI verified-profile projection state.
pub use store::verified_profiles;