goldprice-dev 0.1.0__tar.gz
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.
- goldprice_dev-0.1.0/CHANGELOG.md +8 -0
- goldprice_dev-0.1.0/LICENSE +21 -0
- goldprice_dev-0.1.0/PKG-INFO +90 -0
- goldprice_dev-0.1.0/README.md +65 -0
- goldprice_dev-0.1.0/hatch_build.py +14 -0
- goldprice_dev-0.1.0/pyproject.toml +40 -0
- goldprice_dev-0.1.0/src/goldprice_dev/__init__.py +16 -0
- goldprice_dev-0.1.0/src/goldprice_dev/_client.py +122 -0
- goldprice_dev-0.1.0/src/goldprice_dev/_deadline.py +180 -0
- goldprice_dev-0.1.0/src/goldprice_dev/_decode.py +67 -0
- goldprice_dev-0.1.0/src/goldprice_dev/_generated/__init__.py +2 -0
- goldprice_dev-0.1.0/src/goldprice_dev/_generated/models.py +526 -0
- goldprice_dev-0.1.0/src/goldprice_dev/_generated/operations.py +1112 -0
- goldprice_dev-0.1.0/src/goldprice_dev/_meta.py +40 -0
- goldprice_dev-0.1.0/src/goldprice_dev/_pagination.py +47 -0
- goldprice_dev-0.1.0/src/goldprice_dev/_transport.py +346 -0
- goldprice_dev-0.1.0/src/goldprice_dev/_version.py +1 -0
- goldprice_dev-0.1.0/src/goldprice_dev/errors.py +84 -0
- goldprice_dev-0.1.0/src/goldprice_dev/models.py +42 -0
- goldprice_dev-0.1.0/src/goldprice_dev/py.typed +0 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 — 2026-10-09
|
|
4
|
+
|
|
5
|
+
- Synchronous and asynchronous clients for precious metal prices.
|
|
6
|
+
- Spot prices, history, conversion, bars, ratios, and account usage.
|
|
7
|
+
- Exact decimals, typed errors, bounded retries, and response metadata.
|
|
8
|
+
- Bar and ratio pagination iterators, with page metadata exposed as `meta_`.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nusantara Ventures, LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: goldprice-dev
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Typed clients for the goldprice.dev API
|
|
5
|
+
Project-URL: Homepage, https://goldprice.dev/docs
|
|
6
|
+
Author-email: "Nusantara Ventures, LLC" <hello@goldprice.dev>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: api,commodities,decimal,gold,precious-metals,sdk,silver
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Requires-Dist: httpx<1,>=0.27
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# Goldprice for Python
|
|
27
|
+
|
|
28
|
+
Python clients for precious metal prices from goldprice.dev. Read spot prices,
|
|
29
|
+
price history, bars, ratios, and account usage. Conversion methods cover amounts
|
|
30
|
+
and carat values. The package provides synchronous and asynchronous access.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
Requires Python 3.10 or newer.
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
pip install goldprice-dev
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Quickstart
|
|
41
|
+
|
|
42
|
+
Set `GOLDPRICE_API_KEY` in your environment, then run:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from goldprice_dev import Goldprice
|
|
46
|
+
|
|
47
|
+
with Goldprice() as client:
|
|
48
|
+
spot = client.prices.spot("XAU-USD-SPOT")
|
|
49
|
+
print(spot.price)
|
|
50
|
+
print(spot.meta.request_id)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The context manager closes the client. `AsyncGoldprice` provides asynchronous
|
|
54
|
+
access. Supply `api_key=` to configure a key explicitly. The default base URL
|
|
55
|
+
is `https://api.goldprice.dev`; override it with `GOLDPRICE_BASE_URL`.
|
|
56
|
+
|
|
57
|
+
Use `prices.list()` for price listings and `prices.history(...)` for a symbol's
|
|
58
|
+
history. `bars.latest(symbol=...)` and `ratios.latest(pair=...)` return the latest
|
|
59
|
+
bar or ratio. `account.usage()` reads account usage. History queries accept
|
|
60
|
+
`from_` and `to` keyword arguments.
|
|
61
|
+
|
|
62
|
+
## Decimals
|
|
63
|
+
|
|
64
|
+
Prices and other decimal values use exact `decimal.Decimal` objects, never
|
|
65
|
+
floats. Pass conversion amounts as strings to preserve decimal input.
|
|
66
|
+
|
|
67
|
+
Every response carries `meta` with `request_id` and rate-limit values from
|
|
68
|
+
headers. Bar and ratio pages expose the wire field named `meta` as `meta_`.
|
|
69
|
+
Use `meta_` for page data and `meta` for response information.
|
|
70
|
+
|
|
71
|
+
## Errors and retries
|
|
72
|
+
|
|
73
|
+
`errors.Unauthorized`, `errors.RateLimited`, `errors.NotFound`, and
|
|
74
|
+
`errors.BadRequest` extend `errors.ApiError`. API errors expose `status`, `code`,
|
|
75
|
+
`detail`, and `request_id`. `errors.RateLimited` also carries `retry_after`.
|
|
76
|
+
All client errors derive from `errors.GoldpriceError`. Import `errors` from
|
|
77
|
+
`goldprice_dev` when handling these exceptions.
|
|
78
|
+
|
|
79
|
+
Requests retry up to twice by default for short-window rate limits and temporary
|
|
80
|
+
unavailability. Quota exhaustion is not retried.
|
|
81
|
+
|
|
82
|
+
## Pagination iterators
|
|
83
|
+
|
|
84
|
+
Use `bars.list_iter(...)` and `ratios.list_iter(...)` to consume items across
|
|
85
|
+
pages. Use `for` with `Goldprice` and `async for` with `AsyncGoldprice`.
|
|
86
|
+
The corresponding `list(...)` methods return a single page.
|
|
87
|
+
|
|
88
|
+
Links: [Documentation](https://goldprice.dev/docs)
|
|
89
|
+
|
|
90
|
+
MIT licensed
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Goldprice for Python
|
|
2
|
+
|
|
3
|
+
Python clients for precious metal prices from goldprice.dev. Read spot prices,
|
|
4
|
+
price history, bars, ratios, and account usage. Conversion methods cover amounts
|
|
5
|
+
and carat values. The package provides synchronous and asynchronous access.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Requires Python 3.10 or newer.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
pip install goldprice-dev
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Quickstart
|
|
16
|
+
|
|
17
|
+
Set `GOLDPRICE_API_KEY` in your environment, then run:
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from goldprice_dev import Goldprice
|
|
21
|
+
|
|
22
|
+
with Goldprice() as client:
|
|
23
|
+
spot = client.prices.spot("XAU-USD-SPOT")
|
|
24
|
+
print(spot.price)
|
|
25
|
+
print(spot.meta.request_id)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The context manager closes the client. `AsyncGoldprice` provides asynchronous
|
|
29
|
+
access. Supply `api_key=` to configure a key explicitly. The default base URL
|
|
30
|
+
is `https://api.goldprice.dev`; override it with `GOLDPRICE_BASE_URL`.
|
|
31
|
+
|
|
32
|
+
Use `prices.list()` for price listings and `prices.history(...)` for a symbol's
|
|
33
|
+
history. `bars.latest(symbol=...)` and `ratios.latest(pair=...)` return the latest
|
|
34
|
+
bar or ratio. `account.usage()` reads account usage. History queries accept
|
|
35
|
+
`from_` and `to` keyword arguments.
|
|
36
|
+
|
|
37
|
+
## Decimals
|
|
38
|
+
|
|
39
|
+
Prices and other decimal values use exact `decimal.Decimal` objects, never
|
|
40
|
+
floats. Pass conversion amounts as strings to preserve decimal input.
|
|
41
|
+
|
|
42
|
+
Every response carries `meta` with `request_id` and rate-limit values from
|
|
43
|
+
headers. Bar and ratio pages expose the wire field named `meta` as `meta_`.
|
|
44
|
+
Use `meta_` for page data and `meta` for response information.
|
|
45
|
+
|
|
46
|
+
## Errors and retries
|
|
47
|
+
|
|
48
|
+
`errors.Unauthorized`, `errors.RateLimited`, `errors.NotFound`, and
|
|
49
|
+
`errors.BadRequest` extend `errors.ApiError`. API errors expose `status`, `code`,
|
|
50
|
+
`detail`, and `request_id`. `errors.RateLimited` also carries `retry_after`.
|
|
51
|
+
All client errors derive from `errors.GoldpriceError`. Import `errors` from
|
|
52
|
+
`goldprice_dev` when handling these exceptions.
|
|
53
|
+
|
|
54
|
+
Requests retry up to twice by default for short-window rate limits and temporary
|
|
55
|
+
unavailability. Quota exhaustion is not retried.
|
|
56
|
+
|
|
57
|
+
## Pagination iterators
|
|
58
|
+
|
|
59
|
+
Use `bars.list_iter(...)` and `ratios.list_iter(...)` to consume items across
|
|
60
|
+
pages. Use `for` with `Goldprice` and `async for` with `AsyncGoldprice`.
|
|
61
|
+
The corresponding `list(...)` methods return a single page.
|
|
62
|
+
|
|
63
|
+
Links: [Documentation](https://goldprice.dev/docs)
|
|
64
|
+
|
|
65
|
+
MIT licensed
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Keep repository ignore files out of the source distribution."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class CustomBuildHook(BuildHookInterface):
|
|
9
|
+
def initialize(self, version, build_data):
|
|
10
|
+
if self.target_name == "sdist":
|
|
11
|
+
forced = build_data["force_include"]
|
|
12
|
+
for path in list(forced):
|
|
13
|
+
if Path(path).name in {".gitignore", ".hgignore"}:
|
|
14
|
+
del forced[path]
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "goldprice-dev"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Typed clients for the goldprice.dev API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
authors = [{ name = "Nusantara Ventures, LLC", email = "hello@goldprice.dev" }]
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
dependencies = ["httpx>=0.27,<1"]
|
|
15
|
+
keywords = ["api", "sdk", "gold", "silver", "precious-metals", "commodities", "decimal"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Topic :: Office/Business :: Financial",
|
|
20
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
21
|
+
"Typing :: Typed",
|
|
22
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
23
|
+
"Programming Language :: Python :: 3.10",
|
|
24
|
+
"Programming Language :: Python :: 3.11",
|
|
25
|
+
"Programming Language :: Python :: 3.12",
|
|
26
|
+
"Programming Language :: Python :: 3.13",
|
|
27
|
+
"Programming Language :: Python :: 3.14",
|
|
28
|
+
"License :: OSI Approved :: MIT License",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://goldprice.dev/docs"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/goldprice_dev"]
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.sdist]
|
|
38
|
+
include = ["src/goldprice_dev", "README.md", "CHANGELOG.md", "LICENSE", "pyproject.toml"]
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.hooks.custom]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Typed clients for the goldprice.dev API."""
|
|
2
|
+
|
|
3
|
+
from . import errors, models
|
|
4
|
+
from ._client import AsyncGoldprice, Goldprice
|
|
5
|
+
from ._meta import RateLimit, ResponseMeta
|
|
6
|
+
from ._version import __version__
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"AsyncGoldprice",
|
|
10
|
+
"Goldprice",
|
|
11
|
+
"RateLimit",
|
|
12
|
+
"ResponseMeta",
|
|
13
|
+
"__version__",
|
|
14
|
+
"errors",
|
|
15
|
+
"models",
|
|
16
|
+
]
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Connection-owning synchronous and asynchronous clients."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import random
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
7
|
+
from types import TracebackType
|
|
8
|
+
from typing import TypeVar
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from ._generated.operations import (
|
|
13
|
+
LIVE_SPEC_SHA,
|
|
14
|
+
AsyncStableOperations,
|
|
15
|
+
StableOperations,
|
|
16
|
+
)
|
|
17
|
+
from ._transport import AsyncTransport, Settings, SyncTransport
|
|
18
|
+
|
|
19
|
+
SyncClient = TypeVar("SyncClient", bound="Goldprice")
|
|
20
|
+
AsyncClient = TypeVar("AsyncClient", bound="AsyncGoldprice")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Goldprice(StableOperations):
|
|
24
|
+
"""Share one client across threads and close it when finished."""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
api_key: str | None = None,
|
|
29
|
+
*,
|
|
30
|
+
base_url: str | None = None,
|
|
31
|
+
proxy: str | None = None,
|
|
32
|
+
timeout: float = 30,
|
|
33
|
+
max_retries: int = 2,
|
|
34
|
+
max_retry_wait: float = 30,
|
|
35
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
36
|
+
transport: httpx.BaseTransport | None = None,
|
|
37
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
38
|
+
clock: Callable[[], float] = time.monotonic,
|
|
39
|
+
random_fraction: Callable[[], float] = random.random,
|
|
40
|
+
) -> None:
|
|
41
|
+
settings = Settings(
|
|
42
|
+
api_key=api_key,
|
|
43
|
+
base_url=base_url,
|
|
44
|
+
proxy=proxy,
|
|
45
|
+
timeout=timeout,
|
|
46
|
+
max_retries=max_retries,
|
|
47
|
+
max_retry_wait=max_retry_wait,
|
|
48
|
+
extra_headers=extra_headers,
|
|
49
|
+
clock=clock,
|
|
50
|
+
random_fraction=random_fraction,
|
|
51
|
+
spec_sha=LIVE_SPEC_SHA,
|
|
52
|
+
)
|
|
53
|
+
self._transport = SyncTransport(settings, transport=transport, sleep=sleep)
|
|
54
|
+
super().__init__(self._transport)
|
|
55
|
+
|
|
56
|
+
def __repr__(self) -> str:
|
|
57
|
+
return "Goldprice(api_key=<redacted>)"
|
|
58
|
+
|
|
59
|
+
def close(self) -> None:
|
|
60
|
+
self._transport.http.close()
|
|
61
|
+
|
|
62
|
+
def __enter__(self: SyncClient) -> SyncClient:
|
|
63
|
+
return self
|
|
64
|
+
|
|
65
|
+
def __exit__(
|
|
66
|
+
self,
|
|
67
|
+
exc_type: type[BaseException] | None,
|
|
68
|
+
exc: BaseException | None,
|
|
69
|
+
tb: TracebackType | None,
|
|
70
|
+
) -> None:
|
|
71
|
+
self.close()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class AsyncGoldprice(AsyncStableOperations):
|
|
75
|
+
"""Use one client per event loop and close it with async with."""
|
|
76
|
+
|
|
77
|
+
def __init__(
|
|
78
|
+
self,
|
|
79
|
+
api_key: str | None = None,
|
|
80
|
+
*,
|
|
81
|
+
base_url: str | None = None,
|
|
82
|
+
proxy: str | None = None,
|
|
83
|
+
timeout: float = 30,
|
|
84
|
+
max_retries: int = 2,
|
|
85
|
+
max_retry_wait: float = 30,
|
|
86
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
87
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
88
|
+
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
|
|
89
|
+
clock: Callable[[], float] = time.monotonic,
|
|
90
|
+
random_fraction: Callable[[], float] = random.random,
|
|
91
|
+
) -> None:
|
|
92
|
+
settings = Settings(
|
|
93
|
+
api_key=api_key,
|
|
94
|
+
base_url=base_url,
|
|
95
|
+
proxy=proxy,
|
|
96
|
+
timeout=timeout,
|
|
97
|
+
max_retries=max_retries,
|
|
98
|
+
max_retry_wait=max_retry_wait,
|
|
99
|
+
extra_headers=extra_headers,
|
|
100
|
+
clock=clock,
|
|
101
|
+
random_fraction=random_fraction,
|
|
102
|
+
spec_sha=LIVE_SPEC_SHA,
|
|
103
|
+
)
|
|
104
|
+
self._transport = AsyncTransport(settings, transport=transport, sleep=sleep)
|
|
105
|
+
super().__init__(self._transport)
|
|
106
|
+
|
|
107
|
+
def __repr__(self) -> str:
|
|
108
|
+
return "AsyncGoldprice(api_key=<redacted>)"
|
|
109
|
+
|
|
110
|
+
async def aclose(self) -> None:
|
|
111
|
+
await self._transport.http.aclose()
|
|
112
|
+
|
|
113
|
+
async def __aenter__(self: AsyncClient) -> AsyncClient:
|
|
114
|
+
return self
|
|
115
|
+
|
|
116
|
+
async def __aexit__(
|
|
117
|
+
self,
|
|
118
|
+
exc_type: type[BaseException] | None,
|
|
119
|
+
exc: BaseException | None,
|
|
120
|
+
tb: TracebackType | None,
|
|
121
|
+
) -> None:
|
|
122
|
+
await self.aclose()
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Per-attempt synchronous I/O deadlines, without threads or event loops."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Iterable
|
|
4
|
+
from contextvars import ContextVar
|
|
5
|
+
from ssl import SSLContext
|
|
6
|
+
from typing import Protocol, cast
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
RESPONSE_STARTED = "goldprice_dev.response_started"
|
|
11
|
+
SocketOption = tuple[int, int, int | bytes] | tuple[int, int, None, int]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Deadline:
|
|
15
|
+
def __init__(self, timeout: float, clock: Callable[[], float]) -> None:
|
|
16
|
+
self.clock = clock
|
|
17
|
+
self.expires = clock() + timeout
|
|
18
|
+
|
|
19
|
+
def remaining(self) -> float:
|
|
20
|
+
return max(0.0, self.expires - self.clock())
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
active_deadline: ContextVar[Deadline | None] = ContextVar(
|
|
24
|
+
"goldprice_dev_deadline", default=None
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def io_timeout(timeout: float | None) -> float | None:
|
|
29
|
+
deadline = active_deadline.get()
|
|
30
|
+
if deadline is None:
|
|
31
|
+
return timeout
|
|
32
|
+
remaining = deadline.remaining()
|
|
33
|
+
if remaining <= 0:
|
|
34
|
+
raise httpx.ReadTimeout("Attempt deadline exceeded")
|
|
35
|
+
return remaining if timeout is None else min(timeout, remaining)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class NetworkStream(Protocol):
|
|
39
|
+
def read(self, max_bytes: int, timeout: float | None = None) -> bytes: ...
|
|
40
|
+
def write(self, buffer: bytes, timeout: float | None = None) -> None: ...
|
|
41
|
+
def close(self) -> None: ...
|
|
42
|
+
def start_tls(
|
|
43
|
+
self,
|
|
44
|
+
ssl_context: SSLContext,
|
|
45
|
+
server_hostname: str | None = None,
|
|
46
|
+
timeout: float | None = None,
|
|
47
|
+
) -> "NetworkStream": ...
|
|
48
|
+
def get_extra_info(self, info: str) -> object: ...
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class NetworkBackend(Protocol):
|
|
52
|
+
def connect_tcp(
|
|
53
|
+
self,
|
|
54
|
+
host: str,
|
|
55
|
+
port: int,
|
|
56
|
+
timeout: float | None = None,
|
|
57
|
+
local_address: str | None = None,
|
|
58
|
+
socket_options: Iterable[SocketOption] | None = None,
|
|
59
|
+
) -> NetworkStream: ...
|
|
60
|
+
def connect_unix_socket(
|
|
61
|
+
self,
|
|
62
|
+
path: str,
|
|
63
|
+
timeout: float | None = None,
|
|
64
|
+
socket_options: Iterable[SocketOption] | None = None,
|
|
65
|
+
) -> NetworkStream: ...
|
|
66
|
+
def sleep(self, seconds: float) -> None: ...
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class _Stream:
|
|
70
|
+
def __init__(self, inner: NetworkStream) -> None:
|
|
71
|
+
self.inner = inner
|
|
72
|
+
|
|
73
|
+
def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
|
74
|
+
return self.inner.read(max_bytes, timeout=io_timeout(timeout))
|
|
75
|
+
|
|
76
|
+
def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
|
77
|
+
self.inner.write(buffer, timeout=io_timeout(timeout))
|
|
78
|
+
|
|
79
|
+
def close(self) -> None:
|
|
80
|
+
self.inner.close()
|
|
81
|
+
|
|
82
|
+
def start_tls(
|
|
83
|
+
self,
|
|
84
|
+
ssl_context: SSLContext,
|
|
85
|
+
server_hostname: str | None = None,
|
|
86
|
+
timeout: float | None = None,
|
|
87
|
+
) -> "_Stream":
|
|
88
|
+
return _Stream(
|
|
89
|
+
self.inner.start_tls(
|
|
90
|
+
ssl_context,
|
|
91
|
+
server_hostname=server_hostname,
|
|
92
|
+
timeout=io_timeout(timeout),
|
|
93
|
+
)
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
def get_extra_info(self, info: str) -> object:
|
|
97
|
+
return self.inner.get_extra_info(info)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class _Backend:
|
|
101
|
+
def __init__(self, inner: NetworkBackend) -> None:
|
|
102
|
+
self.inner = inner
|
|
103
|
+
|
|
104
|
+
def connect_tcp(
|
|
105
|
+
self,
|
|
106
|
+
host: str,
|
|
107
|
+
port: int,
|
|
108
|
+
timeout: float | None = None,
|
|
109
|
+
local_address: str | None = None,
|
|
110
|
+
socket_options: Iterable[SocketOption] | None = None,
|
|
111
|
+
) -> NetworkStream:
|
|
112
|
+
return _Stream(
|
|
113
|
+
self.inner.connect_tcp(
|
|
114
|
+
host,
|
|
115
|
+
port,
|
|
116
|
+
timeout=io_timeout(timeout),
|
|
117
|
+
local_address=local_address,
|
|
118
|
+
socket_options=socket_options,
|
|
119
|
+
)
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
def connect_unix_socket(
|
|
123
|
+
self,
|
|
124
|
+
path: str,
|
|
125
|
+
timeout: float | None = None,
|
|
126
|
+
socket_options: Iterable[SocketOption] | None = None,
|
|
127
|
+
) -> NetworkStream:
|
|
128
|
+
return _Stream(
|
|
129
|
+
self.inner.connect_unix_socket(
|
|
130
|
+
path, timeout=io_timeout(timeout), socket_options=socket_options
|
|
131
|
+
)
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def sleep(self, seconds: float) -> None:
|
|
135
|
+
self.inner.sleep(seconds)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class _Pool(Protocol):
|
|
139
|
+
_network_backend: NetworkBackend
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class _ClientTransports(Protocol):
|
|
143
|
+
_transport: httpx.BaseTransport
|
|
144
|
+
_mounts: dict[object, httpx.BaseTransport | None]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def install_deadlines(client: httpx.Client) -> None:
|
|
148
|
+
"""Adapt native pools, including environment and explicit proxy pools.
|
|
149
|
+
|
|
150
|
+
This is the sole boundary using transport internals. The underlying HTTP codec
|
|
151
|
+
caches the body timeout, so mutating the request timeout between chunks alone
|
|
152
|
+
does not bound slow responses. Native-codec tests verify this adapter against
|
|
153
|
+
the locked dependency. Injected transports can read request timeout extensions.
|
|
154
|
+
"""
|
|
155
|
+
transports = cast(_ClientTransports, client)
|
|
156
|
+
for transport in (transports._transport, *transports._mounts.values()):
|
|
157
|
+
if isinstance(transport, httpx.HTTPTransport):
|
|
158
|
+
pool = cast(_Pool, transport._pool)
|
|
159
|
+
if not isinstance(pool._network_backend, _Backend):
|
|
160
|
+
pool._network_backend = _Backend(pool._network_backend)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def read_response(
|
|
164
|
+
response: httpx.Response, request: httpx.Request, deadline: Deadline
|
|
165
|
+
) -> httpx.Response:
|
|
166
|
+
if response.is_stream_consumed:
|
|
167
|
+
return response
|
|
168
|
+
timeouts = cast(dict[str, float | None], request.extensions["timeout"])
|
|
169
|
+
chunks = []
|
|
170
|
+
for chunk in response.iter_raw():
|
|
171
|
+
chunks.append(chunk)
|
|
172
|
+
# Do not raise after a received chunk: it may be the last one. A next
|
|
173
|
+
# network read is where expiry becomes a transport failure.
|
|
174
|
+
timeouts["read"] = deadline.remaining()
|
|
175
|
+
return httpx.Response(
|
|
176
|
+
response.status_code,
|
|
177
|
+
headers=response.headers,
|
|
178
|
+
content=b"".join(chunks),
|
|
179
|
+
request=request,
|
|
180
|
+
)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Strict wire primitives used by generated decoders."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from decimal import Decimal
|
|
6
|
+
from typing import cast
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def read_object(value: object) -> dict[str, object]:
|
|
10
|
+
if not isinstance(value, dict) or any(not isinstance(k, str) for k in value):
|
|
11
|
+
raise ValueError("expected an object")
|
|
12
|
+
return cast(dict[str, object], value)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def read_list(value: object) -> list[object]:
|
|
16
|
+
if not isinstance(value, list):
|
|
17
|
+
raise TypeError("expected an array")
|
|
18
|
+
return cast(list[object], value)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def read_str(value: object) -> str:
|
|
22
|
+
if not isinstance(value, str):
|
|
23
|
+
raise TypeError("expected a string")
|
|
24
|
+
return value
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def read_int(value: object) -> int:
|
|
28
|
+
if type(value) is not int:
|
|
29
|
+
raise ValueError("expected an integer")
|
|
30
|
+
return value
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def read_bool(value: object) -> bool:
|
|
34
|
+
if not isinstance(value, bool):
|
|
35
|
+
raise TypeError("expected a boolean")
|
|
36
|
+
return value
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def read_decimal(value: object) -> Decimal:
|
|
40
|
+
text = read_str(value)
|
|
41
|
+
if re.fullmatch(r"-?\d+(\.\d+)?", text, re.ASCII) is None:
|
|
42
|
+
raise ValueError("expected a decimal wire string")
|
|
43
|
+
return Decimal(text)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def read_decimal_number(value: object) -> Decimal:
|
|
47
|
+
"""A decimal sent as a JSON number; `read_json` keeps its literal as a Decimal."""
|
|
48
|
+
if isinstance(value, bool) or not isinstance(value, (int, Decimal)):
|
|
49
|
+
raise TypeError("expected a JSON number")
|
|
50
|
+
if isinstance(value, Decimal) and not value.is_finite():
|
|
51
|
+
raise ValueError("expected a finite JSON number")
|
|
52
|
+
return Decimal(value)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def reject_number(value: str) -> object:
|
|
56
|
+
raise ValueError("unexpected non-finite JSON number")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def read_json(raw: bytes) -> object:
|
|
60
|
+
return json.loads(raw, parse_float=Decimal, parse_constant=reject_number)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def read_cursor(value: object) -> str:
|
|
64
|
+
cursor = read_str(value)
|
|
65
|
+
if not cursor:
|
|
66
|
+
raise ValueError("next_cursor must not be empty")
|
|
67
|
+
return cursor
|