o
    ;iG                     @   sV  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 dd
lmZ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 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' dZ(eG dd dZ)G dd dZ*ee*Z+dddede,e-e-f fddZ.G dd dedd Z/ee/Z0dS )!    N)	dataclass)datetime)OptionalUnion)Message)classproperty)api_pb2   )LoadContext)_get_environment_name_Objectlive_method)Resolver)is_local)synchronize_api)deprecation_warningwarn_if_passing_namespace)check_object_name)as_timestamptimestamp_to_localized_dt)_Client)AlreadyExistsErrorInvalidErrorNotFoundErrorzGthe env_dict argument to Secret has to be a dict[str, Union[str, None]]c                   @   s2   e Zd ZU dZee ed< eed< ee ed< dS )
SecretInfoz$Information about the Secret object.name
created_at
created_byN)__name__
__module____qualname____doc__r   str__annotations__r    r$   r$   @/home/ubuntu/.local/lib/python3.10/site-packages/modal/secret.pyr      s
   
 r   c                   @   s   e Zd ZdZedddddedeeef dedee d	ee	 d
dfddZ
eddddddee deeeef  ded	ee	 d
ejd f
ddZedddddededee d	ee	 fddZdS )_SecretManagerz9Namespace with methods for managing named Secret objects.FN)allow_existingenvironment_nameclientr   env_dictr'   r(   r)   returnc                   s   t | d |du rt I dH n|}|rtjntj}tj| t|||d}z|j	|I dH  W dS  t
y?   |s< Y dS w )a  Create a new Secret object.

        **Examples:**

        ```python notest
        contents = {"MY_KEY": "my-value", "MY_OTHER_KEY": "my-other-value"}
        modal.Secret.objects.create("my-secret", contents)
        ```

        Secrets will be created in the active environment, or another one can be specified:

        ```python notest
        modal.Secret.objects.create("my-secret", contents, environment_name="dev")
        ```

        By default, an error will be raised if the Secret already exists, but passing
        `allow_existing=True` will make the creation attempt a no-op in this case.
        If the `env_dict` data differs from the existing Secret, it will be ignored.

        ```python notest
        modal.Secret.objects.create("my-secret", contents, allow_existing=True)
        ```

        Note that this method does not return a local instance of the Secret. You can use
        `modal.Secret.from_name` to perform a lookup after creation.

        Added in v1.1.2.

        SecretNdeployment_namer(   object_creation_typer*   )r   r   from_envr   &OBJECT_CREATION_TYPE_CREATE_IF_MISSING*OBJECT_CREATION_TYPE_CREATE_FAIL_IF_EXISTSSecretGetOrCreateRequestr   stubSecretGetOrCreater   )r   r*   r'   r(   r)   r/   reqr$   r$   r%   create*   s(   
&z_SecretManager.create )max_objectscreated_beforer(   r)   r9   r:   _Secretc                    s    du rt  I dH n  durdk rtdg dtdtf fdd}|t|I dH }	 |r7n|d	 jjjI dH }q4 fd
dD }durX|d S |S )a  Return a list of hydrated Secret objects.

        **Examples:**

        ```python
        secrets = modal.Secret.objects.list()
        print([s.name for s in secrets])
        ```

        Secrets will be retreived from the active environment, or another one can be specified:

        ```python notest
        dev_secrets = modal.Secret.objects.list(environment_name="dev")
        ```

        By default, all named Secrets are returned, newest to oldest. It's also possible to limit the
        number of results and to filter by creation date:

        ```python
        secrets = modal.Secret.objects.list(max_objects=10, created_before="2025-01-01")
        ```

        Added in v1.1.2.

        Nr   zmax_objects cannot be negativer:   r+   c                    s   d u rdnt dt }tj|| d}tjt|d} j|I d H }|j	 t|j	|k p?d uo?tk}|S )Nd   )r9   r:   )r(   
pagination)
minlenr   ListPaginationSecretListRequestr   r4   
SecretListextenditems)r:   max_page_sizer=   r6   respfinishedr)   r(   rD   r9   r$   r%   retrieve_page   s   "z*_SecretManager.list.<locals>.retrieve_pageTc                    s.   g | ]}t j|j |jd t |jdqS )T)is_another_apprep)r;   _new_hydrated	secret_idmetadata_reprlabel).0item)r)   r(   r$   r%   
<listcomp>   s    z'_SecretManager.list.<locals>.<listcomp>)	r   r0   r   floatboolr   rO   creation_infor   )r9   r:   r(   r)   rI   rG   secretsr$   rH   r%   listc   s    !
z_SecretManager.list)allow_missingr(   r)   rZ   c                   sb   zt j| |d|I dH }W n ty   |s Y dS w tj|jd}|jj	|I dH  dS )a  Delete a named Secret.

        Warning: Deletion is irreversible and will affect any Apps currently using the Secret.

        **Examples:**

        ```python notest
        await modal.Secret.objects.delete("my-secret")
        ```

        Secrets will be deleted from the active environment, or another one can be specified:

        ```python notest
        await modal.Secret.objects.delete("my-secret", environment_name="dev")
        ```

        Added in v1.1.2.

        )r(   N)rN   )
r;   	from_namehydrater   r   SecretDeleteRequest	object_id_clientr4   SecretDelete)r   rZ   r(   r)   objr6   r$   r$   r%   delete   s   z_SecretManager.delete)r   r   r    r!   staticmethodr"   dictrV   r   r   r7   intr   r   builtinsrY   rb   r$   r$   r$   r%   r&   '   s`    
8Cr&   instancer;   load_contextr*   c                    sf   |j durtjtj||j |jd}n
tjtj||jd}|jj|I dH }| 	|j
|j|j dS )z:helper method for loaders .from_dict and .from_dotenv etc.N)r/   r*   app_idr(   )r/   r*   r(   )ri   r   r3   +OBJECT_CREATION_TYPE_ANONYMOUS_OWNED_BY_APPr(   OBJECT_CREATION_TYPE_EPHEMERALr)   r4   r5   _hydraterN   rO   )rg   rh   r*   r6   rF   r$   r$   r%   _load_from_env_dict   s   
rm   c                   @   s  e Zd ZU dZdZeej ed< e	de
fddZedee fddZd	ee fd
dZdejfddZei fdeeee f dd fddZedee dd fddZed(ddddee dd fddZeddg dddedee dee dee dd f
ddZe				d)d edeeef dee dee d!edefd"d#Ze				d)d edeeef dee dee d!edefd$d%Zedefd&d'ZdS )*r;   a  Secrets provide a dictionary of environment variables for images.

    Secrets are a secure way to add credentials and other sensitive information
    to the containers your functions run in. You can create and edit secrets on
    [the dashboard](https://modal.com/secrets), or programmatically from Python code.

    See [the secrets guide page](https://modal.com/docs/guide/secrets) for more information.
    N	_metadatar+   c                 C   s   t S N)r&   )clsr$   r$   r%   objects   s   z_Secret.objectsc                 C   s   | j S ro   )_nameselfr$   r$   r%   r      s   z_Secret.namerO   c                 C   s*   |rt |tjs
J || _|j| _d S d S ro   )
isinstancer   SecretMetadatarn   r   rr   )rt   rO   r$   r$   r%   _hydrate_metadata   s
   z_Secret._hydrate_metadatac                 C   s   | j sJ | j S ro   )rn   rs   r$   r$   r%   _get_metadata   s   
z_Secret._get_metadatar*   c              	      s   t | ts	ttdd |  D  tdd   D s!tttdd   D s0ttdtdt	dt
d	tt f fd
d}dd|   d}tj||dt
 dS )a  Create a secret from a str-str dictionary. Values can also be `None`, which is ignored.

        Usage:
        ```python
        @app.function(secrets=[modal.Secret.from_dict({"FOO": "bar"})])
        def run():
            print(os.environ["FOO"])
        ```
        c                 S   s   i | ]\}}|d ur||qS ro   r$   rR   kvr$   r$   r%   
<dictcomp>  s    z%_Secret.from_dict.<locals>.<dictcomp>c                 s       | ]}t |tV  qd S ro   ru   r"   rR   rz   r$   r$   r%   	<genexpr>      z$_Secret.from_dict.<locals>.<genexpr>c                 s   r}   ro   r~   )rR   r{   r$   r$   r%   r     r   rt   resolverrh   existing_object_idc                    s   t | | I d H  d S ro   )rm   )rt   r   rh   r   env_dict_filteredr$   r%   _load  s   z _Secret.from_dict.<locals>._loadzSecret.from_dict([z, z])Thydrate_lazilyload_context_overrides)ru   rd   r   ENV_DICT_WRONG_TYPE_ERRrD   allkeysvaluesr;   r   r
   r   r"   join_from_loaderempty)r*   r   rL   r$   r   r%   	from_dict  s$   
z_Secret.from_dictenv_keysc              
   C   sZ   t  r(ztdd | D W S  ty' } z|jd }td| dd}~ww ti S )z>Create secrets from local environment variables automatically.c                 S   s   i | ]}|t j| qS r$   )osenvironr   r$   r$   r%   r|   *  s    z._Secret.from_local_environ.<locals>.<dictcomp>r   z+Could not find local environment variable 'z' for Secret.from_local_environN)r   r;   r   KeyErrorargsr   )r   excmissing_keyr$   r$   r%   from_local_environ"  s   


z_Secret.from_local_environz.env)filenamer)   r)   c             	      s<   dt dtdtdtt f fdd}t j|ddt|d	d
S )a  Create secrets from a .env file automatically.

        If no argument is provided, it will use the current working directory as the starting
        point for finding a `.env` file. Note that it does not use the location of the module
        calling `Secret.from_dotenv`.

        If called with an argument, it will use that as a starting point for finding `.env` files.
        In particular, you can call it like this:
        ```python
        @app.function(secrets=[modal.Secret.from_dotenv(__file__)])
        def run():
            print(os.environ["USERNAME"])  # Assumes USERNAME is defined in your .env file
        ```

        This will use the location of the script calling `modal.Secret.from_dotenv` as a
        starting point for finding the `.env` file.

        A file named `.env` is expected by default, but this can be overridden with the `filename`
        keyword argument:

        ```python
        @app.function(secrets=[modal.Secret.from_dotenv(filename=".env-dev")])
        def run():
            ...
        ```
        rt   r   rh   r   c                    s   zddl m}m} ddlm} W n ty   tdw d ur<|D ]}tj| }tj	|r8|}	 nq%d}	n| dd}	dd	 ||	
 D }
t| ||
I d H  d S )
Nr   )dotenv_valuesfind_dotenv)_walk_to_rootz_Need the `dotenv` package installed. You can install it by running `pip install python-dotenv`.r8   T)usecwdc                 S   s   i | ]	\}}||p
d qS )r8   r$   ry   r$   r$   r%   r|   j  s    z6_Secret.from_dotenv.<locals>._load.<locals>.<dictcomp>)dotenvr   r   dotenv.mainr   ImportErrorr   pathr   isfilerD   rm   )rt   r   rh   r   r   r   r   dirname
check_pathdotenv_pathr*   r   r   r$   r%   r   P  s*   z"_Secret.from_dotenv.<locals>._loadzSecret.from_dotenv()T)r)   r   )r;   r   r
   r   r"   r   )r   r   r)   r   r$   r   r%   from_dotenv3  s   z_Secret.from_dotenv)	namespacer(   required_keysr)   r   r(   r   c             	      sV   t |d dtdtdtdtt f fdd}t |}tj||d t||d	d
S )a  Reference a Secret by its name.

        In contrast to most other Modal objects, named Secrets must be provisioned
        from the Dashboard. See other methods for alternate ways of creating a new
        Secret from code.

        ```python
        secret = modal.Secret.from_name("my-secret")

        @app.function(secrets=[secret])
        def run():
           ...
        ```
        zmodal.Secret.from_namert   r   rh   r   c                    s@   t j |jd}|jj|I d H }| |j|j|j d S )N)r.   r(   r   )	r   r3   r(   r)   r4   r5   rl   rN   rO   )rt   r   rh   r   r6   responser   r   r$   r%   r     s   z _Secret.from_name.<locals>._loadT)r(   r)   )r   r   r   )r   r;   r   r
   r   r"   rP   r   )r   r   r(   r   r)   r   rL   r$   r   r%   r[   r  s$   

z_Secret.from_nameFr.   	overwritec                    s&   t dd t| |||||I dH S )mdmd:hidden)i        zThe undocumented `modal.Secret.create_deployed` method is deprecated and will be removed in a future release. It can be replaced with `modal.Secret.objects.create`.N)r   r;   _create_deployed)r.   r*   r   r)   r(   r   r$   r$   r%   create_deployed  s   
z_Secret.create_deployedc           	         sl   t |d t| d |du rt I dH }|rtj}ntj}tj| t|||d}|j	
|I dH }|jS )r   zmodal.Secret.create_deployedr,   Nr-   )r   r   r   r0   r   /OBJECT_CREATION_TYPE_CREATE_OVERWRITE_IF_EXISTSr2   r3   r   r4   r5   rN   )	r.   r*   r   r)   r(   r   r/   requestrF   r$   r$   r%   r     s    


z_Secret._create_deployedc                    s0   |   }|j}t|jpdt|j|jpddS )z+Return information about the Secret object.N)r   r   r   )rx   rW   r   r   r   r   r   )rt   rO   rW   r$   r$   r%   info  s   z_Secret.inforo   )NNNF) r   r   r    r!   rn   r   r   rv   r#   r   r&   rq   propertyr"   r   r   rw   rx   rc   rd   r   rY   r   r   r   r[   rV   r   r   r   r   r   r$   r$   r$   r%   r;      s   
 	
 ">	.

st)type_prefix)1rf   r   dataclassesr   r   typingr   r   google.protobuf.messager   synchronicityr   modal_protor   _load_contextr
   _objectr   r   r   	_resolverr   _runtime.execution_contextr   _utils.async_utilsr   _utils.deprecationr   r   _utils.name_utilsr   _utils.time_utilsr   r   r)   r   	exceptionr   r   r   r   r   r&   SecretManagerrd   r"   rm   r;   r,   r$   r$   r$   r%   <module>   s8    & x