# generated by datamodel-codegen:
#   filename:  application.json
#   timestamp: 2024-02-15T05:19:20+00:00

from __future__ import annotations

from enum import Enum
from typing import Any, Dict, List, Optional, Union

from servicefoundry.pydantic_v1 import (
    BaseModel,
    Field,
    PositiveFloat,
    PositiveInt,
    confloat,
    conint,
    constr,
)


class AWSAccessKeyAuth(BaseModel):
    aws_access_key_id: str = Field(
        ..., description="+label=AWS Access Key ID\n+usage=AWS Access Key ID\n+sort=1"
    )
    aws_secret_access_key: str = Field(
        ...,
        description="+label=AWS Secret Access Key\n+usage=AWS Secret Access Key for the user to authenticate with\n+sort=2",
    )
    aws_session_token: Optional[str] = Field(
        None,
        description="+label=AWS Session Token\n+usage=AWS Session Token, only required when using temporary credentials\n+sort=3",
    )


class AWSInferentia(BaseModel):
    type: constr(regex=r"^aws_inferentia$") = Field(
        ..., description="+value=aws_inferentia"
    )
    name: Optional[str] = Field(
        None,
        description="+label=Inferentia accelerator name\n+usage=Name of the AWS Inferentia Accccelerator. One of [INF1, INF2].\nThis field is required for Node Selector and can be ignored in Nodepool Selector.",
    )
    count: conint(ge=1, le=16) = Field(
        ...,
        description="+label=Count\n+usage=Count of Inferentia accelerator chips to provide to the application",
    )


class ArtifactsCacheVolume(BaseModel):
    """
    +docs=Describes the volume that will be used to cache the models
    +label=Artifacts Cache Volume
    """

    storage_class: str = Field(
        ...,
        description="+label=Storage Class\n+usage=Storage class of the Volume where artifacts will be cached",
    )
    cache_size: conint(ge=1, le=1000) = Field(
        200,
        description="+label=Cache Size (GB)\n+usage=Size of the Volume (in GB) where artifacts will be cached. Should be greater than twice the size of artifacts getting cached",
    )


class AsyncProcessorSidecar(BaseModel):
    destination_url: str = Field(
        ...,
        description="+label=Destination URL\n+usage=URL for the processor to invoke",
    )
    request_timeout: conint(ge=1) = Field(
        10,
        description="+label=Request Timeout Seconds\n+usage=Timeout for the invoke request in seconds",
    )
    sidecar_image: Optional[str] = Field(
        None,
        description="+label=Sidecar Image\n+usage=Image for the processor sidecar (This field will be deprecated in the future)",
    )


class BaseAutoscaling(BaseModel):
    min_replicas: conint(ge=0) = Field(
        1,
        description="+label=Minimum replicas\n+usage=Minimum number of replicas to keep available\n+sort=1",
    )
    max_replicas: conint(ge=1, le=500) = Field(
        ...,
        description="+label=Maximum replicas\n+usage=Maximum number of replicas allowed for the component.\n+sort=2",
    )
    polling_interval: conint(ge=0) = Field(
        30,
        description="+label=Polling Interval\n+usage=This is the interval to check each trigger on.",
    )
    cooldown_period: conint(ge=0) = Field(
        300,
        description="+label=Cooldown Period\n+usage=The period to wait after the last trigger reported active before scaling the resource back to 0.",
    )


class BasicAuthCreds(BaseModel):
    """
    +label=Username and password for service auth
    """

    type: constr(regex=r"^basic_auth$") = Field(..., description="+value=basic_auth")
    username: constr(regex=r"^[a-z0-9-@\.]{1,64}$") = Field(
        ...,
        description="+label=Username for service auth\n+message=Upto 64 lower case alphanumeric character long\n+sort=1",
    )
    password: constr(regex=r"^[a-zA-Z0-9\.!@#$%^&*()_+=\-]{1,64}$") = Field(
        ...,
        description="+label=Password for service auth\n+message=Password should not be more than 64 characters\n+sort=2",
    )


class BlueGreen(BaseModel):
    """
    +docs=This strategy brings up the new release completely before switching the complete load to the new release.
    This minimizes the time that two versions are serving traffic at the same time.
    +label=Blue Green strategy
    """

    type: constr(regex=r"^blue_green$") = Field(..., description="+value=blue_green")
    enable_auto_promotion: bool = Field(
        False,
        description="+docs=Promote the new release to handle the complete traffic. A manual promotion would be needed if this is disabled\n+label=Auto-promotion",
    )
    auto_promotion_seconds: conint(ge=0) = Field(
        30,
        description="+docs=Promote the new release to handle the complete traffic after waiting for these many seconds\n+label=Auto-promotion seconds",
    )


class CPUUtilizationMetric(BaseModel):
    type: constr(regex=r"^cpu_utilization$") = Field(
        ..., description="+value=cpu_utilization"
    )
    value: conint(lt=100, gt=0) = Field(
        ...,
        description="+label=CPU utilization %\n+usage=Percentage of cpu request averaged over all replicas which the autoscaler should try to maintain",
    )


class CanaryStep(BaseModel):
    weight_percentage: conint(ge=0, le=100) = Field(
        ...,
        description="+docs=Percentage of total traffic to be shifted to the canary release.\nThe rest will continue to go to the existing deployment\n+label=Canary weight percentage\n+unit=%\n+placeholder=Weight",
    )
    pause_duration: conint(ge=0) = Field(
        30,
        description="+docs=Duration for which to pause the release. The release process will wait for these seconds before proceeding to the next step.\nIf this is not set, the step will pause indefinitely on this step\n+label=Pause duration\n+unit=seconds\n+placeholder=Duration",
    )


class CodeserverImage(BaseModel):
    """
    +usage=Codeserver with persistent environment (Python 3.11.6)
    """

    type: constr(regex=r"^codeserver$") = Field(..., description="+value=codeserver")
    enable_sudo: bool = Field(
        True,
        description="+label=Enable root access to the container\n+usage=Changes made to the root directory `/` will not be persisted across notebook restarts",
    )
    apt_packages: Optional[List[str]] = Field(
        None,
        description='+label=List of Debian packages to install.\n+usage=Debian packages to install via `apt get`.\nIn Python/YAML E.g. ["git", "ffmpeg", "htop"]\n+placeholder=Enter a debian package name E.g. ffmpeg',
    )
    docker_registry: Optional[str] = Field(
        None,
        description="+docs=FQN of the container registry. You can the FQN of your desired container registry (or add one)\nin the  Integrations page[Integrations](https://app.truefoundry.tech/integrations?tab=docker-registry) page\n+label=Docker Registry\n+usage=FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )


class CronMetric(BaseModel):
    type: constr(regex=r"^cron$") = Field(..., description="+value=cron")
    desired_replicas: Optional[conint(ge=1)] = Field(
        None,
        description="+label=Desired Replicas\n+usage=Desired number of replicas during the given interval. Default value is max_replicas.",
    )
    start: str = Field(
        ...,
        description="+label=Start Schedule\n+docs=Cron expression indicating the start of the cron schedule.\n+usage=Cron expression indicating the start of the cron schedule.\n```\n* * * * *\n| | | | |\n| | | | |___ day of week (0-6) (Sunday is 0)\n| | | |_____ month (1-12)\n| | |_______ day of month (1-31)\n| |_________ hour (0-23)\n|___________ minute (0-59)\n```",
    )
    end: str = Field(
        ...,
        description="+label=End Schedule\n+docs=Cron expression indicating the end of the cron schedule.\n+usage=Cron expression indicating the end of the cron schedule.\n```\n* * * * *\n| | | | |\n| | | | |___ day of week (0-6) (Sunday is 0)\n| | | |_____ month (1-12)\n| | |_______ day of month (1-31)\n| |_________ hour (0-23)\n|___________ minute (0-59)\n```",
    )
    timezone: str = Field(
        "UTC",
        description='+usage=Timezone against which the cron schedule will be calculated, e.g. "Asia/Tokyo". Default is machine\'s local time.\nhttps://docs.truefoundry.com/docs/list-of-supported-timezones',
    )


class CustomCodeserverImage(BaseModel):
    """
    +usage=User supplied docker image URI for vscode server
    """

    type: constr(regex=r"^customcodeserver$") = Field(
        ..., description="+value=customcodeserver"
    )
    image_uri: str = Field(
        ...,
        description="+label=Image URI\n+usage=The image URI. Specify the name of the image and the tag.\nIf the image is in Dockerhub, you can skip registry-url (for e.g. `tensorflow/tensorflow`).\nYou can use an image from a private registry using Advanced fields\n+placeholder=registry-url/account/image:version",
    )
    docker_registry: Optional[str] = Field(
        None,
        description="+docs=FQN of the container registry. You can use the FQN of your desired container registry (or add one)\nin the Integrations page[Integrations](https://app.truefoundry.tech/integrations?tab=docker-registry) page\n+label=Docker Registry\n+usage=FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )


class CustomNotebookImage(BaseModel):
    """
    +usage=User supplied docker image URI for jupyter notebook
    """

    type: constr(regex=r"^customnotebook$") = Field(
        ..., description="+value=customnotebook"
    )
    image_uri: str = Field(
        ...,
        description="+label=Image URI\n+usage=The image URI. Specify the name of the image and the tag.\nIf the image is in Dockerhub, you can skip registry-url (for e.g. `tensorflow/tensorflow`).\nYou can use an image from a private registry using Advanced fields\n+placeholder=registry-url/account/image:version",
    )
    docker_registry: Optional[str] = Field(
        None,
        description="+docs=FQN of the container registry. You can use the FQN of your desired container registry (or add one)\nin the  Integrations page[Integrations](https://app.truefoundry.tech/integrations?tab=docker-registry) page\n+label=Docker Registry\n+usage=FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )


class CustomSSHServerImage(BaseModel):
    """
    +usage=User supplied docker image URI for ssh server
    """

    type: constr(regex=r"^custom-ssh-server$") = Field(
        ..., description="+value=custom-ssh-server"
    )
    image_uri: str = Field(
        ...,
        description="+label=Image URI\n+usage=The image URI. Specify the name of the image and the tag.\nIf the image is in Dockerhub, you can skip registry-url (for e.g. `tensorflow/tensorflow`).\nYou can use an image from a private registry using Advanced fields\n+placeholder=registry-url/account/image:version",
    )
    docker_registry: Optional[str] = Field(
        None,
        description="+docs=FQN of the container registry. You can use the FQN of your desired container registry (or add one)\nin the  Integrations page[Integrations](https://app.truefoundry.tech/integrations?tab=docker-registry) page\n+label=Docker Registry\n+usage=FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )


class DockerFileBuild(BaseModel):
    """
    +docs=Describes that we are using a dockerfile to build our image
    +label=Docker File (I already have Docker File)
    +icon=fa-brands fa-docker:#0db7ed
    """

    type: constr(regex=r"^dockerfile$") = Field(..., description="+value=dockerfile")
    dockerfile_path: str = Field(
        "./Dockerfile",
        description="+label=Path to Dockerfile\n+usage=The file path of the Dockerfile relative to project root path.",
    )
    build_context_path: str = Field(
        "./",
        description="+label=Path to build context\n+usage=Build context path for the Dockerfile relative to project root path.",
    )
    command: Optional[Union[str, List[str]]] = Field(
        None,
        description="+label=Command Override\n+usage=Override the command to run when the container starts\nWhen deploying a Job, the command can be templatized by defining `params` and referencing them in command\nE.g. `python main.py --learning_rate {{learning_rate}}`",
    )
    build_args: Optional[Dict[str, str]] = Field(
        None,
        description="+label=Build Args\n+usage=Build arguments to pass to `docker build`.",
    )


class Endpoint(BaseModel):
    host: constr(
        regex=r"^((([a-zA-Z0-9\-]{1,63}\.)([a-zA-Z0-9\-]{1,63}\.)*([A-Za-z]{1,63}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))$"
    ) = Field(
        ...,
        description="+usage=Host e.g. ai.example.com, app.truefoundry.com\n+message=Upto 253 characters, each part of host should be at most 63 characters long, can contain alphabets, digits and hypen, must begin and end with an alphanumeric characters. Parts must be separated by periods (.)",
    )
    path: Optional[
        constr(regex=r"^(/([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-_\.]*[a-zA-Z0-9]))*/$")
    ] = Field(
        None,
        description="+usage=Path e.g. /v1/api/ml/, /v2/docs/\n+message=Should begin and end with a forward slash (/). Each part can can contain alphabets, digits and hypen, must begin and end with an alphanumeric characters. Parts should be separated by forward slashes (/)",
    )


class GitSource(BaseModel):
    """
    +docs=Describes that we are using code stored in a git repository to build our image
    +label=Git Source
    +icon=fa-solid fa-code-branch:black
    +sort=300
    """

    type: constr(regex=r"^git$") = Field(..., description="+value=git")
    repo_url: constr(
        regex=r"^(http(s?)://)(github\.com|(.+@)*bitbucket\.org|gitlab\.com).*$"
    ) = Field(
        ...,
        description="+label=Repo URL\n+usage=The repository URL.\n+sort=1\n+message=Needs to be a valid Github, Bitbucket or Gitlab link",
    )
    ref: str = Field(
        ..., description="+label=Commit SHA\n+usage=The commit SHA.\n+sort=2"
    )
    branch_name: Optional[str] = Field(
        None,
        description="+label=Branch Name\n+usage=Selecting branch will select latest commit SHA of the branch.\n+sort=3",
    )


class HelmRepo(BaseModel):
    type: constr(regex=r"^helm-repo$") = Field(..., description="+value=helm-repo")
    repo_url: constr(
        regex=r"^(((https?|wss):\/\/)?(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*))$"
    ) = Field(
        ...,
        description="+label=Helm repository URL\n+sort=1\n+message=Needs to be a valid URL.",
    )
    chart: str = Field(
        ..., description="+label=Chart name\n+sort=2\n+usage=The helm chart name"
    )
    version: str = Field(
        ..., description="+label=Version\n+sort=3\n+usage=Helm chart version"
    )


class HttpProbe(BaseModel):
    """
    +docs=Describes the Instructions for assessing container health by executing an HTTP GET request.
    To learn more you can go [here](https://docs.truefoundry.com/docs/add-health-checks-to-deployments)
    +label=Instructions for assessing container health by executing an HTTP GET request.
    """

    type: constr(regex=r"^http$") = Field(..., description="+sort=1\n+value=http")
    path: str = Field(
        ...,
        description="+usage=The endpoint, relative to the port, to which the HTTP GET request should be directed.\n+sort=2",
    )
    port: conint(ge=0, le=65535) = Field(
        ...,
        description="+usage=The TCP socket within the container to which the HTTP GET request should be directed.\n+sort=3",
    )
    host: Optional[str] = Field(
        None,
        description="+sort=4\n+usage=Host name to connect to, defaults to the pod IP",
    )
    scheme: str = Field(
        "HTTP", description="+sort=5\n+usage=Scheme to use for connecting to the host"
    )


class HuggingfaceArtifactSource(BaseModel):
    """
    +docs=Input for Artifact from Huggingface Model Hub
    +label=Huggingface Model Source
    """

    type: constr(regex=r"^huggingface-hub$") = Field(
        ..., description="+value=huggingface-hub"
    )
    model_id: str = Field(
        ...,
        description="+label=Model ID\n+usage=Model ID of the artifact to be downloaded",
    )
    revision: str = Field(
        ...,
        description="+label=Revision\n+usage=Revision of the artifact to be downloaded",
    )
    ignore_patterns: List[str] = Field(
        ["*.h5", "*.ot", "*.tflite", "*.msgpack"],
        description="+label=Ignore Patterns\n+usage=List of patterns to ignore while downloading the artifact",
    )
    download_path_env_variable: str = Field(
        ...,
        description="+label=Download Path Environment Variable\n+usage=Environment variable which will contain the download path of the artifact",
    )


class Image(BaseModel):
    """
    +docs=Describes that we are using a pre-built image stored in a Docker Image registry
    +label=Docker Image (Deploy an existing image)
    +icon=fa-brands fa-docker:#0db7ed
    """

    type: constr(regex=r"^image$") = Field(..., description="+value=image")
    image_uri: constr(regex=r"^\S*$") = Field(
        ...,
        description="+label=Image URI\n+usage=The image URI. Specify the name of the image and the tag.\nIf the image is in Dockerhub, you can skip registry-url (for e.g. `tensorflow/tensorflow`).\nYou can use an image from a private registry using Advanced fields\n+placeholder=registry-url/account/image:version (e.g. docker.io/tensorflow/tensorflow)",
    )
    docker_registry: Optional[str] = Field(
        None,
        description="+docs=FQN of the container registry. You can the FQN of your desired container registry (or add one)\nin the  Integrations page[Integrations](https://app.truefoundry.tech/integrations?tab=docker-registry) page\n+label=Docker Registry\n+usage=FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )
    command: Optional[Union[str, List[str]]] = Field(
        None,
        description="+label=Command Override\n+usage=Override the command to run when container starts.\nWhen deploying a Job, the command can be templatized by defining `params` and referencing them in command\nE.g. `python main.py --learning_rate {{learning_rate}}`",
    )


class KafkaMetricConfig(BaseModel):
    type: constr(regex=r"^kafka$") = Field(..., description="+value=kafka")
    lag_threshold: PositiveInt = Field(
        ...,
        description="+label=Lag Threshold\n+usage=Upper limit of the number of backlog messages the auto-scaler will try to maintain per replica. If you set this number to 10 and have 30 messages in the stream and one replica, the auto-scaler will scale the number of replicas to 3.",
    )


class KafkaSASLAuth(BaseModel):
    username: str = Field(
        ...,
        description="+label=Username\n+usage=Username for SASL authentication\n+sort=1",
    )
    password: str = Field(
        ...,
        description="+label=Password\n+usage=Password for SASL authentication\n+sort=2",
    )


class Kustomize(BaseModel):
    patch: Optional[Dict[str, Any]] = Field(
        None,
        description="+label=Patch\n+usage=Content of kustomization.yaml to perform kustomize operation. Please do not include the `resources` section. It is filled in automatically",
    )
    additions: Optional[List[Dict[str, Any]]] = Field(
        None,
        description="+label=Additional Manifests\n+usage=Additional kubernetes manifests to be included in the application",
    )


class LocalSource(BaseModel):
    """
    +docs=Describes that we are using code stored in a local developement environment to build our image
    +label=Local
    +icon=fa-folder:black
    +sort=100
    """

    type: constr(regex=r"^local$") = Field(..., description="+value=local")
    project_root_path: str = Field("./", description="+usage=Local project root path.")
    local_build: bool = Field(True, description="run docker build locally")


class Manual(BaseModel):
    """
    +docs=Describes that we are going to manually trigger our job.
    +label=Manual
    +usage=Trigger the job manually. [Docs](https://docs.truefoundry.com/docs/more-configurations)
    """

    type: constr(regex=r"^manual$") = Field(..., description="+value=manual")


class NATSMetricConfig(BaseModel):
    type: constr(regex=r"^nats$") = Field(..., description="+value=nats")
    lag_threshold: PositiveInt = Field(
        ...,
        description="+label=Lag Threshold\n+usage=Upper limit of the number of backlog messages the auto-scaler will try to maintain per replica. If you set this number to 10 and have 30 messages in the stream and one replica, the auto-scaler will scale the number of replicas to 3.",
    )


class NATSUserPasswordAuth(BaseModel):
    """
    +docs=NATS User Password Authentication
    +label=NATS User Password Authentication
    """

    account_name: str = Field(
        "$G",
        description="+label=Account Name\n+usage=Name of the NATS account\n+sort=1",
    )
    user: str = Field(
        ..., description="+label=User\n+usage=User for NATS authentication\n+sort=2"
    )
    password: str = Field(
        ...,
        description="+label=Password\n+usage=Password for NATS authentication\n+sort=3",
    )


class CapacityType(str, Enum):
    """
    +label=Capacity Type
    +usage=Configure what type of nodes to run the app. By default no placement logic is applied.
    "spot_fallback_on_demand" will try to place the application on spot nodes but will fallback to on-demand when spot nodes are not available.
    "spot" will strictly place the application on spot nodes.
    "on_demand" will strictly place the application on on-demand nodes.
    """

    spot_fallback_on_demand = "spot_fallback_on_demand"
    spot = "spot"
    on_demand = "on_demand"


class NodeSelector(BaseModel):
    """
    +label=Node selector
    +usage=Constraints to select a Node - Specific GPU / Instance Families, On-Demand/Spot.
    """

    type: constr(regex=r"^node_selector$") = Field(
        ..., description="+value=node_selector"
    )
    gpu_type: Optional[str] = Field(
        None,
        description="+label=GPU Type\n+usage=Name of the Nvidia GPU. One of [P4, P100, V100, T4, A10G, A100_40GB, A100_80GB]\nOne instance of the card contains the following amount of memory -\nP4: 8 GB, P100: 16 GB, V100: 16 GB, T4: 16 GB, A10G: 24 GB, A100_40GB: 40GB, A100_80GB: 80 GB",
    )
    instance_families: Optional[List[str]] = Field(
        None,
        description="+label=Instance family\n+usage=Instance family of the underlying machine to use. Multiple instance families can be supplied.\nThe workload is guaranteed to be scheduled on one of them.",
    )
    capacity_type: Optional[CapacityType] = Field(
        None,
        description='+label=Capacity Type\n+usage=Configure what type of nodes to run the app. By default no placement logic is applied.\n"spot_fallback_on_demand" will try to place the application on spot nodes but will fallback to on-demand when spot nodes are not available.\n"spot" will strictly place the application on spot nodes.\n"on_demand" will strictly place the application on on-demand nodes.',
    )


class NodepoolSelector(BaseModel):
    """
    +label=Nodepool selector
    +usage=Specify one or more nodepools to run your application on.
    """

    type: constr(regex=r"^nodepool_selector$") = Field(
        ..., description="+value=nodepool_selector"
    )
    nodepools: Optional[List[str]] = Field(
        None,
        description="+label=Nodepools\n+usage=Nodepools where you want to run your workload. Multiple nodepools can be selected.\n The workload is guaranteed to be scheduled on one of the nodepool",
    )


class NvidiaGPU(BaseModel):
    type: constr(regex=r"^nvidia_gpu$") = Field(..., description="+value=nvidia_gpu")
    name: Optional[str] = Field(
        None,
        description="+label=GPU Name\n+usage=Name of the Nvidia GPU. One of [P4, P100, V100, T4, A10G, A100_40GB, A100_80GB]\nThis field is required for Node Selector and can be ignored in Nodepool Selector.\nOne instance of the card contains the following amount of memory -\nP4: 8 GB, P100: 16 GB, V100: 16 GB, T4: 16 GB, A10G: 24 GB, A100_40GB: 40GB, A100_80GB: 80 GB",
    )
    count: conint(ge=1, le=16) = Field(
        ...,
        description="+label=GPU Count\n+usage=Count of GPUs to provide to the application\nNote the exact count and max count available for a given GPU type depends on cloud provider and cluster type.",
    )


class OCIRepo(BaseModel):
    """
    +label=OCIRepo
    """

    type: constr(regex=r"^oci-repo$") = Field(..., description="+value=oci-repo")
    oci_chart_url: constr(
        regex=r"^(((oci):\/\/)?(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*))$"
    ) = Field(..., description="+label=OCI chart URL\n+message=Need to be a valid URL.")
    version: str = Field(..., description="+label=Version\n+usage=Helm chart version")


class ParamType(str, Enum):
    string = "string"
    ml_repo = "ml_repo"


class Param(BaseModel):
    name: constr(regex=r"^[a-z][a-z0-9\-_]{0,30}[a-z0-9]$") = Field(
        ...,
        description="+usage=Name of the param\n+message=name can contain lower case alphabets, digits, underscore (_) and hypen (-). It can be 32 characters long, should start with an alphabet, and should end with either an alphabet or digit.",
    )
    description: Optional[constr(regex=r"^.{1,127}$")] = Field(
        None,
        description="+usage=Description of param\n+message=description cannot be longer than 127 characters",
    )
    default: Optional[constr(regex=r"^.{0,127}$")] = Field(
        None,
        description="+usage=Default value or placeholder\n+message=default value cannot be longer than 127 characters\n+label=Default value",
    )
    param_type: ParamType = "string"


class Protocol(str, Enum):
    """
    +usage=Protocol for the port.
    """

    TCP = "TCP"
    UDP = "UDP"


class AppProtocol(str, Enum):
    """
    +label=Application Protocol
    +usage=Application Protocol for the port.
    Select the application protocol used by your service. For most use cases, this should be `http`(HTTP/1.1).
    If you are running a gRPC server, select the `grpc` option.
    This is only applicable if `expose=true`.
    """

    http = "http"
    grpc = "grpc"
    tcp = "tcp"


class Port(BaseModel):
    """
    +docs=Describes the ports the service should be exposed to.
    """

    port: conint(ge=1, le=65535) = Field(
        80, description="+usage=Port number to expose."
    )
    protocol: Protocol = Field("TCP", description="+usage=Protocol for the port.")
    expose: bool = Field(True, description="+usage=Expose the port")
    app_protocol: Optional[AppProtocol] = Field(
        None,
        description="+label=Application Protocol\n+usage=Application Protocol for the port.\nSelect the application protocol used by your service. For most use cases, this should be `http`(HTTP/1.1).\nIf you are running a gRPC server, select the `grpc` option.\nThis is only applicable if `expose=true`.",
    )
    host: Optional[
        constr(
            regex=r"^((([a-zA-Z0-9\-]{1,63}\.)([a-zA-Z0-9\-]{1,63}\.)*([A-Za-z]{1,63}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))$"
        )
    ] = Field(
        None,
        description="+usage=Host e.g. ai.example.com, app.truefoundry.com\n+message=Upto 253 characters, each part of host should be at most 63 characters long, can contain alphabets, digits and hypen, must begin and end with an alphanumeric characters. Parts must be separated by periods (.)",
    )
    path: Optional[
        constr(regex=r"^(/([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-_\.]*[a-zA-Z0-9]))*/$")
    ] = Field(
        None,
        description="+usage=Path e.g. /v1/api/ml/, /v2/docs/\n+message=Should begin and end with a forward slash (/). Each part can can contain alphabets, digits and hypen, must begin and end with an alphanumeric characters. Parts should be separated by forward slashes (/)",
    )
    rewrite_path_to: Optional[
        constr(regex=r"^(/([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-_\.]*[a-zA-Z0-9]))*/$")
    ] = Field(
        None,
        description="+label=Rewrite Path to\n+usage=Rewrite the path prefix to a different path.\nIf `path` is `/v1/api` and `rewrite_path_to` is `/api`. The URI in the HTTP request `http://0.0.0.0:8080/v1/api/houses` will be rewritten to `http://0.0.0.0:8080/api/houses` before the request is forwarded your service.\nDefaults to `/`.\nThis is only applicable if `path` is given.\n+message=Should begin and end with a forward slash (/). Each part can can contain alphabets, digits and hypen, must begin and end with an alphanumeric characters. Parts should be separated by forward slashes (/)",
    )
    auth: Optional[BasicAuthCreds] = None


class PythonBuild(BaseModel):
    """
    +docs=Describes that we are using python to build a container image with a specific python version and pip packages installed.
    +label=Python Code (I don't have Dockerfile)
    +icon=fa-brands fa-python:#306998
    """

    type: constr(regex=r"^tfy-python-buildpack$") = Field(
        ..., description="+value=tfy-python-buildpack"
    )
    python_version: constr(regex=r"^\d+(\.\d+){1,2}([\-\.a-z0-9]+)?$") = Field(
        "3.9",
        description="+label=Python version\n+usage=Python version to run your application. Should be one of the tags listed on [Official Python Docker Page](https://hub.docker.com/_/python)\n+message=Please enter a valid Python version tag",
    )
    build_context_path: str = Field(
        "./",
        description="+label=Path to build context\n+usage=Build path relative to project root path.",
    )
    requirements_path: Optional[str] = Field(
        None,
        description="`Path to build context`\n+label=Path to requirements\n+usage=Path to `requirements.txt` relative to\n`Path to build context`",
    )
    pip_packages: Optional[List[str]] = Field(
        None,
        description='+label=Pip packages to install\n+usage=Define pip package requirements.\nIn Python/YAML E.g. ["fastapi>=0.90,<1.0", "uvicorn"]\n+placeholder=Enter a pip package name E.g. fastapi>=0.90,<1.0',
    )
    apt_packages: Optional[List[str]] = Field(
        None,
        description='+label=List of Debian packages to install.\n+usage=Debian packages to install via `apt get`.\nIn Python/YAML E.g. ["git", "ffmpeg", "htop"]\n+placeholder=Enter a debian package name E.g. ffmpeg',
    )
    command: Union[str, List[str]] = Field(
        ...,
        description="Command will be set as the Entrypoint of the generated\nimage.\n+label=Command\n+usage=Command to run when the container starts.\nCommand will be set as the Entrypoint of the generated image.\nWhen deploying a Job, the command can be templatized by defining `params` and referencing them in command\nE.g. `python main.py --learning_rate {{learning_rate}}`",
    )
    cuda_version: Optional[
        constr(
            regex=r"^((\d+\.\d+(\.\d+)?-cudnn\d+-(runtime|devel)-ubuntu\d+\.\d+)|11\.0-cudnn8|11\.1-cudnn8|11\.2-cudnn8|11\.3-cudnn8|11\.4-cudnn8|11\.5-cudnn8|11\.6-cudnn8|11\.7-cudnn8|11\.8-cudnn8|12\.0-cudnn8|12\.1-cudnn8|12\.2-cudnn8)$"
        )
    ] = Field(
        None,
        description="+label=CUDA Version\n+usage=Version of CUDA Toolkit and CUDNN to install in the image\nThese combinations are based off of publically available docker images on docker hub\nYou can also specify a valid tag of the form {cuda_version_number}-cudnn{cudnn_version_number}-{runtime|devel}-ubuntu{ubuntu_version}\nRefer https://hub.docker.com/r/nvidia/cuda/tags for valid set of values\nNote: We use deadsnakes ubuntu ppa to add Python that currently supports only Ubuntu 18.04, 20.04 and 22.04",
    )


class RPSMetric(BaseModel):
    type: constr(regex=r"^rps$") = Field(..., description="+value=rps")
    value: PositiveFloat = Field(
        ...,
        description="+label=Requests per second\n+usage=Average request per second averaged over all replicas that autoscaler should try to maintain",
    )


class RemoteSource(BaseModel):
    """
    +docs=Describes that we are using code stored in a remote respository to build our image
    +label=S3
    +icon=fa-brands fa-aws:black
    +sort=200
    """

    type: constr(regex=r"^remote$") = Field(..., description="+value=remote")
    remote_uri: str = Field(
        ..., description="+docs=Remote repository URI\n+label=Remote URI"
    )


class Resources(BaseModel):
    """
    +docs=Describes the resource constraints for the application so that it can be deployed accordingly on the cluster
    To learn more you can go [here](https://docs.truefoundry.com/docs/resources)
    +icon=fa-microchip
    +label=Resources
    +usage=Set resource constraints for the application. [Docs](https://docs.truefoundry.com/docs/resources)
    """

    cpu_request: confloat(ge=0.001, le=256.0) = Field(
        0.2,
        description="+label=CPU Request\n+sort=1\n+usage=Requested CPU which determines the minimum cost incurred. The CPU usage can exceed the requested\namount, but not the value specified in the limit. 1 CPU means 1 CPU core. Fractional CPU can be requested\nlike `0.5` or `0.05`",
    )
    cpu_limit: confloat(ge=0.001, le=256.0) = Field(
        0.5,
        description="+label=CPU Limit\n+usage=CPU limit beyond which the usage cannot be exceeded. 1 CPU means 1 CPU core. Fractional CPU can be requested\nlike `0.5`. CPU limit should be >= cpu request.\n+sort=2",
    )
    memory_request: conint(ge=1, le=2000000) = Field(
        200,
        description="+label=Memory Request\n+usage=Requested memory which determines the minimum cost incurred. The unit of memory is in megabytes(MB).\nSo 1 means 1 MB and 2000 means 2GB.\n+sort=3",
    )
    memory_limit: conint(ge=1, le=2000000) = Field(
        500,
        description="+label=Memory Limit\n+usage=Memory limit after which the application will be killed with an OOM error. The unit of memory is\nin megabytes(MB). So 1 means 1 MB and 2000 means 2GB. MemoryLimit should be greater than memory request.\n+sort=4",
    )
    ephemeral_storage_request: conint(ge=1, le=2000000) = Field(
        1000,
        description="+label=Storage Request\n+usage=Requested disk storage. The unit of memory is in megabytes(MB).\nThis is ephemeral storage and will be wiped out on pod restarts or eviction\n+sort=5",
    )
    ephemeral_storage_limit: conint(ge=1, le=2000000) = Field(
        2000,
        description="+label=Storage Limit\n+usage=Disk storage limit. The unit of memory is in megabytes(MB). Exceeding this limit will result in eviction.\nIt should be greater than the request. This is ephemeral storage and will be wiped out on pod restarts or eviction\n+sort=6",
    )
    gpu_count: conint(ge=0, le=16) = Field(
        0,
        description="+label=GPU Count\n+usage=Count of GPUs to provide to the application\nNote the exact count and max count available for a given GPU type depends on cloud provider and cluster type.",
    )
    shared_memory_size: Optional[conint(ge=64, le=32000)] = Field(
        None,
        description="+label=Shared Memory Size (MB)\n+usage=Define the shared memory requirements for your workload. Machine learning libraries like Pytorch can use Shared Memory\nfor inter-process communication. If you use this, we will mount a `tmpfs` backed volume at the `/dev/shm` directory.\nAny usage will also count against the workload's memory limit (`resources.memory_limit`) along with your workload's memory usage.\nIf the overall usage goes above `resources.memory_limit` the user process may get killed.\nShared Memory Size cannot be more than the defined Memory Limit for the workload.",
    )
    node: Optional[Union[NodeSelector, NodepoolSelector]] = Field(
        None,
        description="+label=Node\n+usage=This field determines how the underlying node resource is to be utilized",
    )
    devices: Optional[List[Union[NvidiaGPU, AWSInferentia]]] = Field(
        None,
        description="+label=Devices\n+usage=Define custom device or accelerator requirements for your workload. We currently support NVIDIA GPUs and AWS Inferentia Accelerators.",
    )


class Rolling(BaseModel):
    """
    +docs=This strategy updates the pods in a rolling fashion such that a subset of the
    total pods are replaced with new version at one time.
    A commonly used strategy can be to have maxUnavailablePercentage close to 0 so that there
    is no downtime and keep the maxSurgePercentage to around 25%. If you are anyways running
    a large number of pods, the service can often tolerate a few pods going down - so you
    max maxUnavailablePercentage = 10 and maxSurgePercentage=0. You can read about it more
    [here](https://spot.io/resources/kubernetes-autoscaling/5-kubernetes-deployment-strategies-roll-out-like-the-pros/)
    +label=Rolling update strategy
    """

    type: constr(regex=r"^rolling_update$") = Field(
        ..., description="+value=rolling_update"
    )
    max_unavailable_percentage: conint(ge=0, le=100) = Field(
        25,
        description="+label=Max unavailable(%)\n+usage=Percentage of total replicas that can be brought down at one time.\nFor a value of 25 when replicas are set to 12 this would mean minimum (25% of 12) = 3 pods might be unavailable during the deployment.\nSetting this to a higher value can help in speeding up the deployment process.",
    )
    max_surge_percentage: conint(ge=0, le=100) = Field(
        0,
        description="+label=Max Surge(%)\n+usage=Percentage of total replicas of updated image that can be brought up over the total replicas count.\nFor a value of 25 when replicas are set to 12 this would mean (12+(25% of 12) = 15) pods might be running at one time.\nSetting this to a higher value can help in speeding up the deployment process.",
    )


class SQSInputConfig(BaseModel):
    """
    +docs=Describes the configuration for the input SQS worker
    +label=SQS Input Config
    """

    type: constr(regex=r"^sqs$") = Field(..., description="+value=sqs")
    queue_url: str = Field(
        ...,
        description="+label=Queue URL\n+usage=AWS SQS Queue URL of Subscriber\n+sort=1",
    )
    region_name: str = Field(
        ..., description="+label=Region Name\n+usage=AWS Region Name\n+sort=2"
    )
    visibility_timeout: conint(le=43200, gt=0) = Field(
        ...,
        description="+label=Visibility Timeout (seconds)\n+usage=A period during which Amazon SQS prevents all consumers from receiving and processing the message. If one message takes 5 seconds to process, you can set this number to 7 or any number higher than 5. This will ensure that while the message is being processed, it will not be available to other replicas. For more information, see [here](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html)\n+sort=3",
    )
    wait_time_seconds: conint(ge=1, le=20) = Field(
        19,
        description="+label=Wait Time Seconds\n+usage=Wait timeout for long polling. For more information, see [here](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html)",
    )
    auth: AWSAccessKeyAuth


class SQSOutputConfig(BaseModel):
    """
    +docs=Describes the configuration for the output SQS worker
    +label=SQS Output Config
    """

    type: constr(regex=r"^sqs$") = Field(..., description="+value=sqs")
    queue_url: str = Field(
        ...,
        description="+label=Queue URL\n+usage=AWS SQS Queue URL of Publisher\n+sort=1",
    )
    region_name: str = Field(
        ..., description="+label=Region Name\n+usage=AWS Region Name\n+sort=2"
    )
    auth: AWSAccessKeyAuth


class SQSQueueMetricConfig(BaseModel):
    type: constr(regex=r"^sqs$") = Field(..., description="+value=sqs")
    queue_length: PositiveInt = Field(
        ...,
        description="+label=Queue length\n+usage=Upper limit of the number of backlog messages the auto-scaler will try to maintain per replica. If you set this number to 10 and have 30 messages in the queue and one replica, the auto-scaler will scale the number of replicas to 3.",
    )


class SSHServerImage(BaseModel):
    """
    +usage=Ssh Server with persistent environment (Python 3.11.6)
    """

    type: constr(regex=r"^ssh-server$") = Field(..., description="+value=ssh-server")
    apt_packages: Optional[List[str]] = Field(
        None,
        description='+label=List of Debian packages to install.\n+usage=Debian packages to install via `apt get`.\nIn Python/YAML E.g. ["git", "ffmpeg", "htop"]\n+placeholder=Enter a debian package name E.g. ffmpeg',
    )
    docker_registry: Optional[str] = Field(
        None,
        description="+docs=FQN of the container registry. You can the FQN of your desired container registry (or add one)\nin the  Integrations page[Integrations](https://app.truefoundry.tech/integrations?tab=docker-registry) page\n+label=Docker Registry\n+usage=FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )


class ConcurrencyPolicy(str, Enum):
    """
    +usage=Choose whether to allow this job to run while another instance of the job is running, or to replace the currently running instance. Allow
    will enable multiple instances of this job to run. Forbid will keep the current instance of the job running and stop a new instance from being run.
    Replace will terminate any currently running instance of the job and start a new one.
    """

    Forbid = "Forbid"
    Allow = "Allow"
    Replace = "Replace"


class Schedule(BaseModel):
    """
    +docs=Describes that we are going to schedule our job to run at a schedule, making our job a cron job.
    +label=Schedule
    +usage=Run the job on a schedule. [Docs](https://docs.truefoundry.com/docs/deploy-a-cron-job)
    """

    type: constr(regex=r"^scheduled$") = Field(..., description="+value=scheduled")
    schedule: str = Field(
        ...,
        description="+docs=Specify the schedule for this job to be run periodically in cron format. [Learn more](https://docs.truefoundry.com/docs/deploy-a-cron-job)\n+usage=Specify the schedule for this job to be run periodically in cron format.\n```\n* * * * *\n| | | | |\n| | | | |___ day of week (0-6) (Sunday is 0)\n| | | |_____ month (1-12)\n| | |_______ day of month (1-31)\n| |_________ hour (0-23)\n|___________ minute (0-59)\n```",
    )
    concurrency_policy: ConcurrencyPolicy = Field(
        "Forbid",
        description="+usage=Choose whether to allow this job to run while another instance of the job is running, or to replace the currently running instance. Allow\nwill enable multiple instances of this job to run. Forbid will keep the current instance of the job running and stop a new instance from being run.\nReplace will terminate any currently running instance of the job and start a new one.",
    )
    timezone: Optional[str] = Field(
        None,
        description='+usage=Timezone against which the cron schedule will be calculated, e.g. "Asia/Tokyo". Default is machine\'s local time.\nhttps://docs.truefoundry.com/docs/list-of-supported-timezones',
    )


class SecretMount(BaseModel):
    type: constr(regex=r"^secret$") = Field(..., description="+value=secret")
    mount_path: constr(regex=r"^\/(?:[^/\n]+\/*)*[^/\n]+(\.[^/\n]+)?$") = Field(
        ...,
        description="+label=File path\n+usage=Absolute file path where the file will be created.\n+message=Please enter a valid file path",
    )
    secret_fqn: constr(regex=r"^tfy-secret:\/\/.+:.+:.+$") = Field(
        ...,
        description="+label=Secret\n+usage=The Truefoundry secret whose value will be the file content.",
    )


class ServiceAutoscaling(BaseAutoscaling):
    metrics: Union[CPUUtilizationMetric, RPSMetric, CronMetric] = Field(
        ...,
        description="+label=Autoscaling metrics\n+usage=Metrics to use for the autoscaler\n+sort=4",
    )


class StringDataMount(BaseModel):
    type: constr(regex=r"^string$") = Field(..., description="+value=string")
    mount_path: constr(regex=r"^\/(?:[^/\n]+\/*)*[^/\n]+(\.[^/\n]+)?$") = Field(
        ...,
        description="+label=File Path\n+usage=Absolute file path where the file will be created.\n+message=Please enter a valid file path",
    )
    data: str = Field(..., description="+label=Data\n+usage=The file content.")


class TruefoundryArtifactSource(BaseModel):
    """
    +docs=Input for Artifact from Truefoundry Artifact Registry
    +label=Truefoundry Artifact Source
    """

    type: constr(regex=r"^truefoundry-artifact$") = Field(
        ..., description="+value=truefoundry-artifact"
    )
    artifact_version_fqn: str = Field(
        ...,
        description="+label=Artifact or Model Version FQN\n+usage=Artifact or Model Version FQN of the artifact to be downloaded",
    )
    download_path_env_variable: str = Field(
        ...,
        description="+label=Download Path Environment Variable\n+usage=Environment variable which will contain the download path of the artifact",
    )


class TruefoundryImageBase(BaseModel):
    """
    +usage=JupyterLab with persistent python environment (Python 3.11.6)
    """

    type: constr(regex=r"^truefoundrybase$") = Field(
        ..., description="+value=truefoundrybase"
    )
    enable_sudo: bool = Field(
        True,
        description="+label=Enable root access to the container\n+usage=Changes made to the root directory `/` will not be persisted across notebook restarts",
    )
    apt_packages: Optional[List[str]] = Field(
        None,
        description='+label=List of Debian packages to install.\n+usage=Debian packages to install via `apt get`.\nIn Python/YAML E.g. ["git", "ffmpeg", "htop"]\n+placeholder=Enter a debian package name E.g. ffmpeg',
    )
    docker_registry: Optional[str] = Field(
        None,
        description="+docs=FQN of the container registry. You can use the FQN of your desired container registry (or add one)\nin the  Integrations page[Integrations](https://app.truefoundry.tech/integrations?tab=docker-registry) page\n+label=Docker Registry\n+usage=FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )


class TruefoundryImageCuda1180(BaseModel):
    """
    +usage=JupyterLab with persistent python environment (Python 3.11.6, Cuda 11.8.0)
    """

    type: constr(regex=r"^truefoundrycuda1180$") = Field(
        ..., description="+value=truefoundrycuda1180"
    )
    apt_packages: Optional[List[str]] = Field(
        None,
        description='+label=List of Debian packages to install.\n+usage=Debian packages to install via `apt get`.\nIn Python/YAML E.g. ["git", "ffmpeg", "htop"]\n+placeholder=Enter a debian package name E.g. ffmpeg',
    )
    docker_registry: Optional[str] = Field(
        None,
        description="+docs=FQN of the container registry. You can use the FQN of your desired container registry (or add one)\nin the  Integrations page[Integrations](https://app.truefoundry.tech/integrations?tab=docker-registry) page\n+label=Docker Registry\n+usage=FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )


class TruefoundryImageCuda1211(BaseModel):
    """
    +usage=JupyterLab with persistent python environment (Python 3.11.6, Cuda 12.1.1)
    """

    type: constr(regex=r"^truefoundrycuda1211$") = Field(
        ..., description="+value=truefoundrycuda1211"
    )
    apt_packages: Optional[List[str]] = Field(
        None,
        description='+label=List of Debian packages to install.\n+usage=Debian packages to install via `apt get`.\nIn Python/YAML E.g. ["git", "ffmpeg", "htop"]\n+placeholder=Enter a debian package name E.g. ffmpeg',
    )
    docker_registry: Optional[str] = Field(
        None,
        description="+docs=FQN of the container registry. You can use the FQN of your desired container registry (or add one)\nin the  Integrations page[Integrations](https://app.truefoundry.tech/integrations?tab=docker-registry) page\n+label=Docker Registry\n+usage=FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )


class TruefoundryImageFull(BaseModel):
    """
    +usage=JupyterLab + Tensorflow 2.15.0 and Pytorch 2.1.1 with persistent environment (Python 3.11.6)
    """

    type: constr(regex=r"^truefoundryfull$") = Field(
        ..., description="+value=truefoundryfull"
    )
    enable_sudo: bool = Field(
        True,
        description="+label=Enable root access to the container\n+usage=Changes made to the root directory `/` will not be persisted across notebook restarts",
    )
    apt_packages: Optional[List[str]] = Field(
        None,
        description='+label=List of Debian packages to install.\n+usage=Debian packages to install via `apt get`.\nIn Python/YAML E.g. ["git", "ffmpeg", "htop"]\n+placeholder=Enter a debian package name E.g. ffmpeg',
    )
    docker_registry: Optional[str] = Field(
        None,
        description="+docs=FQN of the container registry. You can use the FQN of your desired container registry (or add one)\nin the  Integrations page[Integrations](https://app.truefoundry.tech/integrations?tab=docker-registry) page\n+label=Docker Registry\n+usage=FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )


class VolumeBrowser(BaseModel):
    """
    +label=Volume Browser
    """

    username: constr(regex=r"^[a-z][a-z0-9]{1,8}[a-z0-9]$") = Field(
        ...,
        description="+message=3 to 10 lower case characters long alphanumeric word, may contain - in between, cannot start with a number.\n+usage=Username for logging in the volume browser.\n+sort=1",
    )
    password_secret_fqn: constr(regex=r"^tfy-secret:\/\/.+:.+:.+$") = Field(
        ...,
        description="+label=Password Secret FQN\n+usage=TFY Secret containing the password for logging in the volume browser.\n+sort=2",
    )
    endpoint: Endpoint


class VolumeMount(BaseModel):
    type: constr(regex=r"^volume$") = Field(..., description="+value=volume")
    mount_path: constr(regex=r"^\/(?:[^/\n]+\/*)*[^/\n]+(\.[^/\n]+)?$") = Field(
        ...,
        description="+label=Volume mount path\n+usage=Absolute file path where the volume will be mounted.\n+message=Please enter a valid mount path",
    )
    volume_fqn: constr(regex=r"^tfy-volume:\/\/.+:.+:.+$") = Field(
        ...,
        description="+label=Volume\n+usage=The Truefoundry volume that needs to be mounted.",
    )


class ArtifactsDownload(BaseModel):
    """
    +docs=Describes the configuration for the artifacts cache
    +label=Artifacts Download
    """

    cache_volume: Optional[ArtifactsCacheVolume] = None
    artifacts: List[
        Union[TruefoundryArtifactSource, HuggingfaceArtifactSource]
    ] = Field(
        ..., description="+label=Artifacts\n+usage=List of artifacts to be cached"
    )


class AsyncServiceAutoscaling(BaseAutoscaling):
    metrics: Union[
        SQSQueueMetricConfig, NATSMetricConfig, KafkaMetricConfig, CronMetric
    ] = Field(
        ...,
        description="+label=Autoscaling metrics\n+usage=Metrics to use for the autoscaler\n+sort=4",
    )


class BaseWorkbenchInput(BaseModel):
    """
    +docs=Describes the configuration for the service
    """

    name: constr(regex=r"^[a-z][a-z0-9\-]{1,30}[a-z0-9]$") = Field(
        ...,
        description="+usage=Name of the workbench. This uniquely identifies this workbench in the workspace.\n> Name can only contain alphanumeric characters and '-' and can be atmost 25 characters long\n+sort=1\n+message=3 to 32 lower case characters long alphanumeric word, may contain - in between, cannot start with a number",
    )
    home_directory_size: conint(ge=5, le=64000) = Field(
        20,
        description="+label=Home Directory Size in GB (Persistent)\n+usage=Size of the home directory for the workbench (Persistent Storage)\n+sort=6",
    )
    resources: Optional[Resources] = None
    env: Optional[Dict[str, str]] = Field(
        None,
        description="+label=Environment Variables\n+usage=Configure environment variables to be set in the workbench pod(s)\n+sort=10110",
    )
    mounts: Optional[List[Union[SecretMount, StringDataMount, VolumeMount]]] = Field(
        None,
        description="+usage=Configure data to be mounted to workbench pod(s)\n+sort=10111",
    )
    service_account: Optional[str] = Field(
        None,
        description="+usage=Service account that this workload should use\n+sort=10113",
    )


class Build(BaseModel):
    """
    +docs=Describes how we build our code into a Docker image.
    +label=Source Code (Build and deploy source code)
    +icon=fa-code
    """

    type: constr(regex=r"^build$") = Field(..., description="+value=build")
    docker_registry: Optional[str] = Field(
        None,
        description="+docs=FQN of the container registry. You can the FQN of your desired container registry (or add one)\nin the  Integrations page[Integrations](https://app.truefoundry.tech/integrations?tab=docker-registry) page\n+label=Docker Registry\n+usage=FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )
    build_source: Union[RemoteSource, GitSource, LocalSource] = Field(
        ...,
        description="+docs=Source code location.\n+label=Fetch source code to build and deploy\n+icon=fa-code\n+sort=1",
    )
    build_spec: Union[DockerFileBuild, PythonBuild] = Field(
        ...,
        description="+docs=Instructions to build a container image out of the build source\n+label=Build using DockerFile or using Buildpack\n+icon=fa-wrench\n+sort=2",
    )


class Canary(BaseModel):
    """
    +docs=This strategy brings up the new release without bringing the older release down. Traffic is shifted from the older release to the newer release in a staged manner.
    This can help with verifying the health of the new release without shifting complete traffic.
    +label=Canary strategy
    """

    type: constr(regex=r"^canary$") = Field(..., description="+value=canary")
    steps: List[CanaryStep] = Field(
        ...,
        description="+docs=These steps would be executed in order to enable shifting of traffic slowly from stable to canary version\n+label=Steps",
    )


class Codeserver(BaseWorkbenchInput):
    """
    +docs=Describes the configuration for the code server
    """

    type: constr(regex=r"^codeserver$") = Field(..., description="+value=Code Server")
    image: Union[CodeserverImage, CustomCodeserverImage] = Field(
        ..., description="+usage=Pick a codeserver image to deploy\n+sort=2"
    )
    auth: Optional[BasicAuthCreds] = None


class CoreNATSOutputConfig(BaseModel):
    """
    +docs=Describes the configuration for the output Core NATS worker
    +label=Core NATS Output Config
    """

    type: constr(regex=r"^core-nats$") = Field(..., description="+value=core-nats")
    nats_url: str = Field(
        ..., description="+label=NATS URL\n+usage=Output NATS URL\n+sort=1"
    )
    root_subject: constr(regex=r"^[a-zA-Z0-9][a-zA-Z0-9\-.]+[a-zA-Z0-9]$") = Field(
        ...,
        description="+label=Root Subject\n+usage=Root subject of output NATS\n+message=Output NATS root subject should only contain alphanumeric letters, dashes(-), and periods(.)\n+sort=2",
    )
    auth: Optional[NATSUserPasswordAuth] = None


class HealthProbe(BaseModel):
    """
    +docs=Describes the configuration for the Health Probe's
    To learn more you can go [here](https://docs.truefoundry.com/docs/add-health-checks-to-deployments)
    +icon=fa-heart
    """

    config: HttpProbe
    initial_delay_seconds: conint(ge=0, le=36000) = Field(
        0,
        description="+usage=Number of seconds after the container is started before the first probe is initiated.",
    )
    period_seconds: conint(ge=1, le=36000) = Field(
        10, description="+usage=How often, in seconds, to execute the probe."
    )
    timeout_seconds: conint(ge=1, le=36000) = Field(
        1, description="+usage=Number of seconds after which the probe times out."
    )
    success_threshold: conint(ge=1, le=100) = Field(
        1,
        description="+usage=Minimum consecutive successes for the probe to be considered successful after having failed.",
    )
    failure_threshold: conint(ge=1, le=100) = Field(
        3,
        description="+usage=Number of consecutive failures required to determine the container is not alive (liveness probe) or not ready (readiness probe).",
    )


class Helm(BaseModel):
    type: constr(regex=r"^helm$") = Field(..., description="+value=helm")
    name: constr(regex=r"^[a-z][a-z0-9\-]{1,30}[a-z0-9]$") = Field(
        ...,
        description="+sort=1\n+message=3 to 32 lower case characters long alphanumeric word, may contain - in between, cannot start with a number\n+usage=Name of the Helm deployment. This will be set as the release name of the chart you are deploying.",
    )
    labels: Optional[Dict[str, str]] = Field(
        None, description="+label=Labels\n+usage=Add labels to base argo app"
    )
    source: Union[HelmRepo, OCIRepo] = Field(
        ..., description="+label=Source helm repository\n+sort=2"
    )
    values: Optional[Dict[str, Any]] = Field(
        None, description="+label=Values\n+usage=Values file as block file"
    )
    kustomize: Optional[Kustomize] = None


class Job(BaseModel):
    """
    +docs=Describes the configuration for the job
    """

    type: constr(regex=r"^job$") = Field(..., description="+value=job")
    name: constr(regex=r"^[a-z][a-z0-9\-]{1,30}[a-z0-9]$") = Field(
        ...,
        description="+usage=Name of the job\n+sort=1\n+message=3 to 32 lower case characters long alphanumeric word, may contain - in between, cannot start with a number",
    )
    image: Union[Build, Image] = Field(
        ...,
        description="+docs=Specify whether you want to deploy a Docker image or build and deploy from source code\n+label=Deploy a Docker image or build and deploy from source code\n+icon=fa-solid fa-cloud-arrow-up:#21B6A8\n+sort=200",
    )
    trigger: Union[Manual, Schedule] = Field(
        {"type": "manual"}, description="+docs=Specify the trigger\n+sort=300"
    )
    trigger_on_deploy: bool = Field(
        False,
        description="+docs=Trigger on deploy\n+sort=350\n+usage=Trigger the job after deploy immediately",
    )
    params: Optional[List[Param]] = Field(
        None,
        description="+label=Params for input\n+usage=Configure params and pass it to create different job runs\n+sort=400",
    )
    env: Optional[Dict[str, str]] = Field(
        None,
        description="+label=Environment Variables\n+usage=Configure environment variables to be injected in the service. [Docs](https://docs.truefoundry.com/docs/env-variables)\n+icon=fa-globe\n+sort=500",
    )
    resources: Optional[Resources] = None
    retries: conint(ge=0, le=10) = Field(
        0,
        description="+label=Retries\n+usage=Specify the maximum number of attempts to retry a job before it is marked as failed.\n+icon=fa-repeat\n+sort=700",
    )
    timeout: Optional[conint(le=432000, gt=0)] = Field(
        None,
        description="+label=Timeout\n+usage=Job timeout in seconds.\n+icon=fa-clock\n+sort=800",
    )
    concurrency_limit: Optional[PositiveInt] = Field(
        None,
        description="+label=Concurrency Limit\n+usage=Number of runs that can run concurrently\n+icon=fa-copy\n+sort=900",
    )
    service_account: Optional[str] = Field(
        None,
        description="+usage=Service account that this workload should use\n+sort=1000",
    )
    mounts: Optional[List[Union[SecretMount, StringDataMount, VolumeMount]]] = Field(
        None, description="+usage=Configure data to be mounted to job pod(s)"
    )
    labels: Optional[Dict[str, str]] = Field(
        None, description="+label=Labels\n+usage=Add labels to service metadata"
    )


class KafkaInputConfig(BaseModel):
    """
    +docs=Describes the configuration for the input Kafka worker
    +label=Kafka Input Config
    """

    type: constr(regex=r"^kafka$") = Field(..., description="+value=kafka")
    bootstrap_servers: str = Field(
        ...,
        description="+label=Bootstrap servers\n+usage='Kafka Bootstrap servers - Comma separated list of Kafka brokers \"hostname:port\" to connect to for bootstrap'\n+sort=1",
    )
    topic_name: str = Field(
        ...,
        description="+label=Topic Name\n+usage=Kafka topic to subscribe to\n+sort=2",
    )
    consumer_group: str = Field(
        ...,
        description="+label=Consumer Group Name\n+usage=The name of the consumer group to join for dynamic partition assignment\n+sort=3",
    )
    tls: bool = Field(
        True, description="+label=TLS\n+usage=TLS configuration for SASL authentication"
    )
    wait_time_seconds: conint(ge=1, le=300) = Field(
        10,
        description="+label=Wait Time Seconds\n+usage=Wait timeout for long polling.",
    )
    auth: Optional[KafkaSASLAuth] = None


class KafkaOutputConfig(BaseModel):
    """
    +docs=Describes the configuration for the output Kafka worker
    +label=Kafka Output Config
    """

    type: constr(regex=r"^kafka$") = Field(..., description="+value=kafka")
    bootstrap_servers: str = Field(
        ...,
        description="+label=Bootstrap servers\n+usage='Kafka Bootstrap servers - Comma separated list of Kafka brokers \"hostname:port\" to connect to for bootstrap'\n+sort=1",
    )
    topic_name: str = Field(
        ..., description="+label=Topic Name\n+usage=Kafka topic to publish to\n+sort=2"
    )
    tls: bool = Field(
        True, description="+label=TLS\n+usage=TLS configuration for SASL authentication"
    )
    auth: Optional[KafkaSASLAuth] = None


class NATSInputConfig(BaseModel):
    """
    +docs=Describes the configuration for the input NATS worker
    +label=NATS Input Config
    """

    type: constr(regex=r"^nats$") = Field(..., description="+value=nats")
    nats_url: str = Field(
        ..., description="+label=NATS URL\n+usage=Input NATS URL\n+sort=1"
    )
    stream_name: str = Field(
        ..., description="+label=Stream Name\n+usage=Name of the NATS stream\n+sort=2"
    )
    root_subject: constr(regex=r"^[a-zA-Z0-9][a-zA-Z0-9\-.]+[a-zA-Z0-9]$") = Field(
        ...,
        description="+label=Root Subject\n+usage=Root subject of input NATS\n+message=Input NATS root subject should only contain alphanumeric letters, dashes(-), and periods(.)\n+sort=3",
    )
    consumer_name: constr(regex=r"^[a-zA-Z0-9][a-zA-Z0-9\-_]+[a-zA-Z0-9]$") = Field(
        ...,
        description="+label=Consumer Name\n+usage=Consumer name of input NATS\n+message=Consumer name should only contain alphanumeric letters, dashes(-), and underscores(_)\n+sort=4",
    )
    wait_time_seconds: conint(ge=1, le=20) = Field(
        19,
        description="+label=Wait Time Seconds\n+usage=Wait timeout for long polling.\n+sort=5",
    )
    nats_metrics_url: Optional[constr(regex=r"^(http(s?)://).*$")] = Field(
        None,
        description="+label=NATS metrics URL\n+usage=URL for the NATS metrics endpoint. It is compulsory if you want to use NATS autoscaling.\n+message=NATS Metrics URL should be a valid HTTP/HTTPS URL",
    )
    auth: Optional[NATSUserPasswordAuth] = None


class NATSOutputConfig(BaseModel):
    """
    +docs=Describes the configuration for the output NATS worker
    +label=NATS Output Config
    """

    type: constr(regex=r"^nats$") = Field(..., description="+value=nats")
    nats_url: str = Field(
        ..., description="+label=NATS URL\n+usage=Output NATS URL\n+sort=1"
    )
    root_subject: constr(regex=r"^[a-zA-Z0-9][a-zA-Z0-9\-.]+[a-zA-Z0-9]$") = Field(
        ...,
        description="+label=Root Subject\n+usage=Root subject of output NATS\n+message=Output NATS root subject should only contain alphanumeric letters, dashes(-), and periods(.)\n+sort=2",
    )
    auth: Optional[NATSUserPasswordAuth] = None


class Notebook(BaseWorkbenchInput):
    """
    +docs=Describes the configuration for the service
    """

    type: constr(regex=r"^notebook$") = Field(..., description="+value=notebook")
    image: Union[
        TruefoundryImageBase,
        TruefoundryImageFull,
        CustomNotebookImage,
        TruefoundryImageCuda1180,
        TruefoundryImageCuda1211,
    ] = Field(
        ...,
        description="+usage=Changes made to the root directory `/` will not be persisted across notebook restarts\n+sort=2",
    )
    auth: Optional[BasicAuthCreds] = None
    cull_timeout: conint(ge=5) = Field(
        30,
        description="+label=Stop after (minutes of inactivity)\n+usage=Stop the notebook instance after this much time in minutes of inactivity.\nThe notebook instance will be stopped even if the notebook is open in your browser, but nothing is running on the notebook.\n+sort=5",
    )


class SSHServer(BaseWorkbenchInput):
    """
    +docs=Describes the configuration for the ssh server
    """

    type: constr(regex=r"^ssh-server$") = Field(..., description="+value=SSH Server")
    image: Union[SSHServerImage, CustomSSHServerImage] = Field(
        ..., description="+usage=Pick a ssh server image to deploy\n+sort=2"
    )
    ssh_public_key: str = Field(
        ...,
        description="+label: SSH Public Key\n+usage=Add Your SSH Public Key, this will be used to authenticate you to the SSH Server.\n+sort=4",
    )


class Volume(BaseModel):
    type: constr(regex=r"^volume$") = Field(..., description="+value=volume")
    name: constr(regex=r"^[a-z][a-z0-9\-]{1,30}[a-z0-9]$") = Field(
        ...,
        description="+sort=1\n+message=3 to 32 lower case characters long alphanumeric word, may contain - in between, cannot start with a number\n+usage=Name of the Volume. This will be set as the volume name.",
    )
    storage_class: str = Field(..., description="+label=Storage Class\n+sort=2")
    size: conint(ge=1, le=64000) = Field(
        ..., description="+sort=3\n+label=Size\n+unit=Gi\n+usage=Size of volume in Gi"
    )
    volume_browser: Optional[VolumeBrowser] = None


class WorkerConfig(BaseModel):
    input_config: Union[SQSInputConfig, NATSInputConfig, KafkaInputConfig] = Field(
        ..., description="+label=Input Config\n+usage=Input Config\n+sort=1"
    )
    output_config: Optional[
        Union[
            SQSOutputConfig, NATSOutputConfig, CoreNATSOutputConfig, KafkaOutputConfig
        ]
    ] = Field(None, description="+label=Output Config\n+usage=Output Config\n+sort=2")
    num_concurrent_workers: conint(ge=1, le=10) = Field(
        1,
        description="+label=Number of Concurrent Workers\n+usage=Number of concurrent workers to spawn for the processor\n+sort=3",
    )


class BaseService(BaseModel):
    name: constr(regex=r"^[a-z][a-z0-9\-]{1,30}[a-z0-9]$") = Field(
        ...,
        description="+usage=Name of the service. This uniquely identifies this service in the workspace.\n> Name can only contain alphanumeric characters and '-' and can be atmost 25 characters long\n+sort=1\n+message=3 to 32 lower case characters long alphanumeric word, may contain - in between, cannot start with a number",
    )
    image: Union[Build, Image] = Field(
        ...,
        description="+docs=Specify whether you want to deploy a Docker image or build and deploy from source code\n+label=Deploy a Docker image or build and deploy from source code\n+icon=fa-solid fa-cloud-arrow-up:#21B6A8\n+sort=2",
    )
    artifacts_download: Optional[ArtifactsDownload] = None
    resources: Optional[Resources] = None
    env: Optional[Dict[str, str]] = Field(
        None,
        description="+label=Environment Variables\n+usage=Configure environment variables to be injected in the service. [Docs](https://docs.truefoundry.com/docs/env-variables)\n+icon=fa-globe\n+sort=6",
    )
    ports: List[Port] = Field(
        ...,
        description="+docs=Specify the ports you want the service to be exposed to\n+label=Ports (Ports to route customer traffic to)\n+icon=fa-plug\n+sort=4",
    )
    service_account: Optional[str] = Field(
        None, description="+usage=Service account that this workload should use"
    )
    mounts: Optional[List[Union[SecretMount, StringDataMount, VolumeMount]]] = Field(
        None,
        description="+usage=Configure data to be mounted to service pod(s)\n+sort=10011",
    )
    labels: Optional[Dict[str, str]] = Field(
        None, description="+label=Labels\n+usage=Add labels to service metadata"
    )
    kustomize: Optional[Kustomize] = None
    liveness_probe: Optional[HealthProbe] = None
    readiness_probe: Optional[HealthProbe] = None


class Service(BaseService):
    """
    +docs=Describes the configuration for the service
    """

    type: constr(regex=r"^service$") = Field(..., description="+value=service")
    replicas: Union[confloat(ge=0.0, le=500.0), ServiceAutoscaling] = Field(
        1,
        description="+label=Replicas\n+usage=Replicas of service you want to run\n+icon=fa-clone\n+sort=4",
    )
    allow_interception: bool = Field(
        False,
        description="+label=Allow intercepts\n+usage=Whether to allow intercepts to be applied for this service.\nThis would inject an additional sidecar in each pod of the service. Not recommended on production",
    )
    rollout_strategy: Optional[Union[Rolling, Canary, BlueGreen]] = Field(
        None,
        description="+label=Rollout strategy\n+usage=Strategy to dictate how a rollout should happen when a new release for this service is made",
    )


class AsyncService(BaseService):
    """
    +docs=Describes the configuration for the async-service
    """

    type: constr(regex=r"^async-service$") = Field(
        ..., description="+value=async-service"
    )
    replicas: Union[confloat(ge=0.0, le=500.0), AsyncServiceAutoscaling] = Field(
        1,
        description="+label=Replicas\n+usage=Replicas of service you want to run\n+icon=fa-clone",
    )
    rollout_strategy: Optional[Rolling] = None
    worker_config: WorkerConfig
    sidecar: Optional[AsyncProcessorSidecar] = None


class Application(BaseModel):
    __root__: Union[
        Service, AsyncService, Job, Notebook, Codeserver, SSHServer, Helm, Volume
    ]
