recapi 0.4.2__tar.gz → 0.4.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {recapi-0.4.2/recapi.egg-info → recapi-0.4.4}/PKG-INFO +33 -8
- {recapi-0.4.2 → recapi-0.4.4}/README.md +32 -7
- {recapi-0.4.2 → recapi-0.4.4}/pyproject.toml +1 -1
- {recapi-0.4.2 → recapi-0.4.4}/recapi/client.py +76 -4
- {recapi-0.4.2 → recapi-0.4.4/recapi.egg-info}/PKG-INFO +33 -8
- {recapi-0.4.2 → recapi-0.4.4}/recapi.egg-info/SOURCES.txt +2 -1
- recapi-0.4.4/tests/test_stores.py +429 -0
- {recapi-0.4.2 → recapi-0.4.4}/LICENSE +0 -0
- {recapi-0.4.2 → recapi-0.4.4}/recapi/__init__.py +0 -0
- {recapi-0.4.2 → recapi-0.4.4}/recapi/async_client.py +0 -0
- {recapi-0.4.2 → recapi-0.4.4}/recapi/history.py +0 -0
- {recapi-0.4.2 → recapi-0.4.4}/recapi.egg-info/dependency_links.txt +0 -0
- {recapi-0.4.2 → recapi-0.4.4}/recapi.egg-info/top_level.txt +0 -0
- {recapi-0.4.2 → recapi-0.4.4}/setup.cfg +0 -0
- {recapi-0.4.2 → recapi-0.4.4}/tests/test_async_client.py +0 -0
- {recapi-0.4.2 → recapi-0.4.4}/tests/test_client.py +0 -0
- {recapi-0.4.2 → recapi-0.4.4}/tests/test_client_vectors.py +0 -0
- {recapi-0.4.2 → recapi-0.4.4}/tests/test_history.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.4
|
|
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
|
-
|
|
28
|
-
|
|
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
|
|
31
|
+
pip install recapi
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
-
|
|
35
|
-
|
|
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.4-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
|
|
@@ -96,14 +104,31 @@ By default each process keeps its users' state in memory (the 10,000 most
|
|
|
96
104
|
recently seen users). That is enough for one process. When several
|
|
97
105
|
processes or servers serve the same users, give them a shared store: any
|
|
98
106
|
object with `get(key)`, `set(key, value)` (strings) and `delete(key)` works,
|
|
99
|
-
such as a Redis client or Django's cache.
|
|
107
|
+
such as a Redis client or Django's Redis or Memcached cache.
|
|
100
108
|
|
|
101
109
|
```python
|
|
102
110
|
client = recapi.Client("rk_sec_…", "https://api.example.com", store=redis.Redis())
|
|
103
|
-
# or, in Django (from django.core.cache import cache):
|
|
111
|
+
# or, in Django with one of those caches (from django.core.cache import cache):
|
|
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
|
+
|
|
122
|
+
Not every Django cache can hold this. The library recognises Django's own
|
|
123
|
+
classes (a subclass of one is left alone) and logs one line at start:
|
|
124
|
+
|
|
125
|
+
| Django cache | What happens | Shared between |
|
|
126
|
+
|---|---|---|
|
|
127
|
+
| `RedisCache`, `PyMemcacheCache`, `PyLibMCCache` | used, no line | servers |
|
|
128
|
+
| `FileBasedCache` | used, with a warning: it holds 300 entries by default | one server's processes |
|
|
129
|
+
| `LocMemCache` (Django's default) | the library's own store instead, with a warning | nothing |
|
|
130
|
+
| `DummyCache` | the library's own store instead, with a warning | nothing |
|
|
131
|
+
|
|
107
132
|
A user the store doesn't know yet (a new process, an evicted user, another
|
|
108
133
|
server) still gets personalised results: the request then has no history,
|
|
109
134
|
recapi uses the history it keeps from that user's events, and returns it with
|
|
@@ -14,15 +14,23 @@ to the recommendation that showed them (the dashboard's clicks and conversions).
|
|
|
14
14
|
|
|
15
15
|
## Install
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
|
|
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
|
|
21
|
+
pip install recapi
|
|
22
22
|
```
|
|
23
23
|
|
|
24
|
-
|
|
25
|
-
|
|
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.4-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
|
|
@@ -86,14 +94,31 @@ By default each process keeps its users' state in memory (the 10,000 most
|
|
|
86
94
|
recently seen users). That is enough for one process. When several
|
|
87
95
|
processes or servers serve the same users, give them a shared store: any
|
|
88
96
|
object with `get(key)`, `set(key, value)` (strings) and `delete(key)` works,
|
|
89
|
-
such as a Redis client or Django's cache.
|
|
97
|
+
such as a Redis client or Django's Redis or Memcached cache.
|
|
90
98
|
|
|
91
99
|
```python
|
|
92
100
|
client = recapi.Client("rk_sec_…", "https://api.example.com", store=redis.Redis())
|
|
93
|
-
# or, in Django (from django.core.cache import cache):
|
|
101
|
+
# or, in Django with one of those caches (from django.core.cache import cache):
|
|
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
|
+
|
|
112
|
+
Not every Django cache can hold this. The library recognises Django's own
|
|
113
|
+
classes (a subclass of one is left alone) and logs one line at start:
|
|
114
|
+
|
|
115
|
+
| Django cache | What happens | Shared between |
|
|
116
|
+
|---|---|---|
|
|
117
|
+
| `RedisCache`, `PyMemcacheCache`, `PyLibMCCache` | used, no line | servers |
|
|
118
|
+
| `FileBasedCache` | used, with a warning: it holds 300 entries by default | one server's processes |
|
|
119
|
+
| `LocMemCache` (Django's default) | the library's own store instead, with a warning | nothing |
|
|
120
|
+
| `DummyCache` | the library's own store instead, with a warning | nothing |
|
|
121
|
+
|
|
97
122
|
A user the store doesn't know yet (a new process, an evicted user, another
|
|
98
123
|
server) still gets personalised results: the request then has no history,
|
|
99
124
|
recapi uses the history it keeps from that user's events, and returns it with
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "recapi"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.4"
|
|
8
8
|
description = "Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -29,7 +29,7 @@ from typing import Any, Protocol
|
|
|
29
29
|
|
|
30
30
|
from .history import History, is_id
|
|
31
31
|
|
|
32
|
-
__version__ = "0.4.
|
|
32
|
+
__version__ = "0.4.4"
|
|
33
33
|
|
|
34
34
|
log = logging.getLogger("recapi")
|
|
35
35
|
Tags = Sequence[str] | None
|
|
@@ -60,6 +60,27 @@ 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")
|
|
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")
|
|
63
84
|
PUBLIC_KEY_PREFIX = "rk_pub_"
|
|
64
85
|
# Open connections kept between calls: one per call in flight at the busiest
|
|
65
86
|
# moment (AsyncClient runs 8 at once), so a burst of threads can't leave
|
|
@@ -164,6 +185,56 @@ class Store(Protocol):
|
|
|
164
185
|
def delete(self, key: str) -> object: ... # noqa: D102
|
|
165
186
|
|
|
166
187
|
|
|
188
|
+
def _lifetime_argument(store: Store) -> dict[str, int]:
|
|
189
|
+
"""Return what makes ``store.set`` expire the entry; nothing for a store it doesn't recognise.
|
|
190
|
+
|
|
191
|
+
By class name, since the library imports neither package. Any doubt (a
|
|
192
|
+
subclass's own ``set``, another client) means today's ``set(key, value)``.
|
|
193
|
+
"""
|
|
194
|
+
write = getattr(store, "set", None)
|
|
195
|
+
function = getattr(write, "__func__", None)
|
|
196
|
+
if (
|
|
197
|
+
getattr(function, "__module__", ""),
|
|
198
|
+
getattr(function, "__qualname__", ""),
|
|
199
|
+
) in _REDIS_PY_SET:
|
|
200
|
+
return {"ex": STATE_LIFETIME_SECONDS}
|
|
201
|
+
# Django's ``cache`` is a proxy of a per-thread backend, and its class says
|
|
202
|
+
# nothing: only the bound method leads to the backend.
|
|
203
|
+
backend = type(getattr(write, "__self__", None))
|
|
204
|
+
if any((c.__module__, c.__qualname__) == _DJANGO_CACHE for c in backend.__mro__):
|
|
205
|
+
return {"timeout": STATE_LIFETIME_SECONDS}
|
|
206
|
+
return {}
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _store_to_use(store: Store) -> Store:
|
|
210
|
+
"""Return ``store``, or our own in its place if it is a Django cache that loses state.
|
|
211
|
+
|
|
212
|
+
Says so in one line, at start only. Any doubt, or a store that fails here
|
|
213
|
+
(Django's ``cache`` reads the settings at this first touch), means ``store``.
|
|
214
|
+
"""
|
|
215
|
+
try:
|
|
216
|
+
# As in _lifetime_argument: only the bound method leads to Django's backend.
|
|
217
|
+
backend = type(getattr(store.set, "__self__", None))
|
|
218
|
+
name = (backend.__module__, backend.__qualname__)
|
|
219
|
+
if name in _DJANGO_USE_OURS:
|
|
220
|
+
log.warning(
|
|
221
|
+
"recapi: Django's %s %s, so recapi uses its own in-process store (10,000 users)."
|
|
222
|
+
" For several processes or servers, configure Django's Redis or Memcached cache.",
|
|
223
|
+
name[1],
|
|
224
|
+
_DJANGO_USE_OURS[name],
|
|
225
|
+
)
|
|
226
|
+
return MemoryStore()
|
|
227
|
+
if name == _DJANGO_FILES:
|
|
228
|
+
log.warning(
|
|
229
|
+
"recapi: Django's FileBasedCache isn't shared between servers and holds 300"
|
|
230
|
+
" entries by default. For several servers or more visitors, configure Django's"
|
|
231
|
+
" Redis or Memcached cache.",
|
|
232
|
+
)
|
|
233
|
+
except Exception:
|
|
234
|
+
return store
|
|
235
|
+
return store
|
|
236
|
+
|
|
237
|
+
|
|
167
238
|
class MemoryStore:
|
|
168
239
|
"""In-process store keeping the most recently used ``max_users`` users."""
|
|
169
240
|
|
|
@@ -261,7 +332,8 @@ class Client:
|
|
|
261
332
|
user's history from recapi when the store lacks it.
|
|
262
333
|
base_url: Your recapi API origin, e.g. ``https://api.example.com``.
|
|
263
334
|
store: Per-user history and attribution state; defaults to an
|
|
264
|
-
in-memory :class:`MemoryStore
|
|
335
|
+
in-memory :class:`MemoryStore`, which also replaces Django's
|
|
336
|
+
``LocMemCache`` and ``DummyCache``. Pass a shared store (Redis...) when
|
|
265
337
|
several processes serve the same users.
|
|
266
338
|
timeout: Per-request timeout in seconds (recommend() uses at most 1.5).
|
|
267
339
|
flush_interval: Seconds between background event sends.
|
|
@@ -298,7 +370,7 @@ class Client:
|
|
|
298
370
|
self._proxy_auth = _basic_auth(self._proxy)
|
|
299
371
|
# Through a plain HTTP proxy, a request names the whole URL.
|
|
300
372
|
self._target_base = self._base if self._proxy and url.scheme == "http" else url.path
|
|
301
|
-
self._store: Store = store if store is not None else MemoryStore()
|
|
373
|
+
self._store: Store = _store_to_use(store) if store is not None else MemoryStore()
|
|
302
374
|
self._timeout = timeout
|
|
303
375
|
self._interval = flush_interval
|
|
304
376
|
self._max_batch = min(max(1, max_batch), MAX_EVENTS_PER_REQUEST)
|
|
@@ -784,7 +856,7 @@ class Client:
|
|
|
784
856
|
|
|
785
857
|
def _save(self, key: str, state: _UserState, now: int) -> None:
|
|
786
858
|
try:
|
|
787
|
-
self._store.set(key, state.dumps(now))
|
|
859
|
+
self._store.set(key, state.dumps(now), **_lifetime_argument(self._store))
|
|
788
860
|
except Exception:
|
|
789
861
|
log.exception("recapi: store write failed")
|
|
790
862
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.4
|
|
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
|
-
|
|
28
|
-
|
|
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
|
|
31
|
+
pip install recapi
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
-
|
|
35
|
-
|
|
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.4-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
|
|
@@ -96,14 +104,31 @@ By default each process keeps its users' state in memory (the 10,000 most
|
|
|
96
104
|
recently seen users). That is enough for one process. When several
|
|
97
105
|
processes or servers serve the same users, give them a shared store: any
|
|
98
106
|
object with `get(key)`, `set(key, value)` (strings) and `delete(key)` works,
|
|
99
|
-
such as a Redis client or Django's cache.
|
|
107
|
+
such as a Redis client or Django's Redis or Memcached cache.
|
|
100
108
|
|
|
101
109
|
```python
|
|
102
110
|
client = recapi.Client("rk_sec_…", "https://api.example.com", store=redis.Redis())
|
|
103
|
-
# or, in Django (from django.core.cache import cache):
|
|
111
|
+
# or, in Django with one of those caches (from django.core.cache import cache):
|
|
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
|
+
|
|
122
|
+
Not every Django cache can hold this. The library recognises Django's own
|
|
123
|
+
classes (a subclass of one is left alone) and logs one line at start:
|
|
124
|
+
|
|
125
|
+
| Django cache | What happens | Shared between |
|
|
126
|
+
|---|---|---|
|
|
127
|
+
| `RedisCache`, `PyMemcacheCache`, `PyLibMCCache` | used, no line | servers |
|
|
128
|
+
| `FileBasedCache` | used, with a warning: it holds 300 entries by default | one server's processes |
|
|
129
|
+
| `LocMemCache` (Django's default) | the library's own store instead, with a warning | nothing |
|
|
130
|
+
| `DummyCache` | the library's own store instead, with a warning | nothing |
|
|
131
|
+
|
|
107
132
|
A user the store doesn't know yet (a new process, an evicted user, another
|
|
108
133
|
server) still gets personalised results: the request then has no history,
|
|
109
134
|
recapi uses the history it keeps from that user's events, and returns it with
|
|
@@ -0,0 +1,429 @@
|
|
|
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 tempfile
|
|
12
|
+
import threading
|
|
13
|
+
import unittest
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
from unittest import addModuleCleanup, mock
|
|
17
|
+
|
|
18
|
+
import recapi
|
|
19
|
+
from fakeapi import KEY, APITest
|
|
20
|
+
from recapi import client as rc
|
|
21
|
+
|
|
22
|
+
DAY = 24 * 60 * 60
|
|
23
|
+
MINUTE_MS = 60_000
|
|
24
|
+
# Written out rather than read from the library: a change must be a decision.
|
|
25
|
+
LIFETIME = 30 * DAY
|
|
26
|
+
ROOT = Path(__file__).resolve().parents[3]
|
|
27
|
+
CLIENTS = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "recapi/store-clients-1"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def setUpModule() -> None:
|
|
31
|
+
subprocess.run(
|
|
32
|
+
[sys.executable, str(ROOT / "scripts/fetch_store_clients.py"), str(CLIENTS)], check=True
|
|
33
|
+
)
|
|
34
|
+
sys.path.append(str(CLIENTS / "python"))
|
|
35
|
+
from django.conf import settings
|
|
36
|
+
|
|
37
|
+
if not settings.configured:
|
|
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)
|
|
43
|
+
settings.configure(
|
|
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
|
+
}
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def tearDownModule() -> None:
|
|
57
|
+
sys.path.remove(str(CLIENTS / "python"))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class FakeRedis:
|
|
61
|
+
"""Enough of a Redis server for redis-py: GET, SET with its options, DEL, the handshake."""
|
|
62
|
+
|
|
63
|
+
def __init__(self) -> None:
|
|
64
|
+
self.data: dict[str, str] = {}
|
|
65
|
+
self.commands: list[list[str]] = []
|
|
66
|
+
fake = self
|
|
67
|
+
|
|
68
|
+
class Handler(socketserver.StreamRequestHandler):
|
|
69
|
+
def handle(self) -> None:
|
|
70
|
+
with contextlib.suppress(ConnectionError, ValueError):
|
|
71
|
+
while line := self.rfile.readline():
|
|
72
|
+
words = [self.word() for _ in range(int(line[1:]))]
|
|
73
|
+
self.wfile.write(fake.answer(words))
|
|
74
|
+
|
|
75
|
+
def word(self) -> str:
|
|
76
|
+
size = int(self.rfile.readline()[1:])
|
|
77
|
+
# Django's Redis backend pickles values.
|
|
78
|
+
return self.rfile.read(size + 2)[:-2].decode("utf-8", "surrogateescape")
|
|
79
|
+
|
|
80
|
+
self.server = socketserver.ThreadingTCPServer(("127.0.0.1", 0), Handler)
|
|
81
|
+
self.server.daemon_threads = True
|
|
82
|
+
self.port = self.server.server_address[1]
|
|
83
|
+
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
|
84
|
+
|
|
85
|
+
def answer(self, words: list[str]) -> bytes:
|
|
86
|
+
command = words[0].upper()
|
|
87
|
+
if command == "HELLO":
|
|
88
|
+
return b"%1\r\n+proto\r\n:" + words[1].encode() + b"\r\n"
|
|
89
|
+
if command == "GET":
|
|
90
|
+
value = self.data.get(words[1])
|
|
91
|
+
if value is None:
|
|
92
|
+
return b"_\r\n" # RESP3's null: both clients ask for RESP3 in their handshake
|
|
93
|
+
encoded = value.encode("utf-8", "surrogateescape")
|
|
94
|
+
return b"$%d\r\n%s\r\n" % (len(encoded), encoded)
|
|
95
|
+
if command == "SET":
|
|
96
|
+
self.commands.append(words)
|
|
97
|
+
self.data[words[1]] = words[2]
|
|
98
|
+
if command == "DEL":
|
|
99
|
+
self.commands.append(words)
|
|
100
|
+
return b":%d\r\n" % (self.data.pop(words[1], None) is not None)
|
|
101
|
+
return b"+OK\r\n"
|
|
102
|
+
|
|
103
|
+
def close(self) -> None:
|
|
104
|
+
self.server.shutdown()
|
|
105
|
+
self.server.server_close()
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class StoreTest(APITest):
|
|
109
|
+
def setUp(self) -> None:
|
|
110
|
+
super().setUp()
|
|
111
|
+
# Django reads time.time(): one clock for the cache's expiry and the library.
|
|
112
|
+
patcher = mock.patch("time.time", lambda: self.clock / 1000)
|
|
113
|
+
patcher.start()
|
|
114
|
+
self.addCleanup(patcher.stop)
|
|
115
|
+
from django.core.cache import cache, caches
|
|
116
|
+
from django.utils.connection import ConnectionProxy
|
|
117
|
+
|
|
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")
|
|
121
|
+
cache.clear()
|
|
122
|
+
self.cache.clear()
|
|
123
|
+
|
|
124
|
+
def redis(self) -> tuple[Any, FakeRedis]:
|
|
125
|
+
import redis
|
|
126
|
+
|
|
127
|
+
fake = FakeRedis()
|
|
128
|
+
self.addCleanup(fake.close)
|
|
129
|
+
client = redis.Redis(port=fake.port, socket_timeout=5)
|
|
130
|
+
self.addCleanup(client.close)
|
|
131
|
+
return client, fake
|
|
132
|
+
|
|
133
|
+
def async_client(self, **options: Any) -> recapi.AsyncClient:
|
|
134
|
+
client = recapi.AsyncClient(KEY, self.api.url, flush_interval=3600, **options)
|
|
135
|
+
self.addCleanup(lambda: asyncio.run(client.close()))
|
|
136
|
+
return client
|
|
137
|
+
|
|
138
|
+
def clicked(self) -> dict[str, Any]:
|
|
139
|
+
return self.last_body("/v1/events")["events"][-1]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class Django(StoreTest):
|
|
143
|
+
def test_a_click_after_six_minutes_keeps_its_credit(self) -> None:
|
|
144
|
+
client = self.client(store=self.cache)
|
|
145
|
+
self.assertEqual(client.recommend(anon_id="v", count=2).recommendation_id, "rec_1")
|
|
146
|
+
self.clock += 6 * MINUTE_MS
|
|
147
|
+
client.track("r1", "view", anon_id="v")
|
|
148
|
+
client.flush()
|
|
149
|
+
self.assertEqual(self.clicked().get("recommendation_id"), "rec_1")
|
|
150
|
+
|
|
151
|
+
def test_a_click_after_six_minutes_keeps_its_credit_with_the_async_client(self) -> None:
|
|
152
|
+
client = self.async_client(store=self.cache)
|
|
153
|
+
|
|
154
|
+
async def visit() -> None:
|
|
155
|
+
await client.recommend(anon_id="v", count=2)
|
|
156
|
+
self.clock += 6 * MINUTE_MS
|
|
157
|
+
await client.track("r1", "view", anon_id="v")
|
|
158
|
+
await client.flush()
|
|
159
|
+
|
|
160
|
+
asyncio.run(visit())
|
|
161
|
+
self.assertEqual(self.clicked().get("recommendation_id"), "rec_1")
|
|
162
|
+
|
|
163
|
+
def test_the_entry_lasts_30_days_from_its_last_write(self) -> None:
|
|
164
|
+
client = self.client(store=self.cache)
|
|
165
|
+
key = client._key("u", None)
|
|
166
|
+
client.track("a", 3, user_id="u")
|
|
167
|
+
self.clock += 20 * DAY * 1000
|
|
168
|
+
client.track("b", 3, user_id="u") # restarts the lifetime
|
|
169
|
+
self.clock += (LIFETIME - 1) * 1000
|
|
170
|
+
self.assertIsNotNone(self.cache.get(key))
|
|
171
|
+
self.clock += 2 * 1000
|
|
172
|
+
self.assertIsNone(self.cache.get(key))
|
|
173
|
+
|
|
174
|
+
def test_a_backend_taken_from_caches_is_recognised_too(self) -> None:
|
|
175
|
+
from django.core.cache import caches
|
|
176
|
+
|
|
177
|
+
self.assertEqual(rc._lifetime_argument(caches["default"]), {"timeout": LIFETIME})
|
|
178
|
+
|
|
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
|
+
|
|
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
|
+
|
|
316
|
+
def test_a_write_carries_the_expiry(self) -> None:
|
|
317
|
+
store, fake = self.redis()
|
|
318
|
+
client = self.client(store=store)
|
|
319
|
+
client.track("a", 3, user_id="u")
|
|
320
|
+
key = client._key("u", None)
|
|
321
|
+
self.assertEqual(fake.commands[-1][:2], ["SET", key])
|
|
322
|
+
self.assertEqual(fake.commands[-1][3:], ["EX", str(LIFETIME)])
|
|
323
|
+
|
|
324
|
+
def test_a_write_carries_the_expiry_with_the_async_client(self) -> None:
|
|
325
|
+
store, fake = self.redis()
|
|
326
|
+
client = self.async_client(store=store)
|
|
327
|
+
asyncio.run(client.track("a", 3, user_id="u"))
|
|
328
|
+
self.assertEqual(fake.commands[-1][3:], ["EX", str(LIFETIME)])
|
|
329
|
+
|
|
330
|
+
def test_a_click_after_six_minutes_keeps_its_credit(self) -> None:
|
|
331
|
+
store, _ = self.redis()
|
|
332
|
+
client = self.client(store=store)
|
|
333
|
+
client.recommend(anon_id="v", count=2)
|
|
334
|
+
self.clock += 6 * MINUTE_MS
|
|
335
|
+
client.track("r1", "view", anon_id="v")
|
|
336
|
+
client.flush()
|
|
337
|
+
self.assertEqual(self.clicked().get("recommendation_id"), "rec_1")
|
|
338
|
+
|
|
339
|
+
def test_a_subclass_with_its_own_set_gets_a_plain_set(self) -> None:
|
|
340
|
+
import redis
|
|
341
|
+
|
|
342
|
+
class Mine(redis.Redis):
|
|
343
|
+
def set(self, name: str, value: str) -> Any:
|
|
344
|
+
return super().set(name, value)
|
|
345
|
+
|
|
346
|
+
fake = FakeRedis()
|
|
347
|
+
self.addCleanup(fake.close)
|
|
348
|
+
store = Mine(port=fake.port, socket_timeout=5)
|
|
349
|
+
self.addCleanup(store.close)
|
|
350
|
+
self.client(store=store).track("a", 3, user_id="u")
|
|
351
|
+
self.assertEqual(len(fake.commands[-1]), 3)
|
|
352
|
+
|
|
353
|
+
def test_a_store_that_raises_is_logged_and_skipped(self) -> None:
|
|
354
|
+
import redis
|
|
355
|
+
from redis.backoff import NoBackoff
|
|
356
|
+
from redis.retry import Retry
|
|
357
|
+
|
|
358
|
+
fake = FakeRedis()
|
|
359
|
+
fake.close()
|
|
360
|
+
# No retries: redis-py's default backs off for seconds on a refused connection.
|
|
361
|
+
down = redis.Redis(port=fake.port, retry=Retry(NoBackoff(), 0))
|
|
362
|
+
self.addCleanup(down.close)
|
|
363
|
+
client = self.client(store=down)
|
|
364
|
+
with self.assertLogs("recapi", "ERROR") as logs:
|
|
365
|
+
client.track("a", 3, user_id="u")
|
|
366
|
+
self.assertIn("recapi: store write failed", "\n".join(logs.output))
|
|
367
|
+
client.flush()
|
|
368
|
+
self.assertEqual(self.clicked()["item_id"], "a")
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
class OtherStores(unittest.TestCase):
|
|
372
|
+
class Mine:
|
|
373
|
+
"""A store of the customer's, whose arguments happen to carry the same names."""
|
|
374
|
+
|
|
375
|
+
def __init__(self) -> None:
|
|
376
|
+
self.writes: list[tuple[Any, ...]] = []
|
|
377
|
+
|
|
378
|
+
def set(self, key: str, value: str, timeout: int = 0, ex: int = 0) -> None:
|
|
379
|
+
self.writes.append((key, timeout, ex))
|
|
380
|
+
|
|
381
|
+
def get(self, key: str) -> None:
|
|
382
|
+
return None
|
|
383
|
+
|
|
384
|
+
def delete(self, key: str) -> None:
|
|
385
|
+
pass
|
|
386
|
+
|
|
387
|
+
def test_a_store_the_library_doesnt_recognise_gets_a_plain_set(self) -> None:
|
|
388
|
+
store = self.Mine()
|
|
389
|
+
client = recapi.Client(KEY, "http://127.0.0.1:9", store=store, flush_interval=3600)
|
|
390
|
+
self.addCleanup(client.close)
|
|
391
|
+
client._save("k", rc._UserState(), 0)
|
|
392
|
+
self.assertEqual(store.writes, [("k", 0, 0)])
|
|
393
|
+
|
|
394
|
+
def test_older_redis_clients_are_recognised_where_they_define_set(self) -> None:
|
|
395
|
+
# The pinned redis-py is the newest shape; these were read in 3.5.3 and 4.0.2.
|
|
396
|
+
for module, qualname in (
|
|
397
|
+
("redis.client", "Redis.set"),
|
|
398
|
+
("redis.commands.core", "CoreCommands.set"),
|
|
399
|
+
):
|
|
400
|
+
with self.subTest(qualname):
|
|
401
|
+
|
|
402
|
+
class Older:
|
|
403
|
+
def set(self, key: str, value: str, ex: int = 0) -> None:
|
|
404
|
+
pass
|
|
405
|
+
|
|
406
|
+
Older.set.__module__ = module
|
|
407
|
+
Older.set.__qualname__ = qualname
|
|
408
|
+
self.assertEqual(rc._lifetime_argument(Older()), {"ex": LIFETIME})
|
|
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
|
+
|
|
426
|
+
def test_stores_without_a_bound_set_get_a_plain_set(self) -> None:
|
|
427
|
+
for store in (object(), mock.Mock(), recapi.MemoryStore(), None):
|
|
428
|
+
with self.subTest(store=type(store).__name__):
|
|
429
|
+
self.assertEqual(rc._lifetime_argument(store), {})
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|