recapi 0.4.4__tar.gz → 0.4.5__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.
- {recapi-0.4.4/recapi.egg-info → recapi-0.4.5}/PKG-INFO +17 -12
- {recapi-0.4.4 → recapi-0.4.5}/README.md +16 -11
- {recapi-0.4.4 → recapi-0.4.5}/pyproject.toml +1 -1
- {recapi-0.4.4 → recapi-0.4.5}/recapi/client.py +44 -16
- {recapi-0.4.4 → recapi-0.4.5/recapi.egg-info}/PKG-INFO +17 -12
- {recapi-0.4.4 → recapi-0.4.5}/tests/test_async_client.py +28 -1
- {recapi-0.4.4 → recapi-0.4.5}/tests/test_client.py +4 -4
- {recapi-0.4.4 → recapi-0.4.5}/tests/test_client_vectors.py +53 -12
- {recapi-0.4.4 → recapi-0.4.5}/LICENSE +0 -0
- {recapi-0.4.4 → recapi-0.4.5}/recapi/__init__.py +0 -0
- {recapi-0.4.4 → recapi-0.4.5}/recapi/async_client.py +0 -0
- {recapi-0.4.4 → recapi-0.4.5}/recapi/history.py +0 -0
- {recapi-0.4.4 → recapi-0.4.5}/recapi.egg-info/SOURCES.txt +0 -0
- {recapi-0.4.4 → recapi-0.4.5}/recapi.egg-info/dependency_links.txt +0 -0
- {recapi-0.4.4 → recapi-0.4.5}/recapi.egg-info/top_level.txt +0 -0
- {recapi-0.4.4 → recapi-0.4.5}/setup.cfg +0 -0
- {recapi-0.4.4 → recapi-0.4.5}/tests/test_history.py +0 -0
- {recapi-0.4.4 → recapi-0.4.5}/tests/test_stores.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.5
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
6
|
Requires-Python: >=3.11
|
|
@@ -37,7 +37,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
37
37
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
38
|
|
|
39
39
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
40
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.5-py3-none-any.whl
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -61,9 +61,10 @@ client.upsert_items([item])
|
|
|
61
61
|
# The user opened an item (level 3). Queued and sent in the background.
|
|
62
62
|
client.track("item-42", "view", user_id="user-881")
|
|
63
63
|
|
|
64
|
-
# Recommendations for that user. If recapi is slow or failing
|
|
65
|
-
# popular items instead (result.fallback is True), and an
|
|
66
|
-
#
|
|
64
|
+
# Recommendations for that user. If recapi is slow or failing or a limit is
|
|
65
|
+
# reached, this returns popular items instead (result.fallback is True), and an
|
|
66
|
+
# empty list if those fail too or the key is refused (hide the slot): no
|
|
67
|
+
# try/except.
|
|
67
68
|
# item.why says why it is listed, safe to show anyone (docs/api.md, "Reason
|
|
68
69
|
# codes"): pick your own words, no label for codes you don't map.
|
|
69
70
|
LABELS = {
|
|
@@ -207,8 +208,8 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
207
208
|
| Method | What it does |
|
|
208
209
|
|---|---|
|
|
209
210
|
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid id or level |
|
|
210
|
-
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#reason-codes). The user's rejected items are added to `exclude` |
|
|
211
|
-
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user |
|
|
211
|
+
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
212
|
+
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
212
213
|
| `upsert_items(items)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored |
|
|
213
214
|
| `identify(anon_id, user_id)` | At login: merges the visitor's history and shown items into the user's, then deletes the visitor's entry. The user's first restore from recapi then leaves that visitor's browsing out, so it doesn't count twice |
|
|
214
215
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
@@ -217,11 +218,15 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
217
218
|
`Client(api_key, base_url, *, store=None, timeout=5.0, flush_interval=2.0,
|
|
218
219
|
max_batch=1000)`: `timeout` per request in seconds (`recommend` waits at most
|
|
219
220
|
1.5 s). `AsyncClient` takes the same arguments. Errors are `recapi.RecapiError` (`code`, `status`, `retryable`);
|
|
220
|
-
`recommend`
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
network error, a timeout or a
|
|
224
|
-
when `/v1/popular` fails too
|
|
221
|
+
`recommend` and `popular` raise only on a bad request (400, 404, 413, other
|
|
222
|
+
3xx/4xx) or a reply that isn't the API's (`invalid_response`, such as a
|
|
223
|
+
`base_url` pointing at a web page): neither can start on a live site without a
|
|
224
|
+
deploy. On a network error, a timeout, a 5xx or a 429 `recommend` returns popular
|
|
225
|
+
items, or an empty list when `/v1/popular` fails too; on a 401 or 403 (a revoked
|
|
226
|
+
key, a suspended shop) an empty list at once, as `/v1/popular` would refuse the
|
|
227
|
+
same key; `popular` returns an empty list for all of these. Each failed call logs
|
|
228
|
+
one warning with the API's message to the `recapi` logger: a wrong key shows
|
|
229
|
+
there, not as an exception.
|
|
225
230
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
226
231
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
227
232
|
|
|
@@ -27,7 +27,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
27
27
|
(the dashboard's quick start shows the line with your API's address):
|
|
28
28
|
|
|
29
29
|
```sh
|
|
30
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
30
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.5-py3-none-any.whl
|
|
31
31
|
```
|
|
32
32
|
|
|
33
33
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -51,9 +51,10 @@ client.upsert_items([item])
|
|
|
51
51
|
# The user opened an item (level 3). Queued and sent in the background.
|
|
52
52
|
client.track("item-42", "view", user_id="user-881")
|
|
53
53
|
|
|
54
|
-
# Recommendations for that user. If recapi is slow or failing
|
|
55
|
-
# popular items instead (result.fallback is True), and an
|
|
56
|
-
#
|
|
54
|
+
# Recommendations for that user. If recapi is slow or failing or a limit is
|
|
55
|
+
# reached, this returns popular items instead (result.fallback is True), and an
|
|
56
|
+
# empty list if those fail too or the key is refused (hide the slot): no
|
|
57
|
+
# try/except.
|
|
57
58
|
# item.why says why it is listed, safe to show anyone (docs/api.md, "Reason
|
|
58
59
|
# codes"): pick your own words, no label for codes you don't map.
|
|
59
60
|
LABELS = {
|
|
@@ -197,8 +198,8 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
197
198
|
| Method | What it does |
|
|
198
199
|
|---|---|
|
|
199
200
|
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid id or level |
|
|
200
|
-
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#reason-codes). The user's rejected items are added to `exclude` |
|
|
201
|
-
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user |
|
|
201
|
+
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
202
|
+
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
202
203
|
| `upsert_items(items)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored |
|
|
203
204
|
| `identify(anon_id, user_id)` | At login: merges the visitor's history and shown items into the user's, then deletes the visitor's entry. The user's first restore from recapi then leaves that visitor's browsing out, so it doesn't count twice |
|
|
204
205
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
@@ -207,11 +208,15 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
207
208
|
`Client(api_key, base_url, *, store=None, timeout=5.0, flush_interval=2.0,
|
|
208
209
|
max_batch=1000)`: `timeout` per request in seconds (`recommend` waits at most
|
|
209
210
|
1.5 s). `AsyncClient` takes the same arguments. Errors are `recapi.RecapiError` (`code`, `status`, `retryable`);
|
|
210
|
-
`recommend`
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
network error, a timeout or a
|
|
214
|
-
when `/v1/popular` fails too
|
|
211
|
+
`recommend` and `popular` raise only on a bad request (400, 404, 413, other
|
|
212
|
+
3xx/4xx) or a reply that isn't the API's (`invalid_response`, such as a
|
|
213
|
+
`base_url` pointing at a web page): neither can start on a live site without a
|
|
214
|
+
deploy. On a network error, a timeout, a 5xx or a 429 `recommend` returns popular
|
|
215
|
+
items, or an empty list when `/v1/popular` fails too; on a 401 or 403 (a revoked
|
|
216
|
+
key, a suspended shop) an empty list at once, as `/v1/popular` would refuse the
|
|
217
|
+
same key; `popular` returns an empty list for all of these. Each failed call logs
|
|
218
|
+
one warning with the API's message to the `recapi` logger: a wrong key shows
|
|
219
|
+
there, not as an exception.
|
|
215
220
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
216
221
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
217
222
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "recapi"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.5"
|
|
8
8
|
description = "Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -29,7 +29,7 @@ from typing import Any, Protocol
|
|
|
29
29
|
|
|
30
30
|
from .history import History, is_id
|
|
31
31
|
|
|
32
|
-
__version__ = "0.4.
|
|
32
|
+
__version__ = "0.4.5"
|
|
33
33
|
|
|
34
34
|
log = logging.getLogger("recapi")
|
|
35
35
|
Tags = Sequence[str] | None
|
|
@@ -136,13 +136,22 @@ class RecapiError(Exception):
|
|
|
136
136
|
|
|
137
137
|
@property
|
|
138
138
|
def outage(self) -> bool:
|
|
139
|
-
"""Whether recapi couldn't answer in time or failed on its side.
|
|
140
|
-
|
|
141
|
-
A 429 is the tenant's own limit and a 4xx an integration bug: a
|
|
142
|
-
fallback would hide both.
|
|
143
|
-
"""
|
|
139
|
+
"""Whether recapi couldn't answer in time or failed on its side."""
|
|
144
140
|
return self.code in ("network", "timeout") or self.status >= 500
|
|
145
141
|
|
|
142
|
+
@property
|
|
143
|
+
def _spare_the_page(self) -> bool:
|
|
144
|
+
# An outage, a limit or a revoked key can start on a live site with no
|
|
145
|
+
# deploy, and a page must not pay for it: the log and the dashboard show
|
|
146
|
+
# it. What's left (a bad request, a reply that isn't the API's) can't
|
|
147
|
+
# start without a deploy, and a developer sees it on the first run.
|
|
148
|
+
return self.outage or self.status == 429 or self._key_refused
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def _key_refused(self) -> bool:
|
|
152
|
+
# A key or shop recapi won't serve: any other call fails too.
|
|
153
|
+
return self.status in (401, 403)
|
|
154
|
+
|
|
146
155
|
|
|
147
156
|
@dataclass(frozen=True)
|
|
148
157
|
class Item:
|
|
@@ -583,10 +592,13 @@ class Client:
|
|
|
583
592
|
history for ``user_id`` and returns it for the store. A history the
|
|
584
593
|
store started without it (a ``track()`` or ``identify()`` came first)
|
|
585
594
|
gets recapi's fetched once, within the same deadline, and merged in.
|
|
586
|
-
No retry, at most 1.5 s: on a network error, timeout or
|
|
587
|
-
popular items (``fallback=True``, no id) and logs the error. If
|
|
588
|
-
fail too (recapi is down
|
|
589
|
-
|
|
595
|
+
No retry, at most 1.5 s: on a network error, timeout, 5xx or 429 it
|
|
596
|
+
returns popular items (``fallback=True``, no id) and logs the error. If
|
|
597
|
+
those fail too (recapi is down, or the plan's limit covers them), the
|
|
598
|
+
list is empty: hide the slot. On a 401 or 403 (a revoked key, a
|
|
599
|
+
suspended shop) it is empty at once, as popular would be refused too.
|
|
600
|
+
Any other failure raises: a bad request or a reply that isn't the API's
|
|
601
|
+
can't start on a live site without a deploy.
|
|
590
602
|
"""
|
|
591
603
|
return self._recommend(
|
|
592
604
|
time.monotonic() + self._recommend_timeout,
|
|
@@ -658,8 +670,13 @@ class Client:
|
|
|
658
670
|
)
|
|
659
671
|
rec_id, items = _parse_recommendations(response)
|
|
660
672
|
except RecapiError as error:
|
|
661
|
-
if not error.
|
|
673
|
+
if not error._spare_the_page:
|
|
662
674
|
raise
|
|
675
|
+
if error._key_refused:
|
|
676
|
+
log.warning(
|
|
677
|
+
"recapi: recommendations refused, served no items: %s: %s", error.code, error
|
|
678
|
+
)
|
|
679
|
+
return Recommendations(None, True, [])
|
|
663
680
|
# The requested length without the excluded items, so a few more
|
|
664
681
|
# are asked for. 0 is the recommendations default; popular refuses it.
|
|
665
682
|
n = count or DEFAULT_COUNT
|
|
@@ -671,9 +688,9 @@ class Client:
|
|
|
671
688
|
min(n + len(skip), MAX_COUNT), tags_any, tags_all, self._recommend_timeout
|
|
672
689
|
)
|
|
673
690
|
except RecapiError as fallback_error:
|
|
674
|
-
# recapi is down
|
|
675
|
-
# try/except, so an empty list the page can hide
|
|
676
|
-
# exception that fails the whole page.
|
|
691
|
+
# recapi is down or the limit covers popular too. The README
|
|
692
|
+
# promises no try/except, so an empty list the page can hide
|
|
693
|
+
# beats an exception that fails the whole page.
|
|
677
694
|
log.warning(
|
|
678
695
|
"recapi: recommendations failed (%s), popular too, served no items: %s",
|
|
679
696
|
error,
|
|
@@ -774,8 +791,19 @@ class Client:
|
|
|
774
791
|
tags_any: Tags = None,
|
|
775
792
|
tags_all: Tags = None,
|
|
776
793
|
) -> list[Item]:
|
|
777
|
-
"""Non-personalised popular items, for pages without a user (no retry).
|
|
778
|
-
|
|
794
|
+
"""Non-personalised popular items, for pages without a user (no retry).
|
|
795
|
+
|
|
796
|
+
On a network error, timeout, 5xx, 429, 401 or 403 it logs the error and
|
|
797
|
+
returns an empty list: hide the slot. Any other failure raises, as in
|
|
798
|
+
:meth:`recommend`.
|
|
799
|
+
"""
|
|
800
|
+
try:
|
|
801
|
+
return self._popular(count, tags_any, tags_all, None)
|
|
802
|
+
except RecapiError as error:
|
|
803
|
+
if not error._spare_the_page:
|
|
804
|
+
raise
|
|
805
|
+
log.warning("recapi: popular items failed, served no items: %s: %s", error.code, error)
|
|
806
|
+
return []
|
|
779
807
|
|
|
780
808
|
def _popular(self, count: int, tags_any: Tags, tags_all: Tags, timeout: float | None) -> list:
|
|
781
809
|
query = {k: ",".join(v) for k, v in (("tags_any", tags_any), ("tags_all", tags_all)) if v}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.5
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
6
|
Requires-Python: >=3.11
|
|
@@ -37,7 +37,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
37
37
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
38
|
|
|
39
39
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
40
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.5-py3-none-any.whl
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -61,9 +61,10 @@ client.upsert_items([item])
|
|
|
61
61
|
# The user opened an item (level 3). Queued and sent in the background.
|
|
62
62
|
client.track("item-42", "view", user_id="user-881")
|
|
63
63
|
|
|
64
|
-
# Recommendations for that user. If recapi is slow or failing
|
|
65
|
-
# popular items instead (result.fallback is True), and an
|
|
66
|
-
#
|
|
64
|
+
# Recommendations for that user. If recapi is slow or failing or a limit is
|
|
65
|
+
# reached, this returns popular items instead (result.fallback is True), and an
|
|
66
|
+
# empty list if those fail too or the key is refused (hide the slot): no
|
|
67
|
+
# try/except.
|
|
67
68
|
# item.why says why it is listed, safe to show anyone (docs/api.md, "Reason
|
|
68
69
|
# codes"): pick your own words, no label for codes you don't map.
|
|
69
70
|
LABELS = {
|
|
@@ -207,8 +208,8 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
207
208
|
| Method | What it does |
|
|
208
209
|
|---|---|
|
|
209
210
|
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid id or level |
|
|
210
|
-
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#reason-codes). The user's rejected items are added to `exclude` |
|
|
211
|
-
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user |
|
|
211
|
+
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
212
|
+
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
212
213
|
| `upsert_items(items)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored |
|
|
213
214
|
| `identify(anon_id, user_id)` | At login: merges the visitor's history and shown items into the user's, then deletes the visitor's entry. The user's first restore from recapi then leaves that visitor's browsing out, so it doesn't count twice |
|
|
214
215
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
@@ -217,11 +218,15 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
217
218
|
`Client(api_key, base_url, *, store=None, timeout=5.0, flush_interval=2.0,
|
|
218
219
|
max_batch=1000)`: `timeout` per request in seconds (`recommend` waits at most
|
|
219
220
|
1.5 s). `AsyncClient` takes the same arguments. Errors are `recapi.RecapiError` (`code`, `status`, `retryable`);
|
|
220
|
-
`recommend`
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
network error, a timeout or a
|
|
224
|
-
when `/v1/popular` fails too
|
|
221
|
+
`recommend` and `popular` raise only on a bad request (400, 404, 413, other
|
|
222
|
+
3xx/4xx) or a reply that isn't the API's (`invalid_response`, such as a
|
|
223
|
+
`base_url` pointing at a web page): neither can start on a live site without a
|
|
224
|
+
deploy. On a network error, a timeout, a 5xx or a 429 `recommend` returns popular
|
|
225
|
+
items, or an empty list when `/v1/popular` fails too; on a 401 or 403 (a revoked
|
|
226
|
+
key, a suspended shop) an empty list at once, as `/v1/popular` would refuse the
|
|
227
|
+
same key; `popular` returns an empty list for all of these. Each failed call logs
|
|
228
|
+
one warning with the API's message to the `recapi` logger: a wrong key shows
|
|
229
|
+
there, not as an exception.
|
|
225
230
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
226
231
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
227
232
|
|
|
@@ -11,7 +11,7 @@ from pathlib import Path
|
|
|
11
11
|
from typing import Any
|
|
12
12
|
|
|
13
13
|
import recapi
|
|
14
|
-
from fakeapi import KEY, APITest, Reply, recs
|
|
14
|
+
from fakeapi import KEY, APITest, Reply, dead_url, popular, recs
|
|
15
15
|
from recapi import async_client
|
|
16
16
|
|
|
17
17
|
|
|
@@ -22,6 +22,33 @@ class AsyncClient(APITest):
|
|
|
22
22
|
self.addCleanup(lambda: asyncio.run(client.close()))
|
|
23
23
|
return client
|
|
24
24
|
|
|
25
|
+
def test_async_list_calls_keep_the_page_up(self) -> None:
|
|
26
|
+
client = self.async_client()
|
|
27
|
+
dead = recapi.AsyncClient(KEY, dead_url(), flush_interval=3600)
|
|
28
|
+
self.addCleanup(lambda: asyncio.run(dead.close()))
|
|
29
|
+
|
|
30
|
+
async def run() -> None:
|
|
31
|
+
quota = {"error": {"code": "quota_exceeded", "message": "spent"}}
|
|
32
|
+
self.api.on("/v1/recommendations", Reply(429, quota))
|
|
33
|
+
self.api.on("/v1/popular", Reply(200, popular(["p1"])))
|
|
34
|
+
result = await client.recommend(user_id="u")
|
|
35
|
+
self.assertEqual(result.recommendation_id, None)
|
|
36
|
+
self.assertTrue(result.fallback)
|
|
37
|
+
self.assertEqual([i.item_id for i in result.items], ["p1"])
|
|
38
|
+
|
|
39
|
+
self.api.calls.clear()
|
|
40
|
+
self.api.handler = lambda call: Reply(401)
|
|
41
|
+
refused = recapi.Recommendations(None, True, [])
|
|
42
|
+
self.assertEqual(await client.recommend(user_id="u"), refused)
|
|
43
|
+
self.assertEqual(self.api.paths(), ["/v1/recommendations"])
|
|
44
|
+
self.assertEqual(await client.popular(), [])
|
|
45
|
+
|
|
46
|
+
self.assertEqual(await dead.popular(), [])
|
|
47
|
+
|
|
48
|
+
with self.assertLogs("recapi", "WARNING") as logs:
|
|
49
|
+
asyncio.run(run())
|
|
50
|
+
self.assertEqual(len(logs.output), 4)
|
|
51
|
+
|
|
25
52
|
def worst_loop_delay(self, recommend: Any, calls: int) -> tuple[float, list]:
|
|
26
53
|
"""Run ``calls`` recommend() at once next to a 10 ms ticker; return its worst lateness."""
|
|
27
54
|
|
|
@@ -702,7 +702,7 @@ class Connections(APITest):
|
|
|
702
702
|
mock.patch.object(http.client.HTTPResponse, "read", side_effect=ConnectionResetError),
|
|
703
703
|
self.assertRaises(recapi.RecapiError) as caught,
|
|
704
704
|
):
|
|
705
|
-
client.
|
|
705
|
+
client._popular(1, None, None, None) # reused connection: the API has the request
|
|
706
706
|
self.assertEqual(caught.exception.code, "network")
|
|
707
707
|
self.assertEqual(self.api.paths(), ["/v1/popular"] * 2)
|
|
708
708
|
self.assertEqual(client._idle, [])
|
|
@@ -711,8 +711,8 @@ class Connections(APITest):
|
|
|
711
711
|
|
|
712
712
|
def test_a_dropped_request_on_a_new_connection_is_not_resent(self) -> None:
|
|
713
713
|
self.api.on("/v1/popular", Reply(drop=True))
|
|
714
|
-
with self.
|
|
715
|
-
self.client().popular()
|
|
714
|
+
with self.assertLogs("recapi", "WARNING"):
|
|
715
|
+
self.assertEqual(self.client().popular(), [])
|
|
716
716
|
self.assertEqual(self.api.paths(), ["/v1/popular"])
|
|
717
717
|
|
|
718
718
|
def test_a_late_reply_is_never_read_as_the_next_calls(self) -> None:
|
|
@@ -743,7 +743,7 @@ class Connections(APITest):
|
|
|
743
743
|
client = recapi.Client(KEY, "https://recapi.invalid")
|
|
744
744
|
self.addCleanup(client.close)
|
|
745
745
|
with self.assertRaises(recapi.RecapiError) as caught:
|
|
746
|
-
client.
|
|
746
|
+
client._popular(1, None, None, None) # the fake refuses the tunnel
|
|
747
747
|
self.assertEqual(caught.exception.code, "network")
|
|
748
748
|
call = self.api.calls[-1]
|
|
749
749
|
self.assertEqual((call.method, call.target), ("CONNECT", "recapi.invalid:443"))
|
|
@@ -76,37 +76,78 @@ class ClientVectors(APITest):
|
|
|
76
76
|
self.api.handler = lambda call, case=case: error_reply(case)
|
|
77
77
|
client = self.client(timeout=0.2)
|
|
78
78
|
with self.assertRaises(recapi.RecapiError) as caught:
|
|
79
|
-
client.
|
|
79
|
+
client._popular(1, None, None, None)
|
|
80
80
|
error = caught.exception
|
|
81
81
|
self.assertEqual(error.code, case["code"])
|
|
82
82
|
self.assertEqual(error.status, case.get("status", 0))
|
|
83
83
|
self.assertEqual(error.retryable, case["retryable"])
|
|
84
|
-
self.assertEqual(error.outage, case["
|
|
84
|
+
self.assertEqual(error.outage, case["outage"])
|
|
85
85
|
if "retry_after_ms" in case:
|
|
86
86
|
want = case["retry_after_ms"]
|
|
87
87
|
self.assertEqual(error.retry_after, None if want is None else want / 1000)
|
|
88
88
|
|
|
89
|
-
|
|
89
|
+
def test_vector_list_calls_keep_the_page_up(self) -> None:
|
|
90
|
+
for case in VECTORS["errors"]:
|
|
91
|
+
with self.subTest(case=case):
|
|
92
|
+
self.api.handler = lambda call, case=case: error_reply(case)
|
|
93
|
+
client = self.client(timeout=0.2)
|
|
90
94
|
if case["fallback"]:
|
|
91
|
-
result = client.recommend(user_id="u")
|
|
92
|
-
self.assertTrue(result.fallback)
|
|
93
|
-
self.assertEqual([i.item_id for i in result.items], ["p1"])
|
|
94
|
-
# Every request fails this way: recapi is down.
|
|
95
|
-
self.api.on("/v1/popular", error_reply(case))
|
|
96
95
|
with self.assertLogs("recapi", "WARNING"):
|
|
97
|
-
|
|
98
|
-
self.assertEqual(result, recapi.Recommendations(None, True, []))
|
|
96
|
+
self.assertEqual(client.popular(), [])
|
|
99
97
|
else:
|
|
98
|
+
with self.assertRaises(recapi.RecapiError) as caught:
|
|
99
|
+
client.popular()
|
|
100
|
+
self.assertEqual(caught.exception.code, case["code"])
|
|
101
|
+
|
|
102
|
+
self.api.on("/v1/popular", Reply(200, popular(["p1"])))
|
|
103
|
+
before = len(self.api.paths())
|
|
104
|
+
if not case["fallback"]:
|
|
100
105
|
with self.assertRaises(recapi.RecapiError) as caught:
|
|
101
106
|
client.recommend(user_id="u")
|
|
102
107
|
self.assertEqual(caught.exception.code, case["code"])
|
|
103
|
-
self.
|
|
108
|
+
self.assertEqual(self.api.paths()[before:].count("/v1/popular"), 0)
|
|
109
|
+
continue
|
|
110
|
+
with self.assertLogs("recapi", "WARNING"):
|
|
111
|
+
result = client.recommend(user_id="u")
|
|
112
|
+
asked = self.api.paths()[before:].count("/v1/popular")
|
|
113
|
+
self.assertEqual(asked, 1 if case["asks_popular"] else 0)
|
|
114
|
+
self.assertEqual([result.recommendation_id, result.fallback], [None, True])
|
|
115
|
+
want = ["p1"] if case["asks_popular"] else []
|
|
116
|
+
self.assertEqual([i.item_id for i in result.items], want)
|
|
117
|
+
# Every request fails this way: recapi is down, or the limit covers popular.
|
|
118
|
+
self.api.on("/v1/popular", error_reply(case))
|
|
119
|
+
with self.assertLogs("recapi", "WARNING"):
|
|
120
|
+
result = client.recommend(user_id="u")
|
|
121
|
+
self.assertEqual(result, recapi.Recommendations(None, True, []))
|
|
122
|
+
|
|
123
|
+
def test_refused_lists_stay_visible(self) -> None:
|
|
124
|
+
# The operator's own logger gets every refused call and filters; a
|
|
125
|
+
# limit here would hide lines from it.
|
|
126
|
+
refused = {"error": {"code": "unauthorized", "message": "from the test"}}
|
|
127
|
+
self.api.handler = lambda call: Reply(401, refused)
|
|
128
|
+
client = self.client()
|
|
129
|
+
with self.assertLogs("recapi", "WARNING") as logs:
|
|
130
|
+
for _ in range(3):
|
|
131
|
+
self.assertEqual(client.popular(), [])
|
|
132
|
+
self.assertEqual(client.recommend(user_id="u").items, [])
|
|
133
|
+
self.assertEqual(len(logs.output), 6)
|
|
134
|
+
for line in logs.output:
|
|
135
|
+
self.assertIn("unauthorized", line)
|
|
136
|
+
self.assertIn("from the test", line)
|
|
137
|
+
|
|
138
|
+
def test_a_malformed_list_still_fails(self) -> None:
|
|
139
|
+
self.api.handler = lambda call: Reply(200, {"items": "nope"})
|
|
140
|
+
client = self.client()
|
|
141
|
+
for call in (client.popular, lambda: client.recommend(user_id="u")):
|
|
142
|
+
with self.assertRaises(recapi.RecapiError) as caught:
|
|
143
|
+
call()
|
|
144
|
+
self.assertEqual(caught.exception.code, "invalid_response")
|
|
104
145
|
|
|
105
146
|
def test_a_refused_connection_is_a_network_error(self) -> None:
|
|
106
147
|
client = recapi.Client(KEY, dead_url())
|
|
107
148
|
self.addCleanup(client.close)
|
|
108
149
|
with self.assertRaises(recapi.RecapiError) as caught:
|
|
109
|
-
client.
|
|
150
|
+
client._popular(1, None, None, None)
|
|
110
151
|
self.assertEqual(caught.exception.code, "network")
|
|
111
152
|
self.assertTrue(caught.exception.retryable)
|
|
112
153
|
|
|
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
|