config.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. package config
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "gopkg.in/yaml.v3"
  11. "hth/internal/profile"
  12. )
  13. type BackendKind string
  14. const (
  15. BackendMock BackendKind = "mock"
  16. BackendSerial BackendKind = "serial"
  17. BackendReplay BackendKind = "replay"
  18. )
  19. type Serial struct {
  20. Path string `yaml:"path"`
  21. IOTimeoutMS int `yaml:"io_timeout_ms"`
  22. InterByteTimeoutMS int `yaml:"inter_byte_timeout_ms"`
  23. ResponseTimeoutMS int `yaml:"response_timeout_ms"`
  24. SetAllTimeoutMS int `yaml:"set_all_timeout_ms"`
  25. GetTempTimeoutMS int `yaml:"get_temp_timeout_ms"`
  26. GetMotorTimeoutMS int `yaml:"get_motor_timeout_ms"`
  27. ProbeTimeoutMS int `yaml:"probe_timeout_ms"`
  28. OpenTimeoutMS int `yaml:"open_timeout_ms"`
  29. ShutdownSafeMS int `yaml:"shutdown_safe_timeout_ms"`
  30. }
  31. type Sockets struct {
  32. Observe string `yaml:"observe"`
  33. Control string `yaml:"control"`
  34. ObservePerm string `yaml:"observe_perm"`
  35. ControlPerm string `yaml:"control_perm"`
  36. ObserveGroup string `yaml:"observe_group"`
  37. ControlGroup string `yaml:"control_group"`
  38. }
  39. type Poll struct {
  40. TemperatureMS int `yaml:"temperature_ms"`
  41. MotorStatusMS int `yaml:"motor_status_ms"`
  42. }
  43. type Watchdog struct {
  44. HeartbeatPeriodMS int `yaml:"heartbeat_period_ms"`
  45. }
  46. type Lease struct {
  47. MinTTLMS int `yaml:"min_ttl_ms"`
  48. MaxTTLMS int `yaml:"max_ttl_ms"`
  49. }
  50. type Safety struct {
  51. Fan *int `yaml:"fan"`
  52. PTC *int `yaml:"ptc"`
  53. DoorClosePercent *int `yaml:"door_close_percent"`
  54. }
  55. type GRPC struct {
  56. Reflection bool `yaml:"reflection"`
  57. }
  58. type Replay struct {
  59. Path string `yaml:"path"`
  60. Speed float64 `yaml:"speed"`
  61. Step bool `yaml:"step"`
  62. FromEventID uint64 `yaml:"from_event_id"`
  63. AllowObserveStep bool `yaml:"allow_observe_step"`
  64. }
  65. type Mock struct {
  66. Seed int64 `yaml:"seed"`
  67. StartupComplete bool `yaml:"startup_complete"`
  68. FirstOrderThermal bool `yaml:"first_order_thermal"`
  69. SlowGetMS int `yaml:"slow_get_ms"`
  70. }
  71. type Config struct {
  72. APIVersion string `yaml:"api_version"`
  73. DeviceID string `yaml:"device_id"`
  74. DisplayName string `yaml:"display_name"`
  75. Backend BackendKind `yaml:"backend"`
  76. Profile string `yaml:"profile"`
  77. RuntimeRoot string `yaml:"runtime_root"`
  78. Serial Serial `yaml:"serial"`
  79. Sockets Sockets `yaml:"sockets"`
  80. Poll Poll `yaml:"poll"`
  81. Watchdog Watchdog `yaml:"watchdog"`
  82. Lease Lease `yaml:"lease"`
  83. Safety Safety `yaml:"safety"`
  84. RingBufferSize int `yaml:"ring_buffer_size"`
  85. SubscriberBufferSize int `yaml:"subscriber_buffer_size"`
  86. MaxSubscribers int `yaml:"max_subscribers"`
  87. MaxStreamsPerPeer int `yaml:"max_streams_per_peer"`
  88. CommandCacheSize int `yaml:"command_cache_size"`
  89. GRPC GRPC `yaml:"grpc"`
  90. Replay Replay `yaml:"replay"`
  91. Mock Mock `yaml:"mock"`
  92. AllowUnboundActions bool `yaml:"allow_unbound_actions"`
  93. Path string `yaml:"-"`
  94. }
  95. func Load(path string) (*Config, error) {
  96. raw, err := os.ReadFile(path)
  97. if err != nil {
  98. return nil, fmt.Errorf("config: read %s: %w", path, err)
  99. }
  100. dec := yaml.NewDecoder(strings.NewReader(string(raw)))
  101. dec.KnownFields(true)
  102. var c Config
  103. if err := dec.Decode(&c); err != nil {
  104. return nil, fmt.Errorf("config: parse %s: %w", path, err)
  105. }
  106. var extra yaml.Node
  107. if err := dec.Decode(&extra); err != io.EOF {
  108. if err == nil {
  109. return nil, fmt.Errorf("config: extra YAML document rejected in %s", path)
  110. }
  111. return nil, fmt.Errorf("config: trailing YAML in %s: %w", path, err)
  112. }
  113. c.Path = path
  114. c.resolveRelative()
  115. return &c, nil
  116. }
  117. func (c *Config) resolveRelative() {
  118. base := filepath.Dir(c.Path)
  119. c.Profile = resolve(base, c.Profile)
  120. c.Replay.Path = resolve(base, c.Replay.Path)
  121. c.Sockets.Observe = resolve(base, c.Sockets.Observe)
  122. c.Sockets.Control = resolve(base, c.Sockets.Control)
  123. c.Serial.Path = resolve(base, c.Serial.Path)
  124. c.RuntimeRoot = resolve(base, c.RuntimeRoot)
  125. }
  126. func resolve(base, p string) string {
  127. if p == "" || filepath.IsAbs(p) {
  128. return p
  129. }
  130. return filepath.Clean(filepath.Join(base, p))
  131. }
  132. func (c *Config) ApplyBackendOverride(kind string) error {
  133. if kind == "" {
  134. return nil
  135. }
  136. switch BackendKind(kind) {
  137. case BackendMock, BackendSerial, BackendReplay:
  138. c.Backend = BackendKind(kind)
  139. return nil
  140. default:
  141. return fmt.Errorf("config: unknown backend %q", kind)
  142. }
  143. }
  144. func (c *Config) Validate(p *profile.Profile) error {
  145. if c.APIVersion != "" && p != nil && c.APIVersion != p.APIVersion {
  146. return fmt.Errorf("config: api_version %q != profile %q", c.APIVersion, p.APIVersion)
  147. }
  148. switch c.Backend {
  149. case BackendMock, BackendSerial, BackendReplay:
  150. case "":
  151. return fmt.Errorf("config: backend required (mock|serial|replay)")
  152. default:
  153. return fmt.Errorf("config: unknown backend %q", c.Backend)
  154. }
  155. if c.DeviceID == "" {
  156. return fmt.Errorf("config: device_id required")
  157. }
  158. if c.Profile == "" {
  159. return fmt.Errorf("config: profile path required")
  160. }
  161. if c.Sockets.Observe == "" || c.Sockets.Control == "" {
  162. return fmt.Errorf("config: sockets.observe and sockets.control required")
  163. }
  164. if c.Sockets.Observe == c.Sockets.Control {
  165. return fmt.Errorf("config: observe and control sockets must differ")
  166. }
  167. if _, err := c.ManagedRuntimeRoot(); err != nil {
  168. return err
  169. }
  170. root, _ := c.ManagedRuntimeRoot()
  171. for _, pth := range []string{c.Sockets.Observe, c.Sockets.Control} {
  172. abs, err := filepath.Abs(filepath.Clean(pth))
  173. if err != nil {
  174. return err
  175. }
  176. rel, err := filepath.Rel(root, abs)
  177. if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
  178. return fmt.Errorf("config: socket %s is outside runtime_root %s", pth, root)
  179. }
  180. }
  181. if _, err := ParseFileMode(c.Sockets.ObservePerm, 0o660); err != nil {
  182. return fmt.Errorf("config: observe_perm: %w", err)
  183. }
  184. if _, err := ParseFileMode(c.Sockets.ControlPerm, 0o660); err != nil {
  185. return fmt.Errorf("config: control_perm: %w", err)
  186. }
  187. if c.Backend == BackendSerial {
  188. if c.Serial.Path == "" {
  189. return fmt.Errorf("config: serial.path required for serial backend")
  190. }
  191. if c.Safety.Fan == nil || c.Safety.PTC == nil || c.Safety.DoorClosePercent == nil {
  192. return fmt.Errorf("config: safety.fan, safety.ptc, safety.door_close_percent required in serial mode (no silent defaults)")
  193. }
  194. }
  195. if c.Backend == BackendReplay && c.Replay.Path == "" {
  196. return fmt.Errorf("config: replay.path required for replay backend")
  197. }
  198. if c.Poll.TemperatureMS <= 0 || c.Poll.MotorStatusMS <= 0 {
  199. return fmt.Errorf("config: poll periods required")
  200. }
  201. if p != nil {
  202. min := p.MinSamplePeriod()
  203. if time.Duration(c.Poll.TemperatureMS)*time.Millisecond < min {
  204. return fmt.Errorf("config: poll.temperature_ms %d < profile min %s", c.Poll.TemperatureMS, min)
  205. }
  206. }
  207. if c.Watchdog.HeartbeatPeriodMS <= 0 {
  208. return fmt.Errorf("config: watchdog.heartbeat_period_ms required")
  209. }
  210. if p != nil {
  211. fw := p.FirmwareWatchdog()
  212. hb := time.Duration(c.Watchdog.HeartbeatPeriodMS) * time.Millisecond
  213. if hb >= fw {
  214. return fmt.Errorf("config: watchdog heartbeat %s must be < firmware timeout %s", hb, fw)
  215. }
  216. if hb*3 > fw {
  217. return fmt.Errorf("config: watchdog heartbeat %s needs 3x margin vs firmware timeout %s", hb, fw)
  218. }
  219. tempTO := c.GetTempTimeout(p)
  220. setAllTO := c.SetAllTimeout()
  221. probeTO := c.ProbeTimeout()
  222. openTO := c.OpenTimeout()
  223. if tempTO >= fw {
  224. return fmt.Errorf("config: GET_TEMPERATURE timeout %s must be < firmware watchdog %s", tempTO, fw)
  225. }
  226. if setAllTO >= fw {
  227. return fmt.Errorf("config: SET_ALL timeout %s must be < firmware watchdog %s", setAllTO, fw)
  228. }
  229. if probeTO >= fw {
  230. return fmt.Errorf("config: readiness probe timeout %s must be < firmware watchdog %s", probeTO, fw)
  231. }
  232. if openTO >= fw {
  233. return fmt.Errorf("config: serial open timeout %s must be < firmware watchdog %s", openTO, fw)
  234. }
  235. if tempTO+setAllTO >= fw {
  236. return fmt.Errorf("config: GET_TEMPERATURE %s + SET_ALL %s leaves no margin before firmware watchdog %s", tempTO, setAllTO, fw)
  237. }
  238. minGET := time.Duration(p.Timeouts.TemperatureScanBusyMS)*time.Millisecond + 300*time.Millisecond
  239. if p.Timeouts.TemperatureScanBusyMS <= 0 {
  240. minGET = 5300 * time.Millisecond
  241. }
  242. if tempTO < minGET {
  243. return fmt.Errorf("config: GET_TEMPERATURE timeout %s < profile worst-case %s (scan+UART+host margin)", tempTO, minGET)
  244. }
  245. // Lease TTL may be shorter than an uninterruptible UART transaction: the actor
  246. // expires the lease on the control plane while the worker finishes the current
  247. // serial job. max_ttl must still be below the firmware watchdog.
  248. if time.Duration(c.Lease.MaxTTLMS)*time.Millisecond > fw {
  249. return fmt.Errorf("config: lease.max_ttl_ms must be <= firmware watchdog %s", fw)
  250. }
  251. }
  252. if c.Lease.MinTTLMS <= 0 || c.Lease.MaxTTLMS <= 0 || c.Lease.MinTTLMS > c.Lease.MaxTTLMS {
  253. return fmt.Errorf("config: lease min/max TTL invalid")
  254. }
  255. if c.Safety.Fan != nil && (*c.Safety.Fan < 0 || *c.Safety.Fan > 100) {
  256. return fmt.Errorf("config: safety.fan out of 0..100")
  257. }
  258. if c.Safety.PTC != nil && (*c.Safety.PTC < 0 || *c.Safety.PTC > 100) {
  259. return fmt.Errorf("config: safety.ptc out of 0..100")
  260. }
  261. if c.Safety.DoorClosePercent != nil && (*c.Safety.DoorClosePercent < 0 || *c.Safety.DoorClosePercent > 100) {
  262. return fmt.Errorf("config: safety.door_close_percent out of 0..100")
  263. }
  264. if c.RingBufferSize <= 0 {
  265. c.RingBufferSize = 1024
  266. }
  267. if c.RingBufferSize > 1<<20 {
  268. return fmt.Errorf("config: ring_buffer_size %d exceeds 1048576", c.RingBufferSize)
  269. }
  270. if c.SubscriberBufferSize <= 0 {
  271. c.SubscriberBufferSize = 8
  272. }
  273. if c.SubscriberBufferSize > 1024 {
  274. return fmt.Errorf("config: subscriber_buffer_size %d exceeds 1024", c.SubscriberBufferSize)
  275. }
  276. if c.MaxSubscribers <= 0 {
  277. c.MaxSubscribers = 64
  278. }
  279. if c.MaxSubscribers > 4096 {
  280. return fmt.Errorf("config: max_subscribers %d exceeds 4096", c.MaxSubscribers)
  281. }
  282. if c.MaxStreamsPerPeer <= 0 {
  283. c.MaxStreamsPerPeer = 8
  284. }
  285. if c.MaxStreamsPerPeer > 64 {
  286. return fmt.Errorf("config: max_streams_per_peer %d exceeds 64", c.MaxStreamsPerPeer)
  287. }
  288. if c.CommandCacheSize <= 0 {
  289. c.CommandCacheSize = 256
  290. }
  291. if c.Mock.Seed == 0 {
  292. c.Mock.Seed = 1
  293. }
  294. return nil
  295. }
  296. func (c *Config) TemperaturePoll() time.Duration {
  297. return time.Duration(c.Poll.TemperatureMS) * time.Millisecond
  298. }
  299. func (c *Config) MotorPoll() time.Duration {
  300. return time.Duration(c.Poll.MotorStatusMS) * time.Millisecond
  301. }
  302. func (c *Config) Heartbeat() time.Duration {
  303. return time.Duration(c.Watchdog.HeartbeatPeriodMS) * time.Millisecond
  304. }
  305. func (c *Config) MinTTL() time.Duration { return time.Duration(c.Lease.MinTTLMS) * time.Millisecond }
  306. func (c *Config) MaxTTL() time.Duration { return time.Duration(c.Lease.MaxTTLMS) * time.Millisecond }
  307. func (c *Config) ObserveMode() os.FileMode {
  308. m, _ := ParseFileMode(c.Sockets.ObservePerm, 0o660)
  309. return m
  310. }
  311. func (c *Config) ControlMode() os.FileMode {
  312. m, _ := ParseFileMode(c.Sockets.ControlPerm, 0o660)
  313. return m
  314. }
  315. func (c *Config) SetAllTimeout() time.Duration {
  316. if c.Serial.SetAllTimeoutMS > 0 {
  317. return time.Duration(c.Serial.SetAllTimeoutMS) * time.Millisecond
  318. }
  319. if c.Serial.IOTimeoutMS > 0 {
  320. return time.Duration(c.Serial.IOTimeoutMS) * time.Millisecond
  321. }
  322. return 2 * time.Second
  323. }
  324. func (c *Config) GetTempTimeout(p *profile.Profile) time.Duration {
  325. if c.Serial.GetTempTimeoutMS > 0 {
  326. return time.Duration(c.Serial.GetTempTimeoutMS) * time.Millisecond
  327. }
  328. if p != nil && p.Timeouts.TemperatureScanBusyMS > 0 {
  329. return time.Duration(p.Timeouts.TemperatureScanBusyMS)*time.Millisecond + 1500*time.Millisecond
  330. }
  331. if c.Serial.ResponseTimeoutMS > 0 {
  332. return time.Duration(c.Serial.ResponseTimeoutMS) * time.Millisecond
  333. }
  334. return 7 * time.Second
  335. }
  336. func (c *Config) GetMotorTimeout() time.Duration {
  337. if c.Serial.GetMotorTimeoutMS > 0 {
  338. return time.Duration(c.Serial.GetMotorTimeoutMS) * time.Millisecond
  339. }
  340. if c.Serial.ResponseTimeoutMS > 0 {
  341. return time.Duration(c.Serial.ResponseTimeoutMS) * time.Millisecond
  342. }
  343. return 2 * time.Second
  344. }
  345. func (c *Config) ProbeTimeout() time.Duration {
  346. if c.Serial.ProbeTimeoutMS > 0 {
  347. return time.Duration(c.Serial.ProbeTimeoutMS) * time.Millisecond
  348. }
  349. return c.GetMotorTimeout()
  350. }
  351. func (c *Config) OpenTimeout() time.Duration {
  352. if c.Serial.OpenTimeoutMS > 0 {
  353. return time.Duration(c.Serial.OpenTimeoutMS) * time.Millisecond
  354. }
  355. return 2 * time.Second
  356. }
  357. func (c *Config) ShutdownSafeTimeout() time.Duration {
  358. if c.Serial.ShutdownSafeMS > 0 {
  359. return time.Duration(c.Serial.ShutdownSafeMS) * time.Millisecond
  360. }
  361. return 500 * time.Millisecond
  362. }
  363. func (c *Config) ManagedRuntimeRoot() (string, error) {
  364. if c.RuntimeRoot != "" {
  365. return filepath.Abs(filepath.Clean(c.RuntimeRoot))
  366. }
  367. obsDir := filepath.Dir(c.Sockets.Observe)
  368. ctlDir := filepath.Dir(c.Sockets.Control)
  369. root := filepath.Clean(filepath.Dir(obsDir))
  370. other := filepath.Clean(filepath.Dir(ctlDir))
  371. if root != other {
  372. return "", fmt.Errorf("config: observe/control socket dirs must share a runtime root (got %s vs %s); set runtime_root", root, other)
  373. }
  374. switch root {
  375. case "/", "/tmp", "/run", "/var", "/var/run", "/dev", "/etc", ".":
  376. return "", fmt.Errorf("config: inferred runtime root %s is a protected parent; set runtime_root to a dedicated directory", root)
  377. }
  378. return filepath.Abs(root)
  379. }
  380. func ParseFileMode(s string, def os.FileMode) (os.FileMode, error) {
  381. s = strings.TrimSpace(s)
  382. if s == "" {
  383. return def, nil
  384. }
  385. v, err := strconv.ParseUint(s, 8, 32)
  386. if err != nil {
  387. v10, err2 := strconv.ParseUint(s, 10, 32)
  388. if err2 != nil {
  389. return 0, fmt.Errorf("invalid file mode %q", s)
  390. }
  391. v = v10
  392. }
  393. if v > 0o777 {
  394. return 0, fmt.Errorf("file mode %q out of range", s)
  395. }
  396. return os.FileMode(v), nil
  397. }
  398. func IntPtr(v int) *int { return &v }