
    9iF                        d dl mZ d dlZd dlZd dlmZmZ d dlmZm	Z	 d dl
mZmZmZmZ ddlmZ dd	lmZmZmZ  G d
 deeee      Z ed       e	dd       G d de                    Zy)    )annotationsN)ABCabstractmethod)versionaddedversionchanged)MongoClientMongoCollectionMongoDatabasecast   )get_dependency   )MovingWindowSupportSlidingWindowCounterSupportStoragec                  X    e Zd ZdZdgZ	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZedd       Zedd       Zedd       Z	edd       Z
e	 	 	 	 	 	 dd       Ze	 	 dd	       Zdd
ZddZd dZd!dZd"dZd#d$dZd%dZd&dZd#d'dZ	 	 	 	 	 	 d(dZ	 d#	 	 	 	 	 	 	 	 	 d'dZd)dZddZ xZS )*MongoDBStorageBasezV
    Rate limit storage with MongoDB as backend.

    Depends on :pypi:`pymongo`.
    pymongoc                    t        |   |fd|i| || _        ||d| _        | j                  d   j
                  | _        t        d      \  | _        }|| _	        || _
        d| _        y)ai  
        :param uri: uri of the form ``mongodb://[user:password]@host:port?...``,
         This uri is passed directly to :class:`~pymongo.mongo_client.MongoClient`
        :param database_name: The database to use for storing the rate limit
         collections.
        :param counter_collection_name: The collection name to use for individual counters
         used in fixed window strategies
        :param window_collection_name: The collection name to use for sliding & moving window
         storage
        :param wrap_exceptions: Whether to wrap storage exceptions in
         :exc:`limits.errors.StorageError` before raising it.
        :param options: all remaining keyword arguments are passed to the
         constructor of :class:`~pymongo.mongo_client.MongoClient`
        :raise ConfigurationError: when the :pypi:`pymongo` library is not available
        wrap_exceptions)counterswindowsr   zpymongo.errorsN)super__init___database_name_collection_mappingdependenciesmodulelibr   
lib_errors_storage_uri_storage_options_storage)	selfuridatabase_namecounter_collection_namewindow_collection_namer   options_	__class__s	           I/var/www/html/venv/lib/python3.12/site-packages/limits/storage/mongodb.pyr   zMongoDBStorageBase.__init__   sw    2 	IoII+/-$
  $$Y/66+,<= ',0    c                    | j                   < | j                  | j                  fi | j                  | _         | j	                          | j                   S N)r#   _init_mongo_clientr!   r"   (_MongoDBStorageBase__initialize_databaser$   s    r,   storagezMongoDBStorageBase.storageD   sO    == 3D33!!%)%:%:DM &&(}}r-   c                4    | j                   | j                     S r/   )r3   r   r2   s    r,   	_databasezMongoDBStorageBase._databaseM   s    ||D//00r-   c                :    | j                   | j                  d      S )Nr   r5   r   r2   s    r,   r   zMongoDBStorageBase.countersQ   s    ~~d66zBCCr-   c                :    | j                   | j                  d      S )Nr   r7   r2   s    r,   r   zMongoDBStorageBase.windowsU   s    ~~d66yABBr-   c                    t               r/   )NotImplementedErrorr$   r%   r)   s      r,   r0   z%MongoDBStorageBase._init_mongo_clientY   s     "##r-   c                .    | j                   j                  S r/   )r    PyMongoErrorr2   s    r,   base_exceptionsz"MongoDBStorageBase.base_exceptions_   s     +++r-   c                x    | j                   j                  dd       | j                  j                  dd       y )NexpireAtr   )expireAfterSeconds)r   create_indexr   r2   s    r,   __initialize_databasez(MongoDBStorageBase.__initialize_databasee   s0    "":!"D!!*!Cr-   c                    | j                   j                  i       | j                  j                  i       z   }| j                   j                          | j                  j                          t	        |      S )z^
        Delete all rate limit keys in the rate limit collections (counters, windows)
        )r   count_documentsr   dropint)r$   num_keyss     r,   resetzMongoDBStorageBase.reseti   sW     ==004t||7S7STV7WW8}r-   c                x    | j                   j                  d|i       | j                  j                  d|i       y)z>
        :param key: the key to clear rate limits for
        _idN)r   find_one_and_deleter   )r$   keys     r,   clearzMongoDBStorageBase.clears   s0     	))5#,7((%6r-   c                    | j                   j                  d|i      }|r|d   nt        j                  j                         j	                  t        j
                  j                        j                         S )z;
        :param key: the key to get the expiry for
        rK   r@   tzinfo)r   find_onedatetimenowreplacetimezoneutc	timestampr$   rM   counters      r,   
get_expiryzMongoDBStorageBase.get_expiryz   s[     --((%6$+WZ 1B1B1F1F1HWH--11W2Y[	
r-   c                    | j                   j                  |dt        j                  j                  t        j                  j
                        iddg      }|xr |d   xs dS )zB
        :param key: the key to get the counter value for
        $gte)rK   r@   count)
projectionr   )r   rR   rS   rT   rV   rW   rY   s      r,   getzMongoDBStorageBase.get   sh     --((#X%6%6%:%:8;L;L;P;P%QR  y ) 
 +77+0q0r-   c                t   t         j                   j                  t         j                  j                        t        j                  |      z   }t        | j                  j                  d|idddddgi|dd	|gid
iddddgi|dd
idigddg| j                  j                  j                        d         S )z
        increments the counter for a given rate limit key

        :param key: the key to increment
        :param expiry: amount in seconds for the key to expire in
        :param amount: the number to increment by
        secondsrK   $set$condz$lt	$expireAt$$NOW$addz$countifthenelse)r^   r@   Tr^   )upsertr_   return_document)rS   rT   rV   rW   	timedeltarG   r   find_one_and_updater   ReturnDocumentAFTER)r$   rM   expiryamount
expirations        r,   incrzMongoDBStorageBase.incr   s     &&**8+<+<+@+@AHDVDVE
 

 MM--  '+0;2H*I,2-3h5G,H*"& !(+0;2H*I,6,7*")!( #9 $ 7 7 = =1 . 2 3
 	
r-   c                H    	 | j                   j                          y#  Y yxY w)zm
        Check if storage is healthy by calling :meth:`pymongo.mongo_client.MongoClient.server_info`
        TF)r3   server_infor2   s    r,   checkzMongoDBStorageBase.check   s$    	LL$$&	s    !c                    t        j                          }t        | j                  j                  dd|iiddddddd	||z
  gid
iiidddiddidig            x}r|d   d   |d   d   fS |dfS )z
        returns the starting point and the number of entries in the moving
        window

        :param key: rate limit key
        :param expiry: expiry of entry
        :return: (start of window, number of acquired entries)
        z$matchrK   z$projectfilteredEntriesz$filterz$entriesentryr]   z$$entry)inputascondz$minz$filteredEntriesz$size)minr^   r   r   r^   )timelistr   	aggregate)r$   rM   limitrs   rX   results         r,   get_moving_windowz$MongoDBStorageBase.get_moving_window   s     IIK	LL""s|,"- )-7*1-3iVAS5T,U,"0%
 #$*,>#?&-/A%B%
 
6 
0 !9U#VAYw%777!|r-   c           	        ||kD  ryt        j                          }	 d|g|z  d|didt        j                  j                  t        j                  j                        t        j
                  |      z   id}| j                  j                  d|d	||z
   d
d||z
  iii|d       y# | j                  j                  j                  $ r Y yw xY w)z
        :param key: rate limit key to acquire an entry in
        :param limit: amount of entries allowed
        :param expiry: expiry of the entry
        :param amount: the number of entries to acquire
        Fentriesr   )z$eachz	$positionz$slicer@   rb   )z$pushrd   rK   zentries.z$notr]   T)rm   )r   rS   rT   rV   rW   ro   r   
update_oner   errorsDuplicateKeyError)r$   rM   r   rs   rt   rX   updatess          r,   acquire_entryz MongoDBStorageBase.acquire_entry   s     E>IIK		 "+v!5%&"'   ))--h.?.?.C.CD",,V<= & LL##3uv~./&69vCU:V1W  $  xx00 		s   BB) )#CCc                \   |dz  }| j                   j                  d|iddddddgi|gid	d
dgid	ddgididddddgi|gidd	d
dgididddddgi|gidd|giddidig| j                  j                  j                  g d      x}r|j                  d      r;|d   j                  t        j                  j                        j                         nt        j                         }t        d|t        j                         z
        }t        d|d   r||z
  nd      }|d   ||d   |fS y)N  rK   rd   re   $lte	$subtractrf   rg   $ifNull$currentCountr   $previousCountri   rh   )previousCountcurrentCountr@   )r   r   r@   )rn   r_   r@   rP   r   r   )r           r   r   )r   rp   r   rq   rr   r`   rU   rS   rV   rW   rX   r   max)r$   rM   rs   	expiry_msr   
expires_atcurrent_ttlprev_ttls           r,   get_sliding_windowz%MongoDBStorageBase.get_sliding_window  s    TM	\\55CL #$*)4{G6L(M(1-&'" *3_a4H(I)25Eq4I(J	&* $$*)4{G6L(M(1-&'" )*)2_a4H(I	&) $$*)4{G6L(M(1-&'" %+[),D)" )4&%3')+X !HH3399D_ 6 0
 0
6 0
f ::j) 
#++83D3D3H3H+ISSUYY[ 
 adiik!9:K1f_6MkF2STUH '~&	  r-   c                   |dz  }| j                   j                  d|iddddddd	gi|gid
ddgid
ddgidiiidddddd	gi|gidd
ddgididdddd	gi|giddddgidd|gidd	d|z  gididdididdddddddddddd	|gigigi|gigidgiiiidddddd|gi|gidd|giddiiiddddd|gi|giiiddgig| j                  j                  j                  d      }t        t        |d         S )Nr   rK   rd   r   re   r   r   rf   rg   r   r   r   r   ri   z$gtrh   r   )r   r@   curWeightedCountz$floorz	$multiplyz$dividez$maxr   z$curWeightedCount	_acquiredz$unsetT)rn   rm   )r   rp   r   rq   rr   r   bool)r$   rM   r   rs   rt   r   r   s          r,   acquire_sliding_window_entryz/MongoDBStorageBase.acquire_sliding_window_entry]  s    TM	11CL '#$*)4{G6L(M(1-&'" *3_a4H(I)25Eq4I(J	&*" #$*)4{G6L(M(1-&'" )*)2_a4H(I	&) $$*)4{G6L(M(1-&'" %,/4{A6F.G17+y9Q0R17'1y=9Q0R.&)" )4&%!F *$ &(3,<098><=@KDOHNLSLUQJEFNB
=>A:56  5>#<2-.6*%&4 %47)"' -"$L &#$*)/2Ev1N(O(--&'" *0/61J(K(7	&)" #"f/BF.K%Le$T& ./0_pb !HH3399i 2 u
l D&-..r-   c                $    | j                  |      S r/   )rN   )r$   rM   rs   s      r,   clear_sliding_windowz'MongoDBStorageBase.clear_sliding_window  s    zz#r-   c                R    | j                   r| j                   j                          y y r/   )r3   closer2   s    r,   __del__zMongoDBStorageBase.__del__  s    <<LL  r-   )limitsr   r   F)r%   strr&   r   r'   r   r(   r   r   r   r)   int | str | boolreturnNone)r   r   )r   r
   )r   r	   r%   z
str | Noner)   r   r   r   )r   z-type[Exception] | tuple[type[Exception], ...])r   r   )r   z
int | None)rM   r   r   r   )rM   r   r   float)rM   r   r   rG   )r   )rM   r   rs   rG   rt   rG   r   rG   )r   r   )rM   r   r   rG   rs   rG   r   ztuple[float, int])
rM   r   r   rG   rs   rG   rt   rG   r   r   )rM   r   rs   rG   r   ztuple[int, float, int, float])rM   r   rs   rG   r   r   )__name__
__module____qualname____doc__DEPENDENCIESr   propertyr3   r5   r   r   r   r0   r>   r1   rI   rN   r[   r`   rv   ry   r   r   r   r   r   r   __classcell__)r+   s   @r,   r   r      s    ;L
 &'1&/ %#1#1 #1 "%	#1
 !$#1 #1 $#1 
#1J   1 1 D D C C $$*:$	$ $
 ,	6, ,
D7	
1'
R	#J*XCC #C	&CL @Az/z/"z/,/z/9<z/	z/x!r-   r   z2.1)versionz3.14.0zEAdded option to select custom collection names for windows & counters)r   reasonc                  (    e Zd ZddgZ	 	 	 	 	 	 ddZy)MongoDBStoragemongodbzmongodb+srvc                X    t        t         | j                  j                  |fi |      S r/   )r   r   r   r;   s      r,   r0   z!MongoDBStorage._init_mongo_client  s(     K!5!5!5c!EW!EFFr-   Nr   )r   r   r   STORAGE_SCHEMEr0    r-   r,   r   r     s/      /NGG*:G	Gr-   r   )
__future__r   rS   r   abcr   r   deprecated.sphinxr   r   limits.typingr   r	   r
   r   utilr   baser   r   r   r   r   r   r-   r,   <module>r      sx    "   # :  " K KJ! "=sJ!Z eRG' G	 
Gr-   