use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};
use sp_api::ApiError;
use sp_version::RuntimeVersion;
use std::collections::BTreeMap;
use crate::common::events::StorageResult;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorEvent {
pub error: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RuntimeVersionEvent {
pub spec: ChainHeadRuntimeVersion,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChainHeadRuntimeVersion {
pub spec_name: String,
pub impl_name: String,
pub spec_version: u32,
pub impl_version: u32,
pub apis: BTreeMap<String, u32>,
pub transaction_version: u32,
}
impl From<RuntimeVersion> for ChainHeadRuntimeVersion {
fn from(val: RuntimeVersion) -> Self {
Self {
spec_name: val.spec_name.into(),
impl_name: val.impl_name.into(),
spec_version: val.spec_version,
impl_version: val.impl_version,
apis: val
.apis
.into_iter()
.map(|(api, version)| (sp_core::bytes::to_hex(api, false), *version))
.collect(),
transaction_version: val.transaction_version,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(tag = "type")]
pub enum RuntimeEvent {
Valid(RuntimeVersionEvent),
Invalid(ErrorEvent),
}
impl From<ApiError> for RuntimeEvent {
fn from(err: ApiError) -> Self {
RuntimeEvent::Invalid(ErrorEvent { error: format!("Api error: {}", err) })
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Initialized<Hash> {
pub finalized_block_hashes: Vec<Hash>,
pub finalized_block_runtime: Option<RuntimeEvent>,
#[serde(default)]
pub(crate) with_runtime: bool,
}
impl<Hash: Serialize> Serialize for Initialized<Hash> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if self.with_runtime {
let mut state = serializer.serialize_struct("Initialized", 2)?;
state.serialize_field("finalizedBlockHashes", &self.finalized_block_hashes)?;
state.serialize_field("finalizedBlockRuntime", &self.finalized_block_runtime)?;
state.end()
} else {
let mut state = serializer.serialize_struct("Initialized", 1)?;
state.serialize_field("finalizedBlockHashes", &self.finalized_block_hashes)?;
state.end()
}
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NewBlock<Hash> {
pub block_hash: Hash,
pub parent_block_hash: Hash,
pub new_runtime: Option<RuntimeEvent>,
#[serde(default)]
pub(crate) with_runtime: bool,
}
impl<Hash: Serialize> Serialize for NewBlock<Hash> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if self.with_runtime {
let mut state = serializer.serialize_struct("NewBlock", 3)?;
state.serialize_field("blockHash", &self.block_hash)?;
state.serialize_field("parentBlockHash", &self.parent_block_hash)?;
state.serialize_field("newRuntime", &self.new_runtime)?;
state.end()
} else {
let mut state = serializer.serialize_struct("NewBlock", 2)?;
state.serialize_field("blockHash", &self.block_hash)?;
state.serialize_field("parentBlockHash", &self.parent_block_hash)?;
state.end()
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BestBlockChanged<Hash> {
pub best_block_hash: Hash,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Finalized<Hash> {
pub finalized_block_hashes: Vec<Hash>,
pub pruned_block_hashes: Vec<Hash>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperationId {
pub operation_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperationBodyDone {
pub operation_id: String,
pub value: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperationCallDone {
pub operation_id: String,
pub output: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperationStorageItems {
pub operation_id: String,
pub items: Vec<StorageResult>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperationError {
pub operation_id: String,
pub error: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(tag = "event")]
pub enum FollowEvent<Hash> {
Initialized(Initialized<Hash>),
NewBlock(NewBlock<Hash>),
BestBlockChanged(BestBlockChanged<Hash>),
Finalized(Finalized<Hash>),
OperationBodyDone(OperationBodyDone),
OperationCallDone(OperationCallDone),
OperationStorageItems(OperationStorageItems),
OperationWaitingForContinue(OperationId),
OperationStorageDone(OperationId),
OperationInaccessible(OperationId),
OperationError(OperationError),
Stop,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(tag = "result")]
pub enum MethodResponse {
Started(MethodResponseStarted),
LimitReached,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MethodResponseStarted {
pub operation_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub discarded_items: Option<usize>,
}
#[cfg(test)]
mod tests {
use crate::common::events::StorageResultType;
use super::*;
#[test]
fn follow_initialized_event_no_updates() {
let event: FollowEvent<String> = FollowEvent::Initialized(Initialized {
finalized_block_hashes: vec!["0x1".into()],
finalized_block_runtime: None,
with_runtime: false,
});
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"event":"initialized","finalizedBlockHashes":["0x1"]}"#;
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
}
#[test]
fn follow_initialized_event_with_updates() {
let runtime = RuntimeVersion {
spec_name: "ABC".into(),
impl_name: "Impl".into(),
spec_version: 1,
..Default::default()
};
let runtime_event = RuntimeEvent::Valid(RuntimeVersionEvent { spec: runtime.into() });
let mut initialized = Initialized {
finalized_block_hashes: vec!["0x1".into()],
finalized_block_runtime: Some(runtime_event),
with_runtime: true,
};
let event: FollowEvent<String> = FollowEvent::Initialized(initialized.clone());
let ser = serde_json::to_string(&event).unwrap();
let exp = concat!(
r#"{"event":"initialized","finalizedBlockHashes":["0x1"],"#,
r#""finalizedBlockRuntime":{"type":"valid","spec":{"specName":"ABC","implName":"Impl","#,
r#""specVersion":1,"implVersion":0,"apis":{},"transactionVersion":0}}}"#,
);
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
initialized.with_runtime = false;
assert!(matches!(
event_dec, FollowEvent::Initialized(ref dec) if dec == &initialized
));
}
#[test]
fn follow_new_block_event_no_updates() {
let event: FollowEvent<String> = FollowEvent::NewBlock(NewBlock {
block_hash: "0x1".into(),
parent_block_hash: "0x2".into(),
new_runtime: None,
with_runtime: false,
});
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"event":"newBlock","blockHash":"0x1","parentBlockHash":"0x2"}"#;
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
}
#[test]
fn follow_new_block_event_with_updates() {
let runtime = RuntimeVersion {
spec_name: "ABC".into(),
impl_name: "Impl".into(),
spec_version: 1,
apis: vec![([0, 0, 0, 0, 0, 0, 0, 0], 2), ([1, 0, 0, 0, 0, 0, 0, 0], 3)].into(),
..Default::default()
};
let runtime_event = RuntimeEvent::Valid(RuntimeVersionEvent { spec: runtime.into() });
let mut new_block = NewBlock {
block_hash: "0x1".into(),
parent_block_hash: "0x2".into(),
new_runtime: Some(runtime_event),
with_runtime: true,
};
let event: FollowEvent<String> = FollowEvent::NewBlock(new_block.clone());
let ser = serde_json::to_string(&event).unwrap();
let exp = concat!(
r#"{"event":"newBlock","blockHash":"0x1","parentBlockHash":"0x2","#,
r#""newRuntime":{"type":"valid","spec":{"specName":"ABC","implName":"Impl","#,
r#""specVersion":1,"implVersion":0,"apis":{"0x0000000000000000":2,"0x0100000000000000":3},"transactionVersion":0}}}"#,
);
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
new_block.with_runtime = false;
assert!(matches!(
event_dec, FollowEvent::NewBlock(ref dec) if dec == &new_block
));
let mut new_block = NewBlock {
block_hash: "0x1".into(),
parent_block_hash: "0x2".into(),
new_runtime: None,
with_runtime: true,
};
let event: FollowEvent<String> = FollowEvent::NewBlock(new_block.clone());
let ser = serde_json::to_string(&event).unwrap();
let exp =
r#"{"event":"newBlock","blockHash":"0x1","parentBlockHash":"0x2","newRuntime":null}"#;
assert_eq!(ser, exp);
new_block.with_runtime = false;
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
assert!(matches!(
event_dec, FollowEvent::NewBlock(ref dec) if dec == &new_block
));
}
#[test]
fn follow_best_block_changed_event() {
let event: FollowEvent<String> =
FollowEvent::BestBlockChanged(BestBlockChanged { best_block_hash: "0x1".into() });
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"event":"bestBlockChanged","bestBlockHash":"0x1"}"#;
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
}
#[test]
fn follow_finalized_event() {
let event: FollowEvent<String> = FollowEvent::Finalized(Finalized {
finalized_block_hashes: vec!["0x1".into()],
pruned_block_hashes: vec!["0x2".into()],
});
let ser = serde_json::to_string(&event).unwrap();
let exp =
r#"{"event":"finalized","finalizedBlockHashes":["0x1"],"prunedBlockHashes":["0x2"]}"#;
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
}
#[test]
fn follow_op_body_event() {
let event: FollowEvent<String> = FollowEvent::OperationBodyDone(OperationBodyDone {
operation_id: "123".into(),
value: vec!["0x1".into()],
});
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"event":"operationBodyDone","operationId":"123","value":["0x1"]}"#;
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
}
#[test]
fn follow_op_call_event() {
let event: FollowEvent<String> = FollowEvent::OperationCallDone(OperationCallDone {
operation_id: "123".into(),
output: "0x1".into(),
});
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"event":"operationCallDone","operationId":"123","output":"0x1"}"#;
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
}
#[test]
fn follow_op_storage_items_event() {
let event: FollowEvent<String> =
FollowEvent::OperationStorageItems(OperationStorageItems {
operation_id: "123".into(),
items: vec![StorageResult {
key: "0x1".into(),
result: StorageResultType::Value("0x123".to_string()),
}],
});
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"event":"operationStorageItems","operationId":"123","items":[{"key":"0x1","value":"0x123"}]}"#;
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
}
#[test]
fn follow_op_wait_event() {
let event: FollowEvent<String> =
FollowEvent::OperationWaitingForContinue(OperationId { operation_id: "123".into() });
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"event":"operationWaitingForContinue","operationId":"123"}"#;
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
}
#[test]
fn follow_op_storage_done_event() {
let event: FollowEvent<String> =
FollowEvent::OperationStorageDone(OperationId { operation_id: "123".into() });
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"event":"operationStorageDone","operationId":"123"}"#;
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
}
#[test]
fn follow_op_inaccessible_event() {
let event: FollowEvent<String> =
FollowEvent::OperationInaccessible(OperationId { operation_id: "123".into() });
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"event":"operationInaccessible","operationId":"123"}"#;
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
}
#[test]
fn follow_op_error_event() {
let event: FollowEvent<String> = FollowEvent::OperationError(OperationError {
operation_id: "123".into(),
error: "reason".into(),
});
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"event":"operationError","operationId":"123","error":"reason"}"#;
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
}
#[test]
fn follow_stop_event() {
let event: FollowEvent<String> = FollowEvent::Stop;
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"event":"stop"}"#;
assert_eq!(ser, exp);
let event_dec: FollowEvent<String> = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
}
#[test]
fn method_response() {
let event = MethodResponse::Started(MethodResponseStarted {
operation_id: "123".into(),
discarded_items: None,
});
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"result":"started","operationId":"123"}"#;
assert_eq!(ser, exp);
let event_dec: MethodResponse = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
let event = MethodResponse::Started(MethodResponseStarted {
operation_id: "123".into(),
discarded_items: Some(1),
});
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"result":"started","operationId":"123","discardedItems":1}"#;
assert_eq!(ser, exp);
let event_dec: MethodResponse = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
let event = MethodResponse::LimitReached;
let ser = serde_json::to_string(&event).unwrap();
let exp = r#"{"result":"limitReached"}"#;
assert_eq!(ser, exp);
let event_dec: MethodResponse = serde_json::from_str(exp).unwrap();
assert_eq!(event_dec, event);
}
}