Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
28 changes: 25 additions & 3 deletions pkgs/id/crates/id-cli/src/commands/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1556,7 +1556,22 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> {
#[cfg(feature = "web")]
let blob_gate: Option<Arc<crate::blob_gate::RefreshingWorlds>> = match &event_events {
Some(events) => {
let folded = build_blob_gate(events, &store_handle, &groups_log).await;
// A failed first build has no previous fold to keep: the gate
// starts empty — fail-closed, as before — and the refresh task
// below retries on its cadence (#13821).
let folded = match build_blob_gate(events, &store_handle, &groups_log).await {
Ok(folded) => folded,
Err(error) => {
tracing::error!(
"blob gate: initial build failed: {error:#}; \
starting with an empty gate until a refresh succeeds"
);
crate::blob_gate::FoldedWorlds::new(
crate::groups::worlds::Worlds::empty(),
std::collections::HashMap::new(),
)
}
};
Some(Arc::new(crate::blob_gate::RefreshingWorlds::new(folded)))
}
None => None,
Expand Down Expand Up @@ -2431,8 +2446,15 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> {
interval.tick().await;
loop {
interval.tick().await;
let folded = build_blob_gate(&events, &store, &groups_log).await;
gate.refresh(folded);
// A failed rebuild keeps the previous fold (#13821):
// a transient read error must not empty the live gate.
if let Err(error) =
gate.try_refresh(build_blob_gate(&events, &store, &groups_log).await)
{
tracing::error!(
"blob gate: refresh failed: {error:#}; keeping the previous fold"
);
}
}
}))
}
Expand Down
52 changes: 23 additions & 29 deletions pkgs/id/crates/id-cli/src/commands/serve/startup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

use super::*;

use anyhow::Context as _;

#[allow(unused_variables)] // web/port only used with web feature
/// The loaded operator server config and the provisioning it ran
/// (#5119 slice 1). Kept at startup scope so the later slices — the
Expand Down Expand Up @@ -187,36 +189,30 @@ pub(super) const MAX_HASHSEQ_BYTES: u64 = 1 << 20;
/// A referenced blob that parses as a `HashSeq` contributes its children to the
/// same world, but only when every child is present in the store — arbitrary
/// content whose length is a multiple of 32 bytes would otherwise spray
/// references onto hashes nobody stored. Any source that fails to read folds to
/// empty for that source: the gate fails closed, and the next refresh retries.
/// references onto hashes nobody stored.
///
/// # Errors
///
/// Fails when any source fails to read — the group log cannot be opened or
/// does not fold, or the document references cannot be read. A failed build
/// produces no fold at all, so a partial fold built from fallback values is
/// never mistaken for a complete one: the caller decides what a failure
/// means (startup falls back to an empty gate; the refresh loop keeps the
/// previous fold, #13821).
#[cfg(feature = "web")]
pub(super) async fn build_blob_gate(
events: &Arc<tokio::sync::Mutex<crate::local_events::LocalEvents>>,
store: &iroh_blobs::api::Store,
groups_log: &std::path::Path,
) -> crate::blob_gate::FoldedWorlds {
let group_projection = match GroupLog::open(groups_log) {
Ok(log) => match crate::blob_gate::fold_group_events(log.events()) {
Ok(projection) => Some(projection),
Err(error) => {
warn!("blob gate: group log does not fold: {error}");
None
}
},
Err(error) => {
warn!("blob gate: cannot open group log: {error}");
None
}
};
) -> anyhow::Result<crate::blob_gate::FoldedWorlds> {
let log = GroupLog::open(groups_log).context("blob gate: cannot open group log")?;
let group_projection = crate::blob_gate::fold_group_events(log.events())
.context("blob gate: group log does not fold")?;
let references = {
let events = events.lock().await;
match events.document_references() {
Ok(references) => references,
Err(error) => {
warn!("blob gate: cannot read document references: {error}");
Vec::new()
}
}
events
.document_references()
.context("blob gate: cannot read document references")?
};
// Expand HashSeq collections whose children are all in the store. The
// expansion is bounded (#7181 review): only a group-referenced blob can
Expand Down Expand Up @@ -274,10 +270,8 @@ pub(super) async fn build_blob_gate(
let index = crate::blob_gate::build_reference_index(named, |hash| {
children.get(hash).cloned().unwrap_or_default()
});
match group_projection {
Some(projection) => {
crate::blob_gate::FoldedWorlds::from_group_projection(projection, index)
}
None => crate::blob_gate::FoldedWorlds::new(crate::groups::worlds::Worlds::empty(), index),
}
Ok(crate::blob_gate::FoldedWorlds::from_group_projection(
group_projection,
index,
))
}
67 changes: 66 additions & 1 deletion pkgs/id/crates/id-worlds/src/blob_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,8 @@ pub fn build_reference_index(
/// be the snapshot from startup, or a removed member would keep fetching and a new
/// document would stay unreferenced until a restart. The producer re-folds and calls
/// [`RefreshingWorlds::refresh`]; each decision then reads the latest fold. A poisoned
/// lock fails closed, like every other gate refusal.
/// lock fails closed, like every other gate refusal. Rebuilds install through
/// [`RefreshingWorlds::try_refresh`], so a failed rebuild keeps the last good fold.
#[derive(Debug)]
pub struct RefreshingWorlds {
inner: RwLock<FoldedWorlds>,
Expand All @@ -229,6 +230,25 @@ impl RefreshingWorlds {
*current = next;
}
}

/// Installs a rebuilt fold, or keeps the current one when the rebuild
/// failed (#13821).
///
/// A rebuild reads live sources — the group log, the event store — and
/// any of those reads can fail transiently. The fold the gate already
/// holds is the last one built from a complete read, so a failed rebuild
/// must not replace it: the error goes back to the caller to log, and
/// every later decision keeps reading the previous fold until a rebuild
/// succeeds.
pub fn try_refresh<E>(&self, rebuilt: Result<FoldedWorlds, E>) -> Result<(), E> {
match rebuilt {
Ok(next) => {
self.refresh(next);
Ok(())
}
Err(error) => Err(error),
}
}
}

impl WorldAccess for RefreshingWorlds {
Expand Down Expand Up @@ -545,4 +565,49 @@ mod tests {
);
let _ = BTreeMap::<String, String>::new();
}

#[test]
fn failed_rebuild_keeps_the_previous_fold_until_a_successful_one() {
let member = id(2);
let (events, world) = group_events(member, false);
let projection = fold_group_events(&events).expect("the log folds");
let index = build_reference_index([(blob(7), world.clone())], |_| Vec::new());
let gate = RefreshingWorlds::new(FoldedWorlds::from_group_projection(projection, index));
let policy = BlobPolicy::default();
assert!(
decide(&gate, &policy, &member, &blob(7), Request::Fetch),
"a current member fetches a referenced blob"
);

// Every step serve's rebuild can fail at — opening the group log,
// folding it, reading the document references — reaches the gate as
// an `Err`; the previous fold must stay in force through each one
// (#13821).
for step in [
"cannot open group log",
"group log does not fold",
"cannot read document references",
] {
let failed: Result<FoldedWorlds, &str> = Err(step);
assert!(gate.try_refresh(failed).is_err(), "the failure surfaces");
assert!(
decide(&gate, &policy, &member, &blob(7), Request::Fetch),
"a rebuild failing at {step} keeps the previous membership in force"
);
}

// A later successful rebuild that removes the member revokes the
// fetch, exactly as a direct refresh does.
let (events, world) = group_events(member, true);
let projection = fold_group_events(&events).expect("the log folds");
let index = build_reference_index([(blob(7), world)], |_| Vec::new());
let rebuilt: Result<FoldedWorlds, &str> =
Ok(FoldedWorlds::from_group_projection(projection, index));
gate.try_refresh(rebuilt)
.expect("a successful rebuild installs");
assert!(
!decide(&gate, &policy, &member, &blob(7), Request::Fetch),
"a removed member loses fetch once a rebuild succeeds"
);
}
}