aboutsummaryrefslogtreecommitdiff
path: root/src/modules/switch.rs
blob: 466bdd8bd7814f2ad5b5fe71116db86864118174 (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use super::{Node, NodeContext, NodeKind, NodeRequest, NodeResponse};
use crate::{config::DynNode, error::ServiceError};
use anyhow::Result;
use futures::Future;
use headers::{HeaderMapExt, Upgrade};
use http::Version;
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,
    IsPut,
    IsPatch,
    IsOptions,
    HasHeader(String),
    PathStartsWith(String),
    PathIs(String),
    HttpVersion(u8),
}

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::IsPut => req.method() == Method::PUT,
            Condition::IsPatch => req.method() == Method::PATCH,
            Condition::IsOptions => req.method() == Method::OPTIONS,
            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)),
            Condition::HttpVersion(n) => {
                if req.version() == Version::HTTP_3 {
                    *n == 3
                } else if req.version() == Version::HTTP_2 {
                    *n == 2
                } else {
                    *n == 1
                }
            }
        }
    }
}