commit b231e5fba2c38d78af0432d6fdde787f5bea52f3 parent eb1c8bdf69d3aa131888a6715f90ccdd6b2c281d Author: triesap <tyson@radroots.org> Date: Mon, 19 Oct 2026 23:08:39 +0000 storage_indexeddb: Retain original target observations - Bind normalized target facts to the original protected delivery attempt - Preserve first class details and optional time through late capture - Fence coherent reads and retention with actual complete-prefix transactions - Prove browser rollback, uncertainty, corruption and restart behavior Diffstat:
14 files changed, 805 insertions(+), 35 deletions(-)
diff --git a/contracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt b/contracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt @@ -23,6 +23,9 @@ impl radroots_storage_indexeddb::workspace::BrowserWorkspace pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::delivery_attempt(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_identity::key::PublicKey, radroots_transport::sink::DeliveryRequestId, radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage::command::delivery::DeliveryAttempt>, radroots_storage::command::OperationError> pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::prepare_delivery_attempt(&self, radroots_storage::command::delivery::DeliveryAttemptRequest, radroots_storage::workspace::AttachmentProof, core::option::Option<&radroots_storage::command::delivery::EnvelopeCandidate>) -> core::result::Result<radroots_storage::command::delivery::DeliveryAttemptOutcome, radroots_storage::command::OperationError> impl radroots_storage_indexeddb::workspace::BrowserWorkspace +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::delivery_observations(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_identity::key::PublicKey, radroots_transport::sink::DeliveryRequestId, radroots_storage::workspace::AttachmentProof) -> core::result::Result<alloc::vec::Vec<radroots_storage::command::observation::DeliveryObservation>, radroots_storage::command::OperationError> +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::record_delivery_observation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::AttachmentProof, radroots_storage::command::observation::DeliveryObservation) -> core::result::Result<radroots_storage::command::observation::DeliveryObservationOutcome, radroots_storage::command::OperationError> +impl radroots_storage_indexeddb::workspace::BrowserWorkspace pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::install_transition_and_outbox(&self, radroots_storage::command::installation::InstallationRequest, radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage::command::installation::InstallationOutcome, radroots_storage::command::OperationError> pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::operation_snapshot(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage::command::snapshot::OperationSnapshot>, radroots_storage::command::OperationError> impl core::fmt::Debug for radroots_storage_indexeddb::workspace::BrowserWorkspace diff --git a/contracts/architecture/decisions/browser_workspace.v2.json b/contracts/architecture/decisions/browser_workspace.v2.json @@ -1,7 +1,7 @@ { "schema_version": 1, "contract_id": "radroots.storage.browser_workspace.v2", - "state": "implemented_verified_delivery_frame_component", + "state": "implemented_verified_delivery_observation_component", "owner": "radroots_storage_indexeddb", "feature": "workspace", "target": "wasm32-unknown-unknown", @@ -151,9 +151,7 @@ "delivery_observation", "delivery_request_index" ], - "reserved_not_yet_implemented_families": [ - "delivery_observation" - ] + "reserved_not_yet_implemented_families": [] }, "signing_claim": { "phase": "S_claim", @@ -202,7 +200,9 @@ "install_transition_and_outbox", "operation_snapshot", "prepare_delivery_attempt", - "delivery_attempt" + "delivery_attempt", + "record_delivery_observation", + "delivery_observations" ], "delivery_frame": { "phase": "D_attempt", @@ -228,5 +228,22 @@ "actual_complete_prefix_fence": true, "provider_signing_or_network_inside_transaction": false, "delivery_observations_or_full_client_claim": false + }, + "delivery_observation": { + "phase": "D_observation", + "record_bytes_max": 16384, + "reports_max_per_operation": 2304, + "independent_classes": 6, + "append_only_first_original_details_and_optional_time": true, + "expected_context_binds_original_attempt_work_target_class_and_transaction": true, + "streamed_with_actual_attempt_frame": true, + "original_retained_proof_required": true, + "current_expiry_revocation_or_unavailable_clock_discards_obtained_fact": false, + "full_prefix_and_original_grant_checked_in_retention_transaction": true, + "provider_or_network_inside_transaction": false, + "query_current_access_required": true, + "retained_or_unknown_authorizes_dispatch": false, + "capture_only_owner_allows_fresh_authentication_or_commands": false, + "actual_remote_acceptance_or_full_client_claim": false } } diff --git a/crates/storage_indexeddb/README.md b/crates/storage_indexeddb/README.md @@ -89,7 +89,21 @@ Partial or missing predecessors, manifest, index and parts refuse replacement and false absence. Actual uncertain completion preserves the original operation, request and optional transaction anchor. Borrowed candidates remain caller-owned; accepted work retains its bounded copy through observer loss and cancelled close. -Delivery observations and a complete journal/client remain separate phases. +`record_delivery_observation` appends an already obtained normalized target +fact against the actual original attempt and retained proof. Each of six classes +has one immutable first observation per selected target and attempt, including +absent time and normalized details. Later classes append without erasing earlier +facts. Relay acceptance does not imply recipient delivery. Expiry, revocation +and an unavailable clock do not discard obtained evidence; capture-only opening +allows retention while denying current queries and fresh work. Independent v2 +contexts bind the original work, request, outer representation, transaction, +target and class. Each clear record is at most 16 KiB, with at most 2,304 reports +per operation. Reports decode while the original attempt frame is available, +without retaining every raw outer body. The complete prefix and original grant +are compared in the actual retention transaction. Uncertain completion returns +the original observation and stops admission. `delivery_observations` and coherent +snapshots require current access and do not dispatch. A complete journal/client +and browser transport execution remain separate phases. An owner-bound read snapshot witnesses at most 16,384 ordered opaque keys, lengths and SHA-256 digests, using a conservative 2 MiB scan reservation. Every @@ -136,8 +150,11 @@ fixture's lockfile, using an external output directory and the output name directory, that output directory, `chromium`, `firefox`, or `webkit`, and the preserved v1 fixture package directory for actual cross-version refusal checks. The optional final argument selects `delivery`, `delivery_limits`, -`delivery_corruption`, or `delivery_faults`; omission runs the existing base +`delivery_corruption`, `delivery_faults`, `observations`, `observation_faults`, +or `observation_corruption`; omission runs the existing base regressions. Additional profiles preserve that base's bounded deadline. +Synthetic normalized observation inputs prove concrete storage and linkage +behavior; they do not establish remote relay execution or acceptance. Both the page and dedicated worker import those generated bytes. The runner uses isolated loopback origins and bounds each expanded run to 180 seconds. This harness ceiling is not a product deadline or performance acceptance. Route diff --git a/crates/storage_indexeddb/src/workspace/address.rs b/crates/storage_indexeddb/src/workspace/address.rs @@ -12,6 +12,7 @@ pub(super) const EVIDENCE: u8 = 4; pub(super) const INSTALLATION: u8 = 5; pub(super) const PUBLICATION: u8 = 6; pub(super) const DELIVERY: u8 = 7; +pub(super) const OBSERVATION: u8 = 8; pub(super) const REQUEST_INDEX: u8 = 9; fn prefix_bytes(operation: OperationId) -> [u8; 16] { @@ -39,28 +40,30 @@ pub(super) fn fields(key: RecordKey) -> Result<(u8, u8, u8), OperationError> { let kind = bytes[16]; let recipient = bytes[17]; let part = bytes[20]; - let delivery = matches!(kind, DELIVERY | REQUEST_INDEX); + let delivery = matches!(kind, DELIVERY | OBSERVATION | REQUEST_INDEX); let ordinal = u16::from_be_bytes([bytes[18], bytes[19]]); - if bytes[21..].iter().any(|b| *b != 0) - || if delivery { - !(1..=192).contains(&ordinal) - } else { - ordinal != 0 - } - || match kind { - PREPARED => recipient != 0 || part > 4, - PLAN => recipient != 0 || part > 24, - CLAIM => recipient > 1 || part != 0, - EVIDENCE => recipient > 1 || part > 4, - INSTALLATION => recipient != 0 || part != 0, - PUBLICATION => recipient > 1 || part != 0, - DELIVERY => recipient > 1 || part > 24, - REQUEST_INDEX => recipient > 1 || part != 0, - // Later reserved families remain unsupported until their actual - // implementations and proving cohort land. Never ignore them. - _ => true, - } - { + if (if kind == OBSERVATION { + bytes[23..].iter().any(|b| *b != 0) || bytes[21] >= 16 || !(1..=6).contains(&bytes[22]) + } else { + bytes[21..].iter().any(|b| *b != 0) + }) || if delivery { + !(1..=192).contains(&ordinal) + } else { + ordinal != 0 + } || match kind { + PREPARED => recipient != 0 || part > 4, + PLAN => recipient != 0 || part > 24, + CLAIM => recipient > 1 || part != 0, + EVIDENCE => recipient > 1 || part > 4, + INSTALLATION => recipient != 0 || part != 0, + PUBLICATION => recipient > 1 || part != 0, + DELIVERY => recipient > 1 || part > 24, + OBSERVATION => recipient > 1 || part != 0, + REQUEST_INDEX => recipient > 1 || part != 0, + // Later reserved families remain unsupported until their actual + // implementations and proving cohort land. Never ignore them. + _ => true, + } { return Err(OperationError::RecoveryRequired); } Ok((kind, recipient, part)) @@ -78,7 +81,7 @@ pub(super) fn delivery_key( } pub(super) fn delivery_position(key: RecordKey) -> Result<(u8, u8, u16, u8), OperationError> { let (kind, recipient, part) = fields(key)?; - if !matches!(kind, DELIVERY | REQUEST_INDEX) { + if !matches!(kind, DELIVERY | OBSERVATION | REQUEST_INDEX) { return Err(OperationError::RecoveryRequired); } let bytes = key.as_bytes(); @@ -89,6 +92,25 @@ pub(super) fn delivery_position(key: RecordKey) -> Result<(u8, u8, u16, u8), Ope part, )) } +pub(super) fn observation_key( + operation: OperationId, + recipient: u8, + ordinal: u16, + target: u8, + kind: u8, +) -> RecordKey { + let mut bytes = *delivery_key(operation, OBSERVATION, recipient, ordinal, 0).as_bytes(); + bytes[21] = target; + bytes[22] = kind; + RecordKey::new(bytes) +} +pub(super) fn observation_position(key: RecordKey) -> Result<(u8, u16, u8, u8), OperationError> { + let (family, recipient, ordinal, _) = delivery_position(key)?; + if family != OBSERVATION { + return Err(OperationError::RecoveryRequired); + } + Ok((recipient, ordinal, key.as_bytes()[21], key.as_bytes()[22])) +} impl State { pub(super) async fn read_view( &self, diff --git a/crates/storage_indexeddb/src/workspace/delivery/graph.rs b/crates/storage_indexeddb/src/workspace/delivery/graph.rs @@ -8,9 +8,11 @@ use crate::workspace::{ installation::{Records, work_commitment}, retained, }; -use crate::{Mutation, ReadSnapshot}; +use crate::{Mutation, ReadSnapshot, RecordKey}; use radroots_domain::OperationId; -use radroots_storage::command::{DeliveryAttempt, DeliveryAttemptSummary, OperationError}; +use radroots_storage::command::{ + DeliveryAttempt, DeliveryAttemptSummary, DeliveryObservation, OperationError, +}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; use zeroize::Zeroizing; @@ -18,6 +20,8 @@ use zeroize::Zeroizing; pub(in crate::workspace) struct Graph { pub summaries: Vec<DeliveryAttemptSummary>, pub selected: Option<DeliveryAttempt>, + pub(super) selected_slot: Option<Slot>, + pub observations: Vec<DeliveryObservation>, pub slots: [u16; 2], } impl Graph { @@ -30,8 +34,22 @@ impl Graph { selected: Option<Selection<'_>>, ) -> Result<Self, OperationError> { let mut positions = BTreeMap::<(u8, u16), BTreeSet<(u8, u8)>>::new(); + let mut observations = BTreeMap::<(u8, u16), BTreeMap<(u8, u8), RecordKey>>::new(); + let mut observation_count = 0; for key in view.keys() { let (kind, _, _) = address::fields(key)?; + if kind == address::OBSERVATION { + let (recipient, ordinal, target, kind) = address::observation_position(key)?; + observation_count += 1; + if observation_count > 2304 { + return Err(OperationError::RecoveryRequired); + } + observations + .entry((recipient, ordinal)) + .or_default() + .insert((target, kind), key); + continue; + } if !matches!(kind, address::DELIVERY | address::REQUEST_INDEX) { continue; } @@ -47,6 +65,8 @@ impl Graph { let mut result = Self { summaries: Vec::with_capacity(positions.len()), selected: None, + selected_slot: None, + observations: Vec::with_capacity(observation_count), slots: [0; 2], }; let mut representations = BTreeMap::new(); @@ -106,6 +126,18 @@ impl Graph { if !parsed.matches(&report) { return Err(OperationError::RecoveryRequired); } + result.observations.extend( + super::observation::read( + state, + view, + slot, + &report, + observations + .remove(&(recipient, ordinal)) + .unwrap_or_default(), + ) + .await?, + ); routes(bound, participant, report.intent()) .map_err(|_| OperationError::RecoveryRequired)?; if representations @@ -124,9 +156,13 @@ impl Graph { && selected.event == Some(report.intent().event_id())) { result.selected = Some(report); + result.selected_slot = Some(slot); } } } + if !observations.is_empty() { + return Err(OperationError::RecoveryRequired); + } Ok(result) } } diff --git a/crates/storage_indexeddb/src/workspace/delivery/mod.rs b/crates/storage_indexeddb/src/workspace/delivery/mod.rs @@ -2,6 +2,8 @@ mod codec; mod graph; mod json; +mod observation; +mod observation_operations; mod operations; use super::State; @@ -95,6 +97,7 @@ pub(super) struct Selection<'a> { pub(super) struct Facts { pub snapshot: Option<OperationSnapshot>, pub selected: Option<DeliveryAttempt>, + selected_slot: Option<Slot>, pub original: Option<SealEvidence>, pub slots: [u16; 2], } @@ -127,12 +130,13 @@ impl State { .map(|snapshot| { snapshot .with_installation(installed.message, installed.work)? - .with_delivery(deliveries.summaries, Vec::new()) + .with_delivery(deliveries.summaries, deliveries.observations) }) .transpose()?; Ok(Facts { snapshot, selected: deliveries.selected, + selected_slot: deliveries.selected_slot, original: output, slots: deliveries.slots, }) diff --git a/crates/storage_indexeddb/src/workspace/delivery/observation.rs b/crates/storage_indexeddb/src/workspace/delivery/observation.rs @@ -0,0 +1,173 @@ +//! First normalized target facts under independent expected v2 contexts. +use super::{Slot, context, json}; +use crate::workspace::{State, address, crypto, journal::storage_error}; +use crate::{Mutation, ReadSnapshot, RecordKey}; +use core::num::NonZeroU64; +use radroots_domain::{EnvelopeEventId, TransactionId}; +use radroots_secrets::context::{ + EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId, +}; +use radroots_storage::command::{DeliveryAttempt, DeliveryObservation, OperationError}; +use radroots_transport::sink::DeliveryTargetReceipt; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use zeroize::Zeroizing; + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Wire<'a> { + version: u8, + work: [u8; 32], + #[serde(borrow)] + request: &'a str, + event: EnvelopeEventId, + envelope_digest: [u8; 32], + transaction: TransactionId, + target: DeliveryTargetReceipt, + kind: u8, + ordinal: u8, + observed_at: Option<NonZeroU64>, +} +fn scoped( + state: &State, + slot: Slot, + attempt: &DeliveryAttempt, + target: u8, + kind: u8, +) -> Result<EnvelopeContext, OperationError> { + let base = context(state, slot, 0, false)?; + let target = attempt + .intent() + .targets() + .targets() + .get(target as usize) + .ok_or(OperationError::RecoveryRequired)?; + let subject = Sha256::new() + .chain_update(b"radroots.browser.local_outbox.delivery_observation.context.v2\0") + .chain_update(base.authentication_digest()) + .chain_update(attempt.intent().request_id().as_str().as_bytes()) + .chain_update(attempt.transaction_id().as_bytes()) + .chain_update(attempt.envelope_digest()) + .chain_update(target.fingerprint().as_str().as_bytes()) + .chain_update([kind]) + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect::<String>(); + Ok(EnvelopeContext::new( + EnvelopePurpose::parse("radroots.browser.workspace.delivery_observation") + .map_err(|_| OperationError::InvalidCommand)?, + EnvelopeSubject::parse("delivery_observation", subject) + .map_err(|_| OperationError::InvalidCommand)?, + PayloadSchemaId::parse("radroots.browser.workspace.delivery_observation.v2") + .map_err(|_| OperationError::InvalidCommand)?, + )) +} +fn checked( + attempt: &DeliveryAttempt, + wire: Wire<'_>, + slot: Slot, + target: u8, + kind: u8, +) -> Result<DeliveryObservation, OperationError> { + if wire.version != 2 + || wire.work != slot.commitment + || wire.request != attempt.intent().request_id().as_str() + || wire.event != attempt.intent().event_id() + || &wire.envelope_digest != attempt.envelope_digest() + || wire.transaction != attempt.transaction_id() + || wire.kind != kind + || attempt.intent().targets().targets().get(target as usize) != Some(wire.target.target()) + { + return Err(OperationError::RecoveryRequired); + } + let value = DeliveryObservation::from_store_report(attempt, &wire.target, wire.observed_at) + .map_err(|_| OperationError::RecoveryRequired)?; + if value.kind().code() != kind || value.target_ordinal() != wire.ordinal { + return Err(OperationError::RecoveryRequired); + } + Ok(value) +} +pub(super) async fn read( + state: &State, + view: &ReadSnapshot, + slot: Slot, + attempt: &DeliveryAttempt, + positions: BTreeMap<(u8, u8), RecordKey>, +) -> Result<Vec<DeliveryObservation>, OperationError> { + let mut reports = Vec::with_capacity(positions.len()); + for ((target, kind), key) in positions { + let raw = state + .read_view_key(view, key) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let clear = crypto::open_bound( + state.provider.as_ref(), + &state.reference, + scoped(state, slot, attempt, target, kind)?, + &raw, + ) + .await?; + let report = clear.expose_secret(|raw| { + if raw.len() > 16384 || !json::bounded(raw, 32) { + return Err(OperationError::RecoveryRequired); + } + let wire: Wire<'_> = + serde_json::from_slice(raw).map_err(|_| OperationError::RecoveryRequired)?; + checked(attempt, wire, slot, target, kind) + })?; + reports.push(report); + } + Ok(reports) +} +pub(super) async fn protect( + state: &State, + slot: Slot, + attempt: &DeliveryAttempt, + value: &DeliveryObservation, +) -> Result<Mutation, OperationError> { + let target = attempt + .intent() + .targets() + .targets() + .iter() + .position(|target| target == value.target_receipt().target()) + .ok_or(OperationError::InvalidEvidence)? as u8; + let wire = Wire { + version: 2, + work: slot.commitment, + request: value.request_id().as_str(), + event: value.event_id(), + envelope_digest: *value.envelope_digest(), + transaction: attempt.transaction_id(), + target: value.target_receipt().clone(), + kind: value.kind().code(), + ordinal: value.target_ordinal(), + observed_at: value.observed_at_unix_ms(), + }; + let clear = + Zeroizing::new(serde_json::to_vec(&wire).map_err(|_| OperationError::InvalidEvidence)?); + if clear.len() > 16384 { + return Err(OperationError::InvalidEvidence); + } + let protected = crypto::seal_bound( + state.provider.as_ref(), + &state.reference, + scoped(state, slot, attempt, target, value.kind().code())?, + &clear, + ) + .await?; + Mutation::new( + address::observation_key( + slot.operation, + slot.recipient, + slot.ordinal, + target, + value.kind().code(), + ), + None, + Some(protected), + ) + .map_err(storage_error) +} diff --git a/crates/storage_indexeddb/src/workspace/delivery/observation_operations.rs b/crates/storage_indexeddb/src/workspace/delivery/observation_operations.rs @@ -0,0 +1,178 @@ +use super::{Selection, codec, observation}; +use crate::workspace::{ + BrowserWorkspace, WorkspaceError, + journal::{self, OperationChange}, + owned, +}; +use radroots_domain::{CommandDigest, OperationId, PublicKey}; +use radroots_storage::{ + command::{DeliveryObservation, DeliveryObservationOutcome, OperationError}, + workspace::{AttachmentProof, WorkspaceBinding}, +}; +use radroots_transport::sink::DeliveryRequestId; + +impl BrowserWorkspace { + /// Retains an already obtained target fact under the original proof and + /// actual attempt. This grants no permission to dispatch or retry. + pub async fn record_delivery_observation( + &self, + binding: WorkspaceBinding, + proof: AttachmentProof, + supplied: DeliveryObservation, + ) -> Result<DeliveryObservationOutcome, OperationError> { + let fallback = supplied.clone(); + let work = self.state.admit()?; + let state = self.state.clone(); + let result = owned(work, async move { + let input = binding.input().clone(); + let (grant, protected) = state.capture_grant(&input, &proof).await?; + let actual_work = supplied.work(); + let evidence = actual_work.evidence(); + let operation = evidence.operation_id(); + let view = state.read_view(operation).await?; + let t0 = state.operation_records(&view, operation).await?; + let facts = state + .delivery_facts( + &view, + operation, + Some(evidence.command_digest()), + &t0, + binding.observed_at(), + Some(Selection { + recipient: evidence.recipient(), + request: supplied.request_id(), + event: None, + retain_seal: false, + }), + ) + .await?; + let snapshot = facts.snapshot.ok_or(OperationError::InvalidEvidence)?; + radroots_storage::command::protected::same_binding( + snapshot.prepared().request().binding(), + &binding, + )?; + let attempt = facts.selected.ok_or(OperationError::InvalidEvidence)?; + if attempt.work() != actual_work { + return Err(OperationError::InvalidEvidence); + } + let checked = DeliveryObservation::from_store_report( + &attempt, + supplied.target_receipt(), + supplied.observed_at_unix_ms(), + )?; + if checked != supplied { + return Err(OperationError::InvalidEvidence); + } + let existing = snapshot.delivery_observations().iter().find(|value| { + value.work() == actual_work + && value.request_id() == supplied.request_id() + && value.target_receipt().target().fingerprint() + == supplied.target_receipt().target().fingerprint() + && value.kind() == supplied.kind() + }); + let retained = existing.cloned().unwrap_or(supplied); + let extra = if existing.is_some() { + Vec::new() + } else { + vec![ + observation::protect( + &state, + facts + .selected_slot + .ok_or(OperationError::RecoveryRequired)?, + &attempt, + &retained, + ) + .await?, + ] + }; + let batch = journal::mutations(protected, operation, t0, None, extra)?; + let active = state.active()?; + match state + .checked_batch(batch, view, move || { + if !active.get() { + return Err(WorkspaceError::Closed.into()); + } + grant.authenticate_retained_capture(&input, &proof)?; + Ok(()) + }) + .await + { + Ok(()) => Ok(DeliveryObservationOutcome::Committed(retained)), + Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { + state.stop(); + Ok(DeliveryObservationOutcome::Unknown(retained)) + } + Err(error) => Err(error), + } + }) + .await; + match result { + Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { + self.state.stop(); + Ok(DeliveryObservationOutcome::Unknown(fallback)) + } + other => other, + } + } + + /// Queries original target facts under current access without dispatching. + pub async fn delivery_observations( + &self, + binding: WorkspaceBinding, + operation: OperationId, + digest: CommandDigest, + recipient: PublicKey, + request: DeliveryRequestId, + proof: AttachmentProof, + ) -> Result<Vec<DeliveryObservation>, OperationError> { + if !codec::valid_request(request.as_str()) { + return Err(OperationError::InvalidCommand); + } + let work = self.state.admit()?; + let state = self.state.clone(); + owned(work, async move { + let access = state.operation_access(&binding, proof).await?; + let view = state.read_view(operation).await?; + let t0 = state.operation_records(&view, operation).await?; + let facts = state + .delivery_facts( + &view, + operation, + Some(digest), + &t0, + access.binding.observed_at(), + Some(Selection { + recipient, + request: &request, + event: None, + retain_seal: false, + }), + ) + .await?; + let result = match facts.snapshot { + Some(snapshot) => { + radroots_storage::command::protected::same_binding( + snapshot.prepared().request().binding(), + &binding, + )?; + snapshot + .delivery_observations() + .iter() + .filter(|value| { + value.work().evidence().recipient() == recipient + && value.request_id() == &request + }) + .cloned() + .collect() + } + None => Vec::new(), + }; + state + .check_operation(access, operation, OperationChange::observe(t0), view) + .await?; + Ok(result) + }) + .await + } +} diff --git a/crates/storage_indexeddb/tests/browser/observations.mjs b/crates/storage_indexeddb/tests/browser/observations.mjs @@ -0,0 +1,100 @@ +import assert from 'node:assert/strict'; + +export async function runObservations(page,profile) { + const result=await page.evaluate(async profile=>{ + const {default:init,WorkspaceFixture}=await import('./fixture.js');await init(); + const tests=[],passed=name=>{tests.push(name);console.log('PASS '+name);}; + const same=(a,b)=>{if(JSON.stringify(a)!==JSON.stringify(b))throw Error('assertion mismatch: '+JSON.stringify(a)+' / '+JSON.stringify(b));}; + const rejects=async(fn,code)=>{try{await fn();}catch(error){if(String(error)!==code)throw Error('expected '+code+', received '+String(error));return;}throw Error('expected refusal: '+code);}; + const kb=key=>Array.from(new Uint8Array(key)); + const rawOpen=r=>new Promise((resolve,reject)=>{const req=indexedDB.open(r.namespace,1);req.onupgradeneeded=()=>req.transaction.abort();req.onsuccess=()=>resolve(req.result);req.onerror=reject;}); + const rows=async r=>{const db=await rawOpen(r);try{return await new Promise((resolve,reject)=>{const tx=db.transaction('records','readonly'),store=tx.objectStore('records');let keys,values;store.getAllKeys().onsuccess=e=>keys=e.target.result;store.getAll().onsuccess=e=>values=e.target.result;tx.oncomplete=()=>resolve({keys,values});tx.onabort=reject;});}finally{db.close();}}; + const change=async(r,fn)=>{const db=await rawOpen(r);try{await new Promise((resolve,reject)=>{const tx=db.transaction('records','readwrite');fn(tx.objectStore('records'));tx.oncomplete=resolve;tx.onabort=reject;});}finally{db.close();}}; + const sameRows=(a,b)=>{same(a.keys.map(kb),b.keys.map(kb));same(a.values.map(kb),b.values.map(kb));}; + const restore=async(r,before)=>change(r,store=>{store.clear();before.keys.forEach((key,i)=>store.put(before.values[i],key));}); + const open=(r,capture=false)=>(capture?WorkspaceFixture.open_capture:WorkspaceFixture.open)(r.n,new Uint8Array(r.fingerprint),new Uint8Array(r.selection),new Uint8Array(r.proof)); + const receipt=(owner,n)=>({n,fingerprint:Array.from(owner.fingerprint()),selection:Array.from(owner.selection()),proof:Array.from(owner.proof()),namespace:owner.data_namespace()}); + const setup=async(n,selection=1)=>{const owner=await WorkspaceFixture.create(n+1);await owner.admit(n,false);await owner.bind_plan(n,await owner.new_delivery_plan(n));const seal=await owner.obtain(n,0,false);await owner.capture(seal);await owner.install(n);const envelope=await owner.envelope(n,0,0);await owner.store_envelope(n,1,selection,0,envelope);return{owner,envelope,receipt:receipt(owner,n+1)};}; + const query=async(owner,n,id=1)=>JSON.parse(await owner.query_observations(n,0,id)); + const retain=async(s,original)=>JSON.parse(await s.owner.retain_observation(original,false)); + const put=IDBObjectStore.prototype.put,add=IDBObjectStore.prototype.add,abort=IDBTransaction.prototype.abort; + const reset=()=>{IDBObjectStore.prototype.put=put;IDBTransaction.prototype.abort=abort;}; + const inject=(namespace,target,redirect)=>{ + IDBObjectStore.prototype.put=function(bytes,at){if(this.transaction.db.name===namespace&&JSON.stringify(kb(at))===JSON.stringify(kb(target))){const req=add.call(this,bytes,redirect??at);req.addEventListener('error',event=>event.preventDefault());return req;}return put.call(this,bytes,at);}; + IDBTransaction.prototype.abort=function(){if(this.db.name===namespace)return;return abort.call(this);}; + }; + try { + if(profile==='observations') { + const n=230,s=await setup(n,3),empty=await rows(s.receipt);same(await query(s.owner,n),[]);sameRows(await rows(s.receipt),empty); + passed('actual target observation query preserves absence without inventing an acknowledgement'); + const first=await s.owner.observation(n,0,1,0,1,0),later=await s.owner.observation(n,0,1,0,1,1000100),expected=JSON.parse(first.original()); + await rejects(()=>s.owner.retain_observation(first,true),'unauthorized');sameRows(await rows(s.receipt),empty); + const saved=await retain(s,first);same(saved.kind,'committed');same(saved.report,expected);same(expected.at,null);same(expected.ordinal,1);same(expected.attempted,true);same(await query(s.owner,n),[expected]); + passed('actual observation commit requires original proof and preserves exact linkage, absent time and normalized details'); + const before=await rows(s.receipt),random=Crypto.prototype.getRandomValues; + try{Crypto.prototype.getRandomValues=()=>{throw Error('exact observation replay used new entropy');};same((await retain(s,later)).report,expected);}finally{Crypto.prototype.getRandomValues=random;} + sameRows(await rows(s.receipt),before); + passed('first original class observation remains byte-identical when replay supplies a different time and details'); + for(const kind of [2,3,4,5,6]){const value=await s.owner.observation(n,0,1,0,kind,1000000+kind);same((await retain(s,value)).report,JSON.parse(value.original()));} + const classes=await query(s.owner,n);same(classes.length,6);same(classes.map(value=>value.class),[1,2,3,4,5,6]);same(classes[5].attempted,false);same(classes[0],expected); + passed('all six actual protected outcome classes append independently without erasing earlier acceptance'); + const accepted=await s.owner.observation(n,0,1,1,1,1000100);await retain(s,accepted);const snapshot=JSON.parse(await s.owner.snapshot(n));same(snapshot.observations,7);same(snapshot.deliveries,1);same(snapshot.publications.length,1); + passed('coherent actual snapshot retains per-target observations alongside the original message, work and D attempt'); + const alternate=s.owner.alternate_envelope(s.envelope),stable=await rows(s.receipt);same(alternate.event(),s.envelope.event());if(alternate.raw()===s.envelope.raw())throw Error('alternate fixture signature unchanged');await rejects(()=>s.owner.store_envelope(n,2,1,0,alternate),'idempotency_conflict');sameRows(await rows(s.receipt),stable); + passed('independently valid alternate signed outer representation with the same event ID cannot replace retained bytes'); + const golden=await query(s.owner,n);await s.owner.close();return{tests,receipt:s.receipt,operation:n,index:0,id:1,golden}; + } + if(profile==='observation_faults') { + const n=232,s=await setup(n),original=await s.owner.observation(n,0,1,0,2,0),expected=JSON.parse(original.original()),before=await rows(s.receipt); + let written=false; + try{IDBObjectStore.prototype.put=function(bytes,key){const req=put.call(this,bytes,key);if(this.transaction.db.name===s.receipt.namespace&&kb(key)[16]===8)req.addEventListener('success',()=>{written=true;this.transaction.abort();},{once:true});return req;};await rejects(()=>retain(s,original),'storage_failure');}finally{reset();} + same(written,true);sameRows(await rows(s.receipt),before);same((await retain(s,original)).report,expected); + passed('actual observation write success followed by abort rolls back and preserves the caller original for retry'); + const late=await s.owner.observation(n,0,1,0,3,1000200),captureOnly=await s.owner.observation(n,0,1,0,5,0);s.owner.set_time(2500);same((await retain(s,late)).kind,'committed');await rejects(()=>s.owner.query_observation_scope(late),'grant_expired');await s.owner.close(); + s.owner=await open(s.receipt,true);s.owner.set_time(0);same((await retain(s,captureOnly)).report,JSON.parse(captureOnly.original()));const lateUnknown=await s.owner.retain_observation(late,false);same(JSON.parse(lateUnknown).report,JSON.parse(late.original()));await rejects(()=>s.owner.query_observation_scope(late),'unauthorized');await rejects(()=>s.owner.authenticate(),'unauthorized');await s.owner.close(); + passed('expired and unavailable-clock capture-only owners retain original obtained target evidence without fresh access'); + const revokedN=234,revoked=await setup(revokedN),observed=await revoked.owner.observation(revokedN,0,1,0,4,1000300);await revoked.owner.revoke();same((await retain(revoked,observed)).kind,'committed');await revoked.owner.close();revoked.owner=await open(revoked.receipt,true);same((await retain(revoked,observed)).report,JSON.parse(observed.original()));await rejects(()=>revoked.owner.authenticate(),'unauthorized');await revoked.owner.close(); + passed('revocation cannot discard obtained evidence authenticated against the actual original D attempt'); + const unknownN=236,unknown=await setup(unknownN),value=await unknown.owner.observation(unknownN,0,1,0,5,0),all=await rows(unknown.receipt),unchanged=all.keys.find(k=>kb(k)[16]===1&&kb(k)[20]===1);let result; + try{result=JSON.parse(await unknown.owner.retain_observation_unknown(value,()=>inject(unknown.receipt.namespace,unchanged)));}finally{reset();} + same(result.kind,'unknown');same(result.report,JSON.parse(value.original()));await unknown.owner.close();let reopened=await open(unknown.receipt);same(await query(reopened,unknownN),[result.report]);await reopened.close(); + passed('actual unexpected transaction completion returns the original uncertain observation and reconciliation reads the actual retained fact'); + const partialN=242,partial=await setup(partialN),partialValue=await partial.owner.observation(partialN,0,1,0,5,0),partialRows=await rows(partial.receipt),old=partialRows.keys.find(k=>kb(k)[16]===1&&kb(k)[20]===1),target=new Uint8Array(partialRows.keys.find(k=>kb(k)[16]===7&&kb(k)[20]===0));target[16]=8;target[21]=0;target[22]=5; + try{result=JSON.parse(await partial.owner.retain_observation_unknown(partialValue,()=>inject(partial.receipt.namespace,target,old)));}finally{reset();} + same(result.kind,'unknown');same(result.report,JSON.parse(partialValue.original()));await partial.owner.close();reopened=await open(partial.receipt);same(await query(reopened,partialN),[]);same(JSON.parse(await reopened.retain_observation(partialValue,false)).report,result.report);same(await query(reopened,partialN),[result.report]);await reopened.close(); + passed('actual incomplete observation retention stays unknown until exact query and recapture confirm the caller original without redispatch'); + const cancelN=238,cancel=await setup(cancelN),cancelled=await cancel.owner.observation(cancelN,0,1,0,6,0),golden=JSON.parse(cancelled.original());cancel.owner.abandon_observation(cancelled);cancelled.free();cancel.owner.abandon_close();await cancel.owner.close();reopened=await open(cancel.receipt);same(await query(reopened,cancelN),[golden]);await reopened.close(); + passed('accepted observation owns bounded input through lost observer, original disposal and cancelled close'); + return{tests}; + } + if(profile==='observation_corruption') { + const n=240,s=await setup(n);await s.owner.store_envelope(n,2,2,16,s.envelope);const a=await s.owner.observation(n,0,1,0,1,0),b=await s.owner.observation(n,0,2,1,2,1000000);await retain(s,a);await retain(s,b); + await rejects(()=>s.owner.observation(n,0,1,1,1,0),'invalid_evidence');await rejects(()=>s.owner.observation(n,0,1,0,7,0),'invalid_evidence');await s.owner.close();const stable=await rows(s.receipt); + passed('shared checked normalized data refuses unselected targets and recipient-delivered meaning for relay outcomes'); + const found=(family,ordinal)=>stable.keys.find(k=>kb(k)[16]===family&&kb(k)[19]===ordinal),observation=found(8,1),other=found(8,2),original=stable.values[stable.keys.indexOf(observation)]; + for(const mode of ['tampered','foreign_attempt','unselected_target','changed_class','missing_D','missing_T2','missing_S']) { + await change(s.receipt,store=>{ + if(mode==='tampered'){const bytes=new Uint8Array(original);bytes[bytes.length-1]^=1;store.put(bytes,observation);} + if(mode==='foreign_attempt')store.put(stable.values[stable.keys.indexOf(other)],observation); + if(mode==='unselected_target'||mode==='changed_class'){const key=new Uint8Array(observation);key[mode==='changed_class'?22:21]=mode==='changed_class'?2:1;store.delete(observation);store.put(original,key);} + if(mode==='missing_D')stable.keys.filter(k=>[7,9].includes(kb(k)[16])&&kb(k)[19]===1).forEach(k=>store.delete(k)); + if(mode==='missing_T2'||mode==='missing_S')stable.keys.filter(k=>(mode==='missing_T2'?[5,6]:[3,4]).includes(kb(k)[16])).forEach(k=>store.delete(k)); + }); + const damaged=await rows(s.receipt);let owner=await open(s.receipt);await rejects(()=>query(owner,n),'recovery_required');await owner.close();owner=await open(s.receipt);await rejects(()=>owner.install(n),'recovery_required');await owner.close();owner=await open(s.receipt);await rejects(()=>owner.retain_observation(a,false),'recovery_required');await owner.close();if(mode==='missing_S'){owner=await open(s.receipt);await rejects(()=>owner.claim(n,0),'recovery_required');await owner.close();}sameRows(await rows(s.receipt),damaged);await restore(s.receipt,stable); + passed('actual '+mode+' observation damage refuses query, replacement and capture while preserving damaged bytes'); + } + return{tests}; + } + throw Error('unknown observation profile'); + } finally {reset();} + },profile); + if(result.receipt) { + const message={kind:'observation_query',...result.receipt,operation:result.operation,index:result.index,id:result.id}; + const worker=await page.evaluate(message=>new Promise((resolve,reject)=>{const worker=new Worker('./worker.js',{type:'module'});worker.onmessage=e=>{if(e.data.ready){worker.postMessage(message);return;}worker.terminate();resolve(e.data);};worker.onerror=error=>{worker.terminate();reject(Error(error.message));};}),message); + assert.deepEqual(worker,{reports:result.golden});result.tests.push('actual worker termination and fresh WASM retain original target observations'); + await page.reload(); + const reports=await page.evaluate(async r=>{const{default:init,WorkspaceFixture}=await import('./fixture.js');await init();const owner=await WorkspaceFixture.open(r.receipt.n,new Uint8Array(r.receipt.fingerprint),new Uint8Array(r.receipt.selection),new Uint8Array(r.receipt.proof));const reports=JSON.parse(await owner.query_observations(r.operation,r.index,r.id));await owner.close();return reports;},result); + assert.deepEqual(reports,result.golden);result.tests.push('actual page and WASM restart preserve immutable original outcome classes, details and optional times');delete result.receipt;delete result.golden; + } + return result; +} diff --git a/crates/storage_indexeddb/tests/browser/run.mjs b/crates/storage_indexeddb/tests/browser/run.mjs @@ -4,6 +4,7 @@ import { createServer } from 'node:http'; import { readFile } from 'node:fs/promises'; import { resolve, sep } from 'node:path'; import { runDelivery } from './delivery.mjs'; +import { runObservations } from './observations.mjs'; // Caller supplies its installed Playwright package and an external generated // WASM directory. No dependency installation or generated bytes live here. @@ -11,7 +12,7 @@ const [moduleRoot, packageDir, engine = 'chromium', legacyPackageDir, profile = assert(moduleRoot && packageDir && legacyPackageDir, 'usage: node run.mjs PLAYWRIGHT_PACKAGE WASM_DIRECTORY ENGINE V1_WASM_DIRECTORY'); const playwright = createRequire(resolve(moduleRoot, 'package.json'))('playwright'); assert(['chromium','firefox','webkit'].includes(engine)); -assert(['base','delivery','delivery_limits','delivery_faults','delivery_corruption'].includes(profile)); +assert(['base','delivery','delivery_limits','delivery_faults','delivery_corruption','observations','observation_faults','observation_corruption'].includes(profile)); const root = resolve(packageDir); const legacyRoot = resolve(legacyPackageDir); const server = createServer(async (req,res) => { @@ -35,6 +36,7 @@ const server = createServer(async (req,res) => { if(event.data?.kind==='issuance_query'){const m=event.data;const owner=await WorkspaceFixture.open(m.n,new Uint8Array(m.fingerprint),new Uint8Array(m.selection),new Uint8Array(m.proof));const claim=Array.from(await owner.attempt(190,0)),seal=Array.from(await owner.captured(190,0));await owner.close();self.postMessage({claim,seal});return;} if(event.data?.kind==='installation_query'){const m=event.data;const owner=await WorkspaceFixture.open(m.n,new Uint8Array(m.fingerprint),new Uint8Array(m.selection),new Uint8Array(m.proof));const state=JSON.parse(await owner.snapshot(200));await owner.close();self.postMessage({state});return;} if(event.data?.kind==='delivery_query'){const m=event.data;const owner=await WorkspaceFixture.open(m.n,new Uint8Array(m.fingerprint),new Uint8Array(m.selection),new Uint8Array(m.proof));const report=JSON.parse(await owner.query_envelope(m.operation,m.index,m.id));await owner.close();self.postMessage({report});return;} + if(event.data?.kind==='observation_query'){const m=event.data;const owner=await WorkspaceFixture.open(m.n,new Uint8Array(m.fingerprint),new Uint8Array(m.selection),new Uint8Array(m.proof));const reports=JSON.parse(await owner.query_observations(m.operation,m.index,m.id));await owner.close();self.postMessage({reports});return;} if(event.data?.kind==='persistent_create'){const provider=await Persistent.create(90);const fingerprint=provider.fingerprint();const encoded=await provider.protect(new Uint8Array([90,91,92]));await provider.close();self.postMessage({fingerprint:Array.from(fingerprint),encoded:Array.from(encoded)});return;} if(event.data?.kind==='persistent_open'){const provider=await Persistent.open(90,new Uint8Array(event.data.fingerprint));const plain=await provider.reveal(new Uint8Array(event.data.encoded));await provider.close();self.postMessage({plain:Array.from(plain)});return;} await protected_round_trip(79);const db=await Fixture.open(77,true);await db.write(1,undefined,new Uint8Array([77]));await db.close();const again=await Fixture.open(77,false);const value=await again.read(1);await again.close();self.postMessage({value:Array.from(value)});}catch(error){self.postMessage({error:String(error)});}}; @@ -714,7 +716,7 @@ try { const issuanceRestart=await page.evaluate(async r=>{const {default:init,WorkspaceFixture}=await import('./fixture.js');await init();const owner=await WorkspaceFixture.open(r.n,new Uint8Array(r.fingerprint),new Uint8Array(r.selection),new Uint8Array(r.proof));const claim=Array.from(await owner.attempt(190,0)),seal=Array.from(await owner.captured(190,0));await owner.close();return {claim,seal};},result.issuance);assert.deepEqual(issuanceRestart,{claim:result.issuance.originalClaim,seal:result.issuance.originalSeal});result.tests.push('original claim and captured signature survive actual page and WASM restart');delete result.issuance; console.log(JSON.stringify({engine,version:browser.version(),...result})); } else { - const result=await runDelivery(page,profile); + const result=await(profile.startsWith('observation')?runObservations(page,profile):runDelivery(page,profile)); console.log(JSON.stringify({engine,version:browser.version(),profile,...result})); } } finally { diff --git a/crates/storage_indexeddb/tests/browser/src/lib.rs b/crates/storage_indexeddb/tests/browser/src/lib.rs @@ -10,7 +10,7 @@ pub use protected::protected_round_trip; mod persistent; pub use persistent::Persistent; mod workspace; -pub use workspace::{ObtainedEnvelope, ObtainedSeal, WorkspaceFixture}; +pub use workspace::{ObtainedEnvelope, ObtainedObservation, ObtainedSeal, WorkspaceFixture}; mod snapshot; pub use snapshot::Frozen; diff --git a/crates/storage_indexeddb/tests/browser/src/workspace.rs b/crates/storage_indexeddb/tests/browser/src/workspace.rs @@ -2,10 +2,12 @@ mod delivery; mod installation; mod issuance; +mod observations; mod plans; pub use delivery::ObtainedEnvelope; use futures::FutureExt; pub use issuance::ObtainedSeal; +pub use observations::ObtainedObservation; use radroots_domain::{ ActorRole, CommandContextData, Coverage, OperationId, PublicKey, UnixSeconds, WorkspaceId, }; diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/delivery.rs b/crates/storage_indexeddb/tests/browser/src/workspace/delivery.rs @@ -100,6 +100,38 @@ impl WorkspaceFixture { } #[wasm_bindgen] impl WorkspaceFixture { + pub fn alternate_envelope( + &self, + original: &ObtainedEnvelope, + ) -> Result<ObtainedEnvelope, JsValue> { + let event = nostr::Event::from_json(original.candidate.raw_json()).unwrap(); + let context = nostr::secp256k1::Secp256k1::new(); + let mut scalar = [0; 32]; + scalar[31] = 3; + let keys = + nostr::Keys::new_with_ctx(&context, nostr::SecretKey::from_slice(&scalar).unwrap()); + let alternate = nostr::UnsignedEvent { + id: Some(event.id), + pubkey: event.pubkey, + created_at: event.created_at, + kind: event.kind, + tags: event.tags.clone(), + content: event.content.clone(), + } + .sign_with_ctx(&context, &mut BrowserRng, &keys) + .unwrap(); + alternate.verify_with_ctx(&context).unwrap(); + assert_eq!(alternate.id, event.id); + assert_ne!(alternate.as_json(), event.as_json()); + Ok(ObtainedEnvelope { + candidate: EnvelopeCandidate::from_obtained( + original.candidate.work(), + &alternate.as_json(), + &scalar, + ) + .map_err(|e| JsValue::from_str(e.code()))?, + }) + } pub async fn envelope(&self, n: u8, index: u8, mode: u8) -> Result<ObtainedEnvelope, JsValue> { let request = self.request(n, false).await?; let snapshot = self diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/observations.rs b/crates/storage_indexeddb/tests/browser/src/workspace/observations.rs @@ -0,0 +1,184 @@ +//! Synthetic normalized facts prove storage linkage, not remote execution. +use super::{WorkspaceFixture, copied}; +use core::num::NonZeroU64; +use futures::FutureExt; +use radroots_domain::OperationId; +use radroots_storage::{ + command::{DeliveryObservation, DeliveryObservationOutcome}, + workspace::{AttachmentProof, WorkspaceBinding}, +}; +use radroots_transport::{ + outcome::{DeliveryOutcome, Retryability}, + sink::{DeliveryRequestId, DeliveryTargetReceipt}, +}; +use serde_json::{Value, json}; +use wasm_bindgen::prelude::*; + +fn summary(value: &DeliveryObservation) -> Value { + let target = value.target_receipt(); + let outcome = target.outcome(); + json!({"request":value.request_id().as_str(),"event":value.event_id().to_string(),"digest":hex::encode(value.envelope_digest()),"recipient":value.work().evidence().recipient().to_string(),"capture":value.work().evidence().transaction_id().to_string(),"work":value.work().transaction_id().to_string(),"target":target.target().uri().as_str(),"fingerprint":target.target().fingerprint().as_str(),"attempted":target.was_attempted(),"class":value.kind().code(),"ordinal":value.target_ordinal(),"at":value.observed_at_unix_ms().map(|t|t.get()),"code":outcome.code(),"message":outcome.message()}) +} +fn result(value: DeliveryObservationOutcome) -> String { + match value { + DeliveryObservationOutcome::Committed(value) => { + json!({"kind":"committed","report":summary(&value)}) + } + DeliveryObservationOutcome::Unknown(value) => { + json!({"kind":"unknown","report":summary(&value)}) + } + } + .to_string() +} +#[wasm_bindgen] +pub struct ObtainedObservation { + binding: WorkspaceBinding, + value: DeliveryObservation, +} +#[wasm_bindgen] +impl ObtainedObservation { + pub fn original(&self) -> String { + summary(&self.value).to_string() + } +} +#[wasm_bindgen] +impl WorkspaceFixture { + pub async fn observation( + &self, + n: u8, + index: u8, + id: u8, + target: u8, + kind: u8, + time: u32, + ) -> Result<ObtainedObservation, JsValue> { + let request = self.request(n, false).await?; + let mut recipients = vec![self.input.participant(), request.command().peer()]; + recipients.sort_unstable(); + recipients.dedup(); + let attempt = self + .owner + .delivery_attempt( + request.binding().clone(), + OperationId::from_bytes([n; 32]), + request.command().digest(), + recipients[index as usize], + DeliveryRequestId::parse(hex::encode([id; 32])).unwrap(), + copied(&self.proof), + ) + .await + .map_err(|e| JsValue::from_str(e.code()))? + .ok_or(JsValue::from_str("missing_attempt"))?; + let endpoint = attempt.intent().targets().targets()[target as usize].clone(); + let outcome = match kind { + 1 => DeliveryOutcome::accepted(), + 2 => DeliveryOutcome::rejected(), + 7 => DeliveryOutcome::delivered(), + _ => DeliveryOutcome::failed(Retryability::Retryable).unwrap(), + }; + let code = match kind { + 3 => "timeout", + 4 => "disconnected", + _ => "synthetic_result", + }; + let outcome = outcome + .with_detail(code, format!("synthetic normalized detail {time}")) + .unwrap(); + let report = if kind == 6 { + DeliveryTargetReceipt::skipped(endpoint, outcome).unwrap() + } else { + DeliveryTargetReceipt::attempted(endpoint, outcome) + }; + let value = + DeliveryObservation::from_store_report(&attempt, &report, NonZeroU64::new(time as u64)) + .map_err(|e| JsValue::from_str(e.code()))?; + Ok(ObtainedObservation { + binding: request.binding().clone(), + value, + }) + } + pub async fn retain_observation( + &self, + original: &ObtainedObservation, + wrong_proof: bool, + ) -> Result<String, JsValue> { + let proof = if wrong_proof { + AttachmentProof::from_protected_input(&[0x31; 32]).unwrap() + } else { + copied(&self.proof) + }; + self.owner + .record_delivery_observation(original.binding.clone(), proof, original.value.clone()) + .await + .map(result) + .map_err(|e| JsValue::from_str(e.code())) + } + pub async fn retain_observation_unknown( + &self, + original: &ObtainedObservation, + hook: js_sys::Function, + ) -> Result<String, JsValue> { + hook.call0(&JsValue::NULL)?; + self.owner + .record_delivery_observation( + original.binding.clone(), + copied(&self.proof), + original.value.clone(), + ) + .await + .map(result) + .map_err(|e| JsValue::from_str(e.code())) + } + pub fn abandon_observation(&self, original: &ObtainedObservation) -> Result<(), JsValue> { + if self + .owner + .record_delivery_observation( + original.binding.clone(), + copied(&self.proof), + original.value.clone(), + ) + .now_or_never() + .is_some() + { + return Err(JsValue::from_str("unexpected_immediate_observation")); + } + Ok(()) + } + pub async fn query_observations(&self, n: u8, index: u8, id: u8) -> Result<String, JsValue> { + let request = self.request(n, false).await?; + let mut recipients = vec![self.input.participant(), request.command().peer()]; + recipients.sort_unstable(); + recipients.dedup(); + self.owner + .delivery_observations( + request.binding().clone(), + OperationId::from_bytes([n; 32]), + request.command().digest(), + recipients[index as usize], + DeliveryRequestId::parse(hex::encode([id; 32])).unwrap(), + copied(&self.proof), + ) + .await + .map(|values| values.iter().map(summary).collect::<Vec<_>>()) + .map(|v| json!(v).to_string()) + .map_err(|e| JsValue::from_str(e.code())) + } + pub async fn query_observation_scope( + &self, + original: &ObtainedObservation, + ) -> Result<String, JsValue> { + let evidence = original.value.work().evidence(); + self.owner + .delivery_observations( + original.binding.clone(), + evidence.operation_id(), + evidence.command_digest(), + evidence.recipient(), + original.value.request_id().clone(), + copied(&self.proof), + ) + .await + .map(|values| json!(values.iter().map(summary).collect::<Vec<_>>()).to_string()) + .map_err(|e| JsValue::from_str(e.code())) + } +}