Move blocking geocding forward resolving to a separate thread

This commit is contained in:
Paul van Tilburg 2022-02-12 15:57:48 +01:00
parent ae2d2c1c56
commit 6b24c4f6e7
Signed by: paul
GPG key ID: C6DE073EDA9EEC4D

View file

@ -14,6 +14,7 @@
use geocoding::{Forward, Openstreetmap, Point}; use geocoding::{Forward, Openstreetmap, Point};
use rocket::serde::json::Json; use rocket::serde::json::Json;
use rocket::serde::Serialize; use rocket::serde::Serialize;
use rocket::tokio;
use rocket::{get, launch, routes, FromFormField}; use rocket::{get, launch, routes, FromFormField};
/// The current for a specific location. /// The current for a specific location.
@ -148,18 +149,22 @@ async fn forecast(lat: f64, lon: f64, metrics: Vec<Metric>) -> Forecast {
} }
/// Retrieves the geocoded position for the given address. /// Retrieves the geocoded position for the given address.
async fn address_position(address: &str) -> Option<(f64, f64)> { async fn address_position(address: String) -> Option<(f64, f64)> {
let osm = Openstreetmap::new(); tokio::task::spawn_blocking(move || {
// FIXME: Handle or log the error. let osm = Openstreetmap::new();
let points: Vec<Point<f64>> = osm.forward(address).ok()?; let points: Vec<Point<f64>> = osm.forward(&address).ok()?;
points.get(0).map(|point| (point.x(), point.y())) points.get(0).map(|point| (point.x(), point.y()))
})
.await
.ok()
.flatten()
} }
/// Handler for retrieving the forecast for an address. /// Handler for retrieving the forecast for an address.
#[get("/forecast?<address>&<metrics>")] #[get("/forecast?<address>&<metrics>")]
async fn forecast_address(address: String, metrics: Vec<Metric>) -> Option<Json<Forecast>> { async fn forecast_address(address: String, metrics: Vec<Metric>) -> Option<Json<Forecast>> {
let (lat, lon) = address_position(&address).await?; let (lat, lon) = address_position(address).await?;
let forecast = forecast(lat, lon, metrics).await; let forecast = forecast(lat, lon, metrics).await;
Some(Json(forecast)) Some(Json(forecast))