Skip to content
Draft
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 125 additions & 10 deletions crates/buzz-db/src/store/read_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,50 @@ use crate::{observability, Db, DbError, Result};
pub const MAX_SNAPSHOT_EVENTS: usize = 4096;
/// Maximum stored payload or encoded event-array bytes; overflow is an error.
pub const MAX_SNAPSHOT_BYTES: usize = 8 * 1024 * 1024;
/// How far a snapshot's [`ReadStateSnapshot::cursor`] trails its statement.
///
/// `received_at` is stamped by a relay pod before its write transaction
/// commits, so a write can become visible after a snapshot whose statement
/// time is later than its `received_at`. A delta from a cursor this far back
/// re-sends such writes when their `received_at` is newer than the cursor,
/// that is, when the transaction commits within this window of its stamp
/// (less clock skew between relay pods and Postgres). A later commit is in
/// neither read.
pub const SNAPSHOT_CURSOR_OVERLAP_MS: i64 = 5 * 60 * 1000;

/// A complete view at one writer statement's MVCC cut, not a live-delivery fence.
#[derive(Debug)]
pub struct ReadStateSnapshot {
/// Content identifier bound to community, author, and ordered event ids.
/// Not a monotone revision, CAS token, or live-stream cursor.
pub snapshot_id: String,
/// Every current own kind-30078 event, including unrelated application data.
/// Every current own kind-30078 event, including unrelated application
/// data; for a delta, only those received after its cursor.
pub events: Vec<Value>,
/// Pass back as `received_after` to read only later writes: the
/// statement's time in Unix milliseconds, less
/// [`SNAPSHOT_CURSOR_OVERLAP_MS`]. Opaque to clients.
pub cursor: i64,
}

impl Db {
/// Load all current kind-30078 events for exactly one author and community.
/// Load all current kind-30078 events for exactly one author and community,
/// or with `received_after` (an earlier [`ReadStateSnapshot::cursor`]) only
/// those the relay received after it.
///
/// A single writer statement binds selection, resource preflight, and row
/// A delta reads and checks the same rows as a full read, so it fails
/// exactly when a full read would, then returns only those received
/// after the cursor; its [`ReadStateSnapshot::snapshot_id`] is the full
/// read's. A single
/// writer statement binds selection, resource preflight, and row
/// retrieval to the same MVCC snapshot. No tag, horizon, replica, or ordinary
/// query-page cap is involved. Any corrupt row or budget overflow fails the
/// whole operation before a caller can assert completeness.
pub async fn read_state_snapshot(
&self,
community: CommunityId,
author: &nostr::PublicKey,
received_after: Option<i64>,
) -> Result<ReadStateSnapshot> {
let mut conn = observability::acquire_writer(
&self.pool,
Expand All @@ -55,6 +77,8 @@ impl Db {
SELECT count(*) AS n, COALESCE(sum(bytes), 0)::bigint AS bytes FROM candidates
)
SELECT budget.n AS snapshot_count, budget.bytes AS snapshot_bytes,
(floor(extract(epoch FROM statement_timestamp()) * 1000))::bigint
- $7 AS snapshot_cursor,
e.id, e.pubkey, e.created_at, e.kind, e.tags, e.content, e.sig,
e.received_at, e.channel_id
FROM budget
Expand All @@ -69,6 +93,7 @@ impl Db {
.bind((MAX_SNAPSHOT_EVENTS + 1) as i64)
.bind(MAX_SNAPSHOT_EVENTS as i64)
.bind(MAX_SNAPSHOT_BYTES as i64)
.bind(SNAPSHOT_CURSOR_OVERLAP_MS)
.fetch_all(&mut *conn)
.await?;

Expand All @@ -77,10 +102,12 @@ impl Db {
})?;
let count: i64 = first.try_get("snapshot_count")?;
let stored_bytes: i64 = first.try_get("snapshot_bytes")?;
let cursor: i64 = first.try_get("snapshot_cursor")?;
if count > MAX_SNAPSHOT_EVENTS as i64 || stored_bytes > MAX_SNAPSHOT_BYTES as i64 {
return Err(DbError::ReadStateSnapshotTooLarge);
}
let mut events = Vec::with_capacity(count as usize);
let mut read = 0usize;
let mut encoded_bytes = 2usize; // JSON array brackets
let mut hash = Sha256::new();
hash.update(b"buzz-read-state-snapshot-v1\0");
Expand All @@ -103,21 +130,28 @@ impl Db {
DbError::InvalidData("invalid signed read-state snapshot event".into())
})?;
let value = serde_json::to_value(&event)?;
encoded_bytes += serde_json::to_vec(&value)?.len() + usize::from(!events.is_empty());
encoded_bytes += serde_json::to_vec(&value)?.len() + usize::from(read > 0);
if encoded_bytes > MAX_SNAPSHOT_BYTES {
return Err(DbError::ReadStateSnapshotTooLarge);
}
hash.update(event.id.as_bytes());
events.push(value);
read += 1;
// A delta runs every check of a full read over every current
// event, so it fails exactly when a full read would; only then
// does it leave out those received at or before its cursor.
if received_after.is_none_or(|cursor| stored.received_at.timestamp_millis() > cursor) {
events.push(value);
}
}
if events.len() != count as usize {
if read != count as usize {
return Err(DbError::InvalidData(
"read-state snapshot row count mismatch".into(),
));
}
Ok(ReadStateSnapshot {
snapshot_id: hex::encode(hash.finalize()),
events,
cursor,
})
}
}
Expand Down Expand Up @@ -188,7 +222,7 @@ mod postgres_tests {
let reader = snapshot_db.clone();
let pubkey = key.public_key();
let pending =
tokio::spawn(async move { reader.read_state_snapshot(community, &pubkey).await });
tokio::spawn(async move { reader.read_state_snapshot(community, &pubkey, None).await });
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let waiting: bool = sqlx::query_scalar(
Expand Down Expand Up @@ -220,7 +254,7 @@ mod postgres_tests {
let cut = pending.await.unwrap().unwrap();
assert_eq!(cut.events, vec![serde_json::to_value(&before).unwrap()]);
let next = snapshot_db
.read_state_snapshot(community, &key.public_key())
.read_state_snapshot(community, &key.public_key(), None)
.await
.unwrap();
assert_eq!(next.events, vec![serde_json::to_value(&after).unwrap()]);
Expand All @@ -231,6 +265,79 @@ mod postgres_tests {
.unwrap();
}

#[tokio::test]
#[ignore = "requires Postgres"]
async fn read_state_delta_returns_writes_received_after_the_cursor_overlap() {
let pool = PgPool::connect(&crate::test_support::database_url())
.await
.unwrap();
let db = Db::from_pool(pool.clone());
let community = db
.ensure_configured_community(&format!("delta-{}.local", uuid::Uuid::new_v4().simple()))
.await
.unwrap()
.id;
let key = Keys::generate();
let event = |slot: &str| {
EventBuilder::new(Kind::Custom(30078), slot)
.tags([Tag::identifier(slot), Tag::hashtag("read-state")])
.sign_with_keys(&key)
.unwrap()
};
let age = |event: &nostr::Event, millis: i64| {
sqlx::query(
"UPDATE events SET received_at = now() - make_interval(secs => $3::double precision / 1000)
WHERE community_id=$1 AND id=$2",
)
.bind(community.as_uuid())
.bind(event.id.as_bytes().as_slice())
.bind(millis)
.execute(&pool)
};
// Settled long before the snapshot, and one stamped inside the
// overlap: a write that may have committed after the snapshot's cut.
let settled = event("read-state:settled");
let late_commit = event("read-state:late-commit");
for e in [&settled, &late_commit] {
db.insert_event(community, e, None).await.unwrap();
}
age(&settled, SNAPSHOT_CURSOR_OVERLAP_MS + 60_000)
.await
.unwrap();
age(&late_commit, SNAPSHOT_CURSOR_OVERLAP_MS - 60_000)
.await
.unwrap();
let full = db
.read_state_snapshot(community, &key.public_key(), None)
.await
.unwrap();
assert_eq!(full.events.len(), 2);
let now_ms: i64 = sqlx::query_scalar(
"SELECT (floor(extract(epoch FROM statement_timestamp()) * 1000))::bigint",
)
.fetch_one(&pool)
.await
.unwrap();
assert!((now_ms - SNAPSHOT_CURSOR_OVERLAP_MS - full.cursor).abs() < 5_000);

let fresh = event("read-state:fresh");
db.insert_event(community, &fresh, None).await.unwrap();
let delta = db
.read_state_snapshot(community, &key.public_key(), Some(full.cursor))
.await
.unwrap();
let mut ids: Vec<_> = delta
.events
.iter()
.map(|e| e["id"].as_str().unwrap().to_owned())
.collect();
ids.sort();
let mut expected = vec![late_commit.id.to_hex(), fresh.id.to_hex()];
expected.sort();
assert_eq!(ids, expected);
assert!(delta.cursor >= full.cursor);
}

#[tokio::test]
#[ignore = "requires Postgres"]
async fn read_state_snapshot_encoded_bytes_bound_and_writer_not_replica() {
Expand All @@ -257,7 +364,15 @@ mod postgres_tests {
let routed = Db::from_pools(pool.clone(), dead_replica);
assert!(matches!(
routed
.read_state_snapshot(community, &key.public_key())
.read_state_snapshot(community, &key.public_key(), None)
.await,
Err(DbError::ReadStateSnapshotTooLarge)
));
// A delta with nothing changed is refused like the full read, even
// from a cursor past any database timestamp.
assert!(matches!(
routed
.read_state_snapshot(community, &key.public_key(), Some(i64::MAX))
.await,
Err(DbError::ReadStateSnapshotTooLarge)
));
Expand All @@ -267,7 +382,7 @@ mod postgres_tests {
.await
.unwrap();
let empty = routed
.read_state_snapshot(community, &key.public_key())
.read_state_snapshot(community, &key.public_key(), None)
.await
.unwrap();
assert!(empty.events.is_empty());
Expand Down
82 changes: 70 additions & 12 deletions crates/buzz-relay/src/api/bridge/read_state_snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,19 @@ pub(super) async fn query(
filters: &[Value],
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
// Exact raw shape: never silently drop constraints or unknown versions.
let expected = json!({
"kinds": [buzz_core::kind::KIND_READ_STATE],
"authors": [author.to_hex()],
"read_state_snapshot": 1,
});
if filters != [expected] {
let received_after = match filters {
[filter] => delta_cursor(filter, author),
_ => None,
};
let Some(received_after) = received_after else {
return Err(api_error(
StatusCode::BAD_REQUEST,
"read_state_snapshot requires one exact version-1 own-author kind-30078 filter",
));
}
};
let snapshot = state
.db
.read_state_snapshot(tenant.community(), author)
.read_state_snapshot(tenant.community(), author, received_after)
.await
.map_err(|error| match error {
buzz_db::DbError::ReadStateSnapshotTooLarge => api_error(
Expand All @@ -48,14 +47,41 @@ pub(super) async fn query(
)
}
})?;
Ok(Json(json!({
let mut envelope = json!({
"read_state_snapshot": 1,
"complete": true,
"community_id": tenant.community().as_uuid(),
"pubkey": author.to_hex(),
"snapshot_id": snapshot.snapshot_id,
"cursor": snapshot.cursor,
"events": snapshot.events,
})))
});
// A delta never claims completeness: it omits deletions and every write
// received before its cursor.
if received_after.is_some() {
envelope["delta"] = json!(true);
} else {
envelope["complete"] = json!(true);
envelope["snapshot_id"] = json!(snapshot.snapshot_id);
}
Ok(Json(envelope))
}

/// The request's delta cursor: `Some(None)` for a full snapshot,
/// `Some(Some(cursor))` for a delta, `None` for any other filter.
fn delta_cursor(filter: &Value, author: &nostr::PublicKey) -> Option<Option<i64>> {
let expected = json!({
"kinds": [buzz_core::kind::KIND_READ_STATE],
"authors": [author.to_hex()],
"read_state_snapshot": 1,
});
if *filter == expected {
return Some(None);
}
let mut rest = filter.as_object()?.clone();
let cursor = rest
.remove("received_after")?
.as_i64()
.filter(|c| *c >= 0)?;
(Value::Object(rest) == expected).then_some(Some(cursor))
}

#[cfg(test)]
Expand Down Expand Up @@ -255,7 +281,26 @@ mod postgres_tests {
assert_eq!(body["community_id"], community.as_uuid().to_string());
assert_eq!(body["pubkey"], key.public_key().to_hex());
assert_eq!(body["events"], json!([event]));
let cursor = body["cursor"]
.as_i64()
.expect("full snapshot carries a cursor");
let mut delta = filter(&key);
delta[0]["received_after"] = json!(cursor);
let (status, delta_body) = request(state.clone(), &host, Some(&key), delta).await;
assert_eq!(status, StatusCode::OK, "{delta_body}");
assert_eq!(delta_body["delta"], true);
assert_ne!(delta_body["complete"], true);
assert!(delta_body.get("snapshot_id").is_none());
// Inside the cursor overlap, so the delta re-reads it.
assert_eq!(delta_body["events"], json!([event]));
assert!(delta_body["cursor"].as_i64().unwrap() >= cursor);
let mut later = filter(&key);
later[0]["received_after"] =
json!(cursor + 2 * buzz_db::read_state::SNAPSHOT_CURSOR_OVERLAP_MS);
let (_, later_body) = request(state.clone(), &host, Some(&key), later).await;
assert_eq!(later_body["events"], json!([]));
let info = crate::nip11::nip11_document(&state, &host).await.unwrap();
assert_eq!(info.read_state_snapshot.as_ref().unwrap()["delta"], 1);
assert_eq!(
info.read_state_snapshot.as_ref().unwrap()["community_id"],
body["community_id"]
Expand Down Expand Up @@ -283,13 +328,26 @@ mod postgres_tests {
("read_state_snapshot", json!(2)),
("read_state_snapshot", json!(false)),
("read_state_snapshot", Value::Null),
("received_after", json!(-1)),
("received_after", json!("1")),
("received_after", json!(1.5)),
("received_after", Value::Null),
] {
let mut bad = filter(&key);
bad[0][name] = value;
let (status, body) = request(state.clone(), &host, Some(&key), bad).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{name}: {body}");
assert_ne!(body["complete"], true);
}
let mut delta_since = filter(&key);
delta_since[0]["received_after"] = json!(cursor);
delta_since[0]["since"] = json!(0);
assert_eq!(
request(state.clone(), &host, Some(&key), delta_since)
.await
.0,
StatusCode::BAD_REQUEST
);
let mut mixed = filter(&key);
mixed.as_array_mut().unwrap().push(json!({"kinds":[0]}));
assert_eq!(
Expand Down
1 change: 1 addition & 0 deletions crates/buzz-relay/src/nip11.rs
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,7 @@ pub(crate) async fn nip11_document(
"community_id": tenant.community().as_uuid(),
"max_events": buzz_db::read_state::MAX_SNAPSHOT_EVENTS,
"max_event_array_bytes": buzz_db::read_state::MAX_SNAPSHOT_BYTES,
"delta": 1,
}));
}
let tenant_host = if state.config.push_enabled {
Expand Down
Loading
Loading