recapi 0.4.1__tar.gz → 0.4.3__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.1
3
+ Version: 0.4.3
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
@@ -24,15 +24,23 @@ to the recommendation that showed them (the dashboard's clicks and conversions).
24
24
 
25
25
  ## Install
26
26
 
27
- Your recapi API serves the library: install it with pip, or put the same URL
28
- in your `requirements.txt`. No package index, no build step, no dependencies:
27
+ The library is on PyPI, with no dependencies: install it with pip, or add
28
+ `recapi` to your `requirements.txt`.
29
29
 
30
30
  ```sh
31
- pip install https://api.<your-domain>/sdk/python/recapi-0.4.1-py3-none-any.whl
31
+ pip install recapi
32
32
  ```
33
33
 
34
- The dashboard's quick start shows this line with your API's address. To work
35
- on the library itself, install it from a checkout of this repository
34
+ Production releases publish each version there
35
+ ([docs/deployment.md](../../docs/deployment.md#publishing-the-libraries)).
36
+ Your recapi API serves the same library, for servers that can't reach PyPI
37
+ (the dashboard's quick start shows the line with your API's address):
38
+
39
+ ```sh
40
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.3-py3-none-any.whl
41
+ ```
42
+
43
+ To work on the library itself, install it from a checkout of this repository
36
44
  (`pip install ./sdk/python`).
37
45
 
38
46
  ## Quick start
@@ -104,14 +112,24 @@ client = recapi.Client("rk_sec_…", "https://api.example.com", store=redis.Redi
104
112
  client = recapi.Client("rk_sec_…", "https://api.example.com", store=cache)
105
113
  ```
106
114
 
115
+ Written to a redis-py client or Django's cache, a user's state lasts 30 days
116
+ from its last write, with no setting to choose: well past the 24 hours a click
117
+ earns credit, and recapi gives a known `user_id` its history back afterwards.
118
+ Without it, Django would drop the state after its default 5 minutes, taking the
119
+ click's credit with it, and Redis would keep it for ever. Any other store gets a
120
+ 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.
123
+
107
124
  A user the store doesn't know yet (a new process, an evicted user, another
108
125
  server) still gets personalised results: the request then has no history,
109
126
  recapi uses the history it keeps from that user's events, and returns it with
110
127
  the recommendations; the client stores it for the next calls. If the store's
111
128
  first call for that user was a `track()` or an `identify()`, the first
112
129
  `recommend()` fetches that history (`GET /v1/users/{id}/history`, unbilled)
113
- with half of its 1.5 s and merges it with what was tracked here; a failed
114
- fetch is tried again on the next call. This works for `user_id` only, and
130
+ with half of its 1.5 s and merges it with what was tracked here (after an
131
+ `identify()`, without the visitor's browsing, which is already merged here); a
132
+ failed fetch is tried again on the next call. This works for `user_id` only, and
115
133
  only with a secret key. A store that fails
116
134
  (Redis down) is logged and skipped: tracking and recommendations go on.
117
135
  Updates to one user are serialised within a process only: two processes
@@ -184,7 +202,7 @@ one recommendation id collects the events of many users ("Page caches").
184
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` |
185
203
  | `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user |
186
204
  | `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 |
187
- | `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 |
205
+ | `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 |
188
206
  | `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
189
207
  | `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
190
208
 
@@ -14,15 +14,23 @@ to the recommendation that showed them (the dashboard's clicks and conversions).
14
14
 
15
15
  ## Install
16
16
 
17
- Your recapi API serves the library: install it with pip, or put the same URL
18
- in your `requirements.txt`. No package index, no build step, no dependencies:
17
+ The library is on PyPI, with no dependencies: install it with pip, or add
18
+ `recapi` to your `requirements.txt`.
19
19
 
20
20
  ```sh
21
- pip install https://api.<your-domain>/sdk/python/recapi-0.4.1-py3-none-any.whl
21
+ pip install recapi
22
22
  ```
23
23
 
24
- The dashboard's quick start shows this line with your API's address. To work
25
- on the library itself, install it from a checkout of this repository
24
+ Production releases publish each version there
25
+ ([docs/deployment.md](../../docs/deployment.md#publishing-the-libraries)).
26
+ Your recapi API serves the same library, for servers that can't reach PyPI
27
+ (the dashboard's quick start shows the line with your API's address):
28
+
29
+ ```sh
30
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.3-py3-none-any.whl
31
+ ```
32
+
33
+ To work on the library itself, install it from a checkout of this repository
26
34
  (`pip install ./sdk/python`).
27
35
 
28
36
  ## Quick start
@@ -94,14 +102,24 @@ client = recapi.Client("rk_sec_…", "https://api.example.com", store=redis.Redi
94
102
  client = recapi.Client("rk_sec_…", "https://api.example.com", store=cache)
95
103
  ```
96
104
 
105
+ Written to a redis-py client or Django's cache, a user's state lasts 30 days
106
+ from its last write, with no setting to choose: well past the 24 hours a click
107
+ earns credit, and recapi gives a known `user_id` its history back afterwards.
108
+ Without it, Django would drop the state after its default 5 minutes, taking the
109
+ click's credit with it, and Redis would keep it for ever. Any other store gets a
110
+ 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.
113
+
97
114
  A user the store doesn't know yet (a new process, an evicted user, another
98
115
  server) still gets personalised results: the request then has no history,
99
116
  recapi uses the history it keeps from that user's events, and returns it with
100
117
  the recommendations; the client stores it for the next calls. If the store's
101
118
  first call for that user was a `track()` or an `identify()`, the first
102
119
  `recommend()` fetches that history (`GET /v1/users/{id}/history`, unbilled)
103
- with half of its 1.5 s and merges it with what was tracked here; a failed
104
- fetch is tried again on the next call. This works for `user_id` only, and
120
+ with half of its 1.5 s and merges it with what was tracked here (after an
121
+ `identify()`, without the visitor's browsing, which is already merged here); a
122
+ failed fetch is tried again on the next call. This works for `user_id` only, and
105
123
  only with a secret key. A store that fails
106
124
  (Redis down) is logged and skipped: tracking and recommendations go on.
107
125
  Updates to one user are serialised within a process only: two processes
@@ -174,7 +192,7 @@ one recommendation id collects the events of many users ("Page caches").
174
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` |
175
193
  | `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user |
176
194
  | `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 |
177
- | `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 |
195
+ | `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 |
178
196
  | `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
179
197
  | `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
180
198
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "recapi"
7
- version = "0.4.1"
7
+ version = "0.4.3"
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.1"
32
+ __version__ = "0.4.3"
33
33
 
34
34
  log = logging.getLogger("recapi")
35
35
  Tags = Sequence[str] | None
@@ -60,6 +60,19 @@ CLICK_WINDOW_MS = 24 * 60 * 60 * 1000
60
60
  # Shown items remembered per user (the JS SDK keeps 500 for one browser; a
61
61
  # server store holds every user's).
62
62
  MAX_SHOWN_ITEMS = 100
63
+ # How long a recognised shared store keeps a user's state after its last write.
64
+ # Far beyond the 24 hours of click credit, and by then a score has halved four
65
+ # times (under 5% is left). A known user_id gets its history back from recapi,
66
+ # which keeps 90 days, so only a visitor gone for a month starts afresh. It
67
+ # bounds a Redis at about one month's visitors instead of growing for ever.
68
+ STATE_LIFETIME_SECONDS = 30 * 24 * 60 * 60
69
+ # Where redis-py defines ``set`` (4.1 on, 4.0, 3.x), and Django's cache base class.
70
+ _REDIS_PY_SET = {
71
+ ("redis.commands.core", "BasicKeyCommands.set"),
72
+ ("redis.commands.core", "CoreCommands.set"),
73
+ ("redis.client", "Redis.set"),
74
+ }
75
+ _DJANGO_CACHE = ("django.core.cache.backends.base", "BaseCache")
63
76
  PUBLIC_KEY_PREFIX = "rk_pub_"
64
77
  # Open connections kept between calls: one per call in flight at the busiest
65
78
  # moment (AsyncClient runs 8 at once), so a burst of threads can't leave
@@ -164,6 +177,27 @@ class Store(Protocol):
164
177
  def delete(self, key: str) -> object: ... # noqa: D102
165
178
 
166
179
 
180
+ def _lifetime_argument(store: Store) -> dict[str, int]:
181
+ """Return what makes ``store.set`` expire the entry; nothing for a store it doesn't recognise.
182
+
183
+ By class name, since the library imports neither package. Any doubt (a
184
+ subclass's own ``set``, another client) means today's ``set(key, value)``.
185
+ """
186
+ write = getattr(store, "set", None)
187
+ function = getattr(write, "__func__", None)
188
+ if (
189
+ getattr(function, "__module__", ""),
190
+ getattr(function, "__qualname__", ""),
191
+ ) in _REDIS_PY_SET:
192
+ return {"ex": STATE_LIFETIME_SECONDS}
193
+ # Django's ``cache`` is a proxy of a per-thread backend, and its class says
194
+ # nothing: only the bound method leads to the backend.
195
+ backend = type(getattr(write, "__self__", None))
196
+ if any((c.__module__, c.__qualname__) == _DJANGO_CACHE for c in backend.__mro__):
197
+ return {"timeout": STATE_LIFETIME_SECONDS}
198
+ return {}
199
+
200
+
167
201
  class MemoryStore:
168
202
  """In-process store keeping the most recently used ``max_users`` users."""
169
203
 
@@ -196,22 +230,32 @@ class _UserState:
196
230
 
197
231
  ``shown`` maps item -> [recommendation id, shown at, clicked at?], oldest
198
232
  first. ``restored`` is set once the history holds recapi's stored one.
233
+ ``anon_id`` is the visitor identify() merged in before that: recapi's
234
+ snapshot also holds that visitor's browsing, so the restore asks it to
235
+ leave it out.
199
236
  """
200
237
 
201
- __slots__ = ("history", "restored", "shown")
238
+ __slots__ = ("anon_id", "history", "restored", "shown")
202
239
 
203
240
  def __init__(
204
- self, history: History | None = None, shown: dict | None = None, restored: bool = False
241
+ self,
242
+ history: History | None = None,
243
+ shown: dict | None = None,
244
+ restored: bool = False,
245
+ anon_id: str | None = None,
205
246
  ) -> None:
206
247
  self.history = history or History()
207
248
  self.shown: dict[str, list[Any]] = shown or {}
208
249
  self.restored = restored
250
+ self.anon_id = anon_id
209
251
 
210
252
  def dumps(self, now: int) -> str:
211
253
  shown = [[item, *entry] for item, entry in self.shown.items() if _attributable(entry, now)]
212
254
  state = {"history": self.history.encode(), "shown": shown[-MAX_SHOWN_ITEMS:]}
213
255
  if self.restored:
214
256
  state["restored"] = True
257
+ if self.anon_id:
258
+ state["anon_id"] = self.anon_id
215
259
  return json.dumps(state, separators=(",", ":"))
216
260
 
217
261
  @classmethod
@@ -231,7 +275,10 @@ class _UserState:
231
275
  if history is None:
232
276
  log.warning("recapi: discarding a malformed stored user state")
233
277
  return cls()
234
- return cls(history, shown, data.get("restored") is True)
278
+ anon_id = data.get("anon_id")
279
+ return cls(
280
+ history, shown, data.get("restored") is True, anon_id if is_id(anon_id) else None
281
+ )
235
282
 
236
283
 
237
284
  def _attributable(entry: Sequence[Any], t: int) -> bool:
@@ -628,9 +675,11 @@ class Client:
628
675
  a failure leaves the state as it was, to be tried on the next call.
629
676
  """
630
677
  path = "/v1/users/" + urllib.parse.quote(user_id, safe="") + "/history"
678
+ query = {"anon_id": state.anon_id} if state.anon_id else None
631
679
  try:
632
680
  # Half the time left, so the recommendation itself still fits.
633
- snapshot = self._request("GET", path, timeout=(deadline - time.monotonic()) / 2)
681
+ timeout = (deadline - time.monotonic()) / 2
682
+ snapshot = self._request("GET", path, timeout=timeout, query=query)
634
683
  if not isinstance(snapshot, dict):
635
684
  raise RecapiError("invalid_response", "malformed history response")
636
685
  except RecapiError as error:
@@ -642,6 +691,7 @@ class Client:
642
691
  if not state.restored:
643
692
  state.history = state.history.merge_snapshot(History.from_snapshot(snapshot), t)
644
693
  state.restored = True
694
+ state.anon_id = None
645
695
  self._save(key, state, t)
646
696
  return state
647
697
 
@@ -664,6 +714,9 @@ class Client:
664
714
  return
665
715
  state = self._load(user)
666
716
  state.history = state.history.merge(guest.history, t)
717
+ if not state.restored:
718
+ # recapi's snapshot, fetched later, holds this visitor's browsing too.
719
+ state.anon_id = anon_id
667
720
  # Oldest display first, as recommend() keeps them; an item's later display wins.
668
721
  shown = sorted([*state.shown.items(), *guest.shown.items()], key=lambda e: e[1][1])
669
722
  state.shown = {}
@@ -765,7 +818,7 @@ class Client:
765
818
 
766
819
  def _save(self, key: str, state: _UserState, now: int) -> None:
767
820
  try:
768
- self._store.set(key, state.dumps(now))
821
+ self._store.set(key, state.dumps(now), **_lifetime_argument(self._store))
769
822
  except Exception:
770
823
  log.exception("recapi: store write failed")
771
824
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: recapi
3
- Version: 0.4.1
3
+ Version: 0.4.3
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
@@ -24,15 +24,23 @@ to the recommendation that showed them (the dashboard's clicks and conversions).
24
24
 
25
25
  ## Install
26
26
 
27
- Your recapi API serves the library: install it with pip, or put the same URL
28
- in your `requirements.txt`. No package index, no build step, no dependencies:
27
+ The library is on PyPI, with no dependencies: install it with pip, or add
28
+ `recapi` to your `requirements.txt`.
29
29
 
30
30
  ```sh
31
- pip install https://api.<your-domain>/sdk/python/recapi-0.4.1-py3-none-any.whl
31
+ pip install recapi
32
32
  ```
33
33
 
34
- The dashboard's quick start shows this line with your API's address. To work
35
- on the library itself, install it from a checkout of this repository
34
+ Production releases publish each version there
35
+ ([docs/deployment.md](../../docs/deployment.md#publishing-the-libraries)).
36
+ Your recapi API serves the same library, for servers that can't reach PyPI
37
+ (the dashboard's quick start shows the line with your API's address):
38
+
39
+ ```sh
40
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.3-py3-none-any.whl
41
+ ```
42
+
43
+ To work on the library itself, install it from a checkout of this repository
36
44
  (`pip install ./sdk/python`).
37
45
 
38
46
  ## Quick start
@@ -104,14 +112,24 @@ client = recapi.Client("rk_sec_…", "https://api.example.com", store=redis.Redi
104
112
  client = recapi.Client("rk_sec_…", "https://api.example.com", store=cache)
105
113
  ```
106
114
 
115
+ Written to a redis-py client or Django's cache, a user's state lasts 30 days
116
+ from its last write, with no setting to choose: well past the 24 hours a click
117
+ earns credit, and recapi gives a known `user_id` its history back afterwards.
118
+ Without it, Django would drop the state after its default 5 minutes, taking the
119
+ click's credit with it, and Redis would keep it for ever. Any other store gets a
120
+ 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.
123
+
107
124
  A user the store doesn't know yet (a new process, an evicted user, another
108
125
  server) still gets personalised results: the request then has no history,
109
126
  recapi uses the history it keeps from that user's events, and returns it with
110
127
  the recommendations; the client stores it for the next calls. If the store's
111
128
  first call for that user was a `track()` or an `identify()`, the first
112
129
  `recommend()` fetches that history (`GET /v1/users/{id}/history`, unbilled)
113
- with half of its 1.5 s and merges it with what was tracked here; a failed
114
- fetch is tried again on the next call. This works for `user_id` only, and
130
+ with half of its 1.5 s and merges it with what was tracked here (after an
131
+ `identify()`, without the visitor's browsing, which is already merged here); a
132
+ failed fetch is tried again on the next call. This works for `user_id` only, and
115
133
  only with a secret key. A store that fails
116
134
  (Redis down) is logged and skipped: tracking and recommendations go on.
117
135
  Updates to one user are serialised within a process only: two processes
@@ -184,7 +202,7 @@ one recommendation id collects the events of many users ("Page caches").
184
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` |
185
203
  | `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user |
186
204
  | `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 |
187
- | `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 |
205
+ | `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 |
188
206
  | `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
189
207
  | `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
190
208
 
@@ -12,4 +12,5 @@ recapi.egg-info/top_level.txt
12
12
  tests/test_async_client.py
13
13
  tests/test_client.py
14
14
  tests/test_client_vectors.py
15
- tests/test_history.py
15
+ tests/test_history.py
16
+ tests/test_stores.py
@@ -971,6 +971,63 @@ class Restore(APITest):
971
971
  client.recommend(user_id="u/1 é")
972
972
  self.assertEqual(self.api.calls[0].raw_path, "/v1/users/u%2F1%20%C3%A9/history")
973
973
 
974
+ def test_the_visitor_of_a_login_is_left_out_of_the_restore_until_it_succeeds(self) -> None:
975
+ self.api.on(self.HISTORY, Reply(503, {"error": {"code": "unavailable", "message": "x"}}))
976
+ store = recapi.MemoryStore()
977
+ client = self.client(store=store)
978
+ client.track("a", "view", anon_id="v")
979
+ client.identify("v", "u")
980
+ with self.assertLogs("recapi", "WARNING"):
981
+ client.recommend(user_id="u")
982
+ # The failed restore keeps the visitor, also for another process.
983
+ self.assertIn('"anon_id":"v"', store.get(client._key("u", None)))
984
+ self.api.on(self.HISTORY, Reply(200, {"top": [], "recent": [], "as_of": T0}))
985
+ other = self.client(store=store)
986
+ other.recommend(user_id="u")
987
+ other.recommend(user_id="u")
988
+ history = f"GET {self.HISTORY}?anon_id=v"
989
+ recommend = "POST /v1/recommendations"
990
+ self.assertEqual(self.api.lines(), [history, recommend, history, recommend, recommend])
991
+ self.assertNotIn("anon_id", store.get(client._key("u", None)))
992
+
993
+ def test_a_login_after_the_restore_or_an_invalid_stored_visitor_asks_for_no_visitor(
994
+ self,
995
+ ) -> None:
996
+ store = recapi.MemoryStore()
997
+ client = self.client(store=store)
998
+ restored = {
999
+ "history": {
1000
+ "top": [["s", 3.0, T0]],
1001
+ "recent": [["s", T0]],
1002
+ "rejected": [],
1003
+ "lastT": T0,
1004
+ },
1005
+ "shown": [],
1006
+ "restored": True,
1007
+ }
1008
+ store.set(client._key("u", None), json.dumps(restored))
1009
+ client.track("a", "view", anon_id="v")
1010
+ client.identify("v", "u")
1011
+ self.assertNotIn("anon_id", store.get(client._key("u", None)))
1012
+ # Written by a newer version, or by hand: an id the API would refuse is dropped.
1013
+ invalid = {
1014
+ "history": {
1015
+ "top": [["a", 3.0, T0]],
1016
+ "recent": [["a", T0]],
1017
+ "rejected": [],
1018
+ "lastT": T0,
1019
+ },
1020
+ "shown": [],
1021
+ "anon_id": "v\n",
1022
+ }
1023
+ store.set(client._key("w", None), json.dumps(invalid))
1024
+ client.recommend(user_id="u")
1025
+ client.recommend(user_id="w")
1026
+ self.assertEqual(
1027
+ self.api.lines(),
1028
+ ["POST /v1/recommendations", "GET /v1/users/w/history", "POST /v1/recommendations"],
1029
+ )
1030
+
974
1031
 
975
1032
  class Identify(APITest):
976
1033
  def test_a_visitors_history_and_clicks_count_after_login(self) -> None:
@@ -7,7 +7,7 @@ from pathlib import Path
7
7
  from unittest import mock
8
8
 
9
9
  import recapi
10
- from fakeapi import KEY, T0, APITest, Reply, dead_url, popular, recs
10
+ from fakeapi import KEY, T0, APITest, Reply, dead_url, popular, recs, request_line
11
11
  from recapi import client as rc
12
12
 
13
13
  VECTORS = json.loads(
@@ -226,7 +226,7 @@ class ClientVectors(APITest):
226
226
  with self.assertNoLogs("recapi") if "stored" in case else self.assertLogs("recapi"):
227
227
  client.recommend(user_id="u")
228
228
  client.recommend(user_id="u")
229
- self.assertEqual([f"{c.method} {c.path}" for c in self.api.calls], case["requests"])
229
+ self.assertEqual(self.api.lines(), case["requests"])
230
230
  body = next(c.body for c in self.api.calls if c.path == "/v1/recommendations")
231
231
  sent = {k: body.get(k) for k in ("history", "recent", "exclude")}
232
232
  self.assertEqual(sent, case["sent"])
@@ -257,7 +257,7 @@ class ClientVectors(APITest):
257
257
  start = len(self.api.calls)
258
258
  client.recommend(user_id="u")
259
259
  calls = self.api.calls[start:]
260
- self.assertEqual([f"{c.method} {c.path}" for c in calls], case["requests"])
260
+ self.assertEqual([request_line(c) for c in calls], case["requests"])
261
261
  body = calls[-1].body
262
262
  self.assertEqual(
263
263
  {k: body.get(k) for k in ("history", "recent", "exclude")}, case["sent"]
@@ -0,0 +1,260 @@
1
+ """The stores the README prints, for real: Django's cache and redis-py on a local socket."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import os
8
+ import socketserver
9
+ import subprocess
10
+ import sys
11
+ import threading
12
+ import unittest
13
+ from pathlib import Path
14
+ from typing import Any
15
+ from unittest import mock
16
+
17
+ import recapi
18
+ from fakeapi import KEY, APITest
19
+ from recapi import client as rc
20
+
21
+ DAY = 24 * 60 * 60
22
+ MINUTE_MS = 60_000
23
+ # Written out rather than read from the library: a change must be a decision.
24
+ LIFETIME = 30 * DAY
25
+ ROOT = Path(__file__).resolve().parents[3]
26
+ CLIENTS = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "recapi/store-clients-1"
27
+
28
+
29
+ def setUpModule() -> None:
30
+ subprocess.run(
31
+ [sys.executable, str(ROOT / "scripts/fetch_store_clients.py"), str(CLIENTS)], check=True
32
+ )
33
+ sys.path.append(str(CLIENTS / "python"))
34
+ from django.conf import settings
35
+
36
+ if not settings.configured:
37
+ # No TIMEOUT: Django's default of 300 s is what the README's store=cache gets.
38
+ settings.configure(
39
+ CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
40
+ )
41
+
42
+
43
+ def tearDownModule() -> None:
44
+ sys.path.remove(str(CLIENTS / "python"))
45
+
46
+
47
+ class FakeRedis:
48
+ """Enough of a Redis server for redis-py: GET, SET with its options, DEL, the handshake."""
49
+
50
+ def __init__(self) -> None:
51
+ self.data: dict[str, str] = {}
52
+ self.commands: list[list[str]] = []
53
+ fake = self
54
+
55
+ class Handler(socketserver.StreamRequestHandler):
56
+ def handle(self) -> None:
57
+ with contextlib.suppress(ConnectionError, ValueError):
58
+ while line := self.rfile.readline():
59
+ words = [self.word() for _ in range(int(line[1:]))]
60
+ self.wfile.write(fake.answer(words))
61
+
62
+ def word(self) -> str:
63
+ size = int(self.rfile.readline()[1:])
64
+ return self.rfile.read(size + 2)[:-2].decode()
65
+
66
+ self.server = socketserver.ThreadingTCPServer(("127.0.0.1", 0), Handler)
67
+ self.server.daemon_threads = True
68
+ self.port = self.server.server_address[1]
69
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
70
+
71
+ def answer(self, words: list[str]) -> bytes:
72
+ command = words[0].upper()
73
+ if command == "HELLO":
74
+ return b"%1\r\n+proto\r\n:" + words[1].encode() + b"\r\n"
75
+ if command == "GET":
76
+ value = self.data.get(words[1])
77
+ if value is None:
78
+ return b"_\r\n" # RESP3's null: both clients ask for RESP3 in their handshake
79
+ encoded = value.encode()
80
+ return b"$%d\r\n%s\r\n" % (len(encoded), encoded)
81
+ if command == "SET":
82
+ self.commands.append(words)
83
+ self.data[words[1]] = words[2]
84
+ if command == "DEL":
85
+ self.commands.append(words)
86
+ return b":%d\r\n" % (self.data.pop(words[1], None) is not None)
87
+ return b"+OK\r\n"
88
+
89
+ def close(self) -> None:
90
+ self.server.shutdown()
91
+ self.server.server_close()
92
+
93
+
94
+ class StoreTest(APITest):
95
+ def setUp(self) -> None:
96
+ super().setUp()
97
+ # Django reads time.time(): one clock for the cache's expiry and the library.
98
+ patcher = mock.patch("time.time", lambda: self.clock / 1000)
99
+ patcher.start()
100
+ self.addCleanup(patcher.stop)
101
+ from django.core.cache import cache
102
+
103
+ self.cache = cache
104
+ cache.clear()
105
+
106
+ def redis(self) -> tuple[Any, FakeRedis]:
107
+ import redis
108
+
109
+ fake = FakeRedis()
110
+ self.addCleanup(fake.close)
111
+ client = redis.Redis(port=fake.port, socket_timeout=5)
112
+ self.addCleanup(client.close)
113
+ return client, fake
114
+
115
+ def async_client(self, **options: Any) -> recapi.AsyncClient:
116
+ client = recapi.AsyncClient(KEY, self.api.url, flush_interval=3600, **options)
117
+ self.addCleanup(lambda: asyncio.run(client.close()))
118
+ return client
119
+
120
+ def clicked(self) -> dict[str, Any]:
121
+ return self.last_body("/v1/events")["events"][-1]
122
+
123
+
124
+ class Django(StoreTest):
125
+ def test_a_click_after_six_minutes_keeps_its_credit(self) -> None:
126
+ client = self.client(store=self.cache)
127
+ self.assertEqual(client.recommend(anon_id="v", count=2).recommendation_id, "rec_1")
128
+ self.clock += 6 * MINUTE_MS
129
+ client.track("r1", "view", anon_id="v")
130
+ client.flush()
131
+ self.assertEqual(self.clicked().get("recommendation_id"), "rec_1")
132
+
133
+ def test_a_click_after_six_minutes_keeps_its_credit_with_the_async_client(self) -> None:
134
+ client = self.async_client(store=self.cache)
135
+
136
+ async def visit() -> None:
137
+ await client.recommend(anon_id="v", count=2)
138
+ self.clock += 6 * MINUTE_MS
139
+ await client.track("r1", "view", anon_id="v")
140
+ await client.flush()
141
+
142
+ asyncio.run(visit())
143
+ self.assertEqual(self.clicked().get("recommendation_id"), "rec_1")
144
+
145
+ def test_the_entry_lasts_30_days_from_its_last_write(self) -> None:
146
+ client = self.client(store=self.cache)
147
+ key = client._key("u", None)
148
+ client.track("a", 3, user_id="u")
149
+ self.clock += 20 * DAY * 1000
150
+ client.track("b", 3, user_id="u") # restarts the lifetime
151
+ self.clock += (LIFETIME - 1) * 1000
152
+ self.assertIsNotNone(self.cache.get(key))
153
+ self.clock += 2 * 1000
154
+ self.assertIsNone(self.cache.get(key))
155
+
156
+ def test_a_backend_taken_from_caches_is_recognised_too(self) -> None:
157
+ from django.core.cache import caches
158
+
159
+ self.assertEqual(rc._lifetime_argument(caches["default"]), {"timeout": LIFETIME})
160
+
161
+
162
+ class Redis(StoreTest):
163
+ def test_a_write_carries_the_expiry(self) -> None:
164
+ store, fake = self.redis()
165
+ client = self.client(store=store)
166
+ client.track("a", 3, user_id="u")
167
+ key = client._key("u", None)
168
+ self.assertEqual(fake.commands[-1][:2], ["SET", key])
169
+ self.assertEqual(fake.commands[-1][3:], ["EX", str(LIFETIME)])
170
+
171
+ def test_a_write_carries_the_expiry_with_the_async_client(self) -> None:
172
+ store, fake = self.redis()
173
+ client = self.async_client(store=store)
174
+ asyncio.run(client.track("a", 3, user_id="u"))
175
+ self.assertEqual(fake.commands[-1][3:], ["EX", str(LIFETIME)])
176
+
177
+ def test_a_click_after_six_minutes_keeps_its_credit(self) -> None:
178
+ store, _ = self.redis()
179
+ client = self.client(store=store)
180
+ client.recommend(anon_id="v", count=2)
181
+ self.clock += 6 * MINUTE_MS
182
+ client.track("r1", "view", anon_id="v")
183
+ client.flush()
184
+ self.assertEqual(self.clicked().get("recommendation_id"), "rec_1")
185
+
186
+ def test_a_subclass_with_its_own_set_gets_a_plain_set(self) -> None:
187
+ import redis
188
+
189
+ class Mine(redis.Redis):
190
+ def set(self, name: str, value: str) -> Any:
191
+ return super().set(name, value)
192
+
193
+ fake = FakeRedis()
194
+ self.addCleanup(fake.close)
195
+ store = Mine(port=fake.port, socket_timeout=5)
196
+ self.addCleanup(store.close)
197
+ self.client(store=store).track("a", 3, user_id="u")
198
+ self.assertEqual(len(fake.commands[-1]), 3)
199
+
200
+ def test_a_store_that_raises_is_logged_and_skipped(self) -> None:
201
+ import redis
202
+ from redis.backoff import NoBackoff
203
+ from redis.retry import Retry
204
+
205
+ fake = FakeRedis()
206
+ fake.close()
207
+ # No retries: redis-py's default backs off for seconds on a refused connection.
208
+ down = redis.Redis(port=fake.port, retry=Retry(NoBackoff(), 0))
209
+ self.addCleanup(down.close)
210
+ client = self.client(store=down)
211
+ with self.assertLogs("recapi", "ERROR") as logs:
212
+ client.track("a", 3, user_id="u")
213
+ self.assertIn("recapi: store write failed", "\n".join(logs.output))
214
+ client.flush()
215
+ self.assertEqual(self.clicked()["item_id"], "a")
216
+
217
+
218
+ class OtherStores(unittest.TestCase):
219
+ class Mine:
220
+ """A store of the customer's, whose arguments happen to carry the same names."""
221
+
222
+ def __init__(self) -> None:
223
+ self.writes: list[tuple[Any, ...]] = []
224
+
225
+ def set(self, key: str, value: str, timeout: int = 0, ex: int = 0) -> None:
226
+ self.writes.append((key, timeout, ex))
227
+
228
+ def get(self, key: str) -> None:
229
+ return None
230
+
231
+ def delete(self, key: str) -> None:
232
+ pass
233
+
234
+ def test_a_store_the_library_doesnt_recognise_gets_a_plain_set(self) -> None:
235
+ store = self.Mine()
236
+ client = recapi.Client(KEY, "http://127.0.0.1:9", store=store, flush_interval=3600)
237
+ self.addCleanup(client.close)
238
+ client._save("k", rc._UserState(), 0)
239
+ self.assertEqual(store.writes, [("k", 0, 0)])
240
+
241
+ def test_older_redis_clients_are_recognised_where_they_define_set(self) -> None:
242
+ # The pinned redis-py is the newest shape; these were read in 3.5.3 and 4.0.2.
243
+ for module, qualname in (
244
+ ("redis.client", "Redis.set"),
245
+ ("redis.commands.core", "CoreCommands.set"),
246
+ ):
247
+ with self.subTest(qualname):
248
+
249
+ class Older:
250
+ def set(self, key: str, value: str, ex: int = 0) -> None:
251
+ pass
252
+
253
+ Older.set.__module__ = module
254
+ Older.set.__qualname__ = qualname
255
+ self.assertEqual(rc._lifetime_argument(Older()), {"ex": LIFETIME})
256
+
257
+ def test_stores_without_a_bound_set_get_a_plain_set(self) -> None:
258
+ for store in (object(), mock.Mock(), recapi.MemoryStore(), None):
259
+ with self.subTest(store=type(store).__name__):
260
+ self.assertEqual(rc._lifetime_argument(store), {})
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes