api

package
v0.12.14-0...-eb10216 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: AGPL-3.0 Imports: 47 Imported by: 0

Documentation

Overview

Package api provides the control plane HTTP/2 server for Unkey's distributed infrastructure.

The control plane coordinates deployment workflows, certificate management, and cluster operations across the Unkey platform. It exposes Connect RPC services over HTTP/2 and integrates with Restate for durable workflow execution.

Architecture

The control plane sits at the center of Unkey's infrastructure. It coordinates sentinel instances that run customer workloads, Restate for durable workflow execution, build artifact storage, and ACME providers for automatic TLS certificates. Connect RPC services are exposed for core control plane operations, deployment workflows, ACME management, OpenAPI specs, and cluster coordination.

Usage

Configure and start the control plane:

cfg := api.Config{
    InstanceID:      "ctrl-1",
    HttpPort:        8080,
    DatabasePrimary: "postgres://...",
    Restate: api.RestateConfig{
        URL:      "http://restate:8080",
        AdminURL: "http://restate:9070",
    },
}
if err := api.Run(ctx, cfg); err != nil {
    log.Fatal(err)
}

The server supports both HTTP/2 cleartext (h2c) for development and TLS for production. When [Config.TLSConfig] is set, the server uses HTTPS; otherwise it uses h2c to allow HTTP/2 without TLS.

Shutdown

The Run function handles graceful shutdown when the provided context is cancelled. All active connections are drained, database connections closed, and telemetry flushed before the function returns.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(ctx context.Context, cfg Config) error

Run starts the control plane server with the provided configuration.

This function initializes all required services and starts the HTTP/2 Connect server. It performs these major initialization steps: 1. Validates configuration and initializes structured logging 2. Sets up OpenTelemetry if enabled 3. Initializes database and build storage 4. Creates Restate ingress client for invoking workflows 5. Starts HTTP/2 server with all Connect handlers

The server handles graceful shutdown when context is cancelled, properly closing all services and database connections.

Returns an error if configuration validation fails, service initialization fails, or during server startup. Context cancellation results in clean shutdown with nil error.

Types

type ClickHouseConfig

type ClickHouseConfig struct {
	URL string `toml:"url"`
}

ClickHouseConfig holds ClickHouse connection configuration. The api process writes container lifecycle events here when krane reports them via ReportInstanceEvents. When URL is empty the writer falls back to a noop and the dashboard's events panel will be empty.

type Config

type Config struct {
	// InstanceID is the unique identifier for this control plane instance.
	// Used for logging, tracing, and cluster coordination.
	InstanceID string `toml:"instance_id"`

	// Region is the geographic region where this control plane instance runs.
	// Used for logging, tracing, and region-aware routing decisions.
	Region string `toml:"region" config:"required,nonempty"`

	// HttpPort defines the HTTP port for the control plane server.
	// Default: 8080. Cannot be 0.
	HttpPort int `toml:"http_port" config:"default=8080,min=1,max=65535"`

	// PrometheusPort specifies the port for exposing Prometheus metrics.
	// Set to 0 to disable metrics exposure. When enabled, metrics are served
	// on all interfaces (0.0.0.0) on the specified port.
	PrometheusPort int `toml:"prometheus_port"`

	// AuthToken is the authentication token for control plane API access.
	// Used by clients and services to authenticate with this control plane.
	AuthToken string `toml:"auth_token" config:"required,nonempty"`

	// DefaultDomain is the fallback domain for system operations.
	// Used for wildcard certificate bootstrapping. When set, the API will
	// ensure a wildcard certificate exists for *.{DefaultDomain}.
	DefaultDomain string `toml:"default_domain"`

	// RegionalDomain is the base domain for cross-region communication
	// between frontline instances. Combined with AvailableRegions to create
	// per-region wildcard certificates like *.{region}.{RegionalDomain}.
	RegionalDomain string `toml:"regional_domain"`

	// CnameDomain is the base domain for custom domain CNAME targets.
	// Each custom domain gets a unique subdomain like "{random}.{CnameDomain}".
	CnameDomain string `toml:"cname_domain"`

	// Database is the MySQL DSN used for all control plane reads and writes.
	Database string `toml:"database" config:"required,nonempty"`

	// Observability configures tracing, logging, and metrics. See [config.Observability].
	Observability config.Observability `toml:"observability"`

	// Restate configures workflow engine integration. See [RestateConfig].
	Restate RestateConfig `toml:"restate"`

	// GitHub configures GitHub App webhook integration. See [GitHubConfig].
	GitHub GitHubConfig `toml:"github"`

	// DomainConnect configures the Domain Connect protocol for one-click DNS setup.
	// See [DomainConnectConfig].
	DomainConnect DomainConnectConfig `toml:"domain_connect"`

	// ClickHouse configures the analytics database connection used for
	// container lifecycle event ingestion.
	ClickHouse ClickHouseConfig `toml:"clickhouse"`

	// DeployGate configures the Unkey Deploy project-creation entitlement gate.
	DeployGate DeployGateConfig `toml:"deploy_gate"`
}

Config holds the complete configuration for the control plane API server. It is designed to be loaded from a TOML file using config.Load:

cfg, err := config.Load[api.Config]("/etc/unkey/ctrl-api.toml")

Environment variables are expanded in file values using ${VAR} syntax before parsing. Struct tag defaults are applied to any field left at its zero value after parsing, and validation runs automatically via Config.Validate.

TLSConfig is runtime-only and cannot be set through a config file. It is tagged toml:"-" and must be set programmatically after loading.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks cross-field constraints that cannot be expressed through struct tags alone. It implements config.Validator so that config.Load calls it automatically after tag-level validation.

type DeployGateConfig

type DeployGateConfig struct {
	// Enforce hard-blocks project creation for workspaces with no Deploy
	// entitlement. Default false runs in observe mode: it logs what it would
	// block but still allows creation, so the signal can be validated first.
	Enforce bool `toml:"enforce"`
}

DeployGateConfig gates project creation on a Deploy entitlement: a synced plan or a manual override.

type DomainConnectConfig

type DomainConnectConfig struct {
	// PrivateKeyPEM is the PEM-encoded RSA private key for signing
	// Domain Connect redirect URLs. If empty, Domain Connect is disabled.
	PrivateKeyPEM string `toml:"private_key_pem"`
}

DomainConnectConfig holds Domain Connect protocol configuration for one-click DNS setup via supported providers.

type GitHubConfig

type GitHubConfig struct {
	// WebhookSecret is the secret used to verify webhook signatures.
	// Configured in the GitHub App webhook settings.
	WebhookSecret string `toml:"webhook_secret"`

	// AppID is the GitHub App ID for authentication.
	// Required for deployment authorization (fetching branch HEAD).
	AppID int64 `toml:"app_id"`

	// PrivateKeyPEM is the GitHub App private key in PEM format.
	// Required for deployment authorization (fetching branch HEAD).
	PrivateKeyPEM string `toml:"private_key_pem"`

	// AllowUnauthenticatedDeployments controls whether deployments can skip
	// GitHub authentication. Set to true only for local development.
	// Production should keep this false to require GitHub App authentication.
	AllowUnauthenticatedDeployments bool `toml:"allow_unauthenticated_deployments"`
}

GitHubConfig holds GitHub App integration settings for webhook-triggered deployments and deployment authorization.

type GitHubWebhook

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

GitHubWebhook handles incoming GitHub App webhook events by validating signatures and dispatching to the GitHubWebhookService in Restate. The HTTP handler performs no DB access — all processing happens durably inside the Restate virtual object.

func (*GitHubWebhook) ServeHTTP

func (s *GitHubWebhook) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP validates the webhook signature and dispatches to event-specific handlers. Currently supports push events for triggering deployments. Unknown event types are acknowledged with 200 OK but not processed.

type RestateConfig

type RestateConfig struct {
	// URL is the Restate ingress endpoint URL for workflow invocation.
	// Used by clients to start and interact with workflow executions.
	URL string `toml:"url" config:"default=http://restate:8080"`

	// AdminURL is the Restate admin API endpoint for managing invocations.
	// Used for canceling invocations.
	AdminURL string `toml:"admin_url" config:"default=http://restate:9070"`

	// APIKey is the authentication key for Restate ingress requests.
	// If set, this key will be sent with all requests to the Restate ingress.
	APIKey string `toml:"api_key"`
}

RestateConfig holds configuration for Restate workflow engine integration.

The API is a Restate client that invokes workflows. It only needs the ingress URL and optional API key for authentication.

Jump to

Keyboard shortcuts

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