recapi 0.4.7__tar.gz → 0.4.9__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.7/recapi.egg-info → recapi-0.4.9}/PKG-INFO +3 -3
- {recapi-0.4.7 → recapi-0.4.9}/README.md +2 -2
- {recapi-0.4.7 → recapi-0.4.9}/pyproject.toml +1 -1
- {recapi-0.4.7 → recapi-0.4.9}/recapi/__init__.py +11 -1
- {recapi-0.4.7 → recapi-0.4.9}/recapi/async_client.py +2 -2
- {recapi-0.4.7 → recapi-0.4.9}/recapi/client.py +39 -13
- {recapi-0.4.7 → recapi-0.4.9}/recapi/history.py +20 -7
- {recapi-0.4.7 → recapi-0.4.9/recapi.egg-info}/PKG-INFO +3 -3
- {recapi-0.4.7 → recapi-0.4.9}/tests/test_client_vectors.py +54 -0
- {recapi-0.4.7 → recapi-0.4.9}/LICENSE +0 -0
- {recapi-0.4.7 → recapi-0.4.9}/recapi.egg-info/SOURCES.txt +0 -0
- {recapi-0.4.7 → recapi-0.4.9}/recapi.egg-info/dependency_links.txt +0 -0
- {recapi-0.4.7 → recapi-0.4.9}/recapi.egg-info/top_level.txt +0 -0
- {recapi-0.4.7 → recapi-0.4.9}/setup.cfg +0 -0
- {recapi-0.4.7 → recapi-0.4.9}/tests/test_async_client.py +0 -0
- {recapi-0.4.7 → recapi-0.4.9}/tests/test_client.py +0 -0
- {recapi-0.4.7 → recapi-0.4.9}/tests/test_history.py +0 -0
- {recapi-0.4.7 → recapi-0.4.9}/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.9
|
|
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.9-py3-none-any.whl
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -210,7 +210,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
210
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
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
|
-
| `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
|
+
| `upsert_items(items, *, merge=False)` | 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. With `merge=True` only the fields an item has are sent and changed, the others keep their stored values (a tags-only sync keeps titles and metadata); to clear a field, replace the item or set it to `None`, which resets it to its default. A bad item doesn't keep the others out: once all are sent, `recapi.RejectedItemsError` (a `RecapiError`, code `invalid_request`) lists them in `rejected` as `(index, error)` pairs, with the count stored in `upserted` |
|
|
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 |
|
|
215
215
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
216
216
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -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.9-py3-none-any.whl
|
|
31
31
|
```
|
|
32
32
|
|
|
33
33
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -200,7 +200,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
200
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
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
|
-
| `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
|
+
| `upsert_items(items, *, merge=False)` | 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. With `merge=True` only the fields an item has are sent and changed, the others keep their stored values (a tags-only sync keeps titles and metadata); to clear a field, replace the item or set it to `None`, which resets it to its default. A bad item doesn't keep the others out: once all are sent, `recapi.RejectedItemsError` (a `RecapiError`, code `invalid_request`) lists them in `rejected` as `(index, error)` pairs, with the count stored in `upserted` |
|
|
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 |
|
|
205
205
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
206
206
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -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.9"
|
|
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"
|
|
@@ -14,7 +14,16 @@ coroutines. See ``sdk/python/README.md``.
|
|
|
14
14
|
|
|
15
15
|
from typing import Any
|
|
16
16
|
|
|
17
|
-
from .client import
|
|
17
|
+
from .client import (
|
|
18
|
+
Client,
|
|
19
|
+
Item,
|
|
20
|
+
MemoryStore,
|
|
21
|
+
RecapiError,
|
|
22
|
+
Recommendations,
|
|
23
|
+
RejectedItemsError,
|
|
24
|
+
Store,
|
|
25
|
+
__version__,
|
|
26
|
+
)
|
|
18
27
|
|
|
19
28
|
__all__ = [
|
|
20
29
|
"AsyncClient",
|
|
@@ -23,6 +32,7 @@ __all__ = [
|
|
|
23
32
|
"MemoryStore",
|
|
24
33
|
"RecapiError",
|
|
25
34
|
"Recommendations",
|
|
35
|
+
"RejectedItemsError",
|
|
26
36
|
"Store",
|
|
27
37
|
"__version__",
|
|
28
38
|
]
|
|
@@ -75,9 +75,9 @@ class AsyncClient:
|
|
|
75
75
|
"""Popular items: :meth:`Client.popular`."""
|
|
76
76
|
return await self._run(self._client.popular, **params)
|
|
77
77
|
|
|
78
|
-
async def upsert_items(self, items: Any) -> int:
|
|
78
|
+
async def upsert_items(self, items: Any, *, merge: bool = False) -> int:
|
|
79
79
|
"""Create or replace items: :meth:`Client.upsert_items`."""
|
|
80
|
-
return await self._run(self._client.upsert_items, items)
|
|
80
|
+
return await self._run(self._client.upsert_items, items, merge=merge)
|
|
81
81
|
|
|
82
82
|
async def delete_user(self, user_id: str) -> None:
|
|
83
83
|
"""Erase a user (GDPR): :meth:`Client.delete_user`."""
|
|
@@ -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.9"
|
|
33
33
|
|
|
34
34
|
log = logging.getLogger("recapi")
|
|
35
35
|
Tags = Sequence[str] | None
|
|
@@ -153,6 +153,21 @@ class RecapiError(Exception):
|
|
|
153
153
|
return self.status in (401, 403)
|
|
154
154
|
|
|
155
155
|
|
|
156
|
+
class RejectedItemsError(RecapiError):
|
|
157
|
+
"""upsert_items' error when the API refused some items: the others were stored.
|
|
158
|
+
|
|
159
|
+
``upserted`` is how many were stored, ``rejected`` the refused ones as
|
|
160
|
+
(index in the list given to upsert_items, error) pairs.
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
def __init__(self, upserted: int, rejected: list[tuple[int, str]]) -> None:
|
|
164
|
+
index, error = rejected[0]
|
|
165
|
+
message = f"{len(rejected)} items refused, the first items[{index}]: {error}"
|
|
166
|
+
super().__init__("invalid_request", message, status=200)
|
|
167
|
+
self.upserted = upserted
|
|
168
|
+
self.rejected = rejected
|
|
169
|
+
|
|
170
|
+
|
|
156
171
|
@dataclass(frozen=True)
|
|
157
172
|
class Item:
|
|
158
173
|
"""One recommended or popular item."""
|
|
@@ -872,28 +887,39 @@ class Client:
|
|
|
872
887
|
|
|
873
888
|
# --- catalog and users --------------------------------------------------
|
|
874
889
|
|
|
875
|
-
def upsert_items(self, items: Iterable[Mapping[str, Any]]) -> int:
|
|
890
|
+
def upsert_items(self, items: Iterable[Mapping[str, Any]], *, merge: bool = False) -> int:
|
|
876
891
|
"""Create or replace items (dicts of the API's item fields), 1,000 per request.
|
|
877
892
|
|
|
878
|
-
|
|
879
|
-
|
|
893
|
+
With ``merge``, each item changes only the fields it has and keeps the
|
|
894
|
+
others' stored values (a field set to None goes back to its default).
|
|
895
|
+
Retried like events. Returns how many were stored. An invalid item
|
|
896
|
+
doesn't keep the others out: once every request is sent,
|
|
897
|
+
:class:`RejectedItemsError` lists the refused ones.
|
|
880
898
|
"""
|
|
881
899
|
batch: list[dict[str, Any]] = []
|
|
882
|
-
upserted = 0
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
900
|
+
upserted, sent = 0, 0
|
|
901
|
+
rejected: list[tuple[int, str]] = []
|
|
902
|
+
|
|
903
|
+
def send() -> None:
|
|
904
|
+
nonlocal upserted, sent
|
|
905
|
+
# "merge" only when asked: an older API refuses the field.
|
|
906
|
+
body = {"items": batch, "merge": True} if merge else {"items": batch}
|
|
907
|
+
response = _with_retry(lambda: self._request("POST", "/v1/items:batch", body=body))
|
|
908
|
+
if isinstance(response, dict):
|
|
909
|
+
upserted += int(response.get("upserted", 0))
|
|
910
|
+
for entry in response.get("rejected") or []:
|
|
911
|
+
rejected.append((sent + int(entry["index"]), str(entry.get("error", ""))))
|
|
912
|
+
sent += len(batch)
|
|
889
913
|
|
|
890
914
|
for item in items:
|
|
891
915
|
batch.append(dict(item))
|
|
892
916
|
if len(batch) == MAX_ITEMS_PER_REQUEST:
|
|
893
|
-
|
|
917
|
+
send()
|
|
894
918
|
batch = []
|
|
895
919
|
if batch:
|
|
896
|
-
|
|
920
|
+
send()
|
|
921
|
+
if rejected:
|
|
922
|
+
raise RejectedItemsError(upserted, rejected)
|
|
897
923
|
return upserted
|
|
898
924
|
|
|
899
925
|
def delete_user(self, user_id: str) -> None:
|
|
@@ -17,6 +17,8 @@ TOP_K = 50
|
|
|
17
17
|
RECENT_SIZE = 20
|
|
18
18
|
REJECTED_SIZE = 200
|
|
19
19
|
MAX_ID_BYTES = 256
|
|
20
|
+
# The API answers 400 above this, which fails the list: a damaged score is sent as this.
|
|
21
|
+
MAX_REQUEST_WEIGHT = 1e6
|
|
20
22
|
|
|
21
23
|
_RATE = math.log(2) / HALF_LIFE_SECONDS
|
|
22
24
|
# Go's unicode.IsControl, which the API applies to every id: C0, DEL and C1.
|
|
@@ -112,8 +114,12 @@ class History:
|
|
|
112
114
|
self._prune_rejected()
|
|
113
115
|
|
|
114
116
|
def ranked(self, now: float) -> list[tuple[str, float, float]]:
|
|
115
|
-
"""Return (item, weight at ``now``, t) by weight desc, ties by item id asc.
|
|
116
|
-
|
|
117
|
+
"""Return (item, weight at ``now``, t) by weight desc, ties by item id asc.
|
|
118
|
+
|
|
119
|
+
A time ahead of ``now`` reads as ``now``: a clock that ran ahead must not
|
|
120
|
+
grow the weight past what the API takes, or overflow.
|
|
121
|
+
"""
|
|
122
|
+
entries = [(item, s * _decay(max(0, now - t)), t) for item, (s, t) in self.top.items()]
|
|
117
123
|
entries.sort(key=lambda e: (-e[1], e[0]))
|
|
118
124
|
return entries
|
|
119
125
|
|
|
@@ -123,7 +129,10 @@ class History:
|
|
|
123
129
|
|
|
124
130
|
def _prune(self, now: float) -> None:
|
|
125
131
|
if len(self.top) > TOP_K:
|
|
126
|
-
|
|
132
|
+
# Read at the newest entry when an event arrives out of order: at the old
|
|
133
|
+
# event's time ranked() would flatten the newer entries to their score.
|
|
134
|
+
at = max(now, *(t for _, t in self.top.values()))
|
|
135
|
+
self.top = {item: self.top[item] for item, _, _ in self.ranked(at)[:TOP_K]}
|
|
127
136
|
|
|
128
137
|
def _prune_rejected(self) -> None:
|
|
129
138
|
if len(self.rejected) > REJECTED_SIZE:
|
|
@@ -133,12 +142,16 @@ class History:
|
|
|
133
142
|
def wire(self, now: float) -> tuple[list[list[Any]], list[str], list[str]]:
|
|
134
143
|
"""Return the request's ``history`` and ``recent``, and the rejected items.
|
|
135
144
|
|
|
136
|
-
Weights are decayed to ``now
|
|
137
|
-
JS ``Math.round`` (Python's ``round`` rounds half
|
|
138
|
-
whole seconds, never negative.
|
|
145
|
+
Weights are decayed to ``now``, at most what the API accepts, and rounded
|
|
146
|
+
half up to 4 decimals like JS ``Math.round`` (Python's ``round`` rounds half
|
|
147
|
+
to even); ages are whole seconds, never negative.
|
|
139
148
|
"""
|
|
140
149
|
history = [
|
|
141
|
-
[
|
|
150
|
+
[
|
|
151
|
+
item,
|
|
152
|
+
math.floor(min(weight, MAX_REQUEST_WEIGHT) * 1e4 + 0.5) / 1e4,
|
|
153
|
+
max(0, math.floor((now - t) / 1000)),
|
|
154
|
+
]
|
|
142
155
|
for item, weight, t in self.ranked(now)[:TOP_K]
|
|
143
156
|
]
|
|
144
157
|
recent = [item for item, _ in self.recent[-RECENT_SIZE:]]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.9
|
|
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.9-py3-none-any.whl
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -210,7 +210,7 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
210
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
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
|
-
| `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
|
+
| `upsert_items(items, *, merge=False)` | 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. With `merge=True` only the fields an item has are sent and changed, the others keep their stored values (a tags-only sync keeps titles and metadata); to clear a field, replace the item or set it to `None`, which resets it to its default. A bad item doesn't keep the others out: once all are sent, `recapi.RejectedItemsError` (a `RecapiError`, code `invalid_request`) lists them in `rejected` as `(index, error)` pairs, with the count stored in `upserted` |
|
|
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 |
|
|
215
215
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
216
216
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -329,6 +329,38 @@ class ClientVectors(APITest):
|
|
|
329
329
|
sent = [e.get("recommendation_id") for b in self.api.events() for e in b]
|
|
330
330
|
self.assertEqual(sent, [case["attributed"], kept[1]])
|
|
331
331
|
|
|
332
|
+
def test_a_stored_time_ahead_or_a_huge_weight_keeps_the_list(self) -> None:
|
|
333
|
+
vectors = VECTORS["stored_state"]
|
|
334
|
+
self.clock = vectors["now_ms"]
|
|
335
|
+
|
|
336
|
+
def not_json(name: str) -> None:
|
|
337
|
+
self.fail(f"the state saved {name}, which isn't JSON")
|
|
338
|
+
|
|
339
|
+
for case in vectors["history_cases"]:
|
|
340
|
+
with self.subTest(case["name"]):
|
|
341
|
+
self.api.calls.clear()
|
|
342
|
+
store = recapi.MemoryStore()
|
|
343
|
+
client = self.client(store=store)
|
|
344
|
+
key = client._key("u", None)
|
|
345
|
+
top = [case["entry"], *vectors["rest"]]
|
|
346
|
+
history = {**vectors["history"], "top": top}
|
|
347
|
+
store.set(key, json.dumps({"history": history, "shown": [], "restored": True}))
|
|
348
|
+
self.assertFalse(client.recommend(user_id="u").fallback)
|
|
349
|
+
self.assertEqual(self.api.paths(), ["/v1/recommendations"])
|
|
350
|
+
sent = self.api.calls[0].body["history"]
|
|
351
|
+
self.assertEqual(len(sent), len(case["sent"]))
|
|
352
|
+
for got, want in zip(sent, case["sent"], strict=True):
|
|
353
|
+
self.assertEqual(got[:2], want[:2])
|
|
354
|
+
self.assertLessEqual(got[1], vectors["max_request_weight"])
|
|
355
|
+
if want[2] is None:
|
|
356
|
+
self.assertGreaterEqual(got[2], 0)
|
|
357
|
+
else:
|
|
358
|
+
self.assertEqual(got[2], want[2])
|
|
359
|
+
client.track("d", 3, user_id="u")
|
|
360
|
+
client.track("h", 3, user_id="u")
|
|
361
|
+
saved = json.loads(store.get(key), parse_constant=not_json)
|
|
362
|
+
self.assertIn("o", [entry[0] for entry in saved["history"]["top"]])
|
|
363
|
+
|
|
332
364
|
def test_identify(self) -> None:
|
|
333
365
|
vectors = VECTORS["identify"]
|
|
334
366
|
now = vectors["now_ms"]
|
|
@@ -373,3 +405,25 @@ class ClientVectors(APITest):
|
|
|
373
405
|
]
|
|
374
406
|
attributed = [[e["item_id"], e.get("recommendation_id")] for e in events]
|
|
375
407
|
self.assertEqual(attributed, case["attributed"])
|
|
408
|
+
|
|
409
|
+
def test_vector_upsert_items(self) -> None:
|
|
410
|
+
vectors = VECTORS["upsert_items"]
|
|
411
|
+
for case in vectors["cases"]:
|
|
412
|
+
with self.subTest(case=case["name"]):
|
|
413
|
+
self.api.calls.clear()
|
|
414
|
+
replies = iter(case["replies"])
|
|
415
|
+
self.api.on("/v1/items:batch", lambda call, r=replies: Reply(200, next(r)))
|
|
416
|
+
items = [{"item_id": f"i{k}", **vectors["item"]} for k in range(case["count"])]
|
|
417
|
+
rejected = None
|
|
418
|
+
try:
|
|
419
|
+
got = self.client().upsert_items(items, merge=case["merge"])
|
|
420
|
+
except recapi.RejectedItemsError as error:
|
|
421
|
+
self.assertEqual(error.code, "invalid_request")
|
|
422
|
+
got, rejected = error.upserted, [list(r) for r in error.rejected]
|
|
423
|
+
bodies = [c.body for c in self.api.calls if c.path == "/v1/items:batch"]
|
|
424
|
+
self.assertEqual([len(b["items"]) for b in bodies], case["sizes"])
|
|
425
|
+
for body in bodies: # true when asked, else absent
|
|
426
|
+
self.assertEqual(body.get("merge", "absent"), case["merge"] or "absent")
|
|
427
|
+
self.assertEqual([it for b in bodies for it in b["items"]], items)
|
|
428
|
+
self.assertEqual(got, case["upserted"])
|
|
429
|
+
self.assertEqual(rejected, case["rejected"] or None)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|