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
2 changes: 1 addition & 1 deletion pkgs/id/crates/id-core/src/discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ pub const MAX_PEER_NAME_BYTES: usize = 256;
// ============================================================================

/// A peer's presence claim. Gossip carries it inside the id crate's signed,
/// versioned envelope; this plain structure is also nested in `/iroh-meta/2`.
/// versioned envelope; this plain structure is also nested in `/iroh-meta/3`.
///
/// Serialized with [postcard](https://docs.rs/postcard) for compact binary
/// encoding. Typical size: ~50-100 bytes depending on name length.
Expand Down
75 changes: 53 additions & 22 deletions pkgs/id/src/commands/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@
//!
//! Each line contains:
//! ```text
//! <hash>\t<name>
//! <hash>\t<name>\t<origin>\t<uploaded_at>
//! ```
//!
//! Where:
//! - `hash` is the 64-character BLAKE3 content hash
//! - `name` is the tag name assigned to the blob
//! - `origin` is the node that first wrote the file, or `unknown` for
//! files written before origin stamping existed (#4973)
//! - `uploaded_at` is the upload time (unix seconds), or `unknown`
//!
//! # Examples
//!
Expand All @@ -30,7 +33,7 @@ use iroh_base::EndpointId;

use crate::commands::client::create_local_client_endpoint;
use crate::commands::serve::get_serve_info;
use crate::commands::text::tsv_row;
use crate::commands::text::list_tsv_row;
use crate::protocol::{MetaRequest, MetaResponse};
use crate::store::{load_or_create_keypair, open_store};
use crate::{CLIENT_KEY_FILE, META_ALPN, is_node_id};
Expand Down Expand Up @@ -88,8 +91,16 @@ pub async fn cmd_list(node: Option<String>, no_relay: bool) -> Result<()> {
if items.is_empty() {
println!("(no files stored)");
} else {
for (hash, name) in items {
println!("{}", tsv_row(hash, &name));
for entry in &items {
println!(
"{}",
list_tsv_row(
entry.hash,
&entry.name,
entry.origin.as_deref(),
entry.uploaded_at
)
);
}
}
Ok(())
Expand All @@ -100,22 +111,34 @@ pub async fn cmd_list(node: Option<String>, no_relay: bool) -> Result<()> {
return result;
}

let store = open_store(false).await?;
let store_handle = store.as_store();

let mut list = store_handle.tags().list().await?;
let mut count = 0;
while let Some(item) = list.next().await {
let item = item?;
let name = String::from_utf8_lossy(item.name.as_ref());
println!("{}", tsv_row(item.hash, &name));
count += 1;
}
if count == 0 {
println!("(no files stored)");
}
store.shutdown().await?;
Ok(())
// Offline: run the same in-process meta handler the REPL uses, so the
// listing is enriched with the recorded origin + upload time from the
// metadata tags instead of reporting `unknown` for files whose
// metadata exists locally (Codex review, PR #5191).
let node = crate::local::LocalNode::open(false).await?;
let result = match node.request(MetaRequest::List).await {
MetaResponse::List { items } => {
if items.is_empty() {
println!("(no files stored)");
} else {
for entry in &items {
println!(
"{}",
list_tsv_row(
entry.hash,
&entry.name,
entry.origin.as_deref(),
entry.uploaded_at
)
);
}
}
Ok(())
}
_ => Err(anyhow::anyhow!("unexpected response")),
};
node.shutdown().await?;
result
}

/// Lists files on a remote node.
Expand Down Expand Up @@ -154,8 +177,16 @@ pub async fn cmd_list_remote(server_node_id: EndpointId, no_relay: bool) -> Resu
if items.is_empty() {
println!("(no files stored)");
} else {
for (hash, name) in items {
println!("{}", tsv_row(hash, &name));
for entry in &items {
println!(
"{}",
list_tsv_row(
entry.hash,
&entry.name,
entry.origin.as_deref(),
entry.uploaded_at
)
);
}
}
Ok(())
Expand Down
61 changes: 43 additions & 18 deletions pkgs/id/src/commands/repl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ use crate::commands::client::create_local_client_endpoint;
use crate::commands::put::{add_raw, push_and_name};
use crate::commands::serve::get_serve_info;
use crate::commands::tag::{self as tag, TagDisplayOptions};
use crate::commands::text::{plain_field, tsv_row};
use crate::commands::text::{list_tsv_row, plain_field};
use crate::discovery::PeerAnnouncement;
use crate::local::LocalNode;
use crate::meta_client::{MetaRequester, expect_ok, read_capped_response, request_over};
Expand Down Expand Up @@ -446,8 +446,9 @@ impl ReplContext {

/// List all stored blobs.
///
/// Prints a tab-separated list of hash and name for each stored blob.
/// Output format: `<hash>\t<name>`
/// Prints a tab-separated list for each stored blob with its origin
/// node and upload time (#4973; `unknown` when not recorded).
/// Output format: `<hash>\t<name>\t<origin>\t<uploaded_at>`
///
/// In connected modes, sends `MetaRequest::List` to the server.
/// In local mode, directly iterates the store's tags.
Expand All @@ -469,25 +470,41 @@ impl ReplContext {
if items.is_empty() {
println!("(no files stored)");
} else {
for (hash, name) in items {
println!("{}", tsv_row(hash, &name));
for entry in &items {
println!(
"{}",
list_tsv_row(
entry.hash,
&entry.name,
entry.origin.as_deref(),
entry.uploaded_at
)
);
}
}
}
_ => bail!("unexpected response"),
}
} else if let ReplContextInner::Local { node } = &self.inner {
let store_handle = node.blobs();
let mut list = store_handle.tags().list().await?;
let mut count = 0;
while let Some(item) = list.next().await {
let item = item?;
let name = String::from_utf8_lossy(item.name.as_ref());
println!("{}", tsv_row(item.hash, &name));
count += 1;
}
if count == 0 {
println!("(no files stored)");
match node.request(MetaRequest::List).await {
MetaResponse::List { items } => {
if items.is_empty() {
println!("(no files stored)");
} else {
for entry in &items {
println!(
"{}",
list_tsv_row(
entry.hash,
&entry.name,
entry.origin.as_deref(),
entry.uploaded_at
)
);
}
}
}
_ => bail!("unexpected response"),
}
}
Ok(())
Expand Down Expand Up @@ -884,8 +901,16 @@ impl ReplContext {
if items.is_empty() {
println!("(no files stored on @{})", &node_str[..8]);
} else {
for (hash, name) in items {
println!("{}", tsv_row(hash, &name));
for entry in &items {
println!(
"{}",
list_tsv_row(
entry.hash,
&entry.name,
entry.origin.as_deref(),
entry.uploaded_at
)
);
}
}
}
Expand Down
37 changes: 37 additions & 0 deletions pkgs/id/src/commands/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,27 @@ pub fn tsv_row(hash: impl Display, name: &str) -> String {
format!("{hash}\t{}", plain_field(name))
}

/// Formats one file-listing row (#4973):
/// `<hash>\t<name>\t<origin>\t<uploaded_at>`.
///
/// `origin` is the node that first wrote the file and `uploaded_at` its
/// upload time (unix seconds), both from the file's metadata tags. A file
/// written before those tags existed renders both as `unknown` — the
/// listing never guesses an origin.
pub fn list_tsv_row(
hash: impl Display,
name: &str,
origin: Option<&str>,
uploaded_at: Option<u64>,
) -> String {
format!(
"{}\t{}\t{}",
tsv_row(hash, name),
origin.map_or_else(|| "unknown".to_owned(), plain_field),
uploaded_at.map_or_else(|| "unknown".to_owned(), |ts| ts.to_string())
Comment thread
dezren39 marked this conversation as resolved.
Resolved
)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
Expand Down Expand Up @@ -253,6 +274,22 @@ mod tests {
}

#[test]
#[test]
fn list_tsv_row_shows_origin_and_upload_time() {
assert_eq!(
list_tsv_row("hash", "a.txt", Some("node-a"), Some(1_700_000_000)),
"hash\ta.txt\tnode-a\t1700000000"
);
}

#[test]
fn list_tsv_row_unknown_for_pre_change_files() {
assert_eq!(
list_tsv_row("hash", "old.txt", None, None),
"hash\told.txt\tunknown\tunknown"
);
}

fn tsv_row_keeps_control_characters_inside_the_name_field() {
let row = tsv_row("hash", "x\nforged\tcolumn");
assert_eq!(row, format!("hash\t{}", r#""x\nforged\tcolumn""#));
Expand Down
41 changes: 39 additions & 2 deletions pkgs/id/src/fileops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,15 @@ pub struct DeleteOutcome {
}

/// File operations over a blob [`Store`] and a [`TagStore`].
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone)]
pub struct FileOps<'a> {
store: &'a Store,
tags: &'a TagStore,
blob_wait: Duration,
/// Node that originated a write, stamped as the file's `origin` tag
/// (#4973). `None` when the caller does not know its node id: no
/// origin is stamped and listings show the file's origin as unknown.
origin: Option<String>,
}

/// Serialises archive-name resolve+claim within this process (#2462).
Expand Down Expand Up @@ -182,6 +186,7 @@ impl<'a> FileOps<'a> {
store,
tags,
blob_wait: Duration::ZERO,
origin: None,
}
}

Expand All @@ -198,6 +203,16 @@ impl<'a> FileOps<'a> {
self
}

/// Stamp writes with `origin` (a node id) as the file's origin node
/// (#4973). The stamp is set-if-absent: the node that first wrote a
/// file stays its origin across later writes and renames, and files
/// written before origin stamping existed simply have no origin tag.
#[must_use]
pub fn with_origin(mut self, origin: String) -> Self {
self.origin = Some(origin);
self
}

/// Whether the blob is complete, waiting up to `blob_wait` for it.
async fn blob_present(&self, hash: Hash) -> Result<bool> {
let deadline = Instant::now() + self.blob_wait;
Expand Down Expand Up @@ -314,7 +329,11 @@ impl<'a> FileOps<'a> {
/// Name `hash` as `name`, after verifying the blob is complete in the store.
///
/// Sets the `created` tag only if absent and always refreshes `modified`,
/// then auto-tags `name`/`file`.
/// stamps the `origin` node on a genuine first write (no `created` tag
/// recorded yet) if one is configured, then auto-tags `name`/`file`.
/// A legacy file that predates origin stamping keeps an unknown origin
/// when it is overwritten: absence of an `origin` tag alone does not
/// prove this write is the file's first.
pub async fn put(&self, name: &str, hash: Hash) -> Result<(), FileOpError> {
Self::validate_name(name)?;
if !self.blob_present(hash).await? {
Expand All @@ -337,6 +356,15 @@ impl<'a> FileOps<'a> {
let ns = &self.tags.global;
let now = now_unix().to_string();
let subject = name.as_bytes();
// Origin is stamped only for a genuine first write: a name with a
// `created` tag but no `origin` tag is a legacy file whose true
// origin is unknown and must stay unknown (Codex review, PR #5191).
let first_write = self
.tags
.get_by_key(ns, subject, b"created")
.await
.map(|existing| existing.is_empty())
.unwrap_or(false);
let created = if reset_created {
self.tags
.set_singleton(ns, subject, b"created", Some(now.as_bytes()), b"")
Expand All @@ -357,6 +385,15 @@ impl<'a> FileOps<'a> {
{
tracing::warn!("failed to set modified tag for {name}: {e:#}");
}
if first_write
&& let Some(origin) = &self.origin
&& let Err(e) = self
.tags
.set_if_absent(ns, subject, b"origin", Some(origin.as_bytes()), b"")
.await
{
tracing::warn!("failed to set origin tag for {name}: {e:#}");
}
if let Err(e) = self.tags.auto_tag(ns, subject, None).await {
tracing::warn!("failed to auto-tag {name}: {e:#}");
}
Expand Down
11 changes: 8 additions & 3 deletions pkgs/id/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@
//!
//! Two protocols are used:
//! - **Blobs Protocol** (`/iroh-blobs/1`): For blob data transfer
//! - **Meta Protocol** (`/iroh-meta/2`): For metadata operations (list, find, delete, etc.)
//! - **Meta Protocol** (`/iroh-meta/3`): For metadata operations (list, find, delete, etc.)
//!
//! ## Features
//!
Expand Down Expand Up @@ -344,10 +344,15 @@ pub const SERVE_LOCK: &str = ".iroh-serve.lock";
/// and `Error`. It is not wire-compatible with `/iroh-meta/1`; the ALPN bump
/// makes old and new nodes fail the handshake cleanly instead of mis-decoding.
///
/// **Version 3** changes the `List` response item from `(hash, name)` pairs
/// to `ListEntry` records carrying the file's origin node and upload time
/// (#4973). That payload change is not wire-compatible with `/iroh-meta/2`
/// under postcard, so it takes this ALPN bump per the rule below.
///
/// Compatibility rule: within a version, only **append** enum variants. Any
/// other change to [`protocol::MetaRequest`] / [`protocol::MetaResponse`]
/// requires a new ALPN. `protocol::tests` pins every discriminant.
pub const META_ALPN: &[u8] = b"/iroh-meta/2";
pub const META_ALPN: &[u8] = b"/iroh-meta/3";

// ============================================================================
// Utility Functions
Expand Down Expand Up @@ -731,7 +736,7 @@ mod tests {
assert_eq!(CLIENT_KEY_FILE, ".iroh-key-client");
assert_eq!(STORE_PATH, ".iroh-store");
assert_eq!(SERVE_LOCK, ".iroh-serve.lock");
assert_eq!(META_ALPN, b"/iroh-meta/2");
assert_eq!(META_ALPN, b"/iroh-meta/3");
}

#[tokio::test]
Expand Down
Loading
Loading