
    :j:                         d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
mZmZmZ ddlmZ  ed      Z ed	      Ze G d
 d             Z G d dee         Zedde	defd       Zy)z
Resource Management - Resource Pool and Context Managers

This module provides resource management utilities including resource pools
and context managers for network connections.
    N)contextmanager)	dataclass)AnyCallableGenericOptionalTypeVar   )
get_logger	resourcesTc                   f    e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	eed<   dZ
eed<   dZeed<   y	)
ResourceStatszStatistics for resource poolr   createdacquiredreleasedexpiredactive	pool_sizeN)__name__
__module____qualname____doc__r   int__annotations__r   r   r   r   r        6/root/.openclaw/workspace/harvester/tools/resources.pyr   r      s@    &GSHcHcGSFCOIsr   r   c                   |    e Zd ZdZ	 	 	 ddeg ef   dededeeegdf      fdZ	defd	Z
d
eddfdZdefdZddZy)ResourcePoolz5Generic resource pool for managing reusable resourcesNfactorymax_sizemax_agecleanup_funcc                     || _         || _        || _        || _        g | _        t        j                         | _        t        j                         | _
        t               | _        y)a  Initialize resource pool

        Args:
            factory: Function to create new resources
            max_size: Maximum number of resources in pool
            max_age: Maximum age of resources in seconds
            cleanup_func: Optional cleanup function for resources
        N)r!   r"   r#   r$   _poolweakrefWeakSet_active	threadingLock_lockr   _stats)selfr!   r"   r#   r$   s        r   __init__zResourcePool.__init__'   sM      (
(^^%
#or   returnc                    | j                   5  | j                  r| j                  j                         }|\  }}t        j                         |z
  | j                  k  rd| j
                  j                  |       | j                  xj                  dz  c_        | j                  xj                  dz  c_	        |cddd       S | j                  r	 | j                  |       | j                  xj                  dz  c_        | j                  r	 | j                         }| j
                  j                  |       | j                  xj                   dz  c_        | j                  xj                  dz  c_        | j                  xj                  dz  c_	        |cddd       S # t        $ r"}t        j                  d|        Y d}~d}~ww xY w# t        $ r}t        j#                  d|         d}~ww xY w# 1 sw Y   yxY w)z Acquire a resource from the poolr
   Nz$Failed to cleanup expired resource: zFailed to create new resource: )r,   r&   poptimer#   r)   addr-   r   r   r$   	Exceptionloggerwarningr   r!   r   error)r.   resource_inforesource
created_ates        r   acquirezResourcePool.acquire@   s   ZZ 	** $

 0'4$* 99;+dll:LL$$X.KK((A-(KK&&!+&#	 	 ((W --h7 KK''1,'# **(	<<>  *##q(#$$)$""a'"9	 	"  ) W"NN-QRSQT+UVVW  >qcBC;	 	s[   B*G7G7F+G7B	G	G
(G G7G

G7	G4G//G44G77H r:   c                    | j                   5  || j                  v r| j                  j                  |       | j                  xj                  dz  c_        | j                  xj
                  dz  c_        t        | j                        | j                  k  rT| j                  j                  |t        j                         f       t        | j                        | j                  _        n| j                  r	 | j                  |       ddd       y# t        $ r"}t        j                  d|        Y d}~/d}~ww xY w# 1 sw Y   yxY w)z#Release a resource back to the poolr
   zFailed to cleanup resource: N)r,   r)   discardr-   r   r   lenr&   r"   appendr3   r   r$   r5   r6   r7   )r.   r:   r<   s      r   releasezResourcePool.releasec   s   ZZ 	O4<<'$$X.""a'"$$)$ tzz?T]]2JJ%%x&=>,/

ODKK) ((O --h7	O 	O  ) O"NN-I!+MNNO	O 	Os0   C*E 8D	D=D83E 8D==E  E	c                     | j                   5  t        | j                        | j                  _        | j                  cddd       S # 1 sw Y   yxY w)zGet pool statisticsN)r,   r@   r&   r-   r   )r.   s    r   	get_statszResourcePool.get_statsw   s9    ZZ 	$'

ODKK!;;	 	 	s   0AAc                 \   | j                   5  | j                  r&| j                  D ]  \  }}	 | j                  |        | j                  j                          d| j                  _        ddd       y# t        $ r"}t        j                  d|        Y d}~td}~ww xY w# 1 sw Y   yxY w)zCleanup all resources in poolz0Failed to cleanup resource during pool cleanup: Nr   )	r,   r$   r&   r5   r6   r7   clearr-   r   )r.   r:   _r<   s       r   cleanupzResourcePool.cleanup}   s    ZZ 		&  #':: _KHa_))(3_ JJ$%DKK!		& 		&
 % _)YZ[Y\']^^_		& 		&s3   B"A4-B"4	B=BB"BB""B+)
   g     r@N)r0   N)r   r   r   r   r   r   r   floatr   r/   r=   rB   r   rD   rH   r   r   r   r    r    $   s    ?
 6:&"a%& & 	&
 xT	23&2! !FO Od O(= &r   r    
connectionconnection_typec           	   #   J  K   	 t         j                  d| d       |  	 	 t	        | d      r| j                          t         j                  d| d       y# t        $ r!}t         j                  d| d|         d}~ww xY w# t        $ r%}t         j                  d| d|        Y d}~yd}~ww xY w# 	 t	        | d      r| j                          t         j                  d| d       w # t        $ r%}t         j                  d| d|        Y d}~w d}~ww xY wxY ww)	zContext manager for network connections

    Args:
        connection: Network connection object
        connection_type: Type of connection for logging
    z	Acquired z connectionzError with z connection: Nclosez	Released zFailed to close )r6   debugr5   r8   hasattrrN   r7   )rK   rL   r<   s      r   managed_networkrQ      s    Qy 1=>
	Qz7+  "LL9_$5[AB  {?"3=DE  	QNN-o->mA3OPP	Q		Qz7+  "LL9_$5[AB 	QNN-o->mA3OPP	Qs   D#A 5B D#	B"A>>BB7 	B4B/*D#/B44D#7D 95C/.D /	D8DD DD  D#)network)r   r*   r3   r'   
contextlibr   dataclassesr   typingr   r   r   r   r	   r6   r   r   r   r    strrQ   r   r   r   <module>rW      s       % ! < < 	K	 CL   d&71: d&N Q Qc Q Qr   