diff --git a/README.md b/README.md index 7661732..8762f81 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ The page can be added to the phone's home screen with its own icon: "Share → A "Air 5/15/30/60" sends `system_mode: off` for that many minutes, with 5 for a quick Stoßlüften. When the time is up, or on "Heat again", the room gets back the mode and target from before. -The service keeps no saved state, so a restart during airing forgets it: **that room stays off until someone taps "Heat again"**. A target waiting to be sent is lost too. The thermostat's own frost protection still applies. +Airing is saved, so it carries on after a restart or release: a room that should be off is turned off again, and one whose time ran out while the service was down gets heat back right away. A change that can't be saved isn't made, and the page says so. See [Saved state](#saved-state). - A target changed during airing is applied when it ends. - A thermostat leaving off during airing gets off once more. If it leaves off again, someone is at the radiator, so airing ends. So turning it on by hand during airing takes two tries. @@ -32,11 +32,27 @@ Optional: The chart needs Kubernetes and Helm. Without them, run the binary or image with `-config `, using the same settings as `config` in the chart's [`values.yaml`](charts/heating-control/values.yaml). -Nothing else is needed: no database, and no storage, because all state is in memory. +It also needs a writable directory that survives a restart, `dataDir`: the chart mounts a persistent volume there. See [Saved state](#saved-state). + +## Saved state + +The service keeps one SQLite database, `heating-control.db` in `dataDir`. It holds only what can't come back from the thermostats: for each room that is airing, when airing ends, the mode to go back to, and a target chosen during airing. A room's row is deleted once its thermostat confirms it is heating again, so the file is a few kilobytes. Everything else is in memory and comes back from the thermostats' reports. Migrations are part of the binary and run at start; an older binary refuses a newer database. + +A request is answered only once its change is saved. If saving fails, the change isn't made and the page shows "Not changed". When airing ends while the database can't be written, the room still gets heat back, and the database catches up later. + +If the file is lost, nothing unsafe happens: a room that was airing stays off until someone taps "Heat again" (the `TrvStuckOffWarning` alert fires after 2 hours), and a target chosen during airing is lost. Because of that, restoring a backup is optional: an old copy may even hold airing that is long over, which then simply ends at once. The service starts with an empty database if there is none, but refuses to start if it can't open or migrate the file. + +To copy the database while the service runs: + +```bash +kubectl exec -n deploy/ -- /heating-control backup /data/backup.db +``` + +The target must not exist yet. Copying it off the node is up to the cluster's backup. ## Deployment -The Helm chart in [`charts/heating-control`](charts/heating-control) is published with every release as `oci://ghcr.io/subpathdev/charts/heating-control`. Set `config.broker` and `config.rooms`; adding a room is one more entry in `config.rooms`. Run one replica only, and give any other instance its own `config.clientId`: a second client with the same ID disconnects the first. +The Helm chart in [`charts/heating-control`](charts/heating-control) is published with every release as `oci://ghcr.io/subpathdev/charts/heating-control`. Set `config.broker` and `config.rooms`; adding a room is one more entry in `config.rooms`. The chart creates a 64 Mi persistent volume for `config.dataDir` (see `persistence` in `values.yaml`), and keeps it when the release is uninstalled. Run one replica only, and give any other instance its own `config.clientId`: a second client with the same ID disconnects the first. ## API diff --git a/charts/heating-control/ci-values.yaml b/charts/heating-control/ci-values.yaml index ec6e039..5942dc0 100644 --- a/charts/heating-control/ci-values.yaml +++ b/charts/heating-control/ci-values.yaml @@ -13,3 +13,5 @@ serviceMonitor: enabled: true labels: release: kube-prometheus-stack +persistence: + storageClass: local-path diff --git a/charts/heating-control/templates/deployment.yaml b/charts/heating-control/templates/deployment.yaml index c170b18..84911e0 100644 --- a/charts/heating-control/templates/deployment.yaml +++ b/charts/heating-control/templates/deployment.yaml @@ -6,7 +6,8 @@ metadata: {{- include "heating-control.labels" . | nindent 4 }} spec: replicas: 1 - # A fixed MQTT client ID: two pods would keep disconnecting each other. + # A fixed MQTT client ID: two pods would keep disconnecting each other, and the + # database has one writer on a ReadWriteOnce volume. strategy: type: Recreate selector: @@ -25,6 +26,7 @@ spec: runAsNonRoot: true runAsUser: 65532 runAsGroup: 65532 + fsGroup: 65532 seccompProfile: type: RuntimeDefault containers: @@ -55,7 +57,12 @@ spec: - name: config mountPath: /etc/heating-control readOnly: true + - name: data + mountPath: {{ .Values.config.dataDir }} volumes: - name: config configMap: name: {{ .Release.Name }} + - name: data + persistentVolumeClaim: + claimName: {{ .Values.persistence.existingClaim | default (printf "%s-data" .Release.Name) }} diff --git a/charts/heating-control/templates/pvc.yaml b/charts/heating-control/templates/pvc.yaml new file mode 100644 index 0000000..dfa1cd0 --- /dev/null +++ b/charts/heating-control/templates/pvc.yaml @@ -0,0 +1,19 @@ +{{- if not .Values.persistence.existingClaim }} +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: {{ .Release.Name }}-data + labels: + {{- include "heating-control.labels" . | nindent 4 }} + annotations: + # Uninstalling the release keeps the saved airing. + helm.sh/resource-policy: keep +spec: + accessModes: ["ReadWriteOnce"] + {{- with .Values.persistence.storageClass }} + storageClassName: {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.persistence.size }} +{{- end }} diff --git a/charts/heating-control/values.schema.json b/charts/heating-control/values.schema.json index 8db5790..0571a84 100644 --- a/charts/heating-control/values.schema.json +++ b/charts/heating-control/values.schema.json @@ -4,9 +4,10 @@ "properties": { "config": { "type": "object", - "required": ["broker", "rooms"], + "required": ["broker", "rooms", "dataDir"], "properties": { "broker": { "type": "string", "minLength": 1 }, + "dataDir": { "type": "string", "pattern": "^/" }, "rooms": { "type": "array", "minItems": 1, @@ -24,6 +25,15 @@ } } }, + "persistence": { + "type": "object", + "required": ["size"], + "properties": { + "size": { "type": "string", "minLength": 1 }, + "storageClass": { "type": "string" }, + "existingClaim": { "type": "string" } + } + }, "service": { "type": "object", "properties": { diff --git a/charts/heating-control/values.yaml b/charts/heating-control/values.yaml index d91ec14..1c97fb1 100644 --- a/charts/heating-control/values.yaml +++ b/charts/heating-control/values.yaml @@ -18,6 +18,17 @@ config: rooms: [] # Host names the page is reached by. IP addresses and localhost always work. allowedHosts: [] + # Where the database with the saved airing lives. The persistent volume is + # mounted here. + dataDir: /data + +# The volume for dataDir. Losing it is safe, see "Saved state" in the README. +persistence: + size: 64Mi + # Empty uses the cluster's default storage class. + storageClass: "" + # Use this claim instead of creating one. + existingClaim: "" service: type: ClusterIP diff --git a/cmd/heating-control/main.go b/cmd/heating-control/main.go index e38efd8..985245e 100644 --- a/cmd/heating-control/main.go +++ b/cmd/heating-control/main.go @@ -1,10 +1,14 @@ // Command heating-control serves the phone page for the heating. +// +// heating-control [-config file] serves the page (the default) +// heating-control [-config file] backup copies the database while it runs package main import ( "context" "errors" "flag" + "fmt" "log" "net/http" "os" @@ -17,27 +21,81 @@ import ( "github.com/subpathdev/heating-control/internal/health" "github.com/subpathdev/heating-control/internal/metrics" "github.com/subpathdev/heating-control/internal/mqtt" + "github.com/subpathdev/heating-control/internal/sqlite" "github.com/subpathdev/heating-control/internal/web" ) // version is set at build time. var version = "dev" +// app holds what every command needs. +type app struct { + cfg *config.Config + db sqlite.DB +} + func main() { configPath := flag.String("config", "/etc/heating-control/config.yaml", "path to the config file") + flag.Usage = func() { + _, _ = fmt.Fprintf(flag.CommandLine.Output(), "usage: %s [-config file] [serve | backup ]\n", os.Args[0]) + flag.PrintDefaults() + } flag.Parse() - cfg, err := config.Load(*configPath) + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + if err := run(ctx, *configPath, flag.Args()); err != nil { + log.Fatal(err) + } +} + +func run(ctx context.Context, configPath string, args []string) error { + cfg, err := config.Load(configPath) + if err != nil { + return fmt.Errorf("config: %w", err) + } + db, err := sqlite.Open(ctx, cfg.DataDir) if err != nil { - log.Fatalf("config: %v", err) + return err } + a := &app{cfg: cfg, db: db} + defer func() { + if err := db.Close(); err != nil { + log.Printf("close database: %v", err) + } + }() - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) - defer stop() + switch { + case len(args) == 0 || len(args) == 1 && args[0] == "serve": + return a.serve(ctx) + case len(args) == 2 && args[0] == "backup": + return a.backup(ctx, args[1]) + default: + flag.Usage() + return fmt.Errorf("unknown command %q", args) + } +} - client := mqtt.New(cfg) +// backup writes a consistent copy of the database to path, which must not +// exist. It can run next to a serving instance. +func (a *app) backup(ctx context.Context, path string) error { + if err := a.db.Backup(ctx, path); err != nil { + return fmt.Errorf("backup to %s: %w", path, err) + } + log.Printf("database copied to %s", path) + return nil +} + +// serve runs the page, the API and the controller until ctx is done. +func (a *app) serve(ctx context.Context) error { + client := mqtt.New(a.cfg) m := metrics.New(version) - ctrl := controller.New(cfg, m.Thermostat(client)) + // Loaded before anything is sent, so a saved airing carries on. + ctrl, err := controller.New(ctx, a.cfg, m.Thermostat(client), a.db) + if err != nil { + return err + } client.Start(ctrl) defer client.Close() @@ -49,7 +107,7 @@ func main() { health.Register(mux, version, checker) mux.Handle("GET /metrics", m.Handler()) // Probes and scrapes use the pod's IP and stay outside the page's checks. - mux.Handle("/", web.Handler(ctrl, checker, cfg.AllowedHosts)) + mux.Handle("/", web.Handler(ctrl, checker, a.cfg.AllowedHosts)) srv := &http.Server{ Addr: ":8080", @@ -75,9 +133,11 @@ func main() { log.Printf("heating-control %s listening on %s", version, srv.Addr) if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { - log.Fatal(err) + return err } - // ListenAndServe returns as soon as Shutdown starts, so let requests finish. + // ListenAndServe returns as soon as Shutdown starts, so let requests finish, + // and the controller stop before the database closes. <-shutdownDone <-controllerDone + return nil } diff --git a/go.mod b/go.mod index f1c2742..f0ec12d 100644 --- a/go.mod +++ b/go.mod @@ -7,20 +7,28 @@ require ( github.com/oapi-codegen/runtime v1.9.1 github.com/prometheus/client_golang v1.25.0 gopkg.in/yaml.v3 v3.0.1 + modernc.org/sqlite v1.63.0 ) require ( github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/dustin/go-humanize v1.1.0 // indirect github.com/google/uuid v1.6.0 // indirect github.com/gorilla/websocket v1.5.3 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/ncruces/go-strftime v1.1.0 // indirect github.com/prometheus/client_model v0.6.3 // indirect github.com/prometheus/common v0.72.0 // indirect github.com/prometheus/procfs v0.22.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect golang.org/x/net v0.59.0 // indirect - golang.org/x/sync v0.22.0 // indirect - golang.org/x/sys v0.48.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.49.0 // indirect google.golang.org/protobuf v1.36.12 // indirect + modernc.org/libc v1.80.1 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.12.1 // indirect ) diff --git a/go.sum b/go.sum index ebefed8..0debf7d 100644 --- a/go.sum +++ b/go.sum @@ -7,21 +7,31 @@ github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvF github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= github.com/eclipse/paho.mqtt.golang v1.5.1 h1:/VSOv3oDLlpqR2Epjn1Q7b2bSTplJIeV2ISgCl2W7nE= github.com/eclipse/paho.mqtt.golang v1.5.1/go.mod h1:1/yJCneuyOoCOzKSsOTUc0AJfpsItBGWvYpBLimhArU= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= github.com/oapi-codegen/nullable v1.2.0 h1:VflFkDW980KhBPiFF7nWSyjg+r4Obqj8lXipV0UkP5w= github.com/oapi-codegen/nullable v1.2.0/go.mod h1:KUZ3vUzkmEKY90ksAmit2+5juDIhIZhfDl+0PwOQlFY= github.com/oapi-codegen/runtime v1.9.1 h1:77xKS3fIvTBRSCivMyY79002dqH1SMCunGjm/vB9eXY= @@ -35,6 +45,8 @@ github.com/prometheus/common v0.72.0 h1:tAYsE+sPJxIncDAobm4H5aQjmox9ZxEIIqPbiffa github.com/prometheus/common v0.72.0/go.mod h1:77NWqAQ2tXT7BIK40qjJdw5Acrsrg1TlHAnsQi3i6mk= github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics= github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= @@ -46,15 +58,47 @@ go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= -golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= -golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b h1:WE5SLOURcNd8s6uPR/n4WV4weQxxYKi5OpEZkfNVvdE= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.38.1 h1:wdxJVBuFT8JufZnnQyS6Bbz3NOWhViD0xJOGR96Bpd4= +modernc.org/ccgo/v4 v4.38.1/go.mod h1:kOpEkJRbFwBvjUWwn4j1j9B7iFHbl1+orhgTMCDkDBk= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o= +modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.80.1 h1:ejn7HtTV3GknNKbklqWQ1nvUrfX8mTxs1D+xp/JQwy4= +modernc.org/libc v1.80.1/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.63.0 h1:ClxazqRFNfr7XPHTVLbyzTVz2PjWPz+BfJNu2e8JDMs= +modernc.org/sqlite v1.63.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/internal/api/openapi.yaml b/internal/api/openapi.yaml index 4c9b8c8..d54753b 100644 --- a/internal/api/openapi.yaml +++ b/internal/api/openapi.yaml @@ -5,7 +5,7 @@ info: The contract between the heating-control backend and its page. Go types and the server interface are generated from this file, so change it first and run `go generate ./...`. - version: 0.2.0 + version: 0.3.0 paths: /api/rooms: get: @@ -79,7 +79,9 @@ paths: schema: $ref: "#/components/schemas/Error" "500": - description: The server failed to write the response. + description: >- + The server couldn't save the change, so nothing changed, or it failed + to write the response. content: application/json: schema: @@ -91,7 +93,8 @@ paths: description: >- When the time is up, heating comes back with the mode and target from before airing. Calling this again during airing sets a new end time. A 202 - means airing was accepted: follow airingState in the room list. + means airing was accepted and saved, so it carries on after a restart: + follow airingState in the room list. parameters: - name: id in: path @@ -127,7 +130,9 @@ paths: schema: $ref: "#/components/schemas/Error" "500": - description: The server failed to write the response. + description: >- + The server couldn't save the change, so nothing changed, or it failed + to write the response. content: application/json: schema: @@ -161,7 +166,9 @@ paths: schema: $ref: "#/components/schemas/Error" "500": - description: The server failed to write the response. + description: >- + The server couldn't save the change, so nothing changed, or it failed + to write the response. content: application/json: schema: diff --git a/internal/config/config.go b/internal/config/config.go index c9be043..6d5ace4 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -29,6 +29,9 @@ type Config struct { // AllowedHosts lists the host names the page is reached by. IP addresses and // localhost always work, so it's only needed for a DNS name. AllowedHosts []string `yaml:"allowedHosts"` + // DataDir holds the database with the saved airing. It must survive a + // restart, so in Kubernetes it's a persistent volume. + DataDir string `yaml:"dataDir"` } // Load reads and validates the file at path. @@ -53,6 +56,9 @@ func parse(data []byte) (*Config, error) { if cfg.Broker == "" { return nil, fmt.Errorf("broker is required") } + if cfg.DataDir == "" { + return nil, fmt.Errorf("dataDir is required") + } if cfg.MinTarget >= cfg.MaxTarget { return nil, fmt.Errorf("minTarget %v must be below maxTarget %v", cfg.MinTarget, cfg.MaxTarget) } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index b64cb45..c4c433f 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -5,6 +5,7 @@ import "testing" func TestParseDefaults(t *testing.T) { cfg, err := parse([]byte(` broker: tcp://mosquitto:1883 +dataDir: /data rooms: - {id: office, label: Office, trv: trv-office, sensor: temperature-sensor-office} `)) @@ -18,12 +19,13 @@ rooms: func TestParseRejects(t *testing.T) { tests := map[string]string{ - "no broker": `rooms: [{id: a, label: A, trv: t}]`, - "no rooms": `broker: x`, - "no trv": `{broker: x, rooms: [{id: a, label: A}]}`, - "duplicate": `{broker: x, rooms: [{id: a, label: A, trv: t}, {id: a, label: B, trv: u}]}`, - "same trv": `{broker: x, rooms: [{id: a, label: A, trv: t}, {id: b, label: B, trv: t}]}`, - "bad range": `{broker: x, minTarget: 25, maxTarget: 10, rooms: [{id: a, label: A, trv: t}]}`, + "no broker": `{dataDir: /d, rooms: [{id: a, label: A, trv: t}]}`, + "no dataDir": `{broker: x, rooms: [{id: a, label: A, trv: t}]}`, + "no rooms": `{broker: x, dataDir: /d}`, + "no trv": `{broker: x, dataDir: /d, rooms: [{id: a, label: A}]}`, + "duplicate": `{broker: x, dataDir: /d, rooms: [{id: a, label: A, trv: t}, {id: a, label: B, trv: u}]}`, + "same trv": `{broker: x, dataDir: /d, rooms: [{id: a, label: A, trv: t}, {id: b, label: B, trv: t}]}`, + "bad range": `{broker: x, dataDir: /d, minTarget: 25, maxTarget: 10, rooms: [{id: a, label: A, trv: t}]}`, } for name, in := range tests { t.Run(name, func(t *testing.T) { diff --git a/internal/controller/airing.go b/internal/controller/airing.go new file mode 100644 index 0000000..e6e1415 --- /dev/null +++ b/internal/controller/airing.go @@ -0,0 +1,71 @@ +package controller + +import ( + "context" + "errors" + "fmt" + "math" + "time" +) + +// ErrNotSaved is returned when a change couldn't be saved. The change is then +// not made, so a restart can't lose it. +var ErrNotSaved = errors.New("change not saved") + +// AiringStore keeps each room's airing, so a restart doesn't leave a room off +// or forget to turn it back on. +type AiringStore interface { + // Airings returns every saved airing. + Airings(ctx context.Context) ([]Airing, error) + // SaveAiring replaces the room's saved airing. It returns once the airing + // is durable. + SaveAiring(ctx context.Context, a Airing) error + // DeleteAiring removes the room's saved airing, if there is one. + DeleteAiring(ctx context.Context, roomID string) error +} + +// Airing is what a room's airing needs to carry on after a restart: when it +// ends, what to go back to, and a target that waits for it to end. +type Airing interface { + RoomID() string + // Until is when airing ends. ok is false once it has ended and the room is + // waiting for its thermostat to heat again. + Until() (until time.Time, ok bool) + // RestoreMode is the mode the thermostat goes back to. + RestoreMode() Mode + // HeldTarget is a target chosen during airing, applied when it ends. + HeldTarget() (target float64, ok bool) +} + +// RestoreAiring recreates a saved airing. until is the zero time once airing +// has ended, and heldTarget is nil without a held target. +func RestoreAiring(roomID string, until time.Time, restoreMode Mode, heldTarget *float64) (Airing, error) { + if roomID == "" { + return nil, errors.New("airing: room id is empty") + } + if restoreMode != ModeHeat && restoreMode != ModeAuto { + return nil, fmt.Errorf("airing: can't restore mode %q", restoreMode) + } + a := airing{roomID: roomID, until: until.UTC(), restoreMode: restoreMode} + if heldTarget != nil { + if math.IsNaN(*heldTarget) || math.IsInf(*heldTarget, 0) { + return nil, fmt.Errorf("airing: held target %v isn't a temperature", *heldTarget) + } + a.heldTarget, a.hasHeldTarget = *heldTarget, true + } + return a, nil +} + +// airing is comparable with ==, because until is always UTC. +type airing struct { + roomID string + until time.Time + restoreMode Mode + heldTarget float64 + hasHeldTarget bool +} + +func (a airing) RoomID() string { return a.roomID } +func (a airing) Until() (time.Time, bool) { return a.until, !a.until.IsZero() } +func (a airing) RestoreMode() Mode { return a.restoreMode } +func (a airing) HeldTarget() (float64, bool) { return a.heldTarget, a.hasHeldTarget } diff --git a/internal/controller/controller.go b/internal/controller/controller.go index 7531ec3..32b0ca5 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -5,8 +5,9 @@ // which is the only place that talks to a thermostat. So nothing that delivers a // report ever waits for a publish. // -// All state is in memory. After a restart a room that was airing stays off until -// someone taps "Heat again" on the page. +// Airing is saved in an AiringStore, so it carries on after a restart. A change +// that couldn't be saved isn't made. Everything else is in memory and comes back +// from the thermostats' reports. // // Three behaviours of the Sonoff TRVZB shape this code. They were measured on a // real device (firmware 1.3.0): @@ -87,6 +88,9 @@ var ErrTargetOutOfRange = errors.New("target out of range") // tickInterval is how often Run checks timeouts and retries without being woken. const tickInterval = 5 * time.Second +// saveTimeout bounds a write to the store. +const saveTimeout = 5 * time.Second + // Thermostat sends commands to a physical thermostat. type Thermostat interface { Apply(trv string, cmd Command) error @@ -121,18 +125,26 @@ type Controller struct { thermostat Thermostat now func() time.Time min, max float64 + store AiringStore wake chan struct{} - // mu guards the rooms' state and is never held during a publish. rooms itself - // and each room's cfg don't change after New. + // saveMu orders writes to the store, so an older state never overwrites a + // newer one. It is taken before mu. + saveMu sync.Mutex + // mu guards the rooms' state and is never held during a publish. A request + // holds it while its change is saved, so the change and the save are one + // step. rooms itself and each room's cfg don't change after New. mu sync.Mutex rooms []*room } -// New returns a Controller for the configured rooms. -func New(cfg *config.Config, thermostat Thermostat) *Controller { +// New returns a Controller for the configured rooms, carrying on with the +// airing saved in store. A saved airing for a room that is no longer configured +// is left in the store and ignored. +func New(ctx context.Context, cfg *config.Config, thermostat Thermostat, store AiringStore) (*Controller, error) { c := &Controller{ thermostat: thermostat, + store: store, now: time.Now, min: cfg.MinTarget, max: cfg.MaxTarget, @@ -141,7 +153,40 @@ func New(cfg *config.Config, thermostat Thermostat) *Controller { for _, r := range cfg.Rooms { c.rooms = append(c.rooms, &room{cfg: r}) } - return c + airings, err := store.Airings(ctx) + if err != nil { + return nil, fmt.Errorf("load airing: %w", err) + } + for _, a := range airings { + r := c.find(a.RoomID()) + if r == nil { + log.Printf("saved airing for unknown room %q ignored", a.RoomID()) + continue + } + trimmed := false + if target, ok := a.HeldTarget(); ok && !c.inRange(target) { + trimmed = true + // The range was changed since. Dropping the target is safe: the + // thermostat keeps its own. + log.Printf("%s: saved target %v is out of range, dropped", r.cfg.TRV, target) + a, err = RestoreAiring(a.RoomID(), untilOrZero(a), a.RestoreMode(), nil) + if err != nil { + return nil, err + } + } + r.resume(a) + if trimmed { + // The store still has the old target, so the next tick saves this one. + r.hasSaved = false + } + log.Printf("%s: carrying on with saved airing", r.cfg.TRV) + } + return c, nil +} + +func untilOrZero(a Airing) time.Time { + until, _ := a.Until() + return until } // Run sends commands until ctx is done. @@ -190,6 +235,58 @@ func (c *Controller) tick() { r.publishFailed = false c.mu.Unlock() } + for _, r := range c.rooms { + c.saveMu.Lock() + c.mu.Lock() + next, ok := r.pending() + c.mu.Unlock() + if err := c.save(r, next, ok); err != nil { + // Tried again on the next tick. + log.Printf("%s: save airing: %v", r.cfg.TRV, err) + } + c.saveMu.Unlock() + } +} + +// save writes the room's airing if it differs from what the store holds. The +// caller holds saveMu. +func (c *Controller) save(r *room, next airing, ok bool) error { + if ok == r.hasSaved && next == r.saved { + return nil + } + ctx, cancel := context.WithTimeout(context.Background(), saveTimeout) + defer cancel() + var err error + if ok { + err = c.store.SaveAiring(ctx, next) + } else { + err = c.store.DeleteAiring(ctx, r.cfg.ID) + } + if err != nil { + return err + } + r.saved, r.hasSaved = next, ok + return nil +} + +// change makes a requested change to a room and saves it. If it can't be saved, +// it isn't made. +func (c *Controller) change(r *room, apply func(now time.Time)) error { + c.saveMu.Lock() + defer c.saveMu.Unlock() + c.mu.Lock() + defer c.mu.Unlock() + + before := *r + apply(c.now()) + next, ok := r.pending() + if err := c.save(r, next, ok); err != nil { + *r = before + log.Printf("%s: save airing: %v", r.cfg.TRV, err) + return fmt.Errorf("%w: %v", ErrNotSaved, err) + } + c.signal() + return nil } func (c *Controller) signal() { @@ -216,51 +313,45 @@ func (c *Controller) Rooms() []RoomStatus { return out } -// SetTarget accepts a new target for a room. Run delivers it when it can. +// SetTarget accepts a new target for a room. Run delivers it when it can. During +// airing the target is saved, and ErrNotSaved means it wasn't accepted. func (c *Controller) SetTarget(id string, target float64) error { r := c.find(id) if r == nil { return fmt.Errorf("%w: %q", ErrUnknownRoom, id) } - // NaN fails both comparisons, so test for the valid range. - if !(target >= c.min && target <= c.max) { + if !c.inRange(target) { return fmt.Errorf("%w: %v is not within %v..%v", ErrTargetOutOfRange, target, c.min, c.max) } target = math.Round(target*2) / 2 + return c.change(r, func(time.Time) { r.setTarget(target) }) +} - c.mu.Lock() - r.setTarget(target) - c.mu.Unlock() - c.signal() - return nil +// inRange reports whether target is allowed. NaN fails both comparisons, so +// this tests for the valid range. +func (c *Controller) inRange(target float64) bool { + return target >= c.min && target <= c.max } // StartAiring stops heating a room for d. Called during airing, it sets a new -// end time. +// end time. ErrNotSaved means airing wasn't started. func (c *Controller) StartAiring(id string, d time.Duration) error { r := c.find(id) if r == nil { return fmt.Errorf("%w: %q", ErrUnknownRoom, id) } - c.mu.Lock() - r.startAiring(c.now().Add(d)) - c.mu.Unlock() - c.signal() - return nil + return c.change(r, func(now time.Time) { r.startAiring(now.Add(d)) }) } // StopAiring ends airing now. If the room isn't airing but its thermostat is -// off, it turns it back on. Otherwise it does nothing. +// off, it turns it back on. Otherwise it does nothing. ErrNotSaved means nothing +// changed. func (c *Controller) StopAiring(id string) error { r := c.find(id) if r == nil { return fmt.Errorf("%w: %q", ErrUnknownRoom, id) } - c.mu.Lock() - r.heatAgain(c.now()) - c.mu.Unlock() - c.signal() - return nil + return c.change(r, r.heatAgain) } // HandleThermostatState records a thermostat's report. diff --git a/internal/controller/controller_test.go b/internal/controller/controller_test.go index 61f7ae8..4f907b7 100644 --- a/internal/controller/controller_test.go +++ b/internal/controller/controller_test.go @@ -34,22 +34,37 @@ func (f *fakeThermostat) kinds() []string { // harness drives a Controller by hand: time and ticks only move when told to. type harness struct { - t *testing.T - c *Controller - f *fakeThermostat - now time.Time + t *testing.T + c *Controller + f *fakeThermostat + store *memStore + now time.Time } func newHarness(t *testing.T) *harness { t.Helper() - h := &harness{t: t, f: &fakeThermostat{}, now: time.Unix(1000, 0)} - h.c = New(&config.Config{ + return restartHarness(t, newMemStore(), time.Unix(1000, 0)) +} + +// restartHarness starts a Controller on what store holds, as after a restart. +func restartHarness(t *testing.T, store *memStore, now time.Time) *harness { + t.Helper() + h := &harness{t: t, f: &fakeThermostat{}, store: store, now: now} + c, err := New(context.Background(), testConfig(), h.f, store) + if err != nil { + t.Fatal(err) + } + h.c = c + h.c.now = func() time.Time { return h.now } + return h +} + +func testConfig() *config.Config { + return &config.Config{ MinTarget: 10, MaxTarget: 25, Rooms: []config.Room{{ID: "office", Label: "Office", TRV: "trv-office", Sensor: "sensor-office"}}, - }, h.f) - h.c.now = func() time.Time { return h.now } - return h + } } func ptr[T any](v T) *T { return &v } @@ -732,11 +747,14 @@ func TestParseMode(t *testing.T) { // Run is the only place that publishes, so reports and reads never wait for it. func TestRunDoesntBlockReportsDuringAPublish(t *testing.T) { block := &blockingThermostat{entered: make(chan struct{}), release: make(chan struct{})} - c := New(&config.Config{ + c, err := New(context.Background(), &config.Config{ MinTarget: 10, MaxTarget: 25, Rooms: []config.Room{{ID: "office", Label: "Office", TRV: "trv-office"}}, - }, block) + }, block, newMemStore()) + if err != nil { + t.Fatal(err) + } c.HandleThermostatState("trv-office", state("heat", 20)) ctx, cancel := context.WithCancel(context.Background()) diff --git a/internal/controller/room.go b/internal/controller/room.go index 36efa64..df0da77 100644 --- a/internal/controller/room.go +++ b/internal/controller/room.go @@ -87,6 +87,10 @@ type room struct { offConfirmed bool flips int targetFailed bool + + // What the store holds for this room. Guarded by Controller.saveMu, not mu. + saved airing + hasSaved bool } // decide returns the command the room needs now, if any. It changes nothing. @@ -344,3 +348,37 @@ func (r *room) isFrost(setpoint float64) bool { } return setpoint == frost } + +// pending returns what of the room's airing must survive a restart, or false +// if nothing must. +func (r *room) pending() (airing, bool) { + if r.airingUntil == nil && !r.restoring { + return airing{}, false + } + a := airing{roomID: r.cfg.ID, restoreMode: r.restoreMode} + if r.airingUntil != nil { + a.until = r.airingUntil.UTC() + } + if r.targetDirty && r.target != nil { + a.heldTarget, a.hasHeldTarget = *r.target, true + } + return a, true +} + +// resume carries on with an airing saved before a restart. The thermostat +// hasn't reported yet, so its off isn't confirmed: a report saying off confirms +// it, and once airing is over a report saying on can't be older than the off. +func (r *room) resume(a Airing) { + r.restoreMode = a.RestoreMode() + if until, ok := a.Until(); ok { + r.airingUntil = &until + } else { + r.restoring = true + } + if target, ok := a.HeldTarget(); ok { + r.target = &target + r.targetDirty = true + } + // It's what the store holds, so there's nothing to save until it changes. + r.saved, r.hasSaved = r.pending() +} diff --git a/internal/controller/store_test.go b/internal/controller/store_test.go new file mode 100644 index 0000000..54d02ff --- /dev/null +++ b/internal/controller/store_test.go @@ -0,0 +1,286 @@ +package controller + +import ( + "context" + "errors" + "maps" + "slices" + "sync" + "testing" + "time" +) + +// memStore is an AiringStore in memory. err makes every write fail. +type memStore struct { + mu sync.Mutex + airings map[string]Airing + writes int + err error +} + +func newMemStore() *memStore { + return &memStore{airings: map[string]Airing{}} +} + +func (m *memStore) Airings(context.Context) ([]Airing, error) { + m.mu.Lock() + defer m.mu.Unlock() + return slices.Collect(maps.Values(m.airings)), nil +} + +func (m *memStore) SaveAiring(_ context.Context, a Airing) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.err != nil { + return m.err + } + m.writes++ + m.airings[a.RoomID()] = a + return nil +} + +func (m *memStore) DeleteAiring(_ context.Context, roomID string) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.err != nil { + return m.err + } + m.writes++ + delete(m.airings, roomID) + return nil +} + +func (m *memStore) get(t *testing.T, roomID string) (Airing, bool) { + t.Helper() + m.mu.Lock() + defer m.mu.Unlock() + a, ok := m.airings[roomID] + return a, ok +} + +func mustAiring(t *testing.T, until time.Time, mode Mode, held *float64) Airing { + t.Helper() + a, err := RestoreAiring("office", until, mode, held) + if err != nil { + t.Fatal(err) + } + return a +} + +func TestRestoreAiringRejects(t *testing.T) { + nan := 0.0 + nan /= nan + tests := []struct { + name string + roomID string + mode Mode + held *float64 + }{ + {"no room", "", ModeHeat, nil}, + {"mode off", "office", ModeOff, nil}, + {"mode unknown", "office", ModeUnknown, nil}, + {"target NaN", "office", ModeHeat, &nan}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if _, err := RestoreAiring(tt.roomID, time.Time{}, tt.mode, tt.held); err == nil { + t.Error("want an error") + } + }) + } +} + +func TestAiringIsSavedUntilTheRestoreIsConfirmed(t *testing.T) { + h := newHarness(t) + h.report("heat", 20) + + h.startAiring(15 * time.Minute) + a, ok := h.store.get(t, "office") + if !ok { + t.Fatal("airing not saved when it started") + } + if until, ok := a.Until(); !ok || !until.Equal(h.now.Add(15*time.Minute)) { + t.Fatalf("saved until = %v, %v", until, ok) + } + if a.RestoreMode() != ModeHeat { + t.Fatalf("saved mode = %s", a.RestoreMode()) + } + h.report("off", 7) + + h.setTarget(22) + a, _ = h.store.get(t, "office") + if target, ok := a.HeldTarget(); !ok || target != 22 { + t.Fatalf("held target = %v, %v, want 22", target, ok) + } + + h.advance(15 * time.Minute) + a, ok = h.store.get(t, "office") + if _, airing := a.Until(); !ok || airing { + t.Fatal("ended airing not saved as restoring") + } + + h.report("heat", 22) + if _, ok := h.store.get(t, "office"); ok { + t.Fatal("airing still saved after the restore was confirmed") + } +} + +func TestNothingIsSavedWithoutAiring(t *testing.T) { + h := newHarness(t) + h.report("heat", 20) + h.setTarget(21) + h.report("heat", 21) + h.advance(time.Hour) + if h.store.writes != 0 { + t.Fatalf("%d writes without airing", h.store.writes) + } +} + +func TestChangeThatCantBeSavedIsNotMade(t *testing.T) { + h := newHarness(t) + h.report("heat", 20) + h.store.err = errors.New("disk full") + + if err := h.c.StartAiring("office", time.Hour); !errors.Is(err, ErrNotSaved) { + t.Fatalf("StartAiring = %v, want ErrNotSaved", err) + } + h.c.tick() + h.wantKinds() + if got := h.status().AiringState; got != AiringNone { + t.Fatalf("state = %s, want none", got) + } + + h.store.err = nil + h.startAiring(time.Hour) + h.report("off", 7) + h.store.err = errors.New("disk full") + if err := h.c.SetTarget("office", 23); !errors.Is(err, ErrNotSaved) { + t.Fatalf("SetTarget = %v, want ErrNotSaved", err) + } + if got := h.target(); got != 20 { + t.Fatalf("target = %v, want 20", got) + } + if err := h.c.StopAiring("office"); !errors.Is(err, ErrNotSaved) { + t.Fatalf("StopAiring = %v, want ErrNotSaved", err) + } + if got := h.status().AiringState; got != AiringActive { + t.Fatalf("state = %s, want active", got) + } +} + +// When the end of airing can't be saved, it still ends: the thermostat must not +// stay off. The store catches up later. +func TestFailedSaveDoesntStopTheRestore(t *testing.T) { + h := newHarness(t) + h.report("heat", 20) + h.startAiring(15 * time.Minute) + h.report("off", 7) + + h.store.err = errors.New("disk full") + h.advance(15 * time.Minute) + h.wantKinds("off", "restore") + if a, _ := h.store.get(t, "office"); func() bool { _, ok := a.Until(); return !ok }() { + t.Fatal("restoring saved although the store fails") + } + + h.store.err = nil + h.advance(tickInterval) + a, ok := h.store.get(t, "office") + if _, airing := a.Until(); !ok || airing { + t.Fatal("restoring not saved once the store works again") + } +} + +func TestAiringCarriesOnAfterARestart(t *testing.T) { + store := newMemStore() + now := time.Unix(5000, 0) + store.airings["office"] = mustAiring(t, now.Add(10*time.Minute), ModeAuto, nil) + + h := restartHarness(t, store, now) + if got := h.status().AiringState; got != AiringStarting { + t.Fatalf("state = %s, want starting", got) + } + h.report("heat", 20) + h.wantKinds("off") + h.report("off", 7) + if got := h.status().AiringState; got != AiringActive { + t.Fatalf("state = %s, want active", got) + } + + h.advance(10 * time.Minute) + h.wantKinds("off", "restore") + if got := *h.f.sent[1].Mode; got != ModeAuto { + t.Fatalf("restored mode %s, want auto", got) + } + // The restart forgot the target from before, and the thermostat brings back + // its own setpoint with the mode. + if h.f.sent[1].Target != nil { + t.Fatalf("restore sent target %v, want none", *h.f.sent[1].Target) + } + h.advance(retryInterval) + h.report("auto", 20) + if got := h.status().AiringState; got != AiringNone { + t.Fatalf("state = %s, want none", got) + } + if _, ok := store.get(t, "office"); ok { + t.Fatal("airing still saved") + } +} + +func TestAiringThatEndedDuringARestartRestoresAtOnce(t *testing.T) { + store := newMemStore() + now := time.Unix(5000, 0) + held := 21.5 + store.airings["office"] = mustAiring(t, now.Add(-time.Hour), ModeHeat, &held) + + h := restartHarness(t, store, now) + h.c.tick() + h.wantKinds("restore") + if got := *h.f.sent[0].Target; got != 21.5 { + t.Fatalf("restored target %v, want 21.5", got) + } + h.advance(retryInterval) + h.report("heat", 21.5) + if got := h.status().AiringState; got != AiringNone { + t.Fatalf("state = %s, want none", got) + } +} + +func TestRestoringCarriesOnAfterARestart(t *testing.T) { + store := newMemStore() + store.airings["office"] = mustAiring(t, time.Time{}, ModeHeat, nil) + + h := restartHarness(t, store, time.Unix(5000, 0)) + if got := h.status().AiringState; got != AiringRestoring { + t.Fatalf("state = %s, want restoring", got) + } + h.c.tick() + h.wantKinds("restore") + if h.store.writes != 0 { + t.Fatalf("%d writes for an unchanged airing", h.store.writes) + } +} + +func TestSavedAiringOutsideTheConfigIsTrimmed(t *testing.T) { + store := newMemStore() + now := time.Unix(5000, 0) + tooHot := 30.0 + store.airings["office"] = mustAiring(t, now.Add(time.Hour), ModeHeat, &tooHot) + gone, err := RestoreAiring("attic", now.Add(time.Hour), ModeHeat, nil) + if err != nil { + t.Fatal(err) + } + store.airings["attic"] = gone + + h := restartHarness(t, store, now) + if s := h.status(); s.AiringState != AiringStarting || s.Target != nil { + t.Fatalf("status = %+v, want airing without a target", s) + } + h.c.tick() + if a, _ := store.get(t, "office"); func() bool { _, ok := a.HeldTarget(); return ok }() { + t.Fatal("store still has the out-of-range target") + } + if _, ok := store.get(t, "attic"); !ok { + t.Fatal("airing of an unknown room was deleted") + } +} diff --git a/internal/sqlite/migrations/0001_airing.sql b/internal/sqlite/migrations/0001_airing.sql new file mode 100644 index 0000000..d030d1c --- /dev/null +++ b/internal/sqlite/migrations/0001_airing.sql @@ -0,0 +1,10 @@ +-- One row per room that is airing, or whose airing has ended and is waiting for +-- the thermostat to heat again. +CREATE TABLE airing ( + room_id TEXT PRIMARY KEY, + -- RFC 3339 in UTC. NULL once airing has ended. + until TEXT, + restore_mode TEXT NOT NULL CHECK (restore_mode IN ('heat', 'auto')), + -- A target chosen during airing, in °C. NULL if there is none. + held_target REAL +) STRICT; diff --git a/internal/sqlite/sqlite.go b/internal/sqlite/sqlite.go new file mode 100644 index 0000000..ef79369 --- /dev/null +++ b/internal/sqlite/sqlite.go @@ -0,0 +1,205 @@ +// Package sqlite keeps the controller's saved state in a SQLite database. +package sqlite + +import ( + "context" + "database/sql" + "embed" + "errors" + "fmt" + "io/fs" + "net/url" + "path/filepath" + "slices" + "strconv" + "strings" + "time" + + // Registers the pure Go "sqlite" driver. + _ "modernc.org/sqlite" + + "github.com/subpathdev/heating-control/internal/controller" +) + +// FileName is the database's name in the data directory. +const FileName = "heating-control.db" + +//go:embed migrations/*.sql +var migrations embed.FS + +// DB is the saved state. It is safe for concurrent use. +type DB interface { + controller.AiringStore + // Backup writes a consistent copy of the database to path, which must not + // exist yet. It works while the service runs. + Backup(ctx context.Context, path string) error + Close() error +} + +type db struct { + sql *sql.DB +} + +// Open opens or creates the database in dir and brings its schema up to date. +func Open(ctx context.Context, dir string) (DB, error) { + path := filepath.Join(dir, FileName) + // WAL lets a backup read while the service writes. synchronous FULL makes a + // commit durable before it returns. Temporary data stays in memory, because + // the root filesystem is read-only. + q := url.Values{} + q.Add("_pragma", "journal_mode(WAL)") + q.Add("_pragma", "synchronous(FULL)") + q.Add("_pragma", "busy_timeout(5000)") + q.Add("_pragma", "foreign_keys(ON)") + q.Add("_pragma", "temp_store(MEMORY)") + q.Set("_txlock", "immediate") + conn, err := sql.Open("sqlite", "file:"+(&url.URL{Path: path}).EscapedPath()+"?"+q.Encode()) + if err != nil { + return nil, fmt.Errorf("open %s: %w", path, err) + } + // One writer, and pragmas apply per connection. + conn.SetMaxOpenConns(1) + d := &db{sql: conn} + if err := d.migrate(ctx); err != nil { + return nil, errors.Join(fmt.Errorf("migrate %s: %w", path, err), conn.Close()) + } + return d, nil +} + +func (d *db) Close() error { + return d.sql.Close() +} + +// migrate applies the migrations newer than the database's user_version, each in +// its own transaction. File n (counting from 1) brings the schema to version n. +func (d *db) migrate(ctx context.Context) error { + files, err := fs.Glob(migrations, "migrations/*.sql") + if err != nil { + return err + } + slices.Sort(files) + var current int + if err := d.sql.QueryRowContext(ctx, "PRAGMA user_version").Scan(¤t); err != nil { + return err + } + if current > len(files) { + return fmt.Errorf("schema version %d is newer than this program (%d)", current, len(files)) + } + for i, file := range files { + version := i + 1 + name := filepath.Base(file) + if prefix, _, _ := strings.Cut(name, "_"); prefix != fmt.Sprintf("%04d", version) { + return fmt.Errorf("migration %s should be numbered %04d", name, version) + } + if version <= current { + continue + } + body, err := migrations.ReadFile(file) + if err != nil { + return err + } + if err := d.apply(ctx, version, string(body)); err != nil { + return fmt.Errorf("%s: %w", name, err) + } + } + return nil +} + +func (d *db) apply(ctx context.Context, version int, body string) (err error) { + tx, err := d.sql.BeginTx(ctx, nil) + if err != nil { + return err + } + defer func() { + if err != nil { + err = errors.Join(err, tx.Rollback()) + } + }() + if _, err := tx.ExecContext(ctx, body); err != nil { + return err + } + // PRAGMA takes no parameters, and version is an int. + if _, err := tx.ExecContext(ctx, "PRAGMA user_version = "+strconv.Itoa(version)); err != nil { + return err + } + return tx.Commit() +} + +// airingRow is a row of the airing table. +type airingRow struct { + roomID string + until sql.NullString + restoreMode string + heldTarget sql.NullFloat64 +} + +func toAiringRow(a controller.Airing) airingRow { + row := airingRow{roomID: a.RoomID(), restoreMode: string(a.RestoreMode())} + if until, ok := a.Until(); ok { + row.until = sql.NullString{String: until.UTC().Format(time.RFC3339Nano), Valid: true} + } + if target, ok := a.HeldTarget(); ok { + row.heldTarget = sql.NullFloat64{Float64: target, Valid: true} + } + return row +} + +func (row airingRow) toAiring() (controller.Airing, error) { + var until time.Time + if row.until.Valid { + var err error + if until, err = time.Parse(time.RFC3339Nano, row.until.String); err != nil { + return nil, fmt.Errorf("room %q: until: %w", row.roomID, err) + } + } + mode, err := controller.ParseMode(row.restoreMode) + if err != nil { + return nil, fmt.Errorf("room %q: %w", row.roomID, err) + } + var target *float64 + if row.heldTarget.Valid { + target = &row.heldTarget.Float64 + } + return controller.RestoreAiring(row.roomID, until, mode, target) +} + +func (d *db) Airings(ctx context.Context) ([]controller.Airing, error) { + rows, err := d.sql.QueryContext(ctx, "SELECT room_id, until, restore_mode, held_target FROM airing ORDER BY room_id") + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + var out []controller.Airing + for rows.Next() { + var row airingRow + if err := rows.Scan(&row.roomID, &row.until, &row.restoreMode, &row.heldTarget); err != nil { + return nil, err + } + a, err := row.toAiring() + if err != nil { + return nil, err + } + out = append(out, a) + } + return out, rows.Err() +} + +func (d *db) SaveAiring(ctx context.Context, a controller.Airing) error { + row := toAiringRow(a) + _, err := d.sql.ExecContext(ctx, ` + INSERT INTO airing (room_id, until, restore_mode, held_target) VALUES (?, ?, ?, ?) + ON CONFLICT (room_id) DO UPDATE SET + until = excluded.until, restore_mode = excluded.restore_mode, held_target = excluded.held_target`, + row.roomID, row.until, row.restoreMode, row.heldTarget) + return err +} + +func (d *db) DeleteAiring(ctx context.Context, roomID string) error { + _, err := d.sql.ExecContext(ctx, "DELETE FROM airing WHERE room_id = ?", roomID) + return err +} + +func (d *db) Backup(ctx context.Context, path string) error { + _, err := d.sql.ExecContext(ctx, "VACUUM INTO ?", path) + return err +} diff --git a/internal/sqlite/sqlite_test.go b/internal/sqlite/sqlite_test.go new file mode 100644 index 0000000..e3175f4 --- /dev/null +++ b/internal/sqlite/sqlite_test.go @@ -0,0 +1,220 @@ +package sqlite + +import ( + "context" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/subpathdev/heating-control/internal/config" + "github.com/subpathdev/heating-control/internal/controller" +) + +func open(t *testing.T, dir string) DB { + t.Helper() + d, err := Open(context.Background(), dir) + if err != nil { + t.Fatal(err) + } + return d +} + +func airing(t *testing.T, room string, until time.Time, mode controller.Mode, held *float64) controller.Airing { + t.Helper() + a, err := controller.RestoreAiring(room, until, mode, held) + if err != nil { + t.Fatal(err) + } + return a +} + +func TestAiringRoundTrip(t *testing.T) { + ctx := context.Background() + d := open(t, t.TempDir()) + defer func() { _ = d.Close() }() + + until := time.Date(2026, 12, 4, 17, 30, 0, 123456789, time.FixedZone("CET", 3600)) + held := 21.5 + tests := []controller.Airing{ + airing(t, "office", until, controller.ModeHeat, nil), + airing(t, "bedroom", time.Time{}, controller.ModeAuto, &held), + } + for _, a := range tests { + if err := d.SaveAiring(ctx, a); err != nil { + t.Fatal(err) + } + } + got, err := d.Airings(ctx) + if err != nil { + t.Fatal(err) + } + if len(got) != 2 { + t.Fatalf("got %d airings, want 2", len(got)) + } + // Ordered by room id. + bedroom, office := got[0], got[1] + if gotUntil, ok := office.Until(); !ok || !gotUntil.Equal(until) { + t.Errorf("office until = %v, %v, want %v", gotUntil, ok, until) + } + if _, ok := office.HeldTarget(); ok || office.RestoreMode() != controller.ModeHeat { + t.Errorf("office = %+v", office) + } + if _, ok := bedroom.Until(); ok { + t.Error("bedroom has an end time, want restoring") + } + if target, ok := bedroom.HeldTarget(); !ok || target != 21.5 || bedroom.RestoreMode() != controller.ModeAuto { + t.Errorf("bedroom = %+v", bedroom) + } +} + +func TestSaveReplacesAndDeleteRemoves(t *testing.T) { + ctx := context.Background() + d := open(t, t.TempDir()) + defer func() { _ = d.Close() }() + + until := time.Date(2026, 12, 4, 17, 0, 0, 0, time.UTC) + if err := d.SaveAiring(ctx, airing(t, "office", until, controller.ModeHeat, nil)); err != nil { + t.Fatal(err) + } + if err := d.SaveAiring(ctx, airing(t, "office", time.Time{}, controller.ModeHeat, nil)); err != nil { + t.Fatal(err) + } + got, err := d.Airings(ctx) + if err != nil { + t.Fatal(err) + } + if len(got) != 1 { + t.Fatalf("got %d airings, want 1", len(got)) + } + if _, ok := got[0].Until(); ok { + t.Fatal("save didn't replace the end time") + } + + if err := d.DeleteAiring(ctx, "office"); err != nil { + t.Fatal(err) + } + if err := d.DeleteAiring(ctx, "office"); err != nil { + t.Fatalf("deleting twice: %v", err) + } + if got, err := d.Airings(ctx); err != nil || len(got) != 0 { + t.Fatalf("Airings = %v, %v, want none", got, err) + } +} + +func TestOpenRefusesANewerSchema(t *testing.T) { + dir := t.TempDir() + d := open(t, dir) + if _, err := d.(*db).sql.Exec("PRAGMA user_version = 99"); err != nil { + t.Fatal(err) + } + if err := d.Close(); err != nil { + t.Fatal(err) + } + if _, err := Open(context.Background(), dir); err == nil { + t.Fatal("want an error for a newer schema") + } +} + +func TestBackupIsAConsistentCopy(t *testing.T) { + ctx := context.Background() + dir := t.TempDir() + d := open(t, dir) + defer func() { _ = d.Close() }() + if err := d.SaveAiring(ctx, airing(t, "office", time.Time{}, controller.ModeHeat, nil)); err != nil { + t.Fatal(err) + } + + // Named like the database, so the copy opens as one. + restoreDir := t.TempDir() + path := filepath.Join(restoreDir, FileName) + if err := d.Backup(ctx, path); err != nil { + t.Fatal(err) + } + if err := d.Backup(ctx, path); err == nil { + t.Fatal("backup overwrote an existing file") + } + + restored := open(t, restoreDir) + defer func() { _ = restored.Close() }() + got, err := restored.Airings(ctx) + if err != nil || len(got) != 1 || got[0].RoomID() != "office" { + t.Fatalf("backup has %v, %v", got, err) + } +} + +// The end-to-end case: airing started before a restart ends on time after it. +func TestAiringSurvivesReopenAndTheRestoreFires(t *testing.T) { + ctx := context.Background() + dir := t.TempDir() + cfg := &config.Config{ + MinTarget: 10, + MaxTarget: 25, + Rooms: []config.Room{{ID: "office", Label: "Office", TRV: "trv-office"}}, + } + + before := open(t, dir) + first, err := controller.New(ctx, cfg, &recorder{}, before) + if err != nil { + t.Fatal(err) + } + first.HandleThermostatState("trv-office", report(controller.ModeHeat, 20)) + if err := first.StartAiring("office", 50*time.Millisecond); err != nil { + t.Fatal(err) + } + if err := first.SetTarget("office", 22); err != nil { + t.Fatal(err) + } + if err := before.Close(); err != nil { + t.Fatal(err) + } + time.Sleep(100 * time.Millisecond) + + after := open(t, dir) + defer func() { _ = after.Close() }() + rec := &recorder{sent: make(chan controller.Command, 10)} + second, err := controller.New(ctx, cfg, rec, after) + if err != nil { + t.Fatal(err) + } + runCtx, cancel := context.WithCancel(ctx) + done := make(chan struct{}) + go func() { + second.Run(runCtx) + close(done) + }() + defer func() { + cancel() + <-done + }() + + select { + case cmd := <-rec.sent: + if cmd.Kind() != "restore" || *cmd.Mode != controller.ModeHeat || cmd.Target == nil || *cmd.Target != 22 { + t.Fatalf("sent %s, want restore to heat at 22", cmd.Kind()) + } + case <-time.After(5 * time.Second): + t.Fatal("no restore after the restart") + } + if got := second.Rooms()[0].AiringState; got != controller.AiringRestoring { + t.Fatalf("state = %s, want restoring", got) + } +} + +type recorder struct { + mu sync.Mutex + sent chan controller.Command +} + +func (r *recorder) Apply(_ string, cmd controller.Command) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.sent != nil { + r.sent <- cmd + } + return nil +} + +func report(mode controller.Mode, setpoint float64) controller.ThermostatState { + return controller.ThermostatState{Mode: &mode, Setpoint: &setpoint} +} diff --git a/internal/web/web.go b/internal/web/web.go index 63f3ae8..52330a5 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -33,6 +33,9 @@ func init() { const maxBodyBytes = 1024 +// notSaved is shown on the page after "Not changed: ". +const notSaved = "the server couldn't save it" + // Rooms is what the page can read and change. type Rooms interface { Rooms() []controller.RoomStatus @@ -147,6 +150,8 @@ func (s server) SetRoomTarget(_ context.Context, r api.SetRoomTargetRequestObjec return api.SetRoomTarget404JSONResponse{Message: err.Error()}, nil case errors.Is(err, controller.ErrTargetOutOfRange): return api.SetRoomTarget400JSONResponse{Message: err.Error()}, nil + case errors.Is(err, controller.ErrNotSaved): + return api.SetRoomTarget500JSONResponse{Message: notSaved}, nil default: return nil, err } @@ -161,6 +166,8 @@ func (s server) StartRoomAiring(_ context.Context, r api.StartRoomAiringRequestO return api.StartRoomAiring202Response{}, nil case errors.Is(err, controller.ErrUnknownRoom): return api.StartRoomAiring404JSONResponse{Message: err.Error()}, nil + case errors.Is(err, controller.ErrNotSaved): + return api.StartRoomAiring500JSONResponse{Message: notSaved}, nil default: return nil, err } @@ -172,6 +179,8 @@ func (s server) StopRoomAiring(_ context.Context, r api.StopRoomAiringRequestObj return api.StopRoomAiring202Response{}, nil case errors.Is(err, controller.ErrUnknownRoom): return api.StopRoomAiring404JSONResponse{Message: err.Error()}, nil + case errors.Is(err, controller.ErrNotSaved): + return api.StopRoomAiring500JSONResponse{Message: notSaved}, nil default: return nil, err } diff --git a/internal/web/web_test.go b/internal/web/web_test.go index dd48903..e27c250 100644 --- a/internal/web/web_test.go +++ b/internal/web/web_test.go @@ -211,6 +211,7 @@ func TestSetTargetErrors(t *testing.T) { {"unknown room", `{"target":20}`, controller.ErrUnknownRoom, http.StatusNotFound}, {"out of range", `{"target":99}`, controller.ErrTargetOutOfRange, http.StatusBadRequest}, {"unexpected", `{"target":20}`, errors.New("bug"), http.StatusInternalServerError}, + {"not saved", `{"target":20}`, controller.ErrNotSaved, http.StatusInternalServerError}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -271,6 +272,7 @@ func TestStartAiringErrors(t *testing.T) { {"missing", `{}`, nil, http.StatusBadRequest}, {"bad json", `nope`, nil, http.StatusBadRequest}, {"unknown room", `{"minutes":15}`, controller.ErrUnknownRoom, http.StatusNotFound}, + {"not saved", `{"minutes":15}`, controller.ErrNotSaved, http.StatusInternalServerError}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -301,6 +303,10 @@ func TestStopAiring(t *testing.T) { if rec := do(handler(&fakeRooms{err: controller.ErrUnknownRoom})); rec.Code != http.StatusNotFound { t.Fatalf("status %d, want 404", rec.Code) } + if rec := do(handler(&fakeRooms{err: controller.ErrNotSaved})); rec.Code != http.StatusInternalServerError || + !strings.Contains(rec.Body.String(), notSaved) { + t.Fatalf("status %d, body %s, want 500 saying it wasn't saved", rec.Code, rec.Body.String()) + } } func TestOtherWebsitesAreRefused(t *testing.T) {