One servlet filter, two interchangeable stores, 18 tests (9 scenarios x 2 stores) against a real redis-server 7.0.15 and PostgreSQL 16.15, and 20 captured transcripts under output/: replay, 422 on a changed body, concurrent duplicates, expiry, the crash window and a handler slower than the lock. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b5yg8grY17JsVAJviV
45 lines
1.7 KiB
Java
45 lines
1.7 KiB
Java
package com.ankurm.idempotency;
|
|
|
|
import org.springframework.http.ResponseEntity;
|
|
import org.springframework.jdbc.core.simple.JdbcClient;
|
|
import org.springframework.web.bind.annotation.PostMapping;
|
|
import org.springframework.web.bind.annotation.RequestBody;
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
|
|
/**
|
|
* The business operation that must not run twice. {@code /payments} is protected by
|
|
* {@link IdempotencyFilter}; {@code /payments/unprotected} is the same code with nothing in front
|
|
* of it, so a test can show what a retry does without the filter.
|
|
*/
|
|
@RestController
|
|
class PaymentController {
|
|
|
|
private final JdbcClient jdbc;
|
|
private final FaultInjector faults;
|
|
|
|
PaymentController(JdbcClient jdbc, FaultInjector faults) {
|
|
this.jdbc = jdbc;
|
|
this.faults = faults;
|
|
}
|
|
|
|
@PostMapping({"/payments", "/payments/unprotected"})
|
|
ResponseEntity<Payment> create(@RequestBody PaymentRequest request) throws InterruptedException {
|
|
if (faults.slowMillis > 0) {
|
|
Thread.sleep(faults.slowMillis);
|
|
}
|
|
long id = jdbc.sql("""
|
|
INSERT INTO payments (customer, amount, currency)
|
|
VALUES (:customer, :amount, :currency) RETURNING id""")
|
|
.param("customer", request.customer())
|
|
.param("amount", request.amount())
|
|
.param("currency", request.currency())
|
|
.query(Long.class)
|
|
.single();
|
|
if (faults.crashAfterBusiness) {
|
|
throw new SimulatedCrash();
|
|
}
|
|
return ResponseEntity.status(201)
|
|
.body(new Payment(id, request.customer(), request.amount(), request.currency()));
|
|
}
|
|
}
|