device_test.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. package device_test
  2. import (
  3. "context"
  4. "strings"
  5. "sync"
  6. "testing"
  7. "time"
  8. "google.golang.org/protobuf/types/known/durationpb"
  9. "google.golang.org/protobuf/types/known/timestamppb"
  10. "hth/internal/backend"
  11. "hth/internal/clock"
  12. "hth/internal/config"
  13. "hth/internal/control"
  14. "hth/internal/device"
  15. hthv1 "hth/internal/gen/hth/api/v1"
  16. "hth/internal/ids"
  17. "hth/internal/profile"
  18. "hth/internal/protocol"
  19. "hth/internal/testutil"
  20. )
  21. func testDev(t *testing.T, mock *backend.Mock) *device.Device {
  22. t.Helper()
  23. p, err := profile.Load(testutil.ProfilePath(t))
  24. if err != nil {
  25. t.Fatal(err)
  26. }
  27. fan, ptc, door := 10, 0, 0
  28. dir := t.TempDir()
  29. cfg := &config.Config{
  30. APIVersion: "hth.api.v1",
  31. DeviceID: "prod2u-0",
  32. Backend: config.BackendMock,
  33. Profile: testutil.ProfilePath(t),
  34. RuntimeRoot: dir,
  35. Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
  36. Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
  37. Watchdog: config.Watchdog{HeartbeatPeriodMS: 5000},
  38. Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
  39. Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
  40. RingBufferSize: 32,
  41. SubscriberBufferSize: 2,
  42. CommandCacheSize: 16,
  43. AllowUnboundActions: true,
  44. Mock: config.Mock{Seed: 1, StartupComplete: true},
  45. }
  46. if err := cfg.Validate(p); err != nil {
  47. t.Fatal(err)
  48. }
  49. d := device.New(device.Params{Config: cfg, Profile: p, Backend: mock, InstanceID: "test"})
  50. ctx, cancel := context.WithCancel(context.Background())
  51. t.Cleanup(func() { cancel(); d.Stop() })
  52. d.Start(ctx)
  53. waitReady(t, d)
  54. return d
  55. }
  56. func waitReady(t *testing.T, d *device.Device) {
  57. t.Helper()
  58. deadline := time.Now().Add(3 * time.Second)
  59. for time.Now().Before(deadline) {
  60. s := d.Snapshot()
  61. if s != nil && (s.Lifecycle == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY ||
  62. s.Lifecycle == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_DEGRADED) {
  63. // Allow slew budget from the epoch Safe Baseline (100%/s) before tests dispatch.
  64. time.Sleep(time.Second)
  65. return
  66. }
  67. time.Sleep(10 * time.Millisecond)
  68. }
  69. s := d.Snapshot()
  70. t.Fatalf("not ready: %+v", s.GetLifecycle())
  71. }
  72. func acquire(t *testing.T, d *device.Device) *hthv1.ControlLease {
  73. t.Helper()
  74. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  75. defer cancel()
  76. l, err := d.AcquireLease(ctx, "tester", 400*time.Millisecond)
  77. if err != nil {
  78. t.Fatal(err)
  79. }
  80. return l
  81. }
  82. func batch(d *device.Device, l *hthv1.ControlLease, id string, doors uint8) *hthv1.ActionBatch {
  83. s := d.Snapshot()
  84. return &hthv1.ActionBatch{
  85. DeviceId: d.ID(), CommandId: id, LeaseId: l.LeaseId, LeaseEpoch: l.LeaseEpoch,
  86. BasedOnSnapshotSeq: s.SnapshotSeq, ExpectedControlRevision: s.ControlRevision,
  87. ValidUntil: timestamppb.New(time.Now().Add(2 * time.Second)),
  88. ClientId: "test",
  89. ContinuousTargets: []*hthv1.ContinuousTarget{
  90. {Id: ids.Fan1, Value: 20}, {Id: ids.Fan2, Value: 20}, {Id: ids.Fan3, Value: 20}, {Id: ids.Fan4, Value: 20},
  91. {Id: ids.PTC1, Value: 0}, {Id: ids.PTC2, Value: 0}, {Id: ids.PTC3, Value: 0}, {Id: ids.PTC4, Value: 0},
  92. {Id: ids.DoorX, Value: float64(doors)}, {Id: ids.DoorY, Value: float64(doors)}, {Id: ids.DoorZ, Value: float64(doors)},
  93. },
  94. }
  95. }
  96. func TestNoConfirmedOnSetAll(t *testing.T) {
  97. m := backend.NewMock(1, true)
  98. d := testDev(t, m)
  99. l := acquire(t, d)
  100. ctx := context.Background()
  101. res := d.ApplyAction(ctx, batch(d, l, "c1", 50))
  102. if !res.Accepted {
  103. t.Fatal(res.Message, res.RejectReason)
  104. }
  105. if res.Confirmation == hthv1.ConfirmationStatus_CONFIRMATION_STATUS_CONFIRMED {
  106. t.Fatal("SET_ALL must never be CONFIRMED")
  107. }
  108. if res.Confirmation != hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED {
  109. t.Fatalf("got %v", res.Confirmation)
  110. }
  111. }
  112. func TestCommandIDCacheNoSecondWrite(t *testing.T) {
  113. m := backend.NewMock(1, true)
  114. d := testDev(t, m)
  115. l := acquire(t, d)
  116. ctx := context.Background()
  117. b := batch(d, l, "same", 40)
  118. n0 := m.WriteCount()
  119. r1 := d.ApplyAction(ctx, b)
  120. r2 := d.ApplyAction(ctx, b)
  121. if !r2.ReplayedFromCache {
  122. t.Fatal("expected cache replay")
  123. }
  124. if m.WriteCount()-n0 != 1 {
  125. t.Fatalf("writes %d", m.WriteCount()-n0)
  126. }
  127. if r1.Confirmation != r2.Confirmation {
  128. t.Fatal("replay result mismatch")
  129. }
  130. }
  131. func TestCommandIDConflict(t *testing.T) {
  132. m := backend.NewMock(1, true)
  133. d := testDev(t, m)
  134. l := acquire(t, d)
  135. ctx := context.Background()
  136. b := batch(d, l, "cid", 10)
  137. d.ApplyAction(ctx, b)
  138. b2 := batch(d, l, "cid", 20)
  139. r := d.ApplyAction(ctx, b2)
  140. if r.RejectReason != hthv1.RejectReason_REJECT_REASON_IDEMPOTENCY_CONFLICT {
  141. t.Fatalf("got %v %s", r.RejectReason, r.Message)
  142. }
  143. }
  144. func TestHeartbeatKeepsDoorPercents(t *testing.T) {
  145. m := backend.NewMock(1, true)
  146. p, err := profile.Load(testutil.ProfilePath(t))
  147. if err != nil {
  148. t.Fatal(err)
  149. }
  150. fan, ptc, door := 10, 0, 0
  151. dir := t.TempDir()
  152. cfg := &config.Config{
  153. APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
  154. Profile: testutil.ProfilePath(t), RuntimeRoot: dir,
  155. Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
  156. Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
  157. Watchdog: config.Watchdog{HeartbeatPeriodMS: 80},
  158. Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
  159. Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
  160. RingBufferSize: 32, SubscriberBufferSize: 2, CommandCacheSize: 16,
  161. AllowUnboundActions: true,
  162. Mock: config.Mock{Seed: 1, StartupComplete: true},
  163. }
  164. if err := cfg.Validate(p); err != nil {
  165. t.Fatal(err)
  166. }
  167. d := device.New(device.Params{Config: cfg, Profile: p, Backend: m, InstanceID: "hb"})
  168. ctx, cancel := context.WithCancel(context.Background())
  169. t.Cleanup(func() { cancel(); d.Stop() })
  170. d.Start(ctx)
  171. waitReady(t, d)
  172. l := acquire(t, d)
  173. res := d.ApplyAction(context.Background(), batch(d, l, "doors50", 50))
  174. if !res.Accepted {
  175. t.Fatal(res)
  176. }
  177. time.Sleep(200 * time.Millisecond)
  178. writes := m.Writes()
  179. seen := false
  180. for _, w := range writes {
  181. if w.DoorX == 50 && w.DoorY == 50 && w.DoorZ == 50 {
  182. seen = true
  183. continue
  184. }
  185. if seen && (w.DoorX != 50 || w.DoorY != 50 || w.DoorZ != 50) {
  186. t.Fatalf("heartbeat rewrote doors to %+v", w)
  187. }
  188. }
  189. if !seen {
  190. t.Fatalf("never dispatched doors=50, writes=%d", len(writes))
  191. }
  192. }
  193. func TestNoAutoRetryUnknownDoorDispatch(t *testing.T) {
  194. m := backend.NewMock(1, true)
  195. d := testDev(t, m)
  196. l := acquire(t, d)
  197. m.ForceShortWrite()
  198. ctx := context.Background()
  199. res := d.ApplyAction(ctx, batch(d, l, "unk", 70))
  200. if res.Confirmation != hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN {
  201. t.Fatalf("got %v", res.Confirmation)
  202. }
  203. time.Sleep(150 * time.Millisecond)
  204. for _, w := range m.Writes() {
  205. if w.DoorX == 70 || w.DoorY == 70 || w.DoorZ == 70 {
  206. t.Fatal("must not auto-retry unknown door percent change")
  207. }
  208. }
  209. }
  210. func TestLeaseExpireAndReconnectInvalidate(t *testing.T) {
  211. m := backend.NewMock(1, true)
  212. d := testDev(t, m)
  213. l := acquire(t, d)
  214. time.Sleep(600 * time.Millisecond)
  215. ctx := context.Background()
  216. res := d.ApplyAction(ctx, batch(d, l, "late", 10))
  217. if res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED {
  218. t.Fatalf("expire got %v %s", res.RejectReason, res.Message)
  219. }
  220. l2 := acquire(t, d)
  221. e0 := d.Snapshot().DeviceEpoch
  222. m.SetDisconnected(true)
  223. deadline := time.Now().Add(2 * time.Second)
  224. for time.Now().Before(deadline) {
  225. if d.Snapshot().DeviceEpoch > e0 {
  226. break
  227. }
  228. time.Sleep(20 * time.Millisecond)
  229. }
  230. if d.Snapshot().DeviceEpoch <= e0 {
  231. t.Fatal("epoch should bump on disconnect")
  232. }
  233. res = d.ApplyAction(ctx, batch(d, l2, "after-drop", 10))
  234. if res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED &&
  235. res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH &&
  236. res.RejectReason != hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
  237. t.Fatalf("reconnect must invalidate lease or refuse until baseline, got %v %s", res.RejectReason, res.Message)
  238. }
  239. }
  240. func TestClampVsRejectWholeBatch(t *testing.T) {
  241. m := backend.NewMock(1, true)
  242. d := testDev(t, m)
  243. ctx := context.Background()
  244. bad := &hthv1.ActionBatch{
  245. DeviceId: d.ID(), CommandId: "bad",
  246. ContinuousTargets: []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 5}, {Id: ids.DoorX, Value: 200}},
  247. }
  248. r := d.ValidateAction(ctx, bad)
  249. if r.Accepted {
  250. t.Fatal("must reject whole batch")
  251. }
  252. bad.AllowClamp = true
  253. r = d.ValidateAction(ctx, bad)
  254. if !r.Accepted || len(r.Clamps) == 0 {
  255. t.Fatalf("clamp %+v", r)
  256. }
  257. }
  258. func TestSnapshotSeqMonotonic(t *testing.T) {
  259. m := backend.NewMock(1, true)
  260. d := testDev(t, m)
  261. var last uint64
  262. for i := 0; i < 5; i++ {
  263. s := d.Snapshot()
  264. if s.SnapshotSeq < last {
  265. t.Fatal("seq decreased")
  266. }
  267. last = s.SnapshotSeq
  268. time.Sleep(40 * time.Millisecond)
  269. }
  270. if last < 2 {
  271. t.Fatal("expected polls to advance seq")
  272. }
  273. }
  274. func TestGetSnapshotIsCache(t *testing.T) {
  275. m := backend.NewMock(1, true)
  276. m.SetSlow(80 * time.Millisecond)
  277. d := testDev(t, m)
  278. start := time.Now()
  279. _ = d.Snapshot()
  280. if time.Since(start) > 40*time.Millisecond {
  281. t.Fatal("GetSnapshot must not wait on serial/GET_TEMP")
  282. }
  283. }
  284. func TestStaleSnapshotRejected(t *testing.T) {
  285. m := backend.NewMock(1, true)
  286. d := testDev(t, m)
  287. l := acquire(t, d)
  288. deadline := time.Now().Add(3 * time.Second)
  289. for time.Now().Before(deadline) && d.Snapshot().SnapshotSeq <= control.StaleSnapshotSlack+2 {
  290. time.Sleep(20 * time.Millisecond)
  291. }
  292. b := batch(d, l, "stale", 10)
  293. b.BasedOnSnapshotSeq = 1
  294. r := d.ApplyAction(context.Background(), b)
  295. if r.RejectReason != hthv1.RejectReason_REJECT_REASON_STALE_SNAPSHOT {
  296. t.Fatalf("got %v seq=%d", r.RejectReason, d.Snapshot().SnapshotSeq)
  297. }
  298. }
  299. func TestExpiredDeadline(t *testing.T) {
  300. m := backend.NewMock(1, true)
  301. d := testDev(t, m)
  302. l := acquire(t, d)
  303. b := batch(d, l, "dead", 10)
  304. b.ValidUntil = timestamppb.New(time.Now().Add(-time.Second))
  305. r := d.ApplyAction(context.Background(), b)
  306. if r.RejectReason != hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE {
  307. t.Fatalf("got %v", r.RejectReason)
  308. }
  309. }
  310. func TestInvalidTempNot255C(t *testing.T) {
  311. m := backend.NewMock(1, true)
  312. m.SetInvalidChannel(0, true)
  313. d := testDev(t, m)
  314. deadline := time.Now().Add(2 * time.Second)
  315. for time.Now().Before(deadline) {
  316. s := d.Snapshot()
  317. for _, m := range s.Measurements {
  318. if m.Id == ids.TempChannel(0) && m.Quality == hthv1.DataQuality_DATA_QUALITY_INVALID {
  319. if m.Value == 255 {
  320. t.Fatal("must not report 255C")
  321. }
  322. if m.QualityReason != "DEVICE_REPORTED_INVALID" {
  323. t.Fatalf("reason %s", m.QualityReason)
  324. }
  325. return
  326. }
  327. }
  328. time.Sleep(20 * time.Millisecond)
  329. }
  330. t.Fatal("invalid temp not observed")
  331. }
  332. func TestCapabilitiesHonesty(t *testing.T) {
  333. m := backend.NewMock(1, true)
  334. d := testDev(t, m)
  335. c := d.Capabilities()
  336. if c.AckSupported || c.RpmFeedbackSupported || c.PositionFeedbackSupported {
  337. t.Fatal("ack/rpm/actual-position must be false")
  338. }
  339. if c.FirmwareVersionQuality != hthv1.DataQuality_DATA_QUALITY_NOT_SUPPORTED {
  340. t.Fatal("firmware")
  341. }
  342. if c.ReadinessProbe != "motor_status_startup_complete" {
  343. t.Fatal(c.ReadinessProbe)
  344. }
  345. _ = durationpb.New(0)
  346. _ = protocol.SetAll{}
  347. }
  348. func TestNilBatchDoesNotPanic(t *testing.T) {
  349. m := backend.NewMock(1, true)
  350. d := testDev(t, m)
  351. ctx := context.Background()
  352. r := d.ApplyAction(ctx, nil)
  353. if r == nil || r.RejectReason != hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT {
  354. t.Fatalf("apply nil: %+v", r)
  355. }
  356. r = d.ValidateAction(ctx, nil)
  357. if r == nil || r.RejectReason != hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT {
  358. t.Fatalf("validate nil: %+v", r)
  359. }
  360. }
  361. func TestRawRequestedKeepsOriginalFloat(t *testing.T) {
  362. m := backend.NewMock(1, true)
  363. d := testDev(t, m)
  364. l := acquire(t, d)
  365. b := batch(d, l, "raw40", 0)
  366. b.AllowClamp = true
  367. b.ContinuousTargets = []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 40.4}}
  368. r := d.ApplyAction(context.Background(), b)
  369. if !r.Accepted {
  370. t.Fatal(r.Message, r.RejectReason)
  371. }
  372. if r.Requested == nil || len(r.Requested.Actuators) != 1 || r.Requested.Actuators[0].CommandedTarget != 40.4 {
  373. t.Fatalf("raw requested lost: %+v", r.Requested)
  374. }
  375. if r.NormalizedRequested == nil {
  376. t.Fatal("missing normalized")
  377. }
  378. }
  379. func TestStartupRejectsDoorChange(t *testing.T) {
  380. m := backend.NewMock(1, false)
  381. d := testDevNotReady(t, m)
  382. l := acquire(t, d)
  383. r := d.ApplyAction(context.Background(), batch(d, l, "door-startup", 40))
  384. if r.RejectReason != hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
  385. t.Fatalf("got %v %s", r.RejectReason, r.Message)
  386. }
  387. }
  388. func testDevNotReady(t *testing.T, mock *backend.Mock) *device.Device {
  389. t.Helper()
  390. p, err := profile.Load(testutil.ProfilePath(t))
  391. if err != nil {
  392. t.Fatal(err)
  393. }
  394. fan, ptc, door := 10, 0, 0
  395. dir := t.TempDir()
  396. cfg := &config.Config{
  397. APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
  398. Profile: testutil.ProfilePath(t),
  399. RuntimeRoot: dir,
  400. Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
  401. Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
  402. Watchdog: config.Watchdog{HeartbeatPeriodMS: 60},
  403. Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
  404. Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
  405. RingBufferSize: 32, SubscriberBufferSize: 2, CommandCacheSize: 16,
  406. AllowUnboundActions: true,
  407. Mock: config.Mock{Seed: 1, StartupComplete: false},
  408. }
  409. if err := cfg.Validate(p); err != nil {
  410. t.Fatal(err)
  411. }
  412. d := device.New(device.Params{Config: cfg, Profile: p, Backend: mock, InstanceID: "test"})
  413. ctx, cancel := context.WithCancel(context.Background())
  414. t.Cleanup(func() { cancel(); d.Stop() })
  415. d.Start(ctx)
  416. deadline := time.Now().Add(2 * time.Second)
  417. for time.Now().Before(deadline) {
  418. if d.Snapshot() != nil {
  419. return d
  420. }
  421. time.Sleep(10 * time.Millisecond)
  422. }
  423. return d
  424. }
  425. func TestShortWriteBumpsEpochAndKillsLease(t *testing.T) {
  426. m := backend.NewMock(1, true)
  427. d := testDev(t, m)
  428. l := acquire(t, d)
  429. e0 := d.Snapshot().DeviceEpoch
  430. m.ForceShortWrite()
  431. res := d.ApplyAction(context.Background(), batch(d, l, "short", 70))
  432. if res.Confirmation != hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN {
  433. t.Fatalf("got %v", res.Confirmation)
  434. }
  435. deadline := time.Now().Add(2 * time.Second)
  436. for time.Now().Before(deadline) {
  437. if d.Snapshot().DeviceEpoch > e0 {
  438. break
  439. }
  440. time.Sleep(10 * time.Millisecond)
  441. }
  442. if d.Snapshot().DeviceEpoch <= e0 {
  443. t.Fatal("epoch must bump after short write")
  444. }
  445. res = d.ApplyAction(context.Background(), batch(d, l, "after-short", 10))
  446. if res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED &&
  447. res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH &&
  448. res.RejectReason != hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
  449. t.Fatalf("old lease must die, got %v %s", res.RejectReason, res.Message)
  450. }
  451. }
  452. func TestAmbiguousFullWriteBumpsEpochAndKillsLease(t *testing.T) {
  453. m := backend.NewMock(1, true)
  454. d := testDev(t, m)
  455. l := acquire(t, d)
  456. e0 := d.Snapshot().DeviceEpoch
  457. m.ForceAmbiguousWrite()
  458. res := d.ApplyAction(context.Background(), batch(d, l, "ambig", 70))
  459. if res.Confirmation != hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN {
  460. t.Fatalf("got %v", res.Confirmation)
  461. }
  462. deadline := time.Now().Add(2 * time.Second)
  463. for time.Now().Before(deadline) {
  464. if d.Snapshot().DeviceEpoch > e0 {
  465. break
  466. }
  467. time.Sleep(10 * time.Millisecond)
  468. }
  469. if d.Snapshot().DeviceEpoch <= e0 {
  470. t.Fatal("epoch must bump after ambiguous write")
  471. }
  472. res = d.ApplyAction(context.Background(), batch(d, l, "after-ambig", 10))
  473. if res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED &&
  474. res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH &&
  475. res.RejectReason != hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
  476. t.Fatalf("old lease must die, got %v %s", res.RejectReason, res.Message)
  477. }
  478. }
  479. func TestCancelledQueuedApplyDoesNotWrite(t *testing.T) {
  480. m := backend.NewMock(1, true)
  481. d := testDev(t, m)
  482. l := acquire(t, d)
  483. m.SetSlow(250 * time.Millisecond)
  484. n0 := m.WriteCount()
  485. ctx1, cancel1 := context.WithTimeout(context.Background(), 2*time.Second)
  486. defer cancel1()
  487. done := make(chan *hthv1.ActionResult, 1)
  488. go func() { done <- d.ApplyAction(ctx1, batch(d, l, "slow", 10)) }()
  489. time.Sleep(40 * time.Millisecond)
  490. ctx2, cancel2 := context.WithTimeout(context.Background(), 20*time.Millisecond)
  491. defer cancel2()
  492. r2 := d.ApplyAction(ctx2, batch(d, l, "cancelled", 80))
  493. if r2.RejectReason != hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE && r2.RejectReason != hthv1.RejectReason_REJECT_REASON_QUEUE_FULL {
  494. t.Fatalf("expected cancel/queue, got %v %s", r2.RejectReason, r2.Message)
  495. }
  496. <-done
  497. for _, w := range m.Writes()[n0:] {
  498. if w.DoorX == 80 {
  499. t.Fatal("cancelled action must not be written")
  500. }
  501. }
  502. }
  503. func TestSlewRateWithFakeClock(t *testing.T) {
  504. m := backend.NewMock(1, true)
  505. p, err := profile.Load(testutil.ProfilePath(t))
  506. if err != nil {
  507. t.Fatal(err)
  508. }
  509. clk := clock.NewFake(time.Unix(1000, 0).UTC())
  510. fan, ptc, door := 10, 0, 0
  511. dir := t.TempDir()
  512. cfg := &config.Config{
  513. APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
  514. Profile: testutil.ProfilePath(t),
  515. RuntimeRoot: dir,
  516. Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock"},
  517. Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
  518. Watchdog: config.Watchdog{HeartbeatPeriodMS: 5000},
  519. Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 5000},
  520. Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
  521. RingBufferSize: 32, SubscriberBufferSize: 2, CommandCacheSize: 16,
  522. AllowUnboundActions: true,
  523. Mock: config.Mock{Seed: 1, StartupComplete: true},
  524. }
  525. if err := cfg.Validate(p); err != nil {
  526. t.Fatal(err)
  527. }
  528. d := device.New(device.Params{Config: cfg, Profile: p, Backend: m, Clock: clk, InstanceID: "slew"})
  529. ctx, cancel := context.WithCancel(context.Background())
  530. t.Cleanup(func() { cancel(); d.Stop() })
  531. d.Start(ctx)
  532. waitReady(t, d)
  533. clk.Advance(time.Second)
  534. l := acquire(t, d)
  535. first := batch(d, l, "slew1", 0)
  536. r := d.ApplyAction(context.Background(), first)
  537. if !r.Accepted {
  538. t.Fatal(r.Message)
  539. }
  540. clk.Advance(100 * time.Millisecond)
  541. second := batch(d, l, "slew2", 0)
  542. second.ContinuousTargets = []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 100}}
  543. r = d.ApplyAction(context.Background(), second)
  544. if r.RejectReason != hthv1.RejectReason_REJECT_REASON_SLEW_LIMITED {
  545. t.Fatalf("expected slew reject, got %v %s", r.RejectReason, r.Message)
  546. }
  547. second.AllowClamp = true
  548. second.CommandId = "slew2b"
  549. r = d.ApplyAction(context.Background(), second)
  550. if !r.Accepted {
  551. t.Fatal(r.Message)
  552. }
  553. }
  554. func TestLeaseSafeConcurrent(t *testing.T) {
  555. m := backend.NewMock(1, true)
  556. d := testDev(t, m)
  557. ctx := context.Background()
  558. var wg sync.WaitGroup
  559. for i := 0; i < 8; i++ {
  560. wg.Add(1)
  561. go func(i int) {
  562. defer wg.Done()
  563. l, err := d.AcquireLease(ctx, "c-"+string(rune('a'+i)), 200*time.Millisecond)
  564. if err != nil {
  565. return
  566. }
  567. _, _ = d.RenewLease(ctx, l.LeaseId, l.LeaseEpoch, 200*time.Millisecond)
  568. _ = d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "concurrent")
  569. }(i)
  570. }
  571. wg.Wait()
  572. }
  573. func TestFairScheduleRenewWhileApplyFlood(t *testing.T) {
  574. m := backend.NewMock(1, true)
  575. d := testDev(t, m)
  576. l := acquire(t, d)
  577. m.SetSlow(20 * time.Millisecond)
  578. ctx := context.Background()
  579. var wg sync.WaitGroup
  580. for i := 0; i < 8; i++ {
  581. wg.Add(1)
  582. go func(i int) {
  583. defer wg.Done()
  584. b := batch(d, l, "flood-"+string(rune('a'+i)), 10)
  585. _ = d.ApplyAction(ctx, b)
  586. }(i)
  587. }
  588. time.Sleep(40 * time.Millisecond)
  589. start := time.Now()
  590. _, err := d.RenewLease(ctx, l.LeaseId, l.LeaseEpoch, 400*time.Millisecond)
  591. if err != nil {
  592. t.Fatal(err)
  593. }
  594. if time.Since(start) > 400*time.Millisecond {
  595. t.Fatalf("renew delayed %s", time.Since(start))
  596. }
  597. wg.Wait()
  598. }
  599. func TestSlowTemperatureScanDoesNotBlockLease(t *testing.T) {
  600. m := backend.NewMock(1, true)
  601. d := testDev(t, m)
  602. l := acquire(t, d)
  603. m.SetSlowGet(400 * time.Millisecond)
  604. time.Sleep(80 * time.Millisecond)
  605. start := time.Now()
  606. _, err := d.RenewLease(context.Background(), l.LeaseId, l.LeaseEpoch, 400*time.Millisecond)
  607. if err != nil {
  608. t.Fatal(err)
  609. }
  610. if time.Since(start) > 150*time.Millisecond {
  611. t.Fatalf("lease renew blocked by temperature scan: %s", time.Since(start))
  612. }
  613. safeStart := time.Now()
  614. res := d.EnterSafeMode(context.Background(), l.LeaseId, l.LeaseEpoch, "during-scan")
  615. if time.Since(safeStart) > 150*time.Millisecond {
  616. t.Fatalf("EnterSafeMode blocked by scan: %s", time.Since(safeStart))
  617. }
  618. if res == nil || !res.Accepted {
  619. t.Fatalf("safe during scan: %+v", res)
  620. }
  621. }
  622. func TestReconnectDoesNotRestoreOldPTC(t *testing.T) {
  623. m := backend.NewMock(1, true)
  624. d := testDev(t, m)
  625. l := acquire(t, d)
  626. full := batch(d, l, "full-ptc", 0)
  627. for _, tgt := range full.ContinuousTargets {
  628. if len(tgt.Id) >= 4 && tgt.Id[:4] == "ptc." {
  629. tgt.Value = 80
  630. }
  631. }
  632. res := d.ApplyAction(context.Background(), full)
  633. if !res.Accepted {
  634. t.Fatal(res.Message)
  635. }
  636. e0 := d.Snapshot().DeviceEpoch
  637. m.ForceShortWrite()
  638. _ = d.ApplyAction(context.Background(), batch(d, l, "drop", 10))
  639. deadline := time.Now().Add(2 * time.Second)
  640. for time.Now().Before(deadline) {
  641. if d.Snapshot().DeviceEpoch > e0 {
  642. break
  643. }
  644. time.Sleep(10 * time.Millisecond)
  645. }
  646. deadline = time.Now().Add(2 * time.Second)
  647. var l2 *hthv1.ControlLease
  648. var err error
  649. for time.Now().Before(deadline) {
  650. l2, err = d.AcquireLease(context.Background(), "after-reconnect", 400*time.Millisecond)
  651. if err == nil && l2 != nil {
  652. break
  653. }
  654. time.Sleep(20 * time.Millisecond)
  655. }
  656. if l2 == nil {
  657. t.Fatal("could not acquire lease after reconnect", err)
  658. }
  659. waitReady(t, d)
  660. partial := &hthv1.ActionBatch{
  661. DeviceId: d.ID(), CommandId: "partial-fan-only", LeaseId: l2.LeaseId, LeaseEpoch: l2.LeaseEpoch,
  662. BasedOnSnapshotSeq: d.Snapshot().SnapshotSeq, ExpectedControlRevision: d.Snapshot().ControlRevision,
  663. ValidUntil: timestamppb.New(time.Now().Add(2 * time.Second)), ClientId: "test",
  664. ContinuousTargets: []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 30}},
  665. }
  666. pr := d.ApplyAction(context.Background(), partial)
  667. if pr.RejectReason == hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
  668. t.Log("partial rejected until baseline, as required")
  669. }
  670. last := m.LastSetAll()
  671. if last.PTC[0] == 80 {
  672. t.Fatal("old PTC value must not be restored after epoch change")
  673. }
  674. }
  675. func TestFiveSecondScanLeaseAndSafe(t *testing.T) {
  676. m := backend.NewMock(1, true)
  677. d := testDev(t, m)
  678. l := acquire(t, d)
  679. m.SetSlowGet(5 * time.Second)
  680. time.Sleep(120 * time.Millisecond)
  681. start := time.Now()
  682. if _, err := d.RenewLease(context.Background(), l.LeaseId, l.LeaseEpoch, 400*time.Millisecond); err != nil {
  683. t.Fatal(err)
  684. }
  685. if time.Since(start) > 200*time.Millisecond {
  686. t.Fatalf("lease renew blocked by 5s scan: %s", time.Since(start))
  687. }
  688. safeStart := time.Now()
  689. res := d.EnterSafeMode(context.Background(), l.LeaseId, l.LeaseEpoch, "during-5s-scan")
  690. if time.Since(safeStart) > 200*time.Millisecond {
  691. t.Fatalf("EnterSafeMode blocked by 5s scan: %s", time.Since(safeStart))
  692. }
  693. if res == nil || !res.Accepted {
  694. t.Fatalf("safe during 5s scan: %+v", res)
  695. }
  696. if !strings.Contains(res.Message, "queued") && !strings.Contains(res.Message, "dispatched") && !strings.Contains(res.Message, "control-plane") {
  697. t.Logf("safe message: %s", res.Message)
  698. }
  699. }