| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351 |
- package device_test
- import (
- "context"
- "testing"
- "time"
- "google.golang.org/protobuf/types/known/timestamppb"
- "hth/internal/backend"
- "hth/internal/config"
- "hth/internal/device"
- hthv1 "hth/internal/gen/hth/api/v1"
- "hth/internal/ids"
- "hth/internal/profile"
- "hth/internal/testutil"
- )
- func TestStartupSuppressesGetTemperature(t *testing.T) {
- m := backend.NewMock(1, false)
- m.StartupDelay = 11 * time.Second
- d := testDevNoWait(t, m)
- deadline := time.Now().Add(10 * time.Second)
- for time.Now().Before(deadline) {
- if m.TempGetCount() != 0 {
- t.Fatalf("GET_TEMPERATURE sent during startup: %d", m.TempGetCount())
- }
- if m.MotorGetCount() == 0 {
- time.Sleep(20 * time.Millisecond)
- continue
- }
- time.Sleep(50 * time.Millisecond)
- }
- if m.TempGetCount() != 0 {
- t.Fatalf("GET_TEMPERATURE during first 10s startup: %d", m.TempGetCount())
- }
- if m.MotorGetCount() == 0 {
- t.Fatal("expected MOTOR_STATUS polling during startup")
- }
- if d.Snapshot().GetDeviceEpoch() != 1 {
- t.Fatalf("epoch changed during delayed startup: %d", d.Snapshot().GetDeviceEpoch())
- }
- waitReady(t, d)
- deadline = time.Now().Add(3 * time.Second)
- for time.Now().Before(deadline) {
- if m.TempGetCount() > 0 {
- return
- }
- time.Sleep(20 * time.Millisecond)
- }
- t.Fatal("expected GET_TEMPERATURE after startup_complete")
- }
- func testDevNoWait(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: 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)
- return d
- }
- func TestSafeModeRejectsOrdinaryApplyUntilResume(t *testing.T) {
- d := testDev(t, backend.NewMock(1, true))
- l := acquire(t, d)
- ctx := context.Background()
- res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
- if !res.Accepted {
- t.Fatalf("enter safe: %+v", res)
- }
- if res.GetDispatched() != nil && res.GetDispatchState() == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_DISPATCHED {
- t.Fatal("EnterSafeMode must not claim DISPATCHED before the write completes")
- }
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if d.Snapshot().GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
- break
- }
- time.Sleep(10 * time.Millisecond)
- }
- l2, err := d.AcquireLease(ctx, "after-safe", 400*time.Millisecond)
- if err != nil {
- t.Fatal(err)
- }
- batch := &hthv1.ActionBatch{
- DeviceId: "prod2u-0", CommandId: "after-safe-apply",
- LeaseId: l2.LeaseId, LeaseEpoch: l2.LeaseEpoch,
- ValidUntil: timestamppb.New(time.Now().Add(time.Second)),
- ContinuousTargets: []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 20}},
- }
- out := d.ApplyAction(ctx, batch)
- if out.Accepted || out.RejectReason != hthv1.RejectReason_REJECT_REASON_SAFE_MODE_ACTIVE {
- t.Fatalf("ordinary apply must be rejected in SAFE: %+v", out)
- }
- }
- func TestSlewFloorNeverExceedsRateTimesElapsed(t *testing.T) {
- // Delegated to safety package property test; keep a host-level smoke here.
- d := testDev(t, backend.NewMock(1, true))
- if d.Capabilities().GetTiming() == nil || d.Capabilities().GetTiming().GetRecommendedRpcDeadlineMs() < 3000 {
- t.Fatalf("timing capabilities missing: %+v", d.Capabilities().GetTiming())
- }
- if d.Capabilities().GetDeviceFaultQuerySupported() {
- t.Fatal("must not claim device native fault query")
- }
- }
- func TestResumeFromSafeStateMachine(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- ctx := context.Background()
- l := acquire(t, d)
- res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
- if !res.Accepted {
- t.Fatalf("enter safe: %+v", res)
- }
- if res.GetDispatchState() == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_DISPATCHED && res.GetDispatched() != nil {
- t.Fatal("EnterSafeMode must not report DISPATCHED before the serial write finishes")
- }
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if d.Snapshot().GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
- break
- }
- time.Sleep(10 * time.Millisecond)
- }
- if d.Snapshot().GetSafetyControlMode() != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
- t.Fatal("expected latched SAFE after complete safe write")
- }
- l2, err := d.AcquireLease(ctx, "resume-holder", 800*time.Millisecond)
- if err != nil {
- t.Fatal(err)
- }
- denied := d.ApplyAction(ctx, batch(d, l2, "still-safe", 0))
- if denied.RejectReason != hthv1.RejectReason_REJECT_REASON_SAFE_MODE_ACTIVE {
- t.Fatalf("ordinary apply after new lease must stay SAFE: %+v", denied)
- }
- time.Sleep(150 * time.Millisecond)
- out := d.ResumeFromSafe(ctx, l2.LeaseId, l2.LeaseEpoch, batch(d, l2, "resume-full", 0))
- if !out.Accepted && out.RejectReason != 0 {
- t.Fatalf("resume: %+v", out)
- }
- deadline = time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if d.Snapshot().GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL {
- return
- }
- time.Sleep(10 * time.Millisecond)
- }
- t.Fatalf("expected NORMAL after resume, got %v", d.Snapshot().GetSafetyControlMode())
- }
- func TestHangGetInterruptedByCloseBumpsEpoch(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- epoch0 := d.Snapshot().GetDeviceEpoch()
- d.TestingSetMaxSerialTxn(300 * time.Millisecond)
- m.SetHangGetOnce()
- deadline := time.Now().Add(4 * time.Second)
- for time.Now().Before(deadline) {
- if d.Snapshot().GetDeviceEpoch() > epoch0 {
- snap := d.Snapshot()
- if snap == nil {
- t.Fatal("actor stopped responding after hang interrupt")
- }
- return
- }
- _ = d.Snapshot()
- time.Sleep(20 * time.Millisecond)
- }
- t.Fatalf("expected epoch bump after hung GET; epoch=%d busy=%s", d.Snapshot().GetDeviceEpoch(), d.SerialBusy())
- }
- func TestShutdownSafeGoesThroughWorker(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, "pre-stop", 40))
- if !res.Accepted {
- t.Fatalf("apply: %+v", res)
- }
- d.Stop()
- sr := d.TestingShutdownSafeResult()
- if sr == nil {
- t.Fatal("expected shutdown safe result")
- }
- writes := m.Writes()
- if len(writes) == 0 {
- t.Fatal("expected at least the shutdown SET_ALL")
- }
- last := writes[len(writes)-1]
- if last.Fan[0] != 10 || last.PTC[0] != 0 || last.DoorX != 0 || last.DoorY != 0 || last.DoorZ != 0 {
- t.Fatalf("last frame must be safe baseline, got %+v", last)
- }
- }
- func TestStartupRestartsSuppressTemperature(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDev(t, m)
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) && m.TempGetCount() == 0 {
- time.Sleep(20 * time.Millisecond)
- }
- if m.TempGetCount() == 0 {
- t.Fatal("expected temperature after first startup")
- }
- m.SetStartupComplete(false)
- m.StartupDelay = 3 * time.Second
- m.SetDisconnected(true)
- time.Sleep(200 * time.Millisecond)
- afterDrop := m.TempGetCount()
- m.SetDisconnected(false)
- hold := time.Now().Add(2 * time.Second)
- for time.Now().Before(hold) {
- if m.TempGetCount() > afterDrop+1 {
- t.Fatalf("GET_TEMPERATURE during re-startup: before=%d now=%d", afterDrop, m.TempGetCount())
- }
- time.Sleep(40 * time.Millisecond)
- }
- _ = d
- }
- func testDevLongTTL(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: 20000},
- 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 waitSlowGetInflight(t *testing.T, d *device.Device, m *backend.Mock) {
- t.Helper()
- deadline := time.Now().Add(3 * time.Second)
- for time.Now().Before(deadline) {
- if m.TempGetCount() >= 1 && d.SerialBusy() > 80*time.Millisecond {
- return
- }
- time.Sleep(10 * time.Millisecond)
- }
- t.Fatalf("GET_TEMPERATURE never went inflight: gets=%d busy=%s", m.TempGetCount(), d.SerialBusy())
- }
- func TestOldDeadlineRejectedDuringFiveSecondScan(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevLongTTL(t, m)
- ctx := context.Background()
- l, err := d.AcquireLease(ctx, "deadline-old", 15*time.Second)
- if err != nil {
- t.Fatal(err)
- }
- m.SetSlowGet(5 * time.Second)
- waitSlowGetInflight(t, d, m)
- epoch0 := d.Snapshot().GetDeviceEpoch()
- b := batch(d, l, "too-short-ttl", 0)
- b.ValidUntil = timestamppb.New(time.Now().Add(2 * time.Second))
- start := time.Now()
- out := d.ApplyAction(ctx, b)
- if time.Since(start) > 300*time.Millisecond {
- t.Fatalf("2s deadline must be rejected before waiting out the 5s scan: %s", time.Since(start))
- }
- if out.Accepted || out.RejectReason != hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE {
- t.Fatalf("expected EXPIRED_DEADLINE for 2s TTL during 5s GET: %+v", out)
- }
- if d.Snapshot().GetDeviceEpoch() != epoch0 {
- t.Fatalf("rejecting unmeetable deadline must not bump epoch: %d -> %d", epoch0, d.Snapshot().GetDeviceEpoch())
- }
- }
- func TestRecommendedDeadlineSucceedsDuringFiveSecondScan(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevLongTTL(t, m)
- ctx := context.Background()
- l, err := d.AcquireLease(ctx, "deadline-rec", 18*time.Second)
- if err != nil {
- t.Fatal(err)
- }
- timing := d.Capabilities().GetTiming()
- if timing == nil || timing.GetRecommendedActionTtlMs() < 7000 {
- t.Fatalf("recommended TTL too small: %+v", timing)
- }
- m.SetSlowGet(5 * time.Second)
- waitSlowGetInflight(t, d, m)
- b := batch(d, l, "recommended-ttl", 0)
- b.ValidUntil = timestamppb.New(time.Now().Add(time.Duration(timing.GetRecommendedActionTtlMs()) * time.Millisecond))
- start := time.Now()
- out := d.ApplyAction(ctx, b)
- elapsed := time.Since(start)
- if !out.Accepted {
- t.Fatalf("recommended TTL must dispatch after the 5s scan: %+v after %s", out, elapsed)
- }
- if elapsed < 4*time.Second {
- t.Fatalf("expected to wait for in-flight GET_TEMPERATURE, finished in %s", elapsed)
- }
- if elapsed > 12*time.Second {
- t.Fatalf("control dispatch after 5s scan took too long: %s", elapsed)
- }
- }
|