aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-29 03:21:43 +0000
committertv <tv@krebsco.de>2026-11-29 03:21:43 +0000
commite63d30c2581033a85489b10c3f5b252fdbb5049e (patch)
tree5f4e6f65f1cecfb32f841e7ad7d9d106aeb69b20 /src
parent9188fa6e13ea7facfab5fb6f55bf26444ec2c01e (diff)
state: plain writes take a view to write, Automerge's are asked for as such
AppState::mutate_doc, mutate_doc_registering and mutate_doc_by hand what they are given a document::view::Write: the member registry, the users, sessions, forgetting and bootstrap write through them, and take whatever kind of document gives it. AppState::mutate_doc_for is for what asks more of an Automerge document than values at paths (the store's API, a remake's host, a store's events), and gives the heads after the write. What reads a view takes one of any size (dyn Write among them).
Diffstat (limited to 'src')
-rw-r--r--src/access/bans.rs2
-rw-r--r--src/access/challenge.rs2
-rw-r--r--src/access/envelope.rs8
-rw-r--r--src/access/policy.rs4
-rw-r--r--src/access/registry.rs12
-rw-r--r--src/access/rules.rs17
-rw-r--r--src/access/sealed.rs12
-rw-r--r--src/access/strict.rs6
-rw-r--r--src/access/token.rs16
-rw-r--r--src/api/access.rs4
-rw-r--r--src/api/login.rs5
-rw-r--r--src/api/peers.rs2
-rw-r--r--src/api/users.rs8
-rw-r--r--src/federation/held.rs41
-rw-r--r--src/remake/mod.rs2
-rw-r--r--src/simtest/hyparview.rs4
-rw-r--r--src/simtest/mod.rs4
-rw-r--r--src/simtest/remakes.rs4
-rw-r--r--src/simtest/timing.rs4
-rw-r--r--src/state/host.rs15
-rw-r--r--src/state/mod.rs52
-rw-r--r--src/swarm/members.rs38
22 files changed, 159 insertions, 103 deletions
diff --git a/src/access/bans.rs b/src/access/bans.rs
index 999f610..1cb1452 100644
--- a/src/access/bans.rs
+++ b/src/access/bans.rs
@@ -14,6 +14,6 @@ pub(crate) fn path(node: &str) -> Vec<String> {
}
/// Whether `doc` bans `node`.
-pub(crate) fn banned(doc: &impl Read, node: &str) -> bool {
+pub(crate) fn banned(doc: &(impl Read + ?Sized), node: &str) -> bool {
view::read_plain(doc, &path(node)).ok().flatten().is_some()
}
diff --git a/src/access/challenge.rs b/src/access/challenge.rs
index 4dd8dfb..670574c 100644
--- a/src/access/challenge.rs
+++ b/src/access/challenge.rs
@@ -70,7 +70,7 @@ pub(crate) struct Used(HashMap<String, (u64, String)>);
/// `per_user` of its own still remembered. Why not, if not.
#[allow(clippy::too_many_arguments)]
pub(crate) fn take(
- doc: &impl Read,
+ doc: &(impl Read + ?Sized),
key: &NodeKey,
challenge: &str,
signature: &str,
diff --git a/src/access/envelope.rs b/src/access/envelope.rs
index d592bff..95371d3 100644
--- a/src/access/envelope.rs
+++ b/src/access/envelope.rs
@@ -39,7 +39,7 @@ pub(crate) fn listed_at() -> Vec<String> {
/// The paths `doc` lists as user-signed; an entry that isn't a list of strings is left
/// out.
-pub(crate) fn listed(doc: &impl Read) -> Vec<Vec<String>> {
+pub(crate) fn listed(doc: &(impl Read + ?Sized)) -> Vec<Vec<String>> {
let Ok(Some(JsonValue::Array(entries))) = view::read_plain(doc, &listed_at()) else {
return Vec::new();
};
@@ -67,7 +67,7 @@ fn deciding() -> Vec<Vec<String>> {
/// The paths whose values their users sign under a strict policy: what decides who may
/// do what (`deciding`), and those `doc` lists (`listed`).
-pub(crate) fn signed_paths(doc: &impl Read) -> Vec<Vec<String>> {
+pub(crate) fn signed_paths(doc: &(impl Read + ?Sized)) -> Vec<Vec<String>> {
let mut paths = deciding();
paths.extend(listed(doc));
paths
@@ -151,7 +151,7 @@ pub(crate) fn read(envelope: &str) -> Result<Payload, String> {
/// its swarm, that path, naming what it replaces and numbered after it, signed by one of
/// its user's keys, a user who may write there.
pub(crate) fn check(
- doc: &impl Read,
+ doc: &(impl Read + ?Sized),
envelope: &str,
path: &[String],
previous: Option<&str>,
@@ -207,7 +207,7 @@ pub(crate) fn check(
/// with only its keys changed from the one at `path` in `doc`, one left at least: a user
/// manages its own keys, whatever else it may do.
fn own_keys_only(
- doc: &impl Read,
+ doc: &(impl Read + ?Sized),
payload: &Payload,
user: &registry::User,
path: &[String],
diff --git a/src/access/policy.rs b/src/access/policy.rs
index e4027b8..e596175 100644
--- a/src/access/policy.rs
+++ b/src/access/policy.rs
@@ -119,7 +119,7 @@ pub(crate) fn as_written(value: &JsonValue) -> Result<Policy, String> {
/// where its `store` is, as continuum writes them: an Automerge text there, or one holding
/// the policy, reads as a string in plain JSON, so a policy that would read so only
/// through a text is one nobody knows, never what its characters spell.
-pub(crate) fn of(doc: &impl Read) -> Policy {
+pub(crate) fn of(doc: &(impl Read + ?Sized)) -> Policy {
match view::read_plain(doc, &path()) {
Ok(Some(value)) => match read(&value) {
policy if policy.strict() && !a_string(doc, "values") => {
@@ -138,7 +138,7 @@ pub(crate) fn of(doc: &impl Read) -> Policy {
/// Whether the policy `doc` holds, read in typed JSON (where a text is tagged, and an
/// envelope reads as its payload), has a string for its `key`.
-fn a_string(doc: &impl Read, key: &str) -> bool {
+fn a_string(doc: &(impl Read + ?Sized), key: &str) -> bool {
matches!(
doc.read_typed(&path()),
Ok(Some(value)) if value.get(key).is_some_and(JsonValue::is_string)
diff --git a/src/access/registry.rs b/src/access/registry.rs
index 5a58e1f..f0034ba 100644
--- a/src/access/registry.rs
+++ b/src/access/registry.rs
@@ -35,12 +35,12 @@ pub(crate) fn user_path(name: &str) -> Vec<String> {
/// Whether the swarm has a registry: until it has, every user a node lets in may do
/// everything but write protocol data (`docs/access.md`, A swarm without a registry).
-pub(crate) fn exists(doc: &impl Read) -> bool {
+pub(crate) fn exists(doc: &(impl Read + ?Sized)) -> bool {
matches!(view::keys_at(doc, &users_dir()), Ok(Some(_)))
}
/// The registered users' names, sorted.
-pub(crate) fn names(doc: &impl Read) -> Vec<String> {
+pub(crate) fn names(doc: &(impl Read + ?Sized)) -> Vec<String> {
let mut names = view::keys_at(doc, &users_dir())
.ok()
.flatten()
@@ -128,7 +128,7 @@ impl User {
}
/// The entry of user `name`, if it has one.
-pub(crate) fn user(doc: &impl Read, name: &str) -> Option<User> {
+pub(crate) fn user(doc: &(impl Read + ?Sized), name: &str) -> Option<User> {
let value = view::read_plain(doc, &user_path(name)).ok()??;
let mut user = value.is_object().then(|| User::from_json(&value))?;
// A damaged one revokes every token.
@@ -156,7 +156,7 @@ pub(crate) fn session_path(name: &str, session: &str) -> Vec<String> {
}
/// Whether user `name`'s session `session` was ended (`session_path`).
-pub(crate) fn session_ended(doc: &impl Read, name: &str, session: &str) -> bool {
+pub(crate) fn session_ended(doc: &(impl Read + ?Sized), name: &str, session: &str) -> bool {
view::read_path(doc, &session_path(name, session))
.ok()
.flatten()
@@ -164,7 +164,7 @@ pub(crate) fn session_ended(doc: &impl Read, name: &str, session: &str) -> bool
}
/// The users who may manage users: enabled, with `write` on `_continuum/users`.
-pub(crate) fn managers(doc: &impl Read) -> Vec<String> {
+pub(crate) fn managers(doc: &(impl Read + ?Sized)) -> Vec<String> {
names(doc)
.into_iter()
.filter(|name| caps_of(doc, name).allows(Right::Write, &users_dir()))
@@ -172,7 +172,7 @@ pub(crate) fn managers(doc: &impl Read) -> Vec<String> {
}
/// What user `name` may do: none if it isn't registered (or is disabled).
-pub(crate) fn caps_of(doc: &impl Read, name: &str) -> Caps {
+pub(crate) fn caps_of(doc: &(impl Read + ?Sized), name: &str) -> Caps {
user(doc, name).map(|user| user.caps()).unwrap_or_default()
}
diff --git a/src/access/rules.rs b/src/access/rules.rs
index 93cef63..d8831ce 100644
--- a/src/access/rules.rs
+++ b/src/access/rules.rs
@@ -219,7 +219,7 @@ pub(crate) fn judge_reading(
/// In a swarm holding a store of some fold, as `holding` judges it there, which is its
/// kind of document's to say.
pub(crate) fn judge_seen(
- at: &impl Read,
+ at: &(impl Read + ?Sized),
epoch: Epoch,
unit: &Unit<'_>,
read: &mut Seen,
@@ -502,7 +502,7 @@ pub(crate) fn judge_held(
/// string put there that is one (or deleting what is there); nothing within one; nothing
/// in an object nowhere to be found, which might be one.
fn sealed_values(
- at: &impl Read,
+ at: &(impl Read + ?Sized),
declared: &[super::sealed::Declared],
ops: &[Op],
) -> Result<(), String> {
@@ -534,7 +534,7 @@ fn sealed_values(
/// as a write replacing it does); nothing within one; above one,
/// nothing replacing or deleting what holds one (a map made where there is none yet,
/// what is inside a list or text, which holds none).
-fn signed_values(at: &impl Read, ops: &[Op]) -> Result<(), String> {
+fn signed_values(at: &(impl Read + ?Sized), ops: &[Op]) -> Result<(), String> {
let signed = super::envelope::signed_paths(at);
for op in ops {
let path = &op.path;
@@ -589,7 +589,7 @@ fn signed_values(at: &impl Read, ops: &[Op]) -> Result<(), String> {
/// Whether what is at `path` in `at` holds a value at a place for one its user signs,
/// of `signed` (`envelope::signed_paths`), signed or from before the policy; one that
/// doesn't read, as if it did.
-fn holds_signed(at: &impl Read, path: &[String], signed: &[Vec<String>]) -> bool {
+fn holds_signed(at: &(impl Read + ?Sized), path: &[String], signed: &[Vec<String>]) -> bool {
fn within(value: &serde_json::Value, place: &mut Vec<String>, signed: &[Vec<String>]) -> bool {
if super::envelope::is_signed(signed, place) {
return true;
@@ -628,7 +628,12 @@ fn shown(path: &Path) -> String {
/// Whether remake `id`, coordinated by `node`, made `epoch`: as its snapshot's metadata
/// says (`remake::snapshot`), at `at`. Never genesis.
-pub(super) fn made_the_epoch(at: &impl Read, epoch: Epoch, id: &str, node: &str) -> bool {
+pub(super) fn made_the_epoch(
+ at: &(impl Read + ?Sized),
+ epoch: Epoch,
+ id: &str,
+ node: &str,
+) -> bool {
if epoch.generation == 0 {
return false;
}
@@ -647,7 +652,7 @@ pub(super) fn made_the_epoch(at: &impl Read, epoch: Epoch, id: &str, node: &str)
}
/// The coordinator remake `id`'s proposal names, at `at`.
-pub(super) fn coordinator(at: &impl Read, id: &str) -> Option<String> {
+pub(super) fn coordinator(at: &(impl Read + ?Sized), id: &str) -> Option<String> {
let proposal = view::read_path(at, &meta::path(&[meta::REMAKES, id, "proposal"]))
.ok()
.flatten()?;
diff --git a/src/access/sealed.rs b/src/access/sealed.rs
index c30bea7..b39a465 100644
--- a/src/access/sealed.rs
+++ b/src/access/sealed.rs
@@ -48,7 +48,7 @@ pub(crate) struct Declared {
}
/// What `doc` declares sealed; an entry that doesn't read as one is left out.
-pub(crate) fn declared(doc: &impl Read) -> Vec<Declared> {
+pub(crate) fn declared(doc: &(impl Read + ?Sized)) -> Vec<Declared> {
let Ok(Some(JsonValue::Array(entries))) = view::read_plain(doc, &declared_at()) else {
return Vec::new();
};
@@ -141,7 +141,11 @@ pub(crate) fn recipients(sealed: &str) -> Result<BTreeSet<String>, String> {
/// (as its writer saw it): a sealed value, or, signed by its user (`access::envelope`),
/// one holding a sealed value or `null` (deleted); with readers declared, sealed for
/// exactly their keys.
-pub(crate) fn check(doc: &impl Read, declared: &Declared, value: &JsonValue) -> Result<(), String> {
+pub(crate) fn check(
+ doc: &(impl Read + ?Sized),
+ declared: &Declared,
+ value: &JsonValue,
+) -> Result<(), String> {
let JsonValue::String(text) = value else {
return Err("a sealed value is a string (cs1.<age file>)".to_owned());
};
@@ -184,7 +188,7 @@ pub(crate) fn check(doc: &impl Read, declared: &Declared, value: &JsonValue) ->
/// Checks what is at `path` in `doc` after a write there: nothing within a declared
/// place but its value, and every value at one (at `path` or below it) as `check` says.
/// Why not, if not.
-pub(crate) fn kept(doc: &impl Read, path: &[String]) -> Result<(), String> {
+pub(crate) fn kept(doc: &(impl Read + ?Sized), path: &[String]) -> Result<(), String> {
let declared = declared(doc);
if declared.is_empty() || !reaches(&declared, path) {
return Ok(());
@@ -193,7 +197,7 @@ pub(crate) fn kept(doc: &impl Read, path: &[String]) -> Result<(), String> {
return Err(format!("/{} is within a sealed value", path.join("/")));
}
fn walk(
- doc: &impl Read,
+ doc: &(impl Read + ?Sized),
declared: &[Declared],
value: &JsonValue,
at: &mut Vec<String>,
diff --git a/src/access/strict.rs b/src/access/strict.rs
index 9857bed..0aac192 100644
--- a/src/access/strict.rs
+++ b/src/access/strict.rs
@@ -95,9 +95,9 @@ pub(crate) fn digest(value: &JsonValue) -> String {
/// The places values are signed in `doc` (`envelope::signed_paths`, `*` as `doc` has
/// them) that hold one, with it, as the store reads it.
-pub(crate) fn held(doc: &impl Read) -> Vec<(Vec<String>, JsonValue)> {
+pub(crate) fn held(doc: &(impl Read + ?Sized)) -> Vec<(Vec<String>, JsonValue)> {
fn expand(
- doc: &impl Read,
+ doc: &(impl Read + ?Sized),
pattern: &[String],
at: Vec<String>,
out: &mut Vec<(Vec<String>, JsonValue)>,
@@ -135,7 +135,7 @@ pub(crate) fn held(doc: &impl Read) -> Vec<(Vec<String>, JsonValue)> {
/// held at a signed place now, the policy `policy`, for `user` to look over and sign at
/// `at`. Its exact line.
pub(crate) fn manifest_of(
- doc: &impl Read,
+ doc: &(impl Read + ?Sized),
swarm: &str,
epoch: crate::document::replica::EpochRecord,
base: &[crate::document::ChangeHash],
diff --git a/src/access/token.rs b/src/access/token.rs
index 073d1e4..7c7b0ed 100644
--- a/src/access/token.rs
+++ b/src/access/token.rs
@@ -118,7 +118,7 @@ pub(crate) enum Refused {
/// (`registry::User::tokens_not_before`), of a session not ended
/// (`registry::session_ended`).
pub(crate) fn verify(
- doc: &impl Read,
+ doc: &(impl Read + ?Sized),
token: &str,
swarm: &str,
now: u64,
@@ -162,7 +162,11 @@ pub(crate) fn verify(
/// store, only one it issued itself (`docs/store.md`, Members), as a node there is
/// whoever its operator lets in, and lets in nobody's but its own.
#[cfg(feature = "federation")]
-pub(crate) fn issued_here(doc: &impl Read, local: &str, claims: Claims) -> Result<Claims, Refused> {
+pub(crate) fn issued_here(
+ doc: &(impl Read + ?Sized),
+ local: &str,
+ claims: Claims,
+) -> Result<Claims, Refused> {
match super::policy::of(doc) {
super::policy::Policy::Store(_) if claims.issuer != local => Err(Refused::ElsewhereIssued),
_ => Ok(claims),
@@ -173,13 +177,13 @@ pub(crate) fn issued_here(doc: &impl Read, local: &str, claims: Claims) -> Resul
/// its issuer a member and not banned, its user registered, enabled, its tokens not
/// revoked since and its session not ended. What a stream opened with it is judged by
/// as the document changes (`api::login::streams_end`).
-pub(crate) fn still_taken(doc: &impl Read, claims: &Claims) -> Result<(), Refused> {
+pub(crate) fn still_taken(doc: &(impl Read + ?Sized), claims: &Claims) -> Result<(), Refused> {
issuer_counts(doc, claims)?;
user_counts(doc, claims)
}
/// Its issuer a member of the swarm, not banned.
-fn issuer_counts(doc: &impl Read, claims: &Claims) -> Result<(), Refused> {
+fn issuer_counts(doc: &(impl Read + ?Sized), claims: &Claims) -> Result<(), Refused> {
let member = view::read_path(doc, &meta::path(&[meta::MEMBERS, &claims.issuer]))
.ok()
.flatten()
@@ -195,7 +199,7 @@ fn issuer_counts(doc: &impl Read, claims: &Claims) -> Result<(), Refused> {
/// In a swarm with a registry: its user registered, enabled, its tokens not revoked
/// since it was issued, its session not ended.
-fn user_counts(doc: &impl Read, claims: &Claims) -> Result<(), Refused> {
+fn user_counts(doc: &(impl Read + ?Sized), claims: &Claims) -> Result<(), Refused> {
user_taken(doc, &claims.user)?;
if let Some(user) = registry::user(doc, &claims.user) {
if claims.iat < user.tokens_not_before {
@@ -211,7 +215,7 @@ fn user_counts(doc: &impl Read, claims: &Claims) -> Result<(), Refused> {
/// In a swarm with a registry: user `name` registered and enabled. What a stream opened
/// by password or a proxy's header is judged by as the document changes
/// (`api::login::streams_end`), as one opened with a token is by `still_taken`.
-pub(crate) fn user_taken(doc: &impl Read, name: &str) -> Result<(), Refused> {
+pub(crate) fn user_taken(doc: &(impl Read + ?Sized), name: &str) -> Result<(), Refused> {
if registry::exists(doc) {
let user = registry::user(doc, name).ok_or(Refused::UnknownUser)?;
if user.disabled {
diff --git a/src/api/access.rs b/src/api/access.rs
index 9e8a018..daa0f14 100644
--- a/src/api/access.rs
+++ b/src/api/access.rs
@@ -190,7 +190,7 @@ pub(crate) struct Before {
}
impl Before {
- pub(crate) fn of(doc: &impl crate::document::ReadDoc, user: &str) -> Self {
+ pub(crate) fn of(doc: &(impl crate::document::view::Read + ?Sized), user: &str) -> Self {
use crate::access::registry;
let existed = registry::exists(doc);
Self {
@@ -212,7 +212,7 @@ impl Before {
/// leaving nobody once they merge; then the users in `--protocol-writers` may do
/// everything again (`access::authorize`).
pub(crate) fn registry_kept(
- doc: &impl crate::document::ReadDoc,
+ doc: &(impl crate::document::view::Read + ?Sized),
path: &[String],
before: Before,
user: &str,
diff --git a/src/api/login.rs b/src/api/login.rs
index 02c54a3..e442ea2 100644
--- a/src/api/login.rs
+++ b/src/api/login.rs
@@ -674,7 +674,7 @@ async fn end(state: &AppState, claims: &Claims, by: &str) -> Result<(), ApiError
let until = claims.login_exp.max(claims.session_exp);
let recorded = if state.is_ready().await {
state
- .mutate_doc_for(Some(by.to_owned()), Sign::Protocol, move |doc| {
+ .mutate_doc_by(Some(by.to_owned()), Sign::Protocol, move |doc| {
if !registry::exists(&*doc) {
return Ok::<_, ApiError>(false);
}
@@ -682,7 +682,6 @@ async fn end(state: &AppState, claims: &Claims, by: &str) -> Result<(), ApiError
Ok(true)
})
.await?
- .0
} else {
false
};
@@ -773,7 +772,7 @@ pub(crate) async fn revoke_tokens(state: &AppState, name: &str, by: &str) -> Res
// Issued in this very millisecond: revoked too.
let after = state.clock.now_millis().as_u64() + 1;
state
- .mutate_doc_for(Some(by.to_owned()), Sign::Protocol, move |doc| {
+ .mutate_doc_by(Some(by.to_owned()), Sign::Protocol, move |doc| {
if !registry::exists(&*doc) {
return Err(ApiError(
StatusCode::CONFLICT,
diff --git a/src/api/peers.rs b/src/api/peers.rs
index fc203f5..586c32d 100644
--- a/src/api/peers.rs
+++ b/src/api/peers.rs
@@ -322,7 +322,7 @@ pub(crate) async fn delete_peer(
// Named as who asked: rules by path judge the change by them (`access::rules`).
let user = user.map(|axum::Extension(user)| user.0);
state
- .mutate_doc_for(
+ .mutate_doc_by(
user,
crate::document::signatures::Sign::Protocol,
move |doc| {
diff --git a/src/api/users.rs b/src/api/users.rs
index cf28ed1..0c41a56 100644
--- a/src/api/users.rs
+++ b/src/api/users.rs
@@ -132,7 +132,7 @@ fn may_manage(state: &AppState, user: &str, access: &Access) -> Result<(), ApiEr
}
/// A user's entry as the API shows it: as recorded, with its name.
-fn shown(doc: &impl crate::document::ReadDoc, name: &str) -> Option<JsonValue> {
+fn shown(doc: &(impl crate::document::view::Read + ?Sized), name: &str) -> Option<JsonValue> {
let mut entry = view::read_plain(doc, &registry::user_path(name)).ok()??;
if let Some(object) = entry.as_object_mut() {
object.insert("name".to_owned(), json!(name));
@@ -207,7 +207,7 @@ async fn own_key(
let adding = line.is_some();
let id_kept = id.clone();
state
- .mutate_doc_for(Some(user.to_owned()), Sign::Protocol, move |doc| {
+ .mutate_doc_by(Some(user.to_owned()), Sign::Protocol, move |doc| {
if crate::access::policy::of(&*doc).strict() {
return Err(ApiError(
StatusCode::CONFLICT,
@@ -287,7 +287,7 @@ async fn change(
state: &AppState,
user: &str,
what: String,
- f: impl FnOnce(&mut crate::document::Transaction<'_>, &str, u64) -> Result<(), ApiError>
+ f: impl FnOnce(&mut dyn crate::document::view::Write, &str, u64) -> Result<(), ApiError>
+ Send
+ 'static,
) -> Result<(), ApiError> {
@@ -298,7 +298,7 @@ async fn change(
let writer = user.to_owned();
let since = state.clock.now_millis().as_u64();
state
- .mutate_doc_for(Some(user.to_owned()), Sign::Protocol, move |doc| {
+ .mutate_doc_by(Some(user.to_owned()), Sign::Protocol, move |doc| {
if crate::access::policy::of(&*doc).strict() {
return Err(ApiError(
StatusCode::CONFLICT,
diff --git a/src/federation/held.rs b/src/federation/held.rs
index 72633eb..ec3738f 100644
--- a/src/federation/held.rs
+++ b/src/federation/held.rs
@@ -1251,25 +1251,30 @@ pub(crate) async fn write(
async fn put_again(state: &crate::state::AppState) {
let holding = Arc::clone(&state.holding);
let put = state
- .mutate_doc(move |doc| {
- let mut bytes_put = 0;
- let mut put = 0;
- for (id, bytes) in holding.lacking(doc) {
- if bytes_put > 0 && bytes_put + bytes.len() > PUT_BYTES {
- break;
+ .mutate_doc_for(
+ None,
+ crate::document::signatures::Sign::Protocol,
+ move |doc| {
+ let mut bytes_put = 0;
+ let mut put = 0;
+ for (id, bytes) in holding.lacking(doc) {
+ if bytes_put > 0 && bytes_put + bytes.len() > PUT_BYTES {
+ break;
+ }
+ bytes_put += bytes.len();
+ store::write_val_path(
+ doc,
+ &events::event(&id),
+ &crate::document::typed::Val::Scalar(ScalarValue::Bytes(bytes)),
+ store::Writing::sticky(Default::default()),
+ )?;
+ put += 1;
}
- bytes_put += bytes.len();
- store::write_val_path(
- doc,
- &events::event(&id),
- &crate::document::typed::Val::Scalar(ScalarValue::Bytes(bytes)),
- store::Writing::sticky(Default::default()),
- )?;
- put += 1;
- }
- Ok::<usize, store::StoreError>(put)
- })
- .await;
+ Ok::<usize, store::StoreError>(put)
+ },
+ )
+ .await
+ .map(|(put, _)| put);
match put {
Ok(0) => {}
Ok(put) => info!(put, "Put again events the document lacked"),
diff --git a/src/remake/mod.rs b/src/remake/mod.rs
index 6b1103e..90ae436 100644
--- a/src/remake/mod.rs
+++ b/src/remake/mod.rs
@@ -239,7 +239,7 @@ pub(crate) trait Host: Clone + Send + Sync + 'static {
/// alive recently enough, read from `doc`.
fn electorate(
&self,
- doc: &impl crate::document::ReadDoc,
+ doc: &(impl crate::document::view::Read + ?Sized),
now: crate::clock::UnixMillis,
) -> Vec<String>;
diff --git a/src/simtest/hyparview.rs b/src/simtest/hyparview.rs
index 65d581c..b5177d1 100644
--- a/src/simtest/hyparview.rs
+++ b/src/simtest/hyparview.rs
@@ -218,12 +218,12 @@ async fn a_swarm_switches_to_hyparview_at_runtime() {
nodes[0]
.mutate_doc(|doc| {
- crate::document::store::write_path(
+ crate::document::view::write_path(
doc,
&crate::swarm::topology::topology_path(),
&json!("hyparview"),
)?;
- crate::document::store::write_path(
+ crate::document::view::write_path(
doc,
&crate::swarm::topology::dissemination_path(),
&json!("plumtree"),
diff --git a/src/simtest/mod.rs b/src/simtest/mod.rs
index d0f80da..d11a402 100644
--- a/src/simtest/mod.rs
+++ b/src/simtest/mod.rs
@@ -32,8 +32,8 @@ use serde_json::Value as JsonValue;
use tokio::time::Instant;
use crate::document::replica::Epoch;
-use crate::document::store;
use crate::document::{ChangeHash, Document};
+use crate::document::{store, view};
use crate::files::Files;
use crate::identity::NodeKey;
use crate::locks::{MutexExt, RwLockExt};
@@ -482,7 +482,7 @@ pub(crate) fn path(path: &str) -> Vec<String> {
/// Writes `value` at `path` (`a/b/c`) as one change, as the API does.
pub(crate) async fn write(node: &AppState, at: &str, value: JsonValue) {
let at = path(at);
- node.mutate_doc(move |doc| store::write_path(doc, &at, &value))
+ node.mutate_doc(move |doc| view::write_path(doc, &at, &value))
.await
.expect("write");
}
diff --git a/src/simtest/remakes.rs b/src/simtest/remakes.rs
index 6fa4235..49139b6 100644
--- a/src/simtest/remakes.rs
+++ b/src/simtest/remakes.rs
@@ -17,7 +17,7 @@ use serde_json::{Value as JsonValue, json};
use super::{SOON, Sim, read, write};
use crate::document::ChangeHash;
use crate::document::replica::Epoch;
-use crate::document::store;
+use crate::document::view;
use crate::remake::testing;
use crate::state::AppState;
use crate::swarm::bootstrap::Start;
@@ -257,7 +257,7 @@ async fn writes_through_a_rejoin_are_kept() {
while !stop.load(Ordering::Relaxed) {
let at = vec!["w".to_owned(), n.to_string()];
let written = c
- .mutate_doc(move |doc| store::write_path(doc, &at, &json!(n)))
+ .mutate_doc(move |doc| view::write_path(doc, &at, &json!(n)))
.await;
assert!(written.is_ok(), "write {n} refused: {written:?}");
answered.lock().unwrap().push(n);
diff --git a/src/simtest/timing.rs b/src/simtest/timing.rs
index 5f23c21..3f03562 100644
--- a/src/simtest/timing.rs
+++ b/src/simtest/timing.rs
@@ -404,7 +404,7 @@ async fn late_epoch_does_not_flip_a_peers_epoch() {
/// record itself.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn forgotten_node_that_is_alive_cancels_its_record() {
- use crate::document::store;
+ use crate::document::{store, view};
use crate::swarm::peer::forgotten_path;
let sim = Sim::new(9);
@@ -416,7 +416,7 @@ async fn forgotten_node_that_is_alive_cancels_its_record() {
let record = forgotten_path(b.local_id());
let written = record.clone();
- a.mutate_doc(move |doc| store::write_path(doc, &written, &json!({"at": 0, "by": "a"})))
+ a.mutate_doc(move |doc| view::write_path(doc, &written, &json!({"at": 0, "by": "a"})))
.await
.expect("write forget record");
diff --git a/src/state/host.rs b/src/state/host.rs
index 4ef12a1..357814e 100644
--- a/src/state/host.rs
+++ b/src/state/host.rs
@@ -13,7 +13,7 @@ use tracing::{debug, error, info};
use super::{AppState, HelloState, NodeLifecycle, StaleView, Standing};
use crate::document::replica::{Epoch, Replica};
use crate::document::store::{ChangeSet, StoreError};
-use crate::document::{ChangeHash, Document, ReadDoc, Transaction};
+use crate::document::{ChangeHash, Document, Transaction};
use crate::locks::RwLockExt;
use crate::remake::{BegunRejoin, Host, PeerSummary, RemakeState};
@@ -286,7 +286,11 @@ impl Host for AppState {
crate::swarm::skew::measure(self).await
}
- fn electorate(&self, doc: &impl ReadDoc, now: crate::clock::UnixMillis) -> Vec<String> {
+ fn electorate(
+ &self,
+ doc: &(impl crate::document::view::Read + ?Sized),
+ now: crate::clock::UnixMillis,
+ ) -> Vec<String> {
let electorate =
crate::swarm::members::electorate(doc, now.as_u64(), self.electorate_window);
// Holding a store: the members the fold names, with the party their entries name;
@@ -387,7 +391,12 @@ impl Host for AppState {
E: From<StoreError> + Send + 'static,
{
let state = self.clone();
- async move { state.mutate_doc(f).await }
+ async move {
+ state
+ .mutate_doc_for(None, crate::document::signatures::Sign::Protocol, f)
+ .await
+ .map(|(out, _)| out)
+ }
}
fn commit_doc_for<T, E, F>(
diff --git a/src/state/mod.rs b/src/state/mod.rs
index ccd8a93..604f6ae 100644
--- a/src/state/mod.rs
+++ b/src/state/mod.rs
@@ -41,6 +41,7 @@ use crate::document::lock::DocumentLock;
use crate::document::replica::{Epoch, Stamp};
use crate::document::signatures::{Sign, SignEvery};
use crate::document::store::{ChangeSet, StoreError};
+use crate::document::view::Write;
use crate::document::{Document, Transaction};
use crate::locks::{MutexExt, RwLockExt};
use crate::remake::{Host, RemakeState};
@@ -573,44 +574,61 @@ impl AppState {
.expect("document read task panicked")
}
- /// Mutates the document on the blocking pool as one change, then
- /// publishes it. Write and notification run in the same blocking task, so a
- /// cancelled request can't leave a committed write unannounced. While a rejoin runs,
- /// the write goes into the document before it (`StaleView`), replayed when the
- /// rejoin ends; on a node that keeps none, it is refused (`StoreError::Rejoining`,
- /// `f` not called). Protocol data: the change is signed (`document::signatures`).
+ /// Writes to the document on the blocking pool, all of it or none, as one unit of
+ /// its kind (one change), then publishes it. Write and notification run in the same
+ /// blocking task, so a cancelled request can't leave a committed write unannounced.
+ /// While a rejoin runs, the write goes into the document before it (`StaleView`),
+ /// replayed when the rejoin ends; on a node that keeps none, it is refused
+ /// (`StoreError::Rejoining`, `f` not called). Protocol data: what it makes is signed
+ /// (`document::signatures`).
pub(crate) async fn mutate_doc<T, E>(
&self,
- f: impl FnOnce(&mut Transaction<'_>) -> Result<T, E> + Send + 'static,
+ f: impl FnOnce(&mut dyn Write) -> Result<T, E> + Send + 'static,
) -> Result<T, E>
where
T: Send + 'static,
E: From<StoreError> + Send + 'static,
{
- self.mutate_doc_for(None, Sign::Protocol, f)
- .await
- .map(|(out, _)| out)
+ self.mutate_doc_by(None, Sign::Protocol, f).await
}
/// [`mutate_doc`](Self::mutate_doc) of this node's registration in the member list
/// (`swarm::members::ensure_registered`): the one write not preceded by it.
pub(crate) async fn mutate_doc_registering<T, E>(
&self,
- f: impl FnOnce(&mut Transaction<'_>) -> Result<T, E> + Send + 'static,
+ f: impl FnOnce(&mut dyn Write) -> Result<T, E> + Send + 'static,
+ ) -> Result<T, E>
+ where
+ T: Send + 'static,
+ E: From<StoreError> + Send + 'static,
+ {
+ self.mutate_doc_as(None, Sign::Protocol, false, move |write| f(write))
+ .await
+ .map(|(out, _)| out)
+ }
+
+ /// [`mutate_doc`](Self::mutate_doc) for `user`, who wrote through the API: what it
+ /// makes names them (`replica::Writer`), and is signed as `sign` says, with this
+ /// node's key.
+ pub(crate) async fn mutate_doc_by<T, E>(
+ &self,
+ user: Option<String>,
+ sign: Sign,
+ f: impl FnOnce(&mut dyn Write) -> Result<T, E> + Send + 'static,
) -> Result<T, E>
where
T: Send + 'static,
E: From<StoreError> + Send + 'static,
{
- self.mutate_doc_as(None, Sign::Protocol, false, f)
+ self.mutate_doc_as(user, sign, true, move |write| f(write))
.await
.map(|(out, _)| out)
}
- /// [`mutate_doc`](Self::mutate_doc) for `user`, who wrote through the API: the
- /// change names them (`replica::Writer`), and is signed as `sign` says, with this
- /// node's key. With the heads of the document written to after the
- /// write (sorted): what a read must have to include it.
+ /// [`mutate_doc_by`](Self::mutate_doc_by) of an Automerge document as such, for what
+ /// asks more of it than values at paths (`document::store`): the write is one of
+ /// Automerge's. With the heads of the document written to after the write (sorted):
+ /// what a read must have to include it.
pub(crate) async fn mutate_doc_for<T, E>(
&self,
user: Option<String>,
@@ -693,7 +711,7 @@ impl AppState {
let before = replica.doc.get_heads();
replica
.transact(state.clock.now_millis(), &writer, |doc| {
- crate::document::store::write_path(doc, &path, &entry)
+ crate::document::view::write_path(doc, &path, &entry)
})
.map_err(E::from)?;
state.sign_made(&mut replica, &before, &Sign::Protocol);
diff --git a/src/swarm/members.rs b/src/swarm/members.rs
index 4039b2a..754b702 100644
--- a/src/swarm/members.rs
+++ b/src/swarm/members.rs
@@ -41,7 +41,7 @@ pub(crate) fn member_path(pk: &str) -> Vec<String> {
}
/// Public keys of all registered members, sorted.
-pub(crate) fn members(doc: &impl Read) -> Vec<String> {
+pub(crate) fn members(doc: &(impl Read + ?Sized)) -> Vec<String> {
let mut members = view::keys_at(doc, &members_dir())
.ok()
.flatten()
@@ -81,7 +81,11 @@ pub(crate) fn tier(doc: &Document, pk: &str) -> Tier {
}
}
-pub(crate) fn set_tier(doc: &mut impl Write, pk: &str, tier: Tier) -> Result<(), StoreError> {
+pub(crate) fn set_tier(
+ doc: &mut (impl Write + ?Sized),
+ pk: &str,
+ tier: Tier,
+) -> Result<(), StoreError> {
view::write_path(doc, &tier_path(pk), &json!(tier.as_str()))
}
@@ -100,7 +104,7 @@ fn party_path(pk: &str) -> Vec<String> {
/// The party `pk`'s entry names, in a swarm holding a store.
#[cfg(feature = "federation")]
-pub(crate) fn party(doc: &impl Read, pk: &str) -> Option<String> {
+pub(crate) fn party(doc: &(impl Read + ?Sized), pk: &str) -> Option<String> {
match view::read_path(doc, &party_path(pk)) {
Ok(Some(JsonValue::String(party))) => Some(party),
_ => None,
@@ -123,7 +127,11 @@ pub(crate) fn aliases(doc: &Document) -> HashMap<String, String> {
.collect()
}
-fn set_alias(doc: &mut impl Write, pk: &str, alias: Option<&str>) -> Result<(), StoreError> {
+fn set_alias(
+ doc: &mut (impl Write + ?Sized),
+ pk: &str,
+ alias: Option<&str>,
+) -> Result<(), StoreError> {
match alias {
Some(alias) => view::write_path(doc, &alias_path(pk), &json!(alias)),
None => match view::delete_path(doc, &alias_path(pk), false) {
@@ -147,7 +155,11 @@ pub(crate) fn dashboard(doc: &Document, pk: &str) -> Option<String> {
}
}
-fn set_dashboard(doc: &mut impl Write, pk: &str, url: Option<&str>) -> Result<(), StoreError> {
+fn set_dashboard(
+ doc: &mut (impl Write + ?Sized),
+ pk: &str,
+ url: Option<&str>,
+) -> Result<(), StoreError> {
match url {
Some(url) => view::write_path(doc, &dashboard_path(pk), &json!(url)),
None => match view::delete_path(doc, &dashboard_path(pk), false) {
@@ -244,7 +256,7 @@ fn alive_path(pk: &str) -> Vec<String> {
path
}
-fn millis_at(doc: &impl Read, path: &[String]) -> Option<u64> {
+fn millis_at(doc: &(impl Read + ?Sized), path: &[String]) -> Option<u64> {
match view::read_path(doc, path) {
Ok(Some(JsonValue::Number(number))) => number.as_u64(),
_ => None,
@@ -252,7 +264,7 @@ fn millis_at(doc: &impl Read, path: &[String]) -> Option<u64> {
}
/// When `pk` last said it is alive (Unix ms): its last renewal, or its registration.
-pub(crate) fn alive_at(doc: &impl Read, pk: &str) -> Option<u64> {
+pub(crate) fn alive_at(doc: &(impl Read + ?Sized), pk: &str) -> Option<u64> {
let mut since = member_path(pk);
since.push("since".to_owned());
millis_at(doc, &alive_path(pk)).max(millis_at(doc, &since))
@@ -262,7 +274,7 @@ pub(crate) fn alive_at(doc: &impl Read, pk: &str) -> Option<u64> {
/// electorate of a remake (`remake::coordinator`). A stamp further in the future than a
/// renewal interval (`alive_renewal`) doesn't count: its node's clock is that far ahead
/// (it warns about it, `swarm::skew`), and the stamp would never age out.
-pub(crate) fn electorate(doc: &impl Read, now_ms: u64, window: Duration) -> Vec<String> {
+pub(crate) fn electorate(doc: &(impl Read + ?Sized), now_ms: u64, window: Duration) -> Vec<String> {
let oldest = now_ms.saturating_sub(window.as_millis() as u64);
let newest = now_ms.saturating_add(alive_renewal(window).as_millis() as u64);
members(doc)
@@ -281,7 +293,7 @@ fn window_path(pk: &str) -> Vec<String> {
/// publish in their entries (ms, `window`): every node renews its alive stamp by it
/// (`alive_renewal`), so a coordinator with a shorter window than others' still counts
/// them all. Below `MIN_ELECTORATE_WINDOW` (which no node accepts) counts as that.
-pub(crate) fn shortest_window(doc: &impl Read, own: Duration) -> Duration {
+pub(crate) fn shortest_window(doc: &(impl Read + ?Sized), own: Duration) -> Duration {
members(doc)
.iter()
.filter_map(|pk| millis_at(doc, &window_path(pk)))
@@ -304,7 +316,7 @@ pub(crate) const MIN_ELECTORATE_WINDOW: Duration =
Duration::from_secs(7 * RENEWAL_MOST_OFTEN.as_secs());
/// Whether `node` is registered in `doc`'s member list.
-pub(crate) fn registered(doc: &impl Read, node: &str) -> bool {
+pub(crate) fn registered(doc: &(impl Read + ?Sized), node: &str) -> bool {
view::read_path(doc, &member_path(node))
.ok()
.flatten()
@@ -505,7 +517,7 @@ impl RecordedLinks {
/// `pk`'s recorded links; none if its entry doesn't say (at most `MAX_RECORDED_LINKS`
/// in each set).
-pub(crate) fn links(doc: &impl Read, pk: &str) -> RecordedLinks {
+pub(crate) fn links(doc: &(impl Read + ?Sized), pk: &str) -> RecordedLinks {
let Ok(Some(JsonValue::Object(links))) = view::read_path(doc, &links_path(pk)) else {
return RecordedLinks::default();
};
@@ -528,7 +540,7 @@ pub(crate) fn links(doc: &impl Read, pk: &str) -> RecordedLinks {
/// Records `pk`'s `links` (at most `MAX_RECORDED_LINKS` in each set); none removes them.
pub(crate) fn set_links(
- doc: &mut impl Write,
+ doc: &mut (impl Write + ?Sized),
pk: &str,
links: &RecordedLinks,
) -> Result<(), StoreError> {
@@ -549,7 +561,7 @@ pub(crate) fn set_links(
}
/// Removes `pk`'s entry (an operator forgot it). Absent is fine.
-pub(crate) fn unregister(doc: &mut impl Write, pk: &str) -> Result<(), StoreError> {
+pub(crate) fn unregister(doc: &mut (impl Write + ?Sized), pk: &str) -> Result<(), StoreError> {
match view::delete_path(doc, &member_path(pk), false) {
Err(StoreError::NotFound) => Ok(()),
result => result,