discogs-sdk 0.4.0__tar.gz → 0.5.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.
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/PKG-INFO +57 -2
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/README.md +56 -1
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/pyproject.toml +1 -1
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/pyproject.toml.orig +1 -1
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/__init__.py +5 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/_client.py +82 -3
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_base_client.py +28 -1
- discogs_sdk-0.5.0/src/discogs_sdk/_events.py +71 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_exceptions.py +24 -1
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/_client.py +67 -4
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/LICENSE.txt +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/__init__.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/_lazy.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/_oauth.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/_paginator.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/_resource.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/resources/__init__.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/resources/artists.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/resources/collection.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/resources/exports.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/resources/labels.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/resources/lists.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/resources/marketplace.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/resources/masters.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/resources/releases.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/resources/search.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/resources/uploads.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/resources/users.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_async/resources/wantlist.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_cache.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_oauth_types.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/__init__.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/_lazy.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/_oauth.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/_paginator.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/_resource.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/resources/__init__.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/resources/artists.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/resources/collection.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/resources/exports.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/resources/labels.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/resources/lists.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/resources/marketplace.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/resources/masters.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/resources/releases.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/resources/search.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/resources/uploads.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/resources/users.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/_sync/resources/wantlist.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/__init__.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/_common.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/_lazy_fields.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/artist.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/collection.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/export.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/label.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/list_.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/marketplace.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/master.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/release.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/search.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/upload.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/user.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/models/wantlist.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/oauth.py +0 -0
- {discogs_sdk-0.4.0 → discogs_sdk-0.5.0}/src/discogs_sdk/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: discogs-sdk
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.0
|
|
4
4
|
Summary: Modern Python client for the Discogs API
|
|
5
5
|
Keywords: api,discogs,music,python,sdk
|
|
6
6
|
Author: Jean-Marc Fontaine
|
|
@@ -66,7 +66,7 @@ Requires Python 3.10+.
|
|
|
66
66
|
- **Fluent API** — Chain sub-resources naturally: `client.releases.get(id).rating.get()`
|
|
67
67
|
- **Lazy Loading** — No HTTP calls until you actually need the data
|
|
68
68
|
- **Effortless Pagination** — Browse results without managing pages or offsets
|
|
69
|
-
- **Rate Limit Aware** — Bounded retries with `Retry-After` support
|
|
69
|
+
- **Rate Limit Aware** — Bounded retries with `Retry-After` support, the live budget on `client.ratelimit`, and a structured event per request
|
|
70
70
|
- **Built-in Caching** — Optional TTL-based caching reduces API calls
|
|
71
71
|
- **Flexible Auth** — Supports personal tokens, consumer key/secret, or full OAuth 1.0a
|
|
72
72
|
- **Type Safe** — Get autocomplete and IDE support
|
|
@@ -263,6 +263,8 @@ except NotFoundError:
|
|
|
263
263
|
print("Not found")
|
|
264
264
|
except RateLimitError as exc:
|
|
265
265
|
print(f"Rate limited, retry after {exc.retry_after}s")
|
|
266
|
+
if exc.ratelimit: # the 429's own X-Discogs-Ratelimit* headers, when present
|
|
267
|
+
print(f"{exc.ratelimit.used}/{exc.ratelimit.limit} used this window")
|
|
266
268
|
except AuthenticationError:
|
|
267
269
|
print("Bad credentials")
|
|
268
270
|
```
|
|
@@ -272,6 +274,7 @@ The full exception hierarchy:
|
|
|
272
274
|
```
|
|
273
275
|
DiscogsError
|
|
274
276
|
├── DiscogsConnectionError
|
|
277
|
+
├── CacheMissError
|
|
275
278
|
└── DiscogsAPIError
|
|
276
279
|
├── AuthenticationError (401)
|
|
277
280
|
├── ForbiddenError (403)
|
|
@@ -306,6 +309,7 @@ The [`examples/`](examples/) directory has runnable scripts for every feature:
|
|
|
306
309
|
| `consumer_secret` | `None` | OAuth consumer secret |
|
|
307
310
|
| `http_client` | `None` | Custom `httpx2.Client` or `httpx2.AsyncClient` |
|
|
308
311
|
| `max_retries` | `3` | Max retries; reads retry on 429/5xx, network errors and timeouts, mutations only on pre-send failures |
|
|
312
|
+
| `on_request` | `None` | Callback receiving a `RequestEvent` per request |
|
|
309
313
|
| `timeout` | `30.0` | Request timeout in seconds |
|
|
310
314
|
| `token` | `None` | Personal access token |
|
|
311
315
|
|
|
@@ -326,6 +330,57 @@ with client.no_cache():
|
|
|
326
330
|
fresh = client.releases.get(352665).title # always hits the API
|
|
327
331
|
```
|
|
328
332
|
|
|
333
|
+
`client.cache_only()` is the mirror image: inside the scope a request the cache cannot serve — a miss, an expired
|
|
334
|
+
entry, a non-`GET`, a disabled cache or an enclosing `no_cache()` — raises `CacheMissError` before any network I/O.
|
|
335
|
+
It nests and restores exactly like `no_cache()`, so you can try everything for free first:
|
|
336
|
+
|
|
337
|
+
```python
|
|
338
|
+
from discogs_sdk import CacheMissError
|
|
339
|
+
|
|
340
|
+
with client.cache_only():
|
|
341
|
+
try:
|
|
342
|
+
title = client.releases.get(352665).title # never hits the API
|
|
343
|
+
except CacheMissError as exc:
|
|
344
|
+
print(f"Not cached: {exc.method} {exc.url}")
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
### Observability
|
|
348
|
+
|
|
349
|
+
Every live response carries Discogs' `X-Discogs-Ratelimit`, `X-Discogs-Ratelimit-Used` and
|
|
350
|
+
`X-Discogs-Ratelimit-Remaining` headers. `client.ratelimit` holds them as a `RateLimit(limit, used, remaining)`
|
|
351
|
+
parsed from the most recent **network** response: a cache hit never touches it, and a response without the headers
|
|
352
|
+
leaves the last known value in place. It is `None` until the first live response.
|
|
353
|
+
|
|
354
|
+
`on_request` receives one `RequestEvent` per logical request, invoked synchronously — after a cache hit, or after the
|
|
355
|
+
final network response and before any error is raised, so the event exists even when the call raises. Intermediate
|
|
356
|
+
retried attempts do not emit; the final event carries `attempts`. A call that ends in `DiscogsConnectionError` emits
|
|
357
|
+
nothing, since there is no response. Exceptions raised by the callback propagate unchanged; keep it cheap and never
|
|
358
|
+
block in it, because the async client calls it from the event loop.
|
|
359
|
+
|
|
360
|
+
| Field | Meaning |
|
|
361
|
+
|---|---|
|
|
362
|
+
| `method` | Upper-case HTTP method |
|
|
363
|
+
| `url` | Fully resolved URL, query string included |
|
|
364
|
+
| `status_code` | Status of the response that ended the call |
|
|
365
|
+
| `source` | `"network"` or `"cache"` |
|
|
366
|
+
| `elapsed_ms` | Final network attempt, or the cache lookup |
|
|
367
|
+
| `attempts` | Network attempts (`1` = no retry); `0` on a cache hit |
|
|
368
|
+
| `stored` | Whether this call wrote the response to the cache |
|
|
369
|
+
| `ratelimit` | `RateLimit` from the response; always `None` on a cache hit |
|
|
370
|
+
|
|
371
|
+
A minimal pacing loop:
|
|
372
|
+
|
|
373
|
+
```python
|
|
374
|
+
import time
|
|
375
|
+
|
|
376
|
+
client = Discogs(
|
|
377
|
+
token="...", on_request=lambda e: print(e.source, e.status_code, e.elapsed_ms)
|
|
378
|
+
)
|
|
379
|
+
title = client.releases.get(352665).title # lazy — the GET fires here
|
|
380
|
+
if client.ratelimit and client.ratelimit.remaining < 10:
|
|
381
|
+
time.sleep(60)
|
|
382
|
+
```
|
|
383
|
+
|
|
329
384
|
### Custom HTTP clients
|
|
330
385
|
|
|
331
386
|
An injected `http_client` must be an `httpx2` client — the SDK is built on [httpx2](https://github.com/pydantic/httpx2),
|
|
@@ -37,7 +37,7 @@ Requires Python 3.10+.
|
|
|
37
37
|
- **Fluent API** — Chain sub-resources naturally: `client.releases.get(id).rating.get()`
|
|
38
38
|
- **Lazy Loading** — No HTTP calls until you actually need the data
|
|
39
39
|
- **Effortless Pagination** — Browse results without managing pages or offsets
|
|
40
|
-
- **Rate Limit Aware** — Bounded retries with `Retry-After` support
|
|
40
|
+
- **Rate Limit Aware** — Bounded retries with `Retry-After` support, the live budget on `client.ratelimit`, and a structured event per request
|
|
41
41
|
- **Built-in Caching** — Optional TTL-based caching reduces API calls
|
|
42
42
|
- **Flexible Auth** — Supports personal tokens, consumer key/secret, or full OAuth 1.0a
|
|
43
43
|
- **Type Safe** — Get autocomplete and IDE support
|
|
@@ -234,6 +234,8 @@ except NotFoundError:
|
|
|
234
234
|
print("Not found")
|
|
235
235
|
except RateLimitError as exc:
|
|
236
236
|
print(f"Rate limited, retry after {exc.retry_after}s")
|
|
237
|
+
if exc.ratelimit: # the 429's own X-Discogs-Ratelimit* headers, when present
|
|
238
|
+
print(f"{exc.ratelimit.used}/{exc.ratelimit.limit} used this window")
|
|
237
239
|
except AuthenticationError:
|
|
238
240
|
print("Bad credentials")
|
|
239
241
|
```
|
|
@@ -243,6 +245,7 @@ The full exception hierarchy:
|
|
|
243
245
|
```
|
|
244
246
|
DiscogsError
|
|
245
247
|
├── DiscogsConnectionError
|
|
248
|
+
├── CacheMissError
|
|
246
249
|
└── DiscogsAPIError
|
|
247
250
|
├── AuthenticationError (401)
|
|
248
251
|
├── ForbiddenError (403)
|
|
@@ -277,6 +280,7 @@ The [`examples/`](examples/) directory has runnable scripts for every feature:
|
|
|
277
280
|
| `consumer_secret` | `None` | OAuth consumer secret |
|
|
278
281
|
| `http_client` | `None` | Custom `httpx2.Client` or `httpx2.AsyncClient` |
|
|
279
282
|
| `max_retries` | `3` | Max retries; reads retry on 429/5xx, network errors and timeouts, mutations only on pre-send failures |
|
|
283
|
+
| `on_request` | `None` | Callback receiving a `RequestEvent` per request |
|
|
280
284
|
| `timeout` | `30.0` | Request timeout in seconds |
|
|
281
285
|
| `token` | `None` | Personal access token |
|
|
282
286
|
|
|
@@ -297,6 +301,57 @@ with client.no_cache():
|
|
|
297
301
|
fresh = client.releases.get(352665).title # always hits the API
|
|
298
302
|
```
|
|
299
303
|
|
|
304
|
+
`client.cache_only()` is the mirror image: inside the scope a request the cache cannot serve — a miss, an expired
|
|
305
|
+
entry, a non-`GET`, a disabled cache or an enclosing `no_cache()` — raises `CacheMissError` before any network I/O.
|
|
306
|
+
It nests and restores exactly like `no_cache()`, so you can try everything for free first:
|
|
307
|
+
|
|
308
|
+
```python
|
|
309
|
+
from discogs_sdk import CacheMissError
|
|
310
|
+
|
|
311
|
+
with client.cache_only():
|
|
312
|
+
try:
|
|
313
|
+
title = client.releases.get(352665).title # never hits the API
|
|
314
|
+
except CacheMissError as exc:
|
|
315
|
+
print(f"Not cached: {exc.method} {exc.url}")
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
### Observability
|
|
319
|
+
|
|
320
|
+
Every live response carries Discogs' `X-Discogs-Ratelimit`, `X-Discogs-Ratelimit-Used` and
|
|
321
|
+
`X-Discogs-Ratelimit-Remaining` headers. `client.ratelimit` holds them as a `RateLimit(limit, used, remaining)`
|
|
322
|
+
parsed from the most recent **network** response: a cache hit never touches it, and a response without the headers
|
|
323
|
+
leaves the last known value in place. It is `None` until the first live response.
|
|
324
|
+
|
|
325
|
+
`on_request` receives one `RequestEvent` per logical request, invoked synchronously — after a cache hit, or after the
|
|
326
|
+
final network response and before any error is raised, so the event exists even when the call raises. Intermediate
|
|
327
|
+
retried attempts do not emit; the final event carries `attempts`. A call that ends in `DiscogsConnectionError` emits
|
|
328
|
+
nothing, since there is no response. Exceptions raised by the callback propagate unchanged; keep it cheap and never
|
|
329
|
+
block in it, because the async client calls it from the event loop.
|
|
330
|
+
|
|
331
|
+
| Field | Meaning |
|
|
332
|
+
|---|---|
|
|
333
|
+
| `method` | Upper-case HTTP method |
|
|
334
|
+
| `url` | Fully resolved URL, query string included |
|
|
335
|
+
| `status_code` | Status of the response that ended the call |
|
|
336
|
+
| `source` | `"network"` or `"cache"` |
|
|
337
|
+
| `elapsed_ms` | Final network attempt, or the cache lookup |
|
|
338
|
+
| `attempts` | Network attempts (`1` = no retry); `0` on a cache hit |
|
|
339
|
+
| `stored` | Whether this call wrote the response to the cache |
|
|
340
|
+
| `ratelimit` | `RateLimit` from the response; always `None` on a cache hit |
|
|
341
|
+
|
|
342
|
+
A minimal pacing loop:
|
|
343
|
+
|
|
344
|
+
```python
|
|
345
|
+
import time
|
|
346
|
+
|
|
347
|
+
client = Discogs(
|
|
348
|
+
token="...", on_request=lambda e: print(e.source, e.status_code, e.elapsed_ms)
|
|
349
|
+
)
|
|
350
|
+
title = client.releases.get(352665).title # lazy — the GET fires here
|
|
351
|
+
if client.ratelimit and client.ratelimit.remaining < 10:
|
|
352
|
+
time.sleep(60)
|
|
353
|
+
```
|
|
354
|
+
|
|
300
355
|
### Custom HTTP clients
|
|
301
356
|
|
|
302
357
|
An injected `http_client` must be an `httpx2` client — the SDK is built on [httpx2](https://github.com/pydantic/httpx2),
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
from discogs_sdk._async._client import AsyncDiscogs
|
|
2
2
|
from discogs_sdk._async._paginator import AsyncPage
|
|
3
3
|
from discogs_sdk._base_client import MediaType
|
|
4
|
+
from discogs_sdk._events import RateLimit, RequestEvent
|
|
4
5
|
from discogs_sdk._exceptions import (
|
|
5
6
|
AuthenticationError,
|
|
7
|
+
CacheMissError,
|
|
6
8
|
DiscogsAPIError,
|
|
7
9
|
DiscogsConnectionError,
|
|
8
10
|
DiscogsError,
|
|
@@ -88,8 +90,11 @@ __all__ = [
|
|
|
88
90
|
"SyncPage",
|
|
89
91
|
# Client config
|
|
90
92
|
"MediaType",
|
|
93
|
+
"RateLimit",
|
|
94
|
+
"RequestEvent",
|
|
91
95
|
# Exceptions
|
|
92
96
|
"DiscogsError",
|
|
97
|
+
"CacheMissError",
|
|
93
98
|
"DiscogsConnectionError",
|
|
94
99
|
"DiscogsAPIError",
|
|
95
100
|
"AuthenticationError",
|
|
@@ -10,6 +10,7 @@ if True: # ASYNC
|
|
|
10
10
|
else:
|
|
11
11
|
from collections.abc import Generator
|
|
12
12
|
from contextlib import contextmanager
|
|
13
|
+
from collections.abc import Callable
|
|
13
14
|
from contextvars import ContextVar
|
|
14
15
|
from functools import cached_property
|
|
15
16
|
from pathlib import Path
|
|
@@ -38,7 +39,8 @@ from discogs_sdk._base_client import (
|
|
|
38
39
|
may_retry_transport_error,
|
|
39
40
|
)
|
|
40
41
|
from discogs_sdk._cache import MemoryCache, ResponseCache, SQLiteCache
|
|
41
|
-
from discogs_sdk.
|
|
42
|
+
from discogs_sdk._events import RateLimit, RequestEvent
|
|
43
|
+
from discogs_sdk._exceptions import CacheMissError, DiscogsConnectionError
|
|
42
44
|
|
|
43
45
|
if TYPE_CHECKING:
|
|
44
46
|
from discogs_sdk._async._paginator import AsyncPage
|
|
@@ -51,6 +53,10 @@ logger = logging.getLogger("discogs_sdk")
|
|
|
51
53
|
_CACHE_BYPASS: ContextVar[frozenset[int]] = ContextVar(
|
|
52
54
|
"discogs_sdk_cache_bypass", default=frozenset()
|
|
53
55
|
)
|
|
56
|
+
# Clients restricted to the cache in the current execution context; same shape.
|
|
57
|
+
_CACHE_ONLY: ContextVar[frozenset[int]] = ContextVar(
|
|
58
|
+
"discogs_sdk_cache_only", default=frozenset()
|
|
59
|
+
)
|
|
54
60
|
_CACHEABLE_METHODS = frozenset({"GET", "HEAD"})
|
|
55
61
|
|
|
56
62
|
|
|
@@ -81,6 +87,7 @@ class AsyncDiscogs(BaseClient):
|
|
|
81
87
|
http_client: httpx2.AsyncClient | None = None,
|
|
82
88
|
user_agent: str | None = None,
|
|
83
89
|
media_type: MediaType = "discogs",
|
|
90
|
+
on_request: Callable[[RequestEvent], None] | None = None,
|
|
84
91
|
) -> None:
|
|
85
92
|
"""Create an async Discogs client.
|
|
86
93
|
|
|
@@ -123,6 +130,11 @@ class AsyncDiscogs(BaseClient):
|
|
|
123
130
|
compatibility with Discogs.
|
|
124
131
|
media_type: Response text format. ``"discogs"`` returns Discogs markup,
|
|
125
132
|
``"html"`` returns HTML, ``"plaintext"`` returns plain text.
|
|
133
|
+
on_request: Called once per request with a ``RequestEvent``: after a
|
|
134
|
+
cache hit, or after the final network response before any error
|
|
135
|
+
is raised. Invoked synchronously from the calling task, so keep
|
|
136
|
+
it cheap and never block in it. Exceptions it raises propagate
|
|
137
|
+
unchanged.
|
|
126
138
|
"""
|
|
127
139
|
super().__init__(
|
|
128
140
|
token=token,
|
|
@@ -135,6 +147,7 @@ class AsyncDiscogs(BaseClient):
|
|
|
135
147
|
max_retries=max_retries,
|
|
136
148
|
user_agent=user_agent,
|
|
137
149
|
media_type=media_type,
|
|
150
|
+
on_request=on_request,
|
|
138
151
|
)
|
|
139
152
|
if http_client is not None:
|
|
140
153
|
# An injected client owns its transport and lifecycle. SDK headers are
|
|
@@ -195,20 +208,40 @@ class AsyncDiscogs(BaseClient):
|
|
|
195
208
|
# cannot identify, so its responses must not be shared across clients.
|
|
196
209
|
and (self._owns_client or self._auth_mode != "none")
|
|
197
210
|
)
|
|
211
|
+
cache_only = id(self) in _CACHE_ONLY.get()
|
|
198
212
|
cache_key = ""
|
|
199
|
-
if use_cache:
|
|
213
|
+
if use_cache or cache_only:
|
|
200
214
|
# httpx2 merges params into the URL, so build the request first to key
|
|
201
215
|
# on the fully resolved URL.
|
|
202
216
|
req = self._http_client.build_request(method, url, **build_kwargs)
|
|
217
|
+
if use_cache:
|
|
203
218
|
cache_key = self._build_cache_key(method, str(req.url), headers["Accept"])
|
|
204
219
|
|
|
220
|
+
t0 = time.monotonic()
|
|
205
221
|
cached = self._cache.get(cache_key) # type: ignore[union-attr]
|
|
222
|
+
lookup_ms = (time.monotonic() - t0) * 1000
|
|
206
223
|
if cached is not None:
|
|
207
224
|
status, cached_headers, body = cached
|
|
208
225
|
logger.debug("Cache hit: %s %s", method, url)
|
|
209
|
-
|
|
226
|
+
response = httpx2.Response(
|
|
210
227
|
status_code=status, headers=cached_headers, content=body
|
|
211
228
|
)
|
|
229
|
+
self._observe(
|
|
230
|
+
RequestEvent(
|
|
231
|
+
method=method.upper(),
|
|
232
|
+
url=str(req.url),
|
|
233
|
+
status_code=status,
|
|
234
|
+
source="cache",
|
|
235
|
+
elapsed_ms=lookup_ms,
|
|
236
|
+
attempts=0,
|
|
237
|
+
stored=False,
|
|
238
|
+
ratelimit=None,
|
|
239
|
+
)
|
|
240
|
+
)
|
|
241
|
+
return response
|
|
242
|
+
if cache_only:
|
|
243
|
+
# Nothing below this line may run: the scope forbids network I/O.
|
|
244
|
+
raise CacheMissError(method.upper(), str(req.url))
|
|
212
245
|
|
|
213
246
|
for attempt in range(self.max_retries + 1):
|
|
214
247
|
logger.debug("HTTP request: %s %s", method, url)
|
|
@@ -254,6 +287,7 @@ class AsyncDiscogs(BaseClient):
|
|
|
254
287
|
not may_retry_status(method, response.status_code)
|
|
255
288
|
or attempt == self.max_retries
|
|
256
289
|
):
|
|
290
|
+
stored = False
|
|
257
291
|
if use_cache and 200 <= response.status_code < 300:
|
|
258
292
|
assert self._cache is not None # narrowed by use_cache
|
|
259
293
|
# response.content is already decompressed by httpx2, so strip
|
|
@@ -274,6 +308,21 @@ class AsyncDiscogs(BaseClient):
|
|
|
274
308
|
cache_headers,
|
|
275
309
|
response.content,
|
|
276
310
|
)
|
|
311
|
+
stored = True
|
|
312
|
+
# Emitted before the error boundary so the event exists even when
|
|
313
|
+
# the call raises.
|
|
314
|
+
self._observe(
|
|
315
|
+
RequestEvent(
|
|
316
|
+
method=method.upper(),
|
|
317
|
+
url=str(response.request.url),
|
|
318
|
+
status_code=response.status_code,
|
|
319
|
+
source="network",
|
|
320
|
+
elapsed_ms=elapsed_ms,
|
|
321
|
+
attempts=attempt + 1,
|
|
322
|
+
stored=stored,
|
|
323
|
+
ratelimit=RateLimit.from_headers(response.headers),
|
|
324
|
+
)
|
|
325
|
+
)
|
|
277
326
|
# The retry policy is done deciding: this is the final response,
|
|
278
327
|
# so map failures here, before any endpoint parses the body.
|
|
279
328
|
self._raise_for_response(response)
|
|
@@ -315,6 +364,21 @@ class AsyncDiscogs(BaseClient):
|
|
|
315
364
|
yield self
|
|
316
365
|
finally:
|
|
317
366
|
_CACHE_BYPASS.reset(token)
|
|
367
|
+
|
|
368
|
+
@asynccontextmanager
|
|
369
|
+
async def cache_only(self) -> AsyncGenerator[Self, None]:
|
|
370
|
+
"""Serve only from the response cache for the current execution context.
|
|
371
|
+
|
|
372
|
+
A request the cache cannot serve - a miss, an expired entry, a non-GET,
|
|
373
|
+
a disabled cache or an enclosing ``no_cache()`` - raises
|
|
374
|
+
``CacheMissError`` before any network I/O. Scopes nest and restore
|
|
375
|
+
exactly like ``no_cache()``.
|
|
376
|
+
"""
|
|
377
|
+
token = _CACHE_ONLY.set(_CACHE_ONLY.get() | {id(self)})
|
|
378
|
+
try:
|
|
379
|
+
yield self
|
|
380
|
+
finally:
|
|
381
|
+
_CACHE_ONLY.reset(token)
|
|
318
382
|
else:
|
|
319
383
|
|
|
320
384
|
@contextmanager
|
|
@@ -331,6 +395,21 @@ class AsyncDiscogs(BaseClient):
|
|
|
331
395
|
finally:
|
|
332
396
|
_CACHE_BYPASS.reset(token)
|
|
333
397
|
|
|
398
|
+
@contextmanager
|
|
399
|
+
def cache_only(self) -> Generator[Self, None, None]:
|
|
400
|
+
"""Serve only from the response cache for the current execution context.
|
|
401
|
+
|
|
402
|
+
A request the cache cannot serve - a miss, an expired entry, a non-GET,
|
|
403
|
+
a disabled cache or an enclosing ``no_cache()`` - raises
|
|
404
|
+
``CacheMissError`` before any network I/O. Scopes nest and restore
|
|
405
|
+
exactly like ``no_cache()``.
|
|
406
|
+
"""
|
|
407
|
+
token = _CACHE_ONLY.set(_CACHE_ONLY.get() | {id(self)})
|
|
408
|
+
try:
|
|
409
|
+
yield self
|
|
410
|
+
finally:
|
|
411
|
+
_CACHE_ONLY.reset(token)
|
|
412
|
+
|
|
334
413
|
def clear_cache(self) -> None:
|
|
335
414
|
"""Purge all cached responses. No-op when caching is disabled."""
|
|
336
415
|
if self._cache is not None:
|
|
@@ -8,10 +8,12 @@ import os
|
|
|
8
8
|
import random
|
|
9
9
|
import time
|
|
10
10
|
import urllib.parse
|
|
11
|
+
from collections.abc import Callable
|
|
11
12
|
from typing import Any, Literal, NoReturn
|
|
12
13
|
|
|
13
14
|
import httpx2
|
|
14
15
|
|
|
16
|
+
from discogs_sdk._events import RateLimit, RequestEvent
|
|
15
17
|
from discogs_sdk._exceptions import (
|
|
16
18
|
AuthenticationError,
|
|
17
19
|
DiscogsAPIError,
|
|
@@ -145,12 +147,15 @@ class BaseClient:
|
|
|
145
147
|
max_retries: int = 3,
|
|
146
148
|
user_agent: str | None = None,
|
|
147
149
|
media_type: MediaType = "discogs",
|
|
150
|
+
on_request: Callable[[RequestEvent], None] | None = None,
|
|
148
151
|
) -> None:
|
|
149
152
|
self.base_url: str = base_url.rstrip("/")
|
|
150
153
|
self.timeout: float = timeout
|
|
151
154
|
self.max_retries: int = max_retries
|
|
152
155
|
self._user_agent: str = user_agent if user_agent else USER_AGENT
|
|
153
156
|
self._media_type: MediaType = media_type
|
|
157
|
+
self._on_request = on_request
|
|
158
|
+
self._ratelimit: RateLimit | None = None
|
|
154
159
|
|
|
155
160
|
self._auth_mode: AuthMode = self._select_auth_mode(
|
|
156
161
|
token=token,
|
|
@@ -162,6 +167,23 @@ class BaseClient:
|
|
|
162
167
|
logger.debug("Auth: %s", _AUTH_MODE_LABELS[self._auth_mode])
|
|
163
168
|
self._auth_namespace: str = self._build_auth_namespace()
|
|
164
169
|
|
|
170
|
+
@property
|
|
171
|
+
def ratelimit(self) -> RateLimit | None:
|
|
172
|
+
"""Rate limit reported by the most recent live response, or ``None``.
|
|
173
|
+
|
|
174
|
+
Only network responses carrying all three ``X-Discogs-Ratelimit*`` headers
|
|
175
|
+
update it; cache hits and responses without the headers leave the last
|
|
176
|
+
known value in place.
|
|
177
|
+
"""
|
|
178
|
+
return self._ratelimit
|
|
179
|
+
|
|
180
|
+
def _observe(self, event: RequestEvent) -> None:
|
|
181
|
+
"""Record *event*'s rate limit and hand it to the ``on_request`` callback."""
|
|
182
|
+
if event.ratelimit is not None:
|
|
183
|
+
self._ratelimit = event.ratelimit
|
|
184
|
+
if self._on_request is not None:
|
|
185
|
+
self._on_request(event)
|
|
186
|
+
|
|
165
187
|
def _build_auth_namespace(self) -> str:
|
|
166
188
|
"""Stable, non-reversible identity for cache partitioning.
|
|
167
189
|
|
|
@@ -335,7 +357,10 @@ class BaseClient:
|
|
|
335
357
|
body = decoded if isinstance(decoded, dict) else response.text
|
|
336
358
|
|
|
337
359
|
self._maybe_raise(
|
|
338
|
-
response.status_code,
|
|
360
|
+
response.status_code,
|
|
361
|
+
body,
|
|
362
|
+
retry_after=response.headers.get("Retry-After"),
|
|
363
|
+
ratelimit=RateLimit.from_headers(response.headers),
|
|
339
364
|
)
|
|
340
365
|
|
|
341
366
|
def _maybe_raise(
|
|
@@ -344,6 +369,7 @@ class BaseClient:
|
|
|
344
369
|
body: dict[str, Any] | str,
|
|
345
370
|
*,
|
|
346
371
|
retry_after: str | None = None,
|
|
372
|
+
ratelimit: RateLimit | None = None,
|
|
347
373
|
) -> None:
|
|
348
374
|
if status_code < 400:
|
|
349
375
|
return
|
|
@@ -366,6 +392,7 @@ class BaseClient:
|
|
|
366
392
|
status_code=429,
|
|
367
393
|
response_body=body,
|
|
368
394
|
retry_after=retry_after,
|
|
395
|
+
ratelimit=ratelimit,
|
|
369
396
|
)
|
|
370
397
|
case _:
|
|
371
398
|
error_cls = DiscogsAPIError
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Structured request observability: rate-limit headers and per-request events.
|
|
2
|
+
|
|
3
|
+
Stdlib-only so ``_exceptions`` can import it without a cycle.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Literal
|
|
11
|
+
|
|
12
|
+
_LIMIT = "x-discogs-ratelimit"
|
|
13
|
+
_USED = "x-discogs-ratelimit-used"
|
|
14
|
+
_REMAINING = "x-discogs-ratelimit-remaining"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True, slots=True)
|
|
18
|
+
class RateLimit:
|
|
19
|
+
"""Discogs rate-limit headers from one live response.
|
|
20
|
+
|
|
21
|
+
Attributes:
|
|
22
|
+
limit: Requests allowed per window (``X-Discogs-Ratelimit``).
|
|
23
|
+
used: Requests made in the current window (``X-Discogs-Ratelimit-Used``).
|
|
24
|
+
remaining: Requests left in the current window
|
|
25
|
+
(``X-Discogs-Ratelimit-Remaining``).
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
limit: int
|
|
29
|
+
used: int
|
|
30
|
+
remaining: int
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def from_headers(cls, headers: Mapping[str, str]) -> RateLimit | None:
|
|
34
|
+
"""Parse the three headers; ``None`` unless all are present and integers.
|
|
35
|
+
|
|
36
|
+
Header names are matched case-insensitively.
|
|
37
|
+
"""
|
|
38
|
+
lowered = {k.lower(): v for k, v in headers.items()}
|
|
39
|
+
try:
|
|
40
|
+
return cls(
|
|
41
|
+
int(lowered[_LIMIT]), int(lowered[_USED]), int(lowered[_REMAINING])
|
|
42
|
+
)
|
|
43
|
+
except (KeyError, ValueError):
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True)
|
|
48
|
+
class RequestEvent:
|
|
49
|
+
"""One logical request as seen by the client; emitted once per call.
|
|
50
|
+
|
|
51
|
+
Attributes:
|
|
52
|
+
method: Upper-case HTTP method.
|
|
53
|
+
url: Fully resolved request URL, query string included.
|
|
54
|
+
status_code: HTTP status of the response that ended the call.
|
|
55
|
+
source: ``"network"`` for a live response, ``"cache"`` for a cache hit.
|
|
56
|
+
elapsed_ms: Duration of the final network attempt, or of the cache lookup.
|
|
57
|
+
attempts: Network attempts made (``1`` means no retry); ``0`` on a cache
|
|
58
|
+
hit.
|
|
59
|
+
stored: Whether this call wrote the response to the cache.
|
|
60
|
+
ratelimit: Rate limit reported by the response; always ``None`` for a
|
|
61
|
+
cache hit.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
method: str
|
|
65
|
+
url: str
|
|
66
|
+
status_code: int
|
|
67
|
+
source: Literal["network", "cache"]
|
|
68
|
+
elapsed_ms: float
|
|
69
|
+
attempts: int
|
|
70
|
+
stored: bool
|
|
71
|
+
ratelimit: RateLimit | None
|
|
@@ -2,6 +2,8 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
from typing import Any
|
|
4
4
|
|
|
5
|
+
from discogs_sdk._events import RateLimit
|
|
6
|
+
|
|
5
7
|
|
|
6
8
|
class DiscogsError(Exception):
|
|
7
9
|
"""Base exception for all Discogs SDK errors."""
|
|
@@ -11,6 +13,20 @@ class DiscogsConnectionError(DiscogsError):
|
|
|
11
13
|
"""Network-level errors (DNS, timeout, connection refused)."""
|
|
12
14
|
|
|
13
15
|
|
|
16
|
+
class CacheMissError(DiscogsError):
|
|
17
|
+
"""Raised inside ``cache_only()`` when a request cannot be served from cache.
|
|
18
|
+
|
|
19
|
+
Attributes:
|
|
20
|
+
method: Upper-case HTTP method of the request.
|
|
21
|
+
url: Fully resolved request URL.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, method: str, url: str) -> None:
|
|
25
|
+
super().__init__(f"Not cached: {method} {url}")
|
|
26
|
+
self.method = method
|
|
27
|
+
self.url = url
|
|
28
|
+
|
|
29
|
+
|
|
14
30
|
class DiscogsAPIError(DiscogsError):
|
|
15
31
|
"""HTTP error returned by the Discogs API."""
|
|
16
32
|
|
|
@@ -42,7 +58,12 @@ class NotFoundError(DiscogsAPIError):
|
|
|
42
58
|
|
|
43
59
|
|
|
44
60
|
class RateLimitError(DiscogsAPIError):
|
|
45
|
-
"""429 Too Many Requests.
|
|
61
|
+
"""429 Too Many Requests.
|
|
62
|
+
|
|
63
|
+
Attributes:
|
|
64
|
+
retry_after: Raw ``Retry-After`` header value, when present.
|
|
65
|
+
ratelimit: Rate-limit headers carried by the 429 itself, when present.
|
|
66
|
+
"""
|
|
46
67
|
|
|
47
68
|
def __init__(
|
|
48
69
|
self,
|
|
@@ -51,9 +72,11 @@ class RateLimitError(DiscogsAPIError):
|
|
|
51
72
|
status_code: int,
|
|
52
73
|
response_body: dict[str, Any] | str,
|
|
53
74
|
retry_after: str | None = None,
|
|
75
|
+
ratelimit: RateLimit | None = None,
|
|
54
76
|
) -> None:
|
|
55
77
|
super().__init__(message, status_code=status_code, response_body=response_body)
|
|
56
78
|
self.retry_after = retry_after
|
|
79
|
+
self.ratelimit = ratelimit
|
|
57
80
|
|
|
58
81
|
|
|
59
82
|
class ValidationError(DiscogsAPIError):
|
|
@@ -5,7 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
|
|
6
6
|
import logging
|
|
7
7
|
import time
|
|
8
|
-
from collections.abc import Generator
|
|
8
|
+
from collections.abc import Callable, Generator
|
|
9
9
|
from contextlib import contextmanager
|
|
10
10
|
from contextvars import ContextVar
|
|
11
11
|
from functools import cached_property
|
|
@@ -25,7 +25,8 @@ from discogs_sdk._base_client import (
|
|
|
25
25
|
may_retry_transport_error,
|
|
26
26
|
)
|
|
27
27
|
from discogs_sdk._cache import MemoryCache, ResponseCache, SQLiteCache
|
|
28
|
-
from discogs_sdk.
|
|
28
|
+
from discogs_sdk._events import RateLimit, RequestEvent
|
|
29
|
+
from discogs_sdk._exceptions import CacheMissError, DiscogsConnectionError
|
|
29
30
|
from discogs_sdk._sync.resources.artists import Artists
|
|
30
31
|
from discogs_sdk._sync.resources.exports import Exports
|
|
31
32
|
from discogs_sdk._sync.resources.labels import Labels
|
|
@@ -46,6 +47,10 @@ logger = logging.getLogger("discogs_sdk")
|
|
|
46
47
|
_CACHE_BYPASS: ContextVar[frozenset[int]] = ContextVar(
|
|
47
48
|
"discogs_sdk_cache_bypass", default=frozenset()
|
|
48
49
|
)
|
|
50
|
+
# Clients restricted to the cache in the current execution context; same shape.
|
|
51
|
+
_CACHE_ONLY: ContextVar[frozenset[int]] = ContextVar(
|
|
52
|
+
"discogs_sdk_cache_only", default=frozenset()
|
|
53
|
+
)
|
|
49
54
|
_CACHEABLE_METHODS = frozenset({"GET", "HEAD"})
|
|
50
55
|
|
|
51
56
|
|
|
@@ -76,6 +81,7 @@ class Discogs(BaseClient):
|
|
|
76
81
|
http_client: httpx2.Client | None = None,
|
|
77
82
|
user_agent: str | None = None,
|
|
78
83
|
media_type: MediaType = "discogs",
|
|
84
|
+
on_request: Callable[[RequestEvent], None] | None = None,
|
|
79
85
|
) -> None:
|
|
80
86
|
"""Create an async Discogs client.
|
|
81
87
|
|
|
@@ -118,6 +124,11 @@ class Discogs(BaseClient):
|
|
|
118
124
|
compatibility with Discogs.
|
|
119
125
|
media_type: Response text format. ``"discogs"`` returns Discogs markup,
|
|
120
126
|
``"html"`` returns HTML, ``"plaintext"`` returns plain text.
|
|
127
|
+
on_request: Called once per request with a ``RequestEvent``: after a
|
|
128
|
+
cache hit, or after the final network response before any error
|
|
129
|
+
is raised. Invoked synchronously from the calling task, so keep
|
|
130
|
+
it cheap and never block in it. Exceptions it raises propagate
|
|
131
|
+
unchanged.
|
|
121
132
|
"""
|
|
122
133
|
super().__init__(
|
|
123
134
|
token=token,
|
|
@@ -130,6 +141,7 @@ class Discogs(BaseClient):
|
|
|
130
141
|
max_retries=max_retries,
|
|
131
142
|
user_agent=user_agent,
|
|
132
143
|
media_type=media_type,
|
|
144
|
+
on_request=on_request,
|
|
133
145
|
)
|
|
134
146
|
if http_client is not None:
|
|
135
147
|
# An injected client owns its transport and lifecycle. SDK headers are
|
|
@@ -186,19 +198,39 @@ class Discogs(BaseClient):
|
|
|
186
198
|
and (method.upper() in _CACHEABLE_METHODS)
|
|
187
199
|
and (self._owns_client or self._auth_mode != "none")
|
|
188
200
|
)
|
|
201
|
+
cache_only = id(self) in _CACHE_ONLY.get()
|
|
189
202
|
cache_key = ""
|
|
190
|
-
if use_cache:
|
|
203
|
+
if use_cache or cache_only:
|
|
191
204
|
# httpx2 merges params into the URL, so build the request first to key
|
|
192
205
|
# on the fully resolved URL.
|
|
193
206
|
req = self._http_client.build_request(method, url, **build_kwargs)
|
|
207
|
+
if use_cache:
|
|
194
208
|
cache_key = self._build_cache_key(method, str(req.url), headers["Accept"])
|
|
209
|
+
t0 = time.monotonic()
|
|
195
210
|
cached = self._cache.get(cache_key) # type: ignore[union-attr]
|
|
211
|
+
lookup_ms = (time.monotonic() - t0) * 1000
|
|
196
212
|
if cached is not None:
|
|
197
213
|
status, cached_headers, body = cached
|
|
198
214
|
logger.debug("Cache hit: %s %s", method, url)
|
|
199
|
-
|
|
215
|
+
response = httpx2.Response(
|
|
200
216
|
status_code=status, headers=cached_headers, content=body
|
|
201
217
|
)
|
|
218
|
+
self._observe(
|
|
219
|
+
RequestEvent(
|
|
220
|
+
method=method.upper(),
|
|
221
|
+
url=str(req.url),
|
|
222
|
+
status_code=status,
|
|
223
|
+
source="cache",
|
|
224
|
+
elapsed_ms=lookup_ms,
|
|
225
|
+
attempts=0,
|
|
226
|
+
stored=False,
|
|
227
|
+
ratelimit=None,
|
|
228
|
+
)
|
|
229
|
+
)
|
|
230
|
+
return response
|
|
231
|
+
if cache_only:
|
|
232
|
+
# Nothing below this line may run: the scope forbids network I/O.
|
|
233
|
+
raise CacheMissError(method.upper(), str(req.url))
|
|
202
234
|
for attempt in range(self.max_retries + 1):
|
|
203
235
|
logger.debug("HTTP request: %s %s", method, url)
|
|
204
236
|
t0 = time.monotonic() # Unaffected by system clock adjustments (NTP, DST)
|
|
@@ -237,6 +269,7 @@ class Discogs(BaseClient):
|
|
|
237
269
|
not may_retry_status(method, response.status_code)
|
|
238
270
|
or attempt == self.max_retries
|
|
239
271
|
):
|
|
272
|
+
stored = False
|
|
240
273
|
if use_cache and 200 <= response.status_code < 300:
|
|
241
274
|
assert self._cache is not None # narrowed by use_cache
|
|
242
275
|
# response.content is already decompressed by httpx2, so strip
|
|
@@ -254,6 +287,21 @@ class Discogs(BaseClient):
|
|
|
254
287
|
self._cache.set(
|
|
255
288
|
cache_key, response.status_code, cache_headers, response.content
|
|
256
289
|
)
|
|
290
|
+
stored = True
|
|
291
|
+
# Emitted before the error boundary so the event exists even when
|
|
292
|
+
# the call raises.
|
|
293
|
+
self._observe(
|
|
294
|
+
RequestEvent(
|
|
295
|
+
method=method.upper(),
|
|
296
|
+
url=str(response.request.url),
|
|
297
|
+
status_code=response.status_code,
|
|
298
|
+
source="network",
|
|
299
|
+
elapsed_ms=elapsed_ms,
|
|
300
|
+
attempts=attempt + 1,
|
|
301
|
+
stored=stored,
|
|
302
|
+
ratelimit=RateLimit.from_headers(response.headers),
|
|
303
|
+
)
|
|
304
|
+
)
|
|
257
305
|
# The retry policy is done deciding: this is the final response,
|
|
258
306
|
# so map failures here, before any endpoint parses the body.
|
|
259
307
|
self._raise_for_response(response)
|
|
@@ -289,6 +337,21 @@ class Discogs(BaseClient):
|
|
|
289
337
|
finally:
|
|
290
338
|
_CACHE_BYPASS.reset(token)
|
|
291
339
|
|
|
340
|
+
@contextmanager
|
|
341
|
+
def cache_only(self) -> Generator[Self, None, None]:
|
|
342
|
+
"""Serve only from the response cache for the current execution context.
|
|
343
|
+
|
|
344
|
+
A request the cache cannot serve - a miss, an expired entry, a non-GET,
|
|
345
|
+
a disabled cache or an enclosing ``no_cache()`` - raises
|
|
346
|
+
``CacheMissError`` before any network I/O. Scopes nest and restore
|
|
347
|
+
exactly like ``no_cache()``.
|
|
348
|
+
"""
|
|
349
|
+
token = _CACHE_ONLY.set(_CACHE_ONLY.get() | {id(self)})
|
|
350
|
+
try:
|
|
351
|
+
yield self
|
|
352
|
+
finally:
|
|
353
|
+
_CACHE_ONLY.reset(token)
|
|
354
|
+
|
|
292
355
|
def clear_cache(self) -> None:
|
|
293
356
|
"""Purge all cached responses. No-op when caching is disabled."""
|
|
294
357
|
if self._cache is not None:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|