| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433 |
- package config
- import (
- "fmt"
- "io"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "time"
- "gopkg.in/yaml.v3"
- "hth/internal/profile"
- )
- type BackendKind string
- const (
- BackendMock BackendKind = "mock"
- BackendSerial BackendKind = "serial"
- BackendReplay BackendKind = "replay"
- )
- type Serial struct {
- Path string `yaml:"path"`
- IOTimeoutMS int `yaml:"io_timeout_ms"`
- InterByteTimeoutMS int `yaml:"inter_byte_timeout_ms"`
- ResponseTimeoutMS int `yaml:"response_timeout_ms"`
- SetAllTimeoutMS int `yaml:"set_all_timeout_ms"`
- GetTempTimeoutMS int `yaml:"get_temp_timeout_ms"`
- GetMotorTimeoutMS int `yaml:"get_motor_timeout_ms"`
- ProbeTimeoutMS int `yaml:"probe_timeout_ms"`
- OpenTimeoutMS int `yaml:"open_timeout_ms"`
- ShutdownSafeMS int `yaml:"shutdown_safe_timeout_ms"`
- }
- type Sockets struct {
- Observe string `yaml:"observe"`
- Control string `yaml:"control"`
- ObservePerm string `yaml:"observe_perm"`
- ControlPerm string `yaml:"control_perm"`
- ObserveGroup string `yaml:"observe_group"`
- ControlGroup string `yaml:"control_group"`
- }
- type Poll struct {
- TemperatureMS int `yaml:"temperature_ms"`
- MotorStatusMS int `yaml:"motor_status_ms"`
- }
- type Watchdog struct {
- HeartbeatPeriodMS int `yaml:"heartbeat_period_ms"`
- }
- type Lease struct {
- MinTTLMS int `yaml:"min_ttl_ms"`
- MaxTTLMS int `yaml:"max_ttl_ms"`
- }
- type Safety struct {
- Fan *int `yaml:"fan"`
- PTC *int `yaml:"ptc"`
- DoorClosePercent *int `yaml:"door_close_percent"`
- }
- type GRPC struct {
- Reflection bool `yaml:"reflection"`
- }
- type Replay struct {
- Path string `yaml:"path"`
- Speed float64 `yaml:"speed"`
- Step bool `yaml:"step"`
- FromEventID uint64 `yaml:"from_event_id"`
- AllowObserveStep bool `yaml:"allow_observe_step"`
- }
- type Mock struct {
- Seed int64 `yaml:"seed"`
- StartupComplete bool `yaml:"startup_complete"`
- FirstOrderThermal bool `yaml:"first_order_thermal"`
- SlowGetMS int `yaml:"slow_get_ms"`
- }
- type Config struct {
- APIVersion string `yaml:"api_version"`
- DeviceID string `yaml:"device_id"`
- DisplayName string `yaml:"display_name"`
- Backend BackendKind `yaml:"backend"`
- Profile string `yaml:"profile"`
- RuntimeRoot string `yaml:"runtime_root"`
- Serial Serial `yaml:"serial"`
- Sockets Sockets `yaml:"sockets"`
- Poll Poll `yaml:"poll"`
- Watchdog Watchdog `yaml:"watchdog"`
- Lease Lease `yaml:"lease"`
- Safety Safety `yaml:"safety"`
- RingBufferSize int `yaml:"ring_buffer_size"`
- SubscriberBufferSize int `yaml:"subscriber_buffer_size"`
- MaxSubscribers int `yaml:"max_subscribers"`
- MaxStreamsPerPeer int `yaml:"max_streams_per_peer"`
- CommandCacheSize int `yaml:"command_cache_size"`
- GRPC GRPC `yaml:"grpc"`
- Replay Replay `yaml:"replay"`
- Mock Mock `yaml:"mock"`
- AllowUnboundActions bool `yaml:"allow_unbound_actions"`
- Path string `yaml:"-"`
- }
- func Load(path string) (*Config, error) {
- raw, err := os.ReadFile(path)
- if err != nil {
- return nil, fmt.Errorf("config: read %s: %w", path, err)
- }
- dec := yaml.NewDecoder(strings.NewReader(string(raw)))
- dec.KnownFields(true)
- var c Config
- if err := dec.Decode(&c); err != nil {
- return nil, fmt.Errorf("config: parse %s: %w", path, err)
- }
- var extra yaml.Node
- if err := dec.Decode(&extra); err != io.EOF {
- if err == nil {
- return nil, fmt.Errorf("config: extra YAML document rejected in %s", path)
- }
- return nil, fmt.Errorf("config: trailing YAML in %s: %w", path, err)
- }
- c.Path = path
- c.resolveRelative()
- return &c, nil
- }
- func (c *Config) resolveRelative() {
- base := filepath.Dir(c.Path)
- c.Profile = resolve(base, c.Profile)
- c.Replay.Path = resolve(base, c.Replay.Path)
- c.Sockets.Observe = resolve(base, c.Sockets.Observe)
- c.Sockets.Control = resolve(base, c.Sockets.Control)
- c.Serial.Path = resolve(base, c.Serial.Path)
- c.RuntimeRoot = resolve(base, c.RuntimeRoot)
- }
- func resolve(base, p string) string {
- if p == "" || filepath.IsAbs(p) {
- return p
- }
- return filepath.Clean(filepath.Join(base, p))
- }
- func (c *Config) ApplyBackendOverride(kind string) error {
- if kind == "" {
- return nil
- }
- switch BackendKind(kind) {
- case BackendMock, BackendSerial, BackendReplay:
- c.Backend = BackendKind(kind)
- return nil
- default:
- return fmt.Errorf("config: unknown backend %q", kind)
- }
- }
- func (c *Config) Validate(p *profile.Profile) error {
- if c.APIVersion != "" && p != nil && c.APIVersion != p.APIVersion {
- return fmt.Errorf("config: api_version %q != profile %q", c.APIVersion, p.APIVersion)
- }
- switch c.Backend {
- case BackendMock, BackendSerial, BackendReplay:
- case "":
- return fmt.Errorf("config: backend required (mock|serial|replay)")
- default:
- return fmt.Errorf("config: unknown backend %q", c.Backend)
- }
- if c.DeviceID == "" {
- return fmt.Errorf("config: device_id required")
- }
- if c.Profile == "" {
- return fmt.Errorf("config: profile path required")
- }
- if c.Sockets.Observe == "" || c.Sockets.Control == "" {
- return fmt.Errorf("config: sockets.observe and sockets.control required")
- }
- if c.Sockets.Observe == c.Sockets.Control {
- return fmt.Errorf("config: observe and control sockets must differ")
- }
- if _, err := c.ManagedRuntimeRoot(); err != nil {
- return err
- }
- root, _ := c.ManagedRuntimeRoot()
- for _, pth := range []string{c.Sockets.Observe, c.Sockets.Control} {
- abs, err := filepath.Abs(filepath.Clean(pth))
- if err != nil {
- return err
- }
- rel, err := filepath.Rel(root, abs)
- if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
- return fmt.Errorf("config: socket %s is outside runtime_root %s", pth, root)
- }
- }
- if _, err := ParseFileMode(c.Sockets.ObservePerm, 0o660); err != nil {
- return fmt.Errorf("config: observe_perm: %w", err)
- }
- if _, err := ParseFileMode(c.Sockets.ControlPerm, 0o660); err != nil {
- return fmt.Errorf("config: control_perm: %w", err)
- }
- if c.Backend == BackendSerial {
- if c.Serial.Path == "" {
- return fmt.Errorf("config: serial.path required for serial backend")
- }
- if c.Safety.Fan == nil || c.Safety.PTC == nil || c.Safety.DoorClosePercent == nil {
- return fmt.Errorf("config: safety.fan, safety.ptc, safety.door_close_percent required in serial mode (no silent defaults)")
- }
- }
- if c.Backend == BackendReplay && c.Replay.Path == "" {
- return fmt.Errorf("config: replay.path required for replay backend")
- }
- if c.Poll.TemperatureMS <= 0 || c.Poll.MotorStatusMS <= 0 {
- return fmt.Errorf("config: poll periods required")
- }
- if p != nil {
- min := p.MinSamplePeriod()
- if time.Duration(c.Poll.TemperatureMS)*time.Millisecond < min {
- return fmt.Errorf("config: poll.temperature_ms %d < profile min %s", c.Poll.TemperatureMS, min)
- }
- }
- if c.Watchdog.HeartbeatPeriodMS <= 0 {
- return fmt.Errorf("config: watchdog.heartbeat_period_ms required")
- }
- if p != nil {
- fw := p.FirmwareWatchdog()
- hb := time.Duration(c.Watchdog.HeartbeatPeriodMS) * time.Millisecond
- if hb >= fw {
- return fmt.Errorf("config: watchdog heartbeat %s must be < firmware timeout %s", hb, fw)
- }
- if hb*3 > fw {
- return fmt.Errorf("config: watchdog heartbeat %s needs 3x margin vs firmware timeout %s", hb, fw)
- }
- tempTO := c.GetTempTimeout(p)
- setAllTO := c.SetAllTimeout()
- probeTO := c.ProbeTimeout()
- openTO := c.OpenTimeout()
- if tempTO >= fw {
- return fmt.Errorf("config: GET_TEMPERATURE timeout %s must be < firmware watchdog %s", tempTO, fw)
- }
- if setAllTO >= fw {
- return fmt.Errorf("config: SET_ALL timeout %s must be < firmware watchdog %s", setAllTO, fw)
- }
- if probeTO >= fw {
- return fmt.Errorf("config: readiness probe timeout %s must be < firmware watchdog %s", probeTO, fw)
- }
- if openTO >= fw {
- return fmt.Errorf("config: serial open timeout %s must be < firmware watchdog %s", openTO, fw)
- }
- if tempTO+setAllTO >= fw {
- return fmt.Errorf("config: GET_TEMPERATURE %s + SET_ALL %s leaves no margin before firmware watchdog %s", tempTO, setAllTO, fw)
- }
- minGET := time.Duration(p.Timeouts.TemperatureScanBusyMS)*time.Millisecond + 300*time.Millisecond
- if p.Timeouts.TemperatureScanBusyMS <= 0 {
- minGET = 5300 * time.Millisecond
- }
- if tempTO < minGET {
- return fmt.Errorf("config: GET_TEMPERATURE timeout %s < profile worst-case %s (scan+UART+host margin)", tempTO, minGET)
- }
- // Lease TTL may be shorter than an uninterruptible UART transaction: the actor
- // expires the lease on the control plane while the worker finishes the current
- // serial job. max_ttl must still be below the firmware watchdog.
- if time.Duration(c.Lease.MaxTTLMS)*time.Millisecond > fw {
- return fmt.Errorf("config: lease.max_ttl_ms must be <= firmware watchdog %s", fw)
- }
- }
- if c.Lease.MinTTLMS <= 0 || c.Lease.MaxTTLMS <= 0 || c.Lease.MinTTLMS > c.Lease.MaxTTLMS {
- return fmt.Errorf("config: lease min/max TTL invalid")
- }
- if c.Safety.Fan != nil && (*c.Safety.Fan < 0 || *c.Safety.Fan > 100) {
- return fmt.Errorf("config: safety.fan out of 0..100")
- }
- if c.Safety.PTC != nil && (*c.Safety.PTC < 0 || *c.Safety.PTC > 100) {
- return fmt.Errorf("config: safety.ptc out of 0..100")
- }
- if c.Safety.DoorClosePercent != nil && (*c.Safety.DoorClosePercent < 0 || *c.Safety.DoorClosePercent > 100) {
- return fmt.Errorf("config: safety.door_close_percent out of 0..100")
- }
- if c.RingBufferSize <= 0 {
- c.RingBufferSize = 1024
- }
- if c.RingBufferSize > 1<<20 {
- return fmt.Errorf("config: ring_buffer_size %d exceeds 1048576", c.RingBufferSize)
- }
- if c.SubscriberBufferSize <= 0 {
- c.SubscriberBufferSize = 8
- }
- if c.SubscriberBufferSize > 1024 {
- return fmt.Errorf("config: subscriber_buffer_size %d exceeds 1024", c.SubscriberBufferSize)
- }
- if c.MaxSubscribers <= 0 {
- c.MaxSubscribers = 64
- }
- if c.MaxSubscribers > 4096 {
- return fmt.Errorf("config: max_subscribers %d exceeds 4096", c.MaxSubscribers)
- }
- if c.MaxStreamsPerPeer <= 0 {
- c.MaxStreamsPerPeer = 8
- }
- if c.MaxStreamsPerPeer > 64 {
- return fmt.Errorf("config: max_streams_per_peer %d exceeds 64", c.MaxStreamsPerPeer)
- }
- if c.CommandCacheSize <= 0 {
- c.CommandCacheSize = 256
- }
- if c.Mock.Seed == 0 {
- c.Mock.Seed = 1
- }
- return nil
- }
- func (c *Config) TemperaturePoll() time.Duration {
- return time.Duration(c.Poll.TemperatureMS) * time.Millisecond
- }
- func (c *Config) MotorPoll() time.Duration {
- return time.Duration(c.Poll.MotorStatusMS) * time.Millisecond
- }
- func (c *Config) Heartbeat() time.Duration {
- return time.Duration(c.Watchdog.HeartbeatPeriodMS) * time.Millisecond
- }
- func (c *Config) MinTTL() time.Duration { return time.Duration(c.Lease.MinTTLMS) * time.Millisecond }
- func (c *Config) MaxTTL() time.Duration { return time.Duration(c.Lease.MaxTTLMS) * time.Millisecond }
- func (c *Config) ObserveMode() os.FileMode {
- m, _ := ParseFileMode(c.Sockets.ObservePerm, 0o660)
- return m
- }
- func (c *Config) ControlMode() os.FileMode {
- m, _ := ParseFileMode(c.Sockets.ControlPerm, 0o660)
- return m
- }
- func (c *Config) SetAllTimeout() time.Duration {
- if c.Serial.SetAllTimeoutMS > 0 {
- return time.Duration(c.Serial.SetAllTimeoutMS) * time.Millisecond
- }
- if c.Serial.IOTimeoutMS > 0 {
- return time.Duration(c.Serial.IOTimeoutMS) * time.Millisecond
- }
- return 2 * time.Second
- }
- func (c *Config) GetTempTimeout(p *profile.Profile) time.Duration {
- if c.Serial.GetTempTimeoutMS > 0 {
- return time.Duration(c.Serial.GetTempTimeoutMS) * time.Millisecond
- }
- if p != nil && p.Timeouts.TemperatureScanBusyMS > 0 {
- return time.Duration(p.Timeouts.TemperatureScanBusyMS)*time.Millisecond + 1500*time.Millisecond
- }
- if c.Serial.ResponseTimeoutMS > 0 {
- return time.Duration(c.Serial.ResponseTimeoutMS) * time.Millisecond
- }
- return 7 * time.Second
- }
- func (c *Config) GetMotorTimeout() time.Duration {
- if c.Serial.GetMotorTimeoutMS > 0 {
- return time.Duration(c.Serial.GetMotorTimeoutMS) * time.Millisecond
- }
- if c.Serial.ResponseTimeoutMS > 0 {
- return time.Duration(c.Serial.ResponseTimeoutMS) * time.Millisecond
- }
- return 2 * time.Second
- }
- func (c *Config) ProbeTimeout() time.Duration {
- if c.Serial.ProbeTimeoutMS > 0 {
- return time.Duration(c.Serial.ProbeTimeoutMS) * time.Millisecond
- }
- return c.GetMotorTimeout()
- }
- func (c *Config) OpenTimeout() time.Duration {
- if c.Serial.OpenTimeoutMS > 0 {
- return time.Duration(c.Serial.OpenTimeoutMS) * time.Millisecond
- }
- return 2 * time.Second
- }
- func (c *Config) ShutdownSafeTimeout() time.Duration {
- if c.Serial.ShutdownSafeMS > 0 {
- return time.Duration(c.Serial.ShutdownSafeMS) * time.Millisecond
- }
- return 500 * time.Millisecond
- }
- func (c *Config) ManagedRuntimeRoot() (string, error) {
- if c.RuntimeRoot != "" {
- return filepath.Abs(filepath.Clean(c.RuntimeRoot))
- }
- obsDir := filepath.Dir(c.Sockets.Observe)
- ctlDir := filepath.Dir(c.Sockets.Control)
- root := filepath.Clean(filepath.Dir(obsDir))
- other := filepath.Clean(filepath.Dir(ctlDir))
- if root != other {
- return "", fmt.Errorf("config: observe/control socket dirs must share a runtime root (got %s vs %s); set runtime_root", root, other)
- }
- switch root {
- case "/", "/tmp", "/run", "/var", "/var/run", "/dev", "/etc", ".":
- return "", fmt.Errorf("config: inferred runtime root %s is a protected parent; set runtime_root to a dedicated directory", root)
- }
- return filepath.Abs(root)
- }
- func ParseFileMode(s string, def os.FileMode) (os.FileMode, error) {
- s = strings.TrimSpace(s)
- if s == "" {
- return def, nil
- }
- v, err := strconv.ParseUint(s, 8, 32)
- if err != nil {
- v10, err2 := strconv.ParseUint(s, 10, 32)
- if err2 != nil {
- return 0, fmt.Errorf("invalid file mode %q", s)
- }
- v = v10
- }
- if v > 0o777 {
- return 0, fmt.Errorf("file mode %q out of range", s)
- }
- return os.FileMode(v), nil
- }
- func IntPtr(v int) *int { return &v }
|