From 09f0957b36cf1b4e9a89f5594df51a853d0dfffe Mon Sep 17 00:00:00 2001 From: Quentin Gliech Date: Thu, 18 Apr 2024 12:20:30 +0200 Subject: Helpers to transform Twisted requests to Rust http Requests/Responses (#17081) This adds functions to transform a Twisted request to the `http::Request`, and then to send back an `http::Response` through it. It also imports the SynapseError exception so that we can throw that from Rust code directly Example usage of this would be: ```rust use crate::http::{http_request_from_twisted, http_response_to_twisted, HeaderMapPyExt}; fn handler(twisted_request: &PyAny) -> PyResult<()> { let request = http_request_from_twisted(twisted_request)?; let ua: headers::UserAgent = request.headers().typed_get_required()?; if whatever { return Err((crate::errors::SynapseError::new( StatusCode::UNAUTHORIZED, "Whatever".to_owned "M_UNAUTHORIZED", None, None, ))); } let response = Response::new("hello".as_bytes()); http_response_to_twisted(twisted_request, response)?; Ok(()) } ``` --- rust/src/errors.rs | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 rust/src/errors.rs (limited to 'rust/src/errors.rs') diff --git a/rust/src/errors.rs b/rust/src/errors.rs new file mode 100644 index 0000000000..4e580e3e8c --- /dev/null +++ b/rust/src/errors.rs @@ -0,0 +1,60 @@ +/* + * This file is licensed under the Affero General Public License (AGPL) version 3. + * + * Copyright (C) 2024 New Vector, Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * See the GNU Affero General Public License for more details: + * . + */ + +#![allow(clippy::new_ret_no_self)] + +use std::collections::HashMap; + +use http::{HeaderMap, StatusCode}; +use pyo3::{exceptions::PyValueError, import_exception}; + +import_exception!(synapse.api.errors, SynapseError); + +impl SynapseError { + pub fn new( + code: StatusCode, + message: String, + errcode: &'static str, + additional_fields: Option>, + headers: Option, + ) -> pyo3::PyErr { + // Transform the HeaderMap into a HashMap + let headers = if let Some(headers) = headers { + let mut map = HashMap::with_capacity(headers.len()); + for (key, value) in headers.iter() { + let Ok(value) = value.to_str() else { + // This should never happen, but we don't want to panic in case it does + return PyValueError::new_err( + "Could not construct SynapseError: header value is not valid ASCII", + ); + }; + + map.insert(key.as_str().to_owned(), value.to_owned()); + } + Some(map) + } else { + None + }; + + SynapseError::new_err((code.as_u16(), message, errcode, additional_fields, headers)) + } +} + +import_exception!(synapse.api.errors, NotFoundError); + +impl NotFoundError { + pub fn new() -> pyo3::PyErr { + NotFoundError::new_err(()) + } +} -- cgit 1.5.1