Skip to content

Commit 57b7c60

Browse files
authored
🎨 web-api: Simpler error models and auto-generated errors in OAS (#6855)
1 parent 573b7c3 commit 57b7c60

File tree

14 files changed

+650
-177
lines changed

14 files changed

+650
-177
lines changed

api/specs/web-server/_auth.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
from typing import Any
88

9-
from _common import Error, Log
109
from fastapi import APIRouter, status
1110
from models_library.api_schemas_webserver.auth import (
1211
AccountRequestInfo,
@@ -15,6 +14,7 @@
1514
UnregisterCheck,
1615
)
1716
from models_library.generics import Envelope
17+
from models_library.rest_error import EnvelopedError, Log
1818
from pydantic import BaseModel, Field, confloat
1919
from simcore_service_webserver._meta import API_VTAG
2020
from simcore_service_webserver.login._2fa_handlers import Resend2faBody
@@ -75,7 +75,7 @@ async def register(_body: RegisterBody):
7575
"/auth/unregister",
7676
response_model=Envelope[Log],
7777
status_code=status.HTTP_200_OK,
78-
responses={status.HTTP_409_CONFLICT: {"model": Envelope[Error]}},
78+
responses={status.HTTP_409_CONFLICT: {"model": EnvelopedError}},
7979
)
8080
async def unregister_account(_body: UnregisterCheck):
8181
...
@@ -107,7 +107,7 @@ async def phone_confirmation(_body: PhoneConfirmationBody):
107107
responses={
108108
# status.HTTP_503_SERVICE_UNAVAILABLE
109109
status.HTTP_401_UNAUTHORIZED: {
110-
"model": Envelope[Error],
110+
"model": EnvelopedError,
111111
"description": "unauthorized reset due to invalid token code",
112112
}
113113
},
@@ -122,7 +122,7 @@ async def login(_body: LoginBody):
122122
operation_id="auth_login_2fa",
123123
responses={
124124
status.HTTP_401_UNAUTHORIZED: {
125-
"model": Envelope[Error],
125+
"model": EnvelopedError,
126126
"description": "unauthorized reset due to invalid token code",
127127
}
128128
},
@@ -137,7 +137,7 @@ async def login_2fa(_body: LoginTwoFactorAuthBody):
137137
operation_id="auth_resend_2fa_code",
138138
responses={
139139
status.HTTP_401_UNAUTHORIZED: {
140-
"model": Envelope[Error],
140+
"model": EnvelopedError,
141141
"description": "unauthorized reset due to invalid token code",
142142
}
143143
},
@@ -161,7 +161,7 @@ async def logout(_body: LogoutBody):
161161
status_code=status.HTTP_204_NO_CONTENT,
162162
responses={
163163
status.HTTP_401_UNAUTHORIZED: {
164-
"model": Envelope[Error],
164+
"model": EnvelopedError,
165165
"description": "unauthorized reset due to invalid token code",
166166
}
167167
},
@@ -174,7 +174,7 @@ async def check_auth():
174174
"/auth/reset-password",
175175
response_model=Envelope[Log],
176176
operation_id="auth_reset_password",
177-
responses={status.HTTP_503_SERVICE_UNAVAILABLE: {"model": Envelope[Error]}},
177+
responses={status.HTTP_503_SERVICE_UNAVAILABLE: {"model": EnvelopedError}},
178178
)
179179
async def reset_password(_body: ResetPasswordBody):
180180
"""a non logged-in user requests a password reset"""
@@ -186,7 +186,7 @@ async def reset_password(_body: ResetPasswordBody):
186186
operation_id="auth_reset_password_allowed",
187187
responses={
188188
status.HTTP_401_UNAUTHORIZED: {
189-
"model": Envelope[Error],
189+
"model": EnvelopedError,
190190
"description": "unauthorized reset due to invalid token code",
191191
}
192192
},
@@ -201,11 +201,11 @@ async def reset_password_allowed(code: str, _body: ResetPasswordConfirmation):
201201
operation_id="auth_change_email",
202202
responses={
203203
status.HTTP_401_UNAUTHORIZED: {
204-
"model": Envelope[Error],
204+
"model": EnvelopedError,
205205
"description": "unauthorized user. Login required",
206206
},
207207
status.HTTP_503_SERVICE_UNAVAILABLE: {
208-
"model": Envelope[Error],
208+
"model": EnvelopedError,
209209
"description": "unable to send confirmation email",
210210
},
211211
},
@@ -233,15 +233,15 @@ class PasswordCheckSchema(BaseModel):
233233
operation_id="auth_change_password",
234234
responses={
235235
status.HTTP_401_UNAUTHORIZED: {
236-
"model": Envelope[Error],
236+
"model": EnvelopedError,
237237
"description": "unauthorized user. Login required",
238238
},
239239
status.HTTP_409_CONFLICT: {
240-
"model": Envelope[Error],
240+
"model": EnvelopedError,
241241
"description": "mismatch between new and confirmation passwords",
242242
},
243243
status.HTTP_422_UNPROCESSABLE_ENTITY: {
244-
"model": Envelope[Error],
244+
"model": EnvelopedError,
245245
"description": "current password is invalid",
246246
},
247247
},

api/specs/web-server/_common.py

Lines changed: 17 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,22 @@
55
import sys
66
from collections.abc import Callable
77
from pathlib import Path
8-
from typing import Annotated, NamedTuple, Optional, Union, get_args, get_origin
8+
from typing import (
9+
Annotated,
10+
Any,
11+
Generic,
12+
NamedTuple,
13+
Optional,
14+
TypeVar,
15+
Union,
16+
get_args,
17+
get_origin,
18+
)
919

1020
from common_library.json_serialization import json_dumps
1121
from common_library.pydantic_fields_extension import get_type
1222
from fastapi import Query
13-
from models_library.basic_types import LogLevel
14-
from pydantic import BaseModel, ConfigDict, Field, Json, create_model
23+
from pydantic import BaseModel, Json, create_model
1524
from pydantic.fields import FieldInfo
1625

1726
CURRENT_DIR = Path(sys.argv[0] if __name__ == "__main__" else __file__).resolve().parent
@@ -78,43 +87,14 @@ def as_query(model_class: type[BaseModel]) -> type[BaseModel]:
7887
return create_model(new_model_name, **fields)
7988

8089

81-
class Log(BaseModel):
82-
level: LogLevel | None = Field("INFO", description="log level")
83-
message: str = Field(
84-
...,
85-
description="log message. If logger is USER, then it MUST be human readable",
86-
)
87-
logger: str | None = Field(
88-
None, description="name of the logger receiving this message"
89-
)
90-
91-
model_config = ConfigDict(
92-
json_schema_extra={
93-
"example": {
94-
"message": "Hi there, Mr user",
95-
"level": "INFO",
96-
"logger": "user-logger",
97-
}
98-
}
99-
)
100-
90+
ErrorT = TypeVar("ErrorT")
10191

102-
class ErrorItem(BaseModel):
103-
code: str = Field(
104-
...,
105-
description="Typically the name of the exception that produced it otherwise some known error code",
106-
)
107-
message: str = Field(..., description="Error message specific to this item")
108-
resource: str | None = Field(
109-
None, description="API resource affected by this error"
110-
)
111-
field: str | None = Field(None, description="Specific field within the resource")
11292

93+
class EnvelopeE(BaseModel, Generic[ErrorT]):
94+
"""Complementary to models_library.generics.Envelope just for the generators"""
11395

114-
class Error(BaseModel):
115-
logs: list[Log] | None = Field(None, description="log messages")
116-
errors: list[ErrorItem] | None = Field(None, description="errors metadata")
117-
status: int | None = Field(None, description="HTTP error code")
96+
error: ErrorT | None = None
97+
data: Any | None = None
11898

11999

120100
class ParamSpec(NamedTuple):

api/specs/web-server/_folders.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
FolderReplaceBodyParams,
1818
)
1919
from models_library.generics import Envelope
20+
from models_library.rest_error import EnvelopedError
2021
from simcore_service_webserver._meta import API_VTAG
22+
from simcore_service_webserver.folders._exceptions_handlers import _TO_HTTP_ERROR_MAP
2123
from simcore_service_webserver.folders._models import (
2224
FolderSearchQueryParams,
2325
FoldersListQueryParams,
@@ -29,6 +31,9 @@
2931
tags=[
3032
"folders",
3133
],
34+
responses={
35+
i.status_code: {"model": EnvelopedError} for i in _TO_HTTP_ERROR_MAP.values()
36+
},
3237
)
3338

3439

api/specs/web-server/_workspaces.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
WorkspaceReplaceBodyParams,
1818
)
1919
from models_library.generics import Envelope
20+
from models_library.rest_error import EnvelopedError
2021
from simcore_service_webserver._meta import API_VTAG
22+
from simcore_service_webserver.folders._exceptions_handlers import _TO_HTTP_ERROR_MAP
2123
from simcore_service_webserver.workspaces._groups_api import WorkspaceGroupGet
2224
from simcore_service_webserver.workspaces._models import (
2325
WorkspacesGroupsBodyParams,
@@ -31,6 +33,9 @@
3133
tags=[
3234
"workspaces",
3335
],
36+
responses={
37+
i.status_code: {"model": EnvelopedError} for i in _TO_HTTP_ERROR_MAP.values()
38+
},
3439
)
3540

3641

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
from dataclasses import dataclass
2+
from typing import Annotated
3+
4+
from models_library.generics import Envelope
5+
from pydantic import BaseModel, ConfigDict, Field
6+
7+
from .basic_types import IDStr, LogLevel
8+
9+
10+
class Log(BaseModel):
11+
level: LogLevel | None = Field("INFO", description="log level")
12+
message: str = Field(
13+
...,
14+
description="log message. If logger is USER, then it MUST be human readable",
15+
)
16+
logger: str | None = Field(
17+
None, description="name of the logger receiving this message"
18+
)
19+
20+
model_config = ConfigDict(
21+
json_schema_extra={
22+
"example": {
23+
"message": "Hi there, Mr user",
24+
"level": "INFO",
25+
"logger": "user-logger",
26+
}
27+
}
28+
)
29+
30+
31+
class ErrorItem(BaseModel):
32+
code: str = Field(
33+
...,
34+
description="Typically the name of the exception that produced it otherwise some known error code",
35+
)
36+
message: str = Field(..., description="Error message specific to this item")
37+
resource: str | None = Field(
38+
None, description="API resource affected by this error"
39+
)
40+
field: str | None = Field(None, description="Specific field within the resource")
41+
42+
43+
@dataclass
44+
class LogMessageType:
45+
# NOTE: deprecated!
46+
message: str
47+
level: str = "INFO"
48+
logger: str = "user"
49+
50+
51+
@dataclass
52+
class ErrorItemType:
53+
# NOTE: deprecated!
54+
code: str
55+
message: str
56+
resource: str | None
57+
field: str | None
58+
59+
@classmethod
60+
def from_error(cls, err: BaseException):
61+
return cls(
62+
code=err.__class__.__name__, message=str(err), resource=None, field=None
63+
)
64+
65+
66+
class ErrorGet(BaseModel):
67+
message: Annotated[
68+
str,
69+
Field(
70+
min_length=5,
71+
description="Message displayed to the user",
72+
),
73+
]
74+
support_id: Annotated[
75+
IDStr | None,
76+
Field(description="ID to track the incident during support", alias="supportId"),
77+
] = None
78+
79+
# NOTE: The fields blow are DEPRECATED. Still here to keep compatibilty with front-end until updated
80+
status: Annotated[int, Field(deprecated=True)] = 400
81+
errors: Annotated[
82+
list[ErrorItemType],
83+
Field(deprecated=True, default_factory=list, json_schema_extra={"default": []}),
84+
]
85+
logs: Annotated[
86+
list[LogMessageType],
87+
Field(deprecated=True, default_factory=list, json_schema_extra={"default": []}),
88+
]
89+
90+
model_config = ConfigDict(
91+
populate_by_name=True,
92+
extra="ignore", # Used to prune extra fields from internal data
93+
frozen=True,
94+
json_schema_extra={
95+
"examples": [
96+
{
97+
"message": "Sorry you do not have sufficient access rights for product"
98+
},
99+
{
100+
"message": "Opps this error was unexpected. We are working on that!",
101+
"supportId": "OEC:12346789",
102+
},
103+
]
104+
},
105+
)
106+
107+
108+
class EnvelopedError(Envelope[None]):
109+
error: ErrorGet
110+
111+
model_config = ConfigDict(
112+
json_schema_extra={
113+
"examples": [
114+
{"error": {"message": "display error message here"}},
115+
{
116+
"error": {"message": "failure", "supportId": "OEC:123455"},
117+
"data": None,
118+
},
119+
]
120+
},
121+
)

packages/pytest-simcore/src/pytest_simcore/helpers/assert_checks.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,13 +82,17 @@ def _do_assert_error(
8282

8383
assert is_error(expected_status_code)
8484

85-
assert len(error["errors"]) >= 1
85+
# New versions of the error models might not have this attribute
86+
details = error.get("errors", [])
87+
8688
if expected_msg:
87-
messages = [detail["message"] for detail in error["errors"]]
89+
assert details
90+
messages = [e["message"] for e in details]
8891
assert expected_msg in messages
8992

9093
if expected_error_code:
91-
codes = [detail["code"] for detail in error["errors"]]
94+
assert details
95+
codes = [e["code"] for e in details]
9296
assert expected_error_code in codes
9397

9498
return data, error

packages/service-library/src/servicelib/aiohttp/rest_middlewares.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@
1414
from aiohttp.web_response import StreamResponse
1515
from common_library.error_codes import create_error_code
1616
from common_library.json_serialization import json_dumps
17+
from models_library.rest_error import ErrorGet, ErrorItemType, LogMessageType
1718

1819
from ..logging_errors import create_troubleshotting_log_kwargs
1920
from ..mimetype_constants import MIMETYPE_APPLICATION_JSON
2021
from ..utils import is_production_environ
21-
from .rest_models import ErrorItemType, ErrorType, LogMessageType
2222
from .rest_responses import (
2323
create_data_response,
2424
create_http_error,
@@ -98,7 +98,7 @@ async def _middleware_handler(request: web.Request, handler: Handler):
9898
err.content_type = MIMETYPE_APPLICATION_JSON
9999

100100
if not err.text or not is_enveloped_from_text(err.text):
101-
error = ErrorType(
101+
error = ErrorGet(
102102
errors=[
103103
ErrorItemType.from_error(err),
104104
],

0 commit comments

Comments
 (0)