bifrostlink/packet.rs
1use bytes::Bytes;
2use serde::{Deserialize, Serialize};
3
4#[derive(Debug)]
5pub struct OutgoingMessage<Address> {
6 pub(crate) to: Address,
7 pub(crate) message: Bytes,
8}
9
10// impl<Address> OutgoingMessage<Address>
11// where
12// Address: AddressT,
13// {
14// fn new<T: Serialize>(wrapper: PacketWrapper<Address, T>) -> Self {
15// let to = match &wrapper {
16// PacketWrapper::Response { request_origin, .. } => request_origin,
17// PacketWrapper::Request { receiver, .. } => receiver,
18// };
19// let bytes = BytesMut::new();
20// let mut writer = bytes.writer();
21// serde_json::to_writer(&mut writer, &wrapper).expect("serialization should not fail");
22// let bytes = writer.into_inner();
23// Self {
24// to: to.clone(),
25// message: bytes.freeze(),
26// }
27// }
28// pub(crate) fn new_notification<T: OutgoingNotification>(
29// sender: Address,
30// receiver: Address,
31// data: &T,
32// ) -> Self {
33// Self::new(PacketWrapper::Request {
34// sender,
35// receiver,
36// request: T::name().to_owned(),
37// response: None,
38// data,
39// })
40// }
41// pub fn new_request<T: OutgoingRequest>(
42// sender: Address,
43// receiver: Address,
44// id: String,
45// data: &T,
46// ) -> Self
47// where
48// T::Response: DeserializeOwned,
49// {
50// Self::new(PacketWrapper::Request {
51// sender,
52// receiver,
53// request: T::name().to_owned(),
54// response: Some(ResponseTo { rid: id.to_owned() }),
55// data,
56// })
57// }
58// pub fn new_error_response<E: Display>(rid: &str, receiver: Address, error: E) -> Self {
59// Self::new(PacketWrapper::Response {
60// rid: rid.to_owned(),
61// request_origin: receiver,
62// error: Some(error.to_string()),
63// data: (),
64// })
65// }
66// pub fn new_response<T: Serialize>(rid: &str, receiver: Address, data: &T) -> Self {
67// Self::new(PacketWrapper::Response {
68// rid: rid.to_owned(),
69// request_origin: receiver,
70// error: None,
71// data,
72// })
73// }
74// }
75
76#[derive(Deserialize, Serialize, Debug)]
77#[serde(untagged)]
78pub enum OpaquePacketWrapper<Address> {
79 Response {
80 rid: RequestId,
81 response_from: Address,
82 // It is possible to only have `rid` field,
83 // but it makes it important for the whole bifrost network to generate really unique response ids,
84 // while with it, every requester will handle this on its own.
85 request_origin: Address,
86 error: Option<String>,
87 },
88 Request {
89 sender: Address,
90 receiver: Address,
91 request: u16,
92 response: Option<ResponseTo>,
93 },
94}
95
96#[derive(Serialize, Deserialize, Debug, Clone)]
97pub struct ResponseTo {
98 pub(crate) rid: RequestId,
99}
100
101#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
102pub struct RequestId(pub usize);