/
response.rs
217 lines (191 loc) · 6.85 KB
/
response.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
use crate::message::RequestMessage;
use crate::protocol::attributes::AttributeSet;
use crate::protocol::Attribute;
use crate::Identity;
use derive_builder::Builder;
use minicbor::data::{Tag, Type};
use minicbor::encode::{Error, Write};
use minicbor::{Decode, Decoder, Encode, Encoder};
use num_derive::{FromPrimitive, ToPrimitive};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[derive(FromPrimitive, ToPrimitive)]
#[repr(i8)]
pub enum ResponseMessageCborKey {
ProtocolVersion = 0,
From,
To,
_Endpoint, // Unused in Response.
Result,
Timestamp,
Id,
_Nonce, // Unused in Response.
Attributes,
}
/// A MANY message response.
#[derive(Clone, Debug, Builder)]
#[builder(setter(strip_option), default)]
pub struct ResponseMessage {
pub version: Option<u8>,
pub from: Identity,
pub to: Option<Identity>,
pub data: Result<Vec<u8>, super::ManyError>,
/// An optional timestamp for this response. If [None] this will be filled
/// with [SystemTime::now()]
pub timestamp: Option<SystemTime>,
pub id: Option<u64>,
pub attributes: AttributeSet,
}
impl Default for ResponseMessage {
fn default() -> Self {
Self {
version: None,
from: Identity::anonymous(),
to: None,
data: Ok(vec![]),
timestamp: None,
id: None,
attributes: Default::default(),
}
}
}
impl ResponseMessage {
pub fn from_request(
request: &RequestMessage,
from: &Identity,
data: Result<Vec<u8>, super::ManyError>,
) -> Self {
Self {
version: Some(1),
from: *from,
to: request.from, // We're sending back to the same requester.
data,
timestamp: None, // To be filled.
id: request.id,
attributes: Default::default(),
}
}
pub fn error(from: &Identity, id: Option<u64>, data: super::ManyError) -> Self {
Self {
version: Some(1),
from: *from,
to: None,
data: Err(data),
timestamp: None, // To be filled.
id,
attributes: Default::default(),
}
}
pub fn with_attribute(mut self, attr: Attribute) -> Self {
self.attributes.insert(attr);
self
}
pub fn to_bytes(&self) -> Result<Vec<u8>, String> {
minicbor::to_vec(self).map_err(|e| format!("{}", e))
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, String> {
minicbor::decode(bytes).map_err(|e| format!("{}", e))
}
}
impl<C> Encode<C> for ResponseMessage {
fn encode<W: Write>(&self, e: &mut Encoder<W>, _: &mut C) -> Result<(), Error<W::Error>> {
e.tag(Tag::Unassigned(10002))?;
let l = 2
+ if self.from.is_anonymous() { 0 } else { 1 }
+ if self.to.is_none() || self.to == Some(Identity::anonymous()) {
0
} else {
1
}
+ if self.id.is_none() { 0 } else { 1 }
+ if self.attributes.is_empty() { 0 } else { 1 };
e.map(l)?;
// Skip version for this version of the protocol. This message implementation
// only supports version 1.
// e.i8(RequestMessageCborKey::ProtocolVersion as i8)?.u8(*v)?;
// No need to send the anonymous identity.
if !self.from.is_anonymous() {
e.i8(ResponseMessageCborKey::From as i8)?
.encode(&self.from)?;
}
if let Some(ref i) = self.to {
if !i.is_anonymous() {
e.i8(ResponseMessageCborKey::To as i8)?.encode(i)?;
}
}
match &self.data {
Ok(result) => e.i8(ResponseMessageCborKey::Result as i8)?.bytes(result)?,
Err(error) => e.i8(ResponseMessageCborKey::Result as i8)?.encode(&error)?,
};
e.i8(ResponseMessageCborKey::Timestamp as i8)?;
let timestamp = self.timestamp.unwrap_or_else(SystemTime::now);
e.tag(minicbor::data::Tag::Timestamp)?.u64(
timestamp
.duration_since(UNIX_EPOCH)
.expect("Time flew backward")
.as_secs(),
)?;
if let Some(ref id) = self.id {
e.i8(ResponseMessageCborKey::Id as i8)?.u64(*id)?;
}
if !self.attributes.is_empty() {
e.i8(ResponseMessageCborKey::Attributes as i8)?
.encode(&self.attributes)?;
}
Ok(())
}
}
impl<'b, C> Decode<'b, C> for ResponseMessage {
fn decode(d: &mut Decoder<'b>, _: &mut C) -> Result<Self, minicbor::decode::Error> {
if d.tag()? != Tag::Unassigned(10002) {
return Err(minicbor::decode::Error::message(
"Invalid tag, expected 10002 for a message.",
));
};
let mut builder = ResponseMessageBuilder::default();
let mut i = 0;
let x = d.map()?;
// Since we don't know if this is a indef map or a regular map, we just loop
// through items and break when we know the map is done.
loop {
if d.datatype()? == Type::Break {
d.skip()?;
break;
}
match num_traits::FromPrimitive::from_i64(d.i64()?) {
Some(ResponseMessageCborKey::ProtocolVersion) => builder.version(d.decode()?),
Some(ResponseMessageCborKey::From) => builder.from(d.decode()?),
Some(ResponseMessageCborKey::To) => builder.to(d.decode()?),
Some(ResponseMessageCborKey::Result) => match d.datatype()? {
Type::Bytes => builder.data(Ok(d.bytes()?.to_vec())),
Type::Map => builder.data(Err(d.decode()?)),
_ => &mut builder,
},
Some(ResponseMessageCborKey::Timestamp) => {
// Some logic applies.
let t = d.tag()?;
if t != minicbor::data::Tag::Timestamp {
return Err(minicbor::decode::Error::message("Invalid tag."));
}
let secs = d.u64()?;
let timestamp = std::time::UNIX_EPOCH
.checked_add(Duration::from_secs(secs))
.ok_or_else(|| {
minicbor::decode::Error::message(
"duration value can not represent system time",
)
})?;
builder.timestamp(timestamp)
}
Some(ResponseMessageCborKey::Attributes) => builder.attributes(d.decode()?),
_ => &mut builder,
};
i += 1;
if x.map_or(false, |x| i >= x) {
break;
}
}
builder
.build()
.map_err(|_e| minicbor::decode::Error::message("could not build"))
}
}