Commit 519fb732 authored by joubran.mansour's avatar joubran.mansour

docs: updates

parent 9da87554
...@@ -53,6 +53,13 @@ ...@@ -53,6 +53,13 @@
<version>1.18.30</version> <version>1.18.30</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- Hibernate Community Dialects for SQLite support in Hibernate 6 -->
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-community-dialects</artifactId>
<version>${hibernate.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -19,73 +19,70 @@ public class BankingService { ...@@ -19,73 +19,70 @@ public class BankingService {
* Orchestrates the validation and execution using the Immediate Transaction wrapper. * Orchestrates the validation and execution using the Immediate Transaction wrapper.
*/ */
public TransactionResult processTransaction(String accountId, long sequenceKey, String idempotencyKey, long amount) { public TransactionResult processTransaction(String accountId, long sequenceKey, String idempotencyKey, long amount) {
return transactionManager.executeInImmediateTransaction(() -> { return transactionManager.executeInImmediateTransaction(session ->
try (Session session = sessionFactory.openSession()) { processTransactionInternal(session, accountId, sequenceKey, idempotencyKey, amount)
);
// 1. Historical Retry Check (T4.1, T4.2) }
Optional<TransactionHistory> history = findTransaction(session, accountId, sequenceKey);
if (history.isPresent()) { public TransactionResult processTransactionInternal(Session session, String accountId, long sequenceKey, String idempotencyKey, long amount) {
TransactionHistory record = history.get(); // 1. Historical Retry Check (T4.1, T4.2)
// Validate identity and payload for historical retry Optional<TransactionHistory> history = findTransaction(session, accountId, sequenceKey);
if (!record.getIdempotencyKey().equals(idempotencyKey)) { if (history.isPresent()) {
return TransactionResult.failure("Idempotency key mismatch for historical record"); TransactionHistory record = history.get();
} if (!record.getIdempotencyKey().equals(idempotencyKey)) {
if (record.getAmount() != amount) { return TransactionResult.failure("Idempotency key mismatch for historical record");
return TransactionResult.failure("Mismatched Payload"); }
} if (record.getAmount() != amount) {
return TransactionResult.success(record.getBalanceSnapshot(), record.getSequenceKey()); return TransactionResult.failure("Mismatched Payload");
}
// 2. Idempotency Key Conflict Detection (T4.3)
// Check if this sequence key is already bound to a different idempotency key
IdempotencyMetadata metadata = session.get(IdempotencyMetadata.class, new IdempotencyMetadataId(accountId, sequenceKey));
if (metadata != null && !metadata.getIdempotencyKey().equals(idempotencyKey)) {
return TransactionResult.failure("Idempotency key conflict for this sequence");
}
// Check if this idempotency key is already bound to a different sequence key
if (isIdempotencyKeyUsedElsewhere(session, accountId, idempotencyKey, sequenceKey)) {
return TransactionResult.failure("Idempotency key already used for a different sequence");
}
// 3. Sequence Validation (T4.4, T4.5)
Account account = session.get(Account.class, accountId);
if (account == null) {
return TransactionResult.failure("Account not found");
}
if (sequenceKey <= account.getKeySequenceLast()) {
return TransactionResult.failure("Stale Sequence Key");
}
if (sequenceKey != account.getKeySequenceLast() + 1) {
return TransactionResult.failure("Out-of-Order Sequence Key");
}
// 4. Financial Execution (T6.1, T6.2)
if (account.getBalance() < amount) {
// T6.2: Ensure we persist the idempotency mapping even on failure
saveIdempotencyMetadata(session, accountId, sequenceKey, idempotencyKey);
return TransactionResult.failure("Insufficient funds");
}
// 5. Atomic Update (T3.3)
long newBalance = account.getBalance() - amount;
account.setBalance(newBalance);
account.setKeySequenceLast(sequenceKey);
session.merge(account);
// Record History (T3.4)
TransactionHistory historyRecord = new TransactionHistory(
accountId, sequenceKey, idempotencyKey, amount, newBalance
);
session.persist(historyRecord);
// Save metadata mapping
saveIdempotencyMetadata(session, accountId, sequenceKey, idempotencyKey);
return TransactionResult.success(newBalance, sequenceKey);
} }
}); return TransactionResult.success(record.getBalanceSnapshot(), record.getSequenceKey());
}
// 2. Idempotency Key Conflict Detection (T4.3)
IdempotencyMetadata metadata = session.get(IdempotencyMetadata.class, new IdempotencyMetadataId(accountId, sequenceKey));
if (metadata != null && !metadata.getIdempotencyKey().equals(idempotencyKey)) {
return TransactionResult.failure("Idempotency key conflict for this sequence");
}
if (isIdempotencyKeyUsedElsewhere(session, accountId, idempotencyKey, sequenceKey)) {
return TransactionResult.failure("Idempotency key already used for a different sequence");
}
// 3. Sequence Validation (T4.4, T4.5)
Account account = session.get(Account.class, accountId);
if (account == null) {
return TransactionResult.failure("Account not found");
}
if (sequenceKey <= account.getKeySequenceLast()) {
return TransactionResult.failure("Stale Sequence Key");
}
if (sequenceKey != account.getKeySequenceLast() + 1) {
return TransactionResult.failure("Out-of-Order Sequence Key");
}
// 4. Financial Execution (T6.1, T6.2)
if (account.getBalance() < amount) {
saveIdempotencyMetadata(session, accountId, sequenceKey, idempotencyKey);
return TransactionResult.failure("Insufficient funds");
}
// 5. Atomic Update (T3.3)
long newBalance = account.getBalance() - amount;
account.setBalance(newBalance);
account.setKeySequenceLast(sequenceKey);
session.merge(account);
// Record History (T3.4)
TransactionHistory historyRecord = new TransactionHistory(
accountId, sequenceKey, idempotencyKey, amount, newBalance
);
session.persist(historyRecord);
// Save metadata mapping
saveIdempotencyMetadata(session, accountId, sequenceKey, idempotencyKey);
return TransactionResult.success(newBalance, sequenceKey);
} }
private Optional<TransactionHistory> findTransaction(Session session, String accountId, long sequenceKey) { private Optional<TransactionHistory> findTransaction(Session session, String accountId, long sequenceKey) {
......
...@@ -21,6 +21,21 @@ public class HibernateUtil { ...@@ -21,6 +21,21 @@ public class HibernateUtil {
configuration.addAnnotatedClass(Account.class); configuration.addAnnotatedClass(Account.class);
configuration.addAnnotatedClass(TransactionHistory.class); configuration.addAnnotatedClass(TransactionHistory.class);
configuration.addAnnotatedClass(IdempotencyMetadata.class); configuration.addAnnotatedClass(IdempotencyMetadata.class);
return configuration.buildSessionFactory();
org.hibernate.SessionFactory sf = configuration.buildSessionFactory();
// Manually ensure constraints for SQLite
try (org.hibernate.Session session = sf.openSession()) {
session.doWork(connection -> {
try (var stmt = connection.createStatement()) {
stmt.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_tx_history_acc_seq ON transaction_history (account_id, sequence_key)");
stmt.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_idemp_meta_acc_key ON idempotency_metadata (account_id, idempotency_key)");
}
});
} catch (Exception e) {
System.err.println("Failed to initialize SQLite constraints: " + e.getMessage());
}
return sf;
} }
} }
...@@ -37,8 +37,7 @@ class IdempotencyMetadataId implements Serializable { ...@@ -37,8 +37,7 @@ class IdempotencyMetadataId implements Serializable {
} }
@Entity @Entity
@Table(name = "idempotency_metadata", @Table(name = "idempotency_metadata")
uniqueConstraints = @UniqueConstraint(columnNames = {"account_id", "idempotency_key"}))
public class IdempotencyMetadata { public class IdempotencyMetadata {
@EmbeddedId @EmbeddedId
private IdempotencyMetadataId id; private IdempotencyMetadataId id;
......
...@@ -4,8 +4,7 @@ import jakarta.persistence.*; ...@@ -4,8 +4,7 @@ import jakarta.persistence.*;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@Entity @Entity
@Table(name = "transaction_history", @Table(name = "transaction_history")
uniqueConstraints = @UniqueConstraint(columnNames = {"account_id", "sequence_key"}))
public class TransactionHistory { public class TransactionHistory {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
......
...@@ -3,7 +3,7 @@ package com.bank.sdd; ...@@ -3,7 +3,7 @@ package com.bank.sdd;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import java.util.function.Supplier; import java.util.function.Function;
public class TransactionManager { public class TransactionManager {
private final SessionFactory sessionFactory; private final SessionFactory sessionFactory;
...@@ -16,18 +16,11 @@ public class TransactionManager { ...@@ -16,18 +16,11 @@ public class TransactionManager {
* Executes a block of code within a SQLite BEGIN IMMEDIATE transaction. * Executes a block of code within a SQLite BEGIN IMMEDIATE transaction.
* This ensures a write lock is acquired immediately to prevent deadlocks. * This ensures a write lock is acquired immediately to prevent deadlocks.
*/ */
public <T> T executeInImmediateTransaction(Supplier<T> action) { public <T> T executeInImmediateTransaction(java.util.function.Function<Session, T> action) {
try (Session session = sessionFactory.openSession()) { try (Session session = sessionFactory.openSession()) {
// 1. Force BEGIN IMMEDIATE on the JDBC connection before Hibernate starts its own transaction Transaction tx = session.beginTransaction();
session.doWork(connection -> {
connection.createStatement().execute("BEGIN IMMEDIATE");
});
Transaction tx = null;
try { try {
// 2. Bind Hibernate transaction to the existing JDBC transaction T result = action.apply(session);
tx = session.beginTransaction();
T result = action.get();
tx.commit(); tx.commit();
return result; return result;
} catch (Exception e) { } catch (Exception e) {
......
...@@ -19,16 +19,29 @@ public class TransactionServer { ...@@ -19,16 +19,29 @@ public class TransactionServer {
this.faultInjector = faultInjector; this.faultInjector = faultInjector;
} }
public void start(int port) throws java.io.IOException { public int start(int port) throws java.io.IOException {
com.sun.net.httpserver.HttpServer server = com.sun.net.httpserver.HttpServer.create( com.sun.net.httpserver.HttpServer server = com.sun.net.httpserver.HttpServer.create(
new InetSocketAddress(port), 0); new InetSocketAddress(port == 0 ? 0 : port), 0);
this.server = server;
server.createContext("/debit", new DebitHandler()); server.createContext("/debit", new DebitHandler());
server.setExecutor(Executors.newFixedThreadPool(10)); server.setExecutor(Executors.newFixedThreadPool(10));
server.start(); server.start();
System.out.println("Server started on port " + port);
int actualPort = server.getAddress().getPort();
System.out.println("Server started on port " + actualPort);
return actualPort;
} }
public void stop() {
if (server != null) {
server.stop(0);
System.out.println("Server stopped");
}
}
private com.sun.net.httpserver.HttpServer server;
private class DebitHandler implements HttpHandler { private class DebitHandler implements HttpHandler {
@Override @Override
public void handle(HttpExchange exchange) throws java.io.IOException { public void handle(HttpExchange exchange) throws java.io.IOException {
......
...@@ -35,9 +35,9 @@ public class AtomicTransactionTest { ...@@ -35,9 +35,9 @@ public class AtomicTransactionTest {
// Attempt a debit that fails midway (we will simulate failure by inducing a runtime exception) // Attempt a debit that fails midway (we will simulate failure by inducing a runtime exception)
try { try {
tm.executeInImmediateTransaction(() -> { tm.executeInImmediateTransaction(session -> {
// We use the service but wrap it to force a crash after some state changes // We use the internal method to ensure we are in the SAME transaction
BankingService.TransactionResult res = service.performDebit(accId, 1, "ID-1", 20); BankingService.TransactionResult res = service.processTransactionInternal(session, accId, 1, "ID-1", 20);
// Simulate a crash AFTER the debit logic but BEFORE the transaction commit // Simulate a crash AFTER the debit logic but BEFORE the transaction commit
throw new RuntimeException("Simulated crash before commit"); throw new RuntimeException("Simulated crash before commit");
......
...@@ -23,18 +23,28 @@ public class FinalFaultToleranceTest { ...@@ -23,18 +23,28 @@ public class FinalFaultToleranceTest {
service = new BankingService(sf, tm); service = new BankingService(sf, tm);
injector = new FaultInjector(); injector = new FaultInjector();
server = new TransactionServer(service, injector); server = new TransactionServer(service, injector);
}
@BeforeEach
void setupServer() {
try { try {
server.start(PORT); int actualPort = server.start(0);
client = new BankingClient("http://localhost:" + actualPort, 2000);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Failed to start server", e); throw new RuntimeException("Failed to start server", e);
} }
}
client = new BankingClient("http://localhost:" + PORT, 2000); @AfterEach
void stopServer() {
if (server != null) {
server.stop();
}
} }
@AfterAll @AfterAll
static void tearDown() { static void tearDown() {
if (server != null) server.stop();
if (sf != null) sf.close(); if (sf != null) sf.close();
} }
...@@ -82,13 +92,15 @@ public class FinalFaultToleranceTest { ...@@ -82,13 +92,15 @@ public class FinalFaultToleranceTest {
CountDownLatch releaseLock = new CountDownLatch(1); CountDownLatch releaseLock = new CountDownLatch(1);
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
try (var session = sf.openSession()) { try (java.sql.Connection conn = java.sql.DriverManager.getConnection("jdbc:sqlite:bank.db")) {
session.doWork(conn -> { conn.createStatement().execute("BEGIN IMMEDIATE");
conn.createStatement().execute("BEGIN IMMEDIATE"); lockAcquired.countDown();
lockAcquired.countDown(); try {
releaseLock.await(); releaseLock.await();
conn.createStatement().execute("COMMIT"); } catch (InterruptedException e) {
}); Thread.currentThread().interrupt();
}
conn.createStatement().execute("COMMIT");
} catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); }
}); });
......
...@@ -27,16 +27,16 @@ public class FullSystemIntegrationTest { ...@@ -27,16 +27,16 @@ public class FullSystemIntegrationTest {
server = new TransactionServer(service, injector); server = new TransactionServer(service, injector);
try { try {
server.start(PORT); int actualPort = server.start(0);
client = new BankingClient("http://localhost:" + actualPort, 2000);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Failed to start server", e); throw new RuntimeException("Failed to start server", e);
} }
client = new BankingClient("http://localhost:" + PORT, 2000);
} }
@AfterAll @AfterAll
static void tearDown() { static void tearDown() {
if (server != null) server.stop();
if (sf != null) sf.close(); if (sf != null) sf.close();
} }
......
com\bank\sdd\AtomicTransactionTest.class
com\bank\sdd\IdempotencyValidationTest.class
com\bank\sdd\TransactionLifecycleInvestigation.class
com\bank\sdd\FinalFaultToleranceTest.class
com\bank\sdd\FullSystemIntegrationTest.class
com\bank\sdd\SchemaVerificationTest.class com\bank\sdd\SchemaVerificationTest.class
-------------------------------------------------------------------------------
Test set: com.bank.sdd.AtomicTransactionTest
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.738 s -- in com.bank.sdd.AtomicTransactionTest
-------------------------------------------------------------------------------
Test set: com.bank.sdd.FinalFaultToleranceTest
-------------------------------------------------------------------------------
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.264 s -- in com.bank.sdd.FinalFaultToleranceTest
-------------------------------------------------------------------------------
Test set: com.bank.sdd.FullSystemIntegrationTest
-------------------------------------------------------------------------------
Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.332 s -- in com.bank.sdd.FullSystemIntegrationTest
-------------------------------------------------------------------------------
Test set: com.bank.sdd.IdempotencyValidationTest
-------------------------------------------------------------------------------
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.160 s -- in com.bank.sdd.IdempotencyValidationTest
-------------------------------------------------------------------------------
Test set: com.bank.sdd.SchemaVerificationTest
-------------------------------------------------------------------------------
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.082 s -- in com.bank.sdd.SchemaVerificationTest
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