aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/api/events.rs67
-rw-r--r--src/federation/party.rs21
-rw-r--r--src/federation/store/memory.rs75
3 files changed, 144 insertions, 19 deletions
diff --git a/src/api/events.rs b/src/api/events.rs
index 55b29f1..1c4b826 100644
--- a/src/api/events.rs
+++ b/src/api/events.rs
@@ -7,7 +7,7 @@
use axum::{
Extension, Json, Router,
body::Bytes,
- extract::{Path, State},
+ extract::{Path, Query, State},
http::{StatusCode, header::CONTENT_TYPE},
response::{IntoResponse, Response},
routing::{get, post},
@@ -83,12 +83,36 @@ fn why(refusal: &Refusal) -> String {
}
}
+/// Whom `GET /events` names its heads for.
+#[derive(Deserialize)]
+struct Summarized {
+ party: Option<String>,
+}
+
+/// The last write, key set or node list `store` took of `party`: what its next is to have
+/// in its history, as of two neither in the other's the lower ID counts, not the later.
+fn latest_of(store: &Store<Federation>, party: &str) -> Option<Id> {
+ use crate::federation::event::{Does, Event, Signed};
+ store.taken().iter().rev().copied().find(|id| {
+ matches!(
+ store.get(id).and_then(Event::read_taken),
+ Some(Event::Signed(Signed {
+ party: signer,
+ does: Does::Write { .. } | Does::Keys(_) | Does::Nodes(_),
+ ..
+ })) if signer == party
+ )
+ })
+}
+
/// `GET /events`: the store's ID, its checkpoint's, its heads, as many as an event may
-/// name, what a new event builds on (`Store::building_on`), how many events it took
+/// name, what a new event builds on (`Store::building_on`; with `?party=NAME`, one holding
+/// that party's last write, key set or node list among them, where the store holds more
+/// heads than that, `latest_of`), how many events it took
/// after its checkpoint, the event it stopped at, if any, the node's ID and party, whether
/// the node votes for it by itself, and the revisions of the federation its continuum
/// knows.
-async fn summary(State(state): State<AppState>) -> Response {
+async fn summary(State(state): State<AppState>, Query(summarized): Query<Summarized>) -> Response {
let party = state.holding.party().map(str::to_owned);
let votes = state.holding.votes_by_itself();
with_store(&state, |store| {
@@ -98,7 +122,14 @@ async fn summary(State(state): State<AppState>) -> Response {
json!({
"store": store.id().to_string(),
"checkpoint": Id::of(store.checkpoint()).to_string(),
- "heads": ids(store.building_on()),
+ "heads": ids(store.building_on_with(
+ &summarized
+ .party
+ .as_deref()
+ .and_then(|party| latest_of(store, party))
+ .into_iter()
+ .collect::<Vec<_>>(),
+ )),
"taken": store.taken().len(),
"stopped": stopped,
"node": state.local_id(),
@@ -578,3 +609,31 @@ async fn allow(State(state): State<AppState>, Json(named): Json<Named>) -> Respo
no_store()
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::federation::harness::{self, Party, Spec};
+
+ /// A party's latest event, for what its next builds on: its last write, key set or
+ /// node list, not a proposal or a vote of its, which hold no place's value.
+ #[test]
+ fn a_partys_latest_event_is_its_last_write_key_set_or_node_list() {
+ let (tv, lass) = (Party::new("tv", 1), Party::new("lass", 2));
+ let first = Spec::first(&[&tv, &lass], &[]);
+ let mut store = Store::<Federation>::new(first.root(), Vec::new()).unwrap();
+ let root = store.id();
+ let mut take = |bytes: Vec<u8>| -> Id {
+ let id = Id::of(&bytes);
+ assert!(matches!(store.offer(bytes), Offered::Taken(_)));
+ id
+ };
+ take(tv.write(&[root], "home/tv/a", harness::str("1")));
+ let keys = take(tv.keys(&[root], &[tv.key_line()]));
+ let theirs = take(lass.write(&[root], "home/lass/a", harness::str("1")));
+ take(tv.propose(&[root], &first.after(first.hash()).json()));
+ assert_eq!(latest_of(&store, "tv"), Some(keys));
+ assert_eq!(latest_of(&store, "lass"), Some(theirs));
+ assert_eq!(latest_of(&store, "makefu"), None);
+ }
+}
diff --git a/src/federation/party.rs b/src/federation/party.rs
index c8f19ea..4420478 100644
--- a/src/federation/party.rs
+++ b/src/federation/party.rs
@@ -1464,7 +1464,7 @@ async fn sign(
path: &Path,
does: (&str, Json),
) -> Result<()> {
- let (_, heads) = node.summary().await?;
+ let heads = node.heads_for(&signer.party).await?;
let event = signer.sign(&heads, does)?;
record.signed(&event);
record.save(path).map_err(|why| anyhow!(why))?;
@@ -2553,6 +2553,25 @@ impl Node {
Ok(self.answer(response).await?.json().await?)
}
+ /// The heads an event of `party` builds on: the node's, one holding the party's last
+ /// write, key set or node list among them (`GET /events?party=`), so that its next has
+ /// it in its history where the store holds more heads than an event names. A node
+ /// before 0.1.0 names its heads whoever asks.
+ async fn heads_for(&self, party: &str) -> Result<Vec<Id>> {
+ let response = self
+ .request(reqwest::Method::GET, "/events")?
+ .query(&[("party", party)])
+ .send()
+ .await?;
+ let summary: JsonValue = self.answer(response).await?.json().await?;
+ Ok(summary["heads"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(|id| id.as_str().and_then(Id::from_hex))
+ .collect())
+ }
+
/// The store's ID, and its heads.
async fn summary(&self) -> Result<(Id, Vec<Id>)> {
let summary = self.get("/events").await?;
diff --git a/src/federation/store/memory.rs b/src/federation/store/memory.rs
index 73ee1c3..d49fca0 100644
--- a/src/federation/store/memory.rs
+++ b/src/federation/store/memory.rs
@@ -287,26 +287,46 @@ impl<F: Fold> Store<F> {
/// What a new event builds on: its heads, as many as an event may name
/// (`Fold::DEPENDENCIES`), the earliest taken first, so that what is written merges
/// what stayed apart the longest; among them always one holding what the fold judges
- /// a new event by (`Fold::judged_by`), where a head does: the earliest such, in place
- /// of the last of the others. Without it, an event on old heads alone is judged as at
- /// their histories: under the federation's version before, say.
+ /// a new event by (`Fold::judged_by`), where a head does. Without it, an event on old
+ /// heads alone is judged as at their histories: under the federation's version before,
+ /// say.
pub(crate) fn building_on(&self) -> Vec<Id> {
+ self.building_on_with(&[])
+ }
+
+ /// As `building_on`, among them a head holding each of `also` too, where one does: a
+ /// writer's own last event, so that its next has it in its history. Each takes the
+ /// place of the last of the others.
+ pub(crate) fn building_on_with(&self, also: &[Id]) -> Vec<Id> {
let mut heads = self.heads();
if heads.len() <= F::DEPENDENCIES {
return heads;
}
- let judged_by = F::judged_by(&self.state);
- let holding = heads.iter().copied().find(|head| {
- let history = self.history(std::slice::from_ref(head));
- judged_by.iter().any(|id| history.contains(id))
- });
- heads.truncate(F::DEPENDENCIES);
- if let Some(holding) = holding
- && !heads.contains(&holding)
- {
- heads.pop();
- heads.push(holding);
+ let holding = |wanted: &[Id]| {
+ heads.iter().copied().find(|head| {
+ let history = self.history(std::slice::from_ref(head));
+ wanted.iter().any(|id| history.contains(id))
+ })
+ };
+ let mut keep: Vec<Id> = holding(&F::judged_by(&self.state)).into_iter().collect();
+ for id in also {
+ if let Some(head) = holding(std::slice::from_ref(id))
+ && !keep.contains(&head)
+ && keep.len() < F::DEPENDENCIES
+ {
+ keep.push(head);
+ }
}
+ let others = F::DEPENDENCIES - keep.len();
+ let mut left = others;
+ heads.retain(|head| {
+ if keep.contains(head) {
+ return true;
+ }
+ let taken = left > 0;
+ left = left.saturating_sub(1);
+ taken
+ });
heads
}
@@ -1203,6 +1223,33 @@ mod tests {
);
}
+ /// What a new event builds on holds the events it is asked to, a writer's own last
+ /// one say: of more heads than an event may name, the earliest alone may lack it, and
+ /// of two events of one writer neither in the other's history, the lower ID counts.
+ #[test]
+ fn a_new_event_builds_on_what_it_is_asked_to_hold() {
+ let mut store = store();
+ let root = store.id();
+ let apart: Vec<Id> = (0..=TestFold::DEPENDENCIES + 1)
+ .map(|n| taken(store.offer(testfold::put(&[root], &format!("k{n}"), "1"))))
+ .collect();
+ let (last, before) = (apart[apart.len() - 1], apart[apart.len() - 2]);
+ assert!(!store.building_on().contains(&last));
+ let on = store.building_on_with(&[last]);
+ assert_eq!(on.len(), TestFold::DEPENDENCIES);
+ assert!(on.contains(&last) && !on.contains(&before));
+ assert_eq!(on[..on.len() - 1], apart[..TestFold::DEPENDENCIES - 1]);
+ // One held already by what it builds on changes nothing; nor does one not held.
+ assert_eq!(store.building_on_with(&[apart[0]]), store.building_on());
+ assert_eq!(
+ store.building_on_with(&[Id::of(b"none")]),
+ store.building_on()
+ );
+ // In the history of a head, that head.
+ let later = taken(store.offer(testfold::put(&[last], "later", "1")));
+ assert!(store.building_on_with(&[last]).contains(&later));
+ }
+
/// Heads leave out what is neither among them, in their history, nor above them.
#[test]
fn heads_leave_out_what_is_beside_them() {