a
    zi                     @  sn   d dl mZ d dlZd dlZd dlmZ d dlmZ d dlm	Z	 dZ
eG dd dZG d	d
 d
Ze ZdS )    )annotationsN)	dataclass)RLock)Optionali  c                   @  s.   e Zd ZU ded< ded< ded< ded< dS )SessionRecordstr
session_idparticipant_idroom_idfloat
expires_atN)__name__
__module____qualname____annotations__ r   r   app\services\session_store.pyr      s   
r   c                   @  s`   e Zd ZefddddZddddZd	dd
dZddddddddZdddddZdS )SessionStoreint)ttl_secondsc                 C  s   || _ i | _t | _d S N)_ttl_seconds_recordsr   _lock)selfr   r   r   r   __init__   s    zSessionStore.__init__r   )returnc                 C  s   t   S r   )time)r   r   r   r   _now   s    zSessionStore._nowNonec                   s<   |     fdd| j D }|D ]}| j|d  q$d S )Nc                   s   g | ]\}}|j  kr|qS r   )r   ).0sidrecZnowr   r   
<listcomp>        z6SessionStore._purge_expired_locked.<locals>.<listcomp>)r   r   itemspop)r   Zexpiredr!   r   r#   r   _purge_expired_locked   s    z"SessionStore._purge_expired_lockedNr   zOptional[str]r   )r
   r   r	   r   c                 C  s   | j  |   |rZ| j|}|rZ|j|krZ|  | j |_|| j|< |W  d    S t	d}|pvdt
d }t||||  | j d}|| j|< |W  d    S 1 s0    Y  d S )N   zp-   )r   r	   r
   r   )r   r(   r   getr
   r   r   r   secretsZtoken_urlsafeZ	token_hexr   )r   r
   r   r	   existingZnew_session_idZnew_participant_idr"   r   r   r   create_or_reuse$   s$    


zSessionStore.create_or_reusezOptional[SessionRecord])r   r   c                 C  sx   |sd S | j V |   | j|}|s8W d    d S |  | j |_|| j|< |W  d    S 1 sj0    Y  d S r   )r   r(   r   r+   r   r   r   )r   r   r"   r   r   r   r+   >   s    
zSessionStore.get)NN)	r   r   r   DEFAULT_TTL_SECONDSr   r   r(   r.   r+   r   r   r   r   r      s   	  r   )Z
__future__r   r,   r   Zdataclassesr   	threadingr   typingr   r/   r   r   Zsession_storer   r   r   r   <module>   s   6