recapi 0.4.5__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.5/recapi.egg-info → recapi-0.4.6}/PKG-INFO +10 -5
- {recapi-0.4.5 → recapi-0.4.6}/README.md +9 -4
- {recapi-0.4.5 → recapi-0.4.6}/pyproject.toml +1 -1
- {recapi-0.4.5 → recapi-0.4.6}/recapi/client.py +87 -34
- {recapi-0.4.5 → recapi-0.4.6/recapi.egg-info}/PKG-INFO +10 -5
- {recapi-0.4.5 → recapi-0.4.6}/tests/test_async_client.py +78 -0
- {recapi-0.4.5 → recapi-0.4.6}/tests/test_client.py +62 -1
- {recapi-0.4.5 → recapi-0.4.6}/tests/test_client_vectors.py +38 -2
- {recapi-0.4.5 → recapi-0.4.6}/LICENSE +0 -0
- {recapi-0.4.5 → recapi-0.4.6}/recapi/__init__.py +0 -0
- {recapi-0.4.5 → recapi-0.4.6}/recapi/async_client.py +0 -0
- {recapi-0.4.5 → recapi-0.4.6}/recapi/history.py +0 -0
- {recapi-0.4.5 → recapi-0.4.6}/recapi.egg-info/SOURCES.txt +0 -0
- {recapi-0.4.5 → recapi-0.4.6}/recapi.egg-info/dependency_links.txt +0 -0
- {recapi-0.4.5 → recapi-0.4.6}/recapi.egg-info/top_level.txt +0 -0
- {recapi-0.4.5 → recapi-0.4.6}/setup.cfg +0 -0
- {recapi-0.4.5 → recapi-0.4.6}/tests/test_history.py +0 -0
- {recapi-0.4.5 → 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
|
|
@@ -207,8 +207,8 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
207
207
|
|
|
208
208
|
| Method | What it does |
|
|
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
|
|
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 |
|
|
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
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` |
|
|
213
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 |
|
|
214
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 |
|
|
@@ -218,7 +218,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
218
218
|
`Client(api_key, base_url, *, store=None, timeout=5.0, flush_interval=2.0,
|
|
219
219
|
max_batch=1000)`: `timeout` per request in seconds (`recommend` waits at most
|
|
220
220
|
1.5 s). `AsyncClient` takes the same arguments. Errors are `recapi.RecapiError` (`code`, `status`, `retryable`);
|
|
221
|
-
`recommend` and `popular` raise only on a bad request (400, 404, 413, other
|
|
221
|
+
`recommend` and `popular` raise only on a bad request (another 400, 404, 413, other
|
|
222
222
|
3xx/4xx) or a reply that isn't the API's (`invalid_response`, such as a
|
|
223
223
|
`base_url` pointing at a web page): neither can start on a live site without a
|
|
224
224
|
deploy. On a network error, a timeout, a 5xx or a 429 `recommend` returns popular
|
|
@@ -227,6 +227,11 @@ key, a suspended shop) an empty list at once, as `/v1/popular` would refuse the
|
|
|
227
227
|
same key; `popular` returns an empty list for all of these. Each failed call logs
|
|
228
228
|
one warning with the API's message to the `recapi` logger: a wrong key shows
|
|
229
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.
|
|
230
235
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
231
236
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
232
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
|
|
@@ -197,8 +197,8 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
197
197
|
|
|
198
198
|
| Method | What it does |
|
|
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
|
|
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 |
|
|
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
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` |
|
|
203
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 |
|
|
204
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 |
|
|
@@ -208,7 +208,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
208
208
|
`Client(api_key, base_url, *, store=None, timeout=5.0, flush_interval=2.0,
|
|
209
209
|
max_batch=1000)`: `timeout` per request in seconds (`recommend` waits at most
|
|
210
210
|
1.5 s). `AsyncClient` takes the same arguments. Errors are `recapi.RecapiError` (`code`, `status`, `retryable`);
|
|
211
|
-
`recommend` and `popular` raise only on a bad request (400, 404, 413, other
|
|
211
|
+
`recommend` and `popular` raise only on a bad request (another 400, 404, 413, other
|
|
212
212
|
3xx/4xx) or a reply that isn't the API's (`invalid_response`, such as a
|
|
213
213
|
`base_url` pointing at a web page): neither can start on a live site without a
|
|
214
214
|
deploy. On a network error, a timeout, a 5xx or a 429 `recommend` returns popular
|
|
@@ -217,6 +217,11 @@ key, a suspended shop) an empty list at once, as `/v1/popular` would refuse the
|
|
|
217
217
|
same key; `popular` returns an empty list for all of these. Each failed call logs
|
|
218
218
|
one warning with the API's message to the `recapi` logger: a wrong key shows
|
|
219
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.
|
|
220
225
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
221
226
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
222
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
|
|
@@ -425,12 +425,22 @@ class Client:
|
|
|
425
425
|
``level`` is an integer -10 to 10 or ``view`` (3), ``cart`` (5),
|
|
426
426
|
``purchase`` (10), ``reject`` (-10: never recommend the item to this
|
|
427
427
|
user again until a positive event on it). ``recommendation_id``
|
|
428
|
-
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.
|
|
429
432
|
"""
|
|
430
433
|
level = _level(level)
|
|
431
|
-
if not is_id(item_id):
|
|
432
|
-
raise ValueError("item_id must be 1-256 bytes of UTF-8 without control characters")
|
|
433
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
|
|
434
444
|
t = _now_ms()
|
|
435
445
|
attributed = recommendation_id
|
|
436
446
|
key = self._key(user_id, anon_id)
|
|
@@ -597,8 +607,10 @@ class Client:
|
|
|
597
607
|
those fail too (recapi is down, or the plan's limit covers them), the
|
|
598
608
|
list is empty: hide the slot. On a 401 or 403 (a revoked key, a
|
|
599
609
|
suspended shop) it is empty at once, as popular would be refused too.
|
|
600
|
-
|
|
601
|
-
|
|
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.
|
|
602
614
|
"""
|
|
603
615
|
return self._recommend(
|
|
604
616
|
time.monotonic() + self._recommend_timeout,
|
|
@@ -639,6 +651,17 @@ class Client:
|
|
|
639
651
|
key = self._key(user_id, anon_id)
|
|
640
652
|
t = _now_ms()
|
|
641
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
|
+
)
|
|
642
665
|
if (
|
|
643
666
|
user_id
|
|
644
667
|
and not state.restored
|
|
@@ -672,34 +695,15 @@ class Client:
|
|
|
672
695
|
except RecapiError as error:
|
|
673
696
|
if not error._spare_the_page:
|
|
674
697
|
raise
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
if context_item_id is not None:
|
|
685
|
-
skip.add(context_item_id)
|
|
686
|
-
try:
|
|
687
|
-
popular = self._popular(
|
|
688
|
-
min(n + len(skip), MAX_COUNT), tags_any, tags_all, self._recommend_timeout
|
|
689
|
-
)
|
|
690
|
-
except RecapiError as fallback_error:
|
|
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.
|
|
694
|
-
log.warning(
|
|
695
|
-
"recapi: recommendations failed (%s), popular too, served no items: %s",
|
|
696
|
-
error,
|
|
697
|
-
fallback_error,
|
|
698
|
-
)
|
|
699
|
-
return Recommendations(None, True, [])
|
|
700
|
-
log.warning("recapi: recommendations failed, served popular items: %s", error)
|
|
701
|
-
items = [item for item in popular if item.item_id not in skip][:n]
|
|
702
|
-
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
|
+
)
|
|
703
707
|
|
|
704
708
|
if key is not None:
|
|
705
709
|
with self._lock_for(key):
|
|
@@ -720,6 +724,50 @@ class Client:
|
|
|
720
724
|
self._save(key, state, t)
|
|
721
725
|
return Recommendations(rec_id, False, items)
|
|
722
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
|
+
|
|
723
771
|
def _restore(
|
|
724
772
|
self, key: str, user_id: str, state: _UserState, deadline: float, t: int
|
|
725
773
|
) -> _UserState:
|
|
@@ -1124,6 +1172,11 @@ def _check_ids(**ids: str | None) -> None:
|
|
|
1124
1172
|
raise ValueError(f"{name} must be 1-256 bytes of UTF-8 without control characters")
|
|
1125
1173
|
|
|
1126
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
|
+
|
|
1127
1180
|
def _list(values: Sequence[str] | None) -> list[str] | None:
|
|
1128
1181
|
return list(values) if values else None
|
|
1129
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
|
|
@@ -207,8 +207,8 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
207
207
|
|
|
208
208
|
| Method | What it does |
|
|
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
|
|
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 |
|
|
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
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` |
|
|
213
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 |
|
|
214
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 |
|
|
@@ -218,7 +218,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
218
218
|
`Client(api_key, base_url, *, store=None, timeout=5.0, flush_interval=2.0,
|
|
219
219
|
max_batch=1000)`: `timeout` per request in seconds (`recommend` waits at most
|
|
220
220
|
1.5 s). `AsyncClient` takes the same arguments. Errors are `recapi.RecapiError` (`code`, `status`, `retryable`);
|
|
221
|
-
`recommend` and `popular` raise only on a bad request (400, 404, 413, other
|
|
221
|
+
`recommend` and `popular` raise only on a bad request (another 400, 404, 413, other
|
|
222
222
|
3xx/4xx) or a reply that isn't the API's (`invalid_response`, such as a
|
|
223
223
|
`base_url` pointing at a web page): neither can start on a live site without a
|
|
224
224
|
deploy. On a network error, a timeout, a 5xx or a 429 `recommend` returns popular
|
|
@@ -227,6 +227,11 @@ key, a suspended shop) an empty list at once, as `/v1/popular` would refuse the
|
|
|
227
227
|
same key; `popular` returns an empty list for all of these. Each failed call logs
|
|
228
228
|
one warning with the API's message to the `recapi` logger: a wrong key shows
|
|
229
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.
|
|
230
235
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
231
236
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
232
237
|
|
|
@@ -10,6 +10,8 @@ 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
16
|
from fakeapi import KEY, APITest, Reply, dead_url, popular, recs
|
|
15
17
|
from recapi import async_client
|
|
@@ -49,6 +51,82 @@ class AsyncClient(APITest):
|
|
|
49
51
|
asyncio.run(run())
|
|
50
52
|
self.assertEqual(len(logs.output), 4)
|
|
51
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
|
+
|
|
52
130
|
def worst_loop_delay(self, recommend: Any, calls: int) -> tuple[float, list]:
|
|
53
131
|
"""Run ``calls`` recommend() at once next to a 10 ms ticker; return its worst lateness."""
|
|
54
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:
|
|
@@ -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()
|
|
@@ -228,6 +227,43 @@ class ClientVectors(APITest):
|
|
|
228
227
|
self.assertEqual([i.item_id for i in result.items], case["items"])
|
|
229
228
|
self.assertEqual({i.slot for i in result.items} - {"backfill"}, set())
|
|
230
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
|
+
|
|
231
267
|
def test_metadata_and_why(self) -> None:
|
|
232
268
|
for name in ("metadata", "why"):
|
|
233
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
|