From 14df47a0bd2987bd7d7084e79d38a7e42bf334c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:46:13 +0000 Subject: [PATCH] feat(id-worlds): owner report projection from one world's journal (#11774) Streams one world's journal and returns a typed, read-only owner report: durable join counts (host issued, delegated, revoked, distinct accounts, inherited from a fork), journal coverage, a bounded recent-join sample by participant id only, and the caller's storage inventory. The journal records no join time, so join times and window counts are reported unavailable with a reason, never zero. Live membership and program runs are unavailable until #11775 supplies them. Refuses a missing header, another world's journal, an unsupported version, malformed or duplicate-header lines, entries newer than the header and oversized lines as distinct errors. A torn final line is not counted and marks the report incomplete. Fixture and property tests. Co-Authored-By: Claude Opus 5.5 --- pkgs/id/crates/id-worlds/src/lib.rs | 1 + .../id-worlds/src/world_owner_report.rs | 538 ++++++++++++++++++ .../id-worlds/src/world_owner_report_tests.rs | 376 ++++++++++++ 3 files changed, 915 insertions(+) create mode 100644 pkgs/id/crates/id-worlds/src/world_owner_report.rs create mode 100644 pkgs/id/crates/id-worlds/src/world_owner_report_tests.rs diff --git a/pkgs/id/crates/id-worlds/src/lib.rs b/pkgs/id/crates/id-worlds/src/lib.rs index c659bc5589..c08de98164 100644 --- a/pkgs/id/crates/id-worlds/src/lib.rs +++ b/pkgs/id/crates/id-worlds/src/lib.rs @@ -72,6 +72,7 @@ pub mod world_replication_net; pub mod world_session; #[cfg(feature = "ssh")] pub mod world_ssh; +pub mod world_owner_report; pub mod world_storage; pub mod world_store; pub mod world_terminal; diff --git a/pkgs/id/crates/id-worlds/src/world_owner_report.rs b/pkgs/id/crates/id-worlds/src/world_owner_report.rs new file mode 100644 index 0000000000..eb90ab8c7b --- /dev/null +++ b/pkgs/id/crates/id-worlds/src/world_owner_report.rs @@ -0,0 +1,538 @@ +//! The owner report projection for one world, read-only (#11774, design +//! #6308 §§2–4, 8–9). +//! +//! [`project`] streams one world's journal once and returns an +//! [`OwnerReport`]: durable join facts from the journal, the storage +//! inventory the caller measured ([`crate::world_storage`]), and the +//! sections it has no source for yet marked unavailable with a reason. +//! It never writes, never opens a network connection and never loads the +//! whole journal: it keeps one line, a per-participant flag map bounded +//! by [`ReportLimits::max_participants`], and a bounded sample. +//! +//! What the journal can and cannot answer, as of journal version +//! [`crate::world::MAX_JOURNAL_VERSION`]: +//! +//! - A join is an `Issued` entry: a capability the world granted, host +//! issued or delegated. Compaction rewrites every capability ever +//! issued (revoked ones with their `Revoked` entry), so the count is +//! complete across checkpoints. +//! - No journal entry records *when* a capability was issued, so the +//! join time, the earliest answerable time and any count inside a time +//! window are [`UnavailableReason::JoinTimeNotRecorded`], never zero. +//! Recording them is a journal-format change, out of this scope. +//! - Live membership and program runs come from a running world +//! (#11775); this projection reports them unavailable until a caller +//! supplies them. +//! +//! `null` plus a reason means unavailable; `0` means measured zero. + +use std::collections::{BTreeSet, HashMap, VecDeque}; +use std::fmt; +use std::io::{self, BufRead, Read}; + +use serde::ser::SerializeMap; +use serde::{Serialize, Serializer}; + +use crate::world::{JournalEntry, MAX_JOURNAL_VERSION, journal_version_required_by}; +use crate::world_storage::StorageInventory; + +/// Major version of the report's JSON shape. Consumers accept added +/// optional fields and refuse any other major version. +pub const OWNER_REPORT_SCHEMA_VERSION: u32 = 1; + +/// Why a report value is unavailable. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum UnavailableReason { + /// The journal records no time for a capability's issue. + JoinTimeNotRecorded, + /// No live participant snapshot was supplied (the world is not + /// running, or the caller did not ask it). + LiveStateNotProvided, + /// No program-run source was supplied; the journal records no runs. + ProgramRunsNotRecorded, + /// No storage inventory was supplied. + StorageNotMeasured, +} + +impl UnavailableReason { + /// The human-readable form the text report prints. + #[must_use] + pub const fn describe(self) -> &'static str { + match self { + Self::JoinTimeNotRecorded => "the journal does not record when anyone joined", + Self::LiveStateNotProvided => "no live snapshot (the world is not running here)", + Self::ProgramRunsNotRecorded => "program runs are not recorded by this journal", + Self::StorageNotMeasured => "storage was not measured", + } + } +} + +/// A value that is either measured or unavailable for a stated reason. +/// Serializes as `{"value": v}` or `{"value": null, "reason": "…"}`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Measured { + /// The value, measured. + Known(T), + /// No value, and why. + Unavailable(UnavailableReason), +} + +impl Measured { + /// The value when measured. + #[must_use] + pub const fn value(&self) -> Option<&T> { + match self { + Self::Known(value) => Some(value), + Self::Unavailable(_) => None, + } + } + + /// Why the value is unavailable, when it is. + #[must_use] + pub const fn reason(&self) -> Option { + match self { + Self::Known(_) => None, + Self::Unavailable(reason) => Some(*reason), + } + } +} + +impl Serialize for Measured { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::Known(value) => { + let mut map = serializer.serialize_map(Some(1))?; + map.serialize_entry("value", value)?; + map.end() + } + Self::Unavailable(reason) => { + let mut map = serializer.serialize_map(Some(2))?; + map.serialize_entry("value", &None::<()>)?; + map.serialize_entry("reason", reason)?; + map.end() + } + } + } +} + +/// The requested time window, in unix milliseconds, `from` inclusive and +/// `to` exclusive. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct ReportWindow { + /// Start, inclusive. + pub from_unix_ms: u64, + /// End, exclusive. + pub to_unix_ms: u64, +} + +/// Bounds on one projection. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ReportLimits { + /// Longest journal line read, newline included. A longer line is + /// refused rather than buffered. + pub max_line_bytes: usize, + /// Most distinct participants tracked. Past it the counts stop and + /// [`JoinsSection::complete`] is false. + pub max_participants: usize, + /// Most recent joins listed in [`JoinsSection::recent`]. + pub sample_limit: usize, +} + +impl Default for ReportLimits { + fn default() -> Self { + Self { + max_line_bytes: 64 * 1024 * 1024, + max_participants: 1_000_000, + sample_limit: 20, + } + } +} + +/// What a projection was asked for. Every input that varies between +/// calls is here, so the same journal and request give the same report. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ReportRequest { + /// The world the journal must belong to. + pub world_id: String, + /// The report's snapshot time, in unix milliseconds. + pub generated_at_unix_ms: u64, + /// The requested window. + pub window: ReportWindow, + /// Bounds. + pub limits: ReportLimits, +} + +/// How much of the journal the report rests on. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct JournalCoverage { + /// Version in the journal's header (`None` for an empty journal). + pub header_version: Option, + /// Entries read, header included. + pub entries: u64, + /// Whether a compaction checkpoint stands in for earlier events. + pub checkpointed: bool, + /// The world this one was forked from, when the fork record survives. + pub forked_from: Option, + /// Whether the journal ended in an unterminated line (a write cut + /// short). The line is not counted and the report is incomplete. + pub torn_tail: bool, +} + +/// One join in the recent sample: a participant id and its state, never +/// a display name or capability material. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct JoinSample { + /// Server-assigned participant id. + pub participant_id: u64, + /// Whether the capability was delegated from another participant's. + pub delegated: bool, + /// Whether the capability has since been revoked. + pub revoked: bool, +} + +/// Durable join facts. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct JoinsSection { + /// Distinct participants ever issued a capability. + pub count: u64, + /// Of those, issued by the host (no parent capability). + pub host_issued: u64, + /// Of those, delegated from another participant's capability. + pub delegated: u64, + /// Of those, revoked since. + pub revoked: u64, + /// Distinct accounts the capabilities act for; a rejoin under the + /// same account is one subject and several participants. + pub distinct_subjects: u64, + /// Participants the journal had before its fork record, when the + /// world is a fork and the record survives. + pub inherited_from_fork: Option, + /// Joins inside the requested window. + pub in_window: Measured, + /// Earliest time from which joins are answerable. + pub available_since: Measured, + /// Whether every join in the journal was counted. + pub complete: bool, + /// The most recent joins, newest first, at most + /// [`ReportLimits::sample_limit`]. + pub recent: Vec, +} + +/// Live membership (#11775 supplies it). +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct MembersSection { + /// Participants connected at the snapshot. + pub active_count: Measured, + /// What "active" means. + pub definition: &'static str, +} + +/// Program runs (#11775 supplies process-local counters). +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct ProgramRunsSection { + /// Runs counted. + pub count: Measured, +} + +/// The owner report for one world. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct OwnerReport { + /// [`OWNER_REPORT_SCHEMA_VERSION`]. + pub schema_version: u32, + /// The world reported on. + pub world_id: String, + /// Snapshot time, in unix milliseconds. + pub generated_at_unix_ms: u64, + /// The requested window. + pub window: ReportWindow, + /// What the journal covered. + pub journal: JournalCoverage, + /// Durable join facts. + pub joins: JoinsSection, + /// Live membership. + pub members: MembersSection, + /// Program runs. + pub program_runs: ProgramRunsSection, + /// On-disk storage, as measured by the caller. + pub storage: Measured, +} + +/// Why a projection could not produce a report. Each is distinct, so a +/// caller never shows a refusal as an empty report. +#[derive(Debug)] +pub enum OwnerReportError { + /// The window ends before it starts. + InvalidWindow, + /// The journal's first entry is not its header. + MissingHeader, + /// The journal belongs to another world. + WrongWorld { + /// The world named in the header. + found: String, + }, + /// The journal's header version is outside what this binary reads. + UnsupportedJournalVersion { + /// The header version. + version: u32, + }, + /// A line does not parse as a journal entry, or repeats the header. + Malformed { + /// One-based line number. + line: u64, + }, + /// An entry needs a newer journal version than its header declares. + EntryNewerThanHeader { + /// One-based line number. + line: u64, + /// The version the entry needs. + required: u32, + }, + /// A line is longer than [`ReportLimits::max_line_bytes`]. + OversizedLine { + /// One-based line number. + line: u64, + }, + /// Reading the journal failed. + Io(io::Error), +} + +impl fmt::Display for OwnerReportError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidWindow => write!(f, "report window ends before it starts"), + Self::MissingHeader => write!(f, "world journal does not start with a header"), + Self::WrongWorld { found } => write!(f, "journal belongs to world {found:?}"), + Self::UnsupportedJournalVersion { version } => { + write!(f, "unsupported world journal version {version}") + } + Self::Malformed { line } => write!(f, "journal line {line} is not a journal entry"), + Self::EntryNewerThanHeader { line, required } => write!( + f, + "journal line {line} needs journal version {required}, newer than its header" + ), + Self::OversizedLine { line } => write!(f, "journal line {line} exceeds the line limit"), + Self::Io(error) => write!(f, "read journal: {error}"), + } + } +} + +impl std::error::Error for OwnerReportError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(error) => Some(error), + _ => None, + } + } +} + +/// Refuse a report JSON whose major schema version this reader does not +/// know. Added fields are fine; a missing or other version is not. +/// +/// # Errors +/// +/// The version found (or `None` when absent or not a number). +pub fn check_schema_version(report: &serde_json::Value) -> Result> { + let found = report + .get("schema_version") + .and_then(serde_json::Value::as_u64); + match found { + Some(v) if v == u64::from(OWNER_REPORT_SCHEMA_VERSION) => Ok(OWNER_REPORT_SCHEMA_VERSION), + other => Err(other), + } +} + +#[derive(Clone, Copy, Default)] +struct ParticipantFlags { + delegated: bool, + revoked: bool, +} + +/// Read one line of at most `max` bytes. `Ok(None)` at end of input; +/// the flag says whether the line ended in a newline. +fn next_line( + journal: &mut R, + buf: &mut Vec, + max: usize, + line: u64, +) -> Result, OwnerReportError> { + buf.clear(); + let cap = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1); + let read = journal + .by_ref() + .take(cap) + .read_until(b'\n', buf) + .map_err(OwnerReportError::Io)?; + if read == 0 { + return Ok(None); + } + let terminated = buf.last() == Some(&b'\n'); + if buf.len() > max || (!terminated && read as u64 == cap) { + return Err(OwnerReportError::OversizedLine { line }); + } + Ok(Some(terminated)) +} + +/// Project the owner report from one world's journal. +/// +/// `storage` is the caller's [`crate::world_storage::inventory`] of the +/// same world, or `None` when it was not measured. +/// +/// # Errors +/// +/// Any [`OwnerReportError`]: the journal is refused whole rather than +/// reported in part as if complete. +pub fn project( + mut journal: R, + request: &ReportRequest, + storage: Option, +) -> Result { + let window = request.window; + if window.to_unix_ms < window.from_unix_ms { + return Err(OwnerReportError::InvalidWindow); + } + let limits = request.limits; + let mut coverage = JournalCoverage { + header_version: None, + entries: 0, + checkpointed: false, + forked_from: None, + torn_tail: false, + }; + let mut participants: HashMap = HashMap::new(); + let mut subjects: BTreeSet = BTreeSet::new(); + let mut recent: VecDeque = VecDeque::with_capacity(limits.sample_limit); + let mut inherited_from_fork = None; + let mut over_limit = false; + let mut buf = Vec::new(); + let mut line = 0_u64; + + loop { + line += 1; + let Some(terminated) = next_line(&mut journal, &mut buf, limits.max_line_bytes, line)? + else { + break; + }; + if !terminated { + coverage.torn_tail = true; + break; + } + let text = buf.strip_suffix(b"\n").unwrap_or(&buf); + let entry: JournalEntry = + serde_json::from_slice(text).map_err(|_parse_error| OwnerReportError::Malformed { line })?; + coverage.entries += 1; + let Some(version) = coverage.header_version else { + let JournalEntry::Created { world_id, version } = entry else { + return Err(OwnerReportError::MissingHeader); + }; + if world_id != request.world_id { + return Err(OwnerReportError::WrongWorld { found: world_id }); + } + if !(1..=MAX_JOURNAL_VERSION).contains(&version) { + return Err(OwnerReportError::UnsupportedJournalVersion { version }); + } + coverage.header_version = Some(version); + continue; + }; + let required = journal_version_required_by(&entry); + if required > version { + return Err(OwnerReportError::EntryNewerThanHeader { line, required }); + } + match entry { + JournalEntry::Created { .. } => return Err(OwnerReportError::Malformed { line }), + JournalEntry::Issued { + participant, + parent, + subject, + .. + } => { + if participants.contains_key(&participant.id) { + continue; + } + if participants.len() >= limits.max_participants { + over_limit = true; + continue; + } + participants.insert( + participant.id, + ParticipantFlags { + delegated: parent.is_some(), + revoked: false, + }, + ); + if let Some(subject) = subject { + subjects.insert(subject); + } + if limits.sample_limit > 0 { + if recent.len() == limits.sample_limit { + recent.pop_front(); + } + recent.push_back(participant.id); + } + } + JournalEntry::Revoked { participant_id, .. } => { + if let Some(flags) = participants.get_mut(&participant_id) { + flags.revoked = true; + } + } + JournalEntry::Forked { from_world_id, .. } => { + coverage.forked_from = Some(from_world_id); + inherited_from_fork = Some(participants.len() as u64); + } + JournalEntry::Checkpoint { .. } => coverage.checkpointed = true, + _ => {} + } + } + + let count = participants.len() as u64; + let delegated = participants.values().filter(|f| f.delegated).count() as u64; + let revoked = participants.values().filter(|f| f.revoked).count() as u64; + let recent = recent + .iter() + .rev() + .map(|id| { + let flags = participants.get(id).copied().unwrap_or_default(); + JoinSample { + participant_id: *id, + delegated: flags.delegated, + revoked: flags.revoked, + } + }) + .collect(); + let joins = JoinsSection { + count, + host_issued: count - delegated, + delegated, + revoked, + distinct_subjects: subjects.len() as u64, + inherited_from_fork, + in_window: Measured::Unavailable(UnavailableReason::JoinTimeNotRecorded), + available_since: Measured::Unavailable(UnavailableReason::JoinTimeNotRecorded), + complete: !over_limit && !coverage.torn_tail, + recent, + }; + Ok(OwnerReport { + schema_version: OWNER_REPORT_SCHEMA_VERSION, + world_id: request.world_id.clone(), + generated_at_unix_ms: request.generated_at_unix_ms, + window, + journal: coverage, + joins, + members: MembersSection { + active_count: Measured::Unavailable(UnavailableReason::LiveStateNotProvided), + definition: "connected at the snapshot", + }, + program_runs: ProgramRunsSection { + count: Measured::Unavailable(UnavailableReason::ProgramRunsNotRecorded), + }, + storage: storage.map_or( + Measured::Unavailable(UnavailableReason::StorageNotMeasured), + Measured::Known, + ), + }) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +#[path = "world_owner_report_tests.rs"] +mod tests; diff --git a/pkgs/id/crates/id-worlds/src/world_owner_report_tests.rs b/pkgs/id/crates/id-worlds/src/world_owner_report_tests.rs new file mode 100644 index 0000000000..2794af8fca --- /dev/null +++ b/pkgs/id/crates/id-worlds/src/world_owner_report_tests.rs @@ -0,0 +1,376 @@ +//! Tests for the owner report projection (#11774). The oracle is the +//! fixture journal each test writes: counts come from the entries it +//! chose, not from a second implementation of the query. + +use std::io::Cursor; + +use proptest::prelude::*; + +use super::*; +use crate::world::{JournalEntry, Participant}; +use crate::world_storage::ByteCount; + +const WORLD: &str = "w-owner"; + +fn request() -> ReportRequest { + ReportRequest { + world_id: WORLD.to_owned(), + generated_at_unix_ms: 1_800_000_000_000, + window: ReportWindow { + from_unix_ms: 1_799_000_000_000, + to_unix_ms: 1_800_000_000_000, + }, + limits: ReportLimits::default(), + } +} + +fn header(version: u32) -> JournalEntry { + JournalEntry::Created { + world_id: WORLD.to_owned(), + version, + } +} + +fn issued(id: u64, parent: Option, subject: Option<&str>) -> JournalEntry { + JournalEntry::Issued { + participant: Participant { + id, + display_name: format!("name-{id}"), + }, + digest: format!("{id:064x}"), + scopes: 1, + parent, + expires_at: None, + uses: None, + used: 0, + subject: subject.map(str::to_owned), + } +} + +fn revoked(id: u64) -> JournalEntry { + JournalEntry::Revoked { + participant_id: id, + by: None, + } +} + +fn jsonl(entries: &[JournalEntry]) -> Vec { + let mut out = Vec::new(); + for entry in entries { + out.extend(serde_json::to_vec(entry).unwrap()); + out.push(b'\n'); + } + out +} + +fn run(bytes: &[u8]) -> Result { + project(Cursor::new(bytes.to_vec()), &request(), None) +} + +#[test] +fn fixture_journal_gives_exact_join_counts() { + let bytes = jsonl(&[ + header(1), + issued(1, None, Some("acct-a")), + issued(2, Some(1), None), + revoked(2), + issued(3, None, Some("acct-a")), + issued(4, None, Some("acct-b")), + ]); + let report = run(&bytes).unwrap(); + let joins = &report.joins; + assert_eq!(joins.count, 4); + assert_eq!(joins.host_issued, 3); + assert_eq!(joins.delegated, 1); + assert_eq!(joins.revoked, 1); + // A rejoin under one account is two participants and one subject. + assert_eq!(joins.distinct_subjects, 2); + assert!(joins.complete); + assert_eq!(joins.inherited_from_fork, None); + assert_eq!( + joins + .recent + .iter() + .map(|s| s.participant_id) + .collect::>(), + vec![4, 3, 2, 1] + ); + assert!(joins.recent[2].delegated && joins.recent[2].revoked); + assert_eq!(report.journal.header_version, Some(1)); + assert_eq!(report.journal.entries, 6); + assert!(!report.journal.torn_tail); +} + +#[test] +fn join_times_are_unavailable_never_zero() { + let report = run(&jsonl(&[header(1), issued(1, None, None)])).unwrap(); + assert_eq!( + report.joins.in_window.reason(), + Some(UnavailableReason::JoinTimeNotRecorded) + ); + assert_eq!(report.joins.in_window.value(), None); + assert_eq!( + report.joins.available_since.reason(), + Some(UnavailableReason::JoinTimeNotRecorded) + ); + let json = serde_json::to_value(&report).unwrap(); + assert_eq!( + json["joins"]["in_window"], + serde_json::json!({"value": null, "reason": "join_time_not_recorded"}) + ); + assert_eq!( + json["members"]["active_count"]["reason"], + "live_state_not_provided" + ); + assert_eq!( + json["program_runs"]["count"]["reason"], + "program_runs_not_recorded" + ); + assert_eq!(json["storage"]["reason"], "storage_not_measured"); + // A measured zero is a value, with no reason. + assert_eq!(json["joins"]["revoked"], 0); +} + +#[test] +fn empty_journal_is_an_empty_complete_world() { + let report = run(b"").unwrap(); + assert_eq!(report.joins.count, 0); + assert!(report.joins.complete); + assert_eq!(report.journal.header_version, None); + assert_eq!(report.journal.entries, 0); +} + +#[test] +fn repeated_projection_is_identical() { + let bytes = jsonl(&[ + header(1), + issued(7, None, Some("x")), + issued(9, Some(7), None), + revoked(7), + ]); + let a = serde_json::to_string(&run(&bytes).unwrap()).unwrap(); + let b = serde_json::to_string(&run(&bytes).unwrap()).unwrap(); + assert_eq!(a, b); +} + +#[test] +fn a_repeated_issue_counts_once() { + let report = run(&jsonl(&[ + header(1), + issued(5, None, None), + issued(5, None, None), + ])) + .unwrap(); + assert_eq!(report.joins.count, 1); + assert_eq!(report.joins.recent.len(), 1); +} + +#[test] +fn fork_record_names_inherited_participants() { + let bytes = jsonl(&[ + header(1), + issued(1, None, None), + issued(2, None, None), + JournalEntry::Forked { + from_world_id: "parent".to_owned(), + from_module_hash: String::new(), + template: false, + at_sequence: 0, + }, + issued(3, None, None), + ]); + let report = run(&bytes).unwrap(); + assert_eq!(report.journal.forked_from.as_deref(), Some("parent")); + assert_eq!(report.joins.inherited_from_fork, Some(2)); + assert_eq!(report.joins.count, 3); +} + +#[test] +fn torn_tail_is_not_counted_and_marks_incomplete() { + let mut bytes = jsonl(&[header(1), issued(1, None, None)]); + bytes.extend(serde_json::to_vec(&issued(2, None, None)).unwrap()); + let report = run(&bytes).unwrap(); + assert!(report.journal.torn_tail); + assert!(!report.joins.complete); + assert_eq!(report.joins.count, 1); +} + +#[test] +fn participant_limit_stops_counting_and_says_so() { + let mut req = request(); + req.limits.max_participants = 2; + let bytes = jsonl(&[ + header(1), + issued(1, None, None), + issued(2, None, None), + issued(3, None, None), + revoked(3), + ]); + let report = project(Cursor::new(bytes), &req, None).unwrap(); + assert_eq!(report.joins.count, 2); + assert_eq!(report.joins.revoked, 0); + assert!(!report.joins.complete); +} + +#[test] +fn sample_keeps_only_the_newest() { + let mut req = request(); + req.limits.sample_limit = 2; + let bytes = jsonl(&[ + header(1), + issued(1, None, None), + issued(2, None, None), + issued(3, None, None), + ]); + let report = project(Cursor::new(bytes.clone()), &req, None).unwrap(); + let ids: Vec = report + .joins + .recent + .iter() + .map(|s| s.participant_id) + .collect(); + assert_eq!(ids, vec![3, 2]); + req.limits.sample_limit = 0; + let report = project(Cursor::new(bytes), &req, None).unwrap(); + assert!(report.joins.recent.is_empty()); + assert_eq!(report.joins.count, 3); +} + +#[test] +fn sample_never_carries_names_or_capability_material() { + let report = run(&jsonl(&[header(1), issued(1, None, Some("acct-secret"))])).unwrap(); + let json = serde_json::to_string(&report).unwrap(); + assert!(!json.contains("name-1")); + assert!(!json.contains(&format!("{:064x}", 1))); + assert!(!json.contains("acct-secret")); +} + +#[test] +fn supplied_storage_is_reported_as_measured() { + let inventory = StorageInventory { + journal: ByteCount { + bytes: 10, + files: 1, + }, + modules: ByteCount::default(), + other: ByteCount::default(), + total_bytes: 10, + exact: false, + symlinks_skipped: 0, + nested_worlds_skipped: 0, + vanished: 0, + special_files: 0, + truncated: false, + as_of_unix_ms: 5, + }; + let report = project( + Cursor::new(jsonl(&[header(1)])), + &request(), + Some(inventory.clone()), + ) + .unwrap(); + assert_eq!(report.storage, Measured::Known(inventory)); + let json = serde_json::to_value(&report).unwrap(); + assert_eq!(json["storage"]["value"]["total_bytes"], 10); + assert!(json["storage"].get("reason").is_none()); +} + +#[test] +fn refusals_are_distinct() { + assert!(matches!( + run(&jsonl(&[issued(1, None, None)])), + Err(OwnerReportError::MissingHeader) + )); + let other = JournalEntry::Created { + world_id: "elsewhere".to_owned(), + version: 1, + }; + assert!(matches!( + run(&jsonl(&[other])), + Err(OwnerReportError::WrongWorld { found }) if found == "elsewhere" + )); + for version in [0, MAX_JOURNAL_VERSION + 1] { + assert!(matches!( + run(&jsonl(&[header(version)])), + Err(OwnerReportError::UnsupportedJournalVersion { version: v }) if v == version + )); + } + let mut bytes = jsonl(&[header(1)]); + bytes.extend(b"{\"entry\":\"no_such_entry\"}\n"); + assert!(matches!( + run(&bytes), + Err(OwnerReportError::Malformed { line: 2 }) + )); + assert!(matches!( + run(&jsonl(&[header(1), header(1)])), + Err(OwnerReportError::Malformed { line: 2 }) + )); + let mut bytes = jsonl(&[header(1)]); + bytes.extend(b"{\"entry\":\"execution_profile\",\"profile\":{}}\n"); + assert!(matches!( + run(&bytes), + Err(OwnerReportError::EntryNewerThanHeader { line: 2, .. }) + )); + let mut req = request(); + req.window.to_unix_ms = req.window.from_unix_ms - 1; + assert!(matches!( + project(Cursor::new(Vec::new()), &req, None), + Err(OwnerReportError::InvalidWindow) + )); +} + +#[test] +fn oversized_line_is_refused_not_buffered() { + let mut req = request(); + let bytes = jsonl(&[header(1), issued(1, None, None)]); + let second = serde_json::to_vec(&issued(1, None, None)).unwrap().len() + 1; + req.limits.max_line_bytes = second - 1; + assert!(matches!( + project(Cursor::new(bytes.clone()), &req, None), + Err(OwnerReportError::OversizedLine { line: 2 }) + )); + req.limits.max_line_bytes = second; + assert!(project(Cursor::new(bytes), &req, None).is_ok()); +} + +#[test] +fn schema_check_accepts_added_fields_and_refuses_other_majors() { + let report = run(&jsonl(&[header(1)])).unwrap(); + let mut json = serde_json::to_value(&report).unwrap(); + json["added_later"] = serde_json::json!(true); + assert_eq!(check_schema_version(&json), Ok(1)); + json["schema_version"] = serde_json::json!(2); + assert_eq!(check_schema_version(&json), Err(Some(2))); + let missing = serde_json::json!({"world_id": WORLD}); + assert_eq!(check_schema_version(&missing), Err(None)); +} + +proptest! { + /// Counts match a model of the same issue/revoke sequence, and the + /// serialized report is the same however often it is projected. + #[test] + fn counts_match_the_model(ops in prop::collection::vec((0u64..12, any::(), any::()), 0..60)) { + let mut entries = vec![header(1)]; + let mut model: std::collections::BTreeMap = std::collections::BTreeMap::new(); + for (id, is_revoke, delegated) in ops { + if is_revoke { + entries.push(revoked(id)); + if let Some(flags) = model.get_mut(&id) { + flags.1 = true; + } + } else { + entries.push(issued(id, delegated.then_some(100), None)); + model.entry(id).or_insert((delegated, false)); + } + } + let bytes = jsonl(&entries); + let report = run(&bytes).unwrap(); + prop_assert_eq!(report.joins.count, model.len() as u64); + prop_assert_eq!(report.joins.delegated, model.values().filter(|f| f.0).count() as u64); + prop_assert_eq!(report.joins.revoked, model.values().filter(|f| f.1).count() as u64); + prop_assert_eq!(report.joins.host_issued + report.joins.delegated, report.joins.count); + prop_assert!(report.joins.recent.len() <= ReportLimits::default().sample_limit); + let again = run(&bytes).unwrap(); + prop_assert_eq!(serde_json::to_string(&report).unwrap(), serde_json::to_string(&again).unwrap()); + } +}