| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614 |
- package device_test
- import (
- "context"
- "fmt"
- "strings"
- "testing"
- "time"
- "hth/internal/backend"
- "hth/internal/config"
- "hth/internal/device"
- hthv1 "hth/internal/gen/hth/api/v1"
- "hth/internal/profile"
- "hth/internal/testutil"
- )
- func drainActionResults(subC <-chan *hthv1.Event) (<-chan *hthv1.ActionResult, context.CancelFunc) {
- ctx, cancel := context.WithCancel(context.Background())
- out := make(chan *hthv1.ActionResult, 64)
- go func() {
- defer close(out)
- for {
- select {
- case <-ctx.Done():
- return
- case ev, ok := <-subC:
- if !ok {
- return
- }
- if ev != nil && ev.ActionResult != nil {
- select {
- case out <- ev.ActionResult:
- case <-ctx.Done():
- return
- }
- }
- }
- }
- }()
- return out, cancel
- }
- func waitAR(t *testing.T, ch <-chan *hthv1.ActionResult, timeout time.Duration, pred func(*hthv1.ActionResult) bool) *hthv1.ActionResult {
- t.Helper()
- deadline := time.Now().Add(timeout)
- for time.Now().Before(deadline) {
- remain := time.Until(deadline)
- if remain <= 0 {
- break
- }
- select {
- case ar, ok := <-ch:
- if !ok {
- t.Fatal("action result stream closed")
- }
- if pred == nil || pred(ar) {
- return ar
- }
- case <-time.After(remain):
- }
- }
- t.Fatal("timed out waiting for ActionResult")
- return nil
- }
- func TestManualSafeWriteDisconnectedDropsTransport(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevSafety(t, m, 10, 0, 0)
- sub, _, _, err := d.SubscribeEvents(0, "r5-disc")
- if err != nil {
- t.Fatal(err)
- }
- defer sub.Cancel()
- ars, stop := drainActionResults(sub.C)
- defer stop()
- epoch := d.Snapshot().DeviceEpoch
- m.ForceDisconnectOnce()
- ctx := context.Background()
- l := acquire(t, d)
- res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
- if !res.Accepted {
- t.Fatalf("enter accepted=%v %s", res.Accepted, res.Message)
- }
- ar := waitAR(t, ars, 3*time.Second, func(a *hthv1.ActionResult) bool {
- return a.CommandId == res.CommandId && (a.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED ||
- a.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN)
- })
- if ar.Confirmation == hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED {
- t.Fatal("disconnected Safe must not be UNCONFIRMED success")
- }
- deadline := time.Now().Add(3 * time.Second)
- for time.Now().Before(deadline) {
- s := d.Snapshot()
- if s.DeviceEpoch > epoch && s.GetTransportState() != hthv1.TransportState_TRANSPORT_STATE_CONNECTED {
- return
- }
- time.Sleep(20 * time.Millisecond)
- }
- s := d.Snapshot()
- t.Fatalf("want epoch bump and not connected: epoch %d->%d transport %v", epoch, s.DeviceEpoch, s.GetTransportState())
- }
- func startMockNoWait(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)
- return d
- }
- func TestEpochBaselineWriteDisconnectedDrops(t *testing.T) {
- m := backend.NewMock(1, true)
- m.ForceDisconnectOnce()
- d := startMockNoWait(t, m)
- deadline := time.Now().Add(4 * time.Second)
- saw := false
- for time.Now().Before(deadline) {
- s := d.Snapshot()
- if s.DeviceEpoch > 1 && s.GetTransportState() != hthv1.TransportState_TRANSPORT_STATE_CONNECTED {
- saw = true
- break
- }
- time.Sleep(20 * time.Millisecond)
- }
- if !saw {
- t.Fatalf("epoch baseline disconnect did not drop: epoch=%d transport=%v", d.Snapshot().DeviceEpoch, d.Snapshot().GetTransportState())
- }
- }
- func TestManualSafeNotStartedThenSuccessKeepsCommandID(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevSafety(t, m, 10, 0, 0)
- sub, _, _, err := d.SubscribeEvents(0, "r5-ns")
- if err != nil {
- t.Fatal(err)
- }
- defer sub.Cancel()
- ars, stop := drainActionResults(sub.C)
- defer stop()
- m.ForceZeroByteWrite()
- ctx := context.Background()
- l := acquire(t, d)
- res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
- ar := waitAR(t, ars, 5*time.Second, func(a *hthv1.ActionResult) bool {
- return a.CommandId == res.CommandId && (a.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED ||
- a.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED)
- })
- if ar.DispatchState != hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED {
- t.Fatalf("expected NotStarted then success, got %v %s", ar.DispatchState, ar.Message)
- }
- if ar.CommandId != res.CommandId {
- t.Fatalf("command id changed %q -> %q", res.CommandId, ar.CommandId)
- }
- waitMode(t, d, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, 2*time.Second)
- }
- func TestEpochBaselineNotStartedThenSuccess(t *testing.T) {
- m := backend.NewMock(1, true)
- m.ForceZeroByteWrite()
- d := testDev(t, m)
- waitReady(t, d)
- if d.Snapshot().GetContinuousTargets() == nil {
- t.Fatal("baseline should publish commanded targets after retry")
- }
- }
- func TestSafeNotStartedUntilDeadlineEmitsTerminal(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevSafety(t, m, 10, 0, 0)
- sub, _, _, err := d.SubscribeEvents(0, "r5-dead")
- if err != nil {
- t.Fatal(err)
- }
- defer sub.Cancel()
- ars, stop := drainActionResults(sub.C)
- defer stop()
- m.ForceZeroByteWrites(64)
- ctx := context.Background()
- l := acquire(t, d)
- res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
- start := time.Now()
- ar := waitAR(t, ars, 3*time.Second, func(a *hthv1.ActionResult) bool {
- return a.CommandId == res.CommandId && a.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED
- })
- if ar.CommandId != res.CommandId {
- t.Fatalf("retry chain changed command id")
- }
- if time.Since(start) < 40*time.Millisecond {
- t.Fatalf("retries completed too fast (%s); busy-loop?", time.Since(start))
- }
- if d.Snapshot().GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_UNSPECIFIED {
- t.Fatal("mode unset")
- }
- }
- func TestSafeRetryDoesNotBusyLoop(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevSafety(t, m, 10, 0, 0)
- before := m.WriteCount()
- m.ForceZeroByteWrites(32)
- ctx := context.Background()
- l := acquire(t, d)
- _ = d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
- time.Sleep(180 * time.Millisecond)
- after := m.WriteCount()
- delta := after - before
- if delta > 8 {
- t.Fatalf("too many SET_ALL attempts in 180ms: %d (busy loop)", delta)
- }
- }
- func TestEverySETALLHasActionResultIncludingHeartbeat(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevSafety(t, m, 10, 0, 0)
- sub, _, _, err := d.SubscribeEvents(0, "r5-all")
- if err != nil {
- t.Fatal(err)
- }
- defer sub.Cancel()
- ars, stop := drainActionResults(sub.C)
- defer stop()
- ctx := context.Background()
- l := acquire(t, d)
- rev0 := d.Snapshot().ControlRevision
- res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
- ar := waitAR(t, ars, 5*time.Second, func(a *hthv1.ActionResult) bool {
- return a.CommandId == res.CommandId && a.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED
- })
- waitMode(t, d, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, 2*time.Second)
- if ar.Dispatched == nil || ar.Dispatched.ActionEpoch == 0 || ar.Dispatched.PortGeneration == 0 {
- t.Fatal("safe dispatched record missing epoch/port")
- }
- rev1 := d.Snapshot().ControlRevision
- if rev1 <= rev0 {
- t.Fatalf("safe write should bump control_revision %d -> %d", rev0, rev1)
- }
- for _, tgt := range d.Snapshot().ContinuousTargets {
- if tgt.TargetQuality != hthv1.DataQuality_DATA_QUALITY_VALID {
- t.Fatalf("target quality %v want VALID", tgt.TargetQuality)
- }
- if tgt.TargetEpoch == 0 {
- t.Fatal("target epoch 0")
- }
- if tgt.ActualQuality != hthv1.DataQuality_DATA_QUALITY_NOT_SUPPORTED {
- t.Fatal("actual must stay NOT_SUPPORTED")
- }
- }
- }
- func TestHeartbeatDoesNotBumpRevision(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevSafety(t, m, 10, 0, 0)
- waitReady(t, d)
- rev := d.Snapshot().ControlRevision
- time.Sleep(200 * time.Millisecond)
- if d.Snapshot().ControlRevision != rev {
- t.Fatalf("revision changed without a committed new target: %d -> %d", rev, d.Snapshot().ControlRevision)
- }
- }
- func TestCancelledLeaseOpsHaveNoSideEffects(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevSafety(t, m, 10, 0, 0)
- ctx, cancel := context.WithCancel(context.Background())
- cancel()
- lease, err := d.AcquireLease(ctx, "ghost", time.Second)
- if lease != nil && lease.LeaseId != "" && err == nil {
- t.Fatal("cancelled acquire must not return a live lease")
- }
- time.Sleep(80 * time.Millisecond)
- s := d.Snapshot()
- if s.Lease != nil && s.Lease.Active {
- t.Fatal("cancelled acquire mutated lease")
- }
- live := acquire(t, d)
- ctx2, cancel2 := context.WithCancel(context.Background())
- cancel2()
- _ = d.ReleaseLease(ctx2, live.LeaseId, live.LeaseEpoch)
- time.Sleep(80 * time.Millisecond)
- s = d.Snapshot()
- if s.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE ||
- s.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING {
- t.Fatal("cancelled release must not enter Safe")
- }
- ctx3, cancel3 := context.WithCancel(context.Background())
- cancel3()
- _, _ = d.RenewLease(ctx3, live.LeaseId, live.LeaseEpoch, time.Second)
- time.Sleep(50 * time.Millisecond)
- }
- func TestSafeEventNotPublishedBeforeDispatch(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevSafety(t, m, 10, 0, 0)
- sub, _, _, err := d.SubscribeEvents(0, "r5-evt")
- if err != nil {
- t.Fatal(err)
- }
- defer sub.Cancel()
- m.SetSlow(400 * time.Millisecond)
- ctx := context.Background()
- l := acquire(t, d)
- res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
- if res.GetDispatchState() == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED {
- t.Fatal("RPC return must not claim physical SAFE write complete")
- }
- deadline := time.Now().Add(300 * time.Millisecond)
- for time.Now().Before(deadline) {
- select {
- case ev := <-sub.C:
- if ev != nil && ev.Kind == hthv1.EventKind_EVENT_KIND_SAFE_MODE_ENTERED {
- t.Fatal("SAFE_MODE_ENTERED published before write completed")
- }
- default:
- time.Sleep(10 * time.Millisecond)
- }
- }
- }
- func TestIngressLatestWinsDoesNotBacklog(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevSafety(t, m, 10, 0, 0)
- l := acquire(t, d)
- m.SetSlow(80 * time.Millisecond)
- n := 12
- done := make(chan *hthv1.ActionResult, n)
- for i := 0; i < n; i++ {
- b := batch(d, l, fmt.Sprintf("lw-%d", i), uint8(10+i%5))
- go func(b *hthv1.ActionBatch) { done <- d.ApplyAction(context.Background(), b) }(b)
- }
- superseded := 0
- queueFull := 0
- accepted := 0
- deadline := time.Now().Add(8 * time.Second)
- for i := 0; i < n; i++ {
- remain := time.Until(deadline)
- if remain <= 0 {
- t.Fatal("timeout waiting apply results")
- }
- select {
- case r := <-done:
- if r.RejectReason == hthv1.RejectReason_REJECT_REASON_QUEUE_FULL {
- queueFull++
- }
- if r.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED ||
- r.RejectReason == hthv1.RejectReason_REJECT_REASON_SUPERSEDED {
- superseded++
- }
- if r.Accepted {
- accepted++
- }
- case <-time.After(remain):
- t.Fatal("timeout")
- }
- }
- if queueFull != 0 {
- t.Fatalf("ingress must latest-wins not QUEUE_FULL, got %d queue-full", queueFull)
- }
- if accepted+superseded == 0 {
- t.Fatal("expected accepted and/or superseded outcomes")
- }
- }
- func testDevLongLease(t *testing.T, mock *backend.Mock, fan, ptc, door int) *device.Device {
- t.Helper()
- p, err := profile.Load(testutil.ProfilePath(t))
- if err != nil {
- t.Fatal(err)
- }
- 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 TestControlRevisionOnlyAtCommitPoints(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevLongLease(t, m, 10, 0, 0)
- l, err := d.AcquireLease(context.Background(), "rev", 8*time.Second)
- if err != nil {
- t.Fatal(err)
- }
- seen := []uint64{d.Snapshot().ControlRevision}
- for i, duty := range []uint8{20, 30, 40} {
- res := d.ApplyAction(context.Background(), batch(d, l, fmt.Sprintf("rev-%d", i), duty))
- if !res.Accepted {
- t.Fatalf("apply %d rejected %s", i, res.Message)
- }
- time.Sleep(250 * time.Millisecond)
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- rev := d.Snapshot().ControlRevision
- if rev > seen[len(seen)-1] {
- seen = append(seen, rev)
- break
- }
- time.Sleep(10 * time.Millisecond)
- }
- }
- if len(seen) < 4 {
- t.Fatalf("revision should advance on each committed apply, got %v", seen)
- }
- for i := 1; i < len(seen); i++ {
- if seen[i] <= seen[i-1] {
- t.Fatalf("control_revision not strictly monotonic: %v", seen)
- }
- }
- beforeHB := d.Snapshot().ControlRevision
- time.Sleep(50 * time.Millisecond)
- if d.Snapshot().ControlRevision != beforeHB {
- t.Fatal("idle wait must not bump revision")
- }
- }
- func testDevHB(t *testing.T, mock *backend.Mock) *device.Device {
- t.Helper()
- p, err := profile.Load(testutil.ProfilePath(t))
- if err != nil {
- t.Fatal(err)
- }
- dir := t.TempDir()
- fan, ptc, door := 10, 0, 0
- 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: 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 TestHeartbeatStructuredResultDoesNotBumpRevision(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevHB(t, m)
- sub, _, _, err := d.SubscribeEvents(0, "r5-hb")
- if err != nil {
- t.Fatal(err)
- }
- defer sub.Cancel()
- ars, stop := drainActionResults(sub.C)
- defer stop()
- rev := d.Snapshot().ControlRevision
- ar := waitAR(t, ars, 3*time.Second, func(a *hthv1.ActionResult) bool {
- return a != nil && strings.Contains(a.ActionOrigin, "heartbeat") && a.CommandId != ""
- })
- if ar.DispatchState != hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED &&
- ar.DispatchState != hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED {
- t.Fatalf("heartbeat dispatch %v", ar.DispatchState)
- }
- if d.Snapshot().ControlRevision != rev {
- t.Fatalf("heartbeat must not bump control_revision %d -> %d", rev, d.Snapshot().ControlRevision)
- }
- }
- func TestSafeNotStartedRetriesWithoutSubscriber(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevSafety(t, m, 10, 0, 0)
- m.ForceZeroByteWrites(64)
- l := acquire(t, d)
- res := d.EnterSafeMode(context.Background(), l.LeaseId, l.LeaseEpoch, "manual")
- if res.CommandId == "" {
- t.Fatal("missing command id")
- }
- deadline := time.Now().Add(3 * time.Second)
- for time.Now().Before(deadline) {
- for _, f := range d.Snapshot().GetActiveFaults() {
- if f.GetType() == hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED {
- if d.Snapshot().GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
- t.Fatal("must not latch SAFE without a complete write")
- }
- return
- }
- }
- time.Sleep(20 * time.Millisecond)
- }
- t.Fatalf("expected NOT_DELIVERED fault without event subscriber, mode=%v faults=%v",
- d.Snapshot().GetSafetyControlMode(), d.Snapshot().GetActiveFaults())
- }
- func TestQueuedCancelledLeaseOps(t *testing.T) {
- m := backend.NewMock(1, true)
- d := testDevLongLease(t, m, 10, 0, 0)
- d.TestingHoldActor(true)
- time.Sleep(30 * time.Millisecond)
- ctx, cancel := context.WithCancel(context.Background())
- done := make(chan error, 1)
- go func() {
- l, err := d.AcquireLease(ctx, "queued-cancel", 2*time.Second)
- if l != nil && l.LeaseId != "" && err == nil {
- done <- fmt.Errorf("cancelled queued acquire returned live lease")
- return
- }
- done <- nil
- }()
- time.Sleep(25 * time.Millisecond)
- cancel()
- d.TestingHoldActor(false)
- select {
- case err := <-done:
- if err != nil {
- t.Fatal(err)
- }
- case <-time.After(2 * time.Second):
- d.TestingHoldActor(false)
- t.Fatal("acquire did not return")
- }
- if s := d.Snapshot(); s.Lease != nil && s.Lease.Active {
- t.Fatal("queued-cancelled acquire mutated lease")
- }
- live, err := d.AcquireLease(context.Background(), "keeper", 8*time.Second)
- if err != nil {
- t.Fatal(err)
- }
- d.TestingHoldActor(true)
- time.Sleep(20 * time.Millisecond)
- ctxR, cancelR := context.WithCancel(context.Background())
- doneR := make(chan error, 1)
- go func() { doneR <- d.ReleaseLease(ctxR, live.LeaseId, live.LeaseEpoch) }()
- time.Sleep(20 * time.Millisecond)
- cancelR()
- d.TestingHoldActor(false)
- select {
- case <-doneR:
- case <-time.After(2 * time.Second):
- d.TestingHoldActor(false)
- t.Fatal("release did not return")
- }
- s := d.Snapshot()
- if s.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE ||
- s.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING {
- t.Fatal("cancelled queued release must not enter Safe")
- }
- if s.Lease == nil || !s.Lease.Active || s.Lease.LeaseId != live.LeaseId {
- t.Fatal("cancelled queued release must keep lease")
- }
- epoch := live.LeaseEpoch
- d.TestingHoldActor(true)
- time.Sleep(20 * time.Millisecond)
- ctxN, cancelN := context.WithCancel(context.Background())
- doneN := make(chan struct{})
- go func() {
- _, _ = d.RenewLease(ctxN, live.LeaseId, live.LeaseEpoch, 8*time.Second)
- close(doneN)
- }()
- time.Sleep(20 * time.Millisecond)
- cancelN()
- d.TestingHoldActor(false)
- select {
- case <-doneN:
- case <-time.After(2 * time.Second):
- d.TestingHoldActor(false)
- t.Fatal("renew did not return")
- }
- s2 := d.Snapshot()
- if s2.Lease == nil || s2.Lease.LeaseEpoch != epoch {
- t.Fatal("cancelled queued renew must not change lease epoch")
- }
- }
|