diff --git a/src/config.rs b/src/config.rs index 54749cf..72c7208 100644 --- a/src/config.rs +++ b/src/config.rs @@ -36,6 +36,8 @@ pub struct Config { pub tile_fetch_max_attempts: u32, /// Delay before the first retry, doubling for each further attempt. pub tile_fetch_retry_base_ms: u64, + /// Optional 8-neighbor median deviation threshold in metres (Issue #55). + pub plausibility_max_deviation_m: Option, } // Initialize dotenv and config only once @@ -77,6 +79,7 @@ pub static CONFIG: Lazy = Lazy::new(|| { status_probe_timeout_ms: parse_env_var::("STATUS_PROBE_TIMEOUT_MS").unwrap_or(3000), tile_fetch_max_attempts: parse_env_var::("TILE_FETCH_MAX_ATTEMPTS").unwrap_or(3), tile_fetch_retry_base_ms: parse_env_var::("TILE_FETCH_RETRY_BASE_MS").unwrap_or(100), + plausibility_max_deviation_m: parse_env_var::("PLAUSIBILITY_MAX_DEVIATION_M"), } }); diff --git a/src/handlers.rs b/src/handlers.rs index 0d9488d..989a0c3 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -8,13 +8,13 @@ use std::{ time::Duration, }; use tokio::sync::Semaphore; -use tracing::{error, info, instrument, warn}; +use tracing::{debug, error, info, instrument, warn}; use warp::{Rejection, Reply, filters::path::FullPath, reply}; use crate::{ config::Config, tileset::TileSetWithCache, - types::{ElevationResponse, LatLng, LatLngs, StatusResponse}, + types::{BatchQuery, ElevationResponse, LatLng, LatLngs, StatusResponse}, }; #[derive(Debug)] @@ -192,19 +192,25 @@ pub async fn get_elevation( let elevation = match tileset.get_elevation(query.lat, query.lng).await { Ok(elevation) => { info!(elevation = elevation, "Elevation retrieved successfully"); - elevation + Some(elevation) } Err(e) => { - error!(error = %e, "Failed to get elevation"); - return Ok(convert_io_error_to_warp_replay(e).into_response()); + if query.nulls && e.kind() == ErrorKind::NotFound { + debug!(error = %e, "Returning null for single elevation request with nulls=true"); + None + } else { + error!(error = %e, "Failed to get elevation"); + return Ok(convert_io_error_to_warp_replay(e).into_response()); + } } }; Ok(reply::json(&elevation).into_response()) } -#[instrument(skip_all, fields(points_count = locations.latlngs.len()))] +#[instrument(skip_all, fields(points_count = locations.latlngs.len(), nulls = query.nulls))] pub async fn post_elevations( + query: BatchQuery, locations: LatLngs, tileset: Arc, config: Config, @@ -234,17 +240,34 @@ pub async fn post_elevations( .collect::>() .await; - let mut elevations = Vec::new(); + let mut elevations = Vec::with_capacity(results.len()); + let mut null_reasons = Vec::new(); for result in results { match result { - Ok(elevation) => elevations.push(elevation), + Ok(elevation) => elevations.push(Some(elevation)), Err(e) => { - error!(error = %e, "Failed to get elevation in batch request"); - return Ok(convert_io_error_to_warp_replay(e).into_response()); + if query.nulls { + if null_reasons.len() < 5 { + null_reasons.push(e.to_string()); + } + elevations.push(None); + } else { + error!(error = %e, "Failed to get elevation in batch request"); + return Ok(convert_io_error_to_warp_replay(e).into_response()); + } } } } + if query.nulls && !null_reasons.is_empty() { + let null_count = elevations.iter().filter(|e| e.is_none()).count(); + debug!( + null_count, + sample_reasons = ?null_reasons, + "Batch request with nulls=true mapped failing points to null" + ); + } + info!( elevations_count = elevations.len(), "Batch elevation request completed" diff --git a/src/main.rs b/src/main.rs index be9129b..a5c8f33 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,7 +5,7 @@ use crate::{ }, telemetry::init_telemetry, tileset::{TileSetOptions, TileSetWithCache}, - types::{LatLng, LatLngs}, + types::{BatchQuery, LatLng, LatLngs}, }; use std::{sync::Arc, time::Duration}; use tokio::sync::Semaphore; @@ -97,6 +97,7 @@ async fn async_main() -> Result<(), Box> { s3_endpoint: config.s3_endpoint.clone(), max_fetch_attempts: config.tile_fetch_max_attempts, retry_base_delay: Duration::from_millis(config.tile_fetch_retry_base_ms), + plausibility_max_deviation_m: config.plausibility_max_deviation_m, }; let tileset = Arc::new(TileSetWithCache::new(options)?); @@ -144,6 +145,7 @@ async fn async_main() -> Result<(), Box> { // Define the POST route for elevations let post_elevation_route = warp::path::end() .and(warp::post()) + .and(warp::query::()) .and(warp::body::content_length_limit(max_post_size.as_u64())) .and(warp::body::json::()) .and(tileset_filter.clone()) @@ -152,6 +154,7 @@ async fn async_main() -> Result<(), Box> { .and_then(post_elevations) .or(warp::path("api") .and(warp::post()) + .and(warp::query::()) .and(warp::body::content_length_limit(max_post_size.as_u64())) .and(warp::body::json::()) .and(tileset_filter.clone()) diff --git a/src/tileset.rs b/src/tileset.rs index 75f9b5a..d46e23e 100644 --- a/src/tileset.rs +++ b/src/tileset.rs @@ -28,6 +28,8 @@ pub struct TileSetOptions { pub max_fetch_attempts: u32, /// Delay before the first retry; doubles for each further attempt. pub retry_base_delay: Duration, + /// Optional 8-neighbor median deviation threshold in metres (Issue #55). + pub plausibility_max_deviation_m: Option, } impl Default for TileSetOptions { @@ -42,6 +44,7 @@ impl Default for TileSetOptions { s3_endpoint: None, max_fetch_attempts: 3, retry_base_delay: Duration::from_millis(100), + plausibility_max_deviation_m: None, } } } @@ -87,13 +90,19 @@ impl TileSet { pub struct TileSetWithCache { tileset: TileSet, hgt_cache: Cache<(i32, i32), Arc>, // Cache HGT instances instead of raw tile data + plausibility_max_deviation_m: Option, } impl TileSetWithCache { pub fn new(options: TileSetOptions) -> Result> { + let plausibility_max_deviation_m = options.plausibility_max_deviation_m; let tileset = TileSet::new(options.clone())?; let hgt_cache = Cache::new(options.cache_size); - Ok(Self { tileset, hgt_cache }) + Ok(Self { + tileset, + hgt_cache, + plausibility_max_deviation_m, + }) } /// Maps a coordinate to its tile file name. @@ -158,7 +167,11 @@ impl TileSetWithCache { debug!("Loading tile data from cache or source"); // Load tile data and create HGT instance let tile_data = self.get_tile_data(lat_floor, lng_floor).await?; - let hgt = HGT::new(tile_data, (lat_floor, lng_floor))?; + let hgt = HGT::with_plausibility( + tile_data, + (lat_floor, lng_floor), + self.plausibility_max_deviation_m, + )?; info!(lat_floor, lng_floor, "Loaded and cached HGT tile"); Ok::, tokio::io::Error>(Arc::new(hgt)) }) diff --git a/src/tileset/hgt.rs b/src/tileset/hgt.rs index 3410bd8..b6b2cf1 100644 --- a/src/tileset/hgt.rs +++ b/src/tileset/hgt.rs @@ -1,16 +1,36 @@ use std::io::{Error, ErrorKind}; use tracing::{debug, instrument}; +/// Standard SRTM void sentinel (-32768 / 0x8000) and positive int16 clamp +/// sentinel (+32767 / 0x7fff) produced by `tilezen/joerd` when converting +/// float32 USGS NED coastal nodata masks into big-endian HGT tiles (Issue #21, #50, #55). +const VOID_MIN: i16 = i16::MIN; // -32768 +const VOID_MAX: i16 = i16::MAX; // +32767 + +#[inline] +fn is_void_sample(value: i16) -> bool { + value == VOID_MIN || value == VOID_MAX +} + #[derive(Debug, Clone)] pub struct HGT { buffer: Vec, sw_lat_lng: (f64, f64), size: usize, + plausibility_max_deviation_m: Option, } impl HGT { #[instrument(level="debug", skip_all, fields(coord = format!("{},{}", sw_lat_lng.0, sw_lat_lng.1)))] pub fn new(buffer: Vec, sw_lat_lng: (f64, f64)) -> Result { + Self::with_plausibility(buffer, sw_lat_lng, None) + } + + pub fn with_plausibility( + buffer: Vec, + sw_lat_lng: (f64, f64), + plausibility_max_deviation_m: Option, + ) -> Result { let size; let resolution; @@ -40,6 +60,7 @@ impl HGT { buffer, sw_lat_lng, size, + plausibility_max_deviation_m, }) } @@ -64,47 +85,96 @@ impl HGT { #[instrument(skip_all, fields(row, col), level = "trace")] fn interpolation(&self, row: f64, col: f64) -> Result { - let row_low = row.floor(); - let row_high = row_low + 1.0; + let max_idx = (self.size - 1) as f64; + let row_low = row.floor().min(max_idx); + let row_high = (row_low + 1.0).min(max_idx); let row_frac = row - row_low; - let col_low = col.floor(); - let col_high = col_low + 1.0; + let col_low = col.floor().min(max_idx); + let col_high = (col_low + 1.0).min(max_idx); let col_frac = col - col_low; let value_low_low = HGT::get_row_col_value(self, row_low, col_low)?; let value_low_high = HGT::get_row_col_value(self, row_low, col_high)?; let value_high_low = HGT::get_row_col_value(self, row_high, col_low)?; let value_high_high = HGT::get_row_col_value(self, row_high, col_high)?; - let value_low = - (value_low_low as f64 * (1.0 - col_frac) + value_low_high as f64 * col_frac) as i16; - let value_high = - (value_high_low as f64 * (1.0 - col_frac) + value_high_high as f64 * col_frac) as i16; - - debug!("row = {}", row); - debug!("col = {}", col); - debug!("row_low = {}", row_low); - debug!("row_high = {}", row_high); - debug!("row_frac = {}", row_frac); - debug!("col_low = {}", col_low); - debug!("col_high = {}", col_high); - debug!("col_frac = {}", col_frac); - - debug!("value_low_low = {}", value_low_low); - debug!("value_high_low = {}", value_high_low); - debug!("value_high_high = {}", value_high_high); - debug!("value_low_high = {}", value_low_high); - - debug!("value_low = {}", value_low); - debug!("value_high = {}", value_high); - - let value = (value_low as f64 * (1.0 - row_frac) + value_high as f64 * row_frac) as i16; + + let samples = [ + (value_low_low, (1.0 - row_frac) * (1.0 - col_frac)), + (value_low_high, (1.0 - row_frac) * col_frac), + (value_high_low, row_frac * (1.0 - col_frac)), + (value_high_high, row_frac * col_frac), + ]; + + let mut weighted_sum = 0.0; + let mut weight_sum = 0.0; + for (sample, weight) in samples { + if let Some(sample) = sample { + weighted_sum += sample as f64 * weight; + weight_sum += weight; + } + } + + if weight_sum == 0.0 { + return Err(Error::new( + ErrorKind::NotFound, + "No elevation data (void samples) at the requested coordinates.", + )); + } + + let interpolated = weighted_sum / weight_sum; + + if let Some(max_dev) = self.plausibility_max_deviation_m { + if let Some(median) = self.neighbor_median(row.round() as isize, col.round() as isize)? { + if (interpolated - median).abs() > max_dev { + return Err(Error::new( + ErrorKind::NotFound, + format!( + "Implausible elevation {:.1}m deviates from 8-neighbor median {:.1}m by more than {:.1}m.", + interpolated, median, max_dev + ), + )); + } + } + } + + let value = interpolated.round() as i16; debug!("Final interpolated value: {}", value); Ok(value) } + fn neighbor_median(&self, center_row: isize, center_col: isize) -> Result, Error> { + let mut neighbors = Vec::with_capacity(8); + let size = self.size as isize; + for dr in -1..=1 { + for dc in -1..=1 { + if dr == 0 && dc == 0 { + continue; + } + let r = center_row + dr; + let c = center_col + dc; + if r >= 0 && r < size && c >= 0 && c < size { + if let Some(v) = self.get_row_col_value(r as f64, c as f64)? { + neighbors.push(v); + } + } + } + } + if neighbors.is_empty() { + return Ok(None); + } + neighbors.sort_unstable(); + let mid = neighbors.len() / 2; + let med = if neighbors.len() % 2 == 1 { + neighbors[mid] as f64 + } else { + (neighbors[mid - 1] as f64 + neighbors[mid] as f64) / 2.0 + }; + Ok(Some(med)) + } + #[instrument(skip_all, fields(row, col), level = "trace")] - fn get_row_col_value(&self, row: f64, col: f64) -> Result { + fn get_row_col_value(&self, row: f64, col: f64) -> Result, Error> { let offset = ((self.size - row as usize - 1) * self.size + col as usize) * 2; if offset + 1 >= self.buffer.len() { return Err(Error::new( @@ -114,7 +184,10 @@ impl HGT { } let elevation = i16::from_be_bytes([self.buffer[offset], self.buffer[offset + 1]]); - Ok(elevation) + if is_void_sample(elevation) { + return Ok(None); + } + Ok(Some(elevation)) } } @@ -123,9 +196,17 @@ mod tests { use super::*; use std::io::ErrorKind; + const TEST_TILE_SIZE: usize = 1201; + const TEST_TILE_BYTES: usize = 2884802; + + fn set_sample(buffer: &mut [u8], row: usize, col: usize, value: i16) { + let offset = ((TEST_TILE_SIZE - row - 1) * TEST_TILE_SIZE + col) * 2; + buffer[offset..offset + 2].copy_from_slice(&value.to_be_bytes()); + } + #[test] fn test_hgt_creation_valid_buffer() { - let buffer = vec![0; 25934402]; // Valid buffer size for 1 arcsecond resolution + let buffer = vec![0; 25934402]; let sw_lat_lng = (0.0, 0.0); let hgt = HGT::new(buffer, sw_lat_lng); assert!(hgt.is_ok()); @@ -133,7 +214,7 @@ mod tests { #[test] fn test_hgt_creation_invalid_buffer() { - let buffer = vec![0; 100]; // Invalid buffer size + let buffer = vec![0; 100]; let sw_lat_lng = (0.0, 0.0); let hgt = HGT::new(buffer, sw_lat_lng); assert!(hgt.is_err()); @@ -141,22 +222,56 @@ mod tests { } #[test] - fn test_get_elevation_valid_coordinates() { - let buffer = vec![0; 25934402]; // Valid buffer size for 1 arcsecond resolution - let sw_lat_lng = (0.0, 0.0); - let hgt = HGT::new(buffer, sw_lat_lng).unwrap(); - let elevation = hgt.get_elevation(0.5, 0.5); - assert!(elevation.is_ok()); - assert_eq!(elevation.unwrap(), 0); // Default buffer values lead to elevation 0 + fn test_void_min_and_max_corners_are_excluded_from_interpolation() { + let mut buffer = vec![0; TEST_TILE_BYTES]; + set_sample(&mut buffer, 600, 600, 100); + set_sample(&mut buffer, 600, 601, 200); + set_sample(&mut buffer, 601, 600, 300); + set_sample(&mut buffer, 601, 601, VOID_MIN); + + let hgt = HGT::new(buffer, (0.0, 0.0)).unwrap(); + let lat = 600.5 / (TEST_TILE_SIZE - 1) as f64; + assert_eq!(hgt.get_elevation(lat, lat).unwrap(), 200); + + // Regression test for Issue #21 / #55: Boston Harbor positive i16::MAX (32767 / 0x7fff) sentinel + let mut harbor_buf = vec![0; TEST_TILE_BYTES]; + set_sample(&mut harbor_buf, 600, 600, 1); + set_sample(&mut harbor_buf, 600, 601, 2); + set_sample(&mut harbor_buf, 601, 600, VOID_MAX); + set_sample(&mut harbor_buf, 601, 601, 1); + + let harbor_hgt = HGT::new(harbor_buf, (0.0, 0.0)).unwrap(); + assert_eq!(harbor_hgt.get_elevation(lat, lat).unwrap(), 1); } #[test] - fn test_get_elevation_out_of_bounds() { - let buffer = vec![0; 25934402]; // Valid buffer size for 1 arcsecond resolution - let sw_lat_lng = (0.0, 0.0); - let hgt = HGT::new(buffer, sw_lat_lng).unwrap(); - let elevation = hgt.get_elevation(-1.0, -1.0); - assert!(elevation.is_err()); - assert_eq!(elevation.unwrap_err().kind(), ErrorKind::InvalidInput); + fn test_all_void_cell_reports_no_data() { + let mut buffer = vec![0; TEST_TILE_BYTES]; + set_sample(&mut buffer, 600, 600, VOID_MIN); + set_sample(&mut buffer, 600, 601, VOID_MAX); + set_sample(&mut buffer, 601, 600, VOID_MIN); + set_sample(&mut buffer, 601, 601, VOID_MAX); + + let hgt = HGT::new(buffer, (0.0, 0.0)).unwrap(); + let lat = 600.5 / (TEST_TILE_SIZE - 1) as f64; + let error = hgt.get_elevation(lat, lat).unwrap_err(); + assert_eq!(error.kind(), ErrorKind::NotFound); + } + + #[test] + fn test_plausibility_neighbor_median_flags_corrupted_spike() { + let mut buffer = vec![0; TEST_TILE_BYTES]; + for r in 599..=602 { + for c in 599..=602 { + set_sample(&mut buffer, r, c, 10); + } + } + // Inject a non-sentinel corrupted spike of 900m surrounded by 10m water/land + set_sample(&mut buffer, 600, 600, 900); + + let hgt = HGT::with_plausibility(buffer, (0.0, 0.0), Some(250.0)).unwrap(); + let coord = 600.0 / (TEST_TILE_SIZE - 1) as f64; + let err = hgt.get_elevation(coord, coord).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::NotFound); } } diff --git a/src/types.rs b/src/types.rs index af84f6a..18e3bae 100644 --- a/src/types.rs +++ b/src/types.rs @@ -4,6 +4,14 @@ use serde::{Deserialize, Serialize}; pub struct LatLng { pub lat: f64, pub lng: f64, + #[serde(default)] + pub nulls: bool, +} + +#[derive(Deserialize, Default, Clone, Copy)] +pub struct BatchQuery { + #[serde(default)] + pub nulls: bool, } #[derive(Deserialize)] @@ -24,7 +32,7 @@ impl IntoIterator for LatLngs { #[derive(Serialize)] #[serde(transparent)] pub struct ElevationResponse { - pub elevations: Vec, + pub elevations: Vec>, } /// Body of `/status`.