diff --git a/cmd/hardlink/main.go b/cmd/hardlink/main.go index 89e3eca..d1622cc 100644 --- a/cmd/hardlink/main.go +++ b/cmd/hardlink/main.go @@ -33,7 +33,7 @@ import ( ) const ( - buildVersion = "v2.1.4" + buildVersion = "v2.1.5" serviceName = "hardlink" pollingFrequency = 8 * time.Second ) diff --git a/internal/dispenser/dispenserclient.go b/internal/dispenser/dispenserclient.go index 9a72232..c297e98 100644 --- a/internal/dispenser/dispenserclient.go +++ b/internal/dispenser/dispenserclient.go @@ -545,10 +545,24 @@ func (c *Client) waitForDeliveryClearance(ctx context.Context, operation string) return r.status, stock, nil } -func (c *Client) prepareCardAtEncoder(parent context.Context, operation string) (stock string, resultErr error) { +// PreparationResult carries this issuance attempt's handoff and recovery budget. +type PreparationResult struct { + Stock string + UncertainHandoff bool + ShakesUsed int + lastFC7 time.Time +} + +func (c *Client) prepareCardAtEncoder(ctx context.Context, operation string) (string, error) { + preparation, err := c.prepareCardForEncoding(ctx, operation) + return preparation.Stock, err +} + +func (c *Client) prepareCardForEncoding(parent context.Context, operation string) (preparation PreparationResult, resultErr error) { status, stock, err := c.waitForDeliveryClearance(parent, operation) + preparation.Stock = stock if err != nil { - return stock, err + return preparation, err } status = usableObservation(status, nil, operation) started := c.now() @@ -560,6 +574,13 @@ func (c *Client) prepareCardAtEncoder(parent context.Context, operation string) var lastFC7, uncertainSince time.Time var previous preparationClass defer func() { + preparation.Stock = stock + preparation.ShakesUsed = shakes + preparation.lastFC7 = lastFC7 + if resultErr == nil && !lastFC7.IsZero() { + class, _ := classifyPreparationStatus(status) + preparation.UncertainHandoff = class != encoderConfirmed + } log.Infof("[%s] preparation finished; stage=%s shakes=%d elapsed=%s raw status: % X error=%v", operation, stage, shakes, c.now().Sub(started), status, resultErr) }() checkDeadline := func() error { @@ -624,7 +645,7 @@ func (c *Client) prepareCardAtEncoder(parent context.Context, operation string) } for { if err := checkDeadline(); err != nil { - return stock, observationResult(err) + return preparation, observationResult(err) } class, _ := classifyPreparationStatus(status) // No class means unusable telemetry, sharing the uncertainty timer. @@ -634,41 +655,41 @@ func (c *Client) prepareCardAtEncoder(parent context.Context, operation string) switch class { case encoderConfirmed: stage = "encoder sensor handoff" - return stock, observationResult(checkDeadline()) + return preparation, observationResult(checkDeadline()) case positionWellEmpty: stage = "empty" - return stock, ErrCardWellEmpty + return preparation, ErrCardWellEmpty } if lastFC7.IsZero() { if err := sendFC7(); err != nil { - return stock, err + return preparation, err } } else if class == positionNoCard && c.now().Sub(lastFC7) >= sequenceShakeAfter { uncertainSince = time.Time{} if shakes == sequenceMaxShakes { stage = "three shakes exhausted" - return stock, ErrPreparationExhausted + return preparation, ErrPreparationExhausted } shakes++ stage = "RS dispatch" if err := checkDeadline(); err != nil { - return stock, err + return preparation, err } err := c.Reset(ctx) if deadlineErr := checkDeadline(); deadlineErr != nil { - return stock, deadlineErr + return preparation, deadlineErr } if err != nil { - return stock, fmt.Errorf("[%s] RS dispatch: %w", operation, err) + return preparation, fmt.Errorf("[%s] RS dispatch: %w", operation, err) } stage = "reset settling" log.Infof("[%s] RS dispatched; shake=%d settling=%s", operation, shakes, sequenceResetWait) if err := wait(sequenceResetWait); err != nil { - return stock, err + return preparation, err } log.Infof("[%s] reset settle wait completed; shake=%d", operation, shakes) if err := sendFC7(); err != nil { - return stock, err + return preparation, err } } else { if class == positionUncertain || class == "" { @@ -677,26 +698,26 @@ func (c *Client) prepareCardAtEncoder(parent context.Context, operation string) } if c.now().Sub(uncertainSince) >= sequenceUncertainWait { stage = "uncertain position handoff" - return stock, observationResult(checkDeadline()) + return preparation, observationResult(checkDeadline()) } } else { uncertainSince = time.Time{} } stage = "polling" if err := wait(sequencePollInterval); err != nil { - return stock, observationResult(err) + return preparation, observationResult(err) } } stage = "fresh AP" if err := checkDeadline(); err != nil { - return stock, observationResult(err) + return preparation, observationResult(err) } status, stock, err = c.readSequenceStatus(ctx, operation) if deadlineErr := checkDeadline(); deadlineErr != nil { - return stock, observationResult(deadlineErr) + return preparation, observationResult(deadlineErr) } if err != nil { - return stock, err + return preparation, err } } } @@ -706,6 +727,80 @@ func (c *Client) PrepareCurrentCard(ctx context.Context) (string, error) { return c.prepareCardAtEncoder(ctx, "PrepareCurrentCard") } +// PrepareCurrentCardForEncoding preserves preparation while exposing uncertain handoff. +func (c *Client) PrepareCurrentCardForEncoding(ctx context.Context) (PreparationResult, error) { + return c.prepareCardForEncoding(ctx, "PrepareCurrentCard") +} + +// RecoverCurrentCard spends only the remaining issuance budget during encoding. +// It must be cancelled and joined before delivery; all commands use the serial worker. +func (c *Client) RecoverCurrentCard(ctx context.Context, preparation PreparationResult) (resultErr error) { + if !preparation.UncertainHandoff { + return nil + } + const operation = "uncertain encoding recovery" + started := c.now() + shakes, lastFC7 := preparation.ShakesUsed, preparation.lastFC7 + reason := "recovery error" + defer func() { + if ctx.Err() != nil { + reason = context.Cause(ctx).Error() + } + log.Infof("[%s] stopped; reason=%s shakes=%d remaining=%d elapsed=%s error=%v", operation, reason, shakes, sequenceMaxShakes-shakes, c.now().Sub(started), resultErr) + }() + log.Infof("[%s] started; shakes=%d remaining=%d", operation, shakes, sequenceMaxShakes-shakes) + observe := func() (bool, error) { + status, _, err := c.readSequenceStatus(ctx, operation) + if err != nil { + return true, err + } + class, _ := classifyPreparationStatus(status) + log.Infof("[%s] fresh AP; class=%s shakes=%d remaining=%d raw status: % X", operation, class, shakes, sequenceMaxShakes-shakes, status) + switch class { + case encoderConfirmed: + reason = "encoder confirmed" + return true, nil + case positionWellEmpty: + reason = "card well empty" + return true, ErrCardWellEmpty + default: + return false, nil + } + } + for { + if stopped, err := observe(); stopped { + return err + } + if shakes >= sequenceMaxShakes { + reason = "shake budget exhausted" + return nil + } + if remaining := sequenceShakeAfter - c.now().Sub(lastFC7); remaining > 0 { + if err := c.sequenceTiming.wait(ctx, min(sequencePollInterval, remaining)); err != nil { + return err + } + continue + } + shakes++ + log.Infof("[%s] RS attempt; shake=%d remaining=%d", operation, shakes, sequenceMaxShakes-shakes) + if err := c.Reset(ctx); err != nil { + return fmt.Errorf("[%s] RS dispatch: %w", operation, err) + } + if err := c.sequenceTiming.wait(ctx, sequenceResetWait); err != nil { + return err + } + // A diagnostic AP cannot turn unusable telemetry into a fatal error. + if stopped, err := observe(); stopped { + return err + } + log.Infof("[%s] FC7 attempt; shake=%d remaining=%d", operation, shakes, sequenceMaxShakes-shakes) + if err := c.ToEncoder(ctx); err != nil { + return fmt.Errorf("[%s] FC7 dispatch: %w", operation, err) + } + lastFC7 = c.now() + } +} + // DeliverCurrentCard presents the encoded card and confirms command acceptance. func (c *Client) DeliverCurrentCard(ctx context.Context) (string, error) { const operation = "DeliverCurrentCard" diff --git a/internal/dispenser/dispenserclient_test.go b/internal/dispenser/dispenserclient_test.go index cafb3c9..ec748da 100644 --- a/internal/dispenser/dispenserclient_test.go +++ b/internal/dispenser/dispenserclient_test.go @@ -112,6 +112,154 @@ func TestResetPacket(t *testing.T) { } } +func TestUncertainRecoveryContinuesPreparationBudget(t *testing.T) { + responses := append(positionResponses(0x30, 5), positionResponses(0x35, 5)...) + responses = append(responses, cmdResp{status: status(0x35)}, cmdResp{err: errors.New("unusable diagnostic AP")}) + responses = append(responses, positionResponses(0x30, 4)...) + responses = append(responses, cmdResp{status: status(0x35)}, cmdResp{status: status(0x37)}) + c, d := newSequenceTestClient(t, responses...) + preparation, err := c.PrepareCurrentCardForEncoding(context.Background()) + if err != nil || !preparation.UncertainHandoff || preparation.ShakesUsed != 1 { + t.Fatalf("preparation=%+v error=%v, want uncertain handoff after one shake", preparation, err) + } + before := len(d.commands) + if err := c.RecoverCurrentCard(context.Background(), preparation); err != nil { + t.Fatal(err) + } + want := []cmdType{cmdStatus, cmdReset, cmdStatus, cmdToEncoder, cmdStatus, cmdStatus, cmdStatus, cmdStatus, cmdReset, cmdStatus, cmdToEncoder, cmdStatus} + if !reflect.DeepEqual(d.commands[before:], want) { + t.Errorf("recovery commands=%v, want %v", d.commands[before:], want) + } + if commandCount(d.commands, cmdReset) != 3 || commandCount(d.commands, cmdToEncoder) != 4 { + t.Errorf("whole issuance commands=%v, want three RS and four FC7", d.commands) + } + for i := before; i < len(d.commands); i++ { + if d.commands[i] == cmdToEncoder && d.commandTimes[i].Sub(d.commandTimes[i-2]) != sequenceResetWait { + t.Errorf("recovery FC7 at %d did not follow RS, settle and diagnostic AP: %v", i, d.commands) + } + } +} + +func TestUncertainRecoveryProductionTrace(t *testing.T) { + responses := []cmdResp{{status: status(0x30)}} + for i := 0; i < 5; i++ { + responses = append(responses, cmdResp{err: errors.New("AP unavailable")}) + } + responses = append(responses, cmdResp{status: status(0x35)}, cmdResp{status: status(0x35)}, cmdResp{status: status(0x37)}) + c, d := newSequenceTestClient(t, responses...) + preparation, err := c.PrepareCurrentCardForEncoding(context.Background()) + if err != nil || !preparation.UncertainHandoff || preparation.ShakesUsed != 0 { + t.Fatalf("production trace preparation=%+v error=%v, want uncertain handoff with unused budget", preparation, err) + } + if err := c.RecoverCurrentCard(context.Background(), preparation); err != nil { + t.Fatal(err) + } + if commandCount(d.commands, cmdReset) != 1 || commandCount(d.commands, cmdToEncoder) != 2 { + t.Errorf("production trace commands=%v, want one shake after initial FC7", d.commands) + } +} + +func TestUncertainRecoveryStopsAtPhysicalPosition(t *testing.T) { + for _, position := range []byte{0x32, 0x33, 0x37, 0x3F, 0x38} { + for _, afterReset := range []bool{false, true} { + t.Run(fmt.Sprintf("position=%X afterReset=%t", position, afterReset), func(t *testing.T) { + responses := []cmdResp{{status: status(position)}} + if afterReset { + responses = append([]cmdResp{{status: status(0x35)}}, responses...) + } + c, d := newSequenceTestClient(t, responses...) + err := c.RecoverCurrentCard(context.Background(), PreparationResult{UncertainHandoff: true}) + var wantErr error + if position == 0x38 { + wantErr = ErrCardWellEmpty + } + wantRS := 0 + if afterReset { + wantRS = 1 + } + if !errors.Is(err, wantErr) || commandCount(d.commands, cmdReset) != wantRS || commandCount(d.commands, cmdToEncoder) != 0 { + t.Errorf("position %X recovery error=%v commands=%v, want error=%v RS=%d FC7=0", position, err, d.commands, wantErr, wantRS) + } + }) + } + } +} + +func TestUncertainRecoveryExhaustsOnlyRemainingShakes(t *testing.T) { + for used := 0; used <= sequenceMaxShakes; used++ { + t.Run(fmt.Sprint(used), func(t *testing.T) { + c, d := newSequenceTestClient(t, positionResponses(0x35, 30)...) + preparation := PreparationResult{UncertainHandoff: true, ShakesUsed: used, lastFC7: c.now().Add(-sequenceShakeAfter)} + if err := c.RecoverCurrentCard(context.Background(), preparation); err != nil { + t.Fatal(err) + } + want := sequenceMaxShakes - used + if commandCount(d.commands, cmdReset) != want || commandCount(d.commands, cmdToEncoder) != want { + t.Errorf("used=%d commands=%v, want %d RS/FC7", used, d.commands, want) + } + }) + } +} + +func TestUncertainRecoveryPreservesFC7ObservationDelay(t *testing.T) { + c, d := newSequenceTestClient(t, positionResponses(0x35, 4)...) + d.statusResponses = append(d.statusResponses, cmdResp{status: status(0x37)}) + started := c.now() + if err := c.RecoverCurrentCard(context.Background(), PreparationResult{UncertainHandoff: true, lastFC7: started}); err != nil { + t.Fatal(err) + } + if commandCount(d.commands, cmdReset) != 1 || d.commandTimes[4].Sub(started) != sequenceShakeAfter { + t.Errorf("commands=%v times=%v, want first RS after three seconds", d.commands, d.commandTimes) + } +} + +func TestUncertainRecoveryCommandFailuresAndCancellation(t *testing.T) { + for _, command := range []cmdType{cmdReset, cmdToEncoder} { + c, d := newSequenceTestClient(t, positionResponses(0x35, 3)...) + failure := errors.New("recovery dispatch failed") + d.commandErrors[command] = []error{failure} + if err := c.RecoverCurrentCard(context.Background(), PreparationResult{UncertainHandoff: true}); !errors.Is(err, failure) { + t.Errorf("command=%v error=%v, want %v", command, err, failure) + } + if commandCount(d.commands, command) != 1 { + t.Errorf("failed command=%v commands=%v, want one attempt", command, d.commands) + } + } + c, d := newSequenceTestClient(t, cmdResp{status: status(0x35)}) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + c.sequenceTiming.wait = func(ctx context.Context, duration time.Duration) error { + if duration != sequenceResetWait { + t.Errorf("wait=%s, want reset settle", duration) + } + cancel() + return ctx.Err() + } + if err := c.RecoverCurrentCard(ctx, PreparationResult{UncertainHandoff: true}); !errors.Is(err, context.Canceled) { + t.Errorf("settle cancellation=%v, want context.Canceled", err) + } + if !reflect.DeepEqual(d.commands, []cmdType{cmdStatus, cmdReset}) { + t.Errorf("cancelled commands=%v, want AP/RS only", d.commands) + } + if err := c.RecoverCurrentCard(ctx, PreparationResult{UncertainHandoff: true}); !errors.Is(err, context.Canceled) { + t.Errorf("already cancelled recovery=%v, want context.Canceled", err) + } +} + +func TestConfirmedPreparationNeverRecovers(t *testing.T) { + c, d := newSequenceTestClient(t, cmdResp{status: status(0x37)}) + preparation, err := c.PrepareCurrentCardForEncoding(context.Background()) + if err != nil || preparation.UncertainHandoff { + t.Fatalf("confirmed preparation=%+v error=%v", preparation, err) + } + if err := c.RecoverCurrentCard(context.Background(), preparation); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(d.commands, []cmdType{cmdStatus}) { + t.Errorf("confirmed commands=%v, want initial AP only", d.commands) + } +} + func TestDeliverCurrentCardSucceedsAfterCommandAcceptanceWithoutStatusPolling(t *testing.T) { staleStatus := []byte{0x30, 0x32, 0x32, 0x33} client, device := newSequenceTestClient(t, cmdResp{status: staleStatus}) diff --git a/internal/handlers/doorcard_handlers_test.go b/internal/handlers/doorcard_handlers_test.go index e0fe71b..2670d66 100644 --- a/internal/handlers/doorcard_handlers_test.go +++ b/internal/handlers/doorcard_handlers_test.go @@ -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) + } +} diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go index cbf75dd..e029170 100644 --- a/internal/handlers/handlers.go +++ b/internal/handlers/handlers.go @@ -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) } diff --git a/release notes.md b/release notes.md index dc872a3..329ef6f 100644 --- a/release notes.md +++ b/release notes.md @@ -2,6 +2,9 @@ builtVersion is a const in main.go +#### v2.1.5 - 22 October 2026 +feat(dispenser): recover K720 card position during uncertain encoding + #### v2.1.4 - 19 October 2026 added detailed logging for preauth payment processing and result streaming