1pub mod payload;
7pub mod preferences;
8pub mod query_params;
9pub mod types;
10
11pub use preferences::parse_preferences;
12pub use query_params::{parse_query_params, parse_query_params_with, value_is_filter};
13pub use types::*;
14
15use crate::error::{Error, Result};
16use http::{Method, Request};
17use percent_encoding::percent_decode_str;
18use std::collections::{HashMap, HashSet};
19
20pub fn parse_request<B>(
26 req: &Request<B>,
27 default_schema: &str,
28 schemas: &[String],
29 max_rows: Option<i64>,
30) -> Result<ApiRequest>
31where
32 B: AsRef<[u8]>,
33{
34 parse_request_with(req, default_schema, schemas, max_rows, false)
35}
36
37pub fn parse_request_with<B>(
40 req: &Request<B>,
41 default_schema: &str,
42 schemas: &[String],
43 max_rows: Option<i64>,
44 lenient_select: bool,
45) -> Result<ApiRequest>
46where
47 B: AsRef<[u8]>,
48{
49 let method = req.method();
50 let path = req.uri().path();
51 let query = req.uri().query().unwrap_or("");
52
53 let resource = parse_resource(path)?;
55
56 let (schema, negotiated_by_profile) = parse_schema(req, default_schema, schemas)?;
58
59 let action = parse_action(method, &resource, &schema)?;
61
62 let is_rpc = matches!(
68 action,
69 Action::Db(DbAction::Routine {
70 invoke_method: InvokeMethod::InvRead { .. },
71 ..
72 }) | Action::RoutineInfo { .. }
73 );
74 let query_params = parse_query_params_with(query, is_rpc, lenient_select)?;
75
76 let preferences = parse_preferences(req.headers())?;
78
79 let accept_media_types = parse_accept(req.headers())?;
81
82 let content_media_type = parse_content_type(req.headers())?;
84
85 let top_level_range = if method == http::Method::GET {
89 parse_range(req.headers())?
90 } else {
91 Range::default()
92 };
93
94 let headers = extract_headers(req.headers());
96 let cookies = extract_cookies(req.headers());
97
98 Ok(ApiRequest {
99 action,
100 schema,
101 payload: None, query_params,
103 accept_media_types,
104 content_media_type,
105 preferences,
106 columns: HashSet::new(),
107 top_level_range,
108 range_map: HashMap::new(),
109 max_rows,
110 negotiated_by_profile,
111 method: method.to_string(),
112 path: path.to_string(),
113 headers,
114 cookies,
115 trace_id: None,
118 })
119}
120
121fn parse_resource(path: &str) -> Result<Resource> {
123 let path = path.trim_start_matches('/');
124
125 if path.is_empty() {
126 return Ok(Resource::Schema);
127 }
128
129 let path = path.trim_end_matches('/');
131 if path.is_empty() {
132 return Ok(Resource::Schema);
133 }
134
135 let decoded = |segment: &str| -> String {
140 percent_decode_str(segment)
141 .decode_utf8()
142 .map(|name| name.into_owned())
143 .unwrap_or_else(|_| segment.to_string())
144 };
145
146 if let Some(func_name) = path.strip_prefix("rpc/") {
147 if func_name.is_empty() {
148 return Err(Error::InvalidPath("Empty function name".into()));
149 }
150 if func_name.contains('/') {
151 return Err(Error::InvalidResourcePath);
152 }
153 return Ok(Resource::Routine(decoded(func_name)));
154 }
155
156 if path.contains('/') {
161 return Err(Error::InvalidResourcePath);
162 }
163
164 Ok(Resource::Relation(decoded(path)))
165}
166
167fn parse_schema<B>(
169 req: &Request<B>,
170 default_schema: &str,
171 schemas: &[String],
172) -> Result<(String, bool)> {
173 if let Some(profile) = req.headers().get("accept-profile") {
175 let schema = profile
176 .to_str()
177 .map_err(|_| Error::InvalidHeader("Accept-Profile"))?;
178 if !schemas.contains(&schema.to_string()) {
179 return Err(Error::UnacceptableSchema {
180 requested: schema.into(),
181 exposed: schemas.to_vec(),
182 });
183 }
184 return Ok((schema.to_string(), true));
185 }
186
187 if let Some(profile) = req.headers().get("content-profile") {
189 let schema = profile
190 .to_str()
191 .map_err(|_| Error::InvalidHeader("Content-Profile"))?;
192 if !schemas.contains(&schema.to_string()) {
193 return Err(Error::UnacceptableSchema {
194 requested: schema.into(),
195 exposed: schemas.to_vec(),
196 });
197 }
198 return Ok((schema.to_string(), true));
199 }
200
201 Ok((default_schema.to_string(), false))
202}
203
204fn parse_action(method: &Method, resource: &Resource, schema: &str) -> Result<Action> {
206 match (method, resource) {
207 (&Method::GET, Resource::Schema) => Ok(Action::Db(DbAction::SchemaRead {
209 schema: schema.to_string(),
210 headers_only: false,
211 })),
212 (&Method::HEAD, Resource::Schema) => Ok(Action::Db(DbAction::SchemaRead {
213 schema: schema.to_string(),
214 headers_only: true,
215 })),
216 (&Method::OPTIONS, Resource::Schema) => Ok(Action::SchemaInfo),
217
218 (&Method::GET, Resource::Relation(name)) => Ok(Action::Db(DbAction::RelationRead {
220 qi: QualifiedIdentifier::new(schema, name),
221 headers_only: false,
222 })),
223 (&Method::HEAD, Resource::Relation(name)) => Ok(Action::Db(DbAction::RelationRead {
224 qi: QualifiedIdentifier::new(schema, name),
225 headers_only: true,
226 })),
227 (&Method::POST, Resource::Relation(name)) => Ok(Action::Db(DbAction::RelationMut {
228 qi: QualifiedIdentifier::new(schema, name),
229 mutation: Mutation::Create,
230 })),
231 (&Method::PATCH, Resource::Relation(name)) => Ok(Action::Db(DbAction::RelationMut {
232 qi: QualifiedIdentifier::new(schema, name),
233 mutation: Mutation::Update,
234 })),
235 (&Method::PUT, Resource::Relation(name)) => Ok(Action::Db(DbAction::RelationMut {
236 qi: QualifiedIdentifier::new(schema, name),
237 mutation: Mutation::SingleUpsert,
238 })),
239 (&Method::DELETE, Resource::Relation(name)) => Ok(Action::Db(DbAction::RelationMut {
240 qi: QualifiedIdentifier::new(schema, name),
241 mutation: Mutation::Delete,
242 })),
243 (&Method::OPTIONS, Resource::Relation(name)) => {
244 Ok(Action::RelationInfo(QualifiedIdentifier::new(schema, name)))
245 }
246
247 (&Method::GET, Resource::Routine(name)) => Ok(Action::Db(DbAction::Routine {
249 qi: QualifiedIdentifier::new(schema, name),
250 invoke_method: InvokeMethod::InvRead {
251 headers_only: false,
252 },
253 })),
254 (&Method::HEAD, Resource::Routine(name)) => Ok(Action::Db(DbAction::Routine {
255 qi: QualifiedIdentifier::new(schema, name),
256 invoke_method: InvokeMethod::InvRead { headers_only: true },
257 })),
258 (&Method::POST, Resource::Routine(name)) => Ok(Action::Db(DbAction::Routine {
259 qi: QualifiedIdentifier::new(schema, name),
260 invoke_method: InvokeMethod::Inv,
261 })),
262 (&Method::OPTIONS, Resource::Routine(name)) => Ok(Action::RoutineInfo {
263 qi: QualifiedIdentifier::new(schema, name),
264 invoke_method: InvokeMethod::Inv,
265 }),
266
267 (_, Resource::Routine(_)) => Err(Error::InvalidRpcMethod(method.to_string())),
269 _ => Err(Error::UnsupportedMethod(method.to_string())),
270 }
271}
272
273fn parse_accept(headers: &http::HeaderMap) -> Result<Vec<MediaType>> {
275 if let Some(accept) = headers.get(http::header::ACCEPT) {
276 let accept_str = accept
277 .to_str()
278 .map_err(|_| Error::InvalidHeader("Accept"))?;
279 let types: Vec<MediaType> = accept_str
285 .split(',')
286 .map(str::trim)
287 .map(|entry| {
288 let kept: Vec<&str> = entry
289 .split(';')
290 .map(str::trim)
291 .filter(|part| !part.starts_with("q="))
292 .collect();
293 parse_media_type(&kept.join(";"))
294 })
295 .collect();
296 if types.is_empty() {
297 return Ok(vec![MediaType::ApplicationJson]);
298 }
299 return Ok(types);
300 }
301 Ok(vec![MediaType::ApplicationJson])
302}
303
304fn parse_media_type(s: &str) -> MediaType {
309 let mut parts = s.split(';').map(str::trim);
310 let base = parts.next().unwrap_or(s);
311 let parameters: Vec<(String, &str)> = parts
315 .filter_map(|part| part.split_once('='))
316 .map(|(key, value)| {
317 (
318 key.trim().to_ascii_lowercase(),
319 value.trim().trim_matches('"'),
320 )
321 })
322 .collect();
323 let param = |name: &str| {
324 parameters
325 .iter()
326 .find(|(key, _)| key == name)
327 .map(|(_, value)| *value)
328 };
329 let given = |parameter: &str| match parameter.split_once('=') {
330 Some((name, value)) => param(name) == Some(value),
331 None => false,
332 };
333
334 match base {
335 "application/json" => MediaType::ApplicationJson,
336 "application/geo+json" => MediaType::GeoJson,
337 "text/csv" => MediaType::TextCsv,
338 "text/plain" => MediaType::TextPlain,
339 "text/xml" => MediaType::TextXml,
340 "application/openapi+json" => MediaType::OpenApi,
341 "application/x-www-form-urlencoded" => MediaType::UrlEncoded,
342 "application/octet-stream" => MediaType::OctetStream,
343 "*/*" => MediaType::Any,
344 s if s.starts_with("application/vnd.pgrst.plan") => {
351 let format = match s.ends_with("+json") {
352 true => PlanFormat::Json,
353 false => PlanFormat::Text,
354 };
355 let requested = param("options").unwrap_or_default();
356 let options = [
359 ("analyze", PlanOption::Analyze),
360 ("verbose", PlanOption::Verbose),
361 ("settings", PlanOption::Settings),
362 ("buffers", PlanOption::Buffers),
363 ("wal", PlanOption::Wal),
364 ]
365 .into_iter()
366 .filter(|(name, _)| requested.split('|').any(|asked| asked == *name))
367 .map(|(_, option)| option)
368 .collect();
369 MediaType::Plan {
370 base: Box::new(parse_media_type(param("for").unwrap_or("application/json"))),
371 format,
372 options,
373 }
374 }
375 s if s.starts_with("application/vnd.pgrst.object") => MediaType::SingularJson {
376 nullable: given("nulls=null"),
377 strip_nulls: given("nulls=stripped"),
378 },
379 s if s.starts_with("application/vnd.pgrst.array") => MediaType::ArrayJson {
380 strip_nulls: given("nulls=stripped"),
381 },
382 other => MediaType::Other(other.to_string()),
383 }
384}
385
386fn parse_content_type(headers: &http::HeaderMap) -> Result<MediaType> {
388 if let Some(ct) = headers.get(http::header::CONTENT_TYPE) {
389 let ct_str = ct
390 .to_str()
391 .map_err(|_| Error::InvalidHeader("Content-Type"))?;
392 return Ok(parse_media_type(ct_str.trim()));
393 }
394 Ok(MediaType::ApplicationJson)
395}
396
397fn parse_range(headers: &http::HeaderMap) -> Result<Range> {
410 let Some(range) = headers.get(http::header::RANGE) else {
411 return Ok(Range::default());
412 };
413 let range_str = range.to_str().map_err(|_| Error::InvalidHeader("Range"))?;
414
415 let bounds = range_str
418 .split_once('=')
419 .map_or(range_str, |(_unit, bounds)| bounds)
420 .trim();
421
422 let Some((start, end)) = bounds.split_once('-') else {
423 return Ok(Range::default());
424 };
425 let Ok(start) = start.trim().parse::<i64>() else {
426 return Ok(Range::default());
427 };
428 if start < 0 {
429 return Ok(Range::default());
430 }
431
432 let end = end.trim();
433 if end.is_empty() {
434 return Ok(Range::new(start, None));
436 }
437 let Ok(end) = end.parse::<i64>() else {
438 return Ok(Range::default());
439 };
440 if end < start {
441 return Err(Error::InvalidRange(
442 "Requested range not satisfiable".into(),
443 ));
444 }
445
446 Ok(Range::from_bounds(start, Some(end)))
447}
448
449fn extract_headers(headers: &http::HeaderMap) -> indexmap::IndexMap<String, String> {
451 headers
452 .iter()
453 .filter_map(|(k, v)| v.to_str().ok().map(|v| (k.to_string(), v.to_string())))
454 .collect()
455}
456
457fn extract_cookies(headers: &http::HeaderMap) -> indexmap::IndexMap<String, String> {
459 headers
460 .get(http::header::COOKIE)
461 .and_then(|v| v.to_str().ok())
462 .map(|s| {
463 s.split(';')
464 .filter_map(|cookie| {
465 let (key, value) = cookie.trim().split_once('=')?;
466
467 Some((key.to_string(), value.to_string()))
468 })
469 .collect()
470 })
471 .unwrap_or_default()
472}
473
474#[cfg(test)]
475mod tests {
476 use super::*;
477
478 fn range_of(value: &str) -> Result<Range> {
479 let mut headers = http::HeaderMap::new();
480 headers.insert(http::header::RANGE, value.parse().unwrap());
481 parse_range(&headers)
482 }
483
484 #[test]
486 fn a_range_header_names_the_rows_it_says() {
487 assert_eq!(range_of("0-9").unwrap(), Range::from_bounds(0, Some(9)));
488 assert_eq!(range_of("5-9").unwrap(), Range::from_bounds(5, Some(9)));
489 assert_eq!(range_of("10-19").unwrap(), Range::from_bounds(10, Some(19)));
490 assert_eq!(range_of("10-").unwrap(), Range::new(10, None));
492 assert_eq!(range_of("0-").unwrap(), Range::new(0, None));
493 assert_eq!(
495 range_of("items=5-9").unwrap(),
496 Range::from_bounds(5, Some(9))
497 );
498 }
499
500 #[test]
502 fn the_range_header_is_ignored_off_get() {
503 for method in ["POST", "PUT", "PATCH", "DELETE"] {
504 let request = http::Request::builder()
505 .method(method)
506 .uri("/items")
507 .header("Range", "9-5")
508 .body(Vec::<u8>::new())
509 .unwrap();
510 let parsed = parse_request(&request, "public", &["public".to_string()], None).unwrap();
511 assert_eq!(parsed.top_level_range, Range::default(), "{method}");
512 }
513 }
514
515 #[test]
517 fn an_inverted_range_is_refused_rather_than_widened() {
518 assert!(matches!(range_of("9-5"), Err(Error::InvalidRange(_))));
519 }
520
521 #[test]
524 fn a_header_that_is_not_a_range_is_left_alone() {
525 for value in ["", "nonsense", "-5", "a-b", "5"] {
526 assert_eq!(range_of(value).unwrap(), Range::default(), "{value:?}");
527 }
528 }
529
530 #[test]
535 fn a_plan_media_type_is_named_back_in_full() {
536 let named = |s: &str| parse_media_type(s).to_mime();
537
538 assert_eq!(
539 named("application/vnd.pgrst.plan+json"),
540 "application/vnd.pgrst.plan+json; for=\"application/json\""
541 );
542 assert_eq!(
545 named("application/vnd.pgrst.plan+json; for=\"application/vnd.pgrst.object\""),
546 "application/vnd.pgrst.plan+json; for=\"application/vnd.pgrst.object+json\""
547 );
548 assert_eq!(
549 named("application/vnd.pgrst.plan; for=\"text/csv\""),
550 "application/vnd.pgrst.plan+text; for=\"text/csv\""
551 );
552 assert_eq!(
555 named("application/vnd.pgrst.plan+json; options=verbose|analyze|nonsense"),
556 "application/vnd.pgrst.plan+json; for=\"application/json\"; options=analyze|verbose"
557 );
558 }
559
560 #[test]
561 fn test_parse_resource() {
562 assert_eq!(parse_resource("/").unwrap(), Resource::Schema);
563 assert_eq!(
564 parse_resource("/users").unwrap(),
565 Resource::Relation("users".into())
566 );
567 assert_eq!(
568 parse_resource("/rpc/my_func").unwrap(),
569 Resource::Routine("my_func".into())
570 );
571 }
572
573 #[test]
574 fn test_parse_media_type() {
575 assert_eq!(
576 parse_media_type("application/json"),
577 MediaType::ApplicationJson
578 );
579 assert_eq!(parse_media_type("text/csv"), MediaType::TextCsv);
580 assert_eq!(parse_media_type("*/*"), MediaType::Any);
581 }
582}