| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395 |
- //go:build linux
- package tests
- import (
- "context"
- "os"
- "path/filepath"
- "testing"
- "time"
- "google.golang.org/protobuf/types/known/durationpb"
- "google.golang.org/protobuf/types/known/timestamppb"
- "hth/internal/app"
- "hth/internal/devsim"
- hthv1 "hth/internal/gen/hth/api/v1"
- "hth/internal/grpcserver"
- "hth/internal/ids"
- "hth/internal/protocol"
- "hth/internal/serialtransport"
- )
- func startSerialAppR4(t *testing.T, sim *devsim.Sim, getTempMS int) (obs, ctl string, a *app.App) {
- t.Helper()
- serialtransport.SetTestWriteCap(0)
- serialtransport.SetTestForceWriteError(false)
- dir := t.TempDir()
- obs = filepath.Join(dir, "observe", "o.sock")
- ctl = filepath.Join(dir, "control", "c.sock")
- prof := shortScanProfile(t, 80)
- yaml := `
- api_version: hth.api.v1
- device_id: prod2u-0
- backend: serial
- profile: ` + prof + `
- runtime_root: ` + dir + `
- serial:
- path: ` + sim.Name + `
- get_temp_timeout_ms: ` + itoa(getTempMS) + `
- get_motor_timeout_ms: 4000
- probe_timeout_ms: 4000
- sockets:
- observe: ` + obs + `
- control: ` + ctl + `
- observe_perm: "0660"
- control_perm: "0660"
- poll:
- temperature_ms: 80
- motor_status_ms: 60000
- watchdog:
- heartbeat_period_ms: 8000
- lease:
- min_ttl_ms: 50
- max_ttl_ms: 30000
- safety:
- fan: 10
- ptc: 0
- door_close_percent: 0
- ring_buffer_size: 64
- subscriber_buffer_size: 4
- grpc:
- reflection: false
- allow_unbound_actions: true
- `
- cfgPath := filepath.Join(dir, "hthd.yaml")
- if err := os.WriteFile(cfgPath, []byte(yaml), 0o644); err != nil {
- t.Fatal(err)
- }
- var err error
- a, err = app.New(cfgPath, "serial", nil)
- if err != nil {
- t.Fatal(err)
- }
- ctx, cancel := context.WithCancel(context.Background())
- errCh := make(chan error, 1)
- go func() { errCh <- a.Run(ctx) }()
- t.Cleanup(func() {
- serialtransport.SetTestWriteCap(0)
- serialtransport.SetTestForceWriteError(false)
- cancel()
- a.Stop()
- <-errCh
- })
- waitUnix(t, obs, 4*time.Second)
- waitUnix(t, ctl, 4*time.Second)
- return obs, ctl, a
- }
- func itoa(n int) string {
- if n == 0 {
- return "0"
- }
- var b [16]byte
- i := len(b)
- for n > 0 {
- i--
- b[i] = byte('0' + n%10)
- n /= 10
- }
- return string(b[i:])
- }
- func r4Batch(lease *hthv1.LeaseResponse, snap *hthv1.Snapshot, cmd string, door float64) *hthv1.ActionBatch {
- return &hthv1.ActionBatch{
- DeviceId: "prod2u-0", CommandId: cmd, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
- BasedOnSnapshotSeq: snap.SnapshotSeq, ExpectedControlRevision: snap.ControlRevision,
- ValidUntil: timestamppb.New(time.Now().Add(8 * time.Second)),
- ContinuousTargets: []*hthv1.ContinuousTarget{
- {Id: ids.Fan1, Value: 10}, {Id: ids.Fan2, Value: 10}, {Id: ids.Fan3, Value: 10}, {Id: ids.Fan4, Value: 10},
- {Id: ids.PTC1, Value: 0}, {Id: ids.PTC2, Value: 0}, {Id: ids.PTC3, Value: 0}, {Id: ids.PTC4, Value: 0},
- {Id: ids.DoorX, Value: door}, {Id: ids.DoorY, Value: door}, {Id: ids.DoorZ, Value: door},
- },
- }
- }
- func TestPTYLatestWinsDuringDelayedGET(t *testing.T) {
- sim, err := devsim.Start(devsim.Options{StartupDone: true})
- if err != nil {
- t.Fatal(err)
- }
- defer sim.Close()
- obs, ctl, _ := startSerialAppR4(t, sim, 800)
- waitUntilReady(t, obs, 20*time.Second)
- waitSlewBudget()
- sim.SetOptions(devsim.Options{StartupDone: true, Delay: 400 * time.Millisecond})
- oc, err := grpcserver.DialUnix(obs, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer oc.Close()
- cc, err := grpcserver.DialUnix(ctl, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer cc.Close()
- obsCli := hthv1.NewObserveServiceClient(oc)
- ctrl := hthv1.NewControlServiceClient(cc)
- ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
- defer cancel()
- lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
- DeviceId: "prod2u-0", Holder: "pty-lw", Ttl: durationpb.New(8 * time.Second),
- })
- if err != nil {
- t.Fatal(err)
- }
- time.Sleep(60 * time.Millisecond)
- snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
- if err != nil {
- t.Fatal(err)
- }
- oldCh := make(chan *hthv1.ActionResult, 1)
- newCh := make(chan *hthv1.ActionResult, 1)
- go func() {
- r, _ := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: r4Batch(lease, snap.Snapshot, "old-door", 30)})
- oldCh <- r
- }()
- time.Sleep(20 * time.Millisecond)
- go func() {
- r, _ := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: r4Batch(lease, snap.Snapshot, "new-door", 70)})
- newCh <- r
- }()
- oldRes := <-oldCh
- newRes := <-newCh
- if oldRes != nil && oldRes.DispatchState != hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED &&
- oldRes.RejectReason != hthv1.RejectReason_REJECT_REASON_SUPERSEDED &&
- oldRes.Accepted {
- // If GET was not inflight the old apply may have written. Latest-wins only applies to not-started writes.
- t.Logf("old apply completed without supersede (GET may not have been inflight): %+v", oldRes)
- }
- if newRes == nil || newRes.Confirmation == hthv1.ConfirmationStatus_CONFIRMATION_STATUS_CONFIRMED {
- t.Fatalf("new apply: %+v", newRes)
- }
- deadline := time.Now().Add(3 * time.Second)
- saw70 := false
- saw30After70 := false
- for time.Now().Before(deadline) {
- sets := sim.SetAlls()
- seen70 := false
- for _, s := range sets {
- if s.DoorX == 70 {
- seen70 = true
- saw70 = true
- }
- if seen70 && s.DoorX == 30 {
- saw30After70 = true
- }
- }
- if saw70 {
- break
- }
- time.Sleep(30 * time.Millisecond)
- }
- if saw30After70 {
- t.Fatal("superseded door=30 was written after latest door=70")
- }
- if !saw70 && newRes != nil && newRes.Accepted {
- t.Fatal("latest door=70 was not written")
- }
- }
- func TestPTYShutdownDoesNotWritePendingApply(t *testing.T) {
- sim, err := devsim.Start(devsim.Options{StartupDone: true})
- if err != nil {
- t.Fatal(err)
- }
- defer sim.Close()
- obs, ctl, a := startSerialAppR4(t, sim, 900)
- waitUntilReady(t, obs, 20*time.Second)
- waitSlewBudget()
- oc, err := grpcserver.DialUnix(obs, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer oc.Close()
- cc, err := grpcserver.DialUnix(ctl, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer cc.Close()
- obsCli := hthv1.NewObserveServiceClient(oc)
- ctrl := hthv1.NewControlServiceClient(cc)
- ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
- defer cancel()
- // Delay GET replies before taking a lease. After lease, control-window
- // suppresses GET_TEMP, so the in-flight GET must already be sleeping.
- sim.SetOptions(devsim.Options{StartupDone: true, Delay: 1500 * time.Millisecond})
- gets := sim.CountType(protocol.TypeGetTemperature)
- waitGET := time.Now().Add(2 * time.Second)
- for time.Now().Before(waitGET) && sim.CountType(protocol.TypeGetTemperature) <= gets {
- time.Sleep(5 * time.Millisecond)
- }
- if sim.CountType(protocol.TypeGetTemperature) <= gets {
- t.Fatal("GET_TEMPERATURE never started; cannot prove pending-apply shutdown")
- }
- lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
- DeviceId: "prod2u-0", Holder: "pty-sd", Ttl: durationpb.New(8 * time.Second),
- })
- if err != nil {
- t.Fatal(err)
- }
- snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
- if err != nil {
- t.Fatal(err)
- }
- done := make(chan *hthv1.ActionResult, 1)
- go func() {
- r, _ := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: r4Batch(lease, snap.Snapshot, "pending-sd", 40)})
- done <- r
- }()
- time.Sleep(30 * time.Millisecond)
- n0 := sim.FrameCountSETALL()
- a.Stop()
- select {
- case <-done:
- case <-time.After(4 * time.Second):
- }
- for _, s := range sim.SetAlls() {
- _ = n0
- if s.DoorX == 40 && s.DoorY == 40 && s.DoorZ == 40 {
- t.Fatal("pending apply was written on PTY after Stop")
- }
- }
- }
- func TestPTYSafeReconnectStaysSafe(t *testing.T) {
- sim, err := devsim.Start(devsim.Options{StartupDone: true})
- if err != nil {
- t.Fatal(err)
- }
- defer sim.Close()
- obs, ctl, _ := startSerialAppR4(t, sim, 400)
- waitUntilReady(t, obs, 20*time.Second)
- waitSlewBudget()
- oc, err := grpcserver.DialUnix(obs, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer oc.Close()
- cc, err := grpcserver.DialUnix(ctl, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer cc.Close()
- obsCli := hthv1.NewObserveServiceClient(oc)
- ctrl := hthv1.NewControlServiceClient(cc)
- ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
- defer cancel()
- lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
- DeviceId: "prod2u-0", Holder: "pty-safe", Ttl: durationpb.New(8 * time.Second),
- })
- if err != nil {
- t.Fatal(err)
- }
- if _, err := ctrl.EnterSafeMode(ctx, &hthv1.EnterSafeModeRequest{
- DeviceId: "prod2u-0", LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Reason: "pty",
- }); err != nil {
- t.Fatal(err)
- }
- deadline := time.Now().Add(3 * time.Second)
- for time.Now().Before(deadline) {
- s, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
- if err == nil && s.Snapshot.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
- break
- }
- time.Sleep(20 * time.Millisecond)
- }
- e0 := waitEpoch(t, obs, 1)
- pg0 := uint64(0)
- if s, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"}); err == nil {
- pg0 = s.Snapshot.GetPortGeneration()
- }
- sim.Disconnect()
- serialtransport.SetTestForceWriteError(true)
- _ = waitEpoch(t, obs, e0+1)
- serialtransport.SetTestForceWriteError(false)
- deadline = time.Now().Add(6 * time.Second)
- for time.Now().Before(deadline) {
- s, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
- if err != nil || s.Snapshot == nil {
- time.Sleep(30 * time.Millisecond)
- continue
- }
- if s.Snapshot.GetPortGeneration() < pg0 {
- t.Fatal("port generation went backwards")
- }
- mode := s.Snapshot.GetSafetyControlMode()
- if mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL && s.Snapshot.GetDeviceEpoch() > e0 {
- t.Fatal("SAFE latch cleared by reconnect")
- }
- if mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE ||
- mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING {
- if s.Snapshot.GetDeviceEpoch() > e0 {
- return
- }
- }
- time.Sleep(30 * time.Millisecond)
- }
- t.Fatalf("want SAFE after PTY reconnect, last mode unknown")
- }
- func TestPTYHeartbeatFailureDoesNotRewriteDoors(t *testing.T) {
- sim, err := devsim.Start(devsim.Options{StartupDone: true})
- if err != nil {
- t.Fatal(err)
- }
- defer sim.Close()
- obs, ctl, _ := startSerialAppR4(t, sim, 400)
- waitUntilReady(t, obs, 20*time.Second)
- waitSlewBudget()
- oc, err := grpcserver.DialUnix(obs, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer oc.Close()
- cc, err := grpcserver.DialUnix(ctl, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer cc.Close()
- obsCli := hthv1.NewObserveServiceClient(oc)
- ctrl := hthv1.NewControlServiceClient(cc)
- ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
- defer cancel()
- lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
- DeviceId: "prod2u-0", Holder: "pty-hb", Ttl: durationpb.New(8 * time.Second),
- })
- if err != nil {
- t.Fatal(err)
- }
- snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
- if err != nil {
- t.Fatal(err)
- }
- res, err := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: r4Batch(lease, snap.Snapshot, "doors55", 55)})
- if err != nil || !res.Accepted {
- t.Fatalf("apply: %v %+v", err, res)
- }
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- for _, s := range sim.SetAlls() {
- if s.DoorX == 55 {
- serialtransport.SetTestWriteCap(1)
- time.Sleep(200 * time.Millisecond)
- for _, w := range sim.SetAlls() {
- if w.DoorX == 0 && w.DoorY == 0 && w.DoorZ == 0 && w.Fan[0] != 10 {
- t.Fatalf("failed heartbeat rewrote doors to %+v", w)
- }
- }
- return
- }
- }
- time.Sleep(20 * time.Millisecond)
- }
- t.Fatal("door 55 never written before heartbeat-failure probe")
- }
|