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
16 changes: 14 additions & 2 deletions pkgs/id/crates/id-cli/src/cli/doc.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `id doc` subcommand definitions: publish, events, frontier, history.
//! `id doc` subcommand definitions: publish, events, frontier, history, content.

use std::path::PathBuf;

Expand All @@ -10,7 +10,8 @@ pub enum DocCommand {
/// Publish a file as a document, and set a tag for each `--tag`.
///
/// Prints `publish document=<ID>`, the document's event ID. The file's bytes are hashed, and
/// the event names their hash and size. The bytes are not stored in the event.
/// the event names their hash and size. The bytes are not stored in the event: publish stores
/// them in the blob store under their hash, so `id doc content` can fetch them back.
Publish {
/// The file to publish.
file: PathBuf,
Expand All @@ -33,4 +34,15 @@ pub enum DocCommand {
/// The document's event ID, as `publish` printed it.
document: String,
},
/// Print a document's blob bytes, by document event ID.
///
/// Resolves the `document.put` event to the content hash it names and exports the bytes
/// the publish step stored: to a file, or to stdout with the default `-`.
Content {
/// The document's event ID, as `publish` printed it.
document: String,
/// Output path, or "-" for stdout.
#[arg(default_value = "-")]
output: String,
},
}
10 changes: 7 additions & 3 deletions pkgs/id/crates/id-cli/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
//! group Groups: create, policy, add, remove, set roles, list, join
//! delegate Grant a delegate a scope in a group
//! revoke Revoke a delegation by its grant's event ID
//! doc Documents: publish a file; list events, frontier, history
//! doc Documents: publish a file, fetch its bytes; list events, frontier, history
//! claim Tag claims on any subject (set, clear, list, search)
//! writer-sets Writer sets in the event store (show, expand, discover)
//! migrate-tags Migrate existing files to name/file auto-tags (alias: migrate)
Expand Down Expand Up @@ -1391,16 +1391,20 @@ pub enum Command {
Delegate(DelegateArgs),
/// Revoke a delegation by its grant's event ID, as `delegate` printed it (P6.7b).
Revoke(RevokeArgs),
/// Documents: publish a file, and list a document's events, frontier and history (P6.7c).
/// Documents: publish a file, fetch a document's bytes, and list a document's events,
/// frontier and history (P6.7c).
///
/// Each action signs one event into the event store and prints one line, or one JSON object
/// with `--json`. The store stands in for sync: nodes that share it see each other's events.
/// Lists print one line per row, or one JSON array with `--json`.
/// Publish also stores the file's bytes in the blob store under their hash, so `content`
/// can fetch them back by document ID. Lists print one line per row, or one JSON array
/// with `--json`.
///
/// # Examples
///
/// ```bash
/// id doc publish notes.md --media-type text/markdown --tag topic=plans
/// id doc content DOCUMENT
/// id doc history DOCUMENT
/// id doc frontier --json
/// ```
Expand Down
27 changes: 27 additions & 0 deletions pkgs/id/crates/id-cli/src/cli/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -969,6 +969,33 @@ fn test_cli_parse_put_hash() {
}
}

#[test]
fn test_cli_parse_doc_content() {
let cli = Cli::parse_from(["id", "doc", "content", "abc123"]);
match cli.command {
Some(Command::Doc {
command: DocCommand::Content { document, output },
..
}) => {
assert_eq!(document, "abc123");
assert_eq!(output, "-");
}
_ => panic!("Expected Doc::Content command"),
}

let cli = Cli::parse_from(["id", "doc", "content", "abc123", "out.txt"]);
match cli.command {
Some(Command::Doc {
command: DocCommand::Content { document, output },
..
}) => {
assert_eq!(document, "abc123");
assert_eq!(output, "out.txt");
}
_ => panic!("Expected Doc::Content command"),
}
}

#[test]
fn test_cli_verify() {
// Verify CLI structure is valid
Expand Down
141 changes: 136 additions & 5 deletions pkgs/id/crates/id-cli/src/commands/doc.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,40 @@
//! `id doc`: publish a file as a document, and list a document's events, frontier and history
//! (P6.7c): parse the arguments, act on the event store, and print.
//! `id doc`: publish a file as a document, fetch a document's bytes, and list a
//! document's events, frontier and history (P6.7c): parse the arguments, act on the event store,
//! and print.
//!
//! The rules are the library's ([`id_events::local_events`]). This module only turns arguments into
//! calls and results into lines or JSON. The store is the stand-in for sync, as the group log is.
//!
//! Publish stores the file's bytes in the blob store under their hash before recording the
//! events, through the same blob path other writes use, so `content` can fetch them back by the
//! document's event ID. Serving a running node goes through it (ephemeral store plus a push,
//! as `put` does) instead of opening the persistent store the server holds.
//!
//! # Output
//!
//! `publish` prints one line, `publish document=<ID> content=<HASH> size=<N> media_type=<TYPE>`,
//! then one `set` line for each `--tag`. The events, frontier and history print one line per row,
//! then one `set` line for each `--tag`. `content` exports the document's bytes to the output
//! path, or to stdout with `-`. The events, frontier and history print one line per row,
//! with no command word, and `kind=` (or the head's fields) first. With `--json` each action prints
//! one object with a `command` key, and each list prints one array.

use std::path::PathBuf;

use anyhow::{Context, Result};
use anyhow::{Context, Result, bail};
use iroh_blobs::{
ALPN as BLOBS_ALPN, Hash as BlobHash,
protocol::{ChunkRanges, ChunkRangesSeq, PushRequest},
};
use p2panda_core::{Hash, SigningKey};
use serde_json::{Value, json};

use crate::cli::DocCommand;
use crate::commands::claim::print_set;
use crate::commands::get::cmd_gethash;
use crate::commands::group::{hex, object, tokens};
use crate::{KEY_FILE, load_or_create_keypair};
use crate::{
KEY_FILE, create_local_client_endpoint, get_serve_info, load_or_create_keypair, open_store,
};
use id_events::local_events::{DIR_NAME, Entry, LocalEvents};
use id_groups::groups::log::hash_from_hex;

Expand All @@ -36,6 +50,63 @@ pub(super) async fn open_events(path: Option<PathBuf>) -> Result<LocalEvents> {
LocalEvents::open(&dir, SigningKey::from_bytes(&secret.to_bytes()))
}

/// Stores `content` as a raw blob through the same blob path other writes use, and returns
/// its hash: into the persistent store directly, or (when a serve holds that store) into an
/// ephemeral store pushed to the serve, as `put` does.
/// The caller records the document event afterwards, which is what registers the
/// document-to-hash reference the blob gate reads (`EventStore::document_references`).
///
/// # Errors
///
/// Fails if the store cannot be opened, the bytes cannot be added, or (with a serve running)
/// the blob cannot be pushed to it.
async fn store_publish_bytes(content: &[u8]) -> Result<BlobHash> {
if let Some(serve_info) = get_serve_info().await {
let store = open_store(true).await?;
let store_handle = store.as_store();
let added = store_handle.blobs().add_bytes(content.to_vec()).await?;
let hash = added.hash;
let (endpoint, endpoint_addr) = create_local_client_endpoint(&serve_info).await?;
let blobs_conn =
id_core::connectivity::connect(&endpoint, endpoint_addr.clone(), BLOBS_ALPN).await?;
let push_request =
PushRequest::new(hash, ChunkRangesSeq::from_ranges([ChunkRanges::all()]));
store_handle
.remote()
.execute_push(blobs_conn.clone(), push_request)
.await?;
blobs_conn.close(0u32.into(), b"done");
endpoint.close().await;
store.shutdown().await?;
Ok(hash)
} else {
let store = open_store(false).await?;
let store_handle = store.as_store();
let added = store_handle.blobs().add_bytes(content.to_vec()).await?;
let hash = added.hash;
store.shutdown().await?;
Ok(hash)
}
}

/// The blob hash the document `document_hex` names: its `document.put` event's content hash.
/// This is the reference the publish step stored the bytes under.
///
/// # Errors
///
/// Fails if `document_hex` is not a document's event ID, or the store cannot be read.
fn document_content_hash(events: &LocalEvents, document_hex: &str) -> Result<BlobHash> {
let document = hash_from_hex(document_hex)?;
let history = events.history(document)?;
history
.iter()
.find_map(|entry| match entry {
Entry::Document { document, .. } => Some(document.blob_hash()),
_ => None,
})
.with_context(|| format!("{document_hex} names no document.put event"))
}

/// Prints one action: a line `command key=value ...`, or one JSON object with `command` first.
pub(super) fn print_action(json: bool, command: &str, fields: Vec<(&str, Value)>) {
if json {
Expand Down Expand Up @@ -137,7 +208,14 @@ pub async fn cmd_doc(path: Option<PathBuf>, json: bool, command: DocCommand) ->
std::fs::read(&file).with_context(|| format!("read {}", file.display()))?;
let tags: Vec<(String, Option<String>)> =
tags.iter().map(|text| parse_tag(text)).collect();
let stored = store_publish_bytes(&content).await?;
let published = events.publish(&media_type, &content, &tags)?;
if stored != published.document.blob_hash() {
bail!(
"stored blob {stored} does not match the published content hash {}",
published.document.blob_hash()
);
}
let fields = vec![
("document", json!(published.id.to_hex())),
("content", json!(published.document.content.to_hex())),
Expand Down Expand Up @@ -178,6 +256,10 @@ pub async fn cmd_doc(path: Option<PathBuf>, json: bool, command: DocCommand) ->
.collect();
print_rows(json, &rows);
}
DocCommand::Content { document, output } => {
let hash = document_content_hash(&events, &document)?;
cmd_gethash(&hash.to_string(), &output).await?;
}
}
Ok(())
}
Expand Down Expand Up @@ -222,4 +304,53 @@ mod tests {
assert_eq!(get("note"), Some(&json!(hash(10).to_hex())));
assert_eq!(get("parents"), Some(&json!(hash(10).to_hex())));
}

fn test_events() -> (tempfile::TempDir, LocalEvents) {
let dir = tempfile::TempDir::new().unwrap();
let events = LocalEvents::open(dir.path(), SigningKey::from_bytes(&[7; 32])).unwrap();
(dir, events)
}

#[test]
fn test_document_content_hash_resolves_the_published_hash() {
let (_dir, mut events) = test_events();
let content = b"round-trip me";
let published = events.publish("text/plain", content, &[]).unwrap();
let resolved = document_content_hash(&events, &published.id.to_hex()).unwrap();
assert_eq!(resolved, published.document.blob_hash());
}

#[test]
fn test_document_content_hash_rejects_unknown_documents() {
let (_dir, events) = test_events();
assert!(document_content_hash(&events, &hash(9).to_hex()).is_err());
assert!(document_content_hash(&events, "not-hex").is_err());
}

/// The #1008 pairing: the publish step stores the bytes under the hash the document
/// event names, so the content is retrievable by that reference and the reference index
/// the blob gate reads (`EventStore::document_references`) carries it.
#[tokio::test]
async fn test_published_bytes_are_retrievable_by_the_document_reference() {
let (_dir, mut events) = test_events();
let content = b"published bytes round-trip";
let published = events.publish("text/plain", content, &[]).unwrap();

let store = open_store(true).await.unwrap();
let handle = store.as_store();
let added = handle.blobs().add_bytes(content.to_vec()).await.unwrap();
assert_eq!(added.hash, published.document.blob_hash());

let fetched = handle.blobs().get_bytes(added.hash).await.unwrap();
assert_eq!(&fetched[..], &content[..]);

let references = events.document_references().unwrap();
assert!(
references
.iter()
.any(|(hash, _)| *hash == published.document.blob_hash()),
"the published document registers its content hash where the gate reads it"
);
store.shutdown().await.unwrap();
}
}