# generated by datamodel-codegen:
#   filename:  application.json
#   timestamp: 2026-03-17T06:34:23+00:00

from __future__ import annotations

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

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


class AMQPInputConfig(BaseModel):
    """
    Describes the configuration for the input AMQP worker
    """

    type: Literal["amqp"] = Field(..., description="")
    url: constr(
        regex=r"^(amqp|amqps?)://(?:[^:@]+(?::[^:@]+)?@)?([^/?]+)(?:/([^?]+))?/?([^?]+)?(?:\?(.*))?$"
    ) = Field(..., description="AMQP Queue URL of Subscriber")
    queue_name: str = Field(..., description="AMQP Queue Name")
    wait_time_seconds: conint(ge=1) = Field(
        5, description="Wait timeout for long polling."
    )


class AMQPMetricConfig(BaseModel):
    type: Literal["amqp"] = Field(..., description="")
    queue_length: conint(ge=1) = Field(
        ...,
        description="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 AMQPOutputConfig(BaseModel):
    """
    Describes the configuration for the output AMQP worker
    """

    type: Literal["amqp"] = Field(..., description="")
    url: constr(
        regex=r"^(amqp|amqps?)://(?:[^:@]+(?::[^:@]+)?@)?([^/?]+)(?:/([^?]+))?/?([^?]+)?(?:\?(.*))?$"
    ) = Field(..., description="AMQP Queue URL of Publisher")
    routing_key: str = Field(..., description="AMQP Routing Key to publish to.")
    exchange_name: Optional[str] = Field(None, description="AMQP Exchange Name")


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


class AWSInferentia(BaseModel):
    type: Literal["aws_inferentia"] = Field(..., description="")
    name: Optional[str] = Field(
        None,
        description="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="Count of Inferentia accelerator chips to provide to the application",
    )


class ArtifactsCacheVolume(BaseModel):
    """
    Describes the volume that will be used to cache the models
    """

    storage_class: str = Field(
        ..., description="Storage class of the Volume where artifacts will be cached"
    )
    cache_size: conint(ge=1, le=1000) = Field(
        200,
        description="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="URL for the processor to invoke")
    request_timeout: conint(ge=1) = Field(
        10, description="Timeout for the invoke request in seconds"
    )
    sidecar_image: Optional[str] = Field(
        None,
        description="Image for the processor sidecar (This field will be deprecated in the future)",
    )


class Autoshutdown(BaseModel):
    wait_time: conint(ge=0, le=604800) = Field(
        900,
        description="The period to wait after the last received request before scaling the replicas to 0. This value should be high enough to allow for the replicas of the service to come up to avoid premature scaling down.",
    )


class AwsSqsAccessKeyBasedAuth(BaseModel):
    type: Literal["access-key-based"] = Field(..., description="")
    access_key_id: constr(regex=r"^\S+$") = Field(
        ..., description="AWS access key ID that you want to use for authentication."
    )
    secret_access_key: constr(regex=r"^\S+$") = Field(
        ...,
        description="AWS access key secret that you want to use for authentication.",
    )


class AwsSqsAssumedRoleBasedAuth(BaseModel):
    type: Literal["assumed-role-based"] = Field(..., description="")
    assumed_role_arn: constr(
        regex=r"^arn:(aws|aws-us-gov|aws-cn):iam::[0-9]{12}:role(/[\w+=,.@-]+)+$"
    ) = Field(..., description="ARN of the role you want to assume.")


class BaseAutoscaling(BaseModel):
    min_replicas: conint(ge=0) = Field(
        1, description="Minimum number of replicas to keep available"
    )
    max_replicas: conint(ge=1, le=500) = Field(
        ..., description="Maximum number of replicas allowed for the component."
    )
    polling_interval: conint(ge=0) = Field(
        30, description="This is the interval to check each trigger on."
    )


class BasicAuthCreds(BaseModel):
    type: Literal["basic_auth"] = Field(..., description="")
    username: str = Field(..., description="")
    password: str = Field(..., description="")


class BlueGreen(BaseModel):
    """
    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.
    """

    type: Literal["blue_green"] = Field(..., description="")
    enable_auto_promotion: bool = Field(
        False,
        description="Promote the new release to handle the complete traffic. A manual promotion would be needed if this is disabled",
    )
    auto_promotion_seconds: conint(ge=0) = Field(
        30,
        description="Promote the new release to handle the complete traffic after waiting for these many seconds",
    )


class BuildSecret(BaseModel):
    id: constr(regex=r"^\S+$") = Field(..., description="The ID of the build secret.")
    value: str = Field(..., description="The value of the build secret.")
    env: Optional[constr(regex=r"^[_a-zA-Z0-9][_a-zA-Z0-9]{1,31}$")] = Field(
        None,
        description="The name of the environment variable to inject the secret into.",
    )


class CPUUtilizationMetric(BaseModel):
    type: Literal["cpu_utilization"] = Field(..., description="")
    value: conint(ge=1, le=100) = Field(
        ...,
        description="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="Percentage of total traffic to be shifted to the canary release.\nThe rest will continue to go to the existing deployment",
    )
    pause_duration: Optional[conint(ge=0)] = Field(
        None,
        description="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",
    )


class CronMetric(BaseModel):
    type: Literal["cron"] = Field(..., description="")
    desired_replicas: Optional[conint(ge=1)] = Field(
        None,
        description="Desired number of replicas during the given interval. Default value is max_replicas.",
    )
    start: str = Field(
        ...,
        description="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="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='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 DockerFileBuild(BaseModel):
    """
    Describes that we are using a dockerfile to build our image
    """

    type: Literal["dockerfile"] = Field(..., description="")
    dockerfile_path: str = Field(
        "./Dockerfile",
        description="The file path of the Dockerfile relative to project root path.",
    )
    build_context_path: str = Field(
        "./",
        description="Build context path for the Dockerfile relative to project root path.",
    )
    command: Optional[Union[str, List[str]]] = Field(
        None,
        description="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="")
    build_secrets: Optional[List[BuildSecret]] = Field(
        None,
        description="Build secrets you can use in run statements inside dockerfile like RUN --mount=type=secret,id=pip_index_url ... you can learn more about build secrets here https://www.truefoundry.com/docs/docker-build-secrets",
    )


class DynamicVolumeConfig(BaseModel):
    type: Literal["dynamic"] = Field(..., description="Volume Type for the volume.")
    storage_class: str = Field(
        ..., description="Name of the storage class to be used for the volume."
    )
    size: conint(ge=1, le=64000) = Field(..., description="Size of volume in Gi")


class Email(BaseModel):
    type: Literal["email"] = Field(..., description="")
    notification_channel: constr(min_length=1) = Field(
        ..., description="Specify the notification channel to send alerts to"
    )
    to_emails: List[constr(min_length=1)] = Field(
        ...,
        description="List of recipients' email addresses if the notification channel is Email.",
    )


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="Host e.g. ai.example.com, app.truefoundry.com")
    path: Optional[
        constr(regex=r"^(/([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-_\.]*[a-zA-Z0-9]))*/$")
    ] = Field(None, description="Path e.g. /v1/api/ml/, /v2/docs/")


class FlyteLaunchPlanID(BaseModel):
    resourceType: Literal["LAUNCH_PLAN"]
    name: str


class FlyteTaskID(BaseModel):
    resourceType: Literal["TASK"]
    name: str


class FlyteWorkflowID(BaseModel):
    resourceType: Literal["WORKFLOW"]
    name: str


class FlyteWorkflowTemplate(BaseModel):
    id: FlyteWorkflowID


class GcpTPU(BaseModel):
    type: Literal["gcp_tpu"] = Field(..., description="")
    name: constr(regex=r"^tpu-[a-z\d\-]+$") = Field(
        ...,
        description="Name of the TPU Type. One of\n  - `tpu-v4-podslice` (TPU v4, ct4p)\n  - `tpu-v5-lite-device` (TPU v5e, ct5l)\n  - `tpu-v5-lite-podslice`  (TPU v5e, ct5lp)\n  - `tpu-v5p-slice` (TPU v5p, ct5p)",
    )
    topology: constr(regex=r"^\d+x\d+(x\d+)?$") = Field(
        ...,
        description="Topology of the TPU slices. Currently only single-host topology is supported.\n Please refer to [TPUs on GKE docs](https://cloud.google.com/kubernetes-engine/docs/concepts/tpus#plan-tpu-configuration)\n Allowed Values:\n   - `2x2x1` for `tpu-v4-podslice`\n   - One of `1x1`, `2x2`, `2x4` for `tpu-v5-lite-device` and `tpu-v5-lite-podslice`\n   - `2x2x1` for `tpu-v5p-slice`",
    )


class GitHelmRepo(BaseModel):
    type: Literal["git-helm-repo"] = Field(..., description="")
    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="")
    revision: str = Field(..., description="Branch/Commit SHA/Tag of the git repo.")
    path: str = Field(..., description="Path to the chart.")
    value_files: Optional[List[str]] = Field(
        None,
        description="Helm values files for overriding values in the helm chart.\nThe path is relative to the Path directory defined above",
    )


class GitSource(BaseModel):
    """
    Describes that we are using code stored in a git repository to build our image
    """

    type: Literal["git"] = Field(..., description="")
    repo_url: constr(regex=r"^(https?://)\S+$") = Field(
        ..., description="The repository URL."
    )
    ref: constr(regex=r"^\S+$") = Field(..., description="The commit SHA.")
    branch_name: Optional[constr(regex=r"^\S+$")] = Field(
        None,
        description="Selecting branch will select latest commit SHA of the branch.",
    )


class HelmRepo(BaseModel):
    type: Literal["helm-repo"] = Field(..., description="")
    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="")
    integration_fqn: Optional[str] = Field(
        None,
        description="FQN of the helm repo integration. If you can't find your integration here,\nadd it through the [Integrations](/integrations) page",
    )
    chart: str = Field(..., description="The helm chart name")
    version: str = Field(..., description="Helm chart version")


class HttpProbe(BaseModel):
    """
    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/liveness-readiness-probe)
    """

    type: Literal["http"] = Field(..., description="")
    path: str = Field(..., description="Path to the health check endpoint")
    port: conint(ge=0, le=65535) = Field(
        ..., description="Listening port for the health check endpoint"
    )
    host: Optional[str] = Field(
        None, description="Host name to connect to, defaults to the pod IP"
    )
    scheme: str = Field("HTTP", description="Scheme to use for connecting to the host")


class HuggingfaceArtifactSource(BaseModel):
    """
    Input for Artifact from Huggingface Model Hub
    """

    type: Literal["huggingface-hub"] = Field(..., description="")
    model_id: str = Field(..., description="Model ID of the artifact to be downloaded")
    revision: str = Field(..., description="Revision of the artifact to be downloaded")
    ignore_patterns: List[str] = Field(
        ["*.h5", "*.ot", "*.tflite", "*.msgpack"],
        description="List of patterns to ignore while downloading the artifact",
    )
    download_path_env_variable: str = Field(
        ...,
        description="Environment variable which will contain the download path of the artifact",
    )


class Image(BaseModel):
    """
    Describes that we are using a pre-built image stored in a Docker Image registry
    """

    type: Literal["image"] = Field(..., description="")
    image_uri: constr(regex=r"^\S+$") = Field(
        ...,
        description="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",
    )
    docker_registry: Optional[constr(regex=r"^\S+$")] = Field(
        None,
        description="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="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 Claim(BaseModel):
    key: str
    values: List[str]


class JwtAuthConfig(BaseModel):
    """
    Configure JWT-based authentication using JWKS
    """

    type: Literal["jwt_auth"] = Field(..., description="")
    integration_fqn: str = Field(
        ...,
        description="FQN of the JWT Auth integration. If you can't find your integration here,\nadd it through the [Integrations](/integrations) page",
    )
    enable_login: Optional[bool] = Field(
        None, description="Enable login for the service"
    )
    claims: Optional[List[Claim]] = Field(
        None, description="List of key-value pairs of claims to verify in the JWT token"
    )
    bypass_auth_paths: Optional[List[constr(regex=r"^/[^*]*")]] = Field(
        None,
        description="List of paths that will bypass auth.\nneeds to start with a forward slash(/) and should not contain wildcards(*)",
    )


class KafkaMetricConfig(BaseModel):
    type: Literal["kafka"] = Field(..., description="")
    lag_threshold: conint(ge=1) = Field(
        ...,
        description="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="Username for SASL authentication")
    password: str = Field(..., description="Password for SASL authentication")


class Kustomize(BaseModel):
    patch: Optional[Dict[str, Any]] = Field(
        None,
        description="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="Additional kubernetes manifests to be included in the application",
    )


class LocalSource(BaseModel):
    """
    Describes that we are using code stored in a local developement environment to build our image
    """

    type: Literal["local"] = Field(..., description="")
    project_root_path: str = Field("./", description="Local project root path.")
    local_build: bool = Field(True, description="")


class Manual(BaseModel):
    """
    Trigger the job manually. [Docs](https://docs.truefoundry.com/docs/deploy-a-cron-job)
    """

    type: Literal["manual"] = Field(..., description="")


class NATSMetricConfig(BaseModel):
    type: Literal["nats"] = Field(..., description="")
    lag_threshold: conint(ge=1) = Field(
        ...,
        description="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):
    """
    NATS User Password Authentication
    """

    account_name: str = Field("$G", description="Name of the NATS account")
    user: str = Field(..., description="User for NATS authentication")
    password: str = Field(..., description="Password for NATS authentication")


class CapacityType(str, Enum):
    """
    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):
    """
    Constraints to select a Node - Specific GPU / Instance Families, On-Demand/Spot.
    """

    type: Literal["node_selector"] = Field(..., description="")
    instance_families: Optional[List[str]] = Field(
        None,
        description="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='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):
    """
    Specify one or more nodepools to run your application on.
    """

    type: Literal["nodepool_selector"] = Field(..., description="")
    nodepools: Optional[List[str]] = Field(
        None,
        description="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: Literal["nvidia_gpu"] = Field(..., description="")
    name: Optional[str] = Field(
        None,
        description="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="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 Profile(str, Enum):
    """
    Name of the MIG profile to use. One of the following based on gpu type
    Please refer to https://docs.nvidia.com/datacenter/tesla/mig-user-guide/#supported-mig-profiles for more details
    A30 - [1g.6gb, 2g.12gb, 4g.24gb]
    A100 40 GB - [1g.5gb, 1g.10gb, 2g.10gb, 3g.20gb, 4g.20gb, 7g.40gb]
    A100 80 GB / H100 80 GB - [1g.10gb, 1g.20gb, 2g.20gb, 3g.40gb, 4g.40gb, 7g.80gb]
    H100 94 GB - [1g.12gb, 1g.24gb, 2g.24gb, 3g.47gb, 4g.47gb, 7g.94gb]
    H100 96 GB - [1g.12gb, 1g.24gb, 2g.24gb, 3g.48gb, 4g.48gb, 7g.96gb]
    H200 141 GB - [1g.18gb, 1g.35gb, 2g.35gb, 3g.71gb, 4g.71gb]
    B200 180 GB - [1g.23gb, 1g.45gb, 2g.45gb, 3g.90gb, 4g.90gb, 7g.180gb]
    """

    field_1g_6gb = "1g.6gb"
    field_2g_12gb = "2g.12gb"
    field_1g_5gb = "1g.5gb"
    field_1g_10gb = "1g.10gb"
    field_2g_10gb = "2g.10gb"
    field_3g_20gb = "3g.20gb"
    field_4g_20gb = "4g.20gb"
    field_1g_20gb = "1g.20gb"
    field_2g_20gb = "2g.20gb"
    field_3g_40gb = "3g.40gb"
    field_4g_40gb = "4g.40gb"
    field_1g_12gb = "1g.12gb"
    field_1g_24gb = "1g.24gb"
    field_2g_24gb = "2g.24gb"
    field_3g_47gb = "3g.47gb"
    field_4g_47gb = "4g.47gb"
    field_3g_48gb = "3g.48gb"
    field_4g_48gb = "4g.48gb"
    field_1g_18gb = "1g.18gb"
    field_1g_35gb = "1g.35gb"
    field_2g_35gb = "2g.35gb"
    field_3g_71gb = "3g.71gb"
    field_4g_71gb = "4g.71gb"
    field_1g_23gb = "1g.23gb"
    field_1g_45gb = "1g.45gb"
    field_2g_45gb = "2g.45gb"
    field_3g_90gb = "3g.90gb"
    field_4g_90gb = "4g.90gb"
    field_4g_24gb = "4g.24gb"
    field_7g_40gb = "7g.40gb"
    field_7g_80gb = "7g.80gb"
    field_7g_94gb = "7g.94gb"
    field_7g_96gb = "7g.96gb"
    field_7g_180gb = "7g.180gb"


class NvidiaMIGGPU(BaseModel):
    type: Literal["nvidia_mig_gpu"] = Field(..., description="")
    name: Optional[str] = Field(
        None,
        description="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",
    )
    profile: Profile = Field(
        ...,
        description="Name of the MIG profile to use. One of the following based on gpu type\nPlease refer to https://docs.nvidia.com/datacenter/tesla/mig-user-guide/#supported-mig-profiles for more details\nA30 - [1g.6gb, 2g.12gb, 4g.24gb]\nA100 40 GB - [1g.5gb, 1g.10gb, 2g.10gb, 3g.20gb, 4g.20gb, 7g.40gb]\nA100 80 GB / H100 80 GB - [1g.10gb, 1g.20gb, 2g.20gb, 3g.40gb, 4g.40gb, 7g.80gb]\nH100 94 GB - [1g.12gb, 1g.24gb, 2g.24gb, 3g.47gb, 4g.47gb, 7g.94gb]\nH100 96 GB - [1g.12gb, 1g.24gb, 2g.24gb, 3g.48gb, 4g.48gb, 7g.96gb]\nH200 141 GB - [1g.18gb, 1g.35gb, 2g.35gb, 3g.71gb, 4g.71gb]\nB200 180 GB - [1g.23gb, 1g.45gb, 2g.45gb, 3g.90gb, 4g.90gb, 7g.180gb]",
    )


class NvidiaTimeslicingGPU(BaseModel):
    type: Literal["nvidia_timeslicing_gpu"] = Field(..., description="")
    name: Optional[str] = Field(
        None,
        description="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",
    )
    gpu_memory: conint(ge=1, le=400000) = Field(
        ...,
        description="Amount of GPU memory (in MB) to allocate. Please note, this limit is not being enforced today but will be in future. Applications are expected to operate in co-opertative mode",
    )


class OCIRepo(BaseModel):
    type: Literal["oci-repo"] = Field(..., description="")
    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="")
    integration_fqn: Optional[str] = Field(
        None,
        description="FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations) page",
    )
    version: str = Field(..., description="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="Name of the param"
    )
    description: Optional[constr(regex=r"^.{1,127}$")] = Field(
        None, description="Description of param"
    )
    default: Optional[constr(regex=r"^.{0,127}$")] = Field(
        None, description="Default value or placeholder"
    )
    param_type: ParamType = "string"


class Pip(BaseModel):
    """
    Use pip to install requirements files and packages
    """

    type: Literal["pip"] = Field(..., description="")
    requirements_path: Optional[str] = Field(
        None,
        description="Path to `requirements.txt` relative to `Path to build context`",
    )
    pip_packages: Optional[List[str]] = Field(
        None,
        description='Define pip package requirements.\nIn Python/YAML E.g. ["fastapi>=0.90,<1.0", "uvicorn"]',
    )


class Poetry(BaseModel):
    """
    Use `poetry` to setup env.
    Your build context root must contain `pyproject.toml` and `poetry.lock`
    """

    type: Literal["poetry"] = Field(..., description="")
    poetry_version: Union[
        Literal["latest"], constr(regex=r"^\d+(\.\d+){1,2}([\-\.a-z0-9]+)?$")
    ] = Field("latest", description="Poetry version to use")
    install_options: Optional[str] = Field(
        None, description="install options to pass to poetry command"
    )


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

    TCP = "TCP"
    UDP = "UDP"


class AppProtocol(str, Enum):
    """
    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 RPSMetric(BaseModel):
    type: Literal["rps"] = Field(..., description="")
    value: PositiveFloat = Field(
        ...,
        description="Average request per second averaged over all replicas that autoscaler should try to maintain",
    )


class RemoteSource(BaseModel):
    """
    Describes that we are using code stored in a remote repository to build our image
    """

    type: Literal["remote"] = Field(..., description="")
    remote_uri: str = Field(..., description="Remote repository URI")


class Resources(BaseModel):
    """
    Configure resource allocations, specify node constraints and capacity types to improve performance and reduce expenses. [Docs](https://www.truefoundry.com/docs/resources-cpu-memory-storage)
    """

    cpu_request: confloat(ge=0.001, le=256.0) = Field(
        0.2,
        description="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="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.",
    )
    memory_request: conint(ge=1, le=4000000) = Field(
        200,
        description="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.",
    )
    memory_limit: conint(ge=1, le=4000000) = Field(
        500,
        description="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.",
    )
    ephemeral_storage_request: conint(ge=1, le=2000000) = Field(
        1000,
        description="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",
    )
    ephemeral_storage_limit: conint(ge=1, le=2000000) = Field(
        2000,
        description="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",
    )
    shared_memory_size: Optional[conint(ge=64, le=4000000)] = Field(
        None,
        description="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="This field determines how the underlying node resource is to be utilized",
        discriminator="type",
    )
    devices: Optional[
        List[
            Union[NvidiaGPU, AWSInferentia, NvidiaMIGGPU, NvidiaTimeslicingGPU, GcpTPU]
        ]
    ] = Field(
        None,
        description="Define custom device or accelerator requirements for your workload. We currently support NVIDIA GPUs, AWS Inferentia Accelerators, Single Host TPU Slices.",
    )


class Rolling(BaseModel):
    """
    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/)
    """

    type: Literal["rolling_update"] = Field(..., description="")
    max_unavailable_percentage: conint(ge=0, le=100) = Field(
        25,
        description="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(
        25,
        description="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):
    """
    Describes the configuration for the input SQS worker
    """

    type: Literal["sqs"] = Field(..., description="")
    queue_url: str = Field(..., description="AWS SQS Queue URL of Subscriber")
    region_name: str = Field(..., description="AWS Region Name")
    visibility_timeout: conint(ge=1, le=43200) = Field(
        ...,
        description="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)",
    )
    wait_time_seconds: conint(ge=1, le=20) = Field(
        19,
        description="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: Optional[AWSAccessKeyAuth] = None


class SQSOutputConfig(BaseModel):
    """
    Describes the configuration for the output SQS worker
    """

    type: Literal["sqs"] = Field(..., description="")
    queue_url: str = Field(..., description="AWS SQS Queue URL of Publisher")
    region_name: str = Field(..., description="AWS Region Name")
    auth: Optional[AWSAccessKeyAuth] = None


class SQSQueueMetricConfig(BaseModel):
    type: Literal["sqs"] = Field(..., description="")
    queue_length: conint(ge=1) = Field(
        ...,
        description="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.",
    )
    auth: Optional[Union[AwsSqsAccessKeyBasedAuth, AwsSqsAssumedRoleBasedAuth]] = Field(
        None, description="Receive permissions on the SQS Queue", discriminator="type"
    )


class ConcurrencyPolicy(str, Enum):
    """
    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):
    """
    Run the job on a schedule. [Docs](https://docs.truefoundry.com/docs/deploy-a-cron-job)
    """

    type: Literal["scheduled"] = Field(..., description="")
    schedule: str = Field(
        ...,
        description="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="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='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: Literal["secret"] = Field(..., description="")
    mount_path: constr(regex=r"^\/(?:[^/\n]+\/*)*[^/\n]+(\.[^/\n]+)?$") = Field(
        ..., description="Absolute file path where the file will be created."
    )
    secret_fqn: constr(regex=r"^tfy-secret:\/\/.+:.+:.+$") = Field(
        ..., description="The TrueFoundry secret whose value will be the file content."
    )


class ServiceAutoscaling(BaseAutoscaling):
    metrics: Union[CPUUtilizationMetric, RPSMetric, CronMetric] = Field(
        ..., description="Metrics to use for the autoscaler", discriminator="type"
    )


class SlackBot(BaseModel):
    type: Literal["slack-bot"] = Field(..., description="")
    notification_channel: constr(min_length=1) = Field(
        ..., description="Specify the notification channel to send alerts to"
    )
    channels: List[constr(regex=r"^#[a-z0-9\-_]{2,80}$")] = Field(
        ..., description="List of channels to send messages to."
    )


class SlackWebhook(BaseModel):
    type: Literal["slack-webhook"] = Field(..., description="")
    notification_channel: constr(min_length=1) = Field(
        ..., description="Specify the notification channel to send alerts to"
    )


class SparkBuild(BaseModel):
    """
    Describes that we are using python to build a container image with a specific python version and pip packages installed.
    """

    type: Literal["tfy-spark-buildpack"] = Field(..., description="")
    spark_version: str = Field(
        "3.5.2",
        description="Spark version should match the spark version installed in the image.",
    )
    build_context_path: str = Field(
        "./", description="Build path relative to project root path."
    )
    requirements_path: Optional[str] = Field(
        None,
        description="Path to `requirements.txt` relative to\n`Path to build context`",
    )


class SparkDriverConfig(BaseModel):
    resources: Optional[Resources] = None


class SparkExecutorDynamicScaling(BaseModel):
    type: Literal["dynamic"] = Field(..., description="")
    min: conint(ge=0, le=500) = Field(
        1, description="Minimum number of instances to start / scale down to"
    )
    max: conint(ge=0, le=500) = Field(
        1, description="Maximum number of instances to scale up to"
    )


class SparkExecutorFixedInstances(BaseModel):
    type: Literal["fixed"] = Field(..., description="")
    count: conint(ge=0, le=500) = Field(1, description="Number of instances to start")


class SparkImage(BaseModel):
    """
    Describes that we are using a pre-built image stored in a Docker Image registry
    """

    type: Literal["spark-image"] = Field(..., description="")
    spark_version: str = Field(
        "3.5.2",
        description="Spark version should match the spark version installed in the image.",
    )
    image_uri: constr(regex=r"^\S+$") = Field(
        ...,
        description="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",
    )
    docker_registry: Optional[constr(regex=r"^\S+$")] = Field(
        None,
        description="FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )


class SparkImageBuild(BaseModel):
    """
    Describes that we are building a new image based on the spec
    """

    type: Literal["spark-image-build"] = Field(..., description="")
    docker_registry: Optional[constr(regex=r"^\S+$")] = Field(
        None,
        description="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[GitSource, RemoteSource] = Field(
        ..., description="", discriminator="type"
    )
    build_spec: SparkBuild


class SparkJobJavaEntrypoint(BaseModel):
    type: Literal["java"] = Field(..., description="")
    main_application_file: str = Field(
        ..., description="The main application file to be executed by the spark job."
    )
    main_class: str = Field(
        ..., description="The main class to be executed by the spark job."
    )
    arguments: Optional[str] = Field(
        None, description="Arguments to be passed to the main application file."
    )


class SparkJobPythonEntrypoint(BaseModel):
    type: Literal["python"] = Field(..., description="")
    main_application_file: str = Field(
        ...,
        description="The main application file to be executed by the spark job. Relative path in case of git repository.",
    )
    arguments: Optional[str] = Field(
        None, description="Arguments to be passed to the main application file."
    )


class SparkJobPythonNotebookEntrypoint(BaseModel):
    type: Literal["python-notebook"] = Field(..., description="")
    main_application_file: str = Field(
        ...,
        description="The main application file to be executed by the spark job. Relative path in case of git repository.",
    )


class SparkJobScalaEntrypoint(BaseModel):
    type: Literal["scala"] = Field(..., description="")
    main_application_file: str = Field(
        ..., description="The main application file to be executed by the spark job."
    )
    main_class: str = Field(
        ..., description="The main class to be executed by the spark job."
    )
    arguments: Optional[str] = Field(
        None, description="Arguments to be passed to the main application file."
    )


class SparkJobScalaNotebookEntrypoint(BaseModel):
    type: Literal["scala-notebook"] = Field(..., description="")
    main_application_file: str = Field(
        ...,
        description="The main application file to be executed by the spark job. Relative path in case of git repository.",
    )


class StaticVolumeConfig(BaseModel):
    type: Literal["static"] = Field(..., description="Volume Type for the volume.")
    persistent_volume_name: str = Field(
        ..., description="Persistent Volume Name of the volume to be used."
    )


class StringDataMount(BaseModel):
    type: Literal["string"] = Field(..., description="")
    mount_path: constr(regex=r"^\/(?:[^/\n]+\/*)*[^/\n]+(\.[^/\n]+)?$") = Field(
        ..., description="Absolute file path where the file will be created."
    )
    data: str = Field(..., description="The file content.")


class TaskDockerFileBuild(BaseModel):
    """
    Describes the configuration for the docker build for a task
    """

    type: Literal["task-dockerfile-build"] = Field(..., description="")
    docker_registry: Optional[str] = Field(
        None,
        description="FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )
    dockerfile_path: str = Field(
        "./Dockerfile",
        description="The file path of the Dockerfile relative to project root path.",
    )
    build_args: Optional[Dict[str, str]] = Field(None, description="")


class TaskPySparkBuild(BaseModel):
    """
    Describes the configuration for the PySpark build for a task
    """

    type: Literal["task-pyspark-build"] = Field(..., description="")
    spark_version: str = Field(
        "3.5.2",
        description="Spark version should match the spark version installed in the image.",
    )
    container_image: Optional[constr(regex=r"^\S+$")] = Field(
        None,
        description="Custom container image URI. If provided, this image is used instead of the\ndefault Spark base image (public.ecr.aws/bitnami/spark). The image must be\nDebian-based and have Python and Spark pre-installed.",
    )
    docker_registry: Optional[str] = Field(
        None,
        description="FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )
    requirements_path: Optional[str] = Field(
        None,
        description="Path to `requirements.txt` relative to\n`Path to build context`",
    )
    pip_packages: Optional[List[str]] = Field(
        None,
        description='Define pip package requirements.\nIn Python/YAML E.g. ["fastapi>=0.90,<1.0", "uvicorn"]',
    )
    apt_packages: Optional[List[str]] = Field(
        None,
        description='Debian packages to install via `apt get`.\nIn Python/YAML E.g. ["git", "ffmpeg", "htop"]',
    )


class TaskPythonBuild(BaseModel):
    """
    Describes the configuration for the python build for a task
    """

    type: Literal["task-python-build"] = Field(..., description="")
    docker_registry: Optional[str] = Field(
        None,
        description="FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )
    python_version: Optional[constr(regex=r"^\d+(\.\d+){1,2}([\-\.a-z0-9]+)?$")] = (
        Field(
            None,
            description="Python version to run your application. Should be one of the tags listed on [Official Python Docker Page](https://hub.docker.com/_/python)",
        )
    )
    requirements_path: Optional[str] = Field(
        None,
        description="Path to `requirements.txt` relative to\n`Path to build context`",
    )
    pip_packages: Optional[List[str]] = Field(
        None,
        description='Define pip package requirements.\nIn Python/YAML E.g. ["fastapi>=0.90,<1.0", "uvicorn"]',
    )
    apt_packages: Optional[List[str]] = Field(
        None,
        description='Debian packages to install via `apt get`.\nIn Python/YAML E.g. ["git", "ffmpeg", "htop"]',
    )
    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|12\.3-cudnn9|12\.4-cudnn9|12\.5-cudnn9|12\.6-cudnn9|12\.8-cudnn9|12\.9-cudnn9)$"
        )
    ] = Field(
        None,
        description="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 TrueFoundryArtifactSource(BaseModel):
    """
    Input for Artifact from TrueFoundry Artifact Registry
    """

    type: Literal["truefoundry-artifact"] = Field(..., description="")
    artifact_version_fqn: str = Field(
        ...,
        description="Artifact or Model Version FQN of the artifact to be downloaded",
    )
    download_path_env_variable: str = Field(
        ...,
        description="Environment variable which will contain the download path of the artifact",
    )


class TrueFoundryInteractiveLogin(BaseModel):
    type: Literal["truefoundry_oauth"] = Field(..., description="")
    bypass_auth_paths: Optional[List[constr(regex=r"^/[^*]*")]] = Field(
        None,
        description="List of paths that will bypass auth.\nneeds to start with a forward slash(/) and should not contain wildcards(*)",
    )


class UV(BaseModel):
    """
    Use `uv` to setup env.
    Your build context root must contain `pyproject.toml` and `uv.lock`
    """

    type: Literal["uv"] = Field(..., description="")
    uv_version: str = Field("latest", description="UV version to use")
    sync_options: Optional[str] = Field(
        None, description="Sync options to pass to uv command"
    )


class VolumeBrowser(BaseModel):
    username: Optional[constr(regex=r"^[a-z][a-z0-9]{1,8}[a-z0-9]$")] = Field(
        None, description="Username for logging in the volume browser."
    )
    password_secret_fqn: Optional[constr(regex=r"^tfy-secret:\/\/.+:.+:.+$")] = Field(
        None,
        description="TFY Secret containing the password for logging in the volume browser.",
    )
    endpoint: Endpoint
    service_account: Optional[str] = Field(
        None, description="Kubernetes Service account name for the volume browser."
    )


class VolumeMount(BaseModel):
    type: Literal["volume"] = Field(..., description="")
    mount_path: constr(regex=r"^\/(?:[^/\n]+\/*)*[^/\n]+(\.[^/\n]+)?$") = Field(
        ..., description="Absolute file path where the volume will be mounted."
    )
    sub_path: Optional[constr(regex=r"^(?:[^/\n]+/*)*[^/\n]+(\.[^/\n]+)?$")] = Field(
        None,
        description="Sub path within the volume to mount. Defaults to root of the volume.",
    )
    volume_fqn: constr(regex=r"^tfy-volume:\/\/.+:.+:.+$") = Field(
        ..., description="The TrueFoundry volume that needs to be mounted."
    )


class WorkbenchImage(BaseModel):
    """
    Workbench Image with persistent environment (Python 3.11.6)
    """

    image_uri: str = Field(
        ...,
        description="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",
    )
    build_script: Optional[constr(min_length=1, max_length=5120)] = Field(
        None,
        description="The build script to run when building the image.\nThis will be executed as the last step in the docker build process as the root user (RUN DEBIAN_FRONTEND=noninteractive bash -ex build_script.sh)",
    )
    docker_registry: Optional[str] = Field(
        None,
        description="FQN of the container registry. If you can't find your registry here,\nadd it through the [Integrations](/integrations?tab=docker-registry) page",
    )


class ArtifactsDownload(BaseModel):
    """
    Download and cache models in a volume to enhance loading speeds and reduce costs by avoiding repeated downloads. [Docs](https://docs.truefoundry.com/docs/download-and-cache-models)
    """

    cache_volume: Optional[ArtifactsCacheVolume] = None
    artifacts: List[Union[TrueFoundryArtifactSource, HuggingfaceArtifactSource]] = (
        Field(..., description="List of artifacts to be cached")
    )


class AsyncServiceAutoscaling(BaseAutoscaling):
    metrics: Union[
        SQSQueueMetricConfig,
        NATSMetricConfig,
        KafkaMetricConfig,
        CronMetric,
        AMQPMetricConfig,
    ] = Field(
        ..., description="Metrics to use for the autoscaler", discriminator="type"
    )


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

    name: constr(regex=r"^[a-z](?:[a-z0-9]|-(?!-)){1,30}[a-z0-9]$") = Field(
        ...,
        description="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",
    )
    home_directory_size: conint(ge=5, le=64000) = Field(
        20,
        description="Size of the home directory for the workbench (Persistent Storage)",
    )
    resources: Optional[Resources] = None
    env: Optional[Dict[str, str]] = Field(
        None,
        description="Configure environment variables to be injected in the service either as plain text or secrets. [Docs](https://docs.truefoundry.com/docs/environment-variables-and-secrets-jobs)",
    )
    mounts: Optional[List[Union[SecretMount, StringDataMount, VolumeMount]]] = Field(
        None,
        description="Configure data to be mounted to workbench pod(s) as a string, secret or volume. [Docs](https://docs.truefoundry.com/docs/mounting-volumes-job)",
    )
    service_account: Optional[str] = Field(None, description="")
    kustomize: Optional[Kustomize] = None
    workspace_fqn: Optional[str] = Field(
        None, description="Fully qualified name of the workspace"
    )


class Canary(BaseModel):
    """
    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.
    """

    type: Literal["canary"] = Field(..., description="")
    steps: List[CanaryStep] = Field(
        ...,
        description="These steps would be executed in order to enable shifting of traffic slowly from stable to canary version",
    )


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

    type: Literal["codeserver"] = Field(..., description="")
    image: WorkbenchImage


class CoreNATSOutputConfig(BaseModel):
    """
    Describes the configuration for the output Core NATS worker
    """

    type: Literal["core-nats"] = Field(..., description="")
    nats_url: str = Field(..., description="Output NATS URL")
    root_subject: constr(regex=r"^[a-zA-Z0-9][a-zA-Z0-9\-.]+[a-zA-Z0-9]$") = Field(
        ..., description="Root subject of output NATS"
    )
    auth: Optional[NATSUserPasswordAuth] = None


class DatabricksJobTaskConfig(BaseModel):
    """
    Task that triggers a Databricks job via API and polls until completion. Uses image and optional resources; no env or mounts. Execution is handled by the CLI (trigger + poll).
    """

    type: Literal["databricks-job-task-config"] = Field(..., description="")
    image: Union[TaskPythonBuild, TaskDockerFileBuild] = Field(
        ..., description="Specify the image spec for the task", discriminator="type"
    )
    workspace_host: str = Field(
        ...,
        description="Databricks workspace URL, e.g. https://<workspace>.cloud.databricks.com",
    )
    job_id: str = Field(
        ...,
        description="The Databricks job ID to run (from Databricks workspace Jobs).",
    )
    service_account: Optional[str] = Field(None, description="")
    job_parameters: Optional[Dict[str, str]] = Field(
        None,
        description="Optional parameters to pass to the job run (e.g. notebook params, jar params).",
    )
    timeout_seconds: Optional[float] = Field(
        None,
        description="Maximum seconds to wait for the job run to complete. Used by CLI when polling.",
    )
    skip_wait_for_completion: bool = Field(
        False,
        description="If false, the task waits for the Databricks job run to complete (trigger and poll). If true, only triggers the job and returns. Default false.",
    )
    env: Optional[Dict[str, str]] = Field(
        None,
        description="Configure environment variables to be injected in the task either as plain text or secrets. [Docs](https://docs.truefoundry.com/docs/env-variables)",
    )
    resources: Optional[Resources] = None


class FlyteLaunchPlanSpec(BaseModel):
    workflowId: FlyteWorkflowID


class FlyteWorkflow(BaseModel):
    template: FlyteWorkflowTemplate
    description: Optional[Any] = None


class HealthProbe(BaseModel):
    """
    Describes the configuration for the Health Probe's
    To learn more you can go [here](https://docs.truefoundry.com/docs/liveness-readiness-probe)
    """

    config: HttpProbe
    initial_delay_seconds: conint(ge=0, le=36000) = Field(
        0,
        description="Time to wait after container has started before checking the endpoint",
    )
    period_seconds: conint(ge=1, le=36000) = Field(
        10, description="How often to check the endpoint"
    )
    timeout_seconds: conint(ge=1, le=36000) = Field(
        1,
        description="Time to wait for a response from the endpoint before considering it down",
    )
    success_threshold: conint(ge=1, le=5000) = Field(
        1,
        description="Number of successful responses from the endpoint before container is considered healthy",
    )
    failure_threshold: conint(ge=1, le=5000) = Field(
        3,
        description="Number of consecutive failures before the container is considered down",
    )


class Helm(BaseModel):
    type: Literal["helm"] = Field(..., description="")
    name: constr(regex=r"^[a-z](?:[a-z0-9]|-(?!-)){1,30}[a-z0-9]$") = Field(
        ...,
        description="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="Add labels to base argo app"
    )
    source: Union[HelmRepo, OCIRepo, GitHelmRepo] = Field(
        ..., description="", discriminator="type"
    )
    values: Optional[Dict[str, Any]] = Field(
        None, description="Values file as block file"
    )
    kustomize: Optional[Kustomize] = None
    ignoreDifferences: Optional[List[Dict[str, Any]]] = None
    workspace_fqn: Optional[str] = Field(
        None, description="Fully qualified name of the workspace"
    )


class KafkaInputConfig(BaseModel):
    """
    Describes the configuration for the input Kafka worker
    """

    type: Literal["kafka"] = Field(..., description="")
    bootstrap_servers: str = Field(
        ...,
        description="'Kafka Bootstrap servers - Comma separated list of Kafka brokers \"hostname:port\" to connect to for bootstrap'",
    )
    topic_name: str = Field(..., description="Kafka topic to subscribe to")
    consumer_group: str = Field(
        ...,
        description="The name of the consumer group to join for dynamic partition assignment",
    )
    tls: bool = Field(True, description="TLS configuration for SASL authentication")
    wait_time_seconds: conint(ge=1, le=300) = Field(
        10, description="Wait timeout for long polling."
    )
    auth: Optional[KafkaSASLAuth] = None


class KafkaOutputConfig(BaseModel):
    """
    Describes the configuration for the output Kafka worker
    """

    type: Literal["kafka"] = Field(..., description="")
    bootstrap_servers: str = Field(
        ...,
        description="'Kafka Bootstrap servers - Comma separated list of Kafka brokers \"hostname:port\" to connect to for bootstrap'",
    )
    topic_name: str = Field(..., description="Kafka topic to publish to")
    tls: bool = Field(True, description="TLS configuration for SASL authentication")
    auth: Optional[KafkaSASLAuth] = None


class NATSInputConfig(BaseModel):
    """
    Describes the configuration for the input NATS worker
    """

    type: Literal["nats"] = Field(..., description="")
    nats_url: str = Field(..., description="Input NATS URL")
    stream_name: str = Field(..., description="Name of the NATS stream")
    root_subject: constr(regex=r"^[a-zA-Z0-9][a-zA-Z0-9\-.]+[a-zA-Z0-9]$") = Field(
        ..., description="Root subject of input NATS"
    )
    consumer_name: constr(regex=r"^[a-zA-Z0-9][a-zA-Z0-9\-_]+[a-zA-Z0-9]$") = Field(
        ..., description="Consumer name of input NATS"
    )
    wait_time_seconds: conint(ge=1, le=20) = Field(
        19, description="Wait timeout for long polling."
    )
    nats_metrics_url: Optional[constr(regex=r"^(http(s?)://).*$")] = Field(
        None,
        description="URL for the NATS metrics endpoint. It is compulsory if you want to use NATS autoscaling.",
    )
    auth: Optional[NATSUserPasswordAuth] = None


class NATSOutputConfig(BaseModel):
    """
    Describes the configuration for the output NATS worker
    """

    type: Literal["nats"] = Field(..., description="")
    nats_url: str = Field(..., description="Output NATS URL")
    root_subject: constr(regex=r"^[a-zA-Z0-9][a-zA-Z0-9\-.]+[a-zA-Z0-9]$") = Field(
        ..., description="Root subject of output NATS"
    )
    auth: Optional[NATSUserPasswordAuth] = None


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

    type: Literal["notebook"] = Field(..., description="")
    image: WorkbenchImage
    cull_timeout: conint(ge=5) = Field(
        30,
        description="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.",
    )


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

    port: conint(ge=1, le=65535) = Field(80, description="Port number to expose.")
    protocol: Protocol = Field("TCP", description="Protocol for the port.")
    expose: bool = Field(True, description="Expose the port")
    app_protocol: AppProtocol = Field(
        "http",
        description="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="Host e.g. ai.example.com, app.truefoundry.com")
    path: Optional[
        constr(regex=r"^(/([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-_\.]*[a-zA-Z0-9]))*/$")
    ] = Field(None, description="Path e.g. /v1/api/ml/, /v2/docs/")
    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="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.",
    )
    auth: Optional[
        Union[BasicAuthCreds, JwtAuthConfig, TrueFoundryInteractiveLogin]
    ] = Field(
        None,
        description="Authentication method for inbound traffic",
        discriminator="type",
    )


class PythonBuild(BaseModel):
    """
    Describes that we are using python to build a container image with a specific python version and pip packages installed.
    """

    type: Literal["tfy-python-buildpack"] = Field(..., description="")
    python_version: Optional[constr(regex=r"^\d+(\.\d+){1,2}([\-\.a-z0-9]+)?$")] = (
        Field(
            None,
            description="Python version to run your application. Should be one of the tags listed on [Official Python Docker Page](https://hub.docker.com/_/python)",
        )
    )
    build_context_path: str = Field(
        "./", description="Build path relative to project root path."
    )
    requirements_path: Optional[str] = Field(
        None,
        description="Path to `requirements.txt` relative to\n`Path to build context`",
    )
    pip_packages: Optional[List[str]] = Field(
        None,
        description='Define pip package requirements.\nIn Python/YAML E.g. ["fastapi>=0.90,<1.0", "uvicorn"]',
    )
    python_dependencies: Optional[Union[Pip, UV, Poetry]] = Field(
        None, description="Python dependencies to install", discriminator="type"
    )
    apt_packages: Optional[List[str]] = Field(
        None,
        description='Debian packages to install via `apt get`.\nIn Python/YAML E.g. ["git", "ffmpeg", "htop"]',
    )
    command: Union[str, List[str]] = Field(
        ...,
        description="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|12\.3-cudnn9|12\.4-cudnn9|12\.5-cudnn9|12\.6-cudnn9|12\.8-cudnn9|12\.9-cudnn9)$"
        )
    ] = Field(
        None,
        description="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 PythonTaskConfig(BaseModel):
    """
    Describes the configuration for the python function task
    """

    type: Literal["python-task-config"] = Field(..., description="")
    image: Union[TaskPythonBuild, TaskDockerFileBuild] = Field(
        ..., description="Specify the image spec for the task", discriminator="type"
    )
    env: Optional[Dict[str, str]] = Field(
        None,
        description="Configure environment variables to be injected in the task either as plain text or secrets. [Docs](https://docs.truefoundry.com/docs/env-variables)",
    )
    resources: Optional[Resources] = None
    mounts: Optional[List[Union[SecretMount, StringDataMount, VolumeMount]]] = Field(
        None, description="Configure data to be mounted to Workflow pod(s) as a volume."
    )
    service_account: Optional[str] = Field(None, description="")


class RStudio(BaseWorkbenchInput):
    """
    Describes the configuration for the Rstudio server
    """

    type: Literal["rstudio"] = Field(..., description="")
    image: WorkbenchImage


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

    type: Literal["ssh-server"] = Field(..., description="")
    image: WorkbenchImage
    ssh_public_key: str = Field(
        ...,
        description="Add Your SSH Public Key, this will be used to authenticate you to the SSH Server.  \\\nYou can find it using `cat ~/.ssh/id_rsa.pub` in Mac/Linux or `type $home\\.ssh\\id_rsa.pub` in Windows Powershell.  \\\nYou can also generate a new SSH key pair using `ssh-keygen -t rsa` in your local terminal. (same for both Mac/Linux and Windows Powershell)",
    )
    cull_timeout: Optional[conint(ge=5)] = Field(
        None,
        description="Stop the SSH Server instance after this much time in minutes of inactivity. The instance is considered active if there is at least one active SSH connection (a client connected to the SSH server), or if a background job is running using tmux or screen, or if the pod has restarted.",
    )


class SparkExecutorConfig(BaseModel):
    instances: Union[SparkExecutorFixedInstances, SparkExecutorDynamicScaling] = Field(
        default_factory=lambda: SparkExecutorFixedInstances.parse_obj(
            {"type": "fixed", "count": 1}
        ),
        description="",
        discriminator="type",
    )
    resources: Optional[Resources] = None


class SparkJob(BaseModel):
    type: Literal["spark-job"] = Field(..., description="")
    name: constr(regex=r"^[a-z](?:[a-z0-9]|-(?!-)){1,30}[a-z0-9]$") = Field(
        ..., description="Name of the job"
    )
    image: Union[SparkImage, SparkImageBuild] = Field(
        ...,
        description="The image to use for driver and executors. Must have spark installed. Spark version must match the version in the image.",
        discriminator="type",
    )
    entrypoint: Union[
        SparkJobPythonEntrypoint,
        SparkJobScalaEntrypoint,
        SparkJobJavaEntrypoint,
        SparkJobPythonNotebookEntrypoint,
        SparkJobScalaNotebookEntrypoint,
    ] = Field(..., description="", discriminator="type")
    driver_config: SparkDriverConfig
    executor_config: SparkExecutorConfig
    env: Optional[Dict[str, Any]] = Field(
        None,
        description="Configure environment variables to be injected in the service either as plain text. [Docs](https://docs.truefoundry.com/docs/env-variables)",
    )
    spark_conf: Optional[Dict[str, constr(min_length=1)]] = Field(
        None,
        description="Extra configuration properties to be passed to the spark job. [Docs](https://spark.apache.org/docs/latest/configuration.html)",
    )
    mounts: Optional[List[VolumeMount]] = Field(
        None,
        description="Configure volumes to be mounted to driver and executors. [Docs](https://docs.truefoundry.com/docs/mounting-volumes-job)",
    )
    retries: conint(ge=0, le=10) = Field(
        0,
        description="Specify the maximum number of attempts to retry a job before it is marked as failed.",
    )
    service_account: Optional[str] = Field(None, description="")
    workspace_fqn: Optional[str] = Field(
        None, description="Fully qualified name of the workspace"
    )


class Volume(BaseModel):
    type: Literal["volume"] = Field(..., description="")
    name: constr(regex=r"^[a-z](?:[a-z0-9]|-(?!-)){1,30}[a-z0-9]$") = Field(
        ..., description="Name of the Volume. This will be set as the volume name."
    )
    config: Union[DynamicVolumeConfig, StaticVolumeConfig] = Field(
        ..., description="", discriminator="type"
    )
    volume_browser: Optional[VolumeBrowser] = None
    workspace_fqn: Optional[str] = Field(
        None, description="Fully qualified name of the workspace"
    )


class WorkerConfig(BaseModel):
    input_config: Union[
        SQSInputConfig, NATSInputConfig, KafkaInputConfig, AMQPInputConfig
    ] = Field(..., description="Input Config", discriminator="type")
    output_config: Optional[
        Union[
            SQSOutputConfig,
            NATSOutputConfig,
            CoreNATSOutputConfig,
            KafkaOutputConfig,
            AMQPOutputConfig,
        ]
    ] = Field(None, description="Output Config", discriminator="type")
    num_concurrent_workers: conint(ge=1, le=10) = Field(
        1, description="Number of concurrent workers to spawn for the processor"
    )


class WorkflowAlert(BaseModel):
    """
    Describes the configuration for the workflow alerts
    """

    notification_target: Optional[Union[Email, SlackWebhook, SlackBot]] = Field(
        None, description="", discriminator="type"
    )
    on_completion: bool = Field(
        False, description="Send an alert when the job completes"
    )
    on_failure: bool = Field(True, description="Send an alert when the job fails")


class Build(BaseModel):
    """
    Describes how we build our code into a Docker image.
    """

    type: Literal["build"] = Field(..., description="")
    docker_registry: Optional[constr(regex=r"^\S+$")] = Field(
        None,
        description="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="Source code location.", discriminator="type"
    )
    build_spec: Union[DockerFileBuild, PythonBuild] = Field(
        ...,
        description="Instructions to build a container image out of the build source",
        discriminator="type",
    )


class ContainerTaskConfig(BaseModel):
    type: Literal["container-task-config"] = Field(..., description="")
    image: Union[Build, Image] = Field(
        ...,
        description="Specify whether you want to deploy a Docker image or build and deploy from source code",
        discriminator="type",
    )
    env: Optional[Dict[str, str]] = Field(
        None,
        description="Configure environment variables to be injected in the task either as plain text or secrets. [Docs](https://docs.truefoundry.com/docs/env-variables)",
    )
    resources: Optional[Resources] = None
    mounts: Optional[List[Union[SecretMount, StringDataMount, VolumeMount]]] = Field(
        None, description="Configure data to be mounted to Workflow pod(s) as a volume."
    )
    service_account: Optional[str] = Field(None, description="")


class FlyteLaunchPlan(BaseModel):
    id: FlyteLaunchPlanID
    spec: FlyteLaunchPlanSpec
    closure: Any


class JobAlert(BaseModel):
    """
    Describes the configuration for the job alerts
    """

    notification_channel: Optional[constr(min_length=1)] = Field(
        None, description="Specify the notification channel to send alerts to"
    )
    to_emails: Optional[List[constr(min_length=1)]] = Field(
        None,
        description="List of recipients' email addresses if the notification channel is Email.",
    )
    notification_target: Optional[Union[Email, SlackWebhook, SlackBot]] = Field(
        None, description="", discriminator="type"
    )
    on_start: bool = Field(False, description="Send an alert when the job starts")
    on_completion: bool = False
    on_failure: bool = Field(True, description="Send an alert when the job fails")


class PySparkTaskConfig(BaseModel):
    type: Literal["pyspark-task-config"] = Field(..., description="")
    image: TaskPySparkBuild
    driver_config: SparkDriverConfig
    executor_config: SparkExecutorConfig
    spark_conf: Optional[Dict[str, constr(min_length=1)]] = Field(
        None,
        description="Extra configuration properties to be passed to the spark job. [Docs](https://spark.apache.org/docs/latest/configuration.html)",
    )
    env: Optional[Dict[str, str]] = Field(
        None,
        description="Configure environment variables to be injected in the task either as plain text or secrets. [Docs](https://docs.truefoundry.com/docs/env-variables)",
    )
    mounts: Optional[List[VolumeMount]] = Field(
        None, description="Configure data to be mounted to Workflow pod(s) as a volume."
    )
    service_account: Optional[str] = Field(None, description="")


class BaseService(BaseModel):
    name: constr(regex=r"^[a-z](?:[a-z0-9]|-(?!-)){1,30}[a-z0-9]$") = Field(
        ...,
        description="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",
    )
    image: Union[Build, Image] = Field(
        ...,
        description="Specify whether you want to deploy a Docker image or build and deploy from source code",
        discriminator="type",
    )
    artifacts_download: Optional[ArtifactsDownload] = None
    resources: Optional[Resources] = None
    env: Optional[Dict[str, str]] = Field(
        None,
        description="Configure environment variables to be injected in the service either as plain text or secrets. [Docs](https://docs.truefoundry.com/docs/env-variables)",
    )
    ports: List[Port] = Field(
        ...,
        description="Expose the deployment to make it accessible over the internet or keep it private. Implement authentication to restrict access. [Docs](https://docs.truefoundry.com/docs/define-ports-and-domains)",
    )
    service_account: Optional[str] = None
    mounts: Optional[List[Union[SecretMount, StringDataMount, VolumeMount]]] = Field(
        None,
        description="Configure data to be mounted to service pod(s) as a string, secret or volume. [Docs](https://docs.truefoundry.com/docs/mounting-volumes-service)",
    )
    labels: Optional[Dict[str, str]] = Field(None, description="")
    kustomize: Optional[Kustomize] = None
    liveness_probe: Optional[HealthProbe] = None
    readiness_probe: Optional[HealthProbe] = None
    startup_probe: Optional[HealthProbe] = None
    workspace_fqn: Optional[str] = Field(
        None, description="Fully qualified name of the workspace"
    )


class FlyteTaskCustom(BaseModel):
    truefoundry: Union[
        PythonTaskConfig,
        ContainerTaskConfig,
        PySparkTaskConfig,
        DatabricksJobTaskConfig,
    ] = Field(..., description="", discriminator="type")


class FlyteTaskTemplate(BaseModel):
    id: FlyteTaskID
    custom: FlyteTaskCustom


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

    type: Literal["job"] = Field(..., description="")
    name: constr(regex=r"^[a-z](?:[a-z0-9]|-(?!-)){1,30}[a-z0-9]$") = Field(
        ..., description="Name of the job"
    )
    image: Union[Build, Image] = Field(
        ...,
        description="Specify whether you want to deploy a Docker image or build and deploy from source code",
        discriminator="type",
    )
    trigger: Union[Manual, Schedule] = Field(
        default_factory=lambda: Manual.parse_obj({"type": "manual"}),
        description="Specify the trigger",
        discriminator="type",
    )
    trigger_on_deploy: Optional[bool] = Field(
        None, description="Trigger the job after deploy immediately"
    )
    params: Optional[List[Param]] = Field(
        None, description="Configure params and pass it to create different job runs"
    )
    env: Optional[Dict[str, str]] = Field(
        None,
        description="Configure environment variables to be injected in the service either as plain text or secrets. [Docs](https://docs.truefoundry.com/docs/env-variables)",
    )
    resources: Optional[Resources] = None
    alerts: Optional[List[JobAlert]] = Field(
        None,
        description="Configure alerts to be sent when the job starts/fails/completes",
    )
    retries: conint(ge=0, le=10) = Field(
        0,
        description="Specify the maximum number of attempts to retry a job before it is marked as failed.",
    )
    timeout: Optional[conint(le=432000, gt=0)] = Field(
        None, description="Job timeout in seconds."
    )
    concurrency_limit: Optional[PositiveInt] = Field(
        None, description="Number of runs that can run concurrently"
    )
    service_account: Optional[str] = Field(None, description="")
    mounts: Optional[List[Union[SecretMount, StringDataMount, VolumeMount]]] = Field(
        None,
        description="Configure data to be mounted to job pod(s) as a string, secret or volume. [Docs](https://docs.truefoundry.com/docs/mounting-volumes-job)",
    )
    labels: Optional[Dict[str, str]] = Field(None, description="")
    kustomize: Optional[Kustomize] = None
    workspace_fqn: Optional[str] = Field(
        None, description="Fully qualified name of the workspace"
    )


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

    type: Literal["service"] = Field(..., description="")
    replicas: Union[confloat(ge=0.0, le=500.0), ServiceAutoscaling] = Field(
        1,
        description="Deploy multiple instances of your pods to distribute incoming traffic across them, ensuring effective load balancing.",
    )
    auto_shutdown: Optional[Autoshutdown] = None
    allow_interception: bool = Field(
        False,
        description="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="Strategy to dictate how a rollout should happen when a new release for this service is made [Docs](https://docs.truefoundry.com/docs/rollout-strategy)",
        discriminator="type",
    )


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

    type: Literal["async-service"] = Field(..., description="")
    replicas: Union[confloat(ge=0.0, le=500.0), AsyncServiceAutoscaling] = Field(
        1,
        description="Deploy multiple instances of your pods to distribute incoming traffic across them, ensuring effective load balancing.",
    )
    rollout_strategy: Optional[Rolling] = None
    worker_config: WorkerConfig
    sidecar: Optional[AsyncProcessorSidecar] = None


class FlyteTask(BaseModel):
    template: FlyteTaskTemplate
    description: Optional[Any] = None


class Workflow(BaseModel):
    """
    Describes the configuration for the worflow
    """

    type: Literal["workflow"] = Field(..., description="")
    name: constr(regex=r"^[a-z](?:[a-z0-9]|-(?!-)){1,30}[a-z0-9]$") = Field(
        ..., description="Name of the workflow"
    )
    source: Union[LocalSource, RemoteSource] = Field(
        ...,
        description="Source Code for the workflow, either local or remote",
        discriminator="type",
    )
    workflow_file_path: str = Field(
        ..., description="Path to the workflow file relative to the project root path"
    )
    flyte_entities: Optional[List[Union[FlyteTask, FlyteWorkflow, FlyteLaunchPlan]]] = (
        Field(None, description="")
    )
    alerts: Optional[List[WorkflowAlert]] = Field(None, description="")


class ApplicationSet(BaseModel):
    """
    Describes the configuration for the application set
    """

    type: Literal["application-set"] = Field(..., description="")
    name: str = Field(..., description="Name of the application set.")
    components: Optional[List[Union[Service, AsyncService, Job, Helm]]] = Field(
        None, description="Array of components with their specifications."
    )
    template: Optional[str] = Field(
        None, description="Template to be used for the application set."
    )
    values: Optional[Dict[str, Any]] = Field(
        None,
        description="Values to be used to render components for the application set.",
    )
    workspace_fqn: Optional[str] = Field(
        None, description="Fully qualified name of the workspace"
    )
    convert_template_manifest: Optional[bool] = Field(
        None,
        description="Flag to indicate if the template manifest should be converted to TrueFoundry manifest",
    )


class Application(BaseModel):
    __root__: Union[
        Service,
        AsyncService,
        Job,
        Notebook,
        Codeserver,
        SSHServer,
        RStudio,
        Helm,
        Volume,
        ApplicationSet,
        Workflow,
        SparkJob,
    ] = Field(..., description="", discriminator="type")
