Skip to content
9 changes: 9 additions & 0 deletions DashAI/back/api/api_v1/endpoints/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,10 @@ async def delete_converter(

The notebook's working copy, dataset or document, is restored from its
source and the earlier converters are enqueued again in creation order.
A source without stored files answers 409 ``Notebook source data is
missing`` and changes nothing.
"""
from DashAI.back.core.stored_paths import StoredPathError
from DashAI.back.dataloaders.classes.notebook_data import restore_notebook_data
from DashAI.back.dependencies.database.models import Converter, Explorer
from DashAI.back.job.converter_job import ConverterJob
Expand Down Expand Up @@ -369,6 +372,12 @@ async def delete_converter(
last_job_id = job_ids[-1] if job_ids else None
return {"jobId": last_job_id}

except StoredPathError as e:
logger.warning("Notebook %s has no source to restore: %s", notebook.id, e)
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Notebook source data is missing",
) from e
except exc.SQLAlchemyError as e:
logger.exception(e)
raise HTTPException(
Expand Down
14 changes: 11 additions & 3 deletions DashAI/back/api/api_v1/endpoints/data_documents.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
require_content_type,
)
from DashAI.back.core.enums.status import ConverterStatus, DocumentStatus
from DashAI.back.core.stored_paths import copy_stored_tree, is_stored_directory
from DashAI.back.dependencies.database.models import (
Converter,
DataDocument,
Expand Down Expand Up @@ -266,7 +267,7 @@ def _copy_notebook_document(
dict
The item counts of the copied document, keyed by type name.
"""
shutil.copytree(working_copy, target / "document")
copy_stored_tree(working_copy, target / "document")
sidecar_path = target / "document" / "document.json"
with open(sidecar_path, "r", encoding="utf-8") as f:
sidecar = json.load(f)
Expand Down Expand Up @@ -312,8 +313,10 @@ def create_data_document_from_notebook(
------
HTTPException
404 for an unknown notebook; 409 for a taken name or while a
converter of the notebook is still running; 422 for an empty name or
a dataset notebook; 500 when the copy or the database fails.
converter of the notebook is still running; 422 for an empty name, a
dataset notebook, or ``Notebook document is missing`` when the
working copy has no stored files; 500 when the copy or the database
fails.
"""
from DashAI.back.dataloaders.classes.notebook_data import notebook_data_path

Expand All @@ -334,6 +337,11 @@ def create_data_document_from_notebook(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Only document notebooks can be saved as documents",
)
if not is_stored_directory(notebook_data_path(notebook)):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Notebook document is missing",
)
running = db.execute(
select(Converter.id).where(
Converter.notebook_id == notebook.id,
Expand Down
15 changes: 14 additions & 1 deletion DashAI/back/api/api_v1/endpoints/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -950,10 +950,18 @@ async def copy_dataset(
-------
Dataset
The newly created dataset.

Raises
------
HTTPException
404 for an unknown dataset; 422 when it is not finished or has no
stored files; 409 when the copy name is taken; 500 when the copy or
the database write fails.
"""
import shutil

from DashAI.back.core.enums.status import DatasetStatus
from DashAI.back.core.stored_paths import copy_stored_tree, is_stored_directory

dataset_id = dataset["dataset_id"]
logger.debug(f"Copying dataset with ID {dataset_id}.")
Expand All @@ -971,12 +979,17 @@ async def copy_dataset(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Original dataset is not in finished state",
)
if not is_stored_directory(original_dataset.file_path):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Original dataset has no stored files",
)

# Create a new folder for the copied dataset
new_name = f"{original_dataset.name}_copy"
new_folder_path = config["DATASETS_PATH"] / new_name
try:
shutil.copytree(original_dataset.file_path, new_folder_path)
copy_stored_tree(original_dataset.file_path, new_folder_path)
except FileExistsError:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
Expand Down
66 changes: 52 additions & 14 deletions DashAI/back/api/api_v1/endpoints/notebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
read_outline,
require_content_type,
)
from DashAI.back.core.enums.status import DocumentStatus
from DashAI.back.core.enums.status import DatasetStatus, DocumentStatus
from DashAI.back.core.stored_paths import copy_stored_tree, is_stored_directory
from DashAI.back.dependencies.database.models import (
Converter,
DataDocument,
Expand Down Expand Up @@ -60,6 +61,37 @@ class _NotebookCopy(NamedTuple):
file_path: Path


def _ready_source(ready: bool, source: Path, detail: str) -> Path:
"""Return the directory a notebook copies, once its entity is ready.

Parameters
----------
ready : bool
Whether the dataset or document finished loading.
source : Path
The stored directory the notebook would copy.
detail : str
Error detail sent when the source cannot be copied.

Returns
-------
Path
``source``.

Raises
------
HTTPException
422 with ``detail`` when the entity is not finished or its stored
directory is empty, relative or missing.
"""
if not ready or not is_stored_directory(source):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=detail,
)
return source


def _plan_notebook_copy(
db: "Session", params: NotebookCreate, config: Dict[str, Any]
) -> _NotebookCopy:
Expand Down Expand Up @@ -87,8 +119,9 @@ def _plan_notebook_copy(
Raises
------
HTTPException
404 when the source does not exist, 422 when the document has not
finished parsing.
404 when the source does not exist, 422 ``Dataset is not ready`` or
``Document is not ready`` when it has not finished loading or has no
stored files.
"""
if params.document_id is not None:
document = db.get(DataDocument, params.document_id)
Expand All @@ -97,16 +130,16 @@ def _plan_notebook_copy(
status_code=status.HTTP_404_NOT_FOUND,
detail="Document not found",
)
if document.status != DocumentStatus.FINISHED or not document.file_path:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Document is not ready",
)
source = _ready_source(
document.status == DocumentStatus.FINISHED,
Path(document.file_path or "") / "document",
"Document is not ready",
)
working_dir = (
Path(config["NOTEBOOK_PATH"]) / DOCUMENT_NOTEBOOKS_DIR / uuid.uuid4().hex
)
return _NotebookCopy(
source=Path(document.file_path) / "document",
source=source,
destination=working_dir / "document",
file_path=working_dir,
)
Expand All @@ -117,9 +150,14 @@ def _plan_notebook_copy(
status_code=status.HTTP_404_NOT_FOUND,
detail="Dataset not found",
)
source = _ready_source(
dataset.status == DatasetStatus.FINISHED,
Path(dataset.file_path or ""),
"Dataset is not ready",
)
working_dir = Path(config["DATASETS_PATH"]) / uuid.uuid4().hex[:8]
return _NotebookCopy(
source=Path(dataset.file_path),
source=source,
destination=working_dir,
file_path=working_dir,
)
Expand Down Expand Up @@ -153,9 +191,9 @@ def create_notebook(
Raises
------
HTTPException
404 when the dataset or document does not exist, 422 when the
document has not finished parsing, 500 when the copy or the database
write fails.
404 when the dataset or document does not exist, 422 when it has
not finished loading or has no stored files, 500 when the copy or the
database write fails.
"""
import shutil

Expand All @@ -164,7 +202,7 @@ def create_notebook(
with session_factory() as db:
copy = _plan_notebook_copy(db, params, config)
try:
shutil.copytree(copy.source, copy.destination, dirs_exist_ok=True)
copy_stored_tree(copy.source, copy.destination, dirs_exist_ok=True)
notebook_model = Notebook(
name=params.name or "Untitled Notebook",
description=params.description,
Expand Down
157 changes: 157 additions & 0 deletions DashAI/back/core/stored_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
"""Copies of the files an entity keeps under its stored path.

A failed upload or parse leaves an entity with an empty ``file_path``, and
``Path("")`` is the current working directory. Every copy made from a stored
path goes through these helpers, so such a path is refused before anything
is written instead of copying the backend's working directory.
"""

import shutil
from pathlib import Path
from typing import Optional, Union

StoredPath = Union[str, Path, None]


class StoredPathError(FileNotFoundError):
"""A stored path that names no files to copy."""


def _stored_path_problem(path: StoredPath, directory: bool) -> Optional[str]:
"""Explain why a stored path cannot be copied from.

Parameters
----------
path : str, Path or None
The path read from the entity row.
directory : bool
Whether the path must be a directory.

Returns
-------
str or None
The reason, or None when the path can be copied from.
"""
if path is None or not str(path).strip():
return "The stored path is empty."
source = Path(path)
if not source.is_absolute():
return f"The stored path '{path}' is relative to the working directory."
if not source.exists():
return f"The stored path '{path}' does not exist."
if directory and not source.is_dir():
return f"The stored path '{path}' is not a directory."
return None


def is_stored_path(path: StoredPath) -> bool:
"""Tell whether a stored file or directory can be copied from.

Parameters
----------
path : str, Path or None
The path read from the entity row.

Returns
-------
bool
True when the path is absolute and exists.
"""
return _stored_path_problem(path, directory=False) is None


def is_stored_directory(path: StoredPath) -> bool:
"""Tell whether a stored directory can be copied from.

Parameters
----------
path : str, Path or None
The path read from the entity row.

Returns
-------
bool
True when the path is absolute and an existing directory.
"""
return _stored_path_problem(path, directory=True) is None


def require_stored_path(path: StoredPath, directory: bool = False) -> Path:
"""Return a stored path that can be copied from.

Parameters
----------
path : str, Path or None
The path read from the entity row.
directory : bool
Whether the path must be a directory.

Returns
-------
Path
The path.

Raises
------
StoredPathError
If the path is empty, relative, missing, or not a directory when one
is required.
"""
problem = _stored_path_problem(path, directory)
if problem is not None:
raise StoredPathError(problem)
return Path(str(path))


def copy_stored_tree(
source: StoredPath, destination: Union[str, Path], dirs_exist_ok: bool = False
) -> Path:
"""Copy a stored directory.

Parameters
----------
source : str, Path or None
The stored directory.
destination : str or Path
Where the copy goes.
dirs_exist_ok : bool
Whether the copy may write into an existing ``destination``.

Returns
-------
Path
The destination.

Raises
------
StoredPathError
If ``source`` is not a stored directory; nothing is written then.
"""
stored = require_stored_path(source, directory=True)
return Path(shutil.copytree(stored, destination, dirs_exist_ok=dirs_exist_ok))


def copy_stored_entry(source: StoredPath, destination: Union[str, Path]) -> Path:
"""Copy a stored file or directory.

Parameters
----------
source : str, Path or None
The stored file or directory.
destination : str or Path
Where the copy goes.

Returns
-------
Path
The destination.

Raises
------
StoredPathError
If ``source`` is not a stored path; nothing is written then.
"""
stored = require_stored_path(source)
if stored.is_dir():
return Path(shutil.copytree(stored, destination))
return Path(shutil.copy2(stored, destination))
Loading
Loading