Add resilient Valkey User cache with PostgreSQL authorization
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
"""Best-effort cache of immutable public User projections."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
from urllib.parse import urlparse
|
||||
|
||||
USER_TTL_SECONDS = 60
|
||||
|
||||
|
||||
def command(*parts: str) -> str | None:
|
||||
"""Send one RESP command; every call has bounded connect and read times."""
|
||||
target = urlparse(os.environ.get("VALKEY_URL", "redis://valkey:6379/0"))
|
||||
payload = b"*" + str(len(parts)).encode() + b"\r\n"
|
||||
for part in parts:
|
||||
value = part.encode("utf-8")
|
||||
payload += b"$" + str(len(value)).encode() + b"\r\n" + value + b"\r\n"
|
||||
with socket.create_connection((target.hostname or "valkey", target.port or 6379), timeout=0.5) as sock:
|
||||
sock.settimeout(0.5)
|
||||
sock.sendall(payload)
|
||||
with sock.makefile("rb") as response:
|
||||
kind = response.read(1)
|
||||
if kind in (b"+", b":"):
|
||||
return response.readline().rstrip(b"\r\n").decode("utf-8")
|
||||
if kind == b"$":
|
||||
length = int(response.readline())
|
||||
if length < 0:
|
||||
return None
|
||||
value = response.read(length)
|
||||
if len(value) != length or response.read(2) != b"\r\n":
|
||||
raise OSError("incomplete Valkey response")
|
||||
return value.decode("utf-8")
|
||||
raise OSError("invalid Valkey response")
|
||||
|
||||
|
||||
def get_user(user_id: str) -> dict | None:
|
||||
try:
|
||||
value = command("GET", "user:" + user_id)
|
||||
except (OSError, ValueError, UnicodeError):
|
||||
return None
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return json.loads(value)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def put_user(user_id: str, user: dict) -> None:
|
||||
try:
|
||||
command("SET", "user:" + user_id, json.dumps(user, ensure_ascii=False), "EX", str(USER_TTL_SECONDS))
|
||||
except (OSError, ValueError, UnicodeError):
|
||||
pass
|
||||
Reference in New Issue
Block a user