rust: read peer_health rows typed, and stop swallowing database errors
A strum-derived PeerHealthKind (explicit column strings, pinned by a test) replaces kind() and the bare "clock_skew"/"schema_ahead" literals, so clear() and existing() take the enum. existing() and for_node() query their one node (and kind) instead of reading every row through all(). Fixes B7: all() matched `let Ok(..) = row else continue`, which also swallowed real SQLite errors while stepping the query and returned a short roster. Now only a row this build cannot decode is skipped, as documented; a database error fails the read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d7ed7c1b6e
commit
a87648d840
1 file changed
+77
-77
@@ -71,15 +71,17 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use rusqlite::{Transaction, params};
|
||||
use rusqlite::{OptionalExtension, Row, Transaction, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use strum::{EnumDiscriminants, EnumString, IntoStaticStr};
|
||||
|
||||
use crate::documents::Timestamp;
|
||||
use crate::node::NodePubkey;
|
||||
use crate::p2p::wire_time::max_clock_skew;
|
||||
use crate::stores::change_bus::{ChangeChannel, ChangeLedger, ChangeSignal};
|
||||
use crate::stores::sql::{Json, sql_strum_text};
|
||||
|
||||
type Result<T> = std::result::Result<T, PeerHealthStoreError>;
|
||||
|
||||
@@ -100,11 +102,19 @@ crate::stores::rusqlite_error_from!(PeerHealthStoreError, Sqlite);
|
||||
/// freely — an older row simply deserializes without them if they are
|
||||
/// `#[serde(default)]`, and a row that will not deserialize at all is dropped
|
||||
/// on read rather than failing the query (see [`PeerHealthStore::all`]).
|
||||
#[derive(uniffi::Enum, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
///
|
||||
/// [`PeerHealthKind`] is the row's `kind` column — the other half of its
|
||||
/// primary key, so one peer holds at most one row per kind and a repeat report
|
||||
/// updates rather than accumulates. Each variant spells its column text out
|
||||
/// rather than deriving it from the variant or the serde tag: the string is a
|
||||
/// database key, and it must not change because someone renamed a variant.
|
||||
#[derive(uniffi::Enum, Serialize, Deserialize, Clone, Debug, PartialEq, Eq, EnumDiscriminants)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
#[strum_discriminants(name(PeerHealthKind), derive(IntoStaticStr, EnumString))]
|
||||
pub enum PeerHealthDetail {
|
||||
/// This peer's clock is far enough ahead of ours that the bound in
|
||||
/// `wire_time` is refusing, or is about to start refusing, what it writes.
|
||||
#[strum_discriminants(strum(serialize = "clock_skew"))]
|
||||
ClockSkew {
|
||||
/// How far ahead of this node's clock the peer is, in seconds.
|
||||
/// Positive by construction: a peer whose clock is *behind* loses
|
||||
@@ -126,6 +136,7 @@ pub enum PeerHealthDetail {
|
||||
/// peer named on the row. The copy has to say so in as many words — see
|
||||
/// [`crate::copy::peer_health`] — because a message sitting on another
|
||||
/// node's roster row reads by default as being about that node.
|
||||
#[strum_discriminants(strum(serialize = "schema_ahead"))]
|
||||
SchemaAhead {
|
||||
/// The peer's `SYNC_PROTOCOL_VERSION`, from the `SyncHeader` that
|
||||
/// opens every exchange. Stored; the local version it is compared
|
||||
@@ -140,20 +151,7 @@ pub enum PeerHealthDetail {
|
||||
},
|
||||
}
|
||||
|
||||
impl PeerHealthDetail {
|
||||
/// The `kind` column for this variant — the other half of the row's
|
||||
/// primary key, so one peer holds at most one row per kind and a repeat
|
||||
/// report updates rather than accumulates.
|
||||
///
|
||||
/// Deliberately not derived from the serde tag: this string is a database
|
||||
/// key, and it must not change because someone renamed a variant.
|
||||
pub fn kind(&self) -> &'static str {
|
||||
match self {
|
||||
Self::ClockSkew { .. } => "clock_skew",
|
||||
Self::SchemaAhead { .. } => "schema_ahead",
|
||||
}
|
||||
}
|
||||
}
|
||||
sql_strum_text!(PeerHealthKind);
|
||||
|
||||
/// One unresolved problem with one peer, as stored.
|
||||
#[derive(uniffi::Record, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
@@ -263,9 +261,9 @@ impl PeerHealthStore {
|
||||
/// stayed wrong.
|
||||
pub fn observe_clock(&self, tx: &Transaction, node: &NodePubkey, skew_secs: i64) -> Result<()> {
|
||||
if skew_secs <= clock_skew_warn_threshold().num_seconds() {
|
||||
return self.clear(tx, node, "clock_skew");
|
||||
return self.clear(tx, node, PeerHealthKind::ClockSkew);
|
||||
}
|
||||
let records_dropped = match self.existing_clock_skew(tx, node)? {
|
||||
let records_dropped = match self.existing(tx, node, PeerHealthKind::ClockSkew)? {
|
||||
Some(PeerHealthDetail::ClockSkew { records_dropped, .. }) => records_dropped,
|
||||
_ => 0,
|
||||
};
|
||||
@@ -293,7 +291,7 @@ impl PeerHealthStore {
|
||||
skew_secs: i64,
|
||||
count: u64,
|
||||
) -> Result<()> {
|
||||
let skew_secs = match self.existing_clock_skew(tx, node)? {
|
||||
let skew_secs = match self.existing(tx, node, PeerHealthKind::ClockSkew)? {
|
||||
Some(PeerHealthDetail::ClockSkew { skew_secs: known, .. }) => known.max(skew_secs),
|
||||
_ => skew_secs,
|
||||
};
|
||||
@@ -338,9 +336,9 @@ impl PeerHealthStore {
|
||||
records_skipped: u64,
|
||||
) -> Result<()> {
|
||||
if peer_version <= crate::p2p::doc_sync::SYNC_PROTOCOL_VERSION {
|
||||
return self.clear(tx, node, "schema_ahead");
|
||||
return self.clear(tx, node, PeerHealthKind::SchemaAhead);
|
||||
}
|
||||
let records_skipped = match self.existing(tx, node, "schema_ahead")? {
|
||||
let records_skipped = match self.existing(tx, node, PeerHealthKind::SchemaAhead)? {
|
||||
Some(PeerHealthDetail::SchemaAhead { records_skipped: known, .. })
|
||||
if records_skipped == 0 =>
|
||||
{
|
||||
@@ -351,30 +349,24 @@ impl PeerHealthStore {
|
||||
self.upsert(tx, node, &PeerHealthDetail::SchemaAhead { peer_version, records_skipped })
|
||||
}
|
||||
|
||||
/// This peer's stored clock-skew detail, if it has one — what the two
|
||||
/// clock writers read before deciding what to carry forward.
|
||||
fn existing_clock_skew(
|
||||
&self,
|
||||
tx: &Transaction,
|
||||
node: &NodePubkey,
|
||||
) -> Result<Option<PeerHealthDetail>> {
|
||||
self.existing(tx, node, "clock_skew")
|
||||
}
|
||||
|
||||
/// This peer's stored detail of one kind, if it has one. Keyed by the
|
||||
/// `kind()` string rather than by matching the variant, so a writer cannot
|
||||
/// read one kind's row and write another's.
|
||||
/// This peer's stored detail of one kind, if it has one — what the
|
||||
/// writers read before deciding what to carry forward. Keyed by the kind
|
||||
/// column rather than by matching the variant, so a writer cannot read one
|
||||
/// kind's row and write another's. A detail this build cannot decode reads
|
||||
/// as none, as it does in [`all`](Self::all).
|
||||
fn existing(
|
||||
&self,
|
||||
tx: &Transaction,
|
||||
node: &NodePubkey,
|
||||
kind: &str,
|
||||
kind: PeerHealthKind,
|
||||
) -> Result<Option<PeerHealthDetail>> {
|
||||
Ok(self
|
||||
.for_node(tx, node)?
|
||||
.into_iter()
|
||||
.map(|issue| issue.detail)
|
||||
.find(|detail| detail.kind() == kind))
|
||||
Ok(tx
|
||||
.prepare_cached("SELECT detail FROM peer_health WHERE node_pubkey = ?1 AND kind = ?2")?
|
||||
.query_row(params![node.as_bytes(), kind], |row| {
|
||||
Ok(row.get::<_, Json<PeerHealthDetail>>(0).ok().map(|d| d.0))
|
||||
})
|
||||
.optional()?
|
||||
.flatten())
|
||||
}
|
||||
|
||||
/// Insert the issue, or refresh an existing one of the same kind.
|
||||
@@ -395,7 +387,7 @@ impl PeerHealthStore {
|
||||
ON CONFLICT(node_pubkey, kind) DO UPDATE SET
|
||||
detail = ?3,
|
||||
last_at = ?4",
|
||||
params![&node.as_bytes()[..], detail.kind(), encoded, now.to_rfc3339()],
|
||||
params![node.as_bytes(), PeerHealthKind::from(detail), encoded, now],
|
||||
)?;
|
||||
self.changes.touched();
|
||||
Ok(())
|
||||
@@ -403,10 +395,10 @@ impl PeerHealthStore {
|
||||
|
||||
/// Drop this peer's issue of the given kind, if it has one. A no-op when
|
||||
/// it does not, which is the ordinary case on a healthy ensemble.
|
||||
pub fn clear(&self, tx: &Transaction, node: &NodePubkey, kind: &str) -> Result<()> {
|
||||
pub fn clear(&self, tx: &Transaction, node: &NodePubkey, kind: PeerHealthKind) -> Result<()> {
|
||||
let removed = tx.execute(
|
||||
"DELETE FROM peer_health WHERE node_pubkey = ?1 AND kind = ?2",
|
||||
params![&node.as_bytes()[..], kind],
|
||||
params![node.as_bytes(), kind],
|
||||
)?;
|
||||
// Only announce a change when there was one: an announcement arriving
|
||||
// every re-announce interval from every healthy peer would otherwise
|
||||
@@ -423,37 +415,9 @@ impl PeerHealthStore {
|
||||
/// load, and a per-member query would put the peer count into the cost of
|
||||
/// drawing a screen.
|
||||
pub fn all(&self, tx: &Transaction) -> Result<HashMap<NodePubkey, Vec<PeerHealthIssue>>> {
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"SELECT node_pubkey, detail, first_at, last_at
|
||||
FROM peer_health
|
||||
ORDER BY first_at ASC",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |row| {
|
||||
Ok((
|
||||
row.get::<_, Vec<u8>>(0)?,
|
||||
row.get::<_, String>(1)?,
|
||||
row.get::<_, String>(2)?,
|
||||
row.get::<_, String>(3)?,
|
||||
))
|
||||
})?;
|
||||
let mut out: HashMap<NodePubkey, Vec<PeerHealthIssue>> = HashMap::new();
|
||||
for row in rows {
|
||||
// A row this build cannot read is a row written by a build that
|
||||
// knew a kind this one doesn't — a downgrade, or a mid-upgrade
|
||||
// ensemble. Skipping it costs a diagnostic message; failing the
|
||||
// query would cost the whole roster.
|
||||
let Ok((pubkey, detail, first_at, last_at)) = row else { continue };
|
||||
let Ok(bytes) = <[u8; 32]>::try_from(pubkey) else { continue };
|
||||
let Ok(detail) = serde_json::from_str::<PeerHealthDetail>(&detail) else { continue };
|
||||
let (Some(first_at), Some(last_at)) = (parse_secs(&first_at), parse_secs(&last_at))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
out.entry(NodePubkey(bytes)).or_default().push(PeerHealthIssue {
|
||||
detail,
|
||||
first_at_secs: first_at,
|
||||
last_at_secs: last_at,
|
||||
});
|
||||
for (node, issue) in issues_where(tx, "1", params![])? {
|
||||
out.entry(node).or_default().push(issue);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -461,12 +425,37 @@ impl PeerHealthStore {
|
||||
/// This one peer's issues — the node detail screens, which have one node
|
||||
/// and no use for the rest of the map.
|
||||
pub fn for_node(&self, tx: &Transaction, node: &NodePubkey) -> Result<Vec<PeerHealthIssue>> {
|
||||
Ok(self.all(tx)?.remove(node).unwrap_or_default())
|
||||
let issues = issues_where(tx, "node_pubkey = ?1", params![node.as_bytes()])?;
|
||||
Ok(issues.into_iter().map(|(_, issue)| issue).collect())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_secs(rfc3339: &str) -> Option<i64> {
|
||||
chrono::DateTime::parse_from_rfc3339(rfc3339).ok().map(|d| d.timestamp())
|
||||
/// The issues on the rows matching `predicate`, oldest first.
|
||||
fn issues_where(
|
||||
tx: &Transaction,
|
||||
predicate: &str,
|
||||
params: impl rusqlite::Params,
|
||||
) -> Result<Vec<(NodePubkey, PeerHealthIssue)>> {
|
||||
let mut stmt = tx.prepare_cached(&format!(
|
||||
"SELECT node_pubkey, detail, first_at, last_at FROM peer_health
|
||||
WHERE {predicate} ORDER BY first_at ASC"
|
||||
))?;
|
||||
let rows = stmt.query_map(params, |row| Ok(issue_from_row(row)))?;
|
||||
Ok(rows.filter_map(rusqlite::Result::transpose).collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
/// One row, or `None` if this build cannot read it. Such a row was written by
|
||||
/// a build that knew a kind this one doesn't — a downgrade, or a mid-upgrade
|
||||
/// ensemble. Skipping it costs a diagnostic message; failing the query would
|
||||
/// cost the whole roster. (A database error while stepping the query still
|
||||
/// fails it: that is [`issues_where`]'s `?`, not this.)
|
||||
fn issue_from_row(row: &Row<'_>) -> Option<(NodePubkey, PeerHealthIssue)> {
|
||||
let issue = PeerHealthIssue {
|
||||
detail: row.get::<_, Json<PeerHealthDetail>>(1).ok()?.0,
|
||||
first_at_secs: row.get::<_, Timestamp>(2).ok()?.0.timestamp(),
|
||||
last_at_secs: row.get::<_, Timestamp>(3).ok()?.0.timestamp(),
|
||||
};
|
||||
Some((NodePubkey(row.get(0).ok()?), issue))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -499,6 +488,14 @@ mod tests {
|
||||
issues(store).first().map(|i| i.detail.clone())
|
||||
}
|
||||
|
||||
/// The stored kind strings; rows already on disk hold these.
|
||||
#[rstest]
|
||||
#[case(PeerHealthKind::ClockSkew, "clock_skew")]
|
||||
#[case(PeerHealthKind::SchemaAhead, "schema_ahead")]
|
||||
fn kind_column_text(#[case] kind: PeerHealthKind, #[case] text: &str) {
|
||||
assert_eq!(<&str>::from(kind), text);
|
||||
}
|
||||
|
||||
/// A clock inside the tolerance says nothing at all. Every device
|
||||
/// disagrees with every other by some seconds; a roster that reported
|
||||
/// that would be a roster nobody reads.
|
||||
@@ -616,7 +613,10 @@ mod tests {
|
||||
}
|
||||
|
||||
fn schema_detail(store: &TestStore) -> Option<PeerHealthDetail> {
|
||||
issues(store).into_iter().map(|i| i.detail).find(|d| d.kind() == "schema_ahead")
|
||||
issues(store)
|
||||
.into_iter()
|
||||
.map(|i| i.detail)
|
||||
.find(|d| PeerHealthKind::from(d) == PeerHealthKind::SchemaAhead)
|
||||
}
|
||||
|
||||
/// A peer at or behind this build can put nothing on the wire this build
|
||||
|
||||
Reference in new issue
Block a user