recapi 0.4.5__tar.gz → 0.4.7__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: recapi
3
- Version: 0.4.5
3
+ Version: 0.4.7
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.5-py3-none-any.whl
40
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.7-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 level |
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.5-py3-none-any.whl
30
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.7-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 level |
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.5"
7
+ version = "0.4.7"
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.5"
32
+ __version__ = "0.4.7"
33
33
 
34
34
  log = logging.getLogger("recapi")
35
35
  Tags = Sequence[str] | None
@@ -311,11 +311,7 @@ class _UserState:
311
311
  try:
312
312
  data = json.loads(raw)
313
313
  history = History.decode(data["history"])
314
- shown = {
315
- e[0]: list(e[1:])
316
- for e in data["shown"]
317
- if isinstance(e, list) and 3 <= len(e) <= 4 and is_id(e[0])
318
- }
314
+ shown = {e[0]: list(e[1:]) for e in data["shown"] if _is_shown_entry(e)}
319
315
  except (ValueError, KeyError, TypeError):
320
316
  history = None
321
317
  if history is None:
@@ -327,6 +323,18 @@ class _UserState:
327
323
  )
328
324
 
329
325
 
326
+ def _is_shown_entry(e: object) -> bool:
327
+ # Bad types here would raise much later, in track() on the shop's page, or
328
+ # refuse a whole batch of events at the API.
329
+ return (
330
+ isinstance(e, list)
331
+ and 3 <= len(e) <= 4
332
+ and is_id(e[0])
333
+ and isinstance(e[1], str)
334
+ and all(type(t) is int and abs(t) < 2**63 for t in e[2:])
335
+ )
336
+
337
+
330
338
  def _attributable(entry: Sequence[Any], t: int) -> bool:
331
339
  if len(entry) < 3:
332
340
  return t - entry[1] <= DISPLAY_WINDOW_MS
@@ -425,12 +433,22 @@ class Client:
425
433
  ``level`` is an integer -10 to 10 or ``view`` (3), ``cart`` (5),
426
434
  ``purchase`` (10), ``reject`` (-10: never recommend the item to this
427
435
  user again until a positive event on it). ``recommendation_id``
428
- overrides the automatic attribution.
436
+ overrides the automatic attribution. Raises ``ValueError`` on a bad level
437
+ or a bad user, visitor or recommendation id. An ``item_id`` the API would
438
+ refuse isn't one: a page often takes it from a visitor's URL, so the
439
+ event is dropped and logged instead.
429
440
  """
430
441
  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
442
  _check_ids(user_id=user_id, anon_id=anon_id, recommendation_id=recommendation_id)
443
+ # A crafted link must not fail the page. Nothing is kept: in the history
444
+ # it would make the API refuse every later list. The line never quotes
445
+ # the visitor's id.
446
+ if not is_id(item_id):
447
+ log.warning(
448
+ "recapi: event dropped: item_id must be 1-256 bytes of UTF-8 "
449
+ "without control characters"
450
+ )
451
+ return
434
452
  t = _now_ms()
435
453
  attributed = recommendation_id
436
454
  key = self._key(user_id, anon_id)
@@ -597,8 +615,10 @@ class Client:
597
615
  those fail too (recapi is down, or the plan's limit covers them), the
598
616
  list is empty: hide the slot. On a 401 or 403 (a revoked key, a
599
617
  suspended shop) it is empty at once, as popular would be refused too.
600
- Any other failure raises: a bad request or a reply that isn't the API's
601
- can't start on a live site without a deploy.
618
+ A ``context_item_id`` the API would refuse (a page often takes it from a
619
+ visitor's URL, and it may be no string at all) is never sent: the answer
620
+ is the same popular list. Any other failure raises: a bad request or a
621
+ reply that isn't the API's can't start on a live site without a deploy.
602
622
  """
603
623
  return self._recommend(
604
624
  time.monotonic() + self._recommend_timeout,
@@ -639,6 +659,17 @@ class Client:
639
659
  key = self._key(user_id, anon_id)
640
660
  t = _now_ms()
641
661
  state = self._load(key) if key is not None else _UserState()
662
+ if not _usable_context(context_item_id):
663
+ _, _, rejected = state.history.wire(t)
664
+ # The message never quotes the id: a visitor may have written it.
665
+ # No id goes on to the fallback: no item can have this one.
666
+ cause = RecapiError(
667
+ "invalid_request",
668
+ "context_item_id must be 1-256 bytes of UTF-8 without control characters",
669
+ )
670
+ return self._fallback(
671
+ cause, rejected, count=count, tags_any=tags_any, tags_all=tags_all, exclude=exclude
672
+ )
642
673
  if (
643
674
  user_id
644
675
  and not state.restored
@@ -672,34 +703,15 @@ class Client:
672
703
  except RecapiError as error:
673
704
  if not error._spare_the_page:
674
705
  raise
675
- if error._key_refused:
676
- log.warning(
677
- "recapi: recommendations refused, served no items: %s: %s", error.code, error
678
- )
679
- return Recommendations(None, True, [])
680
- # The requested length without the excluded items, so a few more
681
- # are asked for. 0 is the recommendations default; popular refuses it.
682
- n = count or DEFAULT_COUNT
683
- skip = set(_with_rejected(exclude, rejected) or ())
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)
706
+ return self._fallback(
707
+ error,
708
+ rejected,
709
+ count=count,
710
+ tags_any=tags_any,
711
+ tags_all=tags_all,
712
+ exclude=exclude,
713
+ context_item_id=context_item_id,
714
+ )
703
715
 
704
716
  if key is not None:
705
717
  with self._lock_for(key):
@@ -720,6 +732,50 @@ class Client:
720
732
  self._save(key, state, t)
721
733
  return Recommendations(rec_id, False, items)
722
734
 
735
+ def _fallback(
736
+ self,
737
+ error: RecapiError,
738
+ rejected: list[str],
739
+ *,
740
+ count: int,
741
+ tags_any: Tags,
742
+ tags_all: Tags,
743
+ exclude: Tags,
744
+ context_item_id: str | None = None,
745
+ ) -> Recommendations:
746
+ """What recommend() answers instead of a list of its own: popular items, or none."""
747
+ if error._key_refused:
748
+ log.warning(
749
+ "recapi: recommendations refused, served no items: %s: %s", error.code, error
750
+ )
751
+ return Recommendations(None, True, [])
752
+ # The requested length without the excluded items, so a few more
753
+ # are asked for. 0 is the recommendations default; popular refuses it.
754
+ n = count or DEFAULT_COUNT
755
+ skip = set(_with_rejected(exclude, rejected) or ())
756
+ if context_item_id is not None:
757
+ skip.add(context_item_id)
758
+ try:
759
+ popular = self._popular(
760
+ min(n + len(skip), MAX_COUNT), tags_any, tags_all, self._recommend_timeout
761
+ )
762
+ except RecapiError as fallback_error:
763
+ # recapi is down or the limit covers popular too. The README
764
+ # promises no try/except, so an empty list the page can hide
765
+ # beats an exception that fails the whole page.
766
+ log.warning(
767
+ "recapi: recommendations failed (%s: %s), popular too, served no items: %s",
768
+ error.code,
769
+ error,
770
+ fallback_error,
771
+ )
772
+ return Recommendations(None, True, [])
773
+ log.warning(
774
+ "recapi: recommendations failed, served popular items: %s: %s", error.code, error
775
+ )
776
+ items = [item for item in popular if item.item_id not in skip][:n]
777
+ return Recommendations(None, True, items)
778
+
723
779
  def _restore(
724
780
  self, key: str, user_id: str, state: _UserState, deadline: float, t: int
725
781
  ) -> _UserState:
@@ -1124,6 +1180,11 @@ def _check_ids(**ids: str | None) -> None:
1124
1180
  raise ValueError(f"{name} must be 1-256 bytes of UTF-8 without control characters")
1125
1181
 
1126
1182
 
1183
+ def _usable_context(value: object) -> bool:
1184
+ # An id, or nothing: an empty string reads as no context item.
1185
+ return value is None or is_id(value) or (isinstance(value, str) and not value)
1186
+
1187
+
1127
1188
  def _list(values: Sequence[str] | None) -> list[str] | None:
1128
1189
  return list(values) if values else None
1129
1190
 
@@ -9,6 +9,7 @@ from __future__ import annotations
9
9
  import copy
10
10
  import math
11
11
  import re
12
+ import sys
12
13
  from typing import Any
13
14
 
14
15
  HALF_LIFE_SECONDS = 604800
@@ -41,7 +42,13 @@ def _is_weight(value: object) -> bool:
41
42
 
42
43
 
43
44
  def _is_time(value: object) -> bool:
44
- return isinstance(value, int | float) and not isinstance(value, bool) and math.isfinite(value)
45
+ # Compared, not converted: a stored 400-digit integer raises OverflowError in
46
+ # math.isfinite, and every later float() would too. NaN and inf fail the bound.
47
+ return (
48
+ isinstance(value, int | float)
49
+ and not isinstance(value, bool)
50
+ and abs(value) <= sys.float_info.max
51
+ )
45
52
 
46
53
 
47
54
  class History:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: recapi
3
- Version: 0.4.5
3
+ Version: 0.4.7
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.5-py3-none-any.whl
40
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.7-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 level |
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("é" * 129, 3)
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:
@@ -516,6 +577,60 @@ class Store(APITest):
516
577
  [e.get("recommendation_id") for e in self.api.events()[0]], [None, None, "rec_1"]
517
578
  )
518
579
 
580
+ def test_a_stored_time_too_big_for_a_float_discards_the_state(self) -> None:
581
+ store = recapi.MemoryStore()
582
+ client = self.client(store=store)
583
+ key = client._key("u", None)
584
+ big = 10**400
585
+ for history in (
586
+ {"top": [["a", 1, big]], "recent": [], "rejected": [], "lastT": None},
587
+ {"top": [["a", big, T0]], "recent": [], "rejected": [], "lastT": None},
588
+ {"top": [], "recent": [["a", big]], "rejected": [], "lastT": None},
589
+ {"top": [], "recent": [], "rejected": [["a", big]], "lastT": None},
590
+ {"top": [], "recent": [], "rejected": [], "lastT": big},
591
+ ):
592
+ with self.subTest(history=history):
593
+ store.set(key, json.dumps({"history": history, "shown": []}))
594
+ with self.assertLogs("recapi", "WARNING"):
595
+ client.track("i", 3, user_id="u")
596
+ self.assertEqual(
597
+ [e[0] for e in json.loads(store.get(key))["history"]["top"]], ["i"]
598
+ )
599
+
600
+ def test_a_stored_entry_of_the_wrong_types_is_dropped(self) -> None:
601
+ store = recapi.MemoryStore()
602
+ client = self.client(store=store)
603
+ key = client._key("u", None)
604
+ for entry in (
605
+ ["i", "rec_1", "oops"],
606
+ ["i", "rec_1", None],
607
+ ["i", "rec_1", T0, "x"],
608
+ ["i", 5, T0],
609
+ ):
610
+ store.set(key, json.dumps({"history": History().encode(), "shown": [entry]}))
611
+ client.track("i", 3, user_id="u")
612
+ client.flush()
613
+ self.assertEqual([e.get("recommendation_id") for e in self.api.events()[0]], [None] * 4)
614
+
615
+ def test_only_a_stored_true_marks_the_history_restored(self) -> None:
616
+ # Anything else asks recapi again: skipping the fetch would lose a
617
+ # returning user's history for good.
618
+ for flag, fetched in ((True, False), (1, True), ("true", True)):
619
+ with self.subTest(flag=flag):
620
+ before = len(self.api.paths())
621
+ store = recapi.MemoryStore()
622
+ client = self.client(store=store)
623
+ history = {
624
+ "top": [["s", 3.0, T0]],
625
+ "recent": [["s", T0]],
626
+ "rejected": [],
627
+ "lastT": T0,
628
+ }
629
+ state = {"history": history, "shown": [], "restored": flag}
630
+ store.set(client._key("u", None), json.dumps(state))
631
+ client.recommend(user_id="u")
632
+ self.assertEqual("/v1/users/u/history" in self.api.paths()[before:], fetched)
633
+
519
634
  def test_the_memory_store_keeps_the_most_recently_used_users(self) -> None:
520
635
  store = recapi.MemoryStore(max_users=2)
521
636
  store.set("a", "1")
@@ -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
- with self.assertRaises(ValueError):
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):
@@ -272,6 +308,27 @@ class ClientVectors(APITest):
272
308
  sent = {k: body.get(k) for k in ("history", "recent", "exclude")}
273
309
  self.assertEqual(sent, case["sent"])
274
310
 
311
+ def test_a_stored_entry_of_the_wrong_types_is_dropped(self) -> None:
312
+ vectors = VECTORS["stored_state"]
313
+ self.clock = vectors["now_ms"]
314
+ kept = vectors["kept"]
315
+ for case in vectors["cases"]:
316
+ with self.subTest(case=case):
317
+ self.api.calls.clear()
318
+ store = recapi.MemoryStore()
319
+ client = self.client(store=store)
320
+ shown = [case["entry"], kept]
321
+ store.set(
322
+ client._key("u", None),
323
+ json.dumps({"history": vectors["history"], "shown": shown}),
324
+ )
325
+ with self.assertNoLogs("recapi"):
326
+ client.track("i", 3, user_id="u")
327
+ client.track(kept[0], 3, user_id="u")
328
+ client.flush()
329
+ sent = [e.get("recommendation_id") for b in self.api.events() for e in b]
330
+ self.assertEqual(sent, [case["attributed"], kept[1]])
331
+
275
332
  def test_identify(self) -> None:
276
333
  vectors = VECTORS["identify"]
277
334
  now = vectors["now_ms"]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes