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

ajudst ogr time type to json format #988

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
65 changes: 64 additions & 1 deletion services/src/api/handlers/datasets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::{
},
DatasetName,
},
error::{self, Result},
error::{self, Error, Result},
projects::Symbology,
util::{
config::{get_config_element, Data},
Expand Down Expand Up @@ -47,12 +47,14 @@ use geoengine_operators::{
raster_descriptor_from_dataset,
},
};
use serde::{Deserialize, Serialize};
use snafu::ResultExt;
use std::{
collections::HashMap,
convert::{TryFrom, TryInto},
path::Path,
};
use utoipa::{ToResponse, ToSchema};

pub(crate) fn init_dataset_routes<C>(cfg: &mut web::ServiceConfig)
where
Expand All @@ -65,6 +67,10 @@ where
web::resource("/suggest").route(web::post().to(suggest_meta_data_handler::<C>)),
)
.service(web::resource("/auto").route(web::post().to(auto_create_dataset_handler::<C>)))
.service(
web::resource("/volumes/{volume_name}/files/{file_name}/layers")
.route(web::get().to(list_volume_file_layers_handler::<C>)),
)
.service(web::resource("/volumes").route(web::get().to(list_volumes_handler::<C>)))
.service(
web::resource("/{dataset}/loadingInfo")
Expand Down Expand Up @@ -1407,6 +1413,63 @@ pub async fn delete_dataset_handler<C: ApplicationContext>(
Ok(actix_web::HttpResponse::Ok().finish())
}

#[derive(Deserialize, Serialize, ToSchema, ToResponse)]
pub struct VolumeFileLayersResponse {
layers: Vec<String>,
}

/// List the layers of a file in a volume.
#[utoipa::path(
tag = "Datasets",
get,
path = "/dataset/volumes/{volume_name}/files/{file_name}/layers",
responses(
(status = 200, body = VolumeFileLayersResponse,
example = json!({"layers": ["layer1", "layer2"]}))
),
params(
("volume_name" = VolumeName, description = "Volume name"),
("file_name" = String, description = "File name")
),
security(
("session_token" = [])
)
)]
pub async fn list_volume_file_layers_handler<C: ApplicationContext>(

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add one success case test?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

path: web::Path<(VolumeName, String)>,
session: C::Session,
app_ctx: web::Data<C>,
) -> Result<impl Responder> {
let (volume_name, file_name) = path.into_inner();

let session_ctx = app_ctx.session_context(session);
let volumes = session_ctx.volumes()?;

let volume = volumes.iter().find(|v| v.name == volume_name.0).ok_or(
crate::error::Error::UnknownVolumeName {
volume_name: volume_name.0.clone(),
},
)?;

let Some(volume_path) = volume.path.as_ref() else {
return Err(crate::error::Error::CannotAccessVolumePath {
volume_name: volume_name.0.clone(),
});
};

let file_path = path_with_base_path(Path::new(volume_path), Path::new(&file_name))?;

let layers = crate::util::spawn_blocking(move || {
let dataset = gdal_open_dataset(&file_path)?;

// TODO: hide system/internal layer like "layer_styles"
Result::<_, Error>::Ok(dataset.layers().map(|l| l.name()).collect::<Vec<_>>())
})
.await??;

Ok(web::Json(VolumeFileLayersResponse { layers }))
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
112 changes: 111 additions & 1 deletion services/src/api/model/datatypes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use ordered_float::NotNan;
use postgres_types::{FromSql, ToSql};
use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
use snafu::ResultExt;
use std::collections::HashSet;
use std::{
collections::{BTreeMap, HashMap},
fmt::{Debug, Formatter},
Expand Down Expand Up @@ -1719,13 +1720,122 @@ impl From<RasterPropertiesEntryType> for geoengine_datatypes::raster::RasterProp
}
}

#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, ToSchema)]
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct DateTimeParseFormat {
fmt: String,
has_tz: bool,
has_time: bool,
}

enum FormatStrLoopState {
Normal,
Percent(String),
}

impl DateTimeParseFormat {
pub fn custom(fmt: String) -> Self {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks rather complicated. Maybe test it?

Copy link
Contributor Author

@michaelmattig michaelmattig Oct 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actually I just copied the code from datatypes:

pub fn custom(fmt: String) -> Self {

and there it actually is tested. Should I maybe just use that method and then implement From/Into? But then parsing changes in datatypes would reflect in api... so maybe just copy the test as well?

let (has_tz, has_time) = {
let mut has_tz = false;
let mut has_time = false;

let has_tz_values: HashSet<&str> = ["%Z", "%z", "%:z"].into();
let has_time_values: HashSet<&str> =
["%a", "%A", "%M", "%p", "%S", "%X", "%H", "%I"].into();

let mut state = FormatStrLoopState::Normal;

for c in fmt.chars() {
match state {
FormatStrLoopState::Normal => {
if c == '%' {
state = FormatStrLoopState::Percent("%".to_string());
}
}
FormatStrLoopState::Percent(ref mut s) => {
s.push(c);

if c == '%' {
// was escaped percentage
state = FormatStrLoopState::Normal;
} else if c.is_ascii_alphabetic() {
if has_tz_values.contains(s.as_str()) {
has_tz = true;
}
if has_time_values.contains(s.as_str()) {
has_time = true;
}

state = FormatStrLoopState::Normal;
}
}
}
}

(has_tz, has_time)
};

DateTimeParseFormat {
fmt,
has_tz,
has_time,
}
}

pub fn ymd() -> Self {
let fmt = "%Y-%m-%d".to_owned();
Self {
fmt,
has_tz: false,
has_time: false,
}
}

pub fn has_tz(&self) -> bool {
self.has_tz
}

pub fn has_time(&self) -> bool {
self.has_time
}

pub fn is_empty(&self) -> bool {
self.fmt.is_empty()
}

pub fn _to_parse_format(&self) -> &str {
&self.fmt
}
}

impl<'a> ToSchema<'a> for DateTimeParseFormat {
fn schema() -> (&'a str, utoipa::openapi::RefOr<utoipa::openapi::Schema>) {
use utoipa::openapi::*;
(
"DateTimeParseFormat",
ObjectBuilder::new().schema_type(SchemaType::String).into(),
)
}
}

impl<'de> Deserialize<'de> for DateTimeParseFormat {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Ok(Self::custom(s))
}
}

impl Serialize for DateTimeParseFormat {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.fmt)
}
}

impl From<geoengine_datatypes::primitives::DateTimeParseFormat> for DateTimeParseFormat {
fn from(value: geoengine_datatypes::primitives::DateTimeParseFormat) -> Self {
Self {
Expand Down
4 changes: 4 additions & 0 deletions services/src/api/model/operators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -707,13 +707,17 @@ pub enum OgrSourceDatasetTimeType {
start_format: OgrSourceTimeFormat,
duration: OgrSourceDurationSpec,
},
#[serde(rename = "start+end")]
#[schema(title = "OgrSourceDatasetTimeTypeStartEnd")]
#[serde(rename_all = "camelCase")]
StartEnd {
start_field: String,
start_format: OgrSourceTimeFormat,
end_field: String,
end_format: OgrSourceTimeFormat,
},
#[serde(rename = "start+duration")]
#[schema(title = "OgrSourceDatasetTimeTypeStartDuration")]
#[serde(rename_all = "camelCase")]
StartDuration {
start_field: String,
Expand Down
5 changes: 5 additions & 0 deletions services/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,11 @@ pub enum Error {
UnknownVolumeName {
volume_name: String,
},

#[snafu(display("Cannot access path of volume with name {}", volume_name))]
CannotAccessVolumePath {
volume_name: String,
},
}

impl actix_web::error::ResponseError for Error {
Expand Down
4 changes: 4 additions & 0 deletions services/src/pro/api/apidoc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use super::handlers::permissions::{PermissionListOptions, PermissionRequest, Resource};
use super::handlers::users::AddRole;
use crate::api::handlers;
use crate::api::handlers::datasets::VolumeFileLayersResponse;
use crate::api::handlers::plots::WrappedPlotOutput;
use crate::api::handlers::spatial_references::{AxisOrder, SpatialReferenceSpecification};
use crate::api::handlers::tasks::{TaskAbortOptions, TaskResponse};
Expand Down Expand Up @@ -145,6 +146,7 @@ use utoipa::{Modify, OpenApi};
handlers::datasets::update_loading_info_handler,
handlers::datasets::update_dataset_symbology_handler,
handlers::datasets::update_dataset_provenance_handler,
handlers::datasets::list_volume_file_layers_handler,
pro::api::handlers::machine_learning::add_ml_model,
pro::api::handlers::machine_learning::get_ml_model,
pro::api::handlers::machine_learning::list_ml_models,
Expand Down Expand Up @@ -325,6 +327,8 @@ use utoipa::{Modify, OpenApi};

UploadFilesResponse,
UploadFileLayersResponse,

VolumeFileLayersResponse,

CreateDataset,
UpdateDataset,
Expand Down
8 changes: 6 additions & 2 deletions services/src/pro/api/handlers/datasets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use crate::{
handlers::datasets::{
adjust_meta_data_path, auto_create_dataset_handler, create_upload_dataset,
delete_dataset_handler, get_dataset_handler, get_loading_info_handler,
list_datasets_handler, list_volumes_handler, suggest_meta_data_handler,
update_dataset_handler, update_dataset_provenance_handler,
list_datasets_handler, list_volume_file_layers_handler, list_volumes_handler,
suggest_meta_data_handler, update_dataset_handler, update_dataset_provenance_handler,
update_dataset_symbology_handler, update_loading_info_handler,
},
model::{
Expand Down Expand Up @@ -40,6 +40,10 @@ where
web::resource("/suggest").route(web::post().to(suggest_meta_data_handler::<C>)),
)
.service(web::resource("/auto").route(web::post().to(auto_create_dataset_handler::<C>)))
.service(
web::resource("/volumes/{volume_name}/files/{file_name}/layers")
.route(web::get().to(list_volume_file_layers_handler::<C>)),
)
.service(web::resource("/volumes").route(web::get().to(list_volumes_handler::<C>)))
.service(
web::resource("/{dataset}/loadingInfo")
Expand Down
Loading