rn-forge-web 0.3.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of rn-forge-web might be problematic. Click here for more details.
- rn_forge/web/__init__.py +367 -0
- rn_forge/web/asgi.py +147 -0
- rn_forge/web/auth.py +115 -0
- rn_forge/web/concurrency.py +251 -0
- rn_forge/web/conformance/__init__.py +33 -0
- rn_forge/web/conformance/cases.py +1890 -0
- rn_forge/web/conformance/types.py +134 -0
- rn_forge/web/deprecation.py +37 -0
- rn_forge/web/exceptions.py +386 -0
- rn_forge/web/health.py +239 -0
- rn_forge/web/idempotency.py +296 -0
- rn_forge/web/merge_patch.py +98 -0
- rn_forge/web/models.py +24 -0
- rn_forge/web/openapi.py +176 -0
- rn_forge/web/operations.py +54 -0
- rn_forge/web/pagination.py +253 -0
- rn_forge/web/problem.py +593 -0
- rn_forge/web/py.typed +0 -0
- rn_forge/web/read_mask.py +121 -0
- rn_forge/web/security.py +97 -0
- rn_forge/web/soft_delete.py +31 -0
- rn_forge/web/tracing.py +53 -0
- rn_forge/web/transfer.py +408 -0
- rn_forge_web-0.3.0.dev0.dist-info/METADATA +139 -0
- rn_forge_web-0.3.0.dev0.dist-info/RECORD +27 -0
- rn_forge_web-0.3.0.dev0.dist-info/WHEEL +4 -0
- rn_forge_web-0.3.0.dev0.dist-info/licenses/LICENSE +21 -0
rn_forge/web/openapi.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Framework-independent OpenAPI operation naming and problem-response declarations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from http import HTTPStatus
|
|
8
|
+
from typing import Any, Final, cast
|
|
9
|
+
|
|
10
|
+
from rn_forge.web.problem import INTERNAL_ERROR, PROBLEM_MEDIA_TYPE, ProblemRegistry
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"API_CATALOG_PATH",
|
|
14
|
+
"DOCS_PATH",
|
|
15
|
+
"LINKSET_MEDIA_TYPE",
|
|
16
|
+
"OPENAPI_PATH",
|
|
17
|
+
"PROBLEM_DETAIL_REF",
|
|
18
|
+
"add_problem_responses",
|
|
19
|
+
"api_catalog_body",
|
|
20
|
+
"operation_id",
|
|
21
|
+
"problem_response",
|
|
22
|
+
"problem_statuses",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
OPENAPI_PATH: Final = "/openapi.json"
|
|
26
|
+
"""Default path of the OpenAPI document."""
|
|
27
|
+
|
|
28
|
+
DOCS_PATH: Final = "/docs"
|
|
29
|
+
"""Default path of the human-readable documentation UI."""
|
|
30
|
+
|
|
31
|
+
API_CATALOG_PATH: Final = "/.well-known/api-catalog"
|
|
32
|
+
"""RFC 9727's well-known URI for the API catalog."""
|
|
33
|
+
|
|
34
|
+
LINKSET_MEDIA_TYPE: Final = "application/linkset+json"
|
|
35
|
+
"""The media type of an RFC 9264 linkset, which RFC 9727 requires for the catalog."""
|
|
36
|
+
|
|
37
|
+
PROBLEM_DETAIL_REF: Final = "#/components/schemas/ProblemDetail"
|
|
38
|
+
"""The ``$ref`` every declared problem response points at."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def api_catalog_body(
|
|
42
|
+
*,
|
|
43
|
+
anchor: str,
|
|
44
|
+
service_desc: str,
|
|
45
|
+
service_doc: str | None = None,
|
|
46
|
+
status: str | None = None,
|
|
47
|
+
) -> dict[str, Any]:
|
|
48
|
+
"""Return the RFC 9727 ``/.well-known/api-catalog`` body.
|
|
49
|
+
|
|
50
|
+
An RFC 9264 linkset with one entry, following RFC 9727 §4's example: the
|
|
51
|
+
machine-readable description (RFC 8631's ``service-desc`` relation, in
|
|
52
|
+
practice the OpenAPI document) is required, and the human documentation
|
|
53
|
+
(``service-doc``) and the API's status (``status``, in practice
|
|
54
|
+
readiness) are added when given.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
anchor: The API's base URI.
|
|
58
|
+
service_desc: The OpenAPI document's URI.
|
|
59
|
+
service_doc: The human documentation's URI.
|
|
60
|
+
status: The status endpoint's URI.
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
``{"linkset": [{"anchor": ..., "service-desc": [{"href": ...}], ...}]}``.
|
|
64
|
+
"""
|
|
65
|
+
entry: dict[str, Any] = {"anchor": anchor, "service-desc": [{"href": service_desc}]}
|
|
66
|
+
if service_doc is not None:
|
|
67
|
+
entry["service-doc"] = [{"href": service_doc}]
|
|
68
|
+
if status is not None:
|
|
69
|
+
entry["status"] = [{"href": status}]
|
|
70
|
+
return {"linkset": [entry]}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def problem_statuses(registry: ProblemRegistry) -> list[int]:
|
|
74
|
+
"""Return every status *registry* can render, plus 500, ascending."""
|
|
75
|
+
return sorted(
|
|
76
|
+
{row.status for row in registry.rows().values()} | {INTERNAL_ERROR.status}
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def problem_response(status: int) -> dict[str, Any]:
|
|
81
|
+
"""Return the OpenAPI response object for a problem with *status*."""
|
|
82
|
+
return {
|
|
83
|
+
"description": HTTPStatus(status).phrase,
|
|
84
|
+
"content": {PROBLEM_MEDIA_TYPE: {"schema": {"$ref": PROBLEM_DETAIL_REF}}},
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def add_problem_responses(
|
|
89
|
+
document: Mapping[str, Any], registry: ProblemRegistry
|
|
90
|
+
) -> None:
|
|
91
|
+
"""Declare a problem response for each of :func:`problem_statuses` on every operation.
|
|
92
|
+
|
|
93
|
+
Mutates *document* in place. A response the author already declared for a
|
|
94
|
+
status is never overwritten. The ``ProblemDetail`` component itself is the
|
|
95
|
+
caller's to add.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
document: An OpenAPI document, as a generator emitted it.
|
|
99
|
+
registry: The rows the application's problem handler renders with.
|
|
100
|
+
"""
|
|
101
|
+
statuses = problem_statuses(registry)
|
|
102
|
+
paths = cast("Mapping[str, Mapping[str, Any]]", document.get("paths", {}))
|
|
103
|
+
for path_item in paths.values():
|
|
104
|
+
for operation in path_item.values():
|
|
105
|
+
if not isinstance(operation, dict):
|
|
106
|
+
continue
|
|
107
|
+
responses = cast("dict[str, Any]", operation).setdefault("responses", {})
|
|
108
|
+
for status in statuses:
|
|
109
|
+
responses.setdefault(str(status), problem_response(status))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
_VERBS: Final[Mapping[str, str]] = {
|
|
113
|
+
"POST": "Create",
|
|
114
|
+
"PUT": "Update",
|
|
115
|
+
"PATCH": "PartialUpdate",
|
|
116
|
+
"DELETE": "Delete",
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
_UNDERSCORE_LETTER: Final = re.compile(r"_([a-zA-Z])")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _camel(segment: str) -> str:
|
|
123
|
+
"""``work-items`` → ``workItems``."""
|
|
124
|
+
return _UNDERSCORE_LETTER.sub(
|
|
125
|
+
lambda match: match.group(1).upper(), segment.replace("-", "_")
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def operation_id(path: str, method: str) -> str:
|
|
130
|
+
"""Return the ``operationId`` for *path* and *method*: ``<resource><Verb>``.
|
|
131
|
+
|
|
132
|
+
The result is lower camel case. For CRUD, *resource* is the last literal
|
|
133
|
+
path segment
|
|
134
|
+
(``/api/v1/work-items/{id}`` → ``workItems``); *Verb* is ``List`` for a
|
|
135
|
+
``GET`` on a collection and ``Get`` for one on an item (the path ends in a
|
|
136
|
+
parameter), ``Create`` for ``POST``, ``Update`` for ``PUT``,
|
|
137
|
+
``PartialUpdate`` for ``PATCH``, and ``Delete`` for ``DELETE``.
|
|
138
|
+
|
|
139
|
+
Custom methods follow `AIP-136 <https://google.aip.dev/136>`_: an action
|
|
140
|
+
that is not one of the six above is addressed as ``:action`` on the resource
|
|
141
|
+
it acts on, and is named ``<resource><Action>`` regardless of HTTP method.
|
|
142
|
+
``POST /orders/{orderId}:cancel`` → ``ordersCancel``;
|
|
143
|
+
``POST /orders:batchCreate`` → ``ordersBatchCreate``.
|
|
144
|
+
|
|
145
|
+
Routes that do not encode custom methods with the colon form require an
|
|
146
|
+
explicit framework-specific override.
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
path: The route's path template, parameters in braces.
|
|
150
|
+
method: The HTTP method, any case.
|
|
151
|
+
|
|
152
|
+
Returns:
|
|
153
|
+
The ``operationId``.
|
|
154
|
+
"""
|
|
155
|
+
segments = [segment for segment in path.split("/") if segment]
|
|
156
|
+
if segments and ":" in segments[-1]:
|
|
157
|
+
return _custom_method_id(segments)
|
|
158
|
+
literals = [segment for segment in segments if not segment.startswith("{")]
|
|
159
|
+
resource = _camel(literals[-1]) if literals else "root"
|
|
160
|
+
upper = method.upper()
|
|
161
|
+
if upper == "GET":
|
|
162
|
+
verb = "Get" if segments and segments[-1].startswith("{") else "List"
|
|
163
|
+
else:
|
|
164
|
+
verb = _VERBS.get(upper, upper.capitalize())
|
|
165
|
+
return f"{resource}{verb}"
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _custom_method_id(segments: list[str]) -> str:
|
|
169
|
+
"""``['orders', '{orderId}:cancel']`` → ``ordersCancel`` (AIP-136)."""
|
|
170
|
+
head, _, action = segments[-1].partition(":")
|
|
171
|
+
literals = [segment for segment in segments[:-1] if not segment.startswith("{")]
|
|
172
|
+
if head and not head.startswith("{"):
|
|
173
|
+
literals.append(head)
|
|
174
|
+
resource = _camel(literals[-1]) if literals else "root"
|
|
175
|
+
verb = _camel(action)
|
|
176
|
+
return f"{resource}{verb[:1].upper()}{verb[1:]}"
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Long-running operations in the AIP-151 shape, with an RFC 9457 error."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Self
|
|
6
|
+
|
|
7
|
+
from pydantic import ConfigDict, Field, model_validator
|
|
8
|
+
from rn_forge.web.models import WireModel
|
|
9
|
+
from rn_forge.web.problem import ProblemDetail
|
|
10
|
+
|
|
11
|
+
__all__ = ["Operation"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _is_none(value: object) -> bool:
|
|
15
|
+
return value is None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Operation(WireModel):
|
|
19
|
+
"""The resource a long-running call returns and a client polls.
|
|
20
|
+
|
|
21
|
+
The call answers ``202`` with a ``Location`` naming this resource. While
|
|
22
|
+
``done`` is false neither ``error`` nor ``response`` is set; once it is true
|
|
23
|
+
exactly one of them is. Absent members are omitted from the body.
|
|
24
|
+
|
|
25
|
+
Example:
|
|
26
|
+
``Operation(name="operations/7", done=True, response={"id": "1"}).as_body()``
|
|
27
|
+
returns ``{"name": "operations/7", "done": True, "response": {"id": "1"}}``.
|
|
28
|
+
|
|
29
|
+
Raises:
|
|
30
|
+
pydantic.ValidationError: When ``done`` is false and an outcome is set,
|
|
31
|
+
or true and not exactly one is.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
model_config = ConfigDict(frozen=True)
|
|
35
|
+
|
|
36
|
+
name: str
|
|
37
|
+
done: bool = False
|
|
38
|
+
metadata: dict[str, Any] | None = Field(default=None, exclude_if=_is_none)
|
|
39
|
+
error: ProblemDetail | None = Field(default=None, exclude_if=_is_none)
|
|
40
|
+
response: dict[str, Any] | None = Field(default=None, exclude_if=_is_none)
|
|
41
|
+
|
|
42
|
+
@model_validator(mode="after")
|
|
43
|
+
def _outcome_matches_done(self) -> Self:
|
|
44
|
+
outcomes = (self.error is not None) + (self.response is not None)
|
|
45
|
+
if outcomes != (1 if self.done else 0):
|
|
46
|
+
raise ValueError(
|
|
47
|
+
"a finished operation has exactly one of error and response; "
|
|
48
|
+
"an unfinished one has neither"
|
|
49
|
+
)
|
|
50
|
+
return self
|
|
51
|
+
|
|
52
|
+
def as_body(self) -> dict[str, Any]:
|
|
53
|
+
"""Return the wire body, camelCase, omitting absent members."""
|
|
54
|
+
return self.model_dump()
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Opaque cursor pagination and ``orderBy`` using Google AIP-158 and AIP-132.
|
|
2
|
+
|
|
3
|
+
Page sizes are clamped to the configured cap. Responses use ``items``,
|
|
4
|
+
``nextPageToken``, and the optional ``totalSize`` field.
|
|
5
|
+
|
|
6
|
+
No pagination library is adopted: ``fastapi-pagination`` 0.16.0 (checked 2026-09-23) cannot produce
|
|
7
|
+
``{items, nextPageToken}`` without ``total`` from its stock cursor page, and its ``CursorParams``
|
|
8
|
+
reject an oversized page size with a 422 where AIP-158 clamps.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import json
|
|
15
|
+
from collections.abc import Collection
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Any, Final, cast
|
|
18
|
+
from urllib.parse import quote
|
|
19
|
+
|
|
20
|
+
from pydantic import ConfigDict, Field
|
|
21
|
+
from rn_forge.web.exceptions import InvalidCursor, InvalidOrderBy
|
|
22
|
+
from rn_forge.web.models import WireModel
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"DEFAULT_PAGE_SIZE_PARAM",
|
|
26
|
+
"DEFAULT_PAGE_TOKEN_PARAM",
|
|
27
|
+
"ORDER_BY_PARAM",
|
|
28
|
+
"Cursor",
|
|
29
|
+
"OrderField",
|
|
30
|
+
"Page",
|
|
31
|
+
"SortValue",
|
|
32
|
+
"check_cursor_order",
|
|
33
|
+
"clamp_page_size",
|
|
34
|
+
"decode_cursor",
|
|
35
|
+
"encode_cursor",
|
|
36
|
+
"format_order_by",
|
|
37
|
+
"next_link_header",
|
|
38
|
+
"parse_order_by",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
DEFAULT_PAGE_SIZE_PARAM: Final = "pageSize"
|
|
42
|
+
"""The query parameter carrying the requested page size."""
|
|
43
|
+
|
|
44
|
+
DEFAULT_PAGE_TOKEN_PARAM: Final = "pageToken" # noqa: S105 # identifier name, not a secret
|
|
45
|
+
"""The query parameter carrying the continuation token."""
|
|
46
|
+
|
|
47
|
+
ORDER_BY_PARAM: Final = "orderBy"
|
|
48
|
+
"""The query parameter carrying the sort order."""
|
|
49
|
+
|
|
50
|
+
SortValue = str | int | float | bool | None
|
|
51
|
+
"""One sort value in a page token, as its JSON type; dates are ISO 8601 strings."""
|
|
52
|
+
|
|
53
|
+
_SORT_KEY: Final = "k"
|
|
54
|
+
_ENTITY_ID: Final = "id"
|
|
55
|
+
_ORDER_BY: Final = "o"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class Cursor:
|
|
60
|
+
"""The decoded contents of a page token.
|
|
61
|
+
|
|
62
|
+
``sort_keys`` holds the last row's value for each ``orderBy`` term, in term
|
|
63
|
+
order; ``entity_id`` is the tiebreaker that makes the ordering total.
|
|
64
|
+
Together they are the keyset the next page resumes from. ``order_by`` is
|
|
65
|
+
the canonical ``orderBy`` the token was issued for, empty for the
|
|
66
|
+
endpoint's default order, whose ``sort_keys`` is empty.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
sort_keys: tuple[SortValue, ...]
|
|
70
|
+
entity_id: str
|
|
71
|
+
order_by: str = ""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class OrderField:
|
|
76
|
+
"""One ``orderBy`` term: a field name as it appears on the wire and a direction."""
|
|
77
|
+
|
|
78
|
+
field: str
|
|
79
|
+
descending: bool = False
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def parse_order_by(
|
|
83
|
+
raw: str | None, *, allowed: Collection[str]
|
|
84
|
+
) -> tuple[OrderField, ...]:
|
|
85
|
+
"""Parse an AIP-132 ``orderBy`` value such as ``displayName desc``.
|
|
86
|
+
|
|
87
|
+
A term is a field name optionally followed by ``asc`` or ``desc`` (default
|
|
88
|
+
``asc``). Terms are comma-separated, whitespace around a term is ignored,
|
|
89
|
+
and a field may appear only once.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
raw: The query parameter value. ``None`` or blank yields no terms.
|
|
93
|
+
allowed: The field names the endpoint can sort by, as they appear on
|
|
94
|
+
the wire.
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
The terms in order, or an empty tuple when *raw* is blank.
|
|
98
|
+
|
|
99
|
+
Raises:
|
|
100
|
+
InvalidOrderBy: A term is malformed (including an empty one), names a
|
|
101
|
+
field outside *allowed*, or repeats an earlier term's field.
|
|
102
|
+
"""
|
|
103
|
+
if raw is None or not raw.strip():
|
|
104
|
+
return ()
|
|
105
|
+
terms: list[OrderField] = []
|
|
106
|
+
for chunk in raw.split(","):
|
|
107
|
+
parts = chunk.split()
|
|
108
|
+
if len(parts) not in (1, 2) or (
|
|
109
|
+
len(parts) == 2 and parts[1] not in ("asc", "desc")
|
|
110
|
+
):
|
|
111
|
+
raise InvalidOrderBy(
|
|
112
|
+
f"Malformed orderBy term {chunk.strip()!r}", error_code=400
|
|
113
|
+
)
|
|
114
|
+
name = parts[0]
|
|
115
|
+
if name not in allowed:
|
|
116
|
+
raise InvalidOrderBy(
|
|
117
|
+
f"Cannot order by {name!r}; allowed: {', '.join(sorted(allowed))}",
|
|
118
|
+
error_code=400,
|
|
119
|
+
)
|
|
120
|
+
if any(t.field == name for t in terms):
|
|
121
|
+
raise InvalidOrderBy(
|
|
122
|
+
f"orderBy names {name!r} more than once", error_code=400
|
|
123
|
+
)
|
|
124
|
+
terms.append(
|
|
125
|
+
OrderField(name, descending=len(parts) == 2 and parts[1] == "desc")
|
|
126
|
+
)
|
|
127
|
+
return tuple(terms)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def format_order_by(terms: Collection[OrderField]) -> str:
|
|
131
|
+
"""Return the canonical ``orderBy`` string for *terms* (``desc`` explicit, ``asc`` omitted)."""
|
|
132
|
+
return ",".join(f"{t.field} desc" if t.descending else t.field for t in terms)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def check_cursor_order(cursor: Cursor, terms: Collection[OrderField]) -> None:
|
|
136
|
+
"""Reject a page token issued for a different ordering than *terms*.
|
|
137
|
+
|
|
138
|
+
Raises:
|
|
139
|
+
InvalidCursor: The token's order differs from the request's, or it
|
|
140
|
+
holds a different number of sort values than there are terms.
|
|
141
|
+
"""
|
|
142
|
+
if cursor.order_by != format_order_by(terms):
|
|
143
|
+
raise InvalidCursor("pageToken does not match orderBy", error_code=400)
|
|
144
|
+
if len(cursor.sort_keys) != len(terms):
|
|
145
|
+
raise InvalidCursor("Malformed page token", error_code=400)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def encode_cursor(
|
|
149
|
+
sort_keys: tuple[SortValue, ...], entity_id: str, order_by: str = ""
|
|
150
|
+
) -> str:
|
|
151
|
+
"""Encode a keyset position as an opaque page token.
|
|
152
|
+
|
|
153
|
+
URL-safe base64 over compact JSON — small, and safe in a query string
|
|
154
|
+
without further escaping. *sort_keys* holds one value per ``orderBy`` term
|
|
155
|
+
and keeps each value's JSON type. *order_by* is the canonical ordering from
|
|
156
|
+
:func:`format_order_by`; it is omitted from the token when empty.
|
|
157
|
+
"""
|
|
158
|
+
fields: dict[str, Any] = {_SORT_KEY: list(sort_keys), _ENTITY_ID: entity_id}
|
|
159
|
+
if order_by:
|
|
160
|
+
fields[_ORDER_BY] = order_by
|
|
161
|
+
payload = json.dumps(fields, separators=(",", ":"), sort_keys=True)
|
|
162
|
+
return base64.urlsafe_b64encode(payload.encode()).decode()
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def decode_cursor(raw: str) -> Cursor:
|
|
166
|
+
"""Decode a page token.
|
|
167
|
+
|
|
168
|
+
Every malformed input class is caught — not base64, base64 of non-JSON,
|
|
169
|
+
JSON of a non-object, JSON missing a key, a sort-value list that is not a
|
|
170
|
+
list of scalars. Missing one of them turns a tampered token into a 500.
|
|
171
|
+
|
|
172
|
+
Raises:
|
|
173
|
+
InvalidCursor: *raw* is not a well-formed page token.
|
|
174
|
+
"""
|
|
175
|
+
try:
|
|
176
|
+
decoded = base64.urlsafe_b64decode(raw.encode())
|
|
177
|
+
payload = json.loads(decoded)
|
|
178
|
+
sort_keys = payload[_SORT_KEY]
|
|
179
|
+
if not isinstance(sort_keys, list) or not all(
|
|
180
|
+
v is None or isinstance(v, str | int | float | bool)
|
|
181
|
+
for v in cast(list[object], sort_keys)
|
|
182
|
+
):
|
|
183
|
+
raise ValueError("sort values are not a list of scalars")
|
|
184
|
+
return Cursor(
|
|
185
|
+
sort_keys=tuple(cast(list[SortValue], sort_keys)),
|
|
186
|
+
entity_id=str(payload[_ENTITY_ID]),
|
|
187
|
+
order_by=str(payload.get(_ORDER_BY, "")),
|
|
188
|
+
)
|
|
189
|
+
except (ValueError, KeyError, TypeError) as exc:
|
|
190
|
+
raise InvalidCursor("Malformed page token", error_code=400) from exc
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _is_none(value: object) -> bool:
|
|
194
|
+
return value is None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class Page[T](WireModel):
|
|
198
|
+
"""One page of results, in the AIP-158 envelope.
|
|
199
|
+
|
|
200
|
+
``nextPageToken`` is always present and ``null`` on the last page;
|
|
201
|
+
``totalSize`` is omitted from the body when absent.
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
model_config = ConfigDict(frozen=True)
|
|
205
|
+
|
|
206
|
+
items: list[T]
|
|
207
|
+
next_page_token: str | None
|
|
208
|
+
total_size: int | None = Field(default=None, exclude_if=_is_none)
|
|
209
|
+
|
|
210
|
+
def as_body(self) -> dict[str, Any]:
|
|
211
|
+
"""Return the wire body, camelCase, omitting an absent ``totalSize``."""
|
|
212
|
+
return self.model_dump()
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def clamp_page_size(requested: int | None, *, default: int, cap: int) -> int:
|
|
216
|
+
"""Return a usable page size, clamping rather than rejecting.
|
|
217
|
+
|
|
218
|
+
Per AIP-158, an over-large ``pageSize`` is coerced to the maximum.
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
requested: What the client asked for. ``None`` or a non-positive value
|
|
222
|
+
means "unspecified" and yields *default*.
|
|
223
|
+
default: The size used when the client asks for none.
|
|
224
|
+
cap: The largest size this endpoint will serve.
|
|
225
|
+
|
|
226
|
+
Returns:
|
|
227
|
+
A size in ``1..cap``.
|
|
228
|
+
"""
|
|
229
|
+
if requested is None or requested <= 0:
|
|
230
|
+
return min(default, cap)
|
|
231
|
+
return min(requested, cap)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def next_link_header(
|
|
235
|
+
base_url: str, token: str, *, param: str = DEFAULT_PAGE_TOKEN_PARAM
|
|
236
|
+
) -> str:
|
|
237
|
+
"""Build an RFC 8288 ``Link: <...>; rel="next"`` header value.
|
|
238
|
+
|
|
239
|
+
Additive, never a replacement: ``nextPageToken`` in the body is the
|
|
240
|
+
contract, and this header is a convenience for clients that were not
|
|
241
|
+
generated from the schema. A client relying only on the header will break
|
|
242
|
+
on an endpoint that cannot build an absolute URL.
|
|
243
|
+
|
|
244
|
+
Args:
|
|
245
|
+
base_url: The collection URL, with or without an existing query string.
|
|
246
|
+
token: The continuation token to embed.
|
|
247
|
+
param: The query parameter name.
|
|
248
|
+
|
|
249
|
+
Returns:
|
|
250
|
+
A value suitable for the ``Link`` response header.
|
|
251
|
+
"""
|
|
252
|
+
separator = "&" if "?" in base_url else "?"
|
|
253
|
+
return f'<{base_url}{separator}{param}={quote(token, safe="")}>; rel="next"'
|