feat(dispenser): recover K720 card position during uncertain encoding
This commit is contained in:
@@ -5,10 +5,12 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -25,6 +27,10 @@ type dispenserCallResult struct {
|
||||
}
|
||||
|
||||
type fakeDoorCardDispenser struct {
|
||||
preparation dispenser.PreparationResult
|
||||
recoverCurrent func(context.Context, dispenser.PreparationResult) error
|
||||
deliver func()
|
||||
|
||||
prepareCurrent dispenserCallResult
|
||||
deliverCurrent dispenserCallResult
|
||||
beginNextErr error
|
||||
@@ -45,8 +51,25 @@ func (d *fakeDoorCardDispenser) PrepareCurrentCard(context.Context) (string, err
|
||||
return d.prepareCurrent.status, d.prepareCurrent.err
|
||||
}
|
||||
|
||||
func (d *fakeDoorCardDispenser) PrepareCurrentCardForEncoding(ctx context.Context) (dispenser.PreparationResult, error) {
|
||||
stock, err := d.PrepareCurrentCard(ctx)
|
||||
result := d.preparation
|
||||
result.Stock = stock
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (d *fakeDoorCardDispenser) RecoverCurrentCard(ctx context.Context, result dispenser.PreparationResult) error {
|
||||
if d.recoverCurrent != nil {
|
||||
return d.recoverCurrent(ctx, result)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *fakeDoorCardDispenser) DeliverCurrentCard(context.Context) (string, error) {
|
||||
d.calls = append(d.calls, "deliver current")
|
||||
if d.deliver != nil {
|
||||
d.deliver()
|
||||
}
|
||||
return d.deliverCurrent.status, d.deliverCurrent.err
|
||||
}
|
||||
|
||||
@@ -64,6 +87,8 @@ func (d *fakeDoorCardDispenser) PrepareNextCard(context.Context) (string, error)
|
||||
}
|
||||
|
||||
type fakeDoorCardLockServer struct {
|
||||
sequence func() error
|
||||
|
||||
sequenceErr error
|
||||
buildCalls int
|
||||
sequenceCalls int
|
||||
@@ -76,6 +101,9 @@ func (l *fakeDoorCardLockServer) BuildCommand(lockserver.DoorCardRequest, time.T
|
||||
|
||||
func (l *fakeDoorCardLockServer) LockSequence() error {
|
||||
l.sequenceCalls++
|
||||
if l.sequence != nil {
|
||||
return l.sequence()
|
||||
}
|
||||
return l.sequenceErr
|
||||
}
|
||||
|
||||
@@ -409,3 +437,159 @@ func TestDoorCardForegroundLifecycle(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func waitDoorCardSignal(t *testing.T, signal <-chan struct{}, name string) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-signal:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatalf("timed out waiting for %s", name)
|
||||
}
|
||||
}
|
||||
|
||||
func startUncertainDoorCardRequest(t *testing.T, ctx context.Context, d *fakeDoorCardDispenser, lock *fakeDoorCardLockServer) (*httptest.ResponseRecorder, <-chan struct{}) {
|
||||
t.Helper()
|
||||
app := &App{disp: d, lockserver: lock, cfg: &config.ConfigRec{}}
|
||||
request := httptest.NewRequest(http.MethodPost, "/issuedoorcard", strings.NewReader(`{"roomField":"101","checkinTime":"2026-07-23 15:00:00 +0100","checkoutTime":"2026-07-24 11:00:00 +0100"}`)).WithContext(ctx)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
recorder := httptest.NewRecorder()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
app.issueDoorCard(recorder, request)
|
||||
}()
|
||||
return recorder, done
|
||||
}
|
||||
|
||||
func TestIssueDoorCardJoinsUncertainRecoveryBeforeDelivery(t *testing.T) {
|
||||
for _, encodingErr := range []error{nil, errors.New("original lock-server failure")} {
|
||||
t.Run(fmt.Sprint(encodingErr), func(t *testing.T) {
|
||||
lockStarted := make(chan struct{})
|
||||
recoveryStarted := make(chan struct{})
|
||||
recoveryStopped := make(chan struct{})
|
||||
d := &fakeDoorCardDispenser{preparation: dispenser.PreparationResult{UncertainHandoff: true, ShakesUsed: 1}}
|
||||
d.recoverCurrent = func(ctx context.Context, preparation dispenser.PreparationResult) error {
|
||||
defer close(recoveryStopped)
|
||||
<-lockStarted
|
||||
if preparation.ShakesUsed != 1 || !preparation.UncertainHandoff {
|
||||
t.Errorf("recovery preparation=%+v, want same uncertain request and used budget", preparation)
|
||||
}
|
||||
close(recoveryStarted)
|
||||
<-ctx.Done()
|
||||
if context.Cause(ctx).Error() != "LockSequence completed" {
|
||||
t.Errorf("recovery cause=%v, want LockSequence completed", context.Cause(ctx))
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
d.deliver = func() {
|
||||
select {
|
||||
case <-recoveryStopped:
|
||||
default:
|
||||
t.Error("FC0 started before recovery stopped")
|
||||
}
|
||||
}
|
||||
lock := &fakeDoorCardLockServer{sequence: func() error {
|
||||
close(lockStarted)
|
||||
<-recoveryStarted
|
||||
return encodingErr
|
||||
}}
|
||||
recorder, done := startUncertainDoorCardRequest(t, context.Background(), d, lock)
|
||||
waitDoorCardSignal(t, done, "encoding and recovery shutdown")
|
||||
wantHTTP := http.StatusOK
|
||||
wantCalls := []string{"prepare current", "deliver current", "begin prepare next"}
|
||||
if encodingErr != nil {
|
||||
wantHTTP = http.StatusBadGateway
|
||||
wantCalls = []string{"prepare current", "deliver current"}
|
||||
if !strings.Contains(recorder.Body.String(), encodingErr.Error()) {
|
||||
t.Errorf("response=%s, want original encoding failure", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
if recorder.Code != wantHTTP || lock.sequenceCalls != 1 || !reflect.DeepEqual(d.calls, wantCalls) {
|
||||
t.Errorf("HTTP=%d lock calls=%d dispenser calls=%v, want HTTP=%d one encoding and %v", recorder.Code, lock.sequenceCalls, d.calls, wantHTTP, wantCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssueDoorCardRecoveryEndingDoesNotEndEncoding(t *testing.T) {
|
||||
for _, recoveryErr := range []error{nil, dispenser.ErrCardWellEmpty, errors.New("RS dispatch failed")} {
|
||||
t.Run(fmt.Sprint(recoveryErr), func(t *testing.T) {
|
||||
lockStarted := make(chan struct{})
|
||||
recoveryStopped := make(chan struct{})
|
||||
releaseLock := make(chan struct{})
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(releaseLock) }) }
|
||||
t.Cleanup(release)
|
||||
encodingErr := errors.New("original encoding timed out")
|
||||
d := &fakeDoorCardDispenser{preparation: dispenser.PreparationResult{UncertainHandoff: true, ShakesUsed: 3}}
|
||||
d.recoverCurrent = func(ctx context.Context, preparation dispenser.PreparationResult) error {
|
||||
<-lockStarted
|
||||
close(recoveryStopped) // Encoder arrival, exhaustion or a mechanical failure.
|
||||
return recoveryErr
|
||||
}
|
||||
lock := &fakeDoorCardLockServer{sequence: func() error {
|
||||
close(lockStarted)
|
||||
<-releaseLock
|
||||
return encodingErr
|
||||
}}
|
||||
recorder, done := startUncertainDoorCardRequest(t, context.Background(), d, lock)
|
||||
waitDoorCardSignal(t, recoveryStopped, "recovery ending while lock waits")
|
||||
select {
|
||||
case <-done:
|
||||
t.Error("recovery ending replaced still-running LockSequence")
|
||||
default:
|
||||
}
|
||||
release()
|
||||
waitDoorCardSignal(t, done, "original LockSequence result")
|
||||
if recorder.Code != http.StatusBadGateway || !strings.Contains(recorder.Body.String(), encodingErr.Error()) || lock.sequenceCalls != 1 || !reflect.DeepEqual(d.calls, []string{"prepare current", "deliver current"}) {
|
||||
t.Errorf("HTTP=%d body=%s locks=%d commands=%v, want original encoding error and one FC0", recorder.Code, recorder.Body.String(), lock.sequenceCalls, d.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssueDoorCardCancellationStopsOnlyUncertainRecovery(t *testing.T) {
|
||||
lockStarted := make(chan struct{})
|
||||
recoveryStarted := make(chan struct{})
|
||||
recoveryStopped := make(chan struct{})
|
||||
releaseLock := make(chan struct{})
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(releaseLock) }) }
|
||||
t.Cleanup(release)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
d := &fakeDoorCardDispenser{preparation: dispenser.PreparationResult{UncertainHandoff: true}}
|
||||
d.recoverCurrent = func(ctx context.Context, preparation dispenser.PreparationResult) error {
|
||||
defer close(recoveryStopped)
|
||||
<-lockStarted
|
||||
close(recoveryStarted)
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
d.deliver = func() {
|
||||
select {
|
||||
case <-recoveryStopped:
|
||||
default:
|
||||
t.Error("delivery raced cancelled recovery")
|
||||
}
|
||||
}
|
||||
lock := &fakeDoorCardLockServer{sequence: func() error {
|
||||
close(lockStarted)
|
||||
<-releaseLock
|
||||
return nil
|
||||
}}
|
||||
recorder, done := startUncertainDoorCardRequest(t, ctx, d, lock)
|
||||
waitDoorCardSignal(t, recoveryStarted, "concurrent recovery")
|
||||
cancel()
|
||||
waitDoorCardSignal(t, recoveryStopped, "cancelled recovery")
|
||||
select {
|
||||
case <-done:
|
||||
t.Error("caller cancellation ended the original LockSequence")
|
||||
default:
|
||||
}
|
||||
release()
|
||||
waitDoorCardSignal(t, done, "delivery after encoding")
|
||||
if recorder.Code != http.StatusOK || lock.sequenceCalls != 1 || !reflect.DeepEqual(d.calls, []string{"prepare current", "deliver current", "begin prepare next"}) {
|
||||
t.Errorf("cancelled HTTP=%d lock calls=%d commands=%v, want original successful encoding and one delivery", recorder.Code, lock.sequenceCalls, d.calls)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ import (
|
||||
type doorCardDispenser interface {
|
||||
BeginForeground() func()
|
||||
PrepareCurrentCard(context.Context) (string, error)
|
||||
PrepareCurrentCardForEncoding(context.Context) (dispenser.PreparationResult, error)
|
||||
RecoverCurrentCard(context.Context, dispenser.PreparationResult) error
|
||||
DeliverCurrentCard(context.Context) (string, error)
|
||||
BeginPrepareNextCard(context.Context) error
|
||||
PrepareNextCard(context.Context) (string, error)
|
||||
@@ -294,8 +296,8 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||
release := app.disp.BeginForeground()
|
||||
defer release()
|
||||
|
||||
status, err := app.disp.PrepareCurrentCard(r.Context())
|
||||
app.SetCardWellStatus(status)
|
||||
preparation, err := app.disp.PrepareCurrentCardForEncoding(r.Context())
|
||||
app.SetCardWellStatus(preparation.Stock)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
||||
if errors.Is(err, dispenser.ErrCardWellEmpty) {
|
||||
@@ -317,8 +319,28 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||
// Each request performs at most one encoder operation.
|
||||
encodingStarted := time.Now()
|
||||
log.Info("LockSequence started")
|
||||
var stopRecovery context.CancelCauseFunc
|
||||
var recoveryDone chan struct{}
|
||||
if preparation.UncertainHandoff {
|
||||
log.Infof("uncertain handoff; concurrent K720 recovery enabled; shakes=%d", preparation.ShakesUsed)
|
||||
var recoveryCtx context.Context
|
||||
recoveryCtx, stopRecovery = context.WithCancelCause(r.Context())
|
||||
recoveryDone = make(chan struct{})
|
||||
go func() {
|
||||
defer close(recoveryDone)
|
||||
if err := app.disp.RecoverCurrentCard(recoveryCtx, preparation); err != nil && recoveryCtx.Err() == nil {
|
||||
log.WithError(err).Warn("K720 recovery failed; awaiting original LockSequence result")
|
||||
}
|
||||
}()
|
||||
}
|
||||
encodingErr := app.lockserver.LockSequence()
|
||||
if stopRecovery != nil {
|
||||
stopRecovery(errors.New("LockSequence completed"))
|
||||
}
|
||||
log.Infof("LockSequence finished; success=%t duration=%s", encodingErr == nil, time.Since(encodingStarted))
|
||||
if recoveryDone != nil {
|
||||
<-recoveryDone
|
||||
}
|
||||
if encodingErr != nil {
|
||||
logging.Error(types.ServiceName, encodingErr.Error(), "Key encoding", string(op), "", "", 0)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user