diff --git a/.github/scripts/verify-concept.sh b/.github/scripts/verify-concept.sh index f241799..e35292d 100755 --- a/.github/scripts/verify-concept.sh +++ b/.github/scripts/verify-concept.sh @@ -8,32 +8,35 @@ set -uo pipefail project="$1"; start_pass="$2"; total="$3" failed=0 +# Logs go to a private temp folder, so two runs from one checkout do not mix their output. +logs="$(mktemp -d)" +trap 'rm -rf "$logs"' EXIT + count() { grep -c -F "$1" "$2" || true; } echo "== $project/start: expecting $start_pass of $total, and a failing exit code" -(cd "$project/start" && ./check) > start.log 2>&1 +(cd "$project/start" && ./check) > "$logs/start.log" 2>&1 start_exit=$? -pass=$(count "[PASS]" start.log); fail=$(count "[FAIL]" start.log) +pass=$(count "[PASS]" "$logs/start.log"); fail=$(count "[FAIL]" "$logs/start.log") echo " got $pass of $((pass + fail)), exit code $start_exit" if [ "$pass" != "$start_pass" ] || [ "$((pass + fail))" != "$total" ] || [ "$start_exit" = "0" ]; then - echo " WRONG. Output of ./check in start/:"; cat start.log; failed=1 + echo " WRONG. Output of ./check in start/:"; cat "$logs/start.log"; failed=1 fi echo "== $project/solution: expecting $total of $total, and exit code 0" -(cd "$project/solution" && ./check) > solution.log 2>&1 +(cd "$project/solution" && ./check) > "$logs/solution.log" 2>&1 solution_exit=$? -pass=$(count "[PASS]" solution.log); fail=$(count "[FAIL]" solution.log) +pass=$(count "[PASS]" "$logs/solution.log"); fail=$(count "[FAIL]" "$logs/solution.log") echo " got $pass of $((pass + fail)), exit code $solution_exit" if [ "$pass" != "$total" ] || [ "$fail" != "0" ] || [ "$solution_exit" != "0" ]; then - echo " WRONG. Output of ./check in solution/:"; cat solution.log; failed=1 + echo " WRONG. Output of ./check in solution/:"; cat "$logs/solution.log"; failed=1 fi echo "== $project/solution: ./mvnw verify" -if (cd "$project/solution" && ./mvnw -B -q verify) > verify.log 2>&1; then +if (cd "$project/solution" && ./mvnw -B -q verify) > "$logs/verify.log" 2>&1; then echo " green" else - echo " FAILED:"; tail -n 80 verify.log; failed=1 + echo " FAILED:"; tail -n 80 "$logs/verify.log"; failed=1 fi -rm -f start.log solution.log verify.log exit $failed diff --git a/README.md b/README.md index 484b4b7..026b47a 100644 --- a/README.md +++ b/README.md @@ -68,8 +68,8 @@ A collection of hands-on coding interview projects organized by language. Each p > **Backend concepts:** [java/concepts/](java/concepts/) is a different kind of project: not a timed > round, but one concept taught step by step. Each is broken first (you run it and watch the problem > happen), has challenge tasks and a guided version, tests as acceptance criteria, and `start/` and -> `solution/` folders side by side. There are eight so far, numbered in the suggested order from -> `01-transactional` to `08-idempotency`: see the [list](java/concepts/README.md). +> `solution/` folders side by side. There are eleven so far, numbered in the suggested order from +> `01-transactional` to `11-pagination`: see the [list](java/concepts/README.md). ## Structure @@ -97,7 +97,7 @@ interview-prep/ │ ├── karat-drills/ │ ├── secret-storage/ │ ├── concepts/ -│ │ └── junior-mid/ (01-transactional ... 08-idempotency) +│ │ └── junior-mid/ (01-transactional ... 11-pagination) │ ├── DELIVERY_HERO.md │ └── KARAT.md ├── python/ diff --git a/java/concepts/README.md b/java/concepts/README.md index a95bcb4..8385dfc 100644 --- a/java/concepts/README.md +++ b/java/concepts/README.md @@ -19,6 +19,9 @@ under [`java/`](../). | 06 | Junior / mid | [Thread safety](junior-mid/06-thread-safety/) | 1,000 requests are answered, the counter says 915 | | 07 | Junior / mid | [Locking](junior-mid/07-locking/) | Two buyers both get the last item in stock | | 08 | Junior / mid | [Idempotency](junior-mid/08-idempotency/) | One payment is retried and the customer is charged twice | +| 09 | Junior / mid | [Isolation levels](junior-mid/09-isolation-levels/) | A bank statement whose lines add up to 1000 and whose total says 1100 | +| 10 | Junior / mid | [Constraints and races](junior-mid/10-constraints-and-races/) | Two signups with the same email both succeed | +| 11 | Junior / mid | [Pagination](junior-mid/11-pagination/) | Page 5,000 reads 100,000 rows to return 20 | The numbers are the suggested order. Each project stands on its own, so you can start anywhere. diff --git a/java/concepts/ci-projects.json b/java/concepts/ci-projects.json index 5bd5378..4d2e2a3 100644 --- a/java/concepts/ci-projects.json +++ b/java/concepts/ci-projects.json @@ -6,5 +6,8 @@ { "path": "java/concepts/junior-mid/05-rest-and-error-handling", "startPass": 13, "total": 56 }, { "path": "java/concepts/junior-mid/06-thread-safety", "startPass": 18, "total": 29 }, { "path": "java/concepts/junior-mid/07-locking", "startPass": 7, "total": 18 }, - { "path": "java/concepts/junior-mid/08-idempotency", "startPass": 15, "total": 32 } + { "path": "java/concepts/junior-mid/08-idempotency", "startPass": 15, "total": 32 }, + { "path": "java/concepts/junior-mid/09-isolation-levels", "startPass": 22, "total": 31 }, + { "path": "java/concepts/junior-mid/10-constraints-and-races", "startPass": 19, "total": 35 }, + { "path": "java/concepts/junior-mid/11-pagination", "startPass": 15, "total": 35 } ] diff --git a/java/concepts/junior-mid/09-isolation-levels/INTERVIEW_TASKS.md b/java/concepts/junior-mid/09-isolation-levels/INTERVIEW_TASKS.md new file mode 100644 index 0000000..3327d5d --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/INTERVIEW_TASKS.md @@ -0,0 +1,318 @@ +# Interview Tasks — Isolation Levels + +> **In `start/`, `./check` FAILS on purpose: 22 of 31 checks pass.** Tasks 2, 4 and 6 turn the other +> 9 green. Tasks 1, 3, 5, 7 and 8 are inspection tasks: you run things, look, and answer questions. + +Do the tasks in order. Every fix is followed by an inspection task: a green test tells you the fix +works, the inspection tells you **why**, and the why is what an interviewer asks for. + +Stuck, or want the explanation? The same task number in [`TASKS_GUIDED.md`](TASKS_GUIDED.md) walks +you through it with the expected output. + +Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`. + +**Rules:** work in `start/`. Never edit, delete or disable a test. Do not change anything in +`demo/` or `checkpoint/`. + +**The data:** alice has a current account (id 1) with 500 and a savings account (id 2) with 500. +Every demo run and every test starts from there. + +**The demo has two modes.** Without `--level` it runs the application's code, so it shows what your +`@Transactional` settings do. With `--level` it runs the same anomaly as plain SQL at that level. + +--- + +## Task 1: See the Statement That Does Not Add Up (15 min) + +**Story:** *A customer sends a screenshot of her statement: current 500, savings 500, total 1100. +Nothing is in the error log. Before you change anything, reproduce it and find out what the database +did.* + +**Steps:** +1. `docker compose up -d`, then `./demo`. Do the lines add up to the total? Which isolation level + did the application's transaction run at? Nobody chose it: where does it come from? +2. Open `StatementService.statement`. It is one transaction. Match the three queries to the + timeline. Between which two did session B commit? +3. `./demo --anomaly phantom`. What is different about what session B does? What is wrong with the + statement this time? +4. `./demo --anomaly non-repeatable-read --level read-committed` and + `./demo --anomaly phantom --level read-committed`. This is the same thing in plain SQL. In each + one, which statement does session A run twice, and what changes between the two runs? +5. Maybe a lower level is even worse. `./demo --anomaly dirty-read --level read-uncommitted`. What + does session A read while B's change is uncommitted? What does `show transaction_isolation` say? + +**Acceptance Criteria** (`./check 1`, already passing: these tests document what Postgres does) +- [ ] You can name the two anomalies and say what the difference between them is +- [ ] You can say what the default isolation level is in Postgres, and what one query can and cannot + see at that level +- [ ] You can explain why `@Transactional` alone did not protect the statement +- [ ] You can say what READ UNCOMMITTED does in Postgres +- [ ] The five tests in `ReadCommittedIT` pass + +**Hints:** +- Non-repeatable read: a row you already read has **changed**. Phantom: a row you had not seen + **appeared** (or one you saw disappeared) +- A transaction groups your writes. What it lets you see of other people's writes is a separate + setting + +--- + +## Task 2: Fix the Statement With REPEATABLE READ (10 min) + +**Story:** *The statement must describe one moment in time. Whatever commits while it is being +built must not show up in half of it. Fix `StatementService.statement`.* + +**Acceptance Criteria** (`./check 2`) +- [ ] A deposit commits between the queries, and the lines still add up to the total + — `StatementIT.aDepositInTheMiddleDoesNotBreakTheStatement` +- [ ] An account is opened between the queries, and the count still matches the lines + — `StatementIT.aNewAccountInTheMiddleDoesNotBreakTheStatement` +- [ ] All of its queries run in one REPEATABLE READ transaction + — `StatementIT.statementRunsAtRepeatableRead` +- [ ] The next statement shows the deposit — `StatementIT.theNextStatementSeesTheDeposit` (already + passing: keep it that way) +- [ ] `./demo` and `./demo --anomaly phantom` print `RESULT: OK` +- [ ] The baseline tests still pass (`./check`) + +**Hints:** +- `@Transactional` has an `isolation` attribute +- The method only reads. Keep `readOnly = true` +- Could you also fix it without touching the isolation level? How many queries would you need? + +--- + +## Task 3: Inspect the Snapshot (15 min) + +**Story:** *Your fix passes the tests. Now prove you know why.* + +**Steps:** +1. You need two terminals. In the first: `./demo --level read-committed --pause`. While it waits, + in the second: `./inspect`. Find session A. Is `snapshot_xmin` filled in? +2. The same with `./demo --level repeatable-read --pause`. What is in `snapshot_xmin` now? Look at + the `xmin` of account 1 under ACCOUNTS. Which transaction wrote the balance of 600, and can + session A see it? +3. `./demo --pause` (the application this time), and `./inspect`. Which level does the `bank-app` + session report? Is it holding a snapshot? +4. `./demo --anomaly dirty-read --level repeatable-read --pause`, and `./inspect`. Session A has run + `begin` but no query yet. Does it hold a snapshot? So when exactly is the snapshot taken? +5. Session A in step 2 never saw the 600. When will it? Which test proves it? + +**Acceptance Criteria** (no tests: you answer) +- [ ] You can say what a snapshot is, and when a REPEATABLE READ transaction takes it +- [ ] You can say when a READ COMMITTED transaction takes a snapshot, and how long it keeps it +- [ ] You can explain why nobody had to wait: not the deposit, not the statement +- [ ] You can say whether REPEATABLE READ allows phantoms in Postgres, and what the SQL standard says +- [ ] You can name one cost of a transaction that holds a snapshot for a long time + +--- + +## Task 4: Stop the Lost Update, and Retry the Serialization Failure (25 min) + +**Story:** *Two withdrawals of 100 from the same account were paid out, and the balance went from +500 to 400. A snapshot fixed the statement, so use it here too: `Withdrawer.withdraw` at REPEATABLE +READ. Then deal with what the database does to the loser. Fix `Withdrawer`, then +`WithdrawalService`.* + +**Acceptance Criteria** (`./check 4`) +- [ ] One attempt that loses the race fails with Spring's `CannotAcquireLockException`, caused by + SQLSTATE `40001` — `LostUpdateIT.theLosingAttemptFailsWithCannotAcquireLockException` +- [ ] Two withdrawals of 100 from the same account both go through, one on its second attempt, and + the balance is 300 — `LostUpdateIT.bothWithdrawalsGoThroughAndNothingIsLost` +- [ ] When Postgres cancels the transaction, the withdrawal is tried again and succeeds + — `WithdrawalServiceRetryTest.retriesAfterASerializationFailure` +- [ ] After 3 cancelled attempts it stops and throws `WithdrawalConflictException` + — `WithdrawalServiceRetryTest.givesUpAfterThreeAttempts` +- [ ] Insufficient funds is not retried — `WithdrawalServiceRetryTest.doesNotRetryInsufficientFunds` + (already passing: keep it that way) +- [ ] `WithdrawalService` is not `@Transactional` + — `WithdrawalServiceRetryTest.theRetryLoopIsOutsideTheTransaction` (already passing) +- [ ] `./demo --anomaly lost-update` prints `RESULT: OK` + +**Hints:** +- Change the isolation level first and run `./demo --anomaly lost-update` before writing the retry. + Read what session A gets +- `CannotAcquireLockException` is a `ConcurrencyFailureException`. Catch that +- The retry must run a **new transaction**. Why is the loop in `WithdrawalService` and not in + `Withdrawer`? + +--- + +## Task 5: Inspect the Serialization Failure (15 min) + +**Story:** *Same again: the tests are green, now show what the database does.* + +**Steps:** +1. `./demo --anomaly lost-update --level repeatable-read`. Which statement fails, in which session? + Write down the SQLSTATE and the message. Why did session B, which did exactly the same thing, + not fail? +2. `./demo --anomaly lost-update --level read-committed`. Same steps, no error. What did the same + `update` do this time? +3. Look at `Withdrawer.withdraw`. The exception does not come from the line that sets the balance. + Where does it come from, and what does that mean for a `try`/`catch` inside this method? +4. `./demo --anomaly lost-update` (your fixed application). Which isolation level does attempt 2 + report, and which balance does it start from? Where did that number come from? +5. Suppose `Withdrawer.withdraw` also sent an email "you withdrew 100" before returning. What + happens to that email when the transaction is cancelled and run again? + +**Acceptance Criteria** (no tests: you answer) +- [ ] You can quote the SQLSTATE and the message, and say which transaction gets it +- [ ] You can name the exception Spring raises, and its parent that you catch +- [ ] You can explain why the retry must be a new transaction that reads again +- [ ] You can explain why the retry cannot live inside the `@Transactional` method +- [ ] You can say what must not be inside a transaction that may be retried + +--- + +## Task 6: Fix the Write Skew With SERIALIZABLE (15 min) + +**Story:** *Now the two withdrawals come from different accounts: 800 from current, 800 from +savings, at the same time. Both pass the check "the accounts together hold at least 800". The +accounts end at -600. Your REPEATABLE READ fix from Task 4 is in place and did nothing. Fix +`Withdrawer.withdraw`.* + +**Acceptance Criteria** (`./check 6`) +- [ ] 800 from current and 800 from savings at the same time: one goes through, the other is + refused, the accounts keep 200 — `WriteSkewIT.onlyOneOfTheTwoWithdrawalsGoesThrough` +- [ ] Every attempt runs in a SERIALIZABLE transaction — `WriteSkewIT.everyAttemptRunsAtSerializable` +- [ ] `./demo --anomaly write-skew` prints `RESULT: OK` +- [ ] Task 4 is still green (`./check 4`) + +**Hints:** +- Run `./demo --anomaly write-skew` first. Which rows does each session write? Is any row written + twice? +- `./demo --anomaly write-skew --level repeatable-read`, then `--level serializable` +- The retry from Task 4 is already there. Does it need to change? + +--- + +## Task 7: Inspect SERIALIZABLE (15 min) + +**Story:** *SERIALIZABLE sounds like "one at a time". Find out what Postgres really does.* + +**Steps:** +1. `./demo --anomaly write-skew --level serializable`. Which statement fails? Read the `Detail` and + the `Hint`. Did any session wait for the other one? +2. `./demo --anomaly write-skew --level serializable --pause`, and `./inspect` in a second terminal. + Look at PREDICATE LOCKS. Who holds one, and what does it cover? Is `waits_for_pid` filled in for + anyone? +3. `./demo --anomaly write-skew --pause` (the application), and `./inspect`. One predicate lock + belongs to a session that is not in the SESSIONS list. Whose is it, and why is it still there? +4. In step 1 the transaction failed at `commit`. Read `WriteSkewIT.aFailedCommitIsAlsoCannotAcquireLockException`. + Does the retry need a second `catch` for that case? +5. Read `WriteSkewIT.anInnerIsolationLevelIsIgnored`. A colleague calls `withdrawer.withdraw` from + a method that is already `@Transactional`. Which level does the withdrawal run at? +6. The reporting team keeps its transactions at READ COMMITTED. Does your SERIALIZABLE withdrawal + protect the rule against a READ COMMITTED transaction that does the same read-check-write? + +**Acceptance Criteria** (no tests: you answer) +- [ ] You can explain what SERIALIZABLE guarantees, in one sentence +- [ ] You can explain how Postgres does it without making anyone wait +- [ ] You can say at which moments a serializable transaction can be cancelled +- [ ] You can name two costs of SERIALIZABLE +- [ ] You can explain why the isolation level has to be set where the transaction starts + +--- + +## Task 8: Compare Every Level, and Isolation Levels vs Locking (20 min) + +**Story:** *"Which isolation level would you use?" and "Why not just lock the row?" are the +interview questions. Collect the evidence, then answer them.* + +**Steps:** +1. `./demo --matrix`. Which two columns are identical? Which level is the first with no `HAPPENS`? + Compare the table with the one the SQL standard gives (it is in the guided task). Where is + Postgres stricter than the standard asks? +2. `./demo --anomaly write-skew --for-update`. This is READ COMMITTED. What did session B do when + it tried to read? What did it read in the end? +3. Put that next to `./demo --anomaly write-skew --level serializable`. In which run does somebody + wait? In which run is somebody cancelled? +4. `./demo --anomaly write-skew --for-update --pause`, and `./inspect`. Find `waits_for_pid`. Look + at `xmax` of the two account rows. +5. A new rule arrives: "a customer may have at most 3 accounts". Two sessions each count 2 accounts + and each insert one. Can `SELECT ... FOR UPDATE` on the existing rows stop that? Can + SERIALIZABLE? +6. Decide, and say why: which would you use for the statement, for the withdrawal, and for + "decrement the stock of a product" from [`../07-locking`](../07-locking/)? + +**Acceptance Criteria** (`./check 8`, already passing, and you answer) +- [ ] You can draw the table: four levels, which anomalies each one allows in Postgres +- [ ] You can say in one sentence each what an isolation level is and what a lock is +- [ ] You can say what the "loser" experiences with a lock, and with a higher isolation level +- [ ] You can give one situation where `SELECT ... FOR UPDATE` is the better tool, and one where + only SERIALIZABLE works +- [ ] `IsolationVsLockingIT` passes + +--- + +## Questions to Ask Afterwards + +Answer out loud, in full sentences, before reading the answer in brackets. + +- What are the four isolation levels? (READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, + SERIALIZABLE, weakest first. Each one rules out more of what a transaction can observe of other + transactions that run at the same time.) +- What is the default in Postgres? (READ COMMITTED. Every statement sees what was committed when + that statement started. Two statements in the same transaction can see different data. Spring's + `@Transactional` without an `isolation` attribute uses the database default.) +- Dirty read, non-repeatable read, phantom read: what is each? (Dirty: you read a change that was + never committed. Non-repeatable: you read a row twice and it changed in between, because someone + committed. Phantom: you run a query twice and a row appeared or disappeared, because someone + committed an insert or delete.) +- Does READ UNCOMMITTED give you dirty reads in Postgres? (No. Postgres accepts the level and runs + it as READ COMMITTED. There is no way to read uncommitted data in Postgres.) +- What does REPEATABLE READ do in Postgres? (The transaction takes one snapshot at its first query + and reads from it until it ends. So no non-repeatable reads and, in Postgres, no phantoms either, + although the SQL standard would allow them. If it tries to update a row that someone changed after + the snapshot, it is cancelled with SQLSTATE 40001.) +- What is write skew? (Two transactions read the same data, each makes a decision from it, and each + writes a different row. No row is written twice, so nothing looks like a conflict, but the two + decisions together break a rule. REPEATABLE READ allows it. SERIALIZABLE does not.) +- What does SERIALIZABLE guarantee? (The result is the same as if the transactions had run one + after another, in some order. Postgres does not run them one at a time and does not make them + wait. It tracks what each one read, and when the overlap cannot be explained by any order, it + cancels one with 40001.) +- What do you do with a 40001? (Run the whole transaction again, a limited number of times. It is + not a bug in the request. In Spring it arrives as `CannotAcquireLockException`; catch its parent + `ConcurrencyFailureException`. In production add a short random delay between attempts.) +- Where does the retry go? (Outside the transaction, in a different bean. A cancelled transaction + cannot be continued, so every attempt needs a new one, and a call to a method on `this` does not + go through the transactional proxy. With Hibernate the UPDATE is sent at commit, so the exception + comes out of the call to the transactional method, not from a line inside it.) +- What must not be in a transaction that can be retried? (Anything the database cannot roll back: + an email, an HTTP call, a message. It would happen once per attempt. Do it after the commit.) +- Is an isolation level a lock? (No. An isolation level is a setting of one transaction: what it may + see. A lock is a claim on specific rows that makes other transactions wait. With a lock the loser + waits and then carries on with fresh data. A higher isolation level in Postgres adds no waiting: + the loser is cancelled and must retry.) +- When `SELECT ... FOR UPDATE` and when SERIALIZABLE? (Lock when you know exactly which rows you + are going to change and conflicts are common: a stock counter, a seat. Use SERIALIZABLE when the + decision depends on a set of rows, or on rows that do not exist yet, which you cannot lock. Often + the best answer is neither: one conditional UPDATE, or a constraint.) +- You put `@Transactional(isolation = SERIALIZABLE)` on a method and it still runs at READ + COMMITTED. Why? (It was called from inside a transaction that was already open. The method joined + it, and a transaction has one level, fixed when it starts. Spring ignores the inner setting + without telling you.) +- Is SERIALIZABLE on one method enough? (No. Postgres only guarantees it between transactions that + are all SERIALIZABLE. A READ COMMITTED transaction that does the same read-check-write can still + cause write skew against it.) +- What does a long REPEATABLE READ transaction cost? (It pins a snapshot. While it is open, VACUUM + cannot remove any row version that the snapshot might still need, so tables bloat. Keep them + short.) +- Do other databases behave the same? (No. The level names come from the SQL standard, the + behaviour does not. MySQL's InnoDB, for example, defaults to REPEATABLE READ, not READ COMMITTED. + Always say which database you are talking about.) + +## Tips for Interviewers + +- The most common wrong answer is a recited table: "READ UNCOMMITTED allows dirty reads, ..." Ask + "in Postgres?". A candidate who has run it knows that the first two levels are the same level. +- Ask the candidate to predict `./demo --anomaly write-skew --level repeatable-read` before running + it. Most people who say "REPEATABLE READ gives me a consistent view" expect it to be safe. +- "I would set it to SERIALIZABLE" is half an answer. The other half is the retry. Ask what the + user sees when the transaction is cancelled, and watch where the candidate puts the loop. +- A retry loop inside the `@Transactional` method never runs: the exception appears at commit, after + the method has returned. It is the bug that separates levels. +- Listen for "isolation level" and "lock" being used as the same word. Task 8 steps 2 and 3 are the + quickest way to pull them apart: same scenario, one run waits, the other is cancelled. +- For senior candidates, ask Task 8 step 5, then ask for a third option. A good answer is a unique + constraint or a counter row that every writer has to lock. diff --git a/java/concepts/junior-mid/09-isolation-levels/README.md b/java/concepts/junior-mid/09-isolation-levels/README.md new file mode 100644 index 0000000..a0aa555 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/README.md @@ -0,0 +1,180 @@ +# Isolation Levels — What One Transaction Sees of Another + +> **In `start/`, `./check` FAILS on purpose: 22 of 31 checks pass.** That is the exercise, not a +> broken checkout. Tasks 2, 4 and 6 turn the other 9 green. + +A bank prints a statement: current account 500, savings 500, **total 1100**. Nothing crashed. A +deposit was committed between the query that read the lines and the query that read the total. This +project lets you watch that happen, step by step, in two database sessions. Then you raise the +isolation level, meet the error that comes with it (SQLSTATE `40001`), and handle it. + +It answers the interview questions students most often get wrong: + +- "What are the four isolation levels, and which anomalies does each one allow?" +- "What is the default in Postgres? Does READ UNCOMMITTED give you dirty reads there?" +- "What is the difference between a non-repeatable read and a phantom read?" +- "What is write skew, and why does REPEATABLE READ not stop it?" +- "What happens when a SERIALIZABLE transaction fails? Where does the retry go?" +- "Isolation level or `SELECT ... FOR UPDATE`: what is the difference?" + +## Tech Stack + +- **Java 25**, **Spring Boot 4**, Spring Data JPA (Hibernate 7) +- **PostgreSQL 17** in Docker +- JUnit 5, AssertJ, Testcontainers + +## What you need + +- JDK 25 +- Docker, running + +## Getting Started + +Work in `start/`. Commands are shown for macOS and Linux; on Windows type `.\demo` where you see +`./demo` (same for `inspect` and `check`). + +```bash +cd start +docker compose up -d # Postgres on port 5448 +./demo # watch a statement that does not add up +./check # 22 of 31 pass: that is your starting point +``` + +The first run downloads Maven and the dependencies, so it takes a minute or two. + +When you are finished: `docker compose down`. + +## The three tools + +### `./demo` — see what happens + +Two sessions, A and B, run their steps in a fixed order, so the anomaly happens on every run. The +demo prints each step and ends with a `RESULT:` line. Every run starts from the same data: alice +has a current account (id 1) with 500 and a savings account (id 2) with 500. + +It has two modes: + +- **Without `--level` it runs the application's code** (`StatementService`, `WithdrawalService`). + What you see depends on the `@Transactional` settings in the code, so this is how you see your + fix work. +- **With `--level` it runs the same anomaly as plain SQL** at the level you choose. This is what + Postgres itself does, whatever the Java code says. + +``` +./demo the application's statement while a deposit commits +./demo --anomaly phantom dirty-read | non-repeatable-read | phantom | lost-update | write-skew +./demo --anomaly write-skew --level serializable read-uncommitted | read-committed | repeatable-read | serializable +./demo --anomaly write-skew --for-update plain SQL with SELECT ... FOR UPDATE instead of a higher level +./demo --matrix every anomaly at every level, as one table +./demo --pause hold the transactions open for 15 seconds, for ./inspect +./demo --help +``` + +### `./inspect` — look inside the database + +Shows the account rows with the transaction that wrote each one (`xmin`), every session that is +inside a transaction, its isolation level, whether it is holding a snapshot, which session it is +waiting for, and the predicate locks of SERIALIZABLE sessions. Run it in a second terminal while +`./demo --pause` is running. `./inspect --watch` refreshes every second. + +### `./check` — are the acceptance criteria met? + +`./check 2` runs the tests for Task 2 and prints one line per criterion. `./check` runs everything. +`./mvnw verify` runs the same tests the usual Maven way. + +The tests are the acceptance criteria. **Never edit, delete or disable a test.** + +## The code + +``` +start/src/main/java/com/amigoscode/isolation/ +├── statement/ +│ ├── StatementService.java three queries in one transaction. BUG 1 IS HERE +│ └── Statement.java the lines, the account count and the total +├── withdrawal/ +│ ├── WithdrawalService.java calls Withdrawer; the retry goes here +│ └── Withdrawer.java one transaction: read, check, write. BUGS 2 AND 3 ARE HERE +├── account/ the entity and the queries +├── checkpoint/ a named point between a read and a write, where the demo and +│ the tests let the other session in. Nothing to change here +└── demo/ the demo and inspect tools. Nothing to change here +``` + +The bank's rule for withdrawals: **one account may go below zero, as long as all of the customer's +accounts together stay at zero or above.** + +## Two ways to work + +- **[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md)**: challenge mode. A story, acceptance criteria and + hints for each task. Use this if you want to work it out yourself. +- **[`TASKS_GUIDED.md`](TASKS_GUIDED.md)**: the same eight tasks, step by step, with the output you + should see and an explanation of why. Use this to learn the concept, or when you are stuck. + +Both files use the same task numbers. + +| Task | What you do | Checked by | +|---|---|---| +| 1 | See the statement that does not add up | `./check 1` (passes: it documents what Postgres does) | +| 2 | Fix the statement with REPEATABLE READ | `./check 2` | +| 3 | Inspect the snapshot | you answer questions | +| 4 | Stop the lost update, and retry the serialization failure | `./check 4` | +| 5 | Inspect the serialization failure | you answer questions | +| 6 | Fix the write skew with SERIALIZABLE | `./check 6` | +| 7 | Inspect SERIALIZABLE | you answer questions | +| 8 | Compare every level, and isolation levels vs locking | `./check 8` (passes) and you answer questions | + +## Isolation levels are not locks + +Students mix these up in interviews, so keep them apart from the start. + +| | Isolation level | Lock (`SELECT ... FOR UPDATE`) | +|---|---|---| +| What it is | A setting of the **transaction**: what it may see of other transactions | A claim on **specific rows**: nobody else may change or lock them until I finish | +| Who is affected | Only the transaction that sets it | Every other transaction that wants those rows | +| What the other one experiences | No extra waiting. In Postgres a conflict **cancels** one transaction with SQLSTATE `40001` | It **waits** until the lock is released | +| What the application must do | Retry the cancelled transaction | Keep the transaction short, lock in a consistent order | +| Reach for it when | The decision depends on many rows, or on rows that do not exist yet. Conflicts are rare | You know exactly which rows you will change, and redoing the work is expensive or conflicts are common | + +Locking, optimistic and pessimistic, has its own project: [`../07-locking`](../07-locking/). + +## Solution + +`solution/` is the same project with every task done: `cd solution && ./check` prints 31 of 31. + +To start again from scratch: `git checkout -- start` (this throws away your changes in `start/`). + +
+Spoiler: the three bugs and the fixes + +**Bug 1, the statement (Task 2).** `StatementService.statement` runs three queries in a READ +COMMITTED transaction (the Postgres default). Each query sees whatever is committed when that query +starts. A deposit between them is a **non-repeatable read**, a new account is a **phantom read**. +Fix: `@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)`. The transaction takes +one snapshot at its first query and every later query reads from it. + +**Bug 2, the lost update (Task 4).** `Withdrawer.withdraw` reads the balance, subtracts in Java and +writes the result. Two withdrawals from the same account both read 500 and both write 400. At +REPEATABLE READ Postgres cancels the second writer: SQLSTATE `40001`, "could not serialize access +due to concurrent update". Spring raises `CannotAcquireLockException`. `WithdrawalService` catches +it (as `ConcurrencyFailureException`) and runs the withdrawal again in a **new transaction**, up to +3 attempts, then throws `WithdrawalConflictException`. + +**Bug 3, the write skew (Task 6).** Two withdrawals from **different** accounts each check the +combined balance, each see 1000, each write their own row. No row is written twice, so REPEATABLE +READ has nothing to object to, and the accounts end at -600. Fix: +`@Transactional(isolation = Isolation.SERIALIZABLE)`. Postgres tracks what each transaction read, +and cancels one of them with `40001`. The retry from Task 4 handles it. + +**What each level stops in Postgres** (`./demo --matrix`): + +| | read uncommitted | read committed | repeatable read | serializable | +|---|---|---|---|---| +| dirty read | no | no | no | no | +| non-repeatable read | HAPPENS | HAPPENS | no | no | +| phantom read | HAPPENS | HAPPENS | no | no | +| lost update | HAPPENS | HAPPENS | 40001 | 40001 | +| write skew | HAPPENS | HAPPENS | HAPPENS | 40001 | + +READ UNCOMMITTED is accepted and runs as READ COMMITTED: Postgres has no dirty reads. + +
diff --git a/java/concepts/junior-mid/09-isolation-levels/TASKS_GUIDED.md b/java/concepts/junior-mid/09-isolation-levels/TASKS_GUIDED.md new file mode 100644 index 0000000..1e151aa --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/TASKS_GUIDED.md @@ -0,0 +1,890 @@ +# Guided Tasks — Isolation Levels + +The same eight tasks as [`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md), step by step: the command to +run, the output you should see, why it happens, and the change to make. + +Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`. + +Process ids (`pid`), transaction ids (`xmin`, `own_xid`) and times will differ on your machine. The +steps, the values and the `RESULT` line should match: the demo does not race two threads, it runs +the steps of two sessions in a fixed order. + +**Before you start** + +```bash +cd start +docker compose up -d +``` + +**How to read the demo.** Session A is on the left, session B is indented. `->` is what came back. +`#` is something the application works out in Java, outside the database. + +**Two modes.** `./demo` without `--level` runs the application's code, so it changes when you change +the code. `./demo --level ...` runs the same anomaly as plain SQL at the level you ask for, whatever +the code says. + +--- + +## Task 1: See the Statement That Does Not Add Up + +No code in this task. You are collecting evidence. + +### Run it + +```bash +./demo +``` + +### What you should see + +``` +Anomaly: non-repeatable-read | running the application: StatementService.statement +Session A is the application, building alice's statement: the lines first, then the count and the total. +Session B deposits 100 and commits in between. +Before: alice has two accounts, current (id 1) = 500 and savings (id 2) = 500. + + A | StatementService.statement("alice") + A | -> transaction isolation level: read committed + A | -> query 1 done: the lines are read + B | begin + B | update account set balance = balance + 100 where id = 1 + B | -> 1 row + B | commit + A | -> queries 2 and 3 done: the count and the total are read + +The statement the customer gets: + current 500 + savings 500 + ------------------- + 2 accounts 1100 + +RESULT: NON-REPEATABLE READ. The lines add up to 1000, the total says 1100. The queries of one transaction saw two different moments. +``` + +500 + 500 = 1100. Nothing crashed and nothing was logged. Every number on that statement was true +at some moment. They were just not true at the same moment. + +### Find it in the code + +Open `StatementService.statement`: + +```java +@Transactional(readOnly = true) +public Statement statement(String owner) { + List lines = accounts.findByOwnerOrderById(owner)...; // QUERY 1: the lines + checkpoint.reached(Checkpoint.LINES_READ); // ...time passes... + long accountCount = accounts.countByOwner(owner); // QUERY 2: how many accounts + long total = accounts.totalBalance(owner); // QUERY 3: the total + return new Statement(owner, lines, accountCount, total); +} +``` + +It is `@Transactional`, and it still went wrong. A transaction makes **your writes** succeed or fail +together. What you can **see** of other people's writes is a different setting: the **isolation +level**. Nobody set one here, so the transaction ran at the database default. The demo printed it: +`read committed`. + +At READ COMMITTED every **statement** sees what was committed at the moment that statement started. +Query 1 started before the deposit, queries 2 and 3 after it. + +(`checkpoint.reached(...)` does nothing in production. The demo and the tests use it to let session +B in at exactly that point. Without it you would have to be unlucky to see the bug, which is what +makes it so hard to find in real life.) + +### The same thing in plain SQL + +```bash +./demo --anomaly non-repeatable-read --level read-committed +``` + +``` + A | begin isolation level read committed + A | select balance from account where id = 1 + A | -> 500 + B | begin + B | update account set balance = balance + 100 where id = 1 + B | -> 1 row + B | commit + A | select balance from account where id = 1 + A | -> 600 + A | commit + +RESULT: NON-REPEATABLE READ. Session A read the same row twice in one transaction and got 500, then 600. +``` + +Same transaction, same query, same row, two answers. That is a **non-repeatable read**. + +### A row that was not there + +```bash +./demo --anomaly phantom +``` + +``` + B | insert into account (id, owner, name, balance) values (3, 'alice', 'holiday', 250) + ... +The statement the customer gets: + current 500 + savings 500 + ------------------- + 3 accounts 1250 + +RESULT: PHANTOM READ. The statement lists 2 accounts and then says there are 3. The lines add up to 1000, the total says 1250. +``` + +This time no row that A had read was changed. A **new row** appeared that matches A's query. That is +a **phantom read**. In plain SQL: `./demo --anomaly phantom --level read-committed` counts 2 rows, +then 3. + +| | What happened to the data A reads | +|---|---| +| Non-repeatable read | A row A already read was **updated** (or deleted) and committed | +| Phantom read | A row A had never seen was **inserted** and committed, and now matches A's query | + +### Is the level below even worse? + +The textbook says READ UNCOMMITTED allows **dirty reads**: reading a change that was never +committed. Try it: + +```bash +./demo --anomaly dirty-read --level read-uncommitted +``` + +``` + A | begin isolation level read uncommitted + A | show transaction_isolation + A | -> read uncommitted + B | begin + B | update account set balance = 0 where id = 1 + B | -> 1 row + A | select balance from account where id = 1 + A | -> 500 + B | rollback + A | commit + +RESULT: NO DIRTY READ. Session A read 500 while B's uncommitted 0 was in the table. Postgres accepts READ UNCOMMITTED and runs it as READ COMMITTED. +``` + +Postgres takes the level, even reports it back, and then behaves as READ COMMITTED. **There are no +dirty reads in Postgres, at any level.** If an interviewer asks "which level allows dirty reads?", +the textbook answer is READ UNCOMMITTED, and the good answer adds "but not in Postgres". + +### Check + +```bash +./check 1 +``` + +``` + [PASS] READ COMMITTED: non-repeatable read. One transaction reads a balance twice and gets 500, then 600 + ... + 5 of 5 pass +``` + +These pass on purpose. They pin down what Postgres does, so you can see what the fixes change. + +--- + +## Task 2: Fix the Statement With REPEATABLE READ + +**The idea:** the three queries must all look at the database as it was at one moment. That is what +REPEATABLE READ gives you: the transaction takes one **snapshot** and every query reads from it. + +Before you start, `./check 2` says 3 of 6 pass. The three that pass describe Postgres. The three +that fail describe your code. + +### The change + +In `StatementService`: + +```java +@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ) +public Statement statement(String owner) { +``` + +Import `org.springframework.transaction.annotation.Isolation`. That is the whole fix. + +### After + +```bash +./demo +``` + +``` + A | StatementService.statement("alice") + A | -> transaction isolation level: repeatable read + ... +The statement the customer gets: + current 500 + savings 500 + ------------------- + 2 accounts 1000 + +RESULT: OK. 2 lines, 2 accounts, and the lines add up to the total: 1000. What session B committed is not in this statement. It will be in the next one. +``` + +Three things to notice: + +- **B was not blocked.** Its deposit went through and is committed. A just does not look at it. +- **The statement is not "wrong" for showing 500.** It is a correct picture of the moment the + transaction took its snapshot. The next statement shows 600. +- `./demo --anomaly phantom` is also `OK` now. The SQL standard lets REPEATABLE READ have phantoms. + **Postgres does not have them**: a snapshot does not contain rows that were inserted later. + +`./check 2` now says 6 of 6 pass. + +### You did not have to use an isolation level + +One statement always sees one moment, even at READ COMMITTED. If you read the lines once and add +them up in Java, or fetch everything in one query, there is no second query to disagree with the +first. That is often the simplest fix. You need REPEATABLE READ when one piece of work really needs +several queries that must agree, like a report or an export. + +--- + +## Task 3: Inspect the Snapshot + +You need two terminals, both in `start/`. + +### Step 1: READ COMMITTED holds nothing between statements + +Terminal 1: `./demo --level read-committed --pause`. Terminal 2, while it says "Paused for 15 +seconds": `./inspect`. + +``` +SESSIONS INSIDE A TRANSACTION (snapshot_xmin is filled in while the session holds a snapshot) + pid session state snapshot_xmin own_xid waits_for_pid in_transaction_ms last_statement + ---- ----------------------- ------------------- ------------- ------- ------------- ----------------- ---------------------------------------- + 2844 demo A (read committed) idle in transaction 8958 select balance from account where id = 1 +``` + +Session A is in the middle of a transaction and has already run a SELECT. `snapshot_xmin` is empty: +it is holding **no snapshot**. At READ COMMITTED a snapshot lives for one statement. The next +statement takes a new one, and sees whatever is committed by then. + +(Postgres has no column that shows another session's isolation level. The demo's sessions put their +own level into their name, which is why you can read it here.) + +### Step 2: REPEATABLE READ keeps one + +`./demo --level repeatable-read --pause` in terminal 1, `./inspect` in terminal 2: + +``` +ACCOUNTS (what a NEW transaction would read. xmin = the transaction that wrote this version of + the row, xmax = a transaction that has locked or replaced it, 0 = none) + id name balance xmin xmax + -- ------- ------- ---- ---- + 1 current 600 965 0 + 2 savings 500 964 0 + +SESSIONS INSIDE A TRANSACTION (snapshot_xmin is filled in while the session holds a snapshot) + pid session state snapshot_xmin own_xid waits_for_pid in_transaction_ms last_statement + ---- ------------------------ ------------------- ------------- ------- ------------- ----------------- ---------------------------------------- + 5071 demo A (repeatable read) idle in transaction 965 8324 select balance from account where id = 1 +``` + +Your numbers will differ. Read them like this: + +- Every transaction that writes gets a number, a **transaction id**. Every row version remembers the + transaction that wrote it: that is `xmin` in ACCOUNTS. The balance of 600 was written by + transaction 965, session B's deposit. +- Session A's `snapshot_xmin` is 965. It means: "my snapshot contains what transactions **before** + 965 committed". Transaction 965 itself is not in it. +- So when A reads account 1 again, Postgres skips the version written by 965 and gives A the older + version, the one with 500. Postgres keeps old versions of rows for exactly this purpose. The + technique is called MVCC, multi-version concurrency control. + +That is also why nobody waited. B wrote a **new version** of the row, A keeps reading the **old +version**. Readers do not block writers and writers do not block readers. + +### Step 3: your application + +`./demo --pause` in terminal 1, `./inspect` in terminal 2: + +``` + 2976 bank-app (repeatable read) idle in transaction 915 ... +``` + +The application's session reports `repeatable read` and holds a snapshot. That is your annotation +at work. + +### Step 4: when is the snapshot taken? + +`./demo --anomaly dirty-read --level repeatable-read --pause`, then `./inspect`: + +``` + 3915 demo A (repeatable read) idle in transaction 13957 show transaction_isolation +``` + +A has run `begin isolation level repeatable read`, and `snapshot_xmin` is still empty. **The +snapshot is taken by the first query, not by `begin`.** + +### Step 5: when does A see the 600? + +In its next transaction. The snapshot ends with the transaction. `StatementIT.theNextStatementSeesTheDeposit` +proves it for the application. + +### What to take away + +- READ COMMITTED: a new snapshot for every statement. +- REPEATABLE READ: one snapshot, taken at the first query, kept until the transaction ends. +- Nobody waits. The price is paid somewhere else: while a snapshot is open, Postgres cannot clean + up row versions that the snapshot might still need. A transaction that stays open for an hour + makes every busy table grow. Keep them short. + +--- + +## Task 4: Stop the Lost Update, and Retry the Serialization Failure + +### Before + +```bash +./demo --anomaly lost-update +``` + +``` + A | WithdrawalService.withdraw(1, 100) + A | -> attempt 1, transaction isolation level: read committed + A | -> funds checked: enough for 100 + B | WithdrawalService.withdraw(1, 100) + ... + B | -> returns 400, the new balance of account 1 + A | -> returns 400, the new balance of account 1 + +RESULT: LOST UPDATE. 2 withdrawals of 100 were paid out, but the balance only went from 500 to 400. +``` + +Open `Withdrawer.withdraw`. It reads the balance, subtracts **in Java**, and writes the result: + +```java +Account account = accounts.findById(accountId)...; // READ this account +long available = accounts.totalBalance(account.getOwner()); // READ all the customer's accounts +if (available < amount) { throw new InsufficientFundsException(...); } // CHECK the rule +checkpoint.reached(Checkpoint.FUNDS_CHECKED); // ...time passes... +account.setBalance(account.getBalance() - amount); // WRITE a value computed from the READ +``` + +Both sessions read 500, both wrote 500 - 100 = 400. The bank paid out 200 and took 100 off the +account. (This is the bug of [`../07-locking`](../07-locking/). There you fixed it with locks. Here +you fix it with an isolation level, and see what is different.) + +### Step 1: REPEATABLE READ + +In `Withdrawer`: + +```java +@Transactional(isolation = Isolation.REPEATABLE_READ) +public long withdraw(long accountId, long amount) { +``` + +Import `org.springframework.transaction.annotation.Isolation`. + +### Look before you go on + +Do not write the retry yet. Run: + +```bash +./demo --anomaly lost-update +``` + +``` + A | WithdrawalService.withdraw(1, 100) + A | -> attempt 1, transaction isolation level: repeatable read + A | -> funds checked: enough for 100 + B | WithdrawalService.withdraw(1, 100) + ... + B | -> returns 400, the new balance of account 1 + A | -> THROWS org.springframework.dao.CannotAcquireLockException + A | -> caused by PSQLException, SQLSTATE 40001: ERROR: could not serialize access due to concurrent update + +Withdrawals paid out: 1 x 100 +Current (id 1): 400 + +RESULT: NOT HANDLED. The data is right, because Postgres cancelled session A's transaction. But the customer got a CannotAcquireLockException. Nothing was wrong with the request: it has to be run again. +``` + +The data is already correct: one withdrawal paid out, balance 400. Session A wanted to update a row +that had changed since A took its snapshot. At READ COMMITTED Postgres lets that through. At +REPEATABLE READ it refuses: A's decision was made from a picture that is no longer true. + +This error has a name and a number: a **serialization failure**, SQLSTATE **`40001`**. It does not +mean the request was wrong. It means "this transaction cannot finish, run it again". + +Note the Java exception. Spring Boot 4 with Hibernate 7 turns `40001` into +`CannotAcquireLockException`. The name is misleading: no lock was involved and nobody waited. Its +parent classes are `PessimisticLockingFailureException`, then `ConcurrencyFailureException`. + +Half a fix: the data is safe and the customer sees a crash. + +### Step 2: retry in WithdrawalService + +Replace the `withdraw` method in `WithdrawalService`: + +```java +public long withdraw(long accountId, long amount) { + for (int attempt = 1; ; attempt++) { + try { + return withdrawer.withdraw(accountId, amount); + } catch (ConcurrencyFailureException e) { + if (attempt == MAX_ATTEMPTS) { + throw new WithdrawalConflictException(accountId, attempt, e); + } + } + } +} +``` + +Import `org.springframework.dao.ConcurrencyFailureException`. + +Three things to notice: + +- **The retry is in `WithdrawalService`, not in `Withdrawer`.** `withdrawer.withdraw(...)` is a call + to another Spring bean, so every attempt goes through the transactional proxy and gets a brand + new transaction, with a new snapshot. A cancelled transaction cannot be continued. If the loop + were inside the `@Transactional` method, it would not even see the exception (Task 5 shows why). +- **Only the serialization failure is retried.** `InsufficientFundsException` is not caught: trying + again cannot put money in the account. +- **It gives up.** After 3 attempts it throws `WithdrawalConflictException`. A retry loop with no + limit can spin for ever under load. + +### After + +```bash +./demo --anomaly lost-update +``` + +``` + B | -> returns 400, the new balance of account 1 + A | -> attempt 2 (a new transaction: the last one did not commit), transaction isolation level: repeatable read + A | -> funds checked: enough for 100 + A | -> returns 300, the new balance of account 1 + +Withdrawals paid out: 2 x 100 +Current (id 1): 300 + +RESULT: OK. 2 x 100 paid out, both accounts together went from 1000 to 800. Session A was cancelled once and ran again in a new transaction. +``` + +`./check 4` now says 8 of 8 pass. Run `./check` too: Task 2 must still be green. + +--- + +## Task 5: Inspect the Serialization Failure + +### Step 1: which statement fails + +```bash +./demo --anomaly lost-update --level repeatable-read +``` + +``` + A | begin isolation level repeatable read + A | select balance from account where id = 1 + A | -> 500 + B | begin isolation level repeatable read + B | select balance from account where id = 1 + B | -> 500 + B | # 500 - 100 = 400, worked out in the application + B | update account set balance = 400 where id = 1 + B | -> 1 row + B | commit + A | # 500 - 100 = 400, worked out in the application + A | update account set balance = 400 where id = 1 + A | -> ERROR, SQLSTATE 40001: could not serialize access due to concurrent update + A | rollback + A | # this transaction was cancelled, so there is nothing to commit +``` + +A and B did exactly the same thing. B committed first, so B won. The rule is **first committer +wins**: the transaction that tries to change a row which someone else changed after its snapshot is +the one that is cancelled. + +### Step 2: the same steps at READ COMMITTED + +```bash +./demo --anomaly lost-update --level read-committed +``` + +No error. A's `update account set balance = 400` simply runs, on top of B's 400. READ COMMITTED has +no snapshot to compare with, so it cannot know that A's 400 was computed from an old 500. + +### Step 3: where the exception comes from + +In `Withdrawer.withdraw`, `account.setBalance(...)` only changes a Java object. Hibernate sends the +UPDATE when the transaction **commits**, which is after the method has returned. So the exception +does not come from any line inside `withdraw`. It comes out of the **call** to +`withdrawer.withdraw(...)`. + +A `try`/`catch` inside the `@Transactional` method would never see it. This is the second reason +the retry has to be outside. + +### Step 4: the retry reads again + +In the `After` output of Task 4, attempt 2 "returns 300". It did not reuse the 500 from attempt 1. +It is a new transaction with a new snapshot, it read 400, and it wrote 400 - 100 = 300. A retry +that reuses values from the failed attempt brings the lost update straight back. + +### Step 5: what must not be inside + +Everything in a cancelled transaction is rolled back by the database. An email, an HTTP call or a +message to a queue is not. If `withdraw` sent an email, the customer would get one per attempt, for +one withdrawal. Whatever cannot be rolled back goes after the commit, outside the method that is +retried. + +### What to take away + +- SQLSTATE `40001` = serialization failure = "run this transaction again". +- Spring: `CannotAcquireLockException`. Catch `ConcurrencyFailureException`. +- The retry is a new transaction that reads everything again, in another bean, with a limit. +- Nobody waited at any point. The loser paid by doing its work twice. + +--- + +## Task 6: Fix the Write Skew With SERIALIZABLE + +### Before + +Your code is at REPEATABLE READ with a retry. Now the two withdrawals use **different** accounts: + +```bash +./demo --anomaly write-skew +``` + +``` + A | WithdrawalService.withdraw(1, 800) + A | -> attempt 1, transaction isolation level: repeatable read + A | -> funds checked: enough for 800 + B | WithdrawalService.withdraw(2, 800) + ... + B | -> returns -300, the new balance of account 2 + A | -> returns -300, the new balance of account 1 + +Withdrawals paid out: 2 x 800 +Current (id 1): -300 +Savings (id 2): -300 +Both together: -600 + +RESULT: WRITE SKEW. Both withdrawals of 800 went through and the accounts hold -600 together. The rule is broken, and neither transaction changed a row the other one changed. +``` + +The rule says the accounts together must stay at 0 or above. They hold -600, and REPEATABLE READ +did not object. + +### Why REPEATABLE READ cannot see it + +```bash +./demo --anomaly write-skew --level repeatable-read +``` + +``` + A | begin isolation level repeatable read + A | select balance from account where owner = 'alice' order by id + A | -> 500, 500 + A | # 500 + 500 = 1000, enough for 800: go ahead + B | begin isolation level repeatable read + B | select balance from account where owner = 'alice' order by id + B | -> 500, 500 + B | # 500 + 500 = 1000, enough for 800: go ahead + A | update account set balance = balance - 800 where id = 1 + A | -> 1 row + B | update account set balance = balance - 800 where id = 2 + B | -> 1 row + A | commit + B | commit + +RESULT: WRITE SKEW. Both sessions saw 1000, both withdrew 800, both committed. ... +``` + +In Task 4 both sessions wrote **the same row**, and that is what REPEATABLE READ checks. Here A +writes row 1 and B writes row 2. No row is written twice. Each decision was right for the snapshot +it was made from. Together they are wrong. + +This is **write skew**: two transactions read overlapping data, decide, and write **different** +rows. The classic example is a hospital rule "at least one doctor must be on call": two doctors +each see two on call, and both sign off. + +### The change + +In `Withdrawer`: + +```java +@Transactional(isolation = Isolation.SERIALIZABLE) +public long withdraw(long accountId, long amount) { +``` + +### After + +```bash +./demo --anomaly write-skew +``` + +``` + A | WithdrawalService.withdraw(1, 800) + A | -> attempt 1, transaction isolation level: serializable + A | -> funds checked: enough for 800 + ... + B | -> returns -300, the new balance of account 2 + A | -> refused, InsufficientFundsException: Cannot withdraw 800 from account 1: the customer's accounts hold 200 in total + +Both together: 200 + +RESULT: OK. 1 x 800 paid out, both accounts together went from 1000 to 200. Session A passed the check, was cancelled, ran again in a new transaction and was refused. +``` + +Session A's first attempt was cancelled with `40001`. The retry you wrote in Task 4 caught it and +ran A again. The second attempt read 200, and 200 is not enough for 800: a clean +`InsufficientFundsException`. You did not have to change the retry at all. + +```bash +./check 6 +./check +``` + +`./check` should now print 31 passes and no failures. + +--- + +## Task 7: Inspect SERIALIZABLE + +### Step 1: nobody waits, one is cancelled + +```bash +./demo --anomaly write-skew --level serializable +``` + +The steps are the same as at REPEATABLE READ until the end: + +``` + A | commit + B | commit + B | -> ERROR, SQLSTATE 40001: could not serialize access due to read/write dependencies among transactions + B | -> Detail: Reason code: Canceled on identification as a pivot, during commit attempt. + B | -> Hint: The transaction might succeed if retried. +``` + +SERIALIZABLE promises: the result is the same as if the transactions had run **one after another**, +in some order. "A then B" would have refused B. "B then A" would have refused A. Both going through +fits neither order, so Postgres cancels one. + +It does not get there by running them one at a time. Both sessions read at once and both wrote at +once. Postgres remembers **what each transaction read**, and notices that each one read something +the other one then changed. The hint tells you what to do about it. + +### Step 2: the memory of what was read + +`./demo --anomaly write-skew --level serializable --pause` in terminal 1, `./inspect` in terminal 2: + +``` +SESSIONS INSIDE A TRANSACTION (snapshot_xmin is filled in while the session holds a snapshot) + pid session state snapshot_xmin own_xid waits_for_pid in_transaction_ms last_statement + ---- --------------------- ------------------- ------------- ------- ------------- ----------------- -------------------------------------------- + 3376 demo A (serializable) idle in transaction 936 936 8944 update account set balance = balance - 800 w + 3377 demo B (serializable) idle in transaction 936 937 8883 update account set balance = balance - 800 w + +PREDICATE LOCKS (SIReadLock: what SERIALIZABLE sessions have read. They block nobody) + pid session relation covers page row_on_page + ---- --------------------- -------- -------- ---- ----------- + 3376 demo A (serializable) account relation + 3377 demo B (serializable) account relation +``` + +- Both sessions hold a snapshot, as at REPEATABLE READ. SERIALIZABLE in Postgres is REPEATABLE READ + plus this tracking. +- Each one holds a `SIReadLock` on `account`. Despite the name it is not a lock: `waits_for_pid` is + empty for both. It is a note that says "I read this". +- `covers` says `relation`: the whole table. The table has two rows, so Postgres read all of it, + and the note covers all of it. A wider note means more transactions look like they conflict. + SERIALIZABLE may cancel a transaction that would have been fine. That is allowed: it must never + let a wrong result through, and a retry costs only time. + +### Step 3: a committed transaction still matters + +`./demo --anomaly write-skew --pause` (your application) in terminal 1, `./inspect` in terminal 2: + +``` + 3445 bank-app (serializable) idle in transaction 940 ... + +PREDICATE LOCKS (SIReadLock: what SERIALIZABLE sessions have read. They block nobody) + 3445 bank-app (serializable) account relation + 3446 bank-app account relation +``` + +Session 3446 is not in the list of open transactions: it is session B, and it has committed. Its +note is still there, because session A overlapped with it and is not finished. Postgres needs it to +judge A. + +### Step 4: it can fail at COMMIT + +In step 1 every statement of session B worked and the **`commit`** failed. In your application's +run the failure came earlier, at the UPDATE. Both happen. `WriteSkewIT.aFailedCommitIsAlsoCannotAcquireLockException` +shows that Spring raises the same `CannotAcquireLockException` when the commit fails, so one `catch` +covers both. It also means: at SERIALIZABLE, do not believe a transaction worked until the commit +has returned. + +### Step 5: the level is fixed when the transaction starts + +`WriteSkewIT.anInnerIsolationLevelIsIgnored`: a "serializable" block that runs inside a transaction +that is already open runs at **that** transaction's level, here `read committed`. No error, no +warning. If a colleague calls `withdrawer.withdraw` from their own `@Transactional` method, the +withdrawal joins their transaction and your `SERIALIZABLE` is ignored. + +### Step 6: everybody has to take part + +A READ COMMITTED transaction is not covered. Postgres only gives the guarantee among transactions +that are all SERIALIZABLE. We ran the +write skew with session A at SERIALIZABLE and session B at READ COMMITTED: both committed, and the +accounts ended at -600. + +### What to take away + +- SERIALIZABLE = "as if one after another". Postgres checks it afterwards instead of making + transactions queue. +- A transaction can be cancelled at any statement, including COMMIT. Always `40001`, always retry. +- Costs: retries, some of them unnecessary, and bookkeeping for everything that is read. +- It only works if every transaction that touches the data uses it, and if the level is set where + the transaction starts. + +--- + +## Task 8: Compare Every Level, and Isolation Levels vs Locking + +### Step 1: the whole table + +```bash +./demo --matrix +``` + +``` +Every anomaly at every isolation level: plain SQL in two sessions, 20 runs. + + read-uncommitted read-committed repeatable-read serializable + dirty-read no no no no + non-repeatable-read HAPPENS HAPPENS no no + phantom HAPPENS HAPPENS no no + lost-update HAPPENS HAPPENS 40001 40001 + write-skew HAPPENS HAPPENS HAPPENS 40001 + +RESULT: read-uncommitted and read-committed behave the same. Levels with no anomaly left: serializable. +``` + +The SQL standard only says what each level **must** prevent: + +| SQL standard | dirty read | non-repeatable read | phantom read | +|---|---|---|---| +| READ UNCOMMITTED | allowed | allowed | allowed | +| READ COMMITTED | prevented | allowed | allowed | +| REPEATABLE READ | prevented | prevented | allowed | +| SERIALIZABLE | prevented | prevented | prevented | + +Postgres is stricter in two places: READ UNCOMMITTED has no dirty reads, and REPEATABLE READ has no +phantoms. `40001` in the output means: it did not happen, because Postgres cancelled one +transaction. And the standard's table does not mention lost updates or write skew at all, which is +why people who only know the table are surprised by Task 6. + +### Step 2: the same problem, solved with a lock + +```bash +./demo --anomaly write-skew --for-update +``` + +``` + A | begin isolation level read committed + A | select balance from account where owner = 'alice' order by id for update + A | -> 500, 500 + A | # 500 + 500 = 1000, enough for 800: go ahead + B | begin isolation level read committed + B | select balance from account where owner = 'alice' order by id for update + B | -> WAITING. Another session holds a lock this statement needs + A | update account set balance = balance - 800 where id = 1 + A | -> 1 row + A | commit + B | -> (stopped waiting) -300, 500 + B | # -300 + 500 = 200, not enough for 800: refuse + B | rollback + +RESULT: OK. Session B had to wait for A's row locks, then read 200 and refused its withdrawal. The accounts hold 200 together. +``` + +The lowest useful level, and no write skew. `for update` made A's read **lock both rows**. B could +not read them until A was finished, and then it read the truth. + +### Step 3: side by side + +| | `--for-update` (a lock) | `--level serializable` (an isolation level) | +|---|---|---| +| B's read | waits | returns at once, from B's snapshot | +| Who loses | nobody is cancelled. B waits, then decides with fresh data | B is cancelled with `40001` | +| What the code needs | nothing more | a retry | +| Cost | B, and everyone behind it, queues while A works | wasted work, redone on retry | + +### Step 4: see the lock + +`./demo --anomaly write-skew --for-update --pause`, then `./inspect`: + +``` + 1 current 500 943 944 + 2 savings 500 943 944 + 3523 demo A (read committed) idle in transaction 944 9029 update account set balance = balance - 800 w + 3525 demo B (read committed) active 944 3523 8979 select balance from account where owner = 'a +``` + +`waits_for_pid` says session 3525 is waiting for 3523. `xmax` of both rows is 944, which is A's +`own_xid`: that is how Postgres marks a row as locked by transaction 944. Compare with Task 7 step +2, where `waits_for_pid` was empty. + +### Step 5: what a lock cannot do + +"A customer may have at most 3 accounts." Two sessions each count 2 and each insert one. `SELECT ... +FOR UPDATE` locks the rows it **returns**. The row the other session is about to insert does not +exist yet, so there is nothing to lock. SERIALIZABLE handles it: it tracks that both sessions read +"alice's accounts", and cancels the second one at commit with `40001`. + +### Isolation levels vs locking + +They are different tools, and interviews are full of answers that mix them up. + +- An **isolation level** is a setting of one transaction. It decides what that transaction may + **see**. Raising it adds no waiting in Postgres. When two transactions cannot both be right, one + is **cancelled** and has to retry. +- A **lock** is a claim on specific rows. It makes other transactions **wait**. It works at any + isolation level, including the default. + +| Situation | Reach for | +|---|---| +| A report or export: several queries that must agree | REPEATABLE READ, read only. Nothing to retry, nothing to lock | +| You will change one known row, based on its value (stock, a seat, one balance) | A lock: `SELECT ... FOR UPDATE`, or better one conditional `UPDATE`. See [`../07-locking`](../07-locking/) | +| A rule over several rows that all exist, and conflicts are common | Lock those rows with `FOR UPDATE`, always in the same order | +| A rule over a set of rows, or over rows that may not exist yet | SERIALIZABLE and a retry | + +For this project's withdrawal either tool works, because the two account rows exist and can be +locked. The lock makes the second customer wait. SERIALIZABLE makes the second customer's request +run twice. + +`./check 8` says 2 of 2 pass. They passed from the start: they pin down "a lock makes B wait" and +"an isolation level cancels B instead". + +### How to say it in an interview + +> "The isolation level decides what a transaction can see of other transactions. Postgres defaults +> to READ COMMITTED: every statement sees what was committed when that statement started, so two +> queries in one transaction can disagree. That gives you non-repeatable reads and phantoms. READ +> UNCOMMITTED exists, but Postgres runs it as READ COMMITTED, so there are no dirty reads. +> REPEATABLE READ takes one snapshot for the whole transaction, which is what I use for a report. +> It also stops lost updates: if I update a row that changed after my snapshot, I get SQLSTATE +> 40001. It does not stop write skew, where two transactions read the same rows and write different +> ones. For that I need SERIALIZABLE, which cancels one of them, again with 40001. So with either +> of the two higher levels I need a retry, outside the transaction, with a limit. And none of this +> is locking: a higher isolation level does not make anyone wait in Postgres, it cancels the +> loser. If I know which row I am going to change, I would rather lock it with SELECT FOR UPDATE, +> or do it in one UPDATE." + +Then be ready for the follow-ups in "Questions to Ask Afterwards" at the end of +[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md). + +--- + +## Clean up + +```bash +docker compose down +``` diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/.mvn/jvm.config b/java/concepts/junior-mid/09-isolation-levels/solution/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/.mvn/jvm.config @@ -0,0 +1,2 @@ +--enable-native-access=ALL-UNNAMED +--sun-misc-unsafe-memory-access=allow diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/09-isolation-levels/solution/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/check b/java/concepts/junior-mid/09-isolation-levels/solution/check new file mode 100755 index 0000000..8a13e3b --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/check @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use check.cmd (type: .\check). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.isolation.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/check.cmd b/java/concepts/junior-mid/09-isolation-levels/solution/check.cmd new file mode 100644 index 0000000..27c9db8 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/check.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./check +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.isolation.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/compose.yaml b/java/concepts/junior-mid/09-isolation-levels/solution/compose.yaml new file mode 100644 index 0000000..8ba5992 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/compose.yaml @@ -0,0 +1,16 @@ +name: isolation-levels +services: + postgres: + image: postgres:17-alpine + container_name: isolation-levels-postgres + environment: + POSTGRES_DB: bank + POSTGRES_USER: bank + POSTGRES_PASSWORD: bank + ports: + - "5448:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U bank -d bank"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/demo b/java/concepts/junior-mid/09-isolation-levels/solution/demo new file mode 100755 index 0000000..c68c08f --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/demo @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use demo.cmd (type: .\demo). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.isolation.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/demo.cmd b/java/concepts/junior-mid/09-isolation-levels/solution/demo.cmd new file mode 100644 index 0000000..8b56f31 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/demo.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./demo +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.isolation.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/inspect b/java/concepts/junior-mid/09-isolation-levels/solution/inspect new file mode 100755 index 0000000..5b01fcd --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/inspect @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use inspect.cmd (type: .\inspect). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.isolation.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/inspect.cmd b/java/concepts/junior-mid/09-isolation-levels/solution/inspect.cmd new file mode 100644 index 0000000..550a5bb --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/inspect.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./inspect +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.isolation.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/mvnw b/java/concepts/junior-mid/09-isolation-levels/solution/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/mvnw.cmd b/java/concepts/junior-mid/09-isolation-levels/solution/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/pom.xml b/java/concepts/junior-mid/09-isolation-levels/solution/pom.xml new file mode 100644 index 0000000..f773e9e --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + isolation-levels + 0.0.1-SNAPSHOT + isolation-levels + Transaction isolation levels: see the anomalies, then fix them with the right level and a retry + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + runtime + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.mockito + mockito-core + + + org.mockito + mockito-junit-jupiter + + + + + org.springframework.boot + spring-boot-starter-data-jpa-test + test + + + org.testcontainers + testcontainers-postgresql + test + + + org.junit.platform + junit-platform-launcher + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + false + + + + + + diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/IsolationApplication.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/IsolationApplication.java new file mode 100644 index 0000000..80b534d --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/IsolationApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.isolation; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class IsolationApplication { + + public static void main(String[] args) { + SpringApplication.run(IsolationApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/Account.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/Account.java new file mode 100644 index 0000000..83d91c8 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/Account.java @@ -0,0 +1,49 @@ +package com.amigoscode.isolation.account; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +@Entity +@Table(name = "account") +public class Account { + + @Id + private Long id; + + private String owner; + + private String name; + + private long balance; + + protected Account() { + } + + public Account(long id, String owner, String name, long balance) { + this.id = id; + this.owner = owner; + this.name = name; + this.balance = balance; + } + + public Long getId() { + return id; + } + + public String getOwner() { + return owner; + } + + public String getName() { + return name; + } + + public long getBalance() { + return balance; + } + + public void setBalance(long balance) { + this.balance = balance; + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/AccountNotFoundException.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/AccountNotFoundException.java new file mode 100644 index 0000000..73df1c2 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/AccountNotFoundException.java @@ -0,0 +1,8 @@ +package com.amigoscode.isolation.account; + +public class AccountNotFoundException extends RuntimeException { + + public AccountNotFoundException(long accountId) { + super("Account " + accountId + " does not exist"); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/AccountRepository.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/AccountRepository.java new file mode 100644 index 0000000..b614f2e --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/AccountRepository.java @@ -0,0 +1,16 @@ +package com.amigoscode.isolation.account; + +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface AccountRepository extends JpaRepository { + + List findByOwnerOrderById(String owner); + + long countByOwner(String owner); + + @Query("select coalesce(sum(a.balance), 0) from Account a where a.owner = :owner") + long totalBalance(@Param("owner") String owner); +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/Checkpoint.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/Checkpoint.java new file mode 100644 index 0000000..f3fa680 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/Checkpoint.java @@ -0,0 +1,18 @@ +package com.amigoscode.isolation.checkpoint; + +/** + * A named point in the middle of a transaction, between a READ and what the code does with it. + * In production nothing happens here. The demo and the tests use it to let a second session do + * its work at exactly this moment, so the dangerous interleaving happens every time instead of + * once a month. + */ +public interface Checkpoint { + + /** StatementService has read the lines and is about to read the total. */ + String LINES_READ = "statement: lines read"; + + /** Withdrawer has checked the funds and is about to write the new balance. */ + String FUNDS_CHECKED = "withdrawal: funds checked"; + + void reached(String name); +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/NoCheckpoint.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/NoCheckpoint.java new file mode 100644 index 0000000..68c9ab0 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/NoCheckpoint.java @@ -0,0 +1,12 @@ +package com.amigoscode.isolation.checkpoint; + +import org.springframework.stereotype.Component; + +/** What runs in production: nothing. */ +@Component +public class NoCheckpoint implements Checkpoint { + + @Override + public void reached(String name) { + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/ScriptedCheckpoint.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/ScriptedCheckpoint.java new file mode 100644 index 0000000..9ffa0e1 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/ScriptedCheckpoint.java @@ -0,0 +1,52 @@ +package com.amigoscode.isolation.checkpoint; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.IntConsumer; + +/** + * Used by the demo and the tests instead of {@link NoCheckpoint}: runs an action whenever a + * checkpoint is reached, on the thread that reached it, which means in the middle of that + * thread's transaction. + */ +public final class ScriptedCheckpoint implements Checkpoint { + + private final Map arrivals = new ConcurrentHashMap<>(); + private final Map actions = new ConcurrentHashMap<>(); + + /** Forget every action and every count. */ + public void reset() { + arrivals.clear(); + actions.clear(); + } + + /** Runs {@code action} every time {@code name} is reached. It receives the arrival number: 1, 2, 3... */ + public void onReached(String name, IntConsumer action) { + actions.put(name, action); + } + + /** Runs {@code action} the first time {@code name} is reached, and never again (so not on a retry). */ + public void onFirst(String name, Runnable action) { + onReached(name, arrival -> { + if (arrival == 1) { + action.run(); + } + }); + } + + /** How many times {@code name} has been reached. */ + public int arrivals(String name) { + AtomicInteger count = arrivals.get(name); + return count == null ? 0 : count.get(); + } + + @Override + public void reached(String name) { + int arrival = arrivals.computeIfAbsent(name, key -> new AtomicInteger()).incrementAndGet(); + IntConsumer action = actions.get(name); + if (action != null) { + action.accept(arrival); + } + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Anomaly.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Anomaly.java new file mode 100644 index 0000000..de1cf63 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Anomaly.java @@ -0,0 +1,24 @@ +package com.amigoscode.isolation.demo; + +import java.util.Arrays; +import java.util.Locale; +import java.util.stream.Collectors; + +/** The things that can go wrong when two transactions overlap. */ +public enum Anomaly { + DIRTY_READ, NON_REPEATABLE_READ, PHANTOM, LOST_UPDATE, WRITE_SKEW; + + /** As written on the command line: "write-skew". */ + public String flag() { + return name().toLowerCase(Locale.ROOT).replace('_', '-'); + } + + static Anomaly from(String value) { + return Arrays.stream(values()).filter(anomaly -> anomaly.flag().equals(value)).findFirst() + .orElseThrow(() -> new IllegalArgumentException("Unknown anomaly: " + value + ". Use one of: " + names())); + } + + static String names() { + return Arrays.stream(values()).map(Anomaly::flag).collect(Collectors.joining(" | ")); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/AppDemo.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/AppDemo.java new file mode 100644 index 0000000..0452b2f --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/AppDemo.java @@ -0,0 +1,220 @@ +package com.amigoscode.isolation.demo; + +import com.amigoscode.isolation.IsolationApplication; +import com.amigoscode.isolation.checkpoint.Checkpoint; +import com.amigoscode.isolation.checkpoint.ScriptedCheckpoint; +import com.amigoscode.isolation.statement.Statement; +import com.amigoscode.isolation.statement.StatementService; +import com.amigoscode.isolation.withdrawal.InsufficientFundsException; +import com.amigoscode.isolation.withdrawal.WithdrawalService; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * Runs the application's own code (StatementService, WithdrawalService) as session A, and makes a + * second session do its work at a checkpoint in the middle of A's transaction. What you see depends + * on the @Transactional settings in the code. + */ +final class AppDemo { + + private final ConfigurableApplicationContext context; + private final ScriptedCheckpoint checkpoint; + private final JdbcTemplate jdbc; + private final Timeline timeline = new Timeline(System.out); + private final int pauseSeconds; + + private AppDemo(ConfigurableApplicationContext context, ScriptedCheckpoint checkpoint, int pauseSeconds) { + this.context = context; + this.checkpoint = checkpoint; + this.jdbc = context.getBean(JdbcTemplate.class); + this.pauseSeconds = pauseSeconds; + } + + static void run(Anomaly anomaly, int pauseSeconds) throws SQLException { + ScriptedCheckpoint checkpoint = new ScriptedCheckpoint(); + SpringApplication app = new SpringApplication(IsolationApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + // The demo's checkpoint replaces the one that does nothing. + app.addInitializers(context -> ((GenericApplicationContext) context).registerBean( + "demoCheckpoint", ScriptedCheckpoint.class, () -> checkpoint, bean -> bean.setPrimary(true))); + try (ConfigurableApplicationContext context = app.run( + "--logging.level.root=WARN", + // A cancelled transaction is shown as one line in the timeline instead of a log entry. + "--logging.level.org.hibernate.orm.jdbc.error=OFF")) { + try (Connection connection = Db.connect()) { + Db.reset(connection); + } + AppDemo demo = new AppDemo(context, checkpoint, pauseSeconds); + System.out.println(); + switch (anomaly) { + case NON_REPEATABLE_READ, PHANTOM -> demo.statement(anomaly); + case LOST_UPDATE -> demo.withdrawals(anomaly, 1, 1, 100); + case WRITE_SKEW -> demo.withdrawals(anomaly, 1, 2, 800); + case DIRTY_READ -> throw new IllegalStateException("dirty-read is always plain SQL"); + } + System.out.println(); + } + } + + /** Session A is StatementService.statement. Session B commits a change between A's queries. */ + private void statement(Anomaly anomaly) throws SQLException { + System.out.println("Anomaly: " + anomaly.flag() + " | running the application: StatementService.statement"); + System.out.println("Session A is the application, building alice's statement: the lines first, then the count and the total."); + System.out.println(anomaly == Anomaly.PHANTOM + ? "Session B opens a new account for alice and commits in between." + : "Session B deposits 100 and commits in between."); + System.out.println("Before: alice has two accounts, current (id 1) = 500 and savings (id 2) = 500."); + System.out.println(); + + Statement statement; + try (Connection monitor = Db.connect(); Session b = new Session("B", Db.connect(), monitor, timeline)) { + checkpoint.onFirst(Checkpoint.LINES_READ, () -> { + timeline.result("A", "transaction isolation level: " + levelOfThisTransaction()); + timeline.result("A", "query 1 done: the lines are read"); + b.exec("begin"); + b.exec(anomaly == Anomaly.PHANTOM + ? "insert into account (id, owner, name, balance) values (3, 'alice', 'holiday', 250)" + : "update account set balance = balance + 100 where id = 1"); + b.exec("commit"); + pause(); + }); + timeline.step("A", "StatementService.statement(\"alice\")"); + statement = context.getBean(StatementService.class).statement("alice"); + timeline.result("A", "queries 2 and 3 done: the count and the total are read"); + } + + System.out.println(); + System.out.println("The statement the customer gets:"); + for (Statement.Line line : statement.lines()) { + System.out.printf(" %-12s %6d%n", line.account(), line.balance()); + } + System.out.println(" -------------------"); + System.out.printf(" %-12s %6d%n", statement.accountCount() + " accounts", statement.total()); + System.out.println(); + if (statement.addsUp()) { + System.out.println("RESULT: OK. " + statement.lines().size() + " lines, " + statement.accountCount() + + " accounts, and the lines add up to the total: " + statement.total() + + ". What session B committed is not in this statement. It will be in the next one."); + } else if (statement.lines().size() != statement.accountCount()) { + System.out.println("RESULT: PHANTOM READ. The statement lists " + statement.lines().size() + + " accounts and then says there are " + statement.accountCount() + ". The lines add up to " + + statement.sumOfLines() + ", the total says " + statement.total() + "."); + } else { + System.out.println("RESULT: NON-REPEATABLE READ. The lines add up to " + statement.sumOfLines() + + ", the total says " + statement.total() + ". The queries of one transaction saw two different moments."); + } + } + + /** Session A and session B are both WithdrawalService.withdraw. B runs while A is between its check and its write. */ + private void withdrawals(Anomaly anomaly, long accountA, long accountB, long amount) { + System.out.println("Anomaly: " + anomaly.flag() + " | running the application: WithdrawalService.withdraw"); + System.out.println(Demo.story(anomaly)); + System.out.println("Session B does all of its work while A is between checking the funds and writing the new balance."); + System.out.println("Before: alice has two accounts, current (id 1) = 500 and savings (id 2) = 500."); + System.out.println(); + + Thread sessionA = Thread.currentThread(); + Map attempts = new ConcurrentHashMap<>(); + Map thrown = new ConcurrentHashMap<>(); + Map paidOut = new ConcurrentHashMap<>(); + checkpoint.onReached(Checkpoint.FUNDS_CHECKED, arrival -> { + String session = Thread.currentThread() == sessionA ? "A" : "B"; + int attempt = attempts.merge(session, 1, Integer::sum); + timeline.result(session, "attempt " + attempt + (attempt > 1 ? " (a new transaction: the last one did not commit)" : "") + + ", transaction isolation level: " + levelOfThisTransaction()); + timeline.result(session, "funds checked: enough for " + amount); + if (session.equals("A") && attempt == 1) { + Thread sessionB = new Thread(() -> withdraw("B", accountB, amount, thrown, paidOut), "session-B"); + sessionB.start(); + try { + sessionB.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + pause(); + } + }); + withdraw("A", accountA, amount, thrown, paidOut); + + long current = jdbc.queryForObject("select balance from account where id = 1", Long.class); + long savings = jdbc.queryForObject("select balance from account where id = 2", Long.class); + System.out.println(); + System.out.println("Withdrawals paid out: " + paidOut.size() + " x " + amount); + System.out.println("Current (id 1): " + current); + System.out.println("Savings (id 2): " + savings); + System.out.println("Both together: " + (current + savings)); + System.out.println(); + + if (!thrown.isEmpty()) { + String session = thrown.keySet().iterator().next(); + System.out.println("RESULT: NOT HANDLED. The data is right, because Postgres cancelled session " + session + + "'s transaction. But the customer got a " + thrown.get(session).getClass().getSimpleName() + + ". Nothing was wrong with the request: it has to be run again."); + } else if (anomaly == Anomaly.LOST_UPDATE && current != 500 - paidOut.size() * amount) { + System.out.println("RESULT: LOST UPDATE. " + paidOut.size() + " withdrawals of " + amount + + " were paid out, but the balance only went from 500 to " + current + "."); + } else if (current + savings < 0) { + System.out.println("RESULT: WRITE SKEW. Both withdrawals of " + amount + " went through and the accounts hold " + + (current + savings) + " together. The rule is broken, and neither transaction changed a row the other one changed."); + } else { + System.out.println("RESULT: OK. " + paidOut.size() + " x " + amount + " paid out, both accounts together went from 1000 to " + + (current + savings) + "." + (attempts.getOrDefault("A", 1) > 1 + ? " Session A was cancelled once and ran again in a new transaction." + : !paidOut.containsKey("A") + ? " Session A passed the check, was cancelled, ran again in a new transaction and was refused." + : "")); + } + } + + private void withdraw(String session, long accountId, long amount, Map thrown, + Map paidOut) { + timeline.step(session, "WithdrawalService.withdraw(" + accountId + ", " + amount + ")"); + try { + long newBalance = context.getBean(WithdrawalService.class).withdraw(accountId, amount); + paidOut.put(session, true); + timeline.result(session, "returns " + newBalance + ", the new balance of account " + accountId); + } catch (InsufficientFundsException e) { + timeline.result(session, "refused, InsufficientFundsException: " + e.getMessage()); + } catch (RuntimeException e) { + thrown.put(session, e); + timeline.result(session, "THROWS " + e.getClass().getName()); + Throwable root = e; + while (root.getCause() != null) { + root = root.getCause(); + } + String message = String.valueOf(root.getMessage()).lines().findFirst().orElse(""); + timeline.result(session, "caused by " + root.getClass().getSimpleName() + + (root instanceof SQLException sql ? ", SQLSTATE " + sql.getSQLState() : "") + ": " + message); + } + } + + /** + * Asked on the calling thread, so it runs inside that thread's transaction, on its connection. + * The session also puts the level into its application_name, where ./inspect can read it: + * Postgres has no column that shows another session's isolation level. + */ + private String levelOfThisTransaction() { + String level = jdbc.queryForObject("show transaction_isolation", String.class); + jdbc.execute("set local application_name = 'bank-app (" + level + ")'"); + return level; + } + + private void pause() { + if (pauseSeconds > 0) { + timeline.note("Paused for " + pauseSeconds + " seconds. Run ./inspect in another terminal now."); + try { + Thread.sleep(pauseSeconds * 1000L); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Db.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Db.java new file mode 100644 index 0000000..7779e2a --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Db.java @@ -0,0 +1,63 @@ +package com.amigoscode.isolation.demo; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +/** Connection settings shared by the demo and inspect tools. Same defaults as application.properties. */ +public final class Db { + + static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5448/bank"); + static final String USER = env("DB_USER", "bank"); + static final String PASSWORD = env("DB_PASSWORD", "bank"); + + private Db() { + } + + static Connection connect() throws SQLException { + return DriverManager.getConnection(URL, USER, PASSWORD); + } + + /** Returns false, after printing what to do, when Postgres is not reachable. */ + static boolean isUp() { + try (Connection ignored = connect()) { + return true; + } catch (SQLException e) { + System.out.println(); + System.out.println("Cannot reach Postgres at " + URL); + System.out.println("Start it first, from this folder:"); + System.out.println(); + System.out.println(" docker compose up -d"); + System.out.println(); + System.out.println("(" + e.getMessage().lines().findFirst().orElse("") + ")"); + return false; + } + } + + /** Creates the table if needed and puts the data back: alice, current 500 and savings 500. */ + public static void reset(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute(schema()); + statement.execute("delete from account"); + statement.execute("insert into account (id, owner, name, balance) " + + "values (1, 'alice', 'current', 500), (2, 'alice', 'savings', 500)"); + } + } + + private static String schema() { + try (InputStream in = Db.class.getResourceAsStream("/schema.sql")) { + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new IllegalStateException("Cannot read schema.sql", e); + } + } + + private static String env(String name, String fallback) { + String value = System.getenv(name); + return value == null || value.isBlank() ? fallback : value; + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Demo.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Demo.java new file mode 100644 index 0000000..76b74db --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Demo.java @@ -0,0 +1,184 @@ +package com.amigoscode.isolation.demo; + +import com.amigoscode.isolation.demo.Outcome.Verdict; +import java.util.ArrayList; +import java.util.List; + +/** + * Two sessions, one fixed order of steps, printed as a timeline that ends in a RESULT line. + * Without --level it runs the application's own code. With --level it runs the same anomaly as + * plain SQL at the level you choose. Run it with ./demo (or .\demo on Windows). ./demo --help + * lists the flags. + */ +public final class Demo { + + static final int PAUSE_SECONDS = 15; + + private record Options(Anomaly anomaly, Level level, boolean matrix, boolean forUpdate, boolean pause) { + } + + public static void main(String[] args) throws Exception { + Options options; + try { + options = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println(); + printHelp(); + return; + } + if (options == null) { + printHelp(); + return; + } + if (!Db.isUp()) { + return; + } + if (options.matrix()) { + matrix(); + } else if (options.level() != null) { + sql(options); + } else { + AppDemo.run(options.anomaly(), options.pause() ? PAUSE_SECONDS : 0); + } + } + + /** One anomaly as plain SQL at one level. */ + private static void sql(Options options) { + System.out.println(); + System.out.println("Anomaly: " + options.anomaly().flag() + " | level: " + options.level().sql() + + (options.forUpdate() ? " + SELECT ... FOR UPDATE" : "") + " | plain SQL in two sessions"); + System.out.println(story(options.anomaly())); + System.out.println("Before: alice has two accounts, current (id 1) = 500 and savings (id 2) = 500."); + System.out.println(); + Lab lab = new Lab(Db.URL, Db.USER, Db.PASSWORD, System.out); + Outcome outcome = lab.run(options.anomaly(), options.level(), + new Lab.Options(options.forUpdate(), options.pause() ? PAUSE_SECONDS : 0)); + System.out.println(); + System.out.println("RESULT: " + outcome.result()); + System.out.println(); + } + + static String story(Anomaly anomaly) { + return switch (anomaly) { + case DIRTY_READ -> "Session B changes a balance and has NOT committed. Session A reads that balance."; + case NON_REPEATABLE_READ -> "Session A reads one balance twice. Session B deposits 100 and commits in between."; + case PHANTOM -> "Session A counts alice's accounts twice. Session B opens a new account and commits in between."; + case LOST_UPDATE -> "Both sessions withdraw 100 from account 1: read the balance, subtract, write it back."; + case WRITE_SKEW -> "A withdraws 800 from account 1, B withdraws 800 from account 2. " + + "The rule: both accounts together must stay at 0 or above."; + }; + } + + /** Every anomaly at every level. */ + private static void matrix() { + Lab lab = new Lab(Db.URL, Db.USER, Db.PASSWORD, null); + System.out.println(); + System.out.println("Every anomaly at every isolation level: plain SQL in two sessions, " + + Anomaly.values().length * Level.values().length + " runs."); + System.out.println(); + StringBuilder header = new StringBuilder(String.format(" %-21s", "")); + for (Level level : Level.values()) { + header.append(String.format("%-18s", level.flag())); + } + System.out.println(header.toString().stripTrailing()); + List> columns = new ArrayList<>(); + for (Level ignored : Level.values()) { + columns.add(new ArrayList<>()); + } + for (Anomaly anomaly : Anomaly.values()) { + StringBuilder row = new StringBuilder(String.format(" %-21s", anomaly.flag())); + for (Level level : Level.values()) { + Outcome outcome = lab.run(anomaly, level); + String cell = outcome.verdict() == Verdict.HAPPENED ? "HAPPENS" + : outcome.verdict() == Verdict.SERIALIZATION_FAILURE ? outcome.sqlState() : "no"; + columns.get(level.ordinal()).add(cell); + row.append(String.format("%-18s", cell)); + } + System.out.println(row.toString().stripTrailing()); + } + System.out.println(); + System.out.println(" HAPPENS = the anomaly happened and nobody was told"); + System.out.println(" no = it did not happen"); + System.out.println(" 40001 = it did not happen, because Postgres cancelled one transaction with"); + System.out.println(" SQLSTATE 40001 (serialization failure). The application has to retry it"); + System.out.println(); + boolean sameAsReadCommitted = columns.get(Level.READ_UNCOMMITTED.ordinal()) + .equals(columns.get(Level.READ_COMMITTED.ordinal())); + List clean = new ArrayList<>(); + for (Level level : Level.values()) { + if (!columns.get(level.ordinal()).contains("HAPPENS")) { + clean.add(level.flag()); + } + } + System.out.println("RESULT: read-uncommitted and read-committed " + + (sameAsReadCommitted ? "behave the same" : "DIFFER") + ". Levels with no anomaly left: " + + (clean.isEmpty() ? "none" : String.join(", ", clean)) + "."); + System.out.println(); + } + + private static Options parse(String[] args) { + Anomaly anomaly = Anomaly.NON_REPEATABLE_READ; + Level level = null; + boolean matrix = false; + boolean forUpdate = false; + boolean pause = false; + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "--help", "-h" -> { + return null; + } + case "--anomaly" -> anomaly = Anomaly.from(value(args, ++i, arg)); + case "--level" -> level = Level.from(value(args, ++i, arg)); + case "--matrix" -> matrix = true; + case "--for-update" -> forUpdate = true; + case "--pause" -> pause = true; + default -> throw new IllegalArgumentException("Unknown option: " + arg); + } + } + if (forUpdate && anomaly != Anomaly.WRITE_SKEW) { + throw new IllegalArgumentException("--for-update only works with --anomaly write-skew"); + } + if (level == null && forUpdate) { + level = Level.READ_COMMITTED; + } + if (level == null && anomaly == Anomaly.DIRTY_READ) { + // The application has no code that could show a dirty read, so this one is always plain SQL. + level = Level.READ_UNCOMMITTED; + } + return new Options(anomaly, level, matrix, forUpdate, pause); + } + + private static String value(String[] args, int index, String option) { + if (index >= args.length) { + throw new IllegalArgumentException(option + " needs a value"); + } + return args[index]; + } + + private static void printHelp() { + System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])"); + System.out.println(); + System.out.println(" --anomaly " + Anomaly.names()); + System.out.println(" (default: non-repeatable-read)"); + System.out.println(" --level " + Level.names()); + System.out.println(" Runs the anomaly as plain SQL at this level."); + System.out.println(" Without --level the demo runs the APPLICATION's code, so it shows"); + System.out.println(" what your @Transactional settings do. (dirty-read is always plain SQL.)"); + System.out.println(" --for-update write-skew only, plain SQL: the read locks the rows (SELECT ... FOR UPDATE)"); + System.out.println(" --matrix every anomaly at every level, as one table"); + System.out.println(" --pause hold the transactions open for " + PAUSE_SECONDS + + " seconds in the middle, so you can run ./inspect"); + System.out.println(); + System.out.println("Examples:"); + System.out.println(" ./demo"); + System.out.println(" ./demo --anomaly phantom"); + System.out.println(" ./demo --anomaly write-skew --level serializable"); + System.out.println(" ./demo --anomaly dirty-read --level read-uncommitted"); + System.out.println(" ./demo --matrix"); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Inspect.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Inspect.java new file mode 100644 index 0000000..da14cb3 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Inspect.java @@ -0,0 +1,169 @@ +package com.amigoscode.isolation.demo; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +/** + * Shows what the database sees right now: every account row with the transaction that wrote it, + * every session that is inside a transaction, whether it holds a snapshot, and the predicate locks + * of SERIALIZABLE sessions. Run it with ./inspect (or .\inspect on Windows) in a second terminal + * while ./demo --pause is running. + */ +public final class Inspect { + + private static final String ACCOUNTS = """ + select id, name, balance, xmin, xmax + from account + order by id + """; + + /** + * Postgres has no column that shows another session's isolation level. The demo's sessions put + * their own level into their application_name, which is the "session" column here. + * snapshot_xmin is filled in while a session holds a snapshot. + */ + private static final String SESSIONS = """ + select a.pid, + a.application_name as session, + a.state, + coalesce(a.backend_xmin::text, '') as snapshot_xmin, + coalesce(a.backend_xid::text, '') as own_xid, + case when cardinality(pg_blocking_pids(a.pid)) = 0 then '' + else array_to_string(pg_blocking_pids(a.pid), ', ') end as waits_for_pid, + coalesce(round(extract(epoch from (now() - a.xact_start)) * 1000)::text, '') as in_transaction_ms, + left(regexp_replace(a.query, '\\s+', ' ', 'g'), 44) as last_statement + from pg_stat_activity a + where a.datname = current_database() + and a.pid <> pg_backend_pid() + and a.backend_type = 'client backend' + and a.state <> 'idle' + order by a.xact_start nulls last, a.pid + """; + + private static final String PREDICATE_LOCKS = """ + select l.pid, + a.application_name as session, + coalesce(c.relname::text, '') as relation, + l.locktype as covers, + coalesce(l.page::text, '') as page, + coalesce(l.tuple::text, '') as row_on_page + from pg_locks l + join pg_stat_activity a on a.pid = l.pid + left join pg_class c on c.oid = l.relation + where l.mode = 'SIReadLock' + order by l.pid, c.relname, l.page nulls first, l.tuple nulls first + """; + + public static void main(String[] args) throws Exception { + boolean watch = false; + for (String arg : args) { + if (arg.equals("--watch")) { + watch = true; + } else { + System.out.println("Usage: ./inspect [--watch] (Windows: .\\inspect [--watch])"); + System.out.println(); + System.out.println(" --watch refresh every second for one minute (Ctrl+C to stop)"); + return; + } + } + if (!Db.isUp()) { + return; + } + try (Connection connection = Db.connect()) { + int rounds = watch ? 60 : 1; + for (int round = 0; round < rounds; round++) { + snapshot(connection); + if (round < rounds - 1) { + Thread.sleep(1000); + } + } + } + } + + private static void snapshot(Connection connection) throws SQLException { + System.out.println(); + System.out.println("==== " + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")) + " ===="); + System.out.println(); + System.out.println("ACCOUNTS (what a NEW transaction would read. xmin = the transaction that wrote this version of"); + System.out.println(" the row, xmax = a transaction that has locked or replaced it, 0 = none)"); + if (!tableExists(connection)) { + System.out.println(" The account table does not exist yet. Run ./demo once: it creates the table."); + return; + } + printTable(connection, ACCOUNTS); + System.out.println(); + System.out.println("SESSIONS INSIDE A TRANSACTION (snapshot_xmin is filled in while the session holds a snapshot)"); + int sessions = printTable(connection, SESSIONS); + if (sessions == 0) { + System.out.println(" none. Nothing is running. Start ./demo --pause in another terminal."); + } + System.out.println(); + System.out.println("PREDICATE LOCKS (SIReadLock: what SERIALIZABLE sessions have read. They block nobody)"); + int locks = printTable(connection, PREDICATE_LOCKS); + if (locks == 0) { + System.out.println(" none. No SERIALIZABLE transaction is open."); + } + } + + private static boolean tableExists(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement(); + ResultSet row = statement.executeQuery("select to_regclass('account') is not null")) { + row.next(); + return row.getBoolean(1); + } + } + + /** Prints a query result as a plain text table and returns the number of rows. */ + private static int printTable(Connection connection, String sql) throws SQLException { + List rows = new ArrayList<>(); + try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) { + int columns = result.getMetaData().getColumnCount(); + String[] header = new String[columns]; + for (int c = 0; c < columns; c++) { + header[c] = result.getMetaData().getColumnLabel(c + 1); + } + rows.add(header); + while (result.next()) { + String[] row = new String[columns]; + for (int c = 0; c < columns; c++) { + String value = result.getString(c + 1); + row[c] = value == null ? "" : value; + } + rows.add(row); + } + } + if (rows.size() == 1) { + return 0; + } + int[] widths = new int[rows.get(0).length]; + for (String[] row : rows) { + for (int c = 0; c < row.length; c++) { + widths[c] = Math.max(widths[c], row[c].length()); + } + } + for (int r = 0; r < rows.size(); r++) { + StringBuilder line = new StringBuilder(" "); + for (int c = 0; c < widths.length; c++) { + line.append(String.format("%-" + widths[c] + "s", rows.get(r)[c])).append(" "); + } + System.out.println(line.toString().stripTrailing()); + if (r == 0) { + StringBuilder rule = new StringBuilder(" "); + for (int width : widths) { + rule.append("-".repeat(width)).append(" "); + } + System.out.println(rule.toString().stripTrailing()); + } + } + return rows.size() - 1; + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Lab.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Lab.java new file mode 100644 index 0000000..609c57f --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Lab.java @@ -0,0 +1,323 @@ +package com.amigoscode.isolation.demo; + +import com.amigoscode.isolation.demo.Outcome.Verdict; +import com.amigoscode.isolation.demo.Session.Pending; +import com.amigoscode.isolation.demo.Session.Result; +import java.io.PrintStream; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; +import java.util.Properties; + +/** + * Plain SQL in two sessions, one statement at a time, in a fixed order. No Spring, no Hibernate: + * this is what Postgres itself does at each isolation level. The demo prints it, and the tests + * assert on the {@link Outcome}, so everything the demo shows is also checked. + */ +public final class Lab { + + /** + * @param forUpdate write-skew only: the read locks the rows it reads (SELECT ... FOR UPDATE) + * @param pauseSeconds hold both transactions open for this long in the middle, for ./inspect + */ + public record Options(boolean forUpdate, int pauseSeconds) { + + public static final Options NONE = new Options(false, 0); + } + + private static final int WITHDRAWAL = 800; + + private final String url; + private final String user; + private final String password; + private final Timeline timeline; + + /** @param out where to print the timeline, or null to print nothing */ + public Lab(String url, String user, String password, PrintStream out) { + this.url = url; + this.user = user; + this.password = password; + this.timeline = new Timeline(out); + } + + public Outcome run(Anomaly anomaly, Level level) { + return run(anomaly, level, Options.NONE); + } + + public Outcome run(Anomaly anomaly, Level level, Options options) { + try (Connection monitor = DriverManager.getConnection(url, user, password)) { + Db.reset(monitor); + try (Session a = new Session("A", session(), monitor, timeline); + Session b = new Session("B", session(), monitor, timeline)) { + Run run = new Run(level, options, a, b, monitor); + return switch (anomaly) { + case DIRTY_READ -> dirtyRead(run); + case NON_REPEATABLE_READ -> nonRepeatableRead(run); + case PHANTOM -> phantom(run); + case LOST_UPDATE -> lostUpdate(run); + case WRITE_SKEW -> writeSkew(run); + }; + } + } catch (SQLException e) { + throw new IllegalStateException(e); + } + } + + /** + * A connection that sends every statement as plain text, the way psql does, instead of as a + * prepared statement. Nothing is left open on the server between two statements, so ./inspect + * shows exactly which sessions are holding a snapshot. + */ + private Connection session() throws SQLException { + Properties properties = new Properties(); + properties.setProperty("user", user); + properties.setProperty("password", password); + properties.setProperty("preferQueryMode", "simple"); + return DriverManager.getConnection(url, properties); + } + + /** B changes a balance and does not commit. Can A see the change? */ + private Outcome dirtyRead(Run run) { + Session a = run.a; + Session b = run.b; + a.exec(run.begin()); + a.exec("show transaction_isolation"); + b.exec("begin"); + b.exec("update account set balance = 0 where id = 1"); + run.pause(); + Result read = a.exec("select balance from account where id = 1"); + b.exec("rollback"); + a.end(); + + if (read.value().equals("0")) { + return run.outcome(Anomaly.DIRTY_READ, Verdict.HAPPENED, List.of(read.value()), run.balance(1), + "DIRTY READ. Session A read 0, a value that was never committed."); + } + return run.outcome(Anomaly.DIRTY_READ, Verdict.PREVENTED, List.of(read.value()), run.balance(1), + "NO DIRTY READ. Session A read " + read.value() + " while B's uncommitted 0 was in the table." + + (run.level == Level.READ_UNCOMMITTED + ? " Postgres accepts READ UNCOMMITTED and runs it as READ COMMITTED." : "")); + } + + /** A reads one row twice. B changes it and commits in between. */ + private Outcome nonRepeatableRead(Run run) { + Session a = run.a; + Session b = run.b; + a.exec(run.begin()); + Result first = a.exec("select balance from account where id = 1"); + b.exec("begin"); + b.exec("update account set balance = balance + 100 where id = 1"); + b.exec("commit"); + run.pause(); + Result second = a.exec("select balance from account where id = 1"); + a.end(); + + List seen = List.of(first.value(), second.value()); + if (!first.value().equals(second.value())) { + return run.outcome(Anomaly.NON_REPEATABLE_READ, Verdict.HAPPENED, seen, run.balance(1), + "NON-REPEATABLE READ. Session A read the same row twice in one transaction and got " + + first.value() + ", then " + second.value() + "."); + } + return run.outcome(Anomaly.NON_REPEATABLE_READ, Verdict.PREVENTED, seen, run.balance(1), + "OK. Session A read " + first.value() + " both times. The committed value is " + run.balance(1) + + ", and A will see it in its next transaction."); + } + + /** A runs the same query twice. B inserts a row that matches it and commits in between. */ + private Outcome phantom(Run run) { + Session a = run.a; + Session b = run.b; + String count = "select count(*) from account where owner = 'alice'"; + a.exec(run.begin()); + Result first = a.exec(count); + b.exec("begin"); + b.exec("insert into account (id, owner, name, balance) values (3, 'alice', 'holiday', 250)"); + b.exec("commit"); + run.pause(); + Result second = a.exec(count); + a.end(); + + List seen = List.of(first.value(), second.value()); + long rows = run.number(count); + if (!first.value().equals(second.value())) { + return run.outcome(Anomaly.PHANTOM, Verdict.HAPPENED, seen, rows, + "PHANTOM READ. The same query returned " + first.value() + " rows, then " + second.value() + + ": a row appeared in the middle of Session A's transaction."); + } + return run.outcome(Anomaly.PHANTOM, Verdict.PREVENTED, seen, rows, + "OK. Session A counted " + first.value() + " rows both times. The table has " + rows + + ", and A will see the new one in its next transaction."); + } + + /** A and B each withdraw 100 from the same account: read the balance, subtract in the application, write. */ + private Outcome lostUpdate(Run run) { + Session a = run.a; + Session b = run.b; + String read = "select balance from account where id = 1"; + a.exec(run.begin()); + long balanceA = a.exec(read).number(); + b.exec(run.begin()); + long balanceB = b.exec(read).number(); + b.comment(balanceB + " - 100 = " + (balanceB - 100) + ", worked out in the application"); + b.exec("update account set balance = " + (balanceB - 100) + " where id = 1"); + b.exec("commit"); + run.pause(); + a.comment(balanceA + " - 100 = " + (balanceA - 100) + ", worked out in the application"); + Result write = a.exec("update account set balance = " + (balanceA - 100) + " where id = 1"); + a.end(); + + List seen = List.of(String.valueOf(balanceA), String.valueOf(balanceB)); + long balance = run.balance(1); + if (write.failed()) { + return run.failure(Anomaly.LOST_UPDATE, "A", write, seen, balance, + "Nothing was lost: the balance is " + balance + " after one withdrawal. " + + "A has to run again in a new transaction."); + } + return run.outcome(Anomaly.LOST_UPDATE, Verdict.HAPPENED, seen, balance, + "LOST UPDATE. Two withdrawals of 100 were paid out, but the balance only went from 500 to " + + balance + "."); + } + + /** + * A withdraws 800 from account 1, B withdraws 800 from account 2. Each checks that the two + * accounts together hold at least 800. They write different rows. + */ + private Outcome writeSkew(Run run) { + Session a = run.a; + Session b = run.b; + String read = run.options.forUpdate() + ? "select balance from account where owner = 'alice' order by id for update" + : "select balance from account where owner = 'alice' order by id"; + + a.exec(run.begin()); + Result readA = a.exec(read); + boolean allowedA = run.check(a, readA); + b.exec(run.begin()); + Pending readB = b.send(read); + run.waited = readB.waited(); + boolean allowedB = !readB.waited() && run.check(b, readB.result()); + + Result failure = null; + String failed = null; + if (allowedA) { + Result write = a.exec("update account set balance = balance - " + WITHDRAWAL + " where id = 1"); + if (write.failed()) { + failure = write; + failed = "A"; + } + } + if (allowedB) { + Result write = b.exec("update account set balance = balance - " + WITHDRAWAL + " where id = 2"); + if (write.failed()) { + failure = write; + failed = "B"; + } + } + run.pause(); + Result commitA = a.end(); + if (commitA.failed()) { + failure = commitA; + failed = "A"; + } + if (readB.waited()) { + allowedB = run.check(b, readB.result()); + if (allowedB) { + b.exec("update account set balance = balance - " + WITHDRAWAL + " where id = 2"); + } + } + Result commitB = allowedB || b.failed() ? b.end() : b.exec("rollback"); + if (commitB.failed()) { + failure = commitB; + failed = "B"; + } + + List seen = List.of(String.valueOf(readA.sum()), String.valueOf(readB.result().sum())); + long combined = run.number("select sum(balance) from account where owner = 'alice'"); + if (failure != null) { + return run.failure(Anomaly.WRITE_SKEW, failed, failure, seen, combined, + "The rule holds: the accounts hold " + combined + " together after one withdrawal. " + + failed + " has to run again in a new transaction, and will then see " + combined + "."); + } + if (combined < 0) { + return run.outcome(Anomaly.WRITE_SKEW, Verdict.HAPPENED, seen, combined, + "WRITE SKEW. Both sessions saw 1000, both withdrew " + WITHDRAWAL + ", both committed. " + + "The accounts now hold " + combined + " together. Neither session changed a row the other one changed."); + } + return run.outcome(Anomaly.WRITE_SKEW, Verdict.PREVENTED, seen, combined, + "OK. Session B had to wait for A's row locks, then read " + readB.result().sum() + + " and refused its withdrawal. The accounts hold " + combined + " together."); + } + + /** Everything one run needs. */ + private final class Run { + + private final Level level; + private final Options options; + private final Session a; + private final Session b; + private final Connection monitor; + private boolean waited; + + private Run(Level level, Options options, Session a, Session b, Connection monitor) { + this.level = level; + this.options = options; + this.a = a; + this.b = b; + this.monitor = monitor; + } + + String begin() { + return "begin isolation level " + level.sql(); + } + + /** The application's rule, applied to what a session read: do the accounts together cover the withdrawal? */ + boolean check(Session session, Result read) { + boolean allowed = read.sum() >= WITHDRAWAL; + session.comment(read.addition() + " = " + read.sum() + (allowed + ? ", enough for " + WITHDRAWAL + ": go ahead" + : ", not enough for " + WITHDRAWAL + ": refuse")); + return allowed; + } + + void pause() { + if (options.pauseSeconds() > 0) { + timeline.note("Paused for " + options.pauseSeconds() + + " seconds. Run ./inspect in another terminal now."); + try { + Thread.sleep(options.pauseSeconds() * 1000L); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + + long balance(long accountId) { + return number("select balance from account where id = " + accountId); + } + + long number(String sql) { + try (Statement statement = monitor.createStatement(); ResultSet row = statement.executeQuery(sql)) { + row.next(); + return row.getLong(1); + } catch (SQLException e) { + throw new IllegalStateException(e); + } + } + + Outcome outcome(Anomaly anomaly, Verdict verdict, List seen, long finalValue, String result) { + return new Outcome(anomaly, level, verdict, seen, null, null, null, waited, finalValue, result); + } + + Outcome failure(Anomaly anomaly, String session, Result failure, List seen, long finalValue, + String whatNow) { + String message = failure.error().lines().findFirst().orElse("").replaceFirst("^ERROR: ", ""); + Verdict verdict = "40001".equals(failure.sqlState()) ? Verdict.SERIALIZATION_FAILURE : Verdict.PREVENTED; + return new Outcome(anomaly, level, verdict, seen, session, failure.sqlState(), message, waited, finalValue, + "SERIALIZATION FAILURE (SQLSTATE " + failure.sqlState() + "). Postgres cancelled session " + + session + ": \"" + message + "\". " + whatNow); + } + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Level.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Level.java new file mode 100644 index 0000000..b9a5962 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Level.java @@ -0,0 +1,29 @@ +package com.amigoscode.isolation.demo; + +import java.util.Arrays; +import java.util.Locale; +import java.util.stream.Collectors; + +/** The four isolation levels of the SQL standard, weakest first. */ +public enum Level { + READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE; + + /** As written in SQL: "repeatable read". */ + public String sql() { + return name().toLowerCase(Locale.ROOT).replace('_', ' '); + } + + /** As written on the command line: "repeatable-read". */ + public String flag() { + return name().toLowerCase(Locale.ROOT).replace('_', '-'); + } + + static Level from(String value) { + return Arrays.stream(values()).filter(level -> level.flag().equals(value)).findFirst() + .orElseThrow(() -> new IllegalArgumentException("Unknown level: " + value + ". Use one of: " + names())); + } + + static String names() { + return Arrays.stream(values()).map(Level::flag).collect(Collectors.joining(" | ")); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Outcome.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Outcome.java new file mode 100644 index 0000000..eca7d12 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Outcome.java @@ -0,0 +1,27 @@ +package com.amigoscode.isolation.demo; + +import java.util.List; + +/** + * What one run of one anomaly at one isolation level did. + * + * @param seen the values the sessions read, in the order they read them + * @param failedSession "A" or "B" when the database cancelled one of them, otherwise null + * @param sqlState the SQLSTATE of that failure (40001 is a serialization failure), otherwise null + * @param error the database's error message, otherwise null + * @param waited true when a session had to wait for a lock held by the other one + * @param finalValue what is committed at the end: a balance, a row count or a combined balance + * @param result the RESULT line + */ +public record Outcome(Anomaly anomaly, Level level, Verdict verdict, List seen, String failedSession, + String sqlState, String error, boolean waited, long finalValue, String result) { + + public enum Verdict { + /** The anomaly happened and nobody was told. */ + HAPPENED, + /** It did not happen and both sessions finished normally. */ + PREVENTED, + /** It did not happen because the database cancelled one transaction with SQLSTATE 40001. */ + SERIALIZATION_FAILURE + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Session.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Session.java new file mode 100644 index 0000000..d477553 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Session.java @@ -0,0 +1,243 @@ +package com.amigoscode.isolation.demo; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.stream.Collectors; + +/** + * One database session (one connection) that is driven one statement at a time. Each statement is + * sent as plain SQL, including "begin" and "commit", so the timeline shows exactly what Postgres + * received. + */ +final class Session implements AutoCloseable { + + /** What one statement returned: rows, a row count, or an error. */ + record Result(List> rows, int rowCount, String sqlState, String error) { + + boolean failed() { + return sqlState != null; + } + + /** The first column of the first row. */ + String value() { + return rows.get(0).get(0); + } + + long number() { + return Long.parseLong(value()); + } + + /** The first column of every row, added up. */ + long sum() { + return rows.stream().mapToLong(row -> Long.parseLong(row.get(0))).sum(); + } + + /** The first column of every row: "500 + 500". */ + String addition() { + return rows.stream().map(row -> row.get(0)).collect(Collectors.joining(" + ")); + } + } + + /** A statement that has been sent. It may still be waiting for a lock. */ + final class Pending { + + private final String sql; + private final Future future; + private final boolean waited; + private Result result; + + private Pending(String sql, Future future, boolean waited) { + this.sql = sql; + this.future = future; + this.waited = waited; + } + + /** True when the statement did not return at once because another session holds a lock it needs. */ + boolean waited() { + return waited; + } + + /** Waits for the statement to finish, prints what came back, and returns it. */ + Result result() { + if (result == null) { + try { + result = future.get(); + } catch (InterruptedException | ExecutionException e) { + throw new IllegalStateException(e); + } + report(sql, result, waited); + } + return result; + } + } + + private final String name; + private final Connection connection; + private final Connection monitor; + private final Timeline timeline; + private final int pid; + private final ExecutorService thread; + private boolean failed; + + Session(String name, Connection connection, Connection monitor, Timeline timeline) throws SQLException { + this.name = name; + this.connection = connection; + this.monitor = monitor; + this.timeline = timeline; + this.thread = Executors.newSingleThreadExecutor(task -> { + Thread thread = new Thread(task, "session-" + name); + thread.setDaemon(true); + return thread; + }); + try (Statement statement = connection.createStatement()) { + // The name ./inspect shows for this session. + statement.execute("set application_name = 'demo " + name + "'"); + try (ResultSet row = statement.executeQuery("select pg_backend_pid()")) { + row.next(); + this.pid = row.getInt(1); + } + } + } + + /** Sends one statement and waits for it to finish. */ + Result exec(String sql) { + return send(sql).result(); + } + + /** + * Sends one statement and returns as soon as it has finished or Postgres reports that it is + * waiting for a lock. Nothing here guesses with a timer: it asks pg_blocking_pids(). + */ + Pending send(String sql) { + timeline.step(name, sql); + Future future = thread.submit(() -> run(sql)); + boolean waiting = false; + try { + while (!future.isDone() && !(waiting = isWaitingForALock())) { + Thread.sleep(20); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + Pending pending = new Pending(sql, future, waiting); + if (waiting) { + timeline.result(name, "WAITING. Another session holds a lock this statement needs"); + } else { + pending.result(); + } + return pending; + } + + /** Ends the transaction: commit, or rollback when a statement in it has already failed. */ + Result end() { + if (failed) { + Result result = exec("rollback"); + timeline.comment(name, "this transaction was cancelled, so there is nothing to commit"); + return result; + } + return exec("commit"); + } + + /** Prints what the application does with a value it read, outside the database. */ + void comment(String text) { + timeline.comment(name, text); + } + + /** True when the database has cancelled this session's transaction. */ + boolean failed() { + return failed; + } + + private Result run(String sql) { + try (Statement statement = connection.createStatement()) { + List> rows = new ArrayList<>(); + if (statement.execute(sql)) { + try (ResultSet result = statement.getResultSet()) { + int columns = result.getMetaData().getColumnCount(); + while (result.next()) { + List row = new ArrayList<>(); + for (int c = 1; c <= columns; c++) { + row.add(String.valueOf(result.getObject(c))); + } + rows.add(row); + } + } + return new Result(rows, rows.size(), null, null); + } + Result result = new Result(rows, statement.getUpdateCount(), null, null); + if (sql.strip().toLowerCase(Locale.ROOT).startsWith("begin")) { + reportIsolationLevel(statement); + } + return result; + } catch (SQLException e) { + return new Result(List.of(), 0, e.getSQLState(), e.getMessage()); + } + } + + /** + * Postgres has no column that shows another session's isolation level, so every demo session + * puts its own level into its application_name, where ./inspect can read it. SHOW and SET do + * not take a snapshot, so this changes nothing about what the transaction will see. + */ + private void reportIsolationLevel(Statement statement) throws SQLException { + String level; + try (ResultSet row = statement.executeQuery("show transaction_isolation")) { + row.next(); + level = row.getString(1); + } + statement.execute("set local application_name = 'demo " + name + " (" + level + ")'"); + } + + private void report(String sql, Result result, boolean waited) { + String prefix = waited ? "(stopped waiting) " : ""; + String verb = sql.strip().toLowerCase(Locale.ROOT).split("\\s+")[0]; + if (result.failed()) { + // The transaction is now unusable until it is rolled back. A failed COMMIT has already rolled it back. + failed = !verb.equals("commit") && !verb.equals("rollback"); + List lines = result.error().lines().map(String::strip).filter(line -> !line.isEmpty()).toList(); + timeline.result(name, prefix + "ERROR, SQLSTATE " + result.sqlState() + ": " + + lines.get(0).replaceFirst("^ERROR: ", "")); + lines.stream().skip(1).limit(2).forEach(line -> timeline.result(name, line)); + } else if (!result.rows().isEmpty()) { + timeline.result(name, prefix + result.rows().stream() + .map(row -> String.join(" ", row)).collect(Collectors.joining(", "))); + } else if (verb.equals("update") || verb.equals("insert") || verb.equals("delete")) { + timeline.result(name, prefix + result.rowCount() + (result.rowCount() == 1 ? " row" : " rows")); + } else if (verb.equals("rollback") || verb.equals("commit")) { + failed = false; + } + } + + private boolean isWaitingForALock() { + try (PreparedStatement statement = monitor.prepareStatement("select cardinality(pg_blocking_pids(?)) > 0")) { + statement.setInt(1, pid); + try (ResultSet row = statement.executeQuery()) { + row.next(); + return row.getBoolean(1); + } + } catch (SQLException e) { + throw new IllegalStateException(e); + } + } + + @Override + public void close() { + thread.shutdownNow(); + try { + connection.close(); + } catch (SQLException ignored) { + // closing anyway + } + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Timeline.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Timeline.java new file mode 100644 index 0000000..b1a5eea --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Timeline.java @@ -0,0 +1,45 @@ +package com.amigoscode.isolation.demo; + +import java.io.PrintStream; + +/** Prints what each session does, one step per line. Session B is indented so the two are easy to tell apart. */ +final class Timeline { + + private final PrintStream out; + + /** @param out where to print, or null to print nothing (the tests) */ + Timeline(PrintStream out) { + this.out = out; + } + + /** Something a session does. */ + void step(String session, String text) { + print(indent(session) + session + " | " + text); + } + + /** What came back. */ + void result(String session, String text) { + print(indent(session) + session + " | -> " + text); + } + + /** What the application does with a value, outside the database. */ + void comment(String session, String text) { + print(indent(session) + session + " | # " + text); + } + + void note(String text) { + print(""); + print(" " + text); + print(""); + } + + void print(String line) { + if (out != null) { + out.println(line); + } + } + + private static String indent(String session) { + return session.equals("A") ? " " : " "; + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/statement/Statement.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/statement/Statement.java new file mode 100644 index 0000000..f241f7f --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/statement/Statement.java @@ -0,0 +1,19 @@ +package com.amigoscode.isolation.statement; + +import java.util.List; + +/** What the customer is shown: one line per account, then how many accounts and the total. */ +public record Statement(String owner, List lines, long accountCount, long total) { + + public record Line(String account, long balance) { + } + + public long sumOfLines() { + return lines.stream().mapToLong(Line::balance).sum(); + } + + /** A statement a customer can trust: the lines are all the accounts, and they add up to the total. */ + public boolean addsUp() { + return lines.size() == accountCount && sumOfLines() == total; + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/statement/StatementService.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/statement/StatementService.java new file mode 100644 index 0000000..3c900da --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/statement/StatementService.java @@ -0,0 +1,37 @@ +package com.amigoscode.isolation.statement; + +import com.amigoscode.isolation.account.AccountRepository; +import com.amigoscode.isolation.checkpoint.Checkpoint; +import com.amigoscode.isolation.statement.Statement.Line; +import java.util.List; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class StatementService { + + private final AccountRepository accounts; + private final Checkpoint checkpoint; + + public StatementService(AccountRepository accounts, Checkpoint checkpoint) { + this.accounts = accounts; + this.checkpoint = checkpoint; + } + + /** + * Three queries, one transaction. At REPEATABLE READ the transaction takes one snapshot at its + * first query and every later query reads from that same snapshot, so the lines, the count and + * the total always describe the same moment, whatever other sessions commit in between. + */ + @Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ) + public Statement statement(String owner) { + List lines = accounts.findByOwnerOrderById(owner).stream() // QUERY 1: the lines + .map(account -> new Line(account.getName(), account.getBalance())) + .toList(); + checkpoint.reached(Checkpoint.LINES_READ); // ...time passes... + long accountCount = accounts.countByOwner(owner); // QUERY 2: how many accounts + long total = accounts.totalBalance(owner); // QUERY 3: the total + return new Statement(owner, lines, accountCount, total); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/InsufficientFundsException.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/InsufficientFundsException.java new file mode 100644 index 0000000..0a6a478 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/InsufficientFundsException.java @@ -0,0 +1,9 @@ +package com.amigoscode.isolation.withdrawal; + +public class InsufficientFundsException extends RuntimeException { + + public InsufficientFundsException(long accountId, long amount, long available) { + super("Cannot withdraw " + amount + " from account " + accountId + + ": the customer's accounts hold " + available + " in total"); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalConflictException.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalConflictException.java new file mode 100644 index 0000000..7216916 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalConflictException.java @@ -0,0 +1,10 @@ +package com.amigoscode.isolation.withdrawal; + +/** Every attempt was cancelled by the database. Nothing was withdrawn, and it is safe to try again. */ +public class WithdrawalConflictException extends RuntimeException { + + public WithdrawalConflictException(long accountId, int attempts, Throwable cause) { + super("Withdrawal from account " + accountId + " was cancelled " + attempts + + " times by concurrent transactions. Nothing was withdrawn. Try again.", cause); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalService.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalService.java new file mode 100644 index 0000000..7f43b9d --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalService.java @@ -0,0 +1,35 @@ +package com.amigoscode.isolation.withdrawal; + +import org.springframework.dao.ConcurrencyFailureException; +import org.springframework.stereotype.Service; + +/** + * Deliberately NOT transactional. When Postgres cancels a transaction with SQLSTATE 40001 the whole + * transaction is gone, so the only way to try again is a brand new transaction that reads + * everything again. The loop therefore lives outside the transactional bean. + */ +@Service +public class WithdrawalService { + + public static final int MAX_ATTEMPTS = 3; + + private final Withdrawer withdrawer; + + public WithdrawalService(Withdrawer withdrawer) { + this.withdrawer = withdrawer; + } + + public long withdraw(long accountId, long amount) { + for (int attempt = 1; ; attempt++) { + try { + return withdrawer.withdraw(accountId, amount); + } catch (ConcurrencyFailureException e) { + // SQLSTATE 40001 arrives as CannotAcquireLockException, a ConcurrencyFailureException. + // The transaction is already rolled back, so the next attempt re-reads the balances. + if (attempt == MAX_ATTEMPTS) { + throw new WithdrawalConflictException(accountId, attempt, e); + } + } + } + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/Withdrawer.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/Withdrawer.java new file mode 100644 index 0000000..19aae44 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/Withdrawer.java @@ -0,0 +1,47 @@ +package com.amigoscode.isolation.withdrawal; + +import com.amigoscode.isolation.account.Account; +import com.amigoscode.isolation.account.AccountNotFoundException; +import com.amigoscode.isolation.account.AccountRepository; +import com.amigoscode.isolation.checkpoint.Checkpoint; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; + +/** One database transaction per call: one attempt at a withdrawal. */ +@Service +public class Withdrawer { + + private final AccountRepository accounts; + private final Checkpoint checkpoint; + + public Withdrawer(AccountRepository accounts, Checkpoint checkpoint) { + this.accounts = accounts; + this.checkpoint = checkpoint; + } + + /** + * The rule: one account may go below zero, as long as all of the customer's accounts together + * stay at zero or above. So the decision is based on rows this transaction READS but does not + * WRITE. Only SERIALIZABLE makes the database track that: if another transaction changed what + * this one read, one of the two is cancelled with SQLSTATE 40001, and WithdrawalService runs it + * again. + * + * @return the new balance of the account + */ + @Transactional(isolation = Isolation.SERIALIZABLE) + public long withdraw(long accountId, long amount) { + if (amount <= 0) { + throw new IllegalArgumentException("amount must be positive, got " + amount); + } + Account account = accounts.findById(accountId) // READ this account + .orElseThrow(() -> new AccountNotFoundException(accountId)); + long available = accounts.totalBalance(account.getOwner()); // READ all the customer's accounts + if (available < amount) { // CHECK the rule + throw new InsufficientFundsException(accountId, amount, available); + } + checkpoint.reached(Checkpoint.FUNDS_CHECKED); // ...time passes... + account.setBalance(account.getBalance() - amount); // WRITE a value computed from the READ + return account.getBalance(); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/resources/application.properties b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/resources/application.properties new file mode 100644 index 0000000..6de13d3 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/resources/application.properties @@ -0,0 +1,16 @@ +spring.application.name=isolation-levels + +# Postgres from compose.yaml. Port 5448 so it does not clash with a Postgres you already run. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5448/bank} +spring.datasource.username=${DB_USER:bank} +spring.datasource.password=${DB_PASSWORD:bank} +# The name ./inspect shows for the application's database sessions. +spring.datasource.hikari.data-source-properties.ApplicationName=bank-app + +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false +spring.sql.init.mode=always +spring.main.web-application-type=none + +# Uncomment to see every SQL statement Hibernate sends. +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/resources/schema.sql b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/resources/schema.sql new file mode 100644 index 0000000..fd5a4da --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/resources/schema.sql @@ -0,0 +1,13 @@ +create table if not exists account ( + id bigint primary key, + owner text not null, + name text not null, + balance bigint not null +); + +-- One customer, two accounts. The bank's rule: a single account may go below zero, +-- as long as the customer's accounts added together stay at zero or above. +insert into account (id, owner, name, balance) +values (1, 'alice', 'current', 500), + (2, 'alice', 'savings', 500) +on conflict (id) do nothing; diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/BaselineIT.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/BaselineIT.java new file mode 100644 index 0000000..966aa7e --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/BaselineIT.java @@ -0,0 +1,56 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.isolation.statement.Statement; +import com.amigoscode.isolation.support.IntegrationTest; +import com.amigoscode.isolation.withdrawal.InsufficientFundsException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** The bank's rules with one customer at a time. These pass from the start and must stay green. */ +@Tag("baseline") +class BaselineIT extends IntegrationTest { + + @Test + @DisplayName("Withdrawal: 100 from the current account leaves 400, and the new balance is returned") + void withdrawalLowersTheBalance() { + long newBalance = withdrawalService.withdraw(CURRENT, 100); + + assertThat(newBalance).as("returned balance").isEqualTo(400); + assertThat(balance(CURRENT)).as("current account").isEqualTo(400); + assertThat(balance(SAVINGS)).as("savings account").isEqualTo(500); + } + + @Test + @DisplayName("Withdrawal: one account may go below zero while both accounts together stay at zero or above") + void oneAccountMayGoNegative() { + withdrawalService.withdraw(CURRENT, 800); + + assertThat(balance(CURRENT)).as("current account").isEqualTo(-300); + assertThat(combinedBalance()).as("both accounts together").isEqualTo(200); + } + + @Test + @DisplayName("Withdrawal: refused when both accounts together cannot cover it, and nothing changes") + void refusedWhenTheAccountsTogetherCannotCoverIt() { + assertThatThrownBy(() -> withdrawalService.withdraw(CURRENT, 1001)) + .isInstanceOf(InsufficientFundsException.class); + + assertThat(balance(CURRENT)).as("current account").isEqualTo(500); + assertThat(combinedBalance()).as("both accounts together").isEqualTo(1000); + } + + @Test + @DisplayName("Statement: with nobody else writing, it lists both accounts and they add up to the total") + void statementAddsUpWhenNobodyElseIsWriting() { + Statement statement = statementService.statement("alice"); + + assertThat(statement.lines()).as("lines").hasSize(2); + assertThat(statement.accountCount()).as("account count").isEqualTo(2); + assertThat(statement.total()).as("total").isEqualTo(1000); + assertThat(statement.addsUp()).as("lines add up to the total").isTrue(); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/Check.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/Check.java new file mode 100644 index 0000000..18aad18 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/Check.java @@ -0,0 +1,114 @@ +package com.amigoscode.isolation; + +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage; + +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.platform.engine.TestExecutionResult; +import org.junit.platform.engine.discovery.ClassNameFilter; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +import org.junit.platform.launcher.TagFilter; +import org.junit.platform.launcher.TestExecutionListener; +import org.junit.platform.launcher.TestIdentifier; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; + +/** + * Runs the tests that belong to one task and prints one line per acceptance criterion. + * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2 + * (./mvnw verify runs the same tests the usual Maven way.) + */ +public final class Check { + + /** Tasks that have tests. Tasks 3, 5 and 7 are inspection tasks: you answer questions, no code. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: the bank's rules, one customer at a time (passes from the start, must stay green)"); + TASKS.put("1", "Task 1: See the statement that does not add up"); + TASKS.put("2", "Task 2: Fix the statement with REPEATABLE READ"); + TASKS.put("4", "Task 4: Stop the lost update, and retry the serialization failure"); + TASKS.put("6", "Task 6: Fix the write skew with SERIALIZABLE"); + TASKS.put("8", "Task 8: Isolation levels vs locking"); + } + + public static void main(String[] args) { + if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-8]"))) { + System.out.println("Usage: ./check [task] task is a number from 1 to 8. No number checks everything."); + System.exit(2); + } + if (args.length == 1 && !TASKS.containsKey(args[0])) { + System.out.println(); + System.out.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:"); + System.out.println("follow its steps in INTERVIEW_TASKS.md and answer the questions."); + System.out.println(); + return; + } + + boolean allGreen = true; + Launcher launcher = LauncherFactory.create(); + for (Map.Entry task : TASKS.entrySet()) { + if (args.length == 1 && !task.getKey().equals(args[0])) { + continue; + } + String tag = task.getKey().equals("baseline") ? "baseline" : "task" + task.getKey(); + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() + .selectors(selectPackage(Check.class.getPackageName())) + .filters(ClassNameFilter.includeClassNamePatterns(".*"), TagFilter.includeTags(tag)) + .build(); + System.out.println(); + System.out.println(task.getValue()); + Results results = new Results(); + launcher.execute(request, results); + System.out.println(" " + results.passed + " of " + results.total + " pass"); + allGreen &= results.passed == results.total && results.total > 0; + } + System.out.println(); + System.exit(allGreen ? 0 : 1); + } + + private static final class Results implements TestExecutionListener { + + private int total; + private int passed; + + @Override + public void executionFinished(TestIdentifier test, TestExecutionResult result) { + boolean ok = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL; + if (!test.isTest()) { + // A container that fails (for example the Spring context cannot start) takes its tests with it. + if (!ok) { + total++; + System.out.println(" [FAIL] " + test.getDisplayName() + " could not start"); + result.getThrowable().ifPresent(Results::printReason); + } + return; + } + total++; + if (ok) { + passed++; + System.out.println(" [PASS] " + test.getDisplayName()); + } else { + System.out.println(" [FAIL] " + test.getDisplayName()); + result.getThrowable().ifPresent(Results::printReason); + } + } + + private static void printReason(Throwable throwable) { + Throwable root = throwable; + while (root.getCause() != null && root.getCause() != root && root.getMessage() == null) { + root = root.getCause(); + } + String message = root.getMessage() == null ? root.getClass().getSimpleName() : root.getMessage(); + message.strip().lines() + .map(String::strip) + .filter(line -> !line.isEmpty()) + .limit(6) + .forEach(line -> System.out.println(" " + line)); + } + } + + private Check() { + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/IsolationVsLockingIT.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/IsolationVsLockingIT.java new file mode 100644 index 0000000..6802c75 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/IsolationVsLockingIT.java @@ -0,0 +1,44 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.isolation.demo.Anomaly; +import com.amigoscode.isolation.demo.Lab; +import com.amigoscode.isolation.demo.Level; +import com.amigoscode.isolation.demo.Outcome; +import com.amigoscode.isolation.demo.Outcome.Verdict; +import com.amigoscode.isolation.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 8. These pass from the start: they pin down the difference between raising the isolation + * level and taking a lock, on the same write-skew scenario. + */ +@Tag("task8") +class IsolationVsLockingIT extends IntegrationTest { + + @Test + @DisplayName("A lock makes the other session WAIT: with SELECT ... FOR UPDATE at READ COMMITTED, B waits for A, then reads 200 and refuses") + void forUpdateMakesTheSecondSessionWait() { + Outcome outcome = lab().run(Anomaly.WRITE_SKEW, Level.READ_COMMITTED, new Lab.Options(true, 0)); + + assertThat(outcome.waited()).as("session B had to wait for a lock").isTrue(); + assertThat(outcome.seen()).as("the combined balance each session saw").containsExactly("1000", "200"); + assertThat(outcome.failedSession()).as("session cancelled by the database").isNull(); + assertThat(outcome.finalValue()).as("both accounts together").isEqualTo(200); + assertThat(outcome.verdict()).isEqualTo(Verdict.PREVENTED); + } + + @Test + @DisplayName("An isolation level makes nobody wait: at SERIALIZABLE both sessions read 1000 at once, and one is CANCELLED instead") + void serializableCancelsInsteadOfWaiting() { + Outcome outcome = lab().run(Anomaly.WRITE_SKEW, Level.SERIALIZABLE); + + assertThat(outcome.waited()).as("a session had to wait for a lock").isFalse(); + assertThat(outcome.seen()).as("the combined balance each session saw").containsExactly("1000", "1000"); + assertThat(outcome.failedSession()).as("session cancelled by the database").isEqualTo("B"); + assertThat(outcome.finalValue()).as("both accounts together").isEqualTo(200); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/LostUpdateIT.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/LostUpdateIT.java new file mode 100644 index 0000000..81471a0 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/LostUpdateIT.java @@ -0,0 +1,80 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.amigoscode.isolation.checkpoint.Checkpoint; +import com.amigoscode.isolation.demo.Anomaly; +import com.amigoscode.isolation.demo.Level; +import com.amigoscode.isolation.demo.Outcome; +import com.amigoscode.isolation.demo.Outcome.Verdict; +import com.amigoscode.isolation.support.IntegrationTest; +import java.sql.SQLException; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.CannotAcquireLockException; + +@Tag("task4") +class LostUpdateIT extends IntegrationTest { + + @Test + @DisplayName("READ COMMITTED: lost update. Two withdrawals of 100 are paid out and the balance only goes from 500 to 400") + void readCommittedLosesAnUpdate() { + Outcome outcome = lab().run(Anomaly.LOST_UPDATE, Level.READ_COMMITTED); + + assertThat(outcome.seen()).as("the balance each session read").containsExactly("500", "500"); + assertThat(outcome.finalValue()).as("balance after two withdrawals of 100").isEqualTo(400); + assertThat(outcome.verdict()).isEqualTo(Verdict.HAPPENED); + } + + @Test + @DisplayName("REPEATABLE READ: the second writer is cancelled with SQLSTATE 40001, could not serialize access due to concurrent update") + void repeatableReadCancelsTheSecondWriter() { + Outcome outcome = lab().run(Anomaly.LOST_UPDATE, Level.REPEATABLE_READ); + + assertThat(outcome.verdict()).isEqualTo(Verdict.SERIALIZATION_FAILURE); + assertThat(outcome.sqlState()).as("SQLSTATE").isEqualTo("40001"); + assertThat(outcome.error()).isEqualTo("could not serialize access due to concurrent update"); + assertThat(outcome.finalValue()).as("balance after the one withdrawal that committed").isEqualTo(400); + } + + @Test + @DisplayName("Withdrawer: one attempt that loses the race fails with Spring's CannotAcquireLockException, caused by SQLSTATE 40001") + void theLosingAttemptFailsWithCannotAcquireLockException() { + // In the middle of our attempt, another customer session withdraws 100 from the same account and commits. + checkpoint.onFirst(Checkpoint.FUNDS_CHECKED, () -> inAnotherThread(() -> withdrawer.withdraw(CURRENT, 100))); + + Throwable thrown = catchThrowable(() -> withdrawer.withdraw(CURRENT, 100)); + + assertThat(thrown).as("what one losing attempt throws").isInstanceOf(CannotAcquireLockException.class); + assertThat(thrown).rootCause().isInstanceOf(SQLException.class); + assertThat(((SQLException) rootCause(thrown)).getSQLState()).as("SQLSTATE").isEqualTo("40001"); + assertThat(balance(CURRENT)).as("balance: only the other withdrawal committed").isEqualTo(400); + } + + @Test + @DisplayName("Withdrawal: two withdrawals of 100 from the same account both go through, one on its second attempt, and the balance is 300") + void bothWithdrawalsGoThroughAndNothingIsLost() { + AtomicReference other = new AtomicReference<>(); + checkpoint.onFirst(Checkpoint.FUNDS_CHECKED, + () -> other.set(inAnotherThread(() -> withdrawalService.withdraw(CURRENT, 100)))); + + long newBalance = withdrawalService.withdraw(CURRENT, 100); + + assertThat(other.get()).as("what the other withdrawal threw").isNull(); + assertThat(balance(CURRENT)).as("balance after two withdrawals of 100").isEqualTo(300); + assertThat(newBalance).as("balance returned to the customer who retried").isEqualTo(300); + assertThat(checkpoint.arrivals(Checkpoint.FUNDS_CHECKED)) + .as("attempts: ours, the other customer's, and our second one").isEqualTo(3); + } + + private static Throwable rootCause(Throwable throwable) { + Throwable root = throwable; + while (root.getCause() != null) { + root = root.getCause(); + } + return root; + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/ReadCommittedIT.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/ReadCommittedIT.java new file mode 100644 index 0000000..ac5f00e --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/ReadCommittedIT.java @@ -0,0 +1,77 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.isolation.demo.Anomaly; +import com.amigoscode.isolation.demo.Level; +import com.amigoscode.isolation.demo.Outcome; +import com.amigoscode.isolation.demo.Outcome.Verdict; +import com.amigoscode.isolation.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Task 1. These tests pass on purpose: they pin down what Postgres does at its default level, and + * at the level below it. Each one drives two sessions with plain SQL, one statement at a time. + */ +@Tag("task1") +class ReadCommittedIT extends IntegrationTest { + + @Autowired + private PlatformTransactionManager transactionManager; + + @Test + @DisplayName("Default: Postgres runs at READ COMMITTED, and so does a Spring transaction that sets no isolation level") + void theDefaultIsReadCommitted() { + String postgresDefault = jdbc.queryForObject("show default_transaction_isolation", String.class); + String springDefault = new TransactionTemplate(transactionManager) + .execute(status -> isolationLevelOfThisTransaction()); + + assertThat(postgresDefault).as("default_transaction_isolation").isEqualTo("read committed"); + assertThat(springDefault).as("level of a default Spring transaction").isEqualTo("read committed"); + } + + @Test + @DisplayName("READ COMMITTED: non-repeatable read. One transaction reads a balance twice and gets 500, then 600") + void nonRepeatableRead() { + Outcome outcome = lab().run(Anomaly.NON_REPEATABLE_READ, Level.READ_COMMITTED); + + assertThat(outcome.seen()).as("what session A read, in one transaction").containsExactly("500", "600"); + assertThat(outcome.verdict()).isEqualTo(Verdict.HAPPENED); + } + + @Test + @DisplayName("READ COMMITTED: phantom read. The same count returns 2 rows, then 3") + void phantomRead() { + Outcome outcome = lab().run(Anomaly.PHANTOM, Level.READ_COMMITTED); + + assertThat(outcome.seen()).as("what session A counted, in one transaction").containsExactly("2", "3"); + assertThat(outcome.verdict()).isEqualTo(Verdict.HAPPENED); + } + + @Test + @DisplayName("READ UNCOMMITTED: no dirty read in Postgres. Another session's uncommitted change stays invisible") + void noDirtyReadEvenAtReadUncommitted() { + Outcome outcome = lab().run(Anomaly.DIRTY_READ, Level.READ_UNCOMMITTED); + + assertThat(outcome.seen()).as("what session A read while B's uncommitted 0 was in the table") + .containsExactly("500"); + assertThat(outcome.verdict()).isEqualTo(Verdict.PREVENTED); + } + + @Test + @DisplayName("READ UNCOMMITTED: for every anomaly it behaves exactly like READ COMMITTED") + void readUncommittedBehavesAsReadCommitted() { + for (Anomaly anomaly : Anomaly.values()) { + Outcome readUncommitted = lab().run(anomaly, Level.READ_UNCOMMITTED); + Outcome readCommitted = lab().run(anomaly, Level.READ_COMMITTED); + + assertThat(readUncommitted.verdict()).as(anomaly.flag()).isEqualTo(readCommitted.verdict()); + assertThat(readUncommitted.seen()).as(anomaly.flag()).isEqualTo(readCommitted.seen()); + } + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/StatementIT.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/StatementIT.java new file mode 100644 index 0000000..1b14de8 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/StatementIT.java @@ -0,0 +1,90 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.isolation.checkpoint.Checkpoint; +import com.amigoscode.isolation.demo.Anomaly; +import com.amigoscode.isolation.demo.Level; +import com.amigoscode.isolation.demo.Outcome; +import com.amigoscode.isolation.demo.Outcome.Verdict; +import com.amigoscode.isolation.statement.Statement; +import com.amigoscode.isolation.support.IntegrationTest; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +@Tag("task2") +class StatementIT extends IntegrationTest { + + @Test + @DisplayName("REPEATABLE READ: one transaction reads a balance twice and gets 500 both times, although 600 is committed") + void repeatableReadReadsTheSameValueTwice() { + Outcome outcome = lab().run(Anomaly.NON_REPEATABLE_READ, Level.REPEATABLE_READ); + + assertThat(outcome.seen()).as("what session A read, in one transaction").containsExactly("500", "500"); + assertThat(outcome.finalValue()).as("committed balance").isEqualTo(600); + assertThat(outcome.verdict()).isEqualTo(Verdict.PREVENTED); + } + + @Test + @DisplayName("REPEATABLE READ: no phantom in Postgres. The same count returns 2 rows both times, although 3 are committed") + void repeatableReadHasNoPhantomsInPostgres() { + Outcome outcome = lab().run(Anomaly.PHANTOM, Level.REPEATABLE_READ); + + assertThat(outcome.seen()).as("what session A counted, in one transaction").containsExactly("2", "2"); + assertThat(outcome.finalValue()).as("committed rows").isEqualTo(3); + assertThat(outcome.verdict()).isEqualTo(Verdict.PREVENTED); + } + + @Test + @DisplayName("Statement: a deposit commits between its queries, and the lines still add up to the total") + void aDepositInTheMiddleDoesNotBreakTheStatement() { + checkpoint.onFirst(Checkpoint.LINES_READ, + () -> inAnotherSession("update account set balance = balance + 100 where id = 1")); + + Statement statement = statementService.statement("alice"); + + assertThat(balance(CURRENT)).as("the deposit is committed").isEqualTo(600); + assertThat(statement.total()).as("total, when the lines add up to " + statement.sumOfLines()) + .isEqualTo(statement.sumOfLines()); + } + + @Test + @DisplayName("Statement: an account is opened between its queries, and the count still matches the lines") + void aNewAccountInTheMiddleDoesNotBreakTheStatement() { + checkpoint.onFirst(Checkpoint.LINES_READ, () -> inAnotherSession( + "insert into account (id, owner, name, balance) values (3, 'alice', 'holiday', 250)")); + + Statement statement = statementService.statement("alice"); + + assertThat(statement.accountCount()).as("account count, when the statement lists " + + statement.lines().size() + " lines").isEqualTo(statement.lines().size()); + assertThat(statement.total()).as("total, when the lines add up to " + statement.sumOfLines()) + .isEqualTo(statement.sumOfLines()); + } + + @Test + @DisplayName("Statement: all of its queries run in one REPEATABLE READ transaction") + void statementRunsAtRepeatableRead() { + AtomicReference level = new AtomicReference<>(); + checkpoint.onFirst(Checkpoint.LINES_READ, () -> level.set(isolationLevelOfThisTransaction())); + + statementService.statement("alice"); + + assertThat(level.get()).as("isolation level in the middle of statement()").isEqualTo("repeatable read"); + } + + @Test + @DisplayName("Statement: the snapshot ends with the transaction. The next statement shows the deposit") + void theNextStatementSeesTheDeposit() { + checkpoint.onFirst(Checkpoint.LINES_READ, + () -> inAnotherSession("update account set balance = balance + 100 where id = 1")); + statementService.statement("alice"); + + Statement next = statementService.statement("alice"); + + assertThat(next.total()).as("total of the next statement").isEqualTo(1100); + assertThat(next.addsUp()).as("lines add up to the total").isTrue(); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/WithdrawalServiceRetryTest.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/WithdrawalServiceRetryTest.java new file mode 100644 index 0000000..1337190 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/WithdrawalServiceRetryTest.java @@ -0,0 +1,99 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.isolation.withdrawal.InsufficientFundsException; +import com.amigoscode.isolation.withdrawal.WithdrawalConflictException; +import com.amigoscode.isolation.withdrawal.WithdrawalService; +import com.amigoscode.isolation.withdrawal.Withdrawer; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.dao.CannotAcquireLockException; +import org.springframework.transaction.annotation.Transactional; + +/** + * Unit tests: no Spring, no database. Withdrawer is replaced by a scripted stub, so only the retry + * loop in WithdrawalService is under test and the whole class runs in milliseconds. + */ +@Tag("task4") +class WithdrawalServiceRetryTest { + + @Test + @DisplayName("Retry: when Postgres cancels the transaction (40001), the withdrawal is tried again and succeeds") + void retriesAfterASerializationFailure() { + ScriptedWithdrawer withdrawer = new ScriptedWithdrawer(serializationFailure(), 300L); + + long newBalance = new WithdrawalService(withdrawer).withdraw(1, 100); + + assertThat(newBalance).as("returned balance").isEqualTo(300); + assertThat(withdrawer.attempts).as("attempts").isEqualTo(2); + } + + @Test + @DisplayName("Retry: after 3 cancelled attempts it stops and throws WithdrawalConflictException") + void givesUpAfterThreeAttempts() { + ScriptedWithdrawer withdrawer = new ScriptedWithdrawer(serializationFailure()); + + assertThatThrownBy(() -> new WithdrawalService(withdrawer).withdraw(1, 100)) + .isInstanceOf(WithdrawalConflictException.class); + + assertThat(withdrawer.attempts).as("attempts").isEqualTo(3); + } + + @Test + @DisplayName("Retry: insufficient funds is not retried, because trying again cannot change the answer") + void doesNotRetryInsufficientFunds() { + ScriptedWithdrawer withdrawer = new ScriptedWithdrawer(new InsufficientFundsException(1, 100, 0)); + + assertThatThrownBy(() -> new WithdrawalService(withdrawer).withdraw(1, 100)) + .isInstanceOf(InsufficientFundsException.class); + + assertThat(withdrawer.attempts).as("attempts").isEqualTo(1); + } + + @Test + @DisplayName("Retry: WithdrawalService is not @Transactional, so every attempt gets a new transaction") + void theRetryLoopIsOutsideTheTransaction() throws NoSuchMethodException { + assertThat(AnnotatedElementUtils.hasAnnotation(WithdrawalService.class, Transactional.class)) + .as("@Transactional on the WithdrawalService class").isFalse(); + assertThat(AnnotatedElementUtils.hasAnnotation( + WithdrawalService.class.getMethod("withdraw", long.class, long.class), Transactional.class)) + .as("@Transactional on WithdrawalService.withdraw").isFalse(); + } + + /** What Spring throws for SQLSTATE 40001. LostUpdateIT proves that against a real database. */ + private static CannotAcquireLockException serializationFailure() { + return new CannotAcquireLockException("could not serialize access due to concurrent update"); + } + + /** + * Plays back a script: each call to withdraw returns the next balance or throws the next + * exception. The last entry repeats for ever. + */ + private static final class ScriptedWithdrawer extends Withdrawer { + + private final Deque script; + private int attempts; + + ScriptedWithdrawer(Object... outcomes) { + super(null, null); + this.script = new ArrayDeque<>(List.of(outcomes)); + } + + @Override + public long withdraw(long accountId, long amount) { + attempts++; + Object outcome = script.size() > 1 ? script.poll() : script.peek(); + if (outcome instanceof RuntimeException exception) { + throw exception; + } + return (Long) outcome; + } + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/WriteSkewIT.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/WriteSkewIT.java new file mode 100644 index 0000000..28d5d92 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/WriteSkewIT.java @@ -0,0 +1,117 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.amigoscode.isolation.checkpoint.Checkpoint; +import com.amigoscode.isolation.demo.Anomaly; +import com.amigoscode.isolation.demo.Level; +import com.amigoscode.isolation.demo.Outcome; +import com.amigoscode.isolation.demo.Outcome.Verdict; +import com.amigoscode.isolation.support.IntegrationTest; +import com.amigoscode.isolation.withdrawal.InsufficientFundsException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.CannotAcquireLockException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +@Tag("task6") +class WriteSkewIT extends IntegrationTest { + + @Autowired + private PlatformTransactionManager transactionManager; + + @Test + @DisplayName("REPEATABLE READ: write skew. Both sessions see 1000, both withdraw 800, both commit, and the accounts hold -600") + void repeatableReadAllowsWriteSkew() { + Outcome outcome = lab().run(Anomaly.WRITE_SKEW, Level.REPEATABLE_READ); + + assertThat(outcome.seen()).as("the combined balance each session saw").containsExactly("1000", "1000"); + assertThat(outcome.failedSession()).as("session cancelled by the database").isNull(); + assertThat(outcome.finalValue()).as("both accounts together").isEqualTo(-600); + assertThat(outcome.verdict()).isEqualTo(Verdict.HAPPENED); + } + + @Test + @DisplayName("SERIALIZABLE: the second session is cancelled at COMMIT with SQLSTATE 40001, and the accounts keep 200") + void serializableCancelsOneOfTheTwo() { + Outcome outcome = lab().run(Anomaly.WRITE_SKEW, Level.SERIALIZABLE); + + assertThat(outcome.verdict()).isEqualTo(Verdict.SERIALIZATION_FAILURE); + assertThat(outcome.sqlState()).as("SQLSTATE").isEqualTo("40001"); + assertThat(outcome.error()) + .isEqualTo("could not serialize access due to read/write dependencies among transactions"); + assertThat(outcome.finalValue()).as("both accounts together").isEqualTo(200); + } + + @Test + @DisplayName("Spring: a transaction that Postgres cancels at COMMIT also arrives as CannotAcquireLockException") + void aFailedCommitIsAlsoCannotAcquireLockException() { + TransactionTemplate serializable = new TransactionTemplate(transactionManager); + serializable.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + String readBoth = "select sum(balance) from account where owner = 'alice'"; + + // We read both accounts and write account 1. Before we commit, a second transaction reads + // both accounts, writes account 2 and commits. Every statement of ours worked: only COMMIT fails. + Throwable thrown = catchThrowable(() -> serializable.executeWithoutResult(ours -> { + jdbc.queryForObject(readBoth, Long.class); + jdbc.update("update account set balance = balance - 800 where id = 1"); + inAnotherThread(() -> serializable.executeWithoutResult(theirs -> { + jdbc.queryForObject(readBoth, Long.class); + jdbc.update("update account set balance = balance - 800 where id = 2"); + })); + })); + + assertThat(thrown).as("what a failed COMMIT throws").isInstanceOf(CannotAcquireLockException.class); + assertThat(thrown).hasMessageContaining("commit"); + assertThat(combinedBalance()).as("both accounts together").isEqualTo(200); + } + + @Test + @DisplayName("Spring: an isolation level asked for inside a transaction that is already open is silently ignored") + void anInnerIsolationLevelIsIgnored() { + TransactionTemplate outer = new TransactionTemplate(transactionManager); + TransactionTemplate inner = new TransactionTemplate(transactionManager); + inner.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + + // The inner one joins the outer transaction (propagation REQUIRED, the default), which + // started at the default level. A transaction has one level, fixed before its first query. + String level = outer.execute(open -> inner.execute(joined -> isolationLevelOfThisTransaction())); + + assertThat(level).as("level inside the inner, 'serializable' transaction").isEqualTo("read committed"); + } + + @Test + @DisplayName("Withdrawal: 800 from current and 800 from savings at the same time: one goes through, the other is refused, 200 is left") + void onlyOneOfTheTwoWithdrawalsGoesThrough() { + AtomicReference other = new AtomicReference<>(); + checkpoint.onFirst(Checkpoint.FUNDS_CHECKED, + () -> other.set(inAnotherThread(() -> withdrawalService.withdraw(SAVINGS, 800)))); + + Throwable ours = catchThrowable(() -> withdrawalService.withdraw(CURRENT, 800)); + + assertThat(combinedBalance()).as("both accounts together (the rule: never below 0)").isEqualTo(200); + assertThat(other.get()).as("what the withdrawal from savings threw").isNull(); + assertThat(ours).as("what the withdrawal from current threw, after its retry read the new balances") + .isInstanceOf(InsufficientFundsException.class); + } + + @Test + @DisplayName("Withdrawal: every attempt runs in a SERIALIZABLE transaction") + void everyAttemptRunsAtSerializable() { + List levels = Collections.synchronizedList(new ArrayList<>()); + checkpoint.onReached(Checkpoint.FUNDS_CHECKED, arrival -> levels.add(isolationLevelOfThisTransaction())); + + withdrawalService.withdraw(CURRENT, 100); + + assertThat(levels).as("isolation level in the middle of withdraw()").containsExactly("serializable"); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/support/IntegrationTest.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/support/IntegrationTest.java new file mode 100644 index 0000000..e4bdb88 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/support/IntegrationTest.java @@ -0,0 +1,146 @@ +package com.amigoscode.isolation.support; + +import com.amigoscode.isolation.checkpoint.ScriptedCheckpoint; +import com.amigoscode.isolation.demo.Db; +import com.amigoscode.isolation.demo.Lab; +import com.amigoscode.isolation.statement.StatementService; +import com.amigoscode.isolation.withdrawal.WithdrawalService; +import com.amigoscode.isolation.withdrawal.Withdrawer; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.concurrent.atomic.AtomicReference; +import javax.sql.DataSource; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Primary; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * Base class for the *IT tests. They run against a real Postgres started by Testcontainers (Docker + * must be running), because isolation levels are something the database does: none of this shows + * up against mocks or an in-memory database. One container is shared by every test class. + * + *

Nothing here sleeps and hopes. A test decides the exact order of the steps: either it drives + * two database sessions one statement at a time ({@link #lab()}), or it makes a second session do + * its work at a {@link ScriptedCheckpoint} in the middle of the application's transaction. + */ +@SpringBootTest(properties = "spring.main.banner-mode=off") +@Import(IntegrationTest.TestBeans.class) +public abstract class IntegrationTest { + + public static final long CURRENT = 1; + public static final long SAVINGS = 2; + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + static void database(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", POSTGRES::getJdbcUrl); + registry.add("spring.datasource.username", POSTGRES::getUsername); + registry.add("spring.datasource.password", POSTGRES::getPassword); + } + + @TestConfiguration + static class TestBeans { + + @Bean + @Primary + ScriptedCheckpoint scriptedCheckpoint() { + return new ScriptedCheckpoint(); + } + } + + @Autowired + protected StatementService statementService; + + @Autowired + protected WithdrawalService withdrawalService; + + @Autowired + protected Withdrawer withdrawer; + + @Autowired + protected ScriptedCheckpoint checkpoint; + + @Autowired + protected JdbcTemplate jdbc; + + @Autowired + private DataSource dataSource; + + /** Every test starts with alice's two accounts: current (id 1) = 500 and savings (id 2) = 500. */ + @BeforeEach + void aliceHasTwoAccounts() throws SQLException { + checkpoint.reset(); + try (Connection connection = dataSource.getConnection()) { + Db.reset(connection); + } + } + + /** Plain SQL in two sessions, stepped in a fixed order. Prints nothing. */ + protected Lab lab() { + return new Lab(POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword(), null); + } + + /** + * Runs SQL in a different database session from the one the calling thread's transaction uses, + * and commits it at once. This is "somebody else" committing while the application is busy. + */ + protected void inAnotherSession(String sql) { + // dataSource.getConnection() hands out a fresh pooled connection. (JdbcTemplate would not do: + // inside a transaction it joins the transaction's own connection.) + try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { + statement.execute(sql); + } catch (SQLException e) { + throw new IllegalStateException(e); + } + } + + /** + * Runs {@code task} on a second thread and waits for it to finish, so it gets its own + * transaction and its own session. Returns what it threw, or null when it succeeded. + */ + protected Throwable inAnotherThread(Runnable task) { + AtomicReference thrown = new AtomicReference<>(); + Thread thread = new Thread(() -> { + try { + task.run(); + } catch (Throwable e) { + thrown.set(e); + } + }, "second-customer"); + thread.start(); + try { + thread.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + return thrown.get(); + } + + /** The isolation level of the transaction the calling thread is in, as Postgres reports it. */ + protected String isolationLevelOfThisTransaction() { + return jdbc.queryForObject("select current_setting('transaction_isolation')", String.class); + } + + protected long balance(long accountId) { + return jdbc.queryForObject("select balance from account where id = ?", Long.class, accountId); + } + + protected long combinedBalance() { + return jdbc.queryForObject("select sum(balance) from account where owner = 'alice'", Long.class); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/resources/logback-test.xml b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/resources/logback-test.xml new file mode 100644 index 0000000..82166a4 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/resources/logback-test.xml @@ -0,0 +1,11 @@ + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + + diff --git a/java/concepts/junior-mid/09-isolation-levels/start/.mvn/jvm.config b/java/concepts/junior-mid/09-isolation-levels/start/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/.mvn/jvm.config @@ -0,0 +1,2 @@ +--enable-native-access=ALL-UNNAMED +--sun-misc-unsafe-memory-access=allow diff --git a/java/concepts/junior-mid/09-isolation-levels/start/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/09-isolation-levels/start/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/java/concepts/junior-mid/09-isolation-levels/start/check b/java/concepts/junior-mid/09-isolation-levels/start/check new file mode 100755 index 0000000..8a13e3b --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/check @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use check.cmd (type: .\check). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.isolation.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/09-isolation-levels/start/check.cmd b/java/concepts/junior-mid/09-isolation-levels/start/check.cmd new file mode 100644 index 0000000..27c9db8 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/check.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./check +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.isolation.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/09-isolation-levels/start/compose.yaml b/java/concepts/junior-mid/09-isolation-levels/start/compose.yaml new file mode 100644 index 0000000..8ba5992 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/compose.yaml @@ -0,0 +1,16 @@ +name: isolation-levels +services: + postgres: + image: postgres:17-alpine + container_name: isolation-levels-postgres + environment: + POSTGRES_DB: bank + POSTGRES_USER: bank + POSTGRES_PASSWORD: bank + ports: + - "5448:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U bank -d bank"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/09-isolation-levels/start/demo b/java/concepts/junior-mid/09-isolation-levels/start/demo new file mode 100755 index 0000000..c68c08f --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/demo @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use demo.cmd (type: .\demo). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.isolation.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/09-isolation-levels/start/demo.cmd b/java/concepts/junior-mid/09-isolation-levels/start/demo.cmd new file mode 100644 index 0000000..8b56f31 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/demo.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./demo +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.isolation.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/09-isolation-levels/start/inspect b/java/concepts/junior-mid/09-isolation-levels/start/inspect new file mode 100755 index 0000000..5b01fcd --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/inspect @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use inspect.cmd (type: .\inspect). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.isolation.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/09-isolation-levels/start/inspect.cmd b/java/concepts/junior-mid/09-isolation-levels/start/inspect.cmd new file mode 100644 index 0000000..550a5bb --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/inspect.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./inspect +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.isolation.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/09-isolation-levels/start/mvnw b/java/concepts/junior-mid/09-isolation-levels/start/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/java/concepts/junior-mid/09-isolation-levels/start/mvnw.cmd b/java/concepts/junior-mid/09-isolation-levels/start/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/java/concepts/junior-mid/09-isolation-levels/start/pom.xml b/java/concepts/junior-mid/09-isolation-levels/start/pom.xml new file mode 100644 index 0000000..f773e9e --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + isolation-levels + 0.0.1-SNAPSHOT + isolation-levels + Transaction isolation levels: see the anomalies, then fix them with the right level and a retry + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + runtime + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.mockito + mockito-core + + + org.mockito + mockito-junit-jupiter + + + + + org.springframework.boot + spring-boot-starter-data-jpa-test + test + + + org.testcontainers + testcontainers-postgresql + test + + + org.junit.platform + junit-platform-launcher + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + false + + + + + + diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/IsolationApplication.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/IsolationApplication.java new file mode 100644 index 0000000..80b534d --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/IsolationApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.isolation; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class IsolationApplication { + + public static void main(String[] args) { + SpringApplication.run(IsolationApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/account/Account.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/account/Account.java new file mode 100644 index 0000000..83d91c8 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/account/Account.java @@ -0,0 +1,49 @@ +package com.amigoscode.isolation.account; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +@Entity +@Table(name = "account") +public class Account { + + @Id + private Long id; + + private String owner; + + private String name; + + private long balance; + + protected Account() { + } + + public Account(long id, String owner, String name, long balance) { + this.id = id; + this.owner = owner; + this.name = name; + this.balance = balance; + } + + public Long getId() { + return id; + } + + public String getOwner() { + return owner; + } + + public String getName() { + return name; + } + + public long getBalance() { + return balance; + } + + public void setBalance(long balance) { + this.balance = balance; + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/account/AccountNotFoundException.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/account/AccountNotFoundException.java new file mode 100644 index 0000000..73df1c2 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/account/AccountNotFoundException.java @@ -0,0 +1,8 @@ +package com.amigoscode.isolation.account; + +public class AccountNotFoundException extends RuntimeException { + + public AccountNotFoundException(long accountId) { + super("Account " + accountId + " does not exist"); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/account/AccountRepository.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/account/AccountRepository.java new file mode 100644 index 0000000..b614f2e --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/account/AccountRepository.java @@ -0,0 +1,16 @@ +package com.amigoscode.isolation.account; + +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface AccountRepository extends JpaRepository { + + List findByOwnerOrderById(String owner); + + long countByOwner(String owner); + + @Query("select coalesce(sum(a.balance), 0) from Account a where a.owner = :owner") + long totalBalance(@Param("owner") String owner); +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/checkpoint/Checkpoint.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/checkpoint/Checkpoint.java new file mode 100644 index 0000000..f3fa680 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/checkpoint/Checkpoint.java @@ -0,0 +1,18 @@ +package com.amigoscode.isolation.checkpoint; + +/** + * A named point in the middle of a transaction, between a READ and what the code does with it. + * In production nothing happens here. The demo and the tests use it to let a second session do + * its work at exactly this moment, so the dangerous interleaving happens every time instead of + * once a month. + */ +public interface Checkpoint { + + /** StatementService has read the lines and is about to read the total. */ + String LINES_READ = "statement: lines read"; + + /** Withdrawer has checked the funds and is about to write the new balance. */ + String FUNDS_CHECKED = "withdrawal: funds checked"; + + void reached(String name); +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/checkpoint/NoCheckpoint.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/checkpoint/NoCheckpoint.java new file mode 100644 index 0000000..68c9ab0 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/checkpoint/NoCheckpoint.java @@ -0,0 +1,12 @@ +package com.amigoscode.isolation.checkpoint; + +import org.springframework.stereotype.Component; + +/** What runs in production: nothing. */ +@Component +public class NoCheckpoint implements Checkpoint { + + @Override + public void reached(String name) { + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/checkpoint/ScriptedCheckpoint.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/checkpoint/ScriptedCheckpoint.java new file mode 100644 index 0000000..9ffa0e1 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/checkpoint/ScriptedCheckpoint.java @@ -0,0 +1,52 @@ +package com.amigoscode.isolation.checkpoint; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.IntConsumer; + +/** + * Used by the demo and the tests instead of {@link NoCheckpoint}: runs an action whenever a + * checkpoint is reached, on the thread that reached it, which means in the middle of that + * thread's transaction. + */ +public final class ScriptedCheckpoint implements Checkpoint { + + private final Map arrivals = new ConcurrentHashMap<>(); + private final Map actions = new ConcurrentHashMap<>(); + + /** Forget every action and every count. */ + public void reset() { + arrivals.clear(); + actions.clear(); + } + + /** Runs {@code action} every time {@code name} is reached. It receives the arrival number: 1, 2, 3... */ + public void onReached(String name, IntConsumer action) { + actions.put(name, action); + } + + /** Runs {@code action} the first time {@code name} is reached, and never again (so not on a retry). */ + public void onFirst(String name, Runnable action) { + onReached(name, arrival -> { + if (arrival == 1) { + action.run(); + } + }); + } + + /** How many times {@code name} has been reached. */ + public int arrivals(String name) { + AtomicInteger count = arrivals.get(name); + return count == null ? 0 : count.get(); + } + + @Override + public void reached(String name) { + int arrival = arrivals.computeIfAbsent(name, key -> new AtomicInteger()).incrementAndGet(); + IntConsumer action = actions.get(name); + if (action != null) { + action.accept(arrival); + } + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Anomaly.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Anomaly.java new file mode 100644 index 0000000..de1cf63 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Anomaly.java @@ -0,0 +1,24 @@ +package com.amigoscode.isolation.demo; + +import java.util.Arrays; +import java.util.Locale; +import java.util.stream.Collectors; + +/** The things that can go wrong when two transactions overlap. */ +public enum Anomaly { + DIRTY_READ, NON_REPEATABLE_READ, PHANTOM, LOST_UPDATE, WRITE_SKEW; + + /** As written on the command line: "write-skew". */ + public String flag() { + return name().toLowerCase(Locale.ROOT).replace('_', '-'); + } + + static Anomaly from(String value) { + return Arrays.stream(values()).filter(anomaly -> anomaly.flag().equals(value)).findFirst() + .orElseThrow(() -> new IllegalArgumentException("Unknown anomaly: " + value + ". Use one of: " + names())); + } + + static String names() { + return Arrays.stream(values()).map(Anomaly::flag).collect(Collectors.joining(" | ")); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/AppDemo.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/AppDemo.java new file mode 100644 index 0000000..0452b2f --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/AppDemo.java @@ -0,0 +1,220 @@ +package com.amigoscode.isolation.demo; + +import com.amigoscode.isolation.IsolationApplication; +import com.amigoscode.isolation.checkpoint.Checkpoint; +import com.amigoscode.isolation.checkpoint.ScriptedCheckpoint; +import com.amigoscode.isolation.statement.Statement; +import com.amigoscode.isolation.statement.StatementService; +import com.amigoscode.isolation.withdrawal.InsufficientFundsException; +import com.amigoscode.isolation.withdrawal.WithdrawalService; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * Runs the application's own code (StatementService, WithdrawalService) as session A, and makes a + * second session do its work at a checkpoint in the middle of A's transaction. What you see depends + * on the @Transactional settings in the code. + */ +final class AppDemo { + + private final ConfigurableApplicationContext context; + private final ScriptedCheckpoint checkpoint; + private final JdbcTemplate jdbc; + private final Timeline timeline = new Timeline(System.out); + private final int pauseSeconds; + + private AppDemo(ConfigurableApplicationContext context, ScriptedCheckpoint checkpoint, int pauseSeconds) { + this.context = context; + this.checkpoint = checkpoint; + this.jdbc = context.getBean(JdbcTemplate.class); + this.pauseSeconds = pauseSeconds; + } + + static void run(Anomaly anomaly, int pauseSeconds) throws SQLException { + ScriptedCheckpoint checkpoint = new ScriptedCheckpoint(); + SpringApplication app = new SpringApplication(IsolationApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + // The demo's checkpoint replaces the one that does nothing. + app.addInitializers(context -> ((GenericApplicationContext) context).registerBean( + "demoCheckpoint", ScriptedCheckpoint.class, () -> checkpoint, bean -> bean.setPrimary(true))); + try (ConfigurableApplicationContext context = app.run( + "--logging.level.root=WARN", + // A cancelled transaction is shown as one line in the timeline instead of a log entry. + "--logging.level.org.hibernate.orm.jdbc.error=OFF")) { + try (Connection connection = Db.connect()) { + Db.reset(connection); + } + AppDemo demo = new AppDemo(context, checkpoint, pauseSeconds); + System.out.println(); + switch (anomaly) { + case NON_REPEATABLE_READ, PHANTOM -> demo.statement(anomaly); + case LOST_UPDATE -> demo.withdrawals(anomaly, 1, 1, 100); + case WRITE_SKEW -> demo.withdrawals(anomaly, 1, 2, 800); + case DIRTY_READ -> throw new IllegalStateException("dirty-read is always plain SQL"); + } + System.out.println(); + } + } + + /** Session A is StatementService.statement. Session B commits a change between A's queries. */ + private void statement(Anomaly anomaly) throws SQLException { + System.out.println("Anomaly: " + anomaly.flag() + " | running the application: StatementService.statement"); + System.out.println("Session A is the application, building alice's statement: the lines first, then the count and the total."); + System.out.println(anomaly == Anomaly.PHANTOM + ? "Session B opens a new account for alice and commits in between." + : "Session B deposits 100 and commits in between."); + System.out.println("Before: alice has two accounts, current (id 1) = 500 and savings (id 2) = 500."); + System.out.println(); + + Statement statement; + try (Connection monitor = Db.connect(); Session b = new Session("B", Db.connect(), monitor, timeline)) { + checkpoint.onFirst(Checkpoint.LINES_READ, () -> { + timeline.result("A", "transaction isolation level: " + levelOfThisTransaction()); + timeline.result("A", "query 1 done: the lines are read"); + b.exec("begin"); + b.exec(anomaly == Anomaly.PHANTOM + ? "insert into account (id, owner, name, balance) values (3, 'alice', 'holiday', 250)" + : "update account set balance = balance + 100 where id = 1"); + b.exec("commit"); + pause(); + }); + timeline.step("A", "StatementService.statement(\"alice\")"); + statement = context.getBean(StatementService.class).statement("alice"); + timeline.result("A", "queries 2 and 3 done: the count and the total are read"); + } + + System.out.println(); + System.out.println("The statement the customer gets:"); + for (Statement.Line line : statement.lines()) { + System.out.printf(" %-12s %6d%n", line.account(), line.balance()); + } + System.out.println(" -------------------"); + System.out.printf(" %-12s %6d%n", statement.accountCount() + " accounts", statement.total()); + System.out.println(); + if (statement.addsUp()) { + System.out.println("RESULT: OK. " + statement.lines().size() + " lines, " + statement.accountCount() + + " accounts, and the lines add up to the total: " + statement.total() + + ". What session B committed is not in this statement. It will be in the next one."); + } else if (statement.lines().size() != statement.accountCount()) { + System.out.println("RESULT: PHANTOM READ. The statement lists " + statement.lines().size() + + " accounts and then says there are " + statement.accountCount() + ". The lines add up to " + + statement.sumOfLines() + ", the total says " + statement.total() + "."); + } else { + System.out.println("RESULT: NON-REPEATABLE READ. The lines add up to " + statement.sumOfLines() + + ", the total says " + statement.total() + ". The queries of one transaction saw two different moments."); + } + } + + /** Session A and session B are both WithdrawalService.withdraw. B runs while A is between its check and its write. */ + private void withdrawals(Anomaly anomaly, long accountA, long accountB, long amount) { + System.out.println("Anomaly: " + anomaly.flag() + " | running the application: WithdrawalService.withdraw"); + System.out.println(Demo.story(anomaly)); + System.out.println("Session B does all of its work while A is between checking the funds and writing the new balance."); + System.out.println("Before: alice has two accounts, current (id 1) = 500 and savings (id 2) = 500."); + System.out.println(); + + Thread sessionA = Thread.currentThread(); + Map attempts = new ConcurrentHashMap<>(); + Map thrown = new ConcurrentHashMap<>(); + Map paidOut = new ConcurrentHashMap<>(); + checkpoint.onReached(Checkpoint.FUNDS_CHECKED, arrival -> { + String session = Thread.currentThread() == sessionA ? "A" : "B"; + int attempt = attempts.merge(session, 1, Integer::sum); + timeline.result(session, "attempt " + attempt + (attempt > 1 ? " (a new transaction: the last one did not commit)" : "") + + ", transaction isolation level: " + levelOfThisTransaction()); + timeline.result(session, "funds checked: enough for " + amount); + if (session.equals("A") && attempt == 1) { + Thread sessionB = new Thread(() -> withdraw("B", accountB, amount, thrown, paidOut), "session-B"); + sessionB.start(); + try { + sessionB.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + pause(); + } + }); + withdraw("A", accountA, amount, thrown, paidOut); + + long current = jdbc.queryForObject("select balance from account where id = 1", Long.class); + long savings = jdbc.queryForObject("select balance from account where id = 2", Long.class); + System.out.println(); + System.out.println("Withdrawals paid out: " + paidOut.size() + " x " + amount); + System.out.println("Current (id 1): " + current); + System.out.println("Savings (id 2): " + savings); + System.out.println("Both together: " + (current + savings)); + System.out.println(); + + if (!thrown.isEmpty()) { + String session = thrown.keySet().iterator().next(); + System.out.println("RESULT: NOT HANDLED. The data is right, because Postgres cancelled session " + session + + "'s transaction. But the customer got a " + thrown.get(session).getClass().getSimpleName() + + ". Nothing was wrong with the request: it has to be run again."); + } else if (anomaly == Anomaly.LOST_UPDATE && current != 500 - paidOut.size() * amount) { + System.out.println("RESULT: LOST UPDATE. " + paidOut.size() + " withdrawals of " + amount + + " were paid out, but the balance only went from 500 to " + current + "."); + } else if (current + savings < 0) { + System.out.println("RESULT: WRITE SKEW. Both withdrawals of " + amount + " went through and the accounts hold " + + (current + savings) + " together. The rule is broken, and neither transaction changed a row the other one changed."); + } else { + System.out.println("RESULT: OK. " + paidOut.size() + " x " + amount + " paid out, both accounts together went from 1000 to " + + (current + savings) + "." + (attempts.getOrDefault("A", 1) > 1 + ? " Session A was cancelled once and ran again in a new transaction." + : !paidOut.containsKey("A") + ? " Session A passed the check, was cancelled, ran again in a new transaction and was refused." + : "")); + } + } + + private void withdraw(String session, long accountId, long amount, Map thrown, + Map paidOut) { + timeline.step(session, "WithdrawalService.withdraw(" + accountId + ", " + amount + ")"); + try { + long newBalance = context.getBean(WithdrawalService.class).withdraw(accountId, amount); + paidOut.put(session, true); + timeline.result(session, "returns " + newBalance + ", the new balance of account " + accountId); + } catch (InsufficientFundsException e) { + timeline.result(session, "refused, InsufficientFundsException: " + e.getMessage()); + } catch (RuntimeException e) { + thrown.put(session, e); + timeline.result(session, "THROWS " + e.getClass().getName()); + Throwable root = e; + while (root.getCause() != null) { + root = root.getCause(); + } + String message = String.valueOf(root.getMessage()).lines().findFirst().orElse(""); + timeline.result(session, "caused by " + root.getClass().getSimpleName() + + (root instanceof SQLException sql ? ", SQLSTATE " + sql.getSQLState() : "") + ": " + message); + } + } + + /** + * Asked on the calling thread, so it runs inside that thread's transaction, on its connection. + * The session also puts the level into its application_name, where ./inspect can read it: + * Postgres has no column that shows another session's isolation level. + */ + private String levelOfThisTransaction() { + String level = jdbc.queryForObject("show transaction_isolation", String.class); + jdbc.execute("set local application_name = 'bank-app (" + level + ")'"); + return level; + } + + private void pause() { + if (pauseSeconds > 0) { + timeline.note("Paused for " + pauseSeconds + " seconds. Run ./inspect in another terminal now."); + try { + Thread.sleep(pauseSeconds * 1000L); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Db.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Db.java new file mode 100644 index 0000000..7779e2a --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Db.java @@ -0,0 +1,63 @@ +package com.amigoscode.isolation.demo; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +/** Connection settings shared by the demo and inspect tools. Same defaults as application.properties. */ +public final class Db { + + static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5448/bank"); + static final String USER = env("DB_USER", "bank"); + static final String PASSWORD = env("DB_PASSWORD", "bank"); + + private Db() { + } + + static Connection connect() throws SQLException { + return DriverManager.getConnection(URL, USER, PASSWORD); + } + + /** Returns false, after printing what to do, when Postgres is not reachable. */ + static boolean isUp() { + try (Connection ignored = connect()) { + return true; + } catch (SQLException e) { + System.out.println(); + System.out.println("Cannot reach Postgres at " + URL); + System.out.println("Start it first, from this folder:"); + System.out.println(); + System.out.println(" docker compose up -d"); + System.out.println(); + System.out.println("(" + e.getMessage().lines().findFirst().orElse("") + ")"); + return false; + } + } + + /** Creates the table if needed and puts the data back: alice, current 500 and savings 500. */ + public static void reset(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute(schema()); + statement.execute("delete from account"); + statement.execute("insert into account (id, owner, name, balance) " + + "values (1, 'alice', 'current', 500), (2, 'alice', 'savings', 500)"); + } + } + + private static String schema() { + try (InputStream in = Db.class.getResourceAsStream("/schema.sql")) { + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new IllegalStateException("Cannot read schema.sql", e); + } + } + + private static String env(String name, String fallback) { + String value = System.getenv(name); + return value == null || value.isBlank() ? fallback : value; + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Demo.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Demo.java new file mode 100644 index 0000000..76b74db --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Demo.java @@ -0,0 +1,184 @@ +package com.amigoscode.isolation.demo; + +import com.amigoscode.isolation.demo.Outcome.Verdict; +import java.util.ArrayList; +import java.util.List; + +/** + * Two sessions, one fixed order of steps, printed as a timeline that ends in a RESULT line. + * Without --level it runs the application's own code. With --level it runs the same anomaly as + * plain SQL at the level you choose. Run it with ./demo (or .\demo on Windows). ./demo --help + * lists the flags. + */ +public final class Demo { + + static final int PAUSE_SECONDS = 15; + + private record Options(Anomaly anomaly, Level level, boolean matrix, boolean forUpdate, boolean pause) { + } + + public static void main(String[] args) throws Exception { + Options options; + try { + options = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println(); + printHelp(); + return; + } + if (options == null) { + printHelp(); + return; + } + if (!Db.isUp()) { + return; + } + if (options.matrix()) { + matrix(); + } else if (options.level() != null) { + sql(options); + } else { + AppDemo.run(options.anomaly(), options.pause() ? PAUSE_SECONDS : 0); + } + } + + /** One anomaly as plain SQL at one level. */ + private static void sql(Options options) { + System.out.println(); + System.out.println("Anomaly: " + options.anomaly().flag() + " | level: " + options.level().sql() + + (options.forUpdate() ? " + SELECT ... FOR UPDATE" : "") + " | plain SQL in two sessions"); + System.out.println(story(options.anomaly())); + System.out.println("Before: alice has two accounts, current (id 1) = 500 and savings (id 2) = 500."); + System.out.println(); + Lab lab = new Lab(Db.URL, Db.USER, Db.PASSWORD, System.out); + Outcome outcome = lab.run(options.anomaly(), options.level(), + new Lab.Options(options.forUpdate(), options.pause() ? PAUSE_SECONDS : 0)); + System.out.println(); + System.out.println("RESULT: " + outcome.result()); + System.out.println(); + } + + static String story(Anomaly anomaly) { + return switch (anomaly) { + case DIRTY_READ -> "Session B changes a balance and has NOT committed. Session A reads that balance."; + case NON_REPEATABLE_READ -> "Session A reads one balance twice. Session B deposits 100 and commits in between."; + case PHANTOM -> "Session A counts alice's accounts twice. Session B opens a new account and commits in between."; + case LOST_UPDATE -> "Both sessions withdraw 100 from account 1: read the balance, subtract, write it back."; + case WRITE_SKEW -> "A withdraws 800 from account 1, B withdraws 800 from account 2. " + + "The rule: both accounts together must stay at 0 or above."; + }; + } + + /** Every anomaly at every level. */ + private static void matrix() { + Lab lab = new Lab(Db.URL, Db.USER, Db.PASSWORD, null); + System.out.println(); + System.out.println("Every anomaly at every isolation level: plain SQL in two sessions, " + + Anomaly.values().length * Level.values().length + " runs."); + System.out.println(); + StringBuilder header = new StringBuilder(String.format(" %-21s", "")); + for (Level level : Level.values()) { + header.append(String.format("%-18s", level.flag())); + } + System.out.println(header.toString().stripTrailing()); + List> columns = new ArrayList<>(); + for (Level ignored : Level.values()) { + columns.add(new ArrayList<>()); + } + for (Anomaly anomaly : Anomaly.values()) { + StringBuilder row = new StringBuilder(String.format(" %-21s", anomaly.flag())); + for (Level level : Level.values()) { + Outcome outcome = lab.run(anomaly, level); + String cell = outcome.verdict() == Verdict.HAPPENED ? "HAPPENS" + : outcome.verdict() == Verdict.SERIALIZATION_FAILURE ? outcome.sqlState() : "no"; + columns.get(level.ordinal()).add(cell); + row.append(String.format("%-18s", cell)); + } + System.out.println(row.toString().stripTrailing()); + } + System.out.println(); + System.out.println(" HAPPENS = the anomaly happened and nobody was told"); + System.out.println(" no = it did not happen"); + System.out.println(" 40001 = it did not happen, because Postgres cancelled one transaction with"); + System.out.println(" SQLSTATE 40001 (serialization failure). The application has to retry it"); + System.out.println(); + boolean sameAsReadCommitted = columns.get(Level.READ_UNCOMMITTED.ordinal()) + .equals(columns.get(Level.READ_COMMITTED.ordinal())); + List clean = new ArrayList<>(); + for (Level level : Level.values()) { + if (!columns.get(level.ordinal()).contains("HAPPENS")) { + clean.add(level.flag()); + } + } + System.out.println("RESULT: read-uncommitted and read-committed " + + (sameAsReadCommitted ? "behave the same" : "DIFFER") + ". Levels with no anomaly left: " + + (clean.isEmpty() ? "none" : String.join(", ", clean)) + "."); + System.out.println(); + } + + private static Options parse(String[] args) { + Anomaly anomaly = Anomaly.NON_REPEATABLE_READ; + Level level = null; + boolean matrix = false; + boolean forUpdate = false; + boolean pause = false; + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "--help", "-h" -> { + return null; + } + case "--anomaly" -> anomaly = Anomaly.from(value(args, ++i, arg)); + case "--level" -> level = Level.from(value(args, ++i, arg)); + case "--matrix" -> matrix = true; + case "--for-update" -> forUpdate = true; + case "--pause" -> pause = true; + default -> throw new IllegalArgumentException("Unknown option: " + arg); + } + } + if (forUpdate && anomaly != Anomaly.WRITE_SKEW) { + throw new IllegalArgumentException("--for-update only works with --anomaly write-skew"); + } + if (level == null && forUpdate) { + level = Level.READ_COMMITTED; + } + if (level == null && anomaly == Anomaly.DIRTY_READ) { + // The application has no code that could show a dirty read, so this one is always plain SQL. + level = Level.READ_UNCOMMITTED; + } + return new Options(anomaly, level, matrix, forUpdate, pause); + } + + private static String value(String[] args, int index, String option) { + if (index >= args.length) { + throw new IllegalArgumentException(option + " needs a value"); + } + return args[index]; + } + + private static void printHelp() { + System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])"); + System.out.println(); + System.out.println(" --anomaly " + Anomaly.names()); + System.out.println(" (default: non-repeatable-read)"); + System.out.println(" --level " + Level.names()); + System.out.println(" Runs the anomaly as plain SQL at this level."); + System.out.println(" Without --level the demo runs the APPLICATION's code, so it shows"); + System.out.println(" what your @Transactional settings do. (dirty-read is always plain SQL.)"); + System.out.println(" --for-update write-skew only, plain SQL: the read locks the rows (SELECT ... FOR UPDATE)"); + System.out.println(" --matrix every anomaly at every level, as one table"); + System.out.println(" --pause hold the transactions open for " + PAUSE_SECONDS + + " seconds in the middle, so you can run ./inspect"); + System.out.println(); + System.out.println("Examples:"); + System.out.println(" ./demo"); + System.out.println(" ./demo --anomaly phantom"); + System.out.println(" ./demo --anomaly write-skew --level serializable"); + System.out.println(" ./demo --anomaly dirty-read --level read-uncommitted"); + System.out.println(" ./demo --matrix"); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Inspect.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Inspect.java new file mode 100644 index 0000000..da14cb3 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Inspect.java @@ -0,0 +1,169 @@ +package com.amigoscode.isolation.demo; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +/** + * Shows what the database sees right now: every account row with the transaction that wrote it, + * every session that is inside a transaction, whether it holds a snapshot, and the predicate locks + * of SERIALIZABLE sessions. Run it with ./inspect (or .\inspect on Windows) in a second terminal + * while ./demo --pause is running. + */ +public final class Inspect { + + private static final String ACCOUNTS = """ + select id, name, balance, xmin, xmax + from account + order by id + """; + + /** + * Postgres has no column that shows another session's isolation level. The demo's sessions put + * their own level into their application_name, which is the "session" column here. + * snapshot_xmin is filled in while a session holds a snapshot. + */ + private static final String SESSIONS = """ + select a.pid, + a.application_name as session, + a.state, + coalesce(a.backend_xmin::text, '') as snapshot_xmin, + coalesce(a.backend_xid::text, '') as own_xid, + case when cardinality(pg_blocking_pids(a.pid)) = 0 then '' + else array_to_string(pg_blocking_pids(a.pid), ', ') end as waits_for_pid, + coalesce(round(extract(epoch from (now() - a.xact_start)) * 1000)::text, '') as in_transaction_ms, + left(regexp_replace(a.query, '\\s+', ' ', 'g'), 44) as last_statement + from pg_stat_activity a + where a.datname = current_database() + and a.pid <> pg_backend_pid() + and a.backend_type = 'client backend' + and a.state <> 'idle' + order by a.xact_start nulls last, a.pid + """; + + private static final String PREDICATE_LOCKS = """ + select l.pid, + a.application_name as session, + coalesce(c.relname::text, '') as relation, + l.locktype as covers, + coalesce(l.page::text, '') as page, + coalesce(l.tuple::text, '') as row_on_page + from pg_locks l + join pg_stat_activity a on a.pid = l.pid + left join pg_class c on c.oid = l.relation + where l.mode = 'SIReadLock' + order by l.pid, c.relname, l.page nulls first, l.tuple nulls first + """; + + public static void main(String[] args) throws Exception { + boolean watch = false; + for (String arg : args) { + if (arg.equals("--watch")) { + watch = true; + } else { + System.out.println("Usage: ./inspect [--watch] (Windows: .\\inspect [--watch])"); + System.out.println(); + System.out.println(" --watch refresh every second for one minute (Ctrl+C to stop)"); + return; + } + } + if (!Db.isUp()) { + return; + } + try (Connection connection = Db.connect()) { + int rounds = watch ? 60 : 1; + for (int round = 0; round < rounds; round++) { + snapshot(connection); + if (round < rounds - 1) { + Thread.sleep(1000); + } + } + } + } + + private static void snapshot(Connection connection) throws SQLException { + System.out.println(); + System.out.println("==== " + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")) + " ===="); + System.out.println(); + System.out.println("ACCOUNTS (what a NEW transaction would read. xmin = the transaction that wrote this version of"); + System.out.println(" the row, xmax = a transaction that has locked or replaced it, 0 = none)"); + if (!tableExists(connection)) { + System.out.println(" The account table does not exist yet. Run ./demo once: it creates the table."); + return; + } + printTable(connection, ACCOUNTS); + System.out.println(); + System.out.println("SESSIONS INSIDE A TRANSACTION (snapshot_xmin is filled in while the session holds a snapshot)"); + int sessions = printTable(connection, SESSIONS); + if (sessions == 0) { + System.out.println(" none. Nothing is running. Start ./demo --pause in another terminal."); + } + System.out.println(); + System.out.println("PREDICATE LOCKS (SIReadLock: what SERIALIZABLE sessions have read. They block nobody)"); + int locks = printTable(connection, PREDICATE_LOCKS); + if (locks == 0) { + System.out.println(" none. No SERIALIZABLE transaction is open."); + } + } + + private static boolean tableExists(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement(); + ResultSet row = statement.executeQuery("select to_regclass('account') is not null")) { + row.next(); + return row.getBoolean(1); + } + } + + /** Prints a query result as a plain text table and returns the number of rows. */ + private static int printTable(Connection connection, String sql) throws SQLException { + List rows = new ArrayList<>(); + try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) { + int columns = result.getMetaData().getColumnCount(); + String[] header = new String[columns]; + for (int c = 0; c < columns; c++) { + header[c] = result.getMetaData().getColumnLabel(c + 1); + } + rows.add(header); + while (result.next()) { + String[] row = new String[columns]; + for (int c = 0; c < columns; c++) { + String value = result.getString(c + 1); + row[c] = value == null ? "" : value; + } + rows.add(row); + } + } + if (rows.size() == 1) { + return 0; + } + int[] widths = new int[rows.get(0).length]; + for (String[] row : rows) { + for (int c = 0; c < row.length; c++) { + widths[c] = Math.max(widths[c], row[c].length()); + } + } + for (int r = 0; r < rows.size(); r++) { + StringBuilder line = new StringBuilder(" "); + for (int c = 0; c < widths.length; c++) { + line.append(String.format("%-" + widths[c] + "s", rows.get(r)[c])).append(" "); + } + System.out.println(line.toString().stripTrailing()); + if (r == 0) { + StringBuilder rule = new StringBuilder(" "); + for (int width : widths) { + rule.append("-".repeat(width)).append(" "); + } + System.out.println(rule.toString().stripTrailing()); + } + } + return rows.size() - 1; + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Lab.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Lab.java new file mode 100644 index 0000000..609c57f --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Lab.java @@ -0,0 +1,323 @@ +package com.amigoscode.isolation.demo; + +import com.amigoscode.isolation.demo.Outcome.Verdict; +import com.amigoscode.isolation.demo.Session.Pending; +import com.amigoscode.isolation.demo.Session.Result; +import java.io.PrintStream; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; +import java.util.Properties; + +/** + * Plain SQL in two sessions, one statement at a time, in a fixed order. No Spring, no Hibernate: + * this is what Postgres itself does at each isolation level. The demo prints it, and the tests + * assert on the {@link Outcome}, so everything the demo shows is also checked. + */ +public final class Lab { + + /** + * @param forUpdate write-skew only: the read locks the rows it reads (SELECT ... FOR UPDATE) + * @param pauseSeconds hold both transactions open for this long in the middle, for ./inspect + */ + public record Options(boolean forUpdate, int pauseSeconds) { + + public static final Options NONE = new Options(false, 0); + } + + private static final int WITHDRAWAL = 800; + + private final String url; + private final String user; + private final String password; + private final Timeline timeline; + + /** @param out where to print the timeline, or null to print nothing */ + public Lab(String url, String user, String password, PrintStream out) { + this.url = url; + this.user = user; + this.password = password; + this.timeline = new Timeline(out); + } + + public Outcome run(Anomaly anomaly, Level level) { + return run(anomaly, level, Options.NONE); + } + + public Outcome run(Anomaly anomaly, Level level, Options options) { + try (Connection monitor = DriverManager.getConnection(url, user, password)) { + Db.reset(monitor); + try (Session a = new Session("A", session(), monitor, timeline); + Session b = new Session("B", session(), monitor, timeline)) { + Run run = new Run(level, options, a, b, monitor); + return switch (anomaly) { + case DIRTY_READ -> dirtyRead(run); + case NON_REPEATABLE_READ -> nonRepeatableRead(run); + case PHANTOM -> phantom(run); + case LOST_UPDATE -> lostUpdate(run); + case WRITE_SKEW -> writeSkew(run); + }; + } + } catch (SQLException e) { + throw new IllegalStateException(e); + } + } + + /** + * A connection that sends every statement as plain text, the way psql does, instead of as a + * prepared statement. Nothing is left open on the server between two statements, so ./inspect + * shows exactly which sessions are holding a snapshot. + */ + private Connection session() throws SQLException { + Properties properties = new Properties(); + properties.setProperty("user", user); + properties.setProperty("password", password); + properties.setProperty("preferQueryMode", "simple"); + return DriverManager.getConnection(url, properties); + } + + /** B changes a balance and does not commit. Can A see the change? */ + private Outcome dirtyRead(Run run) { + Session a = run.a; + Session b = run.b; + a.exec(run.begin()); + a.exec("show transaction_isolation"); + b.exec("begin"); + b.exec("update account set balance = 0 where id = 1"); + run.pause(); + Result read = a.exec("select balance from account where id = 1"); + b.exec("rollback"); + a.end(); + + if (read.value().equals("0")) { + return run.outcome(Anomaly.DIRTY_READ, Verdict.HAPPENED, List.of(read.value()), run.balance(1), + "DIRTY READ. Session A read 0, a value that was never committed."); + } + return run.outcome(Anomaly.DIRTY_READ, Verdict.PREVENTED, List.of(read.value()), run.balance(1), + "NO DIRTY READ. Session A read " + read.value() + " while B's uncommitted 0 was in the table." + + (run.level == Level.READ_UNCOMMITTED + ? " Postgres accepts READ UNCOMMITTED and runs it as READ COMMITTED." : "")); + } + + /** A reads one row twice. B changes it and commits in between. */ + private Outcome nonRepeatableRead(Run run) { + Session a = run.a; + Session b = run.b; + a.exec(run.begin()); + Result first = a.exec("select balance from account where id = 1"); + b.exec("begin"); + b.exec("update account set balance = balance + 100 where id = 1"); + b.exec("commit"); + run.pause(); + Result second = a.exec("select balance from account where id = 1"); + a.end(); + + List seen = List.of(first.value(), second.value()); + if (!first.value().equals(second.value())) { + return run.outcome(Anomaly.NON_REPEATABLE_READ, Verdict.HAPPENED, seen, run.balance(1), + "NON-REPEATABLE READ. Session A read the same row twice in one transaction and got " + + first.value() + ", then " + second.value() + "."); + } + return run.outcome(Anomaly.NON_REPEATABLE_READ, Verdict.PREVENTED, seen, run.balance(1), + "OK. Session A read " + first.value() + " both times. The committed value is " + run.balance(1) + + ", and A will see it in its next transaction."); + } + + /** A runs the same query twice. B inserts a row that matches it and commits in between. */ + private Outcome phantom(Run run) { + Session a = run.a; + Session b = run.b; + String count = "select count(*) from account where owner = 'alice'"; + a.exec(run.begin()); + Result first = a.exec(count); + b.exec("begin"); + b.exec("insert into account (id, owner, name, balance) values (3, 'alice', 'holiday', 250)"); + b.exec("commit"); + run.pause(); + Result second = a.exec(count); + a.end(); + + List seen = List.of(first.value(), second.value()); + long rows = run.number(count); + if (!first.value().equals(second.value())) { + return run.outcome(Anomaly.PHANTOM, Verdict.HAPPENED, seen, rows, + "PHANTOM READ. The same query returned " + first.value() + " rows, then " + second.value() + + ": a row appeared in the middle of Session A's transaction."); + } + return run.outcome(Anomaly.PHANTOM, Verdict.PREVENTED, seen, rows, + "OK. Session A counted " + first.value() + " rows both times. The table has " + rows + + ", and A will see the new one in its next transaction."); + } + + /** A and B each withdraw 100 from the same account: read the balance, subtract in the application, write. */ + private Outcome lostUpdate(Run run) { + Session a = run.a; + Session b = run.b; + String read = "select balance from account where id = 1"; + a.exec(run.begin()); + long balanceA = a.exec(read).number(); + b.exec(run.begin()); + long balanceB = b.exec(read).number(); + b.comment(balanceB + " - 100 = " + (balanceB - 100) + ", worked out in the application"); + b.exec("update account set balance = " + (balanceB - 100) + " where id = 1"); + b.exec("commit"); + run.pause(); + a.comment(balanceA + " - 100 = " + (balanceA - 100) + ", worked out in the application"); + Result write = a.exec("update account set balance = " + (balanceA - 100) + " where id = 1"); + a.end(); + + List seen = List.of(String.valueOf(balanceA), String.valueOf(balanceB)); + long balance = run.balance(1); + if (write.failed()) { + return run.failure(Anomaly.LOST_UPDATE, "A", write, seen, balance, + "Nothing was lost: the balance is " + balance + " after one withdrawal. " + + "A has to run again in a new transaction."); + } + return run.outcome(Anomaly.LOST_UPDATE, Verdict.HAPPENED, seen, balance, + "LOST UPDATE. Two withdrawals of 100 were paid out, but the balance only went from 500 to " + + balance + "."); + } + + /** + * A withdraws 800 from account 1, B withdraws 800 from account 2. Each checks that the two + * accounts together hold at least 800. They write different rows. + */ + private Outcome writeSkew(Run run) { + Session a = run.a; + Session b = run.b; + String read = run.options.forUpdate() + ? "select balance from account where owner = 'alice' order by id for update" + : "select balance from account where owner = 'alice' order by id"; + + a.exec(run.begin()); + Result readA = a.exec(read); + boolean allowedA = run.check(a, readA); + b.exec(run.begin()); + Pending readB = b.send(read); + run.waited = readB.waited(); + boolean allowedB = !readB.waited() && run.check(b, readB.result()); + + Result failure = null; + String failed = null; + if (allowedA) { + Result write = a.exec("update account set balance = balance - " + WITHDRAWAL + " where id = 1"); + if (write.failed()) { + failure = write; + failed = "A"; + } + } + if (allowedB) { + Result write = b.exec("update account set balance = balance - " + WITHDRAWAL + " where id = 2"); + if (write.failed()) { + failure = write; + failed = "B"; + } + } + run.pause(); + Result commitA = a.end(); + if (commitA.failed()) { + failure = commitA; + failed = "A"; + } + if (readB.waited()) { + allowedB = run.check(b, readB.result()); + if (allowedB) { + b.exec("update account set balance = balance - " + WITHDRAWAL + " where id = 2"); + } + } + Result commitB = allowedB || b.failed() ? b.end() : b.exec("rollback"); + if (commitB.failed()) { + failure = commitB; + failed = "B"; + } + + List seen = List.of(String.valueOf(readA.sum()), String.valueOf(readB.result().sum())); + long combined = run.number("select sum(balance) from account where owner = 'alice'"); + if (failure != null) { + return run.failure(Anomaly.WRITE_SKEW, failed, failure, seen, combined, + "The rule holds: the accounts hold " + combined + " together after one withdrawal. " + + failed + " has to run again in a new transaction, and will then see " + combined + "."); + } + if (combined < 0) { + return run.outcome(Anomaly.WRITE_SKEW, Verdict.HAPPENED, seen, combined, + "WRITE SKEW. Both sessions saw 1000, both withdrew " + WITHDRAWAL + ", both committed. " + + "The accounts now hold " + combined + " together. Neither session changed a row the other one changed."); + } + return run.outcome(Anomaly.WRITE_SKEW, Verdict.PREVENTED, seen, combined, + "OK. Session B had to wait for A's row locks, then read " + readB.result().sum() + + " and refused its withdrawal. The accounts hold " + combined + " together."); + } + + /** Everything one run needs. */ + private final class Run { + + private final Level level; + private final Options options; + private final Session a; + private final Session b; + private final Connection monitor; + private boolean waited; + + private Run(Level level, Options options, Session a, Session b, Connection monitor) { + this.level = level; + this.options = options; + this.a = a; + this.b = b; + this.monitor = monitor; + } + + String begin() { + return "begin isolation level " + level.sql(); + } + + /** The application's rule, applied to what a session read: do the accounts together cover the withdrawal? */ + boolean check(Session session, Result read) { + boolean allowed = read.sum() >= WITHDRAWAL; + session.comment(read.addition() + " = " + read.sum() + (allowed + ? ", enough for " + WITHDRAWAL + ": go ahead" + : ", not enough for " + WITHDRAWAL + ": refuse")); + return allowed; + } + + void pause() { + if (options.pauseSeconds() > 0) { + timeline.note("Paused for " + options.pauseSeconds() + + " seconds. Run ./inspect in another terminal now."); + try { + Thread.sleep(options.pauseSeconds() * 1000L); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + + long balance(long accountId) { + return number("select balance from account where id = " + accountId); + } + + long number(String sql) { + try (Statement statement = monitor.createStatement(); ResultSet row = statement.executeQuery(sql)) { + row.next(); + return row.getLong(1); + } catch (SQLException e) { + throw new IllegalStateException(e); + } + } + + Outcome outcome(Anomaly anomaly, Verdict verdict, List seen, long finalValue, String result) { + return new Outcome(anomaly, level, verdict, seen, null, null, null, waited, finalValue, result); + } + + Outcome failure(Anomaly anomaly, String session, Result failure, List seen, long finalValue, + String whatNow) { + String message = failure.error().lines().findFirst().orElse("").replaceFirst("^ERROR: ", ""); + Verdict verdict = "40001".equals(failure.sqlState()) ? Verdict.SERIALIZATION_FAILURE : Verdict.PREVENTED; + return new Outcome(anomaly, level, verdict, seen, session, failure.sqlState(), message, waited, finalValue, + "SERIALIZATION FAILURE (SQLSTATE " + failure.sqlState() + "). Postgres cancelled session " + + session + ": \"" + message + "\". " + whatNow); + } + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Level.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Level.java new file mode 100644 index 0000000..b9a5962 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Level.java @@ -0,0 +1,29 @@ +package com.amigoscode.isolation.demo; + +import java.util.Arrays; +import java.util.Locale; +import java.util.stream.Collectors; + +/** The four isolation levels of the SQL standard, weakest first. */ +public enum Level { + READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE; + + /** As written in SQL: "repeatable read". */ + public String sql() { + return name().toLowerCase(Locale.ROOT).replace('_', ' '); + } + + /** As written on the command line: "repeatable-read". */ + public String flag() { + return name().toLowerCase(Locale.ROOT).replace('_', '-'); + } + + static Level from(String value) { + return Arrays.stream(values()).filter(level -> level.flag().equals(value)).findFirst() + .orElseThrow(() -> new IllegalArgumentException("Unknown level: " + value + ". Use one of: " + names())); + } + + static String names() { + return Arrays.stream(values()).map(Level::flag).collect(Collectors.joining(" | ")); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Outcome.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Outcome.java new file mode 100644 index 0000000..eca7d12 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Outcome.java @@ -0,0 +1,27 @@ +package com.amigoscode.isolation.demo; + +import java.util.List; + +/** + * What one run of one anomaly at one isolation level did. + * + * @param seen the values the sessions read, in the order they read them + * @param failedSession "A" or "B" when the database cancelled one of them, otherwise null + * @param sqlState the SQLSTATE of that failure (40001 is a serialization failure), otherwise null + * @param error the database's error message, otherwise null + * @param waited true when a session had to wait for a lock held by the other one + * @param finalValue what is committed at the end: a balance, a row count or a combined balance + * @param result the RESULT line + */ +public record Outcome(Anomaly anomaly, Level level, Verdict verdict, List seen, String failedSession, + String sqlState, String error, boolean waited, long finalValue, String result) { + + public enum Verdict { + /** The anomaly happened and nobody was told. */ + HAPPENED, + /** It did not happen and both sessions finished normally. */ + PREVENTED, + /** It did not happen because the database cancelled one transaction with SQLSTATE 40001. */ + SERIALIZATION_FAILURE + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Session.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Session.java new file mode 100644 index 0000000..d477553 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Session.java @@ -0,0 +1,243 @@ +package com.amigoscode.isolation.demo; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.stream.Collectors; + +/** + * One database session (one connection) that is driven one statement at a time. Each statement is + * sent as plain SQL, including "begin" and "commit", so the timeline shows exactly what Postgres + * received. + */ +final class Session implements AutoCloseable { + + /** What one statement returned: rows, a row count, or an error. */ + record Result(List> rows, int rowCount, String sqlState, String error) { + + boolean failed() { + return sqlState != null; + } + + /** The first column of the first row. */ + String value() { + return rows.get(0).get(0); + } + + long number() { + return Long.parseLong(value()); + } + + /** The first column of every row, added up. */ + long sum() { + return rows.stream().mapToLong(row -> Long.parseLong(row.get(0))).sum(); + } + + /** The first column of every row: "500 + 500". */ + String addition() { + return rows.stream().map(row -> row.get(0)).collect(Collectors.joining(" + ")); + } + } + + /** A statement that has been sent. It may still be waiting for a lock. */ + final class Pending { + + private final String sql; + private final Future future; + private final boolean waited; + private Result result; + + private Pending(String sql, Future future, boolean waited) { + this.sql = sql; + this.future = future; + this.waited = waited; + } + + /** True when the statement did not return at once because another session holds a lock it needs. */ + boolean waited() { + return waited; + } + + /** Waits for the statement to finish, prints what came back, and returns it. */ + Result result() { + if (result == null) { + try { + result = future.get(); + } catch (InterruptedException | ExecutionException e) { + throw new IllegalStateException(e); + } + report(sql, result, waited); + } + return result; + } + } + + private final String name; + private final Connection connection; + private final Connection monitor; + private final Timeline timeline; + private final int pid; + private final ExecutorService thread; + private boolean failed; + + Session(String name, Connection connection, Connection monitor, Timeline timeline) throws SQLException { + this.name = name; + this.connection = connection; + this.monitor = monitor; + this.timeline = timeline; + this.thread = Executors.newSingleThreadExecutor(task -> { + Thread thread = new Thread(task, "session-" + name); + thread.setDaemon(true); + return thread; + }); + try (Statement statement = connection.createStatement()) { + // The name ./inspect shows for this session. + statement.execute("set application_name = 'demo " + name + "'"); + try (ResultSet row = statement.executeQuery("select pg_backend_pid()")) { + row.next(); + this.pid = row.getInt(1); + } + } + } + + /** Sends one statement and waits for it to finish. */ + Result exec(String sql) { + return send(sql).result(); + } + + /** + * Sends one statement and returns as soon as it has finished or Postgres reports that it is + * waiting for a lock. Nothing here guesses with a timer: it asks pg_blocking_pids(). + */ + Pending send(String sql) { + timeline.step(name, sql); + Future future = thread.submit(() -> run(sql)); + boolean waiting = false; + try { + while (!future.isDone() && !(waiting = isWaitingForALock())) { + Thread.sleep(20); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + Pending pending = new Pending(sql, future, waiting); + if (waiting) { + timeline.result(name, "WAITING. Another session holds a lock this statement needs"); + } else { + pending.result(); + } + return pending; + } + + /** Ends the transaction: commit, or rollback when a statement in it has already failed. */ + Result end() { + if (failed) { + Result result = exec("rollback"); + timeline.comment(name, "this transaction was cancelled, so there is nothing to commit"); + return result; + } + return exec("commit"); + } + + /** Prints what the application does with a value it read, outside the database. */ + void comment(String text) { + timeline.comment(name, text); + } + + /** True when the database has cancelled this session's transaction. */ + boolean failed() { + return failed; + } + + private Result run(String sql) { + try (Statement statement = connection.createStatement()) { + List> rows = new ArrayList<>(); + if (statement.execute(sql)) { + try (ResultSet result = statement.getResultSet()) { + int columns = result.getMetaData().getColumnCount(); + while (result.next()) { + List row = new ArrayList<>(); + for (int c = 1; c <= columns; c++) { + row.add(String.valueOf(result.getObject(c))); + } + rows.add(row); + } + } + return new Result(rows, rows.size(), null, null); + } + Result result = new Result(rows, statement.getUpdateCount(), null, null); + if (sql.strip().toLowerCase(Locale.ROOT).startsWith("begin")) { + reportIsolationLevel(statement); + } + return result; + } catch (SQLException e) { + return new Result(List.of(), 0, e.getSQLState(), e.getMessage()); + } + } + + /** + * Postgres has no column that shows another session's isolation level, so every demo session + * puts its own level into its application_name, where ./inspect can read it. SHOW and SET do + * not take a snapshot, so this changes nothing about what the transaction will see. + */ + private void reportIsolationLevel(Statement statement) throws SQLException { + String level; + try (ResultSet row = statement.executeQuery("show transaction_isolation")) { + row.next(); + level = row.getString(1); + } + statement.execute("set local application_name = 'demo " + name + " (" + level + ")'"); + } + + private void report(String sql, Result result, boolean waited) { + String prefix = waited ? "(stopped waiting) " : ""; + String verb = sql.strip().toLowerCase(Locale.ROOT).split("\\s+")[0]; + if (result.failed()) { + // The transaction is now unusable until it is rolled back. A failed COMMIT has already rolled it back. + failed = !verb.equals("commit") && !verb.equals("rollback"); + List lines = result.error().lines().map(String::strip).filter(line -> !line.isEmpty()).toList(); + timeline.result(name, prefix + "ERROR, SQLSTATE " + result.sqlState() + ": " + + lines.get(0).replaceFirst("^ERROR: ", "")); + lines.stream().skip(1).limit(2).forEach(line -> timeline.result(name, line)); + } else if (!result.rows().isEmpty()) { + timeline.result(name, prefix + result.rows().stream() + .map(row -> String.join(" ", row)).collect(Collectors.joining(", "))); + } else if (verb.equals("update") || verb.equals("insert") || verb.equals("delete")) { + timeline.result(name, prefix + result.rowCount() + (result.rowCount() == 1 ? " row" : " rows")); + } else if (verb.equals("rollback") || verb.equals("commit")) { + failed = false; + } + } + + private boolean isWaitingForALock() { + try (PreparedStatement statement = monitor.prepareStatement("select cardinality(pg_blocking_pids(?)) > 0")) { + statement.setInt(1, pid); + try (ResultSet row = statement.executeQuery()) { + row.next(); + return row.getBoolean(1); + } + } catch (SQLException e) { + throw new IllegalStateException(e); + } + } + + @Override + public void close() { + thread.shutdownNow(); + try { + connection.close(); + } catch (SQLException ignored) { + // closing anyway + } + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Timeline.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Timeline.java new file mode 100644 index 0000000..b1a5eea --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/demo/Timeline.java @@ -0,0 +1,45 @@ +package com.amigoscode.isolation.demo; + +import java.io.PrintStream; + +/** Prints what each session does, one step per line. Session B is indented so the two are easy to tell apart. */ +final class Timeline { + + private final PrintStream out; + + /** @param out where to print, or null to print nothing (the tests) */ + Timeline(PrintStream out) { + this.out = out; + } + + /** Something a session does. */ + void step(String session, String text) { + print(indent(session) + session + " | " + text); + } + + /** What came back. */ + void result(String session, String text) { + print(indent(session) + session + " | -> " + text); + } + + /** What the application does with a value, outside the database. */ + void comment(String session, String text) { + print(indent(session) + session + " | # " + text); + } + + void note(String text) { + print(""); + print(" " + text); + print(""); + } + + void print(String line) { + if (out != null) { + out.println(line); + } + } + + private static String indent(String session) { + return session.equals("A") ? " " : " "; + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/statement/Statement.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/statement/Statement.java new file mode 100644 index 0000000..f241f7f --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/statement/Statement.java @@ -0,0 +1,19 @@ +package com.amigoscode.isolation.statement; + +import java.util.List; + +/** What the customer is shown: one line per account, then how many accounts and the total. */ +public record Statement(String owner, List lines, long accountCount, long total) { + + public record Line(String account, long balance) { + } + + public long sumOfLines() { + return lines.stream().mapToLong(Line::balance).sum(); + } + + /** A statement a customer can trust: the lines are all the accounts, and they add up to the total. */ + public boolean addsUp() { + return lines.size() == accountCount && sumOfLines() == total; + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/statement/StatementService.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/statement/StatementService.java new file mode 100644 index 0000000..121fd0a --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/statement/StatementService.java @@ -0,0 +1,38 @@ +package com.amigoscode.isolation.statement; + +import com.amigoscode.isolation.account.AccountRepository; +import com.amigoscode.isolation.checkpoint.Checkpoint; +import com.amigoscode.isolation.statement.Statement.Line; +import java.util.List; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class StatementService { + + private final AccountRepository accounts; + private final Checkpoint checkpoint; + + public StatementService(AccountRepository accounts, Checkpoint checkpoint) { + this.accounts = accounts; + this.checkpoint = checkpoint; + } + + /** + * Three queries, one transaction. THE BUG IS HERE: at the default isolation level every query + * sees whatever is committed at the moment that query starts, so the lines, the count and the + * total can each describe a different moment. + * + *

TODO Task 2: make all three queries read from one snapshot. + */ + @Transactional(readOnly = true) + public Statement statement(String owner) { + List lines = accounts.findByOwnerOrderById(owner).stream() // QUERY 1: the lines + .map(account -> new Line(account.getName(), account.getBalance())) + .toList(); + checkpoint.reached(Checkpoint.LINES_READ); // ...time passes... + long accountCount = accounts.countByOwner(owner); // QUERY 2: how many accounts + long total = accounts.totalBalance(owner); // QUERY 3: the total + return new Statement(owner, lines, accountCount, total); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/withdrawal/InsufficientFundsException.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/withdrawal/InsufficientFundsException.java new file mode 100644 index 0000000..0a6a478 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/withdrawal/InsufficientFundsException.java @@ -0,0 +1,9 @@ +package com.amigoscode.isolation.withdrawal; + +public class InsufficientFundsException extends RuntimeException { + + public InsufficientFundsException(long accountId, long amount, long available) { + super("Cannot withdraw " + amount + " from account " + accountId + + ": the customer's accounts hold " + available + " in total"); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalConflictException.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalConflictException.java new file mode 100644 index 0000000..7216916 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalConflictException.java @@ -0,0 +1,10 @@ +package com.amigoscode.isolation.withdrawal; + +/** Every attempt was cancelled by the database. Nothing was withdrawn, and it is safe to try again. */ +public class WithdrawalConflictException extends RuntimeException { + + public WithdrawalConflictException(long accountId, int attempts, Throwable cause) { + super("Withdrawal from account " + accountId + " was cancelled " + attempts + + " times by concurrent transactions. Nothing was withdrawn. Try again.", cause); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalService.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalService.java new file mode 100644 index 0000000..4d5ec72 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalService.java @@ -0,0 +1,26 @@ +package com.amigoscode.isolation.withdrawal; + +import org.springframework.stereotype.Service; + +/** + * Deliberately NOT transactional: each Withdrawer.withdraw call is its own transaction, and this + * class decides what to do when one of them is cancelled by the database. + */ +@Service +public class WithdrawalService { + + public static final int MAX_ATTEMPTS = 3; + + private final Withdrawer withdrawer; + + public WithdrawalService(Withdrawer withdrawer) { + this.withdrawer = withdrawer; + } + + public long withdraw(long accountId, long amount) { + // TODO Task 4: when Postgres cancels the transaction with a serialization failure (SQLSTATE + // 40001), try again, up to MAX_ATTEMPTS attempts in total. If every attempt is + // cancelled, throw WithdrawalConflictException. + return withdrawer.withdraw(accountId, amount); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/withdrawal/Withdrawer.java b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/withdrawal/Withdrawer.java new file mode 100644 index 0000000..b4a93bf --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/java/com/amigoscode/isolation/withdrawal/Withdrawer.java @@ -0,0 +1,52 @@ +package com.amigoscode.isolation.withdrawal; + +import com.amigoscode.isolation.account.Account; +import com.amigoscode.isolation.account.AccountNotFoundException; +import com.amigoscode.isolation.account.AccountRepository; +import com.amigoscode.isolation.checkpoint.Checkpoint; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** One database transaction per call: one attempt at a withdrawal. */ +@Service +public class Withdrawer { + + private final AccountRepository accounts; + private final Checkpoint checkpoint; + + public Withdrawer(AccountRepository accounts, Checkpoint checkpoint) { + this.accounts = accounts; + this.checkpoint = checkpoint; + } + + /** + * The rule: one account may go below zero, as long as all of the customer's accounts together + * stay at zero or above. + * + *

THE BUG IS HERE, twice. Between the READ and the WRITE another transaction can commit, and + * at the default isolation level this one carries on with numbers that are no longer true. + * + *

TODO Task 4: two withdrawals from the SAME account lose an update. Pick the isolation level + * that makes Postgres cancel the second writer, then add the retry in WithdrawalService. + * + *

TODO Task 6: two withdrawals from DIFFERENT accounts break the rule (write skew). Pick the + * isolation level that stops that too. + * + * @return the new balance of the account + */ + @Transactional + public long withdraw(long accountId, long amount) { + if (amount <= 0) { + throw new IllegalArgumentException("amount must be positive, got " + amount); + } + Account account = accounts.findById(accountId) // READ this account + .orElseThrow(() -> new AccountNotFoundException(accountId)); + long available = accounts.totalBalance(account.getOwner()); // READ all the customer's accounts + if (available < amount) { // CHECK the rule + throw new InsufficientFundsException(accountId, amount, available); + } + checkpoint.reached(Checkpoint.FUNDS_CHECKED); // ...time passes... + account.setBalance(account.getBalance() - amount); // WRITE a value computed from the READ + return account.getBalance(); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/resources/application.properties b/java/concepts/junior-mid/09-isolation-levels/start/src/main/resources/application.properties new file mode 100644 index 0000000..6de13d3 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/resources/application.properties @@ -0,0 +1,16 @@ +spring.application.name=isolation-levels + +# Postgres from compose.yaml. Port 5448 so it does not clash with a Postgres you already run. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5448/bank} +spring.datasource.username=${DB_USER:bank} +spring.datasource.password=${DB_PASSWORD:bank} +# The name ./inspect shows for the application's database sessions. +spring.datasource.hikari.data-source-properties.ApplicationName=bank-app + +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false +spring.sql.init.mode=always +spring.main.web-application-type=none + +# Uncomment to see every SQL statement Hibernate sends. +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/main/resources/schema.sql b/java/concepts/junior-mid/09-isolation-levels/start/src/main/resources/schema.sql new file mode 100644 index 0000000..fd5a4da --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/main/resources/schema.sql @@ -0,0 +1,13 @@ +create table if not exists account ( + id bigint primary key, + owner text not null, + name text not null, + balance bigint not null +); + +-- One customer, two accounts. The bank's rule: a single account may go below zero, +-- as long as the customer's accounts added together stay at zero or above. +insert into account (id, owner, name, balance) +values (1, 'alice', 'current', 500), + (2, 'alice', 'savings', 500) +on conflict (id) do nothing; diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/BaselineIT.java b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/BaselineIT.java new file mode 100644 index 0000000..966aa7e --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/BaselineIT.java @@ -0,0 +1,56 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.isolation.statement.Statement; +import com.amigoscode.isolation.support.IntegrationTest; +import com.amigoscode.isolation.withdrawal.InsufficientFundsException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** The bank's rules with one customer at a time. These pass from the start and must stay green. */ +@Tag("baseline") +class BaselineIT extends IntegrationTest { + + @Test + @DisplayName("Withdrawal: 100 from the current account leaves 400, and the new balance is returned") + void withdrawalLowersTheBalance() { + long newBalance = withdrawalService.withdraw(CURRENT, 100); + + assertThat(newBalance).as("returned balance").isEqualTo(400); + assertThat(balance(CURRENT)).as("current account").isEqualTo(400); + assertThat(balance(SAVINGS)).as("savings account").isEqualTo(500); + } + + @Test + @DisplayName("Withdrawal: one account may go below zero while both accounts together stay at zero or above") + void oneAccountMayGoNegative() { + withdrawalService.withdraw(CURRENT, 800); + + assertThat(balance(CURRENT)).as("current account").isEqualTo(-300); + assertThat(combinedBalance()).as("both accounts together").isEqualTo(200); + } + + @Test + @DisplayName("Withdrawal: refused when both accounts together cannot cover it, and nothing changes") + void refusedWhenTheAccountsTogetherCannotCoverIt() { + assertThatThrownBy(() -> withdrawalService.withdraw(CURRENT, 1001)) + .isInstanceOf(InsufficientFundsException.class); + + assertThat(balance(CURRENT)).as("current account").isEqualTo(500); + assertThat(combinedBalance()).as("both accounts together").isEqualTo(1000); + } + + @Test + @DisplayName("Statement: with nobody else writing, it lists both accounts and they add up to the total") + void statementAddsUpWhenNobodyElseIsWriting() { + Statement statement = statementService.statement("alice"); + + assertThat(statement.lines()).as("lines").hasSize(2); + assertThat(statement.accountCount()).as("account count").isEqualTo(2); + assertThat(statement.total()).as("total").isEqualTo(1000); + assertThat(statement.addsUp()).as("lines add up to the total").isTrue(); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/Check.java b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/Check.java new file mode 100644 index 0000000..18aad18 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/Check.java @@ -0,0 +1,114 @@ +package com.amigoscode.isolation; + +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage; + +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.platform.engine.TestExecutionResult; +import org.junit.platform.engine.discovery.ClassNameFilter; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +import org.junit.platform.launcher.TagFilter; +import org.junit.platform.launcher.TestExecutionListener; +import org.junit.platform.launcher.TestIdentifier; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; + +/** + * Runs the tests that belong to one task and prints one line per acceptance criterion. + * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2 + * (./mvnw verify runs the same tests the usual Maven way.) + */ +public final class Check { + + /** Tasks that have tests. Tasks 3, 5 and 7 are inspection tasks: you answer questions, no code. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: the bank's rules, one customer at a time (passes from the start, must stay green)"); + TASKS.put("1", "Task 1: See the statement that does not add up"); + TASKS.put("2", "Task 2: Fix the statement with REPEATABLE READ"); + TASKS.put("4", "Task 4: Stop the lost update, and retry the serialization failure"); + TASKS.put("6", "Task 6: Fix the write skew with SERIALIZABLE"); + TASKS.put("8", "Task 8: Isolation levels vs locking"); + } + + public static void main(String[] args) { + if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-8]"))) { + System.out.println("Usage: ./check [task] task is a number from 1 to 8. No number checks everything."); + System.exit(2); + } + if (args.length == 1 && !TASKS.containsKey(args[0])) { + System.out.println(); + System.out.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:"); + System.out.println("follow its steps in INTERVIEW_TASKS.md and answer the questions."); + System.out.println(); + return; + } + + boolean allGreen = true; + Launcher launcher = LauncherFactory.create(); + for (Map.Entry task : TASKS.entrySet()) { + if (args.length == 1 && !task.getKey().equals(args[0])) { + continue; + } + String tag = task.getKey().equals("baseline") ? "baseline" : "task" + task.getKey(); + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() + .selectors(selectPackage(Check.class.getPackageName())) + .filters(ClassNameFilter.includeClassNamePatterns(".*"), TagFilter.includeTags(tag)) + .build(); + System.out.println(); + System.out.println(task.getValue()); + Results results = new Results(); + launcher.execute(request, results); + System.out.println(" " + results.passed + " of " + results.total + " pass"); + allGreen &= results.passed == results.total && results.total > 0; + } + System.out.println(); + System.exit(allGreen ? 0 : 1); + } + + private static final class Results implements TestExecutionListener { + + private int total; + private int passed; + + @Override + public void executionFinished(TestIdentifier test, TestExecutionResult result) { + boolean ok = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL; + if (!test.isTest()) { + // A container that fails (for example the Spring context cannot start) takes its tests with it. + if (!ok) { + total++; + System.out.println(" [FAIL] " + test.getDisplayName() + " could not start"); + result.getThrowable().ifPresent(Results::printReason); + } + return; + } + total++; + if (ok) { + passed++; + System.out.println(" [PASS] " + test.getDisplayName()); + } else { + System.out.println(" [FAIL] " + test.getDisplayName()); + result.getThrowable().ifPresent(Results::printReason); + } + } + + private static void printReason(Throwable throwable) { + Throwable root = throwable; + while (root.getCause() != null && root.getCause() != root && root.getMessage() == null) { + root = root.getCause(); + } + String message = root.getMessage() == null ? root.getClass().getSimpleName() : root.getMessage(); + message.strip().lines() + .map(String::strip) + .filter(line -> !line.isEmpty()) + .limit(6) + .forEach(line -> System.out.println(" " + line)); + } + } + + private Check() { + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/IsolationVsLockingIT.java b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/IsolationVsLockingIT.java new file mode 100644 index 0000000..6802c75 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/IsolationVsLockingIT.java @@ -0,0 +1,44 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.isolation.demo.Anomaly; +import com.amigoscode.isolation.demo.Lab; +import com.amigoscode.isolation.demo.Level; +import com.amigoscode.isolation.demo.Outcome; +import com.amigoscode.isolation.demo.Outcome.Verdict; +import com.amigoscode.isolation.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 8. These pass from the start: they pin down the difference between raising the isolation + * level and taking a lock, on the same write-skew scenario. + */ +@Tag("task8") +class IsolationVsLockingIT extends IntegrationTest { + + @Test + @DisplayName("A lock makes the other session WAIT: with SELECT ... FOR UPDATE at READ COMMITTED, B waits for A, then reads 200 and refuses") + void forUpdateMakesTheSecondSessionWait() { + Outcome outcome = lab().run(Anomaly.WRITE_SKEW, Level.READ_COMMITTED, new Lab.Options(true, 0)); + + assertThat(outcome.waited()).as("session B had to wait for a lock").isTrue(); + assertThat(outcome.seen()).as("the combined balance each session saw").containsExactly("1000", "200"); + assertThat(outcome.failedSession()).as("session cancelled by the database").isNull(); + assertThat(outcome.finalValue()).as("both accounts together").isEqualTo(200); + assertThat(outcome.verdict()).isEqualTo(Verdict.PREVENTED); + } + + @Test + @DisplayName("An isolation level makes nobody wait: at SERIALIZABLE both sessions read 1000 at once, and one is CANCELLED instead") + void serializableCancelsInsteadOfWaiting() { + Outcome outcome = lab().run(Anomaly.WRITE_SKEW, Level.SERIALIZABLE); + + assertThat(outcome.waited()).as("a session had to wait for a lock").isFalse(); + assertThat(outcome.seen()).as("the combined balance each session saw").containsExactly("1000", "1000"); + assertThat(outcome.failedSession()).as("session cancelled by the database").isEqualTo("B"); + assertThat(outcome.finalValue()).as("both accounts together").isEqualTo(200); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/LostUpdateIT.java b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/LostUpdateIT.java new file mode 100644 index 0000000..81471a0 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/LostUpdateIT.java @@ -0,0 +1,80 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.amigoscode.isolation.checkpoint.Checkpoint; +import com.amigoscode.isolation.demo.Anomaly; +import com.amigoscode.isolation.demo.Level; +import com.amigoscode.isolation.demo.Outcome; +import com.amigoscode.isolation.demo.Outcome.Verdict; +import com.amigoscode.isolation.support.IntegrationTest; +import java.sql.SQLException; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.CannotAcquireLockException; + +@Tag("task4") +class LostUpdateIT extends IntegrationTest { + + @Test + @DisplayName("READ COMMITTED: lost update. Two withdrawals of 100 are paid out and the balance only goes from 500 to 400") + void readCommittedLosesAnUpdate() { + Outcome outcome = lab().run(Anomaly.LOST_UPDATE, Level.READ_COMMITTED); + + assertThat(outcome.seen()).as("the balance each session read").containsExactly("500", "500"); + assertThat(outcome.finalValue()).as("balance after two withdrawals of 100").isEqualTo(400); + assertThat(outcome.verdict()).isEqualTo(Verdict.HAPPENED); + } + + @Test + @DisplayName("REPEATABLE READ: the second writer is cancelled with SQLSTATE 40001, could not serialize access due to concurrent update") + void repeatableReadCancelsTheSecondWriter() { + Outcome outcome = lab().run(Anomaly.LOST_UPDATE, Level.REPEATABLE_READ); + + assertThat(outcome.verdict()).isEqualTo(Verdict.SERIALIZATION_FAILURE); + assertThat(outcome.sqlState()).as("SQLSTATE").isEqualTo("40001"); + assertThat(outcome.error()).isEqualTo("could not serialize access due to concurrent update"); + assertThat(outcome.finalValue()).as("balance after the one withdrawal that committed").isEqualTo(400); + } + + @Test + @DisplayName("Withdrawer: one attempt that loses the race fails with Spring's CannotAcquireLockException, caused by SQLSTATE 40001") + void theLosingAttemptFailsWithCannotAcquireLockException() { + // In the middle of our attempt, another customer session withdraws 100 from the same account and commits. + checkpoint.onFirst(Checkpoint.FUNDS_CHECKED, () -> inAnotherThread(() -> withdrawer.withdraw(CURRENT, 100))); + + Throwable thrown = catchThrowable(() -> withdrawer.withdraw(CURRENT, 100)); + + assertThat(thrown).as("what one losing attempt throws").isInstanceOf(CannotAcquireLockException.class); + assertThat(thrown).rootCause().isInstanceOf(SQLException.class); + assertThat(((SQLException) rootCause(thrown)).getSQLState()).as("SQLSTATE").isEqualTo("40001"); + assertThat(balance(CURRENT)).as("balance: only the other withdrawal committed").isEqualTo(400); + } + + @Test + @DisplayName("Withdrawal: two withdrawals of 100 from the same account both go through, one on its second attempt, and the balance is 300") + void bothWithdrawalsGoThroughAndNothingIsLost() { + AtomicReference other = new AtomicReference<>(); + checkpoint.onFirst(Checkpoint.FUNDS_CHECKED, + () -> other.set(inAnotherThread(() -> withdrawalService.withdraw(CURRENT, 100)))); + + long newBalance = withdrawalService.withdraw(CURRENT, 100); + + assertThat(other.get()).as("what the other withdrawal threw").isNull(); + assertThat(balance(CURRENT)).as("balance after two withdrawals of 100").isEqualTo(300); + assertThat(newBalance).as("balance returned to the customer who retried").isEqualTo(300); + assertThat(checkpoint.arrivals(Checkpoint.FUNDS_CHECKED)) + .as("attempts: ours, the other customer's, and our second one").isEqualTo(3); + } + + private static Throwable rootCause(Throwable throwable) { + Throwable root = throwable; + while (root.getCause() != null) { + root = root.getCause(); + } + return root; + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/ReadCommittedIT.java b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/ReadCommittedIT.java new file mode 100644 index 0000000..ac5f00e --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/ReadCommittedIT.java @@ -0,0 +1,77 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.isolation.demo.Anomaly; +import com.amigoscode.isolation.demo.Level; +import com.amigoscode.isolation.demo.Outcome; +import com.amigoscode.isolation.demo.Outcome.Verdict; +import com.amigoscode.isolation.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Task 1. These tests pass on purpose: they pin down what Postgres does at its default level, and + * at the level below it. Each one drives two sessions with plain SQL, one statement at a time. + */ +@Tag("task1") +class ReadCommittedIT extends IntegrationTest { + + @Autowired + private PlatformTransactionManager transactionManager; + + @Test + @DisplayName("Default: Postgres runs at READ COMMITTED, and so does a Spring transaction that sets no isolation level") + void theDefaultIsReadCommitted() { + String postgresDefault = jdbc.queryForObject("show default_transaction_isolation", String.class); + String springDefault = new TransactionTemplate(transactionManager) + .execute(status -> isolationLevelOfThisTransaction()); + + assertThat(postgresDefault).as("default_transaction_isolation").isEqualTo("read committed"); + assertThat(springDefault).as("level of a default Spring transaction").isEqualTo("read committed"); + } + + @Test + @DisplayName("READ COMMITTED: non-repeatable read. One transaction reads a balance twice and gets 500, then 600") + void nonRepeatableRead() { + Outcome outcome = lab().run(Anomaly.NON_REPEATABLE_READ, Level.READ_COMMITTED); + + assertThat(outcome.seen()).as("what session A read, in one transaction").containsExactly("500", "600"); + assertThat(outcome.verdict()).isEqualTo(Verdict.HAPPENED); + } + + @Test + @DisplayName("READ COMMITTED: phantom read. The same count returns 2 rows, then 3") + void phantomRead() { + Outcome outcome = lab().run(Anomaly.PHANTOM, Level.READ_COMMITTED); + + assertThat(outcome.seen()).as("what session A counted, in one transaction").containsExactly("2", "3"); + assertThat(outcome.verdict()).isEqualTo(Verdict.HAPPENED); + } + + @Test + @DisplayName("READ UNCOMMITTED: no dirty read in Postgres. Another session's uncommitted change stays invisible") + void noDirtyReadEvenAtReadUncommitted() { + Outcome outcome = lab().run(Anomaly.DIRTY_READ, Level.READ_UNCOMMITTED); + + assertThat(outcome.seen()).as("what session A read while B's uncommitted 0 was in the table") + .containsExactly("500"); + assertThat(outcome.verdict()).isEqualTo(Verdict.PREVENTED); + } + + @Test + @DisplayName("READ UNCOMMITTED: for every anomaly it behaves exactly like READ COMMITTED") + void readUncommittedBehavesAsReadCommitted() { + for (Anomaly anomaly : Anomaly.values()) { + Outcome readUncommitted = lab().run(anomaly, Level.READ_UNCOMMITTED); + Outcome readCommitted = lab().run(anomaly, Level.READ_COMMITTED); + + assertThat(readUncommitted.verdict()).as(anomaly.flag()).isEqualTo(readCommitted.verdict()); + assertThat(readUncommitted.seen()).as(anomaly.flag()).isEqualTo(readCommitted.seen()); + } + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/StatementIT.java b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/StatementIT.java new file mode 100644 index 0000000..1b14de8 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/StatementIT.java @@ -0,0 +1,90 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.isolation.checkpoint.Checkpoint; +import com.amigoscode.isolation.demo.Anomaly; +import com.amigoscode.isolation.demo.Level; +import com.amigoscode.isolation.demo.Outcome; +import com.amigoscode.isolation.demo.Outcome.Verdict; +import com.amigoscode.isolation.statement.Statement; +import com.amigoscode.isolation.support.IntegrationTest; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +@Tag("task2") +class StatementIT extends IntegrationTest { + + @Test + @DisplayName("REPEATABLE READ: one transaction reads a balance twice and gets 500 both times, although 600 is committed") + void repeatableReadReadsTheSameValueTwice() { + Outcome outcome = lab().run(Anomaly.NON_REPEATABLE_READ, Level.REPEATABLE_READ); + + assertThat(outcome.seen()).as("what session A read, in one transaction").containsExactly("500", "500"); + assertThat(outcome.finalValue()).as("committed balance").isEqualTo(600); + assertThat(outcome.verdict()).isEqualTo(Verdict.PREVENTED); + } + + @Test + @DisplayName("REPEATABLE READ: no phantom in Postgres. The same count returns 2 rows both times, although 3 are committed") + void repeatableReadHasNoPhantomsInPostgres() { + Outcome outcome = lab().run(Anomaly.PHANTOM, Level.REPEATABLE_READ); + + assertThat(outcome.seen()).as("what session A counted, in one transaction").containsExactly("2", "2"); + assertThat(outcome.finalValue()).as("committed rows").isEqualTo(3); + assertThat(outcome.verdict()).isEqualTo(Verdict.PREVENTED); + } + + @Test + @DisplayName("Statement: a deposit commits between its queries, and the lines still add up to the total") + void aDepositInTheMiddleDoesNotBreakTheStatement() { + checkpoint.onFirst(Checkpoint.LINES_READ, + () -> inAnotherSession("update account set balance = balance + 100 where id = 1")); + + Statement statement = statementService.statement("alice"); + + assertThat(balance(CURRENT)).as("the deposit is committed").isEqualTo(600); + assertThat(statement.total()).as("total, when the lines add up to " + statement.sumOfLines()) + .isEqualTo(statement.sumOfLines()); + } + + @Test + @DisplayName("Statement: an account is opened between its queries, and the count still matches the lines") + void aNewAccountInTheMiddleDoesNotBreakTheStatement() { + checkpoint.onFirst(Checkpoint.LINES_READ, () -> inAnotherSession( + "insert into account (id, owner, name, balance) values (3, 'alice', 'holiday', 250)")); + + Statement statement = statementService.statement("alice"); + + assertThat(statement.accountCount()).as("account count, when the statement lists " + + statement.lines().size() + " lines").isEqualTo(statement.lines().size()); + assertThat(statement.total()).as("total, when the lines add up to " + statement.sumOfLines()) + .isEqualTo(statement.sumOfLines()); + } + + @Test + @DisplayName("Statement: all of its queries run in one REPEATABLE READ transaction") + void statementRunsAtRepeatableRead() { + AtomicReference level = new AtomicReference<>(); + checkpoint.onFirst(Checkpoint.LINES_READ, () -> level.set(isolationLevelOfThisTransaction())); + + statementService.statement("alice"); + + assertThat(level.get()).as("isolation level in the middle of statement()").isEqualTo("repeatable read"); + } + + @Test + @DisplayName("Statement: the snapshot ends with the transaction. The next statement shows the deposit") + void theNextStatementSeesTheDeposit() { + checkpoint.onFirst(Checkpoint.LINES_READ, + () -> inAnotherSession("update account set balance = balance + 100 where id = 1")); + statementService.statement("alice"); + + Statement next = statementService.statement("alice"); + + assertThat(next.total()).as("total of the next statement").isEqualTo(1100); + assertThat(next.addsUp()).as("lines add up to the total").isTrue(); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/WithdrawalServiceRetryTest.java b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/WithdrawalServiceRetryTest.java new file mode 100644 index 0000000..1337190 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/WithdrawalServiceRetryTest.java @@ -0,0 +1,99 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.isolation.withdrawal.InsufficientFundsException; +import com.amigoscode.isolation.withdrawal.WithdrawalConflictException; +import com.amigoscode.isolation.withdrawal.WithdrawalService; +import com.amigoscode.isolation.withdrawal.Withdrawer; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.dao.CannotAcquireLockException; +import org.springframework.transaction.annotation.Transactional; + +/** + * Unit tests: no Spring, no database. Withdrawer is replaced by a scripted stub, so only the retry + * loop in WithdrawalService is under test and the whole class runs in milliseconds. + */ +@Tag("task4") +class WithdrawalServiceRetryTest { + + @Test + @DisplayName("Retry: when Postgres cancels the transaction (40001), the withdrawal is tried again and succeeds") + void retriesAfterASerializationFailure() { + ScriptedWithdrawer withdrawer = new ScriptedWithdrawer(serializationFailure(), 300L); + + long newBalance = new WithdrawalService(withdrawer).withdraw(1, 100); + + assertThat(newBalance).as("returned balance").isEqualTo(300); + assertThat(withdrawer.attempts).as("attempts").isEqualTo(2); + } + + @Test + @DisplayName("Retry: after 3 cancelled attempts it stops and throws WithdrawalConflictException") + void givesUpAfterThreeAttempts() { + ScriptedWithdrawer withdrawer = new ScriptedWithdrawer(serializationFailure()); + + assertThatThrownBy(() -> new WithdrawalService(withdrawer).withdraw(1, 100)) + .isInstanceOf(WithdrawalConflictException.class); + + assertThat(withdrawer.attempts).as("attempts").isEqualTo(3); + } + + @Test + @DisplayName("Retry: insufficient funds is not retried, because trying again cannot change the answer") + void doesNotRetryInsufficientFunds() { + ScriptedWithdrawer withdrawer = new ScriptedWithdrawer(new InsufficientFundsException(1, 100, 0)); + + assertThatThrownBy(() -> new WithdrawalService(withdrawer).withdraw(1, 100)) + .isInstanceOf(InsufficientFundsException.class); + + assertThat(withdrawer.attempts).as("attempts").isEqualTo(1); + } + + @Test + @DisplayName("Retry: WithdrawalService is not @Transactional, so every attempt gets a new transaction") + void theRetryLoopIsOutsideTheTransaction() throws NoSuchMethodException { + assertThat(AnnotatedElementUtils.hasAnnotation(WithdrawalService.class, Transactional.class)) + .as("@Transactional on the WithdrawalService class").isFalse(); + assertThat(AnnotatedElementUtils.hasAnnotation( + WithdrawalService.class.getMethod("withdraw", long.class, long.class), Transactional.class)) + .as("@Transactional on WithdrawalService.withdraw").isFalse(); + } + + /** What Spring throws for SQLSTATE 40001. LostUpdateIT proves that against a real database. */ + private static CannotAcquireLockException serializationFailure() { + return new CannotAcquireLockException("could not serialize access due to concurrent update"); + } + + /** + * Plays back a script: each call to withdraw returns the next balance or throws the next + * exception. The last entry repeats for ever. + */ + private static final class ScriptedWithdrawer extends Withdrawer { + + private final Deque script; + private int attempts; + + ScriptedWithdrawer(Object... outcomes) { + super(null, null); + this.script = new ArrayDeque<>(List.of(outcomes)); + } + + @Override + public long withdraw(long accountId, long amount) { + attempts++; + Object outcome = script.size() > 1 ? script.poll() : script.peek(); + if (outcome instanceof RuntimeException exception) { + throw exception; + } + return (Long) outcome; + } + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/WriteSkewIT.java b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/WriteSkewIT.java new file mode 100644 index 0000000..28d5d92 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/WriteSkewIT.java @@ -0,0 +1,117 @@ +package com.amigoscode.isolation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.amigoscode.isolation.checkpoint.Checkpoint; +import com.amigoscode.isolation.demo.Anomaly; +import com.amigoscode.isolation.demo.Level; +import com.amigoscode.isolation.demo.Outcome; +import com.amigoscode.isolation.demo.Outcome.Verdict; +import com.amigoscode.isolation.support.IntegrationTest; +import com.amigoscode.isolation.withdrawal.InsufficientFundsException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.CannotAcquireLockException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +@Tag("task6") +class WriteSkewIT extends IntegrationTest { + + @Autowired + private PlatformTransactionManager transactionManager; + + @Test + @DisplayName("REPEATABLE READ: write skew. Both sessions see 1000, both withdraw 800, both commit, and the accounts hold -600") + void repeatableReadAllowsWriteSkew() { + Outcome outcome = lab().run(Anomaly.WRITE_SKEW, Level.REPEATABLE_READ); + + assertThat(outcome.seen()).as("the combined balance each session saw").containsExactly("1000", "1000"); + assertThat(outcome.failedSession()).as("session cancelled by the database").isNull(); + assertThat(outcome.finalValue()).as("both accounts together").isEqualTo(-600); + assertThat(outcome.verdict()).isEqualTo(Verdict.HAPPENED); + } + + @Test + @DisplayName("SERIALIZABLE: the second session is cancelled at COMMIT with SQLSTATE 40001, and the accounts keep 200") + void serializableCancelsOneOfTheTwo() { + Outcome outcome = lab().run(Anomaly.WRITE_SKEW, Level.SERIALIZABLE); + + assertThat(outcome.verdict()).isEqualTo(Verdict.SERIALIZATION_FAILURE); + assertThat(outcome.sqlState()).as("SQLSTATE").isEqualTo("40001"); + assertThat(outcome.error()) + .isEqualTo("could not serialize access due to read/write dependencies among transactions"); + assertThat(outcome.finalValue()).as("both accounts together").isEqualTo(200); + } + + @Test + @DisplayName("Spring: a transaction that Postgres cancels at COMMIT also arrives as CannotAcquireLockException") + void aFailedCommitIsAlsoCannotAcquireLockException() { + TransactionTemplate serializable = new TransactionTemplate(transactionManager); + serializable.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + String readBoth = "select sum(balance) from account where owner = 'alice'"; + + // We read both accounts and write account 1. Before we commit, a second transaction reads + // both accounts, writes account 2 and commits. Every statement of ours worked: only COMMIT fails. + Throwable thrown = catchThrowable(() -> serializable.executeWithoutResult(ours -> { + jdbc.queryForObject(readBoth, Long.class); + jdbc.update("update account set balance = balance - 800 where id = 1"); + inAnotherThread(() -> serializable.executeWithoutResult(theirs -> { + jdbc.queryForObject(readBoth, Long.class); + jdbc.update("update account set balance = balance - 800 where id = 2"); + })); + })); + + assertThat(thrown).as("what a failed COMMIT throws").isInstanceOf(CannotAcquireLockException.class); + assertThat(thrown).hasMessageContaining("commit"); + assertThat(combinedBalance()).as("both accounts together").isEqualTo(200); + } + + @Test + @DisplayName("Spring: an isolation level asked for inside a transaction that is already open is silently ignored") + void anInnerIsolationLevelIsIgnored() { + TransactionTemplate outer = new TransactionTemplate(transactionManager); + TransactionTemplate inner = new TransactionTemplate(transactionManager); + inner.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + + // The inner one joins the outer transaction (propagation REQUIRED, the default), which + // started at the default level. A transaction has one level, fixed before its first query. + String level = outer.execute(open -> inner.execute(joined -> isolationLevelOfThisTransaction())); + + assertThat(level).as("level inside the inner, 'serializable' transaction").isEqualTo("read committed"); + } + + @Test + @DisplayName("Withdrawal: 800 from current and 800 from savings at the same time: one goes through, the other is refused, 200 is left") + void onlyOneOfTheTwoWithdrawalsGoesThrough() { + AtomicReference other = new AtomicReference<>(); + checkpoint.onFirst(Checkpoint.FUNDS_CHECKED, + () -> other.set(inAnotherThread(() -> withdrawalService.withdraw(SAVINGS, 800)))); + + Throwable ours = catchThrowable(() -> withdrawalService.withdraw(CURRENT, 800)); + + assertThat(combinedBalance()).as("both accounts together (the rule: never below 0)").isEqualTo(200); + assertThat(other.get()).as("what the withdrawal from savings threw").isNull(); + assertThat(ours).as("what the withdrawal from current threw, after its retry read the new balances") + .isInstanceOf(InsufficientFundsException.class); + } + + @Test + @DisplayName("Withdrawal: every attempt runs in a SERIALIZABLE transaction") + void everyAttemptRunsAtSerializable() { + List levels = Collections.synchronizedList(new ArrayList<>()); + checkpoint.onReached(Checkpoint.FUNDS_CHECKED, arrival -> levels.add(isolationLevelOfThisTransaction())); + + withdrawalService.withdraw(CURRENT, 100); + + assertThat(levels).as("isolation level in the middle of withdraw()").containsExactly("serializable"); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/support/IntegrationTest.java b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/support/IntegrationTest.java new file mode 100644 index 0000000..e4bdb88 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/test/java/com/amigoscode/isolation/support/IntegrationTest.java @@ -0,0 +1,146 @@ +package com.amigoscode.isolation.support; + +import com.amigoscode.isolation.checkpoint.ScriptedCheckpoint; +import com.amigoscode.isolation.demo.Db; +import com.amigoscode.isolation.demo.Lab; +import com.amigoscode.isolation.statement.StatementService; +import com.amigoscode.isolation.withdrawal.WithdrawalService; +import com.amigoscode.isolation.withdrawal.Withdrawer; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.concurrent.atomic.AtomicReference; +import javax.sql.DataSource; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Primary; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * Base class for the *IT tests. They run against a real Postgres started by Testcontainers (Docker + * must be running), because isolation levels are something the database does: none of this shows + * up against mocks or an in-memory database. One container is shared by every test class. + * + *

Nothing here sleeps and hopes. A test decides the exact order of the steps: either it drives + * two database sessions one statement at a time ({@link #lab()}), or it makes a second session do + * its work at a {@link ScriptedCheckpoint} in the middle of the application's transaction. + */ +@SpringBootTest(properties = "spring.main.banner-mode=off") +@Import(IntegrationTest.TestBeans.class) +public abstract class IntegrationTest { + + public static final long CURRENT = 1; + public static final long SAVINGS = 2; + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + static void database(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", POSTGRES::getJdbcUrl); + registry.add("spring.datasource.username", POSTGRES::getUsername); + registry.add("spring.datasource.password", POSTGRES::getPassword); + } + + @TestConfiguration + static class TestBeans { + + @Bean + @Primary + ScriptedCheckpoint scriptedCheckpoint() { + return new ScriptedCheckpoint(); + } + } + + @Autowired + protected StatementService statementService; + + @Autowired + protected WithdrawalService withdrawalService; + + @Autowired + protected Withdrawer withdrawer; + + @Autowired + protected ScriptedCheckpoint checkpoint; + + @Autowired + protected JdbcTemplate jdbc; + + @Autowired + private DataSource dataSource; + + /** Every test starts with alice's two accounts: current (id 1) = 500 and savings (id 2) = 500. */ + @BeforeEach + void aliceHasTwoAccounts() throws SQLException { + checkpoint.reset(); + try (Connection connection = dataSource.getConnection()) { + Db.reset(connection); + } + } + + /** Plain SQL in two sessions, stepped in a fixed order. Prints nothing. */ + protected Lab lab() { + return new Lab(POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword(), null); + } + + /** + * Runs SQL in a different database session from the one the calling thread's transaction uses, + * and commits it at once. This is "somebody else" committing while the application is busy. + */ + protected void inAnotherSession(String sql) { + // dataSource.getConnection() hands out a fresh pooled connection. (JdbcTemplate would not do: + // inside a transaction it joins the transaction's own connection.) + try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { + statement.execute(sql); + } catch (SQLException e) { + throw new IllegalStateException(e); + } + } + + /** + * Runs {@code task} on a second thread and waits for it to finish, so it gets its own + * transaction and its own session. Returns what it threw, or null when it succeeded. + */ + protected Throwable inAnotherThread(Runnable task) { + AtomicReference thrown = new AtomicReference<>(); + Thread thread = new Thread(() -> { + try { + task.run(); + } catch (Throwable e) { + thrown.set(e); + } + }, "second-customer"); + thread.start(); + try { + thread.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + return thrown.get(); + } + + /** The isolation level of the transaction the calling thread is in, as Postgres reports it. */ + protected String isolationLevelOfThisTransaction() { + return jdbc.queryForObject("select current_setting('transaction_isolation')", String.class); + } + + protected long balance(long accountId) { + return jdbc.queryForObject("select balance from account where id = ?", Long.class, accountId); + } + + protected long combinedBalance() { + return jdbc.queryForObject("select sum(balance) from account where owner = 'alice'", Long.class); + } +} diff --git a/java/concepts/junior-mid/09-isolation-levels/start/src/test/resources/logback-test.xml b/java/concepts/junior-mid/09-isolation-levels/start/src/test/resources/logback-test.xml new file mode 100644 index 0000000..82166a4 --- /dev/null +++ b/java/concepts/junior-mid/09-isolation-levels/start/src/test/resources/logback-test.xml @@ -0,0 +1,11 @@ + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + + diff --git a/java/concepts/junior-mid/10-constraints-and-races/INTERVIEW_TASKS.md b/java/concepts/junior-mid/10-constraints-and-races/INTERVIEW_TASKS.md new file mode 100644 index 0000000..5551dfc --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/INTERVIEW_TASKS.md @@ -0,0 +1,351 @@ +# Interview Tasks — Constraints and Races + +> **In `start/`, `./check` FAILS on purpose: 19 of 35 checks pass.** Tasks 2, 4, 5, 6 and 7 turn the +> other 16 green. Tasks 1, 3 and 8 are inspection tasks: you run things, look, and answer questions. + +Do the tasks in order. Every fix is followed by an inspection: Tasks 3 and 8 are nothing else, and +Tasks 4 to 7 each end with an **Inspect** part. A green test tells you the fix works, the inspection +tells you **why**, and the why is what an interviewer asks for. + +Stuck, or want the explanation? The same task number in [`TASKS_GUIDED.md`](TASKS_GUIDED.md) walks +you through it with the expected output. + +Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`. + +**Rules:** work in `start/`. Never edit, delete or disable a test. Constraints go into +`src/main/resources/schema.sql`, which is applied on every start. Do not fix +`SettingsStore.checkThenInsert` or `SettingsStore.insertAndCatchInside`: they stay broken so you can +compare against them. Do not add validation to the controllers: Task 7 needs them as they are. + +--- + +## Task 1: See the Duplicate Signup (10 min) + +**Story:** *Support has a customer who cannot log in: there are two accounts with her email. The +signup code checks `existsByEmail` before it saves, so "this cannot happen". Before you change +anything, reproduce it.* + +**Steps:** +1. `docker compose up -d`, then `./demo`. How many accounts were created? How many rows are there? +2. `./demo --sql`. Each line shows the thread that ran the statement. Write down the order of the + statements across the two threads. +3. Open `SignupService.signUp`. Match each SQL statement to the line of Java that produced it. +4. `./inspect`. Which constraints does `users` have? Find the duplicate in the last section. +5. `./demo --requests 20`. How many rows now? +6. `./demo --work-ms 0`, a few times. Does the bug still happen? + +**Acceptance Criteria** (`./check 1`, already passing: this test documents the race) +- [ ] You can name the pattern that causes the bug +- [ ] You can point to the two SQL statements the bug happens between +- [ ] You can explain why the second request's check did not see the first request's row +- [ ] You can explain why a fast machine, or `@Transactional`, does not make the bug go away +- [ ] `SignupRaceIT.bothRequestsPassTheCheck` passes + +**Hints:** +- Both requests ran the same `select` before either ran an `insert` +- Who is the only party that sees both inserts? + +--- + +## Task 2: Fix It With a UNIQUE Constraint and a 409 (20 min) + +**Story:** *Make the database refuse the second row. Then make sure the person who lost the race +gets a clear "this email is taken", not an error page. Edit `schema.sql`, then `SignupService`.* + +**Acceptance Criteria** (`./check 2`) +- [ ] The database refuses a second row with the same email, even from code that skips the service + — `UniqueEmailIT.theDatabaseRefusesTheSameEmailTwice` +- [ ] Two signups with the same email at the same moment: one account, the other is told the email + is taken — `UniqueEmailIT.onlyOneOfTwoSignupsCreatesAnAccount` +- [ ] 20 signups with the same email: 1 account, 19 told the email is taken, 1 row + — `UniqueEmailIT.onlyOneOfTwentySignupsCreatesAnAccount` +- [ ] When the insert is refused by `users_email_key`, the signup fails with `EmailTakenException` + — `SignupServiceTest.aViolationOfTheEmailConstraintMeansEmailTaken` +- [ ] A violation of any other constraint is not reported as "email taken" + — `SignupServiceTest.aViolationOfAnotherConstraintIsNotEmailTaken` (already passing: keep it + that way) +- [ ] A signup that arrives after the first one finished is still stopped by the application's + check — `UniqueEmailIT.aLaterSignupIsStoppedByTheFastPath` (already passing: keep it that way) +- [ ] `./demo` prints `RESULT: OK` +- [ ] The baseline tests still pass (`./check`) + +**Hints:** +- Name the constraint `users_email_key`. Your code will need that name +- Add the constraint first and run `./demo` before you touch the Java. Look at what the loser gets +- Spring throws `DataIntegrityViolationException`. Its cause is Hibernate's + `ConstraintViolationException`, which has `getConstraintName()` +- Do not delete the `existsByEmail` check. What is it still good for? + +--- + +## Task 3: Inspect the Constraint (15 min) + +**Story:** *Your fix passes the tests. Now prove you know why.* + +**Steps:** +1. `./demo --sql`. Both threads still run the `select` and both still run the `insert`. Which line + is new compared with Task 1? Who wrote it: your code, Hibernate or Postgres? +2. In the same output: the loser's `insert` was sent at the same moment as the winner's. What did + the database do with it until the winner committed? +3. `./inspect`. `users` now has one more line under CONSTRAINTS and one more under INDEXES. Why + both? +4. `./demo --requests 20`. Look at the `id` of the one row that exists. What happened to the other + numbers? +5. Comment out the `existsByEmail` check in `SignupService` and run `./check 2`. Which check fails? + Is the data still correct? Put the check back. +6. `./demo --scenario case`. What is the `RESULT`? Why did the constraint not help? + +**Acceptance Criteria** (no tests: you answer) +- [ ] You can quote the error Postgres sends, including the constraint name and the SQLSTATE +- [ ] You can say what the losing `insert` waits for +- [ ] You can explain the relationship between a UNIQUE constraint and a unique index +- [ ] You can give two reasons to keep the application's check, and one reason it is not enough +- [ ] You can explain what happens when you add a UNIQUE constraint to a table that already holds + duplicates + +--- + +## Task 4: The Same Email in Different Capital Letters (15 min) + +**Story:** *`Ana@Example.com` and `ana@example.com` are the same mailbox, and both just signed up. +The constraint compares text exactly, so it let them through. Marketing wants the email kept the +way the user typed it, so lower-casing it before saving is not allowed.* + +**Acceptance Criteria** (`./check 4`) +- [ ] The database refuses `ana@example.com` when `Ana@Example.com` is already there + — `CaseInsensitiveEmailIT.theDatabaseRefusesTheSameEmailInAnotherCase` +- [ ] Both spellings sign up at the same moment: one account, the other is told the email is taken + — `CaseInsensitiveEmailIT.onlyOneOfTwoSpellingsCreatesAnAccount` +- [ ] `ANA@EXAMPLE.COM` arriving after `ana@example.com` is stopped by the application's check + — `CaseInsensitiveEmailIT.aLaterSignupInAnotherCaseIsStoppedByTheFastPath` +- [ ] `./demo --scenario case` prints `RESULT: OK` +- [ ] `./check 2` still passes + +**Hints:** +- A constraint cannot contain a function call. A unique **index** can: `create unique index ... on + users (lower(email))` +- The new index has its own name. What does the loser get before you teach `SignupService` that + name? +- The check has to compare the same way as the index + +**Inspect:** +1. `./inspect`. Where does the new rule show up: under CONSTRAINTS or under INDEXES? +2. `./demo --scenario case --sql`. Which constraint name is in the error now? +3. Spring Data can derive `existsByEmailIgnoreCase` on its own. Try it and look at the SQL with + `--sql`. Which function does it use, and can that query use your index? + +--- + +## Task 5: One ACTIVE Subscription per User (15 min) + +**Story:** *A customer was charged twice this month: two ACTIVE subscriptions, started in the same +second. The rule is "at most one ACTIVE subscription per user". Cancelled subscriptions are +history: a user may have any number of them. Edit `schema.sql`, then `SubscriptionService`.* + +**Acceptance Criteria** (`./check 5`) +- [ ] The database refuses a second ACTIVE subscription for the same user + — `OneActiveSubscriptionIT.theDatabaseRefusesASecondActiveRow` +- [ ] One user subscribes twice at the same moment: one ACTIVE subscription, the other request is + told the user is already subscribed — `OneActiveSubscriptionIT.onlyOneOfTwoRequestsSubscribes` +- [ ] When the insert is refused by `subscriptions_one_active_per_user`, it fails with + `AlreadySubscribedException` + — `SubscriptionServiceTest.aViolationOfTheOneActiveIndexMeansAlreadySubscribed` +- [ ] Subscribe, cancel, subscribe, cancel, subscribe works: 2 CANCELLED rows and 1 ACTIVE row + — `OneActiveSubscriptionIT.cancelledRowsMayRepeat` (already passing: keep it that way) +- [ ] Two different users are both ACTIVE — `OneActiveSubscriptionIT.twoUsersCanBothBeActive` + (already passing: keep it that way) +- [ ] `./demo --scenario subscription` prints `RESULT: OK` + +**Hints:** +- `unique (user_id)` is too strict and `unique (user_id, status)` is too: why? +- An index can have a `WHERE` clause. Rows that do not match it are not in the index at all +- Name it `subscriptions_one_active_per_user` + +**Inspect:** +1. `./inspect`. Read the definition of the new index. +2. Remove the `where` from your index and run `./demo --scenario subscription`. What is the + `RESULT`? Put it back. +3. `./demo --scenario subscription --requests 20`. Which id does the new subscription get after + the cancel? + +--- + +## Task 6: Create If Absent, and the Aborted Transaction (25 min) + +**Story:** *The home screen asks for the user's settings. The first time, the row does not exist +yet, so the code creates it with the defaults. The app sends two requests when it opens, and one +of them gets a 500. `user_settings` already has a primary key on `user_id`, so the data is fine. +The application is not. Somebody already tried `try { insert } catch { select }`: it made things +worse. Fix `SettingsStore.insertOnConflictDoNothing` and `SettingsStore.saveTheme`.* + +**Steps before you write code:** +1. `./demo --scenario settings --strategy check-first`. Who gets the 500, and what does it say? +2. `./demo --scenario settings --strategy catch-inside --sql`. The duplicate is caught. What fails + now? Which statement was it? +3. Read `SettingsStore.insertAndCatchInside`, then the two strategies that work: + `SettingsService.insertAndCatchOutside` and `SettingsStore.insertWithSavepoint`. Run both with + `--sql`. + +**Acceptance Criteria** (`./check 6`) +- [ ] on-conflict: two first requests at the same moment: both get the settings, one row, exactly + one is told it created the row — `SettingsIT.onConflictDoNothingSurvivesARace` +- [ ] on-conflict: an existing row is left alone: a saved theme is not reset to the default + — `SettingsIT.onConflictDoNothingDoesNotOverwrite` (already passing: keep it that way) +- [ ] save theme: two saves at the same moment for a user without a row: both succeed, one row, + exactly one is told it created the row — `SettingsIT.saveThemeSurvivesARace` +- [ ] save theme: the first save creates the row, the second one updates it + — `SettingsIT.saveThemeCreatesThenUpdates` (already passing: keep it that way) +- [ ] The five tests that document the bug, the trap and the two working shapes still pass +- [ ] `./demo --scenario settings` and `./demo --scenario theme` print `RESULT: OK` + +**Hints:** +- `insert ... on conflict (user_id) do nothing`. `JdbcTemplate.update` returns the number of rows + the statement inserted +- `insert ... on conflict (user_id) do update set theme = excluded.theme`. It reports 1 row whether + it inserted or updated, so the row count is no use here. Look up `RETURNING` and `xmax` +- Neither statement can fail on the primary key. Why does that matter inside a transaction? + +**Inspect:** +1. `./demo --scenario settings --sql`. How many statements does each request run? Is there an + error anywhere in the output? +2. Read `SettingsIT.swallowingInsideTheTransactionLosesEarlierWrites`. The transaction returns + normally. What happened to the `update` that ran before the refused `insert`? + +--- + +## Task 7: Bad Data: NOT NULL, CHECK and FOREIGN KEY (15 min) + +**Story:** *Finance found a subscription with -3 seats, one with a negative price, one for a user +that does not exist, and a user without an email. The controllers validate nothing. Somebody will +fix the validation, and somebody else will add a new endpoint next year and forget it again. Make +the database refuse these rows whoever sends them. Only `schema.sql` changes.* + +**Acceptance Criteria** (`./check 7`) +- [ ] A user without an email is refused — `BadDataIT.aUserNeedsAnEmail` +- [ ] A subscription with -3 seats is refused — `BadDataIT.seatsMustBePositive` +- [ ] A negative price is refused — `BadDataIT.thePriceMustNotBeNegative` +- [ ] A subscription for a user that does not exist is refused — `BadDataIT.aSubscriptionNeedsAUser` +- [ ] `./demo --scenario bad-data` prints `RESULT: OK` +- [ ] `./check` prints 35 passes and no failures + +**Hints:** +- Three kinds of rule: the value must be there, the value must make sense on its own, the value + must point at a row that exists +- `subscriptions.status` already has a named `CHECK`: copy its shape +- A UNIQUE constraint accepts any number of NULLs. Which task does that weaken? + +**Inspect:** +1. `./demo --scenario bad-data`. Every request now gets a 500. Is that better or worse than + before? What would you add so that the caller gets a 400, and would you then remove the + constraints? + +--- + +## Task 8: Inspect Everything and Compare (15 min) + +**Story:** *"How would you stop that at the database level?" is the interview question. Collect +the evidence, then answer it for each rule.* + +**Steps:** +1. `./demo --scenario subscription`, then `./inspect`. Read the whole output. For every line under + CONSTRAINTS and INDEXES, name the task that added it and the bug it stops. +2. `users` has `users_email_key` and `users_email_lower_key`. Is one of them redundant? Which one + fires when the exact same email is inserted twice (`./demo --sql`)? +3. Run the four settings strategies that are not `on-conflict` with `--sql` and count the + statements each one sends for the request that loses. +4. A new rule arrives: "a user may have at most 3 CANCELLED subscriptions per year". Can any of the + tools in this project enforce it? What would you use instead? +5. Another one: "an email may be reused after the account is deleted, and deleted accounts are + kept with `deleted_at` set". Write the index. + +**Acceptance Criteria** (no tests: you answer) +- [ ] For each of UNIQUE, expression index, partial index, NOT NULL, CHECK and FOREIGN KEY you can + give the rule it enforces in this project +- [ ] You can say which rules a constraint cannot express, and what you use then +- [ ] You can describe the three correct ways to handle a constraint violation, and the one that + does not work +- [ ] You can explain why the application check and the constraint are both kept + +--- + +## Questions to Ask Afterwards + +Answer out loud, in full sentences, before reading the answer in brackets. + +- You check `existsByEmail` before you save. How can there still be duplicates? (Check-then-insert + is two statements. Two requests can both run the check before either runs the insert, and both + are told "not there". Each sees only committed rows, and neither has committed yet. Nothing in + the application ties the check to the insert.) +- Does `@Transactional` fix it? (No. A transaction makes your own statements succeed or fail + together. Under the default isolation level it does not stop another transaction from running + the same check at the same time. In this project `checkThenInsert` is `@Transactional` and still + races.) +- So how do you fix it? (A UNIQUE constraint. The database is the only place that sees both + inserts, so it is the only place that can refuse the second one. The second insert waits for the + first transaction to finish and then fails with SQLSTATE 23505.) +- If the constraint does the job, why keep the application check? (It answers almost every + duplicate with one cheap read and a precise message, without a failed insert, an error in the + log and a burned sequence number. It is an optimisation and a courtesy. It is not the + guarantee.) +- How do you turn the violation into a 409? (With JPA, Spring throws + `DataIntegrityViolationException`; its cause is Hibernate's `ConstraintViolationException`, and + `getConstraintName()` gives the name. Match the name: `users_email_key` means "email taken", + anything else is rethrown. With JdbcTemplate a unique violation is a `DuplicateKeyException`, + which is a subclass. Never map every `DataIntegrityViolationException` to 409.) +- Why name your constraints? (Because the name is the only stable way to tell violations apart, + and it shows up in logs. Without a name Postgres generates one, such as `users_email_key`, and + your code then depends on a name nobody chose.) +- How do you make email unique regardless of case? (A unique index on `lower(email)`. A constraint + cannot hold an expression, an index can. The lookup must use `lower(email)` as well, or it cannot + use the index. The alternatives are the `citext` column type, or normalising the value before it + is stored.) +- How do you enforce "one ACTIVE subscription per user"? (A partial unique index: + `unique (user_id) where status = 'ACTIVE'`. Only ACTIVE rows are in the index, so cancelled rows + never collide.) +- What does `INSERT ... ON CONFLICT` do? (It makes "insert unless it is there" one atomic + statement. `DO NOTHING` skips the insert, and the row count tells you whether a row was inserted. + `DO UPDATE` turns it into an upsert; it reports one row either way, so use + `RETURNING (xmax = 0)` to tell an insert from an update. It needs a unique constraint or index to + detect the conflict.) +- You catch the duplicate-key exception and run a SELECT. It fails with "current transaction is + aborted". Why? (In Postgres any failed statement puts the transaction into an aborted state, and + every statement after it is rejected until a rollback. Catching the Java exception does not + change the state of the database transaction.) +- And if you catch it and run nothing else? (Worse. The method returns normally, the commit is + quietly turned into a rollback, and everything the transaction wrote before the failure is gone + without any error. `SettingsIT` has a test that shows it.) +- What are the correct shapes? (Catch the exception outside the transaction, so the failed + transaction is already over. Or set a savepoint and roll back to it. Running the insert in a + `REQUIRES_NEW` transaction works too, but it takes a second connection. Or use `ON CONFLICT` so + that nothing fails in the first place.) +- What are CHECK, NOT NULL and FOREIGN KEY for, if the application validates? (They hold whoever + writes: a new endpoint without validation, a batch job, a script, a second service. Validation + gives the caller a good error message. The constraint gives everyone else a guarantee.) +- Does a UNIQUE constraint treat NULLs as equal? (No. Any number of rows may have NULL in a unique + column. Add NOT NULL, or since Postgres 15 declare it `UNIQUE NULLS NOT DISTINCT`.) +- What happens when you add a unique constraint to a table that already has duplicates? (The + `ALTER TABLE` fails with "could not create unique index ... Key ... is duplicated". You have to + find and merge the duplicates first. This is why the constraint belongs in the first migration, + not the one after the incident.) +- What can a constraint not do? (Rules that span many rows or other tables, such as "at most 3 + per year" or "the total may not exceed the limit". For those you lock a parent row or use an + atomic update, as in `../07-locking`.) +- How is this different from an idempotency key? (Same mechanism, different purpose. An + idempotency key is a unique constraint on a value the client sends, so that a retried request is + recognised. See `../08-idempotency`.) + +## Tips for Interviewers + +- The most common wrong answer is "I check if it exists first". Ask what happens when two requests + run that check at the same time, and wait. +- The second most common is "I put `@Transactional` on it" or "I make the method `synchronized`". + Ask how many instances of the service run in production. +- After Task 2, ask the candidate to predict the output of `./demo --requests 20` including the + `id` of the surviving row. A strong candidate knows the sequence does not roll back. +- Watch what they do with the exception. Catching `DataIntegrityViolationException` and returning + 409 for all of them is the bug that separates levels: a NOT NULL violation is then reported as + "email taken". +- In Task 6, ask "what if you just catch it?" before they run `catch-inside`. Few candidates have + seen "current transaction is aborted" explained, most have seen it in a log. +- For senior candidates, Task 8 steps 4 and 5 are the real questions: knowing where constraints + stop, and writing a partial index for soft deletes without help. diff --git a/java/concepts/junior-mid/10-constraints-and-races/README.md b/java/concepts/junior-mid/10-constraints-and-races/README.md new file mode 100644 index 0000000..d0364fb --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/README.md @@ -0,0 +1,181 @@ +# Constraints and Races — The Database as the Last Line of Defence + +> **In `start/`, `./check` FAILS on purpose: 19 of 35 checks pass.** That is the exercise, not a +> broken checkout. Tasks 2, 4, 5, 6 and 7 turn the other 16 green. + +Two people sign up with the same email at the same moment. The code checks "is this email taken?" +for both, both are told "no", and the `users` table ends up with two accounts for one address. This +project lets you watch that happen, then make the database refuse the second row and turn its +refusal into a clean answer. + +It answers the interview questions students most often get wrong: + +- "You check `existsByEmail` before you save. Why can you still get duplicates?" +- "How do you return a 409 instead of a 500 when a unique constraint is violated?" +- "How do you enforce 'only one ACTIVE subscription per user' in the database?" +- "What is `INSERT ... ON CONFLICT`, and when do you need it?" +- "You caught the exception. Why does the next query say 'current transaction is aborted'?" + +## Tech Stack + +- **Java 25**, **Spring Boot 4**, Spring Data JPA (Hibernate), JdbcTemplate +- **PostgreSQL 17** in Docker +- JUnit 5, AssertJ, Testcontainers + +## What you need + +- JDK 25 +- Docker, running + +## Getting Started + +Work in `start/`. Commands are shown for macOS and Linux; on Windows type `.\demo` where you see +`./demo` (same for `inspect` and `check`). + +```bash +cd start +docker compose up -d # Postgres on port 5449 +./demo # watch one email get two accounts +./check # 19 of 35 pass: that is your starting point +``` + +The first run downloads Maven and the dependencies, so it takes a minute or two. + +When you are finished: `docker compose down`. + +## The three tools + +### `./demo` — see what happens + +Starts the real application, sends requests at it over HTTP at the same moment, and prints the rows +that ended up in the database. Every run starts from empty tables. + +``` +./demo two signups, one email +./demo --scenario case signup | case | subscription | settings | theme | bad-data +./demo --scenario settings --strategy catch-inside + check-first | catch-inside | catch-outside | savepoint | on-conflict +./demo --requests 20 more requests at the same moment +./demo --work-ms 0 no time between the check and the insert +./demo --sql print every SQL statement and the thread that ran it +./demo --help +``` + +### `./inspect` — look inside the database + +For every table: its columns, its constraints (from `pg_constraint`) and its indexes (from +`pg_indexes`). Then what is wrong in the data right now: emails with more than one row, users with +more than one ACTIVE subscription, and rows that should never have been stored. Run it after +`./demo`. + +### `./check` — are the acceptance criteria met? + +`./check 2` runs the tests for Task 2 and prints one line per criterion. `./check` runs everything. +`./mvnw verify` runs the same tests the usual Maven way. + +The tests are the acceptance criteria. **Never edit, delete or disable a test.** + +## The code + +``` +start/src/main/resources/ +└── schema.sql the tables. YOU ADD THE CONSTRAINTS HERE + +start/src/main/java/com/amigoscode/constraints/ +├── user/ +│ ├── SignupController.java POST /api/signups +│ ├── SignupService.java check, then insert. THE BUG IS HERE +│ └── UserRepository.java the email check +├── subscription/ +│ ├── SubscriptionController.java POST /api/subscriptions, POST /api/subscriptions/{id}/cancel +│ └── SubscriptionService.java check, then insert. The same bug +├── settings/ +│ ├── SettingsController.java PUT /api/users/{id}/settings?strategy=... PUT .../settings/theme +│ ├── SettingsService.java picks the strategy +│ └── SettingsStore.java one transaction per strategy, plain SQL +├── work/ 100 ms of work that runs between a check and an insert +└── demo/ the demo and inspect tools. Nothing to change here +``` + +`schema.sql` is run every time the application starts: it drops the tables and creates them again. +So the database always has exactly the constraints written in that file. To add one, edit the file +and run the command again. (In a real project the same line would go into a Flyway or Liquibase +migration.) + +`SettingsStore.checkThenInsert` and `SettingsStore.insertAndCatchInside` stay broken for ever, so +you can always compare against them. + +## Two ways to work + +- **[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md)**: challenge mode. A story, acceptance criteria and + hints for each task. Use this if you want to work it out yourself. +- **[`TASKS_GUIDED.md`](TASKS_GUIDED.md)**: the same eight tasks, step by step, with the output you + should see and an explanation of why. Use this to learn the concept, or when you are stuck. + +Both files use the same task numbers. + +| Task | What you do | Checked by | +|---|---|---| +| 1 | See the duplicate signup | `./check 1` (passes: it documents the race) | +| 2 | Fix it with a UNIQUE constraint and a 409 | `./check 2` | +| 3 | Inspect the constraint | you answer questions | +| 4 | The same email in different capital letters: a unique index on `lower(email)` | `./check 4` | +| 5 | One ACTIVE subscription per user: a partial unique index | `./check 5` | +| 6 | Create if absent: `ON CONFLICT`, and the aborted transaction | `./check 6` | +| 7 | Bad data: NOT NULL, CHECK and FOREIGN KEY | `./check 7` | +| 8 | Inspect everything and compare | you answer questions | + +Related projects: [`../07-locking`](../07-locking) protects a row that already exists (two buyers, +one item), and [`../08-idempotency`](../08-idempotency) uses a unique key to make a retried request +safe. + +## Solution + +`solution/` is the same project with every task done: `cd solution && ./check` prints 35 of 35. + +To start again from scratch: `git checkout -- start` (this throws away your changes in `start/`). + +

+Spoiler: the bug and the fixes + +**The bug.** `SignupService` asks `existsByEmail`, hashes the password, then saves. Nothing ties the +check to the insert. Two requests can both be told "not taken" and both insert. `@Transactional` +does not help, and neither does a faster machine. The application cannot make this check safe on +its own, because the two requests may even run on two different servers. + +**Fix 1, UNIQUE (Task 2).** `constraint users_email_key unique (email)` in `schema.sql`. The +database refuses the second row. `users.save` then throws Spring's +`DataIntegrityViolationException`, whose cause is Hibernate's `ConstraintViolationException`, and +`getConstraintName()` on that says which rule it was. `SignupService` turns `users_email_key` into +`EmailTakenException`, a 409. The `exists` check stays as a fast path. + +**Fix 2, expression index (Task 4).** `create unique index users_email_lower_key on users +(lower(email))`, and the check compares `lower(email)` too. + +**Fix 3, partial index (Task 5).** `create unique index subscriptions_one_active_per_user on +subscriptions (user_id) where status = 'ACTIVE'`. Only ACTIVE rows are in the index, so cancelled +rows may repeat. + +**Fix 4, ON CONFLICT (Task 6).** `insert ... on conflict (user_id) do nothing` and the row count (1 +or 0) for get-or-create; `on conflict (user_id) do update ... returning (xmax = 0)` for +create-or-update. Nothing fails, so the transaction is never aborted. + +**Fix 5, the rest (Task 7).** `not null` on `users.email`, `check (seats > 0)`, +`check (price_cents >= 0)` and `references users (id)` on `subscriptions`. + +**The trap.** In Postgres a failed statement aborts the whole transaction. Catching the exception +inside the `@Transactional` method and carrying on gives "current transaction is aborted, commands +ignored until end of transaction block". Catch it outside the transaction, use a savepoint, or use +`ON CONFLICT` so that nothing fails. + +| The rule | The tool | +|---|---| +| No two rows with the same value | `UNIQUE` constraint | +| The same, on a computed value (`lower(email)`) | unique index on an expression | +| The same, for some of the rows only (`status = 'ACTIVE'`) | partial unique index | +| A value must be present | `NOT NULL` | +| A value must make sense on its own (`seats > 0`) | `CHECK` | +| A row must point at a row that exists | `FOREIGN KEY` | +| Create it unless it is there | `INSERT ... ON CONFLICT` | + +
diff --git a/java/concepts/junior-mid/10-constraints-and-races/TASKS_GUIDED.md b/java/concepts/junior-mid/10-constraints-and-races/TASKS_GUIDED.md new file mode 100644 index 0000000..47436cc --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/TASKS_GUIDED.md @@ -0,0 +1,889 @@ +# Guided Tasks — Constraints and Races + +The same eight tasks as [`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md), step by step: the command to +run, the output you should see, why it happens, and the change to make. + +Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`. + +Timings, thread names, ids and which request wins will differ on your machine. The counts and the +`RESULT` line should match. + +**Before you start** + +```bash +cd start +docker compose up -d +``` + +**How you add a constraint in this project.** Open `src/main/resources/schema.sql`. The application +runs that file every time it starts (`./demo`, `./check`, `./mvnw verify`): it drops the tables and +creates them again. So you edit the file, run the command again, and the database has exactly what +the file says. In a real project the same line would go into a Flyway or Liquibase migration. + +--- + +## Task 1: See the Duplicate Signup + +No code in this task. You are collecting evidence. + +### Run it + +`./demo` prints: + +``` +Scenario: signup | requests: 2 | work between check and insert: 100 ms +Every request signs up ana@example.com at the same moment. + + + 0 ms Request 1 -> POST /api/signups ana@example.com + + 0 ms Request 2 -> POST /api/signups ana@example.com + + 425 ms Request 2 <- 201 user #2 created + + 425 ms Request 1 <- 201 user #1 created + +ROWS IN users + id email display_name + -- --------------- ------------ + 1 ana@example.com Ana + 2 ana@example.com Ana + +RESULT: DUPLICATES. 2 rows in users for ana@example.com. +``` + +One email, two accounts. Nothing crashed and no error was logged. Both people got a 201. + +### See the SQL + +```bash +./demo --sql +``` + +``` + [exec-2] select u1_0.id from users u1_0 where u1_0.email=? fetch first ? rows only + [exec-3] select u1_0.id from users u1_0 where u1_0.email=? fetch first ? rows only + [exec-2] insert into users (created_at,display_name,email) values (?,?,?) + [exec-3] insert into users (created_at,display_name,email) values (?,?,?) +``` + +`exec-2` and `exec-3` are the two request threads. + +### What just happened + +| Time | Request 1 | Request 2 | Rows for ana@example.com | +|---|---|---|---| +| 1 | is the email taken? **no** | | 0 | +| 2 | | is the email taken? **no** | 0 | +| 3 | hash the password (100 ms) | hash the password (100 ms) | 0 | +| 4 | insert | | 1 | +| 5 | | insert | 2 | + +Both requests asked before either inserted, so both were told "no". Each answer was true when it +was given. It was out of date by the time it was used. This pattern is called +**check-then-insert**, or check-then-act, and the bug is a **race condition**. + +### Find it in the code + +Open `SignupService.signUp`: + +```java +if (users.existsByEmail(email)) { // CHECK + throw new EmailTakenException(email); +} +work.run("hash the password"); // ...time passes... +return users.save(new User(email, displayName)); // INSERT +``` + +The CHECK and the INSERT are two separate statements, and nothing ties them together. + +### Look inside the database + +```bash +./inspect +``` + +``` +CONSTRAINTS (pg_constraint) + name kind definition + ---------- ----------- ---------------- + users_pkey PRIMARY KEY PRIMARY KEY (id) +... +SAME EMAIL, MORE THAN ONE ROW (compared without case) + email_lowercase rows user_ids stored_as + --------------- ---- -------- -------------------------------- + ana@example.com 2 1, 2 ana@example.com, ana@example.com +``` + +The only rule the database knows about `users` is the primary key. Nobody ever told it that an +email must be unique, so it stored both rows. + +### Make it worse, then try to make it go away + +`./demo --requests 20` prints `RESULT: DUPLICATES. 20 rows in users for ana@example.com.` + +Now run `./demo --work-ms 0` a few times. It still creates duplicates. Without the 100 ms the gap +between the check and the insert is a millisecond or less, and two requests can still land inside +it. A smaller gap makes the bug rarer, not gone. + +**Would `@Transactional` help?** No. A transaction makes your own statements succeed or fail +together. It does not stop a second transaction from running the same check at the same time, and +neither of them can see the other's row before it is committed. `synchronized` does not help +either: production runs more than one instance of the application. The database is the only place +that sees both inserts, so it is the only place that can refuse one. + +### Check + +`./check 1` prints 1 of 1: *"two requests with the same email are both told "this email is free" by +the application's check (this documents the race)"*. That test passes on purpose, now and after +every fix. The application's check will always be able to give two requests the same answer. The +fixes decide what happens next. + +--- + +## Task 2: Fix It With a UNIQUE Constraint and a 409 + +**The idea:** tell the database the rule. Then the second insert fails, whatever the application +believed. + +`./check 2` prints 2 of 6 before you start. + +### Step 1: add the constraint + +In `src/main/resources/schema.sql`, in `create table users`, replace the Task 2 TODO line. Note the +comma that has to go after the `created_at` line: + +```sql + created_at timestamptz not null default now(), + constraint users_email_key unique (email) +``` + +Give it a name. Your Java code is about to look for that name. + +### Look before you go on + +Do not touch the Java yet. Run `./demo`: + +``` + + 411 ms Request 1 <- 201 user #1 created + + 414 ms Request 2 <- 500 (ERROR: duplicate key value violates unique constraint "users_email_key" Detail: Key (email)=(ana@example.com) already exists.) + +Accounts created (201): 1 +Server errors (500): 1 + +RESULT: SERVER ERROR. No duplicates, but 1 request got a 500 instead of a clear answer. +``` + +The data is already correct: one row. One line of SQL fixed the bug. What is left is manners: the +loser got a 500 with a database error in it, for something that is not a server fault. + +### Step 2: find out which constraint was violated + +When the database refuses the row, `users.save` throws Spring's +`DataIntegrityViolationException`. That exception is thrown for **every** kind of constraint, so +"catch it and return 409" is wrong. You need the name. The cause of Spring's exception is +Hibernate's `ConstraintViolationException`, and Hibernate has already read the name out of the +error Postgres sent. + +Create `src/main/java/com/amigoscode/constraints/db/Violations.java`: + +```java +package com.amigoscode.constraints.db; + +import org.hibernate.exception.ConstraintViolationException; +import org.springframework.dao.DataIntegrityViolationException; + +public final class Violations { + + /** True when the constraint the database refused the row for is one of {@code names}. */ + public static boolean isOn(DataIntegrityViolationException e, String... names) { + for (Throwable cause = e; cause != null; cause = cause.getCause()) { + if (cause instanceof ConstraintViolationException violation) { + for (String name : names) { + if (name.equals(violation.getConstraintName())) { + return true; + } + } + } + } + return false; + } + + private Violations() { + } +} +``` + +Careful with the import: it is `org.hibernate.exception.ConstraintViolationException`, not the one +from `jakarta.validation`. + +### Step 3: translate it + +In `SignupService.signUp`, replace the last line (`return users.save(...)`) with: + +```java +try { + return users.save(new User(email, displayName)); // INSERT +} catch (DataIntegrityViolationException e) { + if (Violations.isOn(e, "users_email_key")) { + throw new EmailTakenException(email); + } + throw e; +} +``` + +Imports: `com.amigoscode.constraints.db.Violations` and +`org.springframework.dao.DataIntegrityViolationException`. + +**Leave the `existsByEmail` check where it is.** `ApiExceptionHandler` already maps +`EmailTakenException` to a 409. + +### After + +`./demo`: + +``` + + 411 ms Request 1 <- 201 user #1 created + + 415 ms Request 2 <- 409 EMAIL_TAKEN + +RESULT: OK. 1 row for ana@example.com: 1 created, 1 told the email is taken. +``` + +`./check 2` now prints 6 of 6. + +--- + +## Task 3: Inspect the Constraint + +### Step 1 and 2: the SQL, and what the loser waited for + +```bash +./demo --sql +``` + +``` + [exec-2] select u1_0.id from users u1_0 where u1_0.email=? fetch first ? rows only + [exec-3] select u1_0.id from users u1_0 where u1_0.email=? fetch first ? rows only + [exec-3] insert into users (created_at,display_name,email) values (?,?,?) + [exec-2] insert into users (created_at,display_name,email) values (?,?,?) + [exec-2] HHH000247: ErrorCode: 0, SQLState: 23505 + [exec-2] ERROR: duplicate key value violates unique constraint "users_email_key" + Detail: Key (email)=(ana@example.com) already exists. + + 456 ms Request 2 <- 201 user #2 created + + 460 ms Request 1 <- 409 EMAIL_TAKEN +``` + +The race is still there: two SELECTs, then two INSERTs, exactly as in Task 1. The difference is the +last three lines. The text after `ERROR:` comes from Postgres. Hibernate logs it (`HHH000247`) and +then throws. **23505** is the SQLSTATE for `unique_violation`. + +The loser's INSERT was sent at the same moment as the winner's. Postgres cannot answer it at once: +the winner's row is not committed yet, and the winner might still roll back. So the second INSERT +**waits** until the first transaction ends. If it commits, the second fails. If it rolls back, the +second goes through. + +Hibernate logs that error for every violation, also for the ones your code handles. (The demo +hides it unless you pass `--sql`.) + +### Step 3: constraint and index + +`./inspect`, the `users` part: + +``` +CONSTRAINTS (pg_constraint) + name kind definition + --------------- ----------- ---------------- + users_pkey PRIMARY KEY PRIMARY KEY (id) + users_email_key UNIQUE UNIQUE (email) + +INDEXES (pg_indexes) + name unique definition + --------------- ------ ------------- + users_email_key yes btree (email) + users_pkey yes btree (id) +``` + +One line of SQL, two entries. A UNIQUE constraint is **enforced by a unique index**: to know +whether a value is already there, Postgres has to be able to look it up quickly. So you got an +index on `email` for free, and the `exists` check uses it. + +### Step 4: the missing ids + +`./demo --requests 20`: + +``` +ROWS IN users + id email display_name + -- --------------- ------------ + 3 ana@example.com Ana +``` + +One row, and its id is 3 (yours can be anything from 1 to 20). All 20 requests passed the check, +all 20 took a number from the id sequence, 19 inserts failed. **A sequence does not roll back**, so +the numbers of the failed inserts are gone. Gaps in ids are normal and never a sign of deleted +rows. + +### Step 5: why keep the application check? + +Comment out the `if (users.existsByEmail(email)) { ... }` block and run `./check 2`. It prints 5 of +6. The one that fails is *"a signup that arrives after the first one finished is stopped by the +application's check, before any insert is tried"*. + +The data is still correct: the constraint catches everything. But now **every** duplicate signup, +including the ordinary one that arrives an hour later, hashes a password, tries an insert, fails, +logs an error and burns an id. The check answers that case with one indexed read. + +- The **check** is the fast path: cheap, with a precise message, right almost every time. +- The **constraint** is the guarantee: right every time. + +Put the check back. + +### Step 6: the hole + +`./demo --scenario case`: + +``` + + 0 ms Request 1 -> POST /api/signups Ana@Example.com + + 0 ms Request 2 -> POST /api/signups ana@example.com + + 391 ms Request 2 <- 201 user #1 created + + 391 ms Request 1 <- 201 user #2 created + +RESULT: DUPLICATES. 2 rows in users for the same address. +``` + +`unique (email)` compares the text byte for byte. To the constraint these are two different values. +That is Task 4. + +### What to take away + +- The losing INSERT waits for the winning transaction, then fails with SQLSTATE 23505. +- Spring: `DataIntegrityViolationException`. Hibernate, underneath: `ConstraintViolationException` + with `getConstraintName()`. Match the name, rethrow everything else. +- Adding a UNIQUE constraint to a table that **already** has duplicates fails ("could not create + unique index ... Key ... is duplicated"). You have to clean up first. Add the constraint with the + table, not after the incident. + +--- + +## Task 4: The Same Email in Different Capital Letters + +**The idea:** make the *lower-cased* email unique. A constraint cannot contain a function call. A +unique **index** can. + +### Step 1: add the index + +In `schema.sql`, replace the Task 4 TODO line: + +```sql +create unique index users_email_lower_key on users (lower(email)); +``` + +Run `./demo --scenario case`: + +``` + + 447 ms Request 1 <- 201 user #1 created + + 449 ms Request 2 <- 500 (ERROR: duplicate key value violates unique constraint "users_email_lower_key" Detail: Key (lower(email))=(ana@example.com) already exists.) + +RESULT: SERVER ERROR. No duplicates, but 1 request got a 500 instead of a clear answer. +``` + +Again the data is right and the answer is not. This is the reason for matching by name: the +violation is a new one, `users_email_lower_key`, and `SignupService` rethrows what it does not +know. + +### Step 2: teach the service the second name + +In `SignupService`: + +```java +if (Violations.isOn(e, "users_email_key", "users_email_lower_key")) { +``` + +`./demo --scenario case` now prints `RESULT: OK`, and `./check 4` prints 2 of 3. The one that fails +is *"ANA@EXAMPLE.COM arriving after ana@example.com is stopped by the application's check"*: the +fast path still compares exactly, so it never fires for a different spelling. + +### Step 3: make the check compare the same way as the index + +In `UserRepository`, replace `existsByEmail` with: + +```java +@Query("select count(u) > 0 from User u where lower(u.email) = lower(:email)") +boolean existsByEmailIgnoreCase(@Param("email") String email); +``` + +Imports: `org.springframework.data.jpa.repository.Query` and +`org.springframework.data.repository.query.Param`. In `SignupService`, call +`users.existsByEmailIgnoreCase(email)`. + +**Why write the query by hand?** Spring Data can derive `existsByEmailIgnoreCase` from the method +name. It passes the tests too. But look at the SQL it writes: + +``` +select u1_0.id from users u1_0 where upper(u1_0.email)=upper(?) fetch first ? rows only +``` + +`upper`, not `lower`. An index on `lower(email)` can only be used by a query that says +`lower(email)`. With `upper` Postgres reads the whole table on every signup. With the hand-written +query the SQL is: + +``` +select count(u1_0.id)>0 from users u1_0 where lower(u1_0.email)=lower(?) +``` + +`./check 4` now prints 3 of 3. + +### Inspect + +```bash +./inspect +``` + +``` +INDEXES (pg_indexes) + name unique definition + --------------------- ------ -------------------- + users_email_key yes btree (email) + users_email_lower_key yes btree (lower(email)) + users_pkey yes btree (id) +``` + +The new rule is under INDEXES only: CONSTRAINTS still lists just the primary key and +`users_email_key`. It is not a "constraint" in Postgres's catalogue, but it enforces uniqueness in +exactly the same way, and the error message even calls it a unique constraint. + +`users_email_key` is now **redundant**: any two rows it rejects, the new index rejects too. Every +index costs a little on every insert, so in production you would drop it. This project keeps both +so that you can see them side by side. + +Two other ways to get the same result: the **`citext`** column type (`create extension citext`), +which compares without case, so that a plain `unique (email)` is enough. Or lower-case the email +before saving, which only protects the rows that go through your code and loses the spelling the +user typed. + +--- + +## Task 5: One ACTIVE Subscription per User + +### Before + +`./demo --scenario subscription`: + +``` + + 128 ms Request 1 <- 201 subscription #1 active + + 130 ms Request 2 <- 201 subscription #2 active +... +RESULT: DUPLICATES. User 1 had 2 ACTIVE subscriptions and pays for each of them. +``` + +`SubscriptionService.subscribe` is the same shape as the signup: check, slow work, insert. + +**Why not a plain UNIQUE?** `unique (user_id)` allows one subscription per user for ever: nobody +could come back after cancelling. `unique (user_id, status)` allows one ACTIVE and one CANCELLED: +the second cancellation would fail. The rule is about **some of the rows only**. + +### Step 1: a partial unique index + +In `schema.sql`, replace the Task 5 TODO line: + +```sql +create unique index subscriptions_one_active_per_user on subscriptions (user_id) where status = 'ACTIVE'; +``` + +The `where` makes it a **partial index**: only rows with `status = 'ACTIVE'` are in it. Among those, +`user_id` must be unique. A cancelled row is not in the index, so it cannot collide with anything. + +### Step 2: translate it + +In `SubscriptionService.subscribe`, replace the last line with: + +```java +try { + return subscriptions.save(new Subscription(userId, plan, seats, priceCents)); // INSERT +} catch (DataIntegrityViolationException e) { + if (Violations.isOn(e, "subscriptions_one_active_per_user")) { + throw new AlreadySubscribedException(userId); + } + throw e; +} +``` + +Same two imports as in Task 2. + +### After + +`./demo --scenario subscription`: + +``` + + 286 ms Request 2 <- 201 subscription #1 active + + 289 ms Request 1 <- 409 ALREADY_SUBSCRIBED + +Then, one after another: cancel what is active, and subscribe again. + + POST /api/subscriptions/1/cancel <- 200 subscription #1 cancelled + POST /api/subscriptions <- 201 subscription #3 active + +ROWS IN subscriptions + id user_id plan status + -- ------- ----- --------- + 1 1 PRO CANCELLED + 3 1 BASIC ACTIVE + +RESULT: OK. Never more than one ACTIVE subscription, and cancelled rows may repeat. +``` + +`./check 5` prints 6 of 6. (Id 2 is missing: it was used by the insert that failed.) + +### Inspect + +`./inspect`, the `subscriptions` part: + +``` +INDEXES (pg_indexes) + name unique definition + --------------------------------- ------ ----------------------------------------------- + subscriptions_one_active_per_user yes btree (user_id) WHERE (status = 'ACTIVE'::text) + subscriptions_pkey yes btree (id) +``` + +Now remove ` where status = 'ACTIVE'` from the index and run the demo again: + +``` + POST /api/subscriptions/1/cancel <- 200 subscription #1 cancelled + POST /api/subscriptions <- 409 ALREADY_SUBSCRIBED + +RESULT: TOO STRICT. The user cancelled and could not subscribe again. +``` + +Put the `where` back. A constraint that is too strict is a bug too. + +The same trick solves soft deletes: `unique (email) where deleted_at is null` lets a deleted +account's email be used again. + +--- + +## Task 6: Create If Absent, and the Aborted Transaction + +`user_settings` has `user_id` as its primary key, so the database already refuses a second row for +one user. This task is about the application's side of that refusal. + +### Step 1: the bug + +```bash +./demo --scenario settings --strategy check-first +``` + +``` + + 192 ms Request 1 <- 500 (ERROR: duplicate key value violates unique constraint "user_settings_pkey" Detail: Key (user_id)=(1) already exists.) + + 198 ms Request 2 <- 200 theme=light created=true + +RESULT: SERVER ERROR. 1 request got a 500. The primary key kept the data clean (1 row), the application did not cope with the refusal. +``` + +`SettingsStore.checkThenInsert` is `@Transactional`, and it races all the same. + +### Step 2: the obvious fix, and the trap + +"Just insert, and if it is already there, catch the exception and read the row." That is +`SettingsStore.insertAndCatchInside`: a `try` around the INSERT, and a SELECT in the +`catch (DuplicateKeyException e)` block, all in one `@Transactional` method. Read it, then run it: + +```bash +./demo --scenario settings --strategy catch-inside --sql +``` + +``` + [exec-2] Executing prepared SQL statement [insert into user_settings (user_id) values (?)] + [exec-3] Executing prepared SQL statement [insert into user_settings (user_id) values (?)] + [exec-2] Executing prepared SQL statement [select user_id, theme from user_settings where user_id = ?] + [exec-3] Executing prepared SQL statement [select user_id, theme from user_settings where user_id = ?] + + 115 ms Request 2 <- 500 (ERROR: current transaction is aborted, commands ignored until end of transaction block) + + 117 ms Request 1 <- 200 theme=light created=true + + PUT /api/users/1/settings (again, later) <- 500 (ERROR: current transaction is aborted, commands ignored until end of transaction block) + +RESULT: SERVER ERROR. 2 requests got a 500. ... +``` + +The exception **was** caught. The SELECT in the catch block is what failed. And it is worse than +before: the request that arrives later, with no race at all, fails too. This endpoint now works +exactly once per user. + +**Why.** In Postgres, when a statement fails inside a transaction, the whole transaction is +**aborted**. Every statement after that is refused with *"current transaction is aborted, commands +ignored until end of transaction block"* (SQLSTATE 25P02) until the transaction is rolled back. +Catching the Java exception changes nothing about the state of the transaction in the database. + +**The quiet version.** If the catch block does *not* touch the database and the method simply +returns, there is no error at all. Spring sends COMMIT, Postgres rolls back instead, and everything +the transaction wrote before the failure is gone. `SettingsIT` has a test for it, and it passes: + +``` + [PASS] swallow: a write, then a caught duplicate key, then a normal return: the commit reports nothing and the write is gone (this documents the trap) +``` + +(With JdbcTemplate nothing warns you, as here. When the failed call was a JPA repository method, +Spring notices and the commit throws `UnexpectedRollbackException`. Either way the work is lost: +never carry on in a transaction after a failed statement.) + +### Step 3: the three shapes that work + +**1. Catch it outside the transaction** (`--strategy catch-outside`). `SettingsService` is not +transactional. It calls `store.insertDefaults`, which is one short transaction. When that fails, +the transaction is rolled back and finished before the exception reaches the `catch`, and the read +that follows starts a new one. This is also what you built in Tasks 2 and 5: `SignupService` is +deliberately not `@Transactional`. + +**2. A savepoint** (`--strategy savepoint --sql`): + +``` + [exec-3] Executing SQL statement [savepoint before_insert] + [exec-3] Executing prepared SQL statement [insert into user_settings (user_id) values (?)] + [exec-3] Executing SQL statement [rollback to savepoint before_insert] + + 42 ms Request 1 <- 200 theme=light created=false +``` + +`rollback to savepoint` undoes the failed insert only and makes the transaction usable again. +Running the insert in its own `REQUIRES_NEW` transaction works as well, at the price of a second +database connection for the duration. + +**3. Do not fail at all.** That is the one you write. + +### Step 4: ON CONFLICT DO NOTHING + +In `SettingsStore`, replace the body of `insertOnConflictDoNothing`: + +```java +@Transactional +public Settings insertOnConflictDoNothing(long userId) { + int inserted = jdbc.update( + "insert into user_settings (user_id) values (?) on conflict (user_id) do nothing", userId); + return read(userId, inserted == 1); +} +``` + +`on conflict (user_id) do nothing` means: if a row with this `user_id` is already there, skip the +insert and report success. The check and the insert are one statement, so there is no gap between +them. `jdbc.update` returns the number of rows inserted: **1** means this call created the row, +**0** means it was already there. + +`./demo --scenario settings`: + +``` + + 106 ms Request 1 <- 200 theme=light created=false + + 106 ms Request 2 <- 200 theme=light created=true + PUT /api/users/1/settings (again, later) <- 200 theme=light created=false + +RESULT: OK. 1 row, every request was answered, exactly 1 was told it created the row. +``` + +Two things to know about `DO NOTHING`: + +- It needs a unique constraint or index on the column in the brackets. It is built on the + constraint, it does not replace it. +- `insert ... on conflict do nothing returning *` returns **no row** when the insert was skipped. + That is why the method does a separate SELECT. + +### Step 5: ON CONFLICT DO UPDATE + +"Save the theme, whether or not the row exists" is the other half: an **upsert**. As shipped, +`saveTheme` runs an UPDATE and inserts when it changed 0 rows. Two requests can both change 0 rows +(`./demo --scenario theme`): + +``` + + 211 ms Request 1 <- 200 theme=dark created=true + + 213 ms Request 2 <- 500 (ERROR: duplicate key value violates unique constraint "user_settings_pkey" Detail: Key (user_id)=(1) already exists.) +``` + +Replace the body of `saveTheme`: + +```java +@Transactional +public Settings saveTheme(long userId, String theme) { + return jdbc.queryForObject( + "insert into user_settings (user_id, theme) values (?, ?) " + + "on conflict (user_id) do update set theme = excluded.theme, updated_at = now() " + + "returning user_id, theme, (xmax = 0) as created", + (row, n) -> new Settings(row.getLong("user_id"), row.getString("theme"), row.getBoolean("created")), + userId, theme); +} +``` + +- `excluded` is the row you tried to insert. `set theme = excluded.theme` means "use the new value". +- An upsert affects 1 row whether it inserted or updated, so the row count cannot tell you which. +- `returning (xmax = 0)` can. `xmax` is a hidden column on every Postgres row: it is 0 on a row + that was just inserted, and not 0 on a row this statement updated. + +Now `./demo --scenario theme` answers both with 200, one `created=true` and one `created=false`, +and prints `RESULT: OK`. `./check 6` prints 9 of 9. + +--- + +## Task 7: Bad Data: NOT NULL, CHECK and FOREIGN KEY + +Not every bad row comes from a race. Some come from an application that simply forgot to look. + +### Before + +```bash +./demo --scenario bad-data +``` + +``` + signup without an email <- 201 user #3 created + subscribe with seats = -3 <- 201 subscription #1 active + subscribe, coupon bigger than price <- 201 subscription #2 active + subscribe a user that does not exist <- 201 subscription #3 active + +BAD ROWS IN THE DATABASE + table id problem + ------------- -- -------------------------- + users 3 email is NULL + subscriptions 1 seats = -3 + subscriptions 2 price_cents = -4100 + subscriptions 3 user 999999 does not exist + +RESULT: BAD DATA. 4 of 4 bad requests are now rows in the database. +``` + +The negative price was not even sent by the caller: the service computed `price - coupon` and +stored whatever came out. + +### The change + +Only `schema.sql`. In `users`, make the email mandatory and delete the Task 7 TODO line: + +```sql + email text not null, +``` + +In `subscriptions`, change three lines and delete the Task 7 TODO line: + +```sql + user_id bigint not null constraint subscriptions_user_id_fkey references users (id), + ... + seats int not null constraint subscriptions_seats_check check (seats > 0), + price_cents int not null constraint subscriptions_price_cents_check check (price_cents >= 0), +``` + +| Rule | Tool | Here | +|---|---|---| +| The value must be there | `NOT NULL` | `users.email` | +| The value must make sense on its own | `CHECK` | `seats > 0`, `price_cents >= 0` | +| The value must point at a row that exists | `FOREIGN KEY` | `subscriptions.user_id` references `users (id)` | + +`NOT NULL` on `email` also closes a hole in Task 2: a UNIQUE constraint accepts **any number of +NULLs**, because NULL is never equal to NULL. + +### After + +```bash +./demo --scenario bad-data +``` + +``` + signup without an email <- 500 (ERROR: null value in column "email" of relation "users" violates not-null constraint) + subscribe with seats = -3 <- 500 (ERROR: new row for relation "subscriptions" violates check constraint "subscriptions_seats_check") + subscribe, coupon bigger than price <- 500 (ERROR: new row for relation "subscriptions" violates check constraint "subscriptions_price_cents_check") + subscribe a user that does not exist <- 500 (ERROR: insert or update on table "subscriptions" violates foreign key constraint "subscriptions_user_id_fkey" Detail: Key (user_id)=(999999) is not present in table "users".) + +BAD ROWS IN THE DATABASE + none + +RESULT: OK. The database refused all 4. Nothing bad was stored. +``` + +`./check` should now print 35 passes and no failures. + +### Inspect: four 500s, and the result is OK? + +Yes. A 500 and no row is better than a 201 and a subscription with a negative price. The 500 is +also honest: the application had a hole, and the database covered for it. + +The proper finish is to **add** validation in the application, so that the caller gets a 400 with a +useful message, and to **keep** the constraints. Validation serves the caller in front of you. The +constraint also holds for the endpoint somebody adds next year, the batch job, and the script run +by hand at 2 a.m. The foreign key works in the other direction too: it refuses to delete a user who +still has subscriptions. + +--- + +## Task 8: Inspect Everything and Compare + +### Step 1: read the whole database + +```bash +./demo --scenario subscription +./inspect +``` + +Read all of it. Every line under CONSTRAINTS and INDEXES is a sentence the database will enforce +whoever is writing: 2 on `users` that you added, 4 on `subscriptions`. Name the task and the bug +for each one. (NOT NULL is in the COLUMNS part.) + +### Step 2: which of the two email rules fires? + +`./demo --sql` (same spelling twice) reports `users_email_key`. `./demo --scenario case --sql` +reports `users_email_lower_key`. The service treats both as "email taken", which is why it does not +matter that one of them is redundant. + +### Step 3: what the loser costs + +| Strategy | Statements for a request that finds the row already there | Works? | +|---|---|---| +| check-first | 2 SELECTs (or a failed INSERT when it loses a race) | No: 500 under a race | +| catch-inside | failed INSERT, failed SELECT | No: 500 on every call after the first | +| catch-outside | failed INSERT, rollback, then a SELECT in a new transaction | Yes | +| savepoint | SAVEPOINT, failed INSERT, ROLLBACK TO SAVEPOINT, SELECT | Yes | +| on-conflict | INSERT ... ON CONFLICT DO NOTHING, SELECT | Yes, and nothing fails | + +### Step 4 and 5: where constraints stop + +"At most 3 CANCELLED subscriptions per year" is a rule about a **count over many rows**. No +UNIQUE, CHECK or foreign key can say that: a CHECK only sees the row being written. For rules like +that you serialise the writers yourself, for example by locking the user row first, which is what +[`../07-locking`](../07-locking) is about. + +"An email may be reused after the account is deleted" is the partial index again: + +```sql +create unique index users_email_active_key on users (lower(email)) where deleted_at is null; +``` + +### Which tool for which rule + +| The rule | The tool | Violation (SQLSTATE) | +|---|---|---| +| No two rows with the same value | `UNIQUE` constraint | 23505 | +| The same, on a computed value | unique index on an expression | 23505 | +| The same, for some of the rows only | partial unique index (`WHERE`) | 23505 | +| A value must be present | `NOT NULL` | 23502 | +| A value must make sense on its own | `CHECK` | 23514 | +| A row must point at a row that exists | `FOREIGN KEY` | 23503 | +| Create it unless it is there | `INSERT ... ON CONFLICT DO NOTHING` | none: it does not fail | +| Create it or update it | `INSERT ... ON CONFLICT DO UPDATE` | none: it does not fail | +| A rule over many rows | not a constraint: lock, or one atomic statement | | + +A unique key that the *client* sends, so that a retried request is recognised, is the same +mechanism with a different purpose: see [`../08-idempotency`](../08-idempotency). + +### How to say it in an interview + +> "Checking whether a row exists and then inserting it is two statements, so two requests can both +> pass the check. The application cannot close that gap, because the requests may run on different +> servers. So I put the rule in the database: a unique constraint, or a unique index on +> `lower(email)` if case should not matter, or a partial unique index if the rule only covers some +> rows, like one active subscription per user. I keep the application check as a fast path with a +> good error message, and I translate the constraint violation into a 409 by matching the +> constraint name, never by catching every data integrity exception. In Postgres a failed +> statement aborts the transaction, so I handle the violation outside the transaction, or I use +> `INSERT ... ON CONFLICT` so that nothing fails. And for plain bad data I add NOT NULL, CHECK and +> foreign keys, because validation in the application only protects the code paths that remember +> to call it." + +Then be ready for the follow-ups in "Questions to Ask Afterwards" at the end of +[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md). + +--- + +## Clean up + +```bash +docker compose down +``` diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/.mvn/jvm.config b/java/concepts/junior-mid/10-constraints-and-races/solution/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/.mvn/jvm.config @@ -0,0 +1,2 @@ +--enable-native-access=ALL-UNNAMED +--sun-misc-unsafe-memory-access=allow diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/10-constraints-and-races/solution/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/check b/java/concepts/junior-mid/10-constraints-and-races/solution/check new file mode 100755 index 0000000..f500026 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/check @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use check.cmd (type: .\check). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.constraints.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/check.cmd b/java/concepts/junior-mid/10-constraints-and-races/solution/check.cmd new file mode 100644 index 0000000..6e0ce70 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/check.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./check +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.constraints.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/compose.yaml b/java/concepts/junior-mid/10-constraints-and-races/solution/compose.yaml new file mode 100644 index 0000000..6a41dfb --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/compose.yaml @@ -0,0 +1,16 @@ +name: constraints-and-races +services: + postgres: + image: postgres:17-alpine + container_name: constraints-and-races-postgres + environment: + POSTGRES_DB: app + POSTGRES_USER: app + POSTGRES_PASSWORD: app + ports: + - "5449:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U app -d app"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/demo b/java/concepts/junior-mid/10-constraints-and-races/solution/demo new file mode 100755 index 0000000..15dc754 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/demo @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use demo.cmd (type: .\demo). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.constraints.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/demo.cmd b/java/concepts/junior-mid/10-constraints-and-races/solution/demo.cmd new file mode 100644 index 0000000..cd9c540 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/demo.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./demo +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.constraints.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/inspect b/java/concepts/junior-mid/10-constraints-and-races/solution/inspect new file mode 100755 index 0000000..6dafb52 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/inspect @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use inspect.cmd (type: .\inspect). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.constraints.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/inspect.cmd b/java/concepts/junior-mid/10-constraints-and-races/solution/inspect.cmd new file mode 100644 index 0000000..89de916 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/inspect.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./inspect +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.constraints.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/mvnw b/java/concepts/junior-mid/10-constraints-and-races/solution/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/mvnw.cmd b/java/concepts/junior-mid/10-constraints-and-races/solution/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/pom.xml b/java/concepts/junior-mid/10-constraints-and-races/solution/pom.xml new file mode 100644 index 0000000..99f9343 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + constraints-and-races + 0.0.1-SNAPSHOT + constraints-and-races + Database constraints as the last line of defence against race conditions + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + runtime + + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.mockito + mockito-core + + + org.mockito + mockito-junit-jupiter + + + + + org.springframework.boot + spring-boot-starter-data-jpa-test + test + + + org.testcontainers + testcontainers-postgresql + test + + + org.junit.platform + junit-platform-launcher + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + false + + + + + + diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/ApiExceptionHandler.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/ApiExceptionHandler.java new file mode 100644 index 0000000..e2e7c92 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/ApiExceptionHandler.java @@ -0,0 +1,48 @@ +package com.amigoscode.constraints; + +import com.amigoscode.constraints.settings.Strategy.UnknownStrategyException; +import com.amigoscode.constraints.subscription.AlreadySubscribedException; +import com.amigoscode.constraints.subscription.SubscriptionNotFoundException; +import com.amigoscode.constraints.user.EmailTakenException; +import com.amigoscode.constraints.user.UserNotFoundException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +/** Anything not listed here, including a raw DataIntegrityViolationException, becomes a 500. */ +@RestControllerAdvice +public class ApiExceptionHandler { + + public record ApiError(String code, String message) { + } + + @ExceptionHandler(EmailTakenException.class) + public ResponseEntity emailTaken(EmailTakenException e) { + return error(HttpStatus.CONFLICT, "EMAIL_TAKEN", e); + } + + @ExceptionHandler(AlreadySubscribedException.class) + public ResponseEntity alreadySubscribed(AlreadySubscribedException e) { + return error(HttpStatus.CONFLICT, "ALREADY_SUBSCRIBED", e); + } + + @ExceptionHandler(UserNotFoundException.class) + public ResponseEntity userNotFound(UserNotFoundException e) { + return error(HttpStatus.NOT_FOUND, "USER_NOT_FOUND", e); + } + + @ExceptionHandler(SubscriptionNotFoundException.class) + public ResponseEntity subscriptionNotFound(SubscriptionNotFoundException e) { + return error(HttpStatus.NOT_FOUND, "SUBSCRIPTION_NOT_FOUND", e); + } + + @ExceptionHandler({UnknownStrategyException.class, IllegalArgumentException.class}) + public ResponseEntity badRequest(RuntimeException e) { + return error(HttpStatus.BAD_REQUEST, "BAD_REQUEST", e); + } + + private static ResponseEntity error(HttpStatus status, String code, RuntimeException e) { + return ResponseEntity.status(status).body(new ApiError(code, e.getMessage())); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/ConstraintsApplication.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/ConstraintsApplication.java new file mode 100644 index 0000000..d2919d8 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/ConstraintsApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.constraints; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ConstraintsApplication { + + public static void main(String[] args) { + SpringApplication.run(ConstraintsApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/db/Violations.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/db/Violations.java new file mode 100644 index 0000000..e21c7a6 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/db/Violations.java @@ -0,0 +1,29 @@ +package com.amigoscode.constraints.db; + +import org.hibernate.exception.ConstraintViolationException; +import org.springframework.dao.DataIntegrityViolationException; + +/** + * Answers the question "which constraint did the database say no to?". Spring wraps Hibernate's + * ConstraintViolationException, and Hibernate reads the constraint name from the error Postgres + * sent. + */ +public final class Violations { + + /** True when the constraint the database refused the row for is one of {@code names}. */ + public static boolean isOn(DataIntegrityViolationException e, String... names) { + for (Throwable cause = e; cause != null; cause = cause.getCause()) { + if (cause instanceof ConstraintViolationException violation) { + for (String name : names) { + if (name.equals(violation.getConstraintName())) { + return true; + } + } + } + } + return false; + } + + private Violations() { + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/demo/Db.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/demo/Db.java new file mode 100644 index 0000000..ad7d0d1 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/demo/Db.java @@ -0,0 +1,97 @@ +package com.amigoscode.constraints.demo; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +/** Connection settings and table printing shared by the demo and inspect tools. Same defaults as application.properties. */ +final class Db { + + static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5449/app"); + static final String USER = env("DB_USER", "app"); + static final String PASSWORD = env("DB_PASSWORD", "app"); + + private Db() { + } + + static Connection connect() throws SQLException { + return DriverManager.getConnection(URL, USER, PASSWORD); + } + + /** Returns false, after printing what to do, when Postgres is not reachable. */ + static boolean isUp() { + try (Connection ignored = connect()) { + return true; + } catch (SQLException e) { + System.out.println(); + System.out.println("Cannot reach Postgres at " + URL); + System.out.println("Start it first, from this folder:"); + System.out.println(); + System.out.println(" docker compose up -d"); + System.out.println(); + System.out.println("(" + e.getMessage().lines().findFirst().orElse("") + ")"); + return false; + } + } + + static int count(Connection connection, String sql) throws SQLException { + try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) { + result.next(); + return result.getInt(1); + } + } + + /** Prints a query result as a plain text table and returns the number of rows. NULL is printed as NULL. */ + static int printTable(Connection connection, String sql) throws SQLException { + List rows = new ArrayList<>(); + try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) { + int columns = result.getMetaData().getColumnCount(); + String[] header = new String[columns]; + for (int c = 0; c < columns; c++) { + header[c] = result.getMetaData().getColumnLabel(c + 1); + } + rows.add(header); + while (result.next()) { + String[] row = new String[columns]; + for (int c = 0; c < columns; c++) { + String value = result.getString(c + 1); + row[c] = value == null ? "NULL" : value; + } + rows.add(row); + } + } + if (rows.size() == 1) { + return 0; + } + int[] widths = new int[rows.get(0).length]; + for (String[] row : rows) { + for (int c = 0; c < row.length; c++) { + widths[c] = Math.max(widths[c], row[c].length()); + } + } + for (int r = 0; r < rows.size(); r++) { + StringBuilder line = new StringBuilder(" "); + for (int c = 0; c < widths.length; c++) { + line.append(String.format("%-" + widths[c] + "s", rows.get(r)[c])).append(" "); + } + System.out.println(line.toString().stripTrailing()); + if (r == 0) { + StringBuilder rule = new StringBuilder(" "); + for (int width : widths) { + rule.append("-".repeat(width)).append(" "); + } + System.out.println(rule.toString().stripTrailing()); + } + } + return rows.size() - 1; + } + + private static String env(String name, String fallback) { + String value = System.getenv(name); + return value == null || value.isBlank() ? fallback : value; + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/demo/Demo.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/demo/Demo.java new file mode 100644 index 0000000..f37b145 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/demo/Demo.java @@ -0,0 +1,556 @@ +package com.amigoscode.constraints.demo; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.turbo.TurboFilter; +import ch.qos.logback.core.spi.FilterReply; +import com.amigoscode.constraints.ConstraintsApplication; +import com.amigoscode.constraints.settings.Strategy; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.function.IntFunction; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.slf4j.LoggerFactory; +import org.slf4j.Marker; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * Starts the real application, sends requests at it over HTTP at the same moment, and prints what + * ended up in the database. Run it with ./demo (or .\demo on Windows). ./demo --help lists the flags. + */ +public final class Demo { + + private static final List SCENARIOS = List.of("signup", "case", "subscription", "settings", "theme", "bad-data"); + private static final String[] SPELLINGS = {"Ana@Example.com", "ana@example.com", "ANA@EXAMPLE.COM", "aNa@eXaMpLe.CoM"}; + private static final long MISSING_USER = 999_999; + + private static final Pattern CODE = Pattern.compile("\"code\"\\s*:\\s*\"([A-Z_]+)\""); + private static final Pattern ID = Pattern.compile("\"id\"\\s*:\\s*(\\d+)"); + private static final Pattern CREATED = Pattern.compile("\"created\"\\s*:\\s*(true|false)"); + private static final Pattern THEME = Pattern.compile("\"theme\"\\s*:\\s*\"([^\"]*)\""); + private static final Pattern MESSAGE = Pattern.compile("\"message\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\""); + + private record Options(String scenario, int requests, long workMillis, Strategy strategy, boolean sql) { + } + + private record Call(String label, HttpRequest request) { + } + + private record Outcome(int status, String body) { + + String code() { + return find(CODE, body); + } + + boolean serverError() { + return status >= 500; + } + } + + private static HttpClient http; + private static String baseUrl; + + public static void main(String[] args) throws Exception { + Options options; + try { + options = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println(); + printHelp(); + return; + } + if (options == null) { + printHelp(); + return; + } + if (!Db.isUp()) { + return; + } + + List springArgs = new ArrayList<>(List.of( + "--server.port=0", + "--logging.level.root=WARN", + // A 500 is shown as one line in the timeline instead of a full stack trace. + "--logging.level.org.apache.catalina.core.ContainerBase=OFF", + "--spring.web.error.include-message=always", + "--app.work-millis=" + options.workMillis())); + if (options.sql()) { + springArgs.add("--logging.level.org.hibernate.SQL=DEBUG"); + springArgs.add("--logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG"); + springArgs.add("--logging.pattern.console= %d{HH:mm:ss.SSS} [%replace(%thread){'http-nio-auto-\\d+-',''}] %msg%n"); + } else { + // Hibernate logs every refused statement as an ERROR, also when the application handles it. + springArgs.add("--logging.level.org.hibernate.engine.jdbc.spi.SqlExceptionHelper=OFF"); + springArgs.add("--logging.level.org.hibernate.orm.jdbc.error=OFF"); + } + + SpringApplication app = new SpringApplication(ConstraintsApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + try (ConfigurableApplicationContext context = app.run(springArgs.toArray(String[]::new)); + Connection db = Db.connect()) { + if (options.sql()) { + hideJdbcTemplateNoise(); + } + baseUrl = "http://localhost:" + context.getEnvironment().getProperty("local.server.port"); + http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build(); + + // Fresh state for every run, and one throwaway request so the first caller is not slowed by startup work. + try (Statement statement = db.createStatement()) { + statement.execute("truncate table subscriptions, user_settings, users restart identity cascade"); + } + http.send(HttpRequest.newBuilder(URI.create(baseUrl + "/warm-up")).build(), HttpResponse.BodyHandlers.discarding()); + + System.out.println(); + switch (options.scenario()) { + case "signup" -> signup(options, db, false); + case "case" -> signup(options, db, true); + case "subscription" -> subscription(options, db); + case "settings" -> settings(options, db); + case "theme" -> theme(options, db); + default -> badData(db); + } + System.out.println(); + } + } + + /** + * JdbcTemplate logs two lines per statement: "Executing prepared SQL update" and then the SQL. + * This drops the first of the two, so that --sql prints one line per statement. + */ + private static void hideJdbcTemplateNoise() { + LoggerContext logging = (LoggerContext) LoggerFactory.getILoggerFactory(); + logging.addTurboFilter(new TurboFilter() { + @Override + public FilterReply decide(Marker marker, ch.qos.logback.classic.Logger logger, Level level, + String format, Object[] params, Throwable t) { + boolean noise = format != null && logger.getName().endsWith("JdbcTemplate") + && (format.equals("Executing prepared SQL update") || format.equals("Executing prepared SQL query")); + return noise ? FilterReply.DENY : FilterReply.NEUTRAL; + } + }); + } + + // ---- signup and case: N requests sign up the same email at the same moment ---- + + private static void signup(Options options, Connection db, boolean mixCase) throws Exception { + String email = "ana@example.com"; + System.out.println("Scenario: " + options.scenario() + " | requests: " + options.requests() + + " | work between check and insert: " + options.workMillis() + " ms"); + System.out.println(mixCase + ? "Every request signs up the same address at the same moment, each with different capital letters." + : "Every request signs up " + email + " at the same moment."); + System.out.println(); + + List outcomes = race(options.requests(), i -> { + String spelling = mixCase ? SPELLINGS[i % SPELLINGS.length] : email; + return new Call("POST /api/signups " + spelling, + post("/api/signups", "{\"email\":\"" + spelling + "\",\"displayName\":\"Ana\"}")); + }); + + System.out.println(); + summary("Accounts created (201):", count(outcomes, 201)); + summary("Email taken (409):", count(outcomes, 409)); + printServerErrors(outcomes); + System.out.println(); + System.out.println("ROWS IN users"); + Db.printTable(db, "select id, email, display_name from users order by id"); + System.out.println(); + + int rows = Db.count(db, "select count(*) from users where lower(email) = '" + email + "'"); + if (rows > 1) { + System.out.println("RESULT: DUPLICATES. " + rows + " rows in users for " + (mixCase ? "the same address." : email + ".")); + } else if (serverErrors(outcomes) > 0) { + System.out.println("RESULT: SERVER ERROR. No duplicates, but " + requests(serverErrors(outcomes)) + + " got a 500 instead of a clear answer."); + } else { + System.out.println("RESULT: OK. 1 row for " + email + ": " + count(outcomes, 201) + " created, " + + count(outcomes, 409) + " told the email is taken."); + } + } + + // ---- subscription: N requests subscribe the same user at the same moment ---- + + private static void subscription(Options options, Connection db) throws Exception { + long userId = createUser(db, "sam@example.com"); + System.out.println("Scenario: subscription | requests: " + options.requests() + + " | work between check and insert: " + options.workMillis() + " ms"); + System.out.println("The rule: a user has at most one ACTIVE subscription. Every request subscribes user " + + userId + " at the same moment."); + System.out.println(); + + List outcomes = race(options.requests(), i -> new Call("POST /api/subscriptions", + post("/api/subscriptions", "{\"userId\":" + userId + ",\"plan\":\"pro\"}"))); + int active = Db.count(db, "select count(*) from subscriptions where status = 'ACTIVE' and user_id = " + userId); + + System.out.println(); + summary("Subscribed (201):", count(outcomes, 201)); + summary("Already subscribed (409):", count(outcomes, 409)); + printServerErrors(outcomes); + summary("ACTIVE rows for user " + userId + ":", active); + System.out.println(); + + System.out.println("Then, one after another: cancel what is active, and subscribe again."); + System.out.println(); + List activeIds = new ArrayList<>(); + try (Statement statement = db.createStatement(); + ResultSet result = statement.executeQuery("select id from subscriptions where status = 'ACTIVE' order by id")) { + while (result.next()) { + activeIds.add(result.getLong(1)); + } + } + for (long id : activeIds) { + one("POST /api/subscriptions/" + id + "/cancel", post("/api/subscriptions/" + id + "/cancel", "")); + } + Outcome again = one("POST /api/subscriptions", post("/api/subscriptions", "{\"userId\":" + userId + ",\"plan\":\"basic\"}")); + + System.out.println(); + System.out.println("ROWS IN subscriptions"); + Db.printTable(db, "select id, user_id, plan, status from subscriptions order by id"); + System.out.println(); + + if (active > 1) { + System.out.println("RESULT: DUPLICATES. User " + userId + " had " + active + " ACTIVE subscriptions and pays for each of them."); + } else if (serverErrors(outcomes) > 0) { + System.out.println("RESULT: SERVER ERROR. One ACTIVE subscription, but " + requests(serverErrors(outcomes)) + + " got a 500 instead of a clear answer."); + } else if (again.status() != 201) { + System.out.println("RESULT: TOO STRICT. The user cancelled and could not subscribe again."); + } else { + System.out.println("RESULT: OK. Never more than one ACTIVE subscription, and cancelled rows may repeat."); + } + } + + // ---- settings: N requests ask for the same user's settings for the first time ---- + + private static void settings(Options options, Connection db) throws Exception { + long userId = createUser(db, "lee@example.com"); + String strategy = options.strategy().label(); + System.out.println("Scenario: settings | strategy: " + strategy + " | requests: " + options.requests() + + " | work between check and insert: " + options.workMillis() + " ms"); + System.out.println("User " + userId + " has no settings row yet. Every request asks for the settings at the same moment,"); + System.out.println("then one more request asks again."); + System.out.println(); + + String path = "/api/users/" + userId + "/settings?strategy=" + strategy; + List outcomes = new ArrayList<>(race(options.requests(), i -> new Call("PUT /api/users/" + userId + "/settings", put(path, "")))); + System.out.println(); + outcomes.add(one("PUT /api/users/" + userId + "/settings (again, later)", put(path, ""))); + settingsSummary(outcomes, db, userId); + } + + // ---- theme: N requests save the theme of a user that has no settings row yet ---- + + private static void theme(Options options, Connection db) throws Exception { + long userId = createUser(db, "kim@example.com"); + System.out.println("Scenario: theme | requests: " + options.requests() + + " | work between check and insert: " + options.workMillis() + " ms"); + System.out.println("User " + userId + " has no settings row yet. Every request saves theme=dark at the same moment,"); + System.out.println("then one more request saves theme=blue."); + System.out.println(); + + String path = "/api/users/" + userId + "/settings/theme"; + List outcomes = new ArrayList<>(race(options.requests(), + i -> new Call("PUT " + path + " dark", put(path, "{\"theme\":\"dark\"}")))); + System.out.println(); + outcomes.add(one("PUT " + path + " blue (later)", put(path, "{\"theme\":\"blue\"}"))); + settingsSummary(outcomes, db, userId); + } + + private static void settingsSummary(List outcomes, Connection db, long userId) throws SQLException { + long created = outcomes.stream().filter(o -> "true".equals(find(CREATED, o.body()))).count(); + System.out.println(); + summary("Answered (200):", count(outcomes, 200)); + summary(" of which created the row:", created); + printServerErrors(outcomes); + System.out.println(); + System.out.println("ROWS IN user_settings"); + if (Db.printTable(db, "select user_id, theme from user_settings order by user_id") == 0) { + System.out.println(" none"); + } + System.out.println(); + int rows = Db.count(db, "select count(*) from user_settings where user_id = " + userId); + if (serverErrors(outcomes) > 0) { + System.out.println("RESULT: SERVER ERROR. " + requests(serverErrors(outcomes)) + " got a 500. The primary key kept the data clean (" + + rows + (rows == 1 ? " row" : " rows") + "), the application did not cope with the refusal."); + } else if (created != 1) { + System.out.println("RESULT: WRONG ANSWER. 1 row was created, but " + created + " requests said they created it."); + } else { + System.out.println("RESULT: OK. 1 row, every request was answered, exactly 1 was told it created the row."); + } + } + + // ---- bad-data: four requests, one after another, that the application should never have accepted ---- + + private static void badData(Connection db) throws Exception { + long first = createUser(db, "bo@example.com"); + long second = createUser(db, "cy@example.com"); + System.out.println("Scenario: bad-data"); + System.out.println("Four requests, one after another. The application does not validate any of them."); + System.out.println(); + + List outcomes = new ArrayList<>(); + outcomes.add(one("signup without an email ", post("/api/signups", "{\"displayName\":\"No Email\"}"))); + outcomes.add(one("subscribe with seats = -3 ", + post("/api/subscriptions", "{\"userId\":" + first + ",\"plan\":\"pro\",\"seats\":-3}"))); + outcomes.add(one("subscribe, coupon bigger than price ", + post("/api/subscriptions", "{\"userId\":" + second + ",\"plan\":\"basic\",\"couponCents\":5000}"))); + outcomes.add(one("subscribe a user that does not exist", + post("/api/subscriptions", "{\"userId\":" + MISSING_USER + ",\"plan\":\"pro\"}"))); + + System.out.println(); + summary("Accepted (201):", count(outcomes, 201)); + printServerErrors(outcomes); + System.out.println(); + System.out.println("BAD ROWS IN THE DATABASE"); + int bad = Db.printTable(db, Inspect.BAD_ROWS); + if (bad == 0) { + System.out.println(" none"); + } + System.out.println(); + if (bad > 0) { + System.out.println("RESULT: BAD DATA. " + bad + " of 4 bad requests are now rows in the database."); + } else { + System.out.println("RESULT: OK. The database refused all 4. Nothing bad was stored."); + } + } + + // ---- sending requests ---- + + /** Sends {@code n} requests at the same moment and waits for all the answers. */ + private static List race(int n, IntFunction calls) throws Exception { + boolean timeline = n <= 10; + CountDownLatch go = new CountDownLatch(1); + List> futures = new ArrayList<>(); + long[] startedAt = new long[1]; + try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { + for (int i = 0; i < n; i++) { + Call call = calls.apply(i); + String who = "Request " + (i + 1); + futures.add(executor.submit(() -> { + go.await(); + if (timeline) { + log(startedAt[0], who + " -> " + call.label()); + } + Outcome outcome = send(call.request()); + if (timeline) { + log(startedAt[0], who + " <- " + describe(outcome)); + } + return outcome; + })); + } + startedAt[0] = System.nanoTime(); + go.countDown(); + } + long elapsedMillis = (System.nanoTime() - startedAt[0]) / 1_000_000; + List outcomes = new ArrayList<>(); + for (Future future : futures) { + outcomes.add(future.get()); + } + if (!timeline) { + System.out.println(" " + n + " requests answered in " + elapsedMillis + " ms"); + } + return outcomes; + } + + /** Sends one request and prints it with its answer. */ + private static Outcome one(String label, HttpRequest request) throws Exception { + Outcome outcome = send(request); + System.out.println(" " + label + " <- " + describe(outcome)); + return outcome; + } + + private static Outcome send(HttpRequest request) throws Exception { + HttpResponse response = http.send(request, HttpResponse.BodyHandlers.ofString()); + return new Outcome(response.statusCode(), response.body()); + } + + /** Sets up a user with plain SQL, so that the scenario itself is the only thing in the output. */ + private static long createUser(Connection db, String email) throws SQLException { + try (Statement statement = db.createStatement(); + ResultSet result = statement.executeQuery( + "insert into users (email, display_name) values ('" + email + "', 'Demo') returning id")) { + result.next(); + return result.getLong(1); + } + } + + private static HttpRequest post(String path, String json) { + return HttpRequest.newBuilder(URI.create(baseUrl + path)) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(json)) + .build(); + } + + private static HttpRequest put(String path, String json) { + return HttpRequest.newBuilder(URI.create(baseUrl + path)) + .header("Content-Type", "application/json") + .PUT(HttpRequest.BodyPublishers.ofString(json)) + .build(); + } + + // ---- printing ---- + + private static String describe(Outcome outcome) { + String body = outcome.body(); + if (outcome.code() != null) { + return outcome.status() + " " + outcome.code(); + } + if (outcome.status() == 201 || outcome.status() == 200) { + String created = find(CREATED, body); + if (created != null) { + return outcome.status() + " theme=" + find(THEME, body) + " created=" + created; + } + if (body.contains("\"status\"")) { + return outcome.status() + " subscription #" + find(ID, body) + (body.contains("CANCELLED") ? " cancelled" : " active"); + } + return outcome.status() + " user #" + find(ID, body) + " created"; + } + return outcome.status() + " " + reason(find(MESSAGE, body)); + } + + /** The reason for a 500, cut down to what the database itself said when there is such a part. */ + private static String reason(String message) { + if (message == null || message.isBlank()) { + return ""; + } + String text = message.replace("\\n", " ").replace("\\\"", "\"").replaceAll("\\s+", " "); + int fromDatabase = text.indexOf("ERROR: "); + if (fromDatabase >= 0) { + text = text.substring(fromDatabase); + int end = text.indexOf("] ["); + text = end > 0 ? text.substring(0, end) : text; + text = text.replaceAll(" Detail: Failing row contains.*", ""); + } + return "(" + (text.length() > 200 ? text.substring(0, 200) + "..." : text) + ")"; + } + + private static void summary(String label, long value) { + System.out.printf("%-28s %d%n", label, value); + } + + private static void printServerErrors(List outcomes) { + if (serverErrors(outcomes) > 0) { + summary("Server errors (500):", serverErrors(outcomes)); + } + } + + private static int count(List outcomes, int status) { + return (int) outcomes.stream().filter(outcome -> outcome.status() == status).count(); + } + + private static int serverErrors(List outcomes) { + return (int) outcomes.stream().filter(Outcome::serverError).count(); + } + + private static String requests(int n) { + return n + (n == 1 ? " request" : " requests"); + } + + private static synchronized void log(long startedAtNanos, String message) { + long millis = (System.nanoTime() - startedAtNanos) / 1_000_000; + System.out.printf(" +%5d ms %s%n", millis, message); + } + + private static String find(Pattern pattern, String body) { + Matcher matcher = pattern.matcher(body == null ? "" : body); + return matcher.find() ? matcher.group(1) : null; + } + + // ---- options ---- + + private static Options parse(String[] args) { + String scenario = "signup"; + int requests = 2; + long workMillis = 100; + Strategy strategy = Strategy.ON_CONFLICT; + boolean sql = false; + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "--help", "-h" -> { + return null; + } + case "--scenario" -> { + scenario = value(args, ++i, arg); + if (!SCENARIOS.contains(scenario)) { + throw new IllegalArgumentException("Unknown scenario '" + scenario + "'. Use one of: " + + String.join(", ", SCENARIOS)); + } + } + case "--strategy" -> { + try { + strategy = Strategy.from(value(args, ++i, arg)); + } catch (Strategy.UnknownStrategyException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + case "--requests" -> requests = number(value(args, ++i, arg), arg, 1, 500); + case "--work-ms" -> workMillis = number(value(args, ++i, arg), arg, 0, 120_000); + case "--sql" -> sql = true; + default -> throw new IllegalArgumentException("Unknown option: " + arg); + } + } + return new Options(scenario, requests, workMillis, strategy, sql); + } + + private static String value(String[] args, int index, String option) { + if (index >= args.length) { + throw new IllegalArgumentException(option + " needs a value"); + } + return args[index]; + } + + private static int number(String value, String option, int min, int max) { + try { + int number = Integer.parseInt(value); + if (number < min || number > max) { + throw new NumberFormatException(); + } + return number; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(option + " must be a number from " + min + " to " + max + ", got: " + value); + } + } + + private static void printHelp() { + System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])"); + System.out.println(); + System.out.println(" --scenario what to try (default: signup)"); + System.out.println(" signup the same email signs up twice at the same moment"); + System.out.println(" case the same email, written with different capital letters"); + System.out.println(" subscription one user subscribes twice at the same moment"); + System.out.println(" settings get-or-create of a settings row (see --strategy)"); + System.out.println(" theme create-or-update of a settings row"); + System.out.println(" bad-data four requests the application should have refused"); + System.out.println(" --strategy for --scenario settings: " + Strategy.names() + " (default: on-conflict)"); + System.out.println(" --requests how many requests are sent at the same moment (default: 2)"); + System.out.println(" --work-ms time between the check and the insert (default: 100)"); + System.out.println(" --sql print every SQL statement, with the thread that ran it"); + System.out.println(); + System.out.println("Examples:"); + System.out.println(" ./demo"); + System.out.println(" ./demo --sql"); + System.out.println(" ./demo --scenario subscription --requests 20"); + System.out.println(" ./demo --scenario settings --strategy catch-inside"); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/demo/Inspect.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/demo/Inspect.java new file mode 100644 index 0000000..37ea1c5 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/demo/Inspect.java @@ -0,0 +1,141 @@ +package com.amigoscode.constraints.demo; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; + +/** + * Shows what the database enforces right now and whether the data already breaks a rule: for each + * table its columns, constraints and indexes, then every duplicate group and every bad row. Run it + * with ./inspect (or .\inspect on Windows), usually right after ./demo. + */ +public final class Inspect { + + private static final List TABLES = List.of("users", "subscriptions", "user_settings"); + + private static final String COLUMNS = """ + select column_name as column, + data_type as type, + case is_nullable when 'YES' then 'yes' else 'NOT NULL' end as null_allowed + from information_schema.columns + where table_schema = 'public' and table_name = '%s' + order by ordinal_position + """; + + private static final String CONSTRAINTS = """ + select c.conname as name, + case c.contype when 'p' then 'PRIMARY KEY' when 'u' then 'UNIQUE' when 'c' then 'CHECK' + when 'f' then 'FOREIGN KEY' else c.contype::text end as kind, + pg_get_constraintdef(c.oid) as definition + from pg_constraint c + where c.conrelid = 'public.%s'::regclass + order by case c.contype when 'p' then 1 when 'u' then 2 when 'f' then 3 else 4 end, c.conname + """; + + private static final String INDEXES = """ + select indexname as name, + case when indexdef like 'CREATE UNIQUE%%' then 'yes' else 'no' end as unique, + regexp_replace(indexdef, '^.* USING ', '') as definition + from pg_indexes + where schemaname = 'public' and tablename = '%s' + order by indexname + """; + + public static void main(String[] args) throws Exception { + if (args.length > 0) { + System.out.println("Usage: ./inspect (Windows: .\\inspect)"); + System.out.println(); + System.out.println("Prints the columns, constraints and indexes of every table, then the duplicates"); + System.out.println("and bad rows that are in the data right now. Run ./demo first to have some data."); + return; + } + if (!Db.isUp()) { + return; + } + try (Connection connection = Db.connect()) { + if (Db.count(connection, "select count(*) from pg_tables where schemaname = 'public' and tablename = 'users'") == 0) { + System.out.println(); + System.out.println("The tables do not exist yet. Run ./demo once: it creates them from schema.sql."); + System.out.println(); + return; + } + for (String table : TABLES) { + table(connection, table); + } + data(connection); + } + } + + private static void table(Connection connection, String table) throws SQLException { + System.out.println(); + int rows = Db.count(connection, "select count(*) from " + table); + System.out.println("==== TABLE " + table + " (" + rows + (rows == 1 ? " row" : " rows") + ") ===="); + System.out.println(); + System.out.println("COLUMNS"); + Db.printTable(connection, COLUMNS.formatted(table)); + System.out.println(); + System.out.println("CONSTRAINTS (pg_constraint)"); + if (Db.printTable(connection, CONSTRAINTS.formatted(table)) == 0) { + System.out.println(" none"); + } + System.out.println(); + System.out.println("INDEXES (pg_indexes)"); + if (Db.printTable(connection, INDEXES.formatted(table)) == 0) { + System.out.println(" none"); + } + } + + private static void data(Connection connection) throws SQLException { + System.out.println(); + System.out.println("==== WHAT IS IN THE DATA RIGHT NOW ===="); + + section(connection, "SAME EMAIL, MORE THAN ONE ROW (compared without case)", """ + select lower(email) as email_lowercase, + count(*) as rows, + string_agg(id::text, ', ' order by id) as user_ids, + string_agg(email, ', ' order by id) as stored_as + from users + where email is not null + group by lower(email) + having count(*) > 1 + order by 1 + """); + section(connection, "MORE THAN ONE ACTIVE SUBSCRIPTION FOR ONE USER", """ + select user_id, + count(*) as active_rows, + string_agg(id::text, ', ' order by id) as subscription_ids + from subscriptions + where status = 'ACTIVE' + group by user_id + having count(*) > 1 + order by 1 + """); + section(connection, "BAD ROWS", BAD_ROWS); + System.out.println(); + } + + /** Every row that breaks a rule the solution enforces with NOT NULL, CHECK or FOREIGN KEY. */ + static final String BAD_ROWS = """ + select 'users' as table, id, 'email is NULL' as problem from users where email is null + union all + select 'subscriptions', id, 'seats = ' || seats from subscriptions where seats <= 0 + union all + select 'subscriptions', id, 'price_cents = ' || price_cents from subscriptions where price_cents < 0 + union all + select 'subscriptions', s.id, 'user ' || s.user_id || ' does not exist' + from subscriptions s + where not exists (select 1 from users u where u.id = s.user_id) + order by 1 desc, 2, 3 + """; + + private static void section(Connection connection, String title, String sql) throws SQLException { + System.out.println(); + System.out.println(title); + if (Db.printTable(connection, sql) == 0) { + System.out.println(" none"); + } + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/Settings.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/Settings.java new file mode 100644 index 0000000..841a4f9 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/Settings.java @@ -0,0 +1,5 @@ +package com.amigoscode.constraints.settings; + +/** One row of user_settings. {@code created} is true when this call inserted the row. */ +public record Settings(long userId, String theme, boolean created) { +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/SettingsController.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/SettingsController.java new file mode 100644 index 0000000..0885d30 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/SettingsController.java @@ -0,0 +1,37 @@ +package com.amigoscode.constraints.settings; + +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/users/{userId}/settings") +public class SettingsController { + + public record ThemeRequest(String theme) { + } + + private final SettingsService settingsService; + + public SettingsController(SettingsService settingsService) { + this.settingsService = settingsService; + } + + /** "Make sure this user has a settings row and give it to me." Safe to repeat, so it is a PUT. */ + @PutMapping + public Settings getOrCreate(@PathVariable long userId, + @RequestParam(defaultValue = "on-conflict") String strategy) { + return settingsService.getOrCreate(Strategy.from(strategy), userId); + } + + @PutMapping("/theme") + public Settings saveTheme(@PathVariable long userId, @RequestBody ThemeRequest request) { + if (request.theme() == null || request.theme().isBlank()) { + throw new IllegalArgumentException("theme is required"); + } + return settingsService.saveTheme(userId, request.theme()); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/SettingsService.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/SettingsService.java new file mode 100644 index 0000000..46d3a79 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/SettingsService.java @@ -0,0 +1,55 @@ +package com.amigoscode.constraints.settings; + +import com.amigoscode.constraints.user.UserNotFoundException; +import com.amigoscode.constraints.user.UserRepository; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.stereotype.Service; + +/** Picks the strategy. Deliberately NOT transactional: every SettingsStore method is its own transaction. */ +@Service +public class SettingsService { + + private final SettingsStore store; + private final UserRepository users; + + public SettingsService(SettingsStore store, UserRepository users) { + this.store = store; + this.users = users; + } + + /** Returns the user's settings, creating the row with the defaults the first time it is asked for. */ + public Settings getOrCreate(Strategy strategy, long userId) { + requireUser(userId); + return switch (strategy) { + case CHECK_FIRST -> store.checkThenInsert(userId); + case CATCH_INSIDE -> store.insertAndCatchInside(userId); + case CATCH_OUTSIDE -> insertAndCatchOutside(userId); + case SAVEPOINT -> store.insertWithSavepoint(userId); + case ON_CONFLICT -> store.insertOnConflictDoNothing(userId); + }; + } + + public Settings saveTheme(long userId, String theme) { + requireUser(userId); + return store.saveTheme(userId, theme); + } + + /** + * Correct shape 1: the insert runs in its own transaction. When it fails, that transaction is + * rolled back and finished before the exception arrives here, so the read starts a fresh one. + */ + private Settings insertAndCatchOutside(long userId) { + try { + store.insertDefaults(userId); + return new Settings(userId, store.find(userId).theme(), true); + } catch (DuplicateKeyException e) { + return store.find(userId); + } + } + + private void requireUser(long userId) { + if (!users.existsById(userId)) { + throw new UserNotFoundException(userId); + } + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/SettingsStore.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/SettingsStore.java new file mode 100644 index 0000000..a9965b5 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/SettingsStore.java @@ -0,0 +1,120 @@ +package com.amigoscode.constraints.settings; + +import com.amigoscode.constraints.work.SlowWork; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +/** + * One database transaction per method, plain SQL through JdbcTemplate. user_settings has user_id as + * its primary key, so the database already refuses a second row for the same user. The methods + * differ in what they do about that refusal. + */ +@Repository +public class SettingsStore { + + private static final String INSERT_DEFAULTS = "insert into user_settings (user_id) values (?)"; + + private final JdbcTemplate jdbc; + private final SlowWork work; + + public SettingsStore(JdbcTemplate jdbc, SlowWork work) { + this.jdbc = jdbc; + this.work = work; + } + + /** + * The bug: check, then insert. Kept as it is so you can always compare against it. Two requests + * can both find nothing, and the slower one hits the primary key: a 500. + */ + @Transactional + public Settings checkThenInsert(long userId) { + if (exists(userId)) { // CHECK + return read(userId, false); + } + work.run("load the defaults"); // ...time passes... + jdbc.update(INSERT_DEFAULTS, userId); // INSERT + return read(userId, true); + } + + /** + * The trap. Kept as it is: insert first, catch the duplicate, carry on in the SAME transaction. + * In Postgres a failed statement aborts the whole transaction, so the read in the catch block + * fails with "current transaction is aborted, commands ignored until end of transaction block". + */ + @Transactional + public Settings insertAndCatchInside(long userId) { + try { + jdbc.update(INSERT_DEFAULTS, userId); + return read(userId, true); + } catch (DuplicateKeyException e) { + return read(userId, false); // never works: the transaction is dead + } + } + + /** Correct shape 1, first half: only the insert. SettingsService catches the duplicate OUTSIDE this transaction. */ + @Transactional + public void insertDefaults(long userId) { + jdbc.update(INSERT_DEFAULTS, userId); + } + + /** + * Correct shape 2: a savepoint. ROLLBACK TO SAVEPOINT undoes the failed insert only, and the + * transaction is usable again. + */ + @Transactional + public Settings insertWithSavepoint(long userId) { + jdbc.execute("savepoint before_insert"); + boolean created; + try { + jdbc.update(INSERT_DEFAULTS, userId); + jdbc.execute("release savepoint before_insert"); + created = true; + } catch (DuplicateKeyException e) { + jdbc.execute("rollback to savepoint before_insert"); + created = false; + } + return read(userId, created); + } + + /** + * Correct shape 3: ask the database to skip the insert when the row is there. Nothing fails, so + * nothing aborts. The number of rows inserted (1 or 0) says whether this call created the row. + */ + @Transactional + public Settings insertOnConflictDoNothing(long userId) { + int inserted = jdbc.update( + "insert into user_settings (user_id) values (?) on conflict (user_id) do nothing", userId); + return read(userId, inserted == 1); + } + + /** + * "Set the theme, whether or not the row exists yet": one statement. ON CONFLICT DO UPDATE + * always reports 1 row, so the row count cannot tell an insert from an update. RETURNING + * (xmax = 0) can: xmax is 0 on a row that was freshly inserted. + */ + @Transactional + public Settings saveTheme(long userId, String theme) { + return jdbc.queryForObject( + "insert into user_settings (user_id, theme) values (?, ?) " + + "on conflict (user_id) do update set theme = excluded.theme, updated_at = now() " + + "returning user_id, theme, (xmax = 0) as created", + (row, n) -> new Settings(row.getLong("user_id"), row.getString("theme"), row.getBoolean("created")), + userId, theme); + } + + @Transactional(readOnly = true) + public Settings find(long userId) { + return read(userId, false); + } + + private boolean exists(long userId) { + return jdbc.queryForObject("select count(*) from user_settings where user_id = ?", Integer.class, userId) > 0; + } + + private Settings read(long userId, boolean created) { + return jdbc.queryForObject("select user_id, theme from user_settings where user_id = ?", + (row, n) -> new Settings(row.getLong("user_id"), row.getString("theme"), created), userId); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/Strategy.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/Strategy.java new file mode 100644 index 0000000..856787c --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/settings/Strategy.java @@ -0,0 +1,37 @@ +package com.amigoscode.constraints.settings; + +import java.util.Arrays; +import java.util.Locale; +import java.util.stream.Collectors; + +/** How "give me this user's settings, create them if they do not exist yet" is done. Chosen with ?strategy=. */ +public enum Strategy { + CHECK_FIRST, + CATCH_INSIDE, + CATCH_OUTSIDE, + SAVEPOINT, + ON_CONFLICT; + + public static Strategy from(String value) { + try { + return valueOf(value.trim().toUpperCase(Locale.ROOT).replace('-', '_')); + } catch (IllegalArgumentException | NullPointerException e) { + throw new UnknownStrategyException(value); + } + } + + public String label() { + return name().toLowerCase(Locale.ROOT).replace('_', '-'); + } + + public static String names() { + return Arrays.stream(values()).map(Strategy::label).collect(Collectors.joining(", ")); + } + + public static class UnknownStrategyException extends RuntimeException { + + public UnknownStrategyException(String value) { + super("Unknown strategy '" + value + "'. Use one of: " + names()); + } + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/AlreadySubscribedException.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/AlreadySubscribedException.java new file mode 100644 index 0000000..8d8dc96 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/AlreadySubscribedException.java @@ -0,0 +1,8 @@ +package com.amigoscode.constraints.subscription; + +public class AlreadySubscribedException extends RuntimeException { + + public AlreadySubscribedException(long userId) { + super("User " + userId + " already has an active subscription"); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/Plan.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/Plan.java new file mode 100644 index 0000000..a918dd9 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/Plan.java @@ -0,0 +1,27 @@ +package com.amigoscode.constraints.subscription; + +import java.util.Locale; + +public enum Plan { + BASIC(900), + PRO(2900); + + private final int priceCents; + + Plan(int priceCents) { + this.priceCents = priceCents; + } + + /** Monthly price of one seat, in cents. */ + public int priceCents() { + return priceCents; + } + + public static Plan from(String value) { + try { + return valueOf(value.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException | NullPointerException e) { + throw new IllegalArgumentException("Unknown plan '" + value + "'. Use one of: basic, pro"); + } + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/Status.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/Status.java new file mode 100644 index 0000000..624b6ca --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/Status.java @@ -0,0 +1,6 @@ +package com.amigoscode.constraints.subscription; + +public enum Status { + ACTIVE, + CANCELLED +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/Subscription.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/Subscription.java new file mode 100644 index 0000000..08c84bd --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/Subscription.java @@ -0,0 +1,87 @@ +package com.amigoscode.constraints.subscription; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import java.time.Instant; + +@Entity +@Table(name = "subscriptions") +public class Subscription { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "user_id") + private long userId; + + @Enumerated(EnumType.STRING) + private Plan plan; + + private int seats; + + /** Monthly price of one seat after the coupon, in cents. */ + @Column(name = "price_cents") + private int priceCents; + + @Enumerated(EnumType.STRING) + private Status status; + + @Column(name = "started_at") + private Instant startedAt; + + protected Subscription() { + } + + public Subscription(long userId, Plan plan, int seats, int priceCents) { + this.userId = userId; + this.plan = plan; + this.seats = seats; + this.priceCents = priceCents; + this.status = Status.ACTIVE; + this.startedAt = Instant.now(); + } + + public void cancel() { + this.status = Status.CANCELLED; + } + + public Long getId() { + return id; + } + + public long getUserId() { + return userId; + } + + public Plan getPlan() { + return plan; + } + + public int getSeats() { + return seats; + } + + public int getPriceCents() { + return priceCents; + } + + public Status getStatus() { + return status; + } + + public Instant getStartedAt() { + return startedAt; + } + + @Override + public String toString() { + return "Subscription #" + id + " of user " + userId + " " + status; + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/SubscriptionController.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/SubscriptionController.java new file mode 100644 index 0000000..f019356 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/SubscriptionController.java @@ -0,0 +1,48 @@ +package com.amigoscode.constraints.subscription; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/subscriptions") +public class SubscriptionController { + + /** seats defaults to 1 and couponCents to 0 when they are left out. */ + public record SubscribeRequest(long userId, String plan, Integer seats, Integer couponCents) { + } + + public record SubscriptionResponse(long id, long userId, String plan, int seats, int priceCents, String status) { + + static SubscriptionResponse of(Subscription subscription) { + return new SubscriptionResponse(subscription.getId(), subscription.getUserId(), + subscription.getPlan().name(), subscription.getSeats(), subscription.getPriceCents(), + subscription.getStatus().name()); + } + } + + private final SubscriptionService subscriptionService; + + public SubscriptionController(SubscriptionService subscriptionService) { + this.subscriptionService = subscriptionService; + } + + /** No validation of seats or the coupon, on purpose: Task 7 shows what the database does about it. */ + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public SubscriptionResponse subscribe(@RequestBody SubscribeRequest request) { + int seats = request.seats() == null ? 1 : request.seats(); + int couponCents = request.couponCents() == null ? 0 : request.couponCents(); + return SubscriptionResponse.of( + subscriptionService.subscribe(request.userId(), Plan.from(request.plan()), seats, couponCents)); + } + + @PostMapping("/{id}/cancel") + public SubscriptionResponse cancel(@PathVariable long id) { + return SubscriptionResponse.of(subscriptionService.cancel(id)); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/SubscriptionNotFoundException.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/SubscriptionNotFoundException.java new file mode 100644 index 0000000..b9f772d --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/SubscriptionNotFoundException.java @@ -0,0 +1,8 @@ +package com.amigoscode.constraints.subscription; + +public class SubscriptionNotFoundException extends RuntimeException { + + public SubscriptionNotFoundException(long subscriptionId) { + super("Subscription " + subscriptionId + " does not exist"); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/SubscriptionRepository.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/SubscriptionRepository.java new file mode 100644 index 0000000..9a77639 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/SubscriptionRepository.java @@ -0,0 +1,8 @@ +package com.amigoscode.constraints.subscription; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface SubscriptionRepository extends JpaRepository { + + boolean existsByUserIdAndStatus(long userId, Status status); +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/SubscriptionService.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/SubscriptionService.java new file mode 100644 index 0000000..51fc842 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/subscription/SubscriptionService.java @@ -0,0 +1,46 @@ +package com.amigoscode.constraints.subscription; + +import com.amigoscode.constraints.db.Violations; +import com.amigoscode.constraints.work.SlowWork; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Service; + +/** Deliberately NOT transactional, for the same reason as SignupService. */ +@Service +public class SubscriptionService { + + /** The partial unique index in schema.sql: one row per user, counting only ACTIVE rows. */ + public static final String ONE_ACTIVE_PER_USER = "subscriptions_one_active_per_user"; + + private final SubscriptionRepository subscriptions; + private final SlowWork work; + + public SubscriptionService(SubscriptionRepository subscriptions, SlowWork work) { + this.subscriptions = subscriptions; + this.work = work; + } + + /** The rule: a user has at most one ACTIVE subscription. Cancelled ones are history. */ + public Subscription subscribe(long userId, Plan plan, int seats, int couponCents) { + if (subscriptions.existsByUserIdAndStatus(userId, Status.ACTIVE)) { // CHECK (fast path) + throw new AlreadySubscribedException(userId); + } + work.run("charge the card"); // ...time passes... + int priceCents = plan.priceCents() - couponCents; + try { + return subscriptions.save(new Subscription(userId, plan, seats, priceCents)); // INSERT + } catch (DataIntegrityViolationException e) { + if (Violations.isOn(e, ONE_ACTIVE_PER_USER)) { + throw new AlreadySubscribedException(userId); + } + throw e; + } + } + + public Subscription cancel(long subscriptionId) { + Subscription subscription = subscriptions.findById(subscriptionId) + .orElseThrow(() -> new SubscriptionNotFoundException(subscriptionId)); + subscription.cancel(); + return subscriptions.save(subscription); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/EmailTakenException.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/EmailTakenException.java new file mode 100644 index 0000000..f17b19a --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/EmailTakenException.java @@ -0,0 +1,8 @@ +package com.amigoscode.constraints.user; + +public class EmailTakenException extends RuntimeException { + + public EmailTakenException(String email) { + super("An account with the email " + email + " already exists"); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/SignupController.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/SignupController.java new file mode 100644 index 0000000..024eec0 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/SignupController.java @@ -0,0 +1,33 @@ +package com.amigoscode.constraints.user; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/signups") +public class SignupController { + + public record SignupRequest(String email, String displayName) { + } + + public record SignupResponse(long id, String email) { + } + + private final SignupService signupService; + + public SignupController(SignupService signupService) { + this.signupService = signupService; + } + + /** No validation here, on purpose: Task 7 shows what the database does when the application forgets. */ + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public SignupResponse signUp(@RequestBody SignupRequest request) { + User user = signupService.signUp(request.email(), request.displayName()); + return new SignupResponse(user.getId(), user.getEmail()); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/SignupService.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/SignupService.java new file mode 100644 index 0000000..4bd909d --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/SignupService.java @@ -0,0 +1,45 @@ +package com.amigoscode.constraints.user; + +import com.amigoscode.constraints.db.Violations; +import com.amigoscode.constraints.work.SlowWork; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Service; + +/** + * Deliberately NOT transactional. users.save runs in its own short transaction, so when the + * database refuses the row that transaction is already over by the time the exception is caught + * here. Task 6 shows what goes wrong when you catch it inside the transaction instead. + */ +@Service +public class SignupService { + + /** The names of the two unique rules on users.email, as written in schema.sql. */ + public static final String EMAIL_UNIQUE = "users_email_key"; + public static final String EMAIL_UNIQUE_ANY_CASE = "users_email_lower_key"; + + private final UserRepository users; + private final SlowWork work; + + public SignupService(UserRepository users, SlowWork work) { + this.users = users; + this.work = work; + } + + public User signUp(String email, String displayName) { + // The fast path. It answers almost every duplicate with a cheap read and a clear message. + // It cannot be trusted: two requests can both get "false" here. + if (users.existsByEmailIgnoreCase(email)) { // CHECK + throw new EmailTakenException(email); + } + work.run("hash the password"); // ...time passes... + try { + return users.save(new User(email, displayName)); // INSERT + } catch (DataIntegrityViolationException e) { + // The last line of defence. The database said no: find out which rule it was. + if (Violations.isOn(e, EMAIL_UNIQUE, EMAIL_UNIQUE_ANY_CASE)) { + throw new EmailTakenException(email); + } + throw e; + } + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/User.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/User.java new file mode 100644 index 0000000..58f40af --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/User.java @@ -0,0 +1,57 @@ +package com.amigoscode.constraints.user; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import java.time.Instant; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + /** Stored exactly as the user typed it. */ + private String email; + + @Column(name = "display_name") + private String displayName; + + @Column(name = "created_at") + private Instant createdAt; + + protected User() { + } + + public User(String email, String displayName) { + this.email = email; + this.displayName = displayName; + this.createdAt = Instant.now(); + } + + public Long getId() { + return id; + } + + public String getEmail() { + return email; + } + + public String getDisplayName() { + return displayName; + } + + public Instant getCreatedAt() { + return createdAt; + } + + @Override + public String toString() { + return "User #" + id + " " + email; + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/UserNotFoundException.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/UserNotFoundException.java new file mode 100644 index 0000000..e367fe3 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/UserNotFoundException.java @@ -0,0 +1,8 @@ +package com.amigoscode.constraints.user; + +public class UserNotFoundException extends RuntimeException { + + public UserNotFoundException(long userId) { + super("User " + userId + " does not exist"); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/UserRepository.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/UserRepository.java new file mode 100644 index 0000000..098f82e --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/user/UserRepository.java @@ -0,0 +1,15 @@ +package com.amigoscode.constraints.user; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface UserRepository extends JpaRepository { + + /** + * Written by hand so that the SQL says lower(email), the same expression as the unique index + * users_email_lower_key. A query can only use an expression index when it uses that expression. + */ + @Query("select count(u) > 0 from User u where lower(u.email) = lower(:email)") + boolean existsByEmailIgnoreCase(@Param("email") String email); +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/work/SleepingSlowWork.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/work/SleepingSlowWork.java new file mode 100644 index 0000000..7eaa974 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/work/SleepingSlowWork.java @@ -0,0 +1,27 @@ +package com.amigoscode.constraints.work; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class SleepingSlowWork implements SlowWork { + + private final long millis; + + public SleepingSlowWork(@Value("${app.work-millis:100}") long millis) { + this.millis = millis; + } + + @Override + public void run(String step) { + if (millis <= 0) { + return; + } + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while: " + step, e); + } + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/work/SlowWork.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/work/SlowWork.java new file mode 100644 index 0000000..f4a2cb0 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/java/com/amigoscode/constraints/work/SlowWork.java @@ -0,0 +1,11 @@ +package com.amigoscode.constraints.work; + +/** + * Stands in for the work a real application does between checking and inserting: hashing the + * password, charging the card, loading the defaults. It takes time, and that time is the window in + * which a second request can run the same check and get the same answer. + */ +public interface SlowWork { + + void run(String step); +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/resources/application.properties b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/resources/application.properties new file mode 100644 index 0000000..9df847f --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/resources/application.properties @@ -0,0 +1,20 @@ +spring.application.name=constraints-and-races + +# Postgres from compose.yaml. Port 5449 so it does not clash with a Postgres you already run. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5449/app} +spring.datasource.username=${DB_USER:app} +spring.datasource.password=${DB_PASSWORD:app} + +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false + +# schema.sql is run on every start. It drops the tables and creates them again, so the database +# always has exactly the constraints that are written in that file. +spring.sql.init.mode=always + +# How long the work between a check and an insert takes, in milliseconds (hashing the password, +# charging the card). +app.work-millis=100 + +# Uncomment to see every SQL statement (or run ./demo --sql). +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/resources/schema.sql b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/resources/schema.sql new file mode 100644 index 0000000..6a231bf --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/main/resources/schema.sql @@ -0,0 +1,42 @@ +-- This file is run every time the application starts (./demo, ./check, ./mvnw verify). +-- It drops the tables and creates them again, so the database always has exactly the +-- constraints written here. To add a constraint: edit this file and run the command again. + +drop table if exists subscriptions, user_settings, users cascade; + +create table users ( + id bigserial primary key, + -- NOT NULL: a UNIQUE rule lets any number of rows have NULL in the column. + email text not null, + display_name text, + created_at timestamptz not null default now(), + -- Two rows may not have the same email. The name is what the application looks for. + constraint users_email_key unique (email) +); + +-- Ana@Example.com and ana@example.com are the same address. A UNIQUE constraint compares the +-- text as it is, so this rule needs a unique INDEX on an expression. +-- (It makes users_email_key above redundant. It is kept so that ./inspect shows both.) +create unique index users_email_lower_key on users (lower(email)); + +create table subscriptions ( + id bigserial primary key, + -- FOREIGN KEY: no subscription for a user that does not exist. + user_id bigint not null constraint subscriptions_user_id_fkey references users (id), + plan text not null, + -- CHECK: the values the application must never store. + seats int not null constraint subscriptions_seats_check check (seats > 0), + price_cents int not null constraint subscriptions_price_cents_check check (price_cents >= 0), + status text not null constraint subscriptions_status_check check (status in ('ACTIVE', 'CANCELLED')), + started_at timestamptz not null default now() +); + +-- One ACTIVE subscription per user. The WHERE makes it a partial index: only ACTIVE rows are +-- in it, so a user can have any number of CANCELLED rows. +create unique index subscriptions_one_active_per_user on subscriptions (user_id) where status = 'ACTIVE'; + +create table user_settings ( + user_id bigint primary key references users (id), + theme text not null default 'light', + updated_at timestamptz not null default now() +); diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/ApiContractTest.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/ApiContractTest.java new file mode 100644 index 0000000..0e9ca02 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/ApiContractTest.java @@ -0,0 +1,140 @@ +package com.amigoscode.constraints; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.amigoscode.constraints.settings.Settings; +import com.amigoscode.constraints.settings.SettingsController; +import com.amigoscode.constraints.settings.SettingsService; +import com.amigoscode.constraints.settings.Strategy; +import com.amigoscode.constraints.subscription.AlreadySubscribedException; +import com.amigoscode.constraints.subscription.Plan; +import com.amigoscode.constraints.subscription.Subscription; +import com.amigoscode.constraints.subscription.SubscriptionController; +import com.amigoscode.constraints.subscription.SubscriptionService; +import com.amigoscode.constraints.user.EmailTakenException; +import com.amigoscode.constraints.user.SignupController; +import com.amigoscode.constraints.user.SignupService; +import com.amigoscode.constraints.user.User; +import com.amigoscode.constraints.user.UserNotFoundException; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +/** + * Unit tests for the HTTP contract: no Spring context, no database, the services are stubs. They + * pass from the start and must keep passing: whatever you change in the services, a request that + * loses a race must get a clear 409, never a 500. + */ +@Tag("baseline") +class ApiContractTest { + + private static final String SIGNUP = "{\"email\":\"ana@example.com\",\"displayName\":\"Ana\"}"; + private static final String SUBSCRIBE = "{\"userId\":7,\"plan\":\"pro\"}"; + + @Test + @DisplayName("HTTP: a signup returns 201 with the user id and the email") + void signupReturnsCreated() throws Exception { + User user = new User("ana@example.com", "Ana"); + ReflectionTestUtils.setField(user, "id", 42L); + + signups(() -> user).perform(post("/api/signups").contentType(MediaType.APPLICATION_JSON).content(SIGNUP)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id").value(42)) + .andExpect(jsonPath("$.email").value("ana@example.com")); + } + + @Test + @DisplayName("HTTP: an email that is taken returns 409 EMAIL_TAKEN") + void emailTakenReturnsConflict() throws Exception { + signups(() -> { + throw new EmailTakenException("ana@example.com"); + }).perform(post("/api/signups").contentType(MediaType.APPLICATION_JSON).content(SIGNUP)) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.code").value("EMAIL_TAKEN")); + } + + @Test + @DisplayName("HTTP: a subscription returns 201 with its id, plan and status") + void subscriptionReturnsCreated() throws Exception { + Subscription subscription = new Subscription(7, Plan.PRO, 1, 2900); + ReflectionTestUtils.setField(subscription, "id", 5L); + + subscriptions(() -> subscription).perform(post("/api/subscriptions").contentType(MediaType.APPLICATION_JSON).content(SUBSCRIBE)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id").value(5)) + .andExpect(jsonPath("$.plan").value("PRO")) + .andExpect(jsonPath("$.status").value("ACTIVE")); + } + + @Test + @DisplayName("HTTP: a second active subscription returns 409 ALREADY_SUBSCRIBED") + void alreadySubscribedReturnsConflict() throws Exception { + subscriptions(() -> { + throw new AlreadySubscribedException(7); + }).perform(post("/api/subscriptions").contentType(MediaType.APPLICATION_JSON).content(SUBSCRIBE)) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.code").value("ALREADY_SUBSCRIBED")); + } + + @Test + @DisplayName("HTTP: settings of an unknown user return 404 USER_NOT_FOUND") + void unknownUserReturnsNotFound() throws Exception { + settings(() -> { + throw new UserNotFoundException(7); + }).perform(put("/api/users/7/settings")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.code").value("USER_NOT_FOUND")); + } + + @Test + @DisplayName("HTTP: an unknown settings strategy returns 400") + void unknownStrategyReturnsBadRequest() throws Exception { + settings(() -> new Settings(7, "light", true)).perform(put("/api/users/7/settings?strategy=hope")) + .andExpect(status().isBadRequest()); + } + + /** Each controller wired to a service that does whatever the test says. */ + private static MockMvc signups(Supplier signUp) { + SignupService stub = new SignupService(null, null) { + @Override + public User signUp(String email, String displayName) { + return signUp.get(); + } + }; + return api(new SignupController(stub)); + } + + private static MockMvc subscriptions(Supplier subscribe) { + SubscriptionService stub = new SubscriptionService(null, null) { + @Override + public Subscription subscribe(long userId, Plan plan, int seats, int couponCents) { + return subscribe.get(); + } + }; + return api(new SubscriptionController(stub)); + } + + private static MockMvc settings(Supplier getOrCreate) { + SettingsService stub = new SettingsService(null, null) { + @Override + public Settings getOrCreate(Strategy strategy, long userId) { + return getOrCreate.get(); + } + }; + return api(new SettingsController(stub)); + } + + private static MockMvc api(Object controller) { + return MockMvcBuilders.standaloneSetup(controller) + .setControllerAdvice(new ApiExceptionHandler()) + .build(); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/BadDataIT.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/BadDataIT.java new file mode 100644 index 0000000..70152e9 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/BadDataIT.java @@ -0,0 +1,76 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.amigoscode.constraints.subscription.Plan; +import com.amigoscode.constraints.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataIntegrityViolationException; + +/** + * Task 7. The application validates none of this, and it stays that way: these tests are about the + * database. Each one tries the bad row twice, with plain SQL and through the service. + */ +@Tag("task7") +class BadDataIT extends IntegrationTest { + + private static final long MISSING_USER = 999_999; + private static final String INSERT_SUBSCRIPTION = + "insert into subscriptions (user_id, plan, seats, price_cents, status) values (?, 'PRO', ?, ?, 'CANCELLED')"; + + @Test + @DisplayName("NOT NULL: a user without an email is refused by the database, and a signup without one stores nothing") + void aUserNeedsAnEmail() { + assertThatThrownBy(() -> jdbc.update("insert into users (email, display_name) values (null, 'No Email')")) + .as("a plain SQL insert with email = NULL") + .isInstanceOf(DataIntegrityViolationException.class); + + catchThrowable(() -> signupService.signUp(null, "No Email")); + + assertThat(userRows()).as("rows in users").isEqualTo(0); + } + + @Test + @DisplayName("CHECK: a subscription with -3 seats is refused by the database, and subscribing with -3 seats stores nothing") + void seatsMustBePositive() { + long user = insertUser("bo@example.com"); + + assertThatThrownBy(() -> jdbc.update(INSERT_SUBSCRIPTION, user, -3, 2900)) + .as("a plain SQL insert with seats = -3") + .isInstanceOf(DataIntegrityViolationException.class); + + catchThrowable(() -> subscriptionService.subscribe(user, Plan.PRO, -3, 0)); + + assertThat(subscriptionRows()).as("rows in subscriptions").isEqualTo(0); + } + + @Test + @DisplayName("CHECK: a negative price is refused by the database, and a coupon bigger than the price stores nothing") + void thePriceMustNotBeNegative() { + long user = insertUser("cy@example.com"); + + assertThatThrownBy(() -> jdbc.update(INSERT_SUBSCRIPTION, user, 1, -4100)) + .as("a plain SQL insert with price_cents = -4100") + .isInstanceOf(DataIntegrityViolationException.class); + + catchThrowable(() -> subscriptionService.subscribe(user, Plan.BASIC, 1, 5000)); + + assertThat(subscriptionRows()).as("rows in subscriptions").isEqualTo(0); + } + + @Test + @DisplayName("FOREIGN KEY: a subscription for a user that does not exist is refused by the database, and subscribing one stores nothing") + void aSubscriptionNeedsAUser() { + assertThatThrownBy(() -> jdbc.update(INSERT_SUBSCRIPTION, MISSING_USER, 1, 2900)) + .as("a plain SQL insert with a user_id that is not in users") + .isInstanceOf(DataIntegrityViolationException.class); + + catchThrowable(() -> subscriptionService.subscribe(MISSING_USER, Plan.PRO, 1, 0)); + + assertThat(subscriptionRows()).as("rows in subscriptions").isEqualTo(0); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/CaseInsensitiveEmailIT.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/CaseInsensitiveEmailIT.java new file mode 100644 index 0000000..052d4a6 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/CaseInsensitiveEmailIT.java @@ -0,0 +1,56 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.constraints.support.IntegrationTest; +import com.amigoscode.constraints.support.Race; +import com.amigoscode.constraints.user.EmailTakenException; +import com.amigoscode.constraints.user.User; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DuplicateKeyException; + +@Tag("task4") +class CaseInsensitiveEmailIT extends IntegrationTest { + + @Test + @DisplayName("Case: the database refuses ana@example.com when Ana@Example.com is already there, even from code that skips the service") + void theDatabaseRefusesTheSameEmailInAnotherCase() { + insertUser("Ana@Example.com"); + + assertThatThrownBy(() -> insertUser("ana@example.com")) + .as("a plain SQL insert of the same address in lower case") + .isInstanceOf(DuplicateKeyException.class); + assertThat(userRows()).as("rows in users").isEqualTo(1); + } + + @Test + @DisplayName("Case: Ana@Example.com and ana@example.com sign up at the same moment: one account, the other is told the email is taken") + void onlyOneOfTwoSpellingsCreatesAnAccount() { + List spellings = List.of("Ana@Example.com", "ana@example.com"); + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.Result result = Race.run(2, i -> () -> signupService.signUp(spellings.get(i), "Ana")); + + assertThat(result.failedWithAnythingBut(EmailTakenException.class)).as("errors that would be a 500").isEmpty(); + assertThat(result.succeeded()).as("accounts created").hasSize(1); + assertThat(result.failedWith(EmailTakenException.class)).as("requests told the email is taken").isEqualTo(1); + assertThat(userRows()).as("rows in users").isEqualTo(1); + } + + @Test + @DisplayName("Case: ANA@EXAMPLE.COM arriving after ana@example.com is stopped by the application's check, before any insert is tried") + void aLaterSignupInAnotherCaseIsStoppedByTheFastPath() { + signupService.signUp("ana@example.com", "Ana"); + + assertThatThrownBy(() -> signupService.signUp("ANA@EXAMPLE.COM", "Ana again")) + .isInstanceOf(EmailTakenException.class); + + assertThat(work.arrivals()) + .as("signups that got past the email check (the second one must not)") + .isEqualTo(1); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/Check.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/Check.java new file mode 100644 index 0000000..631c6b6 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/Check.java @@ -0,0 +1,115 @@ +package com.amigoscode.constraints; + +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage; + +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.platform.engine.TestExecutionResult; +import org.junit.platform.engine.discovery.ClassNameFilter; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +import org.junit.platform.launcher.TagFilter; +import org.junit.platform.launcher.TestExecutionListener; +import org.junit.platform.launcher.TestIdentifier; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; + +/** + * Runs the tests that belong to one task and prints one line per acceptance criterion. + * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2 + * (./mvnw verify runs the same tests the usual Maven way.) + */ +public final class Check { + + /** Tasks that have tests. Tasks 3 and 8 are inspection tasks: you answer questions, no code. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: the HTTP contract (passes from the start, must stay green)"); + TASKS.put("1", "Task 1: See the duplicate signup"); + TASKS.put("2", "Task 2: Fix it with a UNIQUE constraint and a 409"); + TASKS.put("4", "Task 4: The same email in different capital letters"); + TASKS.put("5", "Task 5: One ACTIVE subscription per user"); + TASKS.put("6", "Task 6: Create if absent, and the aborted transaction"); + TASKS.put("7", "Task 7: Bad data: NOT NULL, CHECK and FOREIGN KEY"); + } + + public static void main(String[] args) { + if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-8]"))) { + System.out.println("Usage: ./check [task] task is a number from 1 to 8. No number checks everything."); + System.exit(2); + } + if (args.length == 1 && !TASKS.containsKey(args[0])) { + System.out.println(); + System.out.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:"); + System.out.println("follow its steps in INTERVIEW_TASKS.md and answer the questions."); + System.out.println(); + return; + } + + boolean allGreen = true; + Launcher launcher = LauncherFactory.create(); + for (Map.Entry task : TASKS.entrySet()) { + if (args.length == 1 && !task.getKey().equals(args[0])) { + continue; + } + String tag = task.getKey().equals("baseline") ? "baseline" : "task" + task.getKey(); + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() + .selectors(selectPackage(Check.class.getPackageName())) + .filters(ClassNameFilter.includeClassNamePatterns(".*"), TagFilter.includeTags(tag)) + .build(); + System.out.println(); + System.out.println(task.getValue()); + Results results = new Results(); + launcher.execute(request, results); + System.out.println(" " + results.passed + " of " + results.total + " pass"); + allGreen &= results.passed == results.total && results.total > 0; + } + System.out.println(); + System.exit(allGreen ? 0 : 1); + } + + private static final class Results implements TestExecutionListener { + + private int total; + private int passed; + + @Override + public void executionFinished(TestIdentifier test, TestExecutionResult result) { + boolean ok = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL; + if (!test.isTest()) { + // A container that fails (for example the Spring context cannot start) takes its tests with it. + if (!ok) { + total++; + System.out.println(" [FAIL] " + test.getDisplayName() + " could not start"); + result.getThrowable().ifPresent(Results::printReason); + } + return; + } + total++; + if (ok) { + passed++; + System.out.println(" [PASS] " + test.getDisplayName()); + } else { + System.out.println(" [FAIL] " + test.getDisplayName()); + result.getThrowable().ifPresent(Results::printReason); + } + } + + private static void printReason(Throwable throwable) { + Throwable root = throwable; + while (root.getCause() != null && root.getCause() != root && root.getMessage() == null) { + root = root.getCause(); + } + String message = root.getMessage() == null ? root.getClass().getSimpleName() : root.getMessage(); + message.strip().lines() + .map(String::strip) + .filter(line -> !line.isEmpty() && !line.startsWith("at ") && !line.startsWith("...(")) + .limit(6) + .forEach(line -> System.out.println(" " + line)); + } + } + + private Check() { + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/OneActiveSubscriptionIT.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/OneActiveSubscriptionIT.java new file mode 100644 index 0000000..cf0846e --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/OneActiveSubscriptionIT.java @@ -0,0 +1,72 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.constraints.subscription.AlreadySubscribedException; +import com.amigoscode.constraints.subscription.Plan; +import com.amigoscode.constraints.subscription.Subscription; +import com.amigoscode.constraints.support.IntegrationTest; +import com.amigoscode.constraints.support.Race; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DuplicateKeyException; + +@Tag("task5") +class OneActiveSubscriptionIT extends IntegrationTest { + + private static final String INSERT_ACTIVE = + "insert into subscriptions (user_id, plan, seats, price_cents, status) values (?, 'PRO', 1, 2900, 'ACTIVE')"; + + @Test + @DisplayName("Partial: the database refuses a second ACTIVE subscription for the same user, even from code that skips the service") + void theDatabaseRefusesASecondActiveRow() { + long user = insertUser("sam@example.com"); + jdbc.update(INSERT_ACTIVE, user); + + assertThatThrownBy(() -> jdbc.update(INSERT_ACTIVE, user)) + .as("a plain SQL insert of a second ACTIVE row") + .isInstanceOf(DuplicateKeyException.class); + assertThat(subscriptionRows(user, "ACTIVE")).as("ACTIVE rows").isEqualTo(1); + } + + @Test + @DisplayName("Partial: one user subscribes twice at the same moment: one ACTIVE subscription, the other request is told the user is already subscribed") + void onlyOneOfTwoRequestsSubscribes() { + long user = insertUser("sam@example.com"); + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.Result result = Race.run(2, () -> subscriptionService.subscribe(user, Plan.PRO, 1, 0)); + + assertThat(result.failedWithAnythingBut(AlreadySubscribedException.class)).as("errors that would be a 500").isEmpty(); + assertThat(result.succeeded()).as("subscriptions started").hasSize(1); + assertThat(result.failedWith(AlreadySubscribedException.class)).as("requests told already subscribed").isEqualTo(1); + assertThat(subscriptionRows(user, "ACTIVE")).as("ACTIVE rows").isEqualTo(1); + } + + @Test + @DisplayName("Partial: cancelled subscriptions may repeat: subscribe, cancel, subscribe, cancel, subscribe leaves 2 CANCELLED rows and 1 ACTIVE row") + void cancelledRowsMayRepeat() { + long user = insertUser("sam@example.com"); + + subscriptionService.cancel(subscriptionService.subscribe(user, Plan.BASIC, 1, 0).getId()); + subscriptionService.cancel(subscriptionService.subscribe(user, Plan.PRO, 1, 0).getId()); + subscriptionService.subscribe(user, Plan.PRO, 1, 0); + + assertThat(subscriptionRows(user, "CANCELLED")).as("CANCELLED rows").isEqualTo(2); + assertThat(subscriptionRows(user, "ACTIVE")).as("ACTIVE rows").isEqualTo(1); + } + + @Test + @DisplayName("Partial: the rule is per user: two different users are both ACTIVE at the same time") + void twoUsersCanBothBeActive() { + long sam = insertUser("sam@example.com"); + long lee = insertUser("lee@example.com"); + + subscriptionService.subscribe(sam, Plan.PRO, 1, 0); + subscriptionService.subscribe(lee, Plan.PRO, 1, 0); + + assertThat(subscriptionRows(sam, "ACTIVE") + subscriptionRows(lee, "ACTIVE")).as("ACTIVE rows").isEqualTo(2); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/SettingsIT.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/SettingsIT.java new file mode 100644 index 0000000..f694c6f --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/SettingsIT.java @@ -0,0 +1,146 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.constraints.settings.Settings; +import com.amigoscode.constraints.settings.Strategy; +import com.amigoscode.constraints.support.IntegrationTest; +import com.amigoscode.constraints.support.Race; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Task 6. user_settings has user_id as its primary key, so there can never be two rows for one + * user. These tests are about what the application does when the database says no. The first + * three pass on purpose, before and after your fix: they document the bug and the trap. + */ +@Tag("task6") +class SettingsIT extends IntegrationTest { + + @Autowired + private PlatformTransactionManager transactionManager; + + @Test + @DisplayName("check-first: two first requests at the same moment: one of them fails on the primary key (this documents the bug)") + void checkFirstFailsUnderARace() { + long user = insertUser("lee@example.com"); + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.Result result = Race.run(2, () -> settingsService.getOrCreate(Strategy.CHECK_FIRST, user)); + + assertThat(result.succeeded()).as("requests that got the settings").hasSize(1); + assertThat(result.failedWith(DuplicateKeyException.class)).as("requests that hit the primary key").isEqualTo(1); + assertThat(settingsRows(user)).as("rows in user_settings").isEqualTo(1); + } + + @Test + @DisplayName("catch-inside: after a duplicate key is caught inside the transaction, the next statement fails: \"current transaction is aborted\" (this documents the trap)") + void catchingInsideTheTransactionDoesNotHelp() { + long user = insertUser("lee@example.com"); + settingsService.getOrCreate(Strategy.CATCH_INSIDE, user); + + assertThatThrownBy(() -> settingsService.getOrCreate(Strategy.CATCH_INSIDE, user)) + .as("the second call: the insert fails, the catch block reads the row") + .hasMessageContaining("current transaction is aborted, commands ignored until end of transaction block"); + } + + @Test + @DisplayName("swallow: a write, then a caught duplicate key, then a normal return: the commit reports nothing and the write is gone (this documents the trap)") + void swallowingInsideTheTransactionLosesEarlierWrites() { + long user = insertUser("lee@example.com"); + jdbc.update("insert into user_settings (user_id) values (?)", user); + + new TransactionTemplate(transactionManager).executeWithoutResult(transaction -> { + jdbc.update("update user_settings set theme = 'dark' where user_id = ?", user); // this worked + try { + jdbc.update("insert into user_settings (user_id) values (?)", user); // this is refused + } catch (DuplicateKeyException e) { + // swallowed. Nothing else touches the database, and the method returns normally. + } + }); + + assertThat(jdbc.queryForObject("select theme from user_settings where user_id = ?", String.class, user)) + .as("theme after a transaction that returned without any exception") + .isEqualTo("light"); + } + + @Test + @DisplayName("catch-outside: the duplicate key is caught after the transaction has ended: the second request gets the existing row") + void catchingOutsideTheTransactionWorks() { + long user = insertUser("lee@example.com"); + + assertThat(settingsService.getOrCreate(Strategy.CATCH_OUTSIDE, user).created()).as("first call created the row").isTrue(); + assertThat(settingsService.getOrCreate(Strategy.CATCH_OUTSIDE, user).created()).as("second call created the row").isFalse(); + assertThat(settingsRows(user)).as("rows in user_settings").isEqualTo(1); + } + + @Test + @DisplayName("savepoint: rolling back to a savepoint keeps the transaction alive: the second request gets the existing row") + void aSavepointKeepsTheTransactionAlive() { + long user = insertUser("lee@example.com"); + + assertThat(settingsService.getOrCreate(Strategy.SAVEPOINT, user).created()).as("first call created the row").isTrue(); + assertThat(settingsService.getOrCreate(Strategy.SAVEPOINT, user).created()).as("second call created the row").isFalse(); + assertThat(settingsRows(user)).as("rows in user_settings").isEqualTo(1); + } + + @Test + @DisplayName("on-conflict: two first requests at the same moment: both get the settings, one row, exactly one is told it created the row") + void onConflictDoNothingSurvivesARace() { + long user = insertUser("lee@example.com"); + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.Result result = Race.run(2, () -> settingsService.getOrCreate(Strategy.ON_CONFLICT, user)); + + assertThat(result.failed()).as("errors that would be a 500").isEmpty(); + assertThat(result.succeeded()).as("requests that got the settings").hasSize(2); + assertThat(result.succeeded().stream().filter(Settings::created).count()).as("requests told they created the row").isEqualTo(1); + assertThat(settingsRows(user)).as("rows in user_settings").isEqualTo(1); + } + + @Test + @DisplayName("on-conflict: an existing row is left alone: a saved theme is not reset to the default") + void onConflictDoNothingDoesNotOverwrite() { + long user = insertUser("lee@example.com"); + jdbc.update("insert into user_settings (user_id, theme) values (?, 'dark')", user); + + Settings settings = settingsService.getOrCreate(Strategy.ON_CONFLICT, user); + + assertThat(settings.theme()).as("theme").isEqualTo("dark"); + assertThat(settings.created()).as("created").isFalse(); + } + + @Test + @DisplayName("save theme: two saves at the same moment for a user without a row: both succeed, one row, exactly one is told it created the row") + void saveThemeSurvivesARace() { + long user = insertUser("kim@example.com"); + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.Result result = Race.run(2, () -> settingsService.saveTheme(user, "dark")); + + assertThat(result.failed()).as("errors that would be a 500").isEmpty(); + assertThat(result.succeeded()).as("saves that succeeded").hasSize(2); + assertThat(result.succeeded().stream().filter(Settings::created).count()).as("saves told they created the row").isEqualTo(1); + assertThat(settingsRows(user)).as("rows in user_settings").isEqualTo(1); + } + + @Test + @DisplayName("save theme: the first save creates the row, the second one updates it") + void saveThemeCreatesThenUpdates() { + long user = insertUser("kim@example.com"); + + Settings first = settingsService.saveTheme(user, "dark"); + Settings second = settingsService.saveTheme(user, "blue"); + + assertThat(first.created()).as("first save created the row").isTrue(); + assertThat(second.created()).as("second save created the row").isFalse(); + assertThat(jdbc.queryForObject("select theme from user_settings where user_id = ?", String.class, user)) + .as("theme in the database").isEqualTo("blue"); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/SignupRaceIT.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/SignupRaceIT.java new file mode 100644 index 0000000..d13faf2 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/SignupRaceIT.java @@ -0,0 +1,30 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.constraints.support.IntegrationTest; +import com.amigoscode.constraints.support.Race; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 1. This test passes on purpose, before and after your fixes: it pins down the race in the + * application's own check. No constraint makes that check trustworthy. A constraint only decides + * what happens to the second insert. + */ +@Tag("task1") +class SignupRaceIT extends IntegrationTest { + + @Test + @DisplayName("Signup: two requests with the same email are both told \"this email is free\" by the application's check (this documents the race)") + void bothRequestsPassTheCheck() { + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.run(2, () -> signupService.signUp("ana@example.com", "Ana")); + + assertThat(work.arrivals()) + .as("requests that got past the email check and went on to insert") + .isEqualTo(2); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/SignupServiceTest.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/SignupServiceTest.java new file mode 100644 index 0000000..b351626 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/SignupServiceTest.java @@ -0,0 +1,56 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.constraints.support.Stub; +import com.amigoscode.constraints.user.EmailTakenException; +import com.amigoscode.constraints.user.SignupService; +import com.amigoscode.constraints.user.UserRepository; +import java.sql.SQLException; +import org.hibernate.exception.ConstraintViolationException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataIntegrityViolationException; + +/** + * Unit tests: no Spring, no database. UserRepository is a stub whose check says "the email is free" + * and whose save fails the way the real one does when the database refuses the row, so only the + * translation in SignupService is under test. + */ +@Tag("task2") +class SignupServiceTest { + + @Test + @DisplayName("Translate: when the insert is refused by users_email_key, the signup fails with EmailTakenException (a 409, not a 500)") + void aViolationOfTheEmailConstraintMeansEmailTaken() { + SignupService service = serviceWhoseInsertViolates("users_email_key"); + + assertThatThrownBy(() -> service.signUp("ana@example.com", "Ana")) + .isInstanceOf(EmailTakenException.class); + } + + @Test + @DisplayName("Translate: a violation of any other constraint is not reported as \"email taken\"") + void aViolationOfAnotherConstraintIsNotEmailTaken() { + SignupService service = serviceWhoseInsertViolates("users_display_name_check"); + + assertThatThrownBy(() -> service.signUp("ana@example.com", "Ana")) + .isInstanceOf(DataIntegrityViolationException.class); + } + + private static SignupService serviceWhoseInsertViolates(String constraintName) { + UserRepository users = Stub.repository(UserRepository.class, user -> { + throw refusedBy(constraintName); + }); + return new SignupService(users, step -> { }); + } + + /** The exception users.save really throws: Spring's, wrapping Hibernate's, which knows the constraint name. */ + static DataIntegrityViolationException refusedBy(String constraintName) { + SQLException fromPostgres = new SQLException( + "ERROR: duplicate key value violates unique constraint \"" + constraintName + "\"", "23505"); + return new DataIntegrityViolationException("could not execute statement; constraint [" + constraintName + "]", + new ConstraintViolationException("could not execute statement", fromPostgres, constraintName)); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/SubscriptionServiceTest.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/SubscriptionServiceTest.java new file mode 100644 index 0000000..520270e --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/SubscriptionServiceTest.java @@ -0,0 +1,43 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.constraints.subscription.AlreadySubscribedException; +import com.amigoscode.constraints.subscription.Plan; +import com.amigoscode.constraints.subscription.SubscriptionRepository; +import com.amigoscode.constraints.subscription.SubscriptionService; +import com.amigoscode.constraints.support.Stub; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataIntegrityViolationException; + +/** Unit tests: no Spring, no database. SubscriptionRepository is a stub whose save is refused by a named constraint. */ +@Tag("task5") +class SubscriptionServiceTest { + + @Test + @DisplayName("Translate: when the insert is refused by subscriptions_one_active_per_user, it fails with AlreadySubscribedException (a 409, not a 500)") + void aViolationOfTheOneActiveIndexMeansAlreadySubscribed() { + SubscriptionService service = serviceWhoseInsertViolates("subscriptions_one_active_per_user"); + + assertThatThrownBy(() -> service.subscribe(7, Plan.PRO, 1, 0)) + .isInstanceOf(AlreadySubscribedException.class); + } + + @Test + @DisplayName("Translate: a violation of any other constraint is not reported as \"already subscribed\"") + void aViolationOfAnotherConstraintIsNotAlreadySubscribed() { + SubscriptionService service = serviceWhoseInsertViolates("subscriptions_seats_check"); + + assertThatThrownBy(() -> service.subscribe(7, Plan.PRO, -3, 0)) + .isInstanceOf(DataIntegrityViolationException.class); + } + + private static SubscriptionService serviceWhoseInsertViolates(String constraintName) { + SubscriptionRepository subscriptions = Stub.repository(SubscriptionRepository.class, subscription -> { + throw SignupServiceTest.refusedBy(constraintName); + }); + return new SubscriptionService(subscriptions, step -> { }); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/UniqueEmailIT.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/UniqueEmailIT.java new file mode 100644 index 0000000..5680f1e --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/UniqueEmailIT.java @@ -0,0 +1,67 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.constraints.support.IntegrationTest; +import com.amigoscode.constraints.support.Race; +import com.amigoscode.constraints.user.EmailTakenException; +import com.amigoscode.constraints.user.User; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DuplicateKeyException; + +@Tag("task2") +class UniqueEmailIT extends IntegrationTest { + + @Test + @DisplayName("Unique: the database refuses a second row with the same email, even from code that skips the service") + void theDatabaseRefusesTheSameEmailTwice() { + insertUser("ana@example.com"); + + assertThatThrownBy(() -> insertUser("ana@example.com")) + .as("a plain SQL insert of an email that is already in the table") + .isInstanceOf(DuplicateKeyException.class); + assertThat(userRows()).as("rows in users").isEqualTo(1); + } + + @Test + @DisplayName("Unique: two signups with the same email at the same moment: one account is created, the other is told the email is taken") + void onlyOneOfTwoSignupsCreatesAnAccount() { + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.Result result = Race.run(2, () -> signupService.signUp("ana@example.com", "Ana")); + + assertThat(result.failedWithAnythingBut(EmailTakenException.class)).as("errors that would be a 500").isEmpty(); + assertThat(result.succeeded()).as("accounts created").hasSize(1); + assertThat(result.failedWith(EmailTakenException.class)).as("requests told the email is taken").isEqualTo(1); + assertThat(userRows()).as("rows in users").isEqualTo(1); + } + + @Test + @DisplayName("Unique: 20 signups with the same email: 1 account, 19 told the email is taken, 1 row") + void onlyOneOfTwentySignupsCreatesAnAccount() { + work.takes(20); + + Race.Result result = Race.run(20, () -> signupService.signUp("ana@example.com", "Ana")); + + assertThat(result.failedWithAnythingBut(EmailTakenException.class)).as("errors that would be a 500").isEmpty(); + assertThat(result.succeeded()).as("accounts created").hasSize(1); + assertThat(result.failedWith(EmailTakenException.class)).as("requests told the email is taken").isEqualTo(19); + assertThat(userRows()).as("rows in users").isEqualTo(1); + } + + @Test + @DisplayName("Unique: a signup that arrives after the first one finished is stopped by the application's check, before any insert is tried") + void aLaterSignupIsStoppedByTheFastPath() { + signupService.signUp("ana@example.com", "Ana"); + + assertThatThrownBy(() -> signupService.signUp("ana@example.com", "Ana again")) + .isInstanceOf(EmailTakenException.class); + + assertThat(work.arrivals()) + .as("signups that got past the email check (the second one must not)") + .isEqualTo(1); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/support/ControllableWork.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/support/ControllableWork.java new file mode 100644 index 0000000..c7cfe71 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/support/ControllableWork.java @@ -0,0 +1,65 @@ +package com.amigoscode.constraints.support; + +import com.amigoscode.constraints.work.SlowWork; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Replaces the real slow work in integration tests. The work runs between the check and the insert, + * so controlling it lets a test force the dangerous interleaving on purpose instead of hoping that + * two threads happen to overlap. + */ +public class ControllableWork implements SlowWork { + + private static final long MEETING_TIMEOUT_MILLIS = 1500; + + private final AtomicInteger arrivals = new AtomicInteger(); + private volatile int meetingSize; + private volatile CountDownLatch meeting; + private volatile long delayMillis; + + public void reset() { + arrivals.set(0); + meetingSize = 0; + meeting = null; + delayMillis = 0; + } + + /** + * The first {@code requests} callers wait here until all of them have arrived, so every one of + * them has already passed the check before any of them inserts. If the others never arrive the + * wait ends after 1.5 seconds. + */ + public void everyonePassesTheCheckBeforeAnyoneInserts(int requests) { + meetingSize = requests; + meeting = new CountDownLatch(requests); + } + + public void takes(long millis) { + delayMillis = millis; + } + + /** How many requests got past the check and reached the slow work. */ + public int arrivals() { + return arrivals.get(); + } + + @Override + public void run(String step) { + int arrival = arrivals.incrementAndGet(); + try { + CountDownLatch currentMeeting = meeting; + if (currentMeeting != null && arrival <= meetingSize) { + currentMeeting.countDown(); + currentMeeting.await(MEETING_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } + if (delayMillis > 0) { + Thread.sleep(delayMillis); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/support/IntegrationTest.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/support/IntegrationTest.java new file mode 100644 index 0000000..09c19c7 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/support/IntegrationTest.java @@ -0,0 +1,94 @@ +package com.amigoscode.constraints.support; + +import com.amigoscode.constraints.settings.SettingsService; +import com.amigoscode.constraints.subscription.SubscriptionService; +import com.amigoscode.constraints.user.SignupService; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Primary; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * Base class for the *IT tests. They run the real application against a real Postgres started by + * Testcontainers (Docker must be running), because a constraint only exists in a real database. + * One container is shared by every test class, and schema.sql is applied to it when the + * application starts. + */ +@SpringBootTest(properties = "spring.main.banner-mode=off") +@Import(IntegrationTest.TestBeans.class) +public abstract class IntegrationTest { + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + static void database(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", POSTGRES::getJdbcUrl); + registry.add("spring.datasource.username", POSTGRES::getUsername); + registry.add("spring.datasource.password", POSTGRES::getPassword); + } + + @TestConfiguration + static class TestBeans { + + @Bean + @Primary + ControllableWork controllableWork() { + return new ControllableWork(); + } + } + + @Autowired + protected SignupService signupService; + + @Autowired + protected SubscriptionService subscriptionService; + + @Autowired + protected SettingsService settingsService; + + @Autowired + protected ControllableWork work; + + @Autowired + protected JdbcTemplate jdbc; + + @BeforeEach + void emptyDatabase() { + work.reset(); + jdbc.execute("truncate table subscriptions, user_settings, users restart identity cascade"); + } + + /** Inserts a user with plain SQL, the way a script or another service would: no SignupService. */ + protected long insertUser(String email) { + return jdbc.queryForObject("insert into users (email, display_name) values (?, 'Test') returning id", + Long.class, email); + } + + protected int userRows() { + return jdbc.queryForObject("select count(*) from users", Integer.class); + } + + protected int subscriptionRows(long userId, String status) { + return jdbc.queryForObject("select count(*) from subscriptions where user_id = ? and status = ?", + Integer.class, userId, status); + } + + protected int subscriptionRows() { + return jdbc.queryForObject("select count(*) from subscriptions", Integer.class); + } + + protected int settingsRows(long userId) { + return jdbc.queryForObject("select count(*) from user_settings where user_id = ?", Integer.class, userId); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/support/Race.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/support/Race.java new file mode 100644 index 0000000..aa1b5f6 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/support/Race.java @@ -0,0 +1,70 @@ +package com.amigoscode.constraints.support; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.IntFunction; + +/** Runs several calls at the same moment, each on its own thread, and collects what happened. */ +public final class Race { + + /** {@code succeeded} holds the return values, {@code failed} the exceptions. */ + public record Result(List succeeded, List failed) { + + /** How many calls failed with this kind of exception. */ + public int failedWith(Class type) { + return (int) failed.stream().filter(type::isInstance).count(); + } + + /** Failures that are not of this kind: anything here would be a 500. */ + public List failedWithAnythingBut(Class expected) { + return failed.stream().filter(failure -> !expected.isInstance(failure)).toList(); + } + } + + /** Runs {@code calls} copies of the same call. */ + public static Result run(int calls, Callable call) { + return run(calls, i -> call); + } + + /** Runs {@code calls} different calls: {@code call.apply(0)}, {@code call.apply(1)}, ... */ + public static Result run(int calls, IntFunction> call) { + ExecutorService executor = Executors.newFixedThreadPool(calls); + CountDownLatch go = new CountDownLatch(1); + List> futures = new ArrayList<>(); + for (int i = 0; i < calls; i++) { + Callable one = call.apply(i); + futures.add(executor.submit(() -> { + go.await(); + return one.call(); + })); + } + go.countDown(); + + List succeeded = new ArrayList<>(); + List failed = new ArrayList<>(); + try { + for (Future future : futures) { + try { + succeeded.add(future.get(60, TimeUnit.SECONDS)); + } catch (ExecutionException e) { + failed.add(e.getCause()); + } catch (Exception e) { + failed.add(e); + } + } + } finally { + executor.shutdownNow(); + } + return new Result<>(succeeded, failed); + } + + private Race() { + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/support/Stub.java b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/support/Stub.java new file mode 100644 index 0000000..52b26b1 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/java/com/amigoscode/constraints/support/Stub.java @@ -0,0 +1,31 @@ +package com.amigoscode.constraints.support; + +import java.lang.reflect.Proxy; +import java.util.function.Function; + +/** + * A hand-written stand-in for a Spring Data repository, for unit tests without Spring or a + * database. Every method that returns a boolean ("does it exist?") answers false, and save does + * whatever the test says. Adding a method to the repository does not break the stub. + */ +public final class Stub { + + @SuppressWarnings("unchecked") + public static T repository(Class type, Function save) { + return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, (proxy, method, args) -> { + if (method.getName().equals("save")) { + return save.apply(args[0]); + } + if (method.getReturnType() == boolean.class) { + return false; + } + if (method.getName().equals("toString")) { + return "stub of " + type.getSimpleName(); + } + throw new UnsupportedOperationException("The stub does not know " + method.getName()); + }); + } + + private Stub() { + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/resources/logback-test.xml b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/resources/logback-test.xml new file mode 100644 index 0000000..82166a4 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/solution/src/test/resources/logback-test.xml @@ -0,0 +1,11 @@ + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + + diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/.mvn/jvm.config b/java/concepts/junior-mid/10-constraints-and-races/start/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/.mvn/jvm.config @@ -0,0 +1,2 @@ +--enable-native-access=ALL-UNNAMED +--sun-misc-unsafe-memory-access=allow diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/10-constraints-and-races/start/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/check b/java/concepts/junior-mid/10-constraints-and-races/start/check new file mode 100755 index 0000000..f500026 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/check @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use check.cmd (type: .\check). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.constraints.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/check.cmd b/java/concepts/junior-mid/10-constraints-and-races/start/check.cmd new file mode 100644 index 0000000..6e0ce70 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/check.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./check +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.constraints.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/compose.yaml b/java/concepts/junior-mid/10-constraints-and-races/start/compose.yaml new file mode 100644 index 0000000..6a41dfb --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/compose.yaml @@ -0,0 +1,16 @@ +name: constraints-and-races +services: + postgres: + image: postgres:17-alpine + container_name: constraints-and-races-postgres + environment: + POSTGRES_DB: app + POSTGRES_USER: app + POSTGRES_PASSWORD: app + ports: + - "5449:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U app -d app"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/demo b/java/concepts/junior-mid/10-constraints-and-races/start/demo new file mode 100755 index 0000000..15dc754 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/demo @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use demo.cmd (type: .\demo). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.constraints.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/demo.cmd b/java/concepts/junior-mid/10-constraints-and-races/start/demo.cmd new file mode 100644 index 0000000..cd9c540 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/demo.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./demo +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.constraints.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/inspect b/java/concepts/junior-mid/10-constraints-and-races/start/inspect new file mode 100755 index 0000000..6dafb52 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/inspect @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use inspect.cmd (type: .\inspect). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.constraints.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/inspect.cmd b/java/concepts/junior-mid/10-constraints-and-races/start/inspect.cmd new file mode 100644 index 0000000..89de916 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/inspect.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./inspect +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.constraints.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/mvnw b/java/concepts/junior-mid/10-constraints-and-races/start/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/mvnw.cmd b/java/concepts/junior-mid/10-constraints-and-races/start/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/pom.xml b/java/concepts/junior-mid/10-constraints-and-races/start/pom.xml new file mode 100644 index 0000000..99f9343 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + constraints-and-races + 0.0.1-SNAPSHOT + constraints-and-races + Database constraints as the last line of defence against race conditions + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + runtime + + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.mockito + mockito-core + + + org.mockito + mockito-junit-jupiter + + + + + org.springframework.boot + spring-boot-starter-data-jpa-test + test + + + org.testcontainers + testcontainers-postgresql + test + + + org.junit.platform + junit-platform-launcher + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + false + + + + + + diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/ApiExceptionHandler.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/ApiExceptionHandler.java new file mode 100644 index 0000000..e2e7c92 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/ApiExceptionHandler.java @@ -0,0 +1,48 @@ +package com.amigoscode.constraints; + +import com.amigoscode.constraints.settings.Strategy.UnknownStrategyException; +import com.amigoscode.constraints.subscription.AlreadySubscribedException; +import com.amigoscode.constraints.subscription.SubscriptionNotFoundException; +import com.amigoscode.constraints.user.EmailTakenException; +import com.amigoscode.constraints.user.UserNotFoundException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +/** Anything not listed here, including a raw DataIntegrityViolationException, becomes a 500. */ +@RestControllerAdvice +public class ApiExceptionHandler { + + public record ApiError(String code, String message) { + } + + @ExceptionHandler(EmailTakenException.class) + public ResponseEntity emailTaken(EmailTakenException e) { + return error(HttpStatus.CONFLICT, "EMAIL_TAKEN", e); + } + + @ExceptionHandler(AlreadySubscribedException.class) + public ResponseEntity alreadySubscribed(AlreadySubscribedException e) { + return error(HttpStatus.CONFLICT, "ALREADY_SUBSCRIBED", e); + } + + @ExceptionHandler(UserNotFoundException.class) + public ResponseEntity userNotFound(UserNotFoundException e) { + return error(HttpStatus.NOT_FOUND, "USER_NOT_FOUND", e); + } + + @ExceptionHandler(SubscriptionNotFoundException.class) + public ResponseEntity subscriptionNotFound(SubscriptionNotFoundException e) { + return error(HttpStatus.NOT_FOUND, "SUBSCRIPTION_NOT_FOUND", e); + } + + @ExceptionHandler({UnknownStrategyException.class, IllegalArgumentException.class}) + public ResponseEntity badRequest(RuntimeException e) { + return error(HttpStatus.BAD_REQUEST, "BAD_REQUEST", e); + } + + private static ResponseEntity error(HttpStatus status, String code, RuntimeException e) { + return ResponseEntity.status(status).body(new ApiError(code, e.getMessage())); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/ConstraintsApplication.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/ConstraintsApplication.java new file mode 100644 index 0000000..d2919d8 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/ConstraintsApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.constraints; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ConstraintsApplication { + + public static void main(String[] args) { + SpringApplication.run(ConstraintsApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/demo/Db.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/demo/Db.java new file mode 100644 index 0000000..ad7d0d1 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/demo/Db.java @@ -0,0 +1,97 @@ +package com.amigoscode.constraints.demo; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +/** Connection settings and table printing shared by the demo and inspect tools. Same defaults as application.properties. */ +final class Db { + + static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5449/app"); + static final String USER = env("DB_USER", "app"); + static final String PASSWORD = env("DB_PASSWORD", "app"); + + private Db() { + } + + static Connection connect() throws SQLException { + return DriverManager.getConnection(URL, USER, PASSWORD); + } + + /** Returns false, after printing what to do, when Postgres is not reachable. */ + static boolean isUp() { + try (Connection ignored = connect()) { + return true; + } catch (SQLException e) { + System.out.println(); + System.out.println("Cannot reach Postgres at " + URL); + System.out.println("Start it first, from this folder:"); + System.out.println(); + System.out.println(" docker compose up -d"); + System.out.println(); + System.out.println("(" + e.getMessage().lines().findFirst().orElse("") + ")"); + return false; + } + } + + static int count(Connection connection, String sql) throws SQLException { + try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) { + result.next(); + return result.getInt(1); + } + } + + /** Prints a query result as a plain text table and returns the number of rows. NULL is printed as NULL. */ + static int printTable(Connection connection, String sql) throws SQLException { + List rows = new ArrayList<>(); + try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) { + int columns = result.getMetaData().getColumnCount(); + String[] header = new String[columns]; + for (int c = 0; c < columns; c++) { + header[c] = result.getMetaData().getColumnLabel(c + 1); + } + rows.add(header); + while (result.next()) { + String[] row = new String[columns]; + for (int c = 0; c < columns; c++) { + String value = result.getString(c + 1); + row[c] = value == null ? "NULL" : value; + } + rows.add(row); + } + } + if (rows.size() == 1) { + return 0; + } + int[] widths = new int[rows.get(0).length]; + for (String[] row : rows) { + for (int c = 0; c < row.length; c++) { + widths[c] = Math.max(widths[c], row[c].length()); + } + } + for (int r = 0; r < rows.size(); r++) { + StringBuilder line = new StringBuilder(" "); + for (int c = 0; c < widths.length; c++) { + line.append(String.format("%-" + widths[c] + "s", rows.get(r)[c])).append(" "); + } + System.out.println(line.toString().stripTrailing()); + if (r == 0) { + StringBuilder rule = new StringBuilder(" "); + for (int width : widths) { + rule.append("-".repeat(width)).append(" "); + } + System.out.println(rule.toString().stripTrailing()); + } + } + return rows.size() - 1; + } + + private static String env(String name, String fallback) { + String value = System.getenv(name); + return value == null || value.isBlank() ? fallback : value; + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/demo/Demo.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/demo/Demo.java new file mode 100644 index 0000000..f37b145 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/demo/Demo.java @@ -0,0 +1,556 @@ +package com.amigoscode.constraints.demo; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.turbo.TurboFilter; +import ch.qos.logback.core.spi.FilterReply; +import com.amigoscode.constraints.ConstraintsApplication; +import com.amigoscode.constraints.settings.Strategy; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.function.IntFunction; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.slf4j.LoggerFactory; +import org.slf4j.Marker; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * Starts the real application, sends requests at it over HTTP at the same moment, and prints what + * ended up in the database. Run it with ./demo (or .\demo on Windows). ./demo --help lists the flags. + */ +public final class Demo { + + private static final List SCENARIOS = List.of("signup", "case", "subscription", "settings", "theme", "bad-data"); + private static final String[] SPELLINGS = {"Ana@Example.com", "ana@example.com", "ANA@EXAMPLE.COM", "aNa@eXaMpLe.CoM"}; + private static final long MISSING_USER = 999_999; + + private static final Pattern CODE = Pattern.compile("\"code\"\\s*:\\s*\"([A-Z_]+)\""); + private static final Pattern ID = Pattern.compile("\"id\"\\s*:\\s*(\\d+)"); + private static final Pattern CREATED = Pattern.compile("\"created\"\\s*:\\s*(true|false)"); + private static final Pattern THEME = Pattern.compile("\"theme\"\\s*:\\s*\"([^\"]*)\""); + private static final Pattern MESSAGE = Pattern.compile("\"message\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\""); + + private record Options(String scenario, int requests, long workMillis, Strategy strategy, boolean sql) { + } + + private record Call(String label, HttpRequest request) { + } + + private record Outcome(int status, String body) { + + String code() { + return find(CODE, body); + } + + boolean serverError() { + return status >= 500; + } + } + + private static HttpClient http; + private static String baseUrl; + + public static void main(String[] args) throws Exception { + Options options; + try { + options = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println(); + printHelp(); + return; + } + if (options == null) { + printHelp(); + return; + } + if (!Db.isUp()) { + return; + } + + List springArgs = new ArrayList<>(List.of( + "--server.port=0", + "--logging.level.root=WARN", + // A 500 is shown as one line in the timeline instead of a full stack trace. + "--logging.level.org.apache.catalina.core.ContainerBase=OFF", + "--spring.web.error.include-message=always", + "--app.work-millis=" + options.workMillis())); + if (options.sql()) { + springArgs.add("--logging.level.org.hibernate.SQL=DEBUG"); + springArgs.add("--logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG"); + springArgs.add("--logging.pattern.console= %d{HH:mm:ss.SSS} [%replace(%thread){'http-nio-auto-\\d+-',''}] %msg%n"); + } else { + // Hibernate logs every refused statement as an ERROR, also when the application handles it. + springArgs.add("--logging.level.org.hibernate.engine.jdbc.spi.SqlExceptionHelper=OFF"); + springArgs.add("--logging.level.org.hibernate.orm.jdbc.error=OFF"); + } + + SpringApplication app = new SpringApplication(ConstraintsApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + try (ConfigurableApplicationContext context = app.run(springArgs.toArray(String[]::new)); + Connection db = Db.connect()) { + if (options.sql()) { + hideJdbcTemplateNoise(); + } + baseUrl = "http://localhost:" + context.getEnvironment().getProperty("local.server.port"); + http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build(); + + // Fresh state for every run, and one throwaway request so the first caller is not slowed by startup work. + try (Statement statement = db.createStatement()) { + statement.execute("truncate table subscriptions, user_settings, users restart identity cascade"); + } + http.send(HttpRequest.newBuilder(URI.create(baseUrl + "/warm-up")).build(), HttpResponse.BodyHandlers.discarding()); + + System.out.println(); + switch (options.scenario()) { + case "signup" -> signup(options, db, false); + case "case" -> signup(options, db, true); + case "subscription" -> subscription(options, db); + case "settings" -> settings(options, db); + case "theme" -> theme(options, db); + default -> badData(db); + } + System.out.println(); + } + } + + /** + * JdbcTemplate logs two lines per statement: "Executing prepared SQL update" and then the SQL. + * This drops the first of the two, so that --sql prints one line per statement. + */ + private static void hideJdbcTemplateNoise() { + LoggerContext logging = (LoggerContext) LoggerFactory.getILoggerFactory(); + logging.addTurboFilter(new TurboFilter() { + @Override + public FilterReply decide(Marker marker, ch.qos.logback.classic.Logger logger, Level level, + String format, Object[] params, Throwable t) { + boolean noise = format != null && logger.getName().endsWith("JdbcTemplate") + && (format.equals("Executing prepared SQL update") || format.equals("Executing prepared SQL query")); + return noise ? FilterReply.DENY : FilterReply.NEUTRAL; + } + }); + } + + // ---- signup and case: N requests sign up the same email at the same moment ---- + + private static void signup(Options options, Connection db, boolean mixCase) throws Exception { + String email = "ana@example.com"; + System.out.println("Scenario: " + options.scenario() + " | requests: " + options.requests() + + " | work between check and insert: " + options.workMillis() + " ms"); + System.out.println(mixCase + ? "Every request signs up the same address at the same moment, each with different capital letters." + : "Every request signs up " + email + " at the same moment."); + System.out.println(); + + List outcomes = race(options.requests(), i -> { + String spelling = mixCase ? SPELLINGS[i % SPELLINGS.length] : email; + return new Call("POST /api/signups " + spelling, + post("/api/signups", "{\"email\":\"" + spelling + "\",\"displayName\":\"Ana\"}")); + }); + + System.out.println(); + summary("Accounts created (201):", count(outcomes, 201)); + summary("Email taken (409):", count(outcomes, 409)); + printServerErrors(outcomes); + System.out.println(); + System.out.println("ROWS IN users"); + Db.printTable(db, "select id, email, display_name from users order by id"); + System.out.println(); + + int rows = Db.count(db, "select count(*) from users where lower(email) = '" + email + "'"); + if (rows > 1) { + System.out.println("RESULT: DUPLICATES. " + rows + " rows in users for " + (mixCase ? "the same address." : email + ".")); + } else if (serverErrors(outcomes) > 0) { + System.out.println("RESULT: SERVER ERROR. No duplicates, but " + requests(serverErrors(outcomes)) + + " got a 500 instead of a clear answer."); + } else { + System.out.println("RESULT: OK. 1 row for " + email + ": " + count(outcomes, 201) + " created, " + + count(outcomes, 409) + " told the email is taken."); + } + } + + // ---- subscription: N requests subscribe the same user at the same moment ---- + + private static void subscription(Options options, Connection db) throws Exception { + long userId = createUser(db, "sam@example.com"); + System.out.println("Scenario: subscription | requests: " + options.requests() + + " | work between check and insert: " + options.workMillis() + " ms"); + System.out.println("The rule: a user has at most one ACTIVE subscription. Every request subscribes user " + + userId + " at the same moment."); + System.out.println(); + + List outcomes = race(options.requests(), i -> new Call("POST /api/subscriptions", + post("/api/subscriptions", "{\"userId\":" + userId + ",\"plan\":\"pro\"}"))); + int active = Db.count(db, "select count(*) from subscriptions where status = 'ACTIVE' and user_id = " + userId); + + System.out.println(); + summary("Subscribed (201):", count(outcomes, 201)); + summary("Already subscribed (409):", count(outcomes, 409)); + printServerErrors(outcomes); + summary("ACTIVE rows for user " + userId + ":", active); + System.out.println(); + + System.out.println("Then, one after another: cancel what is active, and subscribe again."); + System.out.println(); + List activeIds = new ArrayList<>(); + try (Statement statement = db.createStatement(); + ResultSet result = statement.executeQuery("select id from subscriptions where status = 'ACTIVE' order by id")) { + while (result.next()) { + activeIds.add(result.getLong(1)); + } + } + for (long id : activeIds) { + one("POST /api/subscriptions/" + id + "/cancel", post("/api/subscriptions/" + id + "/cancel", "")); + } + Outcome again = one("POST /api/subscriptions", post("/api/subscriptions", "{\"userId\":" + userId + ",\"plan\":\"basic\"}")); + + System.out.println(); + System.out.println("ROWS IN subscriptions"); + Db.printTable(db, "select id, user_id, plan, status from subscriptions order by id"); + System.out.println(); + + if (active > 1) { + System.out.println("RESULT: DUPLICATES. User " + userId + " had " + active + " ACTIVE subscriptions and pays for each of them."); + } else if (serverErrors(outcomes) > 0) { + System.out.println("RESULT: SERVER ERROR. One ACTIVE subscription, but " + requests(serverErrors(outcomes)) + + " got a 500 instead of a clear answer."); + } else if (again.status() != 201) { + System.out.println("RESULT: TOO STRICT. The user cancelled and could not subscribe again."); + } else { + System.out.println("RESULT: OK. Never more than one ACTIVE subscription, and cancelled rows may repeat."); + } + } + + // ---- settings: N requests ask for the same user's settings for the first time ---- + + private static void settings(Options options, Connection db) throws Exception { + long userId = createUser(db, "lee@example.com"); + String strategy = options.strategy().label(); + System.out.println("Scenario: settings | strategy: " + strategy + " | requests: " + options.requests() + + " | work between check and insert: " + options.workMillis() + " ms"); + System.out.println("User " + userId + " has no settings row yet. Every request asks for the settings at the same moment,"); + System.out.println("then one more request asks again."); + System.out.println(); + + String path = "/api/users/" + userId + "/settings?strategy=" + strategy; + List outcomes = new ArrayList<>(race(options.requests(), i -> new Call("PUT /api/users/" + userId + "/settings", put(path, "")))); + System.out.println(); + outcomes.add(one("PUT /api/users/" + userId + "/settings (again, later)", put(path, ""))); + settingsSummary(outcomes, db, userId); + } + + // ---- theme: N requests save the theme of a user that has no settings row yet ---- + + private static void theme(Options options, Connection db) throws Exception { + long userId = createUser(db, "kim@example.com"); + System.out.println("Scenario: theme | requests: " + options.requests() + + " | work between check and insert: " + options.workMillis() + " ms"); + System.out.println("User " + userId + " has no settings row yet. Every request saves theme=dark at the same moment,"); + System.out.println("then one more request saves theme=blue."); + System.out.println(); + + String path = "/api/users/" + userId + "/settings/theme"; + List outcomes = new ArrayList<>(race(options.requests(), + i -> new Call("PUT " + path + " dark", put(path, "{\"theme\":\"dark\"}")))); + System.out.println(); + outcomes.add(one("PUT " + path + " blue (later)", put(path, "{\"theme\":\"blue\"}"))); + settingsSummary(outcomes, db, userId); + } + + private static void settingsSummary(List outcomes, Connection db, long userId) throws SQLException { + long created = outcomes.stream().filter(o -> "true".equals(find(CREATED, o.body()))).count(); + System.out.println(); + summary("Answered (200):", count(outcomes, 200)); + summary(" of which created the row:", created); + printServerErrors(outcomes); + System.out.println(); + System.out.println("ROWS IN user_settings"); + if (Db.printTable(db, "select user_id, theme from user_settings order by user_id") == 0) { + System.out.println(" none"); + } + System.out.println(); + int rows = Db.count(db, "select count(*) from user_settings where user_id = " + userId); + if (serverErrors(outcomes) > 0) { + System.out.println("RESULT: SERVER ERROR. " + requests(serverErrors(outcomes)) + " got a 500. The primary key kept the data clean (" + + rows + (rows == 1 ? " row" : " rows") + "), the application did not cope with the refusal."); + } else if (created != 1) { + System.out.println("RESULT: WRONG ANSWER. 1 row was created, but " + created + " requests said they created it."); + } else { + System.out.println("RESULT: OK. 1 row, every request was answered, exactly 1 was told it created the row."); + } + } + + // ---- bad-data: four requests, one after another, that the application should never have accepted ---- + + private static void badData(Connection db) throws Exception { + long first = createUser(db, "bo@example.com"); + long second = createUser(db, "cy@example.com"); + System.out.println("Scenario: bad-data"); + System.out.println("Four requests, one after another. The application does not validate any of them."); + System.out.println(); + + List outcomes = new ArrayList<>(); + outcomes.add(one("signup without an email ", post("/api/signups", "{\"displayName\":\"No Email\"}"))); + outcomes.add(one("subscribe with seats = -3 ", + post("/api/subscriptions", "{\"userId\":" + first + ",\"plan\":\"pro\",\"seats\":-3}"))); + outcomes.add(one("subscribe, coupon bigger than price ", + post("/api/subscriptions", "{\"userId\":" + second + ",\"plan\":\"basic\",\"couponCents\":5000}"))); + outcomes.add(one("subscribe a user that does not exist", + post("/api/subscriptions", "{\"userId\":" + MISSING_USER + ",\"plan\":\"pro\"}"))); + + System.out.println(); + summary("Accepted (201):", count(outcomes, 201)); + printServerErrors(outcomes); + System.out.println(); + System.out.println("BAD ROWS IN THE DATABASE"); + int bad = Db.printTable(db, Inspect.BAD_ROWS); + if (bad == 0) { + System.out.println(" none"); + } + System.out.println(); + if (bad > 0) { + System.out.println("RESULT: BAD DATA. " + bad + " of 4 bad requests are now rows in the database."); + } else { + System.out.println("RESULT: OK. The database refused all 4. Nothing bad was stored."); + } + } + + // ---- sending requests ---- + + /** Sends {@code n} requests at the same moment and waits for all the answers. */ + private static List race(int n, IntFunction calls) throws Exception { + boolean timeline = n <= 10; + CountDownLatch go = new CountDownLatch(1); + List> futures = new ArrayList<>(); + long[] startedAt = new long[1]; + try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { + for (int i = 0; i < n; i++) { + Call call = calls.apply(i); + String who = "Request " + (i + 1); + futures.add(executor.submit(() -> { + go.await(); + if (timeline) { + log(startedAt[0], who + " -> " + call.label()); + } + Outcome outcome = send(call.request()); + if (timeline) { + log(startedAt[0], who + " <- " + describe(outcome)); + } + return outcome; + })); + } + startedAt[0] = System.nanoTime(); + go.countDown(); + } + long elapsedMillis = (System.nanoTime() - startedAt[0]) / 1_000_000; + List outcomes = new ArrayList<>(); + for (Future future : futures) { + outcomes.add(future.get()); + } + if (!timeline) { + System.out.println(" " + n + " requests answered in " + elapsedMillis + " ms"); + } + return outcomes; + } + + /** Sends one request and prints it with its answer. */ + private static Outcome one(String label, HttpRequest request) throws Exception { + Outcome outcome = send(request); + System.out.println(" " + label + " <- " + describe(outcome)); + return outcome; + } + + private static Outcome send(HttpRequest request) throws Exception { + HttpResponse response = http.send(request, HttpResponse.BodyHandlers.ofString()); + return new Outcome(response.statusCode(), response.body()); + } + + /** Sets up a user with plain SQL, so that the scenario itself is the only thing in the output. */ + private static long createUser(Connection db, String email) throws SQLException { + try (Statement statement = db.createStatement(); + ResultSet result = statement.executeQuery( + "insert into users (email, display_name) values ('" + email + "', 'Demo') returning id")) { + result.next(); + return result.getLong(1); + } + } + + private static HttpRequest post(String path, String json) { + return HttpRequest.newBuilder(URI.create(baseUrl + path)) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(json)) + .build(); + } + + private static HttpRequest put(String path, String json) { + return HttpRequest.newBuilder(URI.create(baseUrl + path)) + .header("Content-Type", "application/json") + .PUT(HttpRequest.BodyPublishers.ofString(json)) + .build(); + } + + // ---- printing ---- + + private static String describe(Outcome outcome) { + String body = outcome.body(); + if (outcome.code() != null) { + return outcome.status() + " " + outcome.code(); + } + if (outcome.status() == 201 || outcome.status() == 200) { + String created = find(CREATED, body); + if (created != null) { + return outcome.status() + " theme=" + find(THEME, body) + " created=" + created; + } + if (body.contains("\"status\"")) { + return outcome.status() + " subscription #" + find(ID, body) + (body.contains("CANCELLED") ? " cancelled" : " active"); + } + return outcome.status() + " user #" + find(ID, body) + " created"; + } + return outcome.status() + " " + reason(find(MESSAGE, body)); + } + + /** The reason for a 500, cut down to what the database itself said when there is such a part. */ + private static String reason(String message) { + if (message == null || message.isBlank()) { + return ""; + } + String text = message.replace("\\n", " ").replace("\\\"", "\"").replaceAll("\\s+", " "); + int fromDatabase = text.indexOf("ERROR: "); + if (fromDatabase >= 0) { + text = text.substring(fromDatabase); + int end = text.indexOf("] ["); + text = end > 0 ? text.substring(0, end) : text; + text = text.replaceAll(" Detail: Failing row contains.*", ""); + } + return "(" + (text.length() > 200 ? text.substring(0, 200) + "..." : text) + ")"; + } + + private static void summary(String label, long value) { + System.out.printf("%-28s %d%n", label, value); + } + + private static void printServerErrors(List outcomes) { + if (serverErrors(outcomes) > 0) { + summary("Server errors (500):", serverErrors(outcomes)); + } + } + + private static int count(List outcomes, int status) { + return (int) outcomes.stream().filter(outcome -> outcome.status() == status).count(); + } + + private static int serverErrors(List outcomes) { + return (int) outcomes.stream().filter(Outcome::serverError).count(); + } + + private static String requests(int n) { + return n + (n == 1 ? " request" : " requests"); + } + + private static synchronized void log(long startedAtNanos, String message) { + long millis = (System.nanoTime() - startedAtNanos) / 1_000_000; + System.out.printf(" +%5d ms %s%n", millis, message); + } + + private static String find(Pattern pattern, String body) { + Matcher matcher = pattern.matcher(body == null ? "" : body); + return matcher.find() ? matcher.group(1) : null; + } + + // ---- options ---- + + private static Options parse(String[] args) { + String scenario = "signup"; + int requests = 2; + long workMillis = 100; + Strategy strategy = Strategy.ON_CONFLICT; + boolean sql = false; + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "--help", "-h" -> { + return null; + } + case "--scenario" -> { + scenario = value(args, ++i, arg); + if (!SCENARIOS.contains(scenario)) { + throw new IllegalArgumentException("Unknown scenario '" + scenario + "'. Use one of: " + + String.join(", ", SCENARIOS)); + } + } + case "--strategy" -> { + try { + strategy = Strategy.from(value(args, ++i, arg)); + } catch (Strategy.UnknownStrategyException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + case "--requests" -> requests = number(value(args, ++i, arg), arg, 1, 500); + case "--work-ms" -> workMillis = number(value(args, ++i, arg), arg, 0, 120_000); + case "--sql" -> sql = true; + default -> throw new IllegalArgumentException("Unknown option: " + arg); + } + } + return new Options(scenario, requests, workMillis, strategy, sql); + } + + private static String value(String[] args, int index, String option) { + if (index >= args.length) { + throw new IllegalArgumentException(option + " needs a value"); + } + return args[index]; + } + + private static int number(String value, String option, int min, int max) { + try { + int number = Integer.parseInt(value); + if (number < min || number > max) { + throw new NumberFormatException(); + } + return number; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(option + " must be a number from " + min + " to " + max + ", got: " + value); + } + } + + private static void printHelp() { + System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])"); + System.out.println(); + System.out.println(" --scenario what to try (default: signup)"); + System.out.println(" signup the same email signs up twice at the same moment"); + System.out.println(" case the same email, written with different capital letters"); + System.out.println(" subscription one user subscribes twice at the same moment"); + System.out.println(" settings get-or-create of a settings row (see --strategy)"); + System.out.println(" theme create-or-update of a settings row"); + System.out.println(" bad-data four requests the application should have refused"); + System.out.println(" --strategy for --scenario settings: " + Strategy.names() + " (default: on-conflict)"); + System.out.println(" --requests how many requests are sent at the same moment (default: 2)"); + System.out.println(" --work-ms time between the check and the insert (default: 100)"); + System.out.println(" --sql print every SQL statement, with the thread that ran it"); + System.out.println(); + System.out.println("Examples:"); + System.out.println(" ./demo"); + System.out.println(" ./demo --sql"); + System.out.println(" ./demo --scenario subscription --requests 20"); + System.out.println(" ./demo --scenario settings --strategy catch-inside"); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/demo/Inspect.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/demo/Inspect.java new file mode 100644 index 0000000..37ea1c5 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/demo/Inspect.java @@ -0,0 +1,141 @@ +package com.amigoscode.constraints.demo; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; + +/** + * Shows what the database enforces right now and whether the data already breaks a rule: for each + * table its columns, constraints and indexes, then every duplicate group and every bad row. Run it + * with ./inspect (or .\inspect on Windows), usually right after ./demo. + */ +public final class Inspect { + + private static final List TABLES = List.of("users", "subscriptions", "user_settings"); + + private static final String COLUMNS = """ + select column_name as column, + data_type as type, + case is_nullable when 'YES' then 'yes' else 'NOT NULL' end as null_allowed + from information_schema.columns + where table_schema = 'public' and table_name = '%s' + order by ordinal_position + """; + + private static final String CONSTRAINTS = """ + select c.conname as name, + case c.contype when 'p' then 'PRIMARY KEY' when 'u' then 'UNIQUE' when 'c' then 'CHECK' + when 'f' then 'FOREIGN KEY' else c.contype::text end as kind, + pg_get_constraintdef(c.oid) as definition + from pg_constraint c + where c.conrelid = 'public.%s'::regclass + order by case c.contype when 'p' then 1 when 'u' then 2 when 'f' then 3 else 4 end, c.conname + """; + + private static final String INDEXES = """ + select indexname as name, + case when indexdef like 'CREATE UNIQUE%%' then 'yes' else 'no' end as unique, + regexp_replace(indexdef, '^.* USING ', '') as definition + from pg_indexes + where schemaname = 'public' and tablename = '%s' + order by indexname + """; + + public static void main(String[] args) throws Exception { + if (args.length > 0) { + System.out.println("Usage: ./inspect (Windows: .\\inspect)"); + System.out.println(); + System.out.println("Prints the columns, constraints and indexes of every table, then the duplicates"); + System.out.println("and bad rows that are in the data right now. Run ./demo first to have some data."); + return; + } + if (!Db.isUp()) { + return; + } + try (Connection connection = Db.connect()) { + if (Db.count(connection, "select count(*) from pg_tables where schemaname = 'public' and tablename = 'users'") == 0) { + System.out.println(); + System.out.println("The tables do not exist yet. Run ./demo once: it creates them from schema.sql."); + System.out.println(); + return; + } + for (String table : TABLES) { + table(connection, table); + } + data(connection); + } + } + + private static void table(Connection connection, String table) throws SQLException { + System.out.println(); + int rows = Db.count(connection, "select count(*) from " + table); + System.out.println("==== TABLE " + table + " (" + rows + (rows == 1 ? " row" : " rows") + ") ===="); + System.out.println(); + System.out.println("COLUMNS"); + Db.printTable(connection, COLUMNS.formatted(table)); + System.out.println(); + System.out.println("CONSTRAINTS (pg_constraint)"); + if (Db.printTable(connection, CONSTRAINTS.formatted(table)) == 0) { + System.out.println(" none"); + } + System.out.println(); + System.out.println("INDEXES (pg_indexes)"); + if (Db.printTable(connection, INDEXES.formatted(table)) == 0) { + System.out.println(" none"); + } + } + + private static void data(Connection connection) throws SQLException { + System.out.println(); + System.out.println("==== WHAT IS IN THE DATA RIGHT NOW ===="); + + section(connection, "SAME EMAIL, MORE THAN ONE ROW (compared without case)", """ + select lower(email) as email_lowercase, + count(*) as rows, + string_agg(id::text, ', ' order by id) as user_ids, + string_agg(email, ', ' order by id) as stored_as + from users + where email is not null + group by lower(email) + having count(*) > 1 + order by 1 + """); + section(connection, "MORE THAN ONE ACTIVE SUBSCRIPTION FOR ONE USER", """ + select user_id, + count(*) as active_rows, + string_agg(id::text, ', ' order by id) as subscription_ids + from subscriptions + where status = 'ACTIVE' + group by user_id + having count(*) > 1 + order by 1 + """); + section(connection, "BAD ROWS", BAD_ROWS); + System.out.println(); + } + + /** Every row that breaks a rule the solution enforces with NOT NULL, CHECK or FOREIGN KEY. */ + static final String BAD_ROWS = """ + select 'users' as table, id, 'email is NULL' as problem from users where email is null + union all + select 'subscriptions', id, 'seats = ' || seats from subscriptions where seats <= 0 + union all + select 'subscriptions', id, 'price_cents = ' || price_cents from subscriptions where price_cents < 0 + union all + select 'subscriptions', s.id, 'user ' || s.user_id || ' does not exist' + from subscriptions s + where not exists (select 1 from users u where u.id = s.user_id) + order by 1 desc, 2, 3 + """; + + private static void section(Connection connection, String title, String sql) throws SQLException { + System.out.println(); + System.out.println(title); + if (Db.printTable(connection, sql) == 0) { + System.out.println(" none"); + } + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/Settings.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/Settings.java new file mode 100644 index 0000000..841a4f9 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/Settings.java @@ -0,0 +1,5 @@ +package com.amigoscode.constraints.settings; + +/** One row of user_settings. {@code created} is true when this call inserted the row. */ +public record Settings(long userId, String theme, boolean created) { +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/SettingsController.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/SettingsController.java new file mode 100644 index 0000000..0885d30 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/SettingsController.java @@ -0,0 +1,37 @@ +package com.amigoscode.constraints.settings; + +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/users/{userId}/settings") +public class SettingsController { + + public record ThemeRequest(String theme) { + } + + private final SettingsService settingsService; + + public SettingsController(SettingsService settingsService) { + this.settingsService = settingsService; + } + + /** "Make sure this user has a settings row and give it to me." Safe to repeat, so it is a PUT. */ + @PutMapping + public Settings getOrCreate(@PathVariable long userId, + @RequestParam(defaultValue = "on-conflict") String strategy) { + return settingsService.getOrCreate(Strategy.from(strategy), userId); + } + + @PutMapping("/theme") + public Settings saveTheme(@PathVariable long userId, @RequestBody ThemeRequest request) { + if (request.theme() == null || request.theme().isBlank()) { + throw new IllegalArgumentException("theme is required"); + } + return settingsService.saveTheme(userId, request.theme()); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/SettingsService.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/SettingsService.java new file mode 100644 index 0000000..46d3a79 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/SettingsService.java @@ -0,0 +1,55 @@ +package com.amigoscode.constraints.settings; + +import com.amigoscode.constraints.user.UserNotFoundException; +import com.amigoscode.constraints.user.UserRepository; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.stereotype.Service; + +/** Picks the strategy. Deliberately NOT transactional: every SettingsStore method is its own transaction. */ +@Service +public class SettingsService { + + private final SettingsStore store; + private final UserRepository users; + + public SettingsService(SettingsStore store, UserRepository users) { + this.store = store; + this.users = users; + } + + /** Returns the user's settings, creating the row with the defaults the first time it is asked for. */ + public Settings getOrCreate(Strategy strategy, long userId) { + requireUser(userId); + return switch (strategy) { + case CHECK_FIRST -> store.checkThenInsert(userId); + case CATCH_INSIDE -> store.insertAndCatchInside(userId); + case CATCH_OUTSIDE -> insertAndCatchOutside(userId); + case SAVEPOINT -> store.insertWithSavepoint(userId); + case ON_CONFLICT -> store.insertOnConflictDoNothing(userId); + }; + } + + public Settings saveTheme(long userId, String theme) { + requireUser(userId); + return store.saveTheme(userId, theme); + } + + /** + * Correct shape 1: the insert runs in its own transaction. When it fails, that transaction is + * rolled back and finished before the exception arrives here, so the read starts a fresh one. + */ + private Settings insertAndCatchOutside(long userId) { + try { + store.insertDefaults(userId); + return new Settings(userId, store.find(userId).theme(), true); + } catch (DuplicateKeyException e) { + return store.find(userId); + } + } + + private void requireUser(long userId) { + if (!users.existsById(userId)) { + throw new UserNotFoundException(userId); + } + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/SettingsStore.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/SettingsStore.java new file mode 100644 index 0000000..f84801f --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/SettingsStore.java @@ -0,0 +1,132 @@ +package com.amigoscode.constraints.settings; + +import com.amigoscode.constraints.work.SlowWork; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +/** + * One database transaction per method, plain SQL through JdbcTemplate. user_settings has user_id as + * its primary key, so the database already refuses a second row for the same user. The methods + * differ in what they do about that refusal. + * + *

checkThenInsert and insertAndCatchInside stay broken for ever, so you can always compare + * against them. insertDefaults and insertWithSavepoint already work. You write the last two. + */ +@Repository +public class SettingsStore { + + private static final String INSERT_DEFAULTS = "insert into user_settings (user_id) values (?)"; + + private final JdbcTemplate jdbc; + private final SlowWork work; + + public SettingsStore(JdbcTemplate jdbc, SlowWork work) { + this.jdbc = jdbc; + this.work = work; + } + + /** + * The bug: check, then insert. Do not fix this one. Two requests + * can both find nothing, and the slower one hits the primary key: a 500. + */ + @Transactional + public Settings checkThenInsert(long userId) { + if (exists(userId)) { // CHECK + return read(userId, false); + } + work.run("load the defaults"); // ...time passes... + jdbc.update(INSERT_DEFAULTS, userId); // INSERT + return read(userId, true); + } + + /** + * The trap. Do not fix this one either: insert first, catch the duplicate, carry on in the SAME transaction. + * In Postgres a failed statement aborts the whole transaction, so the read in the catch block + * fails with "current transaction is aborted, commands ignored until end of transaction block". + */ + @Transactional + public Settings insertAndCatchInside(long userId) { + try { + jdbc.update(INSERT_DEFAULTS, userId); + return read(userId, true); + } catch (DuplicateKeyException e) { + return read(userId, false); // never works: the transaction is dead + } + } + + /** Correct shape 1, first half: only the insert. SettingsService catches the duplicate OUTSIDE this transaction. */ + @Transactional + public void insertDefaults(long userId) { + jdbc.update(INSERT_DEFAULTS, userId); + } + + /** + * Correct shape 2: a savepoint. ROLLBACK TO SAVEPOINT undoes the failed insert only, and the + * transaction is usable again. + */ + @Transactional + public Settings insertWithSavepoint(long userId) { + jdbc.execute("savepoint before_insert"); + boolean created; + try { + jdbc.update(INSERT_DEFAULTS, userId); + jdbc.execute("release savepoint before_insert"); + created = true; + } catch (DuplicateKeyException e) { + jdbc.execute("rollback to savepoint before_insert"); + created = false; + } + return read(userId, created); + } + + /** + * TODO Task 6: correct shape 3. Ask the database to skip the insert when the row is already + * there, in one statement, and use the number of rows it inserted to fill in "created". + * + *

As shipped this is the same bug as checkThenInsert. + */ + @Transactional + public Settings insertOnConflictDoNothing(long userId) { + if (exists(userId)) { + return read(userId, false); + } + work.run("load the defaults"); + jdbc.update(INSERT_DEFAULTS, userId); + return read(userId, true); + } + + /** + * "Set the theme, whether or not the row exists yet." + * + *

TODO Task 6: one statement that inserts the row or updates it, and that says which of the + * two it did. + * + *

As shipped it updates, and inserts when the update changed 0 rows. Two requests can both + * change 0 rows. + */ + @Transactional + public Settings saveTheme(long userId, String theme) { + int updated = jdbc.update("update user_settings set theme = ?, updated_at = now() where user_id = ?", theme, userId); + if (updated == 0) { + work.run("load the defaults"); + jdbc.update("insert into user_settings (user_id, theme) values (?, ?)", userId, theme); + } + return new Settings(userId, theme, updated == 0); + } + + @Transactional(readOnly = true) + public Settings find(long userId) { + return read(userId, false); + } + + private boolean exists(long userId) { + return jdbc.queryForObject("select count(*) from user_settings where user_id = ?", Integer.class, userId) > 0; + } + + private Settings read(long userId, boolean created) { + return jdbc.queryForObject("select user_id, theme from user_settings where user_id = ?", + (row, n) -> new Settings(row.getLong("user_id"), row.getString("theme"), created), userId); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/Strategy.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/Strategy.java new file mode 100644 index 0000000..856787c --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/settings/Strategy.java @@ -0,0 +1,37 @@ +package com.amigoscode.constraints.settings; + +import java.util.Arrays; +import java.util.Locale; +import java.util.stream.Collectors; + +/** How "give me this user's settings, create them if they do not exist yet" is done. Chosen with ?strategy=. */ +public enum Strategy { + CHECK_FIRST, + CATCH_INSIDE, + CATCH_OUTSIDE, + SAVEPOINT, + ON_CONFLICT; + + public static Strategy from(String value) { + try { + return valueOf(value.trim().toUpperCase(Locale.ROOT).replace('-', '_')); + } catch (IllegalArgumentException | NullPointerException e) { + throw new UnknownStrategyException(value); + } + } + + public String label() { + return name().toLowerCase(Locale.ROOT).replace('_', '-'); + } + + public static String names() { + return Arrays.stream(values()).map(Strategy::label).collect(Collectors.joining(", ")); + } + + public static class UnknownStrategyException extends RuntimeException { + + public UnknownStrategyException(String value) { + super("Unknown strategy '" + value + "'. Use one of: " + names()); + } + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/AlreadySubscribedException.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/AlreadySubscribedException.java new file mode 100644 index 0000000..8d8dc96 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/AlreadySubscribedException.java @@ -0,0 +1,8 @@ +package com.amigoscode.constraints.subscription; + +public class AlreadySubscribedException extends RuntimeException { + + public AlreadySubscribedException(long userId) { + super("User " + userId + " already has an active subscription"); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/Plan.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/Plan.java new file mode 100644 index 0000000..a918dd9 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/Plan.java @@ -0,0 +1,27 @@ +package com.amigoscode.constraints.subscription; + +import java.util.Locale; + +public enum Plan { + BASIC(900), + PRO(2900); + + private final int priceCents; + + Plan(int priceCents) { + this.priceCents = priceCents; + } + + /** Monthly price of one seat, in cents. */ + public int priceCents() { + return priceCents; + } + + public static Plan from(String value) { + try { + return valueOf(value.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException | NullPointerException e) { + throw new IllegalArgumentException("Unknown plan '" + value + "'. Use one of: basic, pro"); + } + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/Status.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/Status.java new file mode 100644 index 0000000..624b6ca --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/Status.java @@ -0,0 +1,6 @@ +package com.amigoscode.constraints.subscription; + +public enum Status { + ACTIVE, + CANCELLED +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/Subscription.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/Subscription.java new file mode 100644 index 0000000..08c84bd --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/Subscription.java @@ -0,0 +1,87 @@ +package com.amigoscode.constraints.subscription; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import java.time.Instant; + +@Entity +@Table(name = "subscriptions") +public class Subscription { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "user_id") + private long userId; + + @Enumerated(EnumType.STRING) + private Plan plan; + + private int seats; + + /** Monthly price of one seat after the coupon, in cents. */ + @Column(name = "price_cents") + private int priceCents; + + @Enumerated(EnumType.STRING) + private Status status; + + @Column(name = "started_at") + private Instant startedAt; + + protected Subscription() { + } + + public Subscription(long userId, Plan plan, int seats, int priceCents) { + this.userId = userId; + this.plan = plan; + this.seats = seats; + this.priceCents = priceCents; + this.status = Status.ACTIVE; + this.startedAt = Instant.now(); + } + + public void cancel() { + this.status = Status.CANCELLED; + } + + public Long getId() { + return id; + } + + public long getUserId() { + return userId; + } + + public Plan getPlan() { + return plan; + } + + public int getSeats() { + return seats; + } + + public int getPriceCents() { + return priceCents; + } + + public Status getStatus() { + return status; + } + + public Instant getStartedAt() { + return startedAt; + } + + @Override + public String toString() { + return "Subscription #" + id + " of user " + userId + " " + status; + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/SubscriptionController.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/SubscriptionController.java new file mode 100644 index 0000000..f019356 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/SubscriptionController.java @@ -0,0 +1,48 @@ +package com.amigoscode.constraints.subscription; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/subscriptions") +public class SubscriptionController { + + /** seats defaults to 1 and couponCents to 0 when they are left out. */ + public record SubscribeRequest(long userId, String plan, Integer seats, Integer couponCents) { + } + + public record SubscriptionResponse(long id, long userId, String plan, int seats, int priceCents, String status) { + + static SubscriptionResponse of(Subscription subscription) { + return new SubscriptionResponse(subscription.getId(), subscription.getUserId(), + subscription.getPlan().name(), subscription.getSeats(), subscription.getPriceCents(), + subscription.getStatus().name()); + } + } + + private final SubscriptionService subscriptionService; + + public SubscriptionController(SubscriptionService subscriptionService) { + this.subscriptionService = subscriptionService; + } + + /** No validation of seats or the coupon, on purpose: Task 7 shows what the database does about it. */ + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public SubscriptionResponse subscribe(@RequestBody SubscribeRequest request) { + int seats = request.seats() == null ? 1 : request.seats(); + int couponCents = request.couponCents() == null ? 0 : request.couponCents(); + return SubscriptionResponse.of( + subscriptionService.subscribe(request.userId(), Plan.from(request.plan()), seats, couponCents)); + } + + @PostMapping("/{id}/cancel") + public SubscriptionResponse cancel(@PathVariable long id) { + return SubscriptionResponse.of(subscriptionService.cancel(id)); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/SubscriptionNotFoundException.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/SubscriptionNotFoundException.java new file mode 100644 index 0000000..b9f772d --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/SubscriptionNotFoundException.java @@ -0,0 +1,8 @@ +package com.amigoscode.constraints.subscription; + +public class SubscriptionNotFoundException extends RuntimeException { + + public SubscriptionNotFoundException(long subscriptionId) { + super("Subscription " + subscriptionId + " does not exist"); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/SubscriptionRepository.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/SubscriptionRepository.java new file mode 100644 index 0000000..9a77639 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/SubscriptionRepository.java @@ -0,0 +1,8 @@ +package com.amigoscode.constraints.subscription; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface SubscriptionRepository extends JpaRepository { + + boolean existsByUserIdAndStatus(long userId, Status status); +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/SubscriptionService.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/SubscriptionService.java new file mode 100644 index 0000000..2284f2f --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/subscription/SubscriptionService.java @@ -0,0 +1,39 @@ +package com.amigoscode.constraints.subscription; + +import com.amigoscode.constraints.work.SlowWork; +import org.springframework.stereotype.Service; + +/** Deliberately NOT transactional, for the same reason as SignupService. */ +@Service +public class SubscriptionService { + + private final SubscriptionRepository subscriptions; + private final SlowWork work; + + public SubscriptionService(SubscriptionRepository subscriptions, SlowWork work) { + this.subscriptions = subscriptions; + this.work = work; + } + + /** + * The rule: a user has at most one ACTIVE subscription. Cancelled ones are history. + * + *

TODO Task 5: the same race as the signup. Keep the check, make the database enforce the + * rule (schema.sql), and turn its refusal into an AlreadySubscribedException. + */ + public Subscription subscribe(long userId, Plan plan, int seats, int couponCents) { + if (subscriptions.existsByUserIdAndStatus(userId, Status.ACTIVE)) { // CHECK + throw new AlreadySubscribedException(userId); + } + work.run("charge the card"); // ...time passes... + int priceCents = plan.priceCents() - couponCents; + return subscriptions.save(new Subscription(userId, plan, seats, priceCents)); // INSERT + } + + public Subscription cancel(long subscriptionId) { + Subscription subscription = subscriptions.findById(subscriptionId) + .orElseThrow(() -> new SubscriptionNotFoundException(subscriptionId)); + subscription.cancel(); + return subscriptions.save(subscription); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/EmailTakenException.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/EmailTakenException.java new file mode 100644 index 0000000..f17b19a --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/EmailTakenException.java @@ -0,0 +1,8 @@ +package com.amigoscode.constraints.user; + +public class EmailTakenException extends RuntimeException { + + public EmailTakenException(String email) { + super("An account with the email " + email + " already exists"); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/SignupController.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/SignupController.java new file mode 100644 index 0000000..024eec0 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/SignupController.java @@ -0,0 +1,33 @@ +package com.amigoscode.constraints.user; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/signups") +public class SignupController { + + public record SignupRequest(String email, String displayName) { + } + + public record SignupResponse(long id, String email) { + } + + private final SignupService signupService; + + public SignupController(SignupService signupService) { + this.signupService = signupService; + } + + /** No validation here, on purpose: Task 7 shows what the database does when the application forgets. */ + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public SignupResponse signUp(@RequestBody SignupRequest request) { + User user = signupService.signUp(request.email(), request.displayName()); + return new SignupResponse(user.getId(), user.getEmail()); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/SignupService.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/SignupService.java new file mode 100644 index 0000000..9ea19bc --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/SignupService.java @@ -0,0 +1,37 @@ +package com.amigoscode.constraints.user; + +import com.amigoscode.constraints.work.SlowWork; +import org.springframework.stereotype.Service; + +/** + * Deliberately NOT transactional. users.save runs in its own short transaction, so when the + * database refuses a row that transaction is already over by the time the exception arrives here. + * Task 6 shows what goes wrong when you catch it inside the transaction instead. + */ +@Service +public class SignupService { + + private final UserRepository users; + private final SlowWork work; + + public SignupService(UserRepository users, SlowWork work) { + this.users = users; + this.work = work; + } + + /** + * THE BUG IS HERE. Check, then insert: nothing ties the two together. + * + *

TODO Task 2: keep the check. Make the database refuse the second row (schema.sql), and + * turn that refusal into an EmailTakenException. + * + *

TODO Task 4: Ana@Example.com and ana@example.com are the same address. + */ + public User signUp(String email, String displayName) { + if (users.existsByEmail(email)) { // CHECK + throw new EmailTakenException(email); + } + work.run("hash the password"); // ...time passes... + return users.save(new User(email, displayName)); // INSERT + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/User.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/User.java new file mode 100644 index 0000000..58f40af --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/User.java @@ -0,0 +1,57 @@ +package com.amigoscode.constraints.user; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import java.time.Instant; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + /** Stored exactly as the user typed it. */ + private String email; + + @Column(name = "display_name") + private String displayName; + + @Column(name = "created_at") + private Instant createdAt; + + protected User() { + } + + public User(String email, String displayName) { + this.email = email; + this.displayName = displayName; + this.createdAt = Instant.now(); + } + + public Long getId() { + return id; + } + + public String getEmail() { + return email; + } + + public String getDisplayName() { + return displayName; + } + + public Instant getCreatedAt() { + return createdAt; + } + + @Override + public String toString() { + return "User #" + id + " " + email; + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/UserNotFoundException.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/UserNotFoundException.java new file mode 100644 index 0000000..e367fe3 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/UserNotFoundException.java @@ -0,0 +1,8 @@ +package com.amigoscode.constraints.user; + +public class UserNotFoundException extends RuntimeException { + + public UserNotFoundException(long userId) { + super("User " + userId + " does not exist"); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/UserRepository.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/UserRepository.java new file mode 100644 index 0000000..cfbf519 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/user/UserRepository.java @@ -0,0 +1,8 @@ +package com.amigoscode.constraints.user; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { + + boolean existsByEmail(String email); +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/work/SleepingSlowWork.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/work/SleepingSlowWork.java new file mode 100644 index 0000000..7eaa974 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/work/SleepingSlowWork.java @@ -0,0 +1,27 @@ +package com.amigoscode.constraints.work; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class SleepingSlowWork implements SlowWork { + + private final long millis; + + public SleepingSlowWork(@Value("${app.work-millis:100}") long millis) { + this.millis = millis; + } + + @Override + public void run(String step) { + if (millis <= 0) { + return; + } + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while: " + step, e); + } + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/work/SlowWork.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/work/SlowWork.java new file mode 100644 index 0000000..f4a2cb0 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/java/com/amigoscode/constraints/work/SlowWork.java @@ -0,0 +1,11 @@ +package com.amigoscode.constraints.work; + +/** + * Stands in for the work a real application does between checking and inserting: hashing the + * password, charging the card, loading the defaults. It takes time, and that time is the window in + * which a second request can run the same check and get the same answer. + */ +public interface SlowWork { + + void run(String step); +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/resources/application.properties b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/resources/application.properties new file mode 100644 index 0000000..9df847f --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/resources/application.properties @@ -0,0 +1,20 @@ +spring.application.name=constraints-and-races + +# Postgres from compose.yaml. Port 5449 so it does not clash with a Postgres you already run. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5449/app} +spring.datasource.username=${DB_USER:app} +spring.datasource.password=${DB_PASSWORD:app} + +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false + +# schema.sql is run on every start. It drops the tables and creates them again, so the database +# always has exactly the constraints that are written in that file. +spring.sql.init.mode=always + +# How long the work between a check and an insert takes, in milliseconds (hashing the password, +# charging the card). +app.work-millis=100 + +# Uncomment to see every SQL statement (or run ./demo --sql). +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/main/resources/schema.sql b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/resources/schema.sql new file mode 100644 index 0000000..17dd02d --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/main/resources/schema.sql @@ -0,0 +1,35 @@ +-- This file is run every time the application starts (./demo, ./check, ./mvnw verify). +-- It drops the tables and creates them again, so the database always has exactly the +-- constraints written here. To add a constraint: edit this file and run the command again. + +drop table if exists subscriptions, user_settings, users cascade; + +create table users ( + id bigserial primary key, + email text, + display_name text, + created_at timestamptz not null default now() + -- TODO Task 2: two rows may not have the same email. + -- TODO Task 7: a user must have an email. +); + +-- TODO Task 4: Ana@Example.com and ana@example.com are the same address. + +create table subscriptions ( + id bigserial primary key, + user_id bigint not null, + plan text not null, + seats int not null, + price_cents int not null, + status text not null constraint subscriptions_status_check check (status in ('ACTIVE', 'CANCELLED')), + started_at timestamptz not null default now() + -- TODO Task 7: no subscription for a user that does not exist, no seats below 1, no negative price. +); + +-- TODO Task 5: one ACTIVE subscription per user. Cancelled ones may repeat. + +create table user_settings ( + user_id bigint primary key references users (id), + theme text not null default 'light', + updated_at timestamptz not null default now() +); diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/ApiContractTest.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/ApiContractTest.java new file mode 100644 index 0000000..0e9ca02 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/ApiContractTest.java @@ -0,0 +1,140 @@ +package com.amigoscode.constraints; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.amigoscode.constraints.settings.Settings; +import com.amigoscode.constraints.settings.SettingsController; +import com.amigoscode.constraints.settings.SettingsService; +import com.amigoscode.constraints.settings.Strategy; +import com.amigoscode.constraints.subscription.AlreadySubscribedException; +import com.amigoscode.constraints.subscription.Plan; +import com.amigoscode.constraints.subscription.Subscription; +import com.amigoscode.constraints.subscription.SubscriptionController; +import com.amigoscode.constraints.subscription.SubscriptionService; +import com.amigoscode.constraints.user.EmailTakenException; +import com.amigoscode.constraints.user.SignupController; +import com.amigoscode.constraints.user.SignupService; +import com.amigoscode.constraints.user.User; +import com.amigoscode.constraints.user.UserNotFoundException; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +/** + * Unit tests for the HTTP contract: no Spring context, no database, the services are stubs. They + * pass from the start and must keep passing: whatever you change in the services, a request that + * loses a race must get a clear 409, never a 500. + */ +@Tag("baseline") +class ApiContractTest { + + private static final String SIGNUP = "{\"email\":\"ana@example.com\",\"displayName\":\"Ana\"}"; + private static final String SUBSCRIBE = "{\"userId\":7,\"plan\":\"pro\"}"; + + @Test + @DisplayName("HTTP: a signup returns 201 with the user id and the email") + void signupReturnsCreated() throws Exception { + User user = new User("ana@example.com", "Ana"); + ReflectionTestUtils.setField(user, "id", 42L); + + signups(() -> user).perform(post("/api/signups").contentType(MediaType.APPLICATION_JSON).content(SIGNUP)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id").value(42)) + .andExpect(jsonPath("$.email").value("ana@example.com")); + } + + @Test + @DisplayName("HTTP: an email that is taken returns 409 EMAIL_TAKEN") + void emailTakenReturnsConflict() throws Exception { + signups(() -> { + throw new EmailTakenException("ana@example.com"); + }).perform(post("/api/signups").contentType(MediaType.APPLICATION_JSON).content(SIGNUP)) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.code").value("EMAIL_TAKEN")); + } + + @Test + @DisplayName("HTTP: a subscription returns 201 with its id, plan and status") + void subscriptionReturnsCreated() throws Exception { + Subscription subscription = new Subscription(7, Plan.PRO, 1, 2900); + ReflectionTestUtils.setField(subscription, "id", 5L); + + subscriptions(() -> subscription).perform(post("/api/subscriptions").contentType(MediaType.APPLICATION_JSON).content(SUBSCRIBE)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id").value(5)) + .andExpect(jsonPath("$.plan").value("PRO")) + .andExpect(jsonPath("$.status").value("ACTIVE")); + } + + @Test + @DisplayName("HTTP: a second active subscription returns 409 ALREADY_SUBSCRIBED") + void alreadySubscribedReturnsConflict() throws Exception { + subscriptions(() -> { + throw new AlreadySubscribedException(7); + }).perform(post("/api/subscriptions").contentType(MediaType.APPLICATION_JSON).content(SUBSCRIBE)) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.code").value("ALREADY_SUBSCRIBED")); + } + + @Test + @DisplayName("HTTP: settings of an unknown user return 404 USER_NOT_FOUND") + void unknownUserReturnsNotFound() throws Exception { + settings(() -> { + throw new UserNotFoundException(7); + }).perform(put("/api/users/7/settings")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.code").value("USER_NOT_FOUND")); + } + + @Test + @DisplayName("HTTP: an unknown settings strategy returns 400") + void unknownStrategyReturnsBadRequest() throws Exception { + settings(() -> new Settings(7, "light", true)).perform(put("/api/users/7/settings?strategy=hope")) + .andExpect(status().isBadRequest()); + } + + /** Each controller wired to a service that does whatever the test says. */ + private static MockMvc signups(Supplier signUp) { + SignupService stub = new SignupService(null, null) { + @Override + public User signUp(String email, String displayName) { + return signUp.get(); + } + }; + return api(new SignupController(stub)); + } + + private static MockMvc subscriptions(Supplier subscribe) { + SubscriptionService stub = new SubscriptionService(null, null) { + @Override + public Subscription subscribe(long userId, Plan plan, int seats, int couponCents) { + return subscribe.get(); + } + }; + return api(new SubscriptionController(stub)); + } + + private static MockMvc settings(Supplier getOrCreate) { + SettingsService stub = new SettingsService(null, null) { + @Override + public Settings getOrCreate(Strategy strategy, long userId) { + return getOrCreate.get(); + } + }; + return api(new SettingsController(stub)); + } + + private static MockMvc api(Object controller) { + return MockMvcBuilders.standaloneSetup(controller) + .setControllerAdvice(new ApiExceptionHandler()) + .build(); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/BadDataIT.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/BadDataIT.java new file mode 100644 index 0000000..70152e9 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/BadDataIT.java @@ -0,0 +1,76 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.amigoscode.constraints.subscription.Plan; +import com.amigoscode.constraints.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataIntegrityViolationException; + +/** + * Task 7. The application validates none of this, and it stays that way: these tests are about the + * database. Each one tries the bad row twice, with plain SQL and through the service. + */ +@Tag("task7") +class BadDataIT extends IntegrationTest { + + private static final long MISSING_USER = 999_999; + private static final String INSERT_SUBSCRIPTION = + "insert into subscriptions (user_id, plan, seats, price_cents, status) values (?, 'PRO', ?, ?, 'CANCELLED')"; + + @Test + @DisplayName("NOT NULL: a user without an email is refused by the database, and a signup without one stores nothing") + void aUserNeedsAnEmail() { + assertThatThrownBy(() -> jdbc.update("insert into users (email, display_name) values (null, 'No Email')")) + .as("a plain SQL insert with email = NULL") + .isInstanceOf(DataIntegrityViolationException.class); + + catchThrowable(() -> signupService.signUp(null, "No Email")); + + assertThat(userRows()).as("rows in users").isEqualTo(0); + } + + @Test + @DisplayName("CHECK: a subscription with -3 seats is refused by the database, and subscribing with -3 seats stores nothing") + void seatsMustBePositive() { + long user = insertUser("bo@example.com"); + + assertThatThrownBy(() -> jdbc.update(INSERT_SUBSCRIPTION, user, -3, 2900)) + .as("a plain SQL insert with seats = -3") + .isInstanceOf(DataIntegrityViolationException.class); + + catchThrowable(() -> subscriptionService.subscribe(user, Plan.PRO, -3, 0)); + + assertThat(subscriptionRows()).as("rows in subscriptions").isEqualTo(0); + } + + @Test + @DisplayName("CHECK: a negative price is refused by the database, and a coupon bigger than the price stores nothing") + void thePriceMustNotBeNegative() { + long user = insertUser("cy@example.com"); + + assertThatThrownBy(() -> jdbc.update(INSERT_SUBSCRIPTION, user, 1, -4100)) + .as("a plain SQL insert with price_cents = -4100") + .isInstanceOf(DataIntegrityViolationException.class); + + catchThrowable(() -> subscriptionService.subscribe(user, Plan.BASIC, 1, 5000)); + + assertThat(subscriptionRows()).as("rows in subscriptions").isEqualTo(0); + } + + @Test + @DisplayName("FOREIGN KEY: a subscription for a user that does not exist is refused by the database, and subscribing one stores nothing") + void aSubscriptionNeedsAUser() { + assertThatThrownBy(() -> jdbc.update(INSERT_SUBSCRIPTION, MISSING_USER, 1, 2900)) + .as("a plain SQL insert with a user_id that is not in users") + .isInstanceOf(DataIntegrityViolationException.class); + + catchThrowable(() -> subscriptionService.subscribe(MISSING_USER, Plan.PRO, 1, 0)); + + assertThat(subscriptionRows()).as("rows in subscriptions").isEqualTo(0); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/CaseInsensitiveEmailIT.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/CaseInsensitiveEmailIT.java new file mode 100644 index 0000000..052d4a6 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/CaseInsensitiveEmailIT.java @@ -0,0 +1,56 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.constraints.support.IntegrationTest; +import com.amigoscode.constraints.support.Race; +import com.amigoscode.constraints.user.EmailTakenException; +import com.amigoscode.constraints.user.User; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DuplicateKeyException; + +@Tag("task4") +class CaseInsensitiveEmailIT extends IntegrationTest { + + @Test + @DisplayName("Case: the database refuses ana@example.com when Ana@Example.com is already there, even from code that skips the service") + void theDatabaseRefusesTheSameEmailInAnotherCase() { + insertUser("Ana@Example.com"); + + assertThatThrownBy(() -> insertUser("ana@example.com")) + .as("a plain SQL insert of the same address in lower case") + .isInstanceOf(DuplicateKeyException.class); + assertThat(userRows()).as("rows in users").isEqualTo(1); + } + + @Test + @DisplayName("Case: Ana@Example.com and ana@example.com sign up at the same moment: one account, the other is told the email is taken") + void onlyOneOfTwoSpellingsCreatesAnAccount() { + List spellings = List.of("Ana@Example.com", "ana@example.com"); + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.Result result = Race.run(2, i -> () -> signupService.signUp(spellings.get(i), "Ana")); + + assertThat(result.failedWithAnythingBut(EmailTakenException.class)).as("errors that would be a 500").isEmpty(); + assertThat(result.succeeded()).as("accounts created").hasSize(1); + assertThat(result.failedWith(EmailTakenException.class)).as("requests told the email is taken").isEqualTo(1); + assertThat(userRows()).as("rows in users").isEqualTo(1); + } + + @Test + @DisplayName("Case: ANA@EXAMPLE.COM arriving after ana@example.com is stopped by the application's check, before any insert is tried") + void aLaterSignupInAnotherCaseIsStoppedByTheFastPath() { + signupService.signUp("ana@example.com", "Ana"); + + assertThatThrownBy(() -> signupService.signUp("ANA@EXAMPLE.COM", "Ana again")) + .isInstanceOf(EmailTakenException.class); + + assertThat(work.arrivals()) + .as("signups that got past the email check (the second one must not)") + .isEqualTo(1); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/Check.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/Check.java new file mode 100644 index 0000000..631c6b6 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/Check.java @@ -0,0 +1,115 @@ +package com.amigoscode.constraints; + +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage; + +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.platform.engine.TestExecutionResult; +import org.junit.platform.engine.discovery.ClassNameFilter; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +import org.junit.platform.launcher.TagFilter; +import org.junit.platform.launcher.TestExecutionListener; +import org.junit.platform.launcher.TestIdentifier; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; + +/** + * Runs the tests that belong to one task and prints one line per acceptance criterion. + * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2 + * (./mvnw verify runs the same tests the usual Maven way.) + */ +public final class Check { + + /** Tasks that have tests. Tasks 3 and 8 are inspection tasks: you answer questions, no code. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: the HTTP contract (passes from the start, must stay green)"); + TASKS.put("1", "Task 1: See the duplicate signup"); + TASKS.put("2", "Task 2: Fix it with a UNIQUE constraint and a 409"); + TASKS.put("4", "Task 4: The same email in different capital letters"); + TASKS.put("5", "Task 5: One ACTIVE subscription per user"); + TASKS.put("6", "Task 6: Create if absent, and the aborted transaction"); + TASKS.put("7", "Task 7: Bad data: NOT NULL, CHECK and FOREIGN KEY"); + } + + public static void main(String[] args) { + if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-8]"))) { + System.out.println("Usage: ./check [task] task is a number from 1 to 8. No number checks everything."); + System.exit(2); + } + if (args.length == 1 && !TASKS.containsKey(args[0])) { + System.out.println(); + System.out.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:"); + System.out.println("follow its steps in INTERVIEW_TASKS.md and answer the questions."); + System.out.println(); + return; + } + + boolean allGreen = true; + Launcher launcher = LauncherFactory.create(); + for (Map.Entry task : TASKS.entrySet()) { + if (args.length == 1 && !task.getKey().equals(args[0])) { + continue; + } + String tag = task.getKey().equals("baseline") ? "baseline" : "task" + task.getKey(); + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() + .selectors(selectPackage(Check.class.getPackageName())) + .filters(ClassNameFilter.includeClassNamePatterns(".*"), TagFilter.includeTags(tag)) + .build(); + System.out.println(); + System.out.println(task.getValue()); + Results results = new Results(); + launcher.execute(request, results); + System.out.println(" " + results.passed + " of " + results.total + " pass"); + allGreen &= results.passed == results.total && results.total > 0; + } + System.out.println(); + System.exit(allGreen ? 0 : 1); + } + + private static final class Results implements TestExecutionListener { + + private int total; + private int passed; + + @Override + public void executionFinished(TestIdentifier test, TestExecutionResult result) { + boolean ok = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL; + if (!test.isTest()) { + // A container that fails (for example the Spring context cannot start) takes its tests with it. + if (!ok) { + total++; + System.out.println(" [FAIL] " + test.getDisplayName() + " could not start"); + result.getThrowable().ifPresent(Results::printReason); + } + return; + } + total++; + if (ok) { + passed++; + System.out.println(" [PASS] " + test.getDisplayName()); + } else { + System.out.println(" [FAIL] " + test.getDisplayName()); + result.getThrowable().ifPresent(Results::printReason); + } + } + + private static void printReason(Throwable throwable) { + Throwable root = throwable; + while (root.getCause() != null && root.getCause() != root && root.getMessage() == null) { + root = root.getCause(); + } + String message = root.getMessage() == null ? root.getClass().getSimpleName() : root.getMessage(); + message.strip().lines() + .map(String::strip) + .filter(line -> !line.isEmpty() && !line.startsWith("at ") && !line.startsWith("...(")) + .limit(6) + .forEach(line -> System.out.println(" " + line)); + } + } + + private Check() { + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/OneActiveSubscriptionIT.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/OneActiveSubscriptionIT.java new file mode 100644 index 0000000..cf0846e --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/OneActiveSubscriptionIT.java @@ -0,0 +1,72 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.constraints.subscription.AlreadySubscribedException; +import com.amigoscode.constraints.subscription.Plan; +import com.amigoscode.constraints.subscription.Subscription; +import com.amigoscode.constraints.support.IntegrationTest; +import com.amigoscode.constraints.support.Race; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DuplicateKeyException; + +@Tag("task5") +class OneActiveSubscriptionIT extends IntegrationTest { + + private static final String INSERT_ACTIVE = + "insert into subscriptions (user_id, plan, seats, price_cents, status) values (?, 'PRO', 1, 2900, 'ACTIVE')"; + + @Test + @DisplayName("Partial: the database refuses a second ACTIVE subscription for the same user, even from code that skips the service") + void theDatabaseRefusesASecondActiveRow() { + long user = insertUser("sam@example.com"); + jdbc.update(INSERT_ACTIVE, user); + + assertThatThrownBy(() -> jdbc.update(INSERT_ACTIVE, user)) + .as("a plain SQL insert of a second ACTIVE row") + .isInstanceOf(DuplicateKeyException.class); + assertThat(subscriptionRows(user, "ACTIVE")).as("ACTIVE rows").isEqualTo(1); + } + + @Test + @DisplayName("Partial: one user subscribes twice at the same moment: one ACTIVE subscription, the other request is told the user is already subscribed") + void onlyOneOfTwoRequestsSubscribes() { + long user = insertUser("sam@example.com"); + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.Result result = Race.run(2, () -> subscriptionService.subscribe(user, Plan.PRO, 1, 0)); + + assertThat(result.failedWithAnythingBut(AlreadySubscribedException.class)).as("errors that would be a 500").isEmpty(); + assertThat(result.succeeded()).as("subscriptions started").hasSize(1); + assertThat(result.failedWith(AlreadySubscribedException.class)).as("requests told already subscribed").isEqualTo(1); + assertThat(subscriptionRows(user, "ACTIVE")).as("ACTIVE rows").isEqualTo(1); + } + + @Test + @DisplayName("Partial: cancelled subscriptions may repeat: subscribe, cancel, subscribe, cancel, subscribe leaves 2 CANCELLED rows and 1 ACTIVE row") + void cancelledRowsMayRepeat() { + long user = insertUser("sam@example.com"); + + subscriptionService.cancel(subscriptionService.subscribe(user, Plan.BASIC, 1, 0).getId()); + subscriptionService.cancel(subscriptionService.subscribe(user, Plan.PRO, 1, 0).getId()); + subscriptionService.subscribe(user, Plan.PRO, 1, 0); + + assertThat(subscriptionRows(user, "CANCELLED")).as("CANCELLED rows").isEqualTo(2); + assertThat(subscriptionRows(user, "ACTIVE")).as("ACTIVE rows").isEqualTo(1); + } + + @Test + @DisplayName("Partial: the rule is per user: two different users are both ACTIVE at the same time") + void twoUsersCanBothBeActive() { + long sam = insertUser("sam@example.com"); + long lee = insertUser("lee@example.com"); + + subscriptionService.subscribe(sam, Plan.PRO, 1, 0); + subscriptionService.subscribe(lee, Plan.PRO, 1, 0); + + assertThat(subscriptionRows(sam, "ACTIVE") + subscriptionRows(lee, "ACTIVE")).as("ACTIVE rows").isEqualTo(2); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/SettingsIT.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/SettingsIT.java new file mode 100644 index 0000000..f694c6f --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/SettingsIT.java @@ -0,0 +1,146 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.constraints.settings.Settings; +import com.amigoscode.constraints.settings.Strategy; +import com.amigoscode.constraints.support.IntegrationTest; +import com.amigoscode.constraints.support.Race; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Task 6. user_settings has user_id as its primary key, so there can never be two rows for one + * user. These tests are about what the application does when the database says no. The first + * three pass on purpose, before and after your fix: they document the bug and the trap. + */ +@Tag("task6") +class SettingsIT extends IntegrationTest { + + @Autowired + private PlatformTransactionManager transactionManager; + + @Test + @DisplayName("check-first: two first requests at the same moment: one of them fails on the primary key (this documents the bug)") + void checkFirstFailsUnderARace() { + long user = insertUser("lee@example.com"); + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.Result result = Race.run(2, () -> settingsService.getOrCreate(Strategy.CHECK_FIRST, user)); + + assertThat(result.succeeded()).as("requests that got the settings").hasSize(1); + assertThat(result.failedWith(DuplicateKeyException.class)).as("requests that hit the primary key").isEqualTo(1); + assertThat(settingsRows(user)).as("rows in user_settings").isEqualTo(1); + } + + @Test + @DisplayName("catch-inside: after a duplicate key is caught inside the transaction, the next statement fails: \"current transaction is aborted\" (this documents the trap)") + void catchingInsideTheTransactionDoesNotHelp() { + long user = insertUser("lee@example.com"); + settingsService.getOrCreate(Strategy.CATCH_INSIDE, user); + + assertThatThrownBy(() -> settingsService.getOrCreate(Strategy.CATCH_INSIDE, user)) + .as("the second call: the insert fails, the catch block reads the row") + .hasMessageContaining("current transaction is aborted, commands ignored until end of transaction block"); + } + + @Test + @DisplayName("swallow: a write, then a caught duplicate key, then a normal return: the commit reports nothing and the write is gone (this documents the trap)") + void swallowingInsideTheTransactionLosesEarlierWrites() { + long user = insertUser("lee@example.com"); + jdbc.update("insert into user_settings (user_id) values (?)", user); + + new TransactionTemplate(transactionManager).executeWithoutResult(transaction -> { + jdbc.update("update user_settings set theme = 'dark' where user_id = ?", user); // this worked + try { + jdbc.update("insert into user_settings (user_id) values (?)", user); // this is refused + } catch (DuplicateKeyException e) { + // swallowed. Nothing else touches the database, and the method returns normally. + } + }); + + assertThat(jdbc.queryForObject("select theme from user_settings where user_id = ?", String.class, user)) + .as("theme after a transaction that returned without any exception") + .isEqualTo("light"); + } + + @Test + @DisplayName("catch-outside: the duplicate key is caught after the transaction has ended: the second request gets the existing row") + void catchingOutsideTheTransactionWorks() { + long user = insertUser("lee@example.com"); + + assertThat(settingsService.getOrCreate(Strategy.CATCH_OUTSIDE, user).created()).as("first call created the row").isTrue(); + assertThat(settingsService.getOrCreate(Strategy.CATCH_OUTSIDE, user).created()).as("second call created the row").isFalse(); + assertThat(settingsRows(user)).as("rows in user_settings").isEqualTo(1); + } + + @Test + @DisplayName("savepoint: rolling back to a savepoint keeps the transaction alive: the second request gets the existing row") + void aSavepointKeepsTheTransactionAlive() { + long user = insertUser("lee@example.com"); + + assertThat(settingsService.getOrCreate(Strategy.SAVEPOINT, user).created()).as("first call created the row").isTrue(); + assertThat(settingsService.getOrCreate(Strategy.SAVEPOINT, user).created()).as("second call created the row").isFalse(); + assertThat(settingsRows(user)).as("rows in user_settings").isEqualTo(1); + } + + @Test + @DisplayName("on-conflict: two first requests at the same moment: both get the settings, one row, exactly one is told it created the row") + void onConflictDoNothingSurvivesARace() { + long user = insertUser("lee@example.com"); + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.Result result = Race.run(2, () -> settingsService.getOrCreate(Strategy.ON_CONFLICT, user)); + + assertThat(result.failed()).as("errors that would be a 500").isEmpty(); + assertThat(result.succeeded()).as("requests that got the settings").hasSize(2); + assertThat(result.succeeded().stream().filter(Settings::created).count()).as("requests told they created the row").isEqualTo(1); + assertThat(settingsRows(user)).as("rows in user_settings").isEqualTo(1); + } + + @Test + @DisplayName("on-conflict: an existing row is left alone: a saved theme is not reset to the default") + void onConflictDoNothingDoesNotOverwrite() { + long user = insertUser("lee@example.com"); + jdbc.update("insert into user_settings (user_id, theme) values (?, 'dark')", user); + + Settings settings = settingsService.getOrCreate(Strategy.ON_CONFLICT, user); + + assertThat(settings.theme()).as("theme").isEqualTo("dark"); + assertThat(settings.created()).as("created").isFalse(); + } + + @Test + @DisplayName("save theme: two saves at the same moment for a user without a row: both succeed, one row, exactly one is told it created the row") + void saveThemeSurvivesARace() { + long user = insertUser("kim@example.com"); + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.Result result = Race.run(2, () -> settingsService.saveTheme(user, "dark")); + + assertThat(result.failed()).as("errors that would be a 500").isEmpty(); + assertThat(result.succeeded()).as("saves that succeeded").hasSize(2); + assertThat(result.succeeded().stream().filter(Settings::created).count()).as("saves told they created the row").isEqualTo(1); + assertThat(settingsRows(user)).as("rows in user_settings").isEqualTo(1); + } + + @Test + @DisplayName("save theme: the first save creates the row, the second one updates it") + void saveThemeCreatesThenUpdates() { + long user = insertUser("kim@example.com"); + + Settings first = settingsService.saveTheme(user, "dark"); + Settings second = settingsService.saveTheme(user, "blue"); + + assertThat(first.created()).as("first save created the row").isTrue(); + assertThat(second.created()).as("second save created the row").isFalse(); + assertThat(jdbc.queryForObject("select theme from user_settings where user_id = ?", String.class, user)) + .as("theme in the database").isEqualTo("blue"); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/SignupRaceIT.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/SignupRaceIT.java new file mode 100644 index 0000000..d13faf2 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/SignupRaceIT.java @@ -0,0 +1,30 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.constraints.support.IntegrationTest; +import com.amigoscode.constraints.support.Race; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 1. This test passes on purpose, before and after your fixes: it pins down the race in the + * application's own check. No constraint makes that check trustworthy. A constraint only decides + * what happens to the second insert. + */ +@Tag("task1") +class SignupRaceIT extends IntegrationTest { + + @Test + @DisplayName("Signup: two requests with the same email are both told \"this email is free\" by the application's check (this documents the race)") + void bothRequestsPassTheCheck() { + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.run(2, () -> signupService.signUp("ana@example.com", "Ana")); + + assertThat(work.arrivals()) + .as("requests that got past the email check and went on to insert") + .isEqualTo(2); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/SignupServiceTest.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/SignupServiceTest.java new file mode 100644 index 0000000..b351626 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/SignupServiceTest.java @@ -0,0 +1,56 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.constraints.support.Stub; +import com.amigoscode.constraints.user.EmailTakenException; +import com.amigoscode.constraints.user.SignupService; +import com.amigoscode.constraints.user.UserRepository; +import java.sql.SQLException; +import org.hibernate.exception.ConstraintViolationException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataIntegrityViolationException; + +/** + * Unit tests: no Spring, no database. UserRepository is a stub whose check says "the email is free" + * and whose save fails the way the real one does when the database refuses the row, so only the + * translation in SignupService is under test. + */ +@Tag("task2") +class SignupServiceTest { + + @Test + @DisplayName("Translate: when the insert is refused by users_email_key, the signup fails with EmailTakenException (a 409, not a 500)") + void aViolationOfTheEmailConstraintMeansEmailTaken() { + SignupService service = serviceWhoseInsertViolates("users_email_key"); + + assertThatThrownBy(() -> service.signUp("ana@example.com", "Ana")) + .isInstanceOf(EmailTakenException.class); + } + + @Test + @DisplayName("Translate: a violation of any other constraint is not reported as \"email taken\"") + void aViolationOfAnotherConstraintIsNotEmailTaken() { + SignupService service = serviceWhoseInsertViolates("users_display_name_check"); + + assertThatThrownBy(() -> service.signUp("ana@example.com", "Ana")) + .isInstanceOf(DataIntegrityViolationException.class); + } + + private static SignupService serviceWhoseInsertViolates(String constraintName) { + UserRepository users = Stub.repository(UserRepository.class, user -> { + throw refusedBy(constraintName); + }); + return new SignupService(users, step -> { }); + } + + /** The exception users.save really throws: Spring's, wrapping Hibernate's, which knows the constraint name. */ + static DataIntegrityViolationException refusedBy(String constraintName) { + SQLException fromPostgres = new SQLException( + "ERROR: duplicate key value violates unique constraint \"" + constraintName + "\"", "23505"); + return new DataIntegrityViolationException("could not execute statement; constraint [" + constraintName + "]", + new ConstraintViolationException("could not execute statement", fromPostgres, constraintName)); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/SubscriptionServiceTest.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/SubscriptionServiceTest.java new file mode 100644 index 0000000..520270e --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/SubscriptionServiceTest.java @@ -0,0 +1,43 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.constraints.subscription.AlreadySubscribedException; +import com.amigoscode.constraints.subscription.Plan; +import com.amigoscode.constraints.subscription.SubscriptionRepository; +import com.amigoscode.constraints.subscription.SubscriptionService; +import com.amigoscode.constraints.support.Stub; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataIntegrityViolationException; + +/** Unit tests: no Spring, no database. SubscriptionRepository is a stub whose save is refused by a named constraint. */ +@Tag("task5") +class SubscriptionServiceTest { + + @Test + @DisplayName("Translate: when the insert is refused by subscriptions_one_active_per_user, it fails with AlreadySubscribedException (a 409, not a 500)") + void aViolationOfTheOneActiveIndexMeansAlreadySubscribed() { + SubscriptionService service = serviceWhoseInsertViolates("subscriptions_one_active_per_user"); + + assertThatThrownBy(() -> service.subscribe(7, Plan.PRO, 1, 0)) + .isInstanceOf(AlreadySubscribedException.class); + } + + @Test + @DisplayName("Translate: a violation of any other constraint is not reported as \"already subscribed\"") + void aViolationOfAnotherConstraintIsNotAlreadySubscribed() { + SubscriptionService service = serviceWhoseInsertViolates("subscriptions_seats_check"); + + assertThatThrownBy(() -> service.subscribe(7, Plan.PRO, -3, 0)) + .isInstanceOf(DataIntegrityViolationException.class); + } + + private static SubscriptionService serviceWhoseInsertViolates(String constraintName) { + SubscriptionRepository subscriptions = Stub.repository(SubscriptionRepository.class, subscription -> { + throw SignupServiceTest.refusedBy(constraintName); + }); + return new SubscriptionService(subscriptions, step -> { }); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/UniqueEmailIT.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/UniqueEmailIT.java new file mode 100644 index 0000000..5680f1e --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/UniqueEmailIT.java @@ -0,0 +1,67 @@ +package com.amigoscode.constraints; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.constraints.support.IntegrationTest; +import com.amigoscode.constraints.support.Race; +import com.amigoscode.constraints.user.EmailTakenException; +import com.amigoscode.constraints.user.User; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DuplicateKeyException; + +@Tag("task2") +class UniqueEmailIT extends IntegrationTest { + + @Test + @DisplayName("Unique: the database refuses a second row with the same email, even from code that skips the service") + void theDatabaseRefusesTheSameEmailTwice() { + insertUser("ana@example.com"); + + assertThatThrownBy(() -> insertUser("ana@example.com")) + .as("a plain SQL insert of an email that is already in the table") + .isInstanceOf(DuplicateKeyException.class); + assertThat(userRows()).as("rows in users").isEqualTo(1); + } + + @Test + @DisplayName("Unique: two signups with the same email at the same moment: one account is created, the other is told the email is taken") + void onlyOneOfTwoSignupsCreatesAnAccount() { + work.everyonePassesTheCheckBeforeAnyoneInserts(2); + + Race.Result result = Race.run(2, () -> signupService.signUp("ana@example.com", "Ana")); + + assertThat(result.failedWithAnythingBut(EmailTakenException.class)).as("errors that would be a 500").isEmpty(); + assertThat(result.succeeded()).as("accounts created").hasSize(1); + assertThat(result.failedWith(EmailTakenException.class)).as("requests told the email is taken").isEqualTo(1); + assertThat(userRows()).as("rows in users").isEqualTo(1); + } + + @Test + @DisplayName("Unique: 20 signups with the same email: 1 account, 19 told the email is taken, 1 row") + void onlyOneOfTwentySignupsCreatesAnAccount() { + work.takes(20); + + Race.Result result = Race.run(20, () -> signupService.signUp("ana@example.com", "Ana")); + + assertThat(result.failedWithAnythingBut(EmailTakenException.class)).as("errors that would be a 500").isEmpty(); + assertThat(result.succeeded()).as("accounts created").hasSize(1); + assertThat(result.failedWith(EmailTakenException.class)).as("requests told the email is taken").isEqualTo(19); + assertThat(userRows()).as("rows in users").isEqualTo(1); + } + + @Test + @DisplayName("Unique: a signup that arrives after the first one finished is stopped by the application's check, before any insert is tried") + void aLaterSignupIsStoppedByTheFastPath() { + signupService.signUp("ana@example.com", "Ana"); + + assertThatThrownBy(() -> signupService.signUp("ana@example.com", "Ana again")) + .isInstanceOf(EmailTakenException.class); + + assertThat(work.arrivals()) + .as("signups that got past the email check (the second one must not)") + .isEqualTo(1); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/support/ControllableWork.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/support/ControllableWork.java new file mode 100644 index 0000000..c7cfe71 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/support/ControllableWork.java @@ -0,0 +1,65 @@ +package com.amigoscode.constraints.support; + +import com.amigoscode.constraints.work.SlowWork; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Replaces the real slow work in integration tests. The work runs between the check and the insert, + * so controlling it lets a test force the dangerous interleaving on purpose instead of hoping that + * two threads happen to overlap. + */ +public class ControllableWork implements SlowWork { + + private static final long MEETING_TIMEOUT_MILLIS = 1500; + + private final AtomicInteger arrivals = new AtomicInteger(); + private volatile int meetingSize; + private volatile CountDownLatch meeting; + private volatile long delayMillis; + + public void reset() { + arrivals.set(0); + meetingSize = 0; + meeting = null; + delayMillis = 0; + } + + /** + * The first {@code requests} callers wait here until all of them have arrived, so every one of + * them has already passed the check before any of them inserts. If the others never arrive the + * wait ends after 1.5 seconds. + */ + public void everyonePassesTheCheckBeforeAnyoneInserts(int requests) { + meetingSize = requests; + meeting = new CountDownLatch(requests); + } + + public void takes(long millis) { + delayMillis = millis; + } + + /** How many requests got past the check and reached the slow work. */ + public int arrivals() { + return arrivals.get(); + } + + @Override + public void run(String step) { + int arrival = arrivals.incrementAndGet(); + try { + CountDownLatch currentMeeting = meeting; + if (currentMeeting != null && arrival <= meetingSize) { + currentMeeting.countDown(); + currentMeeting.await(MEETING_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } + if (delayMillis > 0) { + Thread.sleep(delayMillis); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/support/IntegrationTest.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/support/IntegrationTest.java new file mode 100644 index 0000000..09c19c7 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/support/IntegrationTest.java @@ -0,0 +1,94 @@ +package com.amigoscode.constraints.support; + +import com.amigoscode.constraints.settings.SettingsService; +import com.amigoscode.constraints.subscription.SubscriptionService; +import com.amigoscode.constraints.user.SignupService; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Primary; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * Base class for the *IT tests. They run the real application against a real Postgres started by + * Testcontainers (Docker must be running), because a constraint only exists in a real database. + * One container is shared by every test class, and schema.sql is applied to it when the + * application starts. + */ +@SpringBootTest(properties = "spring.main.banner-mode=off") +@Import(IntegrationTest.TestBeans.class) +public abstract class IntegrationTest { + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + static void database(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", POSTGRES::getJdbcUrl); + registry.add("spring.datasource.username", POSTGRES::getUsername); + registry.add("spring.datasource.password", POSTGRES::getPassword); + } + + @TestConfiguration + static class TestBeans { + + @Bean + @Primary + ControllableWork controllableWork() { + return new ControllableWork(); + } + } + + @Autowired + protected SignupService signupService; + + @Autowired + protected SubscriptionService subscriptionService; + + @Autowired + protected SettingsService settingsService; + + @Autowired + protected ControllableWork work; + + @Autowired + protected JdbcTemplate jdbc; + + @BeforeEach + void emptyDatabase() { + work.reset(); + jdbc.execute("truncate table subscriptions, user_settings, users restart identity cascade"); + } + + /** Inserts a user with plain SQL, the way a script or another service would: no SignupService. */ + protected long insertUser(String email) { + return jdbc.queryForObject("insert into users (email, display_name) values (?, 'Test') returning id", + Long.class, email); + } + + protected int userRows() { + return jdbc.queryForObject("select count(*) from users", Integer.class); + } + + protected int subscriptionRows(long userId, String status) { + return jdbc.queryForObject("select count(*) from subscriptions where user_id = ? and status = ?", + Integer.class, userId, status); + } + + protected int subscriptionRows() { + return jdbc.queryForObject("select count(*) from subscriptions", Integer.class); + } + + protected int settingsRows(long userId) { + return jdbc.queryForObject("select count(*) from user_settings where user_id = ?", Integer.class, userId); + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/support/Race.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/support/Race.java new file mode 100644 index 0000000..aa1b5f6 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/support/Race.java @@ -0,0 +1,70 @@ +package com.amigoscode.constraints.support; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.IntFunction; + +/** Runs several calls at the same moment, each on its own thread, and collects what happened. */ +public final class Race { + + /** {@code succeeded} holds the return values, {@code failed} the exceptions. */ + public record Result(List succeeded, List failed) { + + /** How many calls failed with this kind of exception. */ + public int failedWith(Class type) { + return (int) failed.stream().filter(type::isInstance).count(); + } + + /** Failures that are not of this kind: anything here would be a 500. */ + public List failedWithAnythingBut(Class expected) { + return failed.stream().filter(failure -> !expected.isInstance(failure)).toList(); + } + } + + /** Runs {@code calls} copies of the same call. */ + public static Result run(int calls, Callable call) { + return run(calls, i -> call); + } + + /** Runs {@code calls} different calls: {@code call.apply(0)}, {@code call.apply(1)}, ... */ + public static Result run(int calls, IntFunction> call) { + ExecutorService executor = Executors.newFixedThreadPool(calls); + CountDownLatch go = new CountDownLatch(1); + List> futures = new ArrayList<>(); + for (int i = 0; i < calls; i++) { + Callable one = call.apply(i); + futures.add(executor.submit(() -> { + go.await(); + return one.call(); + })); + } + go.countDown(); + + List succeeded = new ArrayList<>(); + List failed = new ArrayList<>(); + try { + for (Future future : futures) { + try { + succeeded.add(future.get(60, TimeUnit.SECONDS)); + } catch (ExecutionException e) { + failed.add(e.getCause()); + } catch (Exception e) { + failed.add(e); + } + } + } finally { + executor.shutdownNow(); + } + return new Result<>(succeeded, failed); + } + + private Race() { + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/support/Stub.java b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/support/Stub.java new file mode 100644 index 0000000..52b26b1 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/java/com/amigoscode/constraints/support/Stub.java @@ -0,0 +1,31 @@ +package com.amigoscode.constraints.support; + +import java.lang.reflect.Proxy; +import java.util.function.Function; + +/** + * A hand-written stand-in for a Spring Data repository, for unit tests without Spring or a + * database. Every method that returns a boolean ("does it exist?") answers false, and save does + * whatever the test says. Adding a method to the repository does not break the stub. + */ +public final class Stub { + + @SuppressWarnings("unchecked") + public static T repository(Class type, Function save) { + return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, (proxy, method, args) -> { + if (method.getName().equals("save")) { + return save.apply(args[0]); + } + if (method.getReturnType() == boolean.class) { + return false; + } + if (method.getName().equals("toString")) { + return "stub of " + type.getSimpleName(); + } + throw new UnsupportedOperationException("The stub does not know " + method.getName()); + }); + } + + private Stub() { + } +} diff --git a/java/concepts/junior-mid/10-constraints-and-races/start/src/test/resources/logback-test.xml b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/resources/logback-test.xml new file mode 100644 index 0000000..82166a4 --- /dev/null +++ b/java/concepts/junior-mid/10-constraints-and-races/start/src/test/resources/logback-test.xml @@ -0,0 +1,11 @@ + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + + diff --git a/java/concepts/junior-mid/11-pagination/INTERVIEW_TASKS.md b/java/concepts/junior-mid/11-pagination/INTERVIEW_TASKS.md new file mode 100644 index 0000000..defb5d7 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/INTERVIEW_TASKS.md @@ -0,0 +1,362 @@ +# Interview Tasks — Pagination + +> **In `start/`, `./check` FAILS on purpose: 15 of 35 checks pass.** Tasks 2, 3, 5, 6 and 8 turn the +> other 20 green. Tasks 1, 4, 7 and 9 are inspection tasks: you run things, look, and answer +> questions. + +Do the tasks in order. Every fix is followed by an inspection: a green test tells you the fix works, +the inspection tells you **why**, and the why is what an interviewer asks for. + +Stuck, or want the explanation? The same task number in [`TASKS_GUIDED.md`](TASKS_GUIDED.md) walks +you through it with the expected output. + +Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`. + +**Rules:** work in `start/`. Never edit, delete or disable a test. Indexes go in +`src/main/resources/indexes.sql` and nowhere else. Keep `GET /api/orders?page=&size=` an OFFSET +endpoint: it stays slow on deep pages for ever, so you can always compare against it. + +--- + +## Task 1: See It Break (15 min) + +**Story:** *The back office has an "All orders" screen. It worked fine for two years. Now there are +one million orders, the screen is slow, the nightly export that walks every page takes hours, and +last week the service ran out of memory. Before you change anything, find out what one request +really does.* + +**Steps:** +1. `docker compose up -d`, then `./demo`. It asks for page 1 and page 5,000. How many rows did + Postgres read for each? How many came back? +2. In the same output, count the SQL statements per request. You asked for 20 orders. What is the + second statement for, and how many rows did it read? +3. `./inspect`. Find `OFFSET` in the SQL, and the `rows=` of the `Index Scan` line in the plan. What + did Postgres do with the rows it read and did not return? +4. `./demo --depth 50000`. That is the last page. How many rows now? +5. `./demo --size 100000`. What did the server do? What would `?size=1000000` do? Open `Paging.java`: + what does a request with no `size` at all get? +6. Open `OrderService.page`. That is all the code there is. List everything you have seen go wrong + with this one line. + +**Acceptance Criteria** (`./check 1`, already passing: these tests document the problem) +- [ ] You can say what `OFFSET n` makes the database do +- [ ] You can explain why page 1 is fast and page 5,000 is not, although both return 20 rows +- [ ] You can say where the `SELECT COUNT` comes from +- [ ] `DeepOffsetIT.theFirstPageIsCheap` and `DeepOffsetIT.aDeepPageReadsEveryRowBeforeIt` pass + +**Hints:** +- Compare "Rows read" with "Rows returned to the client" +- Time is printed, but do not trust it: it changes on every run. Rows and pages do not + +--- + +## Task 2: Fix the Unbounded Page Size (10 min) + +**Story:** *The client decides how many rows one request loads, and that is how the service ran out +of memory. Give the API a default page size and a maximum, in `Paging`.* + +**Acceptance Criteria** (`./check 2`) +- [ ] A request without `size` gets 20 orders, and without `page` the first page + — `PageSizeTest.noSizeMeansTwenty` +- [ ] `size=100` is the largest size that is accepted — `PageSizeTest.oneHundredIsAllowed` + (already passing: keep it that way) +- [ ] `size=101` and `size=1000000` return 400 `INVALID_PAGE_REQUEST`, and nothing is loaded + — `PageSizeTest.tooLargeIsRejected` +- [ ] `size=0` and `size=-5` return 400 — `PageSizeTest.zeroAndNegativeAreRejected` +- [ ] `page=-1` returns 400 — `PageSizeTest.negativePageIsRejected` +- [ ] The feed and a customer's history follow the same rules + — `PageSizeTest.theOtherEndpointsFollowTheSameRules` +- [ ] `./demo --size 100000` prints `RESULT: OK` + +**Hints:** +- `InvalidPageRequestException` already exists, and `ApiExceptionHandler` already turns it into a + 400 with the code `INVALID_PAGE_REQUEST` +- All three endpoints call `Paging.size` and `Paging.page`. You do not touch the controller +- Reject or clamp? The tests want a 400. Be ready to argue for it, and for the other choice + +--- + +## Task 3: Fix the Unstable Order (15 min) + +**Story:** *A business customer complains that their order history shows some orders twice and that +others are missing. Support checked: nothing was added or deleted while they were scrolling. Find +out why, and fix the sort order in `OrderService`.* + +**Acceptance Criteria** (`./check 3`) +- [ ] The SQL sorts by `created_at` and then by `id` — `StableOrderIT.theSqlHasATieBreaker` +- [ ] Orders with the same `created_at` come back with the highest id first, however they are stored + — `StableOrderIT.tiesComeBackInOneFixedOrder` +- [ ] Reading a customer's 120 orders page by page returns each order exactly once + — `StableOrderIT.walkingThePagesReturnsEveryOrderOnce` +- [ ] `./demo --mode history` prints `RESULT: OK` + +**Hints:** +- Run `./demo --mode history` first and read the example it prints. What do the repeated orders + have in common? +- What does `ORDER BY created_at` promise about two rows with the same `created_at`? +- One constant. Both offset endpoints use it + +--- + +## Task 4: Inspect What OFFSET Cannot Fix (15 min) + +**Story:** *The order is stable now. Two complaints are still open: the screen is slow on deep pages, +and during the day, when orders keep coming in, people still see an order twice. Show why your last +fix could not help with either.* + +**Steps:** +1. `./demo --mode history` and `./inspect --mode history`. Find the `Sort Key` in the plan. What + changed compared with before Task 3? +2. `./demo --insert`. One order is placed between the request for page 1 and the request for page 2. + Which order comes back twice? Why that one? +3. Now the other direction, on paper: page 1 is read, then an order on page 1 is cancelled and + deleted, then page 2 is read. Which order does the client never see? + (`OffsetShiftIT.aDeleteSkipsARow` is this scenario.) +4. `./demo`. Page 5,000 is still slow. Would an index help? There already is one: which index does + the plan use, and for what? +5. The nightly export reads every page from first to last. With 50,000 pages, roughly how many rows + does Postgres read in total? (Page n reads n x 20 rows.) + +**Acceptance Criteria** (`./check 4`, already passing: these tests document the problem) +- [ ] You can explain why an insert at the top of the list repeats a row, and a delete skips one +- [ ] You can explain why this happens with a perfectly stable `ORDER BY` +- [ ] You can explain why no index makes `OFFSET 99980` cheap +- [ ] `OffsetShiftIT.anInsertRepeatsARow` and `OffsetShiftIT.aDeleteSkipsARow` pass + +--- + +## Task 5: Fix It With Keyset Pagination (30 min) + +**Story:** *Stop counting rows. A page should start where the last one ended: "the 20 orders that +come after this one". Somebody started `GET /api/orders/feed` that way and left. Finish it: +`OrderRepository`, `OrderService.feed` and `indexes.sql`.* + +**Acceptance Criteria** (`./check 5`) +- [ ] `indexes.sql` creates an index on `orders (created_at, id)` + — `KeysetIT.theIndexMatchesTheSortOrder` +- [ ] The feed query finds its starting point in that index with a row comparison, and sorts nothing + — `KeysetIT.theQueryIsARowComparisonOnTheIndex` +- [ ] A page 10,000 orders deep reads 21 rows, exactly as many as the first page + — `KeysetIT.aDeepPageCostsTheSameAsTheFirst` +- [ ] Following `nextCursor` from the first page to the last returns all 20,000 orders exactly once, + newest first — `KeysetIT.followingTheCursorReturnsEveryOrderOnce` +- [ ] `hasNext` is true while orders remain; the last page has `hasNext = false` and no + `nextCursor`, even when it is exactly full — `KeysetIT.theLastPageKnowsItIsTheLast` +- [ ] An order placed between two requests changes nothing + — `KeysetIT.anInsertDoesNotShiftThePages` +- [ ] `./demo --mode keyset` prints `RESULT: OK` + +**Hints:** +- Run `./demo --mode keyset` first. Which orders does page 2 start with, and which did it jump over? + Look at the `WHERE` clause and remember Task 3 +- The position of a row in the list is two values, not one. `Cursor` already carries both +- Postgres can compare two values at once: `(a, b) < (?, ?)`. Write the query as native SQL +- How do you know there is a next page without counting? Ask for one row more than you return +- After the query is right, `./check 5` still complains about a Sort. The index has to have the + same columns as the `ORDER BY`. Replace the old index, do not add a second one + +--- + +## Task 6: Fix the Cursor (15 min) + +**Story:** *The cursor travels to the client and back as `2025-11-25T10:00:00Z|999981`. Clients have +started building it themselves, and when someone sends rubbish the API answers 500. Make the cursor +opaque, and make a cursor the API cannot read a 400. Fix `Cursor`.* + +**Acceptance Criteria** (`./check 6`) +- [ ] `decode(encode(cursor))` gives the same cursor back — `CursorTest.roundTrip` (already passing: + keep it that way) +- [ ] The encoded form is URL-safe Base64, with no timestamp or id readable in it + — `CursorTest.theEncodedFormIsOpaque` +- [ ] Text that is not a cursor is an `InvalidCursorException`, never another exception + — `CursorTest.garbageIsRejected` +- [ ] Over HTTP a malformed cursor returns 400 `INVALID_CURSOR`, not a 500 + — `CursorTest.aMalformedCursorIsABadRequest` +- [ ] A cursor the API handed out is accepted — `CursorTest.aValidCursorReachesTheService` (already + passing) +- [ ] Task 5 is still green (`./check 5`) + +**Hints:** +- `java.util.Base64.getUrlEncoder().withoutPadding()` and `getUrlDecoder()` +- `InvalidCursorException` already exists and is already mapped to a 400 +- Which exceptions can decoding throw? Bad Base64, a bad timestamp, a bad number, a missing + separator. All four must end as the same exception +- Is the cursor a secret now? + +--- + +## Task 7: Inspect Keyset Pagination (15 min) + +**Story:** *The feed passes its tests. Now prove you know why it is fast, and what you gave up.* + +**Steps:** +1. `./demo --mode keyset`. Compare "Rows read" for page 1 and page 5,000. Then + `./demo --mode keyset --depth 50000`. +2. `./inspect --mode keyset`. Find the `Index Cond` line. Compare it with the plan of + `./inspect` (offset): where did Postgres start reading the index in each case? +3. The request returns 20 orders and the SQL says `limit 21`. What happens to the 21st row? +4. `./demo --mode keyset --insert`. Compare with Task 4 step 2. Why does the new order not shift + anything? Will the client ever see the new order? +5. Copy a `nextCursor` from the demo output and decode it (any Base64 tool). What is in it? What + happens if the order it points to is deleted before the client asks for the next page? +6. The demo "looked up the last order of page 4,999 in the database" to get to page 5,000. Why did + it have to? What can a real client not do with this endpoint? +7. The product owner wants to sort the feed by `total_cents`. What would have to change: in the + query, the cursor and the index? + +**Acceptance Criteria** (no tests: you answer) +- [ ] You can explain in one sentence why a deep keyset page costs the same as the first +- [ ] You can explain why `(created_at, id) < (?, ?)` is not the same as + `created_at < ? AND id < ?` +- [ ] You can explain how `hasNext` works without a count +- [ ] You can name two things keyset pagination cannot do + +--- + +## Task 8: Fix the Hidden COUNT(*) (15 min) + +**Story:** *Every request to the two offset endpoints still runs two SQL statements. The second one +counts every matching row, to fill a `totalElements` that no screen shows: the UI only has a "Next" +button. Remove it, in `OrderRepository` and `OrderService`.* + +**Acceptance Criteria** (`./check 8`) +- [ ] One page of `GET /api/orders` is exactly one SQL statement — `CountQueryIT.onePageIsOneStatement` +- [ ] No endpoint sends `SELECT COUNT` — `CountQueryIT.nothingCountsTheTable` +- [ ] The page query asks for one row more than the page size + — `CountQueryIT.thePageQueryFetchesOneRowMore` +- [ ] `hasNext` is still right: true in the middle, false on the last page + — `CountQueryIT.hasNextIsStillRight` (already passing: keep it that way) +- [ ] `./demo` no longer prints `RESULT: HIDDEN COUNT` +- [ ] `./check` prints 35 passes and no failures + +**Hints:** +- The return type of a Spring Data repository method decides what it does. What else can a method + that takes a `Pageable` return? +- `findAll(Pageable)` is inherited and always returns a `Page`. Declare your own method +- You already did the same trick by hand in Task 5 + +--- + +## Task 9: Compare Offset and Keyset (15 min) + +**Story:** *"So keyset is always better?" is the interview question. Collect the numbers, then give +the honest answer.* + +**Steps:** +1. Run these and note statements per request, rows read for page 1 and rows read for the deep page: + - `./demo --depth 5000` + - `./demo --mode keyset --depth 5000` + - `./demo --depth 50000` + - `./demo --mode keyset --depth 50000` +2. `./demo --insert` and `./demo --mode keyset --insert`. Which one repeats a row? +3. `./demo --depth 3`. How much does page 3 cost with OFFSET? Most users never go past it. +4. A support agent wants to jump straight to page 400 of 2,500. Which endpoint can do that? +5. An admin screen lists 300 products, sortable by any column. Would you build keyset pagination + for it? What would it cost you? +6. `./inspect`: look at the `rows` column of the table. Where could a screen get "about 1,000,000 + orders" from without counting them? + +**Acceptance Criteria** (no tests: you answer) +- [ ] You can name three things that go wrong with offset pagination on a big table +- [ ] You can name two things keyset pagination cannot do, and one thing it needs +- [ ] You can give one situation where offset is the right choice and one where it is not +- [ ] You can say what to do when the screen really needs a total + +--- + +## Questions to Ask Afterwards + +Answer out loud, in full sentences, before reading the answer in brackets. + +- How do you paginate a large table? (For anything a user or a job reads far into, keyset + pagination: order by a unique key, remember the key of the last row of a page, and ask for the + rows after it with `WHERE (created_at, id) < (?, ?) ORDER BY created_at DESC, id DESC LIMIT ?`, + backed by an index on the same columns. Every page then costs the same. Offset pagination is fine + for small tables and shallow pages. Either way the API has a default and a maximum page size.) +- What is wrong with `LIMIT` / `OFFSET`? (Three things. `OFFSET n` does not skip rows for free: the + database produces the first n rows and throws them away, so page 5,000 reads 100,000 rows to + return 20. It counts positions from the top at the moment of each request, so an insert or delete + between two requests shifts every row: one is shown twice or one is never shown. And it is usually + paired with a `COUNT(*)` for the total, which reads every matching row on every request.) +- Users see the same row on two pages. Why? (Two different causes. The `ORDER BY` is not unique: + rows with the same `created_at` have no defined order, so the database may arrange them + differently for page 1 and for page 2. Fix: add a unique tie-breaker, usually the primary key. + Or rows were inserted or deleted between the two requests and the offsets shifted. Fix: keyset + pagination. A tie-breaker does not fix the second cause.) +- Why did the same query return ties in a different order for different pages? (Without an index + that gives the order, Postgres sorts. With a `LIMIT` it uses a top-N heapsort that only keeps the + first `offset + limit` rows, and a heapsort does not keep equal rows in their original order. The + rows it keeps among equals depend on how many it keeps, so page 1 and page 2 disagree. Nothing + random is involved: the SQL simply never said which of two equal rows comes first.) +- What is a row-value comparison? (`(a, b) < (x, y)` compares like a dictionary: `a < x`, or + `a = x AND b < y`. It is exactly the order `ORDER BY a, b` produces, so "the rows after this one" + is one condition. Postgres turns it into a single index condition on an index on `(a, b)`. It is + not the same as `a < x AND b < y`, which would lose every row with a smaller `a` and a larger + `b`.) +- Why does the keyset query need a matching index? (Without it the query is still correct, but the + database has to find and sort the rows. With an index on exactly the `ORDER BY` columns it walks + down the tree to the cursor position, 3 or 4 pages, and reads the next 21 entries in order. That + is why depth does not matter.) +- How do you know there is a next page without `COUNT(*)`? (Fetch `size + 1` rows. If the extra row + comes back there is a next page: return `size` rows and drop the extra one. "The page was full" + is not enough: when the last page is exactly full it would promise a page that is empty.) +- What is the difference between `Page` and `Slice` in Spring Data? (Both hold one page of rows. A + `Page` also knows the total number of rows and pages, and to know that it runs a second query, + `SELECT COUNT`, on every request. Spring Data only skips the count when the page came back + shorter than requested, because then the total is already known. A `Slice` knows only whether + there is a next page, which it finds out by fetching `size + 1` rows. No count.) +- The screen really needs a total. What then? (Ask how exact it must be. "About 1,000,000" can come + from the planner's estimate, `pg_class.reltuples`, for free. Or count up to a limit and show + "10,000+". Or cache the count for a minute. Or count once on the first page and not on every + page. An exact count of a large filtered result on every request is the expensive option, and it + is the default.) +- Why an opaque cursor? (The cursor is the server's private bookmark. If clients can read it they + start to build it, and then you can never change the sort key or the format. Base64 makes it + clearly "not yours to parse". It is not security: anyone can decode it, so it must not hold + anything secret, and it must be validated like any other input. If a client must not be able to + forge a position, sign it.) +- What should happen when a client sends a cursor you cannot read? (A 400 with a clear code. It is + the client's mistake, so it must not become a 500, and it must not be silently treated as "no + cursor", which would restart the client at page 1 and loop for ever.) +- Reject a page size that is too large, or clamp it? (Both are used. Clamping is forgiving, and it + is what Spring Data's `Pageable` resolver does by default, at 2,000. Rejecting with a 400 is + louder: a client that asks for 500 and silently gets 100 may conclude "fewer than I asked for, so + that was the last page" and stop early. Whichever you choose, document it and return the size + that was used.) +- What can keyset pagination not do? (Jump to an arbitrary page or show "page 37 of 500": there is + no page number, only "after this row". Sort by anything the user clicks: each sort order needs + its own cursor and its own index, and the sort key must be unique, or made unique with a + tie-breaker, and not null. And if a row's sort key changes while a client is paging, that row can + be seen twice or missed.) +- When is offset pagination perfectly fine? (Small tables. Admin screens with a few hundred rows + and any-column sorting. Search results where nobody goes past page 3. A UI that needs page + numbers. Deep pages and constant inserts are what make it fail. Without those, it is the simpler + tool.) +- A new order arrives while a client is paging with a cursor. Does the client see it? (Not in this + pass: it sorts before the client's position. Nothing is repeated and nothing is skipped. To see + new rows the client starts again from the top, or the API offers a second cursor that goes in the + other direction.) +- How would you export all one million orders? (Not with page numbers. Follow the cursor in a loop + with the largest allowed page size, or stream the result of one query, in key order. Each step + costs the same, and the export does not shift when orders arrive.) + +## Tips for Interviewers + +- The most common weak answer is "I would use `Pageable`". Ask what SQL that produces, and how many + statements. Many candidates have never seen the `COUNT`. +- Ask the candidate to predict "rows read" for page 5,000 before running `./demo`. A strong + candidate says 100,000 without running anything, and adds that the index does not help. +- In Task 3, see whether they separate the two causes of duplicates. A candidate who says "add the + id to the ORDER BY" and believes the insert problem is solved too has learned a recipe. Task 4 + step 2 shows it. +- In Task 5, watch the `WHERE` clause. `created_at < ? AND id < ?` is the classic wrong answer, and + `created_at <= ?` returns rows twice. Ask them to walk through three orders with the same + `created_at`. +- A candidate who uses "the page was full" for `hasNext` should be asked about a table with exactly + 40 rows and a page size of 20. +- In Task 6, ask whether Base64 makes the cursor secure. The right answer is no, and that it does + not need to be. +- For senior candidates, go past the tasks: a previous-page cursor, a sort key that is nullable or + that changes (`updated_at`), mixed sort directions (`ORDER BY a ASC, b DESC` cannot be one row + comparison), keyset over a filtered list and the index that needs, and what Spring Data's + `Window` / `ScrollPosition.keyset()` generates (see the guided file, Task 7). diff --git a/java/concepts/junior-mid/11-pagination/README.md b/java/concepts/junior-mid/11-pagination/README.md new file mode 100644 index 0000000..fbcb3fb --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/README.md @@ -0,0 +1,187 @@ +# Pagination — Offset vs Keyset (Cursor) + +> **In `start/`, `./check` FAILS on purpose: 15 of 35 checks pass.** That is the exercise, not a +> broken checkout. Tasks 2, 3, 5, 6 and 8 turn the other 20 green. + +A shop has one million orders. The order list is paginated with the one line everybody writes: +`repository.findAll(PageRequest.of(page, size, Sort.by("createdAt").descending()))`. Page 1 reads 20 +rows. Page 5,000 reads 100,000 rows to return 20. This project lets you watch that happen, find the +four other problems hiding in the same line, and replace it with keyset (cursor) pagination. + +It answers the interview questions students most often get wrong: + +- "How do you paginate a large table? What is wrong with `LIMIT` / `OFFSET`?" +- "What is keyset (cursor) pagination, and when would you not use it?" +- "Users see the same row on two pages. Why?" +- "What is the difference between `Page` and `Slice` in Spring Data?" +- "A client calls your endpoint with `size=1000000`. What happens?" + +## Tech Stack + +- **Java 25**, **Spring Boot 4**, Spring Data JPA (Hibernate) +- **PostgreSQL 17** in Docker +- JUnit 5, AssertJ, Testcontainers + +## What you need + +- JDK 25 +- Docker, running + +## Getting Started + +Work in `start/`. Commands are shown for macOS and Linux; on Windows type `.\demo` where you see +`./demo` (same for `inspect` and `check`). + +```bash +cd start +docker compose up -d # Postgres on port 5450 +./demo # watch page 5,000 read 100,000 rows to return 20 +./check # 15 of 35 pass: that is your starting point +``` + +The first run downloads Maven and the dependencies, and seeds one million orders. That takes a +minute or two, once. After that `./demo` takes a few seconds. + +When you are finished: `docker compose down`. + +## The three tools + +### `./demo` — see what a page costs + +Starts the real application, asks it for pages over HTTP and prints, for every request, the SQL the +application really sent and what Postgres did with it: rows read, rows returned, pages touched. Ends +with one or more `RESULT` lines. The data is the same on every run. + +``` +./demo offset: page 1 against page 5,000 +./demo --depth 50000 the same, 50,000 pages deep +./demo --size 100000 ask for 100,000 orders in one request +./demo --mode history read ALL orders of customer 42 page by page: is each one returned once? +./demo --insert a new order is placed between the request for page 1 and page 2 +./demo --mode keyset the cursor endpoint: page 1, page 2 and page 5,000 +./demo --mode keyset --insert the same insert, with a cursor +./demo --reseed empty the table and seed it again +./demo --help +``` + +### `./inspect` — look inside the database + +Shows the table and its indexes, then sends one page request and prints the complete +`EXPLAIN (ANALYZE, BUFFERS)` output of every SQL statement that request ran. +`./inspect --mode keyset --depth 5000`, `./inspect --mode history`, `./inspect --depth 1`. + +### `./check` — are the acceptance criteria met? + +`./check 2` runs the tests for Task 2 and prints one line per criterion. `./check` runs everything. +`./mvnw verify` runs the same tests the usual Maven way. + +The tests are the acceptance criteria. **Never edit, delete or disable a test.** They do not measure +time. They call the service, write down the SQL it really sent, and check which rows came back, how +many statements were sent, and how many rows Postgres read to answer them. + +## The code + +``` +start/src/main/ +├── resources/ +│ ├── schema.sql the table. Nothing to change here +│ └── indexes.sql THE INDEXES. Task 5 changes this file +└── java/com/amigoscode/pagination/ + ├── order/ + │ ├── OrderController.java the three endpoints. Nothing to change here + │ ├── Paging.java the rules for ?page= and ?size=. Task 2 + │ ├── OrderService.java the sort order, Page and the feed. Tasks 3, 5 and 8 + │ ├── OrderRepository.java the queries. Tasks 5 and 8 + │ └── Cursor.java what the client sends back to get the next page. Task 6 + ├── db/ seeding, applying indexes.sql, recording SQL, reading plans. Nothing to change here + └── demo/ the demo and inspect tools. Nothing to change here +``` + +The three endpoints: + +| Endpoint | How it pages | +|---|---| +| `GET /api/orders?page=0&size=20` | Every order, newest first, with `LIMIT` and `OFFSET` | +| `GET /api/customers/{id}/orders?page=0&size=20` | The orders of one customer, the same way | +| `GET /api/orders/feed?after=&size=20` | Every order, newest first, with a cursor. Somebody started it and did not finish | + +The data: 1,000,000 orders made inside Postgres with `generate_series`. They arrive from a +marketplace in batches: 40 orders every 40 minutes, written in one transaction, so **all 40 share +the same `created_at`**. The first 12 orders of every batch belong to one business customer. + +You add or change an index in `src/main/resources/indexes.sql`. The next `./demo`, `./inspect` or +`./check` notices that the file changed, drops every index except the primary key and runs the file +again. [`../03-indexes`](../03-indexes/) is the project about indexes themselves; this one assumes +you know what a composite index is. + +## Two ways to work + +- **[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md)**: challenge mode. A story, acceptance criteria and + hints for each task. Use this if you want to work it out yourself. +- **[`TASKS_GUIDED.md`](TASKS_GUIDED.md)**: the same nine tasks, step by step, with the output you + should see and an explanation of why. Use this to learn the concept, or when you are stuck. + +Both files use the same task numbers. + +| Task | What you do | Checked by | +|---|---|---| +| 1 | See the deep `OFFSET`, the unbounded size and the extra `COUNT` | `./check 1` (passes: it documents the problem) | +| 2 | Fix the unbounded page size | `./check 2` | +| 3 | Fix the unstable order with a tie-breaker | `./check 3` | +| 4 | Inspect what `OFFSET` cannot fix: depth and shifting rows | `./check 4` (passes: it documents the problem) | +| 5 | Fix it with keyset pagination | `./check 5` | +| 6 | Fix the cursor: opaque, and a 400 when it is malformed | `./check 6` | +| 7 | Inspect keyset pagination | you answer questions | +| 8 | Fix the hidden `COUNT(*)` | `./check 8` | +| 9 | Compare offset and keyset, and say when each is right | you answer questions | + +## Solution + +`solution/` is the same project with every task done: `cd solution && ./check` prints 35 of 35. + +`start/` and `solution/` use the same database. When you switch from one to the other, the next +command notices that `indexes.sql` is different and rebuilds the indexes. + +To start again from scratch: `git checkout -- start` (this throws away your changes in `start/`). + +

+Spoiler: the problems and the fixes + +**Unbounded size (Task 2).** `?size=1000000` is accepted and a request without `size` returns the +whole table. Fix: a default of 20 and a maximum of 100 in `Paging`, and a 400 for anything outside +1 to 100. + +**Unstable order (Task 3).** `ORDER BY created_at` does not say which of 40 orders with the same +`created_at` comes first, so Postgres may answer differently for every page. Reading a customer's +300 orders page by page returns 14 of them twice and never returns 14 others. Fix: a unique +tie-breaker, `ORDER BY created_at DESC, id DESC`. + +**Deep OFFSET and shifting rows (Task 4).** `OFFSET 99980` means "read 99,980 rows and throw them +away". And because `OFFSET` counts from the top of the list at the moment of each request, an order +placed between two requests moves every row down by one: the last row of page 1 comes back as the +first row of page 2. No tie-breaker and no index fixes either. They are what `OFFSET` is. + +**Keyset pagination (Task 5).** Do not count rows. Remember where the last page ended and start +there: `WHERE (created_at, id) < (?, ?) ORDER BY created_at DESC, id DESC LIMIT ?`, with an index on +`(created_at, id)`. Postgres jumps to that position in the index: page 5,000 reads 21 rows, like +page 1, and an insert at the top cannot shift anything. Fetch `size + 1` rows: the extra row says +whether there is a next page. + +**The cursor (Task 6).** The client gets the position as an opaque string: Base64 of +`createdAt|id`. A cursor that cannot be decoded is the client's mistake: a 400, never a 500. + +**The hidden COUNT (Task 8).** A Spring Data `Page` runs `SELECT COUNT` on every request to fill +`totalElements`, which no screen shows. On one million rows that count reads one million rows. +Return a `Slice`: it fetches `size + 1` rows and never counts. + +**When to use which.** + +| | Offset | Keyset | +|---|---|---| +| Cost of page N | Reads N x size rows | Reads size + 1 rows | +| Rows inserted or deleted while paging | Rows repeat or are skipped | Nothing shifts | +| Jump to page 37, show "page 37 of 500" | Yes | No: only next (and previous) | +| Sort order | Anything | Needs a unique, indexed sort key, fixed for the endpoint | +| Use it when | Small tables, admin screens, a user who needs page numbers | Feeds, infinite scroll, exports, sync jobs, anything deep | + +
diff --git a/java/concepts/junior-mid/11-pagination/TASKS_GUIDED.md b/java/concepts/junior-mid/11-pagination/TASKS_GUIDED.md new file mode 100644 index 0000000..868507f --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/TASKS_GUIDED.md @@ -0,0 +1,898 @@ +# Guided Tasks — Pagination + +The same nine tasks as [`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md), step by step: the command to run, +the output you should see, why it happens, and the change to make. + +Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`. + +All output below was copied from real runs. **Timings differ on every machine and on every run.** +The row counts, the number of SQL statements and the `RESULT` lines should match. Page counts can +be off by a few. + +**Before you start** + +```bash +cd start +docker compose up -d +``` + +**Three things to know about the tools** + +- `./demo` and `./inspect` start the real application and send it real HTTP requests. For every + request they print the SQL the application sent, then run each statement again with + `EXPLAIN (ANALYZE, BUFFERS)` to see what Postgres did. "Rows read" and "pages read" come from there. +- Page numbers in the URL start at 0, the Spring Data way. The demo says "page 1" for `page=0` and + "page 5,000" for `page=4999`. +- You change an index by editing `src/main/resources/indexes.sql`. The next command prints + `indexes.sql changed: rebuilding 2 indexes...` and applies it. + +--- + +## Task 1: See It Break + +No code in this task. You are collecting evidence. + +### Run it + +```bash +./demo +``` + +The very first run prints `Seeding 1,000,000 orders (first run only)...`. It takes a few seconds. + +### What you should see + +``` +Mode: offset | page size: 20 | depth: page 5,000 of 50,000 +Table orders: 1,000,000 rows, newest first. + +--- Page 1 --- +GET /api/orders?page=0&size=20 + 200 OK, 20 orders, 32 ms + SQL statements sent: 2 + 1. select ... from orders o1_0 order by o1_0.created_at desc offset ? rows fetch first ? rows only -- ? = 0, 20 + Index Scan Backward using idx_orders_created_at on orders + rows read: 20 | rows returned: 20 | pages read: 4 + 2. select count(o1_0.id) from orders o1_0 + Seq Scan on orders + rows read: 1,000,000 | rows returned: 1 | pages read: 8,334 + +--- Page 5,000 --- +GET /api/orders?page=4999&size=20 + 200 OK, 20 orders, 35 ms + SQL statements sent: 2 + 1. select ... from orders o1_0 order by o1_0.created_at desc offset ? rows fetch first ? rows only -- ? = 99980, 20 + Index Scan Backward using idx_orders_created_at on orders + rows read: 100,000 | rows returned: 20 | pages read: 1,011 + 2. select count(o1_0.id) from orders o1_0 + Seq Scan on orders + rows read: 1,000,000 | rows returned: 1 | pages read: 8,334 + + page 1 page 5,000 +Rows returned to the client 20 20 +Rows read 20 100,000 +Rows read and thrown away 0 99,980 +Pages read (8 kB each) 4 1,011 +Time in the database 0.04 ms 13.17 ms (differs on every run) + +RESULT: DEEP OFFSET. Page 5,000 read 100,000 rows to return 20. Page 1 read 20. +RESULT: HIDDEN COUNT. The request also sent a SELECT COUNT that nobody asked for. It read 1,000,000 rows to return one number. +``` + +Both pages return 20 orders. Page 1 read 20 rows to do it. Page 5,000 read 100,000. + +### What OFFSET does + +`offset ? rows fetch first ? rows only` is the standard SQL spelling of `LIMIT 20 OFFSET 99980`. +Hibernate writes it that way. Look at the plan: + +```bash +./inspect +``` + +``` + EXPLAIN (ANALYZE, BUFFERS) + Limit (cost=2681.19..2681.72 rows=20 width=37) (actual time=14.246..14.250 rows=20 loops=1) + Buffers: shared hit=1011 + -> Index Scan Backward using idx_orders_created_at on orders o1_0 (cost=0.42..26813.42 rows=1000000 width=37) (actual time=0.011..11.155 rows=100000 loops=1) + Buffers: shared hit=1011 +``` + +Read it from the inside out. The `Index Scan` produced **100,000 rows** (`rows=100000`). The `Limit` +above it let 20 through (`rows=20`). The other 99,980 were fetched from the table, handed up, and +dropped. + +That is all `OFFSET` is: "produce the rows from the top, and do not give me the first n". The +database has no way to know where row 99,981 is without walking past the 99,980 before it. The +index gives the order, so nothing has to be sorted, but it cannot be asked "where is position +99,981?". An index finds **values**, not positions. + +So the cost of a page grows with its number: + +```bash +./demo --depth 50000 +``` + +``` +Rows read 20 1,000,000 +Pages read (8 kB each) 4 10,061 +RESULT: DEEP OFFSET. Page 50,000 read 1,000,000 rows to return 20. Page 1 read 20. +``` + +The last page reads the whole table. (If you need a refresher on reading `EXPLAIN ANALYZE`, on +pages and on why pages are a better measure than milliseconds: [`../03-indexes`](../03-indexes/), +Task 1.) + +### The second statement + +You asked for 20 orders and the application sent two statements. The second one, +`select count(o1_0.id) from orders o1_0`, read all 1,000,000 rows. It is sent on **every** request, +page 1 included. Nobody wrote it: remember it for Task 8. + +### No limit on the size + +```bash +./demo --size 100000 +``` + +``` +GET /api/orders?page=0&size=100000 + 200 OK, 100,000 orders, 10.7 MB of JSON, 505 ms + +RESULT: UNBOUNDED. One request made the server load 100,000 orders and send 10.7 MB. + Nothing stops a client from asking for size=1000000, or from leaving size out. +``` + +The server loaded 100,000 entities into memory and wrote 10.7 MB of JSON because one client asked +for it. Open `Paging.java`: a request with no `size` at all gets `Integer.MAX_VALUE`, which means +every order there is. + +### Find it in the code + +`OrderService.page`: + +```java +Page result = orders.findAll(PageRequest.of(page, size, NEWEST_FIRST)); +``` + +One line, the line every tutorial shows. So far it has three problems: the size is whatever the +client says, deep pages read everything before them, and there is a `COUNT` on every request. Two +more are coming. + +### Check + +```bash +./check 1 +``` + +``` +Task 1: See the deep OFFSET + [PASS] Offset: page 500 reads more than 10,000 rows to return 20: every row of the 500 pages before it (this documents the problem) + [PASS] Offset: the first page reads fewer than 100 rows to return 20 + 2 of 2 pass +``` + +These pass on purpose, now and at the end: `OFFSET` cannot be made cheap. (The tests use a database +of 20,000 orders, started by Testcontainers. The demo uses one million.) + +--- + +## Task 2: Fix the Unbounded Page Size + +**The idea:** the server decides how much one request may cost, not the client. + +### Before + +```bash +./check 2 +``` + +``` + [FAIL] Page size: a request without size gets 20 orders, not every order + [size passed to the service for GET /api/orders] + expected: 20 + but was: 2147483647 + 1 of 6 pass +``` + +### The change + +Replace the two methods in `Paging.java`: + +```java +public static final int DEFAULT_SIZE = 20; +public static final int MAX_SIZE = 100; + +public static int size(Integer requested) { + if (requested == null) { + return DEFAULT_SIZE; + } + if (requested < 1 || requested > MAX_SIZE) { + throw new InvalidPageRequestException("size must be between 1 and " + MAX_SIZE + ", got " + requested); + } + return requested; +} + +public static int page(Integer requested) { + if (requested == null) { + return 0; + } + if (requested < 0) { + throw new InvalidPageRequestException("page must be 0 or more, got " + requested); + } + return requested; +} +``` + +`InvalidPageRequestException` already exists and `ApiExceptionHandler` already maps it to a 400. +All three endpoints call `Paging`, so this one class fixes all of them. + +### Reject or clamp? + +There are two honest answers to `size=1000000`: + +- **Clamp:** quietly use 100. Forgiving, and it is what Spring Data's own `Pageable` argument + resolver does: we ran it, and `size=1000000` came back as 2,000, its default maximum, while + `size=0` and `size=-5` came back as 20. +- **Reject:** answer 400. That is what this project does. + +The argument for rejecting: a client that asks for 500 rows and silently receives 100 often reads +that as "fewer than I asked for, so this was the last page", and stops. Its data is incomplete and +nothing failed. A 400 is noticed on the first call. Either is acceptable in an interview if you can +say why. No limit at all is not. + +### After + +```bash +./demo --size 100000 +``` + +``` +GET /api/orders?page=0&size=100000 + 400 INVALID_PAGE_REQUEST: size must be between 1 and 100, got 100000 + SQL statements sent: 0 + +RESULT: OK. size=100000 was rejected with a 400 before anything was read from the database. +``` + +`./check 2` prints 6 of 6. + +--- + +## Task 3: Fix the Unstable Order + +### Run it + +```bash +./demo --mode history +``` + +Customer 42 is a business customer with 300 orders. The demo reads all of them through +`GET /api/customers/42/orders`, 20 at a time, the way a browser or an export would. + +``` +Customer 42 has 300 orders. The demo reads all of them, page by page. +Nothing is inserted, updated or deleted while it reads. + +GET /api/customers/42/orders?size=20&page=0 + 200 OK, 20 orders, 12 ms + SQL statements sent: 2 + 1. select ... from orders o1_0 where o1_0.customer_id=? order by o1_0.created_at desc fetch first ? rows only -- ? = 42, 20 + Bitmap Heap Scan on orders + Bitmap Index Scan using idx_orders_customer + rows read: 300 | rows returned: 20 | pages read: 31 + ... + +Pages requested 15 +Orders received 300 +Different orders received 286 +Orders received twice 14 +Orders never received 14 + +For example: order #921,649 was on page=0 and again on page=1. +11 other orders of this customer have exactly the same created_at. + +RESULT: UNSTABLE ORDER. Nothing changed in the database, but 14 orders came back twice and 14 never came back. +``` + +300 orders went out, but only 286 different ones. 14 were sent twice, 14 were never sent. And +nothing was written to the database in between. + +### What just happened + +The last line of the example is the clue: **12 orders with exactly the same `created_at`**. This +customer's orders arrive a dozen at a time in one transaction. + +`ORDER BY created_at DESC` tells Postgres to put newer orders first. It says nothing about two +orders that are equally new. For those, any order is a correct answer, and Postgres is free to give +a different correct answer each time. Look at how it sorts: + +```bash +./inspect --mode history +``` + +``` + -> Sort (cost=97.60..97.66 rows=24 width=37) (actual time=1.027..1.072 rows=20 loops=1) + Sort Key: created_at DESC + Sort Method: top-N heapsort Memory: 27kB +``` + +No index gives this order, so Postgres sorts the customer's 300 rows. Because of the limit it uses a +**top-N heapsort**: it keeps only the best `offset + limit` rows and drops the rest as it goes. For +page 0 it keeps 20, for page 1 it keeps 40, for page 2 it keeps 60. Which of twelve equal rows +survive depends on how many are kept, so the pages do not agree with each other. Twelve orders tie +across the boundary between page 0 and page 1; page 0 shows eight of them, page 1 shows a different +arrangement, and some appear on both while others appear on neither. + +Nothing is random and nothing is broken in Postgres. The query asked a question with more than one +right answer. + +> You will not always see this. `GET /api/orders` has the same incomplete `ORDER BY`, but there an +> index hands Postgres the rows already in `created_at` order, nothing is sorted, and the ties came +> back the same way in every run. Nothing in the SQL promises that: it is luck that depends on the +> plan. That is why this bug survives testing and appears in production. + +### The change + +Make the order complete: add a column that is never equal for two rows. In `OrderService`: + +```java +static final Sort NEWEST_FIRST = Sort.by(Sort.Order.desc("createdAt"), Sort.Order.desc("id")); +``` + +`id` is the primary key, so `(created_at, id)` is unique. There is now exactly one right answer for +every page. Both offset endpoints use this constant. + +### After + +```bash +./demo --mode history +``` + +``` + 1. select ... from orders o1_0 where o1_0.customer_id=? order by o1_0.created_at desc,o1_0.id desc fetch first ? rows only -- ? = 42, 20 +... +RESULT: OK. 300 orders, each returned exactly once. +``` + +`./check 3` prints 3 of 3. + +**The rule:** an `ORDER BY` used for pagination must end in a unique column. If the sort column is +not unique, add the primary key as a tie-breaker. + +--- + +## Task 4: Inspect What OFFSET Cannot Fix + +### Step 1: the sort key + +`./inspect --mode history` now shows `Sort Key: created_at DESC, id DESC`. Still a top-N heapsort, +but there are no equal rows left for it to shuffle. + +### Step 2: an order arrives between two requests + +```bash +./demo --insert +``` + +``` +GET /api/orders?page=0&size=20 + 200 OK, 20 orders, 32 ms + last 3 orders: #999,983 #999,982 #999,981 + +A customer places order #1,000,001. It is now the newest order: first in the list. + +GET /api/orders?page=1&size=20 + 200 OK, 20 orders, 34 ms + first 3 orders: #999,981 #999,980 #999,979 + +RESULT: SHIFTED. Order #999,981 was returned twice: at the end of page 1 and again at the start of page 2. + The new order moved every other order down by one, and OFFSET 20 counts from the new top. +``` + +Order #999,981 was position 20 when page 1 was read. Then a new order took position 1 and pushed +everything down: #999,981 is now position 21. "Skip 20, take 20" starts at position 21. The client +gets it again. + +| Position | When page 1 was read | When page 2 was read | +|---|---|---| +| 1 | #1,000,000 | **#1,000,001** (new) | +| ... | ... | ... | +| 20 | #999,981 (last of page 1) | #999,982 | +| 21 | #999,980 | **#999,981** (first of page 2: again) | + +The order is perfectly stable here. The tie-breaker from Task 3 is in place and it did not help, +because this is a different problem: `OFFSET` is a **position**, and positions move when rows are +added or removed. + +### Step 3: the other direction + +Read page 1, then delete one order from page 1, then read page 2. Everything moves **up** by one: +the order that was at position 21 is now at position 20. Page 2 starts at 21, so that order is on +neither page the client saw. It is skipped, silently. For a screen that is an annoyance. For an +export or a sync job it is lost data. + +### Step 4 and 5: depth, again + +```bash +./demo +``` + +``` +RESULT: DEEP OFFSET. Page 5,000 read 100,001 rows to return 20. Page 1 read 41. +``` + +Unchanged, as expected. (Page 1 now reads 41 rows, not 20: the index is on `created_at` alone, so +Postgres reads the whole batch of 40 equal rows and sorts it by id. `./inspect` shows it as +`Incremental Sort`. Task 5 fixes that.) + +The export that reads every page: page n reads n x 20 rows, so 50,000 pages read +20 x (1 + 2 + ... + 50,000), about **25 billion rows**, to export one million. + +`./check 4` prints 2 of 2: one test for the insert, one for the delete. Both pass now and at the +end, because they describe what `OFFSET` is. + +**What to take away:** `OFFSET n` reads n rows and throws them away, and no index changes that. +`OFFSET` is a position in a list that keeps changing: an insert repeats a row, a delete skips one. +A unique `ORDER BY` fixes ties. It fixes neither of these. + +--- + +## Task 5: Fix It With Keyset Pagination + +**The idea:** do not say "skip 99,980 rows". Say "give me the 20 orders that come after **this +one**". The database can find "this one" in an index in 3 or 4 page reads, wherever it is. The last +row of each page becomes the bookmark for the next: the **cursor**. The technique is called keyset +pagination, cursor pagination or the seek method. + +### Before + +`GET /api/orders/feed` was started this way and never finished. + +```bash +./demo --mode keyset +``` + +``` +--- Page 2: the client sends back the nextCursor of page 1 --- +GET /api/orders/feed?size=20&after=2025-11-25T10%3A00%3A00Z%7C999980 + 200 OK, 20 orders, 14 ms + SQL statements sent: 1 + 1. select * from orders where created_at < ? order by created_at desc limit ? -- ? = '2025-11-25T10:00:00Z', 20 + Index Scan Backward using idx_orders_created_at on orders + rows read: 20 | rows returned: 20 | pages read: 4 +... +RESULT: SKIPPED ROWS. After two pages a client should have seen the 40 newest orders. 20 of them were never returned, for example #1,000,000. +RESULT: SKIPPED ROWS. Page 5,000 comes after 99,980 orders, so it should hold the next 20. 20 of them were not returned, for example #900,020. +``` + +It is fast: 20 rows read, at any depth. And it is wrong. The newest 40 orders all share one +`created_at`. Page 1 returned 20 of them. Page 2 asked for `created_at < ?`, strictly older, and so +jumped over the other 20. It is Task 3 again: `created_at` alone does not identify a position. + +### Step 1: the query + +The position of a row is the pair `(created_at, id)`. "After this row" in the order +`created_at DESC, id DESC` means: an older `created_at`, **or** the same `created_at` and a smaller +`id`. SQL can say that in one comparison. In `OrderRepository`, replace the two feed queries: + +```java +@Query(value = """ + select * from orders + order by created_at desc, id desc + limit :limit + """, nativeQuery = true) +List feedFirstPage(@Param("limit") int limit); + +@Query(value = """ + select * from orders + where (created_at, id) < (:createdAt, :id) + order by created_at desc, id desc + limit :limit + """, nativeQuery = true) +List feedAfter(@Param("createdAt") Instant createdAt, @Param("id") long id, @Param("limit") int limit); +``` + +`(created_at, id) < (?, ?)` is a **row-value comparison**. It compares like a dictionary: first by +`created_at`, and only if those are equal, by `id`. That is exactly how the `ORDER BY` sorts. + +Two wrong versions you will meet: + +| Condition | What goes wrong | +|---|---| +| `created_at < ?` | Skips the rest of the rows with the same `created_at` (what the code did) | +| `created_at <= ?` | Returns the rows with the same `created_at` again | +| `created_at < ? AND id < ?` | Loses every older order with a larger id. `(1, 9) < (2, 1)` is true, `1 < 2 AND 9 < 1` is false | + +### Step 2: hasNext without counting + +In `OrderService`, replace the body of `feed`: + +```java +public FeedPage feed(Cursor after, int size) { + // One row more than the page: if it comes back, there is a next page. + List rows = after == null + ? orders.feedFirstPage(size + 1) + : orders.feedAfter(after.createdAt(), after.id(), size + 1); + boolean hasNext = rows.size() > size; + List items = hasNext ? rows.subList(0, size) : rows; + String nextCursor = hasNext ? Cursor.after(items.getLast()).encode() : null; + return new FeedPage(responses(items), nextCursor, hasNext); +} +``` + +Ask for 21, return 20. If the 21st row exists, there is a next page. The old code used "the page is +full" instead, which is wrong when the last page happens to be exactly full: it promises one more +page, and that page is empty. + +The cursor is built from the last row the client **received** (row 20), not from the extra row. + +### Look before you go on + +`./demo --mode keyset`: + +``` +RESULT: NO MATCHING INDEX. The pages are right, but page 5,000 read 81 rows and sorted them to return 20. + The feed is sorted by (created_at, id). No index on orders has exactly those columns. +``` + +The rows are right now, and `./check 5` is at 3 of 6: it reports +`plan has a Sort step: [Limit, Incremental Sort, Index Scan Backward using idx_orders_created_at on orders]`. But the only index is on `created_at`, so Postgres can use it for the first +half of the comparison only: it reads whole batches of equal `created_at`, filters them by id and +sorts them. + +### Step 3: the index + +In `src/main/resources/indexes.sql`, replace the `idx_orders_created_at` line: + +```sql +CREATE INDEX idx_orders_created_at_id ON orders (created_at, id); +``` + +The index now has the same columns, in the same order, as the `ORDER BY`. Replace, do not add: the +new index can do everything the old one did, and every extra index slows down writes +([`../03-indexes`](../03-indexes/), Task 10). + +### After + +```bash +./demo --mode keyset +``` + +``` +indexes.sql changed: rebuilding 2 indexes... +Indexes ready in 0.5 s. + +--- Page 5,000 --- +A client gets here by following nextCursor 4,999 times. To save you the wait, the +demo looked up the last order of page 4,999 in the database and built the cursor from it. +GET /api/orders/feed?size=20&after=2025-09-17T00%3A00%3A00Z%7C900021 + 200 OK, 20 orders, 6 ms + SQL statements sent: 1 + 1. select * from orders where (created_at, id) < (?, ?) order by created_at desc, id desc limit ? -- ? = '2025-09-17T00:00:00Z', 900021, 21 + Index Scan Backward using idx_orders_created_at_id on orders + rows read: 21 | rows returned: 21 | pages read: 5 + + page 1 page 5,000 +Rows returned to the client 20 20 +Rows read 21 21 +Rows read and thrown away 1 1 +Pages read (8 kB each) 4 5 +Time in the database 0.06 ms 0.07 ms (differs on every run) + +RESULT: OK. Page 5,000 read 21 rows to return 20. Page 1 read 21. +``` + +21 rows on page 1, 21 rows on page 5,000. `./check 5` prints 6 of 6. + +--- + +## Task 6: Fix the Cursor + +Look at the URL in the output above: `after=2025-09-17T00%3A00%3A00Z%7C900021`. The cursor is a +readable timestamp and an id. Two problems. + +**Clients will build it.** Once a client knows the format it will construct cursors itself, and from +then on you cannot change the sort key or the format without breaking that client. + +**Rubbish becomes a 500.** `./check 6`: + +``` + [FAIL] HTTP: a malformed cursor returns 400 INVALID_CURSOR, not a 500 + Request processing failed: java.time.format.DateTimeParseException: Text 'not-a-cursor' could not be parsed at index 0 +``` + +A 500 means "the server has a bug". A bad cursor is the client's mistake: a 400. + +### The change + +In `Cursor`, replace `encode` and `decode`: + +```java +public String encode() { + String text = createdAt + "|" + id; + return Base64.getUrlEncoder().withoutPadding().encodeToString(text.getBytes(StandardCharsets.UTF_8)); +} + +public static Cursor decode(String encoded) { + try { + String text = new String(Base64.getUrlDecoder().decode(encoded), StandardCharsets.UTF_8); + int separator = text.indexOf('|'); + if (separator < 0) { + throw new InvalidCursorException(); + } + Instant createdAt = Instant.parse(text.substring(0, separator)); + long id = Long.parseLong(text.substring(separator + 1)); + return new Cursor(createdAt, id); + } catch (IllegalArgumentException | DateTimeException e) { + throw new InvalidCursorException(); + } +} +``` + +Imports: `java.nio.charset.StandardCharsets`, `java.time.DateTimeException`, `java.util.Base64`. + +- `getUrlEncoder()` uses `-` and `_` instead of `+` and `/`, so the cursor can go in a URL as it is. +- Four things can be wrong with the input: not Base64 (`IllegalArgumentException`), no separator, + not a timestamp (`DateTimeParseException`, a `DateTimeException`), not a number + (`NumberFormatException`, an `IllegalArgumentException`). All four end as + `InvalidCursorException`, which `ApiExceptionHandler` already maps to 400 `INVALID_CURSOR`. +- The error message does not repeat what the client sent. Nothing here renders HTML, but echoing + input back is a habit to avoid. + +### Opaque is not secret + +Base64 is an encoding. Anyone can decode `MjAyNS0wOS0xN1QwMDowMDowMFp8OTAwMDIx` back to +`2025-09-17T00:00:00Z|900021`. That is fine: it holds nothing the client did not already receive. +"Opaque" is a contract, not a lock: *this string is ours, send it back unchanged*. Never put +anything in a cursor that the client may not see, and validate it like any other input. If a client +must not be able to invent a position, sign the cursor. + +`./check 6` prints 5 of 5. Run `./check 5` too: it must still be green. + +--- + +## Task 7: Inspect Keyset Pagination + +### Step 1 and 2: why depth does not matter + +```bash +./inspect --mode keyset +``` + +``` + EXPLAIN (ANALYZE, BUFFERS) + Limit (cost=0.42..1.55 rows=21 width=37) (actual time=0.018..0.021 rows=21 loops=1) + Buffers: shared hit=5 + -> Index Scan Backward using idx_orders_created_at_id on orders (cost=0.42..48455.38 rows=900690 width=37) (actual time=0.017..0.019 rows=21 loops=1) + Index Cond: (ROW(created_at, id) < ROW('2025-09-17 01:00:00+01'::timestamp with time zone, '900021'::bigint)) + Buffers: shared hit=5 +``` + +Compare with Task 1. There the index scan had no condition, started at the newest order and +produced 100,000 rows. Here it has an `Index Cond`: Postgres walks down the B-tree to +`(2025-09-17, 900021)` and starts reading **there**. `rows=21`, 5 pages. The offset plan started at +the top and counted. This one starts at the value. + +(The timestamp shows in your machine's time zone. `rows=900690` in the first bracket is the +planner's estimate of how many rows match the condition; the `Limit` stops it after 21.) + +`./demo --mode keyset --depth 50000` reads 20 rows for the very last page. Offset read 1,000,000. + +`limit 21`, 20 returned (step 3): the extra row is only looked at to set `hasNext`, then dropped. + +### Step 4: an order arrives between two requests + +```bash +./demo --mode keyset --insert +``` + +``` +GET /api/orders/feed?size=20 + 200 OK, 20 orders, 7 ms + last 3 orders: #999,983 #999,982 #999,981 + +A customer places order #1,000,001. It is now the newest order: first in the list. + +GET /api/orders/feed?size=20&after=MjAyNS0xMS0yNVQxMDowMDowMFp8OTk5OTgx + 200 OK, 20 orders, 12 ms + first 3 orders: #999,980 #999,979 #999,978 + +RESULT: OK. Page 2 continues exactly where page 1 ended. No order was returned twice or skipped. +``` + +Page 2 is "everything after #999,981". A new order at the top is not after #999,981, so it changes +nothing. The client does not see the new order in this pass: to see it, it starts again from the +top. + +### Step 5: what if the cursor's order is deleted? + +Nothing. The cursor holds **values**, `(created_at, id)`, not a pointer to a row. "Everything that +sorts after these values" is a valid question whether or not a row with those values still exists. + +### Step 6 and 7: what you gave up + +- **No jumping.** The demo had to look up the last order of page 4,999 to build a cursor for page + 5,000. A client cannot. There is no "page 400", only "next". +- **One sort order per endpoint.** Sorting by `total_cents` needs a new query + (`(total_cents, id) < (?, ?)`), a new cursor (it must carry `total_cents`) and a new index on + `(total_cents, id)`. With offset, changing the sort is one parameter. +- **The key must be unique and stable.** Unique: that is what the `id` is for. Stable: if you sort + by `updated_at` and a row is updated while a client is paging, it moves, and the client can see it + twice or not at all. + +### A note on Spring Data's own keyset API + +Spring Data can do keyset pagination for you: a repository method that returns `Window` and +takes a `ScrollPosition`, started with `ScrollPosition.keyset()`. We ran it on Spring Boot 4 against +this table. It works, and it returns the right rows. But look at the SQL it sends: + +``` +where o1_0.created_at`. A `Page` knows `getTotalElements()` and +`getTotalPages()`, and the only way to know them is to count. So Spring Data runs the count for +you, on every request. (It skips it only when the page comes back shorter than the requested size: +then the total is already known.) + +In Postgres a count is not a number stored somewhere. It reads every matching row: + +``` + Aggregate (cost=20834.00..20834.01 rows=1 width=8) (actual time=108.002..108.003 rows=1 loops=1) + -> Seq Scan on orders o1_0 (cost=0.00..18334.00 rows=1000000 width=8) (actual time=0.011..62.942 rows=1000000 loops=1) +``` + +One million rows and 8,334 pages, to fill a field that `OffsetPage` does not even have. The screen +has a "Next" button. It needs `hasNext`, nothing more. + +### The change + +A `Slice` is a `Page` without the total. In `OrderRepository`, replace the comment about `findAll` +and the `findByCustomerId` method: + +```java +Slice findAllBy(Pageable pageable); + +Slice findByCustomerId(long customerId, Pageable pageable); +``` + +Import `org.springframework.data.domain.Slice` and remove the `Page` import. `findAll(Pageable)` is +inherited and always returns a `Page`, so you declare `findAllBy`: the same query, and the return +type tells Spring Data not to count. + +In `OrderService`, in `page` and in `history`: + +```java +Slice result = orders.findAllBy(PageRequest.of(page, size, NEWEST_FIRST)); +``` + +```java +Slice result = orders.findByCustomerId(customerId, PageRequest.of(page, size, NEWEST_FIRST)); +``` + +Same import change. `result.getContent()` and `result.hasNext()` work as before. + +### After + +```bash +./demo +``` + +``` +GET /api/orders?page=0&size=20 + 200 OK, 20 orders, 6 ms + SQL statements sent: 1 + 1. select ... from orders o1_0 order by o1_0.created_at desc,o1_0.id desc fetch first ? rows only -- ? = 21 +... +RESULT: DEEP OFFSET. Page 5,000 read 100,001 rows to return 20. Page 1 read 21. +``` + +One statement. `? = 21`: a `Slice` uses the same trick you wrote by hand in Task 5. It asks for +`size + 1` rows and uses the extra one for `hasNext`. And the request went from about 32 ms to +about 6 ms, on page 1, for every user. + +`RESULT: DEEP OFFSET` is still there, and it stays: this endpoint uses `OFFSET`. + +`./check` now prints 35 passes and no failures. + +### If the screen really needs a total + +Ask how exact it has to be. `./inspect` shows `rows 1,000,000` for the table: that is the planner's +estimate (`pg_class.reltuples`), free and good enough for "about a million orders". Other options: +count up to a limit and show "10,000+", cache the count for a minute, or count only on the first +page. An exact count on every request is the most expensive choice, and with `Page` it is the +default. + +--- + +## Task 9: Compare Offset and Keyset + +### Step 1: the numbers + +Run `./demo` and `./demo --mode keyset`, each with `--depth 5000` and `--depth 50000`. Rows read, +from runs of the finished project. They are the same on every machine. + +| | Page 1 | Page 5,000 | Page 50,000 | Statements per request | +|---|---|---|---|---| +| Offset, as it started | 20 | 100,000 | 1,000,000 | 2 (plus 1,000,000 rows for the count) | +| Offset, after Task 8 | 21 | 100,001 | 1,000,000 | 1 | +| Keyset | 21 | 21 | 20 | 1 | + +### Step 2 and 3 + +`./demo --insert` prints `RESULT: SHIFTED`. `./demo --mode keyset --insert` prints `RESULT: OK`. + +```bash +./demo --depth 3 +``` + +``` +RESULT: OK. Page 3 read 61 rows to return 20. Page 1 read 21. +``` + +Page 3 costs 61 rows. That is nothing. Offset is not slow. **Deep** offset is slow. + +### Step 4, 5 and 6: the honest answer + +- Jump to page 400: only offset can. Keyset has no page numbers. +- 300 products, sortable by any column: use offset. The deepest page reads 300 rows. Keyset would + need a cursor format and an index per sort column, for no gain. +- A total without counting: the estimate in `pg_class.reltuples`. + +### When to use which + +| | Offset | Keyset | +|---|---|---| +| Cost of page N | Reads N x size rows | Reads size + 1 rows, at any depth | +| Rows inserted or deleted while paging | A row repeats or is skipped | Nothing shifts | +| Jump to page N, "page 37 of 500" | Yes | No: next only (previous with a second query) | +| Sort order | Any, chosen per request | One per endpoint: unique, stable, indexed | +| What the client keeps | A page number | An opaque cursor | +| Use it when | Small tables, admin screens, shallow paging, page numbers required | Feeds, infinite scroll, exports, sync jobs, anything deep or busy | + +Whichever you use: a default and a maximum page size, an `ORDER BY` that ends in a unique column, +and no `COUNT` unless somebody reads the total. + +### How to say it in an interview + +> "With OFFSET the database has to produce all the rows before the page and throw them away, so page +> 5,000 of 20 reads 100,000 rows. It is also a position in a list that changes: if a row is inserted +> between two requests, the user sees a row twice. For a large or busy table I would use keyset +> pagination instead: order by a unique key, for example created_at and then id, and ask for the +> rows after the last one I returned, with a row comparison, `WHERE (created_at, id) < (?, ?)`, and +> an index on the same columns. Every page then reads page size plus one rows, and I use that extra +> row to know if there is a next page, so I do not need a COUNT. The client gets an opaque cursor. +> The trade-off is that you cannot jump to page N and you need a fixed sort key, so for a small admin +> table with sortable columns I would keep offset, with a maximum page size, and a Slice instead of +> a Page so Spring Data does not count on every request." + +Then be ready for the follow-ups in "Questions to Ask Afterwards" at the end of +[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md). + +--- + +## Clean up + +```bash +docker compose down +``` diff --git a/java/concepts/junior-mid/11-pagination/solution/.mvn/jvm.config b/java/concepts/junior-mid/11-pagination/solution/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/.mvn/jvm.config @@ -0,0 +1,2 @@ +--enable-native-access=ALL-UNNAMED +--sun-misc-unsafe-memory-access=allow diff --git a/java/concepts/junior-mid/11-pagination/solution/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/11-pagination/solution/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/java/concepts/junior-mid/11-pagination/solution/check b/java/concepts/junior-mid/11-pagination/solution/check new file mode 100755 index 0000000..69483ac --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/check @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use check.cmd (type: .\check). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.pagination.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/11-pagination/solution/check.cmd b/java/concepts/junior-mid/11-pagination/solution/check.cmd new file mode 100644 index 0000000..bd80c37 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/check.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./check +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.pagination.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/11-pagination/solution/compose.yaml b/java/concepts/junior-mid/11-pagination/solution/compose.yaml new file mode 100644 index 0000000..a20e258 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/compose.yaml @@ -0,0 +1,18 @@ +# The project name is set here because the folder is called "solution" (or "start") in every +# project of this repository: without it, "docker compose down" in another project would stop this one. +name: pagination +services: + postgres: + image: postgres:17-alpine + container_name: pagination-postgres + environment: + POSTGRES_DB: pagination + POSTGRES_USER: pagination + POSTGRES_PASSWORD: pagination + ports: + - "5450:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U pagination -d pagination"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/11-pagination/solution/demo b/java/concepts/junior-mid/11-pagination/solution/demo new file mode 100755 index 0000000..6268ffe --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/demo @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use demo.cmd (type: .\demo). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.pagination.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/11-pagination/solution/demo.cmd b/java/concepts/junior-mid/11-pagination/solution/demo.cmd new file mode 100644 index 0000000..c24ba01 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/demo.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./demo +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.pagination.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/11-pagination/solution/inspect b/java/concepts/junior-mid/11-pagination/solution/inspect new file mode 100755 index 0000000..a307d0f --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/inspect @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use inspect.cmd (type: .\inspect). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.pagination.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/11-pagination/solution/inspect.cmd b/java/concepts/junior-mid/11-pagination/solution/inspect.cmd new file mode 100644 index 0000000..4bac1ac --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/inspect.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./inspect +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.pagination.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/11-pagination/solution/mvnw b/java/concepts/junior-mid/11-pagination/solution/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/java/concepts/junior-mid/11-pagination/solution/mvnw.cmd b/java/concepts/junior-mid/11-pagination/solution/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/java/concepts/junior-mid/11-pagination/solution/pom.xml b/java/concepts/junior-mid/11-pagination/solution/pom.xml new file mode 100644 index 0000000..e7c1f10 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + pagination + 0.0.1-SNAPSHOT + pagination + Pagination: see the deep OFFSET, the shifting rows and the hidden COUNT, then fix them with keyset pagination + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + runtime + + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.mockito + mockito-core + + + org.mockito + mockito-junit-jupiter + + + + + org.springframework.boot + spring-boot-starter-data-jpa-test + test + + + org.testcontainers + testcontainers-postgresql + test + + + org.junit.platform + junit-platform-launcher + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + false + + + + + + diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/ApiExceptionHandler.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/ApiExceptionHandler.java new file mode 100644 index 0000000..c3e6f8d --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/ApiExceptionHandler.java @@ -0,0 +1,37 @@ +package com.amigoscode.pagination; + +import com.amigoscode.pagination.order.InvalidCursorException; +import com.amigoscode.pagination.order.InvalidPageRequestException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; + +/** Anything not listed here becomes a 500. */ +@RestControllerAdvice +public class ApiExceptionHandler { + + public record ApiError(String code, String message) { + } + + @ExceptionHandler(InvalidPageRequestException.class) + public ResponseEntity invalidPageRequest(InvalidPageRequestException e) { + return error("INVALID_PAGE_REQUEST", e.getMessage()); + } + + @ExceptionHandler(InvalidCursorException.class) + public ResponseEntity invalidCursor(InvalidCursorException e) { + return error("INVALID_CURSOR", e.getMessage()); + } + + /** For example size=abc. */ + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + public ResponseEntity notANumber(MethodArgumentTypeMismatchException e) { + return error("BAD_REQUEST", e.getName() + " must be a number"); + } + + private static ResponseEntity error(String code, String message) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ApiError(code, message)); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/PaginationApplication.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/PaginationApplication.java new file mode 100644 index 0000000..50b11ec --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/PaginationApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.pagination; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class PaginationApplication { + + public static void main(String[] args) { + SpringApplication.run(PaginationApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/DatabaseSetup.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/DatabaseSetup.java new file mode 100644 index 0000000..2e6193c --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/DatabaseSetup.java @@ -0,0 +1,169 @@ +package com.amigoscode.pagination.db; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.HexFormat; +import java.util.List; +import java.util.Locale; +import java.util.function.Consumer; + +/** + * Puts the database in a known state. Safe to run as often as you like: + * + * 1. schema.sql creates the table if it is missing. + * 2. If the table was not seeded with the wanted number of rows, it is emptied and seeded again + * with generate_series: the rows are made inside Postgres, which takes seconds, not minutes. + * 3. If indexes.sql changed since the last run, every index except the primary key is dropped and + * indexes.sql is run again. Then VACUUM ANALYZE refreshes the planner's statistics. + * + * When nothing changed, steps 2 and 3 are skipped and this takes a few milliseconds. + */ +public final class DatabaseSetup { + + public static final long DEFAULT_ORDERS = 1_000_000; + + /** Orders that arrive together and share one created_at. */ + public static final int BATCH = 40; + + /** A problem the student can fix, for example a typo in indexes.sql. */ + public static final class SetupException extends RuntimeException { + public SetupException(String message) { + super(message); + } + } + + public static void run(Connection connection, long orders, Consumer log) throws SQLException { + if (orders < 1_000 || orders % BATCH != 0) { + throw new IllegalArgumentException("Seed at least 1,000 orders, in a multiple of " + BATCH + ", got " + orders); + } + connection.setAutoCommit(true); + try (Statement statement = connection.createStatement()) { + // Only one setup at a time, even if the application and ./demo start together. + statement.execute("select pg_advisory_lock(20261125)"); + try { + for (String sql : SqlScript.statements(SqlScript.read("schema.sql"))) { + statement.execute(sql); + } + boolean seeded = seed(connection, statement, orders, log); + applyIndexes(connection, statement, seeded, log); + } finally { + statement.execute("select pg_advisory_unlock(20261125)"); + } + } + } + + /** Forgets what was seeded, so the next run starts from an empty table. */ + public static void forget(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute("drop table if exists setup_state"); + } + } + + private static boolean seed(Connection connection, Statement statement, long orders, Consumer log) + throws SQLException { + if (String.valueOf(orders).equals(state(connection, "seeded_orders"))) { + return false; + } + log.accept(String.format(Locale.US, "Seeding %,d orders (first run only)...", orders)); + long start = System.nanoTime(); + + statement.execute("delete from setup_state"); + statement.execute("truncate table orders"); + dropSecondaryIndexes(connection, statement); + + // The shop sells through a marketplace, which sends its orders in batches: 40 orders every + // 40 minutes, written in one transaction, so all 40 share the same created_at. + // - The first 12 orders of a batch belong to one business customer (ids 1 to 1,000, taking + // turns), so a business customer has many orders with the same created_at. + // - The other 28 belong to retail customers (ids from 1,001). + // - Only the newest orders are still PENDING. Of the rest, one in twenty was CANCELLED. + statement.execute(""" + insert into orders (id, customer_id, status, total_cents, created_at) + select i, + case when (i - 1) %% %2$d < 12 then 1 + ((i - 1) / %2$d) %% 1000 + else 1001 + (i * 7919) %% 99000 end, + case when i > %1$d - %1$d / 250 then 'PENDING' + when i %% 20 = 0 then 'CANCELLED' + else 'DELIVERED' end, + 500 + (i * 7919) %% 50000, + timestamptz '2024-01-01 00:00:00+00' + make_interval(mins => (((i - 1) / %2$d) * 40)::int) + from generate_series(1::bigint, %1$d) as i + """.formatted(orders, BATCH)); + + setState(connection, "seeded_orders", String.valueOf(orders)); + log.accept(String.format(Locale.US, "Seeded in %.1f s.", (System.nanoTime() - start) / 1e9)); + return true; + } + + private static void applyIndexes(Connection connection, Statement statement, boolean seeded, Consumer log) + throws SQLException { + String script = SqlScript.read("indexes.sql"); + List statements = SqlScript.statements(script); + String hash = sha256(String.join(";", statements)); + if (!seeded && hash.equals(state(connection, "indexes_sql"))) { + return; + } + log.accept("indexes.sql changed: rebuilding " + statements.size() + + (statements.size() == 1 ? " index..." : " indexes...")); + long start = System.nanoTime(); + statement.execute("delete from setup_state where key = 'indexes_sql'"); + dropSecondaryIndexes(connection, statement); + for (int i = 0; i < statements.size(); i++) { + try { + statement.execute(statements.get(i)); + } catch (SQLException e) { + throw new SetupException("Statement " + (i + 1) + " in src/main/resources/indexes.sql failed:\n\n " + + statements.get(i) + "\n\n" + e.getMessage().lines().findFirst().orElse("")); + } + } + // ANALYZE collects the statistics the planner uses to choose a plan. + statement.execute("vacuum (analyze) orders"); + setState(connection, "indexes_sql", hash); + log.accept(String.format(Locale.US, "Indexes ready in %.1f s.", (System.nanoTime() - start) / 1e9)); + } + + private static void dropSecondaryIndexes(Connection connection, Statement statement) throws SQLException { + for (IndexInfo index : IndexInfo.all(connection)) { + if (index.secondary()) { + statement.execute("drop index if exists \"" + index.name() + "\""); + } + } + } + + private static String state(Connection connection, String key) throws SQLException { + try (PreparedStatement select = connection.prepareStatement("select value from setup_state where key = ?")) { + select.setString(1, key); + try (ResultSet row = select.executeQuery()) { + return row.next() ? row.getString(1) : null; + } + } + } + + private static void setState(Connection connection, String key, String value) throws SQLException { + try (PreparedStatement upsert = connection.prepareStatement(""" + insert into setup_state (key, value) values (?, ?) + on conflict (key) do update set value = excluded.value + """)) { + upsert.setString(1, key); + upsert.setString(2, value); + upsert.executeUpdate(); + } + } + + private static String sha256(String text) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private DatabaseSetup() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/DatabaseSetupRunner.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/DatabaseSetupRunner.java new file mode 100644 index 0000000..a6a1a1d --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/DatabaseSetupRunner.java @@ -0,0 +1,32 @@ +package com.amigoscode.pagination.db; + +import java.sql.Connection; +import java.sql.SQLException; +import javax.sql.DataSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** Runs DatabaseSetup when the application starts: the table, the rows, then the indexes from indexes.sql. */ +@Component +public class DatabaseSetupRunner implements InitializingBean { + + private static final Logger log = LoggerFactory.getLogger(DatabaseSetupRunner.class); + + private final DataSource dataSource; + private final long orders; + + public DatabaseSetupRunner(DataSource dataSource, @Value("${shop.seed.orders}") long orders) { + this.dataSource = dataSource; + this.orders = orders; + } + + @Override + public void afterPropertiesSet() throws SQLException { + try (Connection connection = dataSource.getConnection()) { + DatabaseSetup.run(connection, orders, log::info); + } + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/Explain.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/Explain.java new file mode 100644 index 0000000..644018c --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/Explain.java @@ -0,0 +1,55 @@ +package com.amigoscode.pagination.db; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +/** + * Asks Postgres how it runs a statement the application sent. EXPLAIN ANALYZE really executes the + * statement, with the same values, and reports what happened: which scan, how many rows, how many + * pages. + * + * Parallel query is switched off for the EXPLAIN, so a sequential scan shows up as one plain + * "Seq Scan" line instead of "Gather" over "Parallel Seq Scan" with per-worker numbers. + */ +public final class Explain { + + /** The plan as an object you can ask questions. */ + public static Plan analyze(Connection connection, SqlStatement statement) throws SQLException { + return Plan.parse(String.join("\n", run(connection, "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ", statement))); + } + + /** The plan as the text Postgres prints, one line per list entry. */ + public static List text(Connection connection, SqlStatement statement) throws SQLException { + return run(connection, "EXPLAIN (ANALYZE, BUFFERS) ", statement); + } + + private static List run(Connection connection, String explain, SqlStatement statement) throws SQLException { + try (Statement settings = connection.createStatement()) { + settings.execute("SET max_parallel_workers_per_gather = 0"); + try (PreparedStatement prepared = connection.prepareStatement(explain + statement.sql())) { + statement.bindTo(prepared); + List lines = new ArrayList<>(); + try (ResultSet row = prepared.executeQuery()) { + while (row.next()) { + lines.add(row.getString(1)); + } + } + return lines; + } finally { + try { + settings.execute("RESET max_parallel_workers_per_gather"); + } catch (SQLException ignored) { + // The transaction is already broken by the real error, which is the one to report. + } + } + } + } + + private Explain() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/IndexInfo.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/IndexInfo.java new file mode 100644 index 0000000..9c80a09 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/IndexInfo.java @@ -0,0 +1,51 @@ +package com.amigoscode.pagination.db; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +/** + * One index on the orders table, as the database catalog describes it. + * + * @param definition the CREATE INDEX statement Postgres would use to rebuild it + * @param secondary false for the index that backs the PRIMARY KEY + * @param scans how many times a query used it since it was created + */ +public record IndexInfo(String name, String definition, long sizeBytes, long scans, boolean secondary) { + + private static final String SQL = """ + select c.relname as index_name, + pg_get_indexdef(i.indexrelid) as definition, + pg_relation_size(i.indexrelid) as size_bytes, + coalesce(s.idx_scan, 0) as scans, + not exists (select 1 from pg_constraint k where k.conindid = i.indexrelid) as secondary + from pg_index i + join pg_class c on c.oid = i.indexrelid + join pg_class t on t.oid = i.indrelid + left join pg_stat_user_indexes s on s.indexrelid = i.indexrelid + where t.relname = 'orders' + and t.relnamespace = 'public'::regnamespace + order by secondary, c.relname + """; + + /** Every index on orders. */ + public static List all(Connection connection) throws SQLException { + List indexes = new ArrayList<>(); + try (Statement statement = connection.createStatement(); ResultSet row = statement.executeQuery(SQL)) { + while (row.next()) { + indexes.add(new IndexInfo(row.getString("index_name"), row.getString("definition"), + row.getLong("size_bytes"), row.getLong("scans"), row.getBoolean("secondary"))); + } + } + return indexes; + } + + /** The part of the definition after the table name, for example "(created_at, id)". */ + public String columns() { + int at = definition.indexOf(" USING btree "); + return at < 0 ? definition : definition.substring(at + " USING btree ".length()); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/Plan.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/Plan.java new file mode 100644 index 0000000..f16a568 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/Plan.java @@ -0,0 +1,145 @@ +package com.amigoscode.pagination.db; + +import java.util.ArrayList; +import java.util.List; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * A query plan, parsed from the output of EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON). A plan is a tree + * of nodes: this class flattens it into a list, which is enough to answer "how many rows were read?". + */ +public final class Plan { + + /** + * One step of the plan. + * + * @param type "Seq Scan", "Index Scan", "Sort", "Incremental Sort", "Limit", "Aggregate"... + * @param relation the table the step reads, or null + * @param index the index the step uses, or null + * @param backward true when the index is read from its end to its start (ORDER BY ... DESC) + * @param condition the condition answered by the index (Index Cond), or null + * @param filter the condition checked row by row after reading (Filter), or null + * @param rows rows the step passed on + * @param removedByFilter rows the step read and then threw away + * @param heapFetches for an Index Only Scan: how many times it still had to visit the table + */ + public record Node(String type, String relation, String index, boolean backward, String condition, String filter, + long rows, long removedByFilter, long heapFetches) { + + /** True for the steps that read a table: every kind of scan except the bitmap's index half. */ + public boolean readsTable() { + return relation != null && type.endsWith("Scan") && !type.equals("Bitmap Index Scan"); + } + + @Override + public String toString() { + return type + (backward ? " Backward" : "") + (index == null ? "" : " using " + index) + (relation == null ? "" : " on " + relation); + } + } + + private static final JsonMapper JSON = new JsonMapper(); + + private final List nodes = new ArrayList<>(); + private final double executionMillis; + private final long pages; + + private Plan(JsonNode root) { + JsonNode top = root.get(0); + JsonNode plan = top.path("Plan"); + this.executionMillis = top.path("Execution Time").asDouble(0); + this.pages = plan.path("Shared Hit Blocks").asLong(0) + plan.path("Shared Read Blocks").asLong(0); + collect(plan); + } + + public static Plan parse(String json) { + return new Plan(JSON.readTree(json)); + } + + private void collect(JsonNode node) { + long loops = Math.max(1, node.path("Actual Loops").asLong(1)); + nodes.add(new Node( + text(node, "Node Type"), + text(node, "Relation Name"), + text(node, "Index Name"), + "Backward".equals(text(node, "Scan Direction")), + text(node, "Index Cond"), + text(node, "Filter"), + Math.round(node.path("Actual Rows").asDouble(0) * loops), + Math.round((node.path("Rows Removed by Filter").asDouble(0) + + node.path("Rows Removed by Index Recheck").asDouble(0)) * loops), + Math.round(node.path("Heap Fetches").asDouble(0)))); + JsonNode children = node.path("Plans"); + for (int i = 0; i < children.size(); i++) { + collect(children.get(i)); + } + } + + private static String text(JsonNode node, String field) { + JsonNode value = node.get(field); + return value == null || value.isNull() ? null : value.asString(); + } + + /** Every step, the outermost first. */ + public List nodes() { + return List.copyOf(nodes); + } + + /** True if any step's type contains the text: has("Seq Scan"), has("Sort") (which also finds "Incremental Sort"). */ + public boolean has(String nodeType) { + return nodes.stream().anyMatch(node -> node.type().contains(nodeType)); + } + + /** The names of the indexes the plan uses. */ + public List indexes() { + return nodes.stream().map(Node::index).filter(index -> index != null).distinct().toList(); + } + + /** The steps that read a table. */ + public List scans() { + return nodes.stream().filter(Node::readsTable).toList(); + } + + /** Rows the query returned. */ + public long rowsReturned() { + return nodes.getFirst().rows(); + } + + /** Rows read from tables (or from an index, for an index-only scan), kept or not. */ + public long rowsRead() { + return scans().stream().mapToLong(node -> node.rows() + node.removedByFilter()).sum(); + } + + /** Rows that were read and then thrown away by a Filter. */ + public long rowsThrownAway() { + return nodes.stream().mapToLong(Node::removedByFilter).sum(); + } + + /** Table visits made by index-only scans. 0 is the goal. */ + public long heapFetches() { + return nodes.stream().mapToLong(Node::heapFetches).sum(); + } + + /** 8 kB pages the query touched, in tables and indexes together. */ + public long pages() { + return pages; + } + + public double executionMillis() { + return executionMillis; + } + + /** For example "Index Scan Backward using idx_orders_created_at on orders". */ + public String describe() { + List steps = nodes.stream() + .filter(node -> node.relation() != null || node.index() != null) + .map(Node::toString) + .toList(); + return steps.isEmpty() ? nodes.getFirst().type() : String.join(" + ", steps); + } + + @Override + public String toString() { + return describe(); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/SqlRecorder.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/SqlRecorder.java new file mode 100644 index 0000000..1739193 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/SqlRecorder.java @@ -0,0 +1,133 @@ +package com.amigoscode.pagination.db; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import javax.sql.DataSource; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.DelegatingDataSource; + +/** + * Records the SQL the application really sends to Postgres, whoever wrote it: Hibernate, Spring + * Data or a native query. ./demo, ./inspect and the tests use it to answer "what did this request + * run?" and then ask Postgres to EXPLAIN exactly that. + * + * SqlRecorder.start(); + * ... call the endpoint ... + * List statements = SqlRecorder.stop(); + * + * It works by wrapping the DataSource: every PreparedStatement is watched, and when it is executed + * its SQL and its bound values are written down. When nobody is recording, nothing is kept. + */ +public final class SqlRecorder { + + private static final Object LOCK = new Object(); + private static final Set EXECUTE = Set.of("execute", "executeQuery", "executeUpdate", "executeLargeUpdate"); + private static List recording; + + public static void start() { + synchronized (LOCK) { + recording = new ArrayList<>(); + } + } + + /** Stops recording and returns the statements executed since start(), in order. */ + public static List stop() { + synchronized (LOCK) { + List statements = recording == null ? List.of() : List.copyOf(recording); + recording = null; + return statements; + } + } + + private static void record(String sql, Map bindings) { + synchronized (LOCK) { + if (recording != null) { + recording.add(new SqlStatement(sql, List.copyOf(bindings.values()))); + } + } + } + + /** Wraps every DataSource bean of the application. */ + @Configuration + static class Wiring { + + @Bean + static BeanPostProcessor recordSqlOfEveryDataSource() { + return new BeanPostProcessor() { + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) { + return bean instanceof DataSource dataSource ? new RecordingDataSource(dataSource) : bean; + } + }; + } + } + + private static final class RecordingDataSource extends DelegatingDataSource { + + RecordingDataSource(DataSource target) { + super(target); + } + + @Override + public Connection getConnection() throws SQLException { + return watch(super.getConnection()); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return watch(super.getConnection(username, password)); + } + + private static Connection watch(Connection connection) { + return proxy(Connection.class, (proxy, method, args) -> { + Object result = call(connection, method, args); + if (method.getName().equals("prepareStatement") && result instanceof PreparedStatement statement) { + return watch(statement, (String) args[0]); + } + return result; + }); + } + + private static PreparedStatement watch(PreparedStatement statement, String sql) { + Map bindings = new TreeMap<>(); + return proxy(PreparedStatement.class, (proxy, method, args) -> { + String name = method.getName(); + if (name.startsWith("set") && args != null && args.length >= 2 && args[0] instanceof Integer index) { + bindings.put(index, new SqlStatement.Binding(method, args.clone())); + } else if (name.equals("clearParameters")) { + bindings.clear(); + } else if (EXECUTE.contains(name) && args == null) { + record(sql, bindings); + } + return call(statement, method, args); + }); + } + + private static T proxy(Class type, InvocationHandler handler) { + return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, handler)); + } + + private static Object call(Object target, Method method, Object[] args) throws Throwable { + try { + return method.invoke(target, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } + } + + private SqlRecorder() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/SqlScript.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/SqlScript.java new file mode 100644 index 0000000..167d832 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/SqlScript.java @@ -0,0 +1,44 @@ +package com.amigoscode.pagination.db; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +/** Reads a .sql file from the classpath and splits it into statements. */ +public final class SqlScript { + + /** The file's text. */ + public static String read(String resource) { + try (InputStream in = SqlScript.class.getClassLoader().getResourceAsStream(resource)) { + if (in == null) { + throw new IllegalStateException(resource + " is missing from src/main/resources"); + } + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** The statements in a script: "--" comments are removed, statements end with a semicolon. */ + public static List statements(String script) { + StringBuilder withoutComments = new StringBuilder(); + for (String line : script.lines().toList()) { + int comment = line.indexOf("--"); + withoutComments.append(comment < 0 ? line : line.substring(0, comment)).append('\n'); + } + List statements = new ArrayList<>(); + for (String statement : withoutComments.toString().split(";")) { + String trimmed = statement.strip().replaceAll("\\s+", " "); + if (!trimmed.isEmpty()) { + statements.add(trimmed); + } + } + return statements; + } + + private SqlScript() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/SqlStatement.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/SqlStatement.java new file mode 100644 index 0000000..c3a85d0 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/db/SqlStatement.java @@ -0,0 +1,69 @@ +package com.amigoscode.pagination.db; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.List; +import java.util.Locale; +import java.util.regex.Pattern; + +/** + * One SQL statement the application sent to the database, with the values it bound to the + * ? placeholders. Recorded by SqlRecorder. + */ +public record SqlStatement(String sql, List bindings) { + + /** One call like setLong(2, 20) on the PreparedStatement. */ + public record Binding(Method setter, Object[] arguments) { + + Object value() { + return arguments[1]; + } + } + + private static final Pattern COUNT = Pattern.compile("^\\s*select\\s+count\\s*\\(", Pattern.CASE_INSENSITIVE); + private static final Pattern SELECT_LIST = Pattern.compile("^(select) (.{40,}?) (from .*)$", Pattern.CASE_INSENSITIVE); + + /** True for SELECT COUNT(...): the query that counts every matching row. */ + public boolean isCount() { + return COUNT.matcher(sql).find(); + } + + /** The SQL in lower case on one line: handy for "does it contain ..." checks. */ + public String normalized() { + return sql.replaceAll("\\s+", " ").strip().toLowerCase(Locale.ROOT); + } + + /** The SQL on one line, with a long list of selected columns shortened to "...". */ + public String shortSql() { + String oneLine = sql.replaceAll("\\s+", " ").strip(); + return SELECT_LIST.matcher(oneLine).replaceFirst("$1 ... $3"); + } + + /** The bound values in placeholder order, for example [99980, 20]. */ + public List parameters() { + return bindings.stream().map(Binding::value).toList(); + } + + /** Binds the same values to another PreparedStatement, so the statement can be run again. */ + public void bindTo(PreparedStatement statement) throws SQLException { + for (Binding binding : bindings) { + try { + binding.setter().invoke(statement, binding.arguments()); + } catch (InvocationTargetException e) { + if (e.getCause() instanceof SQLException sql) { + throw sql; + } + throw new IllegalStateException(e.getCause()); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + } + + @Override + public String toString() { + return shortSql() + (bindings.isEmpty() ? "" : " " + parameters()); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/demo/App.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/demo/App.java new file mode 100644 index 0000000..aa4ee1b --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/demo/App.java @@ -0,0 +1,248 @@ +package com.amigoscode.pagination.demo; + +import com.amigoscode.pagination.PaginationApplication; +import com.amigoscode.pagination.db.DatabaseSetup; +import com.amigoscode.pagination.db.Explain; +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.db.SqlRecorder; +import com.amigoscode.pagination.db.SqlStatement; +import com.amigoscode.pagination.order.Cursor; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Timestamp; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * What ./demo and ./inspect share: the seeded database, the real application on a free port, HTTP + * requests against it, the SQL each request sent, and EXPLAIN for that SQL. + */ +final class App implements AutoCloseable { + + /** What came back from one GET, and the SQL statements the application sent to answer it. */ + record Response(String path, int status, JsonNode body, int bytes, long millis, List statements) { + + boolean ok() { + return status == 200; + } + + /** The ids of the orders in "items", in the order they were returned. */ + List ids() { + List ids = new ArrayList<>(); + JsonNode items = body.path("items"); + for (int i = 0; i < items.size(); i++) { + ids.add(items.get(i).path("id").asLong()); + } + return ids; + } + + boolean hasNext() { + return body.path("hasNext").asBoolean(false); + } + + /** The cursor for the next page of the feed, or null. */ + String nextCursor() { + JsonNode cursor = body.path("nextCursor"); + return cursor.isMissingNode() || cursor.isNull() ? null : cursor.asString(); + } + + /** For a response that is not a 200: "INVALID_CURSOR: The cursor ...". */ + String error() { + String code = body.path("code").asString(""); + String message = body.path("message").asString(body.path("error").asString("")); + return (code.isEmpty() ? "" : code + ": ") + message; + } + + /** The statements that fetch rows: everything except SELECT COUNT. */ + List pageQueries() { + return statements.stream().filter(statement -> !statement.isCount()).toList(); + } + + List countQueries() { + return statements.stream().filter(SqlStatement::isCount).toList(); + } + } + + private static final JsonMapper JSON = new JsonMapper(); + + private final Connection connection; + private final ConfigurableApplicationContext context; + private final String baseUrl; + private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build(); + private final long orders; + + private App(Connection connection, ConfigurableApplicationContext context, long orders) { + this.connection = connection; + this.context = context; + this.baseUrl = "http://localhost:" + context.getEnvironment().getProperty("local.server.port"); + this.orders = orders; + } + + /** + * Seeds the database if needed, applies indexes.sql and starts the application. Returns null, + * after printing why, when Postgres is not reachable or indexes.sql has a mistake in it. + */ + static App start(boolean reseed) throws Exception { + if (!Db.isUp()) { + return null; + } + Connection connection = Db.connect(); + System.out.println(); + if (reseed) { + DatabaseSetup.forget(connection); + } + boolean[] logged = new boolean[1]; + try { + DatabaseSetup.run(connection, DatabaseSetup.DEFAULT_ORDERS, message -> { + logged[0] = true; + System.out.println(message); + }); + } catch (DatabaseSetup.SetupException e) { + System.out.println(e.getMessage()); + System.out.println(); + System.out.println("Fix the statement and run the command again."); + System.out.println(); + connection.close(); + return null; + } + if (logged[0]) { + System.out.println(); + } + try (Statement statement = connection.createStatement()) { + // An order left behind by a demo run that was stopped half way. + statement.execute("delete from orders where id > " + DatabaseSetup.DEFAULT_ORDERS); + } + + SpringApplication app = new SpringApplication(PaginationApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + ConfigurableApplicationContext context = app.run( + "--server.port=0", + "--logging.level.root=WARN", + // A 500 is shown as one line instead of a full stack trace. + "--logging.level.org.apache.catalina.core.ContainerBase=OFF", + "--spring.web.error.include-message=always"); + App started = new App(connection, context, DatabaseSetup.DEFAULT_ORDERS); + // Throwaway requests, so the first real one is not slowed down by startup work. + started.get("/api/orders/feed?size=1"); + started.get("/api/orders?page=0&size=1"); + started.get("/api/customers/1/orders?page=0&size=1"); + return started; + } + + long orders() { + return orders; + } + + Connection connection() { + return connection; + } + + /** Sends GET path to the running application and writes down the SQL it sends meanwhile. */ + Response get(String path) throws Exception { + HttpRequest request = HttpRequest.newBuilder(URI.create(baseUrl + path)).build(); + SqlRecorder.start(); + long start = System.nanoTime(); + HttpResponse response; + List statements; + try { + response = http.send(request, HttpResponse.BodyHandlers.ofByteArray()); + } finally { + statements = SqlRecorder.stop(); + } + long millis = (System.nanoTime() - start) / 1_000_000; + JsonNode body; + try { + body = JSON.readTree(response.body()); + } catch (RuntimeException e) { + body = JSON.createObjectNode(); + } + return new Response(path, response.statusCode(), body, response.body().length, millis, statements); + } + + /** Runs the statement again with EXPLAIN (ANALYZE, BUFFERS) and returns what Postgres did. */ + Plan plan(SqlStatement statement) throws SQLException { + return Explain.analyze(connection, statement); + } + + List planText(SqlStatement statement) throws SQLException { + return Explain.text(connection, statement); + } + + /** The ids the feed must return for these positions: newest first, highest id first within one created_at. */ + List expectedIds(long offset, int limit) throws SQLException { + try (PreparedStatement select = connection.prepareStatement( + "select id from orders order by created_at desc, id desc limit ? offset ?")) { + select.setInt(1, limit); + select.setLong(2, offset); + List ids = new ArrayList<>(); + try (ResultSet row = select.executeQuery()) { + while (row.next()) { + ids.add(row.getLong(1)); + } + } + return ids; + } + } + + /** + * The path of a feed page that starts after this many orders. A real client can only get such a + * cursor by following nextCursor from the top. The tools take a shortcut: they look the row up + * in the database and build the cursor from it. + */ + String feedPathAfter(long ordersRead, int size) throws SQLException { + if (ordersRead == 0) { + return "/api/orders/feed?size=" + size; + } + try (PreparedStatement select = connection.prepareStatement( + "select created_at, id from orders order by created_at desc, id desc limit 1 offset ?")) { + select.setLong(1, ordersRead - 1); + try (ResultSet row = select.executeQuery()) { + row.next(); + Cursor cursor = new Cursor(row.getObject(1, OffsetDateTime.class).toInstant(), row.getLong(2)); + return feedPath(cursor.encode(), size); + } + } + } + + static String feedPath(String cursor, int size) { + return "/api/orders/feed?size=" + size + "&after=" + URLEncoder.encode(cursor, StandardCharsets.UTF_8); + } + + /** The values bound to a statement, readable: 99980, 20. */ + static String values(SqlStatement statement) { + return statement.parameters().stream() + .map(value -> value instanceof Timestamp timestamp ? "'" + timestamp.toInstant() + "'" : String.valueOf(value)) + .collect(Collectors.joining(", ")); + } + + static String number(long value) { + return String.format(Locale.US, "%,d", value); + } + + @Override + public void close() throws SQLException { + try { + context.close(); + } finally { + connection.close(); + } + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/demo/Db.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/demo/Db.java new file mode 100644 index 0000000..c410b7a --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/demo/Db.java @@ -0,0 +1,41 @@ +package com.amigoscode.pagination.demo; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +/** Connection settings shared by the demo and inspect tools. Same defaults as application.properties. */ +final class Db { + + static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5450/pagination"); + static final String USER = env("DB_USER", "pagination"); + static final String PASSWORD = env("DB_PASSWORD", "pagination"); + + private Db() { + } + + static Connection connect() throws SQLException { + return DriverManager.getConnection(URL, USER, PASSWORD); + } + + /** Returns false, after printing what to do, when Postgres is not reachable. */ + static boolean isUp() { + try (Connection ignored = connect()) { + return true; + } catch (SQLException e) { + System.out.println(); + System.out.println("Cannot reach Postgres at " + URL); + System.out.println("Start it first, from this folder:"); + System.out.println(); + System.out.println(" docker compose up -d"); + System.out.println(); + System.out.println("(" + e.getMessage().lines().findFirst().orElse("") + ")"); + return false; + } + } + + private static String env(String name, String fallback) { + String value = System.getenv(name); + return value == null || value.isBlank() ? fallback : value; + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/demo/Demo.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/demo/Demo.java new file mode 100644 index 0000000..8885455 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/demo/Demo.java @@ -0,0 +1,526 @@ +package com.amigoscode.pagination.demo; + +import static com.amigoscode.pagination.demo.App.number; + +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.db.SqlStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +/** + * Starts the real application, asks it for pages of orders over HTTP, and prints what each request + * cost inside Postgres: the SQL it sent, the rows that SQL read and the pages it touched. Ends with + * a RESULT line. Run it with ./demo (or .\demo on Windows). ./demo --help lists the flags. + */ +public final class Demo { + + private enum Mode { + OFFSET, KEYSET, HISTORY + } + + private record Options(Mode mode, int depth, int size, boolean insert, long customer, boolean reseed) { + } + + /** What Postgres did for the statement that fetched the rows of one page. */ + private record Cost(App.Response response, Plan plan) { + + long thrownAway() { + return Math.max(0, plan.rowsRead() - response.ids().size()); + } + } + + public static void main(String[] args) throws Exception { + Options options; + try { + options = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println(); + printHelp(); + return; + } + if (options == null) { + printHelp(); + return; + } + try (App app = App.start(options.reseed())) { + if (app == null) { + return; + } + if (options.size() > 100) { + unbounded(app, options); + } else if (options.mode() == Mode.HISTORY) { + history(app, options); + } else if (options.insert()) { + shift(app, options); + } else { + depth(app, options); + } + System.out.println(); + } + } + + // ---- Scenario 1: how much does a deep page cost? ---- + + private static void depth(App app, Options options) throws Exception { + int size = options.size(); + long pages = app.orders() / size; + int depth = (int) Math.min(options.depth(), pages); + long ordersBefore = (long) (depth - 1) * size; + boolean keyset = options.mode() == Mode.KEYSET; + + System.out.println("Mode: " + name(options.mode()) + " | page size: " + size + " | depth: page " + number(depth) + + " of " + number(pages)); + System.out.println("Table orders: " + number(app.orders()) + " rows, newest first."); + + System.out.println(); + System.out.println("--- Page 1 ---"); + Cost first = request(app, keyset ? "/api/orders/feed?size=" + size : "/api/orders?page=0&size=" + size); + if (first == null) { + return; + } + List problems = new ArrayList<>(); + + if (keyset) { + System.out.println(); + System.out.println("--- Page 2: the client sends back the nextCursor of page 1 ---"); + String cursor = first.response().nextCursor(); + if (cursor == null) { + System.out.println("Page 1 has no nextCursor, so the client believes the feed ends here."); + problems.add("Page 1 came back without a nextCursor although " + number(app.orders() - size) + " orders follow it."); + } else { + Cost second = request(app, App.feedPath(cursor, size)); + if (second == null) { + return; + } + Set missing = new LinkedHashSet<>(app.expectedIds(0, 2 * size)); + missing.removeAll(first.response().ids()); + missing.removeAll(second.response().ids()); + if (!missing.isEmpty()) { + problems.add("After two pages a client should have seen the " + (2 * size) + " newest orders. " + + number(missing.size()) + " of them were never returned, for example #" + + number(missing.iterator().next()) + "."); + } + } + } + + Cost deep = first; + if (depth > 1) { + System.out.println(); + System.out.println("--- Page " + number(depth) + " ---"); + if (keyset) { + System.out.println("A client gets here by following nextCursor " + number(depth - 1) + " times. To save you the wait, the"); + System.out.println("demo looked up the last order of page " + number(depth - 1) + " in the database and built the cursor from it."); + } + deep = request(app, keyset ? app.feedPathAfter(ordersBefore, size) : "/api/orders?page=" + (depth - 1) + "&size=" + size); + if (deep == null) { + return; + } + if (keyset) { + Set missing = new LinkedHashSet<>(app.expectedIds(ordersBefore, size)); + missing.removeAll(deep.response().ids()); + if (!missing.isEmpty()) { + problems.add("Page " + number(depth) + " comes after " + number(ordersBefore) + " orders, so it should hold the next " + + size + ". " + number(missing.size()) + " of them were not returned, for example #" + + number(missing.iterator().next()) + "."); + } + } + System.out.println(); + compare(first, deep, depth); + } + + System.out.println(); + if (!problems.isEmpty()) { + problems.forEach(problem -> System.out.println("RESULT: SKIPPED ROWS. " + problem)); + } else if (keyset && (deep.plan().has("Sort") || deep.plan().rowsRead() > size + 1)) { + System.out.println("RESULT: NO MATCHING INDEX. The pages are right, but page " + number(depth) + " read " + + number(deep.plan().rowsRead()) + " rows" + (deep.plan().has("Sort") ? " and sorted them" : "") + " to return " + + deep.response().ids().size() + "."); + System.out.println(" The feed is sorted by (created_at, id). No index on orders has exactly those columns."); + } else if (!keyset && deep.plan().rowsRead() > 10L * (size + 1)) { + System.out.println("RESULT: DEEP OFFSET. Page " + number(depth) + " read " + number(deep.plan().rowsRead()) + + " rows to return " + deep.response().ids().size() + ". Page 1 read " + number(first.plan().rowsRead()) + "."); + } else { + System.out.println("RESULT: OK. Page " + number(depth) + " read " + number(deep.plan().rowsRead()) + " rows to return " + + deep.response().ids().size() + (depth > 1 ? ". Page 1 read " + number(first.plan().rowsRead()) + "." : ".")); + } + hiddenCount(app, deep.response()); + } + + private static void compare(Cost first, Cost deep, int depth) { + String header = "page " + number(depth); + String format = "%-30s%-14s%s%n"; + System.out.printf(format, "", "page 1", header); + System.out.printf(format, "Rows returned to the client", first.response().ids().size(), deep.response().ids().size()); + System.out.printf(format, "Rows read", number(first.plan().rowsRead()), number(deep.plan().rowsRead())); + System.out.printf(format, "Rows read and thrown away", number(first.thrownAway()), number(deep.thrownAway())); + System.out.printf(format, "Pages read (8 kB each)", number(first.plan().pages()), number(deep.plan().pages())); + System.out.printf(format, "Time in the database", millis(first.plan()), millis(deep.plan()) + " (differs on every run)"); + } + + // ---- Scenario 2: an order is placed between two page requests ---- + + private static void shift(App app, Options options) throws Exception { + int size = options.size(); + boolean keyset = options.mode() == Mode.KEYSET; + System.out.println("Mode: " + name(options.mode()) + " | page size: " + size + + " | an order is placed between the two requests"); + + List expected = app.expectedIds(0, 2 * size); + long newOrder = app.orders() + 1; + try { + System.out.println(); + App.Response first = show(app, keyset ? "/api/orders/feed?size=" + size : "/api/orders?page=0&size=" + size); + if (first == null) { + return; + } + System.out.println(" last 3 orders: " + orders(tail(first.ids(), 3))); + + System.out.println(); + placeOrder(app, newOrder); + System.out.println("A customer places order #" + number(newOrder) + ". It is now the newest order: first in the list."); + System.out.println(); + + String next; + if (!keyset) { + next = "/api/orders?page=1&size=" + size; + } else if (first.nextCursor() != null) { + next = App.feedPath(first.nextCursor(), size); + } else { + System.out.println("RESULT: SKIPPED ROWS. Page 1 came back without a nextCursor, so the client stops reading."); + return; + } + App.Response second = show(app, next); + if (second == null) { + return; + } + System.out.println(" first 3 orders: " + orders(second.ids().subList(0, Math.min(3, second.ids().size())))); + + Set twice = new LinkedHashSet<>(first.ids()); + twice.retainAll(second.ids()); + Set missing = new LinkedHashSet<>(expected); + missing.removeAll(first.ids()); + missing.removeAll(second.ids()); + + System.out.println(); + if (!twice.isEmpty()) { + long example = twice.iterator().next(); + System.out.println("RESULT: SHIFTED. Order #" + number(example) + " was returned twice: at the end of page 1 and again" + + " at the start of page 2."); + System.out.println(" The new order moved every other order down by one, and OFFSET " + size + + " counts from the new top."); + } else if (!missing.isEmpty()) { + System.out.println("RESULT: SKIPPED ROWS. " + number(missing.size()) + " of the " + (2 * size) + + " newest orders were on neither page, for example #" + number(missing.iterator().next()) + "."); + } else { + System.out.println("RESULT: OK. Page 2 continues exactly where page 1 ended. No order was returned twice or skipped."); + } + hiddenCount(app, second); + } finally { + try (Statement statement = app.connection().createStatement()) { + statement.execute("delete from orders where id = " + newOrder); + } + } + } + + private static void placeOrder(App app, long id) throws SQLException { + try (PreparedStatement insert = app.connection().prepareStatement(""" + insert into orders (id, customer_id, status, total_cents, created_at) + select ?, 1001, 'PENDING', 1999, max(created_at) + interval '1 minute' from orders + """)) { + insert.setLong(1, id); + insert.executeUpdate(); + } + } + + // ---- Scenario 3: read all orders of one customer, page by page ---- + + private static void history(App app, Options options) throws Exception { + int size = options.size(); + long customer = options.customer(); + List expected = new ArrayList<>(); + try (PreparedStatement select = app.connection().prepareStatement("select id from orders where customer_id = ?")) { + select.setLong(1, customer); + try (ResultSet row = select.executeQuery()) { + while (row.next()) { + expected.add(row.getLong(1)); + } + } + } + System.out.println("Mode: history | customer: " + customer + " | page size: " + size); + System.out.println("Customer " + customer + " has " + number(expected.size()) + " orders. The demo reads all of them, page by page."); + System.out.println("Nothing is inserted, updated or deleted while it reads."); + System.out.println(); + + String path = "/api/customers/" + customer + "/orders?size=" + size + "&page="; + Cost firstPage = request(app, path + 0); + if (firstPage == null) { + return; + } + List received = new ArrayList<>(firstPage.response().ids()); + List> pages = new ArrayList<>(List.of(firstPage.response().ids())); + App.Response last = firstPage.response(); + while (last.hasNext() && !last.ids().isEmpty() && pages.size() < 10_000) { + last = app.get(path + pages.size()); + if (!last.ok()) { + System.out.println("GET " + last.path() + " returned " + last.status() + " " + last.error()); + System.out.println(); + System.out.println("RESULT: FAILED. The demo could not read page " + pages.size() + "."); + return; + } + pages.add(last.ids()); + received.addAll(last.ids()); + } + if (pages.size() > 1) { + System.out.println(); + System.out.println("... and " + (pages.size() - 1) + " more requests, for page=1 to page=" + (pages.size() - 1) + "."); + } + + Set different = new LinkedHashSet<>(received); + Set never = new LinkedHashSet<>(expected); + never.removeAll(different); + int twice = received.size() - different.size(); + + System.out.println(); + System.out.printf("%-30s%s%n", "Pages requested", pages.size()); + System.out.printf("%-30s%s%n", "Orders received", number(received.size())); + System.out.printf("%-30s%s%n", "Different orders received", number(different.size())); + System.out.printf("%-30s%s%n", "Orders received twice", number(twice)); + System.out.printf("%-30s%s%n", "Orders never received", number(never.size())); + if (twice > 0) { + System.out.println(); + System.out.println(repeatExample(app, pages)); + } + + System.out.println(); + if (twice > 0 || !never.isEmpty()) { + System.out.println("RESULT: UNSTABLE ORDER. Nothing changed in the database, but " + number(twice) + + " orders came back twice and " + number(never.size()) + " never came back."); + } else { + System.out.println("RESULT: OK. " + number(expected.size()) + " orders, each returned exactly once."); + } + hiddenCount(app, firstPage.response()); + } + + /** "Order #921,646 was on page 0 and again on page 1. 11 other orders of this customer have the same created_at." */ + private static String repeatExample(App app, List> pages) throws SQLException { + for (int later = 1; later < pages.size(); later++) { + for (long id : pages.get(later)) { + for (int earlier = 0; earlier < later; earlier++) { + if (pages.get(earlier).contains(id)) { + try (PreparedStatement select = app.connection().prepareStatement(""" + select count(*) - 1 from orders o + where (o.customer_id, o.created_at) = (select customer_id, created_at from orders where id = ?) + """)) { + select.setLong(1, id); + try (ResultSet row = select.executeQuery()) { + row.next(); + return "For example: order #" + number(id) + " was on page=" + earlier + " and again on page=" + later + + ".\n" + number(row.getLong(1)) + " other orders of this customer have exactly the same created_at."; + } + } + } + } + } + } + return ""; + } + + // ---- Scenario 4: a page size nobody should be allowed to ask for ---- + + private static void unbounded(App app, Options options) throws Exception { + int size = options.size(); + System.out.println("Mode: " + name(options.mode()) + " | page size: " + number(size)); + System.out.println(); + String path = switch (options.mode()) { + case OFFSET -> "/api/orders?page=0&size=" + size; + case KEYSET -> "/api/orders/feed?size=" + size; + case HISTORY -> "/api/customers/" + options.customer() + "/orders?page=0&size=" + size; + }; + App.Response response = app.get(path); + System.out.println("GET " + path); + if (response.ok()) { + System.out.println(" 200 OK, " + number(response.ids().size()) + " orders, " + + megabytes(response.bytes()) + " of JSON, " + number(response.millis()) + " ms"); + System.out.println(); + System.out.println("RESULT: UNBOUNDED. One request made the server load " + number(response.ids().size()) + + " orders and send " + megabytes(response.bytes()) + "."); + System.out.println(" Nothing stops a client from asking for size=1000000, or from leaving size out."); + } else { + System.out.println(" " + response.status() + " " + response.error()); + System.out.println(" SQL statements sent: " + response.statements().size()); + System.out.println(); + if (response.status() == 400) { + System.out.println("RESULT: OK. size=" + size + " was rejected with a 400 before anything was read from the database."); + } else { + System.out.println("RESULT: FAILED. size=" + size + " should be a 400 (the client's mistake), not a " + response.status() + "."); + } + } + } + + // ---- Shared printing ---- + + /** Sends the request, prints it with the cost of every SQL statement, and returns the cost of the page query. */ + private static Cost request(App app, String path) throws Exception { + App.Response response = show(app, path); + if (response == null) { + return null; + } + Plan pagePlan = null; + System.out.println(" SQL statements sent: " + response.statements().size()); + int position = 1; + for (SqlStatement statement : response.statements()) { + Plan plan = app.plan(statement); + if (pagePlan == null && !statement.isCount()) { + pagePlan = plan; + } + String values = App.values(statement); + System.out.println(" " + position++ + ". " + statement.shortSql() + (values.isEmpty() ? "" : " -- ? = " + values)); + System.out.println(" " + plan.describe()); + System.out.println(" rows read: " + number(plan.rowsRead()) + " | rows returned: " + number(plan.rowsReturned()) + + " | pages read: " + number(plan.pages())); + } + if (pagePlan == null) { + System.out.println(); + System.out.println("RESULT: FAILED. The request sent no SQL that fetches orders."); + return null; + } + return new Cost(response, pagePlan); + } + + /** Sends the request and prints its first lines. Returns null, after printing a RESULT line, if it is not a 200. */ + private static App.Response show(App app, String path) throws Exception { + App.Response response = app.get(path); + System.out.println("GET " + path); + if (!response.ok()) { + System.out.println(" " + response.status() + " " + response.error()); + System.out.println(); + System.out.println("RESULT: FAILED. The request returned " + response.status() + "."); + return null; + } + System.out.println(" 200 OK, " + response.ids().size() + " orders, " + response.millis() + " ms"); + return response; + } + + private static void hiddenCount(App app, App.Response response) throws SQLException { + if (response.countQueries().isEmpty()) { + return; + } + Plan count = app.plan(response.countQueries().getFirst()); + System.out.println("RESULT: HIDDEN COUNT. The request also sent a SELECT COUNT that nobody asked for. It read " + + number(count.rowsRead()) + " rows to return one number."); + } + + private static String orders(List ids) { + StringBuilder text = new StringBuilder(); + for (long id : ids) { + text.append('#').append(number(id)).append(" "); + } + return text.toString().stripTrailing(); + } + + private static List tail(List list, int count) { + return list.subList(Math.max(0, list.size() - count), list.size()); + } + + private static String millis(Plan plan) { + return String.format(Locale.US, "%.2f ms", plan.executionMillis()); + } + + private static String megabytes(int bytes) { + return String.format(Locale.US, "%.1f MB", bytes / 1_000_000.0); + } + + private static String name(Mode mode) { + return mode.name().toLowerCase(Locale.ROOT); + } + + // ---- Options ---- + + private static Options parse(String[] args) { + Mode mode = Mode.OFFSET; + int depth = 5_000; + int size = 20; + boolean insert = false; + long customer = 42; + boolean reseed = false; + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "--help", "-h" -> { + return null; + } + case "--mode" -> mode = mode(value(args, ++i, arg)); + case "--depth" -> depth = between(value(args, ++i, arg), arg, 1, 1_000_000); + case "--size" -> size = between(value(args, ++i, arg), arg, 1, 1_000_000); + case "--customer" -> customer = between(value(args, ++i, arg), arg, 1, 100_000); + case "--insert" -> insert = true; + case "--reseed" -> reseed = true; + default -> throw new IllegalArgumentException("Unknown option: " + arg); + } + } + if (insert && mode == Mode.HISTORY) { + throw new IllegalArgumentException("--insert works with --mode offset and --mode keyset"); + } + return new Options(mode, depth, size, insert, customer, reseed); + } + + private static Mode mode(String value) { + try { + return Mode.valueOf(value.toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("--mode must be offset, keyset or history, got: " + value); + } + } + + private static String value(String[] args, int index, String option) { + if (index >= args.length) { + throw new IllegalArgumentException(option + " needs a value"); + } + return args[index]; + } + + private static int between(String value, String option, int min, int max) { + try { + int number = Integer.parseInt(value); + if (number < min || number > max) { + throw new NumberFormatException(); + } + return number; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(option + " must be a number from " + min + " to " + max + ", got: " + value); + } + } + + private static void printHelp() { + System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])"); + System.out.println(); + System.out.println(" --mode offset | keyset | history (default: offset)"); + System.out.println(" offset GET /api/orders?page=&size= every order, LIMIT and OFFSET"); + System.out.println(" keyset GET /api/orders/feed?after=&size= every order, with a cursor"); + System.out.println(" history GET /api/customers/{id}/orders reads ALL orders of one customer"); + System.out.println(" --depth which page to compare with page 1 (default: 5000)"); + System.out.println(" --size orders per page (default: 20). Above 100 the demo only asks for that one page"); + System.out.println(" --insert place a new order between the request for page 1 and the request for page 2"); + System.out.println(" --customer the customer for --mode history (default: 42, who has 300 orders)"); + System.out.println(" --reseed empty the table and seed the 1,000,000 orders again"); + System.out.println(); + System.out.println("Examples:"); + System.out.println(" ./demo"); + System.out.println(" ./demo --size 100000"); + System.out.println(" ./demo --mode history"); + System.out.println(" ./demo --insert"); + System.out.println(" ./demo --mode keyset --depth 5000"); + System.out.println(" ./demo --mode keyset --insert"); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/demo/Inspect.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/demo/Inspect.java new file mode 100644 index 0000000..69e3029 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/demo/Inspect.java @@ -0,0 +1,228 @@ +package com.amigoscode.pagination.demo; + +import static com.amigoscode.pagination.demo.App.number; + +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.db.SqlStatement; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** + * Shows what Postgres does for one page request: the table and its indexes, the SQL the endpoint + * sends right now, and the full EXPLAIN (ANALYZE, BUFFERS) output of each statement. Run it with + * ./inspect (or .\inspect on Windows). ./inspect --help lists the flags. + */ +public final class Inspect { + + private static final String TABLE = """ + select c.relname as "table", + to_char(c.reltuples::bigint, 'FM999,999,999') as rows, + pg_size_pretty(pg_relation_size(c.oid)) as table_size, + pg_size_pretty(pg_indexes_size(c.oid)) as all_indexes_size + from pg_class c + where c.relname = 'orders' and c.relnamespace = 'public'::regnamespace + """; + + private static final String INDEXES = """ + select c.relname as index, + substring(pg_get_indexdef(i.indexrelid) from 'USING btree (.*)$') as columns, + pg_size_pretty(pg_relation_size(i.indexrelid)) as size, + coalesce(s.idx_scan, 0) as scans, + case when i.indisprimary then 'primary key' else '' end as kind + from pg_index i + join pg_class c on c.oid = i.indexrelid + join pg_class t on t.oid = i.indrelid + left join pg_stat_user_indexes s on s.indexrelid = i.indexrelid + where t.relname = 'orders' and t.relnamespace = 'public'::regnamespace + order by i.indisprimary desc, c.relname + """; + + private record Options(String mode, int depth, int size, long customer) { + } + + public static void main(String[] args) throws Exception { + Options options; + try { + options = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println(); + printHelp(); + return; + } + if (options == null) { + printHelp(); + return; + } + try (App app = App.start(false)) { + if (app == null) { + return; + } + System.out.println("TABLE (rows = the planner's estimate, refreshed by ANALYZE)"); + printTable(app.connection(), TABLE); + System.out.println(); + System.out.println("INDEXES ON orders (scans = how many times a query used the index since it was built)"); + printTable(app.connection(), INDEXES); + System.out.println(); + request(app, options); + System.out.println(); + } + } + + private static void request(App app, Options options) throws Exception { + int size = options.size(); + long ordersBefore = (long) (options.depth() - 1) * size; + String path = switch (options.mode()) { + case "keyset" -> app.feedPathAfter(Math.min(ordersBefore, app.orders() - 1), size); + case "history" -> "/api/customers/" + options.customer() + "/orders?page=" + (options.depth() - 1) + "&size=" + size; + default -> "/api/orders?page=" + (options.depth() - 1) + "&size=" + size; + }; + App.Response response = app.get(path); + + System.out.println("REQUEST (page " + number(options.depth()) + ", " + size + " orders per page)"); + System.out.println(" GET " + path); + if (!response.ok()) { + System.out.println(" " + response.status() + " " + response.error()); + System.out.println(" SQL statements sent: " + response.statements().size()); + return; + } + System.out.println(" 200 OK, " + response.ids().size() + " orders returned, hasNext = " + response.hasNext()); + System.out.println(" SQL statements sent: " + response.statements().size()); + + int position = 1; + for (SqlStatement statement : response.statements()) { + System.out.println(); + System.out.println("STATEMENT " + position++ + " of " + response.statements().size()); + statement.sql().strip().lines().forEach(line -> System.out.println(" " + line.strip())); + if (!statement.bindings().isEmpty()) { + System.out.println(" -- ? = " + App.values(statement)); + } + System.out.println(); + System.out.println(" EXPLAIN (ANALYZE, BUFFERS)"); + app.planText(statement).forEach(line -> System.out.println(" " + line)); + Plan plan = app.plan(statement); + System.out.println(); + System.out.println(" How the rows were found: " + plan.describe()); + System.out.println(" Rows read: " + number(plan.rowsRead())); + System.out.println(" Rows returned: " + number(plan.rowsReturned())); + System.out.println(" Pages read (8 kB each): " + number(plan.pages())); + System.out.println(" Sorted by Postgres: " + (plan.has("Sort") ? "yes, there is a Sort step" : "no")); + } + } + + /** Prints a query result as a plain text table. */ + private static void printTable(Connection connection, String sql) throws SQLException { + List rows = new ArrayList<>(); + try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) { + int columns = result.getMetaData().getColumnCount(); + String[] header = new String[columns]; + for (int c = 0; c < columns; c++) { + header[c] = result.getMetaData().getColumnLabel(c + 1); + } + rows.add(header); + while (result.next()) { + String[] row = new String[columns]; + for (int c = 0; c < columns; c++) { + String value = result.getString(c + 1); + row[c] = value == null ? "" : value; + } + rows.add(row); + } + } + int[] widths = new int[rows.get(0).length]; + for (String[] row : rows) { + for (int c = 0; c < row.length; c++) { + widths[c] = Math.max(widths[c], row[c].length()); + } + } + for (int r = 0; r < rows.size(); r++) { + StringBuilder line = new StringBuilder(" "); + for (int c = 0; c < widths.length; c++) { + line.append(String.format("%-" + widths[c] + "s", rows.get(r)[c])).append(" "); + } + System.out.println(line.toString().stripTrailing()); + if (r == 0) { + StringBuilder rule = new StringBuilder(" "); + for (int width : widths) { + rule.append("-".repeat(width)).append(" "); + } + System.out.println(rule.toString().stripTrailing()); + } + } + } + + private static Options parse(String[] args) { + String mode = "offset"; + int depth = 5_000; + int size = 20; + long customer = 42; + boolean depthGiven = false; + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "--help", "-h" -> { + return null; + } + case "--mode" -> { + mode = value(args, ++i, arg).toLowerCase(Locale.ROOT); + if (!List.of("offset", "keyset", "history").contains(mode)) { + throw new IllegalArgumentException("--mode must be offset, keyset or history, got: " + mode); + } + } + case "--depth" -> { + depth = between(value(args, ++i, arg), arg, 1, 1_000_000); + depthGiven = true; + } + case "--size" -> size = between(value(args, ++i, arg), arg, 1, 1_000_000); + case "--customer" -> customer = between(value(args, ++i, arg), arg, 1, 100_000); + default -> throw new IllegalArgumentException("Unknown option: " + arg); + } + } + if (mode.equals("history") && !depthGiven) { + depth = 1; + } + return new Options(mode, depth, size, customer); + } + + private static String value(String[] args, int index, String option) { + if (index >= args.length) { + throw new IllegalArgumentException(option + " needs a value"); + } + return args[index]; + } + + private static int between(String value, String option, int min, int max) { + try { + int number = Integer.parseInt(value); + if (number < min || number > max) { + throw new NumberFormatException(); + } + return number; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(option + " must be a number from " + min + " to " + max + ", got: " + value); + } + } + + private static void printHelp() { + System.out.println("Usage: ./inspect [options] (Windows: .\\inspect [options])"); + System.out.println(); + System.out.println(" --mode offset | keyset | history (default: offset)"); + System.out.println(" --depth which page to ask for (default: 5000; for history: 1)"); + System.out.println(" --size orders per page (default: 20)"); + System.out.println(" --customer the customer for --mode history (default: 42)"); + System.out.println(); + System.out.println("Examples:"); + System.out.println(" ./inspect"); + System.out.println(" ./inspect --depth 1"); + System.out.println(" ./inspect --mode keyset --depth 5000"); + System.out.println(" ./inspect --mode history"); + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/Cursor.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/Cursor.java new file mode 100644 index 0000000..ac4696b --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/Cursor.java @@ -0,0 +1,43 @@ +package com.amigoscode.pagination.order; + +import java.nio.charset.StandardCharsets; +import java.time.DateTimeException; +import java.time.Instant; +import java.util.Base64; + +/** + * Where a page of the feed ended: the sort key of its last row. The next page is "everything that + * sorts after this". + * + * On the wire it is opaque: Base64 of "createdAt|id". Clients send it back unchanged and never + * build one themselves, so the format can change without breaking them. Base64 is an encoding, not + * a secret: anyone can decode it, which is fine, because it holds nothing the client has not seen. + */ +public record Cursor(Instant createdAt, long id) { + + public static Cursor after(Order lastRow) { + return new Cursor(lastRow.getCreatedAt(), lastRow.getId()); + } + + public String encode() { + String text = createdAt + "|" + id; + return Base64.getUrlEncoder().withoutPadding().encodeToString(text.getBytes(StandardCharsets.UTF_8)); + } + + /** Reads a cursor a client sent. Anything that is not a cursor is the client's mistake: a 400. */ + public static Cursor decode(String encoded) { + try { + String text = new String(Base64.getUrlDecoder().decode(encoded), StandardCharsets.UTF_8); + int separator = text.indexOf('|'); + if (separator < 0) { + throw new InvalidCursorException(); + } + Instant createdAt = Instant.parse(text.substring(0, separator)); + long id = Long.parseLong(text.substring(separator + 1)); + return new Cursor(createdAt, id); + } catch (IllegalArgumentException | DateTimeException e) { + // Not Base64, not a timestamp or not a number. + throw new InvalidCursorException(); + } + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/FeedPage.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/FeedPage.java new file mode 100644 index 0000000..1e63ae1 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/FeedPage.java @@ -0,0 +1,11 @@ +package com.amigoscode.pagination.order; + +import java.util.List; + +/** + * One page of the keyset endpoint: GET /api/orders/feed?after=...&size=20. + * + * @param nextCursor send it back as "after" to get the next page. null on the last page + */ +public record FeedPage(List items, String nextCursor, boolean hasNext) { +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/InvalidCursorException.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/InvalidCursorException.java new file mode 100644 index 0000000..46042bd --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/InvalidCursorException.java @@ -0,0 +1,9 @@ +package com.amigoscode.pagination.order; + +/** The "after" parameter is not a cursor this API handed out. A 400. */ +public class InvalidCursorException extends RuntimeException { + + public InvalidCursorException() { + super("The cursor in 'after' is not valid. Leave 'after' out to start from the newest order."); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/InvalidPageRequestException.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/InvalidPageRequestException.java new file mode 100644 index 0000000..bec0c11 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/InvalidPageRequestException.java @@ -0,0 +1,9 @@ +package com.amigoscode.pagination.order; + +/** The client asked for a page number or a page size the API does not allow. A 400. */ +public class InvalidPageRequestException extends RuntimeException { + + public InvalidPageRequestException(String message) { + super(message); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OffsetPage.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OffsetPage.java new file mode 100644 index 0000000..8c42155 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OffsetPage.java @@ -0,0 +1,12 @@ +package com.amigoscode.pagination.order; + +import java.util.List; + +/** + * One page of the offset endpoints: GET /api/orders?page=3&size=20. + * + * @param page the page number the client asked for, starting at 0 + * @param hasNext true when there is a page after this one. The screens only have a "Next" button + */ +public record OffsetPage(List items, int page, int size, boolean hasNext) { +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/Order.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/Order.java new file mode 100644 index 0000000..f194557 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/Order.java @@ -0,0 +1,57 @@ +package com.amigoscode.pagination.order; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import java.time.Instant; + +@Entity +@Table(name = "orders") +public class Order { + + @Id + private Long id; + + @Column(name = "customer_id") + private long customerId; + + private String status; + + @Column(name = "total_cents") + private int totalCents; + + @Column(name = "created_at") + private Instant createdAt; + + protected Order() { + } + + public Order(long id, long customerId, String status, int totalCents, Instant createdAt) { + this.id = id; + this.customerId = customerId; + this.status = status; + this.totalCents = totalCents; + this.createdAt = createdAt; + } + + public Long getId() { + return id; + } + + public long getCustomerId() { + return customerId; + } + + public String getStatus() { + return status; + } + + public int getTotalCents() { + return totalCents; + } + + public Instant getCreatedAt() { + return createdAt; + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OrderController.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OrderController.java new file mode 100644 index 0000000..86cc684 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OrderController.java @@ -0,0 +1,40 @@ +package com.amigoscode.pagination.order; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class OrderController { + + private final OrderService service; + + public OrderController(OrderService service) { + this.service = service; + } + + /** Every order, newest first, with OFFSET: page 0 is the first page. */ + @GetMapping("/api/orders") + public OffsetPage page(@RequestParam(required = false) Integer page, + @RequestParam(required = false) Integer size) { + return service.page(Paging.page(page), Paging.size(size)); + } + + /** The orders of one customer, newest first, with OFFSET. */ + @GetMapping("/api/customers/{customerId}/orders") + public OffsetPage history(@PathVariable long customerId, + @RequestParam(required = false) Integer page, + @RequestParam(required = false) Integer size) { + return service.history(customerId, Paging.page(page), Paging.size(size)); + } + + /** Every order, newest first, with a cursor: send the nextCursor of one page as "after" to get the next. */ + @GetMapping("/api/orders/feed") + public FeedPage feed(@RequestParam(required = false) String after, + @RequestParam(required = false) Integer size) { + int pageSize = Paging.size(size); + Cursor cursor = after == null || after.isEmpty() ? null : Cursor.decode(after); + return service.feed(cursor, pageSize); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OrderRepository.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OrderRepository.java new file mode 100644 index 0000000..da47686 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OrderRepository.java @@ -0,0 +1,41 @@ +package com.amigoscode.pagination.order; + +import java.time.Instant; +import java.util.List; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface OrderRepository extends JpaRepository { + + // ---- Offset pagination: LIMIT ? OFFSET ?, written by Spring Data from the Pageable ---- + + /** A Slice knows its rows and whether there are more. It never counts the table. */ + Slice findAllBy(Pageable pageable); + + Slice findByCustomerId(long customerId, Pageable pageable); + + // ---- Keyset pagination: no OFFSET. The WHERE clause starts where the last page ended ---- + + @Query(value = """ + select * from orders + order by created_at desc, id desc + limit :limit + """, nativeQuery = true) + List feedFirstPage(@Param("limit") int limit); + + /** + * (created_at, id) < (?, ?) is a row-value comparison: it compares created_at first and uses id + * only to break a tie, exactly like the ORDER BY. Postgres answers it from the index on + * (created_at, id) by jumping straight to that position. + */ + @Query(value = """ + select * from orders + where (created_at, id) < (:createdAt, :id) + order by created_at desc, id desc + limit :limit + """, nativeQuery = true) + List feedAfter(@Param("createdAt") Instant createdAt, @Param("id") long id, @Param("limit") int limit); +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OrderResponse.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OrderResponse.java new file mode 100644 index 0000000..d40f332 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OrderResponse.java @@ -0,0 +1,12 @@ +package com.amigoscode.pagination.order; + +import java.time.Instant; + +/** One order, as the API returns it. */ +public record OrderResponse(long id, long customerId, String status, int totalCents, Instant createdAt) { + + static OrderResponse of(Order order) { + return new OrderResponse(order.getId(), order.getCustomerId(), order.getStatus(), order.getTotalCents(), + order.getCreatedAt()); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OrderService.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OrderService.java new file mode 100644 index 0000000..d998ec3 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/OrderService.java @@ -0,0 +1,51 @@ +package com.amigoscode.pagination.order; + +import java.util.List; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Slice; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; + +@Service +public class OrderService { + + /** + * Newest first. Many orders share one created_at, so created_at alone does not say which of them + * comes first. The id breaks the tie: it is unique, so the order is always the same. + */ + static final Sort NEWEST_FIRST = Sort.by(Sort.Order.desc("createdAt"), Sort.Order.desc("id")); + + private final OrderRepository orders; + + public OrderService(OrderRepository orders) { + this.orders = orders; + } + + /** GET /api/orders?page=&size= : every order, with OFFSET. */ + public OffsetPage page(int page, int size) { + Slice result = orders.findAllBy(PageRequest.of(page, size, NEWEST_FIRST)); + return new OffsetPage(responses(result.getContent()), page, size, result.hasNext()); + } + + /** GET /api/customers/{id}/orders?page=&size= : the orders of one customer, with OFFSET. */ + public OffsetPage history(long customerId, int page, int size) { + Slice result = orders.findByCustomerId(customerId, PageRequest.of(page, size, NEWEST_FIRST)); + return new OffsetPage(responses(result.getContent()), page, size, result.hasNext()); + } + + /** GET /api/orders/feed?after=&size= : every order, with a cursor. after is null for the first page. */ + public FeedPage feed(Cursor after, int size) { + // One row more than the page: if it comes back, there is a next page. No COUNT needed. + List rows = after == null + ? orders.feedFirstPage(size + 1) + : orders.feedAfter(after.createdAt(), after.id(), size + 1); + boolean hasNext = rows.size() > size; + List items = hasNext ? rows.subList(0, size) : rows; + String nextCursor = hasNext ? Cursor.after(items.getLast()).encode() : null; + return new FeedPage(responses(items), nextCursor, hasNext); + } + + private static List responses(List orders) { + return orders.stream().map(OrderResponse::of).toList(); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/Paging.java b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/Paging.java new file mode 100644 index 0000000..e981f6d --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/java/com/amigoscode/pagination/order/Paging.java @@ -0,0 +1,33 @@ +package com.amigoscode.pagination.order; + +/** The rules for the "page" and "size" request parameters, shared by every endpoint. */ +public final class Paging { + + public static final int DEFAULT_SIZE = 20; + public static final int MAX_SIZE = 100; + + /** The page size to use: the default when the client sent none, a 400 when it is out of range. */ + public static int size(Integer requested) { + if (requested == null) { + return DEFAULT_SIZE; + } + if (requested < 1 || requested > MAX_SIZE) { + throw new InvalidPageRequestException("size must be between 1 and " + MAX_SIZE + ", got " + requested); + } + return requested; + } + + /** The page number to use, starting at 0: the first page when the client sent none. */ + public static int page(Integer requested) { + if (requested == null) { + return 0; + } + if (requested < 0) { + throw new InvalidPageRequestException("page must be 0 or more, got " + requested); + } + return requested; + } + + private Paging() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/resources/application.properties b/java/concepts/junior-mid/11-pagination/solution/src/main/resources/application.properties new file mode 100644 index 0000000..a03cbf9 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/resources/application.properties @@ -0,0 +1,17 @@ +spring.application.name=pagination + +# Postgres from compose.yaml. Port 5450 so it does not clash with a Postgres you already run. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5450/pagination} +spring.datasource.username=${DB_USER:pagination} +spring.datasource.password=${DB_PASSWORD:pagination} + +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false + +# The table, the rows and the indexes are set up at startup by DatabaseSetup (see db/). +# It runs schema.sql, seeds this many orders with generate_series, then applies indexes.sql. +spring.sql.init.mode=never +shop.seed.orders=1000000 + +# Uncomment to see every SQL statement. (./demo and ./inspect already print the SQL of each request.) +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/resources/indexes.sql b/java/concepts/junior-mid/11-pagination/solution/src/main/resources/indexes.sql new file mode 100644 index 0000000..893143f --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/resources/indexes.sql @@ -0,0 +1,15 @@ +-- The indexes of the orders table. +-- +-- This file is the single source of truth. Every time the application, ./demo, ./inspect or +-- ./check starts, the database is made to match it: if the file changed, every index on orders +-- (except the primary key) is dropped and this file is run again. +-- So to add an index, add a statement here. To remove one, delete its statement. +-- +-- One statement per index, each ending with a semicolon. Plain CREATE INDEX, nothing else. + +-- Was here before you joined. +CREATE INDEX idx_orders_customer ON orders (customer_id); + +-- Task 5: the feed is sorted by (created_at, id), so the index is too. It replaces the old index +-- on (created_at) alone: everything that one could do, this one can do as well. +CREATE INDEX idx_orders_created_at_id ON orders (created_at, id); diff --git a/java/concepts/junior-mid/11-pagination/solution/src/main/resources/schema.sql b/java/concepts/junior-mid/11-pagination/solution/src/main/resources/schema.sql new file mode 100644 index 0000000..ad20d6e --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/main/resources/schema.sql @@ -0,0 +1,15 @@ +-- The table. You do not change this file. Indexes go in indexes.sql. + +create table if not exists orders ( + id bigint primary key, + customer_id bigint not null, + status text not null, + total_cents int not null, + created_at timestamptz not null +); + +-- Bookkeeping for DatabaseSetup: how many rows were seeded, and which indexes.sql was applied. +create table if not exists setup_state ( + key text primary key, + value text not null +); diff --git a/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/Check.java b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/Check.java new file mode 100644 index 0000000..b3b7a80 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/Check.java @@ -0,0 +1,116 @@ +package com.amigoscode.pagination; + +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage; + +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.platform.engine.TestExecutionResult; +import org.junit.platform.engine.discovery.ClassNameFilter; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +import org.junit.platform.launcher.TagFilter; +import org.junit.platform.launcher.TestExecutionListener; +import org.junit.platform.launcher.TestIdentifier; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; + +/** + * Runs the tests that belong to one task and prints one line per acceptance criterion. + * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2 + * (./mvnw verify runs the same tests the usual Maven way.) + */ +public final class Check { + + /** Tasks that have tests. Tasks 7 and 9 are inspection tasks: you answer questions, no code. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: the tools and the HTTP contract (passes from the start, must stay green)"); + TASKS.put("1", "Task 1: See the deep OFFSET"); + TASKS.put("2", "Task 2: Fix the unbounded page size"); + TASKS.put("3", "Task 3: Fix the unstable order"); + TASKS.put("4", "Task 4: Inspect what OFFSET cannot fix"); + TASKS.put("5", "Task 5: Fix it with keyset pagination"); + TASKS.put("6", "Task 6: Fix the cursor: opaque and validated"); + TASKS.put("8", "Task 8: Fix the hidden COUNT(*)"); + } + + public static void main(String[] args) { + if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-9]"))) { + System.out.println("Usage: ./check [task] task is a number from 1 to 9. No number checks everything."); + System.exit(2); + } + if (args.length == 1 && !TASKS.containsKey(args[0])) { + System.out.println(); + System.out.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:"); + System.out.println("follow its steps in INTERVIEW_TASKS.md and answer the questions."); + System.out.println(); + return; + } + + boolean allGreen = true; + Launcher launcher = LauncherFactory.create(); + for (Map.Entry task : TASKS.entrySet()) { + if (args.length == 1 && !task.getKey().equals(args[0])) { + continue; + } + String tag = task.getKey().equals("baseline") ? "baseline" : "task" + task.getKey(); + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() + .selectors(selectPackage(Check.class.getPackageName())) + .filters(ClassNameFilter.includeClassNamePatterns(".*"), TagFilter.includeTags(tag)) + .build(); + System.out.println(); + System.out.println(task.getValue()); + Results results = new Results(); + launcher.execute(request, results); + System.out.println(" " + results.passed + " of " + results.total + " pass"); + allGreen &= results.passed == results.total && results.total > 0; + } + System.out.println(); + System.exit(allGreen ? 0 : 1); + } + + private static final class Results implements TestExecutionListener { + + private int total; + private int passed; + + @Override + public void executionFinished(TestIdentifier test, TestExecutionResult result) { + boolean ok = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL; + if (!test.isTest()) { + // A container that fails (for example the Spring context cannot start) takes its tests with it. + if (!ok) { + total++; + System.out.println(" [FAIL] " + test.getDisplayName() + " could not start"); + result.getThrowable().ifPresent(Results::printReason); + } + return; + } + total++; + if (ok) { + passed++; + System.out.println(" [PASS] " + test.getDisplayName()); + } else { + System.out.println(" [FAIL] " + test.getDisplayName()); + result.getThrowable().ifPresent(Results::printReason); + } + } + + private static void printReason(Throwable throwable) { + Throwable root = throwable; + while (root.getCause() != null && root.getCause() != root && root.getMessage() == null) { + root = root.getCause(); + } + String message = root.getMessage() == null ? root.getClass().getSimpleName() : root.getMessage(); + message.strip().lines() + .map(String::strip) + .filter(line -> !line.isEmpty()) + .limit(6) + .forEach(line -> System.out.println(" " + line)); + } + } + + private Check() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/CountQueryIT.java b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/CountQueryIT.java new file mode 100644 index 0000000..7a2842e --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/CountQueryIT.java @@ -0,0 +1,58 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.pagination.order.OffsetPage; +import com.amigoscode.pagination.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 8: a Spring Data Page counts every matching row on every request. Nobody asked for the total. */ +@Tag("task8") +class CountQueryIT extends IntegrationTest { + + /** A business customer: 12 orders in the test database. */ + private static final long CUSTOMER = 1; + + @Test + @DisplayName("Count: one page of GET /api/orders is exactly one SQL statement") + void onePageIsOneStatement() { + Recorded request = record(() -> orderService.page(3, 20)); + + assertThat(request.statements()) + .as("SQL statements sent for GET /api/orders?page=3&size=20") + .hasSize(1); + } + + @Test + @DisplayName("Count: no endpoint sends SELECT COUNT: not the order list, not a customer's history, not the feed") + void nothingCountsTheTable() { + assertThat(record(() -> orderService.page(3, 20)).countQueries()) + .as("COUNT statements sent for GET /api/orders").isEmpty(); + assertThat(record(() -> orderService.history(CUSTOMER, 0, 5)).countQueries()) + .as("COUNT statements sent for GET /api/customers/1/orders").isEmpty(); + assertThat(record(() -> orderService.feed(null, 20)).countQueries()) + .as("COUNT statements sent for GET /api/orders/feed").isEmpty(); + } + + @Test + @DisplayName("Count: the page query asks for one row more than the page size, which is how it knows there is a next page") + void thePageQueryFetchesOneRowMore() { + Recorded request = record(() -> orderService.page(3, 20)); + + assertThat(request.result().items()).as("orders returned to the client").hasSize(20); + assertThat(request.pageQueries().getFirst().parameters()) + .as("values bound to the page query (the offset and the number of rows to fetch)") + .containsExactly(60, 21); + } + + @Test + @DisplayName("Count: hasNext is still right without the total: true in the middle, false on the last page") + void hasNextIsStillRight() { + assertThat(orderService.page(0, 20).hasNext()).as("hasNext of page 0").isTrue(); + assertThat(orderService.page(ORDERS / 20 - 1, 20).hasNext()).as("hasNext of the last page").isFalse(); + assertThat(orderService.history(CUSTOMER, 1, 5).hasNext()).as("hasNext of page 1 of 3 of a customer").isTrue(); + assertThat(orderService.history(CUSTOMER, 2, 5).hasNext()).as("hasNext of page 2 of 3 of a customer").isFalse(); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/CursorTest.java b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/CursorTest.java new file mode 100644 index 0000000..80276da --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/CursorTest.java @@ -0,0 +1,92 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.amigoscode.pagination.order.Cursor; +import com.amigoscode.pagination.order.InvalidCursorException; +import com.amigoscode.pagination.support.StubOrderService; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 6: the cursor is opaque to the client, and a cursor the API cannot read is a 400. Unit tests. */ +@Tag("task6") +class CursorTest { + + private static final Cursor CURSOR = new Cursor(Instant.parse("2025-11-25T10:00:00.123456Z"), 987_654); + + private final StubOrderService service = new StubOrderService(); + + @Test + @DisplayName("Cursor: decode(encode(cursor)) gives the same cursor back, to the microsecond") + void roundTrip() { + assertThat(Cursor.decode(CURSOR.encode())).isEqualTo(CURSOR); + } + + @Test + @DisplayName("Cursor: the encoded form is URL-safe Base64, with no timestamp or id readable in it") + void theEncodedFormIsOpaque() { + String encoded = CURSOR.encode(); + + assertThat(encoded).as("encoded cursor").matches("[A-Za-z0-9_-]+"); + assertThat(encoded).as("encoded cursor").doesNotContain("2025-11-25").doesNotContain("987654"); + assertThat(new String(Base64.getUrlDecoder().decode(encoded), StandardCharsets.UTF_8)) + .as("what the Base64 text decodes to") + .contains("2025-11-25T10:00:00.123456Z") + .contains("987654"); + } + + @Test + @DisplayName("Cursor: text that is not a cursor is an InvalidCursorException, never another exception") + void garbageIsRejected() { + List notCursors = List.of( + "not-a-cursor", + "!!!", + "2025-11-25T10:00:00Z|987654", + base64("hello"), + base64("2025-11-25T10:00:00Z"), + base64("2025-11-25T10:00:00Z|"), + base64("2025-11-25T10:00:00Z|abc"), + base64("yesterday|987654"), + base64("|")); + + for (String text : notCursors) { + assertThatThrownBy(() -> Cursor.decode(text)) + .as("Cursor.decode(\"%s\")", text) + .isInstanceOf(InvalidCursorException.class); + } + } + + @Test + @DisplayName("HTTP: a malformed cursor returns 400 INVALID_CURSOR, not a 500") + void aMalformedCursorIsABadRequest() throws Exception { + for (String after : new String[] {"not-a-cursor", "%7C", base64("yesterday|987654")}) { + service.api().perform(get("/api/orders/feed?after=" + after)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("INVALID_CURSOR")); + } + + assertThat(service.calls).as("calls that reached the service").isZero(); + } + + @Test + @DisplayName("HTTP: a cursor the API handed out is accepted and reaches the service") + void aValidCursorReachesTheService() throws Exception { + service.api().perform(get("/api/orders/feed").param("after", CURSOR.encode())) + .andExpect(status().isOk()); + + assertThat(service.after).as("cursor passed to the service").isEqualTo(CURSOR); + } + + private static String base64(String text) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(text.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/DeepOffsetIT.java b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/DeepOffsetIT.java new file mode 100644 index 0000000..8c9cb73 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/DeepOffsetIT.java @@ -0,0 +1,41 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.order.OffsetPage; +import com.amigoscode.pagination.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 1: what OFFSET costs. These tests pass from the start and keep passing: OFFSET cannot be + * made cheap, only replaced. They pin the problem down so you can see what keyset pagination changes. + */ +@Tag("task1") +class DeepOffsetIT extends IntegrationTest { + + @Test + @DisplayName("Offset: the first page reads fewer than 100 rows to return 20") + void theFirstPageIsCheap() { + Recorded request = record(() -> orderService.page(0, 20)); + Plan plan = plan(request.pageQueries().getFirst()); + + assertThat(request.result().items()).as("orders on page 0").hasSize(20); + assertThat(plan.rowsRead()).as("rows read for page 0, with the plan: %s", plan).isLessThan(100); + } + + @Test + @DisplayName("Offset: page 500 reads more than 10,000 rows to return 20: every row of the 500 pages before it (this documents the problem)") + void aDeepPageReadsEveryRowBeforeIt() { + Recorded request = record(() -> orderService.page(500, 20)); + Plan plan = plan(request.pageQueries().getFirst()); + + assertThat(request.result().items()).as("orders on page 500").hasSize(20); + assertThat(request.pageQueries().getFirst().normalized()).as("the SQL of the page query").contains("offset"); + assertThat(plan.rowsRead()) + .as("rows read for page 500 (OFFSET 10000), with the plan: %s", plan) + .isGreaterThanOrEqualTo(10_020); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/KeysetIT.java b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/KeysetIT.java new file mode 100644 index 0000000..35455b7 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/KeysetIT.java @@ -0,0 +1,98 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.order.Cursor; +import com.amigoscode.pagination.order.FeedPage; +import com.amigoscode.pagination.support.IntegrationTest; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 5: keyset pagination. The page starts where the last one ended, instead of counting rows from the top. */ +@Tag("task5") +class KeysetIT extends IntegrationTest { + + @Test + @DisplayName("Keyset: indexes.sql creates an index on orders (created_at, id), the same columns as the ORDER BY") + void theIndexMatchesTheSortOrder() { + assertThat(indexedColumns()) + .as("indexes on orders. Add CREATE INDEX ... ON orders (created_at, id) to indexes.sql") + .anyMatch(columns -> columns.startsWith("(created_at, id")); + } + + @Test + @DisplayName("Keyset: the feed query finds its starting point in the index with a row comparison, and sorts nothing") + void theQueryIsARowComparisonOnTheIndex() { + Cursor deep = cursorAfter(10_000); + Recorded request = record(() -> orderService.feed(deep, 20)); + assertThat(request.statements()).as("SQL statements for one page of the feed").hasSize(1); + Plan plan = plan(request.statements().getFirst()); + + assertThat(plan.has("Sort")).as("plan has a Sort step: %s", plan.nodes()).isFalse(); + assertThat(plan.scans()).as("steps of the plan that read the table").hasSize(1); + assertThat(plan.scans().getFirst().condition()) + .as("Index Cond of the plan: the condition Postgres answers from the index. Plan: %s", plan) + .isNotNull() + .contains("ROW(created_at, id) < ROW("); + } + + @Test + @DisplayName("Keyset: a page 10,000 orders deep reads 21 rows, exactly as many as the first page") + void aDeepPageCostsTheSameAsTheFirst() { + Plan first = plan(record(() -> orderService.feed(null, 20)).statements().getFirst()); + Cursor cursor = cursorAfter(10_000); + Plan deep = plan(record(() -> orderService.feed(cursor, 20)).statements().getFirst()); + + assertThat(first.rowsRead()).as("rows read for the first page (20 orders + 1 to know if there are more)").isEqualTo(21); + assertThat(deep.rowsRead()).as("rows read for the page after 10,000 orders, with the plan: %s", deep).isEqualTo(21); + } + + @Test + @DisplayName("Keyset: following nextCursor from the first page to the last returns all 20,000 orders exactly once, newest first") + void followingTheCursorReturnsEveryOrderOnce() { + List received = new ArrayList<>(); + FeedPage page = orderService.feed(null, 100); + received.addAll(ids(page.items())); + for (int request = 0; page.nextCursor() != null && request < 1_000; request++) { + page = orderService.feed(Cursor.decode(page.nextCursor()), 100); + received.addAll(ids(page.items())); + } + + assertThat(received).as("number of orders received").hasSize(ORDERS); + assertThat(received).as("ids received, in order").isEqualTo(expectedIds(0, ORDERS)); + } + + @Test + @DisplayName("Keyset: hasNext is true while orders remain; the last page has hasNext = false and no nextCursor, even when it is exactly full") + void theLastPageKnowsItIsTheLast() { + FeedPage first = orderService.feed(null, 20); + assertThat(first.items()).as("orders on the first page").hasSize(20); + assertThat(first.hasNext()).as("hasNext of the first page").isTrue(); + assertThat(first.nextCursor()).as("nextCursor of the first page").isNotNull(); + + // The 20 oldest orders: a full page, with nothing after it. + FeedPage last = orderService.feed(cursorAfter(ORDERS - 20), 20); + assertThat(ids(last.items())).as("the last page").isEqualTo(expectedIds(ORDERS - 20, 20)); + assertThat(last.hasNext()).as("hasNext of the last page").isFalse(); + assertThat(last.nextCursor()).as("nextCursor of the last page").isNull(); + } + + @Test + @DisplayName("Keyset: an order placed between two requests changes nothing: the second page continues exactly where the first ended") + void anInsertDoesNotShiftThePages() { + thenRollBack(() -> { + List expected = expectedIds(0, 40); + FeedPage first = orderService.feed(null, 20); + + insertNewestOrder(); + FeedPage second = orderService.feed(Cursor.decode(first.nextCursor()), 20); + + assertThat(ids(first.items())).as("first page").isEqualTo(expected.subList(0, 20)); + assertThat(ids(second.items())).as("second page, read after the insert").isEqualTo(expected.subList(20, 40)); + }); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/OffsetShiftIT.java b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/OffsetShiftIT.java new file mode 100644 index 0000000..fdb71f7 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/OffsetShiftIT.java @@ -0,0 +1,48 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.pagination.support.IntegrationTest; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 4: OFFSET counts rows from the top of the list at the moment of each request. When the list + * changes between two requests, the pages shift. These tests pass from the start and keep passing: + * a tie-breaker does not fix this, only keyset pagination does (Task 5). + */ +@Tag("task4") +class OffsetShiftIT extends IntegrationTest { + + @Test + @DisplayName("Offset: an order placed between two requests pushes the last order of page 0 onto page 1, so the client sees it twice (this documents the problem)") + void anInsertRepeatsARow() { + thenRollBack(() -> { + List pageZero = ids(orderService.page(0, 20).items()); + + insertNewestOrder(); + List pageOne = ids(orderService.page(1, 20).items()); + + assertThat(pageOne.getFirst()) + .as("first order of page 1, read after the insert") + .isEqualTo(pageZero.getLast()); + }); + } + + @Test + @DisplayName("Offset: an order deleted between two requests pulls the first order of page 1 back onto page 0, so the client never sees it (this documents the problem)") + void aDeleteSkipsARow() { + thenRollBack(() -> { + List pageZero = ids(orderService.page(0, 20).items()); + long nextInLine = ids(orderService.page(1, 20).items()).getFirst(); + + jdbc.update("delete from orders where id = ?", pageZero.getFirst()); + List pageOne = ids(orderService.page(1, 20).items()); + + assertThat(pageZero).as("page 0, read before the delete").doesNotContain(nextInLine); + assertThat(pageOne).as("page 1, read after the delete").doesNotContain(nextInLine); + }); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/OrderControllerTest.java b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/OrderControllerTest.java new file mode 100644 index 0000000..3887cc2 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/OrderControllerTest.java @@ -0,0 +1,71 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.amigoscode.pagination.support.StubOrderService; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for the HTTP contract: no Spring context, no database, OrderService is a stub. They + * pass from the start and must keep passing, whatever you change behind the controller. + */ +@Tag("baseline") +class OrderControllerTest { + + private final StubOrderService service = new StubOrderService(); + + @Test + @DisplayName("HTTP: GET /api/orders?page=3&size=10 returns items, page, size and hasNext") + void aPageOfOrders() throws Exception { + service.api().perform(get("/api/orders?page=3&size=10")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.items[0].id").value(42)) + .andExpect(jsonPath("$.items[0].customerId").value(7)) + .andExpect(jsonPath("$.items[0].status").value("PENDING")) + .andExpect(jsonPath("$.page").value(3)) + .andExpect(jsonPath("$.size").value(10)) + .andExpect(jsonPath("$.hasNext").value(true)); + + assertThat(service.page).as("page passed to the service").isEqualTo(3); + assertThat(service.size).as("size passed to the service").isEqualTo(10); + } + + @Test + @DisplayName("HTTP: GET /api/customers/7/orders returns that customer's orders") + void aCustomersHistory() throws Exception { + service.api().perform(get("/api/customers/7/orders?page=1&size=10")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.items[0].id").value(42)) + .andExpect(jsonPath("$.hasNext").value(false)); + + assertThat(service.customerId).as("customer id passed to the service").isEqualTo(7); + assertThat(service.page).as("page passed to the service").isEqualTo(1); + } + + @Test + @DisplayName("HTTP: GET /api/orders/feed returns items, nextCursor and hasNext") + void aPageOfTheFeed() throws Exception { + service.api().perform(get("/api/orders/feed?size=10")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.items[0].id").value(42)) + .andExpect(jsonPath("$.nextCursor").value("next-cursor")) + .andExpect(jsonPath("$.hasNext").value(true)); + + assertThat(service.after).as("cursor passed to the service when the client sent none").isNull(); + } + + @Test + @DisplayName("HTTP: a size that is not a number returns 400") + void sizeMustBeANumber() throws Exception { + service.api().perform(get("/api/orders?size=lots")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("BAD_REQUEST")); + + assertThat(service.calls).as("calls that reached the service").isZero(); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/PageSizeTest.java b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/PageSizeTest.java new file mode 100644 index 0000000..d9c8ebd --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/PageSizeTest.java @@ -0,0 +1,89 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.amigoscode.pagination.support.StubOrderService; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 2: the client does not decide how many rows one request may load. Unit tests: the real + * controller and error handler, a stub service that writes down the size it was asked for. + */ +@Tag("task2") +class PageSizeTest { + + private final StubOrderService service = new StubOrderService(); + + @Test + @DisplayName("Page size: a request without size gets 20 orders, not every order") + void noSizeMeansTwenty() throws Exception { + service.api().perform(get("/api/orders")).andExpect(status().isOk()); + + assertThat(service.size).as("size passed to the service for GET /api/orders").isEqualTo(20); + assertThat(service.page).as("page passed to the service for GET /api/orders").isZero(); + } + + @Test + @DisplayName("Page size: size=100 is the largest size that is accepted") + void oneHundredIsAllowed() throws Exception { + service.api().perform(get("/api/orders?size=100")).andExpect(status().isOk()); + + assertThat(service.size).as("size passed to the service").isEqualTo(100); + } + + @Test + @DisplayName("Page size: size=101 and size=1000000 return 400 INVALID_PAGE_REQUEST, and nothing is loaded") + void tooLargeIsRejected() throws Exception { + for (String size : new String[] {"101", "1000000"}) { + service.api().perform(get("/api/orders?size=" + size)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("INVALID_PAGE_REQUEST")); + } + + assertThat(service.calls).as("calls that reached the service").isZero(); + } + + @Test + @DisplayName("Page size: size=0 and size=-5 return 400 INVALID_PAGE_REQUEST") + void zeroAndNegativeAreRejected() throws Exception { + for (String size : new String[] {"0", "-5"}) { + service.api().perform(get("/api/orders?size=" + size)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("INVALID_PAGE_REQUEST")); + } + + assertThat(service.calls).as("calls that reached the service").isZero(); + } + + @Test + @DisplayName("Page size: page=-1 returns 400 INVALID_PAGE_REQUEST") + void negativePageIsRejected() throws Exception { + service.api().perform(get("/api/orders?page=-1")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("INVALID_PAGE_REQUEST")); + + assertThat(service.calls).as("calls that reached the service").isZero(); + } + + @Test + @DisplayName("Page size: the feed and a customer's history follow the same rules: 20 by default, 400 above 100") + void theOtherEndpointsFollowTheSameRules() throws Exception { + service.api().perform(get("/api/orders/feed")).andExpect(status().isOk()); + assertThat(service.size).as("size passed to the service for GET /api/orders/feed").isEqualTo(20); + + service.api().perform(get("/api/customers/7/orders")).andExpect(status().isOk()); + assertThat(service.size).as("size passed to the service for GET /api/customers/7/orders").isEqualTo(20); + + service.api().perform(get("/api/orders/feed?size=101")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("INVALID_PAGE_REQUEST")); + service.api().perform(get("/api/customers/7/orders?size=101")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("INVALID_PAGE_REQUEST")); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/PlanTest.java b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/PlanTest.java new file mode 100644 index 0000000..e924497 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/PlanTest.java @@ -0,0 +1,70 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.db.SqlStatement; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Unit tests for the tools used by ./demo, ./inspect and the other tests: no Spring, no database. */ +@Tag("baseline") +class PlanTest { + + private static final String DEEP_OFFSET = """ + [{"Plan": {"Node Type": "Limit", "Actual Rows": 20, "Actual Loops": 1, + "Shared Hit Blocks": 1000, "Shared Read Blocks": 11, + "Plans": [{"Node Type": "Index Scan", "Scan Direction": "Backward", "Relation Name": "orders", + "Index Name": "idx_orders_created_at", "Actual Rows": 100000, "Actual Loops": 1, + "Shared Hit Blocks": 1000, "Shared Read Blocks": 11}]}, + "Execution Time": 11.3}] + """; + + private static final String COUNT = """ + [{"Plan": {"Node Type": "Aggregate", "Actual Rows": 1, "Actual Loops": 1, + "Shared Hit Blocks": 8334, "Shared Read Blocks": 0, + "Plans": [{"Node Type": "Seq Scan", "Relation Name": "orders", + "Actual Rows": 1000000, "Actual Loops": 1, + "Shared Hit Blocks": 8334, "Shared Read Blocks": 0}]}, + "Execution Time": 98.5}] + """; + + @Test + @DisplayName("Plan reader: a deep OFFSET is reported with the rows it read, the rows it returned and the pages it touched") + void readsADeepOffset() { + Plan plan = Plan.parse(DEEP_OFFSET); + + assertThat(plan.rowsReturned()).isEqualTo(20); + assertThat(plan.rowsRead()).isEqualTo(100_000); + assertThat(plan.pages()).isEqualTo(1_011); + assertThat(plan.has("Sort")).isFalse(); + assertThat(plan.indexes()).containsExactly("idx_orders_created_at"); + assertThat(plan.describe()).isEqualTo("Index Scan Backward using idx_orders_created_at on orders"); + } + + @Test + @DisplayName("Plan reader: a COUNT is reported with every row it had to read") + void readsACount() { + Plan plan = Plan.parse(COUNT); + + assertThat(plan.has("Seq Scan")).isTrue(); + assertThat(plan.rowsReturned()).isEqualTo(1); + assertThat(plan.rowsRead()).isEqualTo(1_000_000); + } + + @Test + @DisplayName("SQL recorder: SELECT COUNT is told apart from the query that fetches the rows") + void tellsACountFromAPageQuery() { + SqlStatement count = new SqlStatement("select count(o1_0.id) from orders o1_0", List.of()); + SqlStatement page = new SqlStatement( + "select o1_0.id,o1_0.created_at,o1_0.customer_id,o1_0.status,o1_0.total_cents from orders o1_0 " + + "order by o1_0.created_at desc offset ? rows fetch first ? rows only", List.of()); + + assertThat(count.isCount()).isTrue(); + assertThat(page.isCount()).isFalse(); + assertThat(page.shortSql()) + .isEqualTo("select ... from orders o1_0 order by o1_0.created_at desc offset ? rows fetch first ? rows only"); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/StableOrderIT.java b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/StableOrderIT.java new file mode 100644 index 0000000..7aa2567 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/StableOrderIT.java @@ -0,0 +1,61 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.pagination.support.IntegrationTest; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 3: ORDER BY created_at is not a complete order when many rows share a created_at. */ +@Tag("task3") +class StableOrderIT extends IntegrationTest { + + private static final long CUSTOMER = 4_000_000; + + @Test + @DisplayName("Order: the SQL sorts by created_at and then by id, so no two rows are ever equal") + void theSqlHasATieBreaker() { + String list = record(() -> orderService.page(0, 20)).pageQueries().getFirst().normalized(); + String history = record(() -> orderService.history(1, 0, 5)).pageQueries().getFirst().normalized(); + + assertThat(list).as("ORDER BY of GET /api/orders") + .containsPattern("order by \\S*created_at desc, ?\\S*\\bid desc"); + assertThat(history).as("ORDER BY of GET /api/customers/{id}/orders") + .containsPattern("order by \\S*created_at desc, ?\\S*\\bid desc"); + } + + @Test + @DisplayName("Order: orders with the same created_at come back with the highest id first, however they are stored") + void tiesComeBackInOneFixedOrder() { + thenRollBack(() -> { + List expected = customerWithOrders(CUSTOMER, 120); + + assertThat(ids(orderService.history(CUSTOMER, 0, 20).items())) + .as("page 0 of a customer whose orders arrive a dozen at a time") + .containsExactlyElementsOf(expected.subList(0, 20)); + assertThat(ids(orderService.history(CUSTOMER, 2, 20).items())) + .as("page 2") + .containsExactlyElementsOf(expected.subList(40, 60)); + }); + } + + @Test + @DisplayName("Order: reading a customer's 120 orders page by page returns each order exactly once") + void walkingThePagesReturnsEveryOrderOnce() { + thenRollBack(() -> { + List expected = customerWithOrders(CUSTOMER, 120); + + List received = new ArrayList<>(); + for (int page = 0; page < 6; page++) { + received.addAll(ids(orderService.history(CUSTOMER, page, 20).items())); + } + + assertThat(received).as("ids received over 6 pages of 20. Nothing was inserted or deleted in between") + .doesNotHaveDuplicates() + .containsExactlyInAnyOrderElementsOf(expected); + }); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/support/IntegrationTest.java b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/support/IntegrationTest.java new file mode 100644 index 0000000..94e445c --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/support/IntegrationTest.java @@ -0,0 +1,159 @@ +package com.amigoscode.pagination.support; + +import com.amigoscode.pagination.db.Explain; +import com.amigoscode.pagination.db.IndexInfo; +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.db.SqlRecorder; +import com.amigoscode.pagination.db.SqlStatement; +import com.amigoscode.pagination.order.Cursor; +import com.amigoscode.pagination.order.OrderResponse; +import com.amigoscode.pagination.order.OrderService; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.function.Supplier; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.ConnectionCallback; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * Base class for the *IT tests. They start the real application against a real Postgres started by + * Testcontainers (Docker must be running): a query plan only exists in a real database. One + * container is shared by every test class. + * + * The application seeds 20,000 orders at startup (the demo uses 1,000,000) and applies + * src/main/resources/indexes.sql. The tests never look at the clock. They call the service, write + * down the SQL it really sent, and check three things: which rows came back, how many statements + * were sent, and what Postgres did to answer them (the plan, the rows it read). + */ +@SpringBootTest(properties = {"spring.main.banner-mode=off", "shop.seed.orders=" + IntegrationTest.ORDERS}) +public abstract class IntegrationTest { + + /** Orders in the test database: ids 1 to 20,000, in 500 batches of 40 that share a created_at. */ + protected static final int ORDERS = 20_000; + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + static void database(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", POSTGRES::getJdbcUrl); + registry.add("spring.datasource.username", POSTGRES::getUsername); + registry.add("spring.datasource.password", POSTGRES::getPassword); + } + + /** What a call returned, and the SQL statements it sent to Postgres. */ + public record Recorded(T result, List statements) { + + /** The statements that fetch rows: everything except SELECT COUNT. */ + public List pageQueries() { + return statements.stream().filter(statement -> !statement.isCount()).toList(); + } + + public List countQueries() { + return statements.stream().filter(SqlStatement::isCount).toList(); + } + } + + @Autowired + protected OrderService orderService; + + @Autowired + protected JdbcTemplate jdbc; + + @Autowired + private TransactionTemplate transaction; + + /** Runs the call and writes down every SQL statement it sends. */ + protected Recorded record(Supplier call) { + SqlRecorder.start(); + try { + T result = call.get(); + return new Recorded<>(result, SqlRecorder.stop()); + } finally { + SqlRecorder.stop(); + } + } + + /** Runs the recorded statement again with EXPLAIN ANALYZE and returns what Postgres did. */ + protected Plan plan(SqlStatement statement) { + return jdbc.execute((ConnectionCallback) connection -> Explain.analyze(connection, statement)); + } + + /** What the indexes on orders cover, for example "(created_at, id)". */ + protected List indexedColumns() { + return jdbc.execute((ConnectionCallback>) IndexInfo::all).stream() + .map(IndexInfo::columns).toList(); + } + + /** + * Runs the work inside a transaction and rolls it back, so a test can insert, delete or update + * orders and leave the database exactly as it found it. The service joins the same transaction + * and sees those changes. + */ + protected T thenRollBack(Supplier work) { + return transaction.execute(status -> { + status.setRollbackOnly(); + return work.get(); + }); + } + + protected void thenRollBack(Runnable work) { + thenRollBack(() -> { + work.run(); + return null; + }); + } + + /** The ids the API must return for these positions: newest first, and the highest id first within one created_at. */ + protected List expectedIds(int offset, int limit) { + return jdbc.queryForList("select id from orders order by created_at desc, id desc limit ? offset ?", + Long.class, limit, offset); + } + + /** The cursor a client holds after reading this many orders from the top of the feed. */ + protected Cursor cursorAfter(int ordersRead) { + return jdbc.queryForObject( + "select created_at, id from orders order by created_at desc, id desc limit 1 offset ?", + (row, n) -> new Cursor(row.getObject("created_at", OffsetDateTime.class).toInstant(), row.getLong("id")), + ordersRead - 1); + } + + /** A brand new order, newer than every other one. Returns its id. */ + protected long insertNewestOrder() { + long id = jdbc.queryForObject("select max(id) + 1 from orders", Long.class); + jdbc.update(""" + insert into orders (id, customer_id, status, total_cents, created_at) + select ?, 1001, 'PENDING', 1999, max(created_at) + interval '1 minute' from orders + """, id); + return id; + } + + /** + * Gives a new customer this many orders, a dozen per created_at, and stores them in a shuffled + * order, the way rows end up on disk after years of inserts and updates. Returns the ids the API + * must return for that customer, first to last. + */ + protected List customerWithOrders(long customerId, int orders) { + jdbc.update(""" + insert into orders (id, customer_id, status, total_cents, created_at) + select 5000000 + i, ?, 'DELIVERED', 1999, + timestamptz '2030-01-01 00:00:00+00' + make_interval(mins => ((i - 1) / 12)::int) + from generate_series(1, ?) as i + order by md5(i::text) + """, customerId, orders); + return jdbc.queryForList("select id from orders where customer_id = ? order by created_at desc, id desc", + Long.class, customerId); + } + + protected static List ids(List orders) { + return orders.stream().map(OrderResponse::id).toList(); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/support/StubOrderService.java b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/support/StubOrderService.java new file mode 100644 index 0000000..0674ae1 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/test/java/com/amigoscode/pagination/support/StubOrderService.java @@ -0,0 +1,66 @@ +package com.amigoscode.pagination.support; + +import com.amigoscode.pagination.ApiExceptionHandler; +import com.amigoscode.pagination.order.Cursor; +import com.amigoscode.pagination.order.FeedPage; +import com.amigoscode.pagination.order.OffsetPage; +import com.amigoscode.pagination.order.OrderController; +import com.amigoscode.pagination.order.OrderResponse; +import com.amigoscode.pagination.order.OrderService; +import java.time.Instant; +import java.util.List; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +/** + * An OrderService that never touches a database: it writes down what the controller asked for and + * returns one fixed order. Written by hand, no mocking library. + */ +public final class StubOrderService extends OrderService { + + public static final OrderResponse AN_ORDER = + new OrderResponse(42, 7, "PENDING", 1999, Instant.parse("2025-11-25T10:00:00Z")); + + /** What the controller passed on in the last call. null means: that argument was not part of the call. */ + public Integer page; + public Integer size; + public Long customerId; + public Cursor after; + public int calls; + + public StubOrderService() { + super(null); + } + + /** The real controller and the real error handler, wired to this stub. */ + public MockMvc api() { + return MockMvcBuilders.standaloneSetup(new OrderController(this)) + .setControllerAdvice(new ApiExceptionHandler()) + .build(); + } + + @Override + public OffsetPage page(int page, int size) { + calls++; + this.page = page; + this.size = size; + return new OffsetPage(List.of(AN_ORDER), page, size, true); + } + + @Override + public OffsetPage history(long customerId, int page, int size) { + calls++; + this.customerId = customerId; + this.page = page; + this.size = size; + return new OffsetPage(List.of(AN_ORDER), page, size, false); + } + + @Override + public FeedPage feed(Cursor after, int size) { + calls++; + this.after = after; + this.size = size; + return new FeedPage(List.of(AN_ORDER), "next-cursor", true); + } +} diff --git a/java/concepts/junior-mid/11-pagination/solution/src/test/resources/logback-test.xml b/java/concepts/junior-mid/11-pagination/solution/src/test/resources/logback-test.xml new file mode 100644 index 0000000..82166a4 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/solution/src/test/resources/logback-test.xml @@ -0,0 +1,11 @@ + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + + diff --git a/java/concepts/junior-mid/11-pagination/start/.mvn/jvm.config b/java/concepts/junior-mid/11-pagination/start/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/.mvn/jvm.config @@ -0,0 +1,2 @@ +--enable-native-access=ALL-UNNAMED +--sun-misc-unsafe-memory-access=allow diff --git a/java/concepts/junior-mid/11-pagination/start/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/11-pagination/start/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/java/concepts/junior-mid/11-pagination/start/check b/java/concepts/junior-mid/11-pagination/start/check new file mode 100755 index 0000000..69483ac --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/check @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use check.cmd (type: .\check). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.pagination.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/11-pagination/start/check.cmd b/java/concepts/junior-mid/11-pagination/start/check.cmd new file mode 100644 index 0000000..bd80c37 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/check.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./check +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.pagination.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/11-pagination/start/compose.yaml b/java/concepts/junior-mid/11-pagination/start/compose.yaml new file mode 100644 index 0000000..a20e258 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/compose.yaml @@ -0,0 +1,18 @@ +# The project name is set here because the folder is called "solution" (or "start") in every +# project of this repository: without it, "docker compose down" in another project would stop this one. +name: pagination +services: + postgres: + image: postgres:17-alpine + container_name: pagination-postgres + environment: + POSTGRES_DB: pagination + POSTGRES_USER: pagination + POSTGRES_PASSWORD: pagination + ports: + - "5450:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U pagination -d pagination"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/11-pagination/start/demo b/java/concepts/junior-mid/11-pagination/start/demo new file mode 100755 index 0000000..6268ffe --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/demo @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use demo.cmd (type: .\demo). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.pagination.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/11-pagination/start/demo.cmd b/java/concepts/junior-mid/11-pagination/start/demo.cmd new file mode 100644 index 0000000..c24ba01 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/demo.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./demo +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.pagination.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/11-pagination/start/inspect b/java/concepts/junior-mid/11-pagination/start/inspect new file mode 100755 index 0000000..a307d0f --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/inspect @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs on macOS and Linux. On Windows use inspect.cmd (type: .\inspect). +cd "$(dirname "$0")" || exit 1 +exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.pagination.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/11-pagination/start/inspect.cmd b/java/concepts/junior-mid/11-pagination/start/inspect.cmd new file mode 100644 index 0000000..4bac1ac --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/inspect.cmd @@ -0,0 +1,3 @@ +@echo off +rem Runs on Windows. On macOS and Linux use ./inspect +call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.pagination.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/11-pagination/start/mvnw b/java/concepts/junior-mid/11-pagination/start/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/java/concepts/junior-mid/11-pagination/start/mvnw.cmd b/java/concepts/junior-mid/11-pagination/start/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/java/concepts/junior-mid/11-pagination/start/pom.xml b/java/concepts/junior-mid/11-pagination/start/pom.xml new file mode 100644 index 0000000..e7c1f10 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + pagination + 0.0.1-SNAPSHOT + pagination + Pagination: see the deep OFFSET, the shifting rows and the hidden COUNT, then fix them with keyset pagination + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + runtime + + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.mockito + mockito-core + + + org.mockito + mockito-junit-jupiter + + + + + org.springframework.boot + spring-boot-starter-data-jpa-test + test + + + org.testcontainers + testcontainers-postgresql + test + + + org.junit.platform + junit-platform-launcher + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + false + + + + + + diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/ApiExceptionHandler.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/ApiExceptionHandler.java new file mode 100644 index 0000000..c3e6f8d --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/ApiExceptionHandler.java @@ -0,0 +1,37 @@ +package com.amigoscode.pagination; + +import com.amigoscode.pagination.order.InvalidCursorException; +import com.amigoscode.pagination.order.InvalidPageRequestException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; + +/** Anything not listed here becomes a 500. */ +@RestControllerAdvice +public class ApiExceptionHandler { + + public record ApiError(String code, String message) { + } + + @ExceptionHandler(InvalidPageRequestException.class) + public ResponseEntity invalidPageRequest(InvalidPageRequestException e) { + return error("INVALID_PAGE_REQUEST", e.getMessage()); + } + + @ExceptionHandler(InvalidCursorException.class) + public ResponseEntity invalidCursor(InvalidCursorException e) { + return error("INVALID_CURSOR", e.getMessage()); + } + + /** For example size=abc. */ + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + public ResponseEntity notANumber(MethodArgumentTypeMismatchException e) { + return error("BAD_REQUEST", e.getName() + " must be a number"); + } + + private static ResponseEntity error(String code, String message) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ApiError(code, message)); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/PaginationApplication.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/PaginationApplication.java new file mode 100644 index 0000000..50b11ec --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/PaginationApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.pagination; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class PaginationApplication { + + public static void main(String[] args) { + SpringApplication.run(PaginationApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/DatabaseSetup.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/DatabaseSetup.java new file mode 100644 index 0000000..2e6193c --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/DatabaseSetup.java @@ -0,0 +1,169 @@ +package com.amigoscode.pagination.db; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.HexFormat; +import java.util.List; +import java.util.Locale; +import java.util.function.Consumer; + +/** + * Puts the database in a known state. Safe to run as often as you like: + * + * 1. schema.sql creates the table if it is missing. + * 2. If the table was not seeded with the wanted number of rows, it is emptied and seeded again + * with generate_series: the rows are made inside Postgres, which takes seconds, not minutes. + * 3. If indexes.sql changed since the last run, every index except the primary key is dropped and + * indexes.sql is run again. Then VACUUM ANALYZE refreshes the planner's statistics. + * + * When nothing changed, steps 2 and 3 are skipped and this takes a few milliseconds. + */ +public final class DatabaseSetup { + + public static final long DEFAULT_ORDERS = 1_000_000; + + /** Orders that arrive together and share one created_at. */ + public static final int BATCH = 40; + + /** A problem the student can fix, for example a typo in indexes.sql. */ + public static final class SetupException extends RuntimeException { + public SetupException(String message) { + super(message); + } + } + + public static void run(Connection connection, long orders, Consumer log) throws SQLException { + if (orders < 1_000 || orders % BATCH != 0) { + throw new IllegalArgumentException("Seed at least 1,000 orders, in a multiple of " + BATCH + ", got " + orders); + } + connection.setAutoCommit(true); + try (Statement statement = connection.createStatement()) { + // Only one setup at a time, even if the application and ./demo start together. + statement.execute("select pg_advisory_lock(20261125)"); + try { + for (String sql : SqlScript.statements(SqlScript.read("schema.sql"))) { + statement.execute(sql); + } + boolean seeded = seed(connection, statement, orders, log); + applyIndexes(connection, statement, seeded, log); + } finally { + statement.execute("select pg_advisory_unlock(20261125)"); + } + } + } + + /** Forgets what was seeded, so the next run starts from an empty table. */ + public static void forget(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute("drop table if exists setup_state"); + } + } + + private static boolean seed(Connection connection, Statement statement, long orders, Consumer log) + throws SQLException { + if (String.valueOf(orders).equals(state(connection, "seeded_orders"))) { + return false; + } + log.accept(String.format(Locale.US, "Seeding %,d orders (first run only)...", orders)); + long start = System.nanoTime(); + + statement.execute("delete from setup_state"); + statement.execute("truncate table orders"); + dropSecondaryIndexes(connection, statement); + + // The shop sells through a marketplace, which sends its orders in batches: 40 orders every + // 40 minutes, written in one transaction, so all 40 share the same created_at. + // - The first 12 orders of a batch belong to one business customer (ids 1 to 1,000, taking + // turns), so a business customer has many orders with the same created_at. + // - The other 28 belong to retail customers (ids from 1,001). + // - Only the newest orders are still PENDING. Of the rest, one in twenty was CANCELLED. + statement.execute(""" + insert into orders (id, customer_id, status, total_cents, created_at) + select i, + case when (i - 1) %% %2$d < 12 then 1 + ((i - 1) / %2$d) %% 1000 + else 1001 + (i * 7919) %% 99000 end, + case when i > %1$d - %1$d / 250 then 'PENDING' + when i %% 20 = 0 then 'CANCELLED' + else 'DELIVERED' end, + 500 + (i * 7919) %% 50000, + timestamptz '2024-01-01 00:00:00+00' + make_interval(mins => (((i - 1) / %2$d) * 40)::int) + from generate_series(1::bigint, %1$d) as i + """.formatted(orders, BATCH)); + + setState(connection, "seeded_orders", String.valueOf(orders)); + log.accept(String.format(Locale.US, "Seeded in %.1f s.", (System.nanoTime() - start) / 1e9)); + return true; + } + + private static void applyIndexes(Connection connection, Statement statement, boolean seeded, Consumer log) + throws SQLException { + String script = SqlScript.read("indexes.sql"); + List statements = SqlScript.statements(script); + String hash = sha256(String.join(";", statements)); + if (!seeded && hash.equals(state(connection, "indexes_sql"))) { + return; + } + log.accept("indexes.sql changed: rebuilding " + statements.size() + + (statements.size() == 1 ? " index..." : " indexes...")); + long start = System.nanoTime(); + statement.execute("delete from setup_state where key = 'indexes_sql'"); + dropSecondaryIndexes(connection, statement); + for (int i = 0; i < statements.size(); i++) { + try { + statement.execute(statements.get(i)); + } catch (SQLException e) { + throw new SetupException("Statement " + (i + 1) + " in src/main/resources/indexes.sql failed:\n\n " + + statements.get(i) + "\n\n" + e.getMessage().lines().findFirst().orElse("")); + } + } + // ANALYZE collects the statistics the planner uses to choose a plan. + statement.execute("vacuum (analyze) orders"); + setState(connection, "indexes_sql", hash); + log.accept(String.format(Locale.US, "Indexes ready in %.1f s.", (System.nanoTime() - start) / 1e9)); + } + + private static void dropSecondaryIndexes(Connection connection, Statement statement) throws SQLException { + for (IndexInfo index : IndexInfo.all(connection)) { + if (index.secondary()) { + statement.execute("drop index if exists \"" + index.name() + "\""); + } + } + } + + private static String state(Connection connection, String key) throws SQLException { + try (PreparedStatement select = connection.prepareStatement("select value from setup_state where key = ?")) { + select.setString(1, key); + try (ResultSet row = select.executeQuery()) { + return row.next() ? row.getString(1) : null; + } + } + } + + private static void setState(Connection connection, String key, String value) throws SQLException { + try (PreparedStatement upsert = connection.prepareStatement(""" + insert into setup_state (key, value) values (?, ?) + on conflict (key) do update set value = excluded.value + """)) { + upsert.setString(1, key); + upsert.setString(2, value); + upsert.executeUpdate(); + } + } + + private static String sha256(String text) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private DatabaseSetup() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/DatabaseSetupRunner.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/DatabaseSetupRunner.java new file mode 100644 index 0000000..a6a1a1d --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/DatabaseSetupRunner.java @@ -0,0 +1,32 @@ +package com.amigoscode.pagination.db; + +import java.sql.Connection; +import java.sql.SQLException; +import javax.sql.DataSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** Runs DatabaseSetup when the application starts: the table, the rows, then the indexes from indexes.sql. */ +@Component +public class DatabaseSetupRunner implements InitializingBean { + + private static final Logger log = LoggerFactory.getLogger(DatabaseSetupRunner.class); + + private final DataSource dataSource; + private final long orders; + + public DatabaseSetupRunner(DataSource dataSource, @Value("${shop.seed.orders}") long orders) { + this.dataSource = dataSource; + this.orders = orders; + } + + @Override + public void afterPropertiesSet() throws SQLException { + try (Connection connection = dataSource.getConnection()) { + DatabaseSetup.run(connection, orders, log::info); + } + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/Explain.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/Explain.java new file mode 100644 index 0000000..644018c --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/Explain.java @@ -0,0 +1,55 @@ +package com.amigoscode.pagination.db; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +/** + * Asks Postgres how it runs a statement the application sent. EXPLAIN ANALYZE really executes the + * statement, with the same values, and reports what happened: which scan, how many rows, how many + * pages. + * + * Parallel query is switched off for the EXPLAIN, so a sequential scan shows up as one plain + * "Seq Scan" line instead of "Gather" over "Parallel Seq Scan" with per-worker numbers. + */ +public final class Explain { + + /** The plan as an object you can ask questions. */ + public static Plan analyze(Connection connection, SqlStatement statement) throws SQLException { + return Plan.parse(String.join("\n", run(connection, "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ", statement))); + } + + /** The plan as the text Postgres prints, one line per list entry. */ + public static List text(Connection connection, SqlStatement statement) throws SQLException { + return run(connection, "EXPLAIN (ANALYZE, BUFFERS) ", statement); + } + + private static List run(Connection connection, String explain, SqlStatement statement) throws SQLException { + try (Statement settings = connection.createStatement()) { + settings.execute("SET max_parallel_workers_per_gather = 0"); + try (PreparedStatement prepared = connection.prepareStatement(explain + statement.sql())) { + statement.bindTo(prepared); + List lines = new ArrayList<>(); + try (ResultSet row = prepared.executeQuery()) { + while (row.next()) { + lines.add(row.getString(1)); + } + } + return lines; + } finally { + try { + settings.execute("RESET max_parallel_workers_per_gather"); + } catch (SQLException ignored) { + // The transaction is already broken by the real error, which is the one to report. + } + } + } + } + + private Explain() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/IndexInfo.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/IndexInfo.java new file mode 100644 index 0000000..9c80a09 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/IndexInfo.java @@ -0,0 +1,51 @@ +package com.amigoscode.pagination.db; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +/** + * One index on the orders table, as the database catalog describes it. + * + * @param definition the CREATE INDEX statement Postgres would use to rebuild it + * @param secondary false for the index that backs the PRIMARY KEY + * @param scans how many times a query used it since it was created + */ +public record IndexInfo(String name, String definition, long sizeBytes, long scans, boolean secondary) { + + private static final String SQL = """ + select c.relname as index_name, + pg_get_indexdef(i.indexrelid) as definition, + pg_relation_size(i.indexrelid) as size_bytes, + coalesce(s.idx_scan, 0) as scans, + not exists (select 1 from pg_constraint k where k.conindid = i.indexrelid) as secondary + from pg_index i + join pg_class c on c.oid = i.indexrelid + join pg_class t on t.oid = i.indrelid + left join pg_stat_user_indexes s on s.indexrelid = i.indexrelid + where t.relname = 'orders' + and t.relnamespace = 'public'::regnamespace + order by secondary, c.relname + """; + + /** Every index on orders. */ + public static List all(Connection connection) throws SQLException { + List indexes = new ArrayList<>(); + try (Statement statement = connection.createStatement(); ResultSet row = statement.executeQuery(SQL)) { + while (row.next()) { + indexes.add(new IndexInfo(row.getString("index_name"), row.getString("definition"), + row.getLong("size_bytes"), row.getLong("scans"), row.getBoolean("secondary"))); + } + } + return indexes; + } + + /** The part of the definition after the table name, for example "(created_at, id)". */ + public String columns() { + int at = definition.indexOf(" USING btree "); + return at < 0 ? definition : definition.substring(at + " USING btree ".length()); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/Plan.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/Plan.java new file mode 100644 index 0000000..f16a568 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/Plan.java @@ -0,0 +1,145 @@ +package com.amigoscode.pagination.db; + +import java.util.ArrayList; +import java.util.List; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * A query plan, parsed from the output of EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON). A plan is a tree + * of nodes: this class flattens it into a list, which is enough to answer "how many rows were read?". + */ +public final class Plan { + + /** + * One step of the plan. + * + * @param type "Seq Scan", "Index Scan", "Sort", "Incremental Sort", "Limit", "Aggregate"... + * @param relation the table the step reads, or null + * @param index the index the step uses, or null + * @param backward true when the index is read from its end to its start (ORDER BY ... DESC) + * @param condition the condition answered by the index (Index Cond), or null + * @param filter the condition checked row by row after reading (Filter), or null + * @param rows rows the step passed on + * @param removedByFilter rows the step read and then threw away + * @param heapFetches for an Index Only Scan: how many times it still had to visit the table + */ + public record Node(String type, String relation, String index, boolean backward, String condition, String filter, + long rows, long removedByFilter, long heapFetches) { + + /** True for the steps that read a table: every kind of scan except the bitmap's index half. */ + public boolean readsTable() { + return relation != null && type.endsWith("Scan") && !type.equals("Bitmap Index Scan"); + } + + @Override + public String toString() { + return type + (backward ? " Backward" : "") + (index == null ? "" : " using " + index) + (relation == null ? "" : " on " + relation); + } + } + + private static final JsonMapper JSON = new JsonMapper(); + + private final List nodes = new ArrayList<>(); + private final double executionMillis; + private final long pages; + + private Plan(JsonNode root) { + JsonNode top = root.get(0); + JsonNode plan = top.path("Plan"); + this.executionMillis = top.path("Execution Time").asDouble(0); + this.pages = plan.path("Shared Hit Blocks").asLong(0) + plan.path("Shared Read Blocks").asLong(0); + collect(plan); + } + + public static Plan parse(String json) { + return new Plan(JSON.readTree(json)); + } + + private void collect(JsonNode node) { + long loops = Math.max(1, node.path("Actual Loops").asLong(1)); + nodes.add(new Node( + text(node, "Node Type"), + text(node, "Relation Name"), + text(node, "Index Name"), + "Backward".equals(text(node, "Scan Direction")), + text(node, "Index Cond"), + text(node, "Filter"), + Math.round(node.path("Actual Rows").asDouble(0) * loops), + Math.round((node.path("Rows Removed by Filter").asDouble(0) + + node.path("Rows Removed by Index Recheck").asDouble(0)) * loops), + Math.round(node.path("Heap Fetches").asDouble(0)))); + JsonNode children = node.path("Plans"); + for (int i = 0; i < children.size(); i++) { + collect(children.get(i)); + } + } + + private static String text(JsonNode node, String field) { + JsonNode value = node.get(field); + return value == null || value.isNull() ? null : value.asString(); + } + + /** Every step, the outermost first. */ + public List nodes() { + return List.copyOf(nodes); + } + + /** True if any step's type contains the text: has("Seq Scan"), has("Sort") (which also finds "Incremental Sort"). */ + public boolean has(String nodeType) { + return nodes.stream().anyMatch(node -> node.type().contains(nodeType)); + } + + /** The names of the indexes the plan uses. */ + public List indexes() { + return nodes.stream().map(Node::index).filter(index -> index != null).distinct().toList(); + } + + /** The steps that read a table. */ + public List scans() { + return nodes.stream().filter(Node::readsTable).toList(); + } + + /** Rows the query returned. */ + public long rowsReturned() { + return nodes.getFirst().rows(); + } + + /** Rows read from tables (or from an index, for an index-only scan), kept or not. */ + public long rowsRead() { + return scans().stream().mapToLong(node -> node.rows() + node.removedByFilter()).sum(); + } + + /** Rows that were read and then thrown away by a Filter. */ + public long rowsThrownAway() { + return nodes.stream().mapToLong(Node::removedByFilter).sum(); + } + + /** Table visits made by index-only scans. 0 is the goal. */ + public long heapFetches() { + return nodes.stream().mapToLong(Node::heapFetches).sum(); + } + + /** 8 kB pages the query touched, in tables and indexes together. */ + public long pages() { + return pages; + } + + public double executionMillis() { + return executionMillis; + } + + /** For example "Index Scan Backward using idx_orders_created_at on orders". */ + public String describe() { + List steps = nodes.stream() + .filter(node -> node.relation() != null || node.index() != null) + .map(Node::toString) + .toList(); + return steps.isEmpty() ? nodes.getFirst().type() : String.join(" + ", steps); + } + + @Override + public String toString() { + return describe(); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/SqlRecorder.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/SqlRecorder.java new file mode 100644 index 0000000..1739193 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/SqlRecorder.java @@ -0,0 +1,133 @@ +package com.amigoscode.pagination.db; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import javax.sql.DataSource; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.DelegatingDataSource; + +/** + * Records the SQL the application really sends to Postgres, whoever wrote it: Hibernate, Spring + * Data or a native query. ./demo, ./inspect and the tests use it to answer "what did this request + * run?" and then ask Postgres to EXPLAIN exactly that. + * + * SqlRecorder.start(); + * ... call the endpoint ... + * List statements = SqlRecorder.stop(); + * + * It works by wrapping the DataSource: every PreparedStatement is watched, and when it is executed + * its SQL and its bound values are written down. When nobody is recording, nothing is kept. + */ +public final class SqlRecorder { + + private static final Object LOCK = new Object(); + private static final Set EXECUTE = Set.of("execute", "executeQuery", "executeUpdate", "executeLargeUpdate"); + private static List recording; + + public static void start() { + synchronized (LOCK) { + recording = new ArrayList<>(); + } + } + + /** Stops recording and returns the statements executed since start(), in order. */ + public static List stop() { + synchronized (LOCK) { + List statements = recording == null ? List.of() : List.copyOf(recording); + recording = null; + return statements; + } + } + + private static void record(String sql, Map bindings) { + synchronized (LOCK) { + if (recording != null) { + recording.add(new SqlStatement(sql, List.copyOf(bindings.values()))); + } + } + } + + /** Wraps every DataSource bean of the application. */ + @Configuration + static class Wiring { + + @Bean + static BeanPostProcessor recordSqlOfEveryDataSource() { + return new BeanPostProcessor() { + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) { + return bean instanceof DataSource dataSource ? new RecordingDataSource(dataSource) : bean; + } + }; + } + } + + private static final class RecordingDataSource extends DelegatingDataSource { + + RecordingDataSource(DataSource target) { + super(target); + } + + @Override + public Connection getConnection() throws SQLException { + return watch(super.getConnection()); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return watch(super.getConnection(username, password)); + } + + private static Connection watch(Connection connection) { + return proxy(Connection.class, (proxy, method, args) -> { + Object result = call(connection, method, args); + if (method.getName().equals("prepareStatement") && result instanceof PreparedStatement statement) { + return watch(statement, (String) args[0]); + } + return result; + }); + } + + private static PreparedStatement watch(PreparedStatement statement, String sql) { + Map bindings = new TreeMap<>(); + return proxy(PreparedStatement.class, (proxy, method, args) -> { + String name = method.getName(); + if (name.startsWith("set") && args != null && args.length >= 2 && args[0] instanceof Integer index) { + bindings.put(index, new SqlStatement.Binding(method, args.clone())); + } else if (name.equals("clearParameters")) { + bindings.clear(); + } else if (EXECUTE.contains(name) && args == null) { + record(sql, bindings); + } + return call(statement, method, args); + }); + } + + private static T proxy(Class type, InvocationHandler handler) { + return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, handler)); + } + + private static Object call(Object target, Method method, Object[] args) throws Throwable { + try { + return method.invoke(target, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } + } + + private SqlRecorder() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/SqlScript.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/SqlScript.java new file mode 100644 index 0000000..167d832 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/SqlScript.java @@ -0,0 +1,44 @@ +package com.amigoscode.pagination.db; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +/** Reads a .sql file from the classpath and splits it into statements. */ +public final class SqlScript { + + /** The file's text. */ + public static String read(String resource) { + try (InputStream in = SqlScript.class.getClassLoader().getResourceAsStream(resource)) { + if (in == null) { + throw new IllegalStateException(resource + " is missing from src/main/resources"); + } + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** The statements in a script: "--" comments are removed, statements end with a semicolon. */ + public static List statements(String script) { + StringBuilder withoutComments = new StringBuilder(); + for (String line : script.lines().toList()) { + int comment = line.indexOf("--"); + withoutComments.append(comment < 0 ? line : line.substring(0, comment)).append('\n'); + } + List statements = new ArrayList<>(); + for (String statement : withoutComments.toString().split(";")) { + String trimmed = statement.strip().replaceAll("\\s+", " "); + if (!trimmed.isEmpty()) { + statements.add(trimmed); + } + } + return statements; + } + + private SqlScript() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/SqlStatement.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/SqlStatement.java new file mode 100644 index 0000000..c3a85d0 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/db/SqlStatement.java @@ -0,0 +1,69 @@ +package com.amigoscode.pagination.db; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.List; +import java.util.Locale; +import java.util.regex.Pattern; + +/** + * One SQL statement the application sent to the database, with the values it bound to the + * ? placeholders. Recorded by SqlRecorder. + */ +public record SqlStatement(String sql, List bindings) { + + /** One call like setLong(2, 20) on the PreparedStatement. */ + public record Binding(Method setter, Object[] arguments) { + + Object value() { + return arguments[1]; + } + } + + private static final Pattern COUNT = Pattern.compile("^\\s*select\\s+count\\s*\\(", Pattern.CASE_INSENSITIVE); + private static final Pattern SELECT_LIST = Pattern.compile("^(select) (.{40,}?) (from .*)$", Pattern.CASE_INSENSITIVE); + + /** True for SELECT COUNT(...): the query that counts every matching row. */ + public boolean isCount() { + return COUNT.matcher(sql).find(); + } + + /** The SQL in lower case on one line: handy for "does it contain ..." checks. */ + public String normalized() { + return sql.replaceAll("\\s+", " ").strip().toLowerCase(Locale.ROOT); + } + + /** The SQL on one line, with a long list of selected columns shortened to "...". */ + public String shortSql() { + String oneLine = sql.replaceAll("\\s+", " ").strip(); + return SELECT_LIST.matcher(oneLine).replaceFirst("$1 ... $3"); + } + + /** The bound values in placeholder order, for example [99980, 20]. */ + public List parameters() { + return bindings.stream().map(Binding::value).toList(); + } + + /** Binds the same values to another PreparedStatement, so the statement can be run again. */ + public void bindTo(PreparedStatement statement) throws SQLException { + for (Binding binding : bindings) { + try { + binding.setter().invoke(statement, binding.arguments()); + } catch (InvocationTargetException e) { + if (e.getCause() instanceof SQLException sql) { + throw sql; + } + throw new IllegalStateException(e.getCause()); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + } + + @Override + public String toString() { + return shortSql() + (bindings.isEmpty() ? "" : " " + parameters()); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/demo/App.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/demo/App.java new file mode 100644 index 0000000..aa4ee1b --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/demo/App.java @@ -0,0 +1,248 @@ +package com.amigoscode.pagination.demo; + +import com.amigoscode.pagination.PaginationApplication; +import com.amigoscode.pagination.db.DatabaseSetup; +import com.amigoscode.pagination.db.Explain; +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.db.SqlRecorder; +import com.amigoscode.pagination.db.SqlStatement; +import com.amigoscode.pagination.order.Cursor; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Timestamp; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * What ./demo and ./inspect share: the seeded database, the real application on a free port, HTTP + * requests against it, the SQL each request sent, and EXPLAIN for that SQL. + */ +final class App implements AutoCloseable { + + /** What came back from one GET, and the SQL statements the application sent to answer it. */ + record Response(String path, int status, JsonNode body, int bytes, long millis, List statements) { + + boolean ok() { + return status == 200; + } + + /** The ids of the orders in "items", in the order they were returned. */ + List ids() { + List ids = new ArrayList<>(); + JsonNode items = body.path("items"); + for (int i = 0; i < items.size(); i++) { + ids.add(items.get(i).path("id").asLong()); + } + return ids; + } + + boolean hasNext() { + return body.path("hasNext").asBoolean(false); + } + + /** The cursor for the next page of the feed, or null. */ + String nextCursor() { + JsonNode cursor = body.path("nextCursor"); + return cursor.isMissingNode() || cursor.isNull() ? null : cursor.asString(); + } + + /** For a response that is not a 200: "INVALID_CURSOR: The cursor ...". */ + String error() { + String code = body.path("code").asString(""); + String message = body.path("message").asString(body.path("error").asString("")); + return (code.isEmpty() ? "" : code + ": ") + message; + } + + /** The statements that fetch rows: everything except SELECT COUNT. */ + List pageQueries() { + return statements.stream().filter(statement -> !statement.isCount()).toList(); + } + + List countQueries() { + return statements.stream().filter(SqlStatement::isCount).toList(); + } + } + + private static final JsonMapper JSON = new JsonMapper(); + + private final Connection connection; + private final ConfigurableApplicationContext context; + private final String baseUrl; + private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build(); + private final long orders; + + private App(Connection connection, ConfigurableApplicationContext context, long orders) { + this.connection = connection; + this.context = context; + this.baseUrl = "http://localhost:" + context.getEnvironment().getProperty("local.server.port"); + this.orders = orders; + } + + /** + * Seeds the database if needed, applies indexes.sql and starts the application. Returns null, + * after printing why, when Postgres is not reachable or indexes.sql has a mistake in it. + */ + static App start(boolean reseed) throws Exception { + if (!Db.isUp()) { + return null; + } + Connection connection = Db.connect(); + System.out.println(); + if (reseed) { + DatabaseSetup.forget(connection); + } + boolean[] logged = new boolean[1]; + try { + DatabaseSetup.run(connection, DatabaseSetup.DEFAULT_ORDERS, message -> { + logged[0] = true; + System.out.println(message); + }); + } catch (DatabaseSetup.SetupException e) { + System.out.println(e.getMessage()); + System.out.println(); + System.out.println("Fix the statement and run the command again."); + System.out.println(); + connection.close(); + return null; + } + if (logged[0]) { + System.out.println(); + } + try (Statement statement = connection.createStatement()) { + // An order left behind by a demo run that was stopped half way. + statement.execute("delete from orders where id > " + DatabaseSetup.DEFAULT_ORDERS); + } + + SpringApplication app = new SpringApplication(PaginationApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + ConfigurableApplicationContext context = app.run( + "--server.port=0", + "--logging.level.root=WARN", + // A 500 is shown as one line instead of a full stack trace. + "--logging.level.org.apache.catalina.core.ContainerBase=OFF", + "--spring.web.error.include-message=always"); + App started = new App(connection, context, DatabaseSetup.DEFAULT_ORDERS); + // Throwaway requests, so the first real one is not slowed down by startup work. + started.get("/api/orders/feed?size=1"); + started.get("/api/orders?page=0&size=1"); + started.get("/api/customers/1/orders?page=0&size=1"); + return started; + } + + long orders() { + return orders; + } + + Connection connection() { + return connection; + } + + /** Sends GET path to the running application and writes down the SQL it sends meanwhile. */ + Response get(String path) throws Exception { + HttpRequest request = HttpRequest.newBuilder(URI.create(baseUrl + path)).build(); + SqlRecorder.start(); + long start = System.nanoTime(); + HttpResponse response; + List statements; + try { + response = http.send(request, HttpResponse.BodyHandlers.ofByteArray()); + } finally { + statements = SqlRecorder.stop(); + } + long millis = (System.nanoTime() - start) / 1_000_000; + JsonNode body; + try { + body = JSON.readTree(response.body()); + } catch (RuntimeException e) { + body = JSON.createObjectNode(); + } + return new Response(path, response.statusCode(), body, response.body().length, millis, statements); + } + + /** Runs the statement again with EXPLAIN (ANALYZE, BUFFERS) and returns what Postgres did. */ + Plan plan(SqlStatement statement) throws SQLException { + return Explain.analyze(connection, statement); + } + + List planText(SqlStatement statement) throws SQLException { + return Explain.text(connection, statement); + } + + /** The ids the feed must return for these positions: newest first, highest id first within one created_at. */ + List expectedIds(long offset, int limit) throws SQLException { + try (PreparedStatement select = connection.prepareStatement( + "select id from orders order by created_at desc, id desc limit ? offset ?")) { + select.setInt(1, limit); + select.setLong(2, offset); + List ids = new ArrayList<>(); + try (ResultSet row = select.executeQuery()) { + while (row.next()) { + ids.add(row.getLong(1)); + } + } + return ids; + } + } + + /** + * The path of a feed page that starts after this many orders. A real client can only get such a + * cursor by following nextCursor from the top. The tools take a shortcut: they look the row up + * in the database and build the cursor from it. + */ + String feedPathAfter(long ordersRead, int size) throws SQLException { + if (ordersRead == 0) { + return "/api/orders/feed?size=" + size; + } + try (PreparedStatement select = connection.prepareStatement( + "select created_at, id from orders order by created_at desc, id desc limit 1 offset ?")) { + select.setLong(1, ordersRead - 1); + try (ResultSet row = select.executeQuery()) { + row.next(); + Cursor cursor = new Cursor(row.getObject(1, OffsetDateTime.class).toInstant(), row.getLong(2)); + return feedPath(cursor.encode(), size); + } + } + } + + static String feedPath(String cursor, int size) { + return "/api/orders/feed?size=" + size + "&after=" + URLEncoder.encode(cursor, StandardCharsets.UTF_8); + } + + /** The values bound to a statement, readable: 99980, 20. */ + static String values(SqlStatement statement) { + return statement.parameters().stream() + .map(value -> value instanceof Timestamp timestamp ? "'" + timestamp.toInstant() + "'" : String.valueOf(value)) + .collect(Collectors.joining(", ")); + } + + static String number(long value) { + return String.format(Locale.US, "%,d", value); + } + + @Override + public void close() throws SQLException { + try { + context.close(); + } finally { + connection.close(); + } + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/demo/Db.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/demo/Db.java new file mode 100644 index 0000000..c410b7a --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/demo/Db.java @@ -0,0 +1,41 @@ +package com.amigoscode.pagination.demo; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +/** Connection settings shared by the demo and inspect tools. Same defaults as application.properties. */ +final class Db { + + static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5450/pagination"); + static final String USER = env("DB_USER", "pagination"); + static final String PASSWORD = env("DB_PASSWORD", "pagination"); + + private Db() { + } + + static Connection connect() throws SQLException { + return DriverManager.getConnection(URL, USER, PASSWORD); + } + + /** Returns false, after printing what to do, when Postgres is not reachable. */ + static boolean isUp() { + try (Connection ignored = connect()) { + return true; + } catch (SQLException e) { + System.out.println(); + System.out.println("Cannot reach Postgres at " + URL); + System.out.println("Start it first, from this folder:"); + System.out.println(); + System.out.println(" docker compose up -d"); + System.out.println(); + System.out.println("(" + e.getMessage().lines().findFirst().orElse("") + ")"); + return false; + } + } + + private static String env(String name, String fallback) { + String value = System.getenv(name); + return value == null || value.isBlank() ? fallback : value; + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/demo/Demo.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/demo/Demo.java new file mode 100644 index 0000000..8885455 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/demo/Demo.java @@ -0,0 +1,526 @@ +package com.amigoscode.pagination.demo; + +import static com.amigoscode.pagination.demo.App.number; + +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.db.SqlStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +/** + * Starts the real application, asks it for pages of orders over HTTP, and prints what each request + * cost inside Postgres: the SQL it sent, the rows that SQL read and the pages it touched. Ends with + * a RESULT line. Run it with ./demo (or .\demo on Windows). ./demo --help lists the flags. + */ +public final class Demo { + + private enum Mode { + OFFSET, KEYSET, HISTORY + } + + private record Options(Mode mode, int depth, int size, boolean insert, long customer, boolean reseed) { + } + + /** What Postgres did for the statement that fetched the rows of one page. */ + private record Cost(App.Response response, Plan plan) { + + long thrownAway() { + return Math.max(0, plan.rowsRead() - response.ids().size()); + } + } + + public static void main(String[] args) throws Exception { + Options options; + try { + options = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println(); + printHelp(); + return; + } + if (options == null) { + printHelp(); + return; + } + try (App app = App.start(options.reseed())) { + if (app == null) { + return; + } + if (options.size() > 100) { + unbounded(app, options); + } else if (options.mode() == Mode.HISTORY) { + history(app, options); + } else if (options.insert()) { + shift(app, options); + } else { + depth(app, options); + } + System.out.println(); + } + } + + // ---- Scenario 1: how much does a deep page cost? ---- + + private static void depth(App app, Options options) throws Exception { + int size = options.size(); + long pages = app.orders() / size; + int depth = (int) Math.min(options.depth(), pages); + long ordersBefore = (long) (depth - 1) * size; + boolean keyset = options.mode() == Mode.KEYSET; + + System.out.println("Mode: " + name(options.mode()) + " | page size: " + size + " | depth: page " + number(depth) + + " of " + number(pages)); + System.out.println("Table orders: " + number(app.orders()) + " rows, newest first."); + + System.out.println(); + System.out.println("--- Page 1 ---"); + Cost first = request(app, keyset ? "/api/orders/feed?size=" + size : "/api/orders?page=0&size=" + size); + if (first == null) { + return; + } + List problems = new ArrayList<>(); + + if (keyset) { + System.out.println(); + System.out.println("--- Page 2: the client sends back the nextCursor of page 1 ---"); + String cursor = first.response().nextCursor(); + if (cursor == null) { + System.out.println("Page 1 has no nextCursor, so the client believes the feed ends here."); + problems.add("Page 1 came back without a nextCursor although " + number(app.orders() - size) + " orders follow it."); + } else { + Cost second = request(app, App.feedPath(cursor, size)); + if (second == null) { + return; + } + Set missing = new LinkedHashSet<>(app.expectedIds(0, 2 * size)); + missing.removeAll(first.response().ids()); + missing.removeAll(second.response().ids()); + if (!missing.isEmpty()) { + problems.add("After two pages a client should have seen the " + (2 * size) + " newest orders. " + + number(missing.size()) + " of them were never returned, for example #" + + number(missing.iterator().next()) + "."); + } + } + } + + Cost deep = first; + if (depth > 1) { + System.out.println(); + System.out.println("--- Page " + number(depth) + " ---"); + if (keyset) { + System.out.println("A client gets here by following nextCursor " + number(depth - 1) + " times. To save you the wait, the"); + System.out.println("demo looked up the last order of page " + number(depth - 1) + " in the database and built the cursor from it."); + } + deep = request(app, keyset ? app.feedPathAfter(ordersBefore, size) : "/api/orders?page=" + (depth - 1) + "&size=" + size); + if (deep == null) { + return; + } + if (keyset) { + Set missing = new LinkedHashSet<>(app.expectedIds(ordersBefore, size)); + missing.removeAll(deep.response().ids()); + if (!missing.isEmpty()) { + problems.add("Page " + number(depth) + " comes after " + number(ordersBefore) + " orders, so it should hold the next " + + size + ". " + number(missing.size()) + " of them were not returned, for example #" + + number(missing.iterator().next()) + "."); + } + } + System.out.println(); + compare(first, deep, depth); + } + + System.out.println(); + if (!problems.isEmpty()) { + problems.forEach(problem -> System.out.println("RESULT: SKIPPED ROWS. " + problem)); + } else if (keyset && (deep.plan().has("Sort") || deep.plan().rowsRead() > size + 1)) { + System.out.println("RESULT: NO MATCHING INDEX. The pages are right, but page " + number(depth) + " read " + + number(deep.plan().rowsRead()) + " rows" + (deep.plan().has("Sort") ? " and sorted them" : "") + " to return " + + deep.response().ids().size() + "."); + System.out.println(" The feed is sorted by (created_at, id). No index on orders has exactly those columns."); + } else if (!keyset && deep.plan().rowsRead() > 10L * (size + 1)) { + System.out.println("RESULT: DEEP OFFSET. Page " + number(depth) + " read " + number(deep.plan().rowsRead()) + + " rows to return " + deep.response().ids().size() + ". Page 1 read " + number(first.plan().rowsRead()) + "."); + } else { + System.out.println("RESULT: OK. Page " + number(depth) + " read " + number(deep.plan().rowsRead()) + " rows to return " + + deep.response().ids().size() + (depth > 1 ? ". Page 1 read " + number(first.plan().rowsRead()) + "." : ".")); + } + hiddenCount(app, deep.response()); + } + + private static void compare(Cost first, Cost deep, int depth) { + String header = "page " + number(depth); + String format = "%-30s%-14s%s%n"; + System.out.printf(format, "", "page 1", header); + System.out.printf(format, "Rows returned to the client", first.response().ids().size(), deep.response().ids().size()); + System.out.printf(format, "Rows read", number(first.plan().rowsRead()), number(deep.plan().rowsRead())); + System.out.printf(format, "Rows read and thrown away", number(first.thrownAway()), number(deep.thrownAway())); + System.out.printf(format, "Pages read (8 kB each)", number(first.plan().pages()), number(deep.plan().pages())); + System.out.printf(format, "Time in the database", millis(first.plan()), millis(deep.plan()) + " (differs on every run)"); + } + + // ---- Scenario 2: an order is placed between two page requests ---- + + private static void shift(App app, Options options) throws Exception { + int size = options.size(); + boolean keyset = options.mode() == Mode.KEYSET; + System.out.println("Mode: " + name(options.mode()) + " | page size: " + size + + " | an order is placed between the two requests"); + + List expected = app.expectedIds(0, 2 * size); + long newOrder = app.orders() + 1; + try { + System.out.println(); + App.Response first = show(app, keyset ? "/api/orders/feed?size=" + size : "/api/orders?page=0&size=" + size); + if (first == null) { + return; + } + System.out.println(" last 3 orders: " + orders(tail(first.ids(), 3))); + + System.out.println(); + placeOrder(app, newOrder); + System.out.println("A customer places order #" + number(newOrder) + ". It is now the newest order: first in the list."); + System.out.println(); + + String next; + if (!keyset) { + next = "/api/orders?page=1&size=" + size; + } else if (first.nextCursor() != null) { + next = App.feedPath(first.nextCursor(), size); + } else { + System.out.println("RESULT: SKIPPED ROWS. Page 1 came back without a nextCursor, so the client stops reading."); + return; + } + App.Response second = show(app, next); + if (second == null) { + return; + } + System.out.println(" first 3 orders: " + orders(second.ids().subList(0, Math.min(3, second.ids().size())))); + + Set twice = new LinkedHashSet<>(first.ids()); + twice.retainAll(second.ids()); + Set missing = new LinkedHashSet<>(expected); + missing.removeAll(first.ids()); + missing.removeAll(second.ids()); + + System.out.println(); + if (!twice.isEmpty()) { + long example = twice.iterator().next(); + System.out.println("RESULT: SHIFTED. Order #" + number(example) + " was returned twice: at the end of page 1 and again" + + " at the start of page 2."); + System.out.println(" The new order moved every other order down by one, and OFFSET " + size + + " counts from the new top."); + } else if (!missing.isEmpty()) { + System.out.println("RESULT: SKIPPED ROWS. " + number(missing.size()) + " of the " + (2 * size) + + " newest orders were on neither page, for example #" + number(missing.iterator().next()) + "."); + } else { + System.out.println("RESULT: OK. Page 2 continues exactly where page 1 ended. No order was returned twice or skipped."); + } + hiddenCount(app, second); + } finally { + try (Statement statement = app.connection().createStatement()) { + statement.execute("delete from orders where id = " + newOrder); + } + } + } + + private static void placeOrder(App app, long id) throws SQLException { + try (PreparedStatement insert = app.connection().prepareStatement(""" + insert into orders (id, customer_id, status, total_cents, created_at) + select ?, 1001, 'PENDING', 1999, max(created_at) + interval '1 minute' from orders + """)) { + insert.setLong(1, id); + insert.executeUpdate(); + } + } + + // ---- Scenario 3: read all orders of one customer, page by page ---- + + private static void history(App app, Options options) throws Exception { + int size = options.size(); + long customer = options.customer(); + List expected = new ArrayList<>(); + try (PreparedStatement select = app.connection().prepareStatement("select id from orders where customer_id = ?")) { + select.setLong(1, customer); + try (ResultSet row = select.executeQuery()) { + while (row.next()) { + expected.add(row.getLong(1)); + } + } + } + System.out.println("Mode: history | customer: " + customer + " | page size: " + size); + System.out.println("Customer " + customer + " has " + number(expected.size()) + " orders. The demo reads all of them, page by page."); + System.out.println("Nothing is inserted, updated or deleted while it reads."); + System.out.println(); + + String path = "/api/customers/" + customer + "/orders?size=" + size + "&page="; + Cost firstPage = request(app, path + 0); + if (firstPage == null) { + return; + } + List received = new ArrayList<>(firstPage.response().ids()); + List> pages = new ArrayList<>(List.of(firstPage.response().ids())); + App.Response last = firstPage.response(); + while (last.hasNext() && !last.ids().isEmpty() && pages.size() < 10_000) { + last = app.get(path + pages.size()); + if (!last.ok()) { + System.out.println("GET " + last.path() + " returned " + last.status() + " " + last.error()); + System.out.println(); + System.out.println("RESULT: FAILED. The demo could not read page " + pages.size() + "."); + return; + } + pages.add(last.ids()); + received.addAll(last.ids()); + } + if (pages.size() > 1) { + System.out.println(); + System.out.println("... and " + (pages.size() - 1) + " more requests, for page=1 to page=" + (pages.size() - 1) + "."); + } + + Set different = new LinkedHashSet<>(received); + Set never = new LinkedHashSet<>(expected); + never.removeAll(different); + int twice = received.size() - different.size(); + + System.out.println(); + System.out.printf("%-30s%s%n", "Pages requested", pages.size()); + System.out.printf("%-30s%s%n", "Orders received", number(received.size())); + System.out.printf("%-30s%s%n", "Different orders received", number(different.size())); + System.out.printf("%-30s%s%n", "Orders received twice", number(twice)); + System.out.printf("%-30s%s%n", "Orders never received", number(never.size())); + if (twice > 0) { + System.out.println(); + System.out.println(repeatExample(app, pages)); + } + + System.out.println(); + if (twice > 0 || !never.isEmpty()) { + System.out.println("RESULT: UNSTABLE ORDER. Nothing changed in the database, but " + number(twice) + + " orders came back twice and " + number(never.size()) + " never came back."); + } else { + System.out.println("RESULT: OK. " + number(expected.size()) + " orders, each returned exactly once."); + } + hiddenCount(app, firstPage.response()); + } + + /** "Order #921,646 was on page 0 and again on page 1. 11 other orders of this customer have the same created_at." */ + private static String repeatExample(App app, List> pages) throws SQLException { + for (int later = 1; later < pages.size(); later++) { + for (long id : pages.get(later)) { + for (int earlier = 0; earlier < later; earlier++) { + if (pages.get(earlier).contains(id)) { + try (PreparedStatement select = app.connection().prepareStatement(""" + select count(*) - 1 from orders o + where (o.customer_id, o.created_at) = (select customer_id, created_at from orders where id = ?) + """)) { + select.setLong(1, id); + try (ResultSet row = select.executeQuery()) { + row.next(); + return "For example: order #" + number(id) + " was on page=" + earlier + " and again on page=" + later + + ".\n" + number(row.getLong(1)) + " other orders of this customer have exactly the same created_at."; + } + } + } + } + } + } + return ""; + } + + // ---- Scenario 4: a page size nobody should be allowed to ask for ---- + + private static void unbounded(App app, Options options) throws Exception { + int size = options.size(); + System.out.println("Mode: " + name(options.mode()) + " | page size: " + number(size)); + System.out.println(); + String path = switch (options.mode()) { + case OFFSET -> "/api/orders?page=0&size=" + size; + case KEYSET -> "/api/orders/feed?size=" + size; + case HISTORY -> "/api/customers/" + options.customer() + "/orders?page=0&size=" + size; + }; + App.Response response = app.get(path); + System.out.println("GET " + path); + if (response.ok()) { + System.out.println(" 200 OK, " + number(response.ids().size()) + " orders, " + + megabytes(response.bytes()) + " of JSON, " + number(response.millis()) + " ms"); + System.out.println(); + System.out.println("RESULT: UNBOUNDED. One request made the server load " + number(response.ids().size()) + + " orders and send " + megabytes(response.bytes()) + "."); + System.out.println(" Nothing stops a client from asking for size=1000000, or from leaving size out."); + } else { + System.out.println(" " + response.status() + " " + response.error()); + System.out.println(" SQL statements sent: " + response.statements().size()); + System.out.println(); + if (response.status() == 400) { + System.out.println("RESULT: OK. size=" + size + " was rejected with a 400 before anything was read from the database."); + } else { + System.out.println("RESULT: FAILED. size=" + size + " should be a 400 (the client's mistake), not a " + response.status() + "."); + } + } + } + + // ---- Shared printing ---- + + /** Sends the request, prints it with the cost of every SQL statement, and returns the cost of the page query. */ + private static Cost request(App app, String path) throws Exception { + App.Response response = show(app, path); + if (response == null) { + return null; + } + Plan pagePlan = null; + System.out.println(" SQL statements sent: " + response.statements().size()); + int position = 1; + for (SqlStatement statement : response.statements()) { + Plan plan = app.plan(statement); + if (pagePlan == null && !statement.isCount()) { + pagePlan = plan; + } + String values = App.values(statement); + System.out.println(" " + position++ + ". " + statement.shortSql() + (values.isEmpty() ? "" : " -- ? = " + values)); + System.out.println(" " + plan.describe()); + System.out.println(" rows read: " + number(plan.rowsRead()) + " | rows returned: " + number(plan.rowsReturned()) + + " | pages read: " + number(plan.pages())); + } + if (pagePlan == null) { + System.out.println(); + System.out.println("RESULT: FAILED. The request sent no SQL that fetches orders."); + return null; + } + return new Cost(response, pagePlan); + } + + /** Sends the request and prints its first lines. Returns null, after printing a RESULT line, if it is not a 200. */ + private static App.Response show(App app, String path) throws Exception { + App.Response response = app.get(path); + System.out.println("GET " + path); + if (!response.ok()) { + System.out.println(" " + response.status() + " " + response.error()); + System.out.println(); + System.out.println("RESULT: FAILED. The request returned " + response.status() + "."); + return null; + } + System.out.println(" 200 OK, " + response.ids().size() + " orders, " + response.millis() + " ms"); + return response; + } + + private static void hiddenCount(App app, App.Response response) throws SQLException { + if (response.countQueries().isEmpty()) { + return; + } + Plan count = app.plan(response.countQueries().getFirst()); + System.out.println("RESULT: HIDDEN COUNT. The request also sent a SELECT COUNT that nobody asked for. It read " + + number(count.rowsRead()) + " rows to return one number."); + } + + private static String orders(List ids) { + StringBuilder text = new StringBuilder(); + for (long id : ids) { + text.append('#').append(number(id)).append(" "); + } + return text.toString().stripTrailing(); + } + + private static List tail(List list, int count) { + return list.subList(Math.max(0, list.size() - count), list.size()); + } + + private static String millis(Plan plan) { + return String.format(Locale.US, "%.2f ms", plan.executionMillis()); + } + + private static String megabytes(int bytes) { + return String.format(Locale.US, "%.1f MB", bytes / 1_000_000.0); + } + + private static String name(Mode mode) { + return mode.name().toLowerCase(Locale.ROOT); + } + + // ---- Options ---- + + private static Options parse(String[] args) { + Mode mode = Mode.OFFSET; + int depth = 5_000; + int size = 20; + boolean insert = false; + long customer = 42; + boolean reseed = false; + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "--help", "-h" -> { + return null; + } + case "--mode" -> mode = mode(value(args, ++i, arg)); + case "--depth" -> depth = between(value(args, ++i, arg), arg, 1, 1_000_000); + case "--size" -> size = between(value(args, ++i, arg), arg, 1, 1_000_000); + case "--customer" -> customer = between(value(args, ++i, arg), arg, 1, 100_000); + case "--insert" -> insert = true; + case "--reseed" -> reseed = true; + default -> throw new IllegalArgumentException("Unknown option: " + arg); + } + } + if (insert && mode == Mode.HISTORY) { + throw new IllegalArgumentException("--insert works with --mode offset and --mode keyset"); + } + return new Options(mode, depth, size, insert, customer, reseed); + } + + private static Mode mode(String value) { + try { + return Mode.valueOf(value.toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("--mode must be offset, keyset or history, got: " + value); + } + } + + private static String value(String[] args, int index, String option) { + if (index >= args.length) { + throw new IllegalArgumentException(option + " needs a value"); + } + return args[index]; + } + + private static int between(String value, String option, int min, int max) { + try { + int number = Integer.parseInt(value); + if (number < min || number > max) { + throw new NumberFormatException(); + } + return number; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(option + " must be a number from " + min + " to " + max + ", got: " + value); + } + } + + private static void printHelp() { + System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])"); + System.out.println(); + System.out.println(" --mode offset | keyset | history (default: offset)"); + System.out.println(" offset GET /api/orders?page=&size= every order, LIMIT and OFFSET"); + System.out.println(" keyset GET /api/orders/feed?after=&size= every order, with a cursor"); + System.out.println(" history GET /api/customers/{id}/orders reads ALL orders of one customer"); + System.out.println(" --depth which page to compare with page 1 (default: 5000)"); + System.out.println(" --size orders per page (default: 20). Above 100 the demo only asks for that one page"); + System.out.println(" --insert place a new order between the request for page 1 and the request for page 2"); + System.out.println(" --customer the customer for --mode history (default: 42, who has 300 orders)"); + System.out.println(" --reseed empty the table and seed the 1,000,000 orders again"); + System.out.println(); + System.out.println("Examples:"); + System.out.println(" ./demo"); + System.out.println(" ./demo --size 100000"); + System.out.println(" ./demo --mode history"); + System.out.println(" ./demo --insert"); + System.out.println(" ./demo --mode keyset --depth 5000"); + System.out.println(" ./demo --mode keyset --insert"); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/demo/Inspect.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/demo/Inspect.java new file mode 100644 index 0000000..69e3029 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/demo/Inspect.java @@ -0,0 +1,228 @@ +package com.amigoscode.pagination.demo; + +import static com.amigoscode.pagination.demo.App.number; + +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.db.SqlStatement; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** + * Shows what Postgres does for one page request: the table and its indexes, the SQL the endpoint + * sends right now, and the full EXPLAIN (ANALYZE, BUFFERS) output of each statement. Run it with + * ./inspect (or .\inspect on Windows). ./inspect --help lists the flags. + */ +public final class Inspect { + + private static final String TABLE = """ + select c.relname as "table", + to_char(c.reltuples::bigint, 'FM999,999,999') as rows, + pg_size_pretty(pg_relation_size(c.oid)) as table_size, + pg_size_pretty(pg_indexes_size(c.oid)) as all_indexes_size + from pg_class c + where c.relname = 'orders' and c.relnamespace = 'public'::regnamespace + """; + + private static final String INDEXES = """ + select c.relname as index, + substring(pg_get_indexdef(i.indexrelid) from 'USING btree (.*)$') as columns, + pg_size_pretty(pg_relation_size(i.indexrelid)) as size, + coalesce(s.idx_scan, 0) as scans, + case when i.indisprimary then 'primary key' else '' end as kind + from pg_index i + join pg_class c on c.oid = i.indexrelid + join pg_class t on t.oid = i.indrelid + left join pg_stat_user_indexes s on s.indexrelid = i.indexrelid + where t.relname = 'orders' and t.relnamespace = 'public'::regnamespace + order by i.indisprimary desc, c.relname + """; + + private record Options(String mode, int depth, int size, long customer) { + } + + public static void main(String[] args) throws Exception { + Options options; + try { + options = parse(args); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println(); + printHelp(); + return; + } + if (options == null) { + printHelp(); + return; + } + try (App app = App.start(false)) { + if (app == null) { + return; + } + System.out.println("TABLE (rows = the planner's estimate, refreshed by ANALYZE)"); + printTable(app.connection(), TABLE); + System.out.println(); + System.out.println("INDEXES ON orders (scans = how many times a query used the index since it was built)"); + printTable(app.connection(), INDEXES); + System.out.println(); + request(app, options); + System.out.println(); + } + } + + private static void request(App app, Options options) throws Exception { + int size = options.size(); + long ordersBefore = (long) (options.depth() - 1) * size; + String path = switch (options.mode()) { + case "keyset" -> app.feedPathAfter(Math.min(ordersBefore, app.orders() - 1), size); + case "history" -> "/api/customers/" + options.customer() + "/orders?page=" + (options.depth() - 1) + "&size=" + size; + default -> "/api/orders?page=" + (options.depth() - 1) + "&size=" + size; + }; + App.Response response = app.get(path); + + System.out.println("REQUEST (page " + number(options.depth()) + ", " + size + " orders per page)"); + System.out.println(" GET " + path); + if (!response.ok()) { + System.out.println(" " + response.status() + " " + response.error()); + System.out.println(" SQL statements sent: " + response.statements().size()); + return; + } + System.out.println(" 200 OK, " + response.ids().size() + " orders returned, hasNext = " + response.hasNext()); + System.out.println(" SQL statements sent: " + response.statements().size()); + + int position = 1; + for (SqlStatement statement : response.statements()) { + System.out.println(); + System.out.println("STATEMENT " + position++ + " of " + response.statements().size()); + statement.sql().strip().lines().forEach(line -> System.out.println(" " + line.strip())); + if (!statement.bindings().isEmpty()) { + System.out.println(" -- ? = " + App.values(statement)); + } + System.out.println(); + System.out.println(" EXPLAIN (ANALYZE, BUFFERS)"); + app.planText(statement).forEach(line -> System.out.println(" " + line)); + Plan plan = app.plan(statement); + System.out.println(); + System.out.println(" How the rows were found: " + plan.describe()); + System.out.println(" Rows read: " + number(plan.rowsRead())); + System.out.println(" Rows returned: " + number(plan.rowsReturned())); + System.out.println(" Pages read (8 kB each): " + number(plan.pages())); + System.out.println(" Sorted by Postgres: " + (plan.has("Sort") ? "yes, there is a Sort step" : "no")); + } + } + + /** Prints a query result as a plain text table. */ + private static void printTable(Connection connection, String sql) throws SQLException { + List rows = new ArrayList<>(); + try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) { + int columns = result.getMetaData().getColumnCount(); + String[] header = new String[columns]; + for (int c = 0; c < columns; c++) { + header[c] = result.getMetaData().getColumnLabel(c + 1); + } + rows.add(header); + while (result.next()) { + String[] row = new String[columns]; + for (int c = 0; c < columns; c++) { + String value = result.getString(c + 1); + row[c] = value == null ? "" : value; + } + rows.add(row); + } + } + int[] widths = new int[rows.get(0).length]; + for (String[] row : rows) { + for (int c = 0; c < row.length; c++) { + widths[c] = Math.max(widths[c], row[c].length()); + } + } + for (int r = 0; r < rows.size(); r++) { + StringBuilder line = new StringBuilder(" "); + for (int c = 0; c < widths.length; c++) { + line.append(String.format("%-" + widths[c] + "s", rows.get(r)[c])).append(" "); + } + System.out.println(line.toString().stripTrailing()); + if (r == 0) { + StringBuilder rule = new StringBuilder(" "); + for (int width : widths) { + rule.append("-".repeat(width)).append(" "); + } + System.out.println(rule.toString().stripTrailing()); + } + } + } + + private static Options parse(String[] args) { + String mode = "offset"; + int depth = 5_000; + int size = 20; + long customer = 42; + boolean depthGiven = false; + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "--help", "-h" -> { + return null; + } + case "--mode" -> { + mode = value(args, ++i, arg).toLowerCase(Locale.ROOT); + if (!List.of("offset", "keyset", "history").contains(mode)) { + throw new IllegalArgumentException("--mode must be offset, keyset or history, got: " + mode); + } + } + case "--depth" -> { + depth = between(value(args, ++i, arg), arg, 1, 1_000_000); + depthGiven = true; + } + case "--size" -> size = between(value(args, ++i, arg), arg, 1, 1_000_000); + case "--customer" -> customer = between(value(args, ++i, arg), arg, 1, 100_000); + default -> throw new IllegalArgumentException("Unknown option: " + arg); + } + } + if (mode.equals("history") && !depthGiven) { + depth = 1; + } + return new Options(mode, depth, size, customer); + } + + private static String value(String[] args, int index, String option) { + if (index >= args.length) { + throw new IllegalArgumentException(option + " needs a value"); + } + return args[index]; + } + + private static int between(String value, String option, int min, int max) { + try { + int number = Integer.parseInt(value); + if (number < min || number > max) { + throw new NumberFormatException(); + } + return number; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(option + " must be a number from " + min + " to " + max + ", got: " + value); + } + } + + private static void printHelp() { + System.out.println("Usage: ./inspect [options] (Windows: .\\inspect [options])"); + System.out.println(); + System.out.println(" --mode offset | keyset | history (default: offset)"); + System.out.println(" --depth which page to ask for (default: 5000; for history: 1)"); + System.out.println(" --size orders per page (default: 20)"); + System.out.println(" --customer the customer for --mode history (default: 42)"); + System.out.println(); + System.out.println("Examples:"); + System.out.println(" ./inspect"); + System.out.println(" ./inspect --depth 1"); + System.out.println(" ./inspect --mode keyset --depth 5000"); + System.out.println(" ./inspect --mode history"); + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/Cursor.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/Cursor.java new file mode 100644 index 0000000..ad52a64 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/Cursor.java @@ -0,0 +1,26 @@ +package com.amigoscode.pagination.order; + +import java.time.Instant; + +/** + * Where a page of the feed ended: the sort key of its last row. The next page is "everything that + * sorts after this". + * + * On the wire it is the two values with a | between them: 2025-11-25T10:00:00Z|999981 + */ +public record Cursor(Instant createdAt, long id) { + + public static Cursor after(Order lastRow) { + return new Cursor(lastRow.getCreatedAt(), lastRow.getId()); + } + + public String encode() { + return createdAt + "|" + id; + } + + /** Reads a cursor a client sent. */ + public static Cursor decode(String encoded) { + String[] parts = encoded.split("\\|"); + return new Cursor(Instant.parse(parts[0]), Long.parseLong(parts[1])); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/FeedPage.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/FeedPage.java new file mode 100644 index 0000000..1e63ae1 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/FeedPage.java @@ -0,0 +1,11 @@ +package com.amigoscode.pagination.order; + +import java.util.List; + +/** + * One page of the keyset endpoint: GET /api/orders/feed?after=...&size=20. + * + * @param nextCursor send it back as "after" to get the next page. null on the last page + */ +public record FeedPage(List items, String nextCursor, boolean hasNext) { +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/InvalidCursorException.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/InvalidCursorException.java new file mode 100644 index 0000000..46042bd --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/InvalidCursorException.java @@ -0,0 +1,9 @@ +package com.amigoscode.pagination.order; + +/** The "after" parameter is not a cursor this API handed out. A 400. */ +public class InvalidCursorException extends RuntimeException { + + public InvalidCursorException() { + super("The cursor in 'after' is not valid. Leave 'after' out to start from the newest order."); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/InvalidPageRequestException.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/InvalidPageRequestException.java new file mode 100644 index 0000000..bec0c11 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/InvalidPageRequestException.java @@ -0,0 +1,9 @@ +package com.amigoscode.pagination.order; + +/** The client asked for a page number or a page size the API does not allow. A 400. */ +public class InvalidPageRequestException extends RuntimeException { + + public InvalidPageRequestException(String message) { + super(message); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OffsetPage.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OffsetPage.java new file mode 100644 index 0000000..8c42155 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OffsetPage.java @@ -0,0 +1,12 @@ +package com.amigoscode.pagination.order; + +import java.util.List; + +/** + * One page of the offset endpoints: GET /api/orders?page=3&size=20. + * + * @param page the page number the client asked for, starting at 0 + * @param hasNext true when there is a page after this one. The screens only have a "Next" button + */ +public record OffsetPage(List items, int page, int size, boolean hasNext) { +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/Order.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/Order.java new file mode 100644 index 0000000..f194557 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/Order.java @@ -0,0 +1,57 @@ +package com.amigoscode.pagination.order; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import java.time.Instant; + +@Entity +@Table(name = "orders") +public class Order { + + @Id + private Long id; + + @Column(name = "customer_id") + private long customerId; + + private String status; + + @Column(name = "total_cents") + private int totalCents; + + @Column(name = "created_at") + private Instant createdAt; + + protected Order() { + } + + public Order(long id, long customerId, String status, int totalCents, Instant createdAt) { + this.id = id; + this.customerId = customerId; + this.status = status; + this.totalCents = totalCents; + this.createdAt = createdAt; + } + + public Long getId() { + return id; + } + + public long getCustomerId() { + return customerId; + } + + public String getStatus() { + return status; + } + + public int getTotalCents() { + return totalCents; + } + + public Instant getCreatedAt() { + return createdAt; + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OrderController.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OrderController.java new file mode 100644 index 0000000..86cc684 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OrderController.java @@ -0,0 +1,40 @@ +package com.amigoscode.pagination.order; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class OrderController { + + private final OrderService service; + + public OrderController(OrderService service) { + this.service = service; + } + + /** Every order, newest first, with OFFSET: page 0 is the first page. */ + @GetMapping("/api/orders") + public OffsetPage page(@RequestParam(required = false) Integer page, + @RequestParam(required = false) Integer size) { + return service.page(Paging.page(page), Paging.size(size)); + } + + /** The orders of one customer, newest first, with OFFSET. */ + @GetMapping("/api/customers/{customerId}/orders") + public OffsetPage history(@PathVariable long customerId, + @RequestParam(required = false) Integer page, + @RequestParam(required = false) Integer size) { + return service.history(customerId, Paging.page(page), Paging.size(size)); + } + + /** Every order, newest first, with a cursor: send the nextCursor of one page as "after" to get the next. */ + @GetMapping("/api/orders/feed") + public FeedPage feed(@RequestParam(required = false) String after, + @RequestParam(required = false) Integer size) { + int pageSize = Paging.size(size); + Cursor cursor = after == null || after.isEmpty() ? null : Cursor.decode(after); + return service.feed(cursor, pageSize); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OrderRepository.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OrderRepository.java new file mode 100644 index 0000000..6dbb0fc --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OrderRepository.java @@ -0,0 +1,35 @@ +package com.amigoscode.pagination.order; + +import java.time.Instant; +import java.util.List; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface OrderRepository extends JpaRepository { + + // ---- Offset pagination: LIMIT ? OFFSET ?, written by Spring Data from the Pageable ---- + + // findAll(Pageable) is inherited from JpaRepository. It returns a Page. + + Page findByCustomerId(long customerId, Pageable pageable); + + // ---- Keyset pagination: no OFFSET. The WHERE clause starts where the last page ended ---- + + @Query(value = """ + select * from orders + order by created_at desc + limit :limit + """, nativeQuery = true) + List feedFirstPage(@Param("limit") int limit); + + @Query(value = """ + select * from orders + where created_at < :createdAt + order by created_at desc + limit :limit + """, nativeQuery = true) + List feedAfter(@Param("createdAt") Instant createdAt, @Param("limit") int limit); +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OrderResponse.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OrderResponse.java new file mode 100644 index 0000000..d40f332 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OrderResponse.java @@ -0,0 +1,12 @@ +package com.amigoscode.pagination.order; + +import java.time.Instant; + +/** One order, as the API returns it. */ +public record OrderResponse(long id, long customerId, String status, int totalCents, Instant createdAt) { + + static OrderResponse of(Order order) { + return new OrderResponse(order.getId(), order.getCustomerId(), order.getStatus(), order.getTotalCents(), + order.getCreatedAt()); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OrderService.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OrderService.java new file mode 100644 index 0000000..f2f9995 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/OrderService.java @@ -0,0 +1,47 @@ +package com.amigoscode.pagination.order; + +import java.util.List; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; + +@Service +public class OrderService { + + /** Newest first. */ + static final Sort NEWEST_FIRST = Sort.by(Sort.Order.desc("createdAt")); + + private final OrderRepository orders; + + public OrderService(OrderRepository orders) { + this.orders = orders; + } + + /** GET /api/orders?page=&size= : every order, with OFFSET. */ + public OffsetPage page(int page, int size) { + Page result = orders.findAll(PageRequest.of(page, size, NEWEST_FIRST)); + return new OffsetPage(responses(result.getContent()), page, size, result.hasNext()); + } + + /** GET /api/customers/{id}/orders?page=&size= : the orders of one customer, with OFFSET. */ + public OffsetPage history(long customerId, int page, int size) { + Page result = orders.findByCustomerId(customerId, PageRequest.of(page, size, NEWEST_FIRST)); + return new OffsetPage(responses(result.getContent()), page, size, result.hasNext()); + } + + /** GET /api/orders/feed?after=&size= : every order, with a cursor. after is null for the first page. */ + public FeedPage feed(Cursor after, int size) { + List rows = after == null + ? orders.feedFirstPage(size) + : orders.feedAfter(after.createdAt(), size); + // A full page means there is probably more. + boolean hasNext = rows.size() == size; + String nextCursor = hasNext ? Cursor.after(rows.getLast()).encode() : null; + return new FeedPage(responses(rows), nextCursor, hasNext); + } + + private static List responses(List orders) { + return orders.stream().map(OrderResponse::of).toList(); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/Paging.java b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/Paging.java new file mode 100644 index 0000000..5564dd1 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/java/com/amigoscode/pagination/order/Paging.java @@ -0,0 +1,18 @@ +package com.amigoscode.pagination.order; + +/** The rules for the "page" and "size" request parameters, shared by every endpoint. */ +public final class Paging { + + /** The page size to use. A client that sends no size gets everything. */ + public static int size(Integer requested) { + return requested == null ? Integer.MAX_VALUE : requested; + } + + /** The page number to use, starting at 0. */ + public static int page(Integer requested) { + return requested == null ? 0 : requested; + } + + private Paging() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/resources/application.properties b/java/concepts/junior-mid/11-pagination/start/src/main/resources/application.properties new file mode 100644 index 0000000..a03cbf9 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/resources/application.properties @@ -0,0 +1,17 @@ +spring.application.name=pagination + +# Postgres from compose.yaml. Port 5450 so it does not clash with a Postgres you already run. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5450/pagination} +spring.datasource.username=${DB_USER:pagination} +spring.datasource.password=${DB_PASSWORD:pagination} + +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false + +# The table, the rows and the indexes are set up at startup by DatabaseSetup (see db/). +# It runs schema.sql, seeds this many orders with generate_series, then applies indexes.sql. +spring.sql.init.mode=never +shop.seed.orders=1000000 + +# Uncomment to see every SQL statement. (./demo and ./inspect already print the SQL of each request.) +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/resources/indexes.sql b/java/concepts/junior-mid/11-pagination/start/src/main/resources/indexes.sql new file mode 100644 index 0000000..3c7da44 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/resources/indexes.sql @@ -0,0 +1,12 @@ +-- The indexes of the orders table. +-- +-- This file is the single source of truth. Every time the application, ./demo, ./inspect or +-- ./check starts, the database is made to match it: if the file changed, every index on orders +-- (except the primary key) is dropped and this file is run again. +-- So to add an index, add a statement here. To remove one, delete its statement. +-- +-- One statement per index, each ending with a semicolon. Plain CREATE INDEX, nothing else. + +-- These two were here before you joined. +CREATE INDEX idx_orders_created_at ON orders (created_at); +CREATE INDEX idx_orders_customer ON orders (customer_id); diff --git a/java/concepts/junior-mid/11-pagination/start/src/main/resources/schema.sql b/java/concepts/junior-mid/11-pagination/start/src/main/resources/schema.sql new file mode 100644 index 0000000..ad20d6e --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/main/resources/schema.sql @@ -0,0 +1,15 @@ +-- The table. You do not change this file. Indexes go in indexes.sql. + +create table if not exists orders ( + id bigint primary key, + customer_id bigint not null, + status text not null, + total_cents int not null, + created_at timestamptz not null +); + +-- Bookkeeping for DatabaseSetup: how many rows were seeded, and which indexes.sql was applied. +create table if not exists setup_state ( + key text primary key, + value text not null +); diff --git a/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/Check.java b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/Check.java new file mode 100644 index 0000000..b3b7a80 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/Check.java @@ -0,0 +1,116 @@ +package com.amigoscode.pagination; + +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage; + +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.platform.engine.TestExecutionResult; +import org.junit.platform.engine.discovery.ClassNameFilter; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +import org.junit.platform.launcher.TagFilter; +import org.junit.platform.launcher.TestExecutionListener; +import org.junit.platform.launcher.TestIdentifier; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; + +/** + * Runs the tests that belong to one task and prints one line per acceptance criterion. + * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2 + * (./mvnw verify runs the same tests the usual Maven way.) + */ +public final class Check { + + /** Tasks that have tests. Tasks 7 and 9 are inspection tasks: you answer questions, no code. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: the tools and the HTTP contract (passes from the start, must stay green)"); + TASKS.put("1", "Task 1: See the deep OFFSET"); + TASKS.put("2", "Task 2: Fix the unbounded page size"); + TASKS.put("3", "Task 3: Fix the unstable order"); + TASKS.put("4", "Task 4: Inspect what OFFSET cannot fix"); + TASKS.put("5", "Task 5: Fix it with keyset pagination"); + TASKS.put("6", "Task 6: Fix the cursor: opaque and validated"); + TASKS.put("8", "Task 8: Fix the hidden COUNT(*)"); + } + + public static void main(String[] args) { + if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-9]"))) { + System.out.println("Usage: ./check [task] task is a number from 1 to 9. No number checks everything."); + System.exit(2); + } + if (args.length == 1 && !TASKS.containsKey(args[0])) { + System.out.println(); + System.out.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:"); + System.out.println("follow its steps in INTERVIEW_TASKS.md and answer the questions."); + System.out.println(); + return; + } + + boolean allGreen = true; + Launcher launcher = LauncherFactory.create(); + for (Map.Entry task : TASKS.entrySet()) { + if (args.length == 1 && !task.getKey().equals(args[0])) { + continue; + } + String tag = task.getKey().equals("baseline") ? "baseline" : "task" + task.getKey(); + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() + .selectors(selectPackage(Check.class.getPackageName())) + .filters(ClassNameFilter.includeClassNamePatterns(".*"), TagFilter.includeTags(tag)) + .build(); + System.out.println(); + System.out.println(task.getValue()); + Results results = new Results(); + launcher.execute(request, results); + System.out.println(" " + results.passed + " of " + results.total + " pass"); + allGreen &= results.passed == results.total && results.total > 0; + } + System.out.println(); + System.exit(allGreen ? 0 : 1); + } + + private static final class Results implements TestExecutionListener { + + private int total; + private int passed; + + @Override + public void executionFinished(TestIdentifier test, TestExecutionResult result) { + boolean ok = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL; + if (!test.isTest()) { + // A container that fails (for example the Spring context cannot start) takes its tests with it. + if (!ok) { + total++; + System.out.println(" [FAIL] " + test.getDisplayName() + " could not start"); + result.getThrowable().ifPresent(Results::printReason); + } + return; + } + total++; + if (ok) { + passed++; + System.out.println(" [PASS] " + test.getDisplayName()); + } else { + System.out.println(" [FAIL] " + test.getDisplayName()); + result.getThrowable().ifPresent(Results::printReason); + } + } + + private static void printReason(Throwable throwable) { + Throwable root = throwable; + while (root.getCause() != null && root.getCause() != root && root.getMessage() == null) { + root = root.getCause(); + } + String message = root.getMessage() == null ? root.getClass().getSimpleName() : root.getMessage(); + message.strip().lines() + .map(String::strip) + .filter(line -> !line.isEmpty()) + .limit(6) + .forEach(line -> System.out.println(" " + line)); + } + } + + private Check() { + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/CountQueryIT.java b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/CountQueryIT.java new file mode 100644 index 0000000..7a2842e --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/CountQueryIT.java @@ -0,0 +1,58 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.pagination.order.OffsetPage; +import com.amigoscode.pagination.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 8: a Spring Data Page counts every matching row on every request. Nobody asked for the total. */ +@Tag("task8") +class CountQueryIT extends IntegrationTest { + + /** A business customer: 12 orders in the test database. */ + private static final long CUSTOMER = 1; + + @Test + @DisplayName("Count: one page of GET /api/orders is exactly one SQL statement") + void onePageIsOneStatement() { + Recorded request = record(() -> orderService.page(3, 20)); + + assertThat(request.statements()) + .as("SQL statements sent for GET /api/orders?page=3&size=20") + .hasSize(1); + } + + @Test + @DisplayName("Count: no endpoint sends SELECT COUNT: not the order list, not a customer's history, not the feed") + void nothingCountsTheTable() { + assertThat(record(() -> orderService.page(3, 20)).countQueries()) + .as("COUNT statements sent for GET /api/orders").isEmpty(); + assertThat(record(() -> orderService.history(CUSTOMER, 0, 5)).countQueries()) + .as("COUNT statements sent for GET /api/customers/1/orders").isEmpty(); + assertThat(record(() -> orderService.feed(null, 20)).countQueries()) + .as("COUNT statements sent for GET /api/orders/feed").isEmpty(); + } + + @Test + @DisplayName("Count: the page query asks for one row more than the page size, which is how it knows there is a next page") + void thePageQueryFetchesOneRowMore() { + Recorded request = record(() -> orderService.page(3, 20)); + + assertThat(request.result().items()).as("orders returned to the client").hasSize(20); + assertThat(request.pageQueries().getFirst().parameters()) + .as("values bound to the page query (the offset and the number of rows to fetch)") + .containsExactly(60, 21); + } + + @Test + @DisplayName("Count: hasNext is still right without the total: true in the middle, false on the last page") + void hasNextIsStillRight() { + assertThat(orderService.page(0, 20).hasNext()).as("hasNext of page 0").isTrue(); + assertThat(orderService.page(ORDERS / 20 - 1, 20).hasNext()).as("hasNext of the last page").isFalse(); + assertThat(orderService.history(CUSTOMER, 1, 5).hasNext()).as("hasNext of page 1 of 3 of a customer").isTrue(); + assertThat(orderService.history(CUSTOMER, 2, 5).hasNext()).as("hasNext of page 2 of 3 of a customer").isFalse(); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/CursorTest.java b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/CursorTest.java new file mode 100644 index 0000000..80276da --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/CursorTest.java @@ -0,0 +1,92 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.amigoscode.pagination.order.Cursor; +import com.amigoscode.pagination.order.InvalidCursorException; +import com.amigoscode.pagination.support.StubOrderService; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 6: the cursor is opaque to the client, and a cursor the API cannot read is a 400. Unit tests. */ +@Tag("task6") +class CursorTest { + + private static final Cursor CURSOR = new Cursor(Instant.parse("2025-11-25T10:00:00.123456Z"), 987_654); + + private final StubOrderService service = new StubOrderService(); + + @Test + @DisplayName("Cursor: decode(encode(cursor)) gives the same cursor back, to the microsecond") + void roundTrip() { + assertThat(Cursor.decode(CURSOR.encode())).isEqualTo(CURSOR); + } + + @Test + @DisplayName("Cursor: the encoded form is URL-safe Base64, with no timestamp or id readable in it") + void theEncodedFormIsOpaque() { + String encoded = CURSOR.encode(); + + assertThat(encoded).as("encoded cursor").matches("[A-Za-z0-9_-]+"); + assertThat(encoded).as("encoded cursor").doesNotContain("2025-11-25").doesNotContain("987654"); + assertThat(new String(Base64.getUrlDecoder().decode(encoded), StandardCharsets.UTF_8)) + .as("what the Base64 text decodes to") + .contains("2025-11-25T10:00:00.123456Z") + .contains("987654"); + } + + @Test + @DisplayName("Cursor: text that is not a cursor is an InvalidCursorException, never another exception") + void garbageIsRejected() { + List notCursors = List.of( + "not-a-cursor", + "!!!", + "2025-11-25T10:00:00Z|987654", + base64("hello"), + base64("2025-11-25T10:00:00Z"), + base64("2025-11-25T10:00:00Z|"), + base64("2025-11-25T10:00:00Z|abc"), + base64("yesterday|987654"), + base64("|")); + + for (String text : notCursors) { + assertThatThrownBy(() -> Cursor.decode(text)) + .as("Cursor.decode(\"%s\")", text) + .isInstanceOf(InvalidCursorException.class); + } + } + + @Test + @DisplayName("HTTP: a malformed cursor returns 400 INVALID_CURSOR, not a 500") + void aMalformedCursorIsABadRequest() throws Exception { + for (String after : new String[] {"not-a-cursor", "%7C", base64("yesterday|987654")}) { + service.api().perform(get("/api/orders/feed?after=" + after)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("INVALID_CURSOR")); + } + + assertThat(service.calls).as("calls that reached the service").isZero(); + } + + @Test + @DisplayName("HTTP: a cursor the API handed out is accepted and reaches the service") + void aValidCursorReachesTheService() throws Exception { + service.api().perform(get("/api/orders/feed").param("after", CURSOR.encode())) + .andExpect(status().isOk()); + + assertThat(service.after).as("cursor passed to the service").isEqualTo(CURSOR); + } + + private static String base64(String text) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(text.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/DeepOffsetIT.java b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/DeepOffsetIT.java new file mode 100644 index 0000000..8c9cb73 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/DeepOffsetIT.java @@ -0,0 +1,41 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.order.OffsetPage; +import com.amigoscode.pagination.support.IntegrationTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 1: what OFFSET costs. These tests pass from the start and keep passing: OFFSET cannot be + * made cheap, only replaced. They pin the problem down so you can see what keyset pagination changes. + */ +@Tag("task1") +class DeepOffsetIT extends IntegrationTest { + + @Test + @DisplayName("Offset: the first page reads fewer than 100 rows to return 20") + void theFirstPageIsCheap() { + Recorded request = record(() -> orderService.page(0, 20)); + Plan plan = plan(request.pageQueries().getFirst()); + + assertThat(request.result().items()).as("orders on page 0").hasSize(20); + assertThat(plan.rowsRead()).as("rows read for page 0, with the plan: %s", plan).isLessThan(100); + } + + @Test + @DisplayName("Offset: page 500 reads more than 10,000 rows to return 20: every row of the 500 pages before it (this documents the problem)") + void aDeepPageReadsEveryRowBeforeIt() { + Recorded request = record(() -> orderService.page(500, 20)); + Plan plan = plan(request.pageQueries().getFirst()); + + assertThat(request.result().items()).as("orders on page 500").hasSize(20); + assertThat(request.pageQueries().getFirst().normalized()).as("the SQL of the page query").contains("offset"); + assertThat(plan.rowsRead()) + .as("rows read for page 500 (OFFSET 10000), with the plan: %s", plan) + .isGreaterThanOrEqualTo(10_020); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/KeysetIT.java b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/KeysetIT.java new file mode 100644 index 0000000..35455b7 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/KeysetIT.java @@ -0,0 +1,98 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.order.Cursor; +import com.amigoscode.pagination.order.FeedPage; +import com.amigoscode.pagination.support.IntegrationTest; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 5: keyset pagination. The page starts where the last one ended, instead of counting rows from the top. */ +@Tag("task5") +class KeysetIT extends IntegrationTest { + + @Test + @DisplayName("Keyset: indexes.sql creates an index on orders (created_at, id), the same columns as the ORDER BY") + void theIndexMatchesTheSortOrder() { + assertThat(indexedColumns()) + .as("indexes on orders. Add CREATE INDEX ... ON orders (created_at, id) to indexes.sql") + .anyMatch(columns -> columns.startsWith("(created_at, id")); + } + + @Test + @DisplayName("Keyset: the feed query finds its starting point in the index with a row comparison, and sorts nothing") + void theQueryIsARowComparisonOnTheIndex() { + Cursor deep = cursorAfter(10_000); + Recorded request = record(() -> orderService.feed(deep, 20)); + assertThat(request.statements()).as("SQL statements for one page of the feed").hasSize(1); + Plan plan = plan(request.statements().getFirst()); + + assertThat(plan.has("Sort")).as("plan has a Sort step: %s", plan.nodes()).isFalse(); + assertThat(plan.scans()).as("steps of the plan that read the table").hasSize(1); + assertThat(plan.scans().getFirst().condition()) + .as("Index Cond of the plan: the condition Postgres answers from the index. Plan: %s", plan) + .isNotNull() + .contains("ROW(created_at, id) < ROW("); + } + + @Test + @DisplayName("Keyset: a page 10,000 orders deep reads 21 rows, exactly as many as the first page") + void aDeepPageCostsTheSameAsTheFirst() { + Plan first = plan(record(() -> orderService.feed(null, 20)).statements().getFirst()); + Cursor cursor = cursorAfter(10_000); + Plan deep = plan(record(() -> orderService.feed(cursor, 20)).statements().getFirst()); + + assertThat(first.rowsRead()).as("rows read for the first page (20 orders + 1 to know if there are more)").isEqualTo(21); + assertThat(deep.rowsRead()).as("rows read for the page after 10,000 orders, with the plan: %s", deep).isEqualTo(21); + } + + @Test + @DisplayName("Keyset: following nextCursor from the first page to the last returns all 20,000 orders exactly once, newest first") + void followingTheCursorReturnsEveryOrderOnce() { + List received = new ArrayList<>(); + FeedPage page = orderService.feed(null, 100); + received.addAll(ids(page.items())); + for (int request = 0; page.nextCursor() != null && request < 1_000; request++) { + page = orderService.feed(Cursor.decode(page.nextCursor()), 100); + received.addAll(ids(page.items())); + } + + assertThat(received).as("number of orders received").hasSize(ORDERS); + assertThat(received).as("ids received, in order").isEqualTo(expectedIds(0, ORDERS)); + } + + @Test + @DisplayName("Keyset: hasNext is true while orders remain; the last page has hasNext = false and no nextCursor, even when it is exactly full") + void theLastPageKnowsItIsTheLast() { + FeedPage first = orderService.feed(null, 20); + assertThat(first.items()).as("orders on the first page").hasSize(20); + assertThat(first.hasNext()).as("hasNext of the first page").isTrue(); + assertThat(first.nextCursor()).as("nextCursor of the first page").isNotNull(); + + // The 20 oldest orders: a full page, with nothing after it. + FeedPage last = orderService.feed(cursorAfter(ORDERS - 20), 20); + assertThat(ids(last.items())).as("the last page").isEqualTo(expectedIds(ORDERS - 20, 20)); + assertThat(last.hasNext()).as("hasNext of the last page").isFalse(); + assertThat(last.nextCursor()).as("nextCursor of the last page").isNull(); + } + + @Test + @DisplayName("Keyset: an order placed between two requests changes nothing: the second page continues exactly where the first ended") + void anInsertDoesNotShiftThePages() { + thenRollBack(() -> { + List expected = expectedIds(0, 40); + FeedPage first = orderService.feed(null, 20); + + insertNewestOrder(); + FeedPage second = orderService.feed(Cursor.decode(first.nextCursor()), 20); + + assertThat(ids(first.items())).as("first page").isEqualTo(expected.subList(0, 20)); + assertThat(ids(second.items())).as("second page, read after the insert").isEqualTo(expected.subList(20, 40)); + }); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/OffsetShiftIT.java b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/OffsetShiftIT.java new file mode 100644 index 0000000..fdb71f7 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/OffsetShiftIT.java @@ -0,0 +1,48 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.pagination.support.IntegrationTest; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 4: OFFSET counts rows from the top of the list at the moment of each request. When the list + * changes between two requests, the pages shift. These tests pass from the start and keep passing: + * a tie-breaker does not fix this, only keyset pagination does (Task 5). + */ +@Tag("task4") +class OffsetShiftIT extends IntegrationTest { + + @Test + @DisplayName("Offset: an order placed between two requests pushes the last order of page 0 onto page 1, so the client sees it twice (this documents the problem)") + void anInsertRepeatsARow() { + thenRollBack(() -> { + List pageZero = ids(orderService.page(0, 20).items()); + + insertNewestOrder(); + List pageOne = ids(orderService.page(1, 20).items()); + + assertThat(pageOne.getFirst()) + .as("first order of page 1, read after the insert") + .isEqualTo(pageZero.getLast()); + }); + } + + @Test + @DisplayName("Offset: an order deleted between two requests pulls the first order of page 1 back onto page 0, so the client never sees it (this documents the problem)") + void aDeleteSkipsARow() { + thenRollBack(() -> { + List pageZero = ids(orderService.page(0, 20).items()); + long nextInLine = ids(orderService.page(1, 20).items()).getFirst(); + + jdbc.update("delete from orders where id = ?", pageZero.getFirst()); + List pageOne = ids(orderService.page(1, 20).items()); + + assertThat(pageZero).as("page 0, read before the delete").doesNotContain(nextInLine); + assertThat(pageOne).as("page 1, read after the delete").doesNotContain(nextInLine); + }); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/OrderControllerTest.java b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/OrderControllerTest.java new file mode 100644 index 0000000..3887cc2 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/OrderControllerTest.java @@ -0,0 +1,71 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.amigoscode.pagination.support.StubOrderService; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for the HTTP contract: no Spring context, no database, OrderService is a stub. They + * pass from the start and must keep passing, whatever you change behind the controller. + */ +@Tag("baseline") +class OrderControllerTest { + + private final StubOrderService service = new StubOrderService(); + + @Test + @DisplayName("HTTP: GET /api/orders?page=3&size=10 returns items, page, size and hasNext") + void aPageOfOrders() throws Exception { + service.api().perform(get("/api/orders?page=3&size=10")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.items[0].id").value(42)) + .andExpect(jsonPath("$.items[0].customerId").value(7)) + .andExpect(jsonPath("$.items[0].status").value("PENDING")) + .andExpect(jsonPath("$.page").value(3)) + .andExpect(jsonPath("$.size").value(10)) + .andExpect(jsonPath("$.hasNext").value(true)); + + assertThat(service.page).as("page passed to the service").isEqualTo(3); + assertThat(service.size).as("size passed to the service").isEqualTo(10); + } + + @Test + @DisplayName("HTTP: GET /api/customers/7/orders returns that customer's orders") + void aCustomersHistory() throws Exception { + service.api().perform(get("/api/customers/7/orders?page=1&size=10")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.items[0].id").value(42)) + .andExpect(jsonPath("$.hasNext").value(false)); + + assertThat(service.customerId).as("customer id passed to the service").isEqualTo(7); + assertThat(service.page).as("page passed to the service").isEqualTo(1); + } + + @Test + @DisplayName("HTTP: GET /api/orders/feed returns items, nextCursor and hasNext") + void aPageOfTheFeed() throws Exception { + service.api().perform(get("/api/orders/feed?size=10")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.items[0].id").value(42)) + .andExpect(jsonPath("$.nextCursor").value("next-cursor")) + .andExpect(jsonPath("$.hasNext").value(true)); + + assertThat(service.after).as("cursor passed to the service when the client sent none").isNull(); + } + + @Test + @DisplayName("HTTP: a size that is not a number returns 400") + void sizeMustBeANumber() throws Exception { + service.api().perform(get("/api/orders?size=lots")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("BAD_REQUEST")); + + assertThat(service.calls).as("calls that reached the service").isZero(); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/PageSizeTest.java b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/PageSizeTest.java new file mode 100644 index 0000000..d9c8ebd --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/PageSizeTest.java @@ -0,0 +1,89 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.amigoscode.pagination.support.StubOrderService; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 2: the client does not decide how many rows one request may load. Unit tests: the real + * controller and error handler, a stub service that writes down the size it was asked for. + */ +@Tag("task2") +class PageSizeTest { + + private final StubOrderService service = new StubOrderService(); + + @Test + @DisplayName("Page size: a request without size gets 20 orders, not every order") + void noSizeMeansTwenty() throws Exception { + service.api().perform(get("/api/orders")).andExpect(status().isOk()); + + assertThat(service.size).as("size passed to the service for GET /api/orders").isEqualTo(20); + assertThat(service.page).as("page passed to the service for GET /api/orders").isZero(); + } + + @Test + @DisplayName("Page size: size=100 is the largest size that is accepted") + void oneHundredIsAllowed() throws Exception { + service.api().perform(get("/api/orders?size=100")).andExpect(status().isOk()); + + assertThat(service.size).as("size passed to the service").isEqualTo(100); + } + + @Test + @DisplayName("Page size: size=101 and size=1000000 return 400 INVALID_PAGE_REQUEST, and nothing is loaded") + void tooLargeIsRejected() throws Exception { + for (String size : new String[] {"101", "1000000"}) { + service.api().perform(get("/api/orders?size=" + size)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("INVALID_PAGE_REQUEST")); + } + + assertThat(service.calls).as("calls that reached the service").isZero(); + } + + @Test + @DisplayName("Page size: size=0 and size=-5 return 400 INVALID_PAGE_REQUEST") + void zeroAndNegativeAreRejected() throws Exception { + for (String size : new String[] {"0", "-5"}) { + service.api().perform(get("/api/orders?size=" + size)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("INVALID_PAGE_REQUEST")); + } + + assertThat(service.calls).as("calls that reached the service").isZero(); + } + + @Test + @DisplayName("Page size: page=-1 returns 400 INVALID_PAGE_REQUEST") + void negativePageIsRejected() throws Exception { + service.api().perform(get("/api/orders?page=-1")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("INVALID_PAGE_REQUEST")); + + assertThat(service.calls).as("calls that reached the service").isZero(); + } + + @Test + @DisplayName("Page size: the feed and a customer's history follow the same rules: 20 by default, 400 above 100") + void theOtherEndpointsFollowTheSameRules() throws Exception { + service.api().perform(get("/api/orders/feed")).andExpect(status().isOk()); + assertThat(service.size).as("size passed to the service for GET /api/orders/feed").isEqualTo(20); + + service.api().perform(get("/api/customers/7/orders")).andExpect(status().isOk()); + assertThat(service.size).as("size passed to the service for GET /api/customers/7/orders").isEqualTo(20); + + service.api().perform(get("/api/orders/feed?size=101")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("INVALID_PAGE_REQUEST")); + service.api().perform(get("/api/customers/7/orders?size=101")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("INVALID_PAGE_REQUEST")); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/PlanTest.java b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/PlanTest.java new file mode 100644 index 0000000..e924497 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/PlanTest.java @@ -0,0 +1,70 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.db.SqlStatement; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Unit tests for the tools used by ./demo, ./inspect and the other tests: no Spring, no database. */ +@Tag("baseline") +class PlanTest { + + private static final String DEEP_OFFSET = """ + [{"Plan": {"Node Type": "Limit", "Actual Rows": 20, "Actual Loops": 1, + "Shared Hit Blocks": 1000, "Shared Read Blocks": 11, + "Plans": [{"Node Type": "Index Scan", "Scan Direction": "Backward", "Relation Name": "orders", + "Index Name": "idx_orders_created_at", "Actual Rows": 100000, "Actual Loops": 1, + "Shared Hit Blocks": 1000, "Shared Read Blocks": 11}]}, + "Execution Time": 11.3}] + """; + + private static final String COUNT = """ + [{"Plan": {"Node Type": "Aggregate", "Actual Rows": 1, "Actual Loops": 1, + "Shared Hit Blocks": 8334, "Shared Read Blocks": 0, + "Plans": [{"Node Type": "Seq Scan", "Relation Name": "orders", + "Actual Rows": 1000000, "Actual Loops": 1, + "Shared Hit Blocks": 8334, "Shared Read Blocks": 0}]}, + "Execution Time": 98.5}] + """; + + @Test + @DisplayName("Plan reader: a deep OFFSET is reported with the rows it read, the rows it returned and the pages it touched") + void readsADeepOffset() { + Plan plan = Plan.parse(DEEP_OFFSET); + + assertThat(plan.rowsReturned()).isEqualTo(20); + assertThat(plan.rowsRead()).isEqualTo(100_000); + assertThat(plan.pages()).isEqualTo(1_011); + assertThat(plan.has("Sort")).isFalse(); + assertThat(plan.indexes()).containsExactly("idx_orders_created_at"); + assertThat(plan.describe()).isEqualTo("Index Scan Backward using idx_orders_created_at on orders"); + } + + @Test + @DisplayName("Plan reader: a COUNT is reported with every row it had to read") + void readsACount() { + Plan plan = Plan.parse(COUNT); + + assertThat(plan.has("Seq Scan")).isTrue(); + assertThat(plan.rowsReturned()).isEqualTo(1); + assertThat(plan.rowsRead()).isEqualTo(1_000_000); + } + + @Test + @DisplayName("SQL recorder: SELECT COUNT is told apart from the query that fetches the rows") + void tellsACountFromAPageQuery() { + SqlStatement count = new SqlStatement("select count(o1_0.id) from orders o1_0", List.of()); + SqlStatement page = new SqlStatement( + "select o1_0.id,o1_0.created_at,o1_0.customer_id,o1_0.status,o1_0.total_cents from orders o1_0 " + + "order by o1_0.created_at desc offset ? rows fetch first ? rows only", List.of()); + + assertThat(count.isCount()).isTrue(); + assertThat(page.isCount()).isFalse(); + assertThat(page.shortSql()) + .isEqualTo("select ... from orders o1_0 order by o1_0.created_at desc offset ? rows fetch first ? rows only"); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/StableOrderIT.java b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/StableOrderIT.java new file mode 100644 index 0000000..7aa2567 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/StableOrderIT.java @@ -0,0 +1,61 @@ +package com.amigoscode.pagination; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.pagination.support.IntegrationTest; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 3: ORDER BY created_at is not a complete order when many rows share a created_at. */ +@Tag("task3") +class StableOrderIT extends IntegrationTest { + + private static final long CUSTOMER = 4_000_000; + + @Test + @DisplayName("Order: the SQL sorts by created_at and then by id, so no two rows are ever equal") + void theSqlHasATieBreaker() { + String list = record(() -> orderService.page(0, 20)).pageQueries().getFirst().normalized(); + String history = record(() -> orderService.history(1, 0, 5)).pageQueries().getFirst().normalized(); + + assertThat(list).as("ORDER BY of GET /api/orders") + .containsPattern("order by \\S*created_at desc, ?\\S*\\bid desc"); + assertThat(history).as("ORDER BY of GET /api/customers/{id}/orders") + .containsPattern("order by \\S*created_at desc, ?\\S*\\bid desc"); + } + + @Test + @DisplayName("Order: orders with the same created_at come back with the highest id first, however they are stored") + void tiesComeBackInOneFixedOrder() { + thenRollBack(() -> { + List expected = customerWithOrders(CUSTOMER, 120); + + assertThat(ids(orderService.history(CUSTOMER, 0, 20).items())) + .as("page 0 of a customer whose orders arrive a dozen at a time") + .containsExactlyElementsOf(expected.subList(0, 20)); + assertThat(ids(orderService.history(CUSTOMER, 2, 20).items())) + .as("page 2") + .containsExactlyElementsOf(expected.subList(40, 60)); + }); + } + + @Test + @DisplayName("Order: reading a customer's 120 orders page by page returns each order exactly once") + void walkingThePagesReturnsEveryOrderOnce() { + thenRollBack(() -> { + List expected = customerWithOrders(CUSTOMER, 120); + + List received = new ArrayList<>(); + for (int page = 0; page < 6; page++) { + received.addAll(ids(orderService.history(CUSTOMER, page, 20).items())); + } + + assertThat(received).as("ids received over 6 pages of 20. Nothing was inserted or deleted in between") + .doesNotHaveDuplicates() + .containsExactlyInAnyOrderElementsOf(expected); + }); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/support/IntegrationTest.java b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/support/IntegrationTest.java new file mode 100644 index 0000000..94e445c --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/support/IntegrationTest.java @@ -0,0 +1,159 @@ +package com.amigoscode.pagination.support; + +import com.amigoscode.pagination.db.Explain; +import com.amigoscode.pagination.db.IndexInfo; +import com.amigoscode.pagination.db.Plan; +import com.amigoscode.pagination.db.SqlRecorder; +import com.amigoscode.pagination.db.SqlStatement; +import com.amigoscode.pagination.order.Cursor; +import com.amigoscode.pagination.order.OrderResponse; +import com.amigoscode.pagination.order.OrderService; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.function.Supplier; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.ConnectionCallback; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * Base class for the *IT tests. They start the real application against a real Postgres started by + * Testcontainers (Docker must be running): a query plan only exists in a real database. One + * container is shared by every test class. + * + * The application seeds 20,000 orders at startup (the demo uses 1,000,000) and applies + * src/main/resources/indexes.sql. The tests never look at the clock. They call the service, write + * down the SQL it really sent, and check three things: which rows came back, how many statements + * were sent, and what Postgres did to answer them (the plan, the rows it read). + */ +@SpringBootTest(properties = {"spring.main.banner-mode=off", "shop.seed.orders=" + IntegrationTest.ORDERS}) +public abstract class IntegrationTest { + + /** Orders in the test database: ids 1 to 20,000, in 500 batches of 40 that share a created_at. */ + protected static final int ORDERS = 20_000; + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + static void database(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", POSTGRES::getJdbcUrl); + registry.add("spring.datasource.username", POSTGRES::getUsername); + registry.add("spring.datasource.password", POSTGRES::getPassword); + } + + /** What a call returned, and the SQL statements it sent to Postgres. */ + public record Recorded(T result, List statements) { + + /** The statements that fetch rows: everything except SELECT COUNT. */ + public List pageQueries() { + return statements.stream().filter(statement -> !statement.isCount()).toList(); + } + + public List countQueries() { + return statements.stream().filter(SqlStatement::isCount).toList(); + } + } + + @Autowired + protected OrderService orderService; + + @Autowired + protected JdbcTemplate jdbc; + + @Autowired + private TransactionTemplate transaction; + + /** Runs the call and writes down every SQL statement it sends. */ + protected Recorded record(Supplier call) { + SqlRecorder.start(); + try { + T result = call.get(); + return new Recorded<>(result, SqlRecorder.stop()); + } finally { + SqlRecorder.stop(); + } + } + + /** Runs the recorded statement again with EXPLAIN ANALYZE and returns what Postgres did. */ + protected Plan plan(SqlStatement statement) { + return jdbc.execute((ConnectionCallback) connection -> Explain.analyze(connection, statement)); + } + + /** What the indexes on orders cover, for example "(created_at, id)". */ + protected List indexedColumns() { + return jdbc.execute((ConnectionCallback>) IndexInfo::all).stream() + .map(IndexInfo::columns).toList(); + } + + /** + * Runs the work inside a transaction and rolls it back, so a test can insert, delete or update + * orders and leave the database exactly as it found it. The service joins the same transaction + * and sees those changes. + */ + protected T thenRollBack(Supplier work) { + return transaction.execute(status -> { + status.setRollbackOnly(); + return work.get(); + }); + } + + protected void thenRollBack(Runnable work) { + thenRollBack(() -> { + work.run(); + return null; + }); + } + + /** The ids the API must return for these positions: newest first, and the highest id first within one created_at. */ + protected List expectedIds(int offset, int limit) { + return jdbc.queryForList("select id from orders order by created_at desc, id desc limit ? offset ?", + Long.class, limit, offset); + } + + /** The cursor a client holds after reading this many orders from the top of the feed. */ + protected Cursor cursorAfter(int ordersRead) { + return jdbc.queryForObject( + "select created_at, id from orders order by created_at desc, id desc limit 1 offset ?", + (row, n) -> new Cursor(row.getObject("created_at", OffsetDateTime.class).toInstant(), row.getLong("id")), + ordersRead - 1); + } + + /** A brand new order, newer than every other one. Returns its id. */ + protected long insertNewestOrder() { + long id = jdbc.queryForObject("select max(id) + 1 from orders", Long.class); + jdbc.update(""" + insert into orders (id, customer_id, status, total_cents, created_at) + select ?, 1001, 'PENDING', 1999, max(created_at) + interval '1 minute' from orders + """, id); + return id; + } + + /** + * Gives a new customer this many orders, a dozen per created_at, and stores them in a shuffled + * order, the way rows end up on disk after years of inserts and updates. Returns the ids the API + * must return for that customer, first to last. + */ + protected List customerWithOrders(long customerId, int orders) { + jdbc.update(""" + insert into orders (id, customer_id, status, total_cents, created_at) + select 5000000 + i, ?, 'DELIVERED', 1999, + timestamptz '2030-01-01 00:00:00+00' + make_interval(mins => ((i - 1) / 12)::int) + from generate_series(1, ?) as i + order by md5(i::text) + """, customerId, orders); + return jdbc.queryForList("select id from orders where customer_id = ? order by created_at desc, id desc", + Long.class, customerId); + } + + protected static List ids(List orders) { + return orders.stream().map(OrderResponse::id).toList(); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/support/StubOrderService.java b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/support/StubOrderService.java new file mode 100644 index 0000000..0674ae1 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/test/java/com/amigoscode/pagination/support/StubOrderService.java @@ -0,0 +1,66 @@ +package com.amigoscode.pagination.support; + +import com.amigoscode.pagination.ApiExceptionHandler; +import com.amigoscode.pagination.order.Cursor; +import com.amigoscode.pagination.order.FeedPage; +import com.amigoscode.pagination.order.OffsetPage; +import com.amigoscode.pagination.order.OrderController; +import com.amigoscode.pagination.order.OrderResponse; +import com.amigoscode.pagination.order.OrderService; +import java.time.Instant; +import java.util.List; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +/** + * An OrderService that never touches a database: it writes down what the controller asked for and + * returns one fixed order. Written by hand, no mocking library. + */ +public final class StubOrderService extends OrderService { + + public static final OrderResponse AN_ORDER = + new OrderResponse(42, 7, "PENDING", 1999, Instant.parse("2025-11-25T10:00:00Z")); + + /** What the controller passed on in the last call. null means: that argument was not part of the call. */ + public Integer page; + public Integer size; + public Long customerId; + public Cursor after; + public int calls; + + public StubOrderService() { + super(null); + } + + /** The real controller and the real error handler, wired to this stub. */ + public MockMvc api() { + return MockMvcBuilders.standaloneSetup(new OrderController(this)) + .setControllerAdvice(new ApiExceptionHandler()) + .build(); + } + + @Override + public OffsetPage page(int page, int size) { + calls++; + this.page = page; + this.size = size; + return new OffsetPage(List.of(AN_ORDER), page, size, true); + } + + @Override + public OffsetPage history(long customerId, int page, int size) { + calls++; + this.customerId = customerId; + this.page = page; + this.size = size; + return new OffsetPage(List.of(AN_ORDER), page, size, false); + } + + @Override + public FeedPage feed(Cursor after, int size) { + calls++; + this.after = after; + this.size = size; + return new FeedPage(List.of(AN_ORDER), "next-cursor", true); + } +} diff --git a/java/concepts/junior-mid/11-pagination/start/src/test/resources/logback-test.xml b/java/concepts/junior-mid/11-pagination/start/src/test/resources/logback-test.xml new file mode 100644 index 0000000..82166a4 --- /dev/null +++ b/java/concepts/junior-mid/11-pagination/start/src/test/resources/logback-test.xml @@ -0,0 +1,11 @@ + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + +