holochain_types 0.8.0-dev.1

Holochain common types
Documentation
//! Types for agents chain activity

use holo_hash::AgentPubKey;
use holo_hash::{ActionHash, HasHash};
use holochain_serialized_bytes::prelude::*;
use holochain_zome_types::prelude::{
    ActionHashed, AgentActivityStatus, ChainStatus, HighestObserved, Record, SignedWarrant,
};

/// An agents chain records returned from a agent_activity_query
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, SerializedBytes)]
pub struct AgentActivityResponse {
    /// The agent this activity is for
    pub agent: AgentPubKey,
    /// Valid actions on this chain.
    pub valid_activity: ChainItems,
    /// Actions that were rejected by the agent activity
    /// authority and therefor invalidate the chain.
    pub rejected_activity: ChainItems,
    /// The status of this chain.
    pub status: ChainStatus,
    /// The highest chain action that has
    /// been observed by this authority.
    pub highest_observed: Option<HighestObserved>,
    /// Any warrants at the basis of this agent.
    pub warrants: Vec<SignedWarrant>,
}

impl AgentActivityResponse {
    /// Whether this response carries no information about the agent's chain.
    ///
    /// An empty response means the authority holds nothing for the agent:
    /// no valid or rejected activity, an [`ChainStatus::Empty`] status, no
    /// highest observed action and no warrants. Callers that aggregate
    /// responses from several authorities use this to tell "I hold
    /// nothing" answers apart from answers that contribute data.
    pub fn is_empty(&self) -> bool {
        self.valid_activity.is_empty()
            && self.rejected_activity.is_empty()
            && matches!(self.status, ChainStatus::Empty)
            && self.highest_observed.is_none()
            && self.warrants.is_empty()
    }

    /// Convert an empty response to a different type.
    pub fn from_empty(other: AgentActivityResponse) -> Self {
        let convert_activity = |items: &ChainItems| match items {
            ChainItems::Full(_) => ChainItems::Full(Vec::with_capacity(0)),
            ChainItems::Hashes(_) => ChainItems::Hashes(Vec::with_capacity(0)),
            ChainItems::NotRequested => ChainItems::NotRequested,
        };
        AgentActivityResponse {
            agent: other.agent,
            valid_activity: convert_activity(&other.valid_activity),
            rejected_activity: convert_activity(&other.rejected_activity),
            status: ChainStatus::Empty,
            highest_observed: other.highest_observed,
            warrants: other.warrants,
        }
    }

    /// Convert to a status only response.
    pub fn status_only(other: AgentActivityResponse) -> Self {
        AgentActivityResponse {
            agent: other.agent,
            valid_activity: ChainItems::NotRequested,
            rejected_activity: ChainItems::NotRequested,
            status: other.status,
            highest_observed: other.highest_observed,
            warrants: other.warrants,
        }
    }

    /// Convert to a [ChainItems::Hashes] response.
    pub fn hashes_only(other: AgentActivityResponse) -> Self {
        let convert_activity = |items: ChainItems| match items {
            ChainItems::Full(records) => ChainItems::Hashes(
                records
                    .into_iter()
                    .map(|r| (r.action().action_seq(), r.action_address().clone()))
                    .collect(),
            ),
            ChainItems::Hashes(h) => ChainItems::Hashes(h),
            ChainItems::NotRequested => ChainItems::NotRequested,
        };
        AgentActivityResponse {
            agent: other.agent,
            valid_activity: convert_activity(other.valid_activity),
            rejected_activity: convert_activity(other.rejected_activity),
            status: other.status,
            highest_observed: other.highest_observed,
            warrants: other.warrants,
        }
    }
}

/// The type of agent activity returned in this request
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, SerializedBytes)]
pub enum ChainItems {
    /// The full records
    Full(Vec<Record>),
    /// Just the hashes
    Hashes(Vec<(u32, ActionHash)>),
    /// Activity was not requested
    NotRequested,
}

impl ChainItems {
    /// Whether these items carry no activity, either because none was
    /// requested or because the requested list came back empty.
    pub fn is_empty(&self) -> bool {
        match self {
            ChainItems::Full(records) => records.is_empty(),
            ChainItems::Hashes(hashes) => hashes.is_empty(),
            ChainItems::NotRequested => true,
        }
    }
}

impl From<AgentActivityResponse> for AgentActivityStatus {
    fn from(a: AgentActivityResponse) -> Self {
        let valid_activity = match a.valid_activity {
            ChainItems::Full(records) => records
                .into_iter()
                .map(|el| (el.action().action_seq(), el.action_address().clone()))
                .collect(),
            ChainItems::Hashes(h) => h,
            ChainItems::NotRequested => Vec::new(),
        };
        let rejected_activity = match a.rejected_activity {
            ChainItems::Full(records) => records
                .into_iter()
                .map(|el| (el.action().action_seq(), el.action_address().clone()))
                .collect(),
            ChainItems::Hashes(h) => h,
            ChainItems::NotRequested => Vec::new(),
        };
        Self {
            valid_activity,
            rejected_activity,
            status: a.status,
            highest_observed: a.highest_observed,
            warrants: a.warrants,
        }
    }
}

/// A helper trait to allow [`Record`]s, [`SignedActionHashed`](holochain_zome_types::prelude::SignedActionHashed)s, and [`ActionHashed`]s to be converted into [`ChainItems`]
/// without needing to know which source type is being operated on.
pub trait ChainItemsSource {
    /// Convert a source type into a [ChainItems] value.
    fn to_chain_items(self) -> ChainItems;
}

impl ChainItemsSource for Vec<Record> {
    fn to_chain_items(self) -> ChainItems {
        ChainItems::Full(self)
    }
}

impl ChainItemsSource for Vec<ActionHashed> {
    fn to_chain_items(self) -> ChainItems {
        ChainItems::Hashes(
            self.into_iter()
                .map(|a| (a.action_seq(), a.as_hash().clone()))
                .collect(),
        )
    }
}

impl ChainItemsSource for Vec<(u32, ActionHash)> {
    fn to_chain_items(self) -> ChainItems {
        ChainItems::Hashes(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use holochain_zome_types::prelude::ChainHead;

    #[test]
    fn empty_response_detection() {
        // An authority holding nothing for the agent: with activity
        // requested the payload is an empty `Hashes` list, not
        // `NotRequested`. Both shapes carry no information and must be
        // treated as empty.
        let empty = AgentActivityResponse {
            agent: AgentPubKey::from_raw_32(vec![2; 32]),
            valid_activity: ChainItems::Hashes(vec![]),
            rejected_activity: ChainItems::Hashes(vec![]),
            status: ChainStatus::Empty,
            highest_observed: None,
            warrants: vec![],
        };
        assert!(empty.is_empty());
        assert!(AgentActivityResponse {
            valid_activity: ChainItems::NotRequested,
            rejected_activity: ChainItems::NotRequested,
            ..empty.clone()
        }
        .is_empty());

        // Any piece of information makes the response non-empty.
        let head = ChainHead {
            action_seq: 5,
            hash: ActionHash::from_raw_32(vec![1; 32]),
        };
        assert!(!AgentActivityResponse {
            valid_activity: ChainItems::Hashes(vec![(0, ActionHash::from_raw_32(vec![3; 32]))]),
            ..empty.clone()
        }
        .is_empty());
        assert!(!AgentActivityResponse {
            status: ChainStatus::Valid(head.clone()),
            ..empty.clone()
        }
        .is_empty());
        assert!(!AgentActivityResponse {
            highest_observed: Some(HighestObserved {
                action_seq: head.action_seq,
                hash: vec![head.hash],
            }),
            ..empty.clone()
        }
        .is_empty());
    }

    #[test]
    fn status_only_preserves_status() {
        let head = ChainHead {
            action_seq: 5,
            hash: ActionHash::from_raw_32(vec![1; 32]),
        };
        let response = AgentActivityResponse {
            agent: AgentPubKey::from_raw_32(vec![2; 32]),
            valid_activity: ChainItems::Hashes(vec![]),
            rejected_activity: ChainItems::NotRequested,
            status: ChainStatus::Valid(head.clone()),
            highest_observed: None,
            warrants: vec![],
        };

        let only = AgentActivityResponse::status_only(response);

        assert_eq!(only.status, ChainStatus::Valid(head));
        assert_eq!(only.valid_activity, ChainItems::NotRequested);
        assert_eq!(only.rejected_activity, ChainItems::NotRequested);
    }
}