recapi 0.4.4__tar.gz → 0.4.6__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.6}/PKG-INFO +23 -13
- {recapi-0.4.4 → recapi-0.4.6}/README.md +22 -12
- {recapi-0.4.4 → recapi-0.4.6}/pyproject.toml +1 -1
- {recapi-0.4.4 → recapi-0.4.6}/recapi/client.py +120 -39
- {recapi-0.4.4 → recapi-0.4.6/recapi.egg-info}/PKG-INFO +23 -13
- {recapi-0.4.4 → recapi-0.4.6}/tests/test_async_client.py +106 -1
- {recapi-0.4.4 → recapi-0.4.6}/tests/test_client.py +66 -5
- {recapi-0.4.4 → recapi-0.4.6}/tests/test_client_vectors.py +91 -14
- {recapi-0.4.4 → recapi-0.4.6}/LICENSE +0 -0
- {recapi-0.4.4 → recapi-0.4.6}/recapi/__init__.py +0 -0
- {recapi-0.4.4 → recapi-0.4.6}/recapi/async_client.py +0 -0
- {recapi-0.4.4 → recapi-0.4.6}/recapi/history.py +0 -0
- {recapi-0.4.4 → recapi-0.4.6}/recapi.egg-info/SOURCES.txt +0 -0
- {recapi-0.4.4 → recapi-0.4.6}/recapi.egg-info/dependency_links.txt +0 -0
- {recapi-0.4.4 → recapi-0.4.6}/recapi.egg-info/top_level.txt +0 -0
- {recapi-0.4.4 → recapi-0.4.6}/setup.cfg +0 -0
- {recapi-0.4.4 → recapi-0.4.6}/tests/test_history.py +0 -0
- {recapi-0.4.4 → recapi-0.4.6}/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.6
|
|
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.6-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 = {
|
|
@@ -206,9 +207,9 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
206
207
|
|
|
207
208
|
| Method | What it does |
|
|
208
209
|
|---|---|
|
|
209
|
-
| `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
|
|
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 |
|
|
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 level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
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. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. 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,20 @@ 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 (another 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.
|
|
230
|
+
A page often takes a product id from a visitor's URL, so a crafted link can carry
|
|
231
|
+
an id the API would refuse. It raises nowhere: `recommend` never sends such a
|
|
232
|
+
`context_item_id` and answers with popular items, and `track` drops that event
|
|
233
|
+
alone. Each logs one warning, which never quotes the id. An empty or `None`
|
|
234
|
+
`context_item_id` just means none.
|
|
225
235
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
226
236
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
227
237
|
|
|
@@ -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.6-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 = {
|
|
@@ -196,9 +197,9 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
196
197
|
|
|
197
198
|
| Method | What it does |
|
|
198
199
|
|---|---|
|
|
199
|
-
| `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
|
|
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 |
|
|
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 level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
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. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. 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,20 @@ 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 (another 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.
|
|
220
|
+
A page often takes a product id from a visitor's URL, so a crafted link can carry
|
|
221
|
+
an id the API would refuse. It raises nowhere: `recommend` never sends such a
|
|
222
|
+
`context_item_id` and answers with popular items, and `track` drops that event
|
|
223
|
+
alone. Each logs one warning, which never quotes the id. An empty or `None`
|
|
224
|
+
`context_item_id` just means none.
|
|
215
225
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
216
226
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
217
227
|
|
|
@@ -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.6"
|
|
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.6"
|
|
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:
|
|
@@ -416,12 +425,22 @@ class Client:
|
|
|
416
425
|
``level`` is an integer -10 to 10 or ``view`` (3), ``cart`` (5),
|
|
417
426
|
``purchase`` (10), ``reject`` (-10: never recommend the item to this
|
|
418
427
|
user again until a positive event on it). ``recommendation_id``
|
|
419
|
-
overrides the automatic attribution.
|
|
428
|
+
overrides the automatic attribution. Raises ``ValueError`` on a bad level
|
|
429
|
+
or a bad user, visitor or recommendation id. An ``item_id`` the API would
|
|
430
|
+
refuse isn't one: a page often takes it from a visitor's URL, so the
|
|
431
|
+
event is dropped and logged instead.
|
|
420
432
|
"""
|
|
421
433
|
level = _level(level)
|
|
422
|
-
if not is_id(item_id):
|
|
423
|
-
raise ValueError("item_id must be 1-256 bytes of UTF-8 without control characters")
|
|
424
434
|
_check_ids(user_id=user_id, anon_id=anon_id, recommendation_id=recommendation_id)
|
|
435
|
+
# A crafted link must not fail the page. Nothing is kept: in the history
|
|
436
|
+
# it would make the API refuse every later list. The line never quotes
|
|
437
|
+
# the visitor's id.
|
|
438
|
+
if not is_id(item_id):
|
|
439
|
+
log.warning(
|
|
440
|
+
"recapi: event dropped: item_id must be 1-256 bytes of UTF-8 "
|
|
441
|
+
"without control characters"
|
|
442
|
+
)
|
|
443
|
+
return
|
|
425
444
|
t = _now_ms()
|
|
426
445
|
attributed = recommendation_id
|
|
427
446
|
key = self._key(user_id, anon_id)
|
|
@@ -583,10 +602,15 @@ class Client:
|
|
|
583
602
|
history for ``user_id`` and returns it for the store. A history the
|
|
584
603
|
store started without it (a ``track()`` or ``identify()`` came first)
|
|
585
604
|
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
|
-
|
|
605
|
+
No retry, at most 1.5 s: on a network error, timeout, 5xx or 429 it
|
|
606
|
+
returns popular items (``fallback=True``, no id) and logs the error. If
|
|
607
|
+
those fail too (recapi is down, or the plan's limit covers them), the
|
|
608
|
+
list is empty: hide the slot. On a 401 or 403 (a revoked key, a
|
|
609
|
+
suspended shop) it is empty at once, as popular would be refused too.
|
|
610
|
+
A ``context_item_id`` the API would refuse (a page often takes it from a
|
|
611
|
+
visitor's URL, and it may be no string at all) is never sent: the answer
|
|
612
|
+
is the same popular list. Any other failure raises: a bad request or a
|
|
613
|
+
reply that isn't the API's can't start on a live site without a deploy.
|
|
590
614
|
"""
|
|
591
615
|
return self._recommend(
|
|
592
616
|
time.monotonic() + self._recommend_timeout,
|
|
@@ -627,6 +651,17 @@ class Client:
|
|
|
627
651
|
key = self._key(user_id, anon_id)
|
|
628
652
|
t = _now_ms()
|
|
629
653
|
state = self._load(key) if key is not None else _UserState()
|
|
654
|
+
if not _usable_context(context_item_id):
|
|
655
|
+
_, _, rejected = state.history.wire(t)
|
|
656
|
+
# The message never quotes the id: a visitor may have written it.
|
|
657
|
+
# No id goes on to the fallback: no item can have this one.
|
|
658
|
+
cause = RecapiError(
|
|
659
|
+
"invalid_request",
|
|
660
|
+
"context_item_id must be 1-256 bytes of UTF-8 without control characters",
|
|
661
|
+
)
|
|
662
|
+
return self._fallback(
|
|
663
|
+
cause, rejected, count=count, tags_any=tags_any, tags_all=tags_all, exclude=exclude
|
|
664
|
+
)
|
|
630
665
|
if (
|
|
631
666
|
user_id
|
|
632
667
|
and not state.restored
|
|
@@ -658,31 +693,17 @@ class Client:
|
|
|
658
693
|
)
|
|
659
694
|
rec_id, items = _parse_recommendations(response)
|
|
660
695
|
except RecapiError as error:
|
|
661
|
-
if not error.
|
|
696
|
+
if not error._spare_the_page:
|
|
662
697
|
raise
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
)
|
|
673
|
-
except RecapiError as fallback_error:
|
|
674
|
-
# recapi is down altogether. The README promises no
|
|
675
|
-
# try/except, so an empty list the page can hide beats an
|
|
676
|
-
# exception that fails the whole page.
|
|
677
|
-
log.warning(
|
|
678
|
-
"recapi: recommendations failed (%s), popular too, served no items: %s",
|
|
679
|
-
error,
|
|
680
|
-
fallback_error,
|
|
681
|
-
)
|
|
682
|
-
return Recommendations(None, True, [])
|
|
683
|
-
log.warning("recapi: recommendations failed, served popular items: %s", error)
|
|
684
|
-
items = [item for item in popular if item.item_id not in skip][:n]
|
|
685
|
-
return Recommendations(None, True, items)
|
|
698
|
+
return self._fallback(
|
|
699
|
+
error,
|
|
700
|
+
rejected,
|
|
701
|
+
count=count,
|
|
702
|
+
tags_any=tags_any,
|
|
703
|
+
tags_all=tags_all,
|
|
704
|
+
exclude=exclude,
|
|
705
|
+
context_item_id=context_item_id,
|
|
706
|
+
)
|
|
686
707
|
|
|
687
708
|
if key is not None:
|
|
688
709
|
with self._lock_for(key):
|
|
@@ -703,6 +724,50 @@ class Client:
|
|
|
703
724
|
self._save(key, state, t)
|
|
704
725
|
return Recommendations(rec_id, False, items)
|
|
705
726
|
|
|
727
|
+
def _fallback(
|
|
728
|
+
self,
|
|
729
|
+
error: RecapiError,
|
|
730
|
+
rejected: list[str],
|
|
731
|
+
*,
|
|
732
|
+
count: int,
|
|
733
|
+
tags_any: Tags,
|
|
734
|
+
tags_all: Tags,
|
|
735
|
+
exclude: Tags,
|
|
736
|
+
context_item_id: str | None = None,
|
|
737
|
+
) -> Recommendations:
|
|
738
|
+
"""What recommend() answers instead of a list of its own: popular items, or none."""
|
|
739
|
+
if error._key_refused:
|
|
740
|
+
log.warning(
|
|
741
|
+
"recapi: recommendations refused, served no items: %s: %s", error.code, error
|
|
742
|
+
)
|
|
743
|
+
return Recommendations(None, True, [])
|
|
744
|
+
# The requested length without the excluded items, so a few more
|
|
745
|
+
# are asked for. 0 is the recommendations default; popular refuses it.
|
|
746
|
+
n = count or DEFAULT_COUNT
|
|
747
|
+
skip = set(_with_rejected(exclude, rejected) or ())
|
|
748
|
+
if context_item_id is not None:
|
|
749
|
+
skip.add(context_item_id)
|
|
750
|
+
try:
|
|
751
|
+
popular = self._popular(
|
|
752
|
+
min(n + len(skip), MAX_COUNT), tags_any, tags_all, self._recommend_timeout
|
|
753
|
+
)
|
|
754
|
+
except RecapiError as fallback_error:
|
|
755
|
+
# recapi is down or the limit covers popular too. The README
|
|
756
|
+
# promises no try/except, so an empty list the page can hide
|
|
757
|
+
# beats an exception that fails the whole page.
|
|
758
|
+
log.warning(
|
|
759
|
+
"recapi: recommendations failed (%s: %s), popular too, served no items: %s",
|
|
760
|
+
error.code,
|
|
761
|
+
error,
|
|
762
|
+
fallback_error,
|
|
763
|
+
)
|
|
764
|
+
return Recommendations(None, True, [])
|
|
765
|
+
log.warning(
|
|
766
|
+
"recapi: recommendations failed, served popular items: %s: %s", error.code, error
|
|
767
|
+
)
|
|
768
|
+
items = [item for item in popular if item.item_id not in skip][:n]
|
|
769
|
+
return Recommendations(None, True, items)
|
|
770
|
+
|
|
706
771
|
def _restore(
|
|
707
772
|
self, key: str, user_id: str, state: _UserState, deadline: float, t: int
|
|
708
773
|
) -> _UserState:
|
|
@@ -774,8 +839,19 @@ class Client:
|
|
|
774
839
|
tags_any: Tags = None,
|
|
775
840
|
tags_all: Tags = None,
|
|
776
841
|
) -> list[Item]:
|
|
777
|
-
"""Non-personalised popular items, for pages without a user (no retry).
|
|
778
|
-
|
|
842
|
+
"""Non-personalised popular items, for pages without a user (no retry).
|
|
843
|
+
|
|
844
|
+
On a network error, timeout, 5xx, 429, 401 or 403 it logs the error and
|
|
845
|
+
returns an empty list: hide the slot. Any other failure raises, as in
|
|
846
|
+
:meth:`recommend`.
|
|
847
|
+
"""
|
|
848
|
+
try:
|
|
849
|
+
return self._popular(count, tags_any, tags_all, None)
|
|
850
|
+
except RecapiError as error:
|
|
851
|
+
if not error._spare_the_page:
|
|
852
|
+
raise
|
|
853
|
+
log.warning("recapi: popular items failed, served no items: %s: %s", error.code, error)
|
|
854
|
+
return []
|
|
779
855
|
|
|
780
856
|
def _popular(self, count: int, tags_any: Tags, tags_all: Tags, timeout: float | None) -> list:
|
|
781
857
|
query = {k: ",".join(v) for k, v in (("tags_any", tags_any), ("tags_all", tags_all)) if v}
|
|
@@ -1096,6 +1172,11 @@ def _check_ids(**ids: str | None) -> None:
|
|
|
1096
1172
|
raise ValueError(f"{name} must be 1-256 bytes of UTF-8 without control characters")
|
|
1097
1173
|
|
|
1098
1174
|
|
|
1175
|
+
def _usable_context(value: object) -> bool:
|
|
1176
|
+
# An id, or nothing: an empty string reads as no context item.
|
|
1177
|
+
return value is None or is_id(value) or (isinstance(value, str) and not value)
|
|
1178
|
+
|
|
1179
|
+
|
|
1099
1180
|
def _list(values: Sequence[str] | None) -> list[str] | None:
|
|
1100
1181
|
return list(values) if values else None
|
|
1101
1182
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.6
|
|
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.6-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 = {
|
|
@@ -206,9 +207,9 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
206
207
|
|
|
207
208
|
| Method | What it does |
|
|
208
209
|
|---|---|
|
|
209
|
-
| `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
|
|
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 |
|
|
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 level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
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. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. 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,20 @@ 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 (another 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.
|
|
230
|
+
A page often takes a product id from a visitor's URL, so a crafted link can carry
|
|
231
|
+
an id the API would refuse. It raises nowhere: `recommend` never sends such a
|
|
232
|
+
`context_item_id` and answers with popular items, and `track` drops that event
|
|
233
|
+
alone. Each logs one warning, which never quotes the id. An empty or `None`
|
|
234
|
+
`context_item_id` just means none.
|
|
225
235
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
226
236
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
227
237
|
|
|
@@ -10,8 +10,10 @@ import time
|
|
|
10
10
|
from pathlib import Path
|
|
11
11
|
from typing import Any
|
|
12
12
|
|
|
13
|
+
from test_client_vectors import VECTORS, error_reply
|
|
14
|
+
|
|
13
15
|
import recapi
|
|
14
|
-
from fakeapi import KEY, APITest, Reply, recs
|
|
16
|
+
from fakeapi import KEY, APITest, Reply, dead_url, popular, recs
|
|
15
17
|
from recapi import async_client
|
|
16
18
|
|
|
17
19
|
|
|
@@ -22,6 +24,109 @@ class AsyncClient(APITest):
|
|
|
22
24
|
self.addCleanup(lambda: asyncio.run(client.close()))
|
|
23
25
|
return client
|
|
24
26
|
|
|
27
|
+
def test_async_list_calls_keep_the_page_up(self) -> None:
|
|
28
|
+
client = self.async_client()
|
|
29
|
+
dead = recapi.AsyncClient(KEY, dead_url(), flush_interval=3600)
|
|
30
|
+
self.addCleanup(lambda: asyncio.run(dead.close()))
|
|
31
|
+
|
|
32
|
+
async def run() -> None:
|
|
33
|
+
quota = {"error": {"code": "quota_exceeded", "message": "spent"}}
|
|
34
|
+
self.api.on("/v1/recommendations", Reply(429, quota))
|
|
35
|
+
self.api.on("/v1/popular", Reply(200, popular(["p1"])))
|
|
36
|
+
result = await client.recommend(user_id="u")
|
|
37
|
+
self.assertEqual(result.recommendation_id, None)
|
|
38
|
+
self.assertTrue(result.fallback)
|
|
39
|
+
self.assertEqual([i.item_id for i in result.items], ["p1"])
|
|
40
|
+
|
|
41
|
+
self.api.calls.clear()
|
|
42
|
+
self.api.handler = lambda call: Reply(401)
|
|
43
|
+
refused = recapi.Recommendations(None, True, [])
|
|
44
|
+
self.assertEqual(await client.recommend(user_id="u"), refused)
|
|
45
|
+
self.assertEqual(self.api.paths(), ["/v1/recommendations"])
|
|
46
|
+
self.assertEqual(await client.popular(), [])
|
|
47
|
+
|
|
48
|
+
self.assertEqual(await dead.popular(), [])
|
|
49
|
+
|
|
50
|
+
with self.assertLogs("recapi", "WARNING") as logs:
|
|
51
|
+
asyncio.run(run())
|
|
52
|
+
self.assertEqual(len(logs.output), 4)
|
|
53
|
+
|
|
54
|
+
def test_async_vector_context_ids(self) -> None:
|
|
55
|
+
spec = VECTORS["context_ids"]
|
|
56
|
+
client = self.async_client()
|
|
57
|
+
|
|
58
|
+
async def run() -> None:
|
|
59
|
+
for case in VECTORS["ids"]:
|
|
60
|
+
value = case["id"] * case.get("repeat", 1)
|
|
61
|
+
for failing in (False, True):
|
|
62
|
+
with self.subTest(id=case["id"], repeat=case.get("repeat", 1), failing=failing):
|
|
63
|
+
self.api.calls.clear()
|
|
64
|
+
self.api.on(
|
|
65
|
+
"/v1/popular",
|
|
66
|
+
error_reply(spec["popular_error"])
|
|
67
|
+
if failing
|
|
68
|
+
else Reply(200, popular(spec["popular"])),
|
|
69
|
+
)
|
|
70
|
+
result = await client.recommend(
|
|
71
|
+
user_id="u", count=spec["count"], context_item_id=value
|
|
72
|
+
)
|
|
73
|
+
if case["valid"] or value == "":
|
|
74
|
+
self.assertEqual(self.api.paths(), ["/v1/recommendations"])
|
|
75
|
+
self.assertEqual(self.api.calls[0].body["context_item_id"], value)
|
|
76
|
+
self.assertFalse(result.fallback)
|
|
77
|
+
continue
|
|
78
|
+
self.assertEqual(self.api.paths(), ["/v1/popular"])
|
|
79
|
+
self.assertEqual(self.api.calls[0].query, spec["popular_query"])
|
|
80
|
+
self.assertEqual((result.recommendation_id, result.fallback), (None, True))
|
|
81
|
+
want = [] if failing else spec["items"]
|
|
82
|
+
self.assertEqual([i.item_id for i in result.items], want)
|
|
83
|
+
|
|
84
|
+
asyncio.run(run())
|
|
85
|
+
|
|
86
|
+
def test_async_an_unusable_context_item_id_is_reported_without_the_id(self) -> None:
|
|
87
|
+
self.api.on("/v1/popular", Reply(200, popular(["gone", "p1", "p2"])))
|
|
88
|
+
client = self.async_client()
|
|
89
|
+
bad = "evil\nline" + "x" * 300
|
|
90
|
+
|
|
91
|
+
async def run() -> recapi.Recommendations:
|
|
92
|
+
await client.track("seen", "view", user_id="u")
|
|
93
|
+
await client.track("gone", "reject", user_id="u")
|
|
94
|
+
await client.flush()
|
|
95
|
+
self.api.calls.clear()
|
|
96
|
+
return await client.recommend(user_id="u", count=1, context_item_id=bad)
|
|
97
|
+
|
|
98
|
+
with self.assertLogs("recapi", "WARNING") as logs:
|
|
99
|
+
result = asyncio.run(run())
|
|
100
|
+
self.assertEqual((result.recommendation_id, result.fallback), (None, True))
|
|
101
|
+
self.assertEqual([i.item_id for i in result.items], ["p1"])
|
|
102
|
+
self.assertEqual(self.api.lines(), ["GET /v1/popular?count=2"])
|
|
103
|
+
self.assertEqual(len(logs.output), 1)
|
|
104
|
+
self.assertIn("invalid_request", logs.output[0])
|
|
105
|
+
self.assertNotIn("evil", logs.output[0])
|
|
106
|
+
|
|
107
|
+
def test_async_track_drops_an_unusable_item_id(self) -> None:
|
|
108
|
+
client = self.async_client()
|
|
109
|
+
|
|
110
|
+
async def run() -> None:
|
|
111
|
+
await client.track("before", 3, user_id="u")
|
|
112
|
+
await client.track("evil\nline", 3, user_id="u")
|
|
113
|
+
await client.track("after", 3, user_id="u")
|
|
114
|
+
await client.flush()
|
|
115
|
+
await client.recommend(user_id="u")
|
|
116
|
+
with self.assertRaises(ValueError):
|
|
117
|
+
await client.track("evil\nline", 11, user_id="u")
|
|
118
|
+
with self.assertRaises(ValueError):
|
|
119
|
+
await client.track("evil\nline", 3, user_id="a\nb")
|
|
120
|
+
|
|
121
|
+
with self.assertLogs("recapi", "WARNING") as logs:
|
|
122
|
+
asyncio.run(run())
|
|
123
|
+
self.assertEqual(len(logs.output), 1)
|
|
124
|
+
self.assertIn("dropped", logs.output[0])
|
|
125
|
+
self.assertNotIn("evil", logs.output[0])
|
|
126
|
+
sent = [e["item_id"] for batch in self.api.events() for e in batch]
|
|
127
|
+
self.assertEqual(sent, ["before", "after"])
|
|
128
|
+
self.assertNotIn(b"evil", self.api.calls[-1].raw)
|
|
129
|
+
|
|
25
130
|
def worst_loop_delay(self, recommend: Any, calls: int) -> tuple[float, list]:
|
|
26
131
|
"""Run ``calls`` recommend() at once next to a 10 ms ticker; return its worst lateness."""
|
|
27
132
|
|
|
@@ -54,8 +54,30 @@ class Events(APITest):
|
|
|
54
54
|
for kwargs in ({"user_id": ""}, {"anon_id": "a\n"}, {"recommendation_id": "x" * 257}):
|
|
55
55
|
with self.subTest(kwargs=kwargs), self.assertRaises(ValueError):
|
|
56
56
|
client.track("a", 3, **kwargs)
|
|
57
|
+
|
|
58
|
+
def test_track_drops_an_unusable_item_id(self) -> None:
|
|
59
|
+
client = self.client()
|
|
60
|
+
client.track("before", 3, user_id="u")
|
|
61
|
+
# What a URL or a page's bug makes of an id: none of it may fail the page.
|
|
62
|
+
for bad in ("evil\nline", "", "é" * 129, "a\udc80", None, ["a"], {"a": "b"}, 42):
|
|
63
|
+
with self.subTest(bad=bad), self.assertLogs("recapi", "WARNING") as logs:
|
|
64
|
+
client.track(bad, 3, user_id="u")
|
|
65
|
+
self.assertEqual(len(logs.output), 1)
|
|
66
|
+
self.assertIn("dropped", logs.output[0])
|
|
67
|
+
self.assertNotIn("evil", logs.output[0])
|
|
68
|
+
client.track("after", 3, user_id="u")
|
|
69
|
+
client.flush()
|
|
70
|
+
sent = [e["item_id"] for batch in self.api.events() for e in batch]
|
|
71
|
+
self.assertEqual(sent, ["before", "after"])
|
|
72
|
+
client.recommend(user_id="u")
|
|
73
|
+
self.assertNotIn(b"evil", self.api.calls[-1].raw)
|
|
74
|
+
self.assertEqual(sorted(self.api.calls[-1].body["recent"]), ["after", "before"])
|
|
75
|
+
# Other bad arguments are a developer's, and still fail.
|
|
76
|
+
for kwargs in ({"user_id": "a\nb"}, {"anon_id": "a\nb"}, {"recommendation_id": "a\nb"}):
|
|
77
|
+
with self.subTest(kwargs=kwargs), self.assertRaises(ValueError):
|
|
78
|
+
client.track("evil\nline", 3, **kwargs)
|
|
57
79
|
with self.assertRaises(ValueError):
|
|
58
|
-
client.track("
|
|
80
|
+
client.track("evil\nline", 11, user_id="u")
|
|
59
81
|
|
|
60
82
|
def test_the_sender_sends_a_full_batch_at_once_and_the_rest_every_interval(self) -> None:
|
|
61
83
|
full = self.client(max_batch=2)
|
|
@@ -370,6 +392,45 @@ class Recommend(APITest):
|
|
|
370
392
|
self.assertIn("recs down", logs.output[0])
|
|
371
393
|
self.assertIn("pop down", logs.output[0])
|
|
372
394
|
|
|
395
|
+
def test_an_unusable_context_item_id_is_reported_without_the_id(self) -> None:
|
|
396
|
+
# A page takes the id from a visitor's URL: the visitor must not reach
|
|
397
|
+
# the log, the rejected item still leaves the list, and the history
|
|
398
|
+
# (which would ask for a restore) isn't fetched for a list of popular items.
|
|
399
|
+
self.api.on("/v1/popular", Reply(200, popular(["gone", "p1", "p2"])))
|
|
400
|
+
client = self.client()
|
|
401
|
+
client.track("seen", "view", user_id="u")
|
|
402
|
+
client.track("gone", "reject", user_id="u")
|
|
403
|
+
client.flush()
|
|
404
|
+
self.api.calls.clear()
|
|
405
|
+
bad = "evil\nline" + "x" * 300
|
|
406
|
+
with self.assertLogs("recapi", "WARNING") as logs:
|
|
407
|
+
result = client.recommend(user_id="u", count=1, context_item_id=bad)
|
|
408
|
+
self.assertEqual((result.recommendation_id, result.fallback), (None, True))
|
|
409
|
+
self.assertEqual([i.item_id for i in result.items], ["p1"])
|
|
410
|
+
self.assertEqual(self.api.lines(), ["GET /v1/popular?count=2"])
|
|
411
|
+
self.assertEqual(len(logs.output), 1)
|
|
412
|
+
self.assertIn("invalid_request", logs.output[0])
|
|
413
|
+
self.assertNotIn("evil", logs.output[0])
|
|
414
|
+
|
|
415
|
+
def test_a_context_item_id_that_is_no_string_gets_popular_items(self) -> None:
|
|
416
|
+
client = self.client()
|
|
417
|
+
for bad in (["a"], [], {"a": "b"}, {}, 42, 0, 1.5, True, False, b"a", "a\udc80"):
|
|
418
|
+
with self.subTest(bad=bad):
|
|
419
|
+
self.api.calls.clear()
|
|
420
|
+
with self.assertLogs("recapi", "WARNING") as logs:
|
|
421
|
+
result = client.recommend(user_id="u", count=1, context_item_id=bad)
|
|
422
|
+
self.assertEqual(self.api.lines(), ["GET /v1/popular?count=1"])
|
|
423
|
+
self.assertEqual(result.fallback, True)
|
|
424
|
+
self.assertEqual([i.item_id for i in result.items], ["p1"])
|
|
425
|
+
self.assertIn("invalid_request", logs.output[0])
|
|
426
|
+
# Nothing at all is no context item, the usual list.
|
|
427
|
+
for none in (None, ""):
|
|
428
|
+
with self.subTest(none=none):
|
|
429
|
+
self.api.calls.clear()
|
|
430
|
+
result = client.recommend(user_id="u", count=1, context_item_id=none)
|
|
431
|
+
self.assertEqual(self.api.paths(), ["/v1/recommendations"])
|
|
432
|
+
self.assertEqual(result.fallback, False)
|
|
433
|
+
|
|
373
434
|
def test_a_malformed_response_raises(self) -> None:
|
|
374
435
|
self.api.on("/v1/recommendations", Reply(200, {"items": "nope"}))
|
|
375
436
|
with self.assertRaises(recapi.RecapiError) as caught:
|
|
@@ -702,7 +763,7 @@ class Connections(APITest):
|
|
|
702
763
|
mock.patch.object(http.client.HTTPResponse, "read", side_effect=ConnectionResetError),
|
|
703
764
|
self.assertRaises(recapi.RecapiError) as caught,
|
|
704
765
|
):
|
|
705
|
-
client.
|
|
766
|
+
client._popular(1, None, None, None) # reused connection: the API has the request
|
|
706
767
|
self.assertEqual(caught.exception.code, "network")
|
|
707
768
|
self.assertEqual(self.api.paths(), ["/v1/popular"] * 2)
|
|
708
769
|
self.assertEqual(client._idle, [])
|
|
@@ -711,8 +772,8 @@ class Connections(APITest):
|
|
|
711
772
|
|
|
712
773
|
def test_a_dropped_request_on_a_new_connection_is_not_resent(self) -> None:
|
|
713
774
|
self.api.on("/v1/popular", Reply(drop=True))
|
|
714
|
-
with self.
|
|
715
|
-
self.client().popular()
|
|
775
|
+
with self.assertLogs("recapi", "WARNING"):
|
|
776
|
+
self.assertEqual(self.client().popular(), [])
|
|
716
777
|
self.assertEqual(self.api.paths(), ["/v1/popular"])
|
|
717
778
|
|
|
718
779
|
def test_a_late_reply_is_never_read_as_the_next_calls(self) -> None:
|
|
@@ -743,7 +804,7 @@ class Connections(APITest):
|
|
|
743
804
|
client = recapi.Client(KEY, "https://recapi.invalid")
|
|
744
805
|
self.addCleanup(client.close)
|
|
745
806
|
with self.assertRaises(recapi.RecapiError) as caught:
|
|
746
|
-
client.
|
|
807
|
+
client._popular(1, None, None, None) # the fake refuses the tunnel
|
|
747
808
|
self.assertEqual(caught.exception.code, "network")
|
|
748
809
|
call = self.api.calls[-1]
|
|
749
810
|
self.assertEqual((call.method, call.target), ("CONNECT", "recapi.invalid:443"))
|
|
@@ -62,8 +62,7 @@ class ClientVectors(APITest):
|
|
|
62
62
|
client.track(value, 3, user_id=value)
|
|
63
63
|
accepted.append(value)
|
|
64
64
|
continue
|
|
65
|
-
|
|
66
|
-
client.track(value, 3, user_id="u")
|
|
65
|
+
client.track(value, 3, user_id="u")
|
|
67
66
|
with self.assertRaises(ValueError):
|
|
68
67
|
client.track("a", 3, user_id=value)
|
|
69
68
|
client.flush()
|
|
@@ -76,37 +75,78 @@ class ClientVectors(APITest):
|
|
|
76
75
|
self.api.handler = lambda call, case=case: error_reply(case)
|
|
77
76
|
client = self.client(timeout=0.2)
|
|
78
77
|
with self.assertRaises(recapi.RecapiError) as caught:
|
|
79
|
-
client.
|
|
78
|
+
client._popular(1, None, None, None)
|
|
80
79
|
error = caught.exception
|
|
81
80
|
self.assertEqual(error.code, case["code"])
|
|
82
81
|
self.assertEqual(error.status, case.get("status", 0))
|
|
83
82
|
self.assertEqual(error.retryable, case["retryable"])
|
|
84
|
-
self.assertEqual(error.outage, case["
|
|
83
|
+
self.assertEqual(error.outage, case["outage"])
|
|
85
84
|
if "retry_after_ms" in case:
|
|
86
85
|
want = case["retry_after_ms"]
|
|
87
86
|
self.assertEqual(error.retry_after, None if want is None else want / 1000)
|
|
88
87
|
|
|
89
|
-
|
|
88
|
+
def test_vector_list_calls_keep_the_page_up(self) -> None:
|
|
89
|
+
for case in VECTORS["errors"]:
|
|
90
|
+
with self.subTest(case=case):
|
|
91
|
+
self.api.handler = lambda call, case=case: error_reply(case)
|
|
92
|
+
client = self.client(timeout=0.2)
|
|
90
93
|
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
94
|
with self.assertLogs("recapi", "WARNING"):
|
|
97
|
-
|
|
98
|
-
self.assertEqual(result, recapi.Recommendations(None, True, []))
|
|
95
|
+
self.assertEqual(client.popular(), [])
|
|
99
96
|
else:
|
|
97
|
+
with self.assertRaises(recapi.RecapiError) as caught:
|
|
98
|
+
client.popular()
|
|
99
|
+
self.assertEqual(caught.exception.code, case["code"])
|
|
100
|
+
|
|
101
|
+
self.api.on("/v1/popular", Reply(200, popular(["p1"])))
|
|
102
|
+
before = len(self.api.paths())
|
|
103
|
+
if not case["fallback"]:
|
|
100
104
|
with self.assertRaises(recapi.RecapiError) as caught:
|
|
101
105
|
client.recommend(user_id="u")
|
|
102
106
|
self.assertEqual(caught.exception.code, case["code"])
|
|
103
|
-
self.
|
|
107
|
+
self.assertEqual(self.api.paths()[before:].count("/v1/popular"), 0)
|
|
108
|
+
continue
|
|
109
|
+
with self.assertLogs("recapi", "WARNING"):
|
|
110
|
+
result = client.recommend(user_id="u")
|
|
111
|
+
asked = self.api.paths()[before:].count("/v1/popular")
|
|
112
|
+
self.assertEqual(asked, 1 if case["asks_popular"] else 0)
|
|
113
|
+
self.assertEqual([result.recommendation_id, result.fallback], [None, True])
|
|
114
|
+
want = ["p1"] if case["asks_popular"] else []
|
|
115
|
+
self.assertEqual([i.item_id for i in result.items], want)
|
|
116
|
+
# Every request fails this way: recapi is down, or the limit covers popular.
|
|
117
|
+
self.api.on("/v1/popular", error_reply(case))
|
|
118
|
+
with self.assertLogs("recapi", "WARNING"):
|
|
119
|
+
result = client.recommend(user_id="u")
|
|
120
|
+
self.assertEqual(result, recapi.Recommendations(None, True, []))
|
|
121
|
+
|
|
122
|
+
def test_refused_lists_stay_visible(self) -> None:
|
|
123
|
+
# The operator's own logger gets every refused call and filters; a
|
|
124
|
+
# limit here would hide lines from it.
|
|
125
|
+
refused = {"error": {"code": "unauthorized", "message": "from the test"}}
|
|
126
|
+
self.api.handler = lambda call: Reply(401, refused)
|
|
127
|
+
client = self.client()
|
|
128
|
+
with self.assertLogs("recapi", "WARNING") as logs:
|
|
129
|
+
for _ in range(3):
|
|
130
|
+
self.assertEqual(client.popular(), [])
|
|
131
|
+
self.assertEqual(client.recommend(user_id="u").items, [])
|
|
132
|
+
self.assertEqual(len(logs.output), 6)
|
|
133
|
+
for line in logs.output:
|
|
134
|
+
self.assertIn("unauthorized", line)
|
|
135
|
+
self.assertIn("from the test", line)
|
|
136
|
+
|
|
137
|
+
def test_a_malformed_list_still_fails(self) -> None:
|
|
138
|
+
self.api.handler = lambda call: Reply(200, {"items": "nope"})
|
|
139
|
+
client = self.client()
|
|
140
|
+
for call in (client.popular, lambda: client.recommend(user_id="u")):
|
|
141
|
+
with self.assertRaises(recapi.RecapiError) as caught:
|
|
142
|
+
call()
|
|
143
|
+
self.assertEqual(caught.exception.code, "invalid_response")
|
|
104
144
|
|
|
105
145
|
def test_a_refused_connection_is_a_network_error(self) -> None:
|
|
106
146
|
client = recapi.Client(KEY, dead_url())
|
|
107
147
|
self.addCleanup(client.close)
|
|
108
148
|
with self.assertRaises(recapi.RecapiError) as caught:
|
|
109
|
-
client.
|
|
149
|
+
client._popular(1, None, None, None)
|
|
110
150
|
self.assertEqual(caught.exception.code, "network")
|
|
111
151
|
self.assertTrue(caught.exception.retryable)
|
|
112
152
|
|
|
@@ -187,6 +227,43 @@ class ClientVectors(APITest):
|
|
|
187
227
|
self.assertEqual([i.item_id for i in result.items], case["items"])
|
|
188
228
|
self.assertEqual({i.slot for i in result.items} - {"backfill"}, set())
|
|
189
229
|
|
|
230
|
+
def test_vector_context_ids(self) -> None:
|
|
231
|
+
spec = VECTORS["context_ids"]
|
|
232
|
+
for case in VECTORS["ids"]:
|
|
233
|
+
value = case["id"] * case.get("repeat", 1)
|
|
234
|
+
for failing in (False, True):
|
|
235
|
+
with self.subTest(id=case["id"], repeat=case.get("repeat", 1), failing=failing):
|
|
236
|
+
self.api.calls.clear()
|
|
237
|
+
self.api.on(
|
|
238
|
+
"/v1/popular",
|
|
239
|
+
error_reply(spec["popular_error"])
|
|
240
|
+
if failing
|
|
241
|
+
else Reply(200, popular(spec["popular"])),
|
|
242
|
+
)
|
|
243
|
+
client = self.client()
|
|
244
|
+
if case["valid"] or value == "":
|
|
245
|
+
with self.assertNoLogs("recapi"):
|
|
246
|
+
result = client.recommend(
|
|
247
|
+
user_id="u", count=spec["count"], context_item_id=value
|
|
248
|
+
)
|
|
249
|
+
self.assertEqual(self.api.paths(), ["/v1/recommendations"])
|
|
250
|
+
self.assertEqual(self.api.calls[0].body["context_item_id"], value)
|
|
251
|
+
self.assertFalse(result.fallback)
|
|
252
|
+
continue
|
|
253
|
+
with self.assertLogs("recapi", "WARNING") as logs:
|
|
254
|
+
result = client.recommend(
|
|
255
|
+
user_id="u", count=spec["count"], context_item_id=value
|
|
256
|
+
)
|
|
257
|
+
self.assertEqual(self.api.paths(), ["/v1/popular"])
|
|
258
|
+
self.assertEqual(self.api.calls[0].query, spec["popular_query"])
|
|
259
|
+
self.assertTrue(result.fallback)
|
|
260
|
+
self.assertIsNone(result.recommendation_id)
|
|
261
|
+
want = [] if failing else spec["items"]
|
|
262
|
+
self.assertEqual([i.item_id for i in result.items], want)
|
|
263
|
+
self.assertEqual(len(logs.output), 1)
|
|
264
|
+
self.assertIn("invalid_request", logs.output[0])
|
|
265
|
+
self.assertNotIn(value, logs.output[0])
|
|
266
|
+
|
|
190
267
|
def test_metadata_and_why(self) -> None:
|
|
191
268
|
for name in ("metadata", "why"):
|
|
192
269
|
with self.subTest(name):
|
|
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
|