config

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package config provides configuration management using Viper.

Index

Constants

View Source
const (
	StorageTypeLocal = "local"
	StorageTypeS3    = "s3"
	StorageTypeAzure = "azure"
	StorageTypeHTTP  = "http"
)

Storage type constants.

View Source
const (
	TracingTransportHTTP = "http"
	TracingTransportGRPC = "grpc"
)

TracingTransport selects the OTLP transport (http/protobuf or grpc).

Variables

This section is empty.

Functions

func Defaults

func Defaults()

Defaults sets the default configuration values.

Types

type AzureConfig

type AzureConfig struct {
	Container        string `mapstructure:"container"`
	AccountName      string `mapstructure:"account_name"`
	AccountKey       string `mapstructure:"account_key"`
	ConnectionString string `mapstructure:"connection_string"`
	Prefix           string `mapstructure:"prefix"`
}

AzureConfig holds Azure Blob Storage configuration.

type BuildInfo

type BuildInfo struct {
	Version   string
	Commit    string
	BuildDate string
}

BuildInfo captures the binary's build identity. Populated from -ldflags in main.go (or left as "dev"/"none" for local builds).

type CORSConfig

type CORSConfig struct {
	AllowedOrigins []string `mapstructure:"allowed_origins"` // e.g., ["https://example.com", "*.sub.domain.tld"]
}

CORSConfig holds CORS configuration.

func (*CORSConfig) Enabled

func (c *CORSConfig) Enabled() bool

Enabled returns true if CORS is configured with at least one allowed origin.

type Config

type Config struct {
	Server    ServerConfig    `mapstructure:"server"`
	Storage   StorageConfig   `mapstructure:"storage"`
	Query     QueryConfig     `mapstructure:"query"`
	TLS       TLSConfig       `mapstructure:"tls"`
	Metrics   MetricsConfig   `mapstructure:"metrics"`
	Logging   LoggingConfig   `mapstructure:"logging"`
	Sync      SyncConfig      `mapstructure:"sync"`
	Tracing   TracingConfig   `mapstructure:"tracing"`
	MCP       MCPConfig       `mapstructure:"mcp"`
	Gazetteer GazetteerConfig `mapstructure:"gazetteer"`
	Raster    RasterConfig    `mapstructure:"raster"`

	// Build is populated by main.go from -ldflags at startup; not loaded
	// from config files. Used for the MCP Implementation.Version field
	// and any future runtime identification needs.
	Build BuildInfo `mapstructure:"-"`
}

Config holds all application configuration.

func Load

func Load(configPath string) (*Config, error)

Load loads configuration from environment and config file.

func (*Config) MetricsOTLPEndpoint

func (c *Config) MetricsOTLPEndpoint() string

MetricsOTLPEndpoint returns the effective endpoint for metric OTLP export. Falls back to tracing.endpoint when metrics.otlp.endpoint is empty so a single collector can serve both signals.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration.

type DNSConfig

type DNSConfig struct {
	Provider          string `mapstructure:"provider"`            // DNS provider (azure)
	SubscriptionID    string `mapstructure:"subscription_id"`     // Azure subscription ID
	ResourceGroupName string `mapstructure:"resource_group_name"` // Azure resource group containing DNS zone
	ClientID          string `mapstructure:"client_id"`           // User Assigned Managed Identity client ID (optional)
}

DNSConfig holds DNS-01 challenge provider configuration for Azure DNS.

type GazetteerBearingConfig

type GazetteerBearingConfig struct {
	ReachVillageKM  float64 `mapstructure:"reach_village_km"`
	ReachTownKM     float64 `mapstructure:"reach_town_km"`
	ReachCityKM     float64 `mapstructure:"reach_city_km"`
	PreferNearestKM float64 `mapstructure:"prefer_nearest_km"` // a town-or-larger anchor within this radius wins outright
	InsideLabelKM   float64 `mapstructure:"inside_label_km"`
	// Inside radii: the point counts as "in {place}" when the nearest place of a class
	// is within its radius (proxy for settlement extent — city reads far, village close).
	// Replaces admin-containment for the "in X" decision, which wrongly reported fields
	// kilometers from a village as "in <village>".
	InsideRadiusVillageKM float64 `mapstructure:"inside_radius_village_km"`
	InsideRadiusTownKM    float64 `mapstructure:"inside_radius_town_km"`
	InsideRadiusCityKM    float64 `mapstructure:"inside_radius_city_km"`
	CompassPoints         int     `mapstructure:"compass_points"` // 8 or 16
	// Salience selects the anchor-selection strategy: "composite" (default —
	// prominence-vs-proximity score; uses the enriched population/capital/wikidata
	// columns, falls back to class where they are absent) or "rank" (the original
	// class-then-distance behavior). Unknown/empty ⇒ composite.
	Salience string `mapstructure:"salience"`
	// Composite holds the composite-strategy knobs (used only when Salience is
	// "composite"). A zero field takes the calibrated default.
	Composite GazetteerCompositeConfig `mapstructure:"composite"`
}

GazetteerBearingConfig holds the tunable knobs of the bearing selection (the reach radii and the proximity override). The semantic constraint tier lives in the manifest (dataset-bound), not here.

type GazetteerBuiltUpConfig

type GazetteerBuiltUpConfig struct {
	BundlePath string  `mapstructure:"bundle_path"` // gazetteer-owned built-up raster bundle (.zip); "" = gate off
	Layer      string  `mapstructure:"layer"`       // continuous built-up layer id (default "builtup")
	MinM2      float64 `mapstructure:"min_m2"`      // min built-up value for a point to count as "in" a settlement
}

GazetteerBuiltUpConfig wires the optional built-up gate that refines the "in <place>" bearing decision: a gazetteer-owned built-up raster (e.g. GHS-BUILT-S), opened out of competition like the elevation DEM. When set, a point within a settlement's radius must also sit on built-up fabric (>= MinM2) to be labeled "in". Empty BundlePath ⇒ gate off (the "in" decision uses distance alone).

type GazetteerCompositeConfig

type GazetteerCompositeConfig struct {
	CandidateRadiusKM float64 `mapstructure:"candidate_radius_km"` // flat gather radius for all classes
	PopWeight         float64 `mapstructure:"pop_weight"`          // multiplier on log10(1+population)
	WikiWeight        float64 `mapstructure:"wiki_weight"`         // bonus when a wikidata QID is present
	DecayPerKM        float64 `mapstructure:"decay_per_km"`        // score subtracted per km (prominence↔proximity slope)
	CapitalScale      float64 `mapstructure:"capital_scale"`       // scales the capital-rank bonus
	// ClassPrior overrides the base score used when a place has no population, keyed
	// by class name ("city"/"town"/"village"). Empty ⇒ calibrated defaults.
	ClassPrior map[string]float64 `mapstructure:"class_prior"`
	// CapitalBonus overrides the per-rank capital bonus (before capital_scale), keyed
	// by the OSM capital= value ("2".."7","yes"). Empty ⇒ calibrated defaults.
	CapitalBonus map[string]float64 `mapstructure:"capital_bonus"`
}

GazetteerCompositeConfig tunes CompositeSalience. Defaults (the calibrated "balanced" profile) apply per-field when left zero.

type GazetteerConfig

type GazetteerConfig struct {
	Enabled                bool                     `mapstructure:"enabled"`
	GeoPackagePath         string                   `mapstructure:"geopackage_path"`           // the places/admin GeoPackage
	ManifestPath           string                   `mapstructure:"manifest_path"`             // ortus-gazetteer.yaml (layer/column mapping)
	LevelReferencePath     string                   `mapstructure:"level_reference_path"`      // admin-level sidecar (optional; enriches Locate)
	NameSourceManifestPath string                   `mapstructure:"name_source_manifest_path"` // name-source manifest (optional; name provenance)
	Bearing                GazetteerBearingConfig   `mapstructure:"bearing"`
	Elevation              GazetteerElevationConfig `mapstructure:"elevation"`
	BuiltUp                GazetteerBuiltUpConfig   `mapstructure:"builtup"`
	Warmup                 GazetteerWarmupConfig    `mapstructure:"warmup"`
}

GazetteerConfig holds the reverse-geocoding / bearing ("Peilung") feature. It is a dedicated, separately-loaded dataset (not part of the generic PiP source pool); disabled by default so the feature is inert until explicitly wired.

type GazetteerElevationConfig

type GazetteerElevationConfig struct {
	BundlePath            string  `mapstructure:"bundle_path"`              // gazetteer-owned DEM bundle (.zip); "" = elevation/exposure off
	Layer                 string  `mapstructure:"layer"`                    // continuous elevation layer id (default "elevation")
	AccuracyLayer         string  `mapstructure:"accuracy_layer"`           // optional continuous per-point accuracy layer (e.g. HEM); "" = off
	TileCacheSize         int     `mapstructure:"tile_cache_size"`          // open-tile LRU bound for multi-tile DEMs (default 64)
	VerticalDatum         string  `mapstructure:"vertical_datum"`           // e.g. "EGM2008"
	AccuracyM             float64 `mapstructure:"accuracy_m"`               // vertical accuracy constant (dataset LE90), used when no accuracy_layer
	AccuracyBasis         string  `mapstructure:"accuracy_basis"`           // basis for the constant, e.g. "GLO-30 LE90 (absolute)"
	PerPointAccuracyBasis string  `mapstructure:"per_point_accuracy_basis"` // basis when accuracy_layer is set, e.g. "Copernicus HEM (per-pixel 1σ)"
	HorizontalM           float64 `mapstructure:"horizontal_accuracy_m"`    // horizontal accuracy (LE90)
	SurfaceModel          string  `mapstructure:"surface_model"`            // e.g. "DSM"
}

GazetteerElevationConfig wires the optional elevation feature: the gazetteer samples a continuous raster DEM at the query point and reports the height above sea level. The DEM is gazetteer-owned — opened "out of competition" from BundlePath (like the gazetteer GeoPackage), NOT registered in the generic source pool, so it never appears under GET /api/v1/sources and is never point-in-polygon queried. Empty BundlePath leaves the feature off; a missing or unopenable bundle is non-fatal (startup continues, elevation + exposure stay silent). The accuracy/datum/surface fields are dataset-wide constants surfaced in the response so a client can use the value responsibly.

type GazetteerWarmupConfig

type GazetteerWarmupConfig struct {
	Enabled bool    `mapstructure:"enabled"`
	Lon     float64 `mapstructure:"lon"`
	Lat     float64 `mapstructure:"lat"`
}

GazetteerWarmupConfig controls the startup self-warmup: before the server accepts traffic, ortus runs one internal gazetteer query at (Lon, Lat) so the SpatiaLite connection, mod_spatialite and the first DEM tile are already warm — otherwise the first real request pays that cold cost and can time out ("Load failed", then fine). Point Lon/Lat at a coordinate your dataset AND DEM cover.

type HTTPConfig

type HTTPConfig struct {
	BaseURL   string        `mapstructure:"base_url"`
	IndexFile string        `mapstructure:"index_file"` // default: index.txt
	Timeout   time.Duration `mapstructure:"timeout"`
	Username  string        `mapstructure:"username"`
	Password  string        `mapstructure:"password"`
}

HTTPConfig holds HTTP download configuration.

type LoggingConfig

type LoggingConfig struct {
	Level  string `mapstructure:"level"`
	Format string `mapstructure:"format"` // json, text
}

LoggingConfig holds logging configuration.

type MCPConfig

type MCPConfig struct {
	Enabled bool   `mapstructure:"enabled"`
	Host    string `mapstructure:"host"`
	Port    int    `mapstructure:"port"`
	Path    string `mapstructure:"path"`
	// Token is populated from ORTUS_MCP_TOKEN at Load() time, NOT from the
	// config file. Required for non-loopback hosts.
	Token string `mapstructure:"-"`
}

MCPConfig configures the in-process Model Context Protocol server. When enabled, ortus exposes a streamable-HTTP MCP endpoint on a separate port so AI agents (Claude Desktop, Claude Code, …) can query traces, package metadata, and perform point queries against this service. The bearer token is intentionally NOT in the config file — it's pulled from the ORTUS_MCP_TOKEN environment variable so it can't be checked in by accident.

type MetricsConfig

type MetricsConfig struct {
	Enabled bool       `mapstructure:"enabled"`
	Port    int        `mapstructure:"port"`
	Path    string     `mapstructure:"path"`
	OTLP    OTLPConfig `mapstructure:"otlp"`
}

MetricsConfig holds metrics configuration: the Prometheus scrape endpoint (always on when Enabled) plus the optional OTLP push export (configured via OTLP).

type OTLPConfig

type OTLPConfig struct {
	Enabled   bool              `mapstructure:"enabled"`
	Endpoint  string            `mapstructure:"endpoint"`  // host:port; empty ⇒ fall back to tracing.endpoint
	Transport string            `mapstructure:"transport"` // "http" or "grpc"
	Insecure  bool              `mapstructure:"insecure"`
	Headers   map[string]string `mapstructure:"headers"`
	Interval  time.Duration     `mapstructure:"interval"` // PeriodicReader collection interval (default 60s)
}

OTLPConfig configures OTLP export for a single signal (metrics or others). An empty Endpoint falls back to the tracing.endpoint setting so a single collector can serve both signals without duplicate configuration.

type QueryBatchConfig

type QueryBatchConfig struct {
	MaxPoints     int `mapstructure:"max_points"`      // hard cap on points per request (both delivery modes)
	MaxSyncPoints int `mapstructure:"max_sync_points"` // sync-JSON cap; over this → 413 (stream with Accept: application/x-ndjson)
	Concurrency   int `mapstructure:"concurrency"`     // worker pool for the per-point gazetteer enrichment path
}

QueryBatchConfig bounds the POST /api/v1/query/batch endpoint.

type QueryConfig

type QueryConfig struct {
	Timeout      time.Duration    `mapstructure:"timeout"`
	MaxFeatures  int              `mapstructure:"max_features"`
	WithGeometry bool             `mapstructure:"with_geometry"` // Include geometry in results (default: false)
	SQLite       SQLiteConfig     `mapstructure:"sqlite"`
	Batch        QueryBatchConfig `mapstructure:"batch"`
}

QueryConfig holds query-related configuration.

type RasterConfig

type RasterConfig struct {
	// MaxBundleExtractGiB caps the total bytes extracted from one bundle (a
	// decompression-bomb guard). Default 8. Raise it for large trusted bundles
	// such as continental DEM tile sets (e.g. the West-Palearctic elevation
	// bundle is ~40 GiB).
	MaxBundleExtractGiB int `mapstructure:"max_bundle_extract_gib"`
	// ExtractCacheDir, when set, turns on the persistent content-addressed
	// extraction cache: bundles are unpacked once into <dir>/<id>@<fingerprint>
	// and reused across restarts/updates, re-extracting only when the ZIP content
	// changes. Point it at a durable, mounted volume. Empty = ephemeral (unpack to
	// an OS temp dir on every start; today's behavior).
	ExtractCacheDir string `mapstructure:"extract_cache_dir"`
	// ExtractCachePrune removes older cached extractions of a source after a new
	// fingerprint loads. Default false: pruning is unsafe during overlapping
	// rolling updates on a shared volume. Only enable when container starts never
	// overlap.
	ExtractCachePrune bool `mapstructure:"extract_cache_prune"`
}

RasterConfig holds settings for the raster-bundle adapter (COG *.zip sources).

type RateLimitConfig

type RateLimitConfig struct {
	Enabled bool    `mapstructure:"enabled"`
	Rate    float64 `mapstructure:"rate"`  // sustained requests per second per client IP
	Burst   int     `mapstructure:"burst"` // token-bucket burst per client IP
	// TrustedProxies are CIDRs of front proxies/load balancers. When the direct
	// peer is within one, the client IP is taken from X-Forwarded-For; otherwise
	// the direct peer (RemoteAddr) is used. Empty (default) = never trust
	// forwarded headers — correct for ortus exposed directly on a public IP.
	TrustedProxies []string `mapstructure:"trusted_proxies"`
}

RateLimitConfig holds rate limiting configuration.

type S3Config

type S3Config struct {
	Bucket          string `mapstructure:"bucket"`
	Region          string `mapstructure:"region"`
	Prefix          string `mapstructure:"prefix"`
	Endpoint        string `mapstructure:"endpoint"`
	AccessKeyID     string `mapstructure:"access_key_id"`
	SecretAccessKey string `mapstructure:"secret_access_key"`
}

S3Config holds AWS S3 configuration.

type SQLiteConfig

type SQLiteConfig struct {
	// CacheMode is the SQLite cache mode: "private" (default — each connection
	// has its own cache, allowing true concurrent reads) or "shared" (legacy;
	// serializes via table-level locks and hurts read concurrency).
	CacheMode string `mapstructure:"cache_mode"`
	// BusyTimeoutMS makes a connection wait up to this long for a lock instead of
	// failing immediately with SQLITE_BUSY (matters during one-off index builds).
	// 0 disables the timeout.
	BusyTimeoutMS int `mapstructure:"busy_timeout_ms"`
	// JournalMode, when set (e.g. "WAL"), is applied to each opened database.
	// Empty leaves the file's existing mode untouched.
	JournalMode string `mapstructure:"journal_mode"`
	// MaxOpenConns bounds open connections per source DB (each is a cgo handle +
	// its own page cache). 0 = unlimited (database/sql default).
	MaxOpenConns int `mapstructure:"max_open_conns"`
	// MaxIdleConns is the idle connection pool size per source DB.
	MaxIdleConns int `mapstructure:"max_idle_conns"`
}

SQLiteConfig tunes how the GeoPackage adapter opens its SQLite databases. Defaults are conservative read-oriented values; calibrate with a load test on the target infra (see docs/how-to/run-a-load-test.md).

type ServerConfig

type ServerConfig struct {
	Host            string          `mapstructure:"host"`
	Port            int             `mapstructure:"port"`
	ReadTimeout     time.Duration   `mapstructure:"read_timeout"`
	WriteTimeout    time.Duration   `mapstructure:"write_timeout"`
	ShutdownTimeout time.Duration   `mapstructure:"shutdown_timeout"`
	RateLimit       RateLimitConfig `mapstructure:"rate_limit"`
	CORS            CORSConfig      `mapstructure:"cors"`
	FrontendEnabled bool            `mapstructure:"frontend_enabled"` // Enable web frontend at /
	// ReadyWhenEmpty: when true (default), readiness reports ready once the
	// initial load pass is done even with zero sources ("no data today"). When
	// false, readiness additionally requires at least one ready source.
	ReadyWhenEmpty bool `mapstructure:"ready_when_empty"`
}

ServerConfig holds HTTP server configuration.

func (*ServerConfig) Address

func (c *ServerConfig) Address() string

Address returns the server address string.

type StorageConfig

type StorageConfig struct {
	Type      string      `mapstructure:"type"` // s3, azure, http, local
	LocalPath string      `mapstructure:"local_path"`
	S3        S3Config    `mapstructure:"s3"`
	Azure     AzureConfig `mapstructure:"azure"`
	HTTP      HTTPConfig  `mapstructure:"http"`
}

StorageConfig holds object storage configuration.

type SyncConfig

type SyncConfig struct {
	Enabled  bool          `mapstructure:"enabled"`
	Interval time.Duration `mapstructure:"interval"` // e.g., "1h", "24h", "30m"
}

SyncConfig holds remote storage sync configuration.

type TLSConfig

type TLSConfig struct {
	Enabled  bool      `mapstructure:"enabled"`
	Domains  []string  `mapstructure:"domains"`
	Email    string    `mapstructure:"email"`
	CacheDir string    `mapstructure:"cache_dir"`
	Staging  bool      `mapstructure:"staging"` // Use Let's Encrypt staging
	DNS      DNSConfig `mapstructure:"dns"`
}

TLSConfig holds TLS/CertMagic configuration.

type TracingConfig

type TracingConfig struct {
	Enabled     bool              `mapstructure:"enabled"`
	ServiceName string            `mapstructure:"service_name"`
	Environment string            `mapstructure:"environment"`  // e.g., "dev", "prod" — sets deployment.environment.name
	Endpoint    string            `mapstructure:"endpoint"`     // OTLP collector endpoint as host:port; passed verbatim to otlptracehttp.WithEndpoint / otlptracegrpc.WithEndpoint
	Transport   string            `mapstructure:"transport"`    // "http" or "grpc"
	Insecure    bool              `mapstructure:"insecure"`     // disable TLS to the collector
	Headers     map[string]string `mapstructure:"headers"`      // OTLP exporter headers (e.g., auth tokens)
	SampleRatio float64           `mapstructure:"sample_ratio"` // 0.0..1.0; >=1.0 => AlwaysOn, <=0 => NeverSample, else ratio-based (parent-respecting)
	BufferSize  int               `mapstructure:"buffer_size"`  // number of traces retained in the in-memory ring buffer for MCP queries
	Attributes  map[string]string `mapstructure:"attributes"`   // additional static resource attributes
}

TracingConfig holds OpenTelemetry tracing configuration.

Jump to

Keyboard shortcuts

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