1import json
2from collections.abc import Callable, Iterable, Mapping
3from datetime import datetime, timedelta
4from typing import TYPE_CHECKING, Any
5
6from plain.postgres import get_connection, transaction
7from plain.postgres.dialect import quote_name
8from plain.utils import timezone
9
10if TYPE_CHECKING:
11 from .models import CachedItem
12
13# An expiration argument: seconds (int/float), a timedelta, an absolute
14# datetime, or None for "never expires".
15Expiration = datetime | timedelta | int | float | None
16
17
18def _coerce_expiration(expiration: Expiration, *, now: datetime) -> datetime | None:
19 """Resolve an `expiration` argument to a timezone-aware `datetime`, or `None`
20 for "never expires". Relative expirations are measured from `now`, which the
21 caller passes in so a single write derives its expiry and row timestamps from
22 one instant.
23
24 Accepts seconds (`int`/`float`), a `timedelta`, or an absolute `datetime`.
25 Unsupported types are rejected loudly rather than silently treated as "no
26 expiry" -- in particular a `bool` (which is an `int` subclass) and a bare
27 `date` (which is not a `datetime`) are common mistakes.
28 """
29 if expiration is None:
30 return None
31
32 if isinstance(expiration, bool):
33 raise TypeError(
34 "expiration must be seconds, a timedelta, or a datetime -- not a bool"
35 )
36
37 if isinstance(expiration, int | float):
38 expires_at = now + timedelta(seconds=expiration)
39 elif isinstance(expiration, timedelta):
40 expires_at = now + expiration
41 elif isinstance(expiration, datetime):
42 expires_at = expiration
43 else:
44 raise TypeError(
45 "expiration must be seconds, a timedelta, or a datetime -- got "
46 f"{type(expiration).__name__}"
47 )
48
49 if not timezone.is_aware(expires_at):
50 expires_at = timezone.make_aware(expires_at)
51 return expires_at
52
53
54class Cache:
55 """A key/value cache backed by the `CachedItem` Postgres model.
56
57 Reads are expiry-aware: an entry past its `expires_at` reads as absent (the
58 `clear_expired` chore / `plain cache clear-expired` deletes it out of band).
59 Stateless -- nothing is held between calls, so every read reflects the
60 current row. Stored values must be JSON-serializable.
61
62 Use the module-level `cache` singleton: `from plain.cache import cache`.
63 """
64
65 @property
66 def _model(self) -> type[CachedItem]:
67 # Imported lazily so `from plain.cache import cache` works at import time,
68 # before the packages registry is ready.
69 from .models import CachedItem
70
71 return CachedItem
72
73 # Reading -----------------------------------------------------------------
74
75 def get(self, key: str, default: Any = None) -> Any:
76 """Return the value for `key`, or `default` if it's absent or expired."""
77 model = self._model
78 item = model.query.live().first(model.key.equals(key))
79 return item.value if item is not None else default
80
81 def get_many(self, keys: Iterable[str]) -> dict[str, Any]:
82 """Return a `{key: value}` dict of the live entries among `keys`.
83
84 Missing/expired keys are omitted. One query regardless of how many keys.
85 """
86 model = self._model
87 items = model.query.live().where(model.key.is_in(list(keys)))
88 return {item.key: item.value for item in items}
89
90 # Writing -----------------------------------------------------------------
91
92 def set(self, key: str, value: Any, *, expiration: Expiration = None) -> None:
93 """Store `value` under `key`. `expiration=None` (the default) never expires.
94
95 Always rewrites the whole entry, including its expiry -- to change only
96 the expiry of a large value without rewriting it, use `touch()`.
97 """
98 # A single-key upsert -- same one-statement INSERT ... ON CONFLICT path
99 # as set_many(), so set/set_many share one write mechanism.
100 self.set_many({key: value}, expiration=expiration)
101
102 def set_many(
103 self, mapping: Mapping[str, Any], *, expiration: Expiration = None
104 ) -> None:
105 """Store every `{key: value}` in `mapping` with a shared expiration."""
106 if not mapping:
107 return
108
109 # bulk_upsert fires pre_save and refreshes update_now columns on the
110 # conflict path, so updated_at looks after itself. created_at (no
111 # update_now) would otherwise fall to its DB default, evaluated a hair
112 # later -- leaving a brand-new row with updated_at < created_at. Stamp
113 # created_at from an up-front `now` so created_at <= updated_at; being
114 # DB-owned it can't be named in update_fields, so it survives conflicts.
115 now = timezone.now()
116 expires_at = _coerce_expiration(expiration, now=now)
117 items = []
118 for key, value in mapping.items():
119 item = self._model(key=key, value=value, expires_at=expires_at)
120 # created_at is a create_now field (DB-owned), so it's not a
121 # constructor argument -- stamp it from the shared `now` after
122 # construction so created_at <= updated_at (see comment above).
123 item.created_at = now
124 items.append(item)
125 model = self._model
126 model.query.bulk_upsert(
127 items,
128 update_fields=[model.value, model.expires_at],
129 unique_fields=[model.key],
130 )
131
132 def get_or_set(
133 self,
134 key: str,
135 default: Callable[[], Any] | Any,
136 *,
137 expiration: Expiration = None,
138 ) -> Any:
139 """Return the value for `key`, computing and storing it on a miss.
140
141 `default` may be a value or a zero-arg callable; the callable is only
142 invoked on a miss (so a callable can't be cached *as* the value). A
143 stored `None` counts as a hit (it won't recompute).
144 """
145 model = self._model
146 item = model.query.live().first(model.key.equals(key))
147 if item is not None:
148 return item.value
149
150 value = default() if callable(default) else default
151 self.set(key, value, expiration=expiration)
152 return value
153
154 # Counters ----------------------------------------------------------------
155
156 def increment(
157 self, key: str, delta: int = 1, *, expiration: Expiration = None
158 ) -> int | float:
159 """Atomically add `delta` to the number at `key` and return the new total.
160
161 One `INSERT ... ON CONFLICT` statement, so concurrent callers can't lose
162 updates the way a read-then-`set()` would -- the right primitive for
163 counters and fixed-window rate limiters.
164
165 Expiry follows a fixed-window rule:
166
167 - A **missing or expired** key starts fresh at `delta` and takes
168 `expiration` -- a lapsed window resets cleanly to a new deadline.
169 - A **live** key adds `delta` to the existing total and keeps its
170 current `expires_at` -- the window holds its original deadline,
171 regardless of the `expiration` argument. (To slide the expiry too,
172 call `touch()`.)
173
174 A key with no numeric value yet -- missing, or storing `None` -- counts
175 as `0`, so the first increment starts from `delta`. Incrementing a key
176 that stores a non-numeric value (a string, list, etc.) raises.
177 """
178 now = timezone.now()
179 expires_at = _coerce_expiration(expiration, now=now)
180 table = quote_name(self._model.model_options.db_table)
181
182 # The existing-row expiry test matches `expired()` (the inverse of the
183 # `live()` filter reads use): an expired row counts as absent, so the
184 # counter restarts from `delta` with a new deadline instead of resuming a
185 # stale total whose window already lapsed. A never-expiring row has
186 # expires_at = NULL, and `NULL < now` is NULL (falsy in CASE), so it
187 # correctly falls through to the accumulate branch.
188 sql = f"""
189 INSERT INTO {table} (key, value, expires_at, created_at, updated_at)
190 VALUES (%(key)s, to_jsonb(%(delta)s::numeric), %(expires_at)s, %(now)s, %(now)s)
191 ON CONFLICT (key) DO UPDATE SET
192 value = CASE
193 WHEN {table}.expires_at < %(now)s
194 THEN EXCLUDED.value
195 -- `value::text` keeps JSON syntax, so a string like "5"
196 -- stays quoted and fails ::numeric -- only a real JSON
197 -- number parses. NULLIF maps JSON null to SQL NULL so
198 -- COALESCE treats a null/absent value as 0.
199 ELSE to_jsonb(COALESCE(NULLIF({table}.value, 'null'::jsonb)::text::numeric, 0) + %(delta)s)
200 END,
201 expires_at = CASE
202 WHEN {table}.expires_at < %(now)s
203 THEN EXCLUDED.expires_at
204 ELSE {table}.expires_at
205 END,
206 updated_at = %(now)s
207 RETURNING value::text
208 """
209 params = {"key": key, "delta": delta, "expires_at": expires_at, "now": now}
210 # A non-numeric value raises DataError, which leaves the DB transaction
211 # aborted. Mark the connection so an enclosing atomic() block rolls back
212 # even if the caller catches the error -- the same guard ORM writes use.
213 with (
214 transaction.mark_for_rollback_on_error(),
215 get_connection().cursor() as cursor,
216 ):
217 cursor.execute(sql, params)
218 row = cursor.fetchone()
219 assert row is not None # INSERT ... ON CONFLICT DO UPDATE always returns a row
220
221 # `value::text` returns the new total as JSON text regardless of driver;
222 # decode it to the same Python number `get()` would yield.
223 return json.loads(row[0])
224
225 def decrement(
226 self, key: str, delta: int = 1, *, expiration: Expiration = None
227 ) -> int | float:
228 """Atomically subtract `delta` from the number at `key`. See `increment()`."""
229 return self.increment(key, -delta, expiration=expiration)
230
231 def touch(self, key: str, *, expiration: Expiration = None) -> bool:
232 """Change a live entry's expiration *without* rewriting its value.
233
234 `set()` always rewrites `value`, so refreshing a large entry's TTL
235 re-TOASTs the whole blob. `touch()` writes only `expires_at` and
236 `updated_at` -- a heap-only write that reuses the existing TOAST pointer,
237 so a multi-megabyte value isn't re-written. Ideal for a sliding-TTL cache
238 of large values.
239
240 `expiration=None` clears the expiry (never expires). Returns `True` if a
241 live entry was updated, `False` if `key` is absent or already expired.
242 """
243 # QuerySet.update() issues a direct SQL UPDATE and does NOT fire pre_save,
244 # so updated_at's update_now won't bump on its own -- stamp it by hand.
245 # (set_many() relies on pre_save instead, since bulk_upsert does fire it.)
246 now = timezone.now()
247 model = self._model
248 updated = (
249 model.query.live()
250 .where(model.key.equals(key))
251 .update(expires_at=_coerce_expiration(expiration, now=now), updated_at=now)
252 )
253 return updated > 0
254
255 # Deleting ----------------------------------------------------------------
256
257 def delete(self, key: str) -> bool:
258 """Delete `key`. Returns `True` if it existed, `False` otherwise."""
259 model = self._model
260 return model.query.where(model.key.equals(key)).delete() > 0
261
262 def delete_many(self, keys: Iterable[str]) -> int:
263 """Delete every key in `keys`. Returns the number of rows deleted."""
264 model = self._model
265 return model.query.where(model.key.is_in(list(keys))).delete()
266
267 def clear(self) -> int:
268 """Delete every entry in the cache. Returns the number of rows deleted."""
269 return self._model.query.all().delete()
270
271
272cache = Cache()