1use std::sync::Arc;
2
3use crate::balancing::{Balancer, ConsistentHash, LeastRequest, LeastTime, RoundRobin};
4use crate::routing::{HeaderSticky, NoRouteKey, PathSticky, RouteStrategy};
5
6pub struct Policy {
7 pub router: Arc<dyn RouteStrategy>,
8 pub balancer: Arc<dyn Balancer>,
9}
10
11impl Policy {
12 pub fn new() -> Self {
14 Self {
15 router: Arc::new(NoRouteKey),
16 balancer: Arc::new(RoundRobin::new()),
17 }
18 }
19
20 pub fn header_sticky(header: &'static str) -> Self {
22 Self::new()
23 .router(HeaderSticky::new(header))
24 .balancer(ConsistentHash::new())
25 }
26
27 pub fn path_sticky(param: &'static str) -> Self {
29 Self::new()
30 .router(PathSticky::new(param))
31 .balancer(ConsistentHash::new())
32 }
33
34 pub fn consistent_hash() -> Self {
36 Self::new().balancer(ConsistentHash::new())
37 }
38
39 pub fn least_request() -> Self {
41 Self::new().balancer(LeastRequest::new())
42 }
43
44 pub fn least_time() -> Self {
46 Self::new().balancer(LeastTime::new())
47 }
48
49 pub fn round_robin() -> Self {
51 Self::new().balancer(RoundRobin::new())
52 }
53
54 pub fn router<R>(mut self, router: R) -> Self
55 where
56 R: RouteStrategy,
57 {
58 self.router = Arc::new(router);
59 self
60 }
61
62 pub fn balancer<B>(mut self, balancer: B) -> Self
63 where
64 B: Balancer,
65 {
66 self.balancer = Arc::new(balancer);
67 self
68 }
69}
70
71impl Default for Policy {
72 fn default() -> Self {
73 Self::new()
74 }
75}