-
Notifications
You must be signed in to change notification settings - Fork 12
/
transport.rs
61 lines (51 loc) · 1.94 KB
/
transport.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
use crate::message::{ManyError, RequestMessage, ResponseMessage};
use async_trait::async_trait;
use coset::CoseSign1;
use std::fmt::Debug;
pub mod http;
#[async_trait]
pub trait LowLevelManyRequestHandler: Send + Sync + Debug {
async fn execute(&self, envelope: CoseSign1) -> Result<CoseSign1, String>;
}
/// A simpler version of the [ManyRequestHandler] which only deals with methods and payloads.
#[async_trait]
pub trait SimpleRequestHandler: Send + Sync + Debug {
fn validate(&self, _method: &str, _payload: &[u8]) -> Result<(), ManyError> {
Ok(())
}
async fn handle(&self, method: &str, payload: &[u8]) -> Result<Vec<u8>, ManyError>;
}
#[async_trait]
pub trait ManyRequestHandler: Send + Sync + Debug {
/// Validate that a message is okay with us.
fn validate(&self, _message: &RequestMessage) -> Result<(), ManyError> {
Ok(())
}
/// Handle an incoming request message, and returns the response message.
/// This cannot fail. It should instead responds with a proper error response message.
/// See the spec.
async fn execute(&self, message: RequestMessage) -> Result<ResponseMessage, ManyError>;
}
#[derive(Debug)]
pub struct SimpleRequestHandlerAdapter<I: SimpleRequestHandler>(pub I);
#[async_trait]
impl<I: SimpleRequestHandler> ManyRequestHandler for SimpleRequestHandlerAdapter<I> {
fn validate(&self, message: &RequestMessage) -> Result<(), ManyError> {
self.0
.validate(message.method.as_str(), message.data.as_slice())
}
async fn execute(&self, message: RequestMessage) -> Result<ResponseMessage, ManyError> {
let payload = self
.0
.handle(message.method.as_str(), message.data.as_slice())
.await;
Ok(ResponseMessage {
version: Some(1),
from: message.to,
data: payload,
to: message.from,
id: message.id,
..Default::default()
})
}
}