Skip to content
Merged
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
19 changes: 19 additions & 0 deletions docs/problem-standard-members.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# RFC 9457 standard members

`ProblemPayload` and its subclasses ignore JSON null and wrong-category values for `type`, `title`, `status`, `detail`, and `instance` before field validation. String members accept only strings; status accepts numbers, excludes booleans, and still rejects fractional or unrepresentable integer values. Ordinary `SundayModel` types and extension members retain their existing rules.

Direct decoding of `{}` yields `type="about:blank"` and absent optional standard members. The registry chooses the effective type before dispatch. A missing or discarded type never selects a custom registered problem. Typed payload constraints still reject `about:blank` where a custom fixed type is required.

With HTTP context, absent status uses the response status. Valid body status wins. Missing titles receive the status reason only for `about:blank`. Explicit empty strings are retained. Serialization omits absent standard members and preserves nullable extension fields, including through Litestar.

Normalization is a copied-mapping operation used by an inherited Pydantic `before` model validator. Discarded optional members are not marked as explicitly set. The effective type is materialized before validation so inherited custom defaults cannot replace `about:blank`. Pydantic handles defaults, constraints, field serializers, requiredness, and field presence normally; no Problem-specific core-schema rewriting or validation state is used.

The five standard members have fixed RFC wire names. Subclasses may specialize their types, constraints, requiredness, and defaults, but may not rename them with validation or serialization aliases, including path aliases. Extensions may use normal Pydantic aliases and paths, provided they do not claim a reserved standard-member name. Invalid configurations raise `TypeError` when the subclass is defined. This deliberately replaces the earlier prerelease's support for remapping standard members; use an application adapter before decoding if another input format needs translation into RFC Problem Details.

The alias restriction is Sunday's API policy, not an RFC requirement about Python classes. The RFC governs wire names and values; it does not specify language-level property names or aliases. Likewise, required fields in a specialized payload are authored constraints; the RFC itself allows omitted title and detail.

Only mapping/JSON input is normalized. Pydantic's attribute-based validation retains its native behavior. Nullable extensions, including nested objects with keys such as `detail`, are preserved. A small native wrapping serializer omits null standard members even when a subclass redeclares a field without the base `exclude_if` option.

Companion Generator output calls normalization before its own pre-validation checks. Regenerate Problems when adopting the companion Generator release; ordinary models need no migration.

Reference: [RFC 9457 §3.1](https://www.rfc-editor.org/rfc/rfc9457.html#section-3.1).
98 changes: 91 additions & 7 deletions src/sunday/problems.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,27 @@
from __future__ import annotations

from collections.abc import Mapping
from contextlib import suppress
from http import HTTPStatus
from typing import Any, ClassVar, Self

from pydantic import ConfigDict, Field
from pydantic import (
AliasChoices,
AliasPath,
ConfigDict,
Field,
SerializerFunctionWrapHandler,
model_serializer,
model_validator,
)

from .models import SundayModel

_STANDARD_MEMBERS = frozenset({"type", "title", "status", "detail", "instance"})


class ProblemPayload(SundayModel):
"""RFC 9457 problem details payload with extension-member preservation."""
"""RFC 9457 payload with fixed standard wire names and authored extensions."""

model_config = ConfigDict(populate_by_name=True, serialize_by_alias=True, extra="allow")

Expand All @@ -24,6 +36,71 @@ class ProblemPayload(SundayModel):
detail: str | None = Field(default=None, exclude_if=lambda value: value is None)
instance: str | None = Field(default=None, exclude_if=lambda value: value is None)

@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
"""Reserve the RFC wire names while leaving extension aliases to Pydantic."""
super().__pydantic_init_subclass__(**kwargs)
for name, field in cls.model_fields.items():
if name in _STANDARD_MEMBERS:
if any(
alias is not None and alias != name
for alias in (field.alias, field.validation_alias, field.serialization_alias)
):
raise TypeError(f"Problem standard member {name!r} must use its RFC wire name")
continue
alias = field.validation_alias
paths = (
alias.convert_to_aliases()
if isinstance(alias, AliasChoices)
else [alias.path]
if isinstance(alias, AliasPath)
else [[alias]]
if isinstance(alias, str)
else []
)
names = {name, field.alias, field.serialization_alias, *(path[0] for path in paths)}
if names & _STANDARD_MEMBERS:
raise TypeError(f"Problem extension {name!r} cannot use a reserved RFC member name")

@model_validator(mode="before")
@classmethod
def _normalize_standard_members(cls, value: Any) -> Any:
return cls.normalize_standard_members(value)

@classmethod
def normalize_standard_members(cls, value: Any) -> Any:
"""Copy JSON input, discard wrong standard types, and supply the effective type.

Generated union dispatch uses this same function before choosing a subtype.
Correctly typed values, extensions, and nested contents remain untouched.
"""
if not isinstance(value, Mapping):
return value
normalized = value.copy() if isinstance(value, dict) else dict(value)
for name in _STANDARD_MEMBERS:
if name not in normalized:
continue
member = normalized[name]
valid = (
isinstance(member, (int, float)) and not isinstance(member, bool)
if name == "status"
else isinstance(member, str)
)
if not valid:
del normalized[name]
normalized.setdefault("type", "about:blank")
return normalized

@model_serializer(mode="wrap")
def _serialize_standard_members(self, handler: SerializerFunctionWrapHandler): # type: ignore[no-untyped-def]
# A return annotation replaces Pydantic's model JSON schema with that type's schema.
# Redeclaring a field can replace its exclude_if; keep RFC omission on subclasses.
result: dict[str, Any] = handler(self)
for name in _STANDARD_MEMBERS:
if result.get(name) is None:
result.pop(name, None)
return result


class Problem(Exception):
"""Catchable RFC problem backed by a typed Pydantic payload."""
Expand Down Expand Up @@ -87,11 +164,18 @@ def register_problem(self, type_uri: str, problem_type: type[Problem]) -> None:

def decode(self, value: Mapping[str, object], *, response_status: int | None = None) -> Problem:
"""Decode a problem mapping, falling back to the base problem type."""
type_uri = value.get("type", "about:blank")
problem_type = self._problem_types.get(type_uri, Problem) if isinstance(type_uri, str) else Problem
payload = problem_type.payload_type.model_validate(value)
if payload.status is None and response_status is not None:
payload = payload.model_copy(update={"status": response_status})
type_uri = value.get("type")
if not isinstance(type_uri, str):
type_uri = "about:blank"
problem_type = self._problem_types.get(type_uri, Problem)
payload_type = problem_type.payload_type
normalized = payload_type.normalize_standard_members(value)
if response_status is not None:
normalized.setdefault("status", response_status)
if type_uri == "about:blank" and "title" not in normalized:
with suppress(ValueError):
normalized["title"] = HTTPStatus(normalized["status"]).phrase
payload = payload_type.model_validate(normalized)
return problem_type(payload)

def copy(self) -> ProblemRegistry:
Expand Down
3 changes: 3 additions & 0 deletions tests/test_httpx.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,8 @@ async def test_typed_problem_decoding_and_generic_fallback() -> None:
"type": "https://example.test/problems/conflict",
"title": "Conflict",
"conflicting_id": "project-1",
"detail": 42,
"status": "401",
},
),
httpx.Response(
Expand All @@ -427,6 +429,7 @@ def handler(_request: httpx.Request) -> httpx.Response:
with pytest.raises(ConflictProblem) as conflict:
await operation.execute()
assert conflict.value.status == 409
assert conflict.value.detail is None
assert conflict.value.payload.conflicting_id == "project-1" # type: ignore[attr-defined]

with pytest.raises(Problem) as unknown:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_litestar.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ class NullableProblemPayload(ProblemPayload):

@get("/nullable-problem")
async def nullable_problem() -> None:
raise Problem(NullableProblemPayload(status=400, required_nullable=None))
raise Problem(NullableProblemPayload.model_validate({"status": 400, "requiredNullable": None, "detail": []}))

with TestClient(Litestar(route_handlers=[nullable_problem], plugins=[SundayPlugin()])) as client:
response = client.get("/nullable-problem")
Expand Down
Loading
Loading