vercel-internal-core-bundle 0.1.0__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.
@@ -0,0 +1 @@
1
+ """Shared internal runtime for Vercel-owned Python packages."""
@@ -0,0 +1 @@
1
+ """Generated vendored dependencies for vercel-internal-core-bundle."""
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,258 @@
1
+ """Adapt byte sources for business logic shared by sync and async APIs.
2
+
3
+ Shared code consumes the async-shaped ``ReadableByteStream`` and
4
+ ``StagingByteFile`` protocols. Callers select the runtime matching their public
5
+ API, then use its factories instead of constructing the private adapters directly.
6
+ The sync runtime never suspends, while the async runtime awaits or offloads I/O as
7
+ appropriate.
8
+ """
9
+
10
+ import inspect
11
+ import io
12
+ import sys
13
+ import tempfile
14
+ from collections.abc import AsyncIterator
15
+ from contextlib import AbstractAsyncContextManager, asynccontextmanager
16
+ from typing import Protocol, TypeAlias, cast
17
+
18
+ from vercel.internal._vendor import anyio
19
+
20
+ if sys.version_info >= (3, 12):
21
+ from collections.abc import Buffer
22
+ else:
23
+ from vercel.internal._vendor.typing_extensions import Buffer
24
+
25
+
26
+ class SyncByteReader(Protocol):
27
+ """Caller-provided byte source with a blocking ``read`` method."""
28
+
29
+ def read(self, size: int = -1, /) -> bytes: ...
30
+
31
+
32
+ class AsyncByteReader(Protocol):
33
+ """Caller-provided byte source with an asynchronous ``read`` method.
34
+
35
+ This is structurally identical to ``ReadableByteStream`` but describes an
36
+ input that has not yet been normalized by a byte-stream runtime.
37
+ """
38
+
39
+ async def read(self, size: int = -1, /) -> bytes: ...
40
+
41
+
42
+ BytesLike: TypeAlias = bytes | bytearray | memoryview
43
+ SyncByteSource: TypeAlias = BytesLike | SyncByteReader
44
+ AsyncByteSource: TypeAlias = AsyncByteReader
45
+ RawByteSource: TypeAlias = SyncByteSource | AsyncByteSource
46
+
47
+
48
+ class ReadableByteStream(Protocol):
49
+ """Normalized readable stream consumed by shared internal workflows.
50
+
51
+ Its async shape hides whether a runtime performs the read inline, awaits an
52
+ async source, or moves a blocking read to a worker thread.
53
+ """
54
+
55
+ async def read(self, size: int = -1, /) -> bytes: ...
56
+
57
+
58
+ class StagingByteFile(ReadableByteStream, Protocol):
59
+ """SDK-owned temporary byte file used by shared staging workflows.
60
+
61
+ The runtime's temporary-file context manager owns the lifetime of streams
62
+ implementing this protocol.
63
+ """
64
+
65
+ async def write(self, data: bytes, /) -> int: ...
66
+
67
+ async def readinto(self, buffer: Buffer, /) -> int:
68
+ """Read bytes into a writable buffer.
69
+
70
+ ``Buffer`` cannot express mutability, so read-only buffers are rejected
71
+ at runtime.
72
+ """
73
+ ...
74
+
75
+ async def flush(self) -> None: ...
76
+
77
+ async def tell(self) -> int: ...
78
+
79
+ async def seek(self, offset: int, whence: int = 0, /) -> int: ...
80
+
81
+ async def truncate(self, size: int | None = None, /) -> int: ...
82
+
83
+
84
+ class StagingFileRuntime(Protocol):
85
+ """Runtime-specific temporary-file capability for shared business logic."""
86
+
87
+ def temporary_file(self) -> AbstractAsyncContextManager[StagingByteFile]: ...
88
+
89
+
90
+ def _bytes_result(value: object) -> bytes:
91
+ if isinstance(value, bytes):
92
+ return value
93
+ raise TypeError(f"byte stream returned {type(value).__name__}, expected bytes")
94
+
95
+
96
+ class _SyncReader:
97
+ """Expose a blocking reader through an async-shaped, non-suspending method."""
98
+
99
+ def __init__(self, source: SyncByteReader) -> None:
100
+ self._source = source
101
+
102
+ async def read(self, size: int = -1, /) -> bytes:
103
+ return _bytes_result(self._source.read(size))
104
+
105
+
106
+ class _MemoryReader:
107
+ """Give an immutable bytes snapshot a stateful, non-suspending read cursor."""
108
+
109
+ def __init__(self, data: BytesLike) -> None:
110
+ self._data = memoryview(bytes(data))
111
+ self._offset = 0
112
+
113
+ async def read(self, size: int = -1, /) -> bytes:
114
+ remaining = self._data[self._offset :]
115
+ if size < 0:
116
+ self._offset = len(self._data)
117
+ return bytes(remaining)
118
+ chunk = bytes(remaining[:size])
119
+ self._offset += len(chunk)
120
+ return chunk
121
+
122
+
123
+ class _AsyncReader:
124
+ """Normalize a genuinely asynchronous reader and validate its results."""
125
+
126
+ def __init__(self, source: AsyncByteReader) -> None:
127
+ self._source = source
128
+
129
+ async def read(self, size: int = -1, /) -> bytes:
130
+ return _bytes_result(await self._source.read(size))
131
+
132
+
133
+ class _ThreadedSyncReader:
134
+ """Run a blocking reader on a worker thread for use by async workflows."""
135
+
136
+ def __init__(self, source: SyncByteReader) -> None:
137
+ self._source = source
138
+
139
+ async def read(self, size: int = -1, /) -> bytes:
140
+ return _bytes_result(await anyio.to_thread.run_sync(self._source.read, size))
141
+
142
+
143
+ class _SyncTemporaryFile:
144
+ """Expose a blocking temporary file through non-suspending async methods."""
145
+
146
+ def __init__(self) -> None:
147
+ self._file = cast(io.BufferedRandom, tempfile.TemporaryFile("w+b"))
148
+
149
+ def _ensure_open(self) -> None:
150
+ if self._file.closed:
151
+ raise anyio.ClosedResourceError
152
+
153
+ async def read(self, size: int = -1, /) -> bytes:
154
+ self._ensure_open()
155
+ return self._file.read(size)
156
+
157
+ async def write(self, data: bytes, /) -> int:
158
+ self._ensure_open()
159
+ return self._file.write(data)
160
+
161
+ async def readinto(self, buffer: Buffer, /) -> int:
162
+ """Read bytes into a writable buffer.
163
+
164
+ ``Buffer`` cannot express mutability, so read-only buffers are rejected
165
+ at runtime.
166
+ """
167
+ self._ensure_open()
168
+ return self._file.readinto(buffer)
169
+
170
+ async def flush(self) -> None:
171
+ self._ensure_open()
172
+ self._file.flush()
173
+
174
+ async def tell(self) -> int:
175
+ self._ensure_open()
176
+ return self._file.tell()
177
+
178
+ async def seek(self, offset: int, whence: int = 0, /) -> int:
179
+ self._ensure_open()
180
+ return self._file.seek(offset, whence)
181
+
182
+ async def truncate(self, size: int | None = None, /) -> int:
183
+ self._ensure_open()
184
+ return self._file.truncate(size)
185
+
186
+ def close(self) -> None:
187
+ self._file.close()
188
+
189
+
190
+ @asynccontextmanager
191
+ async def _sync_temporary_file() -> AsyncIterator[StagingByteFile]:
192
+ file = _SyncTemporaryFile()
193
+ try:
194
+ yield file
195
+ finally:
196
+ file.close()
197
+
198
+
199
+ class SyncByteStreamRuntime:
200
+ """Adapt blocking byte primitives for shared async-shaped workflows.
201
+
202
+ Every operation completes without suspending so sync entry points can drive
203
+ the shared coroutine with ``iter_coroutine`` and no event loop.
204
+ """
205
+
206
+ @staticmethod
207
+ def reader(source: SyncByteSource) -> ReadableByteStream:
208
+ if isinstance(source, (bytes, bytearray, memoryview)):
209
+ return _MemoryReader(source)
210
+ read = getattr(source, "read", None)
211
+ if not callable(read):
212
+ raise TypeError("byte source must provide a callable read method")
213
+ if inspect.iscoroutinefunction(read):
214
+ raise TypeError("sync byte stream runtime does not support async readers")
215
+ return _SyncReader(cast(SyncByteReader, source))
216
+
217
+ def temporary_file(self) -> AbstractAsyncContextManager[StagingByteFile]:
218
+ return _sync_temporary_file()
219
+
220
+
221
+ class AsyncByteStreamRuntime:
222
+ """Adapt byte primitives for execution under AnyIO.
223
+
224
+ Async readers are awaited directly, while blocking readers run on a worker
225
+ thread so they do not block the event loop.
226
+ """
227
+
228
+ @staticmethod
229
+ def reader(source: RawByteSource) -> ReadableByteStream:
230
+ if isinstance(source, (bytes, bytearray, memoryview)):
231
+ return _MemoryReader(source)
232
+ read = getattr(source, "read", None)
233
+ if not callable(read):
234
+ raise TypeError("byte source must provide a callable read method")
235
+ if inspect.iscoroutinefunction(read):
236
+ return _AsyncReader(cast(AsyncByteReader, source))
237
+ return _ThreadedSyncReader(cast(SyncByteReader, source))
238
+
239
+ def temporary_file(self) -> AbstractAsyncContextManager[StagingByteFile]:
240
+ return cast(
241
+ AbstractAsyncContextManager[StagingByteFile],
242
+ anyio.TemporaryFile("w+b"),
243
+ )
244
+
245
+
246
+ __all__ = [
247
+ "AsyncByteReader",
248
+ "AsyncByteSource",
249
+ "AsyncByteStreamRuntime",
250
+ "BytesLike",
251
+ "RawByteSource",
252
+ "ReadableByteStream",
253
+ "StagingByteFile",
254
+ "StagingFileRuntime",
255
+ "SyncByteReader",
256
+ "SyncByteSource",
257
+ "SyncByteStreamRuntime",
258
+ ]
@@ -0,0 +1,17 @@
1
+ """Shared errors for Vercel Python services."""
2
+
3
+
4
+ class VercelError(Exception):
5
+ """Base error for Vercel Python SDK failures."""
6
+
7
+
8
+ class VercelSessionError(VercelError):
9
+ """Base error for SDK session failures."""
10
+
11
+
12
+ class VercelSessionClosedError(VercelSessionError):
13
+ """Raised when code uses an SDK session after it has been closed."""
14
+
15
+
16
+ class VercelServiceOptionsError(VercelSessionError):
17
+ """Raised when SDK session service options are invalid."""
@@ -0,0 +1,46 @@
1
+ """Shared HTTP infrastructure for Vercel API clients."""
2
+
3
+ from vercel._internal.core.http.config import DEFAULT_API_BASE_URL, DEFAULT_TIMEOUT
4
+ from vercel._internal.core.http.httpx import (
5
+ create_base_async_client,
6
+ create_base_client,
7
+ )
8
+ from vercel._internal.core.http.retry import (
9
+ RetryPolicy,
10
+ SleepFn,
11
+ )
12
+ from vercel._internal.core.http.transport import (
13
+ AsyncTransport,
14
+ BaseTransport,
15
+ BytesBody,
16
+ JSONBody,
17
+ RawBody,
18
+ ReadResponsePolicy,
19
+ RequestBody,
20
+ StreamingRequest,
21
+ StreamingResponse,
22
+ SyncTransport,
23
+ TransportOptions,
24
+ extract_structured_error,
25
+ )
26
+
27
+ __all__ = [
28
+ "DEFAULT_API_BASE_URL",
29
+ "DEFAULT_TIMEOUT",
30
+ "BaseTransport",
31
+ "SyncTransport",
32
+ "AsyncTransport",
33
+ "TransportOptions",
34
+ "JSONBody",
35
+ "BytesBody",
36
+ "RawBody",
37
+ "ReadResponsePolicy",
38
+ "RequestBody",
39
+ "StreamingRequest",
40
+ "StreamingResponse",
41
+ "RetryPolicy",
42
+ "SleepFn",
43
+ "create_base_client",
44
+ "create_base_async_client",
45
+ "extract_structured_error",
46
+ ]
@@ -0,0 +1,9 @@
1
+ """HTTP configuration constants shared by Vercel API clients."""
2
+
3
+ from datetime import timedelta
4
+
5
+ DEFAULT_API_BASE_URL = "https://api.vercel.com"
6
+ DEFAULT_TIMEOUT = timedelta(seconds=60)
7
+
8
+
9
+ __all__ = ["DEFAULT_API_BASE_URL", "DEFAULT_TIMEOUT"]
@@ -0,0 +1,48 @@
1
+ """Client factory functions for creating pre-configured httpx clients."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TypedDict
6
+
7
+ from vercel.internal._vendor import httpx
8
+
9
+ from vercel._internal.core.http.transport import TransportOptions
10
+ from vercel._internal.core.time import to_seconds_float
11
+
12
+
13
+ def _normalize_base_url(base_url: str) -> str:
14
+ return base_url.rstrip("/") + "/"
15
+
16
+
17
+ class _HttpxClientKwargs(TypedDict, total=False):
18
+ timeout: httpx.Timeout
19
+ base_url: str
20
+ limits: httpx.Limits
21
+ http2: bool
22
+
23
+
24
+ def _options_to_httpx_kwargs(options: TransportOptions) -> _HttpxClientKwargs:
25
+ kwargs: _HttpxClientKwargs = {"timeout": httpx.Timeout(to_seconds_float(options.timeout))}
26
+ if options.base_url is not None:
27
+ kwargs["base_url"] = _normalize_base_url(options.base_url)
28
+ if options.max_connections is not None:
29
+ kwargs["limits"] = httpx.Limits(max_connections=options.max_connections)
30
+ if options.enable_http2 is not None:
31
+ kwargs["http2"] = options.enable_http2
32
+ return kwargs
33
+
34
+
35
+ def create_base_client(options: TransportOptions) -> httpx.Client:
36
+ """Create a sync httpx client without auth hooks."""
37
+ return httpx.Client(**_options_to_httpx_kwargs(options))
38
+
39
+
40
+ def create_base_async_client(options: TransportOptions) -> httpx.AsyncClient:
41
+ """Create an async httpx client without auth hooks."""
42
+ return httpx.AsyncClient(**_options_to_httpx_kwargs(options))
43
+
44
+
45
+ __all__ = [
46
+ "create_base_client",
47
+ "create_base_async_client",
48
+ ]
@@ -0,0 +1,20 @@
1
+ from collections.abc import Awaitable, Callable
2
+ from dataclasses import dataclass
3
+
4
+ from vercel.internal._vendor import httpx
5
+
6
+ SleepFn = Callable[[float], Awaitable[None] | None]
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class RetryPolicy:
11
+ """Configuration for automatic request retries."""
12
+
13
+ retries: int = 0
14
+ retry_on_network_error: bool = True
15
+ retry_on_response: Callable[[httpx.Response], bool] | None = None
16
+ backoff_base: float = 0.1
17
+ backoff_max: float = 2.0
18
+
19
+
20
+ __all__ = ["RetryPolicy", "SleepFn"]