Session Store with Auto-TTL & Auditing
TTLConcurrencyPersistence
a realistic session-store example.
examples/session_store.py
1# SPDX-License-Identifier: Apache-2.02# Copyright 2026 Hemanshu Vaidya3"""session_store.py - a realistic session-store example.45Shows: TTL-based session expiry, reactive logging of session lifecycle6events (useful for auditing/security monitoring), and atomic() for a7per-session request counter that's safe even if a session is hit by8concurrent requests.910Run: python examples/session_store.py11"""12import time1314from nimbuskv import NimbusKV1516SESSION_TTL_SECONDS = 60 * 30 # 30 minutes171819def create_session(store: NimbusKV, user_id: str) -> str:20 session_id = f"sess_{user_id}_{int(time.time())}"21 store.set(22 f"session:{session_id}",23 {"user_id": user_id, "created_at": time.time(), "requests": 0},24 ttl=SESSION_TTL_SECONDS,25 )26 return session_id272829def touch_session(store: NimbusKV, session_id: str) -> None:30 """Bump the request counter for a session -- safe under concurrent31 requests for the same session, no lock held."""32 key = f"session:{session_id}"3334 def _bump(session):35 if session is None:36 return session # already expired/gone -- nothing to bump37 session = dict(session)38 session["requests"] += 139 return session4041 store.atomic(key, _bump, default=None)424344def main():45 with NimbusKV() as store:46 # Log every session lifecycle event -- this is the kind of thing47 # you'd wire into real audit logging or a security dashboard.48 def audit_log(key, event, old, new):49 if event == "expire":50 print(f"[audit] session expired: {key}")51 elif event == "set" and old is None:52 print(f"[audit] session created: {key}")5354 store.subscribe(audit_log, key=None)5556 session_id = create_session(store, user_id="alvin")57 print("Created session:", session_id)5859 for _ in range(5):60 touch_session(store, session_id)6162 session = store.get(f"session:{session_id}")63 print("Session state:", session)64 assert session["requests"] == 56566 # Simulate a short-lived demo session to show expiry firing --67 # not something you'd normally do with a real 30-minute TTL.68 demo_id = "demo_session"69 store.set(f"session:{demo_id}", {"user_id": "demo"}, ttl=1)70 print("Waiting for demo session to expire...")71 time.sleep(1.5)72 print("Demo session after expiry:", store.get(f"session:{demo_id}"))737475if __name__ == "__main__":76 main()