Debian Codegraph @

src/anthropic/_utils/_prepare.py

raw
1 """Turns request params into plain data that can be serialized, logged and sent again on a retry.
2
3 This takes two phases. `copy_tree` walks the params once, in document order, copying every
4 container on the way: mappings into dicts without their `NotGiven` / `Omit` entries, sequences,
5 sets and iterators into lists, pydantic models into their dumped form and dates into their ISO
6 8601 string. In a request body it also collects the slots holding a file that is to be sent
7 base64-encoded, but leaves reading them to the second phase -- the only step in which
8 `prepare_request_data` and `async_prepare_request_data` differ. Query params never involve any
9 IO: a path among them stays in place and is later rendered as its string.
10 """
11
12 from __future__ import annotations
13
14 import os
15 import base64
16 import pathlib
17 from typing import IO, Any
18 from datetime import date
19 from collections.abc import Callable
20 from typing_extensions import Literal
21
22 import anyio
23 import pydantic
24
25 from ._json import is_sent_as_list, openapi_dumps_str, openapi_model_dump
26 from ._utils import is_mapping
27 from .._files import is_base64_file_input
28 from .._types import Omit, NotGiven, Base64FileInput
29 from .._constants import FILE_INPUT_MARKERS
30
31 PLAIN_TYPES = (str, int, float, bool, type(None))
32
33 # the walk does not recurse, so only this stops a sequence or iterator that keeps yielding fresh ones
34 # of its kind, which no cycle check catches; far deeper than anything that can be serialized
35 MAX_DEPTH = 100_000
36
37 # `(container, key)`: where a value lives, so that it can be replaced in place. A plain tuple
38 # rather than a NamedTuple, as one is created for every value visited
39 Slot = tuple[Any, Any]
40 VisitLater = Callable[[Slot], None]
41
42 # `(EXIT_CONTAINER, id(container))` is a stack entry marking the end of a container's slots: popped
43 # once every slot inside the container with that id has been prepared
44 EXIT_CONTAINER: Any = object()
45
46
47 def prepare_request_data(data: object, *, location: Literal["body", "query"], keep_top_level_omit: bool = False) -> Any:
48 """Copy request params into plain data that can be serialized and re-sent.
49
50 Drops `NotGiven` / `Omit` entries (`keep_top_level_omit` keeps `Omit` directly under the
51 root, for `_merge_mappings`), turns sequences, sets and iterators into lists, dumps pydantic
52 models and formats dates as ISO 8601 strings. In a `"body"`, a path / file object found under
53 `field` of a mapping matching one of `FILE_INPUT_MARKERS` is read and base64-encoded --
54 nowhere else, and never in a `"query"`.
55 Never mutates the caller's containers; a container that contains itself raises `ValueError`.
56 """
57 root, file_slots = copy_tree(data, location=location, keep_top_level_omit=keep_top_level_omit)
58 for container, key in file_slots:
59 container[key] = read_base64(container[key])
60
61 return root[0]
62
63
64 async def async_prepare_request_data(
65 data: object, *, location: Literal["body", "query"], keep_top_level_omit: bool = False
66 ) -> Any:
67 """`prepare_request_data`, reading `pathlib.Path` inputs without blocking the event loop."""
68 root, file_slots = copy_tree(data, location=location, keep_top_level_omit=keep_top_level_omit)
69 for container, key in file_slots:
70 container[key] = await async_read_base64(container[key])
71
72 return root[0]
73
74
75 def serialize_data(data: object, *, location: Literal["body", "query"]) -> str:
76 """The JSON text that `data` is sent as once prepared."""
77 return openapi_dumps_str(prepare_request_data(data, location=location))
78
79
80 async def async_serialize_data(data: object, *, location: Literal["body", "query"]) -> str:
81 """`serialize_data`, reading `pathlib.Path` inputs without blocking the event loop."""
82 return openapi_dumps_str(await async_prepare_request_data(data, location=location))
83
84
85 def copy_tree(
86 data: object, *, location: Literal["body", "query"], keep_top_level_omit: bool
87 ) -> tuple[list[Any], list[Slot]]:
88 """Returns `[copied data]` and the slots whose file input is still to be read (in a body only)."""
89 # wrapping the data gives the top-level value a slot like any other
90 root: list[Any] = [data]
91 file_slots: list[Slot] = []
92 markers = FILE_INPUT_MARKERS if location == "body" else ()
93
94 # the source containers around the slot being visited, by id: meeting one of them again is
95 # a cycle. Holding each container as the value keeps its id from being reused meanwhile
96 ancestors: dict[int, object] = {}
97
98 # an explicit stack instead of recursion, as bodies may nest deeper than the recursion limit
99 pending: list[Slot] = [(root, 0)]
100 visit_later = pending.append
101
102 while pending:
103 container, key = pending.pop()
104 if container is EXIT_CONTAINER:
105 del ancestors[key]
106 continue
107
108 value: object = container[key]
109 kind = type(value)
110 inner_start = len(pending)
111
112 # plain dicts and lists, by far the most common, are told apart by exact type alone,
113 # sparing them the slow abstract `Mapping` / `Iterable` instance checks
114 if kind is dict or (kind is not list and is_mapping(value)):
115 copied = copy_mapping(value, visit_later, keep_omit=keep_top_level_omit and container is root)
116 for discriminator, tag, field in markers:
117 if copied.get(discriminator) == tag and is_base64_file_input(copied.get(field)):
118 file_slots.append((copied, field))
119
120 container[key] = copied
121 elif kind is list or is_sent_as_list(value):
122 container[key] = copy_items(value, visit_later)
123 elif isinstance(value, pydantic.BaseModel):
124 container[key] = openapi_model_dump(value)
125 elif isinstance(value, date):
126 container[key] = value.isoformat()
127 else:
128 # left for the encoder: a scalar subclass, a file input still to be read, or a value it rejects
129 continue
130
131 if len(pending) > inner_start:
132 # slots inside `value` are still to be visited, so it stays an ancestor until they are all done
133 ident = id(value)
134 if ident in ancestors:
135 raise ValueError("Circular reference detected")
136
137 if len(ancestors) >= MAX_DEPTH:
138 raise ValueError("Exceeds the maximum nesting depth")
139
140 ancestors[ident] = value
141 # the stack pops the last slot first, so the new ones are reversed: values are visited,
142 # iterators drained and file slots collected in document order
143 inner = pending[inner_start:]
144 inner.append((EXIT_CONTAINER, ident))
145 inner.reverse()
146 pending[inner_start:] = inner
147
148 return root, file_slots
149
150
151 def copy_mapping(mapping: Any, visit_later: VisitLater, *, keep_omit: bool) -> dict[Any, object]:
152 """Copies the `Mapping` into a dict without its `NotGiven` / `Omit` entries.
153
154 Schedules a visit to the slots of the copy whose value may need preparing itself.
155 """
156 copied: dict[Any, object] = {}
157 for key, value in mapping.items():
158 if type(value) in PLAIN_TYPES:
159 copied[key] = value
160 elif not isinstance(value, (NotGiven, Omit)):
161 copied[key] = value
162 visit_later((copied, key))
163 elif keep_omit and isinstance(value, Omit):
164 # an `Omit` directly under the root tells `_merge_mappings` to drop this key from the
165 # mapping it merges the copy into, so it has to survive until then
166 copied[key] = value
167
168 return copied
169
170
171 def copy_items(items: Any, visit_later: VisitLater) -> list[object]:
172 """Copies the items into a list, scheduling a visit to the slots whose item may need preparing itself."""
173 copied = list(items)
174 for i, item in enumerate(copied):
175 if type(item) not in PLAIN_TYPES:
176 visit_later((copied, i))
177
178 return copied
179
180
181 def read_base64(file: Base64FileInput) -> str:
182 if isinstance(file, pathlib.Path):
183 return b64encode(file, file.read_bytes())
184
185 return b64encode(file, readable(file).read())
186
187
188 async def async_read_base64(file: Base64FileInput) -> str:
189 if isinstance(file, pathlib.Path):
190 return b64encode(file, await anyio.Path(file).read_bytes())
191
192 return b64encode(file, readable(file).read())
193
194
195 def readable(file: Base64FileInput) -> IO[bytes]:
196 """The file object to read; any other `os.PathLike` is rejected without touching the filesystem."""
197 if isinstance(file, os.PathLike):
198 raise TypeError(f"Cannot read {type(file)}; only pathlib.Path and file objects are read")
199
200 return file
201
202
203 def b64encode(file: Base64FileInput, content: object) -> str:
204 if isinstance(content, str):
205 content = content.encode()
206
207 if not isinstance(content, bytes):
208 raise RuntimeError(f"Could not read bytes from {file}; Received {type(content)}")
209
210 return base64.b64encode(content).decode("ascii")