recapi 0.4.3__tar.gz → 0.4.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: recapi
3
- Version: 0.4.3
3
+ Version: 0.4.5
4
4
  Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
5
5
  License: MIT
6
6
  Requires-Python: >=3.11
@@ -37,7 +37,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
37
37
  (the dashboard's quick start shows the line with your API's address):
38
38
 
39
39
  ```sh
40
- pip install https://api.<your-domain>/sdk/python/recapi-0.4.3-py3-none-any.whl
40
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.5-py3-none-any.whl
41
41
  ```
42
42
 
43
43
  To work on the library itself, install it from a checkout of this repository
@@ -61,9 +61,10 @@ client.upsert_items([item])
61
61
  # The user opened an item (level 3). Queued and sent in the background.
62
62
  client.track("item-42", "view", user_id="user-881")
63
63
 
64
- # Recommendations for that user. If recapi is slow or failing, this returns
65
- # popular items instead (result.fallback is True), and an empty list if
66
- # recapi is down altogether (hide the slot): no try/except.
64
+ # Recommendations for that user. If recapi is slow or failing or a limit is
65
+ # reached, this returns popular items instead (result.fallback is True), and an
66
+ # empty list if those fail too or the key is refused (hide the slot): no
67
+ # try/except.
67
68
  # item.why says why it is listed, safe to show anyone (docs/api.md, "Reason
68
69
  # codes"): pick your own words, no label for codes you don't map.
69
70
  LABELS = {
@@ -104,11 +105,11 @@ By default each process keeps its users' state in memory (the 10,000 most
104
105
  recently seen users). That is enough for one process. When several
105
106
  processes or servers serve the same users, give them a shared store: any
106
107
  object with `get(key)`, `set(key, value)` (strings) and `delete(key)` works,
107
- such as a Redis client or Django's cache.
108
+ such as a Redis client or Django's Redis or Memcached cache.
108
109
 
109
110
  ```python
110
111
  client = recapi.Client("rk_sec_…", "https://api.example.com", store=redis.Redis())
111
- # or, in Django (from django.core.cache import cache):
112
+ # or, in Django with one of those caches (from django.core.cache import cache):
112
113
  client = recapi.Client("rk_sec_…", "https://api.example.com", store=cache)
113
114
  ```
114
115
 
@@ -118,8 +119,16 @@ earns credit, and recapi gives a known `user_id` its history back afterwards.
118
119
  Without it, Django would drop the state after its default 5 minutes, taking the
119
120
  click's credit with it, and Redis would keep it for ever. Any other store gets a
120
121
  plain `set(key, value)`: make it expire entries itself after about 30 days.
121
- Django's default `LocMemCache` isn't shared between processes and holds 300
122
- entries: configure its Redis or Memcached backend for several processes.
122
+
123
+ Not every Django cache can hold this. The library recognises Django's own
124
+ classes (a subclass of one is left alone) and logs one line at start:
125
+
126
+ | Django cache | What happens | Shared between |
127
+ |---|---|---|
128
+ | `RedisCache`, `PyMemcacheCache`, `PyLibMCCache` | used, no line | servers |
129
+ | `FileBasedCache` | used, with a warning: it holds 300 entries by default | one server's processes |
130
+ | `LocMemCache` (Django's default) | the library's own store instead, with a warning | nothing |
131
+ | `DummyCache` | the library's own store instead, with a warning | nothing |
123
132
 
124
133
  A user the store doesn't know yet (a new process, an evicted user, another
125
134
  server) still gets personalised results: the request then has no history,
@@ -199,8 +208,8 @@ one recommendation id collects the events of many users ("Page caches").
199
208
  | Method | What it does |
200
209
  |---|---|
201
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 |
202
- | `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` |
203
- | `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user |
211
+ | `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. Any other failure (a bad request, a reply that isn't the API's) raises |
212
+ | `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
204
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 |
205
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 |
206
215
  | `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
@@ -209,11 +218,15 @@ one recommendation id collects the events of many users ("Page caches").
209
218
  `Client(api_key, base_url, *, store=None, timeout=5.0, flush_interval=2.0,
210
219
  max_batch=1000)`: `timeout` per request in seconds (`recommend` waits at most
211
220
  1.5 s). `AsyncClient` takes the same arguments. Errors are `recapi.RecapiError` (`code`, `status`, `retryable`);
212
- `recommend` raises only on a 3xx, 4xx or 429, or a reply that isn't the API's
213
- (`invalid_response`, such as a `base_url` pointing at a web page): a fallback
214
- would hide them. On a
215
- network error, a timeout or a 5xx it returns popular items, or an empty list
216
- when `/v1/popular` fails too, and logs the errors.
221
+ `recommend` and `popular` raise only on a bad request (400, 404, 413, other
222
+ 3xx/4xx) or a reply that isn't the API's (`invalid_response`, such as a
223
+ `base_url` pointing at a web page): neither can start on a live site without a
224
+ deploy. On a network error, a timeout, a 5xx or a 429 `recommend` returns popular
225
+ items, or an empty list when `/v1/popular` fails too; on a 401 or 403 (a revoked
226
+ key, a suspended shop) an empty list at once, as `/v1/popular` would refuse the
227
+ same key; `popular` returns an empty list for all of these. Each failed call logs
228
+ one warning with the API's message to the `recapi` logger: a wrong key shows
229
+ there, not as an exception.
217
230
  Background failures go to the `recapi` logger: refused events are dropped, a
218
231
  batch that can succeed later is retried with backoff (up to 10,000 queued).
219
232
 
@@ -27,7 +27,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
27
27
  (the dashboard's quick start shows the line with your API's address):
28
28
 
29
29
  ```sh
30
- pip install https://api.<your-domain>/sdk/python/recapi-0.4.3-py3-none-any.whl
30
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.5-py3-none-any.whl
31
31
  ```
32
32
 
33
33
  To work on the library itself, install it from a checkout of this repository
@@ -51,9 +51,10 @@ client.upsert_items([item])
51
51
  # The user opened an item (level 3). Queued and sent in the background.
52
52
  client.track("item-42", "view", user_id="user-881")
53
53
 
54
- # Recommendations for that user. If recapi is slow or failing, this returns
55
- # popular items instead (result.fallback is True), and an empty list if
56
- # recapi is down altogether (hide the slot): no try/except.
54
+ # Recommendations for that user. If recapi is slow or failing or a limit is
55
+ # reached, this returns popular items instead (result.fallback is True), and an
56
+ # empty list if those fail too or the key is refused (hide the slot): no
57
+ # try/except.
57
58
  # item.why says why it is listed, safe to show anyone (docs/api.md, "Reason
58
59
  # codes"): pick your own words, no label for codes you don't map.
59
60
  LABELS = {
@@ -94,11 +95,11 @@ By default each process keeps its users' state in memory (the 10,000 most
94
95
  recently seen users). That is enough for one process. When several
95
96
  processes or servers serve the same users, give them a shared store: any
96
97
  object with `get(key)`, `set(key, value)` (strings) and `delete(key)` works,
97
- such as a Redis client or Django's cache.
98
+ such as a Redis client or Django's Redis or Memcached cache.
98
99
 
99
100
  ```python
100
101
  client = recapi.Client("rk_sec_…", "https://api.example.com", store=redis.Redis())
101
- # or, in Django (from django.core.cache import cache):
102
+ # or, in Django with one of those caches (from django.core.cache import cache):
102
103
  client = recapi.Client("rk_sec_…", "https://api.example.com", store=cache)
103
104
  ```
104
105
 
@@ -108,8 +109,16 @@ earns credit, and recapi gives a known `user_id` its history back afterwards.
108
109
  Without it, Django would drop the state after its default 5 minutes, taking the
109
110
  click's credit with it, and Redis would keep it for ever. Any other store gets a
110
111
  plain `set(key, value)`: make it expire entries itself after about 30 days.
111
- Django's default `LocMemCache` isn't shared between processes and holds 300
112
- entries: configure its Redis or Memcached backend for several processes.
112
+
113
+ Not every Django cache can hold this. The library recognises Django's own
114
+ classes (a subclass of one is left alone) and logs one line at start:
115
+
116
+ | Django cache | What happens | Shared between |
117
+ |---|---|---|
118
+ | `RedisCache`, `PyMemcacheCache`, `PyLibMCCache` | used, no line | servers |
119
+ | `FileBasedCache` | used, with a warning: it holds 300 entries by default | one server's processes |
120
+ | `LocMemCache` (Django's default) | the library's own store instead, with a warning | nothing |
121
+ | `DummyCache` | the library's own store instead, with a warning | nothing |
113
122
 
114
123
  A user the store doesn't know yet (a new process, an evicted user, another
115
124
  server) still gets personalised results: the request then has no history,
@@ -189,8 +198,8 @@ one recommendation id collects the events of many users ("Page caches").
189
198
  | Method | What it does |
190
199
  |---|---|
191
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 |
192
- | `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` |
193
- | `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user |
201
+ | `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. Any other failure (a bad request, a reply that isn't the API's) raises |
202
+ | `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
194
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 |
195
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 |
196
205
  | `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
@@ -199,11 +208,15 @@ one recommendation id collects the events of many users ("Page caches").
199
208
  `Client(api_key, base_url, *, store=None, timeout=5.0, flush_interval=2.0,
200
209
  max_batch=1000)`: `timeout` per request in seconds (`recommend` waits at most
201
210
  1.5 s). `AsyncClient` takes the same arguments. Errors are `recapi.RecapiError` (`code`, `status`, `retryable`);
202
- `recommend` raises only on a 3xx, 4xx or 429, or a reply that isn't the API's
203
- (`invalid_response`, such as a `base_url` pointing at a web page): a fallback
204
- would hide them. On a
205
- network error, a timeout or a 5xx it returns popular items, or an empty list
206
- when `/v1/popular` fails too, and logs the errors.
211
+ `recommend` and `popular` raise only on a bad request (400, 404, 413, other
212
+ 3xx/4xx) or a reply that isn't the API's (`invalid_response`, such as a
213
+ `base_url` pointing at a web page): neither can start on a live site without a
214
+ deploy. On a network error, a timeout, a 5xx or a 429 `recommend` returns popular
215
+ items, or an empty list when `/v1/popular` fails too; on a 401 or 403 (a revoked
216
+ key, a suspended shop) an empty list at once, as `/v1/popular` would refuse the
217
+ same key; `popular` returns an empty list for all of these. Each failed call logs
218
+ one warning with the API's message to the `recapi` logger: a wrong key shows
219
+ there, not as an exception.
207
220
  Background failures go to the `recapi` logger: refused events are dropped, a
208
221
  batch that can succeed later is retried with backoff (up to 10,000 queued).
209
222
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "recapi"
7
- version = "0.4.3"
7
+ version = "0.4.5"
8
8
  description = "Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -29,7 +29,7 @@ from typing import Any, Protocol
29
29
 
30
30
  from .history import History, is_id
31
31
 
32
- __version__ = "0.4.3"
32
+ __version__ = "0.4.5"
33
33
 
34
34
  log = logging.getLogger("recapi")
35
35
  Tags = Sequence[str] | None
@@ -73,6 +73,14 @@ _REDIS_PY_SET = {
73
73
  ("redis.client", "Redis.set"),
74
74
  }
75
75
  _DJANGO_CACHE = ("django.core.cache.backends.base", "BaseCache")
76
+ # Django's caches that lose visitors' state, by exact class: a subclass may have
77
+ # changed what makes them so. They keep nothing or only in this process, where
78
+ # our MemoryStore is as local, holds more and competes with nothing in the app.
79
+ _DJANGO_USE_OURS = {
80
+ ("django.core.cache.backends.dummy", "DummyCache"): "keeps nothing",
81
+ ("django.core.cache.backends.locmem", "LocMemCache"): "keeps its entries in this process only",
82
+ }
83
+ _DJANGO_FILES = ("django.core.cache.backends.filebased", "FileBasedCache")
76
84
  PUBLIC_KEY_PREFIX = "rk_pub_"
77
85
  # Open connections kept between calls: one per call in flight at the busiest
78
86
  # moment (AsyncClient runs 8 at once), so a burst of threads can't leave
@@ -128,13 +136,22 @@ class RecapiError(Exception):
128
136
 
129
137
  @property
130
138
  def outage(self) -> bool:
131
- """Whether recapi couldn't answer in time or failed on its side.
132
-
133
- A 429 is the tenant's own limit and a 4xx an integration bug: a
134
- fallback would hide both.
135
- """
139
+ """Whether recapi couldn't answer in time or failed on its side."""
136
140
  return self.code in ("network", "timeout") or self.status >= 500
137
141
 
142
+ @property
143
+ def _spare_the_page(self) -> bool:
144
+ # An outage, a limit or a revoked key can start on a live site with no
145
+ # deploy, and a page must not pay for it: the log and the dashboard show
146
+ # it. What's left (a bad request, a reply that isn't the API's) can't
147
+ # start without a deploy, and a developer sees it on the first run.
148
+ return self.outage or self.status == 429 or self._key_refused
149
+
150
+ @property
151
+ def _key_refused(self) -> bool:
152
+ # A key or shop recapi won't serve: any other call fails too.
153
+ return self.status in (401, 403)
154
+
138
155
 
139
156
  @dataclass(frozen=True)
140
157
  class Item:
@@ -198,6 +215,35 @@ def _lifetime_argument(store: Store) -> dict[str, int]:
198
215
  return {}
199
216
 
200
217
 
218
+ def _store_to_use(store: Store) -> Store:
219
+ """Return ``store``, or our own in its place if it is a Django cache that loses state.
220
+
221
+ Says so in one line, at start only. Any doubt, or a store that fails here
222
+ (Django's ``cache`` reads the settings at this first touch), means ``store``.
223
+ """
224
+ try:
225
+ # As in _lifetime_argument: only the bound method leads to Django's backend.
226
+ backend = type(getattr(store.set, "__self__", None))
227
+ name = (backend.__module__, backend.__qualname__)
228
+ if name in _DJANGO_USE_OURS:
229
+ log.warning(
230
+ "recapi: Django's %s %s, so recapi uses its own in-process store (10,000 users)."
231
+ " For several processes or servers, configure Django's Redis or Memcached cache.",
232
+ name[1],
233
+ _DJANGO_USE_OURS[name],
234
+ )
235
+ return MemoryStore()
236
+ if name == _DJANGO_FILES:
237
+ log.warning(
238
+ "recapi: Django's FileBasedCache isn't shared between servers and holds 300"
239
+ " entries by default. For several servers or more visitors, configure Django's"
240
+ " Redis or Memcached cache.",
241
+ )
242
+ except Exception:
243
+ return store
244
+ return store
245
+
246
+
201
247
  class MemoryStore:
202
248
  """In-process store keeping the most recently used ``max_users`` users."""
203
249
 
@@ -295,7 +341,8 @@ class Client:
295
341
  user's history from recapi when the store lacks it.
296
342
  base_url: Your recapi API origin, e.g. ``https://api.example.com``.
297
343
  store: Per-user history and attribution state; defaults to an
298
- in-memory :class:`MemoryStore`. Pass a shared store (Redis...) when
344
+ in-memory :class:`MemoryStore`, which also replaces Django's
345
+ ``LocMemCache`` and ``DummyCache``. Pass a shared store (Redis...) when
299
346
  several processes serve the same users.
300
347
  timeout: Per-request timeout in seconds (recommend() uses at most 1.5).
301
348
  flush_interval: Seconds between background event sends.
@@ -332,7 +379,7 @@ class Client:
332
379
  self._proxy_auth = _basic_auth(self._proxy)
333
380
  # Through a plain HTTP proxy, a request names the whole URL.
334
381
  self._target_base = self._base if self._proxy and url.scheme == "http" else url.path
335
- self._store: Store = store if store is not None else MemoryStore()
382
+ self._store: Store = _store_to_use(store) if store is not None else MemoryStore()
336
383
  self._timeout = timeout
337
384
  self._interval = flush_interval
338
385
  self._max_batch = min(max(1, max_batch), MAX_EVENTS_PER_REQUEST)
@@ -545,10 +592,13 @@ class Client:
545
592
  history for ``user_id`` and returns it for the store. A history the
546
593
  store started without it (a ``track()`` or ``identify()`` came first)
547
594
  gets recapi's fetched once, within the same deadline, and merged in.
548
- No retry, at most 1.5 s: on a network error, timeout or 5xx it returns
549
- popular items (``fallback=True``, no id) and logs the error. If those
550
- fail too (recapi is down), the list is empty: hide the slot. A 4xx or
551
- 429 raises: a fallback would hide an integration bug or a plan limit.
595
+ No retry, at most 1.5 s: on a network error, timeout, 5xx or 429 it
596
+ returns popular items (``fallback=True``, no id) and logs the error. If
597
+ those fail too (recapi is down, or the plan's limit covers them), the
598
+ list is empty: hide the slot. On a 401 or 403 (a revoked key, a
599
+ suspended shop) it is empty at once, as popular would be refused too.
600
+ Any other failure raises: a bad request or a reply that isn't the API's
601
+ can't start on a live site without a deploy.
552
602
  """
553
603
  return self._recommend(
554
604
  time.monotonic() + self._recommend_timeout,
@@ -620,8 +670,13 @@ class Client:
620
670
  )
621
671
  rec_id, items = _parse_recommendations(response)
622
672
  except RecapiError as error:
623
- if not error.outage:
673
+ if not error._spare_the_page:
624
674
  raise
675
+ if error._key_refused:
676
+ log.warning(
677
+ "recapi: recommendations refused, served no items: %s: %s", error.code, error
678
+ )
679
+ return Recommendations(None, True, [])
625
680
  # The requested length without the excluded items, so a few more
626
681
  # are asked for. 0 is the recommendations default; popular refuses it.
627
682
  n = count or DEFAULT_COUNT
@@ -633,9 +688,9 @@ class Client:
633
688
  min(n + len(skip), MAX_COUNT), tags_any, tags_all, self._recommend_timeout
634
689
  )
635
690
  except RecapiError as fallback_error:
636
- # recapi is down altogether. The README promises no
637
- # try/except, so an empty list the page can hide beats an
638
- # exception that fails the whole page.
691
+ # recapi is down or the limit covers popular too. The README
692
+ # promises no try/except, so an empty list the page can hide
693
+ # beats an exception that fails the whole page.
639
694
  log.warning(
640
695
  "recapi: recommendations failed (%s), popular too, served no items: %s",
641
696
  error,
@@ -736,8 +791,19 @@ class Client:
736
791
  tags_any: Tags = None,
737
792
  tags_all: Tags = None,
738
793
  ) -> list[Item]:
739
- """Non-personalised popular items, for pages without a user (no retry)."""
740
- return self._popular(count, tags_any, tags_all, None)
794
+ """Non-personalised popular items, for pages without a user (no retry).
795
+
796
+ On a network error, timeout, 5xx, 429, 401 or 403 it logs the error and
797
+ returns an empty list: hide the slot. Any other failure raises, as in
798
+ :meth:`recommend`.
799
+ """
800
+ try:
801
+ return self._popular(count, tags_any, tags_all, None)
802
+ except RecapiError as error:
803
+ if not error._spare_the_page:
804
+ raise
805
+ log.warning("recapi: popular items failed, served no items: %s: %s", error.code, error)
806
+ return []
741
807
 
742
808
  def _popular(self, count: int, tags_any: Tags, tags_all: Tags, timeout: float | None) -> list:
743
809
  query = {k: ",".join(v) for k, v in (("tags_any", tags_any), ("tags_all", tags_all)) if v}
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: recapi
3
- Version: 0.4.3
3
+ Version: 0.4.5
4
4
  Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
5
5
  License: MIT
6
6
  Requires-Python: >=3.11
@@ -37,7 +37,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
37
37
  (the dashboard's quick start shows the line with your API's address):
38
38
 
39
39
  ```sh
40
- pip install https://api.<your-domain>/sdk/python/recapi-0.4.3-py3-none-any.whl
40
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.5-py3-none-any.whl
41
41
  ```
42
42
 
43
43
  To work on the library itself, install it from a checkout of this repository
@@ -61,9 +61,10 @@ client.upsert_items([item])
61
61
  # The user opened an item (level 3). Queued and sent in the background.
62
62
  client.track("item-42", "view", user_id="user-881")
63
63
 
64
- # Recommendations for that user. If recapi is slow or failing, this returns
65
- # popular items instead (result.fallback is True), and an empty list if
66
- # recapi is down altogether (hide the slot): no try/except.
64
+ # Recommendations for that user. If recapi is slow or failing or a limit is
65
+ # reached, this returns popular items instead (result.fallback is True), and an
66
+ # empty list if those fail too or the key is refused (hide the slot): no
67
+ # try/except.
67
68
  # item.why says why it is listed, safe to show anyone (docs/api.md, "Reason
68
69
  # codes"): pick your own words, no label for codes you don't map.
69
70
  LABELS = {
@@ -104,11 +105,11 @@ By default each process keeps its users' state in memory (the 10,000 most
104
105
  recently seen users). That is enough for one process. When several
105
106
  processes or servers serve the same users, give them a shared store: any
106
107
  object with `get(key)`, `set(key, value)` (strings) and `delete(key)` works,
107
- such as a Redis client or Django's cache.
108
+ such as a Redis client or Django's Redis or Memcached cache.
108
109
 
109
110
  ```python
110
111
  client = recapi.Client("rk_sec_…", "https://api.example.com", store=redis.Redis())
111
- # or, in Django (from django.core.cache import cache):
112
+ # or, in Django with one of those caches (from django.core.cache import cache):
112
113
  client = recapi.Client("rk_sec_…", "https://api.example.com", store=cache)
113
114
  ```
114
115
 
@@ -118,8 +119,16 @@ earns credit, and recapi gives a known `user_id` its history back afterwards.
118
119
  Without it, Django would drop the state after its default 5 minutes, taking the
119
120
  click's credit with it, and Redis would keep it for ever. Any other store gets a
120
121
  plain `set(key, value)`: make it expire entries itself after about 30 days.
121
- Django's default `LocMemCache` isn't shared between processes and holds 300
122
- entries: configure its Redis or Memcached backend for several processes.
122
+
123
+ Not every Django cache can hold this. The library recognises Django's own
124
+ classes (a subclass of one is left alone) and logs one line at start:
125
+
126
+ | Django cache | What happens | Shared between |
127
+ |---|---|---|
128
+ | `RedisCache`, `PyMemcacheCache`, `PyLibMCCache` | used, no line | servers |
129
+ | `FileBasedCache` | used, with a warning: it holds 300 entries by default | one server's processes |
130
+ | `LocMemCache` (Django's default) | the library's own store instead, with a warning | nothing |
131
+ | `DummyCache` | the library's own store instead, with a warning | nothing |
123
132
 
124
133
  A user the store doesn't know yet (a new process, an evicted user, another
125
134
  server) still gets personalised results: the request then has no history,
@@ -199,8 +208,8 @@ one recommendation id collects the events of many users ("Page caches").
199
208
  | Method | What it does |
200
209
  |---|---|
201
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 |
202
- | `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` |
203
- | `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user |
211
+ | `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. Any other failure (a bad request, a reply that isn't the API's) raises |
212
+ | `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
204
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 |
205
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 |
206
215
  | `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
@@ -209,11 +218,15 @@ one recommendation id collects the events of many users ("Page caches").
209
218
  `Client(api_key, base_url, *, store=None, timeout=5.0, flush_interval=2.0,
210
219
  max_batch=1000)`: `timeout` per request in seconds (`recommend` waits at most
211
220
  1.5 s). `AsyncClient` takes the same arguments. Errors are `recapi.RecapiError` (`code`, `status`, `retryable`);
212
- `recommend` raises only on a 3xx, 4xx or 429, or a reply that isn't the API's
213
- (`invalid_response`, such as a `base_url` pointing at a web page): a fallback
214
- would hide them. On a
215
- network error, a timeout or a 5xx it returns popular items, or an empty list
216
- when `/v1/popular` fails too, and logs the errors.
221
+ `recommend` and `popular` raise only on a bad request (400, 404, 413, other
222
+ 3xx/4xx) or a reply that isn't the API's (`invalid_response`, such as a
223
+ `base_url` pointing at a web page): neither can start on a live site without a
224
+ deploy. On a network error, a timeout, a 5xx or a 429 `recommend` returns popular
225
+ items, or an empty list when `/v1/popular` fails too; on a 401 or 403 (a revoked
226
+ key, a suspended shop) an empty list at once, as `/v1/popular` would refuse the
227
+ same key; `popular` returns an empty list for all of these. Each failed call logs
228
+ one warning with the API's message to the `recapi` logger: a wrong key shows
229
+ there, not as an exception.
217
230
  Background failures go to the `recapi` logger: refused events are dropped, a
218
231
  batch that can succeed later is retried with backoff (up to 10,000 queued).
219
232
 
@@ -11,7 +11,7 @@ from pathlib import Path
11
11
  from typing import Any
12
12
 
13
13
  import recapi
14
- from fakeapi import KEY, APITest, Reply, recs
14
+ from fakeapi import KEY, APITest, Reply, dead_url, popular, recs
15
15
  from recapi import async_client
16
16
 
17
17
 
@@ -22,6 +22,33 @@ class AsyncClient(APITest):
22
22
  self.addCleanup(lambda: asyncio.run(client.close()))
23
23
  return client
24
24
 
25
+ def test_async_list_calls_keep_the_page_up(self) -> None:
26
+ client = self.async_client()
27
+ dead = recapi.AsyncClient(KEY, dead_url(), flush_interval=3600)
28
+ self.addCleanup(lambda: asyncio.run(dead.close()))
29
+
30
+ async def run() -> None:
31
+ quota = {"error": {"code": "quota_exceeded", "message": "spent"}}
32
+ self.api.on("/v1/recommendations", Reply(429, quota))
33
+ self.api.on("/v1/popular", Reply(200, popular(["p1"])))
34
+ result = await client.recommend(user_id="u")
35
+ self.assertEqual(result.recommendation_id, None)
36
+ self.assertTrue(result.fallback)
37
+ self.assertEqual([i.item_id for i in result.items], ["p1"])
38
+
39
+ self.api.calls.clear()
40
+ self.api.handler = lambda call: Reply(401)
41
+ refused = recapi.Recommendations(None, True, [])
42
+ self.assertEqual(await client.recommend(user_id="u"), refused)
43
+ self.assertEqual(self.api.paths(), ["/v1/recommendations"])
44
+ self.assertEqual(await client.popular(), [])
45
+
46
+ self.assertEqual(await dead.popular(), [])
47
+
48
+ with self.assertLogs("recapi", "WARNING") as logs:
49
+ asyncio.run(run())
50
+ self.assertEqual(len(logs.output), 4)
51
+
25
52
  def worst_loop_delay(self, recommend: Any, calls: int) -> tuple[float, list]:
26
53
  """Run ``calls`` recommend() at once next to a 10 ms ticker; return its worst lateness."""
27
54
 
@@ -702,7 +702,7 @@ class Connections(APITest):
702
702
  mock.patch.object(http.client.HTTPResponse, "read", side_effect=ConnectionResetError),
703
703
  self.assertRaises(recapi.RecapiError) as caught,
704
704
  ):
705
- client.popular() # on the reused connection: the API has the request
705
+ client._popular(1, None, None, None) # reused connection: the API has the request
706
706
  self.assertEqual(caught.exception.code, "network")
707
707
  self.assertEqual(self.api.paths(), ["/v1/popular"] * 2)
708
708
  self.assertEqual(client._idle, [])
@@ -711,8 +711,8 @@ class Connections(APITest):
711
711
 
712
712
  def test_a_dropped_request_on_a_new_connection_is_not_resent(self) -> None:
713
713
  self.api.on("/v1/popular", Reply(drop=True))
714
- with self.assertRaises(recapi.RecapiError):
715
- self.client().popular()
714
+ with self.assertLogs("recapi", "WARNING"):
715
+ self.assertEqual(self.client().popular(), [])
716
716
  self.assertEqual(self.api.paths(), ["/v1/popular"])
717
717
 
718
718
  def test_a_late_reply_is_never_read_as_the_next_calls(self) -> None:
@@ -743,7 +743,7 @@ class Connections(APITest):
743
743
  client = recapi.Client(KEY, "https://recapi.invalid")
744
744
  self.addCleanup(client.close)
745
745
  with self.assertRaises(recapi.RecapiError) as caught:
746
- client.popular() # the fake refuses the tunnel
746
+ client._popular(1, None, None, None) # the fake refuses the tunnel
747
747
  self.assertEqual(caught.exception.code, "network")
748
748
  call = self.api.calls[-1]
749
749
  self.assertEqual((call.method, call.target), ("CONNECT", "recapi.invalid:443"))
@@ -76,37 +76,78 @@ class ClientVectors(APITest):
76
76
  self.api.handler = lambda call, case=case: error_reply(case)
77
77
  client = self.client(timeout=0.2)
78
78
  with self.assertRaises(recapi.RecapiError) as caught:
79
- client.popular()
79
+ client._popular(1, None, None, None)
80
80
  error = caught.exception
81
81
  self.assertEqual(error.code, case["code"])
82
82
  self.assertEqual(error.status, case.get("status", 0))
83
83
  self.assertEqual(error.retryable, case["retryable"])
84
- self.assertEqual(error.outage, case["fallback"])
84
+ self.assertEqual(error.outage, case["outage"])
85
85
  if "retry_after_ms" in case:
86
86
  want = case["retry_after_ms"]
87
87
  self.assertEqual(error.retry_after, None if want is None else want / 1000)
88
88
 
89
- self.api.on("/v1/popular", Reply(200, popular(["p1"])))
89
+ def test_vector_list_calls_keep_the_page_up(self) -> None:
90
+ for case in VECTORS["errors"]:
91
+ with self.subTest(case=case):
92
+ self.api.handler = lambda call, case=case: error_reply(case)
93
+ client = self.client(timeout=0.2)
90
94
  if case["fallback"]:
91
- result = client.recommend(user_id="u")
92
- self.assertTrue(result.fallback)
93
- self.assertEqual([i.item_id for i in result.items], ["p1"])
94
- # Every request fails this way: recapi is down.
95
- self.api.on("/v1/popular", error_reply(case))
96
95
  with self.assertLogs("recapi", "WARNING"):
97
- result = client.recommend(user_id="u")
98
- self.assertEqual(result, recapi.Recommendations(None, True, []))
96
+ self.assertEqual(client.popular(), [])
99
97
  else:
98
+ with self.assertRaises(recapi.RecapiError) as caught:
99
+ client.popular()
100
+ self.assertEqual(caught.exception.code, case["code"])
101
+
102
+ self.api.on("/v1/popular", Reply(200, popular(["p1"])))
103
+ before = len(self.api.paths())
104
+ if not case["fallback"]:
100
105
  with self.assertRaises(recapi.RecapiError) as caught:
101
106
  client.recommend(user_id="u")
102
107
  self.assertEqual(caught.exception.code, case["code"])
103
- self.assertNotIn("/v1/popular", self.api.paths()[-1:])
108
+ self.assertEqual(self.api.paths()[before:].count("/v1/popular"), 0)
109
+ continue
110
+ with self.assertLogs("recapi", "WARNING"):
111
+ result = client.recommend(user_id="u")
112
+ asked = self.api.paths()[before:].count("/v1/popular")
113
+ self.assertEqual(asked, 1 if case["asks_popular"] else 0)
114
+ self.assertEqual([result.recommendation_id, result.fallback], [None, True])
115
+ want = ["p1"] if case["asks_popular"] else []
116
+ self.assertEqual([i.item_id for i in result.items], want)
117
+ # Every request fails this way: recapi is down, or the limit covers popular.
118
+ self.api.on("/v1/popular", error_reply(case))
119
+ with self.assertLogs("recapi", "WARNING"):
120
+ result = client.recommend(user_id="u")
121
+ self.assertEqual(result, recapi.Recommendations(None, True, []))
122
+
123
+ def test_refused_lists_stay_visible(self) -> None:
124
+ # The operator's own logger gets every refused call and filters; a
125
+ # limit here would hide lines from it.
126
+ refused = {"error": {"code": "unauthorized", "message": "from the test"}}
127
+ self.api.handler = lambda call: Reply(401, refused)
128
+ client = self.client()
129
+ with self.assertLogs("recapi", "WARNING") as logs:
130
+ for _ in range(3):
131
+ self.assertEqual(client.popular(), [])
132
+ self.assertEqual(client.recommend(user_id="u").items, [])
133
+ self.assertEqual(len(logs.output), 6)
134
+ for line in logs.output:
135
+ self.assertIn("unauthorized", line)
136
+ self.assertIn("from the test", line)
137
+
138
+ def test_a_malformed_list_still_fails(self) -> None:
139
+ self.api.handler = lambda call: Reply(200, {"items": "nope"})
140
+ client = self.client()
141
+ for call in (client.popular, lambda: client.recommend(user_id="u")):
142
+ with self.assertRaises(recapi.RecapiError) as caught:
143
+ call()
144
+ self.assertEqual(caught.exception.code, "invalid_response")
104
145
 
105
146
  def test_a_refused_connection_is_a_network_error(self) -> None:
106
147
  client = recapi.Client(KEY, dead_url())
107
148
  self.addCleanup(client.close)
108
149
  with self.assertRaises(recapi.RecapiError) as caught:
109
- client.popular()
150
+ client._popular(1, None, None, None)
110
151
  self.assertEqual(caught.exception.code, "network")
111
152
  self.assertTrue(caught.exception.retryable)
112
153
 
@@ -8,11 +8,12 @@ import os
8
8
  import socketserver
9
9
  import subprocess
10
10
  import sys
11
+ import tempfile
11
12
  import threading
12
13
  import unittest
13
14
  from pathlib import Path
14
15
  from typing import Any
15
- from unittest import mock
16
+ from unittest import addModuleCleanup, mock
16
17
 
17
18
  import recapi
18
19
  from fakeapi import KEY, APITest
@@ -35,8 +36,20 @@ def setUpModule() -> None:
35
36
 
36
37
  if not settings.configured:
37
38
  # No TIMEOUT: Django's default of 300 s is what the README's store=cache gets.
39
+ # "default" is what a new Django project has; "files" is the listed cache the
40
+ # library keeps, so it shows what happens to a store that stays.
41
+ files = tempfile.TemporaryDirectory()
42
+ addModuleCleanup(files.cleanup)
38
43
  settings.configure(
39
- CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
44
+ CACHES={
45
+ "default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"},
46
+ "files": {
47
+ "BACKEND": "django.core.cache.backends.filebased.FileBasedCache",
48
+ "LOCATION": files.name,
49
+ },
50
+ "nothing": {"BACKEND": "django.core.cache.backends.dummy.DummyCache"},
51
+ "broken": {"BACKEND": "no.such.Backend"},
52
+ }
40
53
  )
41
54
 
42
55
 
@@ -61,7 +74,8 @@ class FakeRedis:
61
74
 
62
75
  def word(self) -> str:
63
76
  size = int(self.rfile.readline()[1:])
64
- return self.rfile.read(size + 2)[:-2].decode()
77
+ # Django's Redis backend pickles values.
78
+ return self.rfile.read(size + 2)[:-2].decode("utf-8", "surrogateescape")
65
79
 
66
80
  self.server = socketserver.ThreadingTCPServer(("127.0.0.1", 0), Handler)
67
81
  self.server.daemon_threads = True
@@ -76,7 +90,7 @@ class FakeRedis:
76
90
  value = self.data.get(words[1])
77
91
  if value is None:
78
92
  return b"_\r\n" # RESP3's null: both clients ask for RESP3 in their handshake
79
- encoded = value.encode()
93
+ encoded = value.encode("utf-8", "surrogateescape")
80
94
  return b"$%d\r\n%s\r\n" % (len(encoded), encoded)
81
95
  if command == "SET":
82
96
  self.commands.append(words)
@@ -98,10 +112,14 @@ class StoreTest(APITest):
98
112
  patcher = mock.patch("time.time", lambda: self.clock / 1000)
99
113
  patcher.start()
100
114
  self.addCleanup(patcher.stop)
101
- from django.core.cache import cache
115
+ from django.core.cache import cache, caches
116
+ from django.utils.connection import ConnectionProxy
102
117
 
103
- self.cache = cache
118
+ self.default_cache = cache
119
+ # A proxy like the one Django's ``cache`` is, on the cache the library keeps.
120
+ self.cache = ConnectionProxy(caches, "files")
104
121
  cache.clear()
122
+ self.cache.clear()
105
123
 
106
124
  def redis(self) -> tuple[Any, FakeRedis]:
107
125
  import redis
@@ -159,7 +177,142 @@ class Django(StoreTest):
159
177
  self.assertEqual(rc._lifetime_argument(caches["default"]), {"timeout": LIFETIME})
160
178
 
161
179
 
180
+ class DjangoDefaults(StoreTest):
181
+ """The caches Django comes with, by way of the ``cache`` a site passes."""
182
+
183
+ VISITORS = 900
184
+
185
+ def proxy(self, alias: str) -> Any:
186
+ from django.core.cache import caches
187
+ from django.utils.connection import ConnectionProxy
188
+
189
+ return ConnectionProxy(caches, alias)
190
+
191
+ def credited(self, client: recapi.Client, visitors: int) -> int:
192
+ """Recommend to each visitor, then each clicks: the eviction's worst case."""
193
+ for visitor in range(visitors):
194
+ client.recommend(anon_id=f"v{visitor}", count=2)
195
+ for visitor in range(visitors):
196
+ client.track("r1", "view", anon_id=f"v{visitor}")
197
+ client.flush()
198
+ events = [e for c in self.api.calls if c.path == "/v1/events" for e in c.body["events"]]
199
+ self.assertEqual(len(events), visitors)
200
+ return sum(e.get("recommendation_id") == "rec_1" for e in events)
201
+
202
+ def test_every_click_keeps_its_credit_on_locmemcache(self) -> None:
203
+ with self.assertLogs("recapi", "WARNING"):
204
+ client = self.client(store=self.default_cache)
205
+ self.assertEqual(self.credited(client, self.VISITORS), self.VISITORS)
206
+
207
+ def test_every_click_keeps_its_credit_on_dummycache(self) -> None:
208
+ with self.assertLogs("recapi", "WARNING"):
209
+ client = self.client(store=self.proxy("nothing"))
210
+ self.assertEqual(self.credited(client, 20), 20)
211
+
212
+ def test_a_click_keeps_its_credit_with_the_async_client(self) -> None:
213
+ with self.assertLogs("recapi", "WARNING") as logs:
214
+ client = self.async_client(store=self.default_cache)
215
+
216
+ async def visit() -> None:
217
+ await client.recommend(anon_id="v", count=2)
218
+ await client.track("r1", "view", anon_id="v")
219
+ await client.flush()
220
+
221
+ asyncio.run(visit())
222
+ self.assertEqual(len(logs.output), 1)
223
+ self.assertEqual(self.clicked().get("recommendation_id"), "rec_1")
224
+
225
+ def test_a_cache_replaced_prints_one_line_once_per_client(self) -> None:
226
+ for alias, says in (("default", "LocMemCache"), ("nothing", "DummyCache")):
227
+ with self.subTest(alias), self.assertLogs("recapi", "WARNING") as logs:
228
+ client = self.client(store=self.proxy(alias))
229
+ client.recommend(anon_id="v", count=2)
230
+ client.track("r1", "view", anon_id="v")
231
+ client.flush()
232
+ self.assertEqual(len(logs.output), 1, logs.output)
233
+ self.assertIn(says, logs.output[0])
234
+ self.assertIn("own in-process store", logs.output[0])
235
+ self.assertIn("Redis or Memcached", logs.output[0])
236
+ self.assertIsInstance(client._store, recapi.MemoryStore)
237
+
238
+ def test_a_backend_taken_from_caches_is_replaced_too(self) -> None:
239
+ from django.core.cache import caches
240
+
241
+ with self.assertLogs("recapi", "WARNING"):
242
+ client = self.client(store=caches["default"])
243
+ self.assertIsInstance(client._store, recapi.MemoryStore)
244
+
245
+ def test_filebasedcache_stays_and_prints_its_line_once(self) -> None:
246
+ with self.assertLogs("recapi", "WARNING") as logs:
247
+ client = self.client(store=self.cache)
248
+ client.track("a", 3, user_id="u")
249
+ client.track("b", 3, user_id="u")
250
+ client.flush()
251
+ self.assertEqual(len(logs.output), 1, logs.output)
252
+ self.assertIn("FileBasedCache isn't shared between servers", logs.output[0])
253
+ self.assertIn("300", logs.output[0])
254
+ self.assertIs(client._store, self.cache)
255
+ self.assertIsNotNone(self.cache.get(client._key("u", None)))
256
+
257
+ def test_a_subclass_of_a_listed_cache_behaves_as_before(self) -> None:
258
+ from django.core.cache.backends.dummy import DummyCache
259
+ from django.core.cache.backends.filebased import FileBasedCache
260
+ from django.core.cache.backends.locmem import LocMemCache
261
+
262
+ class MyLocal(LocMemCache):
263
+ pass
264
+
265
+ class MyNothing(DummyCache):
266
+ pass
267
+
268
+ class MyFiles(FileBasedCache):
269
+ pass
270
+
271
+ with tempfile.TemporaryDirectory() as folder:
272
+ for store in (MyLocal("mine", {}), MyNothing("mine", {}), MyFiles(folder, {})):
273
+ with self.subTest(type(store).__name__), self.assertNoLogs("recapi", "WARNING"):
274
+ client = self.client(store=store)
275
+ self.assertIs(client._store, store)
276
+ self.assertEqual(rc._lifetime_argument(store), {"timeout": LIFETIME})
277
+
278
+ def test_djangos_redis_backend_prints_nothing_and_lasts_30_days(self) -> None:
279
+ from django.core.cache.backends.redis import RedisCache
280
+
281
+ fake = FakeRedis()
282
+ self.addCleanup(fake.close)
283
+ store = RedisCache(f"redis://127.0.0.1:{fake.port}", {})
284
+ with self.assertNoLogs("recapi", "WARNING"):
285
+ client = self.client(store=store)
286
+ client.track("a", 3, user_id="u")
287
+ client.flush()
288
+ self.assertIs(client._store, store)
289
+ self.assertEqual(fake.commands[-1][3:], ["EX", str(LIFETIME)])
290
+
291
+ def test_a_cache_that_fails_when_recognised_doesnt_stop_the_client(self) -> None:
292
+ from django.core.cache import InvalidCacheBackendError
293
+
294
+ broken = self.proxy("broken")
295
+ with self.assertRaises(InvalidCacheBackendError):
296
+ _ = broken.set
297
+ client = self.client(store=broken)
298
+ self.assertIs(client._store, broken)
299
+ with self.assertLogs("recapi", "ERROR") as logs:
300
+ client.track("a", 3, user_id="u")
301
+ self.assertIn("recapi: store write failed", "\n".join(logs.output))
302
+ client.flush()
303
+ self.assertEqual(self.clicked()["item_id"], "a")
304
+
305
+
162
306
  class Redis(StoreTest):
307
+ def test_a_client_on_redis_prints_nothing(self) -> None:
308
+ store, fake = self.redis()
309
+ with self.assertNoLogs("recapi", "WARNING"):
310
+ client = self.client(store=store)
311
+ client.track("a", 3, user_id="u")
312
+ client.flush()
313
+ self.assertIs(client._store, store)
314
+ self.assertEqual(fake.commands[-1][3:], ["EX", str(LIFETIME)])
315
+
163
316
  def test_a_write_carries_the_expiry(self) -> None:
164
317
  store, fake = self.redis()
165
318
  client = self.client(store=store)
@@ -254,6 +407,22 @@ class OtherStores(unittest.TestCase):
254
407
  Older.set.__qualname__ = qualname
255
408
  self.assertEqual(rc._lifetime_argument(Older()), {"ex": LIFETIME})
256
409
 
410
+ def test_a_store_that_fails_when_recognised_doesnt_stop_the_client(self) -> None:
411
+ class Failing:
412
+ def __getattr__(self, name: str) -> Any:
413
+ raise RuntimeError("not ready")
414
+
415
+ store = Failing()
416
+ client = recapi.Client(KEY, "http://127.0.0.1:9", store=store, flush_interval=3600)
417
+ self.addCleanup(client.close)
418
+ self.assertIs(client._store, store)
419
+
420
+ def test_a_store_without_a_set_is_left_alone_at_start(self) -> None:
421
+ store = object()
422
+ client = recapi.Client(KEY, "http://127.0.0.1:9", store=store, flush_interval=3600)
423
+ self.addCleanup(client.close)
424
+ self.assertIs(client._store, store)
425
+
257
426
  def test_stores_without_a_bound_set_get_a_plain_set(self) -> None:
258
427
  for store in (object(), mock.Mock(), recapi.MemoryStore(), None):
259
428
  with self.subTest(store=type(store).__name__):
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes