Skip to content
Merged
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
84 changes: 80 additions & 4 deletions pkgs/id/src/fileops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,26 @@ pub struct FileOps<'a> {
blob_wait: Duration,
}

/// The archive tag for `name` at `ts`, bumped past any archive tag that
/// already exists: `{name}.archive.{ts}`, then `{name}.archive.{ts + 1}`,
/// and so on until the name is free.
///
/// Archive names carry second-resolution timestamps, so two replaces of one
/// name within the same second would otherwise pick the same tag and the
/// second would silently overwrite the first replace's archive (#1612). The
/// suffix stays all digits: `delete` enumerates a file's archives by exactly
/// that shape, and the web layer parses the suffix as the archive timestamp.
pub(crate) async fn free_archive_name(store: &Store, name: &str, ts: u64) -> Result<String> {
let mut suffix = ts;
loop {
let candidate = format!("{name}.archive.{suffix}");
if store.tags().get(&candidate).await?.is_none() {
return Ok(candidate);
}
suffix += 1;
}
}

impl<'a> FileOps<'a> {
/// Create file operations over the given stores.
pub const fn new(store: &'a Store, tags: &'a TagStore) -> Self {
Expand Down Expand Up @@ -154,7 +174,7 @@ impl<'a> FileOps<'a> {
let Some(existing) = self.store.tags().get(name).await? else {
return Ok(None);
};
let archive = format!("{name}.archive.{ts}");
let archive = free_archive_name(self.store, name, ts).await?;
self.store
.tags()
.set(&archive, existing.hash)
Expand Down Expand Up @@ -245,9 +265,14 @@ impl<'a> FileOps<'a> {
.map_err(anyhow::Error::from)?;

let archived_original = if archive {
let name = format!("{from}.archive.{ts}");
match self.store.tags().set(&name, hash).await {
Ok(()) => Some(name),
match free_archive_name(self.store, from, ts).await {
Ok(name) => match self.store.tags().set(&name, hash).await {
Ok(()) => Some(name),
Err(e) => {
tracing::error!("failed to archive original {from}: {e}");
None
}
},
Err(e) => {
tracing::error!("failed to archive original {from}: {e}");
None
Expand Down Expand Up @@ -420,3 +445,54 @@ impl<'a> FileOps<'a> {
})
}
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod archive_name_tests {
use iroh_blobs::{Hash, store::mem::MemStore};

use super::*;

fn hash(byte: u8) -> Hash {
Hash::from([byte; 32])
}

/// Two replaces of one name within the same second must not share an
/// archive tag (#1612): the second archive is bumped to the next free
/// numeric suffix, and both replaced versions stay archived.
#[tokio::test]
async fn same_second_archives_never_overwrite() {
let store: Store = MemStore::new().into();
let ts = 1_700_000_000_u64;

let first = free_archive_name(&store, "doc", ts).await.unwrap();
assert_eq!(first, format!("doc.archive.{ts}"));
store.tags().set(&first, hash(1)).await.unwrap();

let second = free_archive_name(&store, "doc", ts).await.unwrap();
assert_eq!(second, format!("doc.archive.{}", ts + 1));
store.tags().set(&second, hash(2)).await.unwrap();

// Both archives survive, each still pointing at its own version.
assert_eq!(
store.tags().get(&first).await.unwrap().unwrap().hash,
hash(1)
);
assert_eq!(
store.tags().get(&second).await.unwrap().unwrap().hash,
hash(2)
);

// A third same-second replace bumps past both.
let third = free_archive_name(&store, "doc", ts).await.unwrap();
assert_eq!(third, format!("doc.archive.{}", ts + 2));
}

/// With no collision the archive name is exactly the historic shape.
#[tokio::test]
async fn uncontested_archive_name_is_unchanged() {
let store: Store = MemStore::new().into();
let name = free_archive_name(&store, "doc", 42).await.unwrap();
assert_eq!(name, "doc.archive.42");
}
}
9 changes: 7 additions & 2 deletions pkgs/id/src/web/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use super::templates::{
render_file_list_content, render_main_page_wrapper, render_media_viewer, render_page,
render_peers, render_settings,
};
use crate::fileops::{FileOpError, FileOps};
use crate::fileops::{FileOpError, FileOps, free_archive_name};

/// Default number of files per page.
const DEFAULT_PER_PAGE: usize = 50;
Expand Down Expand Up @@ -2172,7 +2172,12 @@ async fn archive_original_tag(
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let archive_name = format!("{name}.archive.{timestamp}");
// Bump past an existing archive tag so two archives within the same
// second never overwrite each other (#1612).
let Ok(archive_name) = free_archive_name(store, name, timestamp).await else {
tracing::error!("[routes] Failed to find a free archive tag for {}", name);
return None;
};
let archive_tag = iroh_blobs::api::Tag::from(archive_name.clone());

match store.tags().set(archive_tag, expected).await {
Expand Down
Loading