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

docs: updates

parent 9da87554
......@@ -53,6 +53,13 @@
<version>1.18.30</version>
<scope>provided</scope>
</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>
<build>
......
......@@ -19,14 +19,16 @@ public class BankingService {
* Orchestrates the validation and execution using the Immediate Transaction wrapper.
*/
public TransactionResult processTransaction(String accountId, long sequenceKey, String idempotencyKey, long amount) {
return transactionManager.executeInImmediateTransaction(() -> {
try (Session session = sessionFactory.openSession()) {
return transactionManager.executeInImmediateTransaction(session ->
processTransactionInternal(session, accountId, sequenceKey, idempotencyKey, amount)
);
}
public TransactionResult processTransactionInternal(Session session, String accountId, long sequenceKey, String idempotencyKey, long amount) {
// 1. Historical Retry Check (T4.1, T4.2)
Optional<TransactionHistory> history = findTransaction(session, accountId, sequenceKey);
if (history.isPresent()) {
TransactionHistory record = history.get();
// Validate identity and payload for historical retry
if (!record.getIdempotencyKey().equals(idempotencyKey)) {
return TransactionResult.failure("Idempotency key mismatch for historical record");
}
......@@ -37,13 +39,11 @@ public class BankingService {
}
// 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");
}
......@@ -63,7 +63,6 @@ public class BankingService {
// 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");
}
......@@ -85,8 +84,6 @@ public class BankingService {
return TransactionResult.success(newBalance, sequenceKey);
}
});
}
private Optional<TransactionHistory> findTransaction(Session session, String accountId, long sequenceKey) {
return session.createQuery(
......
......@@ -21,6 +21,21 @@ public class HibernateUtil {
configuration.addAnnotatedClass(Account.class);
configuration.addAnnotatedClass(TransactionHistory.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 {
}
@Entity
@Table(name = "idempotency_metadata",
uniqueConstraints = @UniqueConstraint(columnNames = {"account_id", "idempotency_key"}))
@Table(name = "idempotency_metadata")
public class IdempotencyMetadata {
@EmbeddedId
private IdempotencyMetadataId id;
......
......@@ -4,8 +4,7 @@ import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "transaction_history",
uniqueConstraints = @UniqueConstraint(columnNames = {"account_id", "sequence_key"}))
@Table(name = "transaction_history")
public class TransactionHistory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
......
......@@ -3,7 +3,7 @@ package com.bank.sdd;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import java.util.function.Supplier;
import java.util.function.Function;
public class TransactionManager {
private final SessionFactory sessionFactory;
......@@ -16,18 +16,11 @@ public class TransactionManager {
* Executes a block of code within a SQLite BEGIN IMMEDIATE transaction.
* 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()) {
// 1. Force BEGIN IMMEDIATE on the JDBC connection before Hibernate starts its own transaction
session.doWork(connection -> {
connection.createStatement().execute("BEGIN IMMEDIATE");
});
Transaction tx = null;
Transaction tx = session.beginTransaction();
try {
// 2. Bind Hibernate transaction to the existing JDBC transaction
tx = session.beginTransaction();
T result = action.get();
T result = action.apply(session);
tx.commit();
return result;
} catch (Exception e) {
......
......@@ -19,15 +19,28 @@ public class TransactionServer {
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(
new InetSocketAddress(port), 0);
new InetSocketAddress(port == 0 ? 0 : port), 0);
this.server = server;
server.createContext("/debit", new DebitHandler());
server.setExecutor(Executors.newFixedThreadPool(10));
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 {
@Override
......
......@@ -35,9 +35,9 @@ public class AtomicTransactionTest {
// Attempt a debit that fails midway (we will simulate failure by inducing a runtime exception)
try {
tm.executeInImmediateTransaction(() -> {
// We use the service but wrap it to force a crash after some state changes
BankingService.TransactionResult res = service.performDebit(accId, 1, "ID-1", 20);
tm.executeInImmediateTransaction(session -> {
// We use the internal method to ensure we are in the SAME transaction
BankingService.TransactionResult res = service.processTransactionInternal(session, accId, 1, "ID-1", 20);
// Simulate a crash AFTER the debit logic but BEFORE the transaction commit
throw new RuntimeException("Simulated crash before commit");
......
......@@ -23,18 +23,28 @@ public class FinalFaultToleranceTest {
service = new BankingService(sf, tm);
injector = new FaultInjector();
server = new TransactionServer(service, injector);
}
@BeforeEach
void setupServer() {
try {
server.start(PORT);
int actualPort = server.start(0);
client = new BankingClient("http://localhost:" + actualPort, 2000);
} catch (Exception 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
static void tearDown() {
if (server != null) server.stop();
if (sf != null) sf.close();
}
......@@ -82,13 +92,15 @@ public class FinalFaultToleranceTest {
CountDownLatch releaseLock = new CountDownLatch(1);
CompletableFuture.runAsync(() -> {
try (var session = sf.openSession()) {
session.doWork(conn -> {
try (java.sql.Connection conn = java.sql.DriverManager.getConnection("jdbc:sqlite:bank.db")) {
conn.createStatement().execute("BEGIN IMMEDIATE");
lockAcquired.countDown();
try {
releaseLock.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
conn.createStatement().execute("COMMIT");
});
} catch (Exception e) { e.printStackTrace(); }
});
......
......@@ -27,16 +27,16 @@ public class FullSystemIntegrationTest {
server = new TransactionServer(service, injector);
try {
server.start(PORT);
int actualPort = server.start(0);
client = new BankingClient("http://localhost:" + actualPort, 2000);
} catch (Exception e) {
throw new RuntimeException("Failed to start server", e);
}
client = new BankingClient("http://localhost:" + PORT, 2000);
}
@AfterAll
static void tearDown() {
if (server != null) server.stop();
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
-------------------------------------------------------------------------------
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