recapi 0.4.2__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.2
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.2-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,6 +112,15 @@ 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
@@ -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.2-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,6 +102,15 @@ 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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "recapi"
7
- version = "0.4.2"
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.2"
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
 
@@ -784,7 +818,7 @@ class Client:
784
818
 
785
819
  def _save(self, key: str, state: _UserState, now: int) -> None:
786
820
  try:
787
- self._store.set(key, state.dumps(now))
821
+ self._store.set(key, state.dumps(now), **_lifetime_argument(self._store))
788
822
  except Exception:
789
823
  log.exception("recapi: store write failed")
790
824
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: recapi
3
- Version: 0.4.2
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.2-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,6 +112,15 @@ 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
@@ -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
@@ -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
File without changes