
    )`i                         d Z ddlmZmZ ddlmZmZ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  G d d	e          Z G d
 d          ZdS )a
  Generic handler resolution logic for container standards.

This module provides a reusable template for resolving handlers with a consistent
priority order across different container types (SageMaker, etc.).

## Handler Resolution Priority Order

1. **Environment variable** specified function
2. **Registry** @decorated function
3. **Customer script** function
4. **Default** handler (if any)

## Usage Examples

```python
from model_hosting_container_standards.handler_resolver import GenericHandlerResolver

# Define handler-specific configuration
class MyHandlerConfig:
    def get_env_handler(self, handler_type: str):
        # Return handler from environment variable
        pass

    def get_customer_script_handler(self, handler_type: str):
        # Return handler from customer script
        pass

# Create resolver with configuration
resolver = GenericHandlerResolver(MyHandlerConfig())

# Resolve specific handlers
ping_handler = resolver.resolve_handler("ping")
invoke_handler = resolver.resolve_handler("invoke")
```
    )ABCabstractmethod)AnyCallableOptionalUnion)HandlerFileNotFoundErrorHandlerNotFoundErrorHandlerResolutionErrorInvalidHandlerSpecError)logger   )handler_registryc                       e Zd ZdZededeedef         edf         fd            Z	edede
edef                  fd            ZdS )HandlerConfigzAbstract base class for handler configuration.

    Subclasses must implement methods to load handlers from different sources.
    handler_typereturn.Nc                     dS )a  Get handler from environment variable.

        Args:
            handler_type: Type of handler (e.g., "ping", "invoke")

        Returns:
            Callable: Function handler
            str: Router path
            None: No handler found

        Raises:
            HandlerResolutionError: If env var is set but invalid
            InvalidHandlerSpecError: If handler spec is malformed
        N selfr   s     /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/model_hosting_container_standards/common/handler/resolver.pyget_env_handlerzHandlerConfig.get_env_handler9   s	    $ 	    c                     dS )zGet handler from customer script.

        Args:
            handler_type: Type of handler (e.g., "ping", "invoke")

        Returns:
            Callable function or None if not found
        Nr   r   s     r   get_customer_script_handlerz)HandlerConfig.get_customer_script_handlerM   s	     	r   )__name__
__module____qualname____doc__r   strr   r   r   r   r   r   r   r   r   r   r   3   s         
 	xS!3,	-   ^& 	(38$	%   ^  r   r   c                       e Zd ZdZddeddfdZdedee         fdZ	dedee         fdZ
dedee         fd	Zdedee         fd
ZdS )GenericHandlerResolverzGeneric handler resolver that implements consistent priority order.

    The resolver uses a clean separation of concerns with individual methods
    for each resolution step, making the code more maintainable and testable.
    Nconfigr   c                 0    || _         |pt          | _        dS )zInitialize the handler resolver.

        Args:
            config: Handler configuration for loading from different sources
            registry: Handler registry (defaults to global registry)
        N)r$   r   registry)r   r$   r&   s      r   __init__zGenericHandlerResolver.__init__c   s      4$4r   r   c                    	 | j                             |          }t          |          r:t          |dt	          |                    }t          j        d| d|            |S |rt          j        d| d|            n.# t          t          f$ r t          j
        d| d            w xY wt          j        d| d	           d
S )a[  Try to resolve handler from environment variable.

        Args:
            handler_type: Type of handler to resolve

        Returns:
            Handler function if found, None otherwise

        Raises:
            HandlerResolutionError: If env var is set but invalid
            InvalidHandlerSpecError: If handler spec is malformed
        r   z
Found env 
 handler: zEnv z handler is router path: zEnvironment variable z handler configuration errorzNo env  handler foundN)r$   r   callablegetattrr!   r   infodebugr   r   error)r   r   env_handlerhandler_names       r   _try_env_handlerz'GenericHandlerResolver._try_env_handlerm   s   	+55lCCK$$ 
&{JK@P@PQQOOOOOPPP""  O<OO+OO   '(?@ 	 	 	LRRRR   	 	;|;;;<<<ts   A"B %B +B-c                     | j                             |          }|r:t          |dt          |                    }t	          j        d| d|            |S t	          j        d| d           dS )zTry to resolve handler from registry decorators.

        Args:
            handler_type: Type of handler to resolve

        Returns:
            Handler function if found, None otherwise
        r   zFound decorator r)   zNo decorator r*   N)r&   get_decorator_handlerr,   r!   r   r.   )r   r   decorated_handlerr1   s       r   _try_decorator_handlerz-GenericHandlerResolver._try_decorator_handler   s     !M??MM 	%"!:s3D/E/E L LRLRRLRRSSS$$A\AAABBBtr   c           	         	 | j                             |          }|r:t          |dt          |                    }t	          j        d| d|            |S nl# t          t          f$ r6}t	          j        d| dt          |          j	                    Y d}~n*d}~wt          $ r t	          j        d| d            w xY wt	          j        d	| d
           dS )zTry to resolve handler from customer script.

        Args:
            handler_type: Type of handler to resolve

        Returns:
            Handler function if found, None otherwise
        r   zFound customer module z: zNo customer script z function found: NzCustomer script z function failed to loadzNo customer module z found)r$   r   r,   r!   r   r.   r	   r
   typer   	Exceptionr/   )r   r   customer_handlerr1   es        r   _try_customer_script_handlerz3GenericHandlerResolver._try_customer_script_handler   s8   	#{FF|TT (&$j#6F2G2G    TlTTlTTUUU''( )*>? 	 	 	LWlWWT!WWEUWW         	 	 	LRLRRRSSS	
 	?<???@@@ts   AA C*,B'Cc                     t          j        d| d           | j        | j        | j        fD ]} ||          }|r|c S t          j        d| d           dS )a  
        Resolve handler with priority order:
        1. Environment variable specified function
        2. Registry @decorated function
        3. Customer script function
        4. Default handler registered by the framework

        Args:
            handler_type: Type of handler to resolve (e.g., "ping", "invoke")

        Returns:
            Resolved handler function or None if not found
        resolve_z_handler calledzNo z handler found anywhereN)r   r.   r2   r6   r<   )r   r   resolver_methodhandlers       r   resolve_handlerz&GenericHandlerResolver.resolve_handler   s     	====>>> !'- 
 	 	O
 &ol33G  	@<@@@AAAtr   )N)r   r   r   r    r   r'   r!   r   r   r2   r6   r<   rA   r   r   r   r#   r#   \   s         5 5} 5 5 5 5 5"S "Xh5G " " " "H3 8H;M    ( (AS    <!C !HX4F ! ! ! ! ! !r   r#   N)r    abcr   r   typingr   r   r   r   ,model_hosting_container_standards.exceptionsr	   r
   r   r   0model_hosting_container_standards.logging_configr   r&   r   r   r#   r   r   r   <module>rF      s  " "H $ # # # # # # # 1 1 1 1 1 1 1 1 1 1 1 1            D C C C C C & & & & & && & & & &C & & &RH H H H H H H H H Hr   