
    tnit@                        d Z ddlZddlZddlZddlmZ ddlmZmZm	Z	m
Z
 ddlZddlZddlmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZ ddlmZ ddl m!Z!m"Z" ej#        $                    dd          Z%dZ&dZ'ej#        $                    dd          e'dz  Z'dZ(dZ)dZ*dZ+ e"            Z, e            Z-e G d d                      Z!e G d d                      Z.e G d d                      Z/e G d d                       Z0e G d! d"                      Z1d#e2d$ee2ef         d%e3fd&Z4 G d' d(          Z5dS ))zK Used to launch the FastAPI web server when worker is running in API mode.     N)	dataclass)AnyDictOptionalUnion)	APIRouterFastAPI)jsonable_encoderRedirectResponse   )SyncClientSession)__version__   )is_generator)run_jobrun_job_generator)	Heartbeat)JobJobsProgressRUNPOD_ENDPOINT_IDzRunpod | Development Worker APIa.  
The Development Worker API facilitates testing and debugging of your Runpod workers.
It offers a sandbox environment for executing code and simulating interactions with your worker, ensuring your applications can seamlessly transition to production on Runpod serverless platform.
Use this API for comprehensive testing of request submissions and result retrieval, mimicking the behavior of Runpod's operational environment.
---
*Note: This API serves as a local testing tool and will not be utilized once your worker is operational on the Runpod platform.*
RUNPOD_PROJECT_IDu   

    ℹ️ | Consider developing with our CLI tool to streamline your worker development process.

    >_  wget -qO- cli.runpod.net | sudo bash
    >_  runpodctl project create
    aC  
Initiates processing jobs, returning a unique job ID.

**Parameters:**
- **input** (string): The data to be processed by the worker. This could be a string, JSON object, etc., depending on the worker's requirements.
- **webhook** (string, optional): A callback URL for result notification upon completion. If specified, the server will send a POST request to this URL with the job's result once it's available.

**Returns:**
- **job_id** (string): A unique identifier for the job, used with the `/stream` and `/status` endpoints for monitoring progress and checking job status.
a  
Executes processing jobs synchronously, returning the job's output directly.

This endpoint is ideal for tasks where immediate result retrieval is necessary,
streamlining the execution process by eliminating the need for subsequent
status or result checks.

**Parameters:**
- **input** (string): The data to be processed by the worker. This should be in a format that the worker can understand (e.g., JSON, text, etc.).
- **webhook** (string, optional): A callback URL to which the result will be posted. While direct result retrieval is the primary operation mode for this endpoint, specifying a webhook allows for asynchronous result notification if needed.

**Returns:**
- **output** (Any): The direct output from the processing job, formatted according to the job's nature and the expected response structure. This could be a JSON object, plain text, or any data structure depending on the processing logic.
a  
Continuously aggregates the output of a processing job, returning the full output once the job is complete.

This endpoint is especially useful for jobs where the complete output needs to be accessed at once. It provides a consolidated view of the results post-completion, ensuring that users can retrieve the entire output without the need to poll multiple times or manage partial results.

**Parameters:**
- **job_id** (string): The unique identifier of the job for which output is being requested. This ID is used to track the job's progress and aggregate its output.

**Returns:**
- **output** (Any): The aggregated output from the job, returned as a single entity once the job has concluded. The format of the output will depend on the nature of the job and how its results are structured.
av  
Checks the completion status of a processing job and returns its output if the job is complete.

This endpoint is invaluable for monitoring the progress of a job and obtaining the output only after the job has fully completed. It simplifies the process of querying job completion and retrieving results, eliminating the need for continuous polling or result aggregation.

**Parameters:**
- **job_id** (string): The unique identifier for the job being queried. This ID is used to track and assess the status of the job.

**Returns:**
- **status** (string): The completion status of the job, typically 'complete' or 'in progress'. This status indicates whether the job has finished processing and if the output is ready for retrieval.
- **output** (Any, optional): The final output of the job, provided if the job is complete. The format and structure of the output depend on the job's nature and the data processing involved.

**Note:** The availability of the `output` field is contingent on the job's completion status. If the job is still in progress, this field may be omitted or contain partial results, depending on the implementation.
c                   @    e Zd ZU dZeed<   eeeee	e
ef         ed<   dS )r   zRepresents a job.idinputN)__name__
__module____qualname____doc__str__annotations__r   dictlistintfloatbool     a/var/www/html/gpu-tools/venv/lib/python3.11/site-packages/runpod/serverless/modules/rp_fastapi.pyr   r   h   s?         GGGtS#ud2333333r(   r   c                   z    e Zd ZU dZdZee         ed<   dZee	e
eeeeef                  ed<   dZee         ed<   dS )TestJobz>Represents a test job.
    input can be any type of data.
    Nr   r   webhook)r   r   r   r   r   r   r    r!   r   r   r"   r#   r$   r%   r&   r,   r'   r(   r)   r+   r+   p   sm           B@DE8E$c3t;<=DDD!GXc]!!!!!r(   r+   c                   H    e Zd ZU dZeeef         ed<   dZe	e         ed<   dS )DefaultRequestzRepresents a test input.r   Nr,   )
r   r   r   r   r   r    r   r!   r,   r   r'   r(   r)   r.   r.   {   s@         ""S>!GXc]!!!!!r(   r.   c                   t    e Zd ZU dZeed<   eed<   dZeee	e
eeeef                  ed<   dZee         ed<   dS )	JobOutputzRepresents the output of a job.r   statusNoutputerror)r   r   r   r   r    r!   r2   r   r   r"   r#   r$   r%   r&   r3   r'   r(   r)   r0   r0      se         ))GGGKKKAEFHU4sC<=>EEEE8C=r(   r0   c                   x    e Zd ZU dZeed<   dZeed<   dZee	e
eeeeef                  ed<   dZee         ed<   dS )StreamOutputzStream representation of a job.r   IN_PROGRESSr1   Nstreamr3   )r   r   r   r   r    r!   r1   r7   r   r   r"   r#   r$   r%   r&   r3   r'   r(   r)   r5   r5      sl         ))GGGFCAEFHU4sC<=>EEEE8C=r(   r5   urlpayloadreturnc                 *   t                      5 }	 |                    | |d          }|                                 	 ddd           dS # t          j        $ r+}t          d|  d|            Y d}~ddd           dS d}~ww xY w# 1 swxY w Y   dS )z
    Sends a webhook to the provided URL.

    Args:
        url (str): The URL to send the webhook to.
        payload (Dict[str, Any]): The JSON payload to send.

    Returns:
        bool: True if the request was successful, False otherwise.
    
   )jsontimeoutNTzWEBHOOK | Request to z	 failed: F)r   postraise_for_statusrequestsRequestExceptionprint)r8   r9   sessionresponseerrs        r)   _send_webhookrG      s    
		 	||Cgr|BBH%%'''	       
 ( 	 	 	=#====>>>555       
	         s4   B,ABB /B BBBBc                       e Zd ZdZdeeef         fdZddZde	fd	Z
d
edefdZd
edefdZdedefdZdedefdZdS )	WorkerAPIzMUsed to launch the FastAPI web server when the worker is running in API mode.configc           	         t                                            || _        dddddddddg}t          t          t
          t          d|	          | _        t                      }|	                    d
d d           t          r'|	                    dt           d| j        dg           |	                    d| j        dgddt          dg           |	                    d| j        dgddt          dg           |	                    d| j        dgddt"          dg           |	                    d| j        dgddt&          dg           | j                            |           dS )z
        Initializes the WorkerAPI class.
        1. Starts the heartbeat thread.
        2. Initializes the FastAPI web server.
        3. Sets the handler for processing jobs.
        z.Synchronously Submit Request & Get Job Resultsz>Endpoints for submitting job requests and getting the results.)namedescriptionzSubmit Job Requestsz&Endpoints for submitting job requests.zCheck Job ResultszCEndpoints for checking the status of a job and getting the results./)titlerM   versiondocs_urlopenapi_tagsz/docsc                  "    t          d          S )NrN   )r8   r   r'   r(   r)   <lambda>z$WorkerAPI.__init__.<locals>.<lambda>   s    -#666 r(   F)include_in_schemaz	/realtimePOST)methodsz/runTz(Mimics the behavior of the run endpoint.)rW   response_model_exclude_nonesummaryrM   tagsz/runsyncz,Mimics the behavior of the runsync endpoint.z/stream/{job_id}z+Mimics the behavior of the stream endpoint.z/status/{job_id}z+Mimics the behavior of the status endpoint.N)	heartbeat
start_pingrJ   r	   TITLEDESCRIPTIONrunpod_versionrp_appr   add_api_router   	_realtime_sim_runRUN_DESCRIPTION_sim_runsyncRUNSYNC_DESCRIPTION_sim_streamSTREAM_DESCRIPTION_sim_statusSTATUS_DESCRIPTIONinclude_router)selfrJ   tags_metadata
api_routers       r)   __init__zWorkerAPI.__init__   s    	 I_ 
 .G 
 ,d 
  #"&
 
 
 [[
 	  66% 	! 	
 	
 	
  	$$1&1114>F8 %   
 	  MH(,>''( 	! 	
 	
 	
 	  H(,B+BC 	! 	
 	
 	
 	  H(,A*%& 	! 	
 	
 	
 	  H(,A*%& 	! 	
 	
 	
 	"":.....r(   	localhost@  r   c           
          t          j        | j        |t          |          t          |          t          j                            dd          d           dS )z,
        Starts the Uvicorn server.
        UVICORN_LOG_LEVELinfoF)hostportworkers	log_level
access_logN)uvicornrunr`   r$   osenvironget)rl   api_hostapi_portapi_concurrencys       r)   start_uvicornzWorkerAPI.start_uvicorn  sZ     	KX((jnn%8&AA	
 	
 	
 	
 	
 	
r(   jobc                    K   t                               |j                   t          | j        d         |j                   d{V }t                               |j                   t          |          S )z
        Performs model inference on the input data using the provided handler.
        If handler is not provided, returns an error message.
        handlerN)job_listaddr   r   rJ   __dict__remover
   )rl   r   job_resultss      r)   rb   zWorkerAPI._realtime  sl      
 	SV $DK	$:CLIIIIIIII  ,,,r(   job_requestr:   c                    K   dt          j                     }t                              ||j        |j        d           t          |dd          S )z.Development endpoint to simulate run behavior.test-)r   r   r,   r6   )r   r1   )uuiduuid4r   r   r   r,   r
   )rl   r   assigned_job_ids      r)   rc   zWorkerAPI._sim_run0  s`      0$*,,00! &"*
 
 	 	 	
  - P PQQQr(   c                   K   dt          j                     }t          ||j                  }t	          | j        d                   rQt          | j        d         |j                  }dg i}|2 3 d{V }|d                             |d                    )6 n&t          | j        d         |j                   d{V }|
                    dd          rt          |j        d|d         d          S |j        r7t          j        t           |j        |fd	
          }|                                 t          |j        d|d         d          S )z2Development endpoint to simulate runsync behavior.r   r   r   r   r2   Nr3   FAILEDr   r1   r3   Ttargetargsdaemon	COMPLETEDr   r1   r2   )r   r   r+   r   r   rJ   r   r   appendr   r~   r
   r   r,   	threadingThreadrG   start)rl   r   r   r   generator_output
job_outputstream_outputthreads           r)   re   zWorkerAPI._sim_runsync;  s     0$*,,000ABBBI.// 	M0Y1GVV"BJ'7 E E E E E E Em8$++M(,CDDDD (8'7  't{9'=s|LLLLLLLLJ>>'4(( 	#vJw<OPP    	%$!):6  F
 LLNNN6[Jx<PQQ
 
 	
s   /Bjob_idc                 `  K   t                               |          }|t          |ddd          S t          ||j                  }t          | j        d                   rKt          | j        d         |j                  }g }|2 3 d{V }|	                    d|d         i           %6 nt          |ddd          S t           
                    |j                   |j        r7t          j        t          |j        |fd	
          }|                                 t          |d|d          S )z1Development endpoint to simulate stream behavior.Nr   Job ID not foundr   r   r   r2   z2Stream not supported, handler must be a generator.Tr   r   )r   r1   r7   )r   r~   r
   r+   r   r   rJ   r   r   r   r   r   r,   r   r   rG   r   )rl   r   stashed_jobr   r   stream_accumulatorr   r   s           r)   rg   zWorkerAPI._sim_streamZ  s     ll6**#<NOO   {'8999I.// 	0Y1GVV!#'7 O O O O O O Om"))8]85L*MNNNN (8'7 $ &Q    	 	%$!)+=>  F
 LLNNN[<NOO
 
 	
s   B+c                   K   t                               |          }|t          |ddd          S t          |j        |j                  }t          | j        d                   rQt          | j        d         |j	                  }dg i}|2 3 d{V }|d         
                    |d                    )6 n&t          | j        d         |j	                   d{V }t                               |j                   |                    dd          rt          |d|d         d          S |j        r7t          j        t           |j        |fd	
          }|                                 t          |d|d         d          S )z1Development endpoint to simulate status behavior.Nr   r   r   r   r   r2   r3   Tr   r   r   )r   r~   r
   r+   r   r   r   rJ   r   r   r   r   r   r,   r   r   rG   r   )rl   r   r   r   r   r   r   r   s           r)   ri   zWorkerAPI._sim_status  s     ll6**#<NOO   {/@AAAI.// 	M0Y1GVV"BJ'7 E E E E E E Em8$++M(,CDDDD (8'7  't{9'=s|LLLLLLLLJ>>'4(( 	#Jw<OPP    	%$!):6  F
 LLNNN[Jx<PQQ
 
 	
s   B6N)rp   rq   r   )r   r   r   r   r   r    r   ro   r   r   rb   r.   r0   rc   re   r5   rg   ri   r'   r(   r)   rI   rI      s       WWX/tCH~ X/ X/ X/ X/t
 
 
 
-3 - - - -(R. RY R R R R
n 
 
 
 
 
>$
 $
 $
 $
 $
 $
N#
 #
	 #
 #
 #
 #
 #
 #
r(   rI   )6r   r|   r   r   dataclassesr   typingr   r   r   r   rA   rz   fastapir   r	   fastapi.encodersr
   fastapi.responsesr   http_clientr   rP   r   r_   
rp_handlerr   rp_jobr   r   rp_pingr   worker_stater   r   r}   r~   r   r]   r^   rd   rf   rh   rj   r   r[   r+   r.   r0   r5   r    r&   rG   rI   r'   r(   r)   <module>r      s   Q Q 				      ! ! ! ! ! ! - - - - - - - - - - - -   & & & & & & & & - - - - - - . . . . . . , , , , , , 4 4 4 4 4 4 $ $ $ $ $ $ . . . . . . . .       + + + + + + + +Z^^$8$?? ) :>>%t,,4  K	 
  " <>>IKK	 4 4 4 4 4 4 4 4 " " " " " " " " " " " " " " " "                                s T#s(^     0s
 s
 s
 s
 s
 s
 s
 s
 s
 s
r(   