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
1 change: 1 addition & 0 deletions pkgs/id/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ it is — a valid world capability, minted by the host's admin with
| `revoke` | | Revoke a delegation by its grant event ID |
| `doc` | | Publish documents; list events/frontier/history |
| `claim` | | Tag claims on any subject (set, clear, search) |
| `writer-sets` | | Writer sets in the event store (show, expand, discover) |

### Tag Subcommands

Expand Down
66 changes: 66 additions & 0 deletions pkgs/id/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
//! revoke Revoke a delegation by its grant's event ID
//! doc Documents: publish a file; 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 @@ -1326,6 +1327,32 @@ pub enum Command {
#[command(subcommand)]
command: ClaimCommand,
},
/// Writer sets stored in the event store: show one, expand it, or discover
/// sets by scope (writer-set spec §§4–5; issue #6690).
///
/// A writer set is a signed `idset.writer` event whose body the store
/// retains at ingest. `show` prints the stored object, `expand` runs the
/// view projection over the store's resolved group state at the set's own
/// publishing frontier, and `discover` lists every stored set for a scope
/// with the writers each expands to. `--resolution` names the resolution
/// snapshot the projection is pinned under; without one, the zero hash
/// names the store's current resolved state.
///
/// # Examples
///
/// ```bash
/// id writer-sets discover --scope metrics
/// id writer-sets expand EVENT --json
/// id writer-sets show EVENT
/// ```
WriterSets {
/// Print JSON instead of lines (one array for `discover`).
#[arg(long, global = true)]
json: bool,
/// The writer-set action to run.
#[command(subcommand)]
command: WriterSetCommand,
},
/// Migrate existing files to have name/file auto-tags.
///
/// Scans all blob tags in the store and adds `name` and `file`
Expand Down Expand Up @@ -2646,6 +2673,45 @@ pub enum DocCommand {
},
}

/// The actions of `id writer-sets` (writer-set spec §§4–5; issue #6690).
#[derive(Subcommand, Debug, Clone, PartialEq, Eq)]
pub enum WriterSetCommand {
/// Show one stored writer set: its ID, version, owner, scope, and the
/// counts of its admission entries and exclusions.
Show {
/// The publishing event's ID.
event: String,
},
/// Expand one stored writer set at its publishing frontier: whether the
/// expansion is public, and the explicit authors it admits after
/// exclusions.
Expand {
/// The publishing event's ID.
event: String,
/// The resolution snapshot to pin the projection under, as hex.
/// Without one, the zero hash names the store's current resolved
/// state.
#[arg(long)]
resolution: Option<String>,
/// Expand retroactively: only entries marked include-history
/// contribute (exclusions always apply).
#[arg(long)]
retro: bool,
},
/// Discover stored writer sets by scope: one row per set, with the
/// writers it expands to. Without `--scope`, every stored set matches.
Discover {
/// The scope (subject) to match, exactly.
#[arg(long)]
scope: Option<String>,
/// The resolution snapshot to pin each expansion under, as hex.
/// Without one, the zero hash names the store's current resolved
/// state.
#[arg(long)]
resolution: Option<String>,
},
}

/// Subcommands for `id claim`. A claim is the event that sets a tag on a subject.
#[derive(Subcommand, Debug)]
pub enum ClaimCommand {
Expand Down
2 changes: 2 additions & 0 deletions pkgs/id/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ pub mod tag;
pub mod text;
#[cfg(feature = "world")]
pub mod world;
pub mod writer_set;

pub use claim::cmd_claim;
pub use client::create_local_client_endpoint;
Expand Down Expand Up @@ -101,3 +102,4 @@ pub use serve::{
pub use tag::{cmd_migrate_tags, cmd_tag};
#[cfg(feature = "world")]
pub use world::cmd_world;
pub use writer_set::cmd_writer_sets;
150 changes: 150 additions & 0 deletions pkgs/id/src/commands/writer_set.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
//! `id writer-sets`: show, expand, and discover the writer sets stored in
//! the event store (writer-set spec §§4–5; issue #6690).
//!
//! This module parses the arguments, acts on the event store, and prints.
//! The rules are the library's ([`crate::event_store`]): a stored set is read
//! back from its retained body and checked against its publishing header,
//! the projection is [`crate::idset::view::expand_set`] over snapshots the
//! store builds from its resolved group state, and discovery is
//! subject-first — filter by the set's scope, each hit carrying the set and
//! the writers it expands to.
//!
//! # Output
//!
//! `show` prints `show event=<ID> set=<ID> version=<N> owner=<KEY>
//! [scope=<SCOPE>] entries=<N> excludes=<N>`. `expand` prints `expand
//! event=<ID> public=<BOOL> authors=<HEX,HEX,...> retro=<BOOL>`. `discover`
//! prints one row per stored set, `event= set= version= [scope=] public=
//! authors=`, or one JSON array with `--json`.

use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{Result, bail};
use p2panda_core::Hash;
use serde_json::{Value, json};

use crate::cli::WriterSetCommand;
use crate::commands::doc::{print_action, print_rows};
use crate::commands::group::hex;
use crate::event_store::{DiscoveredWriterSet, EventStore};
use crate::groups::log::hash_from_hex;
use crate::idset::WriterSet;
use crate::idset::view::ExpandedWriters;
use crate::local_events::DIR_NAME;
use crate::waiting::WaitingLimits;

/// Opens the event store the command reads, at `path` or the default
/// events directory.
fn open_store(path: Option<PathBuf>) -> Result<EventStore> {
let dir = path.unwrap_or_else(|| PathBuf::from(DIR_NAME));
std::fs::create_dir_all(&dir)
.map_err(|err| anyhow::anyhow!("create {}: {err}", dir.display()))?;
let now_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
.unwrap_or(0);
Ok(EventStore::open(&dir, WaitingLimits::default(), now_ms)?)
}

/// The resolution snapshot a query pins: the `--resolution` hash when one is
/// given, else the zero hash, which names the store's current resolved
/// state.
fn resolution(pin: Option<String>) -> Result<Hash> {
match pin {
Some(text) => hash_from_hex(&text),
None => Ok(Hash::from([0; 32])),
}
}

/// The author keys an expansion admits explicitly, as hex, in key order.
fn author_values(expanded: &ExpandedWriters) -> Value {
json!(
expanded
.explicit_authors()
.iter()
.map(|author| hex(author))
.collect::<Vec<_>>()
)
}

/// The fields of one stored set, as `show` prints them.
fn set_fields(event: Hash, set: &WriterSet) -> Vec<(&'static str, Value)> {
let mut fields = vec![
("event", json!(event.to_hex())),
("set", json!(set.set_id.to_hex())),
("version", json!(set.version)),
("owner", json!(hex(&set.owner))),
];
if let Some(scope) = &set.scope {
fields.push(("scope", json!(scope)));
}
fields.push(("entries", json!(set.entries.len())));
fields.push(("excludes", json!(set.excludes.0.len())));
fields
}

/// The fields of one discovery hit, as `discover` rows print them.
fn hit_fields(hit: &DiscoveredWriterSet) -> Vec<(&'static str, Value)> {
let mut fields = vec![
("event", json!(hit.event_id.to_hex())),
("set", json!(hit.set.set_id.to_hex())),
("version", json!(hit.set.version)),
];
if let Some(scope) = &hit.set.scope {
fields.push(("scope", json!(scope)));
}
fields.push(("public", json!(hit.expanded.is_public())));
fields.push(("authors", author_values(&hit.expanded)));
fields
}

/// Runs an `id writer-sets` command.
///
/// # Errors
///
/// Fails if an argument is malformed, the store cannot be opened or read,
/// or the named event is not a stored writer set.
pub async fn cmd_writer_sets(
path: Option<PathBuf>,
json: bool,
command: WriterSetCommand,
) -> Result<()> {
let store = open_store(path)?;
match command {
WriterSetCommand::Show { event } => {
let event = hash_from_hex(&event)?;
let Some(set) = store.stored_writer_set(&event)? else {
bail!("no stored writer set for event {event}");
};
print_action(json, "show", set_fields(event, &set));
}
WriterSetCommand::Expand {
event,
resolution: pin,
retro,
} => {
let event = hash_from_hex(&event)?;
let expanded = store.expand_stored_writer_set(&event, &resolution(pin)?, retro)?;
print_action(
json,
"expand",
vec![
("event", json!(event.to_hex())),
("public", json!(expanded.is_public())),
("authors", author_values(&expanded)),
("retro", json!(retro)),
],
);
}
WriterSetCommand::Discover {
scope,
resolution: pin,
} => {
let hits = store.discover_writer_sets(scope.as_deref(), &resolution(pin)?)?;
let rows: Vec<Vec<(&str, Value)>> = hits.iter().map(hit_fields).collect();
print_rows(json, &rows);
}
}
Ok(())
}
18 changes: 17 additions & 1 deletion pkgs/id/src/event_store/ingest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,9 @@ impl EventStore {
/// - A body that is not a group operation, or no body at all, makes the event content.
/// - A body that claims to be a group operation decodes to its action, or it is refused.
/// - A body that is not the one the header commits to, by BLAKE3 hash and size, is refused.
/// - A writer-set or rescind event's verified body is retained with the store
/// (`writer_set_bodies`), so the stored object can be read back and projected
/// (issue #6690; see the `writer_set` submodule).
/// - A tag event (kind `tag.set` or `tag.clear`) takes no body. Its operation is in its
/// header (#182), so a payload on a tag event is refused. Its tag takes no membership
/// action, and the fold reads it from the stored header (see `claims`).
Expand All @@ -258,6 +261,13 @@ impl EventStore {
Err(err) => return Ok(Ingest::Refused(Refusal::Malformed(err.to_string()))),
};
let kind = &event.header.extensions.kind;
// A writer-set or rescind body is retained with its event (issue
// #6690): the header commits to it by hash, and `body_action` below
// has already refused a body that is not the committed one, so what
// is retained here is the object the signer published.
let retain_body = body
.filter(|_| crate::idset::is_writer_kind(kind) || crate::idset::is_rescind_kind(kind));
let event_id = event.id;
let action = if is_tag_kind(kind) || is_document_kind(kind) || is_removal_kind(kind) {
if body.is_some() {
return Ok(Ingest::Refused(Refusal::Malformed(
Expand All @@ -272,7 +282,13 @@ impl EventStore {
Err(refusal) => return Ok(Ingest::Refused(refusal)),
}
};
self.ingest_event(event, action.as_ref(), now_ms)
let result = self.ingest_event(event, action.as_ref(), now_ms)?;
if let Some(body) = retain_body
&& !matches!(result, Ingest::Refused(_))
{
self.record_writer_body(&event_id, body)?;
}
Ok(result)
}

/// Verifies one received event, which may be a group operation, and applies what it allows.
Expand Down
17 changes: 14 additions & 3 deletions pkgs/id/src/event_store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,13 @@ pub mod range;
mod resolve;
pub mod sync;
mod waiting_rows;
mod writer_set;

use crate::waiting::{AuthorKey, WaitRefusal, WaitingLimits, WaitingPool};
pub use ingest::{Ingest, Refusal};
use ingest::{is_present, is_proof_header, present_in};
use waiting_rows::{Mirror, Row};
pub use writer_set::{DiscoveredWriterSet, WriterSetStoreError};

/// The store's file name in its directory.
pub const FILE_NAME: &str = "events.redb";
Expand Down Expand Up @@ -109,6 +111,14 @@ const WAITING_BY_DEP: MultimapTableDefinition<'static, &'static [u8], &'static [
const META: TableDefinition<'static, &'static [u8], &'static [u8]> = TableDefinition::new("meta");
const BLOCKS: TableDefinition<'static, &'static [u8], &'static [u8]> =
TableDefinition::new("blocks");
/// Each writer-set or rescind event's retained body, by event ID (writer-set
/// spec §§4–5; issue #6690). Headers commit to bodies by hash but are stored
/// without them; this table is the one place a body is kept, so a stored
/// writer-set object can be read back and checked against its header. Written
/// only from the ingest path, after the body has been verified against the
/// header's payload commitment.
const WRITER_SET_BODIES: TableDefinition<'static, &'static [u8], &'static [u8]> =
TableDefinition::new("writer_set_bodies");
/// Each group operation's encoded action, by event ID. Written when the event arrives, held or
/// stored, so a release reads it back without the caller. The resolution reads it again.
const ACTIONS: TableDefinition<'static, &'static [u8], &'static [u8]> =
Expand Down Expand Up @@ -647,12 +657,13 @@ impl EventStore {
create_fresh(storage)?
};
verify_schema(&db)?;
// The blocks table is additive: stores created before it gain it here,
// on the write every open already performs, instead of a format change
// that would refuse them.
// The blocks and writer-set-bodies tables are additive: stores created
// before them gain them here, on the write every open already
// performs, instead of a format change that would refuse them.
{
let txn = db.begin_write()?;
txn.open_table(BLOCKS)?;
txn.open_table(WRITER_SET_BODIES)?;
txn.commit()?;
}
let mut store = Self {
Expand Down
Loading
Loading