o
    ;if                     @   s  d 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 ddl	m
Z
 ddlmZmZmZmZ ddl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 ddlmZ ddlmZmZ ddl m!Z!m"Z" ddl#m$Z$ ddl%m&Z&m'Z' ddl(m)Z)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6 ddl7m8Z8 ddl9m9Z9m:Z: ddl;m<Z< ddl=m>Z>m?Z?m@Z@mAZAmBZB ddlCmDZD ddlEmFZFmGZG ddlHmIZI ddlJmKZK ddlLmMZM erddlNZedZOd e6d!ePd"dfd#d$ZQd e6d%ePd&ePd"eFfd'd(ZR	)	*d_d e6d+ePd,eSePePf d-eTd&ePd.eUd"eFfd/d0ZV	)d`d e6d1ePd,eSePePf d&ePd"eFf
d2d3ZWd4eFd5d6d7ed"dfd8d9ZX	)	)	dad e6d4eFd-eTd:d6d1ePd;ePd<eejY d"eZePe[ej\ f fd=d>Z]	)d`d e6d!ePd?d@dAePd"df
dBdCZ^dbd e6d!ePdDee_ fdEdFZ`edd*dd*dGdHdId ee6 dJeUd&eeP d.eUd"edK fdLdMZadHdId%ePdNe
d&ePd"df
dOdPZbejcdQdRG dSdT dTZd					)dcdHdId1eeP dUed ee6 d&eeP dVePd"edfdWdXZe	QdddYdIdZe[eP d&ePd[eUd\ed"dfd]d^Zfe+eaZge+ebZhe+eeZie+efZjdS )ez.Internal module for building and running Apps.    N)AsyncGenerator)nullcontext)Event)TYPE_CHECKINGAnyOptionalTypeVar)asynccontextmanager)LoadContext)Retry)api_pb2   )	_Function)_get_environment_name_Object)get_app_logs_loopget_pty_info)Resolver)print_server_warningstraceback_contains_remote_call)TaskContextgather_cancel_on_excsynchronize_api)warn_if_passing_namespace)get_git_commit_info)check_object_nameis_valid_tag)HEARTBEAT_INTERVALHEARTBEAT_TIMEOUT_Client)_Cls)configlogger)_get_environment_cached)ConnectionErrorInteractiveTimeoutErrorInvalidErrorRemoteError_CliUserExecutionError)OutputManager)
RunningApprunning_app_from_layout)_Sandbox)_Secret)
StreamTypeVclientapp_idreturnc                    s.   t j|d}| jj|ttddI d H  d S )Nr1   )attempt_timeout)retry)r   AppHeartbeatRequeststubAppHeartbeatr   r   )r0   r1   request r:   @/home/ubuntu/.local/lib/python3.10/site-packages/modal/runner.py
_heartbeat3   s    r<   existing_app_idenvironment_namec                    sJ   t j|d}t| j|t|| I d H \}}d| }t||j|dS )Nr3   zhttps://modal.com/apps/)app_page_url)r   AppGetLayoutRequestr   r7   AppGetLayoutr#   r+   
app_layout)r0   r=   r>   obj_reqobj_resp_r?   r:   r:   r;   _init_local_app_existing;   s   

rF    Fdescriptiontags	app_stateinteractivec           	         s^   t j||||d}t| j|t|| I d H \}}td|j  t	|j|j
|j|dS )N)rH   r>   rJ   rI   zCreated new app with id )r?   app_logs_urlrK   )r   AppCreateRequestr   r7   	AppCreater#   r"   debugr1   r*   r?   rL   )	r0   rH   rI   rJ   r>   rK   app_reqapp_resprE   r:   r:   r;   _init_local_app_newK   s$   
rR   namec                    s`   t j||d}| j|I d H }|jpd }|d ur#t| ||I d H S t| ||t j|dI d H S )N)rS   r>   r>   )r   AppGetByDeploymentNameRequestr7   AppGetByDeploymentNamer1   rF   rR   APP_STATE_INITIALIZING)r0   rS   rI   r>   rP   rQ   r=   r:   r:   r;   _init_local_app_from_nameg   s   
rX   running_applocal_app_statezmodal.app._LocalAppStateload_contextc                    s   i |j |j}jt t }| Y i jji _i _|	 D ]\}}|
  q*fddfdd tjfdd|	 D  I dH  tj fdd|	 D  I dH  W d   dS 1 ssw   Y  dS )	zCreate objects that have been defined but not created on the server.

    The load_context must have a task_context set for proper exception handling
    when loading shared dependencies.
    c                    s    | }|d ur5||s5|jjd}t|jdd }|r%d| dnd}td| d| d| d	| |I d H  |jrI|j	| < d S d S )
NrE   _type_prefixz (expected prefix z-)rG   zExisting object id z
 is not a z idz. This usually means the object name was previously used for a different type. Rename the object/app or stop the previous deployment and redeploy.)
get_is_id_type	__class____name__stripgetattrr&   preloadis_hydrated	object_id)tagobjexisting_object_idexpected_typeexpected_prefixprefix_hint)r[   resolvertag_to_object_idr:   r;   _preload   s   
z%_create_all_objects.<locals>._preloadc                    sj    | }j| |dI d H  t|jr|jj| < d S t|jr-|jj| < d S td|j )N)rh   zUnexpected object )	r]   loadr   r^   re   function_idsr    	class_idsRuntimeError)rf   rg   rh   )r[   rl   rY   rm   r:   r;   _load   s   
z"_create_all_objects.<locals>._loadc                        g | ]\}}  ||qS r:   create_task.0rf   rg   )rn   tcr:   r;   
<listcomp>        z'_create_all_objects.<locals>.<listcomp>Nc                    rt   r:   ru   rw   )rs   ry   r:   r;   rz      r{   )	functionsclassestask_contextr   r)   r]   display_object_treerp   rq   items
_unhydrateasynciogather)rY   rZ   r[   indexed_objects
output_mgrrf   rg   r:   )rs   rn   r[   rl   rY   rm   ry   r;   _create_all_objects~   s    


$&"r   app_local_statedeployment_tagcommit_infoc                    sf   |j }dd | D }tj|j||j||||j|j|d	}	| j	|	I dH }
t
|
j |
j|
jfS )zWrapper for AppPublish RPC.c                 S   s   i | ]	}|j | jqS r:   )re   _get_metadatadefinition_id)rx   rg   r:   r:   r;   
<dictcomp>   s    z _publish_app.<locals>.<dictcomp>)	r1   rS   rI   r   r   rJ   rp   rq   definition_idsN)r|   valuesr   AppPublishRequestr1   rI   rp   rq   r7   
AppPublishr   server_warningsurl)r0   rY   rJ   r   rS   r   r   r|   r   r9   responser:   r:   r;   _publish_app   s"   

r   reasonz1modal_proto.api_pb2.AppDisconnectReason.ValueTypeexc_strc                    sL   |r	|dd }t d tj|||d}| j|I dH  t d dS )znTell the server the client has disconnected for this app. Terminates all running tasks
    for ephemeral apps.Ni  z#Sending app disconnect/stop request)r1   r   	exceptionzApp disconnected)r"   rO   r   AppClientDisconnectRequestr7   AppClientDisconnect)r0   r1   r   r   req_disconnectr:   r:   r;   _disconnect   s   	
r   exc_infoc                    s   t |ttjfrtj}n|durt|jrtj}ntj	}ntj
}t |tr,t|j}n	|r3t|}nd}t| |||I dH  dS )zDisconnect local session of a running app, sending relevant metadata

    exc_info: Exception if an exception caused the disconnect
    NrG   )
isinstanceKeyboardInterruptr   CancelledErrorr   (APP_DISCONNECT_REASON_KEYBOARD_INTERRUPTr   __traceback__&APP_DISCONNECT_REASON_REMOTE_EXCEPTION%APP_DISCONNECT_REASON_LOCAL_EXCEPTION*APP_DISCONNECT_REASON_ENTRYPOINT_COMPLETEDr(   repr	__cause__r   )r0   r1   r   r   r   r:   r:   r;   _status_based_disconnect   s   


r   )r0   detachr>   rK   appmodal.app._Appr   )r   Nc                  sP  | j  j||dI dH  tjjjrtd| jrtd| j	du r>ddl
}dt|v r8| tj|j n| |j |rCtjntj}t }|rU|jsUd}t|| j}	t j| j	p_d|	j j||d	I dH td
 }
|  j4 I dH  t|
d4 I dH } j|j dI dH   fdd}|j!|t"| d}d}|jr|#d dj$ d}|%| |&j$pd W d   n1 sw   Y  |'t( j|j d}zt)|	 I dH  t* j||	I dH  W n9 t+j,y } zt -d t. jj |I dH   d}~w t/y+ } zt. jj |I dH   d}~ww dj$ dj  dj  d}z6|0  |rFt1 n|2 }| | V  W d   n	1 s[w   Y  |3  t. jj ddI dH  W n t4y } zs|r|%d |-| |r|3  t. jj |I dH  n:|-d t. jj |I dH  |rzt+j5||
dI dH  W n t+j6y   t78d Y nw |%dj$ d W Y d}~W d  I dH  W d  I dH  dS d}~w t9y( } z+|r#|jr#|-d  |-| W Y d}~W d  I dH  W d  I dH  dS  d}~w t/yE } zt7:d! t. jj |I dH   d}~ww |rfzt+j5||
dI dH  W n t+j6ye   t78d Y nw W d  I dH  n1 I dH sww   Y  W d  I dH  n1 I dH sw   Y  t }|jr|%d"j$ d dS dS )#mdmd:hiddenr0   r>   Nz5Can not run an app in global scope within a containerz~App is already running and can't be started again.
You should not use `app.run` or `run_app` within a Modal `local_entrypoint`r   __file__zfInteractive mode requires output to be enabled. (Use the the `modal.enable_output()` context manager.)rG   )r>   rJ   rK   logs_timeout)gracer~   r1   c                      s   t  jjS N)r<   r0   r1   r:   r[   rY   r:   r;   	heartbeatC  s   z_run_app.<locals>.heartbeat)sleeplog_exceptionzInitializing...z,Initialized. [grey70]View run at [underline]z[/underline][/grey70]zERROR:NO_APP_PAGEr3   zAborting app initialization...
zdThe detached App will keep running. You can track its progress on the Dashboard: [magenta underline]z=[/magenta underline]

Stream App logs:
[green]modal app logs z.[/green]

Stop the App:
[green]modal app stop z[/green]r   zShutting down Modal client.zPDisconnecting from Modal - This will terminate your Modal app in a few seconds.
)timeoutz%Timed out waiting for final app logs.z,App aborted. [grey70]View run at [underline]z):white_exclamation_mark: Connection lost!zException during app runz.App completed. [grey70]View run at [underline]);_root_load_contextresetin_place_upgrademodal_runtimeexecution_context_is_currently_importingr&   _running_apprH   __main__dirset_descriptionospathbasenamer   r`   r   APP_STATE_DETACHEDAPP_STATE_EPHEMERALr)   r]   
is_enabled_local_staterR   r0   rI   r>   r!   _set_local_appr   r1   infinite_loopr   make_live_spinnerr?   step_completedupdate_app_page_urlrv   r   r   r   r   r   printr   BaseExceptionenable_image_logsr   show_status_spinnercancelr   wait_forTimeoutErrorr"   warningr$   info)r   r0   r   r>   rK   r   rJ   r   msgrZ   r   ry   r   heartbeat_loop	logs_loopinitialized_msgedetached_disconnect_msgspinner_ctxr:   r   r;   _run_app  s   




	0
		



(S


(Z
Vkr   is_readyc              	      s   | j  j|dI dH }zRt|j||I dH }| j}t 4 I dH }|j||jdI dH  t|||I dH  W d  I dH  n1 I dH sGw   Y  t	|j|t
j|dI dH  |  W dS  tjjyk   Y dS w )r   rT   Nr   )rJ   r   )r   r   r   rF   r0   r   r   r1   r   r   r   APP_STATE_UNSPECIFIEDsetr   
exceptionsr   )r   r=   r   r>   r[   rY   rZ   ry   r:   r:   r;   _serve_update  s&   (r   T)frozenc                   @   s6   e Zd ZU dZeed< eed< eed< ee ed< dS )DeployResultz6Dataclass representing the result of deploying an app.r1   r?   rL   warningsN)r`   
__module____qualname____doc__str__annotations__listr:   r:   r:   r;   r     s   
 r   	namespacerf   c                    s2  t |d |p| jpd}|stdt|d |r(t|dds(td|d d	u r3t I d	H  | j}t }t	
t }| j j |d
I d	H }	t|	j||j|	jdI d	H td4 I d	H ~}
|	j|
jdI d	H   fdd}|
j|td z?t||	I d	H  d	}z|I d	H }W n ty } ztjd|d W Y d	}~nd	}~ww t tj||||dI d	H \}}W n ty } zt jtjdI d	H  |d	}~ww W d	  I d	H  n1 I d	H sw   Y  t ! }t | }|"d|dd |#d| d t$jj%j&dd |D dS )zxInternal function for deploying an App.

    Users should prefer the `modal deploy` CLI or the `App.deploy` method.
    zmodal.runner.deploy_apprG   zYou need to either supply a deployment name or have a name set on the app.

Examples:
modal.runner.deploy_app(app, name="some_name")

or
app = modal.App("some-name")App2   )
max_lengthzDeployment tag z is invalid.

Tags may only contain alphanumeric characters, dashes, periods, and underscores, and must be 50 characters or lessNr   rT   r   r   c                      s   t  jS r   )r<   r1   r:   r0   rY   r:   r;   r     s   z_deploy_app.<locals>.heartbeat)r   zFailed to get git commit infor   )rS   r   r   )r   zApp deployed in z.3fu   s! 🎉z
View Deployment: [magenta]z
[/magenta]c                 S   s   g | ]}|j qS r:   )message)rx   r   r:   r:   r;   rz   8  s    z_deploy_app.<locals>.<listcomp>)r1   r?   rL   r   )'r   rS   r&   r   r   r   from_envr   timer   rv   r   r   r   r   rX   r0   rI   r>   r   r1   r   r   r   	Exceptionr"   rO   r   r   APP_STATE_DEPLOYEDr   *APP_DISCONNECT_REASON_DEPLOYMENT_EXCEPTIONr)   r]   r   r   r   r?   rL   )r   rS   r   r0   r>   rf   rZ   t0commit_info_taskroot_load_contextry   r   r   r   app_urlr   r   tr:   r   r;   _deploy_app  s~   

	

	("r   _appcmdsptykwargsc              	      s  t  I dH }t }|d t| ||d4 I dH  t|dkr%|ndg}td td t d}|	d	g t
|g }	|d
 tj		d| |	d|I dH }
|d z4|rw|
j||rftddndd
dI dH }| I dH  n|
j|tjtjdI dH }| I dH  W n$ ty   tj|
jdd}|
jj|I dH }|jjrt|jj w W d  I dH  dS 1 I dH sw   Y  dS )aB  Run an interactive shell (like `bash`) within the image for this app.

    This is useful for online debugging and interactive exploration of the
    contents of this image. If `cmd` is optionally provided, it will be run
    instead of the default shell inside this image.

    **Example**

    ```python
    import modal

    app = modal.App(image=modal.Image.debian_slim().apt_install("vim"))
    ```

    You can now run this using

    ```
    modal shell script.py --cmd /bin/bash
    ```

    When calling programmatically, `kwargs` are passed to `Sandbox.create()`.
    NTr   r   z	/bin/bashtoken_idtoken_secret)MODAL_TOKEN_IDMODAL_TOKEN_SECRETMODAL_ENVIRONMENTsecretsFr   100000)r   r  )shell)pty_infotext)stdoutstderr)
sandbox_idr   )r   r	  )r   r   r)   r]   set_quiet_moder   lenr!   r   popr-   	from_dictr,   _create_execr   attachr.   STDOUTwaitr%   r   SandboxWaitRequest
_object_id_clientr7   SandboxWaitresultr   r'   )r   r   r>   r  r  r0   r   sandbox_cmdssandbox_envr  sandboxcontainer_processreqrespr:   r:   r;   _interactive_shell<  sT   


	
.r$  )rG   F)rG   )rG   rG   Nr   )NNNNrG   )rG   T)kr   r   dataclassesr   r   collections.abcr   
contextlibr   multiprocessing.synchronizer   typingr   r   r   r   synchronicity.async_wrapr	    modal._runtime.execution_contextr   modal_proto.api_pb2modal_protomodal._load_contextr
   modal._utils.grpc_utilsr   r   
_functionsr   _objectr   r   _output.ptyr   r   	_resolverr   
_tracebackr   r   _utils.async_utilsr   r   r   _utils.deprecationr   _utils.git_utilsr   _utils.name_utilsr   r   r0   r   r   r   clsr    r!   r"   environmentsr#   r   r$   r%   r&   r'   r(   outputr)   rY   r*   r+   r   r,   secretr-   stream_typer.   	modal.appr/   r   r<   rF   dictintboolrR   rX   r   
CommitInfotupler   Warningr   r   r   r   r   r   	dataclassr   r   r$  run_appserve_update
deploy_appinteractive_shellr:   r:   r:   r;   <module>   sh  

 


G
"
 &

!
d
L