602 lines
21 KiB
Go
602 lines
21 KiB
Go
package handlers
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"reflect"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/config"
|
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/dispenser"
|
|
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/lockserver"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
type dispenserCallResult struct {
|
|
status string
|
|
err error
|
|
}
|
|
|
|
type fakeDoorCardDispenser struct {
|
|
preparation dispenser.PreparationResult
|
|
recoverCurrent func(context.Context, dispenser.PreparationResult) error
|
|
deliver func()
|
|
|
|
prepareCurrent dispenserCallResult
|
|
deliverCurrent dispenserCallResult
|
|
beginNextErr error
|
|
beginNext func() error
|
|
prepareNext dispenserCallResult
|
|
activity int
|
|
registrations int
|
|
releases int
|
|
outsideActivity bool
|
|
calls []string
|
|
}
|
|
|
|
func (d *fakeDoorCardDispenser) PrepareCurrentCard(context.Context) (string, error) {
|
|
if d.activity == 0 {
|
|
d.outsideActivity = true
|
|
}
|
|
d.calls = append(d.calls, "prepare current")
|
|
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
|
|
}
|
|
|
|
func (d *fakeDoorCardDispenser) BeginPrepareNextCard(context.Context) error {
|
|
d.calls = append(d.calls, "begin prepare next")
|
|
if d.beginNext != nil {
|
|
return d.beginNext()
|
|
}
|
|
return d.beginNextErr
|
|
}
|
|
|
|
func (d *fakeDoorCardDispenser) PrepareNextCard(context.Context) (string, error) {
|
|
d.calls = append(d.calls, "prepare next")
|
|
return d.prepareNext.status, d.prepareNext.err
|
|
}
|
|
|
|
type fakeDoorCardLockServer struct {
|
|
sequence func() error
|
|
|
|
sequenceErr error
|
|
buildErr error
|
|
storedCommand string
|
|
buildCalls int
|
|
sequenceCalls int
|
|
}
|
|
|
|
func (l *fakeDoorCardLockServer) BuildCommand(request lockserver.DoorCardRequest, _ time.Time, _ time.Time) error {
|
|
l.buildCalls++
|
|
if l.buildErr != nil {
|
|
return l.buildErr
|
|
}
|
|
l.storedCommand = request.RoomField
|
|
return nil
|
|
}
|
|
|
|
func (l *fakeDoorCardLockServer) LockSequence() error {
|
|
l.sequenceCalls++
|
|
if l.sequence != nil {
|
|
return l.sequence()
|
|
}
|
|
return l.sequenceErr
|
|
}
|
|
|
|
func performIssueDoorCardRequest(
|
|
t *testing.T,
|
|
dispenser *fakeDoorCardDispenser,
|
|
lock *fakeDoorCardLockServer,
|
|
) (*httptest.ResponseRecorder, cmstypes.StatusRec, *App) {
|
|
t.Helper()
|
|
|
|
payload := lockserver.DoorCardRequest{
|
|
RoomField: "101",
|
|
CheckinTime: "2026-07-23 15:00:00 +0100",
|
|
CheckoutTime: "2026-07-24 11:00:00 +0100",
|
|
FollowStr: "0",
|
|
}
|
|
body, err := json.Marshal(payload)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
app := &App{
|
|
disp: dispenser,
|
|
lockserver: lock,
|
|
cfg: &config.ConfigRec{},
|
|
}
|
|
request := httptest.NewRequest(http.MethodPost, "/issuedoorcard", bytes.NewReader(body))
|
|
request.Header.Set("Content-Type", "application/json")
|
|
recorder := httptest.NewRecorder()
|
|
|
|
app.issueDoorCard(recorder, request)
|
|
|
|
var response cmstypes.StatusRec
|
|
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
|
|
t.Fatalf("decode response %q: %v", recorder.Body.String(), err)
|
|
}
|
|
return recorder, response, app
|
|
}
|
|
|
|
func TestIssueDoorCardPhysicalOutcomeContract(t *testing.T) {
|
|
encodingErr := errors.New("key encoding failed")
|
|
tests := []struct {
|
|
name string
|
|
dispenser fakeDoorCardDispenser
|
|
lockErr error
|
|
wantHTTP int
|
|
wantMessage string
|
|
wantCalls []string
|
|
wantLockSequence int
|
|
wantCardWell string
|
|
}{
|
|
{
|
|
name: "initial dispenser preparation failure is retryable",
|
|
dispenser: fakeDoorCardDispenser{
|
|
prepareCurrent: dispenserCallResult{status: "Card jammed", err: errors.New("card jammed")},
|
|
},
|
|
wantHTTP: http.StatusBadGateway,
|
|
wantMessage: "Dispense error: card jammed",
|
|
wantCalls: []string{"prepare current"},
|
|
wantCardWell: "Card jammed",
|
|
},
|
|
{
|
|
name: "initial empty card well has stable message",
|
|
dispenser: fakeDoorCardDispenser{
|
|
prepareCurrent: dispenserCallResult{status: "Card empty", err: dispenser.ErrCardWellEmpty},
|
|
},
|
|
wantHTTP: http.StatusServiceUnavailable,
|
|
wantMessage: dispenser.CardWellEmptyMessage,
|
|
wantCalls: []string{"prepare current"},
|
|
wantCardWell: "Card empty",
|
|
},
|
|
{
|
|
name: "exhausted preparation is retryable without encoding or delivery",
|
|
dispenser: fakeDoorCardDispenser{prepareCurrent: dispenserCallResult{err: errors.Join(errors.New("preparation"), dispenser.ErrPreparationExhausted)}},
|
|
wantHTTP: http.StatusBadGateway,
|
|
wantMessage: "preparation\ncard preparation exhausted",
|
|
wantCalls: []string{"prepare current"},
|
|
},
|
|
{
|
|
name: "encoding and accepted delivery command succeed",
|
|
wantHTTP: http.StatusOK,
|
|
wantMessage: "Card issued successfully",
|
|
wantCalls: []string{"prepare current", "deliver current", "begin prepare next"},
|
|
wantLockSequence: 1,
|
|
},
|
|
{
|
|
name: "successful encoding with delivery command failure still prestages and succeeds",
|
|
dispenser: fakeDoorCardDispenser{
|
|
deliverCurrent: dispenserCallResult{status: "Card jammed", err: errors.New("delivery jammed")},
|
|
},
|
|
wantHTTP: http.StatusOK,
|
|
wantMessage: "Card issued successfully",
|
|
wantCalls: []string{"prepare current", "deliver current", "begin prepare next"},
|
|
wantLockSequence: 1,
|
|
wantCardWell: "Card jammed",
|
|
},
|
|
{
|
|
name: "failed next-card dispatch does not undo delivered card",
|
|
dispenser: fakeDoorCardDispenser{
|
|
beginNextErr: errors.New("dispatch failed"),
|
|
},
|
|
wantHTTP: http.StatusOK,
|
|
wantMessage: "Card issued successfully",
|
|
wantCalls: []string{"prepare current", "deliver current", "begin prepare next"},
|
|
wantLockSequence: 1,
|
|
},
|
|
{
|
|
name: "delivery clearance deferral does not undo successful issuance",
|
|
dispenser: fakeDoorCardDispenser{
|
|
beginNextErr: errors.New("next-card preparation deferred: previous delivery is not clear"),
|
|
},
|
|
wantHTTP: http.StatusOK,
|
|
wantMessage: "Card issued successfully",
|
|
wantCalls: []string{"prepare current", "deliver current", "begin prepare next"},
|
|
wantLockSequence: 1,
|
|
},
|
|
{
|
|
name: "encoding failure ends after delivery",
|
|
lockErr: encodingErr,
|
|
wantHTTP: http.StatusBadGateway,
|
|
wantMessage: encodingErr.Error(),
|
|
wantCalls: []string{"prepare current", "deliver current"},
|
|
wantLockSequence: 1,
|
|
},
|
|
{
|
|
name: "encoding failure remains retryable despite FC0 failure",
|
|
dispenser: fakeDoorCardDispenser{
|
|
deliverCurrent: dispenserCallResult{status: "Card jammed", err: errors.New("delivery jammed")},
|
|
},
|
|
lockErr: encodingErr,
|
|
wantHTTP: http.StatusBadGateway,
|
|
wantMessage: encodingErr.Error(),
|
|
wantCalls: []string{"prepare current", "deliver current"},
|
|
wantLockSequence: 1,
|
|
wantCardWell: "Card jammed",
|
|
},
|
|
{
|
|
name: "encoding failure never prepares next card",
|
|
dispenser: fakeDoorCardDispenser{
|
|
prepareNext: dispenserCallResult{status: "Card empty", err: dispenser.ErrCardWellEmpty},
|
|
},
|
|
lockErr: encodingErr,
|
|
wantHTTP: http.StatusBadGateway,
|
|
wantMessage: encodingErr.Error(),
|
|
wantCalls: []string{"prepare current", "deliver current"},
|
|
wantLockSequence: 1,
|
|
},
|
|
}
|
|
|
|
for _, test := range tests {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
dispenser := test.dispenser
|
|
lock := &fakeDoorCardLockServer{sequenceErr: test.lockErr}
|
|
|
|
recorder, response, app := performIssueDoorCardRequest(t, &dispenser, lock)
|
|
|
|
if recorder.Code != test.wantHTTP {
|
|
t.Fatalf("HTTP status = %d, want %d", recorder.Code, test.wantHTTP)
|
|
}
|
|
if response.Code != test.wantHTTP {
|
|
t.Fatalf("response code = %d, want %d", response.Code, test.wantHTTP)
|
|
}
|
|
if response.Message != test.wantMessage {
|
|
t.Fatalf("response message = %q, want %q", response.Message, test.wantMessage)
|
|
}
|
|
if !reflect.DeepEqual(dispenser.calls, test.wantCalls) {
|
|
t.Fatalf("dispenser calls = %#v, want %#v", dispenser.calls, test.wantCalls)
|
|
}
|
|
if lock.sequenceCalls != test.wantLockSequence {
|
|
t.Fatalf("lock sequence calls = %d, want %d", lock.sequenceCalls, test.wantLockSequence)
|
|
}
|
|
if test.wantLockSequence > 0 && lock.buildCalls != 1 {
|
|
t.Fatalf("build command calls = %d, want 1", lock.buildCalls)
|
|
}
|
|
if test.wantLockSequence == 0 && lock.buildCalls != 0 {
|
|
t.Fatalf("build command calls = %d, want 0", lock.buildCalls)
|
|
}
|
|
if got := app.CardWellStatus(); got != test.wantCardWell {
|
|
t.Fatalf("card-well status = %q, want %q", got, test.wantCardWell)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
type responseTrackingRecorder struct {
|
|
*httptest.ResponseRecorder
|
|
wroteResponse bool
|
|
}
|
|
|
|
func (r *responseTrackingRecorder) WriteHeader(statusCode int) {
|
|
r.wroteResponse = true
|
|
r.ResponseRecorder.WriteHeader(statusCode)
|
|
}
|
|
|
|
func (r *responseTrackingRecorder) Write(body []byte) (int, error) {
|
|
r.wroteResponse = true
|
|
return r.ResponseRecorder.Write(body)
|
|
}
|
|
|
|
func TestIssueDoorCardDispatchesNextCardBeforeHTTP200(t *testing.T) {
|
|
var recorder *responseTrackingRecorder
|
|
dispatchCalled := false
|
|
dispenser := &fakeDoorCardDispenser{
|
|
beginNext: func() error {
|
|
dispatchCalled = true
|
|
if recorder.wroteResponse {
|
|
t.Error("HTTP response started before next-card preparation was dispatched")
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
lock := &fakeDoorCardLockServer{}
|
|
payload := lockserver.DoorCardRequest{
|
|
RoomField: "101",
|
|
CheckinTime: "2026-07-23 15:00:00 +0100",
|
|
CheckoutTime: "2026-07-24 11:00:00 +0100",
|
|
}
|
|
body, err := json.Marshal(payload)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
app := &App{disp: dispenser, lockserver: lock, cfg: &config.ConfigRec{}}
|
|
request := httptest.NewRequest(http.MethodPost, "/issuedoorcard", bytes.NewReader(body))
|
|
request.Header.Set("Content-Type", "application/json")
|
|
recorder = &responseTrackingRecorder{ResponseRecorder: httptest.NewRecorder()}
|
|
|
|
app.issueDoorCard(recorder, request)
|
|
|
|
if !dispatchCalled {
|
|
t.Fatal("next-card preparation was not dispatched")
|
|
}
|
|
if recorder.Code != http.StatusOK {
|
|
t.Fatalf("HTTP status = %d, want %d", recorder.Code, http.StatusOK)
|
|
}
|
|
}
|
|
|
|
func TestIssueDoorCardLogsNextCardDispatchFailureAndStillSucceeds(t *testing.T) {
|
|
var logOutput bytes.Buffer
|
|
standardLogger := log.StandardLogger()
|
|
previousOutput := standardLogger.Out
|
|
standardLogger.SetOutput(&logOutput)
|
|
t.Cleanup(func() {
|
|
standardLogger.SetOutput(previousOutput)
|
|
})
|
|
|
|
dispenser := &fakeDoorCardDispenser{beginNextErr: errors.New("dispatch failed")}
|
|
lock := &fakeDoorCardLockServer{}
|
|
recorder, _, _ := performIssueDoorCardRequest(t, dispenser, lock)
|
|
|
|
if recorder.Code != http.StatusOK {
|
|
t.Fatalf("HTTP status = %d, want %d", recorder.Code, http.StatusOK)
|
|
}
|
|
logged := logOutput.String()
|
|
if !strings.Contains(logged, "dispatch failed") ||
|
|
!strings.Contains(logged, "Next card preparation dispatch") {
|
|
t.Fatalf("dispatch failure log = %q", logged)
|
|
}
|
|
}
|
|
|
|
func TestIssueDoorCardLogsDeliveryFailureWithoutReplacingEncoderOutcome(t *testing.T) {
|
|
for _, encodingErr := range []error{nil, errors.New("original encoder failure")} {
|
|
var output bytes.Buffer
|
|
logger := log.StandardLogger()
|
|
previous := logger.Out
|
|
logger.SetOutput(&output)
|
|
d := &fakeDoorCardDispenser{deliverCurrent: dispenserCallResult{err: errors.New("FC0 dispatch failed")}}
|
|
lock := &fakeDoorCardLockServer{sequenceErr: encodingErr}
|
|
recorder, response, _ := performIssueDoorCardRequest(t, d, lock)
|
|
logger.SetOutput(previous)
|
|
wantHTTP := http.StatusOK
|
|
if encodingErr != nil {
|
|
wantHTTP = http.StatusBadGateway
|
|
}
|
|
if recorder.Code != wantHTTP {
|
|
t.Errorf("issueDoorCard(%v) HTTP = %d, want %d", encodingErr, recorder.Code, wantHTTP)
|
|
}
|
|
if encodingErr != nil && response.Message != encodingErr.Error() {
|
|
t.Errorf("issueDoorCard message = %q, want %q", response.Message, encodingErr.Error())
|
|
}
|
|
if !strings.Contains(output.String(), "FC0 dispatch failed") || !strings.Contains(output.String(), "Card delivery") {
|
|
t.Errorf("issueDoorCard delivery log = %q, want FC0 failure and Card delivery", output.String())
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestIssueDoorCardOnlyEmptyPreparationReturns503(t *testing.T) {
|
|
for _, failure := range []error{
|
|
dispenser.ErrCardWellEmpty, errors.Join(errors.New("wrapped"), dispenser.ErrCardWellEmpty),
|
|
dispenser.ErrPreparationExhausted, context.Canceled, context.DeadlineExceeded,
|
|
errors.New("malformed AP"), errors.New("truncated AP"), errors.New("no response"),
|
|
errors.New("serial read failed"), errors.New("serial write failed"), errors.New("FC7 dispatch failed"),
|
|
errors.New("RS dispatch failed"), errors.New(dispenser.CardWellEmptyMessage), errors.New("other preparation error"),
|
|
} {
|
|
d := &fakeDoorCardDispenser{prepareCurrent: dispenserCallResult{err: failure}}
|
|
lock := &fakeDoorCardLockServer{}
|
|
recorder, response, _ := performIssueDoorCardRequest(t, d, lock)
|
|
want := http.StatusBadGateway
|
|
if errors.Is(failure, dispenser.ErrCardWellEmpty) {
|
|
want = http.StatusServiceUnavailable
|
|
}
|
|
if recorder.Code != want || response.Code != want {
|
|
t.Errorf("preparation %v HTTP=%d body=%d, want %d", failure, recorder.Code, response.Code, want)
|
|
}
|
|
if lock.sequenceCalls != 0 || !reflect.DeepEqual(d.calls, []string{"prepare current"}) {
|
|
t.Errorf("preparation %v encoder=%d calls=%v, want no physical continuation", failure, lock.sequenceCalls, d.calls)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (d *fakeDoorCardDispenser) BeginForeground() func() {
|
|
d.activity++
|
|
d.registrations++
|
|
return func() { d.activity--; d.releases++ }
|
|
}
|
|
|
|
func TestDoorCardForegroundLifecycle(t *testing.T) {
|
|
for _, testEndpoint := range []bool{false, true} {
|
|
d := &fakeDoorCardDispenser{prepareCurrent: dispenserCallResult{err: errors.New("stop before encoding")}}
|
|
lock := &fakeDoorCardLockServer{}
|
|
_, _, app := performIssueDoorCardRequest(t, d, lock)
|
|
if d.registrations != 1 || d.releases != 1 || d.activity != 0 || d.outsideActivity {
|
|
t.Fatalf("issue registration=%d release=%d active=%d outside=%t", d.registrations, d.releases, d.activity, d.outsideActivity)
|
|
}
|
|
if testEndpoint {
|
|
req := httptest.NewRequest(http.MethodPost, "/testissuedoorcard", strings.NewReader("{}"))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
app.testIssueDoorCard(httptest.NewRecorder(), req)
|
|
if d.registrations != 2 || d.releases != 2 || d.activity != 0 || d.outsideActivity {
|
|
t.Errorf("test endpoint registration=%d release=%d active=%d outside=%t", d.registrations, d.releases, d.activity, d.outsideActivity)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|