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
|
use super::{Node, NodeContext, NodeKind, NodeRequest, NodeResponse};
use crate::{config::DynNode, error::ServiceError};
use anyhow::Result;
use http::Request;
use http_body_util::{combinators::BoxBody, BodyExt, Full};
use serde::Deserialize;
use serde_yml::Value;
use std::{future::Future, pin::Pin, sync::Arc};
pub struct FallbackKind;
#[derive(Deserialize)]
struct Fallback(Vec<DynNode>);
impl NodeKind for FallbackKind {
fn name(&self) -> &'static str {
"fallback"
}
fn instanciate(&self, config: Value) -> Result<Arc<dyn Node>> {
Ok(Arc::new(serde_yml::from_value::<Fallback>(config)?))
}
}
impl Node for Fallback {
fn handle<'a>(
&'a self,
context: &'a mut NodeContext,
request: NodeRequest,
) -> Pin<Box<dyn Future<Output = Result<NodeResponse, ServiceError>> + Send + Sync + 'a>> {
Box::pin(async move {
let (parts, body) = request.into_parts();
let body = body
.collect()
.await
.map_err(|_| ServiceError::Other)?
.to_bytes();
for (i, h) in self.0.iter().enumerate() {
let last = i == self.0.len() - 1;
let res = h
.handle(
context,
Request::from_parts(
parts.clone(),
BoxBody::new(Full::new(body.clone()).map_err(|x| match x {})),
),
)
.await;
if last {
return res;
}
if let Ok(resp) = res {
if resp.status().is_success()
|| resp.status().is_redirection()
|| resp.status().is_informational()
{
return Ok(resp);
}
}
}
return Err(ServiceError::CustomStatic(
"fallback module without any handlers",
));
})
}
}
|