Commit 8b9af9ae authored by joubran.mansour's avatar joubran.mansour

feat: implement banking transaction logic

parent d6e97b4a
......@@ -26,4 +26,61 @@ never applied twice.
## Process constraint
Spec-Driven Development: constitution -> spec -> plan -> tasks -> implement.
No source code may be written before the spec and plan exist.
\ No newline at end of file
No source code may be written before the spec and plan exist.
## Selected Approach
The system employs a client-server architecture utilizing **Java 21**, **Hibernate 6**, and **SQLite**.
### Key Design Decisions
- **Persistence**: SQLite was selected for its ACID compliance. To prevent write-lock upgrade deadlocks, the server uses `BEGIN IMMEDIATE` transactions.
- **Concurrency**: A combination of per-account Java synchronization (as an optimization) and SQLite's `IMMEDIATE` locking is used to ensure thread-safety.
- **Idempotency**: Enforced via a persistent `TransactionHistory` table and an `IdempotencyMetadata` table that binds sequence keys to idempotency keys, ensuring that failed attempts (e.g., insufficient funds) are also tracked.
- **Consistency**: A `busy_timeout` is configured in the JDBC connection to handle lock contention gracefully.
## Implementation Details
- **Language**: Java 21
- **Build Tool**: Maven
- **AI Coding Agent**: Claude Code
### Setup and Execution
#### Build the Project
```bash
mvn clean install
```
#### Run the Server
Currently, the core logic is implemented in a service layer. To run the system, start the server application:
```bash
mvn exec:java -Dexec.mainClass="com.bank.sdd.Main"
```
#### Execute Tests
```bash
mvn test
```
## Testing and Verification
The system is verified through a layered testing strategy:
- **Unit Tests**: Validate sequence ordering and identity matching logic.
- **Integration Tests**: Verify Hibernate $\rightarrow$ SQLite interaction, specifically the `BEGIN IMMEDIATE` behavior.
- **Concurrency Tests**: Verified that $N$ simultaneous identical requests result in exactly one debit.
- **Fault Scenarios**:
- **Completed**: Atomic rollback on failure, historical retry recognition, and idempotency conflict detection.
- **Planned**: Full end-to-end validation of the four fault-injection scenarios (response loss, crashes, delays).
## Engineering Reflection
Applying Spec-Driven Development (SDD) identified critical gaps during the specification phase that would have otherwise emerged as bugs during implementation. For example:
- **Idempotency Conflict**: SDD revealed that simply tracking committed transactions was insufficient; we needed a separate metadata log to prevent different idempotency keys from being used for the same sequence key during failed attempts.
- **SQLite Deadlocks**: The planning phase highlighted that standard Hibernate transactions (`DEFERRED`) would cause `SQLITE_BUSY` deadlocks during lock upgrades, leading to the requirement for `BEGIN IMMEDIATE`.
## Project Status
- [x] Project Setup and Configuration
- [x] Database Schema and Persistence
- [x] Core Transaction Foundation (Atomic Updates)
- [x] Idempotency and Sequence Validation
- [ ] Server-Side Request Handling (REST API)
- [ ] Financial Logic and Retries
- [ ] Client-Side Implementation
- [ ] Fault Injection and Recovery
- [ ] Comprehensive Testing
- [ ] Final Validation
package com.bank.sdd;
public class TransactionAcknowledgment {
private final String status;
private final long balanceSnapshot;
private final long sequenceKey;
private final String error;
public TransactionAcknowledgment(String status, long balanceSnapshot, long sequenceKey, String error) {
this.status = status;
this.balanceSnapshot = balanceSnapshot;
this.sequenceKey = sequenceKey;
this.error = error;
}
public String getStatus() { return status; }
public long getBalanceSnapshot() { return balanceSnapshot; }
public long getSequenceKey() { return sequenceKey; }
public String getError() { return error; }
@Override
public String toString() {
return "TransactionAcknowledgment{" +
"status='" + status + '\'' +
", balanceSnapshot=" + balanceSnapshot +
", sequenceKey=" + sequenceKey +
", error='" + error + '\'' +
'}';
}
}
package com.bank.sdd;
import java.util.Map;
import java.util.HashMap;
public class TransactionRequest {
private final String accountId;
private final long sequenceKey;
private final String idempotencyKey;
private final boolean retryIs;
private final long amount;
public TransactionRequest(String accountId, long sequenceKey, String idempotencyKey, boolean retryIs, long amount) {
this.accountId = accountId;
this.sequenceKey = sequenceKey;
this.idempotencyKey = idempotencyKey;
this.retryIs = retryIs;
this.amount = amount;
}
public String getAccountId() { return accountId; }
public long getSequenceKey() { return sequenceKey; }
public String getIdempotencyKey() { return idempotencyKey; }
public boolean isRetryIs() { return retryIs; }
public long getAmount() { return amount; }
}
package com.bank.sdd;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java java.io.*;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
public class TransactionServer {
private final BankingService bankingService;
private final ConcurrentHashMap<String, ReentrantLock> accountLocks = new ConcurrentHashMap<>();
public TransactionServer(BankingService bankingService) {
this.bankingService = bankingService;
}
public void start(int port) throws java.io.IOException {
com.sun.net.httpserver.HttpServer server = com.sun.net.httpserver.HttpServer.create(
new InetSocketAddress(port), 0);
server.createContext("/debit", new DebitHandler());
server.setExecutor(Executors.newFixedThreadPool(10));
server.start();
System.out.println("Server started on port " + port);
}
private class DebitHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws java.io.IOException {
if (!"POST".equalsIgnoreCase(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "Method Not Allowed");
return;
}
try {
// Simple JSON parsing (manual to avoid extra dependencies)
String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
TransactionRequest request = parseRequest(body);
// T5.4: Per-account synchronization (Optimization)
ReentrantLock lock = accountLocks.computeIfAbsent(request.getAccountId(), k -> new ReentrantLock());
lock.lock();
try {
BankingService.TransactionResult result = bankingService.processTransaction(
request.getAccountId(),
request.getSequenceKey(),
request.getIdempotencyKey(),
request.getAmount()
);
if (result.success) {
String response = String.format(
"{\"status\":\"SUCCESS\", \"balanceSnapshot\":%d, \"sequenceKey\":%d}",
result.balanceSnapshot, result.sequenceKey);
sendResponse(exchange, 200, response);
} else {
String response = String.format(
"{\"status\":\"FAILURE\", \"error\":\"%s\"}",
result.error);
sendResponse(exchange, 400, response);
}
} finally {
lock.unlock();
}
} catch (Exception e) {
// T5.3: Global Error Handling
sendResponse(exchange, 500, "{\"status\":\"FAILURE\", \"error\":\"Internal Server Error: " + e.getMessage() + "\"}");
}
}
private void sendResponse(HttpExchange exchange, int code, String body) throws java.io.IOException {
byte[] responseBytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(code, responseBytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(responseBytes);
}
}
private TransactionRequest parseRequest(String body) {
// Basic manual JSON extraction to keep it dependency-free
// Expected format: {"accountId":"...", "sequenceKey":1, "idempotencyKey":"...", "retryIs":false, "amount":10}
String accountId = extract(body, "accountId");
long sequenceKey = Long.parseLong(extract(body, "sequenceKey"));
String idempotencyKey = extract(body, "idempotencyKey");
boolean retryIs = Boolean.parseBoolean(extract(body, "retryIs"));
long amount = Long.parseLong(extract(body, "amount"));
return new TransactionRequest(accountId, sequenceKey, idempotencyKey, retryIs, amount);
}
private String extract(String json, String key) {
String pattern = "\"" + key + "\":";
int start = json.indexOf(pattern) + pattern.length();
if (json.charAt(start) == '"') {
start++;
int end = json.indexOf("\"", start);
return json.substring(start, end);
} else {
int end = json.indexOf(",", start);
if (end == -1) end = json.indexOf("}", start);
return json.substring(start, end).trim();
}
}
}
}
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