Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c5e61efd0 | ||
|
|
28aea4aab2 | ||
|
|
8a5325414b |
@@ -33,7 +33,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
buildVersion = "v2.1.2"
|
buildVersion = "v2.1.5"
|
||||||
serviceName = "hardlink"
|
serviceName = "hardlink"
|
||||||
pollingFrequency = 8 * time.Second
|
pollingFrequency = 8 * time.Second
|
||||||
)
|
)
|
||||||
|
|||||||
+1
-1
@@ -89,7 +89,7 @@ func InsertPreauth(ctx context.Context, db *sql.DB, m map[string]string, checkou
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("InsertPreauth: parsing checkoutDate %q: %w", checkoutDate, err)
|
return fmt.Errorf("InsertPreauth: parsing checkoutDate %q: %w", checkoutDate, err)
|
||||||
}
|
}
|
||||||
releaseDate := checkOutDate.Add(48 * time.Hour)
|
releaseDate := checkOutDate.Add(96 * time.Hour)
|
||||||
|
|
||||||
const stmt = `
|
const stmt = `
|
||||||
INSERT INTO dbo.Preauthorizations
|
INSERT INTO dbo.Preauthorizations
|
||||||
|
|||||||
@@ -545,10 +545,24 @@ func (c *Client) waitForDeliveryClearance(ctx context.Context, operation string)
|
|||||||
return r.status, stock, nil
|
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)
|
status, stock, err := c.waitForDeliveryClearance(parent, operation)
|
||||||
|
preparation.Stock = stock
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return stock, err
|
return preparation, err
|
||||||
}
|
}
|
||||||
status = usableObservation(status, nil, operation)
|
status = usableObservation(status, nil, operation)
|
||||||
started := c.now()
|
started := c.now()
|
||||||
@@ -560,6 +574,13 @@ func (c *Client) prepareCardAtEncoder(parent context.Context, operation string)
|
|||||||
var lastFC7, uncertainSince time.Time
|
var lastFC7, uncertainSince time.Time
|
||||||
var previous preparationClass
|
var previous preparationClass
|
||||||
defer func() {
|
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)
|
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 {
|
checkDeadline := func() error {
|
||||||
@@ -624,7 +645,7 @@ func (c *Client) prepareCardAtEncoder(parent context.Context, operation string)
|
|||||||
}
|
}
|
||||||
for {
|
for {
|
||||||
if err := checkDeadline(); err != nil {
|
if err := checkDeadline(); err != nil {
|
||||||
return stock, observationResult(err)
|
return preparation, observationResult(err)
|
||||||
}
|
}
|
||||||
class, _ := classifyPreparationStatus(status)
|
class, _ := classifyPreparationStatus(status)
|
||||||
// No class means unusable telemetry, sharing the uncertainty timer.
|
// No class means unusable telemetry, sharing the uncertainty timer.
|
||||||
@@ -634,41 +655,41 @@ func (c *Client) prepareCardAtEncoder(parent context.Context, operation string)
|
|||||||
switch class {
|
switch class {
|
||||||
case encoderConfirmed:
|
case encoderConfirmed:
|
||||||
stage = "encoder sensor handoff"
|
stage = "encoder sensor handoff"
|
||||||
return stock, observationResult(checkDeadline())
|
return preparation, observationResult(checkDeadline())
|
||||||
case positionWellEmpty:
|
case positionWellEmpty:
|
||||||
stage = "empty"
|
stage = "empty"
|
||||||
return stock, ErrCardWellEmpty
|
return preparation, ErrCardWellEmpty
|
||||||
}
|
}
|
||||||
if lastFC7.IsZero() {
|
if lastFC7.IsZero() {
|
||||||
if err := sendFC7(); err != nil {
|
if err := sendFC7(); err != nil {
|
||||||
return stock, err
|
return preparation, err
|
||||||
}
|
}
|
||||||
} else if class == positionNoCard && c.now().Sub(lastFC7) >= sequenceShakeAfter {
|
} else if class == positionNoCard && c.now().Sub(lastFC7) >= sequenceShakeAfter {
|
||||||
uncertainSince = time.Time{}
|
uncertainSince = time.Time{}
|
||||||
if shakes == sequenceMaxShakes {
|
if shakes == sequenceMaxShakes {
|
||||||
stage = "three shakes exhausted"
|
stage = "three shakes exhausted"
|
||||||
return stock, ErrPreparationExhausted
|
return preparation, ErrPreparationExhausted
|
||||||
}
|
}
|
||||||
shakes++
|
shakes++
|
||||||
stage = "RS dispatch"
|
stage = "RS dispatch"
|
||||||
if err := checkDeadline(); err != nil {
|
if err := checkDeadline(); err != nil {
|
||||||
return stock, err
|
return preparation, err
|
||||||
}
|
}
|
||||||
err := c.Reset(ctx)
|
err := c.Reset(ctx)
|
||||||
if deadlineErr := checkDeadline(); deadlineErr != nil {
|
if deadlineErr := checkDeadline(); deadlineErr != nil {
|
||||||
return stock, deadlineErr
|
return preparation, deadlineErr
|
||||||
}
|
}
|
||||||
if err != nil {
|
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"
|
stage = "reset settling"
|
||||||
log.Infof("[%s] RS dispatched; shake=%d settling=%s", operation, shakes, sequenceResetWait)
|
log.Infof("[%s] RS dispatched; shake=%d settling=%s", operation, shakes, sequenceResetWait)
|
||||||
if err := wait(sequenceResetWait); err != nil {
|
if err := wait(sequenceResetWait); err != nil {
|
||||||
return stock, err
|
return preparation, err
|
||||||
}
|
}
|
||||||
log.Infof("[%s] reset settle wait completed; shake=%d", operation, shakes)
|
log.Infof("[%s] reset settle wait completed; shake=%d", operation, shakes)
|
||||||
if err := sendFC7(); err != nil {
|
if err := sendFC7(); err != nil {
|
||||||
return stock, err
|
return preparation, err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if class == positionUncertain || class == "" {
|
if class == positionUncertain || class == "" {
|
||||||
@@ -677,26 +698,26 @@ func (c *Client) prepareCardAtEncoder(parent context.Context, operation string)
|
|||||||
}
|
}
|
||||||
if c.now().Sub(uncertainSince) >= sequenceUncertainWait {
|
if c.now().Sub(uncertainSince) >= sequenceUncertainWait {
|
||||||
stage = "uncertain position handoff"
|
stage = "uncertain position handoff"
|
||||||
return stock, observationResult(checkDeadline())
|
return preparation, observationResult(checkDeadline())
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
uncertainSince = time.Time{}
|
uncertainSince = time.Time{}
|
||||||
}
|
}
|
||||||
stage = "polling"
|
stage = "polling"
|
||||||
if err := wait(sequencePollInterval); err != nil {
|
if err := wait(sequencePollInterval); err != nil {
|
||||||
return stock, observationResult(err)
|
return preparation, observationResult(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
stage = "fresh AP"
|
stage = "fresh AP"
|
||||||
if err := checkDeadline(); err != nil {
|
if err := checkDeadline(); err != nil {
|
||||||
return stock, observationResult(err)
|
return preparation, observationResult(err)
|
||||||
}
|
}
|
||||||
status, stock, err = c.readSequenceStatus(ctx, operation)
|
status, stock, err = c.readSequenceStatus(ctx, operation)
|
||||||
if deadlineErr := checkDeadline(); deadlineErr != nil {
|
if deadlineErr := checkDeadline(); deadlineErr != nil {
|
||||||
return stock, observationResult(deadlineErr)
|
return preparation, observationResult(deadlineErr)
|
||||||
}
|
}
|
||||||
if err != nil {
|
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")
|
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.
|
// DeliverCurrentCard presents the encoded card and confirms command acceptance.
|
||||||
func (c *Client) DeliverCurrentCard(ctx context.Context) (string, error) {
|
func (c *Client) DeliverCurrentCard(ctx context.Context) (string, error) {
|
||||||
const operation = "DeliverCurrentCard"
|
const operation = "DeliverCurrentCard"
|
||||||
|
|||||||
@@ -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) {
|
func TestDeliverCurrentCardSucceedsAfterCommandAcceptanceWithoutStatusPolling(t *testing.T) {
|
||||||
staleStatus := []byte{0x30, 0x32, 0x32, 0x33}
|
staleStatus := []byte{0x30, 0x32, 0x32, 0x33}
|
||||||
client, device := newSequenceTestClient(t, cmdResp{status: staleStatus})
|
client, device := newSequenceTestClient(t, cmdResp{status: staleStatus})
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall"
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall"
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||||
"gitea.futuresens.co.uk/futuresens/logging"
|
"gitea.futuresens.co.uk/futuresens/logging"
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
type creditCallPreauthRequest struct {
|
type creditCallPreauthRequest struct {
|
||||||
@@ -25,6 +26,11 @@ func (app *App) streamCreditCallPreauth(w http.ResponseWriter, r *http.Request)
|
|||||||
func (app *App) executeCreditCallPreauth(ctx context.Context, request cmstypes.TransactionRec,
|
func (app *App) executeCreditCallPreauth(ctx context.Context, request cmstypes.TransactionRec,
|
||||||
start func(*http.Client) (creditcall.TransactionResultXML, error)) creditCallSaleOutcome {
|
start func(*http.Client) (creditcall.TransactionResultXML, error)) creditCallSaleOutcome {
|
||||||
const op = logging.Op("takePreauthorization")
|
const op = logging.Op("takePreauthorization")
|
||||||
|
entry := log.WithFields(log.Fields{
|
||||||
|
"operation": "preauth", "hotel": app.cfg.Hotel, "kiosk": app.cfg.Kiosk,
|
||||||
|
"requestedType": request.TransactionType, "requestedAmount": request.AmountMinorUnits,
|
||||||
|
})
|
||||||
|
entry.Info("CreditCall PREAUTH started")
|
||||||
outcome := creditCallSaleOutcome{
|
outcome := creditCallSaleOutcome{
|
||||||
HTTPStatus: http.StatusBadGateway,
|
HTTPStatus: http.StatusBadGateway,
|
||||||
Status: cmstypes.StatusRec{Code: http.StatusInternalServerError, Message: "500 Internal server error"},
|
Status: cmstypes.StatusRec{Code: http.StatusInternalServerError, Message: "500 Internal server error"},
|
||||||
@@ -32,14 +38,32 @@ func (app *App) executeCreditCallPreauth(ctx context.Context, request cmstypes.T
|
|||||||
transaction, err := start(app.creditCallClient())
|
transaction, err := start(app.creditCallClient())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Error(types.ServiceName, err.Error(), "Preauth processing error", string(op), "", "", 0)
|
logging.Error(types.ServiceName, err.Error(), "Preauth processing error", string(op), "", "", 0)
|
||||||
|
entry.Error("CreditCall PREAUTH ended without a processor result")
|
||||||
outcome.FailureType = types.ResultError
|
outcome.FailureType = types.ResultError
|
||||||
outcome.FailureDescription = "No response from payment processor"
|
outcome.FailureDescription = "No response from payment processor"
|
||||||
return outcome
|
return outcome
|
||||||
}
|
}
|
||||||
var result creditcall.PaymentResult
|
var result creditcall.PaymentResult
|
||||||
result.FillFromTransactionResult(transaction)
|
result.FillFromTransactionResult(transaction)
|
||||||
|
entry = entry.WithFields(log.Fields{
|
||||||
|
"reference": result.Fields[types.Reference],
|
||||||
|
"transactionResult": result.Fields[types.TransactionResult],
|
||||||
|
"transactionType": result.Fields[types.TransactionType],
|
||||||
|
"totalAmount": result.Fields[types.TotalAmount],
|
||||||
|
"receiptPresent": result.CardholderReceipt != "",
|
||||||
|
})
|
||||||
|
entry.Info("CreditCall PREAUTH processor result received")
|
||||||
|
if result.Fields[types.TransactionType] == "" {
|
||||||
|
entry.Warn("CreditCall PREAUTH result has no TRANSACTION_TYPE")
|
||||||
|
}
|
||||||
app.printCreditCallReceipt(result.CardholderReceipt)
|
app.printCreditCallReceipt(result.CardholderReceipt)
|
||||||
approved, persist := creditcall.PreauthDecision(result.Fields)
|
approved, persist := creditcall.PreauthDecision(result.Fields)
|
||||||
|
decision := entry.WithFields(log.Fields{"approved": approved, "persist": persist})
|
||||||
|
if approved {
|
||||||
|
decision.Info("CreditCall PREAUTH decision")
|
||||||
|
} else {
|
||||||
|
decision.Warn("CreditCall PREAUTH decision")
|
||||||
|
}
|
||||||
outcome.HTTPStatus = http.StatusOK
|
outcome.HTTPStatus = http.StatusOK
|
||||||
outcome.Status = result.Status
|
outcome.Status = result.Status
|
||||||
outcome.Payment = result
|
outcome.Payment = result
|
||||||
@@ -47,6 +71,10 @@ func (app *App) executeCreditCallPreauth(ctx context.Context, request cmstypes.T
|
|||||||
outcome.FailureType = result.Fields[types.TransactionResult]
|
outcome.FailureType = result.Fields[types.TransactionResult]
|
||||||
outcome.FailureDescription = result.Fields[types.Errors]
|
outcome.FailureDescription = result.Fields[types.Errors]
|
||||||
if persist {
|
if persist {
|
||||||
|
if result.Fields[types.TotalAmount] == "" {
|
||||||
|
entry.Warn("CreditCall PREAUTH persistence requested without TOTAL_AMOUNT")
|
||||||
|
}
|
||||||
|
entry.Info("CreditCall PREAUTH persistence scheduled")
|
||||||
go app.persistPreauth(ctx, result.Fields, request.CheckoutDate)
|
go app.persistPreauth(ctx, result.Fields, request.CheckoutDate)
|
||||||
}
|
}
|
||||||
return outcome
|
return outcome
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
logtest "github.com/sirupsen/logrus/hooks/test"
|
||||||
|
)
|
||||||
|
|
||||||
|
func capturePreauthLogs(t *testing.T) *logtest.Hook {
|
||||||
|
t.Helper()
|
||||||
|
logger := log.StandardLogger()
|
||||||
|
previousHooks := logger.ReplaceHooks(make(log.LevelHooks))
|
||||||
|
previousLevel := logger.GetLevel()
|
||||||
|
logger.SetLevel(log.InfoLevel)
|
||||||
|
hook := logtest.NewGlobal()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
logger.ReplaceHooks(previousHooks)
|
||||||
|
logger.SetLevel(previousLevel)
|
||||||
|
})
|
||||||
|
return hook
|
||||||
|
}
|
||||||
|
|
||||||
|
func requirePreauthLog(t *testing.T, hook *logtest.Hook, message string, level log.Level) *log.Entry {
|
||||||
|
t.Helper()
|
||||||
|
for _, entry := range hook.AllEntries() {
|
||||||
|
if entry.Message == message {
|
||||||
|
if entry.Level != level {
|
||||||
|
t.Errorf("log %q level=%v, want %v", message, entry.Level, level)
|
||||||
|
}
|
||||||
|
return entry
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("missing log %q", message)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallPreauthDecisionLogging(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, result, kind string
|
||||||
|
approved bool
|
||||||
|
level log.Level
|
||||||
|
}{
|
||||||
|
{"verification", "APPROVED", "ACCOUNT VERIFICATION", true, log.InfoLevel},
|
||||||
|
{"missing type", "APPROVED", "", false, log.WarnLevel},
|
||||||
|
{"declined", "DECLINED", "SALE", false, log.WarnLevel},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
hook := capturePreauthLogs(t)
|
||||||
|
app := &App{cfg: &config.ConfigRec{}, creditCallReceipt: func(string) {}}
|
||||||
|
outcome := app.executeCreditCallPreauth(context.Background(), cmstypes.TransactionRec{TransactionType: "AccountVerification"},
|
||||||
|
func(*http.Client) (creditcall.TransactionResultXML, error) {
|
||||||
|
return creditcall.TransactionResultXML{Entries: []creditcall.EntryXML{
|
||||||
|
{Key: types.TransactionResult, Value: tc.result},
|
||||||
|
{Key: types.TransactionType, Value: tc.kind},
|
||||||
|
{Key: types.Reference, Value: "log-test-ref"},
|
||||||
|
{Key: types.PanMasked, Value: "sensitive-card-sentinel"},
|
||||||
|
{Key: types.CardHash, Value: "sensitive-hash-sentinel"},
|
||||||
|
{Key: types.ReceiptDataCardholder, Value: "sensitive-receipt-sentinel"},
|
||||||
|
}}, nil
|
||||||
|
})
|
||||||
|
if outcome.Approved != tc.approved {
|
||||||
|
t.Errorf("approved=%t, want %t", outcome.Approved, tc.approved)
|
||||||
|
}
|
||||||
|
requirePreauthLog(t, hook, "CreditCall PREAUTH started", log.InfoLevel)
|
||||||
|
provider := requirePreauthLog(t, hook, "CreditCall PREAUTH processor result received", log.InfoLevel)
|
||||||
|
if provider.Data["transactionType"] != tc.kind || provider.Data["transactionResult"] != tc.result || provider.Data["receiptPresent"] != true {
|
||||||
|
t.Errorf("provider log=%v, want type=%q result=%q receiptPresent=true", provider.Data, tc.kind, tc.result)
|
||||||
|
}
|
||||||
|
decision := requirePreauthLog(t, hook, "CreditCall PREAUTH decision", tc.level)
|
||||||
|
if decision.Data["approved"] != tc.approved || decision.Data["persist"] != false || decision.Data["reference"] != "log-test-ref" {
|
||||||
|
t.Errorf("decision log=%v, want approved=%t persist=false reference=log-test-ref", decision.Data, tc.approved)
|
||||||
|
}
|
||||||
|
if tc.kind == "" {
|
||||||
|
requirePreauthLog(t, hook, "CreditCall PREAUTH result has no TRANSACTION_TYPE", log.WarnLevel)
|
||||||
|
}
|
||||||
|
for _, entry := range hook.AllEntries() {
|
||||||
|
for key, value := range entry.Data {
|
||||||
|
if value == "sensitive-card-sentinel" || value == "sensitive-hash-sentinel" || value == "sensitive-receipt-sentinel" {
|
||||||
|
t.Errorf("log %q exposed sensitive field %q", entry.Message, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if entry.Message == "CreditCall PREAUTH persistence scheduled" {
|
||||||
|
t.Error("non-persisting result logged persistence scheduling")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallPreauthStartFailureLogging(t *testing.T) {
|
||||||
|
hook := capturePreauthLogs(t)
|
||||||
|
app := &App{cfg: &config.ConfigRec{}}
|
||||||
|
outcome := app.executeCreditCallPreauth(context.Background(), cmstypes.TransactionRec{},
|
||||||
|
func(*http.Client) (creditcall.TransactionResultXML, error) {
|
||||||
|
return creditcall.TransactionResultXML{}, errors.New("test transport failure")
|
||||||
|
})
|
||||||
|
if outcome.HTTPStatus != http.StatusBadGateway {
|
||||||
|
t.Errorf("HTTPStatus=%d, want 502", outcome.HTTPStatus)
|
||||||
|
}
|
||||||
|
requirePreauthLog(t, hook, "CreditCall PREAUTH started", log.InfoLevel)
|
||||||
|
requirePreauthLog(t, hook, "CreditCall PREAUTH ended without a processor result", log.ErrorLevel)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreditCallPreauthPersistenceLogging(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, amount, message string
|
||||||
|
level log.Level
|
||||||
|
breakSpool bool
|
||||||
|
}{
|
||||||
|
{"SQL", "3100", "CreditCall PREAUTH SQL persistence completed", log.InfoLevel, false},
|
||||||
|
{"spool", "", "CreditCall PREAUTH saved to spool; SQL persistence pending", log.WarnLevel, false},
|
||||||
|
{"spool failure", "", "failed to spool preauth", log.ErrorLevel, true},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
hook := capturePreauthLogs(t)
|
||||||
|
app := &App{cfg: &config.ConfigRec{}}
|
||||||
|
preauthTestDatabase(t, app)
|
||||||
|
if tc.breakSpool {
|
||||||
|
path := filepath.Join(app.cfg.LogDir, "not-a-directory")
|
||||||
|
if err := os.WriteFile(path, nil, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
app.cfg.LogDir = path
|
||||||
|
}
|
||||||
|
app.persistPreauth(context.Background(), map[string]string{
|
||||||
|
types.Reference: "persist-test-ref", types.TotalAmount: tc.amount,
|
||||||
|
}, "2026-10-21 00:00:00 +0000")
|
||||||
|
entry := requirePreauthLog(t, hook, tc.message, tc.level)
|
||||||
|
if entry.Data["reference"] != "persist-test-ref" || entry.Data["operation"] != "preauth" {
|
||||||
|
t.Errorf("persistence log=%v, want reference=persist-test-ref operation=preauth", entry.Data)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/db"
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/db"
|
||||||
|
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -74,18 +75,23 @@ func (app *App) spoolPath() string {
|
|||||||
// It never returns an error to the caller (so your HTTP flow stays simple),
|
// It never returns an error to the caller (so your HTTP flow stays simple),
|
||||||
// but it logs failures.
|
// but it logs failures.
|
||||||
func (app *App) persistPreauth(ctx context.Context, fields map[string]string, checkoutDate string) {
|
func (app *App) persistPreauth(ctx context.Context, fields map[string]string, checkoutDate string) {
|
||||||
|
entry := log.WithFields(log.Fields{
|
||||||
|
"operation": "preauth", "reference": fields[types.Reference],
|
||||||
|
"hotel": app.cfg.Hotel, "kiosk": app.cfg.Kiosk,
|
||||||
|
})
|
||||||
// First, try DB (with your reconnect logic inside getDB)
|
// First, try DB (with your reconnect logic inside getDB)
|
||||||
dbConn, err := app.getDB(ctx)
|
dbConn, err := app.getDB(ctx)
|
||||||
if err == nil && dbConn != nil {
|
if err == nil && dbConn != nil {
|
||||||
if err := db.InsertPreauth(ctx, dbConn, fields, checkoutDate); err == nil {
|
if err := db.InsertPreauth(ctx, dbConn, fields, checkoutDate); err == nil {
|
||||||
|
entry.Info("CreditCall PREAUTH SQL persistence completed")
|
||||||
// opportunistic drain once DB is alive
|
// opportunistic drain once DB is alive
|
||||||
go app.drainPreauthSpool(context.Background())
|
go app.drainPreauthSpool(context.Background())
|
||||||
return
|
return
|
||||||
} else {
|
} else {
|
||||||
log.WithError(err).Warn("DB insert failed; will spool preauth")
|
entry.WithError(err).Warn("DB insert failed; will spool preauth")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.WithError(err).Warn("DB unavailable; will spool preauth")
|
entry.WithError(err).Warn("DB unavailable; will spool preauth")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback: spool to file
|
// Fallback: spool to file
|
||||||
@@ -95,7 +101,9 @@ func (app *App) persistPreauth(ctx context.Context, fields map[string]string, ch
|
|||||||
Fields: fields,
|
Fields: fields,
|
||||||
}
|
}
|
||||||
if spErr := app.spoolPreauth(rec); spErr != nil {
|
if spErr := app.spoolPreauth(rec); spErr != nil {
|
||||||
log.WithError(spErr).Error("failed to spool preauth")
|
entry.WithError(spErr).Error("failed to spool preauth")
|
||||||
|
} else {
|
||||||
|
entry.Warn("CreditCall PREAUTH saved to spool; SQL persistence pending")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -25,6 +27,10 @@ type dispenserCallResult struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type fakeDoorCardDispenser struct {
|
type fakeDoorCardDispenser struct {
|
||||||
|
preparation dispenser.PreparationResult
|
||||||
|
recoverCurrent func(context.Context, dispenser.PreparationResult) error
|
||||||
|
deliver func()
|
||||||
|
|
||||||
prepareCurrent dispenserCallResult
|
prepareCurrent dispenserCallResult
|
||||||
deliverCurrent dispenserCallResult
|
deliverCurrent dispenserCallResult
|
||||||
beginNextErr error
|
beginNextErr error
|
||||||
@@ -45,8 +51,25 @@ func (d *fakeDoorCardDispenser) PrepareCurrentCard(context.Context) (string, err
|
|||||||
return d.prepareCurrent.status, d.prepareCurrent.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) {
|
func (d *fakeDoorCardDispenser) DeliverCurrentCard(context.Context) (string, error) {
|
||||||
d.calls = append(d.calls, "deliver current")
|
d.calls = append(d.calls, "deliver current")
|
||||||
|
if d.deliver != nil {
|
||||||
|
d.deliver()
|
||||||
|
}
|
||||||
return d.deliverCurrent.status, d.deliverCurrent.err
|
return d.deliverCurrent.status, d.deliverCurrent.err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,6 +87,8 @@ func (d *fakeDoorCardDispenser) PrepareNextCard(context.Context) (string, error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
type fakeDoorCardLockServer struct {
|
type fakeDoorCardLockServer struct {
|
||||||
|
sequence func() error
|
||||||
|
|
||||||
sequenceErr error
|
sequenceErr error
|
||||||
buildCalls int
|
buildCalls int
|
||||||
sequenceCalls int
|
sequenceCalls int
|
||||||
@@ -76,6 +101,9 @@ func (l *fakeDoorCardLockServer) BuildCommand(lockserver.DoorCardRequest, time.T
|
|||||||
|
|
||||||
func (l *fakeDoorCardLockServer) LockSequence() error {
|
func (l *fakeDoorCardLockServer) LockSequence() error {
|
||||||
l.sequenceCalls++
|
l.sequenceCalls++
|
||||||
|
if l.sequence != nil {
|
||||||
|
return l.sequence()
|
||||||
|
}
|
||||||
return l.sequenceErr
|
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 {
|
type doorCardDispenser interface {
|
||||||
BeginForeground() func()
|
BeginForeground() func()
|
||||||
PrepareCurrentCard(context.Context) (string, error)
|
PrepareCurrentCard(context.Context) (string, error)
|
||||||
|
PrepareCurrentCardForEncoding(context.Context) (dispenser.PreparationResult, error)
|
||||||
|
RecoverCurrentCard(context.Context, dispenser.PreparationResult) error
|
||||||
DeliverCurrentCard(context.Context) (string, error)
|
DeliverCurrentCard(context.Context) (string, error)
|
||||||
BeginPrepareNextCard(context.Context) error
|
BeginPrepareNextCard(context.Context) error
|
||||||
PrepareNextCard(context.Context) (string, error)
|
PrepareNextCard(context.Context) (string, error)
|
||||||
@@ -294,8 +296,8 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
|||||||
release := app.disp.BeginForeground()
|
release := app.disp.BeginForeground()
|
||||||
defer release()
|
defer release()
|
||||||
|
|
||||||
status, err := app.disp.PrepareCurrentCard(r.Context())
|
preparation, err := app.disp.PrepareCurrentCardForEncoding(r.Context())
|
||||||
app.SetCardWellStatus(status)
|
app.SetCardWellStatus(preparation.Stock)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Error(types.ServiceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
logging.Error(types.ServiceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
||||||
if errors.Is(err, dispenser.ErrCardWellEmpty) {
|
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.
|
// Each request performs at most one encoder operation.
|
||||||
encodingStarted := time.Now()
|
encodingStarted := time.Now()
|
||||||
log.Info("LockSequence started")
|
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()
|
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))
|
log.Infof("LockSequence finished; success=%t duration=%s", encodingErr == nil, time.Since(encodingStarted))
|
||||||
|
if recoveryDone != nil {
|
||||||
|
<-recoveryDone
|
||||||
|
}
|
||||||
if encodingErr != nil {
|
if encodingErr != nil {
|
||||||
logging.Error(types.ServiceName, encodingErr.Error(), "Key encoding", string(op), "", "", 0)
|
logging.Error(types.ServiceName, encodingErr.Error(), "Key encoding", string(op), "", "", 0)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,17 +2,22 @@ package logging
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
// setupLogging ensures log directory, opens log file, and configures logrus.
|
// SetupLogging ensures the log directory, opens the rotating log writer, and configures logrus.
|
||||||
// Returns the *os.File so caller can defer its Close().
|
func SetupLogging(logDir, serviceName, buildVersion string) (io.WriteCloser, error) {
|
||||||
func SetupLogging(logDir, serviceName, buildVersion string) (*os.File, error) {
|
if err := os.MkdirAll(logDir, 0o755); err != nil {
|
||||||
fileName := logDir + serviceName + ".log"
|
return nil, fmt.Errorf("create log directory: %w", err)
|
||||||
f, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
|
}
|
||||||
|
|
||||||
|
fileName := filepath.Join(logDir, serviceName+".log")
|
||||||
|
f, err := newWeeklyLogWriter(fileName, time.Local, defaultWeeklyLogRuntime())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("open log file: %w", err)
|
return nil, fmt.Errorf("open log file: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,319 @@
|
|||||||
|
package logging
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
_ "time/tzdata"
|
||||||
|
)
|
||||||
|
|
||||||
|
const weeklyLogRetention = 13
|
||||||
|
|
||||||
|
type logRotationTimer interface {
|
||||||
|
C() <-chan time.Time
|
||||||
|
Stop() bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type realLogRotationTimer struct {
|
||||||
|
*time.Timer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t realLogRotationTimer) C() <-chan time.Time {
|
||||||
|
return t.Timer.C
|
||||||
|
}
|
||||||
|
|
||||||
|
type weeklyLogRuntime struct {
|
||||||
|
now func() time.Time
|
||||||
|
newTimer func(time.Duration) logRotationTimer
|
||||||
|
rename func(string, string) error
|
||||||
|
diagnostic io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultWeeklyLogRuntime() weeklyLogRuntime {
|
||||||
|
return weeklyLogRuntime{
|
||||||
|
now: time.Now,
|
||||||
|
newTimer: func(duration time.Duration) logRotationTimer {
|
||||||
|
return realLogRotationTimer{Timer: time.NewTimer(duration)}
|
||||||
|
},
|
||||||
|
rename: os.Rename,
|
||||||
|
diagnostic: os.Stderr,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type weeklyLogWriter struct {
|
||||||
|
path string
|
||||||
|
location *time.Location
|
||||||
|
now func() time.Time
|
||||||
|
newTimer func(time.Duration) logRotationTimer
|
||||||
|
rename func(string, string) error
|
||||||
|
diagnostic io.Writer
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
file *os.File
|
||||||
|
weekStart time.Time
|
||||||
|
closed bool
|
||||||
|
stop chan struct{}
|
||||||
|
done chan struct{}
|
||||||
|
closeOnce sync.Once
|
||||||
|
closeErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
func newWeeklyLogWriter(path string, location *time.Location, runtime weeklyLogRuntime) (*weeklyLogWriter, error) {
|
||||||
|
if location == nil {
|
||||||
|
location = time.Local
|
||||||
|
}
|
||||||
|
if runtime.now == nil {
|
||||||
|
runtime.now = time.Now
|
||||||
|
}
|
||||||
|
if runtime.newTimer == nil {
|
||||||
|
runtime.newTimer = defaultWeeklyLogRuntime().newTimer
|
||||||
|
}
|
||||||
|
if runtime.rename == nil {
|
||||||
|
runtime.rename = os.Rename
|
||||||
|
}
|
||||||
|
if runtime.diagnostic == nil {
|
||||||
|
runtime.diagnostic = os.Stderr
|
||||||
|
}
|
||||||
|
|
||||||
|
now := runtime.now().In(location)
|
||||||
|
weekStart := logWeekStart(now, location)
|
||||||
|
if info, err := os.Stat(path); err == nil {
|
||||||
|
weekStart = logWeekStart(info.ModTime(), location)
|
||||||
|
} else if !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil, fmt.Errorf("inspect active log: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o666)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
writer := &weeklyLogWriter{
|
||||||
|
path: path,
|
||||||
|
location: location,
|
||||||
|
now: runtime.now,
|
||||||
|
newTimer: runtime.newTimer,
|
||||||
|
rename: runtime.rename,
|
||||||
|
diagnostic: runtime.diagnostic,
|
||||||
|
file: file,
|
||||||
|
weekStart: weekStart,
|
||||||
|
stop: make(chan struct{}),
|
||||||
|
done: make(chan struct{}),
|
||||||
|
}
|
||||||
|
writer.rotateIfNeeded(now)
|
||||||
|
go writer.run()
|
||||||
|
return writer, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) Write(data []byte) (int, error) {
|
||||||
|
now := w.now().In(w.location)
|
||||||
|
w.mu.Lock()
|
||||||
|
rotationErr := w.rotateIfNeededLocked(now)
|
||||||
|
if w.closed || w.file == nil {
|
||||||
|
w.mu.Unlock()
|
||||||
|
w.reportRotationError(rotationErr)
|
||||||
|
return 0, os.ErrClosed
|
||||||
|
}
|
||||||
|
n, writeErr := w.file.Write(data)
|
||||||
|
w.mu.Unlock()
|
||||||
|
w.reportRotationError(rotationErr)
|
||||||
|
return n, writeErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) Close() error {
|
||||||
|
w.closeOnce.Do(func() {
|
||||||
|
close(w.stop)
|
||||||
|
<-w.done
|
||||||
|
|
||||||
|
w.mu.Lock()
|
||||||
|
w.closed = true
|
||||||
|
if w.file != nil {
|
||||||
|
w.closeErr = w.file.Close()
|
||||||
|
w.file = nil
|
||||||
|
}
|
||||||
|
w.mu.Unlock()
|
||||||
|
})
|
||||||
|
return w.closeErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) run() {
|
||||||
|
defer close(w.done)
|
||||||
|
for {
|
||||||
|
now := w.now().In(w.location)
|
||||||
|
next := nextLogWeekStart(now, w.location)
|
||||||
|
duration := next.Sub(now)
|
||||||
|
if duration <= 0 {
|
||||||
|
duration = time.Nanosecond
|
||||||
|
}
|
||||||
|
timer := w.newTimer(duration)
|
||||||
|
select {
|
||||||
|
case <-timer.C():
|
||||||
|
w.rotateIfNeeded(w.now().In(w.location))
|
||||||
|
case <-w.stop:
|
||||||
|
timer.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) rotateIfNeeded(now time.Time) {
|
||||||
|
w.mu.Lock()
|
||||||
|
err := w.rotateIfNeededLocked(now)
|
||||||
|
w.mu.Unlock()
|
||||||
|
w.reportRotationError(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) rotateIfNeededLocked(now time.Time) error {
|
||||||
|
if w.closed {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
targetWeek := logWeekStart(now, w.location)
|
||||||
|
if !targetWeek.After(w.weekStart) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record the attempted week even if rotation fails so every write in a
|
||||||
|
// broken environment does not retry and emit another diagnostic.
|
||||||
|
w.weekStart = targetWeek
|
||||||
|
return w.rotateLocked()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) rotateLocked() error {
|
||||||
|
if w.file == nil {
|
||||||
|
return fmt.Errorf("active log file is unavailable")
|
||||||
|
}
|
||||||
|
if err := w.file.Close(); err != nil {
|
||||||
|
w.file = nil
|
||||||
|
return errors.Join(fmt.Errorf("close active log: %w", err), w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
w.file = nil
|
||||||
|
|
||||||
|
if err := w.cleanupOlderGenerationsLocked(); err != nil {
|
||||||
|
return errors.Join(err, w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
if err := removeIfExists(w.generationPath(weeklyLogRetention)); err != nil {
|
||||||
|
return errors.Join(fmt.Errorf("remove oldest weekly log: %w", err), w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
for generation := weeklyLogRetention - 1; generation >= 1; generation-- {
|
||||||
|
source := w.generationPath(generation)
|
||||||
|
if _, err := os.Stat(source); err != nil {
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return errors.Join(fmt.Errorf("inspect weekly log generation %d: %w", generation, err), w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
if err := w.rename(source, w.generationPath(generation+1)); err != nil {
|
||||||
|
return errors.Join(fmt.Errorf("shift weekly log generation %d: %w", generation, err), w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
activeRenamed := false
|
||||||
|
if _, err := os.Stat(w.path); err == nil {
|
||||||
|
if err := w.rename(w.path, w.generationPath(1)); err != nil {
|
||||||
|
return errors.Join(fmt.Errorf("archive active log: %w", err), w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
activeRenamed = true
|
||||||
|
} else if !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return errors.Join(fmt.Errorf("inspect active log: %w", err), w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := os.OpenFile(w.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o666)
|
||||||
|
if err == nil {
|
||||||
|
w.file = file
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
rotationErr := fmt.Errorf("open new active log: %w", err)
|
||||||
|
if activeRenamed {
|
||||||
|
if rollbackErr := w.rename(w.generationPath(1), w.path); rollbackErr != nil {
|
||||||
|
rotationErr = errors.Join(rotationErr, fmt.Errorf("restore archived active log: %w", rollbackErr))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errors.Join(rotationErr, w.reopenActiveLocked())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) cleanupOlderGenerationsLocked() error {
|
||||||
|
directory := filepath.Dir(w.path)
|
||||||
|
entries, err := os.ReadDir(directory)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("list weekly log directory: %w", err)
|
||||||
|
}
|
||||||
|
base := filepath.Base(w.path)
|
||||||
|
extension := filepath.Ext(base)
|
||||||
|
stem := strings.TrimSuffix(base, extension)
|
||||||
|
prefix := stem + "."
|
||||||
|
|
||||||
|
for _, entry := range entries {
|
||||||
|
if entry.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
name := entry.Name()
|
||||||
|
if !strings.HasPrefix(name, prefix) || !strings.HasSuffix(name, extension) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
generationText := strings.TrimSuffix(strings.TrimPrefix(name, prefix), extension)
|
||||||
|
generation, err := strconv.Atoi(generationText)
|
||||||
|
if err != nil || generation <= weeklyLogRetention {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := os.Remove(filepath.Join(directory, name)); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return fmt.Errorf("remove weekly log generation %d: %w", generation, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) reopenActiveLocked() error {
|
||||||
|
file, err := os.OpenFile(w.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o666)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("reopen active log: %w", err)
|
||||||
|
}
|
||||||
|
w.file = file
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) generationPath(generation int) string {
|
||||||
|
extension := filepath.Ext(w.path)
|
||||||
|
stem := strings.TrimSuffix(w.path, extension)
|
||||||
|
return fmt.Sprintf("%s.%d%s", stem, generation, extension)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *weeklyLogWriter) reportRotationError(err error) {
|
||||||
|
if err == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
slog.New(slog.NewJSONHandler(w.diagnostic, nil)).Warn(
|
||||||
|
"weekly log rotation failed",
|
||||||
|
"module", "logging",
|
||||||
|
"action", "weekly_log_rotation_failed",
|
||||||
|
"path", w.path,
|
||||||
|
"error.message", err.Error(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func logWeekStart(value time.Time, location *time.Location) time.Time {
|
||||||
|
local := value.In(location)
|
||||||
|
daysSinceMonday := (int(local.Weekday()) + 6) % 7
|
||||||
|
monday := local.AddDate(0, 0, -daysSinceMonday)
|
||||||
|
return time.Date(monday.Year(), monday.Month(), monday.Day(), 0, 0, 0, 0, location)
|
||||||
|
}
|
||||||
|
|
||||||
|
func nextLogWeekStart(value time.Time, location *time.Location) time.Time {
|
||||||
|
return logWeekStart(value, location).AddDate(0, 0, 7)
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeIfExists(path string) error {
|
||||||
|
err := os.Remove(path)
|
||||||
|
if errors.Is(err, fs.ErrNotExist) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,387 @@
|
|||||||
|
package logging
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWeeklyLogRotationShiftsAndRetainsExactGenerations(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
writeLogTestFile(t, path, "active")
|
||||||
|
for generation := 1; generation <= 14; generation++ {
|
||||||
|
writeLogTestFile(t, weeklyLogTestGeneration(path, generation), fmt.Sprintf("generation-%d", generation))
|
||||||
|
}
|
||||||
|
writeLogTestFile(t, weeklyLogTestGeneration(path, 19), "generation-19")
|
||||||
|
for name, contents := range map[string]string{
|
||||||
|
"hardlink.backup.14.log": "related-looking backup",
|
||||||
|
"another.14.log": "unrelated log",
|
||||||
|
"hardlink.14.log.bak": "different extension",
|
||||||
|
} {
|
||||||
|
writeLogTestFile(t, filepath.Join(directory, name), contents)
|
||||||
|
}
|
||||||
|
|
||||||
|
sunday := time.Date(2026, time.August, 9, 12, 0, 0, 0, time.UTC)
|
||||||
|
setLogTestModTime(t, path, sunday)
|
||||||
|
writer := newLogTestWriter(t, path, sunday, weeklyLogRuntime{})
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.August, 10, 0, 0, 0, 0, time.UTC))
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
requireLogTestContents(t, path, "")
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 1), "active")
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 2), "generation-1")
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 13), "generation-12")
|
||||||
|
for _, generation := range []int{14, 19} {
|
||||||
|
if _, err := os.Stat(weeklyLogTestGeneration(path, generation)); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Errorf("generation %d exists after rotation, want removed: %v", generation, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name, contents := range map[string]string{
|
||||||
|
"hardlink.backup.14.log": "related-looking backup",
|
||||||
|
"another.14.log": "unrelated log",
|
||||||
|
"hardlink.14.log.bak": "different extension",
|
||||||
|
} {
|
||||||
|
requireLogTestContents(t, filepath.Join(directory, name), contents)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWeeklyLogRotationOccursOncePerWeek(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
writeLogTestFile(t, path, "week-zero\n")
|
||||||
|
sunday := time.Date(2026, time.January, 4, 18, 0, 0, 0, time.UTC)
|
||||||
|
setLogTestModTime(t, path, sunday)
|
||||||
|
writer := newLogTestWriter(t, path, sunday, weeklyLogRuntime{})
|
||||||
|
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.January, 4, 23, 59, 59, 0, time.UTC))
|
||||||
|
if _, err := os.Stat(weeklyLogTestGeneration(path, 1)); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatalf("rotation before Monday: %v, want no generation", err)
|
||||||
|
}
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.January, 5, 0, 0, 0, 0, time.UTC))
|
||||||
|
if _, err := writer.Write([]byte("week-one\n")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.January, 6, 12, 0, 0, 0, time.UTC))
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 1), "week-zero\n")
|
||||||
|
requireLogTestContents(t, path, "week-one\n")
|
||||||
|
if _, err := os.Stat(weeklyLogTestGeneration(path, 2)); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Errorf("same-week rotation created generation 2: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWeeklyLogStartupRotatesOnceAfterSeveralMissedWeeks(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
writeLogTestFile(t, path, "old active")
|
||||||
|
writeLogTestFile(t, weeklyLogTestGeneration(path, 1), "older history")
|
||||||
|
setLogTestModTime(t, path, time.Date(2026, time.January, 5, 12, 0, 0, 0, time.UTC))
|
||||||
|
|
||||||
|
now := time.Date(2026, time.February, 23, 9, 0, 0, 0, time.UTC)
|
||||||
|
writer := newLogTestWriter(t, path, now, weeklyLogRuntime{})
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 1), "old active")
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 2), "older history")
|
||||||
|
if _, err := os.Stat(weeklyLogTestGeneration(path, 3)); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Errorf("missed weeks created generation 3: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWeeklyLogSchedulerUsesLocalMondayBoundary(t *testing.T) {
|
||||||
|
location, err := time.LoadLocation("Europe/London")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
writeLogTestFile(t, path, "sunday")
|
||||||
|
sunday := time.Date(2026, time.March, 29, 0, 0, 0, 0, location)
|
||||||
|
setLogTestModTime(t, path, sunday)
|
||||||
|
|
||||||
|
clock := &atomic.Pointer[time.Time]{}
|
||||||
|
clock.Store(&sunday)
|
||||||
|
created := make(chan *logTestTimer, 2)
|
||||||
|
rotated := make(chan struct{})
|
||||||
|
runtime := weeklyLogRuntime{
|
||||||
|
now: func() time.Time { return *clock.Load() },
|
||||||
|
newTimer: func(duration time.Duration) logRotationTimer {
|
||||||
|
timer := &logTestTimer{duration: duration, ch: make(chan time.Time, 1)}
|
||||||
|
created <- timer
|
||||||
|
return timer
|
||||||
|
},
|
||||||
|
rename: func(oldPath, newPath string) error {
|
||||||
|
err := os.Rename(oldPath, newPath)
|
||||||
|
if oldPath == path && err == nil {
|
||||||
|
close(rotated)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
},
|
||||||
|
}
|
||||||
|
writer, err := newWeeklyLogWriter(path, location, runtime)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
timer := <-created
|
||||||
|
if timer.duration != 23*time.Hour {
|
||||||
|
t.Fatalf("timer duration = %v, want 23h across DST boundary", timer.duration)
|
||||||
|
}
|
||||||
|
monday := time.Date(2026, time.March, 30, 0, 0, 0, 0, location)
|
||||||
|
clock.Store(&monday)
|
||||||
|
timer.ch <- monday
|
||||||
|
<-rotated
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
requireLogTestContents(t, weeklyLogTestGeneration(path, 1), "sunday")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWeeklyLogConcurrentWritesRemainCompleteAcrossRotation(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
sunday := time.Date(2026, time.August, 9, 12, 0, 0, 0, time.UTC)
|
||||||
|
writer := newLogTestWriter(t, path, sunday, weeklyLogRuntime{})
|
||||||
|
|
||||||
|
const goroutines = 8
|
||||||
|
const recordsPerGoroutine = 100
|
||||||
|
writeErrors := make(chan error, goroutines)
|
||||||
|
var writers sync.WaitGroup
|
||||||
|
writers.Add(goroutines)
|
||||||
|
for worker := 0; worker < goroutines; worker++ {
|
||||||
|
go func() {
|
||||||
|
defer writers.Done()
|
||||||
|
for record := 0; record < recordsPerGoroutine; record++ {
|
||||||
|
if _, err := writer.Write([]byte(fmt.Sprintf("%d:%d\n", worker, record))); err != nil {
|
||||||
|
writeErrors <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.August, 10, 0, 0, 0, 0, time.UTC))
|
||||||
|
writers.Wait()
|
||||||
|
close(writeErrors)
|
||||||
|
for err := range writeErrors {
|
||||||
|
t.Errorf("weeklyLogWriter.Write() error = %v, want nil", err)
|
||||||
|
}
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
contents := readLogTestFile(t, weeklyLogTestGeneration(path, 1)) + readLogTestFile(t, path)
|
||||||
|
lines := strings.Split(strings.TrimSpace(contents), "\n")
|
||||||
|
if len(lines) != goroutines*recordsPerGoroutine {
|
||||||
|
t.Fatalf("record count = %d, want %d", len(lines), goroutines*recordsPerGoroutine)
|
||||||
|
}
|
||||||
|
seen := make(map[string]bool, len(lines))
|
||||||
|
for _, line := range lines {
|
||||||
|
if _, _, ok := strings.Cut(line, ":"); !ok {
|
||||||
|
t.Fatalf("record %q has no separator", line)
|
||||||
|
}
|
||||||
|
seen[line] = true
|
||||||
|
}
|
||||||
|
if len(seen) != goroutines*recordsPerGoroutine {
|
||||||
|
t.Errorf("unique record count = %d, want %d", len(seen), goroutines*recordsPerGoroutine)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWeeklyLogCloseWaitsForRotationAndIsIdempotent(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
writeLogTestFile(t, path, "active")
|
||||||
|
sunday := time.Date(2026, time.August, 9, 12, 0, 0, 0, time.UTC)
|
||||||
|
setLogTestModTime(t, path, sunday)
|
||||||
|
started := make(chan struct{})
|
||||||
|
release := make(chan struct{})
|
||||||
|
runtime := weeklyLogRuntime{rename: func(oldPath, newPath string) error {
|
||||||
|
if oldPath == path {
|
||||||
|
close(started)
|
||||||
|
<-release
|
||||||
|
}
|
||||||
|
return os.Rename(oldPath, newPath)
|
||||||
|
}}
|
||||||
|
writer := newLogTestWriter(t, path, sunday, runtime)
|
||||||
|
rotationDone := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.August, 10, 0, 0, 0, 0, time.UTC))
|
||||||
|
close(rotationDone)
|
||||||
|
}()
|
||||||
|
<-started
|
||||||
|
|
||||||
|
closeDone := make(chan error, 1)
|
||||||
|
go func() { closeDone <- writer.Close() }()
|
||||||
|
select {
|
||||||
|
case err := <-closeDone:
|
||||||
|
t.Fatalf("weeklyLogWriter.Close() during rotation returned %v, want blocked", err)
|
||||||
|
case <-time.After(20 * time.Millisecond):
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
<-rotationDone
|
||||||
|
if err := <-closeDone; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Errorf("second weeklyLogWriter.Close() error = %v, want nil", err)
|
||||||
|
}
|
||||||
|
if _, err := writer.Write([]byte("after close")); !errors.Is(err, os.ErrClosed) {
|
||||||
|
t.Errorf("weeklyLogWriter.Write() after close error = %v, want os.ErrClosed", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWeeklyLogRotationFailureIsNonRecursiveAndPreservesWrites(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "hardlink.log")
|
||||||
|
writeLogTestFile(t, path, "before\n")
|
||||||
|
sunday := time.Date(2026, time.August, 9, 12, 0, 0, 0, time.UTC)
|
||||||
|
setLogTestModTime(t, path, sunday)
|
||||||
|
var diagnostics bytes.Buffer
|
||||||
|
runtime := weeklyLogRuntime{
|
||||||
|
rename: func(oldPath, newPath string) error {
|
||||||
|
if oldPath == path {
|
||||||
|
return errors.New("injected rename failure")
|
||||||
|
}
|
||||||
|
return os.Rename(oldPath, newPath)
|
||||||
|
},
|
||||||
|
diagnostic: &diagnostics,
|
||||||
|
}
|
||||||
|
writer := newLogTestWriter(t, path, sunday, runtime)
|
||||||
|
writer.rotateIfNeeded(time.Date(2026, time.August, 10, 0, 0, 0, 0, time.UTC))
|
||||||
|
if _, err := writer.Write([]byte("after\n")); err != nil {
|
||||||
|
t.Fatalf("weeklyLogWriter.Write() after failed rotation error = %v, want nil", err)
|
||||||
|
}
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
requireLogTestContents(t, path, "before\nafter\n")
|
||||||
|
if !strings.Contains(diagnostics.String(), "weekly_log_rotation_failed") || !strings.Contains(diagnostics.String(), "injected rename failure") {
|
||||||
|
t.Errorf("rotation diagnostic = %q, want action and injected error", diagnostics.String())
|
||||||
|
}
|
||||||
|
if strings.Contains(readLogTestFile(t, path), "weekly log rotation failed") {
|
||||||
|
t.Error("rotation diagnostic recursively entered active log")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetupLoggingKeepsFilenameAndJSONFormat(t *testing.T) {
|
||||||
|
logger := log.StandardLogger()
|
||||||
|
previousOutput := logger.Out
|
||||||
|
previousFormatter := logger.Formatter
|
||||||
|
previousLevel := logger.Level
|
||||||
|
t.Cleanup(func() {
|
||||||
|
logger.SetOutput(previousOutput)
|
||||||
|
logger.SetFormatter(previousFormatter)
|
||||||
|
logger.SetLevel(previousLevel)
|
||||||
|
})
|
||||||
|
|
||||||
|
directory := filepath.Join(t.TempDir(), "nested", "logs")
|
||||||
|
writer, err := SetupLogging(directory, "hardlink", "v-test")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
log.WithField("probe", "value").Info("test record")
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
contents := readLogTestFile(t, filepath.Join(directory, "hardlink.log"))
|
||||||
|
for _, want := range []string{`"buildVersion":"v-test"`, `"msg":"Logging initialized"`, `"probe":"value"`, `"msg":"test record"`} {
|
||||||
|
if !strings.Contains(contents, want) {
|
||||||
|
t.Errorf("hardlink.log contents missing %q: %s", want, contents)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(directory, "hardlink.1.log")); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Errorf("SetupLogging() created archive during current week: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type logTestTimer struct {
|
||||||
|
duration time.Duration
|
||||||
|
ch chan time.Time
|
||||||
|
stopped atomic.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *logTestTimer) C() <-chan time.Time {
|
||||||
|
return t.ch
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *logTestTimer) Stop() bool {
|
||||||
|
return !t.stopped.Swap(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newLogTestWriter(t *testing.T, path string, now time.Time, overrides weeklyLogRuntime) *weeklyLogWriter {
|
||||||
|
t.Helper()
|
||||||
|
runtime := defaultWeeklyLogRuntime()
|
||||||
|
runtime.now = func() time.Time { return now }
|
||||||
|
if overrides.now != nil {
|
||||||
|
runtime.now = overrides.now
|
||||||
|
}
|
||||||
|
if overrides.newTimer != nil {
|
||||||
|
runtime.newTimer = overrides.newTimer
|
||||||
|
}
|
||||||
|
if overrides.rename != nil {
|
||||||
|
runtime.rename = overrides.rename
|
||||||
|
}
|
||||||
|
if overrides.diagnostic != nil {
|
||||||
|
runtime.diagnostic = overrides.diagnostic
|
||||||
|
}
|
||||||
|
writer, err := newWeeklyLogWriter(path, now.Location(), runtime)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return writer
|
||||||
|
}
|
||||||
|
|
||||||
|
func weeklyLogTestGeneration(path string, generation int) string {
|
||||||
|
extension := filepath.Ext(path)
|
||||||
|
return fmt.Sprintf("%s.%d%s", strings.TrimSuffix(path, extension), generation, extension)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeLogTestFile(t *testing.T, path, contents string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func setLogTestModTime(t *testing.T, path string, value time.Time) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.Chtimes(path, value, value); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readLogTestFile(t *testing.T, path string) string {
|
||||||
|
t.Helper()
|
||||||
|
contents, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(contents)
|
||||||
|
}
|
||||||
|
|
||||||
|
func requireLogTestContents(t *testing.T, path, want string) {
|
||||||
|
t.Helper()
|
||||||
|
if got := readLogTestFile(t, path); got != want {
|
||||||
|
t.Errorf("%s contents = %q, want %q", filepath.Base(path), got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ io.WriteCloser = (*weeklyLogWriter)(nil)
|
||||||
@@ -2,6 +2,15 @@
|
|||||||
|
|
||||||
builtVersion is a const in main.go
|
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
|
||||||
|
|
||||||
|
#### v2.1.3 - 30 September 2026
|
||||||
|
feat(logging): add weekly log rotation and retention
|
||||||
|
|
||||||
#### v2.1.2 - 30 September 2026
|
#### v2.1.2 - 30 September 2026
|
||||||
fix(dispenser): scan ACK responses without assuming 3-byte reads
|
fix(dispenser): scan ACK responses without assuming 3-byte reads
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user