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/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 9e2f1942..d6b4690c 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 @@ -84,4 +84,3 @@ werkzeug==3.1.8 # flask # flask-cors -opengeodeweb-microservice==1.*,>=1.5.1 diff --git a/src/opengeodeweb_back/background_saves.py b/src/opengeodeweb_back/background_saves.py new file mode 100644 index 00000000..3163987a --- /dev/null +++ b/src/opengeodeweb_back/background_saves.py @@ -0,0 +1,155 @@ +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 + # A save still queued is dropped without waiting for it + entry.future.cancel() + 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/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/src/opengeodeweb_back/routes/blueprint_routes.py b/src/opengeodeweb_back/routes/blueprint_routes.py index 2d8e55b1..d2ceb6df 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, @@ -951,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/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 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 a63109df..8a85f5e5 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,10 @@ 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") +# 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 @@ -254,6 +254,23 @@ def _uuid_to_flat_index(data_id: str, viewable_file: str | None) -> dict[str, in return uuid_to_flat_index +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]) -> list[dict[str, Any]]: model_mesh_components = model.mesh_components() mesh_components = [] @@ -315,141 +332,85 @@ def model_components(data_id: str, model: GeodeModel, viewable_file: str | None) } -@dataclass -class _NativeSave: - """A background native save. The object is kept until it is saved, to retry a failure.""" +def _save_native_in_background(geode_object: GeodeObject, data_id: str, native_path: str) -> None: + native_saves.submit(data_id, lambda: geode_object.save(native_path)) - 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 +def discard_native_save(data_id: str) -> None: + """Wait for the native save of data_id, if any, and forget it whatever its outcome.""" + native_saves.discard(data_id) -_native_saves: dict[str, _NativeSave] = {} +# Not "light_viewable": older projects stored a bounding box under that name +LIGHT_VIEWABLE_STEM = "simplified_viewable" -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 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_STEM}.{extension}" - 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 _save_light_viewable_in_background( + geode_object: GeodeObject, data_id: str, data_path: str +) -> None: + light_path = str(Path(data_path) / LIGHT_VIEWABLE_STEM) + light_saves.submit(data_id, lambda: geode_object.save_light_viewable(light_path)) -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] +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 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) + +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" + 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") + # 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": [ + {"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: - """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) -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( @@ -457,6 +418,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(): @@ -464,8 +426,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"), ), ] ) @@ -473,11 +435,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 @@ -509,6 +470,8 @@ def save_all_viewables_and_return_info( 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/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_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 diff --git a/tests/test_crs_routes.py b/tests/test_crs_routes.py index fb744463..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,6 +665,18 @@ def test_assign_only_plausible(client: FlaskClient) -> None: assert _active_crs(client, plausible_id) == LAMBERT +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") + client.post(assign_route, json={"id": brep["id"], **LAMBERT}) + response = client.post(route, json={"id": brep["id"], **UTM}) + assert response.status_code == 200 + 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: route = "/opengeodeweb_back/crs/assign_geographic" # Models built from surfaces often keep their blocks without mesh diff --git a/tests/test_geode_functions.py b/tests/test_geode_functions.py index d6efc9e1..dc33dbc0 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,13 @@ 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) + 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" 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 / "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 87b788f5..68dc720d 100644 --- a/tests/test_utils_functions.py +++ b/tests/test_utils_functions.py @@ -196,6 +196,45 @@ def test_save_all_viewables_and_return_info(client: FlaskClient) -> None: assert expected_data_path.exists() +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) + + bounding_box = base64.b64decode(result["binary_light_viewable"], validate=True) + assert b'type="PolyData"' in bounding_box + for component in result["mesh_components"]: + 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 / "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 == "simplified_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 / "simplified_viewable.vtp").is_file() + data = Data.get(result["id"]) + assert data is not None + assert data.light_viewable_file == "simplified_viewable.vtp" + + def test_save_all_viewables_commits_to_db(client: FlaskClient) -> None: app = client.application with app.app_context(): @@ -238,20 +277,20 @@ 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="PolyData"' 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 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(