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

Add --base-path CLI option to override the URL path in the tilejson #1205

Merged
merged 21 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions martin/src/args/srv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ pub struct SrvArgs {
pub keep_alive: Option<u64>,
#[arg(help = format!("The socket address to bind. [DEFAULT: {}]", LISTEN_ADDRESSES_DEFAULT), short, long)]
pub listen_addresses: Option<String>,
#[arg(help = format!("Base path of martin if it's behind a proxy server. It's useful when you couldn't set x-rewrite-url of proxy server"), long)]
sharkAndshark marked this conversation as resolved.
Show resolved Hide resolved
pub base_path: Option<String>,
/// Number of web server workers
#[arg(short = 'W', long)]
pub workers: Option<usize>,
Expand Down Expand Up @@ -42,5 +44,8 @@ impl SrvArgs {
if self.preferred_encoding.is_some() {
srv_config.preferred_encoding = self.preferred_encoding;
}
if self.base_path.is_some() {
srv_config.base_path = self.base_path;
}
}
}
15 changes: 14 additions & 1 deletion martin/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ use crate::source::{TileInfoSources, TileSources};
use crate::sprites::{SpriteConfig, SpriteSources};
use crate::srv::{SrvConfig, RESERVED_KEYWORDS};
use crate::utils::{CacheValue, MainCache, OptMainCache};
use crate::MartinError::{ConfigLoadError, ConfigParseError, ConfigWriteError, NoSources};
use crate::MartinError::{
BasePathError, ConfigLoadError, ConfigParseError, ConfigWriteError, NoSources,
};
use crate::{IdResolver, MartinResult, OptOneMany};

pub type UnrecognizedValues = HashMap<String, serde_yaml::Value>;
Expand Down Expand Up @@ -71,6 +73,17 @@ impl Config {
let mut res = UnrecognizedValues::new();
copy_unrecognized_config(&mut res, "", &self.unrecognized);

if self
sharkAndshark marked this conversation as resolved.
Show resolved Hide resolved
.srv
.base_path
.as_ref()
.is_some_and(|v| !v.starts_with('/'))
{
return Err(BasePathError(
self.srv.base_path.as_ref().unwrap().to_string(),
));
}

#[cfg(feature = "postgres")]
for pg in self.postgres.iter_mut() {
res.extend(pg.finalize()?);
Expand Down
4 changes: 4 additions & 0 deletions martin/src/srv/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub const LISTEN_ADDRESSES_DEFAULT: &str = "0.0.0.0:3000";
pub struct SrvConfig {
pub keep_alive: Option<u64>,
pub listen_addresses: Option<String>,
pub base_path: Option<String>,
pub worker_processes: Option<usize>,
pub preferred_encoding: Option<PreferredEncoding>,
}
Expand All @@ -35,6 +36,7 @@ mod tests {
listen_addresses: some("0.0.0.0:3000"),
worker_processes: Some(8),
preferred_encoding: None,
base_path: None,
}
);
assert_eq!(
Expand All @@ -50,6 +52,7 @@ mod tests {
listen_addresses: some("0.0.0.0:3000"),
worker_processes: Some(8),
preferred_encoding: Some(PreferredEncoding::Brotli),
base_path: None
}
);
assert_eq!(
Expand All @@ -65,6 +68,7 @@ mod tests {
listen_addresses: some("0.0.0.0:3000"),
worker_processes: Some(8),
preferred_encoding: Some(PreferredEncoding::Brotli),
base_path: None,
}
);
}
Expand Down
25 changes: 16 additions & 9 deletions martin/src/srv/tiles_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use serde::Deserialize;
use tilejson::{tilejson, TileJSON};

use crate::source::{Source, TileSources};
use crate::srv::SrvConfig;

#[derive(Deserialize)]
pub struct SourceIDsRequest {
Expand All @@ -26,18 +27,24 @@ async fn get_source_info(
req: HttpRequest,
path: Path<SourceIDsRequest>,
sources: Data<TileSources>,
srv_config: Data<SrvConfig>,
) -> ActixResult<HttpResponse> {
let sources = sources.get_sources(&path.source_ids, None)?.0;

// Get `X-REWRITE-URL` header value, and extract its `path` component.
// If the header is not present or cannot be parsed as a URL, return the request path.
let tiles_path = req
.headers()
.get("x-rewrite-url")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<Uri>().ok())
.map_or_else(|| req.path().to_owned(), |v| v.path().to_owned());

// if base_path is set, use it as the tiles path
// or try to use x-rewrite-url header value as the tiles path
let tiles_path =
if srv_config.base_path.is_some() & req.headers().get("x-rewrite-url").is_none() {
srv_config.base_path.clone().unwrap()
} else {
// Get `X-REWRITE-URL` header value, and extract its `path` component.
// If the header is not present or cannot be parsed as a URL, return the request path.
req.headers()
.get("x-rewrite-url")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<Uri>().ok())
.map_or_else(|| req.path().to_owned(), |v| v.path().to_owned())
};
let query_string = req.query_string();
let path_and_query = if query_string.is_empty() {
format!("{tiles_path}/{{z}}/{{x}}/{{y}}")
Expand Down
3 changes: 3 additions & 0 deletions martin/src/utils/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ pub enum MartinError {
#[error("Unable to bind to {1}: {0}")]
BindingError(io::Error, String),

#[error("Base path must start with a slash but is '{0}'")]
BasePathError(String),

#[error("Unable to load config file {}: {0}", .1.display())]
ConfigLoadError(io::Error, PathBuf),

Expand Down
Loading