+
    }iPE                    `   ^ RI Ht ^ RIt^ RIHtHtHt ^ RIHt ^ RIH	t	H
t
Ht ^ RIHt ^ RIHtHtHtHtHt ^ RIHt ^ R	IHt ^ R
IHt ^ RIHt ^ RIHtHt ^ RIH t H!t! ]	'       d   ^ RI"H#t# ^ RI$H%t% ]! ]&4      t']
! R]R7      t( ! R R])](,          4      t*]! R4       ! R R4      4       t+R# )    )annotationsN)datetime	timedeltatimezone)	getLogger)TYPE_CHECKINGTypeVarcast)service_locator)ClientSnapshotCpuSnapshotEventLoopSnapshotMemorySnapshotSnapshot)ByteSize)ensure_context)
docs_group)RecurringTask)
MemoryInfoget_memory_info)EventEventSystemInfoData)TracebackType)ConfigurationT)boundc                  &    ] tR t^tRtR R ltRtR# )SortedSnapshotListzRA list that maintains sorted order by `created_at` attribute for snapshot objects.c                    V ^8  d   QhRRRR/# )   itemr   returnNone )formats   "r/Users/ahmad/.openclaw/workspace/my-crawler/.venv/lib/python3.14/site-packages/crawlee/_autoscaling/snapshotter.py__annotate__SortedSnapshotList.__annotate__    s     D D Dd D    c                8    \         P                  ! WR R7       R# )zUAdd an item to the list maintaining sorted order by `created_at` using binary search.c                    V P                   # N
created_at)r!   s   &r&   <lambda>(SortedSnapshotList.add.<locals>.<lambda>"   s    4??r)   )keyN)bisectinsort)selfr!   s   &&r&   addSortedSnapshotList.add    s    d&BCr)   r$   N)__name__
__module____qualname____firstlineno____doc__r5   __static_attributes__r$   r)   r&   r   r      s    \D Dr)   r   Autoscalingc                     ] tR t^%tRt]! RR7      t ]! RR7      t ]! ^R7      t Rt	 ]! RR7      t
 ^t R R	 lt]R,R R ll4       t]R R l4       t]R R l4       tR R ltR R lt]R,R R ll4       t]R,R R ll4       t]R,R R ll4       t]R,R R ll4       t]R,R R ll4       tR R  ltR! R" ltR# R$ ltR% R& ltR' R( ltR) R* lt R+t!R
# )-Snapshottera  Monitors and logs system resource usage at predefined intervals for performance optimization.

The class monitors and records the state of various system resources (CPU, memory, event loop, and client API)
at predefined intervals. This continuous monitoring helps in identifying resource overloads and ensuring optimal
performance of the application. It is utilized in the `AutoscaledPool` module to adjust task allocation
dynamically based on the current demand and system load.
i  )millisecondsi  secondsg      ?i'  c               0    V ^8  d   QhRRRRRRRRRR	R
R/# )r    max_used_cpu_ratiofloatmax_used_memory_ratiomax_event_loop_delayr   max_client_errorsintmax_memory_sizer   r"   r#   r$   )r%   s   "r&   r'   Snapshotter.__annotate__A   sH     * * "*  %	*
 (* * "* 
*r)   c                  Wn         W n        W0n        W@n        WPn        V P                  \        \        ,          ! 4       4      V n        V P                  \        \        ,          ! 4       4      V n
        V P                  \        \        ,          ! 4       4      V n        V P                  \        \        ,          ! 4       4      V n        \        V P                   V P"                  4      V n        \        V P&                  V P(                  4      V n        \,        P.                  ! \0        P2                  4      \5        ^R7      ,
          V n        RV n        R# )a  Initialize a new instance.

In most cases, you should use the `from_config` constructor to create a new instance based on
the provided configuration.

Args:
    max_used_cpu_ratio: Sets the ratio, defining the maximum CPU usage. When the CPU usage is higher than
        the provided ratio, the CPU is considered overloaded.
    max_used_memory_ratio: Sets the ratio, defining the maximum ratio of memory usage. When the memory usage
        is higher than the provided ratio of `max_memory_size`, the memory is considered overloaded.
    max_event_loop_delay: Sets the maximum delay of the event loop. When the delay is higher than the provided
        value, the event loop is considered overloaded.
    max_client_errors: Sets the maximum number of client errors (HTTP 429). When the number of client errors
        is higher than the provided number, the client is considered overloaded.
    max_memory_size: Sets the maximum amount of system memory to be used by the `AutoscaledPool`.
)hoursFN)_max_used_cpu_ratio_max_used_memory_ratio_max_event_loop_delay_max_client_errors_max_memory_size_get_sorted_list_by_created_atlistr   _cpu_snapshotsr   _event_loop_snapshotsr   _memory_snapshotsr   _client_snapshotsr   _snapshot_event_loop_EVENT_LOOP_SNAPSHOT_INTERVAL_snapshot_event_loop_task_snapshot_client_CLIENT_SNAPSHOT_INTERVAL_snapshot_client_taskr   nowr   utcr   !_timestamp_of_last_memory_warning_active)r4   rD   rF   rG   rH   rJ   s   &$$$$$r&   __init__Snapshotter.__init__A   s    2 $6 &;#%9""3 /"AA${BSBUV%)%H%HN_I`Ib%c"!%!D!DT.EYE[!\!%!D!DT.EYE[!\)6t7P7PRVRtRt)u&%243H3H$JhJh%i";C<<;UXahiXj;j. r)   Nc                    V ^8  d   QhRRRR/# )r    configzConfiguration | Noner"   r?   r$   )r%   s   "r&   r'   rK   n   s     
 
!5 
 
r)   c                   T;'       g    \         P                  ! 4       pVP                  '       d!   \        P                  ! VP                  4      M@\        \        \        4       P                  P                  VP                  ,          4      4      pV ! VP                  VP                  VP                  VP                  VR7      # )zInitialize a new instance based on the provided `Configuration`.

Args:
    config: The `Configuration` instance. Uses the global (default) one if not provided.
)rD   rF   rG   rH   rJ   )r   get_configurationmemory_mbytesr   from_mbrI   r   
total_sizebytesavailable_memory_ratiorD   rF   rG   rH   )clsrf   rJ   s   && r&   from_configSnapshotter.from_configm   s     >>?<<> ### V112#o/::@@6C`C``ab 	 %88"(">">!'!<!<$66+
 	
r)   c                    V ^8  d   QhRRRR/# )r    
input_listzlist[T]r"   zSortedSnapshotList[T]r$   )r%   s   "r&   r'   rK      s      7 ?T r)   c                T    \         \        ,          ! 4       pVP                  V 4       V# )zCreate a sorted list from the input list.

Returns a custom list that maintains sorted order by created_at when items are added.
)r   r   extend)rr   results   & r&   rS   *Snapshotter._get_sorted_list_by_created_at   s"     $A&(j!r)   c                   V ^8  d   QhRR/# )r    r"   boolr$   )r%   s   "r&   r'   rK      s       r)   c                    V P                   # )z'Indicate whether the context is active.)rb   )r4   s   &r&   activeSnapshotter.active   s     ||r)   c                   V ^8  d   QhRR/# )r    r"   r?   r$   )r%   s   "r&   r'   rK      s      + r)   c                  "   V P                   '       d$   \        RV P                  P                   R24      hRV n         \        P
                  ! 4       pVP                  \        P                  V P                  R7       VP                  \        P                  V P                  R7       V P                  P                  4        V P                  P                  4        V # 5i)zxStart capturing snapshots at configured intervals.

Raises:
    RuntimeError: If the context manager is already active.
The z is already active.Teventlistener)rb   RuntimeError	__class__r7   r   get_event_manageronr   SYSTEM_INFO_snapshot_cpu_snapshot_memoryr[   startr^   )r4   event_managers   & r&   
__aenter__Snapshotter.__aenter__   s      <<<dnn&=&=%>>QRSS'99;u004;M;MNu004;P;PQ&&,,.""((*s   CC c               (    V ^8  d   QhRRRRRRRR/# )	r    exc_typeztype[BaseException] | None	exc_valuezBaseException | Noneexc_tracebackzTracebackType | Noner"   r#   r$   )r%   s   "r&   r'   rK      s2      , ( ,	
 
r)   c                  "   V P                   '       g$   \        RV P                  P                   R24      h\        P
                  ! 4       pVP                  \        P                  V P                  R7       VP                  \        P                  V P                  R7       V P                  P                  4       G Rj  xL
  V P                  P                  4       G Rj  xL
  RV n         R#  L/ L5i)a  Stop all resource capturing.

This method stops capturing snapshots of system resources (CPU, memory, event loop, and client information).
It should be called to terminate resource capturing when it is no longer needed.

Raises:
    RuntimeError: If the context manager is not active.
r~   z is not active.r   NF)rb   r   r   r7   r   r   offr   r   r   r   r[   stopr^   )r4   r   r   r   r   s   &&&& r&   	__aexit__Snapshotter.__aexit__   s      |||dnn&=&=%>oNOO'99; 1 1D<N<NO 1 1D<Q<QR,,11333((--/// 	4/s$   B>C4 C0!C4"C2#C42C4c                    V ^8  d   QhRRRR/# r    durationtimedelta | Noner"   list[Snapshot]r$   )r%   s   "r&   r'   rK           
5 
5*: 
5n 
5r)   c                P    \        RV P                  4      pV P                  W!4      # )zReturn a sample of the latest memory snapshots.

Args:
    duration: The duration of the sample from the latest snapshot. If omitted, it returns a full history.

Returns:
    A sample of memory snapshots.
r   )r
   rW   _get_sampler4   r   	snapshotss   && r&   get_memory_sampleSnapshotter.get_memory_sample   (     )4+A+AB		44r)   c                    V ^8  d   QhRRRR/# r   r$   )r%   s   "r&   r'   rK      s     
5 
5.> 
5. 
5r)   c                P    \        RV P                  4      pV P                  W!4      # )zReturn a sample of the latest event loop snapshots.

Args:
    duration: The duration of the sample from the latest snapshot. If omitted, it returns a full history.

Returns:
    A sample of event loop snapshots.
r   )r
   rV   r   r   s   && r&   get_event_loop_sample!Snapshotter.get_event_loop_sample   s(     )4+E+EF		44r)   c                    V ^8  d   QhRRRR/# r   r$   )r%   s   "r&   r'   rK      s     
5 
5'7 
5> 
5r)   c                P    \        RV P                  4      pV P                  W!4      # )zReturn a sample of the latest CPU snapshots.

Args:
    duration: The duration of the sample from the latest snapshot. If omitted, it returns a full history.

Returns:
    A sample of CPU snapshots.
r   )r
   rU   r   r   s   && r&   get_cpu_sampleSnapshotter.get_cpu_sample   s(     )4+>+>?		44r)   c                    V ^8  d   QhRRRR/# r   r$   )r%   s   "r&   r'   rK      r   r)   c                P    \        RV P                  4      pV P                  W!4      # )zReturn a sample of the latest client snapshots.

Args:
    duration: The duration of the sample from the latest snapshot. If omitted, it returns a full history.

Returns:
    A sample of client snapshots.
r   )r
   rX   r   r   s   && r&   get_client_sampleSnapshotter.get_client_sample   r   r)   c               $    V ^8  d   QhRRRRRR/# )r    r   r   r   r   r"   r$   )r%   s   "r&   r'   rK      s(     	e 	e~ 	e9I 	eUc 	er)   c                    V'       g   V # V '       g   . # V R,          P                   pV  Uu. uF  q2VP                   ,
          V8:  g   K  VNK   	  up# u upi )zPReturn a time-limited sample from snapshots or full history if duration is None.r-   )r   r   latest_timesnapshots   &&  r&   r   Snapshotter._get_sample   sO     Im..)2dXHDWDW6W[c6cddds   A
Ac                    V ^8  d   QhRRRR/# r    
event_datar   r"   r#   r$   )r%   s   "r&   r'   rK      s     * *(; * *r)   c                2   \        VP                  P                  V P                  VP                  P                  R7      p\        RV P                  4      pV P                  W1P                  P                  4       V P                  P                  V4       R# )a,  Capture a snapshot of the current CPU usage.

This method does not perform CPU usage measurement. Instead, it just reads the data received through
the `event_data` parameter, which is expected to be supplied by the event manager.

Args:
    event_data: System info data from which CPU usage is read.
)
used_ratiomax_used_ratior.   r   N)	r   cpu_infor   rN   r.   r
   rU   _prune_snapshotsr5   )r4   r   r   r   s   &&  r&   r   Snapshotter._snapshot_cpu   sx     !**5533!**55
 )4+>+>?	i)<)<)G)GH)r)   c                    V ^8  d   QhRRRR/# r   r$   )r%   s   "r&   r'   rK     s     k k+> k4 kr)   c           	     4   \        VP                  P                  V P                  V P                  VP                  P
                  RRR7      p\        VP                  ;p\        4      '       d#   VP                  Vn        VP                  Vn
        \        RV P                  4      pV P                  WBP
                  4       V P                  P                  V4       V P                  VP                  P                  VP                  P
                  4       R# )a5  Capture a snapshot of the current memory usage.

This method does not perform memory usage measurement. Instead, it just reads the data received through
the `event_data` parameter, which is expected to be supplied by the event manager.

Args:
    event_data: System info data from which memory usage is read.
N)current_sizerJ   rF   r.   system_wide_used_sizesystem_wide_memory_sizer   )r   memory_infor   rR   rO   r.   
isinstancer   r   rk   r   r
   rW   r   r5   _evaluate_memory_load)r4   r   r   r   r   s   &&   r&   r   Snapshotter._snapshot_memory  s     "#//<< 11"&"="=!--88"&$(
 Z%;%;;kZHH-8-N-NH*/:/E/EH,)4+A+AB	i)<)<=""8,"":#9#9#F#F
H^H^HiHijr)   c                   V ^8  d   QhRR/# r    r"   r#   r$   )r%   s   "r&   r'   rK   -  s     1 1d 1r)   c                   \        V P                  \        ^ R7      R7      pV P                  '       d   V P                  R,          MRpV'       d5   VP                  VP                  ,
          V P
                  ,
          pW1n        \        RV P                  4      pV P                  WAP                  4       V P                  P                  V4       R# )a  Capture a snapshot of the current event loop usage.

This method evaluates the event loop's latency by comparing the expected time between snapshots to the actual
time elapsed since the last snapshot. The delay in the snapshot reflects the time deviation due to event loop
overhead - it's calculated by subtracting the expected interval between snapshots from the actual time elapsed
since the last snapshot. If there's no previous snapshot, the delay is considered zero.
rA   )	max_delaydelayNr   r   )
r   rP   r   rV   r.   rZ   r   r
   r   r5   )r4   r   previous_snapshotevent_loop_delayr   s   &    r&   rY    Snapshotter._snapshot_event_loop-  s     %t/I/IQZcdQef>B>X>X>XD66r:^b'225F5Q5QQTXTvTvv-N)4+E+EF	i)<)<=""&&x0r)   c                   V ^8  d   QhRR/# r   r$   )r%   s   "r&   r'   rK   @  s     - -$ -r)   c                   \         P                  ! 4       pVP                  4       pVP                  V P                  ^ 4      pV P
                  '       d   V P
                  R,          P                  M^ p\        VW4,
          V P                  R7      p\        RV P
                  4      pV P                  WeP                  4       V P
                  P                  V4       R# )a3  Capture a snapshot of the current API state by checking for rate limit errors (HTTP 429).

Only errors produced by a 2nd retry of the API call are considered for snapshotting since earlier errors may
just be caused by a random spike in the number of requests and do not necessarily signify API overloading.
)error_countnew_error_countmax_error_countr   Nr   )r   get_storage_clientget_rate_limit_errorsget$_CLIENT_RATE_LIMIT_ERROR_RETRY_COUNTrX   r   r   rQ   r
   r   r.   r5   )r4   clientrate_limit_errorsr   previous_error_countr   r   s   &      r&   r\   Snapshotter._snapshot_client@  s     !335,2,H,H,J'++D,U,UWXYIMI_I_I_t55b9EEef!#'> 33
 )4+A+AB	i)<)<=""8,r)   c               $    V ^8  d   QhRRRRRR/# )r    r   r   r_   r   r"   r#   r$   )r%   s   "r&   r'   rK   V  s!      . x D r)   c                    Rp\        V4       F*  w  rEW%P                  ,
          V P                  8:  g   K(  Tp M	  Ve   VRV1 R# VP                  4        R# )ah  Remove snapshots that are older than the `self._snapshot_history`.

This method modifies the list of snapshots in place, removing all snapshots that are older than the defined
snapshot history relative to the `now` parameter.

Args:
    snapshots: List of snapshots to be pruned in place.
    now: The current date and time, used as the reference for pruning.
N)	enumerater.   _SNAPSHOT_HISTORYclear)r4   r   r_   keep_from_indexir   s   &&&   r&   r   Snapshotter._prune_snapshotsV  sY     $Y/KA(((D,B,BB"# 0 &*?*+OOr)   c               $    V ^8  d   QhRRRRRR/# )r    current_memory_usage_sizer   snapshot_timestampr   r"   r#   r$   )r%   s   "r&   r'   rK   o  s(     H Hx H]e Hjn Hr)   c           	        W P                   V P                  ,           8  d   R# V P                  V P                  ,          pV P                  ^V P                  ,
          ,          V P                  ,          pW4,           pW8  di   \        VP                  V P                  P                  ,          ^d,          4      p\        P                  RV RV P                   RV R24       W n         R# R# )zEvaluate and logs critical memory load conditions based on the system information.

Args:
    current_memory_usage_size: The current memory usage.
    snapshot_timestamp: The time at which the memory snapshot was taken.
Nz'Memory is critically overloaded. Using z of z (z)%). Consider increasing available memory.)	ra   _MEMORY_WARNING_COOLDOWN_PERIODrO   rR   _RESERVE_MEMORY_RATIOroundrl   loggerwarning)r4   r   r   threshold_memory_sizebuffer_memory_sizeoverload_memory_threshold_sizememory_usage_percentages   &&&    r&   r   !Snapshotter._evaluate_memory_loado  s      F FImIm mm $ ; ;d>S>S S!22a$:U:U6UVY]YsYss)>)S& %E&+-F-L-LtOdOdOjOj-jnq,q&r#NN9:S9TTX((),C+D E88
 6H2 Fr)   )rb   rX   rU   rV   rQ   rP   rR   rN   rO   rW   r^   r[   ra   r,   )"r7   r8   r9   r:   r;   r   rZ   r]   r   r   r   r   rc   classmethodro   staticmethodrS   propertyrz   r   r   r   r   r   r   r   r   r   r   rY   r\   r   r   r<   r$   r)   r&   r?   r?   %   s+    %.3$?!: )t <6!"-=c&/U&C#]+,(f*X 
 
2    "0 
5 
5 
5 
5 
5 
5 
5 
5 	e 	e*&k61&-,2H Hr)   r?   ),
__future__r   r2   r   r   r   loggingr   typingr   r	   r
   crawleer   crawlee._autoscaling._typesr   r   r   r   r   crawlee._utils.byte_sizer   crawlee._utils.contextr   crawlee._utils.docsr   crawlee._utils.recurring_taskr   crawlee._utils.systemr   r   crawlee.events._typesr   r   typesr   crawlee.configurationr   r7   r   r   rT   r   r?   r$   r)   r&   <module>r     s    #  2 2  / / # p p - 1 * 7 = <#3	8	Cx Da D M`H `H `Hr)   