device_test.go 23 KB

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