
    5jF                        S SK Jr  S SKrS SKrS SKJrJr  S SKJrJ	r	  S SK
JrJrJrJr  SSKJr  SS	KJrJrJr   " S
 S\\\\5      r\" SS9\	" SSS9 " S S\5      5       5       rg)    )annotationsN)ABCabstractmethod)versionaddedversionchanged)MongoClientMongoCollectionMongoDatabasecast   )get_dependency   )MovingWindowSupportSlidingWindowCounterSupportStoragec                    ^  \ rS rSrSrS/r    S             SU 4S jjjr\SS j5       r\SS j5       r	\SS j5       r
\SS j5       r\      SS	 j5       r\  SS
 j5       rS S jrS!S jrS"S jrS#S jrS$S jrS%S&S jjrS'S jrS(S jrS%S)S jjr      S*S jr S%         S)S jjrS+S jrS S jrSrU =r$ ),MongoDBStorageBase   zJ
Rate limit storage with MongoDB as backend.

Depends on :pypi:`pymongo`.
pymongoc                   > [         TU ]  " U4SU0UD6  X l        UUS.U l        U R                  S   R
                  U l        [        S5      u  U l        nXl	        X`l
        SU l        g)a  
: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	           U/root/lseg-credit/backend/venv/lib/python3.13/site-packages/limits/storage/mongodb.pyr   MongoDBStorageBase.__init__   sq    2 	IoII+/-$
  $$Y/66+,<= ',0    c                    U R                   c<  U R                  " U R                  40 U R                  D6U l         U R	                  5         U R                   $ N)r$   _init_mongo_clientr"   r#   (_MongoDBStorageBase__initialize_databaser%   s    r-   storageMongoDBStorageBase.storageD   sM    ==  33!!%)%:%:DM &&(}}r/   c                4    U R                   U R                     $ r1   )r5   r   r4   s    r-   	_databaseMongoDBStorageBase._databaseM   s    ||D//00r/   c                :    U R                   U R                  S      $ )Nr   r8   r   r4   s    r-   r   MongoDBStorageBase.countersQ   s    ~~d66zBCCr/   c                :    U R                   U R                  S      $ )Nr   r;   r4   s    r-   r   MongoDBStorageBase.windowsU   s    ~~d66yABBr/   c                    [        5       er1   )NotImplementedErrorr%   r&   r*   s      r-   r2   %MongoDBStorageBase._init_mongo_clientY   s     "##r/   c                .    U R                   R                  $ r1   )r!   PyMongoErrorr4   s    r-   base_exceptions"MongoDBStorageBase.base_exceptions_   s     +++r/   c                l    U R                   R                  SSS9  U R                  R                  SSS9  g )NexpireAtr   )expireAfterSeconds)r   create_indexr   r4   s    r-   __initialize_database(MongoDBStorageBase.__initialize_databasee   s0    "":!"D!!*!Cr/   c                    U R                   R                  0 5      U R                  R                  0 5      -   nU R                   R                  5         U R                  R                  5         [	        U5      $ )zN
Delete all rate limit keys in the rate limit collections (counters, windows)
)r   count_documentsr   dropint)r%   num_keyss     r-   resetMongoDBStorageBase.reseti   sW     ==004t||7S7STV7WW8}r/   c                x    U R                   R                  SU05        U R                  R                  SU05        g)z.
:param key: the key to clear rate limits for
_idN)r   find_one_and_deleter   )r%   keys     r-   clearMongoDBStorageBase.clears   s0     	))5#,7((%6r/   c                    U R                   R                  SU05      nU(       a  US   O[        R                  R                  5       R	                  [        R
                  R                  S9R                  5       $ )z+
:param key: the key to get the expiry for
rU   rH   tzinfo)r   find_onedatetimenowreplacetimezoneutc	timestampr%   rW   counters      r-   
get_expiryMongoDBStorageBase.get_expiryz   s[     --((%6$+WZ 1B1B1F1F1HWH--11W2Y[	
r/   c                    U R                   R                  US[        R                  R                  [        R                  R
                  5      0S.S/S9nU=(       a    US   =(       d    S$ )z2
:param key: the key to get the counter value for
$gte)rU   rH   count)
projectionr   )r   r]   r^   r_   ra   rb   rd   s      r-   getMongoDBStorageBase.get   sh     --((#X%6%6%:%:8;L;L;P;P%QR  y ) 
 +77+0q0r/   c           
     ~   [         R                   R                  [         R                  R                  5      [         R                  " US9-   nU R
                  R                  SU0SSSSS/0USS	U/0S
.0SSSS/0USS
.0S.0/SS/U R                  R                  R                  S9=n(       a  [        US   5      $ g)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)rj   rH   Trj   )upsertrk   return_documentr   )r^   r_   ra   rb   	timedeltar   find_one_and_updater    ReturnDocumentAFTERrP   )r%   rW   expiryamount
expirationresponses         r-   incrMongoDBStorageBase.incr   s     &&**8+<+<+@+@AHDVDVE
 

 }}88CL #',{G.D&E(.)/(F1C(D&" $',{G.D&E(2(3&%( y HH33991 9 
 
8 
4 x())r/   c                H     U R                   R                  5         g!    g= f)z]
Check if storage is healthy by calling :meth:`pymongo.mongo_client.MongoClient.server_info`
TF)r5   server_infor4   s    r-   checkMongoDBStorageBase.check   s$    	LL$$&	s    !c                    [         R                   " 5       n[        U R                  R                  SSU00SSSSSSS	XC-
  /0S
.000SSS0SS0S.0/5      5      =n(       a  US   S   US   S   4$ US4$ )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entryri   z$$entry)inputascondz$minz$filteredEntriesz$size)minrj   r   r   rj   )timelistr   	aggregate)r%   rW   limitr   rc   results         r-   get_moving_window$MongoDBStorageBase.get_moving_window   s     IIK	LL""s|,"- )-7*1-3iAS5T,U,"0%
 #$*,>#?&-/A%B%
 
6 
0 !9U#VAYw%777!|r/   c           	        XB:  a  g[         R                   " 5       n SU/U-  SUS.0S[        R                  R                  [        R                  R                  5      [        R
                  " US9-   0S.nU R                  R                  SUS	X$-
   3S
SXS-
  000USS9  g! U R                  R                  R                   a     gf = f)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   ro   )z$pushrq   rU   zentries.z$notri   T)rz   )r   r^   r_   ra   rb   r|   r   
update_oner    errorsDuplicateKeyError)r%   rW   r   r   r   rc   updatess          r-   acquire_entry MongoDBStorageBase.acquire_entry   s     >IIK		 "+v!5%&"'   ))--h.?.?.C.CD",,V<= & LL##3u~./&69CU:V1W  $  xx00 		s   BB# #$C
	C
c                p   US-  nU R                   R                  SU0SSSSSS/0U/0S	S
S/0S	SS/0S.0SSSSS/0U/0SS	S
S/0S.0SSSSS/0U/0SSU/0SS.0S.0/U R                  R                  R                  / SQS9=n(       a  UR                  S5      (       a8  US   R                  [        R                  R                  S9R                  5       O[        R                  " 5       n[        SU[        R                  " 5       -
  5      n[        SUS   (       a  Xb-
  OS5      nUS   UUS   U4$ g)N  rU   rq   rr   $lte	$subtractrs   rt   $ifNull$currentCountr   $previousCountrv   ru   )previousCountcurrentCountrH   )r   r   rH   )r{   rk   rH   r[   r   r   )r           r   r   )r   r}   r    r~   r   rl   r`   r^   ra   rb   rc   r   max)r%   rW   r   	expiry_msr   
expires_atcurrent_ttlprev_ttls           r-   get_sliding_window%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_6Mk2STUH '~&	  r/   c                   US-  nU R                   R                  SU0SSSSSSS	/0U/0S
SS/0S
SS/0S.000SSSSSS	/0U/0SS
SS/0S.0SSSSS	/0U/0SSSS/0SSU/0SS	SU-  /0S.0SS.0S.0SSSSSSSSSSSSS	U/0/0/0U/0/0S/0000SSSSSSU/0U/0SSU/0SS.000SSSSSU/0U/000SS/0/U R                  R                  R                  SS9n[        [        U(       a	  US   5      $ S5      $ )Nr   rU   rq   r   rr   r   r   rs   rt   r   r   r   r   rv   z$gtru   r   )r   rH   curWeightedCountz$floorz	$multiplyz$dividez$maxr   z$curWeightedCount	_acquiredz$unsetT)r{   rz   F)r   r}   r    r~   r   r   bool)r%   rW   r   r   r   r   r   s          r-   acquire_sliding_window_entry/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&-CCUCCr/   c                $    U R                  U5      $ r1   )rX   )r%   rW   r   s      r-   clear_sliding_window'MongoDBStorageBase.clear_sliding_window  s    zz#r/   c                \    U R                   (       a  U R                   R                  5         g g r1   )r5   closer4   s    r-   __del__MongoDBStorageBase.__del__  s    <<LL  r/   )r   r   r$   r#   r"   r    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)rW   r   r   r   )rW   r   r   float)rW   r   r   rP   )r   )rW   r   r   rP   r   rP   r   rP   )r   r   )rW   r   r   rP   r   rP   r   ztuple[float, int])
rW   r   r   rP   r   rP   r   rP   r   r   )rW   r   r   rP   r   ztuple[int, float, int, float])rW   r   r   rP   r   r   )__name__
__module____qualname____firstlineno____doc__DEPENDENCIESr   propertyr5   r8   r   r   r   r2   rE   r3   rR   rX   rf   rl   r   r   r   r   r   r   r   r   __static_attributes____classcell__)r,   s   @r-   r   r      s    ;L
 &'1&/ %#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DzD"zD,/zD9<zD	zDx! !r/   r   z2.1)versionz3.14.0zEAdded option to select custom collection names for windows & counters)r   reasonc                  2    \ rS rSrSS/r      SS jrSrg)MongoDBStoragei  mongodbzmongodb+srvc                X    [        [        U R                  R                  " U40 UD65      $ r1   )r   r   r    rA   s      r-   r2   !MongoDBStorage._init_mongo_client  s%     K!5!5c!EW!EFFr/    Nr   )r   r   r   r   STORAGE_SCHEMEr2   r   r   r/   r-   r   r     s/      /NGG*:G	Gr/   r   )
__future__r   r^   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/   