
    ZeIi4K              	         d dl mZ d dlZd dlZd dlZd dlmZmZ d dlm	Z	m
Z
mZ d dlmZmZmZ d dlmZ  ed          Z ed          Z ed	
           edd           G d dee	e
                                  ZdS )    )annotationsN)versionaddedversionchanged)MovingWindowSupportSlidingWindowCounterSupportStorage)	ParamSpecTypeVarcast)get_dependencyPRz2.1)versionz3.14.0zEAdded option to select custom collection names for windows & counters)r   reasonc                       e Zd ZdZddgZ	 ddgZ	 	 	 	 d0d1 fdZed2d            Zed             Z	d3dZ
d4dZd5dZd6dZd7d!Zd8d9d%Zd:d&Zd;d)Z	 d8d<d*Z	 d8d<d+Zd=d-Zd>d.Zd3d/Z xZS )?MongoDBStoragezS
    Rate limit storage with MongoDB as backend.

    Depends on :pypi:`motor`
    async+mongodbzasync+mongodb+srvmotor.motor_asynciopymongolimitscounterswindowsFuristrdatabase_namecounter_collection_namewindow_collection_namewrap_exceptionsbooloptionsfloat | str | boolreturnNonec                z   |                     ddd          } t                      j        |fd|i| | j        d         | _        | j        d         | _        t          d          \  | _        } | j        j        j	        |fi || _
        t          j        | j
        _        || _        ||d| _        d	| _        d
S )a  
        :param uri: uri of the form ``async+mongodb://[user:password]@host:port?...``,
         This uri is passed directly to :class:`~motor.motor_asyncio.AsyncIOMotorClient`
        :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:`~motor.motor_asyncio.AsyncIOMotorClient`
        :raise ConfigurationError: when the :pypi:`motor` or :pypi:`pymongo` are
         not available
        r   mongodb   r   r   r   zpymongo.errors)r   r   FN)replacesuper__init__dependencies
dependencyproxy_dependencyr   
lib_errorsmoduleAsyncIOMotorClientstorageasyncioget_running_loopget_io_loop_MongoDBStorage__database_name#_MongoDBStorage__collection_mapping _MongoDBStorage__indices_created)	selfr   r   r   r   r   r    _	__class__s	           _/var/www/html/MCyber-Diagnostic/venv/lib/python3.11/site-packages/limits/aio/storage/mongodb.pyr)   zMongoDBStorage.__init__,   s    4 kk/9a88IIoIIII+,AB $ 1) <+,<==@t-@PPPP $+#; ,/-%
 %
! "'    -type[Exception] | tuple[type[Exception], ...]c                    | j         j        S N)r-   PyMongoErrorr7   s    r:   base_exceptionszMongoDBStorage.base_exceptions[   s     ++r;   c                @    | j                             | j                  S r>   )r0   get_databaser4   r@   s    r:   databasezMongoDBStorage.databasea   s    |(()=>>>r;   c                  K   | j         sqt          j        | j        | j        d                                      dd          | j        | j        d                                      dd                     d {V  d| _         d S )Nr   expireAtr   )expireAfterSecondsr   T)r6   r1   gatherrD   r5   create_indexr@   s    r:   create_indiceszMongoDBStorage.create_indicese   s      % 	.d7
CDQQ1 R   d7	BCPP1 Q  	         "&r;   
int | Nonec                  K   t          t          j        | j        | j        d                                      i           | j        | j        d                                      i                      d{V           }t          j        | j        | j        d                                                  | j        | j        d                                                             d{V  t          t          |          S )z^
        Delete all rate limit keys in the rate limit collections (counters, windows)
        r   r   N)	sumr1   rH   rD   r5   count_documentsdropr   int)r7   num_keyss     r:   resetzMongoDBStorage.resetq   s      .d7
CDTT  d7	BCSSTVWW	       
 
 nM$3J?@EEGGM$3I>?DDFF
 
 	
 	
 	
 	
 	
 	
 	

 C"""r;   keyc                   K   t          j        | j        | j        d                                      d|i          | j        | j        d                                      d|i                     d{V  dS )z>
        :param key: the key to clear rate limits for
        r   _idr   N)r1   rH   rD   r5   find_one_and_delete)r7   rS   s     r:   clearzMongoDBStorage.clear   s       nM$3J?@TT  M$3I>?SS 	
 
 	
 	
 	
 	
 	
 	
 	
 	
 	
r;   floatc                &  K   | j         | j        d                                      d|i           d{V }|r|d         nt          j                                                            t          j        j                                                  S )z;
        :param key: the key to get the expiry for
        r   rU   NrF   tzinfo)	rD   r5   find_onedatetimenowr'   timezoneutc	timestampr7   rS   counters      r:   
get_expiryzMongoDBStorage.get_expiry   s       d&?
&KLUUCL
 
 
 
 
 
 
 
 %,HWZ  1B1F1F1H1HWH-1W22Y[[	
r;   rP   c                   K   | j         | j        d                                      |dt          j                            t          j        j                  iddg           d{V }|r|d         pdS )zB
        :param key: the key to get the counter value for
        r   $gte)rU   rF   count)
projectionNr   )rD   r5   r\   r]   r^   r_   r`   rb   s      r:   getzMongoDBStorage.get   s       d&?
&KLUU#X%6%:%:8;L;P%Q%QR   y V 
 
 
 
 
 
 
 
 +77+0q0r;   r&   expiryamountc           
       K   |                                   d{V  t          j                            t          j        j                  t          j        |          z   }| j        | j        d                                      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        j                   d{V }t          |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
        Nsecondsr   rU   $set$condz$lt	$expireAt$$NOW$addz$countifthenelse)rg   rF   Trg   )upsertrh   return_document)rJ   r]   r^   r_   r`   	timedeltarD   r5   find_one_and_updater,   r.   ReturnDocumentAFTERrP   )r7   rS   rj   rk   
expirationresponses         r:   incrzMongoDBStorage.incr   sW      !!#########&**8+<+@AAHDVE
 E
 E
 

 %j1


CL #',{G.D&E(.)/(F1C(D& &" $',{G.D&E(2(3& &% ( y 18GM1  
 

 
 
 
 
 
: 8G$%%%r;   c                Z   K   	 | j                                          d{V  dS #  Y dS xY w)z{
        Check if storage is healthy by calling
        :meth:`motor.motor_asyncio.AsyncIOMotorClient.server_info`
        NTF)r0   server_infor@   s    r:   checkzMongoDBStorage.check   sF      
	,**,,,,,,,,,4	55s   % *limittuple[float, int]c                <  K   t          j                     }| j        | j        d                                      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                              d           d{V 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 str key: rate limit key
        :param int expiry: expiry of entry
        :return: (start of window, number of acquired entries)
        r   z$matchrU   z$projectfilteredEntriesz$filterz$entriesentryrf   z$$entry)inputascondz$minz$filteredEntriesz$size)minrg   r&   )lengthNr   r   rg   )timerD   r5   	aggregateto_list)r7   rS   r   rj   ra   results         r:   get_moving_windowz MongoDBStorage.get_moving_window   s	      IKK	 M$*CI*NOYs|,"- )-7*1-3iVAS5T,U," ,"0%
 #$*,>#?&-/A%B% % , WAW/      F	84 !9U#VAYw%777!|r;   c           	       K   |                                   d{V  ||k    rdS t          j                    }	 d|g|z  d|didt          j                            t          j        j                  t          j        |          z   id}| j        | j        d	                  	                    d
|d||z
   dd||z
  iii|d           d{V  dS # | j
        j        j        j        $ r Y dS 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
        NFentriesr   )z$eachz	$positionz$slicerF   rm   )z$pushro   r   rU   zentries.z$notrf   T)rx   )rJ   r   r]   r^   r_   r`   rz   rD   r5   
update_oner,   r.   errorsDuplicateKeyError)r7   rS   r   rj   rk   ra   updatess          r:   acquire_entryzMongoDBStorage.acquire_entry  sk      !!#########E>>5IKK		 "+v!5%&"'     )--h.?.CDD",V<<<=  & - 9) DEPP3/uv~//&69vCU:V1W  Q          4$+2D 	 	 	55	s   BC C0/C0c                J  K   |                                   d {V  |dz  }| j        | j        d                                      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        j        d           d {V }t          t          |d                   S )N  r   rU   ro   previousCountrp   $lte	$subtractrq   rr   $ifNull$currentCountr   $previousCountrt   z$gtrs      )currentCountrF   curWeightedCountz$floorz	$multiplyz$dividez$maxr   z$curWeightedCount	_acquiredz$unsetT)ry   rx   )
rJ   rD   r5   r{   r,   r.   r|   r}   r   r   )r7   rS   r   rj   rk   	expiry_msr   s          r:   acquire_sliding_window_entryz+MongoDBStorage.acquire_sliding_window_entry?  s      !!#########TM	}%i0


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 !18GMi  u
 u
w
 w
 w
 w
 w
 w
r D&-...r;   tuple[int, float, int, float]c                  K   |dz  }| j         | j        d                                      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        j        g d           d {V x}r|                    d          r=|d                             t          j
        j                                                  nt          j                    }t          d|t          j                    z
            }t          d|d         r||z
  nd          }|d         ||d         |fS dS )Nr   r   rU   ro   rp   r   r   rq   rr   r   r   r   r   rt   rs   )r   r   rF   )r   r   rF   )ry   rh   rF   rZ   r   r   )r           r   r   )rD   r5   r{   r,   r.   r|   r}   ri   r'   r]   r_   r`   ra   r   max)r7   rS   rj   r   r   
expires_atcurrent_ttlprev_ttls           r:   get_sliding_windowz!MongoDBStorage.get_sliding_window  s.      TM	=%i0


CL #$*)4{G6L(M(1-&'" *3_a4H(I)25Eq4I(J	& 	&* $$*)4{G6L(M(1-&'" )*)2_a4H(I	& 	&) $$*)4{G6L(M(1-&'" *0+y1I(J(3	& 	&%3% %')T !18GMDDD[  .
 .
0
 0
 0
 0
 0
 0
 0
6 >	f ::j))!
#++83D3H+IISSUUUY[[ 
 adikk!9::K1f_6MTkF22STUUH '~&	  ~r;   c                <   K   |                      |           d {V S r>   )rW   )r7   rS   rj   s      r:   clear_sliding_windowz#MongoDBStorage.clear_sliding_window  s(      ZZ__$$$$$$$r;   c                L    | j         o| j                                          d S  d S r>   )r0   closer@   s    r:   __del__zMongoDBStorage.__del__  s,    -++--------r;   )r   r   r   F)r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   )r"   r<   )r"   r#   )r"   rK   )rS   r   r"   r#   )rS   r   r"   rX   )rS   r   r"   rP   )r&   )rS   r   rj   rP   rk   rP   r"   rP   )r"   r   )rS   r   r   rP   rj   rP   r"   r   )
rS   r   r   rP   rj   rP   rk   rP   r"   r   )rS   r   rj   rP   r"   r   )rS   r   rj   rP   r"   r#   )__name__
__module____qualname____doc__STORAGE_SCHEMEDEPENDENCIESr)   propertyrA   rD   rJ   rR   rW   rd   ri   r   r   r   r   r   r   r   r   __classcell__)r9   s   @r:   r   r      s         &':;N *95L
 &'1&/ %-' -' -' -' -' -' -'^ , , , X,
 ? ? X?
& 
& 
& 
&# # # #&
 
 
 

 
 
 
1 1 1 1+& +& +& +& +&Z
 
 
 
( ( ( (V @A. . . . .b @A~/ ~/ ~/ ~/ ~/@C C C CJ% % % %. . . . . . . .r;   r   )
__future__r   r1   r]   r   deprecated.sphinxr   r   limits.aio.storage.baser   r   r   limits.typingr	   r
   r   limits.utilr   r   r   r    r;   r:   <module>r      s^   " " " " " "    : : : : : : : :         
         
 ' & & & & &IcNNGCLL eR  j. j. j. j. j.W13N j. j.	  
j. j. j.r;   