Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions opengeodeweb_back_schemas.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
12 changes: 11 additions & 1 deletion opengeodeweb_back_typed_schemas.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
}

Expand Down Expand Up @@ -678,6 +687,7 @@ export interface Schemas {
readonly model_component_polygon_attribute_names: (typeof json)["opengeodeweb_back"]["model_component_polygon_attribute_names"] & TypedSchema<ModelComponentPolygonAttributeNamesParams, ModelComponentPolygonAttributeNamesResponse>;
readonly model_component_edge_attribute_range: (typeof json)["opengeodeweb_back"]["model_component_edge_attribute_range"] & TypedSchema<ModelComponentEdgeAttributeRangeParams, ModelComponentEdgeAttributeRangeResponse>;
readonly model_component_edge_attribute_names: (typeof json)["opengeodeweb_back"]["model_component_edge_attribute_names"] & TypedSchema<ModelComponentEdgeAttributeNamesParams, ModelComponentEdgeAttributeNamesResponse>;
readonly light_viewable: (typeof json)["opengeodeweb_back"]["light_viewable"] & TypedSchema<LightViewableParams, LightViewableResponse>;
readonly kill: (typeof json)["opengeodeweb_back"]["kill"] & TypedSchema<KillParams, KillResponse>;
readonly import_project: (typeof json)["opengeodeweb_back"]["import_project"] & TypedSchema<ImportProjectParams, ImportProjectResponse>;
readonly horizon_stack_info: (typeof json)["opengeodeweb_back"]["horizon_stack_info"] & TypedSchema<HorizonStackInfoParams, HorizonStackInfoResponse>;
Expand Down
10 changes: 5 additions & 5 deletions requirements.in
Original file line number Diff line number Diff line change
@@ -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
Expand Down
11 changes: 5 additions & 6 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -84,4 +84,3 @@ werkzeug==3.1.8
# flask
# flask-cors

opengeodeweb-microservice==1.*,>=1.5.1
155 changes: 155 additions & 0 deletions src/opengeodeweb_back/background_saves.py
Original file line number Diff line number Diff line change
@@ -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)}"
)
4 changes: 4 additions & 0 deletions src/opengeodeweb_back/geode_objects/geode_brep.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
6 changes: 6 additions & 0 deletions src/opengeodeweb_back/geode_objects/geode_cross_section.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
6 changes: 6 additions & 0 deletions src/opengeodeweb_back/geode_objects/geode_edged_curve2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions src/opengeodeweb_back/geode_objects/geode_edged_curve3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions src/opengeodeweb_back/geode_objects/geode_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions src/opengeodeweb_back/geode_objects/geode_horizon_stack3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}
Expand Down
6 changes: 6 additions & 0 deletions src/opengeodeweb_back/geode_objects/geode_hybrid_solid3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Loading
Loading