Skip to main content

command_dispatch/
command_dispatch.rs

1use dispatch_core::{Dispatcher, Handler, Matcher, Middleware};
2
3/// 本例支持的输入命令。
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5enum Command {
6    Read,
7    Write,
8}
9
10/// 每次分发时携带的输入。
11struct Request {
12    command: Command,
13    authenticated: bool,
14    value: u32,
15}
16
17/// Handler 执行成功后的输出。
18#[derive(Debug, PartialEq, Eq)]
19struct Response {
20    value: u32,
21    audited: bool,
22}
23
24#[derive(Debug, PartialEq, Eq)]
25enum Error {
26    Unauthorized,
27}
28
29/// 分发表中的一项。
30///
31/// 每一项既包含匹配所需的命令,也实现具体的执行逻辑。
32struct Route {
33    command: Command,
34    operation: Operation,
35}
36
37enum Operation {
38    Read,
39    Double,
40}
41
42impl Handler for Route {
43    type Input = Request;
44    type Output = Response;
45    type Error = Error;
46
47    fn handle(&self, request: &Request) -> Result<Response, Error> {
48        let value = match self.operation {
49            Operation::Read => request.value,
50            Operation::Double => request.value * 2,
51        };
52
53        Ok(Response {
54            value,
55            audited: false,
56        })
57    }
58}
59
60/// 根据请求中的 command 选择 Route。
61struct CommandMatcher;
62
63impl Matcher<Route, Request> for CommandMatcher {
64    fn matches(&self, route: &Route, request: &Request) -> bool {
65        route.command == request.command
66    }
67}
68
69/// 前置与后置处理。
70struct SecurityAndAudit {
71    before_count: u32,
72    after_count: u32,
73}
74
75impl Middleware<Route, Request, Response, Error> for SecurityAndAudit {
76    fn before(&mut self, _route: &Route, request: &Request) -> Result<(), Error> {
77        self.before_count += 1;
78
79        // 前置处理:Handler 执行前进行权限检查。
80        if !request.authenticated {
81            return Err(Error::Unauthorized);
82        }
83
84        Ok(())
85    }
86
87    fn after(
88        &mut self,
89        _route: &Route,
90        _request: &Request,
91        response: &mut Response,
92    ) -> Result<(), Error> {
93        self.after_count += 1;
94
95        // 后置处理:Handler 成功后加工输出。
96        response.audited = true;
97        Ok(())
98    }
99}
100
101fn main() {
102    let routes = [
103        Route {
104            command: Command::Read,
105            operation: Operation::Read,
106        },
107        Route {
108            command: Command::Write,
109            operation: Operation::Double,
110        },
111    ];
112
113    let middleware = SecurityAndAudit {
114        before_count: 0,
115        after_count: 0,
116    };
117    let mut dispatcher = Dispatcher::new(CommandMatcher, middleware);
118
119    let request = Request {
120        command: Command::Write,
121        authenticated: true,
122        value: 21,
123    };
124
125    // 也可以写成 dispatch_core::dispatch(&mut dispatcher, &routes, &request)。
126    let response = dispatcher.dispatch(&routes, &request).unwrap();
127
128    assert_eq!(
129        response,
130        Response {
131            value: 42,
132            audited: true,
133        }
134    );
135    assert_eq!(dispatcher.middleware().before_count, 1);
136    assert_eq!(dispatcher.middleware().after_count, 1);
137
138    println!("value={}, audited={}", response.value, response.audited);
139}