-
Notifications
You must be signed in to change notification settings - Fork 12
/
_8_async.rs
314 lines (271 loc) · 9.48 KB
/
_8_async.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
use crate::message::ResponseMessage;
use crate::{Identity, ManyError};
use many_macros::many_module;
use minicbor::data::Type;
use minicbor::encode::{Error, Write};
use minicbor::{Decode, Decoder, Encode, Encoder};
#[cfg(test)]
use mockall::{automock, predicate::*};
/// An AsyncToken which is returned when the server does not have an immediate
/// response.
#[derive(Clone, PartialEq)]
#[repr(transparent)]
pub struct AsyncToken(Vec<u8>);
impl AsRef<[u8]> for AsyncToken {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl<C> Encode<C> for AsyncToken {
fn encode<W: Write>(&self, e: &mut Encoder<W>, _: &mut C) -> Result<(), Error<W::Error>> {
e.bytes(&self.0)?;
Ok(())
}
}
impl<'b, C> Decode<'b, C> for AsyncToken {
fn decode(d: &mut Decoder<'b>, _: &mut C) -> Result<Self, minicbor::decode::Error> {
Ok(Self(d.bytes()?.to_vec()))
}
}
impl From<Vec<u8>> for AsyncToken {
fn from(v: Vec<u8>) -> Self {
Self(v)
}
}
impl std::fmt::Debug for AsyncToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("AsyncToken")
.field(&hex::encode(&self.0))
.finish()
}
}
pub mod attributes {
use super::AsyncToken;
use crate::cbor::CborAny;
use crate::protocol::attributes::TryFromAttributeSet;
use crate::protocol::{Attribute, AttributeSet};
use crate::ManyError;
pub const ASYNC: Attribute = Attribute::id(1);
pub struct AsyncAttribute {
pub token: AsyncToken,
}
impl AsyncAttribute {
pub fn new(token: AsyncToken) -> Self {
Self { token }
}
}
impl From<AsyncAttribute> for Attribute {
fn from(a: AsyncAttribute) -> Attribute {
ASYNC.with_argument(CborAny::Bytes(a.token.0))
}
}
impl TryFrom<Attribute> for AsyncAttribute {
type Error = ManyError;
fn try_from(value: Attribute) -> Result<Self, Self::Error> {
if value.id != ASYNC.id {
return Err(ManyError::invalid_attribute_id(value.id));
}
let arguments = value.into_arguments();
if arguments.len() != 1 {
Err(ManyError::invalid_attribute_arguments())
} else {
match arguments.into_iter().next() {
Some(CborAny::Bytes(token)) => Ok(Self {
token: token.into(),
}),
_ => Err(ManyError::invalid_attribute_arguments()),
}
}
}
}
impl TryFromAttributeSet for AsyncAttribute {
fn try_from_set(set: &AttributeSet) -> Result<Self, ManyError> {
match set.get_attribute(ASYNC.id) {
Some(attr) => AsyncAttribute::try_from(attr.clone()),
None => Err(ManyError::attribute_not_found(ASYNC.id.to_string())),
}
}
}
}
#[derive(Debug, Clone, Encode, Decode, PartialEq)]
#[cbor(map)]
pub struct StatusArgs {
#[n(0)]
pub token: AsyncToken,
}
#[derive(Debug, Clone)]
pub enum StatusReturn {
Unknown,
Queued,
Processing,
Done { response: Box<ResponseMessage> },
Expired,
}
impl StatusReturn {
fn variant(&self) -> u8 {
match self {
StatusReturn::Unknown => 0,
StatusReturn::Queued => 1,
StatusReturn::Processing => 2,
StatusReturn::Done { .. } => 3,
StatusReturn::Expired => 4,
}
}
fn from_kind(kind: u8, response: Option<ResponseMessage>) -> Result<Self, ()> {
match (kind, response) {
(0, None) => Ok(Self::Unknown),
(1, None) => Ok(Self::Queued),
(2, None) => Ok(Self::Processing),
(3, Some(response)) => Ok(Self::Done {
response: Box::new(response),
}),
(4, None) => Ok(Self::Expired),
_ => Err(()),
}
}
}
impl<C> Encode<C> for StatusReturn {
fn encode<W: Write>(&self, e: &mut Encoder<W>, _: &mut C) -> Result<(), Error<W::Error>> {
if let StatusReturn::Done { response } = self {
e.map(2)?;
e.u8(1)?.bytes(
response
.clone()
.to_bytes()
.map_err(|_err| Error::message("Response could not be encoded."))?
.as_ref(),
)?
} else {
e.map(1)?
}
.u8(0)?
.u8(self.variant())?;
Ok(())
}
}
impl<'b, C> Decode<'b, C> for StatusReturn {
fn decode(d: &mut Decoder<'b>, _: &mut C) -> Result<Self, minicbor::decode::Error> {
let len = d.map()?;
let mut i = 0;
let mut key = None;
let mut result = None;
loop {
match d.datatype()? {
Type::Break => {
d.skip()?;
break;
}
Type::U8 | Type::U16 | Type::U32 | Type::U64 => match d.u8()? {
0 => {
key = Some(d.u8()?);
}
1 => {
result = Some(d.bytes()?);
}
x => return Err(minicbor::decode::Error::unknown_variant(u32::from(x))),
},
_ => return Err(minicbor::decode::Error::message("Invalid key type.")),
}
i += 1;
if len.map_or(false, |x| i >= x) {
break;
}
}
Self::from_kind(
key.map_or(Err("Invalid variant."), Ok)
.map_err(minicbor::decode::Error::message)?,
match result {
Some(result) => Some(ResponseMessage::from_bytes(result).map_err(|_| {
minicbor::decode::Error::message(
"Invalid result type, expected ResponseMessage.",
)
})?),
_ => None,
},
)
.map_err(|_| minicbor::decode::Error::message("Invalid variant or result."))
}
}
#[many_module(name = AsyncModule, id = 8, namespace = async, many_crate = crate)]
#[cfg_attr(test, automock)]
pub trait AsyncModuleBackend: Send {
fn status(&self, sender: &Identity, args: StatusArgs) -> Result<StatusReturn, ManyError>;
}
#[cfg(test)]
mod tests {
use super::attributes::AsyncAttribute;
use super::*;
use crate::cbor::CborAny;
use crate::protocol::attributes::TryFromAttributeSet;
use crate::protocol::{Attribute, AttributeSet};
use crate::server::module::_8_async::attributes::ASYNC;
use crate::server::module::testutils::call_module_cbor;
use crate::types::identity::testing::identity;
use mockall::predicate;
use proptest::prelude::*;
use std::sync::{Arc, Mutex};
fn arb_status() -> impl Strategy<Value = StatusReturn> {
prop_oneof![
Just(StatusReturn::Unknown),
Just(StatusReturn::Queued),
Just(StatusReturn::Processing),
Just(StatusReturn::Done {
response: Box::new(ResponseMessage::default())
}),
Just(StatusReturn::Expired),
]
.boxed()
}
proptest! {
#[test]
fn status(status in arb_status()) {
let data = StatusArgs {
token: AsyncToken::from(vec![11, 12, 13])
};
let mut mock = MockAsyncModuleBackend::new();
mock.expect_status()
.with(predicate::eq(tests::identity(1)), predicate::eq(data.clone()))
.times(1)
.return_const(Ok(status.clone()));
let module = super::AsyncModule::new(Arc::new(Mutex::new(mock)));
let status_return: StatusReturn = minicbor::decode(
&call_module_cbor(1, &module, "async.status", minicbor::to_vec(data).unwrap()).unwrap(),
)
.unwrap();
assert_eq!(status_return.variant(), status.variant());
}
}
#[test]
fn async_attr() {
let v = vec![1, 2, 3, 4];
let args = vec![CborAny::Bytes(v.clone())];
// Valid async attr - new
let token = AsyncToken::from(v);
let async_attr = AsyncAttribute::new(token.clone());
assert_eq!(async_attr.token.as_ref(), token.as_ref());
// Valid attribute from async attribute
let attr = Attribute::from(async_attr);
assert_eq!(attr.id, ASYNC.id);
assert_eq!(attr.arguments, args);
// Valid async attr - try_from
let attr = Attribute::new(1, args);
let async_attr = AsyncAttribute::try_from(attr.clone()).unwrap();
assert_eq!(async_attr.token.as_ref(), token.as_ref());
// Valid async attr - try_from_set
let attr_set = AttributeSet::from_iter(vec![attr].into_iter());
let async_attr = AsyncAttribute::try_from_set(&attr_set).unwrap();
assert_eq!(async_attr.token.as_ref(), token.as_ref());
// Invalid async attr - try_from - invalid id
let invalid_attr = Attribute::id(123);
let async_attr = AsyncAttribute::try_from(invalid_attr.clone());
assert!(async_attr.is_err());
// Invalid async attr - try_from_set
let attr_set = AttributeSet::from_iter(vec![invalid_attr].into_iter());
let async_attr = AsyncAttribute::try_from_set(&attr_set);
assert!(async_attr.is_err());
// Invalid async attr - try_from - invalid arguments
let invalid_attr = Attribute::id(1);
let async_attr = AsyncAttribute::try_from(invalid_attr);
assert!(async_attr.is_err());
}
}