aboutsummaryrefslogtreecommitdiff
path: root/src/modules/switch.rs
blob: 289c4062a932e02ed252380203eae7937886f057 (plain)
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
use super::{Node, NodeContext, NodeKind, NodeRequest, NodeResponse};
use crate::{config::DynNode, error::ServiceError};
use anyhow::Result;
use futures::Future;
use headers::{HeaderMapExt, Upgrade};
use hyper::Method;
use serde::Deserialize;
use std::{pin::Pin, sync::Arc};

pub struct SwitchKind;

#[derive(Deserialize)]
pub struct Switch {
    condition: Condition,
    case_true: DynNode,
    case_false: DynNode,
}

impl NodeKind for SwitchKind {
    fn name(&self) -> &'static str {
        "switch"
    }
    fn instanciate(&self, config: serde_yml::Value) -> Result<Arc<dyn Node>> {
        Ok(Arc::new(serde_yml::from_value::<Switch>(config)?))
    }
}

impl Node for Switch {
    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 cond = self.condition.test(&request);
            if cond {
                &self.case_true
            } else {
                &self.case_false
            }
            .handle(context, request)
            .await
        })
    }
}

#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum Condition {
    Any(Vec<Condition>),
    All(Vec<Condition>),
    IsWebsocketUpgrade,
    IsPost,
    IsGet,
    HasHeader(String),
    PathStartsWith(String),
    PathIs(String),
}

impl Condition {
    pub fn test(&self, req: &NodeRequest) -> bool {
        match self {
            Condition::IsWebsocketUpgrade => {
                req.headers().typed_get::<Upgrade>() == Some(Upgrade::websocket())
            }
            Condition::HasHeader(name) => req.headers().contains_key(name),
            Condition::PathStartsWith(path_prefix) => req.uri().path().starts_with(path_prefix),
            Condition::PathIs(path) => req.uri().path() == path,
            Condition::IsPost => req.method() == Method::POST,
            Condition::IsGet => req.method() == Method::GET,
            Condition::Any(conds) => conds.iter().any(|c| c.test(req)),
            Condition::All(conds) => conds.iter().all(|c| c.test(req)),
        }
    }
}