
    ^gnK              	          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y)    )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                  6    e Zd ZdZddgZ	 ddgZ	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZe	 	 dd       Ze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!dZ	 	 	 	 	 	 d"dZ xZS )#MongoDBStoragezS
    Rate limit storage with MongoDB as backend.

    Depends on :pypi:`motor`
    async+mongodbzasync+mongodb+srvmotor.motor_asynciopymongoc                   |j                  ddd      }t        |   |fd|i| | j                  d   | _        | j                  d   | _        t        d      \  | _        } | j                  j                  j                  |fi || _
        t        j                  | j                  _        || _        ||d| _        d	| _        y
)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   wrap_exceptionsr   r   zpymongo.errors)counterswindowsFN)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)	selfuridatabase_namecounter_collection_namewindow_collection_namer   options_	__class__s	           a/var/www/html/suriana-translation/venv/lib/python3.12/site-packages/limits/aio/storage/mongodb.pyr   zMongoDBStorage.__init__,   s    4 kk/9a8IoII++,AB $ 1 1) <+,<=@t--@@PP $+#;#; ,/-%
! "'    c                .    | j                   j                  S N)r"   PyMongoErrorr,   s    r4   base_exceptionszMongoDBStorage.base_exceptions[   s     +++r5   c                L    | j                   j                  | j                        S r7   )r%   get_databaser)   r9   s    r4   databasezMongoDBStorage.databasea   s    ||(()=)=>>r5   c                  K   | j                   stt        j                  | j                  | j                  d      j                  dd      | j                  | j                  d      j                  dd             d {    d| _         y 7 w)Nr   expireAtr   )expireAfterSecondsr   T)r+   r&   gatherr=   r*   create_indexr9   s    r4   create_indiceszMongoDBStorage.create_indicese   s     %%..d77
CDQQ1 R  d77	BCPP1 Q 	   "&s   A<B>B?Bc                   K   t        t        j                  | j                  | j                  d      j                  i       | j                  | j                  d      j                  i              d{         }t        j                  | j                  | j                  d      j                         | j                  | j                  d      j                                d{    t        t        |      S 7 7 w)z^
        Delete all rate limit keys in the rate limit collections (counters, windows)
        r   r   N)	sumr&   rA   r=   r*   count_documentsdropr   int)r,   num_keyss     r4   resetzMongoDBStorage.resetq   s      ..d77
CDTT d77	BCSSTVW	 
 nnMM$33J?@EEGMM$33I>?DDF
 	
 	

 C""	
s%   A1C>3C:4A1C>%C<&C><C>c                   K   t        j                  | j                  | j                  d      j	                  d|i      | j                  | j                  d      j	                  d|i             d{    y7 w)z>
        :param key: the key to clear rate limits for
        r   _idr   N)r&   rA   r=   r*   find_one_and_delete)r,   keys     r4   clearzMongoDBStorage.clear   sr      nnMM$33J?@TT MM$33I>?SS	
 	
 	
s   A0A:2A83A:c                .  K   | j                   | j                  d      j                  d|i       d{   }|r|d   nt        j                  j	                         j                  t        j                  j                        j                         S 7 _w)z;
        :param key: the key to get the expiry for
        r   rL   Nr?   tzinfo)	r=   r*   find_onedatetimenowr   timezoneutc	timestampr,   rN   counters      r4   
get_expiryzMongoDBStorage.get_expiry   s~      d&?&?
&KLUUCL
 
 %,WZ 1B1B1F1F1HWH--11W2Y[	

s   1BBA Bc                  K   | j                   | j                  d      j                  |dt        j                  j	                  t        j
                  j                        iddg       d{   }|xr |d   xs dS 7 w)zB
        :param key: the key to get the counter value for
        r   $gte)rL   r?   count)
projectionNr   )r=   r*   rS   rT   rU   rV   rW   rY   s      r4   getzMongoDBStorage.get   s      d&?&?
&KLUU#X%6%6%:%:8;L;L;P;P%QR  y V 
 
 +77+0q0
s   A,B.B /Bc           
       K   | j                          d{    t        j                  j                  t        j                  j                        t        j
                  |      z   }| j                  | j                  d      j                  d|iddddd	gi|d
d|gididddd	gi||r|nddidigddg| j                  j                  j                  j                         d{   }t        |d         S 7 7 w)aD  
        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 elastic_expiry: whether to keep extending the rate limit
         window every hit.
        :param amount: the number to increment by
        Nsecondsr   rL   $set$condz$ltz	$expireAt$$NOW$addz$countifthenelse)r^   r?   Tr^   )upsertr_   return_document)rC   rT   rU   rV   rW   	timedeltar=   r*   find_one_and_updater!   r#   ReturnDocumentAFTERrH   )r,   rN   expiryelastic_expiryamount
expirationresponses          r4   incrzMongoDBStorage.incr   s3     !!###&&**8+<+<+@+@AHDVDVE
 

 %%j1


CL #',{G.D&E(.)/(F1C(D&" $',{G.D&E(27E;&%( y 1188GGMM1  

: 8G$%%G 	$
s"   D C<CD )C>*D >D c                d   K   	 | j                   j                          d{    y7 #  Y yxY ww)z{
        Check if storage is healthy by calling
        :meth:`motor.motor_asyncio.AsyncIOMotorClient.server_info`
        NTF)r%   server_infor9   s    r4   checkzMongoDBStorage.check   s2     
	,,**,,, -	s    0) ') 0) -0c                2  K   t        j                          }| j                  | j                  d      j                  dd|iidddddd	d
||z
  gidiiiddiddddiddidig      j	                  d       d{   x}r|d   d   |d   d   fS |dfS 7 w)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$matchrL   z$projectentriesz$filterz$entriesentryr]   z$$entry)inputascondz$unwindz$groupz$_idz$minz$sumr   )rL   minr^   )lengthNr   r   r^   )timer=   r*   	aggregateto_list)r,   rN   limitrr   rX   results         r4   get_moving_windowz MongoDBStorage.get_moving_window   s      IIK	-- 9 9) DEYs|,"% )-7*1-3iVAS5T,U,"(%
 
+ #)$*J#7&,a[#0 WAW3
6 
8 !9U#VAYw%777!|9s   A8B:B;Bc           	     (  K   | j                          d{    ||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	      j                  d
|d||z
   dd||z
  iii|d       d{    y7 7 # | j                  j                  j                  j                  $ r Y yw xY w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
        NFr|   r   )z$eachz	$positionz$slicer?   rb   )z$pushrd   r   rL   zentries.z$notr]   T)rl   )rC   r   rT   rU   rV   rW   rn   r=   r*   
update_oner!   r#   errorsDuplicateKeyError)r,   rN   r   rr   rt   rX   updatess          r4   acquire_entryzMongoDBStorage.acquire_entry  s<     !!###E>IIK		 "+v!5%&"'   ))--h.?.?.C.CD",,V<= & -- 9 9) DEPP3uv~./&69vCU:V1W  Q    G 	$4 $$++22DD 		sE   DCDBC CC DC -DDDDc                p  K   | j                          d {    |dz  }| j                  | j                  d      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                  j                  d       d {   }t        t        |d         S 7 7 w)N  r   rL   rd   previousCountre   $lte	$subtract
$expiresAtrf   $ifNull$currentCountr   $previousCountrh   z$gtrg      )currentCount	expiresAtcurWeightedCountz$floorz	$multiplyz$dividez$maxr   z$curWeightedCount	_acquiredz$unsetT)rm   rl   )
rC   r=   r*   ro   r!   r#   rp   rq   r   bool)r,   rN   r   rr   rt   	expiry_msr   s          r4   acquire_sliding_window_entryz+MongoDBStorage.acquire_sliding_window_entryD  s     !!###TM	}}%%i0


CL '#$*)4|W6M(N(1-&'" *3_a4H(I)25Eq4I(J	&*" #$*)4|W6M(N(1-&'" )*)2_a4H(I	&) $$*)4|W6M(N(1-&'" %,/4|Q6G.H17,	9R0S17'1y=9Q0R.&)" )5&&!F *$ &(3,<098><=@KDPHNLSLU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188GGMMi  u
w
r D&-..w 	$w
s"   D6D1DD6D4D64D6c                  K   |dz  }| j                   | j                  d      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
                  j                  g d       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7 w)Nr   r   rL   rd   re   r   r   r   rf   r   r   r   r   rh   rg   )r   r   r   )r   r   r   )rm   r_   r   rQ   r   r   )r           r   r   )r=   r*   ro   r!   r#   rp   rq   r`   r   rT   rV   rW   rX   r   max)r,   rN   rr   r   r   
expires_atcurrent_ttlprev_ttls           r4   get_sliding_windowz!MongoDBStorage.get_sliding_window  s     TM	==%%i0


CL #$*)4|W6M(N(1-&'" *3_a4H(I)25Eq4I(J	&* $$*)4|W6M(N(1-&'" )*)2_a4H(I	&) $$*)4|W6M(N(1-&'" *0,	1J(K(4	&&3%')T !1188GGMME[  .
0
 0
6 0
f ::k* $,,H4E4E4I4I,JTTVYY[ 
 adiik!9:K1f_6MkF2STUH '~&	  0
s   B%E'E(B+E)limitsr   r   F)r-   strr.   r   r/   r   r0   r   r   r   r1   zfloat | str | boolreturnNone)r   z-type[Exception] | tuple[type[Exception], ...])r   r   )r   z
int | None)rN   r   r   r   )rN   r   r   float)rN   r   r   rH   )Fr   )
rN   r   rr   rH   rs   r   rt   rH   r   rH   )r   r   )rN   r   r   rH   rr   rH   r   ztuple[float, int])r   )
rN   r   r   rH   rr   rH   rt   rH   r   r   )rN   r   rr   rH   r   ztuple[int, float, int, float])__name__
__module____qualname____doc__STORAGE_SCHEMEDEPENDENCIESr   propertyr:   r=   rC   rJ   rO   r[   r`   rw   rz   r   r   r   r   __classcell__)r3   s   @r4   r   r      s    &':;N *95L
 &'1&/ %-'-' -' "%	-'
 !$-' -' &-' 
-'^ ,	6, ,
 ? ?
&#&

1 RS/&/& #/&59/&KN/&	/&b
))"),/)	)X @A..".,/.9<.	.b @A~/~/"~/,/~/9<~/	~/@CC #C	&Cr5   r   )
__future__r   r&   rT   r   deprecated.sphinxr   r   limits.aio.storage.baser   r   r   limits.typingr	   r
   r   limits.utilr   r   r   r    r5   r4   <module>r      s{    "    : 
 
 'cNCL eRiW13N i	 
ir5   