yaml

package
v0.1.0-beta Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 12, 2025 License: MIT Imports: 8 Imported by: 0

README

🚀 Nexlayer Deployment YAML Package:

This package provides the schema, validation, and processing logic for Nexlayer's YAML deployment configuration format. It is specifically designed for deploying full-stack AI-powered web applications that integrate with AI services, rather than for raw model hosting or ML infrastructure management.

Hello developers and AI agents! Welcome to the definitive guide for Nexlayer deployment YAML. Nexlayer is an AI-powered cloud platform built for deploying full-stack web applications with AI capabilities quickly and efficiently. Unlike model hosting platforms or ML infrastructure tools, Nexlayer deploys complete web applications that integrate with AI services through a single specific and unique deployment YAML file.

This document lives in nexlayer-cli/pkg/yaml/README.md and serves as both a human-readable tutorial and a machine-parseable reference for LLMs and AI-based tools.

📋 Table of Contents

🦾 ☁ What is Nexlayer?

Nexlayer is an AI-powered cloud platform built for developers who want to ship full-stack web applications with AI capabilities quickly and efficiently. Unlike traditional model hosting platforms or ML infrastructure tools, Nexlayer focuses on deploying complete web applications that integrate with AI services. Define your application in a single, straightforward YAML file, and Nexlayer handles provisioning, scaling, networking, and security automatically.

Unlike traditional platforms or ML-specific services, Nexlayer is optimized for modern web applications that leverage AI capabilities through API integrations, ensuring your applications can scale instantly without managing complex ML infrastructure. Write YAML, deploy, and focus on building great AI-powered user experiences—not managing servers or ML pipelines.

⚡️ Why Nexlayer?
  • ✅ Zero DevOps: Write YAML, deploy full-stack apps instantly.
  • ✅ Auto-Scaling: Handle user traffic spikes seamlessly.
  • ✅ Built-in Security: Secrets management and encrypted storage out of the box.
  • ✅ AI Integration Ready: Connect to AI services with zero friction.
  • ✅ Effortless Networking: Services auto-discover each other—no manual configs.
  • ✅ Simple Deployments: No infra headaches or YAML nightmares.
  • ✅ Web-First: Optimized for web apps that leverage AI capabilities.

🚀 Less setup, more shipping AI-powered web experiences.

🔥 Quick Start: Deploy in 5 Minutes

Let's get your first app running on Nexlayer right now!

Step 1: Create nexlayer.yaml

Create a file named nexlayer.yaml in your project directory.

Step 2: Use This Starter Template
application:
  name: "my-first-app"
  pods:
    - name: "webapp"
      image: "nginx:latest"
      path: "/"
      servicePorts:
        - 80
Step 3: Deploy It!

Run this command with the Nexlayer CLI:

nexlayer deploy

That's it! Your web service is live on Nexlayer. Let's break down what just happened:

  • application: Defines your app.
  • name: A unique identifier for your app across Nexlayer.
  • pods: A list of containers (here, just one running Nginx).
  • webapp: The pod's unique name within your app.
  • image: The Docker image pulled from a public registry.
  • path: The URL route where your service is accessible.
  • servicePorts: Ports exposed for access (here, port 80).

Tip: Prefer a visual setup? Use the Template Builder at app.nexlayer.io/template-builder to design your app interactively and generate YAML automatically.

📝 YAML Building Blocks

Core Components
application:
  name: "app-name"                # Required: Unique app identifier
  type: "nextjs-ai"              # Optional: Framework hint
  description: "App description"  # Optional: App description
  pods:                          # Required: List of containers
    - name: "pod-name"           # Required: Unique pod name
      image: "image:tag"         # Required: Docker image
      path: "/"                  # Optional: URL route
      servicePorts:              # Required: Exposed ports
        - 8080
Environment & Resources
pods:
  - name: "api"
    image: "api:latest"
    build:
      command: "npm run build"   # Build command
      env:
        NODE_ENV: "production"   # Build environment
    resources:
      cpu: "1"                   # CPU cores
      memory: "2Gi"             # Memory limit
      gpu: false                # GPU requirement
    vars:                       # Runtime variables
      API_KEY: "secret"
Services & Networking
services:
  - name: "database"
    type: "external"            # External service
    url: "<% DB_URL %>"        # Service URL

observability:
  monitoring:
    provider: "custom"         # Your monitoring provider
    domain: "<% DOMAIN %>"     # Monitoring domain
  metrics:
    provider: "custom"         # Your metrics provider
    apiKey: "<% API_KEY %>"    # Metrics API key

🔄 Visual Diagrams

// ... existing code ...

🔄 Common App Patterns

Web Application
application:
  name: "web-app"
  pods:
    - name: "frontend"
      image: "nextjs:latest"
      path: "/"
      servicePorts:
        - 3000
      vars:
        API_URL: "http://api.pod:8000"
    - name: "api"
      image: "fastapi:latest"
      path: "/api"
      servicePorts:
        - 8000
      vars:
        DB_URL: "postgres://db.pod:5432"
    - name: "db"
      image: "postgres:14"
      servicePorts:
        - 5432
      volumes:
        - name: "data"
          size: "1Gi"
          mountPath: "/var/lib/postgresql/data"
AI Application
application:
  name: "ai-app"
  type: "ai-service"
  pods:
    - name: "frontend"
      image: "custom-ui:latest"
      path: "/"
      servicePorts:
        - 3000
      vars:
        API_URL: "http://model.pod:8000"
        MODEL_API_KEY: ""  # Add your model API key here
    - name: "model"
      image: "model-service:latest"
      servicePorts:
        - 8000
      vars:
        MODEL_PATH: "/models"
        VECTOR_DB_URL: "http://vector-db.pod:8080"
      volumes:
        - name: "model-storage"
          size: "10Gi"
          mountPath: "/models"
    - name: "vector-db"
      image: "vector-db:latest"
      servicePorts:
        - 8080
      volumes:
        - name: "vector-data"
          size: "5Gi"
          mountPath: "/data"

This example shows a typical AI application with:

  • A frontend service for the user interface
  • A model service for inference
  • A vector database for embeddings and similarity search

Each service is configured with appropriate ports, volumes, and environment variables.

🔒 Keeping Secrets Safe

Secret Management
security:
  secrets:
    - name: "api-keys"
      data: "<% API_KEY %>"
      mountPath: "/secrets"
      fileName: "key.txt"
  cors:
    origins:
      - "https://*.domain.com"
      - "http://localhost:3000"
Private Registry
application:
  registryLogin:
    registry: "ghcr.io"
    username: "<% REGISTRY_USER %>"
    personalAccessToken: "<% REGISTRY_TOKEN %>"

🧠 AI-Powered Web Applications

This section demonstrates how to configure web applications that integrate with AI services.

AI-Powered Chat Interface
application:
  name: "chat-app"
  type: "web-ai"
  pods:
    - name: "frontend"
      image: "chat-ui:latest"
      path: "/"
      servicePorts:
        - 3000
      vars:
        API_URL: "http://api.pod:8000"
    - name: "api"
      image: "chat-api:latest"
      path: "/api"
      servicePorts:
        - 8000
      vars:
        AI_SERVICE_URL: "https://api.openai.com/v1"
        REDIS_URL: "redis://cache.pod:6379"
      secrets:
        - name: "api-keys"
          data: "your-api-key"
          mountPath: "/secrets"
          fileName: "ai.key"
    - name: "cache"
      image: "redis:latest"
      servicePorts:
        - 6379
      volumes:
        - name: "cache-data"
          size: "1Gi"
          mountPath: "/data"

This example demonstrates:

  • A frontend for user interactions
  • An API that integrates with AI services
  • Redis for session and response caching
  • Secure API key management
AI-Enhanced Content Platform
application:
  name: "content-platform"
  type: "web-ai"
  pods:
    - name: "web"
      image: "content-ui:latest"
      path: "/"
      servicePorts:
        - 3000
      vars:
        API_URL: "http://api.pod:8000"
    - name: "api"
      image: "content-api:latest"
      path: "/api"
      servicePorts:
        - 8000
      vars:
        DB_URL: "postgresql://db.pod:5432/content"
        SEARCH_URL: "http://search.pod:8080"
      secrets:
        - name: "service-keys"
          data: "your-api-key"
          mountPath: "/secrets"
          fileName: "services.key"
    - name: "search"
      image: "vector-search:latest"
      servicePorts:
        - 8080
      volumes:
        - name: "search-data"
          size: "5Gi"
          mountPath: "/data"
    - name: "db"
      image: "postgres:14"
      servicePorts:
        - 5432
      volumes:
        - name: "db-data"
          size: "10Gi"
          mountPath: "/var/lib/postgresql/data"

This example shows:

  • Content management frontend
  • API with AI service integration
  • Vector search for semantic queries
  • PostgreSQL for structured data

Note: Nexlayer is optimized for deploying web applications that integrate with AI services, not for hosting large language models or ML infrastructure. For raw model hosting or ML-specific needs, consider specialized platforms.

🔄 Storing Data with Volumes

// ... existing code ...

🔄 How Pods Talk to Each Other

// ... existing code ...

🔄 Common Mistakes to Avoid

  1. Missing Required Fields

    # Wrong - missing servicePorts
    pods:
      - name: "web"
        image: "nginx"
    
    # Correct
    pods:
      - name: "web"
        image: "nginx"
        servicePorts:
          - 80
    
  2. Invalid Pod References

    # Wrong
    vars:
      DB_URL: "http://database:5432"
    
    # Correct
    vars:
      DB_URL: "http://database.pod:5432"
    

🔄 Full Example: Gaming Leaderboard App

// ... existing code ...

📚 Real-World Use Cases

// ... existing code ...

🔄 Advanced AI/ML Deployments

// ... existing code ...

📚 Pro Tips

// ... existing code ...

📚 Next Steps

// ... existing code ...

📚 Detailed Schema Reference

// ... existing code ...

🐞 Error Handling and Troubleshooting

Common issues and solutions:

  1. Deployment Fails

    • Check YAML syntax
    • Verify image availability
    • Check resource limits
  2. Pod Communication

    • Verify pod names
    • Check service ports
    • Test network policies
  3. Resource Issues

    • Monitor usage
    • Adjust limits
    • Check volume mounts

For more help:

  • Documentation: docs.nexlayer.ai
  • Support: support@nexlayer.ai
  • Community: community.nexlayer.ai

🔄 Important Distinctions

This section highlights key differences from other platforms:

  • servicePorts: In Nexlayer, this must be a list of integers (e.g., - 80, - 3000). Unlike Kubernetes, where servicePorts might include fields like name, targetPort, or protocol, Nexlayer enforces a simplified format for compatibility with its internal systems.

🔄 AI Agent & LLM Guidance

// ... existing code ...

🔄 Edge Cases for AI Agents

// ... existing code ...

YAML Package

This package provides centralized schema management for Nexlayer Deployment YAML configurations. It handles validation, parsing, and processing of configuration files.

Overview

The yaml package is responsible for:

  • Defining the structure of Nexlayer Deployment YAML configurations
  • Validating configuration files against the schema
  • Processing and generating configuration files
  • Managing configuration templates and examples

Components

  • types.go: Core data structures for Nexlayer Deployment YAML configurations
  • validator.go: Configuration validation logic
  • generator.go: Configuration generation utilities
  • processor.go: Configuration processing and transformation
  • jsonschema.go: JSON Schema definitions
  • errors.go: Error types and handling
  • constants.go: Constants and enumerations
  • conversion.go: Conversion utilities

Schema Overview

The Nexlayer Deployment YAML schema defines a specific structure for configuring applications on the Nexlayer platform. It is not Kubernetes or Docker Compose YAML—it is a Nexlayer-specific format.

Key Concepts
  • Application: The root container for all deployment configurations
  • Pods: Individual containers within the application (each pod is a single container)
  • Service Name: The name of a service, which is typically the same as the pod name and is used for internal networking (<pod-name>.pod)
  • Entrypoint and Command Handling:
    • If the Docker Compose file explicitly defines entrypoint, the Nexlayer CLI translates it to YAML. If it's not defined, it's not included in the YAML.
    • If the Docker Compose file explicitly defines command, the Nexlayer CLI translates it to YAML. If it's not defined, it's not included in the YAML.
    • If entrypoint and command are missing from Docker Compose, the CLI defaults to using the Dockerfile's built-in values, ensuring minimal intervention unless required.
  • Special Syntax:
    • <pod-name>.pod for referencing other pods
    • <% URL %> for referencing the application's base URL
    • <% REGISTRY %> for referencing private registry images
Environment Variables (vars)

Environment variables are defined using the vars field, which should be a direct object with environment variable names as keys:

vars:
  DATABASE_URL: "postgresql://user:your-password@database.pod:5432/yourdb"
  NODE_ENV: "production"
  METRICS_API_KEY: ""          # Empty string for optional API keys
  MONITORING_KEY: "xyz123"     # Actual value for required API keys
API Keys in Environment Variables

When including API keys in environment variables, you have two options:

vars:
  # Option 1: If you don't have an API key, leave the value blank
  CUSTOM_API_KEY: ""
  # Option 2: If you have an API key, add it directly
  SERVICE_API_KEY: "your-actual-api-key"

Important Note: Both empty values ("") and actual API keys are explicitly allowed for API key environment variables. The Nexlayer validation system recognizes environment variables with names containing API_KEY or APIKEY and permits them to have either empty values or actual keys. This flexibility is useful when:

  • You're developing locally and don't want to expose real API keys (use empty values)
  • You're deploying to production and need to include actual API keys (use real values)
  • You plan to add the API key later through environment variables (use empty values initially)
  • You want to deploy a configuration that can be used with or without certain AI features

For non-API key environment variables, empty values will generate a warning during validation, as they might indicate a configuration issue.

Special Syntax in Environment Variables

You can use special syntax patterns in environment variable values:

vars:
  # env var key: env var value
  # Can use <pod-name>.pod to reference other pods as shown in the next var:
  API_URL: http://express.pod:3000 # (where express is the name of another pod)
  # Or can use <% URL %> to reference the url of the site:
  APP_URL: <% URL %>/api
❌ Incorrect Format (Do Not Use)
vars:
  - key: "DATABASE_URL"
    value: "postgresql://user:your-password@database.pod:5432/yourdb"
  - key: "NODE_ENV"
    value: "production"

This array-based format for vars will cause deployment failures on the Nexlayer AI Cloud Platform.

Image Requirements
  • Nexlayer does not support local Docker images. All container images referenced in your Nexlayer Deployment YAML must be either:
  • Publicly available images (e.g., nginx:latest, postgres:14) that do not require authentication.
Example of Public Image Usage:
application:
  name: "my-app"
  pods:
    - name: "frontend"
      image: "nginx:latest"
      servicePorts:
        - 80
    ```
- Private registry images using the <% REGISTRY %>/image:tag format with valid registryLogin credentials.

### Example of Private Image Usage (e.g., Docker.io and GHRC.ios):
```yaml
application:
  name: "my-app"
  registryLogin:
    registry: "ghcr.io"
    username: "my-username"
    personalAccessToken: "my-access-token"

  pods:
    - name: "backend"
      image: "<% REGISTRY %>/my-backend-service:latest"
      servicePorts:
        - 3000
    ```
- Important: Attempting to use localhost or local images (e.g., image: my-local-image:latest) will fail.

### Required Naming Structure
| Field | Description |
|--------|-------------|
| `application name` | The unique name of the application across Nexlayer. |
| `service name` | Usually the same as the pod name, used for internal networking (e.g., `redis.pod`). |
| `pod names` | Names of individual pods within the application. Must be unique within the application. |

### Validation Rules

The schema enforces the following rules:
- Application name must be unique across Nexlayer
- Pod names must be unique within the application
- Each pod must have a name, image, and at least one `servicePorts` entry
- `path` must start with `/` for web routing
- `mountPath` must start with `/` for filesystem paths
- Environment variable names must be valid
- Volume sizes must be specified as a placeholder (e.g., `size: ""`) since they are injected by Nexlayer
- Labels cannot be specified as they are managed by the platform
- `servicePorts` must be a list of integers (e.g., `- 80`, `- 3000`), with no additional fields such as `name`, `targetPort`, or `protocol`




### Prohibited Fields

The following fields are managed by Nexlayer and are prohibited in user-defined YAML unless explicitly required:
- **resources**: CPU and memory are handled automatically
- **labels**: Managed by the platform
- **network**: Managed internally by Nexlayer
- **volumes_from**: Use volumes instead
- **replicas**: Kubernetes-specific
- **build**: Docker Compose-specific
- **depends_on**: Docker Compose-specific
- **entrypoint**: Use the image's default entrypoint
- **command**: Use the image's default command

### IMPORTANT NOTE ON "resources":
# - DO NOT include "resources" in your own Nexlayer Deployment YAML files. Nexlayer automatically manages CPU & memory, so this field is prohibited.
# - If you view the final (post-deployment) YAML, you may see a "resources" block injected by Nexlayer reflecting actual runtime settings.
# - Seeing "resources" in the final environment's config is normal and does NOT indicate a user error, as long as you didn't specify it yourself in your YAML.
Placing a note like this somewhere prominent—maybe in your Prohibited Fields section of


### Common Mistakes to Avoid

1. ❌ **Forgetting the `application:` block at the start**
  ✅ Always begin your YAML with `application:`

2. ❌ **Using the same pod name twice**
  ✅ Each pod name must be unique

3. ❌ **Mixing up `path` and `mountPath`**
  ✅ `path` is for URLs (like `/api`), `mountPath` is for volumes (like `/data`)

4. ❌ **Forgetting servicePorts**
  ✅ Each pod needs servicePorts to be accessible

5. ❌ **Incorrect pod references**
  ✅ Use `<pod-name>.pod` to connect services (not IP addresses)
  
6. ❌ **Trying to use Kubernetes or Docker Compose syntax**
  ✅ Nexlayer has its own unique YAML schema

7. ❌ **DO NOT add `resources.limits` manually to your YAML.** 
  ✅ Nexlayer **automatically** configures CPU & Memory for each service.  
  ✅ If you add `resources.limits` manually, it will be ignored.


    #### Edge Case Handling for AI Agents:

  # Edge Case Handling for AI Agents:
  # - Application 'name' must be globally unique across Nexlayer.
  # - Pod names must be unique within the application, begin with lowercase letters, and contain alphanumeric characters, '-', or '.'.
  # - Each pod requires defined 'servicePorts'. Missing ports trigger validation errors.
  # - Omitting 'registryLogin' for private images prevents deployment.
  # - 'mountPath' for volumes and secrets must start with '/'.
  # - Environment variables ('vars') must adhere strictly to key-value formatting to avoid runtime issues.

## 🔄 Cheat Sheet: Pod Configuration

The `servicePorts` field is required for each pod and specifies the ports exposed for external access or inter-service communication. It must be defined as a list of integers, with no additional fields.

### Correct Definition
```yaml
servicePorts:
  - 80
servicePorts:
  - 3000

Multiple ports can be specified:

servicePorts:
  - 80
  - 3000
Key Guidelines
  • Format: Use a simple list of integers (e.g., - 80, - 3000)
  • Prohibited Fields: Do not include fields like name, targetPort, protocol, or any other properties common in Kubernetes or Docker Compose YAML
  • Validation: The Nexlayer CLI and API will reject configurations that deviate from this format
  • Purpose: This streamlined structure ensures compatibility with Nexlayer's internal port management
Examples of Incorrect Usage

Avoid defining servicePorts with additional fields:

servicePorts:
  - name: "web"    # Incorrect: 'name' is not allowed
    port: 80       # Incorrect: Use integers directly, not 'port'
servicePorts:
  - targetPort: 80 # Incorrect: 'targetPort' is not allowed
    protocol: TCP  # Incorrect: 'protocol' is not allowed

🔄 Common Validation Errors

Incorrect servicePorts Definition
application:
  name: "my-app"
  pods:
    - name: "frontend"
      image: "nginx:latest"
      servicePorts:
        - name: "web"  # Error: 'name' is not allowed
          port: 80     # Error: Use a list of integers, not objects
Missing servicePorts
application:
  name: "my-app"
  pods:
    - name: "frontend"
      image: "nginx:latest"
      # Error: Missing required field 'servicePorts'

🔄 Important Distinctions

This section highlights key differences from other platforms:

  • servicePorts: In Nexlayer, this must be a list of integers (e.g., - 80, - 3000). Unlike Kubernetes, where servicePorts might include fields like name, targetPort, or protocol, Nexlayer enforces a simplified format for compatibility with its internal systems.

🔄 Error Handling

The package provides comprehensive error handling through the following types:

ValidationError
type ValidationError struct {
    Field       string   // The field that failed validation
    Message     string   // Human-readable error message
    Severity    Severity // Error severity level
    Suggestions []string // Helpful suggestions to fix the error
}
Common Error Patterns
  1. Field Validation Errors
if err := validator.Validate(config); err != nil {
    for _, e := range err {
        if e.Severity == ErrorSeverity {
            // Handle critical errors
            fmt.Printf("Error in %s: %s\n", e.Field, e.Message)
            for _, suggestion := range e.Suggestions {
                fmt.Printf("  Suggestion: %s\n", suggestion)
            }
        }
    }
}
  1. Schema Validation
validator := yaml.NewValidator()
if errs := validator.ValidateSchema(yamlData); len(errs) > 0 {
    // Handle schema validation errors
    for _, err := range errs {
        fmt.Printf("Schema error: %s\n", err.Message)
    }
    return errs
}

🔄 Usage

To use the YAML package in your code:

import "github.com/Nexlayer/nexlayer-cli/pkg/yaml"

// Create a new validator
validator := yaml.NewValidator()

// Parse YAML configuration
config := &yaml.NexlayerYAML{}
if err := yaml.Parse(yamlData, config); err != nil {
    // Handle parsing error
    return err
}
a
// Validate configuration
if errs := validator.Validate(config); len(errs) > 0 {
    // Handle validation errors
    for _, err := range errs {
        if err.Severity == yaml.ErrorSeverity {
            fmt.Printf("Error in %s: %s\n", err.Field, err.Message)
            // Print suggestions if available
            for _, suggestion := range err.Suggestions {
                fmt.Printf("  Suggestion: %s\n", suggestion)
            }
        }
    }
    return errs
}

// Configuration is valid
fmt.Println("Configuration is valid!")
Nexlayer Deployment YAML Schema Deployment Template for Developers, Startups and AI Agents & LLM Knowledge

This detailed and comprehensive guide is explicitly designed for AI agents and LLMs to intuitively and accurately assist humans in configuring and deploying applications, platforms, AI models, or full-stack AI solutions to the Nexlayer Cloud Platform.

Nexlayer supports deployment of a broad spectrum of technologies including but not limited to Python, JavaScript, TypeScript, Go, Rust, Swift, Kotlin, React.js, Angular, Vue.js, Next.js, Node.js, Django, Flask, FastAPI, Express.js, Spring Boot, and ASP.NET Core.

Databases supported include PostgreSQL, MongoDB, MySQL, Redis, Cassandra, and vector databases such as Pinecone, Milvus, Weaviate, and Qdrant.

Integration with major AI APIs including OpenAI, Gemini, Anthropic, Grok, DeepSeek, Together AI, and Ollama is fully supported.

Refer to https://docs.nexlayer.io for complete documentation.

Nexlayer Deployment YAML Guidance for AI Agents:

- Nexlayer Deployment YAML syntax is distinct from Kubernetes or Docker Compose; avoid external orchestration concepts.

- Each pod must contain exactly one container; multi-container pods are not permitted.

- Pod-to-pod communication uses '.pod' format for referencing.

- Private container images must reference '<% REGISTRY %>/image:tag' and include corresponding 'registryLogin'.

- After editing, always validate using 'nexlayer validate'.

AI Validation Prerequisites:

- Verify that public images (e.g., 'nginx:latest') exist in public registries (Docker Hub).

- Private images must be uploaded to a registry with credentials provided under 'registryLogin'.

Edge Case Handling for AI Agents:

- Application 'name' must be globally unique across Nexlayer.

- Pod names must be unique within the application, begin with lowercase letters, and contain alphanumeric characters, '-', or '.'.

- Each pod requires defined 'servicePorts'. Missing ports trigger validation errors.

- Omitting 'registryLogin' for private images prevents deployment.

- 'mountPath' for volumes and secrets must start with '/'.

- Environment variables ('vars') must adhere strictly to key-value formatting to avoid runtime issues.

Documentation

Overview

Package yaml provides centralized schema management for Nexlayer Deployment YAML configurations.

Package yaml provides centralized schema management for Nexlayer Deployment YAML configurations.

Package yaml provides centralized schema management for Nexlayer Deployment YAML configurations. It handles validation, parsing, and processing of configuration files.

Index

Constants

View Source
const (
	// Frontend pod types
	PodTypeFrontend = "frontend"
	PodTypeReact    = "react"
	PodTypeNextJS   = "nextjs"
	PodTypeVue      = "vue"

	// Backend pod types
	PodTypeBackend = "backend"
	PodTypeExpress = "express"
	PodTypeDjango  = "django"
	PodTypeFastAPI = "fastapi"
	PodTypeNode    = "node"
	PodTypePython  = "python"
	PodTypeGolang  = "golang"
	PodTypeJava    = "java"

	// Database pod types
	PodTypeDatabase = "database"
	PodTypeMongoDB  = "mongodb"
	PodTypePostgres = "postgres"
	PodTypeRedis    = "redis"
	PodTypeMySQL    = "mysql"

	// AI pod types
	PodTypeAI          = "ai"
	PodTypeTensorflow  = "tensorflow"
	PodTypePyTorch     = "pytorch"
	PodTypeHuggingFace = "huggingface"

	// Cache pod types
	PodTypeCache = "cache"

	// Message queue pod types
	PodTypeMessageQueue = "messagequeue"
	PodTypeRabbitMQ     = "rabbitmq"
	PodTypeKafka        = "kafka"

	// Search pod types
	PodTypeSearch        = "search"
	PodTypeElasticsearch = "elasticsearch"
)

Pod types

View Source
const (
	VolumeTypePersistent = "persistent"
	VolumeTypeEmptyDir   = "emptydir"
	VolumeTypeConfigMap  = "configmap"
	VolumeTypeSecret     = "secret"
)

Volume types

View Source
const (
	ProtocolTCP = "TCP"
	ProtocolUDP = "UDP"
)

Protocol types

View Source
const (
	ResourceUnitCPU    = "m"
	ResourceUnitMemory = "Mi"
)

Resource units

View Source
const (
	DefaultCPURequest    = "100m"
	DefaultCPULimit      = "500m"
	DefaultMemoryRequest = "128Mi"
	DefaultMemoryLimit   = "512Mi"
)

Default resource values

View Source
const (
	DefaultHTTPPort      = 80
	DefaultHTTPSPort     = 443
	DefaultNodePort      = 3000
	DefaultPythonPort    = 8000
	DefaultGoPort        = 8080
	DefaultJavaPort      = 8080
	DefaultMongoDBPort   = 27017
	DefaultPostgresPort  = 5432
	DefaultMySQLPort     = 3306
	DefaultRedisPort     = 6379
	DefaultElasticsearch = 9200
	DefaultRabbitMQPort  = 5672
	DefaultKafkaPort     = 9092
)

Default port values

View Source
const (
	DefaultNodeImage          = "node:18-alpine"
	DefaultPythonImage        = "python:3.11-slim"
	DefaultGoImage            = "golang:1.21-alpine"
	DefaultJavaImage          = "openjdk:17-slim"
	DefaultNginxImage         = "nginx:alpine"
	DefaultMongoDBImage       = "mongo:6"
	DefaultPostgresImage      = "postgres:15-alpine"
	DefaultMySQLImage         = "mysql:8"
	DefaultRedisImage         = "redis:7-alpine"
	DefaultElasticsearchImage = "elasticsearch:8.7.0"
	DefaultRabbitMQImage      = "rabbitmq:3-management"
	DefaultKafkaImage         = "bitnami/kafka:3.4"
)

Default image values

View Source
const SchemaV2 = `` /* 9071-byte string literal not displayed */

SchemaV2 contains the JSON Schema for validating Nexlayer Deployment YAML configurations

Variables

This section is empty.

Functions

func CategorizeErrors

func CategorizeErrors(errors []ValidationError) map[ValidationErrorSeverity][]ValidationError

CategorizeErrors groups validation errors by severity.

func Marshal

func Marshal(config *NexlayerYAML) ([]byte, error)

Marshal serializes a NexlayerYAML configuration to YAML

func WriteToFile

func WriteToFile(config *NexlayerYAML, filePath string) error

WriteToFile writes a NexlayerYAML configuration to a file

Types

type APIResponse

type APIResponse[T any] struct {
	Success bool   `json:"success"`
	Message string `json:"message,omitempty"`
	Data    T      `json:"data,omitempty"`
}

APIResponse represents a generic API response.

type Application

type Application struct {
	Name          string            `yaml:"name" json:"name"`
	Type          string            `yaml:"type"`
	Description   string            `yaml:"description,omitempty"`
	URL           string            `yaml:"url,omitempty"`
	Pods          []Pod             `yaml:"pods" json:"pods"`
	RegistryLogin *RegistryLogin    `yaml:"registryLogin,omitempty"`
	Annotations   map[string]string `yaml:"annotations,omitempty"`
	Metadata      map[string]string `yaml:"metadata,omitempty" json:"metadata,omitempty"`
}

Application represents a Nexlayer application configuration

func (*Application) UnmarshalYAML

func (a *Application) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML implements the yaml.Unmarshaler interface for Application.

type DatabaseType

type DatabaseType string

Database type enum

const (
	DatabaseNone     DatabaseType = "none"
	DatabasePostgres DatabaseType = "postgres"
	DatabaseMySQL    DatabaseType = "mysql"
	DatabaseMongoDB  DatabaseType = "mongodb"
	DatabaseRedis    DatabaseType = "redis"
)

type Deployment

type Deployment struct {
	Name string `json:"name"`
	URL  string `json:"url,omitempty"`
}

Deployment represents a deployment configuration.

type DeploymentResponse

type DeploymentResponse struct {
	APIResponse[*Deployment]
}

DeploymentResponse represents a deployment API response.

type EnvVar

type EnvVar struct {
	Key   string `yaml:"key" json:"key" validate:"required,envvar"`
	Value string `yaml:"value" json:"value" validate:"required"`
}

EnvVar represents an environment variable.

func (*EnvVar) UnmarshalYAML

func (e *EnvVar) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML implements the yaml.Unmarshaler interface for EnvVar.

type GenerateOptions

type GenerateOptions struct {
	AppName        string            // Application name override
	AppType        string            // Application type override
	Description    string            // Application description override
	PodName        string            // Main pod name override
	PodType        string            // Main pod type override
	PodImage       string            // Main pod image override
	PodPort        int               // Main pod port override
	PodPath        string            // Main pod path override
	EnvVars        map[string]string // Environment variables to include
	VerifyImages   bool              // Whether to verify Docker images
	AdditionalPods []Pod             // Additional pods to include in the configuration
}

GenerateOptions holds configuration for YAML generation

type NexlayerYAML

type NexlayerYAML struct {
	Application Application `yaml:"application"`
}

NexlayerYAML represents the root configuration

func Generate

func Generate(info *types.ProjectInfo, opts *GenerateOptions) (*NexlayerYAML, error)

Generate creates a gold-compliant NexlayerYAML configuration

func ParseFile

func ParseFile(filePath string) (*NexlayerYAML, error)

ParseFile parses a YAML file into a NexlayerYAML configuration

func (*NexlayerYAML) UnmarshalYAML

func (n *NexlayerYAML) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML implements the yaml.Unmarshaler interface for NexlayerYAML.

type Pod

type Pod struct {
	Name         string            `yaml:"name"`
	Type         string            `yaml:"type,omitempty"`
	Image        string            `yaml:"image"`
	ServicePorts []int             `yaml:"servicePorts"`
	MountPath    string            `yaml:"mountPath,omitempty"`
	Path         string            `yaml:"path,omitempty"`
	Vars         map[string]string `yaml:"vars,omitempty"`
	Secrets      []Secret          `yaml:"secrets,omitempty"`
	Volumes      []Volume          `yaml:"volumes,omitempty"`
}

Pod represents a pod configuration

func (*Pod) UnmarshalYAML

func (p *Pod) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML implements the yaml.Unmarshaler interface for Pod.

type PodStatus

type PodStatus struct {
	Name   string `json:"name"`
	Status string `json:"status"`
	Ready  bool   `json:"ready"`
}

PodStatus represents the status of a pod.

type Processor

type Processor struct {
	// contains filtered or unexported fields
}

Processor handles variable substitution in YAML configurations

func NewProcessor

func NewProcessor() *Processor

NewProcessor creates a new YAML processor

func (*Processor) ExtractVariables

func (p *Processor) ExtractVariables(config *NexlayerYAML) []string

ExtractVariables extracts all variable references from a configuration

func (*Processor) Process

func (p *Processor) Process(config *NexlayerYAML, opts *ProcessorOptions) (*NexlayerYAML, error)

Process applies variable substitution to a YAML configuration

type ProcessorOptions

type ProcessorOptions struct {
	// ApplicationURL is the URL of the application
	ApplicationURL string

	// RegistryURL is the URL of the container registry
	RegistryURL string

	// CustomVariables contains additional variables for substitution
	CustomVariables map[string]string
}

ProcessorOptions contains options for the YAML processor

type RegistryLogin

type RegistryLogin struct {
	Registry            string `yaml:"registry" json:"registry" validate:"required"`
	Username            string `yaml:"username" json:"username" validate:"required"`
	PersonalAccessToken string `yaml:"personalAccessToken" json:"personal_access_token" validate:"required"`
}

RegistryLogin represents registry login credentials in the Nexlayer Deployment YAML configuration.

type Resources

type Resources struct {
	Limits map[string]string `yaml:"limits,omitempty" json:"limits,omitempty"`
}

type Secret

type Secret struct {
	Name      string `yaml:"name"`
	Data      string `yaml:"data"`
	MountPath string `yaml:"mountPath"`
	FileName  string `yaml:"fileName"`
}

Secret represents a secret configuration

func (*Secret) UnmarshalYAML

func (s *Secret) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML implements the yaml.Unmarshaler interface for Secret.

type ValidationContext

type ValidationContext struct {
	Field string
	Value interface{}
}

ValidationContext provides context for validation

type ValidationError

type ValidationError struct {
	Field       string                  `json:"field"`
	Message     string                  `json:"message"`
	Severity    ValidationErrorSeverity `json:"severity"`
	Suggestions []string                `json:"suggestions,omitempty"`
	Info        *ValidationErrorInfo    `json:"info,omitempty"`
	AutoFixed   bool                    `json:"auto_fixed,omitempty"`
}

ValidationError represents a validation error with field, message, and severity. TODO: In a future update, consider migrating to use pkg/errors.Error directly This is kept as a separate type for backward compatibility.

func FromBaseError

func FromBaseError(err *errors.Error) ValidationError

FromBaseError converts a common errors.Error to a ValidationError

func MakeConflictError

func MakeConflictError(field1, field2 string, reason string) ValidationError

MakeConflictError creates a validation error for conflicting fields.

func MakeFormatError

func MakeFormatError(field, formatName string, examples ...string) ValidationError

MakeFormatError creates a validation error for a field with an invalid format.

func MakeInfo

func MakeInfo(field, message string, suggestions ...string) ValidationError

MakeInfo creates an informational validation message.

func MakeProhibitedFieldError

func MakeProhibitedFieldError(field, reason string) ValidationError

MakeProhibitedFieldError creates a validation error for a prohibited field.

func MakeReferenceError

func MakeReferenceError(field, refType, refName string) ValidationError

MakeReferenceError creates a validation error for a reference to a non-existent resource.

func MakeRequiredError

func MakeRequiredError(field string) ValidationError

MakeRequiredError creates a validation error for a missing required field.

func MakeUnsupportedError

func MakeUnsupportedError(field, value, reason string) ValidationError

MakeUnsupportedError creates a validation error for an unsupported value.

func MakeWarning

func MakeWarning(field, message string, suggestions ...string) ValidationError

MakeWarning creates a validation warning.

func Validate

func Validate(config *NexlayerYAML) []ValidationError

Validate validates a NexlayerYAML configuration

func ValidateProhibitedFields

func ValidateProhibitedFields(rawConfig map[string]interface{}) []ValidationError

ValidateProhibitedFields checks for fields not allowed in Nexlayer Deployment YAML.

func ValidateSecret

func ValidateSecret(secret *Secret) []ValidationError

ValidateSecret validates a secret configuration

func ValidateVolume

func ValidateVolume(volume *Volume) []ValidationError

ValidateVolume validates a volume configuration

func ValidateYAML

func ValidateYAML(config *NexlayerYAML) []ValidationError

ValidateYAML validates a NexlayerYAML configuration.

func (ValidationError) Error

func (e ValidationError) Error() string

Error implements the error interface for ValidationError.

func (ValidationError) ToBaseError

func (ve ValidationError) ToBaseError() *errors.Error

ToBaseError converts a ValidationError to the common errors.Error type

type ValidationErrorCategory

type ValidationErrorCategory string

ValidationErrorCategory represents the category of a validation error.

const (
	// ValidationErrorCategoryRequired indicates a required field is missing
	ValidationErrorCategoryRequired ValidationErrorCategory = "required"
	// ValidationErrorCategoryFormat indicates a field has an invalid format
	ValidationErrorCategoryFormat ValidationErrorCategory = "format"
	// ValidationErrorCategoryReference indicates a reference to a non-existent resource
	ValidationErrorCategoryReference ValidationErrorCategory = "reference"
	// ValidationErrorCategoryConflict indicates conflicting fields
	ValidationErrorCategoryConflict ValidationErrorCategory = "conflict"
	// ValidationErrorCategoryUnsupported indicates an unsupported value
	ValidationErrorCategoryUnsupported ValidationErrorCategory = "unsupported"
	// ValidationErrorCategoryProhibited indicates a prohibited field
	ValidationErrorCategoryProhibited ValidationErrorCategory = "prohibited"
)

type ValidationErrorInfo

type ValidationErrorInfo struct {
	Line     int                     `json:"line"`
	Column   int                     `json:"column"`
	Detail   string                  `json:"detail,omitempty"`
	Category ValidationErrorCategory `json:"category,omitempty"`
	Details  map[string]interface{}  `json:"details,omitempty"`
}

ValidationErrorInfo contains additional information about a validation error.

type ValidationErrorSeverity

type ValidationErrorSeverity string

ValidationErrorSeverity represents the severity level of a validation error.

const (
	// ErrorSeverity indicates a critical validation error
	ErrorSeverity ValidationErrorSeverity = "error"
	// WarningSeverity indicates a non-critical validation warning
	WarningSeverity ValidationErrorSeverity = "warning"
)

type Volume

type Volume struct {
	Name      string `yaml:"name"`
	Size      string `yaml:"size"`
	MountPath string `yaml:"mountPath"`
	Path      string `yaml:"path,omitempty"`
}

Volume represents a volume configuration

func (*Volume) UnmarshalYAML

func (v *Volume) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML implements the yaml.Unmarshaler interface for Volume.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL