config

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package config loads a service's configuration: one struct, schema from the Go type (schemapb), layers merged by xconf:

schema defaults < file < env <SERVICE>_* (BACKPLANE_* for the SDK block) < Consul KV

Consul KV applies only to Live fields. Load reads once; Open keeps the configuration live.

Index

Constants

View Source
const (
	HooksAuto     = "auto"
	HooksTemporal = "temporal"
	HooksDirect   = "direct"
)

Transports of hook calls.

View Source
const EnvFile = "BACKPLANE_CONFIG_FILE"

EnvFile names the default configuration file.

Variables

View Source
var (
	ErrRemoteDriver = errors.New("config: consul configured without a remote configuration driver")
	ErrRemoteSource = errors.New("config: remote configuration driver returned nil")
)

Remote driver configuration errors.

View Source
var (
	// ErrTLSCA: the CA holds no PEM certificate.
	ErrTLSCA = errors.New("config: tls: ca holds no PEM certificate")
	// ErrTLSPair: only one of cert and key is set.
	ErrTLSPair = errors.New("config: tls: cert and key go together")
)

Errors of TLS.ClientConfig.

Functions

func Load

func Load[C any](ctx context.Context, opts ...Option) (C, error)

Load reads the configuration once: defaults, file and environment. For tools and tests; services use Open through backplane.Open.

Types

type Backplane

type Backplane struct {
	Consul   Consul   `json:"consul"`
	NATS     NATS     `json:"nats"`
	Temporal Temporal `json:"temporal"`
	Hooks    Hooks    `json:"hooks"`
	Shutdown Shutdown `json:"shutdown"`
	Health   Health   `json:"health"`
	// Limits of the SDK's HTTP and gRPC servers (public and platform ports).
	Server Server `json:"server"`

	// Instance id; default <service>-<hostname>.
	Instance string `json:"instance,omitempty"`
	// Address other components reach this instance at; default POD_IP, then
	// the hostname's address.
	Advertise string `json:"advertise,omitempty"`
	// deployment.environment.name for telemetry; exporters use OTEL_*.
	Environment string `json:"environment,omitempty"`
	// Platform port: internal API, health, probes, UI bundle.
	InternalPort int64 `json:"internal_port" schemapb:"default=9400;gte=1;lte=65535"`
	// Shared secret the console relay presents; empty disables the check.
	InternalSecret Secret `json:"internal_secret,omitempty"`
	// Also accepted while the secret rotates: set the new one as
	// internal_secret and the old one here, then drop it.
	InternalSecretPrevious Secret `json:"internal_secret_previous,omitempty"`
	// Default listener of managed public routes.
	PublicPort int64 `json:"public_port" schemapb:"default=8080;gte=1;lte=65535"`
	// Log level; changed live from the console.
	LogLevel Live[string] `json:"log_level" schemapb:"default=info"`
	// Serve /debug/pprof on the platform port behind the internal secret.
	Pprof bool `json:"pprof" schemapb:"default=false"`
}

Backplane is the SDK's own block, part of the service configuration:

type Config struct {
    config.Backplane `json:"backplane"`
    DB string        `json:"db"`
}

Its environment names are fixed (BACKPLANE_*) for every service. Every dependency is optional for a service: an empty address means "without it".

func (Backplane) BackplaneConfig

func (b Backplane) BackplaneConfig() Backplane

BackplaneConfig returns the block; promoted to the embedding struct.

type Backplaner

type Backplaner interface{ BackplaneConfig() Backplane }

Backplaner is satisfied by any struct embedding Backplane.

type Consul

type Consul struct {
	Addr       string `json:"addr,omitempty"`
	Token      Secret `json:"token,omitempty"`
	Datacenter string `json:"datacenter,omitempty"`
	TLS        TLS    `json:"tls"`
	// false when the deployment registers the service itself.
	Register bool `json:"register" schemapb:"default=true"`
	// Tags of the catalog registration.
	Tags []string `json:"tags,omitempty"`
	// Health check of the catalog registration.
	CheckInterval   time.Duration `json:"check_interval"   schemapb:"default=10s"`
	CheckTimeout    time.Duration `json:"check_timeout"    schemapb:"default=5s"`
	DeregisterAfter time.Duration `json:"deregister_after" schemapb:"default=1m"`
	// TTL of the session the instance state lives under.
	SessionTTL time.Duration `json:"session_ttl" schemapb:"default=30s"`
}

Consul connection.

func (Consul) Enabled

func (c Consul) Enabled() bool

Enabled reports whether Consul is configured.

type Health

type Health struct {
	Interval time.Duration `json:"interval" schemapb:"default=5s"`
	// Per evaluation; at most interval.
	Timeout time.Duration `json:"timeout" schemapb:"default=3s"`
}

Health evaluation of the probes.

type Hooks added in v0.3.0

type Hooks struct {
	// Transport of hook calls: "temporal" (Nexus through the configured
	// Temporal), "direct" (gRPC to backplane's platform port, its replicas
	// found through Consul), or "auto": temporal when Temporal is
	// configured, else direct when Consul is.
	Transport string `json:"transport" schemapb:"default=auto"`
}

Hooks: how this service's hook calls reach backplane.

func (Hooks) Resolve added in v0.3.0

func (h Hooks) Resolve(temporal, consul bool) string

Resolve is the transport "auto" stands for given what is configured: HooksTemporal, HooksDirect or "" when neither Temporal nor Consul is.

type Live

type Live[T any] struct {
	// contains filtered or unexported fields
}

Live is a configuration field that changes at runtime: set from the console through Consul KV, applied in place. Every copy of the enclosing section reads the same current value.

Live fields must sit in structs, not in slices or maps: Open rejects those. A zero Live reads the zero value and never fires; LiveOf makes one with a value. Its methods take a pointer (loading fills it in place), so encoding/json and fmt see the current value only through a pointer to the enclosing struct.

func LiveOf

func LiveOf[T any](v T) Live[T]

LiveOf returns a Live holding v: defaults in code, tests.

func (*Live[T]) Get

func (l *Live[T]) Get() T

Get returns the current value.

func (*Live[T]) MarshalJSON

func (l *Live[T]) MarshalJSON() ([]byte, error)

MarshalJSON writes the current value.

func (*Live[T]) SchemaDecodeTarget

func (l *Live[T]) SchemaDecodeTarget() any

SchemaDecodeTarget gives the decoder a fresh private cell to fill.

func (*Live[T]) SchemaField

func (*Live[T]) SchemaField(f *sp.Schema_Field) error

SchemaField marks the field live.

func (*Live[T]) SchemaInner

func (*Live[T]) SchemaInner() reflect.Type

SchemaInner makes the field's schema the schema of T.

func (*Live[T]) Watch

func (l *Live[T]) Watch(fn func(T))

Watch calls fn with every new value applied after loading. Callbacks run in order on the configuration's update goroutine: keep them short and do not close the service from one.

type NATS

type NATS struct {
	URL   Secret `json:"url,omitempty"`
	Creds Secret `json:"creds,omitempty"`
	TLS   TLS    `json:"tls"`
	// Bound of a Publish whose context has no deadline.
	PublishTimeout time.Duration `json:"publish_timeout" schemapb:"default=5s"`

	// Retention of the service's events.
	MaxAge time.Duration `json:"max_age" schemapb:"default=168h"`
	// Size of the event stream in bytes; the oldest events go first.
	MaxBytes int64 `json:"max_bytes" schemapb:"default=0;gte=0"`
	// Replicas of both streams (JetStream cluster).
	Replicas int64 `json:"replicas" schemapb:"default=1;gte=1;lte=5"`
	// Window in which a repeated publish (same ce-id) is dropped; at most
	// max_age.
	DedupWindow time.Duration `json:"dedup_window" schemapb:"default=2m"`
	// Retention of the dead letters of the service's reactors.
	DLQMaxAge time.Duration `json:"dlq_max_age" schemapb:"default=720h"`
}

NATS connection and the streams the service owns: its events bp_<service> (applied when a service that declares events starts) and its dead letters bp_dlq_<service> (applied when its reactors start). Zero max_age, max_bytes or dlq_max_age mean unlimited.

func (NATS) Enabled

func (n NATS) Enabled() bool

Enabled reports whether NATS is configured.

type Option

type Option func(*settings)

Option configures Load and Open.

func ConsulBackoff

func ConsulBackoff(minDelay, maxDelay time.Duration) Option

ConsulBackoff bounds the backoff between retries of an unreachable Consul (default 1s..30s).

func EnvPrefix

func EnvPrefix(prefix string) Option

EnvPrefix replaces the derived prefix <SERVICE>_.

func File

func File(path string) Option

File reads this file (JSON or YAML by extension) instead of BACKPLANE_CONFIG_FILE.

func Service

func Service(name string) Option

Service names the service when build.Service is not stamped.

func Source

func Source(sources ...xconf.Source) Option

Source appends layers above file and environment, below Consul KV, in order.

func WithRemote

func WithRemote(factory RemoteFactory) Option

WithRemote installs a remote configuration driver. The runtime restricts it to Live fields and preserves its last valid values during an outage.

func WithoutConsul

func WithoutConsul() Option

WithoutConsul keeps Open off Consul KV even when the block names it.

func WithoutEnv

func WithoutEnv() Option

WithoutEnv disables the environment layer.

func WithoutFile

func WithoutFile() Option

WithoutFile disables the file layer.

type RemoteFactory

type RemoteFactory func(Backplane, string) (RemoteSource, error)

RemoteFactory creates the remote layer after file and environment are loaded.

type RemoteSource

type RemoteSource interface {
	xconf.Source
	LastRevision() uint64
}

RemoteSource is a watched configuration layer carrying a console revision.

type Runtime

type Runtime[C any] struct {
	// contains filtered or unexported fields
}

Runtime is a loaded, live configuration. Value is stable for the life of the runtime: static fields never change, Live fields change in place.

func Open

func Open[C Backplaner](ctx context.Context, opts ...Option) (*Runtime[C], error)

Open loads the configuration and keeps it live: Consul KV (named by the embedded Backplane block) overrides Live fields only. The Consul layer is resilient: unreachable at start it is empty, failing later it keeps its last values; Degraded reports it and the layer recovers on its own. A required Live value that only Consul holds keeps Open waiting until Consul answers or ctx ends. The runtime outlives ctx; Close it when done.

Every Validator in C (C itself or any section, value or pointer receiver) runs on the loaded configuration — its error fails Open — and on every live update: an update it rejects is not applied, and the instance state reports the error and the rejected revision.

func (*Runtime[C]) Close

func (r *Runtime[C]) Close() error

Close stops watching; safe to call more than once.

func (*Runtime[C]) Degraded

func (r *Runtime[C]) Degraded() error

Degraded reports why the Consul layer is stale or empty; nil when healthy or not configured.

func (*Runtime[C]) Value

func (r *Runtime[C]) Value() *C

Value is the configuration. The pointer is stable; Live fields update in place.

type Secret

type Secret string

Secret is a string that never prints: every fmt verb, text, JSON and logs show "***". The schema marks it secret, so the console and the instance state mask it too. fmt cannot see Secrets in unexported struct fields printed with %v: keep them exported or never print the struct.

func (Secret) Format

func (Secret) Format(f fmt.State, _ rune)

Format masks the value for every verb.

func (Secret) GoString

func (Secret) GoString() string

GoString masks the value.

func (Secret) MarshalJSON

func (Secret) MarshalJSON() ([]byte, error)

MarshalJSON masks the value.

func (Secret) MarshalText

func (Secret) MarshalText() ([]byte, error)

MarshalText masks the value (slog text, YAML, XML).

func (Secret) Reveal

func (s Secret) Reveal() string

Reveal returns the value.

func (Secret) SchemaField

func (Secret) SchemaField(f *sp.Schema_Field) error

SchemaField marks the field secret.

func (Secret) SchemaInner

func (Secret) SchemaInner() reflect.Type

SchemaInner makes the field a plain string in the schema (MarshalJSON would otherwise turn it into a JSON field).

func (Secret) String

func (Secret) String() string

String masks the value.

type Server

type Server struct {
	ReadHeaderTimeout time.Duration `json:"read_header_timeout" schemapb:"default=10s"`
	IdleTimeout       time.Duration `json:"idle_timeout"        schemapb:"default=2m"`
	MaxHeaderBytes    int64         `json:"max_header_bytes"    schemapb:"default=1048576;gte=1"`
	// gRPC: largest message received.
	GRPCMaxRecvMsgSize int64 `json:"grpc_max_recv_msg_size" schemapb:"default=4194304;gte=1"`
	// gRPC: minimum interval of client keepalive pings; some clients ping more
	// often than grpc-go's 5m default allows.
	GRPCKeepaliveMinTime time.Duration `json:"grpc_keepalive_min_time" schemapb:"default=30s"`
	// gRPC: accept keepalive pings on connections without streams.
	GRPCPermitWithoutStream bool `json:"grpc_permit_without_stream" schemapb:"default=true"`
}

Server limits, applied to the public and platform listeners.

type Shutdown

type Shutdown struct {
	Timeout time.Duration `json:"timeout" schemapb:"default=25s"`
	// Time for load balancers to notice the instance left before its
	// listeners close.
	Drain time.Duration `json:"drain" schemapb:"default=3s"`
	// Longest the listeners drain; then open streams are cut.
	Listeners time.Duration `json:"listeners" schemapb:"default=10s"`
	// Kept for the author's tree, dependencies and telemetry after the
	// listeners: drain + listeners + reserve <= timeout.
	Reserve time.Duration `json:"reserve" schemapb:"default=5s"`
}

Shutdown of the instance: readiness drops, Consul deregisters, then after Drain the listeners stop accepting and in-flight work finishes; everything within Timeout. Keep terminationGracePeriodSeconds above Timeout.

type TLS

type TLS struct {
	Enabled    bool   `json:"enabled"               schemapb:"default=false"`
	CA         string `json:"ca,omitempty"`
	Cert       string `json:"cert,omitempty"`
	Key        Secret `json:"key,omitempty"`
	ServerName string `json:"server_name,omitempty"`
	// Development only.
	InsecureSkipVerify bool `json:"insecure_skip_verify" schemapb:"default=false"`
}

TLS of a client connection. PEM contents, not paths: they come from secrets like any other value. Empty CA means the system pool.

func (TLS) ClientConfig

func (t TLS) ClientConfig() (*tls.Config, error)

ClientConfig is the client TLS configuration of t — what the SDK's Consul, NATS and Temporal connections use; nil when TLS is disabled. An empty CA is the system pool, an empty ServerName the host dialed; Cert and Key together are the client certificate.

type Temporal

type Temporal struct {
	Addr      string `json:"addr,omitempty"`
	Namespace string `json:"ns"             schemapb:"default=default"`
	TLS       TLS    `json:"tls"`
	// Temporal Cloud API key.
	APIKey Secret `json:"api_key,omitempty"`
	// First dial attempt; later attempts run in the background.
	DialTimeout time.Duration `json:"dial_timeout" schemapb:"default=2s"`
	// Deadline of a hook call whose context and declaration set none.
	HookTimeout time.Duration `json:"hook_timeout" schemapb:"default=30s"`
	Worker      Worker        `json:"worker"`
}

Temporal connection. Field is `ns`: `namespace` is a CEL reserved word.

func (Temporal) Enabled

func (t Temporal) Enabled() bool

Enabled reports whether Temporal is configured.

type Validator

type Validator interface{ Validate() error }

Validator is implemented by a configuration, or any section of it, that checks itself beyond the schema: Open fails with its error and a live update it rejects is not applied. Value or pointer receiver.

type Worker

type Worker struct {
	// false: this replica runs no worker (activities and the author's
	// workflows are served by replicas that do); it still raises hooks
	// (their own worker runs on every replica) and
	// uses the client.
	Enabled bool `json:"enabled" schemapb:"default=true"`
	// Activities executing at once.
	MaxConcurrentActivities int64 `json:"max_concurrent_activities" schemapb:"default=0;gte=0"`
	// Workflow tasks executing at once.
	MaxConcurrentWorkflowTasks int64 `json:"max_concurrent_workflow_tasks" schemapb:"default=0;gte=0"`
	// Pollers of the activity and workflow task queues.
	ActivityPollers int64 `json:"activity_pollers" schemapb:"default=0;gte=0"`
	WorkflowPollers int64 `json:"workflow_pollers" schemapb:"default=0;gte=0"`
}

Worker on the service's task queue: an operational setting, the same code runs with any of it. A zero limit is Temporal's default.

Jump to

Keyboard shortcuts

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