From 5512180946805cc75f3f6a26446bc7d813cc0b07 Mon Sep 17 00:00:00 2001 From: JulienChampagnol Date: Wed, 2 Dec 2026 10:37:20 +0100 Subject: [PATCH 01/11] fix(requirements): geode-viewables 3.9.0 Model light viewables are now a .vtm with one .vtp per mesh component. Co-Authored-By: Claude Opus 5.5 --- requirements.in | 10 +++++----- requirements.txt | 10 +++++----- tests/test_geode_functions.py | 2 ++ tests/test_utils_functions.py | 4 ++-- 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/requirements.in b/requirements.in index 49ef21cb..bb183fdc 100644 --- a/requirements.in +++ b/requirements.in @@ -1,11 +1,11 @@ -opengeode-core==20.1.0 -opengeode-io==8.2.0 -opengeode-geosciences==10.1.0 +opengeode-core==20.4.2 +opengeode-io==8.3.0 +opengeode-geosciences==10.2.2 opengeode-geosciencesio==6.2.0 opengeode-inspector==6.20.0 opengeode-inspector-geosciences==1.5.0 -geode-common==33.32.0 -geode-viewables==3.8.0 +geode-common==33.35.1 +geode-viewables==3.9.0 flask[async]==3.1.2 flask-cors==6.0.2 werkzeug==3.1.8 diff --git a/requirements.txt b/requirements.txt index 06139be9..5ff2753a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -20,11 +20,11 @@ flask[async]==3.* # flask-cors flask-cors==6.0.2 # via -r requirements.in -geode-common==33.32.0 +geode-common==33.35.1 # via # -r requirements.in # geode-viewables -geode-viewables==3.8.0 +geode-viewables==3.9.0 # via -r requirements.in itsdangerous==2.* # via flask @@ -45,7 +45,7 @@ numpy==2.* # opengeode-inspector # opengeode-inspector-geosciences # opengeode-io -opengeode-core==20.1.0 +opengeode-core==20.4.2 # via # -r requirements.in # geode-common @@ -55,7 +55,7 @@ opengeode-core==20.1.0 # opengeode-inspector # opengeode-inspector-geosciences # opengeode-io -opengeode-geosciences==10.1.0 +opengeode-geosciences==10.2.2 # via # -r requirements.in # geode-viewables @@ -69,7 +69,7 @@ opengeode-inspector==6.20.0 # opengeode-inspector-geosciences opengeode-inspector-geosciences==1.5.0 # via -r requirements.in -opengeode-io==8.2.0 +opengeode-io==8.3.0 # via # -r requirements.in # geode-viewables diff --git a/tests/test_geode_functions.py b/tests/test_geode_functions.py index d6efc9e1..055acf77 100644 --- a/tests/test_geode_functions.py +++ b/tests/test_geode_functions.py @@ -1,6 +1,7 @@ # Standard library imports from __future__ import annotations +import shutil import uuid from pathlib import Path from typing import TYPE_CHECKING @@ -43,6 +44,7 @@ def check_save_and_output_extensions(geode_object: GeodeObject, file_absolute_pa if geode_object.is_viewable(): light_viewable_file_path = geode_object.save_light_viewable(str(output_folder / data_name)) Path(light_viewable_file_path).unlink() + shutil.rmtree(Path(light_viewable_file_path).with_suffix(""), ignore_errors=True) geode_objects_output_extensions = geode_functions.geode_object_output_extensions(geode_object) assert type(geode_objects_output_extensions) is dict for ( diff --git a/tests/test_utils_functions.py b/tests/test_utils_functions.py index 87b788f5..dcf261d2 100644 --- a/tests/test_utils_functions.py +++ b/tests/test_utils_functions.py @@ -238,12 +238,12 @@ def test_generate_files_from_object( assert isinstance(result["binary_light_viewable"], str) light_viewable_bytes = base64.b64decode(result["binary_light_viewable"], validate=True) assert light_viewable_bytes.startswith(b'') - assert b'' in light_viewable_bytes + assert b'type="vtkMultiBlockDataSet"' in light_viewable_bytes data = Data.get(result["id"]) assert data is not None assert data.light_viewable_file is not None - assert data.light_viewable_file.endswith(".vtp") + assert data.light_viewable_file.endswith(".vtm") data_path = Path(app.config["DATA_FOLDER_PATH"]) / result["id"] # The native file is saved in background From d048829b2bcd891799831dae080d52f89e9062c1 Mon Sep 17 00:00:00 2001 From: JulienChampagnol Date: Wed, 2 Dec 2026 10:42:57 +0100 Subject: [PATCH 02/11] feat(light_viewable): per mesh component light viewables Co-Authored-By: Claude Opus 5.5 --- opengeodeweb_back_schemas.json | 15 +++++++ .../routes/create/schemas/edged_curve.py | 17 +++++++- .../routes/create/schemas/horizon_stack.py | 17 +++++++- .../routes/create/schemas/point_set.py | 17 +++++++- .../create/schemas/polygonal_surface.py | 17 +++++++- .../routes/schemas/save_viewable_file.py | 17 +++++++- src/opengeodeweb_back/schema_definitions.json | 3 ++ src/opengeodeweb_back/schema_types.d.ts | 15 +++---- src/opengeodeweb_back/schema_types.json | 3 ++ src/opengeodeweb_back/schema_types.py | 1 + src/opengeodeweb_back/test_utils.py | 7 ++++ src/opengeodeweb_back/utils_functions.py | 39 +++++++++++++++++-- tests/test_utils_functions.py | 24 ++++++++++++ 13 files changed, 176 insertions(+), 16 deletions(-) diff --git a/opengeodeweb_back_schemas.json b/opengeodeweb_back_schemas.json index f58f88f0..4e538a55 100644 --- a/opengeodeweb_back_schemas.json +++ b/opengeodeweb_back_schemas.json @@ -473,6 +473,9 @@ }, "is_active": { "type": "boolean" + }, + "binary_light_viewable": { + "type": "string" } }, "required": [ @@ -724,6 +727,9 @@ }, "is_active": { "type": "boolean" + }, + "binary_light_viewable": { + "type": "string" } }, "required": [ @@ -966,6 +972,9 @@ }, "is_active": { "type": "boolean" + }, + "binary_light_viewable": { + "type": "string" } }, "required": [ @@ -1230,6 +1239,9 @@ }, "is_active": { "type": "boolean" + }, + "binary_light_viewable": { + "type": "string" } }, "required": [ @@ -2365,6 +2377,9 @@ }, "is_active": { "type": "boolean" + }, + "binary_light_viewable": { + "type": "string" } }, "required": [ diff --git a/src/opengeodeweb_back/routes/create/schemas/edged_curve.py b/src/opengeodeweb_back/routes/create/schemas/edged_curve.py index fb16e388..63dcd7bc 100644 --- a/src/opengeodeweb_back/routes/create/schemas/edged_curve.py +++ b/src/opengeodeweb_back/routes/create/schemas/edged_curve.py @@ -1,5 +1,5 @@ from opengeodeweb_microservice.schema_types import DataId, GeodeId -from opengeodeweb_back.schema_types import CRS, CollectionComponent, MeshComponent, Point3D, ViewerId +from opengeodeweb_back.schema_types import CRS, CollectionComponent, Point3D, ViewerId from opengeodeweb_microservice.database.data_types import GeodeObjectType, ViewerObjectType from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema @@ -20,6 +20,21 @@ def __post_init__(self) -> None: points: List[Point3D] +@dataclass +class MeshComponent(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + boundaries: List[GeodeId] + geode_id: GeodeId + internals: List[GeodeId] + is_active: bool + name: str + type: str + viewer_id: ViewerId + binary_light_viewable: Optional[str] = None + + @dataclass class EdgedCurveResponse(DataClassJsonMixin): def __post_init__(self) -> None: diff --git a/src/opengeodeweb_back/routes/create/schemas/horizon_stack.py b/src/opengeodeweb_back/routes/create/schemas/horizon_stack.py index d446c63c..b2b1abe4 100644 --- a/src/opengeodeweb_back/routes/create/schemas/horizon_stack.py +++ b/src/opengeodeweb_back/routes/create/schemas/horizon_stack.py @@ -1,5 +1,5 @@ from opengeodeweb_microservice.schema_types import DataId, GeodeId -from opengeodeweb_back.schema_types import CRS, CollectionComponent, MeshComponent, ViewerId +from opengeodeweb_back.schema_types import CRS, CollectionComponent, ViewerId from opengeodeweb_microservice.database.data_types import GeodeObjectType, ViewerObjectType from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema @@ -20,6 +20,21 @@ def __post_init__(self) -> None: unit_names: List[str] +@dataclass +class MeshComponent(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + boundaries: List[GeodeId] + geode_id: GeodeId + internals: List[GeodeId] + is_active: bool + name: str + type: str + viewer_id: ViewerId + binary_light_viewable: Optional[str] = None + + @dataclass class HorizonStackResponse(DataClassJsonMixin): def __post_init__(self) -> None: diff --git a/src/opengeodeweb_back/routes/create/schemas/point_set.py b/src/opengeodeweb_back/routes/create/schemas/point_set.py index e0af2779..5d3e9c17 100644 --- a/src/opengeodeweb_back/routes/create/schemas/point_set.py +++ b/src/opengeodeweb_back/routes/create/schemas/point_set.py @@ -1,5 +1,5 @@ from opengeodeweb_microservice.schema_types import DataId, GeodeId -from opengeodeweb_back.schema_types import CRS, CollectionComponent, MeshComponent, Point3D, ViewerId +from opengeodeweb_back.schema_types import CRS, CollectionComponent, Point3D, ViewerId from opengeodeweb_microservice.database.data_types import GeodeObjectType, ViewerObjectType from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema @@ -19,6 +19,21 @@ def __post_init__(self) -> None: points: List[Point3D] +@dataclass +class MeshComponent(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + boundaries: List[GeodeId] + geode_id: GeodeId + internals: List[GeodeId] + is_active: bool + name: str + type: str + viewer_id: ViewerId + binary_light_viewable: Optional[str] = None + + @dataclass class PointSetResponse(DataClassJsonMixin): def __post_init__(self) -> None: diff --git a/src/opengeodeweb_back/routes/create/schemas/polygonal_surface.py b/src/opengeodeweb_back/routes/create/schemas/polygonal_surface.py index bcb9c117..c790e11d 100644 --- a/src/opengeodeweb_back/routes/create/schemas/polygonal_surface.py +++ b/src/opengeodeweb_back/routes/create/schemas/polygonal_surface.py @@ -1,5 +1,5 @@ from opengeodeweb_microservice.schema_types import DataId, GeodeId -from opengeodeweb_back.schema_types import CRS, CollectionComponent, MeshComponent, Point3D, ViewerId +from opengeodeweb_back.schema_types import CRS, CollectionComponent, Point3D, ViewerId from opengeodeweb_microservice.database.data_types import GeodeObjectType, ViewerObjectType from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema @@ -20,6 +20,21 @@ def __post_init__(self) -> None: polygons: List[List[int]] +@dataclass +class MeshComponent(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + boundaries: List[GeodeId] + geode_id: GeodeId + internals: List[GeodeId] + is_active: bool + name: str + type: str + viewer_id: ViewerId + binary_light_viewable: Optional[str] = None + + @dataclass class PolygonalSurfaceResponse(DataClassJsonMixin): def __post_init__(self) -> None: diff --git a/src/opengeodeweb_back/routes/schemas/save_viewable_file.py b/src/opengeodeweb_back/routes/schemas/save_viewable_file.py index 2db115e7..02b2539d 100644 --- a/src/opengeodeweb_back/routes/schemas/save_viewable_file.py +++ b/src/opengeodeweb_back/routes/schemas/save_viewable_file.py @@ -1,4 +1,4 @@ -from opengeodeweb_back.schema_types import CRS, CollectionComponent, Filename, MeshComponent, ViewerId +from opengeodeweb_back.schema_types import CRS, CollectionComponent, Filename, ViewerId from opengeodeweb_microservice.schema_types import DataId, GeodeId from opengeodeweb_microservice.database.data_types import GeodeObjectType, ViewerObjectType from pathlib import Path @@ -18,6 +18,21 @@ def __post_init__(self) -> None: geode_object_type: GeodeObjectType +@dataclass +class MeshComponent(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + boundaries: List[GeodeId] + geode_id: GeodeId + internals: List[GeodeId] + is_active: bool + name: str + type: str + viewer_id: ViewerId + binary_light_viewable: Optional[str] = None + + @dataclass class SaveViewableFileItem(DataClassJsonMixin): def __post_init__(self) -> None: diff --git a/src/opengeodeweb_back/schema_definitions.json b/src/opengeodeweb_back/schema_definitions.json index 0a04f5b7..cc505528 100644 --- a/src/opengeodeweb_back/schema_definitions.json +++ b/src/opengeodeweb_back/schema_definitions.json @@ -252,6 +252,9 @@ }, "is_active": { "type": "boolean" + }, + "binary_light_viewable": { + "type": "string" } }, "required": [ diff --git a/src/opengeodeweb_back/schema_types.d.ts b/src/opengeodeweb_back/schema_types.d.ts index 7cc8de14..50fb46f4 100644 --- a/src/opengeodeweb_back/schema_types.d.ts +++ b/src/opengeodeweb_back/schema_types.d.ts @@ -26,13 +26,14 @@ export interface CRS { } export interface MeshComponent { - boundaries: GeodeId[]; - geode_id: GeodeId; - internals: GeodeId[]; - is_active: boolean; - name: string; - type: string; - viewer_id: ViewerId; + binary_light_viewable?: string; + boundaries: GeodeId[]; + geode_id: GeodeId; + internals: GeodeId[]; + is_active: boolean; + name: string; + type: string; + viewer_id: ViewerId; } export interface CollectionComponent { diff --git a/src/opengeodeweb_back/schema_types.json b/src/opengeodeweb_back/schema_types.json index a9c7bc50..da1ba0e0 100644 --- a/src/opengeodeweb_back/schema_types.json +++ b/src/opengeodeweb_back/schema_types.json @@ -109,6 +109,9 @@ }, "is_active": { "type": "boolean" + }, + "binary_light_viewable": { + "type": "string" } }, "required": [ diff --git a/src/opengeodeweb_back/schema_types.py b/src/opengeodeweb_back/schema_types.py index 8a4cce59..e6148afd 100644 --- a/src/opengeodeweb_back/schema_types.py +++ b/src/opengeodeweb_back/schema_types.py @@ -56,6 +56,7 @@ def __post_init__(self) -> None: name: str type: str viewer_id: ViewerId + binary_light_viewable: str | None = None @dataclass diff --git a/src/opengeodeweb_back/test_utils.py b/src/opengeodeweb_back/test_utils.py index 92d5150a..3142b4de 100644 --- a/src/opengeodeweb_back/test_utils.py +++ b/src/opengeodeweb_back/test_utils.py @@ -118,6 +118,13 @@ def get_full_data() -> JsonData: "viewer_object_type is not image, mesh or model", ) _check(type(item["binary_light_viewable"]) is str, "binary_light_viewable is not a string") + for component in item.get("mesh_components", []): + if component["type"] == "Block": + continue + _check( + type(component.get("binary_light_viewable")) is str, + f"Mesh component {component['geode_id']} has no light viewable", + ) # Test all params test_route_wrong_params(client, route, get_full_data) diff --git a/src/opengeodeweb_back/utils_functions.py b/src/opengeodeweb_back/utils_functions.py index a63109df..281fb0bf 100644 --- a/src/opengeodeweb_back/utils_functions.py +++ b/src/opengeodeweb_back/utils_functions.py @@ -254,7 +254,28 @@ def _uuid_to_flat_index(data_id: str, viewable_file: str | None) -> dict[str, in return uuid_to_flat_index -def _mesh_components(model: GeodeModel, uuid_to_flat_index: dict[str, int]) -> list[dict[str, Any]]: +def _uuid_to_light_viewable(data_id: str, light_viewable_file: str | None) -> dict[str, str]: + """Base64 light viewable of each mesh component, by component uuid.""" + uuid_to_light_viewable: dict[str, str] = {} + if light_viewable_file: + vtm_file_path = Path(geode_functions.data_file_path(data_id, light_viewable_file)) + root = parse(vtm_file_path).find("vtkMultiBlockDataSet") + if root is None: + flask.abort(500, "Failed to read light viewable file") + for elem in root.iter("DataSet"): + if "uuid" in elem.attrib and "file" in elem.attrib: + light_viewable = (vtm_file_path.parent / elem.attrib["file"]).read_bytes() + uuid_to_light_viewable[elem.attrib["uuid"]] = base64.b64encode( + light_viewable + ).decode("ascii") + return uuid_to_light_viewable + + +def _mesh_components( + model: GeodeModel, + uuid_to_flat_index: dict[str, int], + uuid_to_light_viewable: dict[str, str], +) -> list[dict[str, Any]]: model_mesh_components = model.mesh_components() mesh_components = [] for mesh_component, ids in model_mesh_components.items(): @@ -279,6 +300,8 @@ def _mesh_components(model: GeodeModel, uuid_to_flat_index: dict[str, int]) -> l "internals": internals_uuid, "is_active": component.is_active(), } + if geode_id in uuid_to_light_viewable: + mesh_component_object["binary_light_viewable"] = uuid_to_light_viewable[geode_id] mesh_components.append(mesh_component_object) return mesh_components @@ -307,10 +330,16 @@ def _collection_components(model: GeodeModel) -> list[dict[str, Any]]: return collection_components -def model_components(data_id: str, model: GeodeModel, viewable_file: str | None) -> dict[str, Any]: +def model_components( + data_id: str, + model: GeodeModel, + viewable_file: str | None, + light_viewable_file: str | None, +) -> dict[str, Any]: uuid_to_flat_index = _uuid_to_flat_index(data_id, viewable_file) + uuid_to_light_viewable = _uuid_to_light_viewable(data_id, light_viewable_file) return { - "mesh_components": _mesh_components(model, uuid_to_flat_index), + "mesh_components": _mesh_components(model, uuid_to_flat_index, uuid_to_light_viewable), "collection_components": _collection_components(model), } @@ -504,7 +533,9 @@ def save_all_viewables_and_return_info( if isinstance(geode_object, GeodeVertexSet): response["nb_vertices"] = geode_object.vertex_set.nb_vertices() if isinstance(geode_object, GeodeModel): - response |= model_components(data.id, geode_object, data.viewable_file) + response |= model_components( + data.id, geode_object, data.viewable_file, data.light_viewable_file + ) crs = active_crs(geode_object) if crs is not None: response["crs"] = crs diff --git a/tests/test_utils_functions.py b/tests/test_utils_functions.py index dcf261d2..bdddb340 100644 --- a/tests/test_utils_functions.py +++ b/tests/test_utils_functions.py @@ -196,6 +196,30 @@ def test_save_all_viewables_and_return_info(client: FlaskClient) -> None: assert expected_data_path.exists() +def test_save_all_viewables_returns_component_light_viewables(client: FlaskClient) -> None: + with client.application.app_context(): + geode_object = GeodeBRep.load_one(str(data_dir / "cube.og_brep")) + geode_object.builder().set_name("cube") + + result = utils_functions.generate_files_from_object(geode_object) + + light_vtm = base64.b64decode(result["binary_light_viewable"], validate=True) + assert b'type="vtkMultiBlockDataSet"' in light_vtm + for component in result["mesh_components"]: + if component["type"] == "Block": + assert "binary_light_viewable" not in component + else: + light_vtp = base64.b64decode(component["binary_light_viewable"], validate=True) + assert b'type="PolyData"' in light_vtp + light_components = [ + component + for component in result["mesh_components"] + if "binary_light_viewable" in component + ] + # 8 corners, 12 lines and 6 surfaces + assert len(light_components) == 26 + + def test_save_all_viewables_commits_to_db(client: FlaskClient) -> None: app = client.application with app.app_context(): From 43e62646b28882dd807e181ff7021db7297259ec Mon Sep 17 00:00:00 2001 From: JulienChampagnol Date: Wed, 2 Dec 2026 10:49:20 +0100 Subject: [PATCH 03/11] feat(crs): return mesh component light viewables Co-Authored-By: Claude Opus 5.5 --- opengeodeweb_back_schemas.json | 236 ++++++++++++++++++ opengeodeweb_back_typed_schemas.d.ts | 4 + .../routes/crs/blueprint_crs.py | 3 +- .../routes/crs/schemas/align.json | 12 + .../routes/crs/schemas/align.py | 36 ++- .../crs/schemas/convert_geographic.json | 12 + .../routes/crs/schemas/convert_geographic.py | 36 ++- tests/test_crs_routes.py | 18 ++ 8 files changed, 353 insertions(+), 4 deletions(-) diff --git a/opengeodeweb_back_schemas.json b/opengeodeweb_back_schemas.json index b3160465..21e4afeb 100644 --- a/opengeodeweb_back_schemas.json +++ b/opengeodeweb_back_schemas.json @@ -1475,6 +1475,65 @@ "binary_light_viewable": { "type": "string" }, + "mesh_components": { + "type": "array", + "items": { + "title": "MeshComponent", + "type": "object", + "properties": { + "viewer_id": { + "title": "ViewerId", + "type": "integer" + }, + "geode_id": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "name": { + "type": "string" + }, + "type": { + "type": "string" + }, + "boundaries": { + "type": "array", + "items": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + } + }, + "internals": { + "type": "array", + "items": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + } + }, + "is_active": { + "type": "boolean" + }, + "binary_light_viewable": { + "type": "string" + } + }, + "required": [ + "viewer_id", + "geode_id", + "name", + "type", + "boundaries", + "internals", + "is_active" + ], + "additionalProperties": false + } + }, "crs": { "title": "CRS", "type": "object", @@ -1536,6 +1595,65 @@ }, "binary_light_viewable": { "type": "string" + }, + "mesh_components": { + "type": "array", + "items": { + "title": "MeshComponent", + "type": "object", + "properties": { + "viewer_id": { + "title": "ViewerId", + "type": "integer" + }, + "geode_id": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "name": { + "type": "string" + }, + "type": { + "type": "string" + }, + "boundaries": { + "type": "array", + "items": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + } + }, + "internals": { + "type": "array", + "items": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + } + }, + "is_active": { + "type": "boolean" + }, + "binary_light_viewable": { + "type": "string" + } + }, + "required": [ + "viewer_id", + "geode_id", + "name", + "type", + "boundaries", + "internals", + "is_active" + ], + "additionalProperties": false + } } }, "required": [ @@ -1780,6 +1898,65 @@ "binary_light_viewable": { "type": "string" }, + "mesh_components": { + "type": "array", + "items": { + "title": "MeshComponent", + "type": "object", + "properties": { + "viewer_id": { + "title": "ViewerId", + "type": "integer" + }, + "geode_id": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "name": { + "type": "string" + }, + "type": { + "type": "string" + }, + "boundaries": { + "type": "array", + "items": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + } + }, + "internals": { + "type": "array", + "items": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + } + }, + "is_active": { + "type": "boolean" + }, + "binary_light_viewable": { + "type": "string" + } + }, + "required": [ + "viewer_id", + "geode_id", + "name", + "type", + "boundaries", + "internals", + "is_active" + ], + "additionalProperties": false + } + }, "crs": { "title": "CRS", "type": "object", @@ -1818,6 +1995,65 @@ "binary_light_viewable": { "type": "string" }, + "mesh_components": { + "type": "array", + "items": { + "title": "MeshComponent", + "type": "object", + "properties": { + "viewer_id": { + "title": "ViewerId", + "type": "integer" + }, + "geode_id": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "name": { + "type": "string" + }, + "type": { + "type": "string" + }, + "boundaries": { + "type": "array", + "items": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + } + }, + "internals": { + "type": "array", + "items": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + } + }, + "is_active": { + "type": "boolean" + }, + "binary_light_viewable": { + "type": "string" + } + }, + "required": [ + "viewer_id", + "geode_id", + "name", + "type", + "boundaries", + "internals", + "is_active" + ], + "additionalProperties": false + } + }, "crs": { "title": "CRS", "type": "object", diff --git a/opengeodeweb_back_typed_schemas.d.ts b/opengeodeweb_back_typed_schemas.d.ts index 8dcc3f2b..3f8f6c97 100644 --- a/opengeodeweb_back_typed_schemas.d.ts +++ b/opengeodeweb_back_typed_schemas.d.ts @@ -170,12 +170,14 @@ export interface CRSConvertGeographicResponse { binary_light_viewable?: string; crs?: CRS; linked?: CRSConvertGeographicResponseLinked[]; + mesh_components?: MeshComponent[]; } export interface CRSConvertGeographicResponseLinked { binary_light_viewable?: string; crs?: CRS; id: DataId; + mesh_components?: MeshComponent[]; } export interface CRSAssignGeographicParams { @@ -226,12 +228,14 @@ export interface CRSAlignResponse { binary_light_viewable?: string; crs?: CRS; linked?: CRSAlignResponseLinked[]; + mesh_components?: MeshComponent[]; } export interface CRSAlignResponseLinked { binary_light_viewable?: string; crs?: CRS; id: DataId; + mesh_components?: MeshComponent[]; } export interface CRSActiveParams { diff --git a/src/opengeodeweb_back/routes/crs/blueprint_crs.py b/src/opengeodeweb_back/routes/crs/blueprint_crs.py index fb167e78..4888b420 100644 --- a/src/opengeodeweb_back/routes/crs/blueprint_crs.py +++ b/src/opengeodeweb_back/routes/crs/blueprint_crs.py @@ -45,7 +45,8 @@ def _bad_request() -> Generator[None]: def _crs_response(saved: dict[str, Any]) -> dict[str, Any]: # Only the fields the front refreshes after a CRS change - return {key: saved[key] for key in ("crs", "binary_light_viewable") if key in saved} + refreshed = ("crs", "binary_light_viewable", "mesh_components") + return {key: saved[key] for key in refreshed if key in saved} def _saved_response(data_id: str, data: Data, geode_object: CrsGeodeObject) -> dict[str, Any]: diff --git a/src/opengeodeweb_back/routes/crs/schemas/align.json b/src/opengeodeweb_back/routes/crs/schemas/align.json index 287f47bf..3183f121 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/align.json +++ b/src/opengeodeweb_back/routes/crs/schemas/align.json @@ -89,6 +89,12 @@ "binary_light_viewable": { "type": "string" }, + "mesh_components": { + "type": "array", + "items": { + "title": "MeshComponent" + } + }, "crs": { "title": "CRS" }, @@ -103,6 +109,12 @@ "binary_light_viewable": { "type": "string" }, + "mesh_components": { + "type": "array", + "items": { + "title": "MeshComponent" + } + }, "crs": { "title": "CRS" } diff --git a/src/opengeodeweb_back/routes/crs/schemas/align.py b/src/opengeodeweb_back/routes/crs/schemas/align.py index 3dc1ad00..214fa943 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/align.py +++ b/src/opengeodeweb_back/routes/crs/schemas/align.py @@ -1,6 +1,8 @@ -from opengeodeweb_microservice.schema_types import DataId +from opengeodeweb_microservice.schema_types import DataId, GeodeId +from opengeodeweb_back.schema_types import ViewerId from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema +from typing import List, Optional from dataclasses_json import DataClassJsonMixin from opengeodeweb_microservice.schemas import print_dataclass from dataclasses import dataclass @@ -60,6 +62,21 @@ def __post_init__(self) -> None: name: str +@dataclass +class LinkedMeshComponent(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + boundaries: List[GeodeId] + geode_id: GeodeId + internals: List[GeodeId] + is_active: bool + name: str + type: str + viewer_id: ViewerId + binary_light_viewable: Optional[str] = None + + @dataclass class Linked(DataClassJsonMixin): def __post_init__(self) -> None: @@ -68,6 +85,22 @@ def __post_init__(self) -> None: id: DataId binary_light_viewable: Optional[str] = None crs: Optional[LinkedCRS] = None + mesh_components: Optional[List[LinkedMeshComponent]] = None + + +@dataclass +class AlignResponseMeshComponent(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + boundaries: List[GeodeId] + geode_id: GeodeId + internals: List[GeodeId] + is_active: bool + name: str + type: str + viewer_id: ViewerId + binary_light_viewable: Optional[str] = None @dataclass @@ -78,6 +111,7 @@ def __post_init__(self) -> None: binary_light_viewable: Optional[str] = None crs: Optional[AlignResponseCRS] = None linked: Optional[List[Linked]] = None + mesh_components: Optional[List[AlignResponseMeshComponent]] = None align_route = Route( diff --git a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.json b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.json index 262a6f30..e0ba50f7 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.json +++ b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.json @@ -41,6 +41,12 @@ "binary_light_viewable": { "type": "string" }, + "mesh_components": { + "type": "array", + "items": { + "title": "MeshComponent" + } + }, "crs": { "title": "CRS" }, @@ -57,6 +63,12 @@ }, "binary_light_viewable": { "type": "string" + }, + "mesh_components": { + "type": "array", + "items": { + "title": "MeshComponent" + } } }, "required": [ diff --git a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py index 465c3446..739e4e93 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py +++ b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py @@ -1,7 +1,7 @@ -from opengeodeweb_microservice.schema_types import DataId +from opengeodeweb_microservice.schema_types import DataId, GeodeId +from opengeodeweb_back.schema_types import ViewerId from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema -from typing import Optional, List from dataclasses_json import DataClassJsonMixin from opengeodeweb_microservice.schemas import print_dataclass from dataclasses import dataclass @@ -40,6 +40,21 @@ def __post_init__(self) -> None: name: str +@dataclass +class LinkedMeshComponent(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + boundaries: List[GeodeId] + geode_id: GeodeId + internals: List[GeodeId] + is_active: bool + name: str + type: str + viewer_id: ViewerId + binary_light_viewable: Optional[str] = None + + @dataclass class Linked(DataClassJsonMixin): def __post_init__(self) -> None: @@ -48,6 +63,22 @@ def __post_init__(self) -> None: id: DataId binary_light_viewable: Optional[str] = None crs: Optional[LinkedCRS] = None + mesh_components: Optional[List[LinkedMeshComponent]] = None + + +@dataclass +class ConvertGeographicResponseMeshComponent(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + boundaries: List[GeodeId] + geode_id: GeodeId + internals: List[GeodeId] + is_active: bool + name: str + type: str + viewer_id: ViewerId + binary_light_viewable: Optional[str] = None @dataclass @@ -58,6 +89,7 @@ def __post_init__(self) -> None: binary_light_viewable: Optional[str] = None crs: Optional[ConvertGeographicResponseCRS] = None linked: Optional[List[Linked]] = None + mesh_components: Optional[List[ConvertGeographicResponseMeshComponent]] = None convert_geographic_route = Route( diff --git a/tests/test_crs_routes.py b/tests/test_crs_routes.py index fb744463..0c9fdc33 100644 --- a/tests/test_crs_routes.py +++ b/tests/test_crs_routes.py @@ -664,6 +664,24 @@ def test_assign_only_plausible(client: FlaskClient) -> None: assert _active_crs(client, plausible_id) == LAMBERT +def test_convert_geographic_model_returns_component_light_viewables(client: FlaskClient) -> None: + assign_route = "/opengeodeweb_back/crs/assign_geographic" + route = "/opengeodeweb_back/crs/convert_geographic" + [brep] = test_utils.check_save_viewable_file(client, "BRep", "cube.og_brep") + [linked_brep] = test_utils.check_save_viewable_file(client, "BRep", "cube.og_brep") + client.post(assign_route, json={"id": brep["id"], "linked_ids": [linked_brep["id"]], **LAMBERT}) + response = client.post(route, json={"id": brep["id"], "linked_ids": [linked_brep["id"]], **UTM}) + assert response.status_code == 200 + [linked] = response.get_json()["linked"] + # The front rebuilds each component actor from its moved light viewable + for converted in (response.get_json(), linked): + for component in converted["mesh_components"]: + if component["type"] == "Block": + assert "binary_light_viewable" not in component + else: + assert type(component["binary_light_viewable"]) is str + + def test_assign_geographic_model_without_block_meshes(client: FlaskClient) -> None: route = "/opengeodeweb_back/crs/assign_geographic" # Models built from surfaces often keep their blocks without mesh From e063b99a9545820e21fd9563dba81ed782a5526b Mon Sep 17 00:00:00 2001 From: JulienChampagnol Date: Wed, 2 Dec 2026 10:58:05 +0100 Subject: [PATCH 04/11] fix(schemas): import the shared MeshComponent Co-Authored-By: Claude Opus 5.5 --- .../routes/create/schemas/edged_curve.py | 17 +---------------- .../routes/create/schemas/horizon_stack.py | 17 +---------------- .../routes/create/schemas/point_set.py | 17 +---------------- .../routes/create/schemas/polygonal_surface.py | 17 +---------------- .../routes/schemas/save_viewable_file.py | 17 +---------------- 5 files changed, 5 insertions(+), 80 deletions(-) diff --git a/src/opengeodeweb_back/routes/create/schemas/edged_curve.py b/src/opengeodeweb_back/routes/create/schemas/edged_curve.py index 63dcd7bc..fb16e388 100644 --- a/src/opengeodeweb_back/routes/create/schemas/edged_curve.py +++ b/src/opengeodeweb_back/routes/create/schemas/edged_curve.py @@ -1,5 +1,5 @@ from opengeodeweb_microservice.schema_types import DataId, GeodeId -from opengeodeweb_back.schema_types import CRS, CollectionComponent, Point3D, ViewerId +from opengeodeweb_back.schema_types import CRS, CollectionComponent, MeshComponent, Point3D, ViewerId from opengeodeweb_microservice.database.data_types import GeodeObjectType, ViewerObjectType from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema @@ -20,21 +20,6 @@ def __post_init__(self) -> None: points: List[Point3D] -@dataclass -class MeshComponent(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - boundaries: List[GeodeId] - geode_id: GeodeId - internals: List[GeodeId] - is_active: bool - name: str - type: str - viewer_id: ViewerId - binary_light_viewable: Optional[str] = None - - @dataclass class EdgedCurveResponse(DataClassJsonMixin): def __post_init__(self) -> None: diff --git a/src/opengeodeweb_back/routes/create/schemas/horizon_stack.py b/src/opengeodeweb_back/routes/create/schemas/horizon_stack.py index b2b1abe4..d446c63c 100644 --- a/src/opengeodeweb_back/routes/create/schemas/horizon_stack.py +++ b/src/opengeodeweb_back/routes/create/schemas/horizon_stack.py @@ -1,5 +1,5 @@ from opengeodeweb_microservice.schema_types import DataId, GeodeId -from opengeodeweb_back.schema_types import CRS, CollectionComponent, ViewerId +from opengeodeweb_back.schema_types import CRS, CollectionComponent, MeshComponent, ViewerId from opengeodeweb_microservice.database.data_types import GeodeObjectType, ViewerObjectType from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema @@ -20,21 +20,6 @@ def __post_init__(self) -> None: unit_names: List[str] -@dataclass -class MeshComponent(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - boundaries: List[GeodeId] - geode_id: GeodeId - internals: List[GeodeId] - is_active: bool - name: str - type: str - viewer_id: ViewerId - binary_light_viewable: Optional[str] = None - - @dataclass class HorizonStackResponse(DataClassJsonMixin): def __post_init__(self) -> None: diff --git a/src/opengeodeweb_back/routes/create/schemas/point_set.py b/src/opengeodeweb_back/routes/create/schemas/point_set.py index 5d3e9c17..e0af2779 100644 --- a/src/opengeodeweb_back/routes/create/schemas/point_set.py +++ b/src/opengeodeweb_back/routes/create/schemas/point_set.py @@ -1,5 +1,5 @@ from opengeodeweb_microservice.schema_types import DataId, GeodeId -from opengeodeweb_back.schema_types import CRS, CollectionComponent, Point3D, ViewerId +from opengeodeweb_back.schema_types import CRS, CollectionComponent, MeshComponent, Point3D, ViewerId from opengeodeweb_microservice.database.data_types import GeodeObjectType, ViewerObjectType from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema @@ -19,21 +19,6 @@ def __post_init__(self) -> None: points: List[Point3D] -@dataclass -class MeshComponent(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - boundaries: List[GeodeId] - geode_id: GeodeId - internals: List[GeodeId] - is_active: bool - name: str - type: str - viewer_id: ViewerId - binary_light_viewable: Optional[str] = None - - @dataclass class PointSetResponse(DataClassJsonMixin): def __post_init__(self) -> None: diff --git a/src/opengeodeweb_back/routes/create/schemas/polygonal_surface.py b/src/opengeodeweb_back/routes/create/schemas/polygonal_surface.py index c790e11d..bcb9c117 100644 --- a/src/opengeodeweb_back/routes/create/schemas/polygonal_surface.py +++ b/src/opengeodeweb_back/routes/create/schemas/polygonal_surface.py @@ -1,5 +1,5 @@ from opengeodeweb_microservice.schema_types import DataId, GeodeId -from opengeodeweb_back.schema_types import CRS, CollectionComponent, Point3D, ViewerId +from opengeodeweb_back.schema_types import CRS, CollectionComponent, MeshComponent, Point3D, ViewerId from opengeodeweb_microservice.database.data_types import GeodeObjectType, ViewerObjectType from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema @@ -20,21 +20,6 @@ def __post_init__(self) -> None: polygons: List[List[int]] -@dataclass -class MeshComponent(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - boundaries: List[GeodeId] - geode_id: GeodeId - internals: List[GeodeId] - is_active: bool - name: str - type: str - viewer_id: ViewerId - binary_light_viewable: Optional[str] = None - - @dataclass class PolygonalSurfaceResponse(DataClassJsonMixin): def __post_init__(self) -> None: diff --git a/src/opengeodeweb_back/routes/schemas/save_viewable_file.py b/src/opengeodeweb_back/routes/schemas/save_viewable_file.py index 02b2539d..2db115e7 100644 --- a/src/opengeodeweb_back/routes/schemas/save_viewable_file.py +++ b/src/opengeodeweb_back/routes/schemas/save_viewable_file.py @@ -1,4 +1,4 @@ -from opengeodeweb_back.schema_types import CRS, CollectionComponent, Filename, ViewerId +from opengeodeweb_back.schema_types import CRS, CollectionComponent, Filename, MeshComponent, ViewerId from opengeodeweb_microservice.schema_types import DataId, GeodeId from opengeodeweb_microservice.database.data_types import GeodeObjectType, ViewerObjectType from pathlib import Path @@ -18,21 +18,6 @@ def __post_init__(self) -> None: geode_object_type: GeodeObjectType -@dataclass -class MeshComponent(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - boundaries: List[GeodeId] - geode_id: GeodeId - internals: List[GeodeId] - is_active: bool - name: str - type: str - viewer_id: ViewerId - binary_light_viewable: Optional[str] = None - - @dataclass class SaveViewableFileItem(DataClassJsonMixin): def __post_init__(self) -> None: From e9f61938f836bccd929eb1bcc447d52b8be9847b Mon Sep 17 00:00:00 2001 From: JulienChampagnol <91873154+JulienChampagnol@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:59:15 +0000 Subject: [PATCH 05/11] Apply prepare changes --- requirements.txt | 1 - src/opengeodeweb_back/schema_types.py | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements.txt b/requirements.txt index 5ff2753a..d6b4690c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -84,4 +84,3 @@ werkzeug==3.1.8 # flask # flask-cors -opengeodeweb-microservice==1.*,>=1.5.0 diff --git a/src/opengeodeweb_back/schema_types.py b/src/opengeodeweb_back/schema_types.py index e6148afd..c5a269ff 100644 --- a/src/opengeodeweb_back/schema_types.py +++ b/src/opengeodeweb_back/schema_types.py @@ -3,6 +3,7 @@ # ruff: noqa: TC002 from dataclasses import dataclass +from typing import Optional from dataclasses_json import DataClassJsonMixin from opengeodeweb_microservice.schema_types import GeodeId @@ -56,7 +57,7 @@ def __post_init__(self) -> None: name: str type: str viewer_id: ViewerId - binary_light_viewable: str | None = None + binary_light_viewable: Optional[str] = None @dataclass From 01f46c418da73b815b25ab7b9149e209e1730187 Mon Sep 17 00:00:00 2001 From: JulienChampagnol Date: Wed, 2 Dec 2026 11:39:10 +0100 Subject: [PATCH 06/11] fix(background_saves): reusable background save registry Co-Authored-By: Claude Opus 5.5 --- src/opengeodeweb_back/background_saves.py | 153 ++++++++++++++++++++++ src/opengeodeweb_back/utils_functions.py | 128 ++---------------- tests/test_background_native_save.py | 10 +- 3 files changed, 167 insertions(+), 124 deletions(-) create mode 100644 src/opengeodeweb_back/background_saves.py diff --git a/src/opengeodeweb_back/background_saves.py b/src/opengeodeweb_back/background_saves.py new file mode 100644 index 00000000..59cf2a2b --- /dev/null +++ b/src/opengeodeweb_back/background_saves.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +# Standard library imports +import logging +import threading +from concurrent.futures import Future, ThreadPoolExecutor, wait +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +# Third party imports +import flask + +if TYPE_CHECKING: + from collections.abc import Callable + +logger = logging.getLogger(__name__) + + +@dataclass +class _BackgroundSave: + """A background save. Its callable is kept until it is saved, to retry a failure.""" + + future: Future[object] + save: Callable[[], object] + # Held by a synchronous retry: a later save of the same data waits for it + retry_lock: threading.Lock = field(default_factory=threading.Lock) + retried: bool = False + + +class BackgroundSaves: + """Files of a data saved without blocking the request, one pending save per data. + + A task only uses what its callable captured: no app context nor DB session. + The Werkzeug debug reloader may kill a save mid-write (dev only). + """ + + def __init__(self, name: str) -> None: + self.name = name + # Several files can be imported at once, hence the default pool size + self._executor = ThreadPoolExecutor(thread_name_prefix=f"{name.replace(' ', '_')}_save") + self._lock = threading.Lock() + self._saves: dict[str, _BackgroundSave] = {} + + def submit(self, data_id: str, save: Callable[[], object]) -> None: + """Run save in background as the pending save of data_id.""" + + def run(previous: _BackgroundSave | None) -> object: + if previous is not None: + # A re-save of the same data supersedes the previous one, whatever its outcome, + # but never writes the same file at the same time. No deadlock: FIFO order puts + # the previous save ahead in the queue or running. + wait([previous.future]) + with previous.retry_lock: + pass + return save() + + # One critical section: two re-saves of the same data cannot chain on the same previous + with self._lock: + previous = self._saves.get(data_id) + future = self._executor.submit(run, previous) + self._saves[data_id] = _BackgroundSave(future, save) + # Outside the lock: the callback takes it, and runs here if the save is already done + future.add_done_callback(lambda done: self._forget(data_id, done)) + + def _forget(self, data_id: str, future: Future[object]) -> None: + """Drop a successful save from the registry; failed ones stay to be retried.""" + if future.cancelled() or future.exception() is not None: + return + with self._lock: + entry = self._saves.get(data_id) + if entry is not None and entry.future is future: + del self._saves[data_id] + + def _drop(self, data_id: str, entry: _BackgroundSave) -> None: + with self._lock: + if self._saves.get(data_id) is entry: + del self._saves[data_id] + + def discard(self, data_id: str) -> None: + """Wait for the save of data_id, if any, and forget it whatever its outcome.""" + with self._lock: + entry = self._saves.get(data_id) + if entry is None: + return + try: + entry.future.result() + except Exception: + logger.warning("Discarded failed %s save of %s", self.name, data_id, exc_info=True) + # A retry running on another thread must not write in a folder being removed, + # and none may start once the entry is dropped + with entry.retry_lock: + self._drop(data_id, entry) + + def _settle(self, data_id: str, entry: _BackgroundSave) -> Exception | None: + """Wait for entry; on failure, retry its save once on this thread. None once saved.""" + try: + entry.future.result() + except Exception as error: + with entry.retry_lock: + with self._lock: + superseded = self._saves.get(data_id) is not entry + if not entry.retried and not superseded: + logger.warning( + "%s save of %s failed, retrying", + self.name.capitalize(), + data_id, + exc_info=error, + ) + try: + entry.save() + except Exception as retry_error: + logger.exception( + "%s file of %s could not be saved", self.name.capitalize(), data_id + ) + return retry_error + entry.retried = True + self._drop(data_id, entry) + return None + + def _ensure(self, data_id: str) -> Exception | None: + """Wait until data_id has no pending save. The error of a save that failed twice, if any.""" + while True: + with self._lock: + entry = self._saves.get(data_id) + if entry is None: + return None + # A superseded entry is not dropped: the loop then waits for the newer save + error = self._settle(data_id, entry) + if error is not None: + return error + + def wait(self, data_id: str) -> None: + """Wait for the background save of data_id, if any, retrying a failure once.""" + error = self._ensure(data_id) + if error is not None: + # The failed save stays registered: a later call retries it again + flask.abort( + 500, f"{self.name.capitalize()} file of {data_id} could not be saved: {error}" + ) + + def wait_all(self) -> None: + """Wait for every pending save, retrying each failure once. + + Aborts once, naming every data whose file could not be saved. + """ + with self._lock: + pending = list(self._saves) + errors = {data_id: self._ensure(data_id) for data_id in pending} + failed = [f"{data_id} ({error})" for data_id, error in errors.items() if error] + if failed: + flask.abort( + 500, f"{self.name.capitalize()} files could not be saved: {', '.join(failed)}" + ) diff --git a/src/opengeodeweb_back/utils_functions.py b/src/opengeodeweb_back/utils_functions.py index 281fb0bf..c1a8a720 100644 --- a/src/opengeodeweb_back/utils_functions.py +++ b/src/opengeodeweb_back/utils_functions.py @@ -10,8 +10,7 @@ import time import uuid import zipfile -from concurrent.futures import Future, ThreadPoolExecutor, wait -from dataclasses import dataclass, field +from concurrent.futures import ThreadPoolExecutor from importlib import metadata from pathlib import Path from typing import TYPE_CHECKING, Any @@ -31,6 +30,7 @@ # Local application imports from . import geode_functions +from .background_saves import BackgroundSaves from .crs.crs_functions import active_crs from .geode_objects import geode_objects from .geode_objects.geode_model import GeodeModel @@ -38,10 +38,8 @@ logger = logging.getLogger(__name__) -# Native files are saved in background: the viewer only needs the viewables. -# Several files can be imported at once, hence the default pool size. -_native_executor = ThreadPoolExecutor(thread_name_prefix="native_save") -_native_saves_lock = threading.Lock() +# Native files are saved in background: the viewer only needs the viewables +native_saves = BackgroundSaves("native") if TYPE_CHECKING: from collections.abc import Callable, Sequence @@ -344,77 +342,13 @@ def model_components( } -@dataclass -class _NativeSave: - """A background native save. The object is kept until it is saved, to retry a failure.""" - - future: Future[list[str]] - geode_object: GeodeObject - native_path: str - # Held by a synchronous retry: a later save of the same data waits for it - retry_lock: threading.Lock = field(default_factory=threading.Lock) - retried: bool = False - - -_native_saves: dict[str, _NativeSave] = {} - - def _save_native_in_background(geode_object: GeodeObject, data_id: str, native_path: str) -> None: - """Save the native file without blocking the request. - - The task only uses the captured geode object: no app context nor DB session. - The Werkzeug debug reloader may kill a save mid-write (dev only). - """ - - def save_native(previous: _NativeSave | None) -> list[str]: - if previous is not None: - # A re-save of the same data supersedes the previous one, whatever its outcome, - # but never writes the same file at the same time. No deadlock: FIFO order puts - # the previous save ahead in the queue or running. - wait([previous.future]) - with previous.retry_lock: - pass - return geode_object.save(native_path) - - # One critical section: two re-saves of the same data cannot chain on the same previous - with _native_saves_lock: - previous = _native_saves.get(data_id) - future = _native_executor.submit(save_native, previous) - _native_saves[data_id] = _NativeSave(future, geode_object, native_path) - # Outside the lock: the callback takes it, and runs here if the save is already done - future.add_done_callback(lambda done: _forget_native_save(data_id, done)) - - -def _forget_native_save(data_id: str, future: Future[list[str]]) -> None: - """Drop a successful save from the registry; failed ones stay to be retried.""" - if future.cancelled() or future.exception() is not None: - return - with _native_saves_lock: - entry = _native_saves.get(data_id) - if entry is not None and entry.future is future: - del _native_saves[data_id] - - -def _drop_native_save(data_id: str, entry: _NativeSave) -> None: - with _native_saves_lock: - if _native_saves.get(data_id) is entry: - del _native_saves[data_id] + native_saves.submit(data_id, lambda: geode_object.save(native_path)) def discard_native_save(data_id: str) -> None: """Wait for the native save of data_id, if any, and forget it whatever its outcome.""" - with _native_saves_lock: - entry = _native_saves.get(data_id) - if entry is None: - return - try: - entry.future.result() - except Exception: - logger.warning("Discarded failed native save of %s", data_id, exc_info=True) - # A retry running on another thread must not write in a folder being removed, - # and none may start once the entry is dropped - with entry.retry_lock: - _drop_native_save(data_id, entry) + native_saves.discard(data_id) def remove_data_folder( @@ -427,58 +361,14 @@ def remove_data_folder( shutil.rmtree(folder, ignore_errors=ignore_errors) -def _settle_native_save(data_id: str, entry: _NativeSave) -> Exception | None: - """Wait for entry; on failure, retry its save once on this thread. None once saved.""" - try: - entry.future.result() - except Exception as error: - with entry.retry_lock: - with _native_saves_lock: - superseded = _native_saves.get(data_id) is not entry - if not entry.retried and not superseded: - logger.warning("Native save of %s failed, retrying", data_id, exc_info=error) - try: - entry.geode_object.save(entry.native_path) - except Exception as retry_error: - logger.exception("Native file of %s could not be saved", data_id) - return retry_error - entry.retried = True - _drop_native_save(data_id, entry) - return None - - -def _ensure_native_saved(data_id: str) -> Exception | None: - """Wait until data_id has no pending save. The error of a save that failed twice, if any.""" - while True: - with _native_saves_lock: - entry = _native_saves.get(data_id) - if entry is None: - return None - # A superseded entry is not dropped: the loop then waits for the newer save - error = _settle_native_save(data_id, entry) - if error is not None: - return error - - def wait_native_saved(data_id: str) -> None: """Wait for the background native save of data_id, if any, retrying a failure once.""" - error = _ensure_native_saved(data_id) - if error is not None: - # The failed save stays registered: a later call retries it again - flask.abort(500, f"Native file of {data_id} could not be saved: {error}") + native_saves.wait(data_id) def wait_all_native_saved() -> None: - """Wait for every pending background native save, retrying each failure once. - - Aborts once, naming every data whose native file could not be saved. - """ - with _native_saves_lock: - pending = list(_native_saves) - errors = {data_id: _ensure_native_saved(data_id) for data_id in pending} - failed = [f"{data_id} ({error})" for data_id, error in errors.items() if error] - if failed: - flask.abort(500, f"Native files could not be saved: {', '.join(failed)}") + """Wait for every pending background native save, retrying each failure once.""" + native_saves.wait_all() def save_all_viewables_and_return_info( diff --git a/tests/test_background_native_save.py b/tests/test_background_native_save.py index 7381feb6..7d18927d 100644 --- a/tests/test_background_native_save.py +++ b/tests/test_background_native_save.py @@ -132,7 +132,7 @@ def blocked_save(self: GeodeTriangulatedSurface3D, filename: str) -> list[str]: # No pending nor failed native save may leak into the next test with client.application.app_context(), contextlib.suppress(HTTPException): utils_functions.wait_all_native_saved() - utils_functions._native_saves.clear() # noqa: SLF001 + utils_functions.native_saves._saves.clear() # noqa: SLF001 def _in_thread[T](state: NativeSave, function: Callable[[], T]) -> Background[T]: @@ -293,8 +293,8 @@ def _test_surface() -> GeodeTriangulatedSurface3D: def _wait_registered_save(data_id: str) -> None: """Wait for the background save of data_id to end, without settling it.""" - with utils_functions._native_saves_lock: # noqa: SLF001 - entry = utils_functions._native_saves.get(data_id) # noqa: SLF001 + with utils_functions.native_saves._lock: # noqa: SLF001 + entry = utils_functions.native_saves._saves.get(data_id) # noqa: SLF001 if entry is not None: entry.future.exception(TIMEOUT) @@ -410,5 +410,5 @@ def test_basemap_delete_waits_for_native_save( response = delete.result() assert response.status_code == 200, response.get_json() assert not folder.exists() - with utils_functions._native_saves_lock: # noqa: SLF001 - assert data_id not in utils_functions._native_saves # noqa: SLF001 + with utils_functions.native_saves._lock: # noqa: SLF001 + assert data_id not in utils_functions.native_saves._saves # noqa: SLF001 From 04590dd1905ac60d12852226728fdbe3e9887238 Mon Sep 17 00:00:00 2001 From: JulienChampagnol Date: Wed, 2 Dec 2026 11:40:56 +0100 Subject: [PATCH 07/11] feat(geode_objects): bounding box viewable Co-Authored-By: Claude Opus 5.5 --- src/opengeodeweb_back/geode_objects/geode_brep.py | 4 ++++ src/opengeodeweb_back/geode_objects/geode_cross_section.py | 6 ++++++ src/opengeodeweb_back/geode_objects/geode_edged_curve2d.py | 6 ++++++ src/opengeodeweb_back/geode_objects/geode_edged_curve3d.py | 6 ++++++ src/opengeodeweb_back/geode_objects/geode_graph.py | 4 ++++ .../geode_objects/geode_horizon_stack3d.py | 4 ++++ src/opengeodeweb_back/geode_objects/geode_hybrid_solid3d.py | 6 ++++++ .../geode_objects/geode_implicit_cross_section.py | 6 ++++++ .../geode_objects/geode_implicit_structural_model.py | 6 ++++++ .../geode_objects/geode_light_regular_grid2d.py | 6 ++++++ .../geode_objects/geode_light_regular_grid3d.py | 6 ++++++ src/opengeodeweb_back/geode_objects/geode_object.py | 3 +++ src/opengeodeweb_back/geode_objects/geode_point_set2d.py | 6 ++++++ src/opengeodeweb_back/geode_objects/geode_point_set3d.py | 6 ++++++ .../geode_objects/geode_polygonal_surface2d.py | 6 ++++++ .../geode_objects/geode_polygonal_surface3d.py | 6 ++++++ .../geode_objects/geode_polyhedral_solid3d.py | 6 ++++++ src/opengeodeweb_back/geode_objects/geode_raster_image2d.py | 6 ++++++ src/opengeodeweb_back/geode_objects/geode_raster_image3d.py | 6 ++++++ src/opengeodeweb_back/geode_objects/geode_regular_grid2d.py | 6 ++++++ src/opengeodeweb_back/geode_objects/geode_regular_grid3d.py | 6 ++++++ src/opengeodeweb_back/geode_objects/geode_section.py | 6 ++++++ .../geode_objects/geode_structural_model.py | 6 ++++++ .../geode_objects/geode_tetrahedral_solid3d.py | 6 ++++++ .../geode_objects/geode_triangulated_surface2d.py | 6 ++++++ .../geode_objects/geode_triangulated_surface3d.py | 6 ++++++ src/opengeodeweb_back/geode_objects/geode_vertex_set.py | 4 ++++ tests/test_geode_functions.py | 6 ++++++ 28 files changed, 157 insertions(+) diff --git a/src/opengeodeweb_back/geode_objects/geode_brep.py b/src/opengeodeweb_back/geode_objects/geode_brep.py index 5fefff53..84a979a5 100644 --- a/src/opengeodeweb_back/geode_objects/geode_brep.py +++ b/src/opengeodeweb_back/geode_objects/geode_brep.py @@ -109,6 +109,10 @@ def save_viewable(self, filename_without_extension: str) -> str: def save_light_viewable(self, filename_without_extension: str) -> str: return viewables.save_light_viewable_brep(self.brep, filename_without_extension) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_brep(self.brep, filename_without_extension) + @override def mesh_components(self) -> ComponentRegistry: return self.brep.mesh_components() diff --git a/src/opengeodeweb_back/geode_objects/geode_cross_section.py b/src/opengeodeweb_back/geode_objects/geode_cross_section.py index 11a5b765..dd40df1b 100644 --- a/src/opengeodeweb_back/geode_objects/geode_cross_section.py +++ b/src/opengeodeweb_back/geode_objects/geode_cross_section.py @@ -88,6 +88,12 @@ def save_light_viewable(self, filename_without_extension: str) -> str: self.cross_section, filename_without_extension ) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_cross_section( + self.cross_section, filename_without_extension + ) + def component_name(self, component_id: og.uuid) -> str | None: return self.cross_section.cross_section_component(component_id).name() diff --git a/src/opengeodeweb_back/geode_objects/geode_edged_curve2d.py b/src/opengeodeweb_back/geode_objects/geode_edged_curve2d.py index 5c1a6146..196904a6 100644 --- a/src/opengeodeweb_back/geode_objects/geode_edged_curve2d.py +++ b/src/opengeodeweb_back/geode_objects/geode_edged_curve2d.py @@ -100,6 +100,12 @@ def save_light_viewable(self, filename_without_extension: str) -> str: self.edged_curve, filename_without_extension ) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_edged_curve2D( + self.edged_curve, filename_without_extension + ) + @override def inspect(self) -> og_inspector.EdgedCurveInspectionResult: return og_inspector.inspect_edged_curve2D(self.edged_curve) diff --git a/src/opengeodeweb_back/geode_objects/geode_edged_curve3d.py b/src/opengeodeweb_back/geode_objects/geode_edged_curve3d.py index 0e545243..cb2c9e2b 100644 --- a/src/opengeodeweb_back/geode_objects/geode_edged_curve3d.py +++ b/src/opengeodeweb_back/geode_objects/geode_edged_curve3d.py @@ -100,6 +100,12 @@ def save_light_viewable(self, filename_without_extension: str) -> str: self.edged_curve, filename_without_extension ) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_edged_curve3D( + self.edged_curve, filename_without_extension + ) + @override def inspect(self) -> og_inspector.EdgedCurveInspectionResult: return og_inspector.inspect_edged_curve3D(self.edged_curve) diff --git a/src/opengeodeweb_back/geode_objects/geode_graph.py b/src/opengeodeweb_back/geode_objects/geode_graph.py index c95a0c69..3cddc407 100644 --- a/src/opengeodeweb_back/geode_objects/geode_graph.py +++ b/src/opengeodeweb_back/geode_objects/geode_graph.py @@ -100,6 +100,10 @@ def save_viewable(self, filename_without_extension: str) -> str: def save_light_viewable(self, filename_without_extension: str) -> str: return "" + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return "" + @override def inspect(self) -> object: return None diff --git a/src/opengeodeweb_back/geode_objects/geode_horizon_stack3d.py b/src/opengeodeweb_back/geode_objects/geode_horizon_stack3d.py index 9e5886c4..02470095 100644 --- a/src/opengeodeweb_back/geode_objects/geode_horizon_stack3d.py +++ b/src/opengeodeweb_back/geode_objects/geode_horizon_stack3d.py @@ -95,6 +95,10 @@ def save_viewable(self, filename_without_extension: str) -> str: def save_light_viewable(self, filename_without_extension: str) -> str: return "" + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return "" + @override def mesh_components(self) -> ComponentRegistry: return {} diff --git a/src/opengeodeweb_back/geode_objects/geode_hybrid_solid3d.py b/src/opengeodeweb_back/geode_objects/geode_hybrid_solid3d.py index 29acbd7e..687c4f7b 100644 --- a/src/opengeodeweb_back/geode_objects/geode_hybrid_solid3d.py +++ b/src/opengeodeweb_back/geode_objects/geode_hybrid_solid3d.py @@ -84,3 +84,9 @@ def save_light_viewable(self, filename_without_extension: str) -> str: return viewables.save_light_viewable_hybrid_solid3D( self.hybrid_solid, filename_without_extension ) + + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_hybrid_solid3D( + self.hybrid_solid, filename_without_extension + ) diff --git a/src/opengeodeweb_back/geode_objects/geode_implicit_cross_section.py b/src/opengeodeweb_back/geode_objects/geode_implicit_cross_section.py index 7fc6d273..27a3dba9 100644 --- a/src/opengeodeweb_back/geode_objects/geode_implicit_cross_section.py +++ b/src/opengeodeweb_back/geode_objects/geode_implicit_cross_section.py @@ -98,3 +98,9 @@ def save_light_viewable(self, filename_without_extension: str) -> str: return viewables.save_light_viewable_implicit_cross_section( self.implicit_cross_section, filename_without_extension ) + + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_implicit_cross_section( + self.implicit_cross_section, filename_without_extension + ) diff --git a/src/opengeodeweb_back/geode_objects/geode_implicit_structural_model.py b/src/opengeodeweb_back/geode_objects/geode_implicit_structural_model.py index 8a1cabea..68ed80f5 100644 --- a/src/opengeodeweb_back/geode_objects/geode_implicit_structural_model.py +++ b/src/opengeodeweb_back/geode_objects/geode_implicit_structural_model.py @@ -101,3 +101,9 @@ def save_light_viewable(self, filename_without_extension: str) -> str: return viewables.save_light_viewable_implicit_structural_model( self.implicit_structural_model, filename_without_extension ) + + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_implicit_structural_model( + self.implicit_structural_model, filename_without_extension + ) diff --git a/src/opengeodeweb_back/geode_objects/geode_light_regular_grid2d.py b/src/opengeodeweb_back/geode_objects/geode_light_regular_grid2d.py index 7adf6824..4b2ff836 100644 --- a/src/opengeodeweb_back/geode_objects/geode_light_regular_grid2d.py +++ b/src/opengeodeweb_back/geode_objects/geode_light_regular_grid2d.py @@ -87,6 +87,12 @@ def save_light_viewable(self, filename_without_extension: str) -> str: self.light_regular_grid, filename_without_extension ) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_light_regular_grid2D( + self.light_regular_grid, filename_without_extension + ) + @override def vertex_attribute_manager(self) -> og.AttributeManager: return self.light_regular_grid.grid_vertex_attribute_manager() diff --git a/src/opengeodeweb_back/geode_objects/geode_light_regular_grid3d.py b/src/opengeodeweb_back/geode_objects/geode_light_regular_grid3d.py index 29ebc8f9..9d2c0e0c 100644 --- a/src/opengeodeweb_back/geode_objects/geode_light_regular_grid3d.py +++ b/src/opengeodeweb_back/geode_objects/geode_light_regular_grid3d.py @@ -87,6 +87,12 @@ def save_light_viewable(self, filename_without_extension: str) -> str: self.light_regular_grid, filename_without_extension ) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_light_regular_grid3D( + self.light_regular_grid, filename_without_extension + ) + @override def vertex_attribute_manager(self) -> og.AttributeManager: return self.light_regular_grid.grid_vertex_attribute_manager() diff --git a/src/opengeodeweb_back/geode_objects/geode_object.py b/src/opengeodeweb_back/geode_objects/geode_object.py index a0159ee4..b778c11f 100644 --- a/src/opengeodeweb_back/geode_objects/geode_object.py +++ b/src/opengeodeweb_back/geode_objects/geode_object.py @@ -104,6 +104,9 @@ def save_viewable(self, filename_without_extension: str) -> str: ... @abstractmethod def save_light_viewable(self, filename_without_extension: str) -> str: ... + @abstractmethod + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: ... + @abstractmethod def inspect(self) -> object: ... diff --git a/src/opengeodeweb_back/geode_objects/geode_point_set2d.py b/src/opengeodeweb_back/geode_objects/geode_point_set2d.py index 137161ef..13234083 100644 --- a/src/opengeodeweb_back/geode_objects/geode_point_set2d.py +++ b/src/opengeodeweb_back/geode_objects/geode_point_set2d.py @@ -98,6 +98,12 @@ def save_viewable(self, filename_without_extension: str) -> str: def save_light_viewable(self, filename_without_extension: str) -> str: return viewables.save_light_viewable_point_set2D(self.point_set, filename_without_extension) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_point_set2D( + self.point_set, filename_without_extension + ) + @override def inspect(self) -> og_inspector.PointSetInspectionResult: return og_inspector.inspect_point_set2D(self.point_set) diff --git a/src/opengeodeweb_back/geode_objects/geode_point_set3d.py b/src/opengeodeweb_back/geode_objects/geode_point_set3d.py index 309d61f7..9429cea9 100644 --- a/src/opengeodeweb_back/geode_objects/geode_point_set3d.py +++ b/src/opengeodeweb_back/geode_objects/geode_point_set3d.py @@ -98,6 +98,12 @@ def save_viewable(self, filename_without_extension: str) -> str: def save_light_viewable(self, filename_without_extension: str) -> str: return viewables.save_light_viewable_point_set3D(self.point_set, filename_without_extension) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_point_set3D( + self.point_set, filename_without_extension + ) + @override def inspect(self) -> og_inspector.PointSetInspectionResult: return og_inspector.inspect_point_set3D(self.point_set) diff --git a/src/opengeodeweb_back/geode_objects/geode_polygonal_surface2d.py b/src/opengeodeweb_back/geode_objects/geode_polygonal_surface2d.py index 4d137be3..f96665f3 100644 --- a/src/opengeodeweb_back/geode_objects/geode_polygonal_surface2d.py +++ b/src/opengeodeweb_back/geode_objects/geode_polygonal_surface2d.py @@ -88,3 +88,9 @@ def save_light_viewable(self, filename_without_extension: str) -> str: return viewables.save_light_viewable_polygonal_surface2D( self.polygonal_surface, filename_without_extension ) + + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_polygonal_surface2D( + self.polygonal_surface, filename_without_extension + ) diff --git a/src/opengeodeweb_back/geode_objects/geode_polygonal_surface3d.py b/src/opengeodeweb_back/geode_objects/geode_polygonal_surface3d.py index a3935fb9..5fb2b54a 100644 --- a/src/opengeodeweb_back/geode_objects/geode_polygonal_surface3d.py +++ b/src/opengeodeweb_back/geode_objects/geode_polygonal_surface3d.py @@ -88,3 +88,9 @@ def save_light_viewable(self, filename_without_extension: str) -> str: return viewables.save_light_viewable_polygonal_surface3D( self.polygonal_surface, filename_without_extension ) + + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_polygonal_surface3D( + self.polygonal_surface, filename_without_extension + ) diff --git a/src/opengeodeweb_back/geode_objects/geode_polyhedral_solid3d.py b/src/opengeodeweb_back/geode_objects/geode_polyhedral_solid3d.py index a705b419..c4b38f84 100644 --- a/src/opengeodeweb_back/geode_objects/geode_polyhedral_solid3d.py +++ b/src/opengeodeweb_back/geode_objects/geode_polyhedral_solid3d.py @@ -88,3 +88,9 @@ def save_light_viewable(self, filename_without_extension: str) -> str: return viewables.save_light_viewable_polyhedral_solid3D( self.polyhedral_solid, filename_without_extension ) + + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_polyhedral_solid3D( + self.polyhedral_solid, filename_without_extension + ) diff --git a/src/opengeodeweb_back/geode_objects/geode_raster_image2d.py b/src/opengeodeweb_back/geode_objects/geode_raster_image2d.py index fc08e3c6..0e53d33a 100644 --- a/src/opengeodeweb_back/geode_objects/geode_raster_image2d.py +++ b/src/opengeodeweb_back/geode_objects/geode_raster_image2d.py @@ -104,6 +104,12 @@ def save_light_viewable(self, filename_without_extension: str) -> str: self.raster_image, filename_without_extension ) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_raster_image2D( + self.raster_image, filename_without_extension + ) + @override def inspect(self) -> None: return None diff --git a/src/opengeodeweb_back/geode_objects/geode_raster_image3d.py b/src/opengeodeweb_back/geode_objects/geode_raster_image3d.py index a459a298..2b4cc51a 100644 --- a/src/opengeodeweb_back/geode_objects/geode_raster_image3d.py +++ b/src/opengeodeweb_back/geode_objects/geode_raster_image3d.py @@ -104,6 +104,12 @@ def save_light_viewable(self, filename_without_extension: str) -> str: self.raster_image, filename_without_extension ) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_raster_image3D( + self.raster_image, filename_without_extension + ) + @override def inspect(self) -> None: return None diff --git a/src/opengeodeweb_back/geode_objects/geode_regular_grid2d.py b/src/opengeodeweb_back/geode_objects/geode_regular_grid2d.py index 8874eafc..0c81334e 100644 --- a/src/opengeodeweb_back/geode_objects/geode_regular_grid2d.py +++ b/src/opengeodeweb_back/geode_objects/geode_regular_grid2d.py @@ -92,6 +92,12 @@ def save_light_viewable(self, filename_without_extension: str) -> str: self.regular_grid, filename_without_extension ) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_regular_grid2D( + self.regular_grid, filename_without_extension + ) + @override def cell_attribute_manager(self) -> og.AttributeManager: return self.regular_grid.cell_attribute_manager() diff --git a/src/opengeodeweb_back/geode_objects/geode_regular_grid3d.py b/src/opengeodeweb_back/geode_objects/geode_regular_grid3d.py index 97bb6761..cabf7714 100644 --- a/src/opengeodeweb_back/geode_objects/geode_regular_grid3d.py +++ b/src/opengeodeweb_back/geode_objects/geode_regular_grid3d.py @@ -88,6 +88,12 @@ def save_light_viewable(self, filename_without_extension: str) -> str: self.regular_grid, filename_without_extension ) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_regular_grid3D( + self.regular_grid, filename_without_extension + ) + @override def cell_attribute_manager(self) -> og.AttributeManager: return self.regular_grid.cell_attribute_manager() diff --git a/src/opengeodeweb_back/geode_objects/geode_section.py b/src/opengeodeweb_back/geode_objects/geode_section.py index 3b7d4bea..8c6f10c0 100644 --- a/src/opengeodeweb_back/geode_objects/geode_section.py +++ b/src/opengeodeweb_back/geode_objects/geode_section.py @@ -98,6 +98,12 @@ def save_viewable(self, filename_without_extension: str) -> str: def save_light_viewable(self, filename_without_extension: str) -> str: return viewables.save_light_viewable_section(self.section, filename_without_extension) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_section( + self.section, filename_without_extension + ) + @override def mesh_components(self) -> ComponentRegistry: return self.section.mesh_components() diff --git a/src/opengeodeweb_back/geode_objects/geode_structural_model.py b/src/opengeodeweb_back/geode_objects/geode_structural_model.py index 03374b7f..c216d6d4 100644 --- a/src/opengeodeweb_back/geode_objects/geode_structural_model.py +++ b/src/opengeodeweb_back/geode_objects/geode_structural_model.py @@ -90,6 +90,12 @@ def save_light_viewable(self, filename_without_extension: str) -> str: self.structural_model, filename_without_extension ) + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_structural_model( + self.structural_model, filename_without_extension + ) + def component_name(self, component_id: og.uuid) -> str | None: return self.structural_model.structural_model_component(component_id).name() diff --git a/src/opengeodeweb_back/geode_objects/geode_tetrahedral_solid3d.py b/src/opengeodeweb_back/geode_objects/geode_tetrahedral_solid3d.py index a1215001..e13a8e12 100644 --- a/src/opengeodeweb_back/geode_objects/geode_tetrahedral_solid3d.py +++ b/src/opengeodeweb_back/geode_objects/geode_tetrahedral_solid3d.py @@ -88,3 +88,9 @@ def save_light_viewable(self, filename_without_extension: str) -> str: return viewables.save_light_viewable_tetrahedral_solid3D( self.tetrahedral_solid, filename_without_extension ) + + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_tetrahedral_solid3D( + self.tetrahedral_solid, filename_without_extension + ) diff --git a/src/opengeodeweb_back/geode_objects/geode_triangulated_surface2d.py b/src/opengeodeweb_back/geode_objects/geode_triangulated_surface2d.py index ac1227d3..c900ed99 100644 --- a/src/opengeodeweb_back/geode_objects/geode_triangulated_surface2d.py +++ b/src/opengeodeweb_back/geode_objects/geode_triangulated_surface2d.py @@ -90,3 +90,9 @@ def save_light_viewable(self, filename_without_extension: str) -> str: return viewables.save_light_viewable_triangulated_surface2D( self.triangulated_surface, filename_without_extension ) + + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_triangulated_surface2D( + self.triangulated_surface, filename_without_extension + ) diff --git a/src/opengeodeweb_back/geode_objects/geode_triangulated_surface3d.py b/src/opengeodeweb_back/geode_objects/geode_triangulated_surface3d.py index 5857d921..4da69205 100644 --- a/src/opengeodeweb_back/geode_objects/geode_triangulated_surface3d.py +++ b/src/opengeodeweb_back/geode_objects/geode_triangulated_surface3d.py @@ -90,3 +90,9 @@ def save_light_viewable(self, filename_without_extension: str) -> str: return viewables.save_light_viewable_triangulated_surface3D( self.triangulated_surface, filename_without_extension ) + + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return viewables.save_bounding_box_viewable_triangulated_surface3D( + self.triangulated_surface, filename_without_extension + ) diff --git a/src/opengeodeweb_back/geode_objects/geode_vertex_set.py b/src/opengeodeweb_back/geode_objects/geode_vertex_set.py index 9f8c2926..42187199 100644 --- a/src/opengeodeweb_back/geode_objects/geode_vertex_set.py +++ b/src/opengeodeweb_back/geode_objects/geode_vertex_set.py @@ -100,6 +100,10 @@ def save_viewable(self, filename_without_extension: str) -> str: def save_light_viewable(self, filename_without_extension: str) -> str: return "" + @override + def save_bounding_box_viewable(self, filename_without_extension: str) -> str: + return "" + @override def inspect(self) -> object: return None diff --git a/tests/test_geode_functions.py b/tests/test_geode_functions.py index 055acf77..dc33dbc0 100644 --- a/tests/test_geode_functions.py +++ b/tests/test_geode_functions.py @@ -45,6 +45,12 @@ def check_save_and_output_extensions(geode_object: GeodeObject, file_absolute_pa light_viewable_file_path = geode_object.save_light_viewable(str(output_folder / data_name)) Path(light_viewable_file_path).unlink() shutil.rmtree(Path(light_viewable_file_path).with_suffix(""), ignore_errors=True) + bounding_box_file_path = geode_object.save_bounding_box_viewable( + str(output_folder / f"{data_name}_box") + ) + assert bounding_box_file_path.endswith(".vtp") + assert Path(bounding_box_file_path).read_bytes().startswith(b" Date: Wed, 2 Dec 2026 11:43:53 +0100 Subject: [PATCH 08/11] feat(light_viewable): bounding box at import, light viewable in background Co-Authored-By: Claude Opus 5.5 --- opengeodeweb_back_schemas.json | 251 ------------------ opengeodeweb_back_typed_schemas.d.ts | 4 - .../routes/crs/blueprint_crs.py | 3 +- .../routes/crs/schemas/align.json | 12 - .../routes/crs/schemas/align.py | 36 +-- .../crs/schemas/convert_geographic.json | 12 - .../routes/crs/schemas/convert_geographic.py | 36 +-- src/opengeodeweb_back/schema_definitions.json | 3 - src/opengeodeweb_back/schema_types.d.ts | 15 +- src/opengeodeweb_back/schema_types.json | 3 - src/opengeodeweb_back/schema_types.py | 2 - src/opengeodeweb_back/test_utils.py | 7 - src/opengeodeweb_back/utils_functions.py | 59 ++-- tests/test_crs_routes.py | 19 +- tests/test_utils_functions.py | 51 ++-- 15 files changed, 85 insertions(+), 428 deletions(-) diff --git a/opengeodeweb_back_schemas.json b/opengeodeweb_back_schemas.json index 21e4afeb..89fad98e 100644 --- a/opengeodeweb_back_schemas.json +++ b/opengeodeweb_back_schemas.json @@ -474,9 +474,6 @@ }, "is_active": { "type": "boolean" - }, - "binary_light_viewable": { - "type": "string" } }, "required": [ @@ -728,9 +725,6 @@ }, "is_active": { "type": "boolean" - }, - "binary_light_viewable": { - "type": "string" } }, "required": [ @@ -973,9 +967,6 @@ }, "is_active": { "type": "boolean" - }, - "binary_light_viewable": { - "type": "string" } }, "required": [ @@ -1240,9 +1231,6 @@ }, "is_active": { "type": "boolean" - }, - "binary_light_viewable": { - "type": "string" } }, "required": [ @@ -1475,65 +1463,6 @@ "binary_light_viewable": { "type": "string" }, - "mesh_components": { - "type": "array", - "items": { - "title": "MeshComponent", - "type": "object", - "properties": { - "viewer_id": { - "title": "ViewerId", - "type": "integer" - }, - "geode_id": { - "title": "GeodeId", - "type": "string", - "minLength": 36, - "maxLength": 36 - }, - "name": { - "type": "string" - }, - "type": { - "type": "string" - }, - "boundaries": { - "type": "array", - "items": { - "title": "GeodeId", - "type": "string", - "minLength": 36, - "maxLength": 36 - } - }, - "internals": { - "type": "array", - "items": { - "title": "GeodeId", - "type": "string", - "minLength": 36, - "maxLength": 36 - } - }, - "is_active": { - "type": "boolean" - }, - "binary_light_viewable": { - "type": "string" - } - }, - "required": [ - "viewer_id", - "geode_id", - "name", - "type", - "boundaries", - "internals", - "is_active" - ], - "additionalProperties": false - } - }, "crs": { "title": "CRS", "type": "object", @@ -1595,65 +1524,6 @@ }, "binary_light_viewable": { "type": "string" - }, - "mesh_components": { - "type": "array", - "items": { - "title": "MeshComponent", - "type": "object", - "properties": { - "viewer_id": { - "title": "ViewerId", - "type": "integer" - }, - "geode_id": { - "title": "GeodeId", - "type": "string", - "minLength": 36, - "maxLength": 36 - }, - "name": { - "type": "string" - }, - "type": { - "type": "string" - }, - "boundaries": { - "type": "array", - "items": { - "title": "GeodeId", - "type": "string", - "minLength": 36, - "maxLength": 36 - } - }, - "internals": { - "type": "array", - "items": { - "title": "GeodeId", - "type": "string", - "minLength": 36, - "maxLength": 36 - } - }, - "is_active": { - "type": "boolean" - }, - "binary_light_viewable": { - "type": "string" - } - }, - "required": [ - "viewer_id", - "geode_id", - "name", - "type", - "boundaries", - "internals", - "is_active" - ], - "additionalProperties": false - } } }, "required": [ @@ -1898,65 +1768,6 @@ "binary_light_viewable": { "type": "string" }, - "mesh_components": { - "type": "array", - "items": { - "title": "MeshComponent", - "type": "object", - "properties": { - "viewer_id": { - "title": "ViewerId", - "type": "integer" - }, - "geode_id": { - "title": "GeodeId", - "type": "string", - "minLength": 36, - "maxLength": 36 - }, - "name": { - "type": "string" - }, - "type": { - "type": "string" - }, - "boundaries": { - "type": "array", - "items": { - "title": "GeodeId", - "type": "string", - "minLength": 36, - "maxLength": 36 - } - }, - "internals": { - "type": "array", - "items": { - "title": "GeodeId", - "type": "string", - "minLength": 36, - "maxLength": 36 - } - }, - "is_active": { - "type": "boolean" - }, - "binary_light_viewable": { - "type": "string" - } - }, - "required": [ - "viewer_id", - "geode_id", - "name", - "type", - "boundaries", - "internals", - "is_active" - ], - "additionalProperties": false - } - }, "crs": { "title": "CRS", "type": "object", @@ -1995,65 +1806,6 @@ "binary_light_viewable": { "type": "string" }, - "mesh_components": { - "type": "array", - "items": { - "title": "MeshComponent", - "type": "object", - "properties": { - "viewer_id": { - "title": "ViewerId", - "type": "integer" - }, - "geode_id": { - "title": "GeodeId", - "type": "string", - "minLength": 36, - "maxLength": 36 - }, - "name": { - "type": "string" - }, - "type": { - "type": "string" - }, - "boundaries": { - "type": "array", - "items": { - "title": "GeodeId", - "type": "string", - "minLength": 36, - "maxLength": 36 - } - }, - "internals": { - "type": "array", - "items": { - "title": "GeodeId", - "type": "string", - "minLength": 36, - "maxLength": 36 - } - }, - "is_active": { - "type": "boolean" - }, - "binary_light_viewable": { - "type": "string" - } - }, - "required": [ - "viewer_id", - "geode_id", - "name", - "type", - "boundaries", - "internals", - "is_active" - ], - "additionalProperties": false - } - }, "crs": { "title": "CRS", "type": "object", @@ -2614,9 +2366,6 @@ }, "is_active": { "type": "boolean" - }, - "binary_light_viewable": { - "type": "string" } }, "required": [ diff --git a/opengeodeweb_back_typed_schemas.d.ts b/opengeodeweb_back_typed_schemas.d.ts index 3f8f6c97..8dcc3f2b 100644 --- a/opengeodeweb_back_typed_schemas.d.ts +++ b/opengeodeweb_back_typed_schemas.d.ts @@ -170,14 +170,12 @@ export interface CRSConvertGeographicResponse { binary_light_viewable?: string; crs?: CRS; linked?: CRSConvertGeographicResponseLinked[]; - mesh_components?: MeshComponent[]; } export interface CRSConvertGeographicResponseLinked { binary_light_viewable?: string; crs?: CRS; id: DataId; - mesh_components?: MeshComponent[]; } export interface CRSAssignGeographicParams { @@ -228,14 +226,12 @@ export interface CRSAlignResponse { binary_light_viewable?: string; crs?: CRS; linked?: CRSAlignResponseLinked[]; - mesh_components?: MeshComponent[]; } export interface CRSAlignResponseLinked { binary_light_viewable?: string; crs?: CRS; id: DataId; - mesh_components?: MeshComponent[]; } export interface CRSActiveParams { diff --git a/src/opengeodeweb_back/routes/crs/blueprint_crs.py b/src/opengeodeweb_back/routes/crs/blueprint_crs.py index 4888b420..fb167e78 100644 --- a/src/opengeodeweb_back/routes/crs/blueprint_crs.py +++ b/src/opengeodeweb_back/routes/crs/blueprint_crs.py @@ -45,8 +45,7 @@ def _bad_request() -> Generator[None]: def _crs_response(saved: dict[str, Any]) -> dict[str, Any]: # Only the fields the front refreshes after a CRS change - refreshed = ("crs", "binary_light_viewable", "mesh_components") - return {key: saved[key] for key in refreshed if key in saved} + return {key: saved[key] for key in ("crs", "binary_light_viewable") if key in saved} def _saved_response(data_id: str, data: Data, geode_object: CrsGeodeObject) -> dict[str, Any]: diff --git a/src/opengeodeweb_back/routes/crs/schemas/align.json b/src/opengeodeweb_back/routes/crs/schemas/align.json index 3183f121..287f47bf 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/align.json +++ b/src/opengeodeweb_back/routes/crs/schemas/align.json @@ -89,12 +89,6 @@ "binary_light_viewable": { "type": "string" }, - "mesh_components": { - "type": "array", - "items": { - "title": "MeshComponent" - } - }, "crs": { "title": "CRS" }, @@ -109,12 +103,6 @@ "binary_light_viewable": { "type": "string" }, - "mesh_components": { - "type": "array", - "items": { - "title": "MeshComponent" - } - }, "crs": { "title": "CRS" } diff --git a/src/opengeodeweb_back/routes/crs/schemas/align.py b/src/opengeodeweb_back/routes/crs/schemas/align.py index 214fa943..3dc1ad00 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/align.py +++ b/src/opengeodeweb_back/routes/crs/schemas/align.py @@ -1,8 +1,6 @@ -from opengeodeweb_microservice.schema_types import DataId, GeodeId -from opengeodeweb_back.schema_types import ViewerId +from opengeodeweb_microservice.schema_types import DataId from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema -from typing import List, Optional from dataclasses_json import DataClassJsonMixin from opengeodeweb_microservice.schemas import print_dataclass from dataclasses import dataclass @@ -62,21 +60,6 @@ def __post_init__(self) -> None: name: str -@dataclass -class LinkedMeshComponent(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - boundaries: List[GeodeId] - geode_id: GeodeId - internals: List[GeodeId] - is_active: bool - name: str - type: str - viewer_id: ViewerId - binary_light_viewable: Optional[str] = None - - @dataclass class Linked(DataClassJsonMixin): def __post_init__(self) -> None: @@ -85,22 +68,6 @@ def __post_init__(self) -> None: id: DataId binary_light_viewable: Optional[str] = None crs: Optional[LinkedCRS] = None - mesh_components: Optional[List[LinkedMeshComponent]] = None - - -@dataclass -class AlignResponseMeshComponent(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - boundaries: List[GeodeId] - geode_id: GeodeId - internals: List[GeodeId] - is_active: bool - name: str - type: str - viewer_id: ViewerId - binary_light_viewable: Optional[str] = None @dataclass @@ -111,7 +78,6 @@ def __post_init__(self) -> None: binary_light_viewable: Optional[str] = None crs: Optional[AlignResponseCRS] = None linked: Optional[List[Linked]] = None - mesh_components: Optional[List[AlignResponseMeshComponent]] = None align_route = Route( diff --git a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.json b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.json index e0ba50f7..262a6f30 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.json +++ b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.json @@ -41,12 +41,6 @@ "binary_light_viewable": { "type": "string" }, - "mesh_components": { - "type": "array", - "items": { - "title": "MeshComponent" - } - }, "crs": { "title": "CRS" }, @@ -63,12 +57,6 @@ }, "binary_light_viewable": { "type": "string" - }, - "mesh_components": { - "type": "array", - "items": { - "title": "MeshComponent" - } } }, "required": [ diff --git a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py index 739e4e93..465c3446 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py +++ b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py @@ -1,7 +1,7 @@ -from opengeodeweb_microservice.schema_types import DataId, GeodeId -from opengeodeweb_back.schema_types import ViewerId +from opengeodeweb_microservice.schema_types import DataId from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema +from typing import Optional, List from dataclasses_json import DataClassJsonMixin from opengeodeweb_microservice.schemas import print_dataclass from dataclasses import dataclass @@ -40,21 +40,6 @@ def __post_init__(self) -> None: name: str -@dataclass -class LinkedMeshComponent(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - boundaries: List[GeodeId] - geode_id: GeodeId - internals: List[GeodeId] - is_active: bool - name: str - type: str - viewer_id: ViewerId - binary_light_viewable: Optional[str] = None - - @dataclass class Linked(DataClassJsonMixin): def __post_init__(self) -> None: @@ -63,22 +48,6 @@ def __post_init__(self) -> None: id: DataId binary_light_viewable: Optional[str] = None crs: Optional[LinkedCRS] = None - mesh_components: Optional[List[LinkedMeshComponent]] = None - - -@dataclass -class ConvertGeographicResponseMeshComponent(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - boundaries: List[GeodeId] - geode_id: GeodeId - internals: List[GeodeId] - is_active: bool - name: str - type: str - viewer_id: ViewerId - binary_light_viewable: Optional[str] = None @dataclass @@ -89,7 +58,6 @@ def __post_init__(self) -> None: binary_light_viewable: Optional[str] = None crs: Optional[ConvertGeographicResponseCRS] = None linked: Optional[List[Linked]] = None - mesh_components: Optional[List[ConvertGeographicResponseMeshComponent]] = None convert_geographic_route = Route( diff --git a/src/opengeodeweb_back/schema_definitions.json b/src/opengeodeweb_back/schema_definitions.json index cc505528..0a04f5b7 100644 --- a/src/opengeodeweb_back/schema_definitions.json +++ b/src/opengeodeweb_back/schema_definitions.json @@ -252,9 +252,6 @@ }, "is_active": { "type": "boolean" - }, - "binary_light_viewable": { - "type": "string" } }, "required": [ diff --git a/src/opengeodeweb_back/schema_types.d.ts b/src/opengeodeweb_back/schema_types.d.ts index 50fb46f4..7cc8de14 100644 --- a/src/opengeodeweb_back/schema_types.d.ts +++ b/src/opengeodeweb_back/schema_types.d.ts @@ -26,14 +26,13 @@ export interface CRS { } export interface MeshComponent { - binary_light_viewable?: string; - boundaries: GeodeId[]; - geode_id: GeodeId; - internals: GeodeId[]; - is_active: boolean; - name: string; - type: string; - viewer_id: ViewerId; + boundaries: GeodeId[]; + geode_id: GeodeId; + internals: GeodeId[]; + is_active: boolean; + name: string; + type: string; + viewer_id: ViewerId; } export interface CollectionComponent { diff --git a/src/opengeodeweb_back/schema_types.json b/src/opengeodeweb_back/schema_types.json index da1ba0e0..a9c7bc50 100644 --- a/src/opengeodeweb_back/schema_types.json +++ b/src/opengeodeweb_back/schema_types.json @@ -109,9 +109,6 @@ }, "is_active": { "type": "boolean" - }, - "binary_light_viewable": { - "type": "string" } }, "required": [ diff --git a/src/opengeodeweb_back/schema_types.py b/src/opengeodeweb_back/schema_types.py index c5a269ff..8a4cce59 100644 --- a/src/opengeodeweb_back/schema_types.py +++ b/src/opengeodeweb_back/schema_types.py @@ -3,7 +3,6 @@ # ruff: noqa: TC002 from dataclasses import dataclass -from typing import Optional from dataclasses_json import DataClassJsonMixin from opengeodeweb_microservice.schema_types import GeodeId @@ -57,7 +56,6 @@ def __post_init__(self) -> None: name: str type: str viewer_id: ViewerId - binary_light_viewable: Optional[str] = None @dataclass diff --git a/src/opengeodeweb_back/test_utils.py b/src/opengeodeweb_back/test_utils.py index 3142b4de..92d5150a 100644 --- a/src/opengeodeweb_back/test_utils.py +++ b/src/opengeodeweb_back/test_utils.py @@ -118,13 +118,6 @@ def get_full_data() -> JsonData: "viewer_object_type is not image, mesh or model", ) _check(type(item["binary_light_viewable"]) is str, "binary_light_viewable is not a string") - for component in item.get("mesh_components", []): - if component["type"] == "Block": - continue - _check( - type(component.get("binary_light_viewable")) is str, - f"Mesh component {component['geode_id']} has no light viewable", - ) # Test all params test_route_wrong_params(client, route, get_full_data) diff --git a/src/opengeodeweb_back/utils_functions.py b/src/opengeodeweb_back/utils_functions.py index c1a8a720..1c5d3b4a 100644 --- a/src/opengeodeweb_back/utils_functions.py +++ b/src/opengeodeweb_back/utils_functions.py @@ -40,6 +40,8 @@ # Native files are saved in background: the viewer only needs the viewables native_saves = BackgroundSaves("native") +# Simplifying is slow: the light viewable is saved in background, a bounding box answers first +light_saves = BackgroundSaves("light viewable") if TYPE_CHECKING: from collections.abc import Callable, Sequence @@ -269,11 +271,7 @@ def _uuid_to_light_viewable(data_id: str, light_viewable_file: str | None) -> di return uuid_to_light_viewable -def _mesh_components( - model: GeodeModel, - uuid_to_flat_index: dict[str, int], - uuid_to_light_viewable: dict[str, str], -) -> list[dict[str, Any]]: +def _mesh_components(model: GeodeModel, uuid_to_flat_index: dict[str, int]) -> list[dict[str, Any]]: model_mesh_components = model.mesh_components() mesh_components = [] for mesh_component, ids in model_mesh_components.items(): @@ -298,8 +296,6 @@ def _mesh_components( "internals": internals_uuid, "is_active": component.is_active(), } - if geode_id in uuid_to_light_viewable: - mesh_component_object["binary_light_viewable"] = uuid_to_light_viewable[geode_id] mesh_components.append(mesh_component_object) return mesh_components @@ -328,16 +324,10 @@ def _collection_components(model: GeodeModel) -> list[dict[str, Any]]: return collection_components -def model_components( - data_id: str, - model: GeodeModel, - viewable_file: str | None, - light_viewable_file: str | None, -) -> dict[str, Any]: +def model_components(data_id: str, model: GeodeModel, viewable_file: str | None) -> dict[str, Any]: uuid_to_flat_index = _uuid_to_flat_index(data_id, viewable_file) - uuid_to_light_viewable = _uuid_to_light_viewable(data_id, light_viewable_file) return { - "mesh_components": _mesh_components(model, uuid_to_flat_index, uuid_to_light_viewable), + "mesh_components": _mesh_components(model, uuid_to_flat_index), "collection_components": _collection_components(model), } @@ -351,11 +341,30 @@ def discard_native_save(data_id: str) -> None: native_saves.discard(data_id) +def light_viewable_filename(geode_object: GeodeObject) -> str: + """The light viewable of a model is an index of its mesh components files.""" + extension = "vtm" if isinstance(geode_object, GeodeModel) else "vtp" + return f"light_viewable.{extension}" + + +def _save_light_viewable_in_background( + geode_object: GeodeObject, data_id: str, data_path: str +) -> None: + light_path = str(Path(data_path) / "light_viewable") + light_saves.submit(data_id, lambda: geode_object.save_light_viewable(light_path)) + + +def wait_light_viewable_saved(data_id: str) -> None: + """Wait for the background light viewable save of data_id, if any, retrying a failure once.""" + light_saves.wait(data_id) + + def remove_data_folder( data_id: str, folder: str | Path | None = None, *, ignore_errors: bool = False ) -> None: - """Remove the folder of data_id once its native save is done (by default its data folder).""" + """Remove the folder of data_id once its background saves are done (default: data folder).""" discard_native_save(data_id) + light_saves.discard(data_id) if folder is None: folder = geode_functions.data_file_path(data_id) shutil.rmtree(folder, ignore_errors=ignore_errors) @@ -376,6 +385,7 @@ def save_all_viewables_and_return_info( data: Data, data_path: str, ) -> dict[str, Any]: + # The bounding box answers at once, the simplified light viewable follows in background with ThreadPoolExecutor() as executor: tasks: list[tuple[Callable[[str], Any], str]] = [] if geode_object.is_viewable(): @@ -383,8 +393,8 @@ def save_all_viewables_and_return_info( [ (geode_object.save_viewable, str(Path(data_path) / "viewable")), ( - geode_object.save_light_viewable, - str(Path(data_path) / "light_viewable"), + geode_object.save_bounding_box_viewable, + str(Path(data_path) / "bounding_box_viewable"), ), ] ) @@ -392,11 +402,10 @@ def save_all_viewables_and_return_info( results = list(executor.map(lambda args: args[0](args[1]), tasks)) if geode_object.is_viewable(): viewable_path = results[0] - light_path = results[1] - binary_light_viewable = Path(light_path).read_bytes() - binary_light_viewable_str = base64.b64encode(binary_light_viewable).decode("ascii") + bounding_box = Path(results[1]).read_bytes() + binary_light_viewable_str = base64.b64encode(bounding_box).decode("ascii") data.viewable_file = Path(viewable_path).name - data.light_viewable_file = Path(light_path).name + data.light_viewable_file = light_viewable_filename(geode_object) else: binary_light_viewable_str = None data.viewable_file = None @@ -423,13 +432,13 @@ def save_all_viewables_and_return_info( if isinstance(geode_object, GeodeVertexSet): response["nb_vertices"] = geode_object.vertex_set.nb_vertices() if isinstance(geode_object, GeodeModel): - response |= model_components( - data.id, geode_object, data.viewable_file, data.light_viewable_file - ) + response |= model_components(data.id, geode_object, data.viewable_file) crs = active_crs(geode_object) if crs is not None: response["crs"] = crs _save_native_in_background(geode_object, data.id, str(Path(data_path) / data.native_file)) + if geode_object.is_viewable(): + _save_light_viewable_in_background(geode_object, data.id, data_path) return response diff --git a/tests/test_crs_routes.py b/tests/test_crs_routes.py index 0c9fdc33..6f55b42d 100644 --- a/tests/test_crs_routes.py +++ b/tests/test_crs_routes.py @@ -1,6 +1,7 @@ from __future__ import annotations # Standard library imports +import base64 import os import shutil from pathlib import Path @@ -664,22 +665,16 @@ def test_assign_only_plausible(client: FlaskClient) -> None: assert _active_crs(client, plausible_id) == LAMBERT -def test_convert_geographic_model_returns_component_light_viewables(client: FlaskClient) -> None: +def test_convert_geographic_model_returns_bounding_box(client: FlaskClient) -> None: assign_route = "/opengeodeweb_back/crs/assign_geographic" route = "/opengeodeweb_back/crs/convert_geographic" [brep] = test_utils.check_save_viewable_file(client, "BRep", "cube.og_brep") - [linked_brep] = test_utils.check_save_viewable_file(client, "BRep", "cube.og_brep") - client.post(assign_route, json={"id": brep["id"], "linked_ids": [linked_brep["id"]], **LAMBERT}) - response = client.post(route, json={"id": brep["id"], "linked_ids": [linked_brep["id"]], **UTM}) + client.post(assign_route, json={"id": brep["id"], **LAMBERT}) + response = client.post(route, json={"id": brep["id"], **UTM}) assert response.status_code == 200 - [linked] = response.get_json()["linked"] - # The front rebuilds each component actor from its moved light viewable - for converted in (response.get_json(), linked): - for component in converted["mesh_components"]: - if component["type"] == "Block": - assert "binary_light_viewable" not in component - else: - assert type(component["binary_light_viewable"]) is str + assert "mesh_components" not in response.get_json() + bounding_box = base64.b64decode(response.get_json()["binary_light_viewable"], validate=True) + assert b'type="PolyData"' in bounding_box def test_assign_geographic_model_without_block_meshes(client: FlaskClient) -> None: diff --git a/tests/test_utils_functions.py b/tests/test_utils_functions.py index bdddb340..f2fcd3c2 100644 --- a/tests/test_utils_functions.py +++ b/tests/test_utils_functions.py @@ -196,28 +196,43 @@ def test_save_all_viewables_and_return_info(client: FlaskClient) -> None: assert expected_data_path.exists() -def test_save_all_viewables_returns_component_light_viewables(client: FlaskClient) -> None: - with client.application.app_context(): +def test_save_all_viewables_returns_bounding_box(client: FlaskClient) -> None: + app = client.application + with app.app_context(): geode_object = GeodeBRep.load_one(str(data_dir / "cube.og_brep")) geode_object.builder().set_name("cube") result = utils_functions.generate_files_from_object(geode_object) - light_vtm = base64.b64decode(result["binary_light_viewable"], validate=True) - assert b'type="vtkMultiBlockDataSet"' in light_vtm + bounding_box = base64.b64decode(result["binary_light_viewable"], validate=True) + assert b'type="PolyData"' in bounding_box for component in result["mesh_components"]: - if component["type"] == "Block": - assert "binary_light_viewable" not in component - else: - light_vtp = base64.b64decode(component["binary_light_viewable"], validate=True) - assert b'type="PolyData"' in light_vtp - light_components = [ - component - for component in result["mesh_components"] - if "binary_light_viewable" in component - ] - # 8 corners, 12 lines and 6 surfaces - assert len(light_components) == 26 + assert "binary_light_viewable" not in component + utils_functions.wait_light_viewable_saved(result["id"]) + data_path = Path(app.config["DATA_FOLDER_PATH"]) / result["id"] + assert (data_path / "light_viewable.vtm").is_file() + assert (data_path / "light_viewable").is_dir() + data = Data.get(result["id"]) + assert data is not None + assert data.light_viewable_file == "light_viewable.vtm" + + +def test_save_all_viewables_saves_mesh_light_viewable(client: FlaskClient) -> None: + app = client.application + with app.app_context(): + geode_object = GeodePolygonalSurface3D.load_one(str(data_dir / "test.og_psf3d")) + geode_object.builder().set_name("surface") + + result = utils_functions.generate_files_from_object(geode_object) + + bounding_box = base64.b64decode(result["binary_light_viewable"], validate=True) + assert b'type="PolyData"' in bounding_box + utils_functions.wait_light_viewable_saved(result["id"]) + data_path = Path(app.config["DATA_FOLDER_PATH"]) / result["id"] + assert (data_path / "light_viewable.vtp").is_file() + data = Data.get(result["id"]) + assert data is not None + assert data.light_viewable_file == "light_viewable.vtp" def test_save_all_viewables_commits_to_db(client: FlaskClient) -> None: @@ -262,7 +277,7 @@ def test_generate_files_from_object( assert isinstance(result["binary_light_viewable"], str) light_viewable_bytes = base64.b64decode(result["binary_light_viewable"], validate=True) assert light_viewable_bytes.startswith(b'') - assert b'type="vtkMultiBlockDataSet"' in light_viewable_bytes + assert b'type="PolyData"' in light_viewable_bytes data = Data.get(result["id"]) assert data is not None @@ -274,8 +289,8 @@ def test_generate_files_from_object( utils_functions.wait_native_saved(result["id"]) assert (data_path / result["native_file"]).exists() assert (data_path / result["viewable_file"]).exists() + utils_functions.wait_light_viewable_saved(result["id"]) assert (data_path / data.light_viewable_file).exists() - assert (data_path / data.light_viewable_file).read_bytes() == light_viewable_bytes def test_generate_files_from_file( From 6aedb1e666313a481d6ea5ee6a382119c8c31830 Mon Sep 17 00:00:00 2001 From: JulienChampagnol Date: Wed, 2 Dec 2026 11:45:47 +0100 Subject: [PATCH 09/11] feat(light_viewable): light_viewable route Co-Authored-By: Claude Opus 5.5 --- opengeodeweb_back_schemas.json | 53 +++++++++++++++++++ opengeodeweb_back_typed_schemas.d.ts | 12 ++++- .../routes/blueprint_routes.py | 6 +++ .../routes/schemas/__init__.py | 1 + .../routes/schemas/light_viewable.json | 32 +++++++++++ .../routes/schemas/light_viewable.py | 34 ++++++++++++ src/opengeodeweb_back/schema_definitions.json | 19 +++++++ src/opengeodeweb_back/schema_types.d.ts | 5 ++ src/opengeodeweb_back/schema_types.json | 16 ++++++ src/opengeodeweb_back/schema_types.py | 10 ++++ src/opengeodeweb_back/utils_functions.py | 27 ++++++++++ tests/test_routes.py | 48 ++++++++++++++++- 12 files changed, 261 insertions(+), 2 deletions(-) create mode 100644 src/opengeodeweb_back/routes/schemas/light_viewable.json create mode 100644 src/opengeodeweb_back/routes/schemas/light_viewable.py diff --git a/opengeodeweb_back_schemas.json b/opengeodeweb_back_schemas.json index 89fad98e..f6ed8dc1 100644 --- a/opengeodeweb_back_schemas.json +++ b/opengeodeweb_back_schemas.json @@ -3384,6 +3384,59 @@ "additionalProperties": false } }, + "light_viewable": { + "$id": "opengeodeweb_back/light_viewable", + "route": "/light_viewable", + "methods": [ + "POST" + ], + "type": "object", + "properties": { + "id": { + "title": "DataId", + "type": "string", + "minLength": 32, + "maxLength": 32 + } + }, + "required": [ + "id" + ], + "additionalProperties": false, + "response": { + "type": "object", + "properties": { + "binary_light_viewable": { + "type": "string" + }, + "mesh_components": { + "type": "array", + "items": { + "title": "ComponentLightViewable", + "type": "object", + "properties": { + "geode_id": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "binary_light_viewable": { + "type": "string" + } + }, + "required": [ + "geode_id", + "binary_light_viewable" + ], + "additionalProperties": false + } + } + }, + "required": [], + "additionalProperties": false + } + }, "kill": { "$id": "opengeodeweb_back/kill", "route": "/kill", diff --git a/opengeodeweb_back_typed_schemas.d.ts b/opengeodeweb_back_typed_schemas.d.ts index 8dcc3f2b..949d2919 100644 --- a/opengeodeweb_back_typed_schemas.d.ts +++ b/opengeodeweb_back_typed_schemas.d.ts @@ -2,7 +2,7 @@ import type json from "./opengeodeweb_back_schemas.json"; import type { DataId, GeodeId } from "@geode/opengeodeweb-microservice/schema_types"; -import type { AttributeInfo, AttributeName, CRS, CollectionComponent, Filename, MeshComponent, Point3D, ViewerId } from "@geode/opengeodeweb-back/schema_types"; +import type { AttributeInfo, AttributeName, CRS, CollectionComponent, ComponentLightViewable, Filename, MeshComponent, Point3D, ViewerId } from "@geode/opengeodeweb-back/schema_types"; import type { GeodeObjectType, ViewerObjectType } from "@geode/opengeodeweb-microservice/data_types"; export interface BasemapDeleteParams { @@ -488,6 +488,15 @@ export interface ModelComponentEdgeAttributeNamesResponse { attributes: AttributeInfo[]; } +export interface LightViewableParams { + id: DataId; +} + +export interface LightViewableResponse { + binary_light_viewable?: string; + mesh_components?: ComponentLightViewable[]; +} + export interface KillParams { } @@ -678,6 +687,7 @@ export interface Schemas { readonly model_component_polygon_attribute_names: (typeof json)["opengeodeweb_back"]["model_component_polygon_attribute_names"] & TypedSchema; readonly model_component_edge_attribute_range: (typeof json)["opengeodeweb_back"]["model_component_edge_attribute_range"] & TypedSchema; readonly model_component_edge_attribute_names: (typeof json)["opengeodeweb_back"]["model_component_edge_attribute_names"] & TypedSchema; + readonly light_viewable: (typeof json)["opengeodeweb_back"]["light_viewable"] & TypedSchema; readonly kill: (typeof json)["opengeodeweb_back"]["kill"] & TypedSchema; readonly import_project: (typeof json)["opengeodeweb_back"]["import_project"] & TypedSchema; readonly horizon_stack_info: (typeof json)["opengeodeweb_back"]["horizon_stack_info"] & TypedSchema; diff --git a/src/opengeodeweb_back/routes/blueprint_routes.py b/src/opengeodeweb_back/routes/blueprint_routes.py index 2d8e55b1..4b3bb37a 100644 --- a/src/opengeodeweb_back/routes/blueprint_routes.py +++ b/src/opengeodeweb_back/routes/blueprint_routes.py @@ -274,6 +274,12 @@ def geode_objects_and_output_extensions( ) +@typed_route(routes, schemas.light_viewable_route) +def light_viewable(params: schemas.LightViewable) -> schemas.LightViewableResponse: + data = geode_functions.get_data_info(params.id) + return schemas.LightViewableResponse.from_dict(utils_functions.light_viewable_response(data)) + + @typed_route(routes, schemas.save_viewable_file_route) def save_viewable_file( params: schemas.SaveViewableFile, diff --git a/src/opengeodeweb_back/routes/schemas/__init__.py b/src/opengeodeweb_back/routes/schemas/__init__.py index c84576fa..1568b6f6 100644 --- a/src/opengeodeweb_back/routes/schemas/__init__.py +++ b/src/opengeodeweb_back/routes/schemas/__init__.py @@ -20,6 +20,7 @@ from .model_component_polygon_attribute_names import * from .model_component_edge_attribute_range import * from .model_component_edge_attribute_names import * +from .light_viewable import * from .kill import * from .import_project import * from .horizon_stack_info import * diff --git a/src/opengeodeweb_back/routes/schemas/light_viewable.json b/src/opengeodeweb_back/routes/schemas/light_viewable.json new file mode 100644 index 00000000..5624f9c6 --- /dev/null +++ b/src/opengeodeweb_back/routes/schemas/light_viewable.json @@ -0,0 +1,32 @@ +{ + "route": "/light_viewable", + "methods": [ + "POST" + ], + "type": "object", + "properties": { + "id": { + "title": "DataId" + } + }, + "required": [ + "id" + ], + "additionalProperties": false, + "response": { + "type": "object", + "properties": { + "binary_light_viewable": { + "type": "string" + }, + "mesh_components": { + "type": "array", + "items": { + "title": "ComponentLightViewable" + } + } + }, + "required": [], + "additionalProperties": false + } +} diff --git a/src/opengeodeweb_back/routes/schemas/light_viewable.py b/src/opengeodeweb_back/routes/schemas/light_viewable.py new file mode 100644 index 00000000..41d6d5e7 --- /dev/null +++ b/src/opengeodeweb_back/routes/schemas/light_viewable.py @@ -0,0 +1,34 @@ +from opengeodeweb_microservice.schema_types import DataId, GeodeId +from opengeodeweb_back.schema_types import ComponentLightViewable +from pathlib import Path +from opengeodeweb_microservice.schemas import Route, load_schema +from typing import Optional, List +from dataclasses_json import DataClassJsonMixin +from opengeodeweb_microservice.schemas import print_dataclass +from dataclasses import dataclass + + +@dataclass +class LightViewable(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + id: DataId + + +@dataclass +class LightViewableResponse(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + binary_light_viewable: Optional[str] = None + mesh_components: Optional[List[ComponentLightViewable]] = None + + +light_viewable_route = Route( + schema=load_schema(Path(__file__)), + params=LightViewable, + response=LightViewableResponse, +) + +__all__ = ["LightViewable", "LightViewableResponse", "light_viewable_route"] diff --git a/src/opengeodeweb_back/schema_definitions.json b/src/opengeodeweb_back/schema_definitions.json index 0a04f5b7..b0d2eae7 100644 --- a/src/opengeodeweb_back/schema_definitions.json +++ b/src/opengeodeweb_back/schema_definitions.json @@ -92,6 +92,25 @@ ], "additionalProperties": false }, + "ComponentLightViewable": { + "type": "object", + "properties": { + "geode_id": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "binary_light_viewable": { + "type": "string" + } + }, + "required": [ + "geode_id", + "binary_light_viewable" + ], + "additionalProperties": false + }, "DataId": { "type": "string", "minLength": 32, diff --git a/src/opengeodeweb_back/schema_types.d.ts b/src/opengeodeweb_back/schema_types.d.ts index 7cc8de14..a2fb2498 100644 --- a/src/opengeodeweb_back/schema_types.d.ts +++ b/src/opengeodeweb_back/schema_types.d.ts @@ -42,3 +42,8 @@ export interface CollectionComponent { name: string; type: string; } + +export interface ComponentLightViewable { + binary_light_viewable: string; + geode_id: GeodeId; +} diff --git a/src/opengeodeweb_back/schema_types.json b/src/opengeodeweb_back/schema_types.json index a9c7bc50..f20e051f 100644 --- a/src/opengeodeweb_back/schema_types.json +++ b/src/opengeodeweb_back/schema_types.json @@ -152,5 +152,21 @@ "is_active" ], "additionalProperties": false + }, + "ComponentLightViewable": { + "type": "object", + "properties": { + "geode_id": { + "title": "GeodeId" + }, + "binary_light_viewable": { + "type": "string" + } + }, + "required": [ + "geode_id", + "binary_light_viewable" + ], + "additionalProperties": false } } diff --git a/src/opengeodeweb_back/schema_types.py b/src/opengeodeweb_back/schema_types.py index 8a4cce59..c631bcad 100644 --- a/src/opengeodeweb_back/schema_types.py +++ b/src/opengeodeweb_back/schema_types.py @@ -70,11 +70,21 @@ def __post_init__(self) -> None: type: str +@dataclass +class ComponentLightViewable(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + binary_light_viewable: str + geode_id: GeodeId + + __all__ = [ "CRS", "AttributeInfo", "AttributeName", "CollectionComponent", + "ComponentLightViewable", "Filename", "MeshComponent", "Point3D", diff --git a/src/opengeodeweb_back/utils_functions.py b/src/opengeodeweb_back/utils_functions.py index 1c5d3b4a..2ae1d84e 100644 --- a/src/opengeodeweb_back/utils_functions.py +++ b/src/opengeodeweb_back/utils_functions.py @@ -359,6 +359,33 @@ def wait_light_viewable_saved(data_id: str) -> None: light_saves.wait(data_id) +def light_viewable_response(data: Data) -> dict[str, Any]: + """Simplified light viewable of data: one file for a mesh, one per mesh component for a model. + + Waits for its background save; a missing file (e.g. a project saved before) is saved now. + """ + wait_light_viewable_saved(data.id) + is_model = data.viewer_object_type == "model" + # Named from the data kind, not the stored name: older projects stored a .vtp for models + light_viewable_file = f"light_viewable.{'vtm' if is_model else 'vtp'}" + light_path = Path(geode_functions.data_file_path(data.id, light_viewable_file)) + if not light_path.is_file(): + geode_object = geode_functions.load_geode_object(data.id) + if not geode_object.is_viewable(): + flask.abort(400, f"Data {data.id} has no light viewable") + geode_object.save_light_viewable(str(light_path.with_suffix(""))) + if is_model: + return { + "mesh_components": [ + {"geode_id": geode_id, "binary_light_viewable": light_viewable} + for geode_id, light_viewable in _uuid_to_light_viewable( + data.id, light_viewable_file + ).items() + ] + } + return {"binary_light_viewable": base64.b64encode(light_path.read_bytes()).decode("ascii")} + + def remove_data_folder( data_id: str, folder: str | Path | None = None, *, ignore_errors: bool = False ) -> None: diff --git a/tests/test_routes.py b/tests/test_routes.py index 056452e3..36310276 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,6 +1,7 @@ from __future__ import annotations # Standard library imports +import base64 import contextlib import json import math @@ -20,7 +21,7 @@ # Local application imports from opengeodeweb_microservice.database.data import Data -from opengeodeweb_back import geode_functions, test_utils +from opengeodeweb_back import geode_functions, test_utils, utils_functions from opengeodeweb_back.geode_objects.geode_edged_curve3d import ( GeodeEdgedCurve3D, ) @@ -258,6 +259,51 @@ def get_full_data() -> test_utils.JsonData: test_utils.test_route_wrong_params(client, route, get_full_data) +def test_light_viewable_mesh(client: FlaskClient) -> None: + route = "/opengeodeweb_back/light_viewable" + [item] = test_utils.check_save_viewable_file(client, "PolygonalSurface3D", "test.og_psf3d") + + def get_full_data() -> test_utils.JsonData: + return {"id": item["id"]} + + response = client.post(route, json=get_full_data()) + assert response.status_code == 200 + light_viewable = base64.b64decode(response.get_json()["binary_light_viewable"], validate=True) + assert b'type="PolyData"' in light_viewable + assert "mesh_components" not in response.get_json() + test_utils.test_route_wrong_params(client, route, get_full_data) + + +def test_light_viewable_model(client: FlaskClient) -> None: + [item] = test_utils.check_save_viewable_file(client, "BRep", "cube.og_brep") + response = client.post("/opengeodeweb_back/light_viewable", json={"id": item["id"]}) + assert response.status_code == 200 + components = response.get_json()["mesh_components"] + # 8 corners, 12 lines and 6 surfaces + assert len(components) == 26 + for component in components: + light_viewable = base64.b64decode(component["binary_light_viewable"], validate=True) + assert b'type="PolyData"' in light_viewable + block_ids = { + component["geode_id"] + for component in item["mesh_components"] + if component["type"] == "Block" + } + assert block_ids.isdisjoint(component["geode_id"] for component in components) + + +def test_light_viewable_missing_file(client: FlaskClient) -> None: + [item] = test_utils.check_save_viewable_file(client, "BRep", "cube.og_brep") + with client.application.app_context(): + utils_functions.wait_light_viewable_saved(item["id"]) + data_path = Path(geode_functions.data_file_path(item["id"])) + (data_path / "light_viewable.vtm").unlink() + shutil.rmtree(data_path / "light_viewable") + response = client.post("/opengeodeweb_back/light_viewable", json={"id": item["id"]}) + assert response.status_code == 200 + assert len(response.get_json()["mesh_components"]) == 26 + + def test_save_viewable_file(client: FlaskClient) -> None: [item] = test_utils.check_save_viewable_file(client, "BRep", "corbi.og_brep") assert "crs" not in item From 44f211f667510be49f6e6f2fc3bc19b7fa826461 Mon Sep 17 00:00:00 2001 From: JulienChampagnol Date: Wed, 2 Dec 2026 11:57:03 +0100 Subject: [PATCH 10/11] fix(light_viewable): export waits for light saves, older projects recompute Co-Authored-By: Claude Opus 5.5 --- src/opengeodeweb_back/background_saves.py | 2 + .../routes/blueprint_routes.py | 1 + src/opengeodeweb_back/utils_functions.py | 16 ++-- tests/conftest.py | 19 ++++ tests/helpers/__init__.py | 0 tests/helpers/light_save.py | 47 ++++++++++ tests/test_background_light_viewable.py | 87 +++++++++++++++++++ tests/test_routes.py | 21 ++++- tests/test_utils_functions.py | 10 +-- 9 files changed, 191 insertions(+), 12 deletions(-) create mode 100644 tests/helpers/__init__.py create mode 100644 tests/helpers/light_save.py create mode 100644 tests/test_background_light_viewable.py diff --git a/src/opengeodeweb_back/background_saves.py b/src/opengeodeweb_back/background_saves.py index 59cf2a2b..3163987a 100644 --- a/src/opengeodeweb_back/background_saves.py +++ b/src/opengeodeweb_back/background_saves.py @@ -82,6 +82,8 @@ def discard(self, data_id: str) -> None: entry = self._saves.get(data_id) if entry is None: return + # A save still queued is dropped without waiting for it + entry.future.cancel() try: entry.future.result() except Exception: diff --git a/src/opengeodeweb_back/routes/blueprint_routes.py b/src/opengeodeweb_back/routes/blueprint_routes.py index 4b3bb37a..d2ceb6df 100644 --- a/src/opengeodeweb_back/routes/blueprint_routes.py +++ b/src/opengeodeweb_back/routes/blueprint_routes.py @@ -957,6 +957,7 @@ def export_project() -> flask.Response: export_vease_path = Path(project_folder) / filename utils_functions.wait_all_native_saved() + utils_functions.light_saves.wait_all() with get_session() as session: rows = session.query(Data.id, Data.native_file).all() # Basemaps are rebuilt from the project style: neither their rows nor their tiles are exported diff --git a/src/opengeodeweb_back/utils_functions.py b/src/opengeodeweb_back/utils_functions.py index 2ae1d84e..8a85f5e5 100644 --- a/src/opengeodeweb_back/utils_functions.py +++ b/src/opengeodeweb_back/utils_functions.py @@ -341,16 +341,20 @@ def discard_native_save(data_id: str) -> None: native_saves.discard(data_id) +# Not "light_viewable": older projects stored a bounding box under that name +LIGHT_VIEWABLE_STEM = "simplified_viewable" + + def light_viewable_filename(geode_object: GeodeObject) -> str: """The light viewable of a model is an index of its mesh components files.""" extension = "vtm" if isinstance(geode_object, GeodeModel) else "vtp" - return f"light_viewable.{extension}" + return f"{LIGHT_VIEWABLE_STEM}.{extension}" def _save_light_viewable_in_background( geode_object: GeodeObject, data_id: str, data_path: str ) -> None: - light_path = str(Path(data_path) / "light_viewable") + light_path = str(Path(data_path) / LIGHT_VIEWABLE_STEM) light_saves.submit(data_id, lambda: geode_object.save_light_viewable(light_path)) @@ -366,14 +370,16 @@ def light_viewable_response(data: Data) -> dict[str, Any]: """ wait_light_viewable_saved(data.id) is_model = data.viewer_object_type == "model" - # Named from the data kind, not the stored name: older projects stored a .vtp for models - light_viewable_file = f"light_viewable.{'vtm' if is_model else 'vtp'}" + light_viewable_file = f"{LIGHT_VIEWABLE_STEM}.{'vtm' if is_model else 'vtp'}" light_path = Path(geode_functions.data_file_path(data.id, light_viewable_file)) if not light_path.is_file(): geode_object = geode_functions.load_geode_object(data.id) if not geode_object.is_viewable(): flask.abort(400, f"Data {data.id} has no light viewable") - geode_object.save_light_viewable(str(light_path.with_suffix(""))) + # Registered like a background save: never written twice at once + light_stem = str(light_path.with_suffix("")) + light_saves.submit(data.id, lambda: geode_object.save_light_viewable(light_stem)) + wait_light_viewable_saved(data.id) if is_model: return { "mesh_components": [ diff --git a/tests/conftest.py b/tests/conftest.py index e2a0e6ec..4d010e96 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,7 @@ from __future__ import annotations # Standard library imports +import contextlib import os import shutil import time @@ -12,10 +13,14 @@ # Third party imports from opengeodeweb_microservice.database import connection from opengeodeweb_microservice.database.connection import init_database +from werkzeug.exceptions import HTTPException + +from opengeodeweb_back import utils_functions # Local application imports from opengeodeweb_back.app import create_app, register_ogw_back_blueprints from opengeodeweb_back.basemap import basemap_tiles +from tests.helpers.light_save import LightSave, block_light_saves if TYPE_CHECKING: from collections.abc import Callable, Generator @@ -90,3 +95,17 @@ def test_id() -> str: def fresh_circuit_breaker(monkeypatch: pytest.MonkeyPatch) -> None: # A source paused by one test must not leave the next one without tiles monkeypatch.setattr(basemap_tiles, "BREAKER", basemap_tiles.CircuitBreaker()) + + +@pytest.fixture +def light_save(client: FlaskClient, monkeypatch: pytest.MonkeyPatch) -> Generator[LightSave]: + state = LightSave() + block_light_saves(monkeypatch, state) + try: + yield state + finally: + state.release.set() + # No pending nor failed light viewable save may leak into the next test + with client.application.app_context(), contextlib.suppress(HTTPException): + utils_functions.light_saves.wait_all() + utils_functions.light_saves._saves.clear() # noqa: SLF001 diff --git a/tests/helpers/__init__.py b/tests/helpers/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/helpers/light_save.py b/tests/helpers/light_save.py new file mode 100644 index 00000000..ee150059 --- /dev/null +++ b/tests/helpers/light_save.py @@ -0,0 +1,47 @@ +"""Blocks the background light viewable saves of a TriangulatedSurface3D until released.""" + +from __future__ import annotations + +# Standard library imports +import threading +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +# Local application imports +from opengeodeweb_back.geode_objects.geode_triangulated_surface3d import ( + GeodeTriangulatedSurface3D, +) + +if TYPE_CHECKING: + import pytest + +TIMEOUT = 25.0 + + +@dataclass +class LightSave: + release: threading.Event = field(default_factory=threading.Event) + lock: threading.Lock = field(default_factory=threading.Lock) + entered: int = 0 + # How many saves fail before one succeeds + failures: int = 0 + + +def block_light_saves(monkeypatch: pytest.MonkeyPatch, state: LightSave) -> None: + original_save = GeodeTriangulatedSurface3D.save_light_viewable + + def blocked_save(self: GeodeTriangulatedSurface3D, filename_without_extension: str) -> str: + with state.lock: + state.entered += 1 + if not state.release.wait(TIMEOUT): + msg = "light viewable save never released" + raise TimeoutError(msg) + with state.lock: + failing = state.failures > 0 + state.failures -= int(failing) + if failing: + msg = "simplification exploded" + raise RuntimeError(msg) + return original_save(self, filename_without_extension) + + monkeypatch.setattr(GeodeTriangulatedSurface3D, "save_light_viewable", blocked_save) diff --git a/tests/test_background_light_viewable.py b/tests/test_background_light_viewable.py new file mode 100644 index 00000000..4fdb78aa --- /dev/null +++ b/tests/test_background_light_viewable.py @@ -0,0 +1,87 @@ +"""The light viewable of an import is saved in background, after the route answered.""" + +from __future__ import annotations + +# Standard library imports +import base64 +import threading +import time +import zipfile +from pathlib import Path +from typing import TYPE_CHECKING + +# Local application imports +from opengeodeweb_back import geode_functions, test_utils, utils_functions + +if TYPE_CHECKING: + from flask.testing import FlaskClient + + from tests.helpers.light_save import LightSave + +LIGHT_ROUTE = "/opengeodeweb_back/light_viewable" +EXPORT_ROUTE = "/opengeodeweb_back/export_project" +RELEASE_DELAY = 0.3 + + +def test_light_route_waits_for_the_pending_save(client: FlaskClient, light_save: LightSave) -> None: + [item] = test_utils.check_save_viewable_file(client, "TriangulatedSurface3D", "test.og_tsf3d") + threading.Timer(RELEASE_DELAY, light_save.release.set).start() + response = client.post(LIGHT_ROUTE, json={"id": item["id"]}) + assert response.status_code == 200 + light_viewable = base64.b64decode(response.get_json()["binary_light_viewable"], validate=True) + assert b'type="PolyData"' in light_viewable + # Waited for the background save, not computed a second time + assert light_save.entered == 1 + + +def test_light_route_retries_a_failed_save(client: FlaskClient, light_save: LightSave) -> None: + light_save.failures = 1 + [item] = test_utils.check_save_viewable_file(client, "TriangulatedSurface3D", "test.og_tsf3d") + light_save.release.set() + response = client.post(LIGHT_ROUTE, json={"id": item["id"]}) + assert response.status_code == 200 + assert light_save.entered == 2 + + +def test_light_route_names_a_save_failing_twice(client: FlaskClient, light_save: LightSave) -> None: + light_save.failures = 2 + [item] = test_utils.check_save_viewable_file(client, "TriangulatedSurface3D", "test.og_tsf3d") + light_save.release.set() + response = client.post(LIGHT_ROUTE, json={"id": item["id"]}) + assert response.status_code == 500 + assert item["id"] in response.get_json()["description"] + + +def test_removing_a_data_discards_its_pending_light_save( + client: FlaskClient, light_save: LightSave +) -> None: + [item] = test_utils.check_save_viewable_file(client, "TriangulatedSurface3D", "test.og_tsf3d") + threading.Timer(RELEASE_DELAY, light_save.release.set).start() + with client.application.app_context(): + folder = Path(geode_functions.data_file_path(item["id"])) + utils_functions.remove_data_folder(item["id"]) + assert not folder.exists() + with utils_functions.light_saves._lock: # noqa: SLF001 + assert item["id"] not in utils_functions.light_saves._saves # noqa: SLF001 + + +def test_export_waits_for_pending_light_saves( + client: FlaskClient, light_save: LightSave, tmp_path: Path +) -> None: + [item] = test_utils.check_save_viewable_file(client, "TriangulatedSurface3D", "test.og_tsf3d") + threading.Timer(RELEASE_DELAY, light_save.release.set).start() + started = time.monotonic() + filename = "light_save.vease" + response = client.post(EXPORT_ROUTE, json={"snapshot": {}, "filename": filename}) + assert response.status_code == 200 + assert time.monotonic() - started >= RELEASE_DELAY + response.direct_passthrough = False + vease = tmp_path / filename + vease.write_bytes(response.get_data()) + response.close() + (Path(client.application.config["DATA_FOLDER_PATH"]) / filename).unlink(missing_ok=True) + with zipfile.ZipFile(vease) as zip_file: + names = zip_file.namelist() + assert any( + name.startswith(f"{item['id']}/") and "simplified_viewable" in name for name in names + ) diff --git a/tests/test_routes.py b/tests/test_routes.py index 36310276..9ca3368e 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -297,13 +297,30 @@ def test_light_viewable_missing_file(client: FlaskClient) -> None: with client.application.app_context(): utils_functions.wait_light_viewable_saved(item["id"]) data_path = Path(geode_functions.data_file_path(item["id"])) - (data_path / "light_viewable.vtm").unlink() - shutil.rmtree(data_path / "light_viewable") + (data_path / "simplified_viewable.vtm").unlink() + shutil.rmtree(data_path / "simplified_viewable") response = client.post("/opengeodeweb_back/light_viewable", json={"id": item["id"]}) assert response.status_code == 200 assert len(response.get_json()["mesh_components"]) == 26 +def test_light_viewable_ignores_older_bounding_box(client: FlaskClient) -> None: + [item] = test_utils.check_save_viewable_file(client, "PolygonalSurface3D", "test.og_psf3d") + with client.application.app_context(): + utils_functions.wait_light_viewable_saved(item["id"]) + data_path = Path(geode_functions.data_file_path(item["id"])) + # Projects saved before the simplification kept a bounding box as their light viewable + for light_file in data_path.glob("*viewable.vtp"): + if light_file.name != "viewable.vtp": + light_file.unlink() + older_bounding_box = base64.b64decode(item["binary_light_viewable"]) + (data_path / "light_viewable.vtp").write_bytes(older_bounding_box) + response = client.post("/opengeodeweb_back/light_viewable", json={"id": item["id"]}) + assert response.status_code == 200 + light_viewable = base64.b64decode(response.get_json()["binary_light_viewable"]) + assert light_viewable != older_bounding_box + + def test_save_viewable_file(client: FlaskClient) -> None: [item] = test_utils.check_save_viewable_file(client, "BRep", "corbi.og_brep") assert "crs" not in item diff --git a/tests/test_utils_functions.py b/tests/test_utils_functions.py index f2fcd3c2..68dc720d 100644 --- a/tests/test_utils_functions.py +++ b/tests/test_utils_functions.py @@ -210,11 +210,11 @@ def test_save_all_viewables_returns_bounding_box(client: FlaskClient) -> None: assert "binary_light_viewable" not in component utils_functions.wait_light_viewable_saved(result["id"]) data_path = Path(app.config["DATA_FOLDER_PATH"]) / result["id"] - assert (data_path / "light_viewable.vtm").is_file() - assert (data_path / "light_viewable").is_dir() + assert (data_path / "simplified_viewable.vtm").is_file() + assert (data_path / "simplified_viewable").is_dir() data = Data.get(result["id"]) assert data is not None - assert data.light_viewable_file == "light_viewable.vtm" + assert data.light_viewable_file == "simplified_viewable.vtm" def test_save_all_viewables_saves_mesh_light_viewable(client: FlaskClient) -> None: @@ -229,10 +229,10 @@ def test_save_all_viewables_saves_mesh_light_viewable(client: FlaskClient) -> No assert b'type="PolyData"' in bounding_box utils_functions.wait_light_viewable_saved(result["id"]) data_path = Path(app.config["DATA_FOLDER_PATH"]) / result["id"] - assert (data_path / "light_viewable.vtp").is_file() + assert (data_path / "simplified_viewable.vtp").is_file() data = Data.get(result["id"]) assert data is not None - assert data.light_viewable_file == "light_viewable.vtp" + assert data.light_viewable_file == "simplified_viewable.vtp" def test_save_all_viewables_commits_to_db(client: FlaskClient) -> None: From b453edfe7fed751872694cc578aa3c59c026d58b Mon Sep 17 00:00:00 2001 From: JulienChampagnol Date: Thu, 3 Dec 2026 10:43:06 +0100 Subject: [PATCH 11/11] fix(crs): generated CRS route schemas use the shared CRS type Co-Authored-By: Claude Opus 5.5 --- .../routes/crs/schemas/align.py | 25 +++---------------- .../routes/crs/schemas/assign_geographic.py | 25 +++---------------- .../routes/crs/schemas/convert_geographic.py | 25 +++---------------- 3 files changed, 9 insertions(+), 66 deletions(-) diff --git a/src/opengeodeweb_back/routes/crs/schemas/align.py b/src/opengeodeweb_back/routes/crs/schemas/align.py index 3dc1ad00..d2c14e99 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/align.py +++ b/src/opengeodeweb_back/routes/crs/schemas/align.py @@ -1,4 +1,5 @@ from opengeodeweb_microservice.schema_types import DataId +from opengeodeweb_back.schema_types import CRS from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema from dataclasses_json import DataClassJsonMixin @@ -40,26 +41,6 @@ def __post_init__(self) -> None: linked_ids: Optional[List[DataId]] = None -@dataclass -class AlignResponseCRS(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - authority: str - code: str - name: str - - -@dataclass -class LinkedCRS(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - authority: str - code: str - name: str - - @dataclass class Linked(DataClassJsonMixin): def __post_init__(self) -> None: @@ -67,7 +48,7 @@ def __post_init__(self) -> None: id: DataId binary_light_viewable: Optional[str] = None - crs: Optional[LinkedCRS] = None + crs: Optional[CRS] = None @dataclass @@ -76,7 +57,7 @@ def __post_init__(self) -> None: print_dataclass(self) binary_light_viewable: Optional[str] = None - crs: Optional[AlignResponseCRS] = None + crs: Optional[CRS] = None linked: Optional[List[Linked]] = None diff --git a/src/opengeodeweb_back/routes/crs/schemas/assign_geographic.py b/src/opengeodeweb_back/routes/crs/schemas/assign_geographic.py index 94997041..585415d0 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/assign_geographic.py +++ b/src/opengeodeweb_back/routes/crs/schemas/assign_geographic.py @@ -1,4 +1,5 @@ from opengeodeweb_microservice.schema_types import DataId +from opengeodeweb_back.schema_types import CRS from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema from typing import Optional, List @@ -21,33 +22,13 @@ def __post_init__(self) -> None: only_plausible: Optional[bool] = None -@dataclass -class AssignGeographicResponseCRS(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - authority: str - code: str - name: str - - -@dataclass -class LinkedCRS(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - authority: str - code: str - name: str - - @dataclass class Linked(DataClassJsonMixin): def __post_init__(self) -> None: print_dataclass(self) id: DataId - crs: Optional[LinkedCRS] = None + crs: Optional[CRS] = None implausible: Optional[bool] = None unsupported: Optional[bool] = None @@ -57,7 +38,7 @@ class AssignGeographicResponse(DataClassJsonMixin): def __post_init__(self) -> None: print_dataclass(self) - crs: Optional[AssignGeographicResponseCRS] = None + crs: Optional[CRS] = None implausible: Optional[bool] = None linked: Optional[List[Linked]] = None unsupported: Optional[bool] = None diff --git a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py index 465c3446..7df2d9fa 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py +++ b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py @@ -1,4 +1,5 @@ from opengeodeweb_microservice.schema_types import DataId +from opengeodeweb_back.schema_types import CRS from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema from typing import Optional, List @@ -20,26 +21,6 @@ def __post_init__(self) -> None: linked_ids: Optional[List[DataId]] = None -@dataclass -class ConvertGeographicResponseCRS(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - authority: str - code: str - name: str - - -@dataclass -class LinkedCRS(DataClassJsonMixin): - def __post_init__(self) -> None: - print_dataclass(self) - - authority: str - code: str - name: str - - @dataclass class Linked(DataClassJsonMixin): def __post_init__(self) -> None: @@ -47,7 +28,7 @@ def __post_init__(self) -> None: id: DataId binary_light_viewable: Optional[str] = None - crs: Optional[LinkedCRS] = None + crs: Optional[CRS] = None @dataclass @@ -56,7 +37,7 @@ def __post_init__(self) -> None: print_dataclass(self) binary_light_viewable: Optional[str] = None - crs: Optional[ConvertGeographicResponseCRS] = None + crs: Optional[CRS] = None linked: Optional[List[Linked]] = None