BlueGit

ict rusty-teams

Files

rusty-teams / crates / session / src / request.rs

request.rs

request.rs 7.6 KiB Download Raw
1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum Method {
6 Get,
7 Post,
8 Put,
9 Patch,
10 Delete,
11}
12
13impl Method {
14 pub fn as_str(self) -> &'static str {
15 match self {
16 Method::Get => "GET",
17 Method::Post => "POST",
18 Method::Put => "PUT",
19 Method::Patch => "PATCH",
20 Method::Delete => "DELETE",
21 }
22 }
23}
24
25#[derive(Debug, Clone)]
26pub struct Request {
27 pub method: Method,
28 pub url: String,
29 pub headers: Vec<(String, String)>,
30 pub body: Option<Value>,
31 pub binary: bool,
32 pub anonymous: bool,
33 pub body_base64: Option<String>,
34}
35
36impl Request {
37 /// A successful answer carries `{"base64": .., "contentType": ..}` as its body.
38 pub fn binary_get(url: impl Into<String>) -> Self {
39 Request {
40 binary: true,
41 ..Request::get(url)
42 }
43 }
44
45 pub fn get(url: impl Into<String>) -> Self {
46 Request {
47 method: Method::Get,
48 url: url.into(),
49 headers: Vec::new(),
50 body: None,
51 binary: false,
52 anonymous: false,
53 body_base64: None,
54 }
55 }
56
57 /// Sent without an Authorization header, for pre-authenticated URLs such as upload sessions.
58 pub fn anonymous_bytes(method: Method, url: impl Into<String>, headers: Vec<(String, String)>, body_base64: String) -> Self {
59 Request {
60 method,
61 headers,
62 anonymous: true,
63 body_base64: Some(body_base64),
64 ..Request::get(url)
65 }
66 }
67
68 /// Sent without an Authorization header; a successful answer carries `{"base64": .., "contentType": ..}`.
69 pub fn anonymous_binary_get(url: impl Into<String>, headers: Vec<(String, String)>) -> Self {
70 Request {
71 headers,
72 anonymous: true,
73 ..Request::binary_get(url)
74 }
75 }
76
77 pub fn delete(url: impl Into<String>) -> Self {
78 Request {
79 method: Method::Delete,
80 ..Request::get(url)
81 }
82 }
83
84 pub fn with_body(method: Method, url: impl Into<String>, body: Value) -> Self {
85 Request {
86 method,
87 url: url.into(),
88 headers: Vec::new(),
89 body: Some(body),
90 binary: false,
91 anonymous: false,
92 body_base64: None,
93 }
94 }
95}
96
97#[derive(Debug, Clone)]
98pub struct ApiResponse {
99 pub status: u16,
100 pub body: Value,
101 pub retry_after: Option<String>,
102}
103
104impl ApiResponse {
105 pub fn is_success(&self) -> bool {
106 (200..400).contains(&self.status)
107 }
108}
109
110#[derive(Debug, Serialize)]
111pub(crate) struct WireRequest<'a> {
112 pub method: &'static str,
113 pub url: &'a str,
114 pub headers: serde_json::Map<String, Value>,
115 pub body: Option<String>,
116 #[serde(rename = "bodyBase64")]
117 pub body_base64: Option<&'a str>,
118 pub binary: bool,
119 pub anonymous: bool,
120}
121
122impl<'a> From<&'a Request> for WireRequest<'a> {
123 fn from(request: &'a Request) -> Self {
124 let mut headers: serde_json::Map<String, Value> = request
125 .headers
126 .iter()
127 .map(|(name, value)| (name.clone(), Value::String(value.clone())))
128 .collect();
129 if request.body.is_some() && !headers.keys().any(|name| name.eq_ignore_ascii_case("content-type")) {
130 headers.insert("Content-Type".into(), "application/json".into());
131 }
132 WireRequest {
133 method: request.method.as_str(),
134 url: &request.url,
135 headers,
136 body: request.body.as_ref().map(Value::to_string),
137 body_base64: request.body_base64.as_deref(),
138 binary: request.binary,
139 anonymous: request.anonymous,
140 }
141 }
142}
143
144#[derive(Debug, Deserialize)]
145pub(crate) struct WireResult {
146 pub status: u16,
147 #[serde(default)]
148 pub body: Value,
149 #[serde(default, rename = "retryAfter")]
150 pub retry_after: Option<String>,
151}
152
153#[derive(Debug, Deserialize)]
154pub(crate) struct Outcome {
155 pub results: Option<Vec<WireResult>>,
156 #[serde(default, rename = "refreshError")]
157 pub refresh_error: Option<String>,
158}
159
160impl From<WireResult> for ApiResponse {
161 fn from(wire: WireResult) -> Self {
162 ApiResponse {
163 status: wire.status,
164 body: wire.body,
165 retry_after: wire.retry_after,
166 }
167 }
168}
169
170#[cfg(test)]
171mod tests {
172 use serde_json::json;
173
174 use super::*;
175
176 #[test]
177 fn json_body_gets_content_type() {
178 let request = Request::with_body(Method::Post, "https://graph.microsoft.com/v1.0/x", json!({"a": 1}));
179 let wire = WireRequest::from(&request);
180 assert_eq!(wire.method, "POST");
181 assert_eq!(wire.body.as_deref(), Some(r#"{"a":1}"#));
182 assert_eq!(wire.headers["Content-Type"], "application/json");
183 }
184
185 #[test]
186 fn explicit_content_type_is_kept() {
187 let mut request = Request::with_body(Method::Post, "u", json!({}));
188 request.headers.push(("content-type".into(), "text/plain".into()));
189 let wire = WireRequest::from(&request);
190 assert_eq!(wire.headers.len(), 1);
191 }
192
193 #[test]
194 fn binary_get_is_flagged_on_the_wire() {
195 let request = Request::binary_get("u");
196 assert!(WireRequest::from(&request).binary);
197 assert!(!WireRequest::from(&Request::get("u")).binary);
198 }
199
200 #[test]
201 fn anonymous_bytes_travel_as_base64_without_a_content_type() {
202 let request = Request::anonymous_bytes(
203 Method::Put,
204 "https://upload.example/session",
205 vec![("Content-Range".into(), "bytes 0-2/3".into())],
206 "AQID".into(),
207 );
208 let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
209 assert_eq!(wire["method"], "PUT");
210 assert_eq!(wire["anonymous"], true);
211 assert_eq!(wire["bodyBase64"], "AQID");
212 assert_eq!(wire["body"], Value::Null);
213 assert!(wire["headers"].get("Content-Type").is_none());
214 assert_eq!(wire["headers"]["Content-Range"], "bytes 0-2/3");
215 }
216
217 #[test]
218 fn anonymous_binary_get_keeps_range_header_and_flags() {
219 let request = Request::anonymous_binary_get("https://download.example/file", vec![("Range".into(), "bytes=0-9".into())]);
220 let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
221 assert_eq!(wire["method"], "GET");
222 assert_eq!(wire["anonymous"], true);
223 assert_eq!(wire["binary"], true);
224 assert_eq!(wire["bodyBase64"], Value::Null);
225 assert_eq!(wire["headers"]["Range"], "bytes=0-9");
226 }
227
228 #[test]
229 fn get_has_no_body() {
230 let request = Request::get("u");
231 let wire = WireRequest::from(&request);
232 assert!(wire.body.is_none() && wire.headers.is_empty());
233 }
234
235 #[test]
236 fn parses_results_outcome() {
237 let outcome: Outcome = serde_json::from_value(json!({
238 "results": [{"status": 200, "retryAfter": null, "body": {"value": []}}, {"status": 429, "retryAfter": "4", "body": "slow"}]
239 }))
240 .unwrap();
241 let responses: Vec<ApiResponse> = outcome.results.unwrap().into_iter().map(Into::into).collect();
242 assert_eq!(responses[0].status, 200);
243 assert_eq!(responses[1].retry_after.as_deref(), Some("4"));
244 assert!(!responses[1].is_success());
245 }
246
247 #[test]
248 fn parses_no_token_outcome() {
249 let outcome: Outcome =
250 serde_json::from_value(json!({"noToken": true, "refreshError": "invalid_grant"})).unwrap();
251 assert!(outcome.results.is_none());
252 assert_eq!(outcome.refresh_error.as_deref(), Some("invalid_grant"));
253 }
254}