use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use wasmflow_entity::Entity;
use wasmflow_packet::PacketMap;
use wasmflow_transport::TransportMap;
use crate::error::Error;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[must_use]
pub struct Invocation {
pub origin: Entity,
pub target: Entity,
pub payload: TransportMap,
pub id: Uuid,
pub tx_id: Uuid,
pub inherent: Option<InherentData>,
pub config: Option<wasmflow_transport::Serialized>,
}
impl Invocation {
pub fn new(origin: Entity, target: Entity, payload: TransportMap, inherent: Option<InherentData>) -> Invocation {
let tx_id = get_uuid();
let invocation_id = get_uuid();
Invocation {
origin,
target,
payload,
id: invocation_id,
tx_id,
inherent,
config: None,
}
}
pub fn into_v1_parts<C>(self) -> Result<(wasmflow_packet::v1::PacketMap, Option<C>), Error>
where
C: std::fmt::Debug + DeserializeOwned,
{
let config = match self.config {
Some(v) => Some(
v.deserialize()
.map_err(|e| Error::IncomingPayload(format!("could not deserialize config: {}", e)))?,
),
None => None,
};
Ok((self.payload.into_v1_map(), config))
}
pub fn next(
tx_id: Uuid,
origin: Entity,
target: Entity,
payload: TransportMap,
inherent: Option<InherentData>,
) -> Invocation {
let invocation_id = get_uuid();
Invocation {
origin,
target,
payload,
id: invocation_id,
tx_id,
inherent,
config: None,
}
}
pub fn new_test(
msg: &str,
target: Entity,
payload: impl Into<PacketMap>,
inherent: Option<InherentData>,
) -> Invocation {
let payload = payload.into();
let tx_id = get_uuid();
let invocation_id = get_uuid();
Invocation {
origin: Entity::test(msg),
target,
payload: payload.into(),
id: invocation_id,
tx_id,
inherent,
config: None,
}
}
#[must_use]
pub fn seed(&self) -> Option<u64> {
self.inherent.map(|i| i.seed)
}
#[must_use]
pub fn timestamp(&self) -> Option<u64> {
self.inherent.map(|i| i.timestamp)
}
#[must_use]
pub fn target_url(&self) -> String {
self.target.url()
}
#[must_use]
pub fn origin_url(&self) -> String {
self.origin.url()
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[must_use]
pub struct InherentData {
pub seed: u64,
pub timestamp: u64,
}
impl InherentData {
pub fn new(seed: u64, timestamp: u64) -> Self {
Self { seed, timestamp }
}
}
pub(crate) fn get_uuid() -> Uuid {
Uuid::new_v4()
}
#[cfg(test)]
mod tests {}