U
    Û~fhC  ã                   @  s˜   d Z ddlmZ ddlmZ ddlmZ ddlmZ erDddl	m
Z
 dZdZd	d	d
dœdd„Zd	dddœdd„Zd	dddœdd„Zd	dddœdd„ZdS )aò  Criteria to select ServerDescriptions based on maxStalenessSeconds.

The Max Staleness Spec says: When there is a known primary P,
a secondary S's staleness is estimated with this formula:

  (S.lastUpdateTime - S.lastWriteDate) - (P.lastUpdateTime - P.lastWriteDate)
  + heartbeatFrequencyMS

When there is no known primary, a secondary S's staleness is estimated with:

  SMax.lastWriteDate - S.lastWriteDate + heartbeatFrequencyMS

where "SMax" is the secondary with the greatest lastWriteDate.
é    )Úannotations)ÚTYPE_CHECKING)ÚConfigurationError)ÚSERVER_TYPE)Ú	Selectioné
   éZ   ÚintÚNone)Úmax_stalenessÚheartbeat_frequencyÚreturnc                 C  s>   | |t  k r"tdt | |d f ƒ‚| tk r:tdt| f ƒ‚d S )NzŒmaxStalenessSeconds must be at least heartbeatFrequencyMS + %d seconds. maxStalenessSeconds is set to %d, heartbeatFrequencyMS is set to %d.iè  zJmaxStalenessSeconds must be at least %d. maxStalenessSeconds is set to %d.)ÚIDLE_WRITE_PERIODr   ÚSMALLEST_MAX_STALENESS)r   r   © r   úC/tmp/pip-unpacked-wheel-36gvocj8/pymongo/max_staleness_selectors.pyÚ_validate_max_staleness.   s    ýÿÿÿr   r   )r   Ú	selectionr   c                 C  s€   |j }|st‚g }|jD ]\}|jtjkrj|jr4|js8t‚|j|j |j|j  |j }|| krt| 	|¡ q| 	|¡ q| 
|¡S )zEApply max_staleness, in seconds, to a Selection with a known primary.)ÚprimaryÚAssertionErrorÚserver_descriptionsÚserver_typer   ÚRSSecondaryÚlast_write_dateZlast_update_timer   ÚappendÚwith_server_descriptions)r   r   r   ÚsdsÚsÚ	stalenessr   r   r   Ú_with_primary?   s     


ÿþÿr   c                 C  s|   |  ¡ }|s| g ¡S g }|jD ]P}|jtjkrf|jr<|js@t‚|j|j |j }|| krp| 	|¡ q | 	|¡ q | |¡S )zFApply max_staleness, in seconds, to a Selection with no known primary.)
Z"secondary_with_max_last_write_dater   r   r   r   r   r   r   r   r   )r   r   Zsmaxr   r   r   r   r   r   Ú_no_primaryW   s    

r    c                 C  s6   | dkr|S t | |jƒ |jr(t| |ƒS t| |ƒS dS )z0Apply max_staleness, in seconds, to a Selection.éÿÿÿÿN)r   r   r   r   r    )r   r   r   r   r   Úselecto   s    
r"   N)Ú__doc__Ú
__future__r   Útypingr   Zpymongo.errorsr   Zpymongo.server_typer   Zpymongo.server_selectorsr   r   r   r   r   r    r"   r   r   r   r   Ú<module>   s   