EEBus: abort run loop and limit assertion on context cancellation (#32494)
This commit is contained in:
parent
4a878838e7
commit
fed3fb731c
8 changed files with 54 additions and 12 deletions
|
|
@ -22,6 +22,7 @@ func init() {
|
|||
|
||||
type EEBus struct {
|
||||
mux sync.RWMutex
|
||||
ctx context.Context // device lifetime, aborts Run
|
||||
log *util.Logger
|
||||
|
||||
*eebus.Connector
|
||||
|
|
@ -104,6 +105,7 @@ func NewEEBus(ctx context.Context, ski string, limits Limits, passthrough func(b
|
|||
}
|
||||
|
||||
c := &EEBus{
|
||||
ctx: ctx,
|
||||
log: util.NewLogger("eebus"),
|
||||
site: site,
|
||||
passthrough: passthrough,
|
||||
|
|
@ -192,14 +194,21 @@ func (c *EEBus) Connect(connected bool) {
|
|||
}
|
||||
}
|
||||
|
||||
// Run applies limits until the device context is cancelled
|
||||
func (c *EEBus) Run() {
|
||||
for range time.Tick(c.interval) {
|
||||
if err := c.run(); err != nil {
|
||||
c.log.ERROR.Println(err)
|
||||
}
|
||||
for tick := time.Tick(c.interval); ; {
|
||||
select {
|
||||
case <-tick:
|
||||
if err := c.run(); err != nil {
|
||||
c.log.ERROR.Println(err)
|
||||
}
|
||||
|
||||
if c.publishFunc != nil {
|
||||
c.publishFunc()
|
||||
if c.publishFunc != nil {
|
||||
c.publishFunc()
|
||||
}
|
||||
|
||||
case <-c.ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package eebus
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
|
|
@ -40,7 +41,9 @@ func newTestEEBus(t *testing.T) *EEBus {
|
|||
|
||||
failsafeProduction := testFailsafeProduction
|
||||
return &EEBus{
|
||||
ctx: t.Context(),
|
||||
log: util.NewLogger("test"),
|
||||
interval: time.Millisecond,
|
||||
site: &stubSite{},
|
||||
Connector: eebus.NewConnector(),
|
||||
heartbeat: util.NewValue[struct{}](time.Hour),
|
||||
|
|
@ -227,3 +230,27 @@ func TestEEBusEdgeTriggered(t *testing.T) {
|
|||
require.Equal(t, 1, calls, "passthrough must fire once on the edge, not every tick")
|
||||
assertConsumptionLimit(t, c, 3000)
|
||||
}
|
||||
|
||||
// TestRunAborts verifies the run loop terminates when the device context is
|
||||
// cancelled instead of ticking for the lifetime of the process.
|
||||
func TestRunAborts(t *testing.T) {
|
||||
c := newTestEEBus(t)
|
||||
c.interval = time.Hour // only the context can end the loop
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
c.ctx = ctx
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
c.Run()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Run did not return on cancelled context")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue