From 3aae843011891bc915cf954526f7a627f139416b Mon Sep 17 00:00:00 2001 From: yurii Date: Thu, 5 Nov 2026 14:28:31 +0000 Subject: [PATCH] fix(creditcall): restore SDK timeout and cancellation classification --- cmd/hardlink/main.go | 2 +- internal/handlers/creditcall_processor.go | 79 +++- internal/handlers/creditcall_sale_test.go | 2 +- internal/handlers/creditcall_timeout_test.go | 369 +++++++++++++++++++ docs/releases.md => release notes.md | 5 +- 5 files changed, 444 insertions(+), 13 deletions(-) create mode 100644 internal/handlers/creditcall_timeout_test.go rename docs/releases.md => release notes.md (98%) diff --git a/cmd/hardlink/main.go b/cmd/hardlink/main.go index 88d7912..6b636ea 100644 --- a/cmd/hardlink/main.go +++ b/cmd/hardlink/main.go @@ -33,7 +33,7 @@ import ( ) const ( - buildVersion = "v2.2.1" + buildVersion = "v2.2.2" serviceName = "hardlink" pollingFrequency = 8 * time.Second ) diff --git a/internal/handlers/creditcall_processor.go b/internal/handlers/creditcall_processor.go index babfc73..da3ae33 100644 --- a/internal/handlers/creditcall_processor.go +++ b/internal/handlers/creditcall_processor.go @@ -16,6 +16,22 @@ import ( // creditCallProcessor delegates to the unchanged legacy execution/finalization core. type creditCallProcessor struct{ app *App } +type creditCallInitialKind uint8 + +const ( + creditCallInitialUnknown creditCallInitialKind = iota + creditCallInitialApproved + creditCallInitialDeclined + creditCallInitialCancelled + creditCallInitialTimeout +) + +// creditCallInitialResult describes only the completed initial SDK response. +type creditCallInitialResult struct { + kind creditCallInitialKind + reason string +} + func (*creditCallProcessor) ValidatePreauth(req paymentsvc.SaleRequest) error { if req.Amount < 0 { return paymentsvc.ErrPreauthUnsupported @@ -34,12 +50,17 @@ func (p *creditCallProcessor) run(ctx context.Context, req paymentsvc.SaleReques transaction.AmountMinorUnits = "" transaction.TransactionType = "AccountVerification" } + var initial creditCallInitialResult start := func(client *http.Client) (creditcall.TransactionResultXML, error) { - return callChipDNATransactionStream(context.WithoutCancel(ctx), client, transaction, func(code string) { + result, err := callChipDNATransactionStream(context.WithoutCancel(ctx), client, transaction, func(code string) { if status != nil { status(paymentsvc.StatusUpdate{Code: code}) } }) + if err == nil { + initial = classifyCreditCallInitialResult(result) + } + return result, err } var outcome creditCallSaleOutcome if preauth { @@ -48,7 +69,7 @@ func (p *creditCallProcessor) run(ctx context.Context, req paymentsvc.SaleReques } else { outcome = p.app.executeCreditCallSale(transaction, start) } - final := outcome.streamResult() + final := outcome.streamResult(initial) final.AmountMinor, final.CurrencyCode = req.Amount, req.Currency if outcome.Approved { if raw := outcome.Payment.Fields[types.TotalAmount]; raw != "" { @@ -66,7 +87,37 @@ func (p *creditCallProcessor) run(ctx context.Context, req paymentsvc.SaleReques return &paymentsvc.Result{Terminal: final}, nil } -func (outcome creditCallSaleOutcome) streamResult() paymentapi.Result { +func classifyCreditCallInitialResult(result creditcall.TransactionResultXML) creditCallInitialResult { + var transactionResult, sdkError string + for _, entry := range result.Entries { + switch entry.Key { + case types.TransactionResult: + transactionResult = entry.Value + case types.Errors: + sdkError = entry.Value + } + } + transactionResult = strings.ToLower(transactionResult) + switch transactionResult { + case types.ResultApproved: + return creditCallInitialResult{kind: creditCallInitialApproved} + case "cancelled", "canceled": + return creditCallInitialResult{kind: creditCallInitialCancelled} + case "", types.ResultError, types.ResultDeclined: + switch sdkError { + case "CardHolderActionTimedOut": + return creditCallInitialResult{kind: creditCallInitialTimeout, reason: "cardholder_timeout"} + case "PinPadUserCancelled": + return creditCallInitialResult{kind: creditCallInitialCancelled, reason: "user_cancelled"} + } + if transactionResult == types.ResultDeclined { + return creditCallInitialResult{kind: creditCallInitialDeclined} + } + } + return creditCallInitialResult{} +} + +func (outcome creditCallSaleOutcome) streamResult(initial creditCallInitialResult) paymentapi.Result { final := paymentapi.Result{Outcome: "unknown", HTTPStatus: outcome.HTTPStatus, Provider: "creditcall", Message: "Payment outcome uncertain; contact reception"} if final.HTTPStatus == 0 { final.HTTPStatus = http.StatusOK @@ -79,13 +130,21 @@ func (outcome creditCallSaleOutcome) streamResult() paymentapi.Result { final.MaskedCardNumber = creditcall.MaskedCardNumber(fields[types.PanMasked]) final.ExpiryDate = fields[types.ExpiryDate] final.CardHash, final.CardReference = fields[types.CardHash], fields[types.CardReference] - } else { - switch strings.ToLower(outcome.FailureType) { - case "declined": - final.Outcome, final.Retryable, final.Message = "declined", true, "Transaction declined" - case "cancelled", "canceled": - final.Outcome, final.Retryable, final.Message = "cancelled", true, "Transaction cancelled" - } + return final + } + // Initial approval followed by unsuccessful confirmation must not permit another charge. + if initial.kind == creditCallInitialApproved { + return final + } + switch initial.kind { + case creditCallInitialDeclined: + final.Outcome, final.Retryable, final.Message = "declined", true, "Transaction declined" + case creditCallInitialCancelled: + final.Outcome, final.Retryable = "cancelled", true + final.Reason, final.Message = initial.reason, "Transaction cancelled" + case creditCallInitialTimeout: + final.Outcome, final.Retryable = "timeout", true + final.Reason, final.Message = initial.reason, "Cardholder action timed out" } return final } diff --git a/internal/handlers/creditcall_sale_test.go b/internal/handlers/creditcall_sale_test.go index 2a4f53c..a996bb5 100644 --- a/internal/handlers/creditcall_sale_test.go +++ b/internal/handlers/creditcall_sale_test.go @@ -84,7 +84,7 @@ func TestCreditCallStructuredFieldsExcludeRawData(t *testing.T) { result := (creditCallSaleOutcome{Approved: true, Payment: creditcall.PaymentResult{Fields: map[string]string{ types.Reference: "ref", types.PanMasked: "1234567890123456", types.CardHash: "hash", types.CardReference: "card-ref", "PAN": "pan-secret", "CVV": "cvv-secret", "PIN": "pin-secret", "TRACK_DATA": "track-secret", types.ReceiptDataCardholder: "receipt-secret", - }}}).streamResult() + }}}).streamResult(creditCallInitialResult{kind: creditCallInitialApproved}) body, err := json.Marshal(result) if err != nil { t.Fatal(err) diff --git a/internal/handlers/creditcall_timeout_test.go b/internal/handlers/creditcall_timeout_test.go new file mode 100644 index 0000000..e6c5656 --- /dev/null +++ b/internal/handlers/creditcall_timeout_test.go @@ -0,0 +1,369 @@ +package handlers + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync/atomic" + "testing" + + "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall" + "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/types" +) + +func TestClassifyCreditCallInitialResult(t *testing.T) { + for _, tc := range []struct { + name, result, sdkError string + want creditCallInitialResult + }{ + {name: "empty", want: creditCallInitialResult{kind: creditCallInitialUnknown}}, + {name: "approval wins over cancellation error", result: "APPROVED", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{kind: creditCallInitialApproved}}, + {name: "mixed-case approval wins over timeout", result: "Approved", sdkError: "CardHolderActionTimedOut", want: creditCallInitialResult{kind: creditCallInitialApproved}}, + {name: "ordinary decline", result: "DECLINED", sdkError: "InsufficientFunds", want: creditCallInitialResult{kind: creditCallInitialDeclined}}, + {name: "declined cancellation", result: "DECLINED", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{kind: creditCallInitialCancelled, reason: "user_cancelled"}}, + {name: "declined cardholder timeout", result: "DECLINED", sdkError: "CardHolderActionTimedOut", want: creditCallInitialResult{kind: creditCallInitialTimeout, reason: "cardholder_timeout"}}, + {name: "explicit cancellation", result: "CANCELLED", want: creditCallInitialResult{kind: creditCallInitialCancelled}}, + {name: "alternate cancellation spelling", result: "Canceled", want: creditCallInitialResult{kind: creditCallInitialCancelled}}, + {name: "SDK timeout", result: "ERROR", sdkError: "CardHolderActionTimedOut", want: creditCallInitialResult{kind: creditCallInitialTimeout, reason: "cardholder_timeout"}}, + {name: "SDK cancellation", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{kind: creditCallInitialCancelled, reason: "user_cancelled"}}, + {name: "CLI wait expiry with SDK timeout", result: "TIMEOUT", sdkError: "CardHolderActionTimedOut", want: creditCallInitialResult{}}, + {name: "CLI wait expiry with SDK cancellation", result: "TIMEOUT", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{}}, + {name: "unknown result", result: "UNKNOWN", sdkError: "PinPadUserCancelled", want: creditCallInitialResult{}}, + {name: "compound error", result: "ERROR", sdkError: "PinPadUserCancelled, DeviceUnavailable", want: creditCallInitialResult{}}, + {name: "case-sensitive SDK error", result: "ERROR", sdkError: "pinpadusercancelled", want: creditCallInitialResult{}}, + } { + t.Run(tc.name, func(t *testing.T) { + input := creditcall.TransactionResultXML{Entries: []creditcall.EntryXML{ + {Key: types.TransactionResult, Value: tc.result}, {Key: types.Errors, Value: tc.sdkError}, + }} + if got := classifyCreditCallInitialResult(input); got != tc.want { + t.Errorf("classifyCreditCallInitialResult(%q,%q)=%+v, want %+v", tc.result, tc.sdkError, got, tc.want) + } + }) + } +} + +func TestClassifyCreditCallInitialResultLastEntryWins(t *testing.T) { + for _, tc := range []struct { + name string + entries []creditcall.EntryXML + want creditCallInitialResult + }{ + {name: "no response fields", want: creditCallInitialResult{}}, + {name: "last result is approval", entries: []creditcall.EntryXML{ + {Key: types.TransactionResult, Value: "DECLINED"}, {Key: types.Errors, Value: "PinPadUserCancelled"}, {Key: types.TransactionResult, Value: "APPROVED"}, + }, want: creditCallInitialResult{kind: creditCallInitialApproved}}, + {name: "last result is declined cancellation", entries: []creditcall.EntryXML{ + {Key: types.TransactionResult, Value: "APPROVED"}, {Key: types.Errors, Value: "PinPadUserCancelled"}, {Key: types.TransactionResult, Value: "DECLINED"}, + }, want: creditCallInitialResult{kind: creditCallInitialCancelled, reason: "user_cancelled"}}, + {name: "last error is unknown", entries: []creditcall.EntryXML{ + {Key: types.Errors, Value: "PinPadUserCancelled"}, {Key: types.Errors, Value: "DeviceUnavailable"}, + }, want: creditCallInitialResult{}}, + {name: "last error is SDK timeout", entries: []creditcall.EntryXML{ + {Key: types.Errors, Value: "DeviceUnavailable"}, {Key: types.Errors, Value: "CardHolderActionTimedOut"}, + }, want: creditCallInitialResult{kind: creditCallInitialTimeout, reason: "cardholder_timeout"}}, + {name: "description is not an SDK code", entries: []creditcall.EntryXML{ + {Key: types.ErrorDescription, Value: "PinPadUserCancelled"}, + }, want: creditCallInitialResult{}}, + } { + t.Run(tc.name, func(t *testing.T) { + input := creditcall.TransactionResultXML{Entries: tc.entries} + before := append([]creditcall.EntryXML(nil), input.Entries...) + if got := classifyCreditCallInitialResult(input); got != tc.want { + t.Errorf("classifyCreditCallInitialResult(%+v)=%+v, want %+v", input.Entries, got, tc.want) + } + if !reflect.DeepEqual(input.Entries, before) { + t.Errorf("classifyCreditCallInitialResult mutated entries: got %+v, want %+v", input.Entries, before) + } + }) + } +} + +func TestCreditCallInitialSDKErrorClassification(t *testing.T) { + for _, operation := range []string{"sale", "preauth"} { + for _, tc := range []struct { + name, result, sdkError, description, want, reason string + retryable, resultPresent bool + }{ + {name: "missing result", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true}, + {name: "empty result", resultPresent: true, sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true}, + {name: "error result", result: "ERROR", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true}, + {name: "mixed-case error result", result: "Error", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true}, + {name: "CLI wait timeout", result: "TIMEOUT", sdkError: "Transaction timed out waiting for device response", want: "unknown"}, + {name: "CLI timeout with conflicting SDK error", result: "TIMEOUT", sdkError: "CardHolderActionTimedOut", want: "unknown"}, + {name: "other SDK error", result: "ERROR", sdkError: "DeviceUnavailable", want: "unknown"}, + {name: "compound error", sdkError: "CardHolderActionTimedOut, DeviceUnavailable", want: "unknown"}, + {name: "description only", description: "CardHolderActionTimedOut", sdkError: "DeviceUnavailable", want: "unknown"}, + {name: "cardholder timeout with declined result", result: "DECLINED", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true}, + {name: "cardholder timeout with mixed-case decline", result: "Declined", sdkError: "CardHolderActionTimedOut", want: "timeout", retryable: true}, + {name: "cancelled retains classification", result: "Cancelled", sdkError: "CardHolderActionTimedOut", want: "cancelled", retryable: true}, + {name: "explicit cancellation", result: "CANCELLED", want: "cancelled", retryable: true}, + {name: "alternate cancellation spelling", result: "CANCELED", want: "cancelled", retryable: true}, + {name: "user cancel missing result", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"}, + {name: "user cancel empty result", resultPresent: true, sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"}, + {name: "user cancel error result", result: "ERROR", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"}, + {name: "user cancel mixed-case error result", result: "Error", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"}, + {name: "user cancel with CLI timeout", result: "TIMEOUT", sdkError: "PinPadUserCancelled", want: "unknown"}, + {name: "user cancel with unknown result", result: "UNKNOWN", sdkError: "PinPadUserCancelled", want: "unknown"}, + {name: "user cancel with declined result", result: "DECLINED", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"}, + {name: "user cancel with mixed-case decline", result: "Declined", sdkError: "PinPadUserCancelled", want: "cancelled", retryable: true, reason: "user_cancelled"}, + {name: "ordinary decline", result: "DECLINED", sdkError: "InsufficientFunds", want: "declined", retryable: true}, + {name: "decline without SDK error", result: "DECLINED", want: "declined", retryable: true}, + {name: "decline with compound timeout error", result: "DECLINED", sdkError: "CardHolderActionTimedOut, DeviceUnavailable", want: "declined", retryable: true}, + {name: "decline with compound cancellation error", result: "DECLINED", sdkError: "PinPadUserCancelled, DeviceUnavailable", want: "declined", retryable: true}, + {name: "user cancel compound error", sdkError: "PinPadUserCancelled, DeviceUnavailable", want: "unknown"}, + {name: "user cancel description only", description: "PinPadUserCancelled", sdkError: "DeviceUnavailable", want: "unknown"}, + } { + t.Run(operation+"/"+tc.name, func(t *testing.T) { + var starts, confirms atomic.Int32 + fields := map[string]string{types.Errors: tc.sdkError, types.ReceiptDataCardholder: "synthetic initial receipt"} + if tc.result != "" || tc.resultPresent { + fields[types.TransactionResult] = tc.result + } + if tc.description != "" { + fields[types.ErrorDescription] = tc.description + } + app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/start-transaction-stream/" { + confirms.Add(1) + t.Errorf("initial %s response reached unexpected path %q", operation, r.URL.Path) + w.WriteHeader(http.StatusBadRequest) + return + } + starts.Add(1) + if err := json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields}); err != nil { + t.Errorf("encode synthetic SDK result: %v", err) + } + }) + var receipts []string + app.creditCallReceipt = func(receipt string) { receipts = append(receipts, receipt) } + recorder := httptest.NewRecorder() + if operation == "preauth" { + app.preauthPayment(recorder, preauthStreamRequest("1234", "Sale", "")) + } else { + app.salePayment(recorder, saleRequest(true)) + } + frames := decodePaymentStream(t, recorder.Body) + if len(frames) != 1 || frames[0].Result == nil { + t.Fatalf("%s(%s) frames=%+v, want one final result", operation, tc.name, frames) + } + final := frames[0].Result + if final.Outcome != tc.want || final.Retryable != tc.retryable || final.HTTPStatus != http.StatusOK { + t.Errorf("%s(%s) final=%+v, want %s retryable=%t HTTP 200", operation, tc.name, final, tc.want, tc.retryable) + } + if tc.want == "timeout" && (final.Reason != "cardholder_timeout" || final.Message != "Cardholder action timed out") { + t.Errorf("%s(%s) reason/message=%q/%q, want sanitized cardholder timeout", operation, tc.name, final.Reason, final.Message) + } + if tc.reason != "" && (final.Reason != tc.reason || final.Message != "Transaction cancelled") { + t.Errorf("%s(%s) reason/message=%q/%q, want %q/Transaction cancelled", operation, tc.name, final.Reason, final.Message, tc.reason) + } + if starts.Load() != 1 || confirms.Load() != 0 || !reflect.DeepEqual(receipts, []string{"synthetic initial receipt"}) { + t.Errorf("%s(%s) starts/confirms/receipts=%d/%d/%v, want 1/0/[synthetic initial receipt]", operation, tc.name, starts.Load(), confirms.Load(), receipts) + } + }) + } + } +} + +func TestCreditCallInitialSDKErrorRequiresCompleteResponse(t *testing.T) { + for _, operation := range []string{"sale", "preauth"} { + for _, sdkError := range []string{"CardHolderActionTimedOut", "PinPadUserCancelled"} { + for _, failure := range []string{"transport loss", "interrupted execution", "truncated result", "error frame", "HTTP failure"} { + t.Run(operation+"/"+sdkError+"/"+failure, func(t *testing.T) { + app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) { + body := fmt.Sprintf(`{"type":"result","result":{"ERRORS":%q}}`, sdkError) + switch failure { + case "error frame": + body = fmt.Sprintf("{\"type\":\"error\",\"error\":%q}\n", sdkError) + case "HTTP failure": + w.WriteHeader(http.StatusBadGateway) + body += "\n" + } + if _, err := io.WriteString(w, body); err != nil { + t.Errorf("write synthetic incomplete SDK result: %v", err) + } + }) + transport := app.creditCallTransport + var calls atomic.Int32 + app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) { + calls.Add(1) + if failure == "transport loss" { + return nil, io.ErrUnexpectedEOF + } + if failure == "interrupted execution" { + return nil, context.Canceled + } + return transport.RoundTrip(r) + }) + app.creditCallReceipt = func(string) { t.Error("incomplete SDK result printed a receipt") } + recorder := httptest.NewRecorder() + if operation == "preauth" { + app.preauthPayment(recorder, preauthStreamRequest("1234", "Sale", "")) + } else { + app.salePayment(recorder, saleRequest(true)) + } + frames := decodePaymentStream(t, recorder.Body) + if len(frames) != 1 || frames[0].Result == nil { + t.Fatalf("%s(%s) frames=%+v, want one uncertain result", operation, failure, frames) + } + final := frames[0].Result + if calls.Load() != 1 || final.Outcome != "unknown" || final.Retryable || final.HTTPStatus != http.StatusBadGateway || strings.Contains(final.Message, sdkError) { + t.Errorf("%s(%s) calls/final=%d/%+v, want one dispatch and sanitized nonretryable uncertainty", operation, failure, calls.Load(), final) + } + }) + } + } + } +} + +func TestCreditCallInitialSDKErrorDuringConfirmationRemainsUncertain(t *testing.T) { + for _, sdkError := range []string{"CardHolderActionTimedOut", "PinPadUserCancelled"} { + for _, result := range []string{"", "ERROR", "TIMEOUT", "DECLINED", "CANCELLED", "CANCELED"} { + t.Run(sdkError+"/confirmation result="+result, func(t *testing.T) { + var starts, confirms atomic.Int32 + app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/start-transaction-stream/" { + starts.Add(1) + fields := map[string]string{types.TransactionResult: "Approved", types.Reference: "SYNTH-APPROVED", types.TotalAmount: "1234"} + if err := json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields}); err != nil { + t.Errorf("encode initial approval: %v", err) + } + return + } + if r.URL.Path != "/confirm-transaction/" { + t.Errorf("unexpected SDK path %q", r.URL.Path) + w.WriteHeader(http.StatusBadRequest) + return + } + confirms.Add(1) + fields := map[string]string{types.TransactionResult: result, types.Errors: sdkError, types.ReceiptDataCardholder: "synthetic confirmation receipt"} + if _, err := io.WriteString(w, chipDNAFixture(t, fields)); err != nil { + t.Errorf("write confirmation result: %v", err) + } + }) + var receipts []string + app.creditCallReceipt = func(receipt string) { receipts = append(receipts, receipt) } + recorder := httptest.NewRecorder() + app.salePayment(recorder, saleRequest(true)) + frames := decodePaymentStream(t, recorder.Body) + if len(frames) != 1 || frames[0].Result == nil { + t.Fatalf("confirmation(%q) frames=%+v, want one uncertain final result", result, frames) + } + final := frames[0].Result + if final.Outcome != "unknown" || final.Retryable { + t.Errorf("confirmation(%q) final=%+v, want nonretryable uncertainty after initial approval", result, final) + } + if starts.Load() != 1 || confirms.Load() != 1 || !reflect.DeepEqual(receipts, []string{"synthetic confirmation receipt"}) { + t.Errorf("confirmation(%q) starts/confirms/receipts=%d/%d/%v, want 1/1/[synthetic confirmation receipt]", result, starts.Load(), confirms.Load(), receipts) + } + }) + } + } +} + +func TestCreditCallInitialApprovalPreservesExecutionWithSDKError(t *testing.T) { + for _, operation := range []string{"sale", "preauth"} { + for _, sdkError := range []string{"CardHolderActionTimedOut", "PinPadUserCancelled"} { + t.Run(operation+"/"+sdkError, func(t *testing.T) { + var starts, confirms atomic.Int32 + app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/start-transaction-stream/" { + starts.Add(1) + fields := map[string]string{types.TransactionResult: "APPROVED", types.TransactionType: "SALE", types.Errors: sdkError, + types.Reference: "SYNTH-APPROVED", types.TotalAmount: "1234", types.ReceiptDataCardholder: "synthetic initial receipt"} + if err := json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields}); err != nil { + t.Errorf("encode initial approval: %v", err) + } + return + } + if r.URL.Path != "/confirm-transaction/" { + t.Errorf("unexpected SDK path %q", r.URL.Path) + w.WriteHeader(http.StatusBadRequest) + return + } + confirms.Add(1) + if _, err := io.WriteString(w, chipDNAFixture(t, map[string]string{types.TransactionResult: "APPROVED", types.ReceiptDataCardholder: "synthetic confirmation receipt"})); err != nil { + t.Errorf("write confirmation approval: %v", err) + } + }) + var receipts []string + app.creditCallReceipt = func(receipt string) { receipts = append(receipts, receipt) } + recorder := httptest.NewRecorder() + wantConfirms, wantReceipt := int32(1), "synthetic confirmation receipt" + if operation == "preauth" { + database := preauthTestDatabase(t, app) + app.preauthPayment(recorder, preauthStreamRequest("1234", "Sale", "2026-11-10 00:00:00 +0000")) + persisted := waitPreauthInsert(t, database) + if persisted["TxnReference"] != "SYNTH-APPROVED" || persisted["TotalMinorUnits"] != "1234" { + t.Errorf("approved PREAUTH persisted=%v, want unchanged reference and terminal amount", persisted) + } + if database.count.Load() != 1 { + t.Errorf("approved PREAUTH persistence calls=%d, want 1", database.count.Load()) + } + wantConfirms, wantReceipt = 0, "synthetic initial receipt" + } else { + app.salePayment(recorder, saleRequest(true)) + } + frames := decodePaymentStream(t, recorder.Body) + if len(frames) != 1 || frames[0].Result == nil { + t.Fatalf("%s approval(%s) frames=%+v, want one approved result", operation, sdkError, frames) + } + final := frames[0].Result + if final.Outcome != "approved" || final.Retryable || final.TransactionReference != "SYNTH-APPROVED" || final.AmountMinor != 1234 { + t.Errorf("%s approval(%s) final=%+v, want approved with unchanged reference and amount", operation, sdkError, final) + } + if starts.Load() != 1 || confirms.Load() != wantConfirms || !reflect.DeepEqual(receipts, []string{wantReceipt}) { + t.Errorf("%s approval(%s) starts/confirms/receipts=%d/%d/%v, want 1/%d/[%s]", operation, sdkError, starts.Load(), confirms.Load(), receipts, wantConfirms, wantReceipt) + } + }) + } + } +} + +func TestCreditCallInitialApprovalConfirmationReadFailureRemainsUncertain(t *testing.T) { + var starts, confirms atomic.Int32 + app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/start-transaction-stream/" { + t.Errorf("unexpected SDK path %q", r.URL.Path) + w.WriteHeader(http.StatusBadRequest) + return + } + starts.Add(1) + fields := map[string]string{types.TransactionResult: "APPROVED", types.Reference: "SYNTH-APPROVED", types.TotalAmount: "1234"} + if err := json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": fields}); err != nil { + t.Errorf("encode initial approval: %v", err) + } + }) + transport := app.creditCallTransport + closed := [2]bool{} + app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) { + if r.URL.Path != "/confirm-transaction/" { + return transport.RoundTrip(r) + } + attempt := int(confirms.Add(1)) - 1 + if attempt >= len(closed) { + t.Error("more than two confirmation attempts") + return nil, io.ErrUnexpectedEOF + } + return &http.Response{StatusCode: http.StatusOK, Body: failedCreditCallBody{closed: &closed[attempt]}}, nil + }) + app.creditCallReceipt = func(string) { t.Error("failed confirmation printed a receipt") } + recorder := httptest.NewRecorder() + app.salePayment(recorder, saleRequest(true)) + frames := decodePaymentStream(t, recorder.Body) + if len(frames) != 1 || frames[0].Result == nil { + t.Fatalf("confirmation read failure frames=%+v, want one uncertain final result", frames) + } + final := frames[0].Result + if final.Outcome != "unknown" || final.Retryable || final.HTTPStatus != http.StatusBadGateway { + t.Errorf("confirmation read failure final=%+v, want nonretryable uncertainty", final) + } + if starts.Load() != 1 || confirms.Load() != 2 || !closed[0] || !closed[1] { + t.Errorf("starts/confirms/closed=%d/%d/%v, want one dispatch and two closed confirmation bodies", starts.Load(), confirms.Load(), closed) + } +} diff --git a/docs/releases.md b/release notes.md similarity index 98% rename from docs/releases.md rename to release notes.md index 7e399a7..adde8e7 100644 --- a/docs/releases.md +++ b/release notes.md @@ -2,7 +2,10 @@ `buildVersion` is a const in `cmd/hardlink/main.go`. -#### v2.2.1 - Unreleased +#### v2.2.2 - 05 November 2026 +fix(creditcall): restore SDK timeout and cancellation classification + +#### v2.2.1 - 04 November 2026 refactor: migrate the Go module and active imports to `gitea.futuresens.co.uk/futuresens/hardlink/v2`; include current module/build documentation. #### v2.2.0 - 02 November 2026