Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch to bitmap markers to increase performance #42

Merged
merged 3 commits into from
Jun 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
332 changes: 332 additions & 0 deletions backend/Cargo.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,5 @@ reqwest = { version = "0.12", features = [
"json",
"rustls-tls",
], default-features = false }
tiny-skia = { version = "0.11.4", features = ["png-format"] }
resvg = "0.42.0"
2 changes: 2 additions & 0 deletions backend/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ pub enum AppError {
Validation(String),
Database(sqlx::Error),
InvalidPagination,
Internal(Option<String>),
}

#[derive(FromRequest)]
Expand Down Expand Up @@ -256,6 +257,7 @@ impl IntoResponse for AppError {
},
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized", None),
AppError::InvalidPagination => (StatusCode::BAD_REQUEST, "invalid_pagination", None),
AppError::Internal(e) => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error", e),
};

let resp = (
Expand Down
241 changes: 199 additions & 42 deletions backend/src/api/icons.rs
Original file line number Diff line number Diff line change
@@ -1,61 +1,218 @@
use std::sync::Arc;

use crate::{api::AppState, models::icon::Icon};
use axum::{
extract::{Path, State},
extract::{Path, Query, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::{get, Router},
Json,
};
use serde_json::json;
use resvg::{tiny_skia, usvg, usvg::ImageHrefResolver};
use serde::Deserialize;
use usvg::ImageKind::{JPEG, PNG, SVG};

use sqlx::{pool::PoolConnection, Postgres};
use tiny_skia::{Pixmap, Transform};
use usvg::{Options, Tree};

use super::DbConn;
use super::{AppError, DbConn};

pub fn routes() -> Router<AppState> {
Router::new().route("/:hash", get(get_icon))
Router::new()
.route("/:hash", get(get_icon))
.route("/pin", get(get_pin))
}

async fn get_icon_internal(
state: &AppState,
hash: String,
conn: &mut PoolConnection<Postgres>,
) -> Result<(Vec<u8>, String), AppError> {
// Check cache firsts
if let Some(icon) = state.icon_cache.read().await.get(&hash) {
return Ok(icon.clone());
}

// If not found in cache, query the database
let icon = Icon::get(hash.clone(), conn).await?;
let icon = (icon.data, icon.http_mime_type);

// Update cache
state.icon_cache.write().await.insert(hash, icon.clone());

Ok(icon)
}

async fn get_icon(
State(state): State<AppState>,
DbConn(mut conn): DbConn,
Path(hash): Path<String>,
) -> Response {
// Check cache firsts
if let Some(icon) = state.icon_cache.read().await.get(&hash) {
return (
StatusCode::OK,
[
("Content-Type", icon.1.clone()),
("Cache-Control", "public, max-age=31536000".to_owned()),
],
icon.0.clone(),
)
.into_response();
) -> Result<Response, AppError> {
let (data, mime_type) = get_icon_internal(&state, hash, &mut conn).await?;

Ok((
StatusCode::OK,
[
("Content-Type", mime_type),
("Cache-Control", "public, max-age=31536000".to_owned()),
],
data,
)
.into_response())
}

#[derive(Deserialize, Debug)]
pub struct RenderQuery {
pub h: Option<u32>,
pub w: Option<u32>,
pub bc: Option<String>,
pub fc: Option<String>,
pub ih: Option<String>,
}

async fn get_pin(
State(state): State<AppState>,
DbConn(mut conn): DbConn,
Query(query): Query<RenderQuery>,
) -> Result<Response, AppError> {
let (border_color, fill_color, icon_hash) = (
format!("#{}", query.bc.as_deref().unwrap_or("222222")),
format!("#{}", query.fc.as_deref().unwrap_or("9999FF")),
query.ih,
);

let icon = match icon_hash {
None => None,
Some(icon_hash) => Some(get_icon_internal(&state, icon_hash, &mut conn).await?),
};

if query.h > Some(100) || query.w > Some(100) {
return Err(AppError::Validation("invalid_size".to_string()));
}

// If not found in cache, query the database
match Icon::get(hash.clone(), &mut conn).await {
Ok(icon) => {
// Update cache
state
.icon_cache
.write()
.await
.insert(hash, (icon.data.clone(), icon.http_mime_type.clone()));

(
StatusCode::OK,
[
("Content-Type", icon.http_mime_type.clone()),
("Cache-Control", "public, max-age=31536000".to_owned()),
],
icon.data,
)
.into_response()
let icon_svg = match icon.as_ref() {
None => "".to_owned(),
Some(_) => r#"
<image
x="9"
y="9"
width="26"
height="26"
xlink:href="icon"
/>
"#
.to_owned(),
};
let pin_svg = format!(
r#"
<svg
version="1.1"
viewBox="0 0 44 67"
xml:space="preserve"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
>
<path
d="m21.905 1.2688c-11.397-1.86e-5 -20.637 9.5307-20.636
21.287 0.00476 3.5178 0.85467 6.9796 2.4736 10.076 5.9268 10.527 12.063 21.068 18.111
31.572 5.8042-10.829 13.224-21.769 18.766-32.581
1.4143-2.9374 1.9205-5.7872 1.9231-9.0669 6.2e-5 -11.757-9.2392-21.287-20.636-21.287z"
fill="{fill_color}"
stroke="{border_color}"
stroke-width="2.5"
/>
{icon_svg}
</svg>
"#
);

let mut opt = Options::default();

// We know that our SVG won't have DataUrl hrefs, just return None for such case.
let resolve_data = Box::new(|_: &str, _: std::sync::Arc<Vec<u8>>, _: &usvg::Options| None);

let parsed_image = if let Some((data, mime)) = icon {
match mime.as_str() {
"image/png" => Some(PNG(Arc::new(data.clone()))),
"image/jpeg" => Some(JPEG(Arc::new(data.clone()))),
"image/svg+xml" => {
let tree: Tree = match Tree::from_data(&data, &Options::default()) {
Ok(tree) => tree,
Err(_) => {
return Err(AppError::Internal(Some("svg_renderer_failed".to_string())))
}
};
Some(SVG(tree))
}
_ => None,
}
Err(_) => (
StatusCode::NOT_FOUND,
Json(json!({"error": "Icon not found"})),
)
.into_response(),
}
} else {
None
};

let resolve_string = Box::new(move |href: &str, _: &Options| {
if let Some(parsed_image) = parsed_image.as_ref() {
match href {
"icon" => Some(parsed_image.clone()),
_ => None,
}
} else {
None
}
});

// Assign new ImageHrefResolver option using our closures.
opt.image_href_resolver = ImageHrefResolver {
resolve_data,
resolve_string,
};

let tree = match Tree::from_str(&pin_svg, &opt) {
Ok(tree) => tree,
Err(_) => return Err(AppError::Internal(Some("svg_renderer_failed".to_string()))),
};

let pixmap_size = tree.size().to_int_size();

let (height, width, scale) = match (query.h, query.w) {
(Some(h), Some(w)) => (h, w, None),
(Some(h), None) => {
let scale = h as f32 / pixmap_size.height() as f32;
(h, (pixmap_size.width() as f32 * scale) as u32, Some(scale))
}
(None, Some(w)) => {
let scale = w as f32 / pixmap_size.width() as f32;
((pixmap_size.height() as f32 * scale) as u32, w, Some(scale))
}
_ => (38, 24, None),
};

let scale_x = scale.unwrap_or(width as f32 / pixmap_size.width() as f32);
let scale_y = scale.unwrap_or(height as f32 / pixmap_size.height() as f32);
let transform = Transform::from_scale(scale_x, scale_y);

let mut pixmap = match Pixmap::new(width, height) {
Some(pixmap) => pixmap,
None => {
return Err(AppError::Internal(Some(
"pixmap_creation_failed".to_string(),
)))
}
};

resvg::render(&tree, transform, &mut pixmap.as_mut());
let image_data = match pixmap.encode_png() {
Ok(image_data) => image_data,
Err(_) => return Err(AppError::Internal(Some("png_encoding_failed".to_string()))),
};

Ok((
StatusCode::OK,
[
("Content-Type", "image/png"),
("Cache-Control", "public, max-age=31536000"),
],
image_data,
)
.into_response())
}
12 changes: 12 additions & 0 deletions backend/src/models/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,14 @@ pub struct CartographyInitConfig {
pub center_lng: f64,
/// Zoom level of the map (from 2 to 20)
pub zoom: u8,
/// Light mode map url
pub light_map_url: String,
/// Dark mode map url
pub dark_map_url: String,
/// Light mode map attributions
pub light_map_attributions: String,
/// Dark mode map attributions
pub dark_map_attributions: String,
}

impl OptionConfig for CartographyInitConfig {
Expand All @@ -121,6 +129,10 @@ impl Default for CartographyInitConfig {
center_lat: 47.0,
center_lng: 2.0,
zoom: 5,
light_map_url: "https://tile.openstreetmap.org/{z}/{x}/{y}.png".to_string(),
light_map_attributions: "Map data © OpenStreetMap contributors".to_string(),
dark_map_url: "https://tile.openstreetmap.org/{z}/{x}/{y}.png".to_string(),
dark_map_attributions: "Map data © OpenStreetMap contributors".to_string(),
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@

# When modifying cargo dependencies, replace the hash with pkgs.lib.fakeSha256
# then run `nix build .#backend`. Use the hash in the error to replace the value.
cargoSha256 = "sha256-uBZXAEDMg2OAcOkj+RbQBPFZFM3hELtk6gZHv0xfxfE=";
cargoSha256 = "sha256-0Rkyor7BXLI8+VZUVFqp1wMvHhBhy7sQSeOvZC8yIgE=";
};

# Frontend derivation
Expand All @@ -190,7 +190,7 @@

# When modifying npm dependencies, replace the hash with pkgs.lib.fakeSha256
# then run `nix build .#frontend`. Use the hash in the error to replace the value.
npmDepsHash = "sha256-KRg9OKedgo+wMQTNsEtTHaxrCZII5RqIJkF0aQxmkb8=";
npmDepsHash = "sha256-btoUwnmxoCO+vetf2uDxdN/nw3YF6H/ERLtIEtksW3A=";

installPhase = ''
runHook preInstall
Expand Down
4 changes: 1 addition & 3 deletions frontend/components/NominatimPicker.vue
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@
class="!h-80"
:coordinates="transformedCoordinates"
:locked="false"
fill-color="#9999FF"
border-color="#222222"
:icon-hash="null"
category-id="default"
:zoom="10"
/>
<small class="text-secondary flex ">Addresse : {{ results[0].display_name }}</small>
Expand Down
11 changes: 1 addition & 10 deletions frontend/components/SingleEntityMap.vue
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,7 @@
:callback-item="null"
:width="24"
:height="38"
:fill="props.fillColor"
:stroke="props.borderColor"
:highlighted="false"
:icon-url="iconUrl"
/>
</ol-overlay>
</ol-map>
Expand All @@ -43,16 +40,10 @@ import type { Coordinate } from 'ol/coordinate'

const props = defineProps<{
coordinates: Coordinate
fillColor: string
borderColor: string
iconHash: string | null | undefined
categoryId: string
zoom: number
locked: boolean
}>()

const iconUrl = computed(() => {
return props.iconHash ? `/api/icons/${props.iconHash}` : null
})
</script>

<style scoped lang="scss">
Expand Down
1 change: 0 additions & 1 deletion frontend/components/viewer/EntityAddForm.vue
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,6 @@ const commentFieldValid = ref(
)

function reset_refs() {
console.log('hein pq fail le captcha switch la famille')
editedEntity.value = {
category_id: '',
data: {},
Expand Down
2 changes: 1 addition & 1 deletion frontend/components/viewer/FullResult.vue
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
:coordinates="[props.entity.web_mercator_x, props.entity.web_mercator_y]"
:fill-color="state.getCategory(props.entity.category_id).fill_color"
:border-color="state.getCategory(props.entity.category_id).fill_color"
:icon-hash="state.getCategory(props.entity.category_id).icon_hash"
:category-id="props.entity.category_id"
:zoom="13"
:locked="true"
/>
Expand Down
Loading
Loading