| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770 |
- package device_test
- import (
- "context"
- "fmt"
- "strings"
- "sync"
- "testing"
- "time"
- "google.golang.org/protobuf/types/known/durationpb"
- "google.golang.org/protobuf/types/known/timestamppb"
- "hth/internal/backend"
- "hth/internal/clock"
- "hth/internal/config"
- "hth/internal/control"
- "hth/internal/device"
- hthv1 "hth/internal/gen/hth/api/v1"
- "hth/internal/ids"
- "hth/internal/profile"
- "hth/internal/protocol"
- "hth/internal/testutil"
- )
- func testDev(t *testing.T, mock *backend.Mock) *device.Device {
- t.Helper()
- p, err := profile.Load(testutil.ProfilePath(t))
- if err != nil {
- t.Fatal(err)
- }
- fan, ptc, door := 10, 0, 0
- dir := t.TempDir()
- cfg := &config.Config{
- APIVersion: "hth.api.v1",
- DeviceID: "prod2u-0",
- Backend: config.BackendMock,
- Profile: testutil.ProfilePath(t),
- RuntimeRoot: dir,
- Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
- Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
- Watchdog: config.Watchdog{HeartbeatPeriodMS: 5000},
- Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
- Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
- RingBufferSize: 32,
- SubscriberBufferSize: 64,
- CommandCacheSize: 16,
- AllowUnboundActions: true,
- Mock: config.Mock{Seed: 1, StartupComplete: true},
- }
- if err := cfg.Validate(p); err != nil {
- t.Fatal(err)
- }
- d := device.New(device.Params{Config: cfg, Profile: p, Backend: mock, InstanceID: "test"})
- ctx, cancel := context.WithCancel(context.Background())
- t.Cleanup(func() { cancel(); d.Stop() })
- d.Start(ctx)
- waitReady(t, d)
- return d
- }
- func waitReady(t *testing.T, d *device.Device) {
- t.Helper()
- deadline := time.Now().Add(3 * time.Second)
- for time.Now().Before(deadline) {
- s := d.Snapshot()
- if s != nil && (s.Lifecycle == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY ||
- s.Lifecycle == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_DEGRADED) {
- // Allow slew budget from the epoch Safe Baseline (100%/s) before tests dispatch.
- time.Sleep(time.Second)
- return
- }
- time.Sleep(10 * time.Millisecond)
- }
- s := d.Snapshot()
- t.Fatalf("not ready: %+v", s.GetLifecycle())
- }
- func acquire(t *testing.T, d *device.Device) *hthv1.ControlLease {
- t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
- l, err := d.AcquireLease(ctx, "tester", 400*time.Millisecond)
- if err != nil {
- t.Fatal(err)
- }
- return l
- }
- func batch(d *device.Device, l *hthv1.ControlLease, id string, doors uint8) *hthv1.ActionBatch {
- s := d.Snapshot()
- return &hthv1.ActionBatch{
- DeviceId: d.ID(), CommandId: id, LeaseId: l.LeaseId, LeaseEpoch: l.LeaseEpoch,
- BasedOnSnapshotSeq: s.SnapshotSeq, ExpectedControlRevision: s.ControlRevision,
- ValidUntil: timestamppb.New(time.Now().Add(20 * time.Second)),
- ClientId: "test",
- ContinuousTargets: []*hthv1.ContinuousTarget{
- {Id: ids.Fan1, Value: 20}, {Id: ids.Fan2, Value: 20}, {Id: ids.Fan3, Value: 20}, {Id: ids.Fan4, Value: 20},
- {Id: ids.PTC1, Value: 0}, {Id: ids.PTC2, Value: 0}, {Id: ids.PTC3, Value: 0}, {Id: ids.PTC4, Value: 0},
- {Id: ids.DoorX, Value: float64(doors)}, {Id: ids.DoorY, Value: float64(doors)}, {Id: ids.DoorZ, Value: float64(doors)},
- },
- }
- }
- func TestNoConfirmedOnSetAll(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- ctx := context.Background()
- res := d.ApplyAction(ctx, batch(d, l, "c1", 50))
- if !res.Accepted {
- t.Fatal(res.Message, res.RejectReason)
- }
- if res.Confirmation == hthv1.ConfirmationStatus_CONFIRMATION_STATUS_CONFIRMED {
- t.Fatal("SET_ALL must never be CONFIRMED")
- }
- if res.Confirmation != hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED {
- t.Fatalf("got %v", res.Confirmation)
- }
- }
- func TestCommandIDCacheNoSecondWrite(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- ctx := context.Background()
- b := batch(d, l, "same", 40)
- n0 := m.WriteCount()
- r1 := d.ApplyAction(ctx, b)
- r2 := d.ApplyAction(ctx, b)
- if !r2.ReplayedFromCache {
- t.Fatal("expected cache replay")
- }
- if m.WriteCount()-n0 != 1 {
- t.Fatalf("writes %d", m.WriteCount()-n0)
- }
- if r1.Confirmation != r2.Confirmation {
- t.Fatal("replay result mismatch")
- }
- }
- func TestCommandIDConflict(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- ctx := context.Background()
- b := batch(d, l, "cid", 10)
- d.ApplyAction(ctx, b)
- b2 := batch(d, l, "cid", 20)
- r := d.ApplyAction(ctx, b2)
- if r.RejectReason != hthv1.RejectReason_REJECT_REASON_IDEMPOTENCY_CONFLICT {
- t.Fatalf("got %v %s", r.RejectReason, r.Message)
- }
- }
- func TestHeartbeatKeepsDoorPercents(t *testing.T) {
- m := backend.NewMock(1, true)
- p, err := profile.Load(testutil.ProfilePath(t))
- if err != nil {
- t.Fatal(err)
- }
- fan, ptc, door := 10, 0, 0
- dir := t.TempDir()
- cfg := &config.Config{
- APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
- Profile: testutil.ProfilePath(t), RuntimeRoot: dir,
- Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
- Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
- Watchdog: config.Watchdog{HeartbeatPeriodMS: 80},
- Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
- Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
- RingBufferSize: 32, SubscriberBufferSize: 64, CommandCacheSize: 16,
- AllowUnboundActions: true,
- Mock: config.Mock{Seed: 1, StartupComplete: true},
- }
- if err := cfg.Validate(p); err != nil {
- t.Fatal(err)
- }
- d := device.New(device.Params{Config: cfg, Profile: p, Backend: m, InstanceID: "hb"})
- ctx, cancel := context.WithCancel(context.Background())
- t.Cleanup(func() { cancel(); d.Stop() })
- d.Start(ctx)
- waitReady(t, d)
- l := acquire(t, d)
- res := d.ApplyAction(context.Background(), batch(d, l, "doors50", 50))
- if !res.Accepted {
- t.Fatal(res)
- }
- time.Sleep(200 * time.Millisecond)
- writes := m.Writes()
- seen := false
- for _, w := range writes {
- if w.DoorX == 50 && w.DoorY == 50 && w.DoorZ == 50 {
- seen = true
- continue
- }
- if seen && (w.DoorX != 50 || w.DoorY != 50 || w.DoorZ != 50) {
- t.Fatalf("heartbeat rewrote doors to %+v", w)
- }
- }
- if !seen {
- t.Fatalf("never dispatched doors=50, writes=%d", len(writes))
- }
- }
- func TestNoAutoRetryUnknownDoorDispatch(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- m.ForceShortWrite()
- ctx := context.Background()
- res := d.ApplyAction(ctx, batch(d, l, "unk", 70))
- if res.Confirmation != hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN {
- t.Fatalf("got %v", res.Confirmation)
- }
- time.Sleep(150 * time.Millisecond)
- for _, w := range m.Writes() {
- if w.DoorX == 70 || w.DoorY == 70 || w.DoorZ == 70 {
- t.Fatal("must not auto-retry unknown door percent change")
- }
- }
- }
- func TestLeaseExpireAndReconnectInvalidate(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- time.Sleep(600 * time.Millisecond)
- ctx := context.Background()
- res := d.ApplyAction(ctx, batch(d, l, "late", 10))
- if res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED {
- t.Fatalf("expire got %v %s", res.RejectReason, res.Message)
- }
- l2 := acquire(t, d)
- e0 := d.Snapshot().DeviceEpoch
- m.SetDisconnected(true)
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if d.Snapshot().DeviceEpoch > e0 {
- break
- }
- time.Sleep(20 * time.Millisecond)
- }
- if d.Snapshot().DeviceEpoch <= e0 {
- t.Fatal("epoch should bump on disconnect")
- }
- res = d.ApplyAction(ctx, batch(d, l2, "after-drop", 10))
- if res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED &&
- res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH &&
- res.RejectReason != hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
- t.Fatalf("reconnect must invalidate lease or refuse until baseline, got %v %s", res.RejectReason, res.Message)
- }
- }
- func TestClampVsRejectWholeBatch(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- ctx := context.Background()
- bad := &hthv1.ActionBatch{
- DeviceId: d.ID(), CommandId: "bad",
- ContinuousTargets: []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 5}, {Id: ids.DoorX, Value: 200}},
- }
- r := d.ValidateAction(ctx, bad)
- if r.Accepted {
- t.Fatal("must reject whole batch")
- }
- bad.AllowClamp = true
- r = d.ValidateAction(ctx, bad)
- if !r.Accepted || len(r.Clamps) == 0 {
- t.Fatalf("clamp %+v", r)
- }
- }
- func TestSnapshotSeqMonotonic(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- var last uint64
- for i := 0; i < 5; i++ {
- s := d.Snapshot()
- if s.SnapshotSeq < last {
- t.Fatal("seq decreased")
- }
- last = s.SnapshotSeq
- time.Sleep(40 * time.Millisecond)
- }
- if last < 2 {
- t.Fatal("expected polls to advance seq")
- }
- }
- func TestGetSnapshotIsCache(t *testing.T) {
- m := backend.NewMock(1, true)
- m.SetSlow(80 * time.Millisecond)
- d := testDev(t, m)
- start := time.Now()
- _ = d.Snapshot()
- if time.Since(start) > 40*time.Millisecond {
- t.Fatal("GetSnapshot must not wait on serial/GET_TEMP")
- }
- }
- func TestStaleSnapshotRejected(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- deadline := time.Now().Add(3 * time.Second)
- for time.Now().Before(deadline) && d.Snapshot().SnapshotSeq <= control.StaleSnapshotSlack+2 {
- time.Sleep(20 * time.Millisecond)
- }
- b := batch(d, l, "stale", 10)
- b.BasedOnSnapshotSeq = 1
- r := d.ApplyAction(context.Background(), b)
- if r.RejectReason != hthv1.RejectReason_REJECT_REASON_STALE_SNAPSHOT {
- t.Fatalf("got %v seq=%d", r.RejectReason, d.Snapshot().SnapshotSeq)
- }
- }
- func TestExpiredDeadline(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- b := batch(d, l, "dead", 10)
- b.ValidUntil = timestamppb.New(time.Now().Add(-time.Second))
- r := d.ApplyAction(context.Background(), b)
- if r.RejectReason != hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE {
- t.Fatalf("got %v", r.RejectReason)
- }
- }
- func TestInvalidTempNot255C(t *testing.T) {
- m := backend.NewMock(1, true)
- m.SetInvalidChannel(0, true)
- d := testDev(t, m)
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- s := d.Snapshot()
- for _, m := range s.Measurements {
- if m.Id == ids.TempChannel(0) && m.Quality == hthv1.DataQuality_DATA_QUALITY_INVALID {
- if m.Value == 255 {
- t.Fatal("must not report 255C")
- }
- if m.QualityReason != "DEVICE_REPORTED_INVALID" {
- t.Fatalf("reason %s", m.QualityReason)
- }
- return
- }
- }
- time.Sleep(20 * time.Millisecond)
- }
- t.Fatal("invalid temp not observed")
- }
- func TestCapabilitiesHonesty(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- c := d.Capabilities()
- if c.AckSupported || c.RpmFeedbackSupported || c.PositionFeedbackSupported {
- t.Fatal("ack/rpm/actual-position must be false")
- }
- if c.FirmwareVersionQuality != hthv1.DataQuality_DATA_QUALITY_NOT_SUPPORTED {
- t.Fatal("firmware")
- }
- if c.ReadinessProbe != "motor_status_startup_complete" {
- t.Fatal(c.ReadinessProbe)
- }
- if c.Timing == nil || c.Timing.RecommendedSamplePeriodMs < 1000 {
- t.Fatalf("recommended_sample_period_ms must be the physical scan, not 50ms poll: %+v", c.Timing)
- }
- if c.Timing.PhysicalTemperatureUpdatePeriodMs < 1000 {
- t.Fatal("physical_temperature_update_period_ms must not look like a 50ms ADC")
- }
- if c.Timing.RecommendedSnapshotSubscriptionPeriodMs == c.Timing.PhysicalTemperatureUpdatePeriodMs {
- t.Fatal("snapshot subscription period must be distinct from physical temperature scan")
- }
- _ = durationpb.New(0)
- _ = protocol.SetAll{}
- }
- func TestNilBatchDoesNotPanic(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- ctx := context.Background()
- r := d.ApplyAction(ctx, nil)
- if r == nil || r.RejectReason != hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT {
- t.Fatalf("apply nil: %+v", r)
- }
- r = d.ValidateAction(ctx, nil)
- if r == nil || r.RejectReason != hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT {
- t.Fatalf("validate nil: %+v", r)
- }
- }
- func TestRawRequestedKeepsOriginalFloat(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- b := batch(d, l, "raw40", 0)
- b.AllowClamp = true
- b.ContinuousTargets = []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 40.4}}
- r := d.ApplyAction(context.Background(), b)
- if !r.Accepted {
- t.Fatal(r.Message, r.RejectReason)
- }
- if r.Requested == nil || len(r.Requested.Actuators) != 1 || r.Requested.Actuators[0].CommandedTarget != 40.4 {
- t.Fatalf("raw requested lost: %+v", r.Requested)
- }
- if r.NormalizedRequested == nil {
- t.Fatal("missing normalized")
- }
- }
- func TestStartupRejectsDoorChange(t *testing.T) {
- m := backend.NewMock(1, false)
- d := testDevNotReady(t, m)
- l := acquire(t, d)
- var r *hthv1.ActionResult
- for i := 0; i < 30; i++ {
- r = d.ApplyAction(context.Background(), batch(d, l, fmt.Sprintf("door-startup-%d", i), 40))
- if r.RejectReason == hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
- return
- }
- if r.RejectReason != hthv1.RejectReason_REJECT_REASON_STALE_CONTROL_REVISION &&
- r.RejectReason != hthv1.RejectReason_REJECT_REASON_STALE_SNAPSHOT {
- t.Fatalf("got %v %s", r.RejectReason, r.Message)
- }
- time.Sleep(5 * time.Millisecond)
- }
- t.Fatalf("got %v %s", r.RejectReason, r.Message)
- }
- func testDevNotReady(t *testing.T, mock *backend.Mock) *device.Device {
- t.Helper()
- p, err := profile.Load(testutil.ProfilePath(t))
- if err != nil {
- t.Fatal(err)
- }
- fan, ptc, door := 10, 0, 0
- dir := t.TempDir()
- cfg := &config.Config{
- APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
- Profile: testutil.ProfilePath(t),
- RuntimeRoot: dir,
- Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
- Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
- Watchdog: config.Watchdog{HeartbeatPeriodMS: 60},
- Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
- Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
- RingBufferSize: 32, SubscriberBufferSize: 64, CommandCacheSize: 16,
- AllowUnboundActions: true,
- Mock: config.Mock{Seed: 1, StartupComplete: false},
- }
- if err := cfg.Validate(p); err != nil {
- t.Fatal(err)
- }
- d := device.New(device.Params{Config: cfg, Profile: p, Backend: mock, InstanceID: "test"})
- ctx, cancel := context.WithCancel(context.Background())
- t.Cleanup(func() { cancel(); d.Stop() })
- d.Start(ctx)
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if d.Snapshot() != nil {
- return d
- }
- time.Sleep(10 * time.Millisecond)
- }
- return d
- }
- func TestShortWriteBumpsEpochAndKillsLease(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- e0 := d.Snapshot().DeviceEpoch
- m.ForceShortWrite()
- res := d.ApplyAction(context.Background(), batch(d, l, "short", 70))
- if res.Confirmation != hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN {
- t.Fatalf("got %v", res.Confirmation)
- }
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if d.Snapshot().DeviceEpoch > e0 {
- break
- }
- time.Sleep(10 * time.Millisecond)
- }
- if d.Snapshot().DeviceEpoch <= e0 {
- t.Fatal("epoch must bump after short write")
- }
- res = d.ApplyAction(context.Background(), batch(d, l, "after-short", 10))
- if res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED &&
- res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH &&
- res.RejectReason != hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
- t.Fatalf("old lease must die, got %v %s", res.RejectReason, res.Message)
- }
- }
- func TestAmbiguousFullWriteBumpsEpochAndKillsLease(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- e0 := d.Snapshot().DeviceEpoch
- m.ForceAmbiguousWrite()
- res := d.ApplyAction(context.Background(), batch(d, l, "ambig", 70))
- if res.Confirmation != hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN {
- t.Fatalf("got %v", res.Confirmation)
- }
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if d.Snapshot().DeviceEpoch > e0 {
- break
- }
- time.Sleep(10 * time.Millisecond)
- }
- if d.Snapshot().DeviceEpoch <= e0 {
- t.Fatal("epoch must bump after ambiguous write")
- }
- res = d.ApplyAction(context.Background(), batch(d, l, "after-ambig", 10))
- if res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED &&
- res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH &&
- res.RejectReason != hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
- t.Fatalf("old lease must die, got %v %s", res.RejectReason, res.Message)
- }
- }
- func TestCancelledQueuedApplyDoesNotWrite(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- m.SetSlow(250 * time.Millisecond)
- n0 := m.WriteCount()
- ctx1, cancel1 := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel1()
- done := make(chan *hthv1.ActionResult, 1)
- go func() { done <- d.ApplyAction(ctx1, batch(d, l, "slow", 10)) }()
- time.Sleep(40 * time.Millisecond)
- ctx2, cancel2 := context.WithTimeout(context.Background(), 20*time.Millisecond)
- defer cancel2()
- r2 := d.ApplyAction(ctx2, batch(d, l, "cancelled", 80))
- if r2.RejectReason != hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE && r2.RejectReason != hthv1.RejectReason_REJECT_REASON_QUEUE_FULL {
- t.Fatalf("expected cancel/queue, got %v %s", r2.RejectReason, r2.Message)
- }
- <-done
- for _, w := range m.Writes()[n0:] {
- if w.DoorX == 80 {
- t.Fatal("cancelled action must not be written")
- }
- }
- }
- func TestSlewRateWithFakeClock(t *testing.T) {
- m := backend.NewMock(1, true)
- p, err := profile.Load(testutil.ProfilePath(t))
- if err != nil {
- t.Fatal(err)
- }
- clk := clock.NewFake(time.Unix(1000, 0).UTC())
- fan, ptc, door := 10, 0, 0
- dir := t.TempDir()
- cfg := &config.Config{
- APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
- Profile: testutil.ProfilePath(t),
- RuntimeRoot: dir,
- Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock"},
- Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
- Watchdog: config.Watchdog{HeartbeatPeriodMS: 5000},
- Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 5000},
- Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
- RingBufferSize: 32, SubscriberBufferSize: 64, CommandCacheSize: 16,
- AllowUnboundActions: true,
- Mock: config.Mock{Seed: 1, StartupComplete: true},
- }
- if err := cfg.Validate(p); err != nil {
- t.Fatal(err)
- }
- d := device.New(device.Params{Config: cfg, Profile: p, Backend: m, Clock: clk, InstanceID: "slew"})
- ctx, cancel := context.WithCancel(context.Background())
- t.Cleanup(func() { cancel(); d.Stop() })
- d.Start(ctx)
- waitReady(t, d)
- clk.Advance(time.Second)
- l := acquire(t, d)
- first := batch(d, l, "slew1", 0)
- r := d.ApplyAction(context.Background(), first)
- if !r.Accepted {
- t.Fatal(r.Message)
- }
- clk.Advance(100 * time.Millisecond)
- second := batch(d, l, "slew2", 0)
- second.ContinuousTargets = []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 100}}
- r = d.ApplyAction(context.Background(), second)
- if r.RejectReason != hthv1.RejectReason_REJECT_REASON_SLEW_LIMITED {
- t.Fatalf("expected slew reject, got %v %s", r.RejectReason, r.Message)
- }
- second.AllowClamp = true
- second.CommandId = "slew2b"
- r = d.ApplyAction(context.Background(), second)
- if !r.Accepted {
- t.Fatal(r.Message)
- }
- }
- func TestLeaseSafeConcurrent(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- ctx := context.Background()
- var wg sync.WaitGroup
- for i := 0; i < 8; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
- l, err := d.AcquireLease(ctx, "c-"+string(rune('a'+i)), 200*time.Millisecond)
- if err != nil {
- return
- }
- _, _ = d.RenewLease(ctx, l.LeaseId, l.LeaseEpoch, 200*time.Millisecond)
- _ = d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "concurrent")
- }(i)
- }
- wg.Wait()
- }
- func TestFairScheduleRenewWhileApplyFlood(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- m.SetSlow(20 * time.Millisecond)
- ctx := context.Background()
- var wg sync.WaitGroup
- for i := 0; i < 8; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
- b := batch(d, l, "flood-"+string(rune('a'+i)), 10)
- _ = d.ApplyAction(ctx, b)
- }(i)
- }
- time.Sleep(40 * time.Millisecond)
- start := time.Now()
- _, err := d.RenewLease(ctx, l.LeaseId, l.LeaseEpoch, 400*time.Millisecond)
- if err != nil {
- t.Fatal(err)
- }
- if time.Since(start) > 400*time.Millisecond {
- t.Fatalf("renew delayed %s", time.Since(start))
- }
- wg.Wait()
- }
- func TestSlowTemperatureScanDoesNotBlockLease(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- m.SetSlowGet(400 * time.Millisecond)
- time.Sleep(80 * time.Millisecond)
- start := time.Now()
- _, err := d.RenewLease(context.Background(), l.LeaseId, l.LeaseEpoch, 400*time.Millisecond)
- if err != nil {
- t.Fatal(err)
- }
- if time.Since(start) > 150*time.Millisecond {
- t.Fatalf("lease renew blocked by temperature scan: %s", time.Since(start))
- }
- safeStart := time.Now()
- res := d.EnterSafeMode(context.Background(), l.LeaseId, l.LeaseEpoch, "during-scan")
- if time.Since(safeStart) > 150*time.Millisecond {
- t.Fatalf("EnterSafeMode blocked by scan: %s", time.Since(safeStart))
- }
- if res == nil || !res.Accepted {
- t.Fatalf("safe during scan: %+v", res)
- }
- }
- func TestReconnectDoesNotRestoreOldPTC(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- full := batch(d, l, "full-ptc", 0)
- for _, tgt := range full.ContinuousTargets {
- if len(tgt.Id) >= 4 && tgt.Id[:4] == "ptc." {
- tgt.Value = 80
- }
- }
- res := d.ApplyAction(context.Background(), full)
- if !res.Accepted {
- t.Fatal(res.Message)
- }
- e0 := d.Snapshot().DeviceEpoch
- m.ForceShortWrite()
- _ = d.ApplyAction(context.Background(), batch(d, l, "drop", 10))
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if d.Snapshot().DeviceEpoch > e0 {
- break
- }
- time.Sleep(10 * time.Millisecond)
- }
- deadline = time.Now().Add(2 * time.Second)
- var l2 *hthv1.ControlLease
- var err error
- for time.Now().Before(deadline) {
- l2, err = d.AcquireLease(context.Background(), "after-reconnect", 400*time.Millisecond)
- if err == nil && l2 != nil {
- break
- }
- time.Sleep(20 * time.Millisecond)
- }
- if l2 == nil {
- t.Fatal("could not acquire lease after reconnect", err)
- }
- waitReady(t, d)
- partial := &hthv1.ActionBatch{
- DeviceId: d.ID(), CommandId: "partial-fan-only", LeaseId: l2.LeaseId, LeaseEpoch: l2.LeaseEpoch,
- BasedOnSnapshotSeq: d.Snapshot().SnapshotSeq, ExpectedControlRevision: d.Snapshot().ControlRevision,
- ValidUntil: timestamppb.New(time.Now().Add(20 * time.Second)), ClientId: "test",
- ContinuousTargets: []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 30}},
- }
- pr := d.ApplyAction(context.Background(), partial)
- if pr.RejectReason == hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
- t.Log("partial rejected until baseline, as required")
- }
- last := m.LastSetAll()
- if last.PTC[0] == 80 {
- t.Fatal("old PTC value must not be restored after epoch change")
- }
- }
- func TestFiveSecondScanLeaseAndSafe(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- m.SetSlowGet(5 * time.Second)
- time.Sleep(120 * time.Millisecond)
- start := time.Now()
- if _, err := d.RenewLease(context.Background(), l.LeaseId, l.LeaseEpoch, 400*time.Millisecond); err != nil {
- t.Fatal(err)
- }
- if time.Since(start) > 200*time.Millisecond {
- t.Fatalf("lease renew blocked by 5s scan: %s", time.Since(start))
- }
- safeStart := time.Now()
- res := d.EnterSafeMode(context.Background(), l.LeaseId, l.LeaseEpoch, "during-5s-scan")
- if time.Since(safeStart) > 200*time.Millisecond {
- t.Fatalf("EnterSafeMode blocked by 5s scan: %s", time.Since(safeStart))
- }
- if res == nil || !res.Accepted {
- t.Fatalf("safe during 5s scan: %+v", res)
- }
- if !strings.Contains(res.Message, "queued") && !strings.Contains(res.Message, "dispatched") && !strings.Contains(res.Message, "control-plane") {
- t.Logf("safe message: %s", res.Message)
- }
- }
- func TestQueuedSafeLatchesAfterSlowGetTemp(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- l := acquire(t, d)
- m.SetSlowGet(5 * time.Second)
- time.Sleep(80 * time.Millisecond)
- res := d.EnterSafeMode(context.Background(), l.LeaseId, l.LeaseEpoch, "during-5s-scan")
- if res == nil || !res.Accepted {
- t.Fatalf("enter safe: %+v", res)
- }
- deadline := time.Now().Add(12 * time.Second)
- for time.Now().Before(deadline) {
- if d.Snapshot().GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
- return
- }
- time.Sleep(20 * time.Millisecond)
- }
- t.Fatalf("SAFE never latched after queued behind 5s GET_TEMP: %v", d.Snapshot().GetSafetyControlMode())
- }
|