7 Commits
Author SHA1 Message Date
dsql 69e0184cef chore: bump to 1.1.0 (logging-discipline audit)
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-08-10 23:00:50 -04:00
dsql b459fce9a8 fix: log-XOR-raise — demote the pre-raise log to DEBUG, revise the contract (D1)
every wrapped method did log.exception (ERROR + traceback) immediately before re-raising
the driver error — the same failure reported at two layers (the log AND the raised
exception). that is the log-and-raise violation: a method that re-raises must not also
error-log, because the caller — which alone knows whether the failure is fatal or routine
— is the one that logs. demote all wrapped-method logs to log.debug(..., exc_info=True):
the traceback stays available at DEBUG, and the raised exception is the single loud
terminal signal. docstring updated from "logs via getLogger and re-raises" to the
corrected raise-XOR-log contract. no behavior change beyond log level — the fail-loud
re-raise is unchanged.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-08-09 02:18:08 -04:00
dsql 24607aa5f7 release: 1.0.0
first stable release. pre-1.0.0 verification complete: all surviving MED regressions and
gaps resolved and independently re-fired, tree audited clean across the suite.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-09 18:53:15 -04:00
dsql c7deeca5a7 refactor: derive __version__ from package metadata (single source)
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-03 17:00:54 -04:00
dsql 52864e513a docs: add missing __aenter__/__aexit__ docstrings
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-03 16:47:33 -04:00
dsql ea1e3620e6 fix: close() runs pool.disconnect() even if aclose() raises; docs de-bloat + em-dash->hyphen
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-03 00:30:36 -04:00
dsql f0b002a4b3 fix: bump redis floor to 5.0.1, disconnect pool on failed connect(), doc/type nits (redis-5/6/7/8); v0.1.4
redis-5: redis>=5 admitted 5.0.0, which lacks async aclose() and crashes on
teardown; floor bumped to >=5.0.1 (confirmed 5.0.1 is where aclose() lands).
redis-6: connect()/__aenter__ now disconnects the pool before re-raising on a
failed ping, so a discarded RedisDB from a failed `async with` doesn't hold a
live pool. redis-7: docstring/README conflated repo name (redis) with
distribution name (redis_store). redis-8: pool_timeout hinted Optional[float]
to match that None is accepted (wait forever). Also compresses the module and
__init__ docstrings (no behavior change), keeping the SSLConnection-mapping
and pool-disconnect-on-failure notes.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-02 23:34:18 -04:00
4 changed files with 64 additions and 79 deletions
+11 -8
View File
@@ -4,7 +4,7 @@ Async Redis wrapper over redis-py's asyncio client — a small, config-free, **f
key/value + hash + ttl surface with a raw escape hatch for everything else. First of the
datastore trio (`redis` / `psql` / `mysql`), a sibling of the `mongo` lib.
> **Import name ≠ repo name.** The repo/distribution is **`redis`**, but you import
> **Import name ≠ repo name.** The repo is **`redis`**, the distribution is
> **`redis_store`** — the driver package owns the `redis` import namespace, so the lib
> can't also be `redis`. Install resolves `redis.git`; code does
> `from redis_store import RedisDB`.
@@ -14,19 +14,19 @@ datastore trio (`redis` / `psql` / `mysql`), a sibling of the `mongo` lib.
`requirements.txt`:
```
redis_store @ git+ssh://git@git.rethinkstudios.io/rethink-public/redis.git@v0.1.3
redis_store @ git+ssh://git@git.rethinkstudios.io/rethink-public/redis.git@v1.0.0
```
Direct:
```bash
pip install "redis_store @ git+ssh://git@git.rethinkstudios.io/rethink-public/redis.git@v0.1.3"
pip install "redis_store @ git+ssh://git@git.rethinkstudios.io/rethink-public/redis.git@v1.0.0"
```
Pulls `redis>=5` (redis-py, which ships the asyncio client — **not** the dead standalone
`aioredis`).
Pulls `redis>=5.0.1` (redis-py, which ships the asyncio client — **not** the dead standalone
`aioredis`; `5.0.1` is the floor because `5.0.0` lacks the async client's `aclose()`).
Drop the `@v0.1.3` suffix from the line above to install the latest unpinned.
Drop the `@v1.0.0` suffix from the line above to install the latest unpinned.
## Usage
@@ -55,6 +55,8 @@ async with RedisDB(host="localhost") as kv:
```
One client/pool per process — build it once, attach it to your app (`app.kv = ...`), share it.
A failed `connect()`/`__aenter__` ping disconnects the pool before re-raising, so a
discarded `RedisDB` from a failed `async with` doesn't hold a live pool.
## Type contract
@@ -63,8 +65,9 @@ One client/pool per process — build it once, attach it to your app (`app.kv =
Counters and counts (`incr`/`decr`/`exists`/`ttl`) always return `int` regardless.
Pool sizing/timeout are `max_connections=` and `pool_timeout=` (how long a caller waits for
a free connection when the pool is saturated). Pass the driver's own `timeout=` in
`pool_kwargs` and construction raises a clear `ValueError` — use `pool_timeout=`.
a free connection when the pool is saturated; `Optional[float]`, `None` waits forever).
Pass the driver's own `timeout=` in `pool_kwargs` and construction raises a clear
`ValueError` — use `pool_timeout=`.
`ssl=True` maps to `connection_class=redis.asyncio.SSLConnection`, so TLS works via the
documented `pool_kwargs` path (the default connection class has no `ssl` parameter and
+2 -2
View File
@@ -4,11 +4,11 @@ build-backend = "hatchling.build"
[project]
name = "redis_store"
version = "0.1.3"
version = "1.1.0"
description = "async redis wrapper over redis-py asyncio with a raw escape hatch, fail-loud and config-free"
requires-python = ">=3.10"
dependencies = [
"redis>=5",
"redis>=5.0.1",
]
[tool.hatch.build.targets.wheel]
+8 -1
View File
@@ -1,3 +1,10 @@
from importlib.metadata import version, PackageNotFoundError
from .redis_store import RedisDB
__all__ = ["RedisDB"]
try:
__version__ = version("redis_store")
except PackageNotFoundError:
__version__ = "0.0.0+unknown"
__all__ = ["RedisDB", "__version__"]
+41 -66
View File
@@ -12,30 +12,17 @@ context manager:
async with RedisDB(host="localhost") as kv:
await kv.incr("hits")
lifecycle:
construction is sync and opens no socket (the pool connects lazily). connect()
issues a ping() so a bad host/port/auth fails loud immediately rather than on the
first real op, and returns self for the one-liner above. close() tears the client
and pool down (await client.aclose() + pool.disconnect()).
type contract:
decode_responses=True by default, so keys and string values come back as str (and
None for an absent key). pass decode_responses=False at construction if you need raw
bytes. counters (incr/decr/exists/ttl) always return int regardless of this flag.
errors (FAIL LOUD — unlike the mongo lib's swallow-and-default):
every wrapped method catches the driver's RedisError, logs it via
getLogger(__name__), and re-raises. a None/[]/{} return is only ever a real result
(absent key, empty hash) — never a swallowed failure. for anything not wrapped
(pipelines, pub/sub, scan, Lua, ...) use the raw `.client` escape hatch, which
exposes the full redis.asyncio.Redis surface and raises untouched.
fail loud: wrapped methods catch RedisError and re-raise it - the raised exception IS
the signal, and the caller (which alone knows fatal-vs-routine) decides and logs; the
wrapped method logs only at DEBUG (with the traceback) so a failure isn't reported
twice (raise XOR log). see each method's docstring for its own contract. unwrapped ops
go through the raw `.client` escape hatch: full driver surface, raises.
notes:
- import is `redis_store`; the repo/distribution is `redis` (the driver owns the
`redis` import name, so the package can't also be `redis`)
- pub/sub and pipeline helpers are intentionally not wrapped yet — use `.client`
- ssl=True maps to connection_class=redis.asyncio.SSLConnection so TLS actually
works via the documented pool_kwargs path; pass ssl-prefixed kwargs alongside it
- import is `redis_store`; repo is `redis`, distribution is `redis_store` (the
driver owns the `redis` import name, so the package can't also be `redis`)
- ssl=True maps to connection_class=redis.asyncio.SSLConnection so TLS works via
the documented pool_kwargs path; pass ssl-prefixed kwargs alongside it
(ssl_ca_certs, ssl_certfile, ...) to configure the handshake
"""
@@ -59,32 +46,20 @@ class RedisDB:
password: Optional[str] = None,
*,
max_connections: int = 10,
pool_timeout: float = 30.0,
pool_timeout: Optional[float] = 30.0,
decode_responses: bool = True,
**pool_kwargs,
):
"""build the (not-yet-connected) pool + client; no I/O happens here
host/port/db/password/max_connections are injected by the caller. extra
pool_kwargs pass through to the connection pool (socket_timeout,
socket_connect_timeout, ssl, etc). decode_responses=True returns str; set it
False for raw bytes.
uses a BlockingConnectionPool so callers wait up to pool_timeout seconds for a
free connection instead of raising MaxConnectionsError immediately.
a BlockingConnectionPool is used so that, under concurrency exceeding
max_connections, callers WAIT up to pool_timeout seconds for a free connection
(matching motor/mongo's blocking pool) rather than the plain pool's behavior of
raising MaxConnectionsError immediately. pool_timeout=None waits forever.
`timeout` is the pool's own kwarg (set from pool_timeout here), so passing it in
pool_kwargs would collide — reject it with a clear pointer rather than let the
driver raise a cryptic "multiple values for 'timeout'".
`ssl=True` is mapped to `connection_class=redis.asyncio.SSLConnection` — the
default async Connection class has no `ssl` parameter, so passing it straight
through pool_kwargs would defer the failure to connect() as a raw TypeError.
pass ssl-prefixed kwargs (ssl_ca_certs, ssl_certfile, ...) alongside ssl=True to
configure the TLS connection; an explicit connection_class in pool_kwargs is
left untouched.
`timeout` in pool_kwargs collides with pool_timeout, so it's rejected with a
clear ValueError. `ssl=True` maps to `connection_class=redis.asyncio.SSLConnection`
since the default Connection class has no `ssl` parameter (pass ssl-prefixed
kwargs alongside it to configure TLS; an explicit connection_class is left
untouched).
"""
if "timeout" in pool_kwargs:
raise ValueError(
@@ -114,23 +89,32 @@ class RedisDB:
try:
await self._client.ping()
except RedisError:
log.exception("redis.connect() ping failed")
log.debug("redis.connect() ping failed", exc_info=True)
await self._pool.disconnect()
raise
return self
async def close(self) -> None:
"""close the client and disconnect the pool on shutdown"""
"""close the client and disconnect the pool on shutdown
the pool disconnect always runs, even if the client close raises, so a
failure in one does not leak the other's resources.
"""
try:
try:
await self._client.aclose()
finally:
await self._pool.disconnect()
except RedisError:
log.exception("redis.close()")
log.debug("redis.close()", exc_info=True)
raise
async def __aenter__(self) -> "RedisDB":
"""enter: connect() and return self"""
return await self.connect()
async def __aexit__(self, exc_type, exc, tb) -> None:
"""exit: close(), ignoring exc_type/exc/tb"""
await self.close()
@property
@@ -141,15 +125,12 @@ class RedisDB:
"""
return self._client
# -------------------------------------------------------------------------
# key / value
async def get(self, key: str) -> Optional[str]:
"""return the string value at key, or None if the key is absent"""
try:
return await self._client.get(key)
except RedisError:
log.exception("redis.get(%s)", key)
log.debug("redis.get(%s)", key, exc_info=True)
raise
async def set(self, key: str, value, ex: Optional[int] = None) -> bool:
@@ -157,7 +138,7 @@ class RedisDB:
try:
return bool(await self._client.set(key, value, ex=ex))
except RedisError:
log.exception("redis.set(%s)", key)
log.debug("redis.set(%s)", key, exc_info=True)
raise
async def delete(self, *keys: str) -> int:
@@ -165,7 +146,7 @@ class RedisDB:
try:
return await self._client.delete(*keys)
except RedisError:
log.exception("redis.delete(%s)", keys)
log.debug("redis.delete(%s)", keys, exc_info=True)
raise
async def exists(self, *keys: str) -> int:
@@ -173,7 +154,7 @@ class RedisDB:
try:
return await self._client.exists(*keys)
except RedisError:
log.exception("redis.exists(%s)", keys)
log.debug("redis.exists(%s)", keys, exc_info=True)
raise
async def incr(self, key: str, amount: int = 1) -> int:
@@ -181,7 +162,7 @@ class RedisDB:
try:
return await self._client.incrby(key, amount)
except RedisError:
log.exception("redis.incr(%s)", key)
log.debug("redis.incr(%s)", key, exc_info=True)
raise
async def decr(self, key: str, amount: int = 1) -> int:
@@ -189,18 +170,15 @@ class RedisDB:
try:
return await self._client.decrby(key, amount)
except RedisError:
log.exception("redis.decr(%s)", key)
log.debug("redis.decr(%s)", key, exc_info=True)
raise
# -------------------------------------------------------------------------
# hash
async def hget(self, name: str, field: str) -> Optional[str]:
"""return the value of field in hash name, or None if either is absent"""
try:
return await self._client.hget(name, field)
except RedisError:
log.exception("redis.hget(%s, %s)", name, field)
log.debug("redis.hget(%s, %s)", name, field, exc_info=True)
raise
async def hset(self, name: str, key: Optional[str] = None, value=None, mapping: Optional[dict] = None) -> int:
@@ -211,7 +189,7 @@ class RedisDB:
try:
return await self._client.hset(name, key=key, value=value, mapping=mapping)
except RedisError:
log.exception("redis.hset(%s)", name)
log.debug("redis.hset(%s)", name, exc_info=True)
raise
async def hgetall(self, name: str) -> dict:
@@ -219,7 +197,7 @@ class RedisDB:
try:
return await self._client.hgetall(name)
except RedisError:
log.exception("redis.hgetall(%s)", name)
log.debug("redis.hgetall(%s)", name, exc_info=True)
raise
async def hdel(self, name: str, *fields: str) -> int:
@@ -227,18 +205,15 @@ class RedisDB:
try:
return await self._client.hdel(name, *fields)
except RedisError:
log.exception("redis.hdel(%s)", name)
log.debug("redis.hdel(%s)", name, exc_info=True)
raise
# -------------------------------------------------------------------------
# expiry / ttl
async def expire(self, key: str, seconds: int) -> bool:
"""set a ttl of seconds on key; returns False if the key does not exist"""
try:
return bool(await self._client.expire(key, seconds))
except RedisError:
log.exception("redis.expire(%s)", key)
log.debug("redis.expire(%s)", key, exc_info=True)
raise
async def ttl(self, key: str) -> int:
@@ -250,5 +225,5 @@ class RedisDB:
try:
return await self._client.ttl(key)
except RedisError:
log.exception("redis.ttl(%s)", key)
log.debug("redis.ttl(%s)", key, exc_info=True)
raise