From 6b24c4f6e73dd81131afe15124e304a36100e1d3 Mon Sep 17 00:00:00 2001 From: Paul van Tilburg Date: Sat, 12 Feb 2022 15:57:48 +0100 Subject: [PATCH] Move blocking geocding forward resolving to a separate thread --- src/main.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index ecf27ac..8ddf126 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,6 +14,7 @@ use geocoding::{Forward, Openstreetmap, Point}; use rocket::serde::json::Json; use rocket::serde::Serialize; +use rocket::tokio; use rocket::{get, launch, routes, FromFormField}; /// The current for a specific location. @@ -148,18 +149,22 @@ async fn forecast(lat: f64, lon: f64, metrics: Vec) -> Forecast { } /// Retrieves the geocoded position for the given address. -async fn address_position(address: &str) -> Option<(f64, f64)> { - let osm = Openstreetmap::new(); - // FIXME: Handle or log the error. - let points: Vec> = osm.forward(address).ok()?; +async fn address_position(address: String) -> Option<(f64, f64)> { + tokio::task::spawn_blocking(move || { + let osm = Openstreetmap::new(); + let points: Vec> = 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. #[get("/forecast?
&")] async fn forecast_address(address: String, metrics: Vec) -> Option> { - let (lat, lon) = address_position(&address).await?; + let (lat, lon) = address_position(address).await?; let forecast = forecast(lat, lon, metrics).await; Some(Json(forecast))