Repository navigation
bug: make deposit/withdraw/transfer transactional with row locks (sfind-baf6d2f9) #376
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
devin-ai-integration
wants to merge
3
commits into
DevOps
Choose a base branch
from
devin/sfind-baf6d2f9-atomic-balance-updates
base: DevOps
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
f74f1a3
fix: make balance updates transactional with row locks
devin-ai-integration[bot] 8b9ffb4
fix: refresh locked accounts so open-in-view copies are not stale
devin-ai-integration[bot] b9821ca
fix: render a freshly loaded account after a failed withdraw/transfer
devin-ai-integration[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
151 changes: 151 additions & 0 deletions
151
src/test/java/com/example/bankapp/controller/BankControllerConcurrencyTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| package com.example.bankapp.controller; | ||
|
|
||
| import com.example.bankapp.repository.AccountRepository; | ||
| import com.example.bankapp.repository.TransactionRepository; | ||
| import com.example.bankapp.service.AccountService; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.boot.test.context.SpringBootTest; | ||
| import org.springframework.boot.test.web.server.LocalServerPort; | ||
| import org.springframework.test.context.ActiveProfiles; | ||
|
|
||
| import java.math.BigDecimal; | ||
| import java.net.URI; | ||
| import java.net.http.HttpClient; | ||
| import java.net.http.HttpRequest; | ||
| import java.net.http.HttpResponse; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.concurrent.CompletableFuture; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
|
|
||
| /** | ||
| * Drives the real HTTP endpoints so the requests go through open-in-view, where the controller's | ||
| * Account stays managed for the whole request. | ||
| */ | ||
| @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) | ||
| @ActiveProfiles("test") | ||
| class BankControllerConcurrencyTest { | ||
|
|
||
| @LocalServerPort | ||
| private int port; | ||
|
|
||
| @Autowired | ||
| private AccountService accountService; | ||
|
|
||
| @Autowired | ||
| private AccountRepository accountRepository; | ||
|
|
||
| @Autowired | ||
| private TransactionRepository transactionRepository; | ||
|
|
||
| private final HttpClient http = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).build(); | ||
|
|
||
| @BeforeEach | ||
| void cleanDatabase() { | ||
| transactionRepository.deleteAll(); | ||
| accountRepository.deleteAll(); | ||
| } | ||
|
|
||
| @Test | ||
| void concurrentWithdrawRequestsCannotOverdraw() throws Exception { | ||
| accountService.registerAccount("mallory", "pw12345"); | ||
| String session = login("mallory", "pw12345"); | ||
| post(session, "/deposit", "amount=100"); | ||
|
|
||
| fireConcurrently(20, i -> post(session, "/withdraw", "amount=100")); | ||
|
|
||
| assertThat(balanceOf("mallory")).isEqualByComparingTo("0.00"); | ||
| assertThat(transactionRepository.findByAccountId(idOf("mallory"))) | ||
| .filteredOn(t -> t.getType().equals("Withdrawal")) | ||
| .hasSize(1); | ||
| } | ||
|
|
||
| @Test | ||
| void concurrentTransferRequestsCannotSpendTheSameBalanceTwice() throws Exception { | ||
| accountService.registerAccount("mallory", "pw12345"); | ||
| for (int i = 0; i < 10; i++) { | ||
| accountService.registerAccount("accomplice" + i, "pw12345"); | ||
| } | ||
| String session = login("mallory", "pw12345"); | ||
| post(session, "/deposit", "amount=100"); | ||
|
|
||
| fireConcurrently(10, i -> post(session, "/transfer", "toUsername=accomplice" + i + "&amount=100")); | ||
|
|
||
| assertThat(balanceOf("mallory")).isEqualByComparingTo("0.00"); | ||
| BigDecimal received = BigDecimal.ZERO; | ||
| for (int i = 0; i < 10; i++) { | ||
| received = received.add(balanceOf("accomplice" + i)); | ||
| } | ||
| assertThat(received).isEqualByComparingTo("100.00"); | ||
| } | ||
|
|
||
| @Test | ||
| void failedTransferRendersThePersistedBalance() throws Exception { | ||
| accountService.registerAccount("sender", "pw12345"); | ||
| String longName = "r".repeat(250); | ||
| accountService.registerAccount(longName, "pw12345"); | ||
| String session = login("sender", "pw12345"); | ||
| post(session, "/deposit", "amount=100"); | ||
|
|
||
| String page = http.send(form(session, "/transfer", "toUsername=" + longName + "&amount=40"), | ||
| HttpResponse.BodyHandlers.ofString()).body(); | ||
|
|
||
| assertThat(balanceOf("sender")).isEqualByComparingTo("100.00"); | ||
| assertThat(page).contains("Current Balance: $100.00").doesNotContain("Current Balance: $60.00"); | ||
| } | ||
|
|
||
| private interface Request { | ||
| void send(int index) throws Exception; | ||
| } | ||
|
|
||
| private void fireConcurrently(int count, Request request) { | ||
| List<CompletableFuture<Void>> futures = new ArrayList<>(); | ||
| for (int i = 0; i < count; i++) { | ||
| int index = i; | ||
| futures.add(CompletableFuture.runAsync(() -> { | ||
| try { | ||
| request.send(index); | ||
| } catch (Exception e) { | ||
| throw new IllegalStateException(e); | ||
| } | ||
| })); | ||
| } | ||
| CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); | ||
| } | ||
|
|
||
| private String login(String username, String password) throws Exception { | ||
| HttpResponse<Void> response = http.send(form(null, "/login", "username=" + username + "&password=" + password), | ||
| HttpResponse.BodyHandlers.discarding()); | ||
| assertThat(response.headers().firstValue("Location")).hasValueSatisfying(l -> assertThat(l).endsWith("/dashboard")); | ||
| return response.headers().allValues("Set-Cookie").stream() | ||
| .filter(c -> c.startsWith("JSESSIONID=")) | ||
| .map(c -> c.substring(0, c.indexOf(';'))) | ||
| .findFirst() | ||
| .orElseThrow(); | ||
| } | ||
|
|
||
| private void post(String session, String path, String body) throws Exception { | ||
| http.send(form(session, path, body), HttpResponse.BodyHandlers.discarding()); | ||
| } | ||
|
|
||
| private HttpRequest form(String session, String path, String body) { | ||
| HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create("http://localhost:" + port + path)) | ||
| .header("Content-Type", "application/x-www-form-urlencoded") | ||
| .POST(HttpRequest.BodyPublishers.ofString(body)); | ||
| if (session != null) { | ||
| builder.header("Cookie", session); | ||
| } | ||
| return builder.build(); | ||
| } | ||
|
|
||
| private Long idOf(String username) { | ||
| return accountRepository.findByUsername(username).orElseThrow().getId(); | ||
| } | ||
|
|
||
| private BigDecimal balanceOf(String username) { | ||
| return accountRepository.findByUsername(username).orElseThrow().getBalance(); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.