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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/// Cache control value
///
/// # Examples
///
/// ```rust
/// use async_graphql::*;
///
/// struct Query;
///
/// #[Object(cache_control(max_age = 60))]
/// impl Query {
///     #[graphql(cache_control(max_age = 30))]
///     async fn value1(&self) -> i32 {
///         0
///     }
///
///     #[graphql(cache_control(private))]
///     async fn value2(&self) -> i32 {
///         0
///     }
///
///     #[graphql(cache_control(no_cache))]
///     async fn value3(&self) -> i32 {
///         0
///     }
/// }
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
/// assert_eq!(
///     schema
///         .execute("{ value1 }")
///         .await
///         .into_result()
///         .unwrap()
///         .cache_control,
///     CacheControl {
///         public: true,
///         max_age: 30
///     }
/// );
///
/// assert_eq!(
///     schema
///         .execute("{ value2 }")
///         .await
///         .into_result()
///         .unwrap()
///         .cache_control,
///     CacheControl {
///         public: false,
///         max_age: 60
///     }
/// );
///
/// assert_eq!(
///     schema
///         .execute("{ value1 value2 }")
///         .await
///         .into_result()
///         .unwrap()
///         .cache_control,
///     CacheControl {
///         public: false,
///         max_age: 30
///     }
/// );
///
/// assert_eq!(
///     schema
///         .execute("{ value1 value2 value3 }")
///         .await
///         .into_result()
///         .unwrap()
///         .cache_control,
///     CacheControl {
///         public: false,
///         max_age: -1
///     }
/// );
/// # });
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct CacheControl {
    /// Scope is public, default is true.
    pub public: bool,

    /// Cache max age, `-1` represent `no-cache`, default is 0.
    pub max_age: i32,
}

impl Default for CacheControl {
    fn default() -> Self {
        Self {
            public: true,
            max_age: 0,
        }
    }
}

impl CacheControl {
    /// Get 'Cache-Control' header value.
    #[must_use]
    pub fn value(&self) -> Option<String> {
        let mut value = if self.max_age > 0 {
            format!("max-age={}", self.max_age)
        } else if self.max_age == -1 {
            "no-cache".to_string()
        } else {
            String::new()
        };

        if !self.public {
            if !value.is_empty() {
                value += ", ";
            }
            value += "private";
        }

        if !value.is_empty() {
            Some(value)
        } else {
            None
        }
    }
}

impl CacheControl {
    #[must_use]
    pub(crate) fn merge(self, other: &CacheControl) -> CacheControl {
        CacheControl {
            public: self.public && other.public,
            max_age: match (self.max_age, other.max_age) {
                (-1, _) => -1,
                (_, -1) => -1,
                (a, 0) => a,
                (0, b) => b,
                (a, b) => a.min(b),
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn to_value() {
        assert_eq!(
            CacheControl {
                public: true,
                max_age: 0,
            }
            .value(),
            None
        );

        assert_eq!(
            CacheControl {
                public: false,
                max_age: 0,
            }
            .value(),
            Some("private".to_string())
        );

        assert_eq!(
            CacheControl {
                public: false,
                max_age: 10,
            }
            .value(),
            Some("max-age=10, private".to_string())
        );

        assert_eq!(
            CacheControl {
                public: true,
                max_age: 10,
            }
            .value(),
            Some("max-age=10".to_string())
        );

        assert_eq!(
            CacheControl {
                public: true,
                max_age: -1,
            }
            .value(),
            Some("no-cache".to_string())
        );

        assert_eq!(
            CacheControl {
                public: false,
                max_age: -1,
            }
            .value(),
            Some("no-cache, private".to_string())
        );
    }
}