Skip to content

Commit 3cf68ba

Browse files
authored
⬆️Datcore adapter: migration (#6594)
1 parent cd6f545 commit 3cf68ba

File tree

14 files changed

+145
-60
lines changed

14 files changed

+145
-60
lines changed

services/datcore-adapter/requirements/_base.in

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,6 @@ aiofiles
1818
fastapi
1919
fastapi-pagination
2020
httpx[http2]
21-
pydantic[email]
21+
pydantic
2222
python-multipart # for fastapi multipart uploads
2323
uvicorn[standard]

services/datcore-adapter/requirements/_base.txt

Lines changed: 84 additions & 13 deletions
Large diffs are not rendered by default.

services/datcore-adapter/src/simcore_service_datcore_adapter/_meta.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@
66
from typing import Final
77

88
from models_library.basic_types import VersionStr
9-
from pydantic import parse_obj_as
9+
from pydantic import TypeAdapter
1010

1111
current_distribution = distribution("simcore_service_datcore_adapter")
1212
__version__ = version("simcore_service_datcore_adapter")
1313

14-
API_VERSION: Final[VersionStr] = parse_obj_as(VersionStr, __version__)
14+
API_VERSION: Final[VersionStr] = TypeAdapter(VersionStr).validate_python(__version__)
1515
MAJOR, MINOR, PATCH = __version__.split(".")
1616
API_VTAG: Final[str] = f"v{MAJOR}"
1717
APP_NAME: Final[str] = current_distribution.metadata["Name"]

services/datcore-adapter/src/simcore_service_datcore_adapter/api/errors/http_error.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1-
from typing import Callable, Optional
1+
from typing import Callable
22

33
from fastapi import HTTPException
44
from fastapi.encoders import jsonable_encoder
55
from starlette.requests import Request
66
from starlette.responses import JSONResponse
77

88

9-
async def http_error_handler(_: Request, exc: HTTPException) -> JSONResponse:
9+
async def http_error_handler(_: Request, exc: Exception) -> JSONResponse:
10+
assert isinstance(exc, HTTPException) # nosec
1011
return JSONResponse(
1112
content=jsonable_encoder({"errors": [exc.detail]}), status_code=exc.status_code
1213
)
@@ -16,7 +17,7 @@ def make_http_error_handler_for_exception(
1617
status_code: int,
1718
exception_cls: type[BaseException],
1819
*,
19-
override_detail_message: Optional[str] = None,
20+
override_detail_message: str | None = None,
2021
) -> Callable:
2122
"""
2223
Produces a handler for BaseException-type exceptions which converts them

services/datcore-adapter/src/simcore_service_datcore_adapter/api/errors/pennsieve_error.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,11 @@
77

88
async def botocore_exceptions_handler(
99
_: Request,
10-
exc: ClientError,
10+
exc: Exception,
1111
) -> JSONResponse:
12+
assert isinstance(exc, ClientError) # nosec
13+
assert "Error" in exc.response # nosec
14+
assert "Code" in exc.response["Error"] # nosec
1215
if exc.response["Error"]["Code"] == "NotAuthorizedException":
1316
return JSONResponse(
1417
content=jsonable_encoder({"errors": exc.response["Error"]}),

services/datcore-adapter/src/simcore_service_datcore_adapter/api/errors/validation_error.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from typing import Union
2-
31
from fastapi.encoders import jsonable_encoder
42
from fastapi.exceptions import RequestValidationError
53
from fastapi.openapi.constants import REF_PREFIX
@@ -12,8 +10,9 @@
1210

1311
async def http422_error_handler(
1412
_: Request,
15-
exc: Union[RequestValidationError, ValidationError],
13+
exc: Exception,
1614
) -> JSONResponse:
15+
assert isinstance(exc, RequestValidationError | ValidationError) # nosec
1716
return JSONResponse(
1817
content=jsonable_encoder({"errors": exc.errors()}),
1918
status_code=HTTP_422_UNPROCESSABLE_ENTITY,

services/datcore-adapter/src/simcore_service_datcore_adapter/api/routes/files.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from typing import Annotated, Any
33

44
from fastapi import APIRouter, Depends, Header, Request
5-
from pydantic import AnyUrl, parse_obj_as
5+
from pydantic import AnyUrl, TypeAdapter
66
from servicelib.fastapi.requests_decorators import cancel_on_disconnect
77
from starlette import status
88

@@ -34,7 +34,9 @@ async def download_file(
3434
api_secret=x_datcore_api_secret,
3535
package_id=file_id,
3636
)
37-
return FileDownloadOut(link=parse_obj_as(AnyUrl, f"{presigned_download_link}"))
37+
return FileDownloadOut(
38+
link=TypeAdapter(AnyUrl).validate_python(f"{presigned_download_link}")
39+
)
3840

3941

4042
@router.delete(

services/datcore-adapter/src/simcore_service_datcore_adapter/core/application.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def create_app(settings: ApplicationSettings | None = None) -> FastAPI:
5050

5151
for name in NOISY_LOGGERS:
5252
logging.getLogger(name).setLevel(quiet_level)
53-
logger.debug("App settings:\n%s", settings.json(indent=2))
53+
logger.debug("App settings:\n%s", settings.model_dump_json(indent=2))
5454

5555
app = FastAPI(
5656
debug=settings.debug,
Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from functools import cached_property
22

33
from models_library.basic_types import BootModeEnum, LogLevel
4-
from pydantic import Field, parse_obj_as, validator
4+
from pydantic import AliasChoices, Field, TypeAdapter, field_validator
55
from pydantic.networks import AnyUrl
66
from settings_library.base import BaseCustomSettings
77
from settings_library.tracing import TracingSettings
@@ -11,7 +11,9 @@
1111
class PennsieveSettings(BaseCustomSettings):
1212
PENNSIEVE_ENABLED: bool = True
1313

14-
PENNSIEVE_API_URL: AnyUrl = parse_obj_as(AnyUrl, "https://api.pennsieve.io")
14+
PENNSIEVE_API_URL: AnyUrl = TypeAdapter(AnyUrl).validate_python(
15+
"https://api.pennsieve.io"
16+
)
1517
PENNSIEVE_API_GENERAL_TIMEOUT: float = 20.0
1618
PENNSIEVE_HEALTCHCHECK_TIMEOUT: float = 1.0
1719

@@ -21,28 +23,31 @@ class ApplicationSettings(BaseCustomSettings, MixinLoggingSettings):
2123
SC_BOOT_MODE: BootModeEnum | None
2224

2325
LOG_LEVEL: LogLevel = Field(
24-
LogLevel.INFO.value,
25-
env=[
26+
default=LogLevel.INFO.value,
27+
validation_alias=AliasChoices(
2628
"DATCORE_ADAPTER_LOGLEVEL",
2729
"DATCORE_ADAPTER_LOG_LEVEL",
2830
"LOG_LEVEL",
2931
"LOGLEVEL",
30-
],
32+
),
3133
)
3234

33-
PENNSIEVE: PennsieveSettings = Field(auto_default_from_env=True)
35+
PENNSIEVE: PennsieveSettings = Field(
36+
json_schema_extra={"auto_default_from_env": True}
37+
)
3438

3539
DATCORE_ADAPTER_LOG_FORMAT_LOCAL_DEV_ENABLED: bool = Field(
36-
False,
37-
env=[
40+
default=False,
41+
validation_alias=AliasChoices(
3842
"DATCORE_ADAPTER_LOG_FORMAT_LOCAL_DEV_ENABLED",
3943
"LOG_FORMAT_LOCAL_DEV_ENABLED",
40-
],
44+
),
4145
description="Enables local development log format. WARNING: make sure it is disabled if you want to have structured logs!",
4246
)
4347
DATCORE_ADAPTER_PROMETHEUS_INSTRUMENTATION_ENABLED: bool = True
4448
DATCORE_ADAPTER_TRACING: TracingSettings | None = Field(
45-
auto_default_from_env=True, description="settings for opentelemetry tracing"
49+
description="settings for opentelemetry tracing",
50+
json_schema_extra={"auto_default_from_env": True},
4651
)
4752

4853
@cached_property
@@ -54,7 +59,7 @@ def debug(self) -> bool:
5459
BootModeEnum.LOCAL,
5560
]
5661

57-
@validator("LOG_LEVEL", pre=True)
62+
@field_validator("LOG_LEVEL", mode="before")
5863
@classmethod
59-
def _validate_loglevel(cls, value) -> str:
64+
def _validate_loglevel(cls, value: str) -> str:
6065
return cls.validate_log_level(value)

services/datcore-adapter/src/simcore_service_datcore_adapter/models/schemas/datasets.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,16 @@ def from_pennsieve_package(
4545
return cls(
4646
dataset_id=package["content"]["datasetNodeId"],
4747
package_id=package["content"]["nodeId"],
48-
id=package["content"]["id"],
48+
id=f"{package['content']['id']}",
4949
name=pck_name,
5050
path=base_path / pck_name,
5151
type=package["content"]["packageType"],
5252
size=file_size,
5353
created_at=package["content"]["createdAt"],
5454
last_modified_at=package["content"]["updatedAt"],
55-
data_type=DataType.FOLDER
56-
if package["content"]["packageType"] == "Collection"
57-
else DataType.FILE,
55+
data_type=(
56+
DataType.FOLDER
57+
if package["content"]["packageType"] == "Collection"
58+
else DataType.FILE
59+
),
5860
)

0 commit comments

Comments
 (0)