recapi 0.4.3__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.3/recapi.egg-info → recapi-0.4.4}/PKG-INFO +14 -6
- {recapi-0.4.3 → recapi-0.4.4}/README.md +13 -5
- {recapi-0.4.3 → recapi-0.4.4}/pyproject.toml +1 -1
- {recapi-0.4.3 → recapi-0.4.4}/recapi/client.py +41 -3
- {recapi-0.4.3 → recapi-0.4.4/recapi.egg-info}/PKG-INFO +14 -6
- {recapi-0.4.3 → recapi-0.4.4}/tests/test_stores.py +175 -6
- {recapi-0.4.3 → recapi-0.4.4}/LICENSE +0 -0
- {recapi-0.4.3 → recapi-0.4.4}/recapi/__init__.py +0 -0
- {recapi-0.4.3 → recapi-0.4.4}/recapi/async_client.py +0 -0
- {recapi-0.4.3 → recapi-0.4.4}/recapi/history.py +0 -0
- {recapi-0.4.3 → recapi-0.4.4}/recapi.egg-info/SOURCES.txt +0 -0
- {recapi-0.4.3 → recapi-0.4.4}/recapi.egg-info/dependency_links.txt +0 -0
- {recapi-0.4.3 → recapi-0.4.4}/recapi.egg-info/top_level.txt +0 -0
- {recapi-0.4.3 → recapi-0.4.4}/setup.cfg +0 -0
- {recapi-0.4.3 → recapi-0.4.4}/tests/test_async_client.py +0 -0
- {recapi-0.4.3 → recapi-0.4.4}/tests/test_client.py +0 -0
- {recapi-0.4.3 → recapi-0.4.4}/tests/test_client_vectors.py +0 -0
- {recapi-0.4.3 → 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
|
|
@@ -37,7 +37,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
37
37
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
38
|
|
|
39
39
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
40
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.4-py3-none-any.whl
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -104,11 +104,11 @@ By default each process keeps its users' state in memory (the 10,000 most
|
|
|
104
104
|
recently seen users). That is enough for one process. When several
|
|
105
105
|
processes or servers serve the same users, give them a shared store: any
|
|
106
106
|
object with `get(key)`, `set(key, value)` (strings) and `delete(key)` works,
|
|
107
|
-
such as a Redis client or Django's cache.
|
|
107
|
+
such as a Redis client or Django's Redis or Memcached cache.
|
|
108
108
|
|
|
109
109
|
```python
|
|
110
110
|
client = recapi.Client("rk_sec_…", "https://api.example.com", store=redis.Redis())
|
|
111
|
-
# or, in Django (from django.core.cache import cache):
|
|
111
|
+
# or, in Django with one of those caches (from django.core.cache import cache):
|
|
112
112
|
client = recapi.Client("rk_sec_…", "https://api.example.com", store=cache)
|
|
113
113
|
```
|
|
114
114
|
|
|
@@ -118,8 +118,16 @@ earns credit, and recapi gives a known `user_id` its history back afterwards.
|
|
|
118
118
|
Without it, Django would drop the state after its default 5 minutes, taking the
|
|
119
119
|
click's credit with it, and Redis would keep it for ever. Any other store gets a
|
|
120
120
|
plain `set(key, value)`: make it expire entries itself after about 30 days.
|
|
121
|
-
|
|
122
|
-
|
|
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 |
|
|
123
131
|
|
|
124
132
|
A user the store doesn't know yet (a new process, an evicted user, another
|
|
125
133
|
server) still gets personalised results: the request then has no history,
|
|
@@ -27,7 +27,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
27
27
|
(the dashboard's quick start shows the line with your API's address):
|
|
28
28
|
|
|
29
29
|
```sh
|
|
30
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
30
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.4-py3-none-any.whl
|
|
31
31
|
```
|
|
32
32
|
|
|
33
33
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -94,11 +94,11 @@ By default each process keeps its users' state in memory (the 10,000 most
|
|
|
94
94
|
recently seen users). That is enough for one process. When several
|
|
95
95
|
processes or servers serve the same users, give them a shared store: any
|
|
96
96
|
object with `get(key)`, `set(key, value)` (strings) and `delete(key)` works,
|
|
97
|
-
such as a Redis client or Django's cache.
|
|
97
|
+
such as a Redis client or Django's Redis or Memcached cache.
|
|
98
98
|
|
|
99
99
|
```python
|
|
100
100
|
client = recapi.Client("rk_sec_…", "https://api.example.com", store=redis.Redis())
|
|
101
|
-
# or, in Django (from django.core.cache import cache):
|
|
101
|
+
# or, in Django with one of those caches (from django.core.cache import cache):
|
|
102
102
|
client = recapi.Client("rk_sec_…", "https://api.example.com", store=cache)
|
|
103
103
|
```
|
|
104
104
|
|
|
@@ -108,8 +108,16 @@ earns credit, and recapi gives a known `user_id` its history back afterwards.
|
|
|
108
108
|
Without it, Django would drop the state after its default 5 minutes, taking the
|
|
109
109
|
click's credit with it, and Redis would keep it for ever. Any other store gets a
|
|
110
110
|
plain `set(key, value)`: make it expire entries itself after about 30 days.
|
|
111
|
-
|
|
112
|
-
|
|
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 |
|
|
113
121
|
|
|
114
122
|
A user the store doesn't know yet (a new process, an evicted user, another
|
|
115
123
|
server) still gets personalised results: the request then has no history,
|
|
@@ -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
|
|
@@ -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
|
|
@@ -198,6 +206,35 @@ def _lifetime_argument(store: Store) -> dict[str, int]:
|
|
|
198
206
|
return {}
|
|
199
207
|
|
|
200
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
|
+
|
|
201
238
|
class MemoryStore:
|
|
202
239
|
"""In-process store keeping the most recently used ``max_users`` users."""
|
|
203
240
|
|
|
@@ -295,7 +332,8 @@ class Client:
|
|
|
295
332
|
user's history from recapi when the store lacks it.
|
|
296
333
|
base_url: Your recapi API origin, e.g. ``https://api.example.com``.
|
|
297
334
|
store: Per-user history and attribution state; defaults to an
|
|
298
|
-
in-memory :class:`MemoryStore
|
|
335
|
+
in-memory :class:`MemoryStore`, which also replaces Django's
|
|
336
|
+
``LocMemCache`` and ``DummyCache``. Pass a shared store (Redis...) when
|
|
299
337
|
several processes serve the same users.
|
|
300
338
|
timeout: Per-request timeout in seconds (recommend() uses at most 1.5).
|
|
301
339
|
flush_interval: Seconds between background event sends.
|
|
@@ -332,7 +370,7 @@ class Client:
|
|
|
332
370
|
self._proxy_auth = _basic_auth(self._proxy)
|
|
333
371
|
# Through a plain HTTP proxy, a request names the whole URL.
|
|
334
372
|
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()
|
|
373
|
+
self._store: Store = _store_to_use(store) if store is not None else MemoryStore()
|
|
336
374
|
self._timeout = timeout
|
|
337
375
|
self._interval = flush_interval
|
|
338
376
|
self._max_batch = min(max(1, max_batch), MAX_EVENTS_PER_REQUEST)
|
|
@@ -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
|
|
@@ -37,7 +37,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
37
37
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
38
|
|
|
39
39
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
40
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.4-py3-none-any.whl
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -104,11 +104,11 @@ By default each process keeps its users' state in memory (the 10,000 most
|
|
|
104
104
|
recently seen users). That is enough for one process. When several
|
|
105
105
|
processes or servers serve the same users, give them a shared store: any
|
|
106
106
|
object with `get(key)`, `set(key, value)` (strings) and `delete(key)` works,
|
|
107
|
-
such as a Redis client or Django's cache.
|
|
107
|
+
such as a Redis client or Django's Redis or Memcached cache.
|
|
108
108
|
|
|
109
109
|
```python
|
|
110
110
|
client = recapi.Client("rk_sec_…", "https://api.example.com", store=redis.Redis())
|
|
111
|
-
# or, in Django (from django.core.cache import cache):
|
|
111
|
+
# or, in Django with one of those caches (from django.core.cache import cache):
|
|
112
112
|
client = recapi.Client("rk_sec_…", "https://api.example.com", store=cache)
|
|
113
113
|
```
|
|
114
114
|
|
|
@@ -118,8 +118,16 @@ earns credit, and recapi gives a known `user_id` its history back afterwards.
|
|
|
118
118
|
Without it, Django would drop the state after its default 5 minutes, taking the
|
|
119
119
|
click's credit with it, and Redis would keep it for ever. Any other store gets a
|
|
120
120
|
plain `set(key, value)`: make it expire entries itself after about 30 days.
|
|
121
|
-
|
|
122
|
-
|
|
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 |
|
|
123
131
|
|
|
124
132
|
A user the store doesn't know yet (a new process, an evicted user, another
|
|
125
133
|
server) still gets personalised results: the request then has no history,
|
|
@@ -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={
|
|
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
|
-
|
|
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.
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|