
    ZeIiF                       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dS )    )annotationsN)ABCabstractmethod)versionaddedversionchanged)MongoClientMongoCollectionMongoDatabasecast   )get_dependency   )MovingWindowSupportSlidingWindowCounterSupportStoragec                  4    e Zd ZdZdgZ	 	 	 	 d5d6 fdZed7d            Zed8d            Zed9d            Z	ed9d            Z
ed:d            Zed;d            Zd<dZd=d Zd>d"Zd?d$Zd@d&ZdAdBd*ZdCd+ZdDd.ZdAdEd/ZdFd1Z	 dAdEd2ZdGd3Zd<d4Z xZS )HMongoDBStorageBasezV
    Rate limit storage with MongoDB as backend.

    Depends on :pypi:`pymongo`.
    pymongolimitscounterswindowsFuristrdatabase_namecounter_collection_namewindow_collection_namewrap_exceptionsbooloptionsint | str | boolreturnNonec                     t                      j        |fd|i| || _        ||d| _        | j        d         j        | _        t          d          \  | _        }|| _	        || _
        d| _        dS )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
        r   )r   r   r   zpymongo.errorsN)super__init___database_name_collection_mappingdependenciesmodulelibr   
lib_errors_storage_uri_storage_options_storage)	selfr   r   r   r   r   r   _	__class__s	           [/var/www/html/MCyber-Diagnostic/venv/lib/python3.11/site-packages/limits/storage/mongodb.pyr%   zMongoDBStorageBase.__init__   s    2 	IIoIIII+/-$
 $
  $Y/6+,<== ',0    r   c                    | j         1 | j        | j        fi | j        | _         |                                  | j         S N)r.   _init_mongo_clientr,   r-   (_MongoDBStorageBase__initialize_databaser/   s    r2   storagezMongoDBStorageBase.storageD   sR    = 3D3! %)%: DM &&(((}r3   r
   c                &    | j         | j                 S r5   )r9   r&   r8   s    r2   	_databasezMongoDBStorageBase._databaseM   s    |D/00r3   r	   c                2    | j         | j        d                  S )Nr   r;   r'   r8   s    r2   r   zMongoDBStorageBase.countersQ   s    ~d6zBCCr3   c                2    | j         | j        d                  S )Nr   r=   r8   s    r2   r   zMongoDBStorageBase.windowsU   s    ~d6yABBr3   
str | Nonec                    t                      r5   )NotImplementedErrorr/   r   r   s      r2   r6   z%MongoDBStorageBase._init_mongo_clientY   s     "###r3   -type[Exception] | tuple[type[Exception], ...]c                    | j         j        S r5   )r+   PyMongoErrorr8   s    r2   base_exceptionsz"MongoDBStorageBase.base_exceptions_   s     ++r3   c                v    | j                             dd           | j                            dd           d S )NexpireAtr   )expireAfterSeconds)r   create_indexr   r8   s    r2   __initialize_databasez(MongoDBStorageBase.__initialize_databasee   s>    "":!"DDD!!*!CCCCCr3   
int | Nonec                    | j                             i           | j                            i           z   }| 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     r2   resetzMongoDBStorageBase.reseti   sc     =0044t|7S7STV7W7WW8}}r3   keyc                v    | j                             d|i           | j                            d|i           dS )z>
        :param key: the key to clear rate limits for
        _idN)r   find_one_and_deleter   )r/   rS   s     r2   clearzMongoDBStorageBase.clears   s>     	))5#,777((%66666r3   floatc                    | j                             d|i          }|r|d         nt          j                                                            t          j        j                                                  S )z;
        :param key: the key to get the expiry for
        rU   rH   tzinfo)r   find_onedatetimenowreplacetimezoneutc	timestampr/   rS   counters      r2   
get_expiryzMongoDBStorageBase.get_expiryz   sa     -((%66$+HWZ  1B1F1F1H1HWH-1W22Y[[	
r3   rP   c                    | j                             |dt          j                            t          j        j                  iddg          }|r|d         pdS )zB
        :param key: the key to get the counter value for
        $gte)rU   rH   count)
projectionr   )r   r\   r]   r^   r`   ra   rc   s      r2   getzMongoDBStorageBase.get   sj     -((#X%6%:%:8;L;P%Q%QR   y ) 
 
 +77+0q0r3   r   expiryamountc                N   t           j                             t           j        j                  t          j        |          z   }t          | 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
        secondsrU   $set$condz$lt	$expireAt$$NOW$addz$countifthenelse)rh   rH   Trh   )upsertri   return_document)r]   r^   r`   ra   	timedeltarP   r   find_one_and_updater*   ReturnDocumentAFTER)r/   rS   rk   rl   
expirations        r2   incrzMongoDBStorageBase.incr   s    &**8+<+@AAHDVE
 E
 E
 

 M--  '+0;2H*I,2-3h5G,H*" *"& !(+0;2H*I,6,7*" *")! !( #9 $ 7 =1 .  2 3
 
 	
r3   c                J    	 | j                                          dS #  Y dS xY w)zm
        Check if storage is healthy by calling :meth:`pymongo.mongo_client.MongoClient.server_info`
        TF)r9   server_infor8   s    r2   checkzMongoDBStorageBase.check   s0    	L$$&&&4	55s    "limittuple[float, int]c                    t          j                     }t          | 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$matchrU   z$projectfilteredEntriesz$filterz$entriesentryrg   z$$entry)inputascondz$minz$filteredEntriesz$size)minrh   r   r   rh   )timelistr   	aggregate)r/   rS   r   rk   rb   results         r2   get_moving_windowz$MongoDBStorageBase.get_moving_window   s     IKK	L""s|,"- )-7*1-3iVAS5T,U," ,"0%
 #$*,>#?&-/A%B% % 
 
 
6 	80 !9U#VAYw%777!|r3   c           	     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                            d|d	||z
   d
d||z
  iii|d           dS # | 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
        Fentriesr   )z$eachz	$positionz$slicerH   rn   )z$pushrp   rU   zentries.z$notrg   T)ry   )r   r]   r^   r`   ra   r{   r   
update_oner*   errorsDuplicateKeyError)r/   rS   r   rk   rl   rb   updatess          r2   acquire_entryz MongoDBStorageBase.acquire_entry   s    E>>5IKK		 "+v!5%&"'     )--h.?.CDD",V<<<=  & L##3/uv~//&69vCU:V1W  $    4x0 	 	 	55	s   BB   B87B8tuple[int, float, int, float]c                h   |dz  }| 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|                    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 )N  rU   rp   rq   $lte	$subtractrr   rs   $ifNull$currentCountr   $previousCountru   rt   )previousCountcurrentCountrH   )r   r   rH   )rz   ri   rH   rZ   r   r   )r           r   r   )r   r|   r*   r}   r~   rj   r_   r]   r`   ra   rb   r   max)r/   rS   rk   	expiry_msr   
expires_atcurrent_ttlprev_ttls           r2   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 !H39DDD_ 6 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 '~&	  ~r3   c                   |dz  }| 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   rU   rp   r   rq   r   r   rr   rs   r   r   r   r   ru   z$gtrt   r   )r   rH   curWeightedCountz$floorz	$multiplyz$dividez$maxr   z$curWeightedCount	_acquiredz$unsetT)rz   ry   )r   r|   r*   r}   r~   r   r   )r/   rS   r   rk   rl   r   r   s          r2   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 !H39i 2 u
 u
l D&-...r3   c                ,    |                      |          S r5   )rW   )r/   rS   rk   s      r2   clear_sliding_windowz'MongoDBStorageBase.clear_sliding_window  s    zz#r3   c                J    | j         r| j                                          d S d S r5   )r9   closer8   s    r2   __del__zMongoDBStorageBase.__del__  s0    < 	!L     	! 	!r3   )r   r   r   F)r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   )r!   r   )r!   r
   )r!   r	   r   r?   r   r    r!   r   )r!   rC   )r!   r"   )r!   rL   )rS   r   r!   r"   )rS   r   r!   rX   )rS   r   r!   rP   )r   )rS   r   rk   rP   rl   rP   r!   rP   )r!   r   )rS   r   r   rP   rk   rP   r!   r   )
rS   r   r   rP   rk   rP   rl   rP   r!   r   )rS   r   rk   rP   r!   r   )rS   r   rk   rP   r!   r"   )__name__
__module____qualname____doc__DEPENDENCIESr%   propertyr9   r;   r   r   r   r6   rF   r7   rR   rW   re   rj   r   r   r   r   r   r   r   r   __classcell__)r1   s   @r2   r   r      sX         ;L
 &'1&/ %#1 #1 #1 #1 #1 #1 #1J    X 1 1 1 X1 D D D XD C C C XC $ $ $ ^$
 , , , X,
D D D D   7 7 7 7	
 	
 	
 	
1 1 1 1'
 '
 '
 '
 '
R	 	 	 	# # # #J* * * * *XC C C CL @Az/ z/ z/ z/ z/x   ! ! ! ! ! ! ! !r3   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d
S )MongoDBStoragemongodbzmongodb+srvr   r?   r   r    r!   r   c                N    t          t           | j        j        |fi |          S r5   )r   r   r*   rB   s      r2   r6   z!MongoDBStorage._init_mongo_client  s,     K!5!5c!E!EW!E!EFFFr3   Nr   )r   r   r   STORAGE_SCHEMEr6    r3   r2   r   r     s:          /NG G G G G Gr3   r   )
__future__r   r]   r   abcr   r   deprecated.sphinxr   r   limits.typingr   r	   r
   r   utilr   baser   r   r   r   r   r   r3   r2   <module>r      s   " " " " " "   # # # # # # # # : : : : : : : :            " ! ! ! ! ! K K K K K K K K K KJ! J! J! J! J! "=sJ! J! J!Z eR  G G G G G' G G	  
G G Gr3   