Commit dd9f3c65 authored by Shouib's avatar Shouib

feat: implement transaction idempotency manager

parent 37bf28f1
......@@ -42,10 +42,10 @@ description: "Task list template for feature implementation"
**Purpose**: Core infrastructure that MUST be complete before ANY user story can be implemented
- [X] T005 Implement `com.banking.persistence.DatabaseManager` for JDBC connection lifecycle management (no pooling)
- [ ] T006 [P] Implement `com.banking.persistence.AccountRepository` for basic account CRUD operations (including `SELECT FOR UPDATE`)
- [ ] T007 [P] Implement `com.banking.persistence.TransactionLedgerRepository` for idempotent ledger operations
- [ ] T008 Implement `com.banking.service.IdempotencyManager` to handle sequence key validation and ledger lookups
- [ ] T009 [P] Implement `com.banking.models` DTOs: `RequestDTO`, `ResponseDTO`, `Account`, and `Transaction`
- [X] T006 [P] Implement `com.banking.persistence.AccountRepository` for basic account CRUD operations (including `SELECT FOR UPDATE`)
- [X] T007 [P] Implement `com.banking.persistence.TransactionLedgerRepository` for idempotent ledger operations
- [X] T008 Implement `com.banking.service.IdempotencyManager` to handle sequence key validation and ledger lookups
- [X] T009 [P] Implement `com.banking.models` DTOs: `RequestDTO`, `ResponseDTO`, `Account`, and `Transaction`
- [ ] T010 Implement `com.banking.server.HttpServerApp` to bootstrap the JDK `HttpServer` on a configurable port
- [ ] T011 Implement `com.banking.server.RequestHandler` for routing `/withdraw` requests to the service layer
- [ ] T012 [P] Implement `com.banking.server.ValidationService` for initial request format and constraint validation
......
package com.banking.service;
import com.banking.models.*;
import com.banking.persistence.*;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Optional;
public class IdempotencyManager {
private final AccountRepository accountRepo;
private final TransactionLedgerRepository ledgerRepo;
public IdempotencyManager(AccountRepository accountRepo, TransactionLedgerRepository ledgerRepo) {
this.accountRepo = accountRepo;
this.ledgerRepo = ledgerRepo;
}
public record Result(
ResultType type,
String outcome,
BigDecimal balanceAfter,
String responseMessage
) {}
public enum ResultType {
NEW,
RETRY,
CONFLICTING_TRANSACTION,
STALE_KEY,
INVALID_SEQUENCE_KEY
}
public Result check(Connection conn, String accountId, long sequenceKey, BigDecimal amount, boolean isRetry) throws SQLException {
// 1. Check the transaction ledger using accountId and sequenceKey.
Optional<Transaction> existingTx = ledgerRepo.findByAccountAndSeqKey(accountId, sequenceKey);
if (existingTx.isPresent()) {
Transaction tx = existingTx.get();
// 2. Compare the original amount using BigDecimal.compareTo().
if (amount.compareTo(tx.amount()) == 0) {
// Identical: return original stored outcome, balance_after, and response_message.
return new Result(ResultType.RETRY, tx.outcome(), tx.balanceAfter(), tx.responseMessage());
} else {
// Different: return CONFLICTING_TRANSACTION.
return new Result(ResultType.CONFLICTING_TRANSACTION, null, null, null);
}
}
// 3. If the key does not exist:
// Reject non-positive sequence keys as INVALID_SEQUENCE_KEY.
if (sequenceKey <= 0) {
return new Result(ResultType.INVALID_SEQUENCE_KEY, null, null, null);
}
// Reject keys less than or equal to last_processed_seq_key as STALE_KEY.
Optional<Account> account = accountRepo.findById(accountId);
if (account.isPresent()) {
if (sequenceKey <= account.get().lastProcessedSeqKey()) {
return new Result(ResultType.STALE_KEY, null, null, null);
}
} else {
// If account doesn't exist, this is typically handled by the service layer (INVALID_ACCOUNT),
// but for the purpose of this manager's logic, we treat it as NEW so the service can fail it.
}
// Otherwise classify the transaction as NEW.
return new Result(ResultType.NEW, null, null, null);
}
}
package com.banking.persistence;
import com.banking.models.Account;
import org.junit.jupiter.api.*;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
class AccountRepositoryTest {
private Connection connection;
private AccountRepository repository;
@BeforeEach
void setUp() throws SQLException {
// Use H2 in-memory database for tests
connection = DriverManager.getConnection("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1", "sa", "");
connection.setAutoCommit(false);
try (Statement stmt = connection.createStatement()) {
stmt.execute("CREATE TABLE IF NOT EXISTS ACCOUNT (account_id VARCHAR(50) PRIMARY KEY, balance DECIMAL(20, 2) NOT NULL CHECK (balance >= 0), last_processed_seq_key BIGINT NOT NULL DEFAULT 0 CHECK (last_processed_seq_key >= 0))");
}
repository = new AccountRepository(connection);
}
@AfterEach
void tearDown() throws SQLException {
connection.rollback();
connection.close();
}
@Test
void testCreateAndFindAccount() throws SQLException {
repository.createAccount("ACC1", new BigDecimal("100.00"));
Optional<Account> account = repository.findById("ACC1");
assertTrue(account.isPresent());
assertEquals(new BigDecimal("100.00"), account.get().balance());
}
@Test
void testUpdateBalance() throws SQLException {
repository.createAccount("ACC1", new BigDecimal("100.00"));
repository.updateBalance("ACC1", new BigDecimal("50.00"));
Account account = repository.findById("ACC1").orElseThrow();
assertEquals(0, new BigDecimal("50.00").compareTo(account.balance()));
}
@Test
void testUpdateSeqKey() throws SQLException {
repository.createAccount("ACC1", new BigDecimal("100.00"));
repository.updateSeqKey("ACC1", 123L);
Account account = repository.findById("ACC1").orElseThrow();
assertEquals(123L, account.lastProcessedSeqKey());
}
@Test
void testFindByIdForUpdate() throws SQLException {
repository.createAccount("ACC1", new BigDecimal("100.00"));
// Open a second connection to simulate concurrent access
try (Connection conn2 = DriverManager.getConnection("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1", "sa", "")) {
conn2.setAutoCommit(false);
// Lock the row in the first connection
repository.findByIdForUpdate("ACC1");
// Try to lock the row in the second connection with a timeout
conn2.setNetworkTimeout(null, 100); // simplified for h2
// Since H2 in-mem locking behaves slightly differently than Postgres/Oracle,
// we verify that the query executes and returns the data.
// Real locking verification requires specific H2 settings or a separate process.
assertTrue(repository.findByIdForUpdate("ACC1").isPresent());
}
}
}
package com.banking.persistence;
import com.banking.models.Transaction;
import org.junit.jupiter.api.*;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
class TransactionLedgerRepositoryTest {
private Connection connection;
private TransactionLedgerRepository repository;
@BeforeEach
void setUp() throws SQLException {
connection = DriverManager.getConnection("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1", "sa", "");
connection.setAutoCommit(false);
try (Statement stmt = connection.createStatement()) {
stmt.execute("CREATE TABLE IF NOT EXISTS ACCOUNT (account_id VARCHAR(50) PRIMARY KEY, balance DECIMAL(20, 2) NOT NULL CHECK (balance >= 0), last_processed_seq_key BIGINT NOT NULL DEFAULT 0 CHECK (last_processed_seq_key >= 0))");
stmt.execute("CREATE TABLE IF NOT EXISTS TRANSACTION_LEDGER (id IDENTITY PRIMARY KEY, account_id VARCHAR(50) NOT NULL, balance_after DECIMAL(20, 2) NOT NULL, sequence_key BIGINT NOT NULL, amount DECIMAL(20, 2) NOT NULL CHECK (amount > 0), outcome VARCHAR(20) NOT NULL CHECK (outcome IN ('SUCCESS', 'INSUFFICIENT_FUNDS')), response_message VARCHAR(255) NOT NULL, timestamp TIMESTAMP NOT NULL, FOREIGN KEY (account_id) REFERENCES ACCOUNT(account_id), UNIQUE (account_id, sequence_key))");
stmt.execute("INSERT INTO ACCOUNT (account_id, balance, last_processed_seq_key) VALUES ('ACC1', 100.00, 0)");
}
repository = new TransactionLedgerRepository(connection);
}
@AfterEach
void tearDown() throws SQLException {
connection.rollback();
connection.close();
}
@Test
void testInsertAndFindTransaction() throws SQLException {
repository.save("ACC1", 100L, new BigDecimal("20.00"), "SUCCESS", new BigDecimal("80.00"), "Withdrawal successful");
Optional<Transaction> tx = repository.findByAccountAndSeqKey("ACC1", 100L);
assertTrue(tx.isPresent());
assertEquals("SUCCESS", tx.get().outcome());
assertEquals(0, new BigDecimal("80.00").compareTo(tx.get().balanceAfter()));
assertEquals("Withdrawal successful", tx.get().responseMessage());
}
@Test
void testInsertInsufficientFunds() throws SQLException {
repository.save("ACC1", 101L, new BigDecimal("200.00"), "INSUFFICIENT_FUNDS", new BigDecimal("100.00"), "Insufficient funds");
Optional<Transaction> tx = repository.findByAccountAndSeqKey("ACC1", 101L);
assertTrue(tx.isPresent());
assertEquals("INSUFFICIENT_FUNDS", tx.get().outcome());
}
@Test
void testDuplicateSeqKeyRejection() {
assertThrows(SQLException.class, () -> {
repository.save("ACC1", 102L, new BigDecimal("10.00"), "SUCCESS", new BigDecimal("90.00"), "Msg 1");
repository.save("ACC1", 102L, new BigDecimal("10.00"), "SUCCESS", new BigDecimal("90.00"), "Msg 2");
});
}
@Test
void testDifferentAccountsSameSeqKey() throws SQLException {
try (Statement stmt = connection.createStatement()) {
stmt.execute("INSERT INTO ACCOUNT (account_id, balance, last_processed_seq_key) VALUES ('ACC2', 100.00, 0)");
}
repository.save("ACC1", 103L, new BigDecimal("10.00"), "SUCCESS", new BigDecimal("90.00"), "Msg 1");
repository.save("ACC2", 103L, new BigDecimal("10.00"), "SUCCESS", new BigDecimal("90.00"), "Msg 2");
assertTrue(repository.findByAccountAndSeqKey("ACC1", 103L).isPresent());
assertTrue(repository.findByAccountAndSeqKey("ACC2", 103L).isPresent());
}
}
package com.banking.service;
import com.banking.models.*;
import com.banking.persistence.*;
import org.junit.jupiter.api.*;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
class IdempotencyManagerTest {
private Connection connection;
private AccountRepository accountRepo;
private TransactionLedgerRepository ledgerRepo;
private IdempotencyManager manager;
@BeforeEach
void setUp() throws SQLException {
connection = DriverManager.getConnection("jdbc:h2:mem:idempotency_test;DB_CLOSE_DELAY=-1", "sa", "");
connection.setAutoCommit(false);
try (Statement stmt = connection.createStatement()) {
stmt.execute("CREATE TABLE IF NOT EXISTS ACCOUNT (account_id VARCHAR(50) PRIMARY KEY, balance DECIMAL(20, 2) NOT NULL CHECK (balance >= 0), last_processed_seq_key BIGINT NOT NULL DEFAULT 0 CHECK (last_processed_seq_key >= 0))");
stmt.execute("CREATE TABLE IF NOT EXISTS TRANSACTION_LEDGER (id IDENTITY PRIMARY KEY, account_id VARCHAR(50) NOT NULL, balance_after DECIMAL(20, 2) NOT NULL, sequence_key BIGINT NOT NULL, amount DECIMAL(20, 2) NOT NULL CHECK (amount > 0), outcome VARCHAR(20) NOT NULL CHECK (outcome IN ('SUCCESS', 'INSUFFICIENT_FUNDS')), response_message VARCHAR(255) NOT NULL, timestamp TIMESTAMP NOT NULL, FOREIGN KEY (account_id) REFERENCES ACCOUNT(account_id), UNIQUE (account_id, sequence_key))");
stmt.execute("INSERT INTO ACCOUNT (account_id, balance, last_processed_seq_key) VALUES ('ACC1', 100.00, 10)");
}
accountRepo = new AccountRepository(connection);
ledgerRepo = new TransactionLedgerRepository(connection);
manager = new IdempotencyManager(accountRepo, ledgerRepo);
}
@AfterEach
void tearDown() throws SQLException {
connection.rollback();
connection.close();
}
@Test
void testNewSequenceKey() throws SQLException {
// account last_processed_seq_key = 10. Key 11 is new and valid.
IdempotencyManager.Result result = manager.check(connection, "ACC1", 11L, new BigDecimal("20.00"), false);
assertEquals(IdempotencyManager.ResultType.NEW, result.type());
}
@Test
void testExistingKeyIdenticalAmount() throws SQLException {
// Setup: existing ledger entry for sequenceKey 5, amount 20.00
ledgerRepo.save("ACC1", 5L, new BigDecimal("20.00"), "SUCCESS", new BigDecimal("80.00"), "Success message");
IdempotencyManager.Result result = manager.check(connection, "ACC1", 5L, new BigDecimal("20.00"), false);
assertEquals(IdempotencyManager.ResultType.RETRY, result.type());
assertEquals("SUCCESS", result.outcome());
assertEquals(0, new BigDecimal("80.00").compareTo(result.balanceAfter()));
assertEquals("Success message", result.responseMessage());
}
@Test
void testExistingKeyIdenticalAmountDifferentScale() throws SQLException {
// Setup: 20.0 vs 20.00
ledgerRepo.save("ACC1", 5L, new BigDecimal("20.0"), "SUCCESS", new BigDecimal("80.0"), "Success message");
IdempotencyManager.Result result = manager.check(connection, "ACC1", 5L, new BigDecimal("20.00"), false);
assertEquals(IdempotencyManager.ResultType.RETRY, result.type());
}
@Test
void testExistingKeyDifferentAmount() throws SQLException {
// Setup: ledger has 20.00, request has 50.00
ledgerRepo.save("ACC1", 5L, new BigDecimal("20.00"), "SUCCESS", new BigDecimal("80.00"), "Success message");
IdempotencyManager.Result result = manager.check(connection, "ACC1", 5L, new BigDecimal("50.00"), false);
assertEquals(IdempotencyManager.ResultType.CONFLICTING_TRANSACTION, result.type());
}
@Test
void testPositiveStaleKey() throws SQLException {
// account last_processed_seq_key = 10. Key 5 is positive but <= 10.
// We must check ledger first. If not in ledger, it's stale.
IdempotencyManager.Result result = manager.check(connection, "ACC1", 5L, new BigDecimal("20.00"), false);
assertEquals(IdempotencyManager.ResultType.STALE_KEY, result.type());
}
@Test
void testZeroKey() throws SQLException {
IdempotencyManager.Result result = manager.check(connection, "ACC1", 0L, new BigDecimal("20.00"), false);
assertEquals(IdempotencyManager.ResultType.INVALID_SEQUENCE_KEY, result.type());
}
@Test
void testNegativeKey() throws SQLException {
IdempotencyManager.Result result = manager.check(connection, "ACC1", -1L, new BigDecimal("20.00"), false);
assertEquals(IdempotencyManager.ResultType.INVALID_SEQUENCE_KEY, result.type());
}
@Test
void testRetryFlagDoesNotAffectIdentity() throws SQLException {
// Existing key with identical amount, isRetry = true
ledgerRepo.save("ACC1", 5L, new BigDecimal("20.00"), "SUCCESS", new BigDecimal("80.00"), "Success message");
IdempotencyManager.Result result = manager.check(connection, "ACC1", 5L, new BigDecimal("20.00"), true);
assertEquals(IdempotencyManager.ResultType.RETRY, result.type());
// New key, isRetry = false
IdempotencyManager.Result result2 = manager.check(connection, "ACC1", 11L, new BigDecimal("20.00"), false);
assertEquals(IdempotencyManager.ResultType.NEW, result2.type());
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment