Source code for cadrumo.adapters.persistence.storage.master_key.live_sessions
"""Process-wide registry of key-holding bucket sessions.The active-session binding is a :class:`~contextvars.ContextVar`, which is theright shape for ordinary work: each thread and each ``asyncio.Task`` gets itsown active session, and an encrypt path can never see a sibling context's key.An embedding host's lifetime watchdog also needs one public shutdown operationthat can zeroise sessions held by other contexts before an abrupt exit. Thismodule owns that process-wide emergency boundary.Registration is a :class:`weakref.WeakSet`, so a session that is droppedwithout an explicit close is garbage collected normally and the registry neverextends the lifetime of key material it is meant to destroy.See Also: :func:`~.active_session.close_active_bucket_session` The ordinary, context-scoped close every normal caller wants."""from__future__importannotationsimportthreadingimportweakreffromtypingimportTYPE_CHECKINGfrom.....core.loggingimportget_loggerifTYPE_CHECKING:from.bucket_sessionimportBucketSession_log=get_logger(__name__)#: Every :class:`BucketSession` ever opened and not yet collected. Weak by#: construction: holding these strongly would keep zeroisable key buffers alive#: past the point the owning code dropped them, which is the opposite of this#: module's purpose._live_sessions:weakref.WeakSet[BucketSession]=weakref.WeakSet()#: Guards the set itself. ``WeakSet`` mutation is not atomic under free-threaded#: builds, and registration happens on whatever thread opened the session._lock=threading.Lock()
[docs]defregister_live_session(session:BucketSession)->None:"""Record ``session`` as a live key holder for emergency zeroisation."""with_lock:_live_sessions.add(session)
[docs]defclose_all_live_bucket_sessions()->int:"""Close every registered session, zeroising its keys. The cross-context counterpart to :func:`~.active_session.close_active_bucket_session`, for the interpreter exit hook and an embedding watchdog's pre-exit hook before an ``os._exit`` that would otherwise skip both. One session's failure never prevents the remaining sessions from being zeroised. Returns: The number of sessions this call transitioned from unsealed to sealed. """with_lock:sessions=list(_live_sessions)closed=0forsessioninsessions:ifsession.sealed:continuetry:session.close()exceptExceptionasexc:_log.debug("live bucket session close failed during shutdown error_type=%s",type(exc).__name__,)continueclosed+=1returnclosed