o
    ;iR                     @   sh  d dl Z d dlZd dlZd dl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 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 ddlmZ dd	lmZ dd
lmZ ddlmZmZ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(m)Z)m*Z*m+Z+m,Z, ddl-m.Z.m/Z/m0Z0 G dd deZ1G dd dej2Z3G dd dej4Z5e6e7e8e9e: e3 dZ;G dd deZ<eG dd dZ=dej>e
de	f e?f d e@e6e?f fd!d"ZAd#ejBd$e@e6e?f d e=fd%d&ZCd'e	d eeDe	df  fd(d)ZEd*e	d e6fd+d,ZFd-e@e6e1f fd.d/ZGd0e6d e6fd1d2ZHd3e6d4e	fd5d6ZId7d8 ZJd9e=d:e
eDe6df e@e6e	f ge	f fd;d<ZKd=ej	d ejBfd>d?ZLd@edAedBejMfdCdDZNd@edEe(dBejMfdFdGZOd@edHefdIdJZPdKeQe' d e6fdLdMZRG dNdO dOejSZTejUeTdPdQejVdRdSdTdUejVdVdWdXdYdZejVd[d\dXd]dZejVd^d_dXd`dZejVdadbe/ddcejVdddXdedZejVdfdXdgdZejWdhdi ZXejYddjdUejZdkdldUe.ejZdmdndUejZdkdodUejZdmdddedUejZdmdfdgdUfdpe6dqe6dre6dse9dte6due9dve9fdwdxZ[ejYddydUde.ejZdmdddedUejZdmdfdgdUfdpe6dzee8 dre6due9dve9f
d{d|Z\dS )}    N)	dataclass)AnyCallableOptional)ClickException)	TypedDict   )AppLocalEntrypoint) _get_class_constructor_signature)config)
ensure_env)ExecutionErrorInvalidError_CliUserExecutionError)Function)OutputManager)
deploy_apprun_app)	serve_app   )
CLICommandMethodReference_get_runnable_appimport_and_filterimport_app_from_refparse_import_ref)
ENV_OPTIONENV_OPTION_HELPstream_app_logsc                   @   s6   e Zd ZU eed< eed< eed< eed< eed< dS )ParameterMetadatanamedefault
annotation	type_hintkindN)__name__
__module____qualname__str__annotations__r    r+   r+   A/home/ubuntu/.local/lib/python3.10/site-packages/modal/cli/run.pyr    %   s   
 r    c                   @   s   e Zd ZdZdd ZdS )AnyParamTypeanyc                 C   s   |S Nr+   )selfvalueparamctxr+   r+   r,   convert0   s   zAnyParamType.convertN)r&   r'   r(   r!   r4   r+   r+   r+   r,   r-   -   s    r-   c                       s:   e Zd ZdZdeedf f fddZ fddZ  ZS )LiteralIntParamTypez7A ParamType for Literal types containing only integers.literal_values.c                    s*   dd |D | _ t t| j   d S )Nc                 S   s   i | ]}t ||qS r+   )r)   .0vr+   r+   r,   
<dictcomp>8       z0LiteralIntParamType.__init__.<locals>.<dictcomp>)
int_valuessuper__init__listkeys)r0   r6   	__class__r+   r,   r>   7   s   zLiteralIntParamType.__init__c                    sH   t |trt |ts|| j v r|S t|}t |||}| j| S r/   )
isinstanceintboolr<   valuesr)   r=   r4   )r0   r1   r2   r3   	str_valuerA   r+   r,   r4   ;   s   
zLiteralIntParamType.convert)	r&   r'   r(   __doc__tuplerD   r>   r4   __classcell__r+   r+   rA   r,   r5   4   s    r5   )r)   rD   floatrE   zdatetime.datetimer   c                   @   s   e Zd ZdS )NoParserAvailableN)r&   r'   r(   r+   r+   r+   r,   rL   R   s    rL   c                   @   s&   e Zd ZU eeef ed< eed< dS )CliRunnableSignature
parametershas_variadic_argsN)r&   r'   r(   dictr)   r    r*   rE   r+   r+   r+   r,   rM   V   s   
 rM   func_or_cls.returnc              
   C   s<   zt | W S  ty } zdt| }t||d }~ww )Nz\Unable to generate command line interface for app entrypoint due to unparseable type hints:
)typingget_type_hints	Exceptionr)   r   )rQ   excmsgr+   r+   r,   safe_get_type_hints\   s   
rX   sig
type_hintsc                 C   sv   d}i }| j  D ] }|jtjjkrd}q	|j|j|j|	|jd|jd||j< q	|r6t
|dkr6tdt||S )NFTr   )r!   r"   r#   r$   r%   r   zYFunctions with variable-length positional arguments (*args) cannot have other parameters.)rN   rF   r%   inspect	ParameterVAR_POSITIONALr!   r"   r#   getlenr   rM   )rY   rZ   rO   	signaturer2   r+   r+   r,   _get_cli_runnable_signaturee   s   
ra   r$   c                 C   s<   zt | }|t ju rt | W S W dS  ty   Y dS w )zExtract values from a Literal type annotation.

    Returns None if not a Literal type, otherwise returns tuple of literal values.
    N)rS   
get_originLiteralget_argsrU   )r$   originr+   r+   r,   _get_literal_valuesz   s   

rf   annotc                 C   s@   t | }g d}|D ]}t||}|dur|d  S q
|S )zMReturn annotation as a string, handling various spellings for optional types.)ztyping\.Optional\[([\w.]+)\]z#typing\.Union\[([\w.]+), NoneType\]z([\w.]+) \| Nonez<class '([\w\.]+)'>Nr   )r)   rematchgroup)rg   	annot_strannot_patternspatmr+   r+   r,   _get_param_type_as_str   s   ro   rN   c           
      C   s*  |  D ]}|d dd}d| }t|d  }durItdd |D r-tt|}nCtd	d |D r;t|}n5d
| d|d  }t|t	|d }|dkrY|d| 7 }t
|}|du rpd
| d|d  }t|d|i}	|d tjjur|d |	d< nd|	d< tj|fi |	|  q| S )z~Adds @click.option based on function signature

    Kind of like typer, but using options instead of positional arguments
    r!   _-z--r$   Nc                 s   s    | ]}t |tV  qd S r/   )rC   r)   r7   r+   r+   r,   	<genexpr>   s    z%_add_click_options.<locals>.<genexpr>c                 s   s&    | ]}t |tot |t V  qd S r/   )rC   rD   rE   r7   r+   r+   r,   rr      s   $ zParameter `z` has unparseable annotation: r#   rE   z/--no-typer"   Trequired)rF   replacerf   allclickChoicer?   r5   rL   ro   option_parsersr^   r[   	Signatureemptyoption)
funcrN   r2   
param_namecli_namer6   parserrW   param_type_strkwargsr+   r+   r,   _add_click_options   s0   

r   func_refc                 C   sB   zt j| }dt j|d  W S  ty    dt j Y S w )N )sysargvindexjoin
ValueError)r   func_ref_arg_idxr+   r+   r,   _get_clean_app_description   s   r   result_pathresc                 C   st   t |trd}nt |trd}nt|j}td| dt| |}|| W d    d S 1 s3w   Y  d S )NwtwbzCFunction must return str or bytes when using `--write-result`; got .)rC   r)   bytesrs   r&   r   openwrite)r   r   moderes_typefidr+   r+   r,   _write_local_result   s   


"r   c                 C   s,   | j d }| j d }|s|rtdd S d S )Ninteractiveshow_progressz0To use interactive mode, remove the --quiet flag)objr   )r3   r   r   r+   r+   r,   "_validate_interactive_quiet_params   s
   

r   r`   innerc                    s   t j fdd}|S )Nc                    s   j rt|dksJ | j}nd}t|  t }|| jd du  || jd  t	 | jd | jd | jd d	 ||}W d    n1 sLw   Y  | jd
  }r_t
|| d S d S )Nr   r+   r   Fshow_timestampsdetachenvr   r   environment_namer   r   )rO   r_   argsr   r   r^   set_quiet_moder   set_timestampsr   r   )r3   r   r   
output_mgrr   r   appr   r`   r+   r,   f   s&   z_make_click_function.<locals>.f)rw   pass_context)r   r`   r   r   r+   r   r,   _make_click_function   s   r   r}   c                 C   s<   i }t jdd dkrddl}|jj|d< tj| fi |S )z7Returns signature with the original source annotations.Nr   )      r   annotation_format)r   version_infoannotationlibFormatSTRINGr[   r`   )r}   r   r   r+   r+   r,   _get_signature   s
   r   r   functionr3   c           	         s|   j rtdtjj}tjj}t||} fdd}t| ||}t||j	}|j
r9tjdddd|S t|S )Nz4`modal run` is not supported for generator functionsc                    s.    j d rj| i | S j| i |S )Nr   )r   spawnr^   remote)r   click_kwargsr3   r   r+   r,   _inner  s   
z/_get_click_command_for_function.<locals>._innerTignore_unknown_optionsallow_extra_argscontext_settings)is_generatorr   r   inforaw_frX   ra   r   r   rN   rO   rw   command)	r   r   r3   rY   rZ   r`   r   r   with_click_optionsr+   r   r,   _get_click_command_for_function  s   

r   
method_refc                    s  |j  |j  }t|}t|}t||jrtd  }dv rBt	|
 }t|dkr7|d ntd   d| }| }	tt|	d }
t|
t|	tdi jj} fdd}t| |}t||}jrtjd	d	d
d|S t|S )NzGModal classes cannot have variable-length positional arguments (*args).)* r   r   z$Please specify a specific method of z- to run, e.g. `modal run foo.py::MyClass.bar`c                    sn    fddj D } fddj D }di |}t|}jd r/|j| i | S |j| i |S )Nc                       i | ]}| | qS r+   r+   r8   kr   r+   r,   r:   B  r;   z>_get_click_command_for_cls.<locals>._inner.<locals>.<dictcomp>c                    r   r+   r+   r   r   r+   r,   r:   C  r;   r   r+   )rN   getattrr   r   r^   r   )r   r   
cls_kwargs
fun_kwargsinstancemethodclscls_signaturer3   fun_signaturemethod_namer   r,   r   ?  s   

z*_get_click_command_for_cls.<locals>._innerTr   r   r+   )r   r   _get_user_clsrX   r   ra   rO   r   _get_partial_functionsr?   r@   r_   rw   
UsageError	_get_name
_get_raw_fr   	functoolspartialrP   rN   r   r   r   )r   r   r3   user_clsrZ   rY   partial_functionsmethod_namespartial_functionr   sig_without_selfrN   r   r   r   r+   r   r,   _get_click_command_for_cls  s:   



r   
entrypointc                    sn   |j jtttttj fdd}t	|j
}jr2tjdddd|S t|S )Nc                    s&  | j d r	td jrt|dkrt|dksJ | j}t|  t }|| j d du  |	| j d  t
 | j d | j d | j d d	3 zrWt|i |}n|i |}W n tys } ztt|d }~ww W d    n1 s~w   Y  | j d
  }rt|| d S d S )Nr   zNote that running a local entrypoint in detached mode only keeps the last triggered Modal function alive after the parent process has been killed or disconnected.r   r   Fr   r   r   r   r   )r   printrO   r_   r   r   r   r^   r   r   r   asynciorunrU   r   r[   getsourcefiler   )r3   r   r   r   r   rV   r   r   r}   isasyncr`   r+   r,   r   ]  s>   
z2_get_click_command_for_local_entrypoint.<locals>.fTr   r   )r   r   r[   iscoroutinefunctionra   r   rX   rw   r   r   rN   rO   r   )r   r   r   r   r+   r   r,   '_get_click_command_for_local_entrypointW  s   
!
r   all_usable_commandsc                 C   s.   g }| D ]}d |j}|| qd |S )Nz / 
)r   namesappend)r   usable_command_linescmd	cmd_namesr+   r+   r,   _get_runnable_list  s
   
r   c                   @   s   e Zd Zdd ZdS )RunGroupc           
      C   s  | t t|jd |jd< t||jd d}t|dddd\}}|sKd|j d	}|r;d
|j d}|t|7 }nd
|j d}t	| d| t
|}|jd u r[|t| t|trgt||}	|	S t|trtt|||}	|	S t|trt|||}	|	S t| d)Nr   rn   use_module_modez	modal runTF)base_cmdaccept_local_entrypointaccept_webhookzFSpecify a Modal Function or local entrypoint to run. E.g.
> modal run z::my_function [..args]'z5' has the following functions and local entrypoints:
z(' has no functions or local entrypoints.z

z6 is neither function, local entrypoint or class/method)ensure_objectrP   r   paramsr   r   r   file_or_moduler   r   r   descriptionset_descriptionr   rC   r
   r   r   r   r   r   r   )
r0   r3   r   
import_refrunnabler   help_headerhelp_footerr   click_commandr+   r+   r,   get_command  s:   






zRunGroup.get_commandN)r&   r'   r(   r  r+   r+   r+   r,   r     s    r   FUNC_REF)r   subcommand_metavarz-wz--write-resultzCWrite return value (which must be str or bytes) to this local path.)helpz-qz--quietTz%Don't show Modal progress indicators.)is_flagr  z-dz--detachz<Don't stop the app if the local process dies or disconnects.z-iz--interactivez Run the app in interactive mode.z-ez--env)r  r"   z-mzHInterpret argument as a Python module path instead of a file/script pathz--timestampsz"Show timestamps for each log line.c                 C   sH   |  t || jd< || jd< |rdnd| jd< || jd< || jd< dS )	aA  Run a Modal function or local entrypoint.

    `FUNC_REF` should be of the format `{file or module}::{function name}`.
    Alternatively, you can refer to the function via the app:

    `{file or module}::{app variable name}.{function name}`

    **Examples:**

    To run the hello_world function (or local entrypoint) in my_app.py:

    ```
    modal run my_app.py::hello_world
    ```

    If your module only has a single app and your app has a
    single local entrypoint (or single function), you can omit the app and
    function parts:

    ```
    modal run my_app.py
    ```

    Instead of pointing to a file, you can also use the Python module path, which
    by default will ensure that your remote functions will use the same module
    names as they do locally.

    ```
    modal run -m my_project.my_app
    ```
    r   r   FTr   r   r   N)r   rP   r   )r3   write_resultr   quietr   r   rn   
timestampsr+   r+   r,   r     s   
,


r   z+Path to a Python file with an app to deployr   zName of the deployment.Fz)Stream logs from the app upon deployment.z"Tag the deployment with a version.app_refr!   r   stream_logstagr   r  c           
      C   sz   t |}t| |d}t | t|dd}|p|jpd}|s$tdt|||p*d|d}	|r;t	|	j
|	j|d dS dS )	ztDeploy a Modal application.

    **Usage:**
    modal deploy my_script.py
    modal deploy -m my_package.my_mod
    r   zmodal deployr   r   zYou need to either supply an explicit deployment name on the command line or have a name set on the App.

Examples:
app = modal.App("some-name")
modal deploy ... --name=some-name)r!   r   r  )app_idapp_logs_urlr   N)r   r   r   r^   r   r   r!   r   r   r   r  r  )
r  r!   r   r  r  r   r  r   r   r   r+   r+   r,   deploy  s   	r  z"Path to a Python file with an app.timeoutc                 C   s   t |}t| |d}t | t|dd}|jdu r#|t|  t	|||d7 |du r3t
d }|du r;td}|dkrYt|d	}t| ||8 }|dks?W d   dS W d   dS 1 sdw   Y  dS )
a  Run a web endpoint(s) associated with a Modal app and hot-reload code.

    **Examples:**

    ```
    modal serve hello_world.py
    ```

    Modal-generated URLs will have a `-dev` suffix appended to them when running with `modal serve`.
    To customize this suffix (i.e., to avoid collisions with other users in your workspace who are
    concurrently serving the App), you can set the `dev_suffix` in your `.modal.toml` file or the
    `MODAL_DEV_SUFFIX` environment variable.

    r   zmodal server  N)r   serve_timeoutinfr   i  )r   r   r   r^   r   r   r   r   r   r   r   rK   mintimesleep)r  r  r   r   r  r   r   tr+   r+   r,   serve  s&   



"r  )]r   r   r[   rh   r   r  rS   dataclassesr   r   r   r   rw   typerr   typing_extensionsr   r   r	   r
   r   r   r   environmentsr   	exceptionr   r   r   	functionsr   outputr   runnerr   r   servingr   import_refsr   r   r   r   r   r   utilsr   r   r   r    	ParamTyper-   rx   r5   r)   rD   rK   rE   DateTimery   rL   rM   Unionrs   rP   rX   rz   ra   rI   rf   ro   r   r   r   r   r   r   Contextr   r   r   r?   r   Groupr   rj   r|   r   r   ArgumentOptionr  r  r+   r+   r+   r,   <module>   s    
, 	(
.
92	+)	
+